From 0d131663e4a7a8c71d665fc8204ea1cec6544268 Mon Sep 17 00:00:00 2001 From: Ravi Ranjan Date: Tue, 10 Aug 2021 23:28:03 +0530 Subject: [PATCH 01/12] Dapp Isseue solved Example with Issue number #338 #337 #321 #304 #303 --- Example/Web3supportBrowser/Podfile | 21 + Example/Web3supportBrowser/Podfile.lock | 44 + .../Web3supportBrowser/Pods/BigInt/LICENSE.md | 20 + .../Web3supportBrowser/Pods/BigInt/README.md | 440 + .../Pods/BigInt/Sources/Addition.swift | 126 + .../Pods/BigInt/Sources/BigInt.swift | 74 + .../Pods/BigInt/Sources/BigUInt.swift | 386 + .../Pods/BigInt/Sources/Bitwise Ops.swift | 121 + .../Pods/BigInt/Sources/Codable.swift | 155 + .../Pods/BigInt/Sources/Comparable.swift | 63 + .../Pods/BigInt/Sources/Data Conversion.swift | 107 + .../Pods/BigInt/Sources/Division.swift | 374 + .../Pods/BigInt/Sources/Exponentiation.swift | 119 + .../Sources/Floating Point Conversion.swift | 73 + .../Pods/BigInt/Sources/GCD.swift | 80 + .../Pods/BigInt/Sources/Hashable.swift | 26 + .../BigInt/Sources/Integer Conversion.swift | 89 + .../Pods/BigInt/Sources/Multiplication.swift | 165 + .../Pods/BigInt/Sources/Prime Test.swift | 153 + .../Pods/BigInt/Sources/Random.swift | 71 + .../Pods/BigInt/Sources/Shifts.swift | 211 + .../Pods/BigInt/Sources/Square Root.swift | 41 + .../Pods/BigInt/Sources/Strideable.swift | 38 + .../BigInt/Sources/String Conversion.swift | 236 + .../Pods/BigInt/Sources/Subtraction.swift | 169 + .../Pods/BigInt/Sources/Words and Bits.swift | 202 + .../Pods/CryptoSwift/LICENSE | 11 + .../Pods/CryptoSwift/README.md | 527 + .../Sources/CryptoSwift/AEAD/AEAD.swift | 40 + .../AEAD/AEADChaCha20Poly1305.swift | 59 + .../Sources/CryptoSwift/AES.Cryptors.swift | 35 + .../CryptoSwift/Sources/CryptoSwift/AES.swift | 539 + .../Sources/CryptoSwift/Array+Extension.swift | 148 + .../Sources/CryptoSwift/Authenticator.swift | 20 + .../CryptoSwift/BatchedCollection.swift | 63 + .../CryptoSwift/Sources/CryptoSwift/Bit.swift | 25 + .../Sources/CryptoSwift/BlockCipher.swift | 18 + .../Sources/CryptoSwift/BlockDecryptor.swift | 85 + .../Sources/CryptoSwift/BlockEncryptor.swift | 57 + .../CryptoSwift/BlockMode/BlockMode.swift | 24 + .../BlockMode/BlockModeOptions.swift | 27 + .../Sources/CryptoSwift/BlockMode/CBC.swift | 70 + .../Sources/CryptoSwift/BlockMode/CCM.swift | 359 + .../Sources/CryptoSwift/BlockMode/CFB.swift | 70 + .../Sources/CryptoSwift/BlockMode/CTR.swift | 134 + .../BlockMode/CipherModeWorker.swift | 61 + .../Sources/CryptoSwift/BlockMode/ECB.swift | 51 + .../Sources/CryptoSwift/BlockMode/GCM.swift | 370 + .../Sources/CryptoSwift/BlockMode/OFB.swift | 70 + .../Sources/CryptoSwift/BlockMode/PCBC.swift | 70 + .../Sources/CryptoSwift/Blowfish.swift | 537 + .../Sources/CryptoSwift/CBCMAC.swift | 104 + .../Sources/CryptoSwift/CMAC.swift | 20 + .../Sources/CryptoSwift/ChaCha20.swift | 347 + .../Sources/CryptoSwift/Checksum.swift | 193 + .../Sources/CryptoSwift/Cipher.swift | 47 + .../CryptoSwift/Collection+Extension.swift | 45 + .../Sources/CryptoSwift/CompactMap.swift | 23 + .../Sources/CryptoSwift/Cryptor.swift | 22 + .../Sources/CryptoSwift/Cryptors.swift | 44 + .../Sources/CryptoSwift/Digest.swift | 78 + .../Sources/CryptoSwift/DigestType.swift | 18 + .../Foundation/AES+Foundation.swift | 23 + .../Foundation/Array+Foundation.swift | 32 + .../Foundation/Blowfish+Foundation.swift | 23 + .../Foundation/ChaCha20+Foundation.swift | 22 + .../Foundation/Data+Extension.swift | 95 + .../Foundation/HMAC+Foundation.swift | 22 + .../Foundation/Rabbit+Foundation.swift | 26 + .../String+FoundationExtension.swift | 41 + .../Foundation/Utils+Foundation.swift | 27 + .../Sources/CryptoSwift/Generics.swift | 55 + .../Sources/CryptoSwift/HKDF.swift | 84 + .../Sources/CryptoSwift/HMAC.swift | 102 + .../Sources/CryptoSwift/Int+Extension.swift | 38 + .../CryptoSwift/Sources/CryptoSwift/MD5.swift | 165 + .../Sources/CryptoSwift/NoPadding.swift | 27 + .../Sources/CryptoSwift/Operators.swift | 32 + .../Sources/CryptoSwift/PKCS/PBKDF1.swift | 87 + .../Sources/CryptoSwift/PKCS/PBKDF2.swift | 116 + .../Sources/CryptoSwift/PKCS/PKCS5.swift | 22 + .../Sources/CryptoSwift/PKCS/PKCS7.swift | 18 + .../CryptoSwift/PKCS/PKCS7Padding.swift | 64 + .../Sources/CryptoSwift/Padding.swift | 49 + .../Sources/CryptoSwift/Poly1305.swift | 165 + .../Sources/CryptoSwift/Rabbit.swift | 217 + .../CryptoSwift/RandomBytesSequence.swift | 50 + .../Sources/CryptoSwift/SHA1.swift | 151 + .../Sources/CryptoSwift/SHA2.swift | 353 + .../Sources/CryptoSwift/SHA3.swift | 289 + .../Sources/CryptoSwift/Scrypt.swift | 256 + .../Sources/CryptoSwift/SecureBytes.swift | 77 + .../Sources/CryptoSwift/StreamDecryptor.swift | 78 + .../Sources/CryptoSwift/StreamEncryptor.swift | 56 + .../CryptoSwift/String+Extension.swift | 81 + .../Sources/CryptoSwift/UInt128.swift | 90 + .../CryptoSwift/UInt16+Extension.swift | 37 + .../CryptoSwift/UInt32+Extension.swift | 48 + .../CryptoSwift/UInt64+Extension.swift | 43 + .../Sources/CryptoSwift/UInt8+Extension.swift | 76 + .../Sources/CryptoSwift/Updatable.swift | 98 + .../Sources/CryptoSwift/Utils.swift | 115 + .../Sources/CryptoSwift/ZeroPadding.swift | 38 + Example/Web3supportBrowser/Pods/Manifest.lock | 44 + .../Pods/Pods.xcodeproj/project.pbxproj | 3389 + .../Sources/NSNotificationCenter+AnyPromise.h | 44 + .../Sources/NSNotificationCenter+AnyPromise.m | 18 + .../NSNotificationCenter+Promise.swift | 33 + .../Foundation/Sources/NSObject+Promise.swift | 57 + .../Foundation/Sources/NSTask+AnyPromise.h | 53 + .../Foundation/Sources/NSTask+AnyPromise.m | 59 + .../Sources/NSURLSession+AnyPromise.h | 79 + .../Sources/NSURLSession+AnyPromise.m | 113 + .../Sources/NSURLSession+Promise.swift | 241 + .../Foundation/Sources/PMKFoundation.h | 3 + .../Foundation/Sources/Process+Promise.swift | 190 + .../Foundation/Sources/afterlife.swift | 26 + .../Extensions/UIKit/Sources/PMKUIKit.h | 8 + .../UIKit/Sources/UIView+AnyPromise.h | 80 + .../UIKit/Sources/UIView+AnyPromise.m | 64 + .../UIKit/Sources/UIView+Promise.swift | 115 + .../Sources/UIViewController+AnyPromise.h | 71 + .../Sources/UIViewController+AnyPromise.m | 140 + .../UIViewPropertyAnimator+Promise.swift | 14 + .../Pods/PromiseKit/LICENSE | 20 + .../Pods/PromiseKit/README.md | 207 + .../PromiseKit/Sources/AnyPromise+Private.h | 32 + .../Pods/PromiseKit/Sources/AnyPromise.h | 299 + .../Pods/PromiseKit/Sources/AnyPromise.m | 175 + .../Pods/PromiseKit/Sources/AnyPromise.swift | 204 + .../Pods/PromiseKit/Sources/Box.swift | 101 + .../Pods/PromiseKit/Sources/Catchable.swift | 256 + .../PromiseKit/Sources/Configuration.swift | 35 + .../Sources/CustomStringConvertible.swift | 44 + .../PromiseKit/Sources/Deprecations.swift | 93 + .../Pods/PromiseKit/Sources/Error.swift | 103 + .../Pods/PromiseKit/Sources/Guarantee.swift | 212 + .../Pods/PromiseKit/Sources/LogEvent.swift | 30 + .../Sources/NSMethodSignatureForBlock.m | 77 + .../PromiseKit/Sources/PMKCallVariadicBlock.m | 120 + .../Pods/PromiseKit/Sources/Promise.swift | 179 + .../Pods/PromiseKit/Sources/PromiseKit.h | 7 + .../Pods/PromiseKit/Sources/Resolver.swift | 99 + .../Pods/PromiseKit/Sources/Thenable.swift | 424 + .../Pods/PromiseKit/Sources/after.m | 14 + .../Pods/PromiseKit/Sources/after.swift | 46 + .../PromiseKit/Sources/dispatch_promise.m | 10 + .../Pods/PromiseKit/Sources/firstly.swift | 39 + .../Pods/PromiseKit/Sources/fwd.h | 165 + .../Pods/PromiseKit/Sources/hang.m | 29 + .../Pods/PromiseKit/Sources/hang.swift | 55 + .../Pods/PromiseKit/Sources/join.m | 54 + .../Pods/PromiseKit/Sources/race.m | 9 + .../Pods/PromiseKit/Sources/race.swift | 57 + .../Pods/PromiseKit/Sources/when.m | 107 + .../Pods/PromiseKit/Sources/when.swift | 262 + .../Pods/Starscream/LICENSE | 176 + .../Pods/Starscream/README.md | 438 + .../Sources/Starscream/Compression.swift | 177 + .../Starscream/SSLClientCertificate.swift | 92 + .../Sources/Starscream/SSLSecurity.swift | 266 + .../Sources/Starscream/WebSocket.swift | 1356 + .../BigInt/BigInt-Info.plist | 26 + .../BigInt/BigInt-dummy.m | 5 + .../BigInt/BigInt-prefix.pch | 12 + .../BigInt/BigInt-umbrella.h | 16 + .../BigInt/BigInt.debug.xcconfig | 12 + .../BigInt/BigInt.modulemap | 6 + .../BigInt/BigInt.release.xcconfig | 12 + .../CryptoSwift/CryptoSwift-Info.plist | 26 + .../CryptoSwift/CryptoSwift-dummy.m | 5 + .../CryptoSwift/CryptoSwift-prefix.pch | 12 + .../CryptoSwift/CryptoSwift-umbrella.h | 16 + .../CryptoSwift/CryptoSwift.debug.xcconfig | 17 + .../CryptoSwift/CryptoSwift.modulemap | 6 + .../CryptoSwift/CryptoSwift.release.xcconfig | 17 + ...-Web3support-Web3supportUITests-Info.plist | 26 + ...b3supportUITests-acknowledgements.markdown | 474 + ...-Web3supportUITests-acknowledgements.plist | 536 + ...ods-Web3support-Web3supportUITests-dummy.m | 5 + ...ts-frameworks-Debug-input-files.xcfilelist | 7 + ...s-frameworks-Debug-output-files.xcfilelist | 6 + ...-frameworks-Release-input-files.xcfilelist | 7 + ...frameworks-Release-output-files.xcfilelist | 6 + ...b3support-Web3supportUITests-frameworks.sh | 195 + ...-Web3support-Web3supportUITests-umbrella.h | 16 + ...3support-Web3supportUITests.debug.xcconfig | 14 + ...s-Web3support-Web3supportUITests.modulemap | 6 + ...upport-Web3supportUITests.release.xcconfig | 14 + .../Pods-Web3support-Info.plist | 26 + ...Pods-Web3support-acknowledgements.markdown | 474 + .../Pods-Web3support-acknowledgements.plist | 536 + .../Pods-Web3support/Pods-Web3support-dummy.m | 5 + ...rt-frameworks-Debug-input-files.xcfilelist | 7 + ...t-frameworks-Debug-output-files.xcfilelist | 6 + ...-frameworks-Release-input-files.xcfilelist | 7 + ...frameworks-Release-output-files.xcfilelist | 6 + .../Pods-Web3support-frameworks.sh | 195 + .../Pods-Web3support-umbrella.h | 16 + .../Pods-Web3support.debug.xcconfig | 14 + .../Pods-Web3support.modulemap | 6 + .../Pods-Web3support.release.xcconfig | 14 + .../Pods-Web3supportTests-Info.plist | 26 + ...Web3supportTests-acknowledgements.markdown | 3 + ...ds-Web3supportTests-acknowledgements.plist | 29 + .../Pods-Web3supportTests-dummy.m | 5 + .../Pods-Web3supportTests-umbrella.h | 16 + .../Pods-Web3supportTests.debug.xcconfig | 11 + .../Pods-Web3supportTests.modulemap | 6 + .../Pods-Web3supportTests.release.xcconfig | 11 + .../PromiseKit/PromiseKit-Info.plist | 26 + .../PromiseKit/PromiseKit-dummy.m | 5 + .../PromiseKit/PromiseKit-prefix.pch | 12 + .../PromiseKit/PromiseKit-umbrella.h | 26 + .../PromiseKit/PromiseKit.debug.xcconfig | 13 + .../PromiseKit/PromiseKit.modulemap | 6 + .../PromiseKit/PromiseKit.release.xcconfig | 13 + .../Starscream/Starscream-Info.plist | 26 + .../Starscream/Starscream-dummy.m | 5 + .../Starscream/Starscream-prefix.pch | 12 + .../Starscream/Starscream-umbrella.h | 16 + .../Starscream/Starscream.debug.xcconfig | 12 + .../Starscream/Starscream.modulemap | 6 + .../Starscream/Starscream.release.xcconfig | 12 + .../secp256k1.c/secp256k1.c-Info.plist | 26 + .../secp256k1.c/secp256k1.c-dummy.m | 5 + .../secp256k1.c/secp256k1.c-prefix.pch | 12 + .../secp256k1.c/secp256k1.c-umbrella.h | 17 + .../secp256k1.c/secp256k1.c.debug.xcconfig | 13 + .../secp256k1.c/secp256k1.c.modulemap | 6 + .../secp256k1.c/secp256k1.c.release.xcconfig | 13 + ...esourceBundle-Browser-web3swift-Info.plist | 24 + .../web3swift/web3swift-Info.plist | 26 + .../web3swift/web3swift-dummy.m | 5 + .../web3swift/web3swift-prefix.pch | 12 + .../web3swift/web3swift-umbrella.h | 16 + .../web3swift/web3swift.debug.xcconfig | 14 + .../web3swift/web3swift.modulemap | 6 + .../web3swift/web3swift.release.xcconfig | 14 + .../Pods/secp256k1.c/License.md | 19 + .../Pods/secp256k1.c/secp256k1/basic-config.h | 33 + .../Pods/secp256k1.c/secp256k1/ecdh_impl.h | 54 + .../Pods/secp256k1.c/secp256k1/ecdsa.h | 21 + .../Pods/secp256k1.c/secp256k1/ecdsa_impl.h | 313 + .../Pods/secp256k1.c/secp256k1/eckey.h | 25 + .../Pods/secp256k1.c/secp256k1/eckey_impl.h | 100 + .../Pods/secp256k1.c/secp256k1/ecmult.h | 47 + .../Pods/secp256k1.c/secp256k1/ecmult_const.h | 17 + .../secp256k1.c/secp256k1/ecmult_const_impl.h | 257 + .../Pods/secp256k1.c/secp256k1/ecmult_gen.h | 43 + .../secp256k1.c/secp256k1/ecmult_gen_impl.h | 210 + .../Pods/secp256k1.c/secp256k1/ecmult_impl.h | 1027 + .../Pods/secp256k1.c/secp256k1/field.h | 130 + .../Pods/secp256k1.c/secp256k1/field_10x26.h | 48 + .../secp256k1.c/secp256k1/field_10x26_impl.h | 1161 + .../Pods/secp256k1.c/secp256k1/field_5x52.h | 47 + .../secp256k1/field_5x52_asm_impl.h | 502 + .../secp256k1.c/secp256k1/field_5x52_impl.h | 494 + .../secp256k1/field_5x52_int128_impl.h | 277 + .../Pods/secp256k1.c/secp256k1/field_impl.h | 313 + .../Pods/secp256k1.c/secp256k1/group.h | 147 + .../Pods/secp256k1.c/secp256k1/group_impl.h | 706 + .../Pods/secp256k1.c/secp256k1/hash.h | 41 + .../Pods/secp256k1.c/secp256k1/hash_impl.h | 282 + .../secp256k1.c/secp256k1/include/secp256k1.h | 767 + .../Pods/secp256k1.c/secp256k1/num.h | 72 + .../Pods/secp256k1.c/secp256k1/num_gmp.h | 20 + .../Pods/secp256k1.c/secp256k1/num_gmp_impl.h | 288 + .../Pods/secp256k1.c/secp256k1/num_impl.h | 22 + .../secp256k1.c/secp256k1/recovery_impl.h | 193 + .../Pods/secp256k1.c/secp256k1/scalar.h | 104 + .../Pods/secp256k1.c/secp256k1/scalar_4x64.h | 19 + .../secp256k1.c/secp256k1/scalar_4x64_impl.h | 949 + .../Pods/secp256k1.c/secp256k1/scalar_8x32.h | 19 + .../secp256k1.c/secp256k1/scalar_8x32_impl.h | 721 + .../Pods/secp256k1.c/secp256k1/scalar_impl.h | 331 + .../Pods/secp256k1.c/secp256k1/scalar_low.h | 15 + .../secp256k1.c/secp256k1/scalar_low_impl.h | 114 + .../Pods/secp256k1.c/secp256k1/scratch.h | 39 + .../Pods/secp256k1.c/secp256k1/scratch_impl.h | 86 + .../secp256k1.c/secp256k1/secp256k1-config.h | 169 + .../Pods/secp256k1.c/secp256k1/secp256k1.c | 597 + .../secp256k1_ec_mult_static_context.h | 1160 + .../secp256k1.c/secp256k1/secp256k1_main.h | 5 + .../Pods/secp256k1.c/secp256k1/util.h | 119 + .../Pods/web3swift/LICENSE.md | 203 + .../Pods/web3swift/README.md | 329 + .../Sources/web3swift/Browser/Bridge.swift | 250 + .../Browser/BrowserViewController.swift | 128 + .../Sources/web3swift/Browser/browser.js | 68351 ++++++++++++++++ .../Sources/web3swift/Browser/browser.min.js | 2 + .../web3swift/Browser/wk.bridge.min.js | 5 + .../Contract/ComparisonExtensions.swift | 95 + .../web3swift/Contract/ContractProtocol.swift | 109 + .../web3swift/Contract/EthereumContract.swift | 297 + .../EthereumFilterEncodingExtensions.swift | 44 + .../web3swift/Contract/EventFiltering.swift | 170 + .../Convenience/Array+Extension.swift | 16 + .../web3swift/Convenience/Base58.swift | 170 + .../Convenience/BigUInt+Extensions.swift | 16 + .../Convenience/CryptoExtensions.swift | 20 + .../Convenience/Data+Extension.swift | 142 + .../Convenience/Decodable+Extensions.swift | 146 + .../Convenience/Dictionary+Extension.swift | 18 + .../Convenience/Encodable+Extensions.swift | 130 + .../NSRegularExpressionExtension.swift | 83 + .../NativeTypesEncoding+Extensions.swift | 91 + .../Convenience/RIPEMD160+StackOveflow.swift | 534 + .../web3swift/Convenience/SECP256k1.swift | 385 + .../Convenience/String+Extension.swift | 137 + .../Sources/web3swift/EthereumABI/ABI.swift | 28 + .../web3swift/EthereumABI/ABIDecoding.swift | 286 + .../web3swift/EthereumABI/ABIElements.swift | 286 + .../web3swift/EthereumABI/ABIEncoding.swift | 388 + .../EthereumABI/ABIParameterTypes.swift | 250 + .../web3swift/EthereumABI/ABIParsing.swift | 186 + .../web3swift/EthereumABI/ABITypeParser.swift | 110 + .../EthereumAddress/EthereumAddress.swift | 136 + .../EthereumAddress/Extensions.swift | 60 + .../Web3+BrowserFunctions.swift | 209 + .../HookedFunctions/Web3+Wallet.swift | 73 + .../KeystoreManager/AbstractKeystore.swift | 23 + .../KeystoreManager/BIP32HDNode.swift | 302 + .../KeystoreManager/BIP32Keystore.swift | 279 + .../BIP32KeystoreJSONStructure.swift | 26 + .../KeystoreManager/BIP39+WordLists.swift | 35 + .../web3swift/KeystoreManager/BIP39.swift | 164 + .../KeystoreManager/EthereumKeystoreV3.swift | 193 + .../web3swift/KeystoreManager/IBAN.swift | 138 + .../KeystoreManager/KeystoreManager.swift | 175 + .../KeystoreV3JSONStructure.swift | 46 + .../KeystoreManager/PlainKeystore.swift | 36 + .../web3swift/Promises/Promise+Batching.swift | 139 + .../Promises/Promise+HttpProvider.swift | 109 + ...omise+Web3+Contract+GetIndexedEvents.swift | 11 + .../Promises/Promise+Web3+Eth+Call.swift | 36 + .../Promise+Web3+Eth+EstimateGas.swift | 38 + .../Promise+Web3+Eth+GetAccounts.swift | 39 + .../Promise+Web3+Eth+GetBalance.swift | 31 + .../Promise+Web3+Eth+GetBlockByHash.swift | 31 + .../Promise+Web3+Eth+GetBlockByNumber.swift | 36 + .../Promise+Web3+Eth+GetBlockNumber.swift | 26 + .../Promise+Web3+Eth+GetGasPrice.swift | 26 + ...Promise+Web3+Eth+GetTransactionCount.swift | 32 + ...omise+Web3+Eth+GetTransactionDetails.swift | 31 + ...omise+Web3+Eth+GetTransactionReceipt.swift | 31 + .../Promise+Web3+Eth+SendRawTransaction.swift | 51 + .../Promise+Web3+Eth+SendTransaction.swift | 79 + .../Promise+Web3+Personal+CreateAccount.swift | 37 + .../Promises/Promise+Web3+Personal+Sign.swift | 44 + .../Promise+Web3+Personal+UnlockAccount.swift | 43 + .../Promises/Promise+Web3+TxPool.swift | 56 + .../Sources/web3swift/SwiftRLP/RLP.swift | 320 + .../Tokens/ERC1155/Web3+ERC1155.swift | 147 + .../Tokens/ERC1376/Web3+ERC1376.swift | 502 + .../Tokens/ERC1400/Web3+ERC1400.swift | 931 + .../Tokens/ERC1410/Web3+ERC1410.swift | 664 + .../Tokens/ERC1594/Web3+ERC1594.swift | 409 + .../Tokens/ERC1633/Web3+ERC1633.swift | 254 + .../Tokens/ERC1643/Web3+ERC1643.swift | 267 + .../Tokens/ERC1644/Web3+ERC1644.swift | 283 + .../web3swift/Tokens/ERC165/Web3+ERC165.swift | 16 + .../web3swift/Tokens/ERC20/Web3+ERC20.swift | 228 + .../web3swift/Tokens/ERC721/Web3+ERC721.swift | 280 + .../Tokens/ERC721x/Web3+ERC721x.swift | 332 + .../web3swift/Tokens/ERC777/Web3+ERC777.swift | 445 + .../web3swift/Tokens/ERC820/Web3+ERC820.swift | 20 + .../web3swift/Tokens/ERC888/Web3+ERC888.swift | 138 + .../web3swift/Tokens/ST20/Web3+ST20.swift | 314 + .../Tokens/ST20/Web3+SecurityToken.swift | 473 + .../web3swift/Transaction/BloomFilter.swift | 110 + .../Transaction/EthereumTransaction.swift | 403 + .../Transaction/TransactionSigner.swift | 118 + .../web3swift/Utils/EIP/EIP67Code.swift | 138 + .../Sources/web3swift/Utils/EIP/EIP681.swift | 232 + .../Sources/web3swift/Utils/ENS/ENS.swift | 286 + .../Utils/ENS/ENSBaseRegistrar.swift | 82 + .../web3swift/Utils/ENS/ENSRegistry.swift | 110 + .../web3swift/Utils/ENS/ENSResolver.swift | 196 + .../Utils/ENS/ENSReverseRegistrar.swift | 68 + .../Utils/ENS/ETHRegistrarController.swift | 93 + .../web3swift/Utils/ENS/NameHash.swift | 52 + .../web3swift/Utils/ENS/PublicKey.swift | 26 + .../Utils/Hooks/NonceMiddleware.swift | 111 + .../web3swift/Web3/Web3+Constants.swift | 15 + .../web3swift/Web3/Web3+Contract.swift | 116 + .../web3swift/Web3/Web3+Eth+Websocket.swift | 42 + .../Sources/web3swift/Web3/Web3+Eth.swift | 358 + .../web3swift/Web3/Web3+EventParser.swift | 307 + .../web3swift/Web3/Web3+Eventloop.swift | 103 + .../web3swift/Web3/Web3+HttpProvider.swift | 57 + .../web3swift/Web3/Web3+InfuraProviders.swift | 275 + .../web3swift/Web3/Web3+Instance.swift | 229 + .../Sources/web3swift/Web3/Web3+JSONRPC.swift | 278 + .../Sources/web3swift/Web3/Web3+Methods.swift | 90 + .../Web3/Web3+MutatingTransaction.swift | 170 + .../Sources/web3swift/Web3/Web3+Options.swift | 246 + .../web3swift/Web3/Web3+Personal.swift | 86 + .../web3swift/Web3/Web3+Protocols.swift | 90 + .../Web3/Web3+ReadingTransaction.swift | 109 + .../web3swift/Web3/Web3+Structures.swift | 691 + .../Sources/web3swift/Web3/Web3+TxPool.swift | 25 + .../Sources/web3swift/Web3/Web3+Utils.swift | 6212 ++ .../Web3/Web3+WebsocketProvider.swift | 300 + .../Sources/web3swift/Web3/Web3.swift | 79 + .../Web3support.xcodeproj/project.pbxproj | 768 + .../contents.xcworkspacedata | 7 + .../xcshareddata/IDEWorkspaceChecks.plist | 8 + .../contents.xcworkspacedata | 10 + .../xcshareddata/IDEWorkspaceChecks.plist | 8 + .../xcshareddata/WorkspaceSettings.xcsettings | 8 + .../Web3support/AppDelegate.swift | 38 + .../AccentColor.colorset/Contents.json | 11 + .../AppIcon.appiconset/Contents.json | 98 + .../Web3support/Assets.xcassets/Contents.json | 6 + .../Base.lproj/LaunchScreen.storyboard | 50 + .../Web3support/Base.lproj/Main.storyboard | 112 + .../Web3support/FeatureTableViewCell.swift | 23 + .../Web3supportBrowser/Web3support/Info.plist | 66 + .../Web3support/SceneDelegate.swift | 58 + .../Web3support/ViewController.swift | 57 + .../BrowserViewController.swift | 130 + .../ViewController/DappViewController.swift | 61 + .../Web3supportTests/Info.plist | 22 + .../Web3supportTests/Web3supportTests.swift | 33 + .../Web3supportUITests/Info.plist | 22 + .../Web3supportUITests.swift | 42 + 427 files changed, 133644 insertions(+) create mode 100644 Example/Web3supportBrowser/Podfile create mode 100644 Example/Web3supportBrowser/Podfile.lock create mode 100644 Example/Web3supportBrowser/Pods/BigInt/LICENSE.md create mode 100644 Example/Web3supportBrowser/Pods/BigInt/README.md create mode 100644 Example/Web3supportBrowser/Pods/BigInt/Sources/Addition.swift create mode 100644 Example/Web3supportBrowser/Pods/BigInt/Sources/BigInt.swift create mode 100644 Example/Web3supportBrowser/Pods/BigInt/Sources/BigUInt.swift create mode 100644 Example/Web3supportBrowser/Pods/BigInt/Sources/Bitwise Ops.swift create mode 100644 Example/Web3supportBrowser/Pods/BigInt/Sources/Codable.swift create mode 100644 Example/Web3supportBrowser/Pods/BigInt/Sources/Comparable.swift create mode 100644 Example/Web3supportBrowser/Pods/BigInt/Sources/Data Conversion.swift create mode 100644 Example/Web3supportBrowser/Pods/BigInt/Sources/Division.swift create mode 100644 Example/Web3supportBrowser/Pods/BigInt/Sources/Exponentiation.swift create mode 100644 Example/Web3supportBrowser/Pods/BigInt/Sources/Floating Point Conversion.swift create mode 100644 Example/Web3supportBrowser/Pods/BigInt/Sources/GCD.swift create mode 100644 Example/Web3supportBrowser/Pods/BigInt/Sources/Hashable.swift create mode 100644 Example/Web3supportBrowser/Pods/BigInt/Sources/Integer Conversion.swift create mode 100644 Example/Web3supportBrowser/Pods/BigInt/Sources/Multiplication.swift create mode 100644 Example/Web3supportBrowser/Pods/BigInt/Sources/Prime Test.swift create mode 100644 Example/Web3supportBrowser/Pods/BigInt/Sources/Random.swift create mode 100644 Example/Web3supportBrowser/Pods/BigInt/Sources/Shifts.swift create mode 100644 Example/Web3supportBrowser/Pods/BigInt/Sources/Square Root.swift create mode 100644 Example/Web3supportBrowser/Pods/BigInt/Sources/Strideable.swift create mode 100644 Example/Web3supportBrowser/Pods/BigInt/Sources/String Conversion.swift create mode 100644 Example/Web3supportBrowser/Pods/BigInt/Sources/Subtraction.swift create mode 100644 Example/Web3supportBrowser/Pods/BigInt/Sources/Words and Bits.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/LICENSE create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/README.md create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEAD.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEADChaCha20Poly1305.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/AES.Cryptors.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/AES.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Array+Extension.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Authenticator.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BatchedCollection.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Bit.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockCipher.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockDecryptor.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockEncryptor.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/BlockMode.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/BlockModeOptions.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CBC.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CCM.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CFB.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CTR.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CipherModeWorker.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/ECB.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/GCM.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/OFB.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/PCBC.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Blowfish.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/CBCMAC.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/CMAC.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/ChaCha20.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Checksum.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Cipher.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Collection+Extension.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/CompactMap.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Cryptor.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Cryptors.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Digest.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/DigestType.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/AES+Foundation.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Array+Foundation.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Blowfish+Foundation.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/ChaCha20+Foundation.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Data+Extension.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/HMAC+Foundation.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Rabbit+Foundation.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/String+FoundationExtension.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Utils+Foundation.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Generics.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/HKDF.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/HMAC.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Int+Extension.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/MD5.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/NoPadding.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Operators.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PBKDF1.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PBKDF2.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS5.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS7.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS7Padding.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Padding.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Poly1305.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Rabbit.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/RandomBytesSequence.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/SHA1.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/SHA2.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/SHA3.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Scrypt.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/SecureBytes.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/StreamDecryptor.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/StreamEncryptor.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/String+Extension.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/UInt128.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/UInt16+Extension.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/UInt32+Extension.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/UInt64+Extension.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/UInt8+Extension.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Updatable.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Utils.swift create mode 100644 Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/ZeroPadding.swift create mode 100644 Example/Web3supportBrowser/Pods/Manifest.lock create mode 100644 Example/Web3supportBrowser/Pods/Pods.xcodeproj/project.pbxproj create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.h create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.m create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+Promise.swift create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSObject+Promise.swift create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.h create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.m create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.h create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.m create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+Promise.swift create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/PMKFoundation.h create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/Process+Promise.swift create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/afterlife.swift create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/PMKUIKit.h create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.h create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.m create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+Promise.swift create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.h create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.m create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewPropertyAnimator+Promise.swift create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/LICENSE create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/README.md create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/AnyPromise+Private.h create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/AnyPromise.h create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/AnyPromise.m create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/AnyPromise.swift create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/Box.swift create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/Catchable.swift create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/Configuration.swift create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/CustomStringConvertible.swift create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/Deprecations.swift create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/Error.swift create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/Guarantee.swift create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/LogEvent.swift create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/NSMethodSignatureForBlock.m create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/PMKCallVariadicBlock.m create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/Promise.swift create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/PromiseKit.h create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/Resolver.swift create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/Thenable.swift create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/after.m create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/after.swift create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/dispatch_promise.m create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/firstly.swift create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/fwd.h create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/hang.m create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/hang.swift create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/join.m create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/race.m create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/race.swift create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/when.m create mode 100644 Example/Web3supportBrowser/Pods/PromiseKit/Sources/when.swift create mode 100644 Example/Web3supportBrowser/Pods/Starscream/LICENSE create mode 100644 Example/Web3supportBrowser/Pods/Starscream/README.md create mode 100644 Example/Web3supportBrowser/Pods/Starscream/Sources/Starscream/Compression.swift create mode 100644 Example/Web3supportBrowser/Pods/Starscream/Sources/Starscream/SSLClientCertificate.swift create mode 100644 Example/Web3supportBrowser/Pods/Starscream/Sources/Starscream/SSLSecurity.swift create mode 100644 Example/Web3supportBrowser/Pods/Starscream/Sources/Starscream/WebSocket.swift create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt-Info.plist create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt-dummy.m create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt-prefix.pch create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt-umbrella.h create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt.debug.xcconfig create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt.modulemap create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt.release.xcconfig create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift-Info.plist create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift-dummy.m create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift-prefix.pch create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift-umbrella.h create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift.debug.xcconfig create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift.modulemap create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift.release.xcconfig create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-Info.plist create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-acknowledgements.markdown create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-acknowledgements.plist create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-dummy.m create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks-Debug-input-files.xcfilelist create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks-Debug-output-files.xcfilelist create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks-Release-input-files.xcfilelist create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks-Release-output-files.xcfilelist create mode 100755 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks.sh create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-umbrella.h create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests.debug.xcconfig create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests.modulemap create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests.release.xcconfig create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-Info.plist create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-acknowledgements.markdown create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-acknowledgements.plist create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-dummy.m create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks-Debug-input-files.xcfilelist create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks-Debug-output-files.xcfilelist create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks-Release-input-files.xcfilelist create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks-Release-output-files.xcfilelist create mode 100755 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks.sh create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-umbrella.h create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support.debug.xcconfig create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support.modulemap create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support.release.xcconfig create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests-Info.plist create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests-acknowledgements.markdown create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests-acknowledgements.plist create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests-dummy.m create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests-umbrella.h create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests.debug.xcconfig create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests.modulemap create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests.release.xcconfig create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit-Info.plist create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit-dummy.m create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit-prefix.pch create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit-umbrella.h create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit.debug.xcconfig create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit.modulemap create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit.release.xcconfig create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream-Info.plist create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream-dummy.m create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream-prefix.pch create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream-umbrella.h create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream.debug.xcconfig create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream.modulemap create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream.release.xcconfig create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c-Info.plist create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c-dummy.m create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c-prefix.pch create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c-umbrella.h create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c.debug.xcconfig create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c.modulemap create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c.release.xcconfig create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/web3swift/ResourceBundle-Browser-web3swift-Info.plist create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift-Info.plist create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift-dummy.m create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift-prefix.pch create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift-umbrella.h create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift.debug.xcconfig create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift.modulemap create mode 100644 Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift.release.xcconfig create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/License.md create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/basic-config.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecdh_impl.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecdsa.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecdsa_impl.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/eckey.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/eckey_impl.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult_const.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult_const_impl.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult_gen.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult_gen_impl.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult_impl.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_10x26.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_10x26_impl.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_5x52.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_5x52_asm_impl.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_5x52_impl.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_5x52_int128_impl.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_impl.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/group.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/group_impl.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/hash.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/hash_impl.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/include/secp256k1.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/num.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/num_gmp.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/num_gmp_impl.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/num_impl.h create mode 100755 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/recovery_impl.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_4x64.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_4x64_impl.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_8x32.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_8x32_impl.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_impl.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_low.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_low_impl.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scratch.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scratch_impl.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/secp256k1-config.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/secp256k1.c create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/secp256k1_ec_mult_static_context.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/secp256k1_main.h create mode 100644 Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/util.h create mode 100755 Example/Web3supportBrowser/Pods/web3swift/LICENSE.md create mode 100755 Example/Web3supportBrowser/Pods/web3swift/README.md create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Browser/Bridge.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Browser/BrowserViewController.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Browser/browser.js create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Browser/browser.min.js create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Browser/wk.bridge.min.js create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Contract/ComparisonExtensions.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Contract/ContractProtocol.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Contract/EthereumContract.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Contract/EthereumFilterEncodingExtensions.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Contract/EventFiltering.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Array+Extension.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Base58.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/BigUInt+Extensions.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/CryptoExtensions.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Data+Extension.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Decodable+Extensions.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Dictionary+Extension.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Encodable+Extensions.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/NSRegularExpressionExtension.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/NativeTypesEncoding+Extensions.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/RIPEMD160+StackOveflow.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/SECP256k1.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/String+Extension.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABI.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABIDecoding.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABIElements.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABIEncoding.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABIParameterTypes.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABIParsing.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABITypeParser.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumAddress/EthereumAddress.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumAddress/Extensions.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/HookedFunctions/Web3+BrowserFunctions.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/HookedFunctions/Web3+Wallet.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/AbstractKeystore.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32HDNode.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32Keystore.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32KeystoreJSONStructure.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP39+WordLists.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP39.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/EthereumKeystoreV3.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/IBAN.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/KeystoreManager.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/KeystoreV3JSONStructure.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/PlainKeystore.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Batching.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+HttpProvider.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Contract+GetIndexedEvents.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+Call.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+EstimateGas.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetAccounts.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBalance.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByHash.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByNumber.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockNumber.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetGasPrice.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionCount.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionDetails.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionReceipt.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+SendRawTransaction.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+SendTransaction.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+CreateAccount.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+Sign.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+UnlockAccount.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+TxPool.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/SwiftRLP/RLP.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1155/Web3+ERC1155.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1376/Web3+ERC1376.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1400/Web3+ERC1400.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1410/Web3+ERC1410.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1594/Web3+ERC1594.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1633/Web3+ERC1633.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1643/Web3+ERC1643.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1644/Web3+ERC1644.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC165/Web3+ERC165.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC20/Web3+ERC20.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC721/Web3+ERC721.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC721x/Web3+ERC721x.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC777/Web3+ERC777.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC820/Web3+ERC820.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC888/Web3+ERC888.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ST20/Web3+ST20.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ST20/Web3+SecurityToken.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Transaction/BloomFilter.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Transaction/EthereumTransaction.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Transaction/TransactionSigner.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/EIP/EIP67Code.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/EIP/EIP681.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ENS.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSBaseRegistrar.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSRegistry.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSResolver.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSReverseRegistrar.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ETHRegistrarController.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/NameHash.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/PublicKey.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/Hooks/NonceMiddleware.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Constants.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Contract.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Eth+Websocket.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Eth.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+EventParser.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Eventloop.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+HttpProvider.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+InfuraProviders.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Instance.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+JSONRPC.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Methods.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+MutatingTransaction.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Options.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Personal.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Protocols.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+ReadingTransaction.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Structures.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+TxPool.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Utils.swift create mode 100644 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+WebsocketProvider.swift create mode 100755 Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3.swift create mode 100644 Example/Web3supportBrowser/Web3support.xcodeproj/project.pbxproj create mode 100644 Example/Web3supportBrowser/Web3support.xcodeproj/project.xcworkspace/contents.xcworkspacedata create mode 100644 Example/Web3supportBrowser/Web3support.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist create mode 100644 Example/Web3supportBrowser/Web3support.xcworkspace/contents.xcworkspacedata create mode 100644 Example/Web3supportBrowser/Web3support.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist create mode 100644 Example/Web3supportBrowser/Web3support.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings create mode 100644 Example/Web3supportBrowser/Web3support/AppDelegate.swift create mode 100644 Example/Web3supportBrowser/Web3support/Assets.xcassets/AccentColor.colorset/Contents.json create mode 100644 Example/Web3supportBrowser/Web3support/Assets.xcassets/AppIcon.appiconset/Contents.json create mode 100644 Example/Web3supportBrowser/Web3support/Assets.xcassets/Contents.json create mode 100644 Example/Web3supportBrowser/Web3support/Base.lproj/LaunchScreen.storyboard create mode 100644 Example/Web3supportBrowser/Web3support/Base.lproj/Main.storyboard create mode 100644 Example/Web3supportBrowser/Web3support/FeatureTableViewCell.swift create mode 100644 Example/Web3supportBrowser/Web3support/Info.plist create mode 100644 Example/Web3supportBrowser/Web3support/SceneDelegate.swift create mode 100644 Example/Web3supportBrowser/Web3support/ViewController.swift create mode 100644 Example/Web3supportBrowser/Web3support/ViewController/BrowserViewController.swift create mode 100644 Example/Web3supportBrowser/Web3support/ViewController/DappViewController.swift create mode 100644 Example/Web3supportBrowser/Web3supportTests/Info.plist create mode 100644 Example/Web3supportBrowser/Web3supportTests/Web3supportTests.swift create mode 100644 Example/Web3supportBrowser/Web3supportUITests/Info.plist create mode 100644 Example/Web3supportBrowser/Web3supportUITests/Web3supportUITests.swift diff --git a/Example/Web3supportBrowser/Podfile b/Example/Web3supportBrowser/Podfile new file mode 100644 index 000000000..57eaae961 --- /dev/null +++ b/Example/Web3supportBrowser/Podfile @@ -0,0 +1,21 @@ +# Uncomment the next line to define a global platform for your project +# platform :ios, '9.0' + +target 'Web3support' do + # Comment the next line if you don't want to use dynamic frameworks + use_frameworks! + + # Pods for Web3support + pod 'web3swift' + + + target 'Web3supportTests' do + inherit! :search_paths + # Pods for testing + end + + target 'Web3supportUITests' do + # Pods for testing + end + +end diff --git a/Example/Web3supportBrowser/Podfile.lock b/Example/Web3supportBrowser/Podfile.lock new file mode 100644 index 000000000..4d6cceaaa --- /dev/null +++ b/Example/Web3supportBrowser/Podfile.lock @@ -0,0 +1,44 @@ +PODS: + - BigInt (4.0.0) + - CryptoSwift (1.0.0) + - PromiseKit (6.8.5): + - PromiseKit/CorePromise (= 6.8.5) + - PromiseKit/Foundation (= 6.8.5) + - PromiseKit/UIKit (= 6.8.5) + - PromiseKit/CorePromise (6.8.5) + - PromiseKit/Foundation (6.8.5): + - PromiseKit/CorePromise + - PromiseKit/UIKit (6.8.5): + - PromiseKit/CorePromise + - secp256k1.c (0.1.2) + - Starscream (3.1.1) + - web3swift (2.3.0): + - BigInt (~> 4.0) + - CryptoSwift (~> 1.0.0) + - PromiseKit (~> 6.8.4) + - secp256k1.c (~> 0.1) + - Starscream (~> 3.1.0) + +DEPENDENCIES: + - web3swift + +SPEC REPOS: + trunk: + - BigInt + - CryptoSwift + - PromiseKit + - secp256k1.c + - Starscream + - web3swift + +SPEC CHECKSUMS: + BigInt: 2aad1a9942dc932ec8b84290d2c564a3d76f97ab + CryptoSwift: d81eeaa59dc5a8d03720fe919a6fd07b51f7439f + PromiseKit: 9616b0afef31eae56ab9ce044c8ec2b8612a15cd + secp256k1.c: db47b726585d80f027423682eb369729e61b3b20 + Starscream: 4bb2f9942274833f7b4d296a55504dcfc7edb7b0 + web3swift: 0f097eafe1d08f478694b882581b85a01afb6633 + +PODFILE CHECKSUM: 88c1fe5ece120ef8aac94b776e02de991c51641d + +COCOAPODS: 1.10.2 diff --git a/Example/Web3supportBrowser/Pods/BigInt/LICENSE.md b/Example/Web3supportBrowser/Pods/BigInt/LICENSE.md new file mode 100644 index 000000000..18cefd118 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/LICENSE.md @@ -0,0 +1,20 @@ + +Copyright (c) 2016-2017 Károly Lőrentey + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Example/Web3supportBrowser/Pods/BigInt/README.md b/Example/Web3supportBrowser/Pods/BigInt/README.md new file mode 100644 index 000000000..e65483bb8 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/README.md @@ -0,0 +1,440 @@ +[![BigInt](https://github.com/attaswift/BigInt/raw/master/images/banner.png)](https://github.com/attaswift/BigInt) + +* [Overview](#overview) +* [API Documentation](#api) +* [License](#license) +* [Requirements and Integration](#integration) +* [Implementation Notes](#notes) + * [Full-width multiplication and division primitives](#fullwidth) + * [Why is there no generic `BigInt` type?](#generics) +* [Calculation Samples](#samples) + * [Obligatory factorial demo](#factorial) + * [RSA Cryptography](#rsa) + * [Calculating the Digits of π](#pi) + +[![Swift 3](https://img.shields.io/badge/Swift-4-blue.svg)](https://developer.apple.com/swift/) +[![License](https://img.shields.io/badge/licence-MIT-blue.svg)](http://cocoapods.org/pods/BigInt) +[![Platform](https://img.shields.io/cocoapods/p/BigInt.svg)](http://cocoapods.org/pods/BigInt) + +[![Build Status](https://travis-ci.org/attaswift/BigInt.svg?branch=master)](https://travis-ci.org/attaswift/BigInt) +[![Code Coverage](https://codecov.io/github/attaswift/BigInt/coverage.svg?branch=master)](https://codecov.io/github/attaswift/BigInt?branch=master) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg)](https://github.com/Carthage/Carthage) +[![Version](https://img.shields.io/cocoapods/v/BigInt.svg)](http://cocoapods.org/pods/BigInt) + +## Overview + +This repository provides [integer types of arbitrary width][wiki] implemented +in 100% pure Swift. The underlying representation is in base 2^64, using `Array`. + +[wiki]: https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic + +This module is handy when you need an integer type that's wider than `UIntMax`, but +you don't want to add [The GNU Multiple Precision Arithmetic Library][GMP] +as a dependency. + +[GMP]: https://gmplib.org + +Two big integer types are included: [`BigUInt`][BigUInt] and [`BigInt`][BigInt], +the latter being the signed variant. +Both of these are Swift structs with copy-on-write value semantics, and they can be used much +like any other integer type. + +The library provides implementations for some of the most frequently useful functions on +big integers, including + +- All functionality from [`Comparable`][comparison] and [`Hashable`][hashing] + +- [The full set of arithmetic operators][addition]: `+`, `-`, `*`, `/`, `%`, `+=`, `-=`, `*=`, `/=`, `%=` + - [Addition][addition] and [subtraction][subtraction] have variants that allow for + shifting the digits of the second operand on the fly. + - Unsigned subtraction will trap when the result would be negative. + ([There are variants][subtraction] that return an overflow flag.) + - [Multiplication][mul] uses brute force for numbers up to 1024 digits, then switches to Karatsuba's recursive method. + (This limit is configurable, see `BigUInt.directMultiplicationLimit`.) + - A [fused multiply-add][fused] method is also available, along with other [special-case variants][multiplication]. + - [Division][division] uses Knuth's Algorithm D, with its 3/2 digits wide quotient approximation. + It will trap when the divisor is zero. + - [`BigUInt.divide`][divide] returns the quotient and + remainder at once; this is faster than calculating them separately. + +- [Bitwise operators][bitwise]: `~`, `|`, `&`, `^`, `|=`, `&=`, `^=`, plus the following read-only properties: + - [`width`][width]: the minimum number of bits required to store the integer, + - [`trailingZeroBitCount`][trailingZeroBitCount]: the number of trailing zero bits in the binary representation, + - [`leadingZeroBitCount`][leadingZeroBitCount]: the number of leading zero bits (when the last digit isn't full), + +- [Shift operators][shift]: `>>`, `<<`, `>>=`, `<<=` + +- Methods to [convert `NSData` to big integers][data] and vice versa. + +- Support for [generating random integers][random] of specified maximum width or magnitude. + +- Radix conversion to/from [`String`s][radix1] and [big integers][radix2] up to base 36 (using repeated divisions). + - Big integers use this to implement `StringLiteralConvertible` (in base 10). + +- [`sqrt(n)`][sqrt]: The square root of an integer (using Newton's method). + +- [`BigUInt.gcd(n, m)`][GCD]: The greatest common divisor of two integers (Stein's algorithm). + +- [`base.power(exponent, modulus)`][powmod]: Modular exponentiation (right-to-left binary method). + [Vanilla exponentiation][power] is also available. +- [`n.inverse(modulus)`][inverse]: Multiplicative inverse in modulo arithmetic (extended Euclidean algorithm). +- [`n.isPrime()`][prime]: Miller–Rabin primality test. + +The implementations are intended to be reasonably efficient, but they are unlikely to be +competitive with GMP at all, even when I happened to implement an algorithm with same asymptotic +behavior as GMP. (I haven't performed a comparison benchmark, though.) + +The library has 100% unit test coverage. Sadly this does not imply that there are no bugs +in it. + +## API Documentation + +Generated API docs are available at http://attaswift.github.io/BigInt/. + +## License + +BigInt can be used, distributed and modified under [the MIT license][license]. + +## Requirements and Integration + +BigInt 3.0.0 requires Swift 4. (The last version with support for Swift 3.x was BigInt 2.1.0. +The last version with support for Swift 2 was BigInt 1.3.0.) + +| Swift Version | last BigInt Version| +| ------------- |:-------------------| +| 3.x | 2.1.0 | +| 4.0 | 3.1.0 | +| 4.2 | 4.0.0 | + +BigInt deploys to macOS 10.10, iOS 9, watchOS 2 and tvOS 9. +It has been tested on the latest OS releases only---however, as the module uses very few platform-provided APIs, +there should be very few issues with earlier versions. + +BigInt uses no APIs specific to Apple platforms except for `arc4random_buf` in `BigUInt Random.swift`, so +it should be easy to port it to other operating systems. + +Setup instructions: + +- **Swift Package Manager:** + Although the Package Manager is still in its infancy, BigInt provides experimental support for it. + Add this to the dependency section of your `Package.swift` manifest: + + ```Swift + .package(url: "https://github.com/attaswift/BigInt.git", from: "4.0.0") + ``` + +- **CocoaPods:** Put this in your `Podfile`: + + ```Ruby + pod 'BigInt', '~> 4.0' + ``` + +- **Carthage:** Put this in your `Cartfile`: + + ``` + github "attaswift/BigInt" ~> 4.0 + ``` + +## Implementation notes + +[`BigUInt`][BigUInt] is a `MutableCollectionType` of its 64-bit digits, with the least significant +digit at index 0. As a convenience, [`BigUInt`][BigUInt] allows you to subscript it with indexes at +or above its `count`. [The subscript operator][subscript] returns 0 for out-of-bound `get`s and +automatically extends the array on out-of-bound `set`s. This makes memory management simpler. + +[`BigInt`][BigInt] is just a tiny wrapper around a `BigUInt` [absolute value][abs] and a +[sign bit][negative], both of which are accessible as public read-write properties. + +### Full-width multiplication and division primitives + +I haven't found (64,64)->128 multiplication or (128,64)->64 division operations +in Swift, so [the module has generic implementations for them][fullmuldiv] in terms of the standard +single-width `*` and `/` operators. I suspect there are LLVM intrinsics for full-width +arithmetics that are probably accessible somehow, though. ([Let me know][twitter] if you know how!) + +This sounds slow, but 64-bit digits are +still considerably faster than 32-bit, even though the latter can use direct 64-bit arithmetic to +implement these primitives. + +### Why is there no generic `BigInt` type? + +The types provided by `BigInt` are not parametric—this is very much intentional, as +Swift generics cost us dearly at runtime in this use case. In every approach I tried, +making arbitrary-precision arithmetic operations work with a generic `Digit` type parameter +resulted in code that was literally *ten times slower*. If you can make the algorithms generic +without such a huge performance hit, [please enlighten me][twitter]! + +This is an area that I plan to investigate more, as it would be useful to have generic +implementations for arbitrary-width arithmetic operations. (Polynomial division and decimal bases +are two examples.) The library already implements double-digit multiplication and division as +extension methods on a protocol with an associated type requirement; this has not measurably affected +performance. Unfortunately, the same is not true for `BigUInt`'s methods. + +Of course, as a last resort, we could just duplicate the code to create a separate +generic variant that was slower but more flexible. + +[license]: https://github.com/attaswift/BigInt/blob/master/LICENSE.md +[twitter]: https://twitter.com/lorentey +[BigUInt]: http://attaswift.github.io/BigInt/Structs/BigUInt.html +[BigInt]: http://attaswift.github.io/BigInt/Structs/BigInt.html +[comparison]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/Comparison +[hashing]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/Hashing +[addition]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/Addition +[subtraction]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/Subtraction +[mul]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/s:ZFV6BigInt7BigUIntoi1mFTS0_S0__S0_ +[fused]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/s:FV6BigInt7BigUInt14multiplyAndAddFTS0_Vs6UInt6410atPositionSi_T_ +[multiplication]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/Multiplication +[division]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/Division +[divide]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/s:FV6BigInt7BigUInt7dividedFT2byS0__T8quotientS0_9remainderS0__ +[bitwise]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/Bitwise%20Operations +[width]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/s:vV6BigInt7BigUInt5widthSi +[leadingZeroBitCount]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/s:vV6BigInt7BigUInt13leadingZeroBitCountSi +[trailingZeroBitCount]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/s:vV6BigInt7BigUInt14trailingZeroBitCountSi +[shift]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/Shift%20Operators +[data]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/NSData%20Conversion +[random]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/Random%20Integers +[radix1]: http://attaswift.github.io/BigInt/Extensions/String.html#/s:FE6BigIntSScFTVS_7BigUInt5radixSi9uppercaseSb_SS +[radix2]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/s:FV6BigInt7BigUIntcFTSS5radixSi_GSqS0__ +[sqrt]: http://attaswift.github.io/BigInt/Functions.html#/s:F6BigInt4sqrtFVS_7BigUIntS0_ +[GCD]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/s:ZFV6BigInt7BigUInt3gcdFTS0_S0__S0_ +[powmod]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/s:FV6BigInt7BigUInt5powerFTS0_7modulusS0__S0_ +[power]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/s:FV6BigInt7BigUInt5powerFSiS0_ +[inverse]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/s:FV6BigInt7BigUInt7inverseFS0_GSqS0__ +[prime]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/Primality%20Testing +[abs]: http://attaswift.github.io/BigInt/Structs/BigInt.html#/s:vV6BigInt6BigInt3absVS_7BigUInt +[negative]: http://attaswift.github.io/BigInt/Structs/BigInt.html#/s:vV6BigInt6BigInt8negativeSb +[subscript]: https://github.com/attaswift/BigInt/blob/v2.0.0/Sources/BigUInt.swift#L216-L239 +[fullmuldiv]: https://github.com/attaswift/BigInt/blob/v2.0.0/Sources/BigDigit.swift#L96-L167 + + +## Calculation Samples + +### Obligatory Factorial Demo + +It is easy to use `BigInt` to calculate the factorial function for any integer: + +```Swift +import BigInt + +func factorial(_ n: Int) -> BigInt { + return (1 ... n).map { BigInt($0) }.reduce(BigInt(1), *) +} + +print(factorial(10)) +==> 362880 + +print(factorial(100)) +==> 93326215443944152681699238856266700490715968264381621468592963895217599993229915 + 6089414639761565182862536979208272237582511852109168640000000000000000000000 + +print(factorial(1000)) +==> 40238726007709377354370243392300398571937486421071463254379991042993851239862902 + 05920442084869694048004799886101971960586316668729948085589013238296699445909974 + 24504087073759918823627727188732519779505950995276120874975462497043601418278094 + 64649629105639388743788648733711918104582578364784997701247663288983595573543251 + 31853239584630755574091142624174743493475534286465766116677973966688202912073791 + 43853719588249808126867838374559731746136085379534524221586593201928090878297308 + 43139284440328123155861103697680135730421616874760967587134831202547858932076716 + 91324484262361314125087802080002616831510273418279777047846358681701643650241536 + 91398281264810213092761244896359928705114964975419909342221566832572080821333186 + 11681155361583654698404670897560290095053761647584772842188967964624494516076535 + 34081989013854424879849599533191017233555566021394503997362807501378376153071277 + 61926849034352625200015888535147331611702103968175921510907788019393178114194545 + 25722386554146106289218796022383897147608850627686296714667469756291123408243920 + 81601537808898939645182632436716167621791689097799119037540312746222899880051954 + 44414282012187361745992642956581746628302955570299024324153181617210465832036786 + 90611726015878352075151628422554026517048330422614397428693306169089796848259012 + 54583271682264580665267699586526822728070757813918581788896522081643483448259932 + 66043367660176999612831860788386150279465955131156552036093988180612138558600301 + 43569452722420634463179746059468257310379008402443243846565724501440282188525247 + 09351906209290231364932734975655139587205596542287497740114133469627154228458623 + 77387538230483865688976461927383814900140767310446640259899490222221765904339901 + 88601856652648506179970235619389701786004081188972991831102117122984590164192106 + 88843871218556461249607987229085192968193723886426148396573822911231250241866493 + 53143970137428531926649875337218940694281434118520158014123344828015051399694290 + 15348307764456909907315243327828826986460278986432113908350621709500259738986355 + 42771967428222487575867657523442202075736305694988250879689281627538488633969099 + 59826280956121450994871701244516461260379029309120889086942028510640182154399457 + 15680594187274899809425474217358240106367740459574178516082923013535808184009699 + 63725242305608559037006242712434169090041536901059339838357779394109700277534720 + 00000000000000000000000000000000000000000000000000000000000000000000000000000000 + 00000000000000000000000000000000000000000000000000000000000000000000000000000000 + 00000000000000000000000000000000000000000000000000000000000000000000000000000000 + 00000 +``` + +Well, I guess that's all right, but it's not very interesting. Let's try something more useful. + +### RSA Cryptography + +The `BigInt` module provides all necessary parts to implement an (overly) +simple [RSA cryptography system][RSA]. + +[RSA]: https://en.wikipedia.org/wiki/RSA_(cryptosystem) + +Let's start with a simple function that generates a random n-bit prime. The module +includes a function to generate random integers of a specific size, and also an +`isPrime` method that performs the Miller–Rabin primality test. These are all we need: + +```Swift +func generatePrime(_ width: Int) -> BigUInt { + while true { + var random = BigUInt.randomInteger(withExactWidth: width) + random |= BigUInt(1) + if random.isPrime() { + return random + } + } +} + +let p = generatePrime(1024) +==> 13308187650642192396256419911012544845370493728424936791561478318443071617242872 + 81980956747087187419914435169914161116601678883358611076800743580556055714173922 + 08406194264346635072293912609713085260354070700055888678514690878149253177960273 + 775659537560220378850112471985434373425534121373466492101182463962031 + +let q = generatePrime(1024) +==> 17072954422657145489547308812333368925007949054501204983863958355897172093173783 + 10108226596943999553784252564650624766276133157586733504784616138305701168410157 + 80784336308507083874651158029602582993233111593356512531869546706885170044355115 + 669728424124141763799008880327106952436883614887277350838425336156327 +``` + +Cool! Now that we have two large primes, we can produce an RSA public/private keypair +out of them. + +```Swift +typealias Key = (modulus: BigUInt, exponent: BigUInt) + +let n = p * q +==> 22721008120758282530010953362926306641542233757318103044313144976976529789946696 + 15454966720907712515917481418981591379647635391260569349099666410127279690367978 + 81184375533755888994370640857883754985364288413796100527262763202679037134021810 + 57933883525572232242690805678883227791774442041516929419640051653934584376704034 + 63953169772816907280591934423237977258358097846511079947337857778137177570668391 + 57455417707100275487770399281417352829897118140972240757708561027087217205975220 + 02207275447810167397968435583004676293892340103729490987263776871467057582629588 + 916498579594964478080508868267360515953225283461208420137 + +let e: BigUInt = 65537 +let phi = (p - 1) * (q - 1) +let d = e.inverse(phi)! // d * e % phi == 1 +==> 13964664343869014759736350480776837992604500903989703383202366291905558996277719 + 77822086142456362972689566985925179681282432115598451765899180050962461295573831 + 37069237934291884106584820998146965085531433195106686745474222222620986858696591 + 69836532468835154412554521152103642453158895363417640676611704542784576974374954 + 45789456921660619938185093118762690200980720312508614337759620606992462563490422 + 76669559556568917533268479190948959560397579572761529852891246283539604545691244 + 89999692877158676643042118662613875863504016129837099223040687512684532694527109 + 80742873307409704484365002175294665608486688146261327793 + +let publicKey: Key = (n, e) +let privateKey: Key = (n, d) +``` + +In RSA, modular exponentiation is used to encrypt (and decrypt) messages. + +```Swift +func encrypt(_ message: BigUInt, key: Key) -> BigUInt { + return message.power(key.exponent, modulus: key.modulus) +} +``` + +Let's try out our new keypair by converting a string into UTF-8, interpreting +the resulting binary representation as a big integer, and encrypting it with the +public key. `BigUInt` has an initializer that takes an `NSData`, so this is pretty +easy to do: + +```Swift +let secret: BigUInt = BigUInt("Arbitrary precision arithmetic is fun!".dataUsingEncoding(NSUTF8StringEncoding)!) +==> 83323446846105976078466731524728681905293067701804838925389198929123912971229457 + 68818568737 + +let cyphertext = encrypt(secret, key: publicKey) +==> 95186982543485985200666516508066093880038842892337880561554910904277290917831453 + 54854954722744805432145474047391353716305176389470779020645959135298322520888633 + 61674945129099575943384767330342554525120384485469428048962027149169876127890306 + 77028183904699491962050888974524603226290836984166164759586952419343589385279641 + 47999991283152843977988979846238236160274201261075188190509539751990119132013021 + 74866638595734222867005089157198503204192264814750832072844208520394603054901706 + 06024394731371973402595826456435944968439153664617188570808940022471990638468783 + 49208193955207336172861151720299024935127021719852700882 +``` + +Well, it looks encrypted all right, but can we get the original message back? +In theory, encrypting the cyphertext with the private key returns the original message. +Let's see: + +```Swift +let plaintext = encrypt(cyphertext, key: privateKey) +==> 83323446846105976078466731524728681905293067701804838925389198929123912971229457 + 68818568737 + +let received = String(data: plaintext.serialize(), encoding: NSUTF8StringEncoding) +==> "Arbitrary precision arithmetic is fun!" +``` + +Yay! This is truly terrific, but please don't use this example code in an actual +cryptography system. RSA has lots of subtle (and some not so subtle) complications +that we ignored to keep this example short. + +### Calculating the Digits of π + +Another fun activity to try with `BigInt`s is to generate the digits of π. +Let's try implementing [Jeremy Gibbon's spigot algorithm][spigot]. +This is a rather slow algorithm as π-generators go, but it makes up for it with its grooviness +factor: it's remarkably short, it only uses (big) integer arithmetic, and every iteration +produces a single new digit in the base-10 representation of π. This naturally leads to an +implementation as an infinite `GeneratorType`: + +[spigot]: http://www.cs.ox.ac.uk/jeremy.gibbons/publications/spigot.pdf + +```Swift +func digitsOfPi() -> AnyGenerator { + var q: BigUInt = 1 + var r: BigUInt = 180 + var t: BigUInt = 60 + var i: UInt64 = 2 // Does not overflow until digit #826_566_842 + return AnyIterator { + let u: UInt64 = 3 * (3 * i + 1) * (3 * i + 2) + let y = (q.multiplied(byDigit: 27 * i - 12) + 5 * r) / (5 * t) + (q, r, t) = ( + 10 * q.multiplied(byDigit: i * (2 * i - 1)), + 10 * (q.multiplied(byDigit: 5 * i - 2) + r - y * t).multiplied(byDigit: u), + t.multiplied(byDigit: u)) + i += 1 + return Int(y[0]) + } +} +``` + +Well, that was surprisingly easy. But does it work? Of course it does! + +```Swift +var digits = "π ≈ " +var count = 0 +for digit in digitsOfPi() { + assert(digit < 10) + digits += String(digit) + count += 1 + if count == 1 { digits += "." } + if count == 1000 { break } +} + +digits +==> π ≈ 3.14159265358979323846264338327950288419716939937510582097494459230781640628 + 62089986280348253421170679821480865132823066470938446095505822317253594081284811 + 17450284102701938521105559644622948954930381964428810975665933446128475648233786 + 78316527120190914564856692346034861045432664821339360726024914127372458700660631 + 55881748815209209628292540917153643678925903600113305305488204665213841469519415 + 11609433057270365759591953092186117381932611793105118548074462379962749567351885 + 75272489122793818301194912983367336244065664308602139494639522473719070217986094 + 37027705392171762931767523846748184676694051320005681271452635608277857713427577 + 89609173637178721468440901224953430146549585371050792279689258923542019956112129 + 02196086403441815981362977477130996051870721134999999837297804995105973173281609 + 63185950244594553469083026425223082533446850352619311881710100031378387528865875 + 33208381420617177669147303598253490428755468731159562863882353787593751957781857 + 780532171226806613001927876611195909216420198 +``` + +Now go and have some fun with big integers on your own! diff --git a/Example/Web3supportBrowser/Pods/BigInt/Sources/Addition.swift b/Example/Web3supportBrowser/Pods/BigInt/Sources/Addition.swift new file mode 100644 index 000000000..34f4d44e8 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/Sources/Addition.swift @@ -0,0 +1,126 @@ +// +// Addition.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension BigUInt { + //MARK: Addition + + /// Add `word` to this integer in place. + /// `word` is shifted `shift` words to the left before being added. + /// + /// - Complexity: O(max(count, shift)) + internal mutating func addWord(_ word: Word, shiftedBy shift: Int = 0) { + precondition(shift >= 0) + var carry = word + var i = shift + while carry > 0 { + let (d, c) = self[i].addingReportingOverflow(carry) + self[i] = d + carry = (c ? 1 : 0) + i += 1 + } + } + + /// Add the digit `d` to this integer and return the result. + /// `d` is shifted `shift` words to the left before being added. + /// + /// - Complexity: O(max(count, shift)) + internal func addingWord(_ word: Word, shiftedBy shift: Int = 0) -> BigUInt { + var r = self + r.addWord(word, shiftedBy: shift) + return r + } + + /// Add `b` to this integer in place. + /// `b` is shifted `shift` words to the left before being added. + /// + /// - Complexity: O(max(count, b.count + shift)) + internal mutating func add(_ b: BigUInt, shiftedBy shift: Int = 0) { + precondition(shift >= 0) + var carry = false + var bi = 0 + let bc = b.count + while bi < bc || carry { + let ai = shift + bi + let (d, c) = self[ai].addingReportingOverflow(b[bi]) + if carry { + let (d2, c2) = d.addingReportingOverflow(1) + self[ai] = d2 + carry = c || c2 + } + else { + self[ai] = d + carry = c + } + bi += 1 + } + } + + /// Add `b` to this integer and return the result. + /// `b` is shifted `shift` words to the left before being added. + /// + /// - Complexity: O(max(count, b.count + shift)) + internal func adding(_ b: BigUInt, shiftedBy shift: Int = 0) -> BigUInt { + var r = self + r.add(b, shiftedBy: shift) + return r + } + + /// Increment this integer by one. If `shift` is non-zero, it selects + /// the word that is to be incremented. + /// + /// - Complexity: O(count + shift) + internal mutating func increment(shiftedBy shift: Int = 0) { + self.addWord(1, shiftedBy: shift) + } + + /// Add `a` and `b` together and return the result. + /// + /// - Complexity: O(max(a.count, b.count)) + public static func +(a: BigUInt, b: BigUInt) -> BigUInt { + return a.adding(b) + } + + /// Add `a` and `b` together, and store the sum in `a`. + /// + /// - Complexity: O(max(a.count, b.count)) + public static func +=(a: inout BigUInt, b: BigUInt) { + a.add(b, shiftedBy: 0) + } +} + +extension BigInt { + /// Add `a` to `b` and return the result. + public static func +(a: BigInt, b: BigInt) -> BigInt { + switch (a.sign, b.sign) { + case (.plus, .plus): + return BigInt(sign: .plus, magnitude: a.magnitude + b.magnitude) + case (.minus, .minus): + return BigInt(sign: .minus, magnitude: a.magnitude + b.magnitude) + case (.plus, .minus): + if a.magnitude >= b.magnitude { + return BigInt(sign: .plus, magnitude: a.magnitude - b.magnitude) + } + else { + return BigInt(sign: .minus, magnitude: b.magnitude - a.magnitude) + } + case (.minus, .plus): + if b.magnitude >= a.magnitude { + return BigInt(sign: .plus, magnitude: b.magnitude - a.magnitude) + } + else { + return BigInt(sign: .minus, magnitude: a.magnitude - b.magnitude) + } + } + } + + /// Add `b` to `a` in place. + public static func +=(a: inout BigInt, b: BigInt) { + a = a + b + } +} + diff --git a/Example/Web3supportBrowser/Pods/BigInt/Sources/BigInt.swift b/Example/Web3supportBrowser/Pods/BigInt/Sources/BigInt.swift new file mode 100644 index 000000000..11318ffcc --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/Sources/BigInt.swift @@ -0,0 +1,74 @@ +// +// BigInt.swift +// BigInt +// +// Created by Károly Lőrentey on 2015-12-27. +// Copyright © 2016-2017 Károly Lőrentey. +// + +//MARK: BigInt + +/// An arbitary precision signed integer type, also known as a "big integer". +/// +/// Operations on big integers never overflow, but they might take a long time to execute. +/// The amount of memory (and address space) available is the only constraint to the magnitude of these numbers. +/// +/// This particular big integer type uses base-2^64 digits to represent integers. +/// +/// `BigInt` is essentially a tiny wrapper that extends `BigUInt` with a sign bit and provides signed integer +/// operations. Both the underlying absolute value and the negative/positive flag are available as read-write +/// properties. +/// +/// Not all algorithms of `BigUInt` are available for `BigInt` values; for example, there is no square root or +/// primality test for signed integers. When you need to call one of these, just extract the absolute value: +/// +/// ```Swift +/// BigInt(255).abs.isPrime() // Returns false +/// ``` +/// +public struct BigInt: SignedInteger { + public enum Sign { + case plus + case minus + } + + public typealias Magnitude = BigUInt + + /// The type representing a digit in `BigInt`'s underlying number system. + public typealias Word = BigUInt.Word + + public static var isSigned: Bool { + return true + } + + /// The absolute value of this integer. + public var magnitude: BigUInt + + /// True iff the value of this integer is negative. + public var sign: Sign + + /// Initializes a new big integer with the provided absolute number and sign flag. + public init(sign: Sign, magnitude: BigUInt) { + self.sign = (magnitude.isZero ? .plus : sign) + self.magnitude = magnitude + } + + /// Return true iff this integer is zero. + /// + /// - Complexity: O(1) + public var isZero: Bool { + return magnitude.isZero + } + + /// Returns `-1` if this value is negative and `1` if it’s positive; otherwise, `0`. + /// + /// - Returns: The sign of this number, expressed as an integer of the same type. + public func signum() -> BigInt { + switch sign { + case .plus: + return isZero ? 0 : 1 + case .minus: + return -1 + } + } +} diff --git a/Example/Web3supportBrowser/Pods/BigInt/Sources/BigUInt.swift b/Example/Web3supportBrowser/Pods/BigInt/Sources/BigUInt.swift new file mode 100644 index 000000000..81aa9a837 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/Sources/BigUInt.swift @@ -0,0 +1,386 @@ +// +// BigUInt.swift +// BigInt +// +// Created by Károly Lőrentey on 2015-12-26. +// Copyright © 2016-2017 Károly Lőrentey. +// + +/// An arbitary precision unsigned integer type, also known as a "big integer". +/// +/// Operations on big integers never overflow, but they may take a long time to execute. +/// The amount of memory (and address space) available is the only constraint to the magnitude of these numbers. +/// +/// This particular big integer type uses base-2^64 digits to represent integers; you can think of it as a wrapper +/// around `Array`. (In fact, `BigUInt` only uses an array if there are more than two digits.) +public struct BigUInt: UnsignedInteger { + /// The type representing a digit in `BigUInt`'s underlying number system. + public typealias Word = UInt + + /// The storage variants of a `BigUInt`. + enum Kind { + /// Value consists of the two specified words (low and high). Either or both words may be zero. + case inline(Word, Word) + /// Words are stored in a slice of the storage array. + case slice(from: Int, to: Int) + /// Words are stored in the storage array. + case array + } + + internal fileprivate (set) var kind: Kind // Internal for testing only + internal fileprivate (set) var storage: [Word] // Internal for testing only; stored separately to prevent COW copies + + /// Initializes a new BigUInt with value 0. + public init() { + self.kind = .inline(0, 0) + self.storage = [] + } + + internal init(word: Word) { + self.kind = .inline(word, 0) + self.storage = [] + } + + internal init(low: Word, high: Word) { + self.kind = .inline(low, high) + self.storage = [] + } + + /// Initializes a new BigUInt with the specified digits. The digits are ordered from least to most significant. + public init(words: [Word]) { + self.kind = .array + self.storage = words + normalize() + } + + internal init(words: [Word], from startIndex: Int, to endIndex: Int) { + self.kind = .slice(from: startIndex, to: endIndex) + self.storage = words + normalize() + } +} + +extension BigUInt { + public static var isSigned: Bool { + return false + } + + /// Return true iff this integer is zero. + /// + /// - Complexity: O(1) + var isZero: Bool { + switch kind { + case .inline(0, 0): return true + case .array: return storage.isEmpty + default: + return false + } + } + + /// Returns `1` if this value is, positive; otherwise, `0`. + /// + /// - Returns: The sign of this number, expressed as an integer of the same type. + public func signum() -> BigUInt { + return isZero ? 0 : 1 + } +} + +extension BigUInt { + mutating func ensureArray() { + switch kind { + case let .inline(w0, w1): + kind = .array + storage = w1 != 0 ? [w0, w1] + : w0 != 0 ? [w0] + : [] + case let .slice(from: start, to: end): + kind = .array + storage = Array(storage[start ..< end]) + case .array: + break + } + } + + var capacity: Int { + guard case .array = kind else { return 0 } + return storage.capacity + } + + mutating func reserveCapacity(_ minimumCapacity: Int) { + switch kind { + case let .inline(w0, w1): + kind = .array + storage.reserveCapacity(minimumCapacity) + if w1 != 0 { + storage.append(w0) + storage.append(w1) + } + else if w0 != 0 { + storage.append(w0) + } + case let .slice(from: start, to: end): + kind = .array + var words: [Word] = [] + words.reserveCapacity(Swift.max(end - start, minimumCapacity)) + words.append(contentsOf: storage[start ..< end]) + storage = words + case .array: + storage.reserveCapacity(minimumCapacity) + } + } + + /// Gets rid of leading zero digits in the digit array and converts slices into inline digits when possible. + internal mutating func normalize() { + switch kind { + case .slice(from: let start, to: var end): + assert(start >= 0 && end <= storage.count && start <= end) + while start < end, storage[end - 1] == 0 { + end -= 1 + } + switch end - start { + case 0: + kind = .inline(0, 0) + storage = [] + case 1: + kind = .inline(storage[start], 0) + storage = [] + case 2: + kind = .inline(storage[start], storage[start + 1]) + storage = [] + case storage.count: + assert(start == 0) + kind = .array + default: + kind = .slice(from: start, to: end) + } + case .array where storage.last == 0: + while storage.last == 0 { + storage.removeLast() + } + default: + break + } + } + + /// Set this integer to 0 without releasing allocated storage capacity (if any). + mutating func clear() { + self.load(0) + } + + /// Set this integer to `value` by copying its digits without releasing allocated storage capacity (if any). + mutating func load(_ value: BigUInt) { + switch kind { + case .inline, .slice: + self = value + case .array: + self.storage.removeAll(keepingCapacity: true) + self.storage.append(contentsOf: value.words) + } + } +} + +extension BigUInt { + //MARK: Collection-like members + + /// The number of digits in this integer, excluding leading zero digits. + var count: Int { + switch kind { + case let .inline(w0, w1): + return w1 != 0 ? 2 + : w0 != 0 ? 1 + : 0 + case let .slice(from: start, to: end): + return end - start + case .array: + return storage.count + } + } + + /// Get or set a digit at a given index. + /// + /// - Note: Unlike a normal collection, it is OK for the index to be greater than or equal to `endIndex`. + /// The subscripting getter returns zero for indexes beyond the most significant digit. + /// Setting these extended digits automatically appends new elements to the underlying digit array. + /// - Requires: index >= 0 + /// - Complexity: The getter is O(1). The setter is O(1) if the conditions below are true; otherwise it's O(count). + /// - The integer's storage is not shared with another integer + /// - The integer wasn't created as a slice of another integer + /// - `index < count` + subscript(_ index: Int) -> Word { + get { + precondition(index >= 0) + switch (kind, index) { + case (.inline(let w0, _), 0): return w0 + case (.inline(_, let w1), 1): return w1 + case (.slice(from: let start, to: let end), _) where index < end - start: + return storage[start + index] + case (.array, _) where index < storage.count: + return storage[index] + default: + return 0 + } + } + set(word) { + precondition(index >= 0) + switch (kind, index) { + case let (.inline(_, w1), 0): + kind = .inline(word, w1) + case let (.inline(w0, _), 1): + kind = .inline(w0, word) + case let (.slice(from: start, to: end), _) where index < end - start: + replace(at: index, with: word) + case (.array, _) where index < storage.count: + replace(at: index, with: word) + default: + extend(at: index, with: word) + } + } + } + + private mutating func replace(at index: Int, with word: Word) { + ensureArray() + precondition(index < storage.count) + storage[index] = word + if word == 0, index == storage.count - 1 { + normalize() + } + } + + private mutating func extend(at index: Int, with word: Word) { + guard word != 0 else { return } + reserveCapacity(index + 1) + precondition(index >= storage.count) + storage.append(contentsOf: repeatElement(0, count: index - storage.count)) + storage.append(word) + } + + /// Returns an integer built from the digits of this integer in the given range. + internal func extract(_ bounds: Range) -> BigUInt { + switch kind { + case let .inline(w0, w1): + let bounds = bounds.clamped(to: 0 ..< 2) + if bounds == 0 ..< 2 { + return BigUInt(low: w0, high: w1) + } + else if bounds == 0 ..< 1 { + return BigUInt(word: w0) + } + else if bounds == 1 ..< 2 { + return BigUInt(word: w1) + } + else { + return BigUInt() + } + case let .slice(from: start, to: end): + let s = Swift.min(end, start + Swift.max(bounds.lowerBound, 0)) + let e = Swift.max(s, (bounds.upperBound > end - start ? end : start + bounds.upperBound)) + return BigUInt(words: storage, from: s, to: e) + case .array: + let b = bounds.clamped(to: storage.startIndex ..< storage.endIndex) + return BigUInt(words: storage, from: b.lowerBound, to: b.upperBound) + } + } + + internal func extract(_ bounds: Bounds) -> BigUInt where Bounds.Bound == Int { + return self.extract(bounds.relative(to: 0 ..< Int.max)) + } +} + +extension BigUInt { + internal mutating func shiftRight(byWords amount: Int) { + assert(amount >= 0) + guard amount > 0 else { return } + switch kind { + case let .inline(_, w1) where amount == 1: + kind = .inline(w1, 0) + case .inline(_, _): + kind = .inline(0, 0) + case let .slice(from: start, to: end): + let s = start + amount + if s >= end { + kind = .inline(0, 0) + } + else { + kind = .slice(from: s, to: end) + normalize() + } + case .array: + if amount >= storage.count { + storage.removeAll(keepingCapacity: true) + } + else { + storage.removeFirst(amount) + } + } + } + + internal mutating func shiftLeft(byWords amount: Int) { + assert(amount >= 0) + guard amount > 0 else { return } + guard !isZero else { return } + switch kind { + case let .inline(w0, 0) where amount == 1: + kind = .inline(0, w0) + case let .inline(w0, w1): + let c = (w1 == 0 ? 1 : 2) + storage.reserveCapacity(amount + c) + storage.append(contentsOf: repeatElement(0, count: amount)) + storage.append(w0) + if w1 != 0 { + storage.append(w1) + } + kind = .array + case let .slice(from: start, to: end): + var words: [Word] = [] + words.reserveCapacity(amount + count) + words.append(contentsOf: repeatElement(0, count: amount)) + words.append(contentsOf: storage[start ..< end]) + storage = words + kind = .array + case .array: + storage.insert(contentsOf: repeatElement(0, count: amount), at: 0) + } + } +} + +extension BigUInt { + //MARK: Low and High + + /// Split this integer into a high-order and a low-order part. + /// + /// - Requires: count > 1 + /// - Returns: `(low, high)` such that + /// - `self == low.add(high, shiftedBy: middleIndex)` + /// - `high.width <= floor(width / 2)` + /// - `low.width <= ceil(width / 2)` + /// - Complexity: Typically O(1), but O(count) in the worst case, because high-order zero digits need to be removed after the split. + internal var split: (high: BigUInt, low: BigUInt) { + precondition(count > 1) + let mid = middleIndex + return (self.extract(mid...), self.extract(.. 1 + internal var low: BigUInt { + return self.extract(0 ..< middleIndex) + } + + /// The high-order half of this BigUInt. + /// + /// - Returns: `self[middleIndex ..< count]` + /// - Requires: count > 1 + internal var high: BigUInt { + return self.extract(middleIndex ..< count) + } +} + diff --git a/Example/Web3supportBrowser/Pods/BigInt/Sources/Bitwise Ops.swift b/Example/Web3supportBrowser/Pods/BigInt/Sources/Bitwise Ops.swift new file mode 100644 index 000000000..0d00148bd --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/Sources/Bitwise Ops.swift @@ -0,0 +1,121 @@ +// +// Bitwise Ops.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +//MARK: Bitwise Operations + +extension BigUInt { + /// Return the ones' complement of `a`. + /// + /// - Complexity: O(a.count) + public static prefix func ~(a: BigUInt) -> BigUInt { + return BigUInt(words: a.words.map { ~$0 }) + } + + /// Calculate the bitwise OR of `a` and `b`, and store the result in `a`. + /// + /// - Complexity: O(max(a.count, b.count)) + public static func |= (a: inout BigUInt, b: BigUInt) { + a.reserveCapacity(b.count) + for i in 0 ..< b.count { + a[i] |= b[i] + } + } + + /// Calculate the bitwise AND of `a` and `b` and return the result. + /// + /// - Complexity: O(max(a.count, b.count)) + public static func &= (a: inout BigUInt, b: BigUInt) { + for i in 0 ..< Swift.max(a.count, b.count) { + a[i] &= b[i] + } + } + + /// Calculate the bitwise XOR of `a` and `b` and return the result. + /// + /// - Complexity: O(max(a.count, b.count)) + public static func ^= (a: inout BigUInt, b: BigUInt) { + a.reserveCapacity(b.count) + for i in 0 ..< b.count { + a[i] ^= b[i] + } + } +} + +extension BigInt { + public static prefix func ~(x: BigInt) -> BigInt { + switch x.sign { + case .plus: + return BigInt(sign: .minus, magnitude: x.magnitude + 1) + case .minus: + return BigInt(sign: .plus, magnitude: x.magnitude - 1) + } + } + + public static func &(lhs: inout BigInt, rhs: BigInt) -> BigInt { + let left = lhs.words + let right = rhs.words + // Note we aren't using left.count/right.count here; we account for the sign bit separately later. + let count = Swift.max(lhs.magnitude.count, rhs.magnitude.count) + var words: [UInt] = [] + words.reserveCapacity(count) + for i in 0 ..< count { + words.append(left[i] & right[i]) + } + if lhs.sign == .minus && rhs.sign == .minus { + words.twosComplement() + return BigInt(sign: .minus, magnitude: BigUInt(words: words)) + } + return BigInt(sign: .plus, magnitude: BigUInt(words: words)) + } + + public static func |(lhs: inout BigInt, rhs: BigInt) -> BigInt { + let left = lhs.words + let right = rhs.words + // Note we aren't using left.count/right.count here; we account for the sign bit separately later. + let count = Swift.max(lhs.magnitude.count, rhs.magnitude.count) + var words: [UInt] = [] + words.reserveCapacity(count) + for i in 0 ..< count { + words.append(left[i] | right[i]) + } + if lhs.sign == .minus || rhs.sign == .minus { + words.twosComplement() + return BigInt(sign: .minus, magnitude: BigUInt(words: words)) + } + return BigInt(sign: .plus, magnitude: BigUInt(words: words)) + } + + public static func ^(lhs: inout BigInt, rhs: BigInt) -> BigInt { + let left = lhs.words + let right = rhs.words + // Note we aren't using left.count/right.count here; we account for the sign bit separately later. + let count = Swift.max(lhs.magnitude.count, rhs.magnitude.count) + var words: [UInt] = [] + words.reserveCapacity(count) + for i in 0 ..< count { + words.append(left[i] ^ right[i]) + } + if (lhs.sign == .minus) != (rhs.sign == .minus) { + words.twosComplement() + return BigInt(sign: .minus, magnitude: BigUInt(words: words)) + } + return BigInt(sign: .plus, magnitude: BigUInt(words: words)) + } + + public static func &=(lhs: inout BigInt, rhs: BigInt) { + lhs = lhs & rhs + } + + public static func |=(lhs: inout BigInt, rhs: BigInt) { + lhs = lhs | rhs + } + + public static func ^=(lhs: inout BigInt, rhs: BigInt) { + lhs = lhs ^ rhs + } +} diff --git a/Example/Web3supportBrowser/Pods/BigInt/Sources/Codable.swift b/Example/Web3supportBrowser/Pods/BigInt/Sources/Codable.swift new file mode 100644 index 000000000..b53b30be5 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/Sources/Codable.swift @@ -0,0 +1,155 @@ +// +// Codable.swift +// BigInt +// +// Created by Károly Lőrentey on 2017-8-11. +// Copyright © 2016-2017 Károly Lőrentey. +// + + +// Little-endian to big-endian +struct Units: RandomAccessCollection +where Words.Element: FixedWidthInteger, Words.Index == Int { + typealias Word = Words.Element + let words: Words + init(of type: Unit.Type, _ words: Words) { + precondition(Word.bitWidth % Unit.bitWidth == 0 || Unit.bitWidth % Word.bitWidth == 0) + self.words = words + } + var count: Int { return (words.count * Word.bitWidth + Unit.bitWidth - 1) / Unit.bitWidth } + var startIndex: Int { return 0 } + var endIndex: Int { return count } + subscript(_ index: Int) -> Unit { + let index = count - 1 - index + if Unit.bitWidth == Word.bitWidth { + return Unit(words[index]) + } + else if Unit.bitWidth > Word.bitWidth { + let c = Unit.bitWidth / Word.bitWidth + var unit: Unit = 0 + var j = 0 + for i in (c * index) ..< Swift.min(c * (index + 1), words.endIndex) { + unit |= Unit(words[i]) << j + j += Word.bitWidth + } + return unit + } + // Unit.bitWidth < Word.bitWidth + let c = Word.bitWidth / Unit.bitWidth + let i = index / c + let j = index % c + return Unit(truncatingIfNeeded: words[i] >> (j * Unit.bitWidth)) + } +} + +extension Array where Element: FixedWidthInteger { + // Big-endian to little-endian + init(count: Int?, generator: () throws -> Unit?) rethrows { + typealias Word = Element + precondition(Word.bitWidth % Unit.bitWidth == 0 || Unit.bitWidth % Word.bitWidth == 0) + self = [] + if Unit.bitWidth == Word.bitWidth { + if let count = count { + self.reserveCapacity(count) + } + while let unit = try generator() { + self.append(Word(unit)) + } + } + else if Unit.bitWidth > Word.bitWidth { + let wordsPerUnit = Unit.bitWidth / Word.bitWidth + if let count = count { + self.reserveCapacity(count * wordsPerUnit) + } + while let unit = try generator() { + var shift = Unit.bitWidth - Word.bitWidth + while shift >= 0 { + self.append(Word(truncatingIfNeeded: unit >> shift)) + shift -= Word.bitWidth + } + } + } + else { + let unitsPerWord = Word.bitWidth / Unit.bitWidth + if let count = count { + self.reserveCapacity((count + unitsPerWord - 1) / unitsPerWord) + } + var word: Word = 0 + var c = 0 + while let unit = try generator() { + word <<= Unit.bitWidth + word |= Word(unit) + c += Unit.bitWidth + if c == Word.bitWidth { + self.append(word) + word = 0 + c = 0 + } + } + if c > 0 { + self.append(word << c) + var shifted: Word = 0 + for i in self.indices { + let word = self[i] + self[i] = shifted | (word >> c) + shifted = word << (Word.bitWidth - c) + } + } + } + self.reverse() + } +} + +extension BigInt: Codable { + public init(from decoder: Decoder) throws { + var container = try decoder.unkeyedContainer() + + // Decode sign + let sign: BigInt.Sign + switch try container.decode(String.self) { + case "+": + sign = .plus + case "-": + sign = .minus + default: + throw DecodingError.dataCorrupted(.init(codingPath: container.codingPath, + debugDescription: "Invalid big integer sign")) + } + + // Decode magnitude + let words = try [UInt](count: container.count?.advanced(by: -1)) { () -> UInt64? in + guard !container.isAtEnd else { return nil } + return try container.decode(UInt64.self) + } + let magnitude = BigUInt(words: words) + + self.init(sign: sign, magnitude: magnitude) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.unkeyedContainer() + try container.encode(sign == .plus ? "+" : "-") + let units = Units(of: UInt64.self, self.magnitude.words) + if units.isEmpty { + try container.encode(0 as UInt64) + } + else { + try container.encode(contentsOf: units) + } + } +} + +extension BigUInt: Codable { + public init(from decoder: Decoder) throws { + let value = try BigInt(from: decoder) + guard value.sign == .plus else { + throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, + debugDescription: "BigUInt cannot hold a negative value")) + } + self = value.magnitude + } + + public func encode(to encoder: Encoder) throws { + try BigInt(sign: .plus, magnitude: self).encode(to: encoder) + } +} diff --git a/Example/Web3supportBrowser/Pods/BigInt/Sources/Comparable.swift b/Example/Web3supportBrowser/Pods/BigInt/Sources/Comparable.swift new file mode 100644 index 000000000..d9ab87e7e --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/Sources/Comparable.swift @@ -0,0 +1,63 @@ +// +// Comparable.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +import Foundation + +extension BigUInt: Comparable { + //MARK: Comparison + + /// Compare `a` to `b` and return an `NSComparisonResult` indicating their order. + /// + /// - Complexity: O(count) + public static func compare(_ a: BigUInt, _ b: BigUInt) -> ComparisonResult { + if a.count != b.count { return a.count > b.count ? .orderedDescending : .orderedAscending } + for i in (0 ..< a.count).reversed() { + let ad = a[i] + let bd = b[i] + if ad != bd { return ad > bd ? .orderedDescending : .orderedAscending } + } + return .orderedSame + } + + /// Return true iff `a` is equal to `b`. + /// + /// - Complexity: O(count) + public static func ==(a: BigUInt, b: BigUInt) -> Bool { + return BigUInt.compare(a, b) == .orderedSame + } + + /// Return true iff `a` is less than `b`. + /// + /// - Complexity: O(count) + public static func <(a: BigUInt, b: BigUInt) -> Bool { + return BigUInt.compare(a, b) == .orderedAscending + } +} + +extension BigInt { + /// Return true iff `a` is equal to `b`. + public static func ==(a: BigInt, b: BigInt) -> Bool { + return a.sign == b.sign && a.magnitude == b.magnitude + } + + /// Return true iff `a` is less than `b`. + public static func <(a: BigInt, b: BigInt) -> Bool { + switch (a.sign, b.sign) { + case (.plus, .plus): + return a.magnitude < b.magnitude + case (.plus, .minus): + return false + case (.minus, .plus): + return true + case (.minus, .minus): + return a.magnitude > b.magnitude + } + } +} + + diff --git a/Example/Web3supportBrowser/Pods/BigInt/Sources/Data Conversion.swift b/Example/Web3supportBrowser/Pods/BigInt/Sources/Data Conversion.swift new file mode 100644 index 000000000..ffc0ac206 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/Sources/Data Conversion.swift @@ -0,0 +1,107 @@ +// +// Data Conversion.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-04. +// Copyright © 2016-2017 Károly Lőrentey. +// + +import Foundation + +extension BigUInt { + //MARK: NSData Conversion + + public init(_ buffer: UnsafeRawBufferPointer) { + // This assumes Word is binary. + precondition(Word.bitWidth % 8 == 0) + + self.init() + + let length = buffer.count + guard length > 0 else { return } + let bytesPerDigit = Word.bitWidth / 8 + var index = length / bytesPerDigit + var c = bytesPerDigit - length % bytesPerDigit + if c == bytesPerDigit { + c = 0 + index -= 1 + } + + var word: Word = 0 + for byte in buffer { + word <<= 8 + word += Word(byte) + c += 1 + if c == bytesPerDigit { + self[index] = word + index -= 1 + c = 0 + word = 0 + } + } + assert(c == 0 && word == 0 && index == -1) + } + + + /// Initializes an integer from the bits stored inside a piece of `Data`. + /// The data is assumed to be in network (big-endian) byte order. + public init(_ data: Data) { + // This assumes Word is binary. + precondition(Word.bitWidth % 8 == 0) + + self.init() + + let length = data.count + guard length > 0 else { return } + let bytesPerDigit = Word.bitWidth / 8 + var index = length / bytesPerDigit + var c = bytesPerDigit - length % bytesPerDigit + if c == bytesPerDigit { + c = 0 + index -= 1 + } + var word: Word = 0 + data.enumerateBytes { p, byteIndex, stop in + for byte in p { + word <<= 8 + word += Word(byte) + c += 1 + if c == bytesPerDigit { + self[index] = word + index -= 1 + c = 0 + word = 0 + } + } + } + assert(c == 0 && word == 0 && index == -1) + } + + /// Return a `Data` value that contains the base-256 representation of this integer, in network (big-endian) byte order. + public func serialize() -> Data { + // This assumes Digit is binary. + precondition(Word.bitWidth % 8 == 0) + + let byteCount = (self.bitWidth + 7) / 8 + + guard byteCount > 0 else { return Data() } + + var data = Data(count: byteCount) + data.withUnsafeMutableBytes { (p: UnsafeMutablePointer) -> Void in + var i = byteCount - 1 + for var word in self.words { + for _ in 0 ..< Word.bitWidth / 8 { + p[i] = UInt8(word & 0xFF) + word >>= 8 + if i == 0 { + assert(word == 0) + break + } + i -= 1 + } + } + } + return data + } +} + diff --git a/Example/Web3supportBrowser/Pods/BigInt/Sources/Division.swift b/Example/Web3supportBrowser/Pods/BigInt/Sources/Division.swift new file mode 100644 index 000000000..4393f52e9 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/Sources/Division.swift @@ -0,0 +1,374 @@ +// +// Division.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +//MARK: Full-width multiplication and division + +extension FixedWidthInteger where Magnitude == Self { + private var halfShift: Self { + return Self(Self.bitWidth / 2) + + } + private var high: Self { + return self &>> halfShift + } + + private var low: Self { + let mask: Self = 1 &<< halfShift - 1 + return self & mask + } + + private var upshifted: Self { + return self &<< halfShift + } + + private var split: (high: Self, low: Self) { + return (self.high, self.low) + } + + private init(_ value: (high: Self, low: Self)) { + self = value.high.upshifted + value.low + } + + /// Divide the double-width integer `dividend` by `self` and return the quotient and remainder. + /// + /// - Requires: `dividend.high < self`, so that the result will fit in a single digit. + /// - Complexity: O(1) with 2 divisions, 6 multiplications and ~12 or so additions/subtractions. + internal func fastDividingFullWidth(_ dividend: (high: Self, low: Self.Magnitude)) -> (quotient: Self, remainder: Self) { + // Division is complicated; doing it with single-digit operations is maddeningly complicated. + // This is a Swift adaptation for "divlu2" in Hacker's Delight, + // which is in turn a C adaptation of Knuth's Algorithm D (TAOCP vol 2, 4.3.1). + precondition(dividend.high < self) + + // This replaces the implementation in stdlib, which is much slower. + // FIXME: Speed up stdlib. It should use full-width idiv on Intel processors, and + // fall back to a reasonably fast algorithm elsewhere. + + // The trick here is that we're actually implementing a 4/2 long division using half-words, + // with the long division loop unrolled into two 3/2 half-word divisions. + // Luckily, 3/2 half-word division can be approximated by a single full-word division operation + // that, when the divisor is normalized, differs from the correct result by at most 2. + + /// Find the half-word quotient in `u / vn`, which must be normalized. + /// `u` contains three half-words in the two halves of `u.high` and the lower half of + /// `u.low`. (The weird distribution makes for a slightly better fit with the input.) + /// `vn` contains the normalized divisor, consisting of two half-words. + /// + /// - Requires: u.high < vn && u.low.high == 0 && vn.leadingZeroBitCount == 0 + func quotient(dividing u: (high: Self, low: Self), by vn: Self) -> Self { + let (vn1, vn0) = vn.split + // Get approximate quotient. + let (q, r) = u.high.quotientAndRemainder(dividingBy: vn1) + let p = q * vn0 + // q is often already correct, but sometimes the approximation overshoots by at most 2. + // The code that follows checks for this while being careful to only perform single-digit operations. + if q.high == 0 && p <= r.upshifted + u.low { return q } + let r2 = r + vn1 + if r2.high != 0 { return q - 1 } + if (q - 1).high == 0 && p - vn0 <= r2.upshifted + u.low { return q - 1 } + //assert((r + 2 * vn1).high != 0 || p - 2 * vn0 <= (r + 2 * vn1).upshifted + u.low) + return q - 2 + } + /// Divide 3 half-digits by 2 half-digits to get a half-digit quotient and a full-digit remainder. + /// + /// - Requires: u.high < v && u.low.high == 0 && vn.width = width(Digit) + func quotientAndRemainder(dividing u: (high: Self, low: Self), by v: Self) -> (quotient: Self, remainder: Self) { + let q = quotient(dividing: u, by: v) + // Note that `uh.low` masks off a couple of bits, and `q * v` and the + // subtraction are likely to overflow. Despite this, the end result (remainder) will + // still be correct and it will fit inside a single (full) Digit. + let r = Self(u) &- q &* v + assert(r < v) + return (q, r) + } + + // Normalize the dividend and the divisor (self) such that the divisor has no leading zeroes. + let z = Self(self.leadingZeroBitCount) + let w = Self(Self.bitWidth) - z + let vn = self << z + + let un32 = (z == 0 ? dividend.high : (dividend.high &<< z) | (dividend.low &>> w)) // No bits are lost + let un10 = dividend.low &<< z + let (un1, un0) = un10.split + + // Divide `(un32,un10)` by `vn`, splitting the full 4/2 division into two 3/2 ones. + let (q1, un21) = quotientAndRemainder(dividing: (un32, un1), by: vn) + let (q0, rn) = quotientAndRemainder(dividing: (un21, un0), by: vn) + + // Undo normalization of the remainder and combine the two halves of the quotient. + let mod = rn >> z + let div = Self((q1, q0)) + return (div, mod) + } + + /// Return the quotient of the 3/2-word division `x/y` as a single word. + /// + /// - Requires: (x.0, x.1) <= y && y.0.high != 0 + /// - Returns: The exact value when it fits in a single word, otherwise `Self`. + static func approximateQuotient(dividing x: (Self, Self, Self), by y: (Self, Self)) -> Self { + // Start with q = (x.0, x.1) / y.0, (or Word.max on overflow) + var q: Self + var r: Self + if x.0 == y.0 { + q = Self.max + let (s, o) = x.0.addingReportingOverflow(x.1) + if o { return q } + r = s + } + else { + (q, r) = y.0.fastDividingFullWidth((x.0, x.1)) + } + // Now refine q by considering x.2 and y.1. + // Note that since y is normalized, q * y - x is between 0 and 2. + let (ph, pl) = q.multipliedFullWidth(by: y.1) + if ph < r || (ph == r && pl <= x.2) { return q } + + let (r1, ro) = r.addingReportingOverflow(y.0) + if ro { return q - 1 } + + let (pl1, so) = pl.subtractingReportingOverflow(y.1) + let ph1 = (so ? ph - 1 : ph) + + if ph1 < r1 || (ph1 == r1 && pl1 <= x.2) { return q - 1 } + return q - 2 + } +} + +extension BigUInt { + //MARK: Division + + /// Divide this integer by the word `y`, leaving the quotient in its place and returning the remainder. + /// + /// - Requires: y > 0 + /// - Complexity: O(count) + internal mutating func divide(byWord y: Word) -> Word { + precondition(y > 0) + if y == 1 { return 0 } + + var remainder: Word = 0 + for i in (0 ..< count).reversed() { + let u = self[i] + (self[i], remainder) = y.fastDividingFullWidth((remainder, u)) + } + return remainder + } + + /// Divide this integer by the word `y` and return the resulting quotient and remainder. + /// + /// - Requires: y > 0 + /// - Returns: (quotient, remainder) where quotient = floor(x/y), remainder = x - quotient * y + /// - Complexity: O(x.count) + internal func quotientAndRemainder(dividingByWord y: Word) -> (quotient: BigUInt, remainder: Word) { + var div = self + let mod = div.divide(byWord: y) + return (div, mod) + } + + /// Divide `x` by `y`, putting the quotient in `x` and the remainder in `y`. + /// Reusing integers like this reduces the number of allocations during the calculation. + static func divide(_ x: inout BigUInt, by y: inout BigUInt) { + // This is a Swift adaptation of "divmnu" from Hacker's Delight, which is in + // turn a C adaptation of Knuth's Algorithm D (TAOCP vol 2, 4.3.1). + + precondition(!y.isZero) + + // First, let's take care of the easy cases. + if x < y { + (x, y) = (0, x) + return + } + if y.count == 1 { + // The single-word case reduces to a simpler loop. + y = BigUInt(x.divide(byWord: y[0])) + return + } + + // In the hard cases, we will perform the long division algorithm we learned in school. + // It works by successively calculating the single-word quotient of the top y.count + 1 + // words of x divided by y, replacing the top of x with the remainder, and repeating + // the process one word lower. + // + // The tricky part is that the algorithm needs to be able to do n+1/n word divisions, + // but we only have a primitive for dividing two words by a single + // word. (Remember that this step is also tricky when we do it on paper!) + // + // The solution is that the long division can be approximated by a single full division + // using just the most significant words. We can then use multiplications and + // subtractions to refine the approximation until we get the correct quotient word. + // + // We could do this by doing a simple 2/1 full division, but Knuth goes one step further, + // and implements a 3/2 division. This results in an exact approximation in the + // vast majority of cases, eliminating an extra subtraction over big integers. + // + // The function `approximateQuotient` above implements Knuth's 3/2 division algorithm. + // It requires that the divisor's most significant word is larger than + // Word.max / 2. This ensures that the approximation has tiny error bounds, + // which is what makes this entire approach viable. + // To satisfy this requirement, we will normalize the division by multiplying + // both the divisor and the dividend by the same (small) factor. + let z = y.leadingZeroBitCount + y <<= z + x <<= z // We'll calculate the remainder in the normalized dividend. + var quotient = BigUInt() + assert(y.leadingZeroBitCount == 0) + + // We're ready to start the long division! + let dc = y.count + let d1 = y[dc - 1] + let d0 = y[dc - 2] + var product: BigUInt = 0 + for j in (dc ... x.count).reversed() { + // Approximate dividing the top dc+1 words of `remainder` using the topmost 3/2 words. + let r2 = x[j] + let r1 = x[j - 1] + let r0 = x[j - 2] + let q = Word.approximateQuotient(dividing: (r2, r1, r0), by: (d1, d0)) + + // Multiply the entire divisor with `q` and subtract the result from remainder. + // Normalization ensures the 3/2 quotient will either be exact for the full division, or + // it may overshoot by at most 1, in which case the product will be greater + // than the remainder. + product.load(y) + product.multiply(byWord: q) + if product <= x.extract(j - dc ..< j + 1) { + x.subtract(product, shiftedBy: j - dc) + quotient[j - dc] = q + } + else { + // This case is extremely rare -- it has a probability of 1/2^(Word.bitWidth - 1). + x.add(y, shiftedBy: j - dc) + x.subtract(product, shiftedBy: j - dc) + quotient[j - dc] = q - 1 + } + } + // The remainder's normalization needs to be undone, but otherwise we're done. + x >>= z + y = x + x = quotient + } + + /// Divide `x` by `y`, putting the remainder in `x`. + mutating func formRemainder(dividingBy y: BigUInt, normalizedBy shift: Int) { + precondition(!y.isZero) + assert(y.leadingZeroBitCount == 0) + if y.count == 1 { + let remainder = self.divide(byWord: y[0] >> shift) + self.load(BigUInt(remainder)) + return + } + self <<= shift + if self >= y { + let dc = y.count + let d1 = y[dc - 1] + let d0 = y[dc - 2] + var product: BigUInt = 0 + for j in (dc ... self.count).reversed() { + let r2 = self[j] + let r1 = self[j - 1] + let r0 = self[j - 2] + let q = Word.approximateQuotient(dividing: (r2, r1, r0), by: (d1, d0)) + product.load(y) + product.multiply(byWord: q) + if product <= self.extract(j - dc ..< j + 1) { + self.subtract(product, shiftedBy: j - dc) + } + else { + self.add(y, shiftedBy: j - dc) + self.subtract(product, shiftedBy: j - dc) + } + } + } + self >>= shift + } + + + /// Divide this integer by `y` and return the resulting quotient and remainder. + /// + /// - Requires: `y > 0` + /// - Returns: `(quotient, remainder)` where `quotient = floor(self/y)`, `remainder = self - quotient * y` + /// - Complexity: O(count^2) + public func quotientAndRemainder(dividingBy y: BigUInt) -> (quotient: BigUInt, remainder: BigUInt) { + var x = self + var y = y + BigUInt.divide(&x, by: &y) + return (x, y) + } + + /// Divide `x` by `y` and return the quotient. + /// + /// - Note: Use `divided(by:)` if you also need the remainder. + public static func /(x: BigUInt, y: BigUInt) -> BigUInt { + return x.quotientAndRemainder(dividingBy: y).quotient + } + + /// Divide `x` by `y` and return the remainder. + /// + /// - Note: Use `divided(by:)` if you also need the remainder. + public static func %(x: BigUInt, y: BigUInt) -> BigUInt { + var x = x + let shift = y.leadingZeroBitCount + x.formRemainder(dividingBy: y << shift, normalizedBy: shift) + return x + } + + /// Divide `x` by `y` and store the quotient in `x`. + /// + /// - Note: Use `divided(by:)` if you also need the remainder. + public static func /=(x: inout BigUInt, y: BigUInt) { + var y = y + BigUInt.divide(&x, by: &y) + } + + /// Divide `x` by `y` and store the remainder in `x`. + /// + /// - Note: Use `divided(by:)` if you also need the remainder. + public static func %=(x: inout BigUInt, y: BigUInt) { + let shift = y.leadingZeroBitCount + x.formRemainder(dividingBy: y << shift, normalizedBy: shift) + } +} + +extension BigInt { + /// Divide this integer by `y` and return the resulting quotient and remainder. + /// + /// - Requires: `y > 0` + /// - Returns: `(quotient, remainder)` where `quotient = floor(self/y)`, `remainder = self - quotient * y` + /// - Complexity: O(count^2) + public func quotientAndRemainder(dividingBy y: BigInt) -> (quotient: BigInt, remainder: BigInt) { + var a = self.magnitude + var b = y.magnitude + BigUInt.divide(&a, by: &b) + return (BigInt(sign: self.sign == y.sign ? .plus : .minus, magnitude: a), + BigInt(sign: self.sign, magnitude: b)) + } + + /// Divide `a` by `b` and return the quotient. Traps if `b` is zero. + public static func /(a: BigInt, b: BigInt) -> BigInt { + return BigInt(sign: a.sign == b.sign ? .plus : .minus, magnitude: a.magnitude / b.magnitude) + } + + /// Divide `a` by `b` and return the remainder. The result has the same sign as `a`. + public static func %(a: BigInt, b: BigInt) -> BigInt { + return BigInt(sign: a.sign, magnitude: a.magnitude % b.magnitude) + } + + /// Return the result of `a` mod `b`. The result is always a nonnegative integer that is less than the absolute value of `b`. + public func modulus(_ mod: BigInt) -> BigInt { + let remainder = self.magnitude % mod.magnitude + return BigInt( + self.sign == .minus && !remainder.isZero + ? mod.magnitude - remainder + : remainder) + } +} + +extension BigInt { + /// Divide `a` by `b` storing the quotient in `a`. + public static func /=(a: inout BigInt, b: BigInt) { a = a / b } + /// Divide `a` by `b` storing the remainder in `a`. + public static func %=(a: inout BigInt, b: BigInt) { a = a % b } +} diff --git a/Example/Web3supportBrowser/Pods/BigInt/Sources/Exponentiation.swift b/Example/Web3supportBrowser/Pods/BigInt/Sources/Exponentiation.swift new file mode 100644 index 000000000..9d7ee85da --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/Sources/Exponentiation.swift @@ -0,0 +1,119 @@ +// +// Exponentiation.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension BigUInt { + //MARK: Exponentiation + + /// Returns this integer raised to the power `exponent`. + /// + /// This function calculates the result by [successively squaring the base while halving the exponent][expsqr]. + /// + /// [expsqr]: https://en.wikipedia.org/wiki/Exponentiation_by_squaring + /// + /// - Note: This function can be unreasonably expensive for large exponents, which is why `exponent` is + /// a simple integer value. If you want to calculate big exponents, you'll probably need to use + /// the modulo arithmetic variant. + /// - Returns: 1 if `exponent == 0`, otherwise `self` raised to `exponent`. (This implies that `0.power(0) == 1`.) + /// - SeeAlso: `BigUInt.power(_:, modulus:)` + /// - Complexity: O((exponent * self.count)^log2(3)) or somesuch. The result may require a large amount of memory, too. + public func power(_ exponent: Int) -> BigUInt { + if exponent == 0 { return 1 } + if exponent == 1 { return self } + if exponent < 0 { + precondition(!self.isZero) + return self == 1 ? 1 : 0 + } + if self <= 1 { return self } + var result = BigUInt(1) + var b = self + var e = exponent + while e > 0 { + if e & 1 == 1 { + result *= b + } + e >>= 1 + b *= b + } + return result + } + + /// Returns the remainder of this integer raised to the power `exponent` in modulo arithmetic under `modulus`. + /// + /// Uses the [right-to-left binary method][rtlb]. + /// + /// [rtlb]: https://en.wikipedia.org/wiki/Modular_exponentiation#Right-to-left_binary_method + /// + /// - Complexity: O(exponent.count * modulus.count^log2(3)) or somesuch + public func power(_ exponent: BigUInt, modulus: BigUInt) -> BigUInt { + precondition(!modulus.isZero) + if modulus == (1 as BigUInt) { return 0 } + let shift = modulus.leadingZeroBitCount + let normalizedModulus = modulus << shift + var result = BigUInt(1) + var b = self + b.formRemainder(dividingBy: normalizedModulus, normalizedBy: shift) + for var e in exponent.words { + for _ in 0 ..< Word.bitWidth { + if e & 1 == 1 { + result *= b + result.formRemainder(dividingBy: normalizedModulus, normalizedBy: shift) + } + e >>= 1 + b *= b + b.formRemainder(dividingBy: normalizedModulus, normalizedBy: shift) + } + } + return result + } +} + +extension BigInt { + /// Returns this integer raised to the power `exponent`. + /// + /// This function calculates the result by [successively squaring the base while halving the exponent][expsqr]. + /// + /// [expsqr]: https://en.wikipedia.org/wiki/Exponentiation_by_squaring + /// + /// - Note: This function can be unreasonably expensive for large exponents, which is why `exponent` is + /// a simple integer value. If you want to calculate big exponents, you'll probably need to use + /// the modulo arithmetic variant. + /// - Returns: 1 if `exponent == 0`, otherwise `self` raised to `exponent`. (This implies that `0.power(0) == 1`.) + /// - SeeAlso: `BigUInt.power(_:, modulus:)` + /// - Complexity: O((exponent * self.count)^log2(3)) or somesuch. The result may require a large amount of memory, too. + public func power(_ exponent: Int) -> BigInt { + return BigInt(sign: self.sign == .minus && exponent & 1 != 0 ? .minus : .plus, + magnitude: self.magnitude.power(exponent)) + } + + /// Returns the remainder of this integer raised to the power `exponent` in modulo arithmetic under `modulus`. + /// + /// Uses the [right-to-left binary method][rtlb]. + /// + /// [rtlb]: https://en.wikipedia.org/wiki/Modular_exponentiation#Right-to-left_binary_method + /// + /// - Complexity: O(exponent.count * modulus.count^log2(3)) or somesuch + public func power(_ exponent: BigInt, modulus: BigInt) -> BigInt { + precondition(!modulus.isZero) + if modulus.magnitude == 1 { return 0 } + if exponent.isZero { return 1 } + if exponent == 1 { return self.modulus(modulus) } + if exponent < 0 { + precondition(!self.isZero) + guard magnitude == 1 else { return 0 } + guard sign == .minus else { return 1 } + guard exponent.magnitude[0] & 1 != 0 else { return 1 } + return BigInt(modulus.magnitude - 1) + } + let power = self.magnitude.power(exponent.magnitude, + modulus: modulus.magnitude) + if self.sign == .plus || exponent.magnitude[0] & 1 == 0 || power.isZero { + return BigInt(power) + } + return BigInt(modulus.magnitude - power) + } +} diff --git a/Example/Web3supportBrowser/Pods/BigInt/Sources/Floating Point Conversion.swift b/Example/Web3supportBrowser/Pods/BigInt/Sources/Floating Point Conversion.swift new file mode 100644 index 000000000..6c2395a31 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/Sources/Floating Point Conversion.swift @@ -0,0 +1,73 @@ +// +// Floating Point Conversion.swift +// BigInt +// +// Created by Károly Lőrentey on 2017-08-11. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension BigUInt { + public init?(exactly source: T) { + guard source.isFinite else { return nil } + guard !source.isZero else { self = 0; return } + guard source.sign == .plus else { return nil } + let value = source.rounded(.towardZero) + guard value == source else { return nil } + assert(value.floatingPointClass == .positiveNormal) + assert(value.exponent >= 0) + let significand = value.significandBitPattern + self = (BigUInt(1) << value.exponent) + BigUInt(significand) >> (T.significandBitCount - Int(value.exponent)) + } + + public init(_ source: T) { + self.init(exactly: source.rounded(.towardZero))! + } +} + +extension BigInt { + public init?(exactly source: T) { + switch source.sign{ + case .plus: + guard let magnitude = BigUInt(exactly: source) else { return nil } + self = BigInt(sign: .plus, magnitude: magnitude) + case .minus: + guard let magnitude = BigUInt(exactly: -source) else { return nil } + self = BigInt(sign: .minus, magnitude: magnitude) + } + } + + public init(_ source: T) { + self.init(exactly: source.rounded(.towardZero))! + } +} + +extension BinaryFloatingPoint where RawExponent: FixedWidthInteger, RawSignificand: FixedWidthInteger { + public init(_ value: BigInt) { + guard !value.isZero else { self = 0; return } + let v = value.magnitude + let bitWidth = v.bitWidth + var exponent = bitWidth - 1 + let shift = bitWidth - Self.significandBitCount - 1 + var significand = value.magnitude >> (shift - 1) + if significand[0] & 3 == 3 { // Handle rounding + significand >>= 1 + significand += 1 + if significand.trailingZeroBitCount >= Self.significandBitCount { + exponent += 1 + } + } + else { + significand >>= 1 + } + let bias = 1 << (Self.exponentBitCount - 1) - 1 + guard exponent <= bias else { self = Self.infinity; return } + significand &= 1 << Self.significandBitCount - 1 + self = Self.init(sign: value.sign == .plus ? .plus : .minus, + exponentBitPattern: RawExponent(bias + exponent), + significandBitPattern: RawSignificand(significand)) + } + + public init(_ value: BigUInt) { + self.init(BigInt(sign: .plus, magnitude: value)) + } +} diff --git a/Example/Web3supportBrowser/Pods/BigInt/Sources/GCD.swift b/Example/Web3supportBrowser/Pods/BigInt/Sources/GCD.swift new file mode 100644 index 000000000..d55605dce --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/Sources/GCD.swift @@ -0,0 +1,80 @@ +// +// GCD.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension BigUInt { + //MARK: Greatest Common Divisor + + /// Returns the greatest common divisor of `self` and `b`. + /// + /// - Complexity: O(count^2) where count = max(self.count, b.count) + public func greatestCommonDivisor(with b: BigUInt) -> BigUInt { + // This is Stein's algorithm: https://en.wikipedia.org/wiki/Binary_GCD_algorithm + if self.isZero { return b } + if b.isZero { return self } + + let az = self.trailingZeroBitCount + let bz = b.trailingZeroBitCount + let twos = Swift.min(az, bz) + + var (x, y) = (self >> az, b >> bz) + if x < y { swap(&x, &y) } + + while !x.isZero { + x >>= x.trailingZeroBitCount + if x < y { swap(&x, &y) } + x -= y + } + return y << twos + } + + /// Returns the [multiplicative inverse of this integer in modulo `modulus` arithmetic][inverse], + /// or `nil` if there is no such number. + /// + /// [inverse]: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Modular_integers + /// + /// - Returns: If `gcd(self, modulus) == 1`, the value returned is an integer `a < modulus` such that `(a * self) % modulus == 1`. If `self` and `modulus` aren't coprime, the return value is `nil`. + /// - Requires: modulus > 1 + /// - Complexity: O(count^3) + public func inverse(_ modulus: BigUInt) -> BigUInt? { + precondition(modulus > 1) + var t1 = BigInt(0) + var t2 = BigInt(1) + var r1 = modulus + var r2 = self + while !r2.isZero { + let quotient = r1 / r2 + (t1, t2) = (t2, t1 - BigInt(quotient) * t2) + (r1, r2) = (r2, r1 - quotient * r2) + } + if r1 > 1 { return nil } + if t1.sign == .minus { return modulus - t1.magnitude } + return t1.magnitude + } +} + +extension BigInt { + /// Returns the greatest common divisor of `a` and `b`. + /// + /// - Complexity: O(count^2) where count = max(a.count, b.count) + public func greatestCommonDivisor(with b: BigInt) -> BigInt { + return BigInt(self.magnitude.greatestCommonDivisor(with: b.magnitude)) + } + + /// Returns the [multiplicative inverse of this integer in modulo `modulus` arithmetic][inverse], + /// or `nil` if there is no such number. + /// + /// [inverse]: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Modular_integers + /// + /// - Returns: If `gcd(self, modulus) == 1`, the value returned is an integer `a < modulus` such that `(a * self) % modulus == 1`. If `self` and `modulus` aren't coprime, the return value is `nil`. + /// - Requires: modulus.magnitude > 1 + /// - Complexity: O(count^3) + public func inverse(_ modulus: BigInt) -> BigInt? { + guard let inv = self.magnitude.inverse(modulus.magnitude) else { return nil } + return BigInt(self.sign == .plus || inv.isZero ? inv : modulus.magnitude - inv) + } +} diff --git a/Example/Web3supportBrowser/Pods/BigInt/Sources/Hashable.swift b/Example/Web3supportBrowser/Pods/BigInt/Sources/Hashable.swift new file mode 100644 index 000000000..c5dc0e642 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/Sources/Hashable.swift @@ -0,0 +1,26 @@ +// +// Hashable.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension BigUInt: Hashable { + //MARK: Hashing + + /// Append this `BigUInt` to the specified hasher. + public func hash(into hasher: inout Hasher) { + for word in self.words { + hasher.combine(word) + } + } +} + +extension BigInt: Hashable { + /// Append this `BigInt` to the specified hasher. + public func hash(into hasher: inout Hasher) { + hasher.combine(sign) + hasher.combine(magnitude) + } +} diff --git a/Example/Web3supportBrowser/Pods/BigInt/Sources/Integer Conversion.swift b/Example/Web3supportBrowser/Pods/BigInt/Sources/Integer Conversion.swift new file mode 100644 index 000000000..9a210e4a4 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/Sources/Integer Conversion.swift @@ -0,0 +1,89 @@ +// +// Integer Conversion.swift +// BigInt +// +// Created by Károly Lőrentey on 2017-08-11. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension BigUInt { + public init?(exactly source: T) { + guard source >= (0 as T) else { return nil } + if source.bitWidth <= 2 * Word.bitWidth { + var it = source.words.makeIterator() + self.init(low: it.next() ?? 0, high: it.next() ?? 0) + precondition(it.next() == nil, "Length of BinaryInteger.words is greater than its bitWidth") + } + else { + self.init(words: source.words) + } + } + + public init(_ source: T) { + precondition(source >= (0 as T), "BigUInt cannot represent negative values") + self.init(exactly: source)! + } + + public init(truncatingIfNeeded source: T) { + self.init(words: source.words) + } + + public init(clamping source: T) { + if source <= (0 as T) { + self.init() + } + else { + self.init(words: source.words) + } + } +} + +extension BigInt { + public init() { + self.init(sign: .plus, magnitude: 0) + } + + /// Initializes a new signed big integer with the same value as the specified unsigned big integer. + public init(_ integer: BigUInt) { + self.magnitude = integer + self.sign = .plus + } + + public init(_ source: T) where T : BinaryInteger { + if source >= (0 as T) { + self.init(sign: .plus, magnitude: BigUInt(source)) + } + else { + var words = Array(source.words) + words.twosComplement() + self.init(sign: .minus, magnitude: BigUInt(words: words)) + } + } + + public init?(exactly source: T) where T : BinaryInteger { + self.init(source) + } + + public init(clamping source: T) where T : BinaryInteger { + self.init(source) + } + + public init(truncatingIfNeeded source: T) where T : BinaryInteger { + self.init(source) + } +} + +extension BigUInt: ExpressibleByIntegerLiteral { + /// Initialize a new big integer from an integer literal. + public init(integerLiteral value: UInt64) { + self.init(value) + } +} + +extension BigInt: ExpressibleByIntegerLiteral { + /// Initialize a new big integer from an integer literal. + public init(integerLiteral value: Int64) { + self.init(value) + } +} + diff --git a/Example/Web3supportBrowser/Pods/BigInt/Sources/Multiplication.swift b/Example/Web3supportBrowser/Pods/BigInt/Sources/Multiplication.swift new file mode 100644 index 000000000..635c36a5f --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/Sources/Multiplication.swift @@ -0,0 +1,165 @@ +// +// Multiplication.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension BigUInt { + + //MARK: Multiplication + + /// Multiply this big integer by a single word, and store the result in place of the original big integer. + /// + /// - Complexity: O(count) + public mutating func multiply(byWord y: Word) { + guard y != 0 else { self = 0; return } + guard y != 1 else { return } + var carry: Word = 0 + let c = self.count + for i in 0 ..< c { + let (h, l) = self[i].multipliedFullWidth(by: y) + let (low, o) = l.addingReportingOverflow(carry) + self[i] = low + carry = (o ? h + 1 : h) + } + self[c] = carry + } + + /// Multiply this big integer by a single Word, and return the result. + /// + /// - Complexity: O(count) + public func multiplied(byWord y: Word) -> BigUInt { + var r = self + r.multiply(byWord: y) + return r + } + + /// Multiply `x` by `y`, and add the result to this integer, optionally shifted `shift` words to the left. + /// + /// - Note: This is the fused multiply/shift/add operation; it is more efficient than doing the components + /// individually. (The fused operation doesn't need to allocate space for temporary big integers.) + /// - Returns: `self` is set to `self + (x * y) << (shift * 2^Word.bitWidth)` + /// - Complexity: O(count) + public mutating func multiplyAndAdd(_ x: BigUInt, _ y: Word, shiftedBy shift: Int = 0) { + precondition(shift >= 0) + guard y != 0 && x.count > 0 else { return } + guard y != 1 else { self.add(x, shiftedBy: shift); return } + var mulCarry: Word = 0 + var addCarry = false + let xc = x.count + var xi = 0 + while xi < xc || addCarry || mulCarry > 0 { + let (h, l) = x[xi].multipliedFullWidth(by: y) + let (low, o) = l.addingReportingOverflow(mulCarry) + mulCarry = (o ? h + 1 : h) + + let ai = shift + xi + let (sum1, so1) = self[ai].addingReportingOverflow(low) + if addCarry { + let (sum2, so2) = sum1.addingReportingOverflow(1) + self[ai] = sum2 + addCarry = so1 || so2 + } + else { + self[ai] = sum1 + addCarry = so1 + } + xi += 1 + } + } + + /// Multiply this integer by `y` and return the result. + /// + /// - Note: This uses the naive O(n^2) multiplication algorithm unless both arguments have more than + /// `BigUInt.directMultiplicationLimit` words. + /// - Complexity: O(n^log2(3)) + public func multiplied(by y: BigUInt) -> BigUInt { + // This method is mostly defined for symmetry with the rest of the arithmetic operations. + return self * y + } + + /// Multiplication switches to an asymptotically better recursive algorithm when arguments have more words than this limit. + public static var directMultiplicationLimit: Int = 1024 + + /// Multiply `a` by `b` and return the result. + /// + /// - Note: This uses the naive O(n^2) multiplication algorithm unless both arguments have more than + /// `BigUInt.directMultiplicationLimit` words. + /// - Complexity: O(n^log2(3)) + public static func *(x: BigUInt, y: BigUInt) -> BigUInt { + let xc = x.count + let yc = y.count + if xc == 0 { return BigUInt() } + if yc == 0 { return BigUInt() } + if yc == 1 { return x.multiplied(byWord: y[0]) } + if xc == 1 { return y.multiplied(byWord: x[0]) } + + if Swift.min(xc, yc) <= BigUInt.directMultiplicationLimit { + // Long multiplication. + let left = (xc < yc ? y : x) + let right = (xc < yc ? x : y) + var result = BigUInt() + for i in (0 ..< right.count).reversed() { + result.multiplyAndAdd(left, right[i], shiftedBy: i) + } + return result + } + + if yc < xc { + let (xh, xl) = x.split + var r = xl * y + r.add(xh * y, shiftedBy: x.middleIndex) + return r + } + else if xc < yc { + let (yh, yl) = y.split + var r = yl * x + r.add(yh * x, shiftedBy: y.middleIndex) + return r + } + + let shift = x.middleIndex + + // Karatsuba multiplication: + // x * y = * = (ignoring carry) + let (a, b) = x.split + let (c, d) = y.split + + let high = a * c + let low = b * d + let xp = a >= b + let yp = c >= d + let xm = (xp ? a - b : b - a) + let ym = (yp ? c - d : d - c) + let m = xm * ym + + var r = low + r.add(high, shiftedBy: 2 * shift) + r.add(low, shiftedBy: shift) + r.add(high, shiftedBy: shift) + if xp == yp { + r.subtract(m, shiftedBy: shift) + } + else { + r.add(m, shiftedBy: shift) + } + return r + } + + /// Multiply `a` by `b` and store the result in `a`. + public static func *=(a: inout BigUInt, b: BigUInt) { + a = a * b + } +} + +extension BigInt { + /// Multiply `a` with `b` and return the result. + public static func *(a: BigInt, b: BigInt) -> BigInt { + return BigInt(sign: a.sign == b.sign ? .plus : .minus, magnitude: a.magnitude * b.magnitude) + } + + /// Multiply `a` with `b` in place. + public static func *=(a: inout BigInt, b: BigInt) { a = a * b } +} diff --git a/Example/Web3supportBrowser/Pods/BigInt/Sources/Prime Test.swift b/Example/Web3supportBrowser/Pods/BigInt/Sources/Prime Test.swift new file mode 100644 index 000000000..7f1871104 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/Sources/Prime Test.swift @@ -0,0 +1,153 @@ +// +// Prime Test.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-04. +// Copyright © 2016-2017 Károly Lőrentey. +// + +/// The first several [prime numbers][primes]. +/// +/// [primes]: https://oeis.org/A000040 +let primes: [BigUInt.Word] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41] + +/// The ith element in this sequence is the smallest composite number that passes the strong probable prime test +/// for all of the first (i+1) primes. +/// +/// This is sequence [A014233](http://oeis.org/A014233) on the [Online Encyclopaedia of Integer Sequences](http://oeis.org). +let pseudoPrimes: [BigUInt] = [ + /* 2 */ 2_047, + /* 3 */ 1_373_653, + /* 5 */ 25_326_001, + /* 7 */ 3_215_031_751, + /* 11 */ 2_152_302_898_747, + /* 13 */ 3_474_749_660_383, + /* 17 */ 341_550_071_728_321, + /* 19 */ 341_550_071_728_321, + /* 23 */ 3_825_123_056_546_413_051, + /* 29 */ 3_825_123_056_546_413_051, + /* 31 */ 3_825_123_056_546_413_051, + /* 37 */ "318665857834031151167461", + /* 41 */ "3317044064679887385961981", +] + +extension BigUInt { + //MARK: Primality Testing + + /// Returns true iff this integer passes the [strong probable prime test][sppt] for the specified base. + /// + /// [sppt]: https://en.wikipedia.org/wiki/Probable_prime + public func isStrongProbablePrime(_ base: BigUInt) -> Bool { + precondition(base > (1 as BigUInt)) + precondition(self > (0 as BigUInt)) + let dec = self - 1 + + let r = dec.trailingZeroBitCount + let d = dec >> r + + var test = base.power(d, modulus: self) + if test == 1 || test == dec { return true } + + if r > 0 { + let shift = self.leadingZeroBitCount + let normalized = self << shift + for _ in 1 ..< r { + test *= test + test.formRemainder(dividingBy: normalized, normalizedBy: shift) + if test == 1 { + return false + } + if test == dec { return true } + } + } + return false + } + + /// Returns true if this integer is probably prime. Returns false if this integer is definitely not prime. + /// + /// This function performs a probabilistic [Miller-Rabin Primality Test][mrpt], consisting of `rounds` iterations, + /// each calculating the strong probable prime test for a random base. The number of rounds is 10 by default, + /// but you may specify your own choice. + /// + /// To speed things up, the function checks if `self` is divisible by the first few prime numbers before + /// diving into (slower) Miller-Rabin testing. + /// + /// Also, when `self` is less than 82 bits wide, `isPrime` does a deterministic test that is guaranteed to + /// return a correct result. + /// + /// [mrpt]: https://en.wikipedia.org/wiki/Miller–Rabin_primality_test + public func isPrime(rounds: Int = 10) -> Bool { + if count <= 1 && self[0] < 2 { return false } + if count == 1 && self[0] < 4 { return true } + + // Even numbers above 2 aren't prime. + if self[0] & 1 == 0 { return false } + + // Quickly check for small primes. + for i in 1 ..< primes.count { + let p = primes[i] + if self.count == 1 && self[0] == p { + return true + } + if self.quotientAndRemainder(dividingByWord: p).remainder == 0 { + return false + } + } + + /// Give an exact answer when we can. + if self < pseudoPrimes.last! { + for i in 0 ..< pseudoPrimes.count { + guard isStrongProbablePrime(BigUInt(primes[i])) else { + break + } + if self < pseudoPrimes[i] { + // `self` is below the lowest pseudoprime corresponding to the prime bases we tested. It's a prime! + return true + } + } + return false + } + + /// Otherwise do as many rounds of random SPPT as required. + for _ in 0 ..< rounds { + let random = BigUInt.randomInteger(lessThan: self - 2) + 2 + guard isStrongProbablePrime(random) else { + return false + } + } + + // Well, it smells primey to me. + return true + } +} + +extension BigInt { + //MARK: Primality Testing + + /// Returns true iff this integer passes the [strong probable prime test][sppt] for the specified base. + /// + /// [sppt]: https://en.wikipedia.org/wiki/Probable_prime + public func isStrongProbablePrime(_ base: BigInt) -> Bool { + precondition(base.sign == .plus) + if self.sign == .minus { return false } + return self.magnitude.isStrongProbablePrime(base.magnitude) + } + + /// Returns true if this integer is probably prime. Returns false if this integer is definitely not prime. + /// + /// This function performs a probabilistic [Miller-Rabin Primality Test][mrpt], consisting of `rounds` iterations, + /// each calculating the strong probable prime test for a random base. The number of rounds is 10 by default, + /// but you may specify your own choice. + /// + /// To speed things up, the function checks if `self` is divisible by the first few prime numbers before + /// diving into (slower) Miller-Rabin testing. + /// + /// Also, when `self` is less than 82 bits wide, `isPrime` does a deterministic test that is guaranteed to + /// return a correct result. + /// + /// [mrpt]: https://en.wikipedia.org/wiki/Miller–Rabin_primality_test + public func isPrime(rounds: Int = 10) -> Bool { + if self.sign == .minus { return false } + return self.magnitude.isPrime(rounds: rounds) + } +} diff --git a/Example/Web3supportBrowser/Pods/BigInt/Sources/Random.swift b/Example/Web3supportBrowser/Pods/BigInt/Sources/Random.swift new file mode 100644 index 000000000..5813b4bde --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/Sources/Random.swift @@ -0,0 +1,71 @@ +// +// Random.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-04. +// Copyright © 2016-2017 Károly Lőrentey. +// + +import Foundation +#if os(Linux) || os(FreeBSD) + import Glibc +#endif + + +extension BigUInt { + //MARK: Random Integers + + /// Create a big integer consisting of `width` uniformly distributed random bits. + /// + /// - Returns: A big integer less than `1 << width`. + /// - Note: This function uses `arc4random_buf` to generate random bits. + public static func randomInteger(withMaximumWidth width: Int) -> BigUInt { + guard width > 0 else { return 0 } + + let byteCount = (width + 7) / 8 + assert(byteCount > 0) + + let buffer = UnsafeMutablePointer.allocate(capacity: byteCount) + #if os(Linux) || os(FreeBSD) + let fd = open("/dev/urandom", O_RDONLY) + defer { + close(fd) + } + let _ = read(fd, buffer, MemoryLayout.size * byteCount) + #else + arc4random_buf(buffer, byteCount) + #endif + if width % 8 != 0 { + buffer[0] &= UInt8(1 << (width % 8) - 1) + } + defer { + buffer.deinitialize(count: byteCount) + buffer.deallocate() + } + return BigUInt(Data(bytesNoCopy: buffer, count: byteCount, deallocator: .none)) + } + + /// Create a big integer consisting of `width-1` uniformly distributed random bits followed by a one bit. + /// + /// - Returns: A random big integer whose width is `width`. + /// - Note: This function uses `arc4random_buf` to generate random bits. + public static func randomInteger(withExactWidth width: Int) -> BigUInt { + guard width > 1 else { return BigUInt(width) } + var result = randomInteger(withMaximumWidth: width - 1) + result[(width - 1) / Word.bitWidth] |= 1 << Word((width - 1) % Word.bitWidth) + return result + } + + /// Create a uniformly distributed random integer that's less than the specified limit. + /// + /// - Returns: A random big integer that is less than `limit`. + /// - Note: This function uses `arc4random_buf` to generate random bits. + public static func randomInteger(lessThan limit: BigUInt) -> BigUInt { + let width = limit.bitWidth + var random = randomInteger(withMaximumWidth: width) + while random >= limit { + random = randomInteger(withMaximumWidth: width) + } + return random + } +} diff --git a/Example/Web3supportBrowser/Pods/BigInt/Sources/Shifts.swift b/Example/Web3supportBrowser/Pods/BigInt/Sources/Shifts.swift new file mode 100644 index 000000000..e676e4143 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/Sources/Shifts.swift @@ -0,0 +1,211 @@ +// +// Shifts.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension BigUInt { + + //MARK: Shift Operators + + internal func shiftedLeft(by amount: Word) -> BigUInt { + guard amount > 0 else { return self } + + let ext = Int(amount / Word(Word.bitWidth)) // External shift amount (new words) + let up = Word(amount % Word(Word.bitWidth)) // Internal shift amount (subword shift) + let down = Word(Word.bitWidth) - up + + var result = BigUInt() + if up > 0 { + var i = 0 + var lowbits: Word = 0 + while i < self.count || lowbits > 0 { + let word = self[i] + result[i + ext] = word << up | lowbits + lowbits = word >> down + i += 1 + } + } + else { + for i in 0 ..< self.count { + result[i + ext] = self[i] + } + } + return result + } + + internal mutating func shiftLeft(by amount: Word) { + guard amount > 0 else { return } + + let ext = Int(amount / Word(Word.bitWidth)) // External shift amount (new words) + let up = Word(amount % Word(Word.bitWidth)) // Internal shift amount (subword shift) + let down = Word(Word.bitWidth) - up + + if up > 0 { + var i = 0 + var lowbits: Word = 0 + while i < self.count || lowbits > 0 { + let word = self[i] + self[i] = word << up | lowbits + lowbits = word >> down + i += 1 + } + } + if ext > 0 && self.count > 0 { + self.shiftLeft(byWords: ext) + } + } + + internal func shiftedRight(by amount: Word) -> BigUInt { + guard amount > 0 else { return self } + guard amount < self.bitWidth else { return 0 } + + let ext = Int(amount / Word(Word.bitWidth)) // External shift amount (new words) + let down = Word(amount % Word(Word.bitWidth)) // Internal shift amount (subword shift) + let up = Word(Word.bitWidth) - down + + var result = BigUInt() + if down > 0 { + var highbits: Word = 0 + for i in (ext ..< self.count).reversed() { + let word = self[i] + result[i - ext] = highbits | word >> down + highbits = word << up + } + } + else { + for i in (ext ..< self.count).reversed() { + result[i - ext] = self[i] + } + } + return result + } + + internal mutating func shiftRight(by amount: Word) { + guard amount > 0 else { return } + guard amount < self.bitWidth else { self.clear(); return } + + let ext = Int(amount / Word(Word.bitWidth)) // External shift amount (new words) + let down = Word(amount % Word(Word.bitWidth)) // Internal shift amount (subword shift) + let up = Word(Word.bitWidth) - down + + if ext > 0 { + self.shiftRight(byWords: ext) + } + if down > 0 { + var i = self.count - 1 + var highbits: Word = 0 + while i >= 0 { + let word = self[i] + self[i] = highbits | word >> down + highbits = word << up + i -= 1 + } + } + } + + public static func >>=(lhs: inout BigUInt, rhs: Other) { + if rhs < (0 as Other) { + lhs <<= (0 - rhs) + } + else if rhs >= lhs.bitWidth { + lhs.clear() + } + else { + lhs.shiftRight(by: UInt(rhs)) + } + } + + public static func <<=(lhs: inout BigUInt, rhs: Other) { + if rhs < (0 as Other) { + lhs >>= (0 - rhs) + return + } + lhs.shiftLeft(by: Word(exactly: rhs)!) + } + + public static func >>(lhs: BigUInt, rhs: Other) -> BigUInt { + if rhs < (0 as Other) { + return lhs << (0 - rhs) + } + if rhs > Word.max { + return 0 + } + return lhs.shiftedRight(by: UInt(rhs)) + } + + public static func <<(lhs: BigUInt, rhs: Other) -> BigUInt { + if rhs < (0 as Other) { + return lhs >> (0 - rhs) + } + return lhs.shiftedLeft(by: Word(exactly: rhs)!) + } +} + +extension BigInt { + func shiftedLeft(by amount: Word) -> BigInt { + return BigInt(sign: self.sign, magnitude: self.magnitude.shiftedLeft(by: amount)) + } + + mutating func shiftLeft(by amount: Word) { + self.magnitude.shiftLeft(by: amount) + } + + func shiftedRight(by amount: Word) -> BigInt { + let m = self.magnitude.shiftedRight(by: amount) + return BigInt(sign: self.sign, magnitude: self.sign == .minus && m.isZero ? 1 : m) + } + + mutating func shiftRight(by amount: Word) { + magnitude.shiftRight(by: amount) + if sign == .minus, magnitude.isZero { + magnitude.load(1) + } + } + + public static func &<<(left: BigInt, right: BigInt) -> BigInt { + return left.shiftedLeft(by: right.words[0]) + } + + public static func &<<=(left: inout BigInt, right: BigInt) { + left.shiftLeft(by: right.words[0]) + } + + public static func &>>(left: BigInt, right: BigInt) -> BigInt { + return left.shiftedRight(by: right.words[0]) + } + + public static func &>>=(left: inout BigInt, right: BigInt) { + left.shiftRight(by: right.words[0]) + } + + public static func <<(lhs: BigInt, rhs: Other) -> BigInt { + guard rhs >= (0 as Other) else { return lhs >> (0 - rhs) } + return lhs.shiftedLeft(by: Word(rhs)) + } + + public static func <<=(lhs: inout BigInt, rhs: Other) { + if rhs < (0 as Other) { + lhs >>= (0 - rhs) + } + else { + lhs.shiftLeft(by: Word(rhs)) + } + } + + public static func >>(lhs: BigInt, rhs: Other) -> BigInt { + guard rhs >= (0 as Other) else { return lhs << (0 - rhs) } + return lhs.shiftedRight(by: Word(rhs)) + } + + public static func >>=(lhs: inout BigInt, rhs: Other) { + if rhs < (0 as Other) { + lhs <<= (0 - rhs) + } + else { + lhs.shiftRight(by: Word(rhs)) + } + } +} diff --git a/Example/Web3supportBrowser/Pods/BigInt/Sources/Square Root.swift b/Example/Web3supportBrowser/Pods/BigInt/Sources/Square Root.swift new file mode 100644 index 000000000..68db0691c --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/Sources/Square Root.swift @@ -0,0 +1,41 @@ +// +// Square Root.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +//MARK: Square Root + +extension BigUInt { + /// Returns the integer square root of a big integer; i.e., the largest integer whose square isn't greater than `value`. + /// + /// - Returns: floor(sqrt(self)) + public func squareRoot() -> BigUInt { + // This implementation uses Newton's method. + guard !self.isZero else { return BigUInt() } + var x = BigUInt(1) << ((self.bitWidth + 1) / 2) + var y: BigUInt = 0 + while true { + y.load(self) + y /= x + y += x + y >>= 1 + if x == y || x == y - 1 { break } + x = y + } + return x + } +} + +extension BigInt { + /// Returns the integer square root of a big integer; i.e., the largest integer whose square isn't greater than `value`. + /// + /// - Requires: self >= 0 + /// - Returns: floor(sqrt(self)) + public func squareRoot() -> BigInt { + precondition(self.sign == .plus) + return BigInt(sign: .plus, magnitude: self.magnitude.squareRoot()) + } +} diff --git a/Example/Web3supportBrowser/Pods/BigInt/Sources/Strideable.swift b/Example/Web3supportBrowser/Pods/BigInt/Sources/Strideable.swift new file mode 100644 index 000000000..2b79babd1 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/Sources/Strideable.swift @@ -0,0 +1,38 @@ +// +// Strideable.swift +// BigInt +// +// Created by Károly Lőrentey on 2017-08-11. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension BigUInt: Strideable { + /// A type that can represent the distance between two values ofa `BigUInt`. + public typealias Stride = BigInt + + /// Adds `n` to `self` and returns the result. Traps if the result would be less than zero. + public func advanced(by n: BigInt) -> BigUInt { + return n.sign == .minus ? self - n.magnitude : self + n.magnitude + } + + /// Returns the (potentially negative) difference between `self` and `other` as a `BigInt`. Never traps. + public func distance(to other: BigUInt) -> BigInt { + return BigInt(other) - BigInt(self) + } +} + +extension BigInt: Strideable { + public typealias Stride = BigInt + + /// Returns `self + n`. + public func advanced(by n: Stride) -> BigInt { + return self + n + } + + /// Returns `other - self`. + public func distance(to other: BigInt) -> Stride { + return other - self + } +} + + diff --git a/Example/Web3supportBrowser/Pods/BigInt/Sources/String Conversion.swift b/Example/Web3supportBrowser/Pods/BigInt/Sources/String Conversion.swift new file mode 100644 index 000000000..d6f340c93 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/Sources/String Conversion.swift @@ -0,0 +1,236 @@ +// +// String Conversion.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension BigUInt { + + //MARK: String Conversion + + /// Calculates the number of numerals in a given radix that fit inside a single `Word`. + /// + /// - Returns: (chars, power) where `chars` is highest that satisfy `radix^chars <= 2^Word.bitWidth`. `power` is zero + /// if radix is a power of two; otherwise `power == radix^chars`. + fileprivate static func charsPerWord(forRadix radix: Int) -> (chars: Int, power: Word) { + var power: Word = 1 + var overflow = false + var count = 0 + while !overflow { + let (p, o) = power.multipliedReportingOverflow(by: Word(radix)) + overflow = o + if !o || p == 0 { + count += 1 + power = p + } + } + return (count, power) + } + + /// Initialize a big integer from an ASCII representation in a given radix. Numerals above `9` are represented by + /// letters from the English alphabet. + /// + /// - Requires: `radix > 1 && radix < 36` + /// - Parameter `text`: A string consisting of characters corresponding to numerals in the given radix. (0-9, a-z, A-Z) + /// - Parameter `radix`: The base of the number system to use, or 10 if unspecified. + /// - Returns: The integer represented by `text`, or nil if `text` contains a character that does not represent a numeral in `radix`. + public init?(_ text: S, radix: Int = 10) { + precondition(radix > 1) + let (charsPerWord, power) = BigUInt.charsPerWord(forRadix: radix) + + var words: [Word] = [] + var end = text.endIndex + var start = end + var count = 0 + while start != text.startIndex { + start = text.index(before: start) + count += 1 + if count == charsPerWord { + guard let d = Word.init(text[start ..< end], radix: radix) else { return nil } + words.append(d) + end = start + count = 0 + } + } + if start != end { + guard let d = Word.init(text[start ..< end], radix: radix) else { return nil } + words.append(d) + } + + if power == 0 { + self.init(words: words) + } + else { + self.init() + for d in words.reversed() { + self.multiply(byWord: power) + self.addWord(d) + } + } + } +} + +extension BigInt { + /// Initialize a big integer from an ASCII representation in a given radix. Numerals above `9` are represented by + /// letters from the English alphabet. + /// + /// - Requires: `radix > 1 && radix < 36` + /// - Parameter `text`: A string optionally starting with "-" or "+" followed by characters corresponding to numerals in the given radix. (0-9, a-z, A-Z) + /// - Parameter `radix`: The base of the number system to use, or 10 if unspecified. + /// - Returns: The integer represented by `text`, or nil if `text` contains a character that does not represent a numeral in `radix`. + public init?(_ text: S, radix: Int = 10) { + var magnitude: BigUInt? + var sign: Sign = .plus + if text.first == "-" { + sign = .minus + let text = text.dropFirst() + magnitude = BigUInt(text, radix: radix) + } + else if text.first == "+" { + let text = text.dropFirst() + magnitude = BigUInt(text, radix: radix) + } + else { + magnitude = BigUInt(text, radix: radix) + } + guard let m = magnitude else { return nil } + self.magnitude = m + self.sign = sign + } +} + +extension String { + /// Initialize a new string with the base-10 representation of an unsigned big integer. + /// + /// - Complexity: O(v.count^2) + public init(_ v: BigUInt) { self.init(v, radix: 10, uppercase: false) } + + /// Initialize a new string representing an unsigned big integer in the given radix (base). + /// + /// Numerals greater than 9 are represented as letters from the English alphabet, + /// starting with `a` if `uppercase` is false or `A` otherwise. + /// + /// - Requires: radix > 1 && radix <= 36 + /// - Complexity: O(count) when radix is a power of two; otherwise O(count^2). + public init(_ v: BigUInt, radix: Int, uppercase: Bool = false) { + precondition(radix > 1) + let (charsPerWord, power) = BigUInt.charsPerWord(forRadix: radix) + + guard !v.isZero else { self = "0"; return } + + var parts: [String] + if power == 0 { + parts = v.words.map { String($0, radix: radix, uppercase: uppercase) } + } + else { + parts = [] + var rest = v + while !rest.isZero { + let mod = rest.divide(byWord: power) + parts.append(String(mod, radix: radix, uppercase: uppercase)) + } + } + assert(!parts.isEmpty) + + self = "" + var first = true + for part in parts.reversed() { + let zeroes = charsPerWord - part.count + assert(zeroes >= 0) + if !first && zeroes > 0 { + // Insert leading zeroes for mid-Words + self += String(repeating: "0", count: zeroes) + } + first = false + self += part + } + } + + /// Initialize a new string representing a signed big integer in the given radix (base). + /// + /// Numerals greater than 9 are represented as letters from the English alphabet, + /// starting with `a` if `uppercase` is false or `A` otherwise. + /// + /// - Requires: radix > 1 && radix <= 36 + /// - Complexity: O(count) when radix is a power of two; otherwise O(count^2). + public init(_ value: BigInt, radix: Int = 10, uppercase: Bool = false) { + self = String(value.magnitude, radix: radix, uppercase: uppercase) + if value.sign == .minus { + self = "-" + self + } + } +} + +extension BigUInt: ExpressibleByStringLiteral { + /// Initialize a new big integer from a Unicode scalar. + /// The scalar must represent a decimal digit. + public init(unicodeScalarLiteral value: UnicodeScalar) { + self = BigUInt(String(value), radix: 10)! + } + + /// Initialize a new big integer from an extended grapheme cluster. + /// The cluster must consist of a decimal digit. + public init(extendedGraphemeClusterLiteral value: String) { + self = BigUInt(value, radix: 10)! + } + + /// Initialize a new big integer from a decimal number represented by a string literal of arbitrary length. + /// The string must contain only decimal digits. + public init(stringLiteral value: StringLiteralType) { + self = BigUInt(value, radix: 10)! + } +} + +extension BigInt: ExpressibleByStringLiteral { + /// Initialize a new big integer from a Unicode scalar. + /// The scalar must represent a decimal digit. + public init(unicodeScalarLiteral value: UnicodeScalar) { + self = BigInt(String(value), radix: 10)! + } + + /// Initialize a new big integer from an extended grapheme cluster. + /// The cluster must consist of a decimal digit. + public init(extendedGraphemeClusterLiteral value: String) { + self = BigInt(value, radix: 10)! + } + + /// Initialize a new big integer from a decimal number represented by a string literal of arbitrary length. + /// The string must contain only decimal digits. + public init(stringLiteral value: StringLiteralType) { + self = BigInt(value, radix: 10)! + } +} + +extension BigUInt: CustomStringConvertible { + /// Return the decimal representation of this integer. + public var description: String { + return String(self, radix: 10) + } +} + +extension BigInt: CustomStringConvertible { + /// Return the decimal representation of this integer. + public var description: String { + return String(self, radix: 10) + } +} + +extension BigUInt: CustomPlaygroundDisplayConvertible { + + /// Return the playground quick look representation of this integer. + public var playgroundDescription: Any { + let text = String(self) + return text + " (\(self.bitWidth) bits)" + } +} + +extension BigInt: CustomPlaygroundDisplayConvertible { + + /// Return the playground quick look representation of this integer. + public var playgroundDescription: Any { + let text = String(self) + return text + " (\(self.magnitude.bitWidth) bits)" + } +} diff --git a/Example/Web3supportBrowser/Pods/BigInt/Sources/Subtraction.swift b/Example/Web3supportBrowser/Pods/BigInt/Sources/Subtraction.swift new file mode 100644 index 000000000..5ac872e65 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/Sources/Subtraction.swift @@ -0,0 +1,169 @@ +// +// Subtraction.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension BigUInt { + //MARK: Subtraction + + /// Subtract `word` from this integer in place, returning a flag indicating if the operation + /// caused an arithmetic overflow. `word` is shifted `shift` words to the left before being subtracted. + /// + /// - Note: If the result indicates an overflow, then `self` becomes the two's complement of the absolute difference. + /// - Complexity: O(count) + internal mutating func subtractWordReportingOverflow(_ word: Word, shiftedBy shift: Int = 0) -> Bool { + precondition(shift >= 0) + var carry: Word = word + var i = shift + let count = self.count + while carry > 0 && i < count { + let (d, c) = self[i].subtractingReportingOverflow(carry) + self[i] = d + carry = (c ? 1 : 0) + i += 1 + } + return carry > 0 + } + + /// Subtract `word` from this integer, returning the difference and a flag that is true if the operation + /// caused an arithmetic overflow. `word` is shifted `shift` words to the left before being subtracted. + /// + /// - Note: If `overflow` is true, then the returned value is the two's complement of the absolute difference. + /// - Complexity: O(count) + internal func subtractingWordReportingOverflow(_ word: Word, shiftedBy shift: Int = 0) -> (partialValue: BigUInt, overflow: Bool) { + var result = self + let overflow = result.subtractWordReportingOverflow(word, shiftedBy: shift) + return (result, overflow) + } + + /// Subtract a digit `d` from this integer in place. + /// `d` is shifted `shift` digits to the left before being subtracted. + /// + /// - Requires: self >= d * 2^shift + /// - Complexity: O(count) + internal mutating func subtractWord(_ word: Word, shiftedBy shift: Int = 0) { + let overflow = subtractWordReportingOverflow(word, shiftedBy: shift) + precondition(!overflow) + } + + /// Subtract a digit `d` from this integer and return the result. + /// `d` is shifted `shift` digits to the left before being subtracted. + /// + /// - Requires: self >= d * 2^shift + /// - Complexity: O(count) + internal func subtractingWord(_ word: Word, shiftedBy shift: Int = 0) -> BigUInt { + var result = self + result.subtractWord(word, shiftedBy: shift) + return result + } + + /// Subtract `other` from this integer in place, and return a flag indicating if the operation caused an + /// arithmetic overflow. `other` is shifted `shift` digits to the left before being subtracted. + /// + /// - Note: If the result indicates an overflow, then `self` becomes the twos' complement of the absolute difference. + /// - Complexity: O(count) + public mutating func subtractReportingOverflow(_ b: BigUInt, shiftedBy shift: Int = 0) -> Bool { + precondition(shift >= 0) + var carry = false + var bi = 0 + let bc = b.count + let count = self.count + while bi < bc || (shift + bi < count && carry) { + let ai = shift + bi + let (d, c) = self[ai].subtractingReportingOverflow(b[bi]) + if carry { + let (d2, c2) = d.subtractingReportingOverflow(1) + self[ai] = d2 + carry = c || c2 + } + else { + self[ai] = d + carry = c + } + bi += 1 + } + return carry + } + + /// Subtract `other` from this integer, returning the difference and a flag indicating arithmetic overflow. + /// `other` is shifted `shift` digits to the left before being subtracted. + /// + /// - Note: If `overflow` is true, then the result value is the twos' complement of the absolute value of the difference. + /// - Complexity: O(count) + public func subtractingReportingOverflow(_ other: BigUInt, shiftedBy shift: Int) -> (partialValue: BigUInt, overflow: Bool) { + var result = self + let overflow = result.subtractReportingOverflow(other, shiftedBy: shift) + return (result, overflow) + } + + /// Subtracts `other` from `self`, returning the result and a flag indicating arithmetic overflow. + /// + /// - Note: When the operation overflows, then `partialValue` is the twos' complement of the absolute value of the difference. + /// - Complexity: O(count) + public func subtractingReportingOverflow(_ other: BigUInt) -> (partialValue: BigUInt, overflow: Bool) { + return self.subtractingReportingOverflow(other, shiftedBy: 0) + } + + /// Subtract `other` from this integer in place. + /// `other` is shifted `shift` digits to the left before being subtracted. + /// + /// - Requires: self >= other * 2^shift + /// - Complexity: O(count) + public mutating func subtract(_ other: BigUInt, shiftedBy shift: Int = 0) { + let overflow = subtractReportingOverflow(other, shiftedBy: shift) + precondition(!overflow) + } + + /// Subtract `b` from this integer, and return the difference. + /// `b` is shifted `shift` digits to the left before being subtracted. + /// + /// - Requires: self >= b * 2^shift + /// - Complexity: O(count) + public func subtracting(_ other: BigUInt, shiftedBy shift: Int = 0) -> BigUInt { + var result = self + result.subtract(other, shiftedBy: shift) + return result + } + + /// Decrement this integer by one. + /// + /// - Requires: !isZero + /// - Complexity: O(count) + public mutating func decrement(shiftedBy shift: Int = 0) { + self.subtract(1, shiftedBy: shift) + } + + /// Subtract `b` from `a` and return the result. + /// + /// - Requires: a >= b + /// - Complexity: O(a.count) + public static func -(a: BigUInt, b: BigUInt) -> BigUInt { + return a.subtracting(b) + } + + /// Subtract `b` from `a` and store the result in `a`. + /// + /// - Requires: a >= b + /// - Complexity: O(a.count) + public static func -=(a: inout BigUInt, b: BigUInt) { + a.subtract(b) + } +} + +extension BigInt { + public mutating func negate() { + guard !magnitude.isZero else { return } + self.sign = self.sign == .plus ? .minus : .plus + } + + /// Subtract `b` from `a` and return the result. + public static func -(a: BigInt, b: BigInt) -> BigInt { + return a + -b + } + + /// Subtract `b` from `a` in place. + public static func -=(a: inout BigInt, b: BigInt) { a = a - b } +} diff --git a/Example/Web3supportBrowser/Pods/BigInt/Sources/Words and Bits.swift b/Example/Web3supportBrowser/Pods/BigInt/Sources/Words and Bits.swift new file mode 100644 index 000000000..040accdde --- /dev/null +++ b/Example/Web3supportBrowser/Pods/BigInt/Sources/Words and Bits.swift @@ -0,0 +1,202 @@ +// +// Words and Bits.swift +// BigInt +// +// Created by Károly Lőrentey on 2017-08-11. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension Array where Element == UInt { + mutating func twosComplement() { + var increment = true + for i in 0 ..< self.count { + if increment { + (self[i], increment) = (~self[i]).addingReportingOverflow(1) + } + else { + self[i] = ~self[i] + } + } + } +} + +extension BigUInt { + public subscript(bitAt index: Int) -> Bool { + get { + precondition(index >= 0) + let (i, j) = index.quotientAndRemainder(dividingBy: Word.bitWidth) + return self[i] & (1 << j) != 0 + } + set { + precondition(index >= 0) + let (i, j) = index.quotientAndRemainder(dividingBy: Word.bitWidth) + if newValue { + self[i] |= 1 << j + } + else { + self[i] &= ~(1 << j) + } + } + } +} + +extension BigUInt { + /// The minimum number of bits required to represent this integer in binary. + /// + /// - Returns: floor(log2(2 * self + 1)) + /// - Complexity: O(1) + public var bitWidth: Int { + guard count > 0 else { return 0 } + return count * Word.bitWidth - self[count - 1].leadingZeroBitCount + } + + /// The number of leading zero bits in the binary representation of this integer in base `2^(Word.bitWidth)`. + /// This is useful when you need to normalize a `BigUInt` such that the top bit of its most significant word is 1. + /// + /// - Note: 0 is considered to have zero leading zero bits. + /// - Returns: A value in `0...(Word.bitWidth - 1)`. + /// - SeeAlso: width + /// - Complexity: O(1) + public var leadingZeroBitCount: Int { + guard count > 0 else { return 0 } + return self[count - 1].leadingZeroBitCount + } + + /// The number of trailing zero bits in the binary representation of this integer. + /// + /// - Note: 0 is considered to have zero trailing zero bits. + /// - Returns: A value in `0...width`. + /// - Complexity: O(count) + public var trailingZeroBitCount: Int { + guard count > 0 else { return 0 } + let i = self.words.index { $0 != 0 }! + return i * Word.bitWidth + self[i].trailingZeroBitCount + } +} + +extension BigInt { + public var bitWidth: Int { + guard !magnitude.isZero else { return 0 } + return magnitude.bitWidth + 1 + } + + public var trailingZeroBitCount: Int { + // Amazingly, this works fine for negative numbers + return magnitude.trailingZeroBitCount + } +} + +extension BigUInt { + public struct Words: RandomAccessCollection { + private let value: BigUInt + + fileprivate init(_ value: BigUInt) { self.value = value } + + public var startIndex: Int { return 0 } + public var endIndex: Int { return value.count } + + public subscript(_ index: Int) -> Word { + return value[index] + } + } + + public var words: Words { return Words(self) } + + public init(words: Words) where Words.Element == Word { + let uc = words.underestimatedCount + if uc > 2 { + self.init(words: Array(words)) + } + else { + var it = words.makeIterator() + guard let w0 = it.next() else { + self.init() + return + } + guard let w1 = it.next() else { + self.init(word: w0) + return + } + if let w2 = it.next() { + var words: [UInt] = [] + words.reserveCapacity(Swift.max(3, uc)) + words.append(w0) + words.append(w1) + words.append(w2) + while let word = it.next() { + words.append(word) + } + self.init(words: words) + } + else { + self.init(low: w0, high: w1) + } + } + } +} + +extension BigInt { + public struct Words: RandomAccessCollection { + public typealias Indices = CountableRange + + private let value: BigInt + private let decrementLimit: Int + + fileprivate init(_ value: BigInt) { + self.value = value + switch value.sign { + case .plus: + self.decrementLimit = 0 + case .minus: + assert(!value.magnitude.isZero) + self.decrementLimit = value.magnitude.words.index(where: { $0 != 0 })! + } + } + + public var count: Int { + switch value.sign { + case .plus: + if let high = value.magnitude.words.last, high >> (Word.bitWidth - 1) != 0 { + return value.magnitude.count + 1 + } + return value.magnitude.count + case .minus: + let high = value.magnitude.words.last! + if high >> (Word.bitWidth - 1) != 0 { + return value.magnitude.count + 1 + } + return value.magnitude.count + } + } + + public var indices: Indices { return 0 ..< count } + public var startIndex: Int { return 0 } + public var endIndex: Int { return count } + + public subscript(_ index: Int) -> UInt { + // Note that indices above `endIndex` are accepted. + if value.sign == .plus { + return value.magnitude[index] + } + if index <= decrementLimit { + return ~(value.magnitude[index] &- 1) + } + return ~value.magnitude[index] + } + } + + public var words: Words { + return Words(self) + } + + public init(words: S) where S.Element == Word { + var words = Array(words) + if (words.last ?? 0) >> (Word.bitWidth - 1) == 0 { + self.init(sign: .plus, magnitude: BigUInt(words: words)) + } + else { + words.twosComplement() + self.init(sign: .minus, magnitude: BigUInt(words: words)) + } + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/LICENSE b/Example/Web3supportBrowser/Pods/CryptoSwift/LICENSE new file mode 100644 index 000000000..b70d6de9a --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/LICENSE @@ -0,0 +1,11 @@ +Copyright (C) 2014-2017 Marcin Krzyżanowski +This software is provided 'as-is', without any express or implied warranty. + +In no event will the authors be held liable for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: + +- The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +- Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +- This notice may not be removed or altered from any source or binary distribution. +- Redistributions of any form whatsoever must retain the following acknowledgment: 'This product includes software developed by the "Marcin Krzyzanowski" (http://krzyzanowskim.com/).' \ No newline at end of file diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/README.md b/Example/Web3supportBrowser/Pods/CryptoSwift/README.md new file mode 100644 index 000000000..a239407d7 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/README.md @@ -0,0 +1,527 @@ +[![Platform](https://img.shields.io/badge/Platforms-iOS%20%7C%20Android%20%7CmacOS%20%7C%20watchOS%20%7C%20tvOS%20%7C%20Linux-4E4E4E.svg?colorA=28a745)](#installation) + +[![Swift support](https://img.shields.io/badge/Swift-3.1%20%7C%203.2%20%7C%204.0%20%7C%204.1%20%7C%204.2%20%7C%205.0-lightgrey.svg?colorA=28a745&colorB=4E4E4E)](#swift-versions-support) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/CryptoSwift.svg?style=flat&label=CocoaPods&colorA=28a745&&colorB=4E4E4E)](https://cocoapods.org/pods/CryptoSwift) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-brightgreen.svg?style=flat&colorA=28a745&&colorB=4E4E4E)](https://github.com/Carthage/Carthage) +[![Swift Package Manager compatible](https://img.shields.io/badge/SPM-compatible-brightgreen.svg?style=flat&colorA=28a745&&colorB=4E4E4E)](https://github.com/apple/swift-package-manager) + +[![Twitter](https://img.shields.io/badge/Twitter-@krzyzanowskim-blue.svg?style=flat)](http://twitter.com/krzyzanowskim) + +# CryptoSwift + +Crypto related functions and helpers for [Swift](https://swift.org) implemented in Swift. ([#PureSwift](https://twitter.com/hashtag/pureswift)) + +**Note**: The `master` branch follows the latest currently released **version of Swift**. If you need an earlier version for an older version of Swift, you can specify its version in your Podfile or use the code on the branch for that version. Older branches are unsupported. Check [versions](#swift-versions-support) for details. + +--- + +If you find the project useful, please [support authors](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=92Z6U3LBHF9J4) to keep it alive. + +--- + +[Requirements](#requirements) +| [Features](#features) +| [Contribution](#contribution) +| [Installation](#installation) +| [Swift versions](#swift-versions-support) +| [How-to](#how-to) +| [Author](#author) +| [License](#license) +| [Changelog](#changelog) + +## Requirements +Good mood + +## Features + +- Easy to use +- Convenient extensions for String and Data +- Support for incremental updates (stream, ...) +- iOS, Android, macOS, AppleTV, watchOS, Linux support + +#### Hash (Digest) + [MD5](http://tools.ietf.org/html/rfc1321) +| [SHA1](http://tools.ietf.org/html/rfc3174) +| [SHA224](http://tools.ietf.org/html/rfc6234) +| [SHA256](http://tools.ietf.org/html/rfc6234) +| [SHA384](http://tools.ietf.org/html/rfc6234) +| [SHA512](http://tools.ietf.org/html/rfc6234) +| [SHA3](http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf) + +#### Cyclic Redundancy Check (CRC) + [CRC32](http://en.wikipedia.org/wiki/Cyclic_redundancy_check) +| [CRC32C](http://en.wikipedia.org/wiki/Cyclic_redundancy_check) +| [CRC16](http://en.wikipedia.org/wiki/Cyclic_redundancy_check) + +#### Cipher + [AES-128, AES-192, AES-256](http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf) +| [ChaCha20](http://cr.yp.to/chacha/chacha-20080128.pdf) +| [Rabbit](https://tools.ietf.org/html/rfc4503) +| [Blowfish](https://www.schneier.com/academic/blowfish/) + +#### Message authenticators + [Poly1305](http://cr.yp.to/mac/poly1305-20050329.pdf) +| [HMAC (MD5, SHA1, SHA256)](https://www.ietf.org/rfc/rfc2104.txt) +| [CMAC](https://tools.ietf.org/html/rfc4493) +| [CBC-MAC](https://en.wikipedia.org/wiki/CBC-MAC) + +#### Cipher mode of operation +- Electronic codebook ([ECB](http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_codebook_.28ECB.29)) +- Cipher-block chaining ([CBC](http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher-block_chaining_.28CBC.29)) +- Propagating Cipher Block Chaining ([PCBC](http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Propagating_Cipher_Block_Chaining_.28PCBC.29)) +- Cipher feedback ([CFB](http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_feedback_.28CFB.29)) +- Output Feedback ([OFB](http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Output_Feedback_.28OFB.29)) +- Counter Mode ([CTR](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_.28CTR.29)) +- Galois/Counter Mode ([GCM](https://csrc.nist.gov/publications/detail/sp/800-38d/final)) +- Counter with Cipher Block Chaining-Message Authentication Code ([CCM](https://csrc.nist.gov/publications/detail/sp/800-38c/final)) + +#### Password-Based Key Derivation Function +- [PBKDF1](http://tools.ietf.org/html/rfc2898#section-5.1) (Password-Based Key Derivation Function 1) +- [PBKDF2](http://tools.ietf.org/html/rfc2898#section-5.2) (Password-Based Key Derivation Function 2) +- [HKDF](https://tools.ietf.org/html/rfc5869) (HMAC-based Extract-and-Expand Key Derivation Function) +- [Scrypt](https://tools.ietf.org/html/rfc7914) (The scrypt Password-Based Key Derivation Function) + +#### Data padding + PKCS#5 +| [PKCS#7](http://tools.ietf.org/html/rfc5652#section-6.3) +| [Zero padding](https://en.wikipedia.org/wiki/Padding_(cryptography)#Zero_padding) +| No padding + +#### Authenticated Encryption with Associated Data (AEAD) +- [AEAD\_CHACHA20\_POLY1305](https://tools.ietf.org/html/rfc7539#section-2.8) + +## Why +[Why?](https://github.com/krzyzanowskim/CryptoSwift/issues/5) [Because I can](https://github.com/krzyzanowskim/CryptoSwift/issues/5#issuecomment-53379391). + +## How do I get involved? + +You want to help, great! Go ahead and fork our repo, make your changes and send us a pull request. + +## Contribution + +Check out [CONTRIBUTING.md](CONTRIBUTING.md) for more information on how to help with CryptoSwift. + +- If you found a bug, [open an issue](https://github.com/krzyzanowskim/CryptoSwift/issues). +- If you have a feature request, [open an issue](https://github.com/krzyzanowskim/CryptoSwift/issues). + +## Installation + +To install CryptoSwift, add it as a submodule to your project (on the top level project directory): + + git submodule add https://github.com/krzyzanowskim/CryptoSwift.git + +It is recommended to enable [Whole-Module Optimization](https://swift.org/blog/whole-module-optimizations/) to gain better performance. Non-optimized build results in significantly worse performance. + +#### Embedded Framework + +Embedded frameworks require a minimum deployment target of iOS 8 or OS X Mavericks (10.9). Drag the `CryptoSwift.xcodeproj` file into your Xcode project, and add appropriate framework as a dependency to your target. Now select your App and choose the General tab for the app target. Find *Embedded Binaries* and press "+", then select `CryptoSwift.framework` (iOS, OS X, watchOS or tvOS) + +![](https://cloud.githubusercontent.com/assets/758033/10834511/25a26852-7e9a-11e5-8c01-6cc8f1838459.png) + +Sometimes "embedded framework" option is not available. In that case, you have to add new build phase for the target + +![](https://cloud.githubusercontent.com/assets/758033/18415615/d5edabb0-77f8-11e6-8c94-f41d9fc2b8cb.png) + +##### iOS, macOS, watchOS, tvOS + +In the project, you'll find [single scheme](http://promisekit.org/news/2016/08/Multiplatform-Single-Scheme-Xcode-Projects/) for all platforms: +- CryptoSwift + +#### Swift versions support + +- Swift 1.2: branch [swift12](https://github.com/krzyzanowskim/CryptoSwift/tree/swift12) version <= 0.0.13 +- Swift 2.1: branch [swift21](https://github.com/krzyzanowskim/CryptoSwift/tree/swift21) version <= 0.2.3 +- Swift 2.2, 2.3: branch [swift2](https://github.com/krzyzanowskim/CryptoSwift/tree/swift2) version <= 0.5.2 +- Swift 3.1, branch [swift3](https://github.com/krzyzanowskim/CryptoSwift/tree/swift3) version <= 0.6.9 +- Swift 3.2, branch [swift32](https://github.com/krzyzanowskim/CryptoSwift/tree/swift32) version = 0.7.0 +- Swift 4.0, branch [swift4](https://github.com/krzyzanowskim/CryptoSwift/tree/swift4) version <= 0.12.0 +- Swift 4.2, branch [swift42](https://github.com/krzyzanowskim/CryptoSwift/tree/swift42) version <= 0.15.0 +- Swift 5.0, branch [master](https://github.com/krzyzanowskim/CryptoSwift/tree/master) + +#### CocoaPods + +You can use [CocoaPods](http://cocoapods.org/?q=cryptoSwift). + +```ruby +platform :ios, '10.0' +use_frameworks! + +target 'MyApp' do + pod 'CryptoSwift' +end +``` + +or for newest version from specified branch of code: + +```ruby +pod 'CryptoSwift', :git => "https://github.com/krzyzanowskim/CryptoSwift", :branch => "master" +``` + +Bear in mind that CocoaPods will build CryptoSwift without [Whole-Module Optimization](https://swift.org/blog/whole-module-optimizations/) that may impact performance. You can change it manually after installation, or use [cocoapods-wholemodule](https://github.com/jedlewison/cocoapods-wholemodule) plugin. + +#### Carthage +You can use [Carthage](https://github.com/Carthage/Carthage). +Specify in Cartfile: + +```ruby +github "krzyzanowskim/CryptoSwift" +``` + +Run `carthage` to build the framework and drag the built CryptoSwift.framework into your Xcode project. Follow [build instructions](https://github.com/Carthage/Carthage#getting-started). [Common issues](https://github.com/krzyzanowskim/CryptoSwift/issues/492#issuecomment-330822874). + +#### Swift Package Manager + +You can use [Swift Package Manager](https://swift.org/package-manager/) and specify dependency in `Package.swift` by adding this: + +```swift +dependencies: [ + .package(url: "https://github.com/krzyzanowskim/CryptoSwift.git", .upToNextMinor(from: "1.0.0")) +] +``` + +or more strict + +```swift +dependencies: [ + .package(url: "https://github.com/krzyzanowskim/CryptoSwift.git", .exact("1.0.0")) +] +``` + +See: [Package.swift - manual](http://blog.krzyzanowskim.com/2016/08/09/package-swift-manual/) + +--- + +## How-to + +* [Basics (data types, conversion, ...)](#basics) +* [Digest (MD5, SHA...)](#calculate-digest) +* [Message authenticators (HMAC, CMAC...)](#message-authenticators-1) +* [Password-Based Key Derivation Function (PBKDF2, ...)](#password-based-key-derivation-functions) +* [HMAC-based Key Derivation Function (HKDF)](#hmac-based-key-derivation-function) +* [Data Padding](#data-padding) +* [ChaCha20](#chacha20) +* [Rabbit](#rabbit) +* [Blowfish](#blowfish) +* [AES - Advanced Encryption Standard](#aes) +* [AES-GCM](#aes-gcm) +* [Authenticated Encryption with Associated Data (AEAD)](#aead) + +also check [Playground](/CryptoSwift.playground/Contents.swift) + +##### Basics + +```swift +import CryptoSwift +``` + +CryptoSwift uses array of bytes aka `Array` as a base type for all operations. Every data may be converted to a stream of bytes. You will find convenience functions that accept `String` or `Data`, and it will be internally converted to the array of bytes. + +##### Data types conversion + +For your convenience, **CryptoSwift** provides two functions to easily convert an array of bytes to `Data` or `Data` to an array of bytes: + +Data from bytes: + +```swift +let data = Data( [0x01, 0x02, 0x03]) +``` + +`Data` to `Array` + +```swift +let bytes = data.bytes // [1,2,3] +``` + +[Hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal) encoding: + +```swift +let bytes = Array(hex: "0x010203") // [1,2,3] +let hex = bytes.toHexString() // "010203" +``` + +Build bytes out of `String` +```swift +let bytes: Array = "cipherkey".bytes // Array("cipherkey".utf8) +``` + +Also... check out helpers that work with **Base64** encoded data: +```swift +"aPf/i9th9iX+vf49eR7PYk2q7S5xmm3jkRLejgzHNJs=".decryptBase64ToString(cipher) +"aPf/i9th9iX+vf49eR7PYk2q7S5xmm3jkRLejgzHNJs=".decryptBase64(cipher) +bytes.toBase64() +``` + +##### Calculate Digest + +Hashing a data or array of bytes (aka `Array`) +```swift +/* Hash struct usage */ +let bytes:Array = [0x01, 0x02, 0x03] +let digest = input.md5() +let digest = Digest.md5(bytes) +``` + +```swift +let data = Data( [0x01, 0x02, 0x03]) + +let hash = data.md5() +let hash = data.sha1() +let hash = data.sha224() +let hash = data.sha256() +let hash = data.sha384() +let hash = data.sha512() +``` +```swift +do { + var digest = MD5() + let partial1 = try digest.update(withBytes: [0x31, 0x32]) + let partial2 = try digest.update(withBytes: [0x33]) + let result = try digest.finish() +} catch { } +``` + +Hashing a String and printing result + +```swift +let hash = "123".md5() // "123".bytes.md5() +``` + +##### Calculate CRC + +```swift +bytes.crc16() +data.crc16() + +bytes.crc32() +data.crc32() +``` + +##### Message authenticators + +```swift +// Calculate Message Authentication Code (MAC) for message +let key:Array = [1,2,3,4,5,6,7,8,9,10,...] + +try Poly1305(key: key).authenticate(bytes) +try HMAC(key: key, variant: .sha256).authenticate(bytes) +try CMAC(key: key).authenticate(bytes) +``` + +##### Password-Based Key Derivation Functions + +```swift +let password: Array = Array("s33krit".utf8) +let salt: Array = Array("nacllcan".utf8) + +let key = try PKCS5.PBKDF2(password: password, salt: salt, iterations: 4096, variant: .sha256).calculate() +``` + +```swift +let password: Array = Array("s33krit".utf8) +let salt: Array = Array("nacllcan".utf8) +// Scrypt implementation does not implement work parallelization, so `p` parameter will +// increase the work time even in multicore systems +let key = try Scrypt(password: password, salt: salt, dkLen: 64, N: 16384, r: 8, p: 1).calculate() +``` + +##### HMAC-based Key Derivation Function + +```swift +let password: Array = Array("s33krit".utf8) +let salt: Array = Array("nacllcan".utf8) + +let key = try HKDF(password: password, salt: salt, variant: .sha256).calculate() +``` + + +##### Data Padding + +Some content-encryption algorithms assume the input length is a multiple of `k` octets, where `k` is greater than one. For such algorithms, the input shall be padded. + +```swift +Padding.pkcs7.add(to: bytes, blockSize: AES.blockSize) +``` + +#### Working with Ciphers +##### ChaCha20 + +```swift +let encrypted = try ChaCha20(key: key, iv: iv).encrypt(message) +let decrypted = try ChaCha20(key: key, iv: iv).decrypt(encrypted) +``` + +##### Rabbit + +```swift +let encrypted = try Rabbit(key: key, iv: iv).encrypt(message) +let decrypted = try Rabbit(key: key, iv: iv).decrypt(encrypted) +``` +##### Blowfish + +```swift +let encrypted = try Blowfish(key: key, blockMode: CBC(iv: iv), padding: .pkcs7).encrypt(message) +let decrypted = try Blowfish(key: key, blockMode: CBC(iv: iv), padding: .pkcs7).decrypt(encrypted) +``` + +##### AES + +Notice regarding padding: *Manual padding of data is optional, and CryptoSwift is using PKCS7 padding by default. If you need to manually disable/enable padding, you can do this by setting parameter for __AES__ class* + +Variant of AES encryption (AES-128, AES-192, AES-256) depends on given key length: + +- AES-128 = 16 bytes +- AES-192 = 24 bytes +- AES-256 = 32 bytes + +AES-256 example +```swift +try AES(key: [1,2,3,...,32], blockMode: CBC(iv: [1,2,3,...,16]), padding: .pkcs7) +``` + +###### All at once +```swift +do { + let aes = try AES(key: "keykeykeykeykeyk", iv: "drowssapdrowssap") // aes128 + let ciphertext = try aes.encrypt(Array("Nullam quis risus eget urna mollis ornare vel eu leo.".utf8)) +} catch { } +``` + +###### Incremental updates + +Incremental operations use instance of Cryptor and encrypt/decrypt one part at a time, this way you can save on memory for large files. + +```swift +do { + var encryptor = try AES(key: "keykeykeykeykeyk", iv: "drowssapdrowssap").makeEncryptor() + + var ciphertext = Array() + // aggregate partial results + ciphertext += try encryptor.update(withBytes: Array("Nullam quis risus ".utf8)) + ciphertext += try encryptor.update(withBytes: Array("eget urna mollis ".utf8)) + ciphertext += try encryptor.update(withBytes: Array("ornare vel eu leo.".utf8)) + // finish at the end + ciphertext += try encryptor.finish() + + print(ciphertext.toHexString()) +} catch { + print(error) +} +``` + +See [Playground](/CryptoSwift.playground/Contents.swift) for sample code that work with stream. + +###### AES Advanced usage +```swift +let input: Array = [0,1,2,3,4,5,6,7,8,9] + +let key: Array = [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00] +let iv: Array = AES.randomIV(AES.blockSize) + +do { + let encrypted = try AES(key: key, blockMode: CBC(iv: iv), padding: .pkcs7).encrypt(input) + let decrypted = try AES(key: key, blockMode: CBC(iv: iv), padding: .pkcs7).decrypt(encrypted) +} catch { + print(error) +} +``` + +AES without data padding + +```swift +let input: Array = [0,1,2,3,4,5,6,7,8,9] +let encrypted: Array = try! AES(key: Array("secret0key000000".utf8), blockMode: CBC(iv: Array("0123456789012345".utf8)), padding: .noPadding).encrypt(input) +``` + +Using convenience extensions + +```swift +let plain = Data( [0x01, 0x02, 0x03]) +let encrypted = try! plain.encrypt(ChaCha20(key: key, iv: iv)) +let decrypted = try! encrypted.decrypt(ChaCha20(key: key, iv: iv)) +``` + +##### AES-GCM + +The result of Galois/Counter Mode (GCM) encryption is ciphertext and **authentication tag**, that is later used to decryption. + +encryption + +```swift +do { + // In combined mode, the authentication tag is directly appended to the encrypted message. This is usually what you want. + let gcm = GCM(iv: iv, mode: .combined) + let aes = try AES(key: key, blockMode: gcm, padding: .noPadding) + let encrypted = try aes.encrypt(plaintext) + let tag = gcm.authenticationTag +catch { + // failed +} +``` + +decryption + +```swift +do { + // In combined mode, the authentication tag is appended to the encrypted message. This is usually what you want. + let gcm = GCM(iv: iv, mode: .combined) + let aes = try AES(key: key, blockMode: gcm, padding: .noPadding) + return try aes.decrypt(encrypted) +} catch { + // failed +} +``` + +**Note**: GCM instance is not intended to be reused. So you can't use the same `GCM` instance from encoding to also perform decoding. + +##### AES-CCM + +The result of Counter with Cipher Block Chaining-Message Authentication Code encryption is ciphertext and **authentication tag**, that is later used to decryption. + +```swift +do { + // The authentication tag is appended to the encrypted message. + let tagLength = 8 + let ccm = CCM(iv: iv, tagLength: tagLength, messageLength: ciphertext.count - tagLength, additionalAuthenticatedData: data) + let aes = try AES(key: key, blockMode: ccm, padding: .noPadding) + return try aes.decrypt(encrypted) +} catch { + // failed +} +``` + +Check documentation or CCM specification for valid parameters for CCM. + +##### AEAD + +```swift +let encrypt = try AEADChaCha20Poly1305.encrypt(plaintext, key: key, iv: nonce, authenticationHeader: header) +let decrypt = try AEADChaCha20Poly1305.decrypt(ciphertext, key: key, iv: nonce, authenticationHeader: header, authenticationTag: tagArr: tag) +``` + +## Author + +CryptoSwift is owned and maintained by [Marcin Krzyżanowski](http://www.krzyzanowskim.com) + +You can follow me on Twitter at [@krzyzanowskim](http://twitter.com/krzyzanowskim) for project updates and releases. + +# Cryptography Notice + +This distribution includes cryptographic software. The country in which you currently reside may have restrictions on the import, possession, use, and/or re-export to another country, of encryption software. BEFORE using any encryption software, please check your country's laws, regulations and policies concerning the import, possession, or use, and re-export of encryption software, to see if this is permitted. See http://www.wassenaar.org/ for more information. + +## License + +Copyright (C) 2014-2017 Marcin Krzyżanowski +This software is provided 'as-is', without any express or implied warranty. + +In no event will the authors be held liable for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: + +- The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, **an acknowledgment in the product documentation is required**. +- Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +- This notice may not be removed or altered from any source or binary distribution. +- Redistributions of any form whatsoever must retain the following acknowledgment: 'This product includes software developed by the "Marcin Krzyzanowski" (http://krzyzanowskim.com/).' + +## Changelog + +See [CHANGELOG](./CHANGELOG) file. diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEAD.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEAD.swift new file mode 100644 index 000000000..67179c597 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEAD.swift @@ -0,0 +1,40 @@ +// +// AEAD.swift +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// +// + +// https://www.iana.org/assignments/aead-parameters/aead-parameters.xhtml + +/// Authenticated Encryption with Associated Data (AEAD) +public protocol AEAD { + static var kLen: Int { get } // key length + static var ivRange: Range { get } // nonce length +} + +extension AEAD { + static func calculateAuthenticationTag(authenticator: Authenticator, cipherText: Array, authenticationHeader: Array) throws -> Array { + let headerPadding = ((16 - (authenticationHeader.count & 0xf)) & 0xf) + let cipherPadding = ((16 - (cipherText.count & 0xf)) & 0xf) + + var mac = authenticationHeader + mac += Array(repeating: 0, count: headerPadding) + mac += cipherText + mac += Array(repeating: 0, count: cipherPadding) + mac += UInt64(bigEndian: UInt64(authenticationHeader.count)).bytes() + mac += UInt64(bigEndian: UInt64(cipherText.count)).bytes() + + return try authenticator.authenticate(mac) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEADChaCha20Poly1305.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEADChaCha20Poly1305.swift new file mode 100644 index 000000000..791f9a442 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEADChaCha20Poly1305.swift @@ -0,0 +1,59 @@ +// +// ChaCha20Poly1305.swift +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// +// +// https://tools.ietf.org/html/rfc7539#section-2.8.1 + +/// AEAD_CHACHA20_POLY1305 +public final class AEADChaCha20Poly1305: AEAD { + public static let kLen = 32 // key length + public static var ivRange = Range(12...12) + + /// Authenticated encryption + public static func encrypt(_ plainText: Array, key: Array, iv: Array, authenticationHeader: Array) throws -> (cipherText: Array, authenticationTag: Array) { + let cipher = try ChaCha20(key: key, iv: iv) + + var polykey = Array(repeating: 0, count: kLen) + var toEncrypt = polykey + polykey = try cipher.encrypt(polykey) + toEncrypt += polykey + toEncrypt += plainText + + let fullCipherText = try cipher.encrypt(toEncrypt) + let cipherText = Array(fullCipherText.dropFirst(64)) + + let tag = try calculateAuthenticationTag(authenticator: Poly1305(key: polykey), cipherText: cipherText, authenticationHeader: authenticationHeader) + return (cipherText, tag) + } + + /// Authenticated decryption + public static func decrypt(_ cipherText: Array, key: Array, iv: Array, authenticationHeader: Array, authenticationTag: Array) throws -> (plainText: Array, success: Bool) { + let chacha = try ChaCha20(key: key, iv: iv) + + let polykey = try chacha.encrypt(Array(repeating: 0, count: kLen)) + let mac = try calculateAuthenticationTag(authenticator: Poly1305(key: polykey), cipherText: cipherText, authenticationHeader: authenticationHeader) + guard mac == authenticationTag else { + return (cipherText, false) + } + + var toDecrypt = Array(reserveCapacity: cipherText.count + 64) + toDecrypt += polykey + toDecrypt += polykey + toDecrypt += cipherText + let fullPlainText = try chacha.decrypt(toDecrypt) + let plainText = Array(fullPlainText.dropFirst(64)) + return (plainText, true) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/AES.Cryptors.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/AES.Cryptors.swift new file mode 100644 index 000000000..a461cd616 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/AES.Cryptors.swift @@ -0,0 +1,35 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// MARK: Cryptors + +extension AES: Cryptors { + public func makeEncryptor() throws -> Cryptor & Updatable { + let worker = try blockMode.worker(blockSize: AES.blockSize, cipherOperation: encrypt) + if worker is StreamModeWorker { + return try StreamEncryptor(blockSize: AES.blockSize, padding: padding, worker) + } + return try BlockEncryptor(blockSize: AES.blockSize, padding: padding, worker) + } + + public func makeDecryptor() throws -> Cryptor & Updatable { + let cipherOperation: CipherOperationOnBlock = blockMode.options.contains(.useEncryptToDecrypt) == true ? encrypt : decrypt + let worker = try blockMode.worker(blockSize: AES.blockSize, cipherOperation: cipherOperation) + if worker is StreamModeWorker { + return try StreamDecryptor(blockSize: AES.blockSize, padding: padding, worker) + } + return try BlockDecryptor(blockSize: AES.blockSize, padding: padding, worker) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/AES.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/AES.swift new file mode 100644 index 000000000..631b7d518 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/AES.swift @@ -0,0 +1,539 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// Implementation of Gladman algorithm http://www.gladman.me.uk/AES +// + +/// The Advanced Encryption Standard (AES) +public final class AES: BlockCipher { + public enum Error: Swift.Error { + /// Invalid key + case invalidKeySize + /// Data padding is required + case dataPaddingRequired + /// Invalid Data + case invalidData + } + + public enum Variant: Int { + case aes128 = 1, aes192, aes256 + + var Nk: Int { // Nk words + return [4, 6, 8][self.rawValue - 1] + } + + var Nb: Int { // Nb words + return 4 + } + + var Nr: Int { // Nr + return Nk + 6 + } + } + + private let variantNr: Int + private let variantNb: Int + private let variantNk: Int + + public static let blockSize: Int = 16 // 128 /8 + public let keySize: Int + + /// AES Variant + public let variant: Variant + + // Parameters + let key: Key + let blockMode: BlockMode + let padding: Padding + + // + private lazy var expandedKey: Array> = self.expandKey(self.key, variant: self.variant) + private lazy var expandedKeyInv: Array> = self.expandKeyInv(self.key, variant: self.variant) + + private lazy var sBoxes: (sBox: Array, invSBox: Array) = self.calculateSBox() + private lazy var sBox: Array = self.sBoxes.sBox + private lazy var sBoxInv: Array = self.sBoxes.invSBox + + // Parameters for Linear Congruence Generators + private static let Rcon: Array = [ + 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, + 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, + 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, + 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, + 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, + 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, + 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, + 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, + 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, + 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, + 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, + 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, + 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, + 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, + 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, + 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, + ] + + private static let T0: Array = [0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0xdf2f2ff, 0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x3010102, 0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d, 0x9a7676ec, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa, 0x15fafaef, 0xeb5959b2, 0xc947478e, 0xbf0f0fb, 0xecadad41, 0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453, 0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d, 0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x2f7f7f5, 0x4fcccc83, 0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x8f1f1f9, 0x937171e2, 0x73d8d8ab, 0x53313162, 0x3f15152a, 0xc040408, 0x52c7c795, 0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0xf05050a, 0xb59a9a2f, 0x907070e, 0x36121224, 0x9b80801b, 0x3de2e2df, 0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912, 0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc, 0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7, 0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413, 0xf55353a6, 0x68d1d1b9, 0x0, 0x2cededc1, 0x60202040, 0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d, 0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0, 0x4acfcf85, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed, 0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a, 0x10f9f9e9, 0x6020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78, 0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d, 0xc0404080, 0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x4f5f5f1, 0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020, 0x1affffe5, 0xef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18, 0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488, 0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a, 0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0xa06060c0, 0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54, 0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b, 0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad, 0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992, 0xa06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd, 0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3, 0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda, 0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8, 0xfa5656ac, 0x7f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4, 0xe9aeae47, 0x18080810, 0xd5baba6f, 0x887878f0, 0x6f25254a, 0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697, 0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96, 0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c, 0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x5030306, 0x1f6f6f7, 0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969, 0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0x38e1e1d9, 0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9, 0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715, 0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5, 0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65, 0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929, 0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d, 0x3a16162c] + private static let T0_INV: Array = [0x50a7f451, 0x5365417e, 0xc3a4171a, 0x965e273a, 0xcb6bab3b, 0xf1459d1f, 0xab58faac, 0x9303e34b, 0x55fa3020, 0xf66d76ad, 0x9176cc88, 0x254c02f5, 0xfcd7e54f, 0xd7cb2ac5, 0x80443526, 0x8fa362b5, 0x495ab1de, 0x671bba25, 0x980eea45, 0xe1c0fe5d, 0x2752fc3, 0x12f04c81, 0xa397468d, 0xc6f9d36b, 0xe75f8f03, 0x959c9215, 0xeb7a6dbf, 0xda595295, 0x2d83bed4, 0xd3217458, 0x2969e049, 0x44c8c98e, 0x6a89c275, 0x78798ef4, 0x6b3e5899, 0xdd71b927, 0xb64fe1be, 0x17ad88f0, 0x66ac20c9, 0xb43ace7d, 0x184adf63, 0x82311ae5, 0x60335197, 0x457f5362, 0xe07764b1, 0x84ae6bbb, 0x1ca081fe, 0x942b08f9, 0x58684870, 0x19fd458f, 0x876cde94, 0xb7f87b52, 0x23d373ab, 0xe2024b72, 0x578f1fe3, 0x2aab5566, 0x728ebb2, 0x3c2b52f, 0x9a7bc586, 0xa50837d3, 0xf2872830, 0xb2a5bf23, 0xba6a0302, 0x5c8216ed, 0x2b1ccf8a, 0x92b479a7, 0xf0f207f3, 0xa1e2694e, 0xcdf4da65, 0xd5be0506, 0x1f6234d1, 0x8afea6c4, 0x9d532e34, 0xa055f3a2, 0x32e18a05, 0x75ebf6a4, 0x39ec830b, 0xaaef6040, 0x69f715e, 0x51106ebd, 0xf98a213e, 0x3d06dd96, 0xae053edd, 0x46bde64d, 0xb58d5491, 0x55dc471, 0x6fd40604, 0xff155060, 0x24fb9819, 0x97e9bdd6, 0xcc434089, 0x779ed967, 0xbd42e8b0, 0x888b8907, 0x385b19e7, 0xdbeec879, 0x470a7ca1, 0xe90f427c, 0xc91e84f8, 0x0, 0x83868009, 0x48ed2b32, 0xac70111e, 0x4e725a6c, 0xfbff0efd, 0x5638850f, 0x1ed5ae3d, 0x27392d36, 0x64d90f0a, 0x21a65c68, 0xd1545b9b, 0x3a2e3624, 0xb1670a0c, 0xfe75793, 0xd296eeb4, 0x9e919b1b, 0x4fc5c080, 0xa220dc61, 0x694b775a, 0x161a121c, 0xaba93e2, 0xe52aa0c0, 0x43e0223c, 0x1d171b12, 0xb0d090e, 0xadc78bf2, 0xb9a8b62d, 0xc8a91e14, 0x8519f157, 0x4c0775af, 0xbbdd99ee, 0xfd607fa3, 0x9f2601f7, 0xbcf5725c, 0xc53b6644, 0x347efb5b, 0x7629438b, 0xdcc623cb, 0x68fcedb6, 0x63f1e4b8, 0xcadc31d7, 0x10856342, 0x40229713, 0x2011c684, 0x7d244a85, 0xf83dbbd2, 0x1132f9ae, 0x6da129c7, 0x4b2f9e1d, 0xf330b2dc, 0xec52860d, 0xd0e3c177, 0x6c16b32b, 0x99b970a9, 0xfa489411, 0x2264e947, 0xc48cfca8, 0x1a3ff0a0, 0xd82c7d56, 0xef903322, 0xc74e4987, 0xc1d138d9, 0xfea2ca8c, 0x360bd498, 0xcf81f5a6, 0x28de7aa5, 0x268eb7da, 0xa4bfad3f, 0xe49d3a2c, 0xd927850, 0x9bcc5f6a, 0x62467e54, 0xc2138df6, 0xe8b8d890, 0x5ef7392e, 0xf5afc382, 0xbe805d9f, 0x7c93d069, 0xa92dd56f, 0xb31225cf, 0x3b99acc8, 0xa77d1810, 0x6e639ce8, 0x7bbb3bdb, 0x97826cd, 0xf418596e, 0x1b79aec, 0xa89a4f83, 0x656e95e6, 0x7ee6ffaa, 0x8cfbc21, 0xe6e815ef, 0xd99be7ba, 0xce366f4a, 0xd4099fea, 0xd67cb029, 0xafb2a431, 0x31233f2a, 0x3094a5c6, 0xc066a235, 0x37bc4e74, 0xa6ca82fc, 0xb0d090e0, 0x15d8a733, 0x4a9804f1, 0xf7daec41, 0xe50cd7f, 0x2ff69117, 0x8dd64d76, 0x4db0ef43, 0x544daacc, 0xdf0496e4, 0xe3b5d19e, 0x1b886a4c, 0xb81f2cc1, 0x7f516546, 0x4ea5e9d, 0x5d358c01, 0x737487fa, 0x2e410bfb, 0x5a1d67b3, 0x52d2db92, 0x335610e9, 0x1347d66d, 0x8c61d79a, 0x7a0ca137, 0x8e14f859, 0x893c13eb, 0xee27a9ce, 0x35c961b7, 0xede51ce1, 0x3cb1477a, 0x59dfd29c, 0x3f73f255, 0x79ce1418, 0xbf37c773, 0xeacdf753, 0x5baafd5f, 0x146f3ddf, 0x86db4478, 0x81f3afca, 0x3ec468b9, 0x2c342438, 0x5f40a3c2, 0x72c31d16, 0xc25e2bc, 0x8b493c28, 0x41950dff, 0x7101a839, 0xdeb30c08, 0x9ce4b4d8, 0x90c15664, 0x6184cb7b, 0x70b632d5, 0x745c6c48, 0x4257b8d0] + private static let T1: Array = [0x6363c6a5, 0x7c7cf884, 0x7777ee99, 0x7b7bf68d, 0xf2f2ff0d, 0x6b6bd6bd, 0x6f6fdeb1, 0xc5c59154, 0x30306050, 0x1010203, 0x6767cea9, 0x2b2b567d, 0xfefee719, 0xd7d7b562, 0xabab4de6, 0x7676ec9a, 0xcaca8f45, 0x82821f9d, 0xc9c98940, 0x7d7dfa87, 0xfafaef15, 0x5959b2eb, 0x47478ec9, 0xf0f0fb0b, 0xadad41ec, 0xd4d4b367, 0xa2a25ffd, 0xafaf45ea, 0x9c9c23bf, 0xa4a453f7, 0x7272e496, 0xc0c09b5b, 0xb7b775c2, 0xfdfde11c, 0x93933dae, 0x26264c6a, 0x36366c5a, 0x3f3f7e41, 0xf7f7f502, 0xcccc834f, 0x3434685c, 0xa5a551f4, 0xe5e5d134, 0xf1f1f908, 0x7171e293, 0xd8d8ab73, 0x31316253, 0x15152a3f, 0x404080c, 0xc7c79552, 0x23234665, 0xc3c39d5e, 0x18183028, 0x969637a1, 0x5050a0f, 0x9a9a2fb5, 0x7070e09, 0x12122436, 0x80801b9b, 0xe2e2df3d, 0xebebcd26, 0x27274e69, 0xb2b27fcd, 0x7575ea9f, 0x909121b, 0x83831d9e, 0x2c2c5874, 0x1a1a342e, 0x1b1b362d, 0x6e6edcb2, 0x5a5ab4ee, 0xa0a05bfb, 0x5252a4f6, 0x3b3b764d, 0xd6d6b761, 0xb3b37dce, 0x2929527b, 0xe3e3dd3e, 0x2f2f5e71, 0x84841397, 0x5353a6f5, 0xd1d1b968, 0x0, 0xededc12c, 0x20204060, 0xfcfce31f, 0xb1b179c8, 0x5b5bb6ed, 0x6a6ad4be, 0xcbcb8d46, 0xbebe67d9, 0x3939724b, 0x4a4a94de, 0x4c4c98d4, 0x5858b0e8, 0xcfcf854a, 0xd0d0bb6b, 0xefefc52a, 0xaaaa4fe5, 0xfbfbed16, 0x434386c5, 0x4d4d9ad7, 0x33336655, 0x85851194, 0x45458acf, 0xf9f9e910, 0x2020406, 0x7f7ffe81, 0x5050a0f0, 0x3c3c7844, 0x9f9f25ba, 0xa8a84be3, 0x5151a2f3, 0xa3a35dfe, 0x404080c0, 0x8f8f058a, 0x92923fad, 0x9d9d21bc, 0x38387048, 0xf5f5f104, 0xbcbc63df, 0xb6b677c1, 0xdadaaf75, 0x21214263, 0x10102030, 0xffffe51a, 0xf3f3fd0e, 0xd2d2bf6d, 0xcdcd814c, 0xc0c1814, 0x13132635, 0xececc32f, 0x5f5fbee1, 0x979735a2, 0x444488cc, 0x17172e39, 0xc4c49357, 0xa7a755f2, 0x7e7efc82, 0x3d3d7a47, 0x6464c8ac, 0x5d5dbae7, 0x1919322b, 0x7373e695, 0x6060c0a0, 0x81811998, 0x4f4f9ed1, 0xdcdca37f, 0x22224466, 0x2a2a547e, 0x90903bab, 0x88880b83, 0x46468cca, 0xeeeec729, 0xb8b86bd3, 0x1414283c, 0xdedea779, 0x5e5ebce2, 0xb0b161d, 0xdbdbad76, 0xe0e0db3b, 0x32326456, 0x3a3a744e, 0xa0a141e, 0x494992db, 0x6060c0a, 0x2424486c, 0x5c5cb8e4, 0xc2c29f5d, 0xd3d3bd6e, 0xacac43ef, 0x6262c4a6, 0x919139a8, 0x959531a4, 0xe4e4d337, 0x7979f28b, 0xe7e7d532, 0xc8c88b43, 0x37376e59, 0x6d6ddab7, 0x8d8d018c, 0xd5d5b164, 0x4e4e9cd2, 0xa9a949e0, 0x6c6cd8b4, 0x5656acfa, 0xf4f4f307, 0xeaeacf25, 0x6565caaf, 0x7a7af48e, 0xaeae47e9, 0x8081018, 0xbaba6fd5, 0x7878f088, 0x25254a6f, 0x2e2e5c72, 0x1c1c3824, 0xa6a657f1, 0xb4b473c7, 0xc6c69751, 0xe8e8cb23, 0xdddda17c, 0x7474e89c, 0x1f1f3e21, 0x4b4b96dd, 0xbdbd61dc, 0x8b8b0d86, 0x8a8a0f85, 0x7070e090, 0x3e3e7c42, 0xb5b571c4, 0x6666ccaa, 0x484890d8, 0x3030605, 0xf6f6f701, 0xe0e1c12, 0x6161c2a3, 0x35356a5f, 0x5757aef9, 0xb9b969d0, 0x86861791, 0xc1c19958, 0x1d1d3a27, 0x9e9e27b9, 0xe1e1d938, 0xf8f8eb13, 0x98982bb3, 0x11112233, 0x6969d2bb, 0xd9d9a970, 0x8e8e0789, 0x949433a7, 0x9b9b2db6, 0x1e1e3c22, 0x87871592, 0xe9e9c920, 0xcece8749, 0x5555aaff, 0x28285078, 0xdfdfa57a, 0x8c8c038f, 0xa1a159f8, 0x89890980, 0xd0d1a17, 0xbfbf65da, 0xe6e6d731, 0x424284c6, 0x6868d0b8, 0x414182c3, 0x999929b0, 0x2d2d5a77, 0xf0f1e11, 0xb0b07bcb, 0x5454a8fc, 0xbbbb6dd6, 0x16162c3a] + private static let T1_INV: Array = [0xa7f45150, 0x65417e53, 0xa4171ac3, 0x5e273a96, 0x6bab3bcb, 0x459d1ff1, 0x58faacab, 0x3e34b93, 0xfa302055, 0x6d76adf6, 0x76cc8891, 0x4c02f525, 0xd7e54ffc, 0xcb2ac5d7, 0x44352680, 0xa362b58f, 0x5ab1de49, 0x1bba2567, 0xeea4598, 0xc0fe5de1, 0x752fc302, 0xf04c8112, 0x97468da3, 0xf9d36bc6, 0x5f8f03e7, 0x9c921595, 0x7a6dbfeb, 0x595295da, 0x83bed42d, 0x217458d3, 0x69e04929, 0xc8c98e44, 0x89c2756a, 0x798ef478, 0x3e58996b, 0x71b927dd, 0x4fe1beb6, 0xad88f017, 0xac20c966, 0x3ace7db4, 0x4adf6318, 0x311ae582, 0x33519760, 0x7f536245, 0x7764b1e0, 0xae6bbb84, 0xa081fe1c, 0x2b08f994, 0x68487058, 0xfd458f19, 0x6cde9487, 0xf87b52b7, 0xd373ab23, 0x24b72e2, 0x8f1fe357, 0xab55662a, 0x28ebb207, 0xc2b52f03, 0x7bc5869a, 0x837d3a5, 0x872830f2, 0xa5bf23b2, 0x6a0302ba, 0x8216ed5c, 0x1ccf8a2b, 0xb479a792, 0xf207f3f0, 0xe2694ea1, 0xf4da65cd, 0xbe0506d5, 0x6234d11f, 0xfea6c48a, 0x532e349d, 0x55f3a2a0, 0xe18a0532, 0xebf6a475, 0xec830b39, 0xef6040aa, 0x9f715e06, 0x106ebd51, 0x8a213ef9, 0x6dd963d, 0x53eddae, 0xbde64d46, 0x8d5491b5, 0x5dc47105, 0xd406046f, 0x155060ff, 0xfb981924, 0xe9bdd697, 0x434089cc, 0x9ed96777, 0x42e8b0bd, 0x8b890788, 0x5b19e738, 0xeec879db, 0xa7ca147, 0xf427ce9, 0x1e84f8c9, 0x0, 0x86800983, 0xed2b3248, 0x70111eac, 0x725a6c4e, 0xff0efdfb, 0x38850f56, 0xd5ae3d1e, 0x392d3627, 0xd90f0a64, 0xa65c6821, 0x545b9bd1, 0x2e36243a, 0x670a0cb1, 0xe757930f, 0x96eeb4d2, 0x919b1b9e, 0xc5c0804f, 0x20dc61a2, 0x4b775a69, 0x1a121c16, 0xba93e20a, 0x2aa0c0e5, 0xe0223c43, 0x171b121d, 0xd090e0b, 0xc78bf2ad, 0xa8b62db9, 0xa91e14c8, 0x19f15785, 0x775af4c, 0xdd99eebb, 0x607fa3fd, 0x2601f79f, 0xf5725cbc, 0x3b6644c5, 0x7efb5b34, 0x29438b76, 0xc623cbdc, 0xfcedb668, 0xf1e4b863, 0xdc31d7ca, 0x85634210, 0x22971340, 0x11c68420, 0x244a857d, 0x3dbbd2f8, 0x32f9ae11, 0xa129c76d, 0x2f9e1d4b, 0x30b2dcf3, 0x52860dec, 0xe3c177d0, 0x16b32b6c, 0xb970a999, 0x489411fa, 0x64e94722, 0x8cfca8c4, 0x3ff0a01a, 0x2c7d56d8, 0x903322ef, 0x4e4987c7, 0xd138d9c1, 0xa2ca8cfe, 0xbd49836, 0x81f5a6cf, 0xde7aa528, 0x8eb7da26, 0xbfad3fa4, 0x9d3a2ce4, 0x9278500d, 0xcc5f6a9b, 0x467e5462, 0x138df6c2, 0xb8d890e8, 0xf7392e5e, 0xafc382f5, 0x805d9fbe, 0x93d0697c, 0x2dd56fa9, 0x1225cfb3, 0x99acc83b, 0x7d1810a7, 0x639ce86e, 0xbb3bdb7b, 0x7826cd09, 0x18596ef4, 0xb79aec01, 0x9a4f83a8, 0x6e95e665, 0xe6ffaa7e, 0xcfbc2108, 0xe815efe6, 0x9be7bad9, 0x366f4ace, 0x99fead4, 0x7cb029d6, 0xb2a431af, 0x233f2a31, 0x94a5c630, 0x66a235c0, 0xbc4e7437, 0xca82fca6, 0xd090e0b0, 0xd8a73315, 0x9804f14a, 0xdaec41f7, 0x50cd7f0e, 0xf691172f, 0xd64d768d, 0xb0ef434d, 0x4daacc54, 0x496e4df, 0xb5d19ee3, 0x886a4c1b, 0x1f2cc1b8, 0x5165467f, 0xea5e9d04, 0x358c015d, 0x7487fa73, 0x410bfb2e, 0x1d67b35a, 0xd2db9252, 0x5610e933, 0x47d66d13, 0x61d79a8c, 0xca1377a, 0x14f8598e, 0x3c13eb89, 0x27a9ceee, 0xc961b735, 0xe51ce1ed, 0xb1477a3c, 0xdfd29c59, 0x73f2553f, 0xce141879, 0x37c773bf, 0xcdf753ea, 0xaafd5f5b, 0x6f3ddf14, 0xdb447886, 0xf3afca81, 0xc468b93e, 0x3424382c, 0x40a3c25f, 0xc31d1672, 0x25e2bc0c, 0x493c288b, 0x950dff41, 0x1a83971, 0xb30c08de, 0xe4b4d89c, 0xc1566490, 0x84cb7b61, 0xb632d570, 0x5c6c4874, 0x57b8d042] + private static let T2: Array = [0x63c6a563, 0x7cf8847c, 0x77ee9977, 0x7bf68d7b, 0xf2ff0df2, 0x6bd6bd6b, 0x6fdeb16f, 0xc59154c5, 0x30605030, 0x1020301, 0x67cea967, 0x2b567d2b, 0xfee719fe, 0xd7b562d7, 0xab4de6ab, 0x76ec9a76, 0xca8f45ca, 0x821f9d82, 0xc98940c9, 0x7dfa877d, 0xfaef15fa, 0x59b2eb59, 0x478ec947, 0xf0fb0bf0, 0xad41ecad, 0xd4b367d4, 0xa25ffda2, 0xaf45eaaf, 0x9c23bf9c, 0xa453f7a4, 0x72e49672, 0xc09b5bc0, 0xb775c2b7, 0xfde11cfd, 0x933dae93, 0x264c6a26, 0x366c5a36, 0x3f7e413f, 0xf7f502f7, 0xcc834fcc, 0x34685c34, 0xa551f4a5, 0xe5d134e5, 0xf1f908f1, 0x71e29371, 0xd8ab73d8, 0x31625331, 0x152a3f15, 0x4080c04, 0xc79552c7, 0x23466523, 0xc39d5ec3, 0x18302818, 0x9637a196, 0x50a0f05, 0x9a2fb59a, 0x70e0907, 0x12243612, 0x801b9b80, 0xe2df3de2, 0xebcd26eb, 0x274e6927, 0xb27fcdb2, 0x75ea9f75, 0x9121b09, 0x831d9e83, 0x2c58742c, 0x1a342e1a, 0x1b362d1b, 0x6edcb26e, 0x5ab4ee5a, 0xa05bfba0, 0x52a4f652, 0x3b764d3b, 0xd6b761d6, 0xb37dceb3, 0x29527b29, 0xe3dd3ee3, 0x2f5e712f, 0x84139784, 0x53a6f553, 0xd1b968d1, 0x0, 0xedc12ced, 0x20406020, 0xfce31ffc, 0xb179c8b1, 0x5bb6ed5b, 0x6ad4be6a, 0xcb8d46cb, 0xbe67d9be, 0x39724b39, 0x4a94de4a, 0x4c98d44c, 0x58b0e858, 0xcf854acf, 0xd0bb6bd0, 0xefc52aef, 0xaa4fe5aa, 0xfbed16fb, 0x4386c543, 0x4d9ad74d, 0x33665533, 0x85119485, 0x458acf45, 0xf9e910f9, 0x2040602, 0x7ffe817f, 0x50a0f050, 0x3c78443c, 0x9f25ba9f, 0xa84be3a8, 0x51a2f351, 0xa35dfea3, 0x4080c040, 0x8f058a8f, 0x923fad92, 0x9d21bc9d, 0x38704838, 0xf5f104f5, 0xbc63dfbc, 0xb677c1b6, 0xdaaf75da, 0x21426321, 0x10203010, 0xffe51aff, 0xf3fd0ef3, 0xd2bf6dd2, 0xcd814ccd, 0xc18140c, 0x13263513, 0xecc32fec, 0x5fbee15f, 0x9735a297, 0x4488cc44, 0x172e3917, 0xc49357c4, 0xa755f2a7, 0x7efc827e, 0x3d7a473d, 0x64c8ac64, 0x5dbae75d, 0x19322b19, 0x73e69573, 0x60c0a060, 0x81199881, 0x4f9ed14f, 0xdca37fdc, 0x22446622, 0x2a547e2a, 0x903bab90, 0x880b8388, 0x468cca46, 0xeec729ee, 0xb86bd3b8, 0x14283c14, 0xdea779de, 0x5ebce25e, 0xb161d0b, 0xdbad76db, 0xe0db3be0, 0x32645632, 0x3a744e3a, 0xa141e0a, 0x4992db49, 0x60c0a06, 0x24486c24, 0x5cb8e45c, 0xc29f5dc2, 0xd3bd6ed3, 0xac43efac, 0x62c4a662, 0x9139a891, 0x9531a495, 0xe4d337e4, 0x79f28b79, 0xe7d532e7, 0xc88b43c8, 0x376e5937, 0x6ddab76d, 0x8d018c8d, 0xd5b164d5, 0x4e9cd24e, 0xa949e0a9, 0x6cd8b46c, 0x56acfa56, 0xf4f307f4, 0xeacf25ea, 0x65caaf65, 0x7af48e7a, 0xae47e9ae, 0x8101808, 0xba6fd5ba, 0x78f08878, 0x254a6f25, 0x2e5c722e, 0x1c38241c, 0xa657f1a6, 0xb473c7b4, 0xc69751c6, 0xe8cb23e8, 0xdda17cdd, 0x74e89c74, 0x1f3e211f, 0x4b96dd4b, 0xbd61dcbd, 0x8b0d868b, 0x8a0f858a, 0x70e09070, 0x3e7c423e, 0xb571c4b5, 0x66ccaa66, 0x4890d848, 0x3060503, 0xf6f701f6, 0xe1c120e, 0x61c2a361, 0x356a5f35, 0x57aef957, 0xb969d0b9, 0x86179186, 0xc19958c1, 0x1d3a271d, 0x9e27b99e, 0xe1d938e1, 0xf8eb13f8, 0x982bb398, 0x11223311, 0x69d2bb69, 0xd9a970d9, 0x8e07898e, 0x9433a794, 0x9b2db69b, 0x1e3c221e, 0x87159287, 0xe9c920e9, 0xce8749ce, 0x55aaff55, 0x28507828, 0xdfa57adf, 0x8c038f8c, 0xa159f8a1, 0x89098089, 0xd1a170d, 0xbf65dabf, 0xe6d731e6, 0x4284c642, 0x68d0b868, 0x4182c341, 0x9929b099, 0x2d5a772d, 0xf1e110f, 0xb07bcbb0, 0x54a8fc54, 0xbb6dd6bb, 0x162c3a16] + private static let T2_INV: Array = [0xf45150a7, 0x417e5365, 0x171ac3a4, 0x273a965e, 0xab3bcb6b, 0x9d1ff145, 0xfaacab58, 0xe34b9303, 0x302055fa, 0x76adf66d, 0xcc889176, 0x2f5254c, 0xe54ffcd7, 0x2ac5d7cb, 0x35268044, 0x62b58fa3, 0xb1de495a, 0xba25671b, 0xea45980e, 0xfe5de1c0, 0x2fc30275, 0x4c8112f0, 0x468da397, 0xd36bc6f9, 0x8f03e75f, 0x9215959c, 0x6dbfeb7a, 0x5295da59, 0xbed42d83, 0x7458d321, 0xe0492969, 0xc98e44c8, 0xc2756a89, 0x8ef47879, 0x58996b3e, 0xb927dd71, 0xe1beb64f, 0x88f017ad, 0x20c966ac, 0xce7db43a, 0xdf63184a, 0x1ae58231, 0x51976033, 0x5362457f, 0x64b1e077, 0x6bbb84ae, 0x81fe1ca0, 0x8f9942b, 0x48705868, 0x458f19fd, 0xde94876c, 0x7b52b7f8, 0x73ab23d3, 0x4b72e202, 0x1fe3578f, 0x55662aab, 0xebb20728, 0xb52f03c2, 0xc5869a7b, 0x37d3a508, 0x2830f287, 0xbf23b2a5, 0x302ba6a, 0x16ed5c82, 0xcf8a2b1c, 0x79a792b4, 0x7f3f0f2, 0x694ea1e2, 0xda65cdf4, 0x506d5be, 0x34d11f62, 0xa6c48afe, 0x2e349d53, 0xf3a2a055, 0x8a0532e1, 0xf6a475eb, 0x830b39ec, 0x6040aaef, 0x715e069f, 0x6ebd5110, 0x213ef98a, 0xdd963d06, 0x3eddae05, 0xe64d46bd, 0x5491b58d, 0xc471055d, 0x6046fd4, 0x5060ff15, 0x981924fb, 0xbdd697e9, 0x4089cc43, 0xd967779e, 0xe8b0bd42, 0x8907888b, 0x19e7385b, 0xc879dbee, 0x7ca1470a, 0x427ce90f, 0x84f8c91e, 0x0, 0x80098386, 0x2b3248ed, 0x111eac70, 0x5a6c4e72, 0xefdfbff, 0x850f5638, 0xae3d1ed5, 0x2d362739, 0xf0a64d9, 0x5c6821a6, 0x5b9bd154, 0x36243a2e, 0xa0cb167, 0x57930fe7, 0xeeb4d296, 0x9b1b9e91, 0xc0804fc5, 0xdc61a220, 0x775a694b, 0x121c161a, 0x93e20aba, 0xa0c0e52a, 0x223c43e0, 0x1b121d17, 0x90e0b0d, 0x8bf2adc7, 0xb62db9a8, 0x1e14c8a9, 0xf1578519, 0x75af4c07, 0x99eebbdd, 0x7fa3fd60, 0x1f79f26, 0x725cbcf5, 0x6644c53b, 0xfb5b347e, 0x438b7629, 0x23cbdcc6, 0xedb668fc, 0xe4b863f1, 0x31d7cadc, 0x63421085, 0x97134022, 0xc6842011, 0x4a857d24, 0xbbd2f83d, 0xf9ae1132, 0x29c76da1, 0x9e1d4b2f, 0xb2dcf330, 0x860dec52, 0xc177d0e3, 0xb32b6c16, 0x70a999b9, 0x9411fa48, 0xe9472264, 0xfca8c48c, 0xf0a01a3f, 0x7d56d82c, 0x3322ef90, 0x4987c74e, 0x38d9c1d1, 0xca8cfea2, 0xd498360b, 0xf5a6cf81, 0x7aa528de, 0xb7da268e, 0xad3fa4bf, 0x3a2ce49d, 0x78500d92, 0x5f6a9bcc, 0x7e546246, 0x8df6c213, 0xd890e8b8, 0x392e5ef7, 0xc382f5af, 0x5d9fbe80, 0xd0697c93, 0xd56fa92d, 0x25cfb312, 0xacc83b99, 0x1810a77d, 0x9ce86e63, 0x3bdb7bbb, 0x26cd0978, 0x596ef418, 0x9aec01b7, 0x4f83a89a, 0x95e6656e, 0xffaa7ee6, 0xbc2108cf, 0x15efe6e8, 0xe7bad99b, 0x6f4ace36, 0x9fead409, 0xb029d67c, 0xa431afb2, 0x3f2a3123, 0xa5c63094, 0xa235c066, 0x4e7437bc, 0x82fca6ca, 0x90e0b0d0, 0xa73315d8, 0x4f14a98, 0xec41f7da, 0xcd7f0e50, 0x91172ff6, 0x4d768dd6, 0xef434db0, 0xaacc544d, 0x96e4df04, 0xd19ee3b5, 0x6a4c1b88, 0x2cc1b81f, 0x65467f51, 0x5e9d04ea, 0x8c015d35, 0x87fa7374, 0xbfb2e41, 0x67b35a1d, 0xdb9252d2, 0x10e93356, 0xd66d1347, 0xd79a8c61, 0xa1377a0c, 0xf8598e14, 0x13eb893c, 0xa9ceee27, 0x61b735c9, 0x1ce1ede5, 0x477a3cb1, 0xd29c59df, 0xf2553f73, 0x141879ce, 0xc773bf37, 0xf753eacd, 0xfd5f5baa, 0x3ddf146f, 0x447886db, 0xafca81f3, 0x68b93ec4, 0x24382c34, 0xa3c25f40, 0x1d1672c3, 0xe2bc0c25, 0x3c288b49, 0xdff4195, 0xa8397101, 0xc08deb3, 0xb4d89ce4, 0x566490c1, 0xcb7b6184, 0x32d570b6, 0x6c48745c, 0xb8d04257] + private static let T3: Array = [0xc6a56363, 0xf8847c7c, 0xee997777, 0xf68d7b7b, 0xff0df2f2, 0xd6bd6b6b, 0xdeb16f6f, 0x9154c5c5, 0x60503030, 0x2030101, 0xcea96767, 0x567d2b2b, 0xe719fefe, 0xb562d7d7, 0x4de6abab, 0xec9a7676, 0x8f45caca, 0x1f9d8282, 0x8940c9c9, 0xfa877d7d, 0xef15fafa, 0xb2eb5959, 0x8ec94747, 0xfb0bf0f0, 0x41ecadad, 0xb367d4d4, 0x5ffda2a2, 0x45eaafaf, 0x23bf9c9c, 0x53f7a4a4, 0xe4967272, 0x9b5bc0c0, 0x75c2b7b7, 0xe11cfdfd, 0x3dae9393, 0x4c6a2626, 0x6c5a3636, 0x7e413f3f, 0xf502f7f7, 0x834fcccc, 0x685c3434, 0x51f4a5a5, 0xd134e5e5, 0xf908f1f1, 0xe2937171, 0xab73d8d8, 0x62533131, 0x2a3f1515, 0x80c0404, 0x9552c7c7, 0x46652323, 0x9d5ec3c3, 0x30281818, 0x37a19696, 0xa0f0505, 0x2fb59a9a, 0xe090707, 0x24361212, 0x1b9b8080, 0xdf3de2e2, 0xcd26ebeb, 0x4e692727, 0x7fcdb2b2, 0xea9f7575, 0x121b0909, 0x1d9e8383, 0x58742c2c, 0x342e1a1a, 0x362d1b1b, 0xdcb26e6e, 0xb4ee5a5a, 0x5bfba0a0, 0xa4f65252, 0x764d3b3b, 0xb761d6d6, 0x7dceb3b3, 0x527b2929, 0xdd3ee3e3, 0x5e712f2f, 0x13978484, 0xa6f55353, 0xb968d1d1, 0x0, 0xc12ceded, 0x40602020, 0xe31ffcfc, 0x79c8b1b1, 0xb6ed5b5b, 0xd4be6a6a, 0x8d46cbcb, 0x67d9bebe, 0x724b3939, 0x94de4a4a, 0x98d44c4c, 0xb0e85858, 0x854acfcf, 0xbb6bd0d0, 0xc52aefef, 0x4fe5aaaa, 0xed16fbfb, 0x86c54343, 0x9ad74d4d, 0x66553333, 0x11948585, 0x8acf4545, 0xe910f9f9, 0x4060202, 0xfe817f7f, 0xa0f05050, 0x78443c3c, 0x25ba9f9f, 0x4be3a8a8, 0xa2f35151, 0x5dfea3a3, 0x80c04040, 0x58a8f8f, 0x3fad9292, 0x21bc9d9d, 0x70483838, 0xf104f5f5, 0x63dfbcbc, 0x77c1b6b6, 0xaf75dada, 0x42632121, 0x20301010, 0xe51affff, 0xfd0ef3f3, 0xbf6dd2d2, 0x814ccdcd, 0x18140c0c, 0x26351313, 0xc32fecec, 0xbee15f5f, 0x35a29797, 0x88cc4444, 0x2e391717, 0x9357c4c4, 0x55f2a7a7, 0xfc827e7e, 0x7a473d3d, 0xc8ac6464, 0xbae75d5d, 0x322b1919, 0xe6957373, 0xc0a06060, 0x19988181, 0x9ed14f4f, 0xa37fdcdc, 0x44662222, 0x547e2a2a, 0x3bab9090, 0xb838888, 0x8cca4646, 0xc729eeee, 0x6bd3b8b8, 0x283c1414, 0xa779dede, 0xbce25e5e, 0x161d0b0b, 0xad76dbdb, 0xdb3be0e0, 0x64563232, 0x744e3a3a, 0x141e0a0a, 0x92db4949, 0xc0a0606, 0x486c2424, 0xb8e45c5c, 0x9f5dc2c2, 0xbd6ed3d3, 0x43efacac, 0xc4a66262, 0x39a89191, 0x31a49595, 0xd337e4e4, 0xf28b7979, 0xd532e7e7, 0x8b43c8c8, 0x6e593737, 0xdab76d6d, 0x18c8d8d, 0xb164d5d5, 0x9cd24e4e, 0x49e0a9a9, 0xd8b46c6c, 0xacfa5656, 0xf307f4f4, 0xcf25eaea, 0xcaaf6565, 0xf48e7a7a, 0x47e9aeae, 0x10180808, 0x6fd5baba, 0xf0887878, 0x4a6f2525, 0x5c722e2e, 0x38241c1c, 0x57f1a6a6, 0x73c7b4b4, 0x9751c6c6, 0xcb23e8e8, 0xa17cdddd, 0xe89c7474, 0x3e211f1f, 0x96dd4b4b, 0x61dcbdbd, 0xd868b8b, 0xf858a8a, 0xe0907070, 0x7c423e3e, 0x71c4b5b5, 0xccaa6666, 0x90d84848, 0x6050303, 0xf701f6f6, 0x1c120e0e, 0xc2a36161, 0x6a5f3535, 0xaef95757, 0x69d0b9b9, 0x17918686, 0x9958c1c1, 0x3a271d1d, 0x27b99e9e, 0xd938e1e1, 0xeb13f8f8, 0x2bb39898, 0x22331111, 0xd2bb6969, 0xa970d9d9, 0x7898e8e, 0x33a79494, 0x2db69b9b, 0x3c221e1e, 0x15928787, 0xc920e9e9, 0x8749cece, 0xaaff5555, 0x50782828, 0xa57adfdf, 0x38f8c8c, 0x59f8a1a1, 0x9808989, 0x1a170d0d, 0x65dabfbf, 0xd731e6e6, 0x84c64242, 0xd0b86868, 0x82c34141, 0x29b09999, 0x5a772d2d, 0x1e110f0f, 0x7bcbb0b0, 0xa8fc5454, 0x6dd6bbbb, 0x2c3a1616] + private static let T3_INV: Array = [0x5150a7f4, 0x7e536541, 0x1ac3a417, 0x3a965e27, 0x3bcb6bab, 0x1ff1459d, 0xacab58fa, 0x4b9303e3, 0x2055fa30, 0xadf66d76, 0x889176cc, 0xf5254c02, 0x4ffcd7e5, 0xc5d7cb2a, 0x26804435, 0xb58fa362, 0xde495ab1, 0x25671bba, 0x45980eea, 0x5de1c0fe, 0xc302752f, 0x8112f04c, 0x8da39746, 0x6bc6f9d3, 0x3e75f8f, 0x15959c92, 0xbfeb7a6d, 0x95da5952, 0xd42d83be, 0x58d32174, 0x492969e0, 0x8e44c8c9, 0x756a89c2, 0xf478798e, 0x996b3e58, 0x27dd71b9, 0xbeb64fe1, 0xf017ad88, 0xc966ac20, 0x7db43ace, 0x63184adf, 0xe582311a, 0x97603351, 0x62457f53, 0xb1e07764, 0xbb84ae6b, 0xfe1ca081, 0xf9942b08, 0x70586848, 0x8f19fd45, 0x94876cde, 0x52b7f87b, 0xab23d373, 0x72e2024b, 0xe3578f1f, 0x662aab55, 0xb20728eb, 0x2f03c2b5, 0x869a7bc5, 0xd3a50837, 0x30f28728, 0x23b2a5bf, 0x2ba6a03, 0xed5c8216, 0x8a2b1ccf, 0xa792b479, 0xf3f0f207, 0x4ea1e269, 0x65cdf4da, 0x6d5be05, 0xd11f6234, 0xc48afea6, 0x349d532e, 0xa2a055f3, 0x532e18a, 0xa475ebf6, 0xb39ec83, 0x40aaef60, 0x5e069f71, 0xbd51106e, 0x3ef98a21, 0x963d06dd, 0xddae053e, 0x4d46bde6, 0x91b58d54, 0x71055dc4, 0x46fd406, 0x60ff1550, 0x1924fb98, 0xd697e9bd, 0x89cc4340, 0x67779ed9, 0xb0bd42e8, 0x7888b89, 0xe7385b19, 0x79dbeec8, 0xa1470a7c, 0x7ce90f42, 0xf8c91e84, 0x0, 0x9838680, 0x3248ed2b, 0x1eac7011, 0x6c4e725a, 0xfdfbff0e, 0xf563885, 0x3d1ed5ae, 0x3627392d, 0xa64d90f, 0x6821a65c, 0x9bd1545b, 0x243a2e36, 0xcb1670a, 0x930fe757, 0xb4d296ee, 0x1b9e919b, 0x804fc5c0, 0x61a220dc, 0x5a694b77, 0x1c161a12, 0xe20aba93, 0xc0e52aa0, 0x3c43e022, 0x121d171b, 0xe0b0d09, 0xf2adc78b, 0x2db9a8b6, 0x14c8a91e, 0x578519f1, 0xaf4c0775, 0xeebbdd99, 0xa3fd607f, 0xf79f2601, 0x5cbcf572, 0x44c53b66, 0x5b347efb, 0x8b762943, 0xcbdcc623, 0xb668fced, 0xb863f1e4, 0xd7cadc31, 0x42108563, 0x13402297, 0x842011c6, 0x857d244a, 0xd2f83dbb, 0xae1132f9, 0xc76da129, 0x1d4b2f9e, 0xdcf330b2, 0xdec5286, 0x77d0e3c1, 0x2b6c16b3, 0xa999b970, 0x11fa4894, 0x472264e9, 0xa8c48cfc, 0xa01a3ff0, 0x56d82c7d, 0x22ef9033, 0x87c74e49, 0xd9c1d138, 0x8cfea2ca, 0x98360bd4, 0xa6cf81f5, 0xa528de7a, 0xda268eb7, 0x3fa4bfad, 0x2ce49d3a, 0x500d9278, 0x6a9bcc5f, 0x5462467e, 0xf6c2138d, 0x90e8b8d8, 0x2e5ef739, 0x82f5afc3, 0x9fbe805d, 0x697c93d0, 0x6fa92dd5, 0xcfb31225, 0xc83b99ac, 0x10a77d18, 0xe86e639c, 0xdb7bbb3b, 0xcd097826, 0x6ef41859, 0xec01b79a, 0x83a89a4f, 0xe6656e95, 0xaa7ee6ff, 0x2108cfbc, 0xefe6e815, 0xbad99be7, 0x4ace366f, 0xead4099f, 0x29d67cb0, 0x31afb2a4, 0x2a31233f, 0xc63094a5, 0x35c066a2, 0x7437bc4e, 0xfca6ca82, 0xe0b0d090, 0x3315d8a7, 0xf14a9804, 0x41f7daec, 0x7f0e50cd, 0x172ff691, 0x768dd64d, 0x434db0ef, 0xcc544daa, 0xe4df0496, 0x9ee3b5d1, 0x4c1b886a, 0xc1b81f2c, 0x467f5165, 0x9d04ea5e, 0x15d358c, 0xfa737487, 0xfb2e410b, 0xb35a1d67, 0x9252d2db, 0xe9335610, 0x6d1347d6, 0x9a8c61d7, 0x377a0ca1, 0x598e14f8, 0xeb893c13, 0xceee27a9, 0xb735c961, 0xe1ede51c, 0x7a3cb147, 0x9c59dfd2, 0x553f73f2, 0x1879ce14, 0x73bf37c7, 0x53eacdf7, 0x5f5baafd, 0xdf146f3d, 0x7886db44, 0xca81f3af, 0xb93ec468, 0x382c3424, 0xc25f40a3, 0x1672c31d, 0xbc0c25e2, 0x288b493c, 0xff41950d, 0x397101a8, 0x8deb30c, 0xd89ce4b4, 0x6490c156, 0x7b6184cb, 0xd570b632, 0x48745c6c, 0xd04257b8] + private static let U1: Array = [0x0, 0xb0d090e, 0x161a121c, 0x1d171b12, 0x2c342438, 0x27392d36, 0x3a2e3624, 0x31233f2a, 0x58684870, 0x5365417e, 0x4e725a6c, 0x457f5362, 0x745c6c48, 0x7f516546, 0x62467e54, 0x694b775a, 0xb0d090e0, 0xbbdd99ee, 0xa6ca82fc, 0xadc78bf2, 0x9ce4b4d8, 0x97e9bdd6, 0x8afea6c4, 0x81f3afca, 0xe8b8d890, 0xe3b5d19e, 0xfea2ca8c, 0xf5afc382, 0xc48cfca8, 0xcf81f5a6, 0xd296eeb4, 0xd99be7ba, 0x7bbb3bdb, 0x70b632d5, 0x6da129c7, 0x66ac20c9, 0x578f1fe3, 0x5c8216ed, 0x41950dff, 0x4a9804f1, 0x23d373ab, 0x28de7aa5, 0x35c961b7, 0x3ec468b9, 0xfe75793, 0x4ea5e9d, 0x19fd458f, 0x12f04c81, 0xcb6bab3b, 0xc066a235, 0xdd71b927, 0xd67cb029, 0xe75f8f03, 0xec52860d, 0xf1459d1f, 0xfa489411, 0x9303e34b, 0x980eea45, 0x8519f157, 0x8e14f859, 0xbf37c773, 0xb43ace7d, 0xa92dd56f, 0xa220dc61, 0xf66d76ad, 0xfd607fa3, 0xe07764b1, 0xeb7a6dbf, 0xda595295, 0xd1545b9b, 0xcc434089, 0xc74e4987, 0xae053edd, 0xa50837d3, 0xb81f2cc1, 0xb31225cf, 0x82311ae5, 0x893c13eb, 0x942b08f9, 0x9f2601f7, 0x46bde64d, 0x4db0ef43, 0x50a7f451, 0x5baafd5f, 0x6a89c275, 0x6184cb7b, 0x7c93d069, 0x779ed967, 0x1ed5ae3d, 0x15d8a733, 0x8cfbc21, 0x3c2b52f, 0x32e18a05, 0x39ec830b, 0x24fb9819, 0x2ff69117, 0x8dd64d76, 0x86db4478, 0x9bcc5f6a, 0x90c15664, 0xa1e2694e, 0xaaef6040, 0xb7f87b52, 0xbcf5725c, 0xd5be0506, 0xdeb30c08, 0xc3a4171a, 0xc8a91e14, 0xf98a213e, 0xf2872830, 0xef903322, 0xe49d3a2c, 0x3d06dd96, 0x360bd498, 0x2b1ccf8a, 0x2011c684, 0x1132f9ae, 0x1a3ff0a0, 0x728ebb2, 0xc25e2bc, 0x656e95e6, 0x6e639ce8, 0x737487fa, 0x78798ef4, 0x495ab1de, 0x4257b8d0, 0x5f40a3c2, 0x544daacc, 0xf7daec41, 0xfcd7e54f, 0xe1c0fe5d, 0xeacdf753, 0xdbeec879, 0xd0e3c177, 0xcdf4da65, 0xc6f9d36b, 0xafb2a431, 0xa4bfad3f, 0xb9a8b62d, 0xb2a5bf23, 0x83868009, 0x888b8907, 0x959c9215, 0x9e919b1b, 0x470a7ca1, 0x4c0775af, 0x51106ebd, 0x5a1d67b3, 0x6b3e5899, 0x60335197, 0x7d244a85, 0x7629438b, 0x1f6234d1, 0x146f3ddf, 0x97826cd, 0x2752fc3, 0x335610e9, 0x385b19e7, 0x254c02f5, 0x2e410bfb, 0x8c61d79a, 0x876cde94, 0x9a7bc586, 0x9176cc88, 0xa055f3a2, 0xab58faac, 0xb64fe1be, 0xbd42e8b0, 0xd4099fea, 0xdf0496e4, 0xc2138df6, 0xc91e84f8, 0xf83dbbd2, 0xf330b2dc, 0xee27a9ce, 0xe52aa0c0, 0x3cb1477a, 0x37bc4e74, 0x2aab5566, 0x21a65c68, 0x10856342, 0x1b886a4c, 0x69f715e, 0xd927850, 0x64d90f0a, 0x6fd40604, 0x72c31d16, 0x79ce1418, 0x48ed2b32, 0x43e0223c, 0x5ef7392e, 0x55fa3020, 0x1b79aec, 0xaba93e2, 0x17ad88f0, 0x1ca081fe, 0x2d83bed4, 0x268eb7da, 0x3b99acc8, 0x3094a5c6, 0x59dfd29c, 0x52d2db92, 0x4fc5c080, 0x44c8c98e, 0x75ebf6a4, 0x7ee6ffaa, 0x63f1e4b8, 0x68fcedb6, 0xb1670a0c, 0xba6a0302, 0xa77d1810, 0xac70111e, 0x9d532e34, 0x965e273a, 0x8b493c28, 0x80443526, 0xe90f427c, 0xe2024b72, 0xff155060, 0xf418596e, 0xc53b6644, 0xce366f4a, 0xd3217458, 0xd82c7d56, 0x7a0ca137, 0x7101a839, 0x6c16b32b, 0x671bba25, 0x5638850f, 0x5d358c01, 0x40229713, 0x4b2f9e1d, 0x2264e947, 0x2969e049, 0x347efb5b, 0x3f73f255, 0xe50cd7f, 0x55dc471, 0x184adf63, 0x1347d66d, 0xcadc31d7, 0xc1d138d9, 0xdcc623cb, 0xd7cb2ac5, 0xe6e815ef, 0xede51ce1, 0xf0f207f3, 0xfbff0efd, 0x92b479a7, 0x99b970a9, 0x84ae6bbb, 0x8fa362b5, 0xbe805d9f, 0xb58d5491, 0xa89a4f83, 0xa397468d] + private static let U2: Array = [0x0, 0xd090e0b, 0x1a121c16, 0x171b121d, 0x3424382c, 0x392d3627, 0x2e36243a, 0x233f2a31, 0x68487058, 0x65417e53, 0x725a6c4e, 0x7f536245, 0x5c6c4874, 0x5165467f, 0x467e5462, 0x4b775a69, 0xd090e0b0, 0xdd99eebb, 0xca82fca6, 0xc78bf2ad, 0xe4b4d89c, 0xe9bdd697, 0xfea6c48a, 0xf3afca81, 0xb8d890e8, 0xb5d19ee3, 0xa2ca8cfe, 0xafc382f5, 0x8cfca8c4, 0x81f5a6cf, 0x96eeb4d2, 0x9be7bad9, 0xbb3bdb7b, 0xb632d570, 0xa129c76d, 0xac20c966, 0x8f1fe357, 0x8216ed5c, 0x950dff41, 0x9804f14a, 0xd373ab23, 0xde7aa528, 0xc961b735, 0xc468b93e, 0xe757930f, 0xea5e9d04, 0xfd458f19, 0xf04c8112, 0x6bab3bcb, 0x66a235c0, 0x71b927dd, 0x7cb029d6, 0x5f8f03e7, 0x52860dec, 0x459d1ff1, 0x489411fa, 0x3e34b93, 0xeea4598, 0x19f15785, 0x14f8598e, 0x37c773bf, 0x3ace7db4, 0x2dd56fa9, 0x20dc61a2, 0x6d76adf6, 0x607fa3fd, 0x7764b1e0, 0x7a6dbfeb, 0x595295da, 0x545b9bd1, 0x434089cc, 0x4e4987c7, 0x53eddae, 0x837d3a5, 0x1f2cc1b8, 0x1225cfb3, 0x311ae582, 0x3c13eb89, 0x2b08f994, 0x2601f79f, 0xbde64d46, 0xb0ef434d, 0xa7f45150, 0xaafd5f5b, 0x89c2756a, 0x84cb7b61, 0x93d0697c, 0x9ed96777, 0xd5ae3d1e, 0xd8a73315, 0xcfbc2108, 0xc2b52f03, 0xe18a0532, 0xec830b39, 0xfb981924, 0xf691172f, 0xd64d768d, 0xdb447886, 0xcc5f6a9b, 0xc1566490, 0xe2694ea1, 0xef6040aa, 0xf87b52b7, 0xf5725cbc, 0xbe0506d5, 0xb30c08de, 0xa4171ac3, 0xa91e14c8, 0x8a213ef9, 0x872830f2, 0x903322ef, 0x9d3a2ce4, 0x6dd963d, 0xbd49836, 0x1ccf8a2b, 0x11c68420, 0x32f9ae11, 0x3ff0a01a, 0x28ebb207, 0x25e2bc0c, 0x6e95e665, 0x639ce86e, 0x7487fa73, 0x798ef478, 0x5ab1de49, 0x57b8d042, 0x40a3c25f, 0x4daacc54, 0xdaec41f7, 0xd7e54ffc, 0xc0fe5de1, 0xcdf753ea, 0xeec879db, 0xe3c177d0, 0xf4da65cd, 0xf9d36bc6, 0xb2a431af, 0xbfad3fa4, 0xa8b62db9, 0xa5bf23b2, 0x86800983, 0x8b890788, 0x9c921595, 0x919b1b9e, 0xa7ca147, 0x775af4c, 0x106ebd51, 0x1d67b35a, 0x3e58996b, 0x33519760, 0x244a857d, 0x29438b76, 0x6234d11f, 0x6f3ddf14, 0x7826cd09, 0x752fc302, 0x5610e933, 0x5b19e738, 0x4c02f525, 0x410bfb2e, 0x61d79a8c, 0x6cde9487, 0x7bc5869a, 0x76cc8891, 0x55f3a2a0, 0x58faacab, 0x4fe1beb6, 0x42e8b0bd, 0x99fead4, 0x496e4df, 0x138df6c2, 0x1e84f8c9, 0x3dbbd2f8, 0x30b2dcf3, 0x27a9ceee, 0x2aa0c0e5, 0xb1477a3c, 0xbc4e7437, 0xab55662a, 0xa65c6821, 0x85634210, 0x886a4c1b, 0x9f715e06, 0x9278500d, 0xd90f0a64, 0xd406046f, 0xc31d1672, 0xce141879, 0xed2b3248, 0xe0223c43, 0xf7392e5e, 0xfa302055, 0xb79aec01, 0xba93e20a, 0xad88f017, 0xa081fe1c, 0x83bed42d, 0x8eb7da26, 0x99acc83b, 0x94a5c630, 0xdfd29c59, 0xd2db9252, 0xc5c0804f, 0xc8c98e44, 0xebf6a475, 0xe6ffaa7e, 0xf1e4b863, 0xfcedb668, 0x670a0cb1, 0x6a0302ba, 0x7d1810a7, 0x70111eac, 0x532e349d, 0x5e273a96, 0x493c288b, 0x44352680, 0xf427ce9, 0x24b72e2, 0x155060ff, 0x18596ef4, 0x3b6644c5, 0x366f4ace, 0x217458d3, 0x2c7d56d8, 0xca1377a, 0x1a83971, 0x16b32b6c, 0x1bba2567, 0x38850f56, 0x358c015d, 0x22971340, 0x2f9e1d4b, 0x64e94722, 0x69e04929, 0x7efb5b34, 0x73f2553f, 0x50cd7f0e, 0x5dc47105, 0x4adf6318, 0x47d66d13, 0xdc31d7ca, 0xd138d9c1, 0xc623cbdc, 0xcb2ac5d7, 0xe815efe6, 0xe51ce1ed, 0xf207f3f0, 0xff0efdfb, 0xb479a792, 0xb970a999, 0xae6bbb84, 0xa362b58f, 0x805d9fbe, 0x8d5491b5, 0x9a4f83a8, 0x97468da3] + private static let U3: Array = [0x0, 0x90e0b0d, 0x121c161a, 0x1b121d17, 0x24382c34, 0x2d362739, 0x36243a2e, 0x3f2a3123, 0x48705868, 0x417e5365, 0x5a6c4e72, 0x5362457f, 0x6c48745c, 0x65467f51, 0x7e546246, 0x775a694b, 0x90e0b0d0, 0x99eebbdd, 0x82fca6ca, 0x8bf2adc7, 0xb4d89ce4, 0xbdd697e9, 0xa6c48afe, 0xafca81f3, 0xd890e8b8, 0xd19ee3b5, 0xca8cfea2, 0xc382f5af, 0xfca8c48c, 0xf5a6cf81, 0xeeb4d296, 0xe7bad99b, 0x3bdb7bbb, 0x32d570b6, 0x29c76da1, 0x20c966ac, 0x1fe3578f, 0x16ed5c82, 0xdff4195, 0x4f14a98, 0x73ab23d3, 0x7aa528de, 0x61b735c9, 0x68b93ec4, 0x57930fe7, 0x5e9d04ea, 0x458f19fd, 0x4c8112f0, 0xab3bcb6b, 0xa235c066, 0xb927dd71, 0xb029d67c, 0x8f03e75f, 0x860dec52, 0x9d1ff145, 0x9411fa48, 0xe34b9303, 0xea45980e, 0xf1578519, 0xf8598e14, 0xc773bf37, 0xce7db43a, 0xd56fa92d, 0xdc61a220, 0x76adf66d, 0x7fa3fd60, 0x64b1e077, 0x6dbfeb7a, 0x5295da59, 0x5b9bd154, 0x4089cc43, 0x4987c74e, 0x3eddae05, 0x37d3a508, 0x2cc1b81f, 0x25cfb312, 0x1ae58231, 0x13eb893c, 0x8f9942b, 0x1f79f26, 0xe64d46bd, 0xef434db0, 0xf45150a7, 0xfd5f5baa, 0xc2756a89, 0xcb7b6184, 0xd0697c93, 0xd967779e, 0xae3d1ed5, 0xa73315d8, 0xbc2108cf, 0xb52f03c2, 0x8a0532e1, 0x830b39ec, 0x981924fb, 0x91172ff6, 0x4d768dd6, 0x447886db, 0x5f6a9bcc, 0x566490c1, 0x694ea1e2, 0x6040aaef, 0x7b52b7f8, 0x725cbcf5, 0x506d5be, 0xc08deb3, 0x171ac3a4, 0x1e14c8a9, 0x213ef98a, 0x2830f287, 0x3322ef90, 0x3a2ce49d, 0xdd963d06, 0xd498360b, 0xcf8a2b1c, 0xc6842011, 0xf9ae1132, 0xf0a01a3f, 0xebb20728, 0xe2bc0c25, 0x95e6656e, 0x9ce86e63, 0x87fa7374, 0x8ef47879, 0xb1de495a, 0xb8d04257, 0xa3c25f40, 0xaacc544d, 0xec41f7da, 0xe54ffcd7, 0xfe5de1c0, 0xf753eacd, 0xc879dbee, 0xc177d0e3, 0xda65cdf4, 0xd36bc6f9, 0xa431afb2, 0xad3fa4bf, 0xb62db9a8, 0xbf23b2a5, 0x80098386, 0x8907888b, 0x9215959c, 0x9b1b9e91, 0x7ca1470a, 0x75af4c07, 0x6ebd5110, 0x67b35a1d, 0x58996b3e, 0x51976033, 0x4a857d24, 0x438b7629, 0x34d11f62, 0x3ddf146f, 0x26cd0978, 0x2fc30275, 0x10e93356, 0x19e7385b, 0x2f5254c, 0xbfb2e41, 0xd79a8c61, 0xde94876c, 0xc5869a7b, 0xcc889176, 0xf3a2a055, 0xfaacab58, 0xe1beb64f, 0xe8b0bd42, 0x9fead409, 0x96e4df04, 0x8df6c213, 0x84f8c91e, 0xbbd2f83d, 0xb2dcf330, 0xa9ceee27, 0xa0c0e52a, 0x477a3cb1, 0x4e7437bc, 0x55662aab, 0x5c6821a6, 0x63421085, 0x6a4c1b88, 0x715e069f, 0x78500d92, 0xf0a64d9, 0x6046fd4, 0x1d1672c3, 0x141879ce, 0x2b3248ed, 0x223c43e0, 0x392e5ef7, 0x302055fa, 0x9aec01b7, 0x93e20aba, 0x88f017ad, 0x81fe1ca0, 0xbed42d83, 0xb7da268e, 0xacc83b99, 0xa5c63094, 0xd29c59df, 0xdb9252d2, 0xc0804fc5, 0xc98e44c8, 0xf6a475eb, 0xffaa7ee6, 0xe4b863f1, 0xedb668fc, 0xa0cb167, 0x302ba6a, 0x1810a77d, 0x111eac70, 0x2e349d53, 0x273a965e, 0x3c288b49, 0x35268044, 0x427ce90f, 0x4b72e202, 0x5060ff15, 0x596ef418, 0x6644c53b, 0x6f4ace36, 0x7458d321, 0x7d56d82c, 0xa1377a0c, 0xa8397101, 0xb32b6c16, 0xba25671b, 0x850f5638, 0x8c015d35, 0x97134022, 0x9e1d4b2f, 0xe9472264, 0xe0492969, 0xfb5b347e, 0xf2553f73, 0xcd7f0e50, 0xc471055d, 0xdf63184a, 0xd66d1347, 0x31d7cadc, 0x38d9c1d1, 0x23cbdcc6, 0x2ac5d7cb, 0x15efe6e8, 0x1ce1ede5, 0x7f3f0f2, 0xefdfbff, 0x79a792b4, 0x70a999b9, 0x6bbb84ae, 0x62b58fa3, 0x5d9fbe80, 0x5491b58d, 0x4f83a89a, 0x468da397] + private static let U4: Array = [0x0, 0xe0b0d09, 0x1c161a12, 0x121d171b, 0x382c3424, 0x3627392d, 0x243a2e36, 0x2a31233f, 0x70586848, 0x7e536541, 0x6c4e725a, 0x62457f53, 0x48745c6c, 0x467f5165, 0x5462467e, 0x5a694b77, 0xe0b0d090, 0xeebbdd99, 0xfca6ca82, 0xf2adc78b, 0xd89ce4b4, 0xd697e9bd, 0xc48afea6, 0xca81f3af, 0x90e8b8d8, 0x9ee3b5d1, 0x8cfea2ca, 0x82f5afc3, 0xa8c48cfc, 0xa6cf81f5, 0xb4d296ee, 0xbad99be7, 0xdb7bbb3b, 0xd570b632, 0xc76da129, 0xc966ac20, 0xe3578f1f, 0xed5c8216, 0xff41950d, 0xf14a9804, 0xab23d373, 0xa528de7a, 0xb735c961, 0xb93ec468, 0x930fe757, 0x9d04ea5e, 0x8f19fd45, 0x8112f04c, 0x3bcb6bab, 0x35c066a2, 0x27dd71b9, 0x29d67cb0, 0x3e75f8f, 0xdec5286, 0x1ff1459d, 0x11fa4894, 0x4b9303e3, 0x45980eea, 0x578519f1, 0x598e14f8, 0x73bf37c7, 0x7db43ace, 0x6fa92dd5, 0x61a220dc, 0xadf66d76, 0xa3fd607f, 0xb1e07764, 0xbfeb7a6d, 0x95da5952, 0x9bd1545b, 0x89cc4340, 0x87c74e49, 0xddae053e, 0xd3a50837, 0xc1b81f2c, 0xcfb31225, 0xe582311a, 0xeb893c13, 0xf9942b08, 0xf79f2601, 0x4d46bde6, 0x434db0ef, 0x5150a7f4, 0x5f5baafd, 0x756a89c2, 0x7b6184cb, 0x697c93d0, 0x67779ed9, 0x3d1ed5ae, 0x3315d8a7, 0x2108cfbc, 0x2f03c2b5, 0x532e18a, 0xb39ec83, 0x1924fb98, 0x172ff691, 0x768dd64d, 0x7886db44, 0x6a9bcc5f, 0x6490c156, 0x4ea1e269, 0x40aaef60, 0x52b7f87b, 0x5cbcf572, 0x6d5be05, 0x8deb30c, 0x1ac3a417, 0x14c8a91e, 0x3ef98a21, 0x30f28728, 0x22ef9033, 0x2ce49d3a, 0x963d06dd, 0x98360bd4, 0x8a2b1ccf, 0x842011c6, 0xae1132f9, 0xa01a3ff0, 0xb20728eb, 0xbc0c25e2, 0xe6656e95, 0xe86e639c, 0xfa737487, 0xf478798e, 0xde495ab1, 0xd04257b8, 0xc25f40a3, 0xcc544daa, 0x41f7daec, 0x4ffcd7e5, 0x5de1c0fe, 0x53eacdf7, 0x79dbeec8, 0x77d0e3c1, 0x65cdf4da, 0x6bc6f9d3, 0x31afb2a4, 0x3fa4bfad, 0x2db9a8b6, 0x23b2a5bf, 0x9838680, 0x7888b89, 0x15959c92, 0x1b9e919b, 0xa1470a7c, 0xaf4c0775, 0xbd51106e, 0xb35a1d67, 0x996b3e58, 0x97603351, 0x857d244a, 0x8b762943, 0xd11f6234, 0xdf146f3d, 0xcd097826, 0xc302752f, 0xe9335610, 0xe7385b19, 0xf5254c02, 0xfb2e410b, 0x9a8c61d7, 0x94876cde, 0x869a7bc5, 0x889176cc, 0xa2a055f3, 0xacab58fa, 0xbeb64fe1, 0xb0bd42e8, 0xead4099f, 0xe4df0496, 0xf6c2138d, 0xf8c91e84, 0xd2f83dbb, 0xdcf330b2, 0xceee27a9, 0xc0e52aa0, 0x7a3cb147, 0x7437bc4e, 0x662aab55, 0x6821a65c, 0x42108563, 0x4c1b886a, 0x5e069f71, 0x500d9278, 0xa64d90f, 0x46fd406, 0x1672c31d, 0x1879ce14, 0x3248ed2b, 0x3c43e022, 0x2e5ef739, 0x2055fa30, 0xec01b79a, 0xe20aba93, 0xf017ad88, 0xfe1ca081, 0xd42d83be, 0xda268eb7, 0xc83b99ac, 0xc63094a5, 0x9c59dfd2, 0x9252d2db, 0x804fc5c0, 0x8e44c8c9, 0xa475ebf6, 0xaa7ee6ff, 0xb863f1e4, 0xb668fced, 0xcb1670a, 0x2ba6a03, 0x10a77d18, 0x1eac7011, 0x349d532e, 0x3a965e27, 0x288b493c, 0x26804435, 0x7ce90f42, 0x72e2024b, 0x60ff1550, 0x6ef41859, 0x44c53b66, 0x4ace366f, 0x58d32174, 0x56d82c7d, 0x377a0ca1, 0x397101a8, 0x2b6c16b3, 0x25671bba, 0xf563885, 0x15d358c, 0x13402297, 0x1d4b2f9e, 0x472264e9, 0x492969e0, 0x5b347efb, 0x553f73f2, 0x7f0e50cd, 0x71055dc4, 0x63184adf, 0x6d1347d6, 0xd7cadc31, 0xd9c1d138, 0xcbdcc623, 0xc5d7cb2a, 0xefe6e815, 0xe1ede51c, 0xf3f0f207, 0xfdfbff0e, 0xa792b479, 0xa999b970, 0xbb84ae6b, 0xb58fa362, 0x9fbe805d, 0x91b58d54, 0x83a89a4f, 0x8da39746] + + /// Initialize AES with variant calculated out of key length: + /// - 16 bytes (AES-128) + /// - 24 bytes (AES-192) + /// - 32 bytes (AES-256) + /// + /// - parameter key: Key. Length of the key decides on AES variant. + /// - parameter iv: Initialization Vector (Optional for some blockMode values) + /// - parameter blockMode: Cipher mode of operation + /// - parameter padding: Padding method. .pkcs7, .noPadding, .zeroPadding, ... + /// + /// - throws: AES.Error + /// + /// - returns: Instance + public init(key: Array, blockMode: BlockMode, padding: Padding = .pkcs7) throws { + self.key = Key(bytes: key) + self.blockMode = blockMode + self.padding = padding + self.keySize = self.key.count + + // Validate key size + switch keySize * 8 { + case 128: + variant = .aes128 + case 192: + variant = .aes192 + case 256: + variant = .aes256 + default: + throw Error.invalidKeySize + } + + variantNb = variant.Nb + variantNk = variant.Nk + variantNr = variant.Nr + } + + internal func encrypt(block: ArraySlice) -> Array? { + if blockMode.options.contains(.paddingRequired) && block.count != AES.blockSize { + return Array(block) + } + + let rounds = variantNr + let rk = expandedKey + + let b00 = UInt32(block[block.startIndex.advanced(by: 0)]) + let b01 = UInt32(block[block.startIndex.advanced(by: 1)]) << 8 + let b02 = UInt32(block[block.startIndex.advanced(by: 2)]) << 16 + let b03 = UInt32(block[block.startIndex.advanced(by: 3)]) << 24 + var b0 = b00 | b01 | b02 | b03 + + let b10 = UInt32(block[block.startIndex.advanced(by: 4)]) + let b11 = UInt32(block[block.startIndex.advanced(by: 5)]) << 8 + let b12 = UInt32(block[block.startIndex.advanced(by: 6)]) << 16 + let b13 = UInt32(block[block.startIndex.advanced(by: 7)]) << 24 + var b1 = b10 | b11 | b12 | b13 + + let b20 = UInt32(block[block.startIndex.advanced(by: 8)]) + let b21 = UInt32(block[block.startIndex.advanced(by: 9)]) << 8 + let b22 = UInt32(block[block.startIndex.advanced(by: 10)]) << 16 + let b23 = UInt32(block[block.startIndex.advanced(by: 11)]) << 24 + var b2 = b20 | b21 | b22 | b23 + + let b30 = UInt32(block[block.startIndex.advanced(by: 12)]) + let b31 = UInt32(block[block.startIndex.advanced(by: 13)]) << 8 + let b32 = UInt32(block[block.startIndex.advanced(by: 14)]) << 16 + let b33 = UInt32(block[block.startIndex.advanced(by: 15)]) << 24 + var b3 = b30 | b31 | b32 | b33 + + let tLength = 4 + let t = UnsafeMutablePointer.allocate(capacity: tLength) + t.initialize(repeating: 0, count: tLength) + defer { + t.deinitialize(count: tLength) + t.deallocate() + } + + for r in 0..> 8) & 0xff)] + let lb02 = AES.T2[Int((t[2] >> 16) & 0xff)] + let lb03 = AES.T3[Int(t[3] >> 24)] + b0 = lb00 ^ lb01 ^ lb02 ^ lb03 + + let lb10 = AES.T0[Int(t[1] & 0xff)] + let lb11 = AES.T1[Int((t[2] >> 8) & 0xff)] + let lb12 = AES.T2[Int((t[3] >> 16) & 0xff)] + let lb13 = AES.T3[Int(t[0] >> 24)] + b1 = lb10 ^ lb11 ^ lb12 ^ lb13 + + let lb20 = AES.T0[Int(t[2] & 0xff)] + let lb21 = AES.T1[Int((t[3] >> 8) & 0xff)] + let lb22 = AES.T2[Int((t[0] >> 16) & 0xff)] + let lb23 = AES.T3[Int(t[1] >> 24)] + b2 = lb20 ^ lb21 ^ lb22 ^ lb23 + + let lb30 = AES.T0[Int(t[3] & 0xff)] + let lb31 = AES.T1[Int((t[0] >> 8) & 0xff)] + let lb32 = AES.T2[Int((t[1] >> 16) & 0xff)] + let lb33 = AES.T3[Int(t[2] >> 24)] + b3 = lb30 ^ lb31 ^ lb32 ^ lb33 + } + + // last round + let r = rounds - 1 + + t[0] = b0 ^ rk[r][0] + t[1] = b1 ^ rk[r][1] + t[2] = b2 ^ rk[r][2] + t[3] = b3 ^ rk[r][3] + + // rounds + b0 = F1(t[0], t[1], t[2], t[3]) ^ rk[rounds][0] + b1 = F1(t[1], t[2], t[3], t[0]) ^ rk[rounds][1] + b2 = F1(t[2], t[3], t[0], t[1]) ^ rk[rounds][2] + b3 = F1(t[3], t[0], t[1], t[2]) ^ rk[rounds][3] + + let encrypted: Array = [ + UInt8(b0 & 0xff), UInt8((b0 >> 8) & 0xff), UInt8((b0 >> 16) & 0xff), UInt8((b0 >> 24) & 0xff), + UInt8(b1 & 0xff), UInt8((b1 >> 8) & 0xff), UInt8((b1 >> 16) & 0xff), UInt8((b1 >> 24) & 0xff), + UInt8(b2 & 0xff), UInt8((b2 >> 8) & 0xff), UInt8((b2 >> 16) & 0xff), UInt8((b2 >> 24) & 0xff), + UInt8(b3 & 0xff), UInt8((b3 >> 8) & 0xff), UInt8((b3 >> 16) & 0xff), UInt8((b3 >> 24) & 0xff), + ] + return encrypted + } + + internal func decrypt(block: ArraySlice) -> Array? { + if blockMode.options.contains(.paddingRequired) && block.count != AES.blockSize { + return Array(block) + } + + let rounds = variantNr + let rk = expandedKeyInv + + // Save miliseconds by not using `block.toUInt32Array()` + let b00 = UInt32(block[block.startIndex.advanced(by: 0)]) + let b01 = UInt32(block[block.startIndex.advanced(by: 1)]) << 8 + let b02 = UInt32(block[block.startIndex.advanced(by: 2)]) << 16 + let b03 = UInt32(block[block.startIndex.advanced(by: 3)]) << 24 + var b0 = b00 | b01 | b02 | b03 + + let b10 = UInt32(block[block.startIndex.advanced(by: 4)]) + let b11 = UInt32(block[block.startIndex.advanced(by: 5)]) << 8 + let b12 = UInt32(block[block.startIndex.advanced(by: 6)]) << 16 + let b13 = UInt32(block[block.startIndex.advanced(by: 7)]) << 24 + var b1 = b10 | b11 | b12 | b13 + + let b20 = UInt32(block[block.startIndex.advanced(by: 8)]) + let b21 = UInt32(block[block.startIndex.advanced(by: 9)]) << 8 + let b22 = UInt32(block[block.startIndex.advanced(by: 10)]) << 16 + let b23 = UInt32(block[block.startIndex.advanced(by: 11)]) << 24 + var b2 = b20 | b21 | b22 | b23 + + let b30 = UInt32(block[block.startIndex.advanced(by: 12)]) + let b31 = UInt32(block[block.startIndex.advanced(by: 13)]) << 8 + let b32 = UInt32(block[block.startIndex.advanced(by: 14)]) << 16 + let b33 = UInt32(block[block.startIndex.advanced(by: 15)]) << 24 + var b3 = b30 | b31 | b32 | b33 + + let tLength = 4 + let t = UnsafeMutablePointer.allocate(capacity: tLength) + t.initialize(repeating: 0, count: tLength) + defer { + t.deinitialize(count: tLength) + t.deallocate() + } + + for r in (2...rounds).reversed() { + t[0] = b0 ^ rk[r][0] + t[1] = b1 ^ rk[r][1] + t[2] = b2 ^ rk[r][2] + t[3] = b3 ^ rk[r][3] + + let b00 = AES.T0_INV[Int(t[0] & 0xff)] + let b01 = AES.T1_INV[Int((t[3] >> 8) & 0xff)] + let b02 = AES.T2_INV[Int((t[2] >> 16) & 0xff)] + let b03 = AES.T3_INV[Int(t[1] >> 24)] + b0 = b00 ^ b01 ^ b02 ^ b03 + + let b10 = AES.T0_INV[Int(t[1] & 0xff)] + let b11 = AES.T1_INV[Int((t[0] >> 8) & 0xff)] + let b12 = AES.T2_INV[Int((t[3] >> 16) & 0xff)] + let b13 = AES.T3_INV[Int(t[2] >> 24)] + b1 = b10 ^ b11 ^ b12 ^ b13 + + let b20 = AES.T0_INV[Int(t[2] & 0xff)] + let b21 = AES.T1_INV[Int((t[1] >> 8) & 0xff)] + let b22 = AES.T2_INV[Int((t[0] >> 16) & 0xff)] + let b23 = AES.T3_INV[Int(t[3] >> 24)] + b2 = b20 ^ b21 ^ b22 ^ b23 + + let b30 = AES.T0_INV[Int(t[3] & 0xff)] + let b31 = AES.T1_INV[Int((t[2] >> 8) & 0xff)] + let b32 = AES.T2_INV[Int((t[1] >> 16) & 0xff)] + let b33 = AES.T3_INV[Int(t[0] >> 24)] + b3 = b30 ^ b31 ^ b32 ^ b33 + } + + // last round + t[0] = b0 ^ rk[1][0] + t[1] = b1 ^ rk[1][1] + t[2] = b2 ^ rk[1][2] + t[3] = b3 ^ rk[1][3] + + // rounds + + let lb00 = sBoxInv[Int(B0(t[0]))] + let lb01 = (sBoxInv[Int(B1(t[3]))] << 8) + let lb02 = (sBoxInv[Int(B2(t[2]))] << 16) + let lb03 = (sBoxInv[Int(B3(t[1]))] << 24) + b0 = lb00 | lb01 | lb02 | lb03 ^ rk[0][0] + + let lb10 = sBoxInv[Int(B0(t[1]))] + let lb11 = (sBoxInv[Int(B1(t[0]))] << 8) + let lb12 = (sBoxInv[Int(B2(t[3]))] << 16) + let lb13 = (sBoxInv[Int(B3(t[2]))] << 24) + b1 = lb10 | lb11 | lb12 | lb13 ^ rk[0][1] + + let lb20 = sBoxInv[Int(B0(t[2]))] + let lb21 = (sBoxInv[Int(B1(t[1]))] << 8) + let lb22 = (sBoxInv[Int(B2(t[0]))] << 16) + let lb23 = (sBoxInv[Int(B3(t[3]))] << 24) + b2 = lb20 | lb21 | lb22 | lb23 ^ rk[0][2] + + let lb30 = sBoxInv[Int(B0(t[3]))] + let lb31 = (sBoxInv[Int(B1(t[2]))] << 8) + let lb32 = (sBoxInv[Int(B2(t[1]))] << 16) + let lb33 = (sBoxInv[Int(B3(t[0]))] << 24) + b3 = lb30 | lb31 | lb32 | lb33 ^ rk[0][3] + + let result: Array = [ + UInt8(b0 & 0xff), UInt8((b0 >> 8) & 0xff), UInt8((b0 >> 16) & 0xff), UInt8((b0 >> 24) & 0xff), + UInt8(b1 & 0xff), UInt8((b1 >> 8) & 0xff), UInt8((b1 >> 16) & 0xff), UInt8((b1 >> 24) & 0xff), + UInt8(b2 & 0xff), UInt8((b2 >> 8) & 0xff), UInt8((b2 >> 16) & 0xff), UInt8((b2 >> 24) & 0xff), + UInt8(b3 & 0xff), UInt8((b3 >> 8) & 0xff), UInt8((b3 >> 16) & 0xff), UInt8((b3 >> 24) & 0xff), + ] + return result + } +} + +private extension AES { + private func expandKeyInv(_ key: Key, variant: Variant) -> Array> { + let rounds = variantNr + var rk2: Array> = expandKey(key, variant: variant) + + for r in 1.. Array> { + func convertExpandedKey(_ expanded: Array) -> Array> { + return expanded.batched(by: 4).map({ UInt32(bytes: $0.reversed()) }).batched(by: 4).map { Array($0) } + } + + /* + * Function used in the Key Expansion routine that takes a four-byte + * input word and applies an S-box to each of the four bytes to + * produce an output word. + */ + func subWord(_ word: Array) -> Array { + precondition(word.count == 4) + + var result = word + for i in 0..<4 { + result[i] = UInt8(sBox[Int(word[i])]) + } + return result + } + + @inline(__always) + func subWordInPlace(_ word: inout Array) { + precondition(word.count == 4) + word[0] = UInt8(sBox[Int(word[0])]) + word[1] = UInt8(sBox[Int(word[1])]) + word[2] = UInt8(sBox[Int(word[2])]) + word[3] = UInt8(sBox[Int(word[3])]) + } + + let wLength = variantNb * (variantNr + 1) * 4 + let w = UnsafeMutablePointer.allocate(capacity: wLength) + w.initialize(repeating: 0, count: wLength) + defer { + w.deinitialize(count: wLength) + w.deallocate() + } + + for i in 0.. + + for i in variantNk..(repeating: 0, count: 4) + + for wordIdx in 0..<4 { + tmp[wordIdx] = w[4 * (i - 1) + wordIdx] + } + if (i % variantNk) == 0 { + tmp = subWord(rotateLeft(UInt32(bytes: tmp), by: 8).bytes(totalBytes: 4)) + tmp[0] = tmp.first! ^ AES.Rcon[i / variantNk] + } else if variantNk > 6 && (i % variantNk) == 4 { + subWordInPlace(&tmp) + } + + // xor array of bytes + for wordIdx in 0..<4 { + w[4 * i + wordIdx] = w[4 * (i - variantNk) + wordIdx] ^ tmp[wordIdx] + } + } + return convertExpandedKey(Array(UnsafeBufferPointer(start: w, count: wLength))) + } + + @inline(__always) + private func B0(_ x: UInt32) -> UInt32 { + return x & 0xff + } + + @inline(__always) + private func B1(_ x: UInt32) -> UInt32 { + return (x >> 8) & 0xff + } + + @inline(__always) + private func B2(_ x: UInt32) -> UInt32 { + return (x >> 16) & 0xff + } + + @inline(__always) + private func B3(_ x: UInt32) -> UInt32 { + return (x >> 24) & 0xff + } + + @inline(__always) + private func F1(_ x0: UInt32, _ x1: UInt32, _ x2: UInt32, _ x3: UInt32) -> UInt32 { + var result: UInt32 = 0 + result |= UInt32(B1(AES.T0[Int(x0 & 255)])) + result |= UInt32(B1(AES.T0[Int((x1 >> 8) & 255)])) << 8 + result |= UInt32(B1(AES.T0[Int((x2 >> 16) & 255)])) << 16 + result |= UInt32(B1(AES.T0[Int(x3 >> 24)])) << 24 + return result + } + + private func calculateSBox() -> (sBox: Array, invSBox: Array) { + let sboxLength = 256 + let sbox = UnsafeMutablePointer.allocate(capacity: sboxLength) + let invsbox = UnsafeMutablePointer.allocate(capacity: sboxLength) + sbox.initialize(repeating: 0, count: sboxLength) + invsbox.initialize(repeating: 0, count: sboxLength) + defer { + sbox.deinitialize(count: sboxLength) + sbox.deallocate() + invsbox.deinitialize(count: sboxLength) + invsbox.deallocate() + } + + sbox[0] = 0x63 + + var p: UInt8 = 1, q: UInt8 = 1 + + repeat { + p = p ^ (UInt8(truncatingIfNeeded: Int(p) << 1) ^ ((p & 0x80) == 0x80 ? 0x1b : 0)) + q ^= q << 1 + q ^= q << 2 + q ^= q << 4 + q ^= (q & 0x80) == 0x80 ? 0x09 : 0 + + let s = 0x63 ^ q ^ rotateLeft(q, by: 1) ^ rotateLeft(q, by: 2) ^ rotateLeft(q, by: 3) ^ rotateLeft(q, by: 4) + + sbox[Int(p)] = UInt32(s) + invsbox[Int(s)] = UInt32(p) + } while (p != 1) + + return (sBox: Array(UnsafeBufferPointer(start: sbox, count: sboxLength)), invSBox: Array(UnsafeBufferPointer(start: invsbox, count: sboxLength))) + } +} + +// MARK: Cipher + +extension AES: Cipher { + public func encrypt(_ bytes: ArraySlice) throws -> Array { + let chunks = bytes.batched(by: AES.blockSize) + + var oneTimeCryptor = try makeEncryptor() + var out = Array(reserveCapacity: bytes.count) + for chunk in chunks { + out += try oneTimeCryptor.update(withBytes: chunk, isLast: false) + } + // Padding may be added at the very end + out += try oneTimeCryptor.finish() + + if blockMode.options.contains(.paddingRequired) && (out.count % AES.blockSize != 0) { + throw Error.dataPaddingRequired + } + + return out + } + + public func decrypt(_ bytes: ArraySlice) throws -> Array { + if blockMode.options.contains(.paddingRequired) && (bytes.count % AES.blockSize != 0) { + throw Error.dataPaddingRequired + } + + var oneTimeCryptor = try makeDecryptor() + let chunks = bytes.batched(by: AES.blockSize) + if chunks.isEmpty { + throw Error.invalidData + } + + var out = Array(reserveCapacity: bytes.count) + + var lastIdx = chunks.startIndex + chunks.indices.formIndex(&lastIdx, offsetBy: chunks.count - 1) + + // To properly remove padding, `isLast` has to be known when called with the last chunk of ciphertext + // Last chunk of ciphertext may contains padded data so next call to update(..) won't be able to remove it + for idx in chunks.indices { + out += try oneTimeCryptor.update(withBytes: chunks[idx], isLast: idx == lastIdx) + } + return out + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Array+Extension.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Array+Extension.swift new file mode 100644 index 000000000..752dcb829 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Array+Extension.swift @@ -0,0 +1,148 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +extension Array { + public init(reserveCapacity: Int) { + self = Array() + self.reserveCapacity(reserveCapacity) + } + + var slice: ArraySlice { + return self[self.startIndex ..< self.endIndex] + } +} + +extension Array where Element == UInt8 { + public init(hex: String) { + self.init(reserveCapacity: hex.unicodeScalars.lazy.underestimatedCount) + var buffer: UInt8? + var skip = hex.hasPrefix("0x") ? 2 : 0 + for char in hex.unicodeScalars.lazy { + guard skip == 0 else { + skip -= 1 + continue + } + guard char.value >= 48 && char.value <= 102 else { + removeAll() + return + } + let v: UInt8 + let c: UInt8 = UInt8(char.value) + switch c { + case let c where c <= 57: + v = c - 48 + case let c where c >= 65 && c <= 70: + v = c - 55 + case let c where c >= 97: + v = c - 87 + default: + removeAll() + return + } + if let b = buffer { + append(b << 4 | v) + buffer = nil + } else { + buffer = v + } + } + if let b = buffer { + append(b) + } + } + + public func toHexString() -> String { + return `lazy`.reduce("") { + var s = String($1, radix: 16) + if s.count == 1 { + s = "0" + s + } + return $0 + s + } + } +} + +extension Array where Element == UInt8 { + /// split in chunks with given chunk size + @available(*, deprecated) + public func chunks(size chunksize: Int) -> Array> { + var words = Array>() + words.reserveCapacity(count / chunksize) + for idx in stride(from: chunksize, through: count, by: chunksize) { + words.append(Array(self[idx - chunksize ..< idx])) // slow for large table + } + let remainder = suffix(count % chunksize) + if !remainder.isEmpty { + words.append(Array(remainder)) + } + return words + } + + public func md5() -> [Element] { + return Digest.md5(self) + } + + public func sha1() -> [Element] { + return Digest.sha1(self) + } + + public func sha224() -> [Element] { + return Digest.sha224(self) + } + + public func sha256() -> [Element] { + return Digest.sha256(self) + } + + public func sha384() -> [Element] { + return Digest.sha384(self) + } + + public func sha512() -> [Element] { + return Digest.sha512(self) + } + + public func sha2(_ variant: SHA2.Variant) -> [Element] { + return Digest.sha2(self, variant: variant) + } + + public func sha3(_ variant: SHA3.Variant) -> [Element] { + return Digest.sha3(self, variant: variant) + } + + public func crc32(seed: UInt32? = nil, reflect: Bool = true) -> UInt32 { + return Checksum.crc32(self, seed: seed, reflect: reflect) + } + + public func crc32c(seed: UInt32? = nil, reflect: Bool = true) -> UInt32 { + return Checksum.crc32c(self, seed: seed, reflect: reflect) + } + + public func crc16(seed: UInt16? = nil) -> UInt16 { + return Checksum.crc16(self, seed: seed) + } + + public func encrypt(cipher: Cipher) throws -> [Element] { + return try cipher.encrypt(slice) + } + + public func decrypt(cipher: Cipher) throws -> [Element] { + return try cipher.decrypt(slice) + } + + public func authenticate(with authenticator: A) throws -> [Element] { + return try authenticator.authenticate(self) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Authenticator.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Authenticator.swift new file mode 100644 index 000000000..03215a646 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Authenticator.swift @@ -0,0 +1,20 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +/// Message authentication code. +public protocol Authenticator { + /// Calculate Message Authentication Code (MAC) for message. + func authenticate(_ bytes: Array) throws -> Array +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BatchedCollection.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BatchedCollection.swift new file mode 100644 index 000000000..575bc1fc0 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BatchedCollection.swift @@ -0,0 +1,63 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +struct BatchedCollectionIndex { + let range: Range +} + +extension BatchedCollectionIndex: Comparable { + static func == (lhs: BatchedCollectionIndex, rhs: BatchedCollectionIndex) -> Bool { + return lhs.range.lowerBound == rhs.range.lowerBound + } + + static func < (lhs: BatchedCollectionIndex, rhs: BatchedCollectionIndex) -> Bool { + return lhs.range.lowerBound < rhs.range.lowerBound + } +} + +protocol BatchedCollectionType: Collection { + associatedtype Base: Collection +} + +struct BatchedCollection: Collection { + let base: Base + let size: Int + typealias Index = BatchedCollectionIndex + private func nextBreak(after idx: Base.Index) -> Base.Index { + return base.index(idx, offsetBy: size, limitedBy: base.endIndex) ?? base.endIndex + } + + var startIndex: Index { + return Index(range: base.startIndex.. Index { + return Index(range: idx.range.upperBound.. Base.SubSequence { + return base[idx.range] + } +} + +extension Collection { + func batched(by size: Int) -> BatchedCollection { + return BatchedCollection(base: self, size: size) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Bit.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Bit.swift new file mode 100644 index 000000000..2e9552ed3 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Bit.swift @@ -0,0 +1,25 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public enum Bit: Int { + case zero + case one +} + +extension Bit { + func inverted() -> Bit { + return self == .zero ? .one : .zero + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockCipher.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockCipher.swift new file mode 100644 index 000000000..b3c1ffa90 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockCipher.swift @@ -0,0 +1,18 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +protocol BlockCipher: Cipher { + static var blockSize: Int { get } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockDecryptor.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockDecryptor.swift new file mode 100644 index 000000000..7990a402b --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockDecryptor.swift @@ -0,0 +1,85 @@ +// CryptoSwift +// +// Copyright (C) 2014-2018 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public class BlockDecryptor: Cryptor, Updatable { + private let blockSize: Int + private let padding: Padding + private var worker: CipherModeWorker + private var accumulated = Array() + + init(blockSize: Int, padding: Padding, _ worker: CipherModeWorker) throws { + self.blockSize = blockSize + self.padding = padding + self.worker = worker + } + + public func update(withBytes bytes: ArraySlice, isLast: Bool = false) throws -> Array { + accumulated += bytes + + // If a worker (eg GCM) can combine ciphertext + tag + // we need to remove tag from the ciphertext. + if !isLast && accumulated.count < blockSize + worker.additionalBufferSize { + return [] + } + + let accumulatedWithoutSuffix: Array + if worker.additionalBufferSize > 0 { + // FIXME: how slow is that? + accumulatedWithoutSuffix = Array(accumulated.prefix(accumulated.count - worker.additionalBufferSize)) + } else { + accumulatedWithoutSuffix = accumulated + } + + var processedBytesCount = 0 + var plaintext = Array(reserveCapacity: accumulatedWithoutSuffix.count) + // Processing in a block-size manner. It's good for block modes, but bad for stream modes. + for var chunk in accumulatedWithoutSuffix.batched(by: blockSize) { + if isLast || (accumulatedWithoutSuffix.count - processedBytesCount) >= blockSize { + let isLastChunk = processedBytesCount + chunk.count == accumulatedWithoutSuffix.count + + if isLast, isLastChunk, var finalizingWorker = worker as? FinalizingDecryptModeWorker { + chunk = try finalizingWorker.willDecryptLast(bytes: chunk + accumulated.suffix(worker.additionalBufferSize)) // tag size + } + + if !chunk.isEmpty { + plaintext += worker.decrypt(block: chunk) + } + + if isLast, isLastChunk, var finalizingWorker = worker as? FinalizingDecryptModeWorker { + plaintext = Array(try finalizingWorker.didDecryptLast(bytes: plaintext.slice)) + } + + processedBytesCount += chunk.count + } + } + accumulated.removeFirst(processedBytesCount) // super-slow + + if isLast { + plaintext = padding.remove(from: plaintext, blockSize: blockSize) + } + + return plaintext + } + + public func seek(to position: Int) throws { + guard var worker = self.worker as? SeekableModeWorker else { + fatalError("Not supported") + } + + try worker.seek(to: position) + self.worker = worker + + accumulated = [] + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockEncryptor.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockEncryptor.swift new file mode 100644 index 000000000..ba3fe2810 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockEncryptor.swift @@ -0,0 +1,57 @@ +// CryptoSwift +// +// Copyright (C) 2014-2018 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// +final class BlockEncryptor: Cryptor, Updatable { + private let blockSize: Int + private var worker: CipherModeWorker + private let padding: Padding + // Accumulated bytes. Not all processed bytes. + private var accumulated = Array(reserveCapacity: 16) + + private var lastBlockRemainder = 0 + + init(blockSize: Int, padding: Padding, _ worker: CipherModeWorker) throws { + self.blockSize = blockSize + self.padding = padding + self.worker = worker + } + + // MARK: Updatable + public func update(withBytes bytes: ArraySlice, isLast: Bool) throws -> Array { + accumulated += bytes + + if isLast { + accumulated = padding.add(to: accumulated, blockSize: blockSize) + } + + var encrypted = Array(reserveCapacity: accumulated.count) + for chunk in accumulated.batched(by: blockSize) { + if isLast || chunk.count == blockSize { + encrypted += worker.encrypt(block: chunk) + } + } + + // Stream encrypts all, so it removes all elements + accumulated.removeFirst(encrypted.count) + + if var finalizingWorker = worker as? FinalizingEncryptModeWorker, isLast == true { + encrypted = Array(try finalizingWorker.finalize(encrypt: encrypted.slice)) + } + + return encrypted + } + + func seek(to: Int) throws { + fatalError("Not supported") + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/BlockMode.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/BlockMode.swift new file mode 100644 index 000000000..b78e27468 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/BlockMode.swift @@ -0,0 +1,24 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public typealias CipherOperationOnBlock = (_ block: ArraySlice) -> Array? + +public protocol BlockMode { + var options: BlockModeOption { get } + //TODO: doesn't have to be public + func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker +} + +typealias StreamMode = BlockMode diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/BlockModeOptions.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/BlockModeOptions.swift new file mode 100644 index 000000000..646184941 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/BlockModeOptions.swift @@ -0,0 +1,27 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public struct BlockModeOption: OptionSet { + public let rawValue: Int + + public init(rawValue: Int) { + self.rawValue = rawValue + } + + static let none = BlockModeOption(rawValue: 1 << 0) + static let initializationVectorRequired = BlockModeOption(rawValue: 1 << 1) + static let paddingRequired = BlockModeOption(rawValue: 1 << 2) + static let useEncryptToDecrypt = BlockModeOption(rawValue: 1 << 3) +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CBC.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CBC.swift new file mode 100644 index 000000000..f98d9bf6e --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CBC.swift @@ -0,0 +1,70 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// Cipher-block chaining (CBC) +// + +public struct CBC: BlockMode { + public enum Error: Swift.Error { + /// Invalid IV + case invalidInitializationVector + } + + public let options: BlockModeOption = [.initializationVectorRequired, .paddingRequired] + private let iv: Array + + public init(iv: Array) { + self.iv = iv + } + + public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker { + if iv.count != blockSize { + throw Error.invalidInitializationVector + } + + return CBCModeWorker(blockSize: blockSize, iv: iv.slice, cipherOperation: cipherOperation) + } +} + +struct CBCModeWorker: BlockModeWorker { + let cipherOperation: CipherOperationOnBlock + var blockSize: Int + let additionalBufferSize: Int = 0 + private let iv: ArraySlice + private var prev: ArraySlice? + + init(blockSize: Int, iv: ArraySlice, cipherOperation: @escaping CipherOperationOnBlock) { + self.blockSize = blockSize + self.iv = iv + self.cipherOperation = cipherOperation + } + + mutating func encrypt(block plaintext: ArraySlice) -> Array { + guard let ciphertext = cipherOperation(xor(prev ?? iv, plaintext)) else { + return Array(plaintext) + } + prev = ciphertext.slice + return ciphertext + } + + mutating func decrypt(block ciphertext: ArraySlice) -> Array { + guard let plaintext = cipherOperation(ciphertext) else { + return Array(ciphertext) + } + let result: Array = xor(prev ?? iv, plaintext) + prev = ciphertext + return result + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CCM.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CCM.swift new file mode 100644 index 000000000..fb59ebe94 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CCM.swift @@ -0,0 +1,359 @@ +//// CryptoSwift +// +// Copyright (C) 2014-2018 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// CCM mode combines the well known CBC-MAC with the well known counter mode of encryption. +// https://tools.ietf.org/html/rfc3610 +// https://csrc.nist.gov/publications/detail/sp/800-38c/final + +#if canImport(Darwin) +import Darwin +#else +import Glibc +#endif + + +/// Counter with Cipher Block Chaining-Message Authentication Code +public struct CCM: StreamMode { + public enum Error: Swift.Error { + /// Invalid IV + case invalidInitializationVector + case invalidParameter + case fail + } + + public let options: BlockModeOption = [.initializationVectorRequired, .useEncryptToDecrypt] + private let nonce: Array + private let additionalAuthenticatedData: Array? + private let tagLength: Int + private let messageLength: Int // total message length. need to know in advance + + // `authenticationTag` nil for encryption, known tag for decryption + /// For encryption, the value is set at the end of the encryption. + /// For decryption, this is a known Tag to validate against. + public var authenticationTag: Array? + + /// Initialize CCM + /// + /// - Parameters: + /// - iv: Initialization vector. Nonce. Valid length between 7 and 13 bytes. + /// - tagLength: Authentication tag length, in bytes. Value of {4, 6, 8, 10, 12, 14, 16}. + /// - messageLength: Plaintext message length (excluding tag if attached). Length have to be provided in advance. + /// - additionalAuthenticatedData: Additional authenticated data. + public init(iv: Array, tagLength: Int, messageLength: Int, additionalAuthenticatedData: Array? = nil) { + self.nonce = iv + self.tagLength = tagLength + self.additionalAuthenticatedData = additionalAuthenticatedData + self.messageLength = messageLength // - tagLength + } + + /// Initialize CCM + /// + /// - Parameters: + /// - iv: Initialization vector. Nonce. Valid length between 7 and 13 bytes. + /// - tagLength: Authentication tag length, in bytes. Value of {4, 6, 8, 10, 12, 14, 16}. + /// - messageLength: Plaintext message length (excluding tag if attached). Length have to be provided in advance. + /// - authenticationTag: Authentication Tag value if not concatenated to ciphertext. + /// - additionalAuthenticatedData: Additional authenticated data. + public init(iv: Array, tagLength: Int, messageLength: Int, authenticationTag: Array, additionalAuthenticatedData: Array? = nil) { + self.init(iv: iv, tagLength: tagLength, messageLength: messageLength, additionalAuthenticatedData: additionalAuthenticatedData) + self.authenticationTag = authenticationTag + } + + + public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker { + if nonce.isEmpty { + throw Error.invalidInitializationVector + } + + return CCMModeWorker(blockSize: blockSize, nonce: nonce.slice, messageLength: messageLength, additionalAuthenticatedData: additionalAuthenticatedData, tagLength: tagLength, cipherOperation: cipherOperation) + } +} + +class CCMModeWorker: StreamModeWorker, SeekableModeWorker, CounterModeWorker, FinalizingEncryptModeWorker, FinalizingDecryptModeWorker { + typealias Counter = Int + var counter = 0 + + let cipherOperation: CipherOperationOnBlock + let blockSize: Int + private let tagLength: Int + private let messageLength: Int // total message length. need to know in advance + private let q: UInt8 + + let additionalBufferSize: Int + private var keystreamPosIdx = 0 + private let nonce: Array + private var last_y: ArraySlice = [] + private var keystream: Array = [] + // Known Tag used to validate during decryption + private var expectedTag: Array? + + public enum Error: Swift.Error { + case invalidParameter + } + + init(blockSize: Int, nonce: ArraySlice, messageLength: Int, additionalAuthenticatedData: [UInt8]?, expectedTag: Array? = nil, tagLength: Int, cipherOperation: @escaping CipherOperationOnBlock) { + self.blockSize = 16 // CCM is defined for 128 block size + self.tagLength = tagLength + self.additionalBufferSize = tagLength + self.messageLength = messageLength + self.expectedTag = expectedTag + self.cipherOperation = cipherOperation + self.nonce = Array(nonce) + self.q = UInt8(15 - nonce.count) // n = 15-q + + let hasAssociatedData = additionalAuthenticatedData != nil && !additionalAuthenticatedData!.isEmpty + processControlInformation(nonce: self.nonce, tagLength: tagLength, hasAssociatedData: hasAssociatedData) + + if let aad = additionalAuthenticatedData, hasAssociatedData { + process(aad: aad) + } + } + + // For the very first time setup new IV (aka y0) from the block0 + private func processControlInformation(nonce: [UInt8], tagLength: Int, hasAssociatedData: Bool) { + let block0 = try! format(nonce: nonce, Q: UInt32(messageLength), q: q, t: UInt8(tagLength), hasAssociatedData: hasAssociatedData).slice + let y0 = cipherOperation(block0)!.slice + last_y = y0 + } + + private func process(aad: [UInt8]) { + let encodedAAD = format(aad: aad) + + for block_i in encodedAAD.batched(by: 16) { + let y_i = cipherOperation(xor(block_i, last_y))!.slice + last_y = y_i + } + } + + private func S(i: Int) throws -> [UInt8] { + let ctr = try format(counter: i, nonce: nonce, q: q) + return cipherOperation(ctr.slice)! + } + + func seek(to position: Int) throws { + self.counter = position + keystream = try S(i: position) + let offset = position % blockSize + keystreamPosIdx = offset + } + + func encrypt(block plaintext: ArraySlice) -> Array { + var result = Array(reserveCapacity: plaintext.count) + + var processed = 0 + while processed < plaintext.count { + // Need a full block here to update keystream and do CBC + if keystream.isEmpty || keystreamPosIdx == blockSize { + // y[i], where i is the counter. Can encrypt 1 block at a time + counter += 1 + guard let S = try? S(i: counter) else { return Array(plaintext) } + let plaintextP = addPadding(Array(plaintext), blockSize: blockSize) + guard let y = cipherOperation(xor(last_y, plaintextP)) else { return Array(plaintext) } + last_y = y.slice + + keystream = S + keystreamPosIdx = 0 + } + + let xored: Array = xor(plaintext[plaintext.startIndex.advanced(by: processed)...], keystream[keystreamPosIdx...]) + keystreamPosIdx += xored.count + processed += xored.count + result += xored + } + return result + } + + func finalize(encrypt ciphertext: ArraySlice) throws -> ArraySlice { + // concatenate T at the end + guard let S0 = try? S(i: 0) else { return ciphertext } + + let computedTag = xor(last_y.prefix(tagLength), S0) as ArraySlice + return ciphertext + computedTag + } + + // Decryption is stream + // CBC is block + private var accumulatedPlaintext: [UInt8] = [] + + func decrypt(block ciphertext: ArraySlice) -> Array { + var output = Array(reserveCapacity: ciphertext.count) + + do { + var currentCounter = counter + var processed = 0 + while processed < ciphertext.count { + // Need a full block here to update keystream and do CBC + // New keystream for a new block + if keystream.isEmpty || keystreamPosIdx == blockSize { + currentCounter += 1 + guard let S = try? S(i: currentCounter) else { return Array(ciphertext) } + keystream = S + keystreamPosIdx = 0 + } + + let xored: Array = xor(ciphertext[ciphertext.startIndex.advanced(by: processed)...], keystream[keystreamPosIdx...]) // plaintext + keystreamPosIdx += xored.count + processed += xored.count + output += xored + counter = currentCounter + } + } + + // Accumulate plaintext for the MAC calculations at the end. + // It would be good to process it together though, here. + accumulatedPlaintext += output + + // Shouldn't return plaintext until validate tag. + // With incremental update, can't validate tag until all block are processed. + return output + } + + func finalize(decrypt plaintext: ArraySlice) throws -> ArraySlice { + // concatenate T at the end + let computedTag = Array(last_y.prefix(tagLength)) + guard let expectedTag = self.expectedTag, expectedTag == computedTag else { + throw CCM.Error.fail + } + + return plaintext + } + + @discardableResult + func willDecryptLast(bytes ciphertext: ArraySlice) throws -> ArraySlice { + // get tag of additionalBufferSize size + // `ciphertext` contains at least additionalBufferSize bytes + // overwrite expectedTag property used later for verification + guard let S0 = try? S(i: 0) else { return ciphertext } + self.expectedTag = xor(ciphertext.suffix(tagLength), S0) as [UInt8] + return ciphertext[ciphertext.startIndex..) throws -> ArraySlice { + + // Calculate Tag, from the last CBC block, for accumulated plaintext. + var processed = 0 + for block in accumulatedPlaintext.batched(by: blockSize) { + let blockP = addPadding(Array(block), blockSize: blockSize) + guard let y = cipherOperation(xor(last_y, blockP)) else { return plaintext } + last_y = y.slice + processed += block.count + } + accumulatedPlaintext.removeFirst(processed) + return plaintext + } +} + +// Q - octet length of P +// q - octet length of Q. Maximum length (in octets) of payload. An element of {2,3,4,5,6,7,8} +// t - octet length of T (MAC length). An element of {4,6,8,10,12,14,16} +private func format(nonce N: [UInt8], Q: UInt32, q: UInt8, t: UInt8, hasAssociatedData: Bool) throws -> [UInt8] { + var flags0: UInt8 = 0 + + if hasAssociatedData { + // 7 bit + flags0 |= (1 << 6) + } + + // 6,5,4 bit is t in 3 bits + flags0 |= (((t-2)/2) & 0x07) << 3 + + // 3,2,1 bit is q in 3 bits + flags0 |= ((q-1) & 0x07) << 0 + + var block0: [UInt8] = Array(repeating: 0, count: 16) + block0[0] = flags0 + + // N in 1...(15-q) octets, n = 15-q + // n is an element of {7,8,9,10,11,12,13} + let n = 15-Int(q) + guard (n + Int(q)) == 15 else { + // n+q == 15 + throw CCMModeWorker.Error.invalidParameter + } + block0[1...n] = N[0...(n-1)] + + // Q in (16-q)...15 octets + block0[(16-Int(q))...15] = Q.bytes(totalBytes: Int(q)).slice + + return block0 +} + +/// Formatting of the Counter Blocks. Ctr[i] +/// The counter generation function. +/// Q - octet length of P +/// q - octet length of Q. Maximum length (in octets) of payload. An element of {2,3,4,5,6,7,8} +private func format(counter i: Int, nonce N: [UInt8], q: UInt8) throws -> [UInt8] { + var flags0: UInt8 = 0 + + // bit 8,7 is Reserved + // bit 4,5,6 shall be set to 0 + // 3,2,1 bit is q in 3 bits + flags0 |= ((q-1) & 0x07) << 0 + + var block = Array(repeating: 0, count: 16) // block[0] + block[0] = flags0 + + // N in 1...(15-q) octets, n = 15-q + // n is an element of {7,8,9,10,11,12,13} + let n = 15-Int(q) + guard (n + Int(q)) == 15 else { + // n+q == 15 + throw CCMModeWorker.Error.invalidParameter + } + block[1...n] = N[0...(n-1)] + + // [i]8q in (16-q)...15 octets + block[(16-Int(q))...15] = i.bytes(totalBytes: Int(q)).slice + + return block +} + +/// Resulting can be partitioned into 16-octet blocks +private func format(aad: [UInt8]) -> [UInt8] { + let a = aad.count + + switch Double(a) { + case 0..<65280: // 2^16-2^8 + // [a]16 + return addPadding(a.bytes(totalBytes: 2) + aad, blockSize: 16) + case 65280..<4_294_967_296: // 2^32 + // [a]32 + return addPadding([0xFF, 0xFE] + a.bytes(totalBytes: 4) + aad, blockSize: 16) + case 4_294_967_296.., blockSize: Int) -> Array { + if bytes.isEmpty { + return Array(repeating: 0, count: blockSize) + } + + let remainder = bytes.count % blockSize + if remainder == 0 { + return bytes + } + + let paddingCount = blockSize - remainder + if paddingCount > 0 { + return bytes + Array(repeating: 0, count: paddingCount) + } + return bytes +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CFB.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CFB.swift new file mode 100644 index 000000000..316283cba --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CFB.swift @@ -0,0 +1,70 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// Cipher feedback (CFB) +// + +public struct CFB: BlockMode { + public enum Error: Swift.Error { + /// Invalid IV + case invalidInitializationVector + } + + public let options: BlockModeOption = [.initializationVectorRequired, .useEncryptToDecrypt] + private let iv: Array + + public init(iv: Array) { + self.iv = iv + } + + public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker { + if iv.count != blockSize { + throw Error.invalidInitializationVector + } + + return CFBModeWorker(blockSize: blockSize, iv: iv.slice, cipherOperation: cipherOperation) + } +} + +struct CFBModeWorker: BlockModeWorker { + let cipherOperation: CipherOperationOnBlock + let blockSize: Int + let additionalBufferSize: Int = 0 + private let iv: ArraySlice + private var prev: ArraySlice? + + init(blockSize: Int, iv: ArraySlice, cipherOperation: @escaping CipherOperationOnBlock) { + self.blockSize = blockSize + self.iv = iv + self.cipherOperation = cipherOperation + } + + mutating func encrypt(block plaintext: ArraySlice) -> Array { + guard let ciphertext = cipherOperation(prev ?? iv) else { + return Array(plaintext) + } + prev = xor(plaintext, ciphertext.slice) + return Array(prev ?? []) + } + + mutating func decrypt(block ciphertext: ArraySlice) -> Array { + guard let plaintext = cipherOperation(prev ?? iv) else { + return Array(ciphertext) + } + let result: Array = xor(plaintext, ciphertext) + prev = ciphertext + return result + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CTR.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CTR.swift new file mode 100644 index 000000000..2dc6a9ecb --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CTR.swift @@ -0,0 +1,134 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// Counter (CTR) + +public struct CTR: StreamMode { + public enum Error: Swift.Error { + /// Invalid IV + case invalidInitializationVector + } + + public let options: BlockModeOption = [.initializationVectorRequired, .useEncryptToDecrypt] + private let iv: Array + private let counter: Int + + public init(iv: Array, counter: Int = 0) { + self.iv = iv + self.counter = counter + } + + public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker { + if iv.count != blockSize { + throw Error.invalidInitializationVector + } + + return CTRModeWorker(blockSize: blockSize, iv: iv.slice, counter: counter, cipherOperation: cipherOperation) + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +struct CTRModeWorker: StreamModeWorker, SeekableModeWorker, CounterModeWorker { + typealias Counter = CTRCounter + + final class CTRCounter { + private let constPrefix: Array + private var value: UInt64 + //TODO: make it an updatable value, computing is too slow + var bytes: Array { + return constPrefix + value.bytes() + } + + init(_ initialValue: Array) { + let halfIndex = initialValue.startIndex.advanced(by: initialValue.count / 2) + constPrefix = Array(initialValue[initialValue.startIndex.., startAt index: Int) { + self.init(buildCounterValue(nonce, counter: UInt64(index))) + } + + static func +=(lhs: CTRCounter, rhs: Int) { + lhs.value += UInt64(rhs) + } + } + + let cipherOperation: CipherOperationOnBlock + let additionalBufferSize: Int = 0 + let iv: Array + var counter: CTRCounter + + private let blockSize: Int + + // The same keystream is used for the block length plaintext + // As new data is added, keystream suffix is used to xor operation. + private var keystream: Array + private var keystreamPosIdx = 0 + + init(blockSize: Int, iv: ArraySlice, counter: Int, cipherOperation: @escaping CipherOperationOnBlock) { + self.cipherOperation = cipherOperation + self.blockSize = blockSize + self.iv = Array(iv) + + // the first keystream is calculated from the nonce = initial value of counter + self.counter = CTRCounter(nonce: Array(iv), startAt: counter) + self.keystream = Array(cipherOperation(self.counter.bytes.slice)!) + } + + mutating func seek(to position: Int) throws { + let offset = position % blockSize + counter = CTRCounter(nonce: iv, startAt: position / blockSize) + keystream = Array(cipherOperation(counter.bytes.slice)!) + keystreamPosIdx = offset + } + + // plaintext is at most blockSize long + mutating func encrypt(block plaintext: ArraySlice) -> Array { + var result = Array(reserveCapacity: plaintext.count) + + var processed = 0 + while processed < plaintext.count { + // Update keystream + if keystreamPosIdx == blockSize { + counter += 1 + keystream = Array(cipherOperation(counter.bytes.slice)!) + keystreamPosIdx = 0 + } + + let xored: Array = xor(plaintext[plaintext.startIndex.advanced(by: processed)...], keystream[keystreamPosIdx...]) + keystreamPosIdx += xored.count + processed += xored.count + result += xored + } + + return result + } + + mutating func decrypt(block ciphertext: ArraySlice) -> Array { + return encrypt(block: ciphertext) + } +} + +private func buildCounterValue(_ iv: Array, counter: UInt64) -> Array { + let noncePartLen = iv.count / 2 + let noncePrefix = iv[iv.startIndex.. +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public protocol CipherModeWorker { + var cipherOperation: CipherOperationOnBlock { get } + + // Additional space needed when incrementally process data + // eg. for GCM combined mode + var additionalBufferSize: Int { get } + + mutating func encrypt(block plaintext: ArraySlice) -> Array + mutating func decrypt(block ciphertext: ArraySlice) -> Array +} + +/// Block workers use `BlockEncryptor` +public protocol BlockModeWorker: CipherModeWorker { + var blockSize: Int { get } +} + +public protocol CounterModeWorker: CipherModeWorker { + associatedtype Counter + var counter: Counter { get set } +} + +public protocol SeekableModeWorker: CipherModeWorker { + mutating func seek(to position: Int) throws +} + +/// Stream workers use `StreamEncryptor` +public protocol StreamModeWorker: CipherModeWorker { +} + +public protocol FinalizingEncryptModeWorker: CipherModeWorker { + // Any final calculations, eg. calculate tag + // Called after the last block is encrypted + mutating func finalize(encrypt ciphertext: ArraySlice) throws -> ArraySlice +} + +public protocol FinalizingDecryptModeWorker: CipherModeWorker { + // Called before decryption, hence input is ciphertext. + // ciphertext is either a last block, or a tag (for stream workers) + @discardableResult + mutating func willDecryptLast(bytes ciphertext: ArraySlice) throws -> ArraySlice + // Called after decryption, hence input is ciphertext + mutating func didDecryptLast(bytes plaintext: ArraySlice) throws -> ArraySlice + // Any final calculations, eg. calculate tag + // Called after the last block is encrypted + mutating func finalize(decrypt plaintext: ArraySlice) throws -> ArraySlice +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/ECB.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/ECB.swift new file mode 100644 index 000000000..ce410b307 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/ECB.swift @@ -0,0 +1,51 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// Electronic codebook (ECB) +// + +public struct ECB: BlockMode { + public let options: BlockModeOption = .paddingRequired + + public init() { + } + + public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker { + return ECBModeWorker(blockSize: blockSize, cipherOperation: cipherOperation) + } +} + +struct ECBModeWorker: BlockModeWorker { + typealias Element = Array + let cipherOperation: CipherOperationOnBlock + let blockSize: Int + let additionalBufferSize: Int = 0 + + init(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) { + self.blockSize = blockSize + self.cipherOperation = cipherOperation + } + + mutating func encrypt(block plaintext: ArraySlice) -> Array { + guard let ciphertext = cipherOperation(plaintext) else { + return Array(plaintext) + } + return ciphertext + } + + mutating func decrypt(block ciphertext: ArraySlice) -> Array { + return encrypt(block: ciphertext) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/GCM.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/GCM.swift new file mode 100644 index 000000000..d9bf5d94d --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/GCM.swift @@ -0,0 +1,370 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// Galois/Counter Mode (GCM) +// https://csrc.nist.gov/publications/detail/sp/800-38d/final +// ref: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.694.695&rep=rep1&type=pdf +// + +public final class GCM: BlockMode { + public enum Mode { + /// In combined mode, the authentication tag is directly appended to the encrypted message. This is usually what you want. + case combined + /// Some applications may need to store the authentication tag and the encrypted message at different locations. + case detached + } + + public let options: BlockModeOption = [.initializationVectorRequired, .useEncryptToDecrypt] + + public enum Error: Swift.Error { + /// Invalid IV + case invalidInitializationVector + /// Special symbol FAIL that indicates that the inputs are not authentic. + case fail + } + + private let iv: Array + private let additionalAuthenticatedData: Array? + private let mode: Mode + + /// Length of authentication tag, in bytes. + /// For encryption, the value is given as init parameter. + /// For decryption, the lenght of given authentication tag is used. + private let tagLength: Int + + // `authenticationTag` nil for encryption, known tag for decryption + /// For encryption, the value is set at the end of the encryption. + /// For decryption, this is a known Tag to validate against. + public var authenticationTag: Array? + + // encrypt + /// Possible tag lengths: 4,8,12,13,14,15,16 + public init(iv: Array, additionalAuthenticatedData: Array? = nil, tagLength: Int = 16, mode: Mode = .detached) { + self.iv = iv + self.additionalAuthenticatedData = additionalAuthenticatedData + self.mode = mode + self.tagLength = tagLength + } + + // decrypt + public convenience init(iv: Array, authenticationTag: Array, additionalAuthenticatedData: Array? = nil, mode: Mode = .detached) { + self.init(iv: iv, additionalAuthenticatedData: additionalAuthenticatedData, tagLength: authenticationTag.count, mode: mode) + self.authenticationTag = authenticationTag + } + + public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker { + if iv.isEmpty { + throw Error.invalidInitializationVector + } + + let worker = GCMModeWorker(iv: iv.slice, aad: additionalAuthenticatedData?.slice, expectedTag: authenticationTag, tagLength: tagLength, mode: mode, cipherOperation: cipherOperation) + worker.didCalculateTag = { [weak self] tag in + self?.authenticationTag = tag + } + return worker + } +} + +// MARK: - Worker + +final class GCMModeWorker: BlockModeWorker, FinalizingEncryptModeWorker, FinalizingDecryptModeWorker { + let cipherOperation: CipherOperationOnBlock + + // Callback called when authenticationTag is ready + var didCalculateTag: ((Array) -> Void)? + + private let tagLength: Int + // GCM nonce is 96-bits by default. It's the most effective length for the IV + private static let nonceSize = 12 + + // GCM is designed for 128-bit ciphers like AES (but not really for Blowfish). 64-bit mode is not implemented. + let blockSize = 16 // 128 bit + let additionalBufferSize: Int + private let iv: ArraySlice + private let mode: GCM.Mode + private var counter: UInt128 + private let eky0: UInt128 // move to GF? + private let h: UInt128 + + // Additional authenticated data + private let aad: ArraySlice? + // Known Tag used to validate during decryption + private var expectedTag: Array? + + // Note: need new worker to reset instance + // Use empty aad if not specified. AAD is optional. + private lazy var gf: GF = { + if let aad = aad { + return GF(aad: Array(aad), h: h, blockSize: blockSize) + } + return GF(aad: [UInt8](), h: h, blockSize: blockSize) + }() + + init(iv: ArraySlice, aad: ArraySlice? = nil, expectedTag: Array? = nil, tagLength: Int, mode: GCM.Mode, cipherOperation: @escaping CipherOperationOnBlock) { + self.cipherOperation = cipherOperation + self.iv = iv + self.mode = mode + self.aad = aad + self.expectedTag = expectedTag + self.tagLength = tagLength + h = UInt128(cipherOperation(Array(repeating: 0, count: blockSize).slice)!) // empty block + + if mode == .combined { + self.additionalBufferSize = tagLength + } else { + self.additionalBufferSize = 0 + } + + // Assume nonce is 12 bytes long, otherwise initial counter would be calulated from GHASH + // counter = GF.ghash(aad: [UInt8](), ciphertext: nonce) + if iv.count == GCMModeWorker.nonceSize { + counter = makeCounter(nonce: Array(self.iv)) + } else { + counter = GF.ghash(h: h, aad: [UInt8](), ciphertext: Array(iv), blockSize: blockSize) + } + + // Set constants + eky0 = UInt128(cipherOperation(counter.bytes.slice)!) + } + + func encrypt(block plaintext: ArraySlice) -> Array { + counter = incrementCounter(counter) + + guard let ekyN = cipherOperation(counter.bytes.slice) else { + return Array(plaintext) + } + + // plaintext block ^ ek1 + let ciphertext = xor(plaintext, ekyN) as Array + + // update ghash incrementally + gf.ghashUpdate(block: ciphertext) + + return Array(ciphertext) + } + + func finalize(encrypt ciphertext: ArraySlice) throws -> ArraySlice { + // Calculate MAC tag. + let ghash = gf.ghashFinish() + let tag = Array((ghash ^ eky0).bytes.prefix(tagLength)) + + // Notify handler + didCalculateTag?(tag) + + switch mode { + case .combined: + return (ciphertext + tag).slice + case .detached: + return ciphertext + } + } + + func decrypt(block ciphertext: ArraySlice) -> Array { + counter = incrementCounter(counter) + + // update ghash incrementally + gf.ghashUpdate(block: Array(ciphertext)) + + guard let ekN = cipherOperation(counter.bytes.slice) else { + return Array(ciphertext) + } + + // ciphertext block ^ ek1 + let plaintext = xor(ciphertext, ekN) as Array + return plaintext + } + + // The authenticated decryption operation has five inputs: K, IV , C, A, and T. It has only a single + // output, either the plaintext value P or a special symbol FAIL that indicates that the inputs are not + // authentic. + @discardableResult + func willDecryptLast(bytes ciphertext: ArraySlice) throws -> ArraySlice { + // Validate tag + switch mode { + case .combined: + // overwrite expectedTag property used later for verification + self.expectedTag = Array(ciphertext.suffix(tagLength)) + return ciphertext[ciphertext.startIndex..) throws -> ArraySlice { + // Calculate MAC tag. + let ghash = gf.ghashFinish() + let computedTag = Array((ghash ^ eky0).bytes.prefix(tagLength)) + + // Validate tag + guard let expectedTag = self.expectedTag, computedTag == expectedTag else { + throw GCM.Error.fail + } + + return plaintext + } + + func finalize(decrypt plaintext: ArraySlice) throws -> ArraySlice { + // do nothing + return plaintext + } +} + +// MARK: - Local utils + +private func makeCounter(nonce: Array) -> UInt128 { + return UInt128(nonce + [0, 0, 0, 1]) +} + +// Successive counter values are generated using the function incr(), which treats the rightmost 32 +// bits of its argument as a nonnegative integer with the least significant bit on the right +private func incrementCounter(_ counter: UInt128) -> UInt128 { + let b = counter.i.b + 1 + let a = (b == 0 ? counter.i.a + 1 : counter.i.a) + return UInt128((a, b)) +} + +// If data is not a multiple of block size bytes long then the remainder is zero padded +// Note: It's similar to ZeroPadding, but it's not the same. +private func addPadding(_ bytes: Array, blockSize: Int) -> Array { + if bytes.isEmpty { + return Array(repeating: 0, count: blockSize) + } + + let remainder = bytes.count % blockSize + if remainder == 0 { + return bytes + } + + let paddingCount = blockSize - remainder + if paddingCount > 0 { + return bytes + Array(repeating: 0, count: paddingCount) + } + return bytes +} + +// MARK: - GF + +/// The Field GF(2^128) +private final class GF { + static let r = UInt128(a: 0xE100000000000000, b: 0) + + let blockSize: Int + let h: UInt128 + + // AAD won't change + let aadLength: Int + + // Updated for every consumed block + var ciphertextLength: Int + + // Start with 0 + var x: UInt128 + + init(aad: [UInt8], h: UInt128, blockSize: Int) { + self.blockSize = blockSize + aadLength = aad.count + ciphertextLength = 0 + self.h = h + x = 0 + + // Calculate for AAD at the begining + x = GF.calculateX(aad: aad, x: x, h: h, blockSize: blockSize) + } + + @discardableResult + func ghashUpdate(block ciphertextBlock: Array) -> UInt128 { + ciphertextLength += ciphertextBlock.count + x = GF.calculateX(block: addPadding(ciphertextBlock, blockSize: blockSize), x: x, h: h, blockSize: blockSize) + return x + } + + func ghashFinish() -> UInt128 { + // len(A) || len(C) + let len = UInt128(a: UInt64(aadLength * 8), b: UInt64(ciphertextLength * 8)) + x = GF.multiply((x ^ len), h) + return x + } + + // GHASH. One-time calculation + static func ghash(x startx: UInt128 = 0, h: UInt128, aad: Array, ciphertext: Array, blockSize: Int) -> UInt128 { + var x = calculateX(aad: aad, x: startx, h: h, blockSize: blockSize) + x = calculateX(ciphertext: ciphertext, x: x, h: h, blockSize: blockSize) + + // len(aad) || len(ciphertext) + let len = UInt128(a: UInt64(aad.count * 8), b: UInt64(ciphertext.count * 8)) + x = multiply((x ^ len), h) + + return x + } + + // Calculate Ciphertext part, for all blocks + // Not used with incremental calculation. + private static func calculateX(ciphertext: [UInt8], x startx: UInt128, h: UInt128, blockSize: Int) -> UInt128 { + let pciphertext = addPadding(ciphertext, blockSize: blockSize) + let blocksCount = pciphertext.count / blockSize + + var x = startx + for i in 0.., x: UInt128, h: UInt128, blockSize: Int) -> UInt128 { + let k = x ^ UInt128(ciphertextBlock) + return multiply(k, h) + } + + // Calculate AAD part, for all blocks + private static func calculateX(aad: [UInt8], x startx: UInt128, h: UInt128, blockSize: Int) -> UInt128 { + let paad = addPadding(aad, blockSize: blockSize) + let blocksCount = paad.count / blockSize + + var x = startx + for i in 0.. UInt128 { + var z: UInt128 = 0 + var v = x + var k = UInt128(a: 1 << 63, b: 0) + + for _ in 0..<128 { + if y & k == k { + z = z ^ v + } + + if v & 1 != 1 { + v = v >> 1 + } else { + v = (v >> 1) ^ r + } + + k = k >> 1 + } + + return z + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/OFB.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/OFB.swift new file mode 100644 index 000000000..0f5c66a48 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/OFB.swift @@ -0,0 +1,70 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// Output Feedback (OFB) +// + +public struct OFB: BlockMode { + public enum Error: Swift.Error { + /// Invalid IV + case invalidInitializationVector + } + + public let options: BlockModeOption = [.initializationVectorRequired, .useEncryptToDecrypt] + private let iv: Array + + public init(iv: Array) { + self.iv = iv + } + + public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker { + if iv.count != blockSize { + throw Error.invalidInitializationVector + } + + return OFBModeWorker(blockSize: blockSize, iv: iv.slice, cipherOperation: cipherOperation) + } +} + +struct OFBModeWorker: BlockModeWorker { + let cipherOperation: CipherOperationOnBlock + let blockSize: Int + let additionalBufferSize: Int = 0 + private let iv: ArraySlice + private var prev: ArraySlice? + + init(blockSize: Int, iv: ArraySlice, cipherOperation: @escaping CipherOperationOnBlock) { + self.blockSize = blockSize + self.iv = iv + self.cipherOperation = cipherOperation + } + + mutating func encrypt(block plaintext: ArraySlice) -> Array { + guard let ciphertext = cipherOperation(prev ?? iv) else { + return Array(plaintext) + } + prev = ciphertext.slice + return xor(plaintext, ciphertext) + } + + mutating func decrypt(block ciphertext: ArraySlice) -> Array { + guard let decrypted = cipherOperation(prev ?? iv) else { + return Array(ciphertext) + } + let plaintext: Array = xor(decrypted, ciphertext) + prev = decrypted.slice + return plaintext + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/PCBC.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/PCBC.swift new file mode 100644 index 000000000..846015d6a --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/PCBC.swift @@ -0,0 +1,70 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// Propagating Cipher Block Chaining (PCBC) +// + +public struct PCBC: BlockMode { + public enum Error: Swift.Error { + /// Invalid IV + case invalidInitializationVector + } + + public let options: BlockModeOption = [.initializationVectorRequired, .paddingRequired] + private let iv: Array + + public init(iv: Array) { + self.iv = iv + } + + public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker { + if iv.count != blockSize { + throw Error.invalidInitializationVector + } + + return PCBCModeWorker(blockSize: blockSize, iv: iv.slice, cipherOperation: cipherOperation) + } +} + +struct PCBCModeWorker: BlockModeWorker { + let cipherOperation: CipherOperationOnBlock + var blockSize: Int + let additionalBufferSize: Int = 0 + private let iv: ArraySlice + private var prev: ArraySlice? + + init(blockSize: Int, iv: ArraySlice, cipherOperation: @escaping CipherOperationOnBlock) { + self.blockSize = blockSize + self.iv = iv + self.cipherOperation = cipherOperation + } + + mutating func encrypt(block plaintext: ArraySlice) -> Array { + guard let ciphertext = cipherOperation(xor(prev ?? iv, plaintext)) else { + return Array(plaintext) + } + prev = xor(plaintext, ciphertext.slice) + return ciphertext + } + + mutating func decrypt(block ciphertext: ArraySlice) -> Array { + guard let plaintext = cipherOperation(ciphertext) else { + return Array(ciphertext) + } + let result: Array = xor(prev ?? iv, plaintext) + prev = xor(plaintext.slice, ciphertext) + return result + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Blowfish.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Blowfish.swift new file mode 100644 index 000000000..34c771c27 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Blowfish.swift @@ -0,0 +1,537 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// https://en.wikipedia.org/wiki/Blowfish_(cipher) +// Based on Paul Kocher implementation +// + +public final class Blowfish { + public enum Error: Swift.Error { + /// Data padding is required + case dataPaddingRequired + /// Invalid key or IV + case invalidKeyOrInitializationVector + /// Invalid IV + case invalidInitializationVector + /// Invalid block mode + case invalidBlockMode + } + + public static let blockSize: Int = 8 // 64 bit + public let keySize: Int + + private let blockMode: BlockMode + private let padding: Padding + private var decryptWorker: CipherModeWorker! + private var encryptWorker: CipherModeWorker! + + private let N = 16 // rounds + private var P: Array + private var S: Array> + private let origP: Array = [ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, + 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, + 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, + 0xb5470917, 0x9216d5d9, 0x8979fb1b, + ] + + private let origS: Array> = [ + [ + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, + 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, + 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, + 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, + 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, + 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, + 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, + 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, + 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, + 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, + 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, + 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, + 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, + 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, + 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, + 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, + 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, + 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, + 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, + 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, + 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, + 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, + 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, + 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, + 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, + 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, + 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, + 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, + 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, + 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, + 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, + 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, + 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, + 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, + 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, + 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, + 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, + 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, + 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, + 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, + 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, + 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, + 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, + 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, + 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, + 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, + 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, + 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, + 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, + 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a, + ], + [ + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, + 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, + 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, + 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, + 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, + 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, + 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, + 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, + 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, + 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, + 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, + 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, + 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, + 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, + 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, + 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, + 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, + 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, + 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, + 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, + 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, + 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, + 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, + 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, + 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, + 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, + 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, + 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, + 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, + 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, + 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, + 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, + 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, + 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, + 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, + 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, + 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, + 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, + 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, + 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, + 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, + 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, + 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7, + ], + [ + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, + 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, + 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, + 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, + 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, + 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, + 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, + 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, + 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, + 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, + 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, + 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, + 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, + 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, + 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, + 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, + 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, + 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, + 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, + 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, + 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, + 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, + 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, + 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, + 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, + 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, + 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, + 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, + 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, + 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, + 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, + 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, + 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, + 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, + 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, + 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, + 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, + 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, + 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, + 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, + 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, + 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, + 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, + 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, + 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, + 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, + 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, + 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, + 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, + 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0, + ], + [ + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, + 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, + 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, + 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, + 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, + 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, + 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, + 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, + 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, + 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, + 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, + 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, + 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, + 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, + 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, + 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, + 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, + 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, + 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, + 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, + 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, + 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, + 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, + 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, + 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, + 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, + 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, + 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, + 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, + 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, + 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, + 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, + 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, + 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, + 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, + 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, + 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, + 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, + 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, + 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, + 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, + 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, + 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, + 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, + 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, + 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, + 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, + 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, + 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, + 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, + 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6, + ], + ] + + public init(key: Array, blockMode: BlockMode = CBC(iv: Array(repeating: 0, count: Blowfish.blockSize)), padding: Padding) throws { + precondition(key.count >= 5 && key.count <= 56) + + self.blockMode = blockMode + self.padding = padding + keySize = key.count + + S = origS + P = origP + + expandKey(key: key) + try setupBlockModeWorkers() + } + + private func setupBlockModeWorkers() throws { + encryptWorker = try blockMode.worker(blockSize: Blowfish.blockSize, cipherOperation: encrypt) + + if blockMode.options.contains(.useEncryptToDecrypt) { + decryptWorker = try blockMode.worker(blockSize: Blowfish.blockSize, cipherOperation: encrypt) + } else { + decryptWorker = try blockMode.worker(blockSize: Blowfish.blockSize, cipherOperation: decrypt) + } + } + + private func reset() { + S = origS + P = origP + // todo expand key + } + + private func expandKey(key: Array) { + var j = 0 + for i in 0..<(N + 2) { + var data: UInt32 = 0x0 + for _ in 0..<4 { + data = (data << 8) | UInt32(key[j]) + j += 1 + if j >= key.count { + j = 0 + } + } + P[i] ^= data + } + + var datal: UInt32 = 0 + var datar: UInt32 = 0 + + for i in stride(from: 0, to: N + 2, by: 2) { + encryptBlowfishBlock(l: &datal, r: &datar) + P[i] = datal + P[i + 1] = datar + } + + for i in 0..<4 { + for j in stride(from: 0, to: 256, by: 2) { + encryptBlowfishBlock(l: &datal, r: &datar) + S[i][j] = datal + S[i][j + 1] = datar + } + } + } + + fileprivate func encrypt(block: ArraySlice) -> Array? { + var result = Array() + + var l = UInt32(bytes: block[block.startIndex..> 24) & 0xff), + UInt8((l >> 16) & 0xff), + ] + result += [ + UInt8((l >> 8) & 0xff), + UInt8((l >> 0) & 0xff), + ] + result += [ + UInt8((r >> 24) & 0xff), + UInt8((r >> 16) & 0xff), + ] + result += [ + UInt8((r >> 8) & 0xff), + UInt8((r >> 0) & 0xff), + ] + + return result + } + + fileprivate func decrypt(block: ArraySlice) -> Array? { + var result = Array() + + var l = UInt32(bytes: block[block.startIndex..> 24) & 0xff), + UInt8((l >> 16) & 0xff), + ] + result += [ + UInt8((l >> 8) & 0xff), + UInt8((l >> 0) & 0xff), + ] + result += [ + UInt8((r >> 24) & 0xff), + UInt8((r >> 16) & 0xff), + ] + result += [ + UInt8((r >> 8) & 0xff), + UInt8((r >> 0) & 0xff), + ] + return result + } + + /// Encrypts the 8-byte padded buffer + /// + /// - Parameters: + /// - l: left half + /// - r: right half + fileprivate func encryptBlowfishBlock(l: inout UInt32, r: inout UInt32) { + var Xl = l + var Xr = r + + for i in 0.. UInt32 { + let f1 = S[0][Int(x >> 24) & 0xff] + let f2 = S[1][Int(x >> 16) & 0xff] + let f3 = S[2][Int(x >> 8) & 0xff] + let f4 = S[3][Int(x & 0xff)] + return ((f1 &+ f2) ^ f3) &+ f4 + } +} + +extension Blowfish: Cipher { + /// Encrypt the 8-byte padded buffer, block by block. Note that for amounts of data larger than a block, it is not safe to just call encrypt() on successive blocks. + /// + /// - Parameter bytes: Plaintext data + /// - Returns: Encrypted data + public func encrypt(_ bytes: C) throws -> Array where C.Element == UInt8, C.Index == Int { + let bytes = padding.add(to: Array(bytes), blockSize: Blowfish.blockSize) // FIXME: Array(bytes) copies + + var out = Array() + out.reserveCapacity(bytes.count) + + for chunk in bytes.batched(by: Blowfish.blockSize) { + out += encryptWorker.encrypt(block: chunk) + } + + if blockMode.options.contains(.paddingRequired) && (out.count % Blowfish.blockSize != 0) { + throw Error.dataPaddingRequired + } + + return out + } + + /// Decrypt the 8-byte padded buffer + /// + /// - Parameter bytes: Ciphertext data + /// - Returns: Plaintext data + public func decrypt(_ bytes: C) throws -> Array where C.Element == UInt8, C.Index == Int { + if blockMode.options.contains(.paddingRequired) && (bytes.count % Blowfish.blockSize != 0) { + throw Error.dataPaddingRequired + } + + var out = Array() + out.reserveCapacity(bytes.count) + + for chunk in Array(bytes).batched(by: Blowfish.blockSize) { + out += decryptWorker.decrypt(block: chunk) // FIXME: copying here is innefective + } + + out = padding.remove(from: out, blockSize: Blowfish.blockSize) + + return out + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/CBCMAC.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/CBCMAC.swift new file mode 100644 index 000000000..e14f2bd52 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/CBCMAC.swift @@ -0,0 +1,104 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public class CBCMAC: Authenticator { + public enum Error: Swift.Error { + case wrongKeyLength + } + + private let key: SecureBytes + + private static let BlockSize: Int = 16 + private static let Zero: Array = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] + private static let Rb: Array = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87] + + public init(key: Array) throws { + if key.count != 16 { + throw Error.wrongKeyLength + } + self.key = SecureBytes(bytes: key) + } + + // MARK: Authenticator + + public func authenticate(_ bytes: Array) throws -> Array { + let aes = try AES(key: Array(key), blockMode: CBC(iv: CBCMAC.Zero), padding: .noPadding) + + let l = try aes.encrypt(CBCMAC.Zero) + var subKey1 = leftShiftOneBit(l) + if (l[0] & 0x80) != 0 { + subKey1 = xor(CBCMAC.Rb, subKey1) + } + var subKey2 = leftShiftOneBit(subKey1) + if (subKey1[0] & 0x80) != 0 { + subKey2 = xor(CBCMAC.Rb, subKey2) + } + + let lastBlockComplete: Bool + let blockCount = (bytes.count + CBCMAC.BlockSize - 1) / CBCMAC.BlockSize + if blockCount == 0 { + lastBlockComplete = false + } else { + lastBlockComplete = bytes.count % CBCMAC.BlockSize == 0 + } + var paddedBytes = bytes + if !lastBlockComplete { + bitPadding(to: &paddedBytes, blockSize: CBCMAC.BlockSize) + } + + var blocks = Array(paddedBytes.batched(by: CBCMAC.BlockSize)) + var lastBlock = blocks.popLast()! + if lastBlockComplete { + lastBlock = xor(lastBlock, subKey1) + } else { + lastBlock = xor(lastBlock, subKey2) + } + + var x = Array(repeating: 0x00, count: CBCMAC.BlockSize) + var y = Array(repeating: 0x00, count: CBCMAC.BlockSize) + for block in blocks { + y = xor(block, x) + x = try aes.encrypt(y) + } + // the difference between CMAC and CBC-MAC is that CMAC xors the final block with a secret value + y = process(lastBlock: lastBlock, with: x) + return try aes.encrypt(y) + } + + func process(lastBlock: ArraySlice, with x: [UInt8]) -> [UInt8] { + return Array(lastBlock) + } + + // MARK: Helper methods + + /** + Performs left shift by one bit to the bit string aquired after concatenating al bytes in the byte array + - parameters: + - bytes: byte array + - returns: bit shifted bit string split again in array of bytes + */ + private func leftShiftOneBit(_ bytes: Array) -> Array { + var shifted = Array(repeating: 0x00, count: bytes.count) + let last = bytes.count - 1 + for index in 0.. +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public final class CMAC: CBCMAC { + override func process(lastBlock: ArraySlice, with x: [UInt8]) -> [UInt8] { + return xor(lastBlock, x) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/ChaCha20.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/ChaCha20.swift new file mode 100644 index 000000000..250ee9d01 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/ChaCha20.swift @@ -0,0 +1,347 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// https://tools.ietf.org/html/rfc7539 +// + +public final class ChaCha20: BlockCipher { + public enum Error: Swift.Error { + case invalidKeyOrInitializationVector + case notSupported + } + + public static let blockSize = 64 // 512 / 8 + public let keySize: Int + + fileprivate let key: Key + fileprivate var counter: Array + + public init(key: Array, iv nonce: Array) throws { + precondition(nonce.count == 12 || nonce.count == 8) + + if key.count != 32 { + throw Error.invalidKeyOrInitializationVector + } + + self.key = Key(bytes: key) + keySize = self.key.count + + if nonce.count == 8 { + counter = [0, 0, 0, 0, 0, 0, 0, 0] + nonce + } else { + counter = [0, 0, 0, 0] + nonce + } + + assert(counter.count == 16) + } + + /// https://tools.ietf.org/html/rfc7539#section-2.3. + fileprivate func core(block: inout Array, counter: Array, key: Array) { + precondition(block.count == ChaCha20.blockSize) + precondition(counter.count == 16) + precondition(key.count == 32) + + let j0: UInt32 = 0x61707865 + let j1: UInt32 = 0x3320646e // 0x3620646e sigma/tau + let j2: UInt32 = 0x79622d32 + let j3: UInt32 = 0x6b206574 + let j4: UInt32 = UInt32(bytes: key[0..<4]).bigEndian + let j5: UInt32 = UInt32(bytes: key[4..<8]).bigEndian + let j6: UInt32 = UInt32(bytes: key[8..<12]).bigEndian + let j7: UInt32 = UInt32(bytes: key[12..<16]).bigEndian + let j8: UInt32 = UInt32(bytes: key[16..<20]).bigEndian + let j9: UInt32 = UInt32(bytes: key[20..<24]).bigEndian + let j10: UInt32 = UInt32(bytes: key[24..<28]).bigEndian + let j11: UInt32 = UInt32(bytes: key[28..<32]).bigEndian + let j12: UInt32 = UInt32(bytes: counter[0..<4]).bigEndian + let j13: UInt32 = UInt32(bytes: counter[4..<8]).bigEndian + let j14: UInt32 = UInt32(bytes: counter[8..<12]).bigEndian + let j15: UInt32 = UInt32(bytes: counter[12..<16]).bigEndian + + var (x0, x1, x2, x3, x4, x5, x6, x7) = (j0, j1, j2, j3, j4, j5, j6, j7) + var (x8, x9, x10, x11, x12, x13, x14, x15) = (j8, j9, j10, j11, j12, j13, j14, j15) + + for _ in 0..<10 { // 20 rounds + x0 = x0 &+ x4 + x12 ^= x0 + x12 = (x12 << 16) | (x12 >> 16) + x8 = x8 &+ x12 + x4 ^= x8 + x4 = (x4 << 12) | (x4 >> 20) + x0 = x0 &+ x4 + x12 ^= x0 + x12 = (x12 << 8) | (x12 >> 24) + x8 = x8 &+ x12 + x4 ^= x8 + x4 = (x4 << 7) | (x4 >> 25) + x1 = x1 &+ x5 + x13 ^= x1 + x13 = (x13 << 16) | (x13 >> 16) + x9 = x9 &+ x13 + x5 ^= x9 + x5 = (x5 << 12) | (x5 >> 20) + x1 = x1 &+ x5 + x13 ^= x1 + x13 = (x13 << 8) | (x13 >> 24) + x9 = x9 &+ x13 + x5 ^= x9 + x5 = (x5 << 7) | (x5 >> 25) + x2 = x2 &+ x6 + x14 ^= x2 + x14 = (x14 << 16) | (x14 >> 16) + x10 = x10 &+ x14 + x6 ^= x10 + x6 = (x6 << 12) | (x6 >> 20) + x2 = x2 &+ x6 + x14 ^= x2 + x14 = (x14 << 8) | (x14 >> 24) + x10 = x10 &+ x14 + x6 ^= x10 + x6 = (x6 << 7) | (x6 >> 25) + x3 = x3 &+ x7 + x15 ^= x3 + x15 = (x15 << 16) | (x15 >> 16) + x11 = x11 &+ x15 + x7 ^= x11 + x7 = (x7 << 12) | (x7 >> 20) + x3 = x3 &+ x7 + x15 ^= x3 + x15 = (x15 << 8) | (x15 >> 24) + x11 = x11 &+ x15 + x7 ^= x11 + x7 = (x7 << 7) | (x7 >> 25) + x0 = x0 &+ x5 + x15 ^= x0 + x15 = (x15 << 16) | (x15 >> 16) + x10 = x10 &+ x15 + x5 ^= x10 + x5 = (x5 << 12) | (x5 >> 20) + x0 = x0 &+ x5 + x15 ^= x0 + x15 = (x15 << 8) | (x15 >> 24) + x10 = x10 &+ x15 + x5 ^= x10 + x5 = (x5 << 7) | (x5 >> 25) + x1 = x1 &+ x6 + x12 ^= x1 + x12 = (x12 << 16) | (x12 >> 16) + x11 = x11 &+ x12 + x6 ^= x11 + x6 = (x6 << 12) | (x6 >> 20) + x1 = x1 &+ x6 + x12 ^= x1 + x12 = (x12 << 8) | (x12 >> 24) + x11 = x11 &+ x12 + x6 ^= x11 + x6 = (x6 << 7) | (x6 >> 25) + x2 = x2 &+ x7 + x13 ^= x2 + x13 = (x13 << 16) | (x13 >> 16) + x8 = x8 &+ x13 + x7 ^= x8 + x7 = (x7 << 12) | (x7 >> 20) + x2 = x2 &+ x7 + x13 ^= x2 + x13 = (x13 << 8) | (x13 >> 24) + x8 = x8 &+ x13 + x7 ^= x8 + x7 = (x7 << 7) | (x7 >> 25) + x3 = x3 &+ x4 + x14 ^= x3 + x14 = (x14 << 16) | (x14 >> 16) + x9 = x9 &+ x14 + x4 ^= x9 + x4 = (x4 << 12) | (x4 >> 20) + x3 = x3 &+ x4 + x14 ^= x3 + x14 = (x14 << 8) | (x14 >> 24) + x9 = x9 &+ x14 + x4 ^= x9 + x4 = (x4 << 7) | (x4 >> 25) + } + + x0 = x0 &+ j0 + x1 = x1 &+ j1 + x2 = x2 &+ j2 + x3 = x3 &+ j3 + x4 = x4 &+ j4 + x5 = x5 &+ j5 + x6 = x6 &+ j6 + x7 = x7 &+ j7 + x8 = x8 &+ j8 + x9 = x9 &+ j9 + x10 = x10 &+ j10 + x11 = x11 &+ j11 + x12 = x12 &+ j12 + x13 = x13 &+ j13 + x14 = x14 &+ j14 + x15 = x15 &+ j15 + + block.replaceSubrange(0..<4, with: x0.bigEndian.bytes()) + block.replaceSubrange(4..<8, with: x1.bigEndian.bytes()) + block.replaceSubrange(8..<12, with: x2.bigEndian.bytes()) + block.replaceSubrange(12..<16, with: x3.bigEndian.bytes()) + block.replaceSubrange(16..<20, with: x4.bigEndian.bytes()) + block.replaceSubrange(20..<24, with: x5.bigEndian.bytes()) + block.replaceSubrange(24..<28, with: x6.bigEndian.bytes()) + block.replaceSubrange(28..<32, with: x7.bigEndian.bytes()) + block.replaceSubrange(32..<36, with: x8.bigEndian.bytes()) + block.replaceSubrange(36..<40, with: x9.bigEndian.bytes()) + block.replaceSubrange(40..<44, with: x10.bigEndian.bytes()) + block.replaceSubrange(44..<48, with: x11.bigEndian.bytes()) + block.replaceSubrange(48..<52, with: x12.bigEndian.bytes()) + block.replaceSubrange(52..<56, with: x13.bigEndian.bytes()) + block.replaceSubrange(56..<60, with: x14.bigEndian.bytes()) + block.replaceSubrange(60..<64, with: x15.bigEndian.bytes()) + } + + // XORKeyStream + func process(bytes: ArraySlice, counter: inout Array, key: Array) -> Array { + precondition(counter.count == 16) + precondition(key.count == 32) + + var block = Array(repeating: 0, count: ChaCha20.blockSize) + var bytesSlice = bytes + var out = Array(reserveCapacity: bytesSlice.count) + + while bytesSlice.count >= ChaCha20.blockSize { + core(block: &block, counter: counter, key: key) + for (i, x) in block.enumerated() { + out.append(bytesSlice[bytesSlice.startIndex + i] ^ x) + } + var u: UInt32 = 1 + for i in 0..<4 { + u += UInt32(counter[i]) + counter[i] = UInt8(u & 0xff) + u >>= 8 + } + bytesSlice = bytesSlice[bytesSlice.startIndex + ChaCha20.blockSize.. 0 { + core(block: &block, counter: counter, key: key) + for (i, v) in bytesSlice.enumerated() { + out.append(v ^ block[i]) + } + } + return out + } +} + +// MARK: Cipher + +extension ChaCha20: Cipher { + public func encrypt(_ bytes: ArraySlice) throws -> Array { + return process(bytes: bytes, counter: &counter, key: Array(key)) + } + + public func decrypt(_ bytes: ArraySlice) throws -> Array { + return try encrypt(bytes) + } +} + +// MARK: Encryptor + +extension ChaCha20 { + public struct ChaChaEncryptor: Cryptor, Updatable { + private var accumulated = Array() + private let chacha: ChaCha20 + + init(chacha: ChaCha20) { + self.chacha = chacha + } + + public mutating func update(withBytes bytes: ArraySlice, isLast: Bool = false) throws -> Array { + accumulated += bytes + + var encrypted = Array() + encrypted.reserveCapacity(accumulated.count) + for chunk in accumulated.batched(by: ChaCha20.blockSize) { + if isLast || accumulated.count >= ChaCha20.blockSize { + encrypted += try chacha.encrypt(chunk) + accumulated.removeFirst(chunk.count) // TODO: improve performance + } + } + return encrypted + } + + public func seek(to: Int) throws { + throw Error.notSupported + } + } +} + +// MARK: Decryptor + +extension ChaCha20 { + public struct ChaChaDecryptor: Cryptor, Updatable { + private var accumulated = Array() + + private var offset: Int = 0 + private var offsetToRemove: Int = 0 + private let chacha: ChaCha20 + + init(chacha: ChaCha20) { + self.chacha = chacha + } + + public mutating func update(withBytes bytes: ArraySlice, isLast: Bool = true) throws -> Array { + // prepend "offset" number of bytes at the beginning + if offset > 0 { + accumulated += Array(repeating: 0, count: offset) + bytes + offsetToRemove = offset + offset = 0 + } else { + accumulated += bytes + } + + var plaintext = Array() + plaintext.reserveCapacity(accumulated.count) + for chunk in accumulated.batched(by: ChaCha20.blockSize) { + if isLast || accumulated.count >= ChaCha20.blockSize { + plaintext += try chacha.decrypt(chunk) + + // remove "offset" from the beginning of first chunk + if offsetToRemove > 0 { + plaintext.removeFirst(offsetToRemove) // TODO: improve performance + offsetToRemove = 0 + } + + accumulated.removeFirst(chunk.count) + } + } + + return plaintext + } + + public func seek(to: Int) throws { + throw Error.notSupported + } + } +} + +// MARK: Cryptors + +extension ChaCha20: Cryptors { + //TODO: Use BlockEncryptor/BlockDecryptor + + public func makeEncryptor() -> Cryptor & Updatable { + return ChaCha20.ChaChaEncryptor(chacha: self) + } + + public func makeDecryptor() -> Cryptor & Updatable { + return ChaCha20.ChaChaDecryptor(chacha: self) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Checksum.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Checksum.swift new file mode 100644 index 000000000..1c4fd48c3 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Checksum.swift @@ -0,0 +1,193 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +/// CRC - cyclic redundancy check code. +public final class Checksum { + private static let table32: Array = [ + 0x0000_0000, 0x7707_3096, 0xEE0E_612C, 0x9909_51BA, 0x076D_C419, 0x706A_F48F, 0xE963_A535, 0x9E64_95A3, + 0x0EDB_8832, 0x79DC_B8A4, 0xE0D5_E91E, 0x97D2_D988, 0x09B6_4C2B, 0x7EB1_7CBD, 0xE7B8_2D07, 0x90BF_1D91, + 0x1DB7_1064, 0x6AB0_20F2, 0xF3B9_7148, 0x84BE_41DE, 0x1ADA_D47D, 0x6DDD_E4EB, 0xF4D4_B551, 0x83D3_85C7, + 0x136C_9856, 0x646B_A8C0, 0xFD62_F97A, 0x8A65_C9EC, 0x1401_5C4F, 0x6306_6CD9, 0xFA0F_3D63, 0x8D08_0DF5, + 0x3B6E_20C8, 0x4C69_105E, 0xD560_41E4, 0xA267_7172, 0x3C03_E4D1, 0x4B04_D447, 0xD20D_85FD, 0xA50A_B56B, + 0x35B5_A8FA, 0x42B2_986C, 0xDBBB_C9D6, 0xACBC_F940, 0x32D8_6CE3, 0x45DF_5C75, 0xDCD6_0DCF, 0xABD1_3D59, + 0x26D9_30AC, 0x51DE_003A, 0xC8D7_5180, 0xBFD0_6116, 0x21B4_F4B5, 0x56B3_C423, 0xCFBA_9599, 0xB8BD_A50F, + 0x2802_B89E, 0x5F05_8808, 0xC60C_D9B2, 0xB10B_E924, 0x2F6F_7C87, 0x5868_4C11, 0xC161_1DAB, 0xB666_2D3D, + 0x76DC_4190, 0x01DB_7106, 0x98D2_20BC, 0xEFD5_102A, 0x71B1_8589, 0x06B6_B51F, 0x9FBF_E4A5, 0xE8B8_D433, + 0x7807_C9A2, 0x0F00_F934, 0x9609_A88E, 0xE10E_9818, 0x7F6A_0DBB, 0x086D_3D2D, 0x9164_6C97, 0xE663_5C01, + 0x6B6B_51F4, 0x1C6C_6162, 0x8565_30D8, 0xF262_004E, 0x6C06_95ED, 0x1B01_A57B, 0x8208_F4C1, 0xF50F_C457, + 0x65B0_D9C6, 0x12B7_E950, 0x8BBE_B8EA, 0xFCB9_887C, 0x62DD_1DDF, 0x15DA_2D49, 0x8CD3_7CF3, 0xFBD4_4C65, + 0x4DB2_6158, 0x3AB5_51CE, 0xA3BC_0074, 0xD4BB_30E2, 0x4ADF_A541, 0x3DD8_95D7, 0xA4D1_C46D, 0xD3D6_F4FB, + 0x4369_E96A, 0x346E_D9FC, 0xAD67_8846, 0xDA60_B8D0, 0x4404_2D73, 0x3303_1DE5, 0xAA0A_4C5F, 0xDD0D_7CC9, + 0x5005_713C, 0x2702_41AA, 0xBE0B_1010, 0xC90C_2086, 0x5768_B525, 0x206F_85B3, 0xB966_D409, 0xCE61_E49F, + 0x5EDE_F90E, 0x29D9_C998, 0xB0D0_9822, 0xC7D7_A8B4, 0x59B3_3D17, 0x2EB4_0D81, 0xB7BD_5C3B, 0xC0BA_6CAD, + 0xEDB8_8320, 0x9ABF_B3B6, 0x03B6_E20C, 0x74B1_D29A, 0xEAD5_4739, 0x9DD2_77AF, 0x04DB_2615, 0x73DC_1683, + 0xE363_0B12, 0x9464_3B84, 0x0D6D_6A3E, 0x7A6A_5AA8, 0xE40E_CF0B, 0x9309_FF9D, 0x0A00_AE27, 0x7D07_9EB1, + 0xF00F_9344, 0x8708_A3D2, 0x1E01_F268, 0x6906_C2FE, 0xF762_575D, 0x8065_67CB, 0x196C_3671, 0x6E6B_06E7, + 0xFED4_1B76, 0x89D3_2BE0, 0x10DA_7A5A, 0x67DD_4ACC, 0xF9B9_DF6F, 0x8EBE_EFF9, 0x17B7_BE43, 0x60B0_8ED5, + 0xD6D6_A3E8, 0xA1D1_937E, 0x38D8_C2C4, 0x4FDF_F252, 0xD1BB_67F1, 0xA6BC_5767, 0x3FB5_06DD, 0x48B2_364B, + 0xD80D_2BDA, 0xAF0A_1B4C, 0x3603_4AF6, 0x4104_7A60, 0xDF60_EFC3, 0xA867_DF55, 0x316E_8EEF, 0x4669_BE79, + 0xCB61_B38C, 0xBC66_831A, 0x256F_D2A0, 0x5268_E236, 0xCC0C_7795, 0xBB0B_4703, 0x2202_16B9, 0x5505_262F, + 0xC5BA_3BBE, 0xB2BD_0B28, 0x2BB4_5A92, 0x5CB3_6A04, 0xC2D7_FFA7, 0xB5D0_CF31, 0x2CD9_9E8B, 0x5BDE_AE1D, + 0x9B64_C2B0, 0xEC63_F226, 0x756A_A39C, 0x026D_930A, 0x9C09_06A9, 0xEB0E_363F, 0x7207_6785, 0x0500_5713, + 0x95BF_4A82, 0xE2B8_7A14, 0x7BB1_2BAE, 0x0CB6_1B38, 0x92D2_8E9B, 0xE5D5_BE0D, 0x7CDC_EFB7, 0x0BDB_DF21, + 0x86D3_D2D4, 0xF1D4_E242, 0x68DD_B3F8, 0x1FDA_836E, 0x81BE_16CD, 0xF6B9_265B, 0x6FB0_77E1, 0x18B7_4777, + 0x8808_5AE6, 0xFF0F_6A70, 0x6606_3BCA, 0x1101_0B5C, 0x8F65_9EFF, 0xF862_AE69, 0x616B_FFD3, 0x166C_CF45, + 0xA00A_E278, 0xD70D_D2EE, 0x4E04_8354, 0x3903_B3C2, 0xA767_2661, 0xD060_16F7, 0x4969_474D, 0x3E6E_77DB, + 0xAED1_6A4A, 0xD9D6_5ADC, 0x40DF_0B66, 0x37D8_3BF0, 0xA9BC_AE53, 0xDEBB_9EC5, 0x47B2_CF7F, 0x30B5_FFE9, + 0xBDBD_F21C, 0xCABA_C28A, 0x53B3_9330, 0x24B4_A3A6, 0xBAD0_3605, 0xCDD7_0693, 0x54DE_5729, 0x23D9_67BF, + 0xB366_7A2E, 0xC461_4AB8, 0x5D68_1B02, 0x2A6F_2B94, 0xB40B_BE37, 0xC30C_8EA1, 0x5A05_DF1B, 0x2D02_EF8D, + ] + + private static let table32c: Array = [ + 0x0000_0000, 0xF26B_8303, 0xE13B_70F7, 0x1350_F3F4, 0xC79A_971F, 0x35F1_141C, 0x26A1_E7E8, 0xD4CA_64EB, + 0x8AD9_58CF, 0x78B2_DBCC, 0x6BE2_2838, 0x9989_AB3B, 0x4D43_CFD0, 0xBF28_4CD3, 0xAC78_BF27, 0x5E13_3C24, + 0x105E_C76F, 0xE235_446C, 0xF165_B798, 0x030E_349B, 0xD7C4_5070, 0x25AF_D373, 0x36FF_2087, 0xC494_A384, + 0x9A87_9FA0, 0x68EC_1CA3, 0x7BBC_EF57, 0x89D7_6C54, 0x5D1D_08BF, 0xAF76_8BBC, 0xBC26_7848, 0x4E4D_FB4B, + 0x20BD_8EDE, 0xD2D6_0DDD, 0xC186_FE29, 0x33ED_7D2A, 0xE727_19C1, 0x154C_9AC2, 0x061C_6936, 0xF477_EA35, + 0xAA64_D611, 0x580F_5512, 0x4B5F_A6E6, 0xB934_25E5, 0x6DFE_410E, 0x9F95_C20D, 0x8CC5_31F9, 0x7EAE_B2FA, + 0x30E3_49B1, 0xC288_CAB2, 0xD1D8_3946, 0x23B3_BA45, 0xF779_DEAE, 0x0512_5DAD, 0x1642_AE59, 0xE429_2D5A, + 0xBA3A_117E, 0x4851_927D, 0x5B01_6189, 0xA96A_E28A, 0x7DA0_8661, 0x8FCB_0562, 0x9C9B_F696, 0x6EF0_7595, + 0x417B_1DBC, 0xB310_9EBF, 0xA040_6D4B, 0x522B_EE48, 0x86E1_8AA3, 0x748A_09A0, 0x67DA_FA54, 0x95B1_7957, + 0xCBA2_4573, 0x39C9_C670, 0x2A99_3584, 0xD8F2_B687, 0x0C38_D26C, 0xFE53_516F, 0xED03_A29B, 0x1F68_2198, + 0x5125_DAD3, 0xA34E_59D0, 0xB01E_AA24, 0x4275_2927, 0x96BF_4DCC, 0x64D4_CECF, 0x7784_3D3B, 0x85EF_BE38, + 0xDBFC_821C, 0x2997_011F, 0x3AC7_F2EB, 0xC8AC_71E8, 0x1C66_1503, 0xEE0D_9600, 0xFD5D_65F4, 0x0F36_E6F7, + 0x61C6_9362, 0x93AD_1061, 0x80FD_E395, 0x7296_6096, 0xA65C_047D, 0x5437_877E, 0x4767_748A, 0xB50C_F789, + 0xEB1F_CBAD, 0x1974_48AE, 0x0A24_BB5A, 0xF84F_3859, 0x2C85_5CB2, 0xDEEE_DFB1, 0xCDBE_2C45, 0x3FD5_AF46, + 0x7198_540D, 0x83F3_D70E, 0x90A3_24FA, 0x62C8_A7F9, 0xB602_C312, 0x4469_4011, 0x5739_B3E5, 0xA552_30E6, + 0xFB41_0CC2, 0x092A_8FC1, 0x1A7A_7C35, 0xE811_FF36, 0x3CDB_9BDD, 0xCEB0_18DE, 0xDDE0_EB2A, 0x2F8B_6829, + 0x82F6_3B78, 0x709D_B87B, 0x63CD_4B8F, 0x91A6_C88C, 0x456C_AC67, 0xB707_2F64, 0xA457_DC90, 0x563C_5F93, + 0x082F_63B7, 0xFA44_E0B4, 0xE914_1340, 0x1B7F_9043, 0xCFB5_F4A8, 0x3DDE_77AB, 0x2E8E_845F, 0xDCE5_075C, + 0x92A8_FC17, 0x60C3_7F14, 0x7393_8CE0, 0x81F8_0FE3, 0x5532_6B08, 0xA759_E80B, 0xB409_1BFF, 0x4662_98FC, + 0x1871_A4D8, 0xEA1A_27DB, 0xF94A_D42F, 0x0B21_572C, 0xDFEB_33C7, 0x2D80_B0C4, 0x3ED0_4330, 0xCCBB_C033, + 0xA24B_B5A6, 0x5020_36A5, 0x4370_C551, 0xB11B_4652, 0x65D1_22B9, 0x97BA_A1BA, 0x84EA_524E, 0x7681_D14D, + 0x2892_ED69, 0xDAF9_6E6A, 0xC9A9_9D9E, 0x3BC2_1E9D, 0xEF08_7A76, 0x1D63_F975, 0x0E33_0A81, 0xFC58_8982, + 0xB215_72C9, 0x407E_F1CA, 0x532E_023E, 0xA145_813D, 0x758F_E5D6, 0x87E4_66D5, 0x94B4_9521, 0x66DF_1622, + 0x38CC_2A06, 0xCAA7_A905, 0xD9F7_5AF1, 0x2B9C_D9F2, 0xFF56_BD19, 0x0D3D_3E1A, 0x1E6D_CDEE, 0xEC06_4EED, + 0xC38D_26C4, 0x31E6_A5C7, 0x22B6_5633, 0xD0DD_D530, 0x0417_B1DB, 0xF67C_32D8, 0xE52C_C12C, 0x1747_422F, + 0x4954_7E0B, 0xBB3F_FD08, 0xA86F_0EFC, 0x5A04_8DFF, 0x8ECE_E914, 0x7CA5_6A17, 0x6FF5_99E3, 0x9D9E_1AE0, + 0xD3D3_E1AB, 0x21B8_62A8, 0x32E8_915C, 0xC083_125F, 0x1449_76B4, 0xE622_F5B7, 0xF572_0643, 0x0719_8540, + 0x590A_B964, 0xAB61_3A67, 0xB831_C993, 0x4A5A_4A90, 0x9E90_2E7B, 0x6CFB_AD78, 0x7FAB_5E8C, 0x8DC0_DD8F, + 0xE330_A81A, 0x115B_2B19, 0x020B_D8ED, 0xF060_5BEE, 0x24AA_3F05, 0xD6C1_BC06, 0xC591_4FF2, 0x37FA_CCF1, + 0x69E9_F0D5, 0x9B82_73D6, 0x88D2_8022, 0x7AB9_0321, 0xAE73_67CA, 0x5C18_E4C9, 0x4F48_173D, 0xBD23_943E, + 0xF36E_6F75, 0x0105_EC76, 0x1255_1F82, 0xE03E_9C81, 0x34F4_F86A, 0xC69F_7B69, 0xD5CF_889D, 0x27A4_0B9E, + 0x79B7_37BA, 0x8BDC_B4B9, 0x988C_474D, 0x6AE7_C44E, 0xBE2D_A0A5, 0x4C46_23A6, 0x5F16_D052, 0xAD7D_5351, + ] + + private static let table16: Array = [ + 0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241, + 0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440, + 0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40, + 0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841, + 0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40, + 0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41, + 0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641, + 0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040, + 0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240, + 0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441, + 0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41, + 0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840, + 0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41, + 0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40, + 0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640, + 0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041, + 0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240, + 0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441, + 0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41, + 0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840, + 0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41, + 0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40, + 0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640, + 0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041, + 0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241, + 0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440, + 0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40, + 0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841, + 0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40, + 0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41, + 0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641, + 0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040, + ] + + /// Polynomial: 0xEDB88320 (Reversed) - IEEE + func crc32(_ message: Array, seed: UInt32? = nil, reflect: Bool = true) -> UInt32 { + var crc: UInt32 = seed != nil ? seed! : 0xFFFF_FFFF + for chunk in message.batched(by: 256) { + for b in chunk { + let idx = Int((crc ^ UInt32(reflect ? b : reversed(b))) & 0xFF) + crc = (crc >> 8) ^ Checksum.table32[idx] + } + } + return (reflect ? crc : reversed(crc)) ^ 0xFFFF_FFFF + } + + /// Polynomial: 0x82F63B78 (Reversed) - Castagnoli + func crc32c(_ message: Array, seed: UInt32? = nil, reflect: Bool = true) -> UInt32 { + var crc: UInt32 = seed != nil ? seed! : 0xFFFF_FFFF + for chunk in message.batched(by: 256) { + for b in chunk { + let idx = Int((crc ^ UInt32(reflect ? b : reversed(b))) & 0xFF) + crc = (crc >> 8) ^ Checksum.table32c[idx] + } + } + return (reflect ? crc : reversed(crc)) ^ 0xFFFF_FFFF + } + + /// Polynomial: 0xA001 (Reversed) - IBM + func crc16(_ message: Array, seed: UInt16? = nil) -> UInt16 { + var crc: UInt16 = seed != nil ? seed! : 0x0000 + for chunk in message.batched(by: 256) { + for b in chunk { + crc = (crc >> 8) ^ Checksum.table16[Int((crc ^ UInt16(b)) & 0xFF)] + } + } + return crc + } +} + +// MARK: Public interface + +public extension Checksum { + /// Calculate CRC32. + /// + /// - parameter message: Message + /// - parameter seed: Seed value (Optional) + /// - parameter reflect: is reflect (default true) + /// + /// - returns: Calculated code + static func crc32(_ message: Array, seed: UInt32? = nil, reflect: Bool = true) -> UInt32 { + return Checksum().crc32(message, seed: seed, reflect: reflect) + } + + /// Calculate CRC32C + /// + /// - parameter message: Message + /// - parameter seed: Seed value (Optional) + /// - parameter reflect: is reflect (default true) + /// + /// - returns: Calculated code + static func crc32c(_ message: Array, seed: UInt32? = nil, reflect: Bool = true) -> UInt32 { + return Checksum().crc32c(message, seed: seed, reflect: reflect) + } + + /// Calculate CRC16 + /// + /// - parameter message: Message + /// - parameter seed: Seed value (Optional) + /// + /// - returns: Calculated code + static func crc16(_ message: Array, seed: UInt16? = nil) -> UInt16 { + return Checksum().crc16(message, seed: seed) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Cipher.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Cipher.swift new file mode 100644 index 000000000..6e2b63622 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Cipher.swift @@ -0,0 +1,47 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public enum CipherError: Error { + case encrypt + case decrypt +} + +public protocol Cipher: class { + var keySize: Int { get } + + /// Encrypt given bytes at once + /// + /// - parameter bytes: Plaintext data + /// - returns: Encrypted data + func encrypt(_ bytes: ArraySlice) throws -> Array + func encrypt(_ bytes: Array) throws -> Array + + /// Decrypt given bytes at once + /// + /// - parameter bytes: Ciphertext data + /// - returns: Plaintext data + func decrypt(_ bytes: ArraySlice) throws -> Array + func decrypt(_ bytes: Array) throws -> Array +} + +extension Cipher { + public func encrypt(_ bytes: Array) throws -> Array { + return try encrypt(bytes.slice) + } + + public func decrypt(_ bytes: Array) throws -> Array { + return try decrypt(bytes.slice) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Collection+Extension.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Collection+Extension.swift new file mode 100644 index 000000000..1b79faad0 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Collection+Extension.swift @@ -0,0 +1,45 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// +extension Collection where Self.Element == UInt8, Self.Index == Int { + // Big endian order + func toUInt32Array() -> Array { + if isEmpty { + return [] + } + + var result = Array(reserveCapacity: 16) + for idx in stride(from: startIndex, to: endIndex, by: 4) { + let val = UInt32(bytes: self, fromIndex: idx).bigEndian + result.append(val) + } + + return result + } + + // Big endian order + func toUInt64Array() -> Array { + if isEmpty { + return [] + } + + var result = Array(reserveCapacity: 32) + for idx in stride(from: startIndex, to: endIndex, by: 8) { + let val = UInt64(bytes: self, fromIndex: idx).bigEndian + result.append(val) + } + + return result + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/CompactMap.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/CompactMap.swift new file mode 100644 index 000000000..74cf92a9c --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/CompactMap.swift @@ -0,0 +1,23 @@ +//// CryptoSwift +// +// Copyright (C) 2014-2018 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +#if swift(>=4.1) + // TODO: remove this file when Xcode 9.2 is no longer used +#else + extension Sequence { + public func compactMap(_ transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] { + return try flatMap(transform) + } + } +#endif diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Cryptor.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Cryptor.swift new file mode 100644 index 000000000..f79f4b359 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Cryptor.swift @@ -0,0 +1,22 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +/// Cryptor (Encryptor or Decryptor) +public protocol Cryptor { + /// Seek to position in file, if block mode allows random access. + /// + /// - parameter to: new value of counter + mutating func seek(to: Int) throws +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Cryptors.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Cryptors.swift new file mode 100644 index 000000000..4baa53bde --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Cryptors.swift @@ -0,0 +1,44 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +#if canImport(Darwin) +import Darwin +#else +import Glibc +#endif + +/// Worker cryptor/decryptor of `Updatable` types +public protocol Cryptors: class { + + /// Cryptor suitable for encryption + func makeEncryptor() throws -> Cryptor & Updatable + + /// Cryptor suitable for decryption + func makeDecryptor() throws -> Cryptor & Updatable + + /// Generate array of random bytes. Helper function. + static func randomIV(_ blockSize: Int) -> Array +} + +extension Cryptors { + public static func randomIV(_ blockSize: Int) -> Array { + var randomIV: Array = Array() + randomIV.reserveCapacity(blockSize) + for randomByte in RandomBytesSequence(size: blockSize) { + randomIV.append(randomByte) + } + return randomIV + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Digest.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Digest.swift new file mode 100644 index 000000000..c3976eada --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Digest.swift @@ -0,0 +1,78 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +@available(*, renamed: "Digest") +public typealias Hash = Digest + +/// Hash functions to calculate Digest. +public struct Digest { + /// Calculate MD5 Digest + /// - parameter bytes: input message + /// - returns: Digest bytes + public static func md5(_ bytes: Array) -> Array { + return MD5().calculate(for: bytes) + } + + /// Calculate SHA1 Digest + /// - parameter bytes: input message + /// - returns: Digest bytes + public static func sha1(_ bytes: Array) -> Array { + return SHA1().calculate(for: bytes) + } + + /// Calculate SHA2-224 Digest + /// - parameter bytes: input message + /// - returns: Digest bytes + public static func sha224(_ bytes: Array) -> Array { + return sha2(bytes, variant: .sha224) + } + + /// Calculate SHA2-256 Digest + /// - parameter bytes: input message + /// - returns: Digest bytes + public static func sha256(_ bytes: Array) -> Array { + return sha2(bytes, variant: .sha256) + } + + /// Calculate SHA2-384 Digest + /// - parameter bytes: input message + /// - returns: Digest bytes + public static func sha384(_ bytes: Array) -> Array { + return sha2(bytes, variant: .sha384) + } + + /// Calculate SHA2-512 Digest + /// - parameter bytes: input message + /// - returns: Digest bytes + public static func sha512(_ bytes: Array) -> Array { + return sha2(bytes, variant: .sha512) + } + + /// Calculate SHA2 Digest + /// - parameter bytes: input message + /// - parameter variant: SHA-2 variant + /// - returns: Digest bytes + public static func sha2(_ bytes: Array, variant: SHA2.Variant) -> Array { + return SHA2(variant: variant).calculate(for: bytes) + } + + /// Calculate SHA3 Digest + /// - parameter bytes: input message + /// - parameter variant: SHA-3 variant + /// - returns: Digest bytes + public static func sha3(_ bytes: Array, variant: SHA3.Variant) -> Array { + return SHA3(variant: variant).calculate(for: bytes) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/DigestType.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/DigestType.swift new file mode 100644 index 000000000..48c40d680 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/DigestType.swift @@ -0,0 +1,18 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +internal protocol DigestType { + func calculate(for bytes: Array) -> Array +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/AES+Foundation.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/AES+Foundation.swift new file mode 100644 index 000000000..ba797337f --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/AES+Foundation.swift @@ -0,0 +1,23 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +import Foundation + +extension AES { + /// Initialize with CBC block mode. + public convenience init(key: String, iv: String, padding: Padding = .pkcs7) throws { + try self.init(key: key.bytes, blockMode: CBC(iv: iv.bytes), padding: padding) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Array+Foundation.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Array+Foundation.swift new file mode 100644 index 000000000..ffab35d4c --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Array+Foundation.swift @@ -0,0 +1,32 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +import Foundation + +public extension Array where Element == UInt8 { + func toBase64() -> String? { + return Data( self).base64EncodedString() + } + + init(base64: String) { + self.init() + + guard let decodedData = Data(base64Encoded: base64) else { + return + } + + append(contentsOf: decodedData.bytes) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Blowfish+Foundation.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Blowfish+Foundation.swift new file mode 100644 index 000000000..be065b92f --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Blowfish+Foundation.swift @@ -0,0 +1,23 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +import Foundation + +extension Blowfish { + /// Initialize with CBC block mode. + public convenience init(key: String, iv: String, padding: Padding = .pkcs7) throws { + try self.init(key: key.bytes, blockMode: CBC(iv: iv.bytes), padding: padding) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/ChaCha20+Foundation.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/ChaCha20+Foundation.swift new file mode 100644 index 000000000..c1f367683 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/ChaCha20+Foundation.swift @@ -0,0 +1,22 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +import Foundation + +extension ChaCha20 { + public convenience init(key: String, iv: String) throws { + try self.init(key: key.bytes, iv: iv.bytes) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Data+Extension.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Data+Extension.swift new file mode 100644 index 000000000..5da7329ad --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Data+Extension.swift @@ -0,0 +1,95 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +import Foundation + +extension Data { + /// Two octet checksum as defined in RFC-4880. Sum of all octets, mod 65536 + public func checksum() -> UInt16 { + var s: UInt32 = 0 + var bytesArray = bytes + for i in 0 ..< bytesArray.count { + s = s + UInt32(bytesArray[i]) + } + s = s % 65536 + return UInt16(s) + } + + public func md5() -> Data { + return Data( Digest.md5(bytes)) + } + + public func sha1() -> Data { + return Data( Digest.sha1(bytes)) + } + + public func sha224() -> Data { + return Data( Digest.sha224(bytes)) + } + + public func sha256() -> Data { + return Data( Digest.sha256(bytes)) + } + + public func sha384() -> Data { + return Data( Digest.sha384(bytes)) + } + + public func sha512() -> Data { + return Data( Digest.sha512(bytes)) + } + + public func sha3(_ variant: SHA3.Variant) -> Data { + return Data( Digest.sha3(bytes, variant: variant)) + } + + public func crc32(seed: UInt32? = nil, reflect: Bool = true) -> Data { + return Data( Checksum.crc32(bytes, seed: seed, reflect: reflect).bytes()) + } + + public func crc32c(seed: UInt32? = nil, reflect: Bool = true) -> Data { + return Data( Checksum.crc32c(bytes, seed: seed, reflect: reflect).bytes()) + } + + public func crc16(seed: UInt16? = nil) -> Data { + return Data( Checksum.crc16(bytes, seed: seed).bytes()) + } + + public func encrypt(cipher: Cipher) throws -> Data { + return Data( try cipher.encrypt(bytes.slice)) + } + + public func decrypt(cipher: Cipher) throws -> Data { + return Data( try cipher.decrypt(bytes.slice)) + } + + public func authenticate(with authenticator: Authenticator) throws -> Data { + return Data( try authenticator.authenticate(bytes)) + } +} + +extension Data { + public init(hex: String) { + self.init(Array(hex: hex)) + } + + public var bytes: Array { + return Array(self) + } + + public func toHexString() -> String { + return bytes.toHexString() + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/HMAC+Foundation.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/HMAC+Foundation.swift new file mode 100644 index 000000000..fd4d77cda --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/HMAC+Foundation.swift @@ -0,0 +1,22 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +import Foundation + +extension HMAC { + public convenience init(key: String, variant: HMAC.Variant = .md5) throws { + self.init(key: key.bytes, variant: variant) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Rabbit+Foundation.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Rabbit+Foundation.swift new file mode 100644 index 000000000..2a497e660 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Rabbit+Foundation.swift @@ -0,0 +1,26 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +import Foundation + +extension Rabbit { + public convenience init(key: String) throws { + try self.init(key: key.bytes) + } + + public convenience init(key: String, iv: String) throws { + try self.init(key: key.bytes, iv: iv.bytes) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/String+FoundationExtension.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/String+FoundationExtension.swift new file mode 100644 index 000000000..5cd7e9dce --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/String+FoundationExtension.swift @@ -0,0 +1,41 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +import Foundation + +extension String { + /// Return Base64 back to String + public func decryptBase64ToString(cipher: Cipher) throws -> String { + guard let decodedData = Data(base64Encoded: self, options: []) else { + throw CipherError.decrypt + } + + let decrypted = try decodedData.decrypt(cipher: cipher) + + if let decryptedString = String(data: decrypted, encoding: String.Encoding.utf8) { + return decryptedString + } + + throw CipherError.decrypt + } + + public func decryptBase64(cipher: Cipher) throws -> Array { + guard let decodedData = Data(base64Encoded: self, options: []) else { + throw CipherError.decrypt + } + + return try decodedData.decrypt(cipher: cipher).bytes + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Utils+Foundation.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Utils+Foundation.swift new file mode 100644 index 000000000..f94536508 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Utils+Foundation.swift @@ -0,0 +1,27 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +import Foundation + +func perf(_ text: String, closure: () -> Void) { + let measurementStart = Date() + + closure() + + let measurementStop = Date() + let executionTime = measurementStop.timeIntervalSince(measurementStart) + + print("\(text) \(executionTime)") +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Generics.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Generics.swift new file mode 100644 index 000000000..9c81e1092 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Generics.swift @@ -0,0 +1,55 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +/** build bit pattern from array of bits */ +//@_specialize(exported: true, where T == UInt8) +func integerFrom(_ bits: Array) -> T { + var bitPattern: T = 0 + for idx in bits.indices { + if bits[idx] == Bit.one { + let bit = T(UInt64(1) << UInt64(idx)) + bitPattern = bitPattern | bit + } + } + return bitPattern +} + +/// Array of bytes. Caution: don't use directly because generic is slow. +/// +/// - parameter value: integer value +/// - parameter length: length of output array. By default size of value type +/// +/// - returns: Array of bytes +//@_specialize(exported: true, where T == Int) +//@_specialize(exported: true, where T == UInt) +//@_specialize(exported: true, where T == UInt8) +//@_specialize(exported: true, where T == UInt16) +//@_specialize(exported: true, where T == UInt32) +//@_specialize(exported: true, where T == UInt64) +func arrayOfBytes(value: T, length totalBytes: Int = MemoryLayout.size) -> Array { + let valuePointer = UnsafeMutablePointer.allocate(capacity: 1) + valuePointer.pointee = value + + let bytesPointer = UnsafeMutablePointer(OpaquePointer(valuePointer)) + var bytes = Array(repeating: 0, count: totalBytes) + for j in 0...size, totalBytes) { + bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee + } + + valuePointer.deinitialize(count: 1) + valuePointer.deallocate() + + return bytes +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/HKDF.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/HKDF.swift new file mode 100644 index 000000000..daa8bbff8 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/HKDF.swift @@ -0,0 +1,84 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// https://www.ietf.org/rfc/rfc5869.txt +// + +#if canImport(Darwin) +import Darwin +#else +import Glibc +#endif + +/// A key derivation function. +/// +/// HKDF - HMAC-based Extract-and-Expand Key Derivation Function. +public struct HKDF { + public enum Error: Swift.Error { + case invalidInput + case derivedKeyTooLong + } + + private let numBlocks: Int // l + private let dkLen: Int + private let info: Array + fileprivate let prk: Array + fileprivate let variant: HMAC.Variant + + /// - parameters: + /// - variant: hash variant + /// - salt: optional salt (if not provided, it is set to a sequence of variant.digestLength zeros) + /// - info: optional context and application specific information + /// - keyLength: intended length of derived key + public init(password: Array, salt: Array? = nil, info: Array? = nil, keyLength: Int? = nil /* dkLen */, variant: HMAC.Variant = .sha256) throws { + guard !password.isEmpty else { + throw Error.invalidInput + } + + let dkLen = keyLength ?? variant.digestLength + let keyLengthFinal = Double(dkLen) + let hLen = Double(variant.digestLength) + let numBlocks = Int(ceil(keyLengthFinal / hLen)) // l = ceil(keyLength / hLen) + guard numBlocks <= 255 else { + throw Error.derivedKeyTooLong + } + + /// HKDF-Extract(salt, password) -> PRK + /// - PRK - a pseudo-random key; it is used by calculate() + prk = try HMAC(key: salt ?? [], variant: variant).authenticate(password) + self.info = info ?? [] + self.variant = variant + self.dkLen = dkLen + self.numBlocks = numBlocks + } + + public func calculate() throws -> Array { + let hmac = HMAC(key: prk, variant: variant) + var ret = Array() + ret.reserveCapacity(numBlocks * variant.digestLength) + var value = Array() + for i in 1...numBlocks { + value.append(contentsOf: info) + value.append(UInt8(i)) + + let bytes = try hmac.authenticate(value) + ret.append(contentsOf: bytes) + + /// update value to use it as input for next iteration + value = bytes + } + return Array(ret.prefix(dkLen)) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/HMAC.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/HMAC.swift new file mode 100644 index 000000000..c5bfe3d3c --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/HMAC.swift @@ -0,0 +1,102 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public final class HMAC: Authenticator { + public enum Error: Swift.Error { + case authenticateError + case invalidInput + } + + public enum Variant { + case sha1, sha256, sha384, sha512, md5 + + var digestLength: Int { + switch self { + case .sha1: + return SHA1.digestLength + case .sha256: + return SHA2.Variant.sha256.digestLength + case .sha384: + return SHA2.Variant.sha384.digestLength + case .sha512: + return SHA2.Variant.sha512.digestLength + case .md5: + return MD5.digestLength + } + } + + func calculateHash(_ bytes: Array) -> Array { + switch self { + case .sha1: + return Digest.sha1(bytes) + case .sha256: + return Digest.sha256(bytes) + case .sha384: + return Digest.sha384(bytes) + case .sha512: + return Digest.sha512(bytes) + case .md5: + return Digest.md5(bytes) + } + } + + func blockSize() -> Int { + switch self { + case .md5: + return MD5.blockSize + case .sha1, .sha256: + return 64 + case .sha384, .sha512: + return 128 + } + } + } + + var key: Array + let variant: Variant + + public init(key: Array, variant: HMAC.Variant = .md5) { + self.variant = variant + self.key = key + + if key.count > variant.blockSize() { + let hash = variant.calculateHash(key) + self.key = hash + } + + if key.count < variant.blockSize() { + self.key = ZeroPadding().add(to: key, blockSize: variant.blockSize()) + } + } + + // MARK: Authenticator + + public func authenticate(_ bytes: Array) throws -> Array { + var opad = Array(repeating: 0x5c, count: variant.blockSize()) + for idx in key.indices { + opad[idx] = key[idx] ^ opad[idx] + } + var ipad = Array(repeating: 0x36, count: variant.blockSize()) + for idx in key.indices { + ipad[idx] = key[idx] ^ ipad[idx] + } + + let ipadAndMessageHash = variant.calculateHash(ipad + bytes) + let result = variant.calculateHash(opad + ipadAndMessageHash) + + // return Array(result[0..<10]) // 80 bits + return result + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Int+Extension.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Int+Extension.swift new file mode 100644 index 000000000..98b14762f --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Int+Extension.swift @@ -0,0 +1,38 @@ +// +// CryptoSwift +// +// Created by Marcin Krzyzanowski on 12/08/14. +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +#if canImport(Darwin) +import Darwin +#else +import Glibc +#endif + +/* array of bits */ +extension Int { + init(bits: [Bit]) { + self.init(bitPattern: integerFrom(bits) as UInt) + } +} + +extension FixedWidthInteger { + @_transparent + func bytes(totalBytes: Int = MemoryLayout.size) -> Array { + return arrayOfBytes(value: self.littleEndian, length: totalBytes) + // TODO: adjust bytes order + // var value = self.littleEndian + // return withUnsafeBytes(of: &value, Array.init).reversed() + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/MD5.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/MD5.swift new file mode 100644 index 000000000..7f44b4a28 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/MD5.swift @@ -0,0 +1,165 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public final class MD5: DigestType { + static let blockSize: Int = 64 + static let digestLength: Int = 16 // 128 / 8 + fileprivate static let hashInitialValue: Array = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] + + fileprivate var accumulated = Array() + fileprivate var processedBytesTotalCount: Int = 0 + fileprivate var accumulatedHash: Array = MD5.hashInitialValue + + /** specifies the per-round shift amounts */ + private let s: Array = [ + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, + 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, + 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, + 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, + ] + + /** binary integer part of the sines of integers (Radians) */ + private let k: Array = [ + 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, + 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, + 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, + 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, + 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, + 0xd62f105d, 0x2441453, 0xd8a1e681, 0xe7d3fbc8, + 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, + 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, + 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, + 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, + 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05, + 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, + 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, + 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, + 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, + 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391, + ] + + public init() { + } + + public func calculate(for bytes: Array) -> Array { + do { + return try update(withBytes: bytes.slice, isLast: true) + } catch { + fatalError() + } + } + + // mutating currentHash in place is way faster than returning new result + fileprivate func process(block chunk: ArraySlice, currentHash: inout Array) { + assert(chunk.count == 16 * 4) + + // Initialize hash value for this chunk: + var A: UInt32 = currentHash[0] + var B: UInt32 = currentHash[1] + var C: UInt32 = currentHash[2] + var D: UInt32 = currentHash[3] + + var dTemp: UInt32 = 0 + + // Main loop + for j in 0.., isLast: Bool = false) throws -> Array { + accumulated += bytes + + if isLast { + let lengthInBits = (processedBytesTotalCount + accumulated.count) * 8 + let lengthBytes = lengthInBits.bytes(totalBytes: 64 / 8) // A 64-bit representation of b + + // Step 1. Append padding + bitPadding(to: &accumulated, blockSize: MD5.blockSize, allowance: 64 / 8) + + // Step 2. Append Length a 64-bit representation of lengthInBits + accumulated += lengthBytes.reversed() + } + + var processedBytes = 0 + for chunk in accumulated.batched(by: MD5.blockSize) { + if isLast || (accumulated.count - processedBytes) >= MD5.blockSize { + process(block: chunk, currentHash: &accumulatedHash) + processedBytes += chunk.count + } + } + accumulated.removeFirst(processedBytes) + processedBytesTotalCount += processedBytes + + // output current hash + var result = Array() + result.reserveCapacity(MD5.digestLength) + + for hElement in accumulatedHash { + let hLE = hElement.littleEndian + result += Array(arrayLiteral: UInt8(hLE & 0xff), UInt8((hLE >> 8) & 0xff), UInt8((hLE >> 16) & 0xff), UInt8((hLE >> 24) & 0xff)) + } + + // reset hash value for instance + if isLast { + accumulatedHash = MD5.hashInitialValue + } + + return result + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/NoPadding.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/NoPadding.swift new file mode 100644 index 000000000..57670ad36 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/NoPadding.swift @@ -0,0 +1,27 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +struct NoPadding: PaddingProtocol { + init() { + } + + func add(to data: Array, blockSize _: Int) -> Array { + return data + } + + func remove(from data: Array, blockSize _: Int?) -> Array { + return data + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Operators.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Operators.swift new file mode 100644 index 000000000..a15fe3c95 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Operators.swift @@ -0,0 +1,32 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +/* + Bit shifting with overflow protection using overflow operator "&". + Approach is consistent with standard overflow operators &+, &-, &*, &/ + and introduce new overflow operators for shifting: &<<, &>> + + Note: Works with unsigned integers values only + + Usage + + var i = 1 // init + var j = i &<< 2 //shift left + j &<<= 2 //shift left and assign + + @see: https://medium.com/@krzyzanowskim/swiftly-shift-bits-and-protect-yourself-be33016ce071 + + This fuctonality is now implemented as part of Swift 3, SE-0104 https://github.com/apple/swift-evolution/blob/master/proposals/0104-improved-integers.md + */ diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PBKDF1.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PBKDF1.swift new file mode 100644 index 000000000..953b36ebd --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PBKDF1.swift @@ -0,0 +1,87 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public extension PKCS5 { + /// A key derivation function. + /// + /// PBKDF1 is recommended only for compatibility with existing + /// applications since the keys it produces may not be large enough for + /// some applications. + struct PBKDF1 { + public enum Error: Swift.Error { + case invalidInput + case derivedKeyTooLong + } + + public enum Variant { + case md5, sha1 + + var size: Int { + switch self { + case .md5: + return MD5.digestLength + case .sha1: + return SHA1.digestLength + } + } + + fileprivate func calculateHash(_ bytes: Array) -> Array { + switch self { + case .sha1: + return Digest.sha1(bytes) + case .md5: + return Digest.md5(bytes) + } + } + } + + private let iterations: Int // c + private let variant: Variant + private let keyLength: Int + private let t1: Array + + /// - parameters: + /// - salt: salt, an eight-bytes + /// - variant: hash variant + /// - iterations: iteration count, a positive integer + /// - keyLength: intended length of derived key + public init(password: Array, salt: Array, variant: Variant = .sha1, iterations: Int = 4096 /* c */, keyLength: Int? = nil /* dkLen */ ) throws { + precondition(iterations > 0) + precondition(salt.count == 8) + + let keyLength = keyLength ?? variant.size + + if keyLength > variant.size { + throw Error.derivedKeyTooLong + } + + let t1 = variant.calculateHash(password + salt) + + self.iterations = iterations + self.variant = variant + self.keyLength = keyLength + self.t1 = t1 + } + + /// Apply the underlying hash function Hash for c iterations + public func calculate() -> Array { + var t = t1 + for _ in 2...iterations { + t = variant.calculateHash(t) + } + return Array(t[0.. +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// https://www.ietf.org/rfc/rfc2898.txt +// + +#if canImport(Darwin) +import Darwin +#else +import Glibc +#endif + +public extension PKCS5 { + /// A key derivation function. + /// + /// PBKDF2 - Password-Based Key Derivation Function 2. Key stretching technique. + /// DK = PBKDF2(PRF, Password, Salt, c, dkLen) + struct PBKDF2 { + public enum Error: Swift.Error { + case invalidInput + case derivedKeyTooLong + } + + private let salt: Array // S + fileprivate let iterations: Int // c + private let numBlocks: Int // l + private let dkLen: Int + fileprivate let prf: HMAC + + /// - parameters: + /// - salt: salt + /// - variant: hash variant + /// - iterations: iteration count, a positive integer + /// - keyLength: intended length of derived key + /// - variant: MAC variant. Defaults to SHA256 + public init(password: Array, salt: Array, iterations: Int = 4096 /* c */, keyLength: Int? = nil /* dkLen */, variant: HMAC.Variant = .sha256) throws { + precondition(iterations > 0) + + let prf = HMAC(key: password, variant: variant) + + guard iterations > 0 && !salt.isEmpty else { + throw Error.invalidInput + } + + dkLen = keyLength ?? variant.digestLength + let keyLengthFinal = Double(dkLen) + let hLen = Double(prf.variant.digestLength) + if keyLengthFinal > (pow(2, 32) - 1) * hLen { + throw Error.derivedKeyTooLong + } + + self.salt = salt + self.iterations = iterations + self.prf = prf + + numBlocks = Int(ceil(Double(keyLengthFinal) / hLen)) // l = ceil(keyLength / hLen) + } + + public func calculate() throws -> Array { + var ret = Array() + ret.reserveCapacity(numBlocks * prf.variant.digestLength) + for i in 1...numBlocks { + // for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter + if let value = try calculateBlock(self.salt, blockNum: i) { + ret.append(contentsOf: value) + } + } + return Array(ret.prefix(dkLen)) + } + } +} + +fileprivate extension PKCS5.PBKDF2 { + func ARR(_ i: Int) -> Array { + var inti = Array(repeating: 0, count: 4) + inti[0] = UInt8((i >> 24) & 0xff) + inti[1] = UInt8((i >> 16) & 0xff) + inti[2] = UInt8((i >> 8) & 0xff) + inti[3] = UInt8(i & 0xff) + return inti + } + + // F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c + // U_1 = PRF (P, S || INT (i)) + func calculateBlock(_ salt: Array, blockNum: Int) throws -> Array? { + guard let u1 = try? prf.authenticate(salt + ARR(blockNum)) else { // blockNum.bytes() is slower + return nil + } + + var u = u1 + var ret = u + if iterations > 1 { + // U_2 = PRF (P, U_1) , + // U_c = PRF (P, U_{c-1}) . + for _ in 2...iterations { + u = try prf.authenticate(u) + for x in 0.. +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// PKCS is a group of public-key cryptography standards devised +// and published by RSA Security Inc, starting in the early 1990s. +// + +public enum PKCS5 { + typealias Padding = PKCS7Padding +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS7.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS7.swift new file mode 100644 index 000000000..9c0128494 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS7.swift @@ -0,0 +1,18 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public enum PKCS7 { + typealias Padding = PKCS7Padding +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS7Padding.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS7Padding.swift new file mode 100644 index 000000000..37cd165e4 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS7Padding.swift @@ -0,0 +1,64 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// PKCS is a group of public-key cryptography standards devised +// and published by RSA Security Inc, starting in the early 1990s. +// + +struct PKCS7Padding: PaddingProtocol { + enum Error: Swift.Error { + case invalidPaddingValue + } + + init() { + } + + func add(to bytes: Array, blockSize: Int) -> Array { + let padding = UInt8(blockSize - (bytes.count % blockSize)) + var withPadding = bytes + if padding == 0 { + // If the original data is a multiple of N bytes, then an extra block of bytes with value N is added. + for _ in 0..(arrayLiteral: UInt8(blockSize)) + } + } else { + // The value of each added byte is the number of bytes that are added + for _ in 0..(arrayLiteral: UInt8(padding)) + } + } + return withPadding + } + + func remove(from bytes: Array, blockSize _: Int?) -> Array { + guard !bytes.isEmpty, let lastByte = bytes.last else { + return bytes + } + + assert(!bytes.isEmpty, "Need bytes to remove padding") + + let padding = Int(lastByte) // last byte + let finalLength = bytes.count - padding + + if finalLength < 0 { + return bytes + } + + if padding >= 1 { + return Array(bytes[0.. +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public protocol PaddingProtocol { + func add(to: Array, blockSize: Int) -> Array + func remove(from: Array, blockSize: Int?) -> Array +} + +public enum Padding: PaddingProtocol { + case noPadding, zeroPadding, pkcs7, pkcs5 + + public func add(to: Array, blockSize: Int) -> Array { + switch self { + case .noPadding: + return to // NoPadding().add(to: to, blockSize: blockSize) + case .zeroPadding: + return ZeroPadding().add(to: to, blockSize: blockSize) + case .pkcs7: + return PKCS7.Padding().add(to: to, blockSize: blockSize) + case .pkcs5: + return PKCS5.Padding().add(to: to, blockSize: blockSize) + } + } + + public func remove(from: Array, blockSize: Int?) -> Array { + switch self { + case .noPadding: + return from //NoPadding().remove(from: from, blockSize: blockSize) + case .zeroPadding: + return ZeroPadding().remove(from: from, blockSize: blockSize) + case .pkcs7: + return PKCS7.Padding().remove(from: from, blockSize: blockSize) + case .pkcs5: + return PKCS5.Padding().remove(from: from, blockSize: blockSize) + } + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Poly1305.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Poly1305.swift new file mode 100644 index 000000000..c97f94044 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Poly1305.swift @@ -0,0 +1,165 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// http://tools.ietf.org/html/draft-agl-tls-chacha20poly1305-04#section-4 +// nacl/crypto_onetimeauth/poly1305/ref/auth.c +// +/// Poly1305 takes a 32-byte, one-time key and a message and produces a 16-byte tag that authenticates the +/// message such that an attacker has a negligible chance of producing a valid tag for an inauthentic message. + +public final class Poly1305: Authenticator { + public enum Error: Swift.Error { + case authenticateError + } + + public static let blockSize: Int = 16 + + private let key: SecureBytes + + /// - parameter key: 32-byte key + public init(key: Array) { + self.key = SecureBytes(bytes: key) + } + + private func squeeze(h: inout Array) { + assert(h.count == 17) + var u: UInt32 = 0 + for j in 0..<16 { + u = u &+ h[j] + h[j] = u & 255 + u = u >> 8 + } + + u = u &+ h[16] + h[16] = u & 3 + u = 5 * (u >> 2) + + for j in 0..<16 { + u = u &+ h[j] + h[j] = u & 255 + u = u >> 8 + } + + u = u &+ h[16] + h[16] = u + } + + private func add(h: inout Array, c: Array) { + assert(h.count == 17 && c.count == 17) + + var u: UInt32 = 0 + for j in 0..<17 { + u = u &+ (h[j] &+ c[j]) + h[j] = u & 255 + u = u >> 8 + } + } + + private func mulmod(h: inout Array, r: Array) { + var hr = Array(repeating: 0, count: 17) + var u: UInt32 = 0 + for i in 0..<17 { + u = 0 + for j in 0...i { + u = u &+ (h[j] * r[i &- j]) + } + for j in (i + 1)..<17 { + u = u &+ (320 * h[j] * r[i &+ 17 &- j]) + } + hr[i] = u + } + h = hr + squeeze(h: &h) + } + + private func freeze(h: inout Array) { + let horig = h + add(h: &h, c: [5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 252]) + let negative = UInt32(bitPattern: -Int32(h[16] >> 7)) + for j in 0..<17 { + h[j] ^= negative & (horig[j] ^ h[j]) + } + } + + /// the key is partitioned into two parts, called "r" and "s" + fileprivate func onetimeauth(message input: Array, key k: Array) -> Array { + // clamp + var r = Array(repeating: 0, count: 17) + var h = Array(repeating: 0, count: 17) + var c = Array(repeating: 0, count: 17) + + r[0] = UInt32(k[0]) + r[1] = UInt32(k[1]) + r[2] = UInt32(k[2]) + r[3] = UInt32(k[3] & 15) + r[4] = UInt32(k[4] & 252) + r[5] = UInt32(k[5]) + r[6] = UInt32(k[6]) + r[7] = UInt32(k[7] & 15) + r[8] = UInt32(k[8] & 252) + r[9] = UInt32(k[9]) + r[10] = UInt32(k[10]) + r[11] = UInt32(k[11] & 15) + r[12] = UInt32(k[12] & 252) + r[13] = UInt32(k[13]) + r[14] = UInt32(k[14]) + r[15] = UInt32(k[15] & 15) + r[16] = 0 + + var inlen = input.count + var inpos = 0 + while inlen > 0 { + for j in 0..) throws -> Array { + return onetimeauth(message: bytes, key: Array(key)) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Rabbit.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Rabbit.swift new file mode 100644 index 000000000..974ae90ce --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Rabbit.swift @@ -0,0 +1,217 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public final class Rabbit: BlockCipher { + public enum Error: Swift.Error { + case invalidKeyOrInitializationVector + } + + /// Size of IV in bytes + public static let ivSize = 64 / 8 + + /// Size of key in bytes + public static let keySize = 128 / 8 + + /// Size of block in bytes + public static let blockSize = 128 / 8 + + public var keySize: Int { + return key.count + } + + /// Key + private let key: Key + + /// IV (optional) + private let iv: Array? + + /// State variables + private var x = Array(repeating: 0, count: 8) + + /// Counter variables + private var c = Array(repeating: 0, count: 8) + + /// Counter carry + private var p7: UInt32 = 0 + + /// 'a' constants + private var a: Array = [ + 0x4d34d34d, + 0xd34d34d3, + 0x34d34d34, + 0x4d34d34d, + 0xd34d34d3, + 0x34d34d34, + 0x4d34d34d, + 0xd34d34d3, + ] + + // MARK: - Initializers + + public convenience init(key: Array) throws { + try self.init(key: key, iv: nil) + } + + public init(key: Array, iv: Array?) throws { + self.key = Key(bytes: key) + self.iv = iv + + guard key.count == Rabbit.keySize && (iv == nil || iv!.count == Rabbit.ivSize) else { + throw Error.invalidKeyOrInitializationVector + } + } + + // MARK: - + + fileprivate func setup() { + p7 = 0 + + // Key divided into 8 subkeys + var k = Array(repeating: 0, count: 8) + for j in 0..<8 { + k[j] = UInt32(key[Rabbit.blockSize - (2 * j + 1)]) | (UInt32(key[Rabbit.blockSize - (2 * j + 2)]) << 8) + } + + // Initialize state and counter variables from subkeys + for j in 0..<8 { + if j % 2 == 0 { + x[j] = (k[(j + 1) % 8] << 16) | k[j] + c[j] = (k[(j + 4) % 8] << 16) | k[(j + 5) % 8] + } else { + x[j] = (k[(j + 5) % 8] << 16) | k[(j + 4) % 8] + c[j] = (k[j] << 16) | k[(j + 1) % 8] + } + } + + // Iterate system four times + nextState() + nextState() + nextState() + nextState() + + // Reinitialize counter variables + for j in 0..<8 { + c[j] = c[j] ^ x[(j + 4) % 8] + } + + if let iv = iv { + setupIV(iv) + } + } + + private func setupIV(_ iv: Array) { + // 63...56 55...48 47...40 39...32 31...24 23...16 15...8 7...0 IV bits + // 0 1 2 3 4 5 6 7 IV bytes in array + let iv0 = UInt32(bytes: [iv[4], iv[5], iv[6], iv[7]]) + let iv1 = UInt32(bytes: [iv[0], iv[1], iv[4], iv[5]]) + let iv2 = UInt32(bytes: [iv[0], iv[1], iv[2], iv[3]]) + let iv3 = UInt32(bytes: [iv[2], iv[3], iv[6], iv[7]]) + + // Modify the counter state as function of the IV + c[0] = c[0] ^ iv0 + c[1] = c[1] ^ iv1 + c[2] = c[2] ^ iv2 + c[3] = c[3] ^ iv3 + c[4] = c[4] ^ iv0 + c[5] = c[5] ^ iv1 + c[6] = c[6] ^ iv2 + c[7] = c[7] ^ iv3 + + // Iterate system four times + nextState() + nextState() + nextState() + nextState() + } + + private func nextState() { + // Before an iteration the counters are incremented + var carry = p7 + for j in 0..<8 { + let prev = c[j] + c[j] = prev &+ a[j] &+ carry + carry = prev > c[j] ? 1 : 0 // detect overflow + } + p7 = carry // save last carry bit + + // Iteration of the system + var newX = Array(repeating: 0, count: 8) + newX[0] = g(0) &+ rotateLeft(g(7), by: 16) &+ rotateLeft(g(6), by: 16) + newX[1] = g(1) &+ rotateLeft(g(0), by: 8) &+ g(7) + newX[2] = g(2) &+ rotateLeft(g(1), by: 16) &+ rotateLeft(g(0), by: 16) + newX[3] = g(3) &+ rotateLeft(g(2), by: 8) &+ g(1) + newX[4] = g(4) &+ rotateLeft(g(3), by: 16) &+ rotateLeft(g(2), by: 16) + newX[5] = g(5) &+ rotateLeft(g(4), by: 8) &+ g(3) + newX[6] = g(6) &+ rotateLeft(g(5), by: 16) &+ rotateLeft(g(4), by: 16) + newX[7] = g(7) &+ rotateLeft(g(6), by: 8) &+ g(5) + x = newX + } + + private func g(_ j: Int) -> UInt32 { + let sum = x[j] &+ c[j] + let square = UInt64(sum) * UInt64(sum) + return UInt32(truncatingIfNeeded: square ^ (square >> 32)) + } + + fileprivate func nextOutput() -> Array { + nextState() + + var output16 = Array(repeating: 0, count: Rabbit.blockSize / 2) + output16[7] = UInt16(truncatingIfNeeded: x[0]) ^ UInt16(truncatingIfNeeded: x[5] >> 16) + output16[6] = UInt16(truncatingIfNeeded: x[0] >> 16) ^ UInt16(truncatingIfNeeded: x[3]) + output16[5] = UInt16(truncatingIfNeeded: x[2]) ^ UInt16(truncatingIfNeeded: x[7] >> 16) + output16[4] = UInt16(truncatingIfNeeded: x[2] >> 16) ^ UInt16(truncatingIfNeeded: x[5]) + output16[3] = UInt16(truncatingIfNeeded: x[4]) ^ UInt16(truncatingIfNeeded: x[1] >> 16) + output16[2] = UInt16(truncatingIfNeeded: x[4] >> 16) ^ UInt16(truncatingIfNeeded: x[7]) + output16[1] = UInt16(truncatingIfNeeded: x[6]) ^ UInt16(truncatingIfNeeded: x[3] >> 16) + output16[0] = UInt16(truncatingIfNeeded: x[6] >> 16) ^ UInt16(truncatingIfNeeded: x[1]) + + var output8 = Array(repeating: 0, count: Rabbit.blockSize) + for j in 0..> 8) + output8[j * 2 + 1] = UInt8(truncatingIfNeeded: output16[j]) + } + return output8 + } +} + +// MARK: Cipher + +extension Rabbit: Cipher { + public func encrypt(_ bytes: ArraySlice) throws -> Array { + setup() + + var result = Array(repeating: 0, count: bytes.count) + var output = nextOutput() + var byteIdx = 0 + var outputIdx = 0 + while byteIdx < bytes.count { + if outputIdx == Rabbit.blockSize { + output = nextOutput() + outputIdx = 0 + } + + result[byteIdx] = bytes[byteIdx] ^ output[outputIdx] + + byteIdx += 1 + outputIdx += 1 + } + return result + } + + public func decrypt(_ bytes: ArraySlice) throws -> Array { + return try encrypt(bytes) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/RandomBytesSequence.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/RandomBytesSequence.swift new file mode 100644 index 000000000..be7bdcb74 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/RandomBytesSequence.swift @@ -0,0 +1,50 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +struct RandomBytesSequence: Sequence { + let size: Int + + func makeIterator() -> AnyIterator { + var count = 0 + return AnyIterator.init { () -> UInt8? in + guard count < self.size else { + return nil + } + count = count + 1 + + #if os(Linux) || os(Android) || os(FreeBSD) + let fd = open("/dev/urandom", O_RDONLY) + if fd <= 0 { + return nil + } + + var value: UInt8 = 0 + let result = read(fd, &value, MemoryLayout.size) + precondition(result == 1) + + close(fd) + return value + #else + return UInt8(arc4random_uniform(UInt32(UInt8.max) + 1)) + #endif + } + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/SHA1.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/SHA1.swift new file mode 100644 index 000000000..61f6bce3f --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/SHA1.swift @@ -0,0 +1,151 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public final class SHA1: DigestType { + static let digestLength: Int = 20 // 160 / 8 + static let blockSize: Int = 64 + fileprivate static let hashInitialValue: ContiguousArray = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0] + + fileprivate var accumulated = Array() + fileprivate var processedBytesTotalCount: Int = 0 + fileprivate var accumulatedHash: ContiguousArray = SHA1.hashInitialValue + + public init() { + } + + public func calculate(for bytes: Array) -> Array { + do { + return try update(withBytes: bytes.slice, isLast: true) + } catch { + return [] + } + } + + fileprivate func process(block chunk: ArraySlice, currentHash hh: inout ContiguousArray) { + // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian + // Extend the sixteen 32-bit words into eighty 32-bit words: + let M = UnsafeMutablePointer.allocate(capacity: 80) + M.initialize(repeating: 0, count: 80) + defer { + M.deinitialize(count: 80) + M.deallocate() + } + + for x in 0..<80 { + switch x { + case 0...15: + let start = chunk.startIndex.advanced(by: x * 4) // * MemoryLayout.size + M[x] = UInt32(bytes: chunk, fromIndex: start) + break + default: + M[x] = rotateLeft(M[x - 3] ^ M[x - 8] ^ M[x - 14] ^ M[x - 16], by: 1) + break + } + } + + var A = hh[0] + var B = hh[1] + var C = hh[2] + var D = hh[3] + var E = hh[4] + + // Main loop + for j in 0...79 { + var f: UInt32 = 0 + var k: UInt32 = 0 + + switch j { + case 0...19: + f = (B & C) | ((~B) & D) + k = 0x5a827999 + break + case 20...39: + f = B ^ C ^ D + k = 0x6ed9eba1 + break + case 40...59: + f = (B & C) | (B & D) | (C & D) + k = 0x8f1bbcdc + break + case 60...79: + f = B ^ C ^ D + k = 0xca62c1d6 + break + default: + break + } + + let temp = rotateLeft(A, by: 5) &+ f &+ E &+ M[j] &+ k + E = D + D = C + C = rotateLeft(B, by: 30) + B = A + A = temp + } + + hh[0] = hh[0] &+ A + hh[1] = hh[1] &+ B + hh[2] = hh[2] &+ C + hh[3] = hh[3] &+ D + hh[4] = hh[4] &+ E + } +} + +extension SHA1: Updatable { + @discardableResult + public func update(withBytes bytes: ArraySlice, isLast: Bool = false) throws -> Array { + accumulated += bytes + + if isLast { + let lengthInBits = (processedBytesTotalCount + accumulated.count) * 8 + let lengthBytes = lengthInBits.bytes(totalBytes: 64 / 8) // A 64-bit representation of b + + // Step 1. Append padding + bitPadding(to: &accumulated, blockSize: SHA1.blockSize, allowance: 64 / 8) + + // Step 2. Append Length a 64-bit representation of lengthInBits + accumulated += lengthBytes + } + + var processedBytes = 0 + for chunk in accumulated.batched(by: SHA1.blockSize) { + if isLast || (accumulated.count - processedBytes) >= SHA1.blockSize { + process(block: chunk, currentHash: &accumulatedHash) + processedBytes += chunk.count + } + } + accumulated.removeFirst(processedBytes) + processedBytesTotalCount += processedBytes + + // output current hash + var result = Array(repeating: 0, count: SHA1.digestLength) + var pos = 0 + for idx in 0..> 24) & 0xff) + result[pos + 1] = UInt8((h >> 16) & 0xff) + result[pos + 2] = UInt8((h >> 8) & 0xff) + result[pos + 3] = UInt8(h & 0xff) + pos += 4 + } + + // reset hash value for instance + if isLast { + accumulatedHash = SHA1.hashInitialValue + } + + return result + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/SHA2.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/SHA2.swift new file mode 100644 index 000000000..2e9940d39 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/SHA2.swift @@ -0,0 +1,353 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// TODO: generic for process32/64 (UInt32/UInt64) +// + +public final class SHA2: DigestType { + let variant: Variant + let size: Int + let blockSize: Int + let digestLength: Int + private let k: Array + + fileprivate var accumulated = Array() + fileprivate var processedBytesTotalCount: Int = 0 + fileprivate var accumulatedHash32 = Array() + fileprivate var accumulatedHash64 = Array() + + public enum Variant: RawRepresentable { + case sha224, sha256, sha384, sha512 + + public var digestLength: Int { + return rawValue / 8 + } + + public var blockSize: Int { + switch self { + case .sha224, .sha256: + return 64 + case .sha384, .sha512: + return 128 + } + } + + public typealias RawValue = Int + public var rawValue: RawValue { + switch self { + case .sha224: + return 224 + case .sha256: + return 256 + case .sha384: + return 384 + case .sha512: + return 512 + } + } + + public init?(rawValue: RawValue) { + switch rawValue { + case 224: + self = .sha224 + break + case 256: + self = .sha256 + break + case 384: + self = .sha384 + break + case 512: + self = .sha512 + break + default: + return nil + } + } + + fileprivate var h: Array { + switch self { + case .sha224: + return [0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4] + case .sha256: + return [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19] + case .sha384: + return [0xcbbb9d5dc1059ed8, 0x629a292a367cd507, 0x9159015a3070dd17, 0x152fecd8f70e5939, 0x67332667ffc00b31, 0x8eb44a8768581511, 0xdb0c2e0d64f98fa7, 0x47b5481dbefa4fa4] + case .sha512: + return [0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179] + } + } + + fileprivate var finalLength: Int { + switch self { + case .sha224: + return 7 + case .sha384: + return 6 + default: + return Int.max + } + } + } + + public init(variant: SHA2.Variant) { + self.variant = variant + switch self.variant { + case .sha224, .sha256: + accumulatedHash32 = variant.h.map { UInt32($0) } // FIXME: UInt64 for process64 + blockSize = variant.blockSize + size = variant.rawValue + digestLength = variant.digestLength + k = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, + ] + case .sha384, .sha512: + accumulatedHash64 = variant.h + blockSize = variant.blockSize + size = variant.rawValue + digestLength = variant.digestLength + k = [ + 0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538, + 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe, + 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, + 0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65, + 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab, + 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725, + 0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, + 0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b, + 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218, + 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, + 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, + 0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec, + 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c, + 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6, + 0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, + 0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817, + ] + } + } + + public func calculate(for bytes: Array) -> Array { + do { + return try update(withBytes: bytes.slice, isLast: true) + } catch { + return [] + } + } + + fileprivate func process64(block chunk: ArraySlice, currentHash hh: inout Array) { + // break chunk into sixteen 64-bit words M[j], 0 ≤ j ≤ 15, big-endian + // Extend the sixteen 64-bit words into eighty 64-bit words: + let M = UnsafeMutablePointer.allocate(capacity: k.count) + M.initialize(repeating: 0, count: k.count) + defer { + M.deinitialize(count: self.k.count) + M.deallocate() + } + for x in 0...size + M[x] = UInt64(bytes: chunk, fromIndex: start) + break + default: + let s0 = rotateRight(M[x - 15], by: 1) ^ rotateRight(M[x - 15], by: 8) ^ (M[x - 15] >> 7) + let s1 = rotateRight(M[x - 2], by: 19) ^ rotateRight(M[x - 2], by: 61) ^ (M[x - 2] >> 6) + M[x] = M[x - 16] &+ s0 &+ M[x - 7] &+ s1 + break + } + } + + var A = hh[0] + var B = hh[1] + var C = hh[2] + var D = hh[3] + var E = hh[4] + var F = hh[5] + var G = hh[6] + var H = hh[7] + + // Main loop + for j in 0.., currentHash hh: inout Array) { + // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian + // Extend the sixteen 32-bit words into sixty-four 32-bit words: + let M = UnsafeMutablePointer.allocate(capacity: k.count) + M.initialize(repeating: 0, count: k.count) + defer { + M.deinitialize(count: self.k.count) + M.deallocate() + } + + for x in 0...size + M[x] = UInt32(bytes: chunk, fromIndex: start) + break + default: + let s0 = rotateRight(M[x - 15], by: 7) ^ rotateRight(M[x - 15], by: 18) ^ (M[x - 15] >> 3) + let s1 = rotateRight(M[x - 2], by: 17) ^ rotateRight(M[x - 2], by: 19) ^ (M[x - 2] >> 10) + M[x] = M[x - 16] &+ s0 &+ M[x - 7] &+ s1 + break + } + } + + var A = hh[0] + var B = hh[1] + var C = hh[2] + var D = hh[3] + var E = hh[4] + var F = hh[5] + var G = hh[6] + var H = hh[7] + + // Main loop + for j in 0.., isLast: Bool = false) throws -> Array { + accumulated += bytes + + if isLast { + let lengthInBits = (processedBytesTotalCount + accumulated.count) * 8 + let lengthBytes = lengthInBits.bytes(totalBytes: blockSize / 8) // A 64-bit/128-bit representation of b. blockSize fit by accident. + + // Step 1. Append padding + bitPadding(to: &accumulated, blockSize: blockSize, allowance: blockSize / 8) + + // Step 2. Append Length a 64-bit representation of lengthInBits + accumulated += lengthBytes + } + + var processedBytes = 0 + for chunk in accumulated.batched(by: blockSize) { + if isLast || (accumulated.count - processedBytes) >= blockSize { + switch variant { + case .sha224, .sha256: + process32(block: chunk, currentHash: &accumulatedHash32) + case .sha384, .sha512: + process64(block: chunk, currentHash: &accumulatedHash64) + } + processedBytes += chunk.count + } + } + accumulated.removeFirst(processedBytes) + processedBytesTotalCount += processedBytes + + // output current hash + var result = Array(repeating: 0, count: variant.digestLength) + switch variant { + case .sha224, .sha256: + var pos = 0 + for idx in 0..> 24) & 0xff) + result[pos + 1] = UInt8((h >> 16) & 0xff) + result[pos + 2] = UInt8((h >> 8) & 0xff) + result[pos + 3] = UInt8(h & 0xff) + pos += 4 + } + case .sha384, .sha512: + var pos = 0 + for idx in 0..> 56) & 0xff) + result[pos + 1] = UInt8((h >> 48) & 0xff) + result[pos + 2] = UInt8((h >> 40) & 0xff) + result[pos + 3] = UInt8((h >> 32) & 0xff) + result[pos + 4] = UInt8((h >> 24) & 0xff) + result[pos + 5] = UInt8((h >> 16) & 0xff) + result[pos + 6] = UInt8((h >> 8) & 0xff) + result[pos + 7] = UInt8(h & 0xff) + pos += 8 + } + } + + // reset hash value for instance + if isLast { + switch variant { + case .sha224, .sha256: + accumulatedHash32 = variant.h.lazy.map { UInt32($0) } // FIXME: UInt64 for process64 + case .sha384, .sha512: + accumulatedHash64 = variant.h + } + } + + return result + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/SHA3.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/SHA3.swift new file mode 100644 index 000000000..b22fb5a19 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/SHA3.swift @@ -0,0 +1,289 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf +// http://keccak.noekeon.org/specs_summary.html +// + +#if canImport(Darwin) +import Darwin +#else +import Glibc +#endif + +public final class SHA3: DigestType { + let round_constants: Array = [ + 0x0000000000000001, 0x0000000000008082, 0x800000000000808a, 0x8000000080008000, + 0x000000000000808b, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009, + 0x000000000000008a, 0x0000000000000088, 0x0000000080008009, 0x000000008000000a, + 0x000000008000808b, 0x800000000000008b, 0x8000000000008089, 0x8000000000008003, + 0x8000000000008002, 0x8000000000000080, 0x000000000000800a, 0x800000008000000a, + 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008, + ] + + public let blockSize: Int + public let digestLength: Int + public let markByte: UInt8 + + fileprivate var accumulated = Array() + fileprivate var accumulatedHash: Array + + public enum Variant { + case sha224, sha256, sha384, sha512, keccak224, keccak256, keccak384, keccak512 + + var digestLength: Int { + return 100 - (blockSize / 2) + } + + var blockSize: Int { + return (1600 - outputLength * 2) / 8 + } + + var markByte: UInt8 { + switch self { + case .sha224, .sha256, .sha384, .sha512: + return 0x06 // 0x1F for SHAKE + case .keccak224, .keccak256, .keccak384, .keccak512: + return 0x01 + } + } + + public var outputLength: Int { + switch self { + case .sha224, .keccak224: + return 224 + case .sha256, .keccak256: + return 256 + case .sha384, .keccak384: + return 384 + case .sha512, .keccak512: + return 512 + } + } + } + + public init(variant: SHA3.Variant) { + blockSize = variant.blockSize + digestLength = variant.digestLength + markByte = variant.markByte + accumulatedHash = Array(repeating: 0, count: digestLength) + } + + public func calculate(for bytes: Array) -> Array { + do { + return try update(withBytes: bytes.slice, isLast: true) + } catch { + return [] + } + } + + /// 1. For all pairs (x,z) such that 0≤x<5 and 0≤z) { + let c = UnsafeMutablePointer.allocate(capacity: 5) + c.initialize(repeating: 0, count: 5) + defer { + c.deinitialize(count: 5) + c.deallocate() + } + let d = UnsafeMutablePointer.allocate(capacity: 5) + d.initialize(repeating: 0, count: 5) + defer { + d.deinitialize(count: 5) + d.deallocate() + } + + for i in 0..<5 { + c[i] = a[i] ^ a[i &+ 5] ^ a[i &+ 10] ^ a[i &+ 15] ^ a[i &+ 20] + } + + d[0] = rotateLeft(c[1], by: 1) ^ c[4] + d[1] = rotateLeft(c[2], by: 1) ^ c[0] + d[2] = rotateLeft(c[3], by: 1) ^ c[1] + d[3] = rotateLeft(c[4], by: 1) ^ c[2] + d[4] = rotateLeft(c[0], by: 1) ^ c[3] + + for i in 0..<5 { + a[i] ^= d[i] + a[i &+ 5] ^= d[i] + a[i &+ 10] ^= d[i] + a[i &+ 15] ^= d[i] + a[i &+ 20] ^= d[i] + } + } + + /// A′[x, y, z]=A[(x &+ 3y) mod 5, x, z] + private func π(_ a: inout Array) { + let a1 = a[1] + a[1] = a[6] + a[6] = a[9] + a[9] = a[22] + a[22] = a[14] + a[14] = a[20] + a[20] = a[2] + a[2] = a[12] + a[12] = a[13] + a[13] = a[19] + a[19] = a[23] + a[23] = a[15] + a[15] = a[4] + a[4] = a[24] + a[24] = a[21] + a[21] = a[8] + a[8] = a[16] + a[16] = a[5] + a[5] = a[3] + a[3] = a[18] + a[18] = a[17] + a[17] = a[11] + a[11] = a[7] + a[7] = a[10] + a[10] = a1 + } + + /// For all triples (x, y, z) such that 0≤x<5, 0≤y<5, and 0≤z) { + for i in stride(from: 0, to: 25, by: 5) { + let a0 = a[0 &+ i] + let a1 = a[1 &+ i] + a[0 &+ i] ^= ~a1 & a[2 &+ i] + a[1 &+ i] ^= ~a[2 &+ i] & a[3 &+ i] + a[2 &+ i] ^= ~a[3 &+ i] & a[4 &+ i] + a[3 &+ i] ^= ~a[4 &+ i] & a0 + a[4 &+ i] ^= ~a0 & a1 + } + } + + private func ι(_ a: inout Array, round: Int) { + a[0] ^= round_constants[round] + } + + fileprivate func process(block chunk: ArraySlice, currentHash hh: inout Array) { + // expand + hh[0] ^= chunk[0].littleEndian + hh[1] ^= chunk[1].littleEndian + hh[2] ^= chunk[2].littleEndian + hh[3] ^= chunk[3].littleEndian + hh[4] ^= chunk[4].littleEndian + hh[5] ^= chunk[5].littleEndian + hh[6] ^= chunk[6].littleEndian + hh[7] ^= chunk[7].littleEndian + hh[8] ^= chunk[8].littleEndian + if blockSize > 72 { // 72 / 8, sha-512 + hh[9] ^= chunk[9].littleEndian + hh[10] ^= chunk[10].littleEndian + hh[11] ^= chunk[11].littleEndian + hh[12] ^= chunk[12].littleEndian + if blockSize > 104 { // 104 / 8, sha-384 + hh[13] ^= chunk[13].littleEndian + hh[14] ^= chunk[14].littleEndian + hh[15] ^= chunk[15].littleEndian + hh[16] ^= chunk[16].littleEndian + if blockSize > 136 { // 136 / 8, sha-256 + hh[17] ^= chunk[17].littleEndian + // FULL_SHA3_FAMILY_SUPPORT + if blockSize > 144 { // 144 / 8, sha-224 + hh[18] ^= chunk[18].littleEndian + hh[19] ^= chunk[19].littleEndian + hh[20] ^= chunk[20].littleEndian + hh[21] ^= chunk[21].littleEndian + hh[22] ^= chunk[22].littleEndian + hh[23] ^= chunk[23].littleEndian + hh[24] ^= chunk[24].littleEndian + } + } + } + } + + // Keccak-f + for round in 0..<24 { + θ(&hh) + + hh[1] = rotateLeft(hh[1], by: 1) + hh[2] = rotateLeft(hh[2], by: 62) + hh[3] = rotateLeft(hh[3], by: 28) + hh[4] = rotateLeft(hh[4], by: 27) + hh[5] = rotateLeft(hh[5], by: 36) + hh[6] = rotateLeft(hh[6], by: 44) + hh[7] = rotateLeft(hh[7], by: 6) + hh[8] = rotateLeft(hh[8], by: 55) + hh[9] = rotateLeft(hh[9], by: 20) + hh[10] = rotateLeft(hh[10], by: 3) + hh[11] = rotateLeft(hh[11], by: 10) + hh[12] = rotateLeft(hh[12], by: 43) + hh[13] = rotateLeft(hh[13], by: 25) + hh[14] = rotateLeft(hh[14], by: 39) + hh[15] = rotateLeft(hh[15], by: 41) + hh[16] = rotateLeft(hh[16], by: 45) + hh[17] = rotateLeft(hh[17], by: 15) + hh[18] = rotateLeft(hh[18], by: 21) + hh[19] = rotateLeft(hh[19], by: 8) + hh[20] = rotateLeft(hh[20], by: 18) + hh[21] = rotateLeft(hh[21], by: 2) + hh[22] = rotateLeft(hh[22], by: 61) + hh[23] = rotateLeft(hh[23], by: 56) + hh[24] = rotateLeft(hh[24], by: 14) + + π(&hh) + χ(&hh) + ι(&hh, round: round) + } + } +} + +extension SHA3: Updatable { + public func update(withBytes bytes: ArraySlice, isLast: Bool = false) throws -> Array { + accumulated += bytes + + if isLast { + // Add padding + let markByteIndex = accumulated.count + + // We need to always pad the input. Even if the input is a multiple of blockSize. + let r = blockSize * 8 + let q = (r / 8) - (accumulated.count % (r / 8)) + accumulated += Array(repeating: 0, count: q) + + accumulated[markByteIndex] |= markByte + accumulated[self.accumulated.count - 1] |= 0x80 + } + + var processedBytes = 0 + for chunk in accumulated.batched(by: blockSize) { + if isLast || (accumulated.count - processedBytes) >= blockSize { + process(block: chunk.toUInt64Array().slice, currentHash: &accumulatedHash) + processedBytes += chunk.count + } + } + accumulated.removeFirst(processedBytes) + + // TODO: verify performance, reduce vs for..in + let result = accumulatedHash.reduce(Array()) { (result, value) -> Array in + return result + value.bigEndian.bytes() + } + + // reset hash value for instance + if isLast { + accumulatedHash = Array(repeating: 0, count: digestLength) + } + + return Array(result[0.. +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// +// https://tools.ietf.org/html/rfc7914 +// + +/// Implementation of the scrypt key derivation function. +public final class Scrypt { + enum Error: Swift.Error { + case nIsTooLarge + case rIsTooLarge + case nMustBeAPowerOf2GreaterThan1 + case invalidInput + } + + /// Configuration parameters. + private let salt: SecureBytes + private let password: SecureBytes + fileprivate let blocksize: Int // 128 * r + fileprivate let salsaBlock = UnsafeMutableRawPointer.allocate(byteCount: 64, alignment: 64) + private let dkLen: Int + private let N: Int + private let r: Int + private let p: Int + + /// - parameters: + /// - password: password + /// - salt: salt + /// - dkLen: output length + /// - N: determines extra memory used + /// - r: determines a block size + /// - p: determines parallelicity degree + public init(password: Array, salt: Array, dkLen: Int, N: Int, r: Int, p: Int) throws { + precondition(dkLen > 0) + precondition(N > 0) + precondition(r > 0) + precondition(p > 0) + + guard !(N < 2 || (N & (N - 1)) != 0) else { throw Error.nMustBeAPowerOf2GreaterThan1 } + + guard N <= .max / 128 / r else { throw Error.nIsTooLarge } + guard r <= .max / 128 / p else { throw Error.rIsTooLarge } + + guard !salt.isEmpty else { + throw Error.invalidInput + } + + blocksize = 128 * r + self.N = N + self.r = r + self.p = p + self.password = SecureBytes.init(bytes: password) + self.salt = SecureBytes.init(bytes: salt) + self.dkLen = dkLen + } + + /// Runs the key derivation function with a specific password. + public func calculate() throws -> [UInt8] { + // Allocate memory (as bytes for now) for further use in mixing steps + let B = UnsafeMutableRawPointer.allocate(byteCount: 128 * r * p, alignment: 64) + let XY = UnsafeMutableRawPointer.allocate(byteCount: 256 * r + 64, alignment: 64) + let V = UnsafeMutableRawPointer.allocate(byteCount: 128 * r * N, alignment: 64) + + // Deallocate memory when done + defer { + B.deallocate() + XY.deallocate() + V.deallocate() + } + + /* 1: (B_0 ... B_{p-1}) <-- PBKDF2(P, S, 1, p * MFLen) */ + // Expand the initial key + let barray = try PKCS5.PBKDF2(password: Array(password), salt: Array(salt), iterations: 1, keyLength: p * 128 * r, variant: .sha256).calculate() + barray.withUnsafeBytes { p in + B.copyMemory(from: p.baseAddress!, byteCount: barray.count) + } + + /* 2: for i = 0 to p - 1 do */ + // do the mixing + for i in 0 ..< p { + /* 3: B_i <-- MF(B_i, N) */ + smix(B + i * 128 * r, V.assumingMemoryBound(to: UInt32.self), XY.assumingMemoryBound(to: UInt32.self)) + } + + /* 5: DK <-- PBKDF2(P, B, 1, dkLen) */ + let pointer = B.assumingMemoryBound(to: UInt8.self) + let bufferPointer = UnsafeBufferPointer(start: pointer, count: p * 128 * r) + let block = [UInt8](bufferPointer) + return try PKCS5.PBKDF2(password: Array(password), salt: block, iterations: 1, keyLength: dkLen, variant: .sha256).calculate() + } +} + +private extension Scrypt { + /// Computes `B = SMix_r(B, N)`. + /// + /// The input `block` must be `128*r` bytes in length; the temporary storage `v` must be `128*r*n` bytes in length; + /// the temporary storage `xy` must be `256*r + 64` bytes in length. The arrays `block`, `v`, and `xy` must be + /// aligned to a multiple of 64 bytes. + @inline(__always) func smix(_ block: UnsafeMutableRawPointer, _ v: UnsafeMutablePointer, _ xy: UnsafeMutablePointer) { + let X = xy + let Y = xy + 32 * r + let Z = xy + 64 * r + + /* 1: X <-- B */ + let typedBlock = block.assumingMemoryBound(to: UInt32.self) + X.assign(from: typedBlock, count: 32 * r) + + /* 2: for i = 0 to N - 1 do */ + for i in stride(from: 0, to: N, by: 2) { + /* 3: V_i <-- X */ + UnsafeMutableRawPointer(v + i * (32 * r)).copyMemory(from: X, byteCount: 128 * r) + + /* 4: X <-- H(X) */ + blockMixSalsa8(X, Y, Z) + + /* 3: V_i <-- X */ + UnsafeMutableRawPointer(v + (i + 1) * (32 * r)).copyMemory(from: Y, byteCount: 128 * r) + + /* 4: X <-- H(X) */ + blockMixSalsa8(Y, X, Z) + } + + /* 6: for i = 0 to N - 1 do */ + for _ in stride(from: 0, to: N, by: 2) { + /* + 7: j <-- Integerify (X) mod N + where Integerify (B[0] ... B[2 * r - 1]) is defined + as the result of interpreting B[2 * r - 1] as a little-endian integer. + */ + var j = Int(integerify(X) & UInt64(N - 1)) + + /* 8: X <-- H(X \xor V_j) */ + blockXor(X, v + j * 32 * r, 128 * r) + blockMixSalsa8(X, Y, Z) + + /* 7: j <-- Integerify(X) mod N */ + j = Int(integerify(Y) & UInt64(N - 1)) + + /* 8: X <-- H(X \xor V_j) */ + blockXor(Y, v + j * 32 * r, 128 * r) + blockMixSalsa8(Y, X, Z) + } + + /* 10: B' <-- X */ + for k in 0 ..< 32 * r { + UnsafeMutableRawPointer(block + 4 * k).storeBytes(of: X[k], as: UInt32.self) + } + } + + /// Returns the result of parsing `B_{2r-1}` as a little-endian integer. + @inline(__always) func integerify(_ block: UnsafeRawPointer) -> UInt64 { + let bi = block + (2 * r - 1) * 64 + return bi.load(as: UInt64.self).littleEndian + } + + /// Compute `bout = BlockMix_{salsa20/8, r}(bin)`. + /// + /// The input `bin` must be `128*r` bytes in length; the output `bout` must also be the same size. The temporary + /// space `x` must be 64 bytes. + @inline(__always) func blockMixSalsa8(_ bin: UnsafePointer, _ bout: UnsafeMutablePointer, _ x: UnsafeMutablePointer) { + /* 1: X <-- B_{2r - 1} */ + UnsafeMutableRawPointer(x).copyMemory(from: bin + (2 * r - 1) * 16, byteCount: 64) + + /* 2: for i = 0 to 2r - 1 do */ + for i in stride(from: 0, to: 2 * r, by: 2) { + /* 3: X <-- H(X \xor B_i) */ + blockXor(x, bin + i * 16, 64) + salsa20_8_typed(x) + + /* 4: Y_i <-- X */ + /* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */ + UnsafeMutableRawPointer(bout + i * 8).copyMemory(from: x, byteCount: 64) + + /* 3: X <-- H(X \xor B_i) */ + blockXor(x, bin + i * 16 + 16, 64) + salsa20_8_typed(x) + + /* 4: Y_i <-- X */ + /* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */ + UnsafeMutableRawPointer(bout + i * 8 + r * 16).copyMemory(from: x, byteCount: 64) + } + } + + @inline(__always) func salsa20_8_typed(_ block: UnsafeMutablePointer) { + salsaBlock.copyMemory(from: UnsafeRawPointer(block), byteCount: 64) + let salsaBlockTyped = salsaBlock.assumingMemoryBound(to: UInt32.self) + + for _ in stride(from: 0, to: 8, by: 2) { + salsaBlockTyped[4] ^= rotateLeft(salsaBlockTyped[0] &+ salsaBlockTyped[12], by: 7) + salsaBlockTyped[8] ^= rotateLeft(salsaBlockTyped[4] &+ salsaBlockTyped[0], by: 9) + salsaBlockTyped[12] ^= rotateLeft(salsaBlockTyped[8] &+ salsaBlockTyped[4], by: 13) + salsaBlockTyped[0] ^= rotateLeft(salsaBlockTyped[12] &+ salsaBlockTyped[8], by: 18) + + salsaBlockTyped[9] ^= rotateLeft(salsaBlockTyped[5] &+ salsaBlockTyped[1], by: 7) + salsaBlockTyped[13] ^= rotateLeft(salsaBlockTyped[9] &+ salsaBlockTyped[5], by: 9) + salsaBlockTyped[1] ^= rotateLeft(salsaBlockTyped[13] &+ salsaBlockTyped[9], by: 13) + salsaBlockTyped[5] ^= rotateLeft(salsaBlockTyped[1] &+ salsaBlockTyped[13], by: 18) + + salsaBlockTyped[14] ^= rotateLeft(salsaBlockTyped[10] &+ salsaBlockTyped[6], by: 7) + salsaBlockTyped[2] ^= rotateLeft(salsaBlockTyped[14] &+ salsaBlockTyped[10], by: 9) + salsaBlockTyped[6] ^= rotateLeft(salsaBlockTyped[2] &+ salsaBlockTyped[14], by: 13) + salsaBlockTyped[10] ^= rotateLeft(salsaBlockTyped[6] &+ salsaBlockTyped[2], by: 18) + + salsaBlockTyped[3] ^= rotateLeft(salsaBlockTyped[15] &+ salsaBlockTyped[11], by: 7) + salsaBlockTyped[7] ^= rotateLeft(salsaBlockTyped[3] &+ salsaBlockTyped[15], by: 9) + salsaBlockTyped[11] ^= rotateLeft(salsaBlockTyped[7] &+ salsaBlockTyped[3], by: 13) + salsaBlockTyped[15] ^= rotateLeft(salsaBlockTyped[11] &+ salsaBlockTyped[7], by: 18) + + salsaBlockTyped[1] ^= rotateLeft(salsaBlockTyped[0] &+ salsaBlockTyped[3], by: 7) + salsaBlockTyped[2] ^= rotateLeft(salsaBlockTyped[1] &+ salsaBlockTyped[0], by: 9) + salsaBlockTyped[3] ^= rotateLeft(salsaBlockTyped[2] &+ salsaBlockTyped[1], by: 13) + salsaBlockTyped[0] ^= rotateLeft(salsaBlockTyped[3] &+ salsaBlockTyped[2], by: 18) + + salsaBlockTyped[6] ^= rotateLeft(salsaBlockTyped[5] &+ salsaBlockTyped[4], by: 7) + salsaBlockTyped[7] ^= rotateLeft(salsaBlockTyped[6] &+ salsaBlockTyped[5], by: 9) + salsaBlockTyped[4] ^= rotateLeft(salsaBlockTyped[7] &+ salsaBlockTyped[6], by: 13) + salsaBlockTyped[5] ^= rotateLeft(salsaBlockTyped[4] &+ salsaBlockTyped[7], by: 18) + + salsaBlockTyped[11] ^= rotateLeft(salsaBlockTyped[10] &+ salsaBlockTyped[9], by: 7) + salsaBlockTyped[8] ^= rotateLeft(salsaBlockTyped[11] &+ salsaBlockTyped[10], by: 9) + salsaBlockTyped[9] ^= rotateLeft(salsaBlockTyped[8] &+ salsaBlockTyped[11], by: 13) + salsaBlockTyped[10] ^= rotateLeft(salsaBlockTyped[9] &+ salsaBlockTyped[8], by: 18) + + salsaBlockTyped[12] ^= rotateLeft(salsaBlockTyped[15] &+ salsaBlockTyped[14], by: 7) + salsaBlockTyped[13] ^= rotateLeft(salsaBlockTyped[12] &+ salsaBlockTyped[15], by: 9) + salsaBlockTyped[14] ^= rotateLeft(salsaBlockTyped[13] &+ salsaBlockTyped[12], by: 13) + salsaBlockTyped[15] ^= rotateLeft(salsaBlockTyped[14] &+ salsaBlockTyped[13], by: 18) + } + for i in 0 ..< 16 { + block[i] = block[i] &+ salsaBlockTyped[i] + } + } + + @inline(__always) func blockXor(_ dest: UnsafeMutableRawPointer, _ src: UnsafeRawPointer, _ len: Int) { + let D = dest.assumingMemoryBound(to: UInt64.self) + let S = src.assumingMemoryBound(to: UInt64.self) + let L = len / MemoryLayout.size + + for i in 0 ..< L { + D[i] ^= S[i] + } + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/SecureBytes.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/SecureBytes.swift new file mode 100644 index 000000000..61e7f693d --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/SecureBytes.swift @@ -0,0 +1,77 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +#if canImport(Darwin) +import Darwin +#else +import Glibc +#endif + +typealias Key = SecureBytes + +/// Keeps bytes in memory. Because this is class, bytes are not copied +/// and memory area is locked as long as referenced, then unlocked on deinit +final class SecureBytes { + fileprivate let bytes: Array + let count: Int + + init(bytes: Array) { + self.bytes = bytes + count = bytes.count + self.bytes.withUnsafeBufferPointer { (pointer) -> Void in + mlock(pointer.baseAddress, pointer.count) + } + } + + deinit { + self.bytes.withUnsafeBufferPointer { (pointer) -> Void in + munlock(pointer.baseAddress, pointer.count) + } + } +} + +extension SecureBytes: Collection { + typealias Index = Int + + var endIndex: Int { + return bytes.endIndex + } + + var startIndex: Int { + return bytes.startIndex + } + + subscript(position: Index) -> UInt8 { + return bytes[position] + } + + subscript(bounds: Range) -> ArraySlice { + return bytes[bounds] + } + + func formIndex(after i: inout Int) { + bytes.formIndex(after: &i) + } + + func index(after i: Int) -> Int { + return bytes.index(after: i) + } +} + +extension SecureBytes: ExpressibleByArrayLiteral { + public convenience init(arrayLiteral elements: UInt8...) { + self.init(bytes: elements) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/StreamDecryptor.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/StreamDecryptor.swift new file mode 100644 index 000000000..81ab2705e --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/StreamDecryptor.swift @@ -0,0 +1,78 @@ +// CryptoSwift +// +// Copyright (C) 2014-2018 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +final class StreamDecryptor: Cryptor, Updatable { + private let blockSize: Int + private var worker: CipherModeWorker + private let padding: Padding + private var accumulated = Array() + + private var lastBlockRemainder = 0 + + init(blockSize: Int, padding: Padding, _ worker: CipherModeWorker) throws { + self.blockSize = blockSize + self.padding = padding + self.worker = worker + } + + // MARK: Updatable + public func update(withBytes bytes: ArraySlice, isLast: Bool) throws -> Array { + accumulated += bytes + + let toProcess = accumulated.prefix(max(accumulated.count - worker.additionalBufferSize, 0)) + + if var finalizingWorker = worker as? FinalizingDecryptModeWorker, isLast == true { + // will truncate suffix if needed + try finalizingWorker.willDecryptLast(bytes: accumulated.slice) + } + + var processedBytesCount = 0 + var plaintext = Array(reserveCapacity: bytes.count + worker.additionalBufferSize) + for chunk in toProcess.batched(by: blockSize) { + plaintext += worker.decrypt(block: chunk) + processedBytesCount += chunk.count + } + + if var finalizingWorker = worker as? FinalizingDecryptModeWorker, isLast == true { + plaintext = Array(try finalizingWorker.didDecryptLast(bytes: plaintext.slice)) + } + + // omit unecessary calculation if not needed + if padding != .noPadding { + lastBlockRemainder = plaintext.count.quotientAndRemainder(dividingBy: blockSize).remainder + } + + if isLast { + // CTR doesn't need padding. Really. Add padding to the last block if really want. but... don't. + plaintext = padding.remove(from: plaintext, blockSize: blockSize - lastBlockRemainder) + } + + accumulated.removeFirst(processedBytesCount) // super-slow + + if var finalizingWorker = worker as? FinalizingDecryptModeWorker, isLast == true { + plaintext = Array(try finalizingWorker.finalize(decrypt: plaintext.slice)) + } + + return plaintext + } + + public func seek(to position: Int) throws { + guard var worker = self.worker as? SeekableModeWorker else { + fatalError("Not supported") + } + + try worker.seek(to: position) + self.worker = worker + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/StreamEncryptor.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/StreamEncryptor.swift new file mode 100644 index 000000000..7cd54e3fb --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/StreamEncryptor.swift @@ -0,0 +1,56 @@ +// CryptoSwift +// +// Copyright (C) 2014-2018 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +final class StreamEncryptor: Cryptor, Updatable { + private let blockSize: Int + private var worker: CipherModeWorker + private let padding: Padding + + private var lastBlockRemainder = 0 + + init(blockSize: Int, padding: Padding, _ worker: CipherModeWorker) throws { + self.blockSize = blockSize + self.padding = padding + self.worker = worker + } + + // MARK: Updatable + public func update(withBytes bytes: ArraySlice, isLast: Bool) throws -> Array { + var accumulated = Array(bytes) + if isLast { + // CTR doesn't need padding. Really. Add padding to the last block if really want. but... don't. + accumulated = padding.add(to: accumulated, blockSize: blockSize - lastBlockRemainder) + } + + var encrypted = Array(reserveCapacity: bytes.count) + for chunk in accumulated.batched(by: blockSize) { + encrypted += worker.encrypt(block: chunk) + } + + // omit unecessary calculation if not needed + if padding != .noPadding { + lastBlockRemainder = encrypted.count.quotientAndRemainder(dividingBy: blockSize).remainder + } + + if var finalizingWorker = worker as? FinalizingEncryptModeWorker, isLast == true { + encrypted = Array(try finalizingWorker.finalize(encrypt: encrypted.slice)) + } + + return encrypted + } + + func seek(to: Int) throws { + fatalError("Not supported") + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/String+Extension.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/String+Extension.swift new file mode 100644 index 000000000..b186e3414 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/String+Extension.swift @@ -0,0 +1,81 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +/** String extension */ +extension String { + public var bytes: Array { + return data(using: String.Encoding.utf8, allowLossyConversion: true)?.bytes ?? Array(utf8) + } + + public func md5() -> String { + return bytes.md5().toHexString() + } + + public func sha1() -> String { + return bytes.sha1().toHexString() + } + + public func sha224() -> String { + return bytes.sha224().toHexString() + } + + public func sha256() -> String { + return bytes.sha256().toHexString() + } + + public func sha384() -> String { + return bytes.sha384().toHexString() + } + + public func sha512() -> String { + return bytes.sha512().toHexString() + } + + public func sha3(_ variant: SHA3.Variant) -> String { + return bytes.sha3(variant).toHexString() + } + + public func crc32(seed: UInt32? = nil, reflect: Bool = true) -> String { + return bytes.crc32(seed: seed, reflect: reflect).bytes().toHexString() + } + + public func crc32c(seed: UInt32? = nil, reflect: Bool = true) -> String { + return bytes.crc32(seed: seed, reflect: reflect).bytes().toHexString() + } + + public func crc16(seed: UInt16? = nil) -> String { + return bytes.crc16(seed: seed).bytes().toHexString() + } + + /// - parameter cipher: Instance of `Cipher` + /// - returns: hex string of bytes + public func encrypt(cipher: Cipher) throws -> String { + return try bytes.encrypt(cipher: cipher).toHexString() + } + + /// - parameter cipher: Instance of `Cipher` + /// - returns: base64 encoded string of encrypted bytes + public func encryptToBase64(cipher: Cipher) throws -> String? { + return try bytes.encrypt(cipher: cipher).toBase64() + } + + // decrypt() does not make sense for String + + /// - parameter authenticator: Instance of `Authenticator` + /// - returns: hex string of string + public func authenticate(with authenticator: A) throws -> String { + return try bytes.authenticate(with: authenticator).toHexString() + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/UInt128.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/UInt128.swift new file mode 100644 index 000000000..201579027 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/UInt128.swift @@ -0,0 +1,90 @@ +// +// UInt128.swift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +import Foundation + +struct UInt128: Equatable, ExpressibleByIntegerLiteral { + let i: (a: UInt64, b: UInt64) + + typealias IntegerLiteralType = UInt64 + + init(integerLiteral value: IntegerLiteralType) { + self = UInt128(value) + } + + init(_ raw: Array) { + self = raw.prefix(MemoryLayout.stride).withUnsafeBytes({ (rawBufferPointer) -> UInt128 in + let arr = rawBufferPointer.bindMemory(to: UInt64.self) + return UInt128((arr[0].bigEndian, arr[1].bigEndian)) + }) + } + + init(_ raw: ArraySlice) { + self.init(Array(raw)) + } + + init(_ i: (a: UInt64, b: UInt64)) { + self.i = i + } + + init(a: UInt64, b: UInt64) { + self.init((a, b)) + } + + init(_ b: UInt64) { + self.init((0, b)) + } + + // Bytes + var bytes: Array { + var at = i.a.bigEndian + var bt = i.b.bigEndian + + let ar = Data(bytes: &at, count: MemoryLayout.size(ofValue: at)) + let br = Data(bytes: &bt, count: MemoryLayout.size(ofValue: bt)) + + var result = Data() + result.append(ar) + result.append(br) + return result.bytes + } + + static func ^(n1: UInt128, n2: UInt128) -> UInt128 { + return UInt128((n1.i.a ^ n2.i.a, n1.i.b ^ n2.i.b)) + } + + static func &(n1: UInt128, n2: UInt128) -> UInt128 { + return UInt128((n1.i.a & n2.i.a, n1.i.b & n2.i.b)) + } + + static func >>(value: UInt128, by: Int) -> UInt128 { + var result = value + for _ in 0..> 1 + let b = result.i.b >> 1 + ((result.i.a & 1) << 63) + result = UInt128((a, b)) + } + return result + } + + // Equatable. + static func ==(lhs: UInt128, rhs: UInt128) -> Bool { + return lhs.i == rhs.i + } + + static func !=(lhs: UInt128, rhs: UInt128) -> Bool { + return !(lhs == rhs) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/UInt16+Extension.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/UInt16+Extension.swift new file mode 100644 index 000000000..98e996f69 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/UInt16+Extension.swift @@ -0,0 +1,37 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +/** array of bytes */ +extension UInt16 { +// @_specialize(exported: true, where T == ArraySlice) + init(bytes: T) where T.Element == UInt8, T.Index == Int { + self = UInt16(bytes: bytes, fromIndex: bytes.startIndex) + } + +// @_specialize(exported: true, where T == ArraySlice) + init(bytes: T, fromIndex index: T.Index) where T.Element == UInt8, T.Index == Int { + if bytes.isEmpty { + self = 0 + return + } + + let count = bytes.count + + let val0 = count > 0 ? UInt16(bytes[index.advanced(by: 0)]) << 8 : 0 + let val1 = count > 1 ? UInt16(bytes[index.advanced(by: 1)]) : 0 + + self = val0 | val1 + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/UInt32+Extension.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/UInt32+Extension.swift new file mode 100644 index 000000000..9e7232b2b --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/UInt32+Extension.swift @@ -0,0 +1,48 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +#if canImport(Darwin) +import Darwin +#else +import Glibc +#endif + +protocol _UInt32Type {} +extension UInt32: _UInt32Type {} + +/** array of bytes */ +extension UInt32 { +// @_specialize(exported: true, where T == ArraySlice) + init(bytes: T) where T.Element == UInt8, T.Index == Int { + self = UInt32(bytes: bytes, fromIndex: bytes.startIndex) + } + +// @_specialize(exported: true, where T == ArraySlice) + init(bytes: T, fromIndex index: T.Index) where T.Element == UInt8, T.Index == Int { + if bytes.isEmpty { + self = 0 + return + } + + let count = bytes.count + + let val0 = count > 0 ? UInt32(bytes[index.advanced(by: 0)]) << 24 : 0 + let val1 = count > 1 ? UInt32(bytes[index.advanced(by: 1)]) << 16 : 0 + let val2 = count > 2 ? UInt32(bytes[index.advanced(by: 2)]) << 8 : 0 + let val3 = count > 3 ? UInt32(bytes[index.advanced(by: 3)]) : 0 + + self = val0 | val1 | val2 | val3 + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/UInt64+Extension.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/UInt64+Extension.swift new file mode 100644 index 000000000..25fea64fa --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/UInt64+Extension.swift @@ -0,0 +1,43 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +/** array of bytes */ +extension UInt64 { +// @_specialize(exported: true, where T == ArraySlice) + init(bytes: T) where T.Element == UInt8, T.Index == Int { + self = UInt64(bytes: bytes, fromIndex: bytes.startIndex) + } + +// @_specialize(exported: true, where T == ArraySlice) + init(bytes: T, fromIndex index: T.Index) where T.Element == UInt8, T.Index == Int { + if bytes.isEmpty { + self = 0 + return + } + + let count = bytes.count + + let val0 = count > 0 ? UInt64(bytes[index.advanced(by: 0)]) << 56 : 0 + let val1 = count > 1 ? UInt64(bytes[index.advanced(by: 1)]) << 48 : 0 + let val2 = count > 2 ? UInt64(bytes[index.advanced(by: 2)]) << 40 : 0 + let val3 = count > 3 ? UInt64(bytes[index.advanced(by: 3)]) << 32 : 0 + let val4 = count > 4 ? UInt64(bytes[index.advanced(by: 4)]) << 24 : 0 + let val5 = count > 5 ? UInt64(bytes[index.advanced(by: 5)]) << 16 : 0 + let val6 = count > 6 ? UInt64(bytes[index.advanced(by: 6)]) << 8 : 0 + let val7 = count > 7 ? UInt64(bytes[index.advanced(by: 7)]) : 0 + + self = val0 | val1 | val2 | val3 | val4 | val5 | val6 | val7 + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/UInt8+Extension.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/UInt8+Extension.swift new file mode 100644 index 000000000..481d57fdb --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/UInt8+Extension.swift @@ -0,0 +1,76 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +#if canImport(Darwin) +import Darwin +#else +import Glibc +#endif + +public protocol _UInt8Type {} +extension UInt8: _UInt8Type {} + +/** casting */ +extension UInt8 { + /** cast because UInt8() because std initializer crash if value is > byte */ + static func with(value: UInt64) -> UInt8 { + let tmp = value & 0xff + return UInt8(tmp) + } + + static func with(value: UInt32) -> UInt8 { + let tmp = value & 0xff + return UInt8(tmp) + } + + static func with(value: UInt16) -> UInt8 { + let tmp = value & 0xff + return UInt8(tmp) + } +} + +/** Bits */ +extension UInt8 { + init(bits: [Bit]) { + self.init(integerFrom(bits) as UInt8) + } + + /** array of bits */ + public func bits() -> [Bit] { + let totalBitsCount = MemoryLayout.size * 8 + + var bitsArray = [Bit](repeating: Bit.zero, count: totalBitsCount) + + for j in 0.. String { + var s = String() + let arr: [Bit] = bits() + for idx in arr.indices { + s += (arr[idx] == Bit.one ? "1" : "0") + if idx.advanced(by: 1) % 8 == 0 { s += " " } + } + return s + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Updatable.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Updatable.swift new file mode 100644 index 000000000..23f165450 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Updatable.swift @@ -0,0 +1,98 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +/// A type that supports incremental updates. For example Digest or Cipher may be updatable +/// and calculate result incerementally. +public protocol Updatable { + /// Update given bytes in chunks. + /// + /// - parameter bytes: Bytes to process. + /// - parameter isLast: Indicate if given chunk is the last one. No more updates after this call. + /// - returns: Processed partial result data or empty array. + mutating func update(withBytes bytes: ArraySlice, isLast: Bool) throws -> Array + + /// Update given bytes in chunks. + /// + /// - Parameters: + /// - bytes: Bytes to process. + /// - isLast: Indicate if given chunk is the last one. No more updates after this call. + /// - output: Resulting bytes callback. + /// - Returns: Processed partial result data or empty array. + mutating func update(withBytes bytes: ArraySlice, isLast: Bool, output: (_ bytes: Array) -> Void) throws +} + +extension Updatable { + public mutating func update(withBytes bytes: ArraySlice, isLast: Bool = false, output: (_ bytes: Array) -> Void) throws { + let processed = try update(withBytes: bytes, isLast: isLast) + if !processed.isEmpty { + output(processed) + } + } + + public mutating func update(withBytes bytes: ArraySlice, isLast: Bool = false) throws -> Array { + return try update(withBytes: bytes, isLast: isLast) + } + + public mutating func update(withBytes bytes: Array, isLast: Bool = false) throws -> Array { + return try update(withBytes: bytes.slice, isLast: isLast) + } + + public mutating func update(withBytes bytes: Array, isLast: Bool = false, output: (_ bytes: Array) -> Void) throws { + return try update(withBytes: bytes.slice, isLast: isLast, output: output) + } + + /// Finish updates. This may apply padding. + /// - parameter bytes: Bytes to process + /// - returns: Processed data. + public mutating func finish(withBytes bytes: ArraySlice) throws -> Array { + return try update(withBytes: bytes, isLast: true) + } + + public mutating func finish(withBytes bytes: Array) throws -> Array { + return try finish(withBytes: bytes.slice) + } + + + /// Finish updates. May add padding. + /// + /// - Returns: Processed data + /// - Throws: Error + public mutating func finish() throws -> Array { + return try update(withBytes: [], isLast: true) + } + + /// Finish updates. This may apply padding. + /// - parameter bytes: Bytes to process + /// - parameter output: Resulting data + /// - returns: Processed data. + public mutating func finish(withBytes bytes: ArraySlice, output: (_ bytes: Array) -> Void) throws { + let processed = try update(withBytes: bytes, isLast: true) + if !processed.isEmpty { + output(processed) + } + } + + public mutating func finish(withBytes bytes: Array, output: (_ bytes: Array) -> Void) throws { + return try finish(withBytes: bytes.slice, output: output) + } + + /// Finish updates. May add padding. + /// + /// - Parameter output: Processed data + /// - Throws: Error + public mutating func finish(output: (Array) -> Void) throws { + try finish(withBytes: [], output: output) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Utils.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Utils.swift new file mode 100644 index 000000000..17b368af0 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/Utils.swift @@ -0,0 +1,115 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +@_transparent +func rotateLeft(_ value: UInt8, by: UInt8) -> UInt8 { + return ((value << by) & 0xff) | (value >> (8 - by)) +} + +@_transparent +func rotateLeft(_ value: UInt16, by: UInt16) -> UInt16 { + return ((value << by) & 0xffff) | (value >> (16 - by)) +} + +@_transparent +func rotateLeft(_ value: UInt32, by: UInt32) -> UInt32 { + return ((value << by) & 0xffffffff) | (value >> (32 - by)) +} + +@_transparent +func rotateLeft(_ value: UInt64, by: UInt64) -> UInt64 { + return (value << by) | (value >> (64 - by)) +} + +@_transparent +func rotateRight(_ value: UInt16, by: UInt16) -> UInt16 { + return (value >> by) | (value << (16 - by)) +} + +@_transparent +func rotateRight(_ value: UInt32, by: UInt32) -> UInt32 { + return (value >> by) | (value << (32 - by)) +} + +@_transparent +func rotateRight(_ value: UInt64, by: UInt64) -> UInt64 { + return ((value >> by) | (value << (64 - by))) +} + +@_transparent +func reversed(_ uint8: UInt8) -> UInt8 { + var v = uint8 + v = (v & 0xf0) >> 4 | (v & 0x0f) << 4 + v = (v & 0xcc) >> 2 | (v & 0x33) << 2 + v = (v & 0xaa) >> 1 | (v & 0x55) << 1 + return v +} + +@_transparent +func reversed(_ uint32: UInt32) -> UInt32 { + var v = uint32 + v = ((v >> 1) & 0x55555555) | ((v & 0x55555555) << 1) + v = ((v >> 2) & 0x33333333) | ((v & 0x33333333) << 2) + v = ((v >> 4) & 0x0f0f0f0f) | ((v & 0x0f0f0f0f) << 4) + v = ((v >> 8) & 0x00ff00ff) | ((v & 0x00ff00ff) << 8) + v = ((v >> 16) & 0xffff) | ((v & 0xffff) << 16) + return v +} + +func xor(_ left: T, _ right: V) -> ArraySlice where T: RandomAccessCollection, V: RandomAccessCollection, T.Element == UInt8, T.Index == Int, V.Element == UInt8, V.Index == Int { + return xor(left, right).slice +} + +func xor(_ left: T, _ right: V) -> Array where T: RandomAccessCollection, V: RandomAccessCollection, T.Element == UInt8, T.Index == Int, V.Element == UInt8, V.Index == Int { + let length = Swift.min(left.count, right.count) + + let buf = UnsafeMutablePointer.allocate(capacity: length) + buf.initialize(repeating: 0, count: length) + defer { + buf.deinitialize(count: length) + buf.deallocate() + } + + // xor + for i in 0.., blockSize: Int, allowance: Int = 0) { + let msgLength = data.count + // Step 1. Append Padding Bits + // append one bit (UInt8 with one bit) to message + data.append(0x80) + + // Step 2. append "0" bit until message length in bits ≡ 448 (mod 512) + let max = blockSize - allowance // 448, 986 + if msgLength % blockSize < max { // 448 + data += Array(repeating: 0, count: max - 1 - (msgLength % blockSize)) + } else { + data += Array(repeating: 0, count: blockSize + max - 1 - (msgLength % blockSize)) + } +} diff --git a/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/ZeroPadding.swift b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/ZeroPadding.swift new file mode 100644 index 000000000..7d1d8276c --- /dev/null +++ b/Example/Web3supportBrowser/Pods/CryptoSwift/Sources/CryptoSwift/ZeroPadding.swift @@ -0,0 +1,38 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2017 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +/// All the bytes that are required to be padded are padded with zero. +/// Zero padding may not be reversible if the original file ends with one or more zero bytes. +struct ZeroPadding: PaddingProtocol { + init() { + } + + func add(to bytes: Array, blockSize: Int) -> Array { + let paddingCount = blockSize - (bytes.count % blockSize) + if paddingCount > 0 { + return bytes + Array(repeating: 0, count: paddingCount) + } + return bytes + } + + func remove(from bytes: Array, blockSize _: Int?) -> Array { + for (idx, value) in bytes.reversed().enumerated() { + if value != 0 { + return Array(bytes[0.. 4.0) + - CryptoSwift (~> 1.0.0) + - PromiseKit (~> 6.8.4) + - secp256k1.c (~> 0.1) + - Starscream (~> 3.1.0) + +DEPENDENCIES: + - web3swift + +SPEC REPOS: + trunk: + - BigInt + - CryptoSwift + - PromiseKit + - secp256k1.c + - Starscream + - web3swift + +SPEC CHECKSUMS: + BigInt: 2aad1a9942dc932ec8b84290d2c564a3d76f97ab + CryptoSwift: d81eeaa59dc5a8d03720fe919a6fd07b51f7439f + PromiseKit: 9616b0afef31eae56ab9ce044c8ec2b8612a15cd + secp256k1.c: db47b726585d80f027423682eb369729e61b3b20 + Starscream: 4bb2f9942274833f7b4d296a55504dcfc7edb7b0 + web3swift: 0f097eafe1d08f478694b882581b85a01afb6633 + +PODFILE CHECKSUM: 88c1fe5ece120ef8aac94b776e02de991c51641d + +COCOAPODS: 1.10.2 diff --git a/Example/Web3supportBrowser/Pods/Pods.xcodeproj/project.pbxproj b/Example/Web3supportBrowser/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 000000000..c3c836264 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,3389 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 50; + objects = { + +/* Begin PBXBuildFile section */ + 0049EB7DC74BEFCDC5740A4FFBE89170 /* Data+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3FF1FE9FD2130495BEE330898A681C39 /* Data+Extension.swift */; }; + 00542E749518733F88FD9339F521159E /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 03D9157C8C0779B825A21D4DA8C71DAB /* UIKit.framework */; }; + 00B42BCCCA2E5CB2F9833D5B0185FAE4 /* num_gmp_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 6E105DF01C418F3B1C230920F963BE01 /* num_gmp_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 00C6A45F25B7C9567ABD4B6CEBB8F3A0 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75235A710D5C7405350FE8C421CF7EE2 /* Utils.swift */; }; + 025EED6A44FE486DD84DA9D38AC02AA0 /* Thenable.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF9FB057769EBF7CC35DF096044A3DDF /* Thenable.swift */; }; + 034BF4DD5B3A3634EF84A71E8D2B4FFD /* Pods-Web3support-Web3supportUITests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = BA3E0D28F68B3F3F1416216C4A0F6AC1 /* Pods-Web3support-Web3supportUITests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 04C4B5D00750E2E4DFD4C4C7CC47283A /* Bitwise Ops.swift in Sources */ = {isa = PBXBuildFile; fileRef = A4CF75EA89B6365105F7EE4170EF3D8E /* Bitwise Ops.swift */; }; + 04F24DFD581372A0BD9D827D77F385EE /* browser.js in Resources */ = {isa = PBXBuildFile; fileRef = E2D44CDE5D3C3AE1F4AE35A6E105AA98 /* browser.js */; }; + 0526AEB2FAAA1D80AC6245AB71BE994F /* BlockEncryptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F7D0C84A7512E1A50E355458C653748 /* BlockEncryptor.swift */; }; + 05958032576427EDBC47854025783311 /* Utils+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7BADEECA71797B1FBC1DCAECD0854C8C /* Utils+Foundation.swift */; }; + 05DC9941687D98BA8FC904388B11CE09 /* Web3+Eventloop.swift in Sources */ = {isa = PBXBuildFile; fileRef = 348BCAB7AD52B6413E93EA928F7BEE6A /* Web3+Eventloop.swift */; }; + 05E4E4CAC324A27052B047FB49A93994 /* Web3+ReadingTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3017C17B6A19772F40C2A00CC7053EC7 /* Web3+ReadingTransaction.swift */; }; + 068E5963381B58D7D8CD321462F567ED /* Compression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02973070D278C6BA9BAF3D1822786EE6 /* Compression.swift */; }; + 07DF8B768EA5C2C8F09B3F9E565252D8 /* secp256k1.c-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = D999058D57C5DCB3D443AE2AC82F7AF9 /* secp256k1.c-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 097672AA9B32748FEDC26BA74BE6B61B /* secp256k1_ec_mult_static_context.h in Headers */ = {isa = PBXBuildFile; fileRef = 9E4905CB06A5E339473019397A94729D /* secp256k1_ec_mult_static_context.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 0C21024B8BA4EF6B1368AAB0BA858CE1 /* RLP.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DDF8B3C487BB15A7C9D7E0F66D04AEB /* RLP.swift */; }; + 0C37352F62817E5CC47A0EC2460F2A0A /* Web3+ST20.swift in Sources */ = {isa = PBXBuildFile; fileRef = 154EA858B5D1E0BA4AF9640574096510 /* Web3+ST20.swift */; }; + 0DCA684E52941FC547C424E89E7FF830 /* Promise+Web3+Eth+Call.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2D82E51D53BAD38089B1DB95451764EF /* Promise+Web3+Eth+Call.swift */; }; + 0DF63A4C8FA0E53FB630F5B5429FF066 /* Exponentiation.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB36D0D3F09F93BB9AA193A077D19ABA /* Exponentiation.swift */; }; + 0E6F0E8337D8928B164D18FC54D6C7F9 /* Bit.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0F7E72D0726BA2223FDF177F5668744 /* Bit.swift */; }; + 0EBF2449E0DE2D9E352BA273F88E8269 /* PromiseKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0985EDDA3BE3F9FD09F7D6B612A46446 /* PromiseKit.framework */; }; + 0FFCCD6DA97D990AE1BA260117BFFE0B /* ecdsa_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = B08B4905158DCEB27F9CD432B2DCB08D /* ecdsa_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 1026E20FA9AAA86877D63DA8330C056B /* SECP256k1.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED4E4B062DAEA914113EBFEA174FFFD8 /* SECP256k1.swift */; }; + 10A7CA08B991B33D86A0B713E094489E /* CryptoExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D6BEB657B8F0CC4FEB1C0944BF892E8 /* CryptoExtensions.swift */; }; + 122311180757E413126BF7D15239A58F /* Dictionary+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = A4B92CA7DE6A389005EBF4F582D0ED9D /* Dictionary+Extension.swift */; }; + 12D6EEDC774272D55AB3321616260521 /* eckey.h in Headers */ = {isa = PBXBuildFile; fileRef = E4A3912DE02D411442B0E1BD5F45206A /* eckey.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 13A4BA994DAE26C3B22F1842D5E186BD /* Padding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 424FF13781C45B35C9ACA160B6118661 /* Padding.swift */; }; + 13C335A0C70755098F8236AAEDE436B1 /* field_10x26.h in Headers */ = {isa = PBXBuildFile; fileRef = 4EAF871AD72ED8B98E4F956A00841E95 /* field_10x26.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 14D34E32263C8D334AC63CA775357BA8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C1F58230773D8EC578B7F1DD661BE4C3 /* Foundation.framework */; }; + 15901C26A398A72C746D1369042356B6 /* join.m in Sources */ = {isa = PBXBuildFile; fileRef = 534AD27A9601B753D3C895597DDB078C /* join.m */; }; + 15DE85B34140EA30C3D8B4D837175214 /* field_5x52_asm_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = A5331A7B06641DC5D025C36D4FB2B521 /* field_5x52_asm_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 1627E6FA0453D6DB472BA444F1D32AE7 /* SSLClientCertificate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5B4C5B85A325DC6BBD1BABDC2BEFE3B /* SSLClientCertificate.swift */; }; + 16A1FA36B38C174BED3937B28FF30535 /* EthereumAddress.swift in Sources */ = {isa = PBXBuildFile; fileRef = F13167EA572351121100E3BA81B6D8E1 /* EthereumAddress.swift */; }; + 16DD36D15AB2DF7134AB207314C88C1B /* Promise+Web3+Personal+CreateAccount.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B4BF3C05BC39315DAE89F43DA29C75A /* Promise+Web3+Personal+CreateAccount.swift */; }; + 16F71F20D31B7EEC6A60DB14135AB7A9 /* Comparable.swift in Sources */ = {isa = PBXBuildFile; fileRef = D66BABFDEA861130F24DA1F117332183 /* Comparable.swift */; }; + 180E9D6CDF30A5F865D97B14BE3DAF81 /* Web3+ERC1594.swift in Sources */ = {isa = PBXBuildFile; fileRef = 59C0A0783CBBE1C7C8F3D2F34AAAEB96 /* Web3+ERC1594.swift */; }; + 18DF6A317CCB7F5BEE8D7AF5D79AEB38 /* PromiseKit-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 99E3E4B1F5A410A44A09223A24E26CB1 /* PromiseKit-dummy.m */; }; + 1B09E265817C6F239010997AAFF015E0 /* NativeTypesEncoding+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B12EE372DB1AFDFABD10118DA3C781C /* NativeTypesEncoding+Extensions.swift */; }; + 1C482705924CA6C3DF716EC60624900B /* Generics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F8B5FCF5522ECCD06CE444D5061F541 /* Generics.swift */; }; + 1C5D3593B983B9369EFCFDE7D4DE0D19 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D239122D0D5E4554A0AE9781080164F /* Configuration.swift */; }; + 1E23D653D73949318D8B1F3D53A05A71 /* EthereumFilterEncodingExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF6DD9C9C1A3ABFA116E929E7183AC5C /* EthereumFilterEncodingExtensions.swift */; }; + 1E6C33DE401D9AEFE660851A3E3394E6 /* NoPadding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8590CEF2172C5BB2B9EFFE7B18A88B42 /* NoPadding.swift */; }; + 1E8F207BAF428C44E0EE33E75C2EB8A5 /* Promise+Web3+Eth+SendRawTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 964D41D5C54F916868B511A8E50EF359 /* Promise+Web3+Eth+SendRawTransaction.swift */; }; + 1F0FDEF447A2FA6E89F4BEB39A81FE56 /* Web3+WebsocketProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C498EC6CEB8421E6EFA36FD8BF629BC /* Web3+WebsocketProvider.swift */; }; + 200C511BF343ABAAAE2A2455F87835CA /* ecmult_gen.h in Headers */ = {isa = PBXBuildFile; fileRef = D25D6EF8DCC49617FFBC667AF78EB12D /* ecmult_gen.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 208EDAA1D258CAA2BD08E462359D4FFF /* when.m in Sources */ = {isa = PBXBuildFile; fileRef = 5FE4310FF86028C19F34F611D349E859 /* when.m */; }; + 20C206CA6EF7BFB37EA703F8BEFBB5B0 /* Pods-Web3supportTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = A2EB54D097B2AC31F8EF4C4382F3F096 /* Pods-Web3supportTests-dummy.m */; }; + 20ED667341DDAE3103E222B85D943C06 /* Starscream.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 280705F0E0D0EBC84DFBBA1068758D6D /* Starscream.framework */; }; + 20FB0F849E1A209C4DB6DBF2DB715116 /* num_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 8C6445049DF4ABD6CE3F2C38F4C8A6C3 /* num_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 2117D9C7CE49B63C17BFBF811C1B709C /* Promise+Web3+Eth+GetBlockByNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7AEBAA42453A3627D0C260F40E3ABA32 /* Promise+Web3+Eth+GetBlockByNumber.swift */; }; + 2210254B6B7F0DBCFEEEBE4D4FA2BF87 /* Web3+ERC721.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEA7A27035F0203B4EBE4DBB88198DDC /* Web3+ERC721.swift */; }; + 2228B8549F0F5445D1B2D346E12A20CD /* Floating Point Conversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = C71739A132569C69D95D4D9C2B3DF8C4 /* Floating Point Conversion.swift */; }; + 24F2EB8E45FE8658FDDFDB0701E0B3B6 /* ABIParameterTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 635FCDE74A464A0EB4FF9B4D20DD8A80 /* ABIParameterTypes.swift */; }; + 2714060BB8E303CE54D62742676563F3 /* field_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 2FF9F9D0F195D9CCFBC308CE982B37AA /* field_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 2859803236FFE4CB1474293BE56D8889 /* Decodable+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8213F1D4FED15BCAC1769CCD95E698F3 /* Decodable+Extensions.swift */; }; + 2949B8CC1CBAD6B0C1B942E3677C72A1 /* Web3+ERC1155.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC4E8E5726428DCE53C0243395168F7C /* Web3+ERC1155.swift */; }; + 294C60E5E562CF3C2917335BDD910F42 /* Checksum.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F4E403D89A362925BE6A61E7E6F853A /* Checksum.swift */; }; + 294D61E8A195B6A1F6AEDCF0F73599A5 /* Starscream-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = F2777B674E6E41ECCFEF16A07EE3021F /* Starscream-dummy.m */; }; + 294EFBCAFC1E9D673CFC767E4311EE93 /* field_5x52.h in Headers */ = {isa = PBXBuildFile; fileRef = 7D04CD7E1EF55A225C04E7F16EB3E724 /* field_5x52.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 29643F7A000899634C9174BCB8D1A1AB /* NSNotificationCenter+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE851043F97E83BEB4FF3A0CD8440239 /* NSNotificationCenter+Promise.swift */; }; + 2D255B2758377F7CF44713FBD9F0DEF3 /* ABI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5A4FCAA67F0525DDA4FF3F94B5BBE816 /* ABI.swift */; }; + 2D7E01E2B44343D0E4C9A50C95318AE6 /* Web3.swift in Sources */ = {isa = PBXBuildFile; fileRef = ABF0E8EB7A3A288536F2B59EBAD394FC /* Web3.swift */; }; + 2DD52D5DFF05949A359999859D75471F /* Browser.bundle in Resources */ = {isa = PBXBuildFile; fileRef = 12DC6A0FDF284A2C935F5EA9F6111B0B /* Browser.bundle */; }; + 2DD9959CD5493A978BCB3B3CC0D2EB49 /* ECB.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1CC8B9335924C1AB0E99E830D0F01CF /* ECB.swift */; }; + 2E40B5BF79B05A81DFA5921032FB032C /* Web3+ERC777.swift in Sources */ = {isa = PBXBuildFile; fileRef = D824AF312F9E0CB944A043A34AA75492 /* Web3+ERC777.swift */; }; + 2E938A3C33EE9130C959EFA811DFB2EE /* Rabbit+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6E8016C1425F39ED0AFCCB9ED4B92D0 /* Rabbit+Foundation.swift */; }; + 2F5E7AF94E160DD850E4D49A75D65FD7 /* Pods-Web3support-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = E3E90DACA7F29B6C0940B7B81CF0B958 /* Pods-Web3support-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2FDD3DAC4E9D0C03A16D3F838A8E15F5 /* SHA2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2EAE3334F923A49D94EA8B8A709A09FD /* SHA2.swift */; }; + 301B5F7669D2DC7E46384FBAC71B7C19 /* hang.m in Sources */ = {isa = PBXBuildFile; fileRef = B3B9120018A02327BF16A71DC822A529 /* hang.m */; }; + 318D1DE9728C02574B9371682D8539A4 /* Web3+ERC820.swift in Sources */ = {isa = PBXBuildFile; fileRef = C895F2E1C112B43AC14C85286BEDAB9D /* Web3+ERC820.swift */; }; + 3208DDEB9CAC16AC7D2C7E9A7F057DC1 /* NSURLSession+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0B624D4A073BA9C14F275FB575B98BD /* NSURLSession+Promise.swift */; }; + 3378C1EEFC149B899433AF30F147CE32 /* after.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4AFF92C7C6621B254DE0DA0D312B3A6 /* after.swift */; }; + 33B79E4BFF8D25E1A705E2C469BBCA9B /* PromiseKit.h in Headers */ = {isa = PBXBuildFile; fileRef = FF6F05ADA7D3265602971B30AD6B3C63 /* PromiseKit.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 352BF48C1712389938C5B533A6A0D55A /* Web3+ERC1643.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4C771AA0054D3FAF040100F0DF5054A /* Web3+ERC1643.swift */; }; + 3607067F46CCABE732B2E0078149F8B2 /* Array+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10554501E08F69E67C555DA71246F0DD /* Array+Foundation.swift */; }; + 362BFC668055F3A0980C4B6E4568043C /* Web3+Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D196B49035EE2558CA931156B3CC775 /* Web3+Utils.swift */; }; + 3673081E4DE5FC570D7F208643205C9B /* scalar_4x64.h in Headers */ = {isa = PBXBuildFile; fileRef = 9135FA8D9B973BC1A3763F25AA44FF64 /* scalar_4x64.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 37018D3DC554A00E9B3E306A28296316 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8008892ABCADAD4E5DC4AA60DC647E31 /* Error.swift */; }; + 374559C0764BF277776F447353E2D740 /* Promise+Web3+Personal+Sign.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4FBCC7677F3EE13A0DC4495B13E7A571 /* Promise+Web3+Personal+Sign.swift */; }; + 37D92C03D9F8CC1339F7F60AAAAD584F /* scalar_4x64_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 126DC0D7440B4233998413303CE4F65F /* scalar_4x64_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 39137B0D7B8FB5BF554BDE012BD85061 /* Data Conversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 554B02C9539B4DE5F116BC0148B0341F /* Data Conversion.swift */; }; + 3A9EA81949CDEFD08121EFDD5F8807BD /* Promise+Web3+Eth+GetBlockNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3386535C108CE2E4983FF6FBAB1C7E01 /* Promise+Web3+Eth+GetBlockNumber.swift */; }; + 3AAE347ADDFEFAC7DDECBC744D1BD6AC /* NSTask+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = E474099C5B69E2295BEA6E9BCF9AC2D4 /* NSTask+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3AE0F49B3815815148F319E9D46C5533 /* Web3+ERC1400.swift in Sources */ = {isa = PBXBuildFile; fileRef = A431DC53AFA0AD3132485BA2EC90117A /* Web3+ERC1400.swift */; }; + 3B637B4A3FB612145E0EF8A1FDF8613E /* Pods-Web3support-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = D171B692D2F68A693D9818BA8E2AC7BE /* Pods-Web3support-dummy.m */; }; + 3B9A2601095A9A72843D76CA44B37782 /* Division.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F2489875CD5603FF6D93A818EEEF2DE /* Division.swift */; }; + 3E3FE29D83B6DB4B229CB38CCB4E1C86 /* CBCMAC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1340186B5B000DD0223DB7799FCEC3E7 /* CBCMAC.swift */; }; + 3ECD67E484E3B7DE40FBFA2660574A87 /* RIPEMD160+StackOveflow.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB3C1EEE1128E485B103001D09DD5DC7 /* RIPEMD160+StackOveflow.swift */; }; + 420C87B493B70746472899A82479242F /* String+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A38ECCB5ECDCB46FC3DD46AE1FC4FC1 /* String+Extension.swift */; }; + 42495A8941D9B42B07F032390AA2389F /* UIViewPropertyAnimator+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9851214ACA0341CA2837DCCE2C90ED9B /* UIViewPropertyAnimator+Promise.swift */; }; + 4362503059C68DFCDCB8621F4FD9E325 /* Square Root.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A013B1BDD344AC6EAC71EC4DEA1CDA5 /* Square Root.swift */; }; + 4366CE3A1EB891338E516632DE63190C /* scalar_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = F786129127F13FD69EF1677CA3998D83 /* scalar_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 438DAC7813FDB677252FB52A8FA3E708 /* Updatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3072E80789DEC0486492C1400591C726 /* Updatable.swift */; }; + 44031DBC1B3905CB9D22525C9E76EB42 /* Promise+Web3+Eth+GetTransactionDetails.swift in Sources */ = {isa = PBXBuildFile; fileRef = 73FA6458DA183DF514E42FE54DC27E66 /* Promise+Web3+Eth+GetTransactionDetails.swift */; }; + 4418281931C4D1176F2C541CDD770F14 /* Catchable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F0FEF67DA3E548C1E04B0EBFF9FEBDE /* Catchable.swift */; }; + 442B1F4F76FBCFAF1F27876847715C12 /* ENSBaseRegistrar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B32A29FD17AA33220D92C8413F32C56 /* ENSBaseRegistrar.swift */; }; + 448506F29495E3B3BAB56D093D681C1A /* Authenticator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6710D1A5A55B50814F9994C62AEF5E9D /* Authenticator.swift */; }; + 455EC7C458C31692757B2733867EB7D7 /* ecmult_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = C8D9FB4C9C15E3BBBC5E8E351D677DBB /* ecmult_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 45746D692A8E7F09C0EED2675231EF41 /* StreamEncryptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC4705742D8057A7777CE10502D81AA3 /* StreamEncryptor.swift */; }; + 458676EF35FF1E0E55B56BA564753395 /* ecmult_const_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 31D4B4B7AA6178320AD9429501FB9D42 /* ecmult_const_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 45B48F57B1039D463A2CB04349F22C5A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C1F58230773D8EC578B7F1DD661BE4C3 /* Foundation.framework */; }; + 46C4120B8C66DBCBEEC55D09F043D618 /* race.m in Sources */ = {isa = PBXBuildFile; fileRef = E17C973147AF3C5B7FFBCE67D54D10F8 /* race.m */; }; + 47134B51DE3E9A10AB40082EE69FC0B3 /* Web3+Eth+Websocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 532A38B4F523E15890612D5578B901BF /* Web3+Eth+Websocket.swift */; }; + 485369BDF5E2ACD219983520F20F42F9 /* Promise+Web3+Eth+EstimateGas.swift in Sources */ = {isa = PBXBuildFile; fileRef = 89047AD6A8F9DED9AD3FAFA4C7E7DC94 /* Promise+Web3+Eth+EstimateGas.swift */; }; + 48E5E91253E9388B606E69C995AC8115 /* CoreImage.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6A88AC5A168517938F01A76CAAE7EBEA /* CoreImage.framework */; }; + 48FEF9536E7763BD21D98545A62B8072 /* hash_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = F25689A430D65A68AE60A2F48BC45363 /* hash_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 49696DF6233801BF2D0F0BE214E56304 /* SecureBytes.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0BF9821783BCEF0E827B1849F7058B4 /* SecureBytes.swift */; }; + 496ED54AB3DA2B56E57B051D23C83BAD /* BrowserViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 23921C08E5242DAB552A4287DD4B4EA9 /* BrowserViewController.swift */; }; + 4981C37D541CDA8BCB7DE77E6607AC50 /* after.m in Sources */ = {isa = PBXBuildFile; fileRef = 7B045C7857F3FB23BE6496792365B9C5 /* after.m */; }; + 49C8C4DFD859391ED9CB7EBC50DDBBD1 /* MD5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18FC982ED53EDF2CD0C51B0E3E600099 /* MD5.swift */; }; + 4A8B21596204A43258F4EC69A7AEC66E /* Hashable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02BCB8FA01E7F4F5CD44B0D0A4B77AD5 /* Hashable.swift */; }; + 4BB3F625F107C3EF2F249F68B6D6788B /* PublicKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0D8A369599F638C6EF1C70946E7DD2F9 /* PublicKey.swift */; }; + 4C0B06508832B66B8FC871EAD70B101E /* Promise+Batching.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1422C33CAB7EAA29DB47C9CBDA6F4E46 /* Promise+Batching.swift */; }; + 4D65C782220C5E27BF8A3B61EBBDAB3E /* Guarantee.swift in Sources */ = {isa = PBXBuildFile; fileRef = 821FD64A61CCB7CBE3A1388FA84834F8 /* Guarantee.swift */; }; + 4DAA45AA4705DC070777F47B26CD5E47 /* ecdh_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = EF9288F7F0BC87F402C584F1315303A7 /* ecdh_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 4DE378D2B9BC193D231C0ED04C61B1E9 /* scratch.h in Headers */ = {isa = PBXBuildFile; fileRef = F1932888AB8E0C660FB6A6329B5EA93D /* scratch.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 4EC7BD8654B3587F1F725E812C9D828C /* race.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567E8F1F8BB7A75EC66096359A535F84 /* race.swift */; }; + 4F05619F8AB68F66AE44B802157E59F8 /* Web3+Instance.swift in Sources */ = {isa = PBXBuildFile; fileRef = 351509184374C023BC9E7318D6D240EC /* Web3+Instance.swift */; }; + 5063B1206FC2051E566265E1909FAC2A /* Bridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD7BBC49506B8E05F19DBAC1F1FE4977 /* Bridge.swift */; }; + 51FA3801910C079DDB18016F5F8FC84D /* ComparisonExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 43CB51FED61E2F731154A09AB346B249 /* ComparisonExtensions.swift */; }; + 5263C1C4A40EAC79395190B4BF4F9096 /* Web3+ERC888.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33F839ECDA9D6E925A8BCA131A664905 /* Web3+ERC888.swift */; }; + 52F57EB35132E86D75FE9443258EFDBF /* UIView+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = A27149F2AAB4BC84A16DB81D2D0C6E35 /* UIView+AnyPromise.m */; }; + 5300EB86348ED2DD35A9339104F21842 /* CBC.swift in Sources */ = {isa = PBXBuildFile; fileRef = D472BD0F97D2F7A5FD034A8C7975F843 /* CBC.swift */; }; + 53ECF855AA367DDE87AA9B0FC85B38F0 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C1F58230773D8EC578B7F1DD661BE4C3 /* Foundation.framework */; }; + 54BDD3BC1B92330FEF7F64FA1660BB13 /* AES.swift in Sources */ = {isa = PBXBuildFile; fileRef = C6740D520A527839549DE4AF221E7FE6 /* AES.swift */; }; + 55FBA344318427AEC1F50404D3BAD645 /* field_5x52_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = C0926ED5FE4B478819019A6247CC89F7 /* field_5x52_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 574AB0DF291869EF77612DDCA1453AD5 /* scalar_low.h in Headers */ = {isa = PBXBuildFile; fileRef = 3C9C4EF51D56F3A2F8C1351ECFBECA51 /* scalar_low.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 57A63C7B947C33B503717E92DA907110 /* Web3+ERC1633.swift in Sources */ = {isa = PBXBuildFile; fileRef = D070DF2AF043438B9AFB9E7FA536729C /* Web3+ERC1633.swift */; }; + 5802BD2A7E671D3015BE4E98C13D10CB /* NSURLSession+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = C7070B7F05AED57BDC930BBE9CFA531E /* NSURLSession+AnyPromise.m */; }; + 58AD203AF555F9B8416F7F9B4C7DA435 /* Rabbit.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5072CEBA6FD51C7376B73182287E404 /* Rabbit.swift */; }; + 59AA176600E91A56BC244B381305060B /* UIView+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = A64D2E5C32AA87FD9F30CAA89A3B6EFC /* UIView+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 59CB2BC19644CCDCE0A6B59528348FD1 /* UInt32+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = CFF55E6004A9D4243CB16AEE55BADC46 /* UInt32+Extension.swift */; }; + 5B48D6BBBD9B1B4F46DDCAD22E7E5709 /* Web3+Constants.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09CF9FD0B42B944753444D05129D819C /* Web3+Constants.swift */; }; + 5B498F77BA82755F0EA392ADAE895038 /* NSRegularExpressionExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2E96278BAD2803E74CFD101EF5EDBC6 /* NSRegularExpressionExtension.swift */; }; + 5B8A5FDFCDA736C6929320348B66149D /* CMAC.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB2C7436F64A01CB65DAC52E4D4051A9 /* CMAC.swift */; }; + 5C9DAD3002768BEFDB26B49836D597C1 /* web3swift-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 6F6E3A560F30E6C76BE396A97D419B02 /* web3swift-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5CEFD4F8821A3A1BD6C78FFCBCC98DA4 /* AES+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6696E07735F6561C9C4A983FE82A92E7 /* AES+Foundation.swift */; }; + 5D2D358E754D92564B259BBACFBA8271 /* PMKFoundation.h in Headers */ = {isa = PBXBuildFile; fileRef = D0F929F70A0BA1CEC964A1FB6A0BA532 /* PMKFoundation.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5E2574B7162EED00A81237F56CDC0BE4 /* BigInt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5D9411FFEE688C3F4C176C536884F130 /* BigInt.swift */; }; + 5E5EBD7039DC8763BFB20616B2AFE5F6 /* CryptoSwift-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 58406D2F94BB714CDB81DAACFAE2A10D /* CryptoSwift-dummy.m */; }; + 5E7F07D663E9DC5279D0059C3CBA2B7F /* KeystoreManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC99C21DE4C65C63327C02905C176992 /* KeystoreManager.swift */; }; + 5E90775673D3B4B6D79C433F2252ADA1 /* ecdsa.h in Headers */ = {isa = PBXBuildFile; fileRef = 7CC5B4139CDFFD75E516BC0C7EB1BA82 /* ecdsa.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 5F8EAE458B798A96B627EDC4FD1D071A /* CryptoSwift.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C3CBACBB4DD68A9DBBA69FA2B9AA05ED /* CryptoSwift.framework */; }; + 5FB5F56A8C4B2462E885C40EC675F5BF /* Web3+ERC721x.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2DFB28013DE80EDBBA6612BE5291E3BF /* Web3+ERC721x.swift */; }; + 5FDAD3F1739595982080BE2DD789C697 /* CipherModeWorker.swift in Sources */ = {isa = PBXBuildFile; fileRef = C6F12F07E23A192C8564A27C7A1FBD84 /* CipherModeWorker.swift */; }; + 6002AD14210CBE9C34EB848031CFD7E6 /* Addition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F1D0B138A229542223B16185A746888 /* Addition.swift */; }; + 60793CB821B498E92576B790FD0F95F8 /* BIP32KeystoreJSONStructure.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4130FCEFEA6178454D763881346DA12 /* BIP32KeystoreJSONStructure.swift */; }; + 60F874ED0F6234A4417CAFDE554D088D /* PMKUIKit.h in Headers */ = {isa = PBXBuildFile; fileRef = 570E189613076E0A18DAF4AC1072CA69 /* PMKUIKit.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 61330480364F92D57CB181E890C8896B /* Collection+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E6F02468AD363BFC7279A294B4087E6 /* Collection+Extension.swift */; }; + 61BBBE50B016C901A3162FAC9E1CA878 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C1F58230773D8EC578B7F1DD661BE4C3 /* Foundation.framework */; }; + 61CBA07C78D3A36DB19ED4E834CBB417 /* String+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A06F8FE8838CD882B9939831BCCE338 /* String+Extension.swift */; }; + 636A216DCBEBED81DA2DB1A12C7639E0 /* Operators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B20BDCDA0ECDF19F240EFFE03A8A53E /* Operators.swift */; }; + 639C6438CD01AE7A36FE1E551F2E7A8F /* CryptoSwift-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 14198AD5163D601BC6E9E4CEA8F0CE28 /* CryptoSwift-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 63EE527DD6C1FD264C5FC890E07966A2 /* secp256k1.c-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 05F1742DB6BF2606852E4AAA34612D4F /* secp256k1.c-dummy.m */; }; + 669DA0C80132D93F424571CD265F2A7F /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C1F58230773D8EC578B7F1DD661BE4C3 /* Foundation.framework */; }; + 68A92231E087567C6A9AD700359DAE80 /* AEADChaCha20Poly1305.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BD8315263E70B60082686DB2FFF5188 /* AEADChaCha20Poly1305.swift */; }; + 694E630570AB4DB0BCDF003411CF2B63 /* SHA3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4DD919542E41CB8E150F5DFC1A540CE6 /* SHA3.swift */; }; + 69BD0ECE9A9C86675C6D00B0A8AEE6C4 /* eckey_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = DC9996B23BD6274F87E53AC36E77A3C9 /* eckey_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 69DBAB1E3A8EEBFCC466D95509DE7125 /* UIView+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 204DC1705C56D7DB30888861287AAED5 /* UIView+Promise.swift */; }; + 69E62D35A7043AEBAFF100D522F38A30 /* DigestType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 327BEAF521485F0E297F4294ED918852 /* DigestType.swift */; }; + 6CA9E1BB397E222835F023CA94E1433B /* Web3+ERC1410.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9CD4E2731EDB8F1B5CA449E40120C65A /* Web3+ERC1410.swift */; }; + 6D78DA2799A948EFEBBDDCDB21181B6E /* HMAC.swift in Sources */ = {isa = PBXBuildFile; fileRef = D67F43FEA15269E642F8478487A5D443 /* HMAC.swift */; }; + 6DE830042E36FDE326546970CA90F9B6 /* Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79548549FC0A5BE4E92657ADCE6AFB03 /* Promise.swift */; }; + 6E052250546198FFA6ACA98591382FB9 /* field_10x26_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 05DDCFDA70BFDD11AABC10650442DAAB /* field_10x26_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 6F03CD1EB789E952809C13D2EA6C819F /* ENSReverseRegistrar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18839F6AF587B42905500F08F445E61B /* ENSReverseRegistrar.swift */; }; + 6F68C4EF34BAFD94802BDE5D5763CA29 /* scalar_low_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 21C0A4CE9CD0DC1F4665EB462C637348 /* scalar_low_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 70EEBB8F6ECE31F6CD454A57AF89D72E /* Promise+HttpProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = C20A6F6851C11E80E59966D5E2B1D9E5 /* Promise+HttpProvider.swift */; }; + 712053A56CCD73B5429412A5B04C28F9 /* KeystoreV3JSONStructure.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1ACC2FBAD75E9B64031CB9CD3CFA6292 /* KeystoreV3JSONStructure.swift */; }; + 73EA1C553B580637369E1D5A72A425B3 /* when.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB7C6C0E89041DFE6708D30416A3EE3A /* when.swift */; }; + 764FB86CFCE8188C52A97C69E35FA451 /* Web3+ERC1376.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0E050664AF64937BD1D7C8F5ADA8668 /* Web3+ERC1376.swift */; }; + 7771BEDF6237FFD4BD975996E99E8768 /* Web3+Contract.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02FBA29B920FE25DB8EE454A4F1E2874 /* Web3+Contract.swift */; }; + 780B79BF175E2CF800F18B65CFEFB892 /* hash.h in Headers */ = {isa = PBXBuildFile; fileRef = 5856772748611034A2DC9F7D6F13F3AD /* hash.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 792AECF194FD9EEC68866D1499302916 /* BlockModeOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE5C989E38CCFD13E2508304A4058F73 /* BlockModeOptions.swift */; }; + 7997EAE951EAB362280E2CE750810231 /* Cryptors.swift in Sources */ = {isa = PBXBuildFile; fileRef = A65ACE51991A9942763DF7D7FE18F8BB /* Cryptors.swift */; }; + 79F73BA854A7EC559E464EC446493D52 /* AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 384E922D8BC4146E932C077F9A2C0651 /* AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7CA57460C1D6652FD0CF4B62C596849B /* PCBC.swift in Sources */ = {isa = PBXBuildFile; fileRef = D42452232E5F0A25F9725E12A54B0D0B /* PCBC.swift */; }; + 7E3E6309C4EB4C70BC8AF5EB9CA3B6FB /* Poly1305.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1D87A56D4C13262ED6350310B53E68E /* Poly1305.swift */; }; + 7E6F4EFB85936E0B3EB9AD287F074C36 /* PKCS7.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9BECB7518C109FD265B3DCCA72289C6 /* PKCS7.swift */; }; + 7EECE9FCF5E07473E6D0FE80BFCB94C9 /* BigInt-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 6E285CA56194AF49BFD1EFB5C97D4334 /* BigInt-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7FC80BD52E47A1A3E58BDB3B2730B2BB /* group_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 572C8E0F590539A171571F4C06D8CB9A /* group_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 8039DF4C1AE7378FB41921D22A44AEF7 /* UInt16+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0ABAA7E59B6E1E62813742DBFE88342A /* UInt16+Extension.swift */; }; + 80910E754A1689207928F1161096798D /* secp256k1.h in Headers */ = {isa = PBXBuildFile; fileRef = 8557A2308502510B11D958EF167ED7DB /* secp256k1.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 812D264C4A7869539BA734E1FE654B27 /* ABIEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 447FB67D09E4D83CDF62C0379ACCC6B5 /* ABIEncoding.swift */; }; + 82EEFD50F58B36720B34916845913842 /* AbstractKeystore.swift in Sources */ = {isa = PBXBuildFile; fileRef = AFFFC1031DB8B0BD09400CA16DCB69B8 /* AbstractKeystore.swift */; }; + 838AD4FB685FD2C3578AAE01B99B8037 /* Promise+Web3+Eth+SendTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6F1CC28425C72AC8913BE51E129F555C /* Promise+Web3+Eth+SendTransaction.swift */; }; + 8532AFAE5B4DE21DCAFB19AB0E4434EB /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C1F58230773D8EC578B7F1DD661BE4C3 /* Foundation.framework */; }; + 854AF7B141389D5512E8E73DF38FEBEA /* BlockMode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FE8062FF8F7EE71B525E058FCD7F293 /* BlockMode.swift */; }; + 8573D5547D4AC8CEE69AB545148A72B6 /* CCM.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B59B8ED26308215F98BAEB6995ADE07 /* CCM.swift */; }; + 8599E23B2946C6F3F6DA3D63EC82C4A3 /* Words and Bits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3910EE551F198BF1791FF438496F9747 /* Words and Bits.swift */; }; + 85C6833DDA0D0E761EE32F7566019DE1 /* Base58.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF34F6B173634CB05270C33E3B633E52 /* Base58.swift */; }; + 866E7694E457A77B466115DADDF00D5B /* PlainKeystore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E306D7806FF9EE954924600AA4E1289 /* PlainKeystore.swift */; }; + 8800FB2685022185627E8840BD19FD43 /* BIP39+WordLists.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F6AAD426CB2B7147BD42370206C1F5B /* BIP39+WordLists.swift */; }; + 89C39070942182119EBF01EE36FE6C10 /* IBAN.swift in Sources */ = {isa = PBXBuildFile; fileRef = 66F16B5D8DEE8BDE87CC2408D8FE5FE3 /* IBAN.swift */; }; + 8A292837D81C3B20F95EB52B3C4048FD /* util.h in Headers */ = {isa = PBXBuildFile; fileRef = 96BA76B86413F1BD6D2642279E7BB1AD /* util.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 8AC718714C214D0C022A8E999307BA8F /* TransactionSigner.swift in Sources */ = {isa = PBXBuildFile; fileRef = 135B192A1A9030D073173CE768BD191B /* TransactionSigner.swift */; }; + 8B3350D96B15B975184C8EE0819F9623 /* SSLSecurity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 081B081BAB76C290DB80364F972A3D98 /* SSLSecurity.swift */; }; + 8C05403EC0F455CB86CFD8060C1C5DC2 /* Cryptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 674945A263B5A171B0D8CAC79DAA6216 /* Cryptor.swift */; }; + 8C167D80A661845226C2A2B22049BFEA /* Promise+Web3+Contract+GetIndexedEvents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01E073C1CD37262FF94E5051A8D55BC3 /* Promise+Web3+Contract+GetIndexedEvents.swift */; }; + 8C35A342254C4AA753BD1F2297057490 /* Web3+HttpProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8910795635358AF5D3F10D643064EF90 /* Web3+HttpProvider.swift */; }; + 8CFAB2E848223BB549F83CDF45D211AA /* ABIDecoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = D712D8A93FBC323100D51A02D9BC7099 /* ABIDecoding.swift */; }; + 8D58B7BD460D20FFEC478698F7F52222 /* PKCS7Padding.swift in Sources */ = {isa = PBXBuildFile; fileRef = D98E85C5728326F38DFE21248CC52894 /* PKCS7Padding.swift */; }; + 8E375613F407E1171F069FFA526B08A2 /* BIP32HDNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4AE1FB59AAB7CFCF16F4D7AECE524894 /* BIP32HDNode.swift */; }; + 8ED7D4847260B4F398ECF4351280AB31 /* Digest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 028968F0E8149D086725FEB0C3962475 /* Digest.swift */; }; + 8F8F2AC356A0467D3FC0CE3118E9BC7E /* Promise+Web3+Personal+UnlockAccount.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8571C3C4E2540AE79C82CC088FF5C809 /* Promise+Web3+Personal+UnlockAccount.swift */; }; + 9094207BFCA7F633807C6790662CE1A9 /* scalar_8x32_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = A6C9FA5D62CF92CD83E5688741541FEA /* scalar_8x32_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 91A59A657AB2118D4FFFC913EAD87EC9 /* BatchedCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 558429F8ABA5EF6470234B32E39EE6DB /* BatchedCollection.swift */; }; + 936AF3BB98A3900202979429453172AA /* web3swift-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 380AE05F318DC350995E5E66ACC19F19 /* web3swift-dummy.m */; }; + 9447BD0FB408B2A7C9BFDFF99BBE1EBE /* UIViewController+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 6DAFC7859E7882E5E0AB3A29C3082C9E /* UIViewController+AnyPromise.m */; }; + 94B88E81C4DD104E870876302B16FC31 /* Promise+Web3+Eth+GetTransactionCount.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E41C42E5233827CA9E9E88D318D954B /* Promise+Web3+Eth+GetTransactionCount.swift */; }; + 968B5CC9B9B0A7E92FACEEBEA3C0DA13 /* PromiseKit-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 07BA1325EFD33D5292CE17473E5F956F /* PromiseKit-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9731EDF8F60C68FC5EBE3FCBB6675846 /* ENSRegistry.swift in Sources */ = {isa = PBXBuildFile; fileRef = F977ED89C342B067EE048C2E57FA3E29 /* ENSRegistry.swift */; }; + 975DB75B4BA3DFBBCC71CF7A8A4AC59C /* BloomFilter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 696516B833D002C3DE6DF92361767CA1 /* BloomFilter.swift */; }; + 997870D5F490326F024B4D8687FF18DC /* Resolver.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7109CA7EDFB5ACD7D4E152EC1950D9A /* Resolver.swift */; }; + 99EE8A649068210DF711EA2FFBE1C3BF /* PBKDF2.swift in Sources */ = {isa = PBXBuildFile; fileRef = EB937DBC76B12E434BD67D13C22BC9DA /* PBKDF2.swift */; }; + 99F35D362CDAA3F01D59E05FAB02907D /* Strideable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5E0378DB2D3422FFD6E14F74781F0694 /* Strideable.swift */; }; + 9A80311C79CED9486D2E9FA4DEC3D45A /* StreamDecryptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = AEABFB0679AD607BA8C19624CD03EB3F /* StreamDecryptor.swift */; }; + 9B65647B927085E2366117D59DC1586D /* CustomStringConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 283FFF6A596C1D84BB8FF9BA94A7ADDB /* CustomStringConvertible.swift */; }; + 9BFE70DD7ECA3C6183B82DE691FE4491 /* Box.swift in Sources */ = {isa = PBXBuildFile; fileRef = 244C067EFEB7A2C4E5ECDDDCF3FB0D79 /* Box.swift */; }; + 9D22006C799C6F6E9452B97B760F7CD1 /* UInt64+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 63BE7C86DDBB5ECBFFA35C3F78742ADF /* UInt64+Extension.swift */; }; + 9DBCF5E7D37DC2CF11A6E4FD53826708 /* ABIElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C0721CA0C6A5B018F4B496B54F7D274 /* ABIElements.swift */; }; + A1A3867F89E6645A9E535A123CF679CE /* BIP39.swift in Sources */ = {isa = PBXBuildFile; fileRef = 12C5C4C81A590ED070F02E971254DEC4 /* BIP39.swift */; }; + A1E6C35C5B3ECB558FE1AF9B1FAAB53B /* AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 5342D36974BCDE8EC75703FD3DBF9F3B /* AnyPromise.m */; }; + A2E252B71846F99034B0BA5D873541B6 /* Web3+Eth.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB16EB86A68E527A7A28E138B85069B5 /* Web3+Eth.swift */; }; + A3BA9877A1CA08CBCC6671FAF10E4254 /* field_5x52_int128_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 2E123B4A564E405B1FEE02F48D534532 /* field_5x52_int128_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + A5F5D7A20264221D4A7F489FB0060D34 /* afterlife.swift in Sources */ = {isa = PBXBuildFile; fileRef = FDE6BF7E45AF488C7D6816FC89DB4D6F /* afterlife.swift */; }; + A65BC55FFE138090EF77D9EC1F72A88B /* HKDF.swift in Sources */ = {isa = PBXBuildFile; fileRef = C58E341F20950270149F0D746714B773 /* HKDF.swift */; }; + A83D65CEE1CB904CA9E923FDBB4CF3BE /* wk.bridge.min.js in Resources */ = {isa = PBXBuildFile; fileRef = 5DA9CD391B4D5E614CAE1DB405B5D95E /* wk.bridge.min.js */; }; + A924D29AB5C6DED4D11695F816435182 /* num.h in Headers */ = {isa = PBXBuildFile; fileRef = 331DA5AED7BF5F4646A90D6F77C91A22 /* num.h */; settings = {ATTRIBUTES = (Project, ); }; }; + A93275D5C1DAD3CA7CCC2A9586AC9ADE /* AEAD.swift in Sources */ = {isa = PBXBuildFile; fileRef = 394050D026F0D950AC11CB1CB8965A25 /* AEAD.swift */; }; + AAA648FE58CC4A49EF39BFDBCBA7C1FA /* PBKDF1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 869339C036B9B7D93560C6864892AAFE /* PBKDF1.swift */; }; + ABF5E5F45D270B8B7CE386D4BB8E614D /* Int+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3099C8E0DFDA6B882C0E55B94FBB3E85 /* Int+Extension.swift */; }; + AC4E061C6A2D21210122B471D8BCC81E /* Random.swift in Sources */ = {isa = PBXBuildFile; fileRef = 699763CCB6877CF34141DDE755F441EB /* Random.swift */; }; + AC7DBF3AD44B3E7644068E6F09F9EBF2 /* BigUInt.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8BDA8BCDF0A7105D483CC6CA145E0E0 /* BigUInt.swift */; }; + ACA8271368449221D95A89A9367AF042 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C1F58230773D8EC578B7F1DD661BE4C3 /* Foundation.framework */; }; + ADE26A6317E68C1CB7FC86D68B4EB8BF /* RandomBytesSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9C358BD213A4F803A4F0D954CDB4A66 /* RandomBytesSequence.swift */; }; + AE242F808DE761641CF108E8844745D6 /* Cipher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02760A62D64944C5DE7DAFDFDEA019F1 /* Cipher.swift */; }; + AF8F1135157EDA1D6857CCE22DC8BFD2 /* Pods-Web3support-Web3supportUITests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 73AE9CE7C402316A90015D8FE30A9C17 /* Pods-Web3support-Web3supportUITests-dummy.m */; }; + B154FB35E7B72F153A3AA603E62E3E6B /* secp256k1-config.h in Headers */ = {isa = PBXBuildFile; fileRef = 3D81CBF6EA6135E28DA96DDC5089008E /* secp256k1-config.h */; settings = {ATTRIBUTES = (Project, ); }; }; + B15E0CD8A2E6D29E9849F092CD078773 /* GCM.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6A055C6C2236AC231E70C766F1F2A9E /* GCM.swift */; }; + B4A6283FDFA04E3A7B6FD0C13B6FEF32 /* Starscream-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 84586FE14E05B1A73DAE9DD316A9D7F2 /* Starscream-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B4E0F6805D68577613B95A18651FC167 /* Blowfish.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D93B2F6F631256A8EF3546A2D3015E9 /* Blowfish.swift */; }; + B593B56495A204E756BAA753BA2D6E9C /* Deprecations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 985C66F4582B57397550A08576C172DC /* Deprecations.swift */; }; + B5F88ED28F9F02C7773DB0EF4CEC020D /* ecmult_gen_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 01ED7D9D89508CA7EAA7F1F043495007 /* ecmult_gen_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + B758241FBF6592EFBE6283378D16F9FD /* NSObject+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 774CC24C803B0C79461A6923DC01B31A /* NSObject+Promise.swift */; }; + B7BAF0D7AAE50645B459C8984D966FCD /* EthereumTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4BFDF5AAA317492732B1D0EECF6E68CB /* EthereumTransaction.swift */; }; + B8610DF9CE98C994CD53723045FF09FD /* secp256k1.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D98ECE7F0FF4B6489BAE75EB0B338CDE /* secp256k1.framework */; }; + B87B17EAF9350E5A984E8A30DCBACF7B /* BigInt.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 857E7AB10DF6BDB0B3A11DF7F010FFAC /* BigInt.framework */; }; + B9BC4E41D4B1A39754CFD8B648C37063 /* browser.min.js in Resources */ = {isa = PBXBuildFile; fileRef = C09C3CDFA62A239E931C8CBCE69AF714 /* browser.min.js */; }; + BAA052C302D45F8DAB72606E997CAD69 /* Subtraction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D3F3745A7D0E990E715D852768455F2 /* Subtraction.swift */; }; + BB8076FBF18C0A9C3FFEEB5B5B24520F /* recovery_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 3056036973AE29A6057B82086C2B0D84 /* recovery_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + BDCE30064CB17E618C38A04797F7F915 /* EthereumContract.swift in Sources */ = {isa = PBXBuildFile; fileRef = 73938AA4C7CACF9566B3616D650B0283 /* EthereumContract.swift */; }; + BE29AFA73FEDAFA471F35F8AB1C3EA99 /* Shifts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B9CBFF9FF052E246CA99F8F60CC30AB /* Shifts.swift */; }; + BE309A78FF212AF93A7E979CD7B9F781 /* EIP681.swift in Sources */ = {isa = PBXBuildFile; fileRef = 431DFDCD5EBFCE95F388BD650BC3F510 /* EIP681.swift */; }; + BE69B05F62FA6C46F1280B896B645696 /* ENS.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1CCA7F271D80CEABEBEC082B807C886 /* ENS.swift */; }; + C02D9FEB295BDA1359D2F52C80F8E75A /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16F91688CB98C09F37FB0532B3341B22 /* WebSocket.swift */; }; + C138FACCB027B81AE55814AA990543D5 /* OFB.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F89D5E973A70A3593E25EBE22FACAD1 /* OFB.swift */; }; + C17E552920AF110E9DB7AB635C65A12D /* Scrypt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25FD464B4ADFC965F65DEB27E8F457B6 /* Scrypt.swift */; }; + C226251E2377797FECAE371AA069E051 /* Promise+Web3+Eth+GetGasPrice.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C0168721A40963DC1F398E1A4B087F6 /* Promise+Web3+Eth+GetGasPrice.swift */; }; + C2D49681C376A0AA1655D9B9C97576C3 /* Web3+MutatingTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = BCC0FB94C80105AA81FC6881C5A9F34A /* Web3+MutatingTransaction.swift */; }; + C426E30A28E2545BCA2824DBCF90816F /* NSNotificationCenter+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = F9762329D78E5F848C2CA1616AF68985 /* NSNotificationCenter+AnyPromise.m */; }; + C48EC56BB7C14ABC19E3BA2ACD91F6A9 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C1F58230773D8EC578B7F1DD661BE4C3 /* Foundation.framework */; }; + C5EF8FBC11CA9E66100F6489B57E35A6 /* LogEvent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6628230DE91FEFDC792C7DBD31BE5251 /* LogEvent.swift */; }; + C680444C2E2E5076D981C2A8452AC067 /* CFB.swift in Sources */ = {isa = PBXBuildFile; fileRef = 537B9FE8F0466BB2293902B1450ED4AE /* CFB.swift */; }; + C6E721B3190ECB4166B66A7111C06AD7 /* ecmult_const.h in Headers */ = {isa = PBXBuildFile; fileRef = 892E151D44D4707DBC204D6F59A99099 /* ecmult_const.h */; settings = {ATTRIBUTES = (Project, ); }; }; + C743E09891827198E2A27DDD70C37238 /* Promise+Web3+Eth+GetBalance.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95FEF9A336D74B30EEC3F0905F44CC91 /* Promise+Web3+Eth+GetBalance.swift */; }; + C7ECF714064C1188A6D042C6ACFD9504 /* dispatch_promise.m in Sources */ = {isa = PBXBuildFile; fileRef = 22BF1378E05475FF065F31B3478EB217 /* dispatch_promise.m */; }; + C829EE08BBA51E4F85528D4D6B4D8DEB /* CTR.swift in Sources */ = {isa = PBXBuildFile; fileRef = B00EC20DCA6A113D5499EA2DE3147E23 /* CTR.swift */; }; + C96D26290D68F1A1AFE25447DEDBC242 /* Web3+InfuraProviders.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74C2AE8219D8A019AF481B6F3383E570 /* Web3+InfuraProviders.swift */; }; + CA5F0FF46E700A877E1ED5C9EF6BDECB /* BlockCipher.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE6049D61D668B65B8E7267220FA207A /* BlockCipher.swift */; }; + CB7485C6A44EBDB23A8D49E129817FBB /* EventFiltering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57536CB2627D968FD6667AA3AA245EB1 /* EventFiltering.swift */; }; + CC03E31F122F91A26DD22BEEF813D779 /* UInt128.swift in Sources */ = {isa = PBXBuildFile; fileRef = CF2636E79F042FE113A41FE09A2BD447 /* UInt128.swift */; }; + CD6894E475BBE3884302A212F9D60F2D /* secp256k1.c in Sources */ = {isa = PBXBuildFile; fileRef = 334450DD7B6EA290D629965834A78C15 /* secp256k1.c */; }; + CD6F384F7FD1471FC28E900AF5C30CD7 /* Web3+ERC20.swift in Sources */ = {isa = PBXBuildFile; fileRef = 99F9F2E3C006B21E7B8B9FF942A63161 /* Web3+ERC20.swift */; }; + CDB3A572D3A67D590B0F2BBD28466B22 /* Web3+Methods.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8B046C9471587821A6DD97B726B97ED /* Web3+Methods.swift */; }; + CDFD73E3F48E41AC02FF863606FD8670 /* Web3+ERC1644.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C137ACAC01A9E33FD886930153E09AD /* Web3+ERC1644.swift */; }; + CE2B3CB0ECF5AEA5F5B6905772D9A48F /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C1F58230773D8EC578B7F1DD661BE4C3 /* Foundation.framework */; }; + CF735CE2B0CCDC8143A795A05268E303 /* Web3+BrowserFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8193AD1F3D63A0C11E45AC8A5A73C47C /* Web3+BrowserFunctions.swift */; }; + D14DFF7622138D4EE68899129147EBC3 /* scalar.h in Headers */ = {isa = PBXBuildFile; fileRef = 63713ECBD4C31420BA66F8AB83825B48 /* scalar.h */; settings = {ATTRIBUTES = (Project, ); }; }; + D265EB1D3322C89E88578203E8D30089 /* Promise+Web3+TxPool.swift in Sources */ = {isa = PBXBuildFile; fileRef = B08FF16C37BC6EF8892E6A0802CBF8C7 /* Promise+Web3+TxPool.swift */; }; + D3802E537EDE6A231508103942435FE4 /* Encodable+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C39C45E6514D78B763CEFF99E933770 /* Encodable+Extensions.swift */; }; + D3A4E037E7EF15EB4ADCA79F2F710442 /* Web3+JSONRPC.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC3239FDC43AB5FE6CE9BD4B53DAFC5C /* Web3+JSONRPC.swift */; }; + D48A4410A7C8CE6B6A0787A0F4999DE5 /* Multiplication.swift in Sources */ = {isa = PBXBuildFile; fileRef = C6D029A08E63EF7AA78545C24F65A4F8 /* Multiplication.swift */; }; + D4C52546E7DEE38CEE04F2B6D61BB9E2 /* fwd.h in Headers */ = {isa = PBXBuildFile; fileRef = FCAA06B735107FE87210D20FB8CB012B /* fwd.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D5BD740464E71320CEF4092FA1CF62E8 /* Promise+Web3+Eth+GetAccounts.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA287BB163B2375F495E506EB9B1E209 /* Promise+Web3+Eth+GetAccounts.swift */; }; + D5CEF6D49D61B3072C11D312D977AA3D /* Data+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BE074A266F0E94B24114B1546E61AC8 /* Data+Extension.swift */; }; + D7825440503C1E88B601F86B8AF1E764 /* Web3+Options.swift in Sources */ = {isa = PBXBuildFile; fileRef = 591F1A7AB716B5FA79DB9D222834A48A /* Web3+Options.swift */; }; + D820172C124F8B10D0C72B31F1819FDC /* String+FoundationExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = E93502FD6A791D20161D852AE5F3B836 /* String+FoundationExtension.swift */; }; + D8C90AFD1D666460C3FE007172ED052E /* CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D3B3202C3C1C2CC880557FB97F4905E /* CompactMap.swift */; }; + D9CB9678AA0D7BC8E936869A104D64AD /* Web3+TxPool.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD2DEA99DCB48EFB7F0B0C42FA904B9E /* Web3+TxPool.swift */; }; + DA520170A95D755F0B8F66894620DAAD /* group.h in Headers */ = {isa = PBXBuildFile; fileRef = 94E9A2CBF0228347F1FD0B55E11990A6 /* group.h */; settings = {ATTRIBUTES = (Project, ); }; }; + DA53D83B9E17BD18CF3DDF9FC233D00C /* NonceMiddleware.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1CE430E8FC9DFE318D59DC2FA083E105 /* NonceMiddleware.swift */; }; + DBAFAD28A00E7AA26EABBAFB7DB9040A /* Web3+ERC165.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC61F602DB607EAED91A9F33D38FF56D /* Web3+ERC165.swift */; }; + DBCA1194814B520897C3D81C016F51DB /* BlockDecryptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2BD035B8A8DC2700DC4D8C32EDB44FE0 /* BlockDecryptor.swift */; }; + DBE9A6D9CB82D8605F4C25B9426B1557 /* Codable.swift in Sources */ = {isa = PBXBuildFile; fileRef = ECA67CC7067DB6978A931779EC2F03DB /* Codable.swift */; }; + DBEF0F49E57B3321CC7067EEF33AB582 /* NSNotificationCenter+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 20C42F3DEF3E9D936622D491DC54EA99 /* NSNotificationCenter+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + DCD218381EF101F92FE235D7588750A8 /* ABIParsing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7961F8F15F5930CDBCDB68FB8ECF4AF6 /* ABIParsing.swift */; }; + DD7CAA2463A742FC740431ED674892FD /* ChaCha20.swift in Sources */ = {isa = PBXBuildFile; fileRef = BED199B0BCB4EBFC5A4153E83E36A87A /* ChaCha20.swift */; }; + DFC7A99D7DB5F4C62BA4EC95F31156AF /* Promise+Web3+Eth+GetBlockByHash.swift in Sources */ = {isa = PBXBuildFile; fileRef = E75F349F4B491DD33B917B5CAB379B18 /* Promise+Web3+Eth+GetBlockByHash.swift */; }; + E0067342787B93C845546321EF1DC7D8 /* AES.Cryptors.swift in Sources */ = {isa = PBXBuildFile; fileRef = DEE532DC8F5CC55783D4704934139380 /* AES.Cryptors.swift */; }; + E0B84D75D0F7E7EA2E905C05774CC361 /* Integer Conversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46D93832BC588A5E75BCD0C7779D0156 /* Integer Conversion.swift */; }; + E0C47625480AC84B765B1BD10F8522F0 /* Web3+Protocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 88E610821C9204BB68397CC03BFC2D63 /* Web3+Protocols.swift */; }; + E0CFF076A747B65E1AFECE3BD7DF563B /* basic-config.h in Headers */ = {isa = PBXBuildFile; fileRef = C4BD23E92A083FEE59176D2D9D42FEFF /* basic-config.h */; settings = {ATTRIBUTES = (Project, ); }; }; + E2F80E676FB1398C55C0D8987DBD9187 /* ecmult.h in Headers */ = {isa = PBXBuildFile; fileRef = 03BE9F98CCE9C1262A3343020887933E /* ecmult.h */; settings = {ATTRIBUTES = (Project, ); }; }; + E425FBEC27FF20E38E5F71856145D72C /* UIViewController+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = C878DFC9B0E1798E2D99F69A980D9549 /* UIViewController+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E5445DFB40D0A11F4EE679B7B965CA32 /* scalar_8x32.h in Headers */ = {isa = PBXBuildFile; fileRef = A22F7BE04044B8DCBBA66B0125EB56B0 /* scalar_8x32.h */; settings = {ATTRIBUTES = (Project, ); }; }; + E60107C234FBEF7FB2AE9567A26B6025 /* Web3+Wallet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9BBE5A3FA798D70651487C9758DA7EEA /* Web3+Wallet.swift */; }; + E6947D331B9074A87D47646860DB02F1 /* EIP67Code.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A9184E2FF7C75C2E8A76EB0565B47F6 /* EIP67Code.swift */; }; + E8ABBB87CFEBE721FC2D14B71A719BC2 /* String Conversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = B39B56D87FA59C512E1636D69039C77A /* String Conversion.swift */; }; + E93CF504980B3D653BB4530E7F98E9F6 /* Prime Test.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3CEB28C9E34F3D4AFF3BA00FAABC5CD0 /* Prime Test.swift */; }; + E9D57E847BA0CD23F259C5439DD01CF8 /* Web3+EventParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61448EC862DAE1EBC85136ED829B571F /* Web3+EventParser.swift */; }; + EA95317C04FA46F08399A9F6DFE82119 /* Blowfish+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = F01E85AC9CACC4F20F6B60C540849932 /* Blowfish+Foundation.swift */; }; + EAC994EA457048CA6AA49B82C9F05DF4 /* NSURLSession+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 93E080B9C39B87B655FF7DC0EE07F04E /* NSURLSession+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EB5C9F0BC0A19563C8644FD12BC52ED2 /* scratch_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 5F4FA3CB88027295C344636E166F0EB8 /* scratch_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + EC1F98C6E1424F6190176058FAA43C5A /* UInt8+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 868A0BB9D02C7B72944922A127342822 /* UInt8+Extension.swift */; }; + ED4ED80104798E648B2B82A10DA586F1 /* HMAC+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = E99A3F687C46D78106341FED1A402BB4 /* HMAC+Foundation.swift */; }; + EDA33C46B91D3C87599782C7307F16BA /* EthereumKeystoreV3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 96B8AFD6283C92280EFE9890E6E6FCCC /* EthereumKeystoreV3.swift */; }; + EDE0A58778159BE3D9A942027BE2E33D /* ENSResolver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3B444B88A9193519CB2B5BBD389EF0E6 /* ENSResolver.swift */; }; + EF8241DFA90BCDBB97B8C504BB80D05C /* AnyPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0576642437AF9B433FCB5859FEDB6E4 /* AnyPromise.swift */; }; + EF9BBCE851B820D4F5DA3163BF466A38 /* Process+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 432EA59B99FE0582E2F6240B54A26680 /* Process+Promise.swift */; }; + F001B953A48906D9B7BA0A7986EAEEF7 /* Pods-Web3supportTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 2D3636CE912662624BE63AE6F2BF5DAB /* Pods-Web3supportTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F05D54B8A44050E36A06FF99D14DC771 /* ETHRegistrarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = F80C3E7711C491383D13370C30FAF506 /* ETHRegistrarController.swift */; }; + F13925E2206A7647AC326ECFA6ED2856 /* GCD.swift in Sources */ = {isa = PBXBuildFile; fileRef = E83F2B1C5DFBB2973EB632FFAF431D24 /* GCD.swift */; }; + F2148DCA360E3D898EBFC61989663D7D /* Array+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 702D95C0DC97359B918067BEA40F18DA /* Array+Extension.swift */; }; + F2AD1E375CDB192DB1322931FB22A49C /* NameHash.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17DC771E4A6654F257A7694843F38538 /* NameHash.swift */; }; + F3B9FF17CD827482C5FCDE987FCBA026 /* SHA1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57CDD67FB7CB521BFE99C29464D58CCC /* SHA1.swift */; }; + F44208FA90F7B7118E5A3CA21AB37A84 /* PKCS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 028215446A8A53879AB93D22579AA449 /* PKCS5.swift */; }; + F472C27B7B2B0E9D87D3CA70E537A681 /* Web3+SecurityToken.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4C649F2A3002FB0DDCDFB5E7E0C1042 /* Web3+SecurityToken.swift */; }; + F4DB8BAA8CC2482A2F0408BB78DC5636 /* Array+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1EC242922DC6212EA368159C20B336B /* Array+Extension.swift */; }; + F4EB4FFB5BFE253769101209CBD7BA13 /* ChaCha20+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F7C8B40A0A88989C96E1D7E70C08358 /* ChaCha20+Foundation.swift */; }; + F725A3D4D65CF179A6344254360B6FEF /* Web3+Structures.swift in Sources */ = {isa = PBXBuildFile; fileRef = 146DA39AC7A46437F8C9CB432A0C4699 /* Web3+Structures.swift */; }; + F782C5EF946C6DCC8124E1F5F965ADCA /* BIP32Keystore.swift in Sources */ = {isa = PBXBuildFile; fileRef = A150D976CA7FF85413210E0B9A5359DC /* BIP32Keystore.swift */; }; + F79836F9B32DACCE139E0D3FF0ADBA3A /* Promise+Web3+Eth+GetTransactionReceipt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67EE3284A1AA023A5653ABC2E4831469 /* Promise+Web3+Eth+GetTransactionReceipt.swift */; }; + FA1AFEE1AD9655343C5A77A8A1305EE2 /* num_gmp.h in Headers */ = {isa = PBXBuildFile; fileRef = 72B760A6B3B21E921E0997E5A1ED3346 /* num_gmp.h */; settings = {ATTRIBUTES = (Project, ); }; }; + FB797FAA96B41ACE7474B8ADEF8107EC /* firstly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 258D67386BCD76CE2E07CC3E6C012ADA /* firstly.swift */; }; + FC380F439D913681D738F1BE7B739646 /* ZeroPadding.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2A11ABF6C19483F9CA47C5D675EFB7C /* ZeroPadding.swift */; }; + FC4A5E6CAB0A4C03DD083AFBD48E33DC /* BigUInt+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0657455EEF72FAA880A0147D76B8F491 /* BigUInt+Extensions.swift */; }; + FCD87C142ABB50A223501EBFEC54C689 /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = B66CE42DFFBBE3305B7E73FFA8225F51 /* Extensions.swift */; }; + FCEA3386F95EE7BF8F1524E5FF02D65D /* Web3+Personal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D379163906FA0B9E003D01EBF69D6AD /* Web3+Personal.swift */; }; + FD2338C29B58E91E4414C7DFF0653DF2 /* field.h in Headers */ = {isa = PBXBuildFile; fileRef = C5D9ACF7F5A9E32D3146843C19AC08B8 /* field.h */; settings = {ATTRIBUTES = (Project, ); }; }; + FDF12428281F08B3F5F2B7DB68E3925D /* NSTask+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 30C36A57832FDED028EEED561EE4FD0C /* NSTask+AnyPromise.m */; }; + FE36801FAFBE465DA7DFB6AD05D21CB3 /* ABITypeParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3DD503D6DB58FBC5EB37EE4ED728382E /* ABITypeParser.swift */; }; + FE6E586C19FC7D452C518016634BD270 /* ContractProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6828680E3AFA8645DA486E98E6DDA086 /* ContractProtocol.swift */; }; + FE7D561BE020956E1511CED7CC7BFC61 /* secp256k1_main.h in Headers */ = {isa = PBXBuildFile; fileRef = AE3A37F080DC241F73D429E7434551FE /* secp256k1_main.h */; settings = {ATTRIBUTES = (Project, ); }; }; + FED8C9BB577D35DBB6E5347B750C184C /* hang.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F8CCDE203D8192D751FF69BB9DA8A8D /* hang.swift */; }; + FFF7E224F5F3094210837EC8C7FE4960 /* BigInt-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 8006ACF6A2FC630EC476D9F1F21CC90F /* BigInt-dummy.m */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 0961DD78639170DFD439B2761E56DED4 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 8CDD759A6130CA265C6D157F4407C39B; + remoteInfo = "web3swift-Browser"; + }; + 0A51A901F3B287BBF1000859EC5BBDF8 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 99313990C1D76A6D1D017868B6975CC8; + remoteInfo = CryptoSwift; + }; + 30917E033BC92A1E31096560E8E3617F /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 7C579CE66A1E7A9AA33CA5F97F9C22C5; + remoteInfo = PromiseKit; + }; + 3D115CEE91175984B06F86BF35058C29 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 161C26511FC920CB146236AB7295D5E0; + remoteInfo = secp256k1.c; + }; + 41A570987EA7C14D60BFB0E6373F68F4 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 9B78EE4AF6AE03E79D88886319853FF7; + remoteInfo = Starscream; + }; + 44893332164B13BB6097FB2FC1759C66 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 09DD83B7D075842A3A5105AD410BD38A; + remoteInfo = BigInt; + }; + 49012792450E6349879C50361A907A0A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 7C579CE66A1E7A9AA33CA5F97F9C22C5; + remoteInfo = PromiseKit; + }; + 4FE21A486B0FC29FA900A9C483959DB9 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 161C26511FC920CB146236AB7295D5E0; + remoteInfo = secp256k1.c; + }; + 6CF15647D9C4825B65AD4FF802C3FB39 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 99364D9FB07EF3FA5DFE1237001805EC; + remoteInfo = web3swift; + }; + 7DDECD3D6C9CB99648CF0248D90A07EF /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = BF16A4D4E4C02517868813AFD92FC23D; + remoteInfo = "Pods-Web3support"; + }; + 83C8508E6D07DC36A130031F3F4D8B5E /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 09DD83B7D075842A3A5105AD410BD38A; + remoteInfo = BigInt; + }; + 896D038F81E5A564CD15AB2995B57ACF /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 161C26511FC920CB146236AB7295D5E0; + remoteInfo = secp256k1.c; + }; + 9C21A707FC9B8CE4B8720A654CF3896D /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 09DD83B7D075842A3A5105AD410BD38A; + remoteInfo = BigInt; + }; + A15407EF6D2CABF3C2E38B488FE2D7BE /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 9B78EE4AF6AE03E79D88886319853FF7; + remoteInfo = Starscream; + }; + A1E809480611834A0D655B4C337B06BB /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 99313990C1D76A6D1D017868B6975CC8; + remoteInfo = CryptoSwift; + }; + A811A6706A5A97C6E1581EE917AAE4A7 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 99313990C1D76A6D1D017868B6975CC8; + remoteInfo = CryptoSwift; + }; + B71CBF8CE0F2043749ABE01D111F132F /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 7C579CE66A1E7A9AA33CA5F97F9C22C5; + remoteInfo = PromiseKit; + }; + FE035B72D4A3A68923514A877A94A464 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 9B78EE4AF6AE03E79D88886319853FF7; + remoteInfo = Starscream; + }; + FFADCAF642253937DD1698CD85D78B9D /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 99364D9FB07EF3FA5DFE1237001805EC; + remoteInfo = web3swift; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 002B1E88BA14EBF633CD66EBFBA107E9 /* PromiseKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PromiseKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 01E073C1CD37262FF94E5051A8D55BC3 /* Promise+Web3+Contract+GetIndexedEvents.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Contract+GetIndexedEvents.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Contract+GetIndexedEvents.swift"; sourceTree = ""; }; + 01ED7D9D89508CA7EAA7F1F043495007 /* ecmult_gen_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecmult_gen_impl.h; path = secp256k1/ecmult_gen_impl.h; sourceTree = ""; }; + 02523820D1CEF318C8623ED384F11439 /* web3swift-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "web3swift-prefix.pch"; sourceTree = ""; }; + 02760A62D64944C5DE7DAFDFDEA019F1 /* Cipher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Cipher.swift; path = Sources/CryptoSwift/Cipher.swift; sourceTree = ""; }; + 028215446A8A53879AB93D22579AA449 /* PKCS5.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PKCS5.swift; path = Sources/CryptoSwift/PKCS/PKCS5.swift; sourceTree = ""; }; + 028968F0E8149D086725FEB0C3962475 /* Digest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Digest.swift; path = Sources/CryptoSwift/Digest.swift; sourceTree = ""; }; + 02973070D278C6BA9BAF3D1822786EE6 /* Compression.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Compression.swift; path = Sources/Starscream/Compression.swift; sourceTree = ""; }; + 02BCB8FA01E7F4F5CD44B0D0A4B77AD5 /* Hashable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Hashable.swift; path = Sources/Hashable.swift; sourceTree = ""; }; + 02FBA29B920FE25DB8EE454A4F1E2874 /* Web3+Contract.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Contract.swift"; path = "Sources/web3swift/Web3/Web3+Contract.swift"; sourceTree = ""; }; + 03BE9F98CCE9C1262A3343020887933E /* ecmult.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecmult.h; path = secp256k1/ecmult.h; sourceTree = ""; }; + 03D9157C8C0779B825A21D4DA8C71DAB /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; }; + 05DDCFDA70BFDD11AABC10650442DAAB /* field_10x26_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = field_10x26_impl.h; path = secp256k1/field_10x26_impl.h; sourceTree = ""; }; + 05F1742DB6BF2606852E4AAA34612D4F /* secp256k1.c-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "secp256k1.c-dummy.m"; sourceTree = ""; }; + 0657455EEF72FAA880A0147D76B8F491 /* BigUInt+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "BigUInt+Extensions.swift"; path = "Sources/web3swift/Convenience/BigUInt+Extensions.swift"; sourceTree = ""; }; + 07BA1325EFD33D5292CE17473E5F956F /* PromiseKit-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PromiseKit-umbrella.h"; sourceTree = ""; }; + 081B081BAB76C290DB80364F972A3D98 /* SSLSecurity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SSLSecurity.swift; path = Sources/Starscream/SSLSecurity.swift; sourceTree = ""; }; + 0985EDDA3BE3F9FD09F7D6B612A46446 /* PromiseKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PromiseKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 09CF9FD0B42B944753444D05129D819C /* Web3+Constants.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Constants.swift"; path = "Sources/web3swift/Web3/Web3+Constants.swift"; sourceTree = ""; }; + 0ABAA7E59B6E1E62813742DBFE88342A /* UInt16+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UInt16+Extension.swift"; path = "Sources/CryptoSwift/UInt16+Extension.swift"; sourceTree = ""; }; + 0B12EE372DB1AFDFABD10118DA3C781C /* NativeTypesEncoding+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NativeTypesEncoding+Extensions.swift"; path = "Sources/web3swift/Convenience/NativeTypesEncoding+Extensions.swift"; sourceTree = ""; }; + 0B32A29FD17AA33220D92C8413F32C56 /* ENSBaseRegistrar.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ENSBaseRegistrar.swift; path = Sources/web3swift/Utils/ENS/ENSBaseRegistrar.swift; sourceTree = ""; }; + 0D8A369599F638C6EF1C70946E7DD2F9 /* PublicKey.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PublicKey.swift; path = Sources/web3swift/Utils/ENS/PublicKey.swift; sourceTree = ""; }; + 10554501E08F69E67C555DA71246F0DD /* Array+Foundation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Array+Foundation.swift"; path = "Sources/CryptoSwift/Foundation/Array+Foundation.swift"; sourceTree = ""; }; + 11552264B3AA84951AD6B2F9F0EDF6F9 /* CryptoSwift-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "CryptoSwift-prefix.pch"; sourceTree = ""; }; + 126DC0D7440B4233998413303CE4F65F /* scalar_4x64_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar_4x64_impl.h; path = secp256k1/scalar_4x64_impl.h; sourceTree = ""; }; + 12C5C4C81A590ED070F02E971254DEC4 /* BIP39.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BIP39.swift; path = Sources/web3swift/KeystoreManager/BIP39.swift; sourceTree = ""; }; + 12DC6A0FDF284A2C935F5EA9F6111B0B /* Browser.bundle */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = Browser.bundle; sourceTree = BUILT_PRODUCTS_DIR; }; + 1340186B5B000DD0223DB7799FCEC3E7 /* CBCMAC.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CBCMAC.swift; path = Sources/CryptoSwift/CBCMAC.swift; sourceTree = ""; }; + 135B192A1A9030D073173CE768BD191B /* TransactionSigner.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TransactionSigner.swift; path = Sources/web3swift/Transaction/TransactionSigner.swift; sourceTree = ""; }; + 14198AD5163D601BC6E9E4CEA8F0CE28 /* CryptoSwift-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "CryptoSwift-umbrella.h"; sourceTree = ""; }; + 1422C33CAB7EAA29DB47C9CBDA6F4E46 /* Promise+Batching.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Batching.swift"; path = "Sources/web3swift/Promises/Promise+Batching.swift"; sourceTree = ""; }; + 146DA39AC7A46437F8C9CB432A0C4699 /* Web3+Structures.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Structures.swift"; path = "Sources/web3swift/Web3/Web3+Structures.swift"; sourceTree = ""; }; + 154EA858B5D1E0BA4AF9640574096510 /* Web3+ST20.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ST20.swift"; path = "Sources/web3swift/Tokens/ST20/Web3+ST20.swift"; sourceTree = ""; }; + 16F91688CB98C09F37FB0532B3341B22 /* WebSocket.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WebSocket.swift; path = Sources/Starscream/WebSocket.swift; sourceTree = ""; }; + 170F39C35458E355F4268434C73CF69F /* Pods-Web3supportTests-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-Web3supportTests-Info.plist"; sourceTree = ""; }; + 17DC771E4A6654F257A7694843F38538 /* NameHash.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NameHash.swift; path = Sources/web3swift/Utils/ENS/NameHash.swift; sourceTree = ""; }; + 18192636EB88C2E682F782E9A7FB734B /* Pods-Web3supportTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Web3supportTests.release.xcconfig"; sourceTree = ""; }; + 18839F6AF587B42905500F08F445E61B /* ENSReverseRegistrar.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ENSReverseRegistrar.swift; path = Sources/web3swift/Utils/ENS/ENSReverseRegistrar.swift; sourceTree = ""; }; + 18FC982ED53EDF2CD0C51B0E3E600099 /* MD5.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MD5.swift; path = Sources/CryptoSwift/MD5.swift; sourceTree = ""; }; + 1A743A4FD9581DB6D29F599446B85E5B /* PromiseKit-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PromiseKit-prefix.pch"; sourceTree = ""; }; + 1A9184E2FF7C75C2E8A76EB0565B47F6 /* EIP67Code.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EIP67Code.swift; path = Sources/web3swift/Utils/EIP/EIP67Code.swift; sourceTree = ""; }; + 1ACC2FBAD75E9B64031CB9CD3CFA6292 /* KeystoreV3JSONStructure.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KeystoreV3JSONStructure.swift; path = Sources/web3swift/KeystoreManager/KeystoreV3JSONStructure.swift; sourceTree = ""; }; + 1B20BDCDA0ECDF19F240EFFE03A8A53E /* Operators.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Operators.swift; path = Sources/CryptoSwift/Operators.swift; sourceTree = ""; }; + 1C0168721A40963DC1F398E1A4B087F6 /* Promise+Web3+Eth+GetGasPrice.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+GetGasPrice.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+GetGasPrice.swift"; sourceTree = ""; }; + 1C0721CA0C6A5B018F4B496B54F7D274 /* ABIElements.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ABIElements.swift; path = Sources/web3swift/EthereumABI/ABIElements.swift; sourceTree = ""; }; + 1CE430E8FC9DFE318D59DC2FA083E105 /* NonceMiddleware.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NonceMiddleware.swift; path = Sources/web3swift/Utils/Hooks/NonceMiddleware.swift; sourceTree = ""; }; + 1D6BEB657B8F0CC4FEB1C0944BF892E8 /* CryptoExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CryptoExtensions.swift; path = Sources/web3swift/Convenience/CryptoExtensions.swift; sourceTree = ""; }; + 1E64004ED18613E15E5FA474A4F25ECD /* Pods-Web3support-Web3supportUITests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Web3support-Web3supportUITests.release.xcconfig"; sourceTree = ""; }; + 1F0FEF67DA3E548C1E04B0EBFF9FEBDE /* Catchable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Catchable.swift; path = Sources/Catchable.swift; sourceTree = ""; }; + 204DC1705C56D7DB30888861287AAED5 /* UIView+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIView+Promise.swift"; path = "Extensions/UIKit/Sources/UIView+Promise.swift"; sourceTree = ""; }; + 2066491A6B91B84DBCE53F56D07835B9 /* Starscream.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Starscream.modulemap; sourceTree = ""; }; + 20C42F3DEF3E9D936622D491DC54EA99 /* NSNotificationCenter+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSNotificationCenter+AnyPromise.h"; path = "Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.h"; sourceTree = ""; }; + 21C0A4CE9CD0DC1F4665EB462C637348 /* scalar_low_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar_low_impl.h; path = secp256k1/scalar_low_impl.h; sourceTree = ""; }; + 22BF1378E05475FF065F31B3478EB217 /* dispatch_promise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = dispatch_promise.m; path = Sources/dispatch_promise.m; sourceTree = ""; }; + 23921C08E5242DAB552A4287DD4B4EA9 /* BrowserViewController.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BrowserViewController.swift; path = Sources/web3swift/Browser/BrowserViewController.swift; sourceTree = ""; }; + 244C067EFEB7A2C4E5ECDDDCF3FB0D79 /* Box.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Box.swift; path = Sources/Box.swift; sourceTree = ""; }; + 2451EA550A1CAB5C8BB12B5CEDD686C2 /* Pods-Web3support.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-Web3support.modulemap"; sourceTree = ""; }; + 258D67386BCD76CE2E07CC3E6C012ADA /* firstly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = firstly.swift; path = Sources/firstly.swift; sourceTree = ""; }; + 25FD464B4ADFC965F65DEB27E8F457B6 /* Scrypt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Scrypt.swift; path = Sources/CryptoSwift/Scrypt.swift; sourceTree = ""; }; + 280705F0E0D0EBC84DFBBA1068758D6D /* Starscream.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Starscream.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 283FFF6A596C1D84BB8FF9BA94A7ADDB /* CustomStringConvertible.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CustomStringConvertible.swift; path = Sources/CustomStringConvertible.swift; sourceTree = ""; }; + 2BD035B8A8DC2700DC4D8C32EDB44FE0 /* BlockDecryptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BlockDecryptor.swift; path = Sources/CryptoSwift/BlockDecryptor.swift; sourceTree = ""; }; + 2C498EC6CEB8421E6EFA36FD8BF629BC /* Web3+WebsocketProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+WebsocketProvider.swift"; path = "Sources/web3swift/Web3/Web3+WebsocketProvider.swift"; sourceTree = ""; }; + 2CC1AE9780ED61CC18DBBB15157156FE /* ResourceBundle-Browser-web3swift-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "ResourceBundle-Browser-web3swift-Info.plist"; sourceTree = ""; }; + 2D3636CE912662624BE63AE6F2BF5DAB /* Pods-Web3supportTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-Web3supportTests-umbrella.h"; sourceTree = ""; }; + 2D82E51D53BAD38089B1DB95451764EF /* Promise+Web3+Eth+Call.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+Call.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+Call.swift"; sourceTree = ""; }; + 2DFB28013DE80EDBBA6612BE5291E3BF /* Web3+ERC721x.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC721x.swift"; path = "Sources/web3swift/Tokens/ERC721x/Web3+ERC721x.swift"; sourceTree = ""; }; + 2E123B4A564E405B1FEE02F48D534532 /* field_5x52_int128_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = field_5x52_int128_impl.h; path = secp256k1/field_5x52_int128_impl.h; sourceTree = ""; }; + 2E41C42E5233827CA9E9E88D318D954B /* Promise+Web3+Eth+GetTransactionCount.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+GetTransactionCount.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionCount.swift"; sourceTree = ""; }; + 2EAE3334F923A49D94EA8B8A709A09FD /* SHA2.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SHA2.swift; path = Sources/CryptoSwift/SHA2.swift; sourceTree = ""; }; + 2F7C8B40A0A88989C96E1D7E70C08358 /* ChaCha20+Foundation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ChaCha20+Foundation.swift"; path = "Sources/CryptoSwift/Foundation/ChaCha20+Foundation.swift"; sourceTree = ""; }; + 2F7D0C84A7512E1A50E355458C653748 /* BlockEncryptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BlockEncryptor.swift; path = Sources/CryptoSwift/BlockEncryptor.swift; sourceTree = ""; }; + 2F7D2C17D3B22156BFB54CEFC3FC8C84 /* Pods-Web3support.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Web3support.release.xcconfig"; sourceTree = ""; }; + 2FF9F9D0F195D9CCFBC308CE982B37AA /* field_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = field_impl.h; path = secp256k1/field_impl.h; sourceTree = ""; }; + 3017C17B6A19772F40C2A00CC7053EC7 /* Web3+ReadingTransaction.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ReadingTransaction.swift"; path = "Sources/web3swift/Web3/Web3+ReadingTransaction.swift"; sourceTree = ""; }; + 3056036973AE29A6057B82086C2B0D84 /* recovery_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = recovery_impl.h; path = secp256k1/recovery_impl.h; sourceTree = ""; }; + 3072E80789DEC0486492C1400591C726 /* Updatable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Updatable.swift; path = Sources/CryptoSwift/Updatable.swift; sourceTree = ""; }; + 3099C8E0DFDA6B882C0E55B94FBB3E85 /* Int+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Int+Extension.swift"; path = "Sources/CryptoSwift/Int+Extension.swift"; sourceTree = ""; }; + 30C36A57832FDED028EEED561EE4FD0C /* NSTask+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSTask+AnyPromise.m"; path = "Extensions/Foundation/Sources/NSTask+AnyPromise.m"; sourceTree = ""; }; + 31D4B4B7AA6178320AD9429501FB9D42 /* ecmult_const_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecmult_const_impl.h; path = secp256k1/ecmult_const_impl.h; sourceTree = ""; }; + 3272C752A91B1AF557A81D034B598BBB /* web3swift.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = web3swift.modulemap; sourceTree = ""; }; + 327BEAF521485F0E297F4294ED918852 /* DigestType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DigestType.swift; path = Sources/CryptoSwift/DigestType.swift; sourceTree = ""; }; + 331DA5AED7BF5F4646A90D6F77C91A22 /* num.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = num.h; path = secp256k1/num.h; sourceTree = ""; }; + 332A47430CFF99501D563788C7AAF1D2 /* secp256k1.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = secp256k1.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 334450DD7B6EA290D629965834A78C15 /* secp256k1.c */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.c; name = secp256k1.c; path = secp256k1/secp256k1.c; sourceTree = ""; }; + 3386535C108CE2E4983FF6FBAB1C7E01 /* Promise+Web3+Eth+GetBlockNumber.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+GetBlockNumber.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockNumber.swift"; sourceTree = ""; }; + 33F839ECDA9D6E925A8BCA131A664905 /* Web3+ERC888.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC888.swift"; path = "Sources/web3swift/Tokens/ERC888/Web3+ERC888.swift"; sourceTree = ""; }; + 348BCAB7AD52B6413E93EA928F7BEE6A /* Web3+Eventloop.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Eventloop.swift"; path = "Sources/web3swift/Web3/Web3+Eventloop.swift"; sourceTree = ""; }; + 351509184374C023BC9E7318D6D240EC /* Web3+Instance.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Instance.swift"; path = "Sources/web3swift/Web3/Web3+Instance.swift"; sourceTree = ""; }; + 37D6266F529B95CA085B5703D44D3C61 /* secp256k1.c-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "secp256k1.c-prefix.pch"; sourceTree = ""; }; + 380AE05F318DC350995E5E66ACC19F19 /* web3swift-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "web3swift-dummy.m"; sourceTree = ""; }; + 384E922D8BC4146E932C077F9A2C0651 /* AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AnyPromise.h; path = Sources/AnyPromise.h; sourceTree = ""; }; + 3910EE551F198BF1791FF438496F9747 /* Words and Bits.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Words and Bits.swift"; path = "Sources/Words and Bits.swift"; sourceTree = ""; }; + 393B420FFE5ABFF234074A6F50BA84EE /* Pods-Web3support-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-Web3support-frameworks.sh"; sourceTree = ""; }; + 394050D026F0D950AC11CB1CB8965A25 /* AEAD.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AEAD.swift; path = Sources/CryptoSwift/AEAD/AEAD.swift; sourceTree = ""; }; + 394218B5A5E8E974A3936D3FF6EBB7D9 /* BigInt.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = BigInt.release.xcconfig; sourceTree = ""; }; + 3B444B88A9193519CB2B5BBD389EF0E6 /* ENSResolver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ENSResolver.swift; path = Sources/web3swift/Utils/ENS/ENSResolver.swift; sourceTree = ""; }; + 3BE074A266F0E94B24114B1546E61AC8 /* Data+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Data+Extension.swift"; path = "Sources/web3swift/Convenience/Data+Extension.swift"; sourceTree = ""; }; + 3C9C4EF51D56F3A2F8C1351ECFBECA51 /* scalar_low.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar_low.h; path = secp256k1/scalar_low.h; sourceTree = ""; }; + 3CEB28C9E34F3D4AFF3BA00FAABC5CD0 /* Prime Test.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Prime Test.swift"; path = "Sources/Prime Test.swift"; sourceTree = ""; }; + 3D239122D0D5E4554A0AE9781080164F /* Configuration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Configuration.swift; path = Sources/Configuration.swift; sourceTree = ""; }; + 3D3F3745A7D0E990E715D852768455F2 /* Subtraction.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Subtraction.swift; path = Sources/Subtraction.swift; sourceTree = ""; }; + 3D81CBF6EA6135E28DA96DDC5089008E /* secp256k1-config.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "secp256k1-config.h"; path = "secp256k1/secp256k1-config.h"; sourceTree = ""; }; + 3DD503D6DB58FBC5EB37EE4ED728382E /* ABITypeParser.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ABITypeParser.swift; path = Sources/web3swift/EthereumABI/ABITypeParser.swift; sourceTree = ""; }; + 3E6F02468AD363BFC7279A294B4087E6 /* Collection+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Collection+Extension.swift"; path = "Sources/CryptoSwift/Collection+Extension.swift"; sourceTree = ""; }; + 3EBF7696596A1EE1DDA7A1F1962DD10D /* secp256k1.c.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = secp256k1.c.release.xcconfig; sourceTree = ""; }; + 3FF1FE9FD2130495BEE330898A681C39 /* Data+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Data+Extension.swift"; path = "Sources/CryptoSwift/Foundation/Data+Extension.swift"; sourceTree = ""; }; + 424FF13781C45B35C9ACA160B6118661 /* Padding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Padding.swift; path = Sources/CryptoSwift/Padding.swift; sourceTree = ""; }; + 431DFDCD5EBFCE95F388BD650BC3F510 /* EIP681.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EIP681.swift; path = Sources/web3swift/Utils/EIP/EIP681.swift; sourceTree = ""; }; + 432EA59B99FE0582E2F6240B54A26680 /* Process+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Process+Promise.swift"; path = "Extensions/Foundation/Sources/Process+Promise.swift"; sourceTree = ""; }; + 43CB51FED61E2F731154A09AB346B249 /* ComparisonExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ComparisonExtensions.swift; path = Sources/web3swift/Contract/ComparisonExtensions.swift; sourceTree = ""; }; + 447FB67D09E4D83CDF62C0379ACCC6B5 /* ABIEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ABIEncoding.swift; path = Sources/web3swift/EthereumABI/ABIEncoding.swift; sourceTree = ""; }; + 46D93832BC588A5E75BCD0C7779D0156 /* Integer Conversion.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Integer Conversion.swift"; path = "Sources/Integer Conversion.swift"; sourceTree = ""; }; + 475C972BE4005D9924C3092BBB7F699C /* Pods-Web3support-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-Web3support-acknowledgements.markdown"; sourceTree = ""; }; + 4A013B1BDD344AC6EAC71EC4DEA1CDA5 /* Square Root.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Square Root.swift"; path = "Sources/Square Root.swift"; sourceTree = ""; }; + 4AE1FB59AAB7CFCF16F4D7AECE524894 /* BIP32HDNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BIP32HDNode.swift; path = Sources/web3swift/KeystoreManager/BIP32HDNode.swift; sourceTree = ""; }; + 4BFDF5AAA317492732B1D0EECF6E68CB /* EthereumTransaction.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EthereumTransaction.swift; path = Sources/web3swift/Transaction/EthereumTransaction.swift; sourceTree = ""; }; + 4DD919542E41CB8E150F5DFC1A540CE6 /* SHA3.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SHA3.swift; path = Sources/CryptoSwift/SHA3.swift; sourceTree = ""; }; + 4E71AAA8231758E672E3ACF6D694EA8D /* Starscream-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Starscream-Info.plist"; sourceTree = ""; }; + 4EAF871AD72ED8B98E4F956A00841E95 /* field_10x26.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = field_10x26.h; path = secp256k1/field_10x26.h; sourceTree = ""; }; + 4F8B5FCF5522ECCD06CE444D5061F541 /* Generics.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Generics.swift; path = Sources/CryptoSwift/Generics.swift; sourceTree = ""; }; + 4FBCC7677F3EE13A0DC4495B13E7A571 /* Promise+Web3+Personal+Sign.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Personal+Sign.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Personal+Sign.swift"; sourceTree = ""; }; + 52EC6BE68BAEE295055F52FF1C3B58B2 /* web3swift-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "web3swift-Info.plist"; sourceTree = ""; }; + 532A38B4F523E15890612D5578B901BF /* Web3+Eth+Websocket.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Eth+Websocket.swift"; path = "Sources/web3swift/Web3/Web3+Eth+Websocket.swift"; sourceTree = ""; }; + 5342D36974BCDE8EC75703FD3DBF9F3B /* AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AnyPromise.m; path = Sources/AnyPromise.m; sourceTree = ""; }; + 534AD27A9601B753D3C895597DDB078C /* join.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = join.m; path = Sources/join.m; sourceTree = ""; }; + 537B9FE8F0466BB2293902B1450ED4AE /* CFB.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CFB.swift; path = Sources/CryptoSwift/BlockMode/CFB.swift; sourceTree = ""; }; + 554B02C9539B4DE5F116BC0148B0341F /* Data Conversion.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Data Conversion.swift"; path = "Sources/Data Conversion.swift"; sourceTree = ""; }; + 558429F8ABA5EF6470234B32E39EE6DB /* BatchedCollection.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BatchedCollection.swift; path = Sources/CryptoSwift/BatchedCollection.swift; sourceTree = ""; }; + 567E8F1F8BB7A75EC66096359A535F84 /* race.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = race.swift; path = Sources/race.swift; sourceTree = ""; }; + 570E189613076E0A18DAF4AC1072CA69 /* PMKUIKit.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PMKUIKit.h; path = Extensions/UIKit/Sources/PMKUIKit.h; sourceTree = ""; }; + 572C8E0F590539A171571F4C06D8CB9A /* group_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = group_impl.h; path = secp256k1/group_impl.h; sourceTree = ""; }; + 57536CB2627D968FD6667AA3AA245EB1 /* EventFiltering.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EventFiltering.swift; path = Sources/web3swift/Contract/EventFiltering.swift; sourceTree = ""; }; + 57CDD67FB7CB521BFE99C29464D58CCC /* SHA1.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SHA1.swift; path = Sources/CryptoSwift/SHA1.swift; sourceTree = ""; }; + 58406D2F94BB714CDB81DAACFAE2A10D /* CryptoSwift-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "CryptoSwift-dummy.m"; sourceTree = ""; }; + 5856772748611034A2DC9F7D6F13F3AD /* hash.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = hash.h; path = secp256k1/hash.h; sourceTree = ""; }; + 591F1A7AB716B5FA79DB9D222834A48A /* Web3+Options.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Options.swift"; path = "Sources/web3swift/Web3/Web3+Options.swift"; sourceTree = ""; }; + 59C0A0783CBBE1C7C8F3D2F34AAAEB96 /* Web3+ERC1594.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1594.swift"; path = "Sources/web3swift/Tokens/ERC1594/Web3+ERC1594.swift"; sourceTree = ""; }; + 5A4FCAA67F0525DDA4FF3F94B5BBE816 /* ABI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ABI.swift; path = Sources/web3swift/EthereumABI/ABI.swift; sourceTree = ""; }; + 5BD8315263E70B60082686DB2FFF5188 /* AEADChaCha20Poly1305.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AEADChaCha20Poly1305.swift; path = Sources/CryptoSwift/AEAD/AEADChaCha20Poly1305.swift; sourceTree = ""; }; + 5D9411FFEE688C3F4C176C536884F130 /* BigInt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BigInt.swift; path = Sources/BigInt.swift; sourceTree = ""; }; + 5DA9CD391B4D5E614CAE1DB405B5D95E /* wk.bridge.min.js */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.javascript; name = wk.bridge.min.js; path = Sources/web3swift/Browser/wk.bridge.min.js; sourceTree = ""; }; + 5E0378DB2D3422FFD6E14F74781F0694 /* Strideable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Strideable.swift; path = Sources/Strideable.swift; sourceTree = ""; }; + 5F4FA3CB88027295C344636E166F0EB8 /* scratch_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scratch_impl.h; path = secp256k1/scratch_impl.h; sourceTree = ""; }; + 5F8CCDE203D8192D751FF69BB9DA8A8D /* hang.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = hang.swift; path = Sources/hang.swift; sourceTree = ""; }; + 5FE4310FF86028C19F34F611D349E859 /* when.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = when.m; path = Sources/when.m; sourceTree = ""; }; + 61448EC862DAE1EBC85136ED829B571F /* Web3+EventParser.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+EventParser.swift"; path = "Sources/web3swift/Web3/Web3+EventParser.swift"; sourceTree = ""; }; + 635FCDE74A464A0EB4FF9B4D20DD8A80 /* ABIParameterTypes.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ABIParameterTypes.swift; path = Sources/web3swift/EthereumABI/ABIParameterTypes.swift; sourceTree = ""; }; + 63713ECBD4C31420BA66F8AB83825B48 /* scalar.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar.h; path = secp256k1/scalar.h; sourceTree = ""; }; + 63BE7C86DDBB5ECBFFA35C3F78742ADF /* UInt64+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UInt64+Extension.swift"; path = "Sources/CryptoSwift/UInt64+Extension.swift"; sourceTree = ""; }; + 650ACFA17614B44CE86F21F89BCED8F7 /* secp256k1.c.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = secp256k1.c.modulemap; sourceTree = ""; }; + 651202A8AF433994EE5EB83E9CB8D24A /* Pods-Web3support-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-Web3support-Info.plist"; sourceTree = ""; }; + 6628230DE91FEFDC792C7DBD31BE5251 /* LogEvent.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LogEvent.swift; path = Sources/LogEvent.swift; sourceTree = ""; }; + 6696E07735F6561C9C4A983FE82A92E7 /* AES+Foundation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "AES+Foundation.swift"; path = "Sources/CryptoSwift/Foundation/AES+Foundation.swift"; sourceTree = ""; }; + 66F16B5D8DEE8BDE87CC2408D8FE5FE3 /* IBAN.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = IBAN.swift; path = Sources/web3swift/KeystoreManager/IBAN.swift; sourceTree = ""; }; + 6710D1A5A55B50814F9994C62AEF5E9D /* Authenticator.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Authenticator.swift; path = Sources/CryptoSwift/Authenticator.swift; sourceTree = ""; }; + 674945A263B5A171B0D8CAC79DAA6216 /* Cryptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Cryptor.swift; path = Sources/CryptoSwift/Cryptor.swift; sourceTree = ""; }; + 67EE3284A1AA023A5653ABC2E4831469 /* Promise+Web3+Eth+GetTransactionReceipt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+GetTransactionReceipt.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionReceipt.swift"; sourceTree = ""; }; + 6828680E3AFA8645DA486E98E6DDA086 /* ContractProtocol.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ContractProtocol.swift; path = Sources/web3swift/Contract/ContractProtocol.swift; sourceTree = ""; }; + 6875770FBEBE2AF71365EB6DC30E3027 /* secp256k1.c.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = secp256k1.c.debug.xcconfig; sourceTree = ""; }; + 696516B833D002C3DE6DF92361767CA1 /* BloomFilter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BloomFilter.swift; path = Sources/web3swift/Transaction/BloomFilter.swift; sourceTree = ""; }; + 699763CCB6877CF34141DDE755F441EB /* Random.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Random.swift; path = Sources/Random.swift; sourceTree = ""; }; + 6A06F8FE8838CD882B9939831BCCE338 /* String+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "String+Extension.swift"; path = "Sources/web3swift/Convenience/String+Extension.swift"; sourceTree = ""; }; + 6A88AC5A168517938F01A76CAAE7EBEA /* CoreImage.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreImage.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/CoreImage.framework; sourceTree = DEVELOPER_DIR; }; + 6C537535F3EDDBA8ED7569976986A05A /* Starscream.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Starscream.release.xcconfig; sourceTree = ""; }; + 6D196B49035EE2558CA931156B3CC775 /* Web3+Utils.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Utils.swift"; path = "Sources/web3swift/Web3/Web3+Utils.swift"; sourceTree = ""; }; + 6D3B3202C3C1C2CC880557FB97F4905E /* CompactMap.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CompactMap.swift; path = Sources/CryptoSwift/CompactMap.swift; sourceTree = ""; }; + 6D93B2F6F631256A8EF3546A2D3015E9 /* Blowfish.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Blowfish.swift; path = Sources/CryptoSwift/Blowfish.swift; sourceTree = ""; }; + 6DAFC7859E7882E5E0AB3A29C3082C9E /* UIViewController+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIViewController+AnyPromise.m"; path = "Extensions/UIKit/Sources/UIViewController+AnyPromise.m"; sourceTree = ""; }; + 6E105DF01C418F3B1C230920F963BE01 /* num_gmp_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = num_gmp_impl.h; path = secp256k1/num_gmp_impl.h; sourceTree = ""; }; + 6E285CA56194AF49BFD1EFB5C97D4334 /* BigInt-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "BigInt-umbrella.h"; sourceTree = ""; }; + 6F1CC28425C72AC8913BE51E129F555C /* Promise+Web3+Eth+SendTransaction.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+SendTransaction.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+SendTransaction.swift"; sourceTree = ""; }; + 6F6E3A560F30E6C76BE396A97D419B02 /* web3swift-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "web3swift-umbrella.h"; sourceTree = ""; }; + 702D95C0DC97359B918067BEA40F18DA /* Array+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Array+Extension.swift"; path = "Sources/web3swift/Convenience/Array+Extension.swift"; sourceTree = ""; }; + 72B760A6B3B21E921E0997E5A1ED3346 /* num_gmp.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = num_gmp.h; path = secp256k1/num_gmp.h; sourceTree = ""; }; + 72CA11293C1FEAD46D53B50D3F53830A /* Pods-Web3support-Web3supportUITests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Web3support-Web3supportUITests.debug.xcconfig"; sourceTree = ""; }; + 73938AA4C7CACF9566B3616D650B0283 /* EthereumContract.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EthereumContract.swift; path = Sources/web3swift/Contract/EthereumContract.swift; sourceTree = ""; }; + 73AE9CE7C402316A90015D8FE30A9C17 /* Pods-Web3support-Web3supportUITests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-Web3support-Web3supportUITests-dummy.m"; sourceTree = ""; }; + 73FA6458DA183DF514E42FE54DC27E66 /* Promise+Web3+Eth+GetTransactionDetails.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+GetTransactionDetails.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionDetails.swift"; sourceTree = ""; }; + 74C2AE8219D8A019AF481B6F3383E570 /* Web3+InfuraProviders.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+InfuraProviders.swift"; path = "Sources/web3swift/Web3/Web3+InfuraProviders.swift"; sourceTree = ""; }; + 75235A710D5C7405350FE8C421CF7EE2 /* Utils.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Utils.swift; path = Sources/CryptoSwift/Utils.swift; sourceTree = ""; }; + 774CC24C803B0C79461A6923DC01B31A /* NSObject+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSObject+Promise.swift"; path = "Extensions/Foundation/Sources/NSObject+Promise.swift"; sourceTree = ""; }; + 782C474493177E8883905027041AA3AE /* Pods-Web3support-Web3supportUITests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-Web3support-Web3supportUITests-acknowledgements.plist"; sourceTree = ""; }; + 79548549FC0A5BE4E92657ADCE6AFB03 /* Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Promise.swift; path = Sources/Promise.swift; sourceTree = ""; }; + 7961F8F15F5930CDBCDB68FB8ECF4AF6 /* ABIParsing.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ABIParsing.swift; path = Sources/web3swift/EthereumABI/ABIParsing.swift; sourceTree = ""; }; + 7A38ECCB5ECDCB46FC3DD46AE1FC4FC1 /* String+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "String+Extension.swift"; path = "Sources/CryptoSwift/String+Extension.swift"; sourceTree = ""; }; + 7AEBAA42453A3627D0C260F40E3ABA32 /* Promise+Web3+Eth+GetBlockByNumber.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+GetBlockByNumber.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByNumber.swift"; sourceTree = ""; }; + 7B045C7857F3FB23BE6496792365B9C5 /* after.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = after.m; path = Sources/after.m; sourceTree = ""; }; + 7B4BF3C05BC39315DAE89F43DA29C75A /* Promise+Web3+Personal+CreateAccount.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Personal+CreateAccount.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Personal+CreateAccount.swift"; sourceTree = ""; }; + 7BADEECA71797B1FBC1DCAECD0854C8C /* Utils+Foundation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Utils+Foundation.swift"; path = "Sources/CryptoSwift/Foundation/Utils+Foundation.swift"; sourceTree = ""; }; + 7C39C45E6514D78B763CEFF99E933770 /* Encodable+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Encodable+Extensions.swift"; path = "Sources/web3swift/Convenience/Encodable+Extensions.swift"; sourceTree = ""; }; + 7C61C143CBF81F3DC8D70800ABDB2FDB /* secp256k1.c-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "secp256k1.c-Info.plist"; sourceTree = ""; }; + 7CC5B4139CDFFD75E516BC0C7EB1BA82 /* ecdsa.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecdsa.h; path = secp256k1/ecdsa.h; sourceTree = ""; }; + 7D04CD7E1EF55A225C04E7F16EB3E724 /* field_5x52.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = field_5x52.h; path = secp256k1/field_5x52.h; sourceTree = ""; }; + 7DDF8B3C487BB15A7C9D7E0F66D04AEB /* RLP.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RLP.swift; path = Sources/web3swift/SwiftRLP/RLP.swift; sourceTree = ""; }; + 7E306D7806FF9EE954924600AA4E1289 /* PlainKeystore.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PlainKeystore.swift; path = Sources/web3swift/KeystoreManager/PlainKeystore.swift; sourceTree = ""; }; + 7F1D0B138A229542223B16185A746888 /* Addition.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Addition.swift; path = Sources/Addition.swift; sourceTree = ""; }; + 7F89D5E973A70A3593E25EBE22FACAD1 /* OFB.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = OFB.swift; path = Sources/CryptoSwift/BlockMode/OFB.swift; sourceTree = ""; }; + 7FE8062FF8F7EE71B525E058FCD7F293 /* BlockMode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BlockMode.swift; path = Sources/CryptoSwift/BlockMode/BlockMode.swift; sourceTree = ""; }; + 8006ACF6A2FC630EC476D9F1F21CC90F /* BigInt-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "BigInt-dummy.m"; sourceTree = ""; }; + 8008892ABCADAD4E5DC4AA60DC647E31 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Sources/Error.swift; sourceTree = ""; }; + 8157D1CD9BA421F2A9DFD9E6C19D177A /* Pods-Web3supportTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-Web3supportTests-acknowledgements.markdown"; sourceTree = ""; }; + 8193AD1F3D63A0C11E45AC8A5A73C47C /* Web3+BrowserFunctions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+BrowserFunctions.swift"; path = "Sources/web3swift/HookedFunctions/Web3+BrowserFunctions.swift"; sourceTree = ""; }; + 8213F1D4FED15BCAC1769CCD95E698F3 /* Decodable+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Decodable+Extensions.swift"; path = "Sources/web3swift/Convenience/Decodable+Extensions.swift"; sourceTree = ""; }; + 821FD64A61CCB7CBE3A1388FA84834F8 /* Guarantee.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Guarantee.swift; path = Sources/Guarantee.swift; sourceTree = ""; }; + 838EF9154AB93D92DB9762BDF5BED700 /* PromiseKit-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "PromiseKit-Info.plist"; sourceTree = ""; }; + 84586FE14E05B1A73DAE9DD316A9D7F2 /* Starscream-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Starscream-umbrella.h"; sourceTree = ""; }; + 84C22EA32BF12EF808714F9517EE7550 /* Pods-Web3support-Web3supportUITests-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-Web3support-Web3supportUITests-Info.plist"; sourceTree = ""; }; + 8557A2308502510B11D958EF167ED7DB /* secp256k1.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = secp256k1.h; path = secp256k1/include/secp256k1.h; sourceTree = ""; }; + 8571C3C4E2540AE79C82CC088FF5C809 /* Promise+Web3+Personal+UnlockAccount.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Personal+UnlockAccount.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Personal+UnlockAccount.swift"; sourceTree = ""; }; + 857E7AB10DF6BDB0B3A11DF7F010FFAC /* BigInt.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = BigInt.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 8590CEF2172C5BB2B9EFFE7B18A88B42 /* NoPadding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NoPadding.swift; path = Sources/CryptoSwift/NoPadding.swift; sourceTree = ""; }; + 868A0BB9D02C7B72944922A127342822 /* UInt8+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UInt8+Extension.swift"; path = "Sources/CryptoSwift/UInt8+Extension.swift"; sourceTree = ""; }; + 869339C036B9B7D93560C6864892AAFE /* PBKDF1.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PBKDF1.swift; path = Sources/CryptoSwift/PKCS/PBKDF1.swift; sourceTree = ""; }; + 86CD85F105AE8490C4D11A857DCCA542 /* Pods_Web3support.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Web3support.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 88E610821C9204BB68397CC03BFC2D63 /* Web3+Protocols.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Protocols.swift"; path = "Sources/web3swift/Web3/Web3+Protocols.swift"; sourceTree = ""; }; + 89047AD6A8F9DED9AD3FAFA4C7E7DC94 /* Promise+Web3+Eth+EstimateGas.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+EstimateGas.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+EstimateGas.swift"; sourceTree = ""; }; + 8910795635358AF5D3F10D643064EF90 /* Web3+HttpProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+HttpProvider.swift"; path = "Sources/web3swift/Web3/Web3+HttpProvider.swift"; sourceTree = ""; }; + 891B2270823847ED23F2ECFC28F935EC /* Starscream.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Starscream.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 892E151D44D4707DBC204D6F59A99099 /* ecmult_const.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecmult_const.h; path = secp256k1/ecmult_const.h; sourceTree = ""; }; + 8A2449DF78D58AD33A7C7504BB3F38A0 /* web3swift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = web3swift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 8B59B8ED26308215F98BAEB6995ADE07 /* CCM.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CCM.swift; path = Sources/CryptoSwift/BlockMode/CCM.swift; sourceTree = ""; }; + 8C6445049DF4ABD6CE3F2C38F4C8A6C3 /* num_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = num_impl.h; path = secp256k1/num_impl.h; sourceTree = ""; }; + 8F4E403D89A362925BE6A61E7E6F853A /* Checksum.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Checksum.swift; path = Sources/CryptoSwift/Checksum.swift; sourceTree = ""; }; + 90692F209BCE17E51BF1F4EDE5BC6EFB /* Starscream-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Starscream-prefix.pch"; sourceTree = ""; }; + 9135FA8D9B973BC1A3763F25AA44FF64 /* scalar_4x64.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar_4x64.h; path = secp256k1/scalar_4x64.h; sourceTree = ""; }; + 91BB24BA472AF523E913108C9AA301F2 /* BigInt.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = BigInt.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 920C71B5D95409F2CAD974B09E5ED5D0 /* Pods-Web3support-Web3supportUITests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-Web3support-Web3supportUITests.modulemap"; sourceTree = ""; }; + 92E1E02B823CD4C95D631F27E2D62E35 /* BigInt-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "BigInt-Info.plist"; sourceTree = ""; }; + 93E080B9C39B87B655FF7DC0EE07F04E /* NSURLSession+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSURLSession+AnyPromise.h"; path = "Extensions/Foundation/Sources/NSURLSession+AnyPromise.h"; sourceTree = ""; }; + 94E9A2CBF0228347F1FD0B55E11990A6 /* group.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = group.h; path = secp256k1/group.h; sourceTree = ""; }; + 95FEF9A336D74B30EEC3F0905F44CC91 /* Promise+Web3+Eth+GetBalance.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+GetBalance.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+GetBalance.swift"; sourceTree = ""; }; + 964D41D5C54F916868B511A8E50EF359 /* Promise+Web3+Eth+SendRawTransaction.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+SendRawTransaction.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+SendRawTransaction.swift"; sourceTree = ""; }; + 96B8AFD6283C92280EFE9890E6E6FCCC /* EthereumKeystoreV3.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EthereumKeystoreV3.swift; path = Sources/web3swift/KeystoreManager/EthereumKeystoreV3.swift; sourceTree = ""; }; + 96BA76B86413F1BD6D2642279E7BB1AD /* util.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = util.h; path = secp256k1/util.h; sourceTree = ""; }; + 9851214ACA0341CA2837DCCE2C90ED9B /* UIViewPropertyAnimator+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIViewPropertyAnimator+Promise.swift"; path = "Extensions/UIKit/Sources/UIViewPropertyAnimator+Promise.swift"; sourceTree = ""; }; + 985C66F4582B57397550A08576C172DC /* Deprecations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Deprecations.swift; path = Sources/Deprecations.swift; sourceTree = ""; }; + 9945A15165461EF000B5FC62AABAE0BE /* BigInt-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "BigInt-prefix.pch"; sourceTree = ""; }; + 99E3E4B1F5A410A44A09223A24E26CB1 /* PromiseKit-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PromiseKit-dummy.m"; sourceTree = ""; }; + 99F9F2E3C006B21E7B8B9FF942A63161 /* Web3+ERC20.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC20.swift"; path = "Sources/web3swift/Tokens/ERC20/Web3+ERC20.swift"; sourceTree = ""; }; + 9A1F8F85F280682DEF327930DF0CB443 /* PromiseKit.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = PromiseKit.modulemap; sourceTree = ""; }; + 9B9CBFF9FF052E246CA99F8F60CC30AB /* Shifts.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Shifts.swift; path = Sources/Shifts.swift; sourceTree = ""; }; + 9BBE5A3FA798D70651487C9758DA7EEA /* Web3+Wallet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Wallet.swift"; path = "Sources/web3swift/HookedFunctions/Web3+Wallet.swift"; sourceTree = ""; }; + 9C137ACAC01A9E33FD886930153E09AD /* Web3+ERC1644.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1644.swift"; path = "Sources/web3swift/Tokens/ERC1644/Web3+ERC1644.swift"; sourceTree = ""; }; + 9CD4E2731EDB8F1B5CA449E40120C65A /* Web3+ERC1410.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1410.swift"; path = "Sources/web3swift/Tokens/ERC1410/Web3+ERC1410.swift"; sourceTree = ""; }; + 9D379163906FA0B9E003D01EBF69D6AD /* Web3+Personal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Personal.swift"; path = "Sources/web3swift/Web3/Web3+Personal.swift"; sourceTree = ""; }; + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 9E4905CB06A5E339473019397A94729D /* secp256k1_ec_mult_static_context.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = secp256k1_ec_mult_static_context.h; path = secp256k1/secp256k1_ec_mult_static_context.h; sourceTree = ""; }; + 9F2489875CD5603FF6D93A818EEEF2DE /* Division.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Division.swift; path = Sources/Division.swift; sourceTree = ""; }; + 9F6AAD426CB2B7147BD42370206C1F5B /* BIP39+WordLists.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "BIP39+WordLists.swift"; path = "Sources/web3swift/KeystoreManager/BIP39+WordLists.swift"; sourceTree = ""; }; + A0576642437AF9B433FCB5859FEDB6E4 /* AnyPromise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyPromise.swift; path = Sources/AnyPromise.swift; sourceTree = ""; }; + A150D976CA7FF85413210E0B9A5359DC /* BIP32Keystore.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BIP32Keystore.swift; path = Sources/web3swift/KeystoreManager/BIP32Keystore.swift; sourceTree = ""; }; + A1D87A56D4C13262ED6350310B53E68E /* Poly1305.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Poly1305.swift; path = Sources/CryptoSwift/Poly1305.swift; sourceTree = ""; }; + A1EC242922DC6212EA368159C20B336B /* Array+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Array+Extension.swift"; path = "Sources/CryptoSwift/Array+Extension.swift"; sourceTree = ""; }; + A22F7BE04044B8DCBBA66B0125EB56B0 /* scalar_8x32.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar_8x32.h; path = secp256k1/scalar_8x32.h; sourceTree = ""; }; + A27149F2AAB4BC84A16DB81D2D0C6E35 /* UIView+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIView+AnyPromise.m"; path = "Extensions/UIKit/Sources/UIView+AnyPromise.m"; sourceTree = ""; }; + A2EB54D097B2AC31F8EF4C4382F3F096 /* Pods-Web3supportTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-Web3supportTests-dummy.m"; sourceTree = ""; }; + A431DC53AFA0AD3132485BA2EC90117A /* Web3+ERC1400.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1400.swift"; path = "Sources/web3swift/Tokens/ERC1400/Web3+ERC1400.swift"; sourceTree = ""; }; + A45A5802DA068F516C2ECF52FAAA8031 /* Pods-Web3supportTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-Web3supportTests-acknowledgements.plist"; sourceTree = ""; }; + A4B92CA7DE6A389005EBF4F582D0ED9D /* Dictionary+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Dictionary+Extension.swift"; path = "Sources/web3swift/Convenience/Dictionary+Extension.swift"; sourceTree = ""; }; + A4CF75EA89B6365105F7EE4170EF3D8E /* Bitwise Ops.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Bitwise Ops.swift"; path = "Sources/Bitwise Ops.swift"; sourceTree = ""; }; + A5072CEBA6FD51C7376B73182287E404 /* Rabbit.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Rabbit.swift; path = Sources/CryptoSwift/Rabbit.swift; sourceTree = ""; }; + A5331A7B06641DC5D025C36D4FB2B521 /* field_5x52_asm_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = field_5x52_asm_impl.h; path = secp256k1/field_5x52_asm_impl.h; sourceTree = ""; }; + A64D2E5C32AA87FD9F30CAA89A3B6EFC /* UIView+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIView+AnyPromise.h"; path = "Extensions/UIKit/Sources/UIView+AnyPromise.h"; sourceTree = ""; }; + A65ACE51991A9942763DF7D7FE18F8BB /* Cryptors.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Cryptors.swift; path = Sources/CryptoSwift/Cryptors.swift; sourceTree = ""; }; + A6C9FA5D62CF92CD83E5688741541FEA /* scalar_8x32_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar_8x32_impl.h; path = secp256k1/scalar_8x32_impl.h; sourceTree = ""; }; + A6D9A40FF4451C0851AD34EE267E14F6 /* BigInt.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = BigInt.modulemap; sourceTree = ""; }; + A82FF443AB4F28BA98ADDAEDC46D3CB5 /* PromiseKit.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PromiseKit.release.xcconfig; sourceTree = ""; }; + A8B046C9471587821A6DD97B726B97ED /* Web3+Methods.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Methods.swift"; path = "Sources/web3swift/Web3/Web3+Methods.swift"; sourceTree = ""; }; + AA287BB163B2375F495E506EB9B1E209 /* Promise+Web3+Eth+GetAccounts.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+GetAccounts.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+GetAccounts.swift"; sourceTree = ""; }; + AB7C6C0E89041DFE6708D30416A3EE3A /* when.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = when.swift; path = Sources/when.swift; sourceTree = ""; }; + ABF0E8EB7A3A288536F2B59EBAD394FC /* Web3.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Web3.swift; path = Sources/web3swift/Web3/Web3.swift; sourceTree = ""; }; + AC4705742D8057A7777CE10502D81AA3 /* StreamEncryptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StreamEncryptor.swift; path = Sources/CryptoSwift/StreamEncryptor.swift; sourceTree = ""; }; + AC61F602DB607EAED91A9F33D38FF56D /* Web3+ERC165.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC165.swift"; path = "Sources/web3swift/Tokens/ERC165/Web3+ERC165.swift"; sourceTree = ""; }; + AC99C21DE4C65C63327C02905C176992 /* KeystoreManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KeystoreManager.swift; path = Sources/web3swift/KeystoreManager/KeystoreManager.swift; sourceTree = ""; }; + AD2DEA99DCB48EFB7F0B0C42FA904B9E /* Web3+TxPool.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+TxPool.swift"; path = "Sources/web3swift/Web3/Web3+TxPool.swift"; sourceTree = ""; }; + AE3A37F080DC241F73D429E7434551FE /* secp256k1_main.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = secp256k1_main.h; path = secp256k1/secp256k1_main.h; sourceTree = ""; }; + AEABFB0679AD607BA8C19624CD03EB3F /* StreamDecryptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StreamDecryptor.swift; path = Sources/CryptoSwift/StreamDecryptor.swift; sourceTree = ""; }; + AF34F6B173634CB05270C33E3B633E52 /* Base58.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Base58.swift; path = Sources/web3swift/Convenience/Base58.swift; sourceTree = ""; }; + AF3FC375FEC3F20B7EC6F6F68A5BAD31 /* Pods-Web3support-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-Web3support-acknowledgements.plist"; sourceTree = ""; }; + AF6DD9C9C1A3ABFA116E929E7183AC5C /* EthereumFilterEncodingExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EthereumFilterEncodingExtensions.swift; path = Sources/web3swift/Contract/EthereumFilterEncodingExtensions.swift; sourceTree = ""; }; + AFFFC1031DB8B0BD09400CA16DCB69B8 /* AbstractKeystore.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AbstractKeystore.swift; path = Sources/web3swift/KeystoreManager/AbstractKeystore.swift; sourceTree = ""; }; + B00EC20DCA6A113D5499EA2DE3147E23 /* CTR.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CTR.swift; path = Sources/CryptoSwift/BlockMode/CTR.swift; sourceTree = ""; }; + B08B4905158DCEB27F9CD432B2DCB08D /* ecdsa_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecdsa_impl.h; path = secp256k1/ecdsa_impl.h; sourceTree = ""; }; + B08FF16C37BC6EF8892E6A0802CBF8C7 /* Promise+Web3+TxPool.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+TxPool.swift"; path = "Sources/web3swift/Promises/Promise+Web3+TxPool.swift"; sourceTree = ""; }; + B39B56D87FA59C512E1636D69039C77A /* String Conversion.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "String Conversion.swift"; path = "Sources/String Conversion.swift"; sourceTree = ""; }; + B3B9120018A02327BF16A71DC822A529 /* hang.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = hang.m; path = Sources/hang.m; sourceTree = ""; }; + B66CE42DFFBBE3305B7E73FFA8225F51 /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Extensions.swift; path = Sources/web3swift/EthereumAddress/Extensions.swift; sourceTree = ""; }; + BA3E0D28F68B3F3F1416216C4A0F6AC1 /* Pods-Web3support-Web3supportUITests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-Web3support-Web3supportUITests-umbrella.h"; sourceTree = ""; }; + BB36D0D3F09F93BB9AA193A077D19ABA /* Exponentiation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Exponentiation.swift; path = Sources/Exponentiation.swift; sourceTree = ""; }; + BB3C1EEE1128E485B103001D09DD5DC7 /* RIPEMD160+StackOveflow.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "RIPEMD160+StackOveflow.swift"; path = "Sources/web3swift/Convenience/RIPEMD160+StackOveflow.swift"; sourceTree = ""; }; + BCC0FB94C80105AA81FC6881C5A9F34A /* Web3+MutatingTransaction.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+MutatingTransaction.swift"; path = "Sources/web3swift/Web3/Web3+MutatingTransaction.swift"; sourceTree = ""; }; + BED199B0BCB4EBFC5A4153E83E36A87A /* ChaCha20.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ChaCha20.swift; path = Sources/CryptoSwift/ChaCha20.swift; sourceTree = ""; }; + C0926ED5FE4B478819019A6247CC89F7 /* field_5x52_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = field_5x52_impl.h; path = secp256k1/field_5x52_impl.h; sourceTree = ""; }; + C09C3CDFA62A239E931C8CBCE69AF714 /* browser.min.js */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.javascript; name = browser.min.js; path = Sources/web3swift/Browser/browser.min.js; sourceTree = ""; }; + C0E050664AF64937BD1D7C8F5ADA8668 /* Web3+ERC1376.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1376.swift"; path = "Sources/web3swift/Tokens/ERC1376/Web3+ERC1376.swift"; sourceTree = ""; }; + C0F7E72D0726BA2223FDF177F5668744 /* Bit.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Bit.swift; path = Sources/CryptoSwift/Bit.swift; sourceTree = ""; }; + C1CC8B9335924C1AB0E99E830D0F01CF /* ECB.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ECB.swift; path = Sources/CryptoSwift/BlockMode/ECB.swift; sourceTree = ""; }; + C1F58230773D8EC578B7F1DD661BE4C3 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + C20A6F6851C11E80E59966D5E2B1D9E5 /* Promise+HttpProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+HttpProvider.swift"; path = "Sources/web3swift/Promises/Promise+HttpProvider.swift"; sourceTree = ""; }; + C2E96278BAD2803E74CFD101EF5EDBC6 /* NSRegularExpressionExtension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NSRegularExpressionExtension.swift; path = Sources/web3swift/Convenience/NSRegularExpressionExtension.swift; sourceTree = ""; }; + C3CBACBB4DD68A9DBBA69FA2B9AA05ED /* CryptoSwift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = CryptoSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + C4BD23E92A083FEE59176D2D9D42FEFF /* basic-config.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "basic-config.h"; path = "secp256k1/basic-config.h"; sourceTree = ""; }; + C4C649F2A3002FB0DDCDFB5E7E0C1042 /* Web3+SecurityToken.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+SecurityToken.swift"; path = "Sources/web3swift/Tokens/ST20/Web3+SecurityToken.swift"; sourceTree = ""; }; + C58E341F20950270149F0D746714B773 /* HKDF.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HKDF.swift; path = Sources/CryptoSwift/HKDF.swift; sourceTree = ""; }; + C5B4C5B85A325DC6BBD1BABDC2BEFE3B /* SSLClientCertificate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SSLClientCertificate.swift; path = Sources/Starscream/SSLClientCertificate.swift; sourceTree = ""; }; + C5D9ACF7F5A9E32D3146843C19AC08B8 /* field.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = field.h; path = secp256k1/field.h; sourceTree = ""; }; + C6740D520A527839549DE4AF221E7FE6 /* AES.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AES.swift; path = Sources/CryptoSwift/AES.swift; sourceTree = ""; }; + C6D029A08E63EF7AA78545C24F65A4F8 /* Multiplication.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Multiplication.swift; path = Sources/Multiplication.swift; sourceTree = ""; }; + C6F12F07E23A192C8564A27C7A1FBD84 /* CipherModeWorker.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CipherModeWorker.swift; path = Sources/CryptoSwift/BlockMode/CipherModeWorker.swift; sourceTree = ""; }; + C7070B7F05AED57BDC930BBE9CFA531E /* NSURLSession+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSURLSession+AnyPromise.m"; path = "Extensions/Foundation/Sources/NSURLSession+AnyPromise.m"; sourceTree = ""; }; + C71739A132569C69D95D4D9C2B3DF8C4 /* Floating Point Conversion.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Floating Point Conversion.swift"; path = "Sources/Floating Point Conversion.swift"; sourceTree = ""; }; + C79A3303BD0F92F861FB31F09E38C4FD /* web3swift.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = web3swift.debug.xcconfig; sourceTree = ""; }; + C878DFC9B0E1798E2D99F69A980D9549 /* UIViewController+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIViewController+AnyPromise.h"; path = "Extensions/UIKit/Sources/UIViewController+AnyPromise.h"; sourceTree = ""; }; + C895F2E1C112B43AC14C85286BEDAB9D /* Web3+ERC820.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC820.swift"; path = "Sources/web3swift/Tokens/ERC820/Web3+ERC820.swift"; sourceTree = ""; }; + C8B1BF09117B1B9461E87777BB773602 /* Pods-Web3support-Web3supportUITests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-Web3support-Web3supportUITests-acknowledgements.markdown"; sourceTree = ""; }; + C8D9FB4C9C15E3BBBC5E8E351D677DBB /* ecmult_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecmult_impl.h; path = secp256k1/ecmult_impl.h; sourceTree = ""; }; + CC3239FDC43AB5FE6CE9BD4B53DAFC5C /* Web3+JSONRPC.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+JSONRPC.swift"; path = "Sources/web3swift/Web3/Web3+JSONRPC.swift"; sourceTree = ""; }; + CC4E8E5726428DCE53C0243395168F7C /* Web3+ERC1155.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1155.swift"; path = "Sources/web3swift/Tokens/ERC1155/Web3+ERC1155.swift"; sourceTree = ""; }; + CE5C989E38CCFD13E2508304A4058F73 /* BlockModeOptions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BlockModeOptions.swift; path = Sources/CryptoSwift/BlockMode/BlockModeOptions.swift; sourceTree = ""; }; + CE851043F97E83BEB4FF3A0CD8440239 /* NSNotificationCenter+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSNotificationCenter+Promise.swift"; path = "Extensions/Foundation/Sources/NSNotificationCenter+Promise.swift"; sourceTree = ""; }; + CF2636E79F042FE113A41FE09A2BD447 /* UInt128.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = UInt128.swift; path = Sources/CryptoSwift/UInt128.swift; sourceTree = ""; }; + CFF55E6004A9D4243CB16AEE55BADC46 /* UInt32+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UInt32+Extension.swift"; path = "Sources/CryptoSwift/UInt32+Extension.swift"; sourceTree = ""; }; + D070DF2AF043438B9AFB9E7FA536729C /* Web3+ERC1633.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1633.swift"; path = "Sources/web3swift/Tokens/ERC1633/Web3+ERC1633.swift"; sourceTree = ""; }; + D0B624D4A073BA9C14F275FB575B98BD /* NSURLSession+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSURLSession+Promise.swift"; path = "Extensions/Foundation/Sources/NSURLSession+Promise.swift"; sourceTree = ""; }; + D0BF9821783BCEF0E827B1849F7058B4 /* SecureBytes.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SecureBytes.swift; path = Sources/CryptoSwift/SecureBytes.swift; sourceTree = ""; }; + D0F929F70A0BA1CEC964A1FB6A0BA532 /* PMKFoundation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PMKFoundation.h; path = Extensions/Foundation/Sources/PMKFoundation.h; sourceTree = ""; }; + D171B692D2F68A693D9818BA8E2AC7BE /* Pods-Web3support-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-Web3support-dummy.m"; sourceTree = ""; }; + D25D6EF8DCC49617FFBC667AF78EB12D /* ecmult_gen.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecmult_gen.h; path = secp256k1/ecmult_gen.h; sourceTree = ""; }; + D33FAACBD900E0D200A24A6433EC43F8 /* Pods-Web3supportTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-Web3supportTests.modulemap"; sourceTree = ""; }; + D42452232E5F0A25F9725E12A54B0D0B /* PCBC.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PCBC.swift; path = Sources/CryptoSwift/BlockMode/PCBC.swift; sourceTree = ""; }; + D463218DEBB89C313D5C6278EAEDDE75 /* CryptoSwift.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = CryptoSwift.modulemap; sourceTree = ""; }; + D472BD0F97D2F7A5FD034A8C7975F843 /* CBC.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CBC.swift; path = Sources/CryptoSwift/BlockMode/CBC.swift; sourceTree = ""; }; + D4AFF92C7C6621B254DE0DA0D312B3A6 /* after.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = after.swift; path = Sources/after.swift; sourceTree = ""; }; + D4C771AA0054D3FAF040100F0DF5054A /* Web3+ERC1643.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1643.swift"; path = "Sources/web3swift/Tokens/ERC1643/Web3+ERC1643.swift"; sourceTree = ""; }; + D66BABFDEA861130F24DA1F117332183 /* Comparable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Comparable.swift; path = Sources/Comparable.swift; sourceTree = ""; }; + D67F43FEA15269E642F8478487A5D443 /* HMAC.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HMAC.swift; path = Sources/CryptoSwift/HMAC.swift; sourceTree = ""; }; + D6E8016C1425F39ED0AFCCB9ED4B92D0 /* Rabbit+Foundation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Rabbit+Foundation.swift"; path = "Sources/CryptoSwift/Foundation/Rabbit+Foundation.swift"; sourceTree = ""; }; + D6FD18A5E5FAABD8378DCFD58EEBADB5 /* CryptoSwift.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = CryptoSwift.release.xcconfig; sourceTree = ""; }; + D7109CA7EDFB5ACD7D4E152EC1950D9A /* Resolver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Resolver.swift; path = Sources/Resolver.swift; sourceTree = ""; }; + D712D8A93FBC323100D51A02D9BC7099 /* ABIDecoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ABIDecoding.swift; path = Sources/web3swift/EthereumABI/ABIDecoding.swift; sourceTree = ""; }; + D824AF312F9E0CB944A043A34AA75492 /* Web3+ERC777.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC777.swift"; path = "Sources/web3swift/Tokens/ERC777/Web3+ERC777.swift"; sourceTree = ""; }; + D98E85C5728326F38DFE21248CC52894 /* PKCS7Padding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PKCS7Padding.swift; path = Sources/CryptoSwift/PKCS/PKCS7Padding.swift; sourceTree = ""; }; + D98ECE7F0FF4B6489BAE75EB0B338CDE /* secp256k1.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = secp256k1.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + D999058D57C5DCB3D443AE2AC82F7AF9 /* secp256k1.c-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "secp256k1.c-umbrella.h"; sourceTree = ""; }; + D9BECB7518C109FD265B3DCCA72289C6 /* PKCS7.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PKCS7.swift; path = Sources/CryptoSwift/PKCS/PKCS7.swift; sourceTree = ""; }; + D9C358BD213A4F803A4F0D954CDB4A66 /* RandomBytesSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RandomBytesSequence.swift; path = Sources/CryptoSwift/RandomBytesSequence.swift; sourceTree = ""; }; + DABED58853DD7154923E1087242C348D /* CryptoSwift-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "CryptoSwift-Info.plist"; sourceTree = ""; }; + DC9996B23BD6274F87E53AC36E77A3C9 /* eckey_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = eckey_impl.h; path = secp256k1/eckey_impl.h; sourceTree = ""; }; + DE6049D61D668B65B8E7267220FA207A /* BlockCipher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BlockCipher.swift; path = Sources/CryptoSwift/BlockCipher.swift; sourceTree = ""; }; + DEE532DC8F5CC55783D4704934139380 /* AES.Cryptors.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AES.Cryptors.swift; path = Sources/CryptoSwift/AES.Cryptors.swift; sourceTree = ""; }; + DF513695C40C8F673B1AB7ACD8F444CF /* Pods_Web3supportTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Web3supportTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + E17C973147AF3C5B7FFBCE67D54D10F8 /* race.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = race.m; path = Sources/race.m; sourceTree = ""; }; + E2A11ABF6C19483F9CA47C5D675EFB7C /* ZeroPadding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ZeroPadding.swift; path = Sources/CryptoSwift/ZeroPadding.swift; sourceTree = ""; }; + E2D25E8396C1FAE8881A5DF91CC9C297 /* Pods-Web3support.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Web3support.debug.xcconfig"; sourceTree = ""; }; + E2D44CDE5D3C3AE1F4AE35A6E105AA98 /* browser.js */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.javascript; name = browser.js; path = Sources/web3swift/Browser/browser.js; sourceTree = ""; }; + E3E90DACA7F29B6C0940B7B81CF0B958 /* Pods-Web3support-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-Web3support-umbrella.h"; sourceTree = ""; }; + E4130FCEFEA6178454D763881346DA12 /* BIP32KeystoreJSONStructure.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BIP32KeystoreJSONStructure.swift; path = Sources/web3swift/KeystoreManager/BIP32KeystoreJSONStructure.swift; sourceTree = ""; }; + E474099C5B69E2295BEA6E9BCF9AC2D4 /* NSTask+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSTask+AnyPromise.h"; path = "Extensions/Foundation/Sources/NSTask+AnyPromise.h"; sourceTree = ""; }; + E4A3912DE02D411442B0E1BD5F45206A /* eckey.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = eckey.h; path = secp256k1/eckey.h; sourceTree = ""; }; + E5EC4C09ED0003376A99775B71A67655 /* Pods-Web3support-Web3supportUITests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-Web3support-Web3supportUITests-frameworks.sh"; sourceTree = ""; }; + E75F349F4B491DD33B917B5CAB379B18 /* Promise+Web3+Eth+GetBlockByHash.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+GetBlockByHash.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByHash.swift"; sourceTree = ""; }; + E83F2B1C5DFBB2973EB632FFAF431D24 /* GCD.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GCD.swift; path = Sources/GCD.swift; sourceTree = ""; }; + E93502FD6A791D20161D852AE5F3B836 /* String+FoundationExtension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "String+FoundationExtension.swift"; path = "Sources/CryptoSwift/Foundation/String+FoundationExtension.swift"; sourceTree = ""; }; + E99A3F687C46D78106341FED1A402BB4 /* HMAC+Foundation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "HMAC+Foundation.swift"; path = "Sources/CryptoSwift/Foundation/HMAC+Foundation.swift"; sourceTree = ""; }; + EB937DBC76B12E434BD67D13C22BC9DA /* PBKDF2.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PBKDF2.swift; path = Sources/CryptoSwift/PKCS/PBKDF2.swift; sourceTree = ""; }; + ECA67CC7067DB6978A931779EC2F03DB /* Codable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Codable.swift; path = Sources/Codable.swift; sourceTree = ""; }; + ED4E4B062DAEA914113EBFEA174FFFD8 /* SECP256k1.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SECP256k1.swift; path = Sources/web3swift/Convenience/SECP256k1.swift; sourceTree = ""; }; + EEA7A27035F0203B4EBE4DBB88198DDC /* Web3+ERC721.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC721.swift"; path = "Sources/web3swift/Tokens/ERC721/Web3+ERC721.swift"; sourceTree = ""; }; + EF9288F7F0BC87F402C584F1315303A7 /* ecdh_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecdh_impl.h; path = secp256k1/ecdh_impl.h; sourceTree = ""; }; + EF9FB057769EBF7CC35DF096044A3DDF /* Thenable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Thenable.swift; path = Sources/Thenable.swift; sourceTree = ""; }; + EFE3F8A99AC6C9B022235FC5AFAA5587 /* PromiseKit.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PromiseKit.debug.xcconfig; sourceTree = ""; }; + F01E85AC9CACC4F20F6B60C540849932 /* Blowfish+Foundation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Blowfish+Foundation.swift"; path = "Sources/CryptoSwift/Foundation/Blowfish+Foundation.swift"; sourceTree = ""; }; + F13167EA572351121100E3BA81B6D8E1 /* EthereumAddress.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EthereumAddress.swift; path = Sources/web3swift/EthereumAddress/EthereumAddress.swift; sourceTree = ""; }; + F1932888AB8E0C660FB6A6329B5EA93D /* scratch.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scratch.h; path = secp256k1/scratch.h; sourceTree = ""; }; + F1CCA7F271D80CEABEBEC082B807C886 /* ENS.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ENS.swift; path = Sources/web3swift/Utils/ENS/ENS.swift; sourceTree = ""; }; + F25689A430D65A68AE60A2F48BC45363 /* hash_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = hash_impl.h; path = secp256k1/hash_impl.h; sourceTree = ""; }; + F2777B674E6E41ECCFEF16A07EE3021F /* Starscream-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Starscream-dummy.m"; sourceTree = ""; }; + F59E103F85C63360F8FE84A3325A58BE /* Starscream.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Starscream.debug.xcconfig; sourceTree = ""; }; + F6A055C6C2236AC231E70C766F1F2A9E /* GCM.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GCM.swift; path = Sources/CryptoSwift/BlockMode/GCM.swift; sourceTree = ""; }; + F777E45908B4CA01B6397251588326AA /* CryptoSwift.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = CryptoSwift.debug.xcconfig; sourceTree = ""; }; + F786129127F13FD69EF1677CA3998D83 /* scalar_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar_impl.h; path = secp256k1/scalar_impl.h; sourceTree = ""; }; + F80C3E7711C491383D13370C30FAF506 /* ETHRegistrarController.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ETHRegistrarController.swift; path = Sources/web3swift/Utils/ENS/ETHRegistrarController.swift; sourceTree = ""; }; + F81274EDB681F11E7CB05F7DCA2BB33C /* CryptoSwift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = CryptoSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + F8BDA8BCDF0A7105D483CC6CA145E0E0 /* BigUInt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BigUInt.swift; path = Sources/BigUInt.swift; sourceTree = ""; }; + F8C2AEC6480C986E57E0B95B0BBFB9F6 /* Pods_Web3support_Web3supportUITests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Web3support_Web3supportUITests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + F9762329D78E5F848C2CA1616AF68985 /* NSNotificationCenter+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSNotificationCenter+AnyPromise.m"; path = "Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.m"; sourceTree = ""; }; + F977ED89C342B067EE048C2E57FA3E29 /* ENSRegistry.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ENSRegistry.swift; path = Sources/web3swift/Utils/ENS/ENSRegistry.swift; sourceTree = ""; }; + FB16EB86A68E527A7A28E138B85069B5 /* Web3+Eth.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Eth.swift"; path = "Sources/web3swift/Web3/Web3+Eth.swift"; sourceTree = ""; }; + FB2C7436F64A01CB65DAC52E4D4051A9 /* CMAC.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CMAC.swift; path = Sources/CryptoSwift/CMAC.swift; sourceTree = ""; }; + FB5389FE6F5CCCD967823377DDEDDAA6 /* BigInt.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = BigInt.debug.xcconfig; sourceTree = ""; }; + FCAA06B735107FE87210D20FB8CB012B /* fwd.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = fwd.h; path = Sources/fwd.h; sourceTree = ""; }; + FD7BBC49506B8E05F19DBAC1F1FE4977 /* Bridge.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Bridge.swift; path = Sources/web3swift/Browser/Bridge.swift; sourceTree = ""; }; + FDAF6B3919EFC6904000083D78B40777 /* Pods-Web3supportTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Web3supportTests.debug.xcconfig"; sourceTree = ""; }; + FDE6BF7E45AF488C7D6816FC89DB4D6F /* afterlife.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = afterlife.swift; path = Extensions/Foundation/Sources/afterlife.swift; sourceTree = ""; }; + FE0467E7D290AD76D8FBF8D93EB6201F /* web3swift.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = web3swift.release.xcconfig; sourceTree = ""; }; + FF6F05ADA7D3265602971B30AD6B3C63 /* PromiseKit.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PromiseKit.h; path = Sources/PromiseKit.h; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 09206235EB9393FD6D895453F2569AF9 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + C48EC56BB7C14ABC19E3BA2ACD91F6A9 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 11311D70953AC99174A763E25F665920 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 8532AFAE5B4DE21DCAFB19AB0E4434EB /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2E81020DA9DF0A8A40F50E1A6FB18054 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 46F9214900CE1F500D4E081AC05BDD61 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 45B48F57B1039D463A2CB04349F22C5A /* Foundation.framework in Frameworks */, + 00542E749518733F88FD9339F521159E /* UIKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4F01C2FAEBEA4A06F5D5E7176B718352 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 669DA0C80132D93F424571CD265F2A7F /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 546857E471326426A714225F21E2B190 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 53ECF855AA367DDE87AA9B0FC85B38F0 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 61271E1192A4EDA80FB1D8AC89FCC54C /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 61BBBE50B016C901A3162FAC9E1CA878 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6CAB820DC68B34B985B867AB2A98627C /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + CE2B3CB0ECF5AEA5F5B6905772D9A48F /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C251B7C6F58014E20CD9D51BF0043104 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + B87B17EAF9350E5A984E8A30DCBACF7B /* BigInt.framework in Frameworks */, + 48E5E91253E9388B606E69C995AC8115 /* CoreImage.framework in Frameworks */, + 5F8EAE458B798A96B627EDC4FD1D071A /* CryptoSwift.framework in Frameworks */, + ACA8271368449221D95A89A9367AF042 /* Foundation.framework in Frameworks */, + 0EBF2449E0DE2D9E352BA273F88E8269 /* PromiseKit.framework in Frameworks */, + B8610DF9CE98C994CD53723045FF09FD /* secp256k1.framework in Frameworks */, + 20ED667341DDAE3103E222B85D943C06 /* Starscream.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E0B8A7B2CF1F2164CC1A302E7AFABD5B /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 14D34E32263C8D334AC63CA775357BA8 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 0BC1A3706E32157FB0A14E46DB20ADBA /* PromiseKit */ = { + isa = PBXGroup; + children = ( + C0B24A729DB4FDA08DFFDAC4AAA0CD6F /* CorePromise */, + C32CFF729D162B456D13A265AD1C6154 /* Foundation */, + 51E27B667CB03B2059D146D21012FFDD /* Support Files */, + EF4BC145EA7E0EC9AAB4A0C969BCAFC9 /* UIKit */, + ); + path = PromiseKit; + sourceTree = ""; + }; + 0F94F8774C745AB972409B1D92A5CC97 /* Pods-Web3support */ = { + isa = PBXGroup; + children = ( + 2451EA550A1CAB5C8BB12B5CEDD686C2 /* Pods-Web3support.modulemap */, + 475C972BE4005D9924C3092BBB7F699C /* Pods-Web3support-acknowledgements.markdown */, + AF3FC375FEC3F20B7EC6F6F68A5BAD31 /* Pods-Web3support-acknowledgements.plist */, + D171B692D2F68A693D9818BA8E2AC7BE /* Pods-Web3support-dummy.m */, + 393B420FFE5ABFF234074A6F50BA84EE /* Pods-Web3support-frameworks.sh */, + 651202A8AF433994EE5EB83E9CB8D24A /* Pods-Web3support-Info.plist */, + E3E90DACA7F29B6C0940B7B81CF0B958 /* Pods-Web3support-umbrella.h */, + E2D25E8396C1FAE8881A5DF91CC9C297 /* Pods-Web3support.debug.xcconfig */, + 2F7D2C17D3B22156BFB54CEFC3FC8C84 /* Pods-Web3support.release.xcconfig */, + ); + name = "Pods-Web3support"; + path = "Target Support Files/Pods-Web3support"; + sourceTree = ""; + }; + 29E9D6BAE2620A57B9941D9AA9E4F049 /* Support Files */ = { + isa = PBXGroup; + children = ( + 650ACFA17614B44CE86F21F89BCED8F7 /* secp256k1.c.modulemap */, + 05F1742DB6BF2606852E4AAA34612D4F /* secp256k1.c-dummy.m */, + 7C61C143CBF81F3DC8D70800ABDB2FDB /* secp256k1.c-Info.plist */, + 37D6266F529B95CA085B5703D44D3C61 /* secp256k1.c-prefix.pch */, + D999058D57C5DCB3D443AE2AC82F7AF9 /* secp256k1.c-umbrella.h */, + 6875770FBEBE2AF71365EB6DC30E3027 /* secp256k1.c.debug.xcconfig */, + 3EBF7696596A1EE1DDA7A1F1962DD10D /* secp256k1.c.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/secp256k1.c"; + sourceTree = ""; + }; + 3450D24615AA57598989D21867AE604A /* CryptoSwift */ = { + isa = PBXGroup; + children = ( + 394050D026F0D950AC11CB1CB8965A25 /* AEAD.swift */, + 5BD8315263E70B60082686DB2FFF5188 /* AEADChaCha20Poly1305.swift */, + C6740D520A527839549DE4AF221E7FE6 /* AES.swift */, + 6696E07735F6561C9C4A983FE82A92E7 /* AES+Foundation.swift */, + DEE532DC8F5CC55783D4704934139380 /* AES.Cryptors.swift */, + A1EC242922DC6212EA368159C20B336B /* Array+Extension.swift */, + 10554501E08F69E67C555DA71246F0DD /* Array+Foundation.swift */, + 6710D1A5A55B50814F9994C62AEF5E9D /* Authenticator.swift */, + 558429F8ABA5EF6470234B32E39EE6DB /* BatchedCollection.swift */, + C0F7E72D0726BA2223FDF177F5668744 /* Bit.swift */, + DE6049D61D668B65B8E7267220FA207A /* BlockCipher.swift */, + 2BD035B8A8DC2700DC4D8C32EDB44FE0 /* BlockDecryptor.swift */, + 2F7D0C84A7512E1A50E355458C653748 /* BlockEncryptor.swift */, + 7FE8062FF8F7EE71B525E058FCD7F293 /* BlockMode.swift */, + CE5C989E38CCFD13E2508304A4058F73 /* BlockModeOptions.swift */, + 6D93B2F6F631256A8EF3546A2D3015E9 /* Blowfish.swift */, + F01E85AC9CACC4F20F6B60C540849932 /* Blowfish+Foundation.swift */, + D472BD0F97D2F7A5FD034A8C7975F843 /* CBC.swift */, + 1340186B5B000DD0223DB7799FCEC3E7 /* CBCMAC.swift */, + 8B59B8ED26308215F98BAEB6995ADE07 /* CCM.swift */, + 537B9FE8F0466BB2293902B1450ED4AE /* CFB.swift */, + BED199B0BCB4EBFC5A4153E83E36A87A /* ChaCha20.swift */, + 2F7C8B40A0A88989C96E1D7E70C08358 /* ChaCha20+Foundation.swift */, + 8F4E403D89A362925BE6A61E7E6F853A /* Checksum.swift */, + 02760A62D64944C5DE7DAFDFDEA019F1 /* Cipher.swift */, + C6F12F07E23A192C8564A27C7A1FBD84 /* CipherModeWorker.swift */, + FB2C7436F64A01CB65DAC52E4D4051A9 /* CMAC.swift */, + 3E6F02468AD363BFC7279A294B4087E6 /* Collection+Extension.swift */, + 6D3B3202C3C1C2CC880557FB97F4905E /* CompactMap.swift */, + 674945A263B5A171B0D8CAC79DAA6216 /* Cryptor.swift */, + A65ACE51991A9942763DF7D7FE18F8BB /* Cryptors.swift */, + B00EC20DCA6A113D5499EA2DE3147E23 /* CTR.swift */, + 3FF1FE9FD2130495BEE330898A681C39 /* Data+Extension.swift */, + 028968F0E8149D086725FEB0C3962475 /* Digest.swift */, + 327BEAF521485F0E297F4294ED918852 /* DigestType.swift */, + C1CC8B9335924C1AB0E99E830D0F01CF /* ECB.swift */, + F6A055C6C2236AC231E70C766F1F2A9E /* GCM.swift */, + 4F8B5FCF5522ECCD06CE444D5061F541 /* Generics.swift */, + C58E341F20950270149F0D746714B773 /* HKDF.swift */, + D67F43FEA15269E642F8478487A5D443 /* HMAC.swift */, + E99A3F687C46D78106341FED1A402BB4 /* HMAC+Foundation.swift */, + 3099C8E0DFDA6B882C0E55B94FBB3E85 /* Int+Extension.swift */, + 18FC982ED53EDF2CD0C51B0E3E600099 /* MD5.swift */, + 8590CEF2172C5BB2B9EFFE7B18A88B42 /* NoPadding.swift */, + 7F89D5E973A70A3593E25EBE22FACAD1 /* OFB.swift */, + 1B20BDCDA0ECDF19F240EFFE03A8A53E /* Operators.swift */, + 424FF13781C45B35C9ACA160B6118661 /* Padding.swift */, + 869339C036B9B7D93560C6864892AAFE /* PBKDF1.swift */, + EB937DBC76B12E434BD67D13C22BC9DA /* PBKDF2.swift */, + D42452232E5F0A25F9725E12A54B0D0B /* PCBC.swift */, + 028215446A8A53879AB93D22579AA449 /* PKCS5.swift */, + D9BECB7518C109FD265B3DCCA72289C6 /* PKCS7.swift */, + D98E85C5728326F38DFE21248CC52894 /* PKCS7Padding.swift */, + A1D87A56D4C13262ED6350310B53E68E /* Poly1305.swift */, + A5072CEBA6FD51C7376B73182287E404 /* Rabbit.swift */, + D6E8016C1425F39ED0AFCCB9ED4B92D0 /* Rabbit+Foundation.swift */, + D9C358BD213A4F803A4F0D954CDB4A66 /* RandomBytesSequence.swift */, + 25FD464B4ADFC965F65DEB27E8F457B6 /* Scrypt.swift */, + D0BF9821783BCEF0E827B1849F7058B4 /* SecureBytes.swift */, + 57CDD67FB7CB521BFE99C29464D58CCC /* SHA1.swift */, + 2EAE3334F923A49D94EA8B8A709A09FD /* SHA2.swift */, + 4DD919542E41CB8E150F5DFC1A540CE6 /* SHA3.swift */, + AEABFB0679AD607BA8C19624CD03EB3F /* StreamDecryptor.swift */, + AC4705742D8057A7777CE10502D81AA3 /* StreamEncryptor.swift */, + 7A38ECCB5ECDCB46FC3DD46AE1FC4FC1 /* String+Extension.swift */, + E93502FD6A791D20161D852AE5F3B836 /* String+FoundationExtension.swift */, + CF2636E79F042FE113A41FE09A2BD447 /* UInt128.swift */, + 0ABAA7E59B6E1E62813742DBFE88342A /* UInt16+Extension.swift */, + CFF55E6004A9D4243CB16AEE55BADC46 /* UInt32+Extension.swift */, + 63BE7C86DDBB5ECBFFA35C3F78742ADF /* UInt64+Extension.swift */, + 868A0BB9D02C7B72944922A127342822 /* UInt8+Extension.swift */, + 3072E80789DEC0486492C1400591C726 /* Updatable.swift */, + 75235A710D5C7405350FE8C421CF7EE2 /* Utils.swift */, + 7BADEECA71797B1FBC1DCAECD0854C8C /* Utils+Foundation.swift */, + E2A11ABF6C19483F9CA47C5D675EFB7C /* ZeroPadding.swift */, + D9291593ADD1DB893A5E10881A8F6C16 /* Support Files */, + ); + path = CryptoSwift; + sourceTree = ""; + }; + 3CFD8F9B1351ACAD945A054BDA5212AC /* Products */ = { + isa = PBXGroup; + children = ( + 91BB24BA472AF523E913108C9AA301F2 /* BigInt.framework */, + 12DC6A0FDF284A2C935F5EA9F6111B0B /* Browser.bundle */, + F81274EDB681F11E7CB05F7DCA2BB33C /* CryptoSwift.framework */, + 86CD85F105AE8490C4D11A857DCCA542 /* Pods_Web3support.framework */, + F8C2AEC6480C986E57E0B95B0BBFB9F6 /* Pods_Web3support_Web3supportUITests.framework */, + DF513695C40C8F673B1AB7ACD8F444CF /* Pods_Web3supportTests.framework */, + 002B1E88BA14EBF633CD66EBFBA107E9 /* PromiseKit.framework */, + 332A47430CFF99501D563788C7AAF1D2 /* secp256k1.framework */, + 891B2270823847ED23F2ECFC28F935EC /* Starscream.framework */, + 8A2449DF78D58AD33A7C7504BB3F38A0 /* web3swift.framework */, + ); + name = Products; + sourceTree = ""; + }; + 45391B0AECA5B4338D5DF285C7E89619 /* Support Files */ = { + isa = PBXGroup; + children = ( + 2CC1AE9780ED61CC18DBBB15157156FE /* ResourceBundle-Browser-web3swift-Info.plist */, + 3272C752A91B1AF557A81D034B598BBB /* web3swift.modulemap */, + 380AE05F318DC350995E5E66ACC19F19 /* web3swift-dummy.m */, + 52EC6BE68BAEE295055F52FF1C3B58B2 /* web3swift-Info.plist */, + 02523820D1CEF318C8623ED384F11439 /* web3swift-prefix.pch */, + 6F6E3A560F30E6C76BE396A97D419B02 /* web3swift-umbrella.h */, + C79A3303BD0F92F861FB31F09E38C4FD /* web3swift.debug.xcconfig */, + FE0467E7D290AD76D8FBF8D93EB6201F /* web3swift.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/web3swift"; + sourceTree = ""; + }; + 51E27B667CB03B2059D146D21012FFDD /* Support Files */ = { + isa = PBXGroup; + children = ( + 9A1F8F85F280682DEF327930DF0CB443 /* PromiseKit.modulemap */, + 99E3E4B1F5A410A44A09223A24E26CB1 /* PromiseKit-dummy.m */, + 838EF9154AB93D92DB9762BDF5BED700 /* PromiseKit-Info.plist */, + 1A743A4FD9581DB6D29F599446B85E5B /* PromiseKit-prefix.pch */, + 07BA1325EFD33D5292CE17473E5F956F /* PromiseKit-umbrella.h */, + EFE3F8A99AC6C9B022235FC5AFAA5587 /* PromiseKit.debug.xcconfig */, + A82FF443AB4F28BA98ADDAEDC46D3CB5 /* PromiseKit.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/PromiseKit"; + sourceTree = ""; + }; + 566F16A3B87F308115422EE121CF95EA /* BigInt */ = { + isa = PBXGroup; + children = ( + 7F1D0B138A229542223B16185A746888 /* Addition.swift */, + 5D9411FFEE688C3F4C176C536884F130 /* BigInt.swift */, + F8BDA8BCDF0A7105D483CC6CA145E0E0 /* BigUInt.swift */, + A4CF75EA89B6365105F7EE4170EF3D8E /* Bitwise Ops.swift */, + ECA67CC7067DB6978A931779EC2F03DB /* Codable.swift */, + D66BABFDEA861130F24DA1F117332183 /* Comparable.swift */, + 554B02C9539B4DE5F116BC0148B0341F /* Data Conversion.swift */, + 9F2489875CD5603FF6D93A818EEEF2DE /* Division.swift */, + BB36D0D3F09F93BB9AA193A077D19ABA /* Exponentiation.swift */, + C71739A132569C69D95D4D9C2B3DF8C4 /* Floating Point Conversion.swift */, + E83F2B1C5DFBB2973EB632FFAF431D24 /* GCD.swift */, + 02BCB8FA01E7F4F5CD44B0D0A4B77AD5 /* Hashable.swift */, + 46D93832BC588A5E75BCD0C7779D0156 /* Integer Conversion.swift */, + C6D029A08E63EF7AA78545C24F65A4F8 /* Multiplication.swift */, + 3CEB28C9E34F3D4AFF3BA00FAABC5CD0 /* Prime Test.swift */, + 699763CCB6877CF34141DDE755F441EB /* Random.swift */, + 9B9CBFF9FF052E246CA99F8F60CC30AB /* Shifts.swift */, + 4A013B1BDD344AC6EAC71EC4DEA1CDA5 /* Square Root.swift */, + 5E0378DB2D3422FFD6E14F74781F0694 /* Strideable.swift */, + B39B56D87FA59C512E1636D69039C77A /* String Conversion.swift */, + 3D3F3745A7D0E990E715D852768455F2 /* Subtraction.swift */, + 3910EE551F198BF1791FF438496F9747 /* Words and Bits.swift */, + C71B44021DB1794405A251F310519BF7 /* Support Files */, + ); + path = BigInt; + sourceTree = ""; + }; + 5E04E5082D34B148B5515FE4F174D0CE /* web3swift */ = { + isa = PBXGroup; + children = ( + 5A4FCAA67F0525DDA4FF3F94B5BBE816 /* ABI.swift */, + D712D8A93FBC323100D51A02D9BC7099 /* ABIDecoding.swift */, + 1C0721CA0C6A5B018F4B496B54F7D274 /* ABIElements.swift */, + 447FB67D09E4D83CDF62C0379ACCC6B5 /* ABIEncoding.swift */, + 635FCDE74A464A0EB4FF9B4D20DD8A80 /* ABIParameterTypes.swift */, + 7961F8F15F5930CDBCDB68FB8ECF4AF6 /* ABIParsing.swift */, + 3DD503D6DB58FBC5EB37EE4ED728382E /* ABITypeParser.swift */, + AFFFC1031DB8B0BD09400CA16DCB69B8 /* AbstractKeystore.swift */, + 702D95C0DC97359B918067BEA40F18DA /* Array+Extension.swift */, + AF34F6B173634CB05270C33E3B633E52 /* Base58.swift */, + 0657455EEF72FAA880A0147D76B8F491 /* BigUInt+Extensions.swift */, + 4AE1FB59AAB7CFCF16F4D7AECE524894 /* BIP32HDNode.swift */, + A150D976CA7FF85413210E0B9A5359DC /* BIP32Keystore.swift */, + E4130FCEFEA6178454D763881346DA12 /* BIP32KeystoreJSONStructure.swift */, + 12C5C4C81A590ED070F02E971254DEC4 /* BIP39.swift */, + 9F6AAD426CB2B7147BD42370206C1F5B /* BIP39+WordLists.swift */, + 696516B833D002C3DE6DF92361767CA1 /* BloomFilter.swift */, + FD7BBC49506B8E05F19DBAC1F1FE4977 /* Bridge.swift */, + 23921C08E5242DAB552A4287DD4B4EA9 /* BrowserViewController.swift */, + 43CB51FED61E2F731154A09AB346B249 /* ComparisonExtensions.swift */, + 6828680E3AFA8645DA486E98E6DDA086 /* ContractProtocol.swift */, + 1D6BEB657B8F0CC4FEB1C0944BF892E8 /* CryptoExtensions.swift */, + 3BE074A266F0E94B24114B1546E61AC8 /* Data+Extension.swift */, + 8213F1D4FED15BCAC1769CCD95E698F3 /* Decodable+Extensions.swift */, + A4B92CA7DE6A389005EBF4F582D0ED9D /* Dictionary+Extension.swift */, + 1A9184E2FF7C75C2E8A76EB0565B47F6 /* EIP67Code.swift */, + 431DFDCD5EBFCE95F388BD650BC3F510 /* EIP681.swift */, + 7C39C45E6514D78B763CEFF99E933770 /* Encodable+Extensions.swift */, + F1CCA7F271D80CEABEBEC082B807C886 /* ENS.swift */, + 0B32A29FD17AA33220D92C8413F32C56 /* ENSBaseRegistrar.swift */, + F977ED89C342B067EE048C2E57FA3E29 /* ENSRegistry.swift */, + 3B444B88A9193519CB2B5BBD389EF0E6 /* ENSResolver.swift */, + 18839F6AF587B42905500F08F445E61B /* ENSReverseRegistrar.swift */, + F13167EA572351121100E3BA81B6D8E1 /* EthereumAddress.swift */, + 73938AA4C7CACF9566B3616D650B0283 /* EthereumContract.swift */, + AF6DD9C9C1A3ABFA116E929E7183AC5C /* EthereumFilterEncodingExtensions.swift */, + 96B8AFD6283C92280EFE9890E6E6FCCC /* EthereumKeystoreV3.swift */, + 4BFDF5AAA317492732B1D0EECF6E68CB /* EthereumTransaction.swift */, + F80C3E7711C491383D13370C30FAF506 /* ETHRegistrarController.swift */, + 57536CB2627D968FD6667AA3AA245EB1 /* EventFiltering.swift */, + B66CE42DFFBBE3305B7E73FFA8225F51 /* Extensions.swift */, + 66F16B5D8DEE8BDE87CC2408D8FE5FE3 /* IBAN.swift */, + AC99C21DE4C65C63327C02905C176992 /* KeystoreManager.swift */, + 1ACC2FBAD75E9B64031CB9CD3CFA6292 /* KeystoreV3JSONStructure.swift */, + 17DC771E4A6654F257A7694843F38538 /* NameHash.swift */, + 0B12EE372DB1AFDFABD10118DA3C781C /* NativeTypesEncoding+Extensions.swift */, + 1CE430E8FC9DFE318D59DC2FA083E105 /* NonceMiddleware.swift */, + C2E96278BAD2803E74CFD101EF5EDBC6 /* NSRegularExpressionExtension.swift */, + 7E306D7806FF9EE954924600AA4E1289 /* PlainKeystore.swift */, + 1422C33CAB7EAA29DB47C9CBDA6F4E46 /* Promise+Batching.swift */, + C20A6F6851C11E80E59966D5E2B1D9E5 /* Promise+HttpProvider.swift */, + 01E073C1CD37262FF94E5051A8D55BC3 /* Promise+Web3+Contract+GetIndexedEvents.swift */, + 2D82E51D53BAD38089B1DB95451764EF /* Promise+Web3+Eth+Call.swift */, + 89047AD6A8F9DED9AD3FAFA4C7E7DC94 /* Promise+Web3+Eth+EstimateGas.swift */, + AA287BB163B2375F495E506EB9B1E209 /* Promise+Web3+Eth+GetAccounts.swift */, + 95FEF9A336D74B30EEC3F0905F44CC91 /* Promise+Web3+Eth+GetBalance.swift */, + E75F349F4B491DD33B917B5CAB379B18 /* Promise+Web3+Eth+GetBlockByHash.swift */, + 7AEBAA42453A3627D0C260F40E3ABA32 /* Promise+Web3+Eth+GetBlockByNumber.swift */, + 3386535C108CE2E4983FF6FBAB1C7E01 /* Promise+Web3+Eth+GetBlockNumber.swift */, + 1C0168721A40963DC1F398E1A4B087F6 /* Promise+Web3+Eth+GetGasPrice.swift */, + 2E41C42E5233827CA9E9E88D318D954B /* Promise+Web3+Eth+GetTransactionCount.swift */, + 73FA6458DA183DF514E42FE54DC27E66 /* Promise+Web3+Eth+GetTransactionDetails.swift */, + 67EE3284A1AA023A5653ABC2E4831469 /* Promise+Web3+Eth+GetTransactionReceipt.swift */, + 964D41D5C54F916868B511A8E50EF359 /* Promise+Web3+Eth+SendRawTransaction.swift */, + 6F1CC28425C72AC8913BE51E129F555C /* Promise+Web3+Eth+SendTransaction.swift */, + 7B4BF3C05BC39315DAE89F43DA29C75A /* Promise+Web3+Personal+CreateAccount.swift */, + 4FBCC7677F3EE13A0DC4495B13E7A571 /* Promise+Web3+Personal+Sign.swift */, + 8571C3C4E2540AE79C82CC088FF5C809 /* Promise+Web3+Personal+UnlockAccount.swift */, + B08FF16C37BC6EF8892E6A0802CBF8C7 /* Promise+Web3+TxPool.swift */, + 0D8A369599F638C6EF1C70946E7DD2F9 /* PublicKey.swift */, + BB3C1EEE1128E485B103001D09DD5DC7 /* RIPEMD160+StackOveflow.swift */, + 7DDF8B3C487BB15A7C9D7E0F66D04AEB /* RLP.swift */, + ED4E4B062DAEA914113EBFEA174FFFD8 /* SECP256k1.swift */, + 6A06F8FE8838CD882B9939831BCCE338 /* String+Extension.swift */, + 135B192A1A9030D073173CE768BD191B /* TransactionSigner.swift */, + ABF0E8EB7A3A288536F2B59EBAD394FC /* Web3.swift */, + 8193AD1F3D63A0C11E45AC8A5A73C47C /* Web3+BrowserFunctions.swift */, + 09CF9FD0B42B944753444D05129D819C /* Web3+Constants.swift */, + 02FBA29B920FE25DB8EE454A4F1E2874 /* Web3+Contract.swift */, + CC4E8E5726428DCE53C0243395168F7C /* Web3+ERC1155.swift */, + C0E050664AF64937BD1D7C8F5ADA8668 /* Web3+ERC1376.swift */, + A431DC53AFA0AD3132485BA2EC90117A /* Web3+ERC1400.swift */, + 9CD4E2731EDB8F1B5CA449E40120C65A /* Web3+ERC1410.swift */, + 59C0A0783CBBE1C7C8F3D2F34AAAEB96 /* Web3+ERC1594.swift */, + D070DF2AF043438B9AFB9E7FA536729C /* Web3+ERC1633.swift */, + D4C771AA0054D3FAF040100F0DF5054A /* Web3+ERC1643.swift */, + 9C137ACAC01A9E33FD886930153E09AD /* Web3+ERC1644.swift */, + AC61F602DB607EAED91A9F33D38FF56D /* Web3+ERC165.swift */, + 99F9F2E3C006B21E7B8B9FF942A63161 /* Web3+ERC20.swift */, + EEA7A27035F0203B4EBE4DBB88198DDC /* Web3+ERC721.swift */, + 2DFB28013DE80EDBBA6612BE5291E3BF /* Web3+ERC721x.swift */, + D824AF312F9E0CB944A043A34AA75492 /* Web3+ERC777.swift */, + C895F2E1C112B43AC14C85286BEDAB9D /* Web3+ERC820.swift */, + 33F839ECDA9D6E925A8BCA131A664905 /* Web3+ERC888.swift */, + FB16EB86A68E527A7A28E138B85069B5 /* Web3+Eth.swift */, + 532A38B4F523E15890612D5578B901BF /* Web3+Eth+Websocket.swift */, + 348BCAB7AD52B6413E93EA928F7BEE6A /* Web3+Eventloop.swift */, + 61448EC862DAE1EBC85136ED829B571F /* Web3+EventParser.swift */, + 8910795635358AF5D3F10D643064EF90 /* Web3+HttpProvider.swift */, + 74C2AE8219D8A019AF481B6F3383E570 /* Web3+InfuraProviders.swift */, + 351509184374C023BC9E7318D6D240EC /* Web3+Instance.swift */, + CC3239FDC43AB5FE6CE9BD4B53DAFC5C /* Web3+JSONRPC.swift */, + A8B046C9471587821A6DD97B726B97ED /* Web3+Methods.swift */, + BCC0FB94C80105AA81FC6881C5A9F34A /* Web3+MutatingTransaction.swift */, + 591F1A7AB716B5FA79DB9D222834A48A /* Web3+Options.swift */, + 9D379163906FA0B9E003D01EBF69D6AD /* Web3+Personal.swift */, + 88E610821C9204BB68397CC03BFC2D63 /* Web3+Protocols.swift */, + 3017C17B6A19772F40C2A00CC7053EC7 /* Web3+ReadingTransaction.swift */, + C4C649F2A3002FB0DDCDFB5E7E0C1042 /* Web3+SecurityToken.swift */, + 154EA858B5D1E0BA4AF9640574096510 /* Web3+ST20.swift */, + 146DA39AC7A46437F8C9CB432A0C4699 /* Web3+Structures.swift */, + AD2DEA99DCB48EFB7F0B0C42FA904B9E /* Web3+TxPool.swift */, + 6D196B49035EE2558CA931156B3CC775 /* Web3+Utils.swift */, + 9BBE5A3FA798D70651487C9758DA7EEA /* Web3+Wallet.swift */, + 2C498EC6CEB8421E6EFA36FD8BF629BC /* Web3+WebsocketProvider.swift */, + 9D0391C17E9266267B07E8CEB993FFFC /* Resources */, + 45391B0AECA5B4338D5DF285C7E89619 /* Support Files */, + ); + path = web3swift; + sourceTree = ""; + }; + 6109CBB56AD287A0C8422C89391F16E4 /* Starscream */ = { + isa = PBXGroup; + children = ( + 02973070D278C6BA9BAF3D1822786EE6 /* Compression.swift */, + C5B4C5B85A325DC6BBD1BABDC2BEFE3B /* SSLClientCertificate.swift */, + 081B081BAB76C290DB80364F972A3D98 /* SSLSecurity.swift */, + 16F91688CB98C09F37FB0532B3341B22 /* WebSocket.swift */, + CDE0688E1AA39AFE3BEFFF8D83152A99 /* Support Files */, + ); + path = Starscream; + sourceTree = ""; + }; + 640D2AF0374198FF3A3730B0C0E3BE18 /* iOS */ = { + isa = PBXGroup; + children = ( + 6A88AC5A168517938F01A76CAAE7EBEA /* CoreImage.framework */, + C1F58230773D8EC578B7F1DD661BE4C3 /* Foundation.framework */, + 03D9157C8C0779B825A21D4DA8C71DAB /* UIKit.framework */, + ); + name = iOS; + sourceTree = ""; + }; + 7ADE5A2F566688A257F097EA84E2CD80 /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + 0F94F8774C745AB972409B1D92A5CC97 /* Pods-Web3support */, + BA7CB0A195B73FFC4F57434B703042AD /* Pods-Web3support-Web3supportUITests */, + E0CC5159466523CA3F024331FAA2A2FC /* Pods-Web3supportTests */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + 7D7324476B3AAA1B935E8539A6899271 /* Pods */ = { + isa = PBXGroup; + children = ( + 566F16A3B87F308115422EE121CF95EA /* BigInt */, + 3450D24615AA57598989D21867AE604A /* CryptoSwift */, + 0BC1A3706E32157FB0A14E46DB20ADBA /* PromiseKit */, + 92CFEEF58DEBB1C26A2CD8B459D6F27E /* secp256k1.c */, + 6109CBB56AD287A0C8422C89391F16E4 /* Starscream */, + 5E04E5082D34B148B5515FE4F174D0CE /* web3swift */, + ); + name = Pods; + sourceTree = ""; + }; + 92CFEEF58DEBB1C26A2CD8B459D6F27E /* secp256k1.c */ = { + isa = PBXGroup; + children = ( + C4BD23E92A083FEE59176D2D9D42FEFF /* basic-config.h */, + EF9288F7F0BC87F402C584F1315303A7 /* ecdh_impl.h */, + 7CC5B4139CDFFD75E516BC0C7EB1BA82 /* ecdsa.h */, + B08B4905158DCEB27F9CD432B2DCB08D /* ecdsa_impl.h */, + E4A3912DE02D411442B0E1BD5F45206A /* eckey.h */, + DC9996B23BD6274F87E53AC36E77A3C9 /* eckey_impl.h */, + 03BE9F98CCE9C1262A3343020887933E /* ecmult.h */, + 892E151D44D4707DBC204D6F59A99099 /* ecmult_const.h */, + 31D4B4B7AA6178320AD9429501FB9D42 /* ecmult_const_impl.h */, + D25D6EF8DCC49617FFBC667AF78EB12D /* ecmult_gen.h */, + 01ED7D9D89508CA7EAA7F1F043495007 /* ecmult_gen_impl.h */, + C8D9FB4C9C15E3BBBC5E8E351D677DBB /* ecmult_impl.h */, + C5D9ACF7F5A9E32D3146843C19AC08B8 /* field.h */, + 4EAF871AD72ED8B98E4F956A00841E95 /* field_10x26.h */, + 05DDCFDA70BFDD11AABC10650442DAAB /* field_10x26_impl.h */, + 7D04CD7E1EF55A225C04E7F16EB3E724 /* field_5x52.h */, + A5331A7B06641DC5D025C36D4FB2B521 /* field_5x52_asm_impl.h */, + C0926ED5FE4B478819019A6247CC89F7 /* field_5x52_impl.h */, + 2E123B4A564E405B1FEE02F48D534532 /* field_5x52_int128_impl.h */, + 2FF9F9D0F195D9CCFBC308CE982B37AA /* field_impl.h */, + 94E9A2CBF0228347F1FD0B55E11990A6 /* group.h */, + 572C8E0F590539A171571F4C06D8CB9A /* group_impl.h */, + 5856772748611034A2DC9F7D6F13F3AD /* hash.h */, + F25689A430D65A68AE60A2F48BC45363 /* hash_impl.h */, + 331DA5AED7BF5F4646A90D6F77C91A22 /* num.h */, + 72B760A6B3B21E921E0997E5A1ED3346 /* num_gmp.h */, + 6E105DF01C418F3B1C230920F963BE01 /* num_gmp_impl.h */, + 8C6445049DF4ABD6CE3F2C38F4C8A6C3 /* num_impl.h */, + 3056036973AE29A6057B82086C2B0D84 /* recovery_impl.h */, + 63713ECBD4C31420BA66F8AB83825B48 /* scalar.h */, + 9135FA8D9B973BC1A3763F25AA44FF64 /* scalar_4x64.h */, + 126DC0D7440B4233998413303CE4F65F /* scalar_4x64_impl.h */, + A22F7BE04044B8DCBBA66B0125EB56B0 /* scalar_8x32.h */, + A6C9FA5D62CF92CD83E5688741541FEA /* scalar_8x32_impl.h */, + F786129127F13FD69EF1677CA3998D83 /* scalar_impl.h */, + 3C9C4EF51D56F3A2F8C1351ECFBECA51 /* scalar_low.h */, + 21C0A4CE9CD0DC1F4665EB462C637348 /* scalar_low_impl.h */, + F1932888AB8E0C660FB6A6329B5EA93D /* scratch.h */, + 5F4FA3CB88027295C344636E166F0EB8 /* scratch_impl.h */, + 334450DD7B6EA290D629965834A78C15 /* secp256k1.c */, + 8557A2308502510B11D958EF167ED7DB /* secp256k1.h */, + 3D81CBF6EA6135E28DA96DDC5089008E /* secp256k1-config.h */, + 9E4905CB06A5E339473019397A94729D /* secp256k1_ec_mult_static_context.h */, + AE3A37F080DC241F73D429E7434551FE /* secp256k1_main.h */, + 96BA76B86413F1BD6D2642279E7BB1AD /* util.h */, + 29E9D6BAE2620A57B9941D9AA9E4F049 /* Support Files */, + ); + path = secp256k1.c; + sourceTree = ""; + }; + 9D0391C17E9266267B07E8CEB993FFFC /* Resources */ = { + isa = PBXGroup; + children = ( + E2D44CDE5D3C3AE1F4AE35A6E105AA98 /* browser.js */, + C09C3CDFA62A239E931C8CBCE69AF714 /* browser.min.js */, + 5DA9CD391B4D5E614CAE1DB405B5D95E /* wk.bridge.min.js */, + ); + name = Resources; + sourceTree = ""; + }; + BA7CB0A195B73FFC4F57434B703042AD /* Pods-Web3support-Web3supportUITests */ = { + isa = PBXGroup; + children = ( + 920C71B5D95409F2CAD974B09E5ED5D0 /* Pods-Web3support-Web3supportUITests.modulemap */, + C8B1BF09117B1B9461E87777BB773602 /* Pods-Web3support-Web3supportUITests-acknowledgements.markdown */, + 782C474493177E8883905027041AA3AE /* Pods-Web3support-Web3supportUITests-acknowledgements.plist */, + 73AE9CE7C402316A90015D8FE30A9C17 /* Pods-Web3support-Web3supportUITests-dummy.m */, + E5EC4C09ED0003376A99775B71A67655 /* Pods-Web3support-Web3supportUITests-frameworks.sh */, + 84C22EA32BF12EF808714F9517EE7550 /* Pods-Web3support-Web3supportUITests-Info.plist */, + BA3E0D28F68B3F3F1416216C4A0F6AC1 /* Pods-Web3support-Web3supportUITests-umbrella.h */, + 72CA11293C1FEAD46D53B50D3F53830A /* Pods-Web3support-Web3supportUITests.debug.xcconfig */, + 1E64004ED18613E15E5FA474A4F25ECD /* Pods-Web3support-Web3supportUITests.release.xcconfig */, + ); + name = "Pods-Web3support-Web3supportUITests"; + path = "Target Support Files/Pods-Web3support-Web3supportUITests"; + sourceTree = ""; + }; + BD79595A3DA54A4C0B2725FEF2479943 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 857E7AB10DF6BDB0B3A11DF7F010FFAC /* BigInt.framework */, + C3CBACBB4DD68A9DBBA69FA2B9AA05ED /* CryptoSwift.framework */, + 0985EDDA3BE3F9FD09F7D6B612A46446 /* PromiseKit.framework */, + D98ECE7F0FF4B6489BAE75EB0B338CDE /* secp256k1.framework */, + 280705F0E0D0EBC84DFBBA1068758D6D /* Starscream.framework */, + 640D2AF0374198FF3A3730B0C0E3BE18 /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + C0B24A729DB4FDA08DFFDAC4AAA0CD6F /* CorePromise */ = { + isa = PBXGroup; + children = ( + 7B045C7857F3FB23BE6496792365B9C5 /* after.m */, + D4AFF92C7C6621B254DE0DA0D312B3A6 /* after.swift */, + 384E922D8BC4146E932C077F9A2C0651 /* AnyPromise.h */, + 5342D36974BCDE8EC75703FD3DBF9F3B /* AnyPromise.m */, + A0576642437AF9B433FCB5859FEDB6E4 /* AnyPromise.swift */, + 244C067EFEB7A2C4E5ECDDDCF3FB0D79 /* Box.swift */, + 1F0FEF67DA3E548C1E04B0EBFF9FEBDE /* Catchable.swift */, + 3D239122D0D5E4554A0AE9781080164F /* Configuration.swift */, + 283FFF6A596C1D84BB8FF9BA94A7ADDB /* CustomStringConvertible.swift */, + 985C66F4582B57397550A08576C172DC /* Deprecations.swift */, + 22BF1378E05475FF065F31B3478EB217 /* dispatch_promise.m */, + 8008892ABCADAD4E5DC4AA60DC647E31 /* Error.swift */, + 258D67386BCD76CE2E07CC3E6C012ADA /* firstly.swift */, + FCAA06B735107FE87210D20FB8CB012B /* fwd.h */, + 821FD64A61CCB7CBE3A1388FA84834F8 /* Guarantee.swift */, + B3B9120018A02327BF16A71DC822A529 /* hang.m */, + 5F8CCDE203D8192D751FF69BB9DA8A8D /* hang.swift */, + 534AD27A9601B753D3C895597DDB078C /* join.m */, + 6628230DE91FEFDC792C7DBD31BE5251 /* LogEvent.swift */, + 79548549FC0A5BE4E92657ADCE6AFB03 /* Promise.swift */, + FF6F05ADA7D3265602971B30AD6B3C63 /* PromiseKit.h */, + E17C973147AF3C5B7FFBCE67D54D10F8 /* race.m */, + 567E8F1F8BB7A75EC66096359A535F84 /* race.swift */, + D7109CA7EDFB5ACD7D4E152EC1950D9A /* Resolver.swift */, + EF9FB057769EBF7CC35DF096044A3DDF /* Thenable.swift */, + 5FE4310FF86028C19F34F611D349E859 /* when.m */, + AB7C6C0E89041DFE6708D30416A3EE3A /* when.swift */, + ); + name = CorePromise; + sourceTree = ""; + }; + C32CFF729D162B456D13A265AD1C6154 /* Foundation */ = { + isa = PBXGroup; + children = ( + FDE6BF7E45AF488C7D6816FC89DB4D6F /* afterlife.swift */, + 20C42F3DEF3E9D936622D491DC54EA99 /* NSNotificationCenter+AnyPromise.h */, + F9762329D78E5F848C2CA1616AF68985 /* NSNotificationCenter+AnyPromise.m */, + CE851043F97E83BEB4FF3A0CD8440239 /* NSNotificationCenter+Promise.swift */, + 774CC24C803B0C79461A6923DC01B31A /* NSObject+Promise.swift */, + E474099C5B69E2295BEA6E9BCF9AC2D4 /* NSTask+AnyPromise.h */, + 30C36A57832FDED028EEED561EE4FD0C /* NSTask+AnyPromise.m */, + 93E080B9C39B87B655FF7DC0EE07F04E /* NSURLSession+AnyPromise.h */, + C7070B7F05AED57BDC930BBE9CFA531E /* NSURLSession+AnyPromise.m */, + D0B624D4A073BA9C14F275FB575B98BD /* NSURLSession+Promise.swift */, + D0F929F70A0BA1CEC964A1FB6A0BA532 /* PMKFoundation.h */, + 432EA59B99FE0582E2F6240B54A26680 /* Process+Promise.swift */, + ); + name = Foundation; + sourceTree = ""; + }; + C71B44021DB1794405A251F310519BF7 /* Support Files */ = { + isa = PBXGroup; + children = ( + A6D9A40FF4451C0851AD34EE267E14F6 /* BigInt.modulemap */, + 8006ACF6A2FC630EC476D9F1F21CC90F /* BigInt-dummy.m */, + 92E1E02B823CD4C95D631F27E2D62E35 /* BigInt-Info.plist */, + 9945A15165461EF000B5FC62AABAE0BE /* BigInt-prefix.pch */, + 6E285CA56194AF49BFD1EFB5C97D4334 /* BigInt-umbrella.h */, + FB5389FE6F5CCCD967823377DDEDDAA6 /* BigInt.debug.xcconfig */, + 394218B5A5E8E974A3936D3FF6EBB7D9 /* BigInt.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/BigInt"; + sourceTree = ""; + }; + CDE0688E1AA39AFE3BEFFF8D83152A99 /* Support Files */ = { + isa = PBXGroup; + children = ( + 2066491A6B91B84DBCE53F56D07835B9 /* Starscream.modulemap */, + F2777B674E6E41ECCFEF16A07EE3021F /* Starscream-dummy.m */, + 4E71AAA8231758E672E3ACF6D694EA8D /* Starscream-Info.plist */, + 90692F209BCE17E51BF1F4EDE5BC6EFB /* Starscream-prefix.pch */, + 84586FE14E05B1A73DAE9DD316A9D7F2 /* Starscream-umbrella.h */, + F59E103F85C63360F8FE84A3325A58BE /* Starscream.debug.xcconfig */, + 6C537535F3EDDBA8ED7569976986A05A /* Starscream.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/Starscream"; + sourceTree = ""; + }; + CF1408CF629C7361332E53B88F7BD30C = { + isa = PBXGroup; + children = ( + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */, + BD79595A3DA54A4C0B2725FEF2479943 /* Frameworks */, + 7D7324476B3AAA1B935E8539A6899271 /* Pods */, + 3CFD8F9B1351ACAD945A054BDA5212AC /* Products */, + 7ADE5A2F566688A257F097EA84E2CD80 /* Targets Support Files */, + ); + sourceTree = ""; + }; + D9291593ADD1DB893A5E10881A8F6C16 /* Support Files */ = { + isa = PBXGroup; + children = ( + D463218DEBB89C313D5C6278EAEDDE75 /* CryptoSwift.modulemap */, + 58406D2F94BB714CDB81DAACFAE2A10D /* CryptoSwift-dummy.m */, + DABED58853DD7154923E1087242C348D /* CryptoSwift-Info.plist */, + 11552264B3AA84951AD6B2F9F0EDF6F9 /* CryptoSwift-prefix.pch */, + 14198AD5163D601BC6E9E4CEA8F0CE28 /* CryptoSwift-umbrella.h */, + F777E45908B4CA01B6397251588326AA /* CryptoSwift.debug.xcconfig */, + D6FD18A5E5FAABD8378DCFD58EEBADB5 /* CryptoSwift.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/CryptoSwift"; + sourceTree = ""; + }; + E0CC5159466523CA3F024331FAA2A2FC /* Pods-Web3supportTests */ = { + isa = PBXGroup; + children = ( + D33FAACBD900E0D200A24A6433EC43F8 /* Pods-Web3supportTests.modulemap */, + 8157D1CD9BA421F2A9DFD9E6C19D177A /* Pods-Web3supportTests-acknowledgements.markdown */, + A45A5802DA068F516C2ECF52FAAA8031 /* Pods-Web3supportTests-acknowledgements.plist */, + A2EB54D097B2AC31F8EF4C4382F3F096 /* Pods-Web3supportTests-dummy.m */, + 170F39C35458E355F4268434C73CF69F /* Pods-Web3supportTests-Info.plist */, + 2D3636CE912662624BE63AE6F2BF5DAB /* Pods-Web3supportTests-umbrella.h */, + FDAF6B3919EFC6904000083D78B40777 /* Pods-Web3supportTests.debug.xcconfig */, + 18192636EB88C2E682F782E9A7FB734B /* Pods-Web3supportTests.release.xcconfig */, + ); + name = "Pods-Web3supportTests"; + path = "Target Support Files/Pods-Web3supportTests"; + sourceTree = ""; + }; + EF4BC145EA7E0EC9AAB4A0C969BCAFC9 /* UIKit */ = { + isa = PBXGroup; + children = ( + 570E189613076E0A18DAF4AC1072CA69 /* PMKUIKit.h */, + A64D2E5C32AA87FD9F30CAA89A3B6EFC /* UIView+AnyPromise.h */, + A27149F2AAB4BC84A16DB81D2D0C6E35 /* UIView+AnyPromise.m */, + 204DC1705C56D7DB30888861287AAED5 /* UIView+Promise.swift */, + C878DFC9B0E1798E2D99F69A980D9549 /* UIViewController+AnyPromise.h */, + 6DAFC7859E7882E5E0AB3A29C3082C9E /* UIViewController+AnyPromise.m */, + 9851214ACA0341CA2837DCCE2C90ED9B /* UIViewPropertyAnimator+Promise.swift */, + ); + name = UIKit; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 161A02771B21A722138EE16CEDF4ECF9 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 7EECE9FCF5E07473E6D0FE80BFCB94C9 /* BigInt-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 268B63E8C4C49B5B9008A22687331D37 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 5C9DAD3002768BEFDB26B49836D597C1 /* web3swift-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2ADA2FC2BCE2F76BE02B50BA2ED24FB5 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 2F5E7AF94E160DD850E4D49A75D65FD7 /* Pods-Web3support-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 56E8CD8A8767D87735DF8378E067D7D4 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + E0CFF076A747B65E1AFECE3BD7DF563B /* basic-config.h in Headers */, + 4DAA45AA4705DC070777F47B26CD5E47 /* ecdh_impl.h in Headers */, + 5E90775673D3B4B6D79C433F2252ADA1 /* ecdsa.h in Headers */, + 0FFCCD6DA97D990AE1BA260117BFFE0B /* ecdsa_impl.h in Headers */, + 12D6EEDC774272D55AB3321616260521 /* eckey.h in Headers */, + 69BD0ECE9A9C86675C6D00B0A8AEE6C4 /* eckey_impl.h in Headers */, + E2F80E676FB1398C55C0D8987DBD9187 /* ecmult.h in Headers */, + C6E721B3190ECB4166B66A7111C06AD7 /* ecmult_const.h in Headers */, + 458676EF35FF1E0E55B56BA564753395 /* ecmult_const_impl.h in Headers */, + 200C511BF343ABAAAE2A2455F87835CA /* ecmult_gen.h in Headers */, + B5F88ED28F9F02C7773DB0EF4CEC020D /* ecmult_gen_impl.h in Headers */, + 455EC7C458C31692757B2733867EB7D7 /* ecmult_impl.h in Headers */, + FD2338C29B58E91E4414C7DFF0653DF2 /* field.h in Headers */, + 13C335A0C70755098F8236AAEDE436B1 /* field_10x26.h in Headers */, + 6E052250546198FFA6ACA98591382FB9 /* field_10x26_impl.h in Headers */, + 294EFBCAFC1E9D673CFC767E4311EE93 /* field_5x52.h in Headers */, + 15DE85B34140EA30C3D8B4D837175214 /* field_5x52_asm_impl.h in Headers */, + 55FBA344318427AEC1F50404D3BAD645 /* field_5x52_impl.h in Headers */, + A3BA9877A1CA08CBCC6671FAF10E4254 /* field_5x52_int128_impl.h in Headers */, + 2714060BB8E303CE54D62742676563F3 /* field_impl.h in Headers */, + DA520170A95D755F0B8F66894620DAAD /* group.h in Headers */, + 7FC80BD52E47A1A3E58BDB3B2730B2BB /* group_impl.h in Headers */, + 780B79BF175E2CF800F18B65CFEFB892 /* hash.h in Headers */, + 48FEF9536E7763BD21D98545A62B8072 /* hash_impl.h in Headers */, + A924D29AB5C6DED4D11695F816435182 /* num.h in Headers */, + FA1AFEE1AD9655343C5A77A8A1305EE2 /* num_gmp.h in Headers */, + 00B42BCCCA2E5CB2F9833D5B0185FAE4 /* num_gmp_impl.h in Headers */, + 20FB0F849E1A209C4DB6DBF2DB715116 /* num_impl.h in Headers */, + BB8076FBF18C0A9C3FFEEB5B5B24520F /* recovery_impl.h in Headers */, + D14DFF7622138D4EE68899129147EBC3 /* scalar.h in Headers */, + 3673081E4DE5FC570D7F208643205C9B /* scalar_4x64.h in Headers */, + 37D92C03D9F8CC1339F7F60AAAAD584F /* scalar_4x64_impl.h in Headers */, + E5445DFB40D0A11F4EE679B7B965CA32 /* scalar_8x32.h in Headers */, + 9094207BFCA7F633807C6790662CE1A9 /* scalar_8x32_impl.h in Headers */, + 4366CE3A1EB891338E516632DE63190C /* scalar_impl.h in Headers */, + 574AB0DF291869EF77612DDCA1453AD5 /* scalar_low.h in Headers */, + 6F68C4EF34BAFD94802BDE5D5763CA29 /* scalar_low_impl.h in Headers */, + 4DE378D2B9BC193D231C0ED04C61B1E9 /* scratch.h in Headers */, + EB5C9F0BC0A19563C8644FD12BC52ED2 /* scratch_impl.h in Headers */, + B154FB35E7B72F153A3AA603E62E3E6B /* secp256k1-config.h in Headers */, + 07DF8B768EA5C2C8F09B3F9E565252D8 /* secp256k1.c-umbrella.h in Headers */, + 80910E754A1689207928F1161096798D /* secp256k1.h in Headers */, + 097672AA9B32748FEDC26BA74BE6B61B /* secp256k1_ec_mult_static_context.h in Headers */, + FE7D561BE020956E1511CED7CC7BFC61 /* secp256k1_main.h in Headers */, + 8A292837D81C3B20F95EB52B3C4048FD /* util.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 709DAB71C5595424D21973A3833F1C93 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 639C6438CD01AE7A36FE1E551F2E7A8F /* CryptoSwift-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7CF1637A149D2A50F1846A83FFDEEC6F /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 79F73BA854A7EC559E464EC446493D52 /* AnyPromise.h in Headers */, + D4C52546E7DEE38CEE04F2B6D61BB9E2 /* fwd.h in Headers */, + DBEF0F49E57B3321CC7067EEF33AB582 /* NSNotificationCenter+AnyPromise.h in Headers */, + 3AAE347ADDFEFAC7DDECBC744D1BD6AC /* NSTask+AnyPromise.h in Headers */, + EAC994EA457048CA6AA49B82C9F05DF4 /* NSURLSession+AnyPromise.h in Headers */, + 5D2D358E754D92564B259BBACFBA8271 /* PMKFoundation.h in Headers */, + 60F874ED0F6234A4417CAFDE554D088D /* PMKUIKit.h in Headers */, + 968B5CC9B9B0A7E92FACEEBEA3C0DA13 /* PromiseKit-umbrella.h in Headers */, + 33B79E4BFF8D25E1A705E2C469BBCA9B /* PromiseKit.h in Headers */, + 59AA176600E91A56BC244B381305060B /* UIView+AnyPromise.h in Headers */, + E425FBEC27FF20E38E5F71856145D72C /* UIViewController+AnyPromise.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A4B4B17A30A2A848BBE0F514477E48EA /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + F001B953A48906D9B7BA0A7986EAEEF7 /* Pods-Web3supportTests-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + ABD37AF9B9F78580D159AE761C456202 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + B4A6283FDFA04E3A7B6FD0C13B6FEF32 /* Starscream-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + ACC9547D8ACEAF402FDB2F1257A0077D /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 034BF4DD5B3A3634EF84A71E8D2B4FFD /* Pods-Web3support-Web3supportUITests-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 06348169D4C39D2E31C7DE0798958918 /* Pods-Web3support-Web3supportUITests */ = { + isa = PBXNativeTarget; + buildConfigurationList = EC4F22A05E3106C2754AD329144A6DE8 /* Build configuration list for PBXNativeTarget "Pods-Web3support-Web3supportUITests" */; + buildPhases = ( + ACC9547D8ACEAF402FDB2F1257A0077D /* Headers */, + EF0BB8557CEBFFC7253D25CED45CFDF1 /* Sources */, + 546857E471326426A714225F21E2B190 /* Frameworks */, + F0FC049CD1FA3C2050140CA1235C3587 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + A8228F3E569A6668515F99173E441EC6 /* PBXTargetDependency */, + 57D2805434C91AC9D27F392D88717076 /* PBXTargetDependency */, + 53169DDC2887E3577BA4E02554C2642F /* PBXTargetDependency */, + 96FFD10FCEC9C56213E501D96B706B24 /* PBXTargetDependency */, + 5DE504F58C77C11303D1142E35694D48 /* PBXTargetDependency */, + 4711010F4D9CC1B8672E51F063FF0C20 /* PBXTargetDependency */, + ); + name = "Pods-Web3support-Web3supportUITests"; + productName = "Pods-Web3support-Web3supportUITests"; + productReference = F8C2AEC6480C986E57E0B95B0BBFB9F6 /* Pods_Web3support_Web3supportUITests.framework */; + productType = "com.apple.product-type.framework"; + }; + 09DD83B7D075842A3A5105AD410BD38A /* BigInt */ = { + isa = PBXNativeTarget; + buildConfigurationList = 5104F4CC467A363177DF298548DA476E /* Build configuration list for PBXNativeTarget "BigInt" */; + buildPhases = ( + 161A02771B21A722138EE16CEDF4ECF9 /* Headers */, + AD425074D950826A1AA1323039964E21 /* Sources */, + 11311D70953AC99174A763E25F665920 /* Frameworks */, + 5C193E54B44DAEF03EE281A99BB02E30 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = BigInt; + productName = BigInt; + productReference = 91BB24BA472AF523E913108C9AA301F2 /* BigInt.framework */; + productType = "com.apple.product-type.framework"; + }; + 161C26511FC920CB146236AB7295D5E0 /* secp256k1.c */ = { + isa = PBXNativeTarget; + buildConfigurationList = 0C905C3678D56B7D838AD8CAB2A28BE8 /* Build configuration list for PBXNativeTarget "secp256k1.c" */; + buildPhases = ( + 56E8CD8A8767D87735DF8378E067D7D4 /* Headers */, + E273F872A91B40D94C04090B6D582310 /* Sources */, + 61271E1192A4EDA80FB1D8AC89FCC54C /* Frameworks */, + E60197C7F363BC8ECACC603DD038E424 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = secp256k1.c; + productName = secp256k1.c; + productReference = 332A47430CFF99501D563788C7AAF1D2 /* secp256k1.framework */; + productType = "com.apple.product-type.framework"; + }; + 2148C0E605D6ED6D0216F7EE1CD04E35 /* Pods-Web3supportTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = D45F87D89ACC91CAABB0F34761B327F9 /* Build configuration list for PBXNativeTarget "Pods-Web3supportTests" */; + buildPhases = ( + A4B4B17A30A2A848BBE0F514477E48EA /* Headers */, + 2773C3D7F17540DCD11DBFB4CD95F894 /* Sources */, + 6CAB820DC68B34B985B867AB2A98627C /* Frameworks */, + BD5169227CA15C23FDEF2D5F645842FD /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + F7C324C36EEA52C09B98528E046A8D41 /* PBXTargetDependency */, + ); + name = "Pods-Web3supportTests"; + productName = "Pods-Web3supportTests"; + productReference = DF513695C40C8F673B1AB7ACD8F444CF /* Pods_Web3supportTests.framework */; + productType = "com.apple.product-type.framework"; + }; + 7C579CE66A1E7A9AA33CA5F97F9C22C5 /* PromiseKit */ = { + isa = PBXNativeTarget; + buildConfigurationList = 058DF38F5922F24842B97693B0188F2D /* Build configuration list for PBXNativeTarget "PromiseKit" */; + buildPhases = ( + 7CF1637A149D2A50F1846A83FFDEEC6F /* Headers */, + 5E5F9E7DC1D3B74E7C15141C2B3E9BD5 /* Sources */, + 46F9214900CE1F500D4E081AC05BDD61 /* Frameworks */, + 409EA903AAA7848EE17474A886579F4C /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = PromiseKit; + productName = PromiseKit; + productReference = 002B1E88BA14EBF633CD66EBFBA107E9 /* PromiseKit.framework */; + productType = "com.apple.product-type.framework"; + }; + 8CDD759A6130CA265C6D157F4407C39B /* web3swift-Browser */ = { + isa = PBXNativeTarget; + buildConfigurationList = 4BDF6CF3744DB028DE330AE92336EAF8 /* Build configuration list for PBXNativeTarget "web3swift-Browser" */; + buildPhases = ( + 6ABAAB41EEC545F9AA87617468292FF2 /* Sources */, + 2E81020DA9DF0A8A40F50E1A6FB18054 /* Frameworks */, + 41E97B47A863474EACED8EB15B269DF7 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "web3swift-Browser"; + productName = "web3swift-Browser"; + productReference = 12DC6A0FDF284A2C935F5EA9F6111B0B /* Browser.bundle */; + productType = "com.apple.product-type.bundle"; + }; + 99313990C1D76A6D1D017868B6975CC8 /* CryptoSwift */ = { + isa = PBXNativeTarget; + buildConfigurationList = CF129DCD30773EF2C3A3E9B2EFFB4A7E /* Build configuration list for PBXNativeTarget "CryptoSwift" */; + buildPhases = ( + 709DAB71C5595424D21973A3833F1C93 /* Headers */, + 883036C28D3D55337CAD22CCFC568F1A /* Sources */, + E0B8A7B2CF1F2164CC1A302E7AFABD5B /* Frameworks */, + 7ACD25997C01FD960F9B4331D0A5D21F /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = CryptoSwift; + productName = CryptoSwift; + productReference = F81274EDB681F11E7CB05F7DCA2BB33C /* CryptoSwift.framework */; + productType = "com.apple.product-type.framework"; + }; + 99364D9FB07EF3FA5DFE1237001805EC /* web3swift */ = { + isa = PBXNativeTarget; + buildConfigurationList = A281CF9B4D89AD9A8062C7D37C919915 /* Build configuration list for PBXNativeTarget "web3swift" */; + buildPhases = ( + 268B63E8C4C49B5B9008A22687331D37 /* Headers */, + 50EC1377492C5102F2F8C553CABE4A49 /* Sources */, + C251B7C6F58014E20CD9D51BF0043104 /* Frameworks */, + 95AE97E98C4676AAD8D2D401201B89FC /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 735E2118F7B8C93B96AE29DDAB2E1FB2 /* PBXTargetDependency */, + C35321477411982E3F6C2F42E00771C3 /* PBXTargetDependency */, + 042A3F3301E93C1CC5EFDB139A9740C4 /* PBXTargetDependency */, + 99596231AB2C18AA302EEF4787A20A08 /* PBXTargetDependency */, + 4C3C2E8D3D728E8267429F61675F8359 /* PBXTargetDependency */, + AF46632C647B5F41C755FC860445EFF1 /* PBXTargetDependency */, + ); + name = web3swift; + productName = web3swift; + productReference = 8A2449DF78D58AD33A7C7504BB3F38A0 /* web3swift.framework */; + productType = "com.apple.product-type.framework"; + }; + 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */ = { + isa = PBXNativeTarget; + buildConfigurationList = ED5C15C705AB67930733A7E237A0A33A /* Build configuration list for PBXNativeTarget "Starscream" */; + buildPhases = ( + ABD37AF9B9F78580D159AE761C456202 /* Headers */, + 621EE447A1C117BDCD418F5DE070FD3C /* Sources */, + 09206235EB9393FD6D895453F2569AF9 /* Frameworks */, + BE174469BA3F43D1B5CE60520CA93EB3 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Starscream; + productName = Starscream; + productReference = 891B2270823847ED23F2ECFC28F935EC /* Starscream.framework */; + productType = "com.apple.product-type.framework"; + }; + BF16A4D4E4C02517868813AFD92FC23D /* Pods-Web3support */ = { + isa = PBXNativeTarget; + buildConfigurationList = 4CB3A9ABAFAABE2A143C23B0FECFD4CF /* Build configuration list for PBXNativeTarget "Pods-Web3support" */; + buildPhases = ( + 2ADA2FC2BCE2F76BE02B50BA2ED24FB5 /* Headers */, + A4AD34E54920BDEC0B564E5EF22910E2 /* Sources */, + 4F01C2FAEBEA4A06F5D5E7176B718352 /* Frameworks */, + 936B5DA164F6EA6FBFF85A388EA9D662 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 8B7E9A16E9B01B06ED404913A69B355E /* PBXTargetDependency */, + AF72EA0E12AB059080306245BBA45FA8 /* PBXTargetDependency */, + F89104DD315458BFBBBD38619CDCFFFB /* PBXTargetDependency */, + FB61F3BB55E87B91CD441503F8C2AC6C /* PBXTargetDependency */, + DE9A214F07E0828F590294A03B20DBB3 /* PBXTargetDependency */, + E2019C760F7AAB6F5AD72A5214B9E8E4 /* PBXTargetDependency */, + ); + name = "Pods-Web3support"; + productName = "Pods-Web3support"; + productReference = 86CD85F105AE8490C4D11A857DCCA542 /* Pods_Web3support.framework */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + BFDFE7DC352907FC980B868725387E98 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1240; + LastUpgradeCheck = 1250; + }; + buildConfigurationList = 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = CF1408CF629C7361332E53B88F7BD30C; + productRefGroup = 3CFD8F9B1351ACAD945A054BDA5212AC /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 09DD83B7D075842A3A5105AD410BD38A /* BigInt */, + 99313990C1D76A6D1D017868B6975CC8 /* CryptoSwift */, + BF16A4D4E4C02517868813AFD92FC23D /* Pods-Web3support */, + 06348169D4C39D2E31C7DE0798958918 /* Pods-Web3support-Web3supportUITests */, + 2148C0E605D6ED6D0216F7EE1CD04E35 /* Pods-Web3supportTests */, + 7C579CE66A1E7A9AA33CA5F97F9C22C5 /* PromiseKit */, + 161C26511FC920CB146236AB7295D5E0 /* secp256k1.c */, + 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */, + 99364D9FB07EF3FA5DFE1237001805EC /* web3swift */, + 8CDD759A6130CA265C6D157F4407C39B /* web3swift-Browser */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 409EA903AAA7848EE17474A886579F4C /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 41E97B47A863474EACED8EB15B269DF7 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 04F24DFD581372A0BD9D827D77F385EE /* browser.js in Resources */, + B9BC4E41D4B1A39754CFD8B648C37063 /* browser.min.js in Resources */, + A83D65CEE1CB904CA9E923FDBB4CF3BE /* wk.bridge.min.js in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5C193E54B44DAEF03EE281A99BB02E30 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7ACD25997C01FD960F9B4331D0A5D21F /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 936B5DA164F6EA6FBFF85A388EA9D662 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 95AE97E98C4676AAD8D2D401201B89FC /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 2DD52D5DFF05949A359999859D75471F /* Browser.bundle in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + BD5169227CA15C23FDEF2D5F645842FD /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + BE174469BA3F43D1B5CE60520CA93EB3 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E60197C7F363BC8ECACC603DD038E424 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F0FC049CD1FA3C2050140CA1235C3587 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 2773C3D7F17540DCD11DBFB4CD95F894 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 20C206CA6EF7BFB37EA703F8BEFBB5B0 /* Pods-Web3supportTests-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 50EC1377492C5102F2F8C553CABE4A49 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 2D255B2758377F7CF44713FBD9F0DEF3 /* ABI.swift in Sources */, + 8CFAB2E848223BB549F83CDF45D211AA /* ABIDecoding.swift in Sources */, + 9DBCF5E7D37DC2CF11A6E4FD53826708 /* ABIElements.swift in Sources */, + 812D264C4A7869539BA734E1FE654B27 /* ABIEncoding.swift in Sources */, + 24F2EB8E45FE8658FDDFDB0701E0B3B6 /* ABIParameterTypes.swift in Sources */, + DCD218381EF101F92FE235D7588750A8 /* ABIParsing.swift in Sources */, + FE36801FAFBE465DA7DFB6AD05D21CB3 /* ABITypeParser.swift in Sources */, + 82EEFD50F58B36720B34916845913842 /* AbstractKeystore.swift in Sources */, + F2148DCA360E3D898EBFC61989663D7D /* Array+Extension.swift in Sources */, + 85C6833DDA0D0E761EE32F7566019DE1 /* Base58.swift in Sources */, + FC4A5E6CAB0A4C03DD083AFBD48E33DC /* BigUInt+Extensions.swift in Sources */, + 8E375613F407E1171F069FFA526B08A2 /* BIP32HDNode.swift in Sources */, + F782C5EF946C6DCC8124E1F5F965ADCA /* BIP32Keystore.swift in Sources */, + 60793CB821B498E92576B790FD0F95F8 /* BIP32KeystoreJSONStructure.swift in Sources */, + 8800FB2685022185627E8840BD19FD43 /* BIP39+WordLists.swift in Sources */, + A1A3867F89E6645A9E535A123CF679CE /* BIP39.swift in Sources */, + 975DB75B4BA3DFBBCC71CF7A8A4AC59C /* BloomFilter.swift in Sources */, + 5063B1206FC2051E566265E1909FAC2A /* Bridge.swift in Sources */, + 496ED54AB3DA2B56E57B051D23C83BAD /* BrowserViewController.swift in Sources */, + 51FA3801910C079DDB18016F5F8FC84D /* ComparisonExtensions.swift in Sources */, + FE6E586C19FC7D452C518016634BD270 /* ContractProtocol.swift in Sources */, + 10A7CA08B991B33D86A0B713E094489E /* CryptoExtensions.swift in Sources */, + D5CEF6D49D61B3072C11D312D977AA3D /* Data+Extension.swift in Sources */, + 2859803236FFE4CB1474293BE56D8889 /* Decodable+Extensions.swift in Sources */, + 122311180757E413126BF7D15239A58F /* Dictionary+Extension.swift in Sources */, + E6947D331B9074A87D47646860DB02F1 /* EIP67Code.swift in Sources */, + BE309A78FF212AF93A7E979CD7B9F781 /* EIP681.swift in Sources */, + D3802E537EDE6A231508103942435FE4 /* Encodable+Extensions.swift in Sources */, + BE69B05F62FA6C46F1280B896B645696 /* ENS.swift in Sources */, + 442B1F4F76FBCFAF1F27876847715C12 /* ENSBaseRegistrar.swift in Sources */, + 9731EDF8F60C68FC5EBE3FCBB6675846 /* ENSRegistry.swift in Sources */, + EDE0A58778159BE3D9A942027BE2E33D /* ENSResolver.swift in Sources */, + 6F03CD1EB789E952809C13D2EA6C819F /* ENSReverseRegistrar.swift in Sources */, + 16A1FA36B38C174BED3937B28FF30535 /* EthereumAddress.swift in Sources */, + BDCE30064CB17E618C38A04797F7F915 /* EthereumContract.swift in Sources */, + 1E23D653D73949318D8B1F3D53A05A71 /* EthereumFilterEncodingExtensions.swift in Sources */, + EDA33C46B91D3C87599782C7307F16BA /* EthereumKeystoreV3.swift in Sources */, + B7BAF0D7AAE50645B459C8984D966FCD /* EthereumTransaction.swift in Sources */, + F05D54B8A44050E36A06FF99D14DC771 /* ETHRegistrarController.swift in Sources */, + CB7485C6A44EBDB23A8D49E129817FBB /* EventFiltering.swift in Sources */, + FCD87C142ABB50A223501EBFEC54C689 /* Extensions.swift in Sources */, + 89C39070942182119EBF01EE36FE6C10 /* IBAN.swift in Sources */, + 5E7F07D663E9DC5279D0059C3CBA2B7F /* KeystoreManager.swift in Sources */, + 712053A56CCD73B5429412A5B04C28F9 /* KeystoreV3JSONStructure.swift in Sources */, + F2AD1E375CDB192DB1322931FB22A49C /* NameHash.swift in Sources */, + 1B09E265817C6F239010997AAFF015E0 /* NativeTypesEncoding+Extensions.swift in Sources */, + DA53D83B9E17BD18CF3DDF9FC233D00C /* NonceMiddleware.swift in Sources */, + 5B498F77BA82755F0EA392ADAE895038 /* NSRegularExpressionExtension.swift in Sources */, + 866E7694E457A77B466115DADDF00D5B /* PlainKeystore.swift in Sources */, + 4C0B06508832B66B8FC871EAD70B101E /* Promise+Batching.swift in Sources */, + 70EEBB8F6ECE31F6CD454A57AF89D72E /* Promise+HttpProvider.swift in Sources */, + 8C167D80A661845226C2A2B22049BFEA /* Promise+Web3+Contract+GetIndexedEvents.swift in Sources */, + 0DCA684E52941FC547C424E89E7FF830 /* Promise+Web3+Eth+Call.swift in Sources */, + 485369BDF5E2ACD219983520F20F42F9 /* Promise+Web3+Eth+EstimateGas.swift in Sources */, + D5BD740464E71320CEF4092FA1CF62E8 /* Promise+Web3+Eth+GetAccounts.swift in Sources */, + C743E09891827198E2A27DDD70C37238 /* Promise+Web3+Eth+GetBalance.swift in Sources */, + DFC7A99D7DB5F4C62BA4EC95F31156AF /* Promise+Web3+Eth+GetBlockByHash.swift in Sources */, + 2117D9C7CE49B63C17BFBF811C1B709C /* Promise+Web3+Eth+GetBlockByNumber.swift in Sources */, + 3A9EA81949CDEFD08121EFDD5F8807BD /* Promise+Web3+Eth+GetBlockNumber.swift in Sources */, + C226251E2377797FECAE371AA069E051 /* Promise+Web3+Eth+GetGasPrice.swift in Sources */, + 94B88E81C4DD104E870876302B16FC31 /* Promise+Web3+Eth+GetTransactionCount.swift in Sources */, + 44031DBC1B3905CB9D22525C9E76EB42 /* Promise+Web3+Eth+GetTransactionDetails.swift in Sources */, + F79836F9B32DACCE139E0D3FF0ADBA3A /* Promise+Web3+Eth+GetTransactionReceipt.swift in Sources */, + 1E8F207BAF428C44E0EE33E75C2EB8A5 /* Promise+Web3+Eth+SendRawTransaction.swift in Sources */, + 838AD4FB685FD2C3578AAE01B99B8037 /* Promise+Web3+Eth+SendTransaction.swift in Sources */, + 16DD36D15AB2DF7134AB207314C88C1B /* Promise+Web3+Personal+CreateAccount.swift in Sources */, + 374559C0764BF277776F447353E2D740 /* Promise+Web3+Personal+Sign.swift in Sources */, + 8F8F2AC356A0467D3FC0CE3118E9BC7E /* Promise+Web3+Personal+UnlockAccount.swift in Sources */, + D265EB1D3322C89E88578203E8D30089 /* Promise+Web3+TxPool.swift in Sources */, + 4BB3F625F107C3EF2F249F68B6D6788B /* PublicKey.swift in Sources */, + 3ECD67E484E3B7DE40FBFA2660574A87 /* RIPEMD160+StackOveflow.swift in Sources */, + 0C21024B8BA4EF6B1368AAB0BA858CE1 /* RLP.swift in Sources */, + 1026E20FA9AAA86877D63DA8330C056B /* SECP256k1.swift in Sources */, + 61CBA07C78D3A36DB19ED4E834CBB417 /* String+Extension.swift in Sources */, + 8AC718714C214D0C022A8E999307BA8F /* TransactionSigner.swift in Sources */, + CF735CE2B0CCDC8143A795A05268E303 /* Web3+BrowserFunctions.swift in Sources */, + 5B48D6BBBD9B1B4F46DDCAD22E7E5709 /* Web3+Constants.swift in Sources */, + 7771BEDF6237FFD4BD975996E99E8768 /* Web3+Contract.swift in Sources */, + 2949B8CC1CBAD6B0C1B942E3677C72A1 /* Web3+ERC1155.swift in Sources */, + 764FB86CFCE8188C52A97C69E35FA451 /* Web3+ERC1376.swift in Sources */, + 3AE0F49B3815815148F319E9D46C5533 /* Web3+ERC1400.swift in Sources */, + 6CA9E1BB397E222835F023CA94E1433B /* Web3+ERC1410.swift in Sources */, + 180E9D6CDF30A5F865D97B14BE3DAF81 /* Web3+ERC1594.swift in Sources */, + 57A63C7B947C33B503717E92DA907110 /* Web3+ERC1633.swift in Sources */, + 352BF48C1712389938C5B533A6A0D55A /* Web3+ERC1643.swift in Sources */, + CDFD73E3F48E41AC02FF863606FD8670 /* Web3+ERC1644.swift in Sources */, + DBAFAD28A00E7AA26EABBAFB7DB9040A /* Web3+ERC165.swift in Sources */, + CD6F384F7FD1471FC28E900AF5C30CD7 /* Web3+ERC20.swift in Sources */, + 2210254B6B7F0DBCFEEEBE4D4FA2BF87 /* Web3+ERC721.swift in Sources */, + 5FB5F56A8C4B2462E885C40EC675F5BF /* Web3+ERC721x.swift in Sources */, + 2E40B5BF79B05A81DFA5921032FB032C /* Web3+ERC777.swift in Sources */, + 318D1DE9728C02574B9371682D8539A4 /* Web3+ERC820.swift in Sources */, + 5263C1C4A40EAC79395190B4BF4F9096 /* Web3+ERC888.swift in Sources */, + 47134B51DE3E9A10AB40082EE69FC0B3 /* Web3+Eth+Websocket.swift in Sources */, + A2E252B71846F99034B0BA5D873541B6 /* Web3+Eth.swift in Sources */, + 05DC9941687D98BA8FC904388B11CE09 /* Web3+Eventloop.swift in Sources */, + E9D57E847BA0CD23F259C5439DD01CF8 /* Web3+EventParser.swift in Sources */, + 8C35A342254C4AA753BD1F2297057490 /* Web3+HttpProvider.swift in Sources */, + C96D26290D68F1A1AFE25447DEDBC242 /* Web3+InfuraProviders.swift in Sources */, + 4F05619F8AB68F66AE44B802157E59F8 /* Web3+Instance.swift in Sources */, + D3A4E037E7EF15EB4ADCA79F2F710442 /* Web3+JSONRPC.swift in Sources */, + CDB3A572D3A67D590B0F2BBD28466B22 /* Web3+Methods.swift in Sources */, + C2D49681C376A0AA1655D9B9C97576C3 /* Web3+MutatingTransaction.swift in Sources */, + D7825440503C1E88B601F86B8AF1E764 /* Web3+Options.swift in Sources */, + FCEA3386F95EE7BF8F1524E5FF02D65D /* Web3+Personal.swift in Sources */, + E0C47625480AC84B765B1BD10F8522F0 /* Web3+Protocols.swift in Sources */, + 05E4E4CAC324A27052B047FB49A93994 /* Web3+ReadingTransaction.swift in Sources */, + F472C27B7B2B0E9D87D3CA70E537A681 /* Web3+SecurityToken.swift in Sources */, + 0C37352F62817E5CC47A0EC2460F2A0A /* Web3+ST20.swift in Sources */, + F725A3D4D65CF179A6344254360B6FEF /* Web3+Structures.swift in Sources */, + D9CB9678AA0D7BC8E936869A104D64AD /* Web3+TxPool.swift in Sources */, + 362BFC668055F3A0980C4B6E4568043C /* Web3+Utils.swift in Sources */, + E60107C234FBEF7FB2AE9567A26B6025 /* Web3+Wallet.swift in Sources */, + 1F0FDEF447A2FA6E89F4BEB39A81FE56 /* Web3+WebsocketProvider.swift in Sources */, + 2D7E01E2B44343D0E4C9A50C95318AE6 /* Web3.swift in Sources */, + 936AF3BB98A3900202979429453172AA /* web3swift-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5E5F9E7DC1D3B74E7C15141C2B3E9BD5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 4981C37D541CDA8BCB7DE77E6607AC50 /* after.m in Sources */, + 3378C1EEFC149B899433AF30F147CE32 /* after.swift in Sources */, + A5F5D7A20264221D4A7F489FB0060D34 /* afterlife.swift in Sources */, + A1E6C35C5B3ECB558FE1AF9B1FAAB53B /* AnyPromise.m in Sources */, + EF8241DFA90BCDBB97B8C504BB80D05C /* AnyPromise.swift in Sources */, + 9BFE70DD7ECA3C6183B82DE691FE4491 /* Box.swift in Sources */, + 4418281931C4D1176F2C541CDD770F14 /* Catchable.swift in Sources */, + 1C5D3593B983B9369EFCFDE7D4DE0D19 /* Configuration.swift in Sources */, + 9B65647B927085E2366117D59DC1586D /* CustomStringConvertible.swift in Sources */, + B593B56495A204E756BAA753BA2D6E9C /* Deprecations.swift in Sources */, + C7ECF714064C1188A6D042C6ACFD9504 /* dispatch_promise.m in Sources */, + 37018D3DC554A00E9B3E306A28296316 /* Error.swift in Sources */, + FB797FAA96B41ACE7474B8ADEF8107EC /* firstly.swift in Sources */, + 4D65C782220C5E27BF8A3B61EBBDAB3E /* Guarantee.swift in Sources */, + 301B5F7669D2DC7E46384FBAC71B7C19 /* hang.m in Sources */, + FED8C9BB577D35DBB6E5347B750C184C /* hang.swift in Sources */, + 15901C26A398A72C746D1369042356B6 /* join.m in Sources */, + C5EF8FBC11CA9E66100F6489B57E35A6 /* LogEvent.swift in Sources */, + C426E30A28E2545BCA2824DBCF90816F /* NSNotificationCenter+AnyPromise.m in Sources */, + 29643F7A000899634C9174BCB8D1A1AB /* NSNotificationCenter+Promise.swift in Sources */, + B758241FBF6592EFBE6283378D16F9FD /* NSObject+Promise.swift in Sources */, + FDF12428281F08B3F5F2B7DB68E3925D /* NSTask+AnyPromise.m in Sources */, + 5802BD2A7E671D3015BE4E98C13D10CB /* NSURLSession+AnyPromise.m in Sources */, + 3208DDEB9CAC16AC7D2C7E9A7F057DC1 /* NSURLSession+Promise.swift in Sources */, + EF9BBCE851B820D4F5DA3163BF466A38 /* Process+Promise.swift in Sources */, + 6DE830042E36FDE326546970CA90F9B6 /* Promise.swift in Sources */, + 18DF6A317CCB7F5BEE8D7AF5D79AEB38 /* PromiseKit-dummy.m in Sources */, + 46C4120B8C66DBCBEEC55D09F043D618 /* race.m in Sources */, + 4EC7BD8654B3587F1F725E812C9D828C /* race.swift in Sources */, + 997870D5F490326F024B4D8687FF18DC /* Resolver.swift in Sources */, + 025EED6A44FE486DD84DA9D38AC02AA0 /* Thenable.swift in Sources */, + 52F57EB35132E86D75FE9443258EFDBF /* UIView+AnyPromise.m in Sources */, + 69DBAB1E3A8EEBFCC466D95509DE7125 /* UIView+Promise.swift in Sources */, + 9447BD0FB408B2A7C9BFDFF99BBE1EBE /* UIViewController+AnyPromise.m in Sources */, + 42495A8941D9B42B07F032390AA2389F /* UIViewPropertyAnimator+Promise.swift in Sources */, + 208EDAA1D258CAA2BD08E462359D4FFF /* when.m in Sources */, + 73EA1C553B580637369E1D5A72A425B3 /* when.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 621EE447A1C117BDCD418F5DE070FD3C /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 068E5963381B58D7D8CD321462F567ED /* Compression.swift in Sources */, + 1627E6FA0453D6DB472BA444F1D32AE7 /* SSLClientCertificate.swift in Sources */, + 8B3350D96B15B975184C8EE0819F9623 /* SSLSecurity.swift in Sources */, + 294D61E8A195B6A1F6AEDCF0F73599A5 /* Starscream-dummy.m in Sources */, + C02D9FEB295BDA1359D2F52C80F8E75A /* WebSocket.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6ABAAB41EEC545F9AA87617468292FF2 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 883036C28D3D55337CAD22CCFC568F1A /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + A93275D5C1DAD3CA7CCC2A9586AC9ADE /* AEAD.swift in Sources */, + 68A92231E087567C6A9AD700359DAE80 /* AEADChaCha20Poly1305.swift in Sources */, + 5CEFD4F8821A3A1BD6C78FFCBCC98DA4 /* AES+Foundation.swift in Sources */, + E0067342787B93C845546321EF1DC7D8 /* AES.Cryptors.swift in Sources */, + 54BDD3BC1B92330FEF7F64FA1660BB13 /* AES.swift in Sources */, + F4DB8BAA8CC2482A2F0408BB78DC5636 /* Array+Extension.swift in Sources */, + 3607067F46CCABE732B2E0078149F8B2 /* Array+Foundation.swift in Sources */, + 448506F29495E3B3BAB56D093D681C1A /* Authenticator.swift in Sources */, + 91A59A657AB2118D4FFFC913EAD87EC9 /* BatchedCollection.swift in Sources */, + 0E6F0E8337D8928B164D18FC54D6C7F9 /* Bit.swift in Sources */, + CA5F0FF46E700A877E1ED5C9EF6BDECB /* BlockCipher.swift in Sources */, + DBCA1194814B520897C3D81C016F51DB /* BlockDecryptor.swift in Sources */, + 0526AEB2FAAA1D80AC6245AB71BE994F /* BlockEncryptor.swift in Sources */, + 854AF7B141389D5512E8E73DF38FEBEA /* BlockMode.swift in Sources */, + 792AECF194FD9EEC68866D1499302916 /* BlockModeOptions.swift in Sources */, + EA95317C04FA46F08399A9F6DFE82119 /* Blowfish+Foundation.swift in Sources */, + B4E0F6805D68577613B95A18651FC167 /* Blowfish.swift in Sources */, + 5300EB86348ED2DD35A9339104F21842 /* CBC.swift in Sources */, + 3E3FE29D83B6DB4B229CB38CCB4E1C86 /* CBCMAC.swift in Sources */, + 8573D5547D4AC8CEE69AB545148A72B6 /* CCM.swift in Sources */, + C680444C2E2E5076D981C2A8452AC067 /* CFB.swift in Sources */, + F4EB4FFB5BFE253769101209CBD7BA13 /* ChaCha20+Foundation.swift in Sources */, + DD7CAA2463A742FC740431ED674892FD /* ChaCha20.swift in Sources */, + 294C60E5E562CF3C2917335BDD910F42 /* Checksum.swift in Sources */, + AE242F808DE761641CF108E8844745D6 /* Cipher.swift in Sources */, + 5FDAD3F1739595982080BE2DD789C697 /* CipherModeWorker.swift in Sources */, + 5B8A5FDFCDA736C6929320348B66149D /* CMAC.swift in Sources */, + 61330480364F92D57CB181E890C8896B /* Collection+Extension.swift in Sources */, + D8C90AFD1D666460C3FE007172ED052E /* CompactMap.swift in Sources */, + 8C05403EC0F455CB86CFD8060C1C5DC2 /* Cryptor.swift in Sources */, + 7997EAE951EAB362280E2CE750810231 /* Cryptors.swift in Sources */, + 5E5EBD7039DC8763BFB20616B2AFE5F6 /* CryptoSwift-dummy.m in Sources */, + C829EE08BBA51E4F85528D4D6B4D8DEB /* CTR.swift in Sources */, + 0049EB7DC74BEFCDC5740A4FFBE89170 /* Data+Extension.swift in Sources */, + 8ED7D4847260B4F398ECF4351280AB31 /* Digest.swift in Sources */, + 69E62D35A7043AEBAFF100D522F38A30 /* DigestType.swift in Sources */, + 2DD9959CD5493A978BCB3B3CC0D2EB49 /* ECB.swift in Sources */, + B15E0CD8A2E6D29E9849F092CD078773 /* GCM.swift in Sources */, + 1C482705924CA6C3DF716EC60624900B /* Generics.swift in Sources */, + A65BC55FFE138090EF77D9EC1F72A88B /* HKDF.swift in Sources */, + ED4ED80104798E648B2B82A10DA586F1 /* HMAC+Foundation.swift in Sources */, + 6D78DA2799A948EFEBBDDCDB21181B6E /* HMAC.swift in Sources */, + ABF5E5F45D270B8B7CE386D4BB8E614D /* Int+Extension.swift in Sources */, + 49C8C4DFD859391ED9CB7EBC50DDBBD1 /* MD5.swift in Sources */, + 1E6C33DE401D9AEFE660851A3E3394E6 /* NoPadding.swift in Sources */, + C138FACCB027B81AE55814AA990543D5 /* OFB.swift in Sources */, + 636A216DCBEBED81DA2DB1A12C7639E0 /* Operators.swift in Sources */, + 13A4BA994DAE26C3B22F1842D5E186BD /* Padding.swift in Sources */, + AAA648FE58CC4A49EF39BFDBCBA7C1FA /* PBKDF1.swift in Sources */, + 99EE8A649068210DF711EA2FFBE1C3BF /* PBKDF2.swift in Sources */, + 7CA57460C1D6652FD0CF4B62C596849B /* PCBC.swift in Sources */, + F44208FA90F7B7118E5A3CA21AB37A84 /* PKCS5.swift in Sources */, + 7E6F4EFB85936E0B3EB9AD287F074C36 /* PKCS7.swift in Sources */, + 8D58B7BD460D20FFEC478698F7F52222 /* PKCS7Padding.swift in Sources */, + 7E3E6309C4EB4C70BC8AF5EB9CA3B6FB /* Poly1305.swift in Sources */, + 2E938A3C33EE9130C959EFA811DFB2EE /* Rabbit+Foundation.swift in Sources */, + 58AD203AF555F9B8416F7F9B4C7DA435 /* Rabbit.swift in Sources */, + ADE26A6317E68C1CB7FC86D68B4EB8BF /* RandomBytesSequence.swift in Sources */, + C17E552920AF110E9DB7AB635C65A12D /* Scrypt.swift in Sources */, + 49696DF6233801BF2D0F0BE214E56304 /* SecureBytes.swift in Sources */, + F3B9FF17CD827482C5FCDE987FCBA026 /* SHA1.swift in Sources */, + 2FDD3DAC4E9D0C03A16D3F838A8E15F5 /* SHA2.swift in Sources */, + 694E630570AB4DB0BCDF003411CF2B63 /* SHA3.swift in Sources */, + 9A80311C79CED9486D2E9FA4DEC3D45A /* StreamDecryptor.swift in Sources */, + 45746D692A8E7F09C0EED2675231EF41 /* StreamEncryptor.swift in Sources */, + 420C87B493B70746472899A82479242F /* String+Extension.swift in Sources */, + D820172C124F8B10D0C72B31F1819FDC /* String+FoundationExtension.swift in Sources */, + CC03E31F122F91A26DD22BEEF813D779 /* UInt128.swift in Sources */, + 8039DF4C1AE7378FB41921D22A44AEF7 /* UInt16+Extension.swift in Sources */, + 59CB2BC19644CCDCE0A6B59528348FD1 /* UInt32+Extension.swift in Sources */, + 9D22006C799C6F6E9452B97B760F7CD1 /* UInt64+Extension.swift in Sources */, + EC1F98C6E1424F6190176058FAA43C5A /* UInt8+Extension.swift in Sources */, + 438DAC7813FDB677252FB52A8FA3E708 /* Updatable.swift in Sources */, + 05958032576427EDBC47854025783311 /* Utils+Foundation.swift in Sources */, + 00C6A45F25B7C9567ABD4B6CEBB8F3A0 /* Utils.swift in Sources */, + FC380F439D913681D738F1BE7B739646 /* ZeroPadding.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A4AD34E54920BDEC0B564E5EF22910E2 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 3B637B4A3FB612145E0EF8A1FDF8613E /* Pods-Web3support-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + AD425074D950826A1AA1323039964E21 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 6002AD14210CBE9C34EB848031CFD7E6 /* Addition.swift in Sources */, + FFF7E224F5F3094210837EC8C7FE4960 /* BigInt-dummy.m in Sources */, + 5E2574B7162EED00A81237F56CDC0BE4 /* BigInt.swift in Sources */, + AC7DBF3AD44B3E7644068E6F09F9EBF2 /* BigUInt.swift in Sources */, + 04C4B5D00750E2E4DFD4C4C7CC47283A /* Bitwise Ops.swift in Sources */, + DBE9A6D9CB82D8605F4C25B9426B1557 /* Codable.swift in Sources */, + 16F71F20D31B7EEC6A60DB14135AB7A9 /* Comparable.swift in Sources */, + 39137B0D7B8FB5BF554BDE012BD85061 /* Data Conversion.swift in Sources */, + 3B9A2601095A9A72843D76CA44B37782 /* Division.swift in Sources */, + 0DF63A4C8FA0E53FB630F5B5429FF066 /* Exponentiation.swift in Sources */, + 2228B8549F0F5445D1B2D346E12A20CD /* Floating Point Conversion.swift in Sources */, + F13925E2206A7647AC326ECFA6ED2856 /* GCD.swift in Sources */, + 4A8B21596204A43258F4EC69A7AEC66E /* Hashable.swift in Sources */, + E0B84D75D0F7E7EA2E905C05774CC361 /* Integer Conversion.swift in Sources */, + D48A4410A7C8CE6B6A0787A0F4999DE5 /* Multiplication.swift in Sources */, + E93CF504980B3D653BB4530E7F98E9F6 /* Prime Test.swift in Sources */, + AC4E061C6A2D21210122B471D8BCC81E /* Random.swift in Sources */, + BE29AFA73FEDAFA471F35F8AB1C3EA99 /* Shifts.swift in Sources */, + 4362503059C68DFCDCB8621F4FD9E325 /* Square Root.swift in Sources */, + 99F35D362CDAA3F01D59E05FAB02907D /* Strideable.swift in Sources */, + E8ABBB87CFEBE721FC2D14B71A719BC2 /* String Conversion.swift in Sources */, + BAA052C302D45F8DAB72606E997CAD69 /* Subtraction.swift in Sources */, + 8599E23B2946C6F3F6DA3D63EC82C4A3 /* Words and Bits.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E273F872A91B40D94C04090B6D582310 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + CD6894E475BBE3884302A212F9D60F2D /* secp256k1.c in Sources */, + 63EE527DD6C1FD264C5FC890E07966A2 /* secp256k1.c-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EF0BB8557CEBFFC7253D25CED45CFDF1 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + AF8F1135157EDA1D6857CCE22DC8BFD2 /* Pods-Web3support-Web3supportUITests-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 042A3F3301E93C1CC5EFDB139A9740C4 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = PromiseKit; + target = 7C579CE66A1E7A9AA33CA5F97F9C22C5 /* PromiseKit */; + targetProxy = B71CBF8CE0F2043749ABE01D111F132F /* PBXContainerItemProxy */; + }; + 4711010F4D9CC1B8672E51F063FF0C20 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = web3swift; + target = 99364D9FB07EF3FA5DFE1237001805EC /* web3swift */; + targetProxy = FFADCAF642253937DD1698CD85D78B9D /* PBXContainerItemProxy */; + }; + 4C3C2E8D3D728E8267429F61675F8359 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = secp256k1.c; + target = 161C26511FC920CB146236AB7295D5E0 /* secp256k1.c */; + targetProxy = 896D038F81E5A564CD15AB2995B57ACF /* PBXContainerItemProxy */; + }; + 53169DDC2887E3577BA4E02554C2642F /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = PromiseKit; + target = 7C579CE66A1E7A9AA33CA5F97F9C22C5 /* PromiseKit */; + targetProxy = 30917E033BC92A1E31096560E8E3617F /* PBXContainerItemProxy */; + }; + 57D2805434C91AC9D27F392D88717076 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = CryptoSwift; + target = 99313990C1D76A6D1D017868B6975CC8 /* CryptoSwift */; + targetProxy = 0A51A901F3B287BBF1000859EC5BBDF8 /* PBXContainerItemProxy */; + }; + 5DE504F58C77C11303D1142E35694D48 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = secp256k1.c; + target = 161C26511FC920CB146236AB7295D5E0 /* secp256k1.c */; + targetProxy = 3D115CEE91175984B06F86BF35058C29 /* PBXContainerItemProxy */; + }; + 735E2118F7B8C93B96AE29DDAB2E1FB2 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = BigInt; + target = 09DD83B7D075842A3A5105AD410BD38A /* BigInt */; + targetProxy = 9C21A707FC9B8CE4B8720A654CF3896D /* PBXContainerItemProxy */; + }; + 8B7E9A16E9B01B06ED404913A69B355E /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = BigInt; + target = 09DD83B7D075842A3A5105AD410BD38A /* BigInt */; + targetProxy = 44893332164B13BB6097FB2FC1759C66 /* PBXContainerItemProxy */; + }; + 96FFD10FCEC9C56213E501D96B706B24 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Starscream; + target = 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */; + targetProxy = A15407EF6D2CABF3C2E38B488FE2D7BE /* PBXContainerItemProxy */; + }; + 99596231AB2C18AA302EEF4787A20A08 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Starscream; + target = 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */; + targetProxy = FE035B72D4A3A68923514A877A94A464 /* PBXContainerItemProxy */; + }; + A8228F3E569A6668515F99173E441EC6 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = BigInt; + target = 09DD83B7D075842A3A5105AD410BD38A /* BigInt */; + targetProxy = 83C8508E6D07DC36A130031F3F4D8B5E /* PBXContainerItemProxy */; + }; + AF46632C647B5F41C755FC860445EFF1 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "web3swift-Browser"; + target = 8CDD759A6130CA265C6D157F4407C39B /* web3swift-Browser */; + targetProxy = 0961DD78639170DFD439B2761E56DED4 /* PBXContainerItemProxy */; + }; + AF72EA0E12AB059080306245BBA45FA8 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = CryptoSwift; + target = 99313990C1D76A6D1D017868B6975CC8 /* CryptoSwift */; + targetProxy = A1E809480611834A0D655B4C337B06BB /* PBXContainerItemProxy */; + }; + C35321477411982E3F6C2F42E00771C3 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = CryptoSwift; + target = 99313990C1D76A6D1D017868B6975CC8 /* CryptoSwift */; + targetProxy = A811A6706A5A97C6E1581EE917AAE4A7 /* PBXContainerItemProxy */; + }; + DE9A214F07E0828F590294A03B20DBB3 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = secp256k1.c; + target = 161C26511FC920CB146236AB7295D5E0 /* secp256k1.c */; + targetProxy = 4FE21A486B0FC29FA900A9C483959DB9 /* PBXContainerItemProxy */; + }; + E2019C760F7AAB6F5AD72A5214B9E8E4 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = web3swift; + target = 99364D9FB07EF3FA5DFE1237001805EC /* web3swift */; + targetProxy = 6CF15647D9C4825B65AD4FF802C3FB39 /* PBXContainerItemProxy */; + }; + F7C324C36EEA52C09B98528E046A8D41 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "Pods-Web3support"; + target = BF16A4D4E4C02517868813AFD92FC23D /* Pods-Web3support */; + targetProxy = 7DDECD3D6C9CB99648CF0248D90A07EF /* PBXContainerItemProxy */; + }; + F89104DD315458BFBBBD38619CDCFFFB /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = PromiseKit; + target = 7C579CE66A1E7A9AA33CA5F97F9C22C5 /* PromiseKit */; + targetProxy = 49012792450E6349879C50361A907A0A /* PBXContainerItemProxy */; + }; + FB61F3BB55E87B91CD441503F8C2AC6C /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Starscream; + target = 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */; + targetProxy = 41A570987EA7C14D60BFB0E6373F68F4 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 18033E6B936EB472E58E9196A01983E9 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = FE0467E7D290AD76D8FBF8D93EB6201F /* web3swift.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/web3swift/web3swift-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/web3swift/web3swift-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/web3swift/web3swift.modulemap"; + PRODUCT_MODULE_NAME = web3swift; + PRODUCT_NAME = web3swift; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 3A71E70CA7A1ACA85C6EF4D3DDAFF3AA /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1E64004ED18613E15E5FA474A4F25ECD /* Pods-Web3support-Web3supportUITests.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 14.5; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 3BE0CA2BAB19A000867078C53C867438 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 394218B5A5E8E974A3936D3FF6EBB7D9 /* BigInt.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/BigInt/BigInt-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/BigInt/BigInt-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/BigInt/BigInt.modulemap"; + PRODUCT_MODULE_NAME = BigInt; + PRODUCT_NAME = BigInt; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 437B9C7164707228276D5955A650693B /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 72CA11293C1FEAD46D53B50D3F53830A /* Pods-Web3support-Web3supportUITests.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 14.5; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 45BB14942973726BBB1BC14D3B4C415D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E2D25E8396C1FAE8881A5DF91CC9C297 /* Pods-Web3support.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-Web3support/Pods-Web3support-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 14.5; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-Web3support/Pods-Web3support.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 4C1BFADBCE2B57C22989C55835A0C6C3 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A82FF443AB4F28BA98ADDAEDC46D3CB5 /* PromiseKit.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/PromiseKit/PromiseKit-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PromiseKit/PromiseKit-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/PromiseKit/PromiseKit.modulemap"; + PRODUCT_MODULE_NAME = PromiseKit; + PRODUCT_NAME = PromiseKit; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 57C239758A1C51A6952D04A4E52ECDC2 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = FB5389FE6F5CCCD967823377DDEDDAA6 /* BigInt.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/BigInt/BigInt-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/BigInt/BigInt-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/BigInt/BigInt.modulemap"; + PRODUCT_MODULE_NAME = BigInt; + PRODUCT_NAME = BigInt; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 5C485EDD9A137EED2388EE0583A131E0 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = F59E103F85C63360F8FE84A3325A58BE /* Starscream.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/Starscream/Starscream-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Starscream/Starscream-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Starscream/Starscream.modulemap"; + PRODUCT_MODULE_NAME = Starscream; + PRODUCT_NAME = Starscream; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 5DD11A33BE96CDA2FE7CEEB91D21E06C /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = F777E45908B4CA01B6397251588326AA /* CryptoSwift.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/CryptoSwift/CryptoSwift-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/CryptoSwift/CryptoSwift-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/CryptoSwift/CryptoSwift.modulemap"; + PRODUCT_MODULE_NAME = CryptoSwift; + PRODUCT_NAME = CryptoSwift; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 751883D55254A1AC52EBAE850DF9C91D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 18192636EB88C2E682F782E9A7FB734B /* Pods-Web3supportTests.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 14.5; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 796DF59A2B23427CAF4DF1B9C3A64889 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = C79A3303BD0F92F861FB31F09E38C4FD /* web3swift.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/web3swift/web3swift-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/web3swift/web3swift-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/web3swift/web3swift.modulemap"; + PRODUCT_MODULE_NAME = web3swift; + PRODUCT_NAME = web3swift; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 89E1D99263B43EA138698B60700386FB /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 6C537535F3EDDBA8ED7569976986A05A /* Starscream.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/Starscream/Starscream-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Starscream/Starscream-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Starscream/Starscream.modulemap"; + PRODUCT_MODULE_NAME = Starscream; + PRODUCT_NAME = Starscream; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 8CB0D0DFD097B78A4EBDFD4DB925494C /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = FDAF6B3919EFC6904000083D78B40777 /* Pods-Web3supportTests.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 14.5; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 906EA630BC47CE48DD14D86271B580DC /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = FE0467E7D290AD76D8FBF8D93EB6201F /* web3swift.release.xcconfig */; + buildSettings = { + CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/web3swift"; + IBSC_MODULE = web3swift; + INFOPLIST_FILE = "Target Support Files/web3swift/ResourceBundle-Browser-web3swift-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + PRODUCT_NAME = Browser; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + WRAPPER_EXTENSION = bundle; + }; + name = Release; + }; + 9EB7695FE0BC834DB945B93CDD41E4F3 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = EFE3F8A99AC6C9B022235FC5AFAA5587 /* PromiseKit.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/PromiseKit/PromiseKit-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PromiseKit/PromiseKit-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/PromiseKit/PromiseKit.modulemap"; + PRODUCT_MODULE_NAME = PromiseKit; + PRODUCT_NAME = PromiseKit; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + A0BBFFC8425325791F8559758BE1DF9B /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = C79A3303BD0F92F861FB31F09E38C4FD /* web3swift.debug.xcconfig */; + buildSettings = { + CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/web3swift"; + IBSC_MODULE = web3swift; + INFOPLIST_FILE = "Target Support Files/web3swift/ResourceBundle-Browser-web3swift-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + PRODUCT_NAME = Browser; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + WRAPPER_EXTENSION = bundle; + }; + name = Debug; + }; + AD82640A041A6CDC6E9971F53AB28A03 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 2F7D2C17D3B22156BFB54CEFC3FC8C84 /* Pods-Web3support.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-Web3support/Pods-Web3support-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 14.5; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-Web3support/Pods-Web3support.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + BC01E0B73776AF6B58DC318A9BE988D7 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_DEBUG=1", + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 14.5; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + C605C363CC9F26F9FF97DBB1D5C6E25C /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_RELEASE=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 14.5; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + SWIFT_VERSION = 5.0; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Release; + }; + C7ABF6DCFA1ABAE3A00A3622F6DB92A8 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 3EBF7696596A1EE1DDA7A1F1962DD10D /* secp256k1.c.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/secp256k1.c/secp256k1.c-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/secp256k1.c/secp256k1.c-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/secp256k1.c/secp256k1.c.modulemap"; + PRODUCT_MODULE_NAME = secp256k1; + PRODUCT_NAME = secp256k1; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + D7D72B111F1A87424023C3B30B9D729A /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D6FD18A5E5FAABD8378DCFD58EEBADB5 /* CryptoSwift.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/CryptoSwift/CryptoSwift-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/CryptoSwift/CryptoSwift-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/CryptoSwift/CryptoSwift.modulemap"; + PRODUCT_MODULE_NAME = CryptoSwift; + PRODUCT_NAME = CryptoSwift; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + E9E964D7BE26C477AFF842B139939D20 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 6875770FBEBE2AF71365EB6DC30E3027 /* secp256k1.c.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/secp256k1.c/secp256k1.c-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/secp256k1.c/secp256k1.c-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/secp256k1.c/secp256k1.c.modulemap"; + PRODUCT_MODULE_NAME = secp256k1; + PRODUCT_NAME = secp256k1; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 058DF38F5922F24842B97693B0188F2D /* Build configuration list for PBXNativeTarget "PromiseKit" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 9EB7695FE0BC834DB945B93CDD41E4F3 /* Debug */, + 4C1BFADBCE2B57C22989C55835A0C6C3 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 0C905C3678D56B7D838AD8CAB2A28BE8 /* Build configuration list for PBXNativeTarget "secp256k1.c" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + E9E964D7BE26C477AFF842B139939D20 /* Debug */, + C7ABF6DCFA1ABAE3A00A3622F6DB92A8 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + BC01E0B73776AF6B58DC318A9BE988D7 /* Debug */, + C605C363CC9F26F9FF97DBB1D5C6E25C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4BDF6CF3744DB028DE330AE92336EAF8 /* Build configuration list for PBXNativeTarget "web3swift-Browser" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A0BBFFC8425325791F8559758BE1DF9B /* Debug */, + 906EA630BC47CE48DD14D86271B580DC /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4CB3A9ABAFAABE2A143C23B0FECFD4CF /* Build configuration list for PBXNativeTarget "Pods-Web3support" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 45BB14942973726BBB1BC14D3B4C415D /* Debug */, + AD82640A041A6CDC6E9971F53AB28A03 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 5104F4CC467A363177DF298548DA476E /* Build configuration list for PBXNativeTarget "BigInt" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 57C239758A1C51A6952D04A4E52ECDC2 /* Debug */, + 3BE0CA2BAB19A000867078C53C867438 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A281CF9B4D89AD9A8062C7D37C919915 /* Build configuration list for PBXNativeTarget "web3swift" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 796DF59A2B23427CAF4DF1B9C3A64889 /* Debug */, + 18033E6B936EB472E58E9196A01983E9 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + CF129DCD30773EF2C3A3E9B2EFFB4A7E /* Build configuration list for PBXNativeTarget "CryptoSwift" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 5DD11A33BE96CDA2FE7CEEB91D21E06C /* Debug */, + D7D72B111F1A87424023C3B30B9D729A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + D45F87D89ACC91CAABB0F34761B327F9 /* Build configuration list for PBXNativeTarget "Pods-Web3supportTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 8CB0D0DFD097B78A4EBDFD4DB925494C /* Debug */, + 751883D55254A1AC52EBAE850DF9C91D /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + EC4F22A05E3106C2754AD329144A6DE8 /* Build configuration list for PBXNativeTarget "Pods-Web3support-Web3supportUITests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 437B9C7164707228276D5955A650693B /* Debug */, + 3A71E70CA7A1ACA85C6EF4D3DDAFF3AA /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + ED5C15C705AB67930733A7E237A0A33A /* Build configuration list for PBXNativeTarget "Starscream" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 5C485EDD9A137EED2388EE0583A131E0 /* Debug */, + 89E1D99263B43EA138698B60700386FB /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = BFDFE7DC352907FC980B868725387E98 /* Project object */; +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.h b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.h new file mode 100644 index 000000000..351a93b97 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.h @@ -0,0 +1,44 @@ +#import +#import + + +/** + To import the `NSNotificationCenter` category: + + use_frameworks! + pod "PromiseKit/Foundation" + + Or `NSNotificationCenter` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + #import +*/ +@interface NSNotificationCenter (PromiseKit) +/** + Observe the named notification once. + + [NSNotificationCenter once:UIKeyboardWillShowNotification].then(^(id note, id userInfo){ + UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue]; + CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue]; + + return [UIView promiseWithDuration:duration delay:0.0 options:(curve << 16) animations:^{ + + }]; + }); + + @warning *Important* Promises only resolve once. If you need your block to execute more than once then use `-addObserverForName:object:queue:usingBlock:`. + + @param notificationName The name of the notification for which to register the observer. + + @return A promise that fulfills with two parameters: + + 1. The NSNotification object. + 2. The NSNotification’s userInfo property. +*/ ++ (AnyPromise *)once:(NSString *)notificationName NS_REFINED_FOR_SWIFT; + +@end diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.m b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.m new file mode 100644 index 000000000..f8aee7109 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.m @@ -0,0 +1,18 @@ +#import +#import +#import "PMKFoundation.h" + +@implementation NSNotificationCenter (PromiseKit) + ++ (AnyPromise *)once:(NSString *)name { + return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { + __block id identifier; + identifier = [[NSNotificationCenter defaultCenter] addObserverForName:name object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) { + [[NSNotificationCenter defaultCenter] removeObserver:identifier name:name object:nil]; + identifier = nil; + resolve(PMKManifold(note, note.userInfo)); + }]; + }]; +} + +@end diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+Promise.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+Promise.swift new file mode 100644 index 000000000..3b7f84345 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+Promise.swift @@ -0,0 +1,33 @@ +import Foundation +#if !PMKCocoaPods +import PromiseKit +#endif + +/** + To import the `NSNotificationCenter` category: + + use_frameworks! + pod "PromiseKit/Foundation" + + Or `NSNotificationCenter` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + import PromiseKit +*/ +extension NotificationCenter { + /// Observe the named notification once + public func observe(once name: Notification.Name, object: Any? = nil) -> Guarantee { + let (promise, fulfill) = Guarantee.pending() + #if os(Linux) && ((swift(>=4.0) && !swift(>=4.0.1)) || (swift(>=3.0) && !swift(>=3.2.1))) + let id = addObserver(forName: name, object: object, queue: nil, usingBlock: fulfill) + #else + let id = addObserver(forName: name, object: object, queue: nil, using: fulfill) + #endif + promise.done { _ in self.removeObserver(id) } + return promise + } +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSObject+Promise.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSObject+Promise.swift new file mode 100644 index 000000000..135719bf6 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSObject+Promise.swift @@ -0,0 +1,57 @@ +import Foundation +#if !PMKCocoaPods +import PromiseKit +#endif + +/** + To import the `NSObject` category: + + use_frameworks! + pod "PromiseKit/Foundation" + + Or `NSObject` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + import PromiseKit +*/ +extension NSObject { + /** + - Returns: A promise that resolves when the provided keyPath changes. + - Warning: *Important* The promise must not outlive the object under observation. + - SeeAlso: Apple’s KVO documentation. + */ + public func observe(_: PMKNamespacer, keyPath: String) -> Guarantee { + return Guarantee { KVOProxy(observee: self, keyPath: keyPath, resolve: $0) } + } +} + +private class KVOProxy: NSObject { + var retainCycle: KVOProxy? + let fulfill: (Any?) -> Void + + @discardableResult + init(observee: NSObject, keyPath: String, resolve: @escaping (Any?) -> Void) { + fulfill = resolve + super.init() + observee.addObserver(self, forKeyPath: keyPath, options: NSKeyValueObservingOptions.new, context: pointer) + retainCycle = self + } + + fileprivate override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { + if let change = change, context == pointer { + defer { retainCycle = nil } + fulfill(change[NSKeyValueChangeKey.newKey]) + if let object = object as? NSObject, let keyPath = keyPath { + object.removeObserver(self, forKeyPath: keyPath) + } + } + } + + private lazy var pointer: UnsafeMutableRawPointer = { + return Unmanaged.passUnretained(self).toOpaque() + }() +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.h b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.h new file mode 100644 index 000000000..29c2c0389 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.h @@ -0,0 +1,53 @@ +#if TARGET_OS_MAC && !TARGET_OS_EMBEDDED && !TARGET_OS_SIMULATOR + +#import +#import + +#define PMKTaskErrorLaunchPathKey @"PMKTaskErrorLaunchPathKey" +#define PMKTaskErrorArgumentsKey @"PMKTaskErrorArgumentsKey" +#define PMKTaskErrorStandardOutputKey @"PMKTaskErrorStandardOutputKey" +#define PMKTaskErrorStandardErrorKey @"PMKTaskErrorStandardErrorKey" +#define PMKTaskErrorExitStatusKey @"PMKTaskErrorExitStatusKey" + +/** + To import the `NSTask` category: + + use_frameworks! + pod "PromiseKit/Foundation" + + Or `NSTask` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + #import +*/ +@interface NSTask (PromiseKit) + +/** + Launches the receiver and resolves when it exits. + + If the task fails the promise is rejected with code `PMKTaskError`, and + `userInfo` keys: `PMKTaskErrorStandardOutputKey`, + `PMKTaskErrorStandardErrorKey` and `PMKTaskErrorExitStatusKey`. + + NSTask *task = [NSTask new]; + task.launchPath = @"/usr/bin/basename"; + task.arguments = @[@"/usr/bin/sleep"]; + [task promise].then(^(NSString *stdout){ + //… + }); + + @return A promise that fulfills with three parameters: + + 1) The stdout interpreted as a UTF8 string. + 2) The stderr interpreted as a UTF8 string. + 3) The stdout as `NSData`. +*/ +- (AnyPromise *)promise NS_REFINED_FOR_SWIFT; + +@end + +#endif diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.m b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.m new file mode 100644 index 000000000..beae27758 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.m @@ -0,0 +1,59 @@ +#import +#import +#import +#import +#import + +#if TARGET_OS_MAC && !TARGET_OS_EMBEDDED && !TARGET_OS_SIMULATOR + +#import "NSTask+AnyPromise.h" + +@implementation NSTask (PromiseKit) + +- (AnyPromise *)promise { + return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { + self.standardOutput = [NSPipe pipe]; + self.standardError = [NSPipe pipe]; + self.terminationHandler = ^(NSTask *task){ + id stdoutData = [[task.standardOutput fileHandleForReading] readDataToEndOfFile]; + id stdoutString = [[NSString alloc] initWithData:stdoutData encoding:NSUTF8StringEncoding]; + id stderrData = [[task.standardError fileHandleForReading] readDataToEndOfFile]; + id stderrString = [[NSString alloc] initWithData:stderrData encoding:NSUTF8StringEncoding]; + + if (task.terminationReason == NSTaskTerminationReasonExit && self.terminationStatus == 0) { + resolve(PMKManifold(stdoutString, stderrString, stdoutData)); + } else { + id cmd = [NSMutableArray arrayWithObject:task.launchPath]; + [cmd addObjectsFromArray:task.arguments]; + cmd = [cmd componentsJoinedByString:@" "]; + + id info = @{ + NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Failed executing: %@.", cmd], + PMKTaskErrorStandardOutputKey: stdoutString, + PMKTaskErrorStandardErrorKey: stderrString, + PMKTaskErrorExitStatusKey: @(task.terminationStatus), + }; + + resolve([NSError errorWithDomain:PMKErrorDomain code:PMKTaskError userInfo:info]); + } + }; + + #if __clang_major__ >= 9 + if (@available(macOS 10.13, *)) { + NSError *error = nil; + + if (![self launchAndReturnError:&error]) { + resolve(error); + } + } else { + [self launch]; + } + #else + [self launch]; // might @throw + #endif + }]; +} + +@end + +#endif diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.h b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.h new file mode 100644 index 000000000..71952d48c --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.h @@ -0,0 +1,79 @@ +#import +#import +#import +#import + +#define PMKURLErrorFailingURLResponseKey @"PMKURLErrorFailingURLResponseKey" +#define PMKURLErrorFailingDataKey @"PMKURLErrorFailingDataKey" +#define PMKURLErrorFailingStringKey @"PMKURLErrorFailingStringKey" +#define PMKJSONErrorJSONObjectKey @"PMKJSONErrorJSONObjectKey" + +/** + Really we shouldn’t assume JSON for (application|text)/(x-)javascript, + really we should return a String of Javascript. However in practice + for the apps we write it *will be* JSON. Thus if you actually want + a Javascript String, use the promise variant of our category functions. + */ +#define PMKHTTPURLResponseIsJSON(rsp) [@[@"application/json", @"text/json", @"text/javascript", @"application/x-javascript", @"application/javascript"] containsObject:[rsp MIMEType]] +#define PMKHTTPURLResponseIsImage(rsp) [@[@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap"] containsObject:[rsp MIMEType]] +#define PMKHTTPURLResponseIsText(rsp) [[rsp MIMEType] hasPrefix:@"text/"] + +#define PMKJSONDeserializationOptions ((NSJSONReadingOptions)(NSJSONReadingAllowFragments | NSJSONReadingMutableContainers)) + + +/** + To import the `NSURLSession` category: + + use_frameworks! + pod "PromiseKit/Foundation" + + Or `NSURLConnection` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + #import +*/ +@interface NSURLSession (PromiseKit) + +/** + Creates a task that retrieves the contents of a URL based on the + specified URL request object. + + PromiseKit automatically deserializes the raw HTTP data response into the + appropriate rich data type based on the mime type the server provides. + Thus if the response is JSON you will get the deserialized JSON response. + PromiseKit supports decoding into strings, JSON and UIImages. + + However if your server does not provide a rich content-type, you will + just get `NSData`. This is rare, but a good example we came across was + downloading files from Dropbox. + + PromiseKit goes to quite some lengths to provide good `NSError` objects + for error conditions at all stages of the HTTP to rich-data type + pipeline. We provide the following additional `userInfo` keys as + appropriate: + + - `PMKURLErrorFailingDataKey` + - `PMKURLErrorFailingStringKey` + - `PMKURLErrorFailingURLResponseKey` + + [[NSURLConnection sharedSession] promiseDataTaskWithRequest:rq].then(^(id response){ + // response is probably an NSDictionary deserialized from JSON + }); + + @param request The URL request. + + @return A promise that fulfills with three parameters: + + 1) The deserialized data response. + 2) The `NSHTTPURLResponse`. + 3) The raw `NSData` response. + + @see https://github.com/mxcl/OMGHTTPURLRQ +*/ +- (AnyPromise *)promiseDataTaskWithRequest:(NSURLRequest *)request NS_REFINED_FOR_SWIFT; + +@end diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.m b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.m new file mode 100644 index 000000000..901eb2813 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.m @@ -0,0 +1,113 @@ +#import +#import +#import +#import "NSURLSession+AnyPromise.h" +#import +#import +#import +#import +#import +#import +#import +#import + +@implementation NSURLSession (PromiseKit) + +- (AnyPromise *)promiseDataTaskWithRequest:(NSURLRequest *)rq { + return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { + [[self dataTaskWithRequest:rq completionHandler:^(NSData *data, id rsp, NSError *urlError){ + assert(![NSThread isMainThread]); + + PMKResolver fulfiller = ^(id responseObject){ + resolve(PMKManifold(responseObject, rsp, data)); + }; + PMKResolver rejecter = ^(NSError *error){ + id userInfo = error.userInfo.mutableCopy ?: [NSMutableDictionary new]; + if (data) userInfo[PMKURLErrorFailingDataKey] = data; + if (rsp) userInfo[PMKURLErrorFailingURLResponseKey] = rsp; + error = [NSError errorWithDomain:error.domain code:error.code userInfo:userInfo]; + resolve(error); + }; + + NSStringEncoding (^stringEncoding)(void) = ^NSStringEncoding{ + id encodingName = [rsp textEncodingName]; + if (encodingName) { + CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)encodingName); + if (encoding != kCFStringEncodingInvalidId) + return CFStringConvertEncodingToNSStringEncoding(encoding); + } + return NSUTF8StringEncoding; + }; + + if (urlError) { + rejecter(urlError); + } else if (![rsp isKindOfClass:[NSHTTPURLResponse class]]) { + fulfiller(data); + } else if ([rsp statusCode] < 200 || [rsp statusCode] >= 300) { + id info = @{ + NSLocalizedDescriptionKey: @"The server returned a bad HTTP response code", + NSURLErrorFailingURLStringErrorKey: rq.URL.absoluteString, + NSURLErrorFailingURLErrorKey: rq.URL + }; + id err = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadServerResponse userInfo:info]; + rejecter(err); + } else if (PMKHTTPURLResponseIsJSON(rsp)) { + // work around ever-so-common Rails workaround: https://github.com/rails/rails/issues/1742 + if ([rsp expectedContentLength] == 1 && [data isEqualToData:[NSData dataWithBytes:" " length:1]]) + return fulfiller(nil); + + NSError *err = nil; + id json = [NSJSONSerialization JSONObjectWithData:data options:PMKJSONDeserializationOptions error:&err]; + if (!err) { + fulfiller(json); + } else { + id userInfo = err.userInfo.mutableCopy; + if (data) { + NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding()]; + if (string) + userInfo[PMKURLErrorFailingStringKey] = string; + } + long long length = [rsp expectedContentLength]; + id bytes = length <= 0 ? @"" : [NSString stringWithFormat:@"%lld bytes", length]; + id fmt = @"The server claimed a %@ JSON response, but decoding failed with: %@"; + userInfo[NSLocalizedDescriptionKey] = [NSString stringWithFormat:fmt, bytes, userInfo[NSLocalizedDescriptionKey]]; + err = [NSError errorWithDomain:err.domain code:err.code userInfo:userInfo]; + rejecter(err); + } + #ifdef UIKIT_EXTERN + } else if (PMKHTTPURLResponseIsImage(rsp)) { + UIImage *image = [[UIImage alloc] initWithData:data]; + image = [[UIImage alloc] initWithCGImage:[image CGImage] scale:image.scale orientation:image.imageOrientation]; + if (image) + fulfiller(image); + else { + id info = @{ + NSLocalizedDescriptionKey: @"The server returned invalid image data", + NSURLErrorFailingURLStringErrorKey: rq.URL.absoluteString, + NSURLErrorFailingURLErrorKey: rq.URL + }; + id err = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:info]; + rejecter(err); + } + #endif + } else if (PMKHTTPURLResponseIsText(rsp)) { + id str = [[NSString alloc] initWithData:data encoding:stringEncoding()]; + if (str) + fulfiller(str); + else { + id info = @{ + NSLocalizedDescriptionKey: @"The server returned invalid string data", + NSURLErrorFailingURLStringErrorKey: rq.URL.absoluteString, + NSURLErrorFailingURLErrorKey: rq.URL + }; + id err = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:info]; + rejecter(err); + } + } else { + fulfiller(data); + } + }] resume]; + }]; +} + +@end diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+Promise.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+Promise.swift new file mode 100644 index 000000000..13259a0c0 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+Promise.swift @@ -0,0 +1,241 @@ +import Foundation +#if !PMKCocoaPods +import PromiseKit +#endif + +/** + To import the `NSURLSession` category: + + use_frameworks! + pod "PromiseKit/Foundation" + + Or `NSURLSession` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + import PromiseKit +*/ +extension URLSession { + /** + Example usage: + + firstly { + URLSession.shared.dataTask(.promise, with: rq) + }.compactMap { data, _ in + try JSONSerialization.jsonObject(with: data) as? [String: Any] + }.then { json in + //… + } + + We recommend the use of [OMGHTTPURLRQ] which allows you to construct correct REST requests: + + firstly { + let rq = OMGHTTPURLRQ.POST(url, json: parameters) + URLSession.shared.dataTask(.promise, with: rq) + }.then { data, urlResponse in + //… + } + + We provide a convenience initializer for `String` specifically for this promise: + + firstly { + URLSession.shared.dataTask(.promise, with: rq) + }.compactMap(String.init).then { string in + // decoded per the string encoding specified by the server + }.then { string in + print("response: string") + } + + Other common types can be easily decoded using compactMap also: + + firstly { + URLSession.shared.dataTask(.promise, with: rq) + }.compactMap { + UIImage(data: $0) + }.then { + self.imageView.image = $0 + } + + Though if you do decode the image this way, we recommend inflating it on a background thread + first as this will improve main thread performance when rendering the image: + + firstly { + URLSession.shared.dataTask(.promise, with: rq) + }.compactMap(on: QoS.userInitiated) { data, _ in + guard let img = UIImage(data: data) else { return nil } + _ = cgImage?.dataProvider?.data + return img + }.then { + self.imageView.image = $0 + } + + - Parameter convertible: A URL or URLRequest. + - Returns: A promise that represents the URL request. + - SeeAlso: [OMGHTTPURLRQ] + - Remark: We deliberately don’t provide a `URLRequestConvertible` for `String` because in our experience, you should be explicit with this error path to make good apps. + + [OMGHTTPURLRQ]: https://github.com/mxcl/OMGHTTPURLRQ + */ + public func dataTask(_: PMKNamespacer, with convertible: URLRequestConvertible) -> Promise<(data: Data, response: URLResponse)> { + return Promise { dataTask(with: convertible.pmkRequest, completionHandler: adapter($0)).resume() } + } + + public func uploadTask(_: PMKNamespacer, with convertible: URLRequestConvertible, from data: Data) -> Promise<(data: Data, response: URLResponse)> { + return Promise { uploadTask(with: convertible.pmkRequest, from: data, completionHandler: adapter($0)).resume() } + } + + public func uploadTask(_: PMKNamespacer, with convertible: URLRequestConvertible, fromFile file: URL) -> Promise<(data: Data, response: URLResponse)> { + return Promise { uploadTask(with: convertible.pmkRequest, fromFile: file, completionHandler: adapter($0)).resume() } + } + + /// - Remark: we force a `to` parameter because Apple deletes the downloaded file immediately after the underyling completion handler returns. + /// - Note: we do not create the destination directory for you, because we move the file with FileManager.moveItem which changes it behavior depending on the directory status of the URL you provide. So create your own directory first! + public func downloadTask(_: PMKNamespacer, with convertible: URLRequestConvertible, to saveLocation: URL) -> Promise<(saveLocation: URL, response: URLResponse)> { + return Promise { seal in + downloadTask(with: convertible.pmkRequest, completionHandler: { tmp, rsp, err in + if let error = err { + seal.reject(error) + } else if let rsp = rsp, let tmp = tmp { + do { + try FileManager.default.moveItem(at: tmp, to: saveLocation) + seal.fulfill((saveLocation, rsp)) + } catch { + seal.reject(error) + } + } else { + seal.reject(PMKError.invalidCallingConvention) + } + }).resume() + } + } +} + + +public protocol URLRequestConvertible { + var pmkRequest: URLRequest { get } +} +extension URLRequest: URLRequestConvertible { + public var pmkRequest: URLRequest { return self } +} +extension URL: URLRequestConvertible { + public var pmkRequest: URLRequest { return URLRequest(url: self) } +} + + +#if !os(Linux) +public extension String { + /** + - Remark: useful when converting a `URLSession` response into a `String` + + firstly { + URLSession.shared.dataTask(.promise, with: rq) + }.map(String.init).done { + print($0) + } + */ + init?(data: Data, urlResponse: URLResponse) { + guard let str = String(bytes: data, encoding: urlResponse.stringEncoding ?? .utf8) else { + return nil + } + self.init(str) + } +} + +private extension URLResponse { + var stringEncoding: String.Encoding? { + guard let encodingName = textEncodingName else { return nil } + let encoding = CFStringConvertIANACharSetNameToEncoding(encodingName as CFString) + guard encoding != kCFStringEncodingInvalidId else { return nil } + return String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(encoding)) + } +} +#endif + +private func adapter(_ seal: Resolver<(data: T, response: U)>) -> (T?, U?, Error?) -> Void { + return { t, u, e in + if let t = t, let u = u { + seal.fulfill((t, u)) + } else if let e = e { + seal.reject(e) + } else { + seal.reject(PMKError.invalidCallingConvention) + } + } +} + + +#if swift(>=3.1) +public enum PMKHTTPError: Error, LocalizedError, CustomStringConvertible { + case badStatusCode(Int, Data, HTTPURLResponse) + + public var errorDescription: String? { + func url(_ rsp: URLResponse) -> String { + return rsp.url?.absoluteString ?? "nil" + } + switch self { + case .badStatusCode(401, _, let response): + return "Unauthorized (\(url(response))" + case .badStatusCode(let code, _, let response): + return "Invalid HTTP response (\(code)) for \(url(response))." + } + } + +#if swift(>=4.0) + public func decodeResponse(_ t: T.Type, decoder: JSONDecoder = JSONDecoder()) -> T? { + switch self { + case .badStatusCode(_, let data, _): + return try? decoder.decode(t, from: data) + } + } +#endif + + //TODO rename responseJSON + public var jsonDictionary: Any? { + switch self { + case .badStatusCode(_, let data, _): + return try? JSONSerialization.jsonObject(with: data) + } + } + + var responseBodyString: String? { + switch self { + case .badStatusCode(_, let data, _): + return String(data: data, encoding: .utf8) + } + } + + public var failureReason: String? { + return responseBodyString + } + + public var description: String { + switch self { + case .badStatusCode(let code, let data, let response): + var dict: [String: Any] = [ + "Status Code": code, + "Body": String(data: data, encoding: .utf8) ?? "\(data.count) bytes" + ] + dict["URL"] = response.url + dict["Headers"] = response.allHeaderFields + return " \(NSDictionary(dictionary: dict))" // as NSDictionary makes the output look like NSHTTPURLResponse looks + } + } +} + +public extension Promise where T == (data: Data, response: URLResponse) { + func validate() -> Promise { + return map { + guard let response = $0.response as? HTTPURLResponse else { return $0 } + switch response.statusCode { + case 200..<300: + return $0 + case let code: + throw PMKHTTPError.badStatusCode(code, $0.data, response) + } + } + } +} +#endif diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/PMKFoundation.h b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/PMKFoundation.h new file mode 100644 index 000000000..8796c0d11 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/PMKFoundation.h @@ -0,0 +1,3 @@ +#import "NSNotificationCenter+AnyPromise.h" +#import "NSURLSession+AnyPromise.h" +#import "NSTask+AnyPromise.h" diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/Process+Promise.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/Process+Promise.swift new file mode 100644 index 000000000..03cab3cfe --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/Process+Promise.swift @@ -0,0 +1,190 @@ +import Foundation +#if !PMKCocoaPods +import PromiseKit +#endif + +#if os(macOS) + +/** + To import the `Process` category: + + use_frameworks! + pod "PromiseKit/Foundation" + + Or `Process` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + import PromiseKit + */ +extension Process { + /** + Launches the receiver and resolves when it exits. + + let proc = Process() + proc.launchPath = "/bin/ls" + proc.arguments = ["/bin"] + proc.launch(.promise).compactMap { std in + String(data: std.out.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) + }.then { stdout in + print(str) + } + */ + public func launch(_: PMKNamespacer) -> Promise<(out: Pipe, err: Pipe)> { + let (stdout, stderr) = (Pipe(), Pipe()) + + do { + standardOutput = stdout + standardError = stderr + + #if swift(>=4.0) + if #available(OSX 10.13, *) { + try run() + } else if let path = launchPath, FileManager.default.isExecutableFile(atPath: path) { + launch() + } else { + throw PMKError.notExecutable(launchPath) + } + #else + guard let path = launchPath, FileManager.default.isExecutableFile(atPath: path) else { + throw PMKError.notExecutable(launchPath) + } + launch() + #endif + } catch { + return Promise(error: error) + } + + + var q: DispatchQueue { + if #available(macOS 10.10, iOS 8.0, tvOS 9.0, watchOS 2.0, *) { + return DispatchQueue.global(qos: .default) + } else { + return DispatchQueue.global(priority: .default) + } + } + + return Promise { seal in + q.async { + self.waitUntilExit() + + guard self.terminationReason == .exit, self.terminationStatus == 0 else { + let stdoutData = try? self.readDataFromPipe(stdout) + let stderrData = try? self.readDataFromPipe(stderr) + + let stdoutString = stdoutData.flatMap { (data: Data) -> String? in String(data: data, encoding: .utf8) } + let stderrString = stderrData.flatMap { (data: Data) -> String? in String(data: data, encoding: .utf8) } + + return seal.reject(PMKError.execution(process: self, standardOutput: stdoutString, standardError: stderrString)) + } + seal.fulfill((stdout, stderr)) + } + } + } + + private func readDataFromPipe(_ pipe: Pipe) throws -> Data { + let handle = pipe.fileHandleForReading + defer { handle.closeFile() } + + // Someday, NSFileHandle will probably be updated with throwing equivalents to its read and write methods, + // as NSTask has, to avoid raising exceptions and crashing the app. + // Unfortunately that day has not yet come, so use the underlying BSD calls for now. + + let fd = handle.fileDescriptor + + let bufsize = 1024 * 8 + let buf = UnsafeMutablePointer.allocate(capacity: bufsize) + + #if swift(>=4.1) + defer { buf.deallocate() } + #else + defer { buf.deallocate(capacity: bufsize) } + #endif + + var data = Data() + + while true { + let bytesRead = read(fd, buf, bufsize) + + if bytesRead == 0 { + break + } + + if bytesRead < 0 { + throw POSIXError.Code(rawValue: errno).map { POSIXError($0) } ?? CocoaError(.fileReadUnknown) + } + + data.append(buf, count: bytesRead) + } + + return data + } + + /** + The error generated by PromiseKit’s `Process` extension + */ + public enum PMKError { + /// NOT AVAILABLE ON 10.13 and above because Apple provide this error handling themselves + case notExecutable(String?) + case execution(process: Process, standardOutput: String?, standardError: String?) + } +} + + +extension Process.PMKError: LocalizedError { + public var errorDescription: String? { + switch self { + case .notExecutable(let path?): + return "File not executable: \(path)" + case .notExecutable(nil): + return "No launch path specified" + case .execution(process: let task, standardOutput: _, standardError: _): + return "Failed executing: `\(task)` (\(task.terminationStatus))." + } + } +} + +public extension Promise where T == (out: Pipe, err: Pipe) { + func print() -> Promise { + return tap { result in + switch result { + case .fulfilled(let raw): + let stdout = String(data: raw.out.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) + let stderr = String(data: raw.err.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) + Swift.print("stdout: `\(stdout ?? "")`") + Swift.print("stderr: `\(stderr ?? "")`") + case .rejected(let err): + Swift.print(err) + } + } + } +} + +extension Process { + /// Provided because Foundation’s is USELESS + open override var description: String { + let launchPath = self.launchPath ?? "$0" + var args = [launchPath] + arguments.flatMap{ args += $0 } + return args.map { arg in + let contains: Bool + #if swift(>=3.2) + contains = arg.contains(" ") + #else + contains = arg.characters.contains(" ") + #endif + if contains { + return "\"\(arg)\"" + } else if arg == "" { + return "\"\"" + } else { + return arg + } + }.joined(separator: " ") + } +} + +#endif diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/afterlife.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/afterlife.swift new file mode 100644 index 000000000..232c8da90 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/Foundation/Sources/afterlife.swift @@ -0,0 +1,26 @@ +import Foundation +#if !PMKCocoaPods +import PromiseKit +#endif + +/** + - Returns: A promise that resolves when the provided object deallocates + - Important: The promise is not guarenteed to resolve immediately when the provided object is deallocated. So you cannot write code that depends on exact timing. + */ +public func after(life object: NSObject) -> Guarantee { + var reaper = objc_getAssociatedObject(object, &handle) as? GrimReaper + if reaper == nil { + reaper = GrimReaper() + objc_setAssociatedObject(object, &handle, reaper, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + return reaper!.promise +} + +private var handle: UInt8 = 0 + +private class GrimReaper: NSObject { + deinit { + fulfill(()) + } + let (promise, fulfill) = Guarantee.pending() +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/PMKUIKit.h b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/PMKUIKit.h new file mode 100644 index 000000000..75cbf90f0 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/PMKUIKit.h @@ -0,0 +1,8 @@ +#import "UIView+AnyPromise.h" +#import "UIViewController+AnyPromise.h" + +typedef NS_OPTIONS(NSInteger, PMKAnimationOptions) { + PMKAnimationOptionsNone = 1 << 0, + PMKAnimationOptionsAppear = 1 << 1, + PMKAnimationOptionsDisappear = 1 << 2, +}; diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.h b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.h new file mode 100644 index 000000000..0a19cd6fe --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.h @@ -0,0 +1,80 @@ +#import +#import + +// Created by Masafumi Yoshida on 2014/07/11. +// Copyright (c) 2014年 DeNA. All rights reserved. + +/** + To import the `UIView` category: + + use_frameworks! + pod "PromiseKit/UIKit" + + Or `UIKit` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + @import PromiseKit; +*/ +@interface UIView (PromiseKit) + +/** + Animate changes to one or more views using the specified duration. + + @param duration The total duration of the animations, measured in + seconds. If you specify a negative value or 0, the changes are made + without animating them. + + @param animations A block object containing the changes to commit to the + views. + + @return A promise that fulfills with a boolean NSNumber indicating + whether or not the animations actually finished. +*/ ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations NS_REFINED_FOR_SWIFT; + +/** + Animate changes to one or more views using the specified duration, delay, + options, and completion handler. + + @param duration The total duration of the animations, measured in + seconds. If you specify a negative value or 0, the changes are made + without animating them. + + @param delay The amount of time (measured in seconds) to wait before + beginning the animations. Specify a value of 0 to begin the animations + immediately. + + @param options A mask of options indicating how you want to perform the + animations. For a list of valid constants, see UIViewAnimationOptions. + + @param animations A block object containing the changes to commit to the + views. + + @return A promise that fulfills with a boolean NSNumber indicating + whether or not the animations actually finished. +*/ ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void (^)(void))animations NS_REFINED_FOR_SWIFT; + +/** + Performs a view animation using a timing curve corresponding to the + motion of a physical spring. + + @return A promise that fulfills with a boolean NSNumber indicating + whether or not the animations actually finished. +*/ ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay usingSpringWithDamping:(CGFloat)dampingRatio initialSpringVelocity:(CGFloat)velocity options:(UIViewAnimationOptions)options animations:(void (^)(void))animations NS_REFINED_FOR_SWIFT; + +/** + Creates an animation block object that can be used to set up + keyframe-based animations for the current view. + + @return A promise that fulfills with a boolean NSNumber indicating + whether or not the animations actually finished. +*/ ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewKeyframeAnimationOptions)options keyframeAnimations:(void (^)(void))animations NS_REFINED_FOR_SWIFT; + +@end diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.m b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.m new file mode 100644 index 000000000..04ee94035 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.m @@ -0,0 +1,64 @@ +// +// UIView+PromiseKit_UIAnimation.m +// YahooDenaStudy +// +// Created by Masafumi Yoshida on 2014/07/11. +// Copyright (c) 2014年 DeNA. All rights reserved. +// + +#import +#import "UIView+AnyPromise.h" + + +#define CopyPasta \ + NSAssert([NSThread isMainThread], @"UIKit animation must be performed on the main thread"); \ + \ + if (![NSThread isMainThread]) { \ + id error = [NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:@{NSLocalizedDescriptionKey: @"Animation was attempted on a background thread"}]; \ + return [AnyPromise promiseWithValue:error]; \ + } \ + \ + PMKResolver resolve = nil; \ + AnyPromise *promise = [[AnyPromise alloc] initWithResolver:&resolve]; + + +@implementation UIView (PromiseKit) + ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations { + return [self promiseWithDuration:duration delay:0 options:0 animations:animations]; +} + ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void(^)(void))animations +{ + CopyPasta; + + [UIView animateWithDuration:duration delay:delay options:options animations:animations completion:^(BOOL finished) { + resolve(@(finished)); + }]; + + return promise; +} + ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay usingSpringWithDamping:(CGFloat)dampingRatio initialSpringVelocity:(CGFloat)velocity options:(UIViewAnimationOptions)options animations:(void(^)(void))animations +{ + CopyPasta; + + [UIView animateWithDuration:duration delay:delay usingSpringWithDamping:dampingRatio initialSpringVelocity:velocity options:options animations:animations completion:^(BOOL finished) { + resolve(@(finished)); + }]; + + return promise; +} + ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewKeyframeAnimationOptions)options keyframeAnimations:(void(^)(void))animations +{ + CopyPasta; + + [UIView animateKeyframesWithDuration:duration delay:delay options:options animations:animations completion:^(BOOL finished) { + resolve(@(finished)); + }]; + + return promise; +} + +@end diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+Promise.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+Promise.swift new file mode 100644 index 000000000..1bbb8c649 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+Promise.swift @@ -0,0 +1,115 @@ +import UIKit.UIView +#if !PMKCocoaPods +import PromiseKit +#endif + +/** + To import the `UIView` category: + + use_frameworks! + pod "PromiseKit/UIKit" + + Or `UIKit` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + import PromiseKit +*/ +public extension UIView { +#if swift(>=4.2) +/** + Animate changes to one or more views using the specified duration, delay, + options, and completion handler. + + - Parameter duration: The total duration of the animations, measured in + seconds. If you specify a negative value or 0, the changes are made + without animating them. + + - Parameter delay: The amount of time (measured in seconds) to wait before + beginning the animations. Specify a value of 0 to begin the animations + immediately. + + - Parameter options: A mask of options indicating how you want to perform the + animations. For a list of valid constants, see UIViewAnimationOptions. + + - Parameter animations: A block object containing the changes to commit to the + views. + + - Returns: A promise that fulfills with a boolean NSNumber indicating + whether or not the animations actually finished. + */ + @discardableResult + static func animate(_: PMKNamespacer, duration: TimeInterval, delay: TimeInterval = 0, options: UIView.AnimationOptions = [], animations: @escaping () -> Void) -> Guarantee { + return Guarantee { animate(withDuration: duration, delay: delay, options: options, animations: animations, completion: $0) } + } + + @discardableResult + static func animate(_: PMKNamespacer, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping damping: CGFloat, initialSpringVelocity: CGFloat, options: UIView.AnimationOptions = [], animations: @escaping () -> Void) -> Guarantee { + return Guarantee { animate(withDuration: duration, delay: delay, usingSpringWithDamping: damping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: $0) } + } + + @discardableResult + static func transition(_: PMKNamespacer, with view: UIView, duration: TimeInterval, options: UIView.AnimationOptions = [], animations: (() -> Void)?) -> Guarantee { + return Guarantee { transition(with: view, duration: duration, options: options, animations: animations, completion: $0) } + } + + @discardableResult + static func transition(_: PMKNamespacer, from: UIView, to: UIView, duration: TimeInterval, options: UIView.AnimationOptions = []) -> Guarantee { + return Guarantee { transition(from: from, to: to, duration: duration, options: options, completion: $0) } + } + + @discardableResult + static func perform(_: PMKNamespacer, animation: UIView.SystemAnimation, on views: [UIView], options: UIView.AnimationOptions = [], animations: (() -> Void)?) -> Guarantee { + return Guarantee { perform(animation, on: views, options: options, animations: animations, completion: $0) } + } +#else + /** + Animate changes to one or more views using the specified duration, delay, + options, and completion handler. + + - Parameter duration: The total duration of the animations, measured in + seconds. If you specify a negative value or 0, the changes are made + without animating them. + + - Parameter delay: The amount of time (measured in seconds) to wait before + beginning the animations. Specify a value of 0 to begin the animations + immediately. + + - Parameter options: A mask of options indicating how you want to perform the + animations. For a list of valid constants, see UIViewAnimationOptions. + + - Parameter animations: A block object containing the changes to commit to the + views. + + - Returns: A promise that fulfills with a boolean NSNumber indicating + whether or not the animations actually finished. + */ + @discardableResult + static func animate(_: PMKNamespacer, duration: TimeInterval, delay: TimeInterval = 0, options: UIViewAnimationOptions = [], animations: @escaping () -> Void) -> Guarantee { + return Guarantee { animate(withDuration: duration, delay: delay, options: options, animations: animations, completion: $0) } + } + + @discardableResult + static func animate(_: PMKNamespacer, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping damping: CGFloat, initialSpringVelocity: CGFloat, options: UIViewAnimationOptions = [], animations: @escaping () -> Void) -> Guarantee { + return Guarantee { animate(withDuration: duration, delay: delay, usingSpringWithDamping: damping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: $0) } + } + + @discardableResult + static func transition(_: PMKNamespacer, with view: UIView, duration: TimeInterval, options: UIViewAnimationOptions = [], animations: (() -> Void)?) -> Guarantee { + return Guarantee { transition(with: view, duration: duration, options: options, animations: animations, completion: $0) } + } + + @discardableResult + static func transition(_: PMKNamespacer, from: UIView, to: UIView, duration: TimeInterval, options: UIViewAnimationOptions = []) -> Guarantee { + return Guarantee { transition(from: from, to: to, duration: duration, options: options, completion: $0) } + } + + @discardableResult + static func perform(_: PMKNamespacer, animation: UISystemAnimation, on views: [UIView], options: UIViewAnimationOptions = [], animations: (() -> Void)?) -> Guarantee { + return Guarantee { perform(animation, on: views, options: options, animations: animations, completion: $0) } + } +#endif +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.h b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.h new file mode 100644 index 000000000..0e60ca9e7 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.h @@ -0,0 +1,71 @@ +#import +#import + +/** + To import the `UIViewController` category: + + use_frameworks! + pod "PromiseKit/UIKit" + + Or `UIKit` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + @import PromiseKit; +*/ +@interface UIViewController (PromiseKit) + +/** + Presents a view controller modally. + + If the view controller is one of the following: + + - MFMailComposeViewController + - MFMessageComposeViewController + - UIImagePickerController + - SLComposeViewController + + Then PromiseKit presents the view controller returning a promise that is + resolved as per the documentation for those classes. Eg. if you present a + `UIImagePickerController` the view controller will be presented for you + and the returned promise will resolve with the media the user selected. + + [self promiseViewController:[MFMailComposeViewController new] animated:YES completion:nil].then(^{ + //… + }); + + Otherwise PromiseKit expects your view controller to implement a + `promise` property. This promise will be returned from this method and + presentation and dismissal of the presented view controller will be + managed for you. + + \@interface MyViewController: UIViewController + @property (readonly) AnyPromise *promise; + @end + + @implementation MyViewController { + PMKResolver resolve; + } + + - (void)viewDidLoad { + _promise = [[AnyPromise alloc] initWithResolver:&resolve]; + } + + - (void)later { + resolve(@"some fulfilled value"); + } + + @end + + [self promiseViewController:[MyViewController new] aniamted:YES completion:nil].then(^(id value){ + // value == @"some fulfilled value" + }); + + @return A promise that can be resolved by the presented view controller. +*/ +- (AnyPromise *)promiseViewController:(UIViewController *)vc animated:(BOOL)animated completion:(void (^)(void))block NS_REFINED_FOR_SWIFT; + +@end diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.m b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.m new file mode 100644 index 000000000..5231e55bf --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.m @@ -0,0 +1,140 @@ +#import +#import "UIViewController+AnyPromise.h" +#import + +#if PMKImagePickerController +#import +#endif + +@interface PMKGenericDelegate : NSObject { +@public + PMKResolver resolve; +} ++ (instancetype)delegateWithPromise:(AnyPromise **)promise; +@end + +@interface UIViewController () +- (AnyPromise*) promise; +@end + +@implementation UIViewController (PromiseKit) + +- (AnyPromise *)promiseViewController:(UIViewController *)vc animated:(BOOL)animated completion:(void (^)(void))block { + __kindof UIViewController *vc2present = vc; + AnyPromise *promise = nil; + + if ([vc isKindOfClass:NSClassFromString(@"MFMailComposeViewController")]) { + PMKGenericDelegate *delegate = [PMKGenericDelegate delegateWithPromise:&promise]; + [vc setValue:delegate forKey:@"mailComposeDelegate"]; + } + else if ([vc isKindOfClass:NSClassFromString(@"MFMessageComposeViewController")]) { + PMKGenericDelegate *delegate = [PMKGenericDelegate delegateWithPromise:&promise]; + [vc setValue:delegate forKey:@"messageComposeDelegate"]; + } +#ifdef PMKImagePickerController + else if ([vc isKindOfClass:[UIImagePickerController class]]) { + PMKGenericDelegate *delegate = [PMKGenericDelegate delegateWithPromise:&promise]; + [vc setValue:delegate forKey:@"delegate"]; + } +#endif + else if ([vc isKindOfClass:NSClassFromString(@"SLComposeViewController")]) { + PMKResolver resolve; + promise = [[AnyPromise alloc] initWithResolver:&resolve]; + [vc setValue:^(NSInteger result){ + if (result == 0) { + resolve([NSError errorWithDomain:NSCocoaErrorDomain code:NSUserCancelledError userInfo:nil]); + } else { + resolve(@(result)); + } + } forKey:@"completionHandler"]; + } + else if ([vc isKindOfClass:[UINavigationController class]]) + vc = [(id)vc viewControllers].firstObject; + + if (!vc) { + id userInfo = @{NSLocalizedDescriptionKey: @"nil or effective nil passed to promiseViewController"}; + id err = [NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:userInfo]; + return [AnyPromise promiseWithValue:err]; + } + + if (!promise) { + if (![vc respondsToSelector:@selector(promise)]) { + id userInfo = @{NSLocalizedDescriptionKey: @"ViewController is not promisable"}; + id err = [NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:userInfo]; + return [AnyPromise promiseWithValue:err]; + } + + promise = [vc valueForKey:@"promise"]; + + if (![promise isKindOfClass:[AnyPromise class]]) { + id userInfo = @{NSLocalizedDescriptionKey: @"The promise property is nil or not of type AnyPromise"}; + id err = [NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:userInfo]; + return [AnyPromise promiseWithValue:err]; + } + } + + if (!promise.pending) + return promise; + + [self presentViewController:vc2present animated:animated completion:block]; + + promise.ensure(^{ + [vc2present.presentingViewController dismissViewControllerAnimated:animated completion:nil]; + }); + + return promise; +} + +@end + + + +@implementation PMKGenericDelegate { + id retainCycle; +} + ++ (instancetype)delegateWithPromise:(AnyPromise **)promise; { + PMKGenericDelegate *d = [PMKGenericDelegate new]; + d->retainCycle = d; + *promise = [[AnyPromise alloc] initWithResolver:&d->resolve]; + return d; +} + +- (void)mailComposeController:(id)controller didFinishWithResult:(int)result error:(NSError *)error { + if (error != nil) { + resolve(error); + } else if (result == 0) { + resolve([NSError errorWithDomain:NSCocoaErrorDomain code:NSUserCancelledError userInfo:nil]); + } else { + resolve(@(result)); + } + retainCycle = nil; +} + +- (void)messageComposeViewController:(id)controller didFinishWithResult:(int)result { + if (result == 2) { + id userInfo = @{NSLocalizedDescriptionKey: @"The attempt to save or send the message was unsuccessful."}; + id error = [NSError errorWithDomain:PMKErrorDomain code:PMKOperationFailed userInfo:userInfo]; + resolve(error); + } else { + resolve(@(result)); + } + retainCycle = nil; +} + +#ifdef PMKImagePickerController + +- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { + id img = info[UIImagePickerControllerEditedImage] ?: info[UIImagePickerControllerOriginalImage]; + resolve(PMKManifold(img, info)); + retainCycle = nil; +} + +- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { + resolve([NSError errorWithDomain:NSCocoaErrorDomain code:NSUserCancelledError userInfo:nil]); + retainCycle = nil; +} + +#endif + +@end diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewPropertyAnimator+Promise.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewPropertyAnimator+Promise.swift new file mode 100644 index 000000000..34ee14084 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewPropertyAnimator+Promise.swift @@ -0,0 +1,14 @@ +#if !PMKCocoaPods +import PromiseKit +#endif +import UIKit + +@available(iOS 10, tvOS 10, *) +public extension UIViewPropertyAnimator { + func startAnimation(_: PMKNamespacer) -> Guarantee { + return Guarantee { + addCompletion($0) + startAnimation() + } + } +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/LICENSE b/Example/Web3supportBrowser/Pods/PromiseKit/LICENSE new file mode 100644 index 000000000..50f758c89 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/LICENSE @@ -0,0 +1,20 @@ +Copyright 2016-present, Max Howell; mxcl@me.com + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/README.md b/Example/Web3supportBrowser/Pods/PromiseKit/README.md new file mode 100644 index 000000000..c06b464fb --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/README.md @@ -0,0 +1,207 @@ +![PromiseKit](../gh-pages/public/img/logo-tight.png) + +[![badge-pod][]][cocoapods] ![badge-languages][] ![badge-pms][] ![badge-platforms][] [![badge-travis][]][travis] + +--- + +Promises simplify asynchronous programming, freeing you up to focus on the more +important things. They are easy to learn, easy to master and result in clearer, +more readable code. Your co-workers will thank you. + +```swift +UIApplication.shared.isNetworkActivityIndicatorVisible = true + +let fetchImage = URLSession.shared.dataTask(.promise, with: url).compactMap{ UIImage(data: $0.data) } +let fetchLocation = CLLocationManager.requestLocation().lastValue + +firstly { + when(fulfilled: fetchImage, fetchLocation) +}.done { image, location in + self.imageView.image = image + self.label.text = "\(location)" +}.ensure { + UIApplication.shared.isNetworkActivityIndicatorVisible = false +}.catch { error in + self.show(UIAlertController(for: error), sender: self) +} +``` + +PromiseKit is a thoughtful and complete implementation of promises for any +platform that has a `swiftc`. It has *excellent* Objective-C bridging and +*delightful* specializations for iOS, macOS, tvOS and watchOS. It is a top-100 +pod used in many of the most popular apps in the world. + +[![codecov](https://codecov.io/gh/mxcl/PromiseKit/branch/master/graph/badge.svg)](https://codecov.io/gh/mxcl/PromiseKit) + +# PromiseKit 7 Alpha + +We are testing PromiseKit 7 alpha, it is Swift 5 only. It is tagged and thus +importable in all package managers. + +# PromiseKit 6 + +[Release notes and migration guide][PMK6]. + +# Quick Start + +In your [Podfile]: + +```ruby +use_frameworks! + +target "Change Me!" do + pod "PromiseKit", "~> 6.8" +end +``` + +> The above gives an Xcode warning? See our [Installation Guide]. + +PromiseKit 6, 5 and 4 support Xcode 8.3, 9.x and 10.0; Swift 3.1, +3.2, 3.3, 3.4, 4.0, 4.1, 4.2, 4.3 and 5.0 (development snapshots); iOS, macOS, +tvOS, watchOS, Linux and Android; CocoaPods, Carthage and SwiftPM; +([CI Matrix](https://travis-ci.org/mxcl/PromiseKit)). + +For Carthage, SwiftPM, Accio, etc., or for instructions when using older Swifts or Xcodes, see our [Installation Guide]. We recommend +[Carthage](https://github.com/Carthage/Carthage) or +[Accio](https://github.com/JamitLabs/Accio). + +# Professionally Supported PromiseKit is Now Available + +TideLift gives software development teams a single source for purchasing +and maintaining their software, with professional grade assurances from +the experts who know it best, while seamlessly integrating with existing +tools. + +[Get Professional Support for PromiseKit with TideLift](https://tidelift.com/subscription/pkg/cocoapods-promisekit?utm_source=cocoapods-promisekit&utm_medium=referral&utm_campaign=readme). + +# PromiseKit is Thousands of Hours of Work + +Hey there, I’m Max Howell. I’m a prolific producer of open source software and +probably you already use some of it (I created [`brew`]). I work full-time on +open source and it’s hard; currently *I earn less than minimum wage*. Please +help me continue my work, I appreciate it 🙏🏻 + + + + + +[Other ways to say thanks](http://mxcl.dev/#donate). + +[`brew`]: https://brew.sh + +# Documentation + +* Handbook + * [Getting Started](Documentation/GettingStarted.md) + * [Promises: Common Patterns](Documentation/CommonPatterns.md) + * [Frequently Asked Questions](Documentation/FAQ.md) +* Manual + * [Installation Guide](Documentation/Installation.md) + * [Objective-C Guide](Documentation/ObjectiveC.md) + * [Troubleshooting](Documentation/Troubleshooting.md) (e.g., solutions to common compile errors) + * [Appendix](Documentation/Appendix.md) +* [API Reference](https://mxcl.dev/PromiseKit/reference/v6/Classes/Promise.html) + +# Extensions + +Promises are only as useful as the asynchronous tasks they represent. Thus, we +have converted (almost) all of Apple’s APIs to promises. The default CocoaPod +provides Promises and the extensions for Foundation and UIKit. The other +extensions are available by specifying additional subspecs in your `Podfile`, +e.g.: + +```ruby +pod "PromiseKit/MapKit" # MKDirections().calculate().then { /*…*/ } +pod "PromiseKit/CoreLocation" # CLLocationManager.requestLocation().then { /*…*/ } +``` + +All our extensions are separate repositories at the [PromiseKit organization]. + +## I don't want the extensions! + +Then don’t have them: + +```ruby +pod "PromiseKit/CorePromise", "~> 6.8" +``` + +> *Note:* Carthage installations come with no extensions by default. + +## Choose Your Networking Library + +Promise chains commonly start with a network operation. Thus, we offer +extensions for `URLSession`: + +```swift +// pod 'PromiseKit/Foundation' # https://github.com/PromiseKit/Foundation + +firstly { + URLSession.shared.dataTask(.promise, with: try makeUrlRequest()).validate() + // ^^ we provide `.validate()` so that eg. 404s get converted to errors +}.map { + try JSONDecoder().decode(Foo.self, with: $0.data) +}.done { foo in + //… +}.catch { error in + //… +} + +func makeUrlRequest() throws -> URLRequest { + var rq = URLRequest(url: url) + rq.httpMethod = "POST" + rq.addValue("application/json", forHTTPHeaderField: "Content-Type") + rq.addValue("application/json", forHTTPHeaderField: "Accept") + rq.httpBody = try JSONEncoder().encode(obj) + return rq +} +``` + +And [Alamofire]: + +```swift +// pod 'PromiseKit/Alamofire' # https://github.com/PromiseKit/Alamofire- + +firstly { + Alamofire + .request("http://example.com", method: .post, parameters: params) + .responseDecodable(Foo.self) +}.done { foo in + //… +}.catch { error in + //… +} +``` + +Nowadays, considering that: + +* We almost always POST JSON +* We now have `JSONDecoder` +* PromiseKit now has `map` and other functional primitives +* PromiseKit (like Alamofire, but not raw-`URLSession`) also defaults to having + callbacks go to the main thread + +We recommend vanilla `URLSession`. It uses fewer black boxes and sticks closer to the metal. Alamofire was essential until the three bullet points above +became true, but nowadays it isn’t really necessary. + +# Support + +Please check our [Troubleshooting Guide](Documentation/Troubleshooting.md), and +if after that you still have a question, ask at our [Gitter chat channel] or on [our bug tracker]. + + +[badge-pod]: https://img.shields.io/cocoapods/v/PromiseKit.svg?label=version +[badge-pms]: https://img.shields.io/badge/supports-CocoaPods%20%7C%20Carthage%20%7C%20Accio%20%7C%20SwiftPM-green.svg +[badge-languages]: https://img.shields.io/badge/languages-Swift%20%7C%20ObjC-orange.svg +[badge-platforms]: https://img.shields.io/badge/platforms-macOS%20%7C%20iOS%20%7C%20watchOS%20%7C%20tvOS%20%7C%20Linux-lightgrey.svg +[badge-mit]: https://img.shields.io/badge/license-MIT-blue.svg +[OMGHTTPURLRQ]: https://github.com/PromiseKit/OMGHTTPURLRQ +[Alamofire]: http://github.com/PromiseKit/Alamofire- +[PromiseKit organization]: https://github.com/PromiseKit +[Gitter chat channel]: https://gitter.im/mxcl/PromiseKit +[our bug tracker]: https://github.com/mxcl/PromiseKit/issues/new +[Podfile]: https://guides.cocoapods.org/syntax/podfile.html +[PMK6]: http://mxcl.dev/PromiseKit/news/2018/02/PromiseKit-6.0-Released/ +[Installation Guide]: Documentation/Installation.md +[badge-travis]: https://travis-ci.org/mxcl/PromiseKit.svg?branch=master +[travis]: https://travis-ci.org/mxcl/PromiseKit +[cocoapods]: https://cocoapods.org/pods/PromiseKit diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/AnyPromise+Private.h b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/AnyPromise+Private.h new file mode 100644 index 000000000..cd28c4183 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/AnyPromise+Private.h @@ -0,0 +1,32 @@ +@import Foundation.NSError; +@import Foundation.NSPointerArray; + +#if TARGET_OS_IPHONE + #define NSPointerArrayMake(N) ({ \ + NSPointerArray *aa = [NSPointerArray strongObjectsPointerArray]; \ + aa.count = N; \ + aa; \ + }) +#else + static inline NSPointerArray * __nonnull NSPointerArrayMake(NSUInteger count) { + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wdeprecated-declarations" + NSPointerArray *aa = [[NSPointerArray class] respondsToSelector:@selector(strongObjectsPointerArray)] + ? [NSPointerArray strongObjectsPointerArray] + : [NSPointerArray pointerArrayWithStrongObjects]; + #pragma clang diagnostic pop + aa.count = count; + return aa; + } +#endif + +#define IsError(o) [o isKindOfClass:[NSError class]] +#define IsPromise(o) [o isKindOfClass:[AnyPromise class]] + +#import "AnyPromise.h" + +@class PMKArray; + +@interface AnyPromise () +- (void)__pipe:(void(^ __nonnull)(__nullable id))block NS_REFINED_FOR_SWIFT; +@end diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/AnyPromise.h b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/AnyPromise.h new file mode 100644 index 000000000..fd1ad3a9b --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/AnyPromise.h @@ -0,0 +1,299 @@ +#import +#import +#import "fwd.h" + +/// INTERNAL DO NOT USE +@class __AnyPromise; + +/// Provided to simplify some usage sites +typedef void (^PMKResolver)(id __nullable) NS_REFINED_FOR_SWIFT; + + +/// An Objective-C implementation of the promise pattern. +@interface AnyPromise: NSObject + +/** + Create a new promise that resolves with the provided block. + + Use this method when wrapping asynchronous code that does *not* use promises so that this code can be used in promise chains. + + If `resolve` is called with an `NSError` object, the promise is rejected, otherwise the promise is fulfilled. + + Don’t use this method if you already have promises! Instead, just return your promise. + + Should you need to fulfill a promise but have no sensical value to use: your promise is a `void` promise: fulfill with `nil`. + + The block you pass is executed immediately on the calling thread. + + - Parameter block: The provided block is immediately executed, inside the block call `resolve` to resolve this promise and cause any attached handlers to execute. If you are wrapping a delegate-based system, we recommend instead to use: initWithResolver: + - Returns: A new promise. + - Warning: Resolving a promise with `nil` fulfills it. + - SeeAlso: https://github.com/mxcl/PromiseKit/blob/master/Documentation/GettingStarted.md#making-promises + - SeeAlso: https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#wrapping-delegate-systems + */ ++ (instancetype __nonnull)promiseWithResolverBlock:(void (^ __nonnull)(__nonnull PMKResolver))resolveBlock NS_REFINED_FOR_SWIFT; + + +/// INTERNAL DO NOT USE +- (instancetype __nonnull)initWith__D:(__AnyPromise * __nonnull)d; + +/** + Creates a resolved promise. + + When developing your own promise systems, it is occasionally useful to be able to return an already resolved promise. + + - Parameter value: The value with which to resolve this promise. Passing an `NSError` will cause the promise to be rejected, passing an AnyPromise will return a new AnyPromise bound to that promise, otherwise the promise will be fulfilled with the value passed. + - Returns: A resolved promise. + */ ++ (instancetype __nonnull)promiseWithValue:(__nullable id)value NS_REFINED_FOR_SWIFT; + +/** + The value of the asynchronous task this promise represents. + + A promise has `nil` value if the asynchronous task it represents has not finished. If the value is `nil` the promise is still `pending`. + + - Warning: *Note* Our Swift variant’s value property returns nil if the promise is rejected where AnyPromise will return the error object. This fits with the pattern where AnyPromise is not strictly typed and is more dynamic, but you should be aware of the distinction. + + - Note: If the AnyPromise was fulfilled with a `PMKManifold`, returns only the first fulfillment object. + + - Returns: The value with which this promise was resolved or `nil` if this promise is pending. + */ +@property (nonatomic, readonly) __nullable id value NS_REFINED_FOR_SWIFT; + +/// - Returns: if the promise is pending resolution. +@property (nonatomic, readonly) BOOL pending NS_REFINED_FOR_SWIFT; + +/// - Returns: if the promise is resolved and fulfilled. +@property (nonatomic, readonly) BOOL fulfilled NS_REFINED_FOR_SWIFT; + +/// - Returns: if the promise is resolved and rejected. +@property (nonatomic, readonly) BOOL rejected NS_REFINED_FOR_SWIFT; + + +/** + The provided block is executed when its receiver is resolved. + + If you provide a block that takes a parameter, the value of the receiver will be passed as that parameter. + + [NSURLSession GET:url].then(^(NSData *data){ + // do something with data + }); + + @return A new promise that is resolved with the value returned from the provided block. For example: + + [NSURLSession GET:url].then(^(NSData *data){ + return data.length; + }).then(^(NSNumber *number){ + //… + }); + + @warning *Important* The block passed to `then` may take zero, one, two or three arguments, and return an object or return nothing. This flexibility is why the method signature for then is `id`, which means you will not get completion for the block parameter, and must type it yourself. It is safe to type any block syntax here, so to start with try just: `^{}`. + + @warning *Important* If an `NSError` or `NSString` is thrown inside your block, or you return an `NSError` object the next `Promise` will be rejected. See `catch` for documentation on error handling. + + @warning *Important* `then` is always executed on the main queue. + + @see thenOn + @see thenInBackground +*/ +- (AnyPromise * __nonnull (^ __nonnull)(id __nonnull))then NS_REFINED_FOR_SWIFT; + + +/** + The provided block is executed on the default queue when the receiver is fulfilled. + + This method is provided as a convenience for `thenOn`. + + @see then + @see thenOn +*/ +- (AnyPromise * __nonnull(^ __nonnull)(id __nonnull))thenInBackground NS_REFINED_FOR_SWIFT; + +/** + The provided block is executed on the dispatch queue of your choice when the receiver is fulfilled. + + @see then + @see thenInBackground +*/ +- (AnyPromise * __nonnull(^ __nonnull)(dispatch_queue_t __nonnull, id __nonnull))thenOn NS_REFINED_FOR_SWIFT; + +#ifndef __cplusplus +/** + The provided block is executed when the receiver is rejected. + + Provide a block of form `^(NSError *){}` or simply `^{}`. The parameter has type `id` to give you the freedom to choose either. + + The provided block always runs on the main queue. + + @warning *Note* Cancellation errors are not caught. + + @warning *Note* Since catch is a c++ keyword, this method is not available in Objective-C++ files. Instead use catchOn. + + @see catchOn + @see catchInBackground +*/ +- (AnyPromise * __nonnull(^ __nonnull)(id __nonnull))catch NS_REFINED_FOR_SWIFT; +#endif + +/** + The provided block is executed when the receiver is rejected. + + Provide a block of form `^(NSError *){}` or simply `^{}`. The parameter has type `id` to give you the freedom to choose either. + + The provided block always runs on the global background queue. + + @warning *Note* Cancellation errors are not caught. + + @warning *Note* Since catch is a c++ keyword, this method is not available in Objective-C++ files. Instead use catchWithPolicy. + + @see catch + @see catchOn + */ +- (AnyPromise * __nonnull(^ __nonnull)(id __nonnull))catchInBackground NS_REFINED_FOR_SWIFT; + + +/** + The provided block is executed when the receiver is rejected. + + Provide a block of form `^(NSError *){}` or simply `^{}`. The parameter has type `id` to give you the freedom to choose either. + + The provided block always runs on queue provided. + + @warning *Note* Cancellation errors are not caught. + + @see catch + @see catchInBackground + */ +- (AnyPromise * __nonnull(^ __nonnull)(dispatch_queue_t __nonnull, id __nonnull))catchOn NS_REFINED_FOR_SWIFT; + +/** + The provided block is executed when the receiver is resolved. + + The provided block always runs on the main queue. + + @see ensureOn +*/ +- (AnyPromise * __nonnull(^ __nonnull)(dispatch_block_t __nonnull))ensure NS_REFINED_FOR_SWIFT; + +/** + The provided block is executed on the dispatch queue of your choice when the receiver is resolved. + + @see ensure + */ +- (AnyPromise * __nonnull(^ __nonnull)(dispatch_queue_t __nonnull, dispatch_block_t __nonnull))ensureOn NS_REFINED_FOR_SWIFT; + +/** + Create a new promise with an associated resolver. + + Use this method when wrapping asynchronous code that does *not* use + promises so that this code can be used in promise chains. Generally, + prefer `promiseWithResolverBlock:` as the resulting code is more elegant. + + PMKResolver resolve; + AnyPromise *promise = [[AnyPromise alloc] initWithResolver:&resolve]; + + // later + resolve(@"foo"); + + @param resolver A reference to a block pointer of PMKResolver type. + You can then call your resolver to resolve this promise. + + @return A new promise. + + @warning *Important* The resolver strongly retains the promise. + + @see promiseWithResolverBlock: +*/ +- (instancetype __nonnull)initWithResolver:(PMKResolver __strong __nonnull * __nonnull)resolver NS_REFINED_FOR_SWIFT; + +@end + + +typedef void (^PMKAdapter)(id __nullable, NSError * __nullable) NS_REFINED_FOR_SWIFT; +typedef void (^PMKIntegerAdapter)(NSInteger, NSError * __nullable) NS_REFINED_FOR_SWIFT; +typedef void (^PMKBooleanAdapter)(BOOL, NSError * __nullable) NS_REFINED_FOR_SWIFT; + + +@interface AnyPromise (Adapters) + +/** + Create a new promise by adapting an existing asynchronous system. + + The pattern of a completion block that passes two parameters, the first + the result and the second an `NSError` object is so common that we + provide this convenience adapter to make wrapping such systems more + elegant. + + return [PMKPromise promiseWithAdapterBlock:^(PMKAdapter adapter){ + PFQuery *query = [PFQuery …]; + [query findObjectsInBackgroundWithBlock:adapter]; + }]; + + @warning *Important* If both parameters are nil, the promise fulfills, + if both are non-nil the promise rejects. This is per the convention. + + @see https://github.com/mxcl/PromiseKit/blob/master/Documentation/GettingStarted.md#making-promises + */ ++ (instancetype __nonnull)promiseWithAdapterBlock:(void (^ __nonnull)(PMKAdapter __nonnull adapter))block NS_REFINED_FOR_SWIFT; + +/** + Create a new promise by adapting an existing asynchronous system. + + Adapts asynchronous systems that complete with `^(NSInteger, NSError *)`. + NSInteger will cast to enums provided the enum has been wrapped with + `NS_ENUM`. All of Apple’s enums are, so if you find one that hasn’t you + may need to make a pull-request. + + @see promiseWithAdapter + */ ++ (instancetype __nonnull)promiseWithIntegerAdapterBlock:(void (^ __nonnull)(PMKIntegerAdapter __nonnull adapter))block NS_REFINED_FOR_SWIFT; + +/** + Create a new promise by adapting an existing asynchronous system. + + Adapts asynchronous systems that complete with `^(BOOL, NSError *)`. + + @see promiseWithAdapter + */ ++ (instancetype __nonnull)promiseWithBooleanAdapterBlock:(void (^ __nonnull)(PMKBooleanAdapter __nonnull adapter))block NS_REFINED_FOR_SWIFT; + +@end + + +#ifdef __cplusplus +extern "C" { +#endif + +/** + Whenever resolving a promise you may resolve with a tuple, eg. + returning from a `then` or `catch` handler or resolving a new promise. + + Consumers of your Promise are not compelled to consume any arguments and + in fact will often only consume the first parameter. Thus ensure the + order of parameters is: from most-important to least-important. + + Currently PromiseKit limits you to THREE parameters to the manifold. +*/ +#define PMKManifold(...) __PMKManifold(__VA_ARGS__, 3, 2, 1) +#define __PMKManifold(_1, _2, _3, N, ...) __PMKArrayWithCount(N, _1, _2, _3) +extern id __nonnull __PMKArrayWithCount(NSUInteger, ...); + +#ifdef __cplusplus +} // Extern C +#endif + + +@interface AnyPromise (Unavailable) + +- (instancetype __nonnull)init __attribute__((unavailable("It is illegal to create an unresolvable promise."))); ++ (instancetype __nonnull)new __attribute__((unavailable("It is illegal to create an unresolvable promise."))); +- (AnyPromise * __nonnull(^ __nonnull)(dispatch_block_t __nonnull))always __attribute__((unavailable("See -ensure"))); +- (AnyPromise * __nonnull(^ __nonnull)(dispatch_block_t __nonnull))alwaysOn __attribute__((unavailable("See -ensureOn"))); +- (AnyPromise * __nonnull(^ __nonnull)(dispatch_block_t __nonnull))finally __attribute__((unavailable("See -ensure"))); +- (AnyPromise * __nonnull(^ __nonnull)(dispatch_block_t __nonnull, dispatch_block_t __nonnull))finallyOn __attribute__((unavailable("See -ensureOn"))); + +@end + +__attribute__((unavailable("See AnyPromise"))) +@interface PMKPromise +@end diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/AnyPromise.m b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/AnyPromise.m new file mode 100644 index 000000000..af6631004 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/AnyPromise.m @@ -0,0 +1,175 @@ +#if __has_include("PromiseKit-Swift.h") + #import "PromiseKit-Swift.h" +#else + #import +#endif +#import "PMKCallVariadicBlock.m" +#import "AnyPromise+Private.h" +#import "AnyPromise.h" + +NSString *const PMKErrorDomain = @"PMKErrorDomain"; + + +@implementation AnyPromise { + __AnyPromise *d; +} + +- (instancetype)initWith__D:(__AnyPromise *)dd { + self = [super init]; + if (self) self->d = dd; + return self; +} + +- (instancetype)initWithResolver:(PMKResolver __strong *)resolver { + self = [super init]; + if (self) + d = [[__AnyPromise alloc] initWithResolver:^(void (^resolve)(id)) { + *resolver = resolve; + }]; + return self; +} + ++ (instancetype)promiseWithResolverBlock:(void (^)(PMKResolver _Nonnull))resolveBlock { + id d = [[__AnyPromise alloc] initWithResolver:resolveBlock]; + return [[self alloc] initWith__D:d]; +} + ++ (instancetype)promiseWithValue:(id)value { + //TODO provide a more efficient route for sealed promises + id d = [[__AnyPromise alloc] initWithResolver:^(void (^resolve)(id)) { + resolve(value); + }]; + return [[self alloc] initWith__D:d]; +} + +//TODO remove if possible, but used by when.m +- (void)__pipe:(void (^)(id _Nullable))block { + [d __pipe:block]; +} + +//NOTE used by AnyPromise.swift +- (id)__d { + return d; +} + +- (AnyPromise *(^)(id))then { + return ^(id block) { + return [self->d __thenOn:dispatch_get_main_queue() execute:^(id obj) { + return PMKCallVariadicBlock(block, obj); + }]; + }; +} + +- (AnyPromise *(^)(dispatch_queue_t, id))thenOn { + return ^(dispatch_queue_t queue, id block) { + return [self->d __thenOn:queue execute:^(id obj) { + return PMKCallVariadicBlock(block, obj); + }]; + }; +} + +- (AnyPromise *(^)(id))thenInBackground { + return ^(id block) { + return [self->d __thenOn:dispatch_get_global_queue(0, 0) execute:^(id obj) { + return PMKCallVariadicBlock(block, obj); + }]; + }; +} + +- (AnyPromise *(^)(dispatch_queue_t, id))catchOn { + return ^(dispatch_queue_t q, id block) { + return [self->d __catchOn:q execute:^(id obj) { + return PMKCallVariadicBlock(block, obj); + }]; + }; +} + +- (AnyPromise *(^)(id))catch { + return ^(id block) { + return [self->d __catchOn:dispatch_get_main_queue() execute:^(id obj) { + return PMKCallVariadicBlock(block, obj); + }]; + }; +} + +- (AnyPromise *(^)(id))catchInBackground { + return ^(id block) { + return [self->d __catchOn:dispatch_get_global_queue(0, 0) execute:^(id obj) { + return PMKCallVariadicBlock(block, obj); + }]; + }; +} + +- (AnyPromise *(^)(dispatch_block_t))ensure { + return ^(dispatch_block_t block) { + return [self->d __ensureOn:dispatch_get_main_queue() execute:block]; + }; +} + +- (AnyPromise *(^)(dispatch_queue_t, dispatch_block_t))ensureOn { + return ^(dispatch_queue_t queue, dispatch_block_t block) { + return [self->d __ensureOn:queue execute:block]; + }; +} + +- (BOOL)pending { + return [[d valueForKey:@"__pending"] boolValue]; +} + +- (BOOL)rejected { + return IsError([d __value]); +} + +- (BOOL)fulfilled { + return !self.rejected; +} + +- (id)value { + id obj = [d __value]; + + if ([obj isKindOfClass:[PMKArray class]]) { + return obj[0]; + } else { + return obj; + } +} + +@end + + + +@implementation AnyPromise (Adapters) + ++ (instancetype)promiseWithAdapterBlock:(void (^)(PMKAdapter))block { + return [self promiseWithResolverBlock:^(PMKResolver resolve) { + block(^(id value, id error){ + resolve(error ?: value); + }); + }]; +} + ++ (instancetype)promiseWithIntegerAdapterBlock:(void (^)(PMKIntegerAdapter))block { + return [self promiseWithResolverBlock:^(PMKResolver resolve) { + block(^(NSInteger value, id error){ + if (error) { + resolve(error); + } else { + resolve(@(value)); + } + }); + }]; +} + ++ (instancetype)promiseWithBooleanAdapterBlock:(void (^)(PMKBooleanAdapter adapter))block { + return [self promiseWithResolverBlock:^(PMKResolver resolve) { + block(^(BOOL value, id error){ + if (error) { + resolve(error); + } else { + resolve(@(value)); + } + }); + }]; +} + +@end diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/AnyPromise.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/AnyPromise.swift new file mode 100644 index 000000000..5dfa1df4c --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/AnyPromise.swift @@ -0,0 +1,204 @@ +import Foundation + +/** + __AnyPromise is an implementation detail. + + Because of how ObjC/Swift compatability work we have to compose our AnyPromise + with this internal object, however this is still part of the public interface. + Sadly. Please don’t use it. +*/ +@objc(__AnyPromise) public class __AnyPromise: NSObject { + fileprivate let box: Box + + @objc public init(resolver body: (@escaping (Any?) -> Void) -> Void) { + box = EmptyBox() + super.init() + body { + if let p = $0 as? AnyPromise { + p.d.__pipe(self.box.seal) + } else { + self.box.seal($0) + } + } + } + + @objc public func __thenOn(_ q: DispatchQueue, execute: @escaping (Any?) -> Any?) -> AnyPromise { + return AnyPromise(__D: __AnyPromise(resolver: { resolve in + self.__pipe { obj in + if !(obj is NSError) { + q.async { + resolve(execute(obj)) + } + } else { + resolve(obj) + } + } + })) + } + + @objc public func __catchOn(_ q: DispatchQueue, execute: @escaping (Any?) -> Any?) -> AnyPromise { + return AnyPromise(__D: __AnyPromise(resolver: { resolve in + self.__pipe { obj in + if obj is NSError { + q.async { + resolve(execute(obj)) + } + } else { + resolve(obj) + } + } + })) + } + + @objc public func __ensureOn(_ q: DispatchQueue, execute: @escaping () -> Void) -> AnyPromise { + return AnyPromise(__D: __AnyPromise(resolver: { resolve in + self.__pipe { obj in + q.async { + execute() + resolve(obj) + } + } + })) + } + + /// Internal, do not use! Some behaviors undefined. + @objc public func __pipe(_ to: @escaping (Any?) -> Void) { + let to = { (obj: Any?) -> Void in + if obj is NSError { + to(obj) // or we cannot determine if objects are errors in objc land + } else { + to(obj) + } + } + switch box.inspect() { + case .pending: + box.inspect { + switch $0 { + case .pending(let handlers): + handlers.append { obj in + to(obj) + } + case .resolved(let obj): + to(obj) + } + } + case .resolved(let obj): + to(obj) + } + } + + @objc public var __value: Any? { + switch box.inspect() { + case .resolved(let obj): + return obj + default: + return nil + } + } + + @objc public var __pending: Bool { + switch box.inspect() { + case .pending: + return true + case .resolved: + return false + } + } +} + +extension AnyPromise: Thenable, CatchMixin { + + /// - Returns: A new `AnyPromise` bound to a `Promise`. + public convenience init(_ bridge: U) { + self.init(__D: __AnyPromise(resolver: { resolve in + bridge.pipe { + switch $0 { + case .rejected(let error): + resolve(error as NSError) + case .fulfilled(let value): + resolve(value) + } + } + })) + } + + public func pipe(to body: @escaping (Result) -> Void) { + + func fulfill() { + // calling through to the ObjC `value` property unwraps (any) PMKManifold + // and considering this is the Swift pipe; we want that. + body(.fulfilled(self.value(forKey: "value"))) + } + + switch box.inspect() { + case .pending: + box.inspect { + switch $0 { + case .pending(let handlers): + handlers.append { + if let error = $0 as? Error { + body(.rejected(error)) + } else { + fulfill() + } + } + case .resolved(let error as Error): + body(.rejected(error)) + case .resolved: + fulfill() + } + } + case .resolved(let error as Error): + body(.rejected(error)) + case .resolved: + fulfill() + } + } + + fileprivate var d: __AnyPromise { + return value(forKey: "__d") as! __AnyPromise + } + + var box: Box { + return d.box + } + + public var result: Result? { + guard let value = __value else { + return nil + } + if let error = value as? Error { + return .rejected(error) + } else { + return .fulfilled(value) + } + } + + public typealias T = Any? +} + + +#if swift(>=3.1) +public extension Promise where T == Any? { + convenience init(_ anyPromise: AnyPromise) { + self.init { + anyPromise.pipe(to: $0.resolve) + } + } +} +#else +extension AnyPromise { + public func asPromise() -> Promise { + return Promise(.pending, resolver: { resolve in + pipe { result in + switch result { + case .rejected(let error): + resolve.reject(error) + case .fulfilled(let obj): + resolve.fulfill(obj) + } + } + }) + } +} +#endif diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Box.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Box.swift new file mode 100644 index 000000000..43cd3d1b0 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Box.swift @@ -0,0 +1,101 @@ +import Dispatch + +enum Sealant { + case pending(Handlers) + case resolved(R) +} + +final class Handlers { + var bodies: [(R) -> Void] = [] + func append(_ item: @escaping(R) -> Void) { bodies.append(item) } +} + +/// - Remark: not protocol ∵ http://www.russbishop.net/swift-associated-types-cont +class Box { + func inspect() -> Sealant { fatalError() } + func inspect(_: (Sealant) -> Void) { fatalError() } + func seal(_: T) {} +} + +final class SealedBox: Box { + let value: T + + init(value: T) { + self.value = value + } + + override func inspect() -> Sealant { + return .resolved(value) + } +} + +class EmptyBox: Box { + private var sealant = Sealant.pending(.init()) + private let barrier = DispatchQueue(label: "org.promisekit.barrier", attributes: .concurrent) + + override func seal(_ value: T) { + var handlers: Handlers! + barrier.sync(flags: .barrier) { + guard case .pending(let _handlers) = self.sealant else { + return // already fulfilled! + } + handlers = _handlers + self.sealant = .resolved(value) + } + + //FIXME we are resolved so should `pipe(to:)` be called at this instant, “thens are called in order” would be invalid + //NOTE we don’t do this in the above `sync` because that could potentially deadlock + //THOUGH since `then` etc. typically invoke after a run-loop cycle, this issue is somewhat less severe + + if let handlers = handlers { + handlers.bodies.forEach{ $0(value) } + } + + //TODO solution is an unfortunate third state “sealed” where then's get added + // to a separate handler pool for that state + // any other solution has potential races + } + + override func inspect() -> Sealant { + var rv: Sealant! + barrier.sync { + rv = self.sealant + } + return rv + } + + override func inspect(_ body: (Sealant) -> Void) { + var sealed = false + barrier.sync(flags: .barrier) { + switch sealant { + case .pending: + // body will append to handlers, so we must stay barrier’d + body(sealant) + case .resolved: + sealed = true + } + } + if sealed { + // we do this outside the barrier to prevent potential deadlocks + // it's safe because we never transition away from this state + body(sealant) + } + } +} + + +extension Optional where Wrapped: DispatchQueue { + @inline(__always) + func async(flags: DispatchWorkItemFlags?, _ body: @escaping() -> Void) { + switch self { + case .none: + body() + case .some(let q): + if let flags = flags { + q.async(flags: flags, execute: body) + } else { + q.async(execute: body) + } + } + } +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Catchable.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Catchable.swift new file mode 100644 index 000000000..596abdcba --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Catchable.swift @@ -0,0 +1,256 @@ +import Dispatch + +/// Provides `catch` and `recover` to your object that conforms to `Thenable` +public protocol CatchMixin: Thenable +{} + +public extension CatchMixin { + + /** + The provided closure executes when this promise rejects. + + Rejecting a promise cascades: rejecting all subsequent promises (unless + recover is invoked) thus you will typically place your catch at the end + of a chain. Often utility promises will not have a catch, instead + delegating the error handling to the caller. + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter policy: The default policy does not execute your handler for cancellation errors. + - Parameter execute: The handler to execute if this promise is rejected. + - Returns: A promise finalizer. + - SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation) + */ + @discardableResult + func `catch`(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, policy: CatchPolicy = conf.catchPolicy, _ body: @escaping(Error) -> Void) -> PMKFinalizer { + let finalizer = PMKFinalizer() + pipe { + switch $0 { + case .rejected(let error): + guard policy == .allErrors || !error.isCancelled else { + fallthrough + } + on.async(flags: flags) { + body(error) + finalizer.pending.resolve(()) + } + case .fulfilled: + finalizer.pending.resolve(()) + } + } + return finalizer + } +} + +public class PMKFinalizer { + let pending = Guarantee.pending() + + /// `finally` is the same as `ensure`, but it is not chainable + public func finally(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping () -> Void) { + pending.guarantee.done(on: on, flags: flags) { + body() + } + } +} + + +public extension CatchMixin { + + /** + The provided closure executes when this promise rejects. + + Unlike `catch`, `recover` continues the chain. + Use `recover` in circumstances where recovering the chain from certain errors is a possibility. For example: + + firstly { + CLLocationManager.requestLocation() + }.recover { error in + guard error == CLError.unknownLocation else { throw error } + return .value(CLLocation.chicago) + } + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter body: The handler to execute if this promise is rejected. + - SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation) + */ + func recover(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, policy: CatchPolicy = conf.catchPolicy, _ body: @escaping(Error) throws -> U) -> Promise where U.T == T { + let rp = Promise(.pending) + pipe { + switch $0 { + case .fulfilled(let value): + rp.box.seal(.fulfilled(value)) + case .rejected(let error): + if policy == .allErrors || !error.isCancelled { + on.async(flags: flags) { + do { + let rv = try body(error) + guard rv !== rp else { throw PMKError.returnedSelf } + rv.pipe(to: rp.box.seal) + } catch { + rp.box.seal(.rejected(error)) + } + } + } else { + rp.box.seal(.rejected(error)) + } + } + } + return rp + } + + /** + The provided closure executes when this promise rejects. + This variant of `recover` requires the handler to return a Guarantee, thus it returns a Guarantee itself and your closure cannot `throw`. + - Note it is logically impossible for this to take a `catchPolicy`, thus `allErrors` are handled. + - Parameter on: The queue to which the provided closure dispatches. + - Parameter body: The handler to execute if this promise is rejected. + - SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation) + */ + @discardableResult + func recover(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(Error) -> Guarantee) -> Guarantee { + let rg = Guarantee(.pending) + pipe { + switch $0 { + case .fulfilled(let value): + rg.box.seal(value) + case .rejected(let error): + on.async(flags: flags) { + body(error).pipe(to: rg.box.seal) + } + } + } + return rg + } + + /** + The provided closure executes when this promise resolves, whether it rejects or not. + + firstly { + UIApplication.shared.networkActivityIndicatorVisible = true + }.done { + //… + }.ensure { + UIApplication.shared.networkActivityIndicatorVisible = false + }.catch { + //… + } + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter body: The closure that executes when this promise resolves. + - Returns: A new promise, resolved with this promise’s resolution. + */ + func ensure(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping () -> Void) -> Promise { + let rp = Promise(.pending) + pipe { result in + on.async(flags: flags) { + body() + rp.box.seal(result) + } + } + return rp + } + + /** + The provided closure executes when this promise resolves, whether it rejects or not. + The chain waits on the returned `Guarantee`. + + firstly { + setup() + }.done { + //… + }.ensureThen { + teardown() // -> Guarante + }.catch { + //… + } + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter body: The closure that executes when this promise resolves. + - Returns: A new promise, resolved with this promise’s resolution. + */ + func ensureThen(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping () -> Guarantee) -> Promise { + let rp = Promise(.pending) + pipe { result in + on.async(flags: flags) { + body().done { + rp.box.seal(result) + } + } + } + return rp + } + + + + /** + Consumes the Swift unused-result warning. + - Note: You should `catch`, but in situations where you know you don’t need a `catch`, `cauterize` makes your intentions clear. + */ + @discardableResult + func cauterize() -> PMKFinalizer { + return self.catch { + conf.logHandler(.cauterized($0)) + } + } +} + + +public extension CatchMixin where T == Void { + + /** + The provided closure executes when this promise rejects. + + This variant of `recover` is specialized for `Void` promises and de-errors your chain returning a `Guarantee`, thus you cannot `throw` and you must handle all errors including cancellation. + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter body: The handler to execute if this promise is rejected. + - SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation) + */ + @discardableResult + func recover(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(Error) -> Void) -> Guarantee { + let rg = Guarantee(.pending) + pipe { + switch $0 { + case .fulfilled: + rg.box.seal(()) + case .rejected(let error): + on.async(flags: flags) { + body(error) + rg.box.seal(()) + } + } + } + return rg + } + + /** + The provided closure executes when this promise rejects. + + This variant of `recover` ensures that no error is thrown from the handler and allows specifying a catch policy. + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter body: The handler to execute if this promise is rejected. + - SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation) + */ + func recover(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, policy: CatchPolicy = conf.catchPolicy, _ body: @escaping(Error) throws -> Void) -> Promise { + let rg = Promise(.pending) + pipe { + switch $0 { + case .fulfilled: + rg.box.seal(.fulfilled(())) + case .rejected(let error): + if policy == .allErrors || !error.isCancelled { + on.async(flags: flags) { + do { + rg.box.seal(.fulfilled(try body(error))) + } catch { + rg.box.seal(.rejected(error)) + } + } + } else { + rg.box.seal(.rejected(error)) + } + } + } + return rg + } +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Configuration.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Configuration.swift new file mode 100644 index 000000000..9d4fc22fb --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Configuration.swift @@ -0,0 +1,35 @@ +import Dispatch + +/** + PromiseKit’s configurable parameters. + + Do not change these after any Promise machinery executes as the configuration object is not thread-safe. + + We would like it to be, but sadly `Swift` does not expose `dispatch_once` et al. which is what we used to use in order to make the configuration immutable once first used. +*/ +public struct PMKConfiguration { + /// The default queues that promises handlers dispatch to + public var Q: (map: DispatchQueue?, return: DispatchQueue?) = (map: DispatchQueue.main, return: DispatchQueue.main) + + /// The default catch-policy for all `catch` and `resolve` + public var catchPolicy = CatchPolicy.allErrorsExceptCancellation + + /// The closure used to log PromiseKit events. + /// Not thread safe; change before processing any promises. + /// - Note: The default handler calls `print()` + public var logHandler: (LogEvent) -> () = { event in + switch event { + case .waitOnMainThread: + print("PromiseKit: warning: `wait()` called on main thread!") + case .pendingPromiseDeallocated: + print("PromiseKit: warning: pending promise deallocated") + case .pendingGuaranteeDeallocated: + print("PromiseKit: warning: pending guarantee deallocated") + case .cauterized (let error): + print("PromiseKit:cauterized-error: \(error)") + } + } +} + +/// Modify this as soon as possible in your application’s lifetime +public var conf = PMKConfiguration() diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/CustomStringConvertible.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/CustomStringConvertible.swift new file mode 100644 index 000000000..eee0b020a --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/CustomStringConvertible.swift @@ -0,0 +1,44 @@ + +extension Promise: CustomStringConvertible { + /// - Returns: A description of the state of this promise. + public var description: String { + switch result { + case nil: + return "Promise(…\(T.self))" + case .rejected(let error)?: + return "Promise(\(error))" + case .fulfilled(let value)?: + return "Promise(\(value))" + } + } +} + +extension Promise: CustomDebugStringConvertible { + /// - Returns: A debug-friendly description of the state of this promise. + public var debugDescription: String { + switch box.inspect() { + case .pending(let handlers): + return "Promise<\(T.self)>.pending(handlers: \(handlers.bodies.count))" + case .resolved(.rejected(let error)): + return "Promise<\(T.self)>.rejected(\(type(of: error)).\(error))" + case .resolved(.fulfilled(let value)): + return "Promise<\(T.self)>.fulfilled(\(value))" + } + } +} + +#if !SWIFT_PACKAGE +extension AnyPromise { + /// - Returns: A description of the state of this promise. + override open var description: String { + switch box.inspect() { + case .pending: + return "AnyPromise(…)" + case .resolved(let obj?): + return "AnyPromise(\(obj))" + case .resolved(nil): + return "AnyPromise(nil)" + } + } +} +#endif diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Deprecations.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Deprecations.swift new file mode 100644 index 000000000..a837dcb8d --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Deprecations.swift @@ -0,0 +1,93 @@ +import Dispatch + +@available(*, deprecated, message: "See `init(resolver:)`") +public func wrap(_ body: (@escaping (T?, Error?) -> Void) throws -> Void) -> Promise { + return Promise { seal in + try body(seal.resolve) + } +} + +@available(*, deprecated, message: "See `init(resolver:)`") +public func wrap(_ body: (@escaping (T, Error?) -> Void) throws -> Void) -> Promise { + return Promise { seal in + try body(seal.resolve) + } +} + +@available(*, deprecated, message: "See `init(resolver:)`") +public func wrap(_ body: (@escaping (Error?, T?) -> Void) throws -> Void) -> Promise { + return Promise { seal in + try body(seal.resolve) + } +} + +@available(*, deprecated, message: "See `init(resolver:)`") +public func wrap(_ body: (@escaping (Error?) -> Void) throws -> Void) -> Promise { + return Promise { seal in + try body(seal.resolve) + } +} + +@available(*, deprecated, message: "See `init(resolver:)`") +public func wrap(_ body: (@escaping (T) -> Void) throws -> Void) -> Promise { + return Promise { seal in + try body(seal.fulfill) + } +} + +public extension Promise { + @available(*, deprecated, message: "See `ensure`") + func always(on q: DispatchQueue = .main, execute body: @escaping () -> Void) -> Promise { + return ensure(on: q, body) + } +} + +public extension Thenable { +#if PMKFullDeprecations + /// disabled due to ambiguity with the other `.flatMap` + @available(*, deprecated, message: "See: `compactMap`") + func flatMap(on: DispatchQueue? = conf.Q.map, _ transform: @escaping(T) throws -> U?) -> Promise { + return compactMap(on: on, transform) + } +#endif +} + +public extension Thenable where T: Sequence { +#if PMKFullDeprecations + /// disabled due to ambiguity with the other `.map` + @available(*, deprecated, message: "See: `mapValues`") + func map(on: DispatchQueue? = conf.Q.map, _ transform: @escaping(T.Iterator.Element) throws -> U) -> Promise<[U]> { + return mapValues(on: on, transform) + } + + /// disabled due to ambiguity with the other `.flatMap` + @available(*, deprecated, message: "See: `flatMapValues`") + func flatMap(on: DispatchQueue? = conf.Q.map, _ transform: @escaping(T.Iterator.Element) throws -> U) -> Promise<[U.Iterator.Element]> { + return flatMapValues(on: on, transform) + } +#endif + + @available(*, deprecated, message: "See: `filterValues`") + func filter(on: DispatchQueue? = conf.Q.map, test: @escaping (T.Iterator.Element) -> Bool) -> Promise<[T.Iterator.Element]> { + return filterValues(on: on, test) + } +} + +public extension Thenable where T: Collection { + @available(*, deprecated, message: "See: `firstValue`") + var first: Promise { + return firstValue + } + + @available(*, deprecated, message: "See: `lastValue`") + var last: Promise { + return lastValue + } +} + +public extension Thenable where T: Sequence, T.Iterator.Element: Comparable { + @available(*, deprecated, message: "See: `sortedValues`") + func sorted(on: DispatchQueue? = conf.Q.map) -> Promise<[T.Iterator.Element]> { + return sortedValues(on: on) + } +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Error.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Error.swift new file mode 100644 index 000000000..7229e6f49 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Error.swift @@ -0,0 +1,103 @@ +import Foundation + +public enum PMKError: Error { + /** + The completionHandler with form `(T?, Error?)` was called with `(nil, nil)`. + This is invalid as per Cocoa/Apple calling conventions. + */ + case invalidCallingConvention + + /** + A handler returned its own promise. 99% of the time, this is likely a + programming error. It is also invalid per Promises/A+. + */ + case returnedSelf + + /** `when()`, `race()` etc. were called with invalid parameters, eg. an empty array. */ + case badInput + + /// The operation was cancelled + case cancelled + + /// `nil` was returned from `flatMap` + @available(*, deprecated, message: "See: `compactMap`") + case flatMap(Any, Any.Type) + + /// `nil` was returned from `compactMap` + case compactMap(Any, Any.Type) + + /** + The lastValue or firstValue of a sequence was requested but the sequence was empty. + + Also used if all values of this collection failed the test passed to `firstValue(where:)`. + */ + case emptySequence +} + +extension PMKError: CustomDebugStringConvertible { + public var debugDescription: String { + switch self { + case .flatMap(let obj, let type): + return "Could not `flatMap<\(type)>`: \(obj)" + case .compactMap(let obj, let type): + return "Could not `compactMap<\(type)>`: \(obj)" + case .invalidCallingConvention: + return "A closure was called with an invalid calling convention, probably (nil, nil)" + case .returnedSelf: + return "A promise handler returned itself" + case .badInput: + return "Bad input was provided to a PromiseKit function" + case .cancelled: + return "The asynchronous sequence was cancelled" + case .emptySequence: + return "The first or last element was requested for an empty sequence" + } + } +} + +extension PMKError: LocalizedError { + public var errorDescription: String? { + return debugDescription + } +} + + +//////////////////////////////////////////////////////////// Cancellation + +/// An error that may represent the cancelled condition +public protocol CancellableError: Error { + /// returns true if this Error represents a cancelled condition + var isCancelled: Bool { get } +} + +extension Error { + public var isCancelled: Bool { + do { + throw self + } catch PMKError.cancelled { + return true + } catch let error as CancellableError { + return error.isCancelled + } catch URLError.cancelled { + return true + } catch CocoaError.userCancelled { + return true + } catch { + #if os(macOS) || os(iOS) || os(tvOS) + let pair = { ($0.domain, $0.code) }(error as NSError) + return ("SKErrorDomain", 2) == pair + #else + return false + #endif + } + } +} + +/// Used by `catch` and `recover` +public enum CatchPolicy { + /// Indicates that `catch` or `recover` handle all error types including cancellable-errors. + case allErrors + + /// Indicates that `catch` or `recover` handle all error except cancellable-errors. + case allErrorsExceptCancellation +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Guarantee.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Guarantee.swift new file mode 100644 index 000000000..b87fad189 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Guarantee.swift @@ -0,0 +1,212 @@ +import class Foundation.Thread +import Dispatch + +/** + A `Guarantee` is a functional abstraction around an asynchronous operation that cannot error. + - See: `Thenable` +*/ +public final class Guarantee: Thenable { + let box: PromiseKit.Box + + fileprivate init(box: SealedBox) { + self.box = box + } + + /// Returns a `Guarantee` sealed with the provided value. + public static func value(_ value: T) -> Guarantee { + return .init(box: SealedBox(value: value)) + } + + /// Returns a pending `Guarantee` that can be resolved with the provided closure’s parameter. + public init(resolver body: (@escaping(T) -> Void) -> Void) { + box = Box() + body(box.seal) + } + + /// - See: `Thenable.pipe` + public func pipe(to: @escaping(Result) -> Void) { + pipe{ to(.fulfilled($0)) } + } + + func pipe(to: @escaping(T) -> Void) { + switch box.inspect() { + case .pending: + box.inspect { + switch $0 { + case .pending(let handlers): + handlers.append(to) + case .resolved(let value): + to(value) + } + } + case .resolved(let value): + to(value) + } + } + + /// - See: `Thenable.result` + public var result: Result? { + switch box.inspect() { + case .pending: + return nil + case .resolved(let value): + return .fulfilled(value) + } + } + + final private class Box: EmptyBox { + deinit { + switch inspect() { + case .pending: + PromiseKit.conf.logHandler(.pendingGuaranteeDeallocated) + case .resolved: + break + } + } + } + + init(_: PMKUnambiguousInitializer) { + box = Box() + } + + /// Returns a tuple of a pending `Guarantee` and a function that resolves it. + public class func pending() -> (guarantee: Guarantee, resolve: (T) -> Void) { + return { ($0, $0.box.seal) }(Guarantee(.pending)) + } +} + +public extension Guarantee { + @discardableResult + func done(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(T) -> Void) -> Guarantee { + let rg = Guarantee(.pending) + pipe { (value: T) in + on.async(flags: flags) { + body(value) + rg.box.seal(()) + } + } + return rg + } + + func get(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping (T) -> Void) -> Guarantee { + return map(on: on, flags: flags) { + body($0) + return $0 + } + } + + func map(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(T) -> U) -> Guarantee { + let rg = Guarantee(.pending) + pipe { value in + on.async(flags: flags) { + rg.box.seal(body(value)) + } + } + return rg + } + + @discardableResult + func then(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(T) -> Guarantee) -> Guarantee { + let rg = Guarantee(.pending) + pipe { value in + on.async(flags: flags) { + body(value).pipe(to: rg.box.seal) + } + } + return rg + } + + func asVoid() -> Guarantee { + return map(on: nil) { _ in } + } + + /** + Blocks this thread, so you know, don’t call this on a serial thread that + any part of your chain may use. Like the main thread for example. + */ + func wait() -> T { + + if Thread.isMainThread { + conf.logHandler(.waitOnMainThread) + } + + var result = value + + if result == nil { + let group = DispatchGroup() + group.enter() + pipe { (foo: T) in result = foo; group.leave() } + group.wait() + } + + return result! + } +} + +public extension Guarantee where T: Sequence { + + /** + `Guarantee<[T]>` => `T` -> `Guarantee` => `Guaranetee<[U]>` + + firstly { + .value([1,2,3]) + }.thenMap { + .value($0 * 2) + }.done { + // $0 => [2,4,6] + } + */ + func thenMap(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) -> Guarantee) -> Guarantee<[U]> { + return then(on: on, flags: flags) { + when(fulfilled: $0.map(transform)) + }.recover { + // if happens then is bug inside PromiseKit + fatalError(String(describing: $0)) + } + } +} + +#if swift(>=3.1) +public extension Guarantee where T == Void { + convenience init() { + self.init(box: SealedBox(value: Void())) + } +} +#endif + + +public extension DispatchQueue { + /** + Asynchronously executes the provided closure on a dispatch queue. + + DispatchQueue.global().async(.promise) { + md5(input) + }.done { md5 in + //… + } + + - Parameter body: The closure that resolves this promise. + - Returns: A new `Guarantee` resolved by the result of the provided closure. + - Note: There is no Promise/Thenable version of this due to Swift compiler ambiguity issues. + */ + @available(macOS 10.10, iOS 2.0, tvOS 10.0, watchOS 2.0, *) + final func async(_: PMKNamespacer, group: DispatchGroup? = nil, qos: DispatchQoS = .default, flags: DispatchWorkItemFlags = [], execute body: @escaping () -> T) -> Guarantee { + let rg = Guarantee(.pending) + async(group: group, qos: qos, flags: flags) { + rg.box.seal(body()) + } + return rg + } +} + + +#if os(Linux) +import func CoreFoundation._CFIsMainThread + +extension Thread { + // `isMainThread` is not implemented yet in swift-corelibs-foundation. + static var isMainThread: Bool { + return _CFIsMainThread() + } +} +#endif diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/LogEvent.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/LogEvent.swift new file mode 100644 index 000000000..99683bdb6 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/LogEvent.swift @@ -0,0 +1,30 @@ +/** + The PromiseKit events which may be logged. + + ```` + /// A promise or guarantee has blocked the main thread + case waitOnMainThread + + /// A promise has been deallocated without being resolved + case pendingPromiseDeallocated + + /// An error which occurred while fulfilling a promise was swallowed + case cauterized(Error) + + /// Errors which give a string error message + case misc (String) + ```` +*/ +public enum LogEvent { + /// A promise or guarantee has blocked the main thread + case waitOnMainThread + + /// A promise has been deallocated without being resolved + case pendingPromiseDeallocated + + /// A guarantee has been deallocated without being resolved + case pendingGuaranteeDeallocated + + /// An error which occurred while resolving a promise was swallowed + case cauterized(Error) +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/NSMethodSignatureForBlock.m b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/NSMethodSignatureForBlock.m new file mode 100644 index 000000000..700c1b37e --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/NSMethodSignatureForBlock.m @@ -0,0 +1,77 @@ +#import + +struct PMKBlockLiteral { + void *isa; // initialized to &_NSConcreteStackBlock or &_NSConcreteGlobalBlock + int flags; + int reserved; + void (*invoke)(void *, ...); + struct block_descriptor { + unsigned long int reserved; // NULL + unsigned long int size; // sizeof(struct Block_literal_1) + // optional helper functions + void (*copy_helper)(void *dst, void *src); // IFF (1<<25) + void (*dispose_helper)(void *src); // IFF (1<<25) + // required ABI.2010.3.16 + const char *signature; // IFF (1<<30) + } *descriptor; + // imported variables +}; + +typedef NS_OPTIONS(NSUInteger, PMKBlockDescriptionFlags) { + PMKBlockDescriptionFlagsHasCopyDispose = (1 << 25), + PMKBlockDescriptionFlagsHasCtor = (1 << 26), // helpers have C++ code + PMKBlockDescriptionFlagsIsGlobal = (1 << 28), + PMKBlockDescriptionFlagsHasStret = (1 << 29), // IFF BLOCK_HAS_SIGNATURE + PMKBlockDescriptionFlagsHasSignature = (1 << 30) +}; + +// It appears 10.7 doesn't support quotes in method signatures. Remove them +// via @rabovik's method. See https://github.com/OliverLetterer/SLObjectiveCRuntimeAdditions/pull/2 +#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_8 +NS_INLINE static const char * pmk_removeQuotesFromMethodSignature(const char *str){ + char *result = malloc(strlen(str) + 1); + BOOL skip = NO; + char *to = result; + char c; + while ((c = *str++)) { + if ('"' == c) { + skip = !skip; + continue; + } + if (skip) continue; + *to++ = c; + } + *to = '\0'; + return result; +} +#endif + +static NSMethodSignature *NSMethodSignatureForBlock(id block) { + if (!block) + return nil; + + struct PMKBlockLiteral *blockRef = (__bridge struct PMKBlockLiteral *)block; + PMKBlockDescriptionFlags flags = (PMKBlockDescriptionFlags)blockRef->flags; + + if (flags & PMKBlockDescriptionFlagsHasSignature) { + void *signatureLocation = blockRef->descriptor; + signatureLocation += sizeof(unsigned long int); + signatureLocation += sizeof(unsigned long int); + + if (flags & PMKBlockDescriptionFlagsHasCopyDispose) { + signatureLocation += sizeof(void(*)(void *dst, void *src)); + signatureLocation += sizeof(void (*)(void *src)); + } + + const char *signature = (*(const char **)signatureLocation); +#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_8 + signature = pmk_removeQuotesFromMethodSignature(signature); + NSMethodSignature *nsSignature = [NSMethodSignature signatureWithObjCTypes:signature]; + free((void *)signature); + + return nsSignature; +#endif + return [NSMethodSignature signatureWithObjCTypes:signature]; + } + return 0; +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/PMKCallVariadicBlock.m b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/PMKCallVariadicBlock.m new file mode 100644 index 000000000..1453a7d26 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/PMKCallVariadicBlock.m @@ -0,0 +1,120 @@ +#import "NSMethodSignatureForBlock.m" +#import +#import +#import "AnyPromise+Private.h" +#import +#import +#import + +#ifndef PMKLog +#define PMKLog NSLog +#endif + +@interface PMKArray : NSObject { +@public + id objs[3]; + NSUInteger count; +} @end + +@implementation PMKArray + +- (id)objectAtIndexedSubscript:(NSUInteger)idx { + if (count <= idx) { + // this check is necessary due to lack of checks in `pmk_safely_call_block` + return nil; + } + return objs[idx]; +} + +@end + +id __PMKArrayWithCount(NSUInteger count, ...) { + PMKArray *this = [PMKArray new]; + this->count = count; + va_list args; + va_start(args, count); + for (NSUInteger x = 0; x < count; ++x) + this->objs[x] = va_arg(args, id); + va_end(args); + return this; +} + + +static inline id _PMKCallVariadicBlock(id frock, id result) { + NSCAssert(frock, @""); + + NSMethodSignature *sig = NSMethodSignatureForBlock(frock); + const NSUInteger nargs = sig.numberOfArguments; + const char rtype = sig.methodReturnType[0]; + + #define call_block_with_rtype(type) ({^type{ \ + switch (nargs) { \ + case 1: \ + return ((type(^)(void))frock)(); \ + case 2: { \ + const id arg = [result class] == [PMKArray class] ? result[0] : result; \ + return ((type(^)(id))frock)(arg); \ + } \ + case 3: { \ + type (^block)(id, id) = frock; \ + return [result class] == [PMKArray class] \ + ? block(result[0], result[1]) \ + : block(result, nil); \ + } \ + case 4: { \ + type (^block)(id, id, id) = frock; \ + return [result class] == [PMKArray class] \ + ? block(result[0], result[1], result[2]) \ + : block(result, nil, nil); \ + } \ + default: \ + @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"PromiseKit: The provided block’s argument count is unsupported." userInfo:nil]; \ + }}();}) + + switch (rtype) { + case 'v': + call_block_with_rtype(void); + return nil; + case '@': + return call_block_with_rtype(id) ?: nil; + case '*': { + char *str = call_block_with_rtype(char *); + return str ? @(str) : nil; + } + case 'c': return @(call_block_with_rtype(char)); + case 'i': return @(call_block_with_rtype(int)); + case 's': return @(call_block_with_rtype(short)); + case 'l': return @(call_block_with_rtype(long)); + case 'q': return @(call_block_with_rtype(long long)); + case 'C': return @(call_block_with_rtype(unsigned char)); + case 'I': return @(call_block_with_rtype(unsigned int)); + case 'S': return @(call_block_with_rtype(unsigned short)); + case 'L': return @(call_block_with_rtype(unsigned long)); + case 'Q': return @(call_block_with_rtype(unsigned long long)); + case 'f': return @(call_block_with_rtype(float)); + case 'd': return @(call_block_with_rtype(double)); + case 'B': return @(call_block_with_rtype(_Bool)); + case '^': + if (strcmp(sig.methodReturnType, "^v") == 0) { + call_block_with_rtype(void); + return nil; + } + // else fall through! + default: + @throw [NSException exceptionWithName:@"PromiseKit" reason:@"PromiseKit: Unsupported method signature." userInfo:nil]; + } +} + +static id PMKCallVariadicBlock(id frock, id result) { + @try { + return _PMKCallVariadicBlock(frock, result); + } @catch (id thrown) { + if ([thrown isKindOfClass:[NSString class]]) + return thrown; + if ([thrown isKindOfClass:[NSError class]]) + return thrown; + + // we don’t catch objc exceptions: they are meant to crash your app + @throw thrown; + } +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Promise.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Promise.swift new file mode 100644 index 000000000..da9f6aa2b --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Promise.swift @@ -0,0 +1,179 @@ +import class Foundation.Thread +import Dispatch + +/** + A `Promise` is a functional abstraction around a failable asynchronous operation. + - See: `Thenable` + */ +public final class Promise: Thenable, CatchMixin { + let box: Box> + + fileprivate init(box: SealedBox>) { + self.box = box + } + + /** + Initialize a new fulfilled promise. + + We do not provide `init(value:)` because Swift is “greedy” + and would pick that initializer in cases where it should pick + one of the other more specific options leading to Promises with + `T` that is eg: `Error` or worse `(T->Void,Error->Void)` for + uses of our PMK < 4 pending initializer due to Swift trailing + closure syntax (nothing good comes without pain!). + + Though often easy to detect, sometimes these issues would be + hidden by other type inference leading to some nasty bugs in + production. + + In PMK5 we tried to work around this by making the pending + initializer take the form `Promise(.pending)` but this led to + bad migration errors for PMK4 users. Hence instead we quickly + released PMK6 and now only provide this initializer for making + sealed & fulfilled promises. + + Usage is still (usually) good: + + guard foo else { + return .value(bar) + } + */ + public class func value(_ value: T) -> Promise { + return Promise(box: SealedBox(value: .fulfilled(value))) + } + + /// Initialize a new rejected promise. + public init(error: Error) { + box = SealedBox(value: .rejected(error)) + } + + /// Initialize a new promise bound to the provided `Thenable`. + public init(_ bridge: U) where U.T == T { + box = EmptyBox() + bridge.pipe(to: box.seal) + } + + /// Initialize a new promise that can be resolved with the provided `Resolver`. + public init(resolver body: (Resolver) throws -> Void) { + box = EmptyBox() + let resolver = Resolver(box) + do { + try body(resolver) + } catch { + resolver.reject(error) + } + } + + /// - Returns: a tuple of a new pending promise and its `Resolver`. + public class func pending() -> (promise: Promise, resolver: Resolver) { + return { ($0, Resolver($0.box)) }(Promise(.pending)) + } + + /// - See: `Thenable.pipe` + public func pipe(to: @escaping(Result) -> Void) { + switch box.inspect() { + case .pending: + box.inspect { + switch $0 { + case .pending(let handlers): + handlers.append(to) + case .resolved(let value): + to(value) + } + } + case .resolved(let value): + to(value) + } + } + + /// - See: `Thenable.result` + public var result: Result? { + switch box.inspect() { + case .pending: + return nil + case .resolved(let result): + return result + } + } + + init(_: PMKUnambiguousInitializer) { + box = EmptyBox() + } +} + +public extension Promise { + /** + Blocks this thread, so—you know—don’t call this on a serial thread that + any part of your chain may use. Like the main thread for example. + */ + func wait() throws -> T { + + if Thread.isMainThread { + conf.logHandler(LogEvent.waitOnMainThread) + } + + var result = self.result + + if result == nil { + let group = DispatchGroup() + group.enter() + pipe { result = $0; group.leave() } + group.wait() + } + + switch result! { + case .rejected(let error): + throw error + case .fulfilled(let value): + return value + } + } +} + +#if swift(>=3.1) +extension Promise where T == Void { + /// Initializes a new promise fulfilled with `Void` + public convenience init() { + self.init(box: SealedBox(value: .fulfilled(Void()))) + } +} +#endif + + +public extension DispatchQueue { + /** + Asynchronously executes the provided closure on a dispatch queue. + + DispatchQueue.global().async(.promise) { + try md5(input) + }.done { md5 in + //… + } + + - Parameter body: The closure that resolves this promise. + - Returns: A new `Promise` resolved by the result of the provided closure. + - Note: There is no Promise/Thenable version of this due to Swift compiler ambiguity issues. + */ + @available(macOS 10.10, iOS 8.0, tvOS 9.0, watchOS 2.0, *) + final func async(_: PMKNamespacer, group: DispatchGroup? = nil, qos: DispatchQoS = .default, flags: DispatchWorkItemFlags = [], execute body: @escaping () throws -> T) -> Promise { + let promise = Promise(.pending) + async(group: group, qos: qos, flags: flags) { + do { + promise.box.seal(.fulfilled(try body())) + } catch { + promise.box.seal(.rejected(error)) + } + } + return promise + } +} + + +/// used by our extensions to provide unambiguous functions with the same name as the original function +public enum PMKNamespacer { + case promise +} + +enum PMKUnambiguousInitializer { + case pending +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/PromiseKit.h b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/PromiseKit.h new file mode 100644 index 000000000..2651530cb --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/PromiseKit.h @@ -0,0 +1,7 @@ +#import "fwd.h" +#import "AnyPromise.h" + +#import // `FOUNDATION_EXPORT` + +FOUNDATION_EXPORT double PromiseKitVersionNumber; +FOUNDATION_EXPORT const unsigned char PromiseKitVersionString[]; diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Resolver.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Resolver.swift new file mode 100644 index 000000000..78531adbd --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Resolver.swift @@ -0,0 +1,99 @@ +/// An object for resolving promises +public final class Resolver { + let box: Box> + + init(_ box: Box>) { + self.box = box + } + + deinit { + if case .pending = box.inspect() { + conf.logHandler(.pendingPromiseDeallocated) + } + } +} + +public extension Resolver { + /// Fulfills the promise with the provided value + func fulfill(_ value: T) { + box.seal(.fulfilled(value)) + } + + /// Rejects the promise with the provided error + func reject(_ error: Error) { + box.seal(.rejected(error)) + } + + /// Resolves the promise with the provided result + func resolve(_ result: Result) { + box.seal(result) + } + + /// Resolves the promise with the provided value or error + func resolve(_ obj: T?, _ error: Error?) { + if let error = error { + reject(error) + } else if let obj = obj { + fulfill(obj) + } else { + reject(PMKError.invalidCallingConvention) + } + } + + /// Fulfills the promise with the provided value unless the provided error is non-nil + func resolve(_ obj: T, _ error: Error?) { + if let error = error { + reject(error) + } else { + fulfill(obj) + } + } + + /// Resolves the promise, provided for non-conventional value-error ordered completion handlers. + func resolve(_ error: Error?, _ obj: T?) { + resolve(obj, error) + } +} + +#if swift(>=3.1) +extension Resolver where T == Void { + /// Fulfills the promise unless error is non-nil + public func resolve(_ error: Error?) { + if let error = error { + reject(error) + } else { + fulfill(()) + } + } +#if false + // disabled ∵ https://github.com/mxcl/PromiseKit/issues/990 + + /// Fulfills the promise + public func fulfill() { + self.fulfill(()) + } +#else + /// Fulfills the promise + /// - Note: underscore is present due to: https://github.com/mxcl/PromiseKit/issues/990 + public func fulfill_() { + self.fulfill(()) + } +#endif +} +#endif + +public enum Result { + case fulfilled(T) + case rejected(Error) +} + +public extension PromiseKit.Result { + var isFulfilled: Bool { + switch self { + case .fulfilled: + return true + case .rejected: + return false + } + } +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Thenable.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Thenable.swift new file mode 100644 index 000000000..776237207 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/Thenable.swift @@ -0,0 +1,424 @@ +import Dispatch + +/// Thenable represents an asynchronous operation that can be chained. +public protocol Thenable: class { + /// The type of the wrapped value + associatedtype T + + /// `pipe` is immediately executed when this `Thenable` is resolved + func pipe(to: @escaping(Result) -> Void) + + /// The resolved result or nil if pending. + var result: Result? { get } +} + +public extension Thenable { + /** + The provided closure executes when this promise resolves. + + This allows chaining promises. The promise returned by the provided closure is resolved before the promise returned by this closure resolves. + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter body: The closure that executes when this promise fulfills. It must return a promise. + - Returns: A new promise that resolves when the promise returned from the provided closure resolves. For example: + + firstly { + URLSession.shared.dataTask(.promise, with: url1) + }.then { response in + transform(data: response.data) + }.done { transformation in + //… + } + */ + func then(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(T) throws -> U) -> Promise { + let rp = Promise(.pending) + pipe { + switch $0 { + case .fulfilled(let value): + on.async(flags: flags) { + do { + let rv = try body(value) + guard rv !== rp else { throw PMKError.returnedSelf } + rv.pipe(to: rp.box.seal) + } catch { + rp.box.seal(.rejected(error)) + } + } + case .rejected(let error): + rp.box.seal(.rejected(error)) + } + } + return rp + } + + /** + The provided closure is executed when this promise is resolved. + + This is like `then` but it requires the closure to return a non-promise. + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter transform: The closure that is executed when this Promise is fulfilled. It must return a non-promise. + - Returns: A new promise that is resolved with the value returned from the provided closure. For example: + + firstly { + URLSession.shared.dataTask(.promise, with: url1) + }.map { response in + response.data.length + }.done { length in + //… + } + */ + func map(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T) throws -> U) -> Promise { + let rp = Promise(.pending) + pipe { + switch $0 { + case .fulfilled(let value): + on.async(flags: flags) { + do { + rp.box.seal(.fulfilled(try transform(value))) + } catch { + rp.box.seal(.rejected(error)) + } + } + case .rejected(let error): + rp.box.seal(.rejected(error)) + } + } + return rp + } + + /** + The provided closure is executed when this promise is resolved. + + In your closure return an `Optional`, if you return `nil` the resulting promise is rejected with `PMKError.compactMap`, otherwise the promise is fulfilled with the unwrapped value. + + firstly { + URLSession.shared.dataTask(.promise, with: url) + }.compactMap { + try JSONSerialization.jsonObject(with: $0.data) as? [String: String] + }.done { dictionary in + //… + }.catch { + // either `PMKError.compactMap` or a `JSONError` + } + */ + func compactMap(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T) throws -> U?) -> Promise { + let rp = Promise(.pending) + pipe { + switch $0 { + case .fulfilled(let value): + on.async(flags: flags) { + do { + if let rv = try transform(value) { + rp.box.seal(.fulfilled(rv)) + } else { + throw PMKError.compactMap(value, U.self) + } + } catch { + rp.box.seal(.rejected(error)) + } + } + case .rejected(let error): + rp.box.seal(.rejected(error)) + } + } + return rp + } + + /** + The provided closure is executed when this promise is resolved. + + Equivalent to `map { x -> Void in`, but since we force the `Void` return Swift + is happier and gives you less hassle about your closure’s qualification. + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter body: The closure that is executed when this Promise is fulfilled. + - Returns: A new promise fulfilled as `Void`. + + firstly { + URLSession.shared.dataTask(.promise, with: url) + }.done { response in + print(response.data) + } + */ + func done(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(T) throws -> Void) -> Promise { + let rp = Promise(.pending) + pipe { + switch $0 { + case .fulfilled(let value): + on.async(flags: flags) { + do { + try body(value) + rp.box.seal(.fulfilled(())) + } catch { + rp.box.seal(.rejected(error)) + } + } + case .rejected(let error): + rp.box.seal(.rejected(error)) + } + } + return rp + } + + /** + The provided closure is executed when this promise is resolved. + + This is like `done` but it returns the same value that the handler is fed. + `get` immutably accesses the fulfilled value; the returned Promise maintains that value. + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter body: The closure that is executed when this Promise is fulfilled. + - Returns: A new promise that is resolved with the value that the handler is fed. For example: + + firstly { + .value(1) + }.get { foo in + print(foo, " is 1") + }.done { foo in + print(foo, " is 1") + }.done { foo in + print(foo, " is Void") + } + */ + func get(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping (T) throws -> Void) -> Promise { + return map(on: on, flags: flags) { + try body($0) + return $0 + } + } + + /** + The provided closure is executed with promise result. + + This is like `get` but provides the Result of the Promise so you can inspect the value of the chain at this point without causing any side effects. + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter body: The closure that is executed with Result of Promise. + - Returns: A new promise that is resolved with the result that the handler is fed. For example: + + promise.tap{ print($0) }.then{ /*…*/ } + */ + func tap(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(Result) -> Void) -> Promise { + return Promise { seal in + pipe { result in + on.async(flags: flags) { + body(result) + seal.resolve(result) + } + } + } + } + + /// - Returns: a new promise chained off this promise but with its value discarded. + func asVoid() -> Promise { + return map(on: nil) { _ in } + } +} + +public extension Thenable { + /** + - Returns: The error with which this promise was rejected; `nil` if this promise is not rejected. + */ + var error: Error? { + switch result { + case .none: + return nil + case .some(.fulfilled): + return nil + case .some(.rejected(let error)): + return error + } + } + + /** + - Returns: `true` if the promise has not yet resolved. + */ + var isPending: Bool { + return result == nil + } + + /** + - Returns: `true` if the promise has resolved. + */ + var isResolved: Bool { + return !isPending + } + + /** + - Returns: `true` if the promise was fulfilled. + */ + var isFulfilled: Bool { + return value != nil + } + + /** + - Returns: `true` if the promise was rejected. + */ + var isRejected: Bool { + return error != nil + } + + /** + - Returns: The value with which this promise was fulfilled or `nil` if this promise is pending or rejected. + */ + var value: T? { + switch result { + case .none: + return nil + case .some(.fulfilled(let value)): + return value + case .some(.rejected): + return nil + } + } +} + +public extension Thenable where T: Sequence { + /** + `Promise<[T]>` => `T` -> `U` => `Promise<[U]>` + + firstly { + .value([1,2,3]) + }.mapValues { integer in + integer * 2 + }.done { + // $0 => [2,4,6] + } + */ + func mapValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) throws -> U) -> Promise<[U]> { + return map(on: on, flags: flags){ try $0.map(transform) } + } + + /** + `Promise<[T]>` => `T` -> `[U]` => `Promise<[U]>` + + firstly { + .value([1,2,3]) + }.flatMapValues { integer in + [integer, integer] + }.done { + // $0 => [1,1,2,2,3,3] + } + */ + func flatMapValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) throws -> U) -> Promise<[U.Iterator.Element]> { + return map(on: on, flags: flags){ (foo: T) in + try foo.flatMap{ try transform($0) } + } + } + + /** + `Promise<[T]>` => `T` -> `U?` => `Promise<[U]>` + + firstly { + .value(["1","2","a","3"]) + }.compactMapValues { + Int($0) + }.done { + // $0 => [1,2,3] + } + */ + func compactMapValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) throws -> U?) -> Promise<[U]> { + return map(on: on, flags: flags) { foo -> [U] in + #if !swift(>=3.3) || (swift(>=4) && !swift(>=4.1)) + return try foo.flatMap(transform) + #else + return try foo.compactMap(transform) + #endif + } + } + + /** + `Promise<[T]>` => `T` -> `Promise` => `Promise<[U]>` + + firstly { + .value([1,2,3]) + }.thenMap { integer in + .value(integer * 2) + }.done { + // $0 => [2,4,6] + } + */ + func thenMap(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) throws -> U) -> Promise<[U.T]> { + return then(on: on, flags: flags) { + when(fulfilled: try $0.map(transform)) + } + } + + /** + `Promise<[T]>` => `T` -> `Promise<[U]>` => `Promise<[U]>` + + firstly { + .value([1,2,3]) + }.thenFlatMap { integer in + .value([integer, integer]) + }.done { + // $0 => [1,1,2,2,3,3] + } + */ + func thenFlatMap(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) throws -> U) -> Promise<[U.T.Iterator.Element]> where U.T: Sequence { + return then(on: on, flags: flags) { + when(fulfilled: try $0.map(transform)) + }.map(on: nil) { + $0.flatMap{ $0 } + } + } + + /** + `Promise<[T]>` => `T` -> Bool => `Promise<[U]>` + + firstly { + .value([1,2,3]) + }.filterValues { + $0 > 1 + }.done { + // $0 => [2,3] + } + */ + func filterValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ isIncluded: @escaping (T.Iterator.Element) -> Bool) -> Promise<[T.Iterator.Element]> { + return map(on: on, flags: flags) { + $0.filter(isIncluded) + } + } +} + +public extension Thenable where T: Collection { + /// - Returns: a promise fulfilled with the first value of this `Collection` or, if empty, a promise rejected with PMKError.emptySequence. + var firstValue: Promise { + return map(on: nil) { aa in + if let a1 = aa.first { + return a1 + } else { + throw PMKError.emptySequence + } + } + } + + func firstValue(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, where test: @escaping (T.Iterator.Element) -> Bool) -> Promise { + return map(on: on, flags: flags) { + for x in $0 where test(x) { + return x + } + throw PMKError.emptySequence + } + } + + /// - Returns: a promise fulfilled with the last value of this `Collection` or, if empty, a promise rejected with PMKError.emptySequence. + var lastValue: Promise { + return map(on: nil) { aa in + if aa.isEmpty { + throw PMKError.emptySequence + } else { + let i = aa.index(aa.endIndex, offsetBy: -1) + return aa[i] + } + } + } +} + +public extension Thenable where T: Sequence, T.Iterator.Element: Comparable { + /// - Returns: a promise fulfilled with the sorted values of this `Sequence`. + func sortedValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil) -> Promise<[T.Iterator.Element]> { + return map(on: on, flags: flags){ $0.sorted() } + } +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/after.m b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/after.m new file mode 100644 index 000000000..25f9966fc --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/after.m @@ -0,0 +1,14 @@ +#import "AnyPromise.h" +@import Dispatch; +@import Foundation.NSDate; +@import Foundation.NSValue; + +/// @return A promise that fulfills after the specified duration. +AnyPromise *PMKAfter(NSTimeInterval duration) { + return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { + dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)); + dispatch_after(time, dispatch_get_global_queue(0, 0), ^{ + resolve(@(duration)); + }); + }]; +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/after.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/after.swift new file mode 100644 index 000000000..cdaeccd9e --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/after.swift @@ -0,0 +1,46 @@ +import struct Foundation.TimeInterval +import Dispatch + +/** + after(seconds: 1.5).then { + //… + } + +- Returns: A guarantee that resolves after the specified duration. +*/ +public func after(seconds: TimeInterval) -> Guarantee { + let (rg, seal) = Guarantee.pending() + let when = DispatchTime.now() + seconds +#if swift(>=4.0) + q.asyncAfter(deadline: when) { seal(()) } +#else + q.asyncAfter(deadline: when, execute: seal) +#endif + return rg +} + +/** + after(.seconds(2)).then { + //… + } + + - Returns: A guarantee that resolves after the specified duration. +*/ +public func after(_ interval: DispatchTimeInterval) -> Guarantee { + let (rg, seal) = Guarantee.pending() + let when = DispatchTime.now() + interval +#if swift(>=4.0) + q.asyncAfter(deadline: when) { seal(()) } +#else + q.asyncAfter(deadline: when, execute: seal) +#endif + return rg +} + +private var q: DispatchQueue { + if #available(macOS 10.10, iOS 8.0, tvOS 9.0, watchOS 2.0, *) { + return DispatchQueue.global(qos: .default) + } else { + return DispatchQueue.global(priority: .default) + } +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/dispatch_promise.m b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/dispatch_promise.m new file mode 100644 index 000000000..ecb89f711 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/dispatch_promise.m @@ -0,0 +1,10 @@ +#import "AnyPromise.h" +@import Dispatch; + +AnyPromise *dispatch_promise_on(dispatch_queue_t queue, id block) { + return [AnyPromise promiseWithValue:nil].thenOn(queue, block); +} + +AnyPromise *dispatch_promise(id block) { + return dispatch_promise_on(dispatch_get_global_queue(0, 0), block); +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/firstly.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/firstly.swift new file mode 100644 index 000000000..a5b477da1 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/firstly.swift @@ -0,0 +1,39 @@ +import Dispatch + +/** + Judicious use of `firstly` *may* make chains more readable. + + Compare: + + URLSession.shared.dataTask(url: url1).then { + URLSession.shared.dataTask(url: url2) + }.then { + URLSession.shared.dataTask(url: url3) + } + + With: + + firstly { + URLSession.shared.dataTask(url: url1) + }.then { + URLSession.shared.dataTask(url: url2) + }.then { + URLSession.shared.dataTask(url: url3) + } + + - Note: the block you pass excecutes immediately on the current thread/queue. + */ +public func firstly(execute body: () throws -> U) -> Promise { + do { + let rp = Promise(.pending) + try body().pipe(to: rp.box.seal) + return rp + } catch { + return Promise(error: error) + } +} + +/// - See: firstly() +public func firstly(execute body: () -> Guarantee) -> Guarantee { + return body() +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/fwd.h b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/fwd.h new file mode 100644 index 000000000..480d1480e --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/fwd.h @@ -0,0 +1,165 @@ +#import +#import + +@class AnyPromise; +extern NSString * __nonnull const PMKErrorDomain; + +#define PMKFailingPromiseIndexKey @"PMKFailingPromiseIndexKey" +#define PMKJoinPromisesKey @"PMKJoinPromisesKey" + +#define PMKUnexpectedError 1l +#define PMKInvalidUsageError 3l +#define PMKAccessDeniedError 4l +#define PMKOperationFailed 8l +#define PMKTaskError 9l +#define PMKJoinError 10l + + +#ifdef __cplusplus +extern "C" { +#endif + +/** + @return A new promise that resolves after the specified duration. + + @parameter duration The duration in seconds to wait before this promise is resolve. + + For example: + + PMKAfter(1).then(^{ + //… + }); +*/ +extern AnyPromise * __nonnull PMKAfter(NSTimeInterval duration) NS_REFINED_FOR_SWIFT; + + + +/** + `when` is a mechanism for waiting more than one asynchronous task and responding when they are all complete. + + `PMKWhen` accepts varied input. If an array is passed then when those promises fulfill, when’s promise fulfills with an array of fulfillment values. If a dictionary is passed then the same occurs, but when’s promise fulfills with a dictionary of fulfillments keyed as per the input. + + Interestingly, if a single promise is passed then when waits on that single promise, and if a single non-promise object is passed then when fulfills immediately with that object. If the array or dictionary that is passed contains objects that are not promises, then these objects are considered fulfilled promises. The reason we do this is to allow a pattern know as "abstracting away asynchronicity". + + If *any* of the provided promises reject, the returned promise is immediately rejected with that promise’s rejection. The error’s `userInfo` object is supplemented with `PMKFailingPromiseIndexKey`. + + For example: + + PMKWhen(@[promise1, promise2]).then(^(NSArray *results){ + //… + }); + + @warning *Important* In the event of rejection the other promises will continue to resolve and as per any other promise will either fulfill or reject. This is the right pattern for `getter` style asynchronous tasks, but often for `setter` tasks (eg. storing data on a server), you most likely will need to wait on all tasks and then act based on which have succeeded and which have failed. In such situations use `PMKJoin`. + + @param input The input upon which to wait before resolving this promise. + + @return A promise that is resolved with either: + + 1. An array of values from the provided array of promises. + 2. The value from the provided promise. + 3. The provided non-promise object. + + @see PMKJoin + +*/ +extern AnyPromise * __nonnull PMKWhen(id __nonnull input) NS_REFINED_FOR_SWIFT; + + + +/** + Creates a new promise that resolves only when all provided promises have resolved. + + Typically, you should use `PMKWhen`. + + For example: + + PMKJoin(@[promise1, promise2]).then(^(NSArray *resultingValues){ + //… + }).catch(^(NSError *error){ + assert(error.domain == PMKErrorDomain); + assert(error.code == PMKJoinError); + + NSArray *promises = error.userInfo[PMKJoinPromisesKey]; + for (AnyPromise *promise in promises) { + if (promise.rejected) { + //… + } + } + }); + + @param promises An array of promises. + + @return A promise that thens three parameters: + + 1) An array of mixed values and errors from the resolved input. + 2) An array of values from the promises that fulfilled. + 3) An array of errors from the promises that rejected or nil if all promises fulfilled. + + @see when +*/ +AnyPromise *__nonnull PMKJoin(NSArray * __nonnull promises) NS_REFINED_FOR_SWIFT; + + + +/** + Literally hangs this thread until the promise has resolved. + + Do not use hang… unless you are testing, playing or debugging. + + If you use it in production code I will literally and honestly cry like a child. + + @return The resolved value of the promise. + + @warning T SAFE. IT IS NOT SAFE. IT IS NOT SAFE. IT IS NOT SAFE. IT IS NO +*/ +extern id __nullable PMKHang(AnyPromise * __nonnull promise); + + + +/** + Executes the provided block on a background queue. + + dispatch_promise is a convenient way to start a promise chain where the + first step needs to run synchronously on a background queue. + + dispatch_promise(^{ + return md5(input); + }).then(^(NSString *md5){ + NSLog(@"md5: %@", md5); + }); + + @param block The block to be executed in the background. Returning an `NSError` will reject the promise, everything else (including void) fulfills the promise. + + @return A promise resolved with the return value of the provided block. + + @see dispatch_async +*/ +extern AnyPromise * __nonnull dispatch_promise(id __nonnull block) NS_SWIFT_UNAVAILABLE("Use our `DispatchQueue.async` override instead"); + + + +/** + Executes the provided block on the specified background queue. + + dispatch_promise_on(myDispatchQueue, ^{ + return md5(input); + }).then(^(NSString *md5){ + NSLog(@"md5: %@", md5); + }); + + @param block The block to be executed in the background. Returning an `NSError` will reject the promise, everything else (including void) fulfills the promise. + + @return A promise resolved with the return value of the provided block. + + @see dispatch_promise +*/ +extern AnyPromise * __nonnull dispatch_promise_on(dispatch_queue_t __nonnull queue, id __nonnull block) NS_SWIFT_UNAVAILABLE("Use our `DispatchQueue.async` override instead"); + +/** + Returns a new promise that resolves when the value of the first resolved promise in the provided array of promises. +*/ +extern AnyPromise * __nonnull PMKRace(NSArray * __nonnull promises) NS_REFINED_FOR_SWIFT; + +#ifdef __cplusplus +} // Extern C +#endif diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/hang.m b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/hang.m new file mode 100644 index 000000000..913339e51 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/hang.m @@ -0,0 +1,29 @@ +#import "AnyPromise.h" +#import "AnyPromise+Private.h" +@import CoreFoundation.CFRunLoop; + +/** + Suspends the active thread waiting on the provided promise. + + @return The value of the provided promise once resolved. + */ +id PMKHang(AnyPromise *promise) { + if (promise.pending) { + static CFRunLoopSourceContext context; + + CFRunLoopRef runLoop = CFRunLoopGetCurrent(); + CFRunLoopSourceRef runLoopSource = CFRunLoopSourceCreate(NULL, 0, &context); + CFRunLoopAddSource(runLoop, runLoopSource, kCFRunLoopDefaultMode); + + promise.ensure(^{ + CFRunLoopStop(runLoop); + }); + while (promise.pending) { + CFRunLoopRun(); + } + CFRunLoopRemoveSource(runLoop, runLoopSource, kCFRunLoopDefaultMode); + CFRelease(runLoopSource); + } + + return promise.value; +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/hang.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/hang.swift new file mode 100644 index 000000000..53d54decb --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/hang.swift @@ -0,0 +1,55 @@ +import Foundation +import CoreFoundation + +/** + Runs the active run-loop until the provided promise resolves. + + This is for debug and is not a generally safe function to use in your applications. We mostly provide it for use in testing environments. + + Still if you like, study how it works (by reading the sources!) and use at your own risk. + + - Returns: The value of the resolved promise + - Throws: An error, should the promise be rejected + - See: `wait()` +*/ +public func hang(_ promise: Promise) throws -> T { +#if os(Linux) || os(Android) +#if swift(>=4.2) + let runLoopMode: CFRunLoopMode = kCFRunLoopDefaultMode +#else + // isMainThread is not yet implemented on Linux. + let runLoopModeRaw = RunLoopMode.defaultRunLoopMode.rawValue._bridgeToObjectiveC() + let runLoopMode: CFString = unsafeBitCast(runLoopModeRaw, to: CFString.self) +#endif +#else + guard Thread.isMainThread else { + // hang doesn't make sense on threads that aren't the main thread. + // use `.wait()` on those threads. + fatalError("Only call hang() on the main thread.") + } + let runLoopMode: CFRunLoopMode = CFRunLoopMode.defaultMode +#endif + + if promise.isPending { + var context = CFRunLoopSourceContext() + let runLoop = CFRunLoopGetCurrent() + let runLoopSource = CFRunLoopSourceCreate(nil, 0, &context) + CFRunLoopAddSource(runLoop, runLoopSource, runLoopMode) + + _ = promise.ensure { + CFRunLoopStop(runLoop) + } + + while promise.isPending { + CFRunLoopRun() + } + CFRunLoopRemoveSource(runLoop, runLoopSource, runLoopMode) + } + + switch promise.result! { + case .rejected(let error): + throw error + case .fulfilled(let value): + return value + } +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/join.m b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/join.m new file mode 100644 index 000000000..979f092df --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/join.m @@ -0,0 +1,54 @@ +@import Foundation.NSDictionary; +#import "AnyPromise+Private.h" +#import +@import Foundation.NSError; +@import Foundation.NSNull; +#import "PromiseKit.h" +#import + +/** + Waits on all provided promises. + + `PMKWhen` rejects as soon as one of the provided promises rejects. `PMKJoin` waits on all provided promises, then rejects if any of those promises rejects, otherwise it fulfills with values from the provided promises. + + - Returns: A new promise that resolves once all the provided promises resolve. +*/ +AnyPromise *PMKJoin(NSArray *promises) { + if (promises == nil) + return [AnyPromise promiseWithValue:[NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:@{NSLocalizedDescriptionKey: @"PMKJoin(nil)"}]]; + + if (promises.count == 0) + return [AnyPromise promiseWithValue:promises]; + + return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { + NSPointerArray *results = NSPointerArrayMake(promises.count); + __block atomic_int countdown = promises.count; + __block BOOL rejected = NO; + + [promises enumerateObjectsUsingBlock:^(AnyPromise *promise, NSUInteger ii, BOOL *stop) { + [promise __pipe:^(id value) { + + if (IsError(value)) { + rejected = YES; + } + + //FIXME surely this isn't thread safe on multiple cores? + [results replacePointerAtIndex:ii withPointer:(__bridge void *)(value ?: [NSNull null])]; + + atomic_fetch_sub_explicit(&countdown, 1, memory_order_relaxed); + + if (countdown == 0) { + if (!rejected) { + resolve(results.allObjects); + } else { + id userInfo = @{PMKJoinPromisesKey: promises}; + id err = [NSError errorWithDomain:PMKErrorDomain code:PMKJoinError userInfo:userInfo]; + resolve(err); + } + } + }]; + + (void) stop; + }]; + }]; +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/race.m b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/race.m new file mode 100644 index 000000000..cab38ec19 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/race.m @@ -0,0 +1,9 @@ +#import "AnyPromise+Private.h" + +AnyPromise *PMKRace(NSArray *promises) { + return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { + for (AnyPromise *promise in promises) { + [promise __pipe:resolve]; + } + }]; +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/race.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/race.swift new file mode 100644 index 000000000..2b817de26 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/race.swift @@ -0,0 +1,57 @@ +@inline(__always) +private func _race(_ thenables: [U]) -> Promise { + let rp = Promise(.pending) + for thenable in thenables { + thenable.pipe(to: rp.box.seal) + } + return rp +} + +/** + Waits for one promise to resolve + + race(promise1, promise2, promise3).then { winner in + //… + } + + - Returns: The promise that resolves first + - Warning: If the first resolution is a rejection, the returned promise is rejected +*/ +public func race(_ thenables: U...) -> Promise { + return _race(thenables) +} + +/** + Waits for one promise to resolve + + race(promise1, promise2, promise3).then { winner in + //… + } + + - Returns: The promise that resolves first + - Warning: If the first resolution is a rejection, the returned promise is rejected + - Remark: If the provided array is empty the returned promise is rejected with PMKError.badInput +*/ +public func race(_ thenables: [U]) -> Promise { + guard !thenables.isEmpty else { + return Promise(error: PMKError.badInput) + } + return _race(thenables) +} + +/** + Waits for one guarantee to resolve + + race(promise1, promise2, promise3).then { winner in + //… + } + + - Returns: The guarantee that resolves first +*/ +public func race(_ guarantees: Guarantee...) -> Guarantee { + let rg = Guarantee(.pending) + for guarantee in guarantees { + guarantee.pipe(to: rg.box.seal) + } + return rg +} diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/when.m b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/when.m new file mode 100644 index 000000000..43e5feddc --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/when.m @@ -0,0 +1,107 @@ +@import Foundation.NSDictionary; +#import "AnyPromise+Private.h" +@import Foundation.NSProgress; +#import +@import Foundation.NSError; +@import Foundation.NSNull; +#import "PromiseKit.h" + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +// ^^ OSAtomicDecrement32 is deprecated on watchOS + + +// NSProgress resources: +// * https://robots.thoughtbot.com/asynchronous-nsprogress +// * http://oleb.net/blog/2014/03/nsprogress/ +// NSProgress! Beware! +// * https://github.com/AFNetworking/AFNetworking/issues/2261 + +/** + Wait for all promises in a set to resolve. + + @note If *any* of the provided promises reject, the returned promise is immediately rejected with that error. + @warning In the event of rejection the other promises will continue to resolve and, as per any other promise, will either fulfill or reject. This is the right pattern for `getter` style asynchronous tasks, but often for `setter` tasks (eg. storing data on a server), you most likely will need to wait on all tasks and then act based on which have succeeded and which have failed, in such situations use `when(resolved:)`. + @param promises The promises upon which to wait before the returned promise resolves. + @note PMKWhen provides NSProgress. + @return A new promise that resolves when all the provided promises fulfill or one of the provided promises rejects. +*/ +AnyPromise *PMKWhen(id promises) { + if (promises == nil) + return [AnyPromise promiseWithValue:[NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:@{NSLocalizedDescriptionKey: @"PMKWhen(nil)"}]]; + + if ([promises isKindOfClass:[NSArray class]] || [promises isKindOfClass:[NSDictionary class]]) { + if ([promises count] == 0) + return [AnyPromise promiseWithValue:promises]; + } else if ([promises isKindOfClass:[AnyPromise class]]) { + promises = @[promises]; + } else { + return [AnyPromise promiseWithValue:promises]; + } + +#ifndef PMKDisableProgress + NSProgress *progress = [NSProgress progressWithTotalUnitCount:(int64_t)[promises count]]; + progress.pausable = NO; + progress.cancellable = NO; +#else + struct PMKProgress { + int completedUnitCount; + int totalUnitCount; + double fractionCompleted; + }; + __block struct PMKProgress progress; +#endif + + __block int32_t countdown = (int32_t)[promises count]; + BOOL const isdict = [promises isKindOfClass:[NSDictionary class]]; + + return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { + NSInteger index = 0; + + for (__strong id key in promises) { + AnyPromise *promise = isdict ? promises[key] : key; + if (!isdict) key = @(index); + + if (![promise isKindOfClass:[AnyPromise class]]) + promise = [AnyPromise promiseWithValue:promise]; + + [promise __pipe:^(id value){ + if (progress.fractionCompleted >= 1) + return; + + if (IsError(value)) { + progress.completedUnitCount = progress.totalUnitCount; + + NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:[(NSError *)value userInfo] ?: @{}]; + userInfo[PMKFailingPromiseIndexKey] = key; + [userInfo setObject:value forKey:NSUnderlyingErrorKey]; + id err = [[NSError alloc] initWithDomain:[value domain] code:[value code] userInfo:userInfo]; + resolve(err); + } + else if (OSAtomicDecrement32(&countdown) == 0) { + progress.completedUnitCount = progress.totalUnitCount; + + id results; + if (isdict) { + results = [NSMutableDictionary new]; + for (id key in promises) { + id promise = promises[key]; + results[key] = IsPromise(promise) ? ((AnyPromise *)promise).value : promise; + } + } else { + results = [NSMutableArray new]; + for (AnyPromise *promise in promises) { + id value = IsPromise(promise) ? (promise.value ?: [NSNull null]) : promise; + [results addObject:value]; + } + } + resolve(results); + } else { + progress.completedUnitCount++; + } + }]; + } + }]; +} + +#pragma GCC diagnostic pop diff --git a/Example/Web3supportBrowser/Pods/PromiseKit/Sources/when.swift b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/when.swift new file mode 100644 index 000000000..0913c64f3 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/PromiseKit/Sources/when.swift @@ -0,0 +1,262 @@ +import Foundation +import Dispatch + +private func _when(_ thenables: [U]) -> Promise { + var countdown = thenables.count + guard countdown > 0 else { + return .value(Void()) + } + + let rp = Promise(.pending) + +#if PMKDisableProgress || os(Linux) + var progress: (completedUnitCount: Int, totalUnitCount: Int) = (0, 0) +#else + let progress = Progress(totalUnitCount: Int64(thenables.count)) + progress.isCancellable = false + progress.isPausable = false +#endif + + let barrier = DispatchQueue(label: "org.promisekit.barrier.when", attributes: .concurrent) + + for promise in thenables { + promise.pipe { result in + barrier.sync(flags: .barrier) { + switch result { + case .rejected(let error): + if rp.isPending { + progress.completedUnitCount = progress.totalUnitCount + rp.box.seal(.rejected(error)) + } + case .fulfilled: + guard rp.isPending else { return } + progress.completedUnitCount += 1 + countdown -= 1 + if countdown == 0 { + rp.box.seal(.fulfilled(())) + } + } + } + } + } + + return rp +} + +/** + Wait for all promises in a set to fulfill. + + For example: + + when(fulfilled: promise1, promise2).then { results in + //… + }.catch { error in + switch error { + case URLError.notConnectedToInternet: + //… + case CLError.denied: + //… + } + } + + - Note: If *any* of the provided promises reject, the returned promise is immediately rejected with that error. + - Warning: In the event of rejection the other promises will continue to resolve and, as per any other promise, will either fulfill or reject. This is the right pattern for `getter` style asynchronous tasks, but often for `setter` tasks (eg. storing data on a server), you most likely will need to wait on all tasks and then act based on which have succeeded and which have failed, in such situations use `when(resolved:)`. + - Parameter promises: The promises upon which to wait before the returned promise resolves. + - Returns: A new promise that resolves when all the provided promises fulfill or one of the provided promises rejects. + - Note: `when` provides `NSProgress`. + - SeeAlso: `when(resolved:)` +*/ +public func when(fulfilled thenables: [U]) -> Promise<[U.T]> { + return _when(thenables).map(on: nil) { thenables.map{ $0.value! } } +} + +/// Wait for all promises in a set to fulfill. +public func when(fulfilled promises: U...) -> Promise where U.T == Void { + return _when(promises) +} + +/// Wait for all promises in a set to fulfill. +public func when(fulfilled promises: [U]) -> Promise where U.T == Void { + return _when(promises) +} + +/// Wait for all promises in a set to fulfill. +public func when(fulfilled pu: U, _ pv: V) -> Promise<(U.T, V.T)> { + return _when([pu.asVoid(), pv.asVoid()]).map(on: nil) { (pu.value!, pv.value!) } +} + +/// Wait for all promises in a set to fulfill. +public func when(fulfilled pu: U, _ pv: V, _ pw: W) -> Promise<(U.T, V.T, W.T)> { + return _when([pu.asVoid(), pv.asVoid(), pw.asVoid()]).map(on: nil) { (pu.value!, pv.value!, pw.value!) } +} + +/// Wait for all promises in a set to fulfill. +public func when(fulfilled pu: U, _ pv: V, _ pw: W, _ px: X) -> Promise<(U.T, V.T, W.T, X.T)> { + return _when([pu.asVoid(), pv.asVoid(), pw.asVoid(), px.asVoid()]).map(on: nil) { (pu.value!, pv.value!, pw.value!, px.value!) } +} + +/// Wait for all promises in a set to fulfill. +public func when(fulfilled pu: U, _ pv: V, _ pw: W, _ px: X, _ py: Y) -> Promise<(U.T, V.T, W.T, X.T, Y.T)> { + return _when([pu.asVoid(), pv.asVoid(), pw.asVoid(), px.asVoid(), py.asVoid()]).map(on: nil) { (pu.value!, pv.value!, pw.value!, px.value!, py.value!) } +} + +/** + Generate promises at a limited rate and wait for all to fulfill. + + For example: + + func downloadFile(url: URL) -> Promise { + // ... + } + + let urls: [URL] = /*…*/ + let urlGenerator = urls.makeIterator() + + let generator = AnyIterator> { + guard url = urlGenerator.next() else { + return nil + } + return downloadFile(url) + } + + when(generator, concurrently: 3).done { datas in + // ... + } + + No more than three downloads will occur simultaneously. + + - Note: The generator is called *serially* on a *background* queue. + - Warning: Refer to the warnings on `when(fulfilled:)` + - Parameter promiseGenerator: Generator of promises. + - Returns: A new promise that resolves when all the provided promises fulfill or one of the provided promises rejects. + - SeeAlso: `when(resolved:)` + */ + +public func when(fulfilled promiseIterator: It, concurrently: Int) -> Promise<[It.Element.T]> where It.Element: Thenable { + + guard concurrently > 0 else { + return Promise(error: PMKError.badInput) + } + + var generator = promiseIterator + var root = Promise<[It.Element.T]>.pending() + var pendingPromises = 0 + var promises: [It.Element] = [] + + let barrier = DispatchQueue(label: "org.promisekit.barrier.when", attributes: [.concurrent]) + + func dequeue() { + guard root.promise.isPending else { return } // don’t continue dequeueing if root has been rejected + + var shouldDequeue = false + barrier.sync { + shouldDequeue = pendingPromises < concurrently + } + guard shouldDequeue else { return } + + var index: Int! + var promise: It.Element! + + barrier.sync(flags: .barrier) { + guard let next = generator.next() else { return } + + promise = next + index = promises.count + + pendingPromises += 1 + promises.append(next) + } + + func testDone() { + barrier.sync { + if pendingPromises == 0 { + #if !swift(>=3.3) || (swift(>=4) && !swift(>=4.1)) + root.resolver.fulfill(promises.flatMap{ $0.value }) + #else + root.resolver.fulfill(promises.compactMap{ $0.value }) + #endif + } + } + } + + guard promise != nil else { + return testDone() + } + + promise.pipe { resolution in + barrier.sync(flags: .barrier) { + pendingPromises -= 1 + } + + switch resolution { + case .fulfilled: + dequeue() + testDone() + case .rejected(let error): + root.resolver.reject(error) + } + } + + dequeue() + } + + dequeue() + + return root.promise +} + +/** + Waits on all provided promises. + + `when(fulfilled:)` rejects as soon as one of the provided promises rejects. `when(resolved:)` waits on all provided promises whatever their result, and then provides an array of `Result` so you can individually inspect the results. As a consequence this function returns a `Guarantee`, ie. errors are lifted from the individual promises into the results array of the returned `Guarantee`. + + when(resolved: promise1, promise2, promise3).then { results in + for result in results where case .fulfilled(let value) { + //… + } + }.catch { error in + // invalid! Never rejects + } + + - Returns: A new promise that resolves once all the provided promises resolve. The array is ordered the same as the input, ie. the result order is *not* resolution order. + - Note: we do not provide tuple variants for `when(resolved:)` but will accept a pull-request + - Remark: Doesn't take Thenable due to protocol `associatedtype` paradox +*/ +public func when(resolved promises: Promise...) -> Guarantee<[Result]> { + return when(resolved: promises) +} + +/// - See: `when(resolved: Promise...)` +public func when(resolved promises: [Promise]) -> Guarantee<[Result]> { + guard !promises.isEmpty else { + return .value([]) + } + + var countdown = promises.count + let barrier = DispatchQueue(label: "org.promisekit.barrier.join", attributes: .concurrent) + + let rg = Guarantee<[Result]>(.pending) + for promise in promises { + promise.pipe { result in + barrier.sync(flags: .barrier) { + countdown -= 1 + } + barrier.sync { + if countdown == 0 { + rg.box.seal(promises.map{ $0.result! }) + } + } + } + } + return rg +} + +/// Waits on all provided Guarantees. +public func when(_ guarantees: Guarantee...) -> Guarantee { + return when(guarantees: guarantees) +} + +// Waits on all provided Guarantees. +public func when(guarantees: [Guarantee]) -> Guarantee { + return when(fulfilled: guarantees).recover{ _ in }.asVoid() +} diff --git a/Example/Web3supportBrowser/Pods/Starscream/LICENSE b/Example/Web3supportBrowser/Pods/Starscream/LICENSE new file mode 100644 index 000000000..d6ab2f1f7 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Starscream/LICENSE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + Copyright (c) 2014-2016 Dalton Cherry. + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. \ No newline at end of file diff --git a/Example/Web3supportBrowser/Pods/Starscream/README.md b/Example/Web3supportBrowser/Pods/Starscream/README.md new file mode 100644 index 000000000..90a7e0e6c --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Starscream/README.md @@ -0,0 +1,438 @@ +![starscream](https://raw.githubusercontent.com/daltoniam/starscream/assets/starscream.jpg) + +Starscream is a conforming WebSocket ([RFC 6455](http://tools.ietf.org/html/rfc6455)) client library in Swift. + +Its Objective-C counterpart can be found here: [Jetfire](https://github.com/acmacalister/jetfire) + +## Features + +- Conforms to all of the base [Autobahn test suite](http://autobahn.ws/testsuite/). +- Nonblocking. Everything happens in the background, thanks to GCD. +- TLS/WSS support. +- Compression Extensions support ([RFC 7692](https://tools.ietf.org/html/rfc7692)) +- Simple concise codebase at just a few hundred LOC. + +## Example + +First thing is to import the framework. See the Installation instructions on how to add the framework to your project. + +```swift +import Starscream +``` + +Once imported, you can open a connection to your WebSocket server. Note that `socket` is probably best as a property, so it doesn't get deallocated right after being setup. + +```swift +socket = WebSocket(url: URL(string: "ws://localhost:8080/")!) +socket.delegate = self +socket.connect() +``` + +After you are connected, there are some delegate methods that we need to implement. + +### websocketDidConnect + +websocketDidConnect is called as soon as the client connects to the server. + +```swift +func websocketDidConnect(socket: WebSocketClient) { + print("websocket is connected") +} +``` + +### websocketDidDisconnect + +websocketDidDisconnect is called as soon as the client is disconnected from the server. + +```swift +func websocketDidDisconnect(socket: WebSocketClient, error: Error?) { + print("websocket is disconnected: \(error?.localizedDescription)") +} +``` + +### websocketDidReceiveMessage + +websocketDidReceiveMessage is called when the client gets a text frame from the connection. + +```swift +func websocketDidReceiveMessage(socket: WebSocketClient, text: String) { + print("got some text: \(text)") +} +``` + +### websocketDidReceiveData + +websocketDidReceiveData is called when the client gets a binary frame from the connection. + +```swift +func websocketDidReceiveData(socket: WebSocketClient, data: Data) { + print("got some data: \(data.count)") +} +``` + +### Optional: websocketDidReceivePong *(required protocol: WebSocketPongDelegate)* + +websocketDidReceivePong is called when the client gets a pong response from the connection. You need to implement the WebSocketPongDelegate protocol and set an additional delegate, eg: ` socket.pongDelegate = self` + +```swift +func websocketDidReceivePong(socket: WebSocketClient, data: Data?) { + print("Got pong! Maybe some data: \(data?.count)") +} +``` + +Or you can use closures. + +```swift +socket = WebSocket(url: URL(string: "ws://localhost:8080/")!) +//websocketDidConnect +socket.onConnect = { + print("websocket is connected") +} +//websocketDidDisconnect +socket.onDisconnect = { (error: Error?) in + print("websocket is disconnected: \(error?.localizedDescription)") +} +//websocketDidReceiveMessage +socket.onText = { (text: String) in + print("got some text: \(text)") +} +//websocketDidReceiveData +socket.onData = { (data: Data) in + print("got some data: \(data.count)") +} +//you could do onPong as well. +socket.connect() +``` + +One more: you can listen to socket connection and disconnection via notifications. Starscream posts `WebsocketDidConnectNotification` and `WebsocketDidDisconnectNotification`. You can find an `Error` that caused the disconection by accessing `WebsocketDisconnectionErrorKeyName` on notification `userInfo`. + + +## The delegate methods give you a simple way to handle data from the server, but how do you send data? + +### write a binary frame + +The writeData method gives you a simple way to send `Data` (binary) data to the server. + +```swift +socket.write(data: data) //write some Data over the socket! +``` + +### write a string frame + +The writeString method is the same as writeData, but sends text/string. + +```swift +socket.write(string: "Hi Server!") //example on how to write text over the socket! +``` + +### write a ping frame + +The writePing method is the same as write, but sends a ping control frame. + +```swift +socket.write(ping: Data()) //example on how to write a ping control frame over the socket! +``` + +### write a pong frame + + +the writePong method is the same as writePing, but sends a pong control frame. + +```swift +socket.write(pong: Data()) //example on how to write a pong control frame over the socket! +``` + +Starscream will automatically respond to incoming `ping` control frames so you do not need to manually send `pong`s. + +However if for some reason you need to control this process you can turn off the automatic `ping` response by disabling `respondToPingWithPong`. + +```swift +socket.respondToPingWithPong = false //Do not automaticaly respond to incoming pings with pongs. +``` + +In most cases you will not need to do this. + +### disconnect + +The disconnect method does what you would expect and closes the socket. + +```swift +socket.disconnect() +``` + +The socket can be forcefully closed, by specifying a timeout (in milliseconds). A timeout of zero will also close the socket immediately without waiting on the server. + +```swift +socket.disconnect(forceTimeout: 10, closeCode: CloseCode.normal.rawValue) +``` + +### isConnected + +Returns if the socket is connected or not. + +```swift +if socket.isConnected { + // do cool stuff. +} +``` + +### Custom Headers + +You can also override the default websocket headers with your own custom ones like so: + +```swift +var request = URLRequest(url: URL(string: "ws://localhost:8080/")!) +request.timeoutInterval = 5 +request.setValue("someother protocols", forHTTPHeaderField: "Sec-WebSocket-Protocol") +request.setValue("14", forHTTPHeaderField: "Sec-WebSocket-Version") +request.setValue("Everything is Awesome!", forHTTPHeaderField: "My-Awesome-Header") +let socket = WebSocket(request: request) +``` + +### Custom HTTP Method + +Your server may use a different HTTP method when connecting to the websocket: + +```swift +var request = URLRequest(url: URL(string: "ws://localhost:8080/")!) +request.httpMethod = "POST" +request.timeoutInterval = 5 +let socket = WebSocket(request: request) +``` + +### Protocols + +If you need to specify a protocol, simple add it to the init: + +```swift +//chat and superchat are the example protocols here +socket = WebSocket(url: URL(string: "ws://localhost:8080/")!, protocols: ["chat","superchat"]) +socket.delegate = self +socket.connect() +``` + +### Self Signed SSL + +```swift +socket = WebSocket(url: URL(string: "ws://localhost:8080/")!, protocols: ["chat","superchat"]) + +//set this if you want to ignore SSL cert validation, so a self signed SSL certificate can be used. +socket.disableSSLCertValidation = true +``` + +### SSL Pinning + +SSL Pinning is also supported in Starscream. + +```swift +socket = WebSocket(url: URL(string: "ws://localhost:8080/")!, protocols: ["chat","superchat"]) +let data = ... //load your certificate from disk +socket.security = SSLSecurity(certs: [SSLCert(data: data)], usePublicKeys: true) +//socket.security = SSLSecurity() //uses the .cer files in your app's bundle +``` +You load either a `Data` blob of your certificate or you can use a `SecKeyRef` if you have a public key you want to use. The `usePublicKeys` bool is whether to use the certificates for validation or the public keys. The public keys will be extracted from the certificates automatically if `usePublicKeys` is choosen. + +### SSL Cipher Suites + +To use an SSL encrypted connection, you need to tell Starscream about the cipher suites your server supports. + +```swift +socket = WebSocket(url: URL(string: "wss://localhost:8080/")!, protocols: ["chat","superchat"]) + +// Set enabled cipher suites to AES 256 and AES 128 +socket.enabledSSLCipherSuites = [TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256] +``` + +If you don't know which cipher suites are supported by your server, you can try pointing [SSL Labs](https://www.ssllabs.com/ssltest/) at it and checking the results. + +### Compression Extensions + +Compression Extensions ([RFC 7692](https://tools.ietf.org/html/rfc7692)) is supported in Starscream. Compression is enabled by default, however compression will only be used if it is supported by the server as well. You may enable or disable compression via the `.enableCompression` property: + +```swift +socket = WebSocket(url: URL(string: "ws://localhost:8080/")!) +socket.enableCompression = false +``` + +Compression should be disabled if your application is transmitting already-compressed, random, or other uncompressable data. + +### Custom Queue + +A custom queue can be specified when delegate methods are called. By default `DispatchQueue.main` is used, thus making all delegate methods calls run on the main thread. It is important to note that all WebSocket processing is done on a background thread, only the delegate method calls are changed when modifying the queue. The actual processing is always on a background thread and will not pause your app. + +```swift +socket = WebSocket(url: URL(string: "ws://localhost:8080/")!, protocols: ["chat","superchat"]) +//create a custom queue +socket.callbackQueue = DispatchQueue(label: "com.vluxe.starscream.myapp") +``` + +## Example Project + +Check out the SimpleTest project in the examples directory to see how to setup a simple connection to a WebSocket server. + +## Requirements + +Starscream works with iOS 7/OSX 10.9 or above. It is recommended to use iOS 8/10.10 or above for CocoaPods/framework support. To use Starscream with a project targeting iOS 7, you must include all Swift files directly in your project. + +## Installation + +### CocoaPods + +Check out [Get Started](http://cocoapods.org/) tab on [cocoapods.org](http://cocoapods.org/). + +To use Starscream in your project add the following 'Podfile' to your project + + source 'https://github.com/CocoaPods/Specs.git' + platform :ios, '9.0' + use_frameworks! + + pod 'Starscream', '~> 3.0.2' + +Then run: + + pod install + +### Carthage + +Check out the [Carthage](https://github.com/Carthage/Carthage) docs on how to add a install. The `Starscream` framework is already setup with shared schemes. + +[Carthage Install](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application) + +You can install Carthage with [Homebrew](http://brew.sh/) using the following command: + +```bash +$ brew update +$ brew install carthage +``` + +To integrate Starscream into your Xcode project using Carthage, specify it in your `Cartfile`: + +``` +github "daltoniam/Starscream" >= 3.0.2 +``` + +### Accio + +Check out the [Accio](https://github.com/JamitLabs/Accio) docs on how to add a install. + +Add the following to your Package.swift: + +```swift +.package(url: "https://github.com/daltoniam/Starscream.git", .upToNextMajor(from: "3.1.0")), +``` + +Next, add `Starscream` to your App targets dependencies like so: + +```swift +.target( + name: "App", + dependencies: [ + "Starscream", + ] +), +``` + +Then run `accio update`. + +### Rogue + +First see the [installation docs](https://github.com/acmacalister/Rogue) for how to install Rogue. + +To install Starscream run the command below in the directory you created the rogue file. + +``` +rogue add https://github.com/daltoniam/Starscream +``` + +Next open the `libs` folder and add the `Starscream.xcodeproj` to your Xcode project. Once that is complete, in your "Build Phases" add the `Starscream.framework` to your "Link Binary with Libraries" phase. Make sure to add the `libs` folder to your `.gitignore` file. + +### Swift Package Manager + +The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. + +Once you have your Swift package set up, adding Starscream as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. + +```swift +dependencies: [ + .Package(url: "https://github.com/daltoniam/Starscream.git", majorVersion: 3) +] +``` + +### Other + +Simply grab the framework (either via git submodule or another package manager). + +Add the `Starscream.xcodeproj` to your Xcode project. Once that is complete, in your "Build Phases" add the `Starscream.framework` to your "Link Binary with Libraries" phase. + +### Add Copy Frameworks Phase + +If you are running this in an OSX app or on a physical iOS device you will need to make sure you add the `Starscream.framework` to be included in your app bundle. To do this, in Xcode, navigate to the target configuration window by clicking on the blue project icon, and selecting the application target under the "Targets" heading in the sidebar. In the tab bar at the top of that window, open the "Build Phases" panel. Expand the "Link Binary with Libraries" group, and add `Starscream.framework`. Click on the + button at the top left of the panel and select "New Copy Files Phase". Rename this new phase to "Copy Frameworks", set the "Destination" to "Frameworks", and add `Starscream.framework` respectively. + + +## WebSocketAdvancedDelegate +The advanced delegate acts just like the simpler delegate but provides some additional information on the connection and incoming frames. + +```swift +socket.advancedDelegate = self +``` + +In most cases you do not need the extra info and should use the normal delegate. + +#### websocketDidReceiveMessage +```swift +func websocketDidReceiveMessage(socket: WebSocketClient, text: String, response: WebSocket.WSResponse) { + print("got some text: \(text)") + print("First frame for this message arrived on \(response.firstFrame)") +} +``` + +#### websocketDidReceiveData +```swift +func websocketDidReceiveData(socket: WebSocketClient, data: Date, response: WebSocket.WSResponse) { + print("got some data it long: \(data.count)") + print("A total of \(response.frameCount) frames were used to send this data") +} +``` + +#### websocketHttpUpgrade +These methods are called when the HTTP upgrade request is sent and when the response returns. +```swift +func websocketHttpUpgrade(socket: WebSocketClient, request: CFHTTPMessage) { + print("the http request was sent we can check the raw http if we need to") +} +``` + +```swift +func websocketHttpUpgrade(socket: WebSocketClient, response: CFHTTPMessage) { + print("the http response has returned.") +} +``` + +## Swift versions + +* Swift 4.2 - 3.0.6 + +## KNOWN ISSUES +- WatchOS does not have the the CFNetwork String constants to modify the stream's SSL behavior. It will be the default Foundation SSL behavior. This means watchOS CANNOT use `SSLCiphers`, `disableSSLCertValidation`, or SSL pinning. All these values set on watchOS will do nothing. +- Linux does not have the security framework, so it CANNOT use SSL pinning or `SSLCiphers` either. + + +## TODOs + +- [ ] Add Unit Tests - Local WebSocket server that runs against Autobahn + +## License + +Starscream is licensed under the Apache v2 License. + +## Contact + +### Dalton Cherry +* https://github.com/daltoniam +* http://twitter.com/daltoniam +* http://daltoniam.com + +### Austin Cherry ### +* https://github.com/acmacalister +* http://twitter.com/acmacalister +* http://austincherry.me diff --git a/Example/Web3supportBrowser/Pods/Starscream/Sources/Starscream/Compression.swift b/Example/Web3supportBrowser/Pods/Starscream/Sources/Starscream/Compression.swift new file mode 100644 index 000000000..ab6579022 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Starscream/Sources/Starscream/Compression.swift @@ -0,0 +1,177 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Compression.swift +// +// Created by Joseph Ross on 7/16/14. +// Copyright © 2017 Joseph Ross. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Compression implementation is implemented in conformance with RFC 7692 Compression Extensions +// for WebSocket: https://tools.ietf.org/html/rfc7692 +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation +import zlib + +class Decompressor { + private var strm = z_stream() + private var buffer = [UInt8](repeating: 0, count: 0x2000) + private var inflateInitialized = false + private let windowBits:Int + + init?(windowBits:Int) { + self.windowBits = windowBits + guard initInflate() else { return nil } + } + + private func initInflate() -> Bool { + if Z_OK == inflateInit2_(&strm, -CInt(windowBits), + ZLIB_VERSION, CInt(MemoryLayout.size)) + { + inflateInitialized = true + return true + } + return false + } + + func reset() throws { + teardownInflate() + guard initInflate() else { throw WSError(type: .compressionError, message: "Error for decompressor on reset", code: 0) } + } + + func decompress(_ data: Data, finish: Bool) throws -> Data { + return try data.withUnsafeBytes { (bytes:UnsafePointer) -> Data in + return try decompress(bytes: bytes, count: data.count, finish: finish) + } + } + + func decompress(bytes: UnsafePointer, count: Int, finish: Bool) throws -> Data { + var decompressed = Data() + try decompress(bytes: bytes, count: count, out: &decompressed) + + if finish { + let tail:[UInt8] = [0x00, 0x00, 0xFF, 0xFF] + try decompress(bytes: tail, count: tail.count, out: &decompressed) + } + + return decompressed + + } + + private func decompress(bytes: UnsafePointer, count: Int, out:inout Data) throws { + var res:CInt = 0 + strm.next_in = UnsafeMutablePointer(mutating: bytes) + strm.avail_in = CUnsignedInt(count) + + repeat { + strm.next_out = UnsafeMutablePointer(&buffer) + strm.avail_out = CUnsignedInt(buffer.count) + + res = inflate(&strm, 0) + + let byteCount = buffer.count - Int(strm.avail_out) + out.append(buffer, count: byteCount) + } while res == Z_OK && strm.avail_out == 0 + + guard (res == Z_OK && strm.avail_out > 0) + || (res == Z_BUF_ERROR && Int(strm.avail_out) == buffer.count) + else { + throw WSError(type: .compressionError, message: "Error on decompressing", code: 0) + } + } + + private func teardownInflate() { + if inflateInitialized, Z_OK == inflateEnd(&strm) { + inflateInitialized = false + } + } + + deinit { + teardownInflate() + } +} + +class Compressor { + private var strm = z_stream() + private var buffer = [UInt8](repeating: 0, count: 0x2000) + private var deflateInitialized = false + private let windowBits:Int + + init?(windowBits: Int) { + self.windowBits = windowBits + guard initDeflate() else { return nil } + } + + private func initDeflate() -> Bool { + if Z_OK == deflateInit2_(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, + -CInt(windowBits), 8, Z_DEFAULT_STRATEGY, + ZLIB_VERSION, CInt(MemoryLayout.size)) + { + deflateInitialized = true + return true + } + return false + } + + func reset() throws { + teardownDeflate() + guard initDeflate() else { throw WSError(type: .compressionError, message: "Error for compressor on reset", code: 0) } + } + + func compress(_ data: Data) throws -> Data { + var compressed = Data() + var res:CInt = 0 + data.withUnsafeBytes { (ptr:UnsafePointer) -> Void in + strm.next_in = UnsafeMutablePointer(mutating: ptr) + strm.avail_in = CUnsignedInt(data.count) + + repeat { + strm.next_out = UnsafeMutablePointer(&buffer) + strm.avail_out = CUnsignedInt(buffer.count) + + res = deflate(&strm, Z_SYNC_FLUSH) + + let byteCount = buffer.count - Int(strm.avail_out) + compressed.append(buffer, count: byteCount) + } + while res == Z_OK && strm.avail_out == 0 + + } + + guard res == Z_OK && strm.avail_out > 0 + || (res == Z_BUF_ERROR && Int(strm.avail_out) == buffer.count) + else { + throw WSError(type: .compressionError, message: "Error on compressing", code: 0) + } + + compressed.removeLast(4) + return compressed + } + + private func teardownDeflate() { + if deflateInitialized, Z_OK == deflateEnd(&strm) { + deflateInitialized = false + } + } + + deinit { + teardownDeflate() + } +} + diff --git a/Example/Web3supportBrowser/Pods/Starscream/Sources/Starscream/SSLClientCertificate.swift b/Example/Web3supportBrowser/Pods/Starscream/Sources/Starscream/SSLClientCertificate.swift new file mode 100644 index 000000000..341091222 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Starscream/Sources/Starscream/SSLClientCertificate.swift @@ -0,0 +1,92 @@ +// +// SSLClientCertificate.swift +// Starscream +// +// Created by Tomasz Trela on 08/03/2018. +// Copyright © 2018 Vluxe. All rights reserved. +// + +import Foundation + +public struct SSLClientCertificateError: LocalizedError { + public var errorDescription: String? + + init(errorDescription: String) { + self.errorDescription = errorDescription + } +} + +public class SSLClientCertificate { + internal let streamSSLCertificates: NSArray + + /** + Convenience init. + - parameter pkcs12Path: Path to pkcs12 file containing private key and X.509 ceritifacte (.p12) + - parameter password: file password, see **kSecImportExportPassphrase** + */ + public convenience init(pkcs12Path: String, password: String) throws { + let pkcs12Url = URL(fileURLWithPath: pkcs12Path) + do { + try self.init(pkcs12Url: pkcs12Url, password: password) + } catch { + throw error + } + } + + /** + Designated init. For more information, see SSLSetCertificate() in Security/SecureTransport.h. + - parameter identity: SecIdentityRef, see **kCFStreamSSLCertificates** + - parameter identityCertificate: CFArray of SecCertificateRefs, see **kCFStreamSSLCertificates** + */ + public init(identity: SecIdentity, identityCertificate: SecCertificate) { + self.streamSSLCertificates = NSArray(objects: identity, identityCertificate) + } + + /** + Convenience init. + - parameter pkcs12Url: URL to pkcs12 file containing private key and X.509 ceritifacte (.p12) + - parameter password: file password, see **kSecImportExportPassphrase** + */ + public convenience init(pkcs12Url: URL, password: String) throws { + let importOptions = [kSecImportExportPassphrase as String : password] as CFDictionary + do { + try self.init(pkcs12Url: pkcs12Url, importOptions: importOptions) + } catch { + throw error + } + } + + /** + Designated init. + - parameter pkcs12Url: URL to pkcs12 file containing private key and X.509 ceritifacte (.p12) + - parameter importOptions: A dictionary containing import options. A + kSecImportExportPassphrase entry is required at minimum. Only password-based + PKCS12 blobs are currently supported. See **SecImportExport.h** + */ + public init(pkcs12Url: URL, importOptions: CFDictionary) throws { + do { + let pkcs12Data = try Data(contentsOf: pkcs12Url) + var rawIdentitiesAndCertificates: CFArray? + let pkcs12CFData: CFData = pkcs12Data as CFData + let importStatus = SecPKCS12Import(pkcs12CFData, importOptions, &rawIdentitiesAndCertificates) + + guard importStatus == errSecSuccess else { + throw SSLClientCertificateError(errorDescription: "(Starscream) Error during 'SecPKCS12Import', see 'SecBase.h' - OSStatus: \(importStatus)") + } + guard let identitiyAndCertificate = (rawIdentitiesAndCertificates as? Array>)?.first else { + throw SSLClientCertificateError(errorDescription: "(Starscream) Error - PKCS12 file is empty") + } + + let identity = identitiyAndCertificate[kSecImportItemIdentity as String] as! SecIdentity + var identityCertificate: SecCertificate? + let copyStatus = SecIdentityCopyCertificate(identity, &identityCertificate) + guard copyStatus == errSecSuccess else { + throw SSLClientCertificateError(errorDescription: "(Starscream) Error during 'SecIdentityCopyCertificate', see 'SecBase.h' - OSStatus: \(copyStatus)") + } + self.streamSSLCertificates = NSArray(objects: identity, identityCertificate!) + } catch { + throw error + } + } +} + diff --git a/Example/Web3supportBrowser/Pods/Starscream/Sources/Starscream/SSLSecurity.swift b/Example/Web3supportBrowser/Pods/Starscream/Sources/Starscream/SSLSecurity.swift new file mode 100644 index 000000000..6a14dd159 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Starscream/Sources/Starscream/SSLSecurity.swift @@ -0,0 +1,266 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// SSLSecurity.swift +// Starscream +// +// Created by Dalton Cherry on 5/16/15. +// Copyright (c) 2014-2016 Dalton Cherry. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// +#if os(Linux) +#else +import Foundation +import Security + +public protocol SSLTrustValidator { + func isValid(_ trust: SecTrust, domain: String?) -> Bool +} + +open class SSLCert { + var certData: Data? + var key: SecKey? + + /** + Designated init for certificates + + - parameter data: is the binary data of the certificate + + - returns: a representation security object to be used with + */ + public init(data: Data) { + self.certData = data + } + + /** + Designated init for public keys + + - parameter key: is the public key to be used + + - returns: a representation security object to be used with + */ + public init(key: SecKey) { + self.key = key + } +} + +open class SSLSecurity : SSLTrustValidator { + public var validatedDN = true //should the domain name be validated? + public var validateEntireChain = true //should the entire cert chain be validated + + var isReady = false //is the key processing done? + var certificates: [Data]? //the certificates + var pubKeys: [SecKey]? //the public keys + var usePublicKeys = false //use public keys or certificate validation? + + /** + Use certs from main app bundle + + - parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation + + - returns: a representation security object to be used with + */ + public convenience init(usePublicKeys: Bool = false) { + let paths = Bundle.main.paths(forResourcesOfType: "cer", inDirectory: ".") + + let certs = paths.reduce([SSLCert]()) { (certs: [SSLCert], path: String) -> [SSLCert] in + var certs = certs + if let data = NSData(contentsOfFile: path) { + certs.append(SSLCert(data: data as Data)) + } + return certs + } + + self.init(certs: certs, usePublicKeys: usePublicKeys) + } + + /** + Designated init + + - parameter certs: is the certificates or public keys to use + - parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation + + - returns: a representation security object to be used with + */ + public init(certs: [SSLCert], usePublicKeys: Bool) { + self.usePublicKeys = usePublicKeys + + if self.usePublicKeys { + DispatchQueue.global(qos: .default).async { + let pubKeys = certs.reduce([SecKey]()) { (pubKeys: [SecKey], cert: SSLCert) -> [SecKey] in + var pubKeys = pubKeys + if let data = cert.certData, cert.key == nil { + cert.key = self.extractPublicKey(data) + } + if let key = cert.key { + pubKeys.append(key) + } + return pubKeys + } + + self.pubKeys = pubKeys + self.isReady = true + } + } else { + let certificates = certs.reduce([Data]()) { (certificates: [Data], cert: SSLCert) -> [Data] in + var certificates = certificates + if let data = cert.certData { + certificates.append(data) + } + return certificates + } + self.certificates = certificates + self.isReady = true + } + } + + /** + Valid the trust and domain name. + + - parameter trust: is the serverTrust to validate + - parameter domain: is the CN domain to validate + + - returns: if the key was successfully validated + */ + open func isValid(_ trust: SecTrust, domain: String?) -> Bool { + + var tries = 0 + while !self.isReady { + usleep(1000) + tries += 1 + if tries > 5 { + return false //doesn't appear it is going to ever be ready... + } + } + var policy: SecPolicy + if self.validatedDN { + policy = SecPolicyCreateSSL(true, domain as NSString?) + } else { + policy = SecPolicyCreateBasicX509() + } + SecTrustSetPolicies(trust,policy) + if self.usePublicKeys { + if let keys = self.pubKeys { + let serverPubKeys = publicKeyChain(trust) + for serverKey in serverPubKeys as [AnyObject] { + for key in keys as [AnyObject] { + if serverKey.isEqual(key) { + return true + } + } + } + } + } else if let certs = self.certificates { + let serverCerts = certificateChain(trust) + var collect = [SecCertificate]() + for cert in certs { + collect.append(SecCertificateCreateWithData(nil,cert as CFData)!) + } + SecTrustSetAnchorCertificates(trust,collect as NSArray) + var result: SecTrustResultType = .unspecified + SecTrustEvaluate(trust,&result) + if result == .unspecified || result == .proceed { + if !validateEntireChain { + return true + } + var trustedCount = 0 + for serverCert in serverCerts { + for cert in certs { + if cert == serverCert { + trustedCount += 1 + break + } + } + } + if trustedCount == serverCerts.count { + return true + } + } + } + return false + } + + /** + Get the public key from a certificate data + + - parameter data: is the certificate to pull the public key from + + - returns: a public key + */ + public func extractPublicKey(_ data: Data) -> SecKey? { + guard let cert = SecCertificateCreateWithData(nil, data as CFData) else { return nil } + + return extractPublicKey(cert, policy: SecPolicyCreateBasicX509()) + } + + /** + Get the public key from a certificate + + - parameter data: is the certificate to pull the public key from + + - returns: a public key + */ + public func extractPublicKey(_ cert: SecCertificate, policy: SecPolicy) -> SecKey? { + var possibleTrust: SecTrust? + SecTrustCreateWithCertificates(cert, policy, &possibleTrust) + + guard let trust = possibleTrust else { return nil } + var result: SecTrustResultType = .unspecified + SecTrustEvaluate(trust, &result) + return SecTrustCopyPublicKey(trust) + } + + /** + Get the certificate chain for the trust + + - parameter trust: is the trust to lookup the certificate chain for + + - returns: the certificate chain for the trust + */ + public func certificateChain(_ trust: SecTrust) -> [Data] { + let certificates = (0.. [Data] in + var certificates = certificates + let cert = SecTrustGetCertificateAtIndex(trust, index) + certificates.append(SecCertificateCopyData(cert!) as Data) + return certificates + } + + return certificates + } + + /** + Get the public key chain for the trust + + - parameter trust: is the trust to lookup the certificate chain and extract the public keys + + - returns: the public keys from the certifcate chain for the trust + */ + public func publicKeyChain(_ trust: SecTrust) -> [SecKey] { + let policy = SecPolicyCreateBasicX509() + let keys = (0.. [SecKey] in + var keys = keys + let cert = SecTrustGetCertificateAtIndex(trust, index) + if let key = extractPublicKey(cert!, policy: policy) { + keys.append(key) + } + + return keys + } + + return keys + } + + +} +#endif diff --git a/Example/Web3supportBrowser/Pods/Starscream/Sources/Starscream/WebSocket.swift b/Example/Web3supportBrowser/Pods/Starscream/Sources/Starscream/WebSocket.swift new file mode 100644 index 000000000..7d48a20d9 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Starscream/Sources/Starscream/WebSocket.swift @@ -0,0 +1,1356 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Websocket.swift +// +// Created by Dalton Cherry on 7/16/14. +// Copyright (c) 2014-2017 Dalton Cherry. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation +import CoreFoundation +import CommonCrypto + +public let WebsocketDidConnectNotification = "WebsocketDidConnectNotification" +public let WebsocketDidDisconnectNotification = "WebsocketDidDisconnectNotification" +public let WebsocketDisconnectionErrorKeyName = "WebsocketDisconnectionErrorKeyName" + +//Standard WebSocket close codes +public enum CloseCode : UInt16 { + case normal = 1000 + case goingAway = 1001 + case protocolError = 1002 + case protocolUnhandledType = 1003 + // 1004 reserved. + case noStatusReceived = 1005 + //1006 reserved. + case encoding = 1007 + case policyViolated = 1008 + case messageTooBig = 1009 +} + +public enum ErrorType: Error { + case outputStreamWriteError //output stream error during write + case compressionError + case invalidSSLError //Invalid SSL certificate + case writeTimeoutError //The socket timed out waiting to be ready to write + case protocolError //There was an error parsing the WebSocket frames + case upgradeError //There was an error during the HTTP upgrade + case closeError //There was an error during the close (socket probably has been dereferenced) +} + +public struct WSError: Error { + public let type: ErrorType + public let message: String + public let code: Int +} + +//WebSocketClient is setup to be dependency injection for testing +public protocol WebSocketClient: class { + var delegate: WebSocketDelegate? {get set} + var pongDelegate: WebSocketPongDelegate? {get set} + var disableSSLCertValidation: Bool {get set} + var overrideTrustHostname: Bool {get set} + var desiredTrustHostname: String? {get set} + var sslClientCertificate: SSLClientCertificate? {get set} + #if os(Linux) + #else + var security: SSLTrustValidator? {get set} + var enabledSSLCipherSuites: [SSLCipherSuite]? {get set} + #endif + var isConnected: Bool {get} + + func connect() + func disconnect(forceTimeout: TimeInterval?, closeCode: UInt16) + func write(string: String, completion: (() -> ())?) + func write(data: Data, completion: (() -> ())?) + func write(ping: Data, completion: (() -> ())?) + func write(pong: Data, completion: (() -> ())?) +} + +//implements some of the base behaviors +extension WebSocketClient { + public func write(string: String) { + write(string: string, completion: nil) + } + + public func write(data: Data) { + write(data: data, completion: nil) + } + + public func write(ping: Data) { + write(ping: ping, completion: nil) + } + + public func write(pong: Data) { + write(pong: pong, completion: nil) + } + + public func disconnect() { + disconnect(forceTimeout: nil, closeCode: CloseCode.normal.rawValue) + } +} + +//SSL settings for the stream +public struct SSLSettings { + public let useSSL: Bool + public let disableCertValidation: Bool + public var overrideTrustHostname: Bool + public var desiredTrustHostname: String? + public let sslClientCertificate: SSLClientCertificate? + #if os(Linux) + #else + public let cipherSuites: [SSLCipherSuite]? + #endif +} + +public protocol WSStreamDelegate: class { + func newBytesInStream() + func streamDidError(error: Error?) +} + +//This protocol is to allow custom implemention of the underlining stream. This way custom socket libraries (e.g. linux) can be used +public protocol WSStream { + var delegate: WSStreamDelegate? {get set} + func connect(url: URL, port: Int, timeout: TimeInterval, ssl: SSLSettings, completion: @escaping ((Error?) -> Void)) + func write(data: Data) -> Int + func read() -> Data? + func cleanup() + #if os(Linux) || os(watchOS) + #else + func sslTrust() -> (trust: SecTrust?, domain: String?) + #endif +} + +open class FoundationStream : NSObject, WSStream, StreamDelegate { + private let workQueue = DispatchQueue(label: "com.vluxe.starscream.websocket", attributes: []) + private var inputStream: InputStream? + private var outputStream: OutputStream? + public weak var delegate: WSStreamDelegate? + let BUFFER_MAX = 4096 + + public var enableSOCKSProxy = false + + public func connect(url: URL, port: Int, timeout: TimeInterval, ssl: SSLSettings, completion: @escaping ((Error?) -> Void)) { + var readStream: Unmanaged? + var writeStream: Unmanaged? + let h = url.host! as NSString + CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream) + inputStream = readStream!.takeRetainedValue() + outputStream = writeStream!.takeRetainedValue() + + #if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work + #else + if enableSOCKSProxy { + let proxyDict = CFNetworkCopySystemProxySettings() + let socksConfig = CFDictionaryCreateMutableCopy(nil, 0, proxyDict!.takeRetainedValue()) + let propertyKey = CFStreamPropertyKey(rawValue: kCFStreamPropertySOCKSProxy) + CFWriteStreamSetProperty(outputStream, propertyKey, socksConfig) + CFReadStreamSetProperty(inputStream, propertyKey, socksConfig) + } + #endif + + guard let inStream = inputStream, let outStream = outputStream else { return } + inStream.delegate = self + outStream.delegate = self + if ssl.useSSL { + inStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey) + outStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey) + #if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work + #else + var settings = [NSObject: NSObject]() + if ssl.disableCertValidation { + settings[kCFStreamSSLValidatesCertificateChain] = NSNumber(value: false) + } + if ssl.overrideTrustHostname { + if let hostname = ssl.desiredTrustHostname { + settings[kCFStreamSSLPeerName] = hostname as NSString + } else { + settings[kCFStreamSSLPeerName] = kCFNull + } + } + if let sslClientCertificate = ssl.sslClientCertificate { + settings[kCFStreamSSLCertificates] = sslClientCertificate.streamSSLCertificates + } + + inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey) + outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey) + #endif + + #if os(Linux) + #else + if let cipherSuites = ssl.cipherSuites { + #if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work + #else + if let sslContextIn = CFReadStreamCopyProperty(inputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext?, + let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? { + let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count) + let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count) + if resIn != errSecSuccess { + completion(WSError(type: .invalidSSLError, message: "Error setting ingoing cypher suites", code: Int(resIn))) + } + if resOut != errSecSuccess { + completion(WSError(type: .invalidSSLError, message: "Error setting outgoing cypher suites", code: Int(resOut))) + } + } + #endif + } + #endif + } + + CFReadStreamSetDispatchQueue(inStream, workQueue) + CFWriteStreamSetDispatchQueue(outStream, workQueue) + inStream.open() + outStream.open() + + var out = timeout// wait X seconds before giving up + workQueue.async { [weak self] in + while !outStream.hasSpaceAvailable { + usleep(100) // wait until the socket is ready + out -= 100 + if out < 0 { + completion(WSError(type: .writeTimeoutError, message: "Timed out waiting for the socket to be ready for a write", code: 0)) + return + } else if let error = outStream.streamError { + completion(error) + return // disconnectStream will be called. + } else if self == nil { + completion(WSError(type: .closeError, message: "socket object has been dereferenced", code: 0)) + return + } + } + completion(nil) //success! + } + } + + public func write(data: Data) -> Int { + guard let outStream = outputStream else {return -1} + let buffer = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self) + return outStream.write(buffer, maxLength: data.count) + } + + public func read() -> Data? { + guard let stream = inputStream else {return nil} + let buf = NSMutableData(capacity: BUFFER_MAX) + let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self) + let length = stream.read(buffer, maxLength: BUFFER_MAX) + if length < 1 { + return nil + } + return Data(bytes: buffer, count: length) + } + + public func cleanup() { + if let stream = inputStream { + stream.delegate = nil + CFReadStreamSetDispatchQueue(stream, nil) + stream.close() + } + if let stream = outputStream { + stream.delegate = nil + CFWriteStreamSetDispatchQueue(stream, nil) + stream.close() + } + outputStream = nil + inputStream = nil + } + + #if os(Linux) || os(watchOS) + #else + public func sslTrust() -> (trust: SecTrust?, domain: String?) { + guard let outputStream = outputStream else { return (nil, nil) } + + let trust = outputStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as! SecTrust? + var domain = outputStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as! String? + if domain == nil, + let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? { + var peerNameLen: Int = 0 + SSLGetPeerDomainNameLength(sslContextOut, &peerNameLen) + var peerName = Data(count: peerNameLen) + let _ = peerName.withUnsafeMutableBytes { (peerNamePtr: UnsafeMutablePointer) in + SSLGetPeerDomainName(sslContextOut, peerNamePtr, &peerNameLen) + } + if let peerDomain = String(bytes: peerName, encoding: .utf8), peerDomain.count > 0 { + domain = peerDomain + } + } + + return (trust, domain) + } + #endif + + /** + Delegate for the stream methods. Processes incoming bytes + */ + open func stream(_ aStream: Stream, handle eventCode: Stream.Event) { + if eventCode == .hasBytesAvailable { + if aStream == inputStream { + delegate?.newBytesInStream() + } + } else if eventCode == .errorOccurred { + delegate?.streamDidError(error: aStream.streamError) + } else if eventCode == .endEncountered { + delegate?.streamDidError(error: nil) + } + } +} + +//WebSocket implementation + +//standard delegate you should use +public protocol WebSocketDelegate: class { + func websocketDidConnect(socket: WebSocketClient) + func websocketDidDisconnect(socket: WebSocketClient, error: Error?) + func websocketDidReceiveMessage(socket: WebSocketClient, text: String) + func websocketDidReceiveData(socket: WebSocketClient, data: Data) +} + +//got pongs +public protocol WebSocketPongDelegate: class { + func websocketDidReceivePong(socket: WebSocketClient, data: Data?) +} + +// A Delegate with more advanced info on messages and connection etc. +public protocol WebSocketAdvancedDelegate: class { + func websocketDidConnect(socket: WebSocket) + func websocketDidDisconnect(socket: WebSocket, error: Error?) + func websocketDidReceiveMessage(socket: WebSocket, text: String, response: WebSocket.WSResponse) + func websocketDidReceiveData(socket: WebSocket, data: Data, response: WebSocket.WSResponse) + func websocketHttpUpgrade(socket: WebSocket, request: String) + func websocketHttpUpgrade(socket: WebSocket, response: String) +} + + +open class WebSocket : NSObject, StreamDelegate, WebSocketClient, WSStreamDelegate { + + public enum OpCode : UInt8 { + case continueFrame = 0x0 + case textFrame = 0x1 + case binaryFrame = 0x2 + // 3-7 are reserved. + case connectionClose = 0x8 + case ping = 0x9 + case pong = 0xA + // B-F reserved. + } + + public static let ErrorDomain = "WebSocket" + + // Where the callback is executed. It defaults to the main UI thread queue. + public var callbackQueue = DispatchQueue.main + + // MARK: - Constants + + let headerWSUpgradeName = "Upgrade" + let headerWSUpgradeValue = "websocket" + let headerWSHostName = "Host" + let headerWSConnectionName = "Connection" + let headerWSConnectionValue = "Upgrade" + let headerWSProtocolName = "Sec-WebSocket-Protocol" + let headerWSVersionName = "Sec-WebSocket-Version" + let headerWSVersionValue = "13" + let headerWSExtensionName = "Sec-WebSocket-Extensions" + let headerWSKeyName = "Sec-WebSocket-Key" + let headerOriginName = "Origin" + let headerWSAcceptName = "Sec-WebSocket-Accept" + let BUFFER_MAX = 4096 + let FinMask: UInt8 = 0x80 + let OpCodeMask: UInt8 = 0x0F + let RSVMask: UInt8 = 0x70 + let RSV1Mask: UInt8 = 0x40 + let MaskMask: UInt8 = 0x80 + let PayloadLenMask: UInt8 = 0x7F + let MaxFrameSize: Int = 32 + let httpSwitchProtocolCode = 101 + let supportedSSLSchemes = ["wss", "https"] + + public class WSResponse { + var isFin = false + public var code: OpCode = .continueFrame + var bytesLeft = 0 + public var frameCount = 0 + public var buffer: NSMutableData? + public let firstFrame = { + return Date() + }() + } + + // MARK: - Delegates + + /// Responds to callback about new messages coming in over the WebSocket + /// and also connection/disconnect messages. + public weak var delegate: WebSocketDelegate? + + /// The optional advanced delegate can be used instead of of the delegate + public weak var advancedDelegate: WebSocketAdvancedDelegate? + + /// Receives a callback for each pong message recived. + public weak var pongDelegate: WebSocketPongDelegate? + + public var onConnect: (() -> Void)? + public var onDisconnect: ((Error?) -> Void)? + public var onText: ((String) -> Void)? + public var onData: ((Data) -> Void)? + public var onPong: ((Data?) -> Void)? + public var onHttpResponseHeaders: (([String: String]) -> Void)? + + public var disableSSLCertValidation = false + public var overrideTrustHostname = false + public var desiredTrustHostname: String? = nil + public var sslClientCertificate: SSLClientCertificate? = nil + + public var enableCompression = true + #if os(Linux) + #else + public var security: SSLTrustValidator? + public var enabledSSLCipherSuites: [SSLCipherSuite]? + #endif + + public var isConnected: Bool { + mutex.lock() + let isConnected = connected + mutex.unlock() + return isConnected + } + public var request: URLRequest //this is only public to allow headers, timeout, etc to be modified on reconnect + public var currentURL: URL { return request.url! } + + public var respondToPingWithPong: Bool = true + + // MARK: - Private + + private struct CompressionState { + var supportsCompression = false + var messageNeedsDecompression = false + var serverMaxWindowBits = 15 + var clientMaxWindowBits = 15 + var clientNoContextTakeover = false + var serverNoContextTakeover = false + var decompressor:Decompressor? = nil + var compressor:Compressor? = nil + } + + private var stream: WSStream + private var connected = false + private var isConnecting = false + private let mutex = NSLock() + private var compressionState = CompressionState() + private var writeQueue = OperationQueue() + private var readStack = [WSResponse]() + private var inputQueue = [Data]() + private var fragBuffer: Data? + private var certValidated = false + private var didDisconnect = false + private var readyToWrite = false + private var headerSecKey = "" + private var canDispatch: Bool { + mutex.lock() + let canWork = readyToWrite + mutex.unlock() + return canWork + } + + /// Used for setting protocols. + public init(request: URLRequest, protocols: [String]? = nil, stream: WSStream = FoundationStream()) { + self.request = request + self.stream = stream + if request.value(forHTTPHeaderField: headerOriginName) == nil { + guard let url = request.url else {return} + var origin = url.absoluteString + if let hostUrl = URL (string: "/", relativeTo: url) { + origin = hostUrl.absoluteString + origin.remove(at: origin.index(before: origin.endIndex)) + } + self.request.setValue(origin, forHTTPHeaderField: headerOriginName) + } + if let protocols = protocols, !protocols.isEmpty { + self.request.setValue(protocols.joined(separator: ","), forHTTPHeaderField: headerWSProtocolName) + } + writeQueue.maxConcurrentOperationCount = 1 + } + + public convenience init(url: URL, protocols: [String]? = nil) { + var request = URLRequest(url: url) + request.timeoutInterval = 5 + self.init(request: request, protocols: protocols) + } + + // Used for specifically setting the QOS for the write queue. + public convenience init(url: URL, writeQueueQOS: QualityOfService, protocols: [String]? = nil) { + self.init(url: url, protocols: protocols) + writeQueue.qualityOfService = writeQueueQOS + } + + /** + Connect to the WebSocket server on a background thread. + */ + open func connect() { + guard !isConnecting else { return } + didDisconnect = false + isConnecting = true + createHTTPRequest() + } + + /** + Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my delegate once the socket has been closed. + + If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate. + + If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my delegate. + + - Parameter forceTimeout: Maximum time to wait for the server to close the socket. + - Parameter closeCode: The code to send on disconnect. The default is the normal close code for cleanly disconnecting a webSocket. + */ + open func disconnect(forceTimeout: TimeInterval? = nil, closeCode: UInt16 = CloseCode.normal.rawValue) { + guard isConnected else { return } + switch forceTimeout { + case .some(let seconds) where seconds > 0: + let milliseconds = Int(seconds * 1_000) + callbackQueue.asyncAfter(deadline: .now() + .milliseconds(milliseconds)) { [weak self] in + self?.disconnectStream(nil) + } + fallthrough + case .none: + writeError(closeCode) + default: + disconnectStream(nil) + break + } + } + + /** + Write a string to the websocket. This sends it as a text frame. + + If you supply a non-nil completion block, I will perform it when the write completes. + + - parameter string: The string to write. + - parameter completion: The (optional) completion handler. + */ + open func write(string: String, completion: (() -> ())? = nil) { + guard isConnected else { return } + dequeueWrite(string.data(using: String.Encoding.utf8)!, code: .textFrame, writeCompletion: completion) + } + + /** + Write binary data to the websocket. This sends it as a binary frame. + + If you supply a non-nil completion block, I will perform it when the write completes. + + - parameter data: The data to write. + - parameter completion: The (optional) completion handler. + */ + open func write(data: Data, completion: (() -> ())? = nil) { + guard isConnected else { return } + dequeueWrite(data, code: .binaryFrame, writeCompletion: completion) + } + + /** + Write a ping to the websocket. This sends it as a control frame. + Yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s + */ + open func write(ping: Data, completion: (() -> ())? = nil) { + guard isConnected else { return } + dequeueWrite(ping, code: .ping, writeCompletion: completion) + } + + /** + Write a pong to the websocket. This sends it as a control frame. + Respond to a Yodel. + */ + open func write(pong: Data, completion: (() -> ())? = nil) { + guard isConnected else { return } + dequeueWrite(pong, code: .pong, writeCompletion: completion) + } + + /** + Private method that starts the connection. + */ + private func createHTTPRequest() { + guard let url = request.url else {return} + var port = url.port + if port == nil { + if supportedSSLSchemes.contains(url.scheme!) { + port = 443 + } else { + port = 80 + } + } + request.setValue(headerWSUpgradeValue, forHTTPHeaderField: headerWSUpgradeName) + request.setValue(headerWSConnectionValue, forHTTPHeaderField: headerWSConnectionName) + headerSecKey = generateWebSocketKey() + request.setValue(headerWSVersionValue, forHTTPHeaderField: headerWSVersionName) + request.setValue(headerSecKey, forHTTPHeaderField: headerWSKeyName) + + if enableCompression { + let val = "permessage-deflate; client_max_window_bits; server_max_window_bits=15" + request.setValue(val, forHTTPHeaderField: headerWSExtensionName) + } + let hostValue = request.allHTTPHeaderFields?[headerWSHostName] ?? "\(url.host!):\(port!)" + request.setValue(hostValue, forHTTPHeaderField: headerWSHostName) + + var path = url.absoluteString + let offset = (url.scheme?.count ?? 2) + 3 + path = String(path[path.index(path.startIndex, offsetBy: offset).. String { + var key = "" + let seed = 16 + for _ in 0.., bufferLen: Int) { + let code = processHTTP(buffer, bufferLen: bufferLen) + switch code { + case 0: + break + case -1: + fragBuffer = Data(bytes: buffer, count: bufferLen) + break // do nothing, we are going to collect more data + default: + doDisconnect(WSError(type: .upgradeError, message: "Invalid HTTP upgrade", code: code)) + } + } + + /** + Finds the HTTP Packet in the TCP stream, by looking for the CRLF. + */ + private func processHTTP(_ buffer: UnsafePointer, bufferLen: Int) -> Int { + let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")] + var k = 0 + var totalSize = 0 + for i in 0.. 0 { + let code = validateResponse(buffer, bufferLen: totalSize) + if code != 0 { + return code + } + isConnecting = false + mutex.lock() + connected = true + mutex.unlock() + didDisconnect = false + if canDispatch { + callbackQueue.async { [weak self] in + guard let self = self else { return } + self.onConnect?() + self.delegate?.websocketDidConnect(socket: self) + self.advancedDelegate?.websocketDidConnect(socket: self) + NotificationCenter.default.post(name: NSNotification.Name(WebsocketDidConnectNotification), object: self) + } + } + //totalSize += 1 //skip the last \n + let restSize = bufferLen - totalSize + if restSize > 0 { + processRawMessagesInBuffer(buffer + totalSize, bufferLen: restSize) + } + return 0 //success + } + return -1 // Was unable to find the full TCP header. + } + + /** + Validates the HTTP is a 101 as per the RFC spec. + */ + private func validateResponse(_ buffer: UnsafePointer, bufferLen: Int) -> Int { + guard let str = String(data: Data(bytes: buffer, count: bufferLen), encoding: .utf8) else { return -1 } + let splitArr = str.components(separatedBy: "\r\n") + var code = -1 + var i = 0 + var headers = [String: String]() + for str in splitArr { + if i == 0 { + let responseSplit = str.components(separatedBy: .whitespaces) + guard responseSplit.count > 1 else { return -1 } + if let c = Int(responseSplit[1]) { + code = c + } + } else { + let responseSplit = str.components(separatedBy: ":") + guard responseSplit.count > 1 else { break } + let key = responseSplit[0].trimmingCharacters(in: .whitespaces) + let val = responseSplit[1].trimmingCharacters(in: .whitespaces) + headers[key.lowercased()] = val + } + i += 1 + } + advancedDelegate?.websocketHttpUpgrade(socket: self, response: str) + onHttpResponseHeaders?(headers) + if code != httpSwitchProtocolCode { + return code + } + + if let extensionHeader = headers[headerWSExtensionName.lowercased()] { + processExtensionHeader(extensionHeader) + } + + if let acceptKey = headers[headerWSAcceptName.lowercased()] { + if acceptKey.count > 0 { + if headerSecKey.count > 0 { + let sha = "\(headerSecKey)258EAFA5-E914-47DA-95CA-C5AB0DC85B11".sha1Base64() + if sha != acceptKey as String { + return -1 + } + } + return 0 + } + } + return -1 + } + + /** + Parses the extension header, setting up the compression parameters. + */ + func processExtensionHeader(_ extensionHeader: String) { + let parts = extensionHeader.components(separatedBy: ";") + for p in parts { + let part = p.trimmingCharacters(in: .whitespaces) + if part == "permessage-deflate" { + compressionState.supportsCompression = true + } else if part.hasPrefix("server_max_window_bits=") { + let valString = part.components(separatedBy: "=")[1] + if let val = Int(valString.trimmingCharacters(in: .whitespaces)) { + compressionState.serverMaxWindowBits = val + } + } else if part.hasPrefix("client_max_window_bits=") { + let valString = part.components(separatedBy: "=")[1] + if let val = Int(valString.trimmingCharacters(in: .whitespaces)) { + compressionState.clientMaxWindowBits = val + } + } else if part == "client_no_context_takeover" { + compressionState.clientNoContextTakeover = true + } else if part == "server_no_context_takeover" { + compressionState.serverNoContextTakeover = true + } + } + if compressionState.supportsCompression { + compressionState.decompressor = Decompressor(windowBits: compressionState.serverMaxWindowBits) + compressionState.compressor = Compressor(windowBits: compressionState.clientMaxWindowBits) + } + } + + /** + Read a 16 bit big endian value from a buffer + */ + private static func readUint16(_ buffer: UnsafePointer, offset: Int) -> UInt16 { + return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1]) + } + + /** + Read a 64 bit big endian value from a buffer + */ + private static func readUint64(_ buffer: UnsafePointer, offset: Int) -> UInt64 { + var value = UInt64(0) + for i in 0...7 { + value = (value << 8) | UInt64(buffer[offset + i]) + } + return value + } + + /** + Write a 16-bit big endian value to a buffer. + */ + private static func writeUint16(_ buffer: UnsafeMutablePointer, offset: Int, value: UInt16) { + buffer[offset + 0] = UInt8(value >> 8) + buffer[offset + 1] = UInt8(value & 0xff) + } + + /** + Write a 64-bit big endian value to a buffer. + */ + private static func writeUint64(_ buffer: UnsafeMutablePointer, offset: Int, value: UInt64) { + for i in 0...7 { + buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff) + } + } + + /** + Process one message at the start of `buffer`. Return another buffer (sharing storage) that contains the leftover contents of `buffer` that I didn't process. + */ + private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer) -> UnsafeBufferPointer { + let response = readStack.last + guard let baseAddress = buffer.baseAddress else {return emptyBuffer} + let bufferLen = buffer.count + if response != nil && bufferLen < 2 { + fragBuffer = Data(buffer: buffer) + return emptyBuffer + } + if let response = response, response.bytesLeft > 0 { + var len = response.bytesLeft + var extra = bufferLen - response.bytesLeft + if response.bytesLeft > bufferLen { + len = bufferLen + extra = 0 + } + response.bytesLeft -= len + response.buffer?.append(Data(bytes: baseAddress, count: len)) + _ = processResponse(response) + return buffer.fromOffset(bufferLen - extra) + } else { + let isFin = (FinMask & baseAddress[0]) + let receivedOpcodeRawValue = (OpCodeMask & baseAddress[0]) + let receivedOpcode = OpCode(rawValue: receivedOpcodeRawValue) + let isMasked = (MaskMask & baseAddress[1]) + let payloadLen = (PayloadLenMask & baseAddress[1]) + var offset = 2 + if compressionState.supportsCompression && receivedOpcode != .continueFrame { + compressionState.messageNeedsDecompression = (RSV1Mask & baseAddress[0]) > 0 + } + if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .pong && !compressionState.messageNeedsDecompression { + let errCode = CloseCode.protocolError.rawValue + doDisconnect(WSError(type: .protocolError, message: "masked and rsv data is not currently supported", code: Int(errCode))) + writeError(errCode) + return emptyBuffer + } + let isControlFrame = (receivedOpcode == .connectionClose || receivedOpcode == .ping) + if !isControlFrame && (receivedOpcode != .binaryFrame && receivedOpcode != .continueFrame && + receivedOpcode != .textFrame && receivedOpcode != .pong) { + let errCode = CloseCode.protocolError.rawValue + doDisconnect(WSError(type: .protocolError, message: "unknown opcode: \(receivedOpcodeRawValue)", code: Int(errCode))) + writeError(errCode) + return emptyBuffer + } + if isControlFrame && isFin == 0 { + let errCode = CloseCode.protocolError.rawValue + doDisconnect(WSError(type: .protocolError, message: "control frames can't be fragmented", code: Int(errCode))) + writeError(errCode) + return emptyBuffer + } + var closeCode = CloseCode.normal.rawValue + if receivedOpcode == .connectionClose { + if payloadLen == 1 { + closeCode = CloseCode.protocolError.rawValue + } else if payloadLen > 1 { + closeCode = WebSocket.readUint16(baseAddress, offset: offset) + if closeCode < 1000 || (closeCode > 1003 && closeCode < 1007) || (closeCode > 1013 && closeCode < 3000) { + closeCode = CloseCode.protocolError.rawValue + } + } + if payloadLen < 2 { + doDisconnect(WSError(type: .protocolError, message: "connection closed by server", code: Int(closeCode))) + writeError(closeCode) + return emptyBuffer + } + } else if isControlFrame && payloadLen > 125 { + writeError(CloseCode.protocolError.rawValue) + return emptyBuffer + } + var dataLength = UInt64(payloadLen) + if dataLength == 127 { + dataLength = WebSocket.readUint64(baseAddress, offset: offset) + offset += MemoryLayout.size + } else if dataLength == 126 { + dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset)) + offset += MemoryLayout.size + } + if bufferLen < offset || UInt64(bufferLen - offset) < dataLength { + fragBuffer = Data(bytes: baseAddress, count: bufferLen) + return emptyBuffer + } + var len = dataLength + if dataLength > UInt64(bufferLen) { + len = UInt64(bufferLen-offset) + } + if receivedOpcode == .connectionClose && len > 0 { + let size = MemoryLayout.size + offset += size + len -= UInt64(size) + } + let data: Data + if compressionState.messageNeedsDecompression, let decompressor = compressionState.decompressor { + do { + data = try decompressor.decompress(bytes: baseAddress+offset, count: Int(len), finish: isFin > 0) + if isFin > 0 && compressionState.serverNoContextTakeover { + try decompressor.reset() + } + } catch { + let closeReason = "Decompression failed: \(error)" + let closeCode = CloseCode.encoding.rawValue + doDisconnect(WSError(type: .protocolError, message: closeReason, code: Int(closeCode))) + writeError(closeCode) + return emptyBuffer + } + } else { + data = Data(bytes: baseAddress+offset, count: Int(len)) + } + + if receivedOpcode == .connectionClose { + var closeReason = "connection closed by server" + if let customCloseReason = String(data: data, encoding: .utf8) { + closeReason = customCloseReason + } else { + closeCode = CloseCode.protocolError.rawValue + } + doDisconnect(WSError(type: .protocolError, message: closeReason, code: Int(closeCode))) + writeError(closeCode) + return emptyBuffer + } + if receivedOpcode == .pong { + if canDispatch { + callbackQueue.async { [weak self] in + guard let self = self else { return } + let pongData: Data? = data.count > 0 ? data : nil + self.onPong?(pongData) + self.pongDelegate?.websocketDidReceivePong(socket: self, data: pongData) + } + } + return buffer.fromOffset(offset + Int(len)) + } + var response = readStack.last + if isControlFrame { + response = nil // Don't append pings. + } + if isFin == 0 && receivedOpcode == .continueFrame && response == nil { + let errCode = CloseCode.protocolError.rawValue + doDisconnect(WSError(type: .protocolError, message: "continue frame before a binary or text frame", code: Int(errCode))) + writeError(errCode) + return emptyBuffer + } + var isNew = false + if response == nil { + if receivedOpcode == .continueFrame { + let errCode = CloseCode.protocolError.rawValue + doDisconnect(WSError(type: .protocolError, message: "first frame can't be a continue frame", code: Int(errCode))) + writeError(errCode) + return emptyBuffer + } + isNew = true + response = WSResponse() + response!.code = receivedOpcode! + response!.bytesLeft = Int(dataLength) + response!.buffer = NSMutableData(data: data) + } else { + if receivedOpcode == .continueFrame { + response!.bytesLeft = Int(dataLength) + } else { + let errCode = CloseCode.protocolError.rawValue + doDisconnect(WSError(type: .protocolError, message: "second and beyond of fragment message must be a continue frame", code: Int(errCode))) + writeError(errCode) + return emptyBuffer + } + response!.buffer!.append(data) + } + if let response = response { + response.bytesLeft -= Int(len) + response.frameCount += 1 + response.isFin = isFin > 0 ? true : false + if isNew { + readStack.append(response) + } + _ = processResponse(response) + } + + let step = Int(offset + numericCast(len)) + return buffer.fromOffset(step) + } + } + + /** + Process all messages in the buffer if possible. + */ + private func processRawMessagesInBuffer(_ pointer: UnsafePointer, bufferLen: Int) { + var buffer = UnsafeBufferPointer(start: pointer, count: bufferLen) + repeat { + buffer = processOneRawMessage(inBuffer: buffer) + } while buffer.count >= 2 + if buffer.count > 0 { + fragBuffer = Data(buffer: buffer) + } + } + + /** + Process the finished response of a buffer. + */ + private func processResponse(_ response: WSResponse) -> Bool { + if response.isFin && response.bytesLeft <= 0 { + if response.code == .ping { + if respondToPingWithPong { + let data = response.buffer! // local copy so it is perverse for writing + dequeueWrite(data as Data, code: .pong) + } + } else if response.code == .textFrame { + guard let str = String(data: response.buffer! as Data, encoding: .utf8) else { + writeError(CloseCode.encoding.rawValue) + return false + } + if canDispatch { + callbackQueue.async { [weak self] in + guard let self = self else { return } + self.onText?(str) + self.delegate?.websocketDidReceiveMessage(socket: self, text: str) + self.advancedDelegate?.websocketDidReceiveMessage(socket: self, text: str, response: response) + } + } + } else if response.code == .binaryFrame { + if canDispatch { + let data = response.buffer! // local copy so it is perverse for writing + callbackQueue.async { [weak self] in + guard let self = self else { return } + self.onData?(data as Data) + self.delegate?.websocketDidReceiveData(socket: self, data: data as Data) + self.advancedDelegate?.websocketDidReceiveData(socket: self, data: data as Data, response: response) + } + } + } + readStack.removeLast() + return true + } + return false + } + + /** + Write an error to the socket + */ + private func writeError(_ code: UInt16) { + let buf = NSMutableData(capacity: MemoryLayout.size) + let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self) + WebSocket.writeUint16(buffer, offset: 0, value: code) + dequeueWrite(Data(bytes: buffer, count: MemoryLayout.size), code: .connectionClose) + } + + /** + Used to write things to the stream + */ + private func dequeueWrite(_ data: Data, code: OpCode, writeCompletion: (() -> ())? = nil) { + let operation = BlockOperation() + operation.addExecutionBlock { [weak self, weak operation] in + //stream isn't ready, let's wait + guard let self = self else { return } + guard let sOperation = operation else { return } + var offset = 2 + var firstByte:UInt8 = self.FinMask | code.rawValue + var data = data + if [.textFrame, .binaryFrame].contains(code), let compressor = self.compressionState.compressor { + do { + data = try compressor.compress(data) + if self.compressionState.clientNoContextTakeover { + try compressor.reset() + } + firstByte |= self.RSV1Mask + } catch { + // TODO: report error? We can just send the uncompressed frame. + } + } + let dataLength = data.count + let frame = NSMutableData(capacity: dataLength + self.MaxFrameSize) + let buffer = UnsafeMutableRawPointer(frame!.mutableBytes).assumingMemoryBound(to: UInt8.self) + buffer[0] = firstByte + if dataLength < 126 { + buffer[1] = CUnsignedChar(dataLength) + } else if dataLength <= Int(UInt16.max) { + buffer[1] = 126 + WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength)) + offset += MemoryLayout.size + } else { + buffer[1] = 127 + WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength)) + offset += MemoryLayout.size + } + buffer[1] |= self.MaskMask + let maskKey = UnsafeMutablePointer(buffer + offset) + _ = SecRandomCopyBytes(kSecRandomDefault, Int(MemoryLayout.size), maskKey) + offset += MemoryLayout.size + + for i in 0...size] + offset += 1 + } + var total = 0 + while !sOperation.isCancelled { + if !self.readyToWrite { + self.doDisconnect(WSError(type: .outputStreamWriteError, message: "output stream had an error during write", code: 0)) + break + } + let stream = self.stream + let writeBuffer = UnsafeRawPointer(frame!.bytes+total).assumingMemoryBound(to: UInt8.self) + let len = stream.write(data: Data(bytes: writeBuffer, count: offset-total)) + if len <= 0 { + self.doDisconnect(WSError(type: .outputStreamWriteError, message: "output stream had an error during write", code: 0)) + break + } else { + total += len + } + if total >= offset { + if let callback = writeCompletion { + self.callbackQueue.async { + callback() + } + } + + break + } + } + } + writeQueue.addOperation(operation) + } + + /** + Used to preform the disconnect delegate + */ + private func doDisconnect(_ error: Error?) { + guard !didDisconnect else { return } + didDisconnect = true + isConnecting = false + mutex.lock() + connected = false + mutex.unlock() + guard canDispatch else {return} + callbackQueue.async { [weak self] in + guard let self = self else { return } + self.onDisconnect?(error) + self.delegate?.websocketDidDisconnect(socket: self, error: error) + self.advancedDelegate?.websocketDidDisconnect(socket: self, error: error) + let userInfo = error.map{ [WebsocketDisconnectionErrorKeyName: $0] } + NotificationCenter.default.post(name: NSNotification.Name(WebsocketDidDisconnectNotification), object: self, userInfo: userInfo) + } + } + + // MARK: - Deinit + + deinit { + mutex.lock() + readyToWrite = false + cleanupStream() + mutex.unlock() + writeQueue.cancelAllOperations() + } + +} + +private extension String { + func sha1Base64() -> String { + let data = self.data(using: String.Encoding.utf8)! + var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH)) + data.withUnsafeBytes { _ = CC_SHA1($0, CC_LONG(data.count), &digest) } + return Data(bytes: digest).base64EncodedString() + } +} + +private extension Data { + + init(buffer: UnsafeBufferPointer) { + self.init(bytes: buffer.baseAddress!, count: buffer.count) + } + +} + +private extension UnsafeBufferPointer { + + func fromOffset(_ offset: Int) -> UnsafeBufferPointer { + return UnsafeBufferPointer(start: baseAddress?.advanced(by: offset), count: count - offset) + } + +} + +private let emptyBuffer = UnsafeBufferPointer(start: nil, count: 0) + +#if swift(>=4) +#else +fileprivate extension String { + var count: Int { + return self.characters.count + } +} +#endif diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt-Info.plist b/Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt-Info.plist new file mode 100644 index 000000000..3424ca661 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 4.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt-dummy.m b/Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt-dummy.m new file mode 100644 index 000000000..7367f8606 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_BigInt : NSObject +@end +@implementation PodsDummy_BigInt +@end diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt-prefix.pch b/Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt-prefix.pch new file mode 100644 index 000000000..beb2a2441 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt-umbrella.h b/Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt-umbrella.h new file mode 100644 index 000000000..e3d2506e1 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double BigIntVersionNumber; +FOUNDATION_EXPORT const unsigned char BigIntVersionString[]; + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt.debug.xcconfig b/Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt.debug.xcconfig new file mode 100644 index 000000000..14420073d --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt.debug.xcconfig @@ -0,0 +1,12 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/BigInt +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/BigInt +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt.modulemap b/Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt.modulemap new file mode 100644 index 000000000..48a38d1cb --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt.modulemap @@ -0,0 +1,6 @@ +framework module BigInt { + umbrella header "BigInt-umbrella.h" + + export * + module * { export * } +} diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt.release.xcconfig b/Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt.release.xcconfig new file mode 100644 index 000000000..14420073d --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/BigInt/BigInt.release.xcconfig @@ -0,0 +1,12 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/BigInt +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/BigInt +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift-Info.plist b/Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift-Info.plist new file mode 100644 index 000000000..2243fe6e2 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift-dummy.m b/Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift-dummy.m new file mode 100644 index 000000000..657061bc6 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_CryptoSwift : NSObject +@end +@implementation PodsDummy_CryptoSwift +@end diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift-prefix.pch b/Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift-prefix.pch new file mode 100644 index 000000000..beb2a2441 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift-umbrella.h b/Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift-umbrella.h new file mode 100644 index 000000000..e93efa884 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double CryptoSwiftVersionNumber; +FOUNDATION_EXPORT const unsigned char CryptoSwiftVersionString[]; + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift.debug.xcconfig b/Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift.debug.xcconfig new file mode 100644 index 000000000..f8490fbfa --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift.debug.xcconfig @@ -0,0 +1,17 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +GCC_UNROLL_LOOPS = YES +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/CryptoSwift +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +SWIFT_COMPILATION_MODE = wholemodule +SWIFT_DISABLE_SAFETY_CHECKS = YES +SWIFT_ENFORCE_EXCLUSIVE_ACCESS = debug-only +SWIFT_OPTIMIZATION_LEVEL = -O +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift.modulemap b/Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift.modulemap new file mode 100644 index 000000000..f090f6a33 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift.modulemap @@ -0,0 +1,6 @@ +framework module CryptoSwift { + umbrella header "CryptoSwift-umbrella.h" + + export * + module * { export * } +} diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift.release.xcconfig b/Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift.release.xcconfig new file mode 100644 index 000000000..f8490fbfa --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/CryptoSwift/CryptoSwift.release.xcconfig @@ -0,0 +1,17 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +GCC_UNROLL_LOOPS = YES +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/CryptoSwift +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +SWIFT_COMPILATION_MODE = wholemodule +SWIFT_DISABLE_SAFETY_CHECKS = YES +SWIFT_ENFORCE_EXCLUSIVE_ACCESS = debug-only +SWIFT_OPTIMIZATION_LEVEL = -O +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-Info.plist b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-Info.plist new file mode 100644 index 000000000..2243fe6e2 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-acknowledgements.markdown b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-acknowledgements.markdown new file mode 100644 index 000000000..7a41759ce --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-acknowledgements.markdown @@ -0,0 +1,474 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## BigInt + + +Copyright (c) 2016-2017 Károly Lőrentey + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +## CryptoSwift + +Copyright (C) 2014-2017 Marcin Krzyżanowski +This software is provided 'as-is', without any express or implied warranty. + +In no event will the authors be held liable for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: + +- The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +- Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +- This notice may not be removed or altered from any source or binary distribution. +- Redistributions of any form whatsoever must retain the following acknowledgment: 'This product includes software developed by the "Marcin Krzyzanowski" (http://krzyzanowskim.com/).' + +## PromiseKit + +Copyright 2016-present, Max Howell; mxcl@me.com + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +## Starscream + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + Copyright (c) 2014-2016 Dalton Cherry. + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +## secp256k1.c + +Copyright (c) 2013 Pieter Wuille + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +## web3swift + +Copyright (c) 2018 Aleksandr Vlasov, + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018 Aleksandr Vlasov + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +Generated by CocoaPods - https://cocoapods.org diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-acknowledgements.plist b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-acknowledgements.plist new file mode 100644 index 000000000..c358ebbf3 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-acknowledgements.plist @@ -0,0 +1,536 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + +Copyright (c) 2016-2017 Károly Lőrentey + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + License + MIT + Title + BigInt + Type + PSGroupSpecifier + + + FooterText + Copyright (C) 2014-2017 Marcin Krzyżanowski <marcin.krzyzanowski@gmail.com> +This software is provided 'as-is', without any express or implied warranty. + +In no event will the authors be held liable for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: + +- The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +- Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +- This notice may not be removed or altered from any source or binary distribution. +- Redistributions of any form whatsoever must retain the following acknowledgment: 'This product includes software developed by the "Marcin Krzyzanowski" (http://krzyzanowskim.com/).' + License + Attribution + Title + CryptoSwift + Type + PSGroupSpecifier + + + FooterText + Copyright 2016-present, Max Howell; mxcl@me.com + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + License + MIT + Title + PromiseKit + Type + PSGroupSpecifier + + + FooterText + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + Copyright (c) 2014-2016 Dalton Cherry. + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + License + Apache License, Version 2.0 + Title + Starscream + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2013 Pieter Wuille + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + License + Apache License 2.0 + Title + secp256k1.c + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2018 Aleksandr Vlasov, <alex.m.vlasov@gmail.com> + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018 Aleksandr Vlasov + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + License + Apache License 2.0 + Title + web3swift + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-dummy.m b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-dummy.m new file mode 100644 index 000000000..9566f4718 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_Web3support_Web3supportUITests : NSObject +@end +@implementation PodsDummy_Pods_Web3support_Web3supportUITests +@end diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks-Debug-input-files.xcfilelist b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks-Debug-input-files.xcfilelist new file mode 100644 index 000000000..ba1bb6393 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks-Debug-input-files.xcfilelist @@ -0,0 +1,7 @@ +${PODS_ROOT}/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks.sh +${BUILT_PRODUCTS_DIR}/BigInt/BigInt.framework +${BUILT_PRODUCTS_DIR}/CryptoSwift/CryptoSwift.framework +${BUILT_PRODUCTS_DIR}/PromiseKit/PromiseKit.framework +${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework +${BUILT_PRODUCTS_DIR}/secp256k1.c/secp256k1.framework +${BUILT_PRODUCTS_DIR}/web3swift/web3swift.framework \ No newline at end of file diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks-Debug-output-files.xcfilelist b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks-Debug-output-files.xcfilelist new file mode 100644 index 000000000..02d4d0015 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks-Debug-output-files.xcfilelist @@ -0,0 +1,6 @@ +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/BigInt.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/CryptoSwift.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PromiseKit.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Starscream.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/secp256k1.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/web3swift.framework \ No newline at end of file diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks-Release-input-files.xcfilelist b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks-Release-input-files.xcfilelist new file mode 100644 index 000000000..ba1bb6393 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks-Release-input-files.xcfilelist @@ -0,0 +1,7 @@ +${PODS_ROOT}/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks.sh +${BUILT_PRODUCTS_DIR}/BigInt/BigInt.framework +${BUILT_PRODUCTS_DIR}/CryptoSwift/CryptoSwift.framework +${BUILT_PRODUCTS_DIR}/PromiseKit/PromiseKit.framework +${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework +${BUILT_PRODUCTS_DIR}/secp256k1.c/secp256k1.framework +${BUILT_PRODUCTS_DIR}/web3swift/web3swift.framework \ No newline at end of file diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks-Release-output-files.xcfilelist b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks-Release-output-files.xcfilelist new file mode 100644 index 000000000..02d4d0015 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks-Release-output-files.xcfilelist @@ -0,0 +1,6 @@ +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/BigInt.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/CryptoSwift.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PromiseKit.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Starscream.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/secp256k1.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/web3swift.framework \ No newline at end of file diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks.sh b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks.sh new file mode 100755 index 000000000..174858ac5 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks.sh @@ -0,0 +1,195 @@ +#!/bin/sh +set -e +set -u +set -o pipefail + +function on_error { + echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" +} +trap 'on_error $LINENO' ERR + +if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then + # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy + # frameworks to, so exit 0 (signalling the script phase was successful). + exit 0 +fi + +echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" +SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" +BCSYMBOLMAP_DIR="BCSymbolMaps" + + +# This protects against multiple targets copying the same framework dependency at the same time. The solution +# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html +RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") + +# Copies and strips a vendored framework +install_framework() +{ + if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then + local source="${BUILT_PRODUCTS_DIR}/$1" + elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then + local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" + elif [ -r "$1" ]; then + local source="$1" + fi + + local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + + if [ -L "${source}" ]; then + echo "Symlinked..." + source="$(readlink "${source}")" + fi + + if [ -d "${source}/${BCSYMBOLMAP_DIR}" ]; then + # Locate and install any .bcsymbolmaps if present, and remove them from the .framework before the framework is copied + find "${source}/${BCSYMBOLMAP_DIR}" -name "*.bcsymbolmap"|while read f; do + echo "Installing $f" + install_bcsymbolmap "$f" "$destination" + rm "$f" + done + rmdir "${source}/${BCSYMBOLMAP_DIR}" + fi + + # Use filter instead of exclude so missing patterns don't throw errors. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" + + local basename + basename="$(basename -s .framework "$1")" + binary="${destination}/${basename}.framework/${basename}" + + if ! [ -r "$binary" ]; then + binary="${destination}/${basename}" + elif [ -L "${binary}" ]; then + echo "Destination binary is symlinked..." + dirname="$(dirname "${binary}")" + binary="${dirname}/$(readlink "${binary}")" + fi + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then + strip_invalid_archs "$binary" + fi + + # Resign the code if required by the build settings to avoid unstable apps + code_sign_if_enabled "${destination}/$(basename "$1")" + + # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. + if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then + local swift_runtime_libs + swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) + for lib in $swift_runtime_libs; do + echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" + rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" + code_sign_if_enabled "${destination}/${lib}" + done + fi +} +# Copies and strips a vendored dSYM +install_dsym() { + local source="$1" + warn_missing_arch=${2:-true} + if [ -r "$source" ]; then + # Copy the dSYM into the targets temp dir. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" + + local basename + basename="$(basename -s .dSYM "$source")" + binary_name="$(ls "$source/Contents/Resources/DWARF")" + binary="${DERIVED_FILES_DIR}/${basename}.dSYM/Contents/Resources/DWARF/${binary_name}" + + # Strip invalid architectures from the dSYM. + if [[ "$(file "$binary")" == *"Mach-O "*"dSYM companion"* ]]; then + strip_invalid_archs "$binary" "$warn_missing_arch" + fi + if [[ $STRIP_BINARY_RETVAL == 0 ]]; then + # Move the stripped file into its final destination. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.dSYM" "${DWARF_DSYM_FOLDER_PATH}" + else + # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. + touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.dSYM" + fi + fi +} + +# Used as a return value for each invocation of `strip_invalid_archs` function. +STRIP_BINARY_RETVAL=0 + +# Strip invalid architectures +strip_invalid_archs() { + binary="$1" + warn_missing_arch=${2:-true} + # Get architectures for current target binary + binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" + # Intersect them with the architectures we are building for + intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" + # If there are no archs supported by this binary then warn the user + if [[ -z "$intersected_archs" ]]; then + if [[ "$warn_missing_arch" == "true" ]]; then + echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." + fi + STRIP_BINARY_RETVAL=1 + return + fi + stripped="" + for arch in $binary_archs; do + if ! [[ "${ARCHS}" == *"$arch"* ]]; then + # Strip non-valid architectures in-place + lipo -remove "$arch" -output "$binary" "$binary" + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi + STRIP_BINARY_RETVAL=0 +} + +# Copies the bcsymbolmap files of a vendored framework +install_bcsymbolmap() { + local bcsymbolmap_path="$1" + local destination="${BUILT_PRODUCTS_DIR}" + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}" +} + +# Signs a framework with the provided identity +code_sign_if_enabled() { + if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then + # Use the current code_sign_identity + echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" + local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" + + if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + code_sign_cmd="$code_sign_cmd &" + fi + echo "$code_sign_cmd" + eval "$code_sign_cmd" + fi +} + +if [[ "$CONFIGURATION" == "Debug" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/BigInt/BigInt.framework" + install_framework "${BUILT_PRODUCTS_DIR}/CryptoSwift/CryptoSwift.framework" + install_framework "${BUILT_PRODUCTS_DIR}/PromiseKit/PromiseKit.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework" + install_framework "${BUILT_PRODUCTS_DIR}/secp256k1.c/secp256k1.framework" + install_framework "${BUILT_PRODUCTS_DIR}/web3swift/web3swift.framework" +fi +if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/BigInt/BigInt.framework" + install_framework "${BUILT_PRODUCTS_DIR}/CryptoSwift/CryptoSwift.framework" + install_framework "${BUILT_PRODUCTS_DIR}/PromiseKit/PromiseKit.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework" + install_framework "${BUILT_PRODUCTS_DIR}/secp256k1.c/secp256k1.framework" + install_framework "${BUILT_PRODUCTS_DIR}/web3swift/web3swift.framework" +fi +if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + wait +fi diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-umbrella.h b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-umbrella.h new file mode 100644 index 000000000..52519824a --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double Pods_Web3support_Web3supportUITestsVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_Web3support_Web3supportUITestsVersionString[]; + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests.debug.xcconfig b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests.debug.xcconfig new file mode 100644 index 000000000..4308570a0 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests.debug.xcconfig @@ -0,0 +1,14 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt/BigInt.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift/CryptoSwift.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit/PromiseKit.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream/Starscream.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c/secp256k1.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift/web3swift.framework/Headers" +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_LDFLAGS = $(inherited) -framework "BigInt" -framework "CoreImage" -framework "CryptoSwift" -framework "Foundation" -framework "PromiseKit" -framework "Starscream" -framework "UIKit" -framework "secp256k1" -framework "web3swift" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests.modulemap b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests.modulemap new file mode 100644 index 000000000..35560c474 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests.modulemap @@ -0,0 +1,6 @@ +framework module Pods_Web3support_Web3supportUITests { + umbrella header "Pods-Web3support-Web3supportUITests-umbrella.h" + + export * + module * { export * } +} diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests.release.xcconfig b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests.release.xcconfig new file mode 100644 index 000000000..4308570a0 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests.release.xcconfig @@ -0,0 +1,14 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt/BigInt.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift/CryptoSwift.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit/PromiseKit.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream/Starscream.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c/secp256k1.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift/web3swift.framework/Headers" +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_LDFLAGS = $(inherited) -framework "BigInt" -framework "CoreImage" -framework "CryptoSwift" -framework "Foundation" -framework "PromiseKit" -framework "Starscream" -framework "UIKit" -framework "secp256k1" -framework "web3swift" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-Info.plist b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-Info.plist new file mode 100644 index 000000000..2243fe6e2 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-acknowledgements.markdown b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-acknowledgements.markdown new file mode 100644 index 000000000..7a41759ce --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-acknowledgements.markdown @@ -0,0 +1,474 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## BigInt + + +Copyright (c) 2016-2017 Károly Lőrentey + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +## CryptoSwift + +Copyright (C) 2014-2017 Marcin Krzyżanowski +This software is provided 'as-is', without any express or implied warranty. + +In no event will the authors be held liable for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: + +- The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +- Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +- This notice may not be removed or altered from any source or binary distribution. +- Redistributions of any form whatsoever must retain the following acknowledgment: 'This product includes software developed by the "Marcin Krzyzanowski" (http://krzyzanowskim.com/).' + +## PromiseKit + +Copyright 2016-present, Max Howell; mxcl@me.com + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +## Starscream + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + Copyright (c) 2014-2016 Dalton Cherry. + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +## secp256k1.c + +Copyright (c) 2013 Pieter Wuille + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +## web3swift + +Copyright (c) 2018 Aleksandr Vlasov, + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018 Aleksandr Vlasov + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +Generated by CocoaPods - https://cocoapods.org diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-acknowledgements.plist b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-acknowledgements.plist new file mode 100644 index 000000000..c358ebbf3 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-acknowledgements.plist @@ -0,0 +1,536 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + +Copyright (c) 2016-2017 Károly Lőrentey + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + License + MIT + Title + BigInt + Type + PSGroupSpecifier + + + FooterText + Copyright (C) 2014-2017 Marcin Krzyżanowski <marcin.krzyzanowski@gmail.com> +This software is provided 'as-is', without any express or implied warranty. + +In no event will the authors be held liable for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: + +- The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +- Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +- This notice may not be removed or altered from any source or binary distribution. +- Redistributions of any form whatsoever must retain the following acknowledgment: 'This product includes software developed by the "Marcin Krzyzanowski" (http://krzyzanowskim.com/).' + License + Attribution + Title + CryptoSwift + Type + PSGroupSpecifier + + + FooterText + Copyright 2016-present, Max Howell; mxcl@me.com + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + License + MIT + Title + PromiseKit + Type + PSGroupSpecifier + + + FooterText + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + Copyright (c) 2014-2016 Dalton Cherry. + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + License + Apache License, Version 2.0 + Title + Starscream + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2013 Pieter Wuille + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + License + Apache License 2.0 + Title + secp256k1.c + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2018 Aleksandr Vlasov, <alex.m.vlasov@gmail.com> + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018 Aleksandr Vlasov + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + License + Apache License 2.0 + Title + web3swift + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-dummy.m b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-dummy.m new file mode 100644 index 000000000..835b6cdc8 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_Web3support : NSObject +@end +@implementation PodsDummy_Pods_Web3support +@end diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks-Debug-input-files.xcfilelist b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks-Debug-input-files.xcfilelist new file mode 100644 index 000000000..3ad344399 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks-Debug-input-files.xcfilelist @@ -0,0 +1,7 @@ +${PODS_ROOT}/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks.sh +${BUILT_PRODUCTS_DIR}/BigInt/BigInt.framework +${BUILT_PRODUCTS_DIR}/CryptoSwift/CryptoSwift.framework +${BUILT_PRODUCTS_DIR}/PromiseKit/PromiseKit.framework +${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework +${BUILT_PRODUCTS_DIR}/secp256k1.c/secp256k1.framework +${BUILT_PRODUCTS_DIR}/web3swift/web3swift.framework \ No newline at end of file diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks-Debug-output-files.xcfilelist b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks-Debug-output-files.xcfilelist new file mode 100644 index 000000000..02d4d0015 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks-Debug-output-files.xcfilelist @@ -0,0 +1,6 @@ +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/BigInt.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/CryptoSwift.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PromiseKit.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Starscream.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/secp256k1.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/web3swift.framework \ No newline at end of file diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks-Release-input-files.xcfilelist b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks-Release-input-files.xcfilelist new file mode 100644 index 000000000..3ad344399 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks-Release-input-files.xcfilelist @@ -0,0 +1,7 @@ +${PODS_ROOT}/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks.sh +${BUILT_PRODUCTS_DIR}/BigInt/BigInt.framework +${BUILT_PRODUCTS_DIR}/CryptoSwift/CryptoSwift.framework +${BUILT_PRODUCTS_DIR}/PromiseKit/PromiseKit.framework +${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework +${BUILT_PRODUCTS_DIR}/secp256k1.c/secp256k1.framework +${BUILT_PRODUCTS_DIR}/web3swift/web3swift.framework \ No newline at end of file diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks-Release-output-files.xcfilelist b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks-Release-output-files.xcfilelist new file mode 100644 index 000000000..02d4d0015 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks-Release-output-files.xcfilelist @@ -0,0 +1,6 @@ +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/BigInt.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/CryptoSwift.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PromiseKit.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Starscream.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/secp256k1.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/web3swift.framework \ No newline at end of file diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks.sh b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks.sh new file mode 100755 index 000000000..174858ac5 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks.sh @@ -0,0 +1,195 @@ +#!/bin/sh +set -e +set -u +set -o pipefail + +function on_error { + echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" +} +trap 'on_error $LINENO' ERR + +if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then + # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy + # frameworks to, so exit 0 (signalling the script phase was successful). + exit 0 +fi + +echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" +SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" +BCSYMBOLMAP_DIR="BCSymbolMaps" + + +# This protects against multiple targets copying the same framework dependency at the same time. The solution +# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html +RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") + +# Copies and strips a vendored framework +install_framework() +{ + if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then + local source="${BUILT_PRODUCTS_DIR}/$1" + elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then + local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" + elif [ -r "$1" ]; then + local source="$1" + fi + + local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + + if [ -L "${source}" ]; then + echo "Symlinked..." + source="$(readlink "${source}")" + fi + + if [ -d "${source}/${BCSYMBOLMAP_DIR}" ]; then + # Locate and install any .bcsymbolmaps if present, and remove them from the .framework before the framework is copied + find "${source}/${BCSYMBOLMAP_DIR}" -name "*.bcsymbolmap"|while read f; do + echo "Installing $f" + install_bcsymbolmap "$f" "$destination" + rm "$f" + done + rmdir "${source}/${BCSYMBOLMAP_DIR}" + fi + + # Use filter instead of exclude so missing patterns don't throw errors. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" + + local basename + basename="$(basename -s .framework "$1")" + binary="${destination}/${basename}.framework/${basename}" + + if ! [ -r "$binary" ]; then + binary="${destination}/${basename}" + elif [ -L "${binary}" ]; then + echo "Destination binary is symlinked..." + dirname="$(dirname "${binary}")" + binary="${dirname}/$(readlink "${binary}")" + fi + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then + strip_invalid_archs "$binary" + fi + + # Resign the code if required by the build settings to avoid unstable apps + code_sign_if_enabled "${destination}/$(basename "$1")" + + # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. + if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then + local swift_runtime_libs + swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) + for lib in $swift_runtime_libs; do + echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" + rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" + code_sign_if_enabled "${destination}/${lib}" + done + fi +} +# Copies and strips a vendored dSYM +install_dsym() { + local source="$1" + warn_missing_arch=${2:-true} + if [ -r "$source" ]; then + # Copy the dSYM into the targets temp dir. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" + + local basename + basename="$(basename -s .dSYM "$source")" + binary_name="$(ls "$source/Contents/Resources/DWARF")" + binary="${DERIVED_FILES_DIR}/${basename}.dSYM/Contents/Resources/DWARF/${binary_name}" + + # Strip invalid architectures from the dSYM. + if [[ "$(file "$binary")" == *"Mach-O "*"dSYM companion"* ]]; then + strip_invalid_archs "$binary" "$warn_missing_arch" + fi + if [[ $STRIP_BINARY_RETVAL == 0 ]]; then + # Move the stripped file into its final destination. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.dSYM" "${DWARF_DSYM_FOLDER_PATH}" + else + # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. + touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.dSYM" + fi + fi +} + +# Used as a return value for each invocation of `strip_invalid_archs` function. +STRIP_BINARY_RETVAL=0 + +# Strip invalid architectures +strip_invalid_archs() { + binary="$1" + warn_missing_arch=${2:-true} + # Get architectures for current target binary + binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" + # Intersect them with the architectures we are building for + intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" + # If there are no archs supported by this binary then warn the user + if [[ -z "$intersected_archs" ]]; then + if [[ "$warn_missing_arch" == "true" ]]; then + echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." + fi + STRIP_BINARY_RETVAL=1 + return + fi + stripped="" + for arch in $binary_archs; do + if ! [[ "${ARCHS}" == *"$arch"* ]]; then + # Strip non-valid architectures in-place + lipo -remove "$arch" -output "$binary" "$binary" + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi + STRIP_BINARY_RETVAL=0 +} + +# Copies the bcsymbolmap files of a vendored framework +install_bcsymbolmap() { + local bcsymbolmap_path="$1" + local destination="${BUILT_PRODUCTS_DIR}" + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}" +} + +# Signs a framework with the provided identity +code_sign_if_enabled() { + if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then + # Use the current code_sign_identity + echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" + local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" + + if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + code_sign_cmd="$code_sign_cmd &" + fi + echo "$code_sign_cmd" + eval "$code_sign_cmd" + fi +} + +if [[ "$CONFIGURATION" == "Debug" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/BigInt/BigInt.framework" + install_framework "${BUILT_PRODUCTS_DIR}/CryptoSwift/CryptoSwift.framework" + install_framework "${BUILT_PRODUCTS_DIR}/PromiseKit/PromiseKit.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework" + install_framework "${BUILT_PRODUCTS_DIR}/secp256k1.c/secp256k1.framework" + install_framework "${BUILT_PRODUCTS_DIR}/web3swift/web3swift.framework" +fi +if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/BigInt/BigInt.framework" + install_framework "${BUILT_PRODUCTS_DIR}/CryptoSwift/CryptoSwift.framework" + install_framework "${BUILT_PRODUCTS_DIR}/PromiseKit/PromiseKit.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework" + install_framework "${BUILT_PRODUCTS_DIR}/secp256k1.c/secp256k1.framework" + install_framework "${BUILT_PRODUCTS_DIR}/web3swift/web3swift.framework" +fi +if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + wait +fi diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-umbrella.h b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-umbrella.h new file mode 100644 index 000000000..5db6815cb --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double Pods_Web3supportVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_Web3supportVersionString[]; + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support.debug.xcconfig b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support.debug.xcconfig new file mode 100644 index 000000000..4308570a0 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support.debug.xcconfig @@ -0,0 +1,14 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt/BigInt.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift/CryptoSwift.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit/PromiseKit.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream/Starscream.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c/secp256k1.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift/web3swift.framework/Headers" +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_LDFLAGS = $(inherited) -framework "BigInt" -framework "CoreImage" -framework "CryptoSwift" -framework "Foundation" -framework "PromiseKit" -framework "Starscream" -framework "UIKit" -framework "secp256k1" -framework "web3swift" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support.modulemap b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support.modulemap new file mode 100644 index 000000000..c4e2f9986 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support.modulemap @@ -0,0 +1,6 @@ +framework module Pods_Web3support { + umbrella header "Pods-Web3support-umbrella.h" + + export * + module * { export * } +} diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support.release.xcconfig b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support.release.xcconfig new file mode 100644 index 000000000..4308570a0 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3support/Pods-Web3support.release.xcconfig @@ -0,0 +1,14 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt/BigInt.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift/CryptoSwift.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit/PromiseKit.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream/Starscream.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c/secp256k1.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift/web3swift.framework/Headers" +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_LDFLAGS = $(inherited) -framework "BigInt" -framework "CoreImage" -framework "CryptoSwift" -framework "Foundation" -framework "PromiseKit" -framework "Starscream" -framework "UIKit" -framework "secp256k1" -framework "web3swift" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests-Info.plist b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests-Info.plist new file mode 100644 index 000000000..2243fe6e2 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests-acknowledgements.markdown b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests-acknowledgements.markdown new file mode 100644 index 000000000..102af7538 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests-acknowledgements.markdown @@ -0,0 +1,3 @@ +# Acknowledgements +This application makes use of the following third party libraries: +Generated by CocoaPods - https://cocoapods.org diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests-acknowledgements.plist b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests-acknowledgements.plist new file mode 100644 index 000000000..7acbad1ea --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests-acknowledgements.plist @@ -0,0 +1,29 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests-dummy.m b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests-dummy.m new file mode 100644 index 000000000..8b1d2bfa7 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_Web3supportTests : NSObject +@end +@implementation PodsDummy_Pods_Web3supportTests +@end diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests-umbrella.h b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests-umbrella.h new file mode 100644 index 000000000..82df2d968 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double Pods_Web3supportTestsVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_Web3supportTestsVersionString[]; + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests.debug.xcconfig b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests.debug.xcconfig new file mode 100644 index 000000000..a93533830 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests.debug.xcconfig @@ -0,0 +1,11 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt/BigInt.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift/CryptoSwift.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit/PromiseKit.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream/Starscream.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c/secp256k1.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift/web3swift.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "BigInt" -framework "CoreImage" -framework "CryptoSwift" -framework "Foundation" -framework "PromiseKit" -framework "Starscream" -framework "UIKit" -framework "secp256k1" -framework "web3swift" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests.modulemap b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests.modulemap new file mode 100644 index 000000000..ed13c65c7 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests.modulemap @@ -0,0 +1,6 @@ +framework module Pods_Web3supportTests { + umbrella header "Pods-Web3supportTests-umbrella.h" + + export * + module * { export * } +} diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests.release.xcconfig b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests.release.xcconfig new file mode 100644 index 000000000..a93533830 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests.release.xcconfig @@ -0,0 +1,11 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt/BigInt.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift/CryptoSwift.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit/PromiseKit.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream/Starscream.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c/secp256k1.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift/web3swift.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "BigInt" -framework "CoreImage" -framework "CryptoSwift" -framework "Foundation" -framework "PromiseKit" -framework "Starscream" -framework "UIKit" -framework "secp256k1" -framework "web3swift" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit-Info.plist b/Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit-Info.plist new file mode 100644 index 000000000..d4e60cc22 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 6.8.5 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit-dummy.m b/Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit-dummy.m new file mode 100644 index 000000000..ce9245130 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_PromiseKit : NSObject +@end +@implementation PodsDummy_PromiseKit +@end diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit-prefix.pch b/Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit-prefix.pch new file mode 100644 index 000000000..beb2a2441 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit-umbrella.h b/Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit-umbrella.h new file mode 100644 index 000000000..4a0b02de6 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit-umbrella.h @@ -0,0 +1,26 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "fwd.h" +#import "AnyPromise.h" +#import "PromiseKit.h" +#import "NSURLSession+AnyPromise.h" +#import "NSTask+AnyPromise.h" +#import "NSNotificationCenter+AnyPromise.h" +#import "PMKFoundation.h" +#import "PMKUIKit.h" +#import "UIView+AnyPromise.h" +#import "UIViewController+AnyPromise.h" + +FOUNDATION_EXPORT double PromiseKitVersionNumber; +FOUNDATION_EXPORT const unsigned char PromiseKitVersionString[]; + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit.debug.xcconfig b/Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit.debug.xcconfig new file mode 100644 index 000000000..3dfb3d928 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit.debug.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = $(inherited) -framework "Foundation" -framework "UIKit" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -DPMKCocoaPods +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/PromiseKit +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit.modulemap b/Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit.modulemap new file mode 100644 index 000000000..2b26033e4 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit.modulemap @@ -0,0 +1,6 @@ +framework module PromiseKit { + umbrella header "PromiseKit-umbrella.h" + + export * + module * { export * } +} diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit.release.xcconfig b/Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit.release.xcconfig new file mode 100644 index 000000000..3dfb3d928 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/PromiseKit/PromiseKit.release.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = $(inherited) -framework "Foundation" -framework "UIKit" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -DPMKCocoaPods +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/PromiseKit +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream-Info.plist b/Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream-Info.plist new file mode 100644 index 000000000..793d31a9f --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 3.1.1 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream-dummy.m b/Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream-dummy.m new file mode 100644 index 000000000..94456b3b0 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Starscream : NSObject +@end +@implementation PodsDummy_Starscream +@end diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream-prefix.pch b/Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream-prefix.pch new file mode 100644 index 000000000..beb2a2441 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream-umbrella.h b/Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream-umbrella.h new file mode 100644 index 000000000..7bffee0b3 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double StarscreamVersionNumber; +FOUNDATION_EXPORT const unsigned char StarscreamVersionString[]; + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream.debug.xcconfig b/Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream.debug.xcconfig new file mode 100644 index 000000000..23e1409be --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream.debug.xcconfig @@ -0,0 +1,12 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Starscream +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Starscream +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream.modulemap b/Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream.modulemap new file mode 100644 index 000000000..2b9097079 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream.modulemap @@ -0,0 +1,6 @@ +framework module Starscream { + umbrella header "Starscream-umbrella.h" + + export * + module * { export * } +} diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream.release.xcconfig b/Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream.release.xcconfig new file mode 100644 index 000000000..23e1409be --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/Starscream/Starscream.release.xcconfig @@ -0,0 +1,12 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Starscream +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Starscream +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c-Info.plist b/Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c-Info.plist new file mode 100644 index 000000000..7c241fa96 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 0.1.2 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c-dummy.m b/Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c-dummy.m new file mode 100644 index 000000000..965dbb1b9 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_secp256k1_c : NSObject +@end +@implementation PodsDummy_secp256k1_c +@end diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c-prefix.pch b/Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c-prefix.pch new file mode 100644 index 000000000..beb2a2441 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c-umbrella.h b/Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c-umbrella.h new file mode 100644 index 000000000..6943b49f3 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c-umbrella.h @@ -0,0 +1,17 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "secp256k1.h" + +FOUNDATION_EXPORT double secp256k1VersionNumber; +FOUNDATION_EXPORT const unsigned char secp256k1VersionString[]; + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c.debug.xcconfig b/Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c.debug.xcconfig new file mode 100644 index 000000000..93ba0a8c7 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c.debug.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/secp256k1" +OTHER_CFLAGS = $(inherited) -pedantic -Wall -Wextra -Wcast-align -Wnested-externs -Wshadow -Wstrict-prototypes -Wno-shorten-64-to-32 -Wno-conditional-uninitialized -Wno-unused-function -Wno-long-long -Wno-overlength-strings -O3 +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/secp256k1.c +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c.modulemap b/Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c.modulemap new file mode 100644 index 000000000..94da377c2 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c.modulemap @@ -0,0 +1,6 @@ +framework module secp256k1 { + umbrella header "secp256k1.c-umbrella.h" + + export * + module * { export * } +} diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c.release.xcconfig b/Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c.release.xcconfig new file mode 100644 index 000000000..93ba0a8c7 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/secp256k1.c/secp256k1.c.release.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/secp256k1" +OTHER_CFLAGS = $(inherited) -pedantic -Wall -Wextra -Wcast-align -Wnested-externs -Wshadow -Wstrict-prototypes -Wno-shorten-64-to-32 -Wno-conditional-uninitialized -Wno-unused-function -Wno-long-long -Wno-overlength-strings -O3 +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/secp256k1.c +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/ResourceBundle-Browser-web3swift-Info.plist b/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/ResourceBundle-Browser-web3swift-Info.plist new file mode 100644 index 000000000..86717ece9 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/ResourceBundle-Browser-web3swift-Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + BNDL + CFBundleShortVersionString + 2.3.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + NSPrincipalClass + + + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift-Info.plist b/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift-Info.plist new file mode 100644 index 000000000..d135faf18 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 2.3.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift-dummy.m b/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift-dummy.m new file mode 100644 index 000000000..ee2665c93 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_web3swift : NSObject +@end +@implementation PodsDummy_web3swift +@end diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift-prefix.pch b/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift-prefix.pch new file mode 100644 index 000000000..beb2a2441 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift-umbrella.h b/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift-umbrella.h new file mode 100644 index 000000000..9ec6a0b48 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double web3swiftVersionNumber; +FOUNDATION_EXPORT const unsigned char web3swiftVersionString[]; + diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift.debug.xcconfig b/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift.debug.xcconfig new file mode 100644 index 000000000..b9fd5fddc --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift.debug.xcconfig @@ -0,0 +1,14 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/web3swift +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = $(inherited) -framework "CoreImage" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/web3swift +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift.modulemap b/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift.modulemap new file mode 100644 index 000000000..241e217a4 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift.modulemap @@ -0,0 +1,6 @@ +framework module web3swift { + umbrella header "web3swift-umbrella.h" + + export * + module * { export * } +} diff --git a/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift.release.xcconfig b/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift.release.xcconfig new file mode 100644 index 000000000..b9fd5fddc --- /dev/null +++ b/Example/Web3supportBrowser/Pods/Target Support Files/web3swift/web3swift.release.xcconfig @@ -0,0 +1,14 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/web3swift +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = $(inherited) -framework "CoreImage" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/web3swift +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/License.md b/Example/Web3supportBrowser/Pods/secp256k1.c/License.md new file mode 100644 index 000000000..4522a5990 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/License.md @@ -0,0 +1,19 @@ +Copyright (c) 2013 Pieter Wuille + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/basic-config.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/basic-config.h new file mode 100644 index 000000000..fc588061c --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/basic-config.h @@ -0,0 +1,33 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_BASIC_CONFIG_H +#define SECP256K1_BASIC_CONFIG_H + +#ifdef USE_BASIC_CONFIG + +#undef USE_ASM_X86_64 +#undef USE_ENDOMORPHISM +#undef USE_FIELD_10X26 +#undef USE_FIELD_5X52 +#undef USE_FIELD_INV_BUILTIN +#undef USE_FIELD_INV_NUM +#undef USE_NUM_GMP +#undef USE_NUM_NONE +#undef USE_SCALAR_4X64 +#undef USE_SCALAR_8X32 +#undef USE_SCALAR_INV_BUILTIN +#undef USE_SCALAR_INV_NUM + +#define USE_NUM_NONE 1 +#define USE_FIELD_INV_BUILTIN 1 +#define USE_SCALAR_INV_BUILTIN 1 +#define USE_FIELD_10X26 1 +#define USE_SCALAR_8X32 1 + +#endif /* USE_BASIC_CONFIG */ + +#endif /* SECP256K1_BASIC_CONFIG_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecdh_impl.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecdh_impl.h new file mode 100644 index 000000000..c6820b8c5 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecdh_impl.h @@ -0,0 +1,54 @@ +/********************************************************************** + * Copyright (c) 2015 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_MODULE_ECDH_MAIN_H +#define SECP256K1_MODULE_ECDH_MAIN_H + +#include "secp256k1.h" +#include "ecmult_const_impl.h" + +int secp256k1_ecdh(const secp256k1_context* ctx, unsigned char *result, const secp256k1_pubkey *point, const unsigned char *scalar) { + int ret = 0; + int overflow = 0; + secp256k1_gej res; + secp256k1_ge pt; + secp256k1_scalar s; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(result != NULL); + ARG_CHECK(point != NULL); + ARG_CHECK(scalar != NULL); + + secp256k1_pubkey_load(ctx, &pt, point); + secp256k1_scalar_set_b32(&s, scalar, &overflow); + if (overflow || secp256k1_scalar_is_zero(&s)) { + ret = 0; + } else { + unsigned char x[32]; + unsigned char y[1]; + secp256k1_sha256 sha; + + secp256k1_ecmult_const(&res, &pt, &s, 256); + secp256k1_ge_set_gej(&pt, &res); + /* Compute a hash of the point in compressed form + * Note we cannot use secp256k1_eckey_pubkey_serialize here since it does not + * expect its output to be secret and has a timing sidechannel. */ + secp256k1_fe_normalize(&pt.x); + secp256k1_fe_normalize(&pt.y); + secp256k1_fe_get_b32(x, &pt.x); + y[0] = 0x02 | secp256k1_fe_is_odd(&pt.y); + + secp256k1_sha256_initialize(&sha); + secp256k1_sha256_write(&sha, y, sizeof(y)); + secp256k1_sha256_write(&sha, x, sizeof(x)); + secp256k1_sha256_finalize(&sha, result); + ret = 1; + } + + secp256k1_scalar_clear(&s); + return ret; +} + +#endif /* SECP256K1_MODULE_ECDH_MAIN_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecdsa.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecdsa.h new file mode 100644 index 000000000..80590c7cc --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecdsa.h @@ -0,0 +1,21 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECDSA_H +#define SECP256K1_ECDSA_H + +#include + +#include "scalar.h" +#include "group.h" +#include "ecmult.h" + +static int secp256k1_ecdsa_sig_parse(secp256k1_scalar *r, secp256k1_scalar *s, const unsigned char *sig, size_t size); +static int secp256k1_ecdsa_sig_serialize(unsigned char *sig, size_t *size, const secp256k1_scalar *r, const secp256k1_scalar *s); +static int secp256k1_ecdsa_sig_verify(const secp256k1_ecmult_context *ctx, const secp256k1_scalar* r, const secp256k1_scalar* s, const secp256k1_ge *pubkey, const secp256k1_scalar *message); +static int secp256k1_ecdsa_sig_sign(const secp256k1_ecmult_gen_context *ctx, secp256k1_scalar* r, secp256k1_scalar* s, const secp256k1_scalar *seckey, const secp256k1_scalar *message, const secp256k1_scalar *nonce, int *recid); + +#endif /* SECP256K1_ECDSA_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecdsa_impl.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecdsa_impl.h new file mode 100644 index 000000000..31a4c0d4a --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecdsa_impl.h @@ -0,0 +1,313 @@ +/********************************************************************** + * Copyright (c) 2013-2015 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + + +#ifndef SECP256K1_ECDSA_IMPL_H +#define SECP256K1_ECDSA_IMPL_H + +#include "scalar.h" +#include "field.h" +#include "group.h" +#include "ecmult.h" +#include "ecmult_gen.h" +#include "ecdsa.h" + +/** Group order for secp256k1 defined as 'n' in "Standards for Efficient Cryptography" (SEC2) 2.7.1 + * sage: for t in xrange(1023, -1, -1): + * .. p = 2**256 - 2**32 - t + * .. if p.is_prime(): + * .. print '%x'%p + * .. break + * 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f' + * sage: a = 0 + * sage: b = 7 + * sage: F = FiniteField (p) + * sage: '%x' % (EllipticCurve ([F (a), F (b)]).order()) + * 'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141' + */ +static const secp256k1_fe secp256k1_ecdsa_const_order_as_fe = SECP256K1_FE_CONST( + 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFEUL, + 0xBAAEDCE6UL, 0xAF48A03BUL, 0xBFD25E8CUL, 0xD0364141UL +); + +/** Difference between field and order, values 'p' and 'n' values defined in + * "Standards for Efficient Cryptography" (SEC2) 2.7.1. + * sage: p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F + * sage: a = 0 + * sage: b = 7 + * sage: F = FiniteField (p) + * sage: '%x' % (p - EllipticCurve ([F (a), F (b)]).order()) + * '14551231950b75fc4402da1722fc9baee' + */ +static const secp256k1_fe secp256k1_ecdsa_const_p_minus_order = SECP256K1_FE_CONST( + 0, 0, 0, 1, 0x45512319UL, 0x50B75FC4UL, 0x402DA172UL, 0x2FC9BAEEUL +); + +static int secp256k1_der_read_len(const unsigned char **sigp, const unsigned char *sigend) { + int lenleft, b1; + size_t ret = 0; + if (*sigp >= sigend) { + return -1; + } + b1 = *((*sigp)++); + if (b1 == 0xFF) { + /* X.690-0207 8.1.3.5.c the value 0xFF shall not be used. */ + return -1; + } + if ((b1 & 0x80) == 0) { + /* X.690-0207 8.1.3.4 short form length octets */ + return b1; + } + if (b1 == 0x80) { + /* Indefinite length is not allowed in DER. */ + return -1; + } + /* X.690-207 8.1.3.5 long form length octets */ + lenleft = b1 & 0x7F; + if (lenleft > sigend - *sigp) { + return -1; + } + if (**sigp == 0) { + /* Not the shortest possible length encoding. */ + return -1; + } + if ((size_t)lenleft > sizeof(size_t)) { + /* The resulting length would exceed the range of a size_t, so + * certainly longer than the passed array size. + */ + return -1; + } + while (lenleft > 0) { + ret = (ret << 8) | **sigp; + if (ret + lenleft > (size_t)(sigend - *sigp)) { + /* Result exceeds the length of the passed array. */ + return -1; + } + (*sigp)++; + lenleft--; + } + if (ret < 128) { + /* Not the shortest possible length encoding. */ + return -1; + } + return (int)ret; +} + +static int secp256k1_der_parse_integer(secp256k1_scalar *r, const unsigned char **sig, const unsigned char *sigend) { + int overflow = 0; + unsigned char ra[32] = {0}; + int rlen; + + if (*sig == sigend || **sig != 0x02) { + /* Not a primitive integer (X.690-0207 8.3.1). */ + return 0; + } + (*sig)++; + rlen = secp256k1_der_read_len(sig, sigend); + if (rlen <= 0 || (*sig) + rlen > sigend) { + /* Exceeds bounds or not at least length 1 (X.690-0207 8.3.1). */ + return 0; + } + if (**sig == 0x00 && rlen > 1 && (((*sig)[1]) & 0x80) == 0x00) { + /* Excessive 0x00 padding. */ + return 0; + } + if (**sig == 0xFF && rlen > 1 && (((*sig)[1]) & 0x80) == 0x80) { + /* Excessive 0xFF padding. */ + return 0; + } + if ((**sig & 0x80) == 0x80) { + /* Negative. */ + overflow = 1; + } + while (rlen > 0 && **sig == 0) { + /* Skip leading zero bytes */ + rlen--; + (*sig)++; + } + if (rlen > 32) { + overflow = 1; + } + if (!overflow) { + memcpy(ra + 32 - rlen, *sig, rlen); + secp256k1_scalar_set_b32(r, ra, &overflow); + } + if (overflow) { + secp256k1_scalar_set_int(r, 0); + } + (*sig) += rlen; + return 1; +} + +static int secp256k1_ecdsa_sig_parse(secp256k1_scalar *rr, secp256k1_scalar *rs, const unsigned char *sig, size_t size) { + const unsigned char *sigend = sig + size; + int rlen; + if (sig == sigend || *(sig++) != 0x30) { + /* The encoding doesn't start with a constructed sequence (X.690-0207 8.9.1). */ + return 0; + } + rlen = secp256k1_der_read_len(&sig, sigend); + if (rlen < 0 || sig + rlen > sigend) { + /* Tuple exceeds bounds */ + return 0; + } + if (sig + rlen != sigend) { + /* Garbage after tuple. */ + return 0; + } + + if (!secp256k1_der_parse_integer(rr, &sig, sigend)) { + return 0; + } + if (!secp256k1_der_parse_integer(rs, &sig, sigend)) { + return 0; + } + + if (sig != sigend) { + /* Trailing garbage inside tuple. */ + return 0; + } + + return 1; +} + +static int secp256k1_ecdsa_sig_serialize(unsigned char *sig, size_t *size, const secp256k1_scalar* ar, const secp256k1_scalar* as) { + unsigned char r[33] = {0}, s[33] = {0}; + unsigned char *rp = r, *sp = s; + size_t lenR = 33, lenS = 33; + secp256k1_scalar_get_b32(&r[1], ar); + secp256k1_scalar_get_b32(&s[1], as); + while (lenR > 1 && rp[0] == 0 && rp[1] < 0x80) { lenR--; rp++; } + while (lenS > 1 && sp[0] == 0 && sp[1] < 0x80) { lenS--; sp++; } + if (*size < 6+lenS+lenR) { + *size = 6 + lenS + lenR; + return 0; + } + *size = 6 + lenS + lenR; + sig[0] = 0x30; + sig[1] = 4 + lenS + lenR; + sig[2] = 0x02; + sig[3] = lenR; + memcpy(sig+4, rp, lenR); + sig[4+lenR] = 0x02; + sig[5+lenR] = lenS; + memcpy(sig+lenR+6, sp, lenS); + return 1; +} + +static int secp256k1_ecdsa_sig_verify(const secp256k1_ecmult_context *ctx, const secp256k1_scalar *sigr, const secp256k1_scalar *sigs, const secp256k1_ge *pubkey, const secp256k1_scalar *message) { + unsigned char c[32]; + secp256k1_scalar sn, u1, u2; +#if !defined(EXHAUSTIVE_TEST_ORDER) + secp256k1_fe xr; +#endif + secp256k1_gej pubkeyj; + secp256k1_gej pr; + + if (secp256k1_scalar_is_zero(sigr) || secp256k1_scalar_is_zero(sigs)) { + return 0; + } + + secp256k1_scalar_inverse_var(&sn, sigs); + secp256k1_scalar_mul(&u1, &sn, message); + secp256k1_scalar_mul(&u2, &sn, sigr); + secp256k1_gej_set_ge(&pubkeyj, pubkey); + secp256k1_ecmult(ctx, &pr, &pubkeyj, &u2, &u1); + if (secp256k1_gej_is_infinity(&pr)) { + return 0; + } + +#if defined(EXHAUSTIVE_TEST_ORDER) +{ + secp256k1_scalar computed_r; + secp256k1_ge pr_ge; + secp256k1_ge_set_gej(&pr_ge, &pr); + secp256k1_fe_normalize(&pr_ge.x); + + secp256k1_fe_get_b32(c, &pr_ge.x); + secp256k1_scalar_set_b32(&computed_r, c, NULL); + return secp256k1_scalar_eq(sigr, &computed_r); +} +#else + secp256k1_scalar_get_b32(c, sigr); + secp256k1_fe_set_b32(&xr, c); + + /** We now have the recomputed R point in pr, and its claimed x coordinate (modulo n) + * in xr. Naively, we would extract the x coordinate from pr (requiring a inversion modulo p), + * compute the remainder modulo n, and compare it to xr. However: + * + * xr == X(pr) mod n + * <=> exists h. (xr + h * n < p && xr + h * n == X(pr)) + * [Since 2 * n > p, h can only be 0 or 1] + * <=> (xr == X(pr)) || (xr + n < p && xr + n == X(pr)) + * [In Jacobian coordinates, X(pr) is pr.x / pr.z^2 mod p] + * <=> (xr == pr.x / pr.z^2 mod p) || (xr + n < p && xr + n == pr.x / pr.z^2 mod p) + * [Multiplying both sides of the equations by pr.z^2 mod p] + * <=> (xr * pr.z^2 mod p == pr.x) || (xr + n < p && (xr + n) * pr.z^2 mod p == pr.x) + * + * Thus, we can avoid the inversion, but we have to check both cases separately. + * secp256k1_gej_eq_x implements the (xr * pr.z^2 mod p == pr.x) test. + */ + if (secp256k1_gej_eq_x_var(&xr, &pr)) { + /* xr * pr.z^2 mod p == pr.x, so the signature is valid. */ + return 1; + } + if (secp256k1_fe_cmp_var(&xr, &secp256k1_ecdsa_const_p_minus_order) >= 0) { + /* xr + n >= p, so we can skip testing the second case. */ + return 0; + } + secp256k1_fe_add(&xr, &secp256k1_ecdsa_const_order_as_fe); + if (secp256k1_gej_eq_x_var(&xr, &pr)) { + /* (xr + n) * pr.z^2 mod p == pr.x, so the signature is valid. */ + return 1; + } + return 0; +#endif +} + +static int secp256k1_ecdsa_sig_sign(const secp256k1_ecmult_gen_context *ctx, secp256k1_scalar *sigr, secp256k1_scalar *sigs, const secp256k1_scalar *seckey, const secp256k1_scalar *message, const secp256k1_scalar *nonce, int *recid) { + unsigned char b[32]; + secp256k1_gej rp; + secp256k1_ge r; + secp256k1_scalar n; + int overflow = 0; + + secp256k1_ecmult_gen(ctx, &rp, nonce); + secp256k1_ge_set_gej(&r, &rp); + secp256k1_fe_normalize(&r.x); + secp256k1_fe_normalize(&r.y); + secp256k1_fe_get_b32(b, &r.x); + secp256k1_scalar_set_b32(sigr, b, &overflow); + /* These two conditions should be checked before calling */ + VERIFY_CHECK(!secp256k1_scalar_is_zero(sigr)); + VERIFY_CHECK(overflow == 0); + + if (recid) { + /* The overflow condition is cryptographically unreachable as hitting it requires finding the discrete log + * of some P where P.x >= order, and only 1 in about 2^127 points meet this criteria. + */ + *recid = (overflow ? 2 : 0) | (secp256k1_fe_is_odd(&r.y) ? 1 : 0); + } + secp256k1_scalar_mul(&n, sigr, seckey); + secp256k1_scalar_add(&n, &n, message); + secp256k1_scalar_inverse(sigs, nonce); + secp256k1_scalar_mul(sigs, sigs, &n); + secp256k1_scalar_clear(&n); + secp256k1_gej_clear(&rp); + secp256k1_ge_clear(&r); + if (secp256k1_scalar_is_zero(sigs)) { + return 0; + } + if (secp256k1_scalar_is_high(sigs)) { + secp256k1_scalar_negate(sigs, sigs); + if (recid) { + *recid ^= 1; + } + } + return 1; +} + +#endif /* SECP256K1_ECDSA_IMPL_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/eckey.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/eckey.h new file mode 100644 index 000000000..b621f1e6c --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/eckey.h @@ -0,0 +1,25 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECKEY_H +#define SECP256K1_ECKEY_H + +#include + +#include "group.h" +#include "scalar.h" +#include "ecmult.h" +#include "ecmult_gen.h" + +static int secp256k1_eckey_pubkey_parse(secp256k1_ge *elem, const unsigned char *pub, size_t size); +static int secp256k1_eckey_pubkey_serialize(secp256k1_ge *elem, unsigned char *pub, size_t *size, int compressed); + +static int secp256k1_eckey_privkey_tweak_add(secp256k1_scalar *key, const secp256k1_scalar *tweak); +static int secp256k1_eckey_pubkey_tweak_add(const secp256k1_ecmult_context *ctx, secp256k1_ge *key, const secp256k1_scalar *tweak); +static int secp256k1_eckey_privkey_tweak_mul(secp256k1_scalar *key, const secp256k1_scalar *tweak); +static int secp256k1_eckey_pubkey_tweak_mul(const secp256k1_ecmult_context *ctx, secp256k1_ge *key, const secp256k1_scalar *tweak); + +#endif /* SECP256K1_ECKEY_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/eckey_impl.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/eckey_impl.h new file mode 100644 index 000000000..1ab9a68ec --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/eckey_impl.h @@ -0,0 +1,100 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECKEY_IMPL_H +#define SECP256K1_ECKEY_IMPL_H + +#include "eckey.h" + +#include "scalar.h" +#include "field.h" +#include "group.h" +#include "ecmult_gen.h" + +static int secp256k1_eckey_pubkey_parse(secp256k1_ge *elem, const unsigned char *pub, size_t size) { + if (size == 33 && (pub[0] == SECP256K1_TAG_PUBKEY_EVEN || pub[0] == SECP256K1_TAG_PUBKEY_ODD)) { + secp256k1_fe x; + return secp256k1_fe_set_b32(&x, pub+1) && secp256k1_ge_set_xo_var(elem, &x, pub[0] == SECP256K1_TAG_PUBKEY_ODD); + } else if (size == 65 && (pub[0] == 0x04 || pub[0] == 0x06 || pub[0] == 0x07)) { + secp256k1_fe x, y; + if (!secp256k1_fe_set_b32(&x, pub+1) || !secp256k1_fe_set_b32(&y, pub+33)) { + return 0; + } + secp256k1_ge_set_xy(elem, &x, &y); + if ((pub[0] == SECP256K1_TAG_PUBKEY_HYBRID_EVEN || pub[0] == SECP256K1_TAG_PUBKEY_HYBRID_ODD) && + secp256k1_fe_is_odd(&y) != (pub[0] == SECP256K1_TAG_PUBKEY_HYBRID_ODD)) { + return 0; + } + return secp256k1_ge_is_valid_var(elem); + } else { + return 0; + } +} + +static int secp256k1_eckey_pubkey_serialize(secp256k1_ge *elem, unsigned char *pub, size_t *size, int compressed) { + if (secp256k1_ge_is_infinity(elem)) { + return 0; + } + secp256k1_fe_normalize_var(&elem->x); + secp256k1_fe_normalize_var(&elem->y); + secp256k1_fe_get_b32(&pub[1], &elem->x); + if (compressed) { + *size = 33; + pub[0] = secp256k1_fe_is_odd(&elem->y) ? SECP256K1_TAG_PUBKEY_ODD : SECP256K1_TAG_PUBKEY_EVEN; + } else { + *size = 65; + pub[0] = SECP256K1_TAG_PUBKEY_UNCOMPRESSED; + secp256k1_fe_get_b32(&pub[33], &elem->y); + } + return 1; +} + +static int secp256k1_eckey_privkey_tweak_add(secp256k1_scalar *key, const secp256k1_scalar *tweak) { + secp256k1_scalar_add(key, key, tweak); + if (secp256k1_scalar_is_zero(key)) { + return 0; + } + return 1; +} + +static int secp256k1_eckey_pubkey_tweak_add(const secp256k1_ecmult_context *ctx, secp256k1_ge *key, const secp256k1_scalar *tweak) { + secp256k1_gej pt; + secp256k1_scalar one; + secp256k1_gej_set_ge(&pt, key); + secp256k1_scalar_set_int(&one, 1); + secp256k1_ecmult(ctx, &pt, &pt, &one, tweak); + + if (secp256k1_gej_is_infinity(&pt)) { + return 0; + } + secp256k1_ge_set_gej(key, &pt); + return 1; +} + +static int secp256k1_eckey_privkey_tweak_mul(secp256k1_scalar *key, const secp256k1_scalar *tweak) { + if (secp256k1_scalar_is_zero(tweak)) { + return 0; + } + + secp256k1_scalar_mul(key, key, tweak); + return 1; +} + +static int secp256k1_eckey_pubkey_tweak_mul(const secp256k1_ecmult_context *ctx, secp256k1_ge *key, const secp256k1_scalar *tweak) { + secp256k1_scalar zero; + secp256k1_gej pt; + if (secp256k1_scalar_is_zero(tweak)) { + return 0; + } + + secp256k1_scalar_set_int(&zero, 0); + secp256k1_gej_set_ge(&pt, key); + secp256k1_ecmult(ctx, &pt, &pt, tweak, &zero); + secp256k1_ge_set_gej(key, &pt); + return 1; +} + +#endif /* SECP256K1_ECKEY_IMPL_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult.h new file mode 100644 index 000000000..ea1cd8a21 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult.h @@ -0,0 +1,47 @@ +/********************************************************************** + * Copyright (c) 2013, 2014, 2017 Pieter Wuille, Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECMULT_H +#define SECP256K1_ECMULT_H + +#include "num.h" +#include "group.h" +#include "scalar.h" +#include "scratch.h" + +typedef struct { + /* For accelerating the computation of a*P + b*G: */ + secp256k1_ge_storage (*pre_g)[]; /* odd multiples of the generator */ +#ifdef USE_ENDOMORPHISM + secp256k1_ge_storage (*pre_g_128)[]; /* odd multiples of 2^128*generator */ +#endif +} secp256k1_ecmult_context; + +static void secp256k1_ecmult_context_init(secp256k1_ecmult_context *ctx); +static void secp256k1_ecmult_context_build(secp256k1_ecmult_context *ctx, const secp256k1_callback *cb); +static void secp256k1_ecmult_context_clone(secp256k1_ecmult_context *dst, + const secp256k1_ecmult_context *src, const secp256k1_callback *cb); +static void secp256k1_ecmult_context_clear(secp256k1_ecmult_context *ctx); +static int secp256k1_ecmult_context_is_built(const secp256k1_ecmult_context *ctx); + +/** Double multiply: R = na*A + ng*G */ +static void secp256k1_ecmult(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_scalar *na, const secp256k1_scalar *ng); + +typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); + +/** + * Multi-multiply: R = inp_g_sc * G + sum_i ni * Ai. + * Chooses the right algorithm for a given number of points and scratch space + * size. Resets and overwrites the given scratch space. If the points do not + * fit in the scratch space the algorithm is repeatedly run with batches of + * points. + * Returns: 1 on success (including when inp_g_sc is NULL and n is 0) + * 0 if there is not enough scratch space for a single point or + * callback returns 0 + */ +static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); + +#endif /* SECP256K1_ECMULT_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult_const.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult_const.h new file mode 100644 index 000000000..d4804b8b6 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult_const.h @@ -0,0 +1,17 @@ +/********************************************************************** + * Copyright (c) 2015 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECMULT_CONST_H +#define SECP256K1_ECMULT_CONST_H + +#include "scalar.h" +#include "group.h" + +/* Here `bits` should be set to the maximum bitlength of the _absolute value_ of `q`, plus + * one because we internally sometimes add 2 to the number during the WNAF conversion. */ +static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, const secp256k1_scalar *q, int bits); + +#endif /* SECP256K1_ECMULT_CONST_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult_const_impl.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult_const_impl.h new file mode 100644 index 000000000..f4c36a1fa --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult_const_impl.h @@ -0,0 +1,257 @@ +/********************************************************************** + * Copyright (c) 2015 Pieter Wuille, Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECMULT_CONST_IMPL_H +#define SECP256K1_ECMULT_CONST_IMPL_H + +#include "scalar.h" +#include "group.h" +#include "ecmult_const.h" +#include "ecmult_impl.h" + +/* This is like `ECMULT_TABLE_GET_GE` but is constant time */ +#define ECMULT_CONST_TABLE_GET_GE(r,pre,n,w) do { \ + int m; \ + int abs_n = (n) * (((n) > 0) * 2 - 1); \ + int idx_n = abs_n / 2; \ + secp256k1_fe neg_y; \ + VERIFY_CHECK(((n) & 1) == 1); \ + VERIFY_CHECK((n) >= -((1 << ((w)-1)) - 1)); \ + VERIFY_CHECK((n) <= ((1 << ((w)-1)) - 1)); \ + VERIFY_SETUP(secp256k1_fe_clear(&(r)->x)); \ + VERIFY_SETUP(secp256k1_fe_clear(&(r)->y)); \ + for (m = 0; m < ECMULT_TABLE_SIZE(w); m++) { \ + /* This loop is used to avoid secret data in array indices. See + * the comment in ecmult_gen_impl.h for rationale. */ \ + secp256k1_fe_cmov(&(r)->x, &(pre)[m].x, m == idx_n); \ + secp256k1_fe_cmov(&(r)->y, &(pre)[m].y, m == idx_n); \ + } \ + (r)->infinity = 0; \ + secp256k1_fe_negate(&neg_y, &(r)->y, 1); \ + secp256k1_fe_cmov(&(r)->y, &neg_y, (n) != abs_n); \ +} while(0) + + +/** Convert a number to WNAF notation. + * The number becomes represented by sum(2^{wi} * wnaf[i], i=0..WNAF_SIZE(w)+1) - return_val. + * It has the following guarantees: + * - each wnaf[i] an odd integer between -(1 << w) and (1 << w) + * - each wnaf[i] is nonzero + * - the number of words set is always WNAF_SIZE(w) + 1 + * + * Adapted from `The Width-w NAF Method Provides Small Memory and Fast Elliptic Scalar + * Multiplications Secure against Side Channel Attacks`, Okeya and Tagaki. M. Joye (Ed.) + * CT-RSA 2003, LNCS 2612, pp. 328-443, 2003. Springer-Verlagy Berlin Heidelberg 2003 + * + * Numbers reference steps of `Algorithm SPA-resistant Width-w NAF with Odd Scalar` on pp. 335 + */ +static int secp256k1_wnaf_const(int *wnaf, secp256k1_scalar s, int w, int size) { + int global_sign; + int skew = 0; + int word = 0; + + /* 1 2 3 */ + int u_last; + int u = 0; + + int flip; + int bit; + secp256k1_scalar neg_s; + int not_neg_one; + /* Note that we cannot handle even numbers by negating them to be odd, as is + * done in other implementations, since if our scalars were specified to have + * width < 256 for performance reasons, their negations would have width 256 + * and we'd lose any performance benefit. Instead, we use a technique from + * Section 4.2 of the Okeya/Tagaki paper, which is to add either 1 (for even) + * or 2 (for odd) to the number we are encoding, returning a skew value indicating + * this, and having the caller compensate after doing the multiplication. + * + * In fact, we _do_ want to negate numbers to minimize their bit-lengths (and in + * particular, to ensure that the outputs from the endomorphism-split fit into + * 128 bits). If we negate, the parity of our number flips, inverting which of + * {1, 2} we want to add to the scalar when ensuring that it's odd. Further + * complicating things, -1 interacts badly with `secp256k1_scalar_cadd_bit` and + * we need to special-case it in this logic. */ + flip = secp256k1_scalar_is_high(&s); + /* We add 1 to even numbers, 2 to odd ones, noting that negation flips parity */ + bit = flip ^ !secp256k1_scalar_is_even(&s); + /* We check for negative one, since adding 2 to it will cause an overflow */ + secp256k1_scalar_negate(&neg_s, &s); + not_neg_one = !secp256k1_scalar_is_one(&neg_s); + secp256k1_scalar_cadd_bit(&s, bit, not_neg_one); + /* If we had negative one, flip == 1, s.d[0] == 0, bit == 1, so caller expects + * that we added two to it and flipped it. In fact for -1 these operations are + * identical. We only flipped, but since skewing is required (in the sense that + * the skew must be 1 or 2, never zero) and flipping is not, we need to change + * our flags to claim that we only skewed. */ + global_sign = secp256k1_scalar_cond_negate(&s, flip); + global_sign *= not_neg_one * 2 - 1; + skew = 1 << bit; + + /* 4 */ + u_last = secp256k1_scalar_shr_int(&s, w); + while (word * w < size) { + int sign; + int even; + + /* 4.1 4.4 */ + u = secp256k1_scalar_shr_int(&s, w); + /* 4.2 */ + even = ((u & 1) == 0); + sign = 2 * (u_last > 0) - 1; + u += sign * even; + u_last -= sign * even * (1 << w); + + /* 4.3, adapted for global sign change */ + wnaf[word++] = u_last * global_sign; + + u_last = u; + } + wnaf[word] = u * global_sign; + + VERIFY_CHECK(secp256k1_scalar_is_zero(&s)); + VERIFY_CHECK(word == WNAF_SIZE_BITS(size, w)); + return skew; +} + +static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, const secp256k1_scalar *scalar, int size) { + secp256k1_ge pre_a[ECMULT_TABLE_SIZE(WINDOW_A)]; + secp256k1_ge tmpa; + secp256k1_fe Z; + + int skew_1; +#ifdef USE_ENDOMORPHISM + secp256k1_ge pre_a_lam[ECMULT_TABLE_SIZE(WINDOW_A)]; + int wnaf_lam[1 + WNAF_SIZE(WINDOW_A - 1)]; + int skew_lam; + secp256k1_scalar q_1, q_lam; +#endif + int wnaf_1[1 + WNAF_SIZE(WINDOW_A - 1)]; + + int i; + secp256k1_scalar sc = *scalar; + + /* build wnaf representation for q. */ + int rsize = size; +#ifdef USE_ENDOMORPHISM + if (size > 128) { + rsize = 128; + /* split q into q_1 and q_lam (where q = q_1 + q_lam*lambda, and q_1 and q_lam are ~128 bit) */ + secp256k1_scalar_split_lambda(&q_1, &q_lam, &sc); + skew_1 = secp256k1_wnaf_const(wnaf_1, q_1, WINDOW_A - 1, 128); + skew_lam = secp256k1_wnaf_const(wnaf_lam, q_lam, WINDOW_A - 1, 128); + } else +#endif + { + skew_1 = secp256k1_wnaf_const(wnaf_1, sc, WINDOW_A - 1, size); +#ifdef USE_ENDOMORPHISM + skew_lam = 0; +#endif + } + + /* Calculate odd multiples of a. + * All multiples are brought to the same Z 'denominator', which is stored + * in Z. Due to secp256k1' isomorphism we can do all operations pretending + * that the Z coordinate was 1, use affine addition formulae, and correct + * the Z coordinate of the result once at the end. + */ + secp256k1_gej_set_ge(r, a); + secp256k1_ecmult_odd_multiples_table_globalz_windowa(pre_a, &Z, r); + for (i = 0; i < ECMULT_TABLE_SIZE(WINDOW_A); i++) { + secp256k1_fe_normalize_weak(&pre_a[i].y); + } +#ifdef USE_ENDOMORPHISM + if (size > 128) { + for (i = 0; i < ECMULT_TABLE_SIZE(WINDOW_A); i++) { + secp256k1_ge_mul_lambda(&pre_a_lam[i], &pre_a[i]); + } + } +#endif + + /* first loop iteration (separated out so we can directly set r, rather + * than having it start at infinity, get doubled several times, then have + * its new value added to it) */ + i = wnaf_1[WNAF_SIZE_BITS(rsize, WINDOW_A - 1)]; + VERIFY_CHECK(i != 0); + ECMULT_CONST_TABLE_GET_GE(&tmpa, pre_a, i, WINDOW_A); + secp256k1_gej_set_ge(r, &tmpa); +#ifdef USE_ENDOMORPHISM + if (size > 128) { + i = wnaf_lam[WNAF_SIZE_BITS(rsize, WINDOW_A - 1)]; + VERIFY_CHECK(i != 0); + ECMULT_CONST_TABLE_GET_GE(&tmpa, pre_a_lam, i, WINDOW_A); + secp256k1_gej_add_ge(r, r, &tmpa); + } +#endif + /* remaining loop iterations */ + for (i = WNAF_SIZE_BITS(rsize, WINDOW_A - 1) - 1; i >= 0; i--) { + int n; + int j; + for (j = 0; j < WINDOW_A - 1; ++j) { + secp256k1_gej_double_nonzero(r, r, NULL); + } + + n = wnaf_1[i]; + ECMULT_CONST_TABLE_GET_GE(&tmpa, pre_a, n, WINDOW_A); + VERIFY_CHECK(n != 0); + secp256k1_gej_add_ge(r, r, &tmpa); +#ifdef USE_ENDOMORPHISM + if (size > 128) { + n = wnaf_lam[i]; + ECMULT_CONST_TABLE_GET_GE(&tmpa, pre_a_lam, n, WINDOW_A); + VERIFY_CHECK(n != 0); + secp256k1_gej_add_ge(r, r, &tmpa); + } +#endif + } + + secp256k1_fe_mul(&r->z, &r->z, &Z); + + { + /* Correct for wNAF skew */ + secp256k1_ge correction = *a; + secp256k1_ge_storage correction_1_stor; +#ifdef USE_ENDOMORPHISM + secp256k1_ge_storage correction_lam_stor; +#endif + secp256k1_ge_storage a2_stor; + secp256k1_gej tmpj; + secp256k1_gej_set_ge(&tmpj, &correction); + secp256k1_gej_double_var(&tmpj, &tmpj, NULL); + secp256k1_ge_set_gej(&correction, &tmpj); + secp256k1_ge_to_storage(&correction_1_stor, a); +#ifdef USE_ENDOMORPHISM + if (size > 128) { + secp256k1_ge_to_storage(&correction_lam_stor, a); + } +#endif + secp256k1_ge_to_storage(&a2_stor, &correction); + + /* For odd numbers this is 2a (so replace it), for even ones a (so no-op) */ + secp256k1_ge_storage_cmov(&correction_1_stor, &a2_stor, skew_1 == 2); +#ifdef USE_ENDOMORPHISM + if (size > 128) { + secp256k1_ge_storage_cmov(&correction_lam_stor, &a2_stor, skew_lam == 2); + } +#endif + + /* Apply the correction */ + secp256k1_ge_from_storage(&correction, &correction_1_stor); + secp256k1_ge_neg(&correction, &correction); + secp256k1_gej_add_ge(r, r, &correction); + +#ifdef USE_ENDOMORPHISM + if (size > 128) { + secp256k1_ge_from_storage(&correction, &correction_lam_stor); + secp256k1_ge_neg(&correction, &correction); + secp256k1_ge_mul_lambda(&correction, &correction); + secp256k1_gej_add_ge(r, r, &correction); + } +#endif + } +} + +#endif /* SECP256K1_ECMULT_CONST_IMPL_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult_gen.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult_gen.h new file mode 100644 index 000000000..7564b7015 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult_gen.h @@ -0,0 +1,43 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECMULT_GEN_H +#define SECP256K1_ECMULT_GEN_H + +#include "scalar.h" +#include "group.h" + +typedef struct { + /* For accelerating the computation of a*G: + * To harden against timing attacks, use the following mechanism: + * * Break up the multiplicand into groups of 4 bits, called n_0, n_1, n_2, ..., n_63. + * * Compute sum(n_i * 16^i * G + U_i, i=0..63), where: + * * U_i = U * 2^i (for i=0..62) + * * U_i = U * (1-2^63) (for i=63) + * where U is a point with no known corresponding scalar. Note that sum(U_i, i=0..63) = 0. + * For each i, and each of the 16 possible values of n_i, (n_i * 16^i * G + U_i) is + * precomputed (call it prec(i, n_i)). The formula now becomes sum(prec(i, n_i), i=0..63). + * None of the resulting prec group elements have a known scalar, and neither do any of + * the intermediate sums while computing a*G. + */ + secp256k1_ge_storage (*prec)[64][16]; /* prec[j][i] = 16^j * i * G + U_i */ + secp256k1_scalar blind; + secp256k1_gej initial; +} secp256k1_ecmult_gen_context; + +static void secp256k1_ecmult_gen_context_init(secp256k1_ecmult_gen_context* ctx); +static void secp256k1_ecmult_gen_context_build(secp256k1_ecmult_gen_context* ctx, const secp256k1_callback* cb); +static void secp256k1_ecmult_gen_context_clone(secp256k1_ecmult_gen_context *dst, + const secp256k1_ecmult_gen_context* src, const secp256k1_callback* cb); +static void secp256k1_ecmult_gen_context_clear(secp256k1_ecmult_gen_context* ctx); +static int secp256k1_ecmult_gen_context_is_built(const secp256k1_ecmult_gen_context* ctx); + +/** Multiply with the generator: R = a*G */ +static void secp256k1_ecmult_gen(const secp256k1_ecmult_gen_context* ctx, secp256k1_gej *r, const secp256k1_scalar *a); + +static void secp256k1_ecmult_gen_blind(secp256k1_ecmult_gen_context *ctx, const unsigned char *seed32); + +#endif /* SECP256K1_ECMULT_GEN_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult_gen_impl.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult_gen_impl.h new file mode 100644 index 000000000..f99be8c92 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult_gen_impl.h @@ -0,0 +1,210 @@ +/********************************************************************** + * Copyright (c) 2013, 2014, 2015 Pieter Wuille, Gregory Maxwell * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECMULT_GEN_IMPL_H +#define SECP256K1_ECMULT_GEN_IMPL_H + +#include "scalar.h" +#include "group.h" +#include "ecmult_gen.h" +#include "hash_impl.h" +#ifdef USE_ECMULT_STATIC_PRECOMPUTATION +#include "secp256k1_ec_mult_static_context.h" +#endif +static void secp256k1_ecmult_gen_context_init(secp256k1_ecmult_gen_context *ctx) { + ctx->prec = NULL; +} + +static void secp256k1_ecmult_gen_context_build(secp256k1_ecmult_gen_context *ctx, const secp256k1_callback* cb) { +#ifndef USE_ECMULT_STATIC_PRECOMPUTATION + secp256k1_ge prec[1024]; + secp256k1_gej gj; + secp256k1_gej nums_gej; + int i, j; +#endif + + if (ctx->prec != NULL) { + return; + } +#ifndef USE_ECMULT_STATIC_PRECOMPUTATION + ctx->prec = (secp256k1_ge_storage (*)[64][16])checked_malloc(cb, sizeof(*ctx->prec)); + + /* get the generator */ + secp256k1_gej_set_ge(&gj, &secp256k1_ge_const_g); + + /* Construct a group element with no known corresponding scalar (nothing up my sleeve). */ + { + static const unsigned char nums_b32[33] = "The scalar for this x is unknown"; + secp256k1_fe nums_x; + secp256k1_ge nums_ge; + int r; + r = secp256k1_fe_set_b32(&nums_x, nums_b32); + (void)r; + VERIFY_CHECK(r); + r = secp256k1_ge_set_xo_var(&nums_ge, &nums_x, 0); + (void)r; + VERIFY_CHECK(r); + secp256k1_gej_set_ge(&nums_gej, &nums_ge); + /* Add G to make the bits in x uniformly distributed. */ + secp256k1_gej_add_ge_var(&nums_gej, &nums_gej, &secp256k1_ge_const_g, NULL); + } + + /* compute prec. */ + { + secp256k1_gej precj[1024]; /* Jacobian versions of prec. */ + secp256k1_gej gbase; + secp256k1_gej numsbase; + gbase = gj; /* 16^j * G */ + numsbase = nums_gej; /* 2^j * nums. */ + for (j = 0; j < 64; j++) { + /* Set precj[j*16 .. j*16+15] to (numsbase, numsbase + gbase, ..., numsbase + 15*gbase). */ + precj[j*16] = numsbase; + for (i = 1; i < 16; i++) { + secp256k1_gej_add_var(&precj[j*16 + i], &precj[j*16 + i - 1], &gbase, NULL); + } + /* Multiply gbase by 16. */ + for (i = 0; i < 4; i++) { + secp256k1_gej_double_var(&gbase, &gbase, NULL); + } + /* Multiply numbase by 2. */ + secp256k1_gej_double_var(&numsbase, &numsbase, NULL); + if (j == 62) { + /* In the last iteration, numsbase is (1 - 2^j) * nums instead. */ + secp256k1_gej_neg(&numsbase, &numsbase); + secp256k1_gej_add_var(&numsbase, &numsbase, &nums_gej, NULL); + } + } + secp256k1_ge_set_all_gej_var(prec, precj, 1024, cb); + } + for (j = 0; j < 64; j++) { + for (i = 0; i < 16; i++) { + secp256k1_ge_to_storage(&(*ctx->prec)[j][i], &prec[j*16 + i]); + } + } +#else + (void)cb; + ctx->prec = (secp256k1_ge_storage (*)[64][16])secp256k1_ecmult_static_context; +#endif + secp256k1_ecmult_gen_blind(ctx, NULL); +} + +static int secp256k1_ecmult_gen_context_is_built(const secp256k1_ecmult_gen_context* ctx) { + return ctx->prec != NULL; +} + +static void secp256k1_ecmult_gen_context_clone(secp256k1_ecmult_gen_context *dst, + const secp256k1_ecmult_gen_context *src, const secp256k1_callback* cb) { + if (src->prec == NULL) { + dst->prec = NULL; + } else { +#ifndef USE_ECMULT_STATIC_PRECOMPUTATION + dst->prec = (secp256k1_ge_storage (*)[64][16])checked_malloc(cb, sizeof(*dst->prec)); + memcpy(dst->prec, src->prec, sizeof(*dst->prec)); +#else + (void)cb; + dst->prec = src->prec; +#endif + dst->initial = src->initial; + dst->blind = src->blind; + } +} + +static void secp256k1_ecmult_gen_context_clear(secp256k1_ecmult_gen_context *ctx) { +#ifndef USE_ECMULT_STATIC_PRECOMPUTATION + free(ctx->prec); +#endif + secp256k1_scalar_clear(&ctx->blind); + secp256k1_gej_clear(&ctx->initial); + ctx->prec = NULL; +} + +static void secp256k1_ecmult_gen(const secp256k1_ecmult_gen_context *ctx, secp256k1_gej *r, const secp256k1_scalar *gn) { + secp256k1_ge add; + secp256k1_ge_storage adds; + secp256k1_scalar gnb; + int bits; + int i, j; + memset(&adds, 0, sizeof(adds)); + *r = ctx->initial; + /* Blind scalar/point multiplication by computing (n-b)G + bG instead of nG. */ + secp256k1_scalar_add(&gnb, gn, &ctx->blind); + add.infinity = 0; + for (j = 0; j < 64; j++) { + bits = secp256k1_scalar_get_bits(&gnb, j * 4, 4); + for (i = 0; i < 16; i++) { + /** This uses a conditional move to avoid any secret data in array indexes. + * _Any_ use of secret indexes has been demonstrated to result in timing + * sidechannels, even when the cache-line access patterns are uniform. + * See also: + * "A word of warning", CHES 2013 Rump Session, by Daniel J. Bernstein and Peter Schwabe + * (https://cryptojedi.org/peter/data/chesrump-20130822.pdf) and + * "Cache Attacks and Countermeasures: the Case of AES", RSA 2006, + * by Dag Arne Osvik, Adi Shamir, and Eran Tromer + * (http://www.tau.ac.il/~tromer/papers/cache.pdf) + */ + secp256k1_ge_storage_cmov(&adds, &(*ctx->prec)[j][i], i == bits); + } + secp256k1_ge_from_storage(&add, &adds); + secp256k1_gej_add_ge(r, r, &add); + } + bits = 0; + secp256k1_ge_clear(&add); + secp256k1_scalar_clear(&gnb); +} + +/* Setup blinding values for secp256k1_ecmult_gen. */ +static void secp256k1_ecmult_gen_blind(secp256k1_ecmult_gen_context *ctx, const unsigned char *seed32) { + secp256k1_scalar b; + secp256k1_gej gb; + secp256k1_fe s; + unsigned char nonce32[32]; + secp256k1_rfc6979_hmac_sha256 rng; + int retry; + unsigned char keydata[64] = {0}; + if (seed32 == NULL) { + /* When seed is NULL, reset the initial point and blinding value. */ + secp256k1_gej_set_ge(&ctx->initial, &secp256k1_ge_const_g); + secp256k1_gej_neg(&ctx->initial, &ctx->initial); + secp256k1_scalar_set_int(&ctx->blind, 1); + } + /* The prior blinding value (if not reset) is chained forward by including it in the hash. */ + secp256k1_scalar_get_b32(nonce32, &ctx->blind); + /** Using a CSPRNG allows a failure free interface, avoids needing large amounts of random data, + * and guards against weak or adversarial seeds. This is a simpler and safer interface than + * asking the caller for blinding values directly and expecting them to retry on failure. + */ + memcpy(keydata, nonce32, 32); + if (seed32 != NULL) { + memcpy(keydata + 32, seed32, 32); + } + secp256k1_rfc6979_hmac_sha256_initialize(&rng, keydata, seed32 ? 64 : 32); + memset(keydata, 0, sizeof(keydata)); + /* Retry for out of range results to achieve uniformity. */ + do { + secp256k1_rfc6979_hmac_sha256_generate(&rng, nonce32, 32); + retry = !secp256k1_fe_set_b32(&s, nonce32); + retry |= secp256k1_fe_is_zero(&s); + } while (retry); /* This branch true is cryptographically unreachable. Requires sha256_hmac output > Fp. */ + /* Randomize the projection to defend against multiplier sidechannels. */ + secp256k1_gej_rescale(&ctx->initial, &s); + secp256k1_fe_clear(&s); + do { + secp256k1_rfc6979_hmac_sha256_generate(&rng, nonce32, 32); + secp256k1_scalar_set_b32(&b, nonce32, &retry); + /* A blinding value of 0 works, but would undermine the projection hardening. */ + retry |= secp256k1_scalar_is_zero(&b); + } while (retry); /* This branch true is cryptographically unreachable. Requires sha256_hmac output > order. */ + secp256k1_rfc6979_hmac_sha256_finalize(&rng); + memset(nonce32, 0, 32); + secp256k1_ecmult_gen(ctx, &gb, &b); + secp256k1_scalar_negate(&b, &b); + ctx->blind = b; + ctx->initial = gb; + secp256k1_scalar_clear(&b); + secp256k1_gej_clear(&gb); +} + +#endif /* SECP256K1_ECMULT_GEN_IMPL_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult_impl.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult_impl.h new file mode 100644 index 000000000..feab1b741 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/ecmult_impl.h @@ -0,0 +1,1027 @@ +/***************************************************************************** + * Copyright (c) 2013, 2014, 2017 Pieter Wuille, Andrew Poelstra, Jonas Nick * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php. * + *****************************************************************************/ + +#ifndef SECP256K1_ECMULT_IMPL_H +#define SECP256K1_ECMULT_IMPL_H + +#include +#include + +#include "group.h" +#include "scalar.h" +#include "ecmult.h" + +#if defined(EXHAUSTIVE_TEST_ORDER) +/* We need to lower these values for exhaustive tests because + * the tables cannot have infinities in them (this breaks the + * affine-isomorphism stuff which tracks z-ratios) */ +# if EXHAUSTIVE_TEST_ORDER > 128 +# define WINDOW_A 5 +# define WINDOW_G 8 +# elif EXHAUSTIVE_TEST_ORDER > 8 +# define WINDOW_A 4 +# define WINDOW_G 4 +# else +# define WINDOW_A 2 +# define WINDOW_G 2 +# endif +#else +/* optimal for 128-bit and 256-bit exponents. */ +#define WINDOW_A 5 +/** larger numbers may result in slightly better performance, at the cost of + exponentially larger precomputed tables. */ +#ifdef USE_ENDOMORPHISM +/** Two tables for window size 15: 1.375 MiB. */ +#define WINDOW_G 15 +#else +/** One table for window size 16: 1.375 MiB. */ +#define WINDOW_G 16 +#endif +#endif + +#ifdef USE_ENDOMORPHISM + #define WNAF_BITS 128 +#else + #define WNAF_BITS 256 +#endif +#define WNAF_SIZE_BITS(bits, w) (((bits) + (w) - 1) / (w)) +#define WNAF_SIZE(w) WNAF_SIZE_BITS(WNAF_BITS, w) + +/** The number of entries a table with precomputed multiples needs to have. */ +#define ECMULT_TABLE_SIZE(w) (1 << ((w)-2)) + +/* The number of objects allocated on the scratch space for ecmult_multi algorithms */ +#define PIPPENGER_SCRATCH_OBJECTS 6 +#define STRAUSS_SCRATCH_OBJECTS 6 + +#define PIPPENGER_MAX_BUCKET_WINDOW 12 + +/* Minimum number of points for which pippenger_wnaf is faster than strauss wnaf */ +#ifdef USE_ENDOMORPHISM + #define ECMULT_PIPPENGER_THRESHOLD 88 +#else + #define ECMULT_PIPPENGER_THRESHOLD 160 +#endif + +#ifdef USE_ENDOMORPHISM + #define ECMULT_MAX_POINTS_PER_BATCH 5000000 +#else + #define ECMULT_MAX_POINTS_PER_BATCH 10000000 +#endif + +/** Fill a table 'prej' with precomputed odd multiples of a. Prej will contain + * the values [1*a,3*a,...,(2*n-1)*a], so it space for n values. zr[0] will + * contain prej[0].z / a.z. The other zr[i] values = prej[i].z / prej[i-1].z. + * Prej's Z values are undefined, except for the last value. + */ +static void secp256k1_ecmult_odd_multiples_table(int n, secp256k1_gej *prej, secp256k1_fe *zr, const secp256k1_gej *a) { + secp256k1_gej d; + secp256k1_ge a_ge, d_ge; + int i; + + VERIFY_CHECK(!a->infinity); + + secp256k1_gej_double_var(&d, a, NULL); + + /* + * Perform the additions on an isomorphism where 'd' is affine: drop the z coordinate + * of 'd', and scale the 1P starting value's x/y coordinates without changing its z. + */ + d_ge.x = d.x; + d_ge.y = d.y; + d_ge.infinity = 0; + + secp256k1_ge_set_gej_zinv(&a_ge, a, &d.z); + prej[0].x = a_ge.x; + prej[0].y = a_ge.y; + prej[0].z = a->z; + prej[0].infinity = 0; + + zr[0] = d.z; + for (i = 1; i < n; i++) { + secp256k1_gej_add_ge_var(&prej[i], &prej[i-1], &d_ge, &zr[i]); + } + + /* + * Each point in 'prej' has a z coordinate too small by a factor of 'd.z'. Only + * the final point's z coordinate is actually used though, so just update that. + */ + secp256k1_fe_mul(&prej[n-1].z, &prej[n-1].z, &d.z); +} + +/** Fill a table 'pre' with precomputed odd multiples of a. + * + * There are two versions of this function: + * - secp256k1_ecmult_odd_multiples_table_globalz_windowa which brings its + * resulting point set to a single constant Z denominator, stores the X and Y + * coordinates as ge_storage points in pre, and stores the global Z in rz. + * It only operates on tables sized for WINDOW_A wnaf multiples. + * - secp256k1_ecmult_odd_multiples_table_storage_var, which converts its + * resulting point set to actually affine points, and stores those in pre. + * It operates on tables of any size, but uses heap-allocated temporaries. + * + * To compute a*P + b*G, we compute a table for P using the first function, + * and for G using the second (which requires an inverse, but it only needs to + * happen once). + */ +static void secp256k1_ecmult_odd_multiples_table_globalz_windowa(secp256k1_ge *pre, secp256k1_fe *globalz, const secp256k1_gej *a) { + secp256k1_gej prej[ECMULT_TABLE_SIZE(WINDOW_A)]; + secp256k1_fe zr[ECMULT_TABLE_SIZE(WINDOW_A)]; + + /* Compute the odd multiples in Jacobian form. */ + secp256k1_ecmult_odd_multiples_table(ECMULT_TABLE_SIZE(WINDOW_A), prej, zr, a); + /* Bring them to the same Z denominator. */ + secp256k1_ge_globalz_set_table_gej(ECMULT_TABLE_SIZE(WINDOW_A), pre, globalz, prej, zr); +} + +static void secp256k1_ecmult_odd_multiples_table_storage_var(int n, secp256k1_ge_storage *pre, const secp256k1_gej *a, const secp256k1_callback *cb) { + secp256k1_gej *prej = (secp256k1_gej*)checked_malloc(cb, sizeof(secp256k1_gej) * n); + secp256k1_ge *prea = (secp256k1_ge*)checked_malloc(cb, sizeof(secp256k1_ge) * n); + secp256k1_fe *zr = (secp256k1_fe*)checked_malloc(cb, sizeof(secp256k1_fe) * n); + int i; + + /* Compute the odd multiples in Jacobian form. */ + secp256k1_ecmult_odd_multiples_table(n, prej, zr, a); + /* Convert them in batch to affine coordinates. */ + secp256k1_ge_set_table_gej_var(prea, prej, zr, n); + /* Convert them to compact storage form. */ + for (i = 0; i < n; i++) { + secp256k1_ge_to_storage(&pre[i], &prea[i]); + } + + free(prea); + free(prej); + free(zr); +} + +/** The following two macro retrieves a particular odd multiple from a table + * of precomputed multiples. */ +#define ECMULT_TABLE_GET_GE(r,pre,n,w) do { \ + VERIFY_CHECK(((n) & 1) == 1); \ + VERIFY_CHECK((n) >= -((1 << ((w)-1)) - 1)); \ + VERIFY_CHECK((n) <= ((1 << ((w)-1)) - 1)); \ + if ((n) > 0) { \ + *(r) = (pre)[((n)-1)/2]; \ + } else { \ + secp256k1_ge_neg((r), &(pre)[(-(n)-1)/2]); \ + } \ +} while(0) + +#define ECMULT_TABLE_GET_GE_STORAGE(r,pre,n,w) do { \ + VERIFY_CHECK(((n) & 1) == 1); \ + VERIFY_CHECK((n) >= -((1 << ((w)-1)) - 1)); \ + VERIFY_CHECK((n) <= ((1 << ((w)-1)) - 1)); \ + if ((n) > 0) { \ + secp256k1_ge_from_storage((r), &(pre)[((n)-1)/2]); \ + } else { \ + secp256k1_ge_from_storage((r), &(pre)[(-(n)-1)/2]); \ + secp256k1_ge_neg((r), (r)); \ + } \ +} while(0) + +static void secp256k1_ecmult_context_init(secp256k1_ecmult_context *ctx) { + ctx->pre_g = NULL; +#ifdef USE_ENDOMORPHISM + ctx->pre_g_128 = NULL; +#endif +} + +static void secp256k1_ecmult_context_build(secp256k1_ecmult_context *ctx, const secp256k1_callback *cb) { + secp256k1_gej gj; + + if (ctx->pre_g != NULL) { + return; + } + + /* get the generator */ + secp256k1_gej_set_ge(&gj, &secp256k1_ge_const_g); + + ctx->pre_g = (secp256k1_ge_storage (*)[])checked_malloc(cb, sizeof((*ctx->pre_g)[0]) * ECMULT_TABLE_SIZE(WINDOW_G)); + + /* precompute the tables with odd multiples */ + secp256k1_ecmult_odd_multiples_table_storage_var(ECMULT_TABLE_SIZE(WINDOW_G), *ctx->pre_g, &gj, cb); + +#ifdef USE_ENDOMORPHISM + { + secp256k1_gej g_128j; + int i; + + ctx->pre_g_128 = (secp256k1_ge_storage (*)[])checked_malloc(cb, sizeof((*ctx->pre_g_128)[0]) * ECMULT_TABLE_SIZE(WINDOW_G)); + + /* calculate 2^128*generator */ + g_128j = gj; + for (i = 0; i < 128; i++) { + secp256k1_gej_double_var(&g_128j, &g_128j, NULL); + } + secp256k1_ecmult_odd_multiples_table_storage_var(ECMULT_TABLE_SIZE(WINDOW_G), *ctx->pre_g_128, &g_128j, cb); + } +#endif +} + +static void secp256k1_ecmult_context_clone(secp256k1_ecmult_context *dst, + const secp256k1_ecmult_context *src, const secp256k1_callback *cb) { + if (src->pre_g == NULL) { + dst->pre_g = NULL; + } else { + size_t size = sizeof((*dst->pre_g)[0]) * ECMULT_TABLE_SIZE(WINDOW_G); + dst->pre_g = (secp256k1_ge_storage (*)[])checked_malloc(cb, size); + memcpy(dst->pre_g, src->pre_g, size); + } +#ifdef USE_ENDOMORPHISM + if (src->pre_g_128 == NULL) { + dst->pre_g_128 = NULL; + } else { + size_t size = sizeof((*dst->pre_g_128)[0]) * ECMULT_TABLE_SIZE(WINDOW_G); + dst->pre_g_128 = (secp256k1_ge_storage (*)[])checked_malloc(cb, size); + memcpy(dst->pre_g_128, src->pre_g_128, size); + } +#endif +} + +static int secp256k1_ecmult_context_is_built(const secp256k1_ecmult_context *ctx) { + return ctx->pre_g != NULL; +} + +static void secp256k1_ecmult_context_clear(secp256k1_ecmult_context *ctx) { + free(ctx->pre_g); +#ifdef USE_ENDOMORPHISM + free(ctx->pre_g_128); +#endif + secp256k1_ecmult_context_init(ctx); +} + +/** Convert a number to WNAF notation. The number becomes represented by sum(2^i * wnaf[i], i=0..bits), + * with the following guarantees: + * - each wnaf[i] is either 0, or an odd integer between -(1<<(w-1) - 1) and (1<<(w-1) - 1) + * - two non-zero entries in wnaf are separated by at least w-1 zeroes. + * - the number of set values in wnaf is returned. This number is at most 256, and at most one more + * than the number of bits in the (absolute value) of the input. + */ +static int secp256k1_ecmult_wnaf(int *wnaf, int len, const secp256k1_scalar *a, int w) { + secp256k1_scalar s = *a; + int last_set_bit = -1; + int bit = 0; + int sign = 1; + int carry = 0; + + VERIFY_CHECK(wnaf != NULL); + VERIFY_CHECK(0 <= len && len <= 256); + VERIFY_CHECK(a != NULL); + VERIFY_CHECK(2 <= w && w <= 31); + + memset(wnaf, 0, len * sizeof(wnaf[0])); + + if (secp256k1_scalar_get_bits(&s, 255, 1)) { + secp256k1_scalar_negate(&s, &s); + sign = -1; + } + + while (bit < len) { + int now; + int word; + if (secp256k1_scalar_get_bits(&s, bit, 1) == (unsigned int)carry) { + bit++; + continue; + } + + now = w; + if (now > len - bit) { + now = len - bit; + } + + word = secp256k1_scalar_get_bits_var(&s, bit, now) + carry; + + carry = (word >> (w-1)) & 1; + word -= carry << w; + + wnaf[bit] = sign * word; + last_set_bit = bit; + + bit += now; + } +#ifdef VERIFY + CHECK(carry == 0); + while (bit < 256) { + CHECK(secp256k1_scalar_get_bits(&s, bit++, 1) == 0); + } +#endif + return last_set_bit + 1; +} + +struct secp256k1_strauss_point_state { +#ifdef USE_ENDOMORPHISM + secp256k1_scalar na_1, na_lam; + int wnaf_na_1[130]; + int wnaf_na_lam[130]; + int bits_na_1; + int bits_na_lam; +#else + int wnaf_na[256]; + int bits_na; +#endif + size_t input_pos; +}; + +struct secp256k1_strauss_state { + secp256k1_gej* prej; + secp256k1_fe* zr; + secp256k1_ge* pre_a; +#ifdef USE_ENDOMORPHISM + secp256k1_ge* pre_a_lam; +#endif + struct secp256k1_strauss_point_state* ps; +}; + +static void secp256k1_ecmult_strauss_wnaf(const secp256k1_ecmult_context *ctx, const struct secp256k1_strauss_state *state, secp256k1_gej *r, int num, const secp256k1_gej *a, const secp256k1_scalar *na, const secp256k1_scalar *ng) { + secp256k1_ge tmpa; + secp256k1_fe Z; +#ifdef USE_ENDOMORPHISM + /* Splitted G factors. */ + secp256k1_scalar ng_1, ng_128; + int wnaf_ng_1[129]; + int bits_ng_1 = 0; + int wnaf_ng_128[129]; + int bits_ng_128 = 0; +#else + int wnaf_ng[256]; + int bits_ng = 0; +#endif + int i; + int bits = 0; + int np; + int no = 0; + + for (np = 0; np < num; ++np) { + if (secp256k1_scalar_is_zero(&na[np]) || secp256k1_gej_is_infinity(&a[np])) { + continue; + } + state->ps[no].input_pos = np; +#ifdef USE_ENDOMORPHISM + /* split na into na_1 and na_lam (where na = na_1 + na_lam*lambda, and na_1 and na_lam are ~128 bit) */ + secp256k1_scalar_split_lambda(&state->ps[no].na_1, &state->ps[no].na_lam, &na[np]); + + /* build wnaf representation for na_1 and na_lam. */ + state->ps[no].bits_na_1 = secp256k1_ecmult_wnaf(state->ps[no].wnaf_na_1, 130, &state->ps[no].na_1, WINDOW_A); + state->ps[no].bits_na_lam = secp256k1_ecmult_wnaf(state->ps[no].wnaf_na_lam, 130, &state->ps[no].na_lam, WINDOW_A); + VERIFY_CHECK(state->ps[no].bits_na_1 <= 130); + VERIFY_CHECK(state->ps[no].bits_na_lam <= 130); + if (state->ps[no].bits_na_1 > bits) { + bits = state->ps[no].bits_na_1; + } + if (state->ps[no].bits_na_lam > bits) { + bits = state->ps[no].bits_na_lam; + } +#else + /* build wnaf representation for na. */ + state->ps[no].bits_na = secp256k1_ecmult_wnaf(state->ps[no].wnaf_na, 256, &na[np], WINDOW_A); + if (state->ps[no].bits_na > bits) { + bits = state->ps[no].bits_na; + } +#endif + ++no; + } + + /* Calculate odd multiples of a. + * All multiples are brought to the same Z 'denominator', which is stored + * in Z. Due to secp256k1' isomorphism we can do all operations pretending + * that the Z coordinate was 1, use affine addition formulae, and correct + * the Z coordinate of the result once at the end. + * The exception is the precomputed G table points, which are actually + * affine. Compared to the base used for other points, they have a Z ratio + * of 1/Z, so we can use secp256k1_gej_add_zinv_var, which uses the same + * isomorphism to efficiently add with a known Z inverse. + */ + if (no > 0) { + /* Compute the odd multiples in Jacobian form. */ + secp256k1_ecmult_odd_multiples_table(ECMULT_TABLE_SIZE(WINDOW_A), state->prej, state->zr, &a[state->ps[0].input_pos]); + for (np = 1; np < no; ++np) { + secp256k1_gej tmp = a[state->ps[np].input_pos]; +#ifdef VERIFY + secp256k1_fe_normalize_var(&(state->prej[(np - 1) * ECMULT_TABLE_SIZE(WINDOW_A) + ECMULT_TABLE_SIZE(WINDOW_A) - 1].z)); +#endif + secp256k1_gej_rescale(&tmp, &(state->prej[(np - 1) * ECMULT_TABLE_SIZE(WINDOW_A) + ECMULT_TABLE_SIZE(WINDOW_A) - 1].z)); + secp256k1_ecmult_odd_multiples_table(ECMULT_TABLE_SIZE(WINDOW_A), state->prej + np * ECMULT_TABLE_SIZE(WINDOW_A), state->zr + np * ECMULT_TABLE_SIZE(WINDOW_A), &tmp); + secp256k1_fe_mul(state->zr + np * ECMULT_TABLE_SIZE(WINDOW_A), state->zr + np * ECMULT_TABLE_SIZE(WINDOW_A), &(a[state->ps[np].input_pos].z)); + } + /* Bring them to the same Z denominator. */ + secp256k1_ge_globalz_set_table_gej(ECMULT_TABLE_SIZE(WINDOW_A) * no, state->pre_a, &Z, state->prej, state->zr); + } else { + secp256k1_fe_set_int(&Z, 1); + } + +#ifdef USE_ENDOMORPHISM + for (np = 0; np < no; ++np) { + for (i = 0; i < ECMULT_TABLE_SIZE(WINDOW_A); i++) { + secp256k1_ge_mul_lambda(&state->pre_a_lam[np * ECMULT_TABLE_SIZE(WINDOW_A) + i], &state->pre_a[np * ECMULT_TABLE_SIZE(WINDOW_A) + i]); + } + } + + if (ng) { + /* split ng into ng_1 and ng_128 (where gn = gn_1 + gn_128*2^128, and gn_1 and gn_128 are ~128 bit) */ + secp256k1_scalar_split_128(&ng_1, &ng_128, ng); + + /* Build wnaf representation for ng_1 and ng_128 */ + bits_ng_1 = secp256k1_ecmult_wnaf(wnaf_ng_1, 129, &ng_1, WINDOW_G); + bits_ng_128 = secp256k1_ecmult_wnaf(wnaf_ng_128, 129, &ng_128, WINDOW_G); + if (bits_ng_1 > bits) { + bits = bits_ng_1; + } + if (bits_ng_128 > bits) { + bits = bits_ng_128; + } + } +#else + if (ng) { + bits_ng = secp256k1_ecmult_wnaf(wnaf_ng, 256, ng, WINDOW_G); + if (bits_ng > bits) { + bits = bits_ng; + } + } +#endif + + secp256k1_gej_set_infinity(r); + + for (i = bits - 1; i >= 0; i--) { + int n; + secp256k1_gej_double_var(r, r, NULL); +#ifdef USE_ENDOMORPHISM + for (np = 0; np < no; ++np) { + if (i < state->ps[np].bits_na_1 && (n = state->ps[np].wnaf_na_1[i])) { + ECMULT_TABLE_GET_GE(&tmpa, state->pre_a + np * ECMULT_TABLE_SIZE(WINDOW_A), n, WINDOW_A); + secp256k1_gej_add_ge_var(r, r, &tmpa, NULL); + } + if (i < state->ps[np].bits_na_lam && (n = state->ps[np].wnaf_na_lam[i])) { + ECMULT_TABLE_GET_GE(&tmpa, state->pre_a_lam + np * ECMULT_TABLE_SIZE(WINDOW_A), n, WINDOW_A); + secp256k1_gej_add_ge_var(r, r, &tmpa, NULL); + } + } + if (i < bits_ng_1 && (n = wnaf_ng_1[i])) { + ECMULT_TABLE_GET_GE_STORAGE(&tmpa, *ctx->pre_g, n, WINDOW_G); + secp256k1_gej_add_zinv_var(r, r, &tmpa, &Z); + } + if (i < bits_ng_128 && (n = wnaf_ng_128[i])) { + ECMULT_TABLE_GET_GE_STORAGE(&tmpa, *ctx->pre_g_128, n, WINDOW_G); + secp256k1_gej_add_zinv_var(r, r, &tmpa, &Z); + } +#else + for (np = 0; np < no; ++np) { + if (i < state->ps[np].bits_na && (n = state->ps[np].wnaf_na[i])) { + ECMULT_TABLE_GET_GE(&tmpa, state->pre_a + np * ECMULT_TABLE_SIZE(WINDOW_A), n, WINDOW_A); + secp256k1_gej_add_ge_var(r, r, &tmpa, NULL); + } + } + if (i < bits_ng && (n = wnaf_ng[i])) { + ECMULT_TABLE_GET_GE_STORAGE(&tmpa, *ctx->pre_g, n, WINDOW_G); + secp256k1_gej_add_zinv_var(r, r, &tmpa, &Z); + } +#endif + } + + if (!r->infinity) { + secp256k1_fe_mul(&r->z, &r->z, &Z); + } +} + +static void secp256k1_ecmult(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_scalar *na, const secp256k1_scalar *ng) { + secp256k1_gej prej[ECMULT_TABLE_SIZE(WINDOW_A)]; + secp256k1_fe zr[ECMULT_TABLE_SIZE(WINDOW_A)]; + secp256k1_ge pre_a[ECMULT_TABLE_SIZE(WINDOW_A)]; + struct secp256k1_strauss_point_state ps[1]; +#ifdef USE_ENDOMORPHISM + secp256k1_ge pre_a_lam[ECMULT_TABLE_SIZE(WINDOW_A)]; +#endif + struct secp256k1_strauss_state state; + + state.prej = prej; + state.zr = zr; + state.pre_a = pre_a; +#ifdef USE_ENDOMORPHISM + state.pre_a_lam = pre_a_lam; +#endif + state.ps = ps; + secp256k1_ecmult_strauss_wnaf(ctx, &state, r, 1, a, na, ng); +} + +static size_t secp256k1_strauss_scratch_size(size_t n_points) { +#ifdef USE_ENDOMORPHISM + static const size_t point_size = (2 * sizeof(secp256k1_ge) + sizeof(secp256k1_gej) + sizeof(secp256k1_fe)) * ECMULT_TABLE_SIZE(WINDOW_A) + sizeof(struct secp256k1_strauss_point_state) + sizeof(secp256k1_gej) + sizeof(secp256k1_scalar); +#else + static const size_t point_size = (sizeof(secp256k1_ge) + sizeof(secp256k1_gej) + sizeof(secp256k1_fe)) * ECMULT_TABLE_SIZE(WINDOW_A) + sizeof(struct secp256k1_strauss_point_state) + sizeof(secp256k1_gej) + sizeof(secp256k1_scalar); +#endif + return n_points*point_size; +} + +static int secp256k1_ecmult_strauss_batch(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n_points, size_t cb_offset) { + secp256k1_gej* points; + secp256k1_scalar* scalars; + struct secp256k1_strauss_state state; + size_t i; + + secp256k1_gej_set_infinity(r); + if (inp_g_sc == NULL && n_points == 0) { + return 1; + } + + if (!secp256k1_scratch_allocate_frame(scratch, secp256k1_strauss_scratch_size(n_points), STRAUSS_SCRATCH_OBJECTS)) { + return 0; + } + points = (secp256k1_gej*)secp256k1_scratch_alloc(scratch, n_points * sizeof(secp256k1_gej)); + scalars = (secp256k1_scalar*)secp256k1_scratch_alloc(scratch, n_points * sizeof(secp256k1_scalar)); + state.prej = (secp256k1_gej*)secp256k1_scratch_alloc(scratch, n_points * ECMULT_TABLE_SIZE(WINDOW_A) * sizeof(secp256k1_gej)); + state.zr = (secp256k1_fe*)secp256k1_scratch_alloc(scratch, n_points * ECMULT_TABLE_SIZE(WINDOW_A) * sizeof(secp256k1_fe)); +#ifdef USE_ENDOMORPHISM + state.pre_a = (secp256k1_ge*)secp256k1_scratch_alloc(scratch, n_points * 2 * ECMULT_TABLE_SIZE(WINDOW_A) * sizeof(secp256k1_ge)); + state.pre_a_lam = state.pre_a + n_points * ECMULT_TABLE_SIZE(WINDOW_A); +#else + state.pre_a = (secp256k1_ge*)secp256k1_scratch_alloc(scratch, n_points * ECMULT_TABLE_SIZE(WINDOW_A) * sizeof(secp256k1_ge)); +#endif + state.ps = (struct secp256k1_strauss_point_state*)secp256k1_scratch_alloc(scratch, n_points * sizeof(struct secp256k1_strauss_point_state)); + + for (i = 0; i < n_points; i++) { + secp256k1_ge point; + if (!cb(&scalars[i], &point, i+cb_offset, cbdata)) { + secp256k1_scratch_deallocate_frame(scratch); + return 0; + } + secp256k1_gej_set_ge(&points[i], &point); + } + secp256k1_ecmult_strauss_wnaf(ctx, &state, r, (int)n_points, points, scalars, inp_g_sc); + secp256k1_scratch_deallocate_frame(scratch); + return 1; +} + +/* Wrapper for secp256k1_ecmult_multi_func interface */ +static int secp256k1_ecmult_strauss_batch_single(const secp256k1_ecmult_context *actx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) { + return secp256k1_ecmult_strauss_batch(actx, scratch, r, inp_g_sc, cb, cbdata, n, 0); +} + +static size_t secp256k1_strauss_max_points(secp256k1_scratch *scratch) { + return secp256k1_scratch_max_allocation(scratch, STRAUSS_SCRATCH_OBJECTS) / secp256k1_strauss_scratch_size(1); +} + +/** Convert a number to WNAF notation. + * The number becomes represented by sum(2^{wi} * wnaf[i], i=0..WNAF_SIZE(w)+1) - return_val. + * It has the following guarantees: + * - each wnaf[i] is either 0 or an odd integer between -(1 << w) and (1 << w) + * - the number of words set is always WNAF_SIZE(w) + * - the returned skew is 0 or 1 + */ +static int secp256k1_wnaf_fixed(int *wnaf, const secp256k1_scalar *s, int w) { + int skew = 0; + int pos; + int max_pos; + int last_w; + const secp256k1_scalar *work = s; + + if (secp256k1_scalar_is_zero(s)) { + for (pos = 0; pos < WNAF_SIZE(w); pos++) { + wnaf[pos] = 0; + } + return 0; + } + + if (secp256k1_scalar_is_even(s)) { + skew = 1; + } + + wnaf[0] = secp256k1_scalar_get_bits_var(work, 0, w) + skew; + /* Compute last window size. Relevant when window size doesn't divide the + * number of bits in the scalar */ + last_w = WNAF_BITS - (WNAF_SIZE(w) - 1) * w; + + /* Store the position of the first nonzero word in max_pos to allow + * skipping leading zeros when calculating the wnaf. */ + for (pos = WNAF_SIZE(w) - 1; pos > 0; pos--) { + int val = secp256k1_scalar_get_bits_var(work, pos * w, pos == WNAF_SIZE(w)-1 ? last_w : w); + if(val != 0) { + break; + } + wnaf[pos] = 0; + } + max_pos = pos; + pos = 1; + + while (pos <= max_pos) { + int val = secp256k1_scalar_get_bits_var(work, pos * w, pos == WNAF_SIZE(w)-1 ? last_w : w); + if ((val & 1) == 0) { + wnaf[pos - 1] -= (1 << w); + wnaf[pos] = (val + 1); + } else { + wnaf[pos] = val; + } + /* Set a coefficient to zero if it is 1 or -1 and the proceeding digit + * is strictly negative or strictly positive respectively. Only change + * coefficients at previous positions because above code assumes that + * wnaf[pos - 1] is odd. + */ + if (pos >= 2 && ((wnaf[pos - 1] == 1 && wnaf[pos - 2] < 0) || (wnaf[pos - 1] == -1 && wnaf[pos - 2] > 0))) { + if (wnaf[pos - 1] == 1) { + wnaf[pos - 2] += 1 << w; + } else { + wnaf[pos - 2] -= 1 << w; + } + wnaf[pos - 1] = 0; + } + ++pos; + } + + return skew; +} + +struct secp256k1_pippenger_point_state { + int skew_na; + size_t input_pos; +}; + +struct secp256k1_pippenger_state { + int *wnaf_na; + struct secp256k1_pippenger_point_state* ps; +}; + +/* + * pippenger_wnaf computes the result of a multi-point multiplication as + * follows: The scalars are brought into wnaf with n_wnaf elements each. Then + * for every i < n_wnaf, first each point is added to a "bucket" corresponding + * to the point's wnaf[i]. Second, the buckets are added together such that + * r += 1*bucket[0] + 3*bucket[1] + 5*bucket[2] + ... + */ +static int secp256k1_ecmult_pippenger_wnaf(secp256k1_gej *buckets, int bucket_window, struct secp256k1_pippenger_state *state, secp256k1_gej *r, const secp256k1_scalar *sc, const secp256k1_ge *pt, size_t num) { + size_t n_wnaf = WNAF_SIZE(bucket_window+1); + size_t np; + size_t no = 0; + int i; + int j; + + for (np = 0; np < num; ++np) { + if (secp256k1_scalar_is_zero(&sc[np]) || secp256k1_ge_is_infinity(&pt[np])) { + continue; + } + state->ps[no].input_pos = np; + state->ps[no].skew_na = secp256k1_wnaf_fixed(&state->wnaf_na[no*n_wnaf], &sc[np], bucket_window+1); + no++; + } + secp256k1_gej_set_infinity(r); + + if (no == 0) { + return 1; + } + + for (i = (int)n_wnaf - 1; i >= 0; i--) { + secp256k1_gej running_sum; + + for(j = 0; j < ECMULT_TABLE_SIZE(bucket_window+2); j++) { + secp256k1_gej_set_infinity(&buckets[j]); + } + + for (np = 0; np < no; ++np) { + int n = state->wnaf_na[np*n_wnaf + i]; + struct secp256k1_pippenger_point_state point_state = state->ps[np]; + secp256k1_ge tmp; + int idx; + + if (i == 0) { + /* correct for wnaf skew */ + int skew = point_state.skew_na; + if (skew) { + secp256k1_ge_neg(&tmp, &pt[point_state.input_pos]); + secp256k1_gej_add_ge_var(&buckets[0], &buckets[0], &tmp, NULL); + } + } + if (n > 0) { + idx = (n - 1)/2; + secp256k1_gej_add_ge_var(&buckets[idx], &buckets[idx], &pt[point_state.input_pos], NULL); + } else if (n < 0) { + idx = -(n + 1)/2; + secp256k1_ge_neg(&tmp, &pt[point_state.input_pos]); + secp256k1_gej_add_ge_var(&buckets[idx], &buckets[idx], &tmp, NULL); + } + } + + for(j = 0; j < bucket_window; j++) { + secp256k1_gej_double_var(r, r, NULL); + } + + secp256k1_gej_set_infinity(&running_sum); + /* Accumulate the sum: bucket[0] + 3*bucket[1] + 5*bucket[2] + 7*bucket[3] + ... + * = bucket[0] + bucket[1] + bucket[2] + bucket[3] + ... + * + 2 * (bucket[1] + 2*bucket[2] + 3*bucket[3] + ...) + * using an intermediate running sum: + * running_sum = bucket[0] + bucket[1] + bucket[2] + ... + * + * The doubling is done implicitly by deferring the final window doubling (of 'r'). + */ + for(j = ECMULT_TABLE_SIZE(bucket_window+2) - 1; j > 0; j--) { + secp256k1_gej_add_var(&running_sum, &running_sum, &buckets[j], NULL); + secp256k1_gej_add_var(r, r, &running_sum, NULL); + } + + secp256k1_gej_add_var(&running_sum, &running_sum, &buckets[0], NULL); + secp256k1_gej_double_var(r, r, NULL); + secp256k1_gej_add_var(r, r, &running_sum, NULL); + } + return 1; +} + +/** + * Returns optimal bucket_window (number of bits of a scalar represented by a + * set of buckets) for a given number of points. + */ +static int secp256k1_pippenger_bucket_window(size_t n) { +#ifdef USE_ENDOMORPHISM + if (n <= 1) { + return 1; + } else if (n <= 4) { + return 2; + } else if (n <= 20) { + return 3; + } else if (n <= 57) { + return 4; + } else if (n <= 136) { + return 5; + } else if (n <= 235) { + return 6; + } else if (n <= 1260) { + return 7; + } else if (n <= 4420) { + return 9; + } else if (n <= 7880) { + return 10; + } else if (n <= 16050) { + return 11; + } else { + return PIPPENGER_MAX_BUCKET_WINDOW; + } +#else + if (n <= 1) { + return 1; + } else if (n <= 11) { + return 2; + } else if (n <= 45) { + return 3; + } else if (n <= 100) { + return 4; + } else if (n <= 275) { + return 5; + } else if (n <= 625) { + return 6; + } else if (n <= 1850) { + return 7; + } else if (n <= 3400) { + return 8; + } else if (n <= 9630) { + return 9; + } else if (n <= 17900) { + return 10; + } else if (n <= 32800) { + return 11; + } else { + return PIPPENGER_MAX_BUCKET_WINDOW; + } +#endif +} + +/** + * Returns the maximum optimal number of points for a bucket_window. + */ +static size_t secp256k1_pippenger_bucket_window_inv(int bucket_window) { + switch(bucket_window) { +#ifdef USE_ENDOMORPHISM + case 1: return 1; + case 2: return 4; + case 3: return 20; + case 4: return 57; + case 5: return 136; + case 6: return 235; + case 7: return 1260; + case 8: return 1260; + case 9: return 4420; + case 10: return 7880; + case 11: return 16050; + case PIPPENGER_MAX_BUCKET_WINDOW: return SIZE_MAX; +#else + case 1: return 1; + case 2: return 11; + case 3: return 45; + case 4: return 100; + case 5: return 275; + case 6: return 625; + case 7: return 1850; + case 8: return 3400; + case 9: return 9630; + case 10: return 17900; + case 11: return 32800; + case PIPPENGER_MAX_BUCKET_WINDOW: return SIZE_MAX; +#endif + } + return 0; +} + + +#ifdef USE_ENDOMORPHISM +SECP256K1_INLINE static void secp256k1_ecmult_endo_split(secp256k1_scalar *s1, secp256k1_scalar *s2, secp256k1_ge *p1, secp256k1_ge *p2) { + secp256k1_scalar tmp = *s1; + secp256k1_scalar_split_lambda(s1, s2, &tmp); + secp256k1_ge_mul_lambda(p2, p1); + + if (secp256k1_scalar_is_high(s1)) { + secp256k1_scalar_negate(s1, s1); + secp256k1_ge_neg(p1, p1); + } + if (secp256k1_scalar_is_high(s2)) { + secp256k1_scalar_negate(s2, s2); + secp256k1_ge_neg(p2, p2); + } +} +#endif + +/** + * Returns the scratch size required for a given number of points (excluding + * base point G) without considering alignment. + */ +static size_t secp256k1_pippenger_scratch_size(size_t n_points, int bucket_window) { +#ifdef USE_ENDOMORPHISM + size_t entries = 2*n_points + 2; +#else + size_t entries = n_points + 1; +#endif + size_t entry_size = sizeof(secp256k1_ge) + sizeof(secp256k1_scalar) + sizeof(struct secp256k1_pippenger_point_state) + (WNAF_SIZE(bucket_window+1)+1)*sizeof(int); + return ((1<ps = (struct secp256k1_pippenger_point_state *) secp256k1_scratch_alloc(scratch, entries * sizeof(*state_space->ps)); + state_space->wnaf_na = (int *) secp256k1_scratch_alloc(scratch, entries*(WNAF_SIZE(bucket_window+1)) * sizeof(int)); + buckets = (secp256k1_gej *) secp256k1_scratch_alloc(scratch, (1<ps[i].skew_na = 0; + for(j = 0; j < WNAF_SIZE(bucket_window+1); j++) { + state_space->wnaf_na[i * WNAF_SIZE(bucket_window+1) + j] = 0; + } + } + for(i = 0; i < 1< max_alloc) { + break; + } + space_for_points = max_alloc - space_overhead; + + n_points = space_for_points/entry_size; + n_points = n_points > max_points ? max_points : n_points; + if (n_points > res) { + res = n_points; + } + if (n_points < max_points) { + /* A larger bucket_window may support even more points. But if we + * would choose that then the caller couldn't safely use any number + * smaller than what this function returns */ + break; + } + } + return res; +} + +typedef int (*secp256k1_ecmult_multi_func)(const secp256k1_ecmult_context*, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t); +static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) { + size_t i; + + int (*f)(const secp256k1_ecmult_context*, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t, size_t); + size_t max_points; + size_t n_batches; + size_t n_batch_points; + + secp256k1_gej_set_infinity(r); + if (inp_g_sc == NULL && n == 0) { + return 1; + } else if (n == 0) { + secp256k1_scalar szero; + secp256k1_scalar_set_int(&szero, 0); + secp256k1_ecmult(ctx, r, r, &szero, inp_g_sc); + return 1; + } + + max_points = secp256k1_pippenger_max_points(scratch); + if (max_points == 0) { + return 0; + } else if (max_points > ECMULT_MAX_POINTS_PER_BATCH) { + max_points = ECMULT_MAX_POINTS_PER_BATCH; + } + n_batches = (n+max_points-1)/max_points; + n_batch_points = (n+n_batches-1)/n_batches; + + if (n_batch_points >= ECMULT_PIPPENGER_THRESHOLD) { + f = secp256k1_ecmult_pippenger_batch; + } else { + max_points = secp256k1_strauss_max_points(scratch); + if (max_points == 0) { + return 0; + } + n_batches = (n+max_points-1)/max_points; + n_batch_points = (n+n_batches-1)/n_batches; + f = secp256k1_ecmult_strauss_batch; + } + for(i = 0; i < n_batches; i++) { + size_t nbp = n < n_batch_points ? n : n_batch_points; + size_t offset = n_batch_points*i; + secp256k1_gej tmp; + if (!f(ctx, scratch, &tmp, i == 0 ? inp_g_sc : NULL, cb, cbdata, nbp, offset)) { + return 0; + } + secp256k1_gej_add_var(r, r, &tmp, NULL); + n -= nbp; + } + return 1; +} + +#endif /* SECP256K1_ECMULT_IMPL_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field.h new file mode 100644 index 000000000..ce3aa462c --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field.h @@ -0,0 +1,130 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_FIELD_H +#define SECP256K1_FIELD_H + +/** Field element module. + * + * Field elements can be represented in several ways, but code accessing + * it (and implementations) need to take certain properties into account: + * - Each field element can be normalized or not. + * - Each field element has a magnitude, which represents how far away + * its representation is away from normalization. Normalized elements + * always have a magnitude of 1, but a magnitude of 1 doesn't imply + * normality. + */ + +#include "secp256k1-config.h" + +#if defined(USE_FIELD_10X26) +#include "field_10x26.h" +#elif defined(USE_FIELD_5X52) +#include "field_5x52.h" +#else +#error "Please select field implementation" +#endif + +#include "util.h" + +/** Normalize a field element. */ +static void secp256k1_fe_normalize(secp256k1_fe *r); + +/** Weakly normalize a field element: reduce it magnitude to 1, but don't fully normalize. */ +static void secp256k1_fe_normalize_weak(secp256k1_fe *r); + +/** Normalize a field element, without constant-time guarantee. */ +static void secp256k1_fe_normalize_var(secp256k1_fe *r); + +/** Verify whether a field element represents zero i.e. would normalize to a zero value. The field + * implementation may optionally normalize the input, but this should not be relied upon. */ +static int secp256k1_fe_normalizes_to_zero(secp256k1_fe *r); + +/** Verify whether a field element represents zero i.e. would normalize to a zero value. The field + * implementation may optionally normalize the input, but this should not be relied upon. */ +static int secp256k1_fe_normalizes_to_zero_var(secp256k1_fe *r); + +/** Set a field element equal to a small integer. Resulting field element is normalized. */ +static void secp256k1_fe_set_int(secp256k1_fe *r, int a); + +/** Sets a field element equal to zero, initializing all fields. */ +static void secp256k1_fe_clear(secp256k1_fe *a); + +/** Verify whether a field element is zero. Requires the input to be normalized. */ +static int secp256k1_fe_is_zero(const secp256k1_fe *a); + +/** Check the "oddness" of a field element. Requires the input to be normalized. */ +static int secp256k1_fe_is_odd(const secp256k1_fe *a); + +/** Compare two field elements. Requires magnitude-1 inputs. */ +static int secp256k1_fe_equal(const secp256k1_fe *a, const secp256k1_fe *b); + +/** Same as secp256k1_fe_equal, but may be variable time. */ +static int secp256k1_fe_equal_var(const secp256k1_fe *a, const secp256k1_fe *b); + +/** Compare two field elements. Requires both inputs to be normalized */ +static int secp256k1_fe_cmp_var(const secp256k1_fe *a, const secp256k1_fe *b); + +/** Set a field element equal to 32-byte big endian value. If successful, the resulting field element is normalized. */ +static int secp256k1_fe_set_b32(secp256k1_fe *r, const unsigned char *a); + +/** Convert a field element to a 32-byte big endian value. Requires the input to be normalized */ +static void secp256k1_fe_get_b32(unsigned char *r, const secp256k1_fe *a); + +/** Set a field element equal to the additive inverse of another. Takes a maximum magnitude of the input + * as an argument. The magnitude of the output is one higher. */ +static void secp256k1_fe_negate(secp256k1_fe *r, const secp256k1_fe *a, int m); + +/** Multiplies the passed field element with a small integer constant. Multiplies the magnitude by that + * small integer. */ +static void secp256k1_fe_mul_int(secp256k1_fe *r, int a); + +/** Adds a field element to another. The result has the sum of the inputs' magnitudes as magnitude. */ +static void secp256k1_fe_add(secp256k1_fe *r, const secp256k1_fe *a); + +/** Sets a field element to be the product of two others. Requires the inputs' magnitudes to be at most 8. + * The output magnitude is 1 (but not guaranteed to be normalized). */ +static void secp256k1_fe_mul(secp256k1_fe *r, const secp256k1_fe *a, const secp256k1_fe * SECP256K1_RESTRICT b); + +/** Sets a field element to be the square of another. Requires the input's magnitude to be at most 8. + * The output magnitude is 1 (but not guaranteed to be normalized). */ +static void secp256k1_fe_sqr(secp256k1_fe *r, const secp256k1_fe *a); + +/** If a has a square root, it is computed in r and 1 is returned. If a does not + * have a square root, the root of its negation is computed and 0 is returned. + * The input's magnitude can be at most 8. The output magnitude is 1 (but not + * guaranteed to be normalized). The result in r will always be a square + * itself. */ +static int secp256k1_fe_sqrt(secp256k1_fe *r, const secp256k1_fe *a); + +/** Checks whether a field element is a quadratic residue. */ +static int secp256k1_fe_is_quad_var(const secp256k1_fe *a); + +/** Sets a field element to be the (modular) inverse of another. Requires the input's magnitude to be + * at most 8. The output magnitude is 1 (but not guaranteed to be normalized). */ +static void secp256k1_fe_inv(secp256k1_fe *r, const secp256k1_fe *a); + +/** Potentially faster version of secp256k1_fe_inv, without constant-time guarantee. */ +static void secp256k1_fe_inv_var(secp256k1_fe *r, const secp256k1_fe *a); + +/** Calculate the (modular) inverses of a batch of field elements. Requires the inputs' magnitudes to be + * at most 8. The output magnitudes are 1 (but not guaranteed to be normalized). The inputs and + * outputs must not overlap in memory. */ +static void secp256k1_fe_inv_all_var(secp256k1_fe *r, const secp256k1_fe *a, size_t len); + +/** Convert a field element to the storage type. */ +static void secp256k1_fe_to_storage(secp256k1_fe_storage *r, const secp256k1_fe *a); + +/** Convert a field element back from the storage type. */ +static void secp256k1_fe_from_storage(secp256k1_fe *r, const secp256k1_fe_storage *a); + +/** If flag is true, set *r equal to *a; otherwise leave it. Constant-time. */ +static void secp256k1_fe_storage_cmov(secp256k1_fe_storage *r, const secp256k1_fe_storage *a, int flag); + +/** If flag is true, set *r equal to *a; otherwise leave it. Constant-time. */ +static void secp256k1_fe_cmov(secp256k1_fe *r, const secp256k1_fe *a, int flag); + +#endif /* SECP256K1_FIELD_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_10x26.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_10x26.h new file mode 100644 index 000000000..727c5267f --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_10x26.h @@ -0,0 +1,48 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_FIELD_REPR_H +#define SECP256K1_FIELD_REPR_H + +#include + +typedef struct { + /* X = sum(i=0..9, elem[i]*2^26) mod n */ + uint32_t n[10]; +#ifdef VERIFY + int magnitude; + int normalized; +#endif +} secp256k1_fe; + +/* Unpacks a constant into a overlapping multi-limbed FE element. */ +#define SECP256K1_FE_CONST_INNER(d7, d6, d5, d4, d3, d2, d1, d0) { \ + (d0) & 0x3FFFFFFUL, \ + (((uint32_t)d0) >> 26) | (((uint32_t)(d1) & 0xFFFFFUL) << 6), \ + (((uint32_t)d1) >> 20) | (((uint32_t)(d2) & 0x3FFFUL) << 12), \ + (((uint32_t)d2) >> 14) | (((uint32_t)(d3) & 0xFFUL) << 18), \ + (((uint32_t)d3) >> 8) | (((uint32_t)(d4) & 0x3UL) << 24), \ + (((uint32_t)d4) >> 2) & 0x3FFFFFFUL, \ + (((uint32_t)d4) >> 28) | (((uint32_t)(d5) & 0x3FFFFFUL) << 4), \ + (((uint32_t)d5) >> 22) | (((uint32_t)(d6) & 0xFFFFUL) << 10), \ + (((uint32_t)d6) >> 16) | (((uint32_t)(d7) & 0x3FFUL) << 16), \ + (((uint32_t)d7) >> 10) \ +} + +#ifdef VERIFY +#define SECP256K1_FE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {SECP256K1_FE_CONST_INNER((d7), (d6), (d5), (d4), (d3), (d2), (d1), (d0)), 1, 1} +#else +#define SECP256K1_FE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {SECP256K1_FE_CONST_INNER((d7), (d6), (d5), (d4), (d3), (d2), (d1), (d0))} +#endif + +typedef struct { + uint32_t n[8]; +} secp256k1_fe_storage; + +#define SECP256K1_FE_STORAGE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{ (d0), (d1), (d2), (d3), (d4), (d5), (d6), (d7) }} +#define SECP256K1_FE_STORAGE_CONST_GET(d) d.n[7], d.n[6], d.n[5], d.n[4],d.n[3], d.n[2], d.n[1], d.n[0] + +#endif /* SECP256K1_FIELD_REPR_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_10x26_impl.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_10x26_impl.h new file mode 100644 index 000000000..06be299c4 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_10x26_impl.h @@ -0,0 +1,1161 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_FIELD_REPR_IMPL_H +#define SECP256K1_FIELD_REPR_IMPL_H + +#include "util.h" +#include "num.h" +#include "field.h" + +#ifdef VERIFY +static void secp256k1_fe_verify(const secp256k1_fe *a) { + const uint32_t *d = a->n; + int m = a->normalized ? 1 : 2 * a->magnitude, r = 1; + r &= (d[0] <= 0x3FFFFFFUL * m); + r &= (d[1] <= 0x3FFFFFFUL * m); + r &= (d[2] <= 0x3FFFFFFUL * m); + r &= (d[3] <= 0x3FFFFFFUL * m); + r &= (d[4] <= 0x3FFFFFFUL * m); + r &= (d[5] <= 0x3FFFFFFUL * m); + r &= (d[6] <= 0x3FFFFFFUL * m); + r &= (d[7] <= 0x3FFFFFFUL * m); + r &= (d[8] <= 0x3FFFFFFUL * m); + r &= (d[9] <= 0x03FFFFFUL * m); + r &= (a->magnitude >= 0); + r &= (a->magnitude <= 32); + if (a->normalized) { + r &= (a->magnitude <= 1); + if (r && (d[9] == 0x03FFFFFUL)) { + uint32_t mid = d[8] & d[7] & d[6] & d[5] & d[4] & d[3] & d[2]; + if (mid == 0x3FFFFFFUL) { + r &= ((d[1] + 0x40UL + ((d[0] + 0x3D1UL) >> 26)) <= 0x3FFFFFFUL); + } + } + } + VERIFY_CHECK(r == 1); +} +#endif + +static void secp256k1_fe_normalize(secp256k1_fe *r) { + uint32_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4], + t5 = r->n[5], t6 = r->n[6], t7 = r->n[7], t8 = r->n[8], t9 = r->n[9]; + + /* Reduce t9 at the start so there will be at most a single carry from the first pass */ + uint32_t m; + uint32_t x = t9 >> 22; t9 &= 0x03FFFFFUL; + + /* The first pass ensures the magnitude is 1, ... */ + t0 += x * 0x3D1UL; t1 += (x << 6); + t1 += (t0 >> 26); t0 &= 0x3FFFFFFUL; + t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL; + t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL; m = t2; + t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL; m &= t3; + t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL; m &= t4; + t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL; m &= t5; + t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL; m &= t6; + t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL; m &= t7; + t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL; m &= t8; + + /* ... except for a possible carry at bit 22 of t9 (i.e. bit 256 of the field element) */ + VERIFY_CHECK(t9 >> 23 == 0); + + /* At most a single final reduction is needed; check if the value is >= the field characteristic */ + x = (t9 >> 22) | ((t9 == 0x03FFFFFUL) & (m == 0x3FFFFFFUL) + & ((t1 + 0x40UL + ((t0 + 0x3D1UL) >> 26)) > 0x3FFFFFFUL)); + + /* Apply the final reduction (for constant-time behaviour, we do it always) */ + t0 += x * 0x3D1UL; t1 += (x << 6); + t1 += (t0 >> 26); t0 &= 0x3FFFFFFUL; + t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL; + t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL; + t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL; + t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL; + t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL; + t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL; + t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL; + t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL; + + /* If t9 didn't carry to bit 22 already, then it should have after any final reduction */ + VERIFY_CHECK(t9 >> 22 == x); + + /* Mask off the possible multiple of 2^256 from the final reduction */ + t9 &= 0x03FFFFFUL; + + r->n[0] = t0; r->n[1] = t1; r->n[2] = t2; r->n[3] = t3; r->n[4] = t4; + r->n[5] = t5; r->n[6] = t6; r->n[7] = t7; r->n[8] = t8; r->n[9] = t9; + +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 1; + secp256k1_fe_verify(r); +#endif +} + +static void secp256k1_fe_normalize_weak(secp256k1_fe *r) { + uint32_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4], + t5 = r->n[5], t6 = r->n[6], t7 = r->n[7], t8 = r->n[8], t9 = r->n[9]; + + /* Reduce t9 at the start so there will be at most a single carry from the first pass */ + uint32_t x = t9 >> 22; t9 &= 0x03FFFFFUL; + + /* The first pass ensures the magnitude is 1, ... */ + t0 += x * 0x3D1UL; t1 += (x << 6); + t1 += (t0 >> 26); t0 &= 0x3FFFFFFUL; + t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL; + t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL; + t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL; + t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL; + t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL; + t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL; + t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL; + t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL; + + /* ... except for a possible carry at bit 22 of t9 (i.e. bit 256 of the field element) */ + VERIFY_CHECK(t9 >> 23 == 0); + + r->n[0] = t0; r->n[1] = t1; r->n[2] = t2; r->n[3] = t3; r->n[4] = t4; + r->n[5] = t5; r->n[6] = t6; r->n[7] = t7; r->n[8] = t8; r->n[9] = t9; + +#ifdef VERIFY + r->magnitude = 1; + secp256k1_fe_verify(r); +#endif +} + +static void secp256k1_fe_normalize_var(secp256k1_fe *r) { + uint32_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4], + t5 = r->n[5], t6 = r->n[6], t7 = r->n[7], t8 = r->n[8], t9 = r->n[9]; + + /* Reduce t9 at the start so there will be at most a single carry from the first pass */ + uint32_t m; + uint32_t x = t9 >> 22; t9 &= 0x03FFFFFUL; + + /* The first pass ensures the magnitude is 1, ... */ + t0 += x * 0x3D1UL; t1 += (x << 6); + t1 += (t0 >> 26); t0 &= 0x3FFFFFFUL; + t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL; + t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL; m = t2; + t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL; m &= t3; + t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL; m &= t4; + t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL; m &= t5; + t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL; m &= t6; + t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL; m &= t7; + t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL; m &= t8; + + /* ... except for a possible carry at bit 22 of t9 (i.e. bit 256 of the field element) */ + VERIFY_CHECK(t9 >> 23 == 0); + + /* At most a single final reduction is needed; check if the value is >= the field characteristic */ + x = (t9 >> 22) | ((t9 == 0x03FFFFFUL) & (m == 0x3FFFFFFUL) + & ((t1 + 0x40UL + ((t0 + 0x3D1UL) >> 26)) > 0x3FFFFFFUL)); + + if (x) { + t0 += 0x3D1UL; t1 += (x << 6); + t1 += (t0 >> 26); t0 &= 0x3FFFFFFUL; + t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL; + t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL; + t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL; + t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL; + t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL; + t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL; + t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL; + t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL; + + /* If t9 didn't carry to bit 22 already, then it should have after any final reduction */ + VERIFY_CHECK(t9 >> 22 == x); + + /* Mask off the possible multiple of 2^256 from the final reduction */ + t9 &= 0x03FFFFFUL; + } + + r->n[0] = t0; r->n[1] = t1; r->n[2] = t2; r->n[3] = t3; r->n[4] = t4; + r->n[5] = t5; r->n[6] = t6; r->n[7] = t7; r->n[8] = t8; r->n[9] = t9; + +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 1; + secp256k1_fe_verify(r); +#endif +} + +static int secp256k1_fe_normalizes_to_zero(secp256k1_fe *r) { + uint32_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4], + t5 = r->n[5], t6 = r->n[6], t7 = r->n[7], t8 = r->n[8], t9 = r->n[9]; + + /* z0 tracks a possible raw value of 0, z1 tracks a possible raw value of P */ + uint32_t z0, z1; + + /* Reduce t9 at the start so there will be at most a single carry from the first pass */ + uint32_t x = t9 >> 22; t9 &= 0x03FFFFFUL; + + /* The first pass ensures the magnitude is 1, ... */ + t0 += x * 0x3D1UL; t1 += (x << 6); + t1 += (t0 >> 26); t0 &= 0x3FFFFFFUL; z0 = t0; z1 = t0 ^ 0x3D0UL; + t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL; z0 |= t1; z1 &= t1 ^ 0x40UL; + t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL; z0 |= t2; z1 &= t2; + t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL; z0 |= t3; z1 &= t3; + t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL; z0 |= t4; z1 &= t4; + t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL; z0 |= t5; z1 &= t5; + t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL; z0 |= t6; z1 &= t6; + t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL; z0 |= t7; z1 &= t7; + t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL; z0 |= t8; z1 &= t8; + z0 |= t9; z1 &= t9 ^ 0x3C00000UL; + + /* ... except for a possible carry at bit 22 of t9 (i.e. bit 256 of the field element) */ + VERIFY_CHECK(t9 >> 23 == 0); + + return (z0 == 0) | (z1 == 0x3FFFFFFUL); +} + +static int secp256k1_fe_normalizes_to_zero_var(secp256k1_fe *r) { + uint32_t t0, t1, t2, t3, t4, t5, t6, t7, t8, t9; + uint32_t z0, z1; + uint32_t x; + + t0 = r->n[0]; + t9 = r->n[9]; + + /* Reduce t9 at the start so there will be at most a single carry from the first pass */ + x = t9 >> 22; + + /* The first pass ensures the magnitude is 1, ... */ + t0 += x * 0x3D1UL; + + /* z0 tracks a possible raw value of 0, z1 tracks a possible raw value of P */ + z0 = t0 & 0x3FFFFFFUL; + z1 = z0 ^ 0x3D0UL; + + /* Fast return path should catch the majority of cases */ + if ((z0 != 0UL) & (z1 != 0x3FFFFFFUL)) { + return 0; + } + + t1 = r->n[1]; + t2 = r->n[2]; + t3 = r->n[3]; + t4 = r->n[4]; + t5 = r->n[5]; + t6 = r->n[6]; + t7 = r->n[7]; + t8 = r->n[8]; + + t9 &= 0x03FFFFFUL; + t1 += (x << 6); + + t1 += (t0 >> 26); + t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL; z0 |= t1; z1 &= t1 ^ 0x40UL; + t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL; z0 |= t2; z1 &= t2; + t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL; z0 |= t3; z1 &= t3; + t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL; z0 |= t4; z1 &= t4; + t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL; z0 |= t5; z1 &= t5; + t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL; z0 |= t6; z1 &= t6; + t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL; z0 |= t7; z1 &= t7; + t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL; z0 |= t8; z1 &= t8; + z0 |= t9; z1 &= t9 ^ 0x3C00000UL; + + /* ... except for a possible carry at bit 22 of t9 (i.e. bit 256 of the field element) */ + VERIFY_CHECK(t9 >> 23 == 0); + + return (z0 == 0) | (z1 == 0x3FFFFFFUL); +} + +SECP256K1_INLINE static void secp256k1_fe_set_int(secp256k1_fe *r, int a) { + r->n[0] = a; + r->n[1] = r->n[2] = r->n[3] = r->n[4] = r->n[5] = r->n[6] = r->n[7] = r->n[8] = r->n[9] = 0; +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 1; + secp256k1_fe_verify(r); +#endif +} + +SECP256K1_INLINE static int secp256k1_fe_is_zero(const secp256k1_fe *a) { + const uint32_t *t = a->n; +#ifdef VERIFY + VERIFY_CHECK(a->normalized); + secp256k1_fe_verify(a); +#endif + return (t[0] | t[1] | t[2] | t[3] | t[4] | t[5] | t[6] | t[7] | t[8] | t[9]) == 0; +} + +SECP256K1_INLINE static int secp256k1_fe_is_odd(const secp256k1_fe *a) { +#ifdef VERIFY + VERIFY_CHECK(a->normalized); + secp256k1_fe_verify(a); +#endif + return a->n[0] & 1; +} + +SECP256K1_INLINE static void secp256k1_fe_clear(secp256k1_fe *a) { + int i; +#ifdef VERIFY + a->magnitude = 0; + a->normalized = 1; +#endif + for (i=0; i<10; i++) { + a->n[i] = 0; + } +} + +static int secp256k1_fe_cmp_var(const secp256k1_fe *a, const secp256k1_fe *b) { + int i; +#ifdef VERIFY + VERIFY_CHECK(a->normalized); + VERIFY_CHECK(b->normalized); + secp256k1_fe_verify(a); + secp256k1_fe_verify(b); +#endif + for (i = 9; i >= 0; i--) { + if (a->n[i] > b->n[i]) { + return 1; + } + if (a->n[i] < b->n[i]) { + return -1; + } + } + return 0; +} + +static int secp256k1_fe_set_b32(secp256k1_fe *r, const unsigned char *a) { + r->n[0] = (uint32_t)a[31] | ((uint32_t)a[30] << 8) | ((uint32_t)a[29] << 16) | ((uint32_t)(a[28] & 0x3) << 24); + r->n[1] = (uint32_t)((a[28] >> 2) & 0x3f) | ((uint32_t)a[27] << 6) | ((uint32_t)a[26] << 14) | ((uint32_t)(a[25] & 0xf) << 22); + r->n[2] = (uint32_t)((a[25] >> 4) & 0xf) | ((uint32_t)a[24] << 4) | ((uint32_t)a[23] << 12) | ((uint32_t)(a[22] & 0x3f) << 20); + r->n[3] = (uint32_t)((a[22] >> 6) & 0x3) | ((uint32_t)a[21] << 2) | ((uint32_t)a[20] << 10) | ((uint32_t)a[19] << 18); + r->n[4] = (uint32_t)a[18] | ((uint32_t)a[17] << 8) | ((uint32_t)a[16] << 16) | ((uint32_t)(a[15] & 0x3) << 24); + r->n[5] = (uint32_t)((a[15] >> 2) & 0x3f) | ((uint32_t)a[14] << 6) | ((uint32_t)a[13] << 14) | ((uint32_t)(a[12] & 0xf) << 22); + r->n[6] = (uint32_t)((a[12] >> 4) & 0xf) | ((uint32_t)a[11] << 4) | ((uint32_t)a[10] << 12) | ((uint32_t)(a[9] & 0x3f) << 20); + r->n[7] = (uint32_t)((a[9] >> 6) & 0x3) | ((uint32_t)a[8] << 2) | ((uint32_t)a[7] << 10) | ((uint32_t)a[6] << 18); + r->n[8] = (uint32_t)a[5] | ((uint32_t)a[4] << 8) | ((uint32_t)a[3] << 16) | ((uint32_t)(a[2] & 0x3) << 24); + r->n[9] = (uint32_t)((a[2] >> 2) & 0x3f) | ((uint32_t)a[1] << 6) | ((uint32_t)a[0] << 14); + + if (r->n[9] == 0x3FFFFFUL && (r->n[8] & r->n[7] & r->n[6] & r->n[5] & r->n[4] & r->n[3] & r->n[2]) == 0x3FFFFFFUL && (r->n[1] + 0x40UL + ((r->n[0] + 0x3D1UL) >> 26)) > 0x3FFFFFFUL) { + return 0; + } +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 1; + secp256k1_fe_verify(r); +#endif + return 1; +} + +/** Convert a field element to a 32-byte big endian value. Requires the input to be normalized */ +static void secp256k1_fe_get_b32(unsigned char *r, const secp256k1_fe *a) { +#ifdef VERIFY + VERIFY_CHECK(a->normalized); + secp256k1_fe_verify(a); +#endif + r[0] = (a->n[9] >> 14) & 0xff; + r[1] = (a->n[9] >> 6) & 0xff; + r[2] = ((a->n[9] & 0x3F) << 2) | ((a->n[8] >> 24) & 0x3); + r[3] = (a->n[8] >> 16) & 0xff; + r[4] = (a->n[8] >> 8) & 0xff; + r[5] = a->n[8] & 0xff; + r[6] = (a->n[7] >> 18) & 0xff; + r[7] = (a->n[7] >> 10) & 0xff; + r[8] = (a->n[7] >> 2) & 0xff; + r[9] = ((a->n[7] & 0x3) << 6) | ((a->n[6] >> 20) & 0x3f); + r[10] = (a->n[6] >> 12) & 0xff; + r[11] = (a->n[6] >> 4) & 0xff; + r[12] = ((a->n[6] & 0xf) << 4) | ((a->n[5] >> 22) & 0xf); + r[13] = (a->n[5] >> 14) & 0xff; + r[14] = (a->n[5] >> 6) & 0xff; + r[15] = ((a->n[5] & 0x3f) << 2) | ((a->n[4] >> 24) & 0x3); + r[16] = (a->n[4] >> 16) & 0xff; + r[17] = (a->n[4] >> 8) & 0xff; + r[18] = a->n[4] & 0xff; + r[19] = (a->n[3] >> 18) & 0xff; + r[20] = (a->n[3] >> 10) & 0xff; + r[21] = (a->n[3] >> 2) & 0xff; + r[22] = ((a->n[3] & 0x3) << 6) | ((a->n[2] >> 20) & 0x3f); + r[23] = (a->n[2] >> 12) & 0xff; + r[24] = (a->n[2] >> 4) & 0xff; + r[25] = ((a->n[2] & 0xf) << 4) | ((a->n[1] >> 22) & 0xf); + r[26] = (a->n[1] >> 14) & 0xff; + r[27] = (a->n[1] >> 6) & 0xff; + r[28] = ((a->n[1] & 0x3f) << 2) | ((a->n[0] >> 24) & 0x3); + r[29] = (a->n[0] >> 16) & 0xff; + r[30] = (a->n[0] >> 8) & 0xff; + r[31] = a->n[0] & 0xff; +} + +SECP256K1_INLINE static void secp256k1_fe_negate(secp256k1_fe *r, const secp256k1_fe *a, int m) { +#ifdef VERIFY + VERIFY_CHECK(a->magnitude <= m); + secp256k1_fe_verify(a); +#endif + r->n[0] = 0x3FFFC2FUL * 2 * (m + 1) - a->n[0]; + r->n[1] = 0x3FFFFBFUL * 2 * (m + 1) - a->n[1]; + r->n[2] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[2]; + r->n[3] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[3]; + r->n[4] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[4]; + r->n[5] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[5]; + r->n[6] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[6]; + r->n[7] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[7]; + r->n[8] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[8]; + r->n[9] = 0x03FFFFFUL * 2 * (m + 1) - a->n[9]; +#ifdef VERIFY + r->magnitude = m + 1; + r->normalized = 0; + secp256k1_fe_verify(r); +#endif +} + +SECP256K1_INLINE static void secp256k1_fe_mul_int(secp256k1_fe *r, int a) { + r->n[0] *= a; + r->n[1] *= a; + r->n[2] *= a; + r->n[3] *= a; + r->n[4] *= a; + r->n[5] *= a; + r->n[6] *= a; + r->n[7] *= a; + r->n[8] *= a; + r->n[9] *= a; +#ifdef VERIFY + r->magnitude *= a; + r->normalized = 0; + secp256k1_fe_verify(r); +#endif +} + +SECP256K1_INLINE static void secp256k1_fe_add(secp256k1_fe *r, const secp256k1_fe *a) { +#ifdef VERIFY + secp256k1_fe_verify(a); +#endif + r->n[0] += a->n[0]; + r->n[1] += a->n[1]; + r->n[2] += a->n[2]; + r->n[3] += a->n[3]; + r->n[4] += a->n[4]; + r->n[5] += a->n[5]; + r->n[6] += a->n[6]; + r->n[7] += a->n[7]; + r->n[8] += a->n[8]; + r->n[9] += a->n[9]; +#ifdef VERIFY + r->magnitude += a->magnitude; + r->normalized = 0; + secp256k1_fe_verify(r); +#endif +} + +#if defined(USE_EXTERNAL_ASM) + +/* External assembler implementation */ +void secp256k1_fe_mul_inner(uint32_t *r, const uint32_t *a, const uint32_t * SECP256K1_RESTRICT b); +void secp256k1_fe_sqr_inner(uint32_t *r, const uint32_t *a); + +#else + +#ifdef VERIFY +#define VERIFY_BITS(x, n) VERIFY_CHECK(((x) >> (n)) == 0) +#else +#define VERIFY_BITS(x, n) do { } while(0) +#endif + +SECP256K1_INLINE static void secp256k1_fe_mul_inner(uint32_t *r, const uint32_t *a, const uint32_t * SECP256K1_RESTRICT b) { + uint64_t c, d; + uint64_t u0, u1, u2, u3, u4, u5, u6, u7, u8; + uint32_t t9, t1, t0, t2, t3, t4, t5, t6, t7; + const uint32_t M = 0x3FFFFFFUL, R0 = 0x3D10UL, R1 = 0x400UL; + + VERIFY_BITS(a[0], 30); + VERIFY_BITS(a[1], 30); + VERIFY_BITS(a[2], 30); + VERIFY_BITS(a[3], 30); + VERIFY_BITS(a[4], 30); + VERIFY_BITS(a[5], 30); + VERIFY_BITS(a[6], 30); + VERIFY_BITS(a[7], 30); + VERIFY_BITS(a[8], 30); + VERIFY_BITS(a[9], 26); + VERIFY_BITS(b[0], 30); + VERIFY_BITS(b[1], 30); + VERIFY_BITS(b[2], 30); + VERIFY_BITS(b[3], 30); + VERIFY_BITS(b[4], 30); + VERIFY_BITS(b[5], 30); + VERIFY_BITS(b[6], 30); + VERIFY_BITS(b[7], 30); + VERIFY_BITS(b[8], 30); + VERIFY_BITS(b[9], 26); + + /** [... a b c] is a shorthand for ... + a<<52 + b<<26 + c<<0 mod n. + * px is a shorthand for sum(a[i]*b[x-i], i=0..x). + * Note that [x 0 0 0 0 0 0 0 0 0 0] = [x*R1 x*R0]. + */ + + d = (uint64_t)a[0] * b[9] + + (uint64_t)a[1] * b[8] + + (uint64_t)a[2] * b[7] + + (uint64_t)a[3] * b[6] + + (uint64_t)a[4] * b[5] + + (uint64_t)a[5] * b[4] + + (uint64_t)a[6] * b[3] + + (uint64_t)a[7] * b[2] + + (uint64_t)a[8] * b[1] + + (uint64_t)a[9] * b[0]; + /* VERIFY_BITS(d, 64); */ + /* [d 0 0 0 0 0 0 0 0 0] = [p9 0 0 0 0 0 0 0 0 0] */ + t9 = d & M; d >>= 26; + VERIFY_BITS(t9, 26); + VERIFY_BITS(d, 38); + /* [d t9 0 0 0 0 0 0 0 0 0] = [p9 0 0 0 0 0 0 0 0 0] */ + + c = (uint64_t)a[0] * b[0]; + VERIFY_BITS(c, 60); + /* [d t9 0 0 0 0 0 0 0 0 c] = [p9 0 0 0 0 0 0 0 0 p0] */ + d += (uint64_t)a[1] * b[9] + + (uint64_t)a[2] * b[8] + + (uint64_t)a[3] * b[7] + + (uint64_t)a[4] * b[6] + + (uint64_t)a[5] * b[5] + + (uint64_t)a[6] * b[4] + + (uint64_t)a[7] * b[3] + + (uint64_t)a[8] * b[2] + + (uint64_t)a[9] * b[1]; + VERIFY_BITS(d, 63); + /* [d t9 0 0 0 0 0 0 0 0 c] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ + u0 = d & M; d >>= 26; c += u0 * R0; + VERIFY_BITS(u0, 26); + VERIFY_BITS(d, 37); + VERIFY_BITS(c, 61); + /* [d u0 t9 0 0 0 0 0 0 0 0 c-u0*R0] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ + t0 = c & M; c >>= 26; c += u0 * R1; + VERIFY_BITS(t0, 26); + VERIFY_BITS(c, 37); + /* [d u0 t9 0 0 0 0 0 0 0 c-u0*R1 t0-u0*R0] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ + /* [d 0 t9 0 0 0 0 0 0 0 c t0] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ + + c += (uint64_t)a[0] * b[1] + + (uint64_t)a[1] * b[0]; + VERIFY_BITS(c, 62); + /* [d 0 t9 0 0 0 0 0 0 0 c t0] = [p10 p9 0 0 0 0 0 0 0 p1 p0] */ + d += (uint64_t)a[2] * b[9] + + (uint64_t)a[3] * b[8] + + (uint64_t)a[4] * b[7] + + (uint64_t)a[5] * b[6] + + (uint64_t)a[6] * b[5] + + (uint64_t)a[7] * b[4] + + (uint64_t)a[8] * b[3] + + (uint64_t)a[9] * b[2]; + VERIFY_BITS(d, 63); + /* [d 0 t9 0 0 0 0 0 0 0 c t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ + u1 = d & M; d >>= 26; c += u1 * R0; + VERIFY_BITS(u1, 26); + VERIFY_BITS(d, 37); + VERIFY_BITS(c, 63); + /* [d u1 0 t9 0 0 0 0 0 0 0 c-u1*R0 t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ + t1 = c & M; c >>= 26; c += u1 * R1; + VERIFY_BITS(t1, 26); + VERIFY_BITS(c, 38); + /* [d u1 0 t9 0 0 0 0 0 0 c-u1*R1 t1-u1*R0 t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ + /* [d 0 0 t9 0 0 0 0 0 0 c t1 t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ + + c += (uint64_t)a[0] * b[2] + + (uint64_t)a[1] * b[1] + + (uint64_t)a[2] * b[0]; + VERIFY_BITS(c, 62); + /* [d 0 0 t9 0 0 0 0 0 0 c t1 t0] = [p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ + d += (uint64_t)a[3] * b[9] + + (uint64_t)a[4] * b[8] + + (uint64_t)a[5] * b[7] + + (uint64_t)a[6] * b[6] + + (uint64_t)a[7] * b[5] + + (uint64_t)a[8] * b[4] + + (uint64_t)a[9] * b[3]; + VERIFY_BITS(d, 63); + /* [d 0 0 t9 0 0 0 0 0 0 c t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ + u2 = d & M; d >>= 26; c += u2 * R0; + VERIFY_BITS(u2, 26); + VERIFY_BITS(d, 37); + VERIFY_BITS(c, 63); + /* [d u2 0 0 t9 0 0 0 0 0 0 c-u2*R0 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ + t2 = c & M; c >>= 26; c += u2 * R1; + VERIFY_BITS(t2, 26); + VERIFY_BITS(c, 38); + /* [d u2 0 0 t9 0 0 0 0 0 c-u2*R1 t2-u2*R0 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ + /* [d 0 0 0 t9 0 0 0 0 0 c t2 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ + + c += (uint64_t)a[0] * b[3] + + (uint64_t)a[1] * b[2] + + (uint64_t)a[2] * b[1] + + (uint64_t)a[3] * b[0]; + VERIFY_BITS(c, 63); + /* [d 0 0 0 t9 0 0 0 0 0 c t2 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ + d += (uint64_t)a[4] * b[9] + + (uint64_t)a[5] * b[8] + + (uint64_t)a[6] * b[7] + + (uint64_t)a[7] * b[6] + + (uint64_t)a[8] * b[5] + + (uint64_t)a[9] * b[4]; + VERIFY_BITS(d, 63); + /* [d 0 0 0 t9 0 0 0 0 0 c t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ + u3 = d & M; d >>= 26; c += u3 * R0; + VERIFY_BITS(u3, 26); + VERIFY_BITS(d, 37); + /* VERIFY_BITS(c, 64); */ + /* [d u3 0 0 0 t9 0 0 0 0 0 c-u3*R0 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ + t3 = c & M; c >>= 26; c += u3 * R1; + VERIFY_BITS(t3, 26); + VERIFY_BITS(c, 39); + /* [d u3 0 0 0 t9 0 0 0 0 c-u3*R1 t3-u3*R0 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ + /* [d 0 0 0 0 t9 0 0 0 0 c t3 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ + + c += (uint64_t)a[0] * b[4] + + (uint64_t)a[1] * b[3] + + (uint64_t)a[2] * b[2] + + (uint64_t)a[3] * b[1] + + (uint64_t)a[4] * b[0]; + VERIFY_BITS(c, 63); + /* [d 0 0 0 0 t9 0 0 0 0 c t3 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ + d += (uint64_t)a[5] * b[9] + + (uint64_t)a[6] * b[8] + + (uint64_t)a[7] * b[7] + + (uint64_t)a[8] * b[6] + + (uint64_t)a[9] * b[5]; + VERIFY_BITS(d, 62); + /* [d 0 0 0 0 t9 0 0 0 0 c t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ + u4 = d & M; d >>= 26; c += u4 * R0; + VERIFY_BITS(u4, 26); + VERIFY_BITS(d, 36); + /* VERIFY_BITS(c, 64); */ + /* [d u4 0 0 0 0 t9 0 0 0 0 c-u4*R0 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ + t4 = c & M; c >>= 26; c += u4 * R1; + VERIFY_BITS(t4, 26); + VERIFY_BITS(c, 39); + /* [d u4 0 0 0 0 t9 0 0 0 c-u4*R1 t4-u4*R0 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 t9 0 0 0 c t4 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ + + c += (uint64_t)a[0] * b[5] + + (uint64_t)a[1] * b[4] + + (uint64_t)a[2] * b[3] + + (uint64_t)a[3] * b[2] + + (uint64_t)a[4] * b[1] + + (uint64_t)a[5] * b[0]; + VERIFY_BITS(c, 63); + /* [d 0 0 0 0 0 t9 0 0 0 c t4 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ + d += (uint64_t)a[6] * b[9] + + (uint64_t)a[7] * b[8] + + (uint64_t)a[8] * b[7] + + (uint64_t)a[9] * b[6]; + VERIFY_BITS(d, 62); + /* [d 0 0 0 0 0 t9 0 0 0 c t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ + u5 = d & M; d >>= 26; c += u5 * R0; + VERIFY_BITS(u5, 26); + VERIFY_BITS(d, 36); + /* VERIFY_BITS(c, 64); */ + /* [d u5 0 0 0 0 0 t9 0 0 0 c-u5*R0 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ + t5 = c & M; c >>= 26; c += u5 * R1; + VERIFY_BITS(t5, 26); + VERIFY_BITS(c, 39); + /* [d u5 0 0 0 0 0 t9 0 0 c-u5*R1 t5-u5*R0 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 0 t9 0 0 c t5 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ + + c += (uint64_t)a[0] * b[6] + + (uint64_t)a[1] * b[5] + + (uint64_t)a[2] * b[4] + + (uint64_t)a[3] * b[3] + + (uint64_t)a[4] * b[2] + + (uint64_t)a[5] * b[1] + + (uint64_t)a[6] * b[0]; + VERIFY_BITS(c, 63); + /* [d 0 0 0 0 0 0 t9 0 0 c t5 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ + d += (uint64_t)a[7] * b[9] + + (uint64_t)a[8] * b[8] + + (uint64_t)a[9] * b[7]; + VERIFY_BITS(d, 61); + /* [d 0 0 0 0 0 0 t9 0 0 c t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ + u6 = d & M; d >>= 26; c += u6 * R0; + VERIFY_BITS(u6, 26); + VERIFY_BITS(d, 35); + /* VERIFY_BITS(c, 64); */ + /* [d u6 0 0 0 0 0 0 t9 0 0 c-u6*R0 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ + t6 = c & M; c >>= 26; c += u6 * R1; + VERIFY_BITS(t6, 26); + VERIFY_BITS(c, 39); + /* [d u6 0 0 0 0 0 0 t9 0 c-u6*R1 t6-u6*R0 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 0 0 t9 0 c t6 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ + + c += (uint64_t)a[0] * b[7] + + (uint64_t)a[1] * b[6] + + (uint64_t)a[2] * b[5] + + (uint64_t)a[3] * b[4] + + (uint64_t)a[4] * b[3] + + (uint64_t)a[5] * b[2] + + (uint64_t)a[6] * b[1] + + (uint64_t)a[7] * b[0]; + /* VERIFY_BITS(c, 64); */ + VERIFY_CHECK(c <= 0x8000007C00000007ULL); + /* [d 0 0 0 0 0 0 0 t9 0 c t6 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ + d += (uint64_t)a[8] * b[9] + + (uint64_t)a[9] * b[8]; + VERIFY_BITS(d, 58); + /* [d 0 0 0 0 0 0 0 t9 0 c t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ + u7 = d & M; d >>= 26; c += u7 * R0; + VERIFY_BITS(u7, 26); + VERIFY_BITS(d, 32); + /* VERIFY_BITS(c, 64); */ + VERIFY_CHECK(c <= 0x800001703FFFC2F7ULL); + /* [d u7 0 0 0 0 0 0 0 t9 0 c-u7*R0 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ + t7 = c & M; c >>= 26; c += u7 * R1; + VERIFY_BITS(t7, 26); + VERIFY_BITS(c, 38); + /* [d u7 0 0 0 0 0 0 0 t9 c-u7*R1 t7-u7*R0 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 0 0 0 t9 c t7 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ + + c += (uint64_t)a[0] * b[8] + + (uint64_t)a[1] * b[7] + + (uint64_t)a[2] * b[6] + + (uint64_t)a[3] * b[5] + + (uint64_t)a[4] * b[4] + + (uint64_t)a[5] * b[3] + + (uint64_t)a[6] * b[2] + + (uint64_t)a[7] * b[1] + + (uint64_t)a[8] * b[0]; + /* VERIFY_BITS(c, 64); */ + VERIFY_CHECK(c <= 0x9000007B80000008ULL); + /* [d 0 0 0 0 0 0 0 0 t9 c t7 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + d += (uint64_t)a[9] * b[9]; + VERIFY_BITS(d, 57); + /* [d 0 0 0 0 0 0 0 0 t9 c t7 t6 t5 t4 t3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + u8 = d & M; d >>= 26; c += u8 * R0; + VERIFY_BITS(u8, 26); + VERIFY_BITS(d, 31); + /* VERIFY_BITS(c, 64); */ + VERIFY_CHECK(c <= 0x9000016FBFFFC2F8ULL); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 t5 t4 t3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + + r[3] = t3; + VERIFY_BITS(r[3], 26); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 t5 t4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[4] = t4; + VERIFY_BITS(r[4], 26); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 t5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[5] = t5; + VERIFY_BITS(r[5], 26); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[6] = t6; + VERIFY_BITS(r[6], 26); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[7] = t7; + VERIFY_BITS(r[7], 26); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + + r[8] = c & M; c >>= 26; c += u8 * R1; + VERIFY_BITS(r[8], 26); + VERIFY_BITS(c, 39); + /* [d u8 0 0 0 0 0 0 0 0 t9+c-u8*R1 r8-u8*R0 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 0 0 0 0 t9+c r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + c += d * R0 + t9; + VERIFY_BITS(c, 45); + /* [d 0 0 0 0 0 0 0 0 0 c-d*R0 r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[9] = c & (M >> 4); c >>= 22; c += d * (R1 << 4); + VERIFY_BITS(r[9], 22); + VERIFY_BITS(c, 46); + /* [d 0 0 0 0 0 0 0 0 r9+((c-d*R1<<4)<<22)-d*R0 r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 0 0 -d*R1 r9+(c<<22)-d*R0 r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + + d = c * (R0 >> 4) + t0; + VERIFY_BITS(d, 56); + /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 t1 d-c*R0>>4] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[0] = d & M; d >>= 26; + VERIFY_BITS(r[0], 26); + VERIFY_BITS(d, 30); + /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 t1+d r0-c*R0>>4] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + d += c * (R1 >> 4) + t1; + VERIFY_BITS(d, 53); + VERIFY_CHECK(d <= 0x10000003FFFFBFULL); + /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 d-c*R1>>4 r0-c*R0>>4] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + /* [r9 r8 r7 r6 r5 r4 r3 t2 d r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[1] = d & M; d >>= 26; + VERIFY_BITS(r[1], 26); + VERIFY_BITS(d, 27); + VERIFY_CHECK(d <= 0x4000000ULL); + /* [r9 r8 r7 r6 r5 r4 r3 t2+d r1 r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + d += t2; + VERIFY_BITS(d, 27); + /* [r9 r8 r7 r6 r5 r4 r3 d r1 r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[2] = (uint32_t)(uint32_t)(uint32_t)(uint32_t)(uint32_t)(uint32_t)d; + VERIFY_BITS(r[2], 27); + /* [r9 r8 r7 r6 r5 r4 r3 r2 r1 r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ +} + +SECP256K1_INLINE static void secp256k1_fe_sqr_inner(uint32_t *r, const uint32_t *a) { + uint64_t c, d; + uint64_t u0, u1, u2, u3, u4, u5, u6, u7, u8; + uint32_t t9, t0, t1, t2, t3, t4, t5, t6, t7; + const uint32_t M = 0x3FFFFFFUL, R0 = 0x3D10UL, R1 = 0x400UL; + + VERIFY_BITS(a[0], 30); + VERIFY_BITS(a[1], 30); + VERIFY_BITS(a[2], 30); + VERIFY_BITS(a[3], 30); + VERIFY_BITS(a[4], 30); + VERIFY_BITS(a[5], 30); + VERIFY_BITS(a[6], 30); + VERIFY_BITS(a[7], 30); + VERIFY_BITS(a[8], 30); + VERIFY_BITS(a[9], 26); + + /** [... a b c] is a shorthand for ... + a<<52 + b<<26 + c<<0 mod n. + * px is a shorthand for sum(a[i]*a[x-i], i=0..x). + * Note that [x 0 0 0 0 0 0 0 0 0 0] = [x*R1 x*R0]. + */ + + d = (uint64_t)(a[0]*2) * a[9] + + (uint64_t)(a[1]*2) * a[8] + + (uint64_t)(a[2]*2) * a[7] + + (uint64_t)(a[3]*2) * a[6] + + (uint64_t)(a[4]*2) * a[5]; + /* VERIFY_BITS(d, 64); */ + /* [d 0 0 0 0 0 0 0 0 0] = [p9 0 0 0 0 0 0 0 0 0] */ + t9 = d & M; d >>= 26; + VERIFY_BITS(t9, 26); + VERIFY_BITS(d, 38); + /* [d t9 0 0 0 0 0 0 0 0 0] = [p9 0 0 0 0 0 0 0 0 0] */ + + c = (uint64_t)a[0] * a[0]; + VERIFY_BITS(c, 60); + /* [d t9 0 0 0 0 0 0 0 0 c] = [p9 0 0 0 0 0 0 0 0 p0] */ + d += (uint64_t)(a[1]*2) * a[9] + + (uint64_t)(a[2]*2) * a[8] + + (uint64_t)(a[3]*2) * a[7] + + (uint64_t)(a[4]*2) * a[6] + + (uint64_t)a[5] * a[5]; + VERIFY_BITS(d, 63); + /* [d t9 0 0 0 0 0 0 0 0 c] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ + u0 = d & M; d >>= 26; c += u0 * R0; + VERIFY_BITS(u0, 26); + VERIFY_BITS(d, 37); + VERIFY_BITS(c, 61); + /* [d u0 t9 0 0 0 0 0 0 0 0 c-u0*R0] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ + t0 = c & M; c >>= 26; c += u0 * R1; + VERIFY_BITS(t0, 26); + VERIFY_BITS(c, 37); + /* [d u0 t9 0 0 0 0 0 0 0 c-u0*R1 t0-u0*R0] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ + /* [d 0 t9 0 0 0 0 0 0 0 c t0] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ + + c += (uint64_t)(a[0]*2) * a[1]; + VERIFY_BITS(c, 62); + /* [d 0 t9 0 0 0 0 0 0 0 c t0] = [p10 p9 0 0 0 0 0 0 0 p1 p0] */ + d += (uint64_t)(a[2]*2) * a[9] + + (uint64_t)(a[3]*2) * a[8] + + (uint64_t)(a[4]*2) * a[7] + + (uint64_t)(a[5]*2) * a[6]; + VERIFY_BITS(d, 63); + /* [d 0 t9 0 0 0 0 0 0 0 c t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ + u1 = d & M; d >>= 26; c += u1 * R0; + VERIFY_BITS(u1, 26); + VERIFY_BITS(d, 37); + VERIFY_BITS(c, 63); + /* [d u1 0 t9 0 0 0 0 0 0 0 c-u1*R0 t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ + t1 = c & M; c >>= 26; c += u1 * R1; + VERIFY_BITS(t1, 26); + VERIFY_BITS(c, 38); + /* [d u1 0 t9 0 0 0 0 0 0 c-u1*R1 t1-u1*R0 t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ + /* [d 0 0 t9 0 0 0 0 0 0 c t1 t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ + + c += (uint64_t)(a[0]*2) * a[2] + + (uint64_t)a[1] * a[1]; + VERIFY_BITS(c, 62); + /* [d 0 0 t9 0 0 0 0 0 0 c t1 t0] = [p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ + d += (uint64_t)(a[3]*2) * a[9] + + (uint64_t)(a[4]*2) * a[8] + + (uint64_t)(a[5]*2) * a[7] + + (uint64_t)a[6] * a[6]; + VERIFY_BITS(d, 63); + /* [d 0 0 t9 0 0 0 0 0 0 c t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ + u2 = d & M; d >>= 26; c += u2 * R0; + VERIFY_BITS(u2, 26); + VERIFY_BITS(d, 37); + VERIFY_BITS(c, 63); + /* [d u2 0 0 t9 0 0 0 0 0 0 c-u2*R0 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ + t2 = c & M; c >>= 26; c += u2 * R1; + VERIFY_BITS(t2, 26); + VERIFY_BITS(c, 38); + /* [d u2 0 0 t9 0 0 0 0 0 c-u2*R1 t2-u2*R0 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ + /* [d 0 0 0 t9 0 0 0 0 0 c t2 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ + + c += (uint64_t)(a[0]*2) * a[3] + + (uint64_t)(a[1]*2) * a[2]; + VERIFY_BITS(c, 63); + /* [d 0 0 0 t9 0 0 0 0 0 c t2 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ + d += (uint64_t)(a[4]*2) * a[9] + + (uint64_t)(a[5]*2) * a[8] + + (uint64_t)(a[6]*2) * a[7]; + VERIFY_BITS(d, 63); + /* [d 0 0 0 t9 0 0 0 0 0 c t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ + u3 = d & M; d >>= 26; c += u3 * R0; + VERIFY_BITS(u3, 26); + VERIFY_BITS(d, 37); + /* VERIFY_BITS(c, 64); */ + /* [d u3 0 0 0 t9 0 0 0 0 0 c-u3*R0 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ + t3 = c & M; c >>= 26; c += u3 * R1; + VERIFY_BITS(t3, 26); + VERIFY_BITS(c, 39); + /* [d u3 0 0 0 t9 0 0 0 0 c-u3*R1 t3-u3*R0 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ + /* [d 0 0 0 0 t9 0 0 0 0 c t3 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ + + c += (uint64_t)(a[0]*2) * a[4] + + (uint64_t)(a[1]*2) * a[3] + + (uint64_t)a[2] * a[2]; + VERIFY_BITS(c, 63); + /* [d 0 0 0 0 t9 0 0 0 0 c t3 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ + d += (uint64_t)(a[5]*2) * a[9] + + (uint64_t)(a[6]*2) * a[8] + + (uint64_t)a[7] * a[7]; + VERIFY_BITS(d, 62); + /* [d 0 0 0 0 t9 0 0 0 0 c t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ + u4 = d & M; d >>= 26; c += u4 * R0; + VERIFY_BITS(u4, 26); + VERIFY_BITS(d, 36); + /* VERIFY_BITS(c, 64); */ + /* [d u4 0 0 0 0 t9 0 0 0 0 c-u4*R0 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ + t4 = c & M; c >>= 26; c += u4 * R1; + VERIFY_BITS(t4, 26); + VERIFY_BITS(c, 39); + /* [d u4 0 0 0 0 t9 0 0 0 c-u4*R1 t4-u4*R0 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 t9 0 0 0 c t4 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ + + c += (uint64_t)(a[0]*2) * a[5] + + (uint64_t)(a[1]*2) * a[4] + + (uint64_t)(a[2]*2) * a[3]; + VERIFY_BITS(c, 63); + /* [d 0 0 0 0 0 t9 0 0 0 c t4 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ + d += (uint64_t)(a[6]*2) * a[9] + + (uint64_t)(a[7]*2) * a[8]; + VERIFY_BITS(d, 62); + /* [d 0 0 0 0 0 t9 0 0 0 c t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ + u5 = d & M; d >>= 26; c += u5 * R0; + VERIFY_BITS(u5, 26); + VERIFY_BITS(d, 36); + /* VERIFY_BITS(c, 64); */ + /* [d u5 0 0 0 0 0 t9 0 0 0 c-u5*R0 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ + t5 = c & M; c >>= 26; c += u5 * R1; + VERIFY_BITS(t5, 26); + VERIFY_BITS(c, 39); + /* [d u5 0 0 0 0 0 t9 0 0 c-u5*R1 t5-u5*R0 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 0 t9 0 0 c t5 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ + + c += (uint64_t)(a[0]*2) * a[6] + + (uint64_t)(a[1]*2) * a[5] + + (uint64_t)(a[2]*2) * a[4] + + (uint64_t)a[3] * a[3]; + VERIFY_BITS(c, 63); + /* [d 0 0 0 0 0 0 t9 0 0 c t5 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ + d += (uint64_t)(a[7]*2) * a[9] + + (uint64_t)a[8] * a[8]; + VERIFY_BITS(d, 61); + /* [d 0 0 0 0 0 0 t9 0 0 c t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ + u6 = d & M; d >>= 26; c += u6 * R0; + VERIFY_BITS(u6, 26); + VERIFY_BITS(d, 35); + /* VERIFY_BITS(c, 64); */ + /* [d u6 0 0 0 0 0 0 t9 0 0 c-u6*R0 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ + t6 = c & M; c >>= 26; c += u6 * R1; + VERIFY_BITS(t6, 26); + VERIFY_BITS(c, 39); + /* [d u6 0 0 0 0 0 0 t9 0 c-u6*R1 t6-u6*R0 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 0 0 t9 0 c t6 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ + + c += (uint64_t)(a[0]*2) * a[7] + + (uint64_t)(a[1]*2) * a[6] + + (uint64_t)(a[2]*2) * a[5] + + (uint64_t)(a[3]*2) * a[4]; + /* VERIFY_BITS(c, 64); */ + VERIFY_CHECK(c <= 0x8000007C00000007ULL); + /* [d 0 0 0 0 0 0 0 t9 0 c t6 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ + d += (uint64_t)(a[8]*2) * a[9]; + VERIFY_BITS(d, 58); + /* [d 0 0 0 0 0 0 0 t9 0 c t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ + u7 = d & M; d >>= 26; c += u7 * R0; + VERIFY_BITS(u7, 26); + VERIFY_BITS(d, 32); + /* VERIFY_BITS(c, 64); */ + VERIFY_CHECK(c <= 0x800001703FFFC2F7ULL); + /* [d u7 0 0 0 0 0 0 0 t9 0 c-u7*R0 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ + t7 = c & M; c >>= 26; c += u7 * R1; + VERIFY_BITS(t7, 26); + VERIFY_BITS(c, 38); + /* [d u7 0 0 0 0 0 0 0 t9 c-u7*R1 t7-u7*R0 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 0 0 0 t9 c t7 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ + + c += (uint64_t)(a[0]*2) * a[8] + + (uint64_t)(a[1]*2) * a[7] + + (uint64_t)(a[2]*2) * a[6] + + (uint64_t)(a[3]*2) * a[5] + + (uint64_t)a[4] * a[4]; + /* VERIFY_BITS(c, 64); */ + VERIFY_CHECK(c <= 0x9000007B80000008ULL); + /* [d 0 0 0 0 0 0 0 0 t9 c t7 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + d += (uint64_t)a[9] * a[9]; + VERIFY_BITS(d, 57); + /* [d 0 0 0 0 0 0 0 0 t9 c t7 t6 t5 t4 t3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + u8 = d & M; d >>= 26; c += u8 * R0; + VERIFY_BITS(u8, 26); + VERIFY_BITS(d, 31); + /* VERIFY_BITS(c, 64); */ + VERIFY_CHECK(c <= 0x9000016FBFFFC2F8ULL); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 t5 t4 t3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + + r[3] = t3; + VERIFY_BITS(r[3], 26); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 t5 t4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[4] = t4; + VERIFY_BITS(r[4], 26); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 t5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[5] = t5; + VERIFY_BITS(r[5], 26); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[6] = t6; + VERIFY_BITS(r[6], 26); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[7] = t7; + VERIFY_BITS(r[7], 26); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + + r[8] = c & M; c >>= 26; c += u8 * R1; + VERIFY_BITS(r[8], 26); + VERIFY_BITS(c, 39); + /* [d u8 0 0 0 0 0 0 0 0 t9+c-u8*R1 r8-u8*R0 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 0 0 0 0 t9+c r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + c += d * R0 + t9; + VERIFY_BITS(c, 45); + /* [d 0 0 0 0 0 0 0 0 0 c-d*R0 r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[9] = c & (M >> 4); c >>= 22; c += d * (R1 << 4); + VERIFY_BITS(r[9], 22); + VERIFY_BITS(c, 46); + /* [d 0 0 0 0 0 0 0 0 r9+((c-d*R1<<4)<<22)-d*R0 r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 0 0 -d*R1 r9+(c<<22)-d*R0 r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + + d = c * (R0 >> 4) + t0; + VERIFY_BITS(d, 56); + /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 t1 d-c*R0>>4] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[0] = d & M; d >>= 26; + VERIFY_BITS(r[0], 26); + VERIFY_BITS(d, 30); + /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 t1+d r0-c*R0>>4] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + d += c * (R1 >> 4) + t1; + VERIFY_BITS(d, 53); + VERIFY_CHECK(d <= 0x10000003FFFFBFULL); + /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 d-c*R1>>4 r0-c*R0>>4] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + /* [r9 r8 r7 r6 r5 r4 r3 t2 d r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[1] = d & M; d >>= 26; + VERIFY_BITS(r[1], 26); + VERIFY_BITS(d, 27); + VERIFY_CHECK(d <= 0x4000000ULL); + /* [r9 r8 r7 r6 r5 r4 r3 t2+d r1 r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + d += t2; + VERIFY_BITS(d, 27); + /* [r9 r8 r7 r6 r5 r4 r3 d r1 r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[2] = (uint32_t)d; + VERIFY_BITS(r[2], 27); + /* [r9 r8 r7 r6 r5 r4 r3 r2 r1 r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ +} +#endif + +static void secp256k1_fe_mul(secp256k1_fe *r, const secp256k1_fe *a, const secp256k1_fe * SECP256K1_RESTRICT b) { +#ifdef VERIFY + VERIFY_CHECK(a->magnitude <= 8); + VERIFY_CHECK(b->magnitude <= 8); + secp256k1_fe_verify(a); + secp256k1_fe_verify(b); + VERIFY_CHECK(r != b); +#endif + secp256k1_fe_mul_inner(r->n, a->n, b->n); +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 0; + secp256k1_fe_verify(r); +#endif +} + +static void secp256k1_fe_sqr(secp256k1_fe *r, const secp256k1_fe *a) { +#ifdef VERIFY + VERIFY_CHECK(a->magnitude <= 8); + secp256k1_fe_verify(a); +#endif + secp256k1_fe_sqr_inner(r->n, a->n); +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 0; + secp256k1_fe_verify(r); +#endif +} + +static SECP256K1_INLINE void secp256k1_fe_cmov(secp256k1_fe *r, const secp256k1_fe *a, int flag) { + uint32_t mask0, mask1; + mask0 = flag + ~((uint32_t)0); + mask1 = ~mask0; + r->n[0] = (r->n[0] & mask0) | (a->n[0] & mask1); + r->n[1] = (r->n[1] & mask0) | (a->n[1] & mask1); + r->n[2] = (r->n[2] & mask0) | (a->n[2] & mask1); + r->n[3] = (r->n[3] & mask0) | (a->n[3] & mask1); + r->n[4] = (r->n[4] & mask0) | (a->n[4] & mask1); + r->n[5] = (r->n[5] & mask0) | (a->n[5] & mask1); + r->n[6] = (r->n[6] & mask0) | (a->n[6] & mask1); + r->n[7] = (r->n[7] & mask0) | (a->n[7] & mask1); + r->n[8] = (r->n[8] & mask0) | (a->n[8] & mask1); + r->n[9] = (r->n[9] & mask0) | (a->n[9] & mask1); +#ifdef VERIFY + if (a->magnitude > r->magnitude) { + r->magnitude = a->magnitude; + } + r->normalized &= a->normalized; +#endif +} + +static SECP256K1_INLINE void secp256k1_fe_storage_cmov(secp256k1_fe_storage *r, const secp256k1_fe_storage *a, int flag) { + uint32_t mask0, mask1; + mask0 = flag + ~((uint32_t)0); + mask1 = ~mask0; + r->n[0] = (r->n[0] & mask0) | (a->n[0] & mask1); + r->n[1] = (r->n[1] & mask0) | (a->n[1] & mask1); + r->n[2] = (r->n[2] & mask0) | (a->n[2] & mask1); + r->n[3] = (r->n[3] & mask0) | (a->n[3] & mask1); + r->n[4] = (r->n[4] & mask0) | (a->n[4] & mask1); + r->n[5] = (r->n[5] & mask0) | (a->n[5] & mask1); + r->n[6] = (r->n[6] & mask0) | (a->n[6] & mask1); + r->n[7] = (r->n[7] & mask0) | (a->n[7] & mask1); +} + +static void secp256k1_fe_to_storage(secp256k1_fe_storage *r, const secp256k1_fe *a) { +#ifdef VERIFY + VERIFY_CHECK(a->normalized); +#endif + r->n[0] = a->n[0] | a->n[1] << 26; + r->n[1] = a->n[1] >> 6 | a->n[2] << 20; + r->n[2] = a->n[2] >> 12 | a->n[3] << 14; + r->n[3] = a->n[3] >> 18 | a->n[4] << 8; + r->n[4] = a->n[4] >> 24 | a->n[5] << 2 | a->n[6] << 28; + r->n[5] = a->n[6] >> 4 | a->n[7] << 22; + r->n[6] = a->n[7] >> 10 | a->n[8] << 16; + r->n[7] = a->n[8] >> 16 | a->n[9] << 10; +} + +static SECP256K1_INLINE void secp256k1_fe_from_storage(secp256k1_fe *r, const secp256k1_fe_storage *a) { + r->n[0] = a->n[0] & 0x3FFFFFFUL; + r->n[1] = a->n[0] >> 26 | ((a->n[1] << 6) & 0x3FFFFFFUL); + r->n[2] = a->n[1] >> 20 | ((a->n[2] << 12) & 0x3FFFFFFUL); + r->n[3] = a->n[2] >> 14 | ((a->n[3] << 18) & 0x3FFFFFFUL); + r->n[4] = a->n[3] >> 8 | ((a->n[4] << 24) & 0x3FFFFFFUL); + r->n[5] = (a->n[4] >> 2) & 0x3FFFFFFUL; + r->n[6] = a->n[4] >> 28 | ((a->n[5] << 4) & 0x3FFFFFFUL); + r->n[7] = a->n[5] >> 22 | ((a->n[6] << 10) & 0x3FFFFFFUL); + r->n[8] = a->n[6] >> 16 | ((a->n[7] << 16) & 0x3FFFFFFUL); + r->n[9] = a->n[7] >> 10; +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 1; +#endif +} + +#endif /* SECP256K1_FIELD_REPR_IMPL_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_5x52.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_5x52.h new file mode 100644 index 000000000..bccd8feb4 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_5x52.h @@ -0,0 +1,47 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_FIELD_REPR_H +#define SECP256K1_FIELD_REPR_H + +#include + +typedef struct { + /* X = sum(i=0..4, elem[i]*2^52) mod n */ + uint64_t n[5]; +#ifdef VERIFY + int magnitude; + int normalized; +#endif +} secp256k1_fe; + +/* Unpacks a constant into a overlapping multi-limbed FE element. */ +#define SECP256K1_FE_CONST_INNER(d7, d6, d5, d4, d3, d2, d1, d0) { \ + (d0) | (((uint64_t)(d1) & 0xFFFFFUL) << 32), \ + ((uint64_t)(d1) >> 20) | (((uint64_t)(d2)) << 12) | (((uint64_t)(d3) & 0xFFUL) << 44), \ + ((uint64_t)(d3) >> 8) | (((uint64_t)(d4) & 0xFFFFFFFUL) << 24), \ + ((uint64_t)(d4) >> 28) | (((uint64_t)(d5)) << 4) | (((uint64_t)(d6) & 0xFFFFUL) << 36), \ + ((uint64_t)(d6) >> 16) | (((uint64_t)(d7)) << 16) \ +} + +#ifdef VERIFY +#define SECP256K1_FE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {SECP256K1_FE_CONST_INNER((d7), (d6), (d5), (d4), (d3), (d2), (d1), (d0)), 1, 1} +#else +#define SECP256K1_FE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {SECP256K1_FE_CONST_INNER((d7), (d6), (d5), (d4), (d3), (d2), (d1), (d0))} +#endif + +typedef struct { + uint64_t n[4]; +} secp256k1_fe_storage; + +#define SECP256K1_FE_STORAGE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{ \ + (d0) | (((uint64_t)(d1)) << 32), \ + (d2) | (((uint64_t)(d3)) << 32), \ + (d4) | (((uint64_t)(d5)) << 32), \ + (d6) | (((uint64_t)(d7)) << 32) \ +}} + +#endif /* SECP256K1_FIELD_REPR_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_5x52_asm_impl.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_5x52_asm_impl.h new file mode 100644 index 000000000..1fc3171f6 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_5x52_asm_impl.h @@ -0,0 +1,502 @@ +/********************************************************************** + * Copyright (c) 2013-2014 Diederik Huys, Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +/** + * Changelog: + * - March 2013, Diederik Huys: original version + * - November 2014, Pieter Wuille: updated to use Peter Dettman's parallel multiplication algorithm + * - December 2014, Pieter Wuille: converted from YASM to GCC inline assembly + */ + +#ifndef SECP256K1_FIELD_INNER5X52_IMPL_H +#define SECP256K1_FIELD_INNER5X52_IMPL_H + +SECP256K1_INLINE static void secp256k1_fe_mul_inner(uint64_t *r, const uint64_t *a, const uint64_t * SECP256K1_RESTRICT b) { +/** + * Registers: rdx:rax = multiplication accumulator + * r9:r8 = c + * r15:rcx = d + * r10-r14 = a0-a4 + * rbx = b + * rdi = r + * rsi = a / t? + */ + uint64_t tmp1, tmp2, tmp3; +__asm__ __volatile__( + "movq 0(%%rsi),%%r10\n" + "movq 8(%%rsi),%%r11\n" + "movq 16(%%rsi),%%r12\n" + "movq 24(%%rsi),%%r13\n" + "movq 32(%%rsi),%%r14\n" + + /* d += a3 * b0 */ + "movq 0(%%rbx),%%rax\n" + "mulq %%r13\n" + "movq %%rax,%%rcx\n" + "movq %%rdx,%%r15\n" + /* d += a2 * b1 */ + "movq 8(%%rbx),%%rax\n" + "mulq %%r12\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += a1 * b2 */ + "movq 16(%%rbx),%%rax\n" + "mulq %%r11\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d = a0 * b3 */ + "movq 24(%%rbx),%%rax\n" + "mulq %%r10\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* c = a4 * b4 */ + "movq 32(%%rbx),%%rax\n" + "mulq %%r14\n" + "movq %%rax,%%r8\n" + "movq %%rdx,%%r9\n" + /* d += (c & M) * R */ + "movq $0xfffffffffffff,%%rdx\n" + "andq %%rdx,%%rax\n" + "movq $0x1000003d10,%%rdx\n" + "mulq %%rdx\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* c >>= 52 (%%r8 only) */ + "shrdq $52,%%r9,%%r8\n" + /* t3 (tmp1) = d & M */ + "movq %%rcx,%%rsi\n" + "movq $0xfffffffffffff,%%rdx\n" + "andq %%rdx,%%rsi\n" + "movq %%rsi,%q1\n" + /* d >>= 52 */ + "shrdq $52,%%r15,%%rcx\n" + "xorq %%r15,%%r15\n" + /* d += a4 * b0 */ + "movq 0(%%rbx),%%rax\n" + "mulq %%r14\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += a3 * b1 */ + "movq 8(%%rbx),%%rax\n" + "mulq %%r13\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += a2 * b2 */ + "movq 16(%%rbx),%%rax\n" + "mulq %%r12\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += a1 * b3 */ + "movq 24(%%rbx),%%rax\n" + "mulq %%r11\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += a0 * b4 */ + "movq 32(%%rbx),%%rax\n" + "mulq %%r10\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += c * R */ + "movq %%r8,%%rax\n" + "movq $0x1000003d10,%%rdx\n" + "mulq %%rdx\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* t4 = d & M (%%rsi) */ + "movq %%rcx,%%rsi\n" + "movq $0xfffffffffffff,%%rdx\n" + "andq %%rdx,%%rsi\n" + /* d >>= 52 */ + "shrdq $52,%%r15,%%rcx\n" + "xorq %%r15,%%r15\n" + /* tx = t4 >> 48 (tmp3) */ + "movq %%rsi,%%rax\n" + "shrq $48,%%rax\n" + "movq %%rax,%q3\n" + /* t4 &= (M >> 4) (tmp2) */ + "movq $0xffffffffffff,%%rax\n" + "andq %%rax,%%rsi\n" + "movq %%rsi,%q2\n" + /* c = a0 * b0 */ + "movq 0(%%rbx),%%rax\n" + "mulq %%r10\n" + "movq %%rax,%%r8\n" + "movq %%rdx,%%r9\n" + /* d += a4 * b1 */ + "movq 8(%%rbx),%%rax\n" + "mulq %%r14\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += a3 * b2 */ + "movq 16(%%rbx),%%rax\n" + "mulq %%r13\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += a2 * b3 */ + "movq 24(%%rbx),%%rax\n" + "mulq %%r12\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += a1 * b4 */ + "movq 32(%%rbx),%%rax\n" + "mulq %%r11\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* u0 = d & M (%%rsi) */ + "movq %%rcx,%%rsi\n" + "movq $0xfffffffffffff,%%rdx\n" + "andq %%rdx,%%rsi\n" + /* d >>= 52 */ + "shrdq $52,%%r15,%%rcx\n" + "xorq %%r15,%%r15\n" + /* u0 = (u0 << 4) | tx (%%rsi) */ + "shlq $4,%%rsi\n" + "movq %q3,%%rax\n" + "orq %%rax,%%rsi\n" + /* c += u0 * (R >> 4) */ + "movq $0x1000003d1,%%rax\n" + "mulq %%rsi\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* r[0] = c & M */ + "movq %%r8,%%rax\n" + "movq $0xfffffffffffff,%%rdx\n" + "andq %%rdx,%%rax\n" + "movq %%rax,0(%%rdi)\n" + /* c >>= 52 */ + "shrdq $52,%%r9,%%r8\n" + "xorq %%r9,%%r9\n" + /* c += a1 * b0 */ + "movq 0(%%rbx),%%rax\n" + "mulq %%r11\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* c += a0 * b1 */ + "movq 8(%%rbx),%%rax\n" + "mulq %%r10\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* d += a4 * b2 */ + "movq 16(%%rbx),%%rax\n" + "mulq %%r14\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += a3 * b3 */ + "movq 24(%%rbx),%%rax\n" + "mulq %%r13\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += a2 * b4 */ + "movq 32(%%rbx),%%rax\n" + "mulq %%r12\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* c += (d & M) * R */ + "movq %%rcx,%%rax\n" + "movq $0xfffffffffffff,%%rdx\n" + "andq %%rdx,%%rax\n" + "movq $0x1000003d10,%%rdx\n" + "mulq %%rdx\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* d >>= 52 */ + "shrdq $52,%%r15,%%rcx\n" + "xorq %%r15,%%r15\n" + /* r[1] = c & M */ + "movq %%r8,%%rax\n" + "movq $0xfffffffffffff,%%rdx\n" + "andq %%rdx,%%rax\n" + "movq %%rax,8(%%rdi)\n" + /* c >>= 52 */ + "shrdq $52,%%r9,%%r8\n" + "xorq %%r9,%%r9\n" + /* c += a2 * b0 */ + "movq 0(%%rbx),%%rax\n" + "mulq %%r12\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* c += a1 * b1 */ + "movq 8(%%rbx),%%rax\n" + "mulq %%r11\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* c += a0 * b2 (last use of %%r10 = a0) */ + "movq 16(%%rbx),%%rax\n" + "mulq %%r10\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* fetch t3 (%%r10, overwrites a0), t4 (%%rsi) */ + "movq %q2,%%rsi\n" + "movq %q1,%%r10\n" + /* d += a4 * b3 */ + "movq 24(%%rbx),%%rax\n" + "mulq %%r14\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += a3 * b4 */ + "movq 32(%%rbx),%%rax\n" + "mulq %%r13\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* c += (d & M) * R */ + "movq %%rcx,%%rax\n" + "movq $0xfffffffffffff,%%rdx\n" + "andq %%rdx,%%rax\n" + "movq $0x1000003d10,%%rdx\n" + "mulq %%rdx\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* d >>= 52 (%%rcx only) */ + "shrdq $52,%%r15,%%rcx\n" + /* r[2] = c & M */ + "movq %%r8,%%rax\n" + "movq $0xfffffffffffff,%%rdx\n" + "andq %%rdx,%%rax\n" + "movq %%rax,16(%%rdi)\n" + /* c >>= 52 */ + "shrdq $52,%%r9,%%r8\n" + "xorq %%r9,%%r9\n" + /* c += t3 */ + "addq %%r10,%%r8\n" + /* c += d * R */ + "movq %%rcx,%%rax\n" + "movq $0x1000003d10,%%rdx\n" + "mulq %%rdx\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* r[3] = c & M */ + "movq %%r8,%%rax\n" + "movq $0xfffffffffffff,%%rdx\n" + "andq %%rdx,%%rax\n" + "movq %%rax,24(%%rdi)\n" + /* c >>= 52 (%%r8 only) */ + "shrdq $52,%%r9,%%r8\n" + /* c += t4 (%%r8 only) */ + "addq %%rsi,%%r8\n" + /* r[4] = c */ + "movq %%r8,32(%%rdi)\n" +: "+S"(a), "=m"(tmp1), "=m"(tmp2), "=m"(tmp3) +: "b"(b), "D"(r) +: "%rax", "%rcx", "%rdx", "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15", "cc", "memory" +); +} + +SECP256K1_INLINE static void secp256k1_fe_sqr_inner(uint64_t *r, const uint64_t *a) { +/** + * Registers: rdx:rax = multiplication accumulator + * r9:r8 = c + * rcx:rbx = d + * r10-r14 = a0-a4 + * r15 = M (0xfffffffffffff) + * rdi = r + * rsi = a / t? + */ + uint64_t tmp1, tmp2, tmp3; +__asm__ __volatile__( + "movq 0(%%rsi),%%r10\n" + "movq 8(%%rsi),%%r11\n" + "movq 16(%%rsi),%%r12\n" + "movq 24(%%rsi),%%r13\n" + "movq 32(%%rsi),%%r14\n" + "movq $0xfffffffffffff,%%r15\n" + + /* d = (a0*2) * a3 */ + "leaq (%%r10,%%r10,1),%%rax\n" + "mulq %%r13\n" + "movq %%rax,%%rbx\n" + "movq %%rdx,%%rcx\n" + /* d += (a1*2) * a2 */ + "leaq (%%r11,%%r11,1),%%rax\n" + "mulq %%r12\n" + "addq %%rax,%%rbx\n" + "adcq %%rdx,%%rcx\n" + /* c = a4 * a4 */ + "movq %%r14,%%rax\n" + "mulq %%r14\n" + "movq %%rax,%%r8\n" + "movq %%rdx,%%r9\n" + /* d += (c & M) * R */ + "andq %%r15,%%rax\n" + "movq $0x1000003d10,%%rdx\n" + "mulq %%rdx\n" + "addq %%rax,%%rbx\n" + "adcq %%rdx,%%rcx\n" + /* c >>= 52 (%%r8 only) */ + "shrdq $52,%%r9,%%r8\n" + /* t3 (tmp1) = d & M */ + "movq %%rbx,%%rsi\n" + "andq %%r15,%%rsi\n" + "movq %%rsi,%q1\n" + /* d >>= 52 */ + "shrdq $52,%%rcx,%%rbx\n" + "xorq %%rcx,%%rcx\n" + /* a4 *= 2 */ + "addq %%r14,%%r14\n" + /* d += a0 * a4 */ + "movq %%r10,%%rax\n" + "mulq %%r14\n" + "addq %%rax,%%rbx\n" + "adcq %%rdx,%%rcx\n" + /* d+= (a1*2) * a3 */ + "leaq (%%r11,%%r11,1),%%rax\n" + "mulq %%r13\n" + "addq %%rax,%%rbx\n" + "adcq %%rdx,%%rcx\n" + /* d += a2 * a2 */ + "movq %%r12,%%rax\n" + "mulq %%r12\n" + "addq %%rax,%%rbx\n" + "adcq %%rdx,%%rcx\n" + /* d += c * R */ + "movq %%r8,%%rax\n" + "movq $0x1000003d10,%%rdx\n" + "mulq %%rdx\n" + "addq %%rax,%%rbx\n" + "adcq %%rdx,%%rcx\n" + /* t4 = d & M (%%rsi) */ + "movq %%rbx,%%rsi\n" + "andq %%r15,%%rsi\n" + /* d >>= 52 */ + "shrdq $52,%%rcx,%%rbx\n" + "xorq %%rcx,%%rcx\n" + /* tx = t4 >> 48 (tmp3) */ + "movq %%rsi,%%rax\n" + "shrq $48,%%rax\n" + "movq %%rax,%q3\n" + /* t4 &= (M >> 4) (tmp2) */ + "movq $0xffffffffffff,%%rax\n" + "andq %%rax,%%rsi\n" + "movq %%rsi,%q2\n" + /* c = a0 * a0 */ + "movq %%r10,%%rax\n" + "mulq %%r10\n" + "movq %%rax,%%r8\n" + "movq %%rdx,%%r9\n" + /* d += a1 * a4 */ + "movq %%r11,%%rax\n" + "mulq %%r14\n" + "addq %%rax,%%rbx\n" + "adcq %%rdx,%%rcx\n" + /* d += (a2*2) * a3 */ + "leaq (%%r12,%%r12,1),%%rax\n" + "mulq %%r13\n" + "addq %%rax,%%rbx\n" + "adcq %%rdx,%%rcx\n" + /* u0 = d & M (%%rsi) */ + "movq %%rbx,%%rsi\n" + "andq %%r15,%%rsi\n" + /* d >>= 52 */ + "shrdq $52,%%rcx,%%rbx\n" + "xorq %%rcx,%%rcx\n" + /* u0 = (u0 << 4) | tx (%%rsi) */ + "shlq $4,%%rsi\n" + "movq %q3,%%rax\n" + "orq %%rax,%%rsi\n" + /* c += u0 * (R >> 4) */ + "movq $0x1000003d1,%%rax\n" + "mulq %%rsi\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* r[0] = c & M */ + "movq %%r8,%%rax\n" + "andq %%r15,%%rax\n" + "movq %%rax,0(%%rdi)\n" + /* c >>= 52 */ + "shrdq $52,%%r9,%%r8\n" + "xorq %%r9,%%r9\n" + /* a0 *= 2 */ + "addq %%r10,%%r10\n" + /* c += a0 * a1 */ + "movq %%r10,%%rax\n" + "mulq %%r11\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* d += a2 * a4 */ + "movq %%r12,%%rax\n" + "mulq %%r14\n" + "addq %%rax,%%rbx\n" + "adcq %%rdx,%%rcx\n" + /* d += a3 * a3 */ + "movq %%r13,%%rax\n" + "mulq %%r13\n" + "addq %%rax,%%rbx\n" + "adcq %%rdx,%%rcx\n" + /* c += (d & M) * R */ + "movq %%rbx,%%rax\n" + "andq %%r15,%%rax\n" + "movq $0x1000003d10,%%rdx\n" + "mulq %%rdx\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* d >>= 52 */ + "shrdq $52,%%rcx,%%rbx\n" + "xorq %%rcx,%%rcx\n" + /* r[1] = c & M */ + "movq %%r8,%%rax\n" + "andq %%r15,%%rax\n" + "movq %%rax,8(%%rdi)\n" + /* c >>= 52 */ + "shrdq $52,%%r9,%%r8\n" + "xorq %%r9,%%r9\n" + /* c += a0 * a2 (last use of %%r10) */ + "movq %%r10,%%rax\n" + "mulq %%r12\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* fetch t3 (%%r10, overwrites a0),t4 (%%rsi) */ + "movq %q2,%%rsi\n" + "movq %q1,%%r10\n" + /* c += a1 * a1 */ + "movq %%r11,%%rax\n" + "mulq %%r11\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* d += a3 * a4 */ + "movq %%r13,%%rax\n" + "mulq %%r14\n" + "addq %%rax,%%rbx\n" + "adcq %%rdx,%%rcx\n" + /* c += (d & M) * R */ + "movq %%rbx,%%rax\n" + "andq %%r15,%%rax\n" + "movq $0x1000003d10,%%rdx\n" + "mulq %%rdx\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* d >>= 52 (%%rbx only) */ + "shrdq $52,%%rcx,%%rbx\n" + /* r[2] = c & M */ + "movq %%r8,%%rax\n" + "andq %%r15,%%rax\n" + "movq %%rax,16(%%rdi)\n" + /* c >>= 52 */ + "shrdq $52,%%r9,%%r8\n" + "xorq %%r9,%%r9\n" + /* c += t3 */ + "addq %%r10,%%r8\n" + /* c += d * R */ + "movq %%rbx,%%rax\n" + "movq $0x1000003d10,%%rdx\n" + "mulq %%rdx\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* r[3] = c & M */ + "movq %%r8,%%rax\n" + "andq %%r15,%%rax\n" + "movq %%rax,24(%%rdi)\n" + /* c >>= 52 (%%r8 only) */ + "shrdq $52,%%r9,%%r8\n" + /* c += t4 (%%r8 only) */ + "addq %%rsi,%%r8\n" + /* r[4] = c */ + "movq %%r8,32(%%rdi)\n" +: "+S"(a), "=m"(tmp1), "=m"(tmp2), "=m"(tmp3) +: "D"(r) +: "%rax", "%rbx", "%rcx", "%rdx", "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15", "cc", "memory" +); +} + +#endif /* SECP256K1_FIELD_INNER5X52_IMPL_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_5x52_impl.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_5x52_impl.h new file mode 100644 index 000000000..004dd8bd1 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_5x52_impl.h @@ -0,0 +1,494 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_FIELD_REPR_IMPL_H +#define SECP256K1_FIELD_REPR_IMPL_H + +#include "secp256k1-config.h" + +#include "util.h" +#include "num.h" +#include "field.h" + +#if defined(USE_ASM_X86_64) +#include "field_5x52_asm_impl.h" +#else +#include "field_5x52_int128_impl.h" +#endif + +/** Implements arithmetic modulo FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE FFFFFC2F, + * represented as 5 uint64_t's in base 2^52. The values are allowed to contain >52 each. In particular, + * each FieldElem has a 'magnitude' associated with it. Internally, a magnitude M means each element + * is at most M*(2^53-1), except the most significant one, which is limited to M*(2^49-1). All operations + * accept any input with magnitude at most M, and have different rules for propagating magnitude to their + * output. + */ + +#ifdef VERIFY +static void secp256k1_fe_verify(const secp256k1_fe *a) { + const uint64_t *d = a->n; + int m = a->normalized ? 1 : 2 * a->magnitude, r = 1; + /* secp256k1 'p' value defined in "Standards for Efficient Cryptography" (SEC2) 2.7.1. */ + r &= (d[0] <= 0xFFFFFFFFFFFFFULL * m); + r &= (d[1] <= 0xFFFFFFFFFFFFFULL * m); + r &= (d[2] <= 0xFFFFFFFFFFFFFULL * m); + r &= (d[3] <= 0xFFFFFFFFFFFFFULL * m); + r &= (d[4] <= 0x0FFFFFFFFFFFFULL * m); + r &= (a->magnitude >= 0); + r &= (a->magnitude <= 2048); + if (a->normalized) { + r &= (a->magnitude <= 1); + if (r && (d[4] == 0x0FFFFFFFFFFFFULL) && ((d[3] & d[2] & d[1]) == 0xFFFFFFFFFFFFFULL)) { + r &= (d[0] < 0xFFFFEFFFFFC2FULL); + } + } + VERIFY_CHECK(r == 1); +} +#endif + +static void secp256k1_fe_normalize(secp256k1_fe *r) { + uint64_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4]; + + /* Reduce t4 at the start so there will be at most a single carry from the first pass */ + uint64_t m; + uint64_t x = t4 >> 48; t4 &= 0x0FFFFFFFFFFFFULL; + + /* The first pass ensures the magnitude is 1, ... */ + t0 += x * 0x1000003D1ULL; + t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL; + t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL; m = t1; + t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL; m &= t2; + t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL; m &= t3; + + /* ... except for a possible carry at bit 48 of t4 (i.e. bit 256 of the field element) */ + VERIFY_CHECK(t4 >> 49 == 0); + + /* At most a single final reduction is needed; check if the value is >= the field characteristic */ + x = (t4 >> 48) | ((t4 == 0x0FFFFFFFFFFFFULL) & (m == 0xFFFFFFFFFFFFFULL) + & (t0 >= 0xFFFFEFFFFFC2FULL)); + + /* Apply the final reduction (for constant-time behaviour, we do it always) */ + t0 += x * 0x1000003D1ULL; + t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL; + t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL; + t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL; + t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL; + + /* If t4 didn't carry to bit 48 already, then it should have after any final reduction */ + VERIFY_CHECK(t4 >> 48 == x); + + /* Mask off the possible multiple of 2^256 from the final reduction */ + t4 &= 0x0FFFFFFFFFFFFULL; + + r->n[0] = t0; r->n[1] = t1; r->n[2] = t2; r->n[3] = t3; r->n[4] = t4; + +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 1; + secp256k1_fe_verify(r); +#endif +} + +static void secp256k1_fe_normalize_weak(secp256k1_fe *r) { + uint64_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4]; + + /* Reduce t4 at the start so there will be at most a single carry from the first pass */ + uint64_t x = t4 >> 48; t4 &= 0x0FFFFFFFFFFFFULL; + + /* The first pass ensures the magnitude is 1, ... */ + t0 += x * 0x1000003D1ULL; + t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL; + t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL; + t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL; + t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL; + + /* ... except for a possible carry at bit 48 of t4 (i.e. bit 256 of the field element) */ + VERIFY_CHECK(t4 >> 49 == 0); + + r->n[0] = t0; r->n[1] = t1; r->n[2] = t2; r->n[3] = t3; r->n[4] = t4; + +#ifdef VERIFY + r->magnitude = 1; + secp256k1_fe_verify(r); +#endif +} + +static void secp256k1_fe_normalize_var(secp256k1_fe *r) { + uint64_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4]; + + /* Reduce t4 at the start so there will be at most a single carry from the first pass */ + uint64_t m; + uint64_t x = t4 >> 48; t4 &= 0x0FFFFFFFFFFFFULL; + + /* The first pass ensures the magnitude is 1, ... */ + t0 += x * 0x1000003D1ULL; + t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL; + t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL; m = t1; + t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL; m &= t2; + t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL; m &= t3; + + /* ... except for a possible carry at bit 48 of t4 (i.e. bit 256 of the field element) */ + VERIFY_CHECK(t4 >> 49 == 0); + + /* At most a single final reduction is needed; check if the value is >= the field characteristic */ + x = (t4 >> 48) | ((t4 == 0x0FFFFFFFFFFFFULL) & (m == 0xFFFFFFFFFFFFFULL) + & (t0 >= 0xFFFFEFFFFFC2FULL)); + + if (x) { + t0 += 0x1000003D1ULL; + t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL; + t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL; + t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL; + t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL; + + /* If t4 didn't carry to bit 48 already, then it should have after any final reduction */ + VERIFY_CHECK(t4 >> 48 == x); + + /* Mask off the possible multiple of 2^256 from the final reduction */ + t4 &= 0x0FFFFFFFFFFFFULL; + } + + r->n[0] = t0; r->n[1] = t1; r->n[2] = t2; r->n[3] = t3; r->n[4] = t4; + +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 1; + secp256k1_fe_verify(r); +#endif +} + +static int secp256k1_fe_normalizes_to_zero(secp256k1_fe *r) { + uint64_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4]; + + /* z0 tracks a possible raw value of 0, z1 tracks a possible raw value of P */ + uint64_t z0, z1; + + /* Reduce t4 at the start so there will be at most a single carry from the first pass */ + uint64_t x = t4 >> 48; t4 &= 0x0FFFFFFFFFFFFULL; + + /* The first pass ensures the magnitude is 1, ... */ + t0 += x * 0x1000003D1ULL; + t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL; z0 = t0; z1 = t0 ^ 0x1000003D0ULL; + t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL; z0 |= t1; z1 &= t1; + t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL; z0 |= t2; z1 &= t2; + t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL; z0 |= t3; z1 &= t3; + z0 |= t4; z1 &= t4 ^ 0xF000000000000ULL; + + /* ... except for a possible carry at bit 48 of t4 (i.e. bit 256 of the field element) */ + VERIFY_CHECK(t4 >> 49 == 0); + + return (z0 == 0) | (z1 == 0xFFFFFFFFFFFFFULL); +} + +static int secp256k1_fe_normalizes_to_zero_var(secp256k1_fe *r) { + uint64_t t0, t1, t2, t3, t4; + uint64_t z0, z1; + uint64_t x; + + t0 = r->n[0]; + t4 = r->n[4]; + + /* Reduce t4 at the start so there will be at most a single carry from the first pass */ + x = t4 >> 48; + + /* The first pass ensures the magnitude is 1, ... */ + t0 += x * 0x1000003D1ULL; + + /* z0 tracks a possible raw value of 0, z1 tracks a possible raw value of P */ + z0 = t0 & 0xFFFFFFFFFFFFFULL; + z1 = z0 ^ 0x1000003D0ULL; + + /* Fast return path should catch the majority of cases */ + if ((z0 != 0ULL) & (z1 != 0xFFFFFFFFFFFFFULL)) { + return 0; + } + + t1 = r->n[1]; + t2 = r->n[2]; + t3 = r->n[3]; + + t4 &= 0x0FFFFFFFFFFFFULL; + + t1 += (t0 >> 52); + t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL; z0 |= t1; z1 &= t1; + t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL; z0 |= t2; z1 &= t2; + t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL; z0 |= t3; z1 &= t3; + z0 |= t4; z1 &= t4 ^ 0xF000000000000ULL; + + /* ... except for a possible carry at bit 48 of t4 (i.e. bit 256 of the field element) */ + VERIFY_CHECK(t4 >> 49 == 0); + + return (z0 == 0) | (z1 == 0xFFFFFFFFFFFFFULL); +} + +SECP256K1_INLINE static void secp256k1_fe_set_int(secp256k1_fe *r, int a) { + r->n[0] = a; + r->n[1] = r->n[2] = r->n[3] = r->n[4] = 0; +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 1; + secp256k1_fe_verify(r); +#endif +} + +SECP256K1_INLINE static int secp256k1_fe_is_zero(const secp256k1_fe *a) { + const uint64_t *t = a->n; +#ifdef VERIFY + VERIFY_CHECK(a->normalized); + secp256k1_fe_verify(a); +#endif + return (t[0] | t[1] | t[2] | t[3] | t[4]) == 0; +} + +SECP256K1_INLINE static int secp256k1_fe_is_odd(const secp256k1_fe *a) { +#ifdef VERIFY + VERIFY_CHECK(a->normalized); + secp256k1_fe_verify(a); +#endif + return a->n[0] & 1; +} + +SECP256K1_INLINE static void secp256k1_fe_clear(secp256k1_fe *a) { + int i; +#ifdef VERIFY + a->magnitude = 0; + a->normalized = 1; +#endif + for (i=0; i<5; i++) { + a->n[i] = 0; + } +} + +static int secp256k1_fe_cmp_var(const secp256k1_fe *a, const secp256k1_fe *b) { + int i; +#ifdef VERIFY + VERIFY_CHECK(a->normalized); + VERIFY_CHECK(b->normalized); + secp256k1_fe_verify(a); + secp256k1_fe_verify(b); +#endif + for (i = 4; i >= 0; i--) { + if (a->n[i] > b->n[i]) { + return 1; + } + if (a->n[i] < b->n[i]) { + return -1; + } + } + return 0; +} + +static int secp256k1_fe_set_b32(secp256k1_fe *r, const unsigned char *a) { + r->n[0] = (uint64_t)a[31] + | ((uint64_t)a[30] << 8) + | ((uint64_t)a[29] << 16) + | ((uint64_t)a[28] << 24) + | ((uint64_t)a[27] << 32) + | ((uint64_t)a[26] << 40) + | ((uint64_t)(a[25] & 0xF) << 48); + r->n[1] = (uint64_t)((a[25] >> 4) & 0xF) + | ((uint64_t)a[24] << 4) + | ((uint64_t)a[23] << 12) + | ((uint64_t)a[22] << 20) + | ((uint64_t)a[21] << 28) + | ((uint64_t)a[20] << 36) + | ((uint64_t)a[19] << 44); + r->n[2] = (uint64_t)a[18] + | ((uint64_t)a[17] << 8) + | ((uint64_t)a[16] << 16) + | ((uint64_t)a[15] << 24) + | ((uint64_t)a[14] << 32) + | ((uint64_t)a[13] << 40) + | ((uint64_t)(a[12] & 0xF) << 48); + r->n[3] = (uint64_t)((a[12] >> 4) & 0xF) + | ((uint64_t)a[11] << 4) + | ((uint64_t)a[10] << 12) + | ((uint64_t)a[9] << 20) + | ((uint64_t)a[8] << 28) + | ((uint64_t)a[7] << 36) + | ((uint64_t)a[6] << 44); + r->n[4] = (uint64_t)a[5] + | ((uint64_t)a[4] << 8) + | ((uint64_t)a[3] << 16) + | ((uint64_t)a[2] << 24) + | ((uint64_t)a[1] << 32) + | ((uint64_t)a[0] << 40); + if (r->n[4] == 0x0FFFFFFFFFFFFULL && (r->n[3] & r->n[2] & r->n[1]) == 0xFFFFFFFFFFFFFULL && r->n[0] >= 0xFFFFEFFFFFC2FULL) { + return 0; + } +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 1; + secp256k1_fe_verify(r); +#endif + return 1; +} + +/** Convert a field element to a 32-byte big endian value. Requires the input to be normalized */ +static void secp256k1_fe_get_b32(unsigned char *r, const secp256k1_fe *a) { +#ifdef VERIFY + VERIFY_CHECK(a->normalized); + secp256k1_fe_verify(a); +#endif + r[0] = (a->n[4] >> 40) & 0xFF; + r[1] = (a->n[4] >> 32) & 0xFF; + r[2] = (a->n[4] >> 24) & 0xFF; + r[3] = (a->n[4] >> 16) & 0xFF; + r[4] = (a->n[4] >> 8) & 0xFF; + r[5] = a->n[4] & 0xFF; + r[6] = (a->n[3] >> 44) & 0xFF; + r[7] = (a->n[3] >> 36) & 0xFF; + r[8] = (a->n[3] >> 28) & 0xFF; + r[9] = (a->n[3] >> 20) & 0xFF; + r[10] = (a->n[3] >> 12) & 0xFF; + r[11] = (a->n[3] >> 4) & 0xFF; + r[12] = ((a->n[2] >> 48) & 0xF) | ((a->n[3] & 0xF) << 4); + r[13] = (a->n[2] >> 40) & 0xFF; + r[14] = (a->n[2] >> 32) & 0xFF; + r[15] = (a->n[2] >> 24) & 0xFF; + r[16] = (a->n[2] >> 16) & 0xFF; + r[17] = (a->n[2] >> 8) & 0xFF; + r[18] = a->n[2] & 0xFF; + r[19] = (a->n[1] >> 44) & 0xFF; + r[20] = (a->n[1] >> 36) & 0xFF; + r[21] = (a->n[1] >> 28) & 0xFF; + r[22] = (a->n[1] >> 20) & 0xFF; + r[23] = (a->n[1] >> 12) & 0xFF; + r[24] = (a->n[1] >> 4) & 0xFF; + r[25] = ((a->n[0] >> 48) & 0xF) | ((a->n[1] & 0xF) << 4); + r[26] = (a->n[0] >> 40) & 0xFF; + r[27] = (a->n[0] >> 32) & 0xFF; + r[28] = (a->n[0] >> 24) & 0xFF; + r[29] = (a->n[0] >> 16) & 0xFF; + r[30] = (a->n[0] >> 8) & 0xFF; + r[31] = a->n[0] & 0xFF; +} + +SECP256K1_INLINE static void secp256k1_fe_negate(secp256k1_fe *r, const secp256k1_fe *a, int m) { +#ifdef VERIFY + VERIFY_CHECK(a->magnitude <= m); + secp256k1_fe_verify(a); +#endif + r->n[0] = 0xFFFFEFFFFFC2FULL * 2 * (m + 1) - a->n[0]; + r->n[1] = 0xFFFFFFFFFFFFFULL * 2 * (m + 1) - a->n[1]; + r->n[2] = 0xFFFFFFFFFFFFFULL * 2 * (m + 1) - a->n[2]; + r->n[3] = 0xFFFFFFFFFFFFFULL * 2 * (m + 1) - a->n[3]; + r->n[4] = 0x0FFFFFFFFFFFFULL * 2 * (m + 1) - a->n[4]; +#ifdef VERIFY + r->magnitude = m + 1; + r->normalized = 0; + secp256k1_fe_verify(r); +#endif +} + +SECP256K1_INLINE static void secp256k1_fe_mul_int(secp256k1_fe *r, int a) { + r->n[0] *= a; + r->n[1] *= a; + r->n[2] *= a; + r->n[3] *= a; + r->n[4] *= a; +#ifdef VERIFY + r->magnitude *= a; + r->normalized = 0; + secp256k1_fe_verify(r); +#endif +} + +SECP256K1_INLINE static void secp256k1_fe_add(secp256k1_fe *r, const secp256k1_fe *a) { +#ifdef VERIFY + secp256k1_fe_verify(a); +#endif + r->n[0] += a->n[0]; + r->n[1] += a->n[1]; + r->n[2] += a->n[2]; + r->n[3] += a->n[3]; + r->n[4] += a->n[4]; +#ifdef VERIFY + r->magnitude += a->magnitude; + r->normalized = 0; + secp256k1_fe_verify(r); +#endif +} + +static void secp256k1_fe_mul(secp256k1_fe *r, const secp256k1_fe *a, const secp256k1_fe * SECP256K1_RESTRICT b) { +#ifdef VERIFY + VERIFY_CHECK(a->magnitude <= 8); + VERIFY_CHECK(b->magnitude <= 8); + secp256k1_fe_verify(a); + secp256k1_fe_verify(b); + VERIFY_CHECK(r != b); +#endif + secp256k1_fe_mul_inner(r->n, a->n, b->n); +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 0; + secp256k1_fe_verify(r); +#endif +} + +static void secp256k1_fe_sqr(secp256k1_fe *r, const secp256k1_fe *a) { +#ifdef VERIFY + VERIFY_CHECK(a->magnitude <= 8); + secp256k1_fe_verify(a); +#endif + secp256k1_fe_sqr_inner(r->n, a->n); +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 0; + secp256k1_fe_verify(r); +#endif +} + +static SECP256K1_INLINE void secp256k1_fe_cmov(secp256k1_fe *r, const secp256k1_fe *a, int flag) { + uint64_t mask0, mask1; + mask0 = flag + ~((uint64_t)0); + mask1 = ~mask0; + r->n[0] = (r->n[0] & mask0) | (a->n[0] & mask1); + r->n[1] = (r->n[1] & mask0) | (a->n[1] & mask1); + r->n[2] = (r->n[2] & mask0) | (a->n[2] & mask1); + r->n[3] = (r->n[3] & mask0) | (a->n[3] & mask1); + r->n[4] = (r->n[4] & mask0) | (a->n[4] & mask1); +#ifdef VERIFY + if (a->magnitude > r->magnitude) { + r->magnitude = a->magnitude; + } + r->normalized &= a->normalized; +#endif +} + +static SECP256K1_INLINE void secp256k1_fe_storage_cmov(secp256k1_fe_storage *r, const secp256k1_fe_storage *a, int flag) { + uint64_t mask0, mask1; + mask0 = flag + ~((uint64_t)0); + mask1 = ~mask0; + r->n[0] = (r->n[0] & mask0) | (a->n[0] & mask1); + r->n[1] = (r->n[1] & mask0) | (a->n[1] & mask1); + r->n[2] = (r->n[2] & mask0) | (a->n[2] & mask1); + r->n[3] = (r->n[3] & mask0) | (a->n[3] & mask1); +} + +static void secp256k1_fe_to_storage(secp256k1_fe_storage *r, const secp256k1_fe *a) { +#ifdef VERIFY + VERIFY_CHECK(a->normalized); +#endif + r->n[0] = a->n[0] | a->n[1] << 52; + r->n[1] = a->n[1] >> 12 | a->n[2] << 40; + r->n[2] = a->n[2] >> 24 | a->n[3] << 28; + r->n[3] = a->n[3] >> 36 | a->n[4] << 16; +} + +static SECP256K1_INLINE void secp256k1_fe_from_storage(secp256k1_fe *r, const secp256k1_fe_storage *a) { + r->n[0] = a->n[0] & 0xFFFFFFFFFFFFFULL; + r->n[1] = a->n[0] >> 52 | ((a->n[1] << 12) & 0xFFFFFFFFFFFFFULL); + r->n[2] = a->n[1] >> 40 | ((a->n[2] << 24) & 0xFFFFFFFFFFFFFULL); + r->n[3] = a->n[2] >> 28 | ((a->n[3] << 36) & 0xFFFFFFFFFFFFFULL); + r->n[4] = a->n[3] >> 16; +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 1; +#endif +} + +#endif /* SECP256K1_FIELD_REPR_IMPL_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_5x52_int128_impl.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_5x52_int128_impl.h new file mode 100644 index 000000000..95a0d1791 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_5x52_int128_impl.h @@ -0,0 +1,277 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_FIELD_INNER5X52_IMPL_H +#define SECP256K1_FIELD_INNER5X52_IMPL_H + +#include + +#ifdef VERIFY +#define VERIFY_BITS(x, n) VERIFY_CHECK(((x) >> (n)) == 0) +#else +#define VERIFY_BITS(x, n) do { } while(0) +#endif + +SECP256K1_INLINE static void secp256k1_fe_mul_inner(uint64_t *r, const uint64_t *a, const uint64_t * SECP256K1_RESTRICT b) { + uint128_t c, d; + uint64_t t3, t4, tx, u0; + uint64_t a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4]; + const uint64_t M = 0xFFFFFFFFFFFFFULL, R = 0x1000003D10ULL; + + VERIFY_BITS(a[0], 56); + VERIFY_BITS(a[1], 56); + VERIFY_BITS(a[2], 56); + VERIFY_BITS(a[3], 56); + VERIFY_BITS(a[4], 52); + VERIFY_BITS(b[0], 56); + VERIFY_BITS(b[1], 56); + VERIFY_BITS(b[2], 56); + VERIFY_BITS(b[3], 56); + VERIFY_BITS(b[4], 52); + VERIFY_CHECK(r != b); + + /* [... a b c] is a shorthand for ... + a<<104 + b<<52 + c<<0 mod n. + * px is a shorthand for sum(a[i]*b[x-i], i=0..x). + * Note that [x 0 0 0 0 0] = [x*R]. + */ + + d = (uint128_t)a0 * b[3] + + (uint128_t)a1 * b[2] + + (uint128_t)a2 * b[1] + + (uint128_t)a3 * b[0]; + VERIFY_BITS(d, 114); + /* [d 0 0 0] = [p3 0 0 0] */ + c = (uint128_t)a4 * b[4]; + VERIFY_BITS(c, 112); + /* [c 0 0 0 0 d 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */ + d += (c & M) * R; c >>= 52; + VERIFY_BITS(d, 115); + VERIFY_BITS(c, 60); + /* [c 0 0 0 0 0 d 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */ + t3 = d & M; d >>= 52; + VERIFY_BITS(t3, 52); + VERIFY_BITS(d, 63); + /* [c 0 0 0 0 d t3 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */ + + d += (uint128_t)a0 * b[4] + + (uint128_t)a1 * b[3] + + (uint128_t)a2 * b[2] + + (uint128_t)a3 * b[1] + + (uint128_t)a4 * b[0]; + VERIFY_BITS(d, 115); + /* [c 0 0 0 0 d t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */ + d += c * R; + VERIFY_BITS(d, 116); + /* [d t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */ + t4 = d & M; d >>= 52; + VERIFY_BITS(t4, 52); + VERIFY_BITS(d, 64); + /* [d t4 t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */ + tx = (t4 >> 48); t4 &= (M >> 4); + VERIFY_BITS(tx, 4); + VERIFY_BITS(t4, 48); + /* [d t4+(tx<<48) t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */ + + c = (uint128_t)a0 * b[0]; + VERIFY_BITS(c, 112); + /* [d t4+(tx<<48) t3 0 0 c] = [p8 0 0 0 p4 p3 0 0 p0] */ + d += (uint128_t)a1 * b[4] + + (uint128_t)a2 * b[3] + + (uint128_t)a3 * b[2] + + (uint128_t)a4 * b[1]; + VERIFY_BITS(d, 115); + /* [d t4+(tx<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */ + u0 = d & M; d >>= 52; + VERIFY_BITS(u0, 52); + VERIFY_BITS(d, 63); + /* [d u0 t4+(tx<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */ + /* [d 0 t4+(tx<<48)+(u0<<52) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */ + u0 = (u0 << 4) | tx; + VERIFY_BITS(u0, 56); + /* [d 0 t4+(u0<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */ + c += (uint128_t)u0 * (R >> 4); + VERIFY_BITS(c, 115); + /* [d 0 t4 t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */ + r[0] = c & M; c >>= 52; + VERIFY_BITS(r[0], 52); + VERIFY_BITS(c, 61); + /* [d 0 t4 t3 0 c r0] = [p8 0 0 p5 p4 p3 0 0 p0] */ + + c += (uint128_t)a0 * b[1] + + (uint128_t)a1 * b[0]; + VERIFY_BITS(c, 114); + /* [d 0 t4 t3 0 c r0] = [p8 0 0 p5 p4 p3 0 p1 p0] */ + d += (uint128_t)a2 * b[4] + + (uint128_t)a3 * b[3] + + (uint128_t)a4 * b[2]; + VERIFY_BITS(d, 114); + /* [d 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */ + c += (d & M) * R; d >>= 52; + VERIFY_BITS(c, 115); + VERIFY_BITS(d, 62); + /* [d 0 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */ + r[1] = c & M; c >>= 52; + VERIFY_BITS(r[1], 52); + VERIFY_BITS(c, 63); + /* [d 0 0 t4 t3 c r1 r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */ + + c += (uint128_t)a0 * b[2] + + (uint128_t)a1 * b[1] + + (uint128_t)a2 * b[0]; + VERIFY_BITS(c, 114); + /* [d 0 0 t4 t3 c r1 r0] = [p8 0 p6 p5 p4 p3 p2 p1 p0] */ + d += (uint128_t)a3 * b[4] + + (uint128_t)a4 * b[3]; + VERIFY_BITS(d, 114); + /* [d 0 0 t4 t3 c t1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + c += (d & M) * R; d >>= 52; + VERIFY_BITS(c, 115); + VERIFY_BITS(d, 62); + /* [d 0 0 0 t4 t3 c r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + + /* [d 0 0 0 t4 t3 c r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[2] = c & M; c >>= 52; + VERIFY_BITS(r[2], 52); + VERIFY_BITS(c, 63); + /* [d 0 0 0 t4 t3+c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + c += d * R + t3; + VERIFY_BITS(c, 100); + /* [t4 c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[3] = c & M; c >>= 52; + VERIFY_BITS(r[3], 52); + VERIFY_BITS(c, 48); + /* [t4+c r3 r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + c += t4; + VERIFY_BITS(c, 49); + /* [c r3 r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[4] = c; + VERIFY_BITS(r[4], 49); + /* [r4 r3 r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ +} + +SECP256K1_INLINE static void secp256k1_fe_sqr_inner(uint64_t *r, const uint64_t *a) { + uint128_t c, d; + uint64_t a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4]; + int64_t t3, t4, tx, u0; + const uint64_t M = 0xFFFFFFFFFFFFFULL, R = 0x1000003D10ULL; + + VERIFY_BITS(a[0], 56); + VERIFY_BITS(a[1], 56); + VERIFY_BITS(a[2], 56); + VERIFY_BITS(a[3], 56); + VERIFY_BITS(a[4], 52); + + /** [... a b c] is a shorthand for ... + a<<104 + b<<52 + c<<0 mod n. + * px is a shorthand for sum(a[i]*a[x-i], i=0..x). + * Note that [x 0 0 0 0 0] = [x*R]. + */ + + d = (uint128_t)(a0*2) * a3 + + (uint128_t)(a1*2) * a2; + VERIFY_BITS(d, 114); + /* [d 0 0 0] = [p3 0 0 0] */ + c = (uint128_t)a4 * a4; + VERIFY_BITS(c, 112); + /* [c 0 0 0 0 d 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */ + d += (c & M) * R; c >>= 52; + VERIFY_BITS(d, 115); + VERIFY_BITS(c, 60); + /* [c 0 0 0 0 0 d 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */ + t3 = d & M; d >>= 52; + VERIFY_BITS(t3, 52); + VERIFY_BITS(d, 63); + /* [c 0 0 0 0 d t3 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */ + + a4 *= 2; + d += (uint128_t)a0 * a4 + + (uint128_t)(a1*2) * a3 + + (uint128_t)a2 * a2; + VERIFY_BITS(d, 115); + /* [c 0 0 0 0 d t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */ + d += c * R; + VERIFY_BITS(d, 116); + /* [d t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */ + t4 = d & M; d >>= 52; + VERIFY_BITS(t4, 52); + VERIFY_BITS(d, 64); + /* [d t4 t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */ + tx = (t4 >> 48); t4 &= (M >> 4); + VERIFY_BITS(tx, 4); + VERIFY_BITS(t4, 48); + /* [d t4+(tx<<48) t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */ + + c = (uint128_t)a0 * a0; + VERIFY_BITS(c, 112); + /* [d t4+(tx<<48) t3 0 0 c] = [p8 0 0 0 p4 p3 0 0 p0] */ + d += (uint128_t)a1 * a4 + + (uint128_t)(a2*2) * a3; + VERIFY_BITS(d, 114); + /* [d t4+(tx<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */ + u0 = d & M; d >>= 52; + VERIFY_BITS(u0, 52); + VERIFY_BITS(d, 62); + /* [d u0 t4+(tx<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */ + /* [d 0 t4+(tx<<48)+(u0<<52) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */ + u0 = (u0 << 4) | tx; + VERIFY_BITS(u0, 56); + /* [d 0 t4+(u0<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */ + c += (uint128_t)u0 * (R >> 4); + VERIFY_BITS(c, 113); + /* [d 0 t4 t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */ + r[0] = c & M; c >>= 52; + VERIFY_BITS(r[0], 52); + VERIFY_BITS(c, 61); + /* [d 0 t4 t3 0 c r0] = [p8 0 0 p5 p4 p3 0 0 p0] */ + + a0 *= 2; + c += (uint128_t)a0 * a1; + VERIFY_BITS(c, 114); + /* [d 0 t4 t3 0 c r0] = [p8 0 0 p5 p4 p3 0 p1 p0] */ + d += (uint128_t)a2 * a4 + + (uint128_t)a3 * a3; + VERIFY_BITS(d, 114); + /* [d 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */ + c += (d & M) * R; d >>= 52; + VERIFY_BITS(c, 115); + VERIFY_BITS(d, 62); + /* [d 0 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */ + r[1] = c & M; c >>= 52; + VERIFY_BITS(r[1], 52); + VERIFY_BITS(c, 63); + /* [d 0 0 t4 t3 c r1 r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */ + + c += (uint128_t)a0 * a2 + + (uint128_t)a1 * a1; + VERIFY_BITS(c, 114); + /* [d 0 0 t4 t3 c r1 r0] = [p8 0 p6 p5 p4 p3 p2 p1 p0] */ + d += (uint128_t)a3 * a4; + VERIFY_BITS(d, 114); + /* [d 0 0 t4 t3 c r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + c += (d & M) * R; d >>= 52; + VERIFY_BITS(c, 115); + VERIFY_BITS(d, 62); + /* [d 0 0 0 t4 t3 c r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[2] = c & M; c >>= 52; + VERIFY_BITS(r[2], 52); + VERIFY_BITS(c, 63); + /* [d 0 0 0 t4 t3+c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + + c += d * R + t3; + VERIFY_BITS(c, 100); + /* [t4 c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[3] = c & M; c >>= 52; + VERIFY_BITS(r[3], 52); + VERIFY_BITS(c, 48); + /* [t4+c r3 r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + c += t4; + VERIFY_BITS(c, 49); + /* [c r3 r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[4] = c; + VERIFY_BITS(r[4], 49); + /* [r4 r3 r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ +} + +#endif /* SECP256K1_FIELD_INNER5X52_IMPL_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_impl.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_impl.h new file mode 100644 index 000000000..685e74b72 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/field_impl.h @@ -0,0 +1,313 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_FIELD_IMPL_H +#define SECP256K1_FIELD_IMPL_H + +#include "secp256k1-config.h" + +#include "util.h" + +#if defined(USE_FIELD_10X26) +#include "field_10x26_impl.h" +#elif defined(USE_FIELD_5X52) +#include "field_5x52_impl.h" +#else +#error "Please select field implementation" +#endif + +SECP256K1_INLINE static int secp256k1_fe_equal(const secp256k1_fe *a, const secp256k1_fe *b) { + secp256k1_fe na; + secp256k1_fe_negate(&na, a, 1); + secp256k1_fe_add(&na, b); + return secp256k1_fe_normalizes_to_zero(&na); +} + +SECP256K1_INLINE static int secp256k1_fe_equal_var(const secp256k1_fe *a, const secp256k1_fe *b) { + secp256k1_fe na; + secp256k1_fe_negate(&na, a, 1); + secp256k1_fe_add(&na, b); + return secp256k1_fe_normalizes_to_zero_var(&na); +} + +static int secp256k1_fe_sqrt(secp256k1_fe *r, const secp256k1_fe *a) { + /** Given that p is congruent to 3 mod 4, we can compute the square root of + * a mod p as the (p+1)/4'th power of a. + * + * As (p+1)/4 is an even number, it will have the same result for a and for + * (-a). Only one of these two numbers actually has a square root however, + * so we test at the end by squaring and comparing to the input. + * Also because (p+1)/4 is an even number, the computed square root is + * itself always a square (a ** ((p+1)/4) is the square of a ** ((p+1)/8)). + */ + secp256k1_fe x2, x3, x6, x9, x11, x22, x44, x88, x176, x220, x223, t1; + int j; + + /** The binary representation of (p + 1)/4 has 3 blocks of 1s, with lengths in + * { 2, 22, 223 }. Use an addition chain to calculate 2^n - 1 for each block: + * 1, [2], 3, 6, 9, 11, [22], 44, 88, 176, 220, [223] + */ + + secp256k1_fe_sqr(&x2, a); + secp256k1_fe_mul(&x2, &x2, a); + + secp256k1_fe_sqr(&x3, &x2); + secp256k1_fe_mul(&x3, &x3, a); + + x6 = x3; + for (j=0; j<3; j++) { + secp256k1_fe_sqr(&x6, &x6); + } + secp256k1_fe_mul(&x6, &x6, &x3); + + x9 = x6; + for (j=0; j<3; j++) { + secp256k1_fe_sqr(&x9, &x9); + } + secp256k1_fe_mul(&x9, &x9, &x3); + + x11 = x9; + for (j=0; j<2; j++) { + secp256k1_fe_sqr(&x11, &x11); + } + secp256k1_fe_mul(&x11, &x11, &x2); + + x22 = x11; + for (j=0; j<11; j++) { + secp256k1_fe_sqr(&x22, &x22); + } + secp256k1_fe_mul(&x22, &x22, &x11); + + x44 = x22; + for (j=0; j<22; j++) { + secp256k1_fe_sqr(&x44, &x44); + } + secp256k1_fe_mul(&x44, &x44, &x22); + + x88 = x44; + for (j=0; j<44; j++) { + secp256k1_fe_sqr(&x88, &x88); + } + secp256k1_fe_mul(&x88, &x88, &x44); + + x176 = x88; + for (j=0; j<88; j++) { + secp256k1_fe_sqr(&x176, &x176); + } + secp256k1_fe_mul(&x176, &x176, &x88); + + x220 = x176; + for (j=0; j<44; j++) { + secp256k1_fe_sqr(&x220, &x220); + } + secp256k1_fe_mul(&x220, &x220, &x44); + + x223 = x220; + for (j=0; j<3; j++) { + secp256k1_fe_sqr(&x223, &x223); + } + secp256k1_fe_mul(&x223, &x223, &x3); + + /* The final result is then assembled using a sliding window over the blocks. */ + + t1 = x223; + for (j=0; j<23; j++) { + secp256k1_fe_sqr(&t1, &t1); + } + secp256k1_fe_mul(&t1, &t1, &x22); + for (j=0; j<6; j++) { + secp256k1_fe_sqr(&t1, &t1); + } + secp256k1_fe_mul(&t1, &t1, &x2); + secp256k1_fe_sqr(&t1, &t1); + secp256k1_fe_sqr(r, &t1); + + /* Check that a square root was actually calculated */ + + secp256k1_fe_sqr(&t1, r); + return secp256k1_fe_equal(&t1, a); +} + +static void secp256k1_fe_inv(secp256k1_fe *r, const secp256k1_fe *a) { + secp256k1_fe x2, x3, x6, x9, x11, x22, x44, x88, x176, x220, x223, t1; + int j; + + /** The binary representation of (p - 2) has 5 blocks of 1s, with lengths in + * { 1, 2, 22, 223 }. Use an addition chain to calculate 2^n - 1 for each block: + * [1], [2], 3, 6, 9, 11, [22], 44, 88, 176, 220, [223] + */ + + secp256k1_fe_sqr(&x2, a); + secp256k1_fe_mul(&x2, &x2, a); + + secp256k1_fe_sqr(&x3, &x2); + secp256k1_fe_mul(&x3, &x3, a); + + x6 = x3; + for (j=0; j<3; j++) { + secp256k1_fe_sqr(&x6, &x6); + } + secp256k1_fe_mul(&x6, &x6, &x3); + + x9 = x6; + for (j=0; j<3; j++) { + secp256k1_fe_sqr(&x9, &x9); + } + secp256k1_fe_mul(&x9, &x9, &x3); + + x11 = x9; + for (j=0; j<2; j++) { + secp256k1_fe_sqr(&x11, &x11); + } + secp256k1_fe_mul(&x11, &x11, &x2); + + x22 = x11; + for (j=0; j<11; j++) { + secp256k1_fe_sqr(&x22, &x22); + } + secp256k1_fe_mul(&x22, &x22, &x11); + + x44 = x22; + for (j=0; j<22; j++) { + secp256k1_fe_sqr(&x44, &x44); + } + secp256k1_fe_mul(&x44, &x44, &x22); + + x88 = x44; + for (j=0; j<44; j++) { + secp256k1_fe_sqr(&x88, &x88); + } + secp256k1_fe_mul(&x88, &x88, &x44); + + x176 = x88; + for (j=0; j<88; j++) { + secp256k1_fe_sqr(&x176, &x176); + } + secp256k1_fe_mul(&x176, &x176, &x88); + + x220 = x176; + for (j=0; j<44; j++) { + secp256k1_fe_sqr(&x220, &x220); + } + secp256k1_fe_mul(&x220, &x220, &x44); + + x223 = x220; + for (j=0; j<3; j++) { + secp256k1_fe_sqr(&x223, &x223); + } + secp256k1_fe_mul(&x223, &x223, &x3); + + /* The final result is then assembled using a sliding window over the blocks. */ + + t1 = x223; + for (j=0; j<23; j++) { + secp256k1_fe_sqr(&t1, &t1); + } + secp256k1_fe_mul(&t1, &t1, &x22); + for (j=0; j<5; j++) { + secp256k1_fe_sqr(&t1, &t1); + } + secp256k1_fe_mul(&t1, &t1, a); + for (j=0; j<3; j++) { + secp256k1_fe_sqr(&t1, &t1); + } + secp256k1_fe_mul(&t1, &t1, &x2); + for (j=0; j<2; j++) { + secp256k1_fe_sqr(&t1, &t1); + } + secp256k1_fe_mul(r, a, &t1); +} + +static void secp256k1_fe_inv_var(secp256k1_fe *r, const secp256k1_fe *a) { +#if defined(USE_FIELD_INV_BUILTIN) + secp256k1_fe_inv(r, a); +#elif defined(USE_FIELD_INV_NUM) + secp256k1_num n, m; + static const secp256k1_fe negone = SECP256K1_FE_CONST( + 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, + 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFEUL, 0xFFFFFC2EUL + ); + /* secp256k1 field prime, value p defined in "Standards for Efficient Cryptography" (SEC2) 2.7.1. */ + static const unsigned char prime[32] = { + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F + }; + unsigned char b[32]; + int res; + secp256k1_fe c = *a; + secp256k1_fe_normalize_var(&c); + secp256k1_fe_get_b32(b, &c); + secp256k1_num_set_bin(&n, b, 32); + secp256k1_num_set_bin(&m, prime, 32); + secp256k1_num_mod_inverse(&n, &n, &m); + secp256k1_num_get_bin(b, 32, &n); + res = secp256k1_fe_set_b32(r, b); + (void)res; + VERIFY_CHECK(res); + /* Verify the result is the (unique) valid inverse using non-GMP code. */ + secp256k1_fe_mul(&c, &c, r); + secp256k1_fe_add(&c, &negone); + CHECK(secp256k1_fe_normalizes_to_zero_var(&c)); +#else +#error "Please select field inverse implementation" +#endif +} + +static void secp256k1_fe_inv_all_var(secp256k1_fe *r, const secp256k1_fe *a, size_t len) { + secp256k1_fe u; + size_t i; + if (len < 1) { + return; + } + + VERIFY_CHECK((r + len <= a) || (a + len <= r)); + + r[0] = a[0]; + + i = 0; + while (++i < len) { + secp256k1_fe_mul(&r[i], &r[i - 1], &a[i]); + } + + secp256k1_fe_inv_var(&u, &r[--i]); + + while (i > 0) { + size_t j = i--; + secp256k1_fe_mul(&r[j], &r[i], &u); + secp256k1_fe_mul(&u, &u, &a[j]); + } + + r[0] = u; +} + +static int secp256k1_fe_is_quad_var(const secp256k1_fe *a) { +#ifndef USE_NUM_NONE + unsigned char b[32]; + secp256k1_num n; + secp256k1_num m; + /* secp256k1 field prime, value p defined in "Standards for Efficient Cryptography" (SEC2) 2.7.1. */ + static const unsigned char prime[32] = { + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F + }; + + secp256k1_fe c = *a; + secp256k1_fe_normalize_var(&c); + secp256k1_fe_get_b32(b, &c); + secp256k1_num_set_bin(&n, b, 32); + secp256k1_num_set_bin(&m, prime, 32); + return secp256k1_num_jacobi(&n, &m) >= 0; +#else + secp256k1_fe r; + return secp256k1_fe_sqrt(&r, a); +#endif +} + +#endif /* SECP256K1_FIELD_IMPL_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/group.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/group.h new file mode 100644 index 000000000..3947ea2dd --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/group.h @@ -0,0 +1,147 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_GROUP_H +#define SECP256K1_GROUP_H + +#include "num.h" +#include "field.h" + +/** A group element of the secp256k1 curve, in affine coordinates. */ +typedef struct { + secp256k1_fe x; + secp256k1_fe y; + int infinity; /* whether this represents the point at infinity */ +} secp256k1_ge; + +#define SECP256K1_GE_CONST(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) {SECP256K1_FE_CONST((a),(b),(c),(d),(e),(f),(g),(h)), SECP256K1_FE_CONST((i),(j),(k),(l),(m),(n),(o),(p)), 0} +#define SECP256K1_GE_CONST_INFINITY {SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 0), SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 0), 1} + +/** A group element of the secp256k1 curve, in jacobian coordinates. */ +typedef struct { + secp256k1_fe x; /* actual X: x/z^2 */ + secp256k1_fe y; /* actual Y: y/z^3 */ + secp256k1_fe z; + int infinity; /* whether this represents the point at infinity */ +} secp256k1_gej; + +#define SECP256K1_GEJ_CONST(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) {SECP256K1_FE_CONST((a),(b),(c),(d),(e),(f),(g),(h)), SECP256K1_FE_CONST((i),(j),(k),(l),(m),(n),(o),(p)), SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 1), 0} +#define SECP256K1_GEJ_CONST_INFINITY {SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 0), SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 0), SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 0), 1} + +typedef struct { + secp256k1_fe_storage x; + secp256k1_fe_storage y; +} secp256k1_ge_storage; + +#define SECP256K1_GE_STORAGE_CONST(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) {SECP256K1_FE_STORAGE_CONST((a),(b),(c),(d),(e),(f),(g),(h)), SECP256K1_FE_STORAGE_CONST((i),(j),(k),(l),(m),(n),(o),(p))} + +#define SECP256K1_GE_STORAGE_CONST_GET(t) SECP256K1_FE_STORAGE_CONST_GET(t.x), SECP256K1_FE_STORAGE_CONST_GET(t.y) + +/** Set a group element equal to the point with given X and Y coordinates */ +static void secp256k1_ge_set_xy(secp256k1_ge *r, const secp256k1_fe *x, const secp256k1_fe *y); + +/** Set a group element (affine) equal to the point with the given X coordinate + * and a Y coordinate that is a quadratic residue modulo p. The return value + * is true iff a coordinate with the given X coordinate exists. + */ +static int secp256k1_ge_set_xquad(secp256k1_ge *r, const secp256k1_fe *x); + +/** Set a group element (affine) equal to the point with the given X coordinate, and given oddness + * for Y. Return value indicates whether the result is valid. */ +static int secp256k1_ge_set_xo_var(secp256k1_ge *r, const secp256k1_fe *x, int odd); + +/** Check whether a group element is the point at infinity. */ +static int secp256k1_ge_is_infinity(const secp256k1_ge *a); + +/** Check whether a group element is valid (i.e., on the curve). */ +static int secp256k1_ge_is_valid_var(const secp256k1_ge *a); + +static void secp256k1_ge_neg(secp256k1_ge *r, const secp256k1_ge *a); + +/** Set a group element equal to another which is given in jacobian coordinates */ +static void secp256k1_ge_set_gej(secp256k1_ge *r, secp256k1_gej *a); + +/** Set a batch of group elements equal to the inputs given in jacobian coordinates */ +static void secp256k1_ge_set_all_gej_var(secp256k1_ge *r, const secp256k1_gej *a, size_t len, const secp256k1_callback *cb); + +/** Set a batch of group elements equal to the inputs given in jacobian + * coordinates (with known z-ratios). zr must contain the known z-ratios such + * that mul(a[i].z, zr[i+1]) == a[i+1].z. zr[0] is ignored. */ +static void secp256k1_ge_set_table_gej_var(secp256k1_ge *r, const secp256k1_gej *a, const secp256k1_fe *zr, size_t len); + +/** Bring a batch inputs given in jacobian coordinates (with known z-ratios) to + * the same global z "denominator". zr must contain the known z-ratios such + * that mul(a[i].z, zr[i+1]) == a[i+1].z. zr[0] is ignored. The x and y + * coordinates of the result are stored in r, the common z coordinate is + * stored in globalz. */ +static void secp256k1_ge_globalz_set_table_gej(size_t len, secp256k1_ge *r, secp256k1_fe *globalz, const secp256k1_gej *a, const secp256k1_fe *zr); + +/** Set a group element (affine) equal to the point at infinity. */ +static void secp256k1_ge_set_infinity(secp256k1_ge *r); + +/** Set a group element (jacobian) equal to the point at infinity. */ +static void secp256k1_gej_set_infinity(secp256k1_gej *r); + +/** Set a group element (jacobian) equal to another which is given in affine coordinates. */ +static void secp256k1_gej_set_ge(secp256k1_gej *r, const secp256k1_ge *a); + +/** Compare the X coordinate of a group element (jacobian). */ +static int secp256k1_gej_eq_x_var(const secp256k1_fe *x, const secp256k1_gej *a); + +/** Set r equal to the inverse of a (i.e., mirrored around the X axis) */ +static void secp256k1_gej_neg(secp256k1_gej *r, const secp256k1_gej *a); + +/** Check whether a group element is the point at infinity. */ +static int secp256k1_gej_is_infinity(const secp256k1_gej *a); + +/** Check whether a group element's y coordinate is a quadratic residue. */ +static int secp256k1_gej_has_quad_y_var(const secp256k1_gej *a); + +/** Set r equal to the double of a. If rzr is not-NULL, r->z = a->z * *rzr (where infinity means an implicit z = 0). + * a may not be zero. Constant time. */ +static void secp256k1_gej_double_nonzero(secp256k1_gej *r, const secp256k1_gej *a, secp256k1_fe *rzr); + +/** Set r equal to the double of a. If rzr is not-NULL, r->z = a->z * *rzr (where infinity means an implicit z = 0). */ +static void secp256k1_gej_double_var(secp256k1_gej *r, const secp256k1_gej *a, secp256k1_fe *rzr); + +/** Set r equal to the sum of a and b. If rzr is non-NULL, r->z = a->z * *rzr (a cannot be infinity in that case). */ +static void secp256k1_gej_add_var(secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_gej *b, secp256k1_fe *rzr); + +/** Set r equal to the sum of a and b (with b given in affine coordinates, and not infinity). */ +static void secp256k1_gej_add_ge(secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_ge *b); + +/** Set r equal to the sum of a and b (with b given in affine coordinates). This is more efficient + than secp256k1_gej_add_var. It is identical to secp256k1_gej_add_ge but without constant-time + guarantee, and b is allowed to be infinity. If rzr is non-NULL, r->z = a->z * *rzr (a cannot be infinity in that case). */ +static void secp256k1_gej_add_ge_var(secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_ge *b, secp256k1_fe *rzr); + +/** Set r equal to the sum of a and b (with the inverse of b's Z coordinate passed as bzinv). */ +static void secp256k1_gej_add_zinv_var(secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_ge *b, const secp256k1_fe *bzinv); + +#ifdef USE_ENDOMORPHISM +/** Set r to be equal to lambda times a, where lambda is chosen in a way such that this is very fast. */ +static void secp256k1_ge_mul_lambda(secp256k1_ge *r, const secp256k1_ge *a); +#endif + +/** Clear a secp256k1_gej to prevent leaking sensitive information. */ +static void secp256k1_gej_clear(secp256k1_gej *r); + +/** Clear a secp256k1_ge to prevent leaking sensitive information. */ +static void secp256k1_ge_clear(secp256k1_ge *r); + +/** Convert a group element to the storage type. */ +static void secp256k1_ge_to_storage(secp256k1_ge_storage *r, const secp256k1_ge *a); + +/** Convert a group element back from the storage type. */ +static void secp256k1_ge_from_storage(secp256k1_ge *r, const secp256k1_ge_storage *a); + +/** If flag is true, set *r equal to *a; otherwise leave it. Constant-time. */ +static void secp256k1_ge_storage_cmov(secp256k1_ge_storage *r, const secp256k1_ge_storage *a, int flag); + +/** Rescale a jacobian point by b which must be non-zero. Constant-time. */ +static void secp256k1_gej_rescale(secp256k1_gej *r, const secp256k1_fe *b); + +#endif /* SECP256K1_GROUP_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/group_impl.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/group_impl.h new file mode 100644 index 000000000..b1ace87b6 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/group_impl.h @@ -0,0 +1,706 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_GROUP_IMPL_H +#define SECP256K1_GROUP_IMPL_H + +#include "num.h" +#include "field.h" +#include "group.h" + +/* These points can be generated in sage as follows: + * + * 0. Setup a worksheet with the following parameters. + * b = 4 # whatever CURVE_B will be set to + * F = FiniteField (0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F) + * C = EllipticCurve ([F (0), F (b)]) + * + * 1. Determine all the small orders available to you. (If there are + * no satisfactory ones, go back and change b.) + * print C.order().factor(limit=1000) + * + * 2. Choose an order as one of the prime factors listed in the above step. + * (You can also multiply some to get a composite order, though the + * tests will crash trying to invert scalars during signing.) We take a + * random point and scale it to drop its order to the desired value. + * There is some probability this won't work; just try again. + * order = 199 + * P = C.random_point() + * P = (int(P.order()) / int(order)) * P + * assert(P.order() == order) + * + * 3. Print the values. You'll need to use a vim macro or something to + * split the hex output into 4-byte chunks. + * print "%x %x" % P.xy() + */ +#if defined(EXHAUSTIVE_TEST_ORDER) +# if EXHAUSTIVE_TEST_ORDER == 199 +const secp256k1_ge secp256k1_ge_const_g = SECP256K1_GE_CONST( + 0xFA7CC9A7, 0x0737F2DB, 0xA749DD39, 0x2B4FB069, + 0x3B017A7D, 0xA808C2F1, 0xFB12940C, 0x9EA66C18, + 0x78AC123A, 0x5ED8AEF3, 0x8732BC91, 0x1F3A2868, + 0x48DF246C, 0x808DAE72, 0xCFE52572, 0x7F0501ED +); + +const int CURVE_B = 4; +# elif EXHAUSTIVE_TEST_ORDER == 13 +const secp256k1_ge secp256k1_ge_const_g = SECP256K1_GE_CONST( + 0xedc60018, 0xa51a786b, 0x2ea91f4d, 0x4c9416c0, + 0x9de54c3b, 0xa1316554, 0x6cf4345c, 0x7277ef15, + 0x54cb1b6b, 0xdc8c1273, 0x087844ea, 0x43f4603e, + 0x0eaf9a43, 0xf6effe55, 0x939f806d, 0x37adf8ac +); +const int CURVE_B = 2; +# else +# error No known generator for the specified exhaustive test group order. +# endif +#else +/** Generator for secp256k1, value 'g' defined in + * "Standards for Efficient Cryptography" (SEC2) 2.7.1. + */ +static const secp256k1_ge secp256k1_ge_const_g = SECP256K1_GE_CONST( + 0x79BE667EUL, 0xF9DCBBACUL, 0x55A06295UL, 0xCE870B07UL, + 0x029BFCDBUL, 0x2DCE28D9UL, 0x59F2815BUL, 0x16F81798UL, + 0x483ADA77UL, 0x26A3C465UL, 0x5DA4FBFCUL, 0x0E1108A8UL, + 0xFD17B448UL, 0xA6855419UL, 0x9C47D08FUL, 0xFB10D4B8UL +); + +const int CURVE_B = 7; +#endif + +static void secp256k1_ge_set_gej_zinv(secp256k1_ge *r, const secp256k1_gej *a, const secp256k1_fe *zi) { + secp256k1_fe zi2; + secp256k1_fe zi3; + secp256k1_fe_sqr(&zi2, zi); + secp256k1_fe_mul(&zi3, &zi2, zi); + secp256k1_fe_mul(&r->x, &a->x, &zi2); + secp256k1_fe_mul(&r->y, &a->y, &zi3); + r->infinity = a->infinity; +} + +static void secp256k1_ge_set_xy(secp256k1_ge *r, const secp256k1_fe *x, const secp256k1_fe *y) { + r->infinity = 0; + r->x = *x; + r->y = *y; +} + +static int secp256k1_ge_is_infinity(const secp256k1_ge *a) { + return a->infinity; +} + +static void secp256k1_ge_neg(secp256k1_ge *r, const secp256k1_ge *a) { + *r = *a; + secp256k1_fe_normalize_weak(&r->y); + secp256k1_fe_negate(&r->y, &r->y, 1); +} + +static void secp256k1_ge_set_gej(secp256k1_ge *r, secp256k1_gej *a) { + secp256k1_fe z2, z3; + r->infinity = a->infinity; + secp256k1_fe_inv(&a->z, &a->z); + secp256k1_fe_sqr(&z2, &a->z); + secp256k1_fe_mul(&z3, &a->z, &z2); + secp256k1_fe_mul(&a->x, &a->x, &z2); + secp256k1_fe_mul(&a->y, &a->y, &z3); + secp256k1_fe_set_int(&a->z, 1); + r->x = a->x; + r->y = a->y; +} + +static void secp256k1_ge_set_gej_var(secp256k1_ge *r, secp256k1_gej *a) { + secp256k1_fe z2, z3; + r->infinity = a->infinity; + if (a->infinity) { + return; + } + secp256k1_fe_inv_var(&a->z, &a->z); + secp256k1_fe_sqr(&z2, &a->z); + secp256k1_fe_mul(&z3, &a->z, &z2); + secp256k1_fe_mul(&a->x, &a->x, &z2); + secp256k1_fe_mul(&a->y, &a->y, &z3); + secp256k1_fe_set_int(&a->z, 1); + r->x = a->x; + r->y = a->y; +} + +static void secp256k1_ge_set_all_gej_var(secp256k1_ge *r, const secp256k1_gej *a, size_t len, const secp256k1_callback *cb) { + secp256k1_fe *az; + secp256k1_fe *azi; + size_t i; + size_t count = 0; + az = (secp256k1_fe *)checked_malloc(cb, sizeof(secp256k1_fe) * len); + for (i = 0; i < len; i++) { + if (!a[i].infinity) { + az[count++] = a[i].z; + } + } + + azi = (secp256k1_fe *)checked_malloc(cb, sizeof(secp256k1_fe) * count); + secp256k1_fe_inv_all_var(azi, az, count); + free(az); + + count = 0; + for (i = 0; i < len; i++) { + r[i].infinity = a[i].infinity; + if (!a[i].infinity) { + secp256k1_ge_set_gej_zinv(&r[i], &a[i], &azi[count++]); + } + } + free(azi); +} + +static void secp256k1_ge_set_table_gej_var(secp256k1_ge *r, const secp256k1_gej *a, const secp256k1_fe *zr, size_t len) { + size_t i = len - 1; + secp256k1_fe zi; + + if (len > 0) { + /* Compute the inverse of the last z coordinate, and use it to compute the last affine output. */ + secp256k1_fe_inv(&zi, &a[i].z); + secp256k1_ge_set_gej_zinv(&r[i], &a[i], &zi); + + /* Work out way backwards, using the z-ratios to scale the x/y values. */ + while (i > 0) { + secp256k1_fe_mul(&zi, &zi, &zr[i]); + i--; + secp256k1_ge_set_gej_zinv(&r[i], &a[i], &zi); + } + } +} + +static void secp256k1_ge_globalz_set_table_gej(size_t len, secp256k1_ge *r, secp256k1_fe *globalz, const secp256k1_gej *a, const secp256k1_fe *zr) { + size_t i = len - 1; + secp256k1_fe zs; + + if (len > 0) { + /* The z of the final point gives us the "global Z" for the table. */ + r[i].x = a[i].x; + r[i].y = a[i].y; + *globalz = a[i].z; + r[i].infinity = 0; + zs = zr[i]; + + /* Work our way backwards, using the z-ratios to scale the x/y values. */ + while (i > 0) { + if (i != len - 1) { + secp256k1_fe_mul(&zs, &zs, &zr[i]); + } + i--; + secp256k1_ge_set_gej_zinv(&r[i], &a[i], &zs); + } + } +} + +static void secp256k1_gej_set_infinity(secp256k1_gej *r) { + r->infinity = 1; + secp256k1_fe_clear(&r->x); + secp256k1_fe_clear(&r->y); + secp256k1_fe_clear(&r->z); +} + +static void secp256k1_ge_set_infinity(secp256k1_ge *r) { + r->infinity = 1; + secp256k1_fe_clear(&r->x); + secp256k1_fe_clear(&r->y); +} + +static void secp256k1_gej_clear(secp256k1_gej *r) { + r->infinity = 0; + secp256k1_fe_clear(&r->x); + secp256k1_fe_clear(&r->y); + secp256k1_fe_clear(&r->z); +} + +static void secp256k1_ge_clear(secp256k1_ge *r) { + r->infinity = 0; + secp256k1_fe_clear(&r->x); + secp256k1_fe_clear(&r->y); +} + +static int secp256k1_ge_set_xquad(secp256k1_ge *r, const secp256k1_fe *x) { + secp256k1_fe x2, x3, c; + r->x = *x; + secp256k1_fe_sqr(&x2, x); + secp256k1_fe_mul(&x3, x, &x2); + r->infinity = 0; + secp256k1_fe_set_int(&c, CURVE_B); + secp256k1_fe_add(&c, &x3); + return secp256k1_fe_sqrt(&r->y, &c); +} + +static int secp256k1_ge_set_xo_var(secp256k1_ge *r, const secp256k1_fe *x, int odd) { + if (!secp256k1_ge_set_xquad(r, x)) { + return 0; + } + secp256k1_fe_normalize_var(&r->y); + if (secp256k1_fe_is_odd(&r->y) != odd) { + secp256k1_fe_negate(&r->y, &r->y, 1); + } + return 1; + +} + +static void secp256k1_gej_set_ge(secp256k1_gej *r, const secp256k1_ge *a) { + r->infinity = a->infinity; + r->x = a->x; + r->y = a->y; + secp256k1_fe_set_int(&r->z, 1); +} + +static int secp256k1_gej_eq_x_var(const secp256k1_fe *x, const secp256k1_gej *a) { + secp256k1_fe r, r2; + VERIFY_CHECK(!a->infinity); + secp256k1_fe_sqr(&r, &a->z); secp256k1_fe_mul(&r, &r, x); + r2 = a->x; secp256k1_fe_normalize_weak(&r2); + return secp256k1_fe_equal_var(&r, &r2); +} + +static void secp256k1_gej_neg(secp256k1_gej *r, const secp256k1_gej *a) { + r->infinity = a->infinity; + r->x = a->x; + r->y = a->y; + r->z = a->z; + secp256k1_fe_normalize_weak(&r->y); + secp256k1_fe_negate(&r->y, &r->y, 1); +} + +static int secp256k1_gej_is_infinity(const secp256k1_gej *a) { + return a->infinity; +} + +static int secp256k1_gej_is_valid_var(const secp256k1_gej *a) { + secp256k1_fe y2, x3, z2, z6; + if (a->infinity) { + return 0; + } + /** y^2 = x^3 + 7 + * (Y/Z^3)^2 = (X/Z^2)^3 + 7 + * Y^2 / Z^6 = X^3 / Z^6 + 7 + * Y^2 = X^3 + 7*Z^6 + */ + secp256k1_fe_sqr(&y2, &a->y); + secp256k1_fe_sqr(&x3, &a->x); secp256k1_fe_mul(&x3, &x3, &a->x); + secp256k1_fe_sqr(&z2, &a->z); + secp256k1_fe_sqr(&z6, &z2); secp256k1_fe_mul(&z6, &z6, &z2); + secp256k1_fe_mul_int(&z6, CURVE_B); + secp256k1_fe_add(&x3, &z6); + secp256k1_fe_normalize_weak(&x3); + return secp256k1_fe_equal_var(&y2, &x3); +} + +static int secp256k1_ge_is_valid_var(const secp256k1_ge *a) { + secp256k1_fe y2, x3, c; + if (a->infinity) { + return 0; + } + /* y^2 = x^3 + 7 */ + secp256k1_fe_sqr(&y2, &a->y); + secp256k1_fe_sqr(&x3, &a->x); secp256k1_fe_mul(&x3, &x3, &a->x); + secp256k1_fe_set_int(&c, CURVE_B); + secp256k1_fe_add(&x3, &c); + secp256k1_fe_normalize_weak(&x3); + return secp256k1_fe_equal_var(&y2, &x3); +} + +static void secp256k1_gej_double_var(secp256k1_gej *r, const secp256k1_gej *a, secp256k1_fe *rzr) { + /* Operations: 3 mul, 4 sqr, 0 normalize, 12 mul_int/add/negate. + * + * Note that there is an implementation described at + * https://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l + * which trades a multiply for a square, but in practice this is actually slower, + * mainly because it requires more normalizations. + */ + secp256k1_fe t1,t2,t3,t4; + /** For secp256k1, 2Q is infinity if and only if Q is infinity. This is because if 2Q = infinity, + * Q must equal -Q, or that Q.y == -(Q.y), or Q.y is 0. For a point on y^2 = x^3 + 7 to have + * y=0, x^3 must be -7 mod p. However, -7 has no cube root mod p. + * + * Having said this, if this function receives a point on a sextic twist, e.g. by + * a fault attack, it is possible for y to be 0. This happens for y^2 = x^3 + 6, + * since -6 does have a cube root mod p. For this point, this function will not set + * the infinity flag even though the point doubles to infinity, and the result + * point will be gibberish (z = 0 but infinity = 0). + */ + r->infinity = a->infinity; + if (r->infinity) { + if (rzr != NULL) { + secp256k1_fe_set_int(rzr, 1); + } + return; + } + + if (rzr != NULL) { + *rzr = a->y; + secp256k1_fe_normalize_weak(rzr); + secp256k1_fe_mul_int(rzr, 2); + } + + secp256k1_fe_mul(&r->z, &a->z, &a->y); + secp256k1_fe_mul_int(&r->z, 2); /* Z' = 2*Y*Z (2) */ + secp256k1_fe_sqr(&t1, &a->x); + secp256k1_fe_mul_int(&t1, 3); /* T1 = 3*X^2 (3) */ + secp256k1_fe_sqr(&t2, &t1); /* T2 = 9*X^4 (1) */ + secp256k1_fe_sqr(&t3, &a->y); + secp256k1_fe_mul_int(&t3, 2); /* T3 = 2*Y^2 (2) */ + secp256k1_fe_sqr(&t4, &t3); + secp256k1_fe_mul_int(&t4, 2); /* T4 = 8*Y^4 (2) */ + secp256k1_fe_mul(&t3, &t3, &a->x); /* T3 = 2*X*Y^2 (1) */ + r->x = t3; + secp256k1_fe_mul_int(&r->x, 4); /* X' = 8*X*Y^2 (4) */ + secp256k1_fe_negate(&r->x, &r->x, 4); /* X' = -8*X*Y^2 (5) */ + secp256k1_fe_add(&r->x, &t2); /* X' = 9*X^4 - 8*X*Y^2 (6) */ + secp256k1_fe_negate(&t2, &t2, 1); /* T2 = -9*X^4 (2) */ + secp256k1_fe_mul_int(&t3, 6); /* T3 = 12*X*Y^2 (6) */ + secp256k1_fe_add(&t3, &t2); /* T3 = 12*X*Y^2 - 9*X^4 (8) */ + secp256k1_fe_mul(&r->y, &t1, &t3); /* Y' = 36*X^3*Y^2 - 27*X^6 (1) */ + secp256k1_fe_negate(&t2, &t4, 2); /* T2 = -8*Y^4 (3) */ + secp256k1_fe_add(&r->y, &t2); /* Y' = 36*X^3*Y^2 - 27*X^6 - 8*Y^4 (4) */ +} + +static SECP256K1_INLINE void secp256k1_gej_double_nonzero(secp256k1_gej *r, const secp256k1_gej *a, secp256k1_fe *rzr) { + VERIFY_CHECK(!secp256k1_gej_is_infinity(a)); + secp256k1_gej_double_var(r, a, rzr); +} + +static void secp256k1_gej_add_var(secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_gej *b, secp256k1_fe *rzr) { + /* Operations: 12 mul, 4 sqr, 2 normalize, 12 mul_int/add/negate */ + secp256k1_fe z22, z12, u1, u2, s1, s2, h, i, i2, h2, h3, t; + + if (a->infinity) { + VERIFY_CHECK(rzr == NULL); + *r = *b; + return; + } + + if (b->infinity) { + if (rzr != NULL) { + secp256k1_fe_set_int(rzr, 1); + } + *r = *a; + return; + } + + r->infinity = 0; + secp256k1_fe_sqr(&z22, &b->z); + secp256k1_fe_sqr(&z12, &a->z); + secp256k1_fe_mul(&u1, &a->x, &z22); + secp256k1_fe_mul(&u2, &b->x, &z12); + secp256k1_fe_mul(&s1, &a->y, &z22); secp256k1_fe_mul(&s1, &s1, &b->z); + secp256k1_fe_mul(&s2, &b->y, &z12); secp256k1_fe_mul(&s2, &s2, &a->z); + secp256k1_fe_negate(&h, &u1, 1); secp256k1_fe_add(&h, &u2); + secp256k1_fe_negate(&i, &s1, 1); secp256k1_fe_add(&i, &s2); + if (secp256k1_fe_normalizes_to_zero_var(&h)) { + if (secp256k1_fe_normalizes_to_zero_var(&i)) { + secp256k1_gej_double_var(r, a, rzr); + } else { + if (rzr != NULL) { + secp256k1_fe_set_int(rzr, 0); + } + r->infinity = 1; + } + return; + } + secp256k1_fe_sqr(&i2, &i); + secp256k1_fe_sqr(&h2, &h); + secp256k1_fe_mul(&h3, &h, &h2); + secp256k1_fe_mul(&h, &h, &b->z); + if (rzr != NULL) { + *rzr = h; + } + secp256k1_fe_mul(&r->z, &a->z, &h); + secp256k1_fe_mul(&t, &u1, &h2); + r->x = t; secp256k1_fe_mul_int(&r->x, 2); secp256k1_fe_add(&r->x, &h3); secp256k1_fe_negate(&r->x, &r->x, 3); secp256k1_fe_add(&r->x, &i2); + secp256k1_fe_negate(&r->y, &r->x, 5); secp256k1_fe_add(&r->y, &t); secp256k1_fe_mul(&r->y, &r->y, &i); + secp256k1_fe_mul(&h3, &h3, &s1); secp256k1_fe_negate(&h3, &h3, 1); + secp256k1_fe_add(&r->y, &h3); +} + +static void secp256k1_gej_add_ge_var(secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_ge *b, secp256k1_fe *rzr) { + /* 8 mul, 3 sqr, 4 normalize, 12 mul_int/add/negate */ + secp256k1_fe z12, u1, u2, s1, s2, h, i, i2, h2, h3, t; + if (a->infinity) { + VERIFY_CHECK(rzr == NULL); + secp256k1_gej_set_ge(r, b); + return; + } + if (b->infinity) { + if (rzr != NULL) { + secp256k1_fe_set_int(rzr, 1); + } + *r = *a; + return; + } + r->infinity = 0; + + secp256k1_fe_sqr(&z12, &a->z); + u1 = a->x; secp256k1_fe_normalize_weak(&u1); + secp256k1_fe_mul(&u2, &b->x, &z12); + s1 = a->y; secp256k1_fe_normalize_weak(&s1); + secp256k1_fe_mul(&s2, &b->y, &z12); secp256k1_fe_mul(&s2, &s2, &a->z); + secp256k1_fe_negate(&h, &u1, 1); secp256k1_fe_add(&h, &u2); + secp256k1_fe_negate(&i, &s1, 1); secp256k1_fe_add(&i, &s2); + if (secp256k1_fe_normalizes_to_zero_var(&h)) { + if (secp256k1_fe_normalizes_to_zero_var(&i)) { + secp256k1_gej_double_var(r, a, rzr); + } else { + if (rzr != NULL) { + secp256k1_fe_set_int(rzr, 0); + } + r->infinity = 1; + } + return; + } + secp256k1_fe_sqr(&i2, &i); + secp256k1_fe_sqr(&h2, &h); + secp256k1_fe_mul(&h3, &h, &h2); + if (rzr != NULL) { + *rzr = h; + } + secp256k1_fe_mul(&r->z, &a->z, &h); + secp256k1_fe_mul(&t, &u1, &h2); + r->x = t; secp256k1_fe_mul_int(&r->x, 2); secp256k1_fe_add(&r->x, &h3); secp256k1_fe_negate(&r->x, &r->x, 3); secp256k1_fe_add(&r->x, &i2); + secp256k1_fe_negate(&r->y, &r->x, 5); secp256k1_fe_add(&r->y, &t); secp256k1_fe_mul(&r->y, &r->y, &i); + secp256k1_fe_mul(&h3, &h3, &s1); secp256k1_fe_negate(&h3, &h3, 1); + secp256k1_fe_add(&r->y, &h3); +} + +static void secp256k1_gej_add_zinv_var(secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_ge *b, const secp256k1_fe *bzinv) { + /* 9 mul, 3 sqr, 4 normalize, 12 mul_int/add/negate */ + secp256k1_fe az, z12, u1, u2, s1, s2, h, i, i2, h2, h3, t; + + if (b->infinity) { + *r = *a; + return; + } + if (a->infinity) { + secp256k1_fe bzinv2, bzinv3; + r->infinity = b->infinity; + secp256k1_fe_sqr(&bzinv2, bzinv); + secp256k1_fe_mul(&bzinv3, &bzinv2, bzinv); + secp256k1_fe_mul(&r->x, &b->x, &bzinv2); + secp256k1_fe_mul(&r->y, &b->y, &bzinv3); + secp256k1_fe_set_int(&r->z, 1); + return; + } + r->infinity = 0; + + /** We need to calculate (rx,ry,rz) = (ax,ay,az) + (bx,by,1/bzinv). Due to + * secp256k1's isomorphism we can multiply the Z coordinates on both sides + * by bzinv, and get: (rx,ry,rz*bzinv) = (ax,ay,az*bzinv) + (bx,by,1). + * This means that (rx,ry,rz) can be calculated as + * (ax,ay,az*bzinv) + (bx,by,1), when not applying the bzinv factor to rz. + * The variable az below holds the modified Z coordinate for a, which is used + * for the computation of rx and ry, but not for rz. + */ + secp256k1_fe_mul(&az, &a->z, bzinv); + + secp256k1_fe_sqr(&z12, &az); + u1 = a->x; secp256k1_fe_normalize_weak(&u1); + secp256k1_fe_mul(&u2, &b->x, &z12); + s1 = a->y; secp256k1_fe_normalize_weak(&s1); + secp256k1_fe_mul(&s2, &b->y, &z12); secp256k1_fe_mul(&s2, &s2, &az); + secp256k1_fe_negate(&h, &u1, 1); secp256k1_fe_add(&h, &u2); + secp256k1_fe_negate(&i, &s1, 1); secp256k1_fe_add(&i, &s2); + if (secp256k1_fe_normalizes_to_zero_var(&h)) { + if (secp256k1_fe_normalizes_to_zero_var(&i)) { + secp256k1_gej_double_var(r, a, NULL); + } else { + r->infinity = 1; + } + return; + } + secp256k1_fe_sqr(&i2, &i); + secp256k1_fe_sqr(&h2, &h); + secp256k1_fe_mul(&h3, &h, &h2); + r->z = a->z; secp256k1_fe_mul(&r->z, &r->z, &h); + secp256k1_fe_mul(&t, &u1, &h2); + r->x = t; secp256k1_fe_mul_int(&r->x, 2); secp256k1_fe_add(&r->x, &h3); secp256k1_fe_negate(&r->x, &r->x, 3); secp256k1_fe_add(&r->x, &i2); + secp256k1_fe_negate(&r->y, &r->x, 5); secp256k1_fe_add(&r->y, &t); secp256k1_fe_mul(&r->y, &r->y, &i); + secp256k1_fe_mul(&h3, &h3, &s1); secp256k1_fe_negate(&h3, &h3, 1); + secp256k1_fe_add(&r->y, &h3); +} + + +static void secp256k1_gej_add_ge(secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_ge *b) { + /* Operations: 7 mul, 5 sqr, 4 normalize, 21 mul_int/add/negate/cmov */ + static const secp256k1_fe fe_1 = SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 1); + secp256k1_fe zz, u1, u2, s1, s2, t, tt, m, n, q, rr; + secp256k1_fe m_alt, rr_alt; + int infinity, degenerate; + VERIFY_CHECK(!b->infinity); + VERIFY_CHECK(a->infinity == 0 || a->infinity == 1); + + /** In: + * Eric Brier and Marc Joye, Weierstrass Elliptic Curves and Side-Channel Attacks. + * In D. Naccache and P. Paillier, Eds., Public Key Cryptography, vol. 2274 of Lecture Notes in Computer Science, pages 335-345. Springer-Verlag, 2002. + * we find as solution for a unified addition/doubling formula: + * lambda = ((x1 + x2)^2 - x1 * x2 + a) / (y1 + y2), with a = 0 for secp256k1's curve equation. + * x3 = lambda^2 - (x1 + x2) + * 2*y3 = lambda * (x1 + x2 - 2 * x3) - (y1 + y2). + * + * Substituting x_i = Xi / Zi^2 and yi = Yi / Zi^3, for i=1,2,3, gives: + * U1 = X1*Z2^2, U2 = X2*Z1^2 + * S1 = Y1*Z2^3, S2 = Y2*Z1^3 + * Z = Z1*Z2 + * T = U1+U2 + * M = S1+S2 + * Q = T*M^2 + * R = T^2-U1*U2 + * X3 = 4*(R^2-Q) + * Y3 = 4*(R*(3*Q-2*R^2)-M^4) + * Z3 = 2*M*Z + * (Note that the paper uses xi = Xi / Zi and yi = Yi / Zi instead.) + * + * This formula has the benefit of being the same for both addition + * of distinct points and doubling. However, it breaks down in the + * case that either point is infinity, or that y1 = -y2. We handle + * these cases in the following ways: + * + * - If b is infinity we simply bail by means of a VERIFY_CHECK. + * + * - If a is infinity, we detect this, and at the end of the + * computation replace the result (which will be meaningless, + * but we compute to be constant-time) with b.x : b.y : 1. + * + * - If a = -b, we have y1 = -y2, which is a degenerate case. + * But here the answer is infinity, so we simply set the + * infinity flag of the result, overriding the computed values + * without even needing to cmov. + * + * - If y1 = -y2 but x1 != x2, which does occur thanks to certain + * properties of our curve (specifically, 1 has nontrivial cube + * roots in our field, and the curve equation has no x coefficient) + * then the answer is not infinity but also not given by the above + * equation. In this case, we cmov in place an alternate expression + * for lambda. Specifically (y1 - y2)/(x1 - x2). Where both these + * expressions for lambda are defined, they are equal, and can be + * obtained from each other by multiplication by (y1 + y2)/(y1 + y2) + * then substitution of x^3 + 7 for y^2 (using the curve equation). + * For all pairs of nonzero points (a, b) at least one is defined, + * so this covers everything. + */ + + secp256k1_fe_sqr(&zz, &a->z); /* z = Z1^2 */ + u1 = a->x; secp256k1_fe_normalize_weak(&u1); /* u1 = U1 = X1*Z2^2 (1) */ + secp256k1_fe_mul(&u2, &b->x, &zz); /* u2 = U2 = X2*Z1^2 (1) */ + s1 = a->y; secp256k1_fe_normalize_weak(&s1); /* s1 = S1 = Y1*Z2^3 (1) */ + secp256k1_fe_mul(&s2, &b->y, &zz); /* s2 = Y2*Z1^2 (1) */ + secp256k1_fe_mul(&s2, &s2, &a->z); /* s2 = S2 = Y2*Z1^3 (1) */ + t = u1; secp256k1_fe_add(&t, &u2); /* t = T = U1+U2 (2) */ + m = s1; secp256k1_fe_add(&m, &s2); /* m = M = S1+S2 (2) */ + secp256k1_fe_sqr(&rr, &t); /* rr = T^2 (1) */ + secp256k1_fe_negate(&m_alt, &u2, 1); /* Malt = -X2*Z1^2 */ + secp256k1_fe_mul(&tt, &u1, &m_alt); /* tt = -U1*U2 (2) */ + secp256k1_fe_add(&rr, &tt); /* rr = R = T^2-U1*U2 (3) */ + /** If lambda = R/M = 0/0 we have a problem (except in the "trivial" + * case that Z = z1z2 = 0, and this is special-cased later on). */ + degenerate = secp256k1_fe_normalizes_to_zero(&m) & + secp256k1_fe_normalizes_to_zero(&rr); + /* This only occurs when y1 == -y2 and x1^3 == x2^3, but x1 != x2. + * This means either x1 == beta*x2 or beta*x1 == x2, where beta is + * a nontrivial cube root of one. In either case, an alternate + * non-indeterminate expression for lambda is (y1 - y2)/(x1 - x2), + * so we set R/M equal to this. */ + rr_alt = s1; + secp256k1_fe_mul_int(&rr_alt, 2); /* rr = Y1*Z2^3 - Y2*Z1^3 (2) */ + secp256k1_fe_add(&m_alt, &u1); /* Malt = X1*Z2^2 - X2*Z1^2 */ + + secp256k1_fe_cmov(&rr_alt, &rr, !degenerate); + secp256k1_fe_cmov(&m_alt, &m, !degenerate); + /* Now Ralt / Malt = lambda and is guaranteed not to be 0/0. + * From here on out Ralt and Malt represent the numerator + * and denominator of lambda; R and M represent the explicit + * expressions x1^2 + x2^2 + x1x2 and y1 + y2. */ + secp256k1_fe_sqr(&n, &m_alt); /* n = Malt^2 (1) */ + secp256k1_fe_mul(&q, &n, &t); /* q = Q = T*Malt^2 (1) */ + /* These two lines use the observation that either M == Malt or M == 0, + * so M^3 * Malt is either Malt^4 (which is computed by squaring), or + * zero (which is "computed" by cmov). So the cost is one squaring + * versus two multiplications. */ + secp256k1_fe_sqr(&n, &n); + secp256k1_fe_cmov(&n, &m, degenerate); /* n = M^3 * Malt (2) */ + secp256k1_fe_sqr(&t, &rr_alt); /* t = Ralt^2 (1) */ + secp256k1_fe_mul(&r->z, &a->z, &m_alt); /* r->z = Malt*Z (1) */ + infinity = secp256k1_fe_normalizes_to_zero(&r->z) * (1 - a->infinity); + secp256k1_fe_mul_int(&r->z, 2); /* r->z = Z3 = 2*Malt*Z (2) */ + secp256k1_fe_negate(&q, &q, 1); /* q = -Q (2) */ + secp256k1_fe_add(&t, &q); /* t = Ralt^2-Q (3) */ + secp256k1_fe_normalize_weak(&t); + r->x = t; /* r->x = Ralt^2-Q (1) */ + secp256k1_fe_mul_int(&t, 2); /* t = 2*x3 (2) */ + secp256k1_fe_add(&t, &q); /* t = 2*x3 - Q: (4) */ + secp256k1_fe_mul(&t, &t, &rr_alt); /* t = Ralt*(2*x3 - Q) (1) */ + secp256k1_fe_add(&t, &n); /* t = Ralt*(2*x3 - Q) + M^3*Malt (3) */ + secp256k1_fe_negate(&r->y, &t, 3); /* r->y = Ralt*(Q - 2x3) - M^3*Malt (4) */ + secp256k1_fe_normalize_weak(&r->y); + secp256k1_fe_mul_int(&r->x, 4); /* r->x = X3 = 4*(Ralt^2-Q) */ + secp256k1_fe_mul_int(&r->y, 4); /* r->y = Y3 = 4*Ralt*(Q - 2x3) - 4*M^3*Malt (4) */ + + /** In case a->infinity == 1, replace r with (b->x, b->y, 1). */ + secp256k1_fe_cmov(&r->x, &b->x, a->infinity); + secp256k1_fe_cmov(&r->y, &b->y, a->infinity); + secp256k1_fe_cmov(&r->z, &fe_1, a->infinity); + r->infinity = infinity; +} + +static void secp256k1_gej_rescale(secp256k1_gej *r, const secp256k1_fe *s) { + /* Operations: 4 mul, 1 sqr */ + secp256k1_fe zz; + VERIFY_CHECK(!secp256k1_fe_is_zero(s)); + secp256k1_fe_sqr(&zz, s); + secp256k1_fe_mul(&r->x, &r->x, &zz); /* r->x *= s^2 */ + secp256k1_fe_mul(&r->y, &r->y, &zz); + secp256k1_fe_mul(&r->y, &r->y, s); /* r->y *= s^3 */ + secp256k1_fe_mul(&r->z, &r->z, s); /* r->z *= s */ +} + +static void secp256k1_ge_to_storage(secp256k1_ge_storage *r, const secp256k1_ge *a) { + secp256k1_fe x, y; + VERIFY_CHECK(!a->infinity); + x = a->x; + secp256k1_fe_normalize(&x); + y = a->y; + secp256k1_fe_normalize(&y); + secp256k1_fe_to_storage(&r->x, &x); + secp256k1_fe_to_storage(&r->y, &y); +} + +static void secp256k1_ge_from_storage(secp256k1_ge *r, const secp256k1_ge_storage *a) { + secp256k1_fe_from_storage(&r->x, &a->x); + secp256k1_fe_from_storage(&r->y, &a->y); + r->infinity = 0; +} + +static SECP256K1_INLINE void secp256k1_ge_storage_cmov(secp256k1_ge_storage *r, const secp256k1_ge_storage *a, int flag) { + secp256k1_fe_storage_cmov(&r->x, &a->x, flag); + secp256k1_fe_storage_cmov(&r->y, &a->y, flag); +} + +#ifdef USE_ENDOMORPHISM +static void secp256k1_ge_mul_lambda(secp256k1_ge *r, const secp256k1_ge *a) { + static const secp256k1_fe beta = SECP256K1_FE_CONST( + 0x7ae96a2bul, 0x657c0710ul, 0x6e64479eul, 0xac3434e9ul, + 0x9cf04975ul, 0x12f58995ul, 0xc1396c28ul, 0x719501eeul + ); + *r = *a; + secp256k1_fe_mul(&r->x, &r->x, &beta); +} +#endif + +static int secp256k1_gej_has_quad_y_var(const secp256k1_gej *a) { + secp256k1_fe yz; + + if (a->infinity) { + return 0; + } + + /* We rely on the fact that the Jacobi symbol of 1 / a->z^3 is the same as + * that of a->z. Thus a->y / a->z^3 is a quadratic residue iff a->y * a->z + is */ + secp256k1_fe_mul(&yz, &a->y, &a->z); + return secp256k1_fe_is_quad_var(&yz); +} + +#endif /* SECP256K1_GROUP_IMPL_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/hash.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/hash.h new file mode 100644 index 000000000..de26e4b89 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/hash.h @@ -0,0 +1,41 @@ +/********************************************************************** + * Copyright (c) 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_HASH_H +#define SECP256K1_HASH_H + +#include +#include + +typedef struct { + uint32_t s[8]; + uint32_t buf[16]; /* In big endian */ + size_t bytes; +} secp256k1_sha256; + +static void secp256k1_sha256_initialize(secp256k1_sha256 *hash); +static void secp256k1_sha256_write(secp256k1_sha256 *hash, const unsigned char *data, size_t size); +static void secp256k1_sha256_finalize(secp256k1_sha256 *hash, unsigned char *out32); + +typedef struct { + secp256k1_sha256 inner, outer; +} secp256k1_hmac_sha256; + +static void secp256k1_hmac_sha256_initialize(secp256k1_hmac_sha256 *hash, const unsigned char *key, size_t size); +static void secp256k1_hmac_sha256_write(secp256k1_hmac_sha256 *hash, const unsigned char *data, size_t size); +static void secp256k1_hmac_sha256_finalize(secp256k1_hmac_sha256 *hash, unsigned char *out32); + +typedef struct { + unsigned char v[32]; + unsigned char k[32]; + int retry; +} secp256k1_rfc6979_hmac_sha256; + +static void secp256k1_rfc6979_hmac_sha256_initialize(secp256k1_rfc6979_hmac_sha256 *rng, const unsigned char *key, size_t keylen); +static void secp256k1_rfc6979_hmac_sha256_generate(secp256k1_rfc6979_hmac_sha256 *rng, unsigned char *out, size_t outlen); +static void secp256k1_rfc6979_hmac_sha256_finalize(secp256k1_rfc6979_hmac_sha256 *rng); + +#endif /* SECP256K1_HASH_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/hash_impl.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/hash_impl.h new file mode 100644 index 000000000..5e015a51f --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/hash_impl.h @@ -0,0 +1,282 @@ +/********************************************************************** + * Copyright (c) 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_HASH_IMPL_H +#define SECP256K1_HASH_IMPL_H + +#include "hash.h" + +#include +#include +#include + +#define Ch(x,y,z) ((z) ^ ((x) & ((y) ^ (z)))) +#define Maj(x,y,z) (((x) & (y)) | ((z) & ((x) | (y)))) +#define Sigma0(x) (((x) >> 2 | (x) << 30) ^ ((x) >> 13 | (x) << 19) ^ ((x) >> 22 | (x) << 10)) +#define Sigma1(x) (((x) >> 6 | (x) << 26) ^ ((x) >> 11 | (x) << 21) ^ ((x) >> 25 | (x) << 7)) +#define sigma0(x) (((x) >> 7 | (x) << 25) ^ ((x) >> 18 | (x) << 14) ^ ((x) >> 3)) +#define sigma1(x) (((x) >> 17 | (x) << 15) ^ ((x) >> 19 | (x) << 13) ^ ((x) >> 10)) + +#define Round(a,b,c,d,e,f,g,h,k,w) do { \ + uint32_t t1 = (h) + Sigma1(e) + Ch((e), (f), (g)) + (k) + (w); \ + uint32_t t2 = Sigma0(a) + Maj((a), (b), (c)); \ + (d) += t1; \ + (h) = t1 + t2; \ +} while(0) + +#ifdef WORDS_BIGENDIAN +#define BE32(x) (x) +#else +#define BE32(p) ((((p) & 0xFF) << 24) | (((p) & 0xFF00) << 8) | (((p) & 0xFF0000) >> 8) | (((p) & 0xFF000000) >> 24)) +#endif + +static void secp256k1_sha256_initialize(secp256k1_sha256 *hash) { + hash->s[0] = 0x6a09e667ul; + hash->s[1] = 0xbb67ae85ul; + hash->s[2] = 0x3c6ef372ul; + hash->s[3] = 0xa54ff53aul; + hash->s[4] = 0x510e527ful; + hash->s[5] = 0x9b05688cul; + hash->s[6] = 0x1f83d9abul; + hash->s[7] = 0x5be0cd19ul; + hash->bytes = 0; +} + +/** Perform one SHA-256 transformation, processing 16 big endian 32-bit words. */ +static void secp256k1_sha256_transform(uint32_t* s, const uint32_t* chunk) { + uint32_t a = s[0], b = s[1], c = s[2], d = s[3], e = s[4], f = s[5], g = s[6], h = s[7]; + uint32_t w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15; + + Round(a, b, c, d, e, f, g, h, 0x428a2f98, w0 = BE32(chunk[0])); + Round(h, a, b, c, d, e, f, g, 0x71374491, w1 = BE32(chunk[1])); + Round(g, h, a, b, c, d, e, f, 0xb5c0fbcf, w2 = BE32(chunk[2])); + Round(f, g, h, a, b, c, d, e, 0xe9b5dba5, w3 = BE32(chunk[3])); + Round(e, f, g, h, a, b, c, d, 0x3956c25b, w4 = BE32(chunk[4])); + Round(d, e, f, g, h, a, b, c, 0x59f111f1, w5 = BE32(chunk[5])); + Round(c, d, e, f, g, h, a, b, 0x923f82a4, w6 = BE32(chunk[6])); + Round(b, c, d, e, f, g, h, a, 0xab1c5ed5, w7 = BE32(chunk[7])); + Round(a, b, c, d, e, f, g, h, 0xd807aa98, w8 = BE32(chunk[8])); + Round(h, a, b, c, d, e, f, g, 0x12835b01, w9 = BE32(chunk[9])); + Round(g, h, a, b, c, d, e, f, 0x243185be, w10 = BE32(chunk[10])); + Round(f, g, h, a, b, c, d, e, 0x550c7dc3, w11 = BE32(chunk[11])); + Round(e, f, g, h, a, b, c, d, 0x72be5d74, w12 = BE32(chunk[12])); + Round(d, e, f, g, h, a, b, c, 0x80deb1fe, w13 = BE32(chunk[13])); + Round(c, d, e, f, g, h, a, b, 0x9bdc06a7, w14 = BE32(chunk[14])); + Round(b, c, d, e, f, g, h, a, 0xc19bf174, w15 = BE32(chunk[15])); + + Round(a, b, c, d, e, f, g, h, 0xe49b69c1, w0 += sigma1(w14) + w9 + sigma0(w1)); + Round(h, a, b, c, d, e, f, g, 0xefbe4786, w1 += sigma1(w15) + w10 + sigma0(w2)); + Round(g, h, a, b, c, d, e, f, 0x0fc19dc6, w2 += sigma1(w0) + w11 + sigma0(w3)); + Round(f, g, h, a, b, c, d, e, 0x240ca1cc, w3 += sigma1(w1) + w12 + sigma0(w4)); + Round(e, f, g, h, a, b, c, d, 0x2de92c6f, w4 += sigma1(w2) + w13 + sigma0(w5)); + Round(d, e, f, g, h, a, b, c, 0x4a7484aa, w5 += sigma1(w3) + w14 + sigma0(w6)); + Round(c, d, e, f, g, h, a, b, 0x5cb0a9dc, w6 += sigma1(w4) + w15 + sigma0(w7)); + Round(b, c, d, e, f, g, h, a, 0x76f988da, w7 += sigma1(w5) + w0 + sigma0(w8)); + Round(a, b, c, d, e, f, g, h, 0x983e5152, w8 += sigma1(w6) + w1 + sigma0(w9)); + Round(h, a, b, c, d, e, f, g, 0xa831c66d, w9 += sigma1(w7) + w2 + sigma0(w10)); + Round(g, h, a, b, c, d, e, f, 0xb00327c8, w10 += sigma1(w8) + w3 + sigma0(w11)); + Round(f, g, h, a, b, c, d, e, 0xbf597fc7, w11 += sigma1(w9) + w4 + sigma0(w12)); + Round(e, f, g, h, a, b, c, d, 0xc6e00bf3, w12 += sigma1(w10) + w5 + sigma0(w13)); + Round(d, e, f, g, h, a, b, c, 0xd5a79147, w13 += sigma1(w11) + w6 + sigma0(w14)); + Round(c, d, e, f, g, h, a, b, 0x06ca6351, w14 += sigma1(w12) + w7 + sigma0(w15)); + Round(b, c, d, e, f, g, h, a, 0x14292967, w15 += sigma1(w13) + w8 + sigma0(w0)); + + Round(a, b, c, d, e, f, g, h, 0x27b70a85, w0 += sigma1(w14) + w9 + sigma0(w1)); + Round(h, a, b, c, d, e, f, g, 0x2e1b2138, w1 += sigma1(w15) + w10 + sigma0(w2)); + Round(g, h, a, b, c, d, e, f, 0x4d2c6dfc, w2 += sigma1(w0) + w11 + sigma0(w3)); + Round(f, g, h, a, b, c, d, e, 0x53380d13, w3 += sigma1(w1) + w12 + sigma0(w4)); + Round(e, f, g, h, a, b, c, d, 0x650a7354, w4 += sigma1(w2) + w13 + sigma0(w5)); + Round(d, e, f, g, h, a, b, c, 0x766a0abb, w5 += sigma1(w3) + w14 + sigma0(w6)); + Round(c, d, e, f, g, h, a, b, 0x81c2c92e, w6 += sigma1(w4) + w15 + sigma0(w7)); + Round(b, c, d, e, f, g, h, a, 0x92722c85, w7 += sigma1(w5) + w0 + sigma0(w8)); + Round(a, b, c, d, e, f, g, h, 0xa2bfe8a1, w8 += sigma1(w6) + w1 + sigma0(w9)); + Round(h, a, b, c, d, e, f, g, 0xa81a664b, w9 += sigma1(w7) + w2 + sigma0(w10)); + Round(g, h, a, b, c, d, e, f, 0xc24b8b70, w10 += sigma1(w8) + w3 + sigma0(w11)); + Round(f, g, h, a, b, c, d, e, 0xc76c51a3, w11 += sigma1(w9) + w4 + sigma0(w12)); + Round(e, f, g, h, a, b, c, d, 0xd192e819, w12 += sigma1(w10) + w5 + sigma0(w13)); + Round(d, e, f, g, h, a, b, c, 0xd6990624, w13 += sigma1(w11) + w6 + sigma0(w14)); + Round(c, d, e, f, g, h, a, b, 0xf40e3585, w14 += sigma1(w12) + w7 + sigma0(w15)); + Round(b, c, d, e, f, g, h, a, 0x106aa070, w15 += sigma1(w13) + w8 + sigma0(w0)); + + Round(a, b, c, d, e, f, g, h, 0x19a4c116, w0 += sigma1(w14) + w9 + sigma0(w1)); + Round(h, a, b, c, d, e, f, g, 0x1e376c08, w1 += sigma1(w15) + w10 + sigma0(w2)); + Round(g, h, a, b, c, d, e, f, 0x2748774c, w2 += sigma1(w0) + w11 + sigma0(w3)); + Round(f, g, h, a, b, c, d, e, 0x34b0bcb5, w3 += sigma1(w1) + w12 + sigma0(w4)); + Round(e, f, g, h, a, b, c, d, 0x391c0cb3, w4 += sigma1(w2) + w13 + sigma0(w5)); + Round(d, e, f, g, h, a, b, c, 0x4ed8aa4a, w5 += sigma1(w3) + w14 + sigma0(w6)); + Round(c, d, e, f, g, h, a, b, 0x5b9cca4f, w6 += sigma1(w4) + w15 + sigma0(w7)); + Round(b, c, d, e, f, g, h, a, 0x682e6ff3, w7 += sigma1(w5) + w0 + sigma0(w8)); + Round(a, b, c, d, e, f, g, h, 0x748f82ee, w8 += sigma1(w6) + w1 + sigma0(w9)); + Round(h, a, b, c, d, e, f, g, 0x78a5636f, w9 += sigma1(w7) + w2 + sigma0(w10)); + Round(g, h, a, b, c, d, e, f, 0x84c87814, w10 += sigma1(w8) + w3 + sigma0(w11)); + Round(f, g, h, a, b, c, d, e, 0x8cc70208, w11 += sigma1(w9) + w4 + sigma0(w12)); + Round(e, f, g, h, a, b, c, d, 0x90befffa, w12 += sigma1(w10) + w5 + sigma0(w13)); + Round(d, e, f, g, h, a, b, c, 0xa4506ceb, w13 += sigma1(w11) + w6 + sigma0(w14)); + Round(c, d, e, f, g, h, a, b, 0xbef9a3f7, w14 + sigma1(w12) + w7 + sigma0(w15)); + Round(b, c, d, e, f, g, h, a, 0xc67178f2, w15 + sigma1(w13) + w8 + sigma0(w0)); + + s[0] += a; + s[1] += b; + s[2] += c; + s[3] += d; + s[4] += e; + s[5] += f; + s[6] += g; + s[7] += h; +} + +static void secp256k1_sha256_write(secp256k1_sha256 *hash, const unsigned char *data, size_t len) { + size_t bufsize = hash->bytes & 0x3F; + hash->bytes += len; + while (bufsize + len >= 64) { + /* Fill the buffer, and process it. */ + size_t chunk_len = 64 - bufsize; + memcpy(((unsigned char*)hash->buf) + bufsize, data, chunk_len); + data += chunk_len; + len -= chunk_len; + secp256k1_sha256_transform(hash->s, hash->buf); + bufsize = 0; + } + if (len) { + /* Fill the buffer with what remains. */ + memcpy(((unsigned char*)hash->buf) + bufsize, data, len); + } +} + +static void secp256k1_sha256_finalize(secp256k1_sha256 *hash, unsigned char *out32) { + static const unsigned char pad[64] = {0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + uint32_t sizedesc[2]; + uint32_t out[8]; + int i = 0; + sizedesc[0] = BE32((uint32_t)hash->bytes >> 29); + sizedesc[1] = BE32((uint32_t)hash->bytes << 3); + secp256k1_sha256_write(hash, pad, 1 + ((119 - (hash->bytes % 64)) % 64)); + secp256k1_sha256_write(hash, (const unsigned char*)sizedesc, 8); + for (i = 0; i < 8; i++) { + out[i] = BE32(hash->s[i]); + hash->s[i] = 0; + } + memcpy(out32, (const unsigned char*)out, 32); +} + +static void secp256k1_hmac_sha256_initialize(secp256k1_hmac_sha256 *hash, const unsigned char *key, size_t keylen) { + size_t n; + unsigned char rkey[64]; + if (keylen <= sizeof(rkey)) { + memcpy(rkey, key, keylen); + memset(rkey + keylen, 0, sizeof(rkey) - keylen); + } else { + secp256k1_sha256 sha256; + secp256k1_sha256_initialize(&sha256); + secp256k1_sha256_write(&sha256, key, keylen); + secp256k1_sha256_finalize(&sha256, rkey); + memset(rkey + 32, 0, 32); + } + + secp256k1_sha256_initialize(&hash->outer); + for (n = 0; n < sizeof(rkey); n++) { + rkey[n] ^= 0x5c; + } + secp256k1_sha256_write(&hash->outer, rkey, sizeof(rkey)); + + secp256k1_sha256_initialize(&hash->inner); + for (n = 0; n < sizeof(rkey); n++) { + rkey[n] ^= 0x5c ^ 0x36; + } + secp256k1_sha256_write(&hash->inner, rkey, sizeof(rkey)); + memset(rkey, 0, sizeof(rkey)); +} + +static void secp256k1_hmac_sha256_write(secp256k1_hmac_sha256 *hash, const unsigned char *data, size_t size) { + secp256k1_sha256_write(&hash->inner, data, size); +} + +static void secp256k1_hmac_sha256_finalize(secp256k1_hmac_sha256 *hash, unsigned char *out32) { + unsigned char temp[32]; + secp256k1_sha256_finalize(&hash->inner, temp); + secp256k1_sha256_write(&hash->outer, temp, 32); + memset(temp, 0, 32); + secp256k1_sha256_finalize(&hash->outer, out32); +} + + +static void secp256k1_rfc6979_hmac_sha256_initialize(secp256k1_rfc6979_hmac_sha256 *rng, const unsigned char *key, size_t keylen) { + secp256k1_hmac_sha256 hmac; + static const unsigned char zero[1] = {0x00}; + static const unsigned char one[1] = {0x01}; + + memset(rng->v, 0x01, 32); /* RFC6979 3.2.b. */ + memset(rng->k, 0x00, 32); /* RFC6979 3.2.c. */ + + /* RFC6979 3.2.d. */ + secp256k1_hmac_sha256_initialize(&hmac, rng->k, 32); + secp256k1_hmac_sha256_write(&hmac, rng->v, 32); + secp256k1_hmac_sha256_write(&hmac, zero, 1); + secp256k1_hmac_sha256_write(&hmac, key, keylen); + secp256k1_hmac_sha256_finalize(&hmac, rng->k); + secp256k1_hmac_sha256_initialize(&hmac, rng->k, 32); + secp256k1_hmac_sha256_write(&hmac, rng->v, 32); + secp256k1_hmac_sha256_finalize(&hmac, rng->v); + + /* RFC6979 3.2.f. */ + secp256k1_hmac_sha256_initialize(&hmac, rng->k, 32); + secp256k1_hmac_sha256_write(&hmac, rng->v, 32); + secp256k1_hmac_sha256_write(&hmac, one, 1); + secp256k1_hmac_sha256_write(&hmac, key, keylen); + secp256k1_hmac_sha256_finalize(&hmac, rng->k); + secp256k1_hmac_sha256_initialize(&hmac, rng->k, 32); + secp256k1_hmac_sha256_write(&hmac, rng->v, 32); + secp256k1_hmac_sha256_finalize(&hmac, rng->v); + rng->retry = 0; +} + +static void secp256k1_rfc6979_hmac_sha256_generate(secp256k1_rfc6979_hmac_sha256 *rng, unsigned char *out, size_t outlen) { + /* RFC6979 3.2.h. */ + static const unsigned char zero[1] = {0x00}; + if (rng->retry) { + secp256k1_hmac_sha256 hmac; + secp256k1_hmac_sha256_initialize(&hmac, rng->k, 32); + secp256k1_hmac_sha256_write(&hmac, rng->v, 32); + secp256k1_hmac_sha256_write(&hmac, zero, 1); + secp256k1_hmac_sha256_finalize(&hmac, rng->k); + secp256k1_hmac_sha256_initialize(&hmac, rng->k, 32); + secp256k1_hmac_sha256_write(&hmac, rng->v, 32); + secp256k1_hmac_sha256_finalize(&hmac, rng->v); + } + + while (outlen > 0) { + secp256k1_hmac_sha256 hmac; + int now = (int)outlen; + secp256k1_hmac_sha256_initialize(&hmac, rng->k, 32); + secp256k1_hmac_sha256_write(&hmac, rng->v, 32); + secp256k1_hmac_sha256_finalize(&hmac, rng->v); + if (now > 32) { + now = 32; + } + memcpy(out, rng->v, now); + out += now; + outlen -= now; + } + + rng->retry = 1; +} + +static void secp256k1_rfc6979_hmac_sha256_finalize(secp256k1_rfc6979_hmac_sha256 *rng) { + memset(rng->k, 0, 32); + memset(rng->v, 0, 32); + rng->retry = 0; +} + +#undef BE32 +#undef Round +#undef sigma1 +#undef sigma0 +#undef Sigma1 +#undef Sigma0 +#undef Maj +#undef Ch + +#endif /* SECP256K1_HASH_IMPL_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/include/secp256k1.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/include/secp256k1.h new file mode 100644 index 000000000..ea2bc0155 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/include/secp256k1.h @@ -0,0 +1,767 @@ +#ifndef SECP256K1_H +#define SECP256K1_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/* These rules specify the order of arguments in API calls: + * + * 1. Context pointers go first, followed by output arguments, combined + * output/input arguments, and finally input-only arguments. + * 2. Array lengths always immediately the follow the argument whose length + * they describe, even if this violates rule 1. + * 3. Within the OUT/OUTIN/IN groups, pointers to data that is typically generated + * later go first. This means: signatures, public nonces, private nonces, + * messages, public keys, secret keys, tweaks. + * 4. Arguments that are not data pointers go last, from more complex to less + * complex: function pointers, algorithm names, messages, void pointers, + * counts, flags, booleans. + * 5. Opaque data pointers follow the function pointer they are to be passed to. + */ + +/** Opaque data structure that holds context information (precomputed tables etc.). + * + * The purpose of context structures is to cache large precomputed data tables + * that are expensive to construct, and also to maintain the randomization data + * for blinding. + * + * Do not create a new context object for each operation, as construction is + * far slower than all other API calls (~100 times slower than an ECDSA + * verification). + * + * A constructed context can safely be used from multiple threads + * simultaneously, but API call that take a non-const pointer to a context + * need exclusive access to it. In particular this is the case for + * secp256k1_context_destroy and secp256k1_context_randomize. + * + * Regarding randomization, either do it once at creation time (in which case + * you do not need any locking for the other calls), or use a read-write lock. + */ +typedef struct secp256k1_context_struct secp256k1_context; + +/** Opaque data structure that holds rewriteable "scratch space" + * + * The purpose of this structure is to replace dynamic memory allocations, + * because we target architectures where this may not be available. It is + * essentially a resizable (within specified parameters) block of bytes, + * which is initially created either by memory allocation or TODO as a pointer + * into some fixed rewritable space. + * + * Unlike the context object, this cannot safely be shared between threads + * without additional synchronization logic. + */ +typedef struct secp256k1_scratch_space_struct secp256k1_scratch_space; + +/** Opaque data structure that holds a parsed and valid public key. + * + * The exact representation of data inside is implementation defined and not + * guaranteed to be portable between different platforms or versions. It is + * however guaranteed to be 64 bytes in size, and can be safely copied/moved. + * If you need to convert to a format suitable for storage, transmission, or + * comparison, use secp256k1_ec_pubkey_serialize and secp256k1_ec_pubkey_parse. + */ +typedef struct { + unsigned char data[64]; +} secp256k1_pubkey; + +/** Opaque data structured that holds a parsed ECDSA signature. + * + * The exact representation of data inside is implementation defined and not + * guaranteed to be portable between different platforms or versions. It is + * however guaranteed to be 64 bytes in size, and can be safely copied/moved. + * If you need to convert to a format suitable for storage, transmission, or + * comparison, use the secp256k1_ecdsa_signature_serialize_* and + * secp256k1_ecdsa_signature_parse_* functions. + */ +typedef struct { + unsigned char data[64]; +} secp256k1_ecdsa_signature; + +/** A pointer to a function to deterministically generate a nonce. + * + * Returns: 1 if a nonce was successfully generated. 0 will cause signing to fail. + * Out: nonce32: pointer to a 32-byte array to be filled by the function. + * In: msg32: the 32-byte message hash being verified (will not be NULL) + * key32: pointer to a 32-byte secret key (will not be NULL) + * algo16: pointer to a 16-byte array describing the signature + * algorithm (will be NULL for ECDSA for compatibility). + * data: Arbitrary data pointer that is passed through. + * attempt: how many iterations we have tried to find a nonce. + * This will almost always be 0, but different attempt values + * are required to result in a different nonce. + * + * Except for test cases, this function should compute some cryptographic hash of + * the message, the algorithm, the key and the attempt. + */ +typedef int (*secp256k1_nonce_function)( + unsigned char *nonce32, + const unsigned char *msg32, + const unsigned char *key32, + const unsigned char *algo16, + void *data, + unsigned int attempt +); + +# if !defined(SECP256K1_GNUC_PREREQ) +# if defined(__GNUC__)&&defined(__GNUC_MINOR__) +# define SECP256K1_GNUC_PREREQ(_maj,_min) \ + ((__GNUC__<<16)+__GNUC_MINOR__>=((_maj)<<16)+(_min)) +# else +# define SECP256K1_GNUC_PREREQ(_maj,_min) 0 +# endif +# endif + +# if (!defined(__STDC_VERSION__) || (__STDC_VERSION__ < 199901L) ) +# if SECP256K1_GNUC_PREREQ(2,7) +# define SECP256K1_INLINE __inline__ +# elif (defined(_MSC_VER)) +# define SECP256K1_INLINE __inline +# else +# define SECP256K1_INLINE +# endif +# else +# define SECP256K1_INLINE inline +# endif + +#ifndef SECP256K1_API +# if defined(_WIN32) +# ifdef SECP256K1_BUILD +# define SECP256K1_API __declspec(dllexport) +# else +# define SECP256K1_API +# endif +# elif defined(__GNUC__) && defined(SECP256K1_BUILD) +# define SECP256K1_API __attribute__ ((visibility ("default"))) +# else +# define SECP256K1_API +# endif +#endif + +/**Warning attributes + * NONNULL is not used if SECP256K1_BUILD is set to avoid the compiler optimizing out + * some paranoid null checks. */ +# if defined(__GNUC__) && SECP256K1_GNUC_PREREQ(3, 4) +# define SECP256K1_WARN_UNUSED_RESULT __attribute__ ((__warn_unused_result__)) +# else +# define SECP256K1_WARN_UNUSED_RESULT +# endif +# if !defined(SECP256K1_BUILD) && defined(__GNUC__) && SECP256K1_GNUC_PREREQ(3, 4) +# define SECP256K1_ARG_NONNULL(_x) __attribute__ ((__nonnull__(_x))) +# else +# define SECP256K1_ARG_NONNULL(_x) +# endif + +/** All flags' lower 8 bits indicate what they're for. Do not use directly. */ +#define SECP256K1_FLAGS_TYPE_MASK ((1 << 8) - 1) +#define SECP256K1_FLAGS_TYPE_CONTEXT (1 << 0) +#define SECP256K1_FLAGS_TYPE_COMPRESSION (1 << 1) +/** The higher bits contain the actual data. Do not use directly. */ +#define SECP256K1_FLAGS_BIT_CONTEXT_VERIFY (1 << 8) +#define SECP256K1_FLAGS_BIT_CONTEXT_SIGN (1 << 9) +#define SECP256K1_FLAGS_BIT_COMPRESSION (1 << 8) + +/** Flags to pass to secp256k1_context_create. */ +#define SECP256K1_CONTEXT_VERIFY (SECP256K1_FLAGS_TYPE_CONTEXT | SECP256K1_FLAGS_BIT_CONTEXT_VERIFY) +#define SECP256K1_CONTEXT_SIGN (SECP256K1_FLAGS_TYPE_CONTEXT | SECP256K1_FLAGS_BIT_CONTEXT_SIGN) +#define SECP256K1_CONTEXT_NONE (SECP256K1_FLAGS_TYPE_CONTEXT) + +/** Flag to pass to secp256k1_ec_pubkey_serialize and secp256k1_ec_privkey_export. */ +#define SECP256K1_EC_COMPRESSED (SECP256K1_FLAGS_TYPE_COMPRESSION | SECP256K1_FLAGS_BIT_COMPRESSION) +#define SECP256K1_EC_UNCOMPRESSED (SECP256K1_FLAGS_TYPE_COMPRESSION) + +/** Prefix byte used to tag various encoded curvepoints for specific purposes */ +#define SECP256K1_TAG_PUBKEY_EVEN 0x02 +#define SECP256K1_TAG_PUBKEY_ODD 0x03 +#define SECP256K1_TAG_PUBKEY_UNCOMPRESSED 0x04 +#define SECP256K1_TAG_PUBKEY_HYBRID_EVEN 0x06 +#define SECP256K1_TAG_PUBKEY_HYBRID_ODD 0x07 + +/** Create a secp256k1 context object. + * + * Returns: a newly created context object. + * In: flags: which parts of the context to initialize. + * + * See also secp256k1_context_randomize. + */ +SECP256K1_API secp256k1_context* secp256k1_context_create( + unsigned int flags +) SECP256K1_WARN_UNUSED_RESULT; + +/** Copies a secp256k1 context object. + * + * Returns: a newly created context object. + * Args: ctx: an existing context to copy (cannot be NULL) + */ +SECP256K1_API secp256k1_context* secp256k1_context_clone( + const secp256k1_context* ctx +) SECP256K1_ARG_NONNULL(1) SECP256K1_WARN_UNUSED_RESULT; + +/** Destroy a secp256k1 context object. + * + * The context pointer may not be used afterwards. + * Args: ctx: an existing context to destroy (cannot be NULL) + */ +SECP256K1_API void secp256k1_context_destroy( + secp256k1_context* ctx +); + +/** Set a callback function to be called when an illegal argument is passed to + * an API call. It will only trigger for violations that are mentioned + * explicitly in the header. + * + * The philosophy is that these shouldn't be dealt with through a + * specific return value, as calling code should not have branches to deal with + * the case that this code itself is broken. + * + * On the other hand, during debug stage, one would want to be informed about + * such mistakes, and the default (crashing) may be inadvisable. + * When this callback is triggered, the API function called is guaranteed not + * to cause a crash, though its return value and output arguments are + * undefined. + * + * Args: ctx: an existing context object (cannot be NULL) + * In: fun: a pointer to a function to call when an illegal argument is + * passed to the API, taking a message and an opaque pointer + * (NULL restores a default handler that calls abort). + * data: the opaque pointer to pass to fun above. + */ +SECP256K1_API void secp256k1_context_set_illegal_callback( + secp256k1_context* ctx, + void (*fun)(const char* message, void* data), + const void* data +) SECP256K1_ARG_NONNULL(1); + +/** Set a callback function to be called when an internal consistency check + * fails. The default is crashing. + * + * This can only trigger in case of a hardware failure, miscompilation, + * memory corruption, serious bug in the library, or other error would can + * otherwise result in undefined behaviour. It will not trigger due to mere + * incorrect usage of the API (see secp256k1_context_set_illegal_callback + * for that). After this callback returns, anything may happen, including + * crashing. + * + * Args: ctx: an existing context object (cannot be NULL) + * In: fun: a pointer to a function to call when an internal error occurs, + * taking a message and an opaque pointer (NULL restores a default + * handler that calls abort). + * data: the opaque pointer to pass to fun above. + */ +SECP256K1_API void secp256k1_context_set_error_callback( + secp256k1_context* ctx, + void (*fun)(const char* message, void* data), + const void* data +) SECP256K1_ARG_NONNULL(1); + +/** Create a secp256k1 scratch space object. + * + * Returns: a newly created scratch space. + * Args: ctx: an existing context object (cannot be NULL) + * In: max_size: maximum amount of memory to allocate + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT secp256k1_scratch_space* secp256k1_scratch_space_create( + const secp256k1_context* ctx, + size_t max_size +) SECP256K1_ARG_NONNULL(1); + +/** Destroy a secp256k1 scratch space. + * + * The pointer may not be used afterwards. + * Args: scratch: space to destroy + */ +SECP256K1_API void secp256k1_scratch_space_destroy( + secp256k1_scratch_space* scratch +); + +/** Parse a variable-length public key into the pubkey object. + * + * Returns: 1 if the public key was fully valid. + * 0 if the public key could not be parsed or is invalid. + * Args: ctx: a secp256k1 context object. + * Out: pubkey: pointer to a pubkey object. If 1 is returned, it is set to a + * parsed version of input. If not, its value is undefined. + * In: input: pointer to a serialized public key + * inputlen: length of the array pointed to by input + * + * This function supports parsing compressed (33 bytes, header byte 0x02 or + * 0x03), uncompressed (65 bytes, header byte 0x04), or hybrid (65 bytes, header + * byte 0x06 or 0x07) format public keys. + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_parse( + const secp256k1_context* ctx, + secp256k1_pubkey* pubkey, + const unsigned char *input, + size_t inputlen +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Serialize a pubkey object into a serialized byte sequence. + * + * Returns: 1 always. + * Args: ctx: a secp256k1 context object. + * Out: output: a pointer to a 65-byte (if compressed==0) or 33-byte (if + * compressed==1) byte array to place the serialized key + * in. + * In/Out: outputlen: a pointer to an integer which is initially set to the + * size of output, and is overwritten with the written + * size. + * In: pubkey: a pointer to a secp256k1_pubkey containing an + * initialized public key. + * flags: SECP256K1_EC_COMPRESSED if serialization should be in + * compressed format, otherwise SECP256K1_EC_UNCOMPRESSED. + */ +SECP256K1_API int secp256k1_ec_pubkey_serialize( + const secp256k1_context* ctx, + unsigned char *output, + size_t *outputlen, + const secp256k1_pubkey* pubkey, + unsigned int flags +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + +/** Parse an ECDSA signature in compact (64 bytes) format. + * + * Returns: 1 when the signature could be parsed, 0 otherwise. + * Args: ctx: a secp256k1 context object + * Out: sig: a pointer to a signature object + * In: input64: a pointer to the 64-byte array to parse + * + * The signature must consist of a 32-byte big endian R value, followed by a + * 32-byte big endian S value. If R or S fall outside of [0..order-1], the + * encoding is invalid. R and S with value 0 are allowed in the encoding. + * + * After the call, sig will always be initialized. If parsing failed or R or + * S are zero, the resulting sig value is guaranteed to fail validation for any + * message and public key. + */ +SECP256K1_API int secp256k1_ecdsa_signature_parse_compact( + const secp256k1_context* ctx, + secp256k1_ecdsa_signature* sig, + const unsigned char *input64 +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Parse a DER ECDSA signature. + * + * Returns: 1 when the signature could be parsed, 0 otherwise. + * Args: ctx: a secp256k1 context object + * Out: sig: a pointer to a signature object + * In: input: a pointer to the signature to be parsed + * inputlen: the length of the array pointed to be input + * + * This function will accept any valid DER encoded signature, even if the + * encoded numbers are out of range. + * + * After the call, sig will always be initialized. If parsing failed or the + * encoded numbers are out of range, signature validation with it is + * guaranteed to fail for every message and public key. + */ +SECP256K1_API int secp256k1_ecdsa_signature_parse_der( + const secp256k1_context* ctx, + secp256k1_ecdsa_signature* sig, + const unsigned char *input, + size_t inputlen +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Serialize an ECDSA signature in DER format. + * + * Returns: 1 if enough space was available to serialize, 0 otherwise + * Args: ctx: a secp256k1 context object + * Out: output: a pointer to an array to store the DER serialization + * In/Out: outputlen: a pointer to a length integer. Initially, this integer + * should be set to the length of output. After the call + * it will be set to the length of the serialization (even + * if 0 was returned). + * In: sig: a pointer to an initialized signature object + */ +SECP256K1_API int secp256k1_ecdsa_signature_serialize_der( + const secp256k1_context* ctx, + unsigned char *output, + size_t *outputlen, + const secp256k1_ecdsa_signature* sig +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + +/** Serialize an ECDSA signature in compact (64 byte) format. + * + * Returns: 1 + * Args: ctx: a secp256k1 context object + * Out: output64: a pointer to a 64-byte array to store the compact serialization + * In: sig: a pointer to an initialized signature object + * + * See secp256k1_ecdsa_signature_parse_compact for details about the encoding. + */ +SECP256K1_API int secp256k1_ecdsa_signature_serialize_compact( + const secp256k1_context* ctx, + unsigned char *output64, + const secp256k1_ecdsa_signature* sig +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Verify an ECDSA signature. + * + * Returns: 1: correct signature + * 0: incorrect or unparseable signature + * Args: ctx: a secp256k1 context object, initialized for verification. + * In: sig: the signature being verified (cannot be NULL) + * msg32: the 32-byte message hash being verified (cannot be NULL) + * pubkey: pointer to an initialized public key to verify with (cannot be NULL) + * + * To avoid accepting malleable signatures, only ECDSA signatures in lower-S + * form are accepted. + * + * If you need to accept ECDSA signatures from sources that do not obey this + * rule, apply secp256k1_ecdsa_signature_normalize to the signature prior to + * validation, but be aware that doing so results in malleable signatures. + * + * For details, see the comments for that function. + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ecdsa_verify( + const secp256k1_context* ctx, + const secp256k1_ecdsa_signature *sig, + const unsigned char *msg32, + const secp256k1_pubkey *pubkey +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + +/** Convert a signature to a normalized lower-S form. + * + * Returns: 1 if sigin was not normalized, 0 if it already was. + * Args: ctx: a secp256k1 context object + * Out: sigout: a pointer to a signature to fill with the normalized form, + * or copy if the input was already normalized. (can be NULL if + * you're only interested in whether the input was already + * normalized). + * In: sigin: a pointer to a signature to check/normalize (cannot be NULL, + * can be identical to sigout) + * + * With ECDSA a third-party can forge a second distinct signature of the same + * message, given a single initial signature, but without knowing the key. This + * is done by negating the S value modulo the order of the curve, 'flipping' + * the sign of the random point R which is not included in the signature. + * + * Forgery of the same message isn't universally problematic, but in systems + * where message malleability or uniqueness of signatures is important this can + * cause issues. This forgery can be blocked by all verifiers forcing signers + * to use a normalized form. + * + * The lower-S form reduces the size of signatures slightly on average when + * variable length encodings (such as DER) are used and is cheap to verify, + * making it a good choice. Security of always using lower-S is assured because + * anyone can trivially modify a signature after the fact to enforce this + * property anyway. + * + * The lower S value is always between 0x1 and + * 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, + * inclusive. + * + * No other forms of ECDSA malleability are known and none seem likely, but + * there is no formal proof that ECDSA, even with this additional restriction, + * is free of other malleability. Commonly used serialization schemes will also + * accept various non-unique encodings, so care should be taken when this + * property is required for an application. + * + * The secp256k1_ecdsa_sign function will by default create signatures in the + * lower-S form, and secp256k1_ecdsa_verify will not accept others. In case + * signatures come from a system that cannot enforce this property, + * secp256k1_ecdsa_signature_normalize must be called before verification. + */ +SECP256K1_API int secp256k1_ecdsa_signature_normalize( + const secp256k1_context* ctx, + secp256k1_ecdsa_signature *sigout, + const secp256k1_ecdsa_signature *sigin +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(3); + +/** An implementation of RFC6979 (using HMAC-SHA256) as nonce generation function. + * If a data pointer is passed, it is assumed to be a pointer to 32 bytes of + * extra entropy. + */ +SECP256K1_API extern const secp256k1_nonce_function secp256k1_nonce_function_rfc6979; + +/** A default safe nonce generation function (currently equal to secp256k1_nonce_function_rfc6979). */ +SECP256K1_API extern const secp256k1_nonce_function secp256k1_nonce_function_default; + +/** Create an ECDSA signature. + * + * Returns: 1: signature created + * 0: the nonce generation function failed, or the private key was invalid. + * Args: ctx: pointer to a context object, initialized for signing (cannot be NULL) + * Out: sig: pointer to an array where the signature will be placed (cannot be NULL) + * In: msg32: the 32-byte message hash being signed (cannot be NULL) + * seckey: pointer to a 32-byte secret key (cannot be NULL) + * noncefp:pointer to a nonce generation function. If NULL, secp256k1_nonce_function_default is used + * ndata: pointer to arbitrary data used by the nonce generation function (can be NULL) + * + * The created signature is always in lower-S form. See + * secp256k1_ecdsa_signature_normalize for more details. + */ +SECP256K1_API int secp256k1_ecdsa_sign( + const secp256k1_context* ctx, + secp256k1_ecdsa_signature *sig, + const unsigned char *msg32, + const unsigned char *seckey, + secp256k1_nonce_function noncefp, + const void *ndata +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + +/** Verify an ECDSA secret key. + * + * Returns: 1: secret key is valid + * 0: secret key is invalid + * Args: ctx: pointer to a context object (cannot be NULL) + * In: seckey: pointer to a 32-byte secret key (cannot be NULL) + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_seckey_verify( + const secp256k1_context* ctx, + const unsigned char *seckey +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2); + +/** Compute the public key for a secret key. + * + * Returns: 1: secret was valid, public key stores + * 0: secret was invalid, try again + * Args: ctx: pointer to a context object, initialized for signing (cannot be NULL) + * Out: pubkey: pointer to the created public key (cannot be NULL) + * In: seckey: pointer to a 32-byte private key (cannot be NULL) + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_create( + const secp256k1_context* ctx, + secp256k1_pubkey *pubkey, + const unsigned char *seckey +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Negates a private key in place. + * + * Returns: 1 always + * Args: ctx: pointer to a context object + * In/Out: seckey: pointer to the 32-byte private key to be negated (cannot be NULL) + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_privkey_negate( + const secp256k1_context* ctx, + unsigned char *seckey +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2); + +/** Negates a public key in place. + * + * Returns: 1 always + * Args: ctx: pointer to a context object + * In/Out: pubkey: pointer to the public key to be negated (cannot be NULL) + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_negate( + const secp256k1_context* ctx, + secp256k1_pubkey *pubkey +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2); + +/** Tweak a private key by adding tweak to it. + * Returns: 0 if the tweak was out of range (chance of around 1 in 2^128 for + * uniformly random 32-byte arrays, or if the resulting private key + * would be invalid (only when the tweak is the complement of the + * private key). 1 otherwise. + * Args: ctx: pointer to a context object (cannot be NULL). + * In/Out: seckey: pointer to a 32-byte private key. + * In: tweak: pointer to a 32-byte tweak. + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_privkey_tweak_add( + const secp256k1_context* ctx, + unsigned char *seckey, + const unsigned char *tweak +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Tweak a public key by adding tweak times the generator to it. + * Returns: 0 if the tweak was out of range (chance of around 1 in 2^128 for + * uniformly random 32-byte arrays, or if the resulting public key + * would be invalid (only when the tweak is the complement of the + * corresponding private key). 1 otherwise. + * Args: ctx: pointer to a context object initialized for validation + * (cannot be NULL). + * In/Out: pubkey: pointer to a public key object. + * In: tweak: pointer to a 32-byte tweak. + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_tweak_add( + const secp256k1_context* ctx, + secp256k1_pubkey *pubkey, + const unsigned char *tweak +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Tweak a private key by multiplying it by a tweak. + * Returns: 0 if the tweak was out of range (chance of around 1 in 2^128 for + * uniformly random 32-byte arrays, or equal to zero. 1 otherwise. + * Args: ctx: pointer to a context object (cannot be NULL). + * In/Out: seckey: pointer to a 32-byte private key. + * In: tweak: pointer to a 32-byte tweak. + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_privkey_tweak_mul( + const secp256k1_context* ctx, + unsigned char *seckey, + const unsigned char *tweak +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Tweak a public key by multiplying it by a tweak value. + * Returns: 0 if the tweak was out of range (chance of around 1 in 2^128 for + * uniformly random 32-byte arrays, or equal to zero. 1 otherwise. + * Args: ctx: pointer to a context object initialized for validation + * (cannot be NULL). + * In/Out: pubkey: pointer to a public key obkect. + * In: tweak: pointer to a 32-byte tweak. + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_tweak_mul( + const secp256k1_context* ctx, + secp256k1_pubkey *pubkey, + const unsigned char *tweak +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Updates the context randomization to protect against side-channel leakage. + * Returns: 1: randomization successfully updated + * 0: error + * Args: ctx: pointer to a context object (cannot be NULL) + * In: seed32: pointer to a 32-byte random seed (NULL resets to initial state) + * + * While secp256k1 code is written to be constant-time no matter what secret + * values are, it's possible that a future compiler may output code which isn't, + * and also that the CPU may not emit the same radio frequencies or draw the same + * amount power for all values. + * + * This function provides a seed which is combined into the blinding value: that + * blinding value is added before each multiplication (and removed afterwards) so + * that it does not affect function results, but shields against attacks which + * rely on any input-dependent behaviour. + * + * You should call this after secp256k1_context_create or + * secp256k1_context_clone, and may call this repeatedly afterwards. + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_context_randomize( + secp256k1_context* ctx, + const unsigned char *seed32 +) SECP256K1_ARG_NONNULL(1); + +/** Add a number of public keys together. + * Returns: 1: the sum of the public keys is valid. + * 0: the sum of the public keys is not valid. + * Args: ctx: pointer to a context object + * Out: out: pointer to a public key object for placing the resulting public key + * (cannot be NULL) + * In: ins: pointer to array of pointers to public keys (cannot be NULL) + * n: the number of public keys to add together (must be at least 1) + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_combine( + const secp256k1_context* ctx, + secp256k1_pubkey *out, + 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. + * + * The exact representation of data inside is implementation defined and not + * guaranteed to be portable between different platforms or versions. It is + * however guaranteed to be 65 bytes in size, and can be safely copied/moved. + * If you need to convert to a format suitable for storage or transmission, use + * the secp256k1_ecdsa_signature_serialize_* and + * secp256k1_ecdsa_signature_parse_* functions. + * + * Furthermore, it is guaranteed that identical signatures (including their + * recoverability) will have identical representation, so they can be + * memcmp'ed. + */ + 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 + * Args: ctx: a secp256k1 context object + * Out: sig: a pointer to a signature object + * In: input64: a pointer to a 64-byte compact signature + * recid: the recovery id (0, 1, 2 or 3) + */ + SECP256K1_API int secp256k1_ecdsa_recoverable_signature_parse_compact( + const secp256k1_context* ctx, + secp256k1_ecdsa_recoverable_signature* sig, + 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 + * Out: sig: a pointer to a normal signature (cannot be NULL). + * In: sigin: a pointer to a recoverable signature (cannot be NULL). + */ + SECP256K1_API int secp256k1_ecdsa_recoverable_signature_convert( + const secp256k1_context* ctx, + 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 + * Args: ctx: a secp256k1 context object + * Out: output64: a pointer to a 64-byte array of the compact signature (cannot be NULL) + * recid: a pointer to an integer to hold the recovery id (can be NULL). + * In: sig: a pointer to an initialized signature object (cannot be NULL) + */ + SECP256K1_API int secp256k1_ecdsa_recoverable_signature_serialize_compact( + const secp256k1_context* ctx, + unsigned char *output64, + 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 + * 0: the nonce generation function failed, or the private key was invalid. + * Args: ctx: pointer to a context object, initialized for signing (cannot be NULL) + * Out: sig: pointer to an array where the signature will be placed (cannot be NULL) + * In: msg32: the 32-byte message hash being signed (cannot be NULL) + * seckey: pointer to a 32-byte secret key (cannot be NULL) + * noncefp:pointer to a nonce generation function. If NULL, secp256k1_nonce_function_default is used + * ndata: pointer to arbitrary data used by the nonce generation function (can be NULL) + */ + SECP256K1_API int secp256k1_ecdsa_sign_recoverable( + const secp256k1_context* ctx, + secp256k1_ecdsa_recoverable_signature *sig, + const unsigned char *msg32, + const unsigned char *seckey, + 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). + * 0: otherwise. + * Args: ctx: pointer to a context object, initialized for verification (cannot be NULL) + * Out: pubkey: pointer to the recovered public key (cannot be NULL) + * In: sig: pointer to initialized signature that supports pubkey recovery (cannot be NULL) + * msg32: the 32-byte message hash assumed to be signed (cannot be NULL) + */ + SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ecdsa_recover( + const secp256k1_context* ctx, + secp256k1_pubkey *pubkey, + const secp256k1_ecdsa_recoverable_signature *sig, + const unsigned char *msg32 + ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + /** Compute an EC Diffie-Hellman secret in constant time + * Returns: 1: exponentiation was successful + * 0: scalar was invalid (zero or overflow) + * Args: ctx: pointer to a context object (cannot be NULL) + * Out: result: a 32-byte array which will be populated by an ECDH + * secret computed from the point and scalar + * In: pubkey: a pointer to a secp256k1_pubkey containing an + * initialized public key + * privkey: a 32-byte scalar with which to multiply the point + */ + SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ecdh( + const secp256k1_context* ctx, + unsigned char *result, + 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 + +#endif /* SECP256K1_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/num.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/num.h new file mode 100644 index 000000000..7aadf7c67 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/num.h @@ -0,0 +1,72 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_NUM_H +#define SECP256K1_NUM_H + +#ifndef USE_NUM_NONE + +#include "secp256k1-config.h" + +#if defined(USE_NUM_GMP) +#include "num_gmp.h" +#else +#error "Please select num implementation" +#endif + +/** Copy a number. */ +static void secp256k1_num_copy(secp256k1_num *r, const secp256k1_num *a); + +/** Convert a number's absolute value to a binary big-endian string. + * There must be enough place. */ +static void secp256k1_num_get_bin(unsigned char *r, unsigned int rlen, const secp256k1_num *a); + +/** Set a number to the value of a binary big-endian string. */ +static void secp256k1_num_set_bin(secp256k1_num *r, const unsigned char *a, unsigned int alen); + +/** Compute a modular inverse. The input must be less than the modulus. */ +static void secp256k1_num_mod_inverse(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *m); + +/** Compute the jacobi symbol (a|b). b must be positive and odd. */ +static int secp256k1_num_jacobi(const secp256k1_num *a, const secp256k1_num *b); + +/** Compare the absolute value of two numbers. */ +static int secp256k1_num_cmp(const secp256k1_num *a, const secp256k1_num *b); + +/** Test whether two number are equal (including sign). */ +static int secp256k1_num_eq(const secp256k1_num *a, const secp256k1_num *b); + +/** Add two (signed) numbers. */ +static void secp256k1_num_add(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b); + +/** Subtract two (signed) numbers. */ +static void secp256k1_num_sub(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b); + +/** Multiply two (signed) numbers. */ +static void secp256k1_num_mul(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b); + +/** Replace a number by its remainder modulo m. M's sign is ignored. The result is a number between 0 and m-1, + even if r was negative. */ +static void secp256k1_num_mod(secp256k1_num *r, const secp256k1_num *m); + +/** Right-shift the passed number by bits bits. */ +static void secp256k1_num_shift(secp256k1_num *r, int bits); + +/** Check whether a number is zero. */ +static int secp256k1_num_is_zero(const secp256k1_num *a); + +/** Check whether a number is one. */ +static int secp256k1_num_is_one(const secp256k1_num *a); + +/** Check whether a number is strictly negative. */ +static int secp256k1_num_is_neg(const secp256k1_num *a); + +/** Change a number's sign. */ +static void secp256k1_num_negate(secp256k1_num *r); + +#endif + +#endif /* SECP256K1_NUM_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/num_gmp.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/num_gmp.h new file mode 100644 index 000000000..3619844bd --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/num_gmp.h @@ -0,0 +1,20 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_NUM_REPR_H +#define SECP256K1_NUM_REPR_H + +#include + +#define NUM_LIMBS ((256+GMP_NUMB_BITS-1)/GMP_NUMB_BITS) + +typedef struct { + mp_limb_t data[2*NUM_LIMBS]; + int neg; + int limbs; +} secp256k1_num; + +#endif /* SECP256K1_NUM_REPR_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/num_gmp_impl.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/num_gmp_impl.h new file mode 100644 index 000000000..0ae2a8ba0 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/num_gmp_impl.h @@ -0,0 +1,288 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_NUM_REPR_IMPL_H +#define SECP256K1_NUM_REPR_IMPL_H + +#include +#include +#include + +#include "util.h" +#include "num.h" + +#ifdef VERIFY +static void secp256k1_num_sanity(const secp256k1_num *a) { + VERIFY_CHECK(a->limbs == 1 || (a->limbs > 1 && a->data[a->limbs-1] != 0)); +} +#else +#define secp256k1_num_sanity(a) do { } while(0) +#endif + +static void secp256k1_num_copy(secp256k1_num *r, const secp256k1_num *a) { + *r = *a; +} + +static void secp256k1_num_get_bin(unsigned char *r, unsigned int rlen, const secp256k1_num *a) { + unsigned char tmp[65]; + int len = 0; + int shift = 0; + if (a->limbs>1 || a->data[0] != 0) { + len = mpn_get_str(tmp, 256, (mp_limb_t*)a->data, a->limbs); + } + while (shift < len && tmp[shift] == 0) shift++; + VERIFY_CHECK(len-shift <= (int)rlen); + memset(r, 0, rlen - len + shift); + if (len > shift) { + memcpy(r + rlen - len + shift, tmp + shift, len - shift); + } + memset(tmp, 0, sizeof(tmp)); +} + +static void secp256k1_num_set_bin(secp256k1_num *r, const unsigned char *a, unsigned int alen) { + int len; + VERIFY_CHECK(alen > 0); + VERIFY_CHECK(alen <= 64); + len = mpn_set_str(r->data, a, alen, 256); + if (len == 0) { + r->data[0] = 0; + len = 1; + } + VERIFY_CHECK(len <= NUM_LIMBS*2); + r->limbs = len; + r->neg = 0; + while (r->limbs > 1 && r->data[r->limbs-1]==0) { + r->limbs--; + } +} + +static void secp256k1_num_add_abs(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b) { + mp_limb_t c = mpn_add(r->data, a->data, a->limbs, b->data, b->limbs); + r->limbs = a->limbs; + if (c != 0) { + VERIFY_CHECK(r->limbs < 2*NUM_LIMBS); + r->data[r->limbs++] = c; + } +} + +static void secp256k1_num_sub_abs(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b) { + mp_limb_t c = mpn_sub(r->data, a->data, a->limbs, b->data, b->limbs); + (void)c; + VERIFY_CHECK(c == 0); + r->limbs = a->limbs; + while (r->limbs > 1 && r->data[r->limbs-1]==0) { + r->limbs--; + } +} + +static void secp256k1_num_mod(secp256k1_num *r, const secp256k1_num *m) { + secp256k1_num_sanity(r); + secp256k1_num_sanity(m); + + if (r->limbs >= m->limbs) { + mp_limb_t t[2*NUM_LIMBS]; + mpn_tdiv_qr(t, r->data, 0, r->data, r->limbs, m->data, m->limbs); + memset(t, 0, sizeof(t)); + r->limbs = m->limbs; + while (r->limbs > 1 && r->data[r->limbs-1]==0) { + r->limbs--; + } + } + + if (r->neg && (r->limbs > 1 || r->data[0] != 0)) { + secp256k1_num_sub_abs(r, m, r); + r->neg = 0; + } +} + +static void secp256k1_num_mod_inverse(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *m) { + int i; + mp_limb_t g[NUM_LIMBS+1]; + mp_limb_t u[NUM_LIMBS+1]; + mp_limb_t v[NUM_LIMBS+1]; + mp_size_t sn; + mp_size_t gn; + secp256k1_num_sanity(a); + secp256k1_num_sanity(m); + + /** mpn_gcdext computes: (G,S) = gcdext(U,V), where + * * G = gcd(U,V) + * * G = U*S + V*T + * * U has equal or more limbs than V, and V has no padding + * If we set U to be (a padded version of) a, and V = m: + * G = a*S + m*T + * G = a*S mod m + * Assuming G=1: + * S = 1/a mod m + */ + VERIFY_CHECK(m->limbs <= NUM_LIMBS); + VERIFY_CHECK(m->data[m->limbs-1] != 0); + for (i = 0; i < m->limbs; i++) { + u[i] = (i < a->limbs) ? a->data[i] : 0; + v[i] = m->data[i]; + } + sn = NUM_LIMBS+1; + gn = mpn_gcdext(g, r->data, &sn, u, m->limbs, v, m->limbs); + (void)gn; + VERIFY_CHECK(gn == 1); + VERIFY_CHECK(g[0] == 1); + r->neg = a->neg ^ m->neg; + if (sn < 0) { + mpn_sub(r->data, m->data, m->limbs, r->data, -sn); + r->limbs = m->limbs; + while (r->limbs > 1 && r->data[r->limbs-1]==0) { + r->limbs--; + } + } else { + r->limbs = sn; + } + memset(g, 0, sizeof(g)); + memset(u, 0, sizeof(u)); + memset(v, 0, sizeof(v)); +} + +static int secp256k1_num_jacobi(const secp256k1_num *a, const secp256k1_num *b) { + int ret; + mpz_t ga, gb; + secp256k1_num_sanity(a); + secp256k1_num_sanity(b); + VERIFY_CHECK(!b->neg && (b->limbs > 0) && (b->data[0] & 1)); + + mpz_inits(ga, gb, NULL); + + mpz_import(gb, b->limbs, -1, sizeof(mp_limb_t), 0, 0, b->data); + mpz_import(ga, a->limbs, -1, sizeof(mp_limb_t), 0, 0, a->data); + if (a->neg) { + mpz_neg(ga, ga); + } + + ret = mpz_jacobi(ga, gb); + + mpz_clears(ga, gb, NULL); + + return ret; +} + +static int secp256k1_num_is_one(const secp256k1_num *a) { + return (a->limbs == 1 && a->data[0] == 1); +} + +static int secp256k1_num_is_zero(const secp256k1_num *a) { + return (a->limbs == 1 && a->data[0] == 0); +} + +static int secp256k1_num_is_neg(const secp256k1_num *a) { + return (a->limbs > 1 || a->data[0] != 0) && a->neg; +} + +static int secp256k1_num_cmp(const secp256k1_num *a, const secp256k1_num *b) { + if (a->limbs > b->limbs) { + return 1; + } + if (a->limbs < b->limbs) { + return -1; + } + return mpn_cmp(a->data, b->data, a->limbs); +} + +static int secp256k1_num_eq(const secp256k1_num *a, const secp256k1_num *b) { + if (a->limbs > b->limbs) { + return 0; + } + if (a->limbs < b->limbs) { + return 0; + } + if ((a->neg && !secp256k1_num_is_zero(a)) != (b->neg && !secp256k1_num_is_zero(b))) { + return 0; + } + return mpn_cmp(a->data, b->data, a->limbs) == 0; +} + +static void secp256k1_num_subadd(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b, int bneg) { + if (!(b->neg ^ bneg ^ a->neg)) { /* a and b have the same sign */ + r->neg = a->neg; + if (a->limbs >= b->limbs) { + secp256k1_num_add_abs(r, a, b); + } else { + secp256k1_num_add_abs(r, b, a); + } + } else { + if (secp256k1_num_cmp(a, b) > 0) { + r->neg = a->neg; + secp256k1_num_sub_abs(r, a, b); + } else { + r->neg = b->neg ^ bneg; + secp256k1_num_sub_abs(r, b, a); + } + } +} + +static void secp256k1_num_add(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b) { + secp256k1_num_sanity(a); + secp256k1_num_sanity(b); + secp256k1_num_subadd(r, a, b, 0); +} + +static void secp256k1_num_sub(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b) { + secp256k1_num_sanity(a); + secp256k1_num_sanity(b); + secp256k1_num_subadd(r, a, b, 1); +} + +static void secp256k1_num_mul(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b) { + mp_limb_t tmp[2*NUM_LIMBS+1]; + secp256k1_num_sanity(a); + secp256k1_num_sanity(b); + + VERIFY_CHECK(a->limbs + b->limbs <= 2*NUM_LIMBS+1); + if ((a->limbs==1 && a->data[0]==0) || (b->limbs==1 && b->data[0]==0)) { + r->limbs = 1; + r->neg = 0; + r->data[0] = 0; + return; + } + if (a->limbs >= b->limbs) { + mpn_mul(tmp, a->data, a->limbs, b->data, b->limbs); + } else { + mpn_mul(tmp, b->data, b->limbs, a->data, a->limbs); + } + r->limbs = a->limbs + b->limbs; + if (r->limbs > 1 && tmp[r->limbs - 1]==0) { + r->limbs--; + } + VERIFY_CHECK(r->limbs <= 2*NUM_LIMBS); + mpn_copyi(r->data, tmp, r->limbs); + r->neg = a->neg ^ b->neg; + memset(tmp, 0, sizeof(tmp)); +} + +static void secp256k1_num_shift(secp256k1_num *r, int bits) { + if (bits % GMP_NUMB_BITS) { + /* Shift within limbs. */ + mpn_rshift(r->data, r->data, r->limbs, bits % GMP_NUMB_BITS); + } + if (bits >= GMP_NUMB_BITS) { + int i; + /* Shift full limbs. */ + for (i = 0; i < r->limbs; i++) { + int index = i + (bits / GMP_NUMB_BITS); + if (index < r->limbs && index < 2*NUM_LIMBS) { + r->data[i] = r->data[index]; + } else { + r->data[i] = 0; + } + } + } + while (r->limbs>1 && r->data[r->limbs-1]==0) { + r->limbs--; + } +} + +static void secp256k1_num_negate(secp256k1_num *r) { + r->neg ^= 1; +} + +#endif /* SECP256K1_NUM_REPR_IMPL_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/num_impl.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/num_impl.h new file mode 100644 index 000000000..59dd6f7a1 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/num_impl.h @@ -0,0 +1,22 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_NUM_IMPL_H +#define SECP256K1_NUM_IMPL_H + +#include "secp256k1-config.h" + +#include "num.h" + +#if defined(USE_NUM_GMP) +#include "num_gmp_impl.h" +#elif defined(USE_NUM_NONE) +/* Nothing. */ +#else +#error "Please select num implementation" +#endif + +#endif /* SECP256K1_NUM_IMPL_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/recovery_impl.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/recovery_impl.h new file mode 100755 index 000000000..eb7051937 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/recovery_impl.h @@ -0,0 +1,193 @@ +/********************************************************************** + * Copyright (c) 2013-2015 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_MODULE_RECOVERY_MAIN_H +#define SECP256K1_MODULE_RECOVERY_MAIN_H + +#include "secp256k1.h" + +static void secp256k1_ecdsa_recoverable_signature_load(const secp256k1_context* ctx, secp256k1_scalar* r, secp256k1_scalar* s, int* recid, const secp256k1_ecdsa_recoverable_signature* sig) { + (void)ctx; + if (sizeof(secp256k1_scalar) == 32) { + /* When the secp256k1_scalar type is exactly 32 byte, use its + * representation inside secp256k1_ecdsa_signature, as conversion is very fast. + * Note that secp256k1_ecdsa_signature_save must use the same representation. */ + memcpy(r, &sig->data[0], 32); + memcpy(s, &sig->data[32], 32); + } else { + secp256k1_scalar_set_b32(r, &sig->data[0], NULL); + secp256k1_scalar_set_b32(s, &sig->data[32], NULL); + } + *recid = sig->data[64]; +} + +static void secp256k1_ecdsa_recoverable_signature_save(secp256k1_ecdsa_recoverable_signature* sig, const secp256k1_scalar* r, const secp256k1_scalar* s, int recid) { + if (sizeof(secp256k1_scalar) == 32) { + memcpy(&sig->data[0], r, 32); + memcpy(&sig->data[32], s, 32); + } else { + secp256k1_scalar_get_b32(&sig->data[0], r); + secp256k1_scalar_get_b32(&sig->data[32], s); + } + sig->data[64] = recid; +} + +int secp256k1_ecdsa_recoverable_signature_parse_compact(const secp256k1_context* ctx, secp256k1_ecdsa_recoverable_signature* sig, const unsigned char *input64, int recid) { + secp256k1_scalar r, s; + int ret = 1; + int overflow = 0; + + (void)ctx; + ARG_CHECK(sig != NULL); + ARG_CHECK(input64 != NULL); + ARG_CHECK(recid >= 0 && recid <= 3); + + secp256k1_scalar_set_b32(&r, &input64[0], &overflow); + ret &= !overflow; + secp256k1_scalar_set_b32(&s, &input64[32], &overflow); + ret &= !overflow; + if (ret) { + secp256k1_ecdsa_recoverable_signature_save(sig, &r, &s, recid); + } else { + memset(sig, 0, sizeof(*sig)); + } + return ret; +} + +int secp256k1_ecdsa_recoverable_signature_serialize_compact(const secp256k1_context* ctx, unsigned char *output64, int *recid, const secp256k1_ecdsa_recoverable_signature* sig) { + secp256k1_scalar r, s; + + (void)ctx; + ARG_CHECK(output64 != NULL); + ARG_CHECK(sig != NULL); + ARG_CHECK(recid != NULL); + + secp256k1_ecdsa_recoverable_signature_load(ctx, &r, &s, recid, sig); + secp256k1_scalar_get_b32(&output64[0], &r); + secp256k1_scalar_get_b32(&output64[32], &s); + return 1; +} + +int secp256k1_ecdsa_recoverable_signature_convert(const secp256k1_context* ctx, secp256k1_ecdsa_signature* sig, const secp256k1_ecdsa_recoverable_signature* sigin) { + secp256k1_scalar r, s; + int recid; + + (void)ctx; + ARG_CHECK(sig != NULL); + ARG_CHECK(sigin != NULL); + + secp256k1_ecdsa_recoverable_signature_load(ctx, &r, &s, &recid, sigin); + secp256k1_ecdsa_signature_save(sig, &r, &s); + return 1; +} + +static int secp256k1_ecdsa_sig_recover(const secp256k1_ecmult_context *ctx, const secp256k1_scalar *sigr, const secp256k1_scalar* sigs, secp256k1_ge *pubkey, const secp256k1_scalar *message, int recid) { + unsigned char brx[32]; + secp256k1_fe fx; + secp256k1_ge x; + secp256k1_gej xj; + secp256k1_scalar rn, u1, u2; + secp256k1_gej qj; + int r; + + if (secp256k1_scalar_is_zero(sigr) || secp256k1_scalar_is_zero(sigs)) { + return 0; + } + + secp256k1_scalar_get_b32(brx, sigr); + r = secp256k1_fe_set_b32(&fx, brx); + (void)r; + VERIFY_CHECK(r); /* brx comes from a scalar, so is less than the order; certainly less than p */ + if (recid & 2) { + if (secp256k1_fe_cmp_var(&fx, &secp256k1_ecdsa_const_p_minus_order) >= 0) { + return 0; + } + secp256k1_fe_add(&fx, &secp256k1_ecdsa_const_order_as_fe); + } + if (!secp256k1_ge_set_xo_var(&x, &fx, recid & 1)) { + return 0; + } + secp256k1_gej_set_ge(&xj, &x); + secp256k1_scalar_inverse_var(&rn, sigr); + secp256k1_scalar_mul(&u1, &rn, message); + secp256k1_scalar_negate(&u1, &u1); + secp256k1_scalar_mul(&u2, &rn, sigs); + secp256k1_ecmult(ctx, &qj, &xj, &u2, &u1); + secp256k1_ge_set_gej_var(pubkey, &qj); + return !secp256k1_gej_is_infinity(&qj); +} + +int secp256k1_ecdsa_sign_recoverable(const secp256k1_context* ctx, secp256k1_ecdsa_recoverable_signature *signature, const unsigned char *msg32, const unsigned char *seckey, secp256k1_nonce_function noncefp, const void* noncedata) { + secp256k1_scalar r, s; + secp256k1_scalar sec, non, msg; + int recid = 0; + int ret = 0; + int overflow = 0; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)); + ARG_CHECK(msg32 != NULL); + ARG_CHECK(signature != NULL); + ARG_CHECK(seckey != NULL); + if (noncefp == NULL) { + noncefp = secp256k1_nonce_function_default; + } + + secp256k1_scalar_set_b32(&sec, seckey, &overflow); + /* Fail if the secret key is invalid. */ + if (!overflow && !secp256k1_scalar_is_zero(&sec)) { + unsigned char nonce32[32]; + unsigned int count = 0; + secp256k1_scalar_set_b32(&msg, msg32, NULL); + while (1) { + ret = noncefp(nonce32, msg32, seckey, NULL, (void*)noncedata, count); + if (!ret) { + break; + } + secp256k1_scalar_set_b32(&non, nonce32, &overflow); + if (!secp256k1_scalar_is_zero(&non) && !overflow) { + if (secp256k1_ecdsa_sig_sign(&ctx->ecmult_gen_ctx, &r, &s, &sec, &msg, &non, &recid)) { + break; + } + } + count++; + } + memset(nonce32, 0, 32); + secp256k1_scalar_clear(&msg); + secp256k1_scalar_clear(&non); + secp256k1_scalar_clear(&sec); + } + if (ret) { + secp256k1_ecdsa_recoverable_signature_save(signature, &r, &s, recid); + } else { + memset(signature, 0, sizeof(*signature)); + } + return ret; +} + +int secp256k1_ecdsa_recover(const secp256k1_context* ctx, secp256k1_pubkey *pubkey, const secp256k1_ecdsa_recoverable_signature *signature, const unsigned char *msg32) { + secp256k1_ge q; + secp256k1_scalar r, s; + secp256k1_scalar m; + int recid; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_context_is_built(&ctx->ecmult_ctx)); + ARG_CHECK(msg32 != NULL); + ARG_CHECK(signature != NULL); + ARG_CHECK(pubkey != NULL); + + secp256k1_ecdsa_recoverable_signature_load(ctx, &r, &s, &recid, signature); + VERIFY_CHECK(recid >= 0 && recid < 4); /* should have been caught in parse_compact */ + secp256k1_scalar_set_b32(&m, msg32, NULL); + if (secp256k1_ecdsa_sig_recover(&ctx->ecmult_ctx, &r, &s, &q, &m, recid)) { + secp256k1_pubkey_save(pubkey, &q); + return 1; + } else { + memset(pubkey, 0, sizeof(*pubkey)); + return 0; + } +} + +#endif /* SECP256K1_MODULE_RECOVERY_MAIN_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar.h new file mode 100644 index 000000000..c909a43f6 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar.h @@ -0,0 +1,104 @@ +/********************************************************************** + * Copyright (c) 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_H +#define SECP256K1_SCALAR_H + +#include "num.h" + +#include "secp256k1-config.h" + +#if defined(EXHAUSTIVE_TEST_ORDER) +#include "scalar_low.h" +#elif defined(USE_SCALAR_4X64) +#include "scalar_4x64.h" +#elif defined(USE_SCALAR_8X32) +#include "scalar_8x32.h" +#else +#error "Please select scalar implementation" +#endif + +/** Clear a scalar to prevent the leak of sensitive data. */ +static void secp256k1_scalar_clear(secp256k1_scalar *r); + +/** Access bits from a scalar. All requested bits must belong to the same 32-bit limb. */ +static unsigned int secp256k1_scalar_get_bits(const secp256k1_scalar *a, unsigned int offset, unsigned int count); + +/** Access bits from a scalar. Not constant time. */ +static unsigned int secp256k1_scalar_get_bits_var(const secp256k1_scalar *a, unsigned int offset, unsigned int count); + +/** Set a scalar from a big endian byte array. */ +static void secp256k1_scalar_set_b32(secp256k1_scalar *r, const unsigned char *bin, int *overflow); + +/** Set a scalar to an unsigned integer. */ +static void secp256k1_scalar_set_int(secp256k1_scalar *r, unsigned int v); + +/** Convert a scalar to a byte array. */ +static void secp256k1_scalar_get_b32(unsigned char *bin, const secp256k1_scalar* a); + +/** Add two scalars together (modulo the group order). Returns whether it overflowed. */ +static int secp256k1_scalar_add(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b); + +/** Conditionally add a power of two to a scalar. The result is not allowed to overflow. */ +static void secp256k1_scalar_cadd_bit(secp256k1_scalar *r, unsigned int bit, int flag); + +/** Multiply two scalars (modulo the group order). */ +static void secp256k1_scalar_mul(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b); + +/** Shift a scalar right by some amount strictly between 0 and 16, returning + * the low bits that were shifted off */ +static int secp256k1_scalar_shr_int(secp256k1_scalar *r, int n); + +/** Compute the square of a scalar (modulo the group order). */ +static void secp256k1_scalar_sqr(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Compute the inverse of a scalar (modulo the group order). */ +static void secp256k1_scalar_inverse(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Compute the inverse of a scalar (modulo the group order), without constant-time guarantee. */ +static void secp256k1_scalar_inverse_var(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Compute the complement of a scalar (modulo the group order). */ +static void secp256k1_scalar_negate(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Check whether a scalar equals zero. */ +static int secp256k1_scalar_is_zero(const secp256k1_scalar *a); + +/** Check whether a scalar equals one. */ +static int secp256k1_scalar_is_one(const secp256k1_scalar *a); + +/** Check whether a scalar, considered as an nonnegative integer, is even. */ +static int secp256k1_scalar_is_even(const secp256k1_scalar *a); + +/** Check whether a scalar is higher than the group order divided by 2. */ +static int secp256k1_scalar_is_high(const secp256k1_scalar *a); + +/** Conditionally negate a number, in constant time. + * Returns -1 if the number was negated, 1 otherwise */ +static int secp256k1_scalar_cond_negate(secp256k1_scalar *a, int flag); + +#ifndef USE_NUM_NONE +/** Convert a scalar to a number. */ +static void secp256k1_scalar_get_num(secp256k1_num *r, const secp256k1_scalar *a); + +/** Get the order of the group as a number. */ +static void secp256k1_scalar_order_get_num(secp256k1_num *r); +#endif + +/** Compare two scalars. */ +static int secp256k1_scalar_eq(const secp256k1_scalar *a, const secp256k1_scalar *b); + +#ifdef USE_ENDOMORPHISM +/** Find r1 and r2 such that r1+r2*2^128 = a. */ +static void secp256k1_scalar_split_128(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a); +/** Find r1 and r2 such that r1+r2*lambda = a, and r1 and r2 are maximum 128 bits long (see secp256k1_gej_mul_lambda). */ +static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a); +#endif + +/** Multiply a and b (without taking the modulus!), divide by 2**shift, and round to the nearest integer. Shift must be at least 256. */ +static void secp256k1_scalar_mul_shift_var(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b, unsigned int shift); + +#endif /* SECP256K1_SCALAR_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_4x64.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_4x64.h new file mode 100644 index 000000000..19c7495d1 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_4x64.h @@ -0,0 +1,19 @@ +/********************************************************************** + * Copyright (c) 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_REPR_H +#define SECP256K1_SCALAR_REPR_H + +#include + +/** A scalar modulo the group order of the secp256k1 curve. */ +typedef struct { + uint64_t d[4]; +} secp256k1_scalar; + +#define SECP256K1_SCALAR_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{((uint64_t)(d1)) << 32 | (d0), ((uint64_t)(d3)) << 32 | (d2), ((uint64_t)(d5)) << 32 | (d4), ((uint64_t)(d7)) << 32 | (d6)}} + +#endif /* SECP256K1_SCALAR_REPR_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_4x64_impl.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_4x64_impl.h new file mode 100644 index 000000000..685bc99e6 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_4x64_impl.h @@ -0,0 +1,949 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_REPR_IMPL_H +#define SECP256K1_SCALAR_REPR_IMPL_H + +/* Limbs of the secp256k1 order. */ +#define SECP256K1_N_0 ((uint64_t)0xBFD25E8CD0364141ULL) +#define SECP256K1_N_1 ((uint64_t)0xBAAEDCE6AF48A03BULL) +#define SECP256K1_N_2 ((uint64_t)0xFFFFFFFFFFFFFFFEULL) +#define SECP256K1_N_3 ((uint64_t)0xFFFFFFFFFFFFFFFFULL) + +/* Limbs of 2^256 minus the secp256k1 order. */ +#define SECP256K1_N_C_0 (~SECP256K1_N_0 + 1) +#define SECP256K1_N_C_1 (~SECP256K1_N_1) +#define SECP256K1_N_C_2 (1) + +/* Limbs of half the secp256k1 order. */ +#define SECP256K1_N_H_0 ((uint64_t)0xDFE92F46681B20A0ULL) +#define SECP256K1_N_H_1 ((uint64_t)0x5D576E7357A4501DULL) +#define SECP256K1_N_H_2 ((uint64_t)0xFFFFFFFFFFFFFFFFULL) +#define SECP256K1_N_H_3 ((uint64_t)0x7FFFFFFFFFFFFFFFULL) + +SECP256K1_INLINE static void secp256k1_scalar_clear(secp256k1_scalar *r) { + r->d[0] = 0; + r->d[1] = 0; + r->d[2] = 0; + r->d[3] = 0; +} + +SECP256K1_INLINE static void secp256k1_scalar_set_int(secp256k1_scalar *r, unsigned int v) { + r->d[0] = v; + r->d[1] = 0; + r->d[2] = 0; + r->d[3] = 0; +} + +SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits(const secp256k1_scalar *a, unsigned int offset, unsigned int count) { + VERIFY_CHECK((offset + count - 1) >> 6 == offset >> 6); + return (uint)(a->d[offset >> 6] >> (offset & 0x3F)) & ((((uint64_t)1) << count) - 1); +} + +SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits_var(const secp256k1_scalar *a, unsigned int offset, unsigned int count) { + VERIFY_CHECK(count < 32); + VERIFY_CHECK(offset + count <= 256); + if ((offset + count - 1) >> 6 == offset >> 6) { + return secp256k1_scalar_get_bits(a, offset, count); + } else { + VERIFY_CHECK((offset >> 6) + 1 < 4); + return (uint)((a->d[offset >> 6] >> (offset & 0x3F)) | (a->d[(offset >> 6) + 1] << (64 - (offset & 0x3F)))) & ((((uint64_t)1) << count) - 1); + } +} + +SECP256K1_INLINE static int secp256k1_scalar_check_overflow(const secp256k1_scalar *a) { + int yes = 0; + int no = 0; + no |= (a->d[3] < SECP256K1_N_3); /* No need for a > check. */ + no |= (a->d[2] < SECP256K1_N_2); + yes |= (a->d[2] > SECP256K1_N_2) & ~no; + no |= (a->d[1] < SECP256K1_N_1); + yes |= (a->d[1] > SECP256K1_N_1) & ~no; + yes |= (a->d[0] >= SECP256K1_N_0) & ~no; + return yes; +} + +SECP256K1_INLINE static int secp256k1_scalar_reduce(secp256k1_scalar *r, unsigned int overflow) { + uint128_t t; + VERIFY_CHECK(overflow <= 1); + t = (uint128_t)r->d[0] + overflow * SECP256K1_N_C_0; + r->d[0] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)r->d[1] + overflow * SECP256K1_N_C_1; + r->d[1] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)r->d[2] + overflow * SECP256K1_N_C_2; + r->d[2] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint64_t)r->d[3]; + r->d[3] = t & 0xFFFFFFFFFFFFFFFFULL; + return overflow; +} + +static int secp256k1_scalar_add(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b) { + int overflow; + uint128_t t = (uint128_t)a->d[0] + b->d[0]; + r->d[0] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)a->d[1] + b->d[1]; + r->d[1] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)a->d[2] + b->d[2]; + r->d[2] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)a->d[3] + b->d[3]; + r->d[3] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + overflow = t + secp256k1_scalar_check_overflow(r); + VERIFY_CHECK(overflow == 0 || overflow == 1); + secp256k1_scalar_reduce(r, overflow); + return overflow; +} + +static void secp256k1_scalar_cadd_bit(secp256k1_scalar *r, unsigned int bit, int flag) { + uint128_t t; + VERIFY_CHECK(bit < 256); + bit += ((uint32_t) flag - 1) & 0x100; /* forcing (bit >> 6) > 3 makes this a noop */ + t = (uint128_t)r->d[0] + (((uint64_t)((bit >> 6) == 0)) << (bit & 0x3F)); + r->d[0] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)r->d[1] + (((uint64_t)((bit >> 6) == 1)) << (bit & 0x3F)); + r->d[1] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)r->d[2] + (((uint64_t)((bit >> 6) == 2)) << (bit & 0x3F)); + r->d[2] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)r->d[3] + (((uint64_t)((bit >> 6) == 3)) << (bit & 0x3F)); + r->d[3] = t & 0xFFFFFFFFFFFFFFFFULL; +#ifdef VERIFY + VERIFY_CHECK((t >> 64) == 0); + VERIFY_CHECK(secp256k1_scalar_check_overflow(r) == 0); +#endif +} + +static void secp256k1_scalar_set_b32(secp256k1_scalar *r, const unsigned char *b32, int *overflow) { + int over; + r->d[0] = (uint64_t)b32[31] | (uint64_t)b32[30] << 8 | (uint64_t)b32[29] << 16 | (uint64_t)b32[28] << 24 | (uint64_t)b32[27] << 32 | (uint64_t)b32[26] << 40 | (uint64_t)b32[25] << 48 | (uint64_t)b32[24] << 56; + r->d[1] = (uint64_t)b32[23] | (uint64_t)b32[22] << 8 | (uint64_t)b32[21] << 16 | (uint64_t)b32[20] << 24 | (uint64_t)b32[19] << 32 | (uint64_t)b32[18] << 40 | (uint64_t)b32[17] << 48 | (uint64_t)b32[16] << 56; + r->d[2] = (uint64_t)b32[15] | (uint64_t)b32[14] << 8 | (uint64_t)b32[13] << 16 | (uint64_t)b32[12] << 24 | (uint64_t)b32[11] << 32 | (uint64_t)b32[10] << 40 | (uint64_t)b32[9] << 48 | (uint64_t)b32[8] << 56; + r->d[3] = (uint64_t)b32[7] | (uint64_t)b32[6] << 8 | (uint64_t)b32[5] << 16 | (uint64_t)b32[4] << 24 | (uint64_t)b32[3] << 32 | (uint64_t)b32[2] << 40 | (uint64_t)b32[1] << 48 | (uint64_t)b32[0] << 56; + over = secp256k1_scalar_reduce(r, secp256k1_scalar_check_overflow(r)); + if (overflow) { + *overflow = over; + } +} + +static void secp256k1_scalar_get_b32(unsigned char *bin, const secp256k1_scalar* a) { + bin[0] = a->d[3] >> 56; bin[1] = a->d[3] >> 48; bin[2] = a->d[3] >> 40; bin[3] = a->d[3] >> 32; bin[4] = a->d[3] >> 24; bin[5] = a->d[3] >> 16; bin[6] = a->d[3] >> 8; bin[7] = a->d[3]; + bin[8] = a->d[2] >> 56; bin[9] = a->d[2] >> 48; bin[10] = a->d[2] >> 40; bin[11] = a->d[2] >> 32; bin[12] = a->d[2] >> 24; bin[13] = a->d[2] >> 16; bin[14] = a->d[2] >> 8; bin[15] = a->d[2]; + bin[16] = a->d[1] >> 56; bin[17] = a->d[1] >> 48; bin[18] = a->d[1] >> 40; bin[19] = a->d[1] >> 32; bin[20] = a->d[1] >> 24; bin[21] = a->d[1] >> 16; bin[22] = a->d[1] >> 8; bin[23] = a->d[1]; + bin[24] = a->d[0] >> 56; bin[25] = a->d[0] >> 48; bin[26] = a->d[0] >> 40; bin[27] = a->d[0] >> 32; bin[28] = a->d[0] >> 24; bin[29] = a->d[0] >> 16; bin[30] = a->d[0] >> 8; bin[31] = a->d[0]; +} + +SECP256K1_INLINE static int secp256k1_scalar_is_zero(const secp256k1_scalar *a) { + return (a->d[0] | a->d[1] | a->d[2] | a->d[3]) == 0; +} + +static void secp256k1_scalar_negate(secp256k1_scalar *r, const secp256k1_scalar *a) { + uint64_t nonzero = 0xFFFFFFFFFFFFFFFFULL * (secp256k1_scalar_is_zero(a) == 0); + uint128_t t = (uint128_t)(~a->d[0]) + SECP256K1_N_0 + 1; + r->d[0] = t & nonzero; t >>= 64; + t += (uint128_t)(~a->d[1]) + SECP256K1_N_1; + r->d[1] = t & nonzero; t >>= 64; + t += (uint128_t)(~a->d[2]) + SECP256K1_N_2; + r->d[2] = t & nonzero; t >>= 64; + t += (uint128_t)(~a->d[3]) + SECP256K1_N_3; + r->d[3] = t & nonzero; +} + +SECP256K1_INLINE static int secp256k1_scalar_is_one(const secp256k1_scalar *a) { + return ((a->d[0] ^ 1) | a->d[1] | a->d[2] | a->d[3]) == 0; +} + +static int secp256k1_scalar_is_high(const secp256k1_scalar *a) { + int yes = 0; + int no = 0; + no |= (a->d[3] < SECP256K1_N_H_3); + yes |= (a->d[3] > SECP256K1_N_H_3) & ~no; + no |= (a->d[2] < SECP256K1_N_H_2) & ~yes; /* No need for a > check. */ + no |= (a->d[1] < SECP256K1_N_H_1) & ~yes; + yes |= (a->d[1] > SECP256K1_N_H_1) & ~no; + yes |= (a->d[0] > SECP256K1_N_H_0) & ~no; + return yes; +} + +static int secp256k1_scalar_cond_negate(secp256k1_scalar *r, int flag) { + /* If we are flag = 0, mask = 00...00 and this is a no-op; + * if we are flag = 1, mask = 11...11 and this is identical to secp256k1_scalar_negate */ + uint64_t mask = !flag - 1; + uint64_t nonzero = (secp256k1_scalar_is_zero(r) != 0) - 1; + uint128_t t = (uint128_t)(r->d[0] ^ mask) + ((SECP256K1_N_0 + 1) & mask); + r->d[0] = t & nonzero; t >>= 64; + t += (uint128_t)(r->d[1] ^ mask) + (SECP256K1_N_1 & mask); + r->d[1] = t & nonzero; t >>= 64; + t += (uint128_t)(r->d[2] ^ mask) + (SECP256K1_N_2 & mask); + r->d[2] = t & nonzero; t >>= 64; + t += (uint128_t)(r->d[3] ^ mask) + (SECP256K1_N_3 & mask); + r->d[3] = t & nonzero; + return 2 * (mask == 0) - 1; +} + +/* Inspired by the macros in OpenSSL's crypto/bn/asm/x86_64-gcc.c. */ + +/** Add a*b to the number defined by (c0,c1,c2). c2 must never overflow. */ +#define muladd(a,b) { \ + uint64_t tl, th; \ + { \ + uint128_t t = (uint128_t)a * b; \ + th = t >> 64; /* at most 0xFFFFFFFFFFFFFFFE */ \ + tl = t; \ + } \ + c0 += tl; /* overflow is handled on the next line */ \ + th += (c0 < tl) ? 1 : 0; /* at most 0xFFFFFFFFFFFFFFFF */ \ + c1 += th; /* overflow is handled on the next line */ \ + c2 += (c1 < th) ? 1 : 0; /* never overflows by contract (verified in the next line) */ \ + VERIFY_CHECK((c1 >= th) || (c2 != 0)); \ +} + +/** Add a*b to the number defined by (c0,c1). c1 must never overflow. */ +#define muladd_fast(a,b) { \ + uint64_t tl, th; \ + { \ + uint128_t t = (uint128_t)a * b; \ + th = t >> 64; /* at most 0xFFFFFFFFFFFFFFFE */ \ + tl = t; \ + } \ + c0 += tl; /* overflow is handled on the next line */ \ + th += (c0 < tl) ? 1 : 0; /* at most 0xFFFFFFFFFFFFFFFF */ \ + c1 += th; /* never overflows by contract (verified in the next line) */ \ + VERIFY_CHECK(c1 >= th); \ +} + +/** Add 2*a*b to the number defined by (c0,c1,c2). c2 must never overflow. */ +#define muladd2(a,b) { \ + uint64_t tl, th, th2, tl2; \ + { \ + uint128_t t = (uint128_t)a * b; \ + th = t >> 64; /* at most 0xFFFFFFFFFFFFFFFE */ \ + tl = t; \ + } \ + th2 = th + th; /* at most 0xFFFFFFFFFFFFFFFE (in case th was 0x7FFFFFFFFFFFFFFF) */ \ + c2 += (th2 < th) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ + VERIFY_CHECK((th2 >= th) || (c2 != 0)); \ + tl2 = tl + tl; /* at most 0xFFFFFFFFFFFFFFFE (in case the lowest 63 bits of tl were 0x7FFFFFFFFFFFFFFF) */ \ + th2 += (tl2 < tl) ? 1 : 0; /* at most 0xFFFFFFFFFFFFFFFF */ \ + c0 += tl2; /* overflow is handled on the next line */ \ + th2 += (c0 < tl2) ? 1 : 0; /* second overflow is handled on the next line */ \ + c2 += (c0 < tl2) & (th2 == 0); /* never overflows by contract (verified the next line) */ \ + VERIFY_CHECK((c0 >= tl2) || (th2 != 0) || (c2 != 0)); \ + c1 += th2; /* overflow is handled on the next line */ \ + c2 += (c1 < th2) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ + VERIFY_CHECK((c1 >= th2) || (c2 != 0)); \ +} + +/** Add a to the number defined by (c0,c1,c2). c2 must never overflow. */ +#define sumadd(a) { \ + unsigned int over; \ + c0 += (a); /* overflow is handled on the next line */ \ + over = (c0 < (a)) ? 1 : 0; \ + c1 += over; /* overflow is handled on the next line */ \ + c2 += (c1 < over) ? 1 : 0; /* never overflows by contract */ \ +} + +/** Add a to the number defined by (c0,c1). c1 must never overflow, c2 must be zero. */ +#define sumadd_fast(a) { \ + c0 += (a); /* overflow is handled on the next line */ \ + c1 += (c0 < (a)) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ + VERIFY_CHECK((c1 != 0) | (c0 >= (a))); \ + VERIFY_CHECK(c2 == 0); \ +} + +/** Extract the lowest 64 bits of (c0,c1,c2) into n, and left shift the number 64 bits. */ +#define extract(n) { \ + (n) = c0; \ + c0 = c1; \ + c1 = c2; \ + c2 = 0; \ +} + +/** Extract the lowest 64 bits of (c0,c1,c2) into n, and left shift the number 64 bits. c2 is required to be zero. */ +#define extract_fast(n) { \ + (n) = c0; \ + c0 = c1; \ + c1 = 0; \ + VERIFY_CHECK(c2 == 0); \ +} + +static void secp256k1_scalar_reduce_512(secp256k1_scalar *r, const uint64_t *l) { +#ifdef USE_ASM_X86_64 + /* Reduce 512 bits into 385. */ + uint64_t m0, m1, m2, m3, m4, m5, m6; + uint64_t p0, p1, p2, p3, p4; + uint64_t c; + + __asm__ __volatile__( + /* Preload. */ + "movq 32(%%rsi), %%r11\n" + "movq 40(%%rsi), %%r12\n" + "movq 48(%%rsi), %%r13\n" + "movq 56(%%rsi), %%r14\n" + /* Initialize r8,r9,r10 */ + "movq 0(%%rsi), %%r8\n" + "xorq %%r9, %%r9\n" + "xorq %%r10, %%r10\n" + /* (r8,r9) += n0 * c0 */ + "movq %8, %%rax\n" + "mulq %%r11\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + /* extract m0 */ + "movq %%r8, %q0\n" + "xorq %%r8, %%r8\n" + /* (r9,r10) += l1 */ + "addq 8(%%rsi), %%r9\n" + "adcq $0, %%r10\n" + /* (r9,r10,r8) += n1 * c0 */ + "movq %8, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* (r9,r10,r8) += n0 * c1 */ + "movq %9, %%rax\n" + "mulq %%r11\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* extract m1 */ + "movq %%r9, %q1\n" + "xorq %%r9, %%r9\n" + /* (r10,r8,r9) += l2 */ + "addq 16(%%rsi), %%r10\n" + "adcq $0, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += n2 * c0 */ + "movq %8, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += n1 * c1 */ + "movq %9, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += n0 */ + "addq %%r11, %%r10\n" + "adcq $0, %%r8\n" + "adcq $0, %%r9\n" + /* extract m2 */ + "movq %%r10, %q2\n" + "xorq %%r10, %%r10\n" + /* (r8,r9,r10) += l3 */ + "addq 24(%%rsi), %%r8\n" + "adcq $0, %%r9\n" + "adcq $0, %%r10\n" + /* (r8,r9,r10) += n3 * c0 */ + "movq %8, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* (r8,r9,r10) += n2 * c1 */ + "movq %9, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* (r8,r9,r10) += n1 */ + "addq %%r12, %%r8\n" + "adcq $0, %%r9\n" + "adcq $0, %%r10\n" + /* extract m3 */ + "movq %%r8, %q3\n" + "xorq %%r8, %%r8\n" + /* (r9,r10,r8) += n3 * c1 */ + "movq %9, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* (r9,r10,r8) += n2 */ + "addq %%r13, %%r9\n" + "adcq $0, %%r10\n" + "adcq $0, %%r8\n" + /* extract m4 */ + "movq %%r9, %q4\n" + /* (r10,r8) += n3 */ + "addq %%r14, %%r10\n" + "adcq $0, %%r8\n" + /* extract m5 */ + "movq %%r10, %q5\n" + /* extract m6 */ + "movq %%r8, %q6\n" + : "=g"(m0), "=g"(m1), "=g"(m2), "=g"(m3), "=g"(m4), "=g"(m5), "=g"(m6) + : "S"(l), "n"(SECP256K1_N_C_0), "n"(SECP256K1_N_C_1) + : "rax", "rdx", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "cc"); + + /* Reduce 385 bits into 258. */ + __asm__ __volatile__( + /* Preload */ + "movq %q9, %%r11\n" + "movq %q10, %%r12\n" + "movq %q11, %%r13\n" + /* Initialize (r8,r9,r10) */ + "movq %q5, %%r8\n" + "xorq %%r9, %%r9\n" + "xorq %%r10, %%r10\n" + /* (r8,r9) += m4 * c0 */ + "movq %12, %%rax\n" + "mulq %%r11\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + /* extract p0 */ + "movq %%r8, %q0\n" + "xorq %%r8, %%r8\n" + /* (r9,r10) += m1 */ + "addq %q6, %%r9\n" + "adcq $0, %%r10\n" + /* (r9,r10,r8) += m5 * c0 */ + "movq %12, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* (r9,r10,r8) += m4 * c1 */ + "movq %13, %%rax\n" + "mulq %%r11\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* extract p1 */ + "movq %%r9, %q1\n" + "xorq %%r9, %%r9\n" + /* (r10,r8,r9) += m2 */ + "addq %q7, %%r10\n" + "adcq $0, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += m6 * c0 */ + "movq %12, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += m5 * c1 */ + "movq %13, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += m4 */ + "addq %%r11, %%r10\n" + "adcq $0, %%r8\n" + "adcq $0, %%r9\n" + /* extract p2 */ + "movq %%r10, %q2\n" + /* (r8,r9) += m3 */ + "addq %q8, %%r8\n" + "adcq $0, %%r9\n" + /* (r8,r9) += m6 * c1 */ + "movq %13, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + /* (r8,r9) += m5 */ + "addq %%r12, %%r8\n" + "adcq $0, %%r9\n" + /* extract p3 */ + "movq %%r8, %q3\n" + /* (r9) += m6 */ + "addq %%r13, %%r9\n" + /* extract p4 */ + "movq %%r9, %q4\n" + : "=&g"(p0), "=&g"(p1), "=&g"(p2), "=g"(p3), "=g"(p4) + : "g"(m0), "g"(m1), "g"(m2), "g"(m3), "g"(m4), "g"(m5), "g"(m6), "n"(SECP256K1_N_C_0), "n"(SECP256K1_N_C_1) + : "rax", "rdx", "r8", "r9", "r10", "r11", "r12", "r13", "cc"); + + /* Reduce 258 bits into 256. */ + __asm__ __volatile__( + /* Preload */ + "movq %q5, %%r10\n" + /* (rax,rdx) = p4 * c0 */ + "movq %7, %%rax\n" + "mulq %%r10\n" + /* (rax,rdx) += p0 */ + "addq %q1, %%rax\n" + "adcq $0, %%rdx\n" + /* extract r0 */ + "movq %%rax, 0(%q6)\n" + /* Move to (r8,r9) */ + "movq %%rdx, %%r8\n" + "xorq %%r9, %%r9\n" + /* (r8,r9) += p1 */ + "addq %q2, %%r8\n" + "adcq $0, %%r9\n" + /* (r8,r9) += p4 * c1 */ + "movq %8, %%rax\n" + "mulq %%r10\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + /* Extract r1 */ + "movq %%r8, 8(%q6)\n" + "xorq %%r8, %%r8\n" + /* (r9,r8) += p4 */ + "addq %%r10, %%r9\n" + "adcq $0, %%r8\n" + /* (r9,r8) += p2 */ + "addq %q3, %%r9\n" + "adcq $0, %%r8\n" + /* Extract r2 */ + "movq %%r9, 16(%q6)\n" + "xorq %%r9, %%r9\n" + /* (r8,r9) += p3 */ + "addq %q4, %%r8\n" + "adcq $0, %%r9\n" + /* Extract r3 */ + "movq %%r8, 24(%q6)\n" + /* Extract c */ + "movq %%r9, %q0\n" + : "=g"(c) + : "g"(p0), "g"(p1), "g"(p2), "g"(p3), "g"(p4), "D"(r), "n"(SECP256K1_N_C_0), "n"(SECP256K1_N_C_1) + : "rax", "rdx", "r8", "r9", "r10", "cc", "memory"); +#else + uint128_t c; + uint64_t c0, c1, c2; + uint64_t n0 = l[4], n1 = l[5], n2 = l[6], n3 = l[7]; + uint64_t m0, m1, m2, m3, m4, m5; + uint32_t m6; + uint64_t p0, p1, p2, p3; + uint32_t p4; + + /* Reduce 512 bits into 385. */ + /* m[0..6] = l[0..3] + n[0..3] * SECP256K1_N_C. */ + c0 = l[0]; c1 = 0; c2 = 0; + muladd_fast(n0, SECP256K1_N_C_0); + extract_fast(m0); + sumadd_fast(l[1]); + muladd(n1, SECP256K1_N_C_0); + muladd(n0, SECP256K1_N_C_1); + extract(m1); + sumadd(l[2]); + muladd(n2, SECP256K1_N_C_0); + muladd(n1, SECP256K1_N_C_1); + sumadd(n0); + extract(m2); + sumadd(l[3]); + muladd(n3, SECP256K1_N_C_0); + muladd(n2, SECP256K1_N_C_1); + sumadd(n1); + extract(m3); + muladd(n3, SECP256K1_N_C_1); + sumadd(n2); + extract(m4); + sumadd_fast(n3); + extract_fast(m5); + VERIFY_CHECK(c0 <= 1); + m6 = (uint32_t)c0; + + /* Reduce 385 bits into 258. */ + /* p[0..4] = m[0..3] + m[4..6] * SECP256K1_N_C. */ + c0 = m0; c1 = 0; c2 = 0; + muladd_fast(m4, SECP256K1_N_C_0); + extract_fast(p0); + sumadd_fast(m1); + muladd(m5, SECP256K1_N_C_0); + muladd(m4, SECP256K1_N_C_1); + extract(p1); + sumadd(m2); + muladd(m6, SECP256K1_N_C_0); + muladd(m5, SECP256K1_N_C_1); + sumadd(m4); + extract(p2); + sumadd_fast(m3); + muladd_fast(m6, SECP256K1_N_C_1); + sumadd_fast(m5); + extract_fast(p3); + p4 = (uint32_t)c0 + m6; + VERIFY_CHECK(p4 <= 2); + + /* Reduce 258 bits into 256. */ + /* r[0..3] = p[0..3] + p[4] * SECP256K1_N_C. */ + c = p0 + (uint128_t)SECP256K1_N_C_0 * p4; + r->d[0] = c & 0xFFFFFFFFFFFFFFFFULL; c >>= 64; + c += p1 + (uint128_t)SECP256K1_N_C_1 * p4; + r->d[1] = c & 0xFFFFFFFFFFFFFFFFULL; c >>= 64; + c += p2 + (uint128_t)p4; + r->d[2] = c & 0xFFFFFFFFFFFFFFFFULL; c >>= 64; + c += p3; + r->d[3] = c & 0xFFFFFFFFFFFFFFFFULL; c >>= 64; +#endif + + /* Final reduction of r. */ + secp256k1_scalar_reduce(r, c + secp256k1_scalar_check_overflow(r)); +} + +static void secp256k1_scalar_mul_512(uint64_t l[8], const secp256k1_scalar *a, const secp256k1_scalar *b) { +#ifdef USE_ASM_X86_64 + const uint64_t *pb = b->d; + __asm__ __volatile__( + /* Preload */ + "movq 0(%%rdi), %%r15\n" + "movq 8(%%rdi), %%rbx\n" + "movq 16(%%rdi), %%rcx\n" + "movq 0(%%rdx), %%r11\n" + "movq 8(%%rdx), %%r12\n" + "movq 16(%%rdx), %%r13\n" + "movq 24(%%rdx), %%r14\n" + /* (rax,rdx) = a0 * b0 */ + "movq %%r15, %%rax\n" + "mulq %%r11\n" + /* Extract l0 */ + "movq %%rax, 0(%%rsi)\n" + /* (r8,r9,r10) = (rdx) */ + "movq %%rdx, %%r8\n" + "xorq %%r9, %%r9\n" + "xorq %%r10, %%r10\n" + /* (r8,r9,r10) += a0 * b1 */ + "movq %%r15, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* (r8,r9,r10) += a1 * b0 */ + "movq %%rbx, %%rax\n" + "mulq %%r11\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* Extract l1 */ + "movq %%r8, 8(%%rsi)\n" + "xorq %%r8, %%r8\n" + /* (r9,r10,r8) += a0 * b2 */ + "movq %%r15, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* (r9,r10,r8) += a1 * b1 */ + "movq %%rbx, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* (r9,r10,r8) += a2 * b0 */ + "movq %%rcx, %%rax\n" + "mulq %%r11\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* Extract l2 */ + "movq %%r9, 16(%%rsi)\n" + "xorq %%r9, %%r9\n" + /* (r10,r8,r9) += a0 * b3 */ + "movq %%r15, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* Preload a3 */ + "movq 24(%%rdi), %%r15\n" + /* (r10,r8,r9) += a1 * b2 */ + "movq %%rbx, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += a2 * b1 */ + "movq %%rcx, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += a3 * b0 */ + "movq %%r15, %%rax\n" + "mulq %%r11\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* Extract l3 */ + "movq %%r10, 24(%%rsi)\n" + "xorq %%r10, %%r10\n" + /* (r8,r9,r10) += a1 * b3 */ + "movq %%rbx, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* (r8,r9,r10) += a2 * b2 */ + "movq %%rcx, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* (r8,r9,r10) += a3 * b1 */ + "movq %%r15, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* Extract l4 */ + "movq %%r8, 32(%%rsi)\n" + "xorq %%r8, %%r8\n" + /* (r9,r10,r8) += a2 * b3 */ + "movq %%rcx, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* (r9,r10,r8) += a3 * b2 */ + "movq %%r15, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* Extract l5 */ + "movq %%r9, 40(%%rsi)\n" + /* (r10,r8) += a3 * b3 */ + "movq %%r15, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + /* Extract l6 */ + "movq %%r10, 48(%%rsi)\n" + /* Extract l7 */ + "movq %%r8, 56(%%rsi)\n" + : "+d"(pb) + : "S"(l), "D"(a->d) + : "rax", "rbx", "rcx", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "cc", "memory"); +#else + /* 160 bit accumulator. */ + uint64_t c0 = 0, c1 = 0; + uint32_t c2 = 0; + + /* l[0..7] = a[0..3] * b[0..3]. */ + muladd_fast(a->d[0], b->d[0]); + extract_fast(l[0]); + muladd(a->d[0], b->d[1]); + muladd(a->d[1], b->d[0]); + extract(l[1]); + muladd(a->d[0], b->d[2]); + muladd(a->d[1], b->d[1]); + muladd(a->d[2], b->d[0]); + extract(l[2]); + muladd(a->d[0], b->d[3]); + muladd(a->d[1], b->d[2]); + muladd(a->d[2], b->d[1]); + muladd(a->d[3], b->d[0]); + extract(l[3]); + muladd(a->d[1], b->d[3]); + muladd(a->d[2], b->d[2]); + muladd(a->d[3], b->d[1]); + extract(l[4]); + muladd(a->d[2], b->d[3]); + muladd(a->d[3], b->d[2]); + extract(l[5]); + muladd_fast(a->d[3], b->d[3]); + extract_fast(l[6]); + VERIFY_CHECK(c1 == 0); + l[7] = c0; +#endif +} + +static void secp256k1_scalar_sqr_512(uint64_t l[8], const secp256k1_scalar *a) { +#ifdef USE_ASM_X86_64 + __asm__ __volatile__( + /* Preload */ + "movq 0(%%rdi), %%r11\n" + "movq 8(%%rdi), %%r12\n" + "movq 16(%%rdi), %%r13\n" + "movq 24(%%rdi), %%r14\n" + /* (rax,rdx) = a0 * a0 */ + "movq %%r11, %%rax\n" + "mulq %%r11\n" + /* Extract l0 */ + "movq %%rax, 0(%%rsi)\n" + /* (r8,r9,r10) = (rdx,0) */ + "movq %%rdx, %%r8\n" + "xorq %%r9, %%r9\n" + "xorq %%r10, %%r10\n" + /* (r8,r9,r10) += 2 * a0 * a1 */ + "movq %%r11, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* Extract l1 */ + "movq %%r8, 8(%%rsi)\n" + "xorq %%r8, %%r8\n" + /* (r9,r10,r8) += 2 * a0 * a2 */ + "movq %%r11, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* (r9,r10,r8) += a1 * a1 */ + "movq %%r12, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* Extract l2 */ + "movq %%r9, 16(%%rsi)\n" + "xorq %%r9, %%r9\n" + /* (r10,r8,r9) += 2 * a0 * a3 */ + "movq %%r11, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += 2 * a1 * a2 */ + "movq %%r12, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* Extract l3 */ + "movq %%r10, 24(%%rsi)\n" + "xorq %%r10, %%r10\n" + /* (r8,r9,r10) += 2 * a1 * a3 */ + "movq %%r12, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* (r8,r9,r10) += a2 * a2 */ + "movq %%r13, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* Extract l4 */ + "movq %%r8, 32(%%rsi)\n" + "xorq %%r8, %%r8\n" + /* (r9,r10,r8) += 2 * a2 * a3 */ + "movq %%r13, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* Extract l5 */ + "movq %%r9, 40(%%rsi)\n" + /* (r10,r8) += a3 * a3 */ + "movq %%r14, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + /* Extract l6 */ + "movq %%r10, 48(%%rsi)\n" + /* Extract l7 */ + "movq %%r8, 56(%%rsi)\n" + : + : "S"(l), "D"(a->d) + : "rax", "rdx", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "cc", "memory"); +#else + /* 160 bit accumulator. */ + uint64_t c0 = 0, c1 = 0; + uint32_t c2 = 0; + + /* l[0..7] = a[0..3] * b[0..3]. */ + muladd_fast(a->d[0], a->d[0]); + extract_fast(l[0]); + muladd2(a->d[0], a->d[1]); + extract(l[1]); + muladd2(a->d[0], a->d[2]); + muladd(a->d[1], a->d[1]); + extract(l[2]); + muladd2(a->d[0], a->d[3]); + muladd2(a->d[1], a->d[2]); + extract(l[3]); + muladd2(a->d[1], a->d[3]); + muladd(a->d[2], a->d[2]); + extract(l[4]); + muladd2(a->d[2], a->d[3]); + extract(l[5]); + muladd_fast(a->d[3], a->d[3]); + extract_fast(l[6]); + VERIFY_CHECK(c1 == 0); + l[7] = c0; +#endif +} + +#undef sumadd +#undef sumadd_fast +#undef muladd +#undef muladd_fast +#undef muladd2 +#undef extract +#undef extract_fast + +static void secp256k1_scalar_mul(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b) { + uint64_t l[8]; + secp256k1_scalar_mul_512(l, a, b); + secp256k1_scalar_reduce_512(r, l); +} + +static int secp256k1_scalar_shr_int(secp256k1_scalar *r, int n) { + int ret; + VERIFY_CHECK(n > 0); + VERIFY_CHECK(n < 16); + ret = r->d[0] & ((1 << n) - 1); + r->d[0] = (r->d[0] >> n) + (r->d[1] << (64 - n)); + r->d[1] = (r->d[1] >> n) + (r->d[2] << (64 - n)); + r->d[2] = (r->d[2] >> n) + (r->d[3] << (64 - n)); + r->d[3] = (r->d[3] >> n); + return ret; +} + +static void secp256k1_scalar_sqr(secp256k1_scalar *r, const secp256k1_scalar *a) { + uint64_t l[8]; + secp256k1_scalar_sqr_512(l, a); + secp256k1_scalar_reduce_512(r, l); +} + +#ifdef USE_ENDOMORPHISM +static void secp256k1_scalar_split_128(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { + r1->d[0] = a->d[0]; + r1->d[1] = a->d[1]; + r1->d[2] = 0; + r1->d[3] = 0; + r2->d[0] = a->d[2]; + r2->d[1] = a->d[3]; + r2->d[2] = 0; + r2->d[3] = 0; +} +#endif + +SECP256K1_INLINE static int secp256k1_scalar_eq(const secp256k1_scalar *a, const secp256k1_scalar *b) { + return ((a->d[0] ^ b->d[0]) | (a->d[1] ^ b->d[1]) | (a->d[2] ^ b->d[2]) | (a->d[3] ^ b->d[3])) == 0; +} + +SECP256K1_INLINE static void secp256k1_scalar_mul_shift_var(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b, unsigned int shift) { + uint64_t l[8]; + unsigned int shiftlimbs; + unsigned int shiftlow; + unsigned int shifthigh; + VERIFY_CHECK(shift >= 256); + secp256k1_scalar_mul_512(l, a, b); + shiftlimbs = shift >> 6; + shiftlow = shift & 0x3F; + shifthigh = 64 - shiftlow; + r->d[0] = shift < 512 ? (l[0 + shiftlimbs] >> shiftlow | (shift < 448 && shiftlow ? (l[1 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[1] = shift < 448 ? (l[1 + shiftlimbs] >> shiftlow | (shift < 384 && shiftlow ? (l[2 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[2] = shift < 384 ? (l[2 + shiftlimbs] >> shiftlow | (shift < 320 && shiftlow ? (l[3 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[3] = shift < 320 ? (l[3 + shiftlimbs] >> shiftlow) : 0; + secp256k1_scalar_cadd_bit(r, 0, (l[(shift - 1) >> 6] >> ((shift - 1) & 0x3f)) & 1); +} + +#endif /* SECP256K1_SCALAR_REPR_IMPL_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_8x32.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_8x32.h new file mode 100644 index 000000000..2c9a348e2 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_8x32.h @@ -0,0 +1,19 @@ +/********************************************************************** + * Copyright (c) 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_REPR_H +#define SECP256K1_SCALAR_REPR_H + +#include + +/** A scalar modulo the group order of the secp256k1 curve. */ +typedef struct { + uint32_t d[8]; +} secp256k1_scalar; + +#define SECP256K1_SCALAR_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{(d0), (d1), (d2), (d3), (d4), (d5), (d6), (d7)}} + +#endif /* SECP256K1_SCALAR_REPR_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_8x32_impl.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_8x32_impl.h new file mode 100644 index 000000000..b2c0581cf --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_8x32_impl.h @@ -0,0 +1,721 @@ +/********************************************************************** + * Copyright (c) 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_REPR_IMPL_H +#define SECP256K1_SCALAR_REPR_IMPL_H + +/* Limbs of the secp256k1 order. */ +#define SECP256K1_N_0 ((uint32_t)0xD0364141UL) +#define SECP256K1_N_1 ((uint32_t)0xBFD25E8CUL) +#define SECP256K1_N_2 ((uint32_t)0xAF48A03BUL) +#define SECP256K1_N_3 ((uint32_t)0xBAAEDCE6UL) +#define SECP256K1_N_4 ((uint32_t)0xFFFFFFFEUL) +#define SECP256K1_N_5 ((uint32_t)0xFFFFFFFFUL) +#define SECP256K1_N_6 ((uint32_t)0xFFFFFFFFUL) +#define SECP256K1_N_7 ((uint32_t)0xFFFFFFFFUL) + +/* Limbs of 2^256 minus the secp256k1 order. */ +#define SECP256K1_N_C_0 (~SECP256K1_N_0 + 1) +#define SECP256K1_N_C_1 (~SECP256K1_N_1) +#define SECP256K1_N_C_2 (~SECP256K1_N_2) +#define SECP256K1_N_C_3 (~SECP256K1_N_3) +#define SECP256K1_N_C_4 (1) + +/* Limbs of half the secp256k1 order. */ +#define SECP256K1_N_H_0 ((uint32_t)0x681B20A0UL) +#define SECP256K1_N_H_1 ((uint32_t)0xDFE92F46UL) +#define SECP256K1_N_H_2 ((uint32_t)0x57A4501DUL) +#define SECP256K1_N_H_3 ((uint32_t)0x5D576E73UL) +#define SECP256K1_N_H_4 ((uint32_t)0xFFFFFFFFUL) +#define SECP256K1_N_H_5 ((uint32_t)0xFFFFFFFFUL) +#define SECP256K1_N_H_6 ((uint32_t)0xFFFFFFFFUL) +#define SECP256K1_N_H_7 ((uint32_t)0x7FFFFFFFUL) + +SECP256K1_INLINE static void secp256k1_scalar_clear(secp256k1_scalar *r) { + r->d[0] = 0; + r->d[1] = 0; + r->d[2] = 0; + r->d[3] = 0; + r->d[4] = 0; + r->d[5] = 0; + r->d[6] = 0; + r->d[7] = 0; +} + +SECP256K1_INLINE static void secp256k1_scalar_set_int(secp256k1_scalar *r, unsigned int v) { + r->d[0] = v; + r->d[1] = 0; + r->d[2] = 0; + r->d[3] = 0; + r->d[4] = 0; + r->d[5] = 0; + r->d[6] = 0; + r->d[7] = 0; +} + +SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits(const secp256k1_scalar *a, unsigned int offset, unsigned int count) { + VERIFY_CHECK((offset + count - 1) >> 5 == offset >> 5); + return (a->d[offset >> 5] >> (offset & 0x1F)) & ((1 << count) - 1); +} + +SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits_var(const secp256k1_scalar *a, unsigned int offset, unsigned int count) { + VERIFY_CHECK(count < 32); + VERIFY_CHECK(offset + count <= 256); + if ((offset + count - 1) >> 5 == offset >> 5) { + return secp256k1_scalar_get_bits(a, offset, count); + } else { + VERIFY_CHECK((offset >> 5) + 1 < 8); + return ((a->d[offset >> 5] >> (offset & 0x1F)) | (a->d[(offset >> 5) + 1] << (32 - (offset & 0x1F)))) & ((((uint32_t)1) << count) - 1); + } +} + +SECP256K1_INLINE static int secp256k1_scalar_check_overflow(const secp256k1_scalar *a) { + int yes = 0; + int no = 0; + no |= (a->d[7] < SECP256K1_N_7); /* No need for a > check. */ + no |= (a->d[6] < SECP256K1_N_6); /* No need for a > check. */ + no |= (a->d[5] < SECP256K1_N_5); /* No need for a > check. */ + no |= (a->d[4] < SECP256K1_N_4); + yes |= (a->d[4] > SECP256K1_N_4) & ~no; + no |= (a->d[3] < SECP256K1_N_3) & ~yes; + yes |= (a->d[3] > SECP256K1_N_3) & ~no; + no |= (a->d[2] < SECP256K1_N_2) & ~yes; + yes |= (a->d[2] > SECP256K1_N_2) & ~no; + no |= (a->d[1] < SECP256K1_N_1) & ~yes; + yes |= (a->d[1] > SECP256K1_N_1) & ~no; + yes |= (a->d[0] >= SECP256K1_N_0) & ~no; + return yes; +} + +SECP256K1_INLINE static int secp256k1_scalar_reduce(secp256k1_scalar *r, uint32_t overflow) { + uint64_t t; + VERIFY_CHECK(overflow <= 1); + t = (uint64_t)r->d[0] + overflow * SECP256K1_N_C_0; + r->d[0] = t & 0xFFFFFFFFUL; t >>= 32; + t += (uint64_t)r->d[1] + overflow * SECP256K1_N_C_1; + r->d[1] = t & 0xFFFFFFFFUL; t >>= 32; + t += (uint64_t)r->d[2] + overflow * SECP256K1_N_C_2; + r->d[2] = t & 0xFFFFFFFFUL; t >>= 32; + t += (uint64_t)r->d[3] + overflow * SECP256K1_N_C_3; + r->d[3] = t & 0xFFFFFFFFUL; t >>= 32; + t += (uint64_t)r->d[4] + overflow * SECP256K1_N_C_4; + r->d[4] = t & 0xFFFFFFFFUL; t >>= 32; + t += (uint64_t)r->d[5]; + r->d[5] = t & 0xFFFFFFFFUL; t >>= 32; + t += (uint64_t)r->d[6]; + r->d[6] = t & 0xFFFFFFFFUL; t >>= 32; + t += (uint64_t)r->d[7]; + r->d[7] = t & 0xFFFFFFFFUL; + return overflow; +} + +static int secp256k1_scalar_add(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b) { + int overflow; + uint64_t t = (uint64_t)a->d[0] + b->d[0]; + r->d[0] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)a->d[1] + b->d[1]; + r->d[1] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)a->d[2] + b->d[2]; + r->d[2] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)a->d[3] + b->d[3]; + r->d[3] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)a->d[4] + b->d[4]; + r->d[4] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)a->d[5] + b->d[5]; + r->d[5] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)a->d[6] + b->d[6]; + r->d[6] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)a->d[7] + b->d[7]; + r->d[7] = t & 0xFFFFFFFFULL; t >>= 32; + overflow = (int)t + secp256k1_scalar_check_overflow(r); + VERIFY_CHECK(overflow == 0 || overflow == 1); + secp256k1_scalar_reduce(r, overflow); + return overflow; +} + +static void secp256k1_scalar_cadd_bit(secp256k1_scalar *r, unsigned int bit, int flag) { + uint64_t t; + VERIFY_CHECK(bit < 256); + bit += ((uint32_t) flag - 1) & 0x100; /* forcing (bit >> 5) > 7 makes this a noop */ + t = (uint64_t)r->d[0] + (((uint32_t)((bit >> 5) == 0)) << (bit & 0x1F)); + r->d[0] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)r->d[1] + (((uint32_t)((bit >> 5) == 1)) << (bit & 0x1F)); + r->d[1] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)r->d[2] + (((uint32_t)((bit >> 5) == 2)) << (bit & 0x1F)); + r->d[2] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)r->d[3] + (((uint32_t)((bit >> 5) == 3)) << (bit & 0x1F)); + r->d[3] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)r->d[4] + (((uint32_t)((bit >> 5) == 4)) << (bit & 0x1F)); + r->d[4] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)r->d[5] + (((uint32_t)((bit >> 5) == 5)) << (bit & 0x1F)); + r->d[5] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)r->d[6] + (((uint32_t)((bit >> 5) == 6)) << (bit & 0x1F)); + r->d[6] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)r->d[7] + (((uint32_t)((bit >> 5) == 7)) << (bit & 0x1F)); + r->d[7] = t & 0xFFFFFFFFULL; +#ifdef VERIFY + VERIFY_CHECK((t >> 32) == 0); + VERIFY_CHECK(secp256k1_scalar_check_overflow(r) == 0); +#endif +} + +static void secp256k1_scalar_set_b32(secp256k1_scalar *r, const unsigned char *b32, int *overflow) { + int over; + r->d[0] = (uint32_t)b32[31] | (uint32_t)b32[30] << 8 | (uint32_t)b32[29] << 16 | (uint32_t)b32[28] << 24; + r->d[1] = (uint32_t)b32[27] | (uint32_t)b32[26] << 8 | (uint32_t)b32[25] << 16 | (uint32_t)b32[24] << 24; + r->d[2] = (uint32_t)b32[23] | (uint32_t)b32[22] << 8 | (uint32_t)b32[21] << 16 | (uint32_t)b32[20] << 24; + r->d[3] = (uint32_t)b32[19] | (uint32_t)b32[18] << 8 | (uint32_t)b32[17] << 16 | (uint32_t)b32[16] << 24; + r->d[4] = (uint32_t)b32[15] | (uint32_t)b32[14] << 8 | (uint32_t)b32[13] << 16 | (uint32_t)b32[12] << 24; + r->d[5] = (uint32_t)b32[11] | (uint32_t)b32[10] << 8 | (uint32_t)b32[9] << 16 | (uint32_t)b32[8] << 24; + r->d[6] = (uint32_t)b32[7] | (uint32_t)b32[6] << 8 | (uint32_t)b32[5] << 16 | (uint32_t)b32[4] << 24; + r->d[7] = (uint32_t)b32[3] | (uint32_t)b32[2] << 8 | (uint32_t)b32[1] << 16 | (uint32_t)b32[0] << 24; + over = secp256k1_scalar_reduce(r, secp256k1_scalar_check_overflow(r)); + if (overflow) { + *overflow = over; + } +} + +static void secp256k1_scalar_get_b32(unsigned char *bin, const secp256k1_scalar* a) { + bin[0] = a->d[7] >> 24; bin[1] = a->d[7] >> 16; bin[2] = a->d[7] >> 8; bin[3] = a->d[7]; + bin[4] = a->d[6] >> 24; bin[5] = a->d[6] >> 16; bin[6] = a->d[6] >> 8; bin[7] = a->d[6]; + bin[8] = a->d[5] >> 24; bin[9] = a->d[5] >> 16; bin[10] = a->d[5] >> 8; bin[11] = a->d[5]; + bin[12] = a->d[4] >> 24; bin[13] = a->d[4] >> 16; bin[14] = a->d[4] >> 8; bin[15] = a->d[4]; + bin[16] = a->d[3] >> 24; bin[17] = a->d[3] >> 16; bin[18] = a->d[3] >> 8; bin[19] = a->d[3]; + bin[20] = a->d[2] >> 24; bin[21] = a->d[2] >> 16; bin[22] = a->d[2] >> 8; bin[23] = a->d[2]; + bin[24] = a->d[1] >> 24; bin[25] = a->d[1] >> 16; bin[26] = a->d[1] >> 8; bin[27] = a->d[1]; + bin[28] = a->d[0] >> 24; bin[29] = a->d[0] >> 16; bin[30] = a->d[0] >> 8; bin[31] = a->d[0]; +} + +SECP256K1_INLINE static int secp256k1_scalar_is_zero(const secp256k1_scalar *a) { + return (a->d[0] | a->d[1] | a->d[2] | a->d[3] | a->d[4] | a->d[5] | a->d[6] | a->d[7]) == 0; +} + +static void secp256k1_scalar_negate(secp256k1_scalar *r, const secp256k1_scalar *a) { + uint32_t nonzero = 0xFFFFFFFFUL * (secp256k1_scalar_is_zero(a) == 0); + uint64_t t = (uint64_t)(~a->d[0]) + SECP256K1_N_0 + 1; + r->d[0] = t & nonzero; t >>= 32; + t += (uint64_t)(~a->d[1]) + SECP256K1_N_1; + r->d[1] = t & nonzero; t >>= 32; + t += (uint64_t)(~a->d[2]) + SECP256K1_N_2; + r->d[2] = t & nonzero; t >>= 32; + t += (uint64_t)(~a->d[3]) + SECP256K1_N_3; + r->d[3] = t & nonzero; t >>= 32; + t += (uint64_t)(~a->d[4]) + SECP256K1_N_4; + r->d[4] = t & nonzero; t >>= 32; + t += (uint64_t)(~a->d[5]) + SECP256K1_N_5; + r->d[5] = t & nonzero; t >>= 32; + t += (uint64_t)(~a->d[6]) + SECP256K1_N_6; + r->d[6] = t & nonzero; t >>= 32; + t += (uint64_t)(~a->d[7]) + SECP256K1_N_7; + r->d[7] = t & nonzero; +} + +SECP256K1_INLINE static int secp256k1_scalar_is_one(const secp256k1_scalar *a) { + return ((a->d[0] ^ 1) | a->d[1] | a->d[2] | a->d[3] | a->d[4] | a->d[5] | a->d[6] | a->d[7]) == 0; +} + +static int secp256k1_scalar_is_high(const secp256k1_scalar *a) { + int yes = 0; + int no = 0; + no |= (a->d[7] < SECP256K1_N_H_7); + yes |= (a->d[7] > SECP256K1_N_H_7) & ~no; + no |= (a->d[6] < SECP256K1_N_H_6) & ~yes; /* No need for a > check. */ + no |= (a->d[5] < SECP256K1_N_H_5) & ~yes; /* No need for a > check. */ + no |= (a->d[4] < SECP256K1_N_H_4) & ~yes; /* No need for a > check. */ + no |= (a->d[3] < SECP256K1_N_H_3) & ~yes; + yes |= (a->d[3] > SECP256K1_N_H_3) & ~no; + no |= (a->d[2] < SECP256K1_N_H_2) & ~yes; + yes |= (a->d[2] > SECP256K1_N_H_2) & ~no; + no |= (a->d[1] < SECP256K1_N_H_1) & ~yes; + yes |= (a->d[1] > SECP256K1_N_H_1) & ~no; + yes |= (a->d[0] > SECP256K1_N_H_0) & ~no; + return yes; +} + +static int secp256k1_scalar_cond_negate(secp256k1_scalar *r, int flag) { + /* If we are flag = 0, mask = 00...00 and this is a no-op; + * if we are flag = 1, mask = 11...11 and this is identical to secp256k1_scalar_negate */ + uint32_t mask = !flag - 1; + uint32_t nonzero = 0xFFFFFFFFUL * (secp256k1_scalar_is_zero(r) == 0); + uint64_t t = (uint64_t)(r->d[0] ^ mask) + ((SECP256K1_N_0 + 1) & mask); + r->d[0] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[1] ^ mask) + (SECP256K1_N_1 & mask); + r->d[1] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[2] ^ mask) + (SECP256K1_N_2 & mask); + r->d[2] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[3] ^ mask) + (SECP256K1_N_3 & mask); + r->d[3] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[4] ^ mask) + (SECP256K1_N_4 & mask); + r->d[4] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[5] ^ mask) + (SECP256K1_N_5 & mask); + r->d[5] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[6] ^ mask) + (SECP256K1_N_6 & mask); + r->d[6] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[7] ^ mask) + (SECP256K1_N_7 & mask); + r->d[7] = t & nonzero; + return 2 * (mask == 0) - 1; +} + + +/* Inspired by the macros in OpenSSL's crypto/bn/asm/x86_64-gcc.c. */ + +/** Add a*b to the number defined by (c0,c1,c2). c2 must never overflow. */ +#define muladd(a,b) { \ + uint32_t tl, th; \ + { \ + uint64_t t = (uint64_t)a * b; \ + th = t >> 32; /* at most 0xFFFFFFFE */ \ + tl = t; \ + } \ + c0 += tl; /* overflow is handled on the next line */ \ + th += (c0 < tl) ? 1 : 0; /* at most 0xFFFFFFFF */ \ + c1 += th; /* overflow is handled on the next line */ \ + c2 += (c1 < th) ? 1 : 0; /* never overflows by contract (verified in the next line) */ \ + VERIFY_CHECK((c1 >= th) || (c2 != 0)); \ +} + +/** Add a*b to the number defined by (c0,c1). c1 must never overflow. */ +#define muladd_fast(a,b) { \ + uint32_t tl, th; \ + { \ + uint64_t t = (uint64_t)a * b; \ + th = t >> 32; /* at most 0xFFFFFFFE */ \ + tl = t; \ + } \ + c0 += tl; /* overflow is handled on the next line */ \ + th += (c0 < tl) ? 1 : 0; /* at most 0xFFFFFFFF */ \ + c1 += th; /* never overflows by contract (verified in the next line) */ \ + VERIFY_CHECK(c1 >= th); \ +} + +/** Add 2*a*b to the number defined by (c0,c1,c2). c2 must never overflow. */ +#define muladd2(a,b) { \ + uint32_t tl, th, th2, tl2; \ + { \ + uint64_t t = (uint64_t)a * b; \ + th = t >> 32; /* at most 0xFFFFFFFE */ \ + tl = t; \ + } \ + th2 = th + th; /* at most 0xFFFFFFFE (in case th was 0x7FFFFFFF) */ \ + c2 += (th2 < th) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ + VERIFY_CHECK((th2 >= th) || (c2 != 0)); \ + tl2 = tl + tl; /* at most 0xFFFFFFFE (in case the lowest 63 bits of tl were 0x7FFFFFFF) */ \ + th2 += (tl2 < tl) ? 1 : 0; /* at most 0xFFFFFFFF */ \ + c0 += tl2; /* overflow is handled on the next line */ \ + th2 += (c0 < tl2) ? 1 : 0; /* second overflow is handled on the next line */ \ + c2 += (c0 < tl2) & (th2 == 0); /* never overflows by contract (verified the next line) */ \ + VERIFY_CHECK((c0 >= tl2) || (th2 != 0) || (c2 != 0)); \ + c1 += th2; /* overflow is handled on the next line */ \ + c2 += (c1 < th2) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ + VERIFY_CHECK((c1 >= th2) || (c2 != 0)); \ +} + +/** Add a to the number defined by (c0,c1,c2). c2 must never overflow. */ +#define sumadd(a) { \ + unsigned int over; \ + c0 += (a); /* overflow is handled on the next line */ \ + over = (c0 < (a)) ? 1 : 0; \ + c1 += over; /* overflow is handled on the next line */ \ + c2 += (c1 < over) ? 1 : 0; /* never overflows by contract */ \ +} + +/** Add a to the number defined by (c0,c1). c1 must never overflow, c2 must be zero. */ +#define sumadd_fast(a) { \ + c0 += (a); /* overflow is handled on the next line */ \ + c1 += (c0 < (a)) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ + VERIFY_CHECK((c1 != 0) | (c0 >= (a))); \ + VERIFY_CHECK(c2 == 0); \ +} + +/** Extract the lowest 32 bits of (c0,c1,c2) into n, and left shift the number 32 bits. */ +#define extract(n) { \ + (n) = c0; \ + c0 = c1; \ + c1 = c2; \ + c2 = 0; \ +} + +/** Extract the lowest 32 bits of (c0,c1,c2) into n, and left shift the number 32 bits. c2 is required to be zero. */ +#define extract_fast(n) { \ + (n) = c0; \ + c0 = c1; \ + c1 = 0; \ + VERIFY_CHECK(c2 == 0); \ +} + +static void secp256k1_scalar_reduce_512(secp256k1_scalar *r, const uint32_t *l) { + uint64_t c; + uint32_t n0 = l[8], n1 = l[9], n2 = l[10], n3 = l[11], n4 = l[12], n5 = l[13], n6 = l[14], n7 = l[15]; + uint32_t m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12; + uint32_t p0, p1, p2, p3, p4, p5, p6, p7, p8; + + /* 96 bit accumulator. */ + uint32_t c0, c1, c2; + + /* Reduce 512 bits into 385. */ + /* m[0..12] = l[0..7] + n[0..7] * SECP256K1_N_C. */ + c0 = l[0]; c1 = 0; c2 = 0; + muladd_fast(n0, SECP256K1_N_C_0); + extract_fast(m0); + sumadd_fast(l[1]); + muladd(n1, SECP256K1_N_C_0); + muladd(n0, SECP256K1_N_C_1); + extract(m1); + sumadd(l[2]); + muladd(n2, SECP256K1_N_C_0); + muladd(n1, SECP256K1_N_C_1); + muladd(n0, SECP256K1_N_C_2); + extract(m2); + sumadd(l[3]); + muladd(n3, SECP256K1_N_C_0); + muladd(n2, SECP256K1_N_C_1); + muladd(n1, SECP256K1_N_C_2); + muladd(n0, SECP256K1_N_C_3); + extract(m3); + sumadd(l[4]); + muladd(n4, SECP256K1_N_C_0); + muladd(n3, SECP256K1_N_C_1); + muladd(n2, SECP256K1_N_C_2); + muladd(n1, SECP256K1_N_C_3); + sumadd(n0); + extract(m4); + sumadd(l[5]); + muladd(n5, SECP256K1_N_C_0); + muladd(n4, SECP256K1_N_C_1); + muladd(n3, SECP256K1_N_C_2); + muladd(n2, SECP256K1_N_C_3); + sumadd(n1); + extract(m5); + sumadd(l[6]); + muladd(n6, SECP256K1_N_C_0); + muladd(n5, SECP256K1_N_C_1); + muladd(n4, SECP256K1_N_C_2); + muladd(n3, SECP256K1_N_C_3); + sumadd(n2); + extract(m6); + sumadd(l[7]); + muladd(n7, SECP256K1_N_C_0); + muladd(n6, SECP256K1_N_C_1); + muladd(n5, SECP256K1_N_C_2); + muladd(n4, SECP256K1_N_C_3); + sumadd(n3); + extract(m7); + muladd(n7, SECP256K1_N_C_1); + muladd(n6, SECP256K1_N_C_2); + muladd(n5, SECP256K1_N_C_3); + sumadd(n4); + extract(m8); + muladd(n7, SECP256K1_N_C_2); + muladd(n6, SECP256K1_N_C_3); + sumadd(n5); + extract(m9); + muladd(n7, SECP256K1_N_C_3); + sumadd(n6); + extract(m10); + sumadd_fast(n7); + extract_fast(m11); + VERIFY_CHECK(c0 <= 1); + m12 = c0; + + /* Reduce 385 bits into 258. */ + /* p[0..8] = m[0..7] + m[8..12] * SECP256K1_N_C. */ + c0 = m0; c1 = 0; c2 = 0; + muladd_fast(m8, SECP256K1_N_C_0); + extract_fast(p0); + sumadd_fast(m1); + muladd(m9, SECP256K1_N_C_0); + muladd(m8, SECP256K1_N_C_1); + extract(p1); + sumadd(m2); + muladd(m10, SECP256K1_N_C_0); + muladd(m9, SECP256K1_N_C_1); + muladd(m8, SECP256K1_N_C_2); + extract(p2); + sumadd(m3); + muladd(m11, SECP256K1_N_C_0); + muladd(m10, SECP256K1_N_C_1); + muladd(m9, SECP256K1_N_C_2); + muladd(m8, SECP256K1_N_C_3); + extract(p3); + sumadd(m4); + muladd(m12, SECP256K1_N_C_0); + muladd(m11, SECP256K1_N_C_1); + muladd(m10, SECP256K1_N_C_2); + muladd(m9, SECP256K1_N_C_3); + sumadd(m8); + extract(p4); + sumadd(m5); + muladd(m12, SECP256K1_N_C_1); + muladd(m11, SECP256K1_N_C_2); + muladd(m10, SECP256K1_N_C_3); + sumadd(m9); + extract(p5); + sumadd(m6); + muladd(m12, SECP256K1_N_C_2); + muladd(m11, SECP256K1_N_C_3); + sumadd(m10); + extract(p6); + sumadd_fast(m7); + muladd_fast(m12, SECP256K1_N_C_3); + sumadd_fast(m11); + extract_fast(p7); + p8 = c0 + m12; + VERIFY_CHECK(p8 <= 2); + + /* Reduce 258 bits into 256. */ + /* r[0..7] = p[0..7] + p[8] * SECP256K1_N_C. */ + c = p0 + (uint64_t)SECP256K1_N_C_0 * p8; + r->d[0] = c & 0xFFFFFFFFUL; c >>= 32; + c += p1 + (uint64_t)SECP256K1_N_C_1 * p8; + r->d[1] = c & 0xFFFFFFFFUL; c >>= 32; + c += p2 + (uint64_t)SECP256K1_N_C_2 * p8; + r->d[2] = c & 0xFFFFFFFFUL; c >>= 32; + c += p3 + (uint64_t)SECP256K1_N_C_3 * p8; + r->d[3] = c & 0xFFFFFFFFUL; c >>= 32; + c += p4 + (uint64_t)p8; + r->d[4] = c & 0xFFFFFFFFUL; c >>= 32; + c += p5; + r->d[5] = c & 0xFFFFFFFFUL; c >>= 32; + c += p6; + r->d[6] = c & 0xFFFFFFFFUL; c >>= 32; + c += p7; + r->d[7] = c & 0xFFFFFFFFUL; c >>= 32; + + /* Final reduction of r. */ + secp256k1_scalar_reduce(r, c + secp256k1_scalar_check_overflow(r)); +} + +static void secp256k1_scalar_mul_512(uint32_t *l, const secp256k1_scalar *a, const secp256k1_scalar *b) { + /* 96 bit accumulator. */ + uint32_t c0 = 0, c1 = 0, c2 = 0; + + /* l[0..15] = a[0..7] * b[0..7]. */ + muladd_fast(a->d[0], b->d[0]); + extract_fast(l[0]); + muladd(a->d[0], b->d[1]); + muladd(a->d[1], b->d[0]); + extract(l[1]); + muladd(a->d[0], b->d[2]); + muladd(a->d[1], b->d[1]); + muladd(a->d[2], b->d[0]); + extract(l[2]); + muladd(a->d[0], b->d[3]); + muladd(a->d[1], b->d[2]); + muladd(a->d[2], b->d[1]); + muladd(a->d[3], b->d[0]); + extract(l[3]); + muladd(a->d[0], b->d[4]); + muladd(a->d[1], b->d[3]); + muladd(a->d[2], b->d[2]); + muladd(a->d[3], b->d[1]); + muladd(a->d[4], b->d[0]); + extract(l[4]); + muladd(a->d[0], b->d[5]); + muladd(a->d[1], b->d[4]); + muladd(a->d[2], b->d[3]); + muladd(a->d[3], b->d[2]); + muladd(a->d[4], b->d[1]); + muladd(a->d[5], b->d[0]); + extract(l[5]); + muladd(a->d[0], b->d[6]); + muladd(a->d[1], b->d[5]); + muladd(a->d[2], b->d[4]); + muladd(a->d[3], b->d[3]); + muladd(a->d[4], b->d[2]); + muladd(a->d[5], b->d[1]); + muladd(a->d[6], b->d[0]); + extract(l[6]); + muladd(a->d[0], b->d[7]); + muladd(a->d[1], b->d[6]); + muladd(a->d[2], b->d[5]); + muladd(a->d[3], b->d[4]); + muladd(a->d[4], b->d[3]); + muladd(a->d[5], b->d[2]); + muladd(a->d[6], b->d[1]); + muladd(a->d[7], b->d[0]); + extract(l[7]); + muladd(a->d[1], b->d[7]); + muladd(a->d[2], b->d[6]); + muladd(a->d[3], b->d[5]); + muladd(a->d[4], b->d[4]); + muladd(a->d[5], b->d[3]); + muladd(a->d[6], b->d[2]); + muladd(a->d[7], b->d[1]); + extract(l[8]); + muladd(a->d[2], b->d[7]); + muladd(a->d[3], b->d[6]); + muladd(a->d[4], b->d[5]); + muladd(a->d[5], b->d[4]); + muladd(a->d[6], b->d[3]); + muladd(a->d[7], b->d[2]); + extract(l[9]); + muladd(a->d[3], b->d[7]); + muladd(a->d[4], b->d[6]); + muladd(a->d[5], b->d[5]); + muladd(a->d[6], b->d[4]); + muladd(a->d[7], b->d[3]); + extract(l[10]); + muladd(a->d[4], b->d[7]); + muladd(a->d[5], b->d[6]); + muladd(a->d[6], b->d[5]); + muladd(a->d[7], b->d[4]); + extract(l[11]); + muladd(a->d[5], b->d[7]); + muladd(a->d[6], b->d[6]); + muladd(a->d[7], b->d[5]); + extract(l[12]); + muladd(a->d[6], b->d[7]); + muladd(a->d[7], b->d[6]); + extract(l[13]); + muladd_fast(a->d[7], b->d[7]); + extract_fast(l[14]); + VERIFY_CHECK(c1 == 0); + l[15] = c0; +} + +static void secp256k1_scalar_sqr_512(uint32_t *l, const secp256k1_scalar *a) { + /* 96 bit accumulator. */ + uint32_t c0 = 0, c1 = 0, c2 = 0; + + /* l[0..15] = a[0..7]^2. */ + muladd_fast(a->d[0], a->d[0]); + extract_fast(l[0]); + muladd2(a->d[0], a->d[1]); + extract(l[1]); + muladd2(a->d[0], a->d[2]); + muladd(a->d[1], a->d[1]); + extract(l[2]); + muladd2(a->d[0], a->d[3]); + muladd2(a->d[1], a->d[2]); + extract(l[3]); + muladd2(a->d[0], a->d[4]); + muladd2(a->d[1], a->d[3]); + muladd(a->d[2], a->d[2]); + extract(l[4]); + muladd2(a->d[0], a->d[5]); + muladd2(a->d[1], a->d[4]); + muladd2(a->d[2], a->d[3]); + extract(l[5]); + muladd2(a->d[0], a->d[6]); + muladd2(a->d[1], a->d[5]); + muladd2(a->d[2], a->d[4]); + muladd(a->d[3], a->d[3]); + extract(l[6]); + muladd2(a->d[0], a->d[7]); + muladd2(a->d[1], a->d[6]); + muladd2(a->d[2], a->d[5]); + muladd2(a->d[3], a->d[4]); + extract(l[7]); + muladd2(a->d[1], a->d[7]); + muladd2(a->d[2], a->d[6]); + muladd2(a->d[3], a->d[5]); + muladd(a->d[4], a->d[4]); + extract(l[8]); + muladd2(a->d[2], a->d[7]); + muladd2(a->d[3], a->d[6]); + muladd2(a->d[4], a->d[5]); + extract(l[9]); + muladd2(a->d[3], a->d[7]); + muladd2(a->d[4], a->d[6]); + muladd(a->d[5], a->d[5]); + extract(l[10]); + muladd2(a->d[4], a->d[7]); + muladd2(a->d[5], a->d[6]); + extract(l[11]); + muladd2(a->d[5], a->d[7]); + muladd(a->d[6], a->d[6]); + extract(l[12]); + muladd2(a->d[6], a->d[7]); + extract(l[13]); + muladd_fast(a->d[7], a->d[7]); + extract_fast(l[14]); + VERIFY_CHECK(c1 == 0); + l[15] = c0; +} + +#undef sumadd +#undef sumadd_fast +#undef muladd +#undef muladd_fast +#undef muladd2 +#undef extract +#undef extract_fast + +static void secp256k1_scalar_mul(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b) { + uint32_t l[16]; + secp256k1_scalar_mul_512(l, a, b); + secp256k1_scalar_reduce_512(r, l); +} + +static int secp256k1_scalar_shr_int(secp256k1_scalar *r, int n) { + int ret; + VERIFY_CHECK(n > 0); + VERIFY_CHECK(n < 16); + ret = r->d[0] & ((1 << n) - 1); + r->d[0] = (r->d[0] >> n) + (r->d[1] << (32 - n)); + r->d[1] = (r->d[1] >> n) + (r->d[2] << (32 - n)); + r->d[2] = (r->d[2] >> n) + (r->d[3] << (32 - n)); + r->d[3] = (r->d[3] >> n) + (r->d[4] << (32 - n)); + r->d[4] = (r->d[4] >> n) + (r->d[5] << (32 - n)); + r->d[5] = (r->d[5] >> n) + (r->d[6] << (32 - n)); + r->d[6] = (r->d[6] >> n) + (r->d[7] << (32 - n)); + r->d[7] = (r->d[7] >> n); + return ret; +} + +static void secp256k1_scalar_sqr(secp256k1_scalar *r, const secp256k1_scalar *a) { + uint32_t l[16]; + secp256k1_scalar_sqr_512(l, a); + secp256k1_scalar_reduce_512(r, l); +} + +#ifdef USE_ENDOMORPHISM +static void secp256k1_scalar_split_128(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { + r1->d[0] = a->d[0]; + r1->d[1] = a->d[1]; + r1->d[2] = a->d[2]; + r1->d[3] = a->d[3]; + r1->d[4] = 0; + r1->d[5] = 0; + r1->d[6] = 0; + r1->d[7] = 0; + r2->d[0] = a->d[4]; + r2->d[1] = a->d[5]; + r2->d[2] = a->d[6]; + r2->d[3] = a->d[7]; + r2->d[4] = 0; + r2->d[5] = 0; + r2->d[6] = 0; + r2->d[7] = 0; +} +#endif + +SECP256K1_INLINE static int secp256k1_scalar_eq(const secp256k1_scalar *a, const secp256k1_scalar *b) { + return ((a->d[0] ^ b->d[0]) | (a->d[1] ^ b->d[1]) | (a->d[2] ^ b->d[2]) | (a->d[3] ^ b->d[3]) | (a->d[4] ^ b->d[4]) | (a->d[5] ^ b->d[5]) | (a->d[6] ^ b->d[6]) | (a->d[7] ^ b->d[7])) == 0; +} + +SECP256K1_INLINE static void secp256k1_scalar_mul_shift_var(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b, unsigned int shift) { + uint32_t l[16]; + unsigned int shiftlimbs; + unsigned int shiftlow; + unsigned int shifthigh; + VERIFY_CHECK(shift >= 256); + secp256k1_scalar_mul_512(l, a, b); + shiftlimbs = shift >> 5; + shiftlow = shift & 0x1F; + shifthigh = 32 - shiftlow; + r->d[0] = shift < 512 ? (l[0 + shiftlimbs] >> shiftlow | (shift < 480 && shiftlow ? (l[1 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[1] = shift < 480 ? (l[1 + shiftlimbs] >> shiftlow | (shift < 448 && shiftlow ? (l[2 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[2] = shift < 448 ? (l[2 + shiftlimbs] >> shiftlow | (shift < 416 && shiftlow ? (l[3 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[3] = shift < 416 ? (l[3 + shiftlimbs] >> shiftlow | (shift < 384 && shiftlow ? (l[4 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[4] = shift < 384 ? (l[4 + shiftlimbs] >> shiftlow | (shift < 352 && shiftlow ? (l[5 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[5] = shift < 352 ? (l[5 + shiftlimbs] >> shiftlow | (shift < 320 && shiftlow ? (l[6 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[6] = shift < 320 ? (l[6 + shiftlimbs] >> shiftlow | (shift < 288 && shiftlow ? (l[7 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[7] = shift < 288 ? (l[7 + shiftlimbs] >> shiftlow) : 0; + secp256k1_scalar_cadd_bit(r, 0, (l[(shift - 1) >> 5] >> ((shift - 1) & 0x1f)) & 1); +} + +#endif /* SECP256K1_SCALAR_REPR_IMPL_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_impl.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_impl.h new file mode 100644 index 000000000..732d7c854 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_impl.h @@ -0,0 +1,331 @@ +/********************************************************************** + * Copyright (c) 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_IMPL_H +#define SECP256K1_SCALAR_IMPL_H + +#include "group.h" +#include "scalar.h" + +#include "secp256k1-config.h" + +#if defined(EXHAUSTIVE_TEST_ORDER) +#include "scalar_low_impl.h" +#elif defined(USE_SCALAR_4X64) +#include "scalar_4x64_impl.h" +#elif defined(USE_SCALAR_8X32) +#include "scalar_8x32_impl.h" +#else +#error "Please select scalar implementation" +#endif + +#ifndef USE_NUM_NONE +static void secp256k1_scalar_get_num(secp256k1_num *r, const secp256k1_scalar *a) { + unsigned char c[32]; + secp256k1_scalar_get_b32(c, a); + secp256k1_num_set_bin(r, c, 32); +} + +/** secp256k1 curve order, see secp256k1_ecdsa_const_order_as_fe in ecdsa_impl.h */ +static void secp256k1_scalar_order_get_num(secp256k1_num *r) { +#if defined(EXHAUSTIVE_TEST_ORDER) + static const unsigned char order[32] = { + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,EXHAUSTIVE_TEST_ORDER + }; +#else + static const unsigned char order[32] = { + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE, + 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B, + 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x41 + }; +#endif + secp256k1_num_set_bin(r, order, 32); +} +#endif + +static void secp256k1_scalar_inverse(secp256k1_scalar *r, const secp256k1_scalar *x) { +#if defined(EXHAUSTIVE_TEST_ORDER) + int i; + *r = 0; + for (i = 0; i < EXHAUSTIVE_TEST_ORDER; i++) + if ((i * *x) % EXHAUSTIVE_TEST_ORDER == 1) + *r = i; + /* If this VERIFY_CHECK triggers we were given a noninvertible scalar (and thus + * have a composite group order; fix it in exhaustive_tests.c). */ + VERIFY_CHECK(*r != 0); +} +#else + secp256k1_scalar *t; + int i; + /* First compute xN as x ^ (2^N - 1) for some values of N, + * and uM as x ^ M for some values of M. */ + secp256k1_scalar x2, x3, x6, x8, x14, x28, x56, x112, x126; + secp256k1_scalar u2, u5, u9, u11, u13; + + secp256k1_scalar_sqr(&u2, x); + secp256k1_scalar_mul(&x2, &u2, x); + secp256k1_scalar_mul(&u5, &u2, &x2); + secp256k1_scalar_mul(&x3, &u5, &u2); + secp256k1_scalar_mul(&u9, &x3, &u2); + secp256k1_scalar_mul(&u11, &u9, &u2); + secp256k1_scalar_mul(&u13, &u11, &u2); + + secp256k1_scalar_sqr(&x6, &u13); + secp256k1_scalar_sqr(&x6, &x6); + secp256k1_scalar_mul(&x6, &x6, &u11); + + secp256k1_scalar_sqr(&x8, &x6); + secp256k1_scalar_sqr(&x8, &x8); + secp256k1_scalar_mul(&x8, &x8, &x2); + + secp256k1_scalar_sqr(&x14, &x8); + for (i = 0; i < 5; i++) { + secp256k1_scalar_sqr(&x14, &x14); + } + secp256k1_scalar_mul(&x14, &x14, &x6); + + secp256k1_scalar_sqr(&x28, &x14); + for (i = 0; i < 13; i++) { + secp256k1_scalar_sqr(&x28, &x28); + } + secp256k1_scalar_mul(&x28, &x28, &x14); + + secp256k1_scalar_sqr(&x56, &x28); + for (i = 0; i < 27; i++) { + secp256k1_scalar_sqr(&x56, &x56); + } + secp256k1_scalar_mul(&x56, &x56, &x28); + + secp256k1_scalar_sqr(&x112, &x56); + for (i = 0; i < 55; i++) { + secp256k1_scalar_sqr(&x112, &x112); + } + secp256k1_scalar_mul(&x112, &x112, &x56); + + secp256k1_scalar_sqr(&x126, &x112); + for (i = 0; i < 13; i++) { + secp256k1_scalar_sqr(&x126, &x126); + } + secp256k1_scalar_mul(&x126, &x126, &x14); + + /* Then accumulate the final result (t starts at x126). */ + t = &x126; + for (i = 0; i < 3; i++) { + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u5); /* 101 */ + for (i = 0; i < 4; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &x3); /* 111 */ + for (i = 0; i < 4; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u5); /* 101 */ + for (i = 0; i < 5; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u11); /* 1011 */ + for (i = 0; i < 4; i++) { + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u11); /* 1011 */ + for (i = 0; i < 4; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &x3); /* 111 */ + for (i = 0; i < 5; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &x3); /* 111 */ + for (i = 0; i < 6; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u13); /* 1101 */ + for (i = 0; i < 4; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u5); /* 101 */ + for (i = 0; i < 3; i++) { + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &x3); /* 111 */ + for (i = 0; i < 5; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u9); /* 1001 */ + for (i = 0; i < 6; i++) { /* 000 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u5); /* 101 */ + for (i = 0; i < 10; i++) { /* 0000000 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &x3); /* 111 */ + for (i = 0; i < 4; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &x3); /* 111 */ + for (i = 0; i < 9; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &x8); /* 11111111 */ + for (i = 0; i < 5; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u9); /* 1001 */ + for (i = 0; i < 6; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u11); /* 1011 */ + for (i = 0; i < 4; i++) { + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u13); /* 1101 */ + for (i = 0; i < 5; i++) { + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &x2); /* 11 */ + for (i = 0; i < 6; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u13); /* 1101 */ + for (i = 0; i < 10; i++) { /* 000000 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u13); /* 1101 */ + for (i = 0; i < 4; i++) { + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u9); /* 1001 */ + for (i = 0; i < 6; i++) { /* 00000 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, x); /* 1 */ + for (i = 0; i < 8; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(r, t, &x6); /* 111111 */ +} + +SECP256K1_INLINE static int secp256k1_scalar_is_even(const secp256k1_scalar *a) { + return !(a->d[0] & 1); +} +#endif + +static void secp256k1_scalar_inverse_var(secp256k1_scalar *r, const secp256k1_scalar *x) { +#if defined(USE_SCALAR_INV_BUILTIN) + secp256k1_scalar_inverse(r, x); +#elif defined(USE_SCALAR_INV_NUM) + unsigned char b[32]; + secp256k1_num n, m; + secp256k1_scalar t = *x; + secp256k1_scalar_get_b32(b, &t); + secp256k1_num_set_bin(&n, b, 32); + secp256k1_scalar_order_get_num(&m); + secp256k1_num_mod_inverse(&n, &n, &m); + secp256k1_num_get_bin(b, 32, &n); + secp256k1_scalar_set_b32(r, b, NULL); + /* Verify that the inverse was computed correctly, without GMP code. */ + secp256k1_scalar_mul(&t, &t, r); + CHECK(secp256k1_scalar_is_one(&t)); +#else +#error "Please select scalar inverse implementation" +#endif +} + +#ifdef USE_ENDOMORPHISM +#if defined(EXHAUSTIVE_TEST_ORDER) +/** + * Find k1 and k2 given k, such that k1 + k2 * lambda == k mod n; unlike in the + * full case we don't bother making k1 and k2 be small, we just want them to be + * nontrivial to get full test coverage for the exhaustive tests. We therefore + * (arbitrarily) set k2 = k + 5 and k1 = k - k2 * lambda. + */ +static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { + *r2 = (*a + 5) % EXHAUSTIVE_TEST_ORDER; + *r1 = (*a + (EXHAUSTIVE_TEST_ORDER - *r2) * EXHAUSTIVE_TEST_LAMBDA) % EXHAUSTIVE_TEST_ORDER; +} +#else +/** + * The Secp256k1 curve has an endomorphism, where lambda * (x, y) = (beta * x, y), where + * lambda is {0x53,0x63,0xad,0x4c,0xc0,0x5c,0x30,0xe0,0xa5,0x26,0x1c,0x02,0x88,0x12,0x64,0x5a, + * 0x12,0x2e,0x22,0xea,0x20,0x81,0x66,0x78,0xdf,0x02,0x96,0x7c,0x1b,0x23,0xbd,0x72} + * + * "Guide to Elliptic Curve Cryptography" (Hankerson, Menezes, Vanstone) gives an algorithm + * (algorithm 3.74) to find k1 and k2 given k, such that k1 + k2 * lambda == k mod n, and k1 + * and k2 have a small size. + * It relies on constants a1, b1, a2, b2. These constants for the value of lambda above are: + * + * - a1 = {0x30,0x86,0xd2,0x21,0xa7,0xd4,0x6b,0xcd,0xe8,0x6c,0x90,0xe4,0x92,0x84,0xeb,0x15} + * - b1 = -{0xe4,0x43,0x7e,0xd6,0x01,0x0e,0x88,0x28,0x6f,0x54,0x7f,0xa9,0x0a,0xbf,0xe4,0xc3} + * - a2 = {0x01,0x14,0xca,0x50,0xf7,0xa8,0xe2,0xf3,0xf6,0x57,0xc1,0x10,0x8d,0x9d,0x44,0xcf,0xd8} + * - b2 = {0x30,0x86,0xd2,0x21,0xa7,0xd4,0x6b,0xcd,0xe8,0x6c,0x90,0xe4,0x92,0x84,0xeb,0x15} + * + * The algorithm then computes c1 = round(b1 * k / n) and c2 = round(b2 * k / n), and gives + * k1 = k - (c1*a1 + c2*a2) and k2 = -(c1*b1 + c2*b2). Instead, we use modular arithmetic, and + * compute k1 as k - k2 * lambda, avoiding the need for constants a1 and a2. + * + * g1, g2 are precomputed constants used to replace division with a rounded multiplication + * when decomposing the scalar for an endomorphism-based point multiplication. + * + * The possibility of using precomputed estimates is mentioned in "Guide to Elliptic Curve + * Cryptography" (Hankerson, Menezes, Vanstone) in section 3.5. + * + * The derivation is described in the paper "Efficient Software Implementation of Public-Key + * Cryptography on Sensor Networks Using the MSP430X Microcontroller" (Gouvea, Oliveira, Lopez), + * Section 4.3 (here we use a somewhat higher-precision estimate): + * d = a1*b2 - b1*a2 + * g1 = round((2^272)*b2/d) + * g2 = round((2^272)*b1/d) + * + * (Note that 'd' is also equal to the curve order here because [a1,b1] and [a2,b2] are found + * as outputs of the Extended Euclidean Algorithm on inputs 'order' and 'lambda'). + * + * The function below splits a in r1 and r2, such that r1 + lambda * r2 == a (mod order). + */ + +static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { + secp256k1_scalar c1, c2; + static const secp256k1_scalar minus_lambda = SECP256K1_SCALAR_CONST( + 0xAC9C52B3UL, 0x3FA3CF1FUL, 0x5AD9E3FDUL, 0x77ED9BA4UL, + 0xA880B9FCUL, 0x8EC739C2UL, 0xE0CFC810UL, 0xB51283CFUL + ); + static const secp256k1_scalar minus_b1 = SECP256K1_SCALAR_CONST( + 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x00000000UL, + 0xE4437ED6UL, 0x010E8828UL, 0x6F547FA9UL, 0x0ABFE4C3UL + ); + static const secp256k1_scalar minus_b2 = SECP256K1_SCALAR_CONST( + 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFEUL, + 0x8A280AC5UL, 0x0774346DUL, 0xD765CDA8UL, 0x3DB1562CUL + ); + static const secp256k1_scalar g1 = SECP256K1_SCALAR_CONST( + 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x00003086UL, + 0xD221A7D4UL, 0x6BCDE86CUL, 0x90E49284UL, 0xEB153DABUL + ); + static const secp256k1_scalar g2 = SECP256K1_SCALAR_CONST( + 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x0000E443UL, + 0x7ED6010EUL, 0x88286F54UL, 0x7FA90ABFUL, 0xE4C42212UL + ); + VERIFY_CHECK(r1 != a); + VERIFY_CHECK(r2 != a); + /* these _var calls are constant time since the shift amount is constant */ + secp256k1_scalar_mul_shift_var(&c1, a, &g1, 272); + secp256k1_scalar_mul_shift_var(&c2, a, &g2, 272); + secp256k1_scalar_mul(&c1, &c1, &minus_b1); + secp256k1_scalar_mul(&c2, &c2, &minus_b2); + secp256k1_scalar_add(r2, &c1, &c2); + secp256k1_scalar_mul(r1, r2, &minus_lambda); + secp256k1_scalar_add(r1, r1, a); +} +#endif +#endif + +#endif /* SECP256K1_SCALAR_IMPL_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_low.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_low.h new file mode 100644 index 000000000..5836febc5 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_low.h @@ -0,0 +1,15 @@ +/********************************************************************** + * Copyright (c) 2015 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_REPR_H +#define SECP256K1_SCALAR_REPR_H + +#include + +/** A scalar modulo the group order of the secp256k1 curve. */ +typedef uint32_t secp256k1_scalar; + +#endif /* SECP256K1_SCALAR_REPR_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_low_impl.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_low_impl.h new file mode 100644 index 000000000..c80e70c5a --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scalar_low_impl.h @@ -0,0 +1,114 @@ +/********************************************************************** + * Copyright (c) 2015 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_REPR_IMPL_H +#define SECP256K1_SCALAR_REPR_IMPL_H + +#include "scalar.h" + +#include + +SECP256K1_INLINE static int secp256k1_scalar_is_even(const secp256k1_scalar *a) { + return !(*a & 1); +} + +SECP256K1_INLINE static void secp256k1_scalar_clear(secp256k1_scalar *r) { *r = 0; } +SECP256K1_INLINE static void secp256k1_scalar_set_int(secp256k1_scalar *r, unsigned int v) { *r = v; } + +SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits(const secp256k1_scalar *a, unsigned int offset, unsigned int count) { + if (offset < 32) + return ((*a >> offset) & ((((uint32_t)1) << count) - 1)); + else + return 0; +} + +SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits_var(const secp256k1_scalar *a, unsigned int offset, unsigned int count) { + return secp256k1_scalar_get_bits(a, offset, count); +} + +SECP256K1_INLINE static int secp256k1_scalar_check_overflow(const secp256k1_scalar *a) { return *a >= EXHAUSTIVE_TEST_ORDER; } + +static int secp256k1_scalar_add(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b) { + *r = (*a + *b) % EXHAUSTIVE_TEST_ORDER; + return *r < *b; +} + +static void secp256k1_scalar_cadd_bit(secp256k1_scalar *r, unsigned int bit, int flag) { + if (flag && bit < 32) + *r += (1 << bit); +#ifdef VERIFY + VERIFY_CHECK(secp256k1_scalar_check_overflow(r) == 0); +#endif +} + +static void secp256k1_scalar_set_b32(secp256k1_scalar *r, const unsigned char *b32, int *overflow) { + const int base = 0x100 % EXHAUSTIVE_TEST_ORDER; + int i; + *r = 0; + for (i = 0; i < 32; i++) { + *r = ((*r * base) + b32[i]) % EXHAUSTIVE_TEST_ORDER; + } + /* just deny overflow, it basically always happens */ + if (overflow) *overflow = 0; +} + +static void secp256k1_scalar_get_b32(unsigned char *bin, const secp256k1_scalar* a) { + memset(bin, 0, 32); + bin[28] = *a >> 24; bin[29] = *a >> 16; bin[30] = *a >> 8; bin[31] = *a; +} + +SECP256K1_INLINE static int secp256k1_scalar_is_zero(const secp256k1_scalar *a) { + return *a == 0; +} + +static void secp256k1_scalar_negate(secp256k1_scalar *r, const secp256k1_scalar *a) { + if (*a == 0) { + *r = 0; + } else { + *r = EXHAUSTIVE_TEST_ORDER - *a; + } +} + +SECP256K1_INLINE static int secp256k1_scalar_is_one(const secp256k1_scalar *a) { + return *a == 1; +} + +static int secp256k1_scalar_is_high(const secp256k1_scalar *a) { + return *a > EXHAUSTIVE_TEST_ORDER / 2; +} + +static int secp256k1_scalar_cond_negate(secp256k1_scalar *r, int flag) { + if (flag) secp256k1_scalar_negate(r, r); + return flag ? -1 : 1; +} + +static void secp256k1_scalar_mul(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b) { + *r = (*a * *b) % EXHAUSTIVE_TEST_ORDER; +} + +static int secp256k1_scalar_shr_int(secp256k1_scalar *r, int n) { + int ret; + VERIFY_CHECK(n > 0); + VERIFY_CHECK(n < 16); + ret = *r & ((1 << n) - 1); + *r >>= n; + return ret; +} + +static void secp256k1_scalar_sqr(secp256k1_scalar *r, const secp256k1_scalar *a) { + *r = (*a * *a) % EXHAUSTIVE_TEST_ORDER; +} + +static void secp256k1_scalar_split_128(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { + *r1 = *a; + *r2 = 0; +} + +SECP256K1_INLINE static int secp256k1_scalar_eq(const secp256k1_scalar *a, const secp256k1_scalar *b) { + return *a == *b; +} + +#endif /* SECP256K1_SCALAR_REPR_IMPL_H */ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scratch.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scratch.h new file mode 100644 index 000000000..fef377af0 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scratch.h @@ -0,0 +1,39 @@ +/********************************************************************** + * Copyright (c) 2017 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef _SECP256K1_SCRATCH_ +#define _SECP256K1_SCRATCH_ + +#define SECP256K1_SCRATCH_MAX_FRAMES 5 + +/* The typedef is used internally; the struct name is used in the public API + * (where it is exposed as a different typedef) */ +typedef struct secp256k1_scratch_space_struct { + void *data[SECP256K1_SCRATCH_MAX_FRAMES]; + size_t offset[SECP256K1_SCRATCH_MAX_FRAMES]; + size_t frame_size[SECP256K1_SCRATCH_MAX_FRAMES]; + size_t frame; + size_t max_size; + const secp256k1_callback* error_callback; +} secp256k1_scratch; + +static secp256k1_scratch* secp256k1_scratch_create(const secp256k1_callback* error_callback, size_t max_size); + +static void secp256k1_scratch_destroy(secp256k1_scratch* scratch); + +/** Attempts to allocate a new stack frame with `n` available bytes. Returns 1 on success, 0 on failure */ +static int secp256k1_scratch_allocate_frame(secp256k1_scratch* scratch, size_t n, size_t objects); + +/** Deallocates a stack frame */ +static void secp256k1_scratch_deallocate_frame(secp256k1_scratch* scratch); + +/** Returns the maximum allocation the scratch space will allow */ +static size_t secp256k1_scratch_max_allocation(const secp256k1_scratch* scratch, size_t n_objects); + +/** Returns a pointer into the most recently allocated frame, or NULL if there is insufficient available space */ +static void *secp256k1_scratch_alloc(secp256k1_scratch* scratch, size_t n); + +#endif diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scratch_impl.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scratch_impl.h new file mode 100644 index 000000000..abed713b2 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/scratch_impl.h @@ -0,0 +1,86 @@ +/********************************************************************** + * Copyright (c) 2017 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef _SECP256K1_SCRATCH_IMPL_H_ +#define _SECP256K1_SCRATCH_IMPL_H_ + +#include "scratch.h" + +/* Using 16 bytes alignment because common architectures never have alignment + * requirements above 8 for any of the types we care about. In addition we + * leave some room because currently we don't care about a few bytes. + * TODO: Determine this at configure time. */ +#define ALIGNMENT 16 + +static secp256k1_scratch* secp256k1_scratch_create(const secp256k1_callback* error_callback, size_t max_size) { + secp256k1_scratch* ret = (secp256k1_scratch*)checked_malloc(error_callback, sizeof(*ret)); + if (ret != NULL) { + memset(ret, 0, sizeof(*ret)); + ret->max_size = max_size; + ret->error_callback = error_callback; + } + return ret; +} + +static void secp256k1_scratch_destroy(secp256k1_scratch* scratch) { + if (scratch != NULL) { + VERIFY_CHECK(scratch->frame == 0); + free(scratch); + } +} + +static size_t secp256k1_scratch_max_allocation(const secp256k1_scratch* scratch, size_t objects) { + size_t i = 0; + size_t allocated = 0; + for (i = 0; i < scratch->frame; i++) { + allocated += scratch->frame_size[i]; + } + if (scratch->max_size - allocated <= objects * ALIGNMENT) { + return 0; + } + return scratch->max_size - allocated - objects * ALIGNMENT; +} + +static int secp256k1_scratch_allocate_frame(secp256k1_scratch* scratch, size_t n, size_t objects) { + VERIFY_CHECK(scratch->frame < SECP256K1_SCRATCH_MAX_FRAMES); + + if (n <= secp256k1_scratch_max_allocation(scratch, objects)) { + n += objects * ALIGNMENT; + scratch->data[scratch->frame] = checked_malloc(scratch->error_callback, n); + if (scratch->data[scratch->frame] == NULL) { + return 0; + } + scratch->frame_size[scratch->frame] = n; + scratch->offset[scratch->frame] = 0; + scratch->frame++; + return 1; + } else { + return 0; + } +} + +static void secp256k1_scratch_deallocate_frame(secp256k1_scratch* scratch) { + VERIFY_CHECK(scratch->frame > 0); + scratch->frame -= 1; + free(scratch->data[scratch->frame]); +} + +static void *secp256k1_scratch_alloc(secp256k1_scratch* scratch, size_t size) { + void *ret; + size_t frame = scratch->frame - 1; + size = ((size + ALIGNMENT - 1) / ALIGNMENT) * ALIGNMENT; + + if (scratch->frame == 0 || size + scratch->offset[frame] > scratch->frame_size[frame]) { + return NULL; + } + ret = (void *) ((unsigned char *) scratch->data[frame] + scratch->offset[frame]); + memset(ret, 0, size); + scratch->offset[frame] += size; + + return ret; +} + +#endif diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/secp256k1-config.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/secp256k1-config.h new file mode 100644 index 000000000..e22848b5f --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/secp256k1-config.h @@ -0,0 +1,169 @@ +/* src/libsecp256k1-config.h. Generated from libsecp256k1-config.h.in by configure. */ +/* src/libsecp256k1-config.h.in. Generated from configure.ac by autoheader. */ + +#ifndef LIBSECP256K1_CONFIG_H + +#define LIBSECP256K1_CONFIG_H + +#undef USE_BASIC_CONFIG + +/* Define if building universal (internal helper macro) */ +/* #undef AC_APPLE_UNIVERSAL_BUILD */ + +/* Define this symbol to compile out all VERIFY code */ +/* #undef COVERAGE */ + +/* Define this symbol to enable the ECDH module */ +/* #undef ENABLE_MODULE_ECDH */ + +/* Define this symbol to enable the ECDSA pubkey recovery module */ +/* #undef ENABLE_MODULE_RECOVERY */ + +/* Define this symbol if OpenSSL EC functions are available */ +/* #undef ENABLE_OPENSSL_TESTS */ + +/* Define this symbol if __builtin_expect is available */ +#define HAVE_BUILTIN_EXPECT 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_DLFCN_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define this symbol if libcrypto is installed */ +/* #define HAVE_LIBCRYPTO 1 */ + +/* Define this symbol if libgmp is installed */ +/* #define HAVE_LIBGMP 1 */ + +/* Define to 1 if you have the header file. */ +#define HAVE_MEMORY_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UNISTD_H 1 + +/* Define to 1 if the system has the type `__int128'. */ +/* #define HAVE___INT128 1 */ + +/* Define to the sub-directory where libtool stores uninstalled libraries. */ +/* #define LT_OBJDIR ".libs/" */ + +/* Name of package */ +#define PACKAGE "libsecp256k1" + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "libsecp256k1" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "libsecp256k1 0.1" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "libsecp256k1" + +/* Define to the home page for this package. */ +#define PACKAGE_URL "" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "0.1" + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Define this symbol to enable x86_64 assembly optimizations */ +/* #define USE_ASM_X86_64 1 */ + +/* Define this symbol to use a statically generated ecmult table */ +#define USE_ECMULT_STATIC_PRECOMPUTATION 1 + +/* Define this symbol to use endomorphism optimization */ +/* #undef USE_ENDOMORPHISM */ + +/* Define this symbol if an external (non-inline) assembly implementation is + used */ +/* #undef USE_EXTERNAL_ASM */ + +/* Define this symbol to use the FIELD_10X26 implementation */ +/* #undef USE_FIELD_10X26 */ + +/* Define this symbol to use the FIELD_5X52 implementation */ +/* #define USE_FIELD_5X52 1 */ + +/* Define this symbol to use the native field inverse implementation */ +/* #undef USE_FIELD_INV_BUILTIN */ + +/* Define this symbol to use the num-based field inverse implementation */ +/* #define USE_FIELD_INV_NUM 1 */ + +/* Define this symbol to use the gmp implementation for num */ +/* #define USE_NUM_GMP 1 */ + +/* Define this symbol to use no num implementation */ +/* #undef USE_NUM_NONE */ + +/* Define this symbol to use the 4x64 scalar implementation */ +/* #define USE_SCALAR_4X64 1 */ + +/* Define this symbol to use the 8x32 scalar implementation */ +/* #undef USE_SCALAR_8X32 */ + +/* Define this symbol to use the native scalar inverse implementation */ +/* #undef USE_SCALAR_INV_BUILTIN */ + +/* Define this symbol to use the num-based scalar inverse implementation */ +/* #define USE_SCALAR_INV_NUM 1 */ + +/* Version number of package */ +#define VERSION "0.1" + +/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most + significant byte first (like Motorola and SPARC, unlike Intel). */ + +// #if defined AC_APPLE_UNIVERSAL_BUILD +// # if defined __BIG_ENDIAN__ +// # define WORDS_BIGENDIAN 1 +// # endif +// #else +// # ifndef WORDS_BIGENDIAN +// /* # undef WORDS_BIGENDIAN */ +// # endif +// #endif + +/* Extra configuration */ + +#define USE_NUM_NONE 1 +#define USE_FIELD_INV_BUILTIN 1 +#define USE_SCALAR_INV_BUILTIN 1 +#define ENABLE_MODULE_RECOVERY 1 + +#ifdef __LP64__ +#define HAVE___INT128 1 +#define USE_FIELD_5X52 1 +#define USE_SCALAR_4X64 1 +#else +#define USE_FIELD_10X26 1 +#define USE_SCALAR_8X32 1 +#endif + +#endif /*LIBSECP256K1_CONFIG_H*/ diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/secp256k1.c b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/secp256k1.c new file mode 100644 index 000000000..25fd50193 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/secp256k1.c @@ -0,0 +1,597 @@ +/********************************************************************** + * Copyright (c) 2013-2015 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#include "secp256k1.h" + +#include "util.h" +#include "num_impl.h" +#include "field_impl.h" +#include "scalar_impl.h" +#include "group_impl.h" +#include "ecmult_impl.h" +#include "ecmult_const_impl.h" +#include "ecmult_gen_impl.h" +#include "ecdsa_impl.h" +#include "eckey_impl.h" +#include "hash_impl.h" +#include "scratch_impl.h" + +#define ARG_CHECK(cond) do { \ + if (EXPECT(!(cond), 0)) { \ + secp256k1_callback_call(&ctx->illegal_callback, #cond); \ + return 0; \ + } \ +} while(0) + +static void default_illegal_callback_fn(const char* str, void* data) { + (void)data; + fprintf(stderr, "[libsecp256k1] illegal argument: %s\n", str); + abort(); +} + +static const secp256k1_callback default_illegal_callback = { + default_illegal_callback_fn, + NULL +}; + +static void default_error_callback_fn(const char* str, void* data) { + (void)data; + fprintf(stderr, "[libsecp256k1] internal consistency check failed: %s\n", str); + abort(); +} + +static const secp256k1_callback default_error_callback = { + default_error_callback_fn, + NULL +}; + + +struct secp256k1_context_struct { + secp256k1_ecmult_context ecmult_ctx; + secp256k1_ecmult_gen_context ecmult_gen_ctx; + secp256k1_callback illegal_callback; + secp256k1_callback error_callback; +}; + +secp256k1_context* secp256k1_context_create(unsigned int flags) { + secp256k1_context* ret = (secp256k1_context*)checked_malloc(&default_error_callback, sizeof(secp256k1_context)); + ret->illegal_callback = default_illegal_callback; + ret->error_callback = default_error_callback; + + if (EXPECT((flags & SECP256K1_FLAGS_TYPE_MASK) != SECP256K1_FLAGS_TYPE_CONTEXT, 0)) { + secp256k1_callback_call(&ret->illegal_callback, + "Invalid flags"); + free(ret); + return NULL; + } + + secp256k1_ecmult_context_init(&ret->ecmult_ctx); + secp256k1_ecmult_gen_context_init(&ret->ecmult_gen_ctx); + + if (flags & SECP256K1_FLAGS_BIT_CONTEXT_SIGN) { + secp256k1_ecmult_gen_context_build(&ret->ecmult_gen_ctx, &ret->error_callback); + } + if (flags & SECP256K1_FLAGS_BIT_CONTEXT_VERIFY) { + secp256k1_ecmult_context_build(&ret->ecmult_ctx, &ret->error_callback); + } + + return ret; +} + +secp256k1_context* secp256k1_context_clone(const secp256k1_context* ctx) { + secp256k1_context* ret = (secp256k1_context*)checked_malloc(&ctx->error_callback, sizeof(secp256k1_context)); + ret->illegal_callback = ctx->illegal_callback; + ret->error_callback = ctx->error_callback; + secp256k1_ecmult_context_clone(&ret->ecmult_ctx, &ctx->ecmult_ctx, &ctx->error_callback); + secp256k1_ecmult_gen_context_clone(&ret->ecmult_gen_ctx, &ctx->ecmult_gen_ctx, &ctx->error_callback); + return ret; +} + +void secp256k1_context_destroy(secp256k1_context* ctx) { + if (ctx != NULL) { + secp256k1_ecmult_context_clear(&ctx->ecmult_ctx); + secp256k1_ecmult_gen_context_clear(&ctx->ecmult_gen_ctx); + + free(ctx); + } +} + +void secp256k1_context_set_illegal_callback(secp256k1_context* ctx, void (*fun)(const char* message, void* data), const void* data) { + if (fun == NULL) { + fun = default_illegal_callback_fn; + } + ctx->illegal_callback.fn = fun; + ctx->illegal_callback.data = data; +} + +void secp256k1_context_set_error_callback(secp256k1_context* ctx, void (*fun)(const char* message, void* data), const void* data) { + if (fun == NULL) { + fun = default_error_callback_fn; + } + ctx->error_callback.fn = fun; + ctx->error_callback.data = data; +} + +secp256k1_scratch_space* secp256k1_scratch_space_create(const secp256k1_context* ctx, size_t max_size) { + VERIFY_CHECK(ctx != NULL); + return secp256k1_scratch_create(&ctx->error_callback, max_size); +} + +void secp256k1_scratch_space_destroy(secp256k1_scratch_space* scratch) { + secp256k1_scratch_destroy(scratch); +} + +static int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey) { + if (sizeof(secp256k1_ge_storage) == 64) { + /* When the secp256k1_ge_storage type is exactly 64 byte, use its + * representation inside secp256k1_pubkey, as conversion is very fast. + * Note that secp256k1_pubkey_save must use the same representation. */ + secp256k1_ge_storage s; + memcpy(&s, &pubkey->data[0], sizeof(s)); + secp256k1_ge_from_storage(ge, &s); + } else { + /* Otherwise, fall back to 32-byte big endian for X and Y. */ + secp256k1_fe x, y; + secp256k1_fe_set_b32(&x, pubkey->data); + secp256k1_fe_set_b32(&y, pubkey->data + 32); + secp256k1_ge_set_xy(ge, &x, &y); + } + ARG_CHECK(!secp256k1_fe_is_zero(&ge->x)); + return 1; +} + +static void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge) { + if (sizeof(secp256k1_ge_storage) == 64) { + secp256k1_ge_storage s; + secp256k1_ge_to_storage(&s, ge); + memcpy(&pubkey->data[0], &s, sizeof(s)); + } else { + VERIFY_CHECK(!secp256k1_ge_is_infinity(ge)); + secp256k1_fe_normalize_var(&ge->x); + secp256k1_fe_normalize_var(&ge->y); + secp256k1_fe_get_b32(pubkey->data, &ge->x); + secp256k1_fe_get_b32(pubkey->data + 32, &ge->y); + } +} + +int secp256k1_ec_pubkey_parse(const secp256k1_context* ctx, secp256k1_pubkey* pubkey, const unsigned char *input, size_t inputlen) { + secp256k1_ge Q; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(pubkey != NULL); + memset(pubkey, 0, sizeof(*pubkey)); + ARG_CHECK(input != NULL); + if (!secp256k1_eckey_pubkey_parse(&Q, input, inputlen)) { + return 0; + } + secp256k1_pubkey_save(pubkey, &Q); + secp256k1_ge_clear(&Q); + return 1; +} + +int secp256k1_ec_pubkey_serialize(const secp256k1_context* ctx, unsigned char *output, size_t *outputlen, const secp256k1_pubkey* pubkey, unsigned int flags) { + secp256k1_ge Q; + size_t len; + int ret = 0; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(outputlen != NULL); + ARG_CHECK(*outputlen >= ((flags & SECP256K1_FLAGS_BIT_COMPRESSION) ? 33 : 65)); + len = *outputlen; + *outputlen = 0; + ARG_CHECK(output != NULL); + memset(output, 0, len); + ARG_CHECK(pubkey != NULL); + ARG_CHECK((flags & SECP256K1_FLAGS_TYPE_MASK) == SECP256K1_FLAGS_TYPE_COMPRESSION); + if (secp256k1_pubkey_load(ctx, &Q, pubkey)) { + ret = secp256k1_eckey_pubkey_serialize(&Q, output, &len, flags & SECP256K1_FLAGS_BIT_COMPRESSION); + if (ret) { + *outputlen = len; + } + } + return ret; +} + +static void secp256k1_ecdsa_signature_load(const secp256k1_context* ctx, secp256k1_scalar* r, secp256k1_scalar* s, const secp256k1_ecdsa_signature* sig) { + (void)ctx; + if (sizeof(secp256k1_scalar) == 32) { + /* When the secp256k1_scalar type is exactly 32 byte, use its + * representation inside secp256k1_ecdsa_signature, as conversion is very fast. + * Note that secp256k1_ecdsa_signature_save must use the same representation. */ + memcpy(r, &sig->data[0], 32); + memcpy(s, &sig->data[32], 32); + } else { + secp256k1_scalar_set_b32(r, &sig->data[0], NULL); + secp256k1_scalar_set_b32(s, &sig->data[32], NULL); + } +} + +static void secp256k1_ecdsa_signature_save(secp256k1_ecdsa_signature* sig, const secp256k1_scalar* r, const secp256k1_scalar* s) { + if (sizeof(secp256k1_scalar) == 32) { + memcpy(&sig->data[0], r, 32); + memcpy(&sig->data[32], s, 32); + } else { + secp256k1_scalar_get_b32(&sig->data[0], r); + secp256k1_scalar_get_b32(&sig->data[32], s); + } +} + +int secp256k1_ecdsa_signature_parse_der(const secp256k1_context* ctx, secp256k1_ecdsa_signature* sig, const unsigned char *input, size_t inputlen) { + secp256k1_scalar r, s; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(sig != NULL); + ARG_CHECK(input != NULL); + + if (secp256k1_ecdsa_sig_parse(&r, &s, input, inputlen)) { + secp256k1_ecdsa_signature_save(sig, &r, &s); + return 1; + } else { + memset(sig, 0, sizeof(*sig)); + return 0; + } +} + +int secp256k1_ecdsa_signature_parse_compact(const secp256k1_context* ctx, secp256k1_ecdsa_signature* sig, const unsigned char *input64) { + secp256k1_scalar r, s; + int ret = 1; + int overflow = 0; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(sig != NULL); + ARG_CHECK(input64 != NULL); + + secp256k1_scalar_set_b32(&r, &input64[0], &overflow); + ret &= !overflow; + secp256k1_scalar_set_b32(&s, &input64[32], &overflow); + ret &= !overflow; + if (ret) { + secp256k1_ecdsa_signature_save(sig, &r, &s); + } else { + memset(sig, 0, sizeof(*sig)); + } + return ret; +} + +int secp256k1_ecdsa_signature_serialize_der(const secp256k1_context* ctx, unsigned char *output, size_t *outputlen, const secp256k1_ecdsa_signature* sig) { + secp256k1_scalar r, s; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(output != NULL); + ARG_CHECK(outputlen != NULL); + ARG_CHECK(sig != NULL); + + secp256k1_ecdsa_signature_load(ctx, &r, &s, sig); + return secp256k1_ecdsa_sig_serialize(output, outputlen, &r, &s); +} + +int secp256k1_ecdsa_signature_serialize_compact(const secp256k1_context* ctx, unsigned char *output64, const secp256k1_ecdsa_signature* sig) { + secp256k1_scalar r, s; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(output64 != NULL); + ARG_CHECK(sig != NULL); + + secp256k1_ecdsa_signature_load(ctx, &r, &s, sig); + secp256k1_scalar_get_b32(&output64[0], &r); + secp256k1_scalar_get_b32(&output64[32], &s); + return 1; +} + +int secp256k1_ecdsa_signature_normalize(const secp256k1_context* ctx, secp256k1_ecdsa_signature *sigout, const secp256k1_ecdsa_signature *sigin) { + secp256k1_scalar r, s; + int ret = 0; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(sigin != NULL); + + secp256k1_ecdsa_signature_load(ctx, &r, &s, sigin); + ret = secp256k1_scalar_is_high(&s); + if (sigout != NULL) { + if (ret) { + secp256k1_scalar_negate(&s, &s); + } + secp256k1_ecdsa_signature_save(sigout, &r, &s); + } + + return ret; +} + +int secp256k1_ecdsa_verify(const secp256k1_context* ctx, const secp256k1_ecdsa_signature *sig, const unsigned char *msg32, const secp256k1_pubkey *pubkey) { + secp256k1_ge q; + secp256k1_scalar r, s; + secp256k1_scalar m; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_context_is_built(&ctx->ecmult_ctx)); + ARG_CHECK(msg32 != NULL); + ARG_CHECK(sig != NULL); + ARG_CHECK(pubkey != NULL); + + secp256k1_scalar_set_b32(&m, msg32, NULL); + secp256k1_ecdsa_signature_load(ctx, &r, &s, sig); + return (!secp256k1_scalar_is_high(&s) && + secp256k1_pubkey_load(ctx, &q, pubkey) && + secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &r, &s, &q, &m)); +} + +static SECP256K1_INLINE void buffer_append(unsigned char *buf, unsigned int *offset, const void *data, unsigned int len) { + memcpy(buf + *offset, data, len); + *offset += len; +} + +static int nonce_function_rfc6979(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter) { + unsigned char keydata[112]; + unsigned int offset = 0; + secp256k1_rfc6979_hmac_sha256 rng; + unsigned int i; + /* We feed a byte array to the PRNG as input, consisting of: + * - the private key (32 bytes) and message (32 bytes), see RFC 6979 3.2d. + * - optionally 32 extra bytes of data, see RFC 6979 3.6 Additional Data. + * - optionally 16 extra bytes with the algorithm name. + * Because the arguments have distinct fixed lengths it is not possible for + * different argument mixtures to emulate each other and result in the same + * nonces. + */ + buffer_append(keydata, &offset, key32, 32); + buffer_append(keydata, &offset, msg32, 32); + if (data != NULL) { + buffer_append(keydata, &offset, data, 32); + } + if (algo16 != NULL) { + buffer_append(keydata, &offset, algo16, 16); + } + secp256k1_rfc6979_hmac_sha256_initialize(&rng, keydata, offset); + memset(keydata, 0, sizeof(keydata)); + for (i = 0; i <= counter; i++) { + secp256k1_rfc6979_hmac_sha256_generate(&rng, nonce32, 32); + } + secp256k1_rfc6979_hmac_sha256_finalize(&rng); + return 1; +} + +const secp256k1_nonce_function secp256k1_nonce_function_rfc6979 = nonce_function_rfc6979; +const secp256k1_nonce_function secp256k1_nonce_function_default = nonce_function_rfc6979; + +int secp256k1_ecdsa_sign(const secp256k1_context* ctx, secp256k1_ecdsa_signature *signature, const unsigned char *msg32, const unsigned char *seckey, secp256k1_nonce_function noncefp, const void* noncedata) { + secp256k1_scalar r, s; + secp256k1_scalar sec, non, msg; + int ret = 0; + int overflow = 0; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)); + ARG_CHECK(msg32 != NULL); + ARG_CHECK(signature != NULL); + ARG_CHECK(seckey != NULL); + if (noncefp == NULL) { + noncefp = secp256k1_nonce_function_default; + } + + secp256k1_scalar_set_b32(&sec, seckey, &overflow); + /* Fail if the secret key is invalid. */ + if (!overflow && !secp256k1_scalar_is_zero(&sec)) { + unsigned char nonce32[32]; + unsigned int count = 0; + secp256k1_scalar_set_b32(&msg, msg32, NULL); + while (1) { + ret = noncefp(nonce32, msg32, seckey, NULL, (void*)noncedata, count); + if (!ret) { + break; + } + secp256k1_scalar_set_b32(&non, nonce32, &overflow); + if (!overflow && !secp256k1_scalar_is_zero(&non)) { + if (secp256k1_ecdsa_sig_sign(&ctx->ecmult_gen_ctx, &r, &s, &sec, &msg, &non, NULL)) { + break; + } + } + count++; + } + memset(nonce32, 0, 32); + secp256k1_scalar_clear(&msg); + secp256k1_scalar_clear(&non); + secp256k1_scalar_clear(&sec); + } + if (ret) { + secp256k1_ecdsa_signature_save(signature, &r, &s); + } else { + memset(signature, 0, sizeof(*signature)); + } + return ret; +} + +int secp256k1_ec_seckey_verify(const secp256k1_context* ctx, const unsigned char *seckey) { + secp256k1_scalar sec; + int ret; + int overflow; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(seckey != NULL); + + secp256k1_scalar_set_b32(&sec, seckey, &overflow); + ret = !overflow && !secp256k1_scalar_is_zero(&sec); + secp256k1_scalar_clear(&sec); + return ret; +} + +int secp256k1_ec_pubkey_create(const secp256k1_context* ctx, secp256k1_pubkey *pubkey, const unsigned char *seckey) { + secp256k1_gej pj; + secp256k1_ge p; + secp256k1_scalar sec; + int overflow; + int ret = 0; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(pubkey != NULL); + memset(pubkey, 0, sizeof(*pubkey)); + ARG_CHECK(secp256k1_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)); + ARG_CHECK(seckey != NULL); + + secp256k1_scalar_set_b32(&sec, seckey, &overflow); + ret = (!overflow) & (!secp256k1_scalar_is_zero(&sec)); + if (ret) { + secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &pj, &sec); + secp256k1_ge_set_gej(&p, &pj); + secp256k1_pubkey_save(pubkey, &p); + } + secp256k1_scalar_clear(&sec); + return ret; +} + +int secp256k1_ec_privkey_negate(const secp256k1_context* ctx, unsigned char *seckey) { + secp256k1_scalar sec; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(seckey != NULL); + + secp256k1_scalar_set_b32(&sec, seckey, NULL); + secp256k1_scalar_negate(&sec, &sec); + secp256k1_scalar_get_b32(seckey, &sec); + + return 1; +} + +int secp256k1_ec_pubkey_negate(const secp256k1_context* ctx, secp256k1_pubkey *pubkey) { + int ret = 0; + secp256k1_ge p; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(pubkey != NULL); + + ret = secp256k1_pubkey_load(ctx, &p, pubkey); + memset(pubkey, 0, sizeof(*pubkey)); + if (ret) { + secp256k1_ge_neg(&p, &p); + secp256k1_pubkey_save(pubkey, &p); + } + return ret; +} + +int secp256k1_ec_privkey_tweak_add(const secp256k1_context* ctx, unsigned char *seckey, const unsigned char *tweak) { + secp256k1_scalar term; + secp256k1_scalar sec; + int ret = 0; + int overflow = 0; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(seckey != NULL); + ARG_CHECK(tweak != NULL); + + secp256k1_scalar_set_b32(&term, tweak, &overflow); + secp256k1_scalar_set_b32(&sec, seckey, NULL); + + ret = !overflow && secp256k1_eckey_privkey_tweak_add(&sec, &term); + memset(seckey, 0, 32); + if (ret) { + secp256k1_scalar_get_b32(seckey, &sec); + } + + secp256k1_scalar_clear(&sec); + secp256k1_scalar_clear(&term); + return ret; +} + +int secp256k1_ec_pubkey_tweak_add(const secp256k1_context* ctx, secp256k1_pubkey *pubkey, const unsigned char *tweak) { + secp256k1_ge p; + secp256k1_scalar term; + int ret = 0; + int overflow = 0; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_context_is_built(&ctx->ecmult_ctx)); + ARG_CHECK(pubkey != NULL); + ARG_CHECK(tweak != NULL); + + secp256k1_scalar_set_b32(&term, tweak, &overflow); + ret = !overflow && secp256k1_pubkey_load(ctx, &p, pubkey); + memset(pubkey, 0, sizeof(*pubkey)); + if (ret) { + if (secp256k1_eckey_pubkey_tweak_add(&ctx->ecmult_ctx, &p, &term)) { + secp256k1_pubkey_save(pubkey, &p); + } else { + ret = 0; + } + } + + return ret; +} + +int secp256k1_ec_privkey_tweak_mul(const secp256k1_context* ctx, unsigned char *seckey, const unsigned char *tweak) { + secp256k1_scalar factor; + secp256k1_scalar sec; + int ret = 0; + int overflow = 0; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(seckey != NULL); + ARG_CHECK(tweak != NULL); + + secp256k1_scalar_set_b32(&factor, tweak, &overflow); + secp256k1_scalar_set_b32(&sec, seckey, NULL); + ret = !overflow && secp256k1_eckey_privkey_tweak_mul(&sec, &factor); + memset(seckey, 0, 32); + if (ret) { + secp256k1_scalar_get_b32(seckey, &sec); + } + + secp256k1_scalar_clear(&sec); + secp256k1_scalar_clear(&factor); + return ret; +} + +int secp256k1_ec_pubkey_tweak_mul(const secp256k1_context* ctx, secp256k1_pubkey *pubkey, const unsigned char *tweak) { + secp256k1_ge p; + secp256k1_scalar factor; + int ret = 0; + int overflow = 0; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_context_is_built(&ctx->ecmult_ctx)); + ARG_CHECK(pubkey != NULL); + ARG_CHECK(tweak != NULL); + + secp256k1_scalar_set_b32(&factor, tweak, &overflow); + ret = !overflow && secp256k1_pubkey_load(ctx, &p, pubkey); + memset(pubkey, 0, sizeof(*pubkey)); + if (ret) { + if (secp256k1_eckey_pubkey_tweak_mul(&ctx->ecmult_ctx, &p, &factor)) { + secp256k1_pubkey_save(pubkey, &p); + } else { + ret = 0; + } + } + + return ret; +} + +int secp256k1_context_randomize(secp256k1_context* ctx, const unsigned char *seed32) { + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)); + secp256k1_ecmult_gen_blind(&ctx->ecmult_gen_ctx, seed32); + return 1; +} + +int secp256k1_ec_pubkey_combine(const secp256k1_context* ctx, secp256k1_pubkey *pubnonce, const secp256k1_pubkey * const *pubnonces, size_t n) { + size_t i; + secp256k1_gej Qj; + secp256k1_ge Q; + + ARG_CHECK(pubnonce != NULL); + memset(pubnonce, 0, sizeof(*pubnonce)); + ARG_CHECK(n >= 1); + ARG_CHECK(pubnonces != NULL); + + secp256k1_gej_set_infinity(&Qj); + + for (i = 0; i < n; i++) { + secp256k1_pubkey_load(ctx, &Q, pubnonces[i]); + secp256k1_gej_add_ge(&Qj, &Qj, &Q); + } + if (secp256k1_gej_is_infinity(&Qj)) { + return 0; + } + secp256k1_ge_set_gej(&Q, &Qj); + secp256k1_pubkey_save(pubnonce, &Q); + return 1; +} + +#ifdef ENABLE_MODULE_ECDH +# include "ecdh_impl.h" +#endif + +#ifdef ENABLE_MODULE_RECOVERY +# include "recovery_impl.h" +#endif diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/secp256k1_ec_mult_static_context.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/secp256k1_ec_mult_static_context.h new file mode 100644 index 000000000..61d937345 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/secp256k1_ec_mult_static_context.h @@ -0,0 +1,1160 @@ +#ifndef _SECP256K1_ECMULT_STATIC_CONTEXT_ +#define _SECP256K1_ECMULT_STATIC_CONTEXT_ +#include "group.h" +#define SC SECP256K1_GE_STORAGE_CONST +static const secp256k1_ge_storage secp256k1_ecmult_static_context[64][16] = { +{ + SC(983487347u, 1861041900u, 2599115456u, 565528146u, 1451326239u, 148794576u, 4224640328u, 3120843701u, 2076989736u, 3184115747u, 3754320824u, 2656004457u, 2876577688u, 2388659905u, 3527541004u, 1170708298u), + SC(3830281845u, 3284871255u, 1309883393u, 2806991612u, 1558611192u, 1249416977u, 1614773327u, 1353445208u, 633124399u, 4264439010u, 426432620u, 167800352u, 2355417627u, 2991792291u, 3042397084u, 505150283u), + SC(1792710820u, 2165839471u, 3876070801u, 3603801374u, 2437636273u, 1231643248u, 860890267u, 4002236272u, 3258245037u, 4085545079u, 2695347418u, 288209541u, 484302592u, 139267079u, 14621978u, 2750167787u), + SC(11094760u, 1663454715u, 3104893589u, 1290390142u, 1334245677u, 2671416785u, 3982578986u, 2050971459u, 2136209393u, 1792200847u, 367473428u, 114820199u, 1096121039u, 425028623u, 3983611854u, 923011107u), + SC(3063072592u, 3527226996u, 3276923831u, 3785926779u, 346414977u, 2234429237u, 547163845u, 1847763663u, 2978762519u, 623753375u, 2207114031u, 3006533282u, 3147176505u, 1421052999u, 4188545436u, 1210097867u), + SC(1763690305u, 2162645845u, 1202943473u, 469109438u, 1159538654u, 390308918u, 1603161004u, 2906790921u, 2394291613u, 4089459264u, 1827402608u, 2166723935u, 3207526147u, 1197293526u, 436375990u, 1773481373u), + SC(1882939156u, 2815960179u, 295089455u, 2929502411u, 2990911492u, 2056857815u, 3502518067u, 957616604u, 1591168682u, 1240626880u, 1298264859u, 1839469436u, 3185927997u, 2386526557u, 4025121105u, 260593756u), + SC(699984967u, 3527536033u, 3843799838u, 958940236u, 927446270u, 2095887205u, 733758855u, 793790581u, 2288595512u, 2237855935u, 4158071588u, 103726164u, 1804839263u, 2006149890u, 3944535719u, 3558448075u), + SC(1145702317u, 3893958345u, 851308226u, 566580932u, 1803510929u, 244954233u, 754894895u, 1321302288u, 772295727u, 4004336128u, 2009158070u, 4026087258u, 1899732245u, 1392930957u, 3019192545u, 149625039u), + SC(3772604811u, 577564124u, 4116730494u, 548732504u, 241159976u, 965811878u, 3286803623u, 3781136673u, 2690883927u, 863484863u, 463101630u, 2948469162u, 1712070245u, 3742601912u, 2535479384u, 1015456764u), + SC(2610513434u, 780361970u, 4072278968u, 3165566617u, 362677842u, 1775830058u, 4195110448u, 2813784845u, 1072168452u, 1018450691u, 1028609376u, 2101464438u, 2419500187u, 2190549840u, 1837865365u, 625038589u), + SC(1347265449u, 3654928411u, 3255194520u, 1322421425u, 3049188507u, 1827004342u, 3467202132u, 4261348427u, 3419671838u, 2239837129u, 3441474020u, 268041876u, 4157379961u, 971431753u, 2053887746u, 2038404815u), + SC(3723233964u, 515696298u, 2908946645u, 1626400003u, 2191461318u, 1201029625u, 186243574u, 1212380923u, 858781105u, 4236445790u, 1936144063u, 1009147468u, 2407567966u, 1865959325u, 1701035060u, 241151649u), + SC(3696430315u, 3089900654u, 1103438577u, 3528924465u, 1259662835u, 2438429227u, 1692672370u, 2989843137u, 1446894995u, 2239587625u, 2340544036u, 434491102u, 128239031u, 2734594294u, 2667284742u, 1865591178u), + SC(1980028431u, 1099813170u, 2013628738u, 4214038867u, 3231891435u, 3896266769u, 2756820145u, 1490749299u, 951981230u, 3655451652u, 1676645053u, 3593230746u, 3010864552u, 405419875u, 1336073872u, 1398624425u), + SC(3414779716u, 2008156201u, 4125277506u, 2287126283u, 2446053551u, 212726297u, 2794923956u, 3421277562u, 1460719994u, 552209919u, 2551004934u, 953727248u, 3096710400u, 3712627263u, 3614955842u, 557715603u) +}, +{ + SC(461660907u, 483260338u, 3090624303u, 3468817529u, 2869411999u, 3408320195u, 157674611u, 1298485121u, 103769941u, 3030878493u, 1440637991u, 4223892787u, 3840844824u, 2730509202u, 2748389383u, 214732837u), + SC(4143598594u, 459898515u, 2922648667u, 1209678535u, 1176716252u, 1612841999u, 2202917330u, 13015901u, 1575346251u, 891263272u, 3091905261u, 3543244385u, 3935435865u, 2372913859u, 1075649255u, 201888830u), + SC(3481295448u, 3640243220u, 2859715852u, 3846556079u, 1065182531u, 2330293896u, 2178091110u, 3893510868u, 4099261975u, 2577582684u, 4207143791u, 589834100u, 2090766670u, 4242818989u, 2413240316u, 1338191979u), + SC(1222367653u, 2295459885u, 1856816550u, 918616911u, 3733449540u, 288527426u, 308654335u, 175301747u, 2585816357u, 1572985110u, 3820086017u, 3400646033u, 3928615806u, 2543586180u, 1619974000u, 1257448912u), + SC(3467862907u, 681146163u, 2909728989u, 83906098u, 2626131995u, 3872919971u, 2290108548u, 1697087700u, 1793941143u, 3236443826u, 1940064764u, 1563989881u, 527371209u, 610869743u, 1604941439u, 3670721525u), + SC(2302729378u, 1391194029u, 1641771531u, 3876177737u, 1929557473u, 2752989331u, 2519109900u, 1131448856u, 3786463166u, 506905989u, 2345013855u, 2144715811u, 1583628159u, 291930150u, 3243470493u, 4130365181u), + SC(2855519179u, 3147287790u, 1536116015u, 1784764672u, 959281397u, 3099717666u, 86403980u, 3409201632u, 3921301684u, 2101228153u, 575924517u, 1382150904u, 641478876u, 3860064926u, 1937521554u, 2358132463u), + SC(972265053u, 3025511526u, 2467192450u, 4011934802u, 4015820825u, 3179306985u, 1744647725u, 423238442u, 2406064939u, 901607195u, 3316491016u, 4128592049u, 1397491632u, 439641584u, 90500461u, 2834580417u), + SC(1730532518u, 2821193463u, 2700804628u, 2416923244u, 3795632308u, 2799866320u, 3434703577u, 3883111373u, 1777933228u, 2963254493u, 3042948878u, 1746288680u, 2832145340u, 544625602u, 3633879343u, 2300858165u), + SC(62331695u, 2228442612u, 3527845246u, 2989876118u, 3995298903u, 3601545798u, 4170931516u, 445717530u, 1981201926u, 94264130u, 2668647577u, 953251412u, 3322279962u, 3837653687u, 3116466555u, 3369796531u), + SC(2739333573u, 3637259489u, 443756582u, 825678124u, 2455706402u, 2994548791u, 3653546249u, 2584145078u, 1245698352u, 89066746u, 1738138166u, 2916153640u, 1850062717u, 3472193431u, 2110631011u, 1214009088u), + SC(2386327178u, 3993497770u, 1051345891u, 4137183237u, 3078790224u, 3598213568u, 3344610192u, 1517270932u, 869515922u, 2057215060u, 2792454282u, 4228826509u, 3425305972u, 2708629086u, 880185559u, 1356729037u), + SC(2989561710u, 3550122639u, 1990591383u, 2036612756u, 3588709655u, 595888062u, 4189293408u, 1955008963u, 987876526u, 542093629u, 1953520395u, 2315684331u, 2929815182u, 3270759899u, 393611756u, 1677885197u), + SC(2331762734u, 371120497u, 1141333410u, 3466824114u, 4113916626u, 3698793791u, 2483365276u, 4265751258u, 3804325409u, 4085909553u, 3531838853u, 2629626707u, 625187055u, 3045263564u, 198131065u, 3993694760u), + SC(27419592u, 3267954699u, 2966738458u, 3143461717u, 3869766944u, 2163162934u, 1886283869u, 2052225367u, 958768216u, 2006727717u, 2069130137u, 1939449196u, 3015752138u, 258766841u, 3290132621u, 4163970366u), + SC(903383785u, 2983456345u, 4269392462u, 3731664159u, 1837248343u, 1888413004u, 652691803u, 897487558u, 3732206419u, 3625013640u, 1917594162u, 967935585u, 1804564817u, 883883125u, 2389854768u, 2347234078u) +}, +{ + SC(1793692126u, 406948681u, 23075151u, 2805328754u, 3264854407u, 427926777u, 2859563730u, 198037267u, 2129133850u, 1089701106u, 3842694445u, 2533380467u, 663211132u, 2312829798u, 807127373u, 38506815u), + SC(571890638u, 3882751380u, 1536180709u, 3437159763u, 3953528399u, 516828575u, 3769463872u, 1449076325u, 4270798907u, 3135758980u, 3520630973u, 1452980147u, 3957715387u, 3054428574u, 2391664223u, 2297670550u), + SC(2724204046u, 2456139736u, 265045669u, 1367810338u, 1722635060u, 1306450931u, 2894913322u, 3094293390u, 3490680992u, 2550020195u, 3028635086u, 4200216295u, 1066664286u, 4170330175u, 777827015u, 183484181u), + SC(947228665u, 1559209921u, 3080864826u, 3123295835u, 2934045313u, 1590990229u, 2766960143u, 3113606941u, 1136432319u, 3758046297u, 2054046144u, 1377389889u, 3244301201u, 127071274u, 1752358610u, 2783507663u), + SC(1460807831u, 3649051054u, 2799484569u, 1231562901u, 3377754600u, 3577118892u, 1234337315u, 380370215u, 3272388869u, 3656237932u, 2653126291u, 786263023u, 1028996455u, 4274234235u, 4225822550u, 10734444u), + SC(2071087047u, 1934036755u, 611830132u, 2015415885u, 1373497691u, 3709112893u, 3810392851u, 1519037663u, 779113716u, 2738053543u, 2754096050u, 2121500804u, 982626833u, 1064427872u, 1627071029u, 1799421889u), + SC(490669665u, 331510235u, 927653097u, 4010558541u, 1341899186u, 2739641489u, 1436050289u, 1379364712u, 441190387u, 3816107121u, 4151493979u, 3530159022u, 2848669857u, 2894763699u, 1938279708u, 3206735972u), + SC(1164630680u, 735028522u, 1426163473u, 1764145219u, 2188722839u, 2599797011u, 2331123230u, 996298865u, 2803113036u, 1732133918u, 4135374745u, 1403496102u, 61305906u, 1982207767u, 35608603u, 680731708u), + SC(3097030574u, 2239944926u, 3004506636u, 3698971324u, 438440050u, 806226289u, 3299217652u, 2137747676u, 2376642592u, 2372355096u, 1444993877u, 4198291752u, 3194432604u, 579432496u, 3143260503u, 58153128u), + SC(3073570790u, 2457870973u, 3254087300u, 132589961u, 3090464363u, 4031655485u, 3397735349u, 3738272915u, 2438408586u, 1610016484u, 3607490511u, 1979839295u, 1993157220u, 1628966973u, 2566520843u, 2415504793u), + SC(2516700697u, 2521039798u, 2777488721u, 3196543385u, 3593950703u, 2445108602u, 4227515375u, 3361503440u, 3741757104u, 1367007706u, 4282009789u, 2127358709u, 2970274265u, 108953332u, 1376097231u, 3612352600u), + SC(2841122028u, 289695603u, 908429972u, 1449591303u, 3496532142u, 430811028u, 1377898285u, 198605765u, 702014643u, 1582973696u, 1654127041u, 4145703462u, 294032334u, 4235431914u, 3438393459u, 865474483u), + SC(3545445168u, 3333415739u, 2928811023u, 1435493501u, 3112072977u, 3466119300u, 61597844u, 839813414u, 3787328278u, 1928915478u, 3046796186u, 549615137u, 3862451403u, 1325262296u, 3520760105u, 1333228419u), + SC(1325790793u, 3907821545u, 4134901119u, 1951705246u, 3223387882u, 561480379u, 1136389443u, 2963679361u, 3722857515u, 626885912u, 3665060294u, 2975869036u, 1378007717u, 1212143055u, 3672021732u, 2520983812u), + SC(436660944u, 1593040065u, 2835874356u, 3054866405u, 1746716106u, 2901130226u, 3275156703u, 889550475u, 1667636846u, 2171317649u, 477876339u, 169193861u, 3301423024u, 2923695575u, 1084572294u, 981889567u), + SC(3803276281u, 4055280968u, 3904809427u, 186227966u, 932166956u, 2399165660u, 3851784532u, 3001852135u, 813014380u, 4116676373u, 2706810629u, 527442580u, 120296772u, 3128162880u, 662936789u, 1729392771u) +}, +{ + SC(1686440452u, 1988561476u, 754604000u, 1313277943u, 3972816537u, 316394247u, 994407191u, 1904170630u, 2086644946u, 2443632379u, 2709748921u, 1003213045u, 3157743406u, 1758245536u, 3227689301u, 1181052876u), + SC(1258105424u, 4154135555u, 2219123623u, 3901620566u, 4152326230u, 2255006844u, 2043811343u, 3401743053u, 1077175625u, 4217078864u, 23446180u, 3296093630u, 2983403379u, 483875022u, 1821322007u, 933769937u), + SC(4094896192u, 2631249021u, 2047644402u, 1580854103u, 3103587285u, 3577080832u, 2726417365u, 309664155u, 1801899606u, 2578001137u, 150353312u, 1950478529u, 895600852u, 3405805048u, 2316670682u, 3067768105u), + SC(443311827u, 441757202u, 1505167796u, 3339695156u, 4080303377u, 2032258566u, 4249816510u, 3524388084u, 3057881006u, 1951550910u, 755229308u, 2331249069u, 1739558582u, 2222328965u, 511821487u, 2764767310u), + SC(989753134u, 2338266356u, 549068233u, 4113024610u, 2746193091u, 2634969710u, 3079940655u, 3384912157u, 143838693u, 4047635856u, 4286586687u, 149695182u, 1777393012u, 52209639u, 2932952119u, 3267437714u), + SC(682610480u, 2717190045u, 3874701500u, 2657184992u, 2055845501u, 1316949440u, 1867841182u, 3514766617u, 3083609836u, 2586162565u, 866399081u, 1085717952u, 3259379257u, 575055971u, 3866877694u, 451222497u), + SC(328731030u, 2942825188u, 1841689481u, 3492191519u, 967390237u, 99172838u, 3036642267u, 3931425637u, 933459735u, 3523655044u, 2662830483u, 2533317360u, 1151283556u, 1285468956u, 15891850u, 3194406721u), + SC(3082245252u, 2305218459u, 2853219703u, 1279555698u, 3695999195u, 2225441691u, 2702374346u, 2002979755u, 3394310641u, 1438568303u, 441738339u, 2319547123u, 745721770u, 3663132780u, 3613740038u, 3163545587u), + SC(3109530474u, 209548946u, 1705898345u, 1227555051u, 1300903197u, 521706788u, 1046889791u, 392785355u, 1195852439u, 1128202903u, 589172095u, 3844020294u, 989062243u, 3765536158u, 3601935109u, 563198009u), + SC(1408383323u, 2941773350u, 4185382573u, 3662857379u, 4172908289u, 4118722458u, 1935569844u, 1296819381u, 439467796u, 917888253u, 1573015538u, 2875181025u, 22626495u, 313409715u, 121133518u, 1579603291u), + SC(838355261u, 2323744266u, 929233883u, 1533162328u, 2939669145u, 1021427197u, 2448693967u, 1568998094u, 455286333u, 2516902543u, 1708158744u, 278073872u, 978123683u, 2512836694u, 3972232382u, 1433020779u), + SC(2010810703u, 4018381427u, 571706262u, 1692351234u, 4256546562u, 1231266051u, 268479287u, 2820752911u, 2261632188u, 845795375u, 3555293251u, 4247559674u, 3383569817u, 4149228066u, 180667610u, 1402241180u), + SC(3525485702u, 3451430050u, 2349871300u, 60510511u, 4165534527u, 3431222792u, 4244473672u, 526926602u, 763199050u, 672899723u, 1978849638u, 489006191u, 1575850086u, 1948428588u, 201110001u, 2038136322u), + SC(3829603224u, 567257667u, 2324557421u, 3080821304u, 1922441927u, 1741539649u, 2023385976u, 3349327437u, 1997432110u, 3734074051u, 1330703636u, 3180299184u, 1913578229u, 141656008u, 2692604045u, 1602929664u), + SC(29051889u, 27392875u, 2013870801u, 1608859787u, 4192290684u, 944038467u, 2706126772u, 4086572363u, 3654238115u, 631287070u, 4277765317u, 2361271762u, 4170133585u, 2022489410u, 2834765713u, 1378478404u), + SC(2835113470u, 3839837803u, 3596950757u, 2129670392u, 1881028173u, 4057879348u, 2459142230u, 3736551989u, 3032996358u, 1333513239u, 3006303259u, 3885122327u, 4228039994u, 134788219u, 3631677646u, 450886807u) +}, +{ + SC(2450731413u, 2768047193u, 2114778718u, 2363611449u, 3811833768u, 1142236074u, 836975073u, 719658637u, 89564040u, 2055034782u, 2279505737u, 2354364196u, 748992674u, 2341838369u, 3471590741u, 3103440079u), + SC(464369172u, 1784969737u, 2303680721u, 1699015058u, 1839678160u, 53342253u, 3929309179u, 3713202491u, 1764215120u, 2190365769u, 3137266333u, 3919018972u, 3446276485u, 1027535494u, 3649392538u, 1979045036u), + SC(3689697965u, 1535268856u, 4095087266u, 1879342666u, 1901613989u, 4062220771u, 1231692686u, 3479254943u, 517178359u, 3704348661u, 3200159500u, 592930780u, 3995209641u, 2367381241u, 1790597847u, 2276745810u), + SC(1563410665u, 2779883331u, 320555798u, 143478861u, 1984047202u, 2486036480u, 1819096593u, 876845470u, 4160262809u, 1685665332u, 1096211683u, 3396846267u, 1079209808u, 1622135728u, 2746449213u, 2258485533u), + SC(1981422448u, 2212169687u, 873443773u, 3576733408u, 3923794933u, 1875069523u, 3053667173u, 4292418240u, 2192702144u, 1027092432u, 278807989u, 2315740043u, 485097259u, 4099751129u, 1350843241u, 1137138810u), + SC(3929635582u, 2647315129u, 1255145681u, 2059161179u, 1939751218u, 2574940312u, 1013734441u, 3958841903u, 615021475u, 1092396560u, 1516857705u, 4167743313u, 744612233u, 1609870616u, 1905505775u, 2106400820u), + SC(1036005687u, 2272703162u, 2208830030u, 2182996589u, 441615709u, 3591433922u, 3586649797u, 164179585u, 3077875769u, 1792522157u, 2657252843u, 657567108u, 656390324u, 1816007391u, 3075467586u, 3873231707u), + SC(1236896749u, 2895887291u, 1978987518u, 822801819u, 516389325u, 1102535042u, 1787993035u, 3557481093u, 3231661433u, 991180576u, 3686912074u, 1297456949u, 3327185778u, 308709174u, 495078044u, 2969592590u), + SC(2019907021u, 744703189u, 2139199843u, 518542186u, 3124680574u, 142934434u, 551498542u, 3021773546u, 4091561632u, 1051317147u, 825719313u, 3707224763u, 335483791u, 4028731434u, 1335000639u, 4102709448u), + SC(1093818871u, 985937516u, 327542691u, 2046117782u, 1264752065u, 697293694u, 1615263505u, 1156460629u, 2812684388u, 1192736815u, 3019618111u, 4209127823u, 2556369187u, 2112950523u, 637809851u, 2176824541u), + SC(1687299893u, 3728297084u, 490922479u, 3634470646u, 250826345u, 3692215527u, 3273717576u, 965983458u, 2226919381u, 1460789800u, 2122435754u, 2519058236u, 1620196106u, 4066817802u, 1130044433u, 3889340415u), + SC(852530522u, 3312783835u, 1596416107u, 1741549460u, 2684468674u, 3424816114u, 2501858342u, 1775689041u, 2140910620u, 3593295971u, 3269455071u, 2386348485u, 3506744308u, 1454965514u, 1429132807u, 1936823584u), + SC(606602909u, 3019871883u, 3512048756u, 3287518999u, 3877975051u, 3914786486u, 3870177904u, 1340649290u, 520571284u, 3028797996u, 2616337132u, 1103844529u, 3133726039u, 1357152000u, 1508799653u, 31330228u), + SC(2817743510u, 2877820134u, 3034826170u, 1694674814u, 3472934533u, 2992700940u, 940570741u, 734740020u, 2101869811u, 3976806699u, 3986671415u, 556491401u, 2336314226u, 3375597171u, 2706276162u, 2068498899u), + SC(2875346415u, 3996130283u, 2530370154u, 2292821435u, 1717542531u, 4166402291u, 2045046397u, 210928306u, 1305773764u, 891667924u, 1720475570u, 2097400197u, 3748242244u, 1645769622u, 3986372109u, 4259524466u), + SC(258680563u, 3407077353u, 3701760456u, 1531445568u, 3746171918u, 2983392727u, 1490964851u, 3947644742u, 2779475335u, 3867487462u, 2573576052u, 3434694262u, 2755711440u, 3366989652u, 566303708u, 3091229946u) +}, +{ + SC(2925506593u, 3911544000u, 1647760999u, 3077282783u, 810174083u, 3532746750u, 1218244633u, 1800164995u, 3882366571u, 1552758454u, 417617232u, 3581187042u, 1107218813u, 308444727u, 2996521844u, 3546298006u), + SC(2766498247u, 1567718891u, 906631353u, 1539374134u, 2937267715u, 3075423755u, 466239025u, 348294756u, 2802746156u, 3822638356u, 2215866298u, 2676073175u, 2327206803u, 3701444736u, 533673746u, 1949565232u), + SC(779912645u, 2120746348u, 3775586707u, 1719694388u, 3225985094u, 1124933767u, 2466028289u, 3688916232u, 2352972448u, 3100332066u, 3699049642u, 105143046u, 3528587757u, 3202351686u, 3275195870u, 2542878955u), + SC(4208701680u, 3032319563u, 1934783333u, 1683344422u, 1898255641u, 1818484420u, 1090856325u, 4203146066u, 3166734039u, 1425051511u, 411614967u, 1272168350u, 905464202u, 2860309946u, 2899721999u, 4016531256u), + SC(1252276677u, 705548877u, 3321309972u, 2587486609u, 1841091772u, 1176108340u, 2483104333u, 1124739854u, 1417860124u, 2145011089u, 1095816787u, 561231448u, 3047186502u, 2188442748u, 782343512u, 2073487869u), + SC(773625401u, 1399854511u, 2112273744u, 3798562401u, 2328245221u, 4053035765u, 884849756u, 2543299151u, 3064173848u, 3322400978u, 2493736578u, 4109781307u, 3356431908u, 2033183790u, 3916558464u, 937192909u), + SC(1676839026u, 1837563838u, 681907940u, 1979087218u, 3861274680u, 1004821519u, 3526269549u, 3587326189u, 4130121750u, 5876755u, 277168273u, 3347389376u, 1295078502u, 3055055655u, 988901279u, 1750695367u), + SC(1466696987u, 793586382u, 3395028606u, 688541023u, 227515247u, 433349930u, 1151320534u, 2638968365u, 2730052118u, 2419949779u, 4184196159u, 3075595332u, 1762597117u, 3208522231u, 3793454426u, 2205574333u), + SC(2271935805u, 2221340650u, 4006866556u, 3892925071u, 3300102857u, 4023132062u, 1966820825u, 193229358u, 3829742367u, 3288127030u, 2999566231u, 1746318860u, 611198282u, 1740582489u, 586692015u, 272371975u), + SC(1512874083u, 1683202061u, 3100471136u, 875884760u, 2252521753u, 3056609126u, 2397470151u, 3238829627u, 398340158u, 1086173909u, 2650682699u, 3851040891u, 267796754u, 1063916466u, 134772391u, 616879617u), + SC(1190901836u, 3498895828u, 121518848u, 4122627266u, 4044339275u, 3929319666u, 3725675569u, 2249645810u, 1648430039u, 805152867u, 604009597u, 428134903u, 3660078748u, 1495738811u, 2912743026u, 3529964664u), + SC(1098872981u, 3803982233u, 1184687675u, 1724685244u, 1166128174u, 3324080552u, 2889006549u, 591614595u, 442372335u, 2188313994u, 392144341u, 559497602u, 2786744839u, 1080958720u, 963196350u, 4153188088u), + SC(2439538370u, 4080798018u, 3371249236u, 2272355420u, 3780648680u, 116755088u, 1743646150u, 3071185844u, 3348389643u, 3506488228u, 3592742183u, 3935997343u, 3470563636u, 4177761627u, 2879753187u, 203653531u), + SC(3278048310u, 2898758456u, 2355004932u, 2165371155u, 909690763u, 4208028121u, 3529336571u, 120122699u, 1468577489u, 2088039937u, 3804192119u, 4005659309u, 496708233u, 114985314u, 4186471387u, 1516837088u), + SC(1694326758u, 3482448156u, 2533790413u, 3535432659u, 1293417127u, 2007819995u, 3512854075u, 2476797465u, 936262398u, 4149678787u, 807292055u, 1683402105u, 3767740082u, 682769936u, 2956180563u, 2800734304u), + SC(804843744u, 1565609957u, 1986774659u, 4163563545u, 1192892219u, 2967653559u, 1407927717u, 134508609u, 2584983666u, 3798685912u, 1759632157u, 1938927553u, 3974685712u, 2763800386u, 3702401831u, 3969543832u) +}, +{ + SC(2016238746u, 3648008750u, 3741265531u, 1468285316u, 3314132186u, 3225615603u, 2260838904u, 650230459u, 666608997u, 1079817106u, 1685466519u, 3417306450u, 465799968u, 1454367507u, 1432699603u, 4060146438u), + SC(1761873323u, 2175765323u, 123320402u, 1086415744u, 3425420197u, 3163463272u, 2096010147u, 892174421u, 3834451486u, 191088153u, 650609666u, 1384830375u, 430440180u, 1275312435u, 936713210u, 3964237847u), + SC(3490530311u, 4154571850u, 1473147571u, 1874492814u, 3394183939u, 690761407u, 1765847887u, 4254640890u, 3957252213u, 852293459u, 403059579u, 1419995731u, 373422976u, 1691953324u, 1513498303u, 3782064719u), + SC(2587537765u, 1727580331u, 2067598687u, 2050934719u, 1018600463u, 825517190u, 281367288u, 396667874u, 2125440864u, 2142555808u, 3739024155u, 471264185u, 2298783646u, 926505635u, 485317745u, 4237064052u), + SC(4177694527u, 1331122857u, 2632274962u, 2272030823u, 2711200568u, 493910969u, 64158788u, 2976239616u, 2805230971u, 1856476899u, 706343172u, 883417303u, 3085501222u, 2167885061u, 2608970459u, 1305891290u), + SC(3887930902u, 1612140391u, 329833229u, 737708613u, 660227298u, 2588285981u, 3429746116u, 4247477263u, 2536670475u, 1091054728u, 1521783433u, 4262529359u, 3261855757u, 453613765u, 484850910u, 3619344637u), + SC(3635973664u, 4002263582u, 683484955u, 1188525929u, 3024525647u, 1588813480u, 3496033065u, 109022234u, 2342061519u, 1416918501u, 2207158673u, 948640868u, 637445219u, 508491813u, 3897434662u, 680054967u), + SC(1039851594u, 403130855u, 3868498597u, 1611578944u, 2942424644u, 2874427101u, 1261647069u, 261871566u, 2520758170u, 2840740989u, 3799279215u, 381717039u, 3582347301u, 2025353438u, 2948438214u, 2918501540u), + SC(81851588u, 3029358979u, 3777821133u, 2109529880u, 3684139703u, 3572137489u, 2624799u, 2076188243u, 53500651u, 2606703535u, 3206313372u, 346558880u, 465806762u, 434266486u, 1902707603u, 4080110534u), + SC(3612241613u, 1917140707u, 4136616607u, 4041104182u, 2193790431u, 801466537u, 3599423303u, 3561003895u, 1189069231u, 8494816u, 4244955339u, 451969883u, 3908494655u, 517115239u, 1812731691u, 777430858u), + SC(3522137911u, 2027939004u, 2210696271u, 3920541975u, 875695915u, 2825269477u, 687289812u, 4252564584u, 1824925315u, 507608234u, 2614820601u, 2462525050u, 3886866857u, 668083682u, 2768243607u, 3293579201u), + SC(1682273922u, 1330912967u, 3636074852u, 840196898u, 1025234484u, 1557176067u, 2837118766u, 3109038869u, 594323342u, 3200796742u, 1959017554u, 1440926582u, 3021668826u, 3738492638u, 446292405u, 2414347832u), + SC(4116164451u, 4091036540u, 474505628u, 1269644927u, 3643568118u, 1673027873u, 1438360759u, 4022285580u, 4024623082u, 1654730750u, 1581385912u, 3853471495u, 335076979u, 2185560806u, 2494598452u, 3520671279u), + SC(4099595861u, 2215053464u, 488918654u, 2772869965u, 2247823716u, 1588093320u, 1138185172u, 732569291u, 247618738u, 1702163570u, 1772683376u, 1056938600u, 1997535786u, 2064838561u, 3705150691u, 1453615480u), + SC(3809909081u, 1962152573u, 3909100601u, 1479514000u, 1615313752u, 3569344372u, 997113509u, 3043376485u, 3480943705u, 4021042580u, 2284195092u, 2749518560u, 3037939132u, 3554704413u, 185068622u, 683070990u), + SC(3163624176u, 326387389u, 438403431u, 1924575191u, 1706136937u, 2432230714u, 4175139676u, 713582699u, 175432919u, 505729353u, 375905517u, 3179239595u, 2233296987u, 472507277u, 1822318909u, 3059447908u) +}, +{ + SC(3955300819u, 2390314746u, 8780989u, 1526705205u, 4147934248u, 1494146575u, 1667625450u, 2277923659u, 406493586u, 957460913u, 3449491434u, 912766689u, 1387230361u, 2368913075u, 3538729245u, 2943257094u), + SC(2095358020u, 3831852940u, 1752942227u, 477088929u, 2503091779u, 898077u, 2215106688u, 1298885808u, 352224250u, 3952364758u, 3669616566u, 664714721u, 1826685582u, 1576488055u, 2121138397u, 1442223205u), + SC(1378268686u, 187975558u, 3210161726u, 870689300u, 1860632239u, 902013623u, 571573600u, 25414363u, 3412397724u, 3841538145u, 215707661u, 324367139u, 2323478150u, 3794355190u, 1128115053u, 2519022352u), + SC(566244395u, 2591175241u, 2926679038u, 2852174582u, 200192886u, 521908517u, 2098042185u, 3563798587u, 1529741033u, 1248315044u, 233787221u, 2706044694u, 2870731528u, 3970719810u, 4167465378u, 525407392u), + SC(2196340159u, 4056996284u, 1702457669u, 2086317410u, 3933566271u, 3751624213u, 4023204768u, 677196918u, 2137509058u, 4037704026u, 2299370032u, 1748548051u, 3326874481u, 1974512389u, 1751264060u, 266112293u), + SC(1812114662u, 524787647u, 285577300u, 3638318945u, 3389691808u, 585441476u, 145370930u, 1149989778u, 1314386440u, 3471672106u, 908522311u, 4171434326u, 329350743u, 2954206373u, 856961382u, 2008618089u), + SC(2318825510u, 3826102862u, 687747522u, 4263777564u, 2387018418u, 1135189382u, 1414060091u, 217356911u, 2998889592u, 698204196u, 801530770u, 3479982231u, 1117806357u, 154519605u, 960816747u, 3149429798u), + SC(3250819610u, 351683992u, 296382659u, 4149667465u, 2183346760u, 1485561783u, 2218034265u, 420633334u, 1869679065u, 1205517989u, 3666184780u, 1975151679u, 371905540u, 367504198u, 1917294142u, 2403996454u), + SC(3958230362u, 3773825115u, 783748416u, 1243337893u, 4032003144u, 3908441244u, 201600922u, 2000451013u, 728826842u, 3533421010u, 3229478766u, 278198864u, 3933272000u, 1331731276u, 3202405750u, 1474627286u), + SC(3181836998u, 2581633616u, 3993055681u, 4020956268u, 2094932060u, 3551878275u, 393027783u, 2154269634u, 2283536956u, 2260289773u, 832949759u, 2403309662u, 3488387345u, 1652392255u, 393935478u, 2309058441u), + SC(4141036972u, 1727820200u, 832481848u, 1055621047u, 1091666560u, 1393833209u, 3406509646u, 2428157250u, 2974564551u, 2286298667u, 3776410458u, 815994971u, 1241023789u, 775596275u, 1035618310u, 3934253771u), + SC(206932164u, 4239023187u, 2046365950u, 2616857124u, 4246776524u, 4059028269u, 129664965u, 907402684u, 3859465657u, 4204192080u, 91453633u, 301171900u, 385561248u, 2689085222u, 1614465584u, 3977451005u), + SC(3683171878u, 3148577689u, 4042394721u, 1085044656u, 682611813u, 2857177748u, 2417075323u, 2983755657u, 3777418770u, 2448398967u, 3909780770u, 4000218621u, 4227580585u, 2425908645u, 1704039191u, 3712924954u), + SC(290465694u, 3921687099u, 2971845338u, 1854613741u, 1583022754u, 371222458u, 1744154613u, 3918664956u, 1960343256u, 1291903121u, 4010470137u, 1525668440u, 4091170130u, 1370665614u, 3468958243u, 1262617601u), + SC(469638518u, 1129475898u, 3766065538u, 1777952666u, 2589258222u, 3182239596u, 2626554219u, 1853296675u, 2912212627u, 2518041806u, 2743002885u, 3765128027u, 851537937u, 2059010589u, 1827964742u, 3630398912u), + SC(2458599023u, 2699477701u, 2305781427u, 2536499567u, 2118412162u, 1356010449u, 1426052710u, 725853717u, 1358092245u, 4196538471u, 66159936u, 4076320019u, 3065284443u, 2664736186u, 1943959552u, 939016920u) +}, +{ + SC(3159079334u, 690659487u, 1550245019u, 1719420482u, 1795694879u, 2846363486u, 15987067u, 569538014u, 1561199762u, 967336684u, 3110376818u, 1863433225u, 3468533545u, 3644881587u, 369296717u, 3652676359u), + SC(3207794512u, 2847938045u, 2415472979u, 1444858769u, 666387488u, 1660608279u, 1038886882u, 10876848u, 2468284561u, 2494495733u, 2622688628u, 2362399325u, 2213804831u, 3448783854u, 3958704532u, 3639349832u), + SC(54374990u, 186360229u, 3420619566u, 1356363720u, 2768151763u, 3862789233u, 4270651882u, 2681019589u, 2332931746u, 928338209u, 3968478928u, 3908570621u, 923281930u, 2285715383u, 3620920276u, 130031468u), + SC(4009596626u, 493238747u, 1786722937u, 653638870u, 1636723425u, 1884625267u, 2113708566u, 1448416211u, 3613674959u, 239497564u, 404863679u, 1521570751u, 2819432609u, 623319225u, 3073321373u, 565867032u), + SC(1220575379u, 4235426741u, 1889734996u, 43054857u, 879216917u, 3299856237u, 2922851906u, 1054251029u, 693641076u, 1704223409u, 961665328u, 2828086835u, 2727513652u, 1580557310u, 4169876178u, 682569510u), + SC(1757813477u, 22814395u, 3549822650u, 2254547303u, 372100012u, 1555116803u, 2587184145u, 3995169383u, 2645743307u, 188252331u, 3723854483u, 2138484090u, 1895504984u, 3538655836u, 1183003060u, 1439034601u), + SC(2578441833u, 3136721732u, 380864696u, 817462912u, 2257087586u, 2256998015u, 93155068u, 930999672u, 2793712092u, 2223512111u, 3157527446u, 1098951014u, 3490358734u, 1362531303u, 2421324125u, 1961922428u), + SC(1049179776u, 2969815936u, 3869567708u, 2883407597u, 1876243265u, 3498929528u, 2248008570u, 1231166427u, 3544374122u, 2839689583u, 1991744998u, 2798946627u, 736844268u, 1293771673u, 153373649u, 1931110485u), + SC(3785289356u, 1913060964u, 169967200u, 3348219956u, 3732729076u, 987877186u, 3063387163u, 3310757163u, 3480818987u, 1991307039u, 2882756981u, 1215305494u, 855630497u, 1471153868u, 1338946323u, 398364632u), + SC(1356154057u, 3013675057u, 3810909135u, 1796458190u, 2691409967u, 3963509663u, 2487357466u, 2764459334u, 2828737787u, 378542508u, 427318427u, 2412936991u, 393927878u, 3384382899u, 1135834101u, 3447900619u), + SC(3813669196u, 1922867812u, 483725924u, 518662823u, 3954558327u, 1908218112u, 2258643690u, 2093138355u, 1162728847u, 205977116u, 821018600u, 1237824238u, 2980682686u, 1821003630u, 3221633606u, 2717269894u), + SC(1353035942u, 2442753208u, 348196860u, 2355246066u, 2218279077u, 2203055542u, 1964199656u, 1329637142u, 1824193111u, 3965017045u, 795175573u, 1029253807u, 3915633667u, 1084707851u, 1682462202u, 2090124205u), + SC(190807548u, 1133131805u, 249542006u, 2858611426u, 304500253u, 2183315108u, 4145782890u, 2998333644u, 962888949u, 974441750u, 1484862994u, 801464190u, 2311388331u, 114769498u, 4260362972u, 1017092877u), + SC(1311406963u, 465174990u, 1760870095u, 883652788u, 1015674641u, 840236175u, 3124632038u, 2756294642u, 178804852u, 3164952754u, 241649187u, 1040890173u, 82588907u, 1771630815u, 1058353446u, 2473824375u), + SC(943051847u, 4107933890u, 535438460u, 2683519853u, 3177219980u, 3711205196u, 3390138615u, 2920849102u, 3747455519u, 4138118615u, 400899690u, 4278329560u, 2602463649u, 808685972u, 136036034u, 1078020636u), + SC(2185570356u, 3896907774u, 3620938057u, 1790823508u, 720763411u, 2404776615u, 3257162972u, 1221107462u, 3223154083u, 2528715719u, 688766234u, 1813423773u, 2324112952u, 83241050u, 4119437520u, 552112812u) +}, +{ + SC(3370489298u, 1718569235u, 523721575u, 2176389434u, 218587365u, 2490878487u, 2288222859u, 812943600u, 2821517993u, 3626217235u, 1545838667u, 3155352961u, 741681736u, 669093936u, 2382929309u, 2620482966u), + SC(40739723u, 469402467u, 1810137291u, 109375068u, 1888845715u, 2140810583u, 1053250454u, 3220064762u, 2539857789u, 4089587896u, 1364971662u, 2996699084u, 3939034030u, 2020251221u, 1606532641u, 3453095239u), + SC(1376139558u, 886121026u, 3003069127u, 3500718919u, 4223467610u, 3212808910u, 126355621u, 2065481301u, 218954382u, 1236555811u, 2283280895u, 4256918831u, 1550185311u, 896721211u, 4286247506u, 2515527710u), + SC(2942433244u, 2364220023u, 3675668782u, 3695614763u, 4041312428u, 2311531471u, 543507321u, 1902188023u, 1380686629u, 2455468346u, 2346421766u, 2211296276u, 3675221499u, 3890242164u, 3592353914u, 323566438u), + SC(971323999u, 4115912859u, 3703400072u, 2662062035u, 2355087034u, 610373016u, 2293984834u, 2456129286u, 2927901115u, 1832014620u, 1168920846u, 552716242u, 3101454502u, 1707155244u, 3450287619u, 2546358284u), + SC(3062358608u, 1394539264u, 4158727824u, 1704721957u, 1117692646u, 4057908715u, 1958466020u, 2309578289u, 271836599u, 2617957229u, 202314495u, 2948978715u, 1423414031u, 4128837100u, 1937488702u, 3301405882u), + SC(1276638700u, 885904232u, 3686149920u, 3283641475u, 619290126u, 2510808612u, 1691008630u, 573145513u, 506979295u, 3062936948u, 2703005699u, 4056634904u, 3460956977u, 3783023797u, 1215556973u, 3726733337u), + SC(3145485089u, 2008513183u, 2407056102u, 633050174u, 2634406893u, 2883313710u, 1233018283u, 3273507959u, 174012667u, 2126243450u, 2258342097u, 2857351925u, 3446764464u, 1187986524u, 3004835628u, 3228122242u), + SC(991481464u, 1720231754u, 1918287975u, 2752686681u, 1174123782u, 4227334584u, 1634945718u, 1074218184u, 3572504705u, 1199611126u, 1378243227u, 2901862427u, 2145083550u, 1055786253u, 3960418624u, 587771424u), + SC(3060872990u, 789280525u, 184089463u, 1784976524u, 344050594u, 2949751745u, 3173202246u, 3813443247u, 1247337895u, 4000924548u, 76989753u, 2093985529u, 265772293u, 3310477933u, 717631968u, 1024610284u), + SC(3399834097u, 2964304651u, 3593395714u, 2850196125u, 2344305533u, 3920139836u, 937580696u, 1116439644u, 4147778799u, 544787491u, 2461636418u, 2647550544u, 1451408824u, 3266700679u, 829974548u, 2625074193u), + SC(645329496u, 2808202504u, 1366740717u, 2841442794u, 1298546911u, 2730798019u, 3834987045u, 3258634143u, 4257492959u, 2976079952u, 1735944512u, 988426767u, 2395072762u, 3103996991u, 730963792u, 4206896923u), + SC(3457675112u, 4140282966u, 1286302693u, 575230857u, 2270112110u, 3056424235u, 1835144711u, 421529065u, 2499621064u, 1907217915u, 1365357672u, 2875249236u, 1193490885u, 644367230u, 2115448516u, 2507997379u), + SC(70240820u, 3745431832u, 1098747160u, 82118642u, 2446590634u, 851446619u, 2715739022u, 2142293045u, 2689000746u, 4219383621u, 3140617705u, 1457579904u, 2541485894u, 3932513084u, 3406615220u, 2746135210u), + SC(2576508439u, 3244150028u, 2516535555u, 3986514000u, 2903382402u, 2225326585u, 1780804949u, 1164188435u, 1682143109u, 2949153515u, 1249412173u, 349674695u, 3467452794u, 1021028584u, 1194554595u, 1296132950u), + SC(1028084134u, 2577983628u, 184499631u, 1037888434u, 1676727662u, 1831883333u, 1276555462u, 4161670547u, 372201005u, 844715673u, 24290758u, 1268964661u, 297554992u, 4061435345u, 719976096u, 1670144314u) +}, +{ + SC(1239892635u, 3772349433u, 1058531752u, 1409211242u, 2847698653u, 2391143499u, 2637108329u, 3000217976u, 4288568828u, 658925470u, 2552628125u, 1468771377u, 3230644908u, 2692030796u, 7587087u, 1951830015u), + SC(488413080u, 1055864530u, 1967623060u, 3973308786u, 2745059783u, 477755698u, 544732176u, 3786002606u, 1569550024u, 2935491988u, 1047898991u, 1749060996u, 1828274710u, 2943223535u, 3716062834u, 1253889972u), + SC(1626917485u, 492893476u, 2371366539u, 3928996000u, 3710769983u, 1237244931u, 1562679102u, 2930576193u, 2085522193u, 2968039733u, 3202113740u, 4250144171u, 3666251088u, 2016963274u, 293320478u, 3775462481u), + SC(3337977767u, 1831658883u, 1096680294u, 2436280860u, 119870062u, 1444445305u, 1467566544u, 2038307180u, 661842797u, 2493843529u, 3851219498u, 3941720925u, 1848373617u, 4051739727u, 1120765529u, 1101800264u), + SC(929493756u, 2211014659u, 3851484027u, 3468182176u, 147674626u, 3850162187u, 1517171722u, 907705770u, 3997080856u, 3666272567u, 659948161u, 2282159142u, 429200635u, 2563204390u, 1422415938u, 1688129608u), + SC(551422730u, 1797390513u, 2828310972u, 97463725u, 131839682u, 3917501017u, 566617767u, 700714239u, 3061891811u, 856175415u, 1072683059u, 1754819408u, 3533865753u, 2568134802u, 4226648923u, 32646755u), + SC(3538971706u, 2916601269u, 2891999350u, 3825811373u, 2355258376u, 2876141009u, 3940019347u, 1309282440u, 2567828520u, 1367177503u, 2910098023u, 1986452448u, 1802584940u, 1360144734u, 2877029236u, 3033303547u), + SC(3313753312u, 261894832u, 3637017242u, 3699232915u, 3508549542u, 3960876382u, 582644479u, 3199091169u, 3644395252u, 2675904765u, 2072396219u, 4071523208u, 3976776729u, 1025403411u, 2178466200u, 1107450603u), + SC(2163612584u, 2845646977u, 4033161886u, 2723908899u, 1902990762u, 3375716497u, 2588626243u, 513179480u, 3101622846u, 1458272618u, 3875706546u, 3028150894u, 3612001457u, 2583302957u, 3385091312u, 3719047138u), + SC(1256280924u, 3685139058u, 1853414115u, 3160743702u, 3455476559u, 2505590918u, 2308735646u, 3742507036u, 4016470170u, 330769483u, 3470077232u, 3383715347u, 1440115354u, 2667395648u, 1883060415u, 3332144245u), + SC(558087170u, 3027059128u, 1986900497u, 1642930671u, 5966195u, 3083778816u, 3199769457u, 1248728791u, 2110460619u, 327014118u, 2524517189u, 1776442925u, 1472982408u, 3459887088u, 1029172283u, 2232815594u), + SC(1544258748u, 3397993939u, 2721410152u, 2948125157u, 3562231734u, 3011402493u, 3266317933u, 527195819u, 369665170u, 3216603774u, 1952585925u, 258420856u, 3339671680u, 3733846143u, 2326118329u, 2310291176u), + SC(4140585488u, 4198875250u, 3415599245u, 3398679011u, 4155727512u, 331520374u, 785987151u, 146809315u, 2929041163u, 1558279570u, 1346822944u, 4167931729u, 2800498595u, 2809390575u, 3295157947u, 4121566122u), + SC(3571413466u, 1596401972u, 140853088u, 3137527478u, 204556611u, 4111255020u, 3835120334u, 3048525996u, 399176328u, 3005771198u, 780994070u, 3747160103u, 3136546207u, 508755537u, 2521091931u, 1715747893u), + SC(1156063870u, 393984449u, 1521183961u, 3649564442u, 183535572u, 3139859119u, 445469714u, 2815871833u, 1268459010u, 355340626u, 2465929503u, 750513297u, 1590602217u, 3983872541u, 97286792u, 110438349u), + SC(2549125874u, 1976691716u, 2532749644u, 279085303u, 633988261u, 3513450026u, 1057503157u, 1110164955u, 317735960u, 3241215082u, 3855084900u, 4137511567u, 3550729054u, 819799870u, 1929320159u, 2825290282u) +}, +{ + SC(2585638847u, 1394876113u, 3750575776u, 4144761638u, 1991524028u, 3165938218u, 158354186u, 812072970u, 3814951634u, 2507408645u, 1163603486u, 3566585210u, 1424854671u, 3326584505u, 3332079056u, 1901915986u), + SC(1520752595u, 1952396314u, 3263601295u, 3458083478u, 3797830135u, 509407552u, 3232598095u, 1205382790u, 2667815610u, 2560349365u, 2472625295u, 2883979179u, 554514567u, 2376619906u, 638138357u, 2568018129u), + SC(2442202610u, 2091297602u, 25025777u, 3622813695u, 3869161931u, 614884494u, 984078136u, 3345125623u, 3918959025u, 227030161u, 3885929851u, 1281751413u, 1612359075u, 2958486463u, 2884267132u, 3619290927u), + SC(3048700207u, 2570072469u, 1076153001u, 3767270422u, 1408579070u, 2076435276u, 2224129615u, 1962182553u, 1823335118u, 1499162388u, 1563913085u, 2068011578u, 1991334162u, 1665201834u, 1756239294u, 648108494u), + SC(2337582449u, 1819429591u, 3833487099u, 3870804287u, 2300831739u, 2232929806u, 1869816966u, 4084965807u, 4220168543u, 1248736546u, 924637940u, 73528534u, 2319796252u, 3657850751u, 2794932350u, 4220430348u), + SC(3028904021u, 2992718647u, 2354594543u, 3084902105u, 3127673085u, 783373559u, 3896264500u, 3984439851u, 820119108u, 4253719169u, 2623678017u, 3039126654u, 2922756242u, 2436956481u, 442364253u, 918876081u), + SC(1539558451u, 2306960255u, 1095386938u, 770368485u, 2906552323u, 3075682102u, 3534951832u, 2083903147u, 1308495764u, 2261904633u, 2112467113u, 1044610889u, 3222649255u, 1736090274u, 1954974285u, 1361850096u), + SC(587984395u, 1588261189u, 4052666242u, 512106258u, 651085942u, 2768947530u, 1250487652u, 1245674804u, 857176247u, 3594046498u, 647658046u, 2882585491u, 259918032u, 3698728358u, 632752990u, 351374374u), + SC(2404749839u, 3296323382u, 805352255u, 3954906457u, 3558496371u, 2470613864u, 2024150378u, 3564550335u, 2499521206u, 2051669779u, 607498894u, 3748811695u, 1128400961u, 3072401950u, 3042994760u, 811721793u), + SC(3595493043u, 1889077187u, 1981480426u, 4189336058u, 2081249554u, 2321560592u, 971543366u, 358725627u, 3595364674u, 3986924883u, 2193763710u, 4189195361u, 3121216309u, 1140981210u, 3226790033u, 353586077u), + SC(2871195936u, 2843651834u, 635723881u, 287569049u, 2067429609u, 2943584978u, 644639896u, 1264563774u, 670309272u, 2690274713u, 246950668u, 933865226u, 4053660195u, 1381269871u, 462688690u, 5420925u), + SC(977313734u, 4104230969u, 3334283655u, 1580178205u, 1578158646u, 1460773045u, 1728595474u, 3957344726u, 553676110u, 966612385u, 1786516334u, 2979157051u, 921122693u, 911238485u, 3922067113u, 1046213221u), + SC(91424183u, 123813459u, 1667146297u, 3387121372u, 438965888u, 4260725592u, 154972710u, 3237027664u, 3006360433u, 2505005588u, 2902337724u, 2660287100u, 1901200613u, 2646189902u, 2780155597u, 49560303u), + SC(3586622617u, 925349590u, 415005474u, 1260234539u, 30249250u, 2179523979u, 3475887768u, 3019952034u, 3517624902u, 4230850494u, 3734868171u, 742624613u, 822822789u, 3974379285u, 3711572581u, 3366701706u), + SC(329275906u, 1905371123u, 4004795330u, 2339811253u, 353091905u, 548998992u, 3687895576u, 356859438u, 2494263562u, 926298666u, 3983230019u, 2882391620u, 2824170047u, 2247742371u, 1881005652u, 1386887463u), + SC(1046492158u, 2680429213u, 1614272999u, 4010933686u, 2479992689u, 595409283u, 765550354u, 2852655093u, 1983575334u, 3910696497u, 2308266592u, 3012641543u, 2582478313u, 14949228u, 60656360u, 1955264759u) +}, +{ + SC(1355623958u, 2575138117u, 2562403739u, 1638722303u, 1523970956u, 2189861089u, 3498071469u, 1919711232u, 231840827u, 3230371223u, 143629793u, 1497495034u, 1677900731u, 1608282251u, 3485501508u, 3944969019u), + SC(1317209868u, 3823870608u, 3335344652u, 3702793515u, 2425890570u, 1442662397u, 4007605978u, 2976935239u, 1444558882u, 3449074340u, 523287240u, 1767769527u, 1776192231u, 1111610095u, 4035220013u, 3434023407u), + SC(1286632782u, 1751340143u, 184421370u, 3989392405u, 1838859918u, 3681550977u, 707040060u, 2695037953u, 1828105102u, 812532736u, 1115387936u, 1381188966u, 1389542552u, 621856846u, 1135930465u, 831833090u), + SC(2741542793u, 3565635943u, 455105161u, 2389444906u, 2966273581u, 4048751601u, 2569017914u, 1796095397u, 1515760827u, 3870103158u, 2737365395u, 818096507u, 2179280538u, 1254083919u, 2114706477u, 1413209953u), + SC(2036431795u, 3313380793u, 2996275588u, 625273343u, 1627738147u, 2163909313u, 2645773664u, 3066825866u, 3862562238u, 3189614065u, 3074707667u, 1611214266u, 689055345u, 1845962762u, 3616153367u, 98214289u), + SC(1783057147u, 1095836105u, 952581152u, 665189523u, 4159236737u, 3621720388u, 2768968806u, 1541462219u, 1550070665u, 2946487171u, 3084327270u, 3528580128u, 3683323170u, 2326350340u, 681502936u, 611874814u), + SC(2075965546u, 3954443814u, 3457426695u, 3100575745u, 795895906u, 2051458923u, 4220432661u, 3191956430u, 2978441632u, 1935083482u, 1260223004u, 1989210512u, 708452144u, 1742032782u, 412060225u, 942058976u), + SC(1554952802u, 1148928548u, 435577880u, 1218016814u, 774531999u, 4171943086u, 2728379380u, 1755428421u, 3096769247u, 551470356u, 663936617u, 2259245103u, 3605128160u, 4254582248u, 2543346251u, 2641240630u), + SC(2834055303u, 3779347324u, 986655417u, 1060344853u, 1961336735u, 3444096071u, 3402507696u, 1296975131u, 4013745799u, 318316127u, 3012349080u, 1543913977u, 3581569730u, 3073345556u, 1048961320u, 3338742347u), + SC(1917475623u, 1573453706u, 3775608035u, 1560651154u, 3305702627u, 840251936u, 2021694407u, 1567223161u, 1217097878u, 4101089784u, 1480235880u, 823763473u, 1860062290u, 3212933927u, 305432786u, 2664137512u), + SC(488290329u, 2159084342u, 1977681447u, 3072933047u, 2133970307u, 2904163387u, 2929381044u, 2852811875u, 3486789427u, 3312981159u, 2897952520u, 3716688458u, 3312599340u, 2231560239u, 2736260178u, 2100166993u), + SC(2561748569u, 2171003952u, 3930314290u, 4171544961u, 4084487200u, 1829909478u, 4190664042u, 1205662930u, 1332053018u, 3102835265u, 2758716514u, 3094681405u, 890009818u, 1835725787u, 3657145276u, 2012429206u), + SC(1490727773u, 2663703693u, 1786667419u, 3911642156u, 1173781475u, 1032437218u, 949369190u, 3379245680u, 3855657643u, 102309733u, 3862169655u, 1953708469u, 2899532678u, 2185103023u, 2246792392u, 2140300644u), + SC(1105179994u, 3403119551u, 2151897995u, 2133026531u, 4095632628u, 1958582421u, 3756551819u, 1353448323u, 343568827u, 940163873u, 3647008605u, 2675342302u, 2020863909u, 3314608025u, 3678853306u, 2350764749u), + SC(3610890660u, 7527132u, 3948519712u, 999155044u, 1566318108u, 1592356541u, 1395933920u, 3725362820u, 1628394109u, 2361449910u, 3407340106u, 1370203307u, 1521539242u, 166450716u, 1562824595u, 815891091u), + SC(4169640806u, 3985781662u, 2412370154u, 452406588u, 105016225u, 176939651u, 3796204183u, 875428687u, 2497589429u, 82221910u, 4277856341u, 1375558239u, 286683641u, 3316069361u, 519521869u, 2295715438u) +}, +{ + SC(1272080061u, 1249052793u, 3406223580u, 3180222548u, 3305857569u, 3627944464u, 989639337u, 2790050407u, 2758101533u, 2203734512u, 1518825984u, 392742217u, 2425492197u, 2028188113u, 3750975833u, 2472872035u), + SC(23055961u, 3145183377u, 2430976923u, 2926141735u, 1297155725u, 3931229778u, 1820665319u, 2985180446u, 3042883880u, 2460902302u, 3663963302u, 4048537328u, 3995357361u, 2497655514u, 2584741032u, 1771542440u), + SC(3555045486u, 1984442910u, 1340694232u, 3778110580u, 1134128670u, 754930307u, 645413801u, 419876731u, 718672506u, 2655370853u, 650960778u, 1175245889u, 3468383881u, 2671574337u, 44753822u, 3359158981u), + SC(289419990u, 2387037467u, 2851881154u, 4063189789u, 1829943773u, 2629576813u, 942097665u, 562844855u, 2647906183u, 117874787u, 202211775u, 3519990636u, 3082138694u, 1836881245u, 583992800u, 2183831281u), + SC(2721107251u, 1807232970u, 3202569269u, 3708638735u, 3532027994u, 4114767065u, 2764680156u, 135914892u, 1473879964u, 2935607101u, 4201045944u, 3202280567u, 3793176244u, 41830505u, 969791663u, 1519485648u), + SC(1497249350u, 1416277963u, 4236912956u, 1827689230u, 1595876921u, 792380080u, 2973128767u, 43523726u, 365213078u, 1703541227u, 1608568996u, 2447861933u, 4236202627u, 2270952660u, 996772411u, 1327926083u), + SC(930257564u, 986864131u, 3788206015u, 4282936823u, 3575152799u, 1711906087u, 3523467955u, 1026809541u, 3754676659u, 126901401u, 34761162u, 674497989u, 546239979u, 3916171265u, 4169565745u, 1773808675u), + SC(1188611875u, 4038625723u, 846346399u, 3124471166u, 3540873247u, 133640400u, 3354116939u, 2182269853u, 3158440321u, 538434017u, 508437111u, 2461460484u, 1662547818u, 3578959375u, 209001526u, 3335522863u), + SC(4264155336u, 4248354463u, 3273048757u, 2876562537u, 4290560912u, 509206354u, 1722430555u, 1796475043u, 864985283u, 4161684480u, 1401260098u, 2472895218u, 2342429930u, 827590760u, 300446032u, 2313806596u), + SC(2581459341u, 3429172659u, 2024065972u, 4099664542u, 1148350145u, 3444652410u, 3577141975u, 2981349935u, 4203645620u, 3053918552u, 3258443245u, 1577847138u, 1635931506u, 873577721u, 2391948063u, 3880308298u), + SC(348781524u, 168814463u, 525438717u, 333282992u, 3413546488u, 563982782u, 3571937262u, 2168075485u, 2567967190u, 4135534212u, 2773230423u, 2560090101u, 4070935767u, 1086323696u, 2826348049u, 1398744384u), + SC(1019826995u, 663251023u, 3152709102u, 4103744231u, 1372971676u, 1214523997u, 1159949230u, 2703418845u, 786011241u, 2156179212u, 1156040729u, 3454726929u, 1928366760u, 4000343119u, 4288863167u, 3214674902u), + SC(2681260382u, 4128008241u, 2510236484u, 1511367526u, 1684226652u, 979685907u, 2954161581u, 3173181201u, 2348267479u, 1347783270u, 1149362033u, 739573388u, 2484197607u, 335176176u, 4239049161u, 739872951u), + SC(2990421330u, 2634202447u, 3179573376u, 2783566953u, 2521510477u, 3781882024u, 2239710944u, 2912891640u, 4089020966u, 4152247187u, 3694477470u, 1764138981u, 2507816564u, 3857045441u, 3960587447u, 1062920229u), + SC(2607237939u, 3082469982u, 2290705462u, 3066564076u, 3196897175u, 4248068159u, 2751492888u, 1096521131u, 1350638971u, 3209282660u, 3725272910u, 717966828u, 1468400702u, 1807609199u, 332456241u, 3283231722u), + SC(752680913u, 2889161941u, 555836002u, 2587892579u, 793746532u, 2681266768u, 719050347u, 3803221u, 1422540107u, 1615046554u, 1724888503u, 923959013u, 3231965435u, 2753642578u, 1839210672u, 3344430910u) +}, +{ + SC(35118683u, 172484830u, 3416100291u, 3700412376u, 540823883u, 3117923166u, 4211300427u, 2853939967u, 3346783680u, 988896867u, 2435731911u, 431849862u, 1744411117u, 2614624696u, 297543835u, 4045956333u), + SC(2040009399u, 3617093372u, 1922089948u, 419196583u, 488784755u, 779735420u, 2537006207u, 704283906u, 1092151363u, 2578829348u, 2820670194u, 2121866485u, 3135057501u, 2561548080u, 1838738028u, 3520705790u), + SC(2347233873u, 2021920507u, 3747005552u, 3302704092u, 1421533666u, 2091592699u, 3349570591u, 3813605549u, 115030445u, 3350012162u, 2428670067u, 3833734570u, 1834087037u, 3648785167u, 3795974654u, 230561124u), + SC(3166315679u, 1499753232u, 1332394568u, 512254231u, 3188709397u, 2787249743u, 4120940214u, 2887173650u, 3906489413u, 2295240998u, 2578634494u, 1588397589u, 1261609842u, 547227344u, 3285763119u, 2699176838u), + SC(2920964533u, 3740093834u, 2438698186u, 1924062654u, 745692322u, 2251363856u, 1198363872u, 1945834517u, 3791006786u, 4021475876u, 1202959856u, 137650558u, 3764418806u, 2028729507u, 3549185474u, 4085572018u), + SC(2715838951u, 1959655040u, 1103474341u, 961883214u, 3220165814u, 946461598u, 3310562057u, 3895921046u, 3423737504u, 3466676673u, 4053794032u, 4003999722u, 704282430u, 186242539u, 1929875533u, 2743489242u), + SC(3863164996u, 1689760206u, 3183192577u, 2929742795u, 2741898431u, 3788088914u, 2356234821u, 7039846u, 36640443u, 397902308u, 1207730645u, 450227359u, 3243815017u, 2084858847u, 1390053102u, 1800322698u), + SC(2899288970u, 284742850u, 4164169257u, 657423444u, 1943078242u, 2187671316u, 2338824812u, 1463135135u, 2886625321u, 272841068u, 3193451269u, 275059886u, 893727404u, 1588413844u, 3713690958u, 858582046u), + SC(220208151u, 2716463025u, 2076296789u, 1220608226u, 1158026410u, 3025895717u, 2670689841u, 80726308u, 1182245224u, 514737744u, 1549626516u, 2794996864u, 1140029757u, 2873715616u, 2877687374u, 2336796195u), + SC(1712499527u, 3009254442u, 159655935u, 3126441867u, 4265886590u, 3094626983u, 2035167860u, 2311303989u, 3444838362u, 2596170866u, 3801673179u, 1837914686u, 3231006463u, 1247923284u, 584065013u, 4147287941u), + SC(900839097u, 216650153u, 2150488455u, 1952211291u, 2276027011u, 3518121564u, 3433005808u, 477320989u, 4007917006u, 2860081630u, 3686269191u, 921073036u, 3922496269u, 1487331039u, 3974930220u, 2054391386u), + SC(3348685354u, 1508268709u, 1715972206u, 4188610176u, 2563479521u, 2178972493u, 3288192040u, 3754144178u, 1173914019u, 454089507u, 3398639886u, 574196980u, 135948897u, 105476021u, 2877469782u, 2140775314u), + SC(60661201u, 2505799644u, 1330476086u, 2641855913u, 3370908611u, 3545887069u, 2369313011u, 278373074u, 1677987717u, 2174519857u, 2497481396u, 1568231376u, 3671812134u, 1893623337u, 1526376990u, 3328774765u), + SC(2836826686u, 3566150450u, 1220364883u, 3711427451u, 3528155780u, 2723292785u, 3326692341u, 2222164977u, 1858144237u, 1869912598u, 665154087u, 1299959695u, 2415334423u, 2100885199u, 1677986979u, 848478053u), + SC(2293836559u, 1740853836u, 1031472293u, 3209927466u, 2722427870u, 1686533972u, 3134525842u, 43165427u, 4133377528u, 4179858803u, 3614537390u, 3380004165u, 2699323023u, 2351902646u, 3408173486u, 2494501357u), + SC(1820258417u, 3371479244u, 1743152481u, 953496909u, 4267482844u, 97428203u, 2755286865u, 830318058u, 1082737155u, 2096588114u, 869939293u, 1138867599u, 3414628151u, 3300388932u, 2755674787u, 886356844u) +}, +{ + SC(1981590337u, 957784565u, 3778147127u, 3909235993u, 1637480329u, 2280601867u, 1059949562u, 2968107974u, 4043469535u, 4159249472u, 895867525u, 402468881u, 3186079639u, 86430659u, 4027560590u, 4067278225u), + SC(174847206u, 2629171882u, 2333280466u, 3666750170u, 1365991192u, 1932613341u, 769674425u, 2870677148u, 3091982589u, 717533940u, 691292429u, 746447527u, 2346750954u, 2424023836u, 2489851473u, 1000862947u), + SC(1294470925u, 420276534u, 18534679u, 2910625938u, 3592407247u, 3676292946u, 91786365u, 2630448437u, 4060747756u, 3372072880u, 766751258u, 2899531047u, 631745164u, 3523898915u, 3168717447u, 2801541394u), + SC(4228902076u, 3340600279u, 3364406353u, 4167190351u, 39030410u, 2148305555u, 4106423272u, 4019775241u, 1048613489u, 896239533u, 2278643848u, 649090509u, 1858593869u, 1017004108u, 2725922618u, 2362479567u), + SC(3279186701u, 4095625861u, 3191586341u, 3252046177u, 4161721618u, 2329134038u, 751155705u, 2989611709u, 942304573u, 3648059604u, 2883823407u, 1492175829u, 54393633u, 3106238944u, 429976962u, 1435978615u), + SC(3849622377u, 2984399872u, 690474125u, 61954906u, 3671421106u, 3429544548u, 2830056933u, 4242121816u, 952897126u, 3854066003u, 462125754u, 3261473627u, 4248077119u, 2601130223u, 2596495819u, 1081964366u), + SC(3544595842u, 126020837u, 2577264196u, 3433073867u, 496013073u, 2132398305u, 2482253446u, 1347711182u, 3954364337u, 261394336u, 1107608476u, 3443266300u, 104305688u, 870955527u, 3446753045u, 646876293u), + SC(164137956u, 1354687087u, 347069906u, 2162313159u, 2097666782u, 2177194309u, 1083298213u, 1791764705u, 445921337u, 2034078155u, 2254058003u, 1297019339u, 2457505957u, 3923390662u, 3364713163u, 2092921u), + SC(2010686846u, 2180989257u, 2265174665u, 208481647u, 547071646u, 2570387552u, 227431381u, 3946252713u, 1802054573u, 2876468168u, 3435214380u, 619729504u, 96719536u, 601795828u, 1679578869u, 3266813859u), + SC(1689091897u, 2850488954u, 85895902u, 2363909390u, 557966933u, 189022184u, 4135255025u, 2090271113u, 2804992462u, 2897353835u, 3129164865u, 2671868525u, 1204434986u, 2421048110u, 1069687644u, 573230363u), + SC(1864118934u, 1742326766u, 130305247u, 3848358018u, 448383585u, 389136808u, 676464280u, 133776905u, 3973153497u, 15653017u, 4189644276u, 1910866015u, 4017185152u, 3100723612u, 137322886u, 3499754296u), + SC(2165760230u, 1978556390u, 4038887110u, 3280144759u, 2755863878u, 1292009146u, 4196675347u, 2883653205u, 2360229279u, 2940095236u, 4183119698u, 122598923u, 483221264u, 2336117478u, 1200036442u, 1470973u), + SC(22625049u, 2110942382u, 3865539390u, 3568657648u, 4280364838u, 467068956u, 1638706151u, 934686603u, 1016938107u, 1378881668u, 2052861738u, 969631954u, 3114829317u, 2704079673u, 4202235721u, 1896331078u), + SC(1272877817u, 322275610u, 2048255u, 3828419764u, 283292018u, 656555904u, 1730883898u, 407673382u, 3259565233u, 3319282763u, 829721223u, 1466466546u, 121051626u, 1142159685u, 3894622225u, 1384264827u), + SC(3763136398u, 3055118026u, 3433748869u, 930030556u, 2135841826u, 2075894041u, 2845381068u, 3086878324u, 257833966u, 160279206u, 524657374u, 1855318297u, 1760771791u, 1248968332u, 2414205221u, 2464430473u), + SC(3809273981u, 900900763u, 2895572448u, 3283497701u, 1349213062u, 580961411u, 3299214221u, 3628519825u, 3643683404u, 3319374656u, 3868217535u, 427844533u, 3841842588u, 2749654710u, 2681210929u, 1051800659u) +}, +{ + SC(1622151271u, 634353693u, 3884689189u, 1079019159u, 1060108012u, 22091029u, 115446660u, 534633082u, 1649201031u, 4042006969u, 137296836u, 1833810040u, 1562442638u, 3756418044u, 1181092791u, 160208619u), + SC(1041667920u, 3037209402u, 1477404634u, 1440610569u, 2797465015u, 2054982250u, 3391499235u, 3605494419u, 3639198696u, 1933432209u, 1915711520u, 2741088986u, 3869566747u, 1879175626u, 717801628u, 458685614u), + SC(2768417957u, 2138940313u, 1896672548u, 1414723957u, 827016389u, 745281061u, 1045174332u, 3577682097u, 2169383377u, 1730416479u, 712654956u, 3155052928u, 1776219501u, 3353461099u, 711436547u, 1497369655u), + SC(1896697766u, 3621973902u, 926548253u, 4069206549u, 2297004301u, 3251063401u, 993943014u, 1270589313u, 3281589988u, 588955836u, 2429665887u, 1734915238u, 3409902793u, 2578722241u, 654727507u, 3216225031u), + SC(2536890957u, 2554531636u, 2109372546u, 2649000077u, 358086224u, 3391808161u, 1211714614u, 2605265326u, 2606629887u, 206756474u, 1092207840u, 3362434504u, 3945886373u, 4232252600u, 2886868947u, 3532954370u), + SC(65718672u, 4071991225u, 2060698395u, 2198173427u, 3957878549u, 4022831630u, 3461473682u, 419893418u, 779469249u, 2019627177u, 2019172804u, 3609556656u, 2681069216u, 2978123659u, 1249817695u, 2366599297u), + SC(2811735153u, 3049657771u, 1390752797u, 1411409994u, 2127695318u, 3083850245u, 787626821u, 1929564189u, 855492837u, 4008216334u, 1809444437u, 2182869717u, 813270534u, 2247412174u, 1161082081u, 1381922858u), + SC(3920648469u, 503487540u, 2083562080u, 327383264u, 2785608988u, 867359286u, 1036950980u, 431152821u, 1419040671u, 2665230771u, 2455357484u, 351717207u, 3187759581u, 3348793239u, 2511298896u, 1213040259u), + SC(2396309679u, 670711827u, 2849604206u, 3201137057u, 818618388u, 2531623890u, 3805810347u, 1463443182u, 79508933u, 3480790940u, 3579218280u, 263259195u, 3368747551u, 3044188079u, 1352272344u, 3090026690u), + SC(337838342u, 789695791u, 185502398u, 1517725636u, 783544345u, 2877621235u, 2946546356u, 1215973672u, 1208860651u, 725001171u, 1289736233u, 3756237869u, 1654092362u, 364807179u, 4279861158u, 4016003402u), + SC(1113567525u, 3780565260u, 836674522u, 1827009520u, 756906197u, 2663480421u, 3902552087u, 3507352398u, 774509259u, 224530498u, 2361577079u, 3744385228u, 3961162378u, 2586454589u, 3040342450u, 332039963u), + SC(3041171145u, 1474749273u, 2282851768u, 649990155u, 2952549483u, 1360702019u, 1809905451u, 544396952u, 68636355u, 2878101257u, 1478326650u, 2199663643u, 320705780u, 628185476u, 2087425498u, 3828181698u), + SC(3988280964u, 459019854u, 4007245269u, 1946776277u, 125932076u, 3922945473u, 608655237u, 759981570u, 1458494773u, 3686363491u, 3746534866u, 3692063331u, 290340676u, 486223220u, 3313127929u, 2280570810u), + SC(233319658u, 3886064320u, 853251650u, 1236563554u, 538386922u, 1967845333u, 3003439052u, 2872751142u, 150287328u, 2176354561u, 3956114759u, 3858039u, 2003618785u, 4212993191u, 2956509701u, 3196752221u), + SC(2121593903u, 3906201458u, 1137774967u, 3978600103u, 780659717u, 3484790562u, 769856015u, 36405780u, 695767695u, 3397748350u, 3377872749u, 1577340836u, 783581424u, 3804923626u, 2896998870u, 1723843622u), + SC(2572703671u, 2154230449u, 1195305676u, 4208655231u, 922600921u, 448134411u, 986012643u, 2442352758u, 1662902878u, 1367546113u, 2863017129u, 59878996u, 2111442975u, 648834983u, 865532037u, 1000323350u) +}, +{ + SC(2802315204u, 2299944053u, 2128407100u, 3463617348u, 2448441666u, 1070000794u, 1884246751u, 210372176u, 4075251068u, 1818330260u, 3223083664u, 3496698459u, 3376508259u, 4156094473u, 3718580079u, 1962552466u), + SC(3866141502u, 1978128229u, 2646349807u, 2688968712u, 1012393569u, 2539553175u, 2230158790u, 2206981245u, 3747509223u, 1243575365u, 3510697084u, 4007723917u, 859148499u, 1713821117u, 199178654u, 2644187203u), + SC(1964672019u, 297703434u, 1518880848u, 3373273121u, 959853764u, 2251122694u, 723413077u, 800337307u, 648287930u, 2947400245u, 1113383775u, 3610122168u, 1829970570u, 2892296971u, 1554744636u, 494969279u), + SC(4031050415u, 1835549397u, 2490029791u, 1131956513u, 1204048760u, 1914510905u, 3436953651u, 3943499769u, 1759802551u, 3820069122u, 4025269834u, 2717988015u, 2671631612u, 1159803272u, 1951365142u, 4085381442u), + SC(606110736u, 4064038873u, 70240913u, 2494945854u, 3729188113u, 2063877878u, 3912150605u, 3215847250u, 2977890044u, 3389766053u, 356841724u, 356991784u, 2228722660u, 3145515298u, 2594559598u, 1158432841u), + SC(1794017518u, 25183950u, 1671020817u, 785574353u, 95301808u, 1715172822u, 2718673424u, 1470113919u, 1142251437u, 2499778479u, 4281783303u, 1325560741u, 2913926884u, 3804531669u, 3139007483u, 1406557472u), + SC(2970751291u, 2450850294u, 545967636u, 1959629374u, 3303894193u, 455065073u, 41447235u, 1831795469u, 3594460859u, 4077235761u, 722461030u, 598330044u, 192707446u, 509790368u, 1051867275u, 1446366645u), + SC(1959543921u, 1887295052u, 3154544834u, 487969766u, 2252004301u, 996805128u, 2018864848u, 597352487u, 1136669046u, 533675042u, 981364938u, 2653382923u, 1408807893u, 2742559841u, 1833041360u, 1912794731u), + SC(2721713526u, 3549551325u, 601974093u, 2790584575u, 3951999363u, 4215366345u, 2845142034u, 4218934731u, 1726020765u, 823952138u, 3809833u, 4233069287u, 1129914456u, 1399496316u, 1915356031u, 4169077603u), + SC(3926695685u, 1849292395u, 1522137139u, 1552827989u, 4109112844u, 2060253220u, 2853920191u, 801241282u, 3422535773u, 1693187125u, 2113050221u, 2708536698u, 2777027446u, 4174902187u, 1811957361u, 3772547370u), + SC(3930825929u, 747327770u, 2505687587u, 2880650279u, 583976081u, 3834434841u, 1957901663u, 82062519u, 1246607062u, 4096185443u, 1298601955u, 3551964017u, 2293924654u, 2316870880u, 1326950040u, 3135743003u), + SC(2476396705u, 2790106263u, 443544224u, 2802435205u, 819417773u, 177556618u, 4130535785u, 2505448107u, 2591437865u, 1610510350u, 3815578981u, 4114533339u, 2461835810u, 3856846001u, 1439644255u, 3343979676u), + SC(4065627430u, 2927818196u, 950831561u, 4171626868u, 1177734694u, 150634338u, 2487656862u, 796691698u, 2119716392u, 2975402883u, 833495592u, 2179672277u, 346833760u, 3054174076u, 3573945862u, 3318693908u), + SC(2752867821u, 4203551149u, 1685153083u, 1110714758u, 1962211454u, 2837810663u, 1792364454u, 4089022191u, 3967274249u, 192406218u, 3350506767u, 1577386058u, 1497165592u, 1817646171u, 1066733732u, 617241273u), + SC(307712584u, 3903562077u, 681601120u, 3047177738u, 2486055863u, 3842609448u, 3660507009u, 2553494609u, 3174736607u, 3482954246u, 1496988826u, 1025695462u, 3184242644u, 1095387068u, 949053977u, 2083266597u), + SC(3022399010u, 1538609936u, 2420072227u, 990220729u, 2914167049u, 3768364162u, 1346299210u, 1681335666u, 2574961060u, 4053930867u, 303191498u, 2606902764u, 726562386u, 2306023171u, 939416980u, 608183941u) +}, +{ + SC(1862109024u, 2933191225u, 198801920u, 104305860u, 4011109577u, 4122560610u, 1283427153u, 1072910968u, 1957473321u, 1766609671u, 2854361911u, 4075423370u, 2724854995u, 3336067759u, 2831739585u, 400030103u), + SC(3665137971u, 362515859u, 3613170351u, 1634568159u, 2407386812u, 2769867978u, 3661728638u, 966943982u, 2329232814u, 928287686u, 386060431u, 2380767940u, 993235698u, 994357638u, 4262826729u, 789587319u), + SC(700222805u, 4205189715u, 1681820282u, 2408317852u, 3145763515u, 149703318u, 2996102375u, 2778856747u, 1243021847u, 118692771u, 660320701u, 2037909966u, 3471407521u, 3539034550u, 2338530850u, 798101514u), + SC(202761792u, 3072251152u, 936980226u, 2112028598u, 55725596u, 545941282u, 2866544613u, 2541609642u, 2986914411u, 250525398u, 494419489u, 904338436u, 448237071u, 2519815520u, 3547503723u, 3479815920u), + SC(2591263445u, 2313710919u, 2225850186u, 2907469855u, 1923973028u, 2439332754u, 1359667863u, 1147453888u, 591668157u, 1802961428u, 2115337573u, 3814501239u, 1652114003u, 3286770823u, 2320492326u, 1627762005u), + SC(915583786u, 1541647557u, 857793588u, 1120457139u, 593298997u, 1235522530u, 3835902793u, 4029633796u, 2892088014u, 950803214u, 2067553664u, 3466102617u, 417988445u, 1721721291u, 2995105031u, 1833135847u), + SC(3713015457u, 984220366u, 1636921821u, 69668826u, 2853588756u, 3372417728u, 1514016965u, 3165630303u, 549067200u, 2237752955u, 3528219045u, 2819816242u, 2536477233u, 430232621u, 1219272797u, 2682238494u), + SC(4158909478u, 628504302u, 1961569314u, 3701318609u, 1298978065u, 2797817112u, 2778611026u, 2986972418u, 2728592083u, 1350107926u, 261737783u, 1726357156u, 2342206098u, 3937750792u, 3688276065u, 1598643893u), + SC(673033353u, 989709407u, 1304069795u, 4233856570u, 603282839u, 3834722266u, 3349356388u, 2690783748u, 318351191u, 3370905692u, 2347975280u, 2009518842u, 2234183321u, 2940030960u, 2623873751u, 1542240694u), + SC(2380479990u, 2443937714u, 165899369u, 1753008008u, 3688956092u, 2346743686u, 143829732u, 3830274100u, 446444093u, 1705814492u, 2316415254u, 1337109896u, 3093454689u, 1928322219u, 2296006624u, 2093435857u), + SC(4072133379u, 1665275533u, 1975626640u, 3338948757u, 3639875020u, 2527617364u, 2537708733u, 3825629008u, 3956434656u, 2047924528u, 2149850378u, 563001677u, 1364815414u, 2503665164u, 637530147u, 630327427u), + SC(2169035971u, 3667715128u, 133026623u, 1213164483u, 1858042667u, 1566345391u, 3257221880u, 1553218197u, 1494901497u, 2543246705u, 3407410762u, 149097838u, 2595763051u, 3921913476u, 3975713216u, 1013875562u), + SC(4285039888u, 3972750160u, 2508056116u, 3828502305u, 1554885499u, 2478771653u, 3465835374u, 2839338634u, 936668484u, 3860842840u, 1796057260u, 539213045u, 1979230663u, 2637220243u, 3822691920u, 124051918u), + SC(4008482152u, 442930842u, 3844390262u, 1477377511u, 2570068482u, 380269897u, 3550124210u, 1507268577u, 1690622835u, 1216029693u, 2876552462u, 1409060125u, 862828291u, 1145788484u, 2966975851u, 3091998876u), + SC(992351977u, 3038251247u, 1125019979u, 3468273479u, 2933515034u, 2848650947u, 3581678949u, 3449520008u, 3870604714u, 2854135121u, 1257402460u, 1206940695u, 2996845551u, 725641056u, 3899090423u, 600507448u), + SC(1594814264u, 3363681343u, 1687711901u, 1220822433u, 2890970125u, 4169329849u, 1095390946u, 3969022672u, 2174219653u, 1940964660u, 1237339498u, 2965031440u, 1016584643u, 2590104317u, 4235803743u, 3748725935u) +}, +{ + SC(770670183u, 2030489407u, 913827766u, 28354808u, 2556411291u, 589717159u, 413516142u, 20574376u, 1695189435u, 3750527782u, 3546610407u, 1435363367u, 2770958348u, 2608593137u, 3331479090u, 2086258508u), + SC(386282669u, 3729286075u, 814752142u, 1413230862u, 2616133966u, 2483044279u, 1602859126u, 1971292416u, 3070813417u, 3451205972u, 735409142u, 4007950155u, 2905395594u, 2869625175u, 3709680291u, 2952203732u), + SC(3404816958u, 563114856u, 2100979818u, 2101934521u, 2503989815u, 1063833326u, 1723163772u, 3130704072u, 2515274210u, 1396315966u, 393457735u, 2691705207u, 828877164u, 3349330754u, 122605524u, 2602269000u), + SC(3709941627u, 592327138u, 2051205206u, 810649302u, 871212350u, 1541388603u, 4163983787u, 2631105522u, 665062813u, 2612020092u, 3229205070u, 3819479307u, 3310127863u, 1843015221u, 2875318880u, 3723951791u), + SC(1567440489u, 946197176u, 1275093448u, 4236630568u, 3990268727u, 196525149u, 15396621u, 1859637416u, 3138749279u, 3859238173u, 3227404352u, 2720346799u, 3006927153u, 2147957966u, 397899810u, 870180302u), + SC(1039540230u, 838590221u, 2330450212u, 923346890u, 4067788704u, 3619481496u, 3864357516u, 1659963629u, 3299501842u, 1079788777u, 949881347u, 2502746723u, 3228809289u, 247884983u, 3118597092u, 302086001u), + SC(3566621623u, 1671359399u, 3923258138u, 1638982085u, 325268348u, 4006635798u, 1207442469u, 3002539627u, 4047574291u, 2011583803u, 1713508996u, 1060703309u, 4012225302u, 3776068377u, 2784459927u, 3025510009u), + SC(4215947449u, 1997878089u, 1026649407u, 646510252u, 850804277u, 1871694871u, 3390738440u, 3114862405u, 3567086852u, 195428920u, 1556755650u, 1851670178u, 2207687769u, 3388294264u, 4058594964u, 4248126948u), + SC(45480372u, 1361999478u, 2195192123u, 956464540u, 1294436548u, 3045580134u, 2390633033u, 757048237u, 1350268583u, 862465366u, 1780970485u, 3285033794u, 559081924u, 163710122u, 3170983363u, 2626972150u), + SC(90053239u, 741607095u, 3003181022u, 3546281037u, 1996206866u, 2019149839u, 2216417072u, 1170259974u, 4159879668u, 130215053u, 2605146665u, 3967236653u, 1930867601u, 2409157952u, 3775975830u, 1489883331u), + SC(40478381u, 3873592210u, 35609037u, 272986081u, 3051595606u, 504620408u, 1019656134u, 250693036u, 942133950u, 156032543u, 3738710122u, 1712961843u, 2888111563u, 1171258741u, 645705716u, 511104714u), + SC(239657447u, 2278853730u, 2391081998u, 746810345u, 3484552464u, 1369592268u, 2655434121u, 1213868536u, 2934523673u, 3058111393u, 4281279490u, 3966376385u, 1307651904u, 1645528218u, 3652190772u, 1126527756u), + SC(123809694u, 110218531u, 117547539u, 2035819815u, 3596140063u, 1382818318u, 3664758070u, 3019339789u, 2719299822u, 3892472009u, 2876096109u, 412140786u, 2578091481u, 2196346764u, 3068803053u, 1395690512u), + SC(880155357u, 791542602u, 112062960u, 2175792069u, 531560395u, 3155859615u, 1042526138u, 680268271u, 1355330482u, 2485441305u, 148200464u, 964096786u, 3215229166u, 2660485876u, 3076499838u, 353883041u), + SC(2388114644u, 1552848777u, 1649071283u, 2325568488u, 3165393822u, 2695611152u, 2713875122u, 898903657u, 2377088931u, 1138573339u, 3366910425u, 3238180215u, 676550680u, 1043832292u, 1583145576u, 3925456200u), + SC(3116588854u, 731097341u, 35427079u, 152855963u, 655343116u, 2522648040u, 3048497137u, 3838372571u, 777022751u, 2851975543u, 235569549u, 3020787559u, 727642795u, 120522014u, 2406411931u, 4235508200u) +}, +{ + SC(2533741935u, 4150033708u, 3133949860u, 2798619408u, 806119564u, 266064305u, 1385120185u, 1697466874u, 3309272849u, 2305765083u, 4237655511u, 751372374u, 3319766406u, 1139025033u, 1880631363u, 2216696728u), + SC(531691765u, 3457214584u, 2884896024u, 292273176u, 250051106u, 4144042126u, 176967583u, 4132839552u, 2406879878u, 872979134u, 3029052987u, 2283805120u, 2613859206u, 553294045u, 1245122721u, 3840523078u), + SC(1249934121u, 993078438u, 2897493833u, 1681305911u, 57100476u, 365202891u, 2111004277u, 4247410280u, 1628827737u, 3793711703u, 3364391257u, 3510640052u, 3346661510u, 885793286u, 3903378618u, 356572920u), + SC(680178688u, 1413780236u, 356581993u, 2539116542u, 3091268161u, 952393142u, 3601213640u, 3759147734u, 3201912600u, 2029303323u, 3233109971u, 3469579370u, 4191225303u, 2727922547u, 4241219026u, 1108397896u), + SC(581424072u, 2231376178u, 2556335427u, 507971440u, 4133814232u, 3831053002u, 2090051536u, 2682264467u, 1696017056u, 2590078109u, 3496563305u, 1242917226u, 2491190071u, 2058502209u, 3614091208u, 50680464u), + SC(1148224059u, 3153210519u, 1979896166u, 3699990000u, 2774705970u, 4177914488u, 1097495713u, 3943642621u, 28438271u, 1936652546u, 2951976972u, 917798112u, 3345031007u, 3414386063u, 2086388059u, 3336786964u), + SC(3207879285u, 3245056275u, 2753912038u, 3444068917u, 3619101580u, 301796681u, 469710494u, 37792426u, 2324375961u, 3765435021u, 2308122387u, 186365381u, 1748483921u, 2929955002u, 2507797221u, 1450081310u), + SC(2628113752u, 657975440u, 4188527535u, 3642824575u, 1167948061u, 570005820u, 1209373950u, 3114955026u, 2156903999u, 3426648275u, 258877187u, 4116394669u, 3424577769u, 1876755024u, 3610721045u, 137959590u), + SC(1295746957u, 2893879416u, 2731249393u, 43796623u, 1509060380u, 3580712054u, 2063633991u, 246915731u, 245935590u, 2758600953u, 1174591025u, 3759438209u, 874703696u, 3900497366u, 2032803558u, 741576512u), + SC(737124188u, 2899307081u, 1769647158u, 617077642u, 1659909664u, 278863054u, 4232490889u, 625515113u, 3013249184u, 3621100329u, 3078044036u, 1407642415u, 2069197169u, 551433765u, 2836890938u, 3978268035u), + SC(1956698332u, 1096426127u, 1006277939u, 3889489220u, 4030026180u, 3579514159u, 4250029335u, 2203857202u, 3553085216u, 3293255490u, 1237506477u, 1050435484u, 3944172449u, 3169627003u, 1477888937u, 2421667267u), + SC(867315816u, 669003983u, 4033294932u, 3994270030u, 1836283861u, 4220295811u, 3981502955u, 1254544883u, 2953929766u, 3399467612u, 2767815501u, 1837724890u, 359769422u, 525366934u, 2275330754u, 1596174485u), + SC(2757381304u, 618201396u, 1587888624u, 1754675322u, 309402992u, 1862772816u, 1766295424u, 776578164u, 3139660404u, 2518031939u, 4144540600u, 2162413735u, 2788510259u, 3413511116u, 1497090248u, 130610227u), + SC(4221771265u, 792248867u, 928054053u, 140258355u, 1340321712u, 917602285u, 1586319677u, 1429062327u, 3604542914u, 1952132240u, 3586261493u, 1380920077u, 1224870626u, 1321897505u, 3109874655u, 2938496454u), + SC(2321281375u, 3760646295u, 420407446u, 4154009512u, 2825227525u, 4188075686u, 2041350513u, 1285713851u, 1670924786u, 1104780793u, 3524777730u, 1315724274u, 2655303597u, 1675669649u, 3173211461u, 1286635196u), + SC(1138423224u, 1326909178u, 3451890502u, 3840823688u, 3093921534u, 4140902218u, 2007985143u, 2980979703u, 3539657192u, 1914000311u, 3861983402u, 1995841174u, 2739822780u, 4269529997u, 1752802206u, 3674790048u) +}, +{ + SC(1529327297u, 3326406825u, 3128910982u, 2593525414u, 42156971u, 3661621938u, 1244490461u, 1967679138u, 1025455708u, 720268318u, 2871990393u, 1117479541u, 1562094725u, 697888549u, 2324777980u, 3391621955u), + SC(1194208642u, 570517940u, 3796480395u, 3996975496u, 1891180536u, 2012913508u, 2586036803u, 2779419249u, 2424448764u, 654631266u, 3378681847u, 1794600320u, 850887774u, 2610529382u, 3440406071u, 442629809u), + SC(3922776395u, 1021134129u, 4161953411u, 3695042522u, 416696694u, 3141869998u, 2208946602u, 2248782897u, 3791212714u, 2183092330u, 2442693998u, 3821686193u, 359924765u, 1313892u, 732537261u, 3441185514u), + SC(3832647873u, 4126820624u, 1633739521u, 1776853127u, 1990846870u, 2931750872u, 723350088u, 2100866125u, 1353427778u, 3735236517u, 2936890827u, 1037652209u, 3538242522u, 1205440750u, 2681851721u, 3428134171u), + SC(3715940368u, 3100195993u, 139205042u, 933899119u, 508675941u, 2073279390u, 3838896736u, 762162827u, 2670162920u, 363468845u, 4142816880u, 2331633868u, 1859516459u, 2571514805u, 1415575689u, 3310370398u), + SC(1850103477u, 2861511197u, 2158258814u, 1914352173u, 4112609179u, 1613408074u, 2229142795u, 2743410061u, 386541358u, 4131835227u, 238820765u, 350328321u, 796595210u, 325800094u, 1477199872u, 130087432u), + SC(3503083399u, 2168288449u, 3773780757u, 707691176u, 2640783803u, 600372304u, 3521490788u, 1266639681u, 3049849833u, 3696342843u, 1559948576u, 3113774976u, 2979720549u, 3508429388u, 1393959701u, 716360542u), + SC(2281167118u, 2404489970u, 874916137u, 3296730075u, 4266077966u, 1052198560u, 3487426822u, 379036992u, 918125804u, 3064034925u, 3007906638u, 2843799763u, 13395259u, 1525101299u, 3917909303u, 323214095u), + SC(4272733253u, 1134926458u, 1071872991u, 1594198106u, 2743911342u, 1759781849u, 3909986783u, 357998405u, 4054491364u, 588230484u, 3248723140u, 4206364217u, 407716541u, 1660843258u, 3535395038u, 735131513u), + SC(3679104282u, 2103136756u, 3192389130u, 3635496721u, 3762160259u, 813057806u, 1922167568u, 196643685u, 1370854030u, 2657803320u, 3197001343u, 2838705898u, 1256322653u, 3731470140u, 1658864516u, 4241135314u), + SC(4138122573u, 1064712956u, 1914688217u, 3980579663u, 234064841u, 1340868250u, 2408246134u, 2334390091u, 3574856083u, 4185747404u, 2592066932u, 72932352u, 1132443153u, 3084950430u, 2850577555u, 531426487u), + SC(2552518597u, 1814188589u, 3771797408u, 1688271073u, 1392417060u, 1864411028u, 2178912172u, 2411760311u, 772279774u, 2791980611u, 2940533230u, 3149501999u, 370215731u, 2968115262u, 942881455u, 2310941126u), + SC(751991992u, 3546574605u, 2773077774u, 2498170045u, 3288367839u, 3030402134u, 1196921751u, 3823185297u, 3245569995u, 3802879953u, 493640893u, 3321821285u, 1141758187u, 3411864659u, 306737884u, 2761165281u), + SC(1865741334u, 706283811u, 2318095713u, 1419794148u, 2504644337u, 1922210484u, 263491957u, 3084520625u, 705689999u, 2554474009u, 3818190952u, 2133768662u, 3690402460u, 3381523320u, 831084441u, 1146769937u), + SC(831531101u, 3633896804u, 1996958159u, 636851001u, 4007892767u, 380666960u, 2826737942u, 4021398986u, 1411635481u, 515161969u, 4199924051u, 371116192u, 1868116156u, 397223417u, 972171737u, 2331326509u), + SC(974457928u, 3569708670u, 2643527780u, 699675161u, 2627045402u, 3565281489u, 1504374419u, 2979851122u, 688725044u, 4064400308u, 4156347928u, 4119156622u, 2098702491u, 2615488234u, 1090654007u, 3790938610u) +}, +{ + SC(1397828129u, 1248172308u, 2194412927u, 3657598991u, 2085616102u, 1202270518u, 3253032741u, 2632389423u, 1019922267u, 332153082u, 1521672215u, 2163564334u, 3102124007u, 582149809u, 329417494u, 188520915u), + SC(2484409087u, 165527253u, 332794704u, 523511269u, 3524328119u, 4077596669u, 3681267981u, 2969751460u, 3456338723u, 628364217u, 4089156990u, 1135761223u, 1241363911u, 2843043452u, 1927162020u, 1187988850u), + SC(3424784620u, 4001207648u, 1967060425u, 33527184u, 588161341u, 2216089406u, 1194534688u, 3972415390u, 3430941953u, 3671974564u, 355464831u, 2638417624u, 987848314u, 3854256447u, 2513703271u, 847178398u), + SC(944122325u, 1095537200u, 1611102749u, 3845108718u, 3985128242u, 1188491807u, 3783427529u, 722821803u, 2594736624u, 4038805042u, 2146959275u, 3199724336u, 3631416672u, 3989329185u, 1113423723u, 925573746u), + SC(536468163u, 2790961065u, 141113925u, 985919057u, 2438788330u, 374449238u, 2980068000u, 621714839u, 2454037345u, 2810385667u, 3189321079u, 794373297u, 4178743943u, 2630861151u, 1229894711u, 2665151675u), + SC(71889345u, 3684655732u, 3834974630u, 40555081u, 3804280840u, 423207811u, 1620826812u, 3717508581u, 1813258849u, 713714932u, 491517868u, 2389605511u, 767769458u, 2826892693u, 3923819122u, 3331321015u), + SC(3333750894u, 150650636u, 3555142699u, 1161199649u, 3068475424u, 1509735584u, 1033908609u, 3073273527u, 3313105177u, 3410735718u, 2770838598u, 2161939200u, 1654309303u, 1247727621u, 4123284974u, 3218452135u), + SC(4107359918u, 3667881557u, 4099213325u, 905728122u, 3167924799u, 3731720507u, 1537227227u, 659110227u, 2101733778u, 2731849932u, 1103266972u, 887588276u, 2413509058u, 3876926094u, 2675347623u, 834362982u), + SC(3178393694u, 2636806389u, 1832500758u, 186297941u, 3662837586u, 3282938029u, 1064394039u, 2117567716u, 95811670u, 1968831533u, 3070787872u, 2658254448u, 3676980228u, 3909574788u, 2135784404u, 3803100103u), + SC(2624310917u, 420491519u, 3322620679u, 3357048697u, 614451586u, 1196461215u, 41516451u, 3256616699u, 3715883496u, 2257787428u, 2455669147u, 880443853u, 2246776764u, 3074399406u, 278369115u, 1177356599u), + SC(439711555u, 2231299488u, 1079942678u, 677737570u, 563039018u, 2032266501u, 3704274118u, 1877323449u, 2386821791u, 2066266240u, 2520835526u, 1611863315u, 3800297318u, 2553770190u, 1751820038u, 2175904420u), + SC(3515911639u, 4055231138u, 2717511782u, 6831543u, 3016647759u, 2007513585u, 1217171617u, 3815960975u, 2720128636u, 364849140u, 4285658094u, 4211508323u, 127732138u, 997100418u, 3152669382u, 146802488u), + SC(3082714386u, 513166810u, 2182067081u, 798923178u, 921230382u, 1956178560u, 883901335u, 4290259857u, 2290170782u, 3274942148u, 2025203706u, 2950735447u, 3706997198u, 979032741u, 1714061744u, 1756952042u), + SC(1785121933u, 665679939u, 3927612276u, 926826810u, 456860581u, 4247102861u, 1802871345u, 3111467239u, 2947918463u, 4090223916u, 2765919892u, 3848356305u, 2236940933u, 2379663516u, 2033761836u, 170415812u), + SC(723418419u, 3083992977u, 2885930256u, 4084559514u, 3550295439u, 795067132u, 3902666387u, 98659646u, 3559229619u, 3518103022u, 3093345450u, 3504265473u, 3135355783u, 1746911831u, 3896748938u, 1982334610u), + SC(4151598450u, 129451956u, 3923175367u, 306344029u, 336516292u, 3560777935u, 2695409605u, 934056748u, 4131395595u, 112767211u, 3377236273u, 797539933u, 516899453u, 2089210576u, 1999558205u, 4107023428u) +}, +{ + SC(87353816u, 3198238907u, 1232123158u, 3291424375u, 3695263554u, 2608617182u, 3798070797u, 3966302680u, 3847946128u, 278442153u, 3929504461u, 3056452729u, 3658519828u, 643043450u, 684101279u, 121314490u), + SC(4041434108u, 1283940781u, 3208791522u, 2974918612u, 861706326u, 3183082284u, 508820598u, 682206875u, 1177134745u, 1065833400u, 1830916342u, 1348337823u, 1877305145u, 2647094535u, 2714586296u, 2450197741u), + SC(2726369020u, 1580548584u, 150986819u, 369792970u, 2983651480u, 3064179956u, 3511715342u, 1538695618u, 3829066845u, 578378703u, 2038030944u, 3732775932u, 1174552062u, 2377418012u, 375009203u, 1203897576u), + SC(3480144388u, 847968760u, 3831609064u, 2454845771u, 827762235u, 3561019074u, 3068061128u, 2125290281u, 500142325u, 2613926927u, 908976630u, 461018064u, 1790330457u, 2138554260u, 3099515250u, 2668195629u), + SC(1153226571u, 752634643u, 4102962367u, 2953166708u, 3172028384u, 1546019245u, 73810680u, 2123706323u, 2289283451u, 1736737040u, 4246735980u, 196740994u, 886758605u, 1893565373u, 3405498929u, 3744937024u), + SC(768993978u, 3888906052u, 3538251248u, 352204151u, 4022234611u, 1471705290u, 4243963811u, 2027117811u, 1763868778u, 1322271979u, 3608278288u, 3888498758u, 3465093513u, 3125049811u, 2129222282u, 295188310u), + SC(2552844131u, 1588346847u, 4175462227u, 3528353039u, 48525488u, 1810438463u, 342094266u, 3279671133u, 111165134u, 1329165912u, 4063411685u, 1911765579u, 2818934337u, 3808545183u, 3789526924u, 1948478023u), + SC(3331030119u, 905985030u, 3533623355u, 799989600u, 1593247216u, 4044824934u, 3057376453u, 1132187407u, 2788031862u, 3252641138u, 1745792893u, 1362467427u, 2194538589u, 4207162080u, 1731158987u, 3426969514u), + SC(282742454u, 1925220542u, 3537150606u, 1044967349u, 4104410814u, 3036747834u, 2170951116u, 4063975818u, 2876870249u, 40785387u, 3225638952u, 2818597718u, 1556539976u, 2301588618u, 2800555653u, 916700871u), + SC(607531008u, 2820787318u, 1270007122u, 63140951u, 2489460286u, 3749254552u, 3480926448u, 2300022433u, 3335552281u, 3577740253u, 4083676266u, 1879037356u, 3793973091u, 653990091u, 981292091u, 2669230849u), + SC(1168110979u, 889306226u, 331429321u, 3194220363u, 4271486769u, 2440942709u, 3008822642u, 561011853u, 2621371879u, 1149493671u, 1110535664u, 2670803472u, 394628735u, 4014155619u, 3742604108u, 1418371877u), + SC(1139004104u, 1152838795u, 3053437035u, 3533998804u, 965296070u, 2842987726u, 3847937142u, 3591812355u, 1659887171u, 3058851485u, 1843832825u, 2284970388u, 153709291u, 2147381595u, 1241923942u, 3246474482u), + SC(2372841964u, 95150550u, 785345036u, 3777509922u, 3777338585u, 1256811659u, 530593057u, 2218391448u, 163045439u, 4110451435u, 940149273u, 3289892018u, 1950559815u, 2046468986u, 785769535u, 229305669u), + SC(4222560409u, 1251917359u, 3419952330u, 3518946758u, 2125025139u, 840904710u, 2104865575u, 3206919775u, 407519472u, 2004634252u, 1712650404u, 3590313236u, 840286442u, 2628712493u, 3254945248u, 1148702071u), + SC(3313735124u, 1648160975u, 2356873919u, 1752134136u, 1812666743u, 1155388994u, 2048656880u, 513774477u, 495906662u, 2103152333u, 2943961999u, 735251223u, 2523783965u, 2210023145u, 1945848363u, 2437613245u), + SC(1086803487u, 4028294733u, 2247710942u, 1830793111u, 1634316303u, 2935377055u, 600165818u, 1578619540u, 2988076738u, 457218665u, 4176910460u, 454493682u, 1199052867u, 1940805269u, 347367761u, 1212452462u) +}, +{ + SC(3715433378u, 171840999u, 971741983u, 2238541363u, 3192426674u, 4094492328u, 467620204u, 194258737u, 3399274574u, 3279461044u, 1351137305u, 2503870624u, 193649547u, 2998335432u, 1712991547u, 2208648311u), + SC(2715750837u, 1950207216u, 2432412079u, 3161034889u, 3163700758u, 2527560734u, 1574123740u, 2830017576u, 1235654592u, 1173758764u, 3503805913u, 3353556737u, 1972267538u, 2593804497u, 4050894516u, 1536909338u), + SC(4252707359u, 3437282014u, 3776749445u, 203710275u, 463138159u, 2772620289u, 1182212975u, 1132575015u, 2008846240u, 1446588540u, 1178588185u, 2810502365u, 3189501211u, 3192046357u, 3703545124u, 2781338651u), + SC(127281203u, 3251296097u, 4229877600u, 1655402395u, 2971465573u, 744237737u, 3839563968u, 1414447733u, 2055975912u, 547297398u, 3544526703u, 1086573241u, 4145442250u, 370020177u, 2948813570u, 1970539713u), + SC(3163465607u, 792227545u, 605650287u, 3454430637u, 4436412u, 957261079u, 2917570432u, 3199157324u, 317922439u, 2607400867u, 3201779931u, 1812841573u, 973872378u, 3838606231u, 3221928943u, 461831659u), + SC(246719913u, 1498935408u, 1945961723u, 1327338499u, 2917210822u, 1660082997u, 597934446u, 1244971072u, 662537876u, 3851981101u, 2064803568u, 1228771649u, 4273868614u, 3144280868u, 3367923741u, 2660003700u), + SC(958115915u, 3015255252u, 3159655209u, 1681296573u, 2092702329u, 3275820278u, 1666603934u, 3861667140u, 2501203189u, 4234907638u, 1084271161u, 60369385u, 1104875606u, 3495688315u, 3738262066u, 4032927728u), + SC(1265262733u, 3131514218u, 237040963u, 4104455196u, 2691347880u, 3487609649u, 1785135800u, 1176579745u, 4089650722u, 3141152552u, 3206481300u, 1333364227u, 276607745u, 113027050u, 176916027u, 1602590030u), + SC(2774594376u, 3129694750u, 2287032514u, 2766750820u, 29083039u, 1069500497u, 840365222u, 3485333678u, 2555809577u, 3972967703u, 629036427u, 3011729266u, 1526288233u, 1119437732u, 917067812u, 194168105u), + SC(592881983u, 3318575349u, 4127058062u, 1732571107u, 3503756272u, 837953701u, 482225210u, 1269788935u, 1504556881u, 1896976655u, 165783184u, 328929494u, 4077662490u, 1253488686u, 3518656631u, 977900779u), + SC(4160682596u, 2908983358u, 1718640008u, 3588190607u, 1505225185u, 4179103009u, 1685793395u, 115536342u, 817223934u, 1402206707u, 3062750872u, 450873212u, 3409531894u, 2142975045u, 1392180850u, 3108320562u), + SC(1943394512u, 2513880371u, 1620134863u, 1529322591u, 4060169700u, 3770293993u, 1183592156u, 3047089385u, 1457468150u, 3671110754u, 1216162597u, 2044466392u, 888112901u, 3589252991u, 523705271u, 1679814981u), + SC(2715251449u, 70744868u, 3381212136u, 1205646623u, 2056792384u, 3523601635u, 3273403565u, 2609964048u, 1635414738u, 3927671477u, 2002719738u, 17329846u, 673666863u, 4128776449u, 1023303890u, 2113317599u), + SC(678583802u, 2909193903u, 1603800869u, 1698604501u, 292539447u, 3194048567u, 1222053939u, 4292027072u, 1744031112u, 463670025u, 1002183205u, 880963334u, 2427537891u, 2521706813u, 3815796576u, 836594698u), + SC(945238598u, 3719965767u, 2849528520u, 3282124488u, 1093917226u, 3479450861u, 2561471910u, 139299258u, 3917471374u, 1798050709u, 2851226278u, 2410252745u, 1571541746u, 2877491529u, 1276119582u, 4206041035u), + SC(3869162698u, 1114491339u, 1196187395u, 1533960773u, 3407411925u, 765004505u, 1831463563u, 3761422880u, 841664315u, 226257499u, 2314441323u, 2186776430u, 2801566686u, 2703073796u, 3780881787u, 1370189991u) +}, +{ + SC(3356584800u, 529363654u, 613773845u, 1186481398u, 3211505163u, 123165303u, 4059481794u, 1428486699u, 3074915494u, 3726640351u, 881339493u, 977699355u, 1396125459u, 3984731327u, 1086458841u, 3721516733u), + SC(3675076449u, 3333909775u, 1262445603u, 3668028655u, 433069981u, 3324184640u, 206500128u, 2656010471u, 782457265u, 4053687660u, 3895856132u, 315252919u, 2755213770u, 922519354u, 2055252100u, 2429801305u), + SC(2756940336u, 2847978751u, 1709353190u, 1195969566u, 1965491900u, 3974470294u, 4065860779u, 457378802u, 2625680435u, 4168918960u, 912437805u, 1940496017u, 2831564708u, 2681452721u, 2977785501u, 178951684u), + SC(2809970073u, 2149172818u, 128792792u, 4173216994u, 3752778392u, 3547909179u, 2139546257u, 363162335u, 1029632619u, 226065897u, 1871318430u, 3511308809u, 4293432909u, 733440206u, 3154916386u, 2246758263u), + SC(731502074u, 2752951666u, 3348551978u, 3130709972u, 1526861742u, 2511266125u, 4044638365u, 215744304u, 1267320586u, 1960868675u, 3421832152u, 2257930073u, 2620941002u, 851383950u, 547951559u, 1340068454u), + SC(2684856551u, 174120198u, 1829892583u, 1225976594u, 2442169561u, 2751359631u, 1396256832u, 4190566994u, 616089248u, 1633732935u, 1633964885u, 3929429044u, 842800539u, 676918864u, 1428572539u, 219449459u), + SC(133428457u, 620472331u, 1882141266u, 1679319159u, 679060192u, 3481716513u, 213482586u, 3423863792u, 4201383258u, 1319777873u, 927348830u, 208213775u, 4087467606u, 3653264448u, 3835415188u, 3916570843u), + SC(1895413499u, 3284443662u, 1774671761u, 36215094u, 1302729892u, 3712548907u, 689399756u, 809699792u, 1542256887u, 1010909539u, 1793915800u, 371041697u, 3719334021u, 1415418990u, 3304256413u, 1722896741u), + SC(4292037144u, 3413799593u, 431584770u, 554753321u, 1212891070u, 139387849u, 4633456u, 4145076332u, 2956733683u, 2226540590u, 257006677u, 3020881975u, 3400787219u, 587473979u, 260993303u, 3410840543u), + SC(4018910540u, 3254488333u, 2078930374u, 2245837925u, 2632570996u, 3139405325u, 1623001428u, 3612462970u, 2032232089u, 519993838u, 198517548u, 1752888302u, 2236384752u, 3428944014u, 3264747145u, 2955960571u), + SC(3519760330u, 3333709979u, 1048481536u, 1985059447u, 2643412116u, 3131942587u, 1137942580u, 1547604917u, 2831143240u, 2752062158u, 438973315u, 216212421u, 839130203u, 4170782680u, 1103599719u, 3606044489u), + SC(3979124118u, 943995448u, 2583700510u, 3458129573u, 1268799005u, 2693058918u, 2421470342u, 2310844252u, 4161944025u, 2910466020u, 1520150746u, 2594375360u, 1025693596u, 3356457299u, 1405172368u, 3357345029u), + SC(3608628529u, 1093067289u, 2172624909u, 336171229u, 1137437622u, 2177129887u, 3319848621u, 3625148145u, 940129946u, 3128586787u, 111536296u, 1792339610u, 2781599252u, 3659875306u, 872551800u, 2302213340u), + SC(1104919194u, 189973497u, 2565652941u, 2930155667u, 3463454839u, 2388313768u, 2445171637u, 16202936u, 1593006897u, 2191020511u, 2084184836u, 1467463398u, 2313657914u, 2691464051u, 4089268188u, 4294499481u), + SC(4188734592u, 3528391612u, 40836399u, 4036867171u, 4090825107u, 2939803682u, 140442162u, 2546416492u, 1084596508u, 3326586985u, 72576332u, 3780421002u, 3675044591u, 2008171921u, 3141075467u, 4288443118u), + SC(3852374110u, 4271371075u, 2076634991u, 3101716180u, 518739558u, 3284103928u, 1607286758u, 3505817896u, 42970787u, 1339303318u, 3280473330u, 1956150319u, 790791234u, 1449585627u, 3814185461u, 3901254732u) +}, +{ + SC(3892284764u, 2210224198u, 97085365u, 934022966u, 3120556498u, 264721182u, 4011343025u, 1936310374u, 2593930315u, 3833725723u, 4141640186u, 2218699022u, 3726005369u, 649732123u, 1594208266u, 3687592104u), + SC(2459115622u, 155132544u, 2344650987u, 2337329027u, 2478875455u, 1363777389u, 666384305u, 779524970u, 131624810u, 1099629813u, 755087667u, 1116544707u, 3462583113u, 1765615231u, 1221263451u, 345614861u), + SC(283432140u, 3102718597u, 937211953u, 3334135604u, 2242058317u, 3044145753u, 1441000856u, 2163904099u, 654999768u, 3976748269u, 4108102772u, 1209693616u, 3022484925u, 2592361118u, 3806239715u, 2457345174u), + SC(1983572202u, 34789206u, 3963513429u, 2661898079u, 3999779459u, 2657216026u, 2570146353u, 810465768u, 1310539449u, 3517224567u, 1830164911u, 2328664885u, 3323158486u, 200812613u, 1588943475u, 1631047872u), + SC(1996456687u, 665652044u, 360516388u, 3634015955u, 3932508085u, 3762889476u, 2869080596u, 2179691892u, 1880327422u, 3850327759u, 1653803674u, 236673399u, 2154944705u, 3229042401u, 2981554507u, 485288416u), + SC(264936494u, 3091907543u, 2050111855u, 2694936127u, 1954787063u, 722933256u, 3813405263u, 739130277u, 2256053561u, 3585156690u, 2029190911u, 3133350308u, 3458910883u, 3499638057u, 41852560u, 491183838u), + SC(2808085465u, 1288453772u, 2477084166u, 3837131567u, 1141955368u, 3112183866u, 1372456734u, 2203526963u, 2954171016u, 3969349716u, 2868857569u, 414601865u, 4013256181u, 468368341u, 1996835394u, 3658768313u), + SC(394302887u, 1097097404u, 3291468368u, 1194224926u, 1035172467u, 1541144594u, 3844885672u, 3479557309u, 3116596876u, 2815221788u, 2598284757u, 360029902u, 1618439794u, 2569763994u, 3258655905u, 2917038348u), + SC(2305403224u, 515881048u, 3401955316u, 2294640138u, 2523482065u, 2913659188u, 1840514079u, 1334322081u, 1545396585u, 4197671987u, 447162882u, 3846426473u, 2663235502u, 750784192u, 4164775689u, 2390294077u), + SC(2816642384u, 3952759529u, 3784236377u, 1797857230u, 1881467157u, 3886776601u, 754213935u, 2085935272u, 3814437883u, 3598631313u, 3014087408u, 1480756254u, 2838244491u, 132661795u, 909841870u, 675503551u), + SC(2053456581u, 627096201u, 3974668317u, 245144267u, 3845450294u, 1209560693u, 1003623636u, 3431474873u, 3952764341u, 3855863791u, 1357940588u, 3374805012u, 2942824193u, 2988435703u, 329942625u, 4139666589u), + SC(73006928u, 4068145413u, 2752900485u, 643186737u, 2386201439u, 296363448u, 2965535934u, 2202307569u, 1300692310u, 3766694667u, 2421404412u, 2295288621u, 1987219755u, 3682346025u, 885571108u, 1086202535u), + SC(3800801259u, 1729576293u, 2024334221u, 266315944u, 3877353536u, 2983817286u, 1164606138u, 2981999790u, 2626097845u, 3537364374u, 3559786635u, 2149380619u, 2137897542u, 2218263339u, 206251476u, 3754285811u), + SC(1009857555u, 1650586423u, 3853695002u, 1715580147u, 1146669099u, 1380681899u, 2219018152u, 1791877891u, 3247738482u, 1042579957u, 4035547117u, 2619207487u, 2408116465u, 3045899420u, 1771645449u, 1340019342u), + SC(2004305920u, 978372350u, 1705342765u, 503429310u, 3635208103u, 3659317811u, 3957481997u, 297103567u, 2521968324u, 599616959u, 1167498361u, 357125999u, 3158983160u, 3114128384u, 3086595483u, 2336612985u), + SC(4103187540u, 1182325894u, 97419735u, 1615223731u, 2031918136u, 2818146326u, 1038685355u, 1330155299u, 2657284062u, 4126074186u, 2871281156u, 2738191090u, 1922990674u, 2689532011u, 4040564095u, 99693623u) +}, +{ + SC(3639643416u, 3974502485u, 1527161781u, 180938703u, 2788643910u, 3418867931u, 2912046968u, 1776807950u, 1185488163u, 2433308651u, 3682797092u, 1938004308u, 753534320u, 795320477u, 3620835863u, 105275502u), + SC(2971894151u, 635573958u, 1662864280u, 3637757763u, 1966418418u, 2382544768u, 3521712538u, 4180511568u, 1216311665u, 1622710591u, 2836323703u, 1065095206u, 3046512769u, 2304432132u, 1370910091u, 3540050165u), + SC(3003078502u, 1266710982u, 63268125u, 3769826631u, 2161222028u, 1624738852u, 2999285769u, 2485757266u, 3350017650u, 1836975640u, 3947916645u, 3226839039u, 3416803572u, 2607406281u, 3224012241u, 1574498192u), + SC(2417128114u, 3148595382u, 316383238u, 491687931u, 3782721648u, 71265990u, 725842943u, 2574280796u, 2910592942u, 1266732336u, 3293910730u, 3812834954u, 758280869u, 2044998492u, 585388705u, 2220041893u), + SC(492257517u, 927280821u, 3326474467u, 3418658462u, 175063450u, 4228793954u, 2332128647u, 2793872080u, 3349562222u, 3060602442u, 1750735766u, 864506271u, 3021446456u, 1089650280u, 684313887u, 2273360774u), + SC(569437869u, 3392548160u, 448456633u, 786222873u, 1891470348u, 56622530u, 1988234620u, 1200550357u, 3540465428u, 1566012807u, 3682627310u, 3118219502u, 421481320u, 474517348u, 4276632114u, 3506654966u), + SC(200012878u, 1289466640u, 383837247u, 2978212823u, 641013196u, 1218428129u, 2429292619u, 1428313217u, 4155302101u, 1036892035u, 3775206351u, 778853475u, 3322870631u, 4195074838u, 3725481759u, 3550082329u), + SC(126839072u, 3914304851u, 1035784989u, 2867617428u, 1989254908u, 3724484330u, 1316610484u, 1040102649u, 1452719164u, 210631948u, 1224888518u, 1113840153u, 910511278u, 2297844676u, 797967535u, 283877762u), + SC(1244500121u, 2493482314u, 3779000024u, 2685901143u, 2759844693u, 2465008309u, 2989069530u, 1046572576u, 3374497605u, 2414541412u, 1726159904u, 3650454710u, 2872643374u, 1536622747u, 1381290537u, 3538573283u), + SC(1982773073u, 895953548u, 653968243u, 2944168854u, 1891156211u, 862699673u, 178384938u, 2122337777u, 3992617936u, 1827424625u, 1827918311u, 4247768891u, 2116109311u, 2389157370u, 3259962586u, 3018719650u), + SC(16401953u, 2306633926u, 2338480543u, 3225473112u, 3429377887u, 2444554167u, 3036218027u, 811186210u, 2350667613u, 3590742085u, 2594672781u, 575072326u, 272468093u, 997542396u, 3031146350u, 3776453205u), + SC(1784787552u, 1031272746u, 3302965053u, 805306745u, 3874552409u, 2790720051u, 483200429u, 1779723984u, 1097599486u, 1897611475u, 2456960784u, 1754250527u, 3808506348u, 3902842183u, 2596972722u, 2928554842u), + SC(2323692909u, 829274841u, 1103316386u, 1866432209u, 1938371795u, 4027514213u, 3989131198u, 2637747342u, 2193562562u, 1183535102u, 290853894u, 707762868u, 1909722738u, 2733745164u, 2354524179u, 94921256u), + SC(390966983u, 2005348047u, 1183001210u, 3460046175u, 1194344520u, 3385791048u, 306982602u, 876126480u, 3192052847u, 3055117485u, 1493712024u, 239443620u, 3677526258u, 3935077241u, 3195438491u, 2508943164u), + SC(3776157658u, 1760005001u, 3371368706u, 4151959572u, 4117952947u, 2782084300u, 3075220020u, 3130861900u, 3220322643u, 4251107806u, 2765944679u, 2454606920u, 3864173523u, 2241965276u, 1056706189u, 2253371852u), + SC(10455103u, 669421195u, 538798805u, 681593482u, 4243109638u, 2765550308u, 1560790187u, 2332940655u, 157674749u, 358872640u, 2549359913u, 811329072u, 318369228u, 2192271276u, 2616093049u, 3105543667u) +}, +{ + SC(3392929934u, 3483303263u, 1976307765u, 4193102460u, 1186037029u, 2559946979u, 3008510830u, 4008303279u, 2792795817u, 3991995u, 311426100u, 3736693519u, 1914150184u, 2000710916u, 1829538652u, 896726226u), + SC(1506989834u, 781231698u, 1423994091u, 932436763u, 2811140941u, 235158077u, 3312925598u, 1277169313u, 2161654787u, 95045550u, 2507009285u, 3400899479u, 1327874861u, 2641030305u, 845165129u, 3067306163u), + SC(81377829u, 4112377516u, 996390415u, 1466127523u, 1087938057u, 1370439327u, 2374941315u, 3221315808u, 35184362u, 4155013651u, 4157224703u, 3036174627u, 820839223u, 644204168u, 3814924360u, 2548030643u), + SC(1091124676u, 3446444543u, 108918031u, 285417020u, 1457053816u, 2518578419u, 3204558864u, 1447981867u, 3090612039u, 774503865u, 3344583272u, 2737274269u, 3562442510u, 1127429989u, 2804182977u, 1775681652u), + SC(2318905039u, 2047942274u, 566069924u, 123115342u, 2915025724u, 2614503051u, 611479778u, 1680640702u, 111791999u, 3565934367u, 3623017458u, 358904698u, 718271833u, 2594429479u, 2455462208u, 1049889789u), + SC(2072590390u, 2994175732u, 776612573u, 3305897523u, 938985307u, 4037860099u, 405398386u, 312125617u, 834030222u, 4269222652u, 3952042783u, 188369721u, 969558599u, 2241466312u, 1494637662u, 3640394545u), + SC(793329188u, 1680204464u, 4194525713u, 1397937237u, 2203558613u, 193170132u, 590149348u, 3837254789u, 2629901211u, 1547324833u, 4256276761u, 178627910u, 1204782838u, 3049171442u, 2847310157u, 1633221731u), + SC(1445130399u, 3305816299u, 706740166u, 1986021205u, 2637844550u, 1419078314u, 1678054887u, 2432697110u, 870544859u, 890225672u, 4294515721u, 4251895411u, 1276311012u, 1177847908u, 2958585231u, 4245816799u), + SC(4225912221u, 703507803u, 1922376483u, 3748563847u, 841832204u, 937238929u, 1762562329u, 2321245641u, 3396851205u, 4196168123u, 2898493537u, 4105193320u, 3913075709u, 3714213782u, 3736794417u, 1813506206u), + SC(473058800u, 1281200026u, 2096535567u, 1916392924u, 2499055699u, 1592813861u, 1665248526u, 1352252079u, 2539722497u, 3800235497u, 2456011531u, 2486813252u, 2969323588u, 2786889819u, 264256920u, 4162650714u), + SC(4093970658u, 1112717313u, 4105391438u, 692152127u, 3191447576u, 765356874u, 3774754898u, 3659714922u, 1417146611u, 4116649329u, 2382824064u, 4091923584u, 2943998996u, 2572469258u, 2350556732u, 4055180934u), + SC(4241530692u, 3958450744u, 2400383404u, 466315350u, 35062538u, 2419973666u, 1574066566u, 718969713u, 2103427683u, 1844215170u, 377438369u, 3472936858u, 4219642124u, 2727593550u, 2415179286u, 530554266u), + SC(1717990860u, 490767589u, 4104938990u, 1912533482u, 1727757083u, 4081637760u, 2971627803u, 4227474711u, 2482396781u, 1077462396u, 1040490667u, 188422725u, 1078987146u, 1905877850u, 3465315863u, 3779881072u), + SC(2343360099u, 2602377036u, 540592495u, 3215700530u, 2276091252u, 330543342u, 1521140429u, 3101043196u, 1353643940u, 4257187260u, 3766970644u, 3977679607u, 2139641066u, 2691703488u, 1191064988u, 3899819176u), + SC(4020334744u, 3662481612u, 4168714619u, 3391835711u, 3785299560u, 71469795u, 2493742903u, 3412561168u, 3292204549u, 1481564183u, 2157273751u, 477496008u, 931448839u, 2827709521u, 2133135454u, 3513095854u), + SC(1821292885u, 77067071u, 2713776553u, 2767520127u, 1059460035u, 985220275u, 2884538737u, 221640066u, 2657382407u, 232264137u, 3155923068u, 3788271780u, 2919723565u, 1308585734u, 3615447351u, 9588952u) +}, +{ + SC(2320406161u, 892569437u, 3092616448u, 1707673477u, 2810327980u, 4012118332u, 4142748730u, 3869507620u, 92116036u, 2366184953u, 1613655167u, 3287845172u, 3562699894u, 416962379u, 1296831910u, 1764080884u), + SC(220529260u, 249394787u, 707093586u, 3327680194u, 3905189366u, 612327964u, 3292761054u, 3030686883u, 1334491337u, 3207860077u, 3280619568u, 1041320647u, 2483468975u, 1479881667u, 3211575507u, 3039423798u), + SC(2075210586u, 859890386u, 3979249840u, 1571749934u, 1787834945u, 3779262932u, 3834468444u, 2848979155u, 3949299214u, 3265482052u, 521566179u, 4090178483u, 2634506734u, 537774764u, 1760986104u, 1885781444u), + SC(2157623553u, 1245488719u, 2108443037u, 4226304849u, 1701247415u, 4110744868u, 1746909616u, 3191493799u, 846028927u, 3826268145u, 3155840342u, 1303740777u, 3325552898u, 2580884535u, 3592783405u, 4209959030u), + SC(535271984u, 3867256577u, 2621667187u, 479852461u, 3031868718u, 681291605u, 3866870888u, 975222367u, 189285295u, 2489945122u, 4002580885u, 1631683077u, 2806354223u, 990581176u, 3013857114u, 805874285u), + SC(4221232460u, 3061114345u, 3434676469u, 1406782470u, 155821803u, 124504941u, 3888697140u, 2788501814u, 1026476732u, 2216503728u, 3089015914u, 2063998098u, 272392246u, 1587339314u, 677528523u, 2432699241u), + SC(3643892943u, 4282202220u, 2100563362u, 826776443u, 1365722925u, 2702305724u, 679208928u, 3149950187u, 1446692720u, 2990196076u, 3121167752u, 25041546u, 1204401671u, 3950457476u, 478874733u, 4191001246u), + SC(1002796340u, 395169719u, 3087599283u, 10336612u, 2123927609u, 504611529u, 4163730275u, 706425703u, 1588733263u, 4149509341u, 1952228143u, 3819719132u, 766367752u, 1435203845u, 1906598194u, 3492363785u), + SC(1774340829u, 3089482890u, 2870005976u, 919794943u, 2035504962u, 4034646005u, 3486869666u, 3458779364u, 2688966610u, 4246698276u, 241215855u, 1193302498u, 1307583268u, 129792487u, 301354381u, 2759318534u), + SC(1993945167u, 2379081822u, 2587040362u, 3154537819u, 1926143939u, 2749781524u, 935556830u, 4138641196u, 1781637476u, 2939621229u, 45782825u, 4247420511u, 1775642409u, 3169645376u, 1224651656u, 1411268824u), + SC(4099217380u, 332485632u, 702660355u, 2932600301u, 2644542769u, 1705216342u, 2043283695u, 2373746705u, 2092217219u, 1660104946u, 3159676245u, 3674605841u, 226100099u, 3987250021u, 2436672589u, 1083744721u), + SC(775618835u, 2173251804u, 4192653515u, 3582997173u, 3769245096u, 484007740u, 503088416u, 1360222738u, 586791868u, 3760447547u, 3490651251u, 3534666198u, 2531156474u, 1207301882u, 832959081u, 3020069982u), + SC(298341207u, 1349761730u, 1369831393u, 1101983922u, 2409775356u, 3892600618u, 3875266737u, 3482966490u, 4002034047u, 2018792567u, 1932407387u, 1184232926u, 3015567427u, 301694942u, 437132459u, 3636206614u), + SC(4090425889u, 2348669465u, 2575850637u, 3995997864u, 3040420324u, 1615191584u, 2490849366u, 2670494936u, 2841563080u, 3763919842u, 3580970157u, 3864708123u, 187158351u, 2199194387u, 4160227448u, 2176418944u), + SC(3040328915u, 1001466289u, 3676795030u, 2946692141u, 3593888463u, 2224708622u, 4148397123u, 4253879884u, 1993280384u, 1176406404u, 3148404923u, 4180061590u, 1786680964u, 4036906941u, 1164279397u, 3562714780u), + SC(1286200509u, 4232891464u, 1656861418u, 3412215448u, 1086562483u, 2512121988u, 2650588176u, 3097245464u, 3192968944u, 2220731064u, 3414522916u, 4204353060u, 3690514744u, 3688465060u, 2246470987u, 498255717u) +}, +{ + SC(1167035839u, 2632944828u, 1562396359u, 1120559767u, 244303722u, 181546963u, 2941229710u, 561240151u, 1460096143u, 346254175u, 110249239u, 1849542582u, 1293066381u, 147850597u, 3876457633u, 1458739232u), + SC(3571928080u, 2436259038u, 1291130511u, 4109706148u, 535321895u, 223400632u, 1981907545u, 281269666u, 3986674262u, 1137333737u, 1403128295u, 1607985509u, 1996916063u, 3564990547u, 3398899933u, 2822030993u), + SC(4187142002u, 2183119934u, 1635192887u, 2899344980u, 2532710469u, 3583070294u, 1537984623u, 296183513u, 2324170481u, 3475303187u, 3887648540u, 634736823u, 1254765115u, 3808584578u, 3772430219u, 561684376u), + SC(513372587u, 1759503751u, 4262413842u, 2894839952u, 1546497784u, 1634597484u, 3075497476u, 1112503488u, 1318854936u, 1645523550u, 1808408161u, 1471049890u, 1607196116u, 1989192912u, 3845591311u, 3230210229u), + SC(4281800629u, 256065360u, 161761292u, 2162610453u, 3289868207u, 803664088u, 1737988317u, 3468667062u, 1313091619u, 3871261661u, 4163576187u, 3519070773u, 663580583u, 2181685257u, 1282501745u, 373224564u), + SC(1305532007u, 4040631353u, 3016994284u, 364840424u, 312087064u, 2832713285u, 813363164u, 1634515727u, 2857968226u, 2482770921u, 2702964276u, 1457003903u, 4233117491u, 978467573u, 454990490u, 2451215822u), + SC(3309788844u, 1373644165u, 2568421202u, 4021050421u, 3214613315u, 3179866441u, 2282215282u, 4192353052u, 766132975u, 1427735093u, 3905164154u, 3510365574u, 3650419996u, 1208798186u, 2311177541u, 3425106727u), + SC(1485656607u, 1872571460u, 3807266779u, 3227427836u, 1367154025u, 2087101352u, 2787930808u, 1683647111u, 611621831u, 1033465938u, 1055561737u, 1718623444u, 3674681330u, 3643294293u, 3841507882u, 2950124804u), + SC(3583452191u, 43558840u, 2702416786u, 2831018419u, 4179535508u, 3293628424u, 3781032090u, 4272940814u, 1561835153u, 3434531879u, 2033417772u, 143682419u, 2206689113u, 2885101743u, 3330838914u, 3213033967u), + SC(1563269339u, 3268845808u, 481878529u, 1366255066u, 188999428u, 2024859095u, 3740130866u, 1902201859u, 3294724532u, 3498902869u, 2063801661u, 3851840419u, 1697955856u, 1216829830u, 2472036433u, 2158918739u), + SC(3706632627u, 1854832685u, 4075722340u, 3009760070u, 1947919686u, 1613829674u, 3359356634u, 160149010u, 3211678034u, 1403957074u, 2395316449u, 232911190u, 3595342115u, 593590477u, 4003146812u, 1042747586u), + SC(3566751331u, 1293366329u, 237055278u, 781035984u, 3490518265u, 471671502u, 3279573882u, 4088428685u, 3341570902u, 1660948465u, 2602036180u, 3189056267u, 1448251311u, 3378653995u, 367559448u, 1247557023u), + SC(332188181u, 124235367u, 2908363616u, 57405667u, 3860321591u, 2915594808u, 3193053797u, 3103490367u, 2893876952u, 791722516u, 2759950240u, 2647310599u, 1060814304u, 1104815755u, 3283917665u, 954167246u), + SC(3633439037u, 1737408037u, 3240746577u, 2032524778u, 210349431u, 1157873376u, 3552462955u, 3068823u, 2593869163u, 1645741574u, 2624282012u, 1595174943u, 3150496822u, 2635369792u, 3670346328u, 1317499755u), + SC(3066163224u, 734815666u, 3189326611u, 2603442644u, 551273493u, 3201260612u, 896218759u, 1203901890u, 3082479753u, 4206490018u, 1615910957u, 3112412856u, 3354260034u, 1776181406u, 227950091u, 2452682654u), + SC(2235295503u, 3336503999u, 656069002u, 1855251063u, 1400966644u, 100804460u, 3316705750u, 794158471u, 3220130150u, 1524496317u, 4024763824u, 915138624u, 1872936127u, 829155670u, 1406327784u, 3285915916u) +}, +{ + SC(3539989726u, 2664422354u, 3717852078u, 3493347675u, 431408204u, 2534904428u, 166307432u, 1071633271u, 2817060747u, 2307358268u, 3433391820u, 2071844151u, 219511979u, 303896099u, 3062367591u, 2892429963u), + SC(4169968731u, 2129799654u, 437437237u, 369342547u, 1225909990u, 105177072u, 378686654u, 1403688950u, 3897807924u, 3252342965u, 1215424641u, 560413328u, 1897408132u, 317929004u, 3828647679u, 1630564758u), + SC(2120346993u, 1574861569u, 4055542703u, 3156063114u, 2155135979u, 3395705935u, 3607950162u, 1649229112u, 1891339524u, 2871189526u, 475543260u, 4035849276u, 919486311u, 4103998043u, 2581732188u, 3337457769u), + SC(2650342494u, 2112594502u, 300482146u, 4214370423u, 3712572735u, 2394678491u, 944484075u, 2859174140u, 1298074617u, 4123981874u, 2931863188u, 4060402101u, 408241016u, 1141274074u, 2343754010u, 2412599648u), + SC(1561545950u, 3513590208u, 46110254u, 2131948246u, 1318148204u, 2154872738u, 1632214749u, 3758828119u, 3082206346u, 1424038120u, 2361241545u, 845137641u, 307971779u, 1724404993u, 861282060u, 1237934782u), + SC(2774909901u, 771645224u, 1285073837u, 2193431137u, 1992145786u, 1323638656u, 695741715u, 2225025760u, 1506694954u, 4281622541u, 648809495u, 1264275594u, 2179049970u, 2134563430u, 1143161913u, 1676304803u), + SC(146493114u, 1026262009u, 3602767471u, 2183478058u, 1903997235u, 4037497130u, 232766761u, 3333583275u, 4037065903u, 338762279u, 3658077565u, 3465013868u, 2987748329u, 1503145496u, 1553131083u, 2250198737u), + SC(2341715858u, 2700579248u, 3859696179u, 2395756825u, 1875611477u, 3083700335u, 3413235310u, 1368601544u, 2011324934u, 2489277894u, 3393073269u, 1479863073u, 1546719681u, 1270920228u, 832404816u, 4096637834u), + SC(3098090164u, 3937526885u, 3922595589u, 3117243593u, 3619511456u, 687964457u, 2049777986u, 2737216841u, 904576627u, 2497431372u, 3782524472u, 2176150332u, 3538905622u, 1249874595u, 386091287u, 597337724u), + SC(653517061u, 2613638042u, 3043803086u, 3430911227u, 3939946327u, 3394071887u, 1634025406u, 422896314u, 2056719107u, 2825344479u, 4064697313u, 3122017483u, 3752686726u, 3984230999u, 2989927946u, 36279219u), + SC(2977387875u, 1756856293u, 2305658602u, 3898809838u, 2022534013u, 3053356239u, 1719149320u, 1006974664u, 3980567886u, 911250528u, 3970581037u, 4208855094u, 2375475175u, 3461024498u, 4207299460u, 172606632u), + SC(2123341088u, 2610619360u, 3636249805u, 2405928311u, 194895330u, 4166746397u, 1666551241u, 3089845290u, 830253287u, 1769367456u, 492844122u, 2898915009u, 1465071417u, 1748645392u, 3136192983u, 3149049830u), + SC(182090295u, 2773063932u, 2875617227u, 2014878906u, 4034576690u, 3504190878u, 648632813u, 578906269u, 3395653562u, 3622802446u, 1642118462u, 1105217635u, 3484288771u, 4187487776u, 3066363798u, 3248936252u), + SC(154149828u, 3967951687u, 1435057545u, 77065166u, 3232269485u, 3912916706u, 592527655u, 4277917673u, 3417904405u, 3905839920u, 1437307359u, 2532079592u, 1386597940u, 4043192840u, 828125384u, 1712244674u), + SC(4144828863u, 1262971610u, 2738002832u, 3848745747u, 554156666u, 3660926287u, 1405749523u, 293551868u, 956195932u, 2061195588u, 3476646641u, 1003448777u, 4182963546u, 1462193925u, 2827901865u, 1370898532u), + SC(287054389u, 4206061741u, 3909899140u, 2957058664u, 2712205523u, 1231432323u, 1252507865u, 2198483068u, 3163354130u, 595880373u, 2050058791u, 535083586u, 4093274722u, 251534866u, 1425149793u, 2349787856u) +}, +{ + SC(3015000623u, 325176924u, 3212623969u, 1014540936u, 2686878702u, 3453922035u, 257234635u, 689320672u, 395365200u, 3425465866u, 3351439740u, 3293249321u, 2261203941u, 1504215424u, 2365812346u, 2486464854u), + SC(2802351214u, 1019547153u, 1581443183u, 2237644987u, 2316167912u, 1277137594u, 922833639u, 1775757119u, 2259030628u, 3320484395u, 3474839377u, 3039388985u, 3157017009u, 701728799u, 45087422u, 1375130067u), + SC(1408178651u, 332882372u, 2572930650u, 1429622838u, 3740348959u, 3769865143u, 1102404486u, 2395773863u, 2055053046u, 1642858333u, 434575788u, 1458579645u, 1077283311u, 3435370625u, 412513198u, 1108997u), + SC(166351317u, 1290556120u, 1492697218u, 3828755332u, 1787027698u, 2627329842u, 818520792u, 3844511768u, 1093689215u, 2840813230u, 4268955351u, 1793367442u, 1197897289u, 1467402002u, 558600125u, 4039642298u), + SC(2618143148u, 4195387407u, 3571081448u, 176847982u, 3021045559u, 2151239299u, 4216918791u, 349987936u, 1438071630u, 2148079477u, 510134808u, 1844452199u, 3473619148u, 3775643892u, 3701006526u, 2069649956u), + SC(2536827719u, 256373429u, 82685205u, 2031847695u, 1685669223u, 3749398630u, 3100433967u, 2559626296u, 2614261735u, 2095898325u, 2650411530u, 4139725354u, 2433652522u, 1465137472u, 3074463995u, 2942034210u), + SC(950856594u, 2511634642u, 447889167u, 3271534101u, 3998181635u, 850059409u, 1500318444u, 2845728509u, 2319192144u, 1285732158u, 3307511706u, 1860111207u, 106597122u, 1317987028u, 3909997475u, 2833499319u), + SC(197466102u, 106471666u, 3969627291u, 425148315u, 2088018812u, 3287551129u, 2083642145u, 386904296u, 2967132086u, 417456225u, 2418726206u, 2685222098u, 3920069151u, 388803267u, 1008714223u, 4223482981u), + SC(1730602173u, 1587573223u, 1136504786u, 801576255u, 1239639300u, 3897044404u, 2640640405u, 3098571739u, 2095045418u, 1782771792u, 2216047065u, 2006450887u, 1019963460u, 450135304u, 1704523436u, 4178916267u), + SC(3045516080u, 2837283309u, 3652809443u, 3617799274u, 2953845221u, 1870697859u, 1987277049u, 671334013u, 2347392220u, 1637733040u, 408564290u, 531095235u, 1714215546u, 2668823252u, 4291679007u, 1499030154u), + SC(1785804164u, 3771923969u, 1688952513u, 4078905240u, 4219818381u, 2140263698u, 3560443409u, 1027592498u, 981877075u, 1273450409u, 1808708945u, 366130160u, 1509712333u, 1419790056u, 3592515372u, 1023304152u), + SC(689558936u, 2052202277u, 1573780309u, 1046114431u, 1768897198u, 1193436549u, 613072153u, 961650488u, 3203433527u, 2587127126u, 2088764244u, 3898254742u, 1779313411u, 2448405043u, 2102013432u, 2635393468u), + SC(2025692259u, 905848568u, 1759010770u, 1792571870u, 4118995060u, 266283808u, 4139640706u, 3438115348u, 2780184652u, 3445643695u, 656585512u, 181166262u, 2272629776u, 370943424u, 1751557846u, 2309122167u), + SC(267180733u, 424783777u, 1080203254u, 2661909603u, 1424050736u, 3737445342u, 2397112235u, 1140319020u, 3540605726u, 1560404816u, 714090654u, 3305695922u, 4001926073u, 4235374954u, 2250613806u, 603974704u), + SC(244840167u, 1554020100u, 3702066775u, 2862773506u, 3785435454u, 3651035430u, 218349583u, 1404753202u, 3766478445u, 2586133471u, 1533117238u, 4149938439u, 2210912076u, 3594357012u, 575816505u, 525962129u), + SC(4146528898u, 2136081288u, 1410528199u, 2682243562u, 3659634297u, 3884779676u, 1276188622u, 3650143718u, 2534539131u, 69352587u, 4188728680u, 4144009400u, 528573366u, 1948891771u, 2778384350u, 3961787045u) +}, +{ + SC(771871546u, 3238832643u, 2874232693u, 1176661863u, 1772130049u, 1442937700u, 2722327092u, 1148976574u, 4122834849u, 744616687u, 1621674295u, 3475628518u, 2284524224u, 1048213347u, 4058663310u, 153122870u), + SC(2125145888u, 3034373129u, 148397811u, 141146887u, 2520820550u, 761993323u, 2298029094u, 2891332110u, 2829144983u, 2531560926u, 2167918181u, 3311166313u, 1986747894u, 2110826144u, 1833688282u, 2697250572u), + SC(3869871954u, 4004844136u, 2445592287u, 191554676u, 1824322074u, 1934754654u, 1806989779u, 631655906u, 1640478312u, 3779394326u, 3878618879u, 1897296401u, 116845712u, 1282189569u, 1638341398u, 253193742u), + SC(869049848u, 3185853214u, 1086566153u, 574813225u, 768296876u, 2336838903u, 1037196762u, 3581040974u, 1545806877u, 1185761684u, 533220394u, 2594450382u, 518321105u, 3416686830u, 2271268151u, 3918676320u), + SC(3856331543u, 2684505765u, 649861433u, 2052378851u, 4281491040u, 1056350427u, 1268888422u, 3791019043u, 2372988231u, 1754646015u, 3964172838u, 3080977165u, 1940074122u, 2762476976u, 3389041795u, 1131517310u), + SC(1630655860u, 1949945516u, 3883647184u, 3029959080u, 1311781856u, 408642488u, 2800393690u, 3410356207u, 115351401u, 3420630797u, 2709679468u, 2872316445u, 1790203899u, 1997501520u, 3278242062u, 551284298u), + SC(2323279372u, 1575922229u, 4047150033u, 1372010426u, 3148623809u, 2453870821u, 2339486538u, 2280451262u, 2466099576u, 2994948921u, 132102763u, 1776872552u, 3906687848u, 1416385780u, 2716658831u, 3839935313u), + SC(1482060017u, 4064599659u, 4201421603u, 1862488009u, 1206323034u, 1506270647u, 4148487892u, 2940354206u, 221477839u, 2184047858u, 1052602625u, 1800724448u, 2376949890u, 1248004043u, 4042069004u, 1001474649u), + SC(1973975072u, 2109156381u, 895285550u, 2806725496u, 4257596779u, 2294716595u, 2126073388u, 4029509053u, 2287557214u, 3863235224u, 910675328u, 3403565516u, 2460443864u, 4145068647u, 1675629270u, 2972605807u), + SC(3067953236u, 2487048107u, 1053067642u, 2406833819u, 1120120518u, 2019615106u, 2151977185u, 2444444329u, 3698388134u, 2675794597u, 2346696087u, 3691916163u, 416413840u, 2548582733u, 2519917531u, 3323365251u), + SC(4258867839u, 1450083676u, 3423817219u, 2338254228u, 956448310u, 2038800503u, 2270893323u, 23474499u, 4001071451u, 434241187u, 4225947271u, 3009484949u, 1212186223u, 3021170789u, 3408787844u, 4241328442u), + SC(544425045u, 2335106449u, 1970249987u, 676962447u, 2451092807u, 3397085111u, 644609608u, 622894566u, 3012162452u, 742316904u, 1183695331u, 1942632009u, 3993963459u, 2025380463u, 2934502595u, 2424729664u), + SC(489227787u, 2064607364u, 749046162u, 1223089239u, 4103152782u, 944881113u, 2156101348u, 2809656549u, 2750173639u, 2290439348u, 455194332u, 3662094961u, 2388553957u, 2373693996u, 3087294434u, 714908241u), + SC(844100070u, 1293873339u, 240400805u, 2741251793u, 4185619158u, 3756747900u, 2600026127u, 4095003808u, 2551250677u, 1982555415u, 1538344606u, 2598805396u, 1759235723u, 1251966u, 1750681115u, 626531732u), + SC(3996016258u, 3876613311u, 1191787057u, 3901742282u, 1577096572u, 270596184u, 3165567618u, 4061944625u, 3613068329u, 3912630805u, 2056061785u, 2568706449u, 2343664228u, 1807908509u, 1314728487u, 1028342757u), + SC(2729604648u, 2866824008u, 1921075953u, 959207538u, 460881358u, 1786258799u, 989199155u, 1140694999u, 3534517067u, 1671080238u, 1077292982u, 69981150u, 2456995550u, 2177711190u, 3355630373u, 505438766u) +}, +{ + SC(2470971363u, 1622646280u, 3521284388u, 611900249u, 53592433u, 1667691553u, 3986964859u, 3228144262u, 4160240678u, 1357358974u, 796266088u, 2135382104u, 2999113584u, 425466269u, 866665252u, 3795780335u), + SC(1943673032u, 163567132u, 2998325065u, 4151760187u, 4286963295u, 2037110896u, 4023804057u, 2843670454u, 4267379728u, 470850548u, 1360194572u, 542908383u, 117354082u, 3909600634u, 3301531838u, 585104523u), + SC(421763950u, 3621776882u, 1804759030u, 1922063749u, 28357531u, 2718763721u, 3528327041u, 2594458380u, 1745913977u, 1705774731u, 3785007083u, 1889010688u, 4275556992u, 2808027536u, 1706627542u, 967259307u), + SC(3761989171u, 2069950976u, 953323220u, 30139149u, 3360357391u, 466334029u, 1085748790u, 717259079u, 3822910993u, 1348849055u, 4159668773u, 3924702853u, 4257335520u, 1714446370u, 3394938265u, 2541598048u), + SC(2132231371u, 3951042779u, 332537683u, 2179456991u, 3112576172u, 2873883577u, 502046554u, 4014018248u, 4272356370u, 2124475345u, 3140973257u, 1234959848u, 3468807232u, 3812306463u, 2768101189u, 3493652974u), + SC(2983624056u, 158967077u, 546553405u, 3473936990u, 3742593866u, 3986716933u, 2905591308u, 285301696u, 2640868047u, 3062221467u, 70156428u, 150492378u, 3977001273u, 1087159682u, 1233481348u, 3391921638u), + SC(3432795737u, 4256529583u, 3151717298u, 4190687875u, 1563633254u, 158068428u, 685294219u, 733826550u, 2829744078u, 4225504275u, 2375584227u, 1429440840u, 2192098666u, 1015042413u, 840775854u, 41702830u), + SC(3231767315u, 1865273494u, 1093659663u, 1873962287u, 1664376931u, 1435837948u, 31100007u, 316783664u, 996300708u, 334486049u, 1648124912u, 3615910102u, 2480590997u, 2253624363u, 548978494u, 3975730498u), + SC(1923874249u, 3947343158u, 2264687656u, 1121555015u, 3593673308u, 289357572u, 3048054908u, 3707221766u, 2043411687u, 1708537123u, 3350208529u, 2939237811u, 2793137666u, 3370678100u, 1405378414u, 2235087472u), + SC(139882711u, 1304366355u, 1276034712u, 2139658031u, 2197726287u, 3663457902u, 2357615523u, 1611719773u, 2323318078u, 260257531u, 2850134214u, 3099029628u, 553263652u, 173876122u, 2118167747u, 1771928540u), + SC(566458485u, 3545725305u, 2257836680u, 2245189792u, 1605297549u, 245844769u, 2016071772u, 1896412522u, 821618527u, 1870442187u, 3958912319u, 4032980189u, 2069248247u, 4226059888u, 3345680132u, 1791157180u), + SC(4148097755u, 2486537082u, 4003164230u, 2318687306u, 2491702264u, 229564758u, 4126839602u, 211561653u, 3452304873u, 2572510204u, 1630441069u, 3167885411u, 4175966562u, 1295680948u, 161732432u, 107333173u), + SC(1923252062u, 311708286u, 1678166990u, 3717252154u, 3161198614u, 1069601573u, 4091259962u, 359278439u, 3768419820u, 2520693990u, 650972975u, 383288062u, 1217231824u, 2559091429u, 4278580592u, 2250271391u), + SC(510621576u, 1629846927u, 3397488683u, 961386517u, 653633283u, 1754007094u, 2769834941u, 2247122605u, 2701964981u, 3912616774u, 3406969249u, 63999109u, 3141040146u, 2619453260u, 1468121925u, 4171492447u), + SC(3961993547u, 1155134029u, 1496861029u, 1279080034u, 2846121209u, 3483514199u, 2468398271u, 505281559u, 3532558643u, 2311328115u, 2310583909u, 3085705085u, 2999958380u, 2683778623u, 32663880u, 1366954658u), + SC(3799286526u, 1580228485u, 2766986278u, 586308614u, 2894037718u, 587959438u, 1301020570u, 2323176208u, 3827747523u, 2955860540u, 455053544u, 124753776u, 703403555u, 1658788582u, 3867772588u, 3276199889u) +}, +{ + SC(2899222640u, 2858879423u, 4023946212u, 3203519621u, 2698675175u, 2895781552u, 3987224702u, 3120457323u, 2482773149u, 4275634169u, 1626305806u, 2497520450u, 1604357181u, 2396667630u, 133501825u, 425754851u), + SC(373198437u, 4218322088u, 1482670194u, 928038760u, 4272261342u, 1584479871u, 2503531505u, 354736840u, 303523947u, 2146627908u, 2295709985u, 233918502u, 3061152653u, 3878359811u, 3090216214u, 1263334344u), + SC(2076294749u, 898460940u, 2754527139u, 2099281956u, 3551675677u, 4195211229u, 3603181913u, 1984445192u, 1121699734u, 573102875u, 2187911072u, 656800898u, 1477748883u, 3685470532u, 3965328576u, 4253954499u), + SC(1876288412u, 2267864341u, 434083874u, 1779401913u, 2781669786u, 3073195348u, 669142308u, 3636028767u, 127310509u, 372075961u, 2537369503u, 2705808591u, 971889633u, 2718294671u, 1415139024u, 276903675u), + SC(3596445084u, 2918342013u, 1827011883u, 3900260359u, 1783558754u, 1921301616u, 3293933601u, 1111091218u, 3238604202u, 967515902u, 1208493040u, 1614341552u, 903992012u, 480937886u, 28823639u, 2379076161u), + SC(1968094521u, 1600813704u, 2958098796u, 909224758u, 1752381729u, 3115930502u, 3643078327u, 2863416031u, 2510423171u, 2162796973u, 1796627662u, 3678673773u, 239312629u, 2457874359u, 3809753210u, 2494718541u), + SC(1731463174u, 4265769542u, 194787641u, 1036371942u, 1745836602u, 660344840u, 1082796561u, 3963871960u, 4001246025u, 3118794916u, 3886266100u, 1928084049u, 3032262555u, 2306541818u, 3921311698u, 2426451176u), + SC(4018285402u, 658949239u, 1329629679u, 2738829796u, 776877685u, 1774949833u, 2797031752u, 3236392582u, 2542061420u, 1832249084u, 183211998u, 1840198657u, 1314474881u, 3361925365u, 3440999944u, 974653576u), + SC(1671164742u, 4271520021u, 1517391404u, 3289979834u, 1233503784u, 3050636514u, 3728319521u, 2919957525u, 3518724155u, 1272537958u, 3303667759u, 3864284110u, 234069183u, 1495943844u, 1989482539u, 3056780355u), + SC(1575547612u, 2187321001u, 2701011625u, 2761636008u, 1864623673u, 3995428494u, 1950725639u, 3749309698u, 2711714857u, 3743669273u, 3222519898u, 621366782u, 2554696188u, 176315043u, 1467854493u, 1806812435u), + SC(1182422499u, 3354985654u, 814715964u, 4226927046u, 3360200226u, 2503195953u, 1526762508u, 3747376732u, 1505823655u, 3718914053u, 2708056196u, 1868291203u, 1664951819u, 1982491563u, 751360443u, 1075645602u), + SC(101076600u, 386741863u, 2955045918u, 1653351871u, 1070602553u, 321875967u, 3200546966u, 2632915072u, 225765461u, 1759013254u, 4169466720u, 3880757831u, 1769634729u, 2642211393u, 4245887731u, 3909815727u), + SC(2379322656u, 1554830911u, 1971754317u, 1058862290u, 623917994u, 2775317172u, 3261049248u, 1667374591u, 3883068608u, 3752131736u, 2607464936u, 1251402973u, 4056909038u, 937468613u, 309280197u, 1804321090u), + SC(395093976u, 2154850233u, 624748058u, 3473623511u, 530005996u, 1656467301u, 451942772u, 3238178099u, 691726480u, 2563588439u, 3675387583u, 3294893253u, 1205949092u, 3844564019u, 114533547u, 4193437592u), + SC(1241354591u, 1121646490u, 1686974686u, 3373490541u, 1189649937u, 2948191343u, 2978671156u, 3827318062u, 3377194192u, 3805066092u, 3271994064u, 2484020181u, 549626522u, 1166583694u, 3299399570u, 764854172u), + SC(2808929206u, 427994673u, 2338143204u, 3942895356u, 2304289727u, 1468778908u, 1350679341u, 3972686632u, 2399853022u, 2097821409u, 3799931826u, 2500883276u, 1352425312u, 3372587055u, 596007302u, 2017539287u) +}, +{ + SC(172527491u, 737404283u, 1378219848u, 1967891125u, 3449182151u, 391223470u, 304889116u, 3996348146u, 1311927616u, 1686958697u, 766780722u, 1429807050u, 1546340567u, 1151984543u, 3172111324u, 2189332513u), + SC(3269764283u, 1288133244u, 1314904801u, 996741356u, 1884733412u, 1544206289u, 558284137u, 1518251699u, 1924323147u, 1635892959u, 1275016917u, 3776324356u, 1705865502u, 202621081u, 499067715u, 3311904259u), + SC(2660619816u, 3307703068u, 1451637465u, 3851776926u, 2364760323u, 1977782632u, 1515607226u, 1445106389u, 2327693248u, 2319920969u, 1115274896u, 1834441597u, 402374626u, 1205432354u, 1396686295u, 491780324u), + SC(1996097434u, 731516361u, 974312078u, 3421366629u, 3812294134u, 3978884039u, 3352635742u, 1797690428u, 13489496u, 1642706934u, 3128398168u, 106641350u, 4016459895u, 2470770670u, 115922099u, 2925890710u), + SC(2686884812u, 2748914055u, 1937433663u, 756783569u, 413219250u, 1566264233u, 3400883298u, 1726270584u, 1877719428u, 1988282262u, 4210071735u, 1623567192u, 186026227u, 1235988261u, 878101455u, 3591361377u), + SC(4053231115u, 4124107153u, 3534184341u, 1110486344u, 81952807u, 4125498697u, 1693462482u, 2990125452u, 3439709895u, 1055710168u, 4246237022u, 1943085528u, 719511299u, 700284484u, 1082914808u, 1529874921u), + SC(1481485493u, 1935423659u, 913226612u, 2395711383u, 1541429099u, 2771316424u, 3338417471u, 399999946u, 26796724u, 1562275554u, 2290450886u, 1574607684u, 2722372873u, 1229315759u, 1998792801u, 1299123352u), + SC(3949810665u, 1328858449u, 2680298883u, 4060684833u, 1165923991u, 2656262528u, 835037267u, 1633040358u, 3109606689u, 3612027263u, 1850965274u, 2501035455u, 1956880692u, 2989837601u, 2991272131u, 514909703u), + SC(3542886422u, 2995653583u, 3564619313u, 2091503271u, 1371789218u, 2765269616u, 3068810600u, 1666719265u, 2118314133u, 3335278251u, 3361418207u, 807286765u, 899334530u, 3994904643u, 2747385847u, 3528707340u), + SC(3132681349u, 3533155425u, 2330764867u, 3555018576u, 1500828005u, 1243623897u, 1071818853u, 2130356426u, 4099162373u, 1333917673u, 445413180u, 915835391u, 3998951530u, 3932499234u, 2014496944u, 1476384528u), + SC(2104877156u, 1430391164u, 3607724722u, 2456386351u, 3275987562u, 653382938u, 360082336u, 281545563u, 2556998173u, 802173963u, 1898654040u, 2873697709u, 3526274706u, 30023701u, 1532464389u, 335648001u), + SC(1216717657u, 3420164715u, 1026103527u, 2814363815u, 3399248527u, 2265457834u, 4230549954u, 3191596424u, 2096767009u, 197782440u, 661821193u, 3129199915u, 3603027595u, 571989255u, 3350141303u, 902722054u), + SC(86788496u, 2319129483u, 1051755765u, 871757145u, 3910221139u, 2373267495u, 991927221u, 3506242540u, 2918237538u, 555183593u, 3050652275u, 2550066259u, 1935622924u, 1141386013u, 1915989302u, 1193809339u), + SC(2961067645u, 912271025u, 3829956364u, 976054309u, 2426360429u, 3756714048u, 860863671u, 2976390123u, 651422564u, 3348472580u, 4062622529u, 3566918328u, 1262646615u, 526922344u, 336090107u, 3690353753u), + SC(1104160934u, 638409761u, 4090697585u, 3951520784u, 412890746u, 3037968225u, 623962484u, 1861465265u, 4172453316u, 2731726287u, 468253494u, 2636411583u, 2233875405u, 976659501u, 1885152597u, 441456529u), + SC(228814647u, 3127034711u, 536841111u, 970423620u, 335496573u, 1496573821u, 3839638808u, 2076574157u, 3960354230u, 1830746438u, 2136594363u, 1397484405u, 335074021u, 421124372u, 4043995000u, 1296743377u) +}, +{ + SC(2759056966u, 2773771898u, 915395955u, 378399267u, 1065424189u, 3786627878u, 2430240867u, 1910948145u, 1268823138u, 2460932406u, 2049702377u, 3729301642u, 2270156417u, 2935515669u, 1488232015u, 333167852u), + SC(3963231590u, 2717344665u, 3330507643u, 2069094492u, 1576271806u, 844971343u, 3725773593u, 3293220801u, 1933125411u, 1106657228u, 3650404527u, 3511000962u, 3309805512u, 23235466u, 884265026u, 3867812812u), + SC(2380535986u, 2007649740u, 291610222u, 4151143005u, 2330231880u, 3336494284u, 4079710776u, 3045731925u, 300175272u, 1753290057u, 2323446107u, 2448133203u, 1897525100u, 62520621u, 938748110u, 2483424933u), + SC(3941565796u, 4020457560u, 536627435u, 849338423u, 1622694903u, 2253013822u, 1890968103u, 2458058141u, 2431563444u, 3273994144u, 2920282564u, 2871620844u, 315460419u, 2331615405u, 105614140u, 3825521500u), + SC(1770365960u, 436268948u, 2889892729u, 3688514673u, 3952720709u, 1774783907u, 605504449u, 2947048934u, 38294098u, 846447109u, 2199988078u, 482652009u, 58745901u, 1043251865u, 1692020085u, 2977904741u), + SC(3749156389u, 3930496686u, 342096417u, 2961755248u, 1791611872u, 2622150301u, 1430397623u, 2049694734u, 1457522946u, 1307567328u, 1594457791u, 2920040322u, 2838823131u, 3221083429u, 2327375059u, 307491364u), + SC(439175999u, 704562179u, 1530705937u, 343762620u, 1895613568u, 82869187u, 23704978u, 3831637605u, 1611450850u, 923617677u, 3571146990u, 2520538539u, 2376639038u, 2377370369u, 3624250410u, 3615349574u), + SC(764309941u, 395778606u, 890380761u, 1156064327u, 244397938u, 560614464u, 4033284221u, 1090955901u, 3643294611u, 2912576497u, 772374999u, 2861631454u, 564730390u, 3124994653u, 646536012u, 3616789797u), + SC(3040822479u, 2767342245u, 2776280569u, 3485527708u, 3592541314u, 980436690u, 2153312390u, 215781809u, 2169043418u, 2501125521u, 3698439429u, 3999324854u, 2793459908u, 501030861u, 3583683133u, 3712651293u), + SC(4078810936u, 708788696u, 3557269243u, 3488736225u, 3893932756u, 4164798985u, 1241795187u, 3595203666u, 2393791384u, 3416169943u, 714289829u, 1522223608u, 2613922570u, 3640037692u, 3871460094u, 693107847u), + SC(2095442944u, 4280954881u, 166522183u, 982064125u, 4072843681u, 2413289870u, 966372633u, 3054322365u, 3306439070u, 657208192u, 175957468u, 411297739u, 771116169u, 1596617487u, 3454202820u, 2489020407u), + SC(1474971529u, 4158663721u, 2047384831u, 2598838221u, 256974012u, 2456523417u, 631366020u, 3323296862u, 3331748634u, 1360209248u, 3346726166u, 365777010u, 1290850614u, 2085594058u, 2979720197u, 2832663037u), + SC(1555709774u, 2326491405u, 2273744879u, 2585453209u, 2182701308u, 3405285511u, 2624534747u, 1273093088u, 862771016u, 2571185727u, 2627816705u, 753650915u, 1122934423u, 1670176575u, 3747348599u, 2369664950u), + SC(90900628u, 2102730721u, 781890942u, 2802660398u, 1018645876u, 4115262915u, 4149550831u, 3399458752u, 3886843346u, 2763694604u, 1310436099u, 1905281291u, 3814148817u, 4190880658u, 4069475791u, 3679310561u), + SC(2090876031u, 2877257381u, 2723690078u, 1430728835u, 1519931567u, 1820574481u, 3028789440u, 1269332520u, 487867652u, 423473929u, 386546855u, 57358783u, 1188070806u, 1428826466u, 1782333616u, 177182180u), + SC(1560550296u, 3093603077u, 293048812u, 568213435u, 3420818052u, 2217333393u, 3134601365u, 71485947u, 1184987600u, 3737951852u, 162939585u, 1604396734u, 102336303u, 398862141u, 820178097u, 490472018u) +}, +{ + SC(1198357412u, 890731121u, 697460724u, 351217501u, 1219769569u, 940317437u, 2678867462u, 4175440864u, 2131908090u, 1470497863u, 3243074932u, 494367929u, 1767796005u, 457609517u, 3543955443u, 4149669314u), + SC(3330984275u, 2556191310u, 3686726368u, 344917147u, 3386773283u, 2065247867u, 3908122913u, 3695674005u, 2012204991u, 2693522884u, 103992040u, 209624682u, 1376640025u, 3686868767u, 2902487256u, 913177313u), + SC(51667624u, 2920015049u, 3017253519u, 1071812123u, 2571723173u, 2160964558u, 1290623835u, 537361271u, 825729747u, 1392761590u, 1142623949u, 609149740u, 478665972u, 658807909u, 3553467330u, 1636424506u), + SC(3616504574u, 1808500084u, 668829693u, 946464586u, 1979729368u, 406956181u, 4175922839u, 412791377u, 2386664246u, 1192624407u, 2943858119u, 2548487829u, 1705793661u, 3457595727u, 202485393u, 1924721832u), + SC(2189382710u, 4186169698u, 1109472631u, 1983920883u, 3607145598u, 92147950u, 1402492489u, 429006982u, 2674194346u, 4283195956u, 1593180543u, 3760708566u, 643378372u, 4031840072u, 3394015175u, 1558737750u), + SC(1805700700u, 1754525187u, 1654624487u, 2216136944u, 68436239u, 2233918826u, 2968997668u, 4123197178u, 634669625u, 2517670383u, 3007433093u, 3522650191u, 696793327u, 1110232330u, 152147442u, 726198231u), + SC(742639492u, 3149716575u, 880320409u, 4630949u, 1505653181u, 1071542118u, 3069898832u, 2578767084u, 1314905164u, 2213468220u, 3680194608u, 2445142726u, 2802637025u, 3977804516u, 1184600151u, 419058566u), + SC(1336605659u, 403108152u, 2724587657u, 3679190711u, 2874389193u, 1647236788u, 3333657299u, 528273159u, 3515102004u, 947876802u, 3658623910u, 174276546u, 653934448u, 3828171172u, 1444811038u, 2933240663u), + SC(339431464u, 3233735983u, 2646677300u, 43177515u, 392637796u, 1436471495u, 1239428896u, 2348305406u, 2289915967u, 3084305790u, 3250948245u, 178888356u, 2146779246u, 4234024427u, 1032696742u, 3905672369u), + SC(961540617u, 2841143833u, 962675692u, 4171962245u, 2791421965u, 2368576296u, 3328980779u, 2916707843u, 1558316022u, 134331787u, 2460382133u, 1215270659u, 146717643u, 3198704598u, 2091590890u, 2460305557u), + SC(1042706599u, 2034894580u, 690504458u, 2345543782u, 4005260856u, 2432547988u, 112379796u, 3543073874u, 835904670u, 2590827554u, 918469413u, 3408148837u, 1789043194u, 1729294718u, 1834822488u, 2928788408u), + SC(3301658713u, 837504950u, 1727706187u, 1845900341u, 896114239u, 2352826711u, 3111232113u, 2017659422u, 2679415011u, 2370224692u, 3953323203u, 2250773775u, 1103871456u, 1933857783u, 3328123972u, 3307902309u), + SC(1767706194u, 3006067357u, 35851140u, 3240494485u, 2221989856u, 1899667734u, 6385932u, 2363969169u, 4105037265u, 1831329288u, 2027489194u, 884350865u, 1094001278u, 159320441u, 4110377537u, 68569781u), + SC(1525490260u, 665735034u, 2452169880u, 171203360u, 1236274187u, 676156893u, 1374080130u, 357190845u, 1839504596u, 1514713169u, 4060710869u, 1096636593u, 2588809028u, 3627704311u, 1809407212u, 476953361u), + SC(957000182u, 26105440u, 3440739633u, 2098069989u, 1584380370u, 2860012851u, 1732766592u, 212521659u, 3179187407u, 887560394u, 2490695882u, 2732057577u, 1018218231u, 3635922188u, 2062474881u, 2513446682u), + SC(1107263183u, 578424674u, 37103195u, 466969755u, 2523291988u, 291121216u, 3279675483u, 2003600853u, 4199013737u, 2715326244u, 4169142308u, 3686083459u, 3512922856u, 3093381668u, 1195683747u, 1393205701u) +}, +{ + SC(1331866444u, 3086683411u, 308412705u, 2554456370u, 2967351597u, 1733087234u, 827692265u, 2178921377u, 289799640u, 3318834771u, 2836568844u, 972864473u, 1500041772u, 4280362943u, 2447939655u, 904037199u), + SC(2575383612u, 3753748540u, 2811819999u, 1587868018u, 1038431720u, 790984055u, 3731301644u, 1846621966u, 951964491u, 415041564u, 2200992348u, 4272384400u, 296027191u, 4287888493u, 2854418940u, 3573682726u), + SC(1970740379u, 2607713160u, 3470587124u, 930264002u, 1173824281u, 122965335u, 3335069900u, 326806848u, 3632692886u, 129472919u, 3226625539u, 2728837633u, 416887061u, 1130551300u, 356705234u, 1369994655u), + SC(4223755401u, 2079062379u, 3389104769u, 4073338565u, 3689225172u, 440818499u, 856809827u, 381405275u, 127244068u, 376610605u, 2598268701u, 2534766433u, 2820385475u, 4294123141u, 330930335u, 318185845u), + SC(761419527u, 3536226585u, 2328998689u, 3591334816u, 1578134205u, 1103093801u, 3418753973u, 3588283844u, 1530820786u, 2684864777u, 924992522u, 3557568163u, 1869705595u, 3313643247u, 841618349u, 1632346896u), + SC(3475240082u, 1688964704u, 2950217939u, 2829510968u, 4218043142u, 1723444205u, 599182149u, 3585292920u, 1201476124u, 1461631424u, 3796636907u, 3015591958u, 325310290u, 4221903599u, 2685464188u, 843835594u), + SC(3270571096u, 3849271420u, 2838244847u, 4029431364u, 3703574760u, 3266810236u, 1964057057u, 1045028730u, 3535646880u, 4117469088u, 268273252u, 28527135u, 616206627u, 3498685014u, 1783632491u, 2430589238u), + SC(1270864764u, 2335784868u, 3187652054u, 3487500065u, 3514696661u, 4279511860u, 2691960889u, 1283768022u, 3239440117u, 3088430000u, 3270700109u, 2562105500u, 920167200u, 797042551u, 4008345612u, 1713652205u), + SC(1233553764u, 2449552413u, 3139739949u, 2886523083u, 3648218127u, 435238208u, 231513377u, 3598351734u, 1003225207u, 1550611030u, 4262337852u, 2819804714u, 3244463273u, 2073740987u, 855086785u, 975917304u), + SC(2715954175u, 3495328708u, 4029028922u, 3684471179u, 2815956881u, 3599669751u, 4163140273u, 33191313u, 2635890672u, 3683103094u, 1579697202u, 287936530u, 2496546027u, 832886459u, 1241267398u, 3564329642u), + SC(718666875u, 1628061148u, 3834972005u, 11037458u, 3790987439u, 2312775807u, 3375415349u, 3089087440u, 2679862136u, 918687461u, 3176925215u, 1435039099u, 1342114588u, 1906963252u, 3488735014u, 1611160706u), + SC(4216184459u, 1084561028u, 249927207u, 3584932419u, 1355984265u, 990857900u, 1870305536u, 582023708u, 1966962179u, 1733088207u, 1190083164u, 3785297292u, 1004947745u, 1784159416u, 1841702516u, 180335137u), + SC(4084089742u, 2441136551u, 426220168u, 1375299216u, 1841338030u, 1250354698u, 2728864721u, 2959990011u, 1071025467u, 1691914484u, 2858760972u, 1516700275u, 2771651049u, 607063247u, 4219381388u, 3373946171u), + SC(2146554811u, 2380633398u, 431356428u, 2501496525u, 4195490782u, 4281443977u, 1707183170u, 3515016439u, 43334925u, 2064458077u, 4149827026u, 2544422546u, 1259302114u, 1919625668u, 729425798u, 2757346641u), + SC(2475010648u, 501654469u, 1262984133u, 2284058265u, 3864896735u, 3216144340u, 3043718887u, 3290359029u, 2513504704u, 1583873907u, 787550022u, 889877880u, 4155285556u, 2519357244u, 1887123831u, 2544852082u), + SC(1329107374u, 3899397847u, 1931705980u, 3537599611u, 2074239136u, 1267070685u, 2447524924u, 3173107761u, 2842541385u, 924561908u, 2664553616u, 395476463u, 813764142u, 3107511895u, 179660379u, 2380654703u) +}, +{ + SC(286197159u, 1217476806u, 1373931377u, 3573925838u, 1757245025u, 108852419u, 959661087u, 2721509987u, 123823405u, 395119964u, 4128806145u, 3492638840u, 789641269u, 663309689u, 1335091190u, 3909761814u), + SC(2458775681u, 3448095605u, 3846079069u, 1243939168u, 2712179703u, 2514528696u, 1400411181u, 3792085496u, 528921884u, 1230512228u, 4062090867u, 931590129u, 3669288723u, 1764179131u, 2650488188u, 764612514u), + SC(3981461254u, 1881876860u, 3861653384u, 1419940889u, 3890280301u, 225359362u, 3772709602u, 2406778923u, 1744011295u, 836946168u, 1547583643u, 2969842237u, 3997288340u, 2150480638u, 3129156617u, 1325216902u), + SC(3592470591u, 3671101194u, 2792523734u, 2070472959u, 1473838345u, 785123121u, 2721504084u, 2212009910u, 4070989896u, 1696639999u, 2859248441u, 3104578877u, 2309769016u, 4267049236u, 2484173427u, 1626540609u), + SC(4267160019u, 2981312649u, 344263087u, 698599319u, 1002907346u, 93565259u, 286808078u, 1804582990u, 3599771325u, 2181306538u, 1961279765u, 187428107u, 223299791u, 4043449191u, 587626985u, 2106033479u), + SC(501761768u, 2386293097u, 1180388710u, 1812775472u, 918601490u, 3009070794u, 1574279477u, 1505824867u, 3643095372u, 3370828988u, 832869144u, 404837899u, 3152252263u, 3925885097u, 69867335u, 3741018586u), + SC(2051920526u, 1020215512u, 2058830843u, 1611771091u, 2552120098u, 75944844u, 1802229404u, 915313553u, 2313215016u, 1745739579u, 443475191u, 2998247588u, 3289885130u, 1289464560u, 2961919458u, 3798282256u), + SC(1496487624u, 2215532014u, 4148657376u, 3923080315u, 216179279u, 3856996518u, 2014567019u, 880786726u, 2125033974u, 58008256u, 4039109547u, 402585883u, 2182540617u, 437175766u, 1441865826u, 1665450276u), + SC(3078919323u, 1109978808u, 3102316446u, 4252174800u, 1046362670u, 3864571927u, 2260100326u, 3682270765u, 2139319322u, 1066628173u, 240059747u, 1164853046u, 1454716611u, 512654137u, 1544275853u, 2556727566u), + SC(580428655u, 115762757u, 1593355348u, 2740341778u, 1504897999u, 975028678u, 2401832824u, 4197869940u, 3667767462u, 644880229u, 691878327u, 369150353u, 4026243769u, 737605979u, 2791271214u, 2620684209u), + SC(624678531u, 4114750403u, 1274989179u, 1531504358u, 3520816024u, 2554021149u, 1865577096u, 1362433716u, 1638936249u, 3016959317u, 2526207810u, 3033412199u, 695904139u, 2060012285u, 3230414132u, 860289224u), + SC(3442642063u, 1520946900u, 218826564u, 968761561u, 4098434233u, 3360677602u, 2204368028u, 486310067u, 2601372374u, 1399175099u, 2183933043u, 806379489u, 2424203087u, 2668736829u, 1664637882u, 3005713727u), + SC(700899790u, 1066183324u, 3546718434u, 998702102u, 2557230354u, 2084117292u, 2934243163u, 1545771642u, 3688392810u, 3908656537u, 3447657276u, 840000010u, 2955752477u, 44371204u, 3799655472u, 3734995825u), + SC(3265506533u, 942399325u, 173917125u, 161041810u, 2297418901u, 849604788u, 2703870825u, 2810175425u, 3617296913u, 1432689375u, 3133875354u, 1118654553u, 2616257301u, 495686053u, 4127407123u, 1943733376u), + SC(2005668850u, 485568946u, 2260461782u, 2622034876u, 2693998905u, 2811925574u, 2831747304u, 3217266392u, 2520502878u, 1176196783u, 2567958416u, 1525744035u, 2841811417u, 1157609637u, 3871707993u, 2765099676u), + SC(207989197u, 368293876u, 3237374184u, 1394768686u, 1254103141u, 935691540u, 375090092u, 2481205522u, 2920254212u, 492683984u, 2055637221u, 4291235240u, 3889542314u, 2465899605u, 1694380507u, 757371549u) +}, +{ + SC(136266275u, 1782161742u, 3530966629u, 586004249u, 4076565170u, 3312577895u, 876489815u, 1337331291u, 888213221u, 1813863938u, 1374206604u, 2668794769u, 1377764865u, 784024905u, 1937217146u, 3627318859u), + SC(3161427495u, 2344678392u, 1808682441u, 2396619894u, 3034006140u, 1044331129u, 4102609084u, 1058091322u, 1515502621u, 1258860285u, 1406233340u, 127619173u, 3057107171u, 225762630u, 1651671815u, 4285298193u), + SC(630785468u, 1344100570u, 1929331818u, 828088181u, 2313124884u, 1302120759u, 3180735860u, 313275450u, 1008942268u, 2707820177u, 4248947940u, 1732478629u, 3645496831u, 611830707u, 1937638387u, 61731419u), + SC(1347537282u, 2857000226u, 227299159u, 1108544547u, 1181072563u, 1291715943u, 3752803919u, 2688390945u, 2484326219u, 1350060758u, 452823659u, 2363636452u, 2152205190u, 1812507720u, 607624535u, 2319475408u), + SC(3222638329u, 3875752446u, 758301165u, 51152840u, 2430504171u, 1189996379u, 44948392u, 232960619u, 3026371583u, 2974537914u, 3244781723u, 3702394182u, 2835938901u, 663347918u, 3320069474u, 3071978352u), + SC(1947047272u, 3022037725u, 949698504u, 1728470528u, 283847009u, 1458268020u, 360012619u, 1579646653u, 4005878207u, 1765381301u, 20903539u, 2558445559u, 757888638u, 2604781527u, 2240457927u, 3990518442u), + SC(4281545336u, 1208697934u, 2578865021u, 2456188396u, 1796646478u, 3757714293u, 2622755030u, 1606025966u, 30472258u, 3850691354u, 1208779266u, 405050222u, 3807844323u, 3748806955u, 358470323u, 4212845387u), + SC(2041619043u, 3711576883u, 835794591u, 2392116351u, 2862318436u, 689502669u, 2866163103u, 2052898811u, 576580608u, 1144506306u, 542475550u, 474572979u, 4137279429u, 2221684538u, 331268239u, 1556318477u), + SC(705880713u, 2092991958u, 815360595u, 3449491044u, 1305192012u, 2057063005u, 3299868133u, 1114733861u, 730760330u, 1129737257u, 4233249504u, 1217580888u, 452658791u, 2612091783u, 1764043106u, 1669202162u), + SC(3689992902u, 700129090u, 282055655u, 756126609u, 382876308u, 4262209576u, 2436932760u, 484247369u, 1415138625u, 2340918814u, 3058199817u, 4145497883u, 334812059u, 461523021u, 2221122791u, 2995497332u), + SC(706669295u, 3007808000u, 3728730665u, 3241577762u, 3126001367u, 292940936u, 1126531898u, 3913205978u, 304146054u, 2548053118u, 3490807704u, 3465095661u, 3938930443u, 804039554u, 297557674u, 1669808877u), + SC(2395818908u, 3199065200u, 4060875213u, 1731284266u, 1022607637u, 1154299144u, 3879751917u, 384430926u, 86892497u, 2036004815u, 2668116514u, 901861508u, 2277490553u, 1312485879u, 562264334u, 170374972u), + SC(2192479620u, 3046309306u, 143307916u, 3468295982u, 3110013374u, 699221760u, 273412494u, 3153322038u, 2886126025u, 1296005576u, 2326933823u, 3713038344u, 919578907u, 258326637u, 1991591857u, 604405680u), + SC(3283196708u, 902217854u, 1295144146u, 503984315u, 566424671u, 1755595238u, 2455519229u, 120267530u, 1004363245u, 1611271287u, 1013059281u, 3646183010u, 183890924u, 188417891u, 1612883046u, 2255154239u), + SC(1231171449u, 2524105034u, 653815517u, 585754026u, 3098352226u, 866901449u, 4223318963u, 1071806142u, 3239364285u, 4077877700u, 423690458u, 2222266564u, 4117269051u, 1893556406u, 3304547745u, 215164118u), + SC(3229321461u, 3443938850u, 803179772u, 3340311630u, 2749197592u, 565049216u, 1674980657u, 45735981u, 3858875409u, 2208179057u, 2167864606u, 3853383863u, 3320158569u, 901453102u, 2505912317u, 1486241881u) +}, +{ + SC(768143995u, 3015559849u, 803917440u, 4076216623u, 2181646206u, 1394504907u, 4103550766u, 2586780259u, 2146132903u, 2528467950u, 4288774330u, 4277434230u, 4233079764u, 751685015u, 1689565875u, 271910800u), + SC(2894970956u, 471567486u, 2880252031u, 2717262342u, 4077383193u, 1268797362u, 4257261832u, 2560701319u, 2691453933u, 1607372210u, 2771176414u, 58794458u, 4272438220u, 2521311077u, 642919262u, 3613569198u), + SC(549667688u, 1635817891u, 3597742712u, 2133548191u, 983618585u, 1077056145u, 1016537981u, 3024916594u, 3788763915u, 2354027825u, 234019788u, 1129974745u, 3836449602u, 132091652u, 2429034711u, 3714188356u), + SC(3752023309u, 1237246457u, 810507218u, 1575719630u, 2984629402u, 1312110059u, 1532351529u, 3778270553u, 500991970u, 3016414634u, 2451804626u, 3116044735u, 2749076428u, 609078974u, 343845623u, 1628221103u), + SC(1079050562u, 537097107u, 2113045556u, 1216978919u, 795109794u, 494396817u, 3615304214u, 3016596136u, 1485503229u, 2246940765u, 2872639209u, 812577075u, 3970992077u, 816616346u, 4279493103u, 2696304890u), + SC(302016674u, 1709668681u, 88411267u, 3337357281u, 3061995584u, 3396993199u, 1858891069u, 2509301562u, 3807375387u, 3567949934u, 3737724046u, 4137514111u, 1709156749u, 1400722499u, 3253197246u, 830289695u), + SC(86642997u, 2517748533u, 1802616926u, 3224858276u, 667521935u, 294768443u, 3699185630u, 2619978653u, 1654256627u, 789295435u, 4056501046u, 2298266369u, 3425028365u, 3740463800u, 2064449616u, 423401599u), + SC(587205175u, 208206623u, 1253389730u, 3674422134u, 284316357u, 2112208954u, 1196434050u, 302049830u, 985808817u, 4037289748u, 2191325460u, 4289570719u, 592322138u, 3671063901u, 886295122u, 2540475213u), + SC(2164961127u, 4048157441u, 2790139366u, 1435011700u, 4142835891u, 3320410016u, 2681849481u, 1047872443u, 2885564134u, 874029678u, 2048520878u, 2934385850u, 1097367713u, 1997417466u, 2045706034u, 898129538u), + SC(3451958921u, 95403444u, 4056502814u, 671939501u, 2069116441u, 3101129770u, 553516228u, 1712496197u, 2639919391u, 3157824758u, 2182076931u, 2920510603u, 91421090u, 3496854290u, 1333938225u, 2005754623u), + SC(469295760u, 426796598u, 3855795018u, 970866434u, 856973549u, 2439780350u, 2385957015u, 2589908140u, 3781058972u, 4109407963u, 32316753u, 3931244779u, 68560366u, 1699148814u, 843806029u, 3772908229u), + SC(3846833357u, 4119412096u, 438094070u, 2645426661u, 884548695u, 2876447138u, 80918210u, 2029354870u, 135282137u, 3030947473u, 2960763605u, 1898348122u, 4127316996u, 2240743006u, 2934791826u, 887094286u), + SC(1897883656u, 1406242187u, 2434671426u, 2734794757u, 2714201131u, 3046668149u, 257451999u, 3794951424u, 152449195u, 3454838096u, 2737741298u, 821046884u, 2554260361u, 962889686u, 1262263641u, 2203109889u), + SC(1985684731u, 222483668u, 2849949193u, 1221492625u, 2084499056u, 1235444595u, 2655267198u, 1020186662u, 1447071023u, 3629752849u, 651251319u, 2167418603u, 2268535831u, 2985934672u, 2652239173u, 3259021212u), + SC(3062826974u, 1796450254u, 1939504794u, 476729966u, 3521076442u, 3086668105u, 234121934u, 986487065u, 1570879569u, 2820662853u, 1206879400u, 4271520206u, 4242315964u, 2749978648u, 3007865079u, 4114755771u), + SC(3649818358u, 3409857055u, 1537210569u, 2398557069u, 3130583052u, 536941530u, 3880813719u, 1419070102u, 1164730147u, 2533104753u, 2046210979u, 2821557175u, 2327264610u, 1639358616u, 2001893732u, 1524105344u) +}, +{ + SC(294473811u, 4198428764u, 2165111046u, 977342291u, 950658751u, 1362860671u, 1381568815u, 4165654500u, 2742156443u, 3373802792u, 668387394u, 853861450u, 2637359866u, 2230427693u, 2824878545u, 103849618u), + SC(3462974251u, 3960356708u, 3970663027u, 1911703734u, 2602955995u, 2496279357u, 210580885u, 3874806640u, 2822070051u, 4063068709u, 2061277285u, 1429537360u, 2349584518u, 2910686068u, 3963567776u, 3972103816u), + SC(2016723458u, 2541590237u, 3532225472u, 3001659539u, 112442257u, 922189826u, 2246032020u, 3487464820u, 1658786807u, 2276379919u, 1596562072u, 457926499u, 2193005220u, 2575074329u, 529788645u, 1519231207u), + SC(1572936313u, 886315817u, 1530415140u, 2311860166u, 3941188424u, 45807153u, 2483174955u, 1469805839u, 3162970586u, 2454510043u, 2417743140u, 2783896043u, 4229304966u, 1351489836u, 284407686u, 4050060666u), + SC(1089549454u, 2684562245u, 1059803961u, 224950790u, 58262787u, 3033299806u, 927475933u, 1400133226u, 3082832878u, 1490904482u, 3040968407u, 593844137u, 1569781919u, 798746464u, 1083127814u, 1590280691u), + SC(1538536818u, 1828650047u, 3754703497u, 985555578u, 1002045074u, 767791702u, 915104522u, 465342914u, 1114045622u, 3426575950u, 1922317875u, 1070157234u, 3077282627u, 509171365u, 1607316331u, 668038565u), + SC(3323765415u, 1224391265u, 2469548057u, 3722781348u, 3031269370u, 4289586349u, 2226931390u, 957179955u, 2298143215u, 388542993u, 1780793152u, 2112973240u, 1502081645u, 1973971844u, 934878133u, 1618693887u), + SC(3954817210u, 3380652139u, 2572526672u, 1228436929u, 465848053u, 3939966705u, 2398020514u, 2900599831u, 2007674400u, 2727714272u, 2337519533u, 1681172994u, 4089802218u, 142069883u, 4261364192u, 2856729470u), + SC(4248537414u, 694781904u, 571619480u, 3221145068u, 2970038253u, 3370542615u, 2832314379u, 1807587465u, 1411648700u, 1964173012u, 121911610u, 1134463822u, 2574507072u, 885427058u, 3741638072u, 3097389771u), + SC(2158675312u, 116080836u, 3333803512u, 3797833536u, 984464391u, 4149942538u, 1145746749u, 1195624987u, 426540232u, 1021913877u, 3121679962u, 3390873776u, 3273678689u, 3851165262u, 4274383191u, 1915176720u), + SC(1158541955u, 1843489443u, 998849897u, 969171492u, 1791167915u, 2484857096u, 1119081920u, 1901041264u, 2534183757u, 1529097558u, 2956376281u, 1260291681u, 1159207651u, 3441978306u, 2518693280u, 4253362775u), + SC(1690661001u, 2213259738u, 3615956917u, 105152953u, 308358176u, 1328282355u, 1666389191u, 1019854259u, 2059193948u, 4244545599u, 1952864052u, 329670934u, 3592985517u, 571024701u, 1172799188u, 3135874872u), + SC(1184018396u, 889004172u, 1920099477u, 1964506637u, 189152569u, 1805931691u, 3250067608u, 3446883320u, 1471577127u, 2315956523u, 1588897116u, 2470229082u, 3602241877u, 554726955u, 1644067322u, 87402371u), + SC(1360270758u, 326216664u, 3362619326u, 1255989535u, 4140691901u, 856602972u, 2084629207u, 3858539838u, 78510889u, 2277092409u, 3136284616u, 1772786459u, 3229606238u, 94732571u, 2598206327u, 492226777u), + SC(1257123658u, 2873597433u, 3001150814u, 421725801u, 236310867u, 582305583u, 3367057659u, 2102668336u, 153914902u, 4226436363u, 290094468u, 690656835u, 1748591179u, 3668885459u, 165028339u, 2139821087u), + SC(2349582063u, 631395785u, 941018791u, 1503410647u, 181331585u, 2473834542u, 2528647747u, 3710284323u, 2364124560u, 3901998444u, 3224972026u, 605068436u, 546878913u, 356944705u, 3829683853u, 160452346u) +}, +{ + SC(1451965994u, 766802222u, 1324674662u, 350355960u, 2823290314u, 951779387u, 2914020724u, 508533147u, 1932833685u, 1640746212u, 1238908653u, 542788672u, 3642566481u, 2475403216u, 1859773861u, 3791645308u), + SC(216282074u, 1906267522u, 1852437064u, 1010678235u, 3729121535u, 4197231849u, 4150055440u, 1128246703u, 3264673345u, 1375783733u, 3415088931u, 34309836u, 2603881793u, 3106237815u, 2950890176u, 505684202u), + SC(3927516830u, 2488673756u, 327917152u, 614182630u, 2355346359u, 730432873u, 88446505u, 4240960753u, 4121410433u, 1398090547u, 2262743232u, 651724036u, 4138228417u, 3106475766u, 4179362424u, 750466827u), + SC(434692713u, 3111300976u, 3323560909u, 3413395188u, 601658363u, 2967722170u, 1070605430u, 74966422u, 813799229u, 4061279746u, 1996953298u, 1765274397u, 4035137864u, 2359104373u, 3535793255u, 618634298u), + SC(1231617791u, 3545122377u, 2628213180u, 2391855988u, 3734909337u, 2705206020u, 681643510u, 368801430u, 691450613u, 2224147576u, 951972679u, 2767063862u, 3676868191u, 158497152u, 2165075628u, 2832330233u), + SC(3529008459u, 1174295398u, 55914117u, 2816083797u, 205887723u, 1756010196u, 1648915894u, 1477354329u, 86311333u, 3889682737u, 1098085375u, 3464880379u, 1139759451u, 542536350u, 186494667u, 2442759451u), + SC(3094023174u, 1995851063u, 4191388160u, 1722723757u, 1329293492u, 727282912u, 2669776257u, 2772951118u, 1386276034u, 3089621174u, 2303649396u, 2292749559u, 1467806712u, 266878652u, 2651863592u, 1006978704u), + SC(2450691869u, 3012269556u, 3887712993u, 4048656504u, 2160727935u, 1940770088u, 174916584u, 3472792113u, 2648524840u, 990354037u, 1957678544u, 3888925732u, 1168435347u, 3720532709u, 3528212798u, 2624020545u), + SC(69863181u, 2459013627u, 4217968964u, 2735851825u, 1081344097u, 737361378u, 2157825722u, 2900791120u, 1412000158u, 1206005337u, 3067055303u, 230632577u, 601427243u, 2760861753u, 3679310020u, 2091861010u), + SC(2304197829u, 1531316041u, 2716383108u, 434697890u, 508817514u, 2929310544u, 3751532879u, 3785491984u, 2716598214u, 3666495867u, 3150261948u, 1306653078u, 2283636929u, 2492138954u, 1527136744u, 3312103429u), + SC(3387483809u, 1095455990u, 3248396980u, 3181117152u, 2258888938u, 2053848664u, 2160875912u, 553275695u, 1752757914u, 1504034431u, 1046528434u, 1855690339u, 2425857774u, 2142030048u, 237252438u, 3919745098u), + SC(3690358562u, 221287988u, 2268047572u, 3655202989u, 756646724u, 68846869u, 1965143185u, 513684595u, 404949341u, 3706987369u, 15990563u, 3409604325u, 658214808u, 2112012281u, 1742449680u, 1802932879u), + SC(2972942716u, 4184192946u, 4124576773u, 3089123761u, 1179063207u, 2093485395u, 512951348u, 59239037u, 3674464770u, 787225894u, 1288484371u, 1987692265u, 3767465580u, 4044585132u, 2916653148u, 2297816723u), + SC(3784876742u, 1057734114u, 4078669159u, 2003536621u, 3146165592u, 3800656487u, 297129408u, 4248472894u, 3906942491u, 4017607636u, 1285879766u, 3310681130u, 2653159866u, 2524355569u, 84128323u, 2374174391u), + SC(1598027967u, 344901367u, 413901309u, 2414916476u, 417612014u, 1371467558u, 1499802638u, 967537237u, 1571117481u, 1088564682u, 3141693657u, 833402800u, 723113978u, 882224086u, 3586817872u, 3592950853u), + SC(513582137u, 3376206006u, 3649593908u, 274710963u, 395026609u, 3340190413u, 1543782101u, 90195397u, 4157807658u, 412153222u, 558068169u, 2001737608u, 3474337160u, 1679447360u, 12885220u, 843004632u) +}, +{ + SC(2083716311u, 321936583u, 1157386229u, 758210093u, 3570268096u, 833886820u, 3681471481u, 4249803963u, 2130717687u, 3101800692u, 172642091u, 421697598u, 4220526099u, 1506535732u, 2318522651u, 2076732404u), + SC(3635330426u, 3675180635u, 4282523718u, 1750526474u, 1682343466u, 1292539119u, 2893227939u, 2897346987u, 1855384826u, 3916002889u, 4211021149u, 3439442996u, 241993264u, 1634586947u, 29890244u, 2635163863u), + SC(2111268073u, 1081371355u, 3873218083u, 4044562588u, 2141674529u, 2107952064u, 3689043955u, 3423481956u, 2548188353u, 2697516682u, 4235866514u, 2985306600u, 3687062917u, 2383095614u, 206503719u, 2548448480u), + SC(961167287u, 839569057u, 3482959339u, 4268254472u, 364097642u, 1343091094u, 3226753483u, 2159507482u, 3968394805u, 2518014496u, 3451298154u, 38127252u, 267735247u, 3484363065u, 957363479u, 1698662790u), + SC(2744437828u, 3863759709u, 3010153901u, 3500431594u, 2624982656u, 875272695u, 1378345519u, 1791692262u, 3726226549u, 2682325366u, 3925052276u, 389591343u, 3869112658u, 650251545u, 6263093u, 860194434u), + SC(309822299u, 841707800u, 2661553828u, 3383039256u, 238699224u, 1100968507u, 3534897900u, 4177846894u, 3463859410u, 1435499569u, 2006933774u, 3007046995u, 2819231184u, 288756524u, 1854189890u, 3858081977u), + SC(2088052675u, 3396090720u, 416722812u, 2597822221u, 1176386826u, 3290882216u, 1002529034u, 2156491632u, 4202546863u, 1988253003u, 164033721u, 941800849u, 1186836065u, 2298291750u, 1863561032u, 1437279190u), + SC(2858016010u, 775169843u, 2706497878u, 2821546952u, 2660836656u, 2077717717u, 3498848893u, 658545289u, 4048269927u, 418273988u, 1144587321u, 3094511386u, 4122354470u, 4225741678u, 603926280u, 979427875u), + SC(1933550557u, 635706492u, 1314164193u, 391588743u, 834468642u, 1475393570u, 467867971u, 1271027212u, 2540684860u, 3801872764u, 1235100171u, 2159823063u, 532708943u, 665828867u, 4215955726u, 3885758496u), + SC(3602864699u, 4002116109u, 644187852u, 1895585048u, 2776091504u, 72205071u, 554242761u, 4049640413u, 3149249833u, 688714164u, 687706448u, 3680924185u, 2274039047u, 303853541u, 2977107717u, 1196398757u), + SC(3014099531u, 1302405838u, 17960870u, 4110705157u, 3801652109u, 2085339416u, 223612049u, 2870889264u, 3353629397u, 3527061798u, 674241336u, 3525864585u, 2278818471u, 2069831593u, 2885891701u, 1329881521u), + SC(943450806u, 3704544104u, 3603194299u, 3757910007u, 502151885u, 765197432u, 4190577627u, 771063523u, 2436865367u, 678307964u, 1498061278u, 4120830837u, 3369466394u, 3399332765u, 1670894068u, 2891073104u), + SC(501595739u, 1876059299u, 4182005344u, 160804770u, 962098784u, 2636270989u, 1828906496u, 1316975808u, 4088133273u, 2943366134u, 216957582u, 1003216568u, 4242258589u, 3505873185u, 2810125978u, 3429220861u), + SC(2021386647u, 4046435053u, 1951135097u, 3941871277u, 2261999657u, 3808836272u, 2028063026u, 3659044589u, 3595750274u, 34514326u, 1889867282u, 1898224864u, 1659225476u, 3153868894u, 1647148554u, 1185039302u), + SC(4119269244u, 1304843028u, 2354051818u, 2031439365u, 533555049u, 1418960734u, 214120313u, 4187370667u, 4256529561u, 2635160409u, 1836564249u, 3828261559u, 3235640513u, 181194540u, 4018312346u, 680914749u), + SC(1914329770u, 3317667974u, 1413160514u, 2952053282u, 3332782151u, 3751637695u, 2146129829u, 167804454u, 2499496888u, 4213150810u, 223599992u, 2197202825u, 2869811316u, 2635473358u, 952082661u, 1532017334u) +}, +{ + SC(701959589u, 2450082966u, 3801334037u, 1119476651u, 3004037339u, 2895659371u, 1706080091u, 3016377454u, 2829429308u, 3274085782u, 3716849048u, 2275653490u, 4020356712u, 1066046591u, 4286629474u, 835127193u), + SC(897324213u, 739161909u, 1962309113u, 3449528554u, 2634765108u, 226285020u, 2832650161u, 324642926u, 2242711487u, 162722959u, 2264531309u, 2307017293u, 4006636248u, 1035416591u, 2557266093u, 3957962218u), + SC(1912896448u, 699621778u, 2975109255u, 1580597872u, 2818493758u, 515803157u, 1642586345u, 785148275u, 2098287545u, 1424779842u, 1039209855u, 4238164284u, 4173562747u, 3569896384u, 1089361492u, 1858690350u), + SC(2757340308u, 2538321018u, 2388474793u, 379482919u, 882562385u, 3129659692u, 4216198588u, 3565768337u, 1772023241u, 2931080253u, 3451485646u, 748689895u, 562737327u, 663797632u, 3315310934u, 2629536884u), + SC(242169331u, 1243063456u, 175561111u, 2950276224u, 3213816292u, 692329775u, 3181354285u, 3015261169u, 1744760252u, 3733849950u, 4219512025u, 693702734u, 2844842003u, 722286940u, 2391355922u, 3564773447u), + SC(2291286292u, 966238959u, 506903622u, 2122264528u, 1392182009u, 3447321781u, 3873294792u, 1373792940u, 991667700u, 2332723711u, 2764968211u, 2471301595u, 649629323u, 783169152u, 1459916213u, 3846736182u), + SC(2664330880u, 1149932862u, 1416201114u, 318583284u, 4140857901u, 1128356267u, 1095497693u, 1624736741u, 761312690u, 241788645u, 2036924781u, 1946525101u, 3225208750u, 4156033061u, 2590150721u, 3771407135u), + SC(2862143077u, 233168744u, 2659004990u, 155440145u, 3918377979u, 1360152661u, 627903232u, 1469886352u, 2876841580u, 3955906097u, 580277652u, 3039511497u, 1597126708u, 1404269416u, 42059925u, 2098341602u), + SC(812381463u, 3272442363u, 496180006u, 1236237424u, 2267310113u, 2237850197u, 1113026387u, 716498059u, 3503382440u, 328287114u, 1410789607u, 477863076u, 1362085890u, 3569642059u, 2006757845u, 675415451u), + SC(747557402u, 4212477852u, 3286869720u, 3708058361u, 3240421074u, 1188732842u, 916816078u, 2444327052u, 2111479336u, 1745064524u, 3637408011u, 3599633029u, 4230973048u, 1160089497u, 1136388910u, 4138160782u), + SC(1255139572u, 1856599651u, 1458352865u, 3271906169u, 3410637086u, 2119040671u, 1680850868u, 413922813u, 2782309328u, 3561735700u, 3723648708u, 609378416u, 268989415u, 3293584485u, 3271843364u, 1954072630u), + SC(4155626312u, 931793228u, 1049414704u, 1037617746u, 265265177u, 616902615u, 844384832u, 3477591939u, 3106685802u, 2357099686u, 1845236259u, 3355104451u, 3327830357u, 3100545339u, 1162051156u, 2646331847u), + SC(514329180u, 948073745u, 1774920952u, 105860125u, 2811186644u, 1695131452u, 940976033u, 2019732362u, 309099076u, 1607914408u, 4118428245u, 1337868060u, 3952860679u, 2578427283u, 265792106u, 295755030u), + SC(3882528435u, 2629929072u, 1617404150u, 1421619579u, 2309432083u, 724299897u, 2666040048u, 1096383838u, 1836447402u, 426930713u, 3934220119u, 3232225281u, 1000075862u, 3631628825u, 3529619355u, 1219322120u), + SC(3335633324u, 4194223138u, 3901817518u, 1335914529u, 3871871049u, 3709757137u, 3499113177u, 235348888u, 781652835u, 1102256292u, 3754223033u, 833068853u, 4178470716u, 1807198743u, 2733399861u, 3740356601u), + SC(228568838u, 3126580587u, 4000897922u, 1303869372u, 3850020302u, 1548458239u, 2356371812u, 3570971356u, 2544858219u, 4220062752u, 2062616152u, 953792592u, 764216612u, 2052428514u, 2314665964u, 2792116584u) +}, +{ + SC(2022030201u, 622422758u, 4099630680u, 255591669u, 2746707126u, 492890866u, 1170945474u, 626140794u, 2553916130u, 3034177025u, 437361978u, 3530139681u, 3716731527u, 788732176u, 2733886498u, 780490151u), + SC(4207089618u, 3411945447u, 1960753704u, 3552759657u, 1130668432u, 848791484u, 3810908171u, 353148861u, 3312275539u, 2963747704u, 2966813687u, 2483733320u, 2880725255u, 463405312u, 3340834122u, 1292390014u), + SC(2664721153u, 4108676217u, 2604619822u, 775242570u, 636236518u, 2873717047u, 1857718302u, 2091477716u, 1586310695u, 2528697445u, 2256487867u, 2787362203u, 2741360704u, 496928924u, 601271512u, 3586110309u), + SC(1791685197u, 4242641311u, 3369628733u, 2052809939u, 806398185u, 3412279529u, 1946210627u, 1398934260u, 3077042954u, 2276630414u, 814388665u, 1749609309u, 3367688729u, 1959714965u, 2411157301u, 2263996211u), + SC(439326213u, 4256425445u, 876987216u, 1314194194u, 3010100734u, 1576065730u, 598365157u, 3705087566u, 3427486218u, 1877721147u, 358249820u, 410263983u, 1386735339u, 573015435u, 3312164843u, 1274000474u), + SC(1340417963u, 1112802360u, 10328826u, 706586684u, 2526013892u, 4135069035u, 3566832565u, 2945858092u, 107866747u, 2114273476u, 1970904771u, 965191541u, 1793617219u, 1453495760u, 4269949644u, 41605060u), + SC(123137558u, 4245690796u, 820317976u, 1443287541u, 4203849632u, 2954045926u, 714382464u, 3076066234u, 1293485113u, 2554869888u, 1663243834u, 1823619723u, 3832632037u, 2772671780u, 1362964704u, 558960720u), + SC(104412626u, 1897841881u, 4081037590u, 3456756312u, 3025873323u, 2036419348u, 663042483u, 1254379139u, 1882881825u, 3296543036u, 153313200u, 916960321u, 2276001640u, 759388499u, 1134495268u, 1699779658u), + SC(4218137867u, 889442133u, 2322944798u, 2659784159u, 2592614267u, 3345396604u, 3647495000u, 2837331949u, 75759322u, 2350992064u, 2461684340u, 2333444962u, 60872001u, 106935728u, 2095087192u, 2026584532u), + SC(818402121u, 2851948581u, 2197490142u, 4158011576u, 1665124994u, 3116095068u, 4019154383u, 478938546u, 1455910301u, 1844755722u, 2818772446u, 2743310120u, 1907022363u, 1639658700u, 517605614u, 2705809838u), + SC(335193145u, 4147885949u, 3527556636u, 2575925391u, 2530836608u, 2938195122u, 3771589905u, 2663025172u, 4017017665u, 2146447634u, 3974365403u, 2994000421u, 3198356067u, 3382731724u, 2593683495u, 3554902256u), + SC(1108422413u, 1982378939u, 2047758090u, 246779179u, 2568353687u, 279750626u, 1730233650u, 784289836u, 2712478714u, 3614283837u, 1824826964u, 2514128237u, 3308726345u, 3623735281u, 887459898u, 3896777957u), + SC(3527405352u, 290146745u, 125808293u, 735109902u, 1788801307u, 3306408847u, 822599754u, 3798637803u, 1514985656u, 2967186195u, 716984495u, 3386310843u, 3156794500u, 1007814159u, 1629566196u, 4265651874u), + SC(1178327293u, 565847309u, 518944000u, 3901419432u, 941693255u, 4276272755u, 3595637504u, 1831384538u, 553054976u, 3799273120u, 516961220u, 3048859574u, 1887176404u, 3648800625u, 2905989893u, 2971331974u), + SC(561598562u, 3812086269u, 2571795641u, 1946669885u, 4094345694u, 1247304730u, 725275648u, 2382611624u, 3912910386u, 3657806663u, 2347179560u, 3311073478u, 3031523768u, 2672297551u, 829774364u, 4138790294u), + SC(3908534093u, 41076189u, 4026661177u, 1264946070u, 3582612650u, 3167460834u, 3305185564u, 1828271691u, 1883569901u, 567401887u, 2154847219u, 3599749472u, 834678216u, 1517326104u, 465030801u, 2253777505u) +}, +{ + SC(69398569u, 525452511u, 2938319650u, 1880483009u, 3967907249u, 2829806383u, 1621746321u, 1916983616u, 1370370736u, 248894365u, 3788903479u, 221658457u, 404383926u, 1308961733u, 2635279776u, 2619294254u), + SC(4116760418u, 3197079795u, 2972456007u, 1278881079u, 1399016013u, 267334468u, 3129907813u, 468505870u, 1237093446u, 3810554944u, 1980244001u, 1830827024u, 4255330344u, 3556724451u, 2936427778u, 3969278111u), + SC(3989128687u, 604159041u, 3302470711u, 1703086807u, 4153485525u, 2444501021u, 449535888u, 2817157702u, 3967126593u, 3774839729u, 4230523164u, 1130105305u, 2419296875u, 560268503u, 173246097u, 1794638932u), + SC(1735434103u, 3810847770u, 4216841726u, 1126260487u, 1019034952u, 4140633019u, 3223272164u, 440162565u, 3864068825u, 3275406276u, 2196958479u, 4212485308u, 539037402u, 431338309u, 4061221107u, 4289896057u), + SC(1802752446u, 2780168117u, 1133399256u, 2599868866u, 3158418134u, 2848371717u, 2893014484u, 1878597835u, 139427334u, 1841937895u, 2016179766u, 2330806831u, 3849381146u, 2224326221u, 2296824272u, 3983748073u), + SC(1520559143u, 1690628296u, 1614953069u, 1422707415u, 257987514u, 3063997315u, 2652769123u, 3445956897u, 843436720u, 4264023440u, 365609354u, 2250088148u, 2769492081u, 59746990u, 1275187671u, 1973406172u), + SC(2823162534u, 2631304853u, 2485683334u, 33106529u, 243176015u, 492943806u, 489814307u, 4023911334u, 4139752347u, 4133120235u, 2455727203u, 1293330101u, 1838339727u, 4219498628u, 2131345625u, 3646653738u), + SC(4198202713u, 3167956639u, 2765023077u, 3652537372u, 1708707687u, 2324231909u, 1009881825u, 1679047879u, 2515346176u, 794145218u, 554048969u, 3173445869u, 2193645289u, 1271864237u, 1006139617u, 1072905092u), + SC(4273823033u, 1749314885u, 4263358248u, 538495360u, 4104454924u, 1997598205u, 3080563305u, 3238994582u, 3099819109u, 3162260128u, 1706963773u, 405274298u, 1894479347u, 1596497438u, 1094591269u, 1522128209u), + SC(2640931764u, 1304425992u, 2939922746u, 3918107623u, 1248692482u, 1121191585u, 2062140937u, 1807331998u, 3643560968u, 3236720945u, 2667270358u, 411521120u, 3664086365u, 2334989504u, 2668098536u, 3236026237u), + SC(2404161740u, 567514400u, 3895963765u, 1201374790u, 674719322u, 2894222365u, 467511362u, 3395036514u, 1038550674u, 2948454520u, 1518702565u, 1362236790u, 157238862u, 3475771959u, 1415257606u, 2714484334u), + SC(1831986705u, 588754101u, 4075551797u, 2767613701u, 2944855428u, 1912813036u, 1398542170u, 3440695634u, 2367865816u, 842155635u, 2602621363u, 2143763320u, 4256143529u, 1826541687u, 1851134007u, 2997377819u), + SC(3699972731u, 227995919u, 3067674252u, 477404832u, 847958753u, 893077929u, 2153170373u, 3057114881u, 1197132301u, 3330088847u, 2465660906u, 549749504u, 722435391u, 4124201578u, 3419977887u, 636305133u), + SC(3346980455u, 338882355u, 1940861469u, 2106574528u, 4065634984u, 939438415u, 880899904u, 173329243u, 3962520186u, 3417951565u, 2532850810u, 1158609417u, 1846710650u, 305050726u, 600225342u, 3684765712u), + SC(1932816778u, 3409537322u, 2445361402u, 1740774412u, 3661005378u, 2854030637u, 1914937560u, 1558250179u, 3808763123u, 1298026979u, 2417248681u, 899022004u, 847010236u, 506303181u, 1296472514u, 648957572u), + SC(600303058u, 722185115u, 3110060002u, 3818809602u, 1551617161u, 4208042174u, 526230670u, 1957951010u, 3160030963u, 3295123990u, 3121214191u, 1337066151u, 2200271451u, 1066776105u, 1163805043u, 2606444927u) +}, +{ + SC(1137648243u, 3815904636u, 35128896u, 1498158156u, 2482392993u, 1978830034u, 1585381051u, 335710867u, 529205549u, 1286325760u, 863511412u, 283835652u, 936788847u, 101075250u, 116973165u, 2483395918u), + SC(2210369250u, 711585268u, 1961210974u, 1353321439u, 1215935705u, 1641330999u, 11213011u, 2020212318u, 695107713u, 3413272123u, 1378074688u, 2790029989u, 658491086u, 1881545465u, 3409839898u, 2042086316u), + SC(1723393102u, 3373492622u, 3599711002u, 3748987970u, 1143620470u, 2663282777u, 2229588531u, 2674289435u, 2963045423u, 2234232397u, 4178299567u, 2791622546u, 4001934471u, 757990509u, 2858420658u, 605204372u), + SC(4272330873u, 3840847353u, 659917277u, 1664684318u, 1563018625u, 821178295u, 3329580379u, 794312951u, 2169136998u, 1706378889u, 3017987093u, 1159314572u, 2524368718u, 2444830959u, 898030098u, 68613446u), + SC(3172236096u, 1547478676u, 3467968131u, 1603626860u, 1411948645u, 2916654969u, 2891471305u, 2110051838u, 1733578576u, 2788816800u, 1613389791u, 759324595u, 3991538909u, 4073480091u, 3323038139u, 2043658072u), + SC(3011536148u, 2207224783u, 101813390u, 4149858178u, 961260436u, 3760245299u, 2099300570u, 3143747485u, 3209436103u, 902146054u, 3598885374u, 597299239u, 1369786353u, 2099087354u, 1506359374u, 1017249349u), + SC(3137350455u, 1622014086u, 2828880803u, 599881832u, 2213606365u, 4248974065u, 675350384u, 1446749674u, 1254778294u, 1745968946u, 409433048u, 1103126998u, 2370471436u, 1143685003u, 3341252280u, 1003299547u), + SC(2019014241u, 1108099665u, 1035538349u, 2878848993u, 2585673617u, 1565675366u, 2261830657u, 117854892u, 1965053814u, 2351841804u, 4065720752u, 3747135308u, 959541091u, 1629950401u, 4236240320u, 189693687u), + SC(3443026785u, 3216851941u, 278623472u, 1568038608u, 1548544711u, 2243949731u, 3359141033u, 1425753427u, 2934907774u, 2301245979u, 2216178210u, 153063705u, 1690071616u, 791861830u, 1201756636u, 1249732113u), + SC(2497506925u, 3815453805u, 1308318422u, 1061717857u, 710358190u, 3797004413u, 1870767051u, 2099598345u, 845543228u, 2941187056u, 1083282999u, 1311194087u, 3227025541u, 423673289u, 2634724972u, 3297305091u), + SC(1394185841u, 1653557808u, 2313575976u, 1732811292u, 2133445032u, 171245194u, 3242484287u, 2667183179u, 1165233778u, 997752293u, 501180123u, 2529762237u, 429212016u, 1660866777u, 1766992150u, 2066419882u), + SC(945381459u, 1085161105u, 3490034658u, 983140246u, 425352282u, 2175943302u, 1166850024u, 3968884285u, 1417959566u, 3386676357u, 3168826489u, 2984241621u, 3305143707u, 246924146u, 4113453679u, 123892017u), + SC(1498291154u, 979168666u, 2565114847u, 3722708999u, 3116533535u, 2044826765u, 118913881u, 2684275795u, 30932180u, 3147559151u, 3769605849u, 2376328043u, 753602217u, 3789763983u, 1247346722u, 4123341034u), + SC(3203969599u, 2514533821u, 1007395325u, 2063305304u, 520326691u, 3823758018u, 3095693832u, 1864628246u, 2586004821u, 4190638257u, 2952735262u, 2977139992u, 1124651421u, 295756268u, 3428261546u, 3110485030u), + SC(1663042556u, 4114384947u, 1430450710u, 3825340149u, 1051862436u, 3194752601u, 3106848742u, 1383208530u, 3142397378u, 4065704146u, 1545077688u, 2297695627u, 3152458457u, 4134880529u, 2187655177u, 3419805764u), + SC(3081663242u, 3880428040u, 2670880433u, 1398290076u, 1232125961u, 3862005121u, 1297357575u, 3334998678u, 1135063881u, 1723120988u, 2716095891u, 1113861429u, 3955845594u, 88397004u, 1699846421u, 887623013u) +}, +{ + SC(2668669863u, 1518051232u, 591131964u, 3625564717u, 2443152079u, 2589878039u, 747840157u, 1417298109u, 2236109461u, 625624150u, 2276484522u, 3671203634u, 3004642785u, 2519941048u, 286358016u, 3502187361u), + SC(1979235571u, 2198968296u, 3104128030u, 1368659294u, 3672213117u, 1391937809u, 2759329883u, 1389958836u, 2420411428u, 890766213u, 2707043165u, 2738550562u, 3382941095u, 378763942u, 3093409509u, 2964936317u), + SC(738589056u, 2116353374u, 2279888429u, 1705963022u, 828292114u, 896734726u, 2179570630u, 199574728u, 977051187u, 779668316u, 2330529056u, 3992755888u, 1000402439u, 2191612089u, 357145081u, 1441305104u), + SC(3372185571u, 1990378702u, 1181109789u, 3007260699u, 2430812419u, 1342872134u, 2198044770u, 1122343273u, 492870646u, 795688582u, 3226537448u, 1245881435u, 1071312339u, 1997541910u, 3829149062u, 1964864598u), + SC(3005241683u, 2859584860u, 2297396821u, 999606499u, 3964655188u, 3075624064u, 1368424820u, 847579236u, 744318941u, 1201524211u, 1104903258u, 3771742070u, 4093550286u, 53333408u, 659192149u, 3026115299u), + SC(3415227510u, 2060701016u, 1724277801u, 2661091313u, 215175235u, 1719160017u, 2940192603u, 1942243742u, 2398510742u, 4053370504u, 720436957u, 3760614784u, 2014232625u, 4199009336u, 2658914393u, 246186938u), + SC(446126854u, 165933106u, 2141828870u, 892600041u, 4146883601u, 2127439849u, 3431174989u, 2697318886u, 754216027u, 2671089369u, 1463409379u, 2826265846u, 334206028u, 1562078629u, 62819702u, 350080249u), + SC(3607678201u, 1305808009u, 3724583207u, 482185919u, 703873206u, 1075587326u, 1772056430u, 1356871295u, 4212601732u, 3762698616u, 2707284202u, 752961239u, 3089561250u, 1634547883u, 2919906767u, 31529502u), + SC(299389109u, 1252069111u, 2304374236u, 1252642323u, 2415535563u, 271885157u, 592252779u, 1178960198u, 53568246u, 3149254195u, 2937703855u, 1474069228u, 1764301842u, 954790502u, 4245417136u, 3132108431u), + SC(2094400513u, 3190829985u, 2239253067u, 2918833540u, 4106202305u, 2502268912u, 1731261142u, 2453877410u, 1861934729u, 934615026u, 3785479199u, 3605446967u, 3582056355u, 3042887218u, 1961855879u, 496882544u), + SC(3179454680u, 881405516u, 158640787u, 2790186672u, 162147899u, 376983910u, 3379568747u, 1408037207u, 1411174731u, 535638557u, 1510230718u, 2856041085u, 1958999115u, 3678347246u, 2958940834u, 520309445u), + SC(1870118851u, 1980314816u, 3987573623u, 4117586697u, 396136405u, 3149345244u, 70002589u, 2314836548u, 1713919226u, 3789182954u, 2123295507u, 3015665476u, 4069315088u, 3980795614u, 2021907367u, 4155874670u), + SC(4078777812u, 3708497519u, 1529048728u, 3747007128u, 2780224299u, 2728976580u, 3953400499u, 550363476u, 3812495996u, 3116459113u, 2211909765u, 3967732138u, 315888386u, 4202077281u, 1437542127u, 2815522910u), + SC(3236576167u, 3189780679u, 2030714184u, 2121402515u, 772212369u, 2193424420u, 1417920098u, 2031545011u, 4110769775u, 697022136u, 1206489717u, 1691036150u, 88940849u, 535864250u, 547921653u, 2569798466u), + SC(598120112u, 3876471191u, 3533286352u, 3003233155u, 1039593763u, 2148663879u, 2659932582u, 279051507u, 988977723u, 3458445518u, 2950275676u, 4048574808u, 3093122873u, 831143981u, 214208408u, 3935649503u), + SC(2893621405u, 3242329790u, 1948255717u, 4083664057u, 3803596193u, 740414223u, 4293576836u, 3875047642u, 667197150u, 2081112783u, 2447275650u, 242164299u, 706345359u, 1928593492u, 1774391838u, 3660333945u) +}, +{ + SC(3009793609u, 3525092161u, 3245586135u, 574145899u, 4034974232u, 2828949446u, 3457574134u, 1546193476u, 3883480541u, 1976722737u, 3557056370u, 994794948u, 106991499u, 1626704265u, 3534503938u, 3271872260u), + SC(2939511082u, 3508735083u, 975571643u, 1775005849u, 4144127005u, 706007446u, 420750190u, 1296964164u, 3061654480u, 2268588398u, 258119220u, 1152421762u, 2183948554u, 3016917902u, 1186604447u, 3147111215u), + SC(405897674u, 923178082u, 1575208079u, 3088321769u, 2214762612u, 3893926734u, 3167279390u, 3951912989u, 2709000001u, 2390687969u, 3858727239u, 866338457u, 2045181240u, 3217044625u, 2328560686u, 1861539550u), + SC(1277015638u, 1098202702u, 1559301990u, 2587773702u, 236499920u, 458659357u, 2353007333u, 2611100088u, 3428309717u, 2008274629u, 3647015407u, 268886847u, 2626192792u, 3341061984u, 1515395072u, 3708589435u), + SC(4042661445u, 3420460388u, 402520550u, 3677541300u, 2230979515u, 1273170666u, 2514471146u, 827498216u, 1259202696u, 3072082970u, 475301020u, 2118811945u, 3612811582u, 1387362670u, 2779447975u, 2265478999u), + SC(2229583001u, 1885758268u, 2744744533u, 2751282929u, 3032060674u, 1949605811u, 1570835257u, 793354274u, 1683039266u, 449593771u, 109462780u, 1941150268u, 1808732776u, 139050949u, 2225765509u, 1246293964u), + SC(2802845617u, 3765730171u, 462111640u, 590276976u, 2549490668u, 1227143343u, 384473299u, 1872236586u, 2432932105u, 2621627369u, 29218585u, 3541815309u, 3762320683u, 3470760231u, 2011203130u, 2527437401u), + SC(796052351u, 4037990088u, 4017471553u, 1320960316u, 561010825u, 3728618461u, 3540350568u, 1334322515u, 2252671868u, 3217596003u, 3122272084u, 3124892250u, 146022162u, 3584383023u, 2911266650u, 2958817688u), + SC(161418820u, 3776882969u, 4050624816u, 1522984750u, 3239766493u, 3767349571u, 782872272u, 4177710199u, 1140123311u, 211837022u, 1955996644u, 402816745u, 3326870942u, 1443720320u, 1645866695u, 3832886909u), + SC(452931871u, 3201459109u, 3989748495u, 3779670060u, 3234605835u, 2462489907u, 3541849378u, 3952908948u, 2234764749u, 2534999097u, 1221823414u, 2220662906u, 2593424893u, 3688122472u, 2131104831u, 243658822u), + SC(1244527825u, 1331697159u, 1126644730u, 922926684u, 1475975786u, 704282514u, 1718439968u, 1878820141u, 2509443841u, 2182928123u, 1663057853u, 2828328506u, 1475048880u, 791101245u, 3209045799u, 807262644u), + SC(1506123994u, 75559732u, 2487617790u, 2776679170u, 2522687136u, 3704896305u, 945074946u, 2943008309u, 1088584510u, 2469322363u, 1078526500u, 2073262975u, 691596720u, 2702927487u, 380178128u, 704842212u), + SC(1460389583u, 4274587105u, 1447626425u, 3957246995u, 1621878179u, 1643627976u, 4030517934u, 1056559397u, 1438644008u, 32976965u, 2197709285u, 3567855255u, 2001746745u, 2603748421u, 3462117821u, 903804357u), + SC(3179129705u, 2297226467u, 1646197352u, 950157362u, 2929140164u, 4242027992u, 1652798968u, 4193267428u, 3343133888u, 2499845914u, 423061238u, 3494957413u, 3637365392u, 784231823u, 595573026u, 2713123590u), + SC(2810225213u, 3951319549u, 1905650326u, 3909017486u, 2335763951u, 3772810842u, 2983632261u, 489145948u, 4173940274u, 2703192453u, 2654763363u, 4064871590u, 1399005653u, 257836626u, 831912020u, 895345820u), + SC(4037755568u, 3145789767u, 2141184942u, 4120133888u, 346636610u, 3895536529u, 2259736314u, 1057113066u, 595225270u, 3051392771u, 2813693848u, 3877775276u, 1832280309u, 1138362004u, 3061980317u, 858203300u) +}, +{ + SC(941124125u, 1620226392u, 1431256941u, 3336438938u, 540497787u, 766040889u, 373284400u, 2979905322u, 177008709u, 2625544842u, 1096614388u, 1196846420u, 4186360501u, 3945210662u, 1143943919u, 3412870088u), + SC(2868459499u, 3255324438u, 807131982u, 2853200483u, 3487859623u, 3501857558u, 3107820062u, 2163227213u, 2115527726u, 2346720657u, 2251713340u, 3377131273u, 3223650794u, 3766790266u, 177525458u, 4167009497u), + SC(311132793u, 3961991670u, 3475828441u, 4275227465u, 4114440759u, 287999228u, 3329759386u, 2384037498u, 4228771259u, 844254234u, 256179964u, 1796107218u, 3127243322u, 1425447302u, 1385509204u, 1101567113u), + SC(2084416542u, 1837746358u, 3915669193u, 60671540u, 2731498203u, 842785439u, 103116859u, 3404407266u, 2713222963u, 3049100113u, 368142082u, 2923502225u, 3018451818u, 2169399182u, 3017634865u, 1845463402u), + SC(1620925474u, 3368534446u, 555437218u, 4144603563u, 1969376145u, 213474605u, 1856420595u, 3939242692u, 1705488978u, 252956811u, 1258322279u, 1776729832u, 3988114536u, 3572272198u, 1383845751u, 1398527932u), + SC(1762997475u, 799707654u, 1609033889u, 2324053368u, 2951656833u, 2545022095u, 1325992886u, 2638191889u, 737853621u, 891297811u, 1613139572u, 594983169u, 2686965496u, 4040759974u, 1496585540u, 294269531u), + SC(3866323582u, 3807637640u, 654389167u, 993860478u, 3985490230u, 874636344u, 2342980699u, 1928023737u, 1520117329u, 644165140u, 150615609u, 199275733u, 463804864u, 310744654u, 2057873049u, 1169977839u), + SC(239011286u, 715635161u, 1855226016u, 2750348850u, 4059485278u, 800137564u, 3998891997u, 4048007508u, 1194893107u, 3761772527u, 273800027u, 653240081u, 1187997500u, 310579555u, 786511222u, 3092283411u), + SC(3036944959u, 3482022954u, 3739636749u, 3919006909u, 4266819119u, 1212326408u, 103856594u, 597427799u, 1319114089u, 4260737761u, 1982976744u, 741084092u, 689793522u, 4260038527u, 1319231386u, 1661185367u), + SC(3846585080u, 1572901113u, 2683774833u, 3251385733u, 3753876990u, 849242549u, 4245340911u, 1064393430u, 3309340124u, 2842098330u, 2556268102u, 2033409485u, 757257328u, 2031055308u, 487255243u, 3197919149u), + SC(273355511u, 2413549351u, 710350577u, 1361281890u, 2485522754u, 1210096318u, 3839671116u, 3619357718u, 3954210633u, 312725146u, 3792397974u, 3833954588u, 1779821907u, 2701218449u, 2422680647u, 3829673069u), + SC(379167192u, 3494512635u, 855436470u, 2928216366u, 4239059924u, 4254878455u, 3617218283u, 739826290u, 3488721213u, 1288540569u, 2623691196u, 4237777587u, 1234356449u, 2367467024u, 185343202u, 2198868227u), + SC(333398980u, 1306721698u, 1267933489u, 3888643170u, 2305763143u, 1886386521u, 2247721544u, 1287414137u, 497238456u, 1934421131u, 1960709128u, 2688614248u, 3637710577u, 3756130276u, 1929365309u, 2796038772u), + SC(772805737u, 461244658u, 3551164236u, 4177074918u, 3920537361u, 4259237061u, 3625379235u, 3715444221u, 3444473673u, 2576271136u, 2750230085u, 2167864295u, 2571239709u, 3663560660u, 743894391u, 703945624u), + SC(2955504442u, 4192737708u, 2813336533u, 2037901957u, 1563142269u, 620241136u, 3249364868u, 1805455553u, 422364625u, 3061329310u, 3824436397u, 1640020182u, 2540832302u, 2063844885u, 2982901072u, 2809011473u), + SC(4188085081u, 1849071252u, 4251112483u, 1368274267u, 2811635355u, 3535120523u, 478922770u, 1090405967u, 2358353504u, 2249592823u, 2367480425u, 1158857070u, 1979230110u, 3661225756u, 2903524693u, 1830110173u) +}, +{ + SC(3638948794u, 3243385178u, 2365114888u, 1084927340u, 2097158816u, 336310452u, 231393062u, 580838002u, 3851653288u, 568877195u, 3846156888u, 2754011062u, 3396743120u, 2639744892u, 1431686029u, 1903473537u), + SC(3268926613u, 1818698216u, 1862252109u, 1578913474u, 4289804840u, 1885759995u, 2888888373u, 2636129891u, 2360477693u, 1672434489u, 4188472821u, 2046052045u, 437371108u, 3454488779u, 2151384078u, 1514762405u), + SC(3140765176u, 3623124217u, 3204258419u, 1994235030u, 4141313973u, 3067394014u, 3891883464u, 3387486245u, 3254639322u, 1970078634u, 2106725210u, 2833086525u, 1670513208u, 472865524u, 2121280699u, 2548725819u), + SC(309446023u, 3610145983u, 678094472u, 3223511337u, 4188624231u, 2675209562u, 619208065u, 1214683627u, 307823706u, 3407147709u, 2103429213u, 3636822787u, 2441204583u, 1675916090u, 1444359140u, 2979809856u), + SC(1982287011u, 2286805587u, 3436767742u, 3002584758u, 477850697u, 439716674u, 3863581947u, 2155905635u, 220608999u, 1402913678u, 2974580099u, 1207717136u, 3265452095u, 2174870701u, 464004734u, 3218951674u), + SC(2374025586u, 3926883961u, 3555874460u, 1238670328u, 856489843u, 4258163476u, 977941661u, 3889087192u, 2262660846u, 1677408901u, 2922467369u, 1043137100u, 4279650771u, 3357788771u, 1512036754u, 2539641395u), + SC(1142842756u, 272648505u, 914080820u, 4056304706u, 1529598235u, 1542384711u, 898735874u, 77881967u, 1035144846u, 702992091u, 2075420139u, 2454875215u, 1266516833u, 2974932401u, 3666315911u, 2262316403u), + SC(282628724u, 2966722803u, 3533567779u, 2474391608u, 1236598744u, 3094620093u, 2714845907u, 369896328u, 366951725u, 2971547133u, 2753808137u, 618960857u, 2006195012u, 551749950u, 1402811398u, 3808228405u), + SC(962649761u, 2486282608u, 1808066694u, 2361174774u, 234593415u, 400975056u, 83848885u, 1091105486u, 1020816894u, 1838575736u, 2668167699u, 73800319u, 2028242253u, 2121917721u, 1921251529u, 2828854963u), + SC(2717497535u, 366873177u, 336873963u, 978494261u, 2877822089u, 2054875183u, 2521644031u, 4057807064u, 3713415744u, 3955164880u, 2229410320u, 3755022307u, 3363858805u, 1398106956u, 800395520u, 1799982442u), + SC(399227430u, 164572050u, 2101616757u, 962629850u, 1654784623u, 3459989194u, 2240801569u, 1986371042u, 1911756881u, 2723553175u, 2964071573u, 3609789600u, 3185432638u, 2208423303u, 2967147750u, 4279453877u), + SC(282950688u, 2418348758u, 1686423600u, 1392917024u, 3343336708u, 976718153u, 671781049u, 4166009090u, 371505957u, 2474457927u, 1126253569u, 3355537407u, 4151375790u, 2105071839u, 941370857u, 331122028u), + SC(2127306191u, 1587304141u, 1137651997u, 1529991785u, 1356564935u, 726775332u, 1952136309u, 4003891353u, 61741949u, 780292838u, 1136081573u, 1836882786u, 528077243u, 30578492u, 465809744u, 2709331701u), + SC(4118645416u, 3394012023u, 348789448u, 3808052591u, 1284813572u, 265335400u, 545565522u, 929596026u, 744207086u, 3837069751u, 130735480u, 1107476780u, 910486599u, 2623115273u, 1478462314u, 2130033795u), + SC(1955617954u, 1897311939u, 3110934223u, 4221780767u, 1556888759u, 3849614629u, 306928433u, 3178221670u, 2099698284u, 308858727u, 2221495536u, 1221057715u, 974275765u, 2399830054u, 3285960273u, 1758193777u), + SC(1309372774u, 3725783295u, 3135972452u, 3122681380u, 3898315320u, 1245625291u, 3684458552u, 2498694383u, 145248803u, 3480764710u, 874108791u, 2482726617u, 434324108u, 1522025692u, 3554266182u, 2125028368u) +}, +{ + SC(4095464112u, 3774124339u, 1954448156u, 2941024780u, 584234335u, 483707475u, 286644251u, 3027719344u, 2257880535u, 651454587u, 3313147574u, 3910046631u, 3169039651u, 2576160449u, 696031594u, 3062648739u), + SC(3459141530u, 1009969738u, 35229281u, 2373814441u, 355537356u, 4228991558u, 213496956u, 1669603654u, 1552983955u, 3304370832u, 604896268u, 499179421u, 2737968344u, 807678026u, 3567168353u, 2353882345u), + SC(2454671851u, 2184874449u, 831795291u, 1169825676u, 1084590471u, 1942690394u, 2762211706u, 3042637679u, 2365319338u, 3552008694u, 348752618u, 993280940u, 1178602031u, 1559708076u, 3354759347u, 972286478u), + SC(2677560697u, 4247966509u, 151962163u, 3310844434u, 2986095882u, 3914030856u, 3436387520u, 860446559u, 4289606749u, 2343453766u, 3218454181u, 293342071u, 1238022655u, 3938175190u, 1394478132u, 4256084776u), + SC(3033685698u, 1795086146u, 719843849u, 255984080u, 2447365525u, 874035973u, 313642533u, 1163634918u, 2316564524u, 1195940716u, 1914843207u, 3907025376u, 23457264u, 1278433300u, 3111232984u, 668125878u), + SC(2135745017u, 2899432034u, 1819124473u, 2109840859u, 3124696519u, 2070710502u, 990727745u, 2752134271u, 1963223245u, 866344359u, 606159585u, 3867224292u, 3038840373u, 3295910586u, 2433460716u, 3384811471u), + SC(1744070416u, 383286836u, 3000319326u, 3310329765u, 4062980155u, 2749127191u, 1895582230u, 439084228u, 1884304792u, 326674045u, 377650590u, 3363592478u, 2947641322u, 1784390018u, 1332541121u, 4203919218u), + SC(472957101u, 1135650637u, 4212757570u, 185931877u, 2096733734u, 4238795506u, 481917546u, 1405180051u, 925427330u, 1923351053u, 2204480714u, 3944038373u, 372144582u, 3395978522u, 3795034464u, 1074487901u), + SC(227727393u, 2219043153u, 2909459085u, 3082645761u, 1970114976u, 3426610084u, 35253812u, 3123666967u, 4231900027u, 2888054525u, 2744804820u, 1500359618u, 191232240u, 3239664209u, 1569663960u, 1330983134u), + SC(996304063u, 2759713926u, 1022152104u, 4268512678u, 2870837640u, 3507597858u, 1252922637u, 3276898019u, 3824649934u, 1524401760u, 2559990337u, 1660220688u, 2350855385u, 609332995u, 2406016501u, 2406242521u), + SC(3333888266u, 3838886221u, 3016467419u, 3341790649u, 3667104212u, 783789160u, 1310400762u, 3633793516u, 4105695306u, 2973076533u, 455893547u, 2864660063u, 3696934279u, 2872882056u, 2264350097u, 539812697u), + SC(3263458726u, 2820785414u, 3760367911u, 628854049u, 1473785327u, 426717862u, 2025377226u, 3498407835u, 3577945153u, 1319190911u, 1062047947u, 3346460201u, 2590672215u, 2723591074u, 1487439866u, 4217021014u), + SC(2076058913u, 33130418u, 1949000294u, 3536165044u, 31327487u, 1891010986u, 2347335564u, 1669503944u, 3753248202u, 881959988u, 3846164684u, 3636142472u, 208517894u, 3407391141u, 3485893709u, 1074365179u), + SC(2175348532u, 3463201667u, 168136052u, 2889266255u, 4105885613u, 3068947090u, 2279310533u, 2649966235u, 828612565u, 2017635648u, 1260407590u, 1970316631u, 2447304459u, 2893112079u, 2425504835u, 1197046834u), + SC(2653983058u, 1419924288u, 2320709126u, 3640188854u, 2683911962u, 2643927342u, 3261193464u, 3929873787u, 2878724355u, 3436083049u, 3424148509u, 1311037973u, 3116391362u, 2037892948u, 454042580u, 970415398u), + SC(16199673u, 2464180001u, 89776423u, 672570852u, 2291071982u, 3899998968u, 4262439281u, 412856039u, 3677249728u, 1182323568u, 3472045521u, 3554674668u, 819725249u, 4078699211u, 2037243914u, 4166444096u) +}, +{ + SC(1740919499u, 3877396933u, 2326751436u, 2985697421u, 1447445291u, 2255966095u, 1611141497u, 1834170313u, 3589822942u, 2703601378u, 299681739u, 3037417379u, 4014970727u, 2126073701u, 3064037855u, 2610138122u), + SC(2959647136u, 3814991611u, 764778261u, 1677371416u, 497556143u, 1000564042u, 4065791500u, 1027030318u, 2636763418u, 2469599275u, 839050056u, 4115114412u, 3982189672u, 2204140838u, 1747652790u, 3786215179u), + SC(3812425833u, 3703652912u, 1980699604u, 1506061914u, 2330998846u, 3874717363u, 20614012u, 1484655664u, 2896690261u, 1196646483u, 159078055u, 1300317512u, 2570981831u, 1267318554u, 3037645632u, 3117135345u), + SC(2012483448u, 279997059u, 1908492604u, 1638405820u, 284407565u, 1607271004u, 1423855670u, 3949669604u, 1635878907u, 4045715556u, 3600475894u, 3387647818u, 3950223476u, 3109131487u, 2524676171u, 3329048150u), + SC(3505120665u, 1999377488u, 158974979u, 636438923u, 1767149410u, 2424026197u, 532320013u, 3350230775u, 3506414357u, 999737675u, 3415715721u, 797201045u, 3439137094u, 3636888232u, 1001867404u, 1070514934u), + SC(803341976u, 972240723u, 2174569332u, 4037031657u, 720363583u, 1532359940u, 222173943u, 3948724459u, 669414977u, 446802288u, 4195328223u, 2316597014u, 3039478974u, 1217500351u, 1058613984u, 3974805650u), + SC(2497689022u, 832535973u, 4012390289u, 3862385792u, 473134599u, 855172718u, 3160709443u, 2946049581u, 1340978834u, 1282260619u, 3672935594u, 1114896253u, 1194768191u, 2151967837u, 3557909289u, 83919397u), + SC(2685697085u, 4183307820u, 393931333u, 2425217781u, 2950365274u, 2300063381u, 3990090983u, 1961757942u, 3357278228u, 2993935030u, 779960569u, 3652282828u, 1743505267u, 3193034940u, 2134245237u, 4042181132u), + SC(2449311128u, 4037657778u, 318968012u, 1098807866u, 3241626396u, 745989749u, 4126255071u, 850508142u, 4075976689u, 357235455u, 2000916706u, 3900438139u, 2804084317u, 3036848582u, 604252796u, 2006800965u), + SC(101955641u, 2732365617u, 2730133770u, 3908553062u, 2872853047u, 264325893u, 2086018926u, 546076667u, 582367640u, 2242336949u, 2223649162u, 1521240572u, 178342991u, 3408523296u, 2216853754u, 1636770650u), + SC(1697876449u, 998213608u, 2367869150u, 3635535434u, 3029347602u, 2697162358u, 300760335u, 3790588806u, 3127970813u, 157171921u, 2766714052u, 3441353031u, 3760111386u, 1962222723u, 1338315915u, 1705537099u), + SC(2069540711u, 3174156395u, 3834082852u, 2243125169u, 1332693007u, 1773075089u, 820191370u, 262117783u, 184405617u, 469065021u, 1286610377u, 946922506u, 2233109630u, 2803987975u, 489850357u, 3341265389u), + SC(3152895344u, 3190413328u, 1371373852u, 2133030998u, 2097773989u, 3484604561u, 3233580762u, 2103971308u, 580626917u, 3723142348u, 1233964596u, 2884246809u, 1451113068u, 2274332609u, 834566918u, 4166322862u), + SC(474309298u, 31198476u, 474732582u, 1614612386u, 2339718649u, 702598622u, 2007092771u, 1563921691u, 3096928870u, 2036801390u, 3171632090u, 2666464957u, 2581592302u, 84487705u, 4066440296u, 250703600u), + SC(2850943751u, 3355276358u, 3608928556u, 645558581u, 1754003398u, 2401097307u, 4007141515u, 2306720640u, 2585847442u, 2486681168u, 916961025u, 2906286711u, 2183350629u, 3403456959u, 1234360906u, 608407455u), + SC(3919397u, 2910764499u, 1130649170u, 2504839137u, 475960727u, 4198145923u, 3575554927u, 727034596u, 3487299979u, 2134210036u, 1295494166u, 1094003986u, 3153584442u, 1125501956u, 1050325095u, 3018071122u) +}, +{ + SC(1456510740u, 215912204u, 253318863u, 2775298218u, 3073705928u, 3154352632u, 3237812190u, 434409115u, 3593346865u, 3020727994u, 1910411353u, 2325723409u, 1818165255u, 3742118891u, 4111316616u, 4010457359u), + SC(2413332453u, 1353953544u, 4051432026u, 303594340u, 1259813651u, 366336945u, 3380747343u, 2634392445u, 2066562619u, 120707135u, 1398541407u, 502464084u, 2984999938u, 3829298149u, 1120989122u, 3373752257u), + SC(1681071159u, 120984332u, 2029459879u, 1382039080u, 3634662556u, 54408822u, 48099449u, 1179080842u, 2669759950u, 3169946602u, 1520730683u, 3878549631u, 1666070500u, 1804495215u, 1101808889u, 1988315741u), + SC(1810699040u, 1982264875u, 1311915666u, 268159494u, 1265118580u, 1494821999u, 2740360551u, 3403457379u, 2370002476u, 3663200326u, 1969174367u, 2988878975u, 2261867571u, 1896957751u, 4228495601u, 268030737u), + SC(3788031612u, 1459331879u, 4195039120u, 148760443u, 2710036304u, 3803193725u, 2316636996u, 1290739855u, 2078515077u, 1158390637u, 187516666u, 1165781180u, 3871854912u, 2887741280u, 3432370474u, 3017515415u), + SC(2660400581u, 1115514969u, 819611304u, 2438542525u, 1149450061u, 641570348u, 4195260176u, 114239580u, 3415942550u, 2418164759u, 3596450733u, 4170880111u, 3742333800u, 707266970u, 294392938u, 1502400257u), + SC(4244209414u, 4144723933u, 1206802017u, 3395049043u, 1534528858u, 212213384u, 273948964u, 2465871688u, 98513287u, 526054552u, 101003852u, 2178852720u, 1739213138u, 2000068838u, 3443316390u, 2907641948u), + SC(4170329393u, 2397160575u, 698736458u, 1726629095u, 2059726015u, 608224441u, 940962377u, 3160021800u, 2474105021u, 1418624931u, 3220142189u, 3165061177u, 609263259u, 3526248509u, 2451110984u, 882122082u), + SC(1803413035u, 2626850042u, 3923382679u, 2501640460u, 887077755u, 2970691407u, 3982443858u, 546345352u, 545064661u, 1905866916u, 4137411501u, 4293519422u, 399697152u, 2101209662u, 4081268472u, 3745325674u), + SC(3913855272u, 3324082002u, 2401043817u, 1769760109u, 2460560183u, 875956117u, 1942607787u, 1641754800u, 1964565342u, 442388011u, 1687580604u, 293988342u, 3046598358u, 2835075967u, 920490836u, 349604594u), + SC(2643665013u, 1607952309u, 2279132309u, 992705865u, 1231530495u, 2682680275u, 2340070945u, 1036310446u, 2160469638u, 3849593659u, 569936175u, 133751759u, 1309000826u, 3681058360u, 1289881501u, 385711414u), + SC(1190130845u, 2798968177u, 277741425u, 3875973536u, 2502592372u, 251555512u, 1825737360u, 462006518u, 2334535950u, 3997809264u, 2012251623u, 3408888487u, 2549759312u, 3379458376u, 2301581275u, 4171117892u), + SC(1923456093u, 1653002750u, 3279649712u, 4281661052u, 1248011568u, 933375742u, 2109342469u, 751470571u, 2742486580u, 2572871261u, 3296809419u, 4075155428u, 3182626853u, 3435860599u, 3916597057u, 245531435u), + SC(514908612u, 2222061780u, 506774061u, 381342968u, 789366883u, 3683832850u, 9270407u, 528428861u, 590313143u, 483933274u, 1128871308u, 2791400346u, 3033966006u, 2397900561u, 174539653u, 2363998101u), + SC(3558289816u, 1015432688u, 3960686128u, 2087286003u, 446928557u, 4028273076u, 3055038539u, 885707705u, 942001648u, 3175434773u, 3929872598u, 2961036794u, 1122092143u, 2142675404u, 4054255588u, 1958229328u), + SC(2852327378u, 1383667573u, 3763466478u, 3195889922u, 2107642962u, 1739908882u, 157313327u, 492435243u, 4236498733u, 1510923342u, 3227437908u, 1896980749u, 154410481u, 2958311799u, 3270353062u, 1889012642u) +}, +{ + SC(822693957u, 1703644293u, 3960229340u, 2092754577u, 3495958557u, 4288710741u, 4092815138u, 1275224613u, 2592916775u, 472063207u, 2931222331u, 2597044591u, 1261640449u, 1272207288u, 2040245568u, 1417421068u), + SC(57865933u, 2591783175u, 1332940705u, 2361514832u, 2842982424u, 2581566511u, 1328343723u, 3898369656u, 2090549923u, 2179715082u, 2370481583u, 775215786u, 3850307123u, 2489521783u, 3999750482u, 1014134079u), + SC(2011629934u, 1914036612u, 3406392133u, 1425412057u, 1338374071u, 683386303u, 3190457777u, 428137206u, 1251032257u, 3672462899u, 2593185313u, 1953316437u, 2123216916u, 3258622817u, 3197533388u, 3442579011u), + SC(265734183u, 884987600u, 2786263189u, 3536027957u, 3885575220u, 1854265340u, 3853595664u, 1987453181u, 2744740518u, 512197390u, 114481815u, 96285071u, 3293497789u, 4015333892u, 4092376929u, 3025411574u), + SC(612519829u, 3198151239u, 3191059512u, 226844204u, 3503855660u, 764021515u, 3628841562u, 3951882416u, 3622158804u, 3603368155u, 2780109382u, 822859403u, 25907739u, 3882220368u, 3789068172u, 1684074913u), + SC(3520260226u, 1656105499u, 1676578448u, 838040958u, 3130046810u, 995588852u, 3233766730u, 2629592527u, 3096399775u, 1659682138u, 1365617549u, 2450677843u, 1725372848u, 2623357383u, 1402837393u, 1993344168u), + SC(2434333993u, 2901722469u, 518468307u, 3322336116u, 3303354477u, 2422295273u, 3584734361u, 1255342255u, 2224600785u, 3752112711u, 3720624102u, 3425652159u, 3563799906u, 957522630u, 501907560u, 3362627156u), + SC(3271809032u, 2402529419u, 3935184016u, 3639910664u, 659985988u, 2584831332u, 1091987512u, 224789177u, 2944016703u, 3591574599u, 1273021052u, 967556634u, 1019501719u, 1864898605u, 3453844870u, 4011599553u), + SC(1326048883u, 3477092042u, 1799777609u, 296885426u, 1109310872u, 255028335u, 163456938u, 2108662143u, 3501831646u, 225777648u, 4099069764u, 3428610561u, 4069711767u, 3876386370u, 1215899260u, 369937558u), + SC(3466874302u, 1921411468u, 3753149186u, 3739960133u, 1909238781u, 2219053499u, 4040572016u, 1651280893u, 754573870u, 383500798u, 2400558032u, 922698902u, 2125517085u, 2541623325u, 2827334144u, 2773618829u), + SC(2040368526u, 2190975469u, 1347589661u, 1684817146u, 2021572959u, 1656810013u, 330975936u, 994237514u, 2596719101u, 3800849855u, 600269956u, 1857741551u, 3033366103u, 1496147464u, 2628189942u, 4210116847u), + SC(3076719908u, 2490548320u, 377911263u, 2002478742u, 2549252529u, 839159951u, 230337140u, 3095221595u, 1528132928u, 2083899038u, 2503451113u, 272698731u, 2624407067u, 161482016u, 4135914440u, 2519252428u), + SC(2556876861u, 2107629748u, 2377697213u, 1433609947u, 3343742332u, 3505415093u, 2690575000u, 2017949066u, 4133794057u, 4184820210u, 2960078982u, 1333558937u, 3733636790u, 3960011078u, 945143131u, 3343864106u), + SC(1801254589u, 1449097227u, 181948563u, 1034221031u, 1779862110u, 3141289560u, 3383585093u, 2578193674u, 554670851u, 2530857925u, 4076682145u, 2827602863u, 4244507626u, 2938597885u, 3223414171u, 2204001183u), + SC(291814305u, 2937237569u, 1434020428u, 3585179044u, 3677832974u, 2016114805u, 3981784693u, 538800869u, 2673738915u, 999373833u, 1457987857u, 3180983013u, 501300267u, 4103517997u, 997980659u, 1113009463u), + SC(3993610129u, 1037741502u, 330412440u, 2749687355u, 1555232145u, 1196959672u, 530284980u, 340384986u, 2298150586u, 3185141181u, 26985524u, 2219307959u, 2447245692u, 1065988754u, 1248620406u, 2208024308u) +}, +{ + SC(3660855132u, 3816892380u, 3431508003u, 1440179111u, 768988979u, 3652895254u, 2084463131u, 3991218655u, 323118457u, 3675476946u, 2157306354u, 2684850253u, 1543808805u, 744627428u, 1091926767u, 3538062578u), + SC(2810298495u, 3411171710u, 4062828084u, 3003344135u, 3264709694u, 1048068132u, 3549102117u, 1927032841u, 3841604555u, 1360558064u, 2204714588u, 1197341693u, 3768005385u, 2899352192u, 2849083812u, 3793398404u), + SC(3631867959u, 3146872034u, 420513606u, 2446059169u, 2652499910u, 429155541u, 748397809u, 3543114527u, 235482177u, 894763888u, 1086818023u, 3285579564u, 1810274445u, 1142434275u, 140188668u, 4059040723u), + SC(2682453748u, 1595694625u, 17869409u, 4001607469u, 759206176u, 3336900820u, 3693692341u, 2473365492u, 2714988574u, 637563477u, 4105755464u, 3161387095u, 2814461644u, 4283494186u, 3858290792u, 1516784203u), + SC(4062605051u, 1956634460u, 3701616314u, 2342355265u, 1267526896u, 464674235u, 2247549950u, 3633206724u, 296547100u, 2905295542u, 4077085273u, 2746567644u, 1803616500u, 918536622u, 2709233803u, 2413530101u), + SC(1383097263u, 1316928613u, 759541292u, 3793001510u, 257497874u, 3658838865u, 3213596633u, 3650670599u, 63812226u, 1947202098u, 3651967368u, 2399936732u, 2521262969u, 322630211u, 4004516883u, 1422335688u), + SC(2852550033u, 3224936812u, 733055828u, 3325391168u, 1930707186u, 731324754u, 3498518219u, 4117056191u, 2179511600u, 2761523161u, 4282458808u, 3042559735u, 2438675720u, 2532100345u, 3706723018u, 4059342362u), + SC(2048163474u, 1848349034u, 3258863528u, 3644103333u, 1151231486u, 3308192205u, 2814277731u, 4197063636u, 3510455851u, 1315219655u, 2185965649u, 3799505477u, 4254363720u, 3128925961u, 1852465545u, 4138612075u), + SC(960983998u, 3301464188u, 2737893955u, 1522861436u, 4164105020u, 1184099683u, 64022400u, 2368856028u, 326418376u, 2065332946u, 2081529277u, 3466798514u, 208026276u, 417986090u, 3587033208u, 2294843214u), + SC(2712989146u, 349068332u, 3978782854u, 1513755929u, 4281030368u, 4041238337u, 1631550267u, 936378809u, 3831648862u, 1780262732u, 3189639539u, 328937247u, 722753719u, 3671027558u, 215485348u, 294998383u), + SC(170533035u, 3100330628u, 2519007245u, 2729143680u, 1780483799u, 1771308699u, 777046078u, 1252661309u, 944830935u, 3219243484u, 2959537667u, 145170296u, 892161275u, 1151850054u, 2176346749u, 598783080u), + SC(3596882604u, 51304713u, 1277701547u, 3288737023u, 2143659411u, 1229626338u, 2504854740u, 2518260221u, 2909459409u, 3820898741u, 1076396276u, 3330086214u, 2070741501u, 1675949151u, 4169029889u, 2072266145u), + SC(3395707749u, 1912264784u, 839246291u, 1812660322u, 2590197689u, 3115125394u, 280633483u, 1476186344u, 2182942190u, 4022517575u, 1314348304u, 2211853573u, 1730367526u, 3842875309u, 1411362967u, 749836026u), + SC(822183119u, 2084092802u, 2957672615u, 1548122281u, 2555590320u, 4127903458u, 704941703u, 3216796016u, 1310798669u, 1681974379u, 2704001393u, 836064664u, 2498528840u, 2878347924u, 3344415063u, 1714110968u), + SC(3763417450u, 1647484613u, 2916400914u, 1340277384u, 3671023234u, 2962715012u, 2086976330u, 2356641838u, 861453503u, 2497852292u, 3384683911u, 2044029625u, 3423593678u, 602612346u, 1947876325u, 1071593133u), + SC(502143537u, 3800930061u, 289630048u, 2019675509u, 690814111u, 1395759030u, 2095320716u, 1658529388u, 2140950369u, 4113871752u, 2130755443u, 1184235968u, 2624156111u, 1053548247u, 1666584094u, 3436241707u) +}, +{ + SC(2819478132u, 2629026829u, 2945562911u, 1854605392u, 41922071u, 2531530491u, 2316774439u, 3550381961u, 1180787169u, 3914439365u, 3786421842u, 3441223373u, 494782102u, 2858003292u, 1448968751u, 2940369046u), + SC(1228705098u, 2320747717u, 1742025124u, 3358828738u, 1857762103u, 2669617968u, 2684123743u, 2427291148u, 3948024171u, 3841263454u, 3817968782u, 3617000488u, 3457510946u, 3443415072u, 3976288418u, 291039859u), + SC(1118114309u, 1364783097u, 3986370035u, 1058514953u, 3723130907u, 2966082807u, 1592373613u, 4029958112u, 1261460522u, 159904028u, 385928252u, 2962822321u, 213058425u, 39305506u, 3400567258u, 2953928339u), + SC(4004285350u, 3275325131u, 2912133301u, 482119944u, 699333459u, 1353300830u, 498723416u, 2738735797u, 3773472794u, 1167510524u, 1995708610u, 1872986795u, 1771998886u, 460328822u, 2566240531u, 3665251184u), + SC(870908870u, 249845288u, 3674648542u, 3670939624u, 3213883826u, 2765218754u, 3292181727u, 1765634472u, 2846619223u, 156162860u, 2158300764u, 3792761756u, 4248292998u, 1588571137u, 1696144875u, 2915693433u), + SC(1257645965u, 743351844u, 3299328612u, 1606739395u, 2242479072u, 526126122u, 3132670209u, 2327012389u, 1257540758u, 1688790030u, 864103666u, 1782879705u, 2344074317u, 878043196u, 569218289u, 3875319913u), + SC(676712446u, 2310487862u, 3297058723u, 154140360u, 1534807165u, 2207878247u, 4002312458u, 1195155314u, 3973562995u, 203866583u, 1307033594u, 1808951889u, 3485439766u, 2123920858u, 3400721970u, 628518531u), + SC(453432196u, 3506137302u, 962794710u, 2800823697u, 944975983u, 445662356u, 620440622u, 225699982u, 1038708892u, 3484553780u, 4174808994u, 3862318255u, 1961625058u, 2183421173u, 2682639230u, 3890472885u), + SC(3472048934u, 1436162338u, 4281682055u, 1419885595u, 1926695253u, 861477946u, 2586543901u, 2286266784u, 2854911092u, 1779735787u, 2994125983u, 2248840912u, 677288518u, 3593153557u, 3383199489u, 2094768467u), + SC(971218259u, 3653638590u, 3374334294u, 479058129u, 1331477004u, 2497262229u, 892109896u, 3651901580u, 1455849852u, 2738531309u, 14202660u, 1968080740u, 1927308794u, 897128363u, 3654300057u, 1275380700u), + SC(684658124u, 660984744u, 2929312783u, 1473333980u, 1562502960u, 656352357u, 338449257u, 2159155320u, 2425193686u, 930413364u, 2001285554u, 307432757u, 2238003500u, 1858295105u, 481986971u, 1067622012u), + SC(943383548u, 127299943u, 2909652237u, 1257655712u, 4123282405u, 78394323u, 1736026340u, 2126927829u, 296638455u, 1861436609u, 641299684u, 636649068u, 3331138991u, 1014270261u, 257248847u, 1556179874u), + SC(2668740334u, 4261010365u, 3376970497u, 2258271000u, 3369826513u, 906131732u, 12531263u, 2501581679u, 861444520u, 2059219969u, 3536488433u, 3392343056u, 3231250347u, 3425501702u, 4204845226u, 3883035310u), + SC(875006280u, 3061145215u, 799684212u, 4150716124u, 1344915012u, 1442298502u, 887378800u, 2722425542u, 4141895498u, 4068116328u, 601774281u, 3538746538u, 1671758462u, 3066546971u, 1116345758u, 554718074u), + SC(1149406575u, 702696847u, 505403366u, 331269161u, 664926760u, 2151357672u, 2890104906u, 3156886545u, 1199701084u, 1614409973u, 4222014462u, 1336462493u, 3214687968u, 1279434993u, 2285235388u, 2975474024u), + SC(2419658919u, 481424988u, 2207220911u, 2736159805u, 4086711147u, 477511738u, 1428567116u, 3971000648u, 429362137u, 3495313342u, 3653961670u, 4170077754u, 2057308114u, 1445981917u, 97057494u, 3847612010u) +}, +{ + SC(3017729014u, 3423125690u, 1534829496u, 1346803271u, 888659105u, 1661894766u, 4165031912u, 697485157u, 3575889724u, 1795181757u, 1507549874u, 1480154979u, 3565672142u, 830054113u, 1507719534u, 3652903656u), + SC(4123340423u, 2168639254u, 3491407759u, 395600125u, 2056091205u, 1233197217u, 2716612715u, 3263564356u, 2257286689u, 2753339767u, 2228663460u, 3584404544u, 3972978154u, 3637886739u, 3854541466u, 1603898424u), + SC(641806023u, 3776877383u, 3574980110u, 2564901152u, 1378226343u, 738790225u, 4030459977u, 2255719927u, 295765315u, 60094770u, 422069111u, 439158593u, 3956842123u, 1242303994u, 150522972u, 3682386439u), + SC(2385589330u, 2076597417u, 605447848u, 3200763641u, 3106877254u, 3374069827u, 3828392492u, 1315607291u, 3211667999u, 305089333u, 179172787u, 3225149656u, 1080822644u, 3286534940u, 2231515542u, 2699760148u), + SC(3983719183u, 1208009460u, 767048521u, 326825213u, 1087716958u, 3599826498u, 3107818740u, 2785268698u, 1304576537u, 1847155836u, 3250405674u, 2694326935u, 2163030471u, 3253944705u, 1698753082u, 3845065767u), + SC(2823293375u, 2790862099u, 1207038844u, 3886043838u, 3567640686u, 3799791258u, 1638354726u, 1428653770u, 2075289233u, 1582582790u, 213364421u, 2858522524u, 2809903954u, 1742449197u, 324107072u, 1051562955u), + SC(2291926834u, 1805734123u, 3420689573u, 1003089617u, 476535216u, 1334543097u, 2045923069u, 2990972415u, 1822043289u, 2128934150u, 3541372378u, 1912558832u, 2295908612u, 1500502429u, 3539272060u, 2641558214u), + SC(3069594753u, 3051481608u, 2339450545u, 2054924228u, 4282917353u, 65440790u, 2134400604u, 3588265957u, 2569563771u, 741034486u, 740973978u, 93172292u, 1583303041u, 2980574219u, 2969067524u, 1088571815u), + SC(78721532u, 1566330912u, 1219109269u, 3229207312u, 2345730495u, 3209647323u, 2033975193u, 1009666575u, 2794060854u, 4218956981u, 3379703631u, 2400336569u, 100401885u, 3519721431u, 4007729122u, 3851183625u), + SC(2344993313u, 2454241381u, 3071516966u, 4207668067u, 250885582u, 1733938903u, 1658948056u, 2192440210u, 1717829063u, 849763004u, 2334162093u, 3715296533u, 1757279167u, 3270001477u, 2677428083u, 4197601814u), + SC(2911676146u, 4069956071u, 3299890629u, 3133371278u, 3551760603u, 558967408u, 205243474u, 237180706u, 4227661901u, 390685951u, 658498389u, 225847327u, 3028263358u, 3941067795u, 1850521034u, 1584413524u), + SC(304549398u, 3089811378u, 549382137u, 2353383127u, 2278640956u, 781853185u, 1734676013u, 3311472816u, 957105351u, 1291924767u, 2025324585u, 3897237789u, 80455313u, 302089802u, 3496158310u, 4000611245u), + SC(1221283087u, 3865703766u, 1551786763u, 3208862988u, 2964616465u, 1429406173u, 2847895093u, 3047143885u, 3187847794u, 3875229246u, 2044093786u, 2855772466u, 2252977997u, 1253496627u, 1824313803u, 3492626272u), + SC(1435191953u, 2954553263u, 3689501374u, 3761866706u, 3160683386u, 2172174457u, 4033800334u, 2293562561u, 500568896u, 2877151546u, 112648553u, 2760351679u, 1976713840u, 2960166087u, 1364536484u, 4127293522u), + SC(2942286091u, 3570696800u, 2680748212u, 879905933u, 371824626u, 2796545677u, 2544287558u, 1654320774u, 3724452395u, 1875952433u, 1755420330u, 700510406u, 2122483560u, 357724466u, 2579725929u, 4152935597u), + SC(732269412u, 3045632405u, 947036931u, 2403831527u, 2919479301u, 2947112020u, 1653738112u, 2316444303u, 3103978479u, 2856978461u, 308282125u, 1154683958u, 2086296447u, 1288456128u, 528614237u, 2945631134u) +}, +{ + SC(3751554592u, 1759634227u, 4138518211u, 3130599659u, 3881948336u, 669688286u, 3672211577u, 695226401u, 1226786139u, 1855160209u, 905875552u, 2831529665u, 1625185017u, 3130043300u, 3227522138u, 3659203373u), + SC(399372699u, 529779700u, 1206056828u, 1867177702u, 196488961u, 2148657353u, 2522788662u, 2308787051u, 1566407979u, 857878238u, 2852634973u, 2131204123u, 2812808340u, 3651465982u, 1947448513u, 3757182587u), + SC(3732610632u, 1025396308u, 60450219u, 3075208965u, 2460440177u, 301478800u, 2020185415u, 2910424285u, 1627945543u, 473410099u, 4114096970u, 2440686062u, 3031404169u, 2099206907u, 1232790956u, 2248800462u), + SC(2343232878u, 1198836246u, 1270188071u, 2305538045u, 1841160260u, 1049160535u, 2935147928u, 3818293360u, 2128394208u, 692132409u, 3183837651u, 981952986u, 3501941431u, 1239605342u, 1265208179u, 225920797u), + SC(1958540456u, 418545838u, 1645667403u, 4203505141u, 81660142u, 351421726u, 2877676470u, 871152679u, 2804776066u, 431108218u, 927442607u, 3782508732u, 318483929u, 4079394971u, 1143889788u, 4195920424u), + SC(2351179626u, 1598459225u, 3579449038u, 4292231882u, 2911534527u, 3174868713u, 2883217980u, 1046921244u, 3074833211u, 117299980u, 3425406982u, 2813303717u, 879305153u, 3439142119u, 1270010014u, 2633468950u), + SC(3394012837u, 1133386629u, 2931266329u, 2512080059u, 3268046571u, 585832644u, 1151303760u, 4164956195u, 1787214290u, 3523549326u, 4139598868u, 530139359u, 2107355242u, 1401770006u, 4264627539u, 3014221080u), + SC(1988836761u, 3474599222u, 2535855552u, 3118306895u, 1953046625u, 30632894u, 8987922u, 1482010220u, 1585584845u, 441041520u, 3045700482u, 362734762u, 3723600227u, 1056985402u, 2472480517u, 3558297033u), + SC(4137318322u, 915055827u, 1432589840u, 3550795442u, 1919127293u, 1256417138u, 946345068u, 1353195020u, 2948635882u, 3916808200u, 3223857138u, 2259986522u, 636089773u, 2116476405u, 266813303u, 3992924481u), + SC(1294364269u, 2282087282u, 719947200u, 1065389577u, 67185303u, 600695627u, 3423704882u, 507439949u, 1464333499u, 954935833u, 1949391476u, 2146234814u, 640934838u, 2477152026u, 3767255766u, 2397668523u), + SC(1825548026u, 2780595753u, 282065873u, 3347141416u, 3152283414u, 1656153711u, 1047376382u, 3616949007u, 464657631u, 3299783240u, 1162505878u, 3862534742u, 3899846651u, 3980167606u, 2513773976u, 1803555687u), + SC(734708953u, 181663675u, 2018505992u, 1055015000u, 2266993350u, 3679506170u, 1032089726u, 2239152753u, 3271229362u, 257492591u, 519168390u, 890304984u, 594386284u, 933877218u, 2646719799u, 439652468u), + SC(1253204385u, 2215899770u, 848155650u, 1305331452u, 1831981169u, 4101626048u, 253253616u, 718148001u, 3846087699u, 2362703617u, 564971301u, 878503956u, 2792594154u, 3831500219u, 630060686u, 2654848235u), + SC(2082956373u, 965635733u, 1172460454u, 3057130868u, 485386699u, 558270142u, 2819896785u, 247008390u, 1884023798u, 3291747866u, 1725636793u, 1552257124u, 171155452u, 894504521u, 3157754944u, 4135144713u), + SC(3013624247u, 3479051648u, 3976465681u, 139584997u, 690715168u, 2972053528u, 2543659091u, 81834710u, 261064551u, 1476481099u, 2550215537u, 1381589752u, 3557508349u, 3578290922u, 1272133161u, 3008228265u), + SC(3507369103u, 1077600519u, 1522596015u, 3088783267u, 2852999673u, 751358577u, 733140212u, 3467225217u, 100497019u, 50410977u, 68742811u, 3090618848u, 1603912616u, 2272476179u, 1767751118u, 3249696448u) +}, +{ + SC(2950670644u, 1870384244u, 3964091927u, 4110714448u, 298132763u, 3177974896u, 3260855649u, 1258311080u, 2976836646u, 3581267654u, 3094482836u, 80535005u, 2024129606u, 168620678u, 4254285674u, 2577025593u), + SC(1515179601u, 3578614970u, 3088354879u, 797813018u, 1355130048u, 1083957563u, 119796717u, 2021253602u, 1525138732u, 4127381203u, 3062851977u, 4142386071u, 1213064952u, 3609844670u, 1484215992u, 3431673114u), + SC(1401099367u, 3953214819u, 830584870u, 2207781603u, 918659453u, 4293181358u, 4072336467u, 4282551694u, 262435288u, 1941569548u, 147995405u, 1811389750u, 4118444114u, 1252574507u, 578798636u, 1074483177u), + SC(2872591360u, 1058667772u, 16799222u, 688522560u, 3475129040u, 3433794124u, 1076991040u, 1425059515u, 2939587530u, 236447274u, 3960100164u, 1298525395u, 2761371754u, 4025787449u, 2464666072u, 3981743594u), + SC(3976786453u, 1358319886u, 3905641993u, 1405765539u, 2585003073u, 3447572652u, 741448872u, 3444688769u, 971292808u, 1486657617u, 3079335839u, 862424956u, 248802634u, 1703726921u, 2982469234u, 2682500687u), + SC(4273605693u, 2467118193u, 3538801384u, 3862847335u, 1065478730u, 1602785515u, 1071410798u, 2624755760u, 2768741032u, 2700950902u, 558848464u, 3400938789u, 1410632048u, 2094050860u, 1686695852u, 2101955993u), + SC(4124709913u, 3191744141u, 3038636619u, 2944952304u, 2687117769u, 1502766822u, 14738299u, 223780235u, 32298390u, 1195949618u, 1154476371u, 1873391152u, 273358443u, 2362272244u, 509120994u, 606974408u), + SC(3937286725u, 1520668653u, 941545039u, 3056942351u, 574018151u, 2549472282u, 82289937u, 374652507u, 619831005u, 2134744303u, 1462663193u, 2963006112u, 3726585674u, 1797461239u, 1470634776u, 3441417480u), + SC(2845288945u, 3925574221u, 1989126288u, 3105801567u, 210047271u, 1545005898u, 2572648420u, 2278643173u, 2633053858u, 3288168184u, 3566345146u, 165026071u, 191806458u, 4116335861u, 1768316231u, 3169297484u), + SC(253765755u, 2509241970u, 1926513613u, 3735004917u, 4188741775u, 2806800711u, 281300019u, 3635185u, 3462483807u, 2277745510u, 1708651892u, 1413928970u, 56262931u, 531946794u, 2864634184u, 3118504241u), + SC(4194010611u, 4232988065u, 1802432341u, 3448133339u, 3732370320u, 253801846u, 2726367450u, 3905836819u, 1373544282u, 2066678017u, 3439519431u, 3381452691u, 2754663978u, 535580478u, 2512241599u, 2720083475u), + SC(3589933363u, 4047249230u, 2311777188u, 270484672u, 1108190662u, 2080251561u, 1724842405u, 4014518744u, 1593608472u, 2342434397u, 4205240553u, 2166622191u, 3528923u, 1996089122u, 4284726332u, 989608730u), + SC(2475269743u, 4230552139u, 3917936952u, 3098769598u, 3209444661u, 4188126675u, 3974782724u, 3639917274u, 2711234947u, 1439392508u, 1127433801u, 478802541u, 4223040451u, 2268034322u, 2452212595u, 3508939070u), + SC(2413851784u, 190519100u, 3576747926u, 2710481928u, 2148944938u, 3984096005u, 2427227598u, 1001464024u, 2191178977u, 1139441673u, 3841324161u, 308061908u, 3976150834u, 1467800561u, 3226772030u, 1743883019u), + SC(281260179u, 1415659644u, 915707047u, 1662956706u, 911938094u, 3456789397u, 2082200558u, 947098788u, 4036848108u, 2455542339u, 1466205449u, 4158358953u, 586549709u, 850657486u, 61343079u, 2292663847u), + SC(3487862268u, 4116082621u, 1969417576u, 1466595601u, 3136251120u, 3697533272u, 438943523u, 1041892750u, 1141661777u, 435333448u, 3031876514u, 2121342186u, 209290199u, 256519609u, 1400190683u, 4260080502u) +}, +{ + SC(1406628534u, 2978091511u, 343468499u, 973866526u, 757277528u, 1142388839u, 2945536141u, 3759469101u, 3001571847u, 2170606364u, 1017327004u, 3120716036u, 468321128u, 3656061918u, 2331571461u, 1930702552u), + SC(3117811324u, 4230396490u, 526101390u, 3589443580u, 12282838u, 3055128772u, 453582536u, 750425919u, 87216299u, 1999749165u, 2446098001u, 1907762611u, 183870981u, 3643605669u, 4232900175u, 2946539195u), + SC(3903405291u, 1034986659u, 2587588236u, 1880077572u, 1696686560u, 1243434386u, 3746745675u, 2212912696u, 2031851135u, 575946730u, 2663616094u, 2706019532u, 2635197066u, 1942621203u, 3760379195u, 4173271368u), + SC(2892050679u, 1105289247u, 1519565685u, 2426902952u, 65580444u, 3373395323u, 2112756687u, 3658806066u, 2548718870u, 3586646888u, 3350821933u, 1921239811u, 4061525916u, 3520594550u, 1872307168u, 3464547908u), + SC(2889143489u, 489507550u, 788811400u, 1800916293u, 3249681744u, 1400920516u, 3917828215u, 1093821500u, 1905385813u, 2931012984u, 1800788801u, 1697549042u, 3133274419u, 3606456099u, 2156683634u, 3205410986u), + SC(2814687995u, 4053305746u, 484530004u, 410862009u, 246830045u, 3164065541u, 3723774424u, 3388961612u, 3438413619u, 3662326637u, 2178649434u, 3555798301u, 164350275u, 2341607004u, 3896269562u, 1591806179u), + SC(3226183767u, 3881369008u, 700458770u, 376569395u, 2607908019u, 1353553198u, 2636334721u, 1140283021u, 2632309194u, 1710844790u, 3031461719u, 4081969123u, 3326745889u, 4034909949u, 3950856167u, 3153389256u), + SC(2184243175u, 2166726232u, 3921103433u, 872887260u, 623636347u, 95935618u, 2766774027u, 697875047u, 164043041u, 993154257u, 4114304816u, 3500729957u, 409872172u, 3504722710u, 2806324915u, 717798207u), + SC(1913401183u, 1684394893u, 957780895u, 2366199383u, 3846687839u, 2225031745u, 50628017u, 764720583u, 2251658783u, 1601491318u, 3836612294u, 3836982164u, 1834686310u, 4239983357u, 2677791106u, 718595268u), + SC(641418698u, 3008658673u, 1590313857u, 1025261614u, 1545641278u, 883067087u, 405447843u, 251932751u, 890679795u, 1380695500u, 4259157180u, 4219905082u, 665298826u, 4240175069u, 1720908833u, 2268480568u), + SC(1323007329u, 2757671761u, 531677728u, 1863777888u, 1512057206u, 2416428007u, 297355401u, 2843988168u, 3028483811u, 4269951770u, 844221740u, 1060678479u, 2913804270u, 3550002834u, 1490208797u, 2041637686u), + SC(4098631786u, 3088674341u, 2277647863u, 546429701u, 239595915u, 96051385u, 2043858235u, 356783975u, 3081379864u, 1495630942u, 1713035648u, 2797737429u, 4252005067u, 1174473008u, 182861961u, 1284115192u), + SC(1497340893u, 2990980382u, 435071738u, 25048206u, 1369038540u, 2388914024u, 3985375113u, 3187649864u, 1375850783u, 2762762203u, 3714513839u, 1546363407u, 2343675571u, 416152492u, 1797618344u, 3540898582u), + SC(2184924310u, 2347360549u, 640504537u, 1253044800u, 1440674061u, 1666425671u, 3827600864u, 2022304946u, 2918906490u, 263308814u, 3892002350u, 1942380643u, 1520343008u, 1245225248u, 3081248535u, 2098883649u), + SC(2377054091u, 3295547231u, 2240796492u, 1757295037u, 62158041u, 1809272299u, 4005194159u, 1592984938u, 366675588u, 3144502911u, 2973082795u, 4105706826u, 2851896979u, 3262002710u, 3082369242u, 634669574u), + SC(729159370u, 3948971047u, 1511320403u, 3061460707u, 3090283349u, 1868816562u, 3759558902u, 3868199437u, 2438888892u, 1660478281u, 2415784493u, 3546303863u, 3144683831u, 3066258755u, 2228021651u, 3294706852u) +} +}; +#undef SC +#endif diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/secp256k1_main.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/secp256k1_main.h new file mode 100644 index 000000000..ff54afffe --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/secp256k1_main.h @@ -0,0 +1,5 @@ +//! Project version number for secp256k1. +FOUNDATION_EXPORT double secp256k1VersionNumber; + +//! Project version string for secp256k1. +FOUNDATION_EXPORT const unsigned char secp256k1VersionString[]; diff --git a/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/util.h b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/util.h new file mode 100644 index 000000000..de2a002ba --- /dev/null +++ b/Example/Web3supportBrowser/Pods/secp256k1.c/secp256k1/util.h @@ -0,0 +1,119 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_UTIL_H +#define SECP256K1_UTIL_H + +#include "secp256k1-config.h" + +#include +#include +#include + +typedef struct { + void (*fn)(const char *text, void* data); + const void* data; +} secp256k1_callback; + +static SECP256K1_INLINE void secp256k1_callback_call(const secp256k1_callback * const cb, const char * const text) { + cb->fn(text, (void*)cb->data); +} + +#ifdef DETERMINISTIC +#define TEST_FAILURE(msg) do { \ + fprintf(stderr, "%s\n", msg); \ + abort(); \ +} while(0); +#else +#define TEST_FAILURE(msg) do { \ + fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, msg); \ + abort(); \ +} while(0) +#endif + +#ifdef HAVE_BUILTIN_EXPECT +#define EXPECT(x,c) __builtin_expect((x),(c)) +#else +#define EXPECT(x,c) (x) +#endif + +#ifdef DETERMINISTIC +#define CHECK(cond) do { \ + if (EXPECT(!(cond), 0)) { \ + TEST_FAILURE("test condition failed"); \ + } \ +} while(0) +#else +#define CHECK(cond) do { \ + if (EXPECT(!(cond), 0)) { \ + TEST_FAILURE("test condition failed: " #cond); \ + } \ +} while(0) +#endif + +/* Like assert(), but when VERIFY is defined, and side-effect safe. */ +#if defined(COVERAGE) +#define VERIFY_CHECK(check) +#define VERIFY_SETUP(stmt) +#elif defined(VERIFY) +#define VERIFY_CHECK CHECK +#define VERIFY_SETUP(stmt) do { stmt; } while(0) +#else +#define VERIFY_CHECK(cond) do { (void)(cond); } while(0) +#define VERIFY_SETUP(stmt) +#endif + +static SECP256K1_INLINE void *checked_malloc(const secp256k1_callback* cb, size_t size) { + void *ret = malloc(size); + if (ret == NULL) { + secp256k1_callback_call(cb, "Out of memory"); + } + return ret; +} + +static SECP256K1_INLINE void *checked_realloc(const secp256k1_callback* cb, void *ptr, size_t size) { + void *ret = realloc(ptr, size); + if (ret == NULL) { + secp256k1_callback_call(cb, "Out of memory"); + } + return ret; +} + +/* Macro for restrict, when available and not in a VERIFY build. */ +#if defined(SECP256K1_BUILD) && defined(VERIFY) +# define SECP256K1_RESTRICT +#else +# if (!defined(__STDC_VERSION__) || (__STDC_VERSION__ < 199901L) ) +# if SECP256K1_GNUC_PREREQ(3,0) +# define SECP256K1_RESTRICT __restrict__ +# elif (defined(_MSC_VER) && _MSC_VER >= 1400) +# define SECP256K1_RESTRICT __restrict +# else +# define SECP256K1_RESTRICT +# endif +# else +# define SECP256K1_RESTRICT restrict +# endif +#endif + +#if defined(_WIN32) +# define I64FORMAT "I64d" +# define I64uFORMAT "I64u" +#else +# define I64FORMAT "lld" +# define I64uFORMAT "llu" +#endif + +#if defined(HAVE___INT128) +# if defined(__GNUC__) +# define SECP256K1_GNUC_EXT __extension__ +# else +# define SECP256K1_GNUC_EXT +# endif +SECP256K1_GNUC_EXT typedef unsigned __int128 uint128_t; +#endif + +#endif /* SECP256K1_UTIL_H */ diff --git a/Example/Web3supportBrowser/Pods/web3swift/LICENSE.md b/Example/Web3supportBrowser/Pods/web3swift/LICENSE.md new file mode 100755 index 000000000..ed25277cc --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/LICENSE.md @@ -0,0 +1,203 @@ +Copyright (c) 2018 Aleksandr Vlasov, + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018 Aleksandr Vlasov + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Example/Web3supportBrowser/Pods/web3swift/README.md b/Example/Web3supportBrowser/Pods/web3swift/README.md new file mode 100755 index 000000000..7d5f30906 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/README.md @@ -0,0 +1,329 @@ +# web3swift +**web3swift** is an iOS toolbelt for interaction with the Ethereum network. + +![matter-github-swift](https://github.com/matter-labs/web3swift/blob/develop/web3swift-logo.png) +[![Build Status](https://travis-ci.com/matter-labs/web3swift.svg?branch=develop)](https://travis-ci.com/matter-labs/web3swift) +[![Swift](https://img.shields.io/badge/Swift-5.0-orange.svg?style=flat)](https://developer.apple.com/swift/) +[![Platform](https://img.shields.io/cocoapods/p/web3swift.svg?style=flat)](http://cocoapods.org/pods/web3.swift.pod) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/web3.swift.pod.svg?style=flat)](http://cocoapods.org/pods/web3.swift.pod) +[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![License](https://img.shields.io/cocoapods/l/web3swift.svg?style=flat)](http://cocoapods.org/pods/web3.swift.pod) +[![support](https://brianmacdonald.github.io/Ethonate/svg/eth-support-blue.svg)](https://brianmacdonald.github.io/Ethonate/address#0xe22b8979739d724343bd002f9f432f5990879901) +[![Stackoverflow](https://img.shields.io/badge/stackoverflow-ask-blue.svg)](https://stackoverflow.com/questions/tagged/web3swift) + +--- + + + + + +- [Core features](#core-features) +- [Installation](#installation) + - [Example usage](#example-usage) + - [Send Ether](#send-ether) + - [Send ERC-20 Token](#send-erc-20-token) + - [Write Transaction and call smart contract method](#write-transaction-and-call-smart-contract-method) + - [Web3View example](#web3view-example) + - [Build from source](#build-from-source) + - [Requirements](#requirements) + - [Migration Guides](#migration-guides) +- [Documentation](#documentation) +- [Projects that are using web3swift](#projects-that-are-using-web3swift) +- [Support](#support) +- [Contribute](#contribute) + - [Future steps](#future-steps) +- [Credits](#credits) +- [Security Disclosure](#security-disclosure) +- [License](#license) + + + +## 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] 🔐 Local **keystore management** (`geth` compatible) +- [x] 🤖 Smart-contract **ABI parsing** +- [x] 🔓**ABI deconding** (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] ⛩ **Infura support**, patial Websockets API support +- [x] ⚒ **Parsing TxPool** content into native values (ethereum addresses and transactions) - easy to get pending transactions +- [x] 🖇 **Event loops** functionality +- [x] 📱Supports Web3View functionality (WKWebView with **injected "web3" provider**) +- [x] 🕵️‍♂️ Possibility to **add or remove "middleware" that intercepts**, modifies and even **cancel transaction** workflow on stages "before assembly", "after assembly"and "before submission" +- [x] ✅**Literally following the standards** (BIP, EIP, etc): + + - [x] **[BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) (HD Wallets), [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) (Seed phrases), [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki) (Key generation prefixes)** +- [x] **[EIP-20](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md)** (Standart interface for tokens - ERC-20), **[EIP-67](https://github.com/ethereum/EIPs/issues/67)** (Standard URI scheme), **[EIP-155](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md)** (Replay attacks protection) + - [x] **And many others** *(For details about this EIP's look at [Documentation page](https://github.com/matter-labs/web3swift/blob/master/Documentation/))*: EIP-681, EIP-721, EIP-165, EIP-777, EIP-820, EIP-888, EIP-1400, EIP-1410, EIP-1594, EIP-1643, EIP-1644, EIP-1633, EIP-721, EIP-1155, EIP-1376, ST-20 + +- [x] 🗜 **Batched requests** in concurrent mode +- [x] **RLP encoding** +- [x] Base58 encoding scheme +- [x] Formatting to and from Ethereum Units +- [x] Comprehensive Unit and Integration Test Coverage + +## Installation + +- CocoaPods + +[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: + +```bash +$ sudo gem install cocoapods +``` + +To integrate web3swift into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '9.0' + +target '' do + use_frameworks! + pod 'web3swift' +end + +``` + + +Then, run the following command: + +```bash +$ pod install +``` + +- Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. + +You can install Carthage with [Homebrew](https://brew.sh/) using the following command: + +```bash +$ brew update +$ brew install carthage +``` + +To integrate web3swift into your Xcode project using Carthage, specify it in your `Cartfile`. +Create an empty Cartfile with the touch command and open it: + +```bash +$ touch Cartfile +$ open -a Xcode Cartfile +``` + +Add the following line to the Cartfile and save it: + +```ogdl +github "matter-labs/web3swift" "master" +``` + +Run `carthage update` to build the framework. By default, Carthage performs checkouts and creates a new directory 'Carthage' in the same location as your Cartfile. Open this directory, go to 'Build' directory, choose iOS or macOS directory, and use the selected directory framework in your Xcode project. + +- Swift Package +Open xcode setting and add this repo as a source + +### Example usage + + +##### Send Ether + +```swift +let value: String = "1.0" // In Ether +let walletAddress = EthereumAddress(wallet.address)! // Your wallet address +let toAddress = EthereumAddress(toAddressString)! +let contract = web3.contract(Web3.Utils.coldWalletABI, at: toAddress, abiVersion: 2)! +let amount = Web3.Utils.parseToBigUInt(value, units: .eth) +var options = TransactionOptions.defaultOptions +options.value = amount +options.from = walletAddress +options.gasPrice = .automatic +options.gasLimit = .automatic +let tx = contract.write( + "fallback", + parameters: [AnyObject](), + extraData: Data(), + transactionOptions: options)! +``` + +##### Send ERC-20 Token + +```swift +let web3 = Web3.InfuraMainnetWeb3() +let value: String = "1.0" // In Tokens +let walletAddress = EthereumAddress(wallet.address)! // Your wallet address +let toAddress = EthereumAddress(toAddressString)! +let erc20ContractAddress = EthereumAddress(token.address)! +let contract = web3.contract(Web3.Utils.erc20ABI, at: erc20ContractAddress, abiVersion: 2)! +let amount = Web3.Utils.parseToBigUInt(value, units: .eth) +var options = TransactionOptions.defaultOptions +options.value = amount +options.from = walletAddress +options.gasPrice = .automatic +options.gasLimit = .automatic +let method = "transfer" +let tx = contract.write( + method, + parameters: [toAddress, amount] as [AnyObject], + extraData: Data(), + transactionOptions: options)! +``` + + +##### Get account balance +```swift +let web3 = Web3.InfuraMainnetWeb3() +let address = EthereumAddress("
")! +let balance = try web3.eth.getBalance(address: address) +let balanceString = Web3.Utils.formatToEthereumUnits(balance, toUnits: .eth, decimals: 3) +``` + +##### Write Transaction and call smart contract method + +```swift +let web3 = Web3.InfuraMainnetWeb3() +let value: String = "0.0" // Any amount of Ether you need to send +let walletAddress = EthereumAddress(wallet.address)! // Your wallet address +let contractMethod = "SOMECONTRACTMETHOD" // Contract method you want to write +let contractABI = "..." // Contract ABI +let contractAddress = EthereumAddress(contractAddressString)! +let abiVersion = 2 // Contract ABI version +let parameters: [AnyObject] = [...]() // Parameters for contract method +let extraData: Data = Data() // Extra data for contract method +let contract = web3.contract(contractABI, at: contractAddress, abiVersion: abiVersion)! +let amount = Web3.Utils.parseToBigUInt(value, units: .eth) +var options = TransactionOptions.defaultOptions +options.value = amount +options.from = walletAddress +options.gasPrice = .automatic +options.gasLimit = .automatic +let tx = contract.write( + contractMethod, + parameters: parameters, + extraData: extraData, + transactionOptions: options)! +``` + +### Web3View example + +You can see how to our demo project: **WKWebView with injected "web3" provider**: + +``` bash +git clone https://github.com/matter-labs/web3swift.git +cd web3swift/Example/web3swiftBrowser +pod install +open ./web3swiftBrowser.xcworkspace +``` + +### Build from source + +- Clone repo +- Instal dependencies via `./carthage-build.sh --platform iOS` (temp workaround, foe of Carthage bug. [For details please look at](https://github.com/Carthage/Carthage/issues/3019#issuecomment-665136323) + +### Requirements + +- iOS 9.0+ / macOS 10.11+ +- Xcode 10.2+ +- Swift 5.0+ + +### Migration Guides + +- [web3swift 2.0 Migration Guide](https://github.com/matterinc/web3swift/blob/master/Documentation/web3swift%202.0%20Migration%20Guide.md) + +## Documentation + +For full documentation details and FAQ, please look at [Documentation](https://github.com/matter-labs/web3swift/blob/master/Documentation/) + +*If you need to find or understand an API, check [Usage.md](https://github.com/matter-labs/web3swift/blob/master/Documentation/Usage.md).* + + **FAQ moved [Documentation Page](https://github.com/matter-labs/web3swift/blob/master/Documentation/)** + +Here are quick references for essential features: + +- [Preffered models](https://github.com/matter-labs/web3swift/blob/master/Documentation/Usage.md#preffered-models) +- [Account Management (create, import, private keys managments, etc.)](https://github.com/matter-labs/web3swift/blob/master/Documentation/Usage.md#account-management) +- [Ethereum Endpoints interaction (web3, balance, tx's operations, chain state)](https://github.com/matter-labs/web3swift/blob/master/Documentation/Usage.md#ethereum-endpoints-interaction) +- [Websockets](https://github.com/matter-labs/web3swift/blob/master/Documentation/Usage.md#websockets) +- [ENS](https://github.com/matter-labs/web3swift/blob/master/Documentation/Usage.md#ens) + +## Projects that are using web3swift + +If you are using this library in your project, please [add a link](https://github.com/matter-labs/web3swift/edit/develop/README.md) to this repo. + +* [MyEtherWallet/MEWconnect-iOS](https://github.com/MyEtherWallet/MEWconnect-iOS) +* [Peepeth iOS client](https://github.com/matterinc/PeepethClient) +* [Ethereum & ERC20Tokens Wallet](https://itunes.apple.com/us/app/ethereum-erc20tokens-wallet/id1386738877?ls=1&mt=8) +* [Pay-iOS](https://github.com/BANKEX/Pay-iOS) +* [GeoChain](https://github.com/awallish/GeoChain) +* [NewHorizonLabs/TRX-Wallet](https://github.com/NewHorizonLabs/TRX-Wallet) +* [SteadyAction/EtherWalletKit](https://github.com/SteadyAction/EtherWalletKit) +* [UP Wallet/loopr-ios](https://github.com/Loopring/loopr-ios) +* [MyENS Wallet](https://github.com/barrasso/enswallet) +* [LoanStar](https://github.com/barrasso/loan-star) +* [AlphaWallet](https://github.com/AlphaWallet/alpha-wallet-ios) +* [Follow_iOS](https://github.com/FollowInc/Follow_iOS) +* [Biomedical Data Sharing dApp - Geolocation](https://github.com/HD2i/Geolocation-iOS) +* [Alice Wallet](https://github.com/alicedapp/AliceX) +* [web3-react-native](https://github.com/cawfree/web3-react-native) +* [YOUR APP CAN BE THERE (click me)](https://github.com/matter-labs/web3swift/edit/develop/README.md) :wink: + +*Nothing makes developers happier than seeing someone else use our work and go wild with it.* + +## Support + +- If you **need help**, [open an issue](https://github.com/matter-labs/web3swift/issues). +- If you'd like to **see web3swift best practices**, check [Projects that using web3swift](https://github.com/matter-labs/web3swift#projects-that-using-web3swift). +- If you **found a bug**, [open an issue](https://github.com/matter-labs/web3swift/issues). + + +## 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)!** + +- If you **have a feature request**, [open an issue](https://github.com/matter-labs/web3swift/issues). + +- If you **want to contribute**, read [contribution policy](https://github.com/matter-labs/web3swift/blob/master/Documentation/CONTRIBUTION_POLICY.md) & [submit a pull request](https://github.com/matter-labs/web3swift/pulls). + +If you use any of our libraries for work, see if your employers would be interested in donating. Any amount you can donate today to help us reach our goal would be much appreciated. + +[Matter Labs](https://github.com/orgs/matter-labs/people) are charged with open-sourсe and do not require money for using their web3swift lib. +We want to continue to do everything we can to move the needle forward. + +- **Support us** via [@gitcoin Grant program](https://gitcoin.co/grants/358/web3swift) +- Ether wallet address: `0x6A3738c6299f45c31697aceA647D49EdCC9C28A4` + + + +### Future steps + +You are more than welcome to participate! **Your contribution will be paid via [@gitcoin Grant program](https://gitcoin.co/grants/358/web3swift).** + +- [ ] **L2 support** (such as [ZkSync](https://zksync.io/)) + +- [ ] **Modularity** with the basic Web3 subspec/SPM (the most basic functions like transaction signing and interacting with an http rpc server) and other modules with additional functionality + +- [ ] Complete Documentation (https://web3swift.github.io/web3swift) + +- [ ] Performance Improvements + +- [ ] Convenient methods for namespaces + + + +## Credits + +- Alex Vlasov, [@shamatar](https://github.com/shamatar) +- Petr Korolev, [@skywinder](https://github.com/skywinder) +- Anton Grigorev, [@baldyash](https://github.com/BaldyAsh) + +## Security Disclosure + +If you believe you have identified a security vulnerability with web3swift, you should report it as soon as possible via email to [hello@matter-labs.io](mailto:hello@matter-labs.io). Please do not post it to a public issue tracker. + + +## License + +web3swift is available under the Apache License 2.0 license. See the [LICENSE](https://github.com/matter-labs/web3swift/blob/master/LICENSE) for details. diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Browser/Bridge.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Browser/Bridge.swift new file mode 100644 index 000000000..b31db12bf --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Browser/Bridge.swift @@ -0,0 +1,250 @@ +// +// Bridge.swift +// JSBridge +// +// Created by SunJiangting on 2017/5/27. +// Copyright © 2017 Samaritan. All rights reserved. +// + +import WebKit + +/// Bridge for WKWebView and JavaScript +open class Bridge: NSObject { + + static let name: String = "pacific" + + fileprivate static let callbackEventName = "PacificDidReceiveNativeCallback" + fileprivate static let postEventName = "PacificDidReceiveNativeBroadcast" + + fileprivate enum MessageKey { + static let action = "action" + static let parameters = "parameters" + static let callback = "callback" + static let printable = "print" + } + + public struct JSError { + public let code: Int + public let description: String + + public init(code: Int, description: String) { + self.code = code + self.description = description + } + } + + /// Used to callback to webpage whether a message from webpage was handled successful or encountered an error. + /// + /// - success: The result of message was successful + /// + /// - failure: Unable to handle the message, notify js with error by **Object Error** { code: Int, description: String} + /// + public enum Results { + + case success([String: Any]?) + + case failure(JSError) + } + + /// Bridge Callback to webpage + /// - Parameter results: Value pass to webpage + public typealias Callback = (_ results: Results) -> Void + + /// Closure when js send message to native + /// - Parameter parameters: js parameters + /// - Parameter callback: callback func + public typealias Handler = (_ parameters: [String: Any]?, _ callback: @escaping Callback) -> Void + + public typealias DefaultHandler = (_ name: String, _ parameters: [String: Any]?, _ callback: @escaping Callback) -> Void + + private(set) var handlers = [String: Handler]() + + public var defaultHandler: DefaultHandler? + + fileprivate let configuration: WKWebViewConfiguration + fileprivate weak var webView: WKWebView? + + /// Print message body from webpage automatically. + public var printScriptMessageAutomatically = false + + deinit { + configuration.removeObserver(self, forKeyPath: #keyPath(WKWebViewConfiguration.userContentController)) + configuration.userContentController.removeScriptMessageHandler(forName: Bridge.name) + } + + fileprivate init(webView: WKWebView) { + self.webView = webView + self.configuration = webView.configuration + super.init() + configuration.addObserver(self, forKeyPath: #keyPath(WKWebViewConfiguration.userContentController), options: [.new, .old], context: nil) + configuration.userContentController.add(self, name: Bridge.name) + } + + /// Register to handle action + /// - Parameter handler: closure when handle message from webpage + /// - parameter action: name of action + /// + /// - SeeAlso: `Handler` + /// + /// ```javascript + /// // Post Event With Action Name + /// window.bridge.post('print', {message: 'Hello, world'}) + /// // Post Event With Callback + /// window.bridge.post('print', {message: 'Hello, world'}, (parameters, error) => { Handler Parameters Or Error}) + /// ``` + public func register(_ handler: @escaping Handler, for action: String) { + handlers[action] = handler + } + + /// Unregister an action + /// - Parameters action: name of action + public func unregister(for action: String) { + handlers[action] = nil + } + + /// send action to webpage + /// - Parameter action: action listened by js `window.bridge.on(**action**, handler)` + /// - Parameter parameters: parameters pass to js + /// + /// ```javascript + /// // listen native login action + /// window.bridge.on('login', (parameters)=> {console.log('User Did Login')}) + /// ``` + public func post(action: String, parameters: [String: Any]?) { + guard let webView = webView else { return } + webView.st_dispatchBridgeEvent(Bridge.postEventName, parameters: ["name": action], results: .success(parameters), completionHandler: nil) + } + + /// Evaluates the given JavaScript string. + /// - Parameter javaScriptString: The JavaScript string to evaluate. + /// - Parameter completion: A block to invoke when script evaluation completes or fails. + public func evaluate(_ javaScriptString: String, completion: ((Any?, Error?) -> Void)? = nil) { + guard let webView = webView else { return } + webView.evaluateJavaScript(javaScriptString, completionHandler: completion) + } + + open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { + if let obj = object as? WKWebViewConfiguration, let kp = keyPath, obj == configuration && kp == #keyPath(WKWebViewConfiguration.userContentController) { + if let change = change { + if let oldContentController = change[.oldKey] as? WKUserContentController { + oldContentController.removeScriptMessageHandler(forName: Bridge.name) + } + if let newContentController = change[.newKey] as? WKUserContentController { + newContentController.add(self, name: Bridge.name) + } + } + } + } +} + +extension Bridge: WKScriptMessageHandler { + + /*! @abstract Invoked when a script message is received from a webpage. + @param userContentController The user content controller invoking the + delegate method. + @param message The script message received. + */ + public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { + guard let body = message.body as? [String: Any], let name = body[MessageKey.action] as? String else { + return + } + if (body[MessageKey.printable] as? NSNumber)?.boolValue ?? printScriptMessageAutomatically { + print(body) + } + guard let handler = handlers[name] else { + guard let defaultHandler = self.defaultHandler else { + return + } + if let callbackID = (body[MessageKey.callback] as? NSNumber) { + defaultHandler(name, body[MessageKey.parameters] as? [String: Any]) { [weak self] (results) in + guard let strongSelf = self else { + return + } + // Do Nothing + guard let webView = strongSelf.webView else { return } + webView.st_dispatchBridgeEvent(Bridge.callbackEventName, parameters: ["id": callbackID], results: results, completionHandler: nil) + } + } else { + defaultHandler(name, body[MessageKey.parameters] as? [String: Any]) { (results) in + // Do Nothing + } + } + return + } + + if let callbackID = (body[MessageKey.callback] as? NSNumber) { + handler(body[MessageKey.parameters] as? [String: Any]) { [weak self] (results) in + guard let strongSelf = self else { + return + } + // Do Nothing + guard let webView = strongSelf.webView else { return } + webView.st_dispatchBridgeEvent(Bridge.callbackEventName, parameters: ["id": callbackID], results: results, completionHandler: nil) + } + } else { + handler(body[MessageKey.parameters] as? [String: Any]) { (results) in + // Do Nothing + } + } + } +} + +public extension WKWebView { + + private struct STPrivateStatic { + fileprivate static var bridgeKey = "STPrivateStatic.bridgeKey" + } + + /// Bridge for WKWebView and JavaScript. Initialize `lazy` + var bridge: Bridge { + if let bridge = objc_getAssociatedObject(self, &STPrivateStatic.bridgeKey) as? Bridge { + return bridge + } + let bridge = Bridge(webView: self) + objc_setAssociatedObject(self, &STPrivateStatic.bridgeKey, bridge, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + return bridge + } + + /// Remove Bridge And Reset, All the handlers will be removed + func removeBridge() { + if let bridge = objc_getAssociatedObject(self, &STPrivateStatic.bridgeKey) as? Bridge { + let userContentController = bridge.configuration.userContentController + userContentController.removeScriptMessageHandler(forName: Bridge.name) + } + objc_setAssociatedObject(self, &STPrivateStatic.bridgeKey, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } +} + +fileprivate extension WKWebView { + + func st_dispatchBridgeEvent(_ eventName: String, + parameters: [String: Any], + results: Bridge.Results, + completionHandler: ((Any?, Error?) -> Void)? = nil) { + + var eventDetail: [String: Any] = parameters + switch results { + case .failure(let error): + eventDetail["error"] = ["code": error.code, "description": error.description] + case .success(let callbackParameters): + eventDetail["parameters"] = callbackParameters ?? [:] + } + let eventBody: [String: Any] = ["detail": eventDetail] + let jsString: String + if + let _data = try? JSONSerialization.data(withJSONObject: eventBody, options: JSONSerialization.WritingOptions()), + let eventString = String(data: _data, encoding: .utf8) { + + jsString = "(function() { var event = new CustomEvent('\(eventName)', \(eventString)); document.dispatchEvent(event)}());" + } else { + // When JSON Not Serializable, Invoke with Default Parameters + switch results { + case .success(_): + jsString = "(function() { var event = new CustomEvent('\(eventName)', {'detail': {'parameters': {}}}); document.dispatchEvent(event)}());" + case .failure(let error): + jsString = "(function() { var event = new CustomEvent('\(eventName)', {'detail': {'error': {'code': \(error.code), 'description': '\(error.description)'}}}); document.dispatchEvent(event)}());" + } + } + evaluateJavaScript(jsString, completionHandler: completionHandler) + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Browser/BrowserViewController.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Browser/BrowserViewController.swift new file mode 100644 index 000000000..90ea08d13 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Browser/BrowserViewController.swift @@ -0,0 +1,128 @@ +// +// BrowserViewController.swift +// web3swift +// +// Created by Anton Grigorev on 16.03.2020. +// Copyright © 2020 Matter Labs. All rights reserved. +// + +import WebKit + +open class BrowserViewController: UIViewController { + + public enum Method: String { + case getAccounts + case signTransaction + case signMessage + case signPersonalMessage + case publishTransaction + case approveTransaction + } + + public lazy var webView: WKWebView = { + let websiteDataTypes = NSSet(array: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache]) + let date = NSDate(timeIntervalSince1970: 0) + + WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes as! Set, modifiedSince: date as Date, completionHandler:{ }) + let webView = WKWebView( + frame: .zero, + configuration: self.config + ) + webView.allowsBackForwardNavigationGestures = true + webView.scrollView.isScrollEnabled = true + webView.navigationDelegate = self + webView.configuration.preferences.setValue(true, forKey: "developerExtrasEnabled") + return webView + }() + + lazy var config: WKWebViewConfiguration = { + let config = WKWebViewConfiguration() + + var js = "" + + if let filepath = Bundle.main.path(forResource: "browser.min", ofType: "js") { + do { + js += try String(contentsOfFile: filepath) + NSLog("Loaded browser.js") + } catch { + NSLog("Failed to load web.js") + } + } else { + NSLog("web3.js not found in bundle") + } + let userScript = WKUserScript(source: js, injectionTime: .atDocumentStart, forMainFrameOnly: false) + config.userContentController.addUserScript(userScript) + return config + }() + + public func registerBridges(for web3: web3) { + self.webView.bridge.register({ (parameters, completion) in + let url = web3.provider.url.absoluteString + completion(.success(["rpcURL": url as Any])) + }, for: "getRPCurl") + + self.webView.bridge.register({ (parameters, completion) in + let allAccounts = web3.browserFunctions.getAccounts() + completion(.success(["accounts": allAccounts as Any])) + }, for: "eth_getAccounts") + + self.webView.bridge.register({ (parameters, completion) in + let coinbase = web3.browserFunctions.getCoinbase() + completion(.success(["coinbase": coinbase as Any])) + }, for: "eth_coinbase") + + self.webView.bridge.register({ (parameters, completion) in + if parameters == nil { + completion(.failure(Bridge.JSError(code: 0, description: "No parameters provided"))) + return + } + let payload = parameters!["payload"] as? [String:Any] + if payload == nil { + completion(.failure(Bridge.JSError(code: 0, description: "No parameters provided"))) + return + } + let personalMessage = payload!["data"] as? String + let account = payload!["from"] as? String + if personalMessage == nil || account == nil { + completion(.failure(Bridge.JSError(code: 0, description: "Not enough parameters provided"))) + return + } + let result = web3.browserFunctions.personalSign(personalMessage!, account: account!) + if result == nil { + completion(.failure(Bridge.JSError(code: 0, description: "Account or data is invalid"))) + return + } + completion(.success(["signedMessage": result as Any])) + }, for: "eth_sign") + + self.webView.bridge.register({ (parameters, completion) in + if parameters == nil { + completion(.failure(Bridge.JSError(code: 0, description: "No parameters provided"))) + return + } + let transaction = parameters!["transaction"] as? [String:Any] + if transaction == nil { + completion(.failure(Bridge.JSError(code: 0, description: "Not enough parameters provided"))) + return + } + let result = web3.browserFunctions.signTransaction(transaction!) + if result == nil { + completion(.failure(Bridge.JSError(code: 0, description: "Data is invalid"))) + return + } + completion(.success(["signedTransaction": result as Any])) + }, for: "eth_signTransaction") + } +} + +extension BrowserViewController: WKNavigationDelegate { + public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { + + } +} + +extension BrowserViewController: WKScriptMessageHandler { + public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { + NSLog("message \(message.body)") + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Browser/browser.js b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Browser/browser.js new file mode 100644 index 000000000..6f7d8ea26 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Browser/browser.js @@ -0,0 +1,68351 @@ +// Web3Swift.js +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// +(function(){function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0) { + window.web3.eth.defaultAccount = accs[0]; + } + })); + } + window.ethereum = engine; + } + }); + }()); + + //# 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")`, + * typically on application load. + * + * If called with no arguments, will return registration in + * following priority: + * + * For Node.js: + * + * 1. Previous registration + * 2. global.Promise if node.js version >= 0.12 + * 3. Auto detected promise based on first sucessful require of + * known promise libraries. Note this is a last resort, as the + * loaded library is non-deterministic. node.js >= 0.12 will + * always use global.Promise over this priority list. + * 4. Throws error. + * + * For Browser: + * + * 1. Previous registration + * 2. window.Promise + * 3. Throws error. + * + * Options: + * + * Promise: Desired Promise constructor + * global: Boolean - Should the registration be cached in a global variable to + * allow cross dependency/bundle registration? (default true) + */ + module.exports = function(root, loadImplementation){ + return function register(implementation, opts){ + implementation = implementation || null + opts = opts || {} + // global registration unless explicitly {global: false} in options (default true) + var registerGlobal = opts.global !== false; + + // load any previous global registration + if(registered === null && registerGlobal){ + registered = root[REGISTRATION_KEY] || null + } + + if(registered !== null + && implementation !== null + && registered.implementation !== implementation){ + // Throw error if attempting to redefine implementation + throw new Error('any-promise already defined as "'+registered.implementation+ + '". You can only register an implementation before the first '+ + ' call to require("any-promise") and an implementation cannot be changed') + } + + if(registered === null){ + // use provided implementation + if(implementation !== null && typeof opts.Promise !== 'undefined'){ + registered = { + Promise: opts.Promise, + implementation: implementation + } + } else { + // require implementation if implementation is specified but not provided + registered = loadImplementation(implementation) + } + + if(registerGlobal){ + // register preference globally in case multiple installations + root[REGISTRATION_KEY] = registered + } + } + + return registered + } + } + + },{}],4:[function(require,module,exports){ + "use strict"; + module.exports = require('./loader')(window, loadImplementation) + + /** + * Browser specific loadImplementation. Always uses `window.Promise` + * + * To register a custom implementation, must register with `Promise` option. + */ + function loadImplementation(){ + if(typeof window.Promise === 'undefined'){ + throw new Error("any-promise browser requires a polyfill or explicit registration"+ + " e.g: require('any-promise/register/bluebird')") + } + return { + Promise: window.Promise, + implementation: 'window.Promise' + } + } + + },{"./loader":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 { + named = require('vm').runInThisContext( + '(function ' + this.name + '(entity) {\n' + + ' this._initNamed(entity);\n' + + '})' + ); + } catch (e) { + named = function (entity) { + this._initNamed(entity); + }; + } + inherits(named, base); + 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 + if (!this.decoders.hasOwnProperty(enc)) + 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 + if (!this.encoders.hasOwnProperty(enc)) + 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; + this.value = value.map(function(item) { + if (!(item instanceof EncoderBuffer)) + item = new EncoderBuffer(item, reporter); + this.length += item.length; + return item; + }, this); + } else if (typeof value === 'number') { + if (!(0 <= value && value <= 0xff)) + return reporter.error('non-byte EncoderBuffer value'); + this.value = value; + this.length = 1; + } else if (typeof value === 'string') { + this.value = value; + this.length = Buffer.byteLength(value); + } else if (Buffer.isBuffer(value)) { + this.value = value; + this.length = value.length; + } else { + return reporter.error('Unsupported type: ' + typeof value); + } + } + 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); + offset += item.length; + }); + } else { + if (typeof this.value === 'number') + out[offset] = this.value; + else if (typeof this.value === 'string') + out.write(this.value, offset); + else if (Buffer.isBuffer(this.value)) + 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', + 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', + '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; + state.reverseArgs = null; + state.choice = null; + state.optional = false; + state.any = false; + state.obj = false; + state.use = null; + state.useDecoder = null; + state.key = null; + state['default'] = null; + state.explicit = null; + state.implicit = null; + state.contains = null; + + // Should create new instance on each method + if (!state.parent) { + state.children = []; + this._wrap(); + } + } + 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 = {}; + stateProps.forEach(function(prop) { + cstate[prop] = state[prop]; + }); + var res = new this.constructor(cstate.parent); + res._baseState = cstate; + return res; + }; + + Node.prototype._wrap = function wrap() { + var state = this._baseState; + methods.forEach(function(method) { + this[method] = function _wrappedMethod() { + var clone = new this.constructor(this); + state.children.push(clone); + return clone[method].apply(clone, arguments); + }; + }, 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; + }, this); + 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; + }, this); + } + if (args.length !== 0) { + assert(state.args === null); + state.args = args; + 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)) + key |= 0; + var value = arg[key]; + res[value] = key; + }); + return res; + }); + } + }; + + // + // 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; + if (state.explicit !== null) + tag = state.explicit; + else if (state.implicit !== null) + tag = state.implicit; + else if (state.tag !== null) + tag = state.tag; + + if (tag === null && !state.any) { + // Trial and Error + var save = input.save(); + try { + if (state.choice === null) + this._decodeGeneric(state.tag, input, options); + else + this._decodeChoice(input, options); + present = true; + } catch (e) { + present = false; + } + 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) { + var explicit = this._decodeTag(input, state.explicit); + if (input.isError(explicit)) + return explicit; + input = explicit; + } + + var start = input.offset; + + // Unwrap implicit and normal values + if (state.use === null && state.choice === null) { + if (state.any) + var save = input.save(); + var body = this._decodeTag( + input, + state.implicit !== null ? state.implicit : state.tag, + state.any + ); + 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; + else if (state.choice === null) + 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) { + // NOTE: We are ignoring errors here, to let parser continue with other + // parts of encoded data + 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); + result = this._getUse(state.contains, input._reporterState.obj) + ._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') + return this._decodeList(input, tag, state.args[0], options); + else if (/str$/.test(tag)) + return this._decodeStr(input, tag, options); + else if (tag === 'objid' && state.args) + return this._decodeObjid(input, state.args[0], state.args[1], options); + else if (tag === 'objid') + return this._decodeObjid(input, null, null, options); + else if (tag === 'gentime' || tag === 'utctime') + return this._decodeTime(input, tag, options); + else if (tag === 'null_') + return this._decodeNull(input, options); + else if (tag === 'bool') + return this._decodeBool(input, options); + else if (tag === 'objDesc') + 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); + } else { + 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); + assert(state.useDecoder._baseState.parent === null); + state.useDecoder = state.useDecoder._baseState.children[0]; + if (state.implicit !== state.useDecoder._baseState.implicit) { + state.useDecoder = state.useDecoder.clone(); + state.useDecoder._baseState.implicit = state.implicit; + } + 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]; + try { + var value = node._decode(input, options); + if (input.isError(value)) + return false; + + result = { type: key, value: value }; + match = true; + } catch (e) { + input.restore(save); + return false; + } + 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) + data = state['default'] + else + return; + } + + // Encode children first + var content = null; + var primitive = false; + if (state.any) { + // Anything that was given is translated to buffer + result = this._createEncoderBuffer(data); + } else if (state.choice) { + result = this._encodeChoice(data, reporter); + } else if (state.contains) { + content = this._getUse(state.contains, parent)._encode(data, reporter); + primitive = true; + } else if (state.children) { + 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; + }); + content = this._createEncoderBuffer(content); + } else { + if (state.tag === 'seqof' || state.tag === 'setof') { + // 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) { + result = this._getUse(state.use, parent)._encode(data, reporter); + } else { + content = this._encodePrimitive(state.tag, data); + 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()'); + } else { + if (state.use === null) + 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( + false, + data.type + ' not found in ' + + JSON.stringify(Object.keys(state.choice))); + } + 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) + return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); + else if (tag === 'objid') + return this._encodeObjid(data, null, null); + else if (tag === 'gentime' || tag === 'utctime') + return this._encodeTime(data, tag); + else if (tag === 'null_') + return this._encodeNull(); + else if (tag === 'int' || tag === 'enum') + return this._encodeInt(data, state.args && state.reverseArgs[0]); + else if (tag === 'bool') + return this._encodeBool(data); + else if (tag === 'objDesc') + return this._encodeStr(data, tag); + 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, + path: [], + options: options || {}, + errors: [] + }; + } + 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; + } else { + err = new ReporterError(state.path.map(function(elem) { + 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 + throw new Error(this.message); + } catch (e) { + this.stack = e.stack; + } + } + return this; + }; + + },{"inherits":180}],11:[function(require,module,exports){ + var constants = require('../constants'); + + exports.tagClass = { + 0: 'universal', + 1: 'application', + 2: 'context', + 3: 'private' + }; + exports.tagClassByName = constants._reverse(exports.tagClass); + + exports.tag = { + 0x00: 'end', + 0x01: 'bool', + 0x02: 'int', + 0x03: 'bitstr', + 0x04: 'octstr', + 0x05: 'null_', + 0x06: 'objid', + 0x07: 'objDesc', + 0x08: 'external', + 0x09: 'real', + 0x0a: 'enum', + 0x0b: 'embed', + 0x0c: 'utf8str', + 0x0d: 'relativeOid', + 0x10: 'seq', + 0x11: 'set', + 0x12: 'numstr', + 0x13: 'printstr', + 0x14: 't61str', + 0x15: 'videostr', + 0x16: 'ia5str', + 0x17: 'utctime', + 0x18: 'gentime', + 0x19: 'graphstr', + 0x1a: 'iso646str', + 0x1b: 'genstr', + 0x1c: 'unistr', + 0x1d: 'charstr', + 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( + buffer, + '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); + if (buffer.isError(tag)) + return tag; + 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 = []; + while (!buffer.isEmpty()) { + 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; + result.push(res); + } + return result; + }; + + DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { + if (tag === 'bitstr') { + var unused = buffer.readUInt8(); + if (buffer.isError(unused)) + return unused; + return { unused: unused, data: buffer.raw() }; + } else if (tag === 'bmpstr') { + 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)); + } + return str; + } else if (tag === 'numstr') { + var numstr = buffer.raw().toString('ascii'); + if (!this._isNumstr(numstr)) { + return buffer.error('Decoding of string type: ' + + 'numstr unsupported characters'); + } + return numstr; + } else if (tag === 'octstr') { + return buffer.raw(); + } else if (tag === 'objDesc') { + return buffer.raw(); + } else if (tag === 'printstr') { + var printstr = buffer.raw().toString('ascii'); + if (!this._isPrintstr(printstr)) { + return buffer.error('Decoding of string type: ' + + 'printstr unsupported characters'); + } + return printstr; + } else if (/str$/.test(tag)) { + return buffer.raw().toString(); + } else { + return buffer.error('Decoding of string type: ' + tag + ' unsupported'); + } + }; + + DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { + var result; + var identifiers = []; + var ident = 0; + while (!buffer.isEmpty()) { + var subident = buffer.readUInt8(); + ident <<= 7; + ident |= subident & 0x7f; + if ((subident & 0x80) === 0) { + identifiers.push(ident); + ident = 0; + } + } + 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) + tmp = values[result.join('.')]; + if (tmp !== undefined) + result = tmp; + } + + return result; + }; + + DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { + var str = buffer.raw().toString(); + if (tag === 'gentime') { + var year = str.slice(0, 4) | 0; + var mon = str.slice(4, 6) | 0; + var day = str.slice(6, 8) | 0; + var hour = str.slice(8, 10) | 0; + var min = str.slice(10, 12) | 0; + var sec = str.slice(12, 14) | 0; + } else if (tag === 'utctime') { + var year = str.slice(0, 2) | 0; + var mon = str.slice(2, 4) | 0; + var day = str.slice(4, 6) | 0; + var hour = str.slice(6, 8) | 0; + var min = str.slice(8, 10) | 0; + var sec = str.slice(10, 12) | 0; + if (year < 70) + year = 2000 + year; + else + year = 1900 + year; + } 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)) + return res; + 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; + tag = 0; + while ((oct & 0x80) === 0x80) { + oct = buf.readUInt8(fail); + if (buf.isError(oct)) + return oct; + + tag <<= 7; + tag |= oct & 0x7f; + } + } else { + tag &= 0x1f; + } + var tagStr = der.tag[tag]; + + return { + cls: cls, + primitive: primitive, + tag: tag, + 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; + var j = buf.readUInt8(fail); + if (buf.isError(j)) + 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; + for (var i = 0; i < lines.length; i++) { + var match = lines[i].match(re); + if (match === null) + continue; + + if (match[2] !== label) + continue; + + if (start === -1) { + if (match[1] !== 'BEGIN') + break; + start = i; + } else { + if (match[1] !== 'END') + break; + end = i; + break; + } + } + 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); + header[0] = encodedTag; + 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 ]); + } else if (tag === 'bmpstr') { + var buf = new Buffer(str.length * 2); + for (var i = 0; i < str.length; i++) { + buf.writeUInt16BE(str.charCodeAt(i), i * 2); + } + return this._createEncoderBuffer(buf); + } else if (tag === 'numstr') { + if (!this._isNumstr(str)) { + return this.reporter.error('Encoding of string type: numstr supports ' + + 'only digits and space'); + } + return this._createEncoderBuffer(str); + } else if (tag === 'printstr') { + if (!this._isPrintstr(str)) { + return this.reporter.error('Encoding of string type: printstr supports ' + + 'only latin upper and lower case letters, ' + + 'digits, space, apostrophe, left and rigth ' + + 'parenthesis, plus sign, comma, hyphen, ' + + 'dot, slash, colon, equal sign, ' + + 'question mark'); + } + return this._createEncoderBuffer(str); + } else if (/str$/.test(tag)) { + return this._createEncoderBuffer(str); + } else if (tag === 'objDesc') { + return this._createEncoderBuffer(str); + } else { + return this.reporter.error('Encoding of string type: ' + tag + + ' unsupported'); + } + }; + + DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { + if (typeof id === 'string') { + if (!values) + return this.reporter.error('string objid given, but no values map found'); + if (!values.hasOwnProperty(id)) + return this.reporter.error('objid not found in values map'); + id = values[id].split(/[\s\.]+/g); + for (var i = 0; i < id.length; i++) + id[i] |= 0; + } else if (Array.isArray(id)) { + id = id.slice(); + 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++) { + var ident = id[i]; + 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--) { + var ident = id[i]; + objid[offset--] = ident & 0x7f; + 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()), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else if (tag === 'utctime') { + str = [ + two(date.getFullYear() % 100), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } 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) + return this.reporter.error('String int or enum given, but no values map'); + if (!values.hasOwnProperty(num)) { + return this.reporter.error('Values map doesn\'t contain: ' + + JSON.stringify(num)); + } + num = values[num]; + } + + // Bignum, assume big endian + if (typeof num !== 'number' && !Buffer.isBuffer(num)) { + var numArray = num.toArray(); + if (!num.sign && numArray[0] & 0x80) { + numArray.unshift(0); + } + 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; + num >>= 8; + } + 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) + out.push(p.slice(i, i + 64)); + 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. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + function compare(a, b) { + if (a === b) { + return 0; + } + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + + if (x < y) { + return -1; + } + if (y < x) { + return 1; + } + return 0; + } + function isBuffer(b) { + if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { + return global.Buffer.isBuffer(b); + } + return !!(b != null && b._isBuffer); + } + + // based on node assert, original notice: + + // http://wiki.commonjs.org/wiki/Unit_Testing/1.0 + // + // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! + // + // Originally from narwhal.js (http://narwhaljs.org) + // Copyright (c) 2009 Thomas Robinson <280north.com> + // + // Permission is hereby granted, free of charge, to any person obtaining a copy + // of this software and associated documentation files (the 'Software'), to + // deal in the Software without restriction, including without limitation the + // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + // sell copies of the Software, and to permit persons to whom the Software is + // furnished to do so, subject to the following conditions: + // + // The above copyright notice and this permission notice shall be included in + // all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + var util = require('util/'); + var hasOwn = Object.prototype.hasOwnProperty; + var pSlice = Array.prototype.slice; + var functionsHaveNames = (function () { + return function foo() {}.name === 'foo'; + }()); + function pToString (obj) { + return Object.prototype.toString.call(obj); + } + function isView(arrbuf) { + if (isBuffer(arrbuf)) { + return false; + } + if (typeof global.ArrayBuffer !== 'function') { + return false; + } + if (typeof ArrayBuffer.isView === 'function') { + return ArrayBuffer.isView(arrbuf); + } + if (!arrbuf) { + return false; + } + if (arrbuf instanceof DataView) { + return true; + } + if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { + return true; + } + return false; + } + // 1. The assert module provides functions that throw + // AssertionError's when particular conditions are not met. The + // assert module must conform to the following interface. + + var assert = module.exports = ok; + + // 2. The AssertionError is defined in assert. + // new assert.AssertionError({ message: message, + // actual: actual, + // expected: expected }) + + var regex = /\s*function\s+([^\(\s]*)\s*/; + // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js + function getName(func) { + if (!util.isFunction(func)) { + return; + } + if (functionsHaveNames) { + return func.name; + } + var str = func.toString(); + var match = str.match(regex); + return match && match[1]; + } + assert.AssertionError = function AssertionError(options) { + this.name = 'AssertionError'; + this.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator; + if (options.message) { + this.message = options.message; + this.generatedMessage = false; + } else { + this.message = getMessage(this); + this.generatedMessage = true; + } + var stackStartFunction = options.stackStartFunction || fail; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, stackStartFunction); + } else { + // non v8 browsers so we can have a stacktrace + var err = new Error(); + if (err.stack) { + var out = err.stack; + + // try to strip useless frames + var fn_name = getName(stackStartFunction); + var idx = out.indexOf('\n' + fn_name); + if (idx >= 0) { + // once we have located the function frame + // we need to strip out everything before it (and its line) + var next_line = out.indexOf('\n', idx + 1); + out = out.substring(next_line + 1); + } + + this.stack = out; + } + } + }; + + // assert.AssertionError instanceof Error + util.inherits(assert.AssertionError, Error); + + function truncate(s, n) { + if (typeof s === 'string') { + return s.length < n ? s : s.slice(0, n); + } else { + return s; + } + } + function inspect(something) { + if (functionsHaveNames || !util.isFunction(something)) { + return util.inspect(something); + } + var rawname = getName(something); + var name = rawname ? ': ' + rawname : ''; + return '[Function' + name + ']'; + } + function getMessage(self) { + return truncate(inspect(self.actual), 128) + ' ' + + self.operator + ' ' + + truncate(inspect(self.expected), 128); + } + + // At present only the three keys mentioned above are used and + // understood by the spec. Implementations or sub modules can pass + // other keys to the AssertionError's constructor - they will be + // ignored. + + // 3. All of the following functions must throw an AssertionError + // when a corresponding condition is not met, with a message that + // may be undefined if not provided. All assertion methods provide + // both the actual and expected values to the assertion error for + // display purposes. + + function fail(actual, expected, message, operator, stackStartFunction) { + throw new assert.AssertionError({ + message: message, + actual: actual, + expected: expected, + operator: operator, + stackStartFunction: stackStartFunction + }); + } + + // EXTENSION! allows for well behaved errors defined elsewhere. + assert.fail = fail; + + // 4. Pure assertion tests whether a value is truthy, as determined + // by !!guard. + // assert.ok(guard, message_opt); + // This statement is equivalent to assert.equal(true, !!guard, + // message_opt);. To test strictly for the value true, use + // assert.strictEqual(true, guard, message_opt);. + + function ok(value, message) { + if (!value) fail(value, true, message, '==', assert.ok); + } + assert.ok = ok; + + // 5. The equality assertion tests shallow, coercive equality with + // ==. + // assert.equal(actual, expected, message_opt); + + assert.equal = function equal(actual, expected, message) { + if (actual != expected) fail(actual, expected, message, '==', assert.equal); + }; + + // 6. The non-equality assertion tests for whether two objects are not equal + // with != assert.notEqual(actual, expected, message_opt); + + assert.notEqual = function notEqual(actual, expected, message) { + if (actual == expected) { + fail(actual, expected, message, '!=', assert.notEqual); + } + }; + + // 7. The equivalence assertion tests a deep equality relation. + // assert.deepEqual(actual, expected, message_opt); + + assert.deepEqual = function deepEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'deepEqual', assert.deepEqual); + } + }; + + assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); + } + }; + + function _deepEqual(actual, expected, strict, memos) { + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; + } else if (isBuffer(actual) && isBuffer(expected)) { + return compare(actual, expected) === 0; + + // 7.2. If the expected value is a Date object, the actual value is + // equivalent if it is also a Date object that refers to the same time. + } else if (util.isDate(actual) && util.isDate(expected)) { + return actual.getTime() === expected.getTime(); + + // 7.3 If the expected value is a RegExp object, the actual value is + // equivalent if it is also a RegExp object with the same source and + // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). + } else if (util.isRegExp(actual) && util.isRegExp(expected)) { + return actual.source === expected.source && + actual.global === expected.global && + actual.multiline === expected.multiline && + actual.lastIndex === expected.lastIndex && + actual.ignoreCase === expected.ignoreCase; + + // 7.4. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if ((actual === null || typeof actual !== 'object') && + (expected === null || typeof expected !== 'object')) { + return strict ? actual === expected : actual == expected; + + // If both values are instances of typed arrays, wrap their underlying + // ArrayBuffers in a Buffer each to increase performance + // This optimization requires the arrays to have the same type as checked by + // Object.prototype.toString (aka pToString). Never perform binary + // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their + // bit patterns are not identical. + } else if (isView(actual) && isView(expected) && + pToString(actual) === pToString(expected) && + !(actual instanceof Float32Array || + actual instanceof Float64Array)) { + return compare(new Uint8Array(actual.buffer), + new Uint8Array(expected.buffer)) === 0; + + // 7.5 For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else if (isBuffer(actual) !== isBuffer(expected)) { + return false; + } else { + memos = memos || {actual: [], expected: []}; + + var actualIndex = memos.actual.indexOf(actual); + if (actualIndex !== -1) { + if (actualIndex === memos.expected.indexOf(expected)) { + return true; + } + } + + memos.actual.push(actual); + memos.expected.push(expected); + + return objEquiv(actual, expected, strict, memos); + } + } + + function isArguments(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; + } + + function objEquiv(a, b, strict, actualVisitedObjects) { + if (a === null || a === undefined || b === null || b === undefined) + return false; + // if one is a primitive, the other must be same + if (util.isPrimitive(a) || util.isPrimitive(b)) + return a === b; + if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) + return false; + var aIsArgs = isArguments(a); + var bIsArgs = isArguments(b); + if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) + return false; + if (aIsArgs) { + a = pSlice.call(a); + b = pSlice.call(b); + return _deepEqual(a, b, strict); + } + var ka = objectKeys(a); + var kb = objectKeys(b); + var key, i; + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length !== kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] !== kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) + return false; + } + return true; + } + + // 8. The non-equivalence assertion tests for any deep inequality. + // assert.notDeepEqual(actual, expected, message_opt); + + assert.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); + } + }; + + assert.notDeepStrictEqual = notDeepStrictEqual; + function notDeepStrictEqual(actual, expected, message) { + if (_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); + } + } + + + // 9. The strict equality assertion tests strict equality, as determined by ===. + // assert.strictEqual(actual, expected, message_opt); + + assert.strictEqual = function strictEqual(actual, expected, message) { + if (actual !== expected) { + fail(actual, expected, message, '===', assert.strictEqual); + } + }; + + // 10. The strict non-equality assertion tests for strict inequality, as + // determined by !==. assert.notStrictEqual(actual, expected, message_opt); + + assert.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (actual === expected) { + fail(actual, expected, message, '!==', assert.notStrictEqual); + } + }; + + function expectedException(actual, expected) { + if (!actual || !expected) { + return false; + } + + if (Object.prototype.toString.call(expected) == '[object RegExp]') { + return expected.test(actual); + } + + try { + if (actual instanceof expected) { + return true; + } + } catch (e) { + // Ignore. The instanceof check doesn't work for arrow functions. + } + + if (Error.isPrototypeOf(expected)) { + return false; + } + + return expected.call({}, actual) === true; + } + + function _tryBlock(block) { + var error; + try { + block(); + } catch (e) { + error = e; + } + return error; + } + + function _throws(shouldThrow, block, expected, message) { + var actual; + + if (typeof block !== 'function') { + throw new TypeError('"block" argument must be a function'); + } + + if (typeof expected === 'string') { + message = expected; + expected = null; + } + + actual = _tryBlock(block); + + message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + + (message ? ' ' + message : '.'); + + if (shouldThrow && !actual) { + fail(actual, expected, 'Missing expected exception' + message); + } + + var userProvidedMessage = typeof message === 'string'; + var isUnwantedException = !shouldThrow && util.isError(actual); + var isUnexpectedException = !shouldThrow && actual && !expected; + + if ((isUnwantedException && + userProvidedMessage && + expectedException(actual, expected)) || + isUnexpectedException) { + fail(actual, expected, 'Got unwanted exception' + message); + } + + if ((shouldThrow && actual && expected && + !expectedException(actual, expected)) || (!shouldThrow && actual)) { + throw actual; + } + } + + // 11. Expected to throw an error: + // assert.throws(block, Error_opt, message_opt); + + assert.throws = function(block, /*optional*/error, /*optional*/message) { + _throws(true, block, error, message); + }; + + // EXTENSION! This is annoying to write outside this module. + assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { + _throws(false, block, error, message); + }; + + assert.ifError = function(err) { if (err) throw err; }; + + var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + if (hasOwn.call(obj, key)) keys.push(key); + } + return keys; + }; + + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + },{"util/":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, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ + function asyncify(func) { + return (0, _initialParams2.default)(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if ((0, _isObject2.default)(result) && typeof result.then === 'function') { + result.then(function (value) { + invokeCallback(callback, null, value); + }, function (err) { + invokeCallback(callback, err.message ? err : new Error(err)); + }); + } else { + callback(null, result); + } + }); + } + + function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (e) { + (0, _setImmediate2.default)(rethrow, e); + } + } + + function rethrow(error) { + throw error; + } + module.exports = exports['default']; + },{"./internal/initialParams":31,"./internal/setImmediate":37,"lodash/isObject":225}],21:[function(require,module,exports){ + (function (process,global){ + (function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + 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); + var newArr = Array(newLen); + for(var idx = 0; idx < newLen; idx++) { + newArr[idx] = arrayLike[start + idx]; + } + return newArr; + } + + /** + * Creates a continuation function with some arguments already applied. + * + * Useful as a shorthand when combined with other control flow functions. Any + * arguments passed to the returned function are added to the arguments + * originally passed to apply. + * + * @name apply + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {Function} fn - The function you want to eventually apply all + * arguments to. Invokes with (arguments...). + * @param {...*} arguments... - Any number of arguments to automatically apply + * when the continuation is called. + * @returns {Function} the partially-applied function + * @example + * + * // using apply + * async.parallel([ + * async.apply(fs.writeFile, 'testfile1', 'test1'), + * async.apply(fs.writeFile, 'testfile2', 'test2') + * ]); + * + * + * // the same process without using apply + * async.parallel([ + * function(callback) { + * fs.writeFile('testfile1', 'test1', callback); + * }, + * function(callback) { + * fs.writeFile('testfile2', 'test2', callback); + * } + * ]); + * + * // It's possible to pass any number of additional arguments when calling the + * // continuation: + * + * node> var fn = async.apply(sys.puts, 'one'); + * node> fn('two', 'three'); + * one + * two + * three + */ + var apply = function(fn/*, ...args*/) { + var args = slice(arguments, 1); + return function(/*callArgs*/) { + var callArgs = slice(arguments); + return fn.apply(null, args.concat(callArgs)); + }; + }; + + var initialParams = function (fn) { + return function (/*...args, callback*/) { + var args = slice(arguments); + var callback = args.pop(); + 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) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + 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); + defer(function () { + fn.apply(null, args); + }); + }; + } + + var _defer; + + if (hasSetImmediate) { + _defer = setImmediate; + } else if (hasNextTick) { + _defer = process.nextTick; + } 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, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ + function asyncify(func) { + return initialParams(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (isObject(result) && typeof result.then === 'function') { + result.then(function(value) { + invokeCallback(callback, null, value); + }, function(err) { + invokeCallback(callback, err.message ? err : new Error(err)); + }); + } else { + callback(null, result); + } + }); + } + + function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (e) { + 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); + var go = initialParams(function(args, callback) { + var that = this; + return eachfn(fns, function (fn, cb) { + wrapAsync(fn).apply(that, args.concat(cb)); + }, callback); + }); + if (args.length) { + return go.apply(this, args); + } + else { + return go; + } + }; + } + + /** 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. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ + 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) { + value[symToStringTag$1] = tag; + } else { + delete value[symToStringTag$1]; + } + } + 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`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + 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. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? 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. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + 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. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + 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 + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + 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`. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Util + * @example + * + * _.times(2, _.noop); + * // => [undefined, undefined] + */ + function noop() { + // No operation performed. + } + + function once(fn) { + return function () { + if (fn === null) return; + var callFn = fn; + fn = null; + 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. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + 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". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return value != null && typeof value == 'object'; + } + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]'; + + /** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + 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. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); + }; + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray; + + /** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ + 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. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => 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. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER$1 : length; + return !!length && + (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]'; + var boolTag = '[object Boolean]'; + var dateTag = '[object Date]'; + var errorTag = '[object Error]'; + var funcTag$1 = '[object Function]'; + var mapTag = '[object Map]'; + var numberTag = '[object Number]'; + var objectTag = '[object Object]'; + var regexpTag = '[object RegExp]'; + var setTag = '[object Set]'; + var stringTag = '[object String]'; + var weakMapTag = '[object WeakMap]'; + + var arrayBufferTag = '[object ArrayBuffer]'; + var dataViewTag = '[object DataView]'; + var float32Tag = '[object Float32Array]'; + var float64Tag = '[object Float64Array]'; + var int8Tag = '[object Int8Array]'; + var int16Tag = '[object Int16Array]'; + var int32Tag = '[object Int32Array]'; + var uint8Tag = '[object Uint8Array]'; + 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] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = + typedArrayTags[mapTag] = typedArrayTags[numberTag] = + typedArrayTags[objectTag] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = false; + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + } + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + 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. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => 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`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + 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 && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; + } + + /** Used for built-in method references. */ + var objectProto$5 = Object.prototype; + + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + 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. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + 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. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty$3.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; + } + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } + + function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? {value: coll[i], key: i} : null; + } + } + + function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) + return null; + i++; + return {value: item.value, key: i}; + } + } + + function createObjectIterator(obj) { + var okeys = keys(obj); + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + 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."); + var callFn = fn; + fn = null; + callFn.apply(this, arguments); + }; + } + + function _eachOfLimit(limit) { + return function (obj, iteratee, callback) { + callback = once(callback || noop); + if (limit <= 0 || !obj) { + return callback(null); + } + var nextElem = iterator(obj); + var done = false; + var running = 0; + + function iterateeCallback(err, value) { + running -= 1; + if (err) { + done = true; + callback(err); + } + else if (value === breakLoop || (done && running <= 0)) { + done = true; + return callback(null); + } + else { + replenish(); + } + } + + function replenish () { + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + 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. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + */ + 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); + var index = 0, + completed = 0, + length = coll.length; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err) { + callback(err); + } else if ((++completed === length) || value === breakLoop) { + 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. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @example + * + * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; + * var configs = {}; + * + * async.forEachOf(obj, function (value, key, callback) { + * fs.readFile(__dirname + value, "utf8", function (err, data) { + * if (err) return callback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * }, function (err) { + * if (err) console.error(err.message); + * // configs is now a map of JSON data + * doSomethingWith(configs); + * }); + */ + var eachOf = function(coll, iteratee, callback) { + 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) { + results[index] = v; + callback(err); + }); + }, function (err) { + 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` + * and a callback for when it has finished processing. Each of these callback + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @example + * + * async.map(['file1','file2','file3'], fs.stat, function(err, results) { + * // results is now an array of stats for each file + * }); + */ + 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 + * argument, `fns`, then it will return a function which lets you pass in the + * arguments as if it were a single function call. If more arguments are + * provided, `callback` is required while `args` is still optional. + * + * @name applyEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s + * to all call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {Function} - If only the first argument, `fns`, is provided, it will + * return a function which lets you pass in the arguments as if it were a single + * function call. The signature is `(..args, callback)`. If invoked with any + * arguments, `callback` is required. + * @example + * + * async.applyEach([enableSearch, updateSchema], 'bucket', callback); + * + * // partial application example: + * async.each( + * buckets, + * async.applyEach([enableSearch, updateSchema]), + * callback + * ); + */ + 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. + * + * @name mapLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * 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. + * + * @name mapSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * 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. + * + * @name applyEachSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.applyEach]{@link module:ControlFlow.applyEach} + * @category Control Flow + * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s to all + * call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {Function} - If only the first argument is provided, it will return + * a function which lets you pass in the arguments as if it were a single + * function call. + */ + var applyEachSeries = applyEach$1(mapSeries); + + /** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEach(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; + } + + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + /** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + + /** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } + + /** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + 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; + } + } + return -1; + } + + /** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ + function baseIsNaN(value) { + return value !== value; + } + + /** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + return value === value + ? 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 + * being completed first, and each function is run as soon as its requirements + * are satisfied. + * + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence + * will stop. Further tasks will not execute (so any other functions depending + * on it will not run), and the main `callback` is immediately called with the + * error. + * + * {@link AsyncFunction}s also receive an object containing the results of functions which + * have completed so far as the first argument, if they have dependencies. If a + * task function has no dependencies, it will only be passed a callback. + * + * @name auto + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Object} tasks - An object. Each of its properties is either a + * function or an array of requirements, with the {@link AsyncFunction} itself the last item + * in the array. The object's key of a property serves as the name of the task + * defined by that property, i.e. can be used when specifying requirements for + * other tasks. The function receives one or two arguments: + * * a `results` object, containing the results of the previously executed + * functions, only passed if the task has any dependencies, + * * a `callback(err, result)` function, which must be called when finished, + * passing an `error` (which can be `null`) and the result of the function's + * execution. + * @param {number} [concurrency=Infinity] - An optional `integer` for + * determining the maximum number of tasks that can be run in parallel. By + * default, as many as possible. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback. Results are always returned; however, if an + * error occurs, no further `tasks` will be performed, and the results object + * will only contain partial results. Invoked with (err, results). + * @returns undefined + * @example + * + * async.auto({ + * // this function will just be passed a callback + * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'), + * showData: ['readData', function(results, cb) { + * // results.readData is the file's contents + * // ... + * }] + * }, callback); + * + * async.auto({ + * get_data: function(callback) { + * console.log('in get_data'); + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * console.log('in make_folder'); + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * console.log('in write_file', JSON.stringify(results)); + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * console.log('in email_link', JSON.stringify(results)); + * // once the file is written let's email a link to it... + * // results.write_file contains the filename returned by write_file. + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }, function(err, results) { + * console.log('err = ', err); + * console.log('results = ', results); + * }); + */ + var auto = function (tasks, concurrency, callback) { + if (typeof concurrency === 'function') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = once(callback || noop); + var keys$$1 = keys(tasks); + var numTasks = keys$$1.length; + if (!numTasks) { + return callback(null); + } + 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 + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } + + var dependencies = task.slice(0, task.length - 1); + var remainingDependencies = dependencies.length; + if (remainingDependencies === 0) { + enqueueTask(key, task); + readyToCheck.push(key); + return; + } + uncheckedDependencies[key] = remainingDependencies; + + arrayEach(dependencies, function (dependencyName) { + if (!tasks[dependencyName]) { + throw new Error('async.auto task `' + key + + '` has a non-existent dependency `' + + dependencyName + '` in ' + + dependencies.join(', ')); + } + addListener(dependencyName, function () { + remainingDependencies--; + if (remainingDependencies === 0) { + enqueueTask(key, task); + } + }); + }); + }); + + checkForDeadlocks(); + processQueue(); + + function enqueueTask(key, task) { + readyTasks.push(function () { + runTask(key, task); + }); + } + + function processQueue() { + if (readyTasks.length === 0 && runningTasks === 0) { + return callback(null, results); + } + while(readyTasks.length && runningTasks < concurrency) { + 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) { + fn(); + }); + processQueue(); + } + + + function runTask(key, task) { + if (hasError) return; + + var taskCallback = onlyOnce(function(err, result) { + runningTasks--; + if (arguments.length > 2) { + result = slice(arguments, 1); + } + if (err) { + var safeResults = {}; + baseForOwn(results, function(val, rkey) { + safeResults[rkey] = val; + }); + 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) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } + } + + function checkForDeadlocks() { + // Kahn's algorithm + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html + var currentTask; + var counter = 0; + while (readyToCheck.length) { + currentTask = readyToCheck.pop(); + counter++; + arrayEach(getDependents(currentTask), function (dependent) { + if (--uncheckedDependencies[dependent] === 0) { + readyToCheck.push(dependent); + } + }); + } + + 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) { + if (isArray(task) && baseIndexOf(task, taskName, 0) >= 0) { + result.push(key); + } + }); + return result; + } + }; + + /** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function arrayMap(array, iteratee) { + 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. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ + function isSymbol(value) { + 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. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ + function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap(value, baseToString) + ''; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + 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. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ + function castSlice(array, start, end) { + var length = array.length; + 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. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the last unmatched string symbol. + */ + 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. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the first unmatched string symbol. + */ + 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. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function asciiToArray(string) { + return string.split(''); + } + + /** Used to compose unicode character classes. */ + var rsAstralRange = '\\ud800-\\udfff'; + var rsComboMarksRange = '\\u0300-\\u036f'; + var reComboHalfMarksRange = '\\ufe20-\\ufe2f'; + 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. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ + function hasUnicode(string) { + return reHasUnicode.test(string); + } + + /** Used to compose unicode character classes. */ + var rsAstralRange$1 = '\\ud800-\\udfff'; + var rsComboMarksRange$1 = '\\u0300-\\u036f'; + var reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f'; + 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 + ']'; + var rsFitz = '\\ud83c[\\udffb-\\udfff]'; + var rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')'; + var rsNonAstral = '[^' + rsAstralRange$1 + ']'; + 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. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function unicodeToArray(string) { + return string.match(reUnicode) || []; + } + + /** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function stringToArray(string) { + return hasUnicode(string) + ? 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. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + 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`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to trim. + * @param {string} [chars=whitespace] The characters to trim. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the trimmed string. + * @example + * + * _.trim(' abc '); + * // => 'abc' + * + * _.trim('-_-abc-_-', '_-'); + * // => 'abc' + * + * _.map([' foo ', ' bar '], _.trim); + * // => ['foo', 'bar'] + */ + function trim(string, chars, guard) { + string = toString(string); + if (string && (guard || chars === undefined)) { + return string.replace(reTrim, ''); + } + if (!string || !(chars = baseToString(chars))) { + return string; + } + var strSymbols = stringToArray(string), + 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(' ', ''); + func = func ? func.split(FN_ARG_SPLIT) : []; + func = func.map(function (arg){ + return trim(arg.replace(FN_ARG, '')); + }); + 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 + * parameter, with the parameter names matching the names of the tasks it + * depends on. This can provide even more readable task graphs which can be + * easier to maintain. + * + * If a final callback is specified, the task results are similarly injected, + * specified as named parameters after the initial error parameter. + * + * The autoInject function is purely syntactic sugar and its semantics are + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. + * + * @name autoInject + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.auto]{@link module:ControlFlow.auto} + * @category Control Flow + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of + * the form 'func([dependencies...], callback). The object's key of a property + * serves as the name of the task defined by that property, i.e. can be used + * when specifying requirements for other tasks. + * * The `callback` parameter is a `callback(err, result)` which must be called + * when finished, passing an `error` (which can be `null`) and the result of + * the function's execution. The remaining parameters name other tasks on + * which the task is dependent, and the results from those tasks are the + * arguments of those parameters. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback, and a `results` object with any completed + * task results, similar to `auto`. + * @example + * + * // The example from `auto` can be rewritten as follows: + * async.autoInject({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: function(get_data, make_folder, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }, + * email_link: function(write_file, callback) { + * // once the file is written let's email a link to it... + * // write_file contains the filename returned by write_file. + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * } + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + * + * // If you are using a JS minifier that mangles parameter names, `autoInject` + * // will not work with plain functions, since the parameter names will be + * // collapsed to a single letter identifier. To work around this, you can + * // explicitly specify the names of the parameters your task function needs + * // in an array, similar to Angular.js dependency injection. + * + * // This still has an advantage over plain `auto`, since the results a task + * // depends on are still spread into arguments. + * async.autoInject({ + * //... + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(write_file, callback) { + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * }] + * //... + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + */ + 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 + newTasks[key] = taskFn; + } else { + params = parseParams(taskFn); + 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]; + }); + newArgs.push(taskCb); + 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 + // for queue support. + function DLL() { + 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; + if (node.next) node.next.prev = newNode; + else this.tail = newNode; + node.next = newNode; + this.length += 1; + }; + + DLL.prototype.insertBefore = function(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode; + else this.head = newNode; + 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; + for(var idx = 0; idx < this.length; idx++) { + arr[idx] = curr.data; + curr = curr.next; + } + return arr; + }; + + DLL.prototype.remove = function (testFn) { + var curr = this.head; + while(!!curr) { + var next = curr.next; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; + }; + + function queue(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } + 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') { + throw new Error('task callback must be a function'); + } + q.started = true; + if (!isArray(data)) { + data = [data]; + } + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + return setImmediate$1(function() { + 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() { + processingScheduled = false; + q.process(); + }); + } + } + + 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(), + concurrency: concurrency, + payload: payload, + saturated: noop, + unsaturated:noop, + buffer: concurrency / 4, + empty: noop, + drain: noop, + error: noop, + started: false, + paused: false, + push: function (data, callback) { + _insert(data, false, callback); + }, + kill: function () { + q.drain = noop; + q._tasks.empty(); + }, + unshift: function (data, callback) { + _insert(data, true, callback); + }, + remove: function (testFn) { + q._tasks.remove(testFn); + }, + process: function () { + // Avoid trying to start too many processing operations. This can occur + // when callbacks resolve synchronously (#1267). + if (isProcessing) { + return; + } + isProcessing = true; + while(!q.paused && numRunning < q.concurrency && q._tasks.length){ + var tasks = [], data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); + tasks.push(node); + 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); + } + isProcessing = false; + }, + length: function () { + return q._tasks.length; + }, + running: function () { + return numRunning; + }, + workersList: function () { + return workersList; + }, + idle: function() { + return q._tasks.length + numRunning === 0; + }, + pause: function () { + q.paused = true; + }, + resume: function () { + if (q.paused === false) { return; } + q.paused = false; + setImmediate$1(q.process); + } + }; + 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}. + * @typedef {Object} CargoObject + * @memberOf module:ControlFlow + * @property {Function} length - A function returning the number of items + * waiting to be processed. Invoke like `cargo.length()`. + * @property {number} payload - An `integer` for determining how many tasks + * should be process per round. This property can be changed after a `cargo` is + * created to alter the payload on-the-fly. + * @property {Function} push - Adds `task` to the `queue`. The callback is + * called once the `worker` has finished processing the task. Instead of a + * single task, an array of `tasks` can be submitted. The respective callback is + * used for every task in the list. Invoke like `cargo.push(task, [callback])`. + * @property {Function} saturated - A callback that is called when the + * `queue.length()` hits the concurrency and further tasks will be queued. + * @property {Function} empty - A callback that is called when the last item + * from the `queue` is given to a `worker`. + * @property {Function} drain - A callback that is called when the last item + * from the `queue` has returned from the `worker`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke like `cargo.idle()`. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke like `cargo.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke like `cargo.resume()`. + * @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 + * `worker` is in progress, the task is queued until it becomes available. Once + * the `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, cargo passes an array of tasks to a single worker, repeating + * when the worker is finished. + * + * @name cargo + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.CargoObject} A cargo object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargo and inner queue. + * @example + * + * // create a cargo object with payload 2 + * var cargo = async.cargo(function(tasks, callback) { + * for (var i=0; i true + */ + function identity(value) { + return value; + } + + function _createTester(check, getResult) { + return function(eachfn, arr, iteratee, cb) { + cb = cb || noop; + var testPassed = false; + var testResult; + eachfn(arr, function(value, _, callback) { + iteratee(value, function(err, result) { + if (err) { + callback(err); + } else if (check(result) && !testResult) { + testPassed = true; + testResult = getResult(true, value); + callback(null, breakLoop); + } else { + callback(); + } + }); + }, function(err) { + if (err) { + cb(err); + } else { + cb(null, testPassed ? testResult : getResult(false)); + } + }); + }; + } + + 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}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @example + * + * async.detect(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // result now equals the first file in the list that exists + * }); + */ + 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. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (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. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + */ + var detectSeries = doLimit(detectLimit, 1); + + function consoleFunc(name) { + return function (fn/*, ...args*/) { + var args = slice(arguments, 1); + args.push(function (err/*, ...args*/) { + var args = slice(arguments, 1); + if (typeof console === 'object') { + if (err) { + if (console.error) { + console.error(err); + } + } else if (console[name]) { + arrayEach(args, function (x) { + console[name](x); + }); + } + } + }); + 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. + * Only works in Node.js or in browsers that support `console.dir` and + * `console.error` (such as FF and Chrome). + * If multiple arguments are returned from the async function, + * `console.dir` is called on each argument in order. + * + * @name dir + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, {hello: name}); + * }, 1000); + * }; + * + * // in the node repl + * node> async.dir(hello, 'world'); + * {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. + * + * Also a version of [`doWhilst`]{@link module:ControlFlow.doWhilst} with asynchronous `test` function. + * @name doDuring + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.during]{@link module:ControlFlow.during} + * @category Control Flow + * @param {AsyncFunction} fn - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `fn`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `fn`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `fn` has stopped. `callback` + * will be passed an error if one occurred, otherwise `null`. + */ + function doDuring(fn, test, callback) { + 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. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {Function} test - synchronous truth test to perform after each + * execution of `iteratee`. Invoked with any non-error callback results of + * `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + */ + function doWhilst(iteratee, test, callback) { + callback = onlyOnce(callback || noop); + var _iteratee = wrapAsync(iteratee); + var next = function(err/*, ...args*/) { + if (err) return callback(err); + var args = slice(arguments, 1); + if (test.apply(this, args)) return _iteratee(next); + callback.apply(null, [null].concat(args)); + }; + _iteratee(next); + } + + /** + * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the + * argument ordering differs from `until`. + * + * @name doUntil + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} test - synchronous truth test to perform after each + * execution of `iteratee`. Invoked with any non-error callback results of + * `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + */ + function doUntil(iteratee, test, callback) { + doWhilst(iteratee, function() { + 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 + * passed to `test` or `fn`, the main callback is immediately called with the + * value of the error. + * + * @name during + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `fn`. Invoked with (callback). + * @param {AsyncFunction} fn - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `fn` has stopped. `callback` + * will be passed an error, if one occurred, otherwise `null`. + * @example + * + * var count = 0; + * + * async.during( + * function (callback) { + * return callback(null, count < 5); + * }, + * function (callback) { + * count++; + * setTimeout(callback, 1000); + * }, + * function (err) { + * // 5 seconds have passed + * } + * ); + */ + function during(test, fn, callback) { + 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 + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @example + * + * // assuming openFiles is an array of file names and saveFile is a function + * // to save the modified contents of that file: + * + * async.each(openFiles, saveFile, function(err){ + * // if any of the saves produced an error, err would equal that error + * }); + * + * // assuming openFiles is an array of file names + * async.each(openFiles, function(file, callback) { + * + * // Perform operation on file here. + * console.log('Processing file ' + file); + * + * if( file.length > 32 ) { + * console.log('This file name is too long'); + * callback('File name too long'); + * } else { + * // Do work to process file here + * console.log('File processed'); + * callback(); + * } + * }, function(err) { + * // if any of the file processing produced an error, err would equal that error + * if( err ) { + * // One of the iterations produced an error. + * // All processing will now stop. + * console.log('A file failed to process'); + * } else { + * console.log('All files have been processed successfully'); + * } + * }); + */ + 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. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + */ + 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. + * + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `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, + * no extra deferral is added. This is useful for preventing stack overflows + * (`RangeError: Maximum call stack size exceeded`) and generally keeping + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + * contained. ES2017 `async` functions are returned as-is -- they are immune + * to Zalgo's corrupting influences, as they always resolve on a later tick. + * + * @name ensureAsync + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - an async function, one that expects a node-style + * callback as its last argument. + * @returns {AsyncFunction} Returns a wrapped function with the exact same call + * signature as the function passed in. + * @example + * + * function sometimesAsync(arg, callback) { + * if (cache[arg]) { + * return callback(null, cache[arg]); // this would be synchronous!! + * } else { + * doSomeIO(arg, callback); // this IO would be asynchronous + * } + * } + * + * // this has a risk of stack overflows if many results are cached in a row + * async.mapSeries(args, sometimesAsync, done); + * + * // this will defer sometimesAsync's callback if necessary, + * // preventing stack overflows + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + */ + function ensureAsync(fn) { + if (isAsync(fn)) return fn; + return initialParams(function (args, callback) { + var sync = true; + args.push(function () { + var innerArgs = arguments; + if (sync) { + setImmediate$1(function () { + callback.apply(null, innerArgs); + }); + } else { + callback.apply(null, innerArgs); + } + }); + fn.apply(this, args); + 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. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @example + * + * async.every(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then every file exists + * }); + */ + 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. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * 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. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * 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. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + function filterArray(eachfn, arr, iteratee, callback) { + var truthValues = new Array(arr.length); + eachfn(arr, function (x, index, callback) { + iteratee(x, function (err, v) { + truthValues[index] = !!v; + callback(err); + }); + }, function (err) { + if (err) return callback(err); + var results = []; + for (var i = 0; i < arr.length; i++) { + if (truthValues[i]) results.push(arr[i]); + } + callback(null, results); + }); + } + + function filterGeneric(eachfn, coll, iteratee, callback) { + var results = []; + eachfn(coll, function (x, index, callback) { + iteratee(x, function (err, v) { + if (err) { + callback(err); + } else { + if (v) { + results.push({index: index, value: x}); + } + callback(); + } + }); + }, function (err) { + if (err) { + callback(err); + } else { + callback(null, arrayMap(results.sort(function (a, b) { + return a.index - b.index; + }), baseProperty('value'))); + } + }); + } + + 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 + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @example + * + * async.filter(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of the existing files + * }); + */ + var filter = doParallel(_filter); + + /** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `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. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `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. + * + * @name forever + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} fn - an async function to call repeatedly. + * Invoked with (next). + * @param {Function} [errback] - when `fn` passes an error to it's callback, + * this function will be called, and execution stops. Invoked with (err). + * @example + * + * async.forever( + * function(next) { + * // next is suitable for passing to things that need a callback(err [, whatever]); + * // it will result in this function being called again. + * }, + * function(err) { + * // if next is called with a value in its first parameter, it will appear + * // in here as 'err', and execution will stop. + * } + * ); + */ + 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. + * + * @name groupByLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + */ + var groupByLimit = function(coll, limit, iteratee, callback) { + callback = callback || noop; + var _iteratee = wrapAsync(iteratee); + mapLimit(coll, limit, function(val, callback) { + _iteratee(val, function(err, key) { + if (err) return callback(err); + return callback(null, {key: key, val: val}); + }); + }, function(err, mapResults) { + 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 { + result[key] = [val]; + } + } + } + + 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 + * correspond to the values passed to the `iteratee` callback. + * + * Note: Since this function applies the `iteratee` to each item in parallel, + * there is no guarantee that the `iteratee` functions will complete in order. + * However, the values for each key in the `result` will be in the same order as + * the original `coll`. For Objects, the values will roughly be in the order of + * the original Objects' keys (but this can vary across JavaScript engines). + * + * @name groupBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @example + * + * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) { + * db.findById(userId, function(err, user) { + * if (err) return callback(err); + * return callback(null, user.age); + * }); + * }, function(err, result) { + * // result is object containing the userIds grouped by age + * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']}; + * }); + */ + var groupBy = doLimit(groupByLimit, Infinity); + + /** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. + * + * @name groupBySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * 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 + * as FF and Chrome). If multiple arguments are returned from the async + * function, `console.log` is called on each argument in order. + * + * @name log + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, 'hello ' + name); + * }, 1000); + * }; + * + * // in the node repl + * node> async.log(hello, 'world'); + * '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. + * + * @name mapValuesLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + */ + function mapValuesLimit(obj, limit, iteratee, callback) { + callback = once(callback || noop); + var newObj = {}; + var _iteratee = wrapAsync(iteratee); + eachOfLimit(obj, limit, function(val, key, next) { + _iteratee(val, key, function (err, result) { + if (err) return next(err); + newObj[key] = result; + next(); + }); + }, function (err) { + callback(err, newObj); + }); + } + + /** + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. + * + * Produces a new Object by mapping each value of `obj` through the `iteratee` + * function. The `iteratee` is called each `value` and `key` from `obj` and a + * callback for when it has finished processing. Each of these callbacks takes + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` + * passes an error to its callback, the main `callback` (for the `mapValues` + * function) is immediately called with the error. + * + * Note, the order of the keys in the result is not guaranteed. The keys will + * be roughly in the order they complete, (but this is very engine-specific) + * + * @name mapValues + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @example + * + * async.mapValues({ + * f1: 'file1', + * f2: 'file2', + * f3: 'file3' + * }, function (file, key, callback) { + * fs.stat(file, callback); + * }, function(err, result) { + * // result is now a map of stats for each file, e.g. + * // { + * // f1: [stats for file1], + * // f2: [stats for file2], + * // f3: [stats for file3] + * // } + * }); + */ + + var mapValues = doLimit(mapValuesLimit, Infinity); + + /** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. + * + * @name mapValuesSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * 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 + * optional hash function can be used. + * + * If no hash function is specified, the first argument is used as a hash key, + * which may work reasonably if it is a string or a data type that converts to a + * distinct string. Note that objects and arrays will not behave reasonably. + * Neither will cases where the other arguments are significant. In such cases, + * specify your own hash function. + * + * The cache of results is exposed as the `memo` property of the function + * returned by `memoize`. + * + * @name memoize + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function to proxy and cache results from. + * @param {Function} hasher - An optional function for generating a custom hash + * for storing results. It has all the arguments applied to it apart from the + * callback, and must be synchronous. + * @returns {AsyncFunction} a memoized version of `fn` + * @example + * + * var slow_fn = function(name, callback) { + * // do something + * callback(null, result); + * }; + * var fn = async.memoize(slow_fn); + * + * // fn can now be used as if it were slow_fn + * fn('some name', function() { + * // callback + * }); + */ + function memoize(fn, hasher) { + var memo = Object.create(null); + var queues = Object.create(null); + hasher = hasher || identity; + var _fn = wrapAsync(fn); + var memoized = initialParams(function memoized(args, callback) { + var key = hasher.apply(null, args); + if (has(memo, key)) { + setImmediate$1(function() { + callback.apply(null, memo[key]); + }); + } else if (has(queues, key)) { + queues[key].push(callback); + } else { + queues[key] = [callback]; + _fn.apply(null, args.concat(function(/*args*/) { + var args = slice(arguments); + memo[key] = args; + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i].apply(null, args); + } + })); + } + }); + memoized.memo = memo; + 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 + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name nextTick + * @static + * @memberOf module:Utils + * @method + * @see [async.setImmediate]{@link module:Utils.setImmediate} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ + var _defer$1; + + if (hasNextTick) { + _defer$1 = process.nextTick; + } else if (hasSetImmediate) { + _defer$1 = setImmediate; + } 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) { + result = slice(arguments, 1); + } + results[key] = result; + callback(err); + }); + }, function (err) { + 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 + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * + * @example + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // optional callback + * function(err, results) { + * // the results array will equal ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equals to: {one: 1, two: 2} + * }); + */ + 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. + * + * @name parallelLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.parallel]{@link module:ControlFlow.parallel} + * @category Control Flow + * @param {Array|Iterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + */ + function parallelLimit$1(tasks, limit, callback) { + _parallel(_eachOfLimit(limit), tasks, callback); + } + + /** + * A queue of tasks for the worker function to complete. + * @typedef {Object} QueueObject + * @memberOf module:ControlFlow + * @property {Function} length - a function returning the number of items + * waiting to be processed. Invoke with `queue.length()`. + * @property {boolean} started - a boolean indicating whether or not any + * items have been pushed and processed by the queue. + * @property {Function} running - a function returning the number of items + * currently being processed. Invoke with `queue.running()`. + * @property {Function} workersList - a function returning the array of items + * currently being processed. Invoke with `queue.workersList()`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke with `queue.idle()`. + * @property {number} concurrency - an integer for determining how many `worker` + * functions should be run in parallel. This property can be changed after a + * `queue` is created to alter the concurrency on-the-fly. + * @property {Function} push - add a new task to the `queue`. Calls `callback` + * once the `worker` has finished processing the task. Instead of a single task, + * a `tasks` array can be submitted. The respective callback is used for every + * task in the list. Invoke with `queue.push(task, [callback])`, + * @property {Function} unshift - add a new task to the front of the `queue`. + * Invoke with `queue.unshift(task, [callback])`. + * @property {Function} remove - remove items from the queue that match a test + * function. The test function will be passed an object with a `data` property, + * and a `priority` property, if this is a + * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. + * Invoked with `queue.remove(testFn)`, where `testFn` is of the form + * `function ({data, priority}) {}` and returns a Boolean. + * @property {Function} saturated - a callback that is called when the number of + * running workers hits the `concurrency` limit, and further tasks will be + * queued. + * @property {Function} unsaturated - a callback that is called when the number + * of running workers is less than the `concurrency` & `buffer` limits, and + * further tasks will not be queued. + * @property {number} buffer - A minimum threshold buffer in order to say that + * the `queue` is `unsaturated`. + * @property {Function} empty - a callback that is called when the last item + * from the `queue` is given to a `worker`. + * @property {Function} drain - a callback that is called when the last item + * from the `queue` has returned from the `worker`. + * @property {Function} error - a callback that is called when a task errors. + * Has the signature `function(error, task)`. + * @property {boolean} paused - a boolean for determining whether the queue is + * in a paused state. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke with `queue.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke with `queue.resume()`. + * @property {Function} kill - a function that removes the `drain` callback and + * 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 + * `worker`s are in progress, the task is queued until one becomes available. + * Once a `worker` completes a `task`, that `task`'s callback is called. + * + * @name queue + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. Invoked with (task, callback). + * @param {number} [concurrency=1] - An `integer` for determining how many + * `worker` functions should be run in parallel. If omitted, the concurrency + * defaults to `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the queue. + * @example + * + * // create a queue object with concurrency 2 + * var q = async.queue(function(task, callback) { + * console.log('hello ' + task.name); + * callback(); + * }, 2); + * + * // assign a callback + * q.drain = function() { + * console.log('all items have been processed'); + * }; + * + * // add some items to the queue + * q.push({name: 'foo'}, function(err) { + * console.log('finished processing foo'); + * }); + * q.push({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + * + * // add some items to the queue (batch-wise) + * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { + * console.log('finished processing item'); + * }); + * + * // add some items to the front of the queue + * q.unshift({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + */ + var queue$1 = function (worker, concurrency) { + var _worker = wrapAsync(worker); + return queue(function (items, cb) { + _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. + * + * @name priorityQueue + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. + * Invoked with (task, callback). + * @param {number} concurrency - An `integer` for determining how many `worker` + * functions should be run in parallel. If omitted, the concurrency defaults to + * `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two + * differences between `queue` and `priorityQueue` objects: + * * `push(task, priority, [callback])` - `priority` should be a number. If an + * array of `tasks` is given, all tasks will be assigned the same priority. + * * The `unshift` method was removed. + */ + 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; + if (typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + if (!isArray(data)) { + data = [data]; + } + if (data.length === 0) { + // call drain immediately if there are no tasks + return setImmediate$1(function() { + 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 { + q._tasks.push(item); + } + } + 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 + * error to its callback, the main `callback` is immediately called. It's + * equivalent to `Promise.race()`. + * + * @name race + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} + * to run. Each function can complete with an optional `result` value. + * @param {Function} callback - A callback to run once any of the functions have + * completed. This function gets an error or result from the first function that + * completed. Invoked with (err, result). + * @returns undefined + * @example + * + * async.race([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // main callback + * function(err, result) { + * // the result will be equal to 'two' as it finishes earlier + * }); + */ + function race(tasks, callback) { + callback = once(callback || noop); + if (!isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); + if (!tasks.length) return callback(); + for (var i = 0, l = tasks.length; i < l; i++) { + wrapAsync(tasks[i])(callback); + } + } + + /** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee complete with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + */ + function reduceRight (array, memo, iteratee, callback) { + 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. + * + * The result object has either the property `error` or `value`. + * + * @name reflect + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function you want to wrap + * @returns {Function} - A function that always passes null to it's callback as + * the error. The second argument to the callback will be an `object` with + * either an `error` or a `value` property. + * @example + * + * async.parallel([ + * async.reflect(function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }), + * async.reflect(function(callback) { + * // do some more stuff but error ... + * callback('bad stuff happened'); + * }), + * async.reflect(function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * }) + * ], + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = 'bad stuff happened' + * // results[2].value = 'two' + * }); + */ + function reflect(fn) { + var _fn = wrapAsync(fn); + return initialParams(function reflectOn(args, reflectCallback) { + args.push(function callback(error, cbArg) { + if (error) { + reflectCallback(null, { error: error }); + } else { + var value; + if (arguments.length <= 2) { + value = cbArg; + } else { + value = slice(arguments, 1); + } + reflectCallback(null, { value: value }); + } + }); + + return _fn.apply(this, args); + }); + } + + /** + * A helper function that wraps an array or an object of functions with `reflect`. + * + * @name reflectAll + * @static + * @memberOf module:Utils + * @method + * @see [async.reflect]{@link module:Utils.reflect} + * @category Util + * @param {Array|Object|Iterable} tasks - The collection of + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. + * @returns {Array} Returns an array of async functions, each wrapped in + * `async.reflect` + * @example + * + * let tasks = [ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * // do some more stuff but error ... + * callback(new Error('bad stuff happened')); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = Error('bad stuff happened') + * // results[2].value = 'two' + * }); + * + * // an example using an object instead of an array + * let tasks = { + * one: function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * two: function(callback) { + * callback('two'); + * }, + * three: function(callback) { + * setTimeout(function() { + * callback(null, 'three'); + * }, 100); + * } + * }; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results.one.value = 'one' + * // results.two.error = 'two' + * // results.three.value = 'three' + * }); + */ + function reflectAll(tasks) { + var results; + if (isArray(tasks)) { + results = arrayMap(tasks, reflect); + } else { + results = {}; + baseForOwn(tasks, function(task, key) { + results[key] = reflect.call(this, task); + }); + } + return results; + } + + function reject$1(eachfn, arr, iteratee, callback) { + _filter(eachfn, arr, function(value, cb) { + iteratee(value, function(err, v) { + cb(err, !v); + }); + }, callback); + } + + /** + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. + * + * @name reject + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @example + * + * async.reject(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of missing files + * createFiles(results); + * }); + */ + var reject = doParallel(reject$1); + + /** + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a + * time. + * + * @name rejectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `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. + * + * @name rejectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + */ + var rejectSeries = doLimit(rejectLimit, 1); + + /** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new constant function. + * @example + * + * var objects = _.times(2, _.constant({ 'a': 1 })); + * + * console.log(objects); + * // => [{ 'a': 1 }, { 'a': 1 }] + * + * console.log(objects[0] === objects[1]); + * // => true + */ + function constant$1(value) { + return function() { + 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 + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ + 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; + } else { + throw new Error("Invalid arguments for async.retry"); + } + } + + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || noop; + task = opts; + } else { + 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) { + if (err && attempt++ < options.times && + (typeof options.errorFilter != 'function' || + options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt)); + } else { + callback.apply(null, arguments); + } + }); + } + + retryAttempt(); + } + + /** + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method + * wraps a task and makes it retryable, rather than immediately calling it + * with retries. + * + * @name retryable + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.retry]{@link module:ControlFlow.retry} + * @category Control Flow + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional + * options, exactly the same as from `retry` + * @param {AsyncFunction} task - the asynchronous function to wrap. + * This function will be passed any arguments passed to the returned wrapper. + * Invoked with (...args, callback). + * @returns {AsyncFunction} The wrapped function, which when invoked, will + * retry on an error, based on the parameters specified in `opts`. + * This function will accept the same parameters as `task`. + * @example + * + * async.auto({ + * dep1: async.retryable(3, getFromFlakyService), + * process: ["dep1", async.retryable(3, function (results, cb) { + * maybeProcessData(results.dep1, cb); + * })] + * }, callback); + */ + var retryable = function (opts, task) { + if (!task) { + task = opts; + opts = null; + } + var _task = wrapAsync(task); + return initialParams(function (args, callback) { + 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 + * error to its callback, no more functions are run, and `callback` is + * immediately called with the value of the error. Otherwise, `callback` + * receives an array of results when `tasks` have completed. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function, and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.series}. + * + * **Note** that while many implementations preserve the order of object + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) + * explicitly states that + * + * > The mechanics and order of enumerating the properties is not specified. + * + * So if you rely on the order in which your series of functions are executed, + * and want this to work on all platforms, consider using an array. + * + * @name series + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|Object} tasks - A collection containing + * [async functions]{@link AsyncFunction} to run in series. + * Each function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This function gets a results array (or object) + * containing all the result arguments passed to the `task` callbacks. Invoked + * with (err, result). + * @example + * async.series([ + * function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }, + * function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * } + * ], + * // optional callback + * function(err, results) { + * // results is now equal to ['one', 'two'] + * }); + * + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback){ + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equal to: {one: 1, two: 2} + * }); + */ + 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 + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @example + * + * async.some(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then at least one of the files exists + * }); + */ + 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. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * 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. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * 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`. + * + * @name sortBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a value to use as the sort criteria as + * its `result`. + * Invoked with (item, callback). + * @param {Function} callback - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is the items + * from the original `coll` sorted by the values returned by the `iteratee` + * calls. Invoked with (err, results). + * @example + * + * async.sortBy(['file1','file2','file3'], function(file, callback) { + * fs.stat(file, function(err, stats) { + * callback(err, stats.mtime); + * }); + * }, function(err, results) { + * // results is now the original array of files sorted by + * // modified date + * }); + * + * // By modifying the callback parameter the + * // sorting order can be influenced: + * + * // ascending order + * async.sortBy([1,9,3,5], function(x, callback) { + * callback(null, x); + * }, function(err,result) { + * // result callback + * }); + * + * // descending order + * async.sortBy([1,9,3,5], function(x, callback) { + * callback(null, x*-1); //<- x*-1 instead of x, turns the order around + * }, function(err,result) { + * // result callback + * }); + */ + function sortBy (coll, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + map(coll, function (x, callback) { + _iteratee(x, function (err, criteria) { + if (err) return callback(err); + callback(null, {value: x, criteria: criteria}); + }); + }, function (err, results) { + 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 + * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * + * @name timeout + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} asyncFn - The async function to limit in time. + * @param {number} milliseconds - The specified time limit. + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) + * to timeout Error for more information.. + * @returns {AsyncFunction} Returns a wrapped function that can be used with any + * of the control flow functions. + * Invoke this function with the same parameters as you would `asyncFunc`. + * @example + * + * function myFunction(foo, callback) { + * doAsyncTask(foo, function(err, data) { + * // handle errors + * if (err) return callback(err); + * + * // do some stuff ... + * + * // return processed data + * return callback(null, data); + * }); + * } + * + * var wrapped = async.timeout(myFunction, 1000); + * + * // call `wrapped` as you would `myFunction` + * wrapped({ bar: 'bar' }, function(err, data) { + * // if `myFunction` takes < 1000 ms to execute, `err` + * // and `data` will have their expected values + * + * // else `err` will be an Error with the code 'ETIMEDOUT' + * }); + */ + 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.'); + error.code = 'ETIMEDOUT'; + if (info) { + error.info = info; + } + 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. + * + * @private + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @param {number} step The value to increment or decrement by. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the range of numbers. + */ + function baseRange(start, end, step, fromRight) { + 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. + * + * @name timesLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} count - The number of times to run the function. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see [async.map]{@link module:Collections.map}. + */ + function timeLimit(count, limit, iteratee, callback) { + 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}. + * + * @name times + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.map]{@link module:Collections.map} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @example + * + * // Pretend this is some complicated async factory + * var createUser = function(id, callback) { + * callback(null, { + * id: 'user' + id + * }); + * }; + * + * // generate 5 users + * async.times(5, function(n, next) { + * createUser(n, function(err, user) { + * next(err, user); + * }); + * }, function(err, users) { + * // we should now have 5 users + * }); + */ + var times = doLimit(timeLimit, Infinity); + + /** + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * + * @name timesSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @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. + * The type of the accumulator defaults to the type of collection passed in. + * + * @name transform + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {*} [accumulator] - The initial state of the transform. If omitted, + * it will default to an empty Object or Array, depending on the type of `coll` + * @param {AsyncFunction} iteratee - A function applied to each item in the + * collection that potentially modifies the accumulator. + * Invoked with (accumulator, item, key, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the transformed accumulator. + * Invoked with (err, result). + * @example + * + * async.transform([1,2,3], function(acc, item, index, callback) { + * // pointless async: + * process.nextTick(function() { + * acc.push(item * 2) + * callback(null) + * }); + * }, function(err, result) { + * // result is now equal to [2, 4, 6] + * }); + * + * @example + * + * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { + * setImmediate(function () { + * obj[key] = val * 2; + * callback(); + * }) + * }, function (err, result) { + * // result is equal to {a: 2, b: 4, c: 6} + * }) + */ + function transform (coll, accumulator, iteratee, callback) { + if (arguments.length <= 3) { + callback = iteratee; + iteratee = accumulator; + accumulator = isArray(coll) ? [] : {}; + } + 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 + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @example + * async.tryEach([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ + function tryEach(tasks, callback) { + var error = null; + var result; + callback = callback || noop; + eachSeries(tasks, function(task, callback) { + wrapAsync(task)(function (err, res/*, ...args*/) { + if (arguments.length > 2) { + result = slice(arguments, 1); + } else { + result = res; + } + error = err; + callback(!err); + }); + }, function () { + callback(error, result); + }); + } + + /** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ + function unmemoize(fn) { + return function () { + return (fn.unmemoized || fn).apply(null, arguments); + }; + } + + /** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Function} test - synchronous truth test to perform before each + * execution of `iteratee`. Invoked with (). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns undefined + * @example + * + * var count = 0; + * async.whilst( + * function() { return count < 5; }, + * function(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ + function whilst(test, iteratee, callback) { + callback = onlyOnce(callback || noop); + var _iteratee = wrapAsync(iteratee); + if (!test()) return callback(null); + var next = function(err/*, ...args*/) { + if (err) return callback(err); + if (test()) return _iteratee(next); + var args = slice(arguments, 1); + callback.apply(null, [null].concat(args)); + }; + _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 + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {Function} test - synchronous truth test to perform before each + * execution of `iteratee`. Invoked with (). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + */ + function until(test, iteratee, callback) { + whilst(function() { + 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 + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns undefined + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ + var waterfall = function(tasks, callback) { + callback = once(callback || noop); + 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. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. + * + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static + */ + + /** + * Async is a utility module which provides straight-forward, powerful functions + * for working with asynchronous JavaScript. Although originally designed for + * use with [Node.js](http://nodejs.org) and installable via + * `npm install --save async`, it can also be used directly in the browser. + * @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, + applyEachSeries: applyEachSeries, + asyncify: asyncify, + auto: auto, + autoInject: autoInject, + cargo: cargo, + compose: compose, + concat: concat, + concatLimit: concatLimit, + concatSeries: concatSeries, + constant: constant, + detect: detect, + detectLimit: detectLimit, + detectSeries: detectSeries, + dir: dir, + doDuring: doDuring, + doUntil: doUntil, + doWhilst: doWhilst, + during: during, + each: eachLimit, + eachLimit: eachLimit$1, + eachOf: eachOf, + eachOfLimit: eachOfLimit, + eachOfSeries: eachOfSeries, + eachSeries: eachSeries, + ensureAsync: ensureAsync, + every: every, + everyLimit: everyLimit, + everySeries: everySeries, + filter: filter, + filterLimit: filterLimit, + filterSeries: filterSeries, + forever: forever, + groupBy: groupBy, + groupByLimit: groupByLimit, + groupBySeries: groupBySeries, + log: log, + map: map, + mapLimit: mapLimit, + mapSeries: mapSeries, + mapValues: mapValues, + mapValuesLimit: mapValuesLimit, + mapValuesSeries: mapValuesSeries, + memoize: memoize, + nextTick: nextTick, + parallel: parallelLimit, + parallelLimit: parallelLimit$1, + priorityQueue: priorityQueue, + queue: queue$1, + race: race, + reduce: reduce, + reduceRight: reduceRight, + reflect: reflect, + reflectAll: reflectAll, + reject: reject, + rejectLimit: rejectLimit, + rejectSeries: rejectSeries, + retry: retry, + retryable: retryable, + seq: seq, + series: series, + setImmediate: setImmediate$1, + some: some, + someLimit: someLimit, + someSeries: someSeries, + sortBy: sortBy, + timeout: timeout, + times: times, + timesLimit: timeLimit, + timesSeries: timesSeries, + transform: transform, + tryEach: tryEach, + unmemoize: unmemoize, + until: until, + waterfall: waterfall, + whilst: whilst, + + // aliases + all: every, + allLimit: everyLimit, + allSeries: everySeries, + any: some, + anyLimit: someLimit, + anySeries: someSeries, + find: detect, + findLimit: detectLimit, + findSeries: detectSeries, + forEach: eachLimit, + forEachSeries: eachSeries, + forEachLimit: eachLimit$1, + forEachOf: eachOf, + forEachOfSeries: eachOfSeries, + forEachOfLimit: eachOfLimit, + inject: reduce, + foldl: reduce, + foldr: reduceRight, + select: filter, + selectLimit: filterLimit, + selectSeries: filterSeries, + wrapSync: asyncify + }; + + exports['default'] = index; + exports.apply = apply; + exports.applyEach = applyEach; + exports.applyEachSeries = applyEachSeries; + exports.asyncify = asyncify; + exports.auto = auto; + exports.autoInject = autoInject; + exports.cargo = cargo; + exports.compose = compose; + exports.concat = concat; + exports.concatLimit = concatLimit; + exports.concatSeries = concatSeries; + exports.constant = constant; + exports.detect = detect; + exports.detectLimit = detectLimit; + exports.detectSeries = detectSeries; + exports.dir = dir; + exports.doDuring = doDuring; + exports.doUntil = doUntil; + exports.doWhilst = doWhilst; + exports.during = during; + exports.each = eachLimit; + exports.eachLimit = eachLimit$1; + exports.eachOf = eachOf; + exports.eachOfLimit = eachOfLimit; + exports.eachOfSeries = eachOfSeries; + exports.eachSeries = eachSeries; + exports.ensureAsync = ensureAsync; + exports.every = every; + exports.everyLimit = everyLimit; + exports.everySeries = everySeries; + exports.filter = filter; + exports.filterLimit = filterLimit; + exports.filterSeries = filterSeries; + exports.forever = forever; + exports.groupBy = groupBy; + exports.groupByLimit = groupByLimit; + exports.groupBySeries = groupBySeries; + exports.log = log; + exports.map = map; + exports.mapLimit = mapLimit; + exports.mapSeries = mapSeries; + exports.mapValues = mapValues; + exports.mapValuesLimit = mapValuesLimit; + exports.mapValuesSeries = mapValuesSeries; + exports.memoize = memoize; + exports.nextTick = nextTick; + exports.parallel = parallelLimit; + exports.parallelLimit = parallelLimit$1; + exports.priorityQueue = priorityQueue; + exports.queue = queue$1; + exports.race = race; + exports.reduce = reduce; + exports.reduceRight = reduceRight; + exports.reflect = reflect; + exports.reflectAll = reflectAll; + exports.reject = reject; + exports.rejectLimit = rejectLimit; + exports.rejectSeries = rejectSeries; + exports.retry = retry; + exports.retryable = retryable; + exports.seq = seq; + exports.series = series; + exports.setImmediate = setImmediate$1; + exports.some = some; + exports.someLimit = someLimit; + exports.someSeries = someSeries; + exports.sortBy = sortBy; + exports.timeout = timeout; + exports.times = times; + exports.timesLimit = timeLimit; + exports.timesSeries = timesSeries; + exports.transform = transform; + exports.tryEach = tryEach; + exports.unmemoize = unmemoize; + exports.until = until; + exports.waterfall = waterfall; + exports.whilst = whilst; + exports.all = every; + exports.allLimit = everyLimit; + exports.allSeries = everySeries; + exports.any = some; + exports.anyLimit = someLimit; + exports.anySeries = someSeries; + exports.find = detect; + exports.findLimit = detectLimit; + exports.findSeries = detectSeries; + exports.forEach = eachLimit; + exports.forEachSeries = eachSeries; + exports.forEachLimit = eachLimit$1; + exports.forEachOf = eachOf; + exports.forEachOfSeries = eachOfSeries; + exports.forEachOfLimit = eachOfLimit; + exports.inject = reduce; + exports.foldl = reduce; + exports.foldr = reduceRight; + exports.select = filter; + 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. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + */ + function eachLimit(coll, limit, iteratee, callback) { + (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); + } + module.exports = exports['default']; + },{"./internal/eachOfLimit":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); + var index = 0, + completed = 0, + length = coll.length; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err) { + callback(err); + } else if (++completed === length || value === _breakLoop2.default) { + 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. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @example + * + * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; + * var configs = {}; + * + * async.forEachOf(obj, function (value, key, callback) { + * fs.readFile(__dirname + value, "utf8", function (err, data) { + * if (err) return callback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * }, function (err) { + * if (err) console.error(err.message); + * // configs is now a map of JSON data + * doSomethingWith(configs); + * }); + */ + 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. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + */ + function eachOfLimit(coll, limit, iteratee, callback) { + (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); + } + 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. + * + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + */ + exports.default = (0, _doLimit2.default)(_eachLimit2.default, 1); + module.exports = exports['default']; + },{"./eachLimit":22,"./internal/doLimit":27}],26:[function(require,module,exports){ + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + // A temporary value used to identify if the loop should be broken. + // See #1064, #1293 + exports.default = {}; + module.exports = exports["default"]; + },{}],27:[function(require,module,exports){ + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = doLimit; + function doLimit(fn, limit) { + return function (iterable, iteratee, callback) { + return fn(iterable, limit, iteratee, callback); + }; + } + 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); + }; + } + 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); + if (limit <= 0 || !obj) { + return callback(null); + } + var nextElem = (0, _iterator2.default)(obj); + var done = false; + var running = 0; + + function iterateeCallback(err, value) { + running -= 1; + if (err) { + done = true; + callback(err); + } else if (value === _breakLoop2.default || done && running <= 0) { + done = true; + return callback(null); + } else { + replenish(); + } + } + + function replenish() { + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + 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); + var callback = args.pop(); + 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; + return function next() { + return ++i < len ? { value: coll[i], key: i } : null; + }; + } + + function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) return null; + i++; + return { value: item.value, key: i }; + }; + } + + function createObjectIterator(obj) { + var okeys = (0, _keys2.default)(obj); + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + 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) { + results[index] = v; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + module.exports = exports['default']; + },{"./wrapAsync":40,"lodash/noop":229}],34:[function(require,module,exports){ + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = once; + function once(fn) { + return function () { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, arguments); + }; + } + module.exports = exports["default"]; + },{}],35:[function(require,module,exports){ + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = onlyOnce; + function onlyOnce(fn) { + return function () { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; + callFn.apply(this, arguments); + }; + } + 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) { + result = (0, _slice2.default)(arguments, 1); + } + results[key] = result; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + module.exports = exports['default']; + },{"./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); + defer(function () { + fn.apply(null, args); + }); + }; + } + + var _defer; + + if (hasSetImmediate) { + _defer = setImmediate; + } else if (hasNextTick) { + _defer = process.nextTick; + } 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 + }); + exports.default = slice; + function slice(arrayLike, start) { + start = start | 0; + var newLen = Math.max(arrayLike.length - start, 0); + var newArr = Array(newLen); + for (var idx = 0; idx < newLen; idx++) { + newArr[idx] = arrayLike[start + idx]; + } + return newArr; + } + module.exports = exports["default"]; + },{}],39:[function(require,module,exports){ + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = _withoutIndex; + function _withoutIndex(iteratee) { + return function (value, index, callback) { + return iteratee(value, callback); + }; + } + 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` + * and a callback for when it has finished processing. Each of these callback + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @example + * + * async.map(['file1','file2','file3'], fs.stat, function(err, results) { + * // results is now an array of stats for each file + * }); + */ + exports.default = (0, _doParallel2.default)(_map2.default); + 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 + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * + * @example + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // optional callback + * function(err, results) { + * // the results array will equal ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equals to: {one: 1, two: 2} + * }); + */ + function parallelLimit(tasks, callback) { + (0, _parallel2.default)(_eachOf2.default, tasks, callback); + } + 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 + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ + 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; + } else { + throw new Error("Invalid arguments for async.retry"); + } + } + + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || _noop2.default; + task = opts; + } else { + 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) { + if (err && attempt++ < options.times && (typeof options.errorFilter != 'function' || options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt)); + } else { + callback.apply(null, arguments); + } + }); + } + + 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 + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns undefined + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ + },{"./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); + fn = args[0]; + vargs = args.slice(1, args.length - 1); + 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(); + } else { + this.backoffDelay_ = this.backoffStrategy_.next(); + this.timeoutID_ = setTimeout(this.handlers.backoff, this.backoffDelay_); + 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; + this.backoffStrategy_.reset(); + 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. + PENDING: 0, + // Call is in progress. + RUNNING: 1, + // Call completed successfully which means that either the wrapped function + // returned successfully or the maximal number of backoffs was reached. + COMPLETED: 2, + // 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) { + precond.checkState(this.isPending(), 'FunctionCall in progress.'); + 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 + // function call. + FunctionCall.prototype.retryIf = function(retryPredicate) { + precond.checkState(this.isPending(), 'FunctionCall in progress.'); + 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) { + this.numRetries_++; + } + var eventArgs = ['call'].concat(this.arguments_); + events.EventEmitter.prototype.emit.apply(this, eventArgs); + 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); + } else { + this.state_ = FunctionCall.State_.COMPLETED; + 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.', + options.factor); + this.factor_ = options.factor; + } + } + 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); + this.backoffDelay_ = 0; + 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: + // + // * `randomisationFactor`: The randomisation factor which must be between 0 + // and 1 where 1 equates to a randomization factor of 100% and 0 to no + // randomization. + // * `initialDelay`: The backoff initial delay in milliseconds. + // * `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() { + var backoffDelay = this.next_(); + var randomisationMultiple = 1 + Math.random() * this.randomisationFactor_; + 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 + // if there is only one, then the three characters before it represent 2 bytes + // 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 + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) + 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 = [] + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output.push(tripletToBase64(tmp)) + } + return output.join('') + } + + function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var 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] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3F] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3F] + 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. + * + * The DER format uses the most significant bit as a sign bit (& 0x80). + * If the significant bit is set AND the integer is positive, a 0x00 is prepended. + * + * Examples: + * + * 0 => 0x00 + * 1 => 0x01 + * -1 => 0xff + * 127 => 0x7f + * -127 => 0x81 + * 128 => 0x0080 + * -128 => 0x80 + * 255 => 0x00ff + * -255 => 0xff01 + * 16300 => 0x3fac + * -16300 => 0xc054 + * 62300 => 0x00f35c + * -62300 => 0xff0ca4 + */ + function encode (r, s) { + var lenR = r.length + var lenS = s.length + if (lenR === 0) throw new Error('R length is zero') + if (lenS === 0) throw new Error('S length is zero') + if (lenR > 33) throw new Error('R length is too long') + if (lenS > 33) throw new Error('S length is too long') + if (r[0] & 0x80) throw new Error('R value is negative') + if (s[0] & 0x80) throw new Error('S value is negative') + if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded') + if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded') + + var signature = Buffer.allocUnsafe(6 + lenR + lenS) + + // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] + signature[0] = 0x30 + signature[1] = signature.length - 2 + signature[2] = 0x02 + signature[3] = r.length + r.copy(signature, 4) + signature[4 + lenR] = 0x02 + signature[5 + lenR] = s.length + s.copy(signature, 6 + lenR) + + return signature + } + + module.exports = { + check: check, + decode: decode, + encode: encode + } + + },{"safe-buffer":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) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + Buffer = require('buffer').Buffer; + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + } + + if (base === 16) { + this._parseHex(number, start); + } else { + this._parseBase(number, base, start); + } + + if (number[0] === '-') { + this.negative = 1; + } + + this.strip(); + + if (endian !== 'le') return; + + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex (str, start, end) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r <<= 4; + + // 'a' - 'f' + if (c >= 49 && c <= 54) { + r |= c - 49 + 0xa; + + // 'A' - 'F' + } else if (c >= 17 && c <= 22) { + r |= c - 17 + 0xa; + + // '0' - '9' + } else { + r |= c & 0xf; + } + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + // Scan 24-bit chunks and add them to the number + var off = 0; + for (i = number.length - 6, j = 0; i >= start; i -= 6) { + w = parseHex(number, i, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + if (i + 6 !== start) { + w = parseHex(number, start, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + } + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + r.strip(); + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; + })(typeof module === 'undefined' || module, this); + + },{"buffer":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 + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + self.crypto.getRandomValues(arr); + return arr; + }; + } else if (self.msCrypto && self.msCrypto.getRandomValues) { + // IE + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + self.msCrypto.getRandomValues(arr); + return arr; + }; + + // Safari's WebWorkers do not have `crypto` + } else if (typeof window === 'object') { + // Old junk + Rand.prototype._rand = function() { + throw new Error('Not implemented yet'); + }; + } + } else { + // Node.js or Web worker with no crypto support + try { + var crypto = require('crypto'); + if (typeof crypto.randomBytes !== 'function') + throw new Error('Not supported'); + + Rand.prototype._rand = function _rand(n) { + return crypto.randomBytes(n); + }; + } catch (e) { + } + } + + },{"crypto":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++] + t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++] + t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++] + s0 = t0 + s1 = t1 + 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++] + t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++] + t0 = t0 >>> 0 + 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 () { + // Compute double table + var d = new Array(256) + for (var j = 0; j < 256; j++) { + if (j < 128) { + d[j] = j << 1 + } else { + 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 + for (var i = 0; i < 256; ++i) { + // Compute sbox + var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4) + 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 { + x = x2 ^ d[d[d[x8 ^ x2]]] + xi ^= d[d[xi]] + } + } + + return { + SBOX: SBOX, + INV_SBOX: INV_SBOX, + SUB_MIX: SUB_MIX, + 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 + AES.prototype.keySize = AES.keySize + AES.prototype._reset = function () { + var keyWords = this._key + 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 = + (G.SBOX[t >>> 24] << 24) | + (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 = + (G.SBOX[t >>> 24] << 24) | + (G.SBOX[(t >>> 16) & 0xff] << 16) | + (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 { + invKeySchedule[ik] = + G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^ + G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^ + G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^ + 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) + buf.writeUInt32BE(out[0], 0) + buf.writeUInt32BE(out[1], 4) + buf.writeUInt32BE(out[2], 8) + 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) + buf.writeUInt32BE(out[3], 4) + buf.writeUInt32BE(out[2], 8) + 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 + var Transform = require('cipher-base') + var inherits = require('inherits') + 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])]) + return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])]) + } + var ghash = new GHASH(ck) + var len = iv.length + var toPad = len % 16 + ghash.update(iv) + if (toPad) { + toPad = 16 - toPad + ghash.update(Buffer.alloc(toPad, 0)) + } + ghash.update(Buffer.alloc(8, 0)) + var ivBits = len * 8 + var tail = Buffer.alloc(8) + tail.writeUIntBE(ivBits, 0, 8) + ghash.update(tail) + self._finID = ghash.state + var out = Buffer.from(self._finID) + incr32(out) + return out + } + 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) + this._decrypt = decrypt + 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) + if (rump < 16) { + rump = Buffer.alloc(rump, 0) + this._ghash.update(rump) + } + } + + this._called = true + var out = this._mode.encrypt(this, chunk) + if (this._decrypt) { + this._ghash.update(chunk) + } else { + this._ghash.update(out) + } + 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 + var MODES = require('./modes') + var StreamCipher = require('./streamCipher') + var Transform = require('cipher-base') + 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) + this._prev = Buffer.from(iv) + this._mode = mode + this._autopadding = true + } + + inherits(Decipher, Transform) + + Decipher.prototype._update = function (data) { + this._cache.add(data) + var chunk + var thing + var out = [] + while ((chunk = this._cache.get(this._autopadding))) { + thing = this._mode.decrypt(this, chunk) + out.push(thing) + } + return Buffer.concat(out) + } + + Decipher.prototype._final = function () { + var chunk = this._cache.flush() + if (this._autopadding) { + return unpad(this._mode.decrypt(this, chunk)) + } else if (chunk) { + 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) { + if (this.cache.length > 16) { + out = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + return out + } + } else { + if (this.cache.length >= 16) { + out = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + 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 + while (++i < padded) { + if (last[(i + (16 - padded))] !== padded) { + throw new Error('unable to decrypt data') + } + } + 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') + var Buffer = require('safe-buffer').Buffer + var StreamCipher = require('./streamCipher') + var Transform = require('cipher-base') + 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) { + chunk = this._mode.encrypt(this, chunk) + 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) + this.cache = this.cache.slice(16) + return out + } + 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), + buf.readUInt32BE(4), + buf.readUInt32BE(8), + buf.readUInt32BE(12) + ] + } + + function fromArray (out) { + var buf = Buffer.allocUnsafe(16) + buf.writeUInt32BE(out[0] >>> 0, 0) + buf.writeUInt32BE(out[1] >>> 0, 4) + buf.writeUInt32BE(out[2] >>> 0, 8) + 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) { + var i = -1 + while (++i < block.length) { + this.state[i] ^= block[i] + } + this._multiply() + } + + GHASH.prototype._multiply = function () { + var Vi = toArray(this.h) + var Zi = [0, 0, 0, 0] + var j, xi, lsbVi + var i = -1 + while (++i < 128) { + xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0 + if (xi) { + // Z_i+1 = Z_i ^ V_i + Zi[0] ^= Vi[0] + Zi[1] ^= Vi[1] + 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) + } + } + this.state = fromArray(Zi) + } + + GHASH.prototype.update = function (buf) { + this.cache = Buffer.concat([this.cache, buf]) + var chunk + while (this.cache.length >= 16) { + chunk = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + 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 + var item + while (len--) { + item = iv.readUInt8(len) + if (item === 255) { + iv.writeUInt8(0, len) + } else { + item++ + iv.writeUInt8(item, len) + break + } + } + } + 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) + self._cache = self._cache.slice(len) + 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)]) + data = data.slice(len) + } else { + out = Buffer.concat([out, encryptStart(self, data, decrypt)]) + 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 + var len = 8 + var out = 0 + var bit, value + while (++i < len) { + pad = self._cipher.encryptBlock(self._prev) + bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0 + value = pad[0] ^ bit + out += ((value & 0x80) >> (i % 8)) + self._prev = shiftIn(self._prev, decrypt ? bit : value) + } + 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) + var start = self._cache.length + self._cache = Buffer.concat([ + self._cache, + Buffer.allocUnsafe(chunkNum * blockSize) + ]) + for (var i = 0; i < chunkNum; i++) { + var out = getBlock(self) + var offset = start + i * blockSize + self._cache.writeUInt32BE(out[0], offset + 0) + self._cache.writeUInt32BE(out[1], offset + 4) + self._cache.writeUInt32BE(out[2], offset + 8) + self._cache.writeUInt32BE(out[3], offset + 12) + } + var pad = self._cache.slice(0, chunk.length) + 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'), + CBC: require('./cbc'), + CFB: require('./cfb'), + CFB8: require('./cfb8'), + CFB1: require('./cfb1'), + OFB: require('./ofb'), + 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": { + "cipher": "AES", + "key": 128, + "iv": 0, + "mode": "ECB", + "type": "block" + }, + "aes-192-ecb": { + "cipher": "AES", + "key": 192, + "iv": 0, + "mode": "ECB", + "type": "block" + }, + "aes-256-ecb": { + "cipher": "AES", + "key": 256, + "iv": 0, + "mode": "ECB", + "type": "block" + }, + "aes-128-cbc": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes-192-cbc": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes-256-cbc": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes128": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes192": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes256": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes-128-cfb": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CFB", + "type": "stream" + }, + "aes-192-cfb": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CFB", + "type": "stream" + }, + "aes-256-cfb": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CFB", + "type": "stream" + }, + "aes-128-cfb8": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CFB8", + "type": "stream" + }, + "aes-192-cfb8": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CFB8", + "type": "stream" + }, + "aes-256-cfb8": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CFB8", + "type": "stream" + }, + "aes-128-cfb1": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CFB1", + "type": "stream" + }, + "aes-192-cfb1": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CFB1", + "type": "stream" + }, + "aes-256-cfb1": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CFB1", + "type": "stream" + }, + "aes-128-ofb": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "OFB", + "type": "stream" + }, + "aes-192-ofb": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "OFB", + "type": "stream" + }, + "aes-256-ofb": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "OFB", + "type": "stream" + }, + "aes-128-ctr": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CTR", + "type": "stream" + }, + "aes-192-ctr": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CTR", + "type": "stream" + }, + "aes-256-ctr": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CTR", + "type": "stream" + }, + "aes-128-gcm": { + "cipher": "AES", + "key": 128, + "iv": 12, + "mode": "GCM", + "type": "auth" + }, + "aes-192-gcm": { + "cipher": "AES", + "key": 192, + "iv": 12, + "mode": "GCM", + "type": "auth" + }, + "aes-256-gcm": { + "cipher": "AES", + "key": 256, + "iv": 12, + "mode": "GCM", + "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) + this._secCache = Buffer.allocUnsafe(0) + 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') + var DES = require('browserify-des') + var desModes = require('browserify-des/modes') + var aesModes = require('browserify-aes/modes') + function createCipher (suite, password) { + var keyLen, ivLen + suite = suite.toLowerCase() + if (aesModes[suite]) { + keyLen = aesModes[suite].key + ivLen = aesModes[suite].iv + } else if (desModes[suite]) { + keyLen = desModes[suite].key * 8 + ivLen = desModes[suite].iv + } else { + throw new TypeError('invalid suite type') + } + var keys = ebtk(password, false, keyLen, ivLen) + return createCipheriv(suite, keys.key, keys.iv) + } + function createDecipher (suite, password) { + var keyLen, ivLen + suite = suite.toLowerCase() + if (aesModes[suite]) { + keyLen = aesModes[suite].key + ivLen = aesModes[suite].iv + } else if (desModes[suite]) { + keyLen = desModes[suite].key * 8 + ivLen = desModes[suite].iv + } else { + throw new TypeError('invalid suite type') + } + 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]) { + return aes.createCipheriv(suite, key, iv) + } else if (desModes[suite]) { + return new DES({ + key: key, + iv: iv, + mode: suite + }) + } else { + throw new TypeError('invalid suite type') + } + } + function createDecipheriv (suite, key, iv) { + suite = suite.toLowerCase() + if (aesModes[suite]) { + return aes.createDecipheriv(suite, key, iv) + } else if (desModes[suite]) { + return new DES({ + key: key, + iv: iv, + mode: suite, + decrypt: true + }) + } else { + throw new TypeError('invalid suite type') + } + } + exports.createCipher = exports.Cipher = createCipher + exports.createCipheriv = exports.Cipheriv = createCipheriv + exports.createDecipher = exports.Decipher = createDecipher + exports.createDecipheriv = exports.Decipheriv = createDecipheriv + function getCiphers () { + 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, + 'des-ede-cbc': des.CBC.instantiate(des.EDE), + 'des-ede': des.EDE, + 'des-cbc': des.CBC.instantiate(des.DES), + 'des-ecb': des.DES + } + modes.des = modes['des-cbc'] + modes.des3 = modes['des-ede3-cbc'] + module.exports = DES + inherits(DES, CipherBase) + function DES (opts) { + CipherBase.call(this) + var modeName = opts.mode.toLowerCase() + var mode = modes[modeName] + var type + if (opts.decrypt) { + type = 'decrypt' + } else { + type = 'encrypt' + } + var key = opts.key + if (modeName === 'des-ede' || modeName === 'des-ede-cbc') { + key = Buffer.concat([key, key.slice(0, 8)]) + } + var iv = opts.iv + this._des = mode.create({ + key: key, + iv: iv, + type: type + }) + } + DES.prototype._update = function (data) { + return new Buffer(this._des.update(data)) + } + 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'] = { + key: 8, + iv: 0 + } + exports['des-cbc'] = exports.des = { + key: 8, + iv: 8 + } + exports['des-ede3-cbc'] = exports.des3 = { + key: 24, + iv: 8 + } + exports['des-ede3'] = { + key: 24, + iv: 0 + } + exports['des-ede-cbc'] = { + key: 16, + iv: 8 + } + exports['des-ede'] = { + key: 16, + iv: 0 + } + + },{}],76:[function(require,module,exports){ + (function (Buffer){ + var bn = require('bn.js'); + var randomBytes = require('randombytes'); + module.exports = crt; + function blind(priv) { + var r = getr(priv); + var blinder = r.toRed(bn.mont(priv.modulus)) + .redPow(new bn(priv.publicExponent)).fromRed(); + return { + blinder: blinder, + unblinder:r.invm(priv.modulus) + }; + } + function crt(msg, priv) { + var blinds = blind(priv); + var len = priv.modulus.byteLength(); + var mod = bn.mont(priv.modulus); + var blinded = new bn(msg).mul(blinds.blinder).umod(priv.modulus); + var c1 = blinded.toRed(bn.mont(priv.prime1)); + var c2 = blinded.toRed(bn.mont(priv.prime2)); + var qinv = priv.coefficient; + var p = priv.prime1; + var q = priv.prime2; + var m1 = c1.redPow(priv.exponent1); + var m2 = c2.redPow(priv.exponent2); + m1 = m1.fromRed(); + m2 = m2.fromRed(); + var h = m1.isub(m2).imul(qinv).umod(p); + h.imul(q); + m2.iadd(h); + return new Buffer(m2.imul(blinds.unblinder).umod(priv.modulus).toArray(false, len)); + } + crt.getr = getr; + function getr(priv) { + var len = priv.modulus.byteLength(); + var r = new bn(randomBytes(len)); + while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)) { + r = new bn(randomBytes(len)); + } + 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": { + "sign": "rsa", + "hash": "sha224", + "id": "302d300d06096086480165030402040500041c" + }, + "RSA-SHA224": { + "sign": "ecdsa/rsa", + "hash": "sha224", + "id": "302d300d06096086480165030402040500041c" + }, + "sha256WithRSAEncryption": { + "sign": "rsa", + "hash": "sha256", + "id": "3031300d060960864801650304020105000420" + }, + "RSA-SHA256": { + "sign": "ecdsa/rsa", + "hash": "sha256", + "id": "3031300d060960864801650304020105000420" + }, + "sha384WithRSAEncryption": { + "sign": "rsa", + "hash": "sha384", + "id": "3041300d060960864801650304020205000430" + }, + "RSA-SHA384": { + "sign": "ecdsa/rsa", + "hash": "sha384", + "id": "3041300d060960864801650304020205000430" + }, + "sha512WithRSAEncryption": { + "sign": "rsa", + "hash": "sha512", + "id": "3051300d060960864801650304020305000440" + }, + "RSA-SHA512": { + "sign": "ecdsa/rsa", + "hash": "sha512", + "id": "3051300d060960864801650304020305000440" + }, + "RSA-SHA1": { + "sign": "rsa", + "hash": "sha1", + "id": "3021300906052b0e03021a05000414" + }, + "ecdsa-with-SHA1": { + "sign": "ecdsa", + "hash": "sha1", + "id": "" + }, + "sha256": { + "sign": "ecdsa", + "hash": "sha256", + "id": "" + }, + "sha224": { + "sign": "ecdsa", + "hash": "sha224", + "id": "" + }, + "sha384": { + "sign": "ecdsa", + "hash": "sha384", + "id": "" + }, + "sha512": { + "sign": "ecdsa", + "hash": "sha512", + "id": "" + }, + "DSA-SHA": { + "sign": "dsa", + "hash": "sha1", + "id": "" + }, + "DSA-SHA1": { + "sign": "dsa", + "hash": "sha1", + "id": "" + }, + "DSA": { + "sign": "dsa", + "hash": "sha1", + "id": "" + }, + "DSA-WITH-SHA224": { + "sign": "dsa", + "hash": "sha224", + "id": "" + }, + "DSA-SHA224": { + "sign": "dsa", + "hash": "sha224", + "id": "" + }, + "DSA-WITH-SHA256": { + "sign": "dsa", + "hash": "sha256", + "id": "" + }, + "DSA-SHA256": { + "sign": "dsa", + "hash": "sha256", + "id": "" + }, + "DSA-WITH-SHA384": { + "sign": "dsa", + "hash": "sha384", + "id": "" + }, + "DSA-SHA384": { + "sign": "dsa", + "hash": "sha384", + "id": "" + }, + "DSA-WITH-SHA512": { + "sign": "dsa", + "hash": "sha512", + "id": "" + }, + "DSA-SHA512": { + "sign": "dsa", + "hash": "sha512", + "id": "" + }, + "DSA-RIPEMD160": { + "sign": "dsa", + "hash": "rmd160", + "id": "" + }, + "ripemd160WithRSA": { + "sign": "rsa", + "hash": "rmd160", + "id": "3021300906052b2403020105000414" + }, + "RSA-RIPEMD160": { + "sign": "rsa", + "hash": "rmd160", + "id": "3021300906052b2403020105000414" + }, + "md5WithRSAEncryption": { + "sign": "rsa", + "hash": "md5", + "id": "3020300c06082a864886f70d020505000410" + }, + "RSA-MD5": { + "sign": "rsa", + "hash": "md5", + "id": "3020300c06082a864886f70d020505000410" + } + } + + },{}],79:[function(require,module,exports){ + module.exports={ + "1.3.132.0.10": "secp256k1", + "1.3.132.0.33": "p224", + "1.2.840.10045.3.1.1": "p192", + "1.2.840.10045.3.1.7": "p256", + "1.3.132.0.34": "p384", + "1.3.132.0.35": "p521" + } + + },{}],80:[function(require,module,exports){ + (function (Buffer){ + var createHash = require('create-hash') + var stream = require('stream') + 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){ + // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js + var createHmac = require('create-hmac') + var crt = require('browserify-rsa') + var EC = require('elliptic').ec + 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) { + // rsa keys can be interpreted as ecdsa ones in openssl + if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type') + return ecSign(hash, priv) + } else if (priv.type === 'dsa') { + if (signType !== 'dsa') throw new Error('wrong private key type') + return dsaSign(hash, priv, hashType) + } else { + if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type') + } + hash = Buffer.concat([tag, hash]) + var len = priv.modulus.byteLength() + var pad = [ 0, 1 ] + while (hash.length + pad.length + 1 < len) pad.push(0xff) + 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 + var q = priv.params.q + var g = priv.params.g + var r = new BN(0) + var k + var H = bits2int(hash, q).mod(q) + var s = false + var kv = getKey(x, q, hash, algo) + while (s === false) { + k = makeKey(q, kv, algo) + r = makeR(g, k, p, q) + s = k.invm(q).imul(H.add(x.mul(r))).mod(q) + if (s.cmpn(0) === 0) { + s = false + r = new BN(0) + } + } + 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()) { + var zeros = new Buffer(q.byteLength() - x.length) + zeros.fill(0) + x = Buffer.concat([ zeros, x ]) + } + var hlen = hash.length + var hbits = bits2octets(hash, q) + var v = new Buffer(hlen) + v.fill(1) + var k = new Buffer(hlen) + k.fill(0) + k = createHmac(algo, k).update(v).update(new Buffer([ 0 ])).update(x).update(hbits).digest() + v = createHmac(algo, k).update(v).digest() + k = createHmac(algo, k).update(v).update(new Buffer([ 1 ])).update(x).update(hbits).digest() + 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) + var out = new Buffer(bits.toArray()) + if (out.length < q.byteLength()) { + var zeros = new Buffer(q.byteLength() - out.length) + zeros.fill(0) + out = Buffer.concat([ zeros, out ]) + } + 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){ + // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js + var BN = require('bn.js') + 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') { + // rsa keys can be interpreted as ecdsa ones in openssl + if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type') + return ecVerify(sig, hash, pub) + } else if (pub.type === 'dsa') { + if (signType !== 'dsa') throw new Error('wrong public key type') + return dsaVerify(sig, hash, pub) + } else { + if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type') + } + hash = Buffer.concat([tag, hash]) + var len = pub.modulus.byteLength() + var pad = [ 1 ] + var padNum = 0 + while (hash.length + pad.length + 2 < len) { + pad.push(0xff) + padNum++ + } + pad.push(0x00) + var i = -1 + while (++i < hash.length) { + pad.push(hash[i]) + } + 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 + var g = pub.data.g + var y = pub.data.pub_key + var unpacked = parseKeys.signature.decode(sig, 'der') + var s = unpacked.s + var r = unpacked.r + checkValue(s, q) + checkValue(r, q) + var montp = BN.mont(p) + var w = s.invm(q) + var v = g.toRed(montp) + .redPow(new BN(hash).mul(w).mod(q)) + .fromRed() + .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed()) + .mod(p) + .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){ + /*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + /* eslint-disable no-proto */ + + 'use strict' + + var base64 = require('base64-js') + var ieee754 = require('ieee754') + + exports.Buffer = Buffer + exports.SlowBuffer = SlowBuffer + exports.INSPECT_MAX_BYTES = 50 + + var K_MAX_LENGTH = 0x7fffffff + exports.kMaxLength = K_MAX_LENGTH + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ + Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + + if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) + } + + function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 + } catch (e) { + return false + } + } + + function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('Invalid typed array length') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length) + buf.__proto__ = Buffer.prototype + return buf + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) + } + + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true, + enumerable: false, + writable: false + }) + } + + Buffer.poolSize = 8192 // not used by this implementation + + function from (value, encodingOrOffset, length) { + if (typeof value === '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. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) + } + + // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: + // https://github.com/feross/buffer/pull/148 + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) + } + + function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) + } + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) + } + + function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"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) + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf + } + + function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is 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) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + buf.__proto__ = Buffer.prototype + return buf + } + + function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + var buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj) { + if (isArrayBufferView(obj) || 'length' in obj) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } + } + + 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.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 + } + + function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) + } + + Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true + } + + 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] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + } + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + } + + Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer + } + + function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (isArrayBufferView(string) || isArrayBuffer(string)) { + return string.byteLength + } + 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 (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } + } + Buffer.byteLength = byteLength + + function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } + } + + // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) + // to detect a Buffer instance. It's not possible to use `instanceof Buffer` + // reliably in a browserify context because there could be multiple different + // copies of the 'buffer' package in use. This method works even for Buffer + // instances that were created from another copy of the `buffer` package. + // See: https://github.com/feross/buffer/issues/154 + Buffer.prototype._isBuffer = true + + function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this + } + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this + } + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this + } + + Buffer.prototype.toString = function toString () { + var length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + } + + Buffer.prototype.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 + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + 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 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + } + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + } + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + } + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + } + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // 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 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } + } + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + } + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000 + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + newBuf.__proto__ = Buffer.prototype + return newBuf + } + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val + } + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val + } + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] + } + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) + } + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] + } + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + } + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + } + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val + } + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val + } + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + } + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val + } + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val + } + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + } + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + } + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) + } + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) + } + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) + } + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) + } + + function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 + } + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 + } + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 + } + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 + } + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 + } + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 + } + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 + } + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 + } + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + } + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + } + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + } + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + } + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('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) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } + + return len + } + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : new Buffer(val, encoding) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this + } + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray + } + + function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i + } + + // 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) { + return obj instanceof ArrayBuffer || + (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", + "101": "Switching Protocols", + "102": "Processing", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a teapot", + "421": "Misdirected Request", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Unordered Collection", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "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' + if (this.hashMode) { + this[hashMode] = this._finalOrDigest + } else { + this.final = this._finalOrDigest + } + if (this._final) { + this.__final = this._final + this._final = null + } + this._decoder = null + this._encoding = null + } + inherits(CipherBase, Transform) + + CipherBase.prototype.update = function (data, inputEnc, outputEnc) { + if (typeof data === 'string') { + data = Buffer.from(data, inputEnc) + } + + var outData = this._update(data) + if (this.hashMode) return this + + if (outputEnc) { + outData = this._toString(outData, outputEnc) + } + + return outData + } + + CipherBase.prototype.setAutoPadding = function () {} + CipherBase.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state') + } + + CipherBase.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state') + } + + CipherBase.prototype.setAAD = function () { + throw new Error('trying to set aad in unsupported state') + } + + CipherBase.prototype._transform = function (data, _, next) { + var err + try { + if (this.hashMode) { + this._update(data) + } else { + this.push(this._update(data)) + } + } catch (e) { + err = e + } finally { + next(err) + } + } + CipherBase.prototype._flush = function (done) { + var err + try { + this.push(this.__final()) + } catch (e) { + err = e + } + + done(err) + } + CipherBase.prototype._finalOrDigest = function (outputEnc) { + var outData = this.__final() || Buffer.alloc(0) + if (outputEnc) { + outData = this._toString(outData, outputEnc, true) + } + return outData + } + + CipherBase.prototype._toString = function (value, enc, fin) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc) + this._encoding = enc + } + + if (this._encoding !== enc) throw new Error('can\'t switch encodings') + + var out = this._decoder.write(value) + if (fin) { + out += this._decoder.end() + } + + return out + } + + module.exports = CipherBase + + },{"inherits":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; + } catch(_) { + // maybe a reference error because no `Map`. Give it a dummy value that no + // 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. + * + * This function supports circular references by default, but if you are certain + * there are no circular references in your object, you can save some CPU time + * by calling clone(obj, false). + * + * Caution: if `circular` is false and `parent` contains circular references, + * your program may enter an infinite loop and crash. + * + * @param `parent` - the object to be cloned + * @param `circular` - set to true if the object to be cloned may contain + * circular references. (optional - true by default) + * @param `depth` - set to a number if the object is only to be cloned to + * a particular depth. (optional - defaults to Infinity) + * @param `prototype` - sets the prototype to be used when cloning an object. + * (optional - defaults to parent prototype). + * @param `includeNonEnumerable` - set to true if the non-enumerable properties + * should be cloned as well. Non-enumerable properties on the prototype + * chain will be ignored. (optional - false by default) + */ + function clone(parent, circular, depth, prototype, includeNonEnumerable) { + if (typeof circular === 'object') { + depth = circular.depth; + prototype = circular.prototype; + includeNonEnumerable = circular.includeNonEnumerable; + circular = circular.circular; + } + // maintain two arrays for circular references, where corresponding parents + // 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)) { + child = new nativeSet(); + } else if (_instanceof(parent, nativePromise)) { + child = new nativePromise(function (resolve, reject) { + parent.then(function(value) { + resolve(_clone(value, depth - 1)); + }, function(err) { + reject(_clone(err, depth - 1)); + }); + }); + } else if (clone.__isArray(parent)) { + child = []; + } else if (clone.__isRegExp(parent)) { + child = new RegExp(parent.source, __getRegExpFlags(parent)); + if (parent.lastIndex) child.lastIndex = parent.lastIndex; + } else if (clone.__isDate(parent)) { + child = new Date(parent.getTime()); + } else if (useBuffer && Buffer.isBuffer(parent)) { + if (Buffer.allocUnsafe) { + // Node.js >= 4.5.0 + child = Buffer.allocUnsafe(parent.length); + } else { + // Older Node.js versions + child = new Buffer(parent.length); + } + parent.copy(child); + return child; + } else if (_instanceof(parent, Error)) { + child = Object.create(parent); + } else { + if (typeof prototype == 'undefined') { + proto = Object.getPrototypeOf(parent); + child = Object.create(proto); + } + else { + child = Object.create(prototype); + 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); + var valueChild = _clone(value, depth - 1); + child.set(keyChild, valueChild); + }); + } + if (_instanceof(parent, nativeSet)) { + parent.forEach(function(value) { + var entryChild = _clone(value, depth - 1); + 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++) { + // Don't need to worry about cloning a symbol because it is a primitive, + // like a number or string. + var symbol = symbols[i]; + var descriptor = Object.getOwnPropertyDescriptor(parent, symbol); + if (descriptor && !descriptor.enumerable && !includeNonEnumerable) { + continue; + } + child[symbol] = _clone(parent[symbol], depth - 1); + if (!descriptor.enumerable) { + Object.defineProperty(child, symbol, { + enumerable: false + }); + } + } + } + + if (includeNonEnumerable) { + var allPropertyNames = Object.getOwnPropertyNames(parent); + for (var i = 0; i < allPropertyNames.length; i++) { + var propertyName = allPropertyNames[i]; + var descriptor = Object.getOwnPropertyDescriptor(parent, propertyName); + if (descriptor && descriptor.enumerable) { + continue; + } + child[propertyName] = _clone(parent[propertyName], depth - 1); + Object.defineProperty(child, propertyName, { + enumerable: false + }); + } + } + + 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). + * + * USE WITH CAUTION! This may not behave as you wish if you do not know how this + * works. + */ + 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'; + if (re.ignoreCase) flags += 'i'; + if (re.multiline) flags += 'm'; + 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; + this.path = path || "/"; + this.secure = !!secure; + this.script = !!script; + return this; + } + return new CookieAccessInfo(domain, path, secure, script); + } + CookieAccessInfo.All = Object.freeze(Object.create(null)); + exports.CookieAccessInfo = CookieAccessInfo; + + function Cookie(cookiestr, request_domain, request_path) { + if (cookiestr instanceof Cookie) { + return cookiestr; + } + if (this instanceof Cookie) { + this.name = null; + this.value = null; + this.expiration_date = Infinity; + this.path = String(request_path || "/"); + this.explicit_path = false; + this.domain = request_domain || null; + this.explicit_domain = false; + this.secure = false; //how to define default? + this.noscript = false; //httponly + if (cookiestr) { + this.parse(cookiestr, request_domain, request_path); + } + return this; + } + 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) { + str.push("expires=" + (new Date(this.expiration_date)).toGMTString()); + } + if (this.domain) { + str.push("domain=" + this.domain); + } + if (this.path) { + str.push("path=" + this.path); + } + if (this.secure) { + str.push("secure"); + } + if (this.noscript) { + str.push("httponly"); + } + 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) { + var parts = str.split(";").filter(function (value) { + 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(); + value = pair[2]; + switch (key) { + case "httponly": + this.noscript = true; + break; + case "expires": + this.expiration_date = value ? + Number(Date.parse(value)) : + Infinity; + break; + case "path": + this.path = value ? + value.trim() : + ""; + this.explicit_path = true; + break; + case "domain": + this.domain = value ? + value.trim() : + ""; + this.explicit_domain = !!this.domain; + break; + case "secure": + this.secure = true; + 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; + } + if (this.noscript && access_info.script || + this.secure && !access_info.secure || + !this.collidesWith(access_info)) { + return false; + } + return true; + }; + + Cookie.prototype.collidesWith = function collidesWith(access_info) { + if ((this.path && !access_info.path) || (this.domain && !access_info.domain)) { + return false; + } + if (this.path && access_info.path.indexOf(this.path) !== 0) { + return false; + } + if (this.explicit_path && access_info.path.indexOf( this.path ) !== 0) { + return false; + } + var access_domain = access_info.domain && access_info.domain.replace(/^[\.]/,''); + var cookie_domain = this.domain && this.domain.replace(/^[\.]/,''); + if (cookie_domain === access_domain) { + return true; + } + if (cookie_domain) { + if (!this.explicit_domain) { + return false; // we already checked if the domains were exactly the same + } + var wildcard = access_domain.indexOf(cookie_domain); + if (wildcard === -1 || wildcard !== access_domain.length - cookie_domain.length) { + return false; + } + return true; + } + 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); + //Delete the cookie if the set is past the current time + remove = cookie.expiration_date <= Date.now(); + if (cookies[cookie.name] !== undefined) { + cookies_list = cookies[cookie.name]; + for (i = 0; i < cookies_list.length; i += 1) { + collidable_cookie = cookies_list[i]; + if (collidable_cookie.collidesWith(cookie)) { + if (remove) { + cookies_list.splice(i, 1); + if (cookies_list.length === 0) { + delete cookies[cookie.name]; + } + return false; + } + cookies_list[i] = cookie; + return cookie; + } + } + if (remove) { + return false; + } + cookies_list.push(cookie); + return cookie; + } + if (remove) { + return false; + } + cookies[cookie.name] = [cookie]; + return cookies[cookie.name]; + }; + //returns a cookie + this.getCookie = function getCookie(cookie_name, access_info) { + var cookie, i; + cookies_list = cookies[cookie_name]; + if (!cookies_list) { + return; + } + for (i = 0; i < cookies_list.length; i += 1) { + cookie = cookies_list[i]; + if (cookie.expiration_date <= Date.now()) { + if (cookies_list.length === 0) { + delete cookies[cookie.name]; + } + continue; + } + + if (cookie.matches(access_info)) { + return cookie; + } + } + }; + //returns a list of cookies + this.getCookies = function getCookies(access_info) { + var matches = [], cookie_name, cookie; + for (cookie_name in cookies) { + cookie = this.getCookie(cookie_name, access_info); + if (cookie) { + matches.push(cookie); + } + } + matches.toString = function toString() { + return matches.join(":"); + }; + matches.toValueString = function toValueString() { + return matches.map(function (c) { + return c.toValueString(); + }).join(';'); + }; + 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) ? + cookies : + cookies.split(cookie_str_splitter); + var successful = [], + i, + cookie; + cookies = cookies.map(function(item){ + return new Cookie(item, request_domain, request_path); + }); + for (i = 0; i < cookies.length; i += 1) { + cookie = cookies[i]; + if (this.setCookie(cookie, request_domain, request_path)) { + successful.push(cookie); + } + } + return successful; + }; + }()); + + },{}],89:[function(require,module,exports){ + (function (Buffer){ + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + + function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; + } + exports.isArray = isArray; + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + exports.isBoolean = isBoolean; + + function isNull(arg) { + return arg === null; + } + exports.isNull = isNull; + + function isNullOrUndefined(arg) { + return arg == null; + } + exports.isNullOrUndefined = isNullOrUndefined; + + function isNumber(arg) { + return typeof arg === 'number'; + } + exports.isNumber = isNumber; + + function isString(arg) { + return typeof arg === 'string'; + } + exports.isString = isString; + + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + exports.isSymbol = isSymbol; + + function isUndefined(arg) { + return arg === void 0; + } + exports.isUndefined = isUndefined; + + function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; + } + exports.isRegExp = isRegExp; + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + exports.isObject = isObject; + + function isDate(d) { + return objectToString(d) === '[object Date]'; + } + exports.isDate = isDate; + + function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); + } + exports.isError = isError; + + function isFunction(arg) { + return typeof arg === 'function'; + } + exports.isFunction = isFunction; + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + exports.isPrimitive = isPrimitive; + + exports.isBuffer = Buffer.isBuffer; + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) + },{"../../is-buffer/index.js":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', + byteLength: 32 + }, + secp224r1: { + name: 'p224', + byteLength: 28 + }, + prime256v1: { + name: 'p256', + byteLength: 32 + }, + prime192v1: { + name: 'p192', + byteLength: 24 + }, + ed25519: { + name: 'ed25519', + byteLength: 32 + }, + secp384r1: { + name: 'p384', + byteLength: 48 + }, + secp521r1: { + name: 'p521', + 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 ) { + this.curveType = { + name: curve + }; + } + 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)) { + other = new Buffer(other, inenc); + } + var otherPub = this.curve.keyFromPublic(other).getPublic(); + 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') { + if (key[key.length - 1] % 2) { + key[0] = 7; + } else { + key [0] = 6; + } + } + 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)) { + pub = new Buffer(pub, enc); + } + this.keys._importPublic(pub); + return this; + }; + + ECDH.prototype.setPrivateKey = function (priv, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(priv)) { + priv = new Buffer(priv, enc); + } + var _priv = new BN(priv); + _priv = _priv.toString(16); + this.keys._importPrivate(_priv); + return this; + }; + + function formatReturnValue(bn, enc, len) { + if (!Array.isArray(bn)) { + bn = bn.toArray(); + } + var buf = new Buffer(bn); + if (len && buf.length < len) { + var zeros = new Buffer(len - buf.length); + zeros.fill(0); + buf = Buffer.concat([zeros, buf]); + } + if (!enc) { + return buf; + } else { + return buf.toString(enc); + } + } + + }).call(this,require("buffer").Buffer) + },{"bn.js":53,"buffer":84,"elliptic":109}],91:[function(require,module,exports){ + (function (Buffer){ + 'use strict' + var inherits = require('inherits') + 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){ + 'use strict' + 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) + for (var i = 0; i < arr.length; i++) { + buf.writeInt32LE(arr[i], i << 2, true) + } + return buf + } + + }).call(this,require("buffer").Buffer) + },{"buffer":84}],93:[function(require,module,exports){ + 'use strict' + /* + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * 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 + */ + function core_md5 (x, len) { + /* 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) + b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330) + a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897) + d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426) + c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341) + b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983) + a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416) + d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417) + c = md5_ff(c, d, a, b, x[i + 10], 17, -42063) + b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162) + a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682) + 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) + b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302) + a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691) + d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083) + c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335) + b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848) + a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438) + d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690) + c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961) + b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501) + a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467) + 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) + b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556) + a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060) + d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353) + c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632) + b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640) + a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174) + d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222) + c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979) + b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189) + a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487) + 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) + b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055) + a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571) + d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606) + c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523) + b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799) + a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359) + d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744) + c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380) + b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649) + a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070) + 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. + */ + function safe_add (x, y) { + var lsw = (x & 0xFFFF) + (y & 0xFFFF) + 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') + var Legacy = require('./legacy') + var Base = require('cipher-base') + var Buffer = require('safe-buffer').Buffer + var md5 = require('create-hash/md5') + var RIPEMD160 = require('ripemd160') + + var sha = require('sha.js') + + var ZEROS = Buffer.alloc(128) + + function Hmac (alg, key) { + Base.call(this, 'digest') + if (typeof key === 'string') { + key = Buffer.from(key) + } + + var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 + + this._alg = alg + this._key = key + if (key.length > blocksize) { + var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) + key = hash.update(key).digest() + } else if (key.length < blocksize) { + key = Buffer.concat([key, ZEROS], blocksize) + } + + var ipad = this._ipad = Buffer.allocUnsafe(blocksize) + var opad = this._opad = Buffer.allocUnsafe(blocksize) + + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36 + opad[i] = key[i] ^ 0x5C + } + this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) + this._hash.update(ipad) + } + + inherits(Hmac, Base) + + Hmac.prototype._update = function (data) { + this._hash.update(data) + } + + Hmac.prototype._final = function () { + var h = this._hash.digest() + var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg) + return hash.update(this._opad).update(h).digest() + } + + module.exports = function createHmac (alg, key) { + alg = alg.toLowerCase() + if (alg === 'rmd160' || alg === 'ripemd160') { + return new Hmac('rmd160', key) + } + if (alg === 'md5') { + return new Legacy(md5, key) + } + return new Hmac(alg, key) + } + + },{"./legacy":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; } + F.prototype = root; + 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, + blob: 'FileReader' in self && 'Blob' in self && (function() { + try { + new Blob(); + return true + } catch(e) { + return false + } + })(), + formData: 'FormData' in self, + arrayBuffer: 'ArrayBuffer' in self + }; + + if (support.arrayBuffer) { + var viewClasses = [ + '[object Int8Array]', + '[object Uint8Array]', + '[object Uint8ClampedArray]', + '[object Int16Array]', + '[object Uint16Array]', + '[object Int32Array]', + '[object Uint32Array]', + '[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); + } + if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) { + throw new TypeError('Invalid character in header field name') + } + 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 = { + next: function() { + var value = items.shift(); + 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); + }, this); + } else if (Array.isArray(headers)) { + headers.forEach(function(header) { + this.append(header[0], header[1]); + }, this); + } else if (headers) { + Object.getOwnPropertyNames(headers).forEach(function(name) { + this.append(name, headers[name]); + }, 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)) { + callback.call(thisArg, this.map[name], name, this); + } + } + }; + + 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() { + resolve(reader.result); + }; + reader.onerror = function() { + reject(reader.error); + }; + }) + } + + 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) + } else { + var view = new Uint8Array(buf.byteLength); + view.set(new Uint8Array(buf)); + return view.buffer + } + } + + function Body() { + this.bodyUsed = false; + + this._initBody = function(body) { + this._bodyInit = body; + if (!body) { + this._bodyText = ''; + } else if (typeof body === 'string') { + this._bodyText = body; + } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { + this._bodyBlob = body; + } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { + this._bodyFormData = body; + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this._bodyText = body.toString(); + } else if (support.arrayBuffer && support.blob && isDataView(body)) { + this._bodyArrayBuffer = bufferClone(body.buffer); + // IE 10-11 can't handle a DataView body. + this._bodyInit = new Blob([this._bodyArrayBuffer]); + } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) { + this._bodyArrayBuffer = bufferClone(body); + } 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'); + } else if (this._bodyBlob && this._bodyBlob.type) { + this.headers.set('content-type', this._bodyBlob.type); + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); + } + } + }; + + 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) { + return Promise.resolve(new Blob([this._bodyArrayBuffer])) + } else if (this._bodyFormData) { + throw new Error('could not read FormData body as blob') + } else { + return Promise.resolve(new Blob([this._bodyText])) + } + }; + + this.arrayBuffer = function() { + if (this._bodyArrayBuffer) { + return consumed(this) || Promise.resolve(this._bodyArrayBuffer) + } else { + return this.blob().then(readBlobAsArrayBuffer) + } + }; + } + + this.text = function() { + var rejected = consumed(this); + if (rejected) { + return rejected + } + + if (this._bodyBlob) { + return readBlobAsText(this._bodyBlob) + } else if (this._bodyArrayBuffer) { + return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer)) + } else if (this._bodyFormData) { + throw new Error('could not read FormData body as text') + } else { + 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') + } + this.url = input.url; + this.credentials = input.credentials; + if (!options.headers) { + this.headers = new Headers(input.headers); + } + this.method = input.method; + this.mode = input.mode; + if (!body && input._bodyInit != null) { + body = input._bodyInit; + input.bodyUsed = true; + } + } else { + this.url = String(input); + } + + this.credentials = options.credentials || this.credentials || 'omit'; + if (options.headers || !this.headers) { + this.headers = new Headers(options.headers); + } + 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) { + if (bytes) { + var split = bytes.split('='); + var name = split.shift().replace(/\+/g, ' '); + var value = split.join('=').replace(/\+/g, ' '); + form.append(decodeURIComponent(name), decodeURIComponent(value)); + } + }); + 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 + // https://tools.ietf.org/html/rfc7230#section-3.2 + var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' '); + preProcessedHeaders.split(/\r?\n/).forEach(function(line) { + var parts = line.split(':'); + var key = parts.shift().trim(); + if (key) { + var value = parts.join(':').trim(); + headers.append(key, value); + } + }); + 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; + this.statusText = 'statusText' in options ? options.statusText : 'OK'; + this.headers = new Headers(options.headers); + this.url = options.url || ''; + this._initBody(bodyInit); + } + + Body.call(Response.prototype); + + Response.prototype.clone = function() { + return new Response(this._bodyInit, { + status: this.status, + statusText: this.statusText, + headers: new Headers(this.headers), + 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, + statusText: xhr.statusText, + headers: parseHeaders(xhr.getAllResponseHeaders() || '') + }; + options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL'); + 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); + }) + }; + self.fetch.polyfill = true; + })(typeof self !== 'undefined' ? self : this); + }).call(__root__, void(0)); + var fetch = __root__.fetch; + var Response = fetch.Response = __root__.Response; + var Request = fetch.Request = __root__.Request; + var Headers = fetch.Headers = __root__.Headers; + if (typeof module === 'object' && module.exports) { + module.exports = fetch; + // 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 + exports.createCipheriv = aes.createCipheriv + exports.Decipher = aes.Decipher + exports.createDecipher = aes.createDecipher + exports.Decipheriv = aes.Decipheriv + 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' + // ].forEach(function (name) { + // exports[name] = function () { + // throw new Error([ + // 'sorry, ' + name + ' is not implemented yet', + // 'we accept pull requests', + // 'https://github.com/crypto-browserify/crypto-browserify' + // ].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', + 'we accept pull requests', + 'https://github.com/crypto-browserify/crypto-browserify' + ].join('\n')) + } + + exports.constants = { + 'DH_CHECK_P_NOT_SAFE_PRIME': 2, + 'DH_CHECK_P_NOT_PRIME': 1, + 'DH_UNABLE_TO_CHECK_GENERATOR': 4, + 'DH_NOT_SUITABLE_GENERATOR': 8, + 'NPN_ENABLED': 1, + 'ALPN_ENABLED': 1, + 'RSA_PKCS1_PADDING': 1, + 'RSA_SSLV23_PADDING': 2, + 'RSA_NO_PADDING': 3, + 'RSA_PKCS1_OAEP_PADDING': 4, + 'RSA_X931_PADDING': 5, + 'RSA_PKCS1_PSS_PADDING': 6, + 'POINT_CONVERSION_COMPRESSED': 2, + '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 + return decodeURIComponent(components.join('')); + } catch (err) { + // Do nothing + } + + if (components.length === 1) { + return components; + } + + split = split || 1; + + // Split the array in 2 parts + var left = components.slice(0, split); + var right = components.slice(split); + + return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right)); + } + + function decode(input) { + try { + return decodeURIComponent(input); + } catch (err) { + var tokens = input.match(singleMatcher); + + for (var i = 1; i < tokens.length; i++) { + input = decodeComponents(tokens, i).join(''); + + tokens = input.match(singleMatcher); + } + + return input; + } + } + + function customDecodeURIComponent(input) { + // Keep track of all the replacements and prefill the map with the `BOM` + var replaceMap = { + '%FE%FF': '\uFFFD\uFFFD', + '%FF%FE': '\uFFFD\uFFFD' + }; + + var match = multiMatcher.exec(input); + while (match) { + try { + // Decode as big chunks as possible + replaceMap[match[0]] = decodeURIComponent(match[0]); + } catch (err) { + var result = decode(match[0]); + + if (result !== match[0]) { + replaceMap[match[0]] = result; + } + } + + match = multiMatcher.exec(input); + } + + // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else + replaceMap['%C2'] = '\uFFFD'; + + var entries = Object.keys(replaceMap); + + for (var i = 0; i < entries.length; i++) { + // Replace all decoded components + var key = entries[i]; + input = input.replace(new RegExp(key, 'g'), replaceMap[key]); + } + + return input; + } + + module.exports = function (encodedURI) { + if (typeof encodedURI !== 'string') { + throw new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`'); + } + + try { + encodedURI = encodedURI.replace(/\+/g, ' '); + + // Try the built in decoder first + return decodeURIComponent(encodedURI); + } catch (err) { + // Fallback to a more advanced decoder + return customDecodeURIComponent(encodedURI); + } + }; + + },{}],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]; + for (var i = 0; i < state.keys.length; i += 2) { + var shift = shiftTable[i >>> 1]; + kL = utils.r28shl(kL, shift); + kR = utils.r28shl(kR, shift); + 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 }), + DES.create({ type: 'decrypt', key: k2 }), + DES.create({ type: 'encrypt', key: k3 }) + ]; + } else { + this.ciphers = [ + DES.create({ type: 'decrypt', key: k3 }), + DES.create({ type: 'encrypt', key: k2 }), + DES.create({ type: 'decrypt', key: k1 }) + ]; + } + } + + 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) | + (bytes[2 + off] << 8) | + 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; + outL |= (inR >>> (j + i)) & 1; + } + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inL >>> (j + i)) & 1; + } + } + + for (var i = 6; i >= 0; i -= 2) { + for (var j = 1; j <= 25; j += 8) { + outR <<= 1; + outR |= (inR >>> (j + i)) & 1; + } + for (var j = 1; j <= 25; j += 8) { + outR <<= 1; + 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; + outL |= (inR >>> (j + i)) & 1; + outL <<= 1; + outL |= (inL >>> (j + i)) & 1; + } + } + for (var i = 4; i < 8; i++) { + for (var j = 24; j >= 0; j -= 8) { + outR <<= 1; + outR |= (inR >>> (j + i)) & 1; + outR <<= 1; + 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 + // 4, 12, 20, 28 + for (var i = 7; i >= 5; i--) { + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inR >> (j + i)) & 1; + } + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inL >> (j + i)) & 1; + } + } + for (var j = 0; j <= 24; j += 8) { + 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 + // 36, 44, 52, 60 + for (var i = 1; i <= 3; i++) { + for (var j = 0; j <= 24; j += 8) { + outR <<= 1; + outR |= (inR >> (j + i)) & 1; + } + for (var j = 0; j <= 24; j += 8) { + outR <<= 1; + outR |= (inL >> (j + i)) & 1; + } + } + for (var j = 0; j <= 24; j += 8) { + 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; + outL |= (inL >>> pc2table[i]) & 0x1; + } + for (var i = len; i < pc2table.length; i++) { + 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; + outL |= (r >>> i) & 0x3f; + } + for (var i = 11; i >= 3; i -= 4) { + outR |= (r >>> i) & 0x3f; + 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++) { + out <<= 1; + out |= (num >>> permuteTable[i]) & 0x1; + } + 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){ + var BN = require('bn.js'); + var MillerRabin = require('miller-rabin'); + var millerRabin = new MillerRabin(); + var TWENTYFOUR = new BN(24); + var ELEVEN = new BN(11); + var TEN = new BN(10); + var THREE = new BN(3); + var SEVEN = new BN(7); + var primes = require('./generatePrime'); + var randomBytes = require('randombytes'); + module.exports = DH; + + function setPublicKey(pub, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(pub)) { + pub = new Buffer(pub, enc); + } + this._pub = new BN(pub); + return this; + } + + function setPrivateKey(priv, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(priv)) { + priv = new Buffer(priv, enc); + } + this._priv = new BN(priv); + return this; + } + + var primeCache = {}; + function checkPrime(prime, generator) { + var gen = generator.toString('hex'); + var hex = [gen, prime.toString(16)].join('_'); + if (hex in primeCache) { + 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 + error += 8; + } else { + //we wouldn't be able to test the generator + // so +4 + error += 4; + } + primeCache[hex] = error; + return error; + } + if (!millerRabin.test(prime.shrn(1))) { + //not a safe prime + error += 2; + } + var rem; + switch (gen) { + case '02': + if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) { + // unsuidable generator + error += 8; + } + break; + case '05': + rem = prime.mod(TEN); + if (rem.cmp(THREE) && rem.cmp(SEVEN)) { + // prime mod 10 needs to equal 3 or 7 + error += 8; + } + break; + default: + error += 4; + } + primeCache[hex] = error; + return error; + } + + function DH(prime, generator, malleable) { + this.setGenerator(generator); + this.__prime = new BN(prime); + this._prime = BN.mont(this.__prime); + this._primeLen = prime.length; + this._pub = undefined; + this._priv = undefined; + this._primeCode = undefined; + if (malleable) { + this.setPublicKey = setPublicKey; + this.setPrivateKey = setPrivateKey; + } else { + this._primeCode = 8; + } + } + Object.defineProperty(DH.prototype, 'verifyError', { + enumerable: true, + get: function () { + if (typeof this._primeCode !== 'number') { + this._primeCode = checkPrime(this.__prime, this.__gen); + } + return this._primeCode; + } + }); + DH.prototype.generateKeys = function () { + if (!this._priv) { + this._priv = new BN(randomBytes(this._primeLen)); + } + 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); + var secret = other.redPow(this._priv).fromRed(); + var out = new Buffer(secret.toArray()); + var prime = this.getPrime(); + if (out.length < prime.length) { + var front = new Buffer(prime.length - out.length); + front.fill(0); + out = Buffer.concat([front, out]); + } + 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)) { + gen = new Buffer(gen, enc); + } + this.__gen = gen; + this._gen = new BN(gen); + return this; + }; + + function formatReturnValue(bn, enc) { + var buf = new Buffer(bn.toArray()); + if (!enc) { + return buf; + } else { + 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'); + module.exports = findPrime; + findPrime.simpleSieve = simpleSieve; + findPrime.fermatTest = fermatTest; + var BN = require('bn.js'); + var TWENTYFOUR = new BN(24); + var MillerRabin = require('miller-rabin'); + var millerRabin = new MillerRabin(); + var ONE = new BN(1); + var TWO = new BN(2); + var FIVE = new BN(5); + var SIXTEEN = new BN(16); + var EIGHT = new BN(8); + var TEN = new BN(10); + var THREE = new BN(3); + var SEVEN = new BN(7); + var ELEVEN = new BN(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; + for (var i = 1, k = 3; k < limit; k += 2) { + var sqrt = Math.ceil(Math.sqrt(k)); + 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) { + return true; + } else { + 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 + if (gen === 2 || gen === 5) { + return new BN([0x8c, 0x7b]); + } else { + return new BN([0x8c, 0x27]); + } + } + gen = new BN(gen); + + var num, n2; + + while (true) { + num = new BN(randomBytes(Math.ceil(bits / 8))); + while (num.bitLength() > bits) { + num.ishrn(1); + } + if (num.isEven()) { + num.iadd(ONE); + } + if (!num.testn(1)) { + num.iadd(TWO); + } + if (!gen.cmp(TWO)) { + while (num.mod(TWENTYFOUR).cmp(ELEVEN)) { + num.iadd(FOUR); + } + } else if (!gen.cmp(FIVE)) { + while (num.mod(TEN).cmp(THREE)) { + num.iadd(FOUR); + } + } + n2 = num.shrn(1); + if (simpleSieve(n2) && simpleSieve(num) && + fermatTest(n2) && fermatTest(num) && + millerRabin.test(n2) && millerRabin.test(num)) { + return num; + } + } + + } + + },{"bn.js":53,"miller-rabin":233,"randombytes":270}],108:[function(require,module,exports){ + module.exports={ + "modp1": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff" + }, + "modp2": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff" + }, + "modp5": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff" + }, + "modp14": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff" + }, + "modp15": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff" + }, + "modp16": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff" + }, + "modp17": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff" + }, + "modp18": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff" + } + } + },{}],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) { + this.redN = null; + } else { + this._maxwellTrick = true; + this.redN = this.n.toRed(this.red); + } + } + module.exports = BaseCurve; + + BaseCurve.prototype.point = function point() { + throw new Error('Not implemented'); + }; + + BaseCurve.prototype.validate = function validate() { + throw new Error('Not implemented'); + }; + + BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { + assert(p.precomputed); + var doubles = p._getDoubles(); + + var naf = getNAF(k, 1); + var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); + I /= 3; + + // Translate into more windowed form + var repr = []; + for (var j = 0; j < naf.length; j += doubles.step) { + var nafW = 0; + for (var k = j + doubles.step - 1; k >= j; k--) + nafW = (nafW << 1) + naf[k]; + repr.push(nafW); + } + + var a = this.jpoint(null, null, null); + var b = this.jpoint(null, null, null); + for (var i = I; i > 0; i--) { + for (var j = 0; j < repr.length; j++) { + var nafW = repr[j]; + if (nafW === i) + b = b.mixedAdd(doubles.points[j]); + else if (nafW === -i) + b = b.mixedAdd(doubles.points[j].neg()); + } + a = a.add(b); + } + return a.toP(); + }; + + BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { + var w = 4; + + // Precompute window + var nafPoints = p._getNAFPoints(w); + w = nafPoints.wnd; + var wnd = nafPoints.points; + + // Get NAF form + var naf = getNAF(k, w); + + // Add `this`*(N+1) for every w-NAF index + var acc = this.jpoint(null, null, null); + for (var i = naf.length - 1; i >= 0; i--) { + // Count zeroes + for (var k = 0; i >= 0 && naf[i] === 0; i--) + k++; + if (i >= 0) + k++; + acc = acc.dblp(k); + + if (i < 0) + break; + var z = naf[i]; + assert(z !== 0); + if (p.type === 'affine') { + // J +- P + if (z > 0) + acc = acc.mixedAdd(wnd[(z - 1) >> 1]); + else + acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); + } else { + // J +- J + if (z > 0) + acc = acc.add(wnd[(z - 1) >> 1]); + else + acc = acc.add(wnd[(-z - 1) >> 1].neg()); + } + } + return p.type === 'affine' ? acc.toP() : acc; + }; + + BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, + points, + coeffs, + len, + jacobianResult) { + var wndWidth = this._wnafT1; + var wnd = this._wnafT2; + var naf = this._wnafT3; + + // Fill all arrays + var max = 0; + for (var i = 0; i < len; i++) { + var p = points[i]; + var nafPoints = p._getNAFPoints(defW); + wndWidth[i] = nafPoints.wnd; + wnd[i] = nafPoints.points; + } + + // Comb small window NAFs + for (var i = len - 1; i >= 1; i -= 2) { + var a = i - 1; + var b = i; + if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { + naf[a] = getNAF(coeffs[a], wndWidth[a]); + naf[b] = getNAF(coeffs[b], wndWidth[b]); + max = Math.max(naf[a].length, max); + max = Math.max(naf[b].length, max); + continue; + } + + var comb = [ + points[a], /* 1 */ + null, /* 3 */ + null, /* 5 */ + points[b] /* 7 */ + ]; + + // Try to avoid Projective points, if possible + if (points[a].y.cmp(points[b].y) === 0) { + comb[1] = points[a].add(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].add(points[b].neg()); + } else { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } + + var index = [ + -3, /* -1 -1 */ + -1, /* -1 0 */ + -5, /* -1 1 */ + -7, /* 0 -1 */ + 0, /* 0 0 */ + 7, /* 0 1 */ + 5, /* 1 -1 */ + 1, /* 1 0 */ + 3 /* 1 1 */ + ]; + + var jsf = getJSF(coeffs[a], coeffs[b]); + max = Math.max(jsf[0].length, max); + naf[a] = new Array(max); + naf[b] = new Array(max); + for (var j = 0; j < max; j++) { + var ja = jsf[0][j] | 0; + var jb = jsf[1][j] | 0; + + naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; + naf[b][j] = 0; + wnd[a] = comb; + } + } + + var acc = this.jpoint(null, null, null); + var tmp = this._wnafT4; + for (var i = max; i >= 0; i--) { + var k = 0; + + while (i >= 0) { + var zero = true; + for (var j = 0; j < len; j++) { + tmp[j] = naf[j][i] | 0; + if (tmp[j] !== 0) + zero = false; + } + if (!zero) + break; + k++; + i--; + } + if (i >= 0) + k++; + acc = acc.dblp(k); + if (i < 0) + break; + + for (var j = 0; j < len; j++) { + var z = tmp[j]; + var p; + if (z === 0) + continue; + else if (z > 0) + p = wnd[j][(z - 1) >> 1]; + else if (z < 0) + p = wnd[j][(-z - 1) >> 1].neg(); + + if (p.type === 'affine') + acc = acc.mixedAdd(p); + else + acc = acc.add(p); + } + } + // Zeroify references + for (var i = 0; i < len; i++) + wnd[i] = null; + + if (jacobianResult) + return acc; + else + return acc.toP(); + }; + + function BasePoint(curve, type) { + this.curve = curve; + this.type = type; + this.precomputed = null; + } + BaseCurve.BasePoint = BasePoint; + + BasePoint.prototype.eq = function eq(/*other*/) { + throw new Error('Not implemented'); + }; + + BasePoint.prototype.validate = function validate() { + return this.curve.validate(this); + }; + + BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + bytes = utils.toArray(bytes, enc); + + var len = this.p.byteLength(); + + // uncompressed, hybrid-odd, hybrid-even + if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) && + bytes.length - 1 === 2 * len) { + if (bytes[0] === 0x06) + assert(bytes[bytes.length - 1] % 2 === 0); + else if (bytes[0] === 0x07) + assert(bytes[bytes.length - 1] % 2 === 1); + + var res = this.point(bytes.slice(1, 1 + len), + bytes.slice(1 + len, 1 + 2 * len)); + + return res; + } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && + bytes.length - 1 === len) { + return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03); + } + throw new Error('Unknown point format'); + }; + + BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { + return this.encode(enc, true); + }; + + BasePoint.prototype._encode = function _encode(compact) { + var len = this.curve.p.byteLength(); + var x = this.getX().toArray('be', len); + + if (compact) + return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); + + return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ; + }; + + BasePoint.prototype.encode = function encode(enc, compact) { + return utils.encode(this._encode(compact), enc); + }; + + BasePoint.prototype.precompute = function precompute(power) { + if (this.precomputed) + return this; + + var precomputed = { + doubles: null, + naf: null, + beta: null + }; + precomputed.naf = this._getNAFPoints(8); + precomputed.doubles = this._getDoubles(4, power); + precomputed.beta = this._getBeta(); + this.precomputed = precomputed; + + return this; + }; + + BasePoint.prototype._hasDoubles = function _hasDoubles(k) { + if (!this.precomputed) + return false; + + var doubles = this.precomputed.doubles; + if (!doubles) + return false; + + return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); + }; + + BasePoint.prototype._getDoubles = function _getDoubles(step, power) { + if (this.precomputed && this.precomputed.doubles) + return this.precomputed.doubles; + + var doubles = [ this ]; + var acc = this; + for (var i = 0; i < power; i += step) { + for (var j = 0; j < step; j++) + acc = acc.dbl(); + doubles.push(acc); + } + return { + step: step, + points: doubles + }; + }; + + BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { + if (this.precomputed && this.precomputed.naf) + return this.precomputed.naf; + + var res = [ this ]; + var max = (1 << wnd) - 1; + var dbl = max === 1 ? null : this.dbl(); + for (var i = 1; i < max; i++) + res[i] = res[i - 1].add(dbl); + return { + wnd: wnd, + points: res + }; + }; + + BasePoint.prototype._getBeta = function _getBeta() { + return null; + }; + + BasePoint.prototype.dblp = function dblp(k) { + var r = this; + for (var i = 0; i < k; i++) + r = r.dbl(); + return r; + }; + + },{"../../elliptic":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) { + this.x = this.curve.zero; + this.y = this.curve.one; + this.z = this.curve.one; + this.t = this.curve.zero; + this.zOne = true; + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + this.z = z ? new BN(z, 16) : this.curve.one; + this.t = t && new BN(t, 16); + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + if (this.t && !this.t.red) + this.t = this.t.toRed(this.curve.red); + this.zOne = this.z === this.curve.one; + + // Use extended coordinates + if (this.curve.extended && !this.t) { + this.t = this.x.redMul(this.y); + if (!this.zOne) + this.t = this.t.redMul(this.z.redInvm()); + } + } + } + inherits(Point, Base.BasePoint); + + EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); + }; + + EdwardsCurve.prototype.point = function point(x, y, z, t) { + return new Point(this, x, y, z, t); + }; + + Point.fromJSON = function fromJSON(curve, obj) { + return new Point(curve, obj[0], obj[1], obj[2]); + }; + + Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; + + Point.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.x.cmpn(0) === 0 && + this.y.cmp(this.z) === 0; + }; + + Point.prototype._extDbl = function _extDbl() { + // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html + // #doubling-dbl-2008-hwcd + // 4M + 4S + + // A = X1^2 + var a = this.x.redSqr(); + // B = Y1^2 + var b = this.y.redSqr(); + // C = 2 * Z1^2 + var c = this.z.redSqr(); + c = c.redIAdd(c); + // D = a * A + var d = this.curve._mulA(a); + // E = (X1 + Y1)^2 - A - B + var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); + // G = D + B + var g = d.redAdd(b); + // F = G - C + var f = g.redSub(c); + // H = D - B + var h = d.redSub(b); + // X3 = E * F + var nx = e.redMul(f); + // Y3 = G * H + var ny = g.redMul(h); + // T3 = E * H + var nt = e.redMul(h); + // Z3 = F * G + var nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); + }; + + Point.prototype._projDbl = function _projDbl() { + // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html + // #doubling-dbl-2008-bbjlp + // #doubling-dbl-2007-bl + // and others + // Generally 3M + 4S or 2M + 4S + + // B = (X1 + Y1)^2 + var b = this.x.redAdd(this.y).redSqr(); + // C = X1^2 + var c = this.x.redSqr(); + // D = Y1^2 + var d = this.y.redSqr(); + + var nx; + var ny; + var nz; + if (this.curve.twisted) { + // E = a * C + var e = this.curve._mulA(c); + // F = E + D + var f = e.redAdd(d); + if (this.zOne) { + // X3 = (B - C - D) * (F - 2) + nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); + // Y3 = F * (E - D) + ny = f.redMul(e.redSub(d)); + // Z3 = F^2 - 2 * F + nz = f.redSqr().redSub(f).redSub(f); + } else { + // H = Z1^2 + var h = this.z.redSqr(); + // J = F - 2 * H + var j = f.redSub(h).redISub(h); + // X3 = (B-C-D)*J + nx = b.redSub(c).redISub(d).redMul(j); + // Y3 = F * (E - D) + ny = f.redMul(e.redSub(d)); + // Z3 = F * J + nz = f.redMul(j); + } + } else { + // E = C + D + var e = c.redAdd(d); + // H = (c * Z1)^2 + var h = this.curve._mulC(this.c.redMul(this.z)).redSqr(); + // J = E - 2 * H + var j = e.redSub(h).redSub(h); + // X3 = c * (B - E) * J + nx = this.curve._mulC(b.redISub(e)).redMul(j); + // Y3 = c * E * (C - D) + ny = this.curve._mulC(e).redMul(c.redISub(d)); + // Z3 = E * J + nz = e.redMul(j); + } + return this.curve.point(nx, ny, nz); + }; + + Point.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + + // Double in extended coordinates + if (this.curve.extended) + return this._extDbl(); + else + return this._projDbl(); + }; + + Point.prototype._extAdd = function _extAdd(p) { + // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html + // #addition-add-2008-hwcd-3 + // 8M + + // A = (Y1 - X1) * (Y2 - X2) + var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); + // B = (Y1 + X1) * (Y2 + X2) + var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); + // C = T1 * k * T2 + var c = this.t.redMul(this.curve.dd).redMul(p.t); + // D = Z1 * 2 * Z2 + var d = this.z.redMul(p.z.redAdd(p.z)); + // E = B - A + var e = b.redSub(a); + // F = D - C + var f = d.redSub(c); + // G = D + C + var g = d.redAdd(c); + // H = B + A + var h = b.redAdd(a); + // X3 = E * F + var nx = e.redMul(f); + // Y3 = G * H + var ny = g.redMul(h); + // T3 = E * H + var nt = e.redMul(h); + // Z3 = F * G + var nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); + }; + + Point.prototype._projAdd = function _projAdd(p) { + // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html + // #addition-add-2008-bbjlp + // #addition-add-2007-bl + // 10M + 1S + + // A = Z1 * Z2 + var a = this.z.redMul(p.z); + // B = A^2 + var b = a.redSqr(); + // C = X1 * X2 + var c = this.x.redMul(p.x); + // D = Y1 * Y2 + var d = this.y.redMul(p.y); + // E = d * C * D + var e = this.curve.d.redMul(c).redMul(d); + // F = B - E + var f = b.redSub(e); + // G = B + E + var g = b.redAdd(e); + // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) + var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); + var nx = a.redMul(f).redMul(tmp); + var ny; + var nz; + if (this.curve.twisted) { + // Y3 = A * G * (D - a * C) + ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); + // Z3 = F * G + nz = f.redMul(g); + } else { + // Y3 = A * G * (D - C) + ny = a.redMul(g).redMul(d.redSub(c)); + // Z3 = c * F * G + nz = this.curve._mulC(f).redMul(g); + } + return this.curve.point(nx, ny, nz); + }; + + Point.prototype.add = function add(p) { + if (this.isInfinity()) + return p; + if (p.isInfinity()) + return this; + + if (this.curve.extended) + return this._extAdd(p); + else + return this._projAdd(p); + }; + + Point.prototype.mul = function mul(k) { + if (this._hasDoubles(k)) + return this.curve._fixedNafMul(this, k); + else + return this.curve._wnafMul(this, k); + }; + + Point.prototype.mulAdd = function mulAdd(k1, p, k2) { + return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); + }; + + Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) { + return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); + }; + + Point.prototype.normalize = function normalize() { + if (this.zOne) + return this; + + // Normalize coordinates + var zi = this.z.redInvm(); + this.x = this.x.redMul(zi); + this.y = this.y.redMul(zi); + if (this.t) + this.t = this.t.redMul(zi); + this.z = this.curve.one; + this.zOne = true; + return this; + }; + + Point.prototype.neg = function neg() { + return this.curve.point(this.x.redNeg(), + this.y, + this.z, + this.t && this.t.redNeg()); + }; + + Point.prototype.getX = function getX() { + this.normalize(); + return this.x.fromRed(); + }; + + Point.prototype.getY = function getY() { + this.normalize(); + return this.y.fromRed(); + }; + + Point.prototype.eq = function eq(other) { + return this === other || + this.getX().cmp(other.getX()) === 0 && + this.getY().cmp(other.getY()) === 0; + }; + + Point.prototype.eqXToP = function eqXToP(x) { + var rx = x.toRed(this.curve.red).redMul(this.z); + if (this.x.cmp(rx) === 0) + return true; + + var xc = x.clone(); + var t = this.curve.redN.redMul(this.z); + for (;;) { + xc.iadd(this.curve.n); + if (xc.cmp(this.curve.p) >= 0) + return false; + + rx.redIAdd(t); + if (this.x.cmp(rx) === 0) + return true; + } + 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(); + this.two = new BN(2).toRed(this.red); + this.a24 = this.i4.redMul(this.a.redAdd(this.two)); + } + inherits(MontCurve, Base); + module.exports = MontCurve; + + MontCurve.prototype.validate = function validate(point) { + var x = point.normalize().x; + var x2 = x.redSqr(); + var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); + var y = rhs.redSqrt(); + + return y.redSqr().cmp(rhs) === 0; + }; + + function Point(curve, x, z) { + Base.BasePoint.call(this, curve, 'projective'); + if (x === null && z === null) { + this.x = this.curve.one; + this.z = this.curve.zero; + } else { + this.x = new BN(x, 16); + this.z = new BN(z, 16); + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + } + } + inherits(Point, Base.BasePoint); + + MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + return this.point(utils.toArray(bytes, enc), 1); + }; + + MontCurve.prototype.point = function point(x, z) { + return new Point(this, x, z); + }; + + MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); + }; + + Point.prototype.precompute = function precompute() { + // No-op + }; + + Point.prototype._encode = function _encode() { + return this.getX().toArray('be', this.curve.p.byteLength()); + }; + + Point.fromJSON = function fromJSON(curve, obj) { + return new Point(curve, obj[0], obj[1] || curve.one); + }; + + Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; + + Point.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; + }; + + Point.prototype.dbl = function dbl() { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 + // 2M + 2S + 4A + + // A = X1 + Z1 + var a = this.x.redAdd(this.z); + // AA = A^2 + var aa = a.redSqr(); + // B = X1 - Z1 + var b = this.x.redSub(this.z); + // BB = B^2 + var bb = b.redSqr(); + // C = AA - BB + var c = aa.redSub(bb); + // X3 = AA * BB + var nx = aa.redMul(bb); + // Z3 = C * (BB + A24 * C) + var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); + return this.curve.point(nx, nz); + }; + + Point.prototype.add = function add() { + throw new Error('Not supported on Montgomery curve'); + }; + + Point.prototype.diffAdd = function diffAdd(p, diff) { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 + // 4M + 2S + 6A + + // A = X2 + Z2 + var a = this.x.redAdd(this.z); + // B = X2 - Z2 + var b = this.x.redSub(this.z); + // C = X3 + Z3 + var c = p.x.redAdd(p.z); + // D = X3 - Z3 + var d = p.x.redSub(p.z); + // DA = D * A + var da = d.redMul(a); + // CB = C * B + var cb = c.redMul(b); + // X5 = Z1 * (DA + CB)^2 + var nx = diff.z.redMul(da.redAdd(cb).redSqr()); + // Z5 = X1 * (DA - CB)^2 + var nz = diff.x.redMul(da.redISub(cb).redSqr()); + return this.curve.point(nx, nz); + }; + + Point.prototype.mul = function mul(k) { + var t = k.clone(); + var a = this; // (N / 2) * Q + Q + var b = this.curve.point(null, null); // (N / 2) * Q + var c = this; // Q + + for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) + bits.push(t.andln(1)); + + for (var i = bits.length - 1; i >= 0; i--) { + if (bits[i] === 0) { + // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q + a = a.diffAdd(b, c); + // N * Q = 2 * ((N / 2) * Q + Q)) + b = b.dbl(); + } else { + // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) + b = a.diffAdd(b, c); + // N * Q + Q = 2 * ((N / 2) * Q + Q) + a = a.dbl(); + } + } + return b; + }; + + Point.prototype.mulAdd = function mulAdd() { + throw new Error('Not supported on Montgomery curve'); + }; + + Point.prototype.jumlAdd = function jumlAdd() { + throw new Error('Not supported on Montgomery curve'); + }; + + Point.prototype.eq = function eq(other) { + return this.getX().cmp(other.getX()) === 0; + }; + + Point.prototype.normalize = function normalize() { + this.x = this.x.redMul(this.z.redInvm()); + this.z = this.curve.one; + return this; + }; + + Point.prototype.getX = function getX() { + // Normalize coordinates + this.normalize(); + + return this.x.fromRed(); + }; + + },{"../../elliptic":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); + this._endoWnafT2 = new Array(4); + } + inherits(ShortCurve, Base); + module.exports = ShortCurve; + + ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { + // No efficient endomorphism + if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) + return; + + // Compute beta and lambda, that lambda * P = (beta * Px; Py) + var beta; + var lambda; + if (conf.beta) { + beta = new BN(conf.beta, 16).toRed(this.red); + } else { + var betas = this._getEndoRoots(this.p); + // Choose the smallest beta + beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; + beta = beta.toRed(this.red); + } + if (conf.lambda) { + lambda = new BN(conf.lambda, 16); + } else { + // Choose the lambda that is matching selected beta + var lambdas = this._getEndoRoots(this.n); + if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { + lambda = lambdas[0]; + } else { + lambda = lambdas[1]; + assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); + } + } + + // Get basis vectors, used for balanced length-two representation + var basis; + if (conf.basis) { + basis = conf.basis.map(function(vec) { + return { + a: new BN(vec.a, 16), + b: new BN(vec.b, 16) + }; + }); + } else { + basis = this._getEndoBasis(lambda); + } + + return { + beta: beta, + lambda: lambda, + basis: basis + }; + }; + + ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { + // Find roots of for x^2 + x + 1 in F + // Root = (-1 +- Sqrt(-3)) / 2 + // + var red = num === this.p ? this.red : BN.mont(num); + var tinv = new BN(2).toRed(red).redInvm(); + var ntinv = tinv.redNeg(); + + var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv); + + var l1 = ntinv.redAdd(s).fromRed(); + var l2 = ntinv.redSub(s).fromRed(); + return [ l1, l2 ]; + }; + + ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { + // aprxSqrt >= sqrt(this.n) + var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); + + // 3.74 + // Run EGCD, until r(L + 1) < aprxSqrt + var u = lambda; + var v = this.n.clone(); + var x1 = new BN(1); + var y1 = new BN(0); + var x2 = new BN(0); + var y2 = new BN(1); + + // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) + var a0; + var b0; + // First vector + var a1; + var b1; + // Second vector + var a2; + var b2; + + var prevR; + var i = 0; + var r; + var x; + while (u.cmpn(0) !== 0) { + var q = v.div(u); + r = v.sub(q.mul(u)); + x = x2.sub(q.mul(x1)); + var y = y2.sub(q.mul(y1)); + + if (!a1 && r.cmp(aprxSqrt) < 0) { + a0 = prevR.neg(); + b0 = x1; + a1 = r.neg(); + b1 = x; + } else if (a1 && ++i === 2) { + break; + } + prevR = r; + + v = u; + u = r; + x2 = x1; + x1 = x; + y2 = y1; + y1 = y; + } + a2 = r.neg(); + b2 = x; + + var len1 = a1.sqr().add(b1.sqr()); + var len2 = a2.sqr().add(b2.sqr()); + if (len2.cmp(len1) >= 0) { + a2 = a0; + b2 = b0; + } + + // Normalize signs + if (a1.negative) { + a1 = a1.neg(); + b1 = b1.neg(); + } + if (a2.negative) { + a2 = a2.neg(); + b2 = b2.neg(); + } + + return [ + { a: a1, b: b1 }, + { a: a2, b: b2 } + ]; + }; + + ShortCurve.prototype._endoSplit = function _endoSplit(k) { + var basis = this.endo.basis; + var v1 = basis[0]; + var v2 = basis[1]; + + var c1 = v2.b.mul(k).divRound(this.n); + var c2 = v1.b.neg().mul(k).divRound(this.n); + + var p1 = c1.mul(v1.a); + var p2 = c2.mul(v2.a); + var q1 = c1.mul(v1.b); + var q2 = c2.mul(v2.b); + + // Calculate answer + var k1 = k.sub(p1).sub(p2); + var k2 = q1.add(q2).neg(); + return { k1: k1, k2: k2 }; + }; + + ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN(x, 16); + if (!x.red) + x = x.toRed(this.red); + + var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); + var y = y2.redSqrt(); + if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) + throw new Error('invalid point'); + + // XXX Is there any way to tell if the number is odd without converting it + // to non-red form? + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) + y = y.redNeg(); + + return this.point(x, y); + }; + + ShortCurve.prototype.validate = function validate(point) { + if (point.inf) + return true; + + var x = point.x; + var y = point.y; + + var ax = this.a.redMul(x); + var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); + return y.redSqr().redISub(rhs).cmpn(0) === 0; + }; + + ShortCurve.prototype._endoWnafMulAdd = + function _endoWnafMulAdd(points, coeffs, jacobianResult) { + var npoints = this._endoWnafT1; + var ncoeffs = this._endoWnafT2; + for (var i = 0; i < points.length; i++) { + var split = this._endoSplit(coeffs[i]); + var p = points[i]; + var beta = p._getBeta(); + + if (split.k1.negative) { + split.k1.ineg(); + p = p.neg(true); + } + if (split.k2.negative) { + split.k2.ineg(); + beta = beta.neg(true); + } + + npoints[i * 2] = p; + npoints[i * 2 + 1] = beta; + ncoeffs[i * 2] = split.k1; + ncoeffs[i * 2 + 1] = split.k2; + } + var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult); + + // Clean-up references to points and coefficients + for (var j = 0; j < i * 2; j++) { + npoints[j] = null; + ncoeffs[j] = null; + } + return res; + }; + + function Point(curve, x, y, isRed) { + Base.BasePoint.call(this, curve, 'affine'); + if (x === null && y === null) { + this.x = null; + this.y = null; + this.inf = true; + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + // Force redgomery representation when loading from JSON + if (isRed) { + this.x.forceRed(this.curve.red); + this.y.forceRed(this.curve.red); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + this.inf = false; + } + } + inherits(Point, Base.BasePoint); + + ShortCurve.prototype.point = function point(x, y, isRed) { + return new Point(this, x, y, isRed); + }; + + ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { + return Point.fromJSON(this, obj, red); + }; + + Point.prototype._getBeta = function _getBeta() { + if (!this.curve.endo) + return; + + var pre = this.precomputed; + if (pre && pre.beta) + return pre.beta; + + var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); + if (pre) { + var curve = this.curve; + var endoMul = function(p) { + return curve.point(p.x.redMul(curve.endo.beta), p.y); + }; + pre.beta = beta; + beta.precomputed = { + beta: null, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(endoMul) + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(endoMul) + } + }; + } + return beta; + }; + + Point.prototype.toJSON = function toJSON() { + if (!this.precomputed) + return [ this.x, this.y ]; + + return [ this.x, this.y, this.precomputed && { + doubles: this.precomputed.doubles && { + step: this.precomputed.doubles.step, + points: this.precomputed.doubles.points.slice(1) + }, + naf: this.precomputed.naf && { + wnd: this.precomputed.naf.wnd, + points: this.precomputed.naf.points.slice(1) + } + } ]; + }; + + Point.fromJSON = function fromJSON(curve, obj, red) { + if (typeof obj === 'string') + obj = JSON.parse(obj); + var res = curve.point(obj[0], obj[1], red); + if (!obj[2]) + return res; + + function obj2point(obj) { + return curve.point(obj[0], obj[1], red); + } + + var pre = obj[2]; + res.precomputed = { + beta: null, + doubles: pre.doubles && { + step: pre.doubles.step, + points: [ res ].concat(pre.doubles.points.map(obj2point)) + }, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: [ res ].concat(pre.naf.points.map(obj2point)) + } + }; + return res; + }; + + Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; + + Point.prototype.isInfinity = function isInfinity() { + return this.inf; + }; + + Point.prototype.add = function add(p) { + // O + P = P + if (this.inf) + return p; + + // P + O = P + if (p.inf) + return this; + + // P + P = 2P + if (this.eq(p)) + return this.dbl(); + + // P + (-P) = O + if (this.neg().eq(p)) + return this.curve.point(null, null); + + // P + Q = O + if (this.x.cmp(p.x) === 0) + return this.curve.point(null, null); + + var c = this.y.redSub(p.y); + if (c.cmpn(0) !== 0) + c = c.redMul(this.x.redSub(p.x).redInvm()); + var nx = c.redSqr().redISub(this.x).redISub(p.x); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); + }; + + Point.prototype.dbl = function dbl() { + if (this.inf) + return this; + + // 2P = O + var ys1 = this.y.redAdd(this.y); + if (ys1.cmpn(0) === 0) + return this.curve.point(null, null); + + var a = this.curve.a; + + var x2 = this.x.redSqr(); + var dyinv = ys1.redInvm(); + var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); + + var nx = c.redSqr().redISub(this.x.redAdd(this.x)); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); + }; + + Point.prototype.getX = function getX() { + return this.x.fromRed(); + }; + + Point.prototype.getY = function getY() { + return this.y.fromRed(); + }; + + Point.prototype.mul = function mul(k) { + k = new BN(k, 16); + + if (this._hasDoubles(k)) + return this.curve._fixedNafMul(this, k); + else if (this.curve.endo) + return this.curve._endoWnafMulAdd([ this ], [ k ]); + else + return this.curve._wnafMul(this, k); + }; + + Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { + var points = [ this, p2 ]; + var coeffs = [ k1, k2 ]; + if (this.curve.endo) + return this.curve._endoWnafMulAdd(points, coeffs); + else + return this.curve._wnafMulAdd(1, points, coeffs, 2); + }; + + Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) { + var points = [ this, p2 ]; + var coeffs = [ k1, k2 ]; + if (this.curve.endo) + return this.curve._endoWnafMulAdd(points, coeffs, true); + else + return this.curve._wnafMulAdd(1, points, coeffs, 2, true); + }; + + Point.prototype.eq = function eq(p) { + return this === p || + this.inf === p.inf && + (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); + }; + + Point.prototype.neg = function neg(_precompute) { + if (this.inf) + return this; + + var res = this.curve.point(this.x, this.y.redNeg()); + if (_precompute && this.precomputed) { + var pre = this.precomputed; + var negate = function(p) { + return p.neg(); + }; + res.precomputed = { + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(negate) + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(negate) + } + }; + } + return res; + }; + + Point.prototype.toJ = function toJ() { + if (this.inf) + return this.curve.jpoint(null, null, null); + + var res = this.curve.jpoint(this.x, this.y, this.curve.one); + return res; + }; + + function JPoint(curve, x, y, z) { + Base.BasePoint.call(this, curve, 'jacobian'); + if (x === null && y === null && z === null) { + this.x = this.curve.one; + this.y = this.curve.one; + this.z = new BN(0); + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + this.z = new BN(z, 16); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + + this.zOne = this.z === this.curve.one; + } + inherits(JPoint, Base.BasePoint); + + ShortCurve.prototype.jpoint = function jpoint(x, y, z) { + return new JPoint(this, x, y, z); + }; + + JPoint.prototype.toP = function toP() { + if (this.isInfinity()) + return this.curve.point(null, null); + + var zinv = this.z.redInvm(); + var zinv2 = zinv.redSqr(); + var ax = this.x.redMul(zinv2); + var ay = this.y.redMul(zinv2).redMul(zinv); + + return this.curve.point(ax, ay); + }; + + JPoint.prototype.neg = function neg() { + return this.curve.jpoint(this.x, this.y.redNeg(), this.z); + }; + + JPoint.prototype.add = function add(p) { + // O + P = P + if (this.isInfinity()) + return p; + + // P + O = P + if (p.isInfinity()) + return this; + + // 12M + 4S + 7A + var pz2 = p.z.redSqr(); + var z2 = this.z.redSqr(); + var u1 = this.x.redMul(pz2); + var u2 = p.x.redMul(z2); + var s1 = this.y.redMul(pz2.redMul(p.z)); + var s2 = p.y.redMul(z2.redMul(this.z)); + + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(p.z).redMul(h); + + return this.curve.jpoint(nx, ny, nz); + }; + + JPoint.prototype.mixedAdd = function mixedAdd(p) { + // O + P = P + if (this.isInfinity()) + return p.toJ(); + + // P + O = P + if (p.isInfinity()) + return this; + + // 8M + 3S + 7A + var z2 = this.z.redSqr(); + var u1 = this.x; + var u2 = p.x.redMul(z2); + var s1 = this.y; + var s2 = p.y.redMul(z2).redMul(this.z); + + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(h); + + return this.curve.jpoint(nx, ny, nz); + }; + + JPoint.prototype.dblp = function dblp(pow) { + if (pow === 0) + return this; + if (this.isInfinity()) + return this; + if (!pow) + return this.dbl(); + + if (this.curve.zeroA || this.curve.threeA) { + var r = this; + for (var i = 0; i < pow; i++) + r = r.dbl(); + return r; + } + + // 1M + 2S + 1A + N * (4S + 5M + 8A) + // N = 1 => 6M + 6S + 9A + var a = this.curve.a; + var tinv = this.curve.tinv; + + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + + // Reuse results + var jyd = jy.redAdd(jy); + for (var i = 0; i < pow; i++) { + var jx2 = jx.redSqr(); + var jyd2 = jyd.redSqr(); + var jyd4 = jyd2.redSqr(); + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + + var t1 = jx.redMul(jyd2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + var dny = c.redMul(t2); + dny = dny.redIAdd(dny).redISub(jyd4); + var nz = jyd.redMul(jz); + if (i + 1 < pow) + jz4 = jz4.redMul(jyd4); + + jx = nx; + jz = nz; + jyd = dny; + } + + return this.curve.jpoint(jx, jyd.redMul(tinv), jz); + }; + + JPoint.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + + if (this.curve.zeroA) + return this._zeroDbl(); + else if (this.curve.threeA) + return this._threeDbl(); + else + return this._dbl(); + }; + + JPoint.prototype._zeroDbl = function _zeroDbl() { + var nx; + var ny; + var nz; + // Z = 1 + if (this.zOne) { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html + // #doubling-mdbl-2007-bl + // 1M + 5S + 14A + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // S = 2 * ((X1 + YY)^2 - XX - YYYY) + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + // M = 3 * XX + a; a = 0 + var m = xx.redAdd(xx).redIAdd(xx); + // T = M ^ 2 - 2*S + var t = m.redSqr().redISub(s).redISub(s); + + // 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + + // X3 = T + nx = t; + // Y3 = M * (S - T) - 8 * YYYY + ny = m.redMul(s.redISub(t)).redISub(yyyy8); + // Z3 = 2*Y1 + nz = this.y.redAdd(this.y); + } else { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html + // #doubling-dbl-2009-l + // 2M + 5S + 13A + + // A = X1^2 + var a = this.x.redSqr(); + // B = Y1^2 + var b = this.y.redSqr(); + // C = B^2 + var c = b.redSqr(); + // D = 2 * ((X1 + B)^2 - A - C) + var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); + d = d.redIAdd(d); + // E = 3 * A + var e = a.redAdd(a).redIAdd(a); + // F = E^2 + var f = e.redSqr(); + + // 8 * C + var c8 = c.redIAdd(c); + c8 = c8.redIAdd(c8); + c8 = c8.redIAdd(c8); + + // X3 = F - 2 * D + nx = f.redISub(d).redISub(d); + // Y3 = E * (D - X3) - 8 * C + ny = e.redMul(d.redISub(nx)).redISub(c8); + // Z3 = 2 * Y1 * Z1 + nz = this.y.redMul(this.z); + nz = nz.redIAdd(nz); + } + + return this.curve.jpoint(nx, ny, nz); + }; + + JPoint.prototype._threeDbl = function _threeDbl() { + var nx; + var ny; + var nz; + // Z = 1 + if (this.zOne) { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html + // #doubling-mdbl-2007-bl + // 1M + 5S + 15A + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // S = 2 * ((X1 + YY)^2 - XX - YYYY) + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + // M = 3 * XX + a + var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); + // T = M^2 - 2 * S + var t = m.redSqr().redISub(s).redISub(s); + // X3 = T + nx = t; + // Y3 = M * (S - T) - 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + ny = m.redMul(s.redISub(t)).redISub(yyyy8); + // Z3 = 2 * Y1 + nz = this.y.redAdd(this.y); + } else { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b + // 3M + 5S + + // delta = Z1^2 + var delta = this.z.redSqr(); + // gamma = Y1^2 + var gamma = this.y.redSqr(); + // beta = X1 * gamma + var beta = this.x.redMul(gamma); + // alpha = 3 * (X1 - delta) * (X1 + delta) + var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); + alpha = alpha.redAdd(alpha).redIAdd(alpha); + // X3 = alpha^2 - 8 * beta + var beta4 = beta.redIAdd(beta); + beta4 = beta4.redIAdd(beta4); + var beta8 = beta4.redAdd(beta4); + nx = alpha.redSqr().redISub(beta8); + // Z3 = (Y1 + Z1)^2 - gamma - delta + nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); + // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 + var ggamma8 = gamma.redSqr(); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); + } + + return this.curve.jpoint(nx, ny, nz); + }; + + JPoint.prototype._dbl = function _dbl() { + var a = this.curve.a; + + // 4M + 6S + 10A + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + + var jx2 = jx.redSqr(); + var jy2 = jy.redSqr(); + + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + + var jxd4 = jx.redAdd(jx); + jxd4 = jxd4.redIAdd(jxd4); + var t1 = jxd4.redMul(jy2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + + var jyd8 = jy2.redSqr(); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + var ny = c.redMul(t2).redISub(jyd8); + var nz = jy.redAdd(jy).redMul(jz); + + return this.curve.jpoint(nx, ny, nz); + }; + + JPoint.prototype.trpl = function trpl() { + if (!this.curve.zeroA) + return this.dbl().add(this); + + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl + // 5M + 10S + ... + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // ZZ = Z1^2 + var zz = this.z.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // M = 3 * XX + a * ZZ2; a = 0 + var m = xx.redAdd(xx).redIAdd(xx); + // MM = M^2 + var mm = m.redSqr(); + // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM + var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + e = e.redIAdd(e); + e = e.redAdd(e).redIAdd(e); + e = e.redISub(mm); + // EE = E^2 + var ee = e.redSqr(); + // T = 16*YYYY + var t = yyyy.redIAdd(yyyy); + t = t.redIAdd(t); + t = t.redIAdd(t); + t = t.redIAdd(t); + // U = (M + E)^2 - MM - EE - T + var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); + // X3 = 4 * (X1 * EE - 4 * YY * U) + var yyu4 = yy.redMul(u); + yyu4 = yyu4.redIAdd(yyu4); + yyu4 = yyu4.redIAdd(yyu4); + var nx = this.x.redMul(ee).redISub(yyu4); + nx = nx.redIAdd(nx); + nx = nx.redIAdd(nx); + // Y3 = 8 * Y1 * (U * (T - U) - E * EE) + var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + // Z3 = (Z1 + E)^2 - ZZ - EE + var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); + + return this.curve.jpoint(nx, ny, nz); + }; + + JPoint.prototype.mul = function mul(k, kbase) { + k = new BN(k, kbase); + + return this.curve._wnafMul(this, k); + }; + + JPoint.prototype.eq = function eq(p) { + if (p.type === 'affine') + return this.eq(p.toJ()); + + if (this === p) + return true; + + // x1 * z2^2 == x2 * z1^2 + var z2 = this.z.redSqr(); + var pz2 = p.z.redSqr(); + if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) + return false; + + // y1 * z2^3 == y2 * z1^3 + var z3 = z2.redMul(this.z); + var pz3 = pz2.redMul(p.z); + return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; + }; + + JPoint.prototype.eqXToP = function eqXToP(x) { + var zs = this.z.redSqr(); + var rx = x.toRed(this.curve.red).redMul(zs); + if (this.x.cmp(rx) === 0) + return true; + + var xc = x.clone(); + var t = this.curve.redN.redMul(zs); + for (;;) { + xc.iadd(this.curve.n); + if (xc.cmp(this.curve.p) >= 0) + return false; + + rx.redIAdd(t); + if (this.x.cmp(rx) === 0) + return true; + } + return false; + }; + + JPoint.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; + + JPoint.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; + }; + + },{"../../elliptic":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); + else if (options.type === 'edwards') + this.curve = new elliptic.curve.edwards(options); + else + this.curve = new elliptic.curve.mont(options); + this.g = this.curve.g; + this.n = this.curve.n; + this.hash = options.hash; + + assert(this.g.validate(), 'Invalid curve'); + assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); + } + curves.PresetCurve = PresetCurve; + + function defineCurve(name, options) { + Object.defineProperty(curves, name, { + configurable: true, + enumerable: true, + get: function() { + var curve = new PresetCurve(options); + Object.defineProperty(curves, name, { + configurable: true, + enumerable: true, + value: curve + }); + return curve; + } + }); + } + + defineCurve('p192', { + type: 'short', + prime: 'p192', + p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', + a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', + b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', + n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', + hash: hash.sha256, + gRed: false, + g: [ + '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', + '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811' + ] + }); + + defineCurve('p224', { + type: 'short', + prime: 'p224', + p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', + a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', + b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', + n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', + hash: hash.sha256, + gRed: false, + g: [ + 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', + 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34' + ] + }); + + defineCurve('p256', { + type: 'short', + prime: null, + p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', + a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', + b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', + n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', + hash: hash.sha256, + gRed: false, + g: [ + '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', + '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5' + ] + }); + + defineCurve('p384', { + type: 'short', + prime: null, + p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'fffffffe ffffffff 00000000 00000000 ffffffff', + a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'fffffffe ffffffff 00000000 00000000 fffffffc', + b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' + + '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef', + n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' + + 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973', + hash: hash.sha384, + gRed: false, + g: [ + 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' + + '5502f25d bf55296c 3a545e38 72760ab7', + '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' + + '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f' + ] + }); + + defineCurve('p521', { + type: 'short', + prime: null, + p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff', + a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff fffffffc', + b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' + + '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' + + '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00', + n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' + + 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409', + hash: hash.sha512, + gRed: false, + g: [ + '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' + + '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' + + 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', + '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' + + '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' + + '3fad0761 353c7086 a272c240 88be9476 9fd16650' + ] + }); + + defineCurve('curve25519', { + type: 'mont', + prime: 'p25519', + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: '76d06', + b: '1', + n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', + hash: hash.sha256, + gRed: false, + g: [ + '9' + ] + }); + + defineCurve('ed25519', { + type: 'edwards', + prime: 'p25519', + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: '-1', + c: '1', + // -121665 * (121666^(-1)) (mod P) + d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', + n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', + hash: hash.sha256, + gRed: false, + g: [ + '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', + + // 4/5 + '6666666666666666666666666666666666666666666666666666666666666658' + ] + }); + + var pre; + try { + pre = require('./precomputed/secp256k1'); + } catch (e) { + pre = undefined; + } + + defineCurve('secp256k1', { + type: 'short', + prime: 'k256', + p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', + a: '0', + b: '7', + n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', + h: '1', + hash: hash.sha256, + + // Precomputed endomorphism + beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', + lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', + basis: [ + { + a: '3086d221a7d46bcde86c90e49284eb15', + b: '-e4437ed6010e88286f547fa90abfe4c3' + }, + { + a: '114ca50f7a8e2f3f657c1108d9d44cfd8', + b: '3086d221a7d46bcde86c90e49284eb15' + } + ], + + gRed: false, + g: [ + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', + pre + ] + }); + + },{"../elliptic":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, + pers: options.pers, + persEnc: options.persEnc || 'utf8', + entropy: options.entropy || elliptic.rand(this.hash.hmacStrength), + entropyEnc: options.entropy && options.entropyEnc || 'utf8', + nonce: this.n.toArray() + }); + + var bytes = this.n.byteLength(); + var ns2 = this.n.sub(new BN(2)); + do { + var priv = new BN(drbg.generate(bytes)); + if (priv.cmp(ns2) > 0) + continue; + + priv.iaddn(1); + return this.keyFromPrivate(priv); + } while (true); + }; + + EC.prototype._truncateToN = function truncateToN(msg, truncOnly) { + var delta = msg.byteLength() * 8 - this.n.bitLength(); + if (delta > 0) + msg = msg.ushrn(delta); + if (!truncOnly && msg.cmp(this.n) >= 0) + return msg.sub(this.n); + else + return msg; + }; + + EC.prototype.sign = function sign(msg, key, enc, options) { + if (typeof enc === 'object') { + options = enc; + enc = null; + } + if (!options) + options = {}; + + key = this.keyFromPrivate(key, enc); + msg = this._truncateToN(new BN(msg, 16)); + + // Zero-extend key to provide enough entropy + var bytes = this.n.byteLength(); + var bkey = key.getPrivate().toArray('be', bytes); + + // Zero-extend nonce to have the same byte size as N + var nonce = msg.toArray('be', bytes); + + // Instantiate Hmac_DRBG + var drbg = new HmacDRBG({ + hash: this.hash, + entropy: bkey, + nonce: nonce, + pers: options.pers, + persEnc: options.persEnc || 'utf8' + }); + + // Number of bytes to generate + var ns1 = this.n.sub(new BN(1)); + + for (var iter = 0; true; iter++) { + var k = options.k ? + options.k(iter) : + new BN(drbg.generate(this.n.byteLength())); + k = this._truncateToN(k, true); + if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) + continue; + + var kp = this.g.mul(k); + if (kp.isInfinity()) + continue; + + var kpX = kp.getX(); + var r = kpX.umod(this.n); + if (r.cmpn(0) === 0) + continue; + + var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); + s = s.umod(this.n); + if (s.cmpn(0) === 0) + continue; + + var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | + (kpX.cmp(r) !== 0 ? 2 : 0); + + // Use complement of `s`, if it is > `n / 2` + if (options.canonical && s.cmp(this.nh) > 0) { + s = this.n.sub(s); + recoveryParam ^= 1; + } + + return new Signature({ r: r, s: s, recoveryParam: recoveryParam }); + } + }; + + EC.prototype.verify = function verify(msg, signature, key, enc) { + msg = this._truncateToN(new BN(msg, 16)); + key = this.keyFromPublic(key, enc); + signature = new Signature(signature, 'hex'); + + // Perform primitive values validation + var r = signature.r; + var s = signature.s; + if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) + return false; + if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) + return false; + + // Validate signature + var sinv = s.invm(this.n); + var u1 = sinv.mul(msg).umod(this.n); + var u2 = sinv.mul(r).umod(this.n); + + if (!this.curve._maxwellTrick) { + var p = this.g.mulAdd(u1, key.getPublic(), u2); + if (p.isInfinity()) + return false; + + return p.getX().umod(this.n).cmp(r) === 0; + } + + // NOTE: Greg Maxwell's trick, inspired by: + // https://git.io/vad3K + + var p = this.g.jmulAdd(u1, key.getPublic(), u2); + if (p.isInfinity()) + return false; + + // Compare `p.x` of Jacobian point with `r`, + // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the + // inverse of `p.z^2` + return p.eqXToP(r); + }; + + EC.prototype.recoverPubKey = function(msg, signature, j, enc) { + assert((3 & j) === j, 'The recovery param is more than two bits'); + signature = new Signature(signature, enc); + + var n = this.n; + var e = new BN(msg); + var r = signature.r; + var s = signature.s; + + // A set LSB signifies that the y-coordinate is odd + var isYOdd = j & 1; + var isSecondKey = j >> 1; + if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) + throw new Error('Unable to find sencond key candinate'); + + // 1.1. Let x = r + jn. + if (isSecondKey) + r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); + else + r = this.curve.pointFromX(r, isYOdd); + + var rInv = signature.r.invm(n); + var s1 = n.sub(e).mul(rInv).umod(n); + var s2 = s.mul(rInv).umod(n); + + // 1.6.1 Compute Q = r^-1 (sR - eG) + // Q = r^-1 (sR + -eG) + return this.g.mulAdd(s1, r, s2); + }; + + EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { + signature = new Signature(signature, enc); + if (signature.recoveryParam !== null) + return signature.recoveryParam; + + for (var i = 0; i < 4; i++) { + var Qprime; + try { + Qprime = this.recoverPubKey(e, signature, i); + } catch (e) { + continue; + } + + if (Qprime.eq(Q)) + return i; + } + throw new Error('Unable to find valid recovery factor'); + }; + + },{"../../elliptic":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); + if (options.pub) + this._importPublic(options.pub, options.pubEnc); + } + module.exports = KeyPair; + + KeyPair.fromPublic = function fromPublic(ec, pub, enc) { + if (pub instanceof KeyPair) + return pub; + + return new KeyPair(ec, { + pub: pub, + pubEnc: enc + }); + }; + + KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) { + if (priv instanceof KeyPair) + return priv; + + return new KeyPair(ec, { + priv: priv, + privEnc: enc + }); + }; + + KeyPair.prototype.validate = function validate() { + var pub = this.getPublic(); + + if (pub.isInfinity()) + return { result: false, reason: 'Invalid public key' }; + if (!pub.validate()) + return { result: false, reason: 'Public key is not a point' }; + if (!pub.mul(this.ec.curve.n).isInfinity()) + return { result: false, reason: 'Public key * N != O' }; + + return { result: true, reason: null }; + }; + + KeyPair.prototype.getPublic = function getPublic(compact, enc) { + // compact is optional argument + if (typeof compact === 'string') { + enc = compact; + compact = null; + } + + if (!this.pub) + this.pub = this.ec.g.mul(this.priv); + + if (!enc) + return this.pub; + + return this.pub.encode(enc, compact); + }; + + KeyPair.prototype.getPrivate = function getPrivate(enc) { + if (enc === 'hex') + return this.priv.toString(16, 2); + else + return this.priv; + }; + + KeyPair.prototype._importPrivate = function _importPrivate(key, enc) { + this.priv = new BN(key, enc || 16); + + // Ensure that the priv won't be bigger than n, otherwise we may fail + // in fixed multiplication method + this.priv = this.priv.umod(this.ec.curve.n); + }; + + KeyPair.prototype._importPublic = function _importPublic(key, enc) { + if (key.x || key.y) { + // Montgomery points only have an `x` coordinate. + // Weierstrass/Edwards points on the other hand have both `x` and + // `y` coordinates. + if (this.ec.curve.type === 'mont') { + assert(key.x, 'Need x coordinate'); + } else if (this.ec.curve.type === 'short' || + this.ec.curve.type === 'edwards') { + assert(key.x && key.y, 'Need both x and y coordinate'); + } + this.pub = this.ec.curve.point(key.x, key.y); + return; + } + this.pub = this.ec.curve.decodePoint(key, enc); + }; + + // ECDH + KeyPair.prototype.derive = function derive(pub) { + return pub.mul(this.priv).getX(); + }; + + // ECDSA + KeyPair.prototype.sign = function sign(msg, enc, options) { + return this.ec.sign(msg, this, enc, options); + }; + + KeyPair.prototype.verify = function verify(msg, signature) { + return this.ec.verify(msg, signature, this); + }; + + KeyPair.prototype.inspect = function inspect() { + return ''; + }; + + },{"../../elliptic":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); + if (options.recoveryParam === undefined) + this.recoveryParam = null; + else + this.recoveryParam = options.recoveryParam; + } + module.exports = Signature; + + function Position() { + this.place = 0; + } + + function getLength(buf, p) { + var initial = buf[p.place++]; + if (!(initial & 0x80)) { + return initial; + } + var octetLen = initial & 0xf; + var val = 0; + for (var i = 0, off = p.place; i < octetLen; i++, off++) { + val <<= 8; + val |= buf[off]; + } + p.place = off; + return val; + } + + function rmPadding(buf) { + var i = 0; + var len = buf.length - 1; + while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) { + i++; + } + if (i === 0) { + return buf; + } + return buf.slice(i); + } + + Signature.prototype._importDER = function _importDER(data, enc) { + data = utils.toArray(data, enc); + var p = new Position(); + if (data[p.place++] !== 0x30) { + return false; + } + var len = getLength(data, p); + if ((len + p.place) !== data.length) { + return false; + } + if (data[p.place++] !== 0x02) { + return false; + } + var rlen = getLength(data, p); + var r = data.slice(p.place, rlen + p.place); + p.place += rlen; + if (data[p.place++] !== 0x02) { + return false; + } + var slen = getLength(data, p); + if (data.length !== slen + p.place) { + return false; + } + var s = data.slice(p.place, slen + p.place); + if (r[0] === 0 && (r[1] & 0x80)) { + r = r.slice(1); + } + if (s[0] === 0 && (s[1] & 0x80)) { + s = s.slice(1); + } + + this.r = new BN(r); + this.s = new BN(s); + this.recoveryParam = null; + + return true; + }; + + function constructLength(arr, len) { + if (len < 0x80) { + arr.push(len); + return; + } + var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); + arr.push(octets | 0x80); + while (--octets) { + arr.push((len >>> (octets << 3)) & 0xff); + } + arr.push(len); + } + + Signature.prototype.toDER = function toDER(enc) { + var r = this.r.toArray(); + var s = this.s.toArray(); + + // Pad values + if (r[0] & 0x80) + r = [ 0 ].concat(r); + // Pad values + if (s[0] & 0x80) + s = [ 0 ].concat(s); + + r = rmPadding(r); + s = rmPadding(s); + + while (!s[0] && !(s[1] & 0x80)) { + s = s.slice(1); + } + var arr = [ 0x02 ]; + constructLength(arr, r.length); + arr = arr.concat(r); + arr.push(0x02); + constructLength(arr, s.length); + var backHalf = arr.concat(s); + var res = [ 0x30 ]; + constructLength(res, backHalf.length); + res = res.concat(backHalf); + return utils.encode(res, enc); + }; + + },{"../../elliptic":109,"bn.js":53}],119:[function(require,module,exports){ + 'use strict'; + + var hash = require('hash.js'); + var elliptic = require('../../elliptic'); + var utils = elliptic.utils; + var assert = utils.assert; + var parseBytes = utils.parseBytes; + var KeyPair = require('./key'); + var Signature = require('./signature'); + + function EDDSA(curve) { + assert(curve === 'ed25519', 'only tested with ed25519 so far'); + + if (!(this instanceof EDDSA)) + return new EDDSA(curve); + + var curve = elliptic.curves[curve].curve; + this.curve = curve; + this.g = curve.g; + this.g.precompute(curve.n.bitLength() + 1); + + this.pointClass = curve.point().constructor; + this.encodingLength = Math.ceil(curve.n.bitLength() / 8); + this.hash = hash.sha512; + } + + module.exports = EDDSA; + + /** + * @param {Array|String} message - message bytes + * @param {Array|String|KeyPair} secret - secret bytes or a keypair + * @returns {Signature} - signature + */ + EDDSA.prototype.sign = function sign(message, secret) { + message = parseBytes(message); + var key = this.keyFromSecret(secret); + var r = this.hashInt(key.messagePrefix(), message); + var R = this.g.mul(r); + var Rencoded = this.encodePoint(R); + var s_ = this.hashInt(Rencoded, key.pubBytes(), message) + .mul(key.priv()); + var S = r.add(s_).umod(this.curve.n); + return this.makeSignature({ R: R, S: S, Rencoded: Rencoded }); + }; + + /** + * @param {Array} message - message bytes + * @param {Array|String|Signature} sig - sig bytes + * @param {Array|String|Point|KeyPair} pub - public key + * @returns {Boolean} - true if public key matches sig of message + */ + EDDSA.prototype.verify = function verify(message, sig, pub) { + message = parseBytes(message); + sig = this.makeSignature(sig); + var key = this.keyFromPublic(pub); + var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message); + var SG = this.g.mul(sig.S()); + var RplusAh = sig.R().add(key.pub().mul(h)); + return RplusAh.eq(SG); + }; + + EDDSA.prototype.hashInt = function hashInt() { + var hash = this.hash(); + for (var i = 0; i < arguments.length; i++) + hash.update(arguments[i]); + return utils.intFromLE(hash.digest()).umod(this.curve.n); + }; + + EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { + return KeyPair.fromPublic(this, pub); + }; + + EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { + return KeyPair.fromSecret(this, secret); + }; + + EDDSA.prototype.makeSignature = function makeSignature(sig) { + if (sig instanceof Signature) + return sig; + return new Signature(this, sig); + }; + + /** + * * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2 + * + * EDDSA defines methods for encoding and decoding points and integers. These are + * helper convenience methods, that pass along to utility functions implied + * parameters. + * + */ + EDDSA.prototype.encodePoint = function encodePoint(point) { + var enc = point.getY().toArray('le', this.encodingLength); + enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0; + return enc; + }; + + EDDSA.prototype.decodePoint = function decodePoint(bytes) { + bytes = utils.parseBytes(bytes); + + var lastIx = bytes.length - 1; + var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); + var xIsOdd = (bytes[lastIx] & 0x80) !== 0; + + var y = utils.intFromLE(normed); + return this.curve.pointFromY(y, xIsOdd); + }; + + EDDSA.prototype.encodeInt = function encodeInt(num) { + return num.toArray('le', this.encodingLength); + }; + + EDDSA.prototype.decodeInt = function decodeInt(bytes) { + return utils.intFromLE(bytes); + }; + + EDDSA.prototype.isPoint = function isPoint(val) { + return val instanceof this.pointClass; + }; + + },{"../../elliptic":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 + * + * @param {Array} [params.secret] - secret seed bytes + * @param {Point} [params.pub] - public key point (aka `A` in eddsa terms) + * @param {Array} [params.pub] - public key point encoded as bytes + * + */ + function KeyPair(eddsa, params) { + this.eddsa = eddsa; + this._secret = parseBytes(params.secret); + if (eddsa.isPoint(params.pub)) + this._pub = params.pub; + else + this._pubBytes = parseBytes(params.pub); + } + + KeyPair.fromPublic = function fromPublic(eddsa, pub) { + if (pub instanceof KeyPair) + return pub; + return new KeyPair(eddsa, { pub: pub }); + }; + + KeyPair.fromSecret = function fromSecret(eddsa, secret) { + if (secret instanceof KeyPair) + return secret; + return new KeyPair(eddsa, { secret: secret }); + }; + + KeyPair.prototype.secret = function secret() { + return this._secret; + }; + + cachedProperty(KeyPair, 'pubBytes', function pubBytes() { + return this.eddsa.encodePoint(this.pub()); + }); + + cachedProperty(KeyPair, 'pub', function pub() { + if (this._pubBytes) + return this.eddsa.decodePoint(this._pubBytes); + return this.eddsa.g.mul(this.priv()); + }); + + cachedProperty(KeyPair, 'privBytes', function privBytes() { + var eddsa = this.eddsa; + var hash = this.hash(); + var lastIx = eddsa.encodingLength - 1; + + var a = hash.slice(0, eddsa.encodingLength); + a[0] &= 248; + a[lastIx] &= 127; + a[lastIx] |= 64; + + return a; + }); + + cachedProperty(KeyPair, 'priv', function priv() { + return this.eddsa.decodeInt(this.privBytes()); + }); + + cachedProperty(KeyPair, 'hash', function hash() { + return this.eddsa.hash().update(this.secret()).digest(); + }); + + cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() { + return this.hash().slice(this.eddsa.encodingLength); + }); + + KeyPair.prototype.sign = function sign(message) { + assert(this._secret, 'KeyPair can only verify'); + return this.eddsa.sign(message, this); + }; + + KeyPair.prototype.verify = function verify(message, sig) { + return this.eddsa.verify(message, sig, this); + }; + + KeyPair.prototype.getSecret = function getSecret(enc) { + assert(this._secret, 'KeyPair is public only'); + return utils.encode(this.secret(), enc); + }; + + KeyPair.prototype.getPublic = function getPublic(enc) { + return utils.encode(this.pubBytes(), enc); + }; + + module.exports = KeyPair; + + },{"../../elliptic":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 - + * @param {Array|Point} [sig.R] - R point as Point or bytes + * @param {Array|bn} [sig.S] - S scalar as bn or bytes + * @param {Array} [sig.Rencoded] - R point encoded + * @param {Array} [sig.Sencoded] - S scalar encoded + */ + function Signature(eddsa, sig) { + this.eddsa = eddsa; + + if (typeof sig !== 'object') + sig = parseBytes(sig); + + if (Array.isArray(sig)) { + sig = { + R: sig.slice(0, eddsa.encodingLength), + S: sig.slice(eddsa.encodingLength) + }; + } + + assert(sig.R && sig.S, 'Signature without R or S'); + + if (eddsa.isPoint(sig.R)) + this._R = sig.R; + if (sig.S instanceof BN) + this._S = sig.S; + + this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; + this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; + } + + cachedProperty(Signature, 'S', function S() { + return this.eddsa.decodeInt(this.Sencoded()); + }); + + cachedProperty(Signature, 'R', function R() { + return this.eddsa.decodePoint(this.Rencoded()); + }); + + cachedProperty(Signature, 'Rencoded', function Rencoded() { + return this.eddsa.encodePoint(this.R()); + }); + + cachedProperty(Signature, 'Sencoded', function Sencoded() { + return this.eddsa.encodeInt(this.S()); + }); + + Signature.prototype.toBytes = function toBytes() { + return this.Rencoded().concat(this.Sencoded()); + }; + + Signature.prototype.toHex = function toHex() { + return utils.encode(this.toBytes(), 'hex').toUpperCase(); + }; + + module.exports = Signature; + + },{"../../elliptic":109,"bn.js":53}],122:[function(require,module,exports){ + module.exports = { + doubles: { + step: 4, + points: [ + [ + 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', + 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821' + ], + [ + '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', + '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf' + ], + [ + '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', + 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695' + ], + [ + '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', + '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9' + ], + [ + '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', + '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36' + ], + [ + '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', + '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f' + ], + [ + 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', + '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999' + ], + [ + '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', + 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09' + ], + [ + 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', + '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d' + ], + [ + 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', + 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088' + ], + [ + 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', + '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d' + ], + [ + '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', + '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8' + ], + [ + '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', + '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a' + ], + [ + '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', + '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453' + ], + [ + '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', + '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160' + ], + [ + '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', + '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0' + ], + [ + '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', + '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6' + ], + [ + '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', + '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589' + ], + [ + '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', + 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17' + ], + [ + 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', + '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda' + ], + [ + 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', + '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd' + ], + [ + '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', + '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2' + ], + [ + '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', + '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6' + ], + [ + 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', + '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f' + ], + [ + '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', + 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01' + ], + [ + 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', + '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3' + ], + [ + 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', + 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f' + ], + [ + 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', + '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7' + ], + [ + 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', + 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78' + ], + [ + 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', + '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1' + ], + [ + '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', + 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150' + ], + [ + '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', + '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82' + ], + [ + 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', + '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc' + ], + [ + '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', + 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b' + ], + [ + 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', + '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51' + ], + [ + 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', + '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45' + ], + [ + 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', + 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120' + ], + [ + '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', + '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84' + ], + [ + '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', + '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d' + ], + [ + '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', + 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d' + ], + [ + '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', + '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8' + ], + [ + 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', + '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8' + ], + [ + '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', + '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac' + ], + [ + '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', + 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f' + ], + [ + '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', + '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962' + ], + [ + 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', + '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907' + ], + [ + '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', + 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec' + ], + [ + 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', + 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d' + ], + [ + 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', + '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414' + ], + [ + '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', + 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd' + ], + [ + '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', + 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0' + ], + [ + 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', + '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811' + ], + [ + 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', + '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1' + ], + [ + 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', + '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c' + ], + [ + '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', + 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73' + ], + [ + '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', + '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd' + ], + [ + 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', + 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405' + ], + [ + '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', + 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589' + ], + [ + '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', + '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e' + ], + [ + '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', + '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27' + ], + [ + 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', + 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1' + ], + [ + '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', + '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482' + ], + [ + '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', + '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945' + ], + [ + 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', + '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573' + ], + [ + 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', + 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82' + ] + ] + }, + naf: { + wnd: 7, + points: [ + [ + 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', + '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672' + ], + [ + '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', + 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6' + ], + [ + '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', + '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da' + ], + [ + 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', + 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37' + ], + [ + '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', + 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b' + ], + [ + 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', + 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81' + ], + [ + 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', + '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58' + ], + [ + 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', + '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77' + ], + [ + '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', + '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a' + ], + [ + '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', + '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c' + ], + [ + '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', + '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67' + ], + [ + '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', + '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402' + ], + [ + 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', + 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55' + ], + [ + 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', + '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482' + ], + [ + '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', + 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82' + ], + [ + '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', + 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396' + ], + [ + '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', + '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49' + ], + [ + '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', + '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf' + ], + [ + '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', + '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a' + ], + [ + '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', + 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7' + ], + [ + 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', + 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933' + ], + [ + '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', + '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a' + ], + [ + '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', + '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6' + ], + [ + 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', + 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37' + ], + [ + '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', + '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e' + ], + [ + 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', + 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6' + ], + [ + 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', + 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476' + ], + [ + '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', + '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40' + ], + [ + '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', + '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61' + ], + [ + '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', + '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683' + ], + [ + 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', + '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5' + ], + [ + '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', + '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b' + ], + [ + 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', + '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417' + ], + [ + '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', + 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868' + ], + [ + '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', + 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a' + ], + [ + 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', + 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6' + ], + [ + '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', + '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996' + ], + [ + '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', + 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e' + ], + [ + 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', + 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d' + ], + [ + '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', + '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2' + ], + [ + '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', + 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e' + ], + [ + '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', + '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437' + ], + [ + '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', + 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311' + ], + [ + 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', + '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4' + ], + [ + '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', + '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575' + ], + [ + '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', + 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d' + ], + [ + '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', + 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d' + ], + [ + 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', + 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629' + ], + [ + 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', + 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06' + ], + [ + '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', + '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374' + ], + [ + '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', + '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee' + ], + [ + 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', + '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1' + ], + [ + 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', + 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b' + ], + [ + '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', + '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661' + ], + [ + '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', + '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6' + ], + [ + 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', + '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e' + ], + [ + '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', + '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d' + ], + [ + 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', + 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc' + ], + [ + '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', + 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4' + ], + [ + '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', + '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c' + ], + [ + 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', + '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b' + ], + [ + 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', + '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913' + ], + [ + '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', + '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154' + ], + [ + '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', + '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865' + ], + [ + '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', + 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc' + ], + [ + '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', + 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224' + ], + [ + '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', + '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e' + ], + [ + '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', + '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6' + ], + [ + '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', + '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511' + ], + [ + '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', + 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b' + ], + [ + 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', + 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2' + ], + [ + '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', + 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c' + ], + [ + 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', + '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3' + ], + [ + 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', + '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d' + ], + [ + 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', + '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700' + ], + [ + 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', + '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4' + ], + [ + '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', + 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196' + ], + [ + '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', + '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4' + ], + [ + '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', + 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257' + ], + [ + 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', + 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13' + ], + [ + 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', + '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096' + ], + [ + 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', + 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38' + ], + [ + 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', + '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f' + ], + [ + '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', + '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448' + ], + [ + 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', + '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a' + ], + [ + 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', + '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4' + ], + [ + '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', + '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437' + ], + [ + '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', + 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7' + ], + [ + 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', + '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d' + ], + [ + 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', + '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a' + ], + [ + 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', + '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54' + ], + [ + '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', + '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77' + ], + [ + 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', + 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517' + ], + [ + '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', + 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10' + ], + [ + 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', + 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125' + ], + [ + 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', + '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e' + ], + [ + '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', + 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1' + ], + [ + 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', + '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2' + ], + [ + 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', + '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423' + ], + [ + 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', + '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8' + ], + [ + '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', + 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758' + ], + [ + '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', + 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375' + ], + [ + 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', + '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d' + ], + [ + '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', + 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec' + ], + [ + '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', + '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0' + ], + [ + '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', + 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c' + ], + [ + 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', + 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4' + ], + [ + '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', + 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f' + ], + [ + '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', + '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649' + ], + [ + '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', + 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826' + ], + [ + '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', + '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5' + ], + [ + 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', + 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87' + ], + [ + '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', + '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b' + ], + [ + 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', + '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc' + ], + [ + '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', + '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c' + ], + [ + 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', + 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f' + ], + [ + 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', + '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a' + ], + [ + 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', + 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46' + ], + [ + '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', + 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f' + ], + [ + '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', + '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03' + ], + [ + '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', + 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08' + ], + [ + '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', + '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8' + ], + [ + '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', + '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373' + ], + [ + '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', + 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3' + ], + [ + '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', + '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8' + ], + [ + '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', + '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1' + ], + [ + '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', + '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9' + ] + ] + } + }; + + },{}],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 = []; + var ws = 1 << (w + 1); + var k = num.clone(); + while (k.cmpn(1) >= 0) { + var z; + if (k.isOdd()) { + var mod = k.andln(ws - 1); + if (mod > (ws >> 1) - 1) + z = (ws >> 1) - mod; + else + z = mod; + k.isubn(z); + } else { + z = 0; + } + naf.push(z); + + // Optimization, shift by word if possible + var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1; + for (var i = 1; i < shift; i++) + naf.push(0); + k.iushrn(shift); + } + + return naf; + } + utils.getNAF = getNAF; + + // Represent k1, k2 in a Joint Sparse Form + function getJSF(k1, k2) { + var jsf = [ + [], + [] + ]; + + k1 = k1.clone(); + k2 = k2.clone(); + var d1 = 0; + var d2 = 0; + while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { + + // First phase + var m14 = (k1.andln(3) + d1) & 3; + var m24 = (k2.andln(3) + d2) & 3; + if (m14 === 3) + m14 = -1; + if (m24 === 3) + m24 = -1; + var u1; + if ((m14 & 1) === 0) { + u1 = 0; + } else { + var m8 = (k1.andln(7) + d1) & 7; + if ((m8 === 3 || m8 === 5) && m24 === 2) + u1 = -m14; + else + u1 = m14; + } + jsf[0].push(u1); + + var u2; + if ((m24 & 1) === 0) { + u2 = 0; + } else { + var m8 = (k2.andln(7) + d2) & 7; + if ((m8 === 3 || m8 === 5) && m14 === 2) + u2 = -m24; + else + u2 = m24; + } + jsf[1].push(u2); + + // Second phase + if (2 * d1 === u1 + 1) + d1 = 1 - d1; + if (2 * d2 === u2 + 1) + d2 = 1 - d2; + k1.iushrn(1); + k2.iushrn(1); + } + + return jsf; + } + utils.getJSF = getJSF; + + function cachedProperty(obj, name, computer) { + var key = '_' + name; + obj.prototype[name] = function cachedProperty() { + return this[key] !== undefined ? this[key] : + this[key] = computer.call(this); + }; + } + utils.cachedProperty = cachedProperty; + + function parseBytes(bytes) { + return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : + bytes; + } + utils.parseBytes = parseBytes; + + function intFromLE(bytes) { + return new BN(bytes, 'hex', 'le'); + } + utils.intFromLE = intFromLE; + + + },{"bn.js":53,"minimalistic-assert":234,"minimalistic-crypto-utils":235}],124:[function(require,module,exports){ + module.exports={ + "_from": "elliptic@^6.0.0", + "_id": "elliptic@6.4.0", + "_inBundle": false, + "_integrity": "sha1-ysmvh2LIWDYYcAPI3+GT5eLq5d8=", + "_location": "/elliptic", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "elliptic@^6.0.0", + "name": "elliptic", + "escapedName": "elliptic", + "rawSpec": "^6.0.0", + "saveSpec": null, + "fetchSpec": "^6.0.0" + }, + "_requiredBy": [ + "/browserify-sign", + "/create-ecdh" + ], + "_resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.4.0.tgz", + "_shasum": "cac9af8762c85836187003c8dfe193e5e2eae5df", + "_spec": "elliptic@^6.0.0", + "_where": "/Users/alexvlasov/Blockchain/web3swift_jsproxy/node_modules/browserify-sign", + "author": { + "name": "Fedor Indutny", + "email": "fedor@indutny.com" + }, + "bugs": { + "url": "https://github.com/indutny/elliptic/issues" + }, + "bundleDependencies": false, + "dependencies": { + "bn.js": "^4.4.0", + "brorand": "^1.0.1", + "hash.js": "^1.0.0", + "hmac-drbg": "^1.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0", + "minimalistic-crypto-utils": "^1.0.0" + }, + "deprecated": false, + "description": "EC cryptography", + "devDependencies": { + "brfs": "^1.4.3", + "coveralls": "^2.11.3", + "grunt": "^0.4.5", + "grunt-browserify": "^5.0.0", + "grunt-cli": "^1.2.0", + "grunt-contrib-connect": "^1.0.0", + "grunt-contrib-copy": "^1.0.0", + "grunt-contrib-uglify": "^1.0.1", + "grunt-mocha-istanbul": "^3.0.1", + "grunt-saucelabs": "^8.6.2", + "istanbul": "^0.4.2", + "jscs": "^2.9.0", + "jshint": "^2.6.0", + "mocha": "^2.1.0" + }, + "files": [ + "lib" + ], + "homepage": "https://github.com/indutny/elliptic", + "keywords": [ + "EC", + "Elliptic", + "curve", + "Cryptography" + ], + "license": "MIT", + "main": "lib/elliptic.js", + "name": "elliptic", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/indutny/elliptic.git" + }, + "scripts": { + "jscs": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js", + "jshint": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js", + "lint": "npm run jscs && npm run jshint", + "test": "npm run lint && npm run unit", + "unit": "istanbul test _mocha --reporter=spec test/index.js", + "version": "grunt dist && git add dist/" + }, + "version": "6.4.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') { + stripped = stripped.substr(1) + } + return `0x${stripped}` + } + + },{"ethjs-util":155}],126:[function(require,module,exports){ + // const EthQuery = require('ethjs-query') + const EthQuery = require('eth-query') + const EventEmitter = require('events') + const pify = require('pify') + const hexUtils = require('./hexUtils') + 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.') + this._provider = opts.provider + this._query = new EthQuery(opts.provider) + // config + this._pollingInterval = opts.pollingInterval || 4 * sec + this._syncingTimeout = opts.syncingTimeout || 1 * min + // state + this._trackingBlock = null + this._trackingBlockTimestamp = null + this._currentBlock = null + this._isRunning = false + // bind methods for cleaner syntax later + 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 + // wait for "sync" event + await new Promise(resolve => this.once('latest', resolve)) + // return newly set current block + return this._currentBlock + } + + async start (opts = {}) { + // abort if already started + if (this._isRunning) return + this._isRunning = true + // if this._currentBlock + if (opts.fromBlock) { + // use specified start point + await this._setTrackingBlock(await this._fetchBlockByNumber(opts.fromBlock)) + } else { + // or query for latest + await this._setTrackingBlock(await this._fetchLatestBlock()) + } + if (this._provider.on) { + await this._initSubscription() + } else { + this._performSync() + .catch((err) => { + if (err) console.error(err) + }) + } + } + + 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 + const previous = this._trackingBlockTimestamp + const now = Date.now() + // check for desynchronization (computer sleep or no internet) + if (previous && (now - previous) > this._syncingTimeout) { + this._trackingBlockTimestamp = null + await this._warpToLatest() + } else { + this._trackingBlock = newBlock + this._trackingBlockTimestamp = now + this.emit('block', newBlock) + } + } + + async _setCurrentBlock (newBlock) { + if (this._currentBlock && (this._currentBlock.hash === newBlock.hash)) return + const oldBlock = this._currentBlock + this._currentBlock = newBlock + 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 + await this._setTrackingBlock(newBlock) + // ask for next block + this._performSync() + } else { + // set tracking block as current block + await this._setCurrentBlock(trackingBlock) + // 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")) { + // set tracking block as current block + await this._setCurrentBlock(trackingBlock) + // setup poll for next block + this._pollForNextBlock() + } else { + 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(), + method: 'eth_subscribe', + params: [ + '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(), + method: 'eth_unsubscribe', + params: [ + 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 + // ├─ gasUsed: 0x6384 + // ├─ hash: 0xf60903687b1559b9c80f2d935b4c4f468ad95c3076928c432ec34f2ef3d4eec9 + // ├─ logsBloom: 0x00000000000000000000000000000000000000000000000000000000000020000000000000000000000000040000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000 + // ├─ miner: 0x01711853335f857442ef6f349b2467c531731318 + // ├─ mixHash: 0xf0d9bec999600eec92e8e4da8fc1182e357468c9ed2f849aa17e0e900412b352 + // ├─ nonce: 0xd556d5a5504198e4 + // ├─ number: 0x72ac8 + // ├─ parentHash: 0xf5239c3ce1085194521435a5052494c02bbb1002b019684dcf368490ea6208e5 + // ├─ receiptsRoot: 0x78c6f8236094b392bcc43b47b0dc1ce93ecd2875bfb5e4e4c3431e5af698ff99 + // ├─ sha3Uncles: 0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347 + // ├─ size: 0x2ad + // ├─ stateRoot: 0x0554f145c481df2fa02ecd2da17071672740c3aa948c896f1465e6772f741ac6 + // ├─ timestamp: 0x58955844 + // ├─ totalDifficulty: 0x751d0dfa03c1 + // ├─ transactions + // │ └─ 0 + // │ ├─ blockHash: 0xf60903687b1559b9c80f2d935b4c4f468ad95c3076928c432ec34f2ef3d4eec9 + // │ ├─ blockNumber: 0x72ac8 + // │ ├─ from: 0x201354729f8d0f8b64e9a0c353c672c6a66b3857 + // │ ├─ gas: 0x15f90 + // │ ├─ gasPrice: 0x4a817c800 + // │ ├─ hash: 0xd5a15d7c2449150db4f74f42a6ca0702150a24c46c5b406a7e1b3e44908ef44d + // │ ├─ input: 0xe1fa8e849bc10d87fb03c6b0603b05a3e29043c7e0b7c927119576a4bec457e96c7d7cde + // │ ├─ nonce: 0x323e + // │ ├─ to: 0xd10e3be2bc8f959bc8c41cf65f60de721cf89adf + // │ ├─ transactionIndex: 0x0 + // │ ├─ value: 0x0 + // │ ├─ v: 0x29 + // │ ├─ r: 0xf35f8ab241e6bb3ccaffd21b268dbfc7fcb5df1c1fb83ee5306207e4a1a3e954 + // │ └─ 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){ + /** + * [js-sha3]{@link https://github.com/emn178/js-sha3} + * + * @version 0.5.7 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2015-2016 + * @license MIT + */ + /*jslint bitwise: true */ + (function () { + 'use strict'; + + var root = typeof window === 'object' ? window : {}; + var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node; + if (NODE_JS) { + root = global; + } + var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && typeof module === 'object' && module.exports; + var HEX_CHARS = '0123456789abcdef'.split(''); + var SHAKE_PADDING = [31, 7936, 2031616, 520093696]; + var KECCAK_PADDING = [1, 256, 65536, 16777216]; + var PADDING = [6, 1536, 393216, 100663296]; + var SHIFT = [0, 8, 16, 24]; + var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, + 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, + 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, + 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, + 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]; + var BITS = [224, 256, 384, 512]; + var SHAKE_BITS = [128, 256]; + var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array']; + + var createOutputMethod = function (bits, padding, outputType) { + return function (message) { + return new Keccak(bits, padding, bits).update(message)[outputType](); + }; + }; + + var createShakeOutputMethod = function (bits, padding, outputType) { + return function (message, outputBits) { + return new Keccak(bits, padding, outputBits).update(message)[outputType](); + }; + }; + + var createMethod = function (bits, padding) { + var method = createOutputMethod(bits, padding, 'hex'); + method.create = function () { + return new Keccak(bits, padding, bits); + }; + method.update = function (message) { + return method.create().update(message); + }; + for (var i = 0; i < OUTPUT_TYPES.length; ++i) { + var type = OUTPUT_TYPES[i]; + method[type] = createOutputMethod(bits, padding, type); + } + return method; + }; + + var createShakeMethod = function (bits, padding) { + var method = createShakeOutputMethod(bits, padding, 'hex'); + method.create = function (outputBits) { + return new Keccak(bits, padding, outputBits); + }; + method.update = function (message, outputBits) { + return method.create(outputBits).update(message); + }; + for (var i = 0; i < OUTPUT_TYPES.length; ++i) { + var type = OUTPUT_TYPES[i]; + method[type] = createShakeOutputMethod(bits, padding, type); + } + return method; + }; + + var algorithms = [ + {name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod}, + {name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod}, + {name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod} + ]; + + var methods = {}, methodNames = []; + + for (var i = 0; i < algorithms.length; ++i) { + var algorithm = algorithms[i]; + var bits = algorithm.bits; + for (var j = 0; j < bits.length; ++j) { + var methodName = algorithm.name +'_' + bits[j]; + methodNames.push(methodName); + methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding); + } + } + + function Keccak(bits, padding, outputBits) { + this.blocks = []; + this.s = []; + this.padding = padding; + this.outputBits = outputBits; + this.reset = true; + this.block = 0; + this.start = 0; + this.blockCount = (1600 - (bits << 1)) >> 5; + this.byteCount = this.blockCount << 2; + this.outputBlocks = outputBits >> 5; + this.extraBytes = (outputBits & 31) >> 3; + + for (var i = 0; i < 50; ++i) { + this.s[i] = 0; + } + } + + Keccak.prototype.update = function (message) { + var notString = typeof message !== 'string'; + if (notString && message.constructor === ArrayBuffer) { + message = new Uint8Array(message); + } + var length = message.length, blocks = this.blocks, byteCount = this.byteCount, + blockCount = this.blockCount, index = 0, s = this.s, i, code; + + while (index < length) { + if (this.reset) { + this.reset = false; + blocks[0] = this.block; + for (i = 1; i < blockCount + 1; ++i) { + blocks[i] = 0; + } + } + if (notString) { + for (i = this.start; index < length && i < byteCount; ++index) { + blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; + } + } else { + for (i = this.start; index < length && i < byteCount; ++index) { + code = message.charCodeAt(index); + if (code < 0x80) { + blocks[i >> 2] |= code << SHIFT[i++ & 3]; + } else if (code < 0x800) { + blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } else if (code < 0xd800 || code >= 0xe000) { + blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } else { + code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); + blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } + } + } + this.lastByteIndex = i; + if (i >= byteCount) { + this.start = i - byteCount; + this.block = blocks[blockCount]; + for (i = 0; i < blockCount; ++i) { + s[i] ^= blocks[i]; + } + f(s); + this.reset = true; + } else { + this.start = i; + } + } + return this; + }; + + Keccak.prototype.finalize = function () { + var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s; + blocks[i >> 2] |= this.padding[i & 3]; + if (this.lastByteIndex === this.byteCount) { + blocks[0] = blocks[blockCount]; + for (i = 1; i < blockCount + 1; ++i) { + blocks[i] = 0; + } + } + blocks[blockCount - 1] |= 0x80000000; + for (i = 0; i < blockCount; ++i) { + s[i] ^= blocks[i]; + } + f(s); + }; + + Keccak.prototype.toString = Keccak.prototype.hex = function () { + this.finalize(); + + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, + extraBytes = this.extraBytes, i = 0, j = 0; + var hex = '', block; + while (j < outputBlocks) { + for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { + block = s[i]; + hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] + + HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] + + HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] + + HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F]; + } + if (j % blockCount === 0) { + f(s); + i = 0; + } + } + if (extraBytes) { + block = s[i]; + if (extraBytes > 0) { + hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F]; + } + if (extraBytes > 1) { + hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F]; + } + if (extraBytes > 2) { + hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F]; + } + } + return hex; + }; + + Keccak.prototype.arrayBuffer = function () { + this.finalize(); + + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, + extraBytes = this.extraBytes, i = 0, j = 0; + var bytes = this.outputBits >> 3; + var buffer; + if (extraBytes) { + buffer = new ArrayBuffer((outputBlocks + 1) << 2); + } else { + buffer = new ArrayBuffer(bytes); + } + var array = new Uint32Array(buffer); + while (j < outputBlocks) { + for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { + array[j] = s[i]; + } + if (j % blockCount === 0) { + f(s); + } + } + if (extraBytes) { + array[i] = s[i]; + buffer = buffer.slice(0, bytes); + } + return buffer; + }; + + Keccak.prototype.buffer = Keccak.prototype.arrayBuffer; + + Keccak.prototype.digest = Keccak.prototype.array = function () { + this.finalize(); + + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, + extraBytes = this.extraBytes, i = 0, j = 0; + var array = [], offset, block; + while (j < outputBlocks) { + for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { + offset = j << 2; + block = s[i]; + array[offset] = block & 0xFF; + array[offset + 1] = (block >> 8) & 0xFF; + array[offset + 2] = (block >> 16) & 0xFF; + array[offset + 3] = (block >> 24) & 0xFF; + } + if (j % blockCount === 0) { + f(s); + } + } + if (extraBytes) { + offset = j << 2; + block = s[i]; + if (extraBytes > 0) { + array[offset] = block & 0xFF; + } + if (extraBytes > 1) { + array[offset + 1] = (block >> 8) & 0xFF; + } + if (extraBytes > 2) { + array[offset + 2] = (block >> 16) & 0xFF; + } + } + return array; + }; + + var f = function (s) { + var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, + b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, + b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, + b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49; + for (n = 0; n < 48; n += 2) { + c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]; + c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]; + c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]; + c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]; + c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]; + c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]; + c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]; + c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]; + c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]; + c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]; + + h = c8 ^ ((c2 << 1) | (c3 >>> 31)); + l = c9 ^ ((c3 << 1) | (c2 >>> 31)); + s[0] ^= h; + s[1] ^= l; + s[10] ^= h; + s[11] ^= l; + s[20] ^= h; + s[21] ^= l; + s[30] ^= h; + s[31] ^= l; + s[40] ^= h; + s[41] ^= l; + h = c0 ^ ((c4 << 1) | (c5 >>> 31)); + l = c1 ^ ((c5 << 1) | (c4 >>> 31)); + s[2] ^= h; + s[3] ^= l; + s[12] ^= h; + s[13] ^= l; + s[22] ^= h; + s[23] ^= l; + s[32] ^= h; + s[33] ^= l; + s[42] ^= h; + s[43] ^= l; + h = c2 ^ ((c6 << 1) | (c7 >>> 31)); + l = c3 ^ ((c7 << 1) | (c6 >>> 31)); + s[4] ^= h; + s[5] ^= l; + s[14] ^= h; + s[15] ^= l; + s[24] ^= h; + s[25] ^= l; + s[34] ^= h; + s[35] ^= l; + s[44] ^= h; + s[45] ^= l; + h = c4 ^ ((c8 << 1) | (c9 >>> 31)); + l = c5 ^ ((c9 << 1) | (c8 >>> 31)); + s[6] ^= h; + s[7] ^= l; + s[16] ^= h; + s[17] ^= l; + s[26] ^= h; + s[27] ^= l; + s[36] ^= h; + s[37] ^= l; + s[46] ^= h; + s[47] ^= l; + h = c6 ^ ((c0 << 1) | (c1 >>> 31)); + l = c7 ^ ((c1 << 1) | (c0 >>> 31)); + s[8] ^= h; + s[9] ^= l; + s[18] ^= h; + s[19] ^= l; + s[28] ^= h; + s[29] ^= l; + s[38] ^= h; + s[39] ^= l; + s[48] ^= h; + s[49] ^= l; + + b0 = s[0]; + b1 = s[1]; + b32 = (s[11] << 4) | (s[10] >>> 28); + b33 = (s[10] << 4) | (s[11] >>> 28); + b14 = (s[20] << 3) | (s[21] >>> 29); + b15 = (s[21] << 3) | (s[20] >>> 29); + b46 = (s[31] << 9) | (s[30] >>> 23); + b47 = (s[30] << 9) | (s[31] >>> 23); + b28 = (s[40] << 18) | (s[41] >>> 14); + b29 = (s[41] << 18) | (s[40] >>> 14); + b20 = (s[2] << 1) | (s[3] >>> 31); + b21 = (s[3] << 1) | (s[2] >>> 31); + b2 = (s[13] << 12) | (s[12] >>> 20); + b3 = (s[12] << 12) | (s[13] >>> 20); + b34 = (s[22] << 10) | (s[23] >>> 22); + b35 = (s[23] << 10) | (s[22] >>> 22); + b16 = (s[33] << 13) | (s[32] >>> 19); + b17 = (s[32] << 13) | (s[33] >>> 19); + b48 = (s[42] << 2) | (s[43] >>> 30); + b49 = (s[43] << 2) | (s[42] >>> 30); + b40 = (s[5] << 30) | (s[4] >>> 2); + b41 = (s[4] << 30) | (s[5] >>> 2); + b22 = (s[14] << 6) | (s[15] >>> 26); + b23 = (s[15] << 6) | (s[14] >>> 26); + b4 = (s[25] << 11) | (s[24] >>> 21); + b5 = (s[24] << 11) | (s[25] >>> 21); + b36 = (s[34] << 15) | (s[35] >>> 17); + b37 = (s[35] << 15) | (s[34] >>> 17); + b18 = (s[45] << 29) | (s[44] >>> 3); + b19 = (s[44] << 29) | (s[45] >>> 3); + b10 = (s[6] << 28) | (s[7] >>> 4); + b11 = (s[7] << 28) | (s[6] >>> 4); + b42 = (s[17] << 23) | (s[16] >>> 9); + b43 = (s[16] << 23) | (s[17] >>> 9); + b24 = (s[26] << 25) | (s[27] >>> 7); + b25 = (s[27] << 25) | (s[26] >>> 7); + b6 = (s[36] << 21) | (s[37] >>> 11); + b7 = (s[37] << 21) | (s[36] >>> 11); + b38 = (s[47] << 24) | (s[46] >>> 8); + b39 = (s[46] << 24) | (s[47] >>> 8); + b30 = (s[8] << 27) | (s[9] >>> 5); + b31 = (s[9] << 27) | (s[8] >>> 5); + b12 = (s[18] << 20) | (s[19] >>> 12); + b13 = (s[19] << 20) | (s[18] >>> 12); + b44 = (s[29] << 7) | (s[28] >>> 25); + b45 = (s[28] << 7) | (s[29] >>> 25); + b26 = (s[38] << 8) | (s[39] >>> 24); + b27 = (s[39] << 8) | (s[38] >>> 24); + b8 = (s[48] << 14) | (s[49] >>> 18); + b9 = (s[49] << 14) | (s[48] >>> 18); + + s[0] = b0 ^ (~b2 & b4); + s[1] = b1 ^ (~b3 & b5); + s[10] = b10 ^ (~b12 & b14); + s[11] = b11 ^ (~b13 & b15); + s[20] = b20 ^ (~b22 & b24); + s[21] = b21 ^ (~b23 & b25); + s[30] = b30 ^ (~b32 & b34); + s[31] = b31 ^ (~b33 & b35); + s[40] = b40 ^ (~b42 & b44); + s[41] = b41 ^ (~b43 & b45); + s[2] = b2 ^ (~b4 & b6); + s[3] = b3 ^ (~b5 & b7); + s[12] = b12 ^ (~b14 & b16); + s[13] = b13 ^ (~b15 & b17); + s[22] = b22 ^ (~b24 & b26); + s[23] = b23 ^ (~b25 & b27); + s[32] = b32 ^ (~b34 & b36); + s[33] = b33 ^ (~b35 & b37); + s[42] = b42 ^ (~b44 & b46); + s[43] = b43 ^ (~b45 & b47); + s[4] = b4 ^ (~b6 & b8); + s[5] = b5 ^ (~b7 & b9); + s[14] = b14 ^ (~b16 & b18); + s[15] = b15 ^ (~b17 & b19); + s[24] = b24 ^ (~b26 & b28); + s[25] = b25 ^ (~b27 & b29); + s[34] = b34 ^ (~b36 & b38); + s[35] = b35 ^ (~b37 & b39); + s[44] = b44 ^ (~b46 & b48); + s[45] = b45 ^ (~b47 & b49); + s[6] = b6 ^ (~b8 & b0); + s[7] = b7 ^ (~b9 & b1); + s[16] = b16 ^ (~b18 & b10); + s[17] = b17 ^ (~b19 & b11); + s[26] = b26 ^ (~b28 & b20); + s[27] = b27 ^ (~b29 & b21); + s[36] = b36 ^ (~b38 & b30); + s[37] = b37 ^ (~b39 & b31); + s[46] = b46 ^ (~b48 & b40); + s[47] = b47 ^ (~b49 & b41); + s[8] = b8 ^ (~b0 & b2); + s[9] = b9 ^ (~b1 & b3); + s[18] = b18 ^ (~b10 & b12); + s[19] = b19 ^ (~b11 & b13); + s[28] = b28 ^ (~b20 & b22); + s[29] = b29 ^ (~b21 & b23); + s[38] = b38 ^ (~b30 & b32); + s[39] = b39 ^ (~b31 & b33); + s[48] = b48 ^ (~b40 & b42); + s[49] = b49 ^ (~b41 & b43); + + s[0] ^= RC[n]; + s[1] ^= RC[n + 1]; + } + }; + + if (COMMON_JS) { + module.exports = methods; + } else { + for (var i = 0; i < methodNames.length; ++i) { + root[methodNames[i]] = methods[methodNames[i]]; + } + } + })(); + + }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + },{"_process":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 + 'Gateway timeout', + 'ETIMEDOUT', + 'ECONNRESET', + // ignore server sent html error pages + // 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++) { + try { + // attempt request + await performFetch(network, req, res) + // request was succesful + break + } catch (err) { + // an error was caught while performing the request + // if not retriable, resolve with the encountered error + if (!isRetriableError(err)) { + // abort with error + throw err + } + // if no more attempts remaining, throw an error + const remainingAttempts = maxAttempts - attempt + if (!remainingAttempts) { + const errMsg = `InfuraProvider - cannot complete request. All retries exhausted.\nOriginal Error:\n${err.toString()}\n\n` + const retriesExhaustedErr = new Error(errMsg) + throw retriesExhaustedErr + } + // otherwise, ignore error and retry again after timeout + await timeout(1000) + } + } + // 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) + const rawData = await response.text() + // handle errors + if (!response.ok) { + 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) + if (isPostMethod) { + fetchParams.method = 'POST' + fetchParams.headers = { + 'Accept': 'application/json', + 'Content-Type': 'application/json' + }, + fetchParams.body = JSON.stringify(cleanReq) + } else { + fetchParams.method = 'GET' + 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 { + id: req.id, + jsonrpc: req.jsonrpc, + method: req.method, + 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 = []; + for (var i = 0; i < num; ++i) { + a.push(fn(i)); + }return a; + }; + + var replicate = function replicate(num, val) { + return generate(num, function () { + return val; + }); + }; + + var concat = function concat(a, b) { + return a.concat(b); + }; + + var flatten = function flatten(a) { + var r = []; + for (var j = 0, J = a.length; j < J; ++j) { + for (var i = 0, I = a[j].length; i < I; ++i) { + r.push(a[j][i]); + } + }return r; + }; + + var chunksOf = function chunksOf(n, a) { + var b = []; + for (var i = 0, l = a.length; i < l; i += n) { + b.push(a.slice(i, i + n)); + }return b; + }; + + module.exports = { + generate: generate, + replicate: replicate, + concat: concat, + flatten: flatten, + chunksOf: chunksOf + }; + },{}],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."; + var hex = "0x"; + for (var i = 0; i < bytes; ++i) { + hex += ("00" + rnd[i].toString(16)).slice(-2); + }return hex; + }; + + var length = function length(a) { + return (a.length - 2) / 2; + }; + + var flatten = function flatten(a) { + return "0x" + a.reduce(function (r, s) { + return r + s.slice(2); + }, ""); + }; + + var slice = function slice(i, j, bs) { + return "0x" + bs.slice(i * 2 + 2, j * 2 + 2); + }; + + var reverse = function reverse(hex) { + var rev = "0x"; + for (var i = 0, l = length(hex); i < l; ++i) { + rev += hex.slice((l - i) * 2, (l - i + 1) * 2); + } + return rev; + }; + + var pad = function pad(l, hex) { + return hex.length === l * 2 + 2 ? hex : pad(l, "0x" + "0" + hex.slice(2)); + }; + + var padRight = function padRight(l, hex) { + return hex.length === l * 2 + 2 ? hex : padRight(l, hex + "0"); + }; + + var toArray = function toArray(hex) { + var arr = []; + for (var i = 2, l = hex.length; i < l; i += 2) { + arr.push(parseInt(hex.slice(i, i + 2), 16)); + }return arr; + }; + + var fromArray = function fromArray(arr) { + var hex = "0x"; + for (var i = 0, l = arr.length; i < l; ++i) { + var b = arr[i]; + hex += (b < 16 ? "0" : "") + b.toString(16); + } + return hex; + }; + + var toUint8Array = function toUint8Array(hex) { + return new Uint8Array(toArray(hex)); + }; + + var fromUint8Array = function fromUint8Array(arr) { + return fromArray([].slice.call(arr, 0)); + }; + + var fromNumber = function fromNumber(num) { + var hex = num.toString(16); + return hex.length % 2 === 0 ? "0x" + hex : "0x0" + hex; + }; + + var toNumber = function toNumber(hex) { + return parseInt(hex.slice(2), 16); + }; + + var concat = function concat(a, b) { + return a.concat(b.slice(2)); + }; + + var fromNat = function fromNat(bn) { + return bn === "0x0" ? "0x" : bn.length % 2 === 0 ? bn : "0x0" + bn.slice(2); + }; + + var toNat = function toNat(bn) { + return bn[2] === "0" ? "0x" + bn.slice(3) : bn; + }; + + var fromAscii = function fromAscii(ascii) { + var hex = "0x"; + for (var i = 0; i < ascii.length; ++i) { + hex += ("00" + ascii.charCodeAt(i).toString(16)).slice(-2); + }return hex; + }; + + var toAscii = function toAscii(hex) { + var ascii = ""; + for (var i = 2; i < hex.length; i += 2) { + ascii += String.fromCharCode(parseInt(hex.slice(i, i + 2), 16)); + }return ascii; + }; + + // From https://gist.github.com/pascaldekloe/62546103a1576803dade9269ccf76330 + var fromString = function fromString(s) { + var makeByte = function makeByte(uint8) { + var b = uint8.toString(16); + return b.length < 2 ? "0" + b : b; + }; + var bytes = "0x"; + for (var ci = 0; ci != s.length; ci++) { + var c = s.charCodeAt(ci); + if (c < 128) { + bytes += makeByte(c); + continue; + } + if (c < 2048) { + bytes += makeByte(c >> 6 | 192); + } else { + if (c > 0xd7ff && c < 0xdc00) { + if (++ci == s.length) return null; + var c2 = s.charCodeAt(ci); + if (c2 < 0xdc00 || c2 > 0xdfff) return null; + c = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff); + bytes += makeByte(c >> 18 | 240); + bytes += makeByte(c >> 12 & 63 | 128); + } else { + // c <= 0xffff + bytes += makeByte(c >> 12 | 224); + } + bytes += makeByte(c >> 6 & 63 | 128); + } + bytes += makeByte(c & 63 | 128); + } + return bytes; + }; + + var toString = function toString(bytes) { + var s = ''; + var i = 0; + var l = length(bytes); + while (i < l) { + var c = at(bytes, i++); + if (c > 127) { + if (c > 191 && c < 224) { + if (i >= l) return null; + c = (c & 31) << 6 | at(bytes, i) & 63; + } else if (c > 223 && c < 240) { + if (i + 1 >= l) return null; + c = (c & 15) << 12 | (at(bytes, i) & 63) << 6 | at(bytes, ++i) & 63; + } else if (c > 239 && c < 248) { + if (i + 2 >= l) return null; + c = (c & 7) << 18 | (at(bytes, i) & 63) << 12 | (at(bytes, ++i) & 63) << 6 | at(bytes, ++i) & 63; + } else return null; + ++i; + } + if (c <= 0xffff) s += String.fromCharCode(c);else if (c <= 0x10ffff) { + c -= 0x10000; + s += String.fromCharCode(c >> 10 | 0xd800); + s += String.fromCharCode(c & 0x3FF | 0xdc00); + } else return null; + } + return s; + }; + + module.exports = { + random: random, + length: length, + concat: concat, + flatten: flatten, + slice: slice, + reverse: reverse, + pad: pad, + padRight: padRight, + fromAscii: fromAscii, + toAscii: toAscii, + fromString: fromString, + toString: toString, + fromNumber: fromNumber, + toNumber: toNumber, + fromNat: fromNat, + toNat: toNat, + fromArray: fromArray, + toArray: toArray, + fromUint8Array: fromUint8Array, + toUint8Array: toUint8Array + }; + },{"./array.js":132}],134:[function(require,module,exports){ + // This was ported from https://github.com/emn178/js-sha3, with some minor + // modifications and pruning. It is licensed under MIT: + // + // Copyright 2015-2016 Chen, Yi-Cyuan + // + // Permission is hereby granted, free of charge, to any person obtaining + // a copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to + // permit persons to whom the Software is furnished to do so, subject to + // the following conditions: + // + // The above copyright notice and this permission notice shall be + // included in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + var HEX_CHARS = '0123456789abcdef'.split(''); + var KECCAK_PADDING = [1, 256, 65536, 16777216]; + var SHIFT = [0, 8, 16, 24]; + var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]; + + var Keccak = function Keccak(bits) { + return { + blocks: [], + reset: true, + block: 0, + start: 0, + blockCount: 1600 - (bits << 1) >> 5, + outputBlocks: bits >> 5, + s: function (s) { + return [].concat(s, s, s, s, s); + }([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) + }; + }; + + var update = function update(state, message) { + var length = message.length, + blocks = state.blocks, + byteCount = state.blockCount << 2, + blockCount = state.blockCount, + outputBlocks = state.outputBlocks, + s = state.s, + index = 0, + i, + code; + + // update + while (index < length) { + if (state.reset) { + state.reset = false; + blocks[0] = state.block; + for (i = 1; i < blockCount + 1; ++i) { + blocks[i] = 0; + } + } + if (typeof message !== "string") { + for (i = state.start; index < length && i < byteCount; ++index) { + blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; + } + } else { + for (i = state.start; index < length && i < byteCount; ++index) { + code = message.charCodeAt(index); + if (code < 0x80) { + blocks[i >> 2] |= code << SHIFT[i++ & 3]; + } else if (code < 0x800) { + blocks[i >> 2] |= (0xc0 | code >> 6) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3]; + } else if (code < 0xd800 || code >= 0xe000) { + blocks[i >> 2] |= (0xe0 | code >> 12) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | code >> 6 & 0x3f) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3]; + } else { + code = 0x10000 + ((code & 0x3ff) << 10 | message.charCodeAt(++index) & 0x3ff); + blocks[i >> 2] |= (0xf0 | code >> 18) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | code >> 12 & 0x3f) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | code >> 6 & 0x3f) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3]; + } + } + } + state.lastByteIndex = i; + if (i >= byteCount) { + state.start = i - byteCount; + state.block = blocks[blockCount]; + for (i = 0; i < blockCount; ++i) { + s[i] ^= blocks[i]; + } + f(s); + state.reset = true; + } else { + state.start = i; + } + } + + // finalize + i = state.lastByteIndex; + blocks[i >> 2] |= KECCAK_PADDING[i & 3]; + if (state.lastByteIndex === byteCount) { + blocks[0] = blocks[blockCount]; + for (i = 1; i < blockCount + 1; ++i) { + blocks[i] = 0; + } + } + blocks[blockCount - 1] |= 0x80000000; + for (i = 0; i < blockCount; ++i) { + s[i] ^= blocks[i]; + } + f(s); + + // toString + var hex = '', + i = 0, + j = 0, + block; + while (j < outputBlocks) { + for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { + block = s[i]; + hex += HEX_CHARS[block >> 4 & 0x0F] + HEX_CHARS[block & 0x0F] + HEX_CHARS[block >> 12 & 0x0F] + HEX_CHARS[block >> 8 & 0x0F] + HEX_CHARS[block >> 20 & 0x0F] + HEX_CHARS[block >> 16 & 0x0F] + HEX_CHARS[block >> 28 & 0x0F] + HEX_CHARS[block >> 24 & 0x0F]; + } + if (j % blockCount === 0) { + f(s); + i = 0; + } + } + return "0x" + hex; + }; + + var f = function f(s) { + var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49; + + for (n = 0; n < 48; n += 2) { + c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]; + c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]; + c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]; + c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]; + c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]; + c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]; + c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]; + c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]; + c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]; + c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]; + + h = c8 ^ (c2 << 1 | c3 >>> 31); + l = c9 ^ (c3 << 1 | c2 >>> 31); + s[0] ^= h; + s[1] ^= l; + s[10] ^= h; + s[11] ^= l; + s[20] ^= h; + s[21] ^= l; + s[30] ^= h; + s[31] ^= l; + s[40] ^= h; + s[41] ^= l; + h = c0 ^ (c4 << 1 | c5 >>> 31); + l = c1 ^ (c5 << 1 | c4 >>> 31); + s[2] ^= h; + s[3] ^= l; + s[12] ^= h; + s[13] ^= l; + s[22] ^= h; + s[23] ^= l; + s[32] ^= h; + s[33] ^= l; + s[42] ^= h; + s[43] ^= l; + h = c2 ^ (c6 << 1 | c7 >>> 31); + l = c3 ^ (c7 << 1 | c6 >>> 31); + s[4] ^= h; + s[5] ^= l; + s[14] ^= h; + s[15] ^= l; + s[24] ^= h; + s[25] ^= l; + s[34] ^= h; + s[35] ^= l; + s[44] ^= h; + s[45] ^= l; + h = c4 ^ (c8 << 1 | c9 >>> 31); + l = c5 ^ (c9 << 1 | c8 >>> 31); + s[6] ^= h; + s[7] ^= l; + s[16] ^= h; + s[17] ^= l; + s[26] ^= h; + s[27] ^= l; + s[36] ^= h; + s[37] ^= l; + s[46] ^= h; + s[47] ^= l; + h = c6 ^ (c0 << 1 | c1 >>> 31); + l = c7 ^ (c1 << 1 | c0 >>> 31); + s[8] ^= h; + s[9] ^= l; + s[18] ^= h; + s[19] ^= l; + s[28] ^= h; + s[29] ^= l; + s[38] ^= h; + s[39] ^= l; + s[48] ^= h; + s[49] ^= l; + + b0 = s[0]; + b1 = s[1]; + b32 = s[11] << 4 | s[10] >>> 28; + b33 = s[10] << 4 | s[11] >>> 28; + b14 = s[20] << 3 | s[21] >>> 29; + b15 = s[21] << 3 | s[20] >>> 29; + b46 = s[31] << 9 | s[30] >>> 23; + b47 = s[30] << 9 | s[31] >>> 23; + b28 = s[40] << 18 | s[41] >>> 14; + b29 = s[41] << 18 | s[40] >>> 14; + b20 = s[2] << 1 | s[3] >>> 31; + b21 = s[3] << 1 | s[2] >>> 31; + b2 = s[13] << 12 | s[12] >>> 20; + b3 = s[12] << 12 | s[13] >>> 20; + b34 = s[22] << 10 | s[23] >>> 22; + b35 = s[23] << 10 | s[22] >>> 22; + b16 = s[33] << 13 | s[32] >>> 19; + b17 = s[32] << 13 | s[33] >>> 19; + b48 = s[42] << 2 | s[43] >>> 30; + b49 = s[43] << 2 | s[42] >>> 30; + b40 = s[5] << 30 | s[4] >>> 2; + b41 = s[4] << 30 | s[5] >>> 2; + b22 = s[14] << 6 | s[15] >>> 26; + b23 = s[15] << 6 | s[14] >>> 26; + b4 = s[25] << 11 | s[24] >>> 21; + b5 = s[24] << 11 | s[25] >>> 21; + b36 = s[34] << 15 | s[35] >>> 17; + b37 = s[35] << 15 | s[34] >>> 17; + b18 = s[45] << 29 | s[44] >>> 3; + b19 = s[44] << 29 | s[45] >>> 3; + b10 = s[6] << 28 | s[7] >>> 4; + b11 = s[7] << 28 | s[6] >>> 4; + b42 = s[17] << 23 | s[16] >>> 9; + b43 = s[16] << 23 | s[17] >>> 9; + b24 = s[26] << 25 | s[27] >>> 7; + b25 = s[27] << 25 | s[26] >>> 7; + b6 = s[36] << 21 | s[37] >>> 11; + b7 = s[37] << 21 | s[36] >>> 11; + b38 = s[47] << 24 | s[46] >>> 8; + b39 = s[46] << 24 | s[47] >>> 8; + b30 = s[8] << 27 | s[9] >>> 5; + b31 = s[9] << 27 | s[8] >>> 5; + b12 = s[18] << 20 | s[19] >>> 12; + b13 = s[19] << 20 | s[18] >>> 12; + b44 = s[29] << 7 | s[28] >>> 25; + b45 = s[28] << 7 | s[29] >>> 25; + b26 = s[38] << 8 | s[39] >>> 24; + b27 = s[39] << 8 | s[38] >>> 24; + b8 = s[48] << 14 | s[49] >>> 18; + b9 = s[49] << 14 | s[48] >>> 18; + + s[0] = b0 ^ ~b2 & b4; + s[1] = b1 ^ ~b3 & b5; + s[10] = b10 ^ ~b12 & b14; + s[11] = b11 ^ ~b13 & b15; + s[20] = b20 ^ ~b22 & b24; + s[21] = b21 ^ ~b23 & b25; + s[30] = b30 ^ ~b32 & b34; + s[31] = b31 ^ ~b33 & b35; + s[40] = b40 ^ ~b42 & b44; + s[41] = b41 ^ ~b43 & b45; + s[2] = b2 ^ ~b4 & b6; + s[3] = b3 ^ ~b5 & b7; + s[12] = b12 ^ ~b14 & b16; + s[13] = b13 ^ ~b15 & b17; + s[22] = b22 ^ ~b24 & b26; + s[23] = b23 ^ ~b25 & b27; + s[32] = b32 ^ ~b34 & b36; + s[33] = b33 ^ ~b35 & b37; + s[42] = b42 ^ ~b44 & b46; + s[43] = b43 ^ ~b45 & b47; + s[4] = b4 ^ ~b6 & b8; + s[5] = b5 ^ ~b7 & b9; + s[14] = b14 ^ ~b16 & b18; + s[15] = b15 ^ ~b17 & b19; + s[24] = b24 ^ ~b26 & b28; + s[25] = b25 ^ ~b27 & b29; + s[34] = b34 ^ ~b36 & b38; + s[35] = b35 ^ ~b37 & b39; + s[44] = b44 ^ ~b46 & b48; + s[45] = b45 ^ ~b47 & b49; + s[6] = b6 ^ ~b8 & b0; + s[7] = b7 ^ ~b9 & b1; + s[16] = b16 ^ ~b18 & b10; + s[17] = b17 ^ ~b19 & b11; + s[26] = b26 ^ ~b28 & b20; + s[27] = b27 ^ ~b29 & b21; + s[36] = b36 ^ ~b38 & b30; + s[37] = b37 ^ ~b39 & b31; + s[46] = b46 ^ ~b48 & b40; + s[47] = b47 ^ ~b49 & b41; + s[8] = b8 ^ ~b0 & b2; + s[9] = b9 ^ ~b1 & b3; + s[18] = b18 ^ ~b10 & b12; + s[19] = b19 ^ ~b11 & b13; + s[28] = b28 ^ ~b20 & b22; + s[29] = b29 ^ ~b21 & b23; + s[38] = b38 ^ ~b30 & b32; + s[39] = b39 ^ ~b31 & b33; + s[48] = b48 ^ ~b40 & b42; + s[49] = b49 ^ ~b41 & b43; + + s[0] ^= RC[n]; + s[1] ^= RC[n + 1]; + } + }; + + var keccak = function keccak(bits) { + return function (str) { + var msg; + if (str.slice(0, 2) === "0x") { + msg = []; + for (var i = 2, l = str.length; i < l; i += 2) { + msg.push(parseInt(str.slice(i, i + 2), 16)); + } + } else { + msg = str; + } + return update(Keccak(bits, bits), msg); + }; + }; + + module.exports = { + keccak256: keccak(256), + keccak512: keccak(512), + keccak256s: keccak(256), + keccak512s: keccak(512) + }; + },{}],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') + EthQuery.prototype.getTransactionCount = generateFnWithDefaultBlockFor(2, 'eth_getTransactionCount') + EthQuery.prototype.getStorageAt = generateFnWithDefaultBlockFor(3, 'eth_getStorageAt') + EthQuery.prototype.call = generateFnWithDefaultBlockFor(2, 'eth_call') + // standard + EthQuery.prototype.protocolVersion = generateFnFor('eth_protocolVersion') + EthQuery.prototype.syncing = generateFnFor('eth_syncing') + EthQuery.prototype.coinbase = generateFnFor('eth_coinbase') + EthQuery.prototype.mining = generateFnFor('eth_mining') + EthQuery.prototype.hashrate = generateFnFor('eth_hashrate') + EthQuery.prototype.gasPrice = generateFnFor('eth_gasPrice') + EthQuery.prototype.accounts = generateFnFor('eth_accounts') + EthQuery.prototype.blockNumber = generateFnFor('eth_blockNumber') + EthQuery.prototype.getBlockTransactionCountByHash = generateFnFor('eth_getBlockTransactionCountByHash') + EthQuery.prototype.getBlockTransactionCountByNumber = generateFnFor('eth_getBlockTransactionCountByNumber') + EthQuery.prototype.getUncleCountByBlockHash = generateFnFor('eth_getUncleCountByBlockHash') + EthQuery.prototype.getUncleCountByBlockNumber = generateFnFor('eth_getUncleCountByBlockNumber') + EthQuery.prototype.sign = generateFnFor('eth_sign') + EthQuery.prototype.sendTransaction = generateFnFor('eth_sendTransaction') + EthQuery.prototype.sendRawTransaction = generateFnFor('eth_sendRawTransaction') + EthQuery.prototype.estimateGas = generateFnFor('eth_estimateGas') + EthQuery.prototype.getBlockByHash = generateFnFor('eth_getBlockByHash') + EthQuery.prototype.getBlockByNumber = generateFnFor('eth_getBlockByNumber') + EthQuery.prototype.getTransactionByHash = generateFnFor('eth_getTransactionByHash') + EthQuery.prototype.getTransactionByBlockHashAndIndex = generateFnFor('eth_getTransactionByBlockHashAndIndex') + EthQuery.prototype.getTransactionByBlockNumberAndIndex = generateFnFor('eth_getTransactionByBlockNumberAndIndex') + EthQuery.prototype.getTransactionReceipt = generateFnFor('eth_getTransactionReceipt') + EthQuery.prototype.getUncleByBlockHashAndIndex = generateFnFor('eth_getUncleByBlockHashAndIndex') + EthQuery.prototype.getUncleByBlockNumberAndIndex = generateFnFor('eth_getUncleByBlockNumberAndIndex') + EthQuery.prototype.getCompilers = generateFnFor('eth_getCompilers') + EthQuery.prototype.compileLLL = generateFnFor('eth_compileLLL') + EthQuery.prototype.compileSolidity = generateFnFor('eth_compileSolidity') + EthQuery.prototype.compileSerpent = generateFnFor('eth_compileSerpent') + EthQuery.prototype.newFilter = generateFnFor('eth_newFilter') + EthQuery.prototype.newBlockFilter = generateFnFor('eth_newBlockFilter') + EthQuery.prototype.newPendingTransactionFilter = generateFnFor('eth_newPendingTransactionFilter') + EthQuery.prototype.uninstallFilter = generateFnFor('eth_uninstallFilter') + EthQuery.prototype.getFilterChanges = generateFnFor('eth_getFilterChanges') + EthQuery.prototype.getFilterLogs = generateFnFor('eth_getFilterLogs') + EthQuery.prototype.getLogs = generateFnFor('eth_getLogs') + 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){ + if (!err && response.error) err = new Error('EthQuery - RPC Error - '+response.error.message) + if (err) return cb(err) + cb(null, response.result) + }) + } + + // util + + function generateFnFor(methodName){ + return function(){ + const self = this + var args = [].slice.call(arguments) + var cb = args.pop() + self.sendAsync({ + method: methodName, + params: args, + }, cb) + } + } + + function generateFnWithDefaultBlockFor(argCount, methodName){ + return function(){ + const self = this + var args = [].slice.call(arguments) + var cb = args.pop() + // set optional default block param + if (args.length < argCount) args.push('latest') + self.sendAsync({ + method: methodName, + params: args, + }, cb) + } + } + + function createPayload(data){ + return extend({ + // defaults + id: createRandomId(), + jsonrpc: '2.0', + params: [], + // 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) + const vSig = ethUtil.bufferToInt(v) + const rStr = padWithZeroes(ethUtil.toUnsigned(rSig).toString('hex'), 64) + const sStr = padWithZeroes(ethUtil.toUnsigned(sSig).toString('hex'), 64) + 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) + var sig = ethUtil.ecsign(msgHash, privateKey) + 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 + */ + 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 + }) + const types = typedData.map(function (e) { return e.type }) + const schema = typedData.map(function (e) { + if (!e.name) throw error + return e.type + ' ' + e.name + }) + + return ethAbi.soliditySHA3( + ['bytes32', 'bytes32'], + [ + ethAbi.soliditySHA3(new Array(typedData.length).fill('string'), schema), + ethAbi.soliditySHA3(types, data) + ] + ) + } + + 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) { + myString = '0' + myString + } + return myString + } + + },{"ethereumjs-abi":138,"ethereumjs-util":141}],137:[function(require,module,exports){ + module.exports={ + "genesisGasLimit": { + "v": 5000, + "d": "Gas limit of the Genesis block." + }, + "genesisDifficulty": { + "v": 17179869184, + "d": "Difficulty of the Genesis block." + }, + "genesisNonce": { + "v": "0x0000000000000042", + "d": "the geneis nonce" + }, + "genesisExtraData": { + "v": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa", + "d": "extra data " + }, + "genesisHash": { + "v": "0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3", + "d": "genesis hash" + }, + "genesisStateRoot": { + "v": "0xd7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544", + "d": "the genesis state root" + }, + "minGasLimit": { + "v": 5000, + "d": "Minimum the gas limit may ever be." + }, + "gasLimitBoundDivisor": { + "v": 1024, + "d": "The bound divisor of the gas limit, used in update calculations." + }, + "minimumDifficulty": { + "v": 131072, + "d": "The minimum that the difficulty may ever be." + }, + "difficultyBoundDivisor": { + "v": 2048, + "d": "The bound divisor of the difficulty, used in the update calculations." + }, + "durationLimit": { + "v": 13, + "d": "The decision boundary on the blocktime duration used to determine whether difficulty should go up or not." + }, + "maximumExtraDataSize": { + "v": 32, + "d": "Maximum size extra data may be after Genesis." + }, + "epochDuration": { + "v": 30000, + "d": "Duration between proof-of-work epochs." + }, + "stackLimit": { + "v": 1024, + "d": "Maximum size of VM stack allowed." + }, + "callCreateDepth": { + "v": 1024, + "d": "Maximum depth of call/create stack." + }, + + "tierStepGas": { + "v": [0, 2, 3, 5, 8, 10, 20], + "d": "Once per operation, for a selection of them." + }, + "expGas": { + "v": 10, + "d": "Once per EXP instuction." + }, + "expByteGas": { + "v": 10, + "d": "Times ceil(log256(exponent)) for the EXP instruction." + }, + + "sha3Gas": { + "v": 30, + "d": "Once per SHA3 operation." + }, + "sha3WordGas": { + "v": 6, + "d": "Once per word of the SHA3 operation's data." + }, + "sloadGas": { + "v": 50, + "d": "Once per SLOAD operation." + }, + "sstoreSetGas": { + "v": 20000, + "d": "Once per SSTORE operation if the zeroness changes from zero." + }, + "sstoreResetGas": { + "v": 5000, + "d": "Once per SSTORE operation if the zeroness does not change from zero." + }, + "sstoreRefundGas": { + "v": 15000, + "d": "Once per SSTORE operation if the zeroness changes to zero." + }, + "jumpdestGas": { + "v": 1, + "d": "Refunded gas, once per SSTORE operation if the zeroness changes to zero." + }, + + "logGas": { + "v": 375, + "d": "Per LOG* operation." + }, + "logDataGas": { + "v": 8, + "d": "Per byte in a LOG* operation's data." + }, + "logTopicGas": { + "v": 375, + "d": "Multiplied by the * of the LOG*, per LOG transaction. e.g. LOG0 incurs 0 * c_txLogTopicGas, LOG4 incurs 4 * c_txLogTopicGas." + }, + + "createGas": { + "v": 32000, + "d": "Once per CREATE operation & contract-creation transaction." + }, + + "callGas": { + "v": 40, + "d": "Once per CALL operation & message call transaction." + }, + "callStipend": { + "v": 2300, + "d": "Free gas given at beginning of call." + }, + "callValueTransferGas": { + "v": 9000, + "d": "Paid for CALL when the value transfor is non-zero." + }, + "callNewAccountGas": { + "v": 25000, + "d": "Paid for CALL when the destination address didn't exist prior." + }, + + "suicideRefundGas": { + "v": 24000, + "d": "Refunded following a suicide operation." + }, + + "memoryGas": { + "v": 3, + "d": "Times the address of the (highest referenced byte in memory + 1). NOTE: referencing happens on read, write and in instructions such as RETURN and CALL." + }, + "quadCoeffDiv": { + "v": 512, + "d": "Divisor for the quadratic particle of the memory cost equation." + }, + + "createDataGas": { + "v": 200, + "d": "" + }, + "txGas": { + "v": 21000, + "d": "Per transaction. NOTE: Not payable on data of calls between transactions." + }, + "txCreation": { + "v": 32000, + "d": "the cost of creating a contract via tx" + }, + "txDataZeroGas": { + "v": 4, + "d": "Per byte of data attached to a transaction that equals zero. NOTE: Not payable on data of calls between transactions." + }, + "txDataNonZeroGas": { + "v": 68, + "d": "Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions." + }, + + "copyGas": { + "v": 3, + "d": "Multiplied by the number of 32-byte words that are copied (round up) for any *COPY operation and added." + }, + + "ecrecoverGas": { + "v": 3000, + "d": "" + }, + "sha256Gas": { + "v": 60, + "d": "" + }, + "sha256WordGas": { + "v": 12, + "d": "" + }, + "ripemd160Gas": { + "v": 600, + "d": "" + }, + "ripemd160WordGas": { + "v": 120, + "d": "" + }, + "identityGas": { + "v": 15, + "d": "" + }, + "identityWordGas": { + "v": 3, + "d": "" + }, + "minerReward": { + "v": "5000000000000000000", + "d": "the amount a miner get rewarded for mining a block" + }, + "ommerReward": { + "v": "625000000000000000", + "d": "The amount of wei a miner of an uncle block gets for being inculded in the blockchain" + }, + "niblingReward": { + "v": "156250000000000000", + "d": "the amount a miner gets for inculding a uncle" + }, + "homeSteadForkNumber": { + "v": 1150000, + "d": "the block that the Homestead fork started at" + }, + "homesteadRepriceForkNumber": { + "v": 2463000, + "d": "the block that the Homestead Reprice (EIP150) fork started at" + }, + "timebombPeriod": { + "v": 100000, + "d": "Exponential difficulty timebomb period" + }, + "freeBlockPeriod": { + "v": 2 + } + } + + },{}],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) { + if (name.startsWith('int[')) { + return 'int256' + name.slice(3) + } else if (name === 'int') { + return 'int256' + } else if (name.startsWith('uint[')) { + return 'uint256' + name.slice(4) + } else if (name === 'uint') { + return 'uint256' + } else if (name.startsWith('fixed[')) { + return 'fixed128x128' + name.slice(5) + } else if (name === 'fixed') { + return 'fixed128x128' + } else if (name.startsWith('ufixed[')) { + return 'ufixed128x128' + name.slice(6) + } else if (name === 'ufixed') { + return 'ufixed128x128' + } + 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(/(.*)\[(.*?)\]$/) + if (tmp) { + return tmp[2] === '' ? 'dynamic' : parseInt(tmp[2], 10) + } + return null + } + + function parseNumber (arg) { + var type = typeof arg + if (type === 'string') { + if (utils.isHexPrefixed(arg)) { + return new BN(utils.stripHexPrefix(arg), 16) + } else { + return new BN(arg, 10) + } + } else if (type === 'number') { + return new BN(arg) + } else if (arg.toArray) { + // assume this is a BN for the moment, replace with BN.isBN soon + return arg + } else { + throw new Error('Argument is not a number') + } + } + + // someMethod(bytes,uint) + // someMethod(bytes,uint):(boolean) + function parseSignature (sig) { + var tmp = /^(\w+)\((.+)\)$/.exec(sig) + 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], + args: args[1].split(','), + retargs: args[2].split(',') + } + } else { + return { + method: tmp[1], + args: tmp[2].split(',') + } + } + } + + // 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') { + return encodeSingle('uint8', arg ? 1 : 0) + } else if (type === 'string') { + return encodeSingle('bytes', new Buffer(arg, 'utf8')) + } else if (isArray(type)) { + // this part handles fixed-length ([2]) and variable length ([]) arrays + // NOTE: we catch here all calls to arrays, that simplifies the rest + if (typeof arg.length === 'undefined') { + throw new Error('Not an array?') + } + size = parseTypeArray(type) + if (size !== 'dynamic' && size !== 0 && arg.length > size) { + throw new Error('Elements exceed array size: ' + size) + } + ret = [] + type = type.slice(0, type.lastIndexOf('[')) + if (typeof arg === 'string') { + arg = JSON.parse(arg) + } + for (i in arg) { + ret.push(encodeSingle(type, arg[i])) + } + if (size === 'dynamic') { + var length = encodeSingle('uint256', arg.length) + ret.unshift(length) + } + 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 + function decodeSingle (parsedType, data, offset) { + if (typeof parsedType === 'string') { + 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') { + return decodeSingle(parsedType.rawType, data, offset).toString() === new BN(1).toString() + } else if (parsedType.name === 'string') { + var bytes = decodeSingle(parsedType.rawType, data, offset) + return new Buffer(bytes, 'utf8').toString() + } else if (parsedType.isArray) { + // this part handles fixed-length arrays ([2]) and variable length ([]) arrays + // 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() + offset = offset + 32 + } + for (i = 0; i < size; i++) { + var decoded = decodeSingle(parsedType.subArray, data, offset) + ret.push(decoded) + offset += parsedType.subArray.memoryUsage + } + return ret + } else if (parsedType.name === 'bytes') { + offset = decodeSingle('uint256', data, offset).toNumber() + size = decodeSingle('uint256', data, offset).toNumber() + return data.slice(offset + 32, offset + 32 + size) + } else if (parsedType.name.startsWith('bytes')) { + return data.slice(offset, offset + parsedType.size) + } else if (parsedType.name.startsWith('uint')) { + num = new BN(data.slice(offset, offset + 32), 16, 'be') + if (num.bitLength() > parsedType.size) { + throw new Error('Decoded int exceeds width: ' + parsedType.size + ' vs ' + num.bitLength()) + } + return num + } else if (parsedType.name.startsWith('int')) { + num = new BN(data.slice(offset, offset + 32), 16, 'be').fromTwos(256) + 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])) + num = decodeSingle('uint256', data, offset) + if (!num.mod(size).isZero()) { + throw new Error('Decimals not supported yet') + } + return num.div(size) + } else if (parsedType.name.startsWith('fixed')) { + size = new BN(2).pow(new BN(parsedType.size[1])) + num = decodeSingle('int256', data, offset) + if (!num.mod(size).isZero()) { + throw new Error('Decimals not supported yet') + } + return num.div(size) + } + 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) { + var size + var ret + if (isArray(type)) { + size = parseTypeArray(type) + var subArray = type.slice(0, type.lastIndexOf('[')) + subArray = parseType(subArray) + ret = { + isArray: true, + name: type, + size: size, + memoryUsage: size === 'dynamic' ? 32 : subArray.memoryUsage * size, + subArray: subArray + } + return ret + } else { + var rawType + switch (type) { + case 'address': + rawType = 'uint160' + break + case 'bool': + rawType = 'uint8' + break + case 'string': + rawType = 'bytes' + break + } + ret = { + rawType: rawType, + 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) + } + if ((type.startsWith('uint') || type.startsWith('int')) && (ret.size % 8 || ret.size < 8 || ret.size > 256)) { + throw new Error('Invalid int/uint width: ' + ret.size) + } + 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 { + headLength += 32 + } + } else { + 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)) + data.push(cur) + headLength += cur.length + } else { + output.push(cur) + } + } + + return Buffer.concat(output.concat(data)) + } + + ABI.rawDecode = function (types, data) { + var ret = [] + data = new Buffer(data) + var offset = 0 + for (var i = 0; i < types.length; i++) { + var type = elementaryName(types[i]) + var parsed = parseType(type, data, offset) + var decoded = decodeSingle(parsed, data, offset) + offset += parsed.memoryUsage + ret.push(decoded) + } + 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') + } else { + 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) { + return stringify(type, item) + }).join(', ') + } 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') { + ret.push(new Buffer(value, 'utf8')) + } else if (type === 'bool') { + ret.push(new Buffer(value ? '01' : '00', 'hex')) + } else if (type === 'address') { + ret.push(utils.setLengthLeft(value, 20)) + } else if (type.startsWith('bytes')) { + size = parseTypeN(type) + 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 = [] + for (var i = 0; i < sig.length; i++) { + var type = sig[i] + if (type === 's') { + ret.push('bytes') + } else if (type === 'b') { + var tmp = 'bytes' + var j = i + 1 + while ((j < sig.length) && isNumeric(sig[j])) { + tmp += sig[j] - '0' + j++ + } + i = j - 1 + ret.push(tmp) + } else if (type === 'i') { + ret.push('int256') + } else if (type === 'a') { + ret.push('int256[]') + } else { + throw new Error('Unsupported or invalid type: ' + type) + } + } + return ret + } + + ABI.toSerpent = function (types) { + var ret = [] + for (var i = 0; i < types.length; i++) { + var type = types[i] + if (type === 'bytes') { + ret.push('s') + } else if (type.startsWith('bytes')) { + ret.push('b' + parseTypeN(type)) + } else if (type === 'int256') { + ret.push('i') + } else if (type === 'int256[]') { + ret.push('a') + } else { + throw new Error('Unsupported or invalid type: ' + type) + } + } + 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. + * + * @example + * var rawTx = { + * nonce: '00', + * gasPrice: '09184e72a000', + * gasLimit: '2710', + * to: '0000000000000000000000000000000000000000', + * value: '00', + * data: '7f7465737432000000000000000000000000000000000000000000000000000000600057', + * v: '1c', + * r: '5e1d3a76fbf824220eafc8c79ad578ad2b67d01b0c2425eb1f1347e8f50882ab', + * s: '5bd428537f05f9830e93792f90ea6a3e2d1ee84952dd96edbae9f658f831ab13' + * }; + * var tx = new Transaction(rawTx); + * + * @class + * @param {Buffer | Array | Object} data a transaction can be initiailized with either a buffer containing the RLP serialized transaction or an array of buffers relating to each of the tx Properties, listed in order below in the exmple. + * + * Or lastly an Object containing the Properties of the transaction like in the Usage example. + * + * For Object and Arrays each of the elements can either be a Buffer, a hex-prefixed (0x) String , Number, or an object with a toBuffer method such as Bignum + * + * @property {Buffer} raw The raw rlp encoded transaction + * @param {Buffer} data.nonce nonce number + * @param {Buffer} data.gasLimit transaction gas limit + * @param {Buffer} data.gasPrice transaction gas price + * @param {Buffer} data.to to the to address + * @param {Buffer} data.value the amount of ether sent + * @param {Buffer} data.data this will contain the data of the message or the init of a contract + * @param {Buffer} data.v EC signature parameter + * @param {Buffer} data.r EC signature parameter + * @param {Buffer} data.s EC recovery ID + * @param {Number} data.chainId EIP 155 chainId - mainnet: 1, ropsten: 3 + * */ + + var Transaction = function () { + function Transaction(data) { + _classCallCheck(this, Transaction); + + data = data || {}; + // Define Properties + var fields = [{ + name: 'nonce', + length: 32, + allowLess: true, + default: new Buffer([]) + }, { + name: 'gasPrice', + length: 32, + allowLess: true, + default: new Buffer([]) + }, { + name: 'gasLimit', + alias: 'gas', + length: 32, + allowLess: true, + default: new Buffer([]) + }, { + name: 'to', + allowZero: true, + length: 20, + default: new Buffer([]) + }, { + name: 'value', + length: 32, + allowLess: true, + default: new Buffer([]) + }, { + name: 'data', + alias: 'input', + allowZero: true, + default: new Buffer([]) + }, { + name: 'v', + allowZero: true, + default: new Buffer([0x1c]) + }, { + name: 'r', + length: 32, + allowZero: true, + allowLess: true, + default: new Buffer([]) + }, { + name: 's', + length: 32, + allowZero: true, + allowLess: true, + default: new Buffer([]) + }]; + + /** + * Returns the rlp encoding of the transaction + * @method serialize + * @return {Buffer} + * @memberof Transaction + * @name serialize + */ + // attached serialize + ethUtil.defineProperties(this, fields, data); + + /** + * @property {Buffer} from (read only) sender address of this transaction, mathematically derived from other parameters. + * @name from + * @memberof Transaction + */ + Object.defineProperty(this, 'from', { + enumerable: true, + configurable: true, + get: this.getSenderAddress.bind(this) + }); + + // calculate chainId from signature + var sigV = ethUtil.bufferToInt(this.v); + var chainId = Math.floor((sigV - 35) / 2); + if (chainId < 0) chainId = 0; + + // set chainId + this._chainId = chainId || data.chainId || 0; + this._homestead = true; + } + + /** + * If the tx's `to` is to the creation address + * @return {Boolean} + */ + + + Transaction.prototype.toCreationAddress = function toCreationAddress() { + return this.to.toString('hex') === ''; + }; + + /** + * Computes a sha3-256 hash of the serialized tx + * @param {Boolean} [includeSignature=true] whether or not to inculde the signature + * @return {Buffer} + */ + + + Transaction.prototype.hash = function hash(includeSignature) { + if (includeSignature === undefined) includeSignature = true; + + // EIP155 spec: + // when computing the hash of a transaction for purposes of signing or recovering, + // instead of hashing only the first six elements (ie. nonce, gasprice, startgas, to, value, data), + // hash nine elements, with v replaced by CHAIN_ID, r = 0 and s = 0 + + var items = void 0; + if (includeSignature) { + items = this.raw; + } else { + if (this._chainId > 0) { + var raw = this.raw.slice(); + this.v = this._chainId; + this.r = 0; + this.s = 0; + items = this.raw; + this.raw = raw; + } else { + items = this.raw.slice(0, 6); + } + } + + // create hash + return ethUtil.rlphash(items); + }; + + /** + * returns the public key of the sender + * @return {Buffer} + */ + + + Transaction.prototype.getChainId = function getChainId() { + return this._chainId; + }; + + /** + * returns the sender's address + * @return {Buffer} + */ + + + Transaction.prototype.getSenderAddress = function getSenderAddress() { + if (this._from) { + return this._from; + } + var pubkey = this.getSenderPublicKey(); + this._from = ethUtil.publicToAddress(pubkey); + return this._from; + }; + + /** + * returns the public key of the sender + * @return {Buffer} + */ + + + Transaction.prototype.getSenderPublicKey = function getSenderPublicKey() { + if (!this._senderPubKey || !this._senderPubKey.length) { + if (!this.verifySignature()) throw new Error('Invalid Signature'); + } + return this._senderPubKey; + }; + + /** + * Determines if the signature is valid + * @return {Boolean} + */ + + + Transaction.prototype.verifySignature = function verifySignature() { + var msgHash = this.hash(false); + // All transaction signatures whose s-value is greater than secp256k1n/2 are considered invalid. + if (this._homestead && new BN(this.s).cmp(N_DIV_2) === 1) { + return false; + } + + try { + var v = ethUtil.bufferToInt(this.v); + if (this._chainId > 0) { + v -= this._chainId * 2 + 8; + } + this._senderPubKey = ethUtil.ecrecover(msgHash, v, this.r, this.s); + } catch (e) { + return false; + } + + return !!this._senderPubKey; + }; + + /** + * sign a transaction with a given a private key + * @param {Buffer} privateKey + */ + + + Transaction.prototype.sign = function sign(privateKey) { + var msgHash = this.hash(false); + var sig = ethUtil.ecsign(msgHash, privateKey); + if (this._chainId > 0) { + sig.v += this._chainId * 2 + 8; + } + Object.assign(this, sig); + }; + + /** + * The amount of gas paid for the data in this tx + * @return {BN} + */ + + + Transaction.prototype.getDataFee = function getDataFee() { + var data = this.raw[5]; + var cost = new BN(0); + for (var i = 0; i < data.length; i++) { + data[i] === 0 ? cost.iaddn(fees.txDataZeroGas.v) : cost.iaddn(fees.txDataNonZeroGas.v); + } + return cost; + }; + + /** + * the minimum amount of gas the tx must have (DataFee + TxFee + Creation Fee) + * @return {BN} + */ + + + Transaction.prototype.getBaseFee = function getBaseFee() { + var fee = this.getDataFee().iaddn(fees.txGas.v); + if (this._homestead && this.toCreationAddress()) { + fee.iaddn(fees.txCreation.v); + } + return fee; + }; + + /** + * the up front amount that an account must have for this transaction to be valid + * @return {BN} + */ + + + Transaction.prototype.getUpfrontCost = function getUpfrontCost() { + return new BN(this.gasLimit).imul(new BN(this.gasPrice)).iadd(new BN(this.value)); + }; + + /** + * validates the signature and checks to see if it has enough gas + * @param {Boolean} [stringError=false] whether to return a string with a dscription of why the validation failed or return a Bloolean + * @return {Boolean|String} + */ + + + Transaction.prototype.validate = function validate(stringError) { + var errors = []; + if (!this.verifySignature()) { + errors.push('Invalid Signature'); + } + + if (this.getBaseFee().cmp(new BN(this.gasLimit)) > 0) { + errors.push(['gas limit is too low. Need at least ' + this.getBaseFee()]); + } + + if (stringError === undefined || stringError === false) { + return errors.length === 0; + } else { + return errors.join(' '); + } + }; + + return Transaction; + }(); + + module.exports = Transaction; + }).call(this,require("buffer").Buffer) + },{"buffer":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'); + var rlp = require('rlp'); + var BN = require('bn.js'); + var createHash = require('create-hash'); + var Buffer = require('safe-buffer').Buffer; + Object.assign(exports, require('ethjs-util')); + + /** + * the max integer that this VM can handle (a ```BN```) + * @var {BN} MAX_INTEGER + */ + exports.MAX_INTEGER = new BN('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16); + + /** + * 2^256 (a ```BN```) + * @var {BN} TWO_POW256 + */ + exports.TWO_POW256 = new BN('10000000000000000000000000000000000000000000000000000000000000000', 16); + + /** + * Keccak-256 hash of null (a ```String```) + * @var {String} KECCAK256_NULL_S + */ + exports.KECCAK256_NULL_S = 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'; + exports.SHA3_NULL_S = exports.KECCAK256_NULL_S; + + /** + * Keccak-256 hash of null (a ```Buffer```) + * @var {Buffer} KECCAK256_NULL + */ + exports.KECCAK256_NULL = Buffer.from(exports.KECCAK256_NULL_S, 'hex'); + exports.SHA3_NULL = exports.KECCAK256_NULL; + + /** + * Keccak-256 of an RLP of an empty array (a ```String```) + * @var {String} KECCAK256_RLP_ARRAY_S + */ + exports.KECCAK256_RLP_ARRAY_S = '1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347'; + exports.SHA3_RLP_ARRAY_S = exports.KECCAK256_RLP_ARRAY_S; + + /** + * Keccak-256 of an RLP of an empty array (a ```Buffer```) + * @var {Buffer} KECCAK256_RLP_ARRAY + */ + exports.KECCAK256_RLP_ARRAY = Buffer.from(exports.KECCAK256_RLP_ARRAY_S, 'hex'); + exports.SHA3_RLP_ARRAY = exports.KECCAK256_RLP_ARRAY; + + /** + * Keccak-256 hash of the RLP of null (a ```String```) + * @var {String} KECCAK256_RLP_S + */ + exports.KECCAK256_RLP_S = '56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421'; + exports.SHA3_RLP_S = exports.KECCAK256_RLP_S; + + /** + * Keccak-256 hash of the RLP of null (a ```Buffer```) + * @var {Buffer} KECCAK256_RLP + */ + exports.KECCAK256_RLP = Buffer.from(exports.KECCAK256_RLP_S, 'hex'); + exports.SHA3_RLP = exports.KECCAK256_RLP; + + /** + * [`BN`](https://github.com/indutny/bn.js) + * @var {Function} + */ + exports.BN = BN; + + /** + * [`rlp`](https://github.com/ethereumjs/rlp) + * @var {Function} + */ + exports.rlp = rlp; + + /** + * [`secp256k1`](https://github.com/cryptocoinjs/secp256k1-node/) + * @var {Object} + */ + exports.secp256k1 = secp256k1; + + /** + * Returns a buffer filled with 0s + * @method zeros + * @param {Number} bytes the number of bytes the buffer should be + * @return {Buffer} + */ + exports.zeros = function (bytes) { + return Buffer.allocUnsafe(bytes).fill(0); + }; + + /** + * Returns a zero address + * @method zeroAddress + * @return {String} + */ + exports.zeroAddress = function () { + var addressLength = 20; + var zeroAddress = exports.zeros(addressLength); + return exports.bufferToHex(zeroAddress); + }; + + /** + * Left Pads an `Array` or `Buffer` with leading zeros till it has `length` bytes. + * Or it truncates the beginning if it exceeds. + * @method lsetLength + * @param {Buffer|Array} msg the value to pad + * @param {Number} length the number of bytes the output should be + * @param {Boolean} [right=false] whether to start padding form the left or right + * @return {Buffer|Array} + */ + exports.setLengthLeft = exports.setLength = function (msg, length, right) { + var buf = exports.zeros(length); + msg = exports.toBuffer(msg); + if (right) { + if (msg.length < length) { + msg.copy(buf); + return buf; + } + return msg.slice(0, length); + } else { + if (msg.length < length) { + msg.copy(buf, length - msg.length); + return buf; + } + return msg.slice(-length); + } + }; + + /** + * Right Pads an `Array` or `Buffer` with leading zeros till it has `length` bytes. + * Or it truncates the beginning if it exceeds. + * @param {Buffer|Array} msg the value to pad + * @param {Number} length the number of bytes the output should be + * @return {Buffer|Array} + */ + exports.setLengthRight = function (msg, length) { + return exports.setLength(msg, length, true); + }; + + /** + * Trims leading zeros from a `Buffer` or an `Array` + * @param {Buffer|Array|String} a + * @return {Buffer|Array|String} + */ + exports.unpad = exports.stripZeros = function (a) { + a = exports.stripHexPrefix(a); + var first = a[0]; + while (a.length > 0 && first.toString() === '0') { + a = a.slice(1); + first = a[0]; + } + return a; + }; + /** + * Attempts to turn a value into a `Buffer`. As input it supports `Buffer`, `String`, `Number`, null/undefined, `BN` and other objects with a `toArray()` method. + * @param {*} v the value + */ + exports.toBuffer = function (v) { + if (!Buffer.isBuffer(v)) { + if (Array.isArray(v)) { + v = Buffer.from(v); + } else if (typeof v === 'string') { + if (exports.isHexString(v)) { + v = Buffer.from(exports.padToEven(exports.stripHexPrefix(v)), 'hex'); + } else { + v = Buffer.from(v); + } + } else if (typeof v === 'number') { + v = exports.intToBuffer(v); + } else if (v === null || v === undefined) { + v = Buffer.allocUnsafe(0); + } else if (BN.isBN(v)) { + v = v.toArrayLike(Buffer); + } else if (v.toArray) { + // converts a BN to a Buffer + v = Buffer.from(v.toArray()); + } else { + throw new Error('invalid type'); + } + } + return v; + }; + + /** + * Converts a `Buffer` to a `Number` + * @param {Buffer} buf + * @return {Number} + * @throws If the input number exceeds 53 bits. + */ + exports.bufferToInt = function (buf) { + return new BN(exports.toBuffer(buf)).toNumber(); + }; + + /** + * Converts a `Buffer` into a hex `String` + * @param {Buffer} buf + * @return {String} + */ + exports.bufferToHex = function (buf) { + buf = exports.toBuffer(buf); + return '0x' + buf.toString('hex'); + }; + + /** + * Interprets a `Buffer` as a signed integer and returns a `BN`. Assumes 256-bit numbers. + * @param {Buffer} num + * @return {BN} + */ + exports.fromSigned = function (num) { + return new BN(num).fromTwos(256); + }; + + /** + * Converts a `BN` to an unsigned integer and returns it as a `Buffer`. Assumes 256-bit numbers. + * @param {BN} num + * @return {Buffer} + */ + exports.toUnsigned = function (num) { + return Buffer.from(num.toTwos(256).toArray()); + }; + + /** + * Creates Keccak hash of the input + * @param {Buffer|Array|String|Number} a the input data + * @param {Number} [bits=256] the Keccak width + * @return {Buffer} + */ + exports.keccak = function (a, bits) { + a = exports.toBuffer(a); + if (!bits) bits = 256; + + return createKeccakHash('keccak' + bits).update(a).digest(); + }; + + /** + * Creates Keccak-256 hash of the input, alias for keccak(a, 256) + * @param {Buffer|Array|String|Number} a the input data + * @return {Buffer} + */ + exports.keccak256 = function (a) { + return exports.keccak(a); + }; + + /** + * Creates SHA-3 (Keccak) hash of the input [OBSOLETE] + * @param {Buffer|Array|String|Number} a the input data + * @param {Number} [bits=256] the SHA-3 width + * @return {Buffer} + */ + exports.sha3 = exports.keccak; + + /** + * Creates SHA256 hash of the input + * @param {Buffer|Array|String|Number} a the input data + * @return {Buffer} + */ + exports.sha256 = function (a) { + a = exports.toBuffer(a); + return createHash('sha256').update(a).digest(); + }; + + /** + * Creates RIPEMD160 hash of the input + * @param {Buffer|Array|String|Number} a the input data + * @param {Boolean} padded whether it should be padded to 256 bits or not + * @return {Buffer} + */ + exports.ripemd160 = function (a, padded) { + a = exports.toBuffer(a); + var hash = createHash('rmd160').update(a).digest(); + if (padded === true) { + return exports.setLength(hash, 32); + } else { + return hash; + } + }; + + /** + * Creates SHA-3 hash of the RLP encoded version of the input + * @param {Buffer|Array|String|Number} a the input data + * @return {Buffer} + */ + exports.rlphash = function (a) { + return exports.keccak(rlp.encode(a)); + }; + + /** + * Checks if the private key satisfies the rules of the curve secp256k1. + * @param {Buffer} privateKey + * @return {Boolean} + */ + exports.isValidPrivate = function (privateKey) { + return secp256k1.privateKeyVerify(privateKey); + }; + + /** + * Checks if the public key satisfies the rules of the curve secp256k1 + * and the requirements of Ethereum. + * @param {Buffer} publicKey The two points of an uncompressed key, unless sanitize is enabled + * @param {Boolean} [sanitize=false] Accept public keys in other formats + * @return {Boolean} + */ + exports.isValidPublic = function (publicKey, sanitize) { + if (publicKey.length === 64) { + // Convert to SEC1 for secp256k1 + return secp256k1.publicKeyVerify(Buffer.concat([Buffer.from([4]), publicKey])); + } + + if (!sanitize) { + return false; + } + + return secp256k1.publicKeyVerify(publicKey); + }; + + /** + * Returns the ethereum address of a given public key. + * Accepts "Ethereum public keys" and SEC1 encoded keys. + * @param {Buffer} pubKey The two points of an uncompressed key, unless sanitize is enabled + * @param {Boolean} [sanitize=false] Accept public keys in other formats + * @return {Buffer} + */ + exports.pubToAddress = exports.publicToAddress = function (pubKey, sanitize) { + pubKey = exports.toBuffer(pubKey); + if (sanitize && pubKey.length !== 64) { + pubKey = secp256k1.publicKeyConvert(pubKey, false).slice(1); + } + assert(pubKey.length === 64); + // Only take the lower 160bits of the hash + return exports.keccak(pubKey).slice(-20); + }; + + /** + * Returns the ethereum public key of a given private key + * @param {Buffer} privateKey A private key must be 256 bits wide + * @return {Buffer} + */ + var privateToPublic = exports.privateToPublic = function (privateKey) { + privateKey = exports.toBuffer(privateKey); + // skip the type flag and use the X, Y points + return secp256k1.publicKeyCreate(privateKey, false).slice(1); + }; + + /** + * Converts a public key to the Ethereum format. + * @param {Buffer} publicKey + * @return {Buffer} + */ + exports.importPublic = function (publicKey) { + publicKey = exports.toBuffer(publicKey); + if (publicKey.length !== 64) { + publicKey = secp256k1.publicKeyConvert(publicKey, false).slice(1); + } + return publicKey; + }; + + /** + * ECDSA sign + * @param {Buffer} msgHash + * @param {Buffer} privateKey + * @return {Object} + */ + exports.ecsign = function (msgHash, privateKey) { + var sig = secp256k1.sign(msgHash, privateKey); + + var ret = {}; + ret.r = sig.signature.slice(0, 32); + ret.s = sig.signature.slice(32, 64); + ret.v = sig.recovery + 27; + return ret; + }; + + /** + * Returns the keccak-256 hash of `message`, prefixed with the header used by the `eth_sign` RPC call. + * The output of this function can be fed into `ecsign` to produce the same signature as the `eth_sign` + * call for a given `message`, or fed to `ecrecover` along with a signature to recover the public key + * used to produce the signature. + * @param message + * @returns {Buffer} hash + */ + exports.hashPersonalMessage = function (message) { + var prefix = exports.toBuffer('\x19Ethereum Signed Message:\n' + message.length.toString()); + return exports.keccak(Buffer.concat([prefix, message])); + }; + + /** + * ECDSA public key recovery from signature + * @param {Buffer} msgHash + * @param {Number} v + * @param {Buffer} r + * @param {Buffer} s + * @return {Buffer} publicKey + */ + exports.ecrecover = function (msgHash, v, r, s) { + var signature = Buffer.concat([exports.setLength(r, 32), exports.setLength(s, 32)], 64); + var recovery = v - 27; + if (recovery !== 0 && recovery !== 1) { + throw new Error('Invalid signature v value'); + } + var senderPubKey = secp256k1.recover(msgHash, signature, recovery); + return secp256k1.publicKeyConvert(senderPubKey, false).slice(1); + }; + + /** + * Convert signature parameters into the format of `eth_sign` RPC method + * @param {Number} v + * @param {Buffer} r + * @param {Buffer} s + * @return {String} sig + */ + exports.toRpcSig = function (v, r, s) { + // NOTE: with potential introduction of chainId this might need to be updated + if (v !== 27 && v !== 28) { + throw new Error('Invalid recovery id'); + } + + // geth (and the RPC eth_sign method) uses the 65 byte format used by Bitcoin + // FIXME: this might change in the future - https://github.com/ethereum/go-ethereum/issues/2053 + return exports.bufferToHex(Buffer.concat([exports.setLengthLeft(r, 32), exports.setLengthLeft(s, 32), exports.toBuffer(v - 27)])); + }; + + /** + * Convert signature format of the `eth_sign` RPC method to signature parameters + * NOTE: all because of a bug in geth: https://github.com/ethereum/go-ethereum/issues/2053 + * @param {String} sig + * @return {Object} + */ + exports.fromRpcSig = function (sig) { + sig = exports.toBuffer(sig); + + // NOTE: with potential introduction of chainId this might need to be updated + if (sig.length !== 65) { + throw new Error('Invalid signature length'); + } + + var v = sig[64]; + // support both versions of `eth_sign` responses + if (v < 27) { + v += 27; + } + + return { + v: v, + r: sig.slice(0, 32), + s: sig.slice(32, 64) + }; + }; + + /** + * Returns the ethereum address of a given private key + * @param {Buffer} privateKey A private key must be 256 bits wide + * @return {Buffer} + */ + exports.privateToAddress = function (privateKey) { + return exports.publicToAddress(privateToPublic(privateKey)); + }; + + /** + * Checks if the address is a valid. Accepts checksummed addresses too + * @param {String} address + * @return {Boolean} + */ + exports.isValidAddress = function (address) { + return (/^0x[0-9a-fA-F]{40}$/.test(address) + ); + }; + + /** + * Checks if a given address is a zero address + * @method isZeroAddress + * @param {String} address + * @return {Boolean} + */ + exports.isZeroAddress = function (address) { + var zeroAddress = exports.zeroAddress(); + return zeroAddress === exports.addHexPrefix(address); + }; + + /** + * Returns a checksummed address + * @param {String} address + * @return {String} + */ + exports.toChecksumAddress = function (address) { + address = exports.stripHexPrefix(address).toLowerCase(); + var hash = exports.keccak(address).toString('hex'); + var ret = '0x'; + + for (var i = 0; i < address.length; i++) { + if (parseInt(hash[i], 16) >= 8) { + ret += address[i].toUpperCase(); + } else { + ret += address[i]; + } + } + + return ret; + }; + + /** + * Checks if the address is a valid checksummed address + * @param {Buffer} address + * @return {Boolean} + */ + exports.isValidChecksumAddress = function (address) { + return exports.isValidAddress(address) && exports.toChecksumAddress(address) === address; + }; + + /** + * Generates an address of a newly created contract + * @param {Buffer} from the address which is creating this new address + * @param {Buffer} nonce the nonce of the from account + * @return {Buffer} + */ + exports.generateAddress = function (from, nonce) { + from = exports.toBuffer(from); + nonce = new BN(nonce); + + if (nonce.isZero()) { + // in RLP we want to encode null in the case of zero nonce + // read the RLP documentation for an answer if you dare + nonce = null; + } else { + nonce = Buffer.from(nonce.toArray()); + } + + // Only take the lower 160bits of the hash + return exports.rlphash([from, nonce]).slice(-20); + }; + + /** + * Returns true if the supplied address belongs to a precompiled account (Byzantium) + * @param {Buffer|String} address + * @return {Boolean} + */ + exports.isPrecompiled = function (address) { + var a = exports.unpad(address); + return a.length === 1 && a[0] >= 1 && a[0] <= 8; + }; + + /** + * Adds "0x" to a given `String` if it does not already start with "0x" + * @param {String} str + * @return {String} + */ + exports.addHexPrefix = function (str) { + if (typeof str !== 'string') { + return str; + } + + return exports.isHexPrefixed(str) ? str : '0x' + str; + }; + + /** + * Validate ECDSA signature + * @method isValidSignature + * @param {Buffer} v + * @param {Buffer} r + * @param {Buffer} s + * @param {Boolean} [homestead=true] + * @return {Boolean} + */ + + exports.isValidSignature = function (v, r, s, homestead) { + var SECP256K1_N_DIV_2 = new BN('7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0', 16); + var SECP256K1_N = new BN('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 16); + + if (r.length !== 32 || s.length !== 32) { + return false; + } + + if (v !== 27 && v !== 28) { + return false; + } + + r = new BN(r); + s = new BN(s); + + if (r.isZero() || r.gt(SECP256K1_N) || s.isZero() || s.gt(SECP256K1_N)) { + return false; + } + + if (homestead === false && new BN(s).cmp(SECP256K1_N_DIV_2) === 1) { + return false; + } + + return true; + }; + + /** + * Converts a `Buffer` or `Array` to JSON + * @param {Buffer|Array} ba + * @return {Array|String|null} + */ + exports.baToJSON = function (ba) { + if (Buffer.isBuffer(ba)) { + return '0x' + ba.toString('hex'); + } else if (ba instanceof Array) { + var array = []; + for (var i = 0; i < ba.length; i++) { + array.push(exports.baToJSON(ba[i])); + } + return array; + } + }; + + /** + * Defines properties on a `Object`. It make the assumption that underlying data is binary. + * @param {Object} self the `Object` to define properties on + * @param {Array} fields an array fields to define. Fields can contain: + * * `name` - the name of the properties + * * `length` - the number of bytes the field can have + * * `allowLess` - if the field can be less than the length + * * `allowEmpty` + * @param {*} data data to be validated against the definitions + */ + exports.defineProperties = function (self, fields, data) { + self.raw = []; + self._fields = []; + + // attach the `toJSON` + self.toJSON = function (label) { + if (label) { + var obj = {}; + self._fields.forEach(function (field) { + obj[field] = '0x' + self[field].toString('hex'); + }); + return obj; + } + return exports.baToJSON(this.raw); + }; + + self.serialize = function serialize() { + return rlp.encode(self.raw); + }; + + fields.forEach(function (field, i) { + self._fields.push(field.name); + function getter() { + return self.raw[i]; + } + function setter(v) { + v = exports.toBuffer(v); + + if (v.toString('hex') === '00' && !field.allowZero) { + v = Buffer.allocUnsafe(0); + } + + if (field.allowLess && field.length) { + v = exports.stripZeros(v); + assert(field.length >= v.length, 'The field ' + field.name + ' must not have more ' + field.length + ' bytes'); + } else if (!(field.allowZero && v.length === 0) && field.length) { + assert(field.length === v.length, 'The field ' + field.name + ' must have byte length of ' + field.length); + } + + self.raw[i] = v; + } + + Object.defineProperty(self, field.name, { + enumerable: true, + configurable: true, + get: getter, + set: setter + }); + + if (field.default) { + self[field.name] = field.default; + } + + // attach alias + if (field.alias) { + Object.defineProperty(self, field.alias, { + enumerable: false, + configurable: true, + set: setter, + get: getter + }); + } + }); + + // if the constuctor is passed data + if (data) { + if (typeof data === 'string') { + data = Buffer.from(exports.stripHexPrefix(data), 'hex'); + } + + if (Buffer.isBuffer(data)) { + data = rlp.decode(data); + } + + if (Array.isArray(data)) { + if (data.length > self._fields.length) { + throw new Error('wrong number of fields in data'); + } + + // make sure all the items are buffers + data.forEach(function (d, i) { + self[self._fields[i]] = exports.toBuffer(d); + }); + } else if ((typeof data === 'undefined' ? 'undefined' : _typeof(data)) === 'object') { + var keys = Object.keys(data); + fields.forEach(function (field) { + if (keys.indexOf(field.name) !== -1) self[field.name] = data[field.name]; + if (keys.indexOf(field.alias) !== -1) self[field.alias] = data[field.alias]; + }); + } else { + throw new Error('invalid data'); + } + } + }; + },{"assert":19,"bn.js":53,"create-hash":91,"ethjs-util":155,"keccak":195,"rlp":289,"safe-buffer":290,"secp256k1":295}],142:[function(require,module,exports){ + arguments[4][128][0].apply(exports,arguments) + },{"_process":257,"dup":128}],143:[function(require,module,exports){ + 'use strict'; + var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + // See: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI + var address_1 = require("./address"); + var bignumber_1 = require("./bignumber"); + var bytes_1 = require("./bytes"); + var utf8_1 = require("./utf8"); + var properties_1 = require("./properties"); + var errors = __importStar(require("./errors")); + var paramTypeBytes = new RegExp(/^bytes([0-9]*)$/); + var paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/); + var paramTypeArray = new RegExp(/^(.*)\[([0-9]*)\]$/); + exports.defaultCoerceFunc = function (type, value) { + var match = type.match(paramTypeNumber); + if (match && parseInt(match[2]) <= 48) { + return value.toNumber(); + } + return value; + }; + /////////////////////////////////// + // Parsing for Solidity Signatures + var regexParen = new RegExp("^([^)(]*)\\((.*)\\)([^)(]*)$"); + var regexIdentifier = new RegExp("^[A-Za-z_][A-Za-z0-9_]*$"); + function verifyType(type) { + // These need to be transformed to their full description + if (type.match(/^uint($|[^1-9])/)) { + type = 'uint256' + type.substring(4); + } + else if (type.match(/^int($|[^1-9])/)) { + type = 'int256' + type.substring(3); + } + return type; + } + function parseParam(param, allowIndexed) { + function throwError(i) { + throw new Error('unexpected character "' + param[i] + '" at position ' + i + ' in "' + param + '"'); + } + var parent = { type: '', name: '', state: { allowType: true } }; + var node = parent; + for (var i = 0; i < param.length; i++) { + var c = param[i]; + switch (c) { + case '(': + if (!node.state.allowParams) { + throwError(i); + } + node.state.allowType = false; + node.type = verifyType(node.type); + node.components = [{ type: '', name: '', parent: node, state: { allowType: true } }]; + node = node.components[0]; + break; + case ')': + delete node.state; + if (allowIndexed && node.name === 'indexed') { + node.indexed = true; + node.name = ''; + } + node.type = verifyType(node.type); + var child = node; + node = node.parent; + if (!node) { + throwError(i); + } + delete child.parent; + node.state.allowParams = false; + node.state.allowName = true; + node.state.allowArray = true; + break; + case ',': + delete node.state; + if (allowIndexed && node.name === 'indexed') { + node.indexed = true; + node.name = ''; + } + node.type = verifyType(node.type); + var sibling = { type: '', name: '', parent: node.parent, state: { allowType: true } }; + node.parent.components.push(sibling); + delete node.parent; + node = sibling; + break; + // Hit a space... + case ' ': + // If reading type, the type is done and may read a param or name + if (node.state.allowType) { + if (node.type !== '') { + node.type = verifyType(node.type); + delete node.state.allowType; + node.state.allowName = true; + node.state.allowParams = true; + } + } + // If reading name, the name is done + if (node.state.allowName) { + if (node.name !== '') { + if (allowIndexed && node.name === 'indexed') { + node.indexed = true; + node.name = ''; + } + else { + node.state.allowName = false; + } + } + } + break; + case '[': + if (!node.state.allowArray) { + throwError(i); + } + node.type += c; + node.state.allowArray = false; + node.state.allowName = false; + node.state.readArray = true; + break; + case ']': + if (!node.state.readArray) { + throwError(i); + } + node.type += c; + node.state.readArray = false; + node.state.allowArray = true; + node.state.allowName = true; + break; + default: + if (node.state.allowType) { + node.type += c; + node.state.allowParams = true; + node.state.allowArray = true; + } + else if (node.state.allowName) { + node.name += c; + delete node.state.allowArray; + } + else if (node.state.readArray) { + node.type += c; + } + else { + throwError(i); + } + } + } + if (node.parent) { + throw new Error("unexpected eof"); + } + delete parent.state; + if (allowIndexed && node.name === 'indexed') { + node.indexed = true; + node.name = ''; + } + parent.type = verifyType(parent.type); + return parent; + } + // @TODO: Better return type + function parseSignatureEvent(fragment) { + var abi = { + anonymous: false, + inputs: [], + name: '', + type: 'event' + }; + var match = fragment.match(regexParen); + if (!match) { + throw new Error('invalid event: ' + fragment); + } + abi.name = match[1].trim(); + splitNesting(match[2]).forEach(function (param) { + param = parseParam(param, true); + param.indexed = !!param.indexed; + abi.inputs.push(param); + }); + match[3].split(' ').forEach(function (modifier) { + switch (modifier) { + case 'anonymous': + abi.anonymous = true; + break; + case '': + break; + default: + console.log('unknown modifier: ' + modifier); + } + }); + if (abi.name && !abi.name.match(regexIdentifier)) { + throw new Error('invalid identifier: "' + abi.name + '"'); + } + return abi; + } + function parseSignatureFunction(fragment) { + var abi = { + constant: false, + inputs: [], + name: '', + outputs: [], + payable: false, + stateMutability: null, + type: 'function' + }; + var comps = fragment.split(' returns '); + var left = comps[0].match(regexParen); + if (!left) { + throw new Error('invalid signature'); + } + abi.name = left[1].trim(); + if (!abi.name.match(regexIdentifier)) { + throw new Error('invalid identifier: "' + left[1] + '"'); + } + splitNesting(left[2]).forEach(function (param) { + abi.inputs.push(parseParam(param)); + }); + left[3].split(' ').forEach(function (modifier) { + switch (modifier) { + case 'constant': + abi.constant = true; + break; + case 'payable': + abi.payable = true; + break; + case 'pure': + abi.constant = true; + abi.stateMutability = 'pure'; + break; + case 'view': + abi.constant = true; + abi.stateMutability = 'view'; + break; + case '': + break; + default: + console.log('unknown modifier: ' + modifier); + } + }); + // We have outputs + if (comps.length > 1) { + var right = comps[1].match(regexParen); + if (right[1].trim() != '' || right[3].trim() != '') { + throw new Error('unexpected tokens'); + } + splitNesting(right[2]).forEach(function (param) { + abi.outputs.push(parseParam(param)); + }); + } + return abi; + } + function parseParamType(type) { + return parseParam(type, true); + } + exports.parseParamType = parseParamType; + // @TODO: Allow a second boolean to expose names + function formatParamType(paramType) { + return getParamCoder(exports.defaultCoerceFunc, paramType).type; + } + exports.formatParamType = formatParamType; + // @TODO: Allow a second boolean to expose names and modifiers + function formatSignature(fragment) { + return fragment.name + '(' + fragment.inputs.map(function (i) { return formatParamType(i); }).join(',') + ')'; + } + exports.formatSignature = formatSignature; + function parseSignature(fragment) { + if (typeof (fragment) === 'string') { + // Make sure the "returns" is surrounded by a space and all whitespace is exactly one space + fragment = fragment.replace(/\(/g, ' (').replace(/\)/g, ') ').replace(/\s+/g, ' '); + fragment = fragment.trim(); + if (fragment.substring(0, 6) === 'event ') { + return parseSignatureEvent(fragment.substring(6).trim()); + } + else { + if (fragment.substring(0, 9) === 'function ') { + fragment = fragment.substring(9); + } + return parseSignatureFunction(fragment.trim()); + } + } + throw new Error('unknown signature'); + } + exports.parseSignature = parseSignature; + var Coder = /** @class */ (function () { + function Coder(coerceFunc, name, type, localName, dynamic) { + this.coerceFunc = coerceFunc; + this.name = name; + this.type = type; + this.localName = localName; + this.dynamic = dynamic; + } + return Coder; + }()); + // Clones the functionality of an existing Coder, but without a localName + var CoderAnonymous = /** @class */ (function (_super) { + __extends(CoderAnonymous, _super); + function CoderAnonymous(coder) { + var _this = _super.call(this, coder.coerceFunc, coder.name, coder.type, undefined, coder.dynamic) || this; + properties_1.defineReadOnly(_this, 'coder', coder); + return _this; + } + CoderAnonymous.prototype.encode = function (value) { return this.coder.encode(value); }; + CoderAnonymous.prototype.decode = function (data, offset) { return this.coder.decode(data, offset); }; + return CoderAnonymous; + }(Coder)); + var CoderNull = /** @class */ (function (_super) { + __extends(CoderNull, _super); + function CoderNull(coerceFunc, localName) { + return _super.call(this, coerceFunc, 'null', '', localName, false) || this; + } + CoderNull.prototype.encode = function (value) { + return bytes_1.arrayify([]); + }; + CoderNull.prototype.decode = function (data, offset) { + if (offset > data.length) { + throw new Error('invalid null'); + } + return { + consumed: 0, + value: this.coerceFunc('null', undefined) + }; + }; + return CoderNull; + }(Coder)); + var CoderNumber = /** @class */ (function (_super) { + __extends(CoderNumber, _super); + function CoderNumber(coerceFunc, size, signed, localName) { + var _this = this; + var name = ((signed ? 'int' : 'uint') + (size * 8)); + _this = _super.call(this, coerceFunc, name, name, localName, false) || this; + _this.size = size; + _this.signed = signed; + return _this; + } + CoderNumber.prototype.encode = function (value) { + try { + var v = bignumber_1.bigNumberify(value); + v = v.toTwos(this.size * 8).maskn(this.size * 8); + //value = value.toTwos(size * 8).maskn(size * 8); + if (this.signed) { + v = v.fromTwos(this.size * 8).toTwos(256); + } + return bytes_1.padZeros(bytes_1.arrayify(v), 32); + } + catch (error) { + errors.throwError('invalid number value', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: this.name, + value: value + }); + } + return null; + }; + CoderNumber.prototype.decode = function (data, offset) { + if (data.length < offset + 32) { + errors.throwError('insufficient data for ' + this.name + ' type', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: this.name, + value: bytes_1.hexlify(data.slice(offset, offset + 32)) + }); + } + var junkLength = 32 - this.size; + var value = bignumber_1.bigNumberify(data.slice(offset + junkLength, offset + 32)); + if (this.signed) { + value = value.fromTwos(this.size * 8); + } + else { + value = value.maskn(this.size * 8); + } + return { + consumed: 32, + value: this.coerceFunc(this.name, value), + }; + }; + return CoderNumber; + }(Coder)); + var uint256Coder = new CoderNumber(function (type, value) { return value; }, 32, false, 'none'); + var CoderBoolean = /** @class */ (function (_super) { + __extends(CoderBoolean, _super); + function CoderBoolean(coerceFunc, localName) { + return _super.call(this, coerceFunc, 'bool', 'bool', localName, false) || this; + } + CoderBoolean.prototype.encode = function (value) { + return uint256Coder.encode(!!value ? 1 : 0); + }; + CoderBoolean.prototype.decode = function (data, offset) { + try { + var result = uint256Coder.decode(data, offset); + } + catch (error) { + if (error.reason === 'insufficient data for uint256 type') { + errors.throwError('insufficient data for boolean type', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: 'boolean', + value: error.value + }); + } + throw error; + } + return { + consumed: result.consumed, + value: this.coerceFunc('bool', !result.value.isZero()) + }; + }; + return CoderBoolean; + }(Coder)); + var CoderFixedBytes = /** @class */ (function (_super) { + __extends(CoderFixedBytes, _super); + function CoderFixedBytes(coerceFunc, length, localName) { + var _this = this; + var name = ('bytes' + length); + _this = _super.call(this, coerceFunc, name, name, localName, false) || this; + _this.length = length; + return _this; + } + CoderFixedBytes.prototype.encode = function (value) { + var result = new Uint8Array(32); + try { + var data = bytes_1.arrayify(value); + if (data.length > 32) { + throw new Error(); + } + result.set(data); + } + catch (error) { + errors.throwError('invalid ' + this.name + ' value', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: this.name, + value: (error.value || value) + }); + } + return result; + }; + CoderFixedBytes.prototype.decode = function (data, offset) { + if (data.length < offset + 32) { + errors.throwError('insufficient data for ' + name + ' type', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: this.name, + value: bytes_1.hexlify(data.slice(offset, offset + 32)) + }); + } + return { + consumed: 32, + value: this.coerceFunc(this.name, bytes_1.hexlify(data.slice(offset, offset + this.length))) + }; + }; + return CoderFixedBytes; + }(Coder)); + var CoderAddress = /** @class */ (function (_super) { + __extends(CoderAddress, _super); + function CoderAddress(coerceFunc, localName) { + return _super.call(this, coerceFunc, 'address', 'address', localName, false) || this; + } + CoderAddress.prototype.encode = function (value) { + var result = new Uint8Array(32); + try { + result.set(bytes_1.arrayify(address_1.getAddress(value)), 12); + } + catch (error) { + errors.throwError('invalid address', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: 'address', + value: value + }); + } + return result; + }; + CoderAddress.prototype.decode = function (data, offset) { + if (data.length < offset + 32) { + errors.throwError('insufficuent data for address type', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: 'address', + value: bytes_1.hexlify(data.slice(offset, offset + 32)) + }); + } + return { + consumed: 32, + value: this.coerceFunc('address', address_1.getAddress(bytes_1.hexlify(data.slice(offset + 12, offset + 32)))) + }; + }; + return CoderAddress; + }(Coder)); + function _encodeDynamicBytes(value) { + var dataLength = 32 * Math.ceil(value.length / 32); + var padding = new Uint8Array(dataLength - value.length); + return bytes_1.concat([ + uint256Coder.encode(value.length), + value, + padding + ]); + } + function _decodeDynamicBytes(data, offset, localName) { + if (data.length < offset + 32) { + errors.throwError('insufficient data for dynamicBytes length', errors.INVALID_ARGUMENT, { + arg: localName, + coderType: 'dynamicBytes', + value: bytes_1.hexlify(data.slice(offset, offset + 32)) + }); + } + var length = uint256Coder.decode(data, offset).value; + try { + length = length.toNumber(); + } + catch (error) { + errors.throwError('dynamic bytes count too large', errors.INVALID_ARGUMENT, { + arg: localName, + coderType: 'dynamicBytes', + value: length.toString() + }); + } + if (data.length < offset + 32 + length) { + errors.throwError('insufficient data for dynamicBytes type', errors.INVALID_ARGUMENT, { + arg: localName, + coderType: 'dynamicBytes', + value: bytes_1.hexlify(data.slice(offset, offset + 32 + length)) + }); + } + return { + consumed: 32 + 32 * Math.ceil(length / 32), + value: data.slice(offset + 32, offset + 32 + length), + }; + } + var CoderDynamicBytes = /** @class */ (function (_super) { + __extends(CoderDynamicBytes, _super); + function CoderDynamicBytes(coerceFunc, localName) { + return _super.call(this, coerceFunc, 'bytes', 'bytes', localName, true) || this; + } + CoderDynamicBytes.prototype.encode = function (value) { + try { + return _encodeDynamicBytes(bytes_1.arrayify(value)); + } + catch (error) { + errors.throwError('invalid bytes value', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: 'bytes', + value: error.value + }); + } + return null; + }; + CoderDynamicBytes.prototype.decode = function (data, offset) { + var result = _decodeDynamicBytes(data, offset, this.localName); + result.value = this.coerceFunc('bytes', bytes_1.hexlify(result.value)); + return result; + }; + return CoderDynamicBytes; + }(Coder)); + var CoderString = /** @class */ (function (_super) { + __extends(CoderString, _super); + function CoderString(coerceFunc, localName) { + return _super.call(this, coerceFunc, 'string', 'string', localName, true) || this; + } + CoderString.prototype.encode = function (value) { + if (typeof (value) !== 'string') { + errors.throwError('invalid string value', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: 'string', + value: value + }); + } + return _encodeDynamicBytes(utf8_1.toUtf8Bytes(value)); + }; + CoderString.prototype.decode = function (data, offset) { + var result = _decodeDynamicBytes(data, offset, this.localName); + result.value = this.coerceFunc('string', utf8_1.toUtf8String(result.value)); + return result; + }; + return CoderString; + }(Coder)); + function alignSize(size) { + return 32 * Math.ceil(size / 32); + } + function pack(coders, values) { + if (Array.isArray(values)) { + // do nothing + } + else if (values && typeof (values) === 'object') { + var arrayValues = []; + coders.forEach(function (coder) { + arrayValues.push(values[coder.localName]); + }); + values = arrayValues; + } + else { + errors.throwError('invalid tuple value', errors.INVALID_ARGUMENT, { + coderType: 'tuple', + value: values + }); + } + if (coders.length !== values.length) { + errors.throwError('types/value length mismatch', errors.INVALID_ARGUMENT, { + coderType: 'tuple', + value: values + }); + } + var parts = []; + coders.forEach(function (coder, index) { + parts.push({ dynamic: coder.dynamic, value: coder.encode(values[index]) }); + }); + var staticSize = 0, dynamicSize = 0; + parts.forEach(function (part) { + if (part.dynamic) { + staticSize += 32; + dynamicSize += alignSize(part.value.length); + } + else { + staticSize += alignSize(part.value.length); + } + }); + var offset = 0, dynamicOffset = staticSize; + var data = new Uint8Array(staticSize + dynamicSize); + parts.forEach(function (part) { + if (part.dynamic) { + //uint256Coder.encode(dynamicOffset).copy(data, offset); + data.set(uint256Coder.encode(dynamicOffset), offset); + offset += 32; + //part.value.copy(data, dynamicOffset); @TODO + data.set(part.value, dynamicOffset); + dynamicOffset += alignSize(part.value.length); + } + else { + //part.value.copy(data, offset); @TODO + data.set(part.value, offset); + offset += alignSize(part.value.length); + } + }); + return data; + } + function unpack(coders, data, offset) { + var baseOffset = offset; + var consumed = 0; + var value = []; + coders.forEach(function (coder) { + if (coder.dynamic) { + var dynamicOffset = uint256Coder.decode(data, offset); + var result = coder.decode(data, baseOffset + dynamicOffset.value.toNumber()); + // The dynamic part is leap-frogged somewhere else; doesn't count towards size + result.consumed = dynamicOffset.consumed; + } + else { + var result = coder.decode(data, offset); + } + if (result.value != undefined) { + value.push(result.value); + } + offset += result.consumed; + consumed += result.consumed; + }); + coders.forEach(function (coder, index) { + var name = coder.localName; + if (!name) { + return; + } + if (name === 'length') { + name = '_length'; + } + if (value[name] != null) { + return; + } + value[name] = value[index]; + }); + return { + value: value, + consumed: consumed + }; + } + var CoderArray = /** @class */ (function (_super) { + __extends(CoderArray, _super); + function CoderArray(coerceFunc, coder, length, localName) { + var _this = this; + var type = (coder.type + '[' + (length >= 0 ? length : '') + ']'); + var dynamic = (length === -1 || coder.dynamic); + _this = _super.call(this, coerceFunc, 'array', type, localName, dynamic) || this; + _this.coder = coder; + _this.length = length; + return _this; + } + CoderArray.prototype.encode = function (value) { + if (!Array.isArray(value)) { + errors.throwError('expected array value', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: 'array', + value: value + }); + } + var count = this.length; + var result = new Uint8Array(0); + if (count === -1) { + count = value.length; + result = uint256Coder.encode(count); + } + errors.checkArgumentCount(count, value.length, 'in coder array' + (this.localName ? (" " + this.localName) : "")); + var coders = []; + for (var i = 0; i < value.length; i++) { + coders.push(this.coder); + } + return bytes_1.concat([result, pack(coders, value)]); + }; + CoderArray.prototype.decode = function (data, offset) { + // @TODO: + //if (data.length < offset + length * 32) { throw new Error('invalid array'); } + var consumed = 0; + var count = this.length; + if (count === -1) { + try { + var decodedLength = uint256Coder.decode(data, offset); + } + catch (error) { + errors.throwError('insufficient data for dynamic array length', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: 'array', + value: error.value + }); + } + try { + count = decodedLength.value.toNumber(); + } + catch (error) { + errors.throwError('array count too large', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: 'array', + value: decodedLength.value.toString() + }); + } + consumed += decodedLength.consumed; + offset += decodedLength.consumed; + } + var coders = []; + for (var i = 0; i < count; i++) { + coders.push(new CoderAnonymous(this.coder)); + } + var result = unpack(coders, data, offset); + result.consumed += consumed; + result.value = this.coerceFunc(this.type, result.value); + return result; + }; + return CoderArray; + }(Coder)); + var CoderTuple = /** @class */ (function (_super) { + __extends(CoderTuple, _super); + function CoderTuple(coerceFunc, coders, localName) { + var _this = this; + var dynamic = false; + var types = []; + coders.forEach(function (coder) { + if (coder.dynamic) { + dynamic = true; + } + types.push(coder.type); + }); + var type = ('tuple(' + types.join(',') + ')'); + _this = _super.call(this, coerceFunc, 'tuple', type, localName, dynamic) || this; + _this.coders = coders; + return _this; + } + CoderTuple.prototype.encode = function (value) { + return pack(this.coders, value); + }; + CoderTuple.prototype.decode = function (data, offset) { + var result = unpack(this.coders, data, offset); + result.value = this.coerceFunc(this.type, result.value); + return result; + }; + return CoderTuple; + }(Coder)); + /* + function getTypes(coders) { + var type = coderTuple(coders).type; + return type.substring(6, type.length - 1); + } + */ + function splitNesting(value) { + var result = []; + var accum = ''; + var depth = 0; + for (var offset = 0; offset < value.length; offset++) { + var c = value[offset]; + if (c === ',' && depth === 0) { + result.push(accum); + accum = ''; + } + else { + accum += c; + if (c === '(') { + depth++; + } + else if (c === ')') { + depth--; + if (depth === -1) { + throw new Error('unbalanced parenthsis'); + } + } + } + } + result.push(accum); + return result; + } + // @TODO: Is there a way to return "class"? + var paramTypeSimple = { + address: CoderAddress, + bool: CoderBoolean, + string: CoderString, + bytes: CoderDynamicBytes, + }; + function getTupleParamCoder(coerceFunc, components, localName) { + if (!components) { + components = []; + } + var coders = []; + components.forEach(function (component) { + coders.push(getParamCoder(coerceFunc, component)); + }); + return new CoderTuple(coerceFunc, coders, localName); + } + function getParamCoder(coerceFunc, param) { + var coder = paramTypeSimple[param.type]; + if (coder) { + return new coder(coerceFunc, param.name); + } + var match = param.type.match(paramTypeNumber); + if (match) { + var size = parseInt(match[2] || "256"); + if (size === 0 || size > 256 || (size % 8) !== 0) { + errors.throwError('invalid ' + match[1] + ' bit length', errors.INVALID_ARGUMENT, { + arg: 'param', + value: param + }); + } + return new CoderNumber(coerceFunc, size / 8, (match[1] === 'int'), param.name); + } + var match = param.type.match(paramTypeBytes); + if (match) { + var size = parseInt(match[1]); + if (size === 0 || size > 32) { + errors.throwError('invalid bytes length', errors.INVALID_ARGUMENT, { + arg: 'param', + value: param + }); + } + return new CoderFixedBytes(coerceFunc, size, param.name); + } + var match = param.type.match(paramTypeArray); + if (match) { + var size = parseInt(match[2] || "-1"); + param = properties_1.jsonCopy(param); + param.type = match[1]; + return new CoderArray(coerceFunc, getParamCoder(coerceFunc, param), size, param.name); + } + if (param.type.substring(0, 5) === 'tuple') { + return getTupleParamCoder(coerceFunc, param.components, param.name); + } + if (param.type === '') { + return new CoderNull(coerceFunc, param.name); + } + errors.throwError('invalid type', errors.INVALID_ARGUMENT, { + arg: 'type', + value: param.type + }); + return null; + } + var AbiCoder = /** @class */ (function () { + function AbiCoder(coerceFunc) { + errors.checkNew(this, AbiCoder); + if (!coerceFunc) { + coerceFunc = exports.defaultCoerceFunc; + } + properties_1.defineReadOnly(this, 'coerceFunc', coerceFunc); + } + AbiCoder.prototype.encode = function (types, values) { + if (types.length !== values.length) { + errors.throwError('types/values length mismatch', errors.INVALID_ARGUMENT, { + count: { types: types.length, values: values.length }, + value: { types: types, values: values } + }); + } + var coders = []; + types.forEach(function (type) { + // Convert types to type objects + // - "uint foo" => { type: "uint", name: "foo" } + // - "tuple(uint, uint)" => { type: "tuple", components: [ { type: "uint" }, { type: "uint" }, ] } + var typeObject = null; + if (typeof (type) === 'string') { + typeObject = parseParam(type); + } + else { + typeObject = type; + } + coders.push(getParamCoder(this.coerceFunc, typeObject)); + }, this); + return bytes_1.hexlify(new CoderTuple(this.coerceFunc, coders, '_').encode(values)); + }; + AbiCoder.prototype.decode = function (types, data) { + var coders = []; + types.forEach(function (type) { + // See encode for details + var typeObject = null; + if (typeof (type) === 'string') { + typeObject = parseParam(type); + } + else { + typeObject = properties_1.jsonCopy(type); + } + coders.push(getParamCoder(this.coerceFunc, typeObject)); + }, this); + return new CoderTuple(this.coerceFunc, coders, '_').decode(bytes_1.arrayify(data), 0).value; + }; + return AbiCoder; + }()); + exports.AbiCoder = AbiCoder; + exports.defaultAbiCoder = new AbiCoder(); + + },{"./address":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) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + // We use this for base 36 maths + var bn_js_1 = __importDefault(require("bn.js")); + var bytes_1 = require("./bytes"); + var keccak256_1 = require("./keccak256"); + var rlp_1 = require("./rlp"); + var errors = require("./errors"); + function getChecksumAddress(address) { + if (typeof (address) !== 'string' || !address.match(/^0x[0-9A-Fa-f]{40}$/)) { + errors.throwError('invalid address', errors.INVALID_ARGUMENT, { arg: 'address', value: address }); + } + address = address.toLowerCase(); + var chars = address.substring(2).split(''); + var hashed = new Uint8Array(40); + for (var i_1 = 0; i_1 < 40; i_1++) { + hashed[i_1] = chars[i_1].charCodeAt(0); + } + hashed = bytes_1.arrayify(keccak256_1.keccak256(hashed)); + for (var i = 0; i < 40; i += 2) { + if ((hashed[i >> 1] >> 4) >= 8) { + chars[i] = chars[i].toUpperCase(); + } + if ((hashed[i >> 1] & 0x0f) >= 8) { + chars[i + 1] = chars[i + 1].toUpperCase(); + } + } + return '0x' + chars.join(''); + } + // Shims for environments that are missing some required constants and functions + var MAX_SAFE_INTEGER = 0x1fffffffffffff; + function log10(x) { + if (Math.log10) { + return Math.log10(x); + } + return Math.log(x) / Math.LN10; + } + // See: https://en.wikipedia.org/wiki/International_Bank_Account_Number + // Create lookup table + var ibanLookup = {}; + for (var i = 0; i < 10; i++) { + ibanLookup[String(i)] = String(i); + } + for (var i = 0; i < 26; i++) { + ibanLookup[String.fromCharCode(65 + i)] = String(10 + i); + } + // How many decimal digits can we process? (for 64-bit float, this is 15) + var safeDigits = Math.floor(log10(MAX_SAFE_INTEGER)); + function ibanChecksum(address) { + address = address.toUpperCase(); + address = address.substring(4) + address.substring(0, 2) + '00'; + var expanded = ''; + address.split('').forEach(function (c) { + expanded += ibanLookup[c]; + }); + // Javascript can handle integers safely up to 15 (decimal) digits + while (expanded.length >= safeDigits) { + var block = expanded.substring(0, safeDigits); + expanded = parseInt(block, 10) % 97 + expanded.substring(block.length); + } + var checksum = String(98 - (parseInt(expanded, 10) % 97)); + while (checksum.length < 2) { + checksum = '0' + checksum; + } + return checksum; + } + ; + function getAddress(address) { + var result = null; + if (typeof (address) !== 'string') { + errors.throwError('invalid address', errors.INVALID_ARGUMENT, { arg: 'address', value: address }); + } + if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) { + // Missing the 0x prefix + if (address.substring(0, 2) !== '0x') { + address = '0x' + address; + } + result = getChecksumAddress(address); + // It is a checksummed address with a bad checksum + if (address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) && result !== address) { + errors.throwError('bad address checksum', errors.INVALID_ARGUMENT, { arg: 'address', value: address }); + } + // Maybe ICAP? (we only support direct mode) + } + else if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) { + // It is an ICAP address with a bad checksum + if (address.substring(2, 4) !== ibanChecksum(address)) { + errors.throwError('bad icap checksum', errors.INVALID_ARGUMENT, { arg: 'address', value: address }); + } + result = (new bn_js_1.default.BN(address.substring(4), 36)).toString(16); + while (result.length < 40) { + result = '0' + result; + } + result = getChecksumAddress('0x' + result); + } + else { + errors.throwError('invalid address', errors.INVALID_ARGUMENT, { arg: 'address', value: address }); + } + return result; + } + exports.getAddress = getAddress; + function getIcapAddress(address) { + var base36 = (new bn_js_1.default.BN(getAddress(address).substring(2), 16)).toString(36).toUpperCase(); + while (base36.length < 30) { + base36 = '0' + base36; + } + return 'XE' + ibanChecksum('XE00' + base36) + base36; + } + exports.getIcapAddress = getIcapAddress; + // http://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed + function getContractAddress(transaction) { + if (!transaction.from) { + throw new Error('missing from address'); + } + var nonce = transaction.nonce; + return getAddress('0x' + keccak256_1.keccak256(rlp_1.encode([ + getAddress(transaction.from), + bytes_1.stripZeros(bytes_1.hexlify(nonce)) + ])).substring(26)); + } + exports.getContractAddress = getContractAddress; + + },{"./bytes":146,"./errors":147,"./keccak256":148,"./rlp":150,"bn.js":53}],145:[function(require,module,exports){ + 'use strict'; + var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + /** + * BigNumber + * + * A wrapper around the BN.js object. We use the BN.js library + * because it is used by elliptic, so it is required regardles. + * + */ + var bn_js_1 = __importDefault(require("bn.js")); + var bytes_1 = require("./bytes"); + var properties_1 = require("./properties"); + var types_1 = require("./types"); + var errors = __importStar(require("./errors")); + var BN_1 = new bn_js_1.default.BN(-1); + function toHex(bn) { + var value = bn.toString(16); + if (value[0] === '-') { + if ((value.length % 2) === 0) { + return '-0x0' + value.substring(1); + } + return "-0x" + value.substring(1); + } + if ((value.length % 2) === 1) { + return '0x0' + value; + } + return '0x' + value; + } + function toBN(value) { + return bigNumberify(value)._bn; + } + function toBigNumber(bn) { + return new BigNumber(toHex(bn)); + } + var BigNumber = /** @class */ (function (_super) { + __extends(BigNumber, _super); + function BigNumber(value) { + var _this = _super.call(this) || this; + errors.checkNew(_this, BigNumber); + if (typeof (value) === 'string') { + if (bytes_1.isHexString(value)) { + if (value == '0x') { + value = '0x0'; + } + properties_1.defineReadOnly(_this, '_hex', value); + } + else if (value[0] === '-' && bytes_1.isHexString(value.substring(1))) { + properties_1.defineReadOnly(_this, '_hex', value); + } + else if (value.match(/^-?[0-9]*$/)) { + if (value == '') { + value = '0'; + } + properties_1.defineReadOnly(_this, '_hex', toHex(new bn_js_1.default.BN(value))); + } + else { + errors.throwError('invalid BigNumber string value', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); + } + } + else if (typeof (value) === 'number') { + if (parseInt(String(value)) !== value) { + errors.throwError('underflow', errors.NUMERIC_FAULT, { operation: 'setValue', fault: 'underflow', value: value, outputValue: parseInt(String(value)) }); + } + try { + properties_1.defineReadOnly(_this, '_hex', toHex(new bn_js_1.default.BN(value))); + } + catch (error) { + errors.throwError('overflow', errors.NUMERIC_FAULT, { operation: 'setValue', fault: 'overflow', details: error.message }); + } + } + else if (value instanceof BigNumber) { + properties_1.defineReadOnly(_this, '_hex', value._hex); + } + else if (value.toHexString) { + properties_1.defineReadOnly(_this, '_hex', toHex(toBN(value.toHexString()))); + } + else if (bytes_1.isArrayish(value)) { + properties_1.defineReadOnly(_this, '_hex', toHex(new bn_js_1.default.BN(bytes_1.hexlify(value).substring(2), 16))); + } + else { + errors.throwError('invalid BigNumber value', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); + } + return _this; + } + Object.defineProperty(BigNumber.prototype, "_bn", { + get: function () { + if (this._hex[0] === '-') { + return (new bn_js_1.default.BN(this._hex.substring(3), 16)).mul(BN_1); + } + return new bn_js_1.default.BN(this._hex.substring(2), 16); + }, + enumerable: true, + configurable: true + }); + BigNumber.prototype.fromTwos = function (value) { + return toBigNumber(this._bn.fromTwos(value)); + }; + BigNumber.prototype.toTwos = function (value) { + return toBigNumber(this._bn.toTwos(value)); + }; + BigNumber.prototype.add = function (other) { + return toBigNumber(this._bn.add(toBN(other))); + }; + BigNumber.prototype.sub = function (other) { + return toBigNumber(this._bn.sub(toBN(other))); + }; + BigNumber.prototype.div = function (other) { + var o = bigNumberify(other); + if (o.isZero()) { + errors.throwError('division by zero', errors.NUMERIC_FAULT, { operation: 'divide', fault: 'division by zero' }); + } + return toBigNumber(this._bn.div(toBN(other))); + }; + BigNumber.prototype.mul = function (other) { + return toBigNumber(this._bn.mul(toBN(other))); + }; + BigNumber.prototype.mod = function (other) { + return toBigNumber(this._bn.mod(toBN(other))); + }; + BigNumber.prototype.pow = function (other) { + return toBigNumber(this._bn.pow(toBN(other))); + }; + BigNumber.prototype.maskn = function (value) { + return toBigNumber(this._bn.maskn(value)); + }; + BigNumber.prototype.eq = function (other) { + return this._bn.eq(toBN(other)); + }; + BigNumber.prototype.lt = function (other) { + return this._bn.lt(toBN(other)); + }; + BigNumber.prototype.lte = function (other) { + return this._bn.lte(toBN(other)); + }; + BigNumber.prototype.gt = function (other) { + return this._bn.gt(toBN(other)); + }; + BigNumber.prototype.gte = function (other) { + return this._bn.gte(toBN(other)); + }; + BigNumber.prototype.isZero = function () { + return this._bn.isZero(); + }; + BigNumber.prototype.toNumber = function () { + try { + return this._bn.toNumber(); + } + catch (error) { + errors.throwError('overflow', errors.NUMERIC_FAULT, { operation: 'setValue', fault: 'overflow', details: error.message }); + } + return null; + }; + BigNumber.prototype.toString = function () { + return this._bn.toString(10); + }; + BigNumber.prototype.toHexString = function () { + return this._hex; + }; + return BigNumber; + }(types_1.BigNumber)); + function bigNumberify(value) { + if (value instanceof BigNumber) { + return value; + } + return new BigNumber(value); + } + exports.bigNumberify = bigNumberify; + exports.ConstantNegativeOne = bigNumberify(-1); + exports.ConstantZero = bigNumberify(0); + exports.ConstantOne = bigNumberify(1); + exports.ConstantTwo = bigNumberify(2); + exports.ConstantWeiPerEther = bigNumberify('1000000000000000000'); + + },{"./bytes":146,"./errors":147,"./properties":149,"./types":151,"bn.js":53}],146:[function(require,module,exports){ + "use strict"; + /** + * Conversion Utilities + * + */ + Object.defineProperty(exports, "__esModule", { value: true }); + var errors = require("./errors"); + exports.AddressZero = '0x0000000000000000000000000000000000000000'; + exports.HashZero = '0x0000000000000000000000000000000000000000000000000000000000000000'; + function isBigNumber(value) { + return !!value._bn; + } + function addSlice(array) { + if (array.slice) { + return array; + } + array.slice = function () { + var args = Array.prototype.slice.call(arguments); + return new Uint8Array(Array.prototype.slice.apply(array, args)); + }; + return array; + } + function isArrayish(value) { + if (!value || parseInt(String(value.length)) != value.length || typeof (value) === 'string') { + return false; + } + for (var i = 0; i < value.length; i++) { + var v = value[i]; + if (v < 0 || v >= 256 || parseInt(String(v)) != v) { + return false; + } + } + return true; + } + exports.isArrayish = isArrayish; + function arrayify(value) { + if (value == null) { + errors.throwError('cannot convert null value to array', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); + } + if (isBigNumber(value)) { + value = value.toHexString(); + } + if (typeof (value) === 'string') { + var match = value.match(/^(0x)?[0-9a-fA-F]*$/); + if (!match) { + errors.throwError('invalid hexidecimal string', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); + } + if (match[1] !== '0x') { + errors.throwError('hex string must have 0x prefix', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); + } + value = value.substring(2); + if (value.length % 2) { + value = '0' + value; + } + var result = []; + for (var i = 0; i < value.length; i += 2) { + result.push(parseInt(value.substr(i, 2), 16)); + } + return addSlice(new Uint8Array(result)); + } + else if (typeof (value) === 'string') { + } + if (isArrayish(value)) { + return addSlice(new Uint8Array(value)); + } + errors.throwError('invalid arrayify value', null, { arg: 'value', value: value, type: typeof (value) }); + return null; + } + exports.arrayify = arrayify; + function concat(objects) { + var arrays = []; + var length = 0; + for (var i = 0; i < objects.length; i++) { + var object = arrayify(objects[i]); + arrays.push(object); + length += object.length; + } + var result = new Uint8Array(length); + var offset = 0; + for (var i = 0; i < arrays.length; i++) { + result.set(arrays[i], offset); + offset += arrays[i].length; + } + return addSlice(result); + } + exports.concat = concat; + function stripZeros(value) { + var result = arrayify(value); + if (result.length === 0) { + return result; + } + // Find the first non-zero entry + var start = 0; + while (result[start] === 0) { + start++; + } + // If we started with zeros, strip them + if (start) { + result = result.slice(start); + } + return result; + } + exports.stripZeros = stripZeros; + function padZeros(value, length) { + value = arrayify(value); + if (length < value.length) { + throw new Error('cannot pad'); + } + var result = new Uint8Array(length); + result.set(value, length - value.length); + return addSlice(result); + } + exports.padZeros = padZeros; + function isHexString(value, length) { + if (typeof (value) !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) { + return false; + } + if (length && value.length !== 2 + 2 * length) { + return false; + } + return true; + } + exports.isHexString = isHexString; + var HexCharacters = '0123456789abcdef'; + function hexlify(value) { + if (isBigNumber(value)) { + return value.toHexString(); + } + if (typeof (value) === 'number') { + if (value < 0) { + errors.throwError('cannot hexlify negative value', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); + } + var hex = ''; + while (value) { + hex = HexCharacters[value & 0x0f] + hex; + value = Math.floor(value / 16); + } + if (hex.length) { + if (hex.length % 2) { + hex = '0' + hex; + } + return '0x' + hex; + } + return '0x00'; + } + if (typeof (value) === 'string') { + var match = value.match(/^(0x)?[0-9a-fA-F]*$/); + if (!match) { + errors.throwError('invalid hexidecimal string', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); + } + if (match[1] !== '0x') { + errors.throwError('hex string must have 0x prefix', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); + } + if (value.length % 2) { + value = '0x0' + value.substring(2); + } + return value; + } + if (isArrayish(value)) { + var result = []; + for (var i = 0; i < value.length; i++) { + var v = value[i]; + result.push(HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f]); + } + return '0x' + result.join(''); + } + errors.throwError('invalid hexlify value', null, { arg: 'value', value: value }); + return 'never'; + } + exports.hexlify = hexlify; + function hexDataLength(data) { + if (!isHexString(data) || (data.length % 2) !== 0) { + return null; + } + return (data.length - 2) / 2; + } + exports.hexDataLength = hexDataLength; + function hexDataSlice(data, offset, length) { + if (!isHexString(data)) { + errors.throwError('invalid hex data', errors.INVALID_ARGUMENT, { arg: 'value', value: data }); + } + if ((data.length % 2) !== 0) { + errors.throwError('hex data length must be even', errors.INVALID_ARGUMENT, { arg: 'value', value: data }); + } + offset = 2 + 2 * offset; + if (length != null) { + return '0x' + data.substring(offset, offset + 2 * length); + } + return '0x' + data.substring(offset); + } + exports.hexDataSlice = hexDataSlice; + function hexStripZeros(value) { + if (!isHexString(value)) { + errors.throwError('invalid hex string', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); + } + while (value.length > 3 && value.substring(0, 3) === '0x0') { + value = '0x' + value.substring(3); + } + return value; + } + exports.hexStripZeros = hexStripZeros; + function hexZeroPad(value, length) { + if (!isHexString(value)) { + errors.throwError('invalid hex string', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); + } + while (value.length < 2 * length + 2) { + value = '0x0' + value.substring(2); + } + return value; + } + exports.hexZeroPad = hexZeroPad; + function isSignature(value) { + return (value && value.r != null && value.s != null); + } + function splitSignature(signature) { + var v = 0; + var r = '0x', s = '0x'; + if (isSignature(signature)) { + if (signature.v == null && signature.recoveryParam == null) { + errors.throwError('at least on of recoveryParam or v must be specified', errors.INVALID_ARGUMENT, { argument: 'signature', value: signature }); + } + r = hexZeroPad(signature.r, 32); + s = hexZeroPad(signature.s, 32); + v = signature.v; + if (typeof (v) === 'string') { + v = parseInt(v, 16); + } + var recoveryParam = signature.recoveryParam; + if (recoveryParam == null && signature.v != null) { + recoveryParam = 1 - (v % 2); + } + v = 27 + recoveryParam; + } + else { + var bytes = arrayify(signature); + if (bytes.length !== 65) { + throw new Error('invalid signature'); + } + r = hexlify(bytes.slice(0, 32)); + s = hexlify(bytes.slice(32, 64)); + v = bytes[64]; + if (v !== 27 && v !== 28) { + v = 27 + (v % 2); + } + } + return { + r: r, + s: s, + recoveryParam: (v - 27), + v: v + }; + } + exports.splitSignature = splitSignature; + function joinSignature(signature) { + signature = splitSignature(signature); + return hexlify(concat([ + signature.r, + signature.s, + (signature.recoveryParam ? '0x1c' : '0x1b') + ])); + } + exports.joinSignature = joinSignature; + + },{"./errors":147}],147:[function(require,module,exports){ + 'use strict'; + Object.defineProperty(exports, "__esModule", { value: true }); + // Unknown Error + exports.UNKNOWN_ERROR = 'UNKNOWN_ERROR'; + // Not implemented + exports.NOT_IMPLEMENTED = 'NOT_IMPLEMENTED'; + // Missing new operator to an object + // - name: The name of the class + exports.MISSING_NEW = 'MISSING_NEW'; + // Call exception + // - transaction: the transaction + // - address?: the contract address + // - args?: The arguments passed into the function + // - method?: The Solidity method signature + // - errorSignature?: The EIP848 error signature + // - errorArgs?: The EIP848 error parameters + // - reason: The reason (only for EIP848 "Error(string)") + exports.CALL_EXCEPTION = 'CALL_EXCEPTION'; + // Response from a server was invalid + // - response: The body of the response + //'BAD_RESPONSE', + // Invalid argument (e.g. value is incompatible with type) to a function: + // - arg: The argument name that was invalid + // - value: The value of the argument + exports.INVALID_ARGUMENT = 'INVALID_ARGUMENT'; + // Missing argument to a function: + // - count: The number of arguments received + // - expectedCount: The number of arguments expected + exports.MISSING_ARGUMENT = 'MISSING_ARGUMENT'; + // Too many arguments + // - count: The number of arguments received + // - expectedCount: The number of arguments expected + exports.UNEXPECTED_ARGUMENT = 'UNEXPECTED_ARGUMENT'; + // Numeric Fault + // - operation: the operation being executed + // - fault: the reason this faulted + exports.NUMERIC_FAULT = 'NUMERIC_FAULT'; + // Unsupported operation + // - operation + exports.UNSUPPORTED_OPERATION = 'UNSUPPORTED_OPERATION'; + var _permanentCensorErrors = false; + var _censorErrors = false; + // @TODO: Enum + function throwError(message, code, params) { + if (_censorErrors) { + throw new Error('unknown error'); + } + if (!code) { + code = exports.UNKNOWN_ERROR; + } + if (!params) { + params = {}; + } + var messageDetails = []; + Object.keys(params).forEach(function (key) { + try { + messageDetails.push(key + '=' + JSON.stringify(params[key])); + } + catch (error) { + messageDetails.push(key + '=' + JSON.stringify(params[key].toString())); + } + }); + var reason = message; + if (messageDetails.length) { + message += ' (' + messageDetails.join(', ') + ')'; + } + // @TODO: Any?? + var error = new Error(message); + error.reason = reason; + error.code = code; + Object.keys(params).forEach(function (key) { + error[key] = params[key]; + }); + throw error; + } + exports.throwError = throwError; + function checkNew(self, kind) { + if (!(self instanceof kind)) { + throwError('missing new', exports.MISSING_NEW, { name: kind.name }); + } + } + exports.checkNew = checkNew; + function checkArgumentCount(count, expectedCount, suffix) { + if (!suffix) { + suffix = ''; + } + if (count < expectedCount) { + throwError('missing argument' + suffix, exports.MISSING_ARGUMENT, { count: count, expectedCount: expectedCount }); + } + if (count > expectedCount) { + throwError('too many arguments' + suffix, exports.UNEXPECTED_ARGUMENT, { count: count, expectedCount: expectedCount }); + } + } + exports.checkArgumentCount = checkArgumentCount; + function setCensorship(censorship, permanent) { + if (_permanentCensorErrors) { + throwError('error censorship permanent', exports.UNSUPPORTED_OPERATION, { operation: 'setCersorship' }); + } + _censorErrors = !!censorship; + _permanentCensorErrors = !!permanent; + } + exports.setCensorship = setCensorship; + + },{}],148:[function(require,module,exports){ + 'use strict'; + Object.defineProperty(exports, "__esModule", { value: true }); + var sha3 = require("js-sha3"); + var bytes_1 = require("./bytes"); + function keccak256(data) { + return '0x' + sha3.keccak_256(bytes_1.arrayify(data)); + } + exports.keccak256 = keccak256; + + },{"./bytes":146,"js-sha3":142}],149:[function(require,module,exports){ + 'use strict'; + Object.defineProperty(exports, "__esModule", { value: true }); + function defineReadOnly(object, name, value) { + Object.defineProperty(object, name, { + enumerable: true, + value: value, + writable: false, + }); + } + exports.defineReadOnly = defineReadOnly; + function defineFrozen(object, name, value) { + var frozen = JSON.stringify(value); + Object.defineProperty(object, name, { + enumerable: true, + get: function () { return JSON.parse(frozen); } + }); + } + exports.defineFrozen = defineFrozen; + function resolveProperties(object) { + var result = {}; + var promises = []; + Object.keys(object).forEach(function (key) { + var value = object[key]; + if (value instanceof Promise) { + promises.push(value.then(function (value) { + result[key] = value; + return null; + })); + } + else { + result[key] = value; + } + }); + return Promise.all(promises).then(function () { + return result; + }); + } + exports.resolveProperties = resolveProperties; + function shallowCopy(object) { + var result = {}; + for (var key in object) { + result[key] = object[key]; + } + return result; + } + exports.shallowCopy = shallowCopy; + function jsonCopy(object) { + return JSON.parse(JSON.stringify(object)); + } + exports.jsonCopy = jsonCopy; + + },{}],150:[function(require,module,exports){ + "use strict"; + //See: https://github.com/ethereum/wiki/wiki/RLP + Object.defineProperty(exports, "__esModule", { value: true }); + var bytes_1 = require("./bytes"); + function arrayifyInteger(value) { + var result = []; + while (value) { + result.unshift(value & 0xff); + value >>= 8; + } + return result; + } + function unarrayifyInteger(data, offset, length) { + var result = 0; + for (var i = 0; i < length; i++) { + result = (result * 256) + data[offset + i]; + } + return result; + } + function _encode(object) { + if (Array.isArray(object)) { + var payload = []; + object.forEach(function (child) { + payload = payload.concat(_encode(child)); + }); + if (payload.length <= 55) { + payload.unshift(0xc0 + payload.length); + return payload; + } + var length = arrayifyInteger(payload.length); + length.unshift(0xf7 + length.length); + return length.concat(payload); + } + var data = Array.prototype.slice.call(bytes_1.arrayify(object)); + if (data.length === 1 && data[0] <= 0x7f) { + return data; + } + else if (data.length <= 55) { + data.unshift(0x80 + data.length); + return data; + } + var length = arrayifyInteger(data.length); + length.unshift(0xb7 + length.length); + return length.concat(data); + } + function encode(object) { + return bytes_1.hexlify(_encode(object)); + } + exports.encode = encode; + function _decodeChildren(data, offset, childOffset, length) { + var result = []; + while (childOffset < offset + 1 + length) { + var decoded = _decode(data, childOffset); + result.push(decoded.result); + childOffset += decoded.consumed; + if (childOffset > offset + 1 + length) { + throw new Error('invalid rlp'); + } + } + return { consumed: (1 + length), result: result }; + } + // returns { consumed: number, result: Object } + function _decode(data, offset) { + if (data.length === 0) { + throw new Error('invalid rlp data'); + } + // Array with extra length prefix + if (data[offset] >= 0xf8) { + var lengthLength = data[offset] - 0xf7; + if (offset + 1 + lengthLength > data.length) { + throw new Error('too short'); + } + var length = unarrayifyInteger(data, offset + 1, lengthLength); + if (offset + 1 + lengthLength + length > data.length) { + throw new Error('to short'); + } + return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length); + } + else if (data[offset] >= 0xc0) { + var length = data[offset] - 0xc0; + if (offset + 1 + length > data.length) { + throw new Error('invalid rlp data'); + } + return _decodeChildren(data, offset, offset + 1, length); + } + else if (data[offset] >= 0xb8) { + var lengthLength = data[offset] - 0xb7; + if (offset + 1 + lengthLength > data.length) { + throw new Error('invalid rlp data'); + } + var length = unarrayifyInteger(data, offset + 1, lengthLength); + if (offset + 1 + lengthLength + length > data.length) { + throw new Error('invalid rlp data'); + } + var result = bytes_1.hexlify(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length)); + return { consumed: (1 + lengthLength + length), result: result }; + } + else if (data[offset] >= 0x80) { + var length = data[offset] - 0x80; + if (offset + 1 + length > data.length) { + throw new Error('invlaid rlp data'); + } + var result = bytes_1.hexlify(data.slice(offset + 1, offset + 1 + length)); + return { consumed: (1 + length), result: result }; + } + return { consumed: 1, result: bytes_1.hexlify(data[offset]) }; + } + function decode(data) { + var bytes = bytes_1.arrayify(data); + var decoded = _decode(bytes, 0); + if (decoded.consumed !== bytes.length) { + throw new Error('invalid rlp data'); + } + return decoded.result; + } + exports.decode = decode; + + },{"./bytes":146}],151:[function(require,module,exports){ + "use strict"; + /////////////////////////////// + // Bytes + Object.defineProperty(exports, "__esModule", { value: true }); + /////////////////////////////// + // BigNumber + var BigNumber = /** @class */ (function () { + function BigNumber() { + } + return BigNumber; + }()); + exports.BigNumber = BigNumber; + ; + ; + ; + /////////////////////////////// + // Interface + var Indexed = /** @class */ (function () { + function Indexed() { + } + return Indexed; + }()); + exports.Indexed = Indexed; + /** + * Provider + * + * Note: We use an abstract class so we can use instanceof to determine if an + * object is a Provider. + */ + var MinimalProvider = /** @class */ (function () { + function MinimalProvider() { + } + return MinimalProvider; + }()); + exports.MinimalProvider = MinimalProvider; + /** + * Signer + * + * Note: We use an abstract class so we can use instanceof to determine if an + * object is a Signer. + */ + var Signer = /** @class */ (function () { + function Signer() { + } + return Signer; + }()); + exports.Signer = Signer; + /////////////////////////////// + // HDNode + var HDNode = /** @class */ (function () { + function HDNode() { + } + return HDNode; + }()); + exports.HDNode = HDNode; + + },{}],152:[function(require,module,exports){ + 'use strict'; + Object.defineProperty(exports, "__esModule", { value: true }); + var bytes_1 = require("./bytes"); + var UnicodeNormalizationForm; + (function (UnicodeNormalizationForm) { + UnicodeNormalizationForm["current"] = ""; + UnicodeNormalizationForm["NFC"] = "NFC"; + UnicodeNormalizationForm["NFD"] = "NFD"; + UnicodeNormalizationForm["NFKC"] = "NFKC"; + UnicodeNormalizationForm["NFKD"] = "NFKD"; + })(UnicodeNormalizationForm = exports.UnicodeNormalizationForm || (exports.UnicodeNormalizationForm = {})); + ; + // http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array + function toUtf8Bytes(str, form) { + if (form === void 0) { form = UnicodeNormalizationForm.current; } + if (form != UnicodeNormalizationForm.current) { + str = str.normalize(form); + } + var result = []; + var offset = 0; + for (var i = 0; i < str.length; i++) { + var c = str.charCodeAt(i); + if (c < 128) { + result[offset++] = c; + } + else if (c < 2048) { + result[offset++] = (c >> 6) | 192; + result[offset++] = (c & 63) | 128; + } + else if (((c & 0xFC00) == 0xD800) && (i + 1) < str.length && ((str.charCodeAt(i + 1) & 0xFC00) == 0xDC00)) { + // Surrogate Pair + c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF); + result[offset++] = (c >> 18) | 240; + result[offset++] = ((c >> 12) & 63) | 128; + result[offset++] = ((c >> 6) & 63) | 128; + result[offset++] = (c & 63) | 128; + } + else { + result[offset++] = (c >> 12) | 224; + result[offset++] = ((c >> 6) & 63) | 128; + result[offset++] = (c & 63) | 128; + } + } + return bytes_1.arrayify(result); + } + exports.toUtf8Bytes = toUtf8Bytes; + ; + // http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499 + function toUtf8String(bytes) { + bytes = bytes_1.arrayify(bytes); + var result = ''; + var i = 0; + // Invalid bytes are ignored + while (i < bytes.length) { + var c = bytes[i++]; + if (c >> 7 == 0) { + // 0xxx xxxx + result += String.fromCharCode(c); + continue; + } + // Invalid starting byte + if (c >> 6 == 0x02) { + continue; + } + // Multibyte; how many bytes left for thus character? + var extraLength = null; + if (c >> 5 == 0x06) { + extraLength = 1; + } + else if (c >> 4 == 0x0e) { + extraLength = 2; + } + else if (c >> 3 == 0x1e) { + extraLength = 3; + } + else if (c >> 2 == 0x3e) { + extraLength = 4; + } + else if (c >> 1 == 0x7e) { + extraLength = 5; + } + else { + continue; + } + // Do we have enough bytes in our data? + if (i + extraLength > bytes.length) { + // If there is an invalid unprocessed byte, try to continue + for (; i < bytes.length; i++) { + if (bytes[i] >> 6 != 0x02) { + break; + } + } + if (i != bytes.length) + continue; + // All leftover bytes are valid. + return result; + } + // Remove the UTF-8 prefix from the char (res) + var res = c & ((1 << (8 - extraLength - 1)) - 1); + var count; + for (count = 0; count < extraLength; count++) { + var nextChar = bytes[i++]; + // Is the char valid multibyte part? + if (nextChar >> 6 != 0x02) { + break; + } + ; + res = (res << 6) | (nextChar & 0x3f); + } + if (count != extraLength) { + i--; + continue; + } + if (res <= 0xffff) { + result += String.fromCharCode(res); + continue; + } + res -= 0x10000; + result += String.fromCharCode(((res >> 10) & 0x3ff) + 0xd800, (res & 0x3ff) + 0xdc00); + } + return result; + } + exports.toUtf8String = toUtf8String; + + },{"./bytes":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 + 'wei': '1', // eslint-disable-line + 'kwei': '1000', // eslint-disable-line + 'Kwei': '1000', // eslint-disable-line + 'babbage': '1000', // eslint-disable-line + 'femtoether': '1000', // eslint-disable-line + 'mwei': '1000000', // eslint-disable-line + 'Mwei': '1000000', // eslint-disable-line + 'lovelace': '1000000', // eslint-disable-line + 'picoether': '1000000', // eslint-disable-line + 'gwei': '1000000000', // eslint-disable-line + 'Gwei': '1000000000', // eslint-disable-line + 'shannon': '1000000000', // eslint-disable-line + 'nanoether': '1000000000', // eslint-disable-line + 'nano': '1000000000', // eslint-disable-line + 'szabo': '1000000000000', // eslint-disable-line + 'microether': '1000000000000', // eslint-disable-line + 'micro': '1000000000000', // eslint-disable-line + 'finney': '1000000000000000', // eslint-disable-line + 'milliether': '1000000000000000', // eslint-disable-line + 'milli': '1000000000000000', // eslint-disable-line + 'ether': '1000000000000000000', // eslint-disable-line + 'kether': '1000000000000000000000', // eslint-disable-line + 'grand': '1000000000000000000000', // eslint-disable-line + 'mether': '1000000000000000000000000', // eslint-disable-line + 'gether': '1000000000000000000000000000', // eslint-disable-line + 'tether': '1000000000000000000000000000000' }; + + /** + * Returns value of unit in Wei + * + * @method getValueOfUnit + * @param {String} unit the unit to convert to, default ether + * @returns {BigNumber} value of the unit (in Wei) + * @throws error if the unit is not correct:w + */ + function getValueOfUnit(unitInput) { + var unit = unitInput ? unitInput.toLowerCase() : 'ether'; + var unitValue = unitMap[unit]; // eslint-disable-line + + if (typeof unitValue !== 'string') { + throw new Error('[ethjs-unit] the unit provided ' + unitInput + ' doesn\'t exists, please use the one of the following units ' + JSON.stringify(unitMap, null, 2)); + } + + return new BN(unitValue, 10); + } + + function numberToString(arg) { + if (typeof arg === 'string') { + if (!arg.match(/^-?[0-9.]+$/)) { + throw new Error('while converting number to string, invalid number value \'' + arg + '\', should be a number matching (^-?[0-9.]+).'); + } + return arg; + } else if (typeof arg === 'number') { + return String(arg); + } else if (typeof arg === 'object' && arg.toString && (arg.toTwos || arg.dividedToIntegerBy)) { + if (arg.toPrecision) { + return String(arg.toPrecision()); + } else { + // eslint-disable-line + return arg.toString(10); + } + } + throw new Error('while converting number to string, invalid number value \'' + arg + '\' type ' + typeof arg + '.'); + } + + function fromWei(weiInput, unit, optionsInput) { + var wei = numberToBN(weiInput); // eslint-disable-line + var negative = wei.lt(zero); // eslint-disable-line + var base = getValueOfUnit(unit); + var baseLength = unitMap[unit].length - 1 || 1; + var options = optionsInput || {}; + + if (negative) { + wei = wei.mul(negative1); + } + + var fraction = wei.mod(base).toString(10); // eslint-disable-line + + while (fraction.length < baseLength) { + fraction = '0' + fraction; + } + + if (!options.pad) { + fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1]; + } + + var whole = wei.div(base).toString(10); // eslint-disable-line + + if (options.commify) { + whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ','); + } + + var value = '' + whole + (fraction == '0' ? '' : '.' + fraction); // eslint-disable-line + + if (negative) { + value = '-' + value; + } + + return value; + } + + function toWei(etherInput, unit) { + var ether = numberToString(etherInput); // eslint-disable-line + var base = getValueOfUnit(unit); + var baseLength = unitMap[unit].length - 1 || 1; + + // Is it negative? + var negative = ether.substring(0, 1) === '-'; // eslint-disable-line + if (negative) { + ether = ether.substring(1); + } + + if (ether === '.') { + throw new Error('[ethjs-unit] while converting number ' + etherInput + ' to wei, invalid value'); + } + + // Split it into a whole and fractional part + var comps = ether.split('.'); // eslint-disable-line + if (comps.length > 2) { + throw new Error('[ethjs-unit] while converting number ' + etherInput + ' to wei, too many decimal points'); + } + + var whole = comps[0], + fraction = comps[1]; // eslint-disable-line + + if (!whole) { + whole = '0'; + } + if (!fraction) { + fraction = '0'; + } + if (fraction.length > baseLength) { + throw new Error('[ethjs-unit] while converting number ' + etherInput + ' to wei, too many decimal places'); + } + + while (fraction.length < baseLength) { + fraction += '0'; + } + + whole = new BN(whole); + fraction = new BN(fraction); + var wei = whole.mul(base).add(fraction); // eslint-disable-line + + if (negative) { + wei = wei.mul(negative1); + } + + return new BN(wei.toString(10), 10); + } + + module.exports = { + unitMap: unitMap, + numberToString: numberToString, + getValueOfUnit: getValueOfUnit, + fromWei: fromWei, + toWei: toWei + }; + },{"bn.js":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) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + Buffer = require('buf' + 'fer').Buffer; + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + } + + if (base === 16) { + this._parseHex(number, start); + } else { + this._parseBase(number, base, start); + } + + if (number[0] === '-') { + this.negative = 1; + } + + this.strip(); + + if (endian !== 'le') return; + + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex (str, start, end) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r <<= 4; + + // 'a' - 'f' + if (c >= 49 && c <= 54) { + r |= c - 49 + 0xa; + + // 'A' - 'F' + } else if (c >= 17 && c <= 22) { + r |= c - 17 + 0xa; + + // '0' - '9' + } else { + r |= c & 0xf; + } + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + // Scan 24-bit chunks and add them to the number + var off = 0; + for (i = number.length - 6, j = 0; i >= start; i -= 6) { + w = parseHex(number, i, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + if (i + 6 !== start) { + w = parseHex(number, start, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + } + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + r.strip(); + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; + })(typeof module === 'undefined' || module, this); + + },{}],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 + * @return {String} output + */ + function padToEven(value) { + var a = value; // eslint-disable-line + + if (typeof a !== 'string') { + throw new Error('[ethjs-util] while padding to even, value must be string, is currently ' + typeof a + ', while padToEven.'); + } + + if (a.length % 2) { + a = '0' + a; + } + + return a; + } + + /** + * Converts a `Number` into a hex `String` + * @param {Number} i + * @return {String} + */ + function intToHex(i) { + var hex = i.toString(16); // eslint-disable-line + + return '0x' + hex; + } + + /** + * Converts an `Number` to a `Buffer` + * @param {Number} i + * @return {Buffer} + */ + function intToBuffer(i) { + var hex = intToHex(i); + + return new Buffer(padToEven(hex.slice(2)), 'hex'); + } + + /** + * Get the binary size of a string + * @param {String} str + * @return {Number} + */ + function getBinarySize(str) { + if (typeof str !== 'string') { + throw new Error('[ethjs-util] while getting binary size, method getBinarySize requires input \'str\' to be type String, got \'' + typeof str + '\'.'); + } + + return Buffer.byteLength(str, 'utf8'); + } + + /** + * Returns TRUE if the first specified array contains all elements + * from the second one. FALSE otherwise. + * + * @param {array} superset + * @param {array} subset + * + * @returns {boolean} + */ + function arrayContainsArray(superset, subset, some) { + if (Array.isArray(superset) !== true) { + throw new Error('[ethjs-util] method arrayContainsArray requires input \'superset\' to be an array got type \'' + typeof superset + '\''); + } + if (Array.isArray(subset) !== true) { + throw new Error('[ethjs-util] method arrayContainsArray requires input \'subset\' to be an array got type \'' + typeof subset + '\''); + } + + return subset[Boolean(some) && 'some' || 'every'](function (value) { + return superset.indexOf(value) >= 0; + }); + } + + /** + * Should be called to get utf8 from it's hex representation + * + * @method toUtf8 + * @param {String} string in hex + * @returns {String} ascii string representation of hex value + */ + function toUtf8(hex) { + var bufferValue = new Buffer(padToEven(stripHexPrefix(hex).replace(/^0+|0+$/g, '')), 'hex'); + + return bufferValue.toString('utf8'); + } + + /** + * Should be called to get ascii from it's hex representation + * + * @method toAscii + * @param {String} string in hex + * @returns {String} ascii string representation of hex value + */ + function toAscii(hex) { + var str = ''; // eslint-disable-line + var i = 0, + l = hex.length; // eslint-disable-line + + if (hex.substring(0, 2) === '0x') { + i = 2; + } + + for (; i < l; i += 2) { + var code = parseInt(hex.substr(i, 2), 16); + str += String.fromCharCode(code); + } + + return str; + } + + /** + * Should be called to get hex representation (prefixed by 0x) of utf8 string + * + * @method fromUtf8 + * @param {String} string + * @param {Number} optional padding + * @returns {String} hex representation of input string + */ + function fromUtf8(stringValue) { + var str = new Buffer(stringValue, 'utf8'); + + return '0x' + padToEven(str.toString('hex')).replace(/^0+|0+$/g, ''); + } + + /** + * Should be called to get hex representation (prefixed by 0x) of ascii string + * + * @method fromAscii + * @param {String} string + * @param {Number} optional padding + * @returns {String} hex representation of input string + */ + function fromAscii(stringValue) { + var hex = ''; // eslint-disable-line + for (var i = 0; i < stringValue.length; i++) { + // eslint-disable-line + var code = stringValue.charCodeAt(i); + var n = code.toString(16); + hex += n.length < 2 ? '0' + n : n; + } + + return '0x' + hex; + } + + /** + * getKeys([{a: 1, b: 2}, {a: 3, b: 4}], 'a') => [1, 3] + * + * @method getKeys get specific key from inner object array of objects + * @param {String} params + * @param {String} key + * @param {Boolean} allowEmpty + * @returns {Array} output just a simple array of output keys + */ + function getKeys(params, key, allowEmpty) { + if (!Array.isArray(params)) { + throw new Error('[ethjs-util] method getKeys expecting type Array as \'params\' input, got \'' + typeof params + '\''); + } + if (typeof key !== 'string') { + throw new Error('[ethjs-util] method getKeys expecting type String for input \'key\' got \'' + typeof key + '\'.'); + } + + var result = []; // eslint-disable-line + + for (var i = 0; i < params.length; i++) { + // eslint-disable-line + var value = params[i][key]; // eslint-disable-line + if (allowEmpty && !value) { + value = ''; + } else if (typeof value !== 'string') { + throw new Error('invalid abi'); + } + result.push(value); + } + + return result; + } + + /** + * Is the string a hex string. + * + * @method check if string is hex string of specific length + * @param {String} value + * @param {Number} length + * @returns {Boolean} output the string is a hex string + */ + function isHexString(value, length) { + if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) { + return false; + } + + if (length && value.length !== 2 + 2 * length) { + return false; + } + + return true; + } + + module.exports = { + arrayContainsArray: arrayContainsArray, + intToBuffer: intToBuffer, + getBinarySize: getBinarySize, + isHexPrefixed: isHexPrefixed, + stripHexPrefix: stripHexPrefix, + padToEven: padToEven, + intToHex: intToHex, + fromAscii: fromAscii, + fromUtf8: fromUtf8, + toAscii: toAscii, + toUtf8: toUtf8, + getKeys: getKeys, + isHexString: isHexString + }; + }).call(this,require("buffer").Buffer) + },{"buffer":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 + // `~` to make sure that the built-in object properties are not overridden or + // used as an attack vector. + // We also assume that `Object.create(null)` is available when the event name + // is an ES6 Symbol. + // + var prefix = typeof Object.create !== 'function' ? '~' : false; + + /** + * Representation of a single EventEmitter function. + * + * @param {Function} fn Event handler to be called. + * @param {Mixed} context Context for function execution. + * @param {Boolean} once Only emit once + * @api private + */ + function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; + } + + /** + * Minimal EventEmitter interface that is molded against the Node.js + * EventEmitter interface. + * + * @constructor + * @api public + */ + function EventEmitter() { /* Nothing to set */ } + + /** + * Holds the assigned EventEmitters by name. + * + * @type {Object} + * @private + */ + EventEmitter.prototype._events = undefined; + + /** + * Return a list of assigned event listeners. + * + * @param {String} event The events that should be listed. + * @param {Boolean} exists We only need to know if there are listeners. + * @returns {Array|Boolean} + * @api public + */ + 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. + * + * @param {String} event The name of the event. + * @returns {Boolean} Indication if we've emitted an event. + * @api public + */ + 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; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + 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; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + default: + 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. + * + * @param {String} event Name of the event. + * @param {Functon} fn Callback function. + * @param {Mixed} context The context of the function. + * @api public + */ + 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 { + if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [ + this._events[evt], listener + ]; + } + + return this; + }; + + /** + * Add an EventListener that's only called once. + * + * @param {String} event Name of the event. + * @param {Function} fn Callback function. + * @param {Mixed} context The context of the function. + * @api public + */ + 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 { + if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [ + this._events[evt], listener + ]; + } + + return this; + }; + + /** + * Remove event listeners. + * + * @param {String} event The event we want to remove. + * @param {Function} fn The listener that we need to find. + * @param {Mixed} context Only remove listeners matching this context. + * @param {Boolean} once Only remove once listeners. + * @api public + */ + 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 ( + listeners.fn !== fn + || (once && !listeners.once) + || (context && listeners.context !== context) + ) { + events.push(listeners); + } + } else { + for (var i = 0, length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn + || (once && !listeners[i].once) + || (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) { + this._events[evt] = events.length === 1 ? events[0] : events; + } else { + delete this._events[evt]; + } + + return this; + }; + + /** + * Remove all listeners or only the listeners for the specified event. + * + * @param {String} event The event want to remove all listeners for. + * @api public + */ + 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. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 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) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + 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 || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + } + } + + handler = this._events[type]; + + if (isUndefined(handler)) + return false; + + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); + } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + 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; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + 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)) { + m = this._maxListeners; + } 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 ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } + + 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 || + (list[i].listener && list[i].listener === listener)) { + position = i; + 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) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } + + listeners = this._events[type]; + + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + 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]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + 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) + return evlistener.length; + } + 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') + if (salt) { + 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) + tmp.copy(iv, ivStart, used, used + length) + 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)) { + if (receiver == null) { + iterator(array[i], i, array); + } else { + iterator.call(receiver, array[i], i, array); + } + } + } + }; + + var forEachString = function forEachString(string, iterator, receiver) { + for (var i = 0, len = string.length; i < len; i++) { + // no such thing as a sparse string. + if (receiver == null) { + iterator(string.charAt(i), i, string); + } else { + iterator.call(receiver, string.charAt(i), i, string); + } + } + }; + + var forEachObject = function forEachObject(object, iterator, receiver) { + for (var k in object) { + if (hasOwnProperty.call(object, k)) { + if (receiver == null) { + iterator(object[k], k, object); + } else { + iterator.call(receiver, object[k], k, object); + } + } + } + }; + + var forEach = function forEach(list, iterator, thisArg) { + if (!isCallable(iterator)) { + throw new TypeError('iterator must be a function'); + } + + var receiver; + if (arguments.length >= 3) { + receiver = thisArg; + } + + if (toStr.call(list) === '[object Array]') { + forEachArray(list, iterator, receiver); + } else if (typeof list === 'string') { + forEachString(list, iterator, receiver); + } else { + forEachObject(list, iterator, receiver); + } + }; + + module.exports = forEach; + + },{"is-callable":182}],160:[function(require,module,exports){ + (function (global){ + var win; + + if (typeof window !== "undefined") { + win = window; + } else if (typeof global !== "undefined") { + win = global; + } else if (typeof self !== "undefined"){ + win = self; + } else { + win = {}; + } + + module.exports = win; + + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + },{}],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 { + if (encoding !== 'buffer') chunk = new Buffer(chunk, encoding) + this.update(chunk) + } catch (err) { + error = err + } + + callback(error) + } + + HashBase.prototype._flush = function (callback) { + var error = null + try { + this.push(this._digest()) + } catch (err) { + error = err + } + + callback(error) + } + + HashBase.prototype.update = function (data, encoding) { + 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 + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] + this._update() + this._blockOffset = 0 + } + while (offset < data.length) block[this._blockOffset++] = data[offset++] + + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry + carry = (this._length[j] / 0x0100000000) | 0 + if (carry > 0) this._length[j] -= 0x0100000000 * carry + } + + return this + } + + HashBase.prototype._update = function (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; + hash.sha224 = hash.sha.sha224; + 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; + this.blockSize = this.constructor.blockSize; + this.outSize = this.constructor.outSize; + this.hmacStrength = this.constructor.hmacStrength; + this.padLength = this.constructor.padLength / 8; + this.endian = 'big'; + + this._delta8 = this.blockSize / 8; + this._delta32 = this.blockSize / 32; + } + exports.BlockHash = BlockHash; + + BlockHash.prototype.update = function update(msg, enc) { + // Convert message to array, pad it, and join into 32bit blocks + msg = utils.toArray(msg, enc); + if (!this.pending) + this.pending = msg; + else + this.pending = this.pending.concat(msg); + this.pendingTotal += msg.length; + + // Enough data, try updating + if (this.pending.length >= this._delta8) { + msg = this.pending; + + // Process pending data in blocks + var r = msg.length % this._delta8; + this.pending = msg.slice(msg.length - r, msg.length); + if (this.pending.length === 0) + this.pending = null; + + msg = utils.join32(msg, 0, msg.length - r, this.endian); + for (var i = 0; i < msg.length; i += this._delta32) + this._update(msg, i, i + this._delta32); + } + + return this; + }; + + BlockHash.prototype.digest = function digest(enc) { + this.update(this._pad()); + assert(this.pending === null); + + return this._digest(enc); + }; + + BlockHash.prototype._pad = function pad() { + var len = this.pendingTotal; + var bytes = this._delta8; + var k = bytes - ((len + this.padLength) % bytes); + var res = new Array(k + this.padLength); + res[0] = 0x80; + for (var i = 1; i < k; i++) + res[i] = 0; + + // Append length + len <<= 3; + if (this.endian === 'big') { + for (var t = 8; t < this.padLength; t++) + res[i++] = 0; + + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = (len >>> 24) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = len & 0xff; + } else { + res[i++] = len & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 24) & 0xff; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + + for (t = 8; t < this.padLength; t++) + res[i++] = 0; + } + + return res; + }; + + },{"./utils":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); + this.Hash = hash; + this.blockSize = hash.blockSize / 8; + this.outSize = hash.outSize / 8; + this.inner = null; + this.outer = null; + + this._init(utils.toArray(key, enc)); + } + module.exports = Hmac; + + Hmac.prototype._init = function init(key) { + // Shorten key, if needed + if (key.length > this.blockSize) + key = new this.Hash().update(key).digest(); + assert(key.length <= this.blockSize); + + // Add padding to key + for (var i = key.length; i < this.blockSize; i++) + key.push(0); + + for (i = 0; i < key.length; i++) + key[i] ^= 0x36; + this.inner = new this.Hash().update(key); + + // 0x36 ^ 0x5c = 0x6a + for (i = 0; i < key.length; i++) + key[i] ^= 0x6a; + this.outer = new this.Hash().update(key); + }; + + Hmac.prototype.update = function update(msg, enc) { + this.inner.update(msg, enc); + return this; + }; + + Hmac.prototype.digest = function digest(enc) { + this.outer.update(this.inner.digest()); + return this.outer.digest(enc); + }; + + },{"./utils":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]; + var C = this.h[2]; + var D = this.h[3]; + var E = this.h[4]; + var Ah = A; + var Bh = B; + var Ch = C; + var Dh = D; + var Eh = E; + for (var j = 0; j < 80; j++) { + var T = sum32( + rotl32( + sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), + s[j]), + E); + A = E; + E = D; + D = rotl32(C, 10); + C = B; + B = T; + T = sum32( + rotl32( + sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), + sh[j]), + Eh); + Ah = Eh; + Eh = Dh; + Dh = rotl32(Ch, 10); + Ch = Bh; + Bh = T; + } + T = sum32_3(this.h[1], C, Dh); + this.h[1] = sum32_3(this.h[2], D, Eh); + this.h[2] = sum32_3(this.h[3], E, Ah); + this.h[3] = sum32_3(this.h[4], A, Bh); + this.h[4] = sum32_3(this.h[0], B, Ch); + this.h[0] = T; + }; + + RIPEMD160.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'little'); + else + return utils.split32(this.h, 'little'); + }; + + function f(j, x, y, z) { + if (j <= 15) + return x ^ y ^ z; + else if (j <= 31) + return (x & y) | ((~x) & z); + else if (j <= 47) + return (x | (~y)) ^ z; + else if (j <= 63) + return (x & z) | (y & (~z)); + else + return x ^ (y | (~z)); + } + + function K(j) { + if (j <= 15) + return 0x00000000; + else if (j <= 31) + return 0x5a827999; + else if (j <= 47) + return 0x6ed9eba1; + else if (j <= 63) + return 0x8f1bbcdc; + else + return 0xa953fd4e; + } + + function Kh(j) { + if (j <= 15) + return 0x50a28be6; + else if (j <= 31) + return 0x5c4dd124; + else if (j <= 47) + return 0x6d703ef3; + else if (j <= 63) + return 0x7a6d76e9; + else + return 0x00000000; + } + + var r = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 + ]; + + var rh = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 + ]; + + var s = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 + ]; + + var sh = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 + ]; + + },{"./common":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]); + e = d; + d = c; + c = rotl32(b, 30); + b = a; + a = t; + } + + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); + }; + + SHA1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); + }; + + },{"../common":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, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; + } + utils.inherits(SHA224, SHA256); + module.exports = SHA224; + + SHA224.blockSize = 512; + SHA224.outSize = 224; + SHA224.hmacStrength = 192; + SHA224.padLength = 64; + + SHA224.prototype._digest = function digest(enc) { + // Just truncate output + if (enc === 'hex') + return utils.toHex32(this.h.slice(0, 7), 'big'); + else + return utils.split32(this.h.slice(0, 7), 'big'); + }; + + + },{"../utils":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; + var ch32 = shaCommon.ch32; + var maj32 = shaCommon.maj32; + var s0_256 = shaCommon.s0_256; + var s1_256 = shaCommon.s1_256; + var g0_256 = shaCommon.g0_256; + var g1_256 = shaCommon.g1_256; + + var BlockHash = common.BlockHash; + + var sha256_K = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, + 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, + 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, + 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, + 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, + 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 + ]; + + function SHA256() { + if (!(this instanceof SHA256)) + return new SHA256(); + + BlockHash.call(this); + this.h = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + ]; + this.k = sha256_K; + this.W = new Array(64); + } + utils.inherits(SHA256, BlockHash); + module.exports = SHA256; + + SHA256.blockSize = 512; + SHA256.outSize = 256; + SHA256.hmacStrength = 192; + SHA256.padLength = 64; + + SHA256.prototype._update = function _update(msg, start) { + var W = this.W; + + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + for (; i < W.length; i++) + W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); + + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + var f = this.h[5]; + var g = this.h[6]; + var h = this.h[7]; + + assert(this.k.length === W.length); + for (i = 0; i < W.length; i++) { + var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]); + var T2 = sum32(s0_256(a), maj32(a, b, c)); + h = g; + g = f; + f = e; + e = sum32(d, T1); + d = c; + c = b; + b = a; + a = sum32(T1, T2); + } + + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); + this.h[5] = sum32(this.h[5], f); + this.h[6] = sum32(this.h[6], g); + this.h[7] = sum32(this.h[7], h); + }; + + SHA256.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); + }; + + },{"../common":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, + 0x629a292a, 0x367cd507, + 0x9159015a, 0x3070dd17, + 0x152fecd8, 0xf70e5939, + 0x67332667, 0xffc00b31, + 0x8eb44a87, 0x68581511, + 0xdb0c2e0d, 0x64f98fa7, + 0x47b5481d, 0xbefa4fa4 ]; + } + utils.inherits(SHA384, SHA512); + module.exports = SHA384; + + SHA384.blockSize = 1024; + SHA384.outSize = 384; + SHA384.hmacStrength = 192; + SHA384.padLength = 128; + + SHA384.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h.slice(0, 12), 'big'); + else + return utils.split32(this.h.slice(0, 12), 'big'); + }; + + },{"../utils":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; + var shr64_lo = utils.shr64_lo; + var sum64 = utils.sum64; + var sum64_hi = utils.sum64_hi; + var sum64_lo = utils.sum64_lo; + var sum64_4_hi = utils.sum64_4_hi; + var sum64_4_lo = utils.sum64_4_lo; + var sum64_5_hi = utils.sum64_5_hi; + var sum64_5_lo = utils.sum64_5_lo; + + var BlockHash = common.BlockHash; + + var sha512_K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 + ]; + + function SHA512() { + if (!(this instanceof SHA512)) + return new SHA512(); + + BlockHash.call(this); + this.h = [ + 0x6a09e667, 0xf3bcc908, + 0xbb67ae85, 0x84caa73b, + 0x3c6ef372, 0xfe94f82b, + 0xa54ff53a, 0x5f1d36f1, + 0x510e527f, 0xade682d1, + 0x9b05688c, 0x2b3e6c1f, + 0x1f83d9ab, 0xfb41bd6b, + 0x5be0cd19, 0x137e2179 ]; + this.k = sha512_K; + this.W = new Array(160); + } + utils.inherits(SHA512, BlockHash); + module.exports = SHA512; + + SHA512.blockSize = 1024; + SHA512.outSize = 512; + SHA512.hmacStrength = 192; + SHA512.padLength = 128; + + SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { + var W = this.W; + + // 32 x 32bit words + for (var i = 0; i < 32; i++) + W[i] = msg[start + i]; + for (; i < W.length; i += 2) { + var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2 + var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); + var c1_hi = W[i - 14]; // i - 7 + var c1_lo = W[i - 13]; + var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 + var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); + var c3_hi = W[i - 32]; // i - 16 + var c3_lo = W[i - 31]; + + W[i] = sum64_4_hi( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo); + W[i + 1] = sum64_4_lo( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo); + } + }; + + SHA512.prototype._update = function _update(msg, start) { + this._prepareBlock(msg, start); + + var W = this.W; + + var ah = this.h[0]; + var al = this.h[1]; + var bh = this.h[2]; + var bl = this.h[3]; + var ch = this.h[4]; + var cl = this.h[5]; + var dh = this.h[6]; + var dl = this.h[7]; + var eh = this.h[8]; + var el = this.h[9]; + var fh = this.h[10]; + var fl = this.h[11]; + var gh = this.h[12]; + var gl = this.h[13]; + var hh = this.h[14]; + var hl = this.h[15]; + + assert(this.k.length === W.length); + for (var i = 0; i < W.length; i += 2) { + var c0_hi = hh; + var c0_lo = hl; + var c1_hi = s1_512_hi(eh, el); + var c1_lo = s1_512_lo(eh, el); + var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl); + var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); + var c3_hi = this.k[i]; + var c3_lo = this.k[i + 1]; + var c4_hi = W[i]; + var c4_lo = W[i + 1]; + + var T1_hi = sum64_5_hi( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo, + c4_hi, c4_lo); + var T1_lo = sum64_5_lo( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo, + c4_hi, c4_lo); + + c0_hi = s0_512_hi(ah, al); + c0_lo = s0_512_lo(ah, al); + c1_hi = maj64_hi(ah, al, bh, bl, ch, cl); + c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); + + var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo); + var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo); + + hh = gh; + hl = gl; + + gh = fh; + gl = fl; + + fh = eh; + fl = el; + + eh = sum64_hi(dh, dl, T1_hi, T1_lo); + el = sum64_lo(dl, dl, T1_hi, T1_lo); + + dh = ch; + dl = cl; + + ch = bh; + cl = bl; + + bh = ah; + bl = al; + + ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); + al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); + } + + sum64(this.h, 0, ah, al); + sum64(this.h, 2, bh, bl); + sum64(this.h, 4, ch, cl); + sum64(this.h, 6, dh, dl); + sum64(this.h, 8, eh, el); + sum64(this.h, 10, fh, fl); + sum64(this.h, 12, gh, gl); + sum64(this.h, 14, hh, hl); + }; + + SHA512.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); + }; + + function ch64_hi(xh, xl, yh, yl, zh) { + var r = (xh & yh) ^ ((~xh) & zh); + if (r < 0) + r += 0x100000000; + return r; + } + + function ch64_lo(xh, xl, yh, yl, zh, zl) { + var r = (xl & yl) ^ ((~xl) & zl); + if (r < 0) + r += 0x100000000; + return r; + } + + function maj64_hi(xh, xl, yh, yl, zh) { + var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); + if (r < 0) + r += 0x100000000; + return r; + } + + function maj64_lo(xh, xl, yh, yl, zh, zl) { + var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); + if (r < 0) + r += 0x100000000; + return r; + } + + function s0_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 28); + var c1_hi = rotr64_hi(xl, xh, 2); // 34 + var c2_hi = rotr64_hi(xl, xh, 7); // 39 + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; + } + + function s0_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 28); + var c1_lo = rotr64_lo(xl, xh, 2); // 34 + var c2_lo = rotr64_lo(xl, xh, 7); // 39 + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; + } + + function s1_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 14); + var c1_hi = rotr64_hi(xh, xl, 18); + var c2_hi = rotr64_hi(xl, xh, 9); // 41 + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; + } + + function s1_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 14); + var c1_lo = rotr64_lo(xh, xl, 18); + var c2_lo = rotr64_lo(xl, xh, 9); // 41 + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; + } + + function g0_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 1); + var c1_hi = rotr64_hi(xh, xl, 8); + var c2_hi = shr64_hi(xh, xl, 7); + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; + } + + function g0_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 1); + var c1_lo = rotr64_lo(xh, xl, 8); + var c2_lo = shr64_lo(xh, xl, 7); + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; + } + + function g1_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 19); + var c1_hi = rotr64_hi(xl, xh, 29); // 61 + var c2_hi = shr64_hi(xh, xl, 6); + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; + } + + function g1_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 19); + var c1_lo = rotr64_lo(xl, xh, 29); // 61 + var c2_lo = shr64_lo(xh, xl, 6); + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; + } + + },{"../common":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); + if (s === 1 || s === 3) + return p32(x, y, z); + if (s === 2) + return maj32(x, y, z); + } + exports.ft_1 = ft_1; + + function ch32(x, y, z) { + return (x & y) ^ ((~x) & z); + } + exports.ch32 = ch32; + + function maj32(x, y, z) { + return (x & y) ^ (x & z) ^ (y & z); + } + exports.maj32 = maj32; + + function p32(x, y, z) { + return x ^ y ^ z; + } + exports.p32 = p32; + + function s0_256(x) { + return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); + } + exports.s0_256 = s0_256; + + function s1_256(x) { + return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); + } + exports.s1_256 = s1_256; + + function g0_256(x) { + return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); + } + exports.g0_256 = g0_256; + + function g1_256(x) { + return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); + } + exports.g1_256 = g1_256; + + },{"../utils":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(); + if (!msg) + return []; + var res = []; + if (typeof msg === 'string') { + if (!enc) { + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + var hi = c >> 8; + var lo = c & 0xff; + if (hi) + res.push(hi, lo); + else + res.push(lo); + } + } else if (enc === 'hex') { + msg = msg.replace(/[^a-z0-9]+/ig, ''); + if (msg.length % 2 !== 0) + msg = '0' + msg; + for (i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } + } else { + for (i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + } + return res; + } + exports.toArray = toArray; + + function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; + } + exports.toHex = toHex; + + function htonl(w) { + var res = (w >>> 24) | + ((w >>> 8) & 0xff00) | + ((w << 8) & 0xff0000) | + ((w & 0xff) << 24); + return res >>> 0; + } + exports.htonl = htonl; + + function toHex32(msg, endian) { + var res = ''; + for (var i = 0; i < msg.length; i++) { + var w = msg[i]; + if (endian === 'little') + w = htonl(w); + res += zero8(w.toString(16)); + } + return res; + } + exports.toHex32 = toHex32; + + function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; + } + exports.zero2 = zero2; + + function zero8(word) { + if (word.length === 7) + return '0' + word; + else if (word.length === 6) + return '00' + word; + else if (word.length === 5) + return '000' + word; + else if (word.length === 4) + return '0000' + word; + else if (word.length === 3) + return '00000' + word; + else if (word.length === 2) + return '000000' + word; + else if (word.length === 1) + return '0000000' + word; + else + return word; + } + exports.zero8 = zero8; + + function join32(msg, start, end, endian) { + var len = end - start; + assert(len % 4 === 0); + var res = new Array(len / 4); + for (var i = 0, k = start; i < res.length; i++, k += 4) { + var w; + if (endian === 'big') + w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; + else + w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; + res[i] = w >>> 0; + } + return res; + } + exports.join32 = join32; + + function split32(msg, endian) { + var res = new Array(msg.length * 4); + for (var i = 0, k = 0; i < msg.length; i++, k += 4) { + var m = msg[i]; + if (endian === 'big') { + res[k] = m >>> 24; + res[k + 1] = (m >>> 16) & 0xff; + res[k + 2] = (m >>> 8) & 0xff; + res[k + 3] = m & 0xff; + } else { + res[k + 3] = m >>> 24; + res[k + 2] = (m >>> 16) & 0xff; + res[k + 1] = (m >>> 8) & 0xff; + res[k] = m & 0xff; + } + } + return res; + } + exports.split32 = split32; + + function rotr32(w, b) { + return (w >>> b) | (w << (32 - b)); + } + exports.rotr32 = rotr32; + + function rotl32(w, b) { + return (w << b) | (w >>> (32 - b)); + } + exports.rotl32 = rotl32; + + function sum32(a, b) { + return (a + b) >>> 0; + } + exports.sum32 = sum32; + + function sum32_3(a, b, c) { + return (a + b + c) >>> 0; + } + exports.sum32_3 = sum32_3; + + function sum32_4(a, b, c, d) { + return (a + b + c + d) >>> 0; + } + exports.sum32_4 = sum32_4; + + function sum32_5(a, b, c, d, e) { + return (a + b + c + d + e) >>> 0; + } + exports.sum32_5 = sum32_5; + + function sum64(buf, pos, ah, al) { + var bh = buf[pos]; + var bl = buf[pos + 1]; + + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + buf[pos] = hi >>> 0; + buf[pos + 1] = lo; + } + exports.sum64 = sum64; + + function sum64_hi(ah, al, bh, bl) { + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + return hi >>> 0; + } + exports.sum64_hi = sum64_hi; + + function sum64_lo(ah, al, bh, bl) { + var lo = al + bl; + return lo >>> 0; + } + exports.sum64_lo = sum64_lo; + + function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { + var carry = 0; + var lo = al; + lo = (lo + bl) >>> 0; + carry += lo < al ? 1 : 0; + lo = (lo + cl) >>> 0; + carry += lo < cl ? 1 : 0; + lo = (lo + dl) >>> 0; + carry += lo < dl ? 1 : 0; + + var hi = ah + bh + ch + dh + carry; + return hi >>> 0; + } + exports.sum64_4_hi = sum64_4_hi; + + function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { + var lo = al + bl + cl + dl; + return lo >>> 0; + } + exports.sum64_4_lo = sum64_4_lo; + + function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var carry = 0; + var lo = al; + lo = (lo + bl) >>> 0; + carry += lo < al ? 1 : 0; + lo = (lo + cl) >>> 0; + carry += lo < cl ? 1 : 0; + lo = (lo + dl) >>> 0; + carry += lo < dl ? 1 : 0; + lo = (lo + el) >>> 0; + carry += lo < el ? 1 : 0; + + var hi = ah + bh + ch + dh + eh + carry; + return hi >>> 0; + } + exports.sum64_5_hi = sum64_5_hi; + + function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var lo = al + bl + cl + dl + el; + + return lo >>> 0; + } + exports.sum64_5_lo = sum64_5_lo; + + function rotr64_hi(ah, al, num) { + var r = (al << (32 - num)) | (ah >>> num); + return r >>> 0; + } + exports.rotr64_hi = rotr64_hi; + + function rotr64_lo(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; + } + exports.rotr64_lo = rotr64_lo; + + function shr64_hi(ah, al, num) { + return ah >>> num; + } + exports.shr64_hi = shr64_hi; + + function shr64_lo(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; + } + exports.shr64_lo = shr64_lo; + + },{"inherits":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'); + assert(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + this._init(entropy, nonce, pers); + } + module.exports = HmacDRBG; + + HmacDRBG.prototype._init = function init(entropy, nonce, pers) { + var seed = entropy.concat(nonce).concat(pers); + + this.K = new Array(this.outLen / 8); + this.V = new Array(this.outLen / 8); + for (var i = 0; i < this.V.length; i++) { + this.K[i] = 0x00; + this.V[i] = 0x01; + } + + this._update(seed); + this._reseed = 1; + this.reseedInterval = 0x1000000000000; // 2^48 + }; + + HmacDRBG.prototype._hmac = function hmac() { + return new hash.hmac(this.hash, this.K); + }; + + HmacDRBG.prototype._update = function update(seed) { + var kmac = this._hmac() + .update(this.V) + .update([ 0x00 ]); + if (seed) + kmac = kmac.update(seed); + this.K = kmac.digest(); + this.V = this._hmac().update(this.V).digest(); + if (!seed) + return; + + this.K = this._hmac() + .update(this.V) + .update([ 0x01 ]) + .update(seed) + .digest(); + this.V = this._hmac().update(this.V).digest(); + }; + + HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { + // Optional entropy enc + if (typeof entropyEnc !== 'string') { + addEnc = add; + add = entropyEnc; + entropyEnc = null; + } + + entropy = utils.toArray(entropy, entropyEnc); + add = utils.toArray(add, addEnc); + + assert(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + + this._update(entropy.concat(add || [])); + this._reseed = 1; + }; + + HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { + if (this._reseed > this.reseedInterval) + throw new Error('Reseed is required'); + + // Optional encoding + if (typeof enc !== 'string') { + addEnc = add; + add = enc; + enc = null; + } + + // Optional additional data + if (add) { + add = utils.toArray(add, addEnc || 'hex'); + this._update(add); + } + + var temp = []; + while (temp.length < len) { + this.V = this._hmac().update(this.V).digest(); + temp = temp.concat(this.V); + } + + var res = temp.slice(0, len); + this._update(add); + this._reseed++; + return utils.encode(res, enc); + }; + + },{"hash.js":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) + } + if (!params.protocol) { + params.protocol = 'https:' + } + if (params.protocol !== 'https:') { + throw new Error('Protocol "' + params.protocol + '" not supported. Expected "https:"') + } + 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) { + define([], function () { return factory(); }); + } else if (typeof exports === 'object') { + module.exports = factory(); + } else { + root.uts46_map = factory(); + } + }(this, function () { + var blocks = [ + new Uint32Array([2157250,2157314,2157378,2157442,2157506,2157570,2157634,0,2157698,2157762,2157826,2157890,2157954,0,2158018,0]), + new Uint32Array([2179041,6291456,2179073,6291456,2179105,6291456,2179137,6291456,2179169,6291456,2179201,6291456,2179233,6291456,2179265,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,14680064,14680064,14680064,14680064,14680064]), + new Uint32Array([0,2113729,2197345,2197377,2113825,2197409,2197441,2113921,2197473,2114017,2197505,2197537,2197569,2197601,2197633,2197665]), + new Uint32Array([6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,23068672,23068672,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,0,23068672,23068672,23068672,0,0,0,0,23068672]), + new Uint32Array([14680064,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,14680064,14680064]), + new Uint32Array([2196001,2196033,2196065,2196097,2196129,2196161,2196193,2196225,2196257,2196289,2196321,2196353,2196385,2196417,2196449,2196481]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,6291456,0,0,0,0,0]), + new Uint32Array([2097281,2105921,2097729,2106081,0,2097601,2162337,2106017,2133281,2097505,2105889,2097185,2097697,2135777,2097633,2097441]), + new Uint32Array([2177025,6291456,2177057,6291456,2177089,6291456,2177121,6291456,2177153,6291456,2177185,6291456,2177217,6291456,2177249,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,0,6291456,6291456,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456]), + new Uint32Array([0,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,6291456]), + new Uint32Array([2134435,2134531,2134627,2134723,2134723,2134819,2134819,2134915,2134915,2135011,2105987,2135107,2135203,2135299,2131587,2135395]), + new Uint32Array([0,0,0,0,0,0,0,6291456,2168673,2169249,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2147906,2147970,2148034,2148098,2148162,2148226,2148290,2148354,2147906,2147970,2148034,2148098,2148162,2148226,2148290,2148354]), + new Uint32Array([2125219,2125315,2152834,2152898,2125411,2152962,2153026,2125506,2125507,2125603,2153090,2153154,2153218,2153282,2153346,2105348]), + new Uint32Array([2203393,6291456,2203425,6291456,2203457,6291456,2203489,6291456,6291456,6291456,6291456,2203521,6291456,2181281,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,23068672,6291456,2145538,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,6291456]), + new Uint32Array([2139426,2160834,2160898,2160962,2134242,2161026,2161090,2161154,2161218,2161282,2161346,2161410,2138658,2161474,2161538,2134722]), + new Uint32Array([2119939,2124930,2125026,2106658,2125218,2128962,2129058,2129154,2129250,2129346,2129442,2108866,2108770,2150466,2150530,2150594]), + new Uint32Array([2201601,6291456,2201633,6291456,2201665,6291456,2201697,6291456,2201729,6291456,2201761,6291456,2201793,6291456,2201825,6291456]), + new Uint32Array([2193537,2193569,2193601,2193633,2193665,2193697,2193729,2193761,2193793,2193825,2193857,2193889,2193921,2193953,2193985,2194017]), + new Uint32Array([6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([0,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2190561,6291456,2190593,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2190625,6291456,2190657,6291456,23068672]), + new Uint32Array([2215905,2215937,2215969,2216001,2216033,2216065,2216097,2216129,2216161,2216193,2216225,2216257,2105441,2216289,2216321,2216353]), + new Uint32Array([23068672,18884130,23068672,23068672,23068672,6291456,23068672,23068672,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672]), + new Uint32Array([23068672,23068672,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,6291456,23068672,23068672,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2191233,2191265,2191297,2191329,2191361,2191393,2191425,2117377,2191457,2191489,2191521,2191553,2191585,2191617,2191649,2117953]), + new Uint32Array([2132227,2132323,2132419,2132419,2132515,2132515,2132611,2132707,2132707,2132803,2132899,2132899,2132995,2132995,2133091,2133187]), + new Uint32Array([0,0,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,6291456,0,0]), + new Uint32Array([2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,10609889,10610785,10609921,10610817,2222241]), + new Uint32Array([6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,0,0]), + new Uint32Array([2219969,2157121,2157441,2157505,2157889,2157953,2220001,2158465,2158529,10575617,2156994,2157058,2129923,2130019,2157122,2157186]), + new Uint32Array([6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0]), + new Uint32Array([2185249,6291456,2185281,6291456,2185313,6291456,2185345,6291456,2185377,6291456,2185409,6291456,2185441,6291456,2185473,6291456]), + new Uint32Array([0,0,0,0,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,0,23068672,23068672,0,0,23068672,23068672,23068672,6291456,0]), + new Uint32Array([2183361,6291456,2183393,6291456,2183425,6291456,2183457,6291456,2183489,6291456,2183521,6291456,2183553,6291456,2183585,6291456]), + new Uint32Array([2192161,2192193,2192225,2192257,2192289,2192321,2192353,2192385,2192417,2192449,2192481,2192513,2192545,2192577,2192609,2192641]), + new Uint32Array([2212001,2212033,2212065,2212097,2212129,2212161,2212193,2212225,2212257,2212289,2212321,2212353,2212385,2212417,2212449,2207265]), + new Uint32Array([2249825,2249857,2249889,2249921,2249954,2250018,2250082,2250145,2250177,2250209,2250241,2250274,2250337,2250370,2250433,2250465]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2147905,2147969,2148033,2148097,2148161,2148225,2148289,2148353]), + new Uint32Array([10485857,6291456,2197217,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,23068672,23068672]), + new Uint32Array([0,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456]), + new Uint32Array([2180353,2180385,2144033,2180417,2180449,2180481,2180513,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,10610209,10610465,10610241,10610753,10609857]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,0,0]), + new Uint32Array([2223842,2223906,2223970,2224034,2224098,2224162,2224226,2224290,2224354,2224418,2224482,2224546,2224610,2224674,2224738,2224802]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,6291456,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456]), + new Uint32Array([23068672,23068672,23068672,18923650,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,18923714,23068672,23068672]), + new Uint32Array([2126179,2125538,2126275,2126371,2126467,2125634,2126563,2105603,2105604,2125346,2126659,2126755,2126851,2098179,2098181,2098182]), + new Uint32Array([2227426,2227490,2227554,2227618,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2192353,2240642,2240642,2240705,2240737,2240737,2240769,2240802,2240866,2240929,2240961,2240993,2241025,2241057,2241089,2241121]), + new Uint32Array([6291456,2170881,2170913,2170945,6291456,2170977,6291456,2171009,2171041,6291456,6291456,6291456,2171073,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2132226,2132514,2163586,2132610,2160386,2133090,2133186,2160450,2160514,2160578,2133570,2106178,2160642,2133858,2160706,2160770]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,10532162,10532226,10532290,10532354,10532418,10532482,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,23068672]), + new Uint32Array([2098209,2108353,2108193,2108481,2170241,2111713,2105473,2105569,2105601,2112289,2112481,2098305,2108321,0,0,0]), + new Uint32Array([2209121,2209153,2209185,2209217,2209249,2209281,2209313,2209345,2209377,2209409,2209441,2209473,2207265,2209505,2209537,2209569]), + new Uint32Array([2189025,6291456,2189057,6291456,2189089,6291456,2189121,6291456,2189153,6291456,2189185,6291456,2189217,6291456,2189249,6291456]), + new Uint32Array([2173825,2153473,2173857,2173889,2173921,2173953,2173985,2173761,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233057]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2165764,2140004]), + new Uint32Array([2215105,6291456,2215137,6291456,6291456,2215169,2215201,6291456,6291456,6291456,2215233,2215265,2215297,2215329,2215361,2215393]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,6291456,6291456,6291456,23068672,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([10505091,10505187,10505283,10505379,10505475,10505571,10505667,10505763,10505859,10505955,10506051,10506147,10506243,10506339,10506435,10506531]), + new Uint32Array([2229730,2229794,2229858,2229922,2229986,2230050,2230114,2230178,2230242,2230306,2230370,2230434,2230498,2230562,2230626,2230690]), + new Uint32Array([2105505,2098241,2108353,2108417,2105825,0,2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177]), + new Uint32Array([6291456,6291456,6291456,6291456,10502115,10502178,10502211,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([0,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456]), + new Uint32Array([2190305,6291456,2190337,6291456,2190369,6291456,2190401,6291456,2190433,6291456,2190465,6291456,2190497,6291456,2190529,6291456]), + new Uint32Array([2173793,2173985,2174017,6291456,2173761,2173697,6291456,2174689,6291456,2174017,2174721,6291456,6291456,2174753,2174785,2174817]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2099521,2099105,2120705,2098369,2120801,2103361,2097985,2098433,2121377,2121473,2099169,2099873,2098401,2099393,2152609,2100033]), + new Uint32Array([2132898,2163842,2163906,2133282,2132034,2131938,2137410,2132802,2132706,2164866,2133282,2160578,2165186,2165186,6291456,6291456]), + new Uint32Array([10500003,10500099,10500195,10500291,10500387,10500483,10500579,10500675,10500771,10500867,10500963,10501059,10501155,10501251,10501347,10501443]), + new Uint32Array([2163458,2130978,2131074,2131266,2131362,2163522,2160130,2132066,2131010,2131106,2106018,2131618,2131298,2132034,2131938,2137410]), + new Uint32Array([2212961,2116993,2212993,2213025,2213057,2213089,2213121,2213153,2213185,2213217,2213249,2209633,2213281,2213313,2213345,2213377]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456]), + new Uint32Array([2113729,2113825,2113921,2114017,2114113,2114209,2114305,2114401,2114497,2114593,2114689,2114785,2114881,2114977,2115073,2115169]), + new Uint32Array([2238177,2238209,2238241,2238273,2238305,2238337,2238337,2217537,2238369,2238401,2238433,2238465,2215649,2238497,2238529,2238561]), + new Uint32Array([2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905]), + new Uint32Array([6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,0,0]), + new Uint32Array([6291456,0,6291456,2145026,0,6291456,2145090,0,6291456,6291456,0,0,23068672,0,23068672,23068672]), + new Uint32Array([2099233,2122017,2200673,2098113,2121537,2103201,2200705,2104033,2121857,2121953,2122401,2099649,2099969,2123009,2100129,2100289]), + new Uint32Array([6291456,23068672,6291456,0,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,23068672,23068672,0,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0]), + new Uint32Array([2187681,2187713,2187745,2187777,2187809,2187841,2187873,2187905,2187937,2187969,2188001,2188033,2188065,2188097,2188129,2188161]), + new Uint32Array([0,10554498,10554562,10554626,10554690,10554754,10554818,10554882,10554946,10555010,10555074,6291456,6291456,0,0,0]), + new Uint32Array([2235170,2235234,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0]), + new Uint32Array([2181153,6291456,2188897,6291456,6291456,2188929,6291456,6291456,6291456,6291456,6291456,6291456,2111905,2100865,2188961,2188993]), + new Uint32Array([2100833,2100897,0,0,2101569,2101697,2101825,2101953,2102081,2102209,10575617,2187041,10502177,10489601,10489697,2112289]), + new Uint32Array([6291456,2172833,6291456,2172865,2172897,2172929,2172961,6291456,2172993,6291456,2173025,6291456,2173057,6291456,2173089,6291456]), + new Uint32Array([6291456,0,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,0,0,23068672,6291456,23068672,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,2190721]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,23068672,6291456,6291456]), + new Uint32Array([2184993,6291456,2185025,6291456,2185057,6291456,2185089,6291456,2185121,6291456,2185153,6291456,2185185,6291456,2185217,6291456]), + new Uint32Array([2115265,2115361,2115457,2115553,2115649,2115745,2115841,2115937,2116033,2116129,2116225,2116321,2150658,2150722,2200225,6291456]), + new Uint32Array([2168321,6291456,2168353,6291456,2168385,6291456,2168417,6291456,2168449,6291456,2168481,6291456,2168513,6291456,2168545,6291456]), + new Uint32Array([23068672,23068672,23068672,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,0,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456,0,6291456,0,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,2186625,0,0,6291456,6291456,2186657,2186689,2186721,2173505,0,10496067,10496163,10496259]), + new Uint32Array([2178785,6291456,2178817,6291456,2178849,6291456,2178881,6291456,2178913,6291456,2178945,6291456,2178977,6291456,2179009,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0]), + new Uint32Array([2097152,0,0,0,2097152,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456]), + new Uint32Array([6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([0,0,2197857,2197889,2197921,2197953,2197985,2198017,0,0,2198049,2198081,2198113,2198145,2198177,2198209]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2098209,2167297,2111137,6291456]), + new Uint32Array([2171393,6291456,2171425,6291456,2171457,6291456,2171489,6291456,2171521,6291456,2171553,6291456,2171585,6291456,2171617,6291456]), + new Uint32Array([2206753,2206785,2195457,2206817,2206849,2206881,2206913,2197153,2197153,2206945,2117857,2206977,2207009,2207041,2207073,2207105]), + new Uint32Array([0,0,0,0,0,0,0,23068672,0,0,0,0,2144834,2144898,0,2144962]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,23068672]), + new Uint32Array([2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,0,2105505,2098241]), + new Uint32Array([6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,2202049,6291456,2202081,6291456,2202113,6291456,2202145,6291456,2202177,6291456,2202209,6291456,2202241,6291456]), + new Uint32Array([10501155,10501251,10501347,10501443,10501539,10501635,10501731,10501827,10501923,10502019,2141731,2105505,2098177,2155586,2166530,0]), + new Uint32Array([2102081,2102209,2100833,2100737,2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209,2100833,2100737,2098337,2101441]), + new Uint32Array([2146882,2146946,2147010,2147074,2147138,2147202,2147266,2147330,2146882,2146946,2147010,2147074,2147138,2147202,2147266,2147330]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0]), + new Uint32Array([10502307,10502403,10502499,10502595,10502691,10502787,10502883,10502979,10503075,10503171,10503267,10503363,10503459,10503555,10503651,10503747]), + new Uint32Array([2179937,2179969,2180001,2180033,2156545,2180065,2156577,2180097,2180129,2180161,2180193,2180225,2180257,2180289,2156737,2180321]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,0,0,0,6291456,0,0,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0]), + new Uint32Array([2227682,2227746,2227810,2227874,2227938,2228002,2228066,2228130,2228194,2228258,2228322,2228386,2228450,2228514,2228578,2228642]), + new Uint32Array([2105601,2169121,2108193,2170049,2181025,2181057,2112481,2108321,2108289,2181089,2170497,2100865,2181121,2173601,2173633,2173665]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2180641,6291456,6291456,6291456]), + new Uint32Array([0,6291456,6291456,6291456,0,6291456,0,6291456,0,0,6291456,6291456,0,6291456,6291456,6291456]), + new Uint32Array([2178273,6291456,2178305,6291456,2178337,6291456,2178369,6291456,2178401,6291456,2178433,6291456,2178465,6291456,2178497,6291456]), + new Uint32Array([6291456,6291456,23068672,23068672,23068672,6291456,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,14680064,14680064,14680064,14680064,14680064,14680064]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456]), + new Uint32Array([2237377,2237409,2236225,2237441,2237473,2217441,2215521,2215553,2217473,2237505,2237537,2209697,2237569,2215585,2237601,2237633]), + new Uint32Array([2221985,2165601,2165601,2165665,2165665,2222017,2222017,2165729,2165729,2158913,2158913,2158913,2158913,2097281,2097281,2105921]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2149634,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2176897,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,2176929,6291456,2176961,6291456,2176993,6291456]), + new Uint32Array([2172641,6291456,2172673,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2172705,2172737,6291456,2172769,2172801,6291456]), + new Uint32Array([2099173,2104196,2121667,2099395,2121763,2152258,2152322,2098946,2152386,2121859,2121955,2099333,2122051,2104324,2099493,2122147]), + new Uint32Array([6291456,6291456,6291456,2145794,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,2145858,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,0,0,6291456,0]), + new Uint32Array([0,2105921,2097729,0,2097377,0,0,2106017,0,2097505,2105889,2097185,2097697,2135777,2097633,2097441]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2239074,2239138,2239201,2239233,2239265,2239297,2239329,2239361,0,2239393,2239425,2239425,2239458,2239521,2239553,2209569]), + new Uint32Array([14680064,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,6291456,23068672]), + new Uint32Array([2108321,2108289,2113153,2098209,2180897,2180929,2180961,2111137,2098241,2108353,2170241,2170273,2180993,2105825,6291456,2105473]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2146114,6291456,6291456,6291456,0,0,0]), + new Uint32Array([2105921,2105921,2105921,2222049,2222049,2130977,2130977,2130977,2130977,2160065,2160065,2160065,2160065,2097729,2097729,2097729]), + new Uint32Array([2218145,2214785,2207937,2218177,2218209,2192993,2210113,2212769,2218241,2218273,2216129,2218305,2216161,2218337,2218369,2218401]), + new Uint32Array([0,0,0,2156546,2156610,2156674,2156738,2156802,0,0,0,0,0,2156866,23068672,2156930]), + new Uint32Array([23068672,23068672,23068672,0,0,0,0,23068672,23068672,0,0,23068672,23068672,23068672,0,0]), + new Uint32Array([2213409,2213441,2213473,2213505,2213537,2213569,2213601,2213633,2213665,2195681,2213697,2213729,2213761,2213793,2213825,2213857]), + new Uint32Array([2100033,2099233,2122017,2200673,2098113,2121537,2103201,2200705,2104033,2121857,2121953,2122401,2099649,2099969,2123009,2100129]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2201857,6291456,2201889,6291456,2201921,6291456,2201953,6291456,2201985,6291456,2202017,6291456,2176193,2176257,23068672,23068672]), + new Uint32Array([6291456,6291456,23068672,23068672,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2188193,2188225,2188257,2188289,2188321,2188353,2188385,2188417,2188449,2188481,2188513,2188545,2188577,2188609,2188641,0]), + new Uint32Array([10554529,2221089,0,10502113,10562017,10537921,10538049,2221121,2221153,0,0,0,0,0,0,0]), + new Uint32Array([2213889,2213921,2213953,2213985,2214017,2214049,2214081,2194177,2214113,2214145,2214177,2214209,2214241,2214273,2214305,2214337]), + new Uint32Array([2166978,2167042,2099169,0,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2180545,6291456,6291456,6291456]), + new Uint32Array([10518915,10519011,10519107,10519203,2162242,2162306,2159554,2162370,2159362,2159618,2105922,2162434,2159746,2162498,2159810,2159874]), + new Uint32Array([2161730,2161794,2135586,2161858,2161922,2137186,2131810,2160290,2135170,2161986,2137954,2162050,2162114,2162178,10518723,10518819]), + new Uint32Array([10506627,10506723,10506819,10506915,10507011,10507107,10507203,10507299,10507395,10507491,10507587,10507683,10507779,10507875,10507971,10508067]), + new Uint32Array([6291456,23068672,23068672,23068672,0,23068672,23068672,0,0,0,0,0,23068672,23068672,23068672,23068672]), + new Uint32Array([23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0]), + new Uint32Array([2175873,2175905,2175937,2175969,2176001,2176033,2176065,2176097,2176129,2176161,2176193,2176225,2176257,2176289,2176321,2176353]), + new Uint32Array([2140006,2140198,2140390,2140582,2140774,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,23068672,23068672,23068672]), + new Uint32Array([2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241]), + new Uint32Array([0,23068672,0,0,0,0,0,0,0,2145154,2145218,2145282,6291456,0,2145346,0]), + new Uint32Array([0,0,0,0,10531458,10495395,2148545,2143201,2173473,2148865,2173505,0,2173537,0,2173569,2149121]), + new Uint32Array([10537282,10495683,2148738,2148802,2148866,0,6291456,2148930,2186593,2173473,2148737,2148865,2148802,10495779,10495875,10495971]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2215425,2215457,2215489,2215521,2215553,2215585,2215617,2215649,2215681,2215713,2215745,2215777,2192033,2215809,2215841,2215873]), + new Uint32Array([2242049,2242081,2242113,2242145,2242177,2242209,2242241,2242273,2215937,2242305,2242338,2242401,2242433,2242465,2242497,2216001]), + new Uint32Array([10554529,2221089,0,0,10562017,10502113,10538049,10537921,2221185,10489601,10489697,10609889,10609921,2141729,2141793,10610273]), + new Uint32Array([2141923,2142019,2142115,2142211,2142307,2142403,2142499,2142595,2142691,0,0,0,0,0,0,0]), + new Uint32Array([0,2221185,2221217,10609857,10609857,10489601,10489697,10609889,10609921,2141729,2141793,2221345,2221377,2221409,2221441,2187105]), + new Uint32Array([6291456,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,18923970,23068672,23068672,23068672,0,6291456,6291456]), + new Uint32Array([2183105,6291456,2183137,6291456,2183169,6291456,2183201,6291456,2183233,6291456,2183265,6291456,2183297,6291456,2183329,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0]), + new Uint32Array([23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456]), + new Uint32Array([2134434,2134818,2097666,2097186,2097474,2097698,2105986,2131586,2132450,2131874,2131778,2135970,2135778,2161602,2136162,2161666]), + new Uint32Array([2236865,2236897,2236930,2236993,2237025,2235681,2237058,2237121,2237153,2237185,2237217,2217281,2237250,2191233,2237313,2237345]), + new Uint32Array([2190049,6291456,2190081,6291456,2190113,6291456,2190145,6291456,2190177,6291456,2190209,6291456,2190241,6291456,2190273,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2101922,2102050,2102178,2102306,10498755,10498851,10498947,10499043,10499139,10499235,10499331,10499427,10499523,10489604,10489732,10489860]), + new Uint32Array([2166914,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0]), + new Uint32Array([2181601,2170561,2181633,2181665,2170753,2181697,2172897,2170881,2181729,2170913,2172929,2113441,2181761,2181793,2171009,2173761]), + new Uint32Array([0,2105921,2097729,2106081,0,2097601,2162337,2106017,2133281,2097505,0,2097185,2097697,2135777,2097633,2097441]), + new Uint32Array([6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,0,0,0,0]), + new Uint32Array([2248001,2248033,2248066,2248130,2248193,2248226,2248289,2248322,2248385,2248417,2216673,2248450,2248514,2248577,2248610,2248673]), + new Uint32Array([6291456,6291456,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,0,0,0]), + new Uint32Array([2169729,6291456,2169761,6291456,2169793,6291456,2169825,6291456,2169857,2169889,6291456,2169921,6291456,2143329,6291456,2098305]), + new Uint32Array([2162178,2163202,2163266,2135170,2136226,2161986,2137954,2159426,2159490,2163330,2159554,2163394,2159682,2139522,2136450,2159746]), + new Uint32Array([2173953,2173985,0,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2174209,2174241,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,4271169,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2174273]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,6291456,0,0,0,0,0,0,0,6291456,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,2190785,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2189793,6291456,2189825,6291456,2189857,6291456,2189889,6291456,2189921,6291456,2189953,6291456,2189985,6291456,2190017,6291456]), + new Uint32Array([2105601,2112289,2108193,2112481,2112577,0,2098305,2108321,2108289,2100865,2113153,2108481,2113345,0,2098209,2111137]), + new Uint32Array([2172129,6291456,2172161,6291456,2172193,6291456,2172225,6291456,2172257,6291456,2172289,6291456,2172321,6291456,2172353,6291456]), + new Uint32Array([2214753,6291456,2214785,6291456,6291456,2214817,2214849,2214881,2214913,2214945,2214977,2215009,2215041,2215073,2194401,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,6291456,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([0,0,0,0,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([10610305,10610337,10575617,2221761,10610401,10610433,10502177,0,10610465,10610497,10610529,10610561,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,23068672,0,0,0,0,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2187105,2187137,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2199393,2199425,2199457,2199489,2199521,2199553,2199585,2199617,2199649,2199681,2199713,2199745,2199777,2199809,2199841,0]), + new Uint32Array([2217249,2217281,2217313,2217345,2217377,2217409,2217441,2217473,2215617,2217505,2217537,2217569,2214753,2217601,2217633,2217665]), + new Uint32Array([2170273,2170305,6291456,2170337,2170369,6291456,2170401,2170433,2170465,6291456,6291456,6291456,2170497,2170529,6291456,2170561]), + new Uint32Array([2188673,6291456,2188705,2188737,2188769,6291456,6291456,2188801,6291456,2188833,6291456,2188865,6291456,2180929,2181505,2180897]), + new Uint32Array([10489988,10490116,10490244,10490372,10490500,10490628,10490756,10490884,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2147393,2147457,2147521,2147585,2147649,2147713,2147777,2147841]), + new Uint32Array([23068672,23068672,0,23068672,23068672,0,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0]), + new Uint32Array([2241153,2241185,2241217,2215809,2241250,2241313,2241345,2241377,2217921,2241377,2241409,2215873,2241441,2241473,2241505,2241537]), + new Uint32Array([23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2220417,2220417,2220449,2220449,2220481,2220481,2220513,2220513,2220545,2220545,2220577,2220577,2220609,2220609,2220641,2220641]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,2144002,0,6291456,6291456,0,0,6291456,6291456,6291456]), + new Uint32Array([2167105,2167137,2167169,2167201,2167233,2167265,2167297,2167329,2167361,2167393,2167425,2167457,2167489,2167521,2167553,2167585]), + new Uint32Array([10575521,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193]), + new Uint32Array([2234146,2234210,2234274,2234338,2234402,2234466,2234530,2234594,2234658,2234722,2234786,2234850,2234914,2234978,2235042,2235106]), + new Uint32Array([0,0,0,0,0,0,0,2180577,0,0,0,0,0,2180609,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,0,0,6291456,6291456]), + new Uint32Array([2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481]), + new Uint32Array([23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2242529,2242561,2242593,2242625,2242657,2242689,2242721,2242753,2207937,2218177,2242785,2242817,2242849,2242882,2242945,2242977]), + new Uint32Array([2118049,2105345,2118241,2105441,2118433,2118529,2118625,2118721,2118817,2200257,2200289,2191809,2200321,2200353,2200385,2200417]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0]), + new Uint32Array([2185505,6291456,2185537,6291456,2185569,6291456,2185601,6291456,2185633,6291456,2185665,6291456,2185697,6291456,2185729,6291456]), + new Uint32Array([2231970,2232034,2232098,2232162,2232226,2232290,2232354,2232418,2232482,2232546,2232610,2232674,2232738,2232802,2232866,2232930]), + new Uint32Array([2218625,2246402,2246466,2246530,2246594,2246657,2246689,2246689,2218657,2219681,2246721,2246753,2246785,2246818,2246881,2208481]), + new Uint32Array([2197025,2197057,2197089,2197121,2197153,2197185,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2219137,2216961,2219169,2219201,2219233,2219265,2219297,2217025,2215041,2219329,2217057,2219361,2217089,2219393,2197153,2219426]), + new Uint32Array([23068672,23068672,23068672,0,0,0,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,0,0]), + new Uint32Array([2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713]), + new Uint32Array([2243522,2243585,2243617,2243649,2243681,2210113,2243713,2243746,2243810,2243874,2243937,2243970,2244033,2244065,2244097,2244129]), + new Uint32Array([2178017,6291456,2178049,6291456,2178081,6291456,2178113,6291456,2178145,6291456,2178177,6291456,2178209,6291456,2178241,6291456]), + new Uint32Array([10553858,2165314,10518722,6291456,10518818,0,10518914,2130690,10519010,2130786,10519106,2130882,10519202,2165378,10554050,2165506]), + new Uint32Array([0,0,2135491,2135587,2135683,2135779,2135875,2135971,2135971,2136067,2136163,2136259,2136355,2136355,2136451,2136547]), + new Uint32Array([23068672,23068672,23068672,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456]), + new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2220033,2220033,2220065,2220065,2220065,2220065,2220097,2220097,2220097,2220097,2220129,2220129,2220129,2220129,2220161,2220161]), + new Uint32Array([6291456,6291456,6291456,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,23068672,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2100897,2100898,2100899,2150018,2100865,2100866,2100867,2100868,2150082,2108481,2109858,2109859,2105569,2105505,2098241,2105601]), + new Uint32Array([2097217,2097505,2097505,2097505,2097505,2165570,2165570,2165634,2165634,2165698,2165698,2097858,2097858,0,0,2097152]), + new Uint32Array([23068672,6291456,23068672,23068672,23068672,6291456,6291456,23068672,23068672,6291456,6291456,6291456,6291456,6291456,23068672,23068672]), + new Uint32Array([23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0]), + new Uint32Array([10503843,10503939,10504035,10504131,10504227,10504323,10504419,10504515,10504611,10504707,10504803,10504899,10504995,10491140,10491268,0]), + new Uint32Array([2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889,2173921,2173953,2173985,2173761,2174017,2174049]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2134145,2097153,2134241,2105953,2132705,2130977,2160065,2131297,2162049,2133089,2160577,2133857,2235297,2220769,2235329,2235361]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2222401,2222433,2222465,10531394,2222497,2222529,2222561,0,2222593,2222625,2222657,2222689,2222721,2222753,2222785,0]), + new Uint32Array([2184481,6291456,2184513,6291456,2184545,6291456,2184577,6291456,2184609,6291456,2184641,6291456,2184673,6291456,2184705,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,23068672,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,23068672,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2105570,2156034,2126947,2156098,2153666,2127043,2127139,2156162,0,2127235,2156226,2156290,2156354,2156418,2127331,2127427]), + new Uint32Array([2215905,2207041,2153185,2241569,2241601,2241633,2241665,2241697,2241730,2241793,2241825,2241857,2241889,2241921,2241954,2242017]), + new Uint32Array([2203777,6291456,2203809,6291456,2203841,6291456,2203873,6291456,2203905,6291456,2173121,2180993,2181249,2203937,2181313,0]), + new Uint32Array([2168577,6291456,2168609,6291456,2168641,6291456,2168673,6291456,2168705,6291456,2168737,6291456,2168769,6291456,2168801,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,23068672,23068672,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,0,23068672,23068672,23068672,0,0]), + new Uint32Array([2210113,2195521,2210145,2210177,2210209,2210241,2210273,2210305,2210337,2210369,2210401,2210433,2210465,2210497,2210529,2210561]), + new Uint32Array([6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0]), + new Uint32Array([2228706,2228770,2228834,2228898,2228962,2229026,2229090,2229154,2229218,2229282,2229346,2229410,2229474,2229538,2229602,2229666]), + new Uint32Array([23068672,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,0,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,18874368,18874368,18874368,0,0]), + new Uint32Array([2133089,2133281,2133281,2133281,2133281,2160577,2160577,2160577,2160577,2097441,2097441,2097441,2097441,2133857,2133857,2133857]), + new Uint32Array([6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2173825,2153473,2173857,2173889,2173921,2173953,2173985,2174017,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233089]), + new Uint32Array([2178529,6291456,2178561,6291456,2178593,6291456,2178625,6291456,2178657,6291456,2178689,6291456,2178721,6291456,2178753,6291456]), + new Uint32Array([2221025,2221025,2221057,2221057,2159329,2159329,2159329,2159329,2097217,2097217,2158914,2158914,2158978,2158978,2159042,2159042]), + new Uint32Array([2208161,2208193,2208225,2208257,2194433,2208289,2208321,2208353,2208385,2208417,2208449,2208481,2208513,2208545,2208577,2208609]), + new Uint32Array([2169217,6291456,2169249,6291456,2169281,6291456,2169313,6291456,2169345,6291456,2169377,6291456,2169409,6291456,2169441,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456]), + new Uint32Array([2133187,2133283,2133283,2133379,2133475,2133571,2133667,2133667,2133763,2133859,2133955,2134051,2134147,2134147,2134243,2134339]), + new Uint32Array([2197697,2114113,2114209,2197729,2197761,2114305,2197793,2114401,2114497,2197825,2114593,2114689,2114785,2114881,2114977,0]), + new Uint32Array([2193089,2193121,2193153,2193185,2117665,2117569,2193217,2193249,2193281,2193313,2193345,2193377,2193409,2193441,2193473,2193505]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0]), + new Uint32Array([6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2184225,6291456,2184257,6291456,2184289,6291456,2184321,6291456,2184353,6291456,2184385,6291456,2184417,6291456,2184449,6291456]), + new Uint32Array([2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2100833,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2098657,2098049,2200737,2123489,2123681,2200769,2098625,2100321,2098145,2100449,2098017,2098753,2200801,2200833,2200865,0]), + new Uint32Array([23068672,23068672,23068672,0,0,0,0,0,0,0,0,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0]), + new Uint32Array([2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,0,2098241,2108353,2108417,2105825,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2181153,2105505,2181185,2167617,2180993]), + new Uint32Array([2160002,2160066,2160130,2160194,2160258,2132066,2131010,2131106,2106018,2131618,2160322,2131298,2132034,2131938,2137410,2132226]), + new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,6291456]), + new Uint32Array([2183617,6291456,2183649,6291456,2183681,6291456,2183713,6291456,2183745,6291456,2183777,6291456,2183809,6291456,2183841,6291456]), + new Uint32Array([0,6291456,6291456,0,6291456,0,0,6291456,6291456,0,6291456,0,0,6291456,0,0]), + new Uint32Array([2250977,2251009,2251041,2251073,2195009,2251106,2251169,2251201,2251233,2251265,2251297,2251330,2251394,2251457,2251489,2251521]), + new Uint32Array([2205729,2205761,2205793,2205825,2205857,2205889,2205921,2205953,2205985,2206017,2206049,2206081,2206113,2206145,2206177,2206209]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2143170,2168993,6291456,2169025,6291456,2169057,6291456,2169089,6291456,2143234,2169121,6291456,2169153,6291456,2169185,6291456]), + new Uint32Array([23068672,23068672,2190689,6291456,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2248706,2248769,2248801,2248833,2248865,2248897,2248929,2248962,2249026,2249090,2249154,2240705,2249217,2249249,2249281,2249313]), + new Uint32Array([10485857,6291456,6291456,6291456,6291456,6291456,6291456,6291456,10495394,6291456,2098209,6291456,6291456,2097152,6291456,10531394]), + new Uint32Array([0,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,0]), + new Uint32Array([14680064,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2173985,2173953,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889]), + new Uint32Array([6291456,2186977,6291456,6291456,6291456,6291456,6291456,10537858,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2209601,2209633,2209665,2209697,2209729,2209761,2209793,2209825,2209857,2209889,2209921,2209953,2209985,2210017,2210049,2210081]), + new Uint32Array([10501539,10501635,10501731,10501827,10501923,10502019,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905]), + new Uint32Array([2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889,2173921,2173953,2173985,2174017,2174017,2174049]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,0,0]), + new Uint32Array([6291456,6291456,23068672,23068672,23068672,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2194561,2194593,2194625,2119777,2119873,2194657,2194689,2194721,2194753,2194785,2194817,2194849,2194881,2194913,2194945,2194977]), + new Uint32Array([2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569]), + new Uint32Array([2222818,2222882,2222946,2223010,2223074,2223138,2223202,2223266,2223330,2223394,2223458,2223522,2223586,2223650,2223714,2223778]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672]), + new Uint32Array([0,2179553,2179585,2179617,2179649,2144001,2179681,2179713,2179745,2179777,2179809,2156705,2179841,2156833,2179873,2179905]), + new Uint32Array([6291456,23068672,6291456,2145602,23068672,23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,6291456,0,0]), + new Uint32Array([2196513,2196545,2196577,2196609,2196641,2196673,2196705,2196737,2196769,2196801,2196833,2196865,2196897,2196929,2196961,2196993]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2177281,6291456,2177313,6291456,2177345,6291456,2177377,6291456,2177409,6291456,2177441,6291456,2177473,6291456,2177505,6291456]), + new Uint32Array([2187137,2221473,2221505,2221537,2221569,6291456,6291456,10610209,10610241,10537986,10537986,10537986,10537986,10609857,10609857,10609857]), + new Uint32Array([2243009,2243041,2216033,2243074,2243137,2243169,2243201,2219617,2243233,2243265,2243297,2243329,2243362,2243425,2243457,2243489]), + new Uint32Array([10485857,10485857,10485857,10485857,10485857,10485857,10485857,10485857,10485857,10485857,10485857,2097152,4194304,4194304,0,0]), + new Uint32Array([2143042,6291456,2143106,2143106,2168833,6291456,2168865,6291456,6291456,2168897,6291456,2168929,6291456,2168961,6291456,2143170]), + new Uint32Array([6291456,6291456,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2204193,2204225,2204257,2204289,2204321,2204353,2204385,2204417,2204449,2204481,2204513,2204545,2204577,2204609,2204641,2204673]), + new Uint32Array([2202753,6291456,2202785,6291456,2202817,6291456,2202849,6291456,2202881,6291456,2202913,6291456,2202945,6291456,2202977,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177,2098305,2108321]), + new Uint32Array([2147394,2147458,2147522,2147586,2147650,2147714,2147778,2147842,2147394,2147458,2147522,2147586,2147650,2147714,2147778,2147842]), + new Uint32Array([2253313,2253346,2253409,2253441,2253473,2253505,2253537,2253569,2253601,2253634,2219393,2253697,2253729,2253761,2253793,2253825]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,6291456,6291456]), + new Uint32Array([2162562,2162626,2131362,2162690,2159938,2160002,2162754,2162818,2160130,2162882,2160194,2160258,2160834,2160898,2161026,2161090]), + new Uint32Array([2175361,2175393,2175425,2175457,2175489,2175521,2175553,2175585,2175617,2175649,2175681,2175713,2175745,2175777,2175809,2175841]), + new Uint32Array([2253858,2253921,2253954,2254018,2254082,2196737,2254145,2196865,2254177,2254209,2254241,2254273,2197025,2254306,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2202113,2204129,2188705,2204161]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,0,6291456,6291456,6291456,6291456,0,0]), + new Uint32Array([2173985,2174017,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233089,2173697,2173761,2173793,2174113,2173985,2173953]), + new Uint32Array([2101569,2101697,2101825,2101953,2102081,2102209,2100833,2100737,2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209]), + new Uint32Array([2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241,0,2108417,0,2111713,2100897,2111905]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0]), + new Uint32Array([2175425,2175489,2175809,2175905,2175937,2175937,2176193,2176417,2180865,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,2143298,2143298,2143298,2143362,2143362,2143362,2143426,2143426,2143426,2171105,6291456,2171137]), + new Uint32Array([2120162,2120258,2151618,2151682,2151746,2151810,2151874,2151938,2152002,2120035,2120131,2120227,2152066,2120323,2152130,2120419]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2195361,2142433,2236065,2236097,2236129,2236161,2118241,2117473,2236193,2236225,2236257,2236289,0,0,0,0]), + new Uint32Array([2189281,6291456,2189313,6291456,2189345,6291456,2189377,6291456,2189409,6291456,2189441,6291456,2189473,6291456,2189505,6291456]), + new Uint32Array([6291456,6291456,2145922,6291456,6291456,6291456,6291456,2145986,6291456,6291456,6291456,6291456,2146050,6291456,6291456,6291456]), + new Uint32Array([2100833,2100737,2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209,10502113,10562017,10610401,10502177,10610433,10538049]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,2186401,0,2186433,0,2186465,0,2186497]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,23068672,23068672,23068672]), + new Uint32Array([0,0,2198241,2198273,2198305,2198337,2198369,2198401,0,0,2198433,2198465,2198497,0,0,0]), + new Uint32Array([6291456,0,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,0,6291456,0,23068672,23068672,23068672,23068672,23068672,23068672,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,0,0,23068672,6291456,23068672,23068672]), + new Uint32Array([0,2105921,2097729,0,2097377,0,0,2106017,2133281,2097505,2105889,0,2097697,2135777,2097633,2097441]), + new Uint32Array([2197889,2197921,2197953,2197985,2198017,2198049,2198081,2198113,2198145,2198177,2198209,2198241,2198273,2198305,2198337,2198369]), + new Uint32Array([2132514,2132610,2160386,2133090,2133186,2160450,2160514,2133282,2160578,2133570,2106178,2160642,2133858,2160706,2160770,2134146]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,23068672,0,0,0,0,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,23068672,23068672,6291456,23068672,23068672,6291456,23068672,0,0,0,0,0,0,0,0]), + new Uint32Array([2184737,6291456,2184769,6291456,2184801,6291456,2184833,6291456,2184865,6291456,2184897,6291456,2184929,6291456,2184961,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,0,6291456,6291456,6291456,6291456,0,6291456]), + new Uint32Array([6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,6291456,23068672,23068672,23068672,6291456,23068672,23068672,23068672,23068672,23068672,0,0]), + new Uint32Array([6291456,6291456,6291456,2186753,6291456,6291456,6291456,6291456,2186785,2186817,2186849,2173569,2186881,10496355,10495395,10575521]), + new Uint32Array([0,0,2097729,0,0,0,0,2106017,0,2097505,0,2097185,0,2135777,2097633,2097441]), + new Uint32Array([2189537,6291456,2189569,6291456,2189601,6291456,2189633,6291456,2189665,6291456,2189697,6291456,2189729,6291456,2189761,6291456]), + new Uint32Array([2202497,6291456,2202529,6291456,2202561,6291456,2202593,6291456,2202625,6291456,2202657,6291456,2202689,6291456,2202721,6291456]), + new Uint32Array([2245217,2218369,2245249,2245282,2245345,2245377,2245410,2245474,2245537,2245569,2245601,2245633,2245665,2245665,2245697,2245729]), + new Uint32Array([6291456,0,23068672,23068672,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,0,0,0,0,0,0,23068672,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,6291456,23068672,6291456,23068672,6291456,6291456,6291456,6291456,23068672,23068672]), + new Uint32Array([0,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2097281,2105921,2097729,2106081,2097377,2097601,2162337,2106017,2133281,2097505,0,2097185,2097697,2135777,2097633,2097441]), + new Uint32Array([2176641,6291456,2176673,6291456,2176705,6291456,2176737,6291456,2176769,6291456,2176801,6291456,2176833,6291456,2176865,6291456]), + new Uint32Array([2174145,2174177,2149057,2233089,2173697,2173761,2173793,2174113,2173985,2173953,2174369,2174369,0,0,2100833,2100737]), + new Uint32Array([2116513,2190817,2190849,2190881,2190913,2190945,2116609,2190977,2191009,2191041,2191073,2117185,2191105,2191137,2191169,2191201]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,6291456,6291456,6291456]), + new Uint32Array([0,0,0,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456]), + new Uint32Array([2167617,2167649,2167681,2167713,2167745,2167777,2167809,6291456,2167841,2167873,2167905,2167937,2167969,2168001,2168033,4240130]), + new Uint32Array([2165122,2163970,2164034,2164098,2164162,2164226,2164290,2164354,2164418,2164482,2164546,2133122,2134562,2132162,2132834,2136866]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,2186209,2186241,2186273,2186305,2186337,2186369,0,0]), + new Uint32Array([2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,14680064,14680064,14680064,14680064,14680064]), + new Uint32Array([0,0,23068672,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456]), + new Uint32Array([0,10537921,10610689,10610273,10610497,10610529,10610305,10610721,10489601,10489697,10610337,10575617,10554529,2221761,2197217,10496577]), + new Uint32Array([2105473,2105569,2105601,2112289,0,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441]), + new Uint32Array([2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481]), + new Uint32Array([2125346,2153410,2153474,2127394,2153538,2153602,2153666,2153730,2105507,2105476,2153794,2153858,2153922,2153986,2154050,2105794]), + new Uint32Array([2200449,2119681,2200481,2153313,2199873,2199905,2199937,2200513,2200545,2200577,2200609,2119105,2119201,2119297,2119393,2119489]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2175777,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2222273,2197217,2221473,2221505,2221089,2222305,2200865,2099681,2104481,2222337,2099905,2120737,2222369,2103713,2100225,2098785]), + new Uint32Array([2201377,6291456,2201409,6291456,2201441,6291456,2201473,6291456,2201505,6291456,2201537,6291456,2201569,6291456,6291456,23068672]), + new Uint32Array([2174081,2174113,2174145,2174177,2149057,2233057,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793]), + new Uint32Array([2200897,6291456,2200929,6291456,2200961,6291456,2200993,6291456,2201025,6291456,2180865,6291456,2201057,6291456,2201089,6291456]), + new Uint32Array([0,0,0,0,0,23068672,23068672,0,6291456,6291456,6291456,0,0,0,0,0]), + new Uint32Array([2161154,2161410,2138658,2161474,2161538,2097666,2097186,2097474,2162946,2132450,2163010,2163074,2136162,2163138,2161666,2161730]), + new Uint32Array([2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889,2173921,2173953]), + new Uint32Array([0,0,0,0,0,0,23068672,23068672,0,0,0,0,2145410,2145474,0,6291456]), + new Uint32Array([2244161,2216065,2212769,2244193,2244225,2244257,2244290,2244353,2244385,2244417,2244449,2218273,2244481,2244514,2244577,2244609]), + new Uint32Array([2125730,2125699,2125795,2125891,2125987,2154114,2154178,2154242,2154306,2154370,2154434,2154498,2126082,2126178,2126274,2126083]), + new Uint32Array([2237665,2237697,2237697,2237697,2237730,2237793,2237825,2237857,2237890,2237953,2237985,2238017,2238049,2238081,2238113,2238145]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2150146,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,0,23068672,23068672,0,0,23068672,23068672,23068672,0,0]), + new Uint32Array([2214369,2238593,2238625,2238657,2238689,2238721,2238753,2238785,2238817,2238850,2238913,2238945,2238977,2235457,2239009,2239041]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0]), + new Uint32Array([2252066,2252130,2252193,2252225,2252257,2252290,2252353,2252385,2252417,2252449,2252481,2252513,2252545,2252578,2252641,2252673]), + new Uint32Array([2197697,2114113,2114209,2197729,2197761,2114305,2197793,2114401,2114497,2197825,2114593,2114689,2114785,2114881,2114977,2197857]), + new Uint32Array([2224866,2224930,2224994,2225058,2225122,2225186,2225250,2225314,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2219490,2219554,2219617,2219649,2219681,2219714,2219778,2219842,2219905,2219937,0,0,0,0,0,0]), + new Uint32Array([6291456,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456]), + new Uint32Array([2113345,2113441,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289]), + new Uint32Array([2174081,2174113,2174145,2174177,2149057,2233089,2173697,2173761,2173793,2174113,2173985,2173953,2148481,2173601,2173633,2173665]), + new Uint32Array([2220161,2220161,2220193,2220193,2220193,2220193,2220225,2220225,2220225,2220225,2220257,2220257,2220257,2220257,2220289,2220289]), + new Uint32Array([2192673,2192705,2192737,2192769,2192801,2192833,2192865,2118049,2192897,2117473,2117761,2192929,2192961,2192993,2193025,2193057]), + new Uint32Array([2179297,6291456,2179329,6291456,2179361,6291456,2179393,6291456,2179425,6291456,2179457,6291456,2179489,6291456,2179521,6291456]), + new Uint32Array([6291456,6291456,6291456,23068672,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2235745,2235777,2193633,2235809,2235841,2235873,2235905,2235937,2235969,2116513,2116705,2236001,2200513,2199905,2200545,2236033]), + new Uint32Array([2113153,2108481,2113345,2113441,2232993,2233025,0,0,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761]), + new Uint32Array([2170593,6291456,2170625,6291456,2170657,6291456,2170689,2170721,6291456,2170753,6291456,6291456,2170785,6291456,2170817,2170849]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2166786,2166850,0,0,0,0]), + new Uint32Array([23068672,6291456,0,0,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456]), + new Uint32Array([2100833,2100737,2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209,10575617,2187041,10502177,10489601,10489697,0]), + new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2134562,2132162,2132834,2136866,2136482,2164610,2164674,2164738,2164802,2132802,2132706,2164866,2132898,2164930,2164994,2165058]), + new Uint32Array([6291456,6291456,2098337,2101441,10531458,2153473,6291456,6291456,10531522,2100737,2108193,6291456,2106499,2106595,2106691,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2233122,2233186,2233250,2233314,2233378,2233442,2233506,2233570,2233634,2233698,2233762,2233826,2233890,2233954,2234018,2234082]), + new Uint32Array([23068672,6291456,23068672,23068672,23068672,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2205217,2205249,2205281,2205313,2205345,2205377,2205409,2205441,2205473,2205505,2205537,2205569,2205601,2205633,2205665,2205697]), + new Uint32Array([6291456,0,6291456,0,0,0,6291456,6291456,6291456,6291456,0,0,23068672,6291456,23068672,23068672]), + new Uint32Array([2173601,2173761,2174081,2173569,2174241,2174113,2173953,6291456,2174305,6291456,2174337,6291456,2174369,6291456,2174401,6291456]), + new Uint32Array([6291456,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456]), + new Uint32Array([2152450,2152514,2099653,2104452,2099813,2122243,2099973,2152578,2122339,2122435,2122531,2122627,2122723,2104580,2122819,2152642]), + new Uint32Array([2236385,2236417,2236449,2236482,2236545,2215425,2236577,2236609,2236641,2236673,2215457,2236705,2236737,2236770,2215489,2236833]), + new Uint32Array([2163394,2159746,2163458,2131362,2163522,2160130,2163778,2132226,2163842,2132898,2163906,2161410,2138658,2097666,2136162,2163650]), + new Uint32Array([2218721,2246913,2246946,2216385,2247010,2247074,2215009,2247137,2247169,2216481,2247201,2247233,2247266,2247330,2247330,0]), + new Uint32Array([2129730,2129762,2129858,2129731,2129827,2156482,2156482,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,0,0,0,0,0,6291456,0,0]), + new Uint32Array([2203969,2204001,2181377,2204033,2204065,6291456,2204097,6291456,0,0,0,0,0,0,0,0]), + new Uint32Array([2169473,6291456,2169505,6291456,2169537,6291456,2169569,6291456,2169601,6291456,2169633,6291456,2169665,6291456,2169697,6291456]), + new Uint32Array([2141542,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2220801,2220801,2220801,2220801,2220833,2220833,2220865,2220865,2220865,2220865,2220897,2220897,2220897,2220897,2139873,2139873]), + new Uint32Array([0,0,0,0,0,23068672,23068672,0,0,0,0,0,0,0,6291456,0]), + new Uint32Array([2214849,2218433,2218465,2218497,2218529,2218561,2214881,2218593,2218625,2218657,2218689,2218721,2218753,2216545,2218785,2218817]), + new Uint32Array([23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0,0,0,0,6291456]), + new Uint32Array([2136482,2164610,2164674,2164738,2164802,2132802,2132706,2164866,2132898,2164930,2164994,2165058,2165122,2132802,2132706,2164866]), + new Uint32Array([2207649,2207681,2207713,2207745,2207777,2207809,2207841,2207873,2207905,2207937,2207969,2208001,2208033,2208065,2208097,2208129]), + new Uint32Array([2123683,2105092,2152706,2123779,2105220,2152770,2100453,2098755,2123906,2124002,2124098,2124194,2124290,2124386,2124482,2124578]), + new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,6291456,0,0,0,0,0,0,0,10485857]), + new Uint32Array([6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([10508163,10508259,10508355,10508451,2200129,2200161,2192737,2200193,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2203553,6291456,2203585,6291456,6291456,6291456,2203617,6291456,2203649,6291456,2203681,6291456,2203713,6291456,2203745,6291456]), + new Uint32Array([18884449,18884065,23068672,18884417,18884034,18921185,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,18874368]), + new Uint32Array([2247393,2247426,2247489,2247521,2247553,2247586,2247649,2247681,2247713,2247745,2247777,2247810,2247873,2247905,2247937,2247969]), + new Uint32Array([6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,23068672]), + new Uint32Array([2134145,2097153,2134241,0,2132705,2130977,2160065,2131297,0,2133089,2160577,2133857,2235297,0,2235329,0]), + new Uint32Array([2182593,6291456,2182625,6291456,2182657,6291456,2182689,6291456,2182721,6291456,2182753,6291456,2182785,6291456,2182817,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2102402,2102403,6291456,2110050]), + new Uint32Array([2149890,2108323,2149954,6291456,2113441,6291456,2149057,6291456,2113441,6291456,2105473,2167265,2111137,2105505,6291456,2108353]), + new Uint32Array([2219105,2219137,2195233,2251554,2251617,2251649,2251681,2251713,2251746,2251810,2251873,2251905,2251937,2251970,2252033,2219169]), + new Uint32Array([2203009,6291456,2203041,6291456,2203073,6291456,2203105,6291456,2203137,6291456,2203169,6291456,2203201,6291456,2203233,6291456]), + new Uint32Array([2128195,2128291,2128387,2128483,2128579,2128675,2128771,2128867,2128963,2129059,2129155,2129251,2129347,2129443,2129539,2129635]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2140964,2141156,2140966,2141158,2141350]), + new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2225378,2225442,2225506,2225570,2225634,2225698,2225762,2225826,2225890,2225954,2226018,2226082,2226146,2226210,2226274,2226338]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241,2108353,2108417]), + new Uint32Array([2108353,2108417,0,2105601,2108193,2157121,2157313,2157377,2157441,2100897,6291456,2108419,2173953,2173633,2173633,2173953]), + new Uint32Array([2111713,2173121,2111905,2098177,2173153,2173185,2173217,2113153,2113345,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,2190753]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,2197249,6291456,2117377,2197281,2197313,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,0,0,0,0,0,0,23068672,0,0,0,0,0,6291456,6291456,6291456]), + new Uint32Array([2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209,2100833,2100737,2098337,2101441,2101569,2101697,2101825,2101953]), + new Uint32Array([23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0]), + new Uint32Array([0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,23068672,23068672,23068672]), + new Uint32Array([2173281,6291456,2173313,6291456,2173345,6291456,2173377,6291456,0,0,10532546,6291456,6291456,6291456,10562017,2173441]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,0,0]), + new Uint32Array([23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2159426,2159490,2159554,2159362,2159618,2159682,2139522,2136450,2159746,2159810,2159874,2130978,2131074,2131266,2131362,2159938]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2203233,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2203265,6291456,2203297,6291456,2203329,2203361,6291456]), + new Uint32Array([6291456,6291456,2148418,2148482,2148546,0,6291456,2148610,2186529,2186561,2148417,2148545,2148482,10495778,2143969,10495778]), + new Uint32Array([2134146,2139426,2160962,2134242,2161218,2161282,2161346,2161410,2138658,2134722,2134434,2134818,2097666,2097346,2097698,2105986]), + new Uint32Array([2198881,2198913,2198945,2198977,2199009,2199041,2199073,2199105,2199137,2199169,2199201,2199233,2199265,2199297,2199329,2199361]), + new Uint32Array([0,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456]), + new Uint32Array([10610561,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193]), + new Uint32Array([2183873,6291456,2183905,6291456,2183937,6291456,2183969,6291456,2184001,6291456,2184033,6291456,2184065,6291456,2184097,6291456]), + new Uint32Array([2244642,2244706,2244769,2244801,2218305,2244833,2244865,2244897,2244929,2244961,2244993,2245026,2245089,2245122,2245185,0]), + new Uint32Array([6291456,6291456,2116513,2116609,2116705,2116801,2199873,2199905,2199937,2199969,2190913,2200001,2200033,2200065,2200097,2191009]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,2180673,2180705,2180737,2180769,2180801,2180833,0,0]), + new Uint32Array([2098081,2099521,2099105,2120705,2098369,2120801,2103361,2097985,2098433,2121377,2121473,2099169,2099873,2098401,2099393,2152609]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2150402]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,2145666,2145730,6291456,6291456]), + new Uint32Array([2173921,2173953,2173985,2173761,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233057,2148481,2173601,2173633,2173665]), + new Uint32Array([2187073,6291456,6291456,6291456,6291456,2098241,2098241,2108353,2100897,2111905,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2102404,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,2100612,6291456,6291456,6291456,6291456,6291456,6291456,6291456,10485857]), + new Uint32Array([2149057,2233057,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889]), + new Uint32Array([2217697,2217729,2217761,2217793,2217825,2217857,2217889,2217921,2217953,2215873,2217985,2215905,2218017,2218049,2218081,2218113]), + new Uint32Array([2211233,2218849,2216673,2218881,2218913,2218945,2218977,2219009,2216833,2219041,2215137,2219073,2216865,2209505,2219105,2216897]), + new Uint32Array([2240097,2240129,2240161,2240193,2240225,2240257,2240289,2240321,2240353,2240386,2240449,2240481,2240513,2240545,2207905,2240578]), + new Uint32Array([6291456,6291456,2202273,6291456,2202305,6291456,2202337,6291456,2202369,6291456,2202401,6291456,2202433,6291456,2202465,6291456]), + new Uint32Array([0,23068672,23068672,18923394,23068672,18923458,18923522,18884099,18923586,18884195,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2201121,6291456,2201153,6291456,2201185,6291456,2201217,6291456,2201249,6291456,2201281,6291456,2201313,6291456,2201345,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456]), + new Uint32Array([2211041,2211073,2211105,2211137,2211169,2211201,2211233,2211265,2211297,2211329,2211361,2211393,2211425,2211457,2211489,2211521]), + new Uint32Array([2181825,6291456,2181857,6291456,2181889,6291456,2181921,6291456,2181953,6291456,2181985,6291456,2182017,6291456,2182049,6291456]), + new Uint32Array([2162337,2097633,2097633,2097633,2097633,2132705,2132705,2132705,2132705,2097153,2097153,2097153,2097153,2133089,2133089,2133089]), + new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,2148545,6291456,2173473,6291456,2148865,6291456,2173505,6291456,2173537,6291456,2173569,6291456,2149121,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,0,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0]), + new Uint32Array([2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889,2173921,2173953,2173985,2174017,2174017,2174049,2174081,2174113]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2207137,2207169,2207201,2207233,2207265,2207297,2207329,2207361,2207393,2207425,2207457,2207489,2207521,2207553,2207585,2207617]), + new Uint32Array([6291456,6291456,23068672,23068672,23068672,6291456,6291456,0,23068672,23068672,0,0,0,0,0,0]), + new Uint32Array([2198401,2198433,2198465,2198497,0,2198529,2198561,2198593,2198625,2198657,2198689,2198721,2198753,2198785,2198817,2198849]), + new Uint32Array([2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177]), + new Uint32Array([23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,0,0]), + new Uint32Array([2216385,2118721,2216417,2216449,2216481,2216513,2216545,2211233,2216577,2216609,2216641,2216673,2216705,2216737,2216737,2216769]), + new Uint32Array([2216801,2216833,2216865,2216897,2216929,2216961,2216993,2215169,2217025,2217057,2217089,2217121,2217154,2217217,0,0]), + new Uint32Array([2210593,2191809,2210625,2210657,2210689,2210721,2210753,2210785,2210817,2210849,2191297,2210881,2210913,2210945,2210977,2211009]), + new Uint32Array([0,0,2105825,0,0,2111905,2105473,0,0,2112289,2108193,2112481,2112577,0,2098305,2108321]), + new Uint32Array([0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([0,2097153,2134241,0,2132705,0,0,2131297,0,2133089,0,2133857,0,2220769,0,2235361]), + new Uint32Array([14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,6291456,6291456,14680064]), + new Uint32Array([23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0]), + new Uint32Array([2171873,6291456,2171905,6291456,2171937,6291456,2171969,6291456,2172001,6291456,2172033,6291456,2172065,6291456,2172097,6291456]), + new Uint32Array([2220929,2220929,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2133857,2134145,2134145,2134145,2134145,2134241,2134241,2134241,2134241,2105889,2105889,2105889,2105889,2097185,2097185,2097185]), + new Uint32Array([2173697,2173761,2173793,2174113,2173985,2173953,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793]), + new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,0,10499619,10499715,10499811,10499907]), + new Uint32Array([0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,0,0,0,0,0,0,0,0,0,0,0,0,0,0,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,0,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,0,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,23068672,23068672]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,2144322,2144386,2144450,2144514,2144578,2144642,2144706,2144770]), + new Uint32Array([23068672,23068672,23068672,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456]), + new Uint32Array([2113153,2108481,2113345,2113441,2098209,2111137,0,2098241,2108353,2108417,2105825,0,0,2111905,2105473,2105569]), + new Uint32Array([2236321,2236353,0,0,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2152194,2121283,2103684,2103812,2097986,2098533,2097990,2098693,2098595,2098853,2099013,2103940,2121379,2121475,2121571,2104068]), + new Uint32Array([2206241,2206273,2206305,2206337,2206369,2206401,2206433,2206465,2206497,2206529,2206561,2206593,2206625,2206657,2206689,2206721]), + new Uint32Array([6291456,6291456,6291456,6291456,16777216,16777216,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,23068672,23068672,10538818,10538882,6291456,6291456,2150338]), + new Uint32Array([6291456,6291456,6291456,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2214369,2214401,2214433,2214465,2214497,2214529,2214561,2214593,2194977,2214625,2195073,2214657,2214689,2214721,6291456,6291456]), + new Uint32Array([2097152,2097152,2097152,2097152,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2182081,6291456,2182113,6291456,2182145,6291456,2182177,6291456,2182209,6291456,2182241,6291456,2182273,6291456,2182305,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2146881,2146945,2147009,2147073,2147137,2147201,2147265,2147329]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,23068672,23068672]), + new Uint32Array([0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2122915,2123011,2123107,2104708,2123203,2123299,2123395,2100133,2104836,2100290,2100293,2104962,2104964,2098052,2123491,2123587]), + new Uint32Array([23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456]), + new Uint32Array([6291456,2171169,6291456,2171201,6291456,2171233,6291456,2171265,6291456,2171297,6291456,2171329,6291456,6291456,2171361,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([0,0,2148994,2149058,2149122,0,6291456,2149186,2186945,2173537,2148993,2149121,2149058,10531458,10496066,0]), + new Uint32Array([2195009,2195041,2195073,2195105,2195137,2195169,2195201,2195233,2195265,2195297,2195329,2195361,2195393,2195425,2195457,2195489]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,0,0,6291456,6291456]), + new Uint32Array([2182849,6291456,2182881,6291456,2182913,6291456,2182945,6291456,2182977,6291456,2183009,6291456,2183041,6291456,2183073,6291456]), + new Uint32Array([2211553,2210081,2211585,2211617,2211649,2211681,2211713,2211745,2211777,2211809,2209569,2211841,2211873,2211905,2211937,2211969]), + new Uint32Array([2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2166594,2127298,2166658,2142978,2141827,2166722]), + new Uint32Array([2173985,2173761,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233057,2148481,2173601,2173633,2173665,2173697,2173729]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,2185761,2185793,2185825,2185857,2185889,2185921,0,0]), + new Uint32Array([6291456,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889,2173921]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,6291456]), + new Uint32Array([0,0,0,2220961,2220961,2220961,2220961,2144193,2144193,2159201,2159201,2159265,2159265,2144194,2220993,2220993]), + new Uint32Array([2192641,2235393,2235425,2152257,2116609,2235457,2235489,2200065,2235521,2235553,2235585,2212449,2235617,2235649,2235681,2235713]), + new Uint32Array([2194049,2194081,2194113,2194145,2194177,2194209,2194241,2194273,2194305,2194337,2194369,2194401,2194433,2194465,2194497,2194529]), + new Uint32Array([2196673,2208641,2208673,2208705,2208737,2208769,2208801,2208833,2208865,2208897,2208929,2208961,2208993,2209025,2209057,2209089]), + new Uint32Array([2191681,2191713,2191745,2191777,2153281,2191809,2191841,2191873,2191905,2191937,2191969,2192001,2192033,2192065,2192097,2192129]), + new Uint32Array([2230946,2231010,2231074,2231138,2231202,2231266,2231330,2231394,2231458,2231522,2231586,2231650,2231714,2231778,2231842,2231906]), + new Uint32Array([14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2185953,2185985,2186017,2186049,2186081,2186113,2186145,2186177]), + new Uint32Array([2139811,2139907,2097284,2105860,2105988,2106116,2106244,2097444,2097604,2097155,10485778,10486344,2106372,6291456,0,0]), + new Uint32Array([2110051,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([0,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2172385,6291456,2172417,6291456,2172449,6291456,2172481,6291456,2172513,6291456,2172545,6291456,2172577,6291456,2172609,6291456]), + new Uint32Array([0,0,23068672,23068672,6291456,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2249345,2249377,2249409,2249441,2249473,2249505,2249537,2249570,2210209,2249633,2249665,2249697,2249729,2249761,2249793,2216769]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,6291456,6291456,6291456,6291456]), + new Uint32Array([2187169,2187201,2187233,2187265,2187297,2187329,2187361,2187393,2187425,2187457,2187489,2187521,2187553,2187585,2187617,2187649]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([0,0,0,6291456,6291456,0,0,0,6291456,6291456,6291456,0,0,0,6291456,6291456]), + new Uint32Array([2182337,6291456,2182369,6291456,2182401,6291456,2182433,6291456,2182465,6291456,2182497,6291456,2182529,6291456,2182561,6291456]), + new Uint32Array([2138179,2138275,2138371,2138467,2134243,2134435,2138563,2138659,2138755,2138851,2138947,2139043,2138947,2138755,2139139,2139235]), + new Uint32Array([23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0]), + new Uint32Array([0,0,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2250498,2250562,2250625,2250657,2208321,2250689,2250721,2250753,2250785,2250817,2250849,2218945,2250881,2250913,2250945,0]), + new Uint32Array([2170369,2105569,2098305,2108481,2173249,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456]), + new Uint32Array([2100897,2111905,2105473,2105569,2105601,0,2108193,0,0,0,2098305,2108321,2108289,2100865,2113153,2108481]), + new Uint32Array([2100897,2100897,2105569,2105569,6291456,2112289,2149826,6291456,6291456,2112481,2112577,2098177,2098177,2098177,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,6291456,6291456,6291456]), + new Uint32Array([6291456,2169953,2169985,6291456,2170017,6291456,2170049,2170081,6291456,2170113,2170145,2170177,6291456,6291456,2170209,2170241]), + new Uint32Array([6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2220641,2220641,2220673,2220673,2220673,2220673,2220705,2220705,2220705,2220705,2220737,2220737,2220737,2220737,2220769,2220769]), + new Uint32Array([2127650,2127746,2127842,2127938,2128034,2128130,2128226,2128322,2128418,2127523,2127619,2127715,2127811,2127907,2128003,2128099]), + new Uint32Array([2143969,2173793,2173825,2153473,2173857,2173889,2173921,2173953,2173985,2173761,2174017,2174049,2174081,2174113,2174145,2174177]), + new Uint32Array([0,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2204705,2204737,2204769,2204801,2204833,2204865,2204897,2204929,2204961,2204993,2205025,2205057,2205089,2205121,2205153,2205185]), + new Uint32Array([2176385,6291456,2176417,6291456,2176449,6291456,2176481,6291456,2176513,6291456,2176545,6291456,2176577,6291456,2176609,6291456]), + new Uint32Array([2195521,2195553,2195585,2195617,2195649,2195681,2117857,2195713,2195745,2195777,2195809,2195841,2195873,2195905,2195937,2195969]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456]), + new Uint32Array([2173921,2173953,2173985,2174017,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233089,2173697,2173761,2173793,2174113]), + new Uint32Array([2131586,2132450,2135970,2135778,2161602,2136162,2163650,2161794,2135586,2163714,2137186,2131810,2160290,2135170,2097506,2159554]), + new Uint32Array([2134145,2097153,2134241,2105953,2132705,2130977,2160065,2131297,2162049,2133089,2160577,2133857,0,0,0,0]), + new Uint32Array([2116513,2116609,2116705,2116801,2116897,2116993,2117089,2117185,2117281,2117377,2117473,2117569,2117665,2117761,2117857,2117953]), + new Uint32Array([2100737,2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209,2100802,2101154,2101282,2101410,2101538,2101666,2101794]), + new Uint32Array([2100289,2098657,2098049,2200737,2123489,2123681,2200769,2098625,2100321,2098145,2100449,2098017,2098753,2098977,2150241,2150305]), + new Uint32Array([6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,2109955,6291456,6291456,0,0,0,0]), + new Uint32Array([18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,0,6291456,0,0]), + new Uint32Array([2130979,2131075,2131075,2131171,2131267,2131363,2131459,2131555,2131651,2131651,2131747,2131843,2131939,2132035,2132131,2132227]), + new Uint32Array([0,2177793,6291456,2177825,6291456,2177857,6291456,2177889,6291456,2177921,6291456,2177953,6291456,2177985,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2113345,0,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289]), + new Uint32Array([2136643,2136739,2136835,2136931,2137027,2137123,2137219,2137315,2137411,2137507,2137603,2137699,2137795,2137891,2137987,2138083]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0]), + new Uint32Array([2174433,6291456,2174465,6291456,2174497,6291456,2174529,6291456,2174561,6291456,2174593,6291456,2174625,6291456,2174657,6291456]), + new Uint32Array([0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441]), + new Uint32Array([10496547,10496643,2105505,2149698,6291456,10496739,10496835,2170273,6291456,2149762,2105825,2111713,2111713,2111713,2111713,2168673]), + new Uint32Array([6291456,2143490,2143490,2143490,2171649,6291456,2171681,2171713,2171745,6291456,2171777,6291456,2171809,6291456,2171841,6291456]), + new Uint32Array([2159106,2159106,2159170,2159170,2159234,2159234,2159298,2159298,2159298,2159362,2159362,2159362,2106401,2106401,2106401,2106401]), + new Uint32Array([2105601,2112289,2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137]), + new Uint32Array([2108417,2181217,2181249,2181281,2170433,2170401,2181313,2181345,2181377,2181409,2181441,2181473,2181505,2181537,2170529,2181569]), + new Uint32Array([2218433,2245761,2245793,2245825,2245857,2245890,2245953,2245986,2209665,2246050,2246113,2246146,2246210,2246274,2246337,2246369]), + new Uint32Array([2230754,2230818,2230882,0,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,0,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2184129,6291456,2184161,6291456,2184193,6291456,6291456,6291456,6291456,6291456,2146818,2183361,6291456,6291456,2142978,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2135170,2097506,2130691,2130787,2130883,2163970,2164034,2164098,2164162,2164226,2164290,2164354,2164418,2164482,2164546,2133122]), + new Uint32Array([2108515,2108611,2100740,2108707,2108803,2108899,2108995,2109091,2109187,2109283,2109379,2109475,2109571,2109667,2109763,2100738]), + new Uint32Array([2102788,2102916,2103044,2120515,2103172,2120611,2120707,2098373,2103300,2120803,2120899,2120995,2103428,2103556,2121091,2121187]), + new Uint32Array([2158082,2158146,0,2158210,2158274,0,2158338,2158402,2158466,2129922,2158530,2158594,2158658,2158722,2158786,2158850]), + new Uint32Array([10499619,10499715,10499811,10499907,10500003,10500099,10500195,10500291,10500387,10500483,10500579,10500675,10500771,10500867,10500963,10501059]), + new Uint32Array([2239585,2239618,2239681,2239713,0,2191969,2239745,2239777,2192033,2239809,2239841,2239874,2239937,2239970,2240033,2240065]), + new Uint32Array([2252705,2252738,2252801,2252833,2252865,2252897,2252930,2252994,2253057,2253089,2253121,2253154,2253217,2253250,2219361,2219361]), + new Uint32Array([2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,10538050,10538114,10538178,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2226402,2226466,2226530,2226594,2226658,2226722,2226786,2226850,2226914,2226978,2227042,2227106,2227170,2227234,2227298,2227362]), + new Uint32Array([23068672,6291456,6291456,6291456,6291456,2144066,2144130,2144194,2144258,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,6291456,23068672,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0]), + new Uint32Array([2124674,2124770,2123875,2123971,2124067,2124163,2124259,2124355,2124451,2124547,2124643,2124739,2124835,2124931,2125027,2125123]), + new Uint32Array([2168065,6291456,2168097,6291456,2168129,6291456,2168161,6291456,2168193,6291456,2168225,6291456,2168257,6291456,2168289,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0]), + new Uint32Array([23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,2100610,2100611,6291456,2107842,2107843,6291456,6291456,6291456,6291456,10537922,6291456,10537986,6291456]), + new Uint32Array([2174849,2174881,2174913,2174945,2174977,2175009,2175041,2175073,2175105,2175137,2175169,2175201,2175233,2175265,2175297,2175329]), + new Uint32Array([2154562,2154626,2154690,2154754,2141858,2154818,2154882,2127298,2154946,2127298,2155010,2155074,2155138,2155202,2155266,2155202]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,23068672,0]), + new Uint32Array([2200641,2150786,2150850,2150914,2150978,2151042,2106562,2151106,2150562,2151170,2151234,2151298,2151362,2151426,2151490,2151554]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0,6291456,6291456]), + new Uint32Array([2220289,2220289,2220321,2220321,2220321,2220321,2220353,2220353,2220353,2220353,2220385,2220385,2220385,2220385,2220417,2220417]), + new Uint32Array([2155330,2155394,0,2155458,2155522,2155586,2105732,0,2155650,2155714,2155778,2125314,2155842,2155906,2126274,2155970]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,6291456,6291456,23068672,23068672,6291456,23068672,23068672,23068672,23068672,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0]), + new Uint32Array([2097729,2106017,2106017,2106017,2106017,2131297,2131297,2131297,2131297,2106081,2106081,2162049,2162049,2105953,2105953,2162337]), + new Uint32Array([2097185,2097697,2097697,2097697,2097697,2135777,2135777,2135777,2135777,2097377,2097377,2097377,2097377,2097601,2097601,2097217]), + new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,23068672]), + new Uint32Array([2139331,2139427,2139523,2139043,2133571,2132611,2139619,2139715,0,0,0,0,0,0,0,0]), + new Uint32Array([2174113,2174145,2100897,2098177,2108289,2100865,2173601,2173633,2173985,2174113,2174145,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,23068672,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,18923778,23068672,23068672,23068672,23068672,18923842,23068672,23068672,23068672,23068672,18923906,23068672,23068672,23068672]), + new Uint32Array([2134145,2097153,2134241,0,2132705,2130977,2160065,2131297,0,2133089,0,2133857,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2177537,6291456,2177569,6291456,2177601,6291456,2177633,6291456,2177665,6291456,2177697,6291456,2177729,6291456,2177761,6291456]), + new Uint32Array([2212481,2212513,2212545,2212577,2197121,2212609,2212641,2212673,2212705,2212737,2212769,2212801,2212833,2212865,2212897,2212929]), + new Uint32Array([6291456,6291456,23068672,23068672,23068672,6291456,6291456,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2098241,2108353,2170209,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,6291456,2108193,2172417,2112481,2098177]), + new Uint32Array([6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456]), + ]; + var blockIdxes = new Uint16Array([616,616,565,147,161,411,330,2,131,131,328,454,241,408,86,86,696,113,285,350,325,301,473,214,639,232,447,64,369,598,124,672,567,223,621,154,107,86,86,86,86,86,86,505,86,68,634,86,218,218,218,218,486,218,218,513,188,608,216,86,217,463,668,85,700,360,184,86,86,86,647,402,153,10,346,718,662,260,145,298,117,1,443,342,138,54,563,86,240,572,218,70,387,86,118,460,641,602,86,86,306,218,86,692,86,86,86,86,86,162,707,86,458,26,86,218,638,86,86,86,86,86,65,449,86,86,306,183,86,58,391,667,86,157,131,131,131,131,86,433,131,406,31,218,247,86,86,693,218,581,351,86,438,295,69,462,45,126,173,650,14,295,69,97,168,187,641,78,523,390,69,108,287,664,173,219,83,295,69,108,431,426,173,694,412,115,628,52,257,398,641,118,501,121,69,579,151,423,173,620,464,121,69,382,151,476,173,27,53,121,86,594,578,226,173,86,632,130,86,96,228,268,641,622,563,86,86,21,148,650,131,131,321,43,144,343,381,531,131,131,178,20,86,399,156,375,164,541,30,60,715,198,92,118,131,131,86,86,306,407,86,280,457,196,488,358,131,131,244,86,86,143,86,86,86,86,86,667,563,86,86,86,86,86,86,86,86,86,86,86,86,86,336,363,86,86,336,86,86,380,678,67,86,86,86,678,86,86,86,512,86,307,86,708,86,86,86,86,86,528,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,563,307,86,86,86,86,86,104,450,337,86,720,86,32,450,397,86,86,86,587,218,558,708,708,293,708,86,86,86,86,86,694,205,86,8,86,86,86,86,549,86,667,697,697,679,86,458,460,86,86,650,86,708,543,86,86,86,245,86,86,86,140,218,127,708,708,458,197,131,131,131,131,500,86,86,483,251,86,306,510,515,86,722,86,86,86,65,201,86,86,483,580,470,86,86,86,368,131,131,131,694,114,110,555,86,86,123,721,163,142,713,418,86,317,675,209,218,218,218,371,545,592,629,490,603,199,46,320,525,680,310,279,388,111,42,252,593,607,235,617,410,377,50,548,135,356,17,520,189,116,392,600,349,332,482,699,690,535,119,106,451,71,152,667,131,218,218,265,671,637,492,504,533,683,269,269,658,86,86,86,86,86,86,86,86,86,491,619,86,86,6,86,86,86,86,86,86,86,86,86,86,86,229,86,86,86,86,86,86,86,86,86,86,86,86,667,86,86,171,131,118,131,656,206,234,571,89,334,670,246,311,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,534,86,86,86,86,86,86,82,86,86,86,86,86,430,86,86,86,86,86,86,86,86,86,599,86,324,86,470,69,640,264,131,626,101,174,86,86,667,233,105,73,374,394,221,204,84,28,326,86,86,471,86,86,86,109,573,86,171,200,200,200,200,218,218,86,86,86,86,460,131,131,131,86,506,86,86,86,86,86,220,404,34,614,47,442,305,25,612,338,601,648,7,344,255,131,131,51,86,312,507,563,86,86,86,86,588,86,86,86,86,86,530,511,86,458,3,435,384,556,522,230,527,86,118,86,86,717,86,137,273,79,181,484,23,93,112,655,249,417,703,370,87,98,313,684,585,155,465,596,481,695,18,416,428,61,701,706,282,643,495,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,549,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,549,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,307,86,86,86,171,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,650,131,422,542,420,263,24,172,86,86,86,86,86,566,86,86,132,540,395,353,494,519,19,485,284,472,131,131,131,16,714,86,211,708,86,86,86,694,698,86,86,483,704,708,218,272,86,86,120,86,159,478,86,307,247,86,86,663,597,459,627,667,86,86,277,455,39,302,86,250,86,86,86,271,99,452,306,281,329,400,200,86,86,362,549,352,646,461,323,586,86,86,4,708,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,717,86,518,86,86,650,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,125,554,480,300,613,72,333,288,561,544,604,48,719,91,169,176,590,224,76,191,29,559,560,231,537,166,477,538,256,437,131,131,469,167,40,0,685,266,441,705,239,642,475,568,640,610,299,673,517,318,385,22,202,180,179,359,424,215,90,66,521,653,467,682,453,409,479,88,131,661,35,303,15,262,666,630,712,131,131,618,659,175,218,195,347,193,227,261,150,165,709,546,294,569,710,270,413,376,524,55,242,38,419,529,170,657,3,304,122,379,278,131,651,86,67,576,458,458,131,131,86,86,86,86,86,86,86,118,309,86,86,547,86,86,86,86,667,650,664,131,131,86,86,56,131,131,131,131,131,131,131,131,86,307,86,86,86,664,238,650,86,86,717,86,118,86,86,315,86,59,86,86,574,549,131,131,340,57,436,86,86,86,86,86,86,458,708,499,691,62,86,650,86,86,694,86,86,86,319,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,171,86,549,694,131,131,131,131,131,131,131,131,131,77,86,86,139,86,502,86,86,86,667,595,131,131,131,86,12,86,13,86,609,131,131,131,131,86,86,86,625,86,669,86,86,182,129,86,5,694,104,86,86,86,86,131,131,86,86,386,171,86,86,86,345,86,324,86,589,86,213,36,131,131,131,131,131,86,86,86,86,104,131,131,131,141,290,80,677,86,86,86,267,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,667,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,515,86,86,33,136,669,86,711,515,86,86,550,640,86,104,708,515,86,159,372,717,86,86,444,515,86,86,663,37,86,563,460,86,390,624,702,131,131,131,131,389,59,708,86,86,341,208,708,635,295,69,108,431,508,100,190,131,131,131,131,131,131,131,131,86,86,86,649,516,660,131,131,86,86,86,218,631,708,131,131,131,131,131,131,131,131,131,131,86,86,341,575,238,514,131,131,86,86,86,218,291,708,307,131,86,86,306,367,708,131,131,131,86,378,697,86,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,615,253,86,86,86,292,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,104,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,69,86,341,553,549,86,307,86,86,645,275,455,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,708,131,131,131,131,131,131,86,86,86,86,86,86,667,460,86,86,86,86,86,86,86,86,86,86,86,86,717,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,667,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,171,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,104,86,667,459,131,131,131,131,131,131,86,458,225,86,86,86,516,549,11,390,405,86,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,460,44,218,197,711,515,131,131,131,131,664,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,307,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,308,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,640,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,118,307,104,286,591,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,549,86,86,681,86,86,75,185,314,582,86,358,496,474,86,104,131,86,86,86,86,146,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,171,86,640,131,131,131,131,131,131,131,131,246,503,689,339,674,81,258,415,439,128,562,366,414,246,503,689,583,222,557,316,636,665,186,355,95,670,246,503,689,339,674,557,258,415,439,186,355,95,670,246,503,689,446,644,536,652,331,532,335,440,274,421,297,570,74,425,364,425,606,552,403,509,134,365,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,218,218,218,498,218,218,577,627,551,497,572,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,553,354,236,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,296,455,131,131,456,243,103,86,41,459,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,9,276,158,716,393,564,383,489,401,654,210,654,131,131,131,640,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,650,86,86,86,86,86,86,717,667,563,563,563,86,549,102,686,133,246,605,86,448,86,86,207,307,131,131,131,641,86,177,611,445,373,194,584,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,308,307,171,86,86,86,86,86,86,86,717,86,86,86,86,86,460,131,131,650,86,86,86,694,708,86,86,694,86,458,131,131,131,131,131,131,667,694,289,650,667,131,131,86,640,131,131,664,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,171,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,460,86,86,86,86,86,86,86,86,86,86,86,86,86,458,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,640,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,466,203,149,429,94,432,160,687,539,63,237,283,192,248,348,259,427,526,396,676,254,468,487,212,327,623,49,633,322,493,434,688,357,361,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131]); + var mappingStr = "صلى الله عليه وسلمجل جلالهキロメートルrad∕s2エスクードキログラムキロワットグラムトンクルゼイロサンチームパーセントピアストルファラッドブッシェルヘクタールマンションミリバールレントゲン′′′′1⁄10viii(10)(11)(12)(13)(14)(15)(16)(17)(18)(19)(20)∫∫∫∫(오전)(오후)アパートアルファアンペアイニングエーカーカラットカロリーキュリーギルダークローネサイクルシリングバーレルフィートポイントマイクロミクロンメガトンリットルルーブル株式会社kcalm∕s2c∕kgاكبرمحمدصلعمرسولریال1⁄41⁄23⁄4 ̈́ྲཱྀླཱྀ ̈͂ ̓̀ ̓́ ̓͂ ̔̀ ̔́ ̔͂ ̈̀‵‵‵a/ca/sc/oc/utelfax1⁄71⁄91⁄32⁄31⁄52⁄53⁄54⁄51⁄65⁄61⁄83⁄85⁄87⁄8xii0⁄3∮∮∮(1)(2)(3)(4)(5)(6)(7)(8)(9)(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)(q)(r)(s)(t)(u)(v)(w)(x)(y)(z)::====(ᄀ)(ᄂ)(ᄃ)(ᄅ)(ᄆ)(ᄇ)(ᄉ)(ᄋ)(ᄌ)(ᄎ)(ᄏ)(ᄐ)(ᄑ)(ᄒ)(가)(나)(다)(라)(마)(바)(사)(아)(자)(차)(카)(타)(파)(하)(주)(一)(二)(三)(四)(五)(六)(七)(八)(九)(十)(月)(火)(水)(木)(金)(土)(日)(株)(有)(社)(名)(特)(財)(祝)(労)(代)(呼)(学)(監)(企)(資)(協)(祭)(休)(自)(至)pte10月11月12月ergltdアールインチウォンオンスオームカイリガロンガンマギニーケースコルナコーポセンチダースノットハイツパーツピクルフランペニヒヘルツペンスページベータボルトポンドホールホーンマイルマッハマルクヤードヤールユアンルピー10点11点12点13点14点15点16点17点18点19点20点21点22点23点24点hpabardm2dm3khzmhzghzthzmm2cm2km2mm3cm3km3kpampagpalogmilmolppmv∕ma∕m10日11日12日13日14日15日16日17日18日19日20日21日22日23日24日25日26日27日28日29日30日31日galffifflשּׁשּׂ ٌّ ٍّ َّ ُّ ِّ ّٰـَّـُّـِّتجمتحجتحمتخمتمجتمحتمخجمححميحمىسحجسجحسجىسمحسمجسممصححصممشحمشجيشمخشممضحىضخمطمحطممطميعجمعممعمىغممغميغمىفخمقمحقمملحملحيلحىلججلخملمحمحجمحيمجحمجممخممجخهمجهممنحمنحىنجمنجىنمينمىيممبخيتجيتجىتخيتخىتميتمىجميجحىجمىسخىصحيشحيضحيلجيلمييحييجييميمميقمينحيعميكمينجحمخيلجمكممجحيحجيمجيفميبحيسخينجيصلےقلے𝅘𝅥𝅮𝅘𝅥𝅯𝅘𝅥𝅰𝅘𝅥𝅱𝅘𝅥𝅲𝆹𝅥𝅮𝆺𝅥𝅮𝆹𝅥𝅯𝆺𝅥𝅯〔s〕ppv〔本〕〔三〕〔二〕〔安〕〔点〕〔打〕〔盗〕〔勝〕〔敗〕 ̄ ́ ̧ssi̇ijl·ʼndžljnjdz ̆ ̇ ̊ ̨ ̃ ̋ ιեւاٴوٴۇٴيٴक़ख़ग़ज़ड़ढ़फ़य़ড়ঢ়য়ਲ਼ਸ਼ਖ਼ਗ਼ਜ਼ਫ਼ଡ଼ଢ଼ําໍາຫນຫມགྷཌྷདྷབྷཛྷཀྵཱཱིུྲྀླྀྒྷྜྷྡྷྦྷྫྷྐྵaʾἀιἁιἂιἃιἄιἅιἆιἇιἠιἡιἢιἣιἤιἥιἦιἧιὠιὡιὢιὣιὤιὥιὦιὧιὰιαιάιᾶι ͂ὴιηιήιῆιὼιωιώιῶι ̳!! ̅???!!?rs°c°fnosmtmivix⫝̸ ゙ ゚よりコト333435참고주의363738394042444546474849503月4月5月6月7月8月9月hgevギガデシドルナノピコビルペソホンリラレムdaauovpciu平成昭和大正明治naμakakbmbgbpfnfμfμgmgμlmldlklfmnmμmpsnsμsmsnvμvkvpwnwμwmwkwkωmωbqcccddbgyhainkkktlnlxphprsrsvwbstմնմեմիվնմխיִײַשׁשׂאַאָאּבּגּדּהּוּזּטּיּךּכּלּמּנּסּףּפּצּקּרּתּוֹבֿכֿפֿאלئائەئوئۇئۆئۈئېئىئجئحئمئيبجبمبىبيتىتيثجثمثىثيخحضجضمطحظمغجفجفحفىفيقحقىقيكاكجكحكخكلكىكينخنىنيهجهىهييىذٰرٰىٰئرئزئنبزبنترتزتنثرثزثنمانرنزننيريزئخئهبهتهصخنههٰثهسهشهطىطيعىعيغىغيسىسيشىشيصىصيضىضيشخشرسرصرضراً ًـًـّ ْـْلآلألإ𝅗𝅥0,1,2,3,4,5,6,7,8,9,wzhvsdwcmcmddjほかココàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþāăąćĉċčďđēĕėęěĝğġģĥħĩīĭįĵķĺļľłńņňŋōŏőœŕŗřśŝşšţťŧũūŭůűųŵŷÿźżɓƃƅɔƈɖɗƌǝəɛƒɠɣɩɨƙɯɲɵơƣƥʀƨʃƭʈưʊʋƴƶʒƹƽǎǐǒǔǖǘǚǜǟǡǣǥǧǩǫǭǯǵƕƿǹǻǽǿȁȃȅȇȉȋȍȏȑȓȕȗșțȝȟƞȣȥȧȩȫȭȯȱȳⱥȼƚⱦɂƀʉʌɇɉɋɍɏɦɹɻʁʕͱͳʹͷ;ϳέίόύβγδεζθκλνξοπρστυφχψϊϋϗϙϛϝϟϡϣϥϧϩϫϭϯϸϻͻͼͽѐёђѓєѕіїјљњћќѝўџабвгдежзийклмнопрстуфхцчшщъыьэюяѡѣѥѧѩѫѭѯѱѳѵѷѹѻѽѿҁҋҍҏґғҕҗҙқҝҟҡңҥҧҩҫҭүұҳҵҷҹһҽҿӂӄӆӈӊӌӎӑӓӕӗәӛӝӟӡӣӥӧөӫӭӯӱӳӵӷӹӻӽӿԁԃԅԇԉԋԍԏԑԓԕԗԙԛԝԟԡԣԥԧԩԫԭԯաբգդզէըթժլծկհձղճյշոչպջռստրցփքօֆ་ⴧⴭნᏰᏱᏲᏳᏴᏵꙋɐɑᴂɜᴖᴗᴝᴥɒɕɟɡɥɪᵻʝɭᶅʟɱɰɳɴɸʂƫᴜʐʑḁḃḅḇḉḋḍḏḑḓḕḗḙḛḝḟḡḣḥḧḩḫḭḯḱḳḵḷḹḻḽḿṁṃṅṇṉṋṍṏṑṓṕṗṙṛṝṟṡṣṥṧṩṫṭṯṱṳṵṷṹṻṽṿẁẃẅẇẉẋẍẏẑẓẕạảấầẩẫậắằẳẵặẹẻẽếềểễệỉịọỏốồổỗộớờởỡợụủứừửữựỳỵỷỹỻỽỿἐἑἒἓἔἕἰἱἲἳἴἵἶἷὀὁὂὃὄὅὑὓὕὗᾰᾱὲΐῐῑὶΰῠῡὺῥ`ὸ‐+−∑〈〉ⰰⰱⰲⰳⰴⰵⰶⰷⰸⰹⰺⰻⰼⰽⰾⰿⱀⱁⱂⱃⱄⱅⱆⱇⱈⱉⱊⱋⱌⱍⱎⱏⱐⱑⱒⱓⱔⱕⱖⱗⱘⱙⱚⱛⱜⱝⱞⱡɫᵽɽⱨⱪⱬⱳⱶȿɀⲁⲃⲅⲇⲉⲋⲍⲏⲑⲓⲕⲗⲙⲛⲝⲟⲡⲣⲥⲧⲩⲫⲭⲯⲱⲳⲵⲷⲹⲻⲽⲿⳁⳃⳅⳇⳉⳋⳍⳏⳑⳓⳕⳗⳙⳛⳝⳟⳡⳣⳬⳮⳳⵡ母龟丨丶丿乙亅亠人儿入冂冖冫几凵刀力勹匕匚匸卜卩厂厶又口囗士夂夊夕女子宀寸小尢尸屮山巛工己巾干幺广廴廾弋弓彐彡彳心戈戶手支攴文斗斤方无曰欠止歹殳毋比毛氏气爪父爻爿片牙牛犬玄玉瓜瓦甘生用田疋疒癶白皮皿目矛矢石示禸禾穴立竹米糸缶网羊羽老而耒耳聿肉臣臼舌舛舟艮色艸虍虫血行衣襾見角言谷豆豕豸貝赤走足身車辛辰辵邑酉釆里長門阜隶隹雨靑非面革韋韭音頁風飛食首香馬骨高髟鬥鬯鬲鬼魚鳥鹵鹿麥麻黃黍黑黹黽鼎鼓鼠鼻齊齒龍龜龠.〒卄卅ᄁᆪᆬᆭᄄᆰᆱᆲᆳᆴᆵᄚᄈᄡᄊ짜ᅢᅣᅤᅥᅦᅧᅨᅩᅪᅫᅬᅭᅮᅯᅰᅱᅲᅳᅴᅵᄔᄕᇇᇈᇌᇎᇓᇗᇙᄜᇝᇟᄝᄞᄠᄢᄣᄧᄩᄫᄬᄭᄮᄯᄲᄶᅀᅇᅌᇱᇲᅗᅘᅙᆄᆅᆈᆑᆒᆔᆞᆡ上中下甲丙丁天地問幼箏우秘男適優印注項写左右医宗夜テヌモヨヰヱヲꙁꙃꙅꙇꙉꙍꙏꙑꙓꙕꙗꙙꙛꙝꙟꙡꙣꙥꙧꙩꙫꙭꚁꚃꚅꚇꚉꚋꚍꚏꚑꚓꚕꚗꚙꚛꜣꜥꜧꜩꜫꜭꜯꜳꜵꜷꜹꜻꜽꜿꝁꝃꝅꝇꝉꝋꝍꝏꝑꝓꝕꝗꝙꝛꝝꝟꝡꝣꝥꝧꝩꝫꝭꝯꝺꝼᵹꝿꞁꞃꞅꞇꞌꞑꞓꞗꞙꞛꞝꞟꞡꞣꞥꞧꞩɬʞʇꭓꞵꞷꬷꭒᎠᎡᎢᎣᎤᎥᎦᎧᎨᎩᎪᎫᎬᎭᎮᎯᎰᎱᎲᎳᎴᎵᎶᎷᎸᎹᎺᎻᎼᎽᎾᎿᏀᏁᏂᏃᏄᏅᏆᏇᏈᏉᏊᏋᏌᏍᏎᏏᏐᏑᏒᏓᏔᏕᏖᏗᏘᏙᏚᏛᏜᏝᏞᏟᏠᏡᏢᏣᏤᏥᏦᏧᏨᏩᏪᏫᏬᏭᏮᏯ豈更賈滑串句契喇奈懶癩羅蘿螺裸邏樂洛烙珞落酪駱亂卵欄爛蘭鸞嵐濫藍襤拉臘蠟廊朗浪狼郎來冷勞擄櫓爐盧蘆虜路露魯鷺碌祿綠菉錄論壟弄籠聾牢磊賂雷壘屢樓淚漏累縷陋勒肋凜凌稜綾菱陵讀拏諾丹寧怒率異北磻便復不泌數索參塞省葉說殺沈拾若掠略亮兩凉梁糧良諒量勵呂廬旅濾礪閭驪麗黎曆歷轢年憐戀撚漣煉璉秊練聯輦蓮連鍊列劣咽烈裂廉念捻殮簾獵令囹嶺怜玲瑩羚聆鈴零靈領例禮醴隸惡了僚寮尿料燎療蓼遼暈阮劉杻柳流溜琉留硫紐類戮陸倫崙淪輪律慄栗隆利吏履易李梨泥理痢罹裏裡離匿溺吝燐璘藺隣鱗麟林淋臨笠粒狀炙識什茶刺切度拓糖宅洞暴輻降廓兀嗀塚晴凞猪益礼神祥福靖精蘒諸逸都飯飼館鶴郞隷侮僧免勉勤卑喝嘆器塀墨層悔慨憎懲敏既暑梅海渚漢煮爫琢碑祉祈祐祖禍禎穀突節縉繁署者臭艹著褐視謁謹賓贈辶難響頻恵𤋮舘並况全侀充冀勇勺啕喙嗢墳奄奔婢嬨廒廙彩徭惘慎愈慠戴揄搜摒敖望杖滛滋瀞瞧爵犯瑱甆画瘝瘟盛直睊着磌窱类絛缾荒華蝹襁覆調請諭變輸遲醙鉶陼韛頋鬒𢡊𢡄𣏕㮝䀘䀹𥉉𥳐𧻓齃龎עםٱٻپڀٺٿٹڤڦڄڃچڇڍڌڎڈژڑکگڳڱںڻۀہھۓڭۋۅۉ、〖〗—–_{}【】《》「」『』[]#&*-<>\\$%@ءؤة\"'^|~⦅⦆・ゥャ¢£¬¦¥₩│←↑→↓■○𐐨𐐩𐐪𐐫𐐬𐐭𐐮𐐯𐐰𐐱𐐲𐐳𐐴𐐵𐐶𐐷𐐸𐐹𐐺𐐻𐐼𐐽𐐾𐐿𐑀𐑁𐑂𐑃𐑄𐑅𐑆𐑇𐑈𐑉𐑊𐑋𐑌𐑍𐑎𐑏𐓘𐓙𐓚𐓛𐓜𐓝𐓞𐓟𐓠𐓡𐓢𐓣𐓤𐓥𐓦𐓧𐓨𐓩𐓪𐓫𐓬𐓭𐓮𐓯𐓰𐓱𐓲𐓳𐓴𐓵𐓶𐓷𐓸𐓹𐓺𐓻𐳀𐳁𐳂𐳃𐳄𐳅𐳆𐳇𐳈𐳉𐳊𐳋𐳌𐳍𐳎𐳏𐳐𐳑𐳒𐳓𐳔𐳕𐳖𐳗𐳘𐳙𐳚𐳛𐳜𐳝𐳞𐳟𐳠𐳡𐳢𐳣𐳤𐳥𐳦𐳧𐳨𐳩𐳪𐳫𐳬𐳭𐳮𐳯𐳰𐳱𐳲𑣀𑣁𑣂𑣃𑣄𑣅𑣆𑣇𑣈𑣉𑣊𑣋𑣌𑣍𑣎𑣏𑣐𑣑𑣒𑣓𑣔𑣕𑣖𑣗𑣘𑣙𑣚𑣛𑣜𑣝𑣞𑣟ıȷ∇∂𞤢𞤣𞤤𞤥𞤦𞤧𞤨𞤩𞤪𞤫𞤬𞤭𞤮𞤯𞤰𞤱𞤲𞤳𞤴𞤵𞤶𞤷𞤸𞤹𞤺𞤻𞤼𞤽𞤾𞤿𞥀𞥁𞥂𞥃ٮڡٯ字双多解交映無前後再新初終販声吹演投捕遊指禁空合満申割営配得可丽丸乁𠄢你侻倂偺備像㒞𠘺兔兤具𠔜㒹內𠕋冗冤仌冬𩇟刃㓟刻剆剷㔕包匆卉博即卽卿𠨬灰及叟𠭣叫叱吆咞吸呈周咢哶唐啓啣善喫喳嗂圖圗噑噴壮城埴堍型堲報墬𡓤売壷夆夢奢𡚨𡛪姬娛娧姘婦㛮嬈嬾𡧈寃寘寳𡬘寿将㞁屠峀岍𡷤嵃𡷦嵮嵫嵼巡巢㠯巽帨帽幩㡢𢆃㡼庰庳庶𪎒𢌱舁弢㣇𣊸𦇚形彫㣣徚忍志忹悁㤺㤜𢛔惇慈慌慺憲憤憯懞戛扝抱拔捐𢬌挽拼捨掃揤𢯱搢揅掩㨮摩摾撝摷㩬敬𣀊旣書晉㬙㬈㫤冒冕最暜肭䏙朡杞杓𣏃㭉柺枅桒𣑭梎栟椔楂榣槪檨𣚣櫛㰘次𣢧歔㱎歲殟殻𣪍𡴋𣫺汎𣲼沿泍汧洖派浩浸涅𣴞洴港湮㴳滇𣻑淹潮𣽞𣾎濆瀹瀛㶖灊災灷炭𠔥煅𤉣熜爨牐𤘈犀犕𤜵𤠔獺王㺬玥㺸瑇瑜璅瓊㼛甤𤰶甾𤲒𢆟瘐𤾡𤾸𥁄㿼䀈𥃳𥃲𥄙𥄳眞真瞋䁆䂖𥐝硎䃣𥘦𥚚𥛅秫䄯穊穏𥥼𥪧䈂𥮫篆築䈧𥲀糒䊠糨糣紀𥾆絣䌁緇縂繅䌴𦈨𦉇䍙𦋙罺𦌾羕翺𦓚𦔣聠𦖨聰𣍟䏕育脃䐋脾媵𦞧𦞵𣎓𣎜舄辞䑫芑芋芝劳花芳芽苦𦬼茝荣莭茣莽菧荓菊菌菜𦰶𦵫𦳕䔫蓱蓳蔖𧏊蕤𦼬䕝䕡𦾱𧃒䕫虐虧虩蚩蚈蜎蛢蜨蝫螆蟡蠁䗹衠𧙧裗裞䘵裺㒻𧢮𧥦䚾䛇誠𧲨貫賁贛起𧼯𠠄跋趼跰𠣞軔𨗒𨗭邔郱鄑𨜮鄛鈸鋗鋘鉼鏹鐕𨯺開䦕閷𨵷䧦雃嶲霣𩅅𩈚䩮䩶韠𩐊䪲𩒖頩𩖶飢䬳餩馧駂駾䯎𩬰鱀鳽䳎䳭鵧𪃎䳸𪄅𪈎𪊑䵖黾鼅鼏鼖𪘀"; + + function mapChar(codePoint) { + if (codePoint >= 0x30000) { + // High planes are special cased. + if (codePoint >= 0xE0100 && codePoint <= 0xE01EF) + return 18874368; + return 0; + } + return blocks[blockIdxes[codePoint >> 4]][codePoint & 15]; + } + + return { + mapStr: mappingStr, + mapChar: mapChar + }; + })); + + },{}],177:[function(require,module,exports){ + (function(root, factory) { + /* istanbul ignore next */ + if (typeof define === 'function' && define.amd) { + define(['punycode', './idna-map'], function(punycode, idna_map) { + return factory(punycode, idna_map); + }); + } + else if (typeof exports === 'object') { + module.exports = factory(require('punycode'), require('./idna-map')); + } + else { + root.uts46 = factory(root.punycode, root.idna_map); + } + }(this, function(punycode, idna_map) { + + function mapLabel(label, useStd3ASCII, transitional) { + var mapped = []; + var chars = punycode.ucs2.decode(label); + for (var i = 0; i < chars.length; i++) { + var cp = chars[i]; + var ch = punycode.ucs2.encode([chars[i]]); + var composite = idna_map.mapChar(cp); + var flags = (composite >> 23); + var kind = (composite >> 21) & 3; + var index = (composite >> 5) & 0xffff; + var length = composite & 0x1f; + var value = idna_map.mapStr.substr(index, length); + if (kind === 0 || (useStd3ASCII && (flags & 1))) { + throw new Error("Illegal char " + ch); + } + else if (kind === 1) { + mapped.push(value); + } + else if (kind === 2) { + mapped.push(transitional ? value : ch); + } + /* istanbul ignore next */ + else if (kind === 3) { + mapped.push(ch); + } + } + + var newLabel = mapped.join("").normalize("NFC"); + return newLabel; + } + + function process(domain, transitional, useStd3ASCII) { + /* istanbul ignore if */ + if (useStd3ASCII === undefined) + useStd3ASCII = false; + var mappedIDNA = mapLabel(domain, useStd3ASCII, transitional); + + // Step 3. Break + var labels = mappedIDNA.split("."); + + // Step 4. Convert/Validate + labels = labels.map(function(label) { + if (label.startsWith("xn--")) { + label = punycode.decode(label.substring(4)); + validateLabel(label, useStd3ASCII, false); + } + else { + validateLabel(label, useStd3ASCII, transitional); + } + return label; + }); + + return labels.join("."); + } + + function validateLabel(label, useStd3ASCII, transitional) { + // 2. The label must not contain a U+002D HYPHEN-MINUS character in both the + // third position and fourth positions. + if (label[2] === '-' && label[3] === '-') + throw new Error("Failed to validate " + label); + + // 3. The label must neither begin nor end with a U+002D HYPHEN-MINUS + // character. + if (label.startsWith('-') || label.endsWith('-')) + throw new Error("Failed to validate " + label); + + // 4. The label must not contain a U+002E ( . ) FULL STOP. + // this should nerver happen as label is chunked internally by this character + /* istanbul ignore if */ + if (label.includes('.')) + throw new Error("Failed to validate " + label); + + if (mapLabel(label, useStd3ASCII, transitional) !== label) + throw new Error("Failed to validate " + label); + + // 5. The label must not begin with a combining mark, that is: + // General_Category=Mark. + var ch = label.codePointAt(0); + if (idna_map.mapChar(ch) & (0x2 << 23)) + throw new Error("Label contains illegal character: " + ch); + } + + function toAscii(domain, options) { + if (options === undefined) + options = {}; + var transitional = 'transitional' in options ? options.transitional : true; + var useStd3ASCII = 'useStd3ASCII' in options ? options.useStd3ASCII : false; + var verifyDnsLength = 'verifyDnsLength' in options ? options.verifyDnsLength : false; + var labels = process(domain, transitional, useStd3ASCII).split('.'); + var asciiLabels = labels.map(punycode.toASCII); + var asciiString = asciiLabels.join('.'); + var i; + if (verifyDnsLength) { + if (asciiString.length < 1 || asciiString.length > 253) { + throw new Error("DNS name has wrong length: " + asciiString); + } + for (i = 0; i < asciiLabels.length; i++) {//for .. of replacement + var label = asciiLabels[i]; + if (label.length < 1 || label.length > 63) + throw new Error("DNS label has wrong length: " + label); + } + } + return asciiString; + } + + function toUnicode(domain, options) { + if (options === undefined) + options = {}; + var useStd3ASCII = 'useStd3ASCII' in options ? options.useStd3ASCII : false; + return process(domain, false, useStd3ASCII); + } + + return { + toUnicode: toUnicode, + toAscii: toAscii, + }; + })); + + },{"./idna-map":176,"punycode":265}],178:[function(require,module,exports){ + exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 + } + + },{}],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) { + if (arr[i] === obj) return i; + } + return -1; + }; + },{}],180:[function(require,module,exports){ + if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } + + },{}],181:[function(require,module,exports){ + /*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ + + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + module.exports = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) + } + + function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) + } + + },{}],182:[function(require,module,exports){ + 'use strict'; + + var fnToStr = Function.prototype.toString; + + var constructorRegex = /^\s*class\b/; + var isES6ClassFn = function isES6ClassFunction(value) { + try { + var fnStr = fnToStr.call(value); + return constructorRegex.test(fnStr); + } catch (e) { + return false; // not a function + } + }; + + var tryFunctionObject = function tryFunctionToStr(value) { + try { + if (isES6ClassFn(value)) { return false; } + fnToStr.call(value); + return true; + } catch (e) { + return false; + } + }; + var toStr = Object.prototype.toString; + 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; } + if (typeof value === 'function' && !value.prototype) { return true; } + if (hasToStringTag) { return tryFunctionObject(value); } + if (isES6ClassFn(value)) { return false; } + 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]' || + (typeof fn === 'function' && string !== '[object RegExp]') || + (typeof window !== 'undefined' && + // IE8 and below + (fn === window.setTimeout || + fn === window.alert || + fn === window.confirm || + fn === window.prompt)) + }; + + },{}],185:[function(require,module,exports){ + /** + * Returns a `Boolean` on whether or not the a `String` starts with '0x' + * @param {String} str the string input value + * @return {Boolean} a boolean if it is or is not hex prefixed + * @throws if the str input is not a string + */ + module.exports = function isHexPrefixed(str) { + if (typeof str !== 'string') { + throw new Error("[is-hex-prefixed] value must be type 'string', is currently type " + (typeof str) + ", while checking isHexPrefixed."); + } + + return str.slice(0, 2) === '0x'; + } + + },{}],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 () { + var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + nextDonePromise = getNextDoneCallback(); + _context.next = 3; + return nextDonePromise; + + case 3: + return _context.abrupt('return', undefined); + + case 4: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + return function getNextPromise() { + return _ref.apply(this, arguments); + }; + }(); + + var nextDonePromise = null; + var finishedPromise = asyncMiddleware(req, res, getNextPromise); + promiseToCallback(finishedPromise)(function (err) { + // async middleware ended + if (nextDonePromise) { + // next handler was called - complete nextHandler + promiseToCallback(nextDonePromise)(function (nextErr, nextHandlerSignalDone) { + // nextErr is only present if something went really wrong + // if an error is thrown after `await next()` it appears as `err` and not `nextErr` + if (nextErr) { + console.error(nextErr); + return end(nextErr); + } + nextHandlerSignalDone(err); + }); + } else { + // next handler was not called - complete middleware + end(err); + } + }); + + function getNextDoneCallback() { + return new Promise(function (resolve) { + next(function (cb) { + return resolve(cb); + }); + }); + } + }; + } + + },{"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) { + this._middleware.push(middleware); + } + }, { + key: 'handle', + value: function handle(req, cb) { + // batch request support + if (Array.isArray(req)) { + async.map(req, this._handle.bind(this), cb); + } else { + this._handle(req, cb); + } + } + + // + // Private + // + + }, { + key: '_handle', + value: function _handle(_req, cb) { + // shallow clone request object + var req = Object.assign({}, _req); + // create response obj + var res = { + id: req.id, + jsonrpc: req.jsonrpc + // process all middleware + };this._runMiddleware(req, res, function (err) { + // return response + cb(err, res); + }); + } + }, { + 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); + var message = 'JsonRpcEngine - response has no error or result for request:\n' + requestBody; + return cb(new Error(message)); + } + if (!isComplete) { + var _requestBody = JSON.stringify(req, null, 2); + var _message = 'JsonRpcEngine - nothing ended request:\n' + _requestBody; + return cb(new Error(_message)); + } + // 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) { + // for climbing back up the stack + 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); + cb(); + } + function end(err) { + if (err) return cb(err); + // mark as completed + isComplete = true; + cb(); + } + } + + // returns, indicating whether or not it ended + function completeRequest(err) { + if (err) { + // prepare error message + res.error = { + code: err.code || -32603, + message: err.stack + // return error-first and res with err + };return onDone(err, res); + } + var returnHandlers = allReturnHandlers.filter(Boolean).reverse(); + onDone(null, { isComplete: isComplete, returnHandlers: returnHandlers }); + } + } + + // climbs the stack calling return handlers + + }, { + key: '_runReturnHandlersUp', + value: function _runReturnHandlersUp(returnHandlers, cb) { + async.eachSeries(returnHandlers, function (handler, next) { + return handler(next); + }, 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 + escapee = { + '"': '"', + '\\': '\\', + '/': '/', + b: '\b', + f: '\f', + n: '\n', + r: '\r', + t: '\t' + }, + text, + + error = function (m) { + // Call error when something is wrong. + throw { + name: 'SyntaxError', + message: m, + at: at, + 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('-'); + } + while (ch >= '0' && ch <= '9') { + string += ch; + next(); + } + if (ch === '.') { + string += '.'; + while (next() && ch >= '0' && ch <= '9') { + string += ch; + } + } + if (ch === 'e' || ch === 'E') { + string += ch; + next(); + if (ch === '-' || ch === '+') { + string += ch; + next(); + } + while (ch >= '0' && ch <= '9') { + string += ch; + next(); + } + } + number = +string; + if (!isFinite(number)) { + error("Bad number"); + } else { + 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()) { + if (ch === '"') { + next(); + return string; + } else if (ch === '\\') { + next(); + if (ch === 'u') { + uffff = 0; + for (i = 0; i < 4; i += 1) { + hex = parseInt(next(), 16); + if (!isFinite(hex)) { + break; + } + uffff = uffff * 16 + hex; + } + string += String.fromCharCode(uffff); + } else if (typeof escapee[ch] === 'string') { + string += escapee[ch]; + } else { + break; + } + } else { + string += ch; + } + } + } + error("Bad string"); + }, + + white = function () { + + // Skip whitespace. + + while (ch && ch <= ' ') { + next(); + } + }, + + word = function () { + + // true, false, or null. + + switch (ch) { + case 't': + next('t'); + next('r'); + next('u'); + next('e'); + return true; + case 'f': + next('f'); + next('a'); + next('l'); + next('s'); + next('e'); + return false; + case 'n': + next('n'); + next('u'); + next('l'); + next('l'); + return null; + } + error("Unexpected '" + ch + "'"); + }, + + value, // Place holder for the value function. + + array = function () { + + // Parse an array value. + + var array = []; + + if (ch === '[') { + next('['); + white(); + if (ch === ']') { + next(']'); + return array; // empty array + } + while (ch) { + array.push(value()); + white(); + if (ch === ']') { + next(']'); + return array; + } + next(','); + white(); + } + } + error("Bad array"); + }, + + object = function () { + + // Parse an object value. + + var key, + object = {}; + + if (ch === '{') { + next('{'); + white(); + if (ch === '}') { + next('}'); + return object; // empty object + } + while (ch) { + key = string(); + white(); + next(':'); + if (Object.hasOwnProperty.call(object, key)) { + error('Duplicate key "' + key + '"'); + } + object[key] = value(); + white(); + if (ch === '}') { + next('}'); + return object; + } + next(','); + white(); + } + } + 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 '{': + return object(); + case '[': + return array(); + case '"': + return string(); + case '-': + return number(); + default: + 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 = ' '; + result = value(); + white(); + 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') { + for (k in value) { + if (Object.prototype.hasOwnProperty.call(value, k)) { + v = walk(value, k); + if (v !== undefined) { + value[k] = v; + } else { + delete value[k]; + } + } + } + } + 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, + gap, + indent, + meta = { // table of character substitutions + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + '"' : '\\"', + '\\': '\\\\' + }, + 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]; + return typeof c === 'string' ? c : + '\\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. + k, // The member key. + v, // The member value. + length, + 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 ? + '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : + '[' + partial.join(',') + ']'; + gap = mind; + return v; + } + + // If the replacer is an array, use it to select the members to be + // stringified. + if (rep && typeof rep === 'object') { + length = rep.length; + for (i = 0; i < length; i += 1) { + k = rep[i]; + if (typeof k === 'string') { + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } + else { + // Otherwise, iterate through all of the keys in the object. + for (k in value) { + if (Object.prototype.hasOwnProperty.call(value, k)) { + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } + + // 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(',') + '}'; + gap = mind; + 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') { + for (i = 0; i < space; i += 1) { + indent += ' '; + } + } + // If the space parameter is a string, it will be used as the indent string. + 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; + if (replacer && typeof replacer !== 'function' + && (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) { + case 'keccak224': return new Keccak(1152, 448, null, 224, options) + case 'keccak256': return new Keccak(1088, 512, null, 256, options) + case 'keccak384': return new Keccak(832, 768, null, 384, options) + case 'keccak512': return new Keccak(576, 1024, null, 512, options) + + case 'sha3-224': return new Keccak(1152, 448, 0x06, 224, options) + case 'sha3-256': return new Keccak(1088, 512, 0x06, 256, options) + case 'sha3-384': return new Keccak(832, 768, 0x06, 384, options) + case 'sha3-512': return new Keccak(576, 1024, 0x06, 512, options) + + case 'shake128': return new Shake(1344, 256, 0x1f, options) + case 'shake256': return new Shake(1088, 512, 0x1f, options) + + default: throw new Error('Invald algorithm: ' + algorithm) + } + } + } + + },{"./keccak":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 { + this.update(chunk, encoding) + } catch (err) { + error = err + } + + callback(error) + } + + Keccak.prototype._flush = function (callback) { + var error = null + try { + this.push(this.digest()) + } catch (err) { + error = err + } + + callback(error) + } + + Keccak.prototype.update = function (data, encoding) { + if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer') + if (this._finalized) throw new Error('Digest already called') + if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) + + this._state.absorb(data) + + return this + } + + Keccak.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true + + if (this._delimitedSuffix) this._state.absorbLastFewBits(this._delimitedSuffix) + var digest = this._state.squeeze(this._hashBitLength / 8) + if (encoding !== undefined) digest = digest.toString(encoding) + + this._resetState() + + return digest + } + + // remove result from memory + Keccak.prototype._resetState = function () { + this._state.initialize(this._rate, this._capacity) + return this + } + + // because sometimes we need hash right now and little later + Keccak.prototype._clone = function () { + var clone = new Keccak(this._rate, this._capacity, this._delimitedSuffix, this._hashBitLength, this._options) + this._state.copy(clone._state) + clone._finalized = this._finalized + + return clone + } + + return Keccak + } + + },{"inherits":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 { + this.update(chunk, encoding) + } catch (err) { + error = err + } + + callback(error) + } + + Shake.prototype._flush = function () {} + + Shake.prototype._read = function (size) { + this.push(this.squeeze(size)) + } + + Shake.prototype.update = function (data, encoding) { + if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer') + if (this._finalized) throw new Error('Squeeze already called') + if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) + + this._state.absorb(data) + + return this + } + + Shake.prototype.squeeze = function (dataByteLength, encoding) { + if (!this._finalized) { + this._finalized = true + this._state.absorbLastFewBits(this._delimitedSuffix) + } + + var data = this._state.squeeze(dataByteLength) + if (encoding !== undefined) data = data.toString(encoding) + + return data + } + + Shake.prototype._resetState = function () { + this._state.initialize(this._rate, this._capacity) + return this + } + + Shake.prototype._clone = function () { + var clone = new Shake(this._rate, this._capacity, this._delimitedSuffix, this._options) + this._state.copy(clone._state) + clone._finalized = this._finalized + + return clone + } + + return Shake + } + + },{"inherits":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 + var lo0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40] + var hi0 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41] + var lo1 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42] + var hi1 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43] + var lo2 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44] + var hi2 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45] + var lo3 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46] + var hi3 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47] + var lo4 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48] + var hi4 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49] + + var lo = lo4 ^ (lo1 << 1 | hi1 >>> 31) + var hi = hi4 ^ (hi1 << 1 | lo1 >>> 31) + var t1slo0 = s[0] ^ lo + var t1shi0 = s[1] ^ hi + var t1slo5 = s[10] ^ lo + var t1shi5 = s[11] ^ hi + var t1slo10 = s[20] ^ lo + var t1shi10 = s[21] ^ hi + var t1slo15 = s[30] ^ lo + var t1shi15 = s[31] ^ hi + var t1slo20 = s[40] ^ lo + var t1shi20 = s[41] ^ hi + lo = lo0 ^ (lo2 << 1 | hi2 >>> 31) + hi = hi0 ^ (hi2 << 1 | lo2 >>> 31) + var t1slo1 = s[2] ^ lo + var t1shi1 = s[3] ^ hi + var t1slo6 = s[12] ^ lo + var t1shi6 = s[13] ^ hi + var t1slo11 = s[22] ^ lo + var t1shi11 = s[23] ^ hi + var t1slo16 = s[32] ^ lo + var t1shi16 = s[33] ^ hi + var t1slo21 = s[42] ^ lo + var t1shi21 = s[43] ^ hi + lo = lo1 ^ (lo3 << 1 | hi3 >>> 31) + hi = hi1 ^ (hi3 << 1 | lo3 >>> 31) + var t1slo2 = s[4] ^ lo + var t1shi2 = s[5] ^ hi + var t1slo7 = s[14] ^ lo + var t1shi7 = s[15] ^ hi + var t1slo12 = s[24] ^ lo + var t1shi12 = s[25] ^ hi + var t1slo17 = s[34] ^ lo + var t1shi17 = s[35] ^ hi + var t1slo22 = s[44] ^ lo + var t1shi22 = s[45] ^ hi + lo = lo2 ^ (lo4 << 1 | hi4 >>> 31) + hi = hi2 ^ (hi4 << 1 | lo4 >>> 31) + var t1slo3 = s[6] ^ lo + var t1shi3 = s[7] ^ hi + var t1slo8 = s[16] ^ lo + var t1shi8 = s[17] ^ hi + var t1slo13 = s[26] ^ lo + var t1shi13 = s[27] ^ hi + var t1slo18 = s[36] ^ lo + var t1shi18 = s[37] ^ hi + var t1slo23 = s[46] ^ lo + var t1shi23 = s[47] ^ hi + lo = lo3 ^ (lo0 << 1 | hi0 >>> 31) + hi = hi3 ^ (hi0 << 1 | lo0 >>> 31) + var t1slo4 = s[8] ^ lo + var t1shi4 = s[9] ^ hi + var t1slo9 = s[18] ^ lo + var t1shi9 = s[19] ^ hi + var t1slo14 = s[28] ^ lo + var t1shi14 = s[29] ^ hi + var t1slo19 = s[38] ^ lo + var t1shi19 = s[39] ^ hi + var t1slo24 = s[48] ^ lo + var t1shi24 = s[49] ^ hi + + // rho & pi + var t2slo0 = t1slo0 + var t2shi0 = t1shi0 + var t2slo16 = (t1shi5 << 4 | t1slo5 >>> 28) + var t2shi16 = (t1slo5 << 4 | t1shi5 >>> 28) + var t2slo7 = (t1slo10 << 3 | t1shi10 >>> 29) + var t2shi7 = (t1shi10 << 3 | t1slo10 >>> 29) + var t2slo23 = (t1shi15 << 9 | t1slo15 >>> 23) + var t2shi23 = (t1slo15 << 9 | t1shi15 >>> 23) + var t2slo14 = (t1slo20 << 18 | t1shi20 >>> 14) + var t2shi14 = (t1shi20 << 18 | t1slo20 >>> 14) + var t2slo10 = (t1slo1 << 1 | t1shi1 >>> 31) + var t2shi10 = (t1shi1 << 1 | t1slo1 >>> 31) + var t2slo1 = (t1shi6 << 12 | t1slo6 >>> 20) + var t2shi1 = (t1slo6 << 12 | t1shi6 >>> 20) + var t2slo17 = (t1slo11 << 10 | t1shi11 >>> 22) + var t2shi17 = (t1shi11 << 10 | t1slo11 >>> 22) + var t2slo8 = (t1shi16 << 13 | t1slo16 >>> 19) + var t2shi8 = (t1slo16 << 13 | t1shi16 >>> 19) + var t2slo24 = (t1slo21 << 2 | t1shi21 >>> 30) + var t2shi24 = (t1shi21 << 2 | t1slo21 >>> 30) + var t2slo20 = (t1shi2 << 30 | t1slo2 >>> 2) + var t2shi20 = (t1slo2 << 30 | t1shi2 >>> 2) + var t2slo11 = (t1slo7 << 6 | t1shi7 >>> 26) + var t2shi11 = (t1shi7 << 6 | t1slo7 >>> 26) + var t2slo2 = (t1shi12 << 11 | t1slo12 >>> 21) + var t2shi2 = (t1slo12 << 11 | t1shi12 >>> 21) + var t2slo18 = (t1slo17 << 15 | t1shi17 >>> 17) + var t2shi18 = (t1shi17 << 15 | t1slo17 >>> 17) + var t2slo9 = (t1shi22 << 29 | t1slo22 >>> 3) + var t2shi9 = (t1slo22 << 29 | t1shi22 >>> 3) + var t2slo5 = (t1slo3 << 28 | t1shi3 >>> 4) + var t2shi5 = (t1shi3 << 28 | t1slo3 >>> 4) + var t2slo21 = (t1shi8 << 23 | t1slo8 >>> 9) + var t2shi21 = (t1slo8 << 23 | t1shi8 >>> 9) + var t2slo12 = (t1slo13 << 25 | t1shi13 >>> 7) + var t2shi12 = (t1shi13 << 25 | t1slo13 >>> 7) + var t2slo3 = (t1slo18 << 21 | t1shi18 >>> 11) + var t2shi3 = (t1shi18 << 21 | t1slo18 >>> 11) + var t2slo19 = (t1shi23 << 24 | t1slo23 >>> 8) + var t2shi19 = (t1slo23 << 24 | t1shi23 >>> 8) + var t2slo15 = (t1slo4 << 27 | t1shi4 >>> 5) + var t2shi15 = (t1shi4 << 27 | t1slo4 >>> 5) + var t2slo6 = (t1slo9 << 20 | t1shi9 >>> 12) + var t2shi6 = (t1shi9 << 20 | t1slo9 >>> 12) + var t2slo22 = (t1shi14 << 7 | t1slo14 >>> 25) + var t2shi22 = (t1slo14 << 7 | t1shi14 >>> 25) + var t2slo13 = (t1slo19 << 8 | t1shi19 >>> 24) + var t2shi13 = (t1shi19 << 8 | t1slo19 >>> 24) + var t2slo4 = (t1slo24 << 14 | t1shi24 >>> 18) + var t2shi4 = (t1shi24 << 14 | t1slo24 >>> 18) + + // chi + s[0] = t2slo0 ^ (~t2slo1 & t2slo2) + s[1] = t2shi0 ^ (~t2shi1 & t2shi2) + s[10] = t2slo5 ^ (~t2slo6 & t2slo7) + s[11] = t2shi5 ^ (~t2shi6 & t2shi7) + s[20] = t2slo10 ^ (~t2slo11 & t2slo12) + s[21] = t2shi10 ^ (~t2shi11 & t2shi12) + s[30] = t2slo15 ^ (~t2slo16 & t2slo17) + s[31] = t2shi15 ^ (~t2shi16 & t2shi17) + s[40] = t2slo20 ^ (~t2slo21 & t2slo22) + s[41] = t2shi20 ^ (~t2shi21 & t2shi22) + s[2] = t2slo1 ^ (~t2slo2 & t2slo3) + s[3] = t2shi1 ^ (~t2shi2 & t2shi3) + s[12] = t2slo6 ^ (~t2slo7 & t2slo8) + s[13] = t2shi6 ^ (~t2shi7 & t2shi8) + s[22] = t2slo11 ^ (~t2slo12 & t2slo13) + s[23] = t2shi11 ^ (~t2shi12 & t2shi13) + s[32] = t2slo16 ^ (~t2slo17 & t2slo18) + s[33] = t2shi16 ^ (~t2shi17 & t2shi18) + s[42] = t2slo21 ^ (~t2slo22 & t2slo23) + s[43] = t2shi21 ^ (~t2shi22 & t2shi23) + s[4] = t2slo2 ^ (~t2slo3 & t2slo4) + s[5] = t2shi2 ^ (~t2shi3 & t2shi4) + s[14] = t2slo7 ^ (~t2slo8 & t2slo9) + s[15] = t2shi7 ^ (~t2shi8 & t2shi9) + s[24] = t2slo12 ^ (~t2slo13 & t2slo14) + s[25] = t2shi12 ^ (~t2shi13 & t2shi14) + s[34] = t2slo17 ^ (~t2slo18 & t2slo19) + s[35] = t2shi17 ^ (~t2shi18 & t2shi19) + s[44] = t2slo22 ^ (~t2slo23 & t2slo24) + s[45] = t2shi22 ^ (~t2shi23 & t2shi24) + s[6] = t2slo3 ^ (~t2slo4 & t2slo0) + s[7] = t2shi3 ^ (~t2shi4 & t2shi0) + s[16] = t2slo8 ^ (~t2slo9 & t2slo5) + s[17] = t2shi8 ^ (~t2shi9 & t2shi5) + s[26] = t2slo13 ^ (~t2slo14 & t2slo10) + s[27] = t2shi13 ^ (~t2shi14 & t2shi10) + s[36] = t2slo18 ^ (~t2slo19 & t2slo15) + s[37] = t2shi18 ^ (~t2shi19 & t2shi15) + s[46] = t2slo23 ^ (~t2slo24 & t2slo20) + s[47] = t2shi23 ^ (~t2shi24 & t2shi20) + s[8] = t2slo4 ^ (~t2slo0 & t2slo1) + s[9] = t2shi4 ^ (~t2shi0 & t2shi1) + s[18] = t2slo9 ^ (~t2slo5 & t2slo6) + s[19] = t2shi9 ^ (~t2shi5 & t2shi6) + s[28] = t2slo14 ^ (~t2slo10 & t2slo11) + s[29] = t2shi14 ^ (~t2shi10 & t2shi11) + s[38] = t2slo19 ^ (~t2slo15 & t2slo16) + s[39] = t2shi19 ^ (~t2shi15 & t2shi16) + s[48] = t2slo24 ^ (~t2slo20 & t2slo21) + s[49] = t2shi24 ^ (~t2shi20 & t2shi21) + + // iota + s[0] ^= P1600_ROUND_CONSTANTS[round * 2] + s[1] ^= P1600_ROUND_CONSTANTS[round * 2 + 1] + } + } + + },{}],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 = [ + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0 + ] + + this.blockSize = null + this.count = 0 + this.squeezing = false + } + + Keccak.prototype.initialize = function (rate, capacity) { + for (var i = 0; i < 50; ++i) this.state[i] = 0 + this.blockSize = rate / 8 + this.count = 0 + this.squeezing = false + } + + Keccak.prototype.absorb = function (data) { + for (var i = 0; i < data.length; ++i) { + this.state[~~(this.count / 4)] ^= data[i] << (8 * (this.count % 4)) + this.count += 1 + if (this.count === this.blockSize) { + keccakState.p1600(this.state) + this.count = 0 + } + } + } + + Keccak.prototype.absorbLastFewBits = function (bits) { + this.state[~~(this.count / 4)] ^= bits << (8 * (this.count % 4)) + if ((bits & 0x80) !== 0 && this.count === (this.blockSize - 1)) keccakState.p1600(this.state) + this.state[~~((this.blockSize - 1) / 4)] ^= 0x80 << (8 * ((this.blockSize - 1) % 4)) + keccakState.p1600(this.state) + this.count = 0 + this.squeezing = true + } + + Keccak.prototype.squeeze = function (length) { + if (!this.squeezing) this.absorbLastFewBits(0x01) + + var output = Buffer.alloc(length) + for (var i = 0; i < length; ++i) { + output[i] = (this.state[~~(this.count / 4)] >>> (8 * (this.count % 4))) & 0xff + this.count += 1 + if (this.count === this.blockSize) { + keccakState.p1600(this.state) + this.count = 0 + } + } + + return output + } + + Keccak.prototype.copy = function (dest) { + for (var i = 0; i < 50; ++i) dest.state[i] = this.state[i] + dest.blockSize = this.blockSize + dest.count = this.count + dest.squeezing = this.squeezing + } + + module.exports = Keccak + + },{"./keccak-state-unroll":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'), + isArray = require('./isArray'), + 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`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + 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 && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + 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. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? 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`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + 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]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + weakMapTag = '[object WeakMap]'; + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag] = + typedArrayTags[objectTag] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = false; + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + 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. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; + } + + module.exports = baseKeys; + + },{"./_isPrototype":212,"./_nativeKeys":213}],207:[function(require,module,exports){ + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + 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. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + 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. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ + 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) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + 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. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (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. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + 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`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + 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. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + 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`. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new constant function. + * @example + * + * var objects = _.times(2, _.constant({ 'a': 1 })); + * + * console.log(objects); + * // => [{ 'a': 1 }, { 'a': 1 }] + * + * console.log(objects[0] === objects[1]); + * // => true + */ + function constant(value) { + return function() { + 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. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + 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. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => 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 + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + 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. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => 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. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + 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. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + 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 + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + 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` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + 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. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => 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`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + 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`. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Util + * @example + * + * _.times(2, _.noop); + * // => [undefined, undefined] + */ + function noop() { + // No operation performed. + } + + module.exports = noop; + + },{}],230:[function(require,module,exports){ + /** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ + 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) + b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22) + a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7) + d = fnF(d, a, b, c, M[5], 0x4787c62a, 12) + c = fnF(c, d, a, b, M[6], 0xa8304613, 17) + b = fnF(b, c, d, a, M[7], 0xfd469501, 22) + a = fnF(a, b, c, d, M[8], 0x698098d8, 7) + d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12) + c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17) + b = fnF(b, c, d, a, M[11], 0x895cd7be, 22) + a = fnF(a, b, c, d, M[12], 0x6b901122, 7) + d = fnF(d, a, b, c, M[13], 0xfd987193, 12) + c = fnF(c, d, a, b, M[14], 0xa679438e, 17) + b = fnF(b, c, d, a, M[15], 0x49b40821, 22) + + a = fnG(a, b, c, d, M[1], 0xf61e2562, 5) + d = fnG(d, a, b, c, M[6], 0xc040b340, 9) + c = fnG(c, d, a, b, M[11], 0x265e5a51, 14) + b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20) + a = fnG(a, b, c, d, M[5], 0xd62f105d, 5) + d = fnG(d, a, b, c, M[10], 0x02441453, 9) + c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14) + b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20) + a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5) + d = fnG(d, a, b, c, M[14], 0xc33707d6, 9) + c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14) + b = fnG(b, c, d, a, M[8], 0x455a14ed, 20) + a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5) + d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9) + c = fnG(c, d, a, b, M[7], 0x676f02d9, 14) + b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20) + + a = fnH(a, b, c, d, M[5], 0xfffa3942, 4) + d = fnH(d, a, b, c, M[8], 0x8771f681, 11) + c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16) + b = fnH(b, c, d, a, M[14], 0xfde5380c, 23) + a = fnH(a, b, c, d, M[1], 0xa4beea44, 4) + d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11) + c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16) + b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23) + a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4) + d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11) + c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16) + b = fnH(b, c, d, a, M[6], 0x04881d05, 23) + a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4) + d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11) + c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16) + b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23) + + a = fnI(a, b, c, d, M[0], 0xf4292244, 6) + d = fnI(d, a, b, c, M[7], 0x432aff97, 10) + c = fnI(c, d, a, b, M[14], 0xab9423a7, 15) + b = fnI(b, c, d, a, M[5], 0xfc93a039, 21) + a = fnI(a, b, c, d, M[12], 0x655b59c3, 6) + d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10) + c = fnI(c, d, a, b, M[10], 0xffeff47d, 15) + b = fnI(b, c, d, a, M[1], 0x85845dd1, 21) + a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6) + d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10) + c = fnI(c, d, a, b, M[6], 0xa3014314, 15) + b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21) + a = fnI(a, b, c, d, M[4], 0xf7537e82, 6) + d = fnI(d, a, b, c, M[11], 0xbd3af235, 10) + c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15) + b = fnI(b, c, d, a, M[9], 0xeb86d391, 21) + + this._a = (this._a + a) | 0 + this._b = (this._b + b) | 0 + this._c = (this._c + c) | 0 + this._d = (this._d + d) | 0 + } + + MD5.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80 + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64) + this._update() + this._blockOffset = 0 + } + + this._block.fill(0, this._blockOffset, 56) + this._block.writeUInt32LE(this._length[0], 56) + this._block.writeUInt32LE(this._length[1], 60) + this._update() + + // produce result + var buffer = new Buffer(16) + buffer.writeInt32LE(this._a, 0) + buffer.writeInt32LE(this._b, 4) + buffer.writeInt32LE(this._c, 8) + buffer.writeInt32LE(this._d, 12) + return buffer + } + + function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) + } + + function fnF (a, b, c, d, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 + } + + function fnG (a, b, c, d, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 + } + + function fnH (a, b, c, d, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 + } + + function fnI (a, b, c, d, m, k, s) { + return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 + } + + module.exports = MD5 + + }).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 { + this.update(chunk, encoding) + } catch (err) { + error = err + } + + callback(error) + } + + HashBase.prototype._flush = function (callback) { + var error = null + try { + this.push(this.digest()) + } catch (err) { + error = err + } + + callback(error) + } + + HashBase.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data') + if (this._finalized) throw new Error('Digest already called') + if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) + + // consume data + var block = this._block + var offset = 0 + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] + this._update() + this._blockOffset = 0 + } + while (offset < data.length) block[this._blockOffset++] = data[offset++] + + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry + carry = (this._length[j] / 0x0100000000) | 0 + if (carry > 0) this._length[j] -= 0x0100000000 * carry + } + + return this + } + + HashBase.prototype._update = function () { + throw new Error('_update is not implemented') + } + + HashBase.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true + + var digest = this._digest() + if (encoding !== undefined) digest = digest.toString(encoding) + + // reset state + this._block.fill(0) + this._blockOffset = 0 + for (var i = 0; i < 4; ++i) this._length[i] = 0 + + return digest + } + + HashBase.prototype._digest = function () { + throw new Error('_digest is not implemented') + } + + module.exports = HashBase + + },{"inherits":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(); + if (!msg) + return []; + var res = []; + if (typeof msg !== 'string') { + for (var i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + return res; + } + if (enc === 'hex') { + msg = msg.replace(/[^a-z0-9]+/ig, ''); + if (msg.length % 2 !== 0) + msg = '0' + msg; + for (var i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } else { + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + var hi = c >> 8; + var lo = c & 0xff; + if (hi) + res.push(hi, lo); + else + res.push(lo); + } + } + return res; + } + utils.toArray = toArray; + + function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; + } + utils.zero2 = zero2; + + function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; + } + utils.toHex = toHex; + + utils.encode = function encode(arr, enc) { + if (enc === 'hex') + return toHex(arr); + else + return arr; + }; + + },{}],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 + * @return {Object} `output` BN object of the number + * @throws if the argument is not an array, object that isn't a bignumber, not a string number or number + */ + module.exports = function numberToBN(arg) { + if (typeof arg === 'string' || typeof arg === 'number') { + var multiplier = new BN(1); // eslint-disable-line + var formattedString = String(arg).toLowerCase().trim(); + var isHexPrefixed = formattedString.substr(0, 2) === '0x' || formattedString.substr(0, 3) === '-0x'; + var stringArg = stripHexPrefix(formattedString); // eslint-disable-line + if (stringArg.substr(0, 1) === '-') { + stringArg = stripHexPrefix(stringArg.slice(1)); + 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); + } + } else if (typeof arg === 'object' && arg.toString && (!arg.pop && !arg.push)) { + if (arg.toString(10).match(/^-?[0-9]+$/) && (arg.mul || arg.dividedToIntegerBy)) { + 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++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + '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++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + 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 + PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + */ + + /** + * 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"); + * // 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) + + 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; + + 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)]; + } + + return varArgs(function(startParams){ + + return foldR(next, startParams, fnsList)[0]; + }); + }); + + /** + * A more optimised version of compose that takes exactly two functions + * @param f1 + * @param f2 + */ + function compose2(f1, f2){ + return function(){ + 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 + * 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]) + * + * @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 + * 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 + * 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; + + + if( numberOfFixedArguments == 0 ) { + // 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 + + // 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); + + return function(){ + + for (var i = 0; i < numberOfFixedArguments; i++) { + argsHolder[i] = arguments[i]; + } + + argsHolder[numberOfFixedArguments] = + slice.call(arguments, numberOfFixedArguments); + + 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){ + return function(a, b){ + 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 + */ + function functor(val){ + return function(){ + return val; + } + } + + /** + * 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'), + 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 + * is not an object. + */ + function hasAllProperties(fieldList, o) { + + return (o instanceof Object) + && + 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 + performance and this slows oboe-mark down by + ~25%. Under theoretical future JS engines that freeze more + efficiently (possibly even use immutability to + 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 + * + * asList([a,b,c]) + * + * is equivalent to: + * + * cons(a, cons(b, cons(c, emptyList))) + **/ + function arrayAsList(inputArray){ + + return reverseList( + inputArray.reduce( + flip(cons), + emptyList + ) + ); + } + + /** + * A varargs version of arrayAsList. Works a bit like list + * in LISP. + * + * 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 + */ + 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 + */ + function foldR(fn, startValue, 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 + */ + function foldR1(fn, 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 + */ + function without(list, test, removedFn) { + + return withoutInner(list, removedFn || noop); + + function withoutInner(subList, removedFn) { + 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 + */ + function all(fn, 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 + * it doesn't return anything. Hence, this is only really useful if the + * functions being called have side-effects. + */ + function applyEach(fnList, args) { + + if( fnList ) { + head(fnList).apply(null, args); + + applyEach(tail(fnList), args); + } + } + + /** + * Reverse the order of a 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 + 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 + */ + + function clarinet(eventBus) { + "use strict"; + + 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 + , OPEN_OBJECT = _n++ // { + , CLOSE_OBJECT = _n++ // } + , OPEN_ARRAY = _n++ // [ + , CLOSE_ARRAY = _n++ // ] + , STRING = _n++ // "" + , OPEN_KEY = _n++ // , "a" + , CLOSE_KEY = _n++ // : + , TRUE = _n++ // r + , TRUE2 = _n++ // u + , TRUE3 = _n++ // e + , FALSE = _n++ // a + , FALSE2 = _n++ // l + , FALSE3 = _n++ // s + , FALSE4 = _n++ // e + , NULL = _n++ // u + , NULL2 = _n++ // l + , NULL3 = _n++ // l + , NUMBER_DECIMAL_POINT = _n++ // . + , NUMBER_DIGIT = _n // [0-9] + + // setup initial parser values + , bufferCheckPosition = MAX_BUFFER_LENGTH + , latestError + , c + , p + , textNode = undefined + , numberNode = "" + , slashed = false + , closed = false + , state = BEGIN + , stack = [] + , unicodeS = null + , unicodeI = 0 + , depth = 0 + , position = 0 + , 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); + } + if (numberNode.length > MAX_BUFFER_LENGTH) { + 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 + valid json, ie if not all arrays, objects and Strings closed properly */ + 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]; + + 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; + if(state === OPEN_KEY) stack.push(CLOSE_KEY); + else { + if(c === '}') { + emitValueOpen({}); + emitValueClose(); + state = stack.pop() || VALUE; + continue; + } else stack.push(CLOSE_OBJECT); + } + if(c === '"') + state = STRING; + 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 + emitValueOpen({}); + emitSaxKey(textNode); + textNode = undefined; + } + depth++; + } else { + if (textNode !== undefined) { + emitSaxKey(textNode); + textNode = undefined; + } + } + state = VALUE; + } else if (c==='}') { + if (textNode !== undefined) { + emitValueOpen(textNode); + emitValueClose(); + textNode = undefined; + } + emitValueClose(); + depth--; + state = stack.pop() || VALUE; + } else if(c===',') { + if(state === CLOSE_OBJECT) + stack.push(CLOSE_OBJECT); + if (textNode !== undefined) { + emitValueOpen(textNode); + emitValueClose(); + textNode = undefined; + } + state = OPEN_KEY; + } 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++; + state = VALUE; + if(c === ']') { + emitValueClose(); + depth--; + state = stack.pop() || VALUE; + continue; + } else { + stack.push(CLOSE_ARRAY); + } + } + if(c === '"') state = STRING; + else if(c === '{') state = OPEN_OBJECT; + else if(c === '[') state = OPEN_ARRAY; + else if(c === 't') state = TRUE; + else if(c === 'f') state = FALSE; + else if(c === 'n') state = NULL; + else if(c === '-') { // keep and continue + numberNode += c; + } else if(c==='0') { + numberNode += c; + state = NUMBER_DIGIT; + } else if('123456789'.indexOf(c) !== -1) { + numberNode += c; + state = NUMBER_DIGIT; + } else + return emitError("Bad value"); + continue; + + case CLOSE_ARRAY: + if(c===',') { + stack.push(CLOSE_ARRAY); + if (textNode !== undefined) { + emitValueOpen(textNode); + emitValueClose(); + textNode = undefined; + } + state = VALUE; + } else if (c===']') { + if (textNode !== undefined) { + emitValueOpen(textNode); + emitValueClose(); + textNode = undefined; + } + emitValueClose(); + depth--; + state = stack.pop() || VALUE; + } else if (whitespace(c)) + continue; + 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; + c = chunk.charAt(i++); + if (unicodeI === 4) { + // TODO this might be slow? well, probably not used too often anyway + textNode += String.fromCharCode(parseInt(unicodeS, 16)); + unicodeI = 0; + starti = i-1; + } else { + unicodeI++; + } + // we can just break here: no stuff we skipped that still has to be sliced out or so + if (!c) break STRING_BIGLOOP; + } + if (c === '"' && !slashed) { + state = stack.pop() || VALUE; + textNode += chunk.substring(starti, i-1); + break; + } + if (c === '\\' && !slashed) { + slashed = true; + textNode += chunk.substring(starti, i-1); + c = chunk.charAt(i++); + if (!c) break; + } + if (slashed) { + slashed = false; + if (c === 'n') { textNode += '\n'; } + else if (c === 'r') { textNode += '\r'; } + else if (c === 't') { textNode += '\t'; } + else if (c === 'f') { textNode += '\f'; } + else if (c === 'b') { textNode += '\b'; } + else if (c === 'u') { + // \uxxxx. meh! + unicodeI = 1; + unicodeS = ''; + } else { + textNode += c; + } + c = chunk.charAt(i++); + starti = i-1; + if (!c) break; + else continue; + } + + stringTokenPattern.lastIndex = i; + var reResult = stringTokenPattern.exec(chunk); + if (!reResult) { + i = chunk.length+1; + textNode += chunk.substring(starti, i-1); + break; + } + i = reResult.index+1; + c = chunk.charAt(reResult.index); + if (!c) { + textNode += chunk.substring(starti, i-1); + break; + } + } + 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') { + emitValueOpen(true); + emitValueClose(); + state = stack.pop() || VALUE; + } 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') { + emitValueOpen(false); + emitValueClose(); + state = stack.pop() || VALUE; + } 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 + return emitError('Invalid null started with nul'+ c); + continue; + + case NUMBER_DECIMAL_POINT: + if(c==='.') { + numberNode += c; + state = NUMBER_DIGIT; + } else + return emitError('Leading zero not followed by .'); + continue; + + case NUMBER_DIGIT: + if('0123456789'.indexOf(c) !== -1) numberNode += c; + else if (c==='.') { + if(numberNode.indexOf('.')!==-1) + return emitError('Invalid number has two dots'); + numberNode += c; + } else if (c==='e' || c==='E') { + if(numberNode.indexOf('e')!==-1 || + numberNode.indexOf('E')!==-1 ) + return emitError('Invalid number has two exponential'); + numberNode += c; + } else if (c==="+" || c==="-") { + if(!(p==='e' || p==='E')) + return emitError('Invalid symbol in number'); + numberNode += c; + } else { + if (numberNode) { + emitValueOpen(parseFloat(numberNode)); + emitValueClose(); + numberNode = ""; + } + i--; // go back one + state = stack.pop() || VALUE; + } + continue; + + default: + return emitError("Unknown state: " + state); + } + } + if (position >= bufferCheckPosition) + 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: + * http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders-method + * This method parses that string into a user-friendly key/value pair object. + */ + 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)] + = 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 + * origin of the url that we want to ajax in + */ + function isCrossOrigin(pageLocation, ajaxHost) { + + /* + * NB: defaultPort only knows http and https. + * Returns undefined otherwise. + */ + 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 + // if such is given + // + // 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 + * event whenever a new part of the response is available. + * + * 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 + * but for tests a stub can be provided instead. + * @param {String} method one of 'GET' 'POST' 'PUT' 'PATCH' 'DELETE' + * @param {String} url the url to make a request to + * @param {String|Null} data some content to be sent with the request. + * Only valid if method is POST or PUT. + * @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 + oboeBus( ABORTING ).on( function(){ + + // 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 + 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 + // the next readyState if it fails + try{ + stillToSendStartEvent && oboeBus( HTTP_START ).emit( + xhr.status, + parseResponseHeaders(xhr.getAllResponseHeaders()) ); + 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 + // progress event for each part of the response + handleProgress(); + + oboeBus(STREAM_END).emit(); + } else { + + emitFail( errorReport( + 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. + 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 + * 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 + * 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 + componentRegexes.unshift(/^/); + + return regexDescriptor( + RegExp( + componentRegexes.map(attr('source')).join('') + ) + ); + }) + + , possiblyCapturing = /(\$?)/ + , namedNode = /([\w-_]+|\*)/ + , namePlaceholder = /()/ + , nodeInArrayNotation = /\["([^"]+)"\]/ + , numberedNodeInArrayNotation = /\[(\d+|\*)\]/ + , fieldList = /{([\w ]*?)}/ + , optionalFieldList = /(?:{([\w ]*?)})?/ + + + // foo or * + , jsonPathNamedNodeInObjectNotation = jsonPathClause( + possiblyCapturing, + namedNode, + optionalFieldList + ) + + // ["foo"] + , jsonPathNamedNodeInArrayNotation = jsonPathClause( + possiblyCapturing, + nodeInArrayNotation, + optionalFieldList + ) + + // [2] or [*] + , jsonPathNumberedNodeInArrayNotation = jsonPathClause( + possiblyCapturing, + numberedNodeInArrayNotation, + optionalFieldList + ) + + // {a b c} + , jsonPathPureDuckTyping = jsonPathClause( + possiblyCapturing, + namePlaceholder, + fieldList + ) + + // .. + , jsonPathDoubleDot = jsonPathClause(/\.\./) + + // . + , jsonPathDot = jsonPathClause(/\./) + + // ! + , jsonPathBang = jsonPathClause( + possiblyCapturing, + /!/ + ) + + // nada! + , emptyString = jsonPathClause(/$/) + + ; + + + /* We export only a single function. When called, this function injects + into another function the descriptors from above. + */ + return function (fn){ + return fn( + lazyUnion( + jsonPathNamedNodeInObjectNotation + , jsonPathNamedNodeInArrayNotation + , jsonPathNumberedNodeInArrayNotation + , jsonPathPureDuckTyping + ) + , jsonPathDoubleDot + , jsonPathDot + , jsonPathBang + , 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 + * 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. + **/ + var ROOT_PATH = {}; + + + /** + * 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 + numbers. */ + + var parentNode = nodeOf( head( possiblyInconsistentAscent)); + + return isOfType( Array, parentNode) + ? + keyFound( possiblyInconsistentAscent, + len(parentNode), + newDeepestNode + ) + : + // nothing needed, return unchanged + possiblyInconsistentAscent + ; + } + + function nodeOpened( ascent, newDeepestNode ) { + + if( !ascent ) { + // we discovered the root node, + emitRootOpened( newDeepestNode); + + return keyFound( ascent, ROOT_PATH, newDeepestNode); + } + + // we discovered a non-root node + + var arrayConsistentAscent = arrayIndicesAreKeys( ascent, newDeepestNode), + ancestorBranches = tail( arrayConsistentAscent), + previouslyUnmappedName = keyOf( head( arrayConsistentAscent)); + + appendBuiltContent( + ancestorBranches, + 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 + * 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 + * 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: + appendBuiltContent( ascent, 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: + 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 + * 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 + * arguments and no variables are reassigned. + */ + // the call to jsonPathSyntax injects the token syntaxes that are needed + // inside the compiler + 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] + */ + function nameClause(previousExpr, detection ) { + + var name = detection[NAME_INDEX], + + 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 + + var hasAllrequiredFields = partialComplete( + hasAllProperties, + arrayAsList(fieldListStr.split(/\W+/)) + ), + + isMatch = compose2( + hasAllrequiredFields, + headNode + ); + + return lazyIntersection(isMatch, previousExpr); + } + + /** + * Expression for $, returns the evaluator function + */ + function capture( previousExpr, 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 + + 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. + * + * 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 + is at the start of the jsonPath. + 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 + 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 + 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) + ); + + } + + /** + * 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 + is at the start of the jsonPath. + 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; + } + + 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. + terminalCaseWhenArrivingAtRoot = rootExpr(), + terminalCaseWhenPreviousExpressionIsSatisfied = previousExpr, + recursiveCase = skip1(function(ascent) { + return cases(ascent); + }), + + cases = lazyUnion( + terminalCaseWhenArrivingAtRoot + , terminalCaseWhenPreviousExpressionIsSatisfied + , recursiveCase + ); + + return cases; + } + + /** + * Generate an evaluator for ! - matches only the root element of the json + * 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 + * 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 + * 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 + // this as a special case + + return foldR( + function( parserGeneratedSoFar, expr ){ + + return expr(parserGeneratedSoFar, detection); + }, + 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 + * 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, + detected + ), + + remainingUnparsedJsonPath = jsonPath.substr(len(detected[0])); + + return onSuccess(remainingUnparsedJsonPath, compiledParser); + } + } + + /** + * Partially completes generateClauseReaderIfTokenFound above. + */ + function clauseMatcher(tokenDetector, exprs) { + + return partialComplete( + generateClauseReaderIfTokenFound, + tokenDetector, + exprs + ); + } + + /** + * 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, + 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 + // expressions when this token is found + , clauseMatcher(dotSyntax , list() ) + + , clauseMatcher(bangSyntax , list( capture, + rootExpr)) + + , clauseMatcher(emptySyntax , list( statementExpr)) + + , function (jsonPath) { + throw Error('"' + jsonPath + '" could not be tokenised') + } + ); + + + /** + * 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 + * any remaining jsonPath to be compiled. + */ + function returnFoundParser(_remainingJsonPath, compiledParser){ + return compiledParser + } + + /** + * Recursively compile a JSONPath expression. + * + * 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, + 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 + * the parser that we have found so far. + */ + var onFind = uncompiledJsonPath + ? compileJsonPathToFunction + : returnFoundParser; + + 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 + return compileJsonPathToFunction(jsonPath, always); + + } catch( e ) { + throw Error( 'Could not compile "' + jsonPath + + '" because ' + e.message + ); + } + } + + }); + + /** + * 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 + * the name of the events managed by this singleEventPubSub + * @param {singleEventPubSub} [newListener] + * place to notify of new listeners + * @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 + * can be iterated more quickly when we are emitting + */ + var listenerTupleList, + listenerList; + + function hasId(id){ + return function(tuple) { + return tuple.id == id; + }; + } + + return { + + /** + * @param {Function} listener + * @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 () { + applyEach( listenerList, arguments ); + }, + + un: function( listenerId ) { + + 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)); + } + }; + } + /** + * 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 + * 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'); + + function newSingle(eventName) { + return singles[eventName] = singleEventPubSub( + eventName, + newListener, + removeListener + ); + } + + /** pubSub instances are functions */ + 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 + // 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 - + 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 + * 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 + 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 + listAsArray(tail(map(keyOf,descent))), // path + 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 + * oboeBus('node:!') + * + * + * + * @param {Function} predicateEvent + * either oboeBus(NODE_CLOSED) or oboeBus(NODE_OPENED). + * @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: + 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. + */ + if (maybeMatchingMapping !== false) { + + emitMatchingNode( + emitMatch, + nodeOf(maybeMatchingMapping), + ascent + ); + } + }, fullEventName); + + oboeBus('removeListener').on( function(removedEventName){ + + // 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) ) { + + addUnderlyingListener( + fullEventName, + predicateEvent, + jsonPathCompiler( match[2] ) + ); + } + } + }) + + } + + /** + * The instance API is the thing that is returned when oboe() is called. + * it allows: + * + * - listeners for various events to be added and removed + * - 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 + * fired instead) + * + * The callback is used as the listener id so that it can later be + * removed using .un(callback) + */ + function addProtectedCallback(eventName, callback) { + 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 + */ + function protectedCallback( callback ) { + return function() { + try{ + return callback.apply(oboeApi, arguments); + }catch(e) { + setTimeout(function() { + throw e; + }); + } + } + } + + /** + * Return the fully qualified event for when a pattern matches + * either a node or a path + * + * @param type {String} either 'node' or 'path' + */ + 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 { + emitNodeSwap(returnValueFromCallback); + } + } + } + } + + 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 + */ + return oboeApi = { + on : addListener, + 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(), + httpMethodName, + contentSource, + body, + headers, + withCredentials + ); + } + + clarinet(oboeBus); + + ascentManager(oboeBus, incrementalContentBuilder(oboeBus)); + + 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: + // oboe( readableStream ) + return applyDefaults( + wire, + arg1 // url + ); + + } else { + + // method signature is: + // oboe({method:m, url:u, body:b, headers:{...}}) + + return applyDefaults( + wire, + arg1.url, + arg1.method, + arg1.body, + arg1.headers, + arg1.withCredentials, + arg1.cached + ); + + } + } else { + // 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') { + module.exports = oboe; + } else { + window.oboe = oboe; + } + })((function(){ + // Access to the window object throws an exception in HTML5 web workers so + // point it to "self" if it runs in a web worker + try { + return window; + } catch (e) { + 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", + "2.16.840.1.101.3.4.1.3": "aes-128-ofb", + "2.16.840.1.101.3.4.1.4": "aes-128-cfb", + "2.16.840.1.101.3.4.1.21": "aes-192-ecb", + "2.16.840.1.101.3.4.1.22": "aes-192-cbc", + "2.16.840.1.101.3.4.1.23": "aes-192-ofb", + "2.16.840.1.101.3.4.1.24": "aes-192-cfb", + "2.16.840.1.101.3.4.1.41": "aes-256-ecb", + "2.16.840.1.101.3.4.1.42": "aes-256-cbc", + "2.16.840.1.101.3.4.1.43": "aes-256-ofb", + "2.16.840.1.101.3.4.1.44": "aes-256-cfb" + } + },{}],242:[function(require,module,exports){ + // 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(), + this.key('modulus').int(), + this.key('publicExponent').int(), + this.key('privateExponent').int(), + this.key('prime1').int(), + this.key('prime2').int(), + this.key('exponent1').int(), + this.key('exponent2').int(), + this.key('coefficient').int() + ) + }) + exports.RSAPrivateKey = RSAPrivateKey + + var RSAPublicKey = asn1.define('RSAPublicKey', function () { + this.seq().obj( + this.key('modulus').int(), + this.key('publicExponent').int() + ) + }) + exports.RSAPublicKey = RSAPublicKey + + var PublicKey = asn1.define('SubjectPublicKeyInfo', function () { + this.seq().obj( + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPublicKey').bitstr() + ) + }) + exports.PublicKey = PublicKey + + var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () { + this.seq().obj( + this.key('algorithm').objid(), + this.key('none').null_().optional(), + this.key('curve').objid().optional(), + this.key('params').seq().obj( + this.key('p').int(), + this.key('q').int(), + this.key('g').int() + ).optional() + ) + }) + + var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () { + this.seq().obj( + this.key('version').int(), + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPrivateKey').octstr() + ) + }) + exports.PrivateKey = PrivateKeyInfo + var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () { + this.seq().obj( + this.key('algorithm').seq().obj( + this.key('id').objid(), + this.key('decrypt').seq().obj( + this.key('kde').seq().obj( + this.key('id').objid(), + this.key('kdeparams').seq().obj( + this.key('salt').octstr(), + this.key('iters').int() + ) + ), + this.key('cipher').seq().obj( + this.key('algo').objid(), + this.key('iv').octstr() + ) + ) + ), + this.key('subjectPrivateKey').octstr() + ) + }) + + exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo + + var DSAPrivateKey = asn1.define('DSAPrivateKey', function () { + this.seq().obj( + this.key('version').int(), + this.key('p').int(), + this.key('q').int(), + this.key('g').int(), + this.key('pub_key').int(), + this.key('priv_key').int() + ) + }) + exports.DSAPrivateKey = DSAPrivateKey + + exports.DSAparam = asn1.define('DSAparam', function () { + this.int() + }) + + var ECPrivateKey = asn1.define('ECPrivateKey', function () { + this.seq().obj( + this.key('version').int(), + this.key('privateKey').octstr(), + this.key('parameters').optional().explicit(0).use(ECParameters), + this.key('publicKey').optional().explicit(1).bitstr() + ) + }) + 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(), + this.key('critical').bool().def(false), + this.key('extnValue').octstr() + ) + }) + + var TBSCertificate = asn.define('TBSCertificate', function () { + this.seq().obj( + this.key('version').explicit(0).int(), + this.key('serialNumber').int(), + this.key('signature').use(AlgorithmIdentifier), + this.key('issuer').use(Name), + this.key('validity').use(Validity), + this.key('subject').use(Name), + this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo), + this.key('issuerUniqueID').implicit(1).bitstr().optional(), + this.key('subjectUniqueID').implicit(2).bitstr().optional(), + this.key('extensions').explicit(3).seqof(Extension).optional() + ) + }) + + var X509Certificate = asn.define('X509Certificate', function () { + this.seq().obj( + this.key('tbsCertificate').use(TBSCertificate), + this.key('signatureAlgorithm').use(AlgorithmIdentifier), + this.key('signatureValue').bitstr() + ) + }) + + module.exports = X509Certificate + + },{"asn1.js":5}],244:[function(require,module,exports){ + (function (Buffer){ + // adapted from https://github.com/apatil/pemstrip + var findProc = /Proc-Type: 4,ENCRYPTED\n\r?DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)\n\r?\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?/m + var startRegex = /^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----\n/m + var fullRegex = /^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?-----END \1-----$/m + var evp = require('evp_bytestokey') + var ciphers = require('browserify-aes') + module.exports = function (okey, password) { + var key = okey.toString() + var match = key.match(findProc) + var decrypted + if (!match) { + var match2 = key.match(fullRegex) + decrypted = new Buffer(match2[2].replace(/\r?\n/g, ''), 'base64') + } else { + var suite = 'aes' + match[1] + var iv = new Buffer(match[2], 'hex') + var cipherText = new Buffer(match[3].replace(/\r?\n/g, ''), 'base64') + var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key + var out = [] + var cipher = ciphers.createDecipheriv(suite, cipherKey, iv) + out.push(cipher.update(cipherText)) + out.push(cipher.final()) + decrypted = Buffer.concat(out) + } + var tag = key.match(startRegex)[1] + return { + tag: tag, + data: decrypted + } + } + + }).call(this,require("buffer").Buffer) + },{"browserify-aes":58,"buffer":84,"evp_bytestokey":158}],245:[function(require,module,exports){ + (function (Buffer){ + var asn1 = require('./asn1') + var aesid = require('./aesid.json') + var fixProc = require('./fixProc') + var ciphers = require('browserify-aes') + var compat = require('pbkdf2') + module.exports = parseKeys + + function parseKeys (buffer) { + var password + if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) { + password = buffer.passphrase + buffer = buffer.key + } + if (typeof buffer === 'string') { + buffer = new Buffer(buffer) + } + + var stripped = fixProc(buffer, password) + + var type = stripped.tag + var data = stripped.data + var subtype, ndata + switch (type) { + case 'CERTIFICATE': + ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo + // falls through + case 'PUBLIC KEY': + if (!ndata) { + ndata = asn1.PublicKey.decode(data, 'der') + } + subtype = ndata.algorithm.algorithm.join('.') + switch (subtype) { + case '1.2.840.113549.1.1.1': + return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der') + case '1.2.840.10045.2.1': + ndata.subjectPrivateKey = ndata.subjectPublicKey + return { + type: 'ec', + data: ndata + } + case '1.2.840.10040.4.1': + ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der') + return { + type: 'dsa', + data: ndata.algorithm.params + } + default: throw new Error('unknown key id ' + subtype) + } + throw new Error('unknown key type ' + type) + case 'ENCRYPTED PRIVATE KEY': + data = asn1.EncryptedPrivateKey.decode(data, 'der') + data = decrypt(data, password) + // falls through + case 'PRIVATE KEY': + ndata = asn1.PrivateKey.decode(data, 'der') + subtype = ndata.algorithm.algorithm.join('.') + switch (subtype) { + case '1.2.840.113549.1.1.1': + return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der') + case '1.2.840.10045.2.1': + return { + curve: ndata.algorithm.curve, + privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey + } + case '1.2.840.10040.4.1': + ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der') + return { + type: 'dsa', + params: ndata.algorithm.params + } + default: throw new Error('unknown key id ' + subtype) + } + throw new Error('unknown key type ' + type) + case 'RSA PUBLIC KEY': + return asn1.RSAPublicKey.decode(data, 'der') + case 'RSA PRIVATE KEY': + return asn1.RSAPrivateKey.decode(data, 'der') + case 'DSA PRIVATE KEY': + return { + type: 'dsa', + params: asn1.DSAPrivateKey.decode(data, 'der') + } + case 'EC PRIVATE KEY': + data = asn1.ECPrivateKey.decode(data, 'der') + return { + curve: data.parameters.value, + privateKey: data.privateKey + } + default: throw new Error('unknown key type ' + type) + } + } + parseKeys.signature = asn1.signature + function decrypt (data, password) { + var salt = data.algorithm.decrypt.kde.kdeparams.salt + var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10) + var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')] + var iv = data.algorithm.decrypt.cipher.iv + var cipherText = data.subjectPrivateKey + var keylen = parseInt(algo.split('-')[1], 10) / 8 + var key = compat.pbkdf2Sync(password, salt, iters, keylen) + var cipher = ciphers.createDecipheriv(algo, key, iv) + var out = [] + out.push(cipher.update(cipherText)) + 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') + , forEach = require('for-each') + , 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])) { + result[key].push(value) + } else { + result[key] = [ result[key], value ] + } + } + ) + + 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 = { + 'sha': 'SHA-1', + 'sha-1': 'SHA-1', + 'sha1': 'SHA-1', + 'sha256': 'SHA-256', + 'sha-256': 'SHA-256', + 'sha384': 'SHA-384', + 'sha-384': 'SHA-384', + 'sha-512': 'SHA-512', + 'sha512': 'SHA-512' + } + var checks = [] + function checkNative (algo) { + if (global.process && !global.process.browser) { + return Promise.resolve(false) + } + if (!subtle || !subtle.importKey || !subtle.deriveBits) { + return Promise.resolve(false) + } + if (checks[algo] !== undefined) { + return checks[algo] + } + ZERO_BUF = ZERO_BUF || Buffer.alloc(8) + var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo) + .then(function () { + return true + }).catch(function () { + return false + }) + checks[algo] = prom + return prom + } + function browserPbkdf2 (password, salt, iterations, length, algo) { + return subtle.importKey( + 'raw', password, {name: 'PBKDF2'}, false, ['deriveBits'] + ).then(function (key) { + return subtle.deriveBits({ + name: 'PBKDF2', + salt: salt, + iterations: iterations, + hash: { + name: algo + } + }, key, length << 3) + }).then(function (res) { + return Buffer.from(res) + }) + } + function resolvePromise (promise, callback) { + promise.then(function (out) { + process.nextTick(function () { + callback(null, out) + }) + }, function (e) { + process.nextTick(function () { + callback(e) + }) + }) + } + 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') { + return process.nextTick(function () { + var out + try { + out = sync(password, salt, iterations, keylen, digest) + } catch (e) { + return callback(e) + } + callback(null, out) + }) + } + resolvePromise(checkNative(algo).then(function (resp) { + if (resp) { + return browserPbkdf2(password, salt, iterations, keylen, algo) + } else { + return sync(password, salt, iterations, keylen, digest) + } + }), 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){ + var defaultEncoding + /* istanbul ignore next */ + if (process.browser) { + 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 + module.exports = function (iterations, keylen) { + 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 + var ZEROS = Buffer.alloc(128) + var sizes = { + md5: 16, + sha1: 20, + sha224: 28, + sha256: 32, + sha384: 48, + sha512: 64, + 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 + this.ipad2 = ipad + this.opad = opad + this.alg = alg + this.blocksize = blocksize + 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)); + var error = new ExceptionConstructor(message); + 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) { + var s = typeof value; + if (s == 'object') { + if (!value) { + return 'null'; + } else if (value instanceof Array) { + return 'array'; + } + } + 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) { + module.exports = { nextTick: nextTick }; + } else { + module.exports = process + } + + function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } + } + + + }).call(this,require('_process')) + },{"_process":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'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + (function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } + } ()) + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + + process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + }; + + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + process.title = 'browser'; + process.browser = true; + process.env = {}; + process.argv = []; + process.version = ''; // empty string to avoid regexp issues + process.versions = {}; + + function noop() {} + + process.on = noop; + process.addListener = noop; + process.once = noop; + process.off = noop; + process.removeListener = noop; + process.removeAllListeners = noop; + process.emit = noop; + process.prependListener = noop; + process.prependOnceListener = noop; + + process.listeners = function (name) { return [] } + + process.binding = function (name) { + throw new Error('process.binding is not supported'); + }; + + process.cwd = function () { return '/' }; + process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); + }; + process.umask = function() { return 0; }; + + },{}],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); + }, function (err) { + setImmediate(cb, err); + }); + }; + }; + + },{"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); + }; + },{"./privateDecrypt":261,"./publicEncrypt":262}],260:[function(require,module,exports){ + (function (Buffer){ + var createHash = require('create-hash'); + module.exports = function (seed, len) { + var t = new Buffer(''); + var i = 0, c; + while (t.length < len) { + c = i2ops(i++); + t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()]); + } + return t.slice(0, len); + }; + + function i2ops(c) { + var out = new Buffer(4); + out.writeUInt32BE(c,0); + return out; + } + }).call(this,require("buffer").Buffer) + },{"buffer":84,"create-hash":91}],261:[function(require,module,exports){ + (function (Buffer){ + var parseKeys = require('parse-asn1'); + var mgf = require('./mgf'); + var xor = require('./xor'); + var bn = require('bn.js'); + var crt = require('browserify-rsa'); + var createHash = require('create-hash'); + var withPublic = require('./withPublic'); + module.exports = function privateDecrypt(private_key, enc, reverse) { + var padding; + if (private_key.padding) { + padding = private_key.padding; + } else if (reverse) { + padding = 1; + } else { + padding = 4; + } + + var key = parseKeys(private_key); + var k = key.modulus.byteLength(); + if (enc.length > k || new bn(enc).cmp(key.modulus) >= 0) { + throw new Error('decryption error'); + } + var msg; + if (reverse) { + msg = withPublic(new bn(enc), key); + } else { + msg = crt(enc, key); + } + var zBuffer = new Buffer(k - msg.length); + zBuffer.fill(0); + msg = Buffer.concat([zBuffer, msg], k); + if (padding === 4) { + return oaep(key, msg); + } else if (padding === 1) { + return pkcs1(key, msg, reverse); + } else if (padding === 3) { + return msg; + } else { + throw new Error('unknown padding'); + } + }; + + function oaep(key, msg){ + var n = key.modulus; + var k = key.modulus.byteLength(); + var mLen = msg.length; + var iHash = createHash('sha1').update(new Buffer('')).digest(); + var hLen = iHash.length; + var hLen2 = 2 * hLen; + if (msg[0] !== 0) { + throw new Error('decryption error'); + } + var maskedSeed = msg.slice(1, hLen + 1); + var maskedDb = msg.slice(hLen + 1); + var seed = xor(maskedSeed, mgf(maskedDb, hLen)); + var db = xor(maskedDb, mgf(seed, k - hLen - 1)); + if (compare(iHash, db.slice(0, hLen))) { + throw new Error('decryption error'); + } + var i = hLen; + while (db[i] === 0) { + i++; + } + if (db[i++] !== 1) { + throw new Error('decryption error'); + } + return db.slice(i); + } + + function pkcs1(key, msg, reverse){ + var p1 = msg.slice(0, 2); + var i = 2; + var status = 0; + while (msg[i++] !== 0) { + if (i >= msg.length) { + status++; + break; + } + } + 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++; + } + if (ps.length < 8) { + status++; + } + if (status) { + throw new Error('decryption error'); + } + return msg.slice(i); + } + function compare(a, b){ + a = new Buffer(a); + b = new Buffer(b); + var dif = 0; + var len = a.length; + if (a.length !== b.length) { + dif++; + len = Math.min(a.length, b.length); + } + var i = -1; + while (++i < len) { + dif += (a[i] ^ b[i]); + } + return dif; + } + }).call(this,require("buffer").Buffer) + },{"./mgf":260,"./withPublic":263,"./xor":264,"bn.js":53,"browserify-rsa":76,"buffer":84,"create-hash":91,"parse-asn1":245}],262:[function(require,module,exports){ + (function (Buffer){ + var parseKeys = require('parse-asn1'); + var randomBytes = require('randombytes'); + var createHash = require('create-hash'); + var mgf = require('./mgf'); + var xor = require('./xor'); + 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) { + padding = public_key.padding; + } else if (reverse) { + padding = 1; + } else { + padding = 4; + } + var key = parseKeys(public_key); + var paddedMsg; + if (padding === 4) { + paddedMsg = oaep(key, msg); + } else if (padding === 1) { + paddedMsg = pkcs1(key, msg, reverse); + } else if (padding === 3) { + paddedMsg = new bn(msg); + if (paddedMsg.cmp(key.modulus) >= 0) { + throw new Error('data too long for modulus'); + } + } else { + throw new Error('unknown padding'); + } + if (reverse) { + return crt(paddedMsg, key); + } else { + return withPublic(paddedMsg, key); + } + }; + + function oaep(key, msg){ + var k = key.modulus.byteLength(); + var mLen = msg.length; + var iHash = createHash('sha1').update(new Buffer('')).digest(); + var hLen = iHash.length; + var hLen2 = 2 * hLen; + if (mLen > k - hLen2 - 2) { + throw new Error('message too long'); + } + var ps = new Buffer(k - mLen - hLen2 - 2); + ps.fill(0); + var dblen = k - hLen - 1; + var seed = randomBytes(hLen); + var maskedDb = xor(Buffer.concat([iHash, ps, new Buffer([1]), msg], dblen), mgf(seed, dblen)); + var maskedSeed = xor(seed, mgf(maskedDb, hLen)); + return new bn(Buffer.concat([new Buffer([0]), maskedSeed, maskedDb], k)); + } + function pkcs1(key, msg, reverse){ + var mLen = msg.length; + var k = key.modulus.byteLength(); + if (mLen > k - 11) { + throw new Error('message too long'); + } + var ps; + if (reverse) { + ps = new Buffer(k - mLen - 3); + ps.fill(0xff); + } else { + ps = nonZero(k - mLen - 3); + } + return new bn(Buffer.concat([new Buffer([0, reverse?1:2]), ps, new Buffer([0]), msg], k)); + } + function nonZero(len, crypto) { + var out = new Buffer(len); + var i = 0; + var cache = randomBytes(len*2); + var cur = 0; + var num; + while (i < len) { + if (cur === cache.length) { + cache = randomBytes(len*2); + cur = 0; + } + num = cache[cur++]; + if (num) { + out[i++] = num; + } + } + return out; + } + }).call(this,require("buffer").Buffer) + },{"./mgf":260,"./withPublic":263,"./xor":264,"bn.js":53,"browserify-rsa":76,"buffer":84,"create-hash":91,"parse-asn1":245,"randombytes":270}],263:[function(require,module,exports){ + (function (Buffer){ + var bn = require('bn.js'); + function withPublic(paddedMsg, key) { + return new Buffer(paddedMsg + .toRed(bn.mont(key.modulus)) + .redPow(new bn(key.publicExponent)) + .fromRed() + .toArray()); + } + + module.exports = withPublic; + }).call(this,require("buffer").Buffer) + },{"bn.js":53,"buffer":84}],264:[function(require,module,exports){ + module.exports = function xor(a, b) { + var len = a.length; + var i = -1; + while (++i < len) { + a[i] ^= b[i]; + } + return a + }; + },{}],265:[function(require,module,exports){ + (function (global){ + /*! https://mths.be/punycode v1.4.1 by @mathias */ + ;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + + }(this)); + + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + },{}],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': + return function (key, value, index) { + return value === null ? [ + encode(key, opts), + '[', + index, + ']' + ].join('') : [ + encode(key, opts), + '[', + encode(index, opts), + ']=', + encode(value, opts) + ].join(''); + }; + + case 'bracket': + return function (key, value) { + return value === null ? encode(key, opts) : [ + encode(key, opts), + '[]=', + encode(value, opts) + ].join(''); + }; + + default: + return function (key, value) { + return value === null ? encode(key, opts) : [ + encode(key, opts), + '=', + encode(value, opts) + ].join(''); + }; + } + } + + 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; + } else if (accumulator[key] === undefined) { + 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(); + } else if (typeof input === 'object') { + return keysSorter(Object.keys(input)).sort(function (a, b) { + return Number(a) - Number(b); + }).map(function (key) { + return input[key]; + }); + } + + return input; + } + + function extract(str) { + var queryStart = str.indexOf('?'); + if (queryStart === -1) { + return ''; + } + 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)) { + // Sort object keys, not values + result[key] = keysSorter(val); + } 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. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 'use strict'; + + // 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); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + 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. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 'use strict'; + + var 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; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + 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 = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; + } + + var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + 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') + } + var safeBuffer = require('safe-buffer') + var randombytes = require('randombytes') + var Buffer = safeBuffer.Buffer + var kBufferMaxLength = safeBuffer.kMaxLength + var crypto = global.crypto || global.msCrypto + var kMaxUint32 = Math.pow(2, 32) - 1 + function assertOffset (offset, length) { + 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') + } + } + if ((crypto && crypto.getRandomValues) || !process.browser) { + exports.randomFill = randomFill + exports.randomFillSync = randomFillSync + } else { + exports.randomFill = oldBrowser + exports.randomFillSync = oldBrowser + } + function randomFill (buf, offset, size, cb) { + 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 + size = buf.length + } else if (typeof size === 'function') { + cb = size + size = buf.length - offset + } else if (typeof cb !== 'function') { + throw new TypeError('"cb" argument must be a function') + } + assertOffset(offset, buf.length) + assertSize(size, offset, buf.length) + return actualFill(buf, offset, size, cb) + } + + function actualFill (buf, offset, size, cb) { + if (process.browser) { + var ourBuf = buf.buffer + var uint = new Uint8Array(ourBuf, offset, size) + crypto.getRandomValues(uint) + if (cb) { + process.nextTick(function () { + cb(null, buf) + }) + return + } + return buf + } + if (cb) { + randombytes(size, function (err, bytes) { + if (err) { + return cb(err) + } + bytes.copy(buf, offset) + cb(null, buf) + }) + return + } + var bytes = randombytes(size) + bytes.copy(buf, offset) + return buf + } + function randomFillSync (buf, offset, size) { + if (typeof offset === 'undefined') { + offset = 0 + } + 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; + },{}],273:[function(require,module,exports){ + module.exports = require('crypto'); + },{"crypto":272}],274:[function(require,module,exports){ + 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.')); + } else { + 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) { + callback(null, '0x'+ result.toString('hex')); + } else { + callback(error); + } + }) + } 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 { + throw error; + } + } + } + }; + + + 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. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + // a duplex stream is just a stream that is both readable and writable. + // Since JS doesn't have multiple prototypal inheritance, this class + // prototypally inherits from Readable, and then parasitically from + // Writable. + + 'use strict'; + + /**/ + + var processNextTick = require('process-nextick-args').nextTick; + /**/ + + /**/ + var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; + }; + /**/ + + module.exports = Duplex; + + /**/ + var util = require('core-util-is'); + util.inherits = require('inherits'); + /**/ + + var Readable = require('./_stream_readable'); + var Writable = require('./_stream_writable'); + + util.inherits(Duplex, Readable); + + 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) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } + }); + + Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); + + processNextTick(cb, err); + }; + + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + },{"./_stream_readable":278,"./_stream_writable":280,"core-util-is":89,"inherits":180,"process-nextick-args":256}],277:[function(require,module,exports){ + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + // a passthrough stream. + // basically just the most minimal sort of Transform stream. + // Every written chunk gets output as-is. + + 'use strict'; + + module.exports = PassThrough; + + var Transform = require('./_stream_transform'); + + /**/ + var util = require('core-util-is'); + util.inherits = require('inherits'); + /**/ + + util.inherits(PassThrough, Transform); + + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); + } + + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + },{"./_stream_transform":279,"core-util-is":89,"inherits":180}],278:[function(require,module,exports){ + (function (process,global){ + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 'use strict'; + + /**/ + + var 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) { + return Buffer.from(chunk); + } + function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; + } + + /**/ + + /**/ + var util = require('core-util-is'); + util.inherits = require('inherits'); + /**/ + + /**/ + var debugUtil = require('util'); + var debug = void 0; + if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); + } else { + debug = function () {}; + } + /**/ + + var BufferList = require('./internal/streams/BufferList'); + var destroyImpl = require('./internal/streams/destroy'); + var StringDecoder; + + util.inherits(Readable, Stream); + + var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + } + + function ReadableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var readableHwm = options.readableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + + function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); + } + + Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } + }); + + Readable.prototype.destroy = destroyImpl.destroy; + Readable.prototype._undestroy = destroyImpl.undestroy; + Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); + }; + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); + }; + + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); + }; + + function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + } + } + + return needMoreData(state); + } + + function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); + } + + function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; + } + + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; + + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; + }; + + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) 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 + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + processNextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; + } + + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); + }; + + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; + } + + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, unpipeInfo); + }return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this, unpipeInfo); + + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + processNextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + 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) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; + }; + + // exposed for testing purposes only. + Readable._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; + } + + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } + + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + processNextTick(endReadableNT, state, stream); + } + } + + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } + + function 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; + } + return -1; + } + }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + },{"./_stream_duplex":276,"./internal/streams/BufferList":281,"./internal/streams/destroy":282,"./internal/streams/stream":283,"_process":257,"core-util-is":89,"events":157,"inherits":180,"isarray":186,"process-nextick-args":256,"safe-buffer":290,"string_decoder/":317,"util":55}],279:[function(require,module,exports){ + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. + + 'use strict'; + + module.exports = Transform; + + var Duplex = require('./_stream_duplex'); + + /**/ + var util = require('core-util-is'); + util.inherits = require('inherits'); + /**/ + + util.inherits(Transform, Duplex); + + function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) { + return this.emit('error', new Error('write callback called multiple times')); + } + + ts.writechunk = null; + ts.writecb = null; + + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + + cb(er); + + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } + } + + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); + } + + function prefinish() { + var _this = this; + + if (typeof this._flush === 'function') { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } + } + + Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); + }; + + Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + Transform.prototype._destroy = function (err, cb) { + var _this2 = this; + + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this2.emit('close'); + }); + }; + + function done(stream, er, data) { + if (er) return stream.emit('error', er); + + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); + + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); + } + },{"./_stream_duplex":276,"core-util-is":89,"inherits":180}],280:[function(require,module,exports){ + (function (process,global){ + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + // 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; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } + + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; + } + /* */ + + /**/ + var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : 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) { + return Buffer.from(chunk); + } + function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; + } + + /**/ + + var destroyImpl = require('./internal/streams/destroy'); + + util.inherits(Writable, Stream); + + function nop() {} + + function WritableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var writableHwm = options.writableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + + (function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} + })(); + + // Test _writableState for inheritance to account for Duplex streams, + // whose prototype chain only points to Readable. + var realHasInstance; + if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + + return object && object._writableState instanceof WritableState; + } + }); + } else { + realHasInstance = function (object) { + return object instanceof this; + }; + } + + function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + + if (typeof options.final === 'function') this._final = options.final; + } + + Stream.call(this); + } + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; + + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + 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) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + processNextTick(cb, er); + valid = false; + } + return valid; + } + + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + + return ret; + }; + + Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; + }; + + Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; + } + + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + processNextTick(cb, er); + // this can emit finish, and it will always happen + // after error + processNextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } + + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); + }; + + Writable.prototype._writev = null; + + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); + }; + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + stream.emit('error', err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); + } + function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function') { + state.pendingcb++; + state.finalCalled = true; + processNextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + } + } + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) processNextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } + + function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = corkReq; + } else { + state.corkedRequestsFree = corkReq; + } + } + + Object.defineProperty(Writable.prototype, 'destroyed', { + get: function () { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } + }); + + Writable.prototype.destroy = destroyImpl.destroy; + Writable.prototype._undestroy = destroyImpl.undestroy; + Writable.prototype._destroy = function (err, cb) { + this.end(); + cb(err); + }; + }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + },{"./_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; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + return BufferList; + }(); + + if (util && util.inspect && util.inspect.custom) { + module.exports.prototype[util.inspect.custom] = function () { + var obj = util.inspect({ length: this.length }); + return this.constructor.name + ' ' + obj; + }; + } + },{"safe-buffer":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); + } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { + processNextTick(emitErrorNT, this, err); + } + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + processNextTick(emitErrorNT, _this, err); + if (_this._writableState) { + _this._writableState.errorEmitted = true; + } + } else if (cb) { + cb(err); + } + }); + + return this; + } + + function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } + } + + function emitErrorNT(self, err) { + self.emit('error', err); + } + + module.exports = { + destroy: destroy, + undestroy: undestroy + }; + },{"process-nextick-args":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; + exports.Readable = exports; + exports.Writable = require('./lib/_stream_writable.js'); + exports.Duplex = require('./lib/_stream_duplex.js'); + exports.Transform = require('./lib/_stream_transform.js'); + exports.PassThrough = require('./lib/_stream_passthrough.js'); + + },{"./lib/_stream_duplex.js":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 + this._c = 0x98badcfe + 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 + al = fn1(al, bl, cl, dl, el, m[0], 0x00000000, 11); cl = rotl(cl, 10) + el = fn1(el, al, bl, cl, dl, m[1], 0x00000000, 14); bl = rotl(bl, 10) + dl = fn1(dl, el, al, bl, cl, m[2], 0x00000000, 15); al = rotl(al, 10) + cl = fn1(cl, dl, el, al, bl, m[3], 0x00000000, 12); el = rotl(el, 10) + bl = fn1(bl, cl, dl, el, al, m[4], 0x00000000, 5); dl = rotl(dl, 10) + al = fn1(al, bl, cl, dl, el, m[5], 0x00000000, 8); cl = rotl(cl, 10) + el = fn1(el, al, bl, cl, dl, m[6], 0x00000000, 7); bl = rotl(bl, 10) + dl = fn1(dl, el, al, bl, cl, m[7], 0x00000000, 9); al = rotl(al, 10) + cl = fn1(cl, dl, el, al, bl, m[8], 0x00000000, 11); el = rotl(el, 10) + bl = fn1(bl, cl, dl, el, al, m[9], 0x00000000, 13); dl = rotl(dl, 10) + al = fn1(al, bl, cl, dl, el, m[10], 0x00000000, 14); cl = rotl(cl, 10) + el = fn1(el, al, bl, cl, dl, m[11], 0x00000000, 15); bl = rotl(bl, 10) + dl = fn1(dl, el, al, bl, cl, m[12], 0x00000000, 6); al = rotl(al, 10) + 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 + el = fn2(el, al, bl, cl, dl, m[7], 0x5a827999, 7); bl = rotl(bl, 10) + dl = fn2(dl, el, al, bl, cl, m[4], 0x5a827999, 6); al = rotl(al, 10) + cl = fn2(cl, dl, el, al, bl, m[13], 0x5a827999, 8); el = rotl(el, 10) + bl = fn2(bl, cl, dl, el, al, m[1], 0x5a827999, 13); dl = rotl(dl, 10) + al = fn2(al, bl, cl, dl, el, m[10], 0x5a827999, 11); cl = rotl(cl, 10) + el = fn2(el, al, bl, cl, dl, m[6], 0x5a827999, 9); bl = rotl(bl, 10) + dl = fn2(dl, el, al, bl, cl, m[15], 0x5a827999, 7); al = rotl(al, 10) + cl = fn2(cl, dl, el, al, bl, m[3], 0x5a827999, 15); el = rotl(el, 10) + bl = fn2(bl, cl, dl, el, al, m[12], 0x5a827999, 7); dl = rotl(dl, 10) + al = fn2(al, bl, cl, dl, el, m[0], 0x5a827999, 12); cl = rotl(cl, 10) + el = fn2(el, al, bl, cl, dl, m[9], 0x5a827999, 15); bl = rotl(bl, 10) + dl = fn2(dl, el, al, bl, cl, m[5], 0x5a827999, 9); al = rotl(al, 10) + cl = fn2(cl, dl, el, al, bl, m[2], 0x5a827999, 11); el = rotl(el, 10) + 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 + dl = fn3(dl, el, al, bl, cl, m[3], 0x6ed9eba1, 11); al = rotl(al, 10) + cl = fn3(cl, dl, el, al, bl, m[10], 0x6ed9eba1, 13); el = rotl(el, 10) + bl = fn3(bl, cl, dl, el, al, m[14], 0x6ed9eba1, 6); dl = rotl(dl, 10) + al = fn3(al, bl, cl, dl, el, m[4], 0x6ed9eba1, 7); cl = rotl(cl, 10) + el = fn3(el, al, bl, cl, dl, m[9], 0x6ed9eba1, 14); bl = rotl(bl, 10) + dl = fn3(dl, el, al, bl, cl, m[15], 0x6ed9eba1, 9); al = rotl(al, 10) + cl = fn3(cl, dl, el, al, bl, m[8], 0x6ed9eba1, 13); el = rotl(el, 10) + bl = fn3(bl, cl, dl, el, al, m[1], 0x6ed9eba1, 15); dl = rotl(dl, 10) + al = fn3(al, bl, cl, dl, el, m[2], 0x6ed9eba1, 14); cl = rotl(cl, 10) + el = fn3(el, al, bl, cl, dl, m[7], 0x6ed9eba1, 8); bl = rotl(bl, 10) + dl = fn3(dl, el, al, bl, cl, m[0], 0x6ed9eba1, 13); al = rotl(al, 10) + cl = fn3(cl, dl, el, al, bl, m[6], 0x6ed9eba1, 6); el = rotl(el, 10) + bl = fn3(bl, cl, dl, el, al, m[13], 0x6ed9eba1, 5); dl = rotl(dl, 10) + 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 + cl = fn4(cl, dl, el, al, bl, m[1], 0x8f1bbcdc, 11); el = rotl(el, 10) + bl = fn4(bl, cl, dl, el, al, m[9], 0x8f1bbcdc, 12); dl = rotl(dl, 10) + al = fn4(al, bl, cl, dl, el, m[11], 0x8f1bbcdc, 14); cl = rotl(cl, 10) + el = fn4(el, al, bl, cl, dl, m[10], 0x8f1bbcdc, 15); bl = rotl(bl, 10) + dl = fn4(dl, el, al, bl, cl, m[0], 0x8f1bbcdc, 14); al = rotl(al, 10) + cl = fn4(cl, dl, el, al, bl, m[8], 0x8f1bbcdc, 15); el = rotl(el, 10) + bl = fn4(bl, cl, dl, el, al, m[12], 0x8f1bbcdc, 9); dl = rotl(dl, 10) + al = fn4(al, bl, cl, dl, el, m[4], 0x8f1bbcdc, 8); cl = rotl(cl, 10) + el = fn4(el, al, bl, cl, dl, m[13], 0x8f1bbcdc, 9); bl = rotl(bl, 10) + dl = fn4(dl, el, al, bl, cl, m[3], 0x8f1bbcdc, 14); al = rotl(al, 10) + cl = fn4(cl, dl, el, al, bl, m[7], 0x8f1bbcdc, 5); el = rotl(el, 10) + bl = fn4(bl, cl, dl, el, al, m[15], 0x8f1bbcdc, 6); dl = rotl(dl, 10) + al = fn4(al, bl, cl, dl, el, m[14], 0x8f1bbcdc, 8); cl = rotl(cl, 10) + 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 + bl = fn5(bl, cl, dl, el, al, m[4], 0xa953fd4e, 9); dl = rotl(dl, 10) + al = fn5(al, bl, cl, dl, el, m[0], 0xa953fd4e, 15); cl = rotl(cl, 10) + el = fn5(el, al, bl, cl, dl, m[5], 0xa953fd4e, 5); bl = rotl(bl, 10) + dl = fn5(dl, el, al, bl, cl, m[9], 0xa953fd4e, 11); al = rotl(al, 10) + cl = fn5(cl, dl, el, al, bl, m[7], 0xa953fd4e, 6); el = rotl(el, 10) + bl = fn5(bl, cl, dl, el, al, m[12], 0xa953fd4e, 8); dl = rotl(dl, 10) + al = fn5(al, bl, cl, dl, el, m[2], 0xa953fd4e, 13); cl = rotl(cl, 10) + el = fn5(el, al, bl, cl, dl, m[10], 0xa953fd4e, 12); bl = rotl(bl, 10) + dl = fn5(dl, el, al, bl, cl, m[14], 0xa953fd4e, 5); al = rotl(al, 10) + cl = fn5(cl, dl, el, al, bl, m[1], 0xa953fd4e, 12); el = rotl(el, 10) + bl = fn5(bl, cl, dl, el, al, m[3], 0xa953fd4e, 13); dl = rotl(dl, 10) + al = fn5(al, bl, cl, dl, el, m[8], 0xa953fd4e, 14); cl = rotl(cl, 10) + el = fn5(el, al, bl, cl, dl, m[11], 0xa953fd4e, 11); bl = rotl(bl, 10) + 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 + ar = fn5(ar, br, cr, dr, er, m[5], 0x50a28be6, 8); cr = rotl(cr, 10) + er = fn5(er, ar, br, cr, dr, m[14], 0x50a28be6, 9); br = rotl(br, 10) + dr = fn5(dr, er, ar, br, cr, m[7], 0x50a28be6, 9); ar = rotl(ar, 10) + cr = fn5(cr, dr, er, ar, br, m[0], 0x50a28be6, 11); er = rotl(er, 10) + br = fn5(br, cr, dr, er, ar, m[9], 0x50a28be6, 13); dr = rotl(dr, 10) + ar = fn5(ar, br, cr, dr, er, m[2], 0x50a28be6, 15); cr = rotl(cr, 10) + er = fn5(er, ar, br, cr, dr, m[11], 0x50a28be6, 15); br = rotl(br, 10) + dr = fn5(dr, er, ar, br, cr, m[4], 0x50a28be6, 5); ar = rotl(ar, 10) + cr = fn5(cr, dr, er, ar, br, m[13], 0x50a28be6, 7); er = rotl(er, 10) + br = fn5(br, cr, dr, er, ar, m[6], 0x50a28be6, 7); dr = rotl(dr, 10) + ar = fn5(ar, br, cr, dr, er, m[15], 0x50a28be6, 8); cr = rotl(cr, 10) + er = fn5(er, ar, br, cr, dr, m[8], 0x50a28be6, 11); br = rotl(br, 10) + dr = fn5(dr, er, ar, br, cr, m[1], 0x50a28be6, 14); ar = rotl(ar, 10) + 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 + er = fn4(er, ar, br, cr, dr, m[6], 0x5c4dd124, 9); br = rotl(br, 10) + dr = fn4(dr, er, ar, br, cr, m[11], 0x5c4dd124, 13); ar = rotl(ar, 10) + cr = fn4(cr, dr, er, ar, br, m[3], 0x5c4dd124, 15); er = rotl(er, 10) + br = fn4(br, cr, dr, er, ar, m[7], 0x5c4dd124, 7); dr = rotl(dr, 10) + ar = fn4(ar, br, cr, dr, er, m[0], 0x5c4dd124, 12); cr = rotl(cr, 10) + er = fn4(er, ar, br, cr, dr, m[13], 0x5c4dd124, 8); br = rotl(br, 10) + dr = fn4(dr, er, ar, br, cr, m[5], 0x5c4dd124, 9); ar = rotl(ar, 10) + cr = fn4(cr, dr, er, ar, br, m[10], 0x5c4dd124, 11); er = rotl(er, 10) + br = fn4(br, cr, dr, er, ar, m[14], 0x5c4dd124, 7); dr = rotl(dr, 10) + ar = fn4(ar, br, cr, dr, er, m[15], 0x5c4dd124, 7); cr = rotl(cr, 10) + er = fn4(er, ar, br, cr, dr, m[8], 0x5c4dd124, 12); br = rotl(br, 10) + dr = fn4(dr, er, ar, br, cr, m[12], 0x5c4dd124, 7); ar = rotl(ar, 10) + cr = fn4(cr, dr, er, ar, br, m[4], 0x5c4dd124, 6); er = rotl(er, 10) + 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 + dr = fn3(dr, er, ar, br, cr, m[15], 0x6d703ef3, 9); ar = rotl(ar, 10) + cr = fn3(cr, dr, er, ar, br, m[5], 0x6d703ef3, 7); er = rotl(er, 10) + br = fn3(br, cr, dr, er, ar, m[1], 0x6d703ef3, 15); dr = rotl(dr, 10) + ar = fn3(ar, br, cr, dr, er, m[3], 0x6d703ef3, 11); cr = rotl(cr, 10) + er = fn3(er, ar, br, cr, dr, m[7], 0x6d703ef3, 8); br = rotl(br, 10) + dr = fn3(dr, er, ar, br, cr, m[14], 0x6d703ef3, 6); ar = rotl(ar, 10) + cr = fn3(cr, dr, er, ar, br, m[6], 0x6d703ef3, 6); er = rotl(er, 10) + br = fn3(br, cr, dr, er, ar, m[9], 0x6d703ef3, 14); dr = rotl(dr, 10) + ar = fn3(ar, br, cr, dr, er, m[11], 0x6d703ef3, 12); cr = rotl(cr, 10) + er = fn3(er, ar, br, cr, dr, m[8], 0x6d703ef3, 13); br = rotl(br, 10) + dr = fn3(dr, er, ar, br, cr, m[12], 0x6d703ef3, 5); ar = rotl(ar, 10) + cr = fn3(cr, dr, er, ar, br, m[2], 0x6d703ef3, 14); er = rotl(er, 10) + br = fn3(br, cr, dr, er, ar, m[10], 0x6d703ef3, 13); dr = rotl(dr, 10) + 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 + cr = fn2(cr, dr, er, ar, br, m[8], 0x7a6d76e9, 15); er = rotl(er, 10) + br = fn2(br, cr, dr, er, ar, m[6], 0x7a6d76e9, 5); dr = rotl(dr, 10) + ar = fn2(ar, br, cr, dr, er, m[4], 0x7a6d76e9, 8); cr = rotl(cr, 10) + er = fn2(er, ar, br, cr, dr, m[1], 0x7a6d76e9, 11); br = rotl(br, 10) + dr = fn2(dr, er, ar, br, cr, m[3], 0x7a6d76e9, 14); ar = rotl(ar, 10) + cr = fn2(cr, dr, er, ar, br, m[11], 0x7a6d76e9, 14); er = rotl(er, 10) + br = fn2(br, cr, dr, er, ar, m[15], 0x7a6d76e9, 6); dr = rotl(dr, 10) + ar = fn2(ar, br, cr, dr, er, m[0], 0x7a6d76e9, 14); cr = rotl(cr, 10) + er = fn2(er, ar, br, cr, dr, m[5], 0x7a6d76e9, 6); br = rotl(br, 10) + dr = fn2(dr, er, ar, br, cr, m[12], 0x7a6d76e9, 9); ar = rotl(ar, 10) + cr = fn2(cr, dr, er, ar, br, m[2], 0x7a6d76e9, 12); er = rotl(er, 10) + br = fn2(br, cr, dr, er, ar, m[13], 0x7a6d76e9, 9); dr = rotl(dr, 10) + ar = fn2(ar, br, cr, dr, er, m[9], 0x7a6d76e9, 12); cr = rotl(cr, 10) + 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 + br = fn1(br, cr, dr, er, ar, m[12], 0x00000000, 8); dr = rotl(dr, 10) + ar = fn1(ar, br, cr, dr, er, m[15], 0x00000000, 5); cr = rotl(cr, 10) + er = fn1(er, ar, br, cr, dr, m[10], 0x00000000, 12); br = rotl(br, 10) + dr = fn1(dr, er, ar, br, cr, m[4], 0x00000000, 9); ar = rotl(ar, 10) + cr = fn1(cr, dr, er, ar, br, m[1], 0x00000000, 12); er = rotl(er, 10) + br = fn1(br, cr, dr, er, ar, m[5], 0x00000000, 5); dr = rotl(dr, 10) + ar = fn1(ar, br, cr, dr, er, m[8], 0x00000000, 14); cr = rotl(cr, 10) + er = fn1(er, ar, br, cr, dr, m[7], 0x00000000, 6); br = rotl(br, 10) + dr = fn1(dr, er, ar, br, cr, m[6], 0x00000000, 8); ar = rotl(ar, 10) + cr = fn1(cr, dr, er, ar, br, m[2], 0x00000000, 13); er = rotl(er, 10) + br = fn1(br, cr, dr, er, ar, m[13], 0x00000000, 6); dr = rotl(dr, 10) + ar = fn1(ar, br, cr, dr, er, m[14], 0x00000000, 5); cr = rotl(cr, 10) + er = fn1(er, ar, br, cr, dr, m[0], 0x00000000, 15); br = rotl(br, 10) + 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 + this._c = (this._d + el + ar) | 0 + this._d = (this._e + al + br) | 0 + this._e = (this._a + bl + cr) | 0 + this._a = t + } + + RIPEMD160.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80 + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64) + this._update() + this._blockOffset = 0 + } + + this._block.fill(0, this._blockOffset, 56) + this._block.writeUInt32LE(this._length[0], 56) + this._block.writeUInt32LE(this._length[1], 60) + this._update() + + // produce result + var buffer = new Buffer(20) + buffer.writeInt32LE(this._a, 0) + buffer.writeInt32LE(this._b, 4) + buffer.writeInt32LE(this._c, 8) + buffer.writeInt32LE(this._d, 12) + buffer.writeInt32LE(this._e, 16) + return buffer + } + + function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) + } + + function fn1 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 + } + + function fn2 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 + } + + function fn3 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 + } + + function fn4 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 + } + + function fn5 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 + } + + module.exports = RIPEMD160 + + }).call(this,require("buffer").Buffer) + },{"buffer":84,"hash-base":161,"inherits":180}],289:[function(require,module,exports){ + const assert = require('assert') + const Buffer = require('safe-buffer').Buffer + /** + * RLP Encoding based on: https://github.com/ethereum/wiki/wiki/%5BEnglish%5D-RLP + * This function takes in a data, convert it to buffer if not, and a length for recursion + * + * @param {Buffer,String,Integer,Array} data - will be converted to buffer + * @returns {Buffer} - returns buffer of encoded data + **/ + exports.encode = function (input) { + if (input instanceof Array) { + var output = [] + for (var i = 0; i < input.length; i++) { + output.push(exports.encode(input[i])) + } + var buf = Buffer.concat(output) + return Buffer.concat([encodeLength(buf.length, 192), buf]) + } else { + input = toBuffer(input) + if (input.length === 1 && input[0] < 128) { + return input + } else { + return Buffer.concat([encodeLength(input.length, 128), input]) + } + } + } + + function safeParseInt (v, base) { + if (v.slice(0, 2) === '00') { + throw (new Error('invalid RLP: extra zeros')) + } + + return parseInt(v, base) + } + + function encodeLength (len, offset) { + if (len < 56) { + return Buffer.from([len + offset]) + } else { + var hexLength = intToHex(len) + var lLength = hexLength.length / 2 + var firstByte = intToHex(offset + 55 + lLength) + return Buffer.from(firstByte + hexLength, 'hex') + } + } + + /** + * 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 + * @returns {Array} - returns decode Array of Buffers containg the original message + **/ + exports.decode = function (input, stream) { + 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) { + return input.length + } else if (firstByte <= 0xb7) { + return firstByte - 0x7f + } else if (firstByte <= 0xbf) { + return firstByte - 0xb6 + } else if (firstByte <= 0xf7) { + // a list between 0-55 bytes long + return firstByte - 0xbf + } else { + // a list over 55 bytes long + var llength = firstByte - 0xf6 + var length = safeParseInt(input.slice(1, llength).toString('hex'), 16) + 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 { + data: input.slice(0, 1), + remainder: input.slice(1) + } + } else if (firstByte <= 0xb7) { + // string is 0-55 bytes long. A single byte with value 0x80 plus the length of the string followed by the string + // The range of the first byte is [0x80, 0xb7] + length = firstByte - 0x7f + + // set 0x80 null to 0 + if (firstByte === 0x80) { + data = Buffer.from([]) + } else { + data = input.slice(1, length) + } + + if (length === 2 && data[0] < 0x80) { + throw new Error('invalid rlp encoding: byte must be less 0x80') + } + + return { + data: data, + remainder: input.slice(length) + } + } else if (firstByte <= 0xbf) { + llength = firstByte - 0xb6 + length = safeParseInt(input.slice(1, llength).toString('hex'), 16) + data = input.slice(llength, length + llength) + if (data.length < length) { + throw (new Error('invalid RLP')) + } + + return { + data: data, + remainder: input.slice(length + llength) + } + } else if (firstByte <= 0xf7) { + // a list between 0-55 bytes long + length = firstByte - 0xbf + innerRemainder = input.slice(1, length) + while (innerRemainder.length) { + d = _decode(innerRemainder) + decoded.push(d.data) + innerRemainder = d.remainder + } + + return { + data: decoded, + remainder: input.slice(length) + } + } else { + // a list over 55 bytes long + llength = firstByte - 0xf6 + length = safeParseInt(input.slice(1, llength).toString('hex'), 16) + var totalLength = llength + length + if (totalLength > input.length) { + throw new Error('invalid rlp: total length is larger than the data') + } + + innerRemainder = input.slice(llength, totalLength) + if (innerRemainder.length === 0) { + throw new Error('invalid rlp, List has a invalid length') + } + + while (innerRemainder.length) { + d = _decode(innerRemainder) + decoded.push(d.data) + innerRemainder = d.remainder + } + return { + data: decoded, + remainder: input.slice(totalLength) + } + } + } + + function isHexPrefixed (str) { + return str.slice(0, 2) === '0x' + } + + // Removes 0x from a given String + function stripHexPrefix (str) { + if (typeof str !== 'string') { + return str + } + return isHexPrefixed(str) ? str.slice(2) : str + } + + 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') { + if (isHexPrefixed(v)) { + v = Buffer.from(padToEven(stripHexPrefix(v)), 'hex') + } else { + v = Buffer.from(v) + } + } else if (typeof v === 'number') { + if (!v) { + v = Buffer.from([]) + } else { + v = intToBuffer(v) + } + } else if (v === null || v === undefined) { + v = Buffer.from([]) + } else if (v.toArray) { + // converts a BN to a Buffer + v = Buffer.from(v.toArray()) + } else { + throw new Error('invalid type') + } + } + 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) { + dst[key] = src[key] + } + } + if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer + } else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer + } + + function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) + } + + // Copy static methods from Buffer + copyProps(Buffer, SafeBuffer) + + SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) + } + + SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf + } + + SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) + } + + SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) + } + + },{"buffer":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; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + // Note: The comments on the `throw` lines are intentional, they show + // up in Node's output if this results in an unhandled exception. + throw er; // Unhandled 'error' event + } + // At least give some kind of context to the user + var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); + 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); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + // edited: using safeApply + safeApply(listeners[i], this, args); + } + + return true; + } + + function safeApply(handler, context, args) { + try { + ReflectApply(handler, context, args) + } catch (err) { + // throw error after timeout so as not to interupt the stack + setTimeout(() => { + throw err + }) + } + } + + 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. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 'use strict'; + + var 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 + } else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target) + .concat(Object.getOwnPropertySymbols(target)); + }; + } else { + ReflectOwnKeys = function ReflectOwnKeys(target) { + 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() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); + } + 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) { + if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); + } + 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; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + // Note: The comments on the `throw` lines are intentional, they show + // up in Node's output if this results in an unhandled exception. + throw er; // Unhandled 'error' event + } + // At least give some kind of context to the user + var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); + 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 { + var len = handler.length; + var listeners = arrayClone(handler, len); + 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); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener !== 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; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + // If we've already got an array, just append. + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + + // Check for listener leak + m = $getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + // No error code for this since it is a Warning + // eslint-disable-next-line no-restricted-syntax + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + String(type) + ' listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + 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]); + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + 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); + wrapped.listener = listener; + 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); + } + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } + 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); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + + if (list.length === 1) + events[type] = list[0]; + + if (events.removeListener !== 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) { + this._events = Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== undefined) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = Object.create(null); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners !== undefined) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + + return this; + }; + + function _listeners(target, type, unwrap) { + var events = target._events; + + if (events === 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); + } else { + 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) { + ret[i] = arr[i].listener || arr[i]; + } + 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({ + current: currentOp, + total: totalOps, + percent: (currentOp / totalOps) * 100.0 + }) + } + } + } + + 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 + B32[i] |= (B[i * 4 + 2] & 0xff) << 16 + 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) + x[12] ^= R(x[ 8] + x[ 4], 13) + x[ 0] ^= R(x[12] + x[ 8], 18) + x[ 9] ^= R(x[ 5] + x[ 1], 7) + x[13] ^= R(x[ 9] + x[ 5], 9) + x[ 1] ^= R(x[13] + x[ 9], 13) + x[ 5] ^= R(x[ 1] + x[13], 18) + x[14] ^= R(x[10] + x[ 6], 7) + x[ 2] ^= R(x[14] + x[10], 9) + x[ 6] ^= R(x[ 2] + x[14], 13) + x[10] ^= R(x[ 6] + x[ 2], 18) + x[ 3] ^= R(x[15] + x[11], 7) + x[ 7] ^= R(x[ 3] + x[15], 9) + x[11] ^= R(x[ 7] + x[ 3], 13) + x[15] ^= R(x[11] + x[ 7], 18) + x[ 1] ^= R(x[ 0] + x[ 3], 7) + x[ 2] ^= R(x[ 1] + x[ 0], 9) + x[ 3] ^= R(x[ 2] + x[ 1], 13) + x[ 0] ^= R(x[ 3] + x[ 2], 18) + x[ 6] ^= R(x[ 5] + x[ 4], 7) + x[ 7] ^= R(x[ 6] + x[ 5], 9) + x[ 4] ^= R(x[ 7] + x[ 6], 13) + x[ 5] ^= R(x[ 4] + x[ 7], 18) + x[11] ^= R(x[10] + x[ 9], 7) + x[ 8] ^= R(x[11] + x[10], 9) + x[ 9] ^= R(x[ 8] + x[11], 13) + x[10] ^= R(x[ 9] + x[ 8], 18) + x[12] ^= R(x[15] + x[14], 7) + x[13] ^= R(x[12] + x[15], 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) + B[bi + 1] = (B32[i] >> 8 & 0xff) + B[bi + 2] = (B32[i] >> 16 & 0xff) + B[bi + 3] = (B32[i] >> 24 & 0xff) + // 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++) { + D[Di + i] ^= S[Si + i] + } + } + } + + function arraycopy (src, srcPos, dest, destPos, length) { + if (Buffer.isBuffer(src) && Buffer.isBuffer(dest)) { + src.copy(dest, destPos, srcPos, srcPos + length) + } else { + while (length--) { + dest[destPos++] = src[srcPos++] + } + } + } + + 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, + // private key + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // middle + 0xa0, 0x81, 0x85, 0x30, 0x81, 0x82, 0x02, 0x01, 0x01, 0x30, 0x2c, 0x06, 0x07, 0x2a, 0x86, 0x48, + 0xcE, 0x3d, 0x01, 0x01, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xfE, 0xff, 0xff, 0xfc, 0x2f, 0x30, 0x06, 0x04, 0x01, 0x00, 0x04, 0x01, 0x07, 0x04, + 0x21, 0x02, 0x79, 0xbE, 0x66, 0x7E, 0xf9, 0xdc, 0xbb, 0xac, 0x55, 0xa0, 0x62, 0x95, 0xcE, 0x87, + 0x0b, 0x07, 0x02, 0x9b, 0xfc, 0xdb, 0x2d, 0xcE, 0x28, 0xd9, 0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8, + 0x17, 0x98, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xfE, 0xba, 0xaE, 0xdc, 0xE6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5E, + 0x8c, 0xd0, 0x36, 0x41, 0x41, 0x02, 0x01, 0x01, 0xa1, 0x24, 0x03, 0x22, 0x00, + // public key + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00 + ]) + + var EC_PRIVKEY_EXPORT_DER_UNCOMPRESSED = Buffer.from([ + // begin + 0x30, 0x82, 0x01, 0x13, 0x02, 0x01, 0x01, 0x04, 0x20, + // private key + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // middle + 0xa0, 0x81, 0xa5, 0x30, 0x81, 0xa2, 0x02, 0x01, 0x01, 0x30, 0x2c, 0x06, 0x07, 0x2a, 0x86, 0x48, + 0xcE, 0x3d, 0x01, 0x01, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xfE, 0xff, 0xff, 0xfc, 0x2f, 0x30, 0x06, 0x04, 0x01, 0x00, 0x04, 0x01, 0x07, 0x04, + 0x41, 0x04, 0x79, 0xbE, 0x66, 0x7E, 0xf9, 0xdc, 0xbb, 0xac, 0x55, 0xa0, 0x62, 0x95, 0xcE, 0x87, + 0x0b, 0x07, 0x02, 0x9b, 0xfc, 0xdb, 0x2d, 0xcE, 0x28, 0xd9, 0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8, + 0x17, 0x98, 0x48, 0x3a, 0xda, 0x77, 0x26, 0xa3, 0xc4, 0x65, 0x5d, 0xa4, 0xfb, 0xfc, 0x0E, 0x11, + 0x08, 0xa8, 0xfd, 0x17, 0xb4, 0x48, 0xa6, 0x85, 0x54, 0x19, 0x9c, 0x47, 0xd0, 0x8f, 0xfb, 0x10, + 0xd4, 0xb8, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xfE, 0xba, 0xaE, 0xdc, 0xE6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5E, + 0x8c, 0xd0, 0x36, 0x41, 0x41, 0x02, 0x01, 0x01, 0xa1, 0x44, 0x03, 0x42, 0x00, + // public key + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00 + ]) + + exports.privateKeyExport = function (privateKey, publicKey, compressed) { + var result = Buffer.from(compressed ? EC_PRIVKEY_EXPORT_DER_COMPRESSED : EC_PRIVKEY_EXPORT_DER_UNCOMPRESSED) + privateKey.copy(result, compressed ? 8 : 9) + publicKey.copy(result, compressed ? 181 : 214) + return result + } + + exports.privateKeyImport = function (privateKey) { + var length = privateKey.length + + // sequence header + var index = 0 + if (length < index + 1 || privateKey[index] !== 0x30) return + index += 1 + + // sequence length constructor + if (length < index + 1 || !(privateKey[index] & 0x80)) return + + var lenb = privateKey[index] & 0x7f + index += 1 + if (lenb < 1 || lenb > 2) return + if (length < index + lenb) return + + // sequence length + var len = privateKey[index + lenb - 1] | (lenb > 1 ? privateKey[index + lenb - 2] << 8 : 0) + index += lenb + if (length < index + len) return + + // sequence element 0: version number (=1) + if (length < index + 3 || + privateKey[index] !== 0x02 || + privateKey[index + 1] !== 0x01 || + privateKey[index + 2] !== 0x01) { + return + } + index += 3 + + // sequence element 1: octet string, up to 32 bytes + if (length < index + 2 || + privateKey[index] !== 0x04 || + privateKey[index + 1] > 0x20 || + length < index + 2 + privateKey[index + 1]) { + return + } + + return privateKey.slice(index + 2, index + 2 + privateKey[index + 1]) + } + + exports.signatureExport = function (sigObj) { + var r = Buffer.concat([Buffer.from([0]), sigObj.r]) + for (var lenR = 33, posR = 0; lenR > 1 && r[posR] === 0x00 && !(r[posR + 1] & 0x80); --lenR, ++posR); + + var s = Buffer.concat([Buffer.from([0]), sigObj.s]) + for (var lenS = 33, posS = 0; lenS > 1 && s[posS] === 0x00 && !(s[posS + 1] & 0x80); --lenS, ++posS); + + return bip66.encode(r.slice(posR), s.slice(posS)) + } + + exports.signatureImport = function (sig) { + var r = Buffer.alloc(32, 0) + var s = Buffer.alloc(32, 0) + + try { + var sigObj = bip66.decode(sig) + if (sigObj.r.length === 33 && sigObj.r[0] === 0x00) sigObj.r = sigObj.r.slice(1) + if (sigObj.r.length > 32) throw new Error('R length is too long') + if (sigObj.s.length === 33 && sigObj.s[0] === 0x00) sigObj.s = sigObj.s.slice(1) + if (sigObj.s.length > 32) throw new Error('S length is too long') + } catch (err) { + return + } + + sigObj.r.copy(r, 32 - sigObj.r.length) + sigObj.s.copy(s, 32 - sigObj.s.length) + + return { r: r, s: s } + } + + exports.signatureImportLax = function (sig) { + var r = Buffer.alloc(32, 0) + var s = Buffer.alloc(32, 0) + + var length = sig.length + var index = 0 + + // sequence tag byte + if (sig[index++] !== 0x30) return + + // sequence length byte + var lenbyte = sig[index++] + if (lenbyte & 0x80) { + index += lenbyte - 0x80 + if (index > length) return + } + + // sequence tag byte for r + if (sig[index++] !== 0x02) return + + // length for r + var rlen = sig[index++] + if (rlen & 0x80) { + lenbyte = rlen - 0x80 + if (index + lenbyte > length) return + for (; lenbyte > 0 && sig[index] === 0x00; index += 1, lenbyte -= 1); + for (rlen = 0; lenbyte > 0; index += 1, lenbyte -= 1) rlen = (rlen << 8) + sig[index] + } + if (rlen > length - index) return + var rindex = index + index += rlen + + // sequence tag byte for s + if (sig[index++] !== 0x02) return + + // length for s + var slen = sig[index++] + if (slen & 0x80) { + lenbyte = slen - 0x80 + if (index + lenbyte > length) return + for (; lenbyte > 0 && sig[index] === 0x00; index += 1, lenbyte -= 1); + for (slen = 0; lenbyte > 0; index += 1, lenbyte -= 1) slen = (slen << 8) + sig[index] + } + if (slen > length - index) return + var sindex = index + index += slen + + // ignore leading zeros in r + for (; rlen > 0 && sig[rindex] === 0x00; rlen -= 1, rindex += 1); + // copy r value + if (rlen > 32) return + var rvalue = sig.slice(rindex, rindex + rlen) + rvalue.copy(r, 32 - rvalue.length) + + // ignore leading zeros in s + for (; slen > 0 && sig[sindex] === 0x00; slen -= 1, sindex += 1); + // copy s value + if (slen > 32) return + var svalue = sig.slice(sindex, sindex + slen) + svalue.copy(s, 32 - svalue.length) + + return { r: r, s: s } + } + + },{"bip66":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) { + case 0x02: + case 0x03: + if (publicKey.length !== 33) return null + return loadCompressedPublicKey(first, publicKey.slice(1, 33)) + case 0x04: + case 0x06: + case 0x07: + if (publicKey.length !== 65) return null + return loadUncompressedPublicKey(first, publicKey.slice(1, 33), publicKey.slice(33, 65)) + default: + return null + } + } + + exports.privateKeyVerify = function (privateKey) { + var bn = new BN(privateKey) + return bn.cmp(ecparams.n) < 0 && !bn.isZero() + } + + exports.privateKeyExport = function (privateKey, compressed) { + var d = new BN(privateKey) + if (d.cmp(ecparams.n) >= 0 || d.isZero()) throw new Error(messages.EC_PRIVATE_KEY_EXPORT_DER_FAIL) + + return Buffer.from(ec.keyFromPrivate(privateKey).getPublic(compressed, true)) + } + + exports.privateKeyNegate = function (privateKey) { + var bn = new BN(privateKey) + return bn.isZero() ? Buffer.alloc(32) : ecparams.n.sub(bn).umod(ecparams.n).toArrayLike(Buffer, 'be', 32) + } + + exports.privateKeyModInverse = function (privateKey) { + var bn = new BN(privateKey) + if (bn.cmp(ecparams.n) >= 0 || bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_RANGE_INVALID) + + return bn.invm(ecparams.n).toArrayLike(Buffer, 'be', 32) + } + + exports.privateKeyTweakAdd = function (privateKey, tweak) { + var bn = new BN(tweak) + if (bn.cmp(ecparams.n) >= 0) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_ADD_FAIL) + + bn.iadd(new BN(privateKey)) + if (bn.cmp(ecparams.n) >= 0) bn.isub(ecparams.n) + if (bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_ADD_FAIL) + + return bn.toArrayLike(Buffer, 'be', 32) + } + + exports.privateKeyTweakMul = function (privateKey, tweak) { + var bn = new BN(tweak) + if (bn.cmp(ecparams.n) >= 0 || bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_MUL_FAIL) + + bn.imul(new BN(privateKey)) + if (bn.cmp(ecparams.n)) bn = bn.umod(ecparams.n) + + return bn.toArrayLike(Buffer, 'be', 32) + } + + exports.publicKeyCreate = function (privateKey, compressed) { + var d = new BN(privateKey) + if (d.cmp(ecparams.n) >= 0 || d.isZero()) throw new Error(messages.EC_PUBLIC_KEY_CREATE_FAIL) + + return Buffer.from(ec.keyFromPrivate(privateKey).getPublic(compressed, true)) + } + + exports.publicKeyConvert = function (publicKey, compressed) { + var pair = loadPublicKey(publicKey) + if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) + + return Buffer.from(pair.getPublic(compressed, true)) + } + + exports.publicKeyVerify = function (publicKey) { + return loadPublicKey(publicKey) !== null + } + + exports.publicKeyTweakAdd = function (publicKey, tweak, compressed) { + var pair = loadPublicKey(publicKey) + if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) + + tweak = new BN(tweak) + if (tweak.cmp(ecparams.n) >= 0) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_ADD_FAIL) + + 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([ + result.r.toArrayLike(Buffer, 'be', 32), + result.s.toArrayLike(Buffer, 'be', 32) + ]), + recovery: result.recoveryParam + } + } + + exports.verify = function (message, signature, publicKey) { + var sigObj = {r: signature.slice(0, 32), s: signature.slice(32, 64)} + + var sigr = new BN(sigObj.r) + var sigs = new BN(sigObj.s) + if (sigr.cmp(ecparams.n) >= 0 || sigs.cmp(ecparams.n) >= 0) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL) + if (sigs.cmp(ec.nh) === 1 || sigr.isZero() || sigs.isZero()) return false + + var pair = loadPublicKey(publicKey) + if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) + + return ec.verify(message, sigObj, {x: pair.pub.x, y: pair.pub.y}) + } + + exports.recover = function (message, signature, recovery, compressed) { + var sigObj = {r: signature.slice(0, 32), s: signature.slice(32, 64)} + + var sigr = new BN(sigObj.r) + var sigs = new BN(sigObj.s) + if (sigr.cmp(ecparams.n) >= 0 || sigs.cmp(ecparams.n) >= 0) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL) + + try { + if (sigr.isZero() || sigs.isZero()) throw new Error() + + var point = ec.recoverPubKey(message, sigObj, recovery) + return Buffer.from(point.encode(true, compressed)) + } catch (err) { + throw new Error(messages.ECDSA_RECOVER_FAIL) + } + } + + exports.ecdh = function (publicKey, privateKey) { + var shared = exports.ecdhUnsafe(publicKey, privateKey, true) + return createHash('sha256').update(shared).digest() + } + + exports.ecdhUnsafe = function (publicKey, privateKey, compressed) { + var pair = loadPublicKey(publicKey) + if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) + + var scalar = new BN(privateKey) + if (scalar.cmp(ecparams.n) >= 0 || scalar.isZero()) throw new Error(messages.ECDH_FAIL) + + return Buffer.from(pair.pub.mul(scalar).encode(true, compressed)) + } + + },{"../messages.json":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) + for (var i = 0; i < publicKeys.length; ++i) { + assert.isBuffer(publicKeys[i], messages.EC_PUBLIC_KEY_TYPE_INVALID) + assert.isBufferLength2(publicKeys[i], 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) + } + + compressed = initCompressedValue(compressed, true) + + return secp256k1.publicKeyCombine(publicKeys, compressed) + }, + + signatureNormalize: function (signature) { + assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) + assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) + + return secp256k1.signatureNormalize(signature) + }, + + signatureExport: function (signature) { + assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) + assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) + + var sigObj = secp256k1.signatureExport(signature) + return der.signatureExport(sigObj) + }, + + signatureImport: function (sig) { + assert.isBuffer(sig, messages.ECDSA_SIGNATURE_TYPE_INVALID) + assert.isLengthGTZero(sig, messages.ECDSA_SIGNATURE_LENGTH_INVALID) + + var sigObj = der.signatureImport(sig) + if (sigObj) return secp256k1.signatureImport(sigObj) + + throw new Error(messages.ECDSA_SIGNATURE_PARSE_DER_FAIL) + }, + + signatureImportLax: function (sig) { + assert.isBuffer(sig, messages.ECDSA_SIGNATURE_TYPE_INVALID) + assert.isLengthGTZero(sig, messages.ECDSA_SIGNATURE_LENGTH_INVALID) + + var sigObj = der.signatureImportLax(sig) + if (sigObj) return secp256k1.signatureImport(sigObj) + + throw new Error(messages.ECDSA_SIGNATURE_PARSE_DER_FAIL) + }, + + sign: function (message, privateKey, options) { + assert.isBuffer(message, messages.MSG32_TYPE_INVALID) + assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID) + + assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) + assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) + + var data = null + var noncefn = null + if (options !== undefined) { + assert.isObject(options, messages.OPTIONS_TYPE_INVALID) + + if (options.data !== undefined) { + assert.isBuffer(options.data, messages.OPTIONS_DATA_TYPE_INVALID) + assert.isBufferLength(options.data, 32, messages.OPTIONS_DATA_LENGTH_INVALID) + data = options.data + } + + if (options.noncefn !== undefined) { + assert.isFunction(options.noncefn, messages.OPTIONS_NONCEFN_TYPE_INVALID) + noncefn = options.noncefn + } + } + + return secp256k1.sign(message, privateKey, noncefn, data) + }, + + verify: function (message, signature, publicKey) { + assert.isBuffer(message, messages.MSG32_TYPE_INVALID) + assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID) + + assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) + assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) + + assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) + assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) + + return secp256k1.verify(message, signature, publicKey) + }, + + recover: function (message, signature, recovery, compressed) { + assert.isBuffer(message, messages.MSG32_TYPE_INVALID) + assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID) + + assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) + assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) + + assert.isNumber(recovery, messages.RECOVERY_ID_TYPE_INVALID) + assert.isNumberInInterval(recovery, -1, 4, messages.RECOVERY_ID_VALUE_INVALID) + + compressed = initCompressedValue(compressed, true) + + return secp256k1.recover(message, signature, recovery, compressed) + }, + + ecdh: function (publicKey, privateKey) { + assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) + assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) + + assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) + assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) + + return secp256k1.ecdh(publicKey, privateKey) + }, + + ecdhUnsafe: function (publicKey, privateKey, compressed) { + assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) + assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) + + assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) + assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) + + compressed = initCompressedValue(compressed, true) + + return secp256k1.ecdhUnsafe(publicKey, privateKey, compressed) + } + } + } + + },{"./assert":296,"./der":297,"./messages.json":300}],300:[function(require,module,exports){ + module.exports={ + "COMPRESSED_TYPE_INVALID": "compressed should be a boolean", + "EC_PRIVATE_KEY_TYPE_INVALID": "private key should be a Buffer", + "EC_PRIVATE_KEY_LENGTH_INVALID": "private key length is invalid", + "EC_PRIVATE_KEY_RANGE_INVALID": "private key range is invalid", + "EC_PRIVATE_KEY_TWEAK_ADD_FAIL": "tweak out of range or resulting private key is invalid", + "EC_PRIVATE_KEY_TWEAK_MUL_FAIL": "tweak out of range", + "EC_PRIVATE_KEY_EXPORT_DER_FAIL": "couldn't export to DER format", + "EC_PRIVATE_KEY_IMPORT_DER_FAIL": "couldn't import from DER format", + "EC_PUBLIC_KEYS_TYPE_INVALID": "public keys should be an Array", + "EC_PUBLIC_KEYS_LENGTH_INVALID": "public keys Array should have at least 1 element", + "EC_PUBLIC_KEY_TYPE_INVALID": "public key should be a Buffer", + "EC_PUBLIC_KEY_LENGTH_INVALID": "public key length is invalid", + "EC_PUBLIC_KEY_PARSE_FAIL": "the public key could not be parsed or is invalid", + "EC_PUBLIC_KEY_CREATE_FAIL": "private was invalid, try again", + "EC_PUBLIC_KEY_TWEAK_ADD_FAIL": "tweak out of range or resulting public key is invalid", + "EC_PUBLIC_KEY_TWEAK_MUL_FAIL": "tweak out of range", + "EC_PUBLIC_KEY_COMBINE_FAIL": "the sum of the public keys is not valid", + "ECDH_FAIL": "scalar was invalid (zero or overflow)", + "ECDSA_SIGNATURE_TYPE_INVALID": "signature should be a Buffer", + "ECDSA_SIGNATURE_LENGTH_INVALID": "signature length is invalid", + "ECDSA_SIGNATURE_PARSE_FAIL": "couldn't parse signature", + "ECDSA_SIGNATURE_PARSE_DER_FAIL": "couldn't parse DER signature", + "ECDSA_SIGNATURE_SERIALIZE_DER_FAIL": "couldn't serialize signature to DER format", + "ECDSA_SIGN_FAIL": "nonce generation function failed or private key is invalid", + "ECDSA_RECOVER_FAIL": "couldn't recover public key from signature", + "MSG32_TYPE_INVALID": "message should be a Buffer", + "MSG32_LENGTH_INVALID": "message length is invalid", + "OPTIONS_TYPE_INVALID": "options should be an Object", + "OPTIONS_DATA_TYPE_INVALID": "options.data should be a Buffer", + "OPTIONS_DATA_LENGTH_INVALID": "options.data length is invalid", + "OPTIONS_NONCEFN_TYPE_INVALID": "options.noncefn should be a Function", + "RECOVERY_ID_TYPE_INVALID": "recovery should be a Number", + "RECOVERY_ID_VALUE_INVALID": "recovery should have value between -1 and 4", + "TWEAK_TYPE_INVALID": "tweak should be a Buffer", + "TWEAK_LENGTH_INVALID": "tweak length is invalid" + } + + },{}],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++; + semaphore.firstHere = true; + var isFirst = 1; + } else { + 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--; + semaphore.firstHere = false; + } + 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; + } else if (typeof define === 'function' && define.amd) { + // amd export + define(function () { + return semaphore; + }); + } else { + // browser global + global.semaphore = semaphore; + } + }(this)); + + }).call(this,require('_process')) + },{"_process":257}],302:[function(require,module,exports){ + 'use strict'; + module.exports = typeof setImmediate === 'function' ? setImmediate : + function setImmediate() { + var args = [].slice.apply(arguments); + 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) + this._finalSize = finalSize + this._blockSize = blockSize + this._len = 0 + } + + Hash.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8' + data = Buffer.from(data, enc) + } + + var block = this._block + var blockSize = this._blockSize + var length = data.length + var accum = this._len + + for (var offset = 0; offset < length;) { + var assigned = accum % blockSize + var remainder = Math.min(length - offset, blockSize - assigned) + + for (var i = 0; i < remainder; i++) { + block[assigned + i] = data[offset + i] + } + + accum += remainder + offset += remainder + + if ((accum % blockSize) === 0) { + this._update(block) + } + } + + this._len += length + return this + } + + Hash.prototype.digest = function (enc) { + var rem = this._len % this._blockSize + + this._block[rem] = 0x80 + + // zero (rem + 1) trailing bits, where (rem + 1) is the smallest + // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize + this._block.fill(0, rem + 1) + + if (rem >= this._finalSize) { + this._update(this._block) + this._block.fill(0) + } + + var bits = this._len * 8 + + // uint32 + if (bits <= 0xffffffff) { + this._block.writeUInt32BE(bits, this._blockSize - 4) + + // uint64 + } else { + var lowBits = (bits & 0xffffffff) >>> 0 + var highBits = (bits - lowBits) / 0x100000000 + + this._block.writeUInt32BE(highBits, this._blockSize - 8) + this._block.writeUInt32BE(lowBits, this._blockSize - 4) + } + + this._update(this._block) + var hash = this._hash() + + return enc ? hash.toString(enc) : hash + } + + Hash.prototype._update = function () { + throw new Error('_update must be implemented by subclass') + } + + module.exports = Hash + + },{"safe-buffer":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 + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ + + var inherits = require('inherits') + var Hash = require('./hash') + var Buffer = require('safe-buffer').Buffer + + var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ] + + var W = new Array(80) + + function Sha () { + this.init() + this._w = W + + Hash.call(this, 64, 56) + } + + inherits(Sha, Hash) + + Sha.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + + return this + } + + function rotl5 (num) { + return (num << 5) | (num >>> 27) + } + + function rotl30 (num) { + return (num << 30) | (num >>> 2) + } + + function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d + } + + Sha.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16] + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + + e = d + d = c + c = rotl30(b) + b = a + a = t + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 + } + + Sha.prototype._hash = function () { + var H = Buffer.allocUnsafe(20) + + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) + + return H + } + + module.exports = Sha + + },{"./hash":303,"inherits":180,"safe-buffer":290}],306:[function(require,module,exports){ + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ + + var inherits = require('inherits') + var Hash = require('./hash') + var Buffer = require('safe-buffer').Buffer + + var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ] + + var W = new Array(80) + + function Sha1 () { + this.init() + this._w = W + + Hash.call(this, 64, 56) + } + + inherits(Sha1, Hash) + + Sha1.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + + return this + } + + function rotl1 (num) { + return (num << 1) | (num >>> 31) + } + + function rotl5 (num) { + return (num << 5) | (num >>> 27) + } + + function rotl30 (num) { + return (num << 30) | (num >>> 2) + } + + function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d + } + + Sha1.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]) + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + + e = d + d = c + c = rotl30(b) + b = a + a = t + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 + } + + Sha1.prototype._hash = function () { + var H = Buffer.allocUnsafe(20) + + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) + + return H + } + + module.exports = Sha1 + + },{"./hash":303,"inherits":180,"safe-buffer":290}],307:[function(require,module,exports){ + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + + var inherits = require('inherits') + var Sha256 = require('./sha256') + var Hash = require('./hash') + var Buffer = require('safe-buffer').Buffer + + var W = new Array(64) + + function Sha224 () { + this.init() + + this._w = W // new Array(64) + + Hash.call(this, 64, 56) + } + + inherits(Sha224, Sha256) + + Sha224.prototype.init = function () { + this._a = 0xc1059ed8 + this._b = 0x367cd507 + this._c = 0x3070dd17 + this._d = 0xf70e5939 + this._e = 0xffc00b31 + this._f = 0x68581511 + this._g = 0x64f98fa7 + this._h = 0xbefa4fa4 + + return this + } + + Sha224.prototype._hash = function () { + var H = Buffer.allocUnsafe(28) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + + return H + } + + module.exports = Sha224 + + },{"./hash":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 + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + + var inherits = require('inherits') + var Hash = require('./hash') + var Buffer = require('safe-buffer').Buffer + + var K = [ + 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, + 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, + 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, + 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, + 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, + 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, + 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, + 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, + 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, + 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, + 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, + 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, + 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, + 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, + 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, + 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 + ] + + var W = new Array(64) + + function Sha256 () { + this.init() + + this._w = W // new Array(64) + + Hash.call(this, 64, 56) + } + + inherits(Sha256, Hash) + + Sha256.prototype.init = function () { + this._a = 0x6a09e667 + this._b = 0xbb67ae85 + this._c = 0x3c6ef372 + this._d = 0xa54ff53a + this._e = 0x510e527f + this._f = 0x9b05688c + this._g = 0x1f83d9ab + this._h = 0x5be0cd19 + + return this + } + + function ch (x, y, z) { + return z ^ (x & (y ^ z)) + } + + function maj (x, y, z) { + return (x & y) | (z & (x | y)) + } + + function sigma0 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) + } + + function sigma1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) + } + + function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) + } + + function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) + } + + Sha256.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + var f = this._f | 0 + var g = this._g | 0 + var h = this._h | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 + + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 + var T2 = (sigma0(a) + maj(a, b, c)) | 0 + + h = g + g = f + f = e + e = (d + T1) | 0 + d = c + c = b + b = a + a = (T1 + T2) | 0 + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 + this._f = (f + this._f) | 0 + this._g = (g + this._g) | 0 + this._h = (h + this._h) | 0 + } + + Sha256.prototype._hash = function () { + var H = Buffer.allocUnsafe(32) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + H.writeInt32BE(this._h, 28) + + return H + } + + module.exports = Sha256 + + },{"./hash":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 + this._ch = 0x9159015a + this._dh = 0x152fecd8 + this._eh = 0x67332667 + this._fh = 0x8eb44a87 + this._gh = 0xdb0c2e0d + this._hh = 0x47b5481d + + this._al = 0xc1059ed8 + this._bl = 0x367cd507 + this._cl = 0x3070dd17 + this._dl = 0xf70e5939 + this._el = 0xffc00b31 + this._fl = 0x68581511 + this._gl = 0x64f98fa7 + this._hl = 0xbefa4fa4 + + return this + } + + Sha384.prototype._hash = function () { + var H = Buffer.allocUnsafe(48) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + + return H + } + + module.exports = Sha384 + + },{"./hash":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, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 + ] + + var W = new Array(160) + + function Sha512 () { + this.init() + this._w = W + + Hash.call(this, 128, 112) + } + + inherits(Sha512, Hash) + + Sha512.prototype.init = function () { + this._ah = 0x6a09e667 + this._bh = 0xbb67ae85 + this._ch = 0x3c6ef372 + this._dh = 0xa54ff53a + this._eh = 0x510e527f + this._fh = 0x9b05688c + this._gh = 0x1f83d9ab + this._hh = 0x5be0cd19 + + this._al = 0xf3bcc908 + this._bl = 0x84caa73b + this._cl = 0xfe94f82b + this._dl = 0x5f1d36f1 + this._el = 0xade682d1 + this._fl = 0x2b3e6c1f + this._gl = 0xfb41bd6b + this._hl = 0x137e2179 + + return this + } + + function Ch (x, y, z) { + return z ^ (x & (y ^ z)) + } + + function maj (x, y, z) { + return (x & y) | (z & (x | y)) + } + + function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) + } + + function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) + } + + function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) + } + + function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) + } + + function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) + } + + function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) + } + + function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 + } + + Sha512.prototype._update = function (M) { + var W = this._w + + var ah = this._ah | 0 + var bh = this._bh | 0 + var ch = this._ch | 0 + var dh = this._dh | 0 + var eh = this._eh | 0 + var fh = this._fh | 0 + var gh = this._gh | 0 + var hh = this._hh | 0 + + var al = this._al | 0 + var bl = this._bl | 0 + var cl = this._cl | 0 + var dl = this._dl | 0 + var el = this._el | 0 + var fl = this._fl | 0 + var gl = this._gl | 0 + var hl = this._hl | 0 + + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4) + W[i + 1] = M.readInt32BE(i * 4 + 4) + } + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2] + var xl = W[i - 15 * 2 + 1] + var gamma0 = Gamma0(xh, xl) + var gamma0l = Gamma0l(xl, xh) + + xh = W[i - 2 * 2] + xl = W[i - 2 * 2 + 1] + var gamma1 = Gamma1(xh, xl) + var gamma1l = Gamma1l(xl, xh) + + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2] + var Wi7l = W[i - 7 * 2 + 1] + + var Wi16h = W[i - 16 * 2] + var Wi16l = W[i - 16 * 2 + 1] + + var Wil = (gamma0l + Wi7l) | 0 + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 + Wil = (Wil + gamma1l) | 0 + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 + Wil = (Wil + Wi16l) | 0 + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 + + W[i] = Wih + W[i + 1] = Wil + } + + for (var j = 0; j < 160; j += 2) { + Wih = W[j] + Wil = W[j + 1] + + var majh = maj(ah, bh, ch) + var majl = maj(al, bl, cl) + + var sigma0h = sigma0(ah, al) + var sigma0l = sigma0(al, ah) + var sigma1h = sigma1(eh, el) + var sigma1l = sigma1(el, eh) + + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K[j] + var Kil = K[j + 1] + + var chh = Ch(eh, fh, gh) + var chl = Ch(el, fl, gl) + + var t1l = (hl + sigma1l) | 0 + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 + t1l = (t1l + chl) | 0 + t1h = (t1h + chh + getCarry(t1l, chl)) | 0 + t1l = (t1l + Kil) | 0 + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 + t1l = (t1l + Wil) | 0 + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 + + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0 + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 + + hh = gh + hl = gl + gh = fh + gl = fl + fh = eh + fl = el + el = (dl + t1l) | 0 + eh = (dh + t1h + getCarry(el, dl)) | 0 + dh = ch + dl = cl + ch = bh + cl = bl + bh = ah + bl = al + al = (t1l + t2l) | 0 + ah = (t1h + t2h + getCarry(al, t1l)) | 0 + } + + this._al = (this._al + al) | 0 + this._bl = (this._bl + bl) | 0 + this._cl = (this._cl + cl) | 0 + this._dl = (this._dl + dl) | 0 + this._el = (this._el + el) | 0 + this._fl = (this._fl + fl) | 0 + this._gl = (this._gl + gl) | 0 + this._hl = (this._hl + hl) | 0 + + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 + } + + Sha512.prototype._hash = function () { + var H = Buffer.allocUnsafe(64) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + writeInt64BE(this._gh, this._gl, 48) + writeInt64BE(this._hh, this._hl, 56) + + return H + } + + module.exports = Sha512 + + },{"./hash":303,"inherits":180,"safe-buffer":290}],311:[function(require,module,exports){ + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + module.exports = Stream; + + var EE = require('events').EventEmitter; + var inherits = require('inherits'); + + inherits(Stream, EE); + Stream.Readable = require('readable-stream/readable.js'); + Stream.Writable = require('readable-stream/writable.js'); + Stream.Duplex = require('readable-stream/duplex.js'); + Stream.Transform = require('readable-stream/transform.js'); + Stream.PassThrough = require('readable-stream/passthrough.js'); + + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; + + + + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. + + function Stream() { + EE.call(this); + } + + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; + + },{"events":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') + var IncomingMessage = require('./lib/response') + 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', + 'COPY', + 'DELETE', + 'GET', + 'HEAD', + 'LOCK', + 'M-SEARCH', + 'MERGE', + 'MKACTIVITY', + 'MKCOL', + 'MOVE', + 'NOTIFY', + 'OPTIONS', + 'PATCH', + 'POST', + 'PROPFIND', + 'PROPPATCH', + 'PURGE', + 'PUT', + 'REPORT', + 'SEARCH', + 'SUBSCRIBE', + 'TRACE', + 'UNLOCK', + 'UNSUBSCRIBE' + ] + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + },{"./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. + var xhr + 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 + // cross domain), use the page location. Otherwise use example.com + // Note: this doesn't actually make an http request. + try { + xhr.open('GET', global.XDomainRequest ? '/' : 'https://example.com') + } catch(e) { + xhr = null + } + } else { + // Service workers don't have XHR + xhr = null + } + return xhr + } + + function checkTypeSupport (type) { + var xhr = getXHR() + if (!xhr) return false + try { + xhr.responseType = type + return xhr.responseType === type + } 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){ + var capability = require('./capability') + var inherits = require('inherits') + 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' + } else if (capability.mozchunkedarraybuffer) { + return 'moz-chunked-arraybuffer' + } else if (capability.msstream) { + return 'ms-stream' + } else if (capability.arraybuffer && preferBinary) { + return 'arraybuffer' + } else if (capability.vbArray && preferBinary) { + return 'text:vbarray' + } else { + return 'text' + } + } + + var ClientRequest = module.exports = function (opts) { + var self = this + stream.Writable.call(self) + + self._opts = opts + self._body = [] + self._headers = {} + if (opts.auth) + self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64')) + 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)) { + // If the use of XHR should be preferred. Not typically needed. + useFetch = false + preferBinary = true + } else if (opts.mode === 'prefer-streaming') { + // If streaming is a high priority but binary compatibility and + // the accuracy of the 'content-type' header aren't + preferBinary = false + } else if (opts.mode === 'allow-wrong-content-type') { + // If streaming is more important than preserving the 'content-type' header + preferBinary = !capability.overrideMimeType + } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') { + // Use binary if text streaming may corrupt data or the content-type header, or for speed + preferBinary = true + } else { + 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() + // This check is not necessary, but it prevents warnings from browsers about setting unsafe + // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but + // 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') { + if (capability.arraybuffer) { + body = toArrayBuffer(Buffer.concat(self._body)) + } else if (capability.blobConstructor) { + body = new global.Blob(self._body.map(function (buffer) { + return toArrayBuffer(buffer) + }), { + type: (headersObj['content-type'] || {}).value || '' + }) + } else { + // get utf8 string + body = Buffer.concat(self._body).toString() + } + } + + // create flattened list of headers + var headersList = [] + Object.keys(headersObj).forEach(function (keyName) { + var name = headersObj[keyName].name + var value = headersObj[keyName].value + if (Array.isArray(value)) { + value.forEach(function (v) { + headersList.push([name, v]) + }) + } else { + 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') + if (self._fetchAbortController) + self._fetchAbortController.abort() + }, opts.requestTimeout) + } + } + + global.fetch(self._opts.url, { + method: self._opts.method, + headers: headersList, + body: body || undefined, + mode: 'cors', + credentials: opts.withCredentials ? 'include' : 'same-origin', + signal: signal + }).then(function (response) { + self._fetchResponse = response + self._connect() + }, function (reason) { + self.emit('error', reason) + }) + } else { + var xhr = self._xhr = new global.XMLHttpRequest() + try { + xhr.open(self._opts.method, self._opts.url, true) + } catch (err) { + process.nextTick(function () { + self.emit('error', err) + }) + 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) { + case rStates.LOADING: + case rStates.DONE: + self._onXHRProgress() + break + } + } + // Necessary for streaming in Firefox, since xhr.response is ONLY defined + // in onprogress, not in onreadystatechange with xhr.readyState = 3 + if (self._mode === 'moz-chunked-arraybuffer') { + xhr.onprogress = function () { + self._onXHRProgress() + } + } + + xhr.onerror = function () { + if (self._destroyed) + return + self.emit('error', new Error('XHR error')) + } + + try { + xhr.send(body) + } catch (err) { + process.nextTick(function () { + self.emit('error', err) + }) + return + } + } + } + + /** + * Checks if xhr.status is readable and non-zero, indicating no error. + * Even though the spec says it should be available in readyState 3, + * accessing it throws an exception in IE8 + */ + function statusValid (xhr) { + try { + var status = xhr.status + return (status !== null && status !== 0) + } catch (e) { + 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 + if (self._response) + self._response._destroyed = true + if (self._xhr) + self._xhr.abort() + 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', + 'accept-encoding', + 'access-control-request-headers', + 'access-control-request-method', + 'connection', + 'content-length', + 'cookie', + 'cookie2', + 'date', + 'dnt', + 'expect', + 'host', + 'keep-alive', + 'origin', + 'referer', + 'te', + 'trailer', + 'transfer-encoding', + 'upgrade', + '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, + HEADERS_RECEIVED: 2, + 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 + process.nextTick(function () { + 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) { + return new Promise(function (resolve, reject) { + if (self._destroyed) { + return + } else if(self.push(new Buffer(chunk))) { + resolve() + } else { + self._resumeFetch = resolve + } + }) + }, + close: function () { + if (!self._destroyed) + self.push(null) + }, + abort: function (err) { + if (!self._destroyed) + self.emit('error', err) + } + }) + + try { + response.body.pipeTo(writable) + return + } catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this + } + // fallback for when writableStream or pipeTo aren't available + var reader = response.body.getReader() + function read () { + reader.read().then(function (result) { + if (self._destroyed) + return + if (result.done) { + self.push(null) + return + } + self.push(new Buffer(result.value)) + read() + }).catch(function(err) { + if (!self._destroyed) + self.emit('error', err) + }) + } + read() + } else { + self._xhr = xhr + self._pos = 0 + + self.url = xhr.responseURL + self.statusCode = xhr.status + self.statusMessage = xhr.statusText + var headers = xhr.getAllResponseHeaders().split(/\r?\n/) + headers.forEach(function (header) { + var matches = header.match(/^([^:]+):\s*(.*)/) + if (matches) { + var key = matches[1].toLowerCase() + if (key === 'set-cookie') { + if (self.headers[key] === undefined) { + self.headers[key] = [] + } + self.headers[key].push(matches[2]) + } else if (self.headers[key] !== undefined) { + self.headers[key] += ', ' + matches[2] + } else { + self.headers[key] = matches[2] + } + self.rawHeaders.push(matches[1], matches[2]) + } + }) + + self._charset = 'x-user-defined' + if (!capability.overrideMimeType) { + var mimeType = self.rawHeaders['mime-type'] + if (mimeType) { + var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/) + if (charsetMatch) { + self._charset = charsetMatch[1].toLowerCase() + } + } + if (!self._charset) + self._charset = 'utf-8' // best guess + } + } + } + + 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 + if (xhr.readyState !== rStates.DONE) + break + try { + // This fails in IE8 + response = new global.VBArray(xhr.responseBody).toArray() + } catch (e) {} + if (response !== null) { + self.push(new Buffer(response)) + break + } + // 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 + } catch (e) { + self._mode = 'text:vbarray' + break + } + if (response.length > self._pos) { + var newData = response.substr(self._pos) + if (self._charset === 'x-user-defined') { + 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) + } + self._pos = response.length + } + break + case 'arraybuffer': + if (xhr.readyState !== rStates.DONE || !xhr.response) + break + response = xhr.response + self.push(new Buffer(new Uint8Array(response))) + break + case 'moz-chunked-arraybuffer': // take whole + response = xhr.response + if (xhr.readyState !== rStates.LOADING || !response) + break + self.push(new Buffer(new Uint8Array(response))) + break + case 'ms-stream': + response = xhr.response + if (xhr.readyState !== rStates.LOADING) + break + var reader = new global.MSStreamReader() + reader.onprogress = function () { + if (reader.result.byteLength > self._pos) { + self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos)))) + self._pos = reader.result.byteLength + } + } + reader.onload = function () { + self.push(null) + } + // reader.onerror = ??? // TODO: this + 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'; + module.exports = function (str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { + 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()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } + }; + + function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } + }; + + // Do not cache `Buffer.isEncoding` when checking encoding names as some + // modules monkey-patch it to support additional encodings + function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. + exports.StringDecoder = StringDecoder; + function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); + } + + StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; + }; + + StringDecoder.prototype.end = utf8End; + + // Returns only complete characters in a Buffer + StringDecoder.prototype.text = utf8Text; + + // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer + StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; + }; + + // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a + // continuation byte. + 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. + function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; + } + + // Validates as many continuation bytes for a multi-byte UTF-8 character as + // needed or are available. If we see a non-continuation byte where we expect + // one, we "replace" the validated continuation bytes we've seen so far with + // UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding + // behavior. The continuation byte check is included three times in the case + // where all of the continuation bytes for a character exist in the same buffer. + // It is also done this way as a slight performance increase instead of using a + // loop. + function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'.repeat(p); + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'.repeat(p + 1); + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'.repeat(p + 2); + } + } + } + } + + // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. + function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; + } + + // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a + // partial character, the character's bytes are buffered until the required + // number of bytes are available. + function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); + } + + // For UTF-8, a replacement character for each buffered byte of a (partial) + // character needs to be added to the output. + function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + 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 + // decode the last character properly. + function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); + } + + // For UTF-16LE we do not explicitly append special replacement characters if we + // end on a partial character, we simply let v8 handle that. + function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; + } + + function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); + } + + function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; + } + + // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) + function simpleWrite(buf) { + return buf.toString(this.encoding); + } + + function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; + } + },{"safe-buffer":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 + * @return {String|Optional} a string by pass if necessary + */ + module.exports = function stripHexPrefix(str) { + if (typeof str !== 'string') { + return str; + } + + return isHexPrefixed(str) ? str.slice(2) : str; + } + + },{"is-hex-prefixed":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 }; + var path = { join: unavailable, slice: unavailable }; + var child_process = { spawn: unavailable }; + var mimetype = { lookup: unavailable }; + var defaultArchives = {}; + var downloadUrl = null; + var request = require("xhr-request-promise"); + var bytes = require("eth-lib/lib/bytes"); + var hash = require("./swarm-hash.js"); + var pick = require("./pick.js"); + var swarm = require("./swarm"); + + module.exports = swarm({ + fsp: fsp, + files: files, + os: os, + path: path, + child_process: child_process, + defaultArchives: defaultArchives, + mimetype: mimetype, + request: request, + downloadUrl: downloadUrl, + bytes: bytes, + hash: hash, + pick: pick + }); + },{"./pick.js":320,"./swarm":322,"./swarm-hash.js":321,"eth-lib/lib/bytes":133,"xhr-request-promise":411}],320:[function(require,module,exports){ + var picker = function picker(type) { + return function () { + return new Promise(function (resolve, reject) { + var fileLoader = function fileLoader(e) { + var directory = {}; + var totalFiles = e.target.files.length; + var loadedFiles = 0; + [].map.call(e.target.files, function (file) { + var reader = new FileReader(); + reader.onload = function (e) { + var data = new Uint8Array(e.target.result); + if (type === "directory") { + var path = file.webkitRelativePath; + directory[path.slice(path.indexOf("/") + 1)] = { + type: "text/plain", + data: data + }; + if (++loadedFiles === totalFiles) resolve(directory); + } else if (type === "file") { + var _path = file.webkitRelativePath; + resolve({ "type": mimetype.lookup(_path), "data": data }); + } else { + resolve(data); + } + }; + reader.readAsArrayBuffer(file); + }); + }; + + var fileInput = void 0; + if (type === "directory") { + fileInput = document.createElement("input"); + fileInput.addEventListener("change", fileLoader); + fileInput.type = "file"; + fileInput.webkitdirectory = true; + fileInput.mozdirectory = true; + fileInput.msdirectory = true; + fileInput.odirectory = true; + fileInput.directory = true; + } else { + fileInput = document.createElement("input"); + 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"), + directory: picker("directory") + }; + },{}],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") { + data = Bytes.fromString(data); + } 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 + // slightly better long-term solution would be to split this file into two, + // separating the functions that are used on Node.js from the functions that + // are used only on the browser. + module.exports = function (_ref) { + var fsp = _ref.fsp, + files = _ref.files, + os = _ref.os, + path = _ref.path, + child_process = _ref.child_process, + mimetype = _ref.mimetype, + defaultArchives = _ref.defaultArchives, + request = _ref.request, + downloadUrl = _ref.downloadUrl, + 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) { + return function (val) { + return function (map) { + return map[key] = val, map; + }; + }; + }; + + // String -> JSON -> Map String JSON + // Merges an array of keys and an array of vals into an object. + var toMap = function toMap(keys) { + return function (vals) { + var map = {}; + for (var i = 0, l = keys.length; i < l; ++i) { + map[keys[i]] = vals[i]; + }return map; + }; + }; + + // ∀ a . Map String a -> Map String a -> Map String a + // Merges two maps into one. + var merge = function merge(a) { + return function (b) { + var map = {}; + for (var key in a) { + map[key] = a[key]; + }for (var _key in b) { + map[_key] = b[_key]; + }return map; + }; + }; + + // ∀ a . [a] -> [a] -> Bool + var equals = function equals(a) { + return function (b) { + if (a.length !== b.length) { + return false; + } else { + for (var i = 0, l = a.length; i < a; ++i) { + if (a[i] !== b[i]) return false; + } + } + 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) { + return function (hash) { + return request(rawUrl(swarmUrl)(hash), { responseType: "arraybuffer" }).then(function (arrayBuffer) { + var uint8Array = new Uint8Array(arrayBuffer); + var error404 = [52, 48, 52, 32, 112, 97, 103, 101, 32, 110, 111, 116, 32, 102, 111, 117, 110, 100, 10]; + if (equals(uint8Array)(error404)) throw "Error 404."; + return uint8Array; + }); + }; + }; + + // 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. + var downloadEntries = function downloadEntries(swarmUrl) { + return function (hash) { + var search = function search(hash) { + return function (path) { + return function (routes) { + // Formats an entry to the Swarm.js type. + var format = function format(entry) { + return { + 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 + var downloadEntry = function downloadEntry(entry) { + if (entry.path === undefined) { + return Promise.resolve(); + } else { + 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; + }).then(function (entries) { + return Promise.all(entries.map(downloadEntry)); + }).then(function () { + return routes; + }); + }; + }; + }; + + return search(hash)("")({}); + }; + }; + + // String -> String -> Promise (Map String String) + // Same as `downloadEntries`, but returns only hashes (no types). + var downloadRoutes = function downloadRoutes(swarmUrl) { + return function (hash) { + return downloadEntries(swarmUrl)(hash).then(function (entries) { + return toMap(Object.keys(entries))(Object.keys(entries).map(function (route) { + return entries[route].hash; + })); + }); + }; + }; + + // String -> String -> Promise (Map String File) + // Gets the entire directory tree in a Swarm address. + // Returns a promise mapping paths to file contents. + var downloadDirectory = function downloadDirectory(swarmUrl) { + return function (hash) { + return downloadEntries(swarmUrl)(hash).then(function (entries) { + var paths = Object.keys(entries); + var hashs = paths.map(function (path) { + return entries[path].hash; + }); + var types = paths.map(function (path) { + return entries[path].type; + }); + var datas = hashs.map(downloadData(swarmUrl)); + var files = function files(datas) { + return datas.map(function (data, i) { + return { type: types[i], data: data }; + }); + }; + return Promise.all(datas).then(function (datas) { + return toMap(paths)(files(datas)); + }); + }); + }; + }; + + // String -> String -> String -> Promise String + // Gets the raw contents of a Swarm hash address. + // Returns a promise with the downloaded file path. + var downloadDataToDisk = function downloadDataToDisk(swarmUrl) { + return function (hash) { + return function (filePath) { + return files.download(rawUrl(swarmUrl)(hash))(filePath); + }; + }; + }; + + // String -> String -> String -> Promise (Map String String) + // Gets the entire directory tree in a Swarm address. + // Returns a promise mapping paths to file contents. + var downloadDirectoryToDisk = function downloadDirectoryToDisk(swarmUrl) { + return function (hash) { + return function (dirPath) { + return downloadRoutes(swarmUrl)(hash).then(function (routingTable) { + var downloads = []; + for (var route in routingTable) { + if (route.length > 0) { + var filePath = path.join(dirPath, route); + downloads.push(downloadDataToDisk(swarmUrl)(routingTable[route])(filePath)); + }; + }; + return Promise.all(downloads).then(function () { + return dirPath; + }); + }); + }; + }; + }; + + // String -> Uint8Array -> Promise String + // Uploads raw data to Swarm. + // Returns a promise with the uploaded hash. + var uploadData = function uploadData(swarmUrl) { + return function (data) { + return request(swarmUrl + "/bzzr:/", { + body: typeof data === "string" ? fromString(data) : data, + 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. + // FIXME: for some reasons Swarm-Gateways is sometimes returning + // error 404 (bad request), so we retry up to 3 times. Why? + var uploadToManifest = function uploadToManifest(swarmUrl) { + return function (hash) { + return function (route) { + return function (file) { + var attempt = function attempt(n) { + var slashRoute = route[0] === "/" ? route : "/" + route; + var url = swarmUrl + "/bzz:/" + hash + slashRoute; + var opt = { + method: "PUT", + headers: { "Content-Type": file.type }, + body: file.data }; + return request(url, opt).then(function (response) { + if (response.indexOf("error") !== -1) { + throw response; + } + return response; + }).catch(function (e) { + return n > 0 && attempt(n - 1); + }); + }; + return attempt(3); + }; + }; + }; + }; + + // 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) { + return fsp.readFile(filePath).then(function (data) { + return uploadFile(swarmUrl)({ type: mimetype.lookup(filePath), data: data }); + }); + }; + }; + + // String -> Map String File -> Promise String + // Uploads a directory to Swarm. The directory is + // represented as a map of routes and files. + // A default path is encoded by having a "" route. + var uploadDirectory = function uploadDirectory(swarmUrl) { + return function (directory) { + return uploadData(swarmUrl)("{}").then(function (hash) { + var uploadRoute = function uploadRoute(route) { + return function (hash) { + return uploadToManifest(swarmUrl)(hash)(route)(directory[route]); + }; + }; + var uploadToHash = function uploadToHash(hash, route) { + return hash.then(uploadRoute(route)); + }; + return Object.keys(directory).reduce(uploadToHash, Promise.resolve(hash)); + }); + }; + }; + + // 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) { + return function (dirPath) { + return files.directoryTree(dirPath).then(function (fullPaths) { + return Promise.all(fullPaths.map(function (path) { + return fsp.readFile(path); + })).then(function (datas) { + var paths = fullPaths.map(function (path) { + return path.slice(dirPath.length); + }); + var types = fullPaths.map(function (path) { + return mimetype.lookup(path) || "text/plain"; + }); + return toMap(paths)(datas.map(function (data, i) { + return { type: types[i], data: data }; + })); + }); + }).then(function (directory) { + return merge(defaultPath ? { "": directory[defaultPath] } : {})(directory); + }).then(uploadDirectory(swarmUrl)); + }; + }; + }; + + // String -> UploadInfo -> Promise String + // Simplified multi-type upload which calls the correct + // one based on the type of the argument given. + var _upload = function _upload(swarmUrl) { + return function (arg) { + // 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) { + case "data": + return uploadDataFromDisk(swarmUrl)(arg.path); + case "file": + return uploadFileFromDisk(swarmUrl)(arg.path); + 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 + // directory or a file. + var _download = function _download(swarmUrl) { + return function (hash) { + return function (path) { + return isDirectory(swarmUrl)(hash).then(function (isDir) { + if (isDir) { + return path ? downloadDirectoryToDisk(swarmUrl)(hash)(path) : downloadDirectory(swarmUrl)(hash); + } else { + return path ? downloadDataToDisk(swarmUrl)(hash)(path) : downloadData(swarmUrl)(hash); + } + }); + }; + }; + }; + + // 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. + // If it was already there to begin with, skips the download. + var downloadBinary = function downloadBinary(path, archives) { + var system = os.platform().replace("win32", "windows") + "-" + (os.arch() === "x64" ? "amd64" : "386"); + var archive = (archives || defaultArchives)[system]; + var archiveUrl = downloadUrl + archive.archive + ".tar.gz"; + var archiveMD5 = archive.archiveMD5; + var binaryMD5 = archive.binaryMD5; + return files.safeDownloadArchived(archiveUrl)(archiveMD5)(binaryMD5)(path); + }; + + // type SwarmSetup = { + // account : String, + // password : String, + // dataDir : String, + // binPath : String, + // ensApi : String, + // onDownloadProgress : Number ~> (), + // archives : [{ + // archive: String, + // binaryMD5: String, + // 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; + }; + }; + var account = swarmSetup.account, + password = swarmSetup.password, + 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 () { + state = STARTING; + swarmProcess.stdin.write(password + '\n'); + }, 500); + } else if (hasString(LISTENING_HOOK)(data)) { + state = LISTENING; + clearTimeout(timeout); + 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); + }; + var error = function error() { + return reject(new Error("Couldn't start swarm process.")); + }; + var timeout = setTimeout(error, 20000); + }); + }; + + // Process ~> Promise () + // Stops the Swarm process. + var stopProcess = function stopProcess(process) { + return new Promise(function (resolve, reject) { + process.stderr.removeAllListeners('data'); + process.stdout.removeAllListeners('data'); + process.stdin.removeAllListeners('error'); + 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 + // downloads the Swarm binaries to the dataDir (if not there), checksums, + // starts the Swarm process and calls the callback function with an API + // object using the local node. That callback must return a promise which + // will resolve when it is done using the API, so that this function can + // close the Swarm process properly. Returns a promise that resolves when the + // user is done with the API and the Swarm process is closed. + // TODO: check if Swarm process is already running (improve `isAvailable`) + var local = function local(swarmSetup) { + return function (useAPI) { + return _isAvailable("http://localhost:8500").then(function (isAvailable) { + return isAvailable ? useAPI(at("http://localhost:8500")).then(function () {}) : downloadBinary(swarmSetup.binPath, swarmSetup.archives).onData(function (data) { + return (swarmSetup.onProgress || function () {})(data.length); + }).then(function () { + return startProcess(swarmSetup); + }).then(function (process) { + return useAPI(at("http://localhost:8500")).then(function () { + return process; + }); + }).then(stopProcess); + }); + }; + }; + + // String ~> Promise Bool + // Returns true if Swarm is available on `url`. + // Perfoms a test upload to determine that. + // TODO: improve this? + var _isAvailable = function _isAvailable(swarmUrl) { + var testFile = "test"; + var testHash = "c9a99c7d326dcc6316f32fe2625b311f6dc49a175e6877681ded93137d3569e7"; + return uploadData(swarmUrl)(testFile).then(function (hash) { + return hash === testHash; + }).catch(function () { + 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. + // TODO: improve this? + var isDirectory = function isDirectory(swarmUrl) { + return function (hash) { + return downloadData(swarmUrl)(hash).then(function (data) { + try { + return !!JSON.parse(toString(data)).entries; + } catch (e) { + return false; + } + }); + }; + }; + + // 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) { + var p; + // Hardcoded because efficiency (`arguments` is very slow). + if (typeof a !== "undefined") p = f(a); + if (typeof b !== "undefined") p = f(b); + if (typeof c !== "undefined") p = f(c); + if (typeof d !== "undefined") p = f(d); + if (typeof e !== "undefined") p = f(e); + 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) { + return { + download: function download(hash, path) { + return _download(swarmUrl)(hash)(path); + }, + downloadData: uncurry(downloadData(swarmUrl)), + downloadDataToDisk: uncurry(downloadDataToDisk(swarmUrl)), + downloadDirectory: uncurry(downloadDirectory(swarmUrl)), + downloadDirectoryToDisk: uncurry(downloadDirectoryToDisk(swarmUrl)), + downloadEntries: uncurry(downloadEntries(swarmUrl)), + downloadRoutes: uncurry(downloadRoutes(swarmUrl)), + isAvailable: function isAvailable() { + return _isAvailable(swarmUrl); + }, + upload: function upload(arg) { + return _upload(swarmUrl)(arg); + }, + uploadData: uncurry(uploadData(swarmUrl)), + uploadFile: uncurry(uploadFile(swarmUrl)), + uploadFileFromDisk: uncurry(uploadFile(swarmUrl)), + uploadDataFromDisk: uncurry(uploadDataFromDisk(swarmUrl)), + uploadDirectory: uncurry(uploadDirectory(swarmUrl)), + uploadDirectoryFromDisk: uncurry(uploadDirectoryFromDisk(swarmUrl)), + uploadToManifest: uncurry(uploadToManifest(swarmUrl)), + pick: pick, + hash: hash, + fromString: fromString, + toString: toString + }; + }; + + return { + at: at, + local: local, + download: _download, + downloadBinary: downloadBinary, + downloadData: downloadData, + downloadDataToDisk: downloadDataToDisk, + downloadDirectory: downloadDirectory, + downloadDirectoryToDisk: downloadDirectoryToDisk, + downloadEntries: downloadEntries, + downloadRoutes: downloadRoutes, + isAvailable: _isAvailable, + startProcess: startProcess, + stopProcess: stopProcess, + upload: _upload, + uploadData: uploadData, + uploadDataFromDisk: uploadDataFromDisk, + uploadFile: uploadFile, + uploadFileFromDisk: uploadFileFromDisk, + uploadDirectory: uploadDirectory, + uploadDirectoryFromDisk: uploadDirectoryFromDisk, + uploadToManifest: uploadToManifest, + pick: pick, + hash: hash, + fromString: fromString, + 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) { + // If the buffer isn't a subarray, return the underlying ArrayBuffer + if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) { + return buf.buffer + } else if (typeof buf.buffer.slice === 'function') { + // Otherwise we need to get a proper copy + 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) + var arrayCopy = new Uint8Array(buf.length) + var len = buf.length + for (var i = 0; i < len; i++) { + arrayCopy[i] = buf[i] + } + return arrayCopy.buffer + } else { + 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 + nativeIsArray = Array.isArray, + 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. + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = _; + } + exports._ = _; + } 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. + var optimizeCb = function(func, context, argCount) { + if (context === void 0) return func; + switch (argCount == null ? 3 : argCount) { + case 1: return function(value) { + return func.call(context, value); + }; + case 2: return function(value, other) { + return func.call(context, value, other); + }; + case 3: return function(value, index, collection) { + return func.call(context, value, index, collection); + }; + case 4: return function(accumulator, value, index, collection) { + return func.call(context, accumulator, value, index, collection); + }; + } + return function() { + 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. + var cb = function(value, context, argCount) { + if (value == null) return _.identity; + if (_.isFunction(value)) return optimizeCb(value, context, argCount); + if (_.isObject(value)) return _.matcher(value); + return _.property(value); + }; + _.iteratee = function(value, context) { + return cb(value, context, Infinity); + }; + + // An internal function for creating assigner functions. + var createAssigner = function(keysFunc, undefinedOnly) { + return function(obj) { + var length = arguments.length; + if (length < 2 || obj == null) return obj; + for (var index = 1; index < length; index++) { + var source = arguments[index], + keys = keysFunc(source), + l = keys.length; + for (var i = 0; i < l; i++) { + var key = keys[i]; + if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key]; + } + } + return obj; + }; + }; + + // An internal function for creating a new object that inherits from another. + var baseCreate = function(prototype) { + if (!_.isObject(prototype)) return {}; + if (nativeCreate) return nativeCreate(prototype); + Ctor.prototype = prototype; + var result = new Ctor; + 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 + // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094 + var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; + var getLength = property('length'); + var isArrayLike = function(collection) { + 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. + _.each = _.forEach = function(obj, iteratee, context) { + iteratee = optimizeCb(iteratee, context); + var i, length; + if (isArrayLike(obj)) { + for (i = 0, length = obj.length; i < length; i++) { + iteratee(obj[i], i, obj); + } + } else { + var keys = _.keys(obj); + for (i = 0, length = keys.length; i < length; i++) { + iteratee(obj[keys[i]], keys[i], obj); + } + } + return obj; + }; + + // Return the results of applying the iteratee to each element. + _.map = _.collect = function(obj, iteratee, context) { + iteratee = cb(iteratee, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length, + results = Array(length); + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + results[index] = iteratee(obj[currentKey], currentKey, obj); + } + return results; + }; + + // Create a reducing function iterating left or right. + function createReduce(dir) { + // Optimized iterator function as using arguments.length + // in the main function will deoptimize the, see #1991. + function iterator(obj, iteratee, memo, keys, index, length) { + for (; index >= 0 && index < length; index += dir) { + var currentKey = keys ? keys[index] : index; + memo = iteratee(memo, obj[currentKey], currentKey, obj); + } + return memo; + } + + return function(obj, iteratee, memo, context) { + iteratee = optimizeCb(iteratee, context, 4); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length, + index = dir > 0 ? 0 : length - 1; + // Determine the initial value if none is provided. + if (arguments.length < 3) { + memo = obj[keys ? keys[index] : index]; + index += dir; + } + 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; + if (isArrayLike(obj)) { + key = _.findIndex(obj, predicate, context); + } else { + key = _.findKey(obj, predicate, context); + } + 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) { + var results = []; + predicate = cb(predicate, context); + _.each(obj, function(value, index, list) { + if (predicate(value, index, list)) results.push(value); + }); + 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) { + predicate = cb(predicate, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length; + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + if (!predicate(obj[currentKey], currentKey, obj)) return false; + } + return true; + }; + + // Determine if at least one element in the object matches a truth test. + // Aliased as `any`. + _.some = _.any = function(obj, predicate, context) { + predicate = cb(predicate, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length; + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + if (predicate(obj[currentKey], currentKey, obj)) return true; + } + 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) { + if (!isArrayLike(obj)) obj = _.values(obj); + 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); + var isFunc = _.isFunction(method); + return _.map(obj, function(value) { + var func = isFunc ? method : value[method]; + 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, + value, computed; + if (iteratee == null && obj != null) { + obj = isArrayLike(obj) ? obj : _.values(obj); + for (var i = 0, length = obj.length; i < length; i++) { + value = obj[i]; + if (value > result) { + result = value; + } + } + } else { + iteratee = cb(iteratee, context); + _.each(obj, function(value, index, list) { + computed = iteratee(value, index, list); + if (computed > lastComputed || computed === -Infinity && result === -Infinity) { + result = value; + lastComputed = computed; + } + }); + } + return result; + }; + + // Return the minimum element (or element-based computation). + _.min = function(obj, iteratee, context) { + var result = Infinity, lastComputed = Infinity, + value, computed; + if (iteratee == null && obj != null) { + obj = isArrayLike(obj) ? obj : _.values(obj); + for (var i = 0, length = obj.length; i < length; i++) { + value = obj[i]; + if (value < result) { + result = value; + } + } + } else { + iteratee = cb(iteratee, context); + _.each(obj, function(value, index, list) { + computed = iteratee(value, index, list); + if (computed < lastComputed || computed === Infinity && result === Infinity) { + result = value; + lastComputed = computed; + } + }); + } + 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) { + var set = isArrayLike(obj) ? obj : _.values(obj); + var length = set.length; + var shuffled = Array(length); + for (var index = 0, rand; index < length; index++) { + rand = _.random(0, index); + if (rand !== index) shuffled[index] = shuffled[rand]; + shuffled[rand] = set[index]; + } + 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`. + _.sample = function(obj, n, guard) { + if (n == null || guard) { + if (!isArrayLike(obj)) obj = _.values(obj); + return obj[_.random(obj.length - 1)]; + } + 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); + return _.pluck(_.map(obj, function(value, index, list) { + return { + value: value, + index: index, + criteria: iteratee(value, index, list) + }; + }).sort(function(left, right) { + var a = left.criteria; + var b = right.criteria; + if (a !== b) { + if (a > b || a === void 0) return 1; + if (a < b || b === void 0) return -1; + } + return left.index - right.index; + }), 'value'); + }; + + // An internal function used for aggregate "group by" operations. + var group = function(behavior) { + return function(obj, iteratee, context) { + var result = {}; + iteratee = cb(iteratee, context); + _.each(obj, function(value, index) { + var key = iteratee(value, index, obj); + behavior(result, value, key); + }); + 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 []; + if (_.isArray(obj)) return slice.call(obj); + 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) { + predicate = cb(predicate, context); + var pass = [], fail = []; + _.each(obj, function(value, key, obj) { + (predicate(value, key, obj) ? pass : fail).push(value); + }); + 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`. + _.first = _.head = _.take = function(array, n, guard) { + if (array == null) return void 0; + 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) { + if (array == null) return void 0; + 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; + for (var i = startIndex || 0, length = getLength(input); i < length; i++) { + var value = input[i]; + if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) { + //flatten current level of array or arguments object + if (!shallow) value = flatten(value, shallow, strict); + var j = 0, len = value.length; + output.length += len; + while (j < len) { + output[idx++] = value[j++]; + } + } else if (!strict) { + output[idx++] = value; + } + } + 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`. + _.uniq = _.unique = function(array, isSorted, iteratee, context) { + if (!_.isBoolean(isSorted)) { + context = iteratee; + iteratee = isSorted; + isSorted = false; + } + if (iteratee != null) iteratee = cb(iteratee, context); + var result = []; + var seen = []; + for (var i = 0, length = getLength(array); i < length; i++) { + var value = array[i], + computed = iteratee ? iteratee(value, i, array) : value; + if (isSorted) { + if (!i || seen !== computed) result.push(value); + seen = computed; + } else if (iteratee) { + if (!_.contains(seen, computed)) { + seen.push(computed); + result.push(value); + } + } else if (!_.contains(result, value)) { + result.push(value); + } + } + 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) { + var result = []; + var argsLength = arguments.length; + for (var i = 0, length = getLength(array); i < length; i++) { + var item = array[i]; + if (_.contains(result, item)) continue; + for (var j = 1; j < argsLength; j++) { + if (!_.contains(arguments[j], item)) break; + } + if (j === argsLength) result.push(item); + } + 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) { + var rest = flatten(arguments, true, true, 1); + return _.filter(array, function(value){ + 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. + _.object = function(list, values) { + var result = {}; + for (var i = 0, length = getLength(list); i < length; i++) { + if (values) { + result[list[i]] = values[i]; + } else { + result[list[i][0]] = list[i][1]; + } + } + return result; + }; + + // Generator function to create the findIndex and findLastIndex functions + function createPredicateIndexFinder(dir) { + return function(array, predicate, context) { + predicate = cb(predicate, context); + var length = getLength(array); + var index = dir > 0 ? 0 : length - 1; + for (; index >= 0 && index < length; index += dir) { + if (predicate(array[index], index, array)) return index; + } + 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) { + iteratee = cb(iteratee, context, 1); + var value = iteratee(obj); + var low = 0, high = getLength(array); + while (low < high) { + var mid = Math.floor((low + high) / 2); + if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; + } + return low; + }; + + // Generator function to create the indexOf and lastIndexOf functions + function createIndexFinder(dir, predicateFind, sortedIndex) { + return function(array, item, idx) { + var i = 0, length = getLength(array); + if (typeof idx == 'number') { + if (dir > 0) { + i = idx >= 0 ? idx : Math.max(idx + length, i); + } else { + length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; + } + } else if (sortedIndex && idx && length) { + idx = sortedIndex(array, item); + return array[idx] === item ? idx : -1; + } + if (item !== item) { + idx = predicateFind(slice.call(array, i, length), _.isNaN); + return idx >= 0 ? idx + i : -1; + } + for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) { + if (array[idx] === item) return idx; + } + 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). + _.range = function(start, stop, step) { + if (stop == null) { + stop = start || 0; + 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) { + if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args); + var self = baseCreate(sourceFunc.prototype); + var result = sourceFunc.apply(self, args); + 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. + _.bind = function(func, context) { + if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); + if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); + var args = slice.call(arguments, 2); + var bound = function() { + return executeBound(func, bound, context, this, args.concat(slice.call(arguments))); + }; + 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. + _.partial = function(func) { + var boundArgs = slice.call(arguments, 1); + var bound = function() { + var position = 0, length = boundArgs.length; + var args = Array(length); + for (var i = 0; i < length; i++) { + args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i]; + } + while (position < arguments.length) args.push(arguments[position++]); + return executeBound(func, bound, this, this, args); + }; + 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. + _.bindAll = function(obj) { + var i, length = arguments.length, key; + if (length <= 1) throw new Error('bindAll must be passed function names'); + for (i = 1; i < length; i++) { + key = arguments[i]; + obj[key] = _.bind(obj[key], obj); + } + return obj; + }; + + // Memoize an expensive function by storing its results. + _.memoize = function(func, hasher) { + var memoize = function(key) { + var cache = memoize.cache; + var address = '' + (hasher ? hasher.apply(this, arguments) : key); + if (!_.has(cache, address)) cache[address] = func.apply(this, arguments); + return cache[address]; + }; + 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) { + var args = slice.call(arguments, 2); + return setTimeout(function(){ + 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; + // but if you'd like to disable the execution on the leading edge, pass + // `{leading: false}`. To disable execution on the trailing edge, ditto. + _.throttle = function(func, wait, options) { + var context, args, result; + var timeout = null; + var previous = 0; + if (!options) options = {}; + var later = function() { + previous = options.leading === false ? 0 : _.now(); + timeout = null; + result = func.apply(context, args); + if (!timeout) context = args = null; + }; + return function() { + var now = _.now(); + if (!previous && options.leading === false) previous = now; + var remaining = wait - (now - previous); + context = this; + args = arguments; + if (remaining <= 0 || remaining > wait) { + if (timeout) { + clearTimeout(timeout); + timeout = null; + } + previous = now; + result = func.apply(context, args); + if (!timeout) context = args = null; + } else if (!timeout && options.trailing !== false) { + timeout = setTimeout(later, remaining); + } + 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 { + timeout = null; + if (!immediate) { + result = func.apply(context, args); + if (!timeout) context = args = null; + } + } + }; + + return function() { + context = this; + args = arguments; + timestamp = _.now(); + var callNow = immediate && !timeout; + if (!timeout) timeout = setTimeout(later, wait); + if (callNow) { + 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() { + var args = arguments; + var start = args.length - 1; + return function() { + var i = start; + var result = args[start].apply(this, arguments); + while (i--) result = args[i].call(this, result); + return result; + }; + }; + + // Returns a function that will only be executed on and after the Nth call. + _.after = function(times, func) { + return function() { + if (--times < 1) { + return func.apply(this, arguments); + } + }; + }; + + // Returns a function that will only be executed up to (but not including) the Nth call. + _.before = function(times, func) { + var memo; + return function() { + if (--times > 0) { + memo = func.apply(this, arguments); + } + if (times <= 1) func = null; + 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)) { + keys.push(prop); + } + } + } + + // Retrieve the names of an object's own properties. + // Delegates to **ECMAScript 5**'s native `Object.keys` + _.keys = function(obj) { + if (!_.isObject(obj)) return []; + if (nativeKeys) return nativeKeys(obj); + var keys = []; + for (var key in obj) if (_.has(obj, key)) keys.push(key); + // Ahem, IE < 9. + if (hasEnumBug) collectNonEnumProps(obj, keys); + return keys; + }; + + // Retrieve all the property names of an object. + _.allKeys = function(obj) { + if (!_.isObject(obj)) return []; + var keys = []; + for (var key in obj) keys.push(key); + // Ahem, IE < 9. + if (hasEnumBug) collectNonEnumProps(obj, keys); + return keys; + }; + + // Retrieve the values of an object's properties. + _.values = function(obj) { + var keys = _.keys(obj); + var length = keys.length; + var values = Array(length); + for (var i = 0; i < length; i++) { + values[i] = obj[keys[i]]; + } + 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) { + iteratee = cb(iteratee, context); + var keys = _.keys(obj), + length = keys.length, + results = {}, + currentKey; + for (var index = 0; index < length; index++) { + currentKey = keys[index]; + results[currentKey] = iteratee(obj[currentKey], currentKey, obj); + } + return results; + }; + + // Convert an object into a list of `[key, value]` pairs. + _.pairs = function(obj) { + var keys = _.keys(obj); + var length = keys.length; + var pairs = Array(length); + for (var i = 0; i < length; i++) { + pairs[i] = [keys[i], obj[keys[i]]]; + } + return pairs; + }; + + // Invert the keys and values of an object. The values must be serializable. + _.invert = function(obj) { + var result = {}; + var keys = _.keys(obj); + for (var i = 0, length = keys.length; i < length; i++) { + result[obj[keys[i]]] = keys[i]; + } + return result; + }; + + // Return a sorted list of the function names available on the object. + // Aliased as `methods` + _.functions = _.methods = function(obj) { + var names = []; + for (var key in obj) { + if (_.isFunction(obj[key])) names.push(key); + } + 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); + var keys = _.keys(obj), key; + for (var i = 0, length = keys.length; i < length; i++) { + key = keys[i]; + 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; + if (obj == null) return result; + if (_.isFunction(oiteratee)) { + keys = _.allKeys(obj); + iteratee = optimizeCb(oiteratee, context); + } else { + keys = flatten(arguments, false, false, 1); + iteratee = function(value, key, obj) { return key in obj; }; + obj = Object(obj); + } + for (var i = 0, length = keys.length; i < length; i++) { + var key = keys[i]; + var value = obj[key]; + if (iteratee(value, key, obj)) result[key] = value; + } + return result; + }; + + // Return a copy of the object without the blacklisted properties. + _.omit = function(obj, iteratee, context) { + if (_.isFunction(iteratee)) { + iteratee = _.negate(iteratee); + } else { + var keys = _.map(flatten(arguments, false, false, 1), String); + iteratee = function(value, key) { + return !_.contains(keys, key); + }; + } + 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. + _.create = function(prototype, props) { + var result = baseCreate(prototype); + 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. + _.tap = function(obj, interceptor) { + 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; + if (object == null) return !length; + var obj = Object(object); + for (var i = 0; i < length; i++) { + var key = keys[i]; + if (attrs[key] !== obj[key] || !(key in obj)) return false; + } + 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. + // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). + if (a === b) return a !== 0 || 1 / a === 1 / b; + // A strict comparison is necessary because `null == undefined`. + if (a == null || b == null) return a === b; + // Unwrap any wrapped objects. + if (a instanceof _) a = a._wrapped; + if (b instanceof _) b = b._wrapped; + // Compare `[[Class]]` names. + var className = toString.call(a); + if (className !== toString.call(b)) return false; + switch (className) { + // Strings, numbers, regular expressions, dates, and booleans are compared by value. + case '[object RegExp]': + // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') + case '[object String]': + // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is + // equivalent to `new String("5")`. + return '' + a === '' + b; + case '[object Number]': + // `NaN`s are equivalent, but non-reflexive. + // Object(NaN) is equivalent to NaN + if (+a !== +a) return +b !== +b; + // An `egal` comparison is performed for other numeric values. + return +a === 0 ? 1 / +a === 1 / b : +a === +b; + case '[object Date]': + case '[object Boolean]': + // Coerce dates and booleans to numeric primitive values. Dates are compared by their + // millisecond representations. Note that invalid dates with millisecond representations + // 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; + if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor && + _.isFunction(bCtor) && bCtor instanceof bCtor) + && ('constructor' in a && 'constructor' in b)) { + return false; + } + } + // 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 || []; + bStack = bStack || []; + var length = aStack.length; + while (length--) { + // Linear search. Performance is inversely proportional to the number of + // 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. + length = a.length; + if (length !== b.length) return false; + // Deep compare the contents, ignoring non-numeric properties. + while (length--) { + if (!eq(a[length], b[length], aStack, bStack)) return false; + } + } else { + // Deep compare objects. + var keys = _.keys(a), key; + length = keys.length; + // Ensure that both objects contain the same number of properties before comparing deep equality. + if (_.keys(b).length !== length) return false; + while (length--) { + // Deep compare each member + key = keys[length]; + if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false; + } + } + // Remove the first object from the stack of traversed objects. + aStack.pop(); + 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) { + if (obj == null) return true; + 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)) { + _.isArguments = function(obj) { + 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') { + _.isFunction = function(obj) { + 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) { + attrs = _.extendOwn({}, attrs); + return function(obj) { + return _.isMatch(obj, attrs); + }; + }; + + // Run a function **n** times. + _.times = function(n, iteratee, context) { + var accum = Array(Math.max(0, n)); + iteratee = optimizeCb(iteratee, context, 1); + 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) { + max = min; + min = 0; + } + 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 = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', + '`': '`' + }; + var unescapeMap = _.invert(escapeMap); + + // Functions for escaping and unescaping strings to/from HTML interpolation. + var createEscaper = function(map) { + var escaper = function(match) { + return map[match]; + }; + // Regexes for identifying a key that needs to be escaped + var source = '(?:' + _.keys(map).join('|') + ')'; + var testRegexp = RegExp(source); + var replaceRegexp = RegExp(source, 'g'); + return function(string) { + string = string == null ? '' : '' + string; + return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; + }; + }; + _.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) { + var value = object == null ? void 0 : object[property]; + if (value === void 0) { + value = fallback; + } + 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; + _.uniqueId = function(prefix) { + 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 = { + evaluate : /<%([\s\S]+?)%>/g, + 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 = { + "'": "'", + '\\': '\\', + '\r': 'r', + '\n': 'n', + '\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. + // NB: `oldSettings` only exists for backwards compatibility. + _.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) { + source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; + } 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) { + var func = _[name] = obj[name]; + _.prototype[name] = function() { + var args = [this._wrapped]; + push.apply(args, arguments); + return result(this, func.apply(_, args)); + }; + }); + }; + + // 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]; + _.prototype[name] = function() { + var obj = this._wrapped; + method.apply(obj, arguments); + if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; + return result(this, obj); + }; + }); + + // Add all accessor Array functions to the wrapper. + _.each(['concat', 'join', 'slice'], function(name) { + var method = ArrayProto[name]; + _.prototype[name] = function() { + 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 + // as a named module because, like jQuery, it is a base library that is + // popular enough to be bundled in a third party lib, but not be part of + // an AMD load request. Those cases could generate an error when an + // anonymous define() is called outside of a loader request. + if (typeof define === 'function' && define.amd) { + define('underscore', [], function() { + return _; + }); + } + }.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)) { + // e.g. http://foo.com -> http://foo.com/ + start = start + '/' + } + var match = url.match(/(\#.*)$/) + url = start + query + if (match) { // add hash back in + url = url + match[0] + } + } + return url + } + + },{}],327:[function(require,module,exports){ + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 'use strict'; + + var 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; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + 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. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + '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 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + 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); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + 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 + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // 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++) { + var hec = rest.indexOf(hostEndingChars[i]); + 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; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // 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) { + auth = rest.slice(0, atSign); + 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++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // 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(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + 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 + // have non-ASCII characters, i.e. it doesn't matter if + // 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) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // 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. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + 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. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); + } + + Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + 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) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + 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 || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } 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 + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + 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 + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + 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. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + 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. + var last = srcPath.slice(-1)[0]; + 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; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + 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 ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + 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 : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + }; + + Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + 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'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + 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 = []; + var counter = 0; + var length = string.length; + var value; + var extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + // Taken from https://mths.be/punycode + function ucs2encode(array) { + var length = array.length; + var index = -1; + var value; + var output = ''; + while (++index < length) { + value = array[index]; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + } + return output; + } + + function checkScalarValue(codePoint) { + if (codePoint >= 0xD800 && codePoint <= 0xDFFF) { + throw Error( + 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() + + ' is not a scalar value' + ); + } + } + /*--------------------------------------------------------------------------*/ + + function createByte(codePoint, shift) { + return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80); + } + + function encodeCodePoint(codePoint) { + if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence + return stringFromCharCode(codePoint); + } + var symbol = ''; + if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence + symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0); + } + else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence + checkScalarValue(codePoint); + symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0); + symbol += createByte(codePoint, 6); + } + else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence + symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0); + symbol += createByte(codePoint, 12); + symbol += createByte(codePoint, 6); + } + symbol += stringFromCharCode((codePoint & 0x3F) | 0x80); + return symbol; + } + + function utf8encode(string) { + var codePoints = ucs2decode(string); + var length = codePoints.length; + var index = -1; + var codePoint; + var byteString = ''; + while (++index < length) { + codePoint = codePoints[index]; + byteString += encodeCodePoint(codePoint); + } + 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(); + codePoint = ((byte1 & 0x1F) << 6) | byte2; + if (codePoint >= 0x80) { + return codePoint; + } else { + throw Error('Invalid continuation byte'); + } + } + + // 3-byte sequence (may include unpaired surrogates) + if ((byte1 & 0xF0) == 0xE0) { + byte2 = readContinuationByte(); + byte3 = readContinuationByte(); + codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3; + if (codePoint >= 0x0800) { + checkScalarValue(codePoint); + return codePoint; + } else { + throw Error('Invalid continuation byte'); + } + } + + // 4-byte sequence + if ((byte1 & 0xF8) == 0xF0) { + byte2 = readContinuationByte(); + byte3 = readContinuationByte(); + byte4 = readContinuationByte(); + codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) | + (byte3 << 0x06) | byte4; + if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) { + return codePoint; + } + } + + throw Error('Invalid UTF-8 detected'); + } + + var byteArray; + var byteCount; + var byteIndex; + function utf8decode(byteString) { + byteArray = ucs2decode(byteString); + byteCount = byteArray.length; + byteIndex = 0; + var codePoints = []; + var tmp; + while ((tmp = decodeSymbol()) !== false) { + codePoints.push(tmp); + } + 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 ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define(function() { + return utf8; + }); + } else if (freeExports && !freeExports.nodeType) { + if (freeModule) { // in Node.js or RingoJS v0.8.0+ + freeModule.exports = utf8; + } else { // in Narwhal or RingoJS v0.7.0- + var object = {}; + var hasOwnProperty = object.hasOwnProperty; + for (var key in utf8) { + hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]); + } + } + } 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. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + + function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + } + + /** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + + function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; + } + + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + },{}],331:[function(require,module,exports){ + arguments[4][180][0].apply(exports,arguments) + },{"dup":180}],332:[function(require,module,exports){ + module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; + } + },{}],333:[function(require,module,exports){ + (function (process,global){ + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var formatRegExp = /%[sdj%]/g; + exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + }; + + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + }; + + + var debugs = {}; + var debugEnviron; + exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + }; + + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + exports.inspect = inspect; + + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + exports.isArray = isArray; + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + exports.isBoolean = isBoolean; + + function isNull(arg) { + return arg === null; + } + exports.isNull = isNull; + + function isNullOrUndefined(arg) { + return arg == null; + } + exports.isNullOrUndefined = isNullOrUndefined; + + function isNumber(arg) { + return typeof arg === 'number'; + } + exports.isNumber = isNumber; + + function isString(arg) { + return typeof arg === 'string'; + } + exports.isString = isString; + + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + exports.isSymbol = isSymbol; + + function isUndefined(arg) { + return arg === void 0; + } + exports.isUndefined = isUndefined; + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + exports.isRegExp = isRegExp; + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + exports.isObject = isObject; + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + exports.isDate = isDate; + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + exports.isError = isError; + + function isFunction(arg) { + return typeof arg === 'function'; + } + exports.isFunction = isFunction; + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + exports.isPrimitive = isPrimitive; + + exports.isBuffer = require('./support/isBuffer'); + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); + }; + + + /** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ + exports.inherits = require('inherits'); + + exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + }; + + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + },{"./support/isBuffer":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 { + var res = []; + for (var key in obj) res.push(key) + 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({}, '_', {}); + return function(obj, name, value) { + Object.defineProperty(obj, name, { + writable: true, + enumerable: false, + configurable: true, + value: value + }) + }; + } catch(e) { + return function(obj, name, value) { + obj[name] = value; + }; + } + }()); + + 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]; + }); + forEach(globals, function (key) { + if (context[key]) { + 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` + // that was only introduced after the eval. + if (key in context || indexOf(winKeys, key) === -1) { + 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') { + forEach(Object_keys(context), function (key) { + copy[key] = context[key]; + }); + } + 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 . + */ + /** + * @file index.js + * @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; + if(typeof ethereumProvider !== 'undefined' && ethereumProvider.bzz) { + Bzz.givenProvider = ethereumProvider.bzz; + } + /* jshint ignore:end */ + + Bzz.prototype.setProvider = function(provider) { + // is ethereum provider + if(_.isObject(provider) && _.isString(provider.bzz)) { + provider = provider.bzz; + // is no string, set default + } + // 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 . + */ + /** + * @file errors.js + * @author Fabian Vogelsteller + * @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); + return new Error('Returned error: ' + message); + }, + InvalidNumberOfParams: function (got, expected, method) { + return new Error('Invalid number of parameters for "'+ method +'". Got '+ got +' expected '+ expected +'!'); + }, + InvalidConnection: function (host){ + return new Error('CONNECTION ERROR: Couldn\'t connect to node '+ host +'.'); + }, + InvalidProvider: function () { + return new Error('Provider not set or invalid'); + }, + InvalidResponse: function (result){ + var message = !!result && !!result.error && !!result.error.message ? result.error.message : 'Invalid JSON RPC response: ' + JSON.stringify(result); + return new Error(message); + }, + ConnectionTimeout: function (ms){ + 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 . + */ + /** + * @file formatters.js + * @author Fabian Vogelsteller + * @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 + * + * @method outputBigNumberFormatter + * @param {String|Number|BigNumber} number + * @returns {BigNumber} object + */ + 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; + } + if (blockNumber === 'genesis' || blockNumber === 'earliest') { + return '0x0'; + } + return inputBlockNumberFormatter(blockNumber); + }; + + var inputBlockNumberFormatter = function (blockNumber) { + if (blockNumber === undefined) { + return undefined; + } else if (isPredefinedBlockNumber(blockNumber)) { + return blockNumber; + } + return (utils.isHexStrict(blockNumber)) ? ((_.isString(blockNumber)) ? blockNumber.toLowerCase() : blockNumber) : utils.numberToHex(blockNumber); + }; + + /** + * Formats the input of a transaction and converts all values to HEX + * + * @method _txInputFormatter + * @param {Object} transaction options + * @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 + * + * @method inputCallFormatter + * @param {Object} transaction options + * @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 + * + * @method inputTransactionFormatter + * @param {Object} options + * @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 + * + * @method inputSignFormatter + * @param {String} data + * @returns {String} + */ + var inputSignFormatter = function (data) { + return (utils.isHexStrict(data)) ? data : utils.utf8ToHex(data); + }; + + /** + * Formats the output of a transaction to its proper values + * + * @method outputTransactionFormatter + * @param {Object} tx + * @returns {Object} + */ + var outputTransactionFormatter = function (tx){ + if(tx.blockNumber !== null) + tx.blockNumber = utils.hexToNumber(tx.blockNumber); + if(tx.transactionIndex !== null) + tx.transactionIndex = utils.hexToNumber(tx.transactionIndex); + tx.nonce = utils.hexToNumber(tx.nonce); + 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 + * + * @method outputTransactionReceiptFormatter + * @param {Object} receipt + * @returns {Object} + */ + var outputTransactionReceiptFormatter = function (receipt){ + 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 + * + * @method outputBlockFormatter + * @param {Object} block + * @returns {Object} + */ + var outputBlockFormatter = function(block) { + + // transform to number + block.gasLimit = utils.hexToNumber(block.gasLimit); + block.gasUsed = utils.hexToNumber(block.gasUsed); + block.size = utils.hexToNumber(block.size); + 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 + * + * @method inputLogFormatter + * @param {Object} log object + * @returns {Object} log + */ + 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 + * + * @method outputLogFormatter + * @param {Object} log object + * @returns {Object} log + */ + var outputLogFormatter = function(log) { + + // generate a custom log id + if(typeof log.blockHash === 'string' && + typeof log.transactionHash === 'string' && + typeof log.logIndex === 'string') { + var shaId = utils.sha3(log.blockHash.replace('0x','') + log.transactionHash.replace('0x','') + log.logIndex.replace('0x','')); + log.id = 'log_'+ shaId.replace('0x','').substr(0,8); + } 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 + * + * @method inputPostFormatter + * @param {Object} transaction object + * @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 + * + * @method outputPostFormatter + * @param {Object} + * @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 = []; + } + 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()) { + return iban.toAddress().toLowerCase(); + } else if (utils.isAddress(address)) { + return '0x' + address.toLowerCase().replace('0x',''); + } + 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); + if (result.knownStates) { + result.knownStates = utils.hexToNumber(result.knownStates); + result.pulledStates = utils.hexToNumber(result.pulledStates); + } + + return result; + }; + + module.exports = { + inputDefaultBlockNumberFormatter: inputDefaultBlockNumberFormatter, + inputBlockNumberFormatter: inputBlockNumberFormatter, + inputCallFormatter: inputCallFormatter, + inputTransactionFormatter: inputTransactionFormatter, + inputAddressFormatter: inputAddressFormatter, + inputPostFormatter: inputPostFormatter, + inputLogFormatter: inputLogFormatter, + inputSignFormatter: inputSignFormatter, + outputBigNumberFormatter: outputBigNumberFormatter, + outputTransactionFormatter: outputTransactionFormatter, + outputTransactionReceiptFormatter: outputTransactionReceiptFormatter, + outputBlockFormatter: outputBlockFormatter, + outputLogFormatter: outputLogFormatter, + 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 . + */ + /** + * @file index.js + * @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 . + */ + /** + * @file index.js + * @author Fabian Vogelsteller + * @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; + this.inputFormatter = options.inputFormatter; + 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; + var name = this.name.split('.'); + if (name.length > 1) { + obj[name[0]] = obj[name[0]] || {}; + obj[name[0]][name[1]] = func; + } else { + obj[name[0]] = func; + } + }; + + /** + * Should be used to determine name of the jsonrpc method based on arguments + * + * @method getCall + * @param {Array} arguments + * @return {String} name of jsonrpc method + */ + 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 + * + * @method extractCallback + * @param {Array} arguments + * @return {Function|Null} callback, if exists + */ + Method.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 + * + * @method validateArgs + * @param {Array} arguments + * @throws {Error} if it is not + */ + Method.prototype.validateArgs = function (args) { + if (args.length !== this.params) { + throw errors.InvalidNumberOfParams(args.length, this.params, this.name); + } + }; + + /** + * Should be called to format input args of method + * + * @method formatInput + * @param {Array} + * @return {Array} + */ + 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 + * + * @method formatOutput + * @param {Object} + * @return {Object} + */ + Method.prototype.formatOutput = function (result) { + var _this = this; + + if(_.isArray(result)) { + return result.map(function(res){ + return _this.outputFormatter && res ? _this.outputFormatter(res) : res; + }); + } else { + return this.outputFormatter && result ? this.outputFormatter(result) : result; + } + }; + + /** + * Should create payload from given input args + * + * @method toPayload + * @param {Array} args + * @return {Object} + */ + Method.prototype.toPayload = function (args) { + var call = this.getCall(args); + 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, + canUnsubscribe = true, + timeoutCount = 0, + confirmationCount = 0, + intervalId = null, + receiptJSON = '', + gasProvided = (_.isObject(payload.params[0]) && payload.params[0].gas) ? payload.params[0].gas : null, + isContractDeployment = _.isObject(payload.params[0]) && + payload.params[0].data && + payload.params[0].from && + !payload.params[0].to; + + // add custom send Methods + var _ethereumCalls = [ + new Method({ + name: 'getTransactionReceipt', + call: 'eth_getTransactionReceipt', + params: 1, + inputFormatter: [null], + outputFormatter: formatters.outputTransactionReceiptFormatter + }), + new Method({ + name: 'getCode', + call: 'eth_getCode', + params: 2, + inputFormatter: [formatters.inputAddressFormatter, formatters.inputDefaultBlockNumberFormatter] + }), + new Subscriptions({ + name: 'subscribe', + type: 'eth', + subscriptions: { + 'newBlockHeaders': { + subscriptionName: 'newHeads', // replace subscription with this name + params: 0, + outputFormatter: formatters.outputBlockFormatter + } + } + }) + ]; + // attach methods to this._ethereumCall + var _ethereumCall = {}; + _.each(_ethereumCalls, function (mthd) { + 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) { + // create fake unsubscribe + if (!sub) { + sub = { + unsubscribe: function () { + clearInterval(intervalId); + } + }; + } + // if we have a valid receipt we don't need to send a request + return (existingReceipt ? promiEvent.resolve(existingReceipt) : _ethereumCall.getTransactionReceipt(result)) + // catch error from requesting receipt + .catch(function (err) { + sub.unsubscribe(); + promiseResolved = true; + utils._fireError({message: 'Failed to check for transaction receipt:', data: err}, defer.eventEmitter, defer.reject); + }) + // if CONFIRMATION listener exists check for confirmations, by setting canUnsubscribe = false + .then(function(receipt) { + 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') { + utils._fireError(new Error("Transaction has been reverted by the EVM:\n" + receiptJSON), + defer.eventEmitter, defer.reject); + } else { + utils._fireError( + new Error("Transaction ran out of gas. Please provide more gas:\n" + receiptJSON), + 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 + if (timeoutCount - 1 >= POLLINGTIMEOUT) { + sub.unsubscribe(); + promiseResolved = true; + utils._fireError(new Error('Transaction was not mined within' + POLLINGTIMEOUT + ' seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!'), defer.eventEmitter, defer.reject); + } + } else { + if (timeoutCount - 1 >= TIMEOUTBLOCK) { + sub.unsubscribe(); + promiseResolved = true; + utils._fireError(new Error('Transaction was not mined within 50 blocks, please make sure your transaction was properly sent. Be aware that it might still be mined!'), defer.eventEmitter, defer.reject); + } + } + }); + + + } 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 + if (_.isFunction(this.requestManager.provider.on)) { + _ethereumCall.subscribe('newBlockHeaders', checkConfirmation.bind(null, existingReceipt, false)); + } else { + 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) { + if (receipt && receipt.blockHash) { + if (defer.eventEmitter.listeners('confirmation').length > 0) { + // We must keep on watching for new Blocks, if a confirmation listener is present + startWatching(receipt); + } + checkConfirmation(receipt, false); + + } else if (!promiseResolved) { + startWatching(); + } + }) + .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 { + result = method.formatOutput(result); + } catch(e) { + err = e; + } + + if (result instanceof Error) { + err = result; + } + + if (!err) { + if (payload.callback) { + payload.callback(null, result); + } + } else { + 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 + * + * @method request + * @return {Object} jsonrpc request + */ + Method.prototype.request = function () { + var payload = this.toPayload(Array.prototype.slice.call(arguments)); + 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 . + */ + /** + * @file index.js + * @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 + * + * @method eventifiedPromise + */ + var PromiEvent = function PromiEvent(justPromise) { + var resolve, reject, + eventEmitter = new Promise(function() { + resolve = arguments[0]; + reject = arguments[1]; + }); + + if(justPromise) { + return { + resolve: resolve, + reject: reject, + eventEmitter: eventEmitter + }; + } + + // get eventEmitter + var emitter = new EventEmitter(); + + // add eventEmitter to the promise + eventEmitter._events = emitter._events; + eventEmitter.emit = emitter.emit; + eventEmitter.on = emitter.on; + eventEmitter.once = emitter.once; + eventEmitter.off = emitter.off; + eventEmitter.listeners = emitter.listeners; + 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 . + */ + /** + * @file batch.js + * @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 + * + * @method add + * @param {Object} jsonrpc requet object + */ + Batch.prototype.add = function (request) { + this.requests.push(request); + }; + + /** + * Should be called to execute batch request + * + * @method execute + */ + Batch.prototype.execute = function () { + var requests = this.requests; + this.requestManager.sendBatch(requests, function (err, results) { + results = results || []; + requests.map(function (request, index) { + return results[index] || {}; + }).forEach(function (result, index) { + if (requests[index].callback) { + 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) { + requests[index].callback(err); + } + } + }); + }); + }; + + 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 . + */ + /** + * @file givenProvider.js + * @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 . + */ + /** + * @file index.js + * @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 + * Default poll timeout is 1 second + * Singleton + */ + 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 + * + * @method setProvider + * @param {Object} p + */ + 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); + } + }); + // TODO add error, end, timeout, connect?? + // this.provider.on('error', function requestManagerNotification(result){ + // Object.keys(_this.subscriptions).forEach(function(id){ + // if(_this.subscriptions[id].callback) + // _this.subscriptions[id].callback(err); + // }); + // } + } + }; + + + /** + * Should be used to asynchronously send request + * + * @method sendAsync + * @param {Object} data + * @param {Function} callback + */ + 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 + * + * @method sendBatch + * @param {Array} batch data + * @param {Function} callback + */ + RequestManager.prototype.sendBatch = function (data, callback) { + 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 + * + * @method addSubscription + * @param {String} id the subscription id + * @param {String} name the subscription name + * @param {String} type the subscription namespace (eth, personal, etc) + * @param {Function} callback the callback to call for incoming notifications + */ + RequestManager.prototype.addSubscription = function (id, name, type, callback) { + if(this.provider.on) { + this.subscriptions[id] = { + callback: callback, + type: type, + name: name + }; + + } else { + throw new Error('The provider doesn\'t support subscriptions: '+ this.provider.constructor.name); + } + }; + + /** + * Waits for notifications + * + * @method removeSubscription + * @param {String} id the subscription id + * @param {Function} callback fired once the subscription is removed + */ + 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 + * + * @method reset + */ + 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 . + */ + /** @file jsonrpc.js + * @authors: + * Fabian Vogelsteller + * Marek Kotewicz + * 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 + * + * @method toPayload + * @param {Function} method of jsonrpc call, required + * @param {Array} params, an array of method params, optional + * @returns {Object} valid jsonrpc payload object + */ + Jsonrpc.toPayload = function (method, params) { + 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, + method: method, + params: params || [] + }; + }; + + /** + * Should be called to check if jsonrpc response is valid + * + * @method isValidResponse + * @param {Object} + * @returns {Boolean} true if response is valid, otherwise false + */ + Jsonrpc.isValidResponse = function (response) { + return Array.isArray(response) ? response.every(validateSingleMessage) : validateSingleMessage(response); + + function validateSingleMessage(message){ + return !!message && + !message.error && + message.jsonrpc === '2.0' && + (typeof message.id === 'number' || typeof message.id === 'string') && + message.result !== undefined; // only undefined is not valid json object + } + }; + + /** + * Should be called to create batch payload object + * + * @method toBatchPayload + * @param {Array} messages, an array of objects with method (required) and params (optional) fields + * @returns {Array} batch payload + */ + Jsonrpc.toBatchPayload = function (messages) { + return messages.map(function (message) { + 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 . + */ + /** + * @file index.js + * @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('.'); + if (name.length > 1) { + obj[name[0]] = obj[name[0]] || {}; + obj[name[0]][name[1]] = func; + } else { + 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 . + */ + /** + * @file subscription.js + * @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 + * + * @method extractCallback + * @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 + * + * @method validateArgs + * @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 + * + * @method formatInput + * @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 + * + * @method formatOutput + * @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 + * + * @method toPayload + * @param {Array} args + * @return {Object} + */ + 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 + * + * @method unsubscribe + * @return {Object} + */ + Subscription.prototype.unsubscribe = function(callback) { + this.options.requestManager.removeSubscription(this.id, callback); + this.id = null; + this.removeAllListeners(); + clearInterval(this._reconnectIntervalId); + }; + + /** + * Subscribes and watches for changes + * + * @method subscribe + * @param {String} subscription the subscription + * @param {Object} options the options object with address topics and fromBlock + * @return {Object} + */ + Subscription.prototype.subscribe = function() { + 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); + this.callback(err2, null, this); + 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 + this.options.requestManager.send({ + method: 'eth_getLogs', + params: [payload.params[1]] + }, function (err, logs) { + if(!err) { + logs.forEach(function(log){ + var output = _this._formatOutput(log); + _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 () { + // TODO check if that makes sense! + if (_this.options.requestManager.provider.reconnect) { + _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); + } + }); + } else { + _this.callback(err, null, _this); + _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 . + */ + /** + * @file extend.js + * @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]) { + pckg[extension.property] = {}; + } + extendedObject = pckg[extension.property]; + } 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 . + */ + /** + * @file index.js + * @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 () { + return pkg._provider; + }, + set: function (value) { + return pkg.setProvider(value); + }, + 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) { + pkg._requestManager.setProvider(provider, net); + pkg._provider = pkg._requestManager.provider; + return true; + }; + } + + // attach batch request creation + pkg.BatchRequest = requestManager.BatchManager.bind(null, pkg._requestManager); + + // attach extend function + pkg.extend = extend(pkg); + }, + addProviders: function (pkg) { + pkg.givenProvider = requestManager.Manager.givenProvider; + 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 . + */ + /** + * @file index.js + * @author Marek Kotewicz + * @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')) { + return value.toString(); + } + 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. + * + * @method encodeFunctionSignature + * @param {String|Object} functionName + * @return {String} encoded function name + */ + ABICoder.prototype.encodeFunctionSignature = function (functionName) { + 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. + * + * @method encodeEventSignature + * @param {String|Object} functionName + * @return {String} encoded function name + */ + ABICoder.prototype.encodeEventSignature = function (functionName) { + if (_.isObject(functionName)) { + functionName = utils._jsonInterfaceMethodToString(functionName); + } + + return utils.sha3(functionName); + }; + + /** + * Should be used to encode plain param + * + * @method encodeParameter + * @param {String} type + * @param {Object} param + * @return {String} encoded plain param + */ + ABICoder.prototype.encodeParameter = function (type, param) { + return this.encodeParameters([type], [param]); + }; + + /** + * Should be used to encode list of params + * + * @method encodeParameters + * @param {Array} types + * @param {Array} params + * @return {String} encoded list of params + */ + ABICoder.prototype.encodeParameters = function (types, params) { + return ethersAbiCoder.encode(this.mapTypes(types), params); + }; + + /** + * Map types if simplified format is used + * + * @method mapTypes + * @param {Array} types + * @return {Array} + */ + ABICoder.prototype.mapTypes = function (types) { + var self = this; + var mappedTypes = []; + types.forEach(function (type) { + if (self.isSimplifiedStructFormat(type)) { + var structName = Object.keys(type)[0]; + mappedTypes.push( + Object.assign( + self.mapStructNameAndType(structName), + { + components: self.mapStructToCoderFormat(type[structName]) + } + ) + ); + + return; + } + + mappedTypes.push(type); + }); + + return mappedTypes; + }; + + /** + * Check if type is simplified struct format + * + * @method isSimplifiedStructFormat + * @param {string | Object} type + * @returns {boolean} + */ + 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 + * + * @method mapStructNameAndType + * @param {string} structName + * @return {{type: string, name: *}} + */ + 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 + * + * @method mapStructToCoderFormat + * @param {Object} struct + * @return {Array} + */ + ABICoder.prototype.mapStructToCoderFormat = function (struct) { + var self = this; + var components = []; + Object.keys(struct).forEach(function (key) { + if (typeof struct[key] === 'object') { + components.push( + Object.assign( + self.mapStructNameAndType(key), + { + components: self.mapStructToCoderFormat(struct[key]) + } + ) + ); + + return; + } + + components.push({ + name: key, + type: struct[key] + }); + }); + + return components; + }; + + /** + * Encodes a function call from its json interface and parameters. + * + * @method encodeFunctionCall + * @param {Array} jsonInterface + * @param {Array} params + * @return {String} The encoded ABI for this function call + */ + 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 + * + * @method decodeParameter + * @param {String} type + * @param {String} bytes + * @return {Object} plain param + */ + ABICoder.prototype.decodeParameter = function (type, bytes) { + return this.decodeParameters([type], bytes)[0]; + }; + + /** + * Should be used to decode list of params + * + * @method decodeParameter + * @param {Array} outputs + * @param {String} bytes + * @return {Array} array of plain params + */ + ABICoder.prototype.decodeParameters = function (outputs, bytes) { + 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. + * + * @method decodeLog + * @param {Object} inputs + * @param {String} data + * @param {Array} topics + * @return {Array} array of plain params + */ + 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) { + return input.type.indexOf(staticType) !== -1; + })) ? _this.decodeParameter(input.type, topics[topicCount]) : topics[topicCount]; + topicCount++; + } else { + 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"; + for (var i = 0; i < 40; i++) { + 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); + var publicKey = "0x" + ecKey.getPublic(false, 'hex').slice(2); + var publicHash = keccak256(publicKey); + var address = toChecksum("0x" + publicHash.slice(-40)); + return { + address: address, + 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) }; + var ecPublicKey = secp256k1.recoverPubKey(new Buffer(hash.slice(2), "hex"), vrs, vrs.v < 2 ? vrs.v : 1 - vrs.v % 2); // because odd vals mean v=0... sadly that means v=0 means v=1... I hate that + var publicKey = "0x" + ecPublicKey.encode("hex", false).slice(2); + var publicHash = keccak256(publicKey); + var address = toChecksum("0x" + publicHash.slice(-40)); + return address; + }; + + module.exports = { + create: create, + toChecksum: toChecksum, + fromPrivate: fromPrivate, + sign: sign, + makeSigner: makeSigner, + recover: recover, + encodeSignature: encodeSignature, + decodeSignature: decodeSignature + }; + }).call(this,require("buffer").Buffer) + },{"./bytes":352,"./hash":353,"./nat":354,"./rlp":355,"buffer":84,"elliptic":109}],351:[function(require,module,exports){ + arguments[4][132][0].apply(exports,arguments) + },{"dup":132}],352:[function(require,module,exports){ + arguments[4][133][0].apply(exports,arguments) + },{"./array.js":351,"dup":133}],353:[function(require,module,exports){ + arguments[4][134][0].apply(exports,arguments) + },{"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, + toNumber: toNumber, + fromNumber: fromNumber, + toEther: toEther, + fromEther: fromEther, + toUint256: toUint256, + add: add, + mul: mul, + div: div, + sub: sub + }; + },{"./bytes":352,"bn.js":53}],355:[function(require,module,exports){ + // The RLP format + // Serialization and deserialization for the BytesTree type, under the following grammar: + // | First byte | Meaning | + // | ---------- | -------------------------------------------------------------------------- | + // | 0 to 127 | HEX(leaf) | + // | 128 to 183 | HEX(length_of_leaf + 128) + HEX(leaf) | + // | 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); + var pre = hex.length != 2 || hex >= "80" ? length(hex.length / 2, 128) : ""; + return pre + hex; + } else { + var _hex = tree.map(dataTree).join(""); + var _pre = length(_hex.length / 2, 192); + 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 = []; + while (i < lim) { + 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 + var _rnds8 = new Uint8Array(16); + rng = function whatwgRNG() { + crypto.getRandomValues(_rnds8); + return _rnds8; + }; + } + + if (!rng) { + // Math.random()-based (RNG) + // + // If all else fails, use Math.random(). It's fast, but is of unspecified + // quality. + var _rnds = new Array(16); + rng = function() { + for (var i = 0, r; i < 16; i++) { + 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 = {}; + for (var i = 0; i < 256; i++) { + _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; + return bth[buf[i++]] + bth[buf[i++]] + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + + 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 . + */ + /** + * @file accounts.js + * @author Fabian Vogelsteller + * @date 2017 + */ + + "use strict"; + + var _ = require("underscore"); + var core = require('web3-core'); + var Method = require('web3-core-method'); + var Promise = require('any-promise'); + var Account = require("eth-lib/lib/account"); + var Hash = require("eth-lib/lib/hash"); + var RLP = require("eth-lib/lib/rlp"); + var Nat = require("eth-lib/lib/nat"); + var Bytes = require("eth-lib/lib/bytes"); + var cryp = (typeof global === 'undefined') ? require('crypto-browserify') : require('crypto'); + var scryptsy = require('scrypt.js'); + 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', + call: 'net_version', + params: 0, + outputFormatter: utils.hexToNumber + }), + new Method({ + name: 'getGasPrice', + call: 'eth_gasPrice', + params: 0 + }), + new Method({ + name: 'getTransactionCount', + call: 'eth_getTransactionCount', + params: 2, + inputFormatter: [function (address) { + if (utils.isAddress(address)) { + return address; + } else { + throw new Error('Address '+ address +' is not a valid address to get the "transactionCount".'); + } + }, function () { return 'latest'; }] + }) + ]; + // attach methods to this._ethereumCall + this._ethereumCall = {}; + _.each(_ethereumCall, function (method) { + 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); + }; + 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), + Bytes.fromNat(transaction.gas), + transaction.to.toLowerCase(), + Bytes.fromNat(transaction.value), + transaction.data, + 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, + v: trimLeadingZero(values[6]), + r: trimLeadingZero(values[7]), + 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, + isNot(tx.gasPrice) ? _this._ethereumCall.getGasPrice() : tx.gasPrice, + isNot(tx.nonce) ? _this._ethereumCall.getTransactionCount(_this.privateKeyToAccount(privateKey).address) : tx.nonce + ]).then(function (args) { + if (isNot(args[0]) || isNot(args[1]) || isNot(args[2])) { + throw new Error('One of the values "chainId", "gasPrice", or "nonce" couldn\'t be fetched: '+ JSON.stringify(args)); + } + 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); + var signature = Account.encodeSignature(values.slice(6,9)); + var recovery = Bytes.toNumber(values[6]); + var extraData = recovery < 35 ? [] : [Bytes.fromNumber((recovery - 35) >> 1), "0x", "0x"]; + var signingData = values.slice(0,6).concat(extraData); + var signingDataHex = RLP.encode(signingData); + 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); + var preamble = "\x19Ethereum Signed Message:\n" + message.length; + var preambleBuffer = Buffer.from(preamble); + 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); + var vrs = Account.decodeSignature(signature); + return { + message: data, + messageHash: hash, + v: vrs[0], + r: vrs[1], + s: vrs[2], + 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'; + derivedKey = cryp.pbkdf2Sync(new Buffer(password), salt, kdfparams.c, kdfparams.dklen, 'sha256'); + } else if (kdf === 'scrypt') { + // FIXME: support progress reporting callback + kdfparams.n = options.n || 8192; // 2048 4096 8192 16384 + kdfparams.r = options.r || 8; + kdfparams.p = options.p || 1; + derivedKey = scryptsy(new Buffer(password), salt, kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen); + } 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) }), + address: account.address.toLowerCase().replace('0x',''), + crypto: { + ciphertext: ciphertext.toString('hex'), + cipherparams: { + iv: iv.toString('hex') + }, + cipher: options.cipher || 'aes-128-ctr', + kdf: kdf, + kdfparams: kdfparams, + mac: mac.toString('hex') + } + }; + }; + + + // 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)) { + return this._findSafeIndex(pointer + 1); + } else { + 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; + delete this[account.address]; + // address lowercase + this[account.address.toLowerCase()].privateKey = null; + delete this[account.address.toLowerCase()]; + // 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 . + */ + /** + * @file contract.js + * + * To initialize a contract use: + * + * var Contract = require('web3-eth-contract'); + * Contract.setProvider('ws://localhost:8546'); + * var contract = new Contract(abi, address, ...); + * + * @author Fabian Vogelsteller + * @date 2017 + */ + + + "use strict"; + + + var _ = require('underscore'); + var core = require('web3-core'); + var Method = require('web3-core-method'); + var utils = require('web3-utils'); + var Subscription = require('web3-core-subscriptions').subscription; + var formatters = require('web3-core-helpers').formatters; + 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 + * + * @method Contract + * @constructor + * @param {Array} jsonInterface + * @param {String} address + * @param {Object} options + */ + 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){ + if(value) { + _this._address = utils.toChecksumAddress(formatters.inputAddressFormatter(value)); + } + }, + get: function(){ + return _this._address; + }, + 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); + func = _this._createTxObject.bind({ + method: method, + parent: _this + }); + + + // add method only if not one already exists + if(!_this.methods[method.name]) { + _this.methods[method.name] = func; + } else { + var cascadeFunc = _this._createTxObject.bind({ + method: method, + parent: _this, + nextMethod: _this.methods[method.name] + }); + _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(){ + return _this._jsonInterface; + }, + 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; + }, + set: function (val) { + if(val) { + defaultAccount = utils.toChecksumAddress(formatters.inputAddressFormatter(val)); + } + + return val; + }, + enumerable: true + }); + Object.defineProperty(this, 'defaultBlock', { + get: function () { + return defaultBlock; + }, + 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 + * + * @method _getCallback + * @param {Array} args + * @return {Function} the callback + */ + Contract.prototype._getCallback = function getCallback(args) { + if (args && _.isFunction(args[args.length - 1])) { + return args.pop(); // modify the args array! + } + }; + + /** + * Checks that no listener with name "newListener" or "removeListener" is added. + * + * @method _checkListener + * @param {String} type + * @param {String} event + * @return {Object} the contract instance + */ + Contract.prototype._checkListener = function(type, event){ + if(event === type) { + throw new Error('The event "'+ type +'" is a reserved event name, you can\'t use it.'); + } + }; + + + /** + * Use default values, if options are not available + * + * @method _getOrSetDefaultOptions + * @param {Object} options the options gived by the user + * @return {Object} the options with gaps filled by defaults + */ + 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 + * + * @method _encodeEventABI + * @param {Object} event + * @param {Object} options + * @return {Object} everything combined together and encoded + */ + Contract.prototype._encodeEventABI = function (event, options) { + 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) { + return i.indexed === true; + }).map(function (i) { + var value = filter[i.name]; + 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); + }); + } + 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 + * + * @method _decodeEventABI + * @param {Object} data + * @return {Object} result object with decoded indexed && not indexed params + */ + 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, + topics: result.topics + }; + 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. + * + * @method _encodeMethodABI + * @param {Mixed} args the arguments to encode + * @param {String} the encoded ABI + */ + 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; + } + return _.isArray(json.inputs) ? json.inputs : []; + }).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 + * + * @method _decodeMethodReturn + * @param {Array} outputs + * @param {String} returnValues + * @return {Object} decoded output return values + */ + Contract.prototype._decodeMethodReturn = function (outputs, returnValues) { + 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 { + delete result.__length__; + return result; + } + }; + + + /** + * Deploys a contract and fire events based on its state: transactionHash, receipt + * + * All event listeners will be removed, once the last possible event is fired ("error", or "receipt") + * + * @method deploy + * @param {Object} options + * @param {Function} callback + * @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 + * + * @method _generateEventOptions + * @param {Object} event + * @param {Object} options + * @param {Function} callback + * @return {Object} the event options object + */ + 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', + jsonInterface: this.options.jsonInterface + } : 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. + * + * @method clone + * @return {Object} the event subscription + */ + 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. + * + * @method once + * @param {String} event + * @param {Object} options + * @param {Function} callback + * @return {Object} the event subscription + */ + 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(); + if(_.isFunction(callback)){ + callback(err, res, sub); + } + }); + + return undefined; + }; + + /** + * Adds event listeners and creates a subscription. + * + * @method _on + * @param {String} event + * @param {Object} options + * @param {Function} callback + * @return {Object} the event subscription + */ + 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: { + params: 1, + inputFormatter: [formatters.inputLogFormatter], + outputFormatter: this._decodeEventABI.bind(subOptions.event), + // DUBLICATE, also in web3-eth + subscriptionHandler: function (output) { + if(output.removed) { + this.emit('changed', output); + } else { + this.emit('data', output); + } + + if (_.isFunction(this.callback)) { + this.callback(null, output, this); + } + } + }, + type: 'eth', + requestManager: this._requestManager + }); + subscription.subscribe('logs', subOptions.params, subOptions.callback || function () {}); + + return subscription; + }; + + /** + * Get past events from contracts + * + * @method getPastEvents + * @param {String} event + * @param {Object} options + * @param {Function} callback + * @return {Object} the promievent + */ + Contract.prototype.getPastEvents = function(){ + var subOptions = this._generateEventOptions.apply(this, arguments); + + var getPastLogs = new Method({ + name: 'getPastLogs', + call: 'eth_getLogs', + params: 1, + inputFormatter: [formatters.inputLogFormatter], + outputFormatter: this._decodeEventABI.bind(subOptions.event) + }); + 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 + * + * @method _createTxObject + * @returns {Object} an object with functions to call the methods + */ + 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 + * + * @method _processExecuteArguments + * @param {Array} args + * @param {Promise} defer + */ + 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 + * + * @method _executeMethod + * @param {String} type the type this execute function should execute + * @param {Boolean} makeRequest if true, it simply returns the request parameters, rather than executing it + */ + Contract.prototype._executeMethod = function _executeMethod(){ + var _this = this, + 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'; + payload.format = this._parent._decodeMethodReturn.bind(null, this._method.outputs); + } else { + payload.method = 'eth_sendTransaction'; + } + + return payload; + + } else { + + switch (args.type) { + case 'estimate': + + var estimateGas = (new Method({ + name: 'estimateGas', + call: 'eth_estimateGas', + params: 1, + inputFormatter: [formatters.inputCallFormatter], + outputFormatter: utils.hexToNumber, + requestManager: _this._parent._requestManager, + accounts: ethAccounts, // is eth.accounts (necessary for wallet signing) + 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', + params: 2, + inputFormatter: [formatters.inputCallFormatter, formatters.inputDefaultBlockNumberFormatter], + // add output formatter for decoding + outputFormatter: function (result) { + return _this._parent._decodeMethodReturn(_this._method.outputs, result); + }, + requestManager: _this._parent._requestManager, + accounts: ethAccounts, // is eth.accounts (necessary for wallet signing) + 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({ + name: 'ALLEVENTS', + jsonInterface: _this._parent.options.jsonInterface + }, log); + }); + + // make log names keys + receipt.events = {}; + var count = 0; + events.forEach(function (ev) { + if (ev.event) { + // if > 1 of the same event, don't overwrite any existing events + if (receipt.events[ev.event]) { + if (Array.isArray(receipt.events[ ev.event ])) { + receipt.events[ ev.event ].push(ev); + } else { + receipt.events[ev.event] = [receipt.events[ev.event], ev]; + } + } else { + receipt.events[ ev.event ] = ev; + } + } else { + receipt.events[count] = ev; + count++; + } + }); + + delete receipt.logs; + } + return receipt; + }, + contractDeployFormatter: function (receipt) { + var newContract = _this._parent.clone(); + newContract.options.address = receipt.contractAddress; + return newContract; + } + }; + + var sendTransaction = (new Method({ + name: 'sendTransaction', + call: 'eth_sendTransaction', + params: 1, + inputFormatter: [formatters.inputTransactionFormatter], + requestManager: _this._parent._requestManager, + accounts: _this.constructor._ethAccounts || _this._ethAccounts, // is eth.accounts (necessary for wallet signing) + defaultAccount: _this._parent.defaultAccount, + 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. + 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 . + */ + /** + * @file ENS.js + * + * @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 + * + * @method ENS + * @param {Object} eth + * @constructor + */ + 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} + */ + ENS.prototype.resolver = function (name) { + return this.registry.resolver(name); + }; + + /** + * Returns the address record associated with a name. + * + * @method getAddress + * @param {string} name + * @param {function} callback + * @return {eventifiedPromise} + */ + ENS.prototype.getAddress = function (name, callback) { + return this.resolverMethodHandler.method(name, 'addr', []).call(callback); + }; + + /** + * Sets a new address + * + * @method setAddress + * @param {string} name + * @param {string} address + * @param {Object} sendOptions + * @param {function} callback + * @returns {eventifiedPromise} + */ + ENS.prototype.setAddress = function (name, address, sendOptions, callback) { + return this.resolverMethodHandler.method(name, 'setAddr', [address]).send(sendOptions, callback); + }; + + /** + * Returns the public key + * + * @method getPubkey + * @param {string} name + * @param {function} callback + * @returns {eventifiedPromise} + */ + ENS.prototype.getPubkey = function (name, callback) { + return this.resolverMethodHandler.method(name, 'pubkey', [], callback).call(callback); + }; + + /** + * Set the new public key + * + * @method setPubkey + * @param {string} name + * @param {string} x + * @param {string} y + * @param {Object} sendOptions + * @param {function} callback + * @returns {eventifiedPromise} + */ + ENS.prototype.setPubkey = function (name, x, y, sendOptions, callback) { + return this.resolverMethodHandler.method(name, 'setPubkey', [x, y]).send(sendOptions, callback); + }; + + /** + * Returns the content + * + * @method getContent + * @param {string} name + * @param {function} callback + * @returns {eventifiedPromise} + */ + ENS.prototype.getContent = function (name, callback) { + return this.resolverMethodHandler.method(name, 'content', []).call(callback); + }; + + /** + * Set the content + * + * @method setContent + * @param {string} name + * @param {string} hash + * @param {function} callback + * @param {Object} sendOptions + * @returns {eventifiedPromise} + */ + ENS.prototype.setContent = function (name, hash, sendOptions, callback) { + return this.resolverMethodHandler.method(name, 'setContent', [hash]).send(sendOptions, callback); + }; + + /** + * Get the multihash + * + * @method getMultihash + * @param {string} name + * @param {function} callback + * @returns {eventifiedPromise} + */ + ENS.prototype.getMultihash = function (name, callback) { + return this.resolverMethodHandler.method(name, 'multihash', []).call(callback); + }; + + /** + * Set the multihash + * + * @method setMultihash + * @param {string} name + * @param {string} hash + * @param {Object} sendOptions + * @param {function} callback + * @returns {eventifiedPromise} + */ + 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. + * + * @returns {Promise} + */ + ENS.prototype.checkNetwork = function () { + var self = this; + return self.eth.getBlock('latest').then(function (block) { + var headAge = new Date() / 1000 - block.timestamp; + if (headAge > 3600) { + throw new Error("Network not synced; last block was " + headAge + " seconds ago"); + } + return self.eth.net.getNetworkType(); + }).then(function (networkType) { + var addr = config.addresses[networkType]; + 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", + ropsten: "0x112234455c3a32fd11230c42e7bccd4a84e02010", + rinkeby: "0xe7410170f87102df0055eb195163a03b7f2bff4a" + }, + }; + + module.exports = config; + + },{}],362:[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 . + */ + /** + * @file Registry.js + * + * @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. + * + * @method Registry + * @param {Ens} ens + * @constructor + */ + function Registry(ens) { + var self = this; + this.ens = ens; + 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. + * + * @method owner + * @param {string} name + * @param {function} callback + * @return {Promise} + */ + 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. + * + * @method resolver + * @param {string} name + * @return {Promise} + */ + 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) { + var contract = new Contract(RESOLVER_ABI, address); + contract.setProvider(self.ens.eth.currentProvider); + 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. + 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 . + */ + /** + * @file index.js + * + * @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. + 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 . + */ + /** + * @file ResolverMethodHandler.js + * + * @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 + */ + function ResolverMethodHandler(registry) { + this.registry = registry; + } + + /** + * Executes an resolver method and returns an eventifiedPromise + * + * @param {string} ensName + * @param {string} methodName + * @param {array} methodArguments + * @param {function} callback + * @returns {Object} + */ + ResolverMethodHandler.prototype.method = function (ensName, methodName, methodArguments, callback) { + return { + call: this.call.bind({ + ensName: ensName, + methodName: methodName, + methodArguments: methodArguments, + callback: callback, + parent: this + }), + send: this.send.bind({ + ensName: ensName, + methodName: methodName, + methodArguments: methodArguments, + callback: callback, + parent: this + }) + }; + }; + + /** + * Executes call + * + * @returns {eventifiedPromise} + */ + ResolverMethodHandler.prototype.call = function (callback) { + 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 + * + * @param {Object} sendOptions + * @param {function} callback + * @returns {eventifiedPromise} + */ + ResolverMethodHandler.prototype.send = function (sendOptions, callback) { + 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 + * + * @param {eventifiedPromise} promiEvent + * @param {function} method + * @param {array} preparedArguments + * @param {function} callback + * @returns {eventifiedPromise} + */ + ResolverMethodHandler.prototype.handleCall = function (promiEvent, method, preparedArguments, callback) { + 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 + * + * @param {eventifiedPromise} promiEvent + * @param {function} method + * @param {array} preparedArguments + * @param {Object} sendOptions + * @param {function} callback + * @returns {eventifiedPromise} + */ + ResolverMethodHandler.prototype.handleSend = function (promiEvent, method, preparedArguments, sendOptions, callback) { + method.apply(this, preparedArguments).send(sendOptions) + .on('transactionHash', function (hash) { + promiEvent.eventEmitter.emit('transactionHash', hash); + }) + .on('confirmation', function (confirmationNumber, receipt) { + promiEvent.eventEmitter.emit('confirmation', confirmationNumber, receipt); + }) + .on('receipt', function (receipt) { + promiEvent.eventEmitter.emit('receipt', receipt); + promiEvent.resolve(receipt); + + if (_.isFunction(callback)) { + callback(receipt); + } + }) + .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 + * + * @param {string} name + * @param {array} methodArguments + * @returns {array} + */ + 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, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "resolver", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "owner", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "label", + "type": "bytes32" + }, + { + "name": "owner", + "type": "address" + } + ], + "name": "setSubnodeOwner", + "outputs": [], + "payable": false, + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "ttl", + "type": "uint64" + } + ], + "name": "setTTL", + "outputs": [], + "payable": false, + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "ttl", + "outputs": [ + { + "name": "", + "type": "uint64" + } + ], + "payable": false, + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "resolver", + "type": "address" + } + ], + "name": "setResolver", + "outputs": [], + "payable": false, + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "owner", + "type": "address" + } + ], + "name": "setOwner", + "outputs": [], + "payable": false, + "type": "function" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "owner", + "type": "address" + } + ], + "name": "Transfer", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": true, + "name": "label", + "type": "bytes32" + }, + { + "indexed": false, + "name": "owner", + "type": "address" + } + ], + "name": "NewOwner", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "resolver", + "type": "address" + } + ], + "name": "NewResolver", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "ttl", + "type": "uint64" + } + ], + "name": "NewTTL", + "type": "event" + } + ]; + + module.exports = REGISTRY; + + },{}],366:[function(require,module,exports){ + "use strict"; + + var RESOLVER = [ + { + "constant": true, + "inputs": [ + { + "name": "interfaceID", + "type": "bytes4" + } + ], + "name": "supportsInterface", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "contentTypes", + "type": "uint256" + } + ], + "name": "ABI", + "outputs": [ + { + "name": "contentType", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + } + ], + "payable": false, + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "hash", + "type": "bytes" + } + ], + "name": "setMultihash", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "multihash", + "outputs": [ + { + "name": "", + "type": "bytes" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "x", + "type": "bytes32" + }, + { + "name": "y", + "type": "bytes32" + } + ], + "name": "setPubkey", + "outputs": [], + "payable": false, + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "content", + "outputs": [ + { + "name": "ret", + "type": "bytes32" + } + ], + "payable": false, + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "addr", + "outputs": [ + { + "name": "ret", + "type": "address" + } + ], + "payable": false, + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "contentType", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + } + ], + "name": "setABI", + "outputs": [], + "payable": false, + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "name", + "outputs": [ + { + "name": "ret", + "type": "string" + } + ], + "payable": false, + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "name", + "type": "string" + } + ], + "name": "setName", + "outputs": [], + "payable": false, + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "hash", + "type": "bytes32" + } + ], + "name": "setContent", + "outputs": [], + "payable": false, + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "pubkey", + "outputs": [ + { + "name": "x", + "type": "bytes32" + }, + { + "name": "y", + "type": "bytes32" + } + ], + "payable": false, + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "addr", + "type": "address" + } + ], + "name": "setAddr", + "outputs": [], + "payable": false, + "type": "function" + }, + { + "inputs": [ + { + "name": "ensAddr", + "type": "address" + } + ], + "payable": false, + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "a", + "type": "address" + } + ], + "name": "AddrChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "hash", + "type": "bytes32" + } + ], + "name": "ContentChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "name", + "type": "string" + } + ], + "name": "NameChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": true, + "name": "contentType", + "type": "uint256" + } + ], + "name": "ABIChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "x", + "type": "bytes32" + }, + { + "indexed": false, + "name": "y", + "type": "bytes32" + } + ], + "name": "PubkeyChanged", + "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 . + */ + /** + * @file iban.js + * + * Details: https://github.com/ethereum/wiki/wiki/ICAP:-Inter-exchange-Client-Address-Protocol + * + * @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) { + result = '0' + result; + } + 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. + * + * @method iso13616Prepare + * @param {String} iban the IBAN + * @returns {String} the prepared IBAN + */ + 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){ + // A = 10, B = 11, ... Z = 35 + return code - A + 10; + } else { + return n; + } + }).join(''); + }; + + /** + * Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064. + * + * @method mod9710 + * @param {String} iban + * @returns {Number} + */ + 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 + * + * @param {String} iban + */ + var Iban = function Iban(iban) { + this._iban = iban; + }; + + /** + * This method should be used to create an ethereum address from a direct iban address + * + * @method toAddress + * @param {String} iban address + * @return {String} the ethereum address + */ + 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 + * + * @method toIban + * @param {String} address + * @return {String} the IBAN address + */ + Iban.toIban = function (address) { + return Iban.fromAddress(address).toString(); + }; + + /** + * This method should be used to create iban object from an ethereum address + * + * @method fromAddress + * @param {String} address + * @return {Iban} the IBAN object + */ + Iban.fromAddress = function (address) { + 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". + * This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits + * + * @method fromBban + * @param {String} bban the BBAN to convert to IBAN + * @returns {Iban} the IBAN object + */ + 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 + * + * @method createIndirect + * @param {Object} options, required options are "institution" and "identifier" + * @return {Iban} the IBAN object + */ + 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 + * + * @method isValid + * @param {String} iban string + * @return {Boolean} true if it is valid IBAN + */ + Iban.isValid = function (iban) { + var i = new Iban(iban); + return i.isValid(); + }; + + /** + * Should be called to check if iban is correct + * + * @method isValid + * @returns {Boolean} true if it is, otherwise false + */ + Iban.prototype.isValid = function () { + 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 + * + * @method isDirect + * @returns {Boolean} true if it is, otherwise false + */ + Iban.prototype.isDirect = function () { + return this._iban.length === 34 || this._iban.length === 35; + }; + + /** + * Should be called to check if iban number if indirect + * + * @method isIndirect + * @returns {Boolean} true if it is, otherwise false + */ + 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) + * + * @method checksum + * @returns {String} checksum + */ + Iban.prototype.checksum = function () { + return this._iban.substr(2, 2); + }; + + /** + * Should be called to get institution identifier + * eg. XREG + * + * @method institution + * @returns {String} institution identifier + */ + Iban.prototype.institution = function () { + return this.isIndirect() ? this._iban.substr(7, 4) : ''; + }; + + /** + * Should be called to get client identifier within institution + * eg. GAVOFYORK + * + * @method client + * @returns {String} client identifier + */ + Iban.prototype.client = function () { + return this.isIndirect() ? this._iban.substr(11) : ''; + }; + + /** + * Should be called to get client direct address + * + * @method toAddress + * @returns {String} ethereum address + */ + Iban.prototype.toAddress = function () { + if (this.isDirect()) { + var base36 = this._iban.substr(4); + 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 . + */ + /** + * @file index.js + * @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; + }, + set: function (val) { + if(val) { + defaultAccount = utils.toChecksumAddress(formatters.inputAddressFormatter(val)); + } + + // update defaultBlock + methods.forEach(function(method) { + method.defaultAccount = defaultAccount; + }); + + return val; + }, + enumerable: true + }); + Object.defineProperty(this, 'defaultBlock', { + get: function () { + return defaultBlock; + }, + set: function (val) { + defaultBlock = val; + + // update defaultBlock + methods.forEach(function(method) { + method.defaultBlock = defaultBlock; + }); + + return val; + }, + enumerable: true + }); + + + var methods = [ + new Method({ + name: 'getAccounts', + call: 'personal_listAccounts', + params: 0, + outputFormatter: utils.toChecksumAddress + }), + new Method({ + name: 'newAccount', + call: 'personal_newAccount', + params: 1, + inputFormatter: [null], + outputFormatter: utils.toChecksumAddress + }), + new Method({ + name: 'unlockAccount', + call: 'personal_unlockAccount', + params: 3, + inputFormatter: [formatters.inputAddressFormatter, null, null] + }), + new Method({ + name: 'lockAccount', + call: 'personal_lockAccount', + params: 1, + inputFormatter: [formatters.inputAddressFormatter] + }), + new Method({ + name: 'importRawKey', + call: 'personal_importRawKey', + params: 2 + }), + new Method({ + name: 'sendTransaction', + call: 'personal_sendTransaction', + params: 2, + inputFormatter: [formatters.inputTransactionFormatter, null] + }), + new Method({ + name: 'signTransaction', + call: 'personal_signTransaction', + params: 2, + inputFormatter: [formatters.inputTransactionFormatter, null] + }), + new Method({ + name: 'sign', + call: 'personal_sign', + params: 3, + inputFormatter: [formatters.inputSignFormatter, formatters.inputAddressFormatter, null] + }), + new Method({ + name: 'ecRecover', + call: 'personal_ecRecover', + params: 2, + inputFormatter: [formatters.inputSignFormatter, null] + }) + ]; + methods.forEach(function(method) { + method.attachToObject(_this); + method.setRequestManager(_this._requestManager); + method.defaultBlock = _this.defaultBlock; + 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 . + */ + /** + * @file getNetworkType.js + * @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'; + } + if (genesis.hash === '0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303' && + id === 2) { + returnValue = 'morden'; + } + if (genesis.hash === '0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d' && + id === 3) { + returnValue = 'ropsten'; + } + if (genesis.hash === '0x6341fd3daf94b748c72ced5a5b26028f2474f5f00d824504e4fa37a75767e177' && + id === 4) { + returnValue = 'rinkeby'; + } + if (genesis.hash === '0xa3c565fc15c7478862d50ccd6561e3c06b24cc509bf388941c25ea985ce32cb9' && + id === 42) { + returnValue = 'kovan'; + } + + if (_.isFunction(callback)) { + callback(null, returnValue); + } + + return returnValue; + }) + .catch(function (err) { + if (_.isFunction(callback)) { + callback(err); + } else { + throw err; + } + }); + }; + + 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 . + */ + /** + * @file index.js + * @author Fabian Vogelsteller + * @date 2017 + */ + + "use strict"; + + var _ = require('underscore'); + var core = require('web3-core'); + var helpers = require('web3-core-helpers'); + var Subscriptions = require('web3-core-subscriptions').subscriptions; + 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 () { + setProvider.apply(_this, arguments); + _this.net.setProvider.apply(_this, arguments); + _this.personal.setProvider.apply(_this, arguments); + _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; + }, + set: function (val) { + 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 + }); + Object.defineProperty(this, 'defaultBlock', { + get: function () { + return defaultBlock; + }, + set: function (val) { + defaultBlock = val; + // 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 + // web3-eth would subsequently change the provider for _all_ contract + // instances! + 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 + // the contract instances + var _this = this; + var setProvider = self.setProvider; + self.setProvider = function() { + setProvider.apply(self, arguments); + 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', + call: 'web3_clientVersion' + }), + new Method({ + name: 'getProtocolVersion', + call: 'eth_protocolVersion', + params: 0 + }), + new Method({ + name: 'getCoinbase', + call: 'eth_coinbase', + params: 0 + }), + new Method({ + name: 'isMining', + call: 'eth_mining', + params: 0 + }), + new Method({ + name: 'getHashrate', + call: 'eth_hashrate', + params: 0, + outputFormatter: utils.hexToNumber + }), + new Method({ + name: 'isSyncing', + call: 'eth_syncing', + params: 0, + outputFormatter: formatter.outputSyncingFormatter + }), + new Method({ + name: 'getGasPrice', + call: 'eth_gasPrice', + params: 0, + outputFormatter: formatter.outputBigNumberFormatter + }), + new Method({ + name: 'getAccounts', + call: 'eth_accounts', + params: 0, + outputFormatter: utils.toChecksumAddress + }), + new Method({ + name: 'getBlockNumber', + call: 'eth_blockNumber', + params: 0, + outputFormatter: utils.hexToNumber + }), + new Method({ + name: 'getBalance', + call: 'eth_getBalance', + params: 2, + inputFormatter: [formatter.inputAddressFormatter, formatter.inputDefaultBlockNumberFormatter], + outputFormatter: formatter.outputBigNumberFormatter + }), + new Method({ + name: 'getStorageAt', + call: 'eth_getStorageAt', + params: 3, + inputFormatter: [formatter.inputAddressFormatter, utils.numberToHex, formatter.inputDefaultBlockNumberFormatter] + }), + new Method({ + name: 'getCode', + call: 'eth_getCode', + params: 2, + inputFormatter: [formatter.inputAddressFormatter, formatter.inputDefaultBlockNumberFormatter] + }), + new Method({ + name: 'getBlock', + call: blockCall, + params: 2, + inputFormatter: [formatter.inputBlockNumberFormatter, function (val) { return !!val; }], + outputFormatter: formatter.outputBlockFormatter + }), + new Method({ + name: 'getUncle', + call: uncleCall, + params: 2, + inputFormatter: [formatter.inputBlockNumberFormatter, utils.numberToHex], + outputFormatter: formatter.outputBlockFormatter, + + }), + new Method({ + name: 'getBlockTransactionCount', + call: getBlockTransactionCountCall, + params: 1, + inputFormatter: [formatter.inputBlockNumberFormatter], + outputFormatter: utils.hexToNumber + }), + new Method({ + name: 'getBlockUncleCount', + call: uncleCountCall, + params: 1, + inputFormatter: [formatter.inputBlockNumberFormatter], + outputFormatter: utils.hexToNumber + }), + new Method({ + name: 'getTransaction', + call: 'eth_getTransactionByHash', + params: 1, + inputFormatter: [null], + outputFormatter: formatter.outputTransactionFormatter + }), + new Method({ + name: 'getTransactionFromBlock', + call: transactionFromBlockCall, + params: 2, + inputFormatter: [formatter.inputBlockNumberFormatter, utils.numberToHex], + outputFormatter: formatter.outputTransactionFormatter + }), + new Method({ + name: 'getTransactionReceipt', + call: 'eth_getTransactionReceipt', + params: 1, + inputFormatter: [null], + outputFormatter: formatter.outputTransactionReceiptFormatter + }), + new Method({ + name: 'getTransactionCount', + call: 'eth_getTransactionCount', + params: 2, + inputFormatter: [formatter.inputAddressFormatter, formatter.inputDefaultBlockNumberFormatter], + outputFormatter: utils.hexToNumber + }), + new Method({ + name: 'sendSignedTransaction', + call: 'eth_sendRawTransaction', + params: 1, + inputFormatter: [null] + }), + new Method({ + name: 'signTransaction', + call: 'eth_signTransaction', + params: 1, + inputFormatter: [formatter.inputTransactionFormatter] + }), + new Method({ + name: 'sendTransaction', + call: 'eth_sendTransaction', + params: 1, + inputFormatter: [formatter.inputTransactionFormatter] + }), + new Method({ + name: 'sign', + call: 'eth_sign', + params: 2, + inputFormatter: [formatter.inputSignFormatter, formatter.inputAddressFormatter], + transformPayload: function (payload) { + payload.params.reverse(); + return payload; + } + }), + new Method({ + name: 'call', + call: 'eth_call', + params: 2, + inputFormatter: [formatter.inputCallFormatter, formatter.inputDefaultBlockNumberFormatter] + }), + new Method({ + name: 'estimateGas', + call: 'eth_estimateGas', + params: 1, + inputFormatter: [formatter.inputCallFormatter], + outputFormatter: utils.hexToNumber + }), + new Method({ + name: 'submitWork', + call: 'eth_submitWork', + params: 3 + }), + new Method({ + name: 'getWork', + call: 'eth_getWork', + params: 0 + }), + new Method({ + name: 'getPastLogs', + call: 'eth_getLogs', + params: 1, + inputFormatter: [formatter.inputLogFormatter], + outputFormatter: formatter.outputLogFormatter + }), + + // subscriptions + new Subscriptions({ + name: 'subscribe', + type: 'eth', + subscriptions: { + 'newBlockHeaders': { + // TODO rename on RPC side? + subscriptionName: 'newHeads', // replace subscription with this name + params: 0, + outputFormatter: formatter.outputBlockFormatter + }, + 'pendingTransactions': { + subscriptionName: 'newPendingTransactions', // replace subscription with this name + params: 0 + }, + 'logs': { + params: 1, + inputFormatter: [formatter.inputLogFormatter], + outputFormatter: formatter.outputLogFormatter, + // DUBLICATE, also in web3-eth-contract + subscriptionHandler: function (output) { + if(output.removed) { + this.emit('changed', output); + } else { + this.emit('data', output); + } + + if (_.isFunction(this.callback)) { + this.callback(null, output, this); + } + } + }, + 'syncing': { + params: 0, + 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); + } + } + }, 500); + } + } + } + } + }) + ]; + + 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 . + */ + /** + * @file index.js + * @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', + call: 'net_version', + params: 0, + outputFormatter: utils.hexToNumber + }), + new Method({ + name: 'isListening', + call: 'net_listening', + params: 0 + }), + new Method({ + name: 'getPeerCount', + call: 'net_peerCount', + params: 0, + outputFormatter: utils.hexToNumber + }) + ].forEach(function(method) { + 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 + const ethUtil = require('ethereumjs-util') + const EthBlockTracker = require('eth-block-tracker') + const map = require('async/map') + const eachSeries = require('async/eachSeries') + const Stoplight = require('./util/stoplight.js') + 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 + self._blockTracker = opts.blockTracker || new EthBlockTracker({ + 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 + self._blockTracker.once('block', () => { + self._ready.go() + }) + // local state + 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) + } else { + // 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) { + end(new Error('Request for method "' + payload.method + '" not handled by any subprovider. Please check your subprovider configuration to ensure this method is handled.')) + } else { + try { + var provider = self._providers[currentProvider] + provider.handleRequest(payload, next, end) + } catch (e) { + end(e) + } + } + } + + function end(_error, _result) { + error = _error + result = _result + + eachSeries(stack, function(fn, callback) { + + if (fn) { + fn(error, result, callback) + } else { + callback() + } + }, 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, + code: -32000 + } + // respond with both error formats + finished(error, resultObj) + } else { + finished(null, resultObj) + } + }) + } + } + + // + // 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), + hash: ethUtil.toBuffer(jsonBlock.hash), + parentHash: ethUtil.toBuffer(jsonBlock.parentHash), + nonce: ethUtil.toBuffer(jsonBlock.nonce), + mixHash: ethUtil.toBuffer(jsonBlock.mixHash), + sha3Uncles: ethUtil.toBuffer(jsonBlock.sha3Uncles), + logsBloom: ethUtil.toBuffer(jsonBlock.logsBloom), + transactionsRoot: ethUtil.toBuffer(jsonBlock.transactionsRoot), + stateRoot: ethUtil.toBuffer(jsonBlock.stateRoot), + receiptsRoot: ethUtil.toBuffer(jsonBlock.receiptRoot || jsonBlock.receiptsRoot), + miner: ethUtil.toBuffer(jsonBlock.miner), + difficulty: ethUtil.toBuffer(jsonBlock.difficulty), + totalDifficulty: ethUtil.toBuffer(jsonBlock.totalDifficulty), + size: ethUtil.toBuffer(jsonBlock.size), + extraData: ethUtil.toBuffer(jsonBlock.extraData), + gasLimit: ethUtil.toBuffer(jsonBlock.gasLimit), + gasUsed: ethUtil.toBuffer(jsonBlock.gasUsed), + timestamp: ethUtil.toBuffer(jsonBlock.timestamp), + 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 }; + var space = opts.space || ''; + 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) { + var aobj = { key: a, value: node[a] }; + var bobj = { key: b, value: node[b] }; + return f(aobj, bobj); + }; + }; + })(opts.cmp); + + var seen = []; + return (function stringify (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; + } + if (typeof node !== 'object' || node === null) { + return json.stringify(node); + } + if (isArray(node)) { + var out = []; + for (var i = 0; i < node.length; i++) { + var item = stringify(node, i, node[i], level+1) || json.stringify(null); + out.push(indent + space + item); + } + return '[' + out.join(',') + indent + ']'; + } + else { + if (seen.indexOf(node) !== -1) { + if (cycles) return json.stringify('__cycle__'); + 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; + ; + out.push(indent + space + keyValue); + } + seen.splice(seen.indexOf(node), 1); + return '{' + out.join(',') + indent + '}'; + } + })({ '': 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 = []; + for (var key in obj) { + if (has.call(obj, key)) keys.push(key); + } + return keys; + }; + + },{"jsonify":192}],375:[function(require,module,exports){ + module.exports={ + "_from": "web3-provider-engine@14.1.0", + "_id": "web3-provider-engine@14.1.0", + "_inBundle": false, + "_integrity": "sha512-vGZtqhSUzGTiMGhJXNnB/aRDlrPZLhLnBZ2NPArkZtr8XSrwg9m08tw4+PuWg5za0TJuoE/vuPQc501HddZZWw==", + "_location": "/web3-provider-engine", + "_phantomChildren": { + "jsonify": "0.0.0" + }, + "_requested": { + "type": "version", + "registry": true, + "raw": "web3-provider-engine@14.1.0", + "name": "web3-provider-engine", + "escapedName": "web3-provider-engine", + "rawSpec": "14.1.0", + "saveSpec": null, + "fetchSpec": "14.1.0" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/web3-provider-engine/-/web3-provider-engine-14.1.0.tgz", + "_shasum": "91590020f8b8c1b65846321310cbfdb039090fc6", + "_spec": "web3-provider-engine@14.1.0", + "_where": "/Users/alexvlasov/Blockchain/web3swift/web3swiftJSProxy", + "author": "", + "browser": { + "request": false, + "ws": false + }, + "bugs": { + "url": "https://github.com/MetaMask/provider-engine/issues" + }, + "bundleDependencies": false, + "dependencies": { + "async": "^2.5.0", + "backoff": "^2.5.0", + "clone": "^2.0.0", + "cross-fetch": "^2.1.0", + "eth-block-tracker": "^3.0.0", + "eth-json-rpc-infura": "^3.1.0", + "eth-sig-util": "^1.4.2", + "ethereumjs-block": "^1.2.2", + "ethereumjs-tx": "^1.2.0", + "ethereumjs-util": "^5.1.5", + "ethereumjs-vm": "^2.3.4", + "json-rpc-error": "^2.0.0", + "json-stable-stringify": "^1.0.1", + "promise-to-callback": "^1.0.0", + "readable-stream": "^2.2.9", + "request": "^2.85.0", + "semaphore": "^1.0.3", + "ws": "^5.1.1", + "xhr": "^2.2.0", + "xtend": "^4.0.1" + }, + "deprecated": false, + "description": "[![Greenkeeper badge](https://badges.greenkeeper.io/MetaMask/provider-engine.svg)](https://greenkeeper.io/)", + "devDependencies": { + "babel-cli": "^6.26.0", + "babel-preset-es2015": "^6.24.1", + "babel-preset-stage-0": "^6.24.1", + "browserify": "^16.1.1", + "ethjs": "^0.3.6", + "tape": "^4.4.0" + }, + "homepage": "https://github.com/MetaMask/provider-engine#readme", + "license": "MIT", + "main": "index.js", + "name": "web3-provider-engine", + "repository": { + "type": "git", + "url": "git+https://github.com/MetaMask/provider-engine.git" + }, + "scripts": { + "build": "babel zero.js index.js -d dist/es5 && babel subproviders -d dist/es5/subproviders && babel util -d dist/es5/util", + "bundle": "mkdir -p ./dist && npm run bundle-engine && npm run bundle-zero", + "bundle-engine": "browserify -s ProviderEngine -e index.js -t [ babelify --presets [ es2015 ] ] > dist/ProviderEngine.js", + "bundle-zero": "browserify -s ZeroClientProvider -e zero.js -t [ babelify --presets [ es2015 ] ] > dist/ZeroClientProvider.js", + "prepublish": "npm run build && npm run bundle", + "test": "node test/index.js" + }, + "version": "14.1.0" + } + + },{}],376:[function(require,module,exports){ + const inherits = require('util').inherits + const ethUtil = require('ethereumjs-util') + const BN = ethUtil.BN + const clone = require('clone') + 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 || {} + // set initialization blocker + self._ready = new Stoplight() + self.strategies = { + perma: new ConditionalPermaCacheStrategy({ + eth_getTransactionByHash: containsBlockhash, + eth_getTransactionReceipt: containsBlockhash, + }), + block: new BlockCacheStrategy(self), + fork: new BlockCacheStrategy(self), + } + } + + // setup a block listener on 'setEngine' + BlockCacheProvider.prototype.setEngine = function(engine) { + const self = this + self.engine = engine + // unblock initialization after first block + engine.once('block', function(block) { + self.currentBlock = block + self._ready.go() + // from now on, empty old cache every block + engine.on('block', clearOldCache) + }) + + function clearOldCache(newBlock) { + var previousBlock = self.currentBlock + self.currentBlock = newBlock + if (!previousBlock) return + self.strategies.block.cacheRollOff(previousBlock) + 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') { + requestedBlockNumber = ethUtil.bufferToHex(self.currentBlock.number) + } else { + // 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. + next(function(err, result, cb) { + // err is already handled by engine + if (err) return cb() + strategy.cacheResult(payload, result, requestedBlockNumber, cb) + }) + }) + } + + // + // Cache Strategies + // + + function PermaCacheStrategy() { + var self = this + self.cache = {} + // clear cache every ten minutes + var timeout = setInterval(function(){ + self.cache = {} + }, 10 * 60 * 1e3) + // 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, + // send it back down to the client (where it will be recached.) + var cacheIsEarlyEnough = compareHex(requestedBlockNumber, cached.blockNumber) >= 0 + if (cacheIsEarlyEnough) { + var clonedValue = clone(cached.result) + return hit(null, clonedValue) + } else { + return miss() + } + } + + PermaCacheStrategy.prototype.cacheResult = function(payload, result, requestedBlockNumber, callback) { + var identifier = cacheUtils.cacheIdentifierForPayload(payload) + + if (result) { + var clonedValue = clone(result) + this.cache[identifier] = { + blockNumber: requestedBlockNumber, + 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) + } else { + callback() + } + } else { + // Cache all requests that don't have a conditional + 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] + // create new cache if necesary + if (!blockCache) { + const newCache = {} + this.cache[blockNumber] = newCache + blockCache = newCache + } + 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) + var identifier = cacheUtils.cacheIdentifierForPayload(payload) + blockCache[identifier] = result + } + 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 + const previousHex = ethUtil.bufferToHex(previousBlock.number) + const oldBlockNumber = Number.parseInt(previousHex, 16) + // clear old caches + Object.keys(self.cache) + .map(Number) + .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 || {} + var responses = extend({ + web3_clientVersion: 'ProviderEngine/v'+version+'/javascript', + net_listening: true, + eth_hashrate: '0x00', + eth_mining: false, + }, 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 + const retry = require('async/retry') + const waterfall = require('async/waterfall') + const asyncify = require('async/asyncify') + const JsonRpcError = require('json-rpc-error') + 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', + 'ETIMEDOUT', + // ignore server sent html error pages + // 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: { + 'Accept': 'application/json', + 'Content-Type': 'application/json' + }, + body: JSON.stringify(newPayload) + } + + if (self.originHttpHeaderKey && originDomain) { + reqParams.headers[self.originHttpHeaderKey] = originDomain + } + + retry({ + times: 5, + interval: 1000, + errorFilter: isErrorRetriable, + }, + (cb) => self._submitRequest(reqParams, cb), + (err, result) => { + // ends on retriable error + if (err && isErrorRetriable(err)) { + const errMsg = `FetchSubprovider - cannot complete request. All retries exhausted.\nOriginal Error:\n${err.toString()}\n\n` + const retriesExhaustedErr = new Error(errMsg) + return end(retriesExhaustedErr) + } + // otherwise continue normally + 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, + // buffer body + (cb) => promiseToCallback(res.text())(cb), + // parse body + 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) { + return cb(new JsonRpcError.InternalError(body)) + } + // check for rpc error + if (body.error) return cb(new JsonRpcError.InternalError(body.error)) + // return successful result + cb(null, body.result) + } + }) + } + + 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 + const ethUtil = require('ethereumjs-util') + 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 + // eth_newFilter + // eth_getFilterChanges + // eth_uninstallFilter + // eth_getFilterLogs + + inherits(FilterSubprovider, Subprovider) + + function FilterSubprovider(opts) { + opts = opts || {} + const self = this + self.filterIndex = 0 + self.filters = {} + self.filterDestroyHandlers = {} + self.asyncBlockHandlers = {} + self.asyncPendingBlockHandlers = {} + self._ready = new Stoplight() + self._ready.setMaxListeners(opts.maxFilters || 25) + 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 + self.engine.on('block', function(block){ + // pause processing + self._ready.stop() + // update filters + var updaters = valuesFor(self.asyncBlockHandlers) + .map(function(fn){ return fn.bind(null, block) }) + async.parallel(updaters, function(err){ + if (err) console.error(err) + // unpause processing + self._ready.go() + }) + }) + }) + + } + + 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){ + self._logsForBlock(block, function(err, logs){ + if (err) return cb(err) + newLogHandler(logs) + 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){ + self._txHashesForBlock(block, function(err, txs){ + if (err) return cb(err) + newTxHandler(txs) + 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) + if (!filter) return cb(null, []) + var results = filter.getChanges() + 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) + if (!filter) return cb(null, []) + if (filter.type === 'log') { + self.emitPayload({ + method: 'eth_getLogs', + params: [{ + fromBlock: filter.fromBlock, + toBlock: filter.toBlock, + address: filter.address, + topics: filter.topics, + }], + }, function(err, res){ + if (err) return cb(err) + cb(null, res.result) + }) + } else { + var results = [] + 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 + if (self.checkForPendingBlocksActive) return + var activePendingTxFilters = !!Object.keys(self.asyncPendingBlockHandlers).length + if (activePendingTxFilters) { + self.checkForPendingBlocksActive = true + self.emitPayload({ + method: 'eth_getBlockByNumber', + params: ['pending', true], + }, function(err, res){ + if (err) { + self.checkForPendingBlocksActive = false + console.error(err) + return + } + self.onNewPendingBlock(res.result, function(err){ + if (err) console.error(err) + self.checkForPendingBlocksActive = false + setTimeout(self.checkForPendingBlocks.bind(self), self.pendingBlockTimeout) + }) + }) + } + } + + FilterSubprovider.prototype.onNewPendingBlock = function(block, cb){ + const self = this + // update filters + var updaters = valuesFor(self.asyncPendingBlockHandlers) + .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) + self.emitPayload({ + method: 'eth_getLogs', + params: [{ + fromBlock: blockNumber, + toBlock: blockNumber, + }], + }, function(err, response){ + if (err) return cb(err) + if (response.error) return cb(response.error) + cb(null, response.result) + }) + + } + + FilterSubprovider.prototype._txHashesForBlock = function(block, cb) { + const self = this + var txs = block.transactions + // short circuit if empty + if (txs.length === 0) return cb(null, []) + // txs are already hashes + if ('string' === typeof txs[0]) { + cb(null, txs) + // txs are obj, need to map to hashes + } else { + var results = txs.map((tx) => tx.hash) + cb(null, results) + } + } + + // + // BlockFilter + // + + inherits(BlockFilter, EventEmitter) + + function BlockFilter(opts) { + // console.log('BlockFilter - new') + const self = this + EventEmitter.apply(self) + self.type = 'block' + self.engine = opts.engine + self.blockNumber = opts.blockNumber + self.updates = [] + } + + BlockFilter.prototype.update = function(block){ + // console.log('BlockFilter - update') + const self = this + var blockHash = bufferToHex(block.hash) + 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 + EventEmitter.apply(self) + self.type = 'log' + self.fromBlock = (opts.fromBlock !== undefined) ? opts.fromBlock : 'latest' + self.toBlock = (opts.toBlock !== undefined) ? opts.toBlock : 'latest' + var expectedAddress = opts.address && (Array.isArray(opts.address) ? opts.address : [opts.address]); + self.address = expectedAddress && expectedAddress.map(normalizeHex); + self.topics = opts.topics || [] + 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] + // topics can be null, representing a wild card for that position + // console.log('LogFilter - validateLog - topics', log.topics) + // console.log('LogFilter - validateLog - against topics', self.topics) + var topicsMatch = self.topics.reduce(function(previousMatched, topicPattern, index){ + // abort in progress + if (!previousMatched) return false + // wild card + if (!topicPattern) return true + // pattern is longer than actual topics + var logTopic = log.topics[index] + if (!logTopic) return false + // check each possible matching topic + var subtopicsToMatch = Array.isArray(topicPattern) ? topicPattern : [topicPattern] + var topicDoesMatch = subtopicsToMatch.filter(function(subTopic) { + return logTopic.toLowerCase() === subTopic.toLowerCase() + }).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 + // validate filter match + var validLogs = [] + logs.forEach(function(log) { + var validated = self.validateLog(log) + if (!validated) return + // add to results + validLogs.push(log) + self.updates.push(log) + self.allResults.push(log) + }) + if (validLogs.length > 0) { + 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 + EventEmitter.apply(self) + self.type = 'pendingTx' + 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 + var validTxs = [] + txs.forEach(function (tx) { + // validate filter match + var validated = self.validateUnique(tx) + if (!validated) return + // add to results + validTxs.push(tx) + self.updates.push(tx) + self.allResults.push(tx) + }) + if (validTxs.length > 0) { + 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') { + stripped = stripped.substr(1) + } + 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] + // async function + if ('function' === typeof staticResponse) { + staticResponse(payload, next, end) + // static response - null is valid response + } else if (staticResponse !== undefined) { + // return result asynchronously + setTimeout(() => end(null, staticResponse)) + // no prepared response - skip + } else { + next() + } + } + + },{"./subprovider.js":387,"util":333}],381:[function(require,module,exports){ + /* + * Emulate 'eth_accounts' / 'eth_sendTransaction' using 'eth_sendRawTransaction' + * + * The two callbacks a user needs to implement are: + * - 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 + const ethUtil = require('ethereumjs-util') + const sigUtil = require('eth-sig-util') + const extend = require('xtend') + const Semaphore = require('semaphore') + 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 + // eth_sendTransaction + // eth_sign + // eth_signTypedData + // personal_sign + // personal_ecRecover + // parity_postTransaction + // parity_checkRequest + // parity_defaultAccount + + // + // Tx Signature Flow + // + // handleRequest: eth_sendTransaction + // validateTransaction (basic validity check) + // validateSender (checks that sender is in accounts) + // processTransaction (sign tx and submit to network) + // approveTransaction (UI approval hook) + // checkApproval + // finalizeAndSubmitTx (tx signing) + // nonceLock.take (bottle neck to ensure atomic nonce) + // fillInTxExtras (set fallback gasPrice, nonce, etc) + // 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 + if (opts.processTransaction) self.processTransaction = opts.processTransaction + if (opts.processMessage) self.processMessage = opts.processMessage + if (opts.processPersonalMessage) self.processPersonalMessage = opts.processPersonalMessage + if (opts.processTypedMessage) self.processTypedMessage = opts.processTypedMessage + // approval hooks + self.approveTransaction = opts.approveTransaction || self.autoApprove + self.approveMessage = opts.approveMessage || self.autoApprove + self.approvePersonalMessage = opts.approvePersonalMessage || self.autoApprove + self.approveTypedMessage = opts.approveTypedMessage || self.autoApprove + // actually perform the signature + if (opts.signTransaction) self.signTransaction = opts.signTransaction || mustProvideInConstructor('signTransaction') + if (opts.signMessage) self.signMessage = opts.signMessage || mustProvideInConstructor('signMessage') + if (opts.signPersonalMessage) self.signPersonalMessage = opts.signPersonalMessage || mustProvideInConstructor('signPersonalMessage') + if (opts.signTypedMessage) self.signTypedMessage = opts.signTypedMessage || mustProvideInConstructor('signTypedMessage') + if (opts.recoverPersonalSignature) self.recoverPersonalSignature = opts.recoverPersonalSignature + // 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){ + if (err) return end(err) + let result = accounts[0] || null + end(null, result) + }) + return + + case 'eth_accounts': + // process normally + self.getAccounts(function(err, accounts){ + if (err) return end(err) + end(null, accounts) + }) + return + + case 'eth_sendTransaction': + txParams = payload.params[0] + waterfall([ + (cb) => self.validateTransaction(txParams, cb), + (cb) => self.processTransaction(txParams, cb), + ], end) + return + + case 'eth_signTransaction': + txParams = payload.params[0] + waterfall([ + (cb) => self.validateTransaction(txParams, cb), + (cb) => self.processSignTransaction(txParams, cb), + ], end) + return + + case 'eth_sign': + // process normally + address = payload.params[0] + message = payload.params[1] + // non-standard "extraParams" to be appended to our "msgParams" obj + // good place for metadata + extraParams = payload.params[2] || {} + msgParams = extend(extraParams, { + from: address, + data: message, + }) + waterfall([ + (cb) => self.validateMessage(msgParams, cb), + (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 + // when it is clearly identifiable. + // + // That means when the first param is definitely an address, + // and the second param is definitely not, but is hex. + if (resemblesData(second) && resemblesAddress(first)) { + let warning = `The eth_personalSign method requires params ordered ` + warning += `[message, address]. This was previously handled incorrectly, ` + 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] || {} + msgParams = extend(extraParams, { + from: address, + data: message, + }) + waterfall([ + (cb) => self.validatePersonalMessage(msgParams, cb), + (cb) => self.processPersonalMessage(msgParams, cb), + ], end) + return + + case 'personal_ecRecover': + message = payload.params[0] + let signature = payload.params[1] + // non-standard "extraParams" to be appended to our "msgParams" obj + // good place for metadata + extraParams = payload.params[2] || {} + msgParams = extend(extraParams, { + sig: signature, + data: message, + }) + self.recoverPersonalSignature(msgParams, end) + return + + case 'eth_signTypedData': + // process normally + message = payload.params[0] + address = payload.params[1] + extraParams = payload.params[2] || {} + msgParams = extend(extraParams, { + from: address, + data: message, + }) + waterfall([ + (cb) => self.validateTypedMessage(msgParams, cb), + (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) + const account = accounts[0] || null + 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([ + (cb) => self.approveTransaction(txParams, cb), + (didApprove, cb) => self.checkApproval('transaction', didApprove, cb), + (cb) => self.finalizeAndSubmitTx(txParams, cb), + ], cb) + } + + + HookedWalletSubprovider.prototype.processSignTransaction = function(txParams, cb) { + const self = this + waterfall([ + (cb) => self.approveTransaction(txParams, cb), + (didApprove, cb) => self.checkApproval('transaction', didApprove, cb), + (cb) => self.finalizeTx(txParams, cb), + ], cb) + } + + HookedWalletSubprovider.prototype.processMessage = function(msgParams, cb) { + const self = this + waterfall([ + (cb) => self.approveMessage(msgParams, cb), + (didApprove, cb) => self.checkApproval('message', didApprove, cb), + (cb) => self.signMessage(msgParams, cb), + ], cb) + } + + HookedWalletSubprovider.prototype.processPersonalMessage = function(msgParams, cb) { + const self = this + waterfall([ + (cb) => self.approvePersonalMessage(msgParams, cb), + (didApprove, cb) => self.checkApproval('message', didApprove, cb), + (cb) => self.signPersonalMessage(msgParams, cb), + ], cb) + } + + HookedWalletSubprovider.prototype.processTypedMessage = function(msgParams, cb) { + const self = this + waterfall([ + (cb) => self.approveTypedMessage(msgParams, cb), + (didApprove, cb) => self.checkApproval('message', didApprove, cb), + (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], + }, function(error, res){ + if (error) { + self._parityRequests[reqId] = { error } + return + } + 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], + }, function(error, res){ + if (error) { + self._parityRequests[reqId] = { error } + return + } + 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 + // tx not handled yet + if (!result) return cb(null, null) + // tx was rejected (or other error) + if (result.error) return cb(result.error) + // tx sent + cb(null, result) + } + + // + // signature and recovery + // + + HookedWalletSubprovider.prototype.recoverPersonalSignature = function(msgParams, cb) { + let senderHex + try { + senderHex = sigUtil.recoverPersonalSignature(msgParams) + } catch (err) { + return cb(err) + } + cb(null, senderHex) + } + + // + // validation + // + + HookedWalletSubprovider.prototype.validateTransaction = function(txParams, cb){ + const self = this + // shortcut: undefined sender is invalid + if (txParams.from === undefined) return cb(new Error(`Undefined address - from address required to sign transaction.`)) + self.validateSender(txParams.from, function(err, senderIsValid){ + if (err) return cb(err) + if (!senderIsValid) return cb(new Error(`Unknown address - unable to sign transaction for this address: "${txParams.from}"`)) + 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.`)) + self.validateSender(msgParams.from, function(err, senderIsValid){ + if (err) return cb(err) + if (!senderIsValid) return cb(new Error(`Unknown address - unable to sign message for this address: "${msgParams.from}"`)) + 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.`)) + if (msgParams.data === undefined) return cb(new Error(`Undefined message - message required to sign personal message.`)) + if (!isValidHex(msgParams.data)) return cb(new Error(`HookedWalletSubprovider - validateMessage - message was not encoded as hex.`)) + self.validateSender(msgParams.from, function(err, senderIsValid){ + if (err) return cb(err) + if (!senderIsValid) return cb(new Error(`Unknown address - unable to sign message for this address: "${msgParams.from}"`)) + 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.`)) + this.validateSender(msgParams.from, function(err, senderIsValid){ + if (err) return cb(err) + if (!senderIsValid) return cb(new Error(`Unknown address - unable to sign message for this address: "${msgParams.from}"`)) + cb() + }) + } + + HookedWalletSubprovider.prototype.validateSender = function(senderAddress, cb){ + const self = this + // shortcut: undefined sender is invalid + if (!senderAddress) return cb(null, false) + self.getAccounts(function(err, accounts){ + if (err) return cb(err) + const senderIsValid = (accounts.map(toLowerCase).indexOf(senderAddress.toLowerCase()) !== -1) + 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 + // so we can atomically consume a nonce + self.nonceLock.take(function(){ + waterfall([ + self.fillInTxExtras.bind(self, txParams), + self.signTransaction.bind(self), + self.publishTransaction.bind(self), + ], function(err, txHash){ + self.nonceLock.leave() + if (err) return cb(err) + cb(null, txHash) + }) + }) + } + + HookedWalletSubprovider.prototype.finalizeTx = function(txParams, cb) { + const self = this + // can only allow one tx to pass through this flow at a time + // so we can atomically consume a nonce + self.nonceLock.take(function(){ + waterfall([ + self.fillInTxExtras.bind(self, txParams), + self.signTransaction.bind(self), + ], function(err, signedTx){ + self.nonceLock.leave() + if (err) return cb(err) + cb(null, {raw: signedTx, tx: txParams}) + }) + }) + } + + HookedWalletSubprovider.prototype.publishTransaction = function(rawTx, cb) { + const self = this + self.emitPayload({ + method: 'eth_sendRawTransaction', + params: [rawTx], + }, function(err, res){ + if (err) return cb(err) + 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 { + from: txParams.from, + to: txParams.to, + value: txParams.value, + data: txParams.data, + gas: txParams.gas, + gasPrice: txParams.gasPrice, + 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) { + const fixed = ethUtil.addHexPrefix(string) + const isValidAddress = ethUtil.isValidAddress(fixed) + return !isValidAddress && isValidHex(string) + } + + function isValidHex(data) { + const isString = typeof data === 'string' + if (!isString) return false + const isHexPrefixed = data.slice(0,2) === '0x' + if (!isHexPrefixed) return false + const nonPrefixed = data.slice(2) + 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 + const Transaction = require('ethereumjs-tx') + 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() + var cachedResult = self.nonceCache[address] + // only handle requests against the 'pending' blockTag + if (blockTag === 'pending') { + // has a result + if (cachedResult) { + end(null, cachedResult) + // fallthrough then populate cache + } else { + next(function(err, result, cb){ + if (err) return cb() + if (self.nonceCache[address] === undefined) { + self.nonceCache[address] = result + } + cb() + }) + } + } else { + next() + } + return + + case 'eth_sendRawTransaction': + // allow the request to continue normally + next(function(err, result, cb){ + // only update local nonce if tx was submitted correctly + if (err) return cb() + // parse raw tx + var rawTx = payload.params[0] + var stripped = ethUtil.stripHexPrefix(rawTx) + var rawData = new Buffer(ethUtil.stripHexPrefix(rawTx), 'hex') + var tx = new Transaction(new Buffer(ethUtil.stripHexPrefix(rawTx), 'hex')) + // extract address + var address = '0x'+tx.getSenderAddress().toString('hex').toLowerCase() + // extract nonce and increment + var nonce = ethUtil.bufferToInt(tx.nonce) + nonce++ + // hexify and normalize + var hexNonce = nonce.toString(16) + if (hexNonce.length%2) hexNonce = '0'+hexNonce + hexNonce = '0x'+hexNonce + // dont update our record on the nonce until the submit was successful + // update cache + self.nonceCache[address] = hexNonce + 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) + if (response.error) return end(new Error(response.error.message)) + 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', + 'to', + 'value', + 'data', + 'gas', + 'gasPrice', + 'nonce', + 'fromBlock', + 'toBlock', + 'address', + 'topics', + ] + + function cloneTxParams(txParams){ + var sanitized = permitted.reduce(function(copy, permitted) { + if (permitted in txParams) { + if (Array.isArray(txParams[permitted])) { + copy[permitted] = txParams[permitted] + .map(function(item) { + return sanitize(item) + }) + } else { + copy[permitted] = sanitize(txParams[permitted]) + } + } + return copy + }, {}) + + return sanitized + } + + function sanitize(value) { + switch (value) { + case 'latest': + return value + case 'pending': + return value + case 'earliest': + return value + default: + if (typeof value === 'string') { + return ethUtil.addHexPrefix(value.toLowerCase()) + } else { + return value + } + } + } + + },{"./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 + engine.on('block', function(block) { + 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) + } + },{"../util/create-payload.js":391}],388:[function(require,module,exports){ + const EventEmitter = require('events').EventEmitter + const FilterSubprovider = require('./filters.js') + 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': + createSubscriptionFilter = self.newPendingTransactionFilter.bind(self) + break + case 'newHeads': + createSubscriptionFilter = self.newBlockFilter.bind(self) + break + case 'syncing': + default: + 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() + }) + if (subscriptionType === 'newPendingTransactions') { + self.checkForPendingBlocks() + } + cb(null, hexId) + }) + } + + SubscriptionSubprovider.prototype.eth_unsubscribe = function(payload, cb) { + const self = this + let hexId = payload.params[0] + const id = Number.parseInt(hexId, 16) + if (!self.subscriptions[id]) { + cb(new Error(`Subscription ID ${hexId} not found.`)) + } else { + let subscriptionType = self.subscriptions[id] + self.uninstallFilter(hexId, function (err, result) { + delete self.subscriptions[id] + cb(err, result) + }) + } + } + + + 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, { + jsonrpc: "2.0", + method: "eth_subscription", + params: { + subscription: hexId, + result: result, + }, + }) + } + + SubscriptionSubprovider.prototype._notificationResultFromBlock = function(block) { + return { + hash: utils.bufferToHex(block.hash), + parentHash: utils.bufferToHex(block.parentHash), + sha3Uncles: utils.bufferToHex(block.sha3Uncles), + miner: utils.bufferToHex(block.miner), + stateRoot: utils.bufferToHex(block.stateRoot), + transactionsRoot: utils.bufferToHex(block.transactionsRoot), + receiptsRoot: utils.bufferToHex(block.receiptsRoot), + logsBloom: utils.bufferToHex(block.logsBloom), + difficulty: from.intToQuantityHex(utils.bufferToInt(block.difficulty)), + number: from.intToQuantityHex(utils.bufferToInt(block.number)), + gasLimit: from.intToQuantityHex(utils.bufferToInt(block.gasLimit)), + gasUsed: from.intToQuantityHex(utils.bufferToInt(block.gasUsed)), + nonce: block.nonce ? utils.bufferToHex(block.nonce): null, + mixHash: utils.bufferToHex(block.mixHash), + timestamp: from.intToQuantityHex(utils.bufferToInt(block.timestamp)), + extraData: utils.bufferToHex(block.extraData) + } + } + + SubscriptionSubprovider.prototype.handleRequest = function(payload, next, end) { + switch(payload.method){ + case 'eth_subscribe': + this.eth_subscribe(payload, end) + break + case 'eth_unsubscribe': + this.eth_unsubscribe(payload, end) + break + default: + 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') + const EventEmitter = require('events') + const inherits = require('util').inherits + 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({ + randomisationFactor: 0.2, + maxDelay: 5000 + }) + }, + _connectTime: { + value: null, + writable: true + }, + _log: { + value: debug + ? (...args) => console.info.apply(console, ['[WSProvider]', ...args]) + : () => { } + }, + _origin: { + value: origin + }, + _pendingRequests: { + value: new Map() + }, + _socket: { + value: null, + writable: true + }, + _unhandledRequests: { + value: [] + }, + _url: { + 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}) + this._socket.addEventListener('close', this._handleSocketClose) + this._socket.addEventListener('message', this._handleSocketMessage) + 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 + id: getRandomId(), + jsonrpc: '2.0', + params: [], + // 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', + params: [txParams] + }), function(err, res){ + if (err) { + // handle simple value transfer case + if (err.message === 'no contract code at given address') { + return cb(null, '0xcf08') + } else { + return cb(err) + } + } + cb(null, res.result) + }) + } + },{"./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) + // 3 random digits + var extraPart = Math.floor(Math.random()*Math.pow(10, extraDigits)) + // 16 digits + return datePart+extraPart + } + },{}],394:[function(require,module,exports){ + const stringify = require('json-stable-stringify') + + module.exports = { + cacheIdentifierForPayload: cacheIdentifierForPayload, + canCache: canCache, + blockTagForPayload: blockTagForPayload, + paramsWithoutBlockTag: paramsWithoutBlockTag, + 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 + case 'eth_getStorageAt': + return 2 + // blockTag is second param + case 'eth_getBalance': + case 'eth_getCode': + case 'eth_getTransactionCount': + case 'eth_call': + case 'eth_estimateGas': + return 1 + // blockTag is first param + case 'eth_getBlockByNumber': + return 0 + // there is no blockTag + default: + return undefined + } + } + + function cacheTypeForPayload(payload) { + switch (payload.method) { + // cache permanently + case 'web3_clientVersion': + case 'web3_sha3': + case 'eth_protocolVersion': + case 'eth_getBlockTransactionCountByHash': + case 'eth_getUncleCountByBlockHash': + case 'eth_getCode': + case 'eth_getBlockByHash': + case 'eth_getTransactionByHash': + case 'eth_getTransactionByBlockHashAndIndex': + case 'eth_getTransactionReceipt': + case 'eth_getUncleByBlockHashAndIndex': + case 'eth_getCompilers': + case 'eth_compileLLL': + case 'eth_compileSolidity': + case 'eth_compileSerpent': + case 'shh_version': + return 'perma' + + // cache until fork + case 'eth_getBlockByNumber': + case 'eth_getBlockTransactionCountByNumber': + case 'eth_getUncleCountByBlockNumber': + case 'eth_getTransactionByBlockNumberAndIndex': + case 'eth_getUncleByBlockNumberAndIndex': + return 'fork' + + // cache for block + case 'eth_gasPrice': + case 'eth_blockNumber': + case 'eth_getBalance': + case 'eth_getStorageAt': + case 'eth_getTransactionCount': + case 'eth_call': + case 'eth_estimateGas': + case 'eth_getFilterLogs': + case 'eth_getLogs': + case 'net_peerCount': + return 'block' + + // never cache + case 'net_version': + case 'net_peerCount': + case 'net_listening': + case 'eth_syncing': + case 'eth_sign': + case 'eth_coinbase': + case 'eth_mining': + case 'eth_hashrate': + case 'eth_accounts': + case 'eth_sendTransaction': + case 'eth_sendRawTransaction': + case 'eth_newFilter': + case 'eth_newBlockFilter': + case 'eth_newPendingTransactionFilter': + case 'eth_uninstallFilter': + case 'eth_getFilterChanges': + case 'eth_getWork': + case 'eth_submitWork': + case 'eth_submitHashrate': + case 'db_putString': + case 'db_getString': + case 'db_putHex': + case 'db_getHex': + case 'shh_post': + case 'shh_newIdentity': + case 'shh_hasIdentity': + case 'shh_newGroup': + case 'shh_addToGroup': + case 'shh_newFilter': + case 'shh_uninstallFilter': + case 'shh_getFilterChanges': + case 'shh_getMessages': + 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') + if (nHex[0] === '0') { + nHex = nHex.substring(1) + } + return ethUtil.addHexPrefix(nHex) + } + + function quantityHexToInt(prefixedQuantityHex) { + assert(typeof prefixedQuantityHex === 'string', 'arg to quantityHexToInt must be a string') + var quantityHex = ethUtil.stripHexPrefix(prefixedQuantityHex) + var isEven = quantityHex.length % 2 === 0 + if (!isEven) { + quantityHex = '0' + quantityHex + } + 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) { + self.once('unlock', fn) + } else { + setTimeout(fn) + } + } + },{"events":157,"util":333}],397:[function(require,module,exports){ + const ProviderEngine = require('./index.js') + const DefaultFixture = require('./subproviders/default-fixture.js') + const NonceTrackerSubprovider = require('./subproviders/nonce-tracker.js') + const CacheSubprovider = require('./subproviders/cache.js') + const FilterSubprovider = require('./subproviders/filters.js') + const SubscriptionSubprovider = require('./subproviders/subscriptions') + const InflightCacheSubprovider = require('./subproviders/inflight-cache') + const HookedWalletSubprovider = require('./subproviders/hooked-wallet.js') + const SanitizingSubprovider = require('./subproviders/sanitizer.js') + 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') { + const filterSubprovider = new FilterSubprovider() + engine.addProvider(filterSubprovider) + // otherwise, polyfill both subscriptions and filters + } else { + const filterAndSubsSubprovider = new SubscriptionSubprovider() + // forward subscription events through provider + filterAndSubsSubprovider.on('data', (err, notification) => { + engine.emit('data', err, notification) + }) + engine.addProvider(filterAndSubsSubprovider) + } + + // inflight cache + const inflightCache = new InflightCacheSubprovider() + engine.addProvider(inflightCache) + + // id mgmt + const idmgmtSubprovider = new HookedWalletSubprovider({ + // accounts + getAccounts: opts.getAccounts, + // transactions + processTransaction: opts.processTransaction, + approveTransaction: opts.approveTransaction, + signTransaction: opts.signTransaction, + publishTransaction: opts.publishTransaction, + // messages + // old eth_sign + processMessage: opts.processMessage, + approveMessage: opts.approveMessage, + signMessage: opts.signMessage, + // new personal_sign + processPersonalMessage: opts.processPersonalMessage, + processTypedMessage: opts.processTypedMessage, + approvePersonalMessage: opts.approvePersonalMessage, + approveTypedMessage: opts.approveTypedMessage, + signPersonalMessage: opts.signPersonalMessage, + signTypedMessage: opts.signTypedMessage, + personalRecoverSigner: opts.personalRecoverSigner, + }) + engine.addProvider(idmgmtSubprovider) + + // data source + const dataSubprovider = opts.dataSubprovider || createDataSubprovider(connectionType, opts) + // for websockets, forward subscription events through provider + if (connectionType === 'ws') { + dataSubprovider.on('data', (err, notification) => { + engine.emit('data', err, notification) + }) + } + 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() + } + if (connectionType === 'http') { + return new FetchSubprovider({ rpcUrl, debug }) + } + 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': + case 'https': + return 'http' + case 'ws': + case 'wss': + return 'ws' + default: + 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 . + */ + /** @file httpprovider.js + * @authors: + * Marek Kotewicz + * Marian Oancea + * 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 + */ + var HttpProvider = function HttpProvider(host, options) { + options = options || {}; + this.host = host || 'http://localhost:8545'; + if (this.host.substring(0,5) === "https"){ + this.httpsAgent = new https.Agent({ keepAlive: true }); + }else{ + this.httpAgent = new http.Agent({ keepAlive: true }); + } + this.timeout = options.timeout || 0; + 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 + * + * @method send + * @param {Object} payload + * @param {Function} callback triggered on end with (err, result) + */ + 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) { + this.connected = false; + 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 . + */ + /** @file index.js + * @authors: + * 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){ + if(_this.responseCallbacks[load.id]) + id = load.id; + }); + } 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) + .done(callback); + } else { + this.connection.on('data', function(data){ + _this._parseResponse(data.toString()).forEach(callback); + }); + } + }; + + /** + 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,'}|--|{') // }{ + .replace(/\}\][\n\r]?\[\{/g,'}]|--|[{') // }][{ + .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() { + for(var key in this.responseCallbacks) { + if(this.responseCallbacks.hasOwnProperty(key)){ + this.responseCallbacks[key](errors.InvalidConnection('on IPC')); + delete this.responseCallbacks[key]; + } + } + }; + + /** + 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){ + if(cb === callback) + _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' + */ + IpcProvider.prototype.removeAllListeners = function (type) { + switch(type){ + 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 . + */ + /** @file WebsocketProvider.js + * @authors: + * 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; + if (typeof window !== 'undefined' && typeof window.WebSocket !== 'undefined') { + Ws = function(url, protocols) { + return new window.WebSocket(url, protocols); + }; + _btoa = btoa; + parseURL = function(url) { + return new URL(url); + }; + } else { + Ws = require('websocket').w3cwebsocket; + _btoa = function(str) { + return Buffer(str).toString('base64'); + }; + var url = require('url'); + if (url.URL) { + // Use the new Node 6+ API for parsing URLs that supports username/password + var newURL = url.URL; + parseURL = function(url) { + return new newURL(url); + }; + } + else { + // Web3 supports Node.js 5, so fall back to the legacy URL API if necessary + parseURL = require('url').parse; + } + } + // 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 + var parsedURL = parseURL(url); + var headers = options.headers || {}; + var protocol = options.protocol || undefined; + 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){ + if(_this.responseCallbacks[load.id]) + id = load.id; + }); + } 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); + delete _this.responseCallbacks[id]; + } + }); + }; + + // make property `connected` which will return the current connection status + Object.defineProperty(this, 'connected', { + get: function () { + return this.connection && this.connection.readyState === this.connection.OPEN; + }, + 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,'}|--|{') // }{ + .replace(/\}\][\n\r]?\[\{/g,'}]|--|[{') // }][{ + .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 () { + if (_this.responseCallbacks[id]) { + _this.responseCallbacks[id](errors.ConnectionTimeout(_this._customTimeout)); + delete _this.responseCallbacks[id]; + } + }, this._customTimeout); + } + }; + + /** + Timeout all requests when the end/error event is fired + + @method _timeout + */ + WebsocketProvider.prototype._timeout = function() { + for(var key in this.responseCallbacks) { + if(this.responseCallbacks.hasOwnProperty(key)){ + this.responseCallbacks[key](errors.InvalidConnection('on WS')); + delete this.responseCallbacks[key]; + } + } + }; + + + 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}); + if (this.connection.readyState !== this.connection.OPEN) { + console.error('connection not open on send()'); + if (typeof this.connection.onerror === 'function') { + this.connection.onerror(new Error('connection not open')); + } else { + console.error('no error callback'); + } + 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){ + if(cb === callback) + _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' + */ + WebsocketProvider.prototype.removeAllListeners = function (type) { + switch(type){ + 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 . + */ + /** + * @file index.js + * @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', + type: 'shh', + subscriptions: { + 'messages': { + params: 1 + // inputFormatter: [formatters.inputPostFormatter], + // outputFormatter: formatters.outputPostFormatter + } + } + }), + + new Method({ + name: 'getVersion', + call: 'shh_version', + params: 0 + }), + new Method({ + name: 'getInfo', + call: 'shh_info', + params: 0 + }), + new Method({ + name: 'setMaxMessageSize', + call: 'shh_setMaxMessageSize', + params: 1 + }), + new Method({ + name: 'setMinPoW', + call: 'shh_setMinPoW', + params: 1 + }), + new Method({ + name: 'markTrustedPeer', + call: 'shh_markTrustedPeer', + params: 1 + }), + new Method({ + name: 'newKeyPair', + call: 'shh_newKeyPair', + params: 0 + }), + new Method({ + name: 'addPrivateKey', + call: 'shh_addPrivateKey', + params: 1 + }), + new Method({ + name: 'deleteKeyPair', + call: 'shh_deleteKeyPair', + params: 1 + }), + new Method({ + name: 'hasKeyPair', + call: 'shh_hasKeyPair', + params: 1 + }), + new Method({ + name: 'getPublicKey', + call: 'shh_getPublicKey', + params: 1 + }), + new Method({ + name: 'getPrivateKey', + call: 'shh_getPrivateKey', + params: 1 + }), + new Method({ + name: 'newSymKey', + call: 'shh_newSymKey', + params: 0 + }), + new Method({ + name: 'addSymKey', + call: 'shh_addSymKey', + params: 1 + }), + new Method({ + name: 'generateSymKeyFromPassword', + call: 'shh_generateSymKeyFromPassword', + params: 1 + }), + new Method({ + name: 'hasSymKey', + call: 'shh_hasSymKey', + params: 1 + }), + new Method({ + name: 'getSymKey', + call: 'shh_getSymKey', + params: 1 + }), + new Method({ + name: 'deleteSymKey', + call: 'shh_deleteSymKey', + params: 1 + }), + + new Method({ + name: 'newMessageFilter', + call: 'shh_newMessageFilter', + params: 1 + }), + new Method({ + name: 'getFilterMessages', + call: 'shh_getFilterMessages', + params: 1 + }), + new Method({ + name: 'deleteMessageFilter', + call: 'shh_deleteMessageFilter', + params: 1 + }), + + new Method({ + name: 'post', + call: 'shh_post', + params: 1, + inputFormatter: [null] + }), + + new Method({ + name: 'unsubscribe', + call: 'shh_unsubscribe', + params: 1 + }) + ].forEach(function(method) { + method.attachToObject(_this); + 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 . + */ + /** + * @file utils.js + * @author Marek Kotewicz + * @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 + * + * @method _fireError + * @param {Object} error a string, a error, or an object with {message, data} + * @param {Object} emitter + * @param {Function} reject + * @param {Function} callback + * @return {Object} the emitter + */ + 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); + } + if (_.isFunction(reject)) { + // suppress uncatched error if an error listener is present + // OR suppress uncatched error if an callback listener is present + if (emitter && + (_.isFunction(emitter.listeners) && + emitter.listeners('error').length) || _.isFunction(callback)) { + emitter.catch(function(){}); + } + // reject later, to be able to return emitter + setTimeout(function () { + reject(error); + }, 1); + } + + if(emitter && _.isFunction(emitter.emit)) { + // emit later, to be able to return emitter + setTimeout(function () { + emitter.emit('error', error); + emitter.removeAllListeners(); + }, 1); + } + + return emitter; + }; + + /** + * Should be used to create full function/event name from json abi + * + * @method _jsonInterfaceMethodToString + * @param {Object} json + * @return {String} full function/event name + */ + var _jsonInterfaceMethodToString = function (json) { + 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 + * + * @method _flattenTypes + * @param {bool} includeTuple + * @param {Object} puts + * @return {Array} parameters as strings + */ + var _flattenTypes = function(includeTuple, puts) + { + // 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') { + throw new Error('components found but type is not tuple; report on GitHub'); + } + var suffix = ''; + var arrayBracket = param.type.indexOf('['); + if (arrayBracket >= 0) { suffix = param.type.substring(arrayBracket); } + var result = _flattenTypes(includeTuple, param.components); + // console.log("result should have things: " + result) + if(_.isArray(result) && includeTuple) { + // console.log("include tuple word, and its an array. joining...: " + result.types) + types.push('tuple(' + result.join(',') + ')' + suffix); + } + else if(!includeTuple) { + // console.log("don't include tuple, but its an array. joining...: " + result) + types.push('(' + result.join(',') + ')' + suffix); + } + else { + // console.log("its a single type within a tuple: " + result.types) + types.push('(' + result + ')'); + } + } else { + // console.log("its a type and not directly in a tuple: " + param.type) + types.push(param.type); + } + }); + + return types; + }; + + + /** + * Should be called to get ascii from it's hex representation + * + * @method hexToAscii + * @param {String} hex + * @returns {String} ascii string representation of hex value + */ + 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') { + 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 ascii string + * + * @method asciiToHex + * @param {String} str + * @returns {String} hex representation of input string + */ + var asciiToHex = function(str) { + if(!str) + return "0x00"; + var hex = ""; + for(var i = 0; i < str.length; i++) { + var code = str.charCodeAt(i); + var n = code.toString(16); + hex += n.length < 2 ? '0' + n : n; + } + + return "0x" + hex; + }; + + + + /** + * Returns value of unit in Wei + * + * @method getUnitValue + * @param {String} unit the unit to convert to, default ether + * @returns {BN} value of the unit (in Wei) + * @throws error if the unit is not correct:w + */ + var getUnitValue = function (unit) { + unit = unit ? unit.toLowerCase() : 'ether'; + if (!ethjsUnit.unitMap[unit]) { + throw new Error('This unit "'+ unit +'" doesn\'t exist, please use the one of the following units' + JSON.stringify(ethjsUnit.unitMap, null, 2)); + } + return unit; + }; + + /** + * Takes a number of wei and converts it to any other ether unit. + * + * Possible units are: + * SI Short SI Full Effigy Other + * - kwei femtoether babbage + * - mwei picoether lovelace + * - gwei nanoether shannon nano + * - -- microether szabo micro + * - -- milliether finney milli + * - ether -- -- + * - kether -- grand + * - mether + * - gether + * - tether + * + * @method fromWei + * @param {Number|String} number can be a number, number string or a HEX of a decimal + * @param {String} unit the unit to convert to, default ether + * @return {String|Object} When given a BN object it returns one as well, otherwise a number + */ + 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. + * + * Possible units are: + * SI Short SI Full Effigy Other + * - kwei femtoether babbage + * - mwei picoether lovelace + * - gwei nanoether shannon nano + * - -- microether szabo micro + * - -- microether szabo micro + * - -- milliether finney milli + * - ether -- -- + * - kether -- grand + * - mether + * - gether + * - tether + * + * @method toWei + * @param {Number|String|BN} number can be a number, number string or a HEX of a decimal + * @param {String} unit the unit to convert from, default ether + * @return {String|Object} When given a BN object it returns one as well, otherwise a number + */ + 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 + * + * @method toChecksumAddress + * @param {String} address the given HEX address + * @return {String} + */ + 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) { + checksumAddress += address[i].toUpperCase(); + } else { + checksumAddress += address[i]; + } + } + return checksumAddress; + }; + + + + module.exports = { + _fireError: _fireError, + _jsonInterfaceMethodToString: _jsonInterfaceMethodToString, + _flattenTypes: _flattenTypes, + // extractDisplayName: extractDisplayName, + // extractTypeName: extractTypeName, + randomHex: randomHex, + _: _, + BN: utils.BN, + isBN: utils.isBN, + isBigNumber: utils.isBigNumber, + isHex: utils.isHex, + isHexStrict: utils.isHexStrict, + sha3: utils.sha3, + keccak256: utils.sha3, + soliditySha3: soliditySha3, + isAddress: utils.isAddress, + checkAddressChecksum: utils.checkAddressChecksum, + 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 . + */ + /** + * @file soliditySha3.js + * @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') { + return 'int256'; + } else if (name.startsWith('uint[')) { + return 'uint256' + name.slice(4); + } else if (name === 'uint') { + return 'uint256'; + } else if (name.startsWith('fixed[')) { + return 'fixed128x128' + name.slice(5); + } else if (name === 'fixed') { + return 'fixed128x128'; + } else if (name.startsWith('ufixed[')) { + return 'ufixed128x128' + name.slice(6); + } else if (name === 'ufixed') { + return 'ufixed128x128'; + } + 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') { + if (utils.isHexStrict(arg)) { + return new BN(arg.replace(/0x/i,''), 16); + } else { + return new BN(arg, 10); + } + } else if (type === 'number') { + return new BN(arg); + } else if (utils.isBigNumber(arg)) { + return new BN(arg.toString(10)); + } else if (utils.isBN(arg)) { + return arg; + } else { + 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); + } else if (type === 'bool') { + return value ? '01' : '00'; + } else if (type.startsWith('address')) { + if(arraySize) { + size = 64; + } 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); + if(arraySize && value.length !== arraySize) { + throw new Error(type +' is not matching the given array '+ JSON.stringify(value)); + } else { + arraySize = value.length; + } + } + + + if (_.isArray(value)) { + hexArg = value.map(function (val) { + return _solidityPack(type, val, arraySize).toString('hex').replace('0x',''); + }); + return hexArg.join(''); + } else { + hexArg = _solidityPack(type, value, arraySize); + return hexArg.toString('hex').replace('0x',''); + } + + }; + + /** + * Hashes solidity values to a sha3 hash using keccak 256 + * + * @method soliditySha3 + * @return {Object} the sha3 + */ + 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 . + */ + /** + * @file utils.js + * @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 + * + * @method isBN + * @param {Object} object + * @return {Boolean} + */ + var isBN = function (object) { + return object instanceof BN || + (object && object.constructor && object.constructor.name === 'BN'); + }; + + /** + * Returns true if object is BigNumber, otherwise false + * + * @method isBigNumber + * @param {Object} object + * @return {Boolean} + */ + var isBigNumber = function (object) { + return object && object.constructor && object.constructor.name === 'BigNumber'; + }; + + /** + * Takes an input and transforms it into an BN + * + * @method toBN + * @param {Number|String|BN} number, string, HEX string or BN + * @return {BN} BN + */ + var toBN = function(number){ + try { + return numberToBN.apply(null, arguments); + } catch(e) { + throw new Error(e + ' Given value: "'+ number +'"'); + } + }; + + + /** + * Takes and input transforms it into BN and if it is negative value, into two's complement + * + * @method toTwosComplement + * @param {Number|String|BN} number + * @return {String} + */ + var toTwosComplement = function (number) { + return '0x'+ toBN(number).toTwos(256).toString(16, 64); + }; + + /** + * Checks if the given string is an address + * + * @method isAddress + * @param {String} address the given HEX address + * @return {Boolean} + */ + var isAddress = function (address) { + // check if it has the basic requirements of an address + if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) { + return false; + // If it's ALL lowercase or ALL upppercase + } else if (/^(0x|0X)?[0-9a-f]{40}$/.test(address) || /^(0x|0X)?[0-9A-F]{40}$/.test(address)) { + return true; + // Otherwise check each case + } else { + return checkAddressChecksum(address); + } + }; + + + + /** + * Checks if the given string is a checksummed address + * + * @method checkAddressChecksum + * @param {String} address the given HEX address + * @return {Boolean} + */ + var checkAddressChecksum = function (address) { + // 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])) { + return false; + } + } + return true; + }; + + /** + * Should be called to pad string to expected length + * + * @method leftPad + * @param {String} string to be padded + * @param {Number} chars that result string should have + * @param {String} sign, by default 0 + * @returns {String} right aligned string + */ + 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 + * + * @method rightPad + * @param {String} string to be padded + * @param {Number} chars that result string should have + * @param {String} sign, by default 0 + * @returns {String} right aligned string + */ + 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 + * + * @method utf8ToHex + * @param {String} str + * @returns {String} hex representation of input string + */ + 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) { + var n = code.toString(16); + hex += n.length < 2 ? '0' + n : n; + // } + } + + return "0x" + hex; + }; + + /** + * Should be called to get utf8 from it's hex representation + * + * @method hexToUtf8 + * @param {String} hex + * @returns {String} ascii string representation of hex value + */ + 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 + * + * @method hexToNumber + * @param {String|Number|BN} value + * @return {String} + */ + var hexToNumber = function (value) { + if (!value) { + return value; + } + + return toBN(value).toNumber(); + }; + + /** + * Converts value to it's decimal representation in string + * + * @method hexToNumberString + * @param {String|Number|BN} value + * @return {String} + */ + var hexToNumberString = function (value) { + if (!value) return value; + + return toBN(value).toString(10); + }; + + + /** + * Converts value to it's hex representation + * + * @method numberToHex + * @param {String|Number|BN} value + * @return {String} + */ + var numberToHex = function (value) { + 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 + * + * Note: Implementation from crypto-js + * + * @method bytesToHex + * @param {Array} bytes + * @return {String} the hex string + */ + var bytesToHex = function(bytes) { + for (var hex = [], i = 0; i < bytes.length; i++) { + /* jshint ignore:start */ + hex.push((bytes[i] >>> 4).toString(16)); + hex.push((bytes[i] & 0xF).toString(16)); + /* jshint ignore:end */ + } + return '0x'+ hex.join(""); + }; + + /** + * Convert a hex string to a byte array + * + * Note: Implementation from crypto-js + * + * @method hexToBytes + * @param {string} hex + * @return {Array} the byte array + */ + 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. + * + * And even stringifys objects before. + * + * @method toHex + * @param {String|Number|BN|Object} value + * @param {Boolean} returnType + * @return {String} + */ + 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) { + return returnType ? 'int256' : numberToHex(value); + } else if(value.indexOf('0x') === 0 || value.indexOf('0X') === 0) { + return returnType ? 'bytes' : value; + } else if (!isFinite(value)) { + return returnType ? 'string' : utf8ToHex(value); + } + } + + return returnType ? (value < 0 ? 'int256' : 'uint256') : numberToHex(value); + }; + + + /** + * Check if string is HEX, requires a 0x in front + * + * @method isHexStrict + * @param {String} hex to be checked + * @returns {Boolean} + */ + var isHexStrict = function (hex) { + return ((_.isString(hex) || _.isNumber(hex)) && /^(-)?0x[0-9a-f]*$/i.test(hex)); + }; + + /** + * Check if string is HEX + * + * @method isHex + * @param {String} hex to be checked + * @returns {Boolean} + */ + 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. + * + * TODO UNDOCUMENTED + * + * @method isBloom + * @param {String} hex encoded bloom filter + * @return {Boolean} + */ + var isBloom = function (bloom) { + if (!/^(0x)?[0-9a-f]{512}$/i.test(bloom)) { + return false; + } else if (/^(0x)?[0-9a-f]{512}$/.test(bloom) || /^(0x)?[0-9A-F]{512}$/.test(bloom)) { + return true; + } + return false; + }; + + /** + * Returns true if given string is a valid log topic. + * + * TODO UNDOCUMENTED + * + * @method isTopic + * @param {String} hex encoded topic + * @return {Boolean} + */ + var isTopic = function (topic) { + if (!/^(0x)?[0-9a-f]{64}$/i.test(topic)) { + return false; + } else if (/^(0x)?[0-9a-f]{64}$/.test(topic) || /^(0x)?[0-9A-F]{64}$/.test(topic)) { + return true; + } + return false; + }; + + + /** + * Hashes values to a sha3 hash using keccak 256 + * + * To hash a HEX string the hex must have 0x in front. + * + * @method sha3 + * @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 { + return returnValue; + } + }; + // expose the under the hood keccak256 + sha3._Hash = Hash; + + + module.exports = { + BN: BN, + isBN: isBN, + isBigNumber: isBigNumber, + toBN: toBN, + isAddress: isAddress, + isBloom: isBloom, // TODO UNDOCUMENTED + isTopic: isTopic, // TODO UNDOCUMENTED + checkAddressChecksum: checkAddressChecksum, + utf8ToHex: utf8ToHex, + hexToUtf8: hexToUtf8, + hexToNumber: hexToNumber, + hexToNumberString: hexToNumberString, + numberToHex: numberToHex, + toHex: toHex, + hexToBytes: hexToBytes, + bytesToHex: bytesToHex, + isHex: isHex, + isHexStrict: isHexStrict, + leftPad: leftPad, + rightPad: rightPad, + 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", + "_id": "web3@1.0.0-beta.36", + "_inBundle": false, + "_integrity": "sha512-fZDunw1V0AQS27r5pUN3eOVP7u8YAvyo6vOapdgVRolAu5LgaweP7jncYyLINqIX9ZgWdS5A090bt+ymgaYHsw==", + "_location": "/web3", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "web3@1.0.0-beta.36", + "name": "web3", + "escapedName": "web3", + "rawSpec": "1.0.0-beta.36", + "saveSpec": null, + "fetchSpec": "1.0.0-beta.36" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/web3/-/web3-1.0.0-beta.36.tgz", + "_shasum": "2954da9e431124c88396025510d840ba731c8373", + "_spec": "web3@1.0.0-beta.36", + "_where": "/Users/alexvlasov/Blockchain/web3swift/web3swiftJSProxy", + "author": { + "name": "ethereum.org" + }, + "authors": [ + { + "name": "Fabian Vogelsteller", + "email": "fabian@ethereum.org", + "homepage": "http://frozeman.de" + }, + { + "name": "Marek Kotewicz", + "email": "marek@parity.io", + "url": "https://github.com/debris" + }, + { + "name": "Marian Oancea", + "url": "https://github.com/cubedro" + }, + { + "name": "Gav Wood", + "email": "g@parity.io", + "homepage": "http://gavwood.com" + }, + { + "name": "Jeffery Wilcke", + "email": "jeffrey.wilcke@ethereum.org", + "url": "https://github.com/obscuren" + } + ], + "bugs": { + "url": "https://github.com/ethereum/web3.js/issues" + }, + "bundleDependencies": false, + "dependencies": { + "web3-bzz": "1.0.0-beta.36", + "web3-core": "1.0.0-beta.36", + "web3-eth": "1.0.0-beta.36", + "web3-eth-personal": "1.0.0-beta.36", + "web3-net": "1.0.0-beta.36", + "web3-shh": "1.0.0-beta.36", + "web3-utils": "1.0.0-beta.36" + }, + "deprecated": false, + "description": "Ethereum JavaScript API", + "keywords": [ + "Ethereum", + "JavaScript", + "API" + ], + "license": "LGPL-3.0", + "main": "src/index.js", + "name": "web3", + "namespace": "ethereum", + "repository": { + "type": "git", + "url": "https://github.com/ethereum/web3.js/tree/master/packages/web3" + }, + "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 . + */ + /** + * @file index.js + * @authors: + * Fabian Vogelsteller + * Gav Wood + * Jeffrey Wilcke + * Marek Kotewicz + * Marian Oancea + * @date 2017 + */ + + "use strict"; + + + var version = require('../package.json').version; + var core = require('web3-core'); + var Eth = require('web3-eth'); + var Net = require('web3-net'); + var Personal = require('web3-eth-personal'); + 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 = { + Eth: Eth, + Net: Net, + Personal: Personal, + 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 + * instance of W3CWebSocket via 'new W3CWebSocket()'. + * + * ECMAScript 5: http://bclary.com/2004/11/07/#a-13.2.2 + */ + return native_instance; + } + if (NativeWebSocket) { + ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'].forEach(function(prop) { + Object.defineProperty(W3CWebSocket, prop, { + get: function() { return NativeWebSocket[prop]; } + }); + }); + } + + /** + * Module exports. + */ + module.exports = { + '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", + "_id": "websocket@1.0.26", + "_inBundle": false, + "_integrity": "", + "_location": "/websocket", + "_phantomChildren": {}, + "_requested": { + "type": "git", + "raw": "websocket@git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible", + "name": "websocket", + "escapedName": "websocket", + "rawSpec": "git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible", + "saveSpec": "git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible", + "fetchSpec": "git://github.com/frozeman/WebSocket-Node.git", + "gitCommittish": "browserifyCompatible" + }, + "_requiredBy": [ + "/web3-providers-ws" + ], + "_resolved": "git://github.com/frozeman/WebSocket-Node.git#6c72925e3f8aaaea8dc8450f97627e85263999f2", + "_spec": "websocket@git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible", + "_where": "/Users/alexvlasov/Blockchain/web3swift/web3swiftJSProxy/node_modules/web3-providers-ws", + "author": { + "name": "Brian McKelvey", + "email": "brian@worlize.com", + "url": "https://www.worlize.com/" + }, + "browser": "lib/browser.js", + "bugs": { + "url": "https://github.com/theturtle32/WebSocket-Node/issues" + }, + "bundleDependencies": false, + "config": { + "verbose": false + }, + "contributors": [ + { + "name": "Iñaki Baz Castillo", + "email": "ibc@aliax.net", + "url": "http://dev.sipdoc.net" + } + ], + "dependencies": { + "debug": "^2.2.0", + "nan": "^2.3.3", + "typedarray-to-buffer": "^3.1.2", + "yaeti": "^0.0.6" + }, + "deprecated": false, + "description": "Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.", + "devDependencies": { + "buffer-equal": "^1.0.0", + "faucet": "^0.0.1", + "gulp": "git+https://github.com/gulpjs/gulp.git#4.0", + "gulp-jshint": "^2.0.4", + "jshint": "^2.0.0", + "jshint-stylish": "^2.2.1", + "tape": "^4.0.1" + }, + "directories": { + "lib": "./lib" + }, + "engines": { + "node": ">=0.10.0" + }, + "homepage": "https://github.com/theturtle32/WebSocket-Node", + "keywords": [ + "websocket", + "websockets", + "socket", + "networking", + "comet", + "push", + "RFC-6455", + "realtime", + "server", + "client" + ], + "license": "Apache-2.0", + "main": "index", + "name": "websocket", + "repository": { + "type": "git", + "url": "git+https://github.com/theturtle32/WebSocket-Node.git" + }, + "scripts": { + "gulp": "gulp", + "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", + "test": "faucet test/unit" + }, + "version": "1.0.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) { + if (err) reject(err); + else resolve(data); + }); + }); + }; + + },{"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') { + throw new TypeError('must specify a URL') + } + if (typeof opt === 'function') { + cb = opt + opt = {} + } + 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 + if (query) { + if (typeof query !== 'string') { + query = queryString.stringify(query) + } + 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) { + var lower = key.toLowerCase() + if (!headers[key] && !headers[lower]) { + headers[key] = value + } + } + + },{}],414:[function(require,module,exports){ + module.exports = getResponse + function getResponse (opt, resp) { + if (!resp) return null + return { + statusCode: resp.statusCode, + headers: resp.headers, + method: opt.method, + url: opt.url, + // the XHR object in browser, http response in Node + 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 { + var text = resp.rawRequest.responseText + body = JSON.parse(text) + } catch (e) { + 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 () { + var ret = onabort.apply(req, Array.prototype.slice.call(arguments)) + cb(new Error('XHR Aborted')) + 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) + options.method = method.toUpperCase() + 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") { + params = {uri:uri} + } + } 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){ + called = true + 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)){ + evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") ) + } + evt.statusCode = 0 + return callback(evt, failureResponse) + } + + // will load the data & process the response in a special response object + function loadFunc() { + if (aborted) return + var status + clearTimeout(timeoutTimer) + if(options.useXDR && xhr.status===undefined) { + //IE8 CORS GET successful response doesn't have a status field, but body is fine + status = 200 + } else { + status = (xhr.status === 1223 ? 204 : xhr.status) + } + var response = failureResponse + var err = null + + if (status !== 0){ + response = { + body: getBody(), + statusCode: status, + method: method, + headers: {}, + url: uri, + rawRequest: xhr + } + if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE + response.headers = parseHeaders(xhr.getAllResponseHeaders()) + } + } else { + err = new Error("Internal XMLHttpRequest Error") + } + return callback(err, response, response.body) + } + + var xhr = options.xhr || null + + if (!xhr) { + if (options.cors || options.useXDR) { + xhr = new createXHR.XDomainRequest() + }else{ + xhr = new createXHR.XMLHttpRequest() + } + } + + var key + var aborted + var uri = xhr.url = options.uri || options.url + var method = xhr.method = options.method || "GET" + var body = options.body || options.data + var headers = xhr.headers = options.headers || {} + var sync = !!options.sync + var isJson = false + var timeoutTimer + var failureResponse = { + body: undefined, + headers: {}, + statusCode: 0, + method: method, + 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 + if (method !== "GET" && method !== "HEAD") { + headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user + body = JSON.stringify(options.json === true ? body : options.json) + } + } + + xhr.onreadystatechange = readystatechange + xhr.onload = loadFunc + xhr.onerror = errorFunc + // IE9 must have onprogress be set to a unique function. + xhr.onprogress = function () { + // IE must die + } + xhr.onabort = function(){ + aborted = true; + } + xhr.ontimeout = errorFunc + xhr.open(method, uri, !sync, options.username, options.password) + //has to be after open + if(!sync) { + xhr.withCredentials = !!options.withCredentials + } + // Cannot set timeout with sync request + // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly + // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent + if (!sync && options.timeout > 0 ) { + timeoutTimer = setTimeout(function(){ + if (aborted) return + aborted = true//IE9 may still call readystatechange + xhr.abort("timeout") + var e = new Error("XMLHttpRequest timeout") + e.code = "ETIMEDOUT" + errorFunc(e) + }, options.timeout ) + } + + if (xhr.setRequestHeader) { + for(key in headers){ + if(headers.hasOwnProperty(key)){ + xhr.setRequestHeader(key, headers[key]) + } + } + } 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. + try { + if (xhr.responseType === "document") { + return xhr.responseXML + } + var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror" + if (xhr.responseType === "" && !firefoxBugTakenEffect) { + 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 () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + var SecurityError = /** @class */ (function (_super) { + __extends(SecurityError, _super); + function SecurityError() { + return _super !== null && _super.apply(this, arguments) || this; + } + return SecurityError; + }(Error)); + exports.SecurityError = SecurityError; + var InvalidStateError = /** @class */ (function (_super) { + __extends(InvalidStateError, _super); + function InvalidStateError() { + return _super !== null && _super.apply(this, arguments) || this; + } + return InvalidStateError; + }(Error)); + exports.InvalidStateError = InvalidStateError; + var NetworkError = /** @class */ (function (_super) { + __extends(NetworkError, _super); + function NetworkError() { + return _super !== null && _super.apply(this, arguments) || this; + } + return NetworkError; + }(Error)); + exports.NetworkError = NetworkError; + var SyntaxError = /** @class */ (function (_super) { + __extends(SyntaxError, _super); + function SyntaxError() { + return _super !== null && _super.apply(this, arguments) || this; + } + return SyntaxError; + }(Error)); + exports.SyntaxError = SyntaxError; + + },{}],418:[function(require,module,exports){ + "use strict"; + function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; + } + Object.defineProperty(exports, "__esModule", { value: true }); + __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 }); + var ProgressEvent = /** @class */ (function () { + function ProgressEvent(type) { + this.type = type; + this.bubbles = false; + this.cancelable = false; + this.loaded = 0; + this.lengthComputable = false; + this.total = 0; + } + return ProgressEvent; + }()); + exports.ProgressEvent = ProgressEvent; + + },{}],420:[function(require,module,exports){ + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var XMLHttpRequestEventTarget = /** @class */ (function () { + function XMLHttpRequestEventTarget() { + this.listeners = {}; + } + XMLHttpRequestEventTarget.prototype.addEventListener = function (eventType, listener) { + eventType = eventType.toLowerCase(); + this.listeners[eventType] = this.listeners[eventType] || []; + this.listeners[eventType].push(listener.handleEvent || listener); + }; + XMLHttpRequestEventTarget.prototype.removeEventListener = function (eventType, listener) { + eventType = eventType.toLowerCase(); + if (!this.listeners[eventType]) { + return; + } + var index = this.listeners[eventType].indexOf(listener.handleEvent || listener); + if (index < 0) { + return; + } + this.listeners[eventType].splice(index, 1); + }; + XMLHttpRequestEventTarget.prototype.dispatchEvent = function (event) { + var eventType = event.type.toLowerCase(); + event.target = this; // TODO: set event.currentTarget? + if (this.listeners[eventType]) { + for (var _i = 0, _a = this.listeners[eventType]; _i < _a.length; _i++) { + var listener_1 = _a[_i]; + listener_1.call(this, event); + } + } + var listener = this["on" + eventType]; + if (listener) { + listener.call(this, event); + } + return true; + }; + return XMLHttpRequestEventTarget; + }()); + exports.XMLHttpRequestEventTarget = XMLHttpRequestEventTarget; + + },{}],421:[function(require,module,exports){ + (function (Buffer){ + "use strict"; + var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + var xml_http_request_event_target_1 = require("./xml-http-request-event-target"); + var XMLHttpRequestUpload = /** @class */ (function (_super) { + __extends(XMLHttpRequestUpload, _super); + function XMLHttpRequestUpload() { + var _this = _super.call(this) || this; + _this._contentType = null; + _this._body = null; + _this._reset(); + return _this; + } + XMLHttpRequestUpload.prototype._reset = function () { + this._contentType = null; + this._body = null; + }; + XMLHttpRequestUpload.prototype._setData = function (data) { + if (data == null) { + return; + } + if (typeof data === 'string') { + if (data.length !== 0) { + this._contentType = 'text/plain;charset=UTF-8'; + } + this._body = new Buffer(data, 'utf-8'); + } + else if (Buffer.isBuffer(data)) { + this._body = data; + } + else if (data instanceof ArrayBuffer) { + var body = new Buffer(data.byteLength); + var view = new Uint8Array(data); + for (var i = 0; i < data.byteLength; i++) { + body[i] = view[i]; + } + this._body = body; + } + else if (data.buffer && data.buffer instanceof ArrayBuffer) { + var body = new Buffer(data.byteLength); + var offset = data.byteOffset; + var view = new Uint8Array(data.buffer); + for (var i = 0; i < data.byteLength; i++) { + body[i] = view[i + offset]; + } + this._body = body; + } + else { + throw new Error("Unsupported send() data " + data); + } + }; + XMLHttpRequestUpload.prototype._finalizeHeaders = function (headers, loweredHeaders) { + if (this._contentType && !loweredHeaders['content-type']) { + headers['Content-Type'] = this._contentType; + } + if (this._body) { + headers['Content-Length'] = this._body.length.toString(); + } + }; + XMLHttpRequestUpload.prototype._startUpload = function (request) { + if (this._body) { + request.write(this._body); + } + request.end(); + }; + 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){ + "use strict"; + var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + var http = require("http"); + var https = require("https"); + var os = require("os"); + var url = require("url"); + var progress_event_1 = require("./progress-event"); + var errors_1 = require("./errors"); + var xml_http_request_event_target_1 = require("./xml-http-request-event-target"); + var xml_http_request_upload_1 = require("./xml-http-request-upload"); + var Cookie = require("cookiejar"); + var XMLHttpRequest = /** @class */ (function (_super) { + __extends(XMLHttpRequest, _super); + function XMLHttpRequest(options) { + if (options === void 0) { options = {}; } + var _this = _super.call(this) || this; + _this.UNSENT = XMLHttpRequest.UNSENT; + _this.OPENED = XMLHttpRequest.OPENED; + _this.HEADERS_RECEIVED = XMLHttpRequest.HEADERS_RECEIVED; + _this.LOADING = XMLHttpRequest.LOADING; + _this.DONE = XMLHttpRequest.DONE; + _this.onreadystatechange = null; + _this.readyState = XMLHttpRequest.UNSENT; + _this.response = null; + _this.responseText = ''; + _this.responseType = ''; + _this.status = 0; // TODO: UNSENT? + _this.statusText = ''; + _this.timeout = 0; + _this.upload = new xml_http_request_upload_1.XMLHttpRequestUpload(); + _this.responseUrl = ''; + _this.withCredentials = false; + _this._method = null; + _this._url = null; + _this._sync = false; + _this._headers = {}; + _this._loweredHeaders = {}; + _this._mimeOverride = null; // TODO: is type right? + _this._request = null; + _this._response = null; + _this._responseParts = null; + _this._responseHeaders = null; + _this._aborting = null; // TODO: type? + _this._error = null; // TODO: type? + _this._loadedBytes = 0; + _this._totalBytes = 0; + _this._lengthComputable = false; + _this._restrictedMethods = { CONNECT: true, TRACE: true, TRACK: true }; + _this._restrictedHeaders = { + 'accept-charset': true, + 'accept-encoding': true, + 'access-control-request-headers': true, + 'access-control-request-method': true, + connection: true, + 'content-length': true, + cookie: true, + cookie2: true, + date: true, + dnt: true, + expect: true, + host: true, + 'keep-alive': true, + origin: true, + referer: true, + te: true, + trailer: true, + 'transfer-encoding': true, + upgrade: true, + 'user-agent': true, + via: true + }; + _this._privateHeaders = { 'set-cookie': true, 'set-cookie2': true }; + _this._userAgent = "Mozilla/5.0 (" + os.type() + " " + os.arch() + ") node.js/" + process.versions.node + " v8/" + process.versions.v8; + _this._anonymous = options.anon || false; + return _this; + } + XMLHttpRequest.prototype.open = function (method, url, async, user, password) { + if (async === void 0) { async = true; } + method = method.toUpperCase(); + if (this._restrictedMethods[method]) { + throw new XMLHttpRequest.SecurityError("HTTP method " + method + " is not allowed in XHR"); + } + ; + var xhrUrl = this._parseUrl(url, user, password); + if (this.readyState === XMLHttpRequest.HEADERS_RECEIVED || this.readyState === XMLHttpRequest.LOADING) { + // TODO(pwnall): terminate abort(), terminate send() + } + this._method = method; + this._url = xhrUrl; + this._sync = !async; + this._headers = {}; + this._loweredHeaders = {}; + this._mimeOverride = null; + this._setReadyState(XMLHttpRequest.OPENED); + this._request = null; + this._response = null; + this.status = 0; + this.statusText = ''; + this._responseParts = []; + this._responseHeaders = null; + this._loadedBytes = 0; + this._totalBytes = 0; + this._lengthComputable = false; + }; + XMLHttpRequest.prototype.setRequestHeader = function (name, value) { + if (this.readyState !== XMLHttpRequest.OPENED) { + throw new XMLHttpRequest.InvalidStateError('XHR readyState must be OPENED'); + } + var loweredName = name.toLowerCase(); + if (this._restrictedHeaders[loweredName] || /^sec-/.test(loweredName) || /^proxy-/.test(loweredName)) { + console.warn("Refused to set unsafe header \"" + name + "\""); + return; + } + value = value.toString(); + if (this._loweredHeaders[loweredName] != null) { + name = this._loweredHeaders[loweredName]; + this._headers[name] = this._headers[name] + ", " + value; + } + else { + this._loweredHeaders[loweredName] = name; + this._headers[name] = value; + } + }; + XMLHttpRequest.prototype.send = function (data) { + if (this.readyState !== XMLHttpRequest.OPENED) { + throw new XMLHttpRequest.InvalidStateError('XHR readyState must be OPENED'); + } + if (this._request) { + throw new XMLHttpRequest.InvalidStateError('send() already called'); + } + switch (this._url.protocol) { + case 'file:': + return this._sendFile(data); + case 'http:': + case 'https:': + return this._sendHttp(data); + default: + throw new XMLHttpRequest.NetworkError("Unsupported protocol " + this._url.protocol); + } + }; + XMLHttpRequest.prototype.abort = function () { + if (this._request == null) { + return; + } + this._request.abort(); + this._setError(); + this._dispatchProgress('abort'); + this._dispatchProgress('loadend'); + }; + XMLHttpRequest.prototype.getResponseHeader = function (name) { + if (this._responseHeaders == null || name == null) { + return null; + } + var loweredName = name.toLowerCase(); + return this._responseHeaders.hasOwnProperty(loweredName) + ? this._responseHeaders[name.toLowerCase()] + : null; + }; + XMLHttpRequest.prototype.getAllResponseHeaders = function () { + var _this = this; + if (this._responseHeaders == null) { + return ''; + } + return Object.keys(this._responseHeaders).map(function (key) { return key + ": " + _this._responseHeaders[key]; }).join('\r\n'); + }; + XMLHttpRequest.prototype.overrideMimeType = function (mimeType) { + if (this.readyState === XMLHttpRequest.LOADING || this.readyState === XMLHttpRequest.DONE) { + throw new XMLHttpRequest.InvalidStateError('overrideMimeType() not allowed in LOADING or DONE'); + } + this._mimeOverride = mimeType.toLowerCase(); + }; + XMLHttpRequest.prototype.nodejsSet = function (options) { + this.nodejsHttpAgent = options.httpAgent || this.nodejsHttpAgent; + this.nodejsHttpsAgent = options.httpsAgent || this.nodejsHttpsAgent; + if (options.hasOwnProperty('baseUrl')) { + if (options.baseUrl != null) { + var parsedUrl = url.parse(options.baseUrl, false, true); + if (!parsedUrl.protocol) { + throw new XMLHttpRequest.SyntaxError("baseUrl must be an absolute URL"); + } + } + this.nodejsBaseUrl = options.baseUrl; + } + }; + XMLHttpRequest.nodejsSet = function (options) { + XMLHttpRequest.prototype.nodejsSet(options); + }; + XMLHttpRequest.prototype._setReadyState = function (readyState) { + this.readyState = readyState; + this.dispatchEvent(new progress_event_1.ProgressEvent('readystatechange')); + }; + XMLHttpRequest.prototype._sendFile = function (data) { + // TODO + throw new Error('Protocol file: not implemented'); + }; + XMLHttpRequest.prototype._sendHttp = function (data) { + if (this._sync) { + throw new Error('Synchronous XHR processing not implemented'); + } + if (data && (this._method === 'GET' || this._method === 'HEAD')) { + console.warn("Discarding entity body for " + this._method + " requests"); + data = null; + } + else { + data = data || ''; + } + this.upload._setData(data); + this._finalizeHeaders(); + this._sendHxxpRequest(); + }; + XMLHttpRequest.prototype._sendHxxpRequest = function () { + var _this = this; + if (this.withCredentials) { + var cookie = XMLHttpRequest.cookieJar + .getCookies(Cookie.CookieAccessInfo(this._url.hostname, this._url.pathname, this._url.protocol === 'https:')).toValueString(); + this._headers.cookie = this._headers.cookie2 = cookie; + } + var _a = this._url.protocol === 'http:' ? [http, this.nodejsHttpAgent] : [https, this.nodejsHttpsAgent], hxxp = _a[0], agent = _a[1]; + var requestMethod = hxxp.request.bind(hxxp); + var request = requestMethod({ + hostname: this._url.hostname, + port: +this._url.port, + path: this._url.path, + auth: this._url.auth, + method: this._method, + headers: this._headers, + agent: agent + }); + this._request = request; + if (this.timeout) { + request.setTimeout(this.timeout, function () { return _this._onHttpTimeout(request); }); + } + request.on('response', function (response) { return _this._onHttpResponse(request, response); }); + request.on('error', function (error) { return _this._onHttpRequestError(request, error); }); + this.upload._startUpload(request); + if (this._request === request) { + this._dispatchProgress('loadstart'); + } + }; + XMLHttpRequest.prototype._finalizeHeaders = function () { + this._headers = __assign({}, this._headers, { Connection: 'keep-alive', Host: this._url.host, 'User-Agent': this._userAgent }, this._anonymous ? { Referer: 'about:blank' } : {}); + this.upload._finalizeHeaders(this._headers, this._loweredHeaders); + }; + XMLHttpRequest.prototype._onHttpResponse = function (request, response) { + var _this = this; + if (this._request !== request) { + return; + } + if (this.withCredentials && (response.headers['set-cookie'] || response.headers['set-cookie2'])) { + XMLHttpRequest.cookieJar + .setCookies(response.headers['set-cookie'] || response.headers['set-cookie2']); + } + if ([301, 302, 303, 307, 308].indexOf(response.statusCode) >= 0) { + this._url = this._parseUrl(response.headers.location); + this._method = 'GET'; + if (this._loweredHeaders['content-type']) { + delete this._headers[this._loweredHeaders['content-type']]; + delete this._loweredHeaders['content-type']; + } + if (this._headers['Content-Type'] != null) { + delete this._headers['Content-Type']; + } + delete this._headers['Content-Length']; + this.upload._reset(); + this._finalizeHeaders(); + this._sendHxxpRequest(); + return; + } + this._response = response; + this._response.on('data', function (data) { return _this._onHttpResponseData(response, data); }); + this._response.on('end', function () { return _this._onHttpResponseEnd(response); }); + this._response.on('close', function () { return _this._onHttpResponseClose(response); }); + this.responseUrl = this._url.href.split('#')[0]; + this.status = response.statusCode; + this.statusText = http.STATUS_CODES[this.status]; + this._parseResponseHeaders(response); + var lengthString = this._responseHeaders['content-length'] || ''; + this._totalBytes = +lengthString; + this._lengthComputable = !!lengthString; + this._setReadyState(XMLHttpRequest.HEADERS_RECEIVED); + }; + XMLHttpRequest.prototype._onHttpResponseData = function (response, data) { + if (this._response !== response) { + return; + } + this._responseParts.push(new Buffer(data)); + this._loadedBytes += data.length; + if (this.readyState !== XMLHttpRequest.LOADING) { + this._setReadyState(XMLHttpRequest.LOADING); + } + this._dispatchProgress('progress'); + }; + XMLHttpRequest.prototype._onHttpResponseEnd = function (response) { + if (this._response !== response) { + return; + } + this._parseResponse(); + this._request = null; + this._response = null; + this._setReadyState(XMLHttpRequest.DONE); + this._dispatchProgress('load'); + this._dispatchProgress('loadend'); + }; + XMLHttpRequest.prototype._onHttpResponseClose = function (response) { + if (this._response !== response) { + return; + } + var request = this._request; + this._setError(); + request.abort(); + this._setReadyState(XMLHttpRequest.DONE); + this._dispatchProgress('error'); + this._dispatchProgress('loadend'); + }; + XMLHttpRequest.prototype._onHttpTimeout = function (request) { + if (this._request !== request) { + return; + } + this._setError(); + request.abort(); + this._setReadyState(XMLHttpRequest.DONE); + this._dispatchProgress('timeout'); + this._dispatchProgress('loadend'); + }; + XMLHttpRequest.prototype._onHttpRequestError = function (request, error) { + if (this._request !== request) { + return; + } + this._setError(); + request.abort(); + this._setReadyState(XMLHttpRequest.DONE); + this._dispatchProgress('error'); + this._dispatchProgress('loadend'); + }; + XMLHttpRequest.prototype._dispatchProgress = function (eventType) { + var event = new XMLHttpRequest.ProgressEvent(eventType); + event.lengthComputable = this._lengthComputable; + event.loaded = this._loadedBytes; + event.total = this._totalBytes; + this.dispatchEvent(event); + }; + XMLHttpRequest.prototype._setError = function () { + this._request = null; + this._response = null; + this._responseHeaders = null; + this._responseParts = null; + }; + XMLHttpRequest.prototype._parseUrl = function (urlString, user, password) { + var absoluteUrl = this.nodejsBaseUrl == null ? urlString : url.resolve(this.nodejsBaseUrl, urlString); + var xhrUrl = url.parse(absoluteUrl, false, true); + xhrUrl.hash = null; + var _a = (xhrUrl.auth || '').split(':'), xhrUser = _a[0], xhrPassword = _a[1]; + if (xhrUser || xhrPassword || user || password) { + xhrUrl.auth = (user || xhrUser || '') + ":" + (password || xhrPassword || ''); + } + return xhrUrl; + }; + XMLHttpRequest.prototype._parseResponseHeaders = function (response) { + this._responseHeaders = {}; + for (var name_1 in response.headers) { + var loweredName = name_1.toLowerCase(); + if (this._privateHeaders[loweredName]) { + continue; + } + this._responseHeaders[loweredName] = response.headers[name_1]; + } + if (this._mimeOverride != null) { + this._responseHeaders['content-type'] = this._mimeOverride; + } + }; + XMLHttpRequest.prototype._parseResponse = function () { + var buffer = Buffer.concat(this._responseParts); + this._responseParts = null; + switch (this.responseType) { + case 'json': + this.responseText = null; + try { + this.response = JSON.parse(buffer.toString('utf-8')); + } + catch (_a) { + this.response = null; + } + return; + case 'buffer': + this.responseText = null; + this.response = buffer; + return; + case 'arraybuffer': + this.responseText = null; + var arrayBuffer = new ArrayBuffer(buffer.length); + var view = new Uint8Array(arrayBuffer); + for (var i = 0; i < buffer.length; i++) { + view[i] = buffer[i]; + } + this.response = arrayBuffer; + return; + case 'text': + default: + try { + this.responseText = buffer.toString(this._parseResponseEncoding()); + } + catch (_b) { + this.responseText = buffer.toString('binary'); + } + this.response = this.responseText; + } + }; + XMLHttpRequest.prototype._parseResponseEncoding = function () { + return /;\s*charset=(.*)$/.exec(this._responseHeaders['content-type'] || '')[1] || 'utf-8'; + }; + XMLHttpRequest.ProgressEvent = progress_event_1.ProgressEvent; + XMLHttpRequest.InvalidStateError = errors_1.InvalidStateError; + XMLHttpRequest.NetworkError = errors_1.NetworkError; + XMLHttpRequest.SecurityError = errors_1.SecurityError; + XMLHttpRequest.SyntaxError = errors_1.SyntaxError; + XMLHttpRequest.XMLHttpRequestUpload = xml_http_request_upload_1.XMLHttpRequestUpload; + XMLHttpRequest.UNSENT = 0; + XMLHttpRequest.OPENED = 1; + XMLHttpRequest.HEADERS_RECEIVED = 2; + XMLHttpRequest.LOADING = 3; + XMLHttpRequest.DONE = 4; + XMLHttpRequest.cookieJar = Cookie.CookieJar(); + return XMLHttpRequest; + }(xml_http_request_event_target_1.XMLHttpRequestEventTarget)); + exports.XMLHttpRequest = XMLHttpRequest; + 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() { + if (window.isIOS) { + return; + } + window.isIOS = function() { + return navigator && navigator.userAgent && (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)); + }; + }()); + (function() { + if (window.bridge) { + return; + } + window.bridge = function() { + var callbacks = [], + callbackID = 0, + registerHandlers = []; + document.addEventListener('PacificDidReceiveNativeCallback', function(e) { + if (e.detail) { + var detail = e.detail; + var id = isNaN(parseInt(detail.id)) ? -1 : parseInt(detail.id); + if (id != -1) { + callbacks[id] && callbacks[id](detail.parameters, detail.error); + delete callbacks[id]; + } + } + }, false); + document.addEventListener('PacificDidReceiveNativeBroadcast', function(e) { + if (e.detail) { + var detail = e.detail; + var name = detail.name; + if (name !== undefined && registerHandlers[name]) { + var namedListeners = registerHandlers[name]; + if (namedListeners instanceof Array) { + var parameters = detail.parameters; + namedListeners.forEach(function(handler) { + handler(parameters); + }); + } + } + } + }, false); + return { + 'post': function(action, parameters, callback, print) { + var id = callbackID++; + callbacks[id] = callback; + if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.pacific) { + window.webkit.messageHandlers.pacific.postMessage({ + 'action': action, + 'parameters': parameters, + 'callback': id, + 'print': print || 0 + }); + } + }, + 'on': function(name, callback) { + var namedListeners = registerHandlers[name]; + if (!namedListeners) { + registerHandlers[name] = namedListeners = []; + } + namedListeners.push(callback); + return function() { + namedListeners[indexOf(namedListeners, callback)] = null; + }; + }, + 'off': function(name) { + delete registerHandlers[name]; + } + }; + }(); + }()); + + //# sourceURL=/Users/alexvlasov/Blockchain/web3swift/web3swiftJSProxy/wk.bridge.js + },{}]},{},[1]); + \ No newline at end of file diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Browser/browser.min.js b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Browser/browser.min.js new file mode 100644 index 000000000..f838d4a4b --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Browser/browser.min.js @@ -0,0 +1,2 @@ +!function(){return function e(t,r,n){function i(a,s){if(!r[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(o)return o(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var f=r[a]={exports:{}};t[a][0].call(f.exports,function(e){var r=t[a][1][e];return i(r||e)},f,f.exports,e,t,r,n)}return r[a].exports}for(var o="function"==typeof require&&require,a=0;a0&&(window.web3.eth.defaultAccount=t[0])})}window.ethereum=s}}},console.log("JS bridging rpc url access"),"undefined"!=typeof window&&window.bridge?window.bridge.post("getRPCurl",{},function(e,r){r&&t(r.description,null),t(null,e.rpcURL)}):(console.log("No bridge to native code is found"),t(!0,null))}()},{"./wk.bridge":424,web3:407,"web3-provider-engine/zero.js":397}],2:[function(e,t,r){t.exports=e("./register")().Promise},{"./register":4}],3:[function(e,t,r){"use strict";var n=null;t.exports=function(e,t){return function(r,i){r=r||null;var o=!1!==(i=i||{}).global;if(null===n&&o&&(n=e["@@any-promise/REGISTRATION"]||null),null!==n&&null!==r&&n.implementation!==r)throw new Error('any-promise already defined as "'+n.implementation+'". You can only register an implementation before the first call to require("any-promise") and an implementation cannot be changed');return null===n&&(n=null!==r&&void 0!==i.Promise?{Promise:i.Promise,implementation:r}:t(r),o&&(e["@@any-promise/REGISTRATION"]=n)),n}}},{}],4:[function(e,t,r){"use strict";t.exports=e("./loader")(window,function(){if(void 0===window.Promise)throw new Error("any-promise browser requires a polyfill or explicit registration e.g: require('any-promise/register/bluebird')");return{Promise:window.Promise,implementation:"window.Promise"}})},{"./loader":3}],5:[function(e,t,r){var n=r;n.bignum=e("bn.js"),n.define=e("./asn1/api").define,n.base=e("./asn1/base"),n.constants=e("./asn1/constants"),n.decoders=e("./asn1/decoders"),n.encoders=e("./asn1/encoders")},{"./asn1/api":6,"./asn1/base":8,"./asn1/constants":12,"./asn1/decoders":14,"./asn1/encoders":17,"bn.js":53}],6:[function(e,t,r){var n=e("../asn1"),i=e("inherits");function o(e,t){this.name=e,this.body=t,this.decoders={},this.encoders={}}r.define=function(e,t){return new o(e,t)},o.prototype._createNamed=function(t){var r;try{r=e("vm").runInThisContext("(function "+this.name+"(entity) {\n this._initNamed(entity);\n})")}catch(e){r=function(e){this._initNamed(e)}}return i(r,t),r.prototype._initNamed=function(e){t.call(this,e)},new r(this)},o.prototype._getDecoder=function(e){return e=e||"der",this.decoders.hasOwnProperty(e)||(this.decoders[e]=this._createNamed(n.decoders[e])),this.decoders[e]},o.prototype.decode=function(e,t,r){return this._getDecoder(t).decode(e,r)},o.prototype._getEncoder=function(e){return e=e||"der",this.encoders.hasOwnProperty(e)||(this.encoders[e]=this._createNamed(n.encoders[e])),this.encoders[e]},o.prototype.encode=function(e,t,r){return this._getEncoder(t).encode(e,r)}},{"../asn1":5,inherits:180,vm:334}],7:[function(e,t,r){var n=e("inherits"),i=e("../base").Reporter,o=e("buffer").Buffer;function a(e,t){i.call(this,t),o.isBuffer(e)?(this.base=e,this.offset=0,this.length=e.length):this.error("Input not Buffer")}function s(e,t){if(Array.isArray(e))this.length=0,this.value=e.map(function(e){return e instanceof s||(e=new s(e,t)),this.length+=e.length,e},this);else if("number"==typeof e){if(!(0<=e&&e<=255))return t.error("non-byte EncoderBuffer value");this.value=e,this.length=1}else if("string"==typeof e)this.value=e,this.length=o.byteLength(e);else{if(!o.isBuffer(e))return t.error("Unsupported type: "+typeof e);this.value=e,this.length=e.length}}n(a,i),r.DecoderBuffer=a,a.prototype.save=function(){return{offset:this.offset,reporter:i.prototype.save.call(this)}},a.prototype.restore=function(e){var t=new a(this.base);return t.offset=e.offset,t.length=this.offset,this.offset=e.offset,i.prototype.restore.call(this,e.reporter),t},a.prototype.isEmpty=function(){return this.offset===this.length},a.prototype.readUInt8=function(e){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(e||"DecoderBuffer overrun")},a.prototype.skip=function(e,t){if(!(this.offset+e<=this.length))return this.error(t||"DecoderBuffer overrun");var r=new a(this.base);return r._reporterState=this._reporterState,r.offset=this.offset,r.length=this.offset+e,this.offset+=e,r},a.prototype.raw=function(e){return this.base.slice(e?e.offset:this.offset,this.length)},r.EncoderBuffer=s,s.prototype.join=function(e,t){return e||(e=new o(this.length)),t||(t=0),0===this.length?e:(Array.isArray(this.value)?this.value.forEach(function(r){r.join(e,t),t+=r.length}):("number"==typeof this.value?e[t]=this.value:"string"==typeof this.value?e.write(this.value,t):o.isBuffer(this.value)&&this.value.copy(e,t),t+=this.length),e)}},{"../base":8,buffer:84,inherits:180}],8:[function(e,t,r){var n=r;n.Reporter=e("./reporter").Reporter,n.DecoderBuffer=e("./buffer").DecoderBuffer,n.EncoderBuffer=e("./buffer").EncoderBuffer,n.Node=e("./node")},{"./buffer":7,"./node":9,"./reporter":10}],9:[function(e,t,r){var n=e("../base").Reporter,i=e("../base").EncoderBuffer,o=e("../base").DecoderBuffer,a=e("minimalistic-assert"),s=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],u=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(s);function c(e,t){var r={};this._baseState=r,r.enc=e,r.parent=t||null,r.children=null,r.tag=null,r.args=null,r.reverseArgs=null,r.choice=null,r.optional=!1,r.any=!1,r.obj=!1,r.use=null,r.useDecoder=null,r.key=null,r.default=null,r.explicit=null,r.implicit=null,r.contains=null,r.parent||(r.children=[],this._wrap())}t.exports=c;var f=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];c.prototype.clone=function(){var e=this._baseState,t={};f.forEach(function(r){t[r]=e[r]});var r=new this.constructor(t.parent);return r._baseState=t,r},c.prototype._wrap=function(){var e=this._baseState;u.forEach(function(t){this[t]=function(){var r=new this.constructor(this);return e.children.push(r),r[t].apply(r,arguments)}},this)},c.prototype._init=function(e){var t=this._baseState;a(null===t.parent),e.call(this),t.children=t.children.filter(function(e){return e._baseState.parent===this},this),a.equal(t.children.length,1,"Root node can have only one child")},c.prototype._useArgs=function(e){var t=this._baseState,r=e.filter(function(e){return e instanceof this.constructor},this);e=e.filter(function(e){return!(e instanceof this.constructor)},this),0!==r.length&&(a(null===t.children),t.children=r,r.forEach(function(e){e._baseState.parent=this},this)),0!==e.length&&(a(null===t.args),t.args=e,t.reverseArgs=e.map(function(e){if("object"!=typeof e||e.constructor!==Object)return e;var t={};return Object.keys(e).forEach(function(r){r==(0|r)&&(r|=0);var n=e[r];t[n]=r}),t}))},["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"].forEach(function(e){c.prototype[e]=function(){var t=this._baseState;throw new Error(e+" not implemented for encoding: "+t.enc)}}),s.forEach(function(e){c.prototype[e]=function(){var t=this._baseState,r=Array.prototype.slice.call(arguments);return a(null===t.tag),t.tag=e,this._useArgs(r),this}}),c.prototype.use=function(e){a(e);var t=this._baseState;return a(null===t.use),t.use=e,this},c.prototype.optional=function(){return this._baseState.optional=!0,this},c.prototype.def=function(e){var t=this._baseState;return a(null===t.default),t.default=e,t.optional=!0,this},c.prototype.explicit=function(e){var t=this._baseState;return a(null===t.explicit&&null===t.implicit),t.explicit=e,this},c.prototype.implicit=function(e){var t=this._baseState;return a(null===t.explicit&&null===t.implicit),t.implicit=e,this},c.prototype.obj=function(){var e=this._baseState,t=Array.prototype.slice.call(arguments);return e.obj=!0,0!==t.length&&this._useArgs(t),this},c.prototype.key=function(e){var t=this._baseState;return a(null===t.key),t.key=e,this},c.prototype.any=function(){return this._baseState.any=!0,this},c.prototype.choice=function(e){var t=this._baseState;return a(null===t.choice),t.choice=e,this._useArgs(Object.keys(e).map(function(t){return e[t]})),this},c.prototype.contains=function(e){var t=this._baseState;return a(null===t.use),t.contains=e,this},c.prototype._decode=function(e,t){var r=this._baseState;if(null===r.parent)return e.wrapResult(r.children[0]._decode(e,t));var n,i=r.default,a=!0,s=null;if(null!==r.key&&(s=e.enterKey(r.key)),r.optional){var u=null;if(null!==r.explicit?u=r.explicit:null!==r.implicit?u=r.implicit:null!==r.tag&&(u=r.tag),null!==u||r.any){if(a=this._peekTag(e,u,r.any),e.isError(a))return a}else{var c=e.save();try{null===r.choice?this._decodeGeneric(r.tag,e,t):this._decodeChoice(e,t),a=!0}catch(e){a=!1}e.restore(c)}}if(r.obj&&a&&(n=e.enterObject()),a){if(null!==r.explicit){var f=this._decodeTag(e,r.explicit);if(e.isError(f))return f;e=f}var h=e.offset;if(null===r.use&&null===r.choice){if(r.any)c=e.save();var l=this._decodeTag(e,null!==r.implicit?r.implicit:r.tag,r.any);if(e.isError(l))return l;r.any?i=e.raw(c):e=l}if(t&&t.track&&null!==r.tag&&t.track(e.path(),h,e.length,"tagged"),t&&t.track&&null!==r.tag&&t.track(e.path(),e.offset,e.length,"content"),i=r.any?i:null===r.choice?this._decodeGeneric(r.tag,e,t):this._decodeChoice(e,t),e.isError(i))return i;if(r.any||null!==r.choice||null===r.children||r.children.forEach(function(r){r._decode(e,t)}),r.contains&&("octstr"===r.tag||"bitstr"===r.tag)){var d=new o(i);i=this._getUse(r.contains,e._reporterState.obj)._decode(d,t)}}return r.obj&&a&&(i=e.leaveObject(n)),null===r.key||null===i&&!0!==a?null!==s&&e.exitKey(s):e.leaveKey(s,r.key,i),i},c.prototype._decodeGeneric=function(e,t,r){var n=this._baseState;return"seq"===e||"set"===e?null:"seqof"===e||"setof"===e?this._decodeList(t,e,n.args[0],r):/str$/.test(e)?this._decodeStr(t,e,r):"objid"===e&&n.args?this._decodeObjid(t,n.args[0],n.args[1],r):"objid"===e?this._decodeObjid(t,null,null,r):"gentime"===e||"utctime"===e?this._decodeTime(t,e,r):"null_"===e?this._decodeNull(t,r):"bool"===e?this._decodeBool(t,r):"objDesc"===e?this._decodeStr(t,e,r):"int"===e||"enum"===e?this._decodeInt(t,n.args&&n.args[0],r):null!==n.use?this._getUse(n.use,t._reporterState.obj)._decode(t,r):t.error("unknown tag: "+e)},c.prototype._getUse=function(e,t){var r=this._baseState;return r.useDecoder=this._use(e,t),a(null===r.useDecoder._baseState.parent),r.useDecoder=r.useDecoder._baseState.children[0],r.implicit!==r.useDecoder._baseState.implicit&&(r.useDecoder=r.useDecoder.clone(),r.useDecoder._baseState.implicit=r.implicit),r.useDecoder},c.prototype._decodeChoice=function(e,t){var r=this._baseState,n=null,i=!1;return Object.keys(r.choice).some(function(o){var a=e.save(),s=r.choice[o];try{var u=s._decode(e,t);if(e.isError(u))return!1;n={type:o,value:u},i=!0}catch(t){return e.restore(a),!1}return!0},this),i?n:e.error("Choice not matched")},c.prototype._createEncoderBuffer=function(e){return new i(e,this.reporter)},c.prototype._encode=function(e,t,r){var n=this._baseState;if(null===n.default||n.default!==e){var i=this._encodeValue(e,t,r);if(void 0!==i&&!this._skipDefault(i,t,r))return i}},c.prototype._encodeValue=function(e,t,r){var i=this._baseState;if(null===i.parent)return i.children[0]._encode(e,t||new n);var o=null;if(this.reporter=t,i.optional&&void 0===e){if(null===i.default)return;e=i.default}var a=null,s=!1;if(i.any)o=this._createEncoderBuffer(e);else if(i.choice)o=this._encodeChoice(e,t);else if(i.contains)a=this._getUse(i.contains,r)._encode(e,t),s=!0;else if(i.children)a=i.children.map(function(r){if("null_"===r._baseState.tag)return r._encode(null,t,e);if(null===r._baseState.key)return t.error("Child should have a key");var n=t.enterKey(r._baseState.key);if("object"!=typeof e)return t.error("Child expected, but input is not object");var i=r._encode(e[r._baseState.key],t,e);return t.leaveKey(n),i},this).filter(function(e){return e}),a=this._createEncoderBuffer(a);else if("seqof"===i.tag||"setof"===i.tag){if(!i.args||1!==i.args.length)return t.error("Too many args for : "+i.tag);if(!Array.isArray(e))return t.error("seqof/setof, but data is not Array");var u=this.clone();u._baseState.implicit=null,a=this._createEncoderBuffer(e.map(function(r){var n=this._baseState;return this._getUse(n.args[0],e)._encode(r,t)},u))}else null!==i.use?o=this._getUse(i.use,r)._encode(e,t):(a=this._encodePrimitive(i.tag,e),s=!0);if(!i.any&&null===i.choice){var c=null!==i.implicit?i.implicit:i.tag,f=null===i.implicit?"universal":"context";null===c?null===i.use&&t.error("Tag could be omitted only for .use()"):null===i.use&&(o=this._encodeComposite(c,s,f,a))}return null!==i.explicit&&(o=this._encodeComposite(i.explicit,!1,"context",o)),o},c.prototype._encodeChoice=function(e,t){var r=this._baseState,n=r.choice[e.type];return n||a(!1,e.type+" not found in "+JSON.stringify(Object.keys(r.choice))),n._encode(e.value,t)},c.prototype._encodePrimitive=function(e,t){var r=this._baseState;if(/str$/.test(e))return this._encodeStr(t,e);if("objid"===e&&r.args)return this._encodeObjid(t,r.reverseArgs[0],r.args[1]);if("objid"===e)return this._encodeObjid(t,null,null);if("gentime"===e||"utctime"===e)return this._encodeTime(t,e);if("null_"===e)return this._encodeNull();if("int"===e||"enum"===e)return this._encodeInt(t,r.args&&r.reverseArgs[0]);if("bool"===e)return this._encodeBool(t);if("objDesc"===e)return this._encodeStr(t,e);throw new Error("Unsupported tag: "+e)},c.prototype._isNumstr=function(e){return/^[0-9 ]*$/.test(e)},c.prototype._isPrintstr=function(e){return/^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(e)}},{"../base":8,"minimalistic-assert":234}],10:[function(e,t,r){var n=e("inherits");function i(e){this._reporterState={obj:null,path:[],options:e||{},errors:[]}}function o(e,t){this.path=e,this.rethrow(t)}r.Reporter=i,i.prototype.isError=function(e){return e instanceof o},i.prototype.save=function(){var e=this._reporterState;return{obj:e.obj,pathLen:e.path.length}},i.prototype.restore=function(e){var t=this._reporterState;t.obj=e.obj,t.path=t.path.slice(0,e.pathLen)},i.prototype.enterKey=function(e){return this._reporterState.path.push(e)},i.prototype.exitKey=function(e){var t=this._reporterState;t.path=t.path.slice(0,e-1)},i.prototype.leaveKey=function(e,t,r){var n=this._reporterState;this.exitKey(e),null!==n.obj&&(n.obj[t]=r)},i.prototype.path=function(){return this._reporterState.path.join("/")},i.prototype.enterObject=function(){var e=this._reporterState,t=e.obj;return e.obj={},t},i.prototype.leaveObject=function(e){var t=this._reporterState,r=t.obj;return t.obj=e,r},i.prototype.error=function(e){var t,r=this._reporterState,n=e instanceof o;if(t=n?e:new o(r.path.map(function(e){return"["+JSON.stringify(e)+"]"}).join(""),e.message||e,e.stack),!r.options.partial)throw t;return n||r.errors.push(t),t},i.prototype.wrapResult=function(e){var t=this._reporterState;return t.options.partial?{result:this.isError(e)?null:e,errors:t.errors}:e},n(o,Error),o.prototype.rethrow=function(e){if(this.message=e+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,o),!this.stack)try{throw new Error(this.message)}catch(e){this.stack=e.stack}return this}},{inherits:180}],11:[function(e,t,r){var n=e("../constants");r.tagClass={0:"universal",1:"application",2:"context",3:"private"},r.tagClassByName=n._reverse(r.tagClass),r.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},r.tagByName=n._reverse(r.tag)},{"../constants":12}],12:[function(e,t,r){var n=r;n._reverse=function(e){var t={};return Object.keys(e).forEach(function(r){(0|r)==r&&(r|=0);var n=e[r];t[n]=r}),t},n.der=e("./der")},{"./der":11}],13:[function(e,t,r){var n=e("inherits"),i=e("../../asn1"),o=i.base,a=i.bignum,s=i.constants.der;function u(e){this.enc="der",this.name=e.name,this.entity=e,this.tree=new c,this.tree._init(e.body)}function c(e){o.Node.call(this,"der",e)}function f(e,t){var r=e.readUInt8(t);if(e.isError(r))return r;var n=s.tagClass[r>>6],i=0==(32&r);if(31==(31&r)){var o=r;for(r=0;128==(128&o);){if(o=e.readUInt8(t),e.isError(o))return o;r<<=7,r|=127&o}}else r&=31;return{cls:n,primitive:i,tag:r,tagStr:s.tag[r]}}function h(e,t,r){var n=e.readUInt8(r);if(e.isError(n))return n;if(!t&&128===n)return null;if(0==(128&n))return n;var i=127&n;if(i>4)return e.error("length octect is too long");n=0;for(var o=0;o=31)return n.error("Multi-octet tag encoding unsupported");t||(i|=32);return i|=s.tagClassByName[r||"universal"]<<6}(e,t,r,this.reporter);if(n.length<128)return(o=new i(2))[0]=a,o[1]=n.length,this._createEncoderBuffer([o,n]);for(var u=1,c=n.length;c>=256;c>>=8)u++;(o=new i(2+u))[0]=a,o[1]=128|u;c=1+u;for(var f=n.length;f>0;c--,f>>=8)o[c]=255&f;return this._createEncoderBuffer([o,n])},c.prototype._encodeStr=function(e,t){if("bitstr"===t)return this._createEncoderBuffer([0|e.unused,e.data]);if("bmpstr"===t){for(var r=new i(2*e.length),n=0;n=40)return this.reporter.error("Second objid identifier OOB");e.splice(0,2,40*e[0]+e[1])}var o=0;for(n=0;n=128;a>>=7)o++}var s=new i(o),u=s.length-1;for(n=e.length-1;n>=0;n--){a=e[n];for(s[u--]=127&a;(a>>=7)>0;)s[u--]=128|127&a}return this._createEncoderBuffer(s)},c.prototype._encodeTime=function(e,t){var r,n=new Date(e);return"gentime"===t?r=[f(n.getFullYear()),f(n.getUTCMonth()+1),f(n.getUTCDate()),f(n.getUTCHours()),f(n.getUTCMinutes()),f(n.getUTCSeconds()),"Z"].join(""):"utctime"===t?r=[f(n.getFullYear()%100),f(n.getUTCMonth()+1),f(n.getUTCDate()),f(n.getUTCHours()),f(n.getUTCMinutes()),f(n.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+t+" time is not supported yet"),this._encodeStr(r,"octstr")},c.prototype._encodeNull=function(){return this._createEncoderBuffer("")},c.prototype._encodeInt=function(e,t){if("string"==typeof e){if(!t)return this.reporter.error("String int or enum given, but no values map");if(!t.hasOwnProperty(e))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(e));e=t[e]}if("number"!=typeof e&&!i.isBuffer(e)){var r=e.toArray();!e.sign&&128&r[0]&&r.unshift(0),e=new i(r)}if(i.isBuffer(e)){var n=e.length;0===e.length&&n++;var o=new i(n);return e.copy(o),0===e.length&&(o[0]=0),this._createEncoderBuffer(o)}if(e<128)return this._createEncoderBuffer(e);if(e<256)return this._createEncoderBuffer([0,e]);n=1;for(var a=e;a>=256;a>>=8)n++;for(a=(o=new Array(n)).length-1;a>=0;a--)o[a]=255&e,e>>=8;return 128&o[0]&&o.unshift(0),this._createEncoderBuffer(new i(o))},c.prototype._encodeBool=function(e){return this._createEncoderBuffer(e?255:0)},c.prototype._use=function(e,t){return"function"==typeof e&&(e=e(t)),e._getEncoder("der").tree},c.prototype._skipDefault=function(e,t,r){var n,i=this._baseState;if(null===i.default)return!1;var o=e.join();if(void 0===i.defaultBuffer&&(i.defaultBuffer=this._encodeValue(i.default,t,r).join()),o.length!==i.defaultBuffer.length)return!1;for(n=0;n=0;c--)if(f[c]!==h[c])return!1;for(c=f.length-1;c>=0;c--)if(u=f[c],!v(e[u],t[u],r,n))return!1;return!0}(e,t,r,a))}return r?e===t:e==t}function g(e){return"[object Arguments]"==Object.prototype.toString.call(e)}function w(e,t){if(!e||!t)return!1;if("[object RegExp]"==Object.prototype.toString.call(t))return t.test(e);try{if(e instanceof t)return!0}catch(e){}return!Error.isPrototypeOf(t)&&!0===t.call({},e)}function _(e,t,r,n){var i;if("function"!=typeof t)throw new TypeError('"block" argument must be a function');"string"==typeof r&&(n=r,r=null),i=function(e){var t;try{e()}catch(e){t=e}return t}(t),n=(r&&r.name?" ("+r.name+").":".")+(n?" "+n:"."),e&&!i&&y(i,r,"Missing expected exception"+n);var a="string"==typeof n,s=!e&&i&&!r;if((!e&&o.isError(i)&&a&&w(i,r)||s)&&y(i,r,"Got unwanted exception"+n),e&&i&&r&&!w(i,r)||!e&&i)throw i}h.AssertionError=function(e){var t;this.name="AssertionError",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,e.message?(this.message=e.message,this.generatedMessage=!1):(this.message=p(b((t=this).actual),128)+" "+t.operator+" "+p(b(t.expected),128),this.generatedMessage=!0);var r=e.stackStartFunction||y;if(Error.captureStackTrace)Error.captureStackTrace(this,r);else{var n=new Error;if(n.stack){var i=n.stack,o=d(r),a=i.indexOf("\n"+o);if(a>=0){var s=i.indexOf("\n",a+1);i=i.substring(s+1)}this.stack=i}}},o.inherits(h.AssertionError,Error),h.fail=y,h.ok=m,h.equal=function(e,t,r){e!=t&&y(e,t,r,"==",h.equal)},h.notEqual=function(e,t,r){e==t&&y(e,t,r,"!=",h.notEqual)},h.deepEqual=function(e,t,r){v(e,t,!1)||y(e,t,r,"deepEqual",h.deepEqual)},h.deepStrictEqual=function(e,t,r){v(e,t,!0)||y(e,t,r,"deepStrictEqual",h.deepStrictEqual)},h.notDeepEqual=function(e,t,r){v(e,t,!1)&&y(e,t,r,"notDeepEqual",h.notDeepEqual)},h.notDeepStrictEqual=function e(t,r,n){v(t,r,!0)&&y(t,r,n,"notDeepStrictEqual",e)},h.strictEqual=function(e,t,r){e!==t&&y(e,t,r,"===",h.strictEqual)},h.notStrictEqual=function(e,t,r){e===t&&y(e,t,r,"!==",h.notStrictEqual)},h.throws=function(e,t,r){_(!0,e,t,r)},h.doesNotThrow=function(e,t,r){_(!1,e,t,r)},h.ifError=function(e){if(e)throw e};var A=Object.keys||function(e){var t=[];for(var r in e)a.call(e,r)&&t.push(r);return t}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"util/":333}],20:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(function(t,r){var i;try{i=e.apply(this,t)}catch(e){return r(e)}(0,n.default)(i)&&"function"==typeof i.then?i.then(function(e){s(r,null,e)},function(e){s(r,e.message?e:new Error(e))}):r(null,i)})};var n=a(e("lodash/isObject")),i=a(e("./internal/initialParams")),o=a(e("./internal/setImmediate"));function a(e){return e&&e.__esModule?e:{default:e}}function s(e,t,r){try{e(t,r)}catch(e){(0,o.default)(u,e)}}function u(e){throw e}t.exports=r.default},{"./internal/initialParams":31,"./internal/setImmediate":37,"lodash/isObject":225}],21:[function(e,t,r){(function(e,n){!function(e,n){"object"==typeof r&&void 0!==t?n(r):"function"==typeof define&&define.amd?define(["exports"],n):n(e.async=e.async||{})}(this,function(r){"use strict";function i(e,t){t|=0;for(var r=Math.max(e.length-t,0),n=Array(r),i=0;i-1&&e%1==0&&e<=L}function D(e){return null!=e&&O(e.length)&&!function(e){if(!s(e))return!1;var t=B(e);return t==C||t==N||t==P||t==R}(e)}var F={};function q(){}function H(e){return function(){if(null!==e){var t=e;e=null,t.apply(this,arguments)}}}var z="function"==typeof Symbol&&Symbol.iterator,K=function(e){return z&&e[z]&&e[z]()};function V(e){return null!=e&&"object"==typeof e}var G="[object Arguments]";function W(e){return V(e)&&B(e)==G}var Y=Object.prototype,X=Y.hasOwnProperty,Z=Y.propertyIsEnumerable,J=W(function(){return arguments}())?W:function(e){return V(e)&&X.call(e,"callee")&&!Z.call(e,"callee")},$=Array.isArray;var Q="object"==typeof r&&r&&!r.nodeType&&r,ee=Q&&"object"==typeof t&&t&&!t.nodeType&&t,te=ee&&ee.exports===Q?A.Buffer:void 0,re=(te?te.isBuffer:void 0)||function(){return!1},ne=9007199254740991,ie=/^(?:0|[1-9]\d*)$/;function oe(e,t){return!!(t=null==t?ne:t)&&("number"==typeof e||ie.test(e))&&e>-1&&e%1==0&&e2&&(n=i(arguments,1)),t){var c={};Fe(o,function(e,t){c[t]=e}),c[e]=n,s=!0,u=Object.create(null),r(t,c)}else o[e]=n,Le(u[e]||[],function(e){e()}),d()});a++;var c=v(t[t.length-1]);t.length>1?c(o,n):c(n)}(e,t)})}function d(){if(0===c.length&&0===a)return r(null,o);for(;c.length&&a=0&&r.push(n)}),r}Fe(e,function(t,r){if(!$(t))return l(r,[t]),void f.push(r);var n=t.slice(0,t.length-1),i=n.length;if(0===i)return l(r,t),void f.push(r);h[r]=i,Le(n,function(o){if(!e[o])throw new Error("async.auto task `"+r+"` has a non-existent dependency `"+o+"` in "+n.join(", "));!function(e,t){var r=u[e];r||(r=u[e]=[]);r.push(t)}(o,function(){0===--i&&l(r,t)})})}),function(){var e,t=0;for(;f.length;)e=f.pop(),t++,Le(p(e),function(e){0==--h[e]&&f.push(e)});if(t!==n)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}(),d()};function Ke(e,t){for(var r=-1,n=null==e?0:e.length,i=Array(n);++r=n?e:function(e,t,r){var n=-1,i=e.length;t<0&&(t=-t>i?0:i+t),(r=r>i?i:r)<0&&(r+=i),i=t>r?0:r-t>>>0,t>>>=0;for(var o=Array(i);++n-1;);return r}(i,o),function(e,t){for(var r=e.length;r--&&He(t,e[r],0)>-1;);return r}(i,o)+1).join("")}var ht=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,lt=/,/,dt=/(=.+)?(\s*)$/,pt=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;function bt(e,t){var r={};Fe(e,function(e,t){var n,i,o=m(e),a=!o&&1===e.length||o&&0===e.length;if($(e))n=e.slice(0,-1),e=e[e.length-1],r[t]=n.concat(n.length>0?s:e);else if(a)r[t]=e;else{if(n=i=(i=(i=(i=(i=e).toString().replace(pt,"")).match(ht)[2].replace(" ",""))?i.split(lt):[]).map(function(e){return ft(e.replace(dt,""))}),0===e.length&&!o&&0===n.length)throw new Error("autoInject task functions require explicit parameters.");o||n.pop(),r[t]=n.concat(s)}function s(t,r){var i=Ke(n,function(e){return t[e]});i.push(r),v(e).apply(null,i)}}),ze(r,t)}function yt(){this.head=this.tail=null,this.length=0}function mt(e,t){e.length=1,e.head=e.tail=t}function vt(e,t,r){if(null==t)t=1;else if(0===t)throw new Error("Concurrency must not be zero");var n=v(e),i=0,o=[],a=!1;function s(e,t,r){if(null!=r&&"function"!=typeof r)throw new Error("task callback must be a function");if(f.started=!0,$(e)||(e=[e]),0===e.length&&f.idle())return l(function(){f.drain()});for(var n=0,i=e.length;n0&&o.splice(s,1),a.callback.apply(a,arguments),null!=t&&f.error(t,a.data)}i<=f.concurrency-f.buffer&&f.unsaturated(),f.idle()&&f.drain(),f.process()}}var c=!1,f={_tasks:new yt,concurrency:t,payload:r,saturated:q,unsaturated:q,buffer:t/4,empty:q,drain:q,error:q,started:!1,paused:!1,push:function(e,t){s(e,!1,t)},kill:function(){f.drain=q,f._tasks.empty()},unshift:function(e,t){s(e,!0,t)},remove:function(e){f._tasks.remove(e)},process:function(){if(!c){for(c=!0;!f.paused&&i2&&(o=i(arguments,1)),n[t]=o,r(e)})},function(e){r(e,n)})}function br(e,t){pr(Ie,e,t)}function yr(e,t,r){pr(Ee(t),e,r)}var mr=function(e,t){var r=v(e);return vt(function(e,t){r(e[0],t)},t,1)},vr=function(e,t){var r=mr(e,t);return r.push=function(e,t,n){if(null==n&&(n=q),"function"!=typeof n)throw new Error("task callback must be a function");if(r.started=!0,$(e)||(e=[e]),0===e.length)return l(function(){r.drain()});t=t||0;for(var i=r._tasks.head;i&&t>=i.priority;)i=i.next;for(var o=0,a=e.length;on?1:0}je(e,function(e,t){n(e,function(r,n){if(r)return t(r);t(null,{value:e,criteria:n})})},function(e,t){if(e)return r(e);r(null,Ke(t.sort(i),Zt("value")))})}function Nr(e,t,r){var n=v(e);return a(function(i,o){var a,s=!1;i.push(function(){s||(o.apply(null,arguments),clearTimeout(a))}),a=setTimeout(function(){var t=e.name||"anonymous",n=new Error('Callback function "'+t+'" timed out.');n.code="ETIMEDOUT",r&&(n.info=r),s=!0,o(n)},t),n.apply(null,i)})}var Rr=Math.ceil,Lr=Math.max;function Or(e,t,r,n){var i=v(r);Ce(function(e,t,r,n){for(var i=-1,o=Lr(Rr((t-e)/(r||1)),0),a=Array(o);o--;)a[n?o:++i]=e,e+=r;return a}(0,e,1),t,i,n)}var Dr=ke(Or,1/0),Fr=ke(Or,1);function qr(e,t,r,n){arguments.length<=3&&(n=r,r=t,t=$(e)?[]:{}),n=H(n||q);var i=v(r);Ie(e,function(e,r,n){i(t,e,r,n)},function(e){n(e,t)})}function Hr(e,t){var r,n=null;t=t||q,Kt(e,function(e,t){v(e)(function(e,o){r=arguments.length>2?i(arguments,1):o,n=e,t(!e)})},function(){t(n,r)})}function zr(e){return function(){return(e.unmemoized||e).apply(null,arguments)}}function Kr(e,t,r){r=Ae(r||q);var n=v(t);if(!e())return r(null);var o=function(t){if(t)return r(t);if(e())return n(o);var a=i(arguments,1);r.apply(null,[null].concat(a))};n(o)}function Vr(e,t,r){Kr(function(){return!e.apply(this,arguments)},t,r)}var Gr=function(e,t){if(t=H(t||q),!$(e))return t(new Error("First argument to waterfall must be an array of functions"));if(!e.length)return t();var r=0;function n(t){var n=v(e[r++]);t.push(Ae(o)),n.apply(null,t)}function o(o){if(o||r===e.length)return t.apply(null,arguments);n(i(arguments,1))}n([])},Wr={apply:o,applyEach:Be,applyEachSeries:Re,asyncify:d,auto:ze,autoInject:bt,cargo:gt,compose:Et,concat:St,concatLimit:kt,concatSeries:Mt,constant:It,detect:Bt,detectLimit:Pt,detectSeries:Ct,dir:Rt,doDuring:Lt,doUntil:Dt,doWhilst:Ot,during:Ft,each:Ht,eachLimit:zt,eachOf:Ie,eachOfLimit:xe,eachOfSeries:wt,eachSeries:Kt,ensureAsync:Vt,every:Wt,everyLimit:Yt,everySeries:Xt,filter:er,filterLimit:tr,filterSeries:rr,forever:nr,groupBy:or,groupByLimit:ir,groupBySeries:ar,log:sr,map:je,mapLimit:Ce,mapSeries:Ne,mapValues:cr,mapValuesLimit:ur,mapValuesSeries:fr,memoize:lr,nextTick:dr,parallel:br,parallelLimit:yr,priorityQueue:vr,queue:mr,race:gr,reduce:_t,reduceRight:wr,reflect:_r,reflectAll:Ar,reject:xr,rejectLimit:kr,rejectSeries:Sr,retry:Ir,retryable:Tr,seq:At,series:Ur,setImmediate:l,some:jr,someLimit:Br,someSeries:Pr,sortBy:Cr,timeout:Nr,times:Dr,timesLimit:Or,timesSeries:Fr,transform:qr,tryEach:Hr,unmemoize:zr,until:Vr,waterfall:Gr,whilst:Kr,all:Wt,allLimit:Yt,allSeries:Xt,any:jr,anyLimit:Br,anySeries:Pr,find:Bt,findLimit:Pt,findSeries:Ct,forEach:Ht,forEachSeries:Kt,forEachLimit:zt,forEachOf:Ie,forEachOfSeries:wt,forEachOfLimit:xe,inject:_t,foldl:_t,foldr:wr,select:er,selectLimit:tr,selectSeries:rr,wrapSync:d};r.default=Wr,r.apply=o,r.applyEach=Be,r.applyEachSeries=Re,r.asyncify=d,r.auto=ze,r.autoInject=bt,r.cargo=gt,r.compose=Et,r.concat=St,r.concatLimit=kt,r.concatSeries=Mt,r.constant=It,r.detect=Bt,r.detectLimit=Pt,r.detectSeries=Ct,r.dir=Rt,r.doDuring=Lt,r.doUntil=Dt,r.doWhilst=Ot,r.during=Ft,r.each=Ht,r.eachLimit=zt,r.eachOf=Ie,r.eachOfLimit=xe,r.eachOfSeries=wt,r.eachSeries=Kt,r.ensureAsync=Vt,r.every=Wt,r.everyLimit=Yt,r.everySeries=Xt,r.filter=er,r.filterLimit=tr,r.filterSeries=rr,r.forever=nr,r.groupBy=or,r.groupByLimit=ir,r.groupBySeries=ar,r.log=sr,r.map=je,r.mapLimit=Ce,r.mapSeries=Ne,r.mapValues=cr,r.mapValuesLimit=ur,r.mapValuesSeries=fr,r.memoize=lr,r.nextTick=dr,r.parallel=br,r.parallelLimit=yr,r.priorityQueue=vr,r.queue=mr,r.race=gr,r.reduce=_t,r.reduceRight=wr,r.reflect=_r,r.reflectAll=Ar,r.reject=xr,r.rejectLimit=kr,r.rejectSeries=Sr,r.retry=Ir,r.retryable=Tr,r.seq=At,r.series=Ur,r.setImmediate=l,r.some=jr,r.someLimit=Br,r.someSeries=Pr,r.sortBy=Cr,r.timeout=Nr,r.times=Dr,r.timesLimit=Or,r.timesSeries=Fr,r.transform=qr,r.tryEach=Hr,r.unmemoize=zr,r.until=Vr,r.waterfall=Gr,r.whilst=Kr,r.all=Wt,r.allLimit=Yt,r.allSeries=Xt,r.any=jr,r.anyLimit=Br,r.anySeries=Pr,r.find=Bt,r.findLimit=Pt,r.findSeries=Ct,r.forEach=Ht,r.forEachSeries=Kt,r.forEachLimit=zt,r.forEachOf=Ie,r.forEachOfSeries=wt,r.forEachOfLimit=xe,r.inject=_t,r.foldl=_t,r.foldr=wr,r.select=er,r.selectLimit=tr,r.selectSeries=rr,r.wrapSync=d,Object.defineProperty(r,"__esModule",{value:!0})})}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:257}],22:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t,r,a){(0,n.default)(t)(e,(0,i.default)((0,o.default)(r)),a)};var n=a(e("./internal/eachOfLimit")),i=a(e("./internal/withoutIndex")),o=a(e("./internal/wrapAsync"));function a(e){return e&&e.__esModule?e:{default:e}}t.exports=r.default},{"./internal/eachOfLimit":29,"./internal/withoutIndex":39,"./internal/wrapAsync":40}],23:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t,r){((0,n.default)(e)?l:d)(e,(0,f.default)(t),r)};var n=h(e("lodash/isArrayLike")),i=h(e("./internal/breakLoop")),o=h(e("./eachOfLimit")),a=h(e("./internal/doLimit")),s=h(e("lodash/noop")),u=h(e("./internal/once")),c=h(e("./internal/onlyOnce")),f=h(e("./internal/wrapAsync"));function h(e){return e&&e.__esModule?e:{default:e}}function l(e,t,r){r=(0,u.default)(r||s.default);var n=0,o=0,a=e.length;function f(e,t){e?r(e):++o!==a&&t!==i.default||r(null)}for(0===a&&r(null);n2&&(n=(0,o.default)(arguments,1)),s[t]=n,r(e)})},function(e){r(e,s)})};var n=s(e("lodash/noop")),i=s(e("lodash/isArrayLike")),o=s(e("./slice")),a=s(e("./wrapAsync"));function s(e){return e&&e.__esModule?e:{default:e}}t.exports=r.default},{"./slice":38,"./wrapAsync":40,"lodash/isArrayLike":221,"lodash/noop":229}],37:[function(e,t,r){(function(t){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.hasNextTick=r.hasSetImmediate=void 0,r.fallback=c,r.wrap=f;var n,i=e("./slice"),o=(n=i)&&n.__esModule?n:{default:n};var a,s=r.hasSetImmediate="function"==typeof setImmediate&&setImmediate,u=r.hasNextTick="object"==typeof t&&"function"==typeof t.nextTick;function c(e){setTimeout(e,0)}function f(e){return function(t){var r=(0,o.default)(arguments,1);e(function(){t.apply(null,r)})}}a=s?setImmediate:u?t.nextTick:c,r.default=f(a)}).call(this,e("_process"))},{"./slice":38,_process:257}],38:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){t|=0;for(var r=Math.max(e.length-t,0),n=Array(r),i=0;i0,"Expected a maximum number of retry greater than 0 but got %s.",e),this.maxNumberOfRetry_=e},o.prototype.backoff=function(e){i.checkState(-1===this.timeoutID_,"Backoff in progress."),this.backoffNumber_===this.maxNumberOfRetry_?(this.emit("fail",e),this.reset()):(this.backoffDelay_=this.backoffStrategy_.next(),this.timeoutID_=setTimeout(this.handlers.backoff,this.backoffDelay_),this.emit("backoff",this.backoffNumber_,this.backoffDelay_,e))},o.prototype.onBackoff_=function(){this.timeoutID_=-1,this.emit("ready",this.backoffNumber_,this.backoffDelay_),this.backoffNumber_++},o.prototype.reset=function(){this.backoffNumber_=0,this.backoffStrategy_.reset(),clearTimeout(this.timeoutID_),this.timeoutID_=-1},t.exports=o},{events:157,precond:253,util:333}],47:[function(e,t,r){var n=e("events"),i=e("precond"),o=e("util"),a=e("./backoff"),s=e("./strategy/fibonacci");function u(e,t,r){n.EventEmitter.call(this),i.checkIsFunction(e,"Expected fn to be a function."),i.checkIsArray(t,"Expected args to be an array."),i.checkIsFunction(r,"Expected callback to be a function."),this.function_=e,this.arguments_=t,this.callback_=r,this.lastResult_=[],this.numRetries_=0,this.backoff_=null,this.strategy_=null,this.failAfter_=-1,this.retryPredicate_=u.DEFAULT_RETRY_PREDICATE_,this.state_=u.State_.PENDING}o.inherits(u,n.EventEmitter),u.State_={PENDING:0,RUNNING:1,COMPLETED:2,ABORTED:3},u.DEFAULT_RETRY_PREDICATE_=function(e){return!0},u.prototype.isPending=function(){return this.state_==u.State_.PENDING},u.prototype.isRunning=function(){return this.state_==u.State_.RUNNING},u.prototype.isCompleted=function(){return this.state_==u.State_.COMPLETED},u.prototype.isAborted=function(){return this.state_==u.State_.ABORTED},u.prototype.setStrategy=function(e){return i.checkState(this.isPending(),"FunctionCall in progress."),this.strategy_=e,this},u.prototype.retryIf=function(e){return i.checkState(this.isPending(),"FunctionCall in progress."),this.retryPredicate_=e,this},u.prototype.getLastResult=function(){return this.lastResult_.concat()},u.prototype.getNumRetries=function(){return this.numRetries_},u.prototype.failAfter=function(e){return i.checkState(this.isPending(),"FunctionCall in progress."),this.failAfter_=e,this},u.prototype.abort=function(){this.isCompleted()||this.isAborted()||(this.isRunning()&&this.backoff_.reset(),this.state_=u.State_.ABORTED,this.lastResult_=[new Error("Backoff aborted.")],this.emit("abort"),this.doCallback_())},u.prototype.start=function(e){i.checkState(!this.isAborted(),"FunctionCall is aborted."),i.checkState(this.isPending(),"FunctionCall already started.");var t=this.strategy_||new s;this.backoff_=e?e(t):new a(t),this.backoff_.on("ready",this.doCall_.bind(this,!0)),this.backoff_.on("fail",this.doCallback_.bind(this)),this.backoff_.on("backoff",this.handleBackoff_.bind(this)),this.failAfter_>0&&this.backoff_.failAfter(this.failAfter_),this.state_=u.State_.RUNNING,this.doCall_(!1)},u.prototype.doCall_=function(e){e&&this.numRetries_++;var t=["call"].concat(this.arguments_);n.EventEmitter.prototype.emit.apply(this,t);var r=this.handleFunctionCallback_.bind(this);this.function_.apply(null,this.arguments_.concat(r))},u.prototype.doCallback_=function(){this.callback_.apply(null,this.lastResult_)},u.prototype.handleFunctionCallback_=function(){if(!this.isAborted()){var e=Array.prototype.slice.call(arguments);this.lastResult_=e,n.EventEmitter.prototype.emit.apply(this,["callback"].concat(e));var t=e[0];t&&this.retryPredicate_(t)?this.backoff_.backoff(t):(this.state_=u.State_.COMPLETED,this.doCallback_())}},u.prototype.handleBackoff_=function(e,t,r){this.emit("backoff",e,t,r)},t.exports=u},{"./backoff":46,"./strategy/fibonacci":49,events:157,precond:253,util:333}],48:[function(e,t,r){var n=e("util"),i=e("precond"),o=e("./strategy");function a(e){o.call(this,e),this.backoffDelay_=0,this.nextBackoffDelay_=this.getInitialDelay(),this.factor_=a.DEFAULT_FACTOR,e&&void 0!==e.factor&&(i.checkArgument(e.factor>1,"Exponential factor should be greater than 1 but got %s.",e.factor),this.factor_=e.factor)}n.inherits(a,o),a.DEFAULT_FACTOR=2,a.prototype.next_=function(){return this.backoffDelay_=Math.min(this.nextBackoffDelay_,this.getMaxDelay()),this.nextBackoffDelay_=this.backoffDelay_*this.factor_,this.backoffDelay_},a.prototype.reset_=function(){this.backoffDelay_=0,this.nextBackoffDelay_=this.getInitialDelay()},t.exports=a},{"./strategy":50,precond:253,util:333}],49:[function(e,t,r){var n=e("util"),i=e("./strategy");function o(e){i.call(this,e),this.backoffDelay_=0,this.nextBackoffDelay_=this.getInitialDelay()}n.inherits(o,i),o.prototype.next_=function(){var e=Math.min(this.nextBackoffDelay_,this.getMaxDelay());return this.nextBackoffDelay_+=this.backoffDelay_,this.backoffDelay_=e,e},o.prototype.reset_=function(){this.nextBackoffDelay_=this.getInitialDelay(),this.backoffDelay_=0},t.exports=o},{"./strategy":50,util:333}],50:[function(e,t,r){e("events"),e("util");function n(e){return null!=e}function i(e){if(n((e=e||{}).initialDelay)&&e.initialDelay<1)throw new Error("The initial timeout must be greater than 0.");if(n(e.maxDelay)&&e.maxDelay<1)throw new Error("The maximal timeout must be greater than 0.");if(this.initialDelay_=e.initialDelay||100,this.maxDelay_=e.maxDelay||1e4,this.maxDelay_<=this.initialDelay_)throw new Error("The maximal backoff delay must be greater than the initial backoff delay.");if(n(e.randomisationFactor)&&(e.randomisationFactor<0||e.randomisationFactor>1))throw new Error("The randomisation factor must be between 0 and 1.");this.randomisationFactor_=e.randomisationFactor||0}i.prototype.getMaxDelay=function(){return this.maxDelay_},i.prototype.getInitialDelay=function(){return this.initialDelay_},i.prototype.next=function(){var e=this.next_(),t=1+Math.random()*this.randomisationFactor_;return Math.round(e*t)},i.prototype.next_=function(){throw new Error("BackoffStrategy.next_() unimplemented.")},i.prototype.reset=function(){this.reset_()},i.prototype.reset_=function(){throw new Error("BackoffStrategy.reset_() unimplemented.")},t.exports=i},{events:157,util:333}],51:[function(e,t,r){"use strict";r.byteLength=function(e){return 3*e.length/4-c(e)},r.toByteArray=function(e){var t,r,n,a,s,u=e.length;a=c(e),s=new o(3*u/4-a),r=a>0?u-4:u;var f=0;for(t=0;t>16&255,s[f++]=n>>8&255,s[f++]=255&n;2===a?(n=i[e.charCodeAt(t)]<<2|i[e.charCodeAt(t+1)]>>4,s[f++]=255&n):1===a&&(n=i[e.charCodeAt(t)]<<10|i[e.charCodeAt(t+1)]<<4|i[e.charCodeAt(t+2)]>>2,s[f++]=n>>8&255,s[f++]=255&n);return s},r.fromByteArray=function(e){for(var t,r=e.length,i=r%3,o="",a=[],s=0,u=r-i;su?u:s+16383));1===i?(t=e[r-1],o+=n[t>>2],o+=n[t<<4&63],o+="=="):2===i&&(t=(e[r-2]<<8)+e[r-1],o+=n[t>>10],o+=n[t>>4&63],o+=n[t<<2&63],o+="=");return a.push(o),a.join("")};for(var n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,u=a.length;s0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===e[t-2]?2:"="===e[t-1]?1:0}function f(e,t,r){for(var i,o,a=[],s=t;s>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return a.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},{}],52:[function(e,t,r){var n=e("safe-buffer").Buffer;t.exports={check:function(e){if(e.length<8)return!1;if(e.length>72)return!1;if(48!==e[0])return!1;if(e[1]!==e.length-2)return!1;if(2!==e[2])return!1;var t=e[3];if(0===t)return!1;if(5+t>=e.length)return!1;if(2!==e[4+t])return!1;var r=e[5+t];return!(0===r||6+t+r!==e.length||128&e[4]||t>1&&0===e[4]&&!(128&e[5])||128&e[t+6]||r>1&&0===e[t+6]&&!(128&e[t+7]))},decode:function(e){if(e.length<8)throw new Error("DER sequence length is too short");if(e.length>72)throw new Error("DER sequence length is too long");if(48!==e[0])throw new Error("Expected DER sequence");if(e[1]!==e.length-2)throw new Error("DER sequence length is invalid");if(2!==e[2])throw new Error("Expected DER integer");var t=e[3];if(0===t)throw new Error("R length is zero");if(5+t>=e.length)throw new Error("R length is too long");if(2!==e[4+t])throw new Error("Expected DER integer (2)");var r=e[5+t];if(0===r)throw new Error("S length is zero");if(6+t+r!==e.length)throw new Error("S length is invalid");if(128&e[4])throw new Error("R value is negative");if(t>1&&0===e[4]&&!(128&e[5]))throw new Error("R value excessively padded");if(128&e[t+6])throw new Error("S value is negative");if(r>1&&0===e[t+6]&&!(128&e[t+7]))throw new Error("S value excessively padded");return{r:e.slice(4,4+t),s:e.slice(6+t)}},encode:function(e,t){var r=e.length,i=t.length;if(0===r)throw new Error("R length is zero");if(0===i)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(i>33)throw new Error("S length is too long");if(128&e[0])throw new Error("R value is negative");if(128&t[0])throw new Error("S value is negative");if(r>1&&0===e[0]&&!(128&e[1]))throw new Error("R value excessively padded");if(i>1&&0===t[0]&&!(128&t[1]))throw new Error("S value excessively padded");var o=n.allocUnsafe(6+r+i);return o[0]=48,o[1]=o.length-2,o[2]=2,o[3]=e.length,e.copy(o,4),o[4+r]=2,o[5+r]=t.length,t.copy(o,6+r),o}}},{"safe-buffer":290}],53:[function(e,t,r){!function(t,r){"use strict";function n(e,t){if(!e)throw new Error(t||"Assertion failed")}function i(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}function o(e,t,r){if(o.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(r=t,t=10),this._init(e||0,t||10,r||"be"))}var a;"object"==typeof t?t.exports=o:r.BN=o,o.BN=o,o.wordSize=26;try{a=e("buffer").Buffer}catch(e){}function s(e,t,r){for(var n=0,i=Math.min(e.length,r),o=t;o=49&&a<=54?a-49+10:a>=17&&a<=22?a-17+10:15&a}return n}function u(e,t,r,n){for(var i=0,o=Math.min(e.length,r),a=t;a=49?s-49+10:s>=17?s-17+10:s}return i}o.isBN=function(e){return e instanceof o||null!==e&&"object"==typeof e&&e.constructor.wordSize===o.wordSize&&Array.isArray(e.words)},o.max=function(e,t){return e.cmp(t)>0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&i++,16===t?this._parseHex(e,i):this._parseBase(e,t,i),"-"===e[0]&&(this.negative=1),this.strip(),"le"===r&&this._initArray(this.toArray(),t,r)},o.prototype._initNumber=function(e,t,r){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(n(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===r&&this._initArray(this.toArray(),t,r)},o.prototype._initArray=function(e,t,r){if(n("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3)a=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[o]|=a<>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);else if("le"===r)for(i=0,o=0;i>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);return this.strip()},o.prototype._parseHex=function(e,t){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var r=0;r=t;r-=6)i=s(e,r,r+6),this.words[n]|=i<>>26-o&4194303,(o+=24)>=26&&(o-=26,n++);r+6!==t&&(i=s(e,t,r+6),this.words[n]|=i<>>26-o&4194303),this.strip()},o.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=t)n++;n--,i=i/t|0;for(var o=e.length-r,a=o%n,s=Math.min(o,o-a)+r,c=0,f=r;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},o.prototype.inspect=function(){return(this.red?""};var c=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],f=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],h=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(e,t,r){r.negative=t.negative^e.negative;var n=e.length+t.length|0;r.length=n,n=n-1|0;var i=0|e.words[0],o=0|t.words[0],a=i*o,s=67108863&a,u=a/67108864|0;r.words[0]=s;for(var c=1;c>>26,h=67108863&u,l=Math.min(c,t.length-1),d=Math.max(0,c-e.length+1);d<=l;d++){var p=c-d|0;f+=(a=(i=0|e.words[p])*(o=0|t.words[d])+h)/67108864|0,h=67108863&a}r.words[c]=0|h,u=0|f}return 0!==u?r.words[c]=0|u:r.length--,r.strip()}o.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var i=0,o=0,a=0;a>>24-i&16777215)||a!==this.length-1?c[6-u.length]+u+r:u+r,(i+=2)>=26&&(i-=26,a--)}for(0!==o&&(r=o.toString(16)+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var l=f[e],d=h[e];r="";var p=this.clone();for(p.negative=0;!p.isZero();){var b=p.modn(d).toString(e);r=(p=p.idivn(d)).isZero()?b+r:c[l-b.length]+b+r}for(this.isZero()&&(r="0"+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16)},o.prototype.toBuffer=function(e,t){return n(void 0!==a),this.toArrayLike(a,e,t)},o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},o.prototype.toArrayLike=function(e,t,r){var i=this.byteLength(),o=r||Math.max(1,i);n(i<=o,"byte array longer than desired length"),n(o>0,"Requested array length <= 0"),this.strip();var a,s,u="le"===t,c=new e(o),f=this.clone();if(u){for(s=0;!f.isZero();s++)a=f.andln(255),f.iushrn(8),c[s]=a;for(;s=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;re.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,r;this.length>e.length?(t=this,r=e):(t=e,r=this);for(var n=0;ne.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-r),this.strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,i=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<e.length?(r=this,n=e):(r=e,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;oe.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var r,n,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=e):(r=e,n=this);for(var o=0,a=0;a>26,this.words[a]=67108863&t;for(;0!==o&&a>26,this.words[a]=67108863&t;if(0===o&&a>>13,d=0|a[1],p=8191&d,b=d>>>13,y=0|a[2],m=8191&y,v=y>>>13,g=0|a[3],w=8191&g,_=g>>>13,A=0|a[4],E=8191&A,x=A>>>13,k=0|a[5],S=8191&k,M=k>>>13,I=0|a[6],T=8191&I,U=I>>>13,j=0|a[7],B=8191&j,P=j>>>13,C=0|a[8],N=8191&C,R=C>>>13,L=0|a[9],O=8191&L,D=L>>>13,F=0|s[0],q=8191&F,H=F>>>13,z=0|s[1],K=8191&z,V=z>>>13,G=0|s[2],W=8191&G,Y=G>>>13,X=0|s[3],Z=8191&X,J=X>>>13,$=0|s[4],Q=8191&$,ee=$>>>13,te=0|s[5],re=8191&te,ne=te>>>13,ie=0|s[6],oe=8191&ie,ae=ie>>>13,se=0|s[7],ue=8191&se,ce=se>>>13,fe=0|s[8],he=8191&fe,le=fe>>>13,de=0|s[9],pe=8191&de,be=de>>>13;r.negative=e.negative^t.negative,r.length=19;var ye=(c+(n=Math.imul(h,q))|0)+((8191&(i=(i=Math.imul(h,H))+Math.imul(l,q)|0))<<13)|0;c=((o=Math.imul(l,H))+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,n=Math.imul(p,q),i=(i=Math.imul(p,H))+Math.imul(b,q)|0,o=Math.imul(b,H);var me=(c+(n=n+Math.imul(h,K)|0)|0)+((8191&(i=(i=i+Math.imul(h,V)|0)+Math.imul(l,K)|0))<<13)|0;c=((o=o+Math.imul(l,V)|0)+(i>>>13)|0)+(me>>>26)|0,me&=67108863,n=Math.imul(m,q),i=(i=Math.imul(m,H))+Math.imul(v,q)|0,o=Math.imul(v,H),n=n+Math.imul(p,K)|0,i=(i=i+Math.imul(p,V)|0)+Math.imul(b,K)|0,o=o+Math.imul(b,V)|0;var ve=(c+(n=n+Math.imul(h,W)|0)|0)+((8191&(i=(i=i+Math.imul(h,Y)|0)+Math.imul(l,W)|0))<<13)|0;c=((o=o+Math.imul(l,Y)|0)+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,n=Math.imul(w,q),i=(i=Math.imul(w,H))+Math.imul(_,q)|0,o=Math.imul(_,H),n=n+Math.imul(m,K)|0,i=(i=i+Math.imul(m,V)|0)+Math.imul(v,K)|0,o=o+Math.imul(v,V)|0,n=n+Math.imul(p,W)|0,i=(i=i+Math.imul(p,Y)|0)+Math.imul(b,W)|0,o=o+Math.imul(b,Y)|0;var ge=(c+(n=n+Math.imul(h,Z)|0)|0)+((8191&(i=(i=i+Math.imul(h,J)|0)+Math.imul(l,Z)|0))<<13)|0;c=((o=o+Math.imul(l,J)|0)+(i>>>13)|0)+(ge>>>26)|0,ge&=67108863,n=Math.imul(E,q),i=(i=Math.imul(E,H))+Math.imul(x,q)|0,o=Math.imul(x,H),n=n+Math.imul(w,K)|0,i=(i=i+Math.imul(w,V)|0)+Math.imul(_,K)|0,o=o+Math.imul(_,V)|0,n=n+Math.imul(m,W)|0,i=(i=i+Math.imul(m,Y)|0)+Math.imul(v,W)|0,o=o+Math.imul(v,Y)|0,n=n+Math.imul(p,Z)|0,i=(i=i+Math.imul(p,J)|0)+Math.imul(b,Z)|0,o=o+Math.imul(b,J)|0;var we=(c+(n=n+Math.imul(h,Q)|0)|0)+((8191&(i=(i=i+Math.imul(h,ee)|0)+Math.imul(l,Q)|0))<<13)|0;c=((o=o+Math.imul(l,ee)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,n=Math.imul(S,q),i=(i=Math.imul(S,H))+Math.imul(M,q)|0,o=Math.imul(M,H),n=n+Math.imul(E,K)|0,i=(i=i+Math.imul(E,V)|0)+Math.imul(x,K)|0,o=o+Math.imul(x,V)|0,n=n+Math.imul(w,W)|0,i=(i=i+Math.imul(w,Y)|0)+Math.imul(_,W)|0,o=o+Math.imul(_,Y)|0,n=n+Math.imul(m,Z)|0,i=(i=i+Math.imul(m,J)|0)+Math.imul(v,Z)|0,o=o+Math.imul(v,J)|0,n=n+Math.imul(p,Q)|0,i=(i=i+Math.imul(p,ee)|0)+Math.imul(b,Q)|0,o=o+Math.imul(b,ee)|0;var _e=(c+(n=n+Math.imul(h,re)|0)|0)+((8191&(i=(i=i+Math.imul(h,ne)|0)+Math.imul(l,re)|0))<<13)|0;c=((o=o+Math.imul(l,ne)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,n=Math.imul(T,q),i=(i=Math.imul(T,H))+Math.imul(U,q)|0,o=Math.imul(U,H),n=n+Math.imul(S,K)|0,i=(i=i+Math.imul(S,V)|0)+Math.imul(M,K)|0,o=o+Math.imul(M,V)|0,n=n+Math.imul(E,W)|0,i=(i=i+Math.imul(E,Y)|0)+Math.imul(x,W)|0,o=o+Math.imul(x,Y)|0,n=n+Math.imul(w,Z)|0,i=(i=i+Math.imul(w,J)|0)+Math.imul(_,Z)|0,o=o+Math.imul(_,J)|0,n=n+Math.imul(m,Q)|0,i=(i=i+Math.imul(m,ee)|0)+Math.imul(v,Q)|0,o=o+Math.imul(v,ee)|0,n=n+Math.imul(p,re)|0,i=(i=i+Math.imul(p,ne)|0)+Math.imul(b,re)|0,o=o+Math.imul(b,ne)|0;var Ae=(c+(n=n+Math.imul(h,oe)|0)|0)+((8191&(i=(i=i+Math.imul(h,ae)|0)+Math.imul(l,oe)|0))<<13)|0;c=((o=o+Math.imul(l,ae)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,n=Math.imul(B,q),i=(i=Math.imul(B,H))+Math.imul(P,q)|0,o=Math.imul(P,H),n=n+Math.imul(T,K)|0,i=(i=i+Math.imul(T,V)|0)+Math.imul(U,K)|0,o=o+Math.imul(U,V)|0,n=n+Math.imul(S,W)|0,i=(i=i+Math.imul(S,Y)|0)+Math.imul(M,W)|0,o=o+Math.imul(M,Y)|0,n=n+Math.imul(E,Z)|0,i=(i=i+Math.imul(E,J)|0)+Math.imul(x,Z)|0,o=o+Math.imul(x,J)|0,n=n+Math.imul(w,Q)|0,i=(i=i+Math.imul(w,ee)|0)+Math.imul(_,Q)|0,o=o+Math.imul(_,ee)|0,n=n+Math.imul(m,re)|0,i=(i=i+Math.imul(m,ne)|0)+Math.imul(v,re)|0,o=o+Math.imul(v,ne)|0,n=n+Math.imul(p,oe)|0,i=(i=i+Math.imul(p,ae)|0)+Math.imul(b,oe)|0,o=o+Math.imul(b,ae)|0;var Ee=(c+(n=n+Math.imul(h,ue)|0)|0)+((8191&(i=(i=i+Math.imul(h,ce)|0)+Math.imul(l,ue)|0))<<13)|0;c=((o=o+Math.imul(l,ce)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,n=Math.imul(N,q),i=(i=Math.imul(N,H))+Math.imul(R,q)|0,o=Math.imul(R,H),n=n+Math.imul(B,K)|0,i=(i=i+Math.imul(B,V)|0)+Math.imul(P,K)|0,o=o+Math.imul(P,V)|0,n=n+Math.imul(T,W)|0,i=(i=i+Math.imul(T,Y)|0)+Math.imul(U,W)|0,o=o+Math.imul(U,Y)|0,n=n+Math.imul(S,Z)|0,i=(i=i+Math.imul(S,J)|0)+Math.imul(M,Z)|0,o=o+Math.imul(M,J)|0,n=n+Math.imul(E,Q)|0,i=(i=i+Math.imul(E,ee)|0)+Math.imul(x,Q)|0,o=o+Math.imul(x,ee)|0,n=n+Math.imul(w,re)|0,i=(i=i+Math.imul(w,ne)|0)+Math.imul(_,re)|0,o=o+Math.imul(_,ne)|0,n=n+Math.imul(m,oe)|0,i=(i=i+Math.imul(m,ae)|0)+Math.imul(v,oe)|0,o=o+Math.imul(v,ae)|0,n=n+Math.imul(p,ue)|0,i=(i=i+Math.imul(p,ce)|0)+Math.imul(b,ue)|0,o=o+Math.imul(b,ce)|0;var xe=(c+(n=n+Math.imul(h,he)|0)|0)+((8191&(i=(i=i+Math.imul(h,le)|0)+Math.imul(l,he)|0))<<13)|0;c=((o=o+Math.imul(l,le)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,n=Math.imul(O,q),i=(i=Math.imul(O,H))+Math.imul(D,q)|0,o=Math.imul(D,H),n=n+Math.imul(N,K)|0,i=(i=i+Math.imul(N,V)|0)+Math.imul(R,K)|0,o=o+Math.imul(R,V)|0,n=n+Math.imul(B,W)|0,i=(i=i+Math.imul(B,Y)|0)+Math.imul(P,W)|0,o=o+Math.imul(P,Y)|0,n=n+Math.imul(T,Z)|0,i=(i=i+Math.imul(T,J)|0)+Math.imul(U,Z)|0,o=o+Math.imul(U,J)|0,n=n+Math.imul(S,Q)|0,i=(i=i+Math.imul(S,ee)|0)+Math.imul(M,Q)|0,o=o+Math.imul(M,ee)|0,n=n+Math.imul(E,re)|0,i=(i=i+Math.imul(E,ne)|0)+Math.imul(x,re)|0,o=o+Math.imul(x,ne)|0,n=n+Math.imul(w,oe)|0,i=(i=i+Math.imul(w,ae)|0)+Math.imul(_,oe)|0,o=o+Math.imul(_,ae)|0,n=n+Math.imul(m,ue)|0,i=(i=i+Math.imul(m,ce)|0)+Math.imul(v,ue)|0,o=o+Math.imul(v,ce)|0,n=n+Math.imul(p,he)|0,i=(i=i+Math.imul(p,le)|0)+Math.imul(b,he)|0,o=o+Math.imul(b,le)|0;var ke=(c+(n=n+Math.imul(h,pe)|0)|0)+((8191&(i=(i=i+Math.imul(h,be)|0)+Math.imul(l,pe)|0))<<13)|0;c=((o=o+Math.imul(l,be)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,n=Math.imul(O,K),i=(i=Math.imul(O,V))+Math.imul(D,K)|0,o=Math.imul(D,V),n=n+Math.imul(N,W)|0,i=(i=i+Math.imul(N,Y)|0)+Math.imul(R,W)|0,o=o+Math.imul(R,Y)|0,n=n+Math.imul(B,Z)|0,i=(i=i+Math.imul(B,J)|0)+Math.imul(P,Z)|0,o=o+Math.imul(P,J)|0,n=n+Math.imul(T,Q)|0,i=(i=i+Math.imul(T,ee)|0)+Math.imul(U,Q)|0,o=o+Math.imul(U,ee)|0,n=n+Math.imul(S,re)|0,i=(i=i+Math.imul(S,ne)|0)+Math.imul(M,re)|0,o=o+Math.imul(M,ne)|0,n=n+Math.imul(E,oe)|0,i=(i=i+Math.imul(E,ae)|0)+Math.imul(x,oe)|0,o=o+Math.imul(x,ae)|0,n=n+Math.imul(w,ue)|0,i=(i=i+Math.imul(w,ce)|0)+Math.imul(_,ue)|0,o=o+Math.imul(_,ce)|0,n=n+Math.imul(m,he)|0,i=(i=i+Math.imul(m,le)|0)+Math.imul(v,he)|0,o=o+Math.imul(v,le)|0;var Se=(c+(n=n+Math.imul(p,pe)|0)|0)+((8191&(i=(i=i+Math.imul(p,be)|0)+Math.imul(b,pe)|0))<<13)|0;c=((o=o+Math.imul(b,be)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,n=Math.imul(O,W),i=(i=Math.imul(O,Y))+Math.imul(D,W)|0,o=Math.imul(D,Y),n=n+Math.imul(N,Z)|0,i=(i=i+Math.imul(N,J)|0)+Math.imul(R,Z)|0,o=o+Math.imul(R,J)|0,n=n+Math.imul(B,Q)|0,i=(i=i+Math.imul(B,ee)|0)+Math.imul(P,Q)|0,o=o+Math.imul(P,ee)|0,n=n+Math.imul(T,re)|0,i=(i=i+Math.imul(T,ne)|0)+Math.imul(U,re)|0,o=o+Math.imul(U,ne)|0,n=n+Math.imul(S,oe)|0,i=(i=i+Math.imul(S,ae)|0)+Math.imul(M,oe)|0,o=o+Math.imul(M,ae)|0,n=n+Math.imul(E,ue)|0,i=(i=i+Math.imul(E,ce)|0)+Math.imul(x,ue)|0,o=o+Math.imul(x,ce)|0,n=n+Math.imul(w,he)|0,i=(i=i+Math.imul(w,le)|0)+Math.imul(_,he)|0,o=o+Math.imul(_,le)|0;var Me=(c+(n=n+Math.imul(m,pe)|0)|0)+((8191&(i=(i=i+Math.imul(m,be)|0)+Math.imul(v,pe)|0))<<13)|0;c=((o=o+Math.imul(v,be)|0)+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863,n=Math.imul(O,Z),i=(i=Math.imul(O,J))+Math.imul(D,Z)|0,o=Math.imul(D,J),n=n+Math.imul(N,Q)|0,i=(i=i+Math.imul(N,ee)|0)+Math.imul(R,Q)|0,o=o+Math.imul(R,ee)|0,n=n+Math.imul(B,re)|0,i=(i=i+Math.imul(B,ne)|0)+Math.imul(P,re)|0,o=o+Math.imul(P,ne)|0,n=n+Math.imul(T,oe)|0,i=(i=i+Math.imul(T,ae)|0)+Math.imul(U,oe)|0,o=o+Math.imul(U,ae)|0,n=n+Math.imul(S,ue)|0,i=(i=i+Math.imul(S,ce)|0)+Math.imul(M,ue)|0,o=o+Math.imul(M,ce)|0,n=n+Math.imul(E,he)|0,i=(i=i+Math.imul(E,le)|0)+Math.imul(x,he)|0,o=o+Math.imul(x,le)|0;var Ie=(c+(n=n+Math.imul(w,pe)|0)|0)+((8191&(i=(i=i+Math.imul(w,be)|0)+Math.imul(_,pe)|0))<<13)|0;c=((o=o+Math.imul(_,be)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,n=Math.imul(O,Q),i=(i=Math.imul(O,ee))+Math.imul(D,Q)|0,o=Math.imul(D,ee),n=n+Math.imul(N,re)|0,i=(i=i+Math.imul(N,ne)|0)+Math.imul(R,re)|0,o=o+Math.imul(R,ne)|0,n=n+Math.imul(B,oe)|0,i=(i=i+Math.imul(B,ae)|0)+Math.imul(P,oe)|0,o=o+Math.imul(P,ae)|0,n=n+Math.imul(T,ue)|0,i=(i=i+Math.imul(T,ce)|0)+Math.imul(U,ue)|0,o=o+Math.imul(U,ce)|0,n=n+Math.imul(S,he)|0,i=(i=i+Math.imul(S,le)|0)+Math.imul(M,he)|0,o=o+Math.imul(M,le)|0;var Te=(c+(n=n+Math.imul(E,pe)|0)|0)+((8191&(i=(i=i+Math.imul(E,be)|0)+Math.imul(x,pe)|0))<<13)|0;c=((o=o+Math.imul(x,be)|0)+(i>>>13)|0)+(Te>>>26)|0,Te&=67108863,n=Math.imul(O,re),i=(i=Math.imul(O,ne))+Math.imul(D,re)|0,o=Math.imul(D,ne),n=n+Math.imul(N,oe)|0,i=(i=i+Math.imul(N,ae)|0)+Math.imul(R,oe)|0,o=o+Math.imul(R,ae)|0,n=n+Math.imul(B,ue)|0,i=(i=i+Math.imul(B,ce)|0)+Math.imul(P,ue)|0,o=o+Math.imul(P,ce)|0,n=n+Math.imul(T,he)|0,i=(i=i+Math.imul(T,le)|0)+Math.imul(U,he)|0,o=o+Math.imul(U,le)|0;var Ue=(c+(n=n+Math.imul(S,pe)|0)|0)+((8191&(i=(i=i+Math.imul(S,be)|0)+Math.imul(M,pe)|0))<<13)|0;c=((o=o+Math.imul(M,be)|0)+(i>>>13)|0)+(Ue>>>26)|0,Ue&=67108863,n=Math.imul(O,oe),i=(i=Math.imul(O,ae))+Math.imul(D,oe)|0,o=Math.imul(D,ae),n=n+Math.imul(N,ue)|0,i=(i=i+Math.imul(N,ce)|0)+Math.imul(R,ue)|0,o=o+Math.imul(R,ce)|0,n=n+Math.imul(B,he)|0,i=(i=i+Math.imul(B,le)|0)+Math.imul(P,he)|0,o=o+Math.imul(P,le)|0;var je=(c+(n=n+Math.imul(T,pe)|0)|0)+((8191&(i=(i=i+Math.imul(T,be)|0)+Math.imul(U,pe)|0))<<13)|0;c=((o=o+Math.imul(U,be)|0)+(i>>>13)|0)+(je>>>26)|0,je&=67108863,n=Math.imul(O,ue),i=(i=Math.imul(O,ce))+Math.imul(D,ue)|0,o=Math.imul(D,ce),n=n+Math.imul(N,he)|0,i=(i=i+Math.imul(N,le)|0)+Math.imul(R,he)|0,o=o+Math.imul(R,le)|0;var Be=(c+(n=n+Math.imul(B,pe)|0)|0)+((8191&(i=(i=i+Math.imul(B,be)|0)+Math.imul(P,pe)|0))<<13)|0;c=((o=o+Math.imul(P,be)|0)+(i>>>13)|0)+(Be>>>26)|0,Be&=67108863,n=Math.imul(O,he),i=(i=Math.imul(O,le))+Math.imul(D,he)|0,o=Math.imul(D,le);var Pe=(c+(n=n+Math.imul(N,pe)|0)|0)+((8191&(i=(i=i+Math.imul(N,be)|0)+Math.imul(R,pe)|0))<<13)|0;c=((o=o+Math.imul(R,be)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863;var Ce=(c+(n=Math.imul(O,pe))|0)+((8191&(i=(i=Math.imul(O,be))+Math.imul(D,pe)|0))<<13)|0;return c=((o=Math.imul(D,be))+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,u[0]=ye,u[1]=me,u[2]=ve,u[3]=ge,u[4]=we,u[5]=_e,u[6]=Ae,u[7]=Ee,u[8]=xe,u[9]=ke,u[10]=Se,u[11]=Me,u[12]=Ie,u[13]=Te,u[14]=Ue,u[15]=je,u[16]=Be,u[17]=Pe,u[18]=Ce,0!==c&&(u[19]=c,r.length++),r};function p(e,t,r){return(new b).mulp(e,t,r)}function b(e,t){this.x=e,this.y=t}Math.imul||(d=l),o.prototype.mulTo=function(e,t){var r=this.length+e.length;return 10===this.length&&10===e.length?d(this,e,t):r<63?l(this,e,t):r<1024?function(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,a&=67108863}r.words[o]=s,n=a,a=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,e,t):p(this,e,t)},b.prototype.makeRBT=function(e){for(var t=new Array(e),r=o.prototype._countBits(e)-1,n=0;n>=1;return n},b.prototype.permute=function(e,t,r,n,i,o){for(var a=0;a>>=1)i++;return 1<>>=13,r[2*a+1]=8191&o,o>>>=13;for(a=2*t;a>=26,t+=i/67108864|0,t+=o>>>26,this.words[r]=67108863&o}return 0!==t&&(this.words[r]=t,this.length++),this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),r=0;r>>i}return t}(e);if(0===t.length)return new o(1);for(var r=this,n=0;n=0);var t,r=e%26,i=(e-r)/26,o=67108863>>>26-r<<26-r;if(0!==r){var a=0;for(t=0;t>>26-r}a&&(this.words[t]=a,this.length++)}if(0!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t=0),i=t?(t-t%26)/26:0;var o=e%26,a=Math.min((e-o)/26,this.length),s=67108863^67108863>>>o<a)for(this.length-=a,c=0;c=0&&(0!==f||c>=i);c--){var h=0|this.words[c];this.words[c]=f<<26-o|h>>>o,f=h&s}return u&&0!==f&&(u.words[u.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},o.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,i=1<=0);var t=e%26,r=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var i=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(u/67108864|0),this.words[i+r]=67108863&o}for(;i>26,this.words[i+r]=67108863&o;if(0===s)return this.strip();for(n(-1===s),s=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},o.prototype._wordDiv=function(e,t){var r=(this.length,e.length),n=this.clone(),i=e,a=0|i.words[i.length-1];0!==(r=26-this._countBits(a))&&(i=i.ushln(r),n.iushln(r),a=0|i.words[i.length-1]);var s,u=n.length-i.length;if("mod"!==t){(s=new o(null)).length=u+1,s.words=new Array(s.length);for(var c=0;c=0;h--){var l=67108864*(0|n.words[i.length+h])+(0|n.words[i.length+h-1]);for(l=Math.min(l/a|0,67108863),n._ishlnsubmul(i,l,h);0!==n.negative;)l--,n.negative=0,n._ishlnsubmul(i,1,h),n.isZero()||(n.negative^=1);s&&(s.words[h]=l)}return s&&s.strip(),n.strip(),"div"!==t&&0!==r&&n.iushrn(r),{div:s||null,mod:n}},o.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(s=this.neg().divmod(e,t),"mod"!==t&&(i=s.div.neg()),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.iadd(e)),{div:i,mod:a}):0===this.negative&&0!==e.negative?(s=this.divmod(e.neg(),t),"mod"!==t&&(i=s.div.neg()),{div:i,mod:s.mod}):0!=(this.negative&e.negative)?(s=this.neg().divmod(e.neg(),t),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.isub(e)),{div:s.div,mod:a}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modn(e.words[0]))}:this._wordDiv(e,t);var i,a,s},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=0!==t.div.negative?t.mod.isub(e):t.mod,n=e.ushrn(1),i=e.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modn=function(e){n(e<=67108863);for(var t=(1<<26)%e,r=0,i=this.length-1;i>=0;i--)r=(t*r+(0|this.words[i]))%e;return r},o.prototype.idivn=function(e){n(e<=67108863);for(var t=0,r=this.length-1;r>=0;r--){var i=(0|this.words[r])+67108864*t;this.words[r]=i/e|0,t=i%e}return this.strip()},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new o(1),a=new o(0),s=new o(0),u=new o(1),c=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++c;for(var f=r.clone(),h=t.clone();!t.isZero();){for(var l=0,d=1;0==(t.words[0]&d)&&l<26;++l,d<<=1);if(l>0)for(t.iushrn(l);l-- >0;)(i.isOdd()||a.isOdd())&&(i.iadd(f),a.isub(h)),i.iushrn(1),a.iushrn(1);for(var p=0,b=1;0==(r.words[0]&b)&&p<26;++p,b<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(s.isOdd()||u.isOdd())&&(s.iadd(f),u.isub(h)),s.iushrn(1),u.iushrn(1);t.cmp(r)>=0?(t.isub(r),i.isub(s),a.isub(u)):(r.isub(t),s.isub(i),u.isub(a))}return{a:s,b:u,gcd:r.iushln(c)}},o.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,a=new o(1),s=new o(0),u=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var c=0,f=1;0==(t.words[0]&f)&&c<26;++c,f<<=1);if(c>0)for(t.iushrn(c);c-- >0;)a.isOdd()&&a.iadd(u),a.iushrn(1);for(var h=0,l=1;0==(r.words[0]&l)&&h<26;++h,l<<=1);if(h>0)for(r.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(u),s.iushrn(1);t.cmp(r)>=0?(t.isub(r),a.isub(s)):(r.isub(t),s.isub(a))}return(i=0===t.cmpn(1)?a:s).cmpn(0)<0&&i.iadd(e),i},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var n=0;t.isEven()&&r.isEven();n++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=t.cmp(r);if(i<0){var o=t;t=r,r=o}else if(0===i||0===r.cmpn(1))break;t.isub(r)}return r.iushln(n)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return 0==(1&this.words[0])},o.prototype.isOdd=function(){return 1==(1&this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,i=1<>>26,s&=67108863,this.words[a]=s}return 0!==o&&(this.words[a]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this.strip(),this.length>1)t=1;else{r&&(e=-e),n(e<=67108863,"Number is too big");var i=0|this.words[0];t=i===e?0:ie.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|e.words[r];if(n!==i){ni&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new A(e)},o.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var y={k256:null,p224:null,p192:null,p25519:null};function m(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function v(){m.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function g(){m.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function w(){m.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function _(){m.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function A(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function E(e){A.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(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)}m.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},m.prototype.ireduce=function(e){var t,r=e;do{this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(t>this.n);var n=t0?r.isub(this.p):r.strip(),r},m.prototype.split=function(e,t){e.iushrn(this.n,0,t)},m.prototype.imulK=function(e){return e.imul(this.k)},i(v,m),v.prototype.split=function(e,t){for(var r=Math.min(e.length,9),n=0;n>>22,i=o}i>>>=22,e.words[n-10]=i,0===i&&e.length>10?e.length-=10:e.length-=9},v.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r>>=26,e.words[r]=i,t=n}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(y[e])return y[e];var t;if("k256"===e)t=new v;else if("p224"===e)t=new g;else if("p192"===e)t=new w;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new _}return y[e]=t,t},A.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},A.prototype._verify2=function(e,t){n(0==(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},A.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},A.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},A.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},A.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},A.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},A.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},A.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},A.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},A.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},A.prototype.isqr=function(e){return this.imul(e,e.clone())},A.prototype.sqr=function(e){return this.mul(e,e)},A.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var r=this.m.add(new o(1)).iushrn(2);return this.pow(e,r)}for(var i=this.m.subn(1),a=0;!i.isZero()&&0===i.andln(1);)a++,i.iushrn(1);n(!i.isZero());var s=new o(1).toRed(this),u=s.redNeg(),c=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new o(2*f*f).toRed(this);0!==this.pow(f,c).cmp(u);)f.redIAdd(u);for(var h=this.pow(f,i),l=this.pow(e,i.addn(1).iushrn(1)),d=this.pow(e,i),p=a;0!==d.cmp(s);){for(var b=d,y=0;0!==b.cmp(s);y++)b=b.redSqr();n(y=0;n--){for(var c=t.words[n],f=u-1;f>=0;f--){var h=c>>f&1;i!==r[0]&&(i=this.sqr(i)),0!==h||0!==a?(a<<=1,a|=h,(4===++s||0===n&&0===f)&&(i=this.mul(i,r[a]),s=0,a=0)):s=0}u=26}return i},A.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},A.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new E(e)},i(E,A),E.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},E.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},E.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},E.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var r=e.mul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},E.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===t||t,this)},{buffer:55}],54:[function(e,t,r){var n;function i(e){this.rand=e}if(t.exports=function(e){return n||(n=new i(null)),n.generate(e)},t.exports.Rand=i,i.prototype.generate=function(e){return this._rand(e)},i.prototype._rand=function(e){if(this.rand.getBytes)return this.rand.getBytes(e);for(var t=new Uint8Array(e),r=0;r>>24]^f[p>>>16&255]^h[b>>>8&255]^l[255&y]^t[m++],a=c[p>>>24]^f[b>>>16&255]^h[y>>>8&255]^l[255&d]^t[m++],s=c[b>>>24]^f[y>>>16&255]^h[d>>>8&255]^l[255&p]^t[m++],u=c[y>>>24]^f[d>>>16&255]^h[p>>>8&255]^l[255&b]^t[m++],d=o,p=a,b=s,y=u;return o=(n[d>>>24]<<24|n[p>>>16&255]<<16|n[b>>>8&255]<<8|n[255&y])^t[m++],a=(n[p>>>24]<<24|n[b>>>16&255]<<16|n[y>>>8&255]<<8|n[255&d])^t[m++],s=(n[b>>>24]<<24|n[y>>>16&255]<<16|n[d>>>8&255]<<8|n[255&p])^t[m++],u=(n[y>>>24]<<24|n[d>>>16&255]<<16|n[p>>>8&255]<<8|n[255&b])^t[m++],[o>>>=0,a>>>=0,s>>>=0,u>>>=0]}var s=[0,1,2,4,8,16,32,64,128,27,54],u=function(){for(var e=new Array(256),t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;for(var r=[],n=[],i=[[],[],[],[]],o=[[],[],[],[]],a=0,s=0,u=0;u<256;++u){var c=s^s<<1^s<<2^s<<3^s<<4;c=c>>>8^255&c^99,r[a]=c,n[c]=a;var f=e[a],h=e[f],l=e[h],d=257*e[c]^16843008*c;i[0][a]=d<<24|d>>>8,i[1][a]=d<<16|d>>>16,i[2][a]=d<<8|d>>>24,i[3][a]=d,d=16843009*l^65537*h^257*f^16843008*a,o[0][c]=d<<24|d>>>8,o[1][c]=d<<16|d>>>16,o[2][c]=d<<8|d>>>24,o[3][c]=d,0===a?a=s=1:(a=f^e[e[e[l^f]]],s^=e[e[s]])}return{SBOX:r,INV_SBOX:n,SUB_MIX:i,INV_SUB_MIX:o}}();function c(e){this._key=i(e),this._reset()}c.blockSize=16,c.keySize=32,c.prototype.blockSize=c.blockSize,c.prototype.keySize=c.keySize,c.prototype._reset=function(){for(var e=this._key,t=e.length,r=t+6,n=4*(r+1),i=[],o=0;o>>24,a=u.SBOX[a>>>24]<<24|u.SBOX[a>>>16&255]<<16|u.SBOX[a>>>8&255]<<8|u.SBOX[255&a],a^=s[o/t|0]<<24):t>6&&o%t==4&&(a=u.SBOX[a>>>24]<<24|u.SBOX[a>>>16&255]<<16|u.SBOX[a>>>8&255]<<8|u.SBOX[255&a]),i[o]=i[o-t]^a}for(var c=[],f=0;f>>24]]^u.INV_SUB_MIX[1][u.SBOX[l>>>16&255]]^u.INV_SUB_MIX[2][u.SBOX[l>>>8&255]]^u.INV_SUB_MIX[3][u.SBOX[255&l]]}this._nRounds=r,this._keySchedule=i,this._invKeySchedule=c},c.prototype.encryptBlockRaw=function(e){return a(e=i(e),this._keySchedule,u.SUB_MIX,u.SBOX,this._nRounds)},c.prototype.encryptBlock=function(e){var t=this.encryptBlockRaw(e),r=n.allocUnsafe(16);return r.writeUInt32BE(t[0],0),r.writeUInt32BE(t[1],4),r.writeUInt32BE(t[2],8),r.writeUInt32BE(t[3],12),r},c.prototype.decryptBlock=function(e){var t=(e=i(e))[1];e[1]=e[3],e[3]=t;var r=a(e,this._invKeySchedule,u.INV_SUB_MIX,u.INV_SBOX,this._nRounds),o=n.allocUnsafe(16);return o.writeUInt32BE(r[0],0),o.writeUInt32BE(r[3],4),o.writeUInt32BE(r[2],8),o.writeUInt32BE(r[1],12),o},c.prototype.scrub=function(){o(this._keySchedule),o(this._invKeySchedule),o(this._key)},t.exports.AES=c},{"safe-buffer":290}],57:[function(e,t,r){var n=e("./aes"),i=e("safe-buffer").Buffer,o=e("cipher-base"),a=e("inherits"),s=e("./ghash"),u=e("buffer-xor"),c=e("./incr32");function f(e,t,r,a){o.call(this);var u=i.alloc(4,0);this._cipher=new n.AES(t);var f=this._cipher.encryptBlock(u);this._ghash=new s(f),r=function(e,t,r){if(12===t.length)return e._finID=i.concat([t,i.from([0,0,0,1])]),i.concat([t,i.from([0,0,0,2])]);var n=new s(r),o=t.length,a=o%16;n.update(t),a&&(a=16-a,n.update(i.alloc(a,0))),n.update(i.alloc(8,0));var u=8*o,f=i.alloc(8);f.writeUIntBE(u,0,8),n.update(f),e._finID=n.state;var h=i.from(e._finID);return c(h),h}(this,r,f),this._prev=i.from(r),this._cache=i.allocUnsafe(0),this._secCache=i.allocUnsafe(0),this._decrypt=a,this._alen=0,this._len=0,this._mode=e,this._authTag=null,this._called=!1}a(f,o),f.prototype._update=function(e){if(!this._called&&this._alen){var t=16-this._alen%16;t<16&&(t=i.alloc(t,0),this._ghash.update(t))}this._called=!0;var r=this._mode.encrypt(this,e);return this._decrypt?this._ghash.update(e):this._ghash.update(r),this._len+=e.length,r},f.prototype._final=function(){if(this._decrypt&&!this._authTag)throw new Error("Unsupported state or unable to authenticate data");var e=u(this._ghash.final(8*this._alen,8*this._len),this._cipher.encryptBlock(this._finID));if(this._decrypt&&function(e,t){var r=0;e.length!==t.length&&r++;for(var n=Math.min(e.length,t.length),i=0;i16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t}else if(this.cache.length>=16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t;return null},h.prototype.flush=function(){if(this.cache.length)return this.cache},r.createDecipher=function(e,t){var r=o[e.toLowerCase()];if(!r)throw new TypeError("invalid suite type");var n=c(t,!1,r.key,r.iv);return l(e,n.key,n.iv)},r.createDecipheriv=l},{"./aes":56,"./authCipher":57,"./modes":69,"./streamCipher":72,"cipher-base":86,evp_bytestokey:158,inherits:180,"safe-buffer":290}],60:[function(e,t,r){var n=e("./modes"),i=e("./authCipher"),o=e("safe-buffer").Buffer,a=e("./streamCipher"),s=e("cipher-base"),u=e("./aes"),c=e("evp_bytestokey");function f(e,t,r){s.call(this),this._cache=new l,this._cipher=new u.AES(t),this._prev=o.from(r),this._mode=e,this._autopadding=!0}e("inherits")(f,s),f.prototype._update=function(e){var t,r;this._cache.add(e);for(var n=[];t=this._cache.get();)r=this._mode.encrypt(this,t),n.push(r);return o.concat(n)};var h=o.alloc(16,16);function l(){this.cache=o.allocUnsafe(0)}function d(e,t,r){var s=n[e.toLowerCase()];if(!s)throw new TypeError("invalid suite type");if("string"==typeof t&&(t=o.from(t)),t.length!==s.key/8)throw new TypeError("invalid key length "+t.length);if("string"==typeof r&&(r=o.from(r)),"GCM"!==s.mode&&r.length!==s.iv)throw new TypeError("invalid iv length "+r.length);return"stream"===s.type?new a(s.module,t,r):"auth"===s.type?new i(s.module,t,r):new f(s.module,t,r)}f.prototype._final=function(){var e=this._cache.flush();if(this._autopadding)return e=this._mode.encrypt(this,e),this._cipher.scrub(),e;if(!e.equals(h))throw this._cipher.scrub(),new Error("data not multiple of block length")},f.prototype.setAutoPadding=function(e){return this._autopadding=!!e,this},l.prototype.add=function(e){this.cache=o.concat([this.cache,e])},l.prototype.get=function(){if(this.cache.length>15){var e=this.cache.slice(0,16);return this.cache=this.cache.slice(16),e}return null},l.prototype.flush=function(){for(var e=16-this.cache.length,t=o.allocUnsafe(e),r=-1;++r>>0,0),t.writeUInt32BE(e[1]>>>0,4),t.writeUInt32BE(e[2]>>>0,8),t.writeUInt32BE(e[3]>>>0,12),t}function a(e){this.h=e,this.state=n.alloc(16,0),this.cache=n.allocUnsafe(0)}a.prototype.ghash=function(e){for(var t=-1;++t0;t--)n[t]=n[t]>>>1|(1&n[t-1])<<31;n[0]=n[0]>>>1,r&&(n[0]=n[0]^225<<24)}this.state=o(i)},a.prototype.update=function(e){var t;for(this.cache=n.concat([this.cache,e]);this.cache.length>=16;)t=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(t)},a.prototype.final=function(e,t){return this.cache.length&&this.ghash(n.concat([this.cache,i],16)),this.ghash(o([0,e,0,t])),this.state},t.exports=a},{"safe-buffer":290}],62:[function(e,t,r){t.exports=function(e){for(var t,r=e.length;r--;){if(255!==(t=e.readUInt8(r))){t++,e.writeUInt8(t,r);break}e.writeUInt8(0,r)}}},{}],63:[function(e,t,r){var n=e("buffer-xor");r.encrypt=function(e,t){var r=n(t,e._prev);return e._prev=e._cipher.encryptBlock(r),e._prev},r.decrypt=function(e,t){var r=e._prev;e._prev=t;var i=e._cipher.decryptBlock(t);return n(i,r)}},{"buffer-xor":83}],64:[function(e,t,r){var n=e("safe-buffer").Buffer,i=e("buffer-xor");function o(e,t,r){var o=t.length,a=i(t,e._cache);return e._cache=e._cache.slice(o),e._prev=n.concat([e._prev,r?t:a]),a}r.encrypt=function(e,t,r){for(var i,a=n.allocUnsafe(0);t.length;){if(0===e._cache.length&&(e._cache=e._cipher.encryptBlock(e._prev),e._prev=n.allocUnsafe(0)),!(e._cache.length<=t.length)){a=n.concat([a,o(e,t,r)]);break}i=e._cache.length,a=n.concat([a,o(e,t.slice(0,i),r)]),t=t.slice(i)}return a}},{"buffer-xor":83,"safe-buffer":290}],65:[function(e,t,r){var n=e("safe-buffer").Buffer;function i(e,t,r){for(var n,i,a=-1,s=0;++a<8;)n=t&1<<7-a?128:0,s+=(128&(i=e._cipher.encryptBlock(e._prev)[0]^n))>>a%8,e._prev=o(e._prev,r?n:i);return s}function o(e,t){var r=e.length,i=-1,o=n.allocUnsafe(e.length);for(e=n.concat([e,n.from([t])]);++i>7;return o}r.encrypt=function(e,t,r){for(var o=t.length,a=n.allocUnsafe(o),s=-1;++s=0||!r.umod(e.prime1)||!r.umod(e.prime2);)r=new n(i(t));return r}t.exports=o,o.getr=a}).call(this,e("buffer").Buffer)},{"bn.js":53,buffer:84,randombytes:270}],77:[function(e,t,r){t.exports=e("./browser/algorithms.json")},{"./browser/algorithms.json":78}],78:[function(e,t,r){t.exports={sha224WithRSAEncryption:{sign:"rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},"RSA-SHA224":{sign:"ecdsa/rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},sha256WithRSAEncryption:{sign:"rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},"RSA-SHA256":{sign:"ecdsa/rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},sha384WithRSAEncryption:{sign:"rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},"RSA-SHA384":{sign:"ecdsa/rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},sha512WithRSAEncryption:{sign:"rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA512":{sign:"ecdsa/rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA1":{sign:"rsa",hash:"sha1",id:"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{sign:"ecdsa",hash:"sha1",id:""},sha256:{sign:"ecdsa",hash:"sha256",id:""},sha224:{sign:"ecdsa",hash:"sha224",id:""},sha384:{sign:"ecdsa",hash:"sha384",id:""},sha512:{sign:"ecdsa",hash:"sha512",id:""},"DSA-SHA":{sign:"dsa",hash:"sha1",id:""},"DSA-SHA1":{sign:"dsa",hash:"sha1",id:""},DSA:{sign:"dsa",hash:"sha1",id:""},"DSA-WITH-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-WITH-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-WITH-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-WITH-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-RIPEMD160":{sign:"dsa",hash:"rmd160",id:""},ripemd160WithRSA:{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},"RSA-RIPEMD160":{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},md5WithRSAEncryption:{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"},"RSA-MD5":{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"}}},{}],79:[function(e,t,r){t.exports={"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"}},{}],80:[function(e,t,r){(function(r){var n=e("create-hash"),i=e("stream"),o=e("inherits"),a=e("./sign"),s=e("./verify"),u=e("./algorithms.json");function c(e){i.Writable.call(this);var t=u[e];if(!t)throw new Error("Unknown message digest");this._hashType=t.hash,this._hash=n(t.hash),this._tag=t.id,this._signType=t.sign}function f(e){i.Writable.call(this);var t=u[e];if(!t)throw new Error("Unknown message digest");this._hash=n(t.hash),this._tag=t.id,this._signType=t.sign}function h(e){return new c(e)}function l(e){return new f(e)}Object.keys(u).forEach(function(e){u[e].id=new r(u[e].id,"hex"),u[e.toLowerCase()]=u[e]}),o(c,i.Writable),c.prototype._write=function(e,t,r){this._hash.update(e),r()},c.prototype.update=function(e,t){return"string"==typeof e&&(e=new r(e,t)),this._hash.update(e),this},c.prototype.sign=function(e,t){this.end();var r=this._hash.digest(),n=a(r,e,this._hashType,this._signType,this._tag);return t?n.toString(t):n},o(f,i.Writable),f.prototype._write=function(e,t,r){this._hash.update(e),r()},f.prototype.update=function(e,t){return"string"==typeof e&&(e=new r(e,t)),this._hash.update(e),this},f.prototype.verify=function(e,t,n){"string"==typeof t&&(t=new r(t,n)),this.end();var i=this._hash.digest();return s(t,i,e,this._signType,this._tag)},t.exports={Sign:h,Verify:l,createSign:h,createVerify:l}}).call(this,e("buffer").Buffer)},{"./algorithms.json":78,"./sign":81,"./verify":82,buffer:84,"create-hash":91,inherits:180,stream:311}],81:[function(e,t,r){(function(r){var n=e("create-hmac"),i=e("browserify-rsa"),o=e("elliptic").ec,a=e("bn.js"),s=e("parse-asn1"),u=e("./curves.json");function c(e,t,i,o){if((e=new r(e.toArray())).length0&&r.ishrn(n),r}function h(e,t,i){var o,a;do{for(o=new r(0);8*o.length=t)throw new Error("invalid sig")}t.exports=function(e,t,u,c,f){var h=o(u);if("ec"===h.type){if("ecdsa"!==c&&"ecdsa/rsa"!==c)throw new Error("wrong public key type");return function(e,t,r){var n=a[r.data.algorithm.curve.join(".")];if(!n)throw new Error("unknown curve "+r.data.algorithm.curve.join("."));var o=new i(n),s=r.data.subjectPrivateKey.data;return o.verify(t,e,s)}(e,t,h)}if("dsa"===h.type){if("dsa"!==c)throw new Error("wrong public key type");return function(e,t,r){var i=r.data.p,a=r.data.q,u=r.data.g,c=r.data.pub_key,f=o.signature.decode(e,"der"),h=f.s,l=f.r;s(h,a),s(l,a);var d=n.mont(i),p=h.invm(a);return 0===u.toRed(d).redPow(new n(t).mul(p).mod(a)).fromRed().mul(c.toRed(d).redPow(l.mul(p).mod(a)).fromRed()).mod(i).mod(a).cmp(l)}(e,t,h)}if("rsa"!==c&&"ecdsa/rsa"!==c)throw new Error("wrong public key type");t=r.concat([f,t]);for(var l=h.modulus.byteLength(),d=[1],p=0;t.length+d.length+2o)throw new RangeError("Invalid typed array length");var t=new Uint8Array(e);return t.__proto__=s.prototype,t}function s(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return f(e)}return u(e,t,r)}function u(e,t,r){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return F(e)?function(e,t,r){if(t<0||e.byteLength=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function d(e,t){if(s.isBuffer(e))return e.length;if(q(e)||F(e))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return L(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return O(e).length;default:if(n)return L(e).length;t=(""+t).toLowerCase(),n=!0}}function p(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function b(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),H(r=+r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=s.from(t,n)),s.isBuffer(t))return 0===t.length?-1:y(e,t,r,n,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):y(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function y(e,t,r,n,i){var o,a=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,r/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(i){var f=-1;for(o=r;os&&(r=s-u),o=r;o>=0;o--){for(var h=!0,l=0;li&&(n=i):n=i;var o=t.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var a=0;a>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function E(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function x(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i239?4:c>223?3:c>191?2:1;if(i+h<=r)switch(h){case 1:c<128&&(f=c);break;case 2:128==(192&(o=e[i+1]))&&(u=(31&c)<<6|63&o)>127&&(f=u);break;case 3:o=e[i+1],a=e[i+2],128==(192&o)&&128==(192&a)&&(u=(15&c)<<12|(63&o)<<6|63&a)>2047&&(u<55296||u>57343)&&(f=u);break;case 4:o=e[i+1],a=e[i+2],s=e[i+3],128==(192&o)&&128==(192&a)&&128==(192&s)&&(u=(15&c)<<18|(63&o)<<12|(63&a)<<6|63&s)>65535&&u<1114112&&(f=u)}null===f?(f=65533,h=1):f>65535&&(f-=65536,n.push(f>>>10&1023|55296),f=56320|1023&f),n.push(f),i+=h}return function(e){var t=e.length;if(t<=k)return String.fromCharCode.apply(String,e);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return I(this,t,r);case"utf8":case"utf-8":return x(this,t,r);case"ascii":return S(this,t,r);case"latin1":case"binary":return M(this,t,r);case"base64":return E(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}.apply(this,arguments)},s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.prototype.inspect=function(){var e="",t=r.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},s.prototype.compare=function(e,t,r,n,i){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;for(var o=(i>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0),u=Math.min(o,a),c=this.slice(n,i),f=e.slice(t,r),h=0;h>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return m(this,e,t,r);case"utf8":case"utf-8":return v(this,e,t,r);case"ascii":return g(this,e,t,r);case"latin1":case"binary":return w(this,e,t,r);case"base64":return _(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var k=4096;function S(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;in)&&(r=n);for(var i="",o=t;or)throw new RangeError("Trying to access beyond buffer length")}function j(e,t,r,n,i,o){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function B(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function P(e,t,r,n,o){return t=+t,r>>>=0,o||B(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function C(e,t,r,n,o){return t=+t,r>>>=0,o||B(e,0,r,8),i.write(e,t,r,n,52,8),r+8}s.prototype.slice=function(e,t){var r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||U(e,t,this.length);for(var n=this[e],i=1,o=0;++o>>=0,t>>>=0,r||U(e,t,this.length);for(var n=this[e+--t],i=1;t>0&&(i*=256);)n+=this[e+--t]*i;return n},s.prototype.readUInt8=function(e,t){return e>>>=0,t||U(e,1,this.length),this[e]},s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||U(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||U(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||U(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||U(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);for(var n=this[e],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*t)),n},s.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);for(var n=t,i=1,o=this[e+--n];n>0&&(i*=256);)o+=this[e+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*t)),o},s.prototype.readInt8=function(e,t){return e>>>=0,t||U(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||U(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt16BE=function(e,t){e>>>=0,t||U(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||U(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||U(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readFloatLE=function(e,t){return e>>>=0,t||U(e,4,this.length),i.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||U(e,4,this.length),i.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||U(e,8,this.length),i.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||U(e,8,this.length),i.read(this,e,!1,52,8)},s.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t>>>=0,r>>>=0,n)||j(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[t]=255&e;++o>>=0,r>>>=0,n)||j(this,e,t,r,Math.pow(2,8*r)-1,0);var i=r-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r},s.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);j(this,e,t,r,i-1,-i)}var o=0,a=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+r},s.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);j(this,e,t,r,i-1,-i)}var o=r-1,a=1,s=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a>>0)-s&255;return t+r},s.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeFloatLE=function(e,t,r){return P(this,e,t,!0,r)},s.prototype.writeFloatBE=function(e,t,r){return P(this,e,t,!1,r)},s.prototype.writeDoubleLE=function(e,t,r){return C(this,e,t,!0,r)},s.prototype.writeDoubleBE=function(e,t,r){return C(this,e,t,!1,r)},s.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--i)e[i+t]=this[i+r];else if(o<1e3)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function O(e){return n.toByteArray(function(e){if((e=e.trim().replace(N,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function D(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function F(e){return e instanceof ArrayBuffer||null!=e&&null!=e.constructor&&"ArrayBuffer"===e.constructor.name&&"number"==typeof e.byteLength}function q(e){return"function"==typeof ArrayBuffer.isView&&ArrayBuffer.isView(e)}function H(e){return e!=e}},{"base64-js":51,ieee754:178}],85:[function(e,t,r){t.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}},{}],86:[function(e,t,r){var n=e("safe-buffer").Buffer,i=e("stream").Transform,o=e("string_decoder").StringDecoder;function a(e){i.call(this),this.hashMode="string"==typeof e,this.hashMode?this[e]=this._finalOrDigest:this.final=this._finalOrDigest,this._final&&(this.__final=this._final,this._final=null),this._decoder=null,this._encoding=null}e("inherits")(a,i),a.prototype.update=function(e,t,r){"string"==typeof e&&(e=n.from(e,t));var i=this._update(e);return this.hashMode?this:(r&&(i=this._toString(i,r)),i)},a.prototype.setAutoPadding=function(){},a.prototype.getAuthTag=function(){throw new Error("trying to get auth tag in unsupported state")},a.prototype.setAuthTag=function(){throw new Error("trying to set auth tag in unsupported state")},a.prototype.setAAD=function(){throw new Error("trying to set aad in unsupported state")},a.prototype._transform=function(e,t,r){var n;try{this.hashMode?this._update(e):this.push(this._update(e))}catch(e){n=e}finally{r(n)}},a.prototype._flush=function(e){var t;try{this.push(this.__final())}catch(e){t=e}e(t)},a.prototype._finalOrDigest=function(e){var t=this.__final()||n.alloc(0);return e&&(t=this._toString(t,e,!0)),t},a.prototype._toString=function(e,t,r){if(this._decoder||(this._decoder=new o(t),this._encoding=t),this._encoding!==t)throw new Error("can't switch encodings");var n=this._decoder.write(e);return r&&(n+=this._decoder.end()),n},t.exports=a},{inherits:180,"safe-buffer":290,stream:311,string_decoder:317}],87:[function(e,t,r){(function(e){var r=function(){"use strict";function t(e,t){return null!=t&&e instanceof t}var r,n,i;try{r=Map}catch(e){r=function(){}}try{n=Set}catch(e){n=function(){}}try{i=Promise}catch(e){i=function(){}}function o(a,u,c,f,h){"object"==typeof u&&(c=u.depth,f=u.prototype,h=u.includeNonEnumerable,u=u.circular);var l=[],d=[],p=void 0!==e;return void 0===u&&(u=!0),void 0===c&&(c=1/0),function a(c,b){if(null===c)return null;if(0===b)return c;var y,m;if("object"!=typeof c)return c;if(t(c,r))y=new r;else if(t(c,n))y=new n;else if(t(c,i))y=new i(function(e,t){c.then(function(t){e(a(t,b-1))},function(e){t(a(e,b-1))})});else if(o.__isArray(c))y=[];else if(o.__isRegExp(c))y=new RegExp(c.source,s(c)),c.lastIndex&&(y.lastIndex=c.lastIndex);else if(o.__isDate(c))y=new Date(c.getTime());else{if(p&&e.isBuffer(c))return y=e.allocUnsafe?e.allocUnsafe(c.length):new e(c.length),c.copy(y),y;t(c,Error)?y=Object.create(c):void 0===f?(m=Object.getPrototypeOf(c),y=Object.create(m)):(y=Object.create(f),m=f)}if(u){var v=l.indexOf(c);if(-1!=v)return d[v];l.push(c),d.push(y)}for(var g in t(c,r)&&c.forEach(function(e,t){var r=a(t,b-1),n=a(e,b-1);y.set(r,n)}),t(c,n)&&c.forEach(function(e){var t=a(e,b-1);y.add(t)}),c){var w;m&&(w=Object.getOwnPropertyDescriptor(m,g)),w&&null==w.set||(y[g]=a(c[g],b-1))}if(Object.getOwnPropertySymbols){var _=Object.getOwnPropertySymbols(c);for(g=0;g<_.length;g++){var A=_[g];(!(x=Object.getOwnPropertyDescriptor(c,A))||x.enumerable||h)&&(y[A]=a(c[A],b-1),x.enumerable||Object.defineProperty(y,A,{enumerable:!1}))}}if(h){var E=Object.getOwnPropertyNames(c);for(g=0;g>>2),a=0,s=0;a>5]|=128<>>9<<4)]=t;for(var r=1732584193,n=-271733879,i=-1732584194,o=271733878,h=0;h>>32-s,r);var a,s}function a(e,t,r,n,i,a,s){return o(t&r|~t&n,e,t,i,a,s)}function s(e,t,r,n,i,a,s){return o(t&n|r&~n,e,t,i,a,s)}function u(e,t,r,n,i,a,s){return o(t^r^n,e,t,i,a,s)}function c(e,t,r,n,i,a,s){return o(r^(t|~n),e,t,i,a,s)}function f(e,t){var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}t.exports=function(e){return n(e,i)}},{"./make-hash":92}],94:[function(e,t,r){"use strict";var n=e("inherits"),i=e("./legacy"),o=e("cipher-base"),a=e("safe-buffer").Buffer,s=e("create-hash/md5"),u=e("ripemd160"),c=e("sha.js"),f=a.alloc(128);function h(e,t){o.call(this,"digest"),"string"==typeof t&&(t=a.from(t));var r="sha512"===e||"sha384"===e?128:64;(this._alg=e,this._key=t,t.length>r)?t=("rmd160"===e?new u:c(e)).update(t).digest():t.lengths?t=e(t):t.length-1};f.prototype.append=function(e,t){e=s(e),t=u(t);var r=this.map[e];this.map[e]=r?r+","+t:t},f.prototype.delete=function(e){delete this.map[s(e)]},f.prototype.get=function(e){return e=s(e),this.has(e)?this.map[e]:null},f.prototype.has=function(e){return this.map.hasOwnProperty(s(e))},f.prototype.set=function(e,t){this.map[s(e)]=u(t)},f.prototype.forEach=function(e,t){for(var r in this.map)this.map.hasOwnProperty(r)&&e.call(t,this.map[r],r,this)},f.prototype.keys=function(){var e=[];return this.forEach(function(t,r){e.push(r)}),c(e)},f.prototype.values=function(){var e=[];return this.forEach(function(t){e.push(t)}),c(e)},f.prototype.entries=function(){var e=[];return this.forEach(function(t,r){e.push([r,t])}),c(e)},t.iterable&&(f.prototype[Symbol.iterator]=f.prototype.entries);var o=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];y.prototype.clone=function(){return new y(this,{body:this._bodyInit})},b.call(y.prototype),b.call(v.prototype),v.prototype.clone=function(){return new v(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new f(this.headers),url:this.url})},v.error=function(){var e=new v(null,{status:0,statusText:""});return e.type="error",e};var a=[301,302,303,307,308];v.redirect=function(e,t){if(-1===a.indexOf(t))throw new RangeError("Invalid status code");return new v(null,{status:t,headers:{location:e}})},e.Headers=f,e.Request=y,e.Response=v,e.fetch=function(e,r){return new Promise(function(n,i){var o=new y(e,r),a=new XMLHttpRequest;a.onload=function(){var e,t,r={status:a.status,statusText:a.statusText,headers:(e=a.getAllResponseHeaders()||"",t=new f,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach(function(e){var r=e.split(":"),n=r.shift().trim();if(n){var i=r.join(":").trim();t.append(n,i)}}),t)};r.url="responseURL"in a?a.responseURL:r.headers.get("X-Request-URL");var i="response"in a?a.response:a.responseText;n(new v(i,r))},a.onerror=function(){i(new TypeError("Network request failed"))},a.ontimeout=function(){i(new TypeError("Network request failed"))},a.open(o.method,o.url,!0),"include"===o.credentials?a.withCredentials=!0:"omit"===o.credentials&&(a.withCredentials=!1),"responseType"in a&&t.blob&&(a.responseType="blob"),o.headers.forEach(function(e,t){a.setRequestHeader(t,e)}),a.send(void 0===o._bodyInit?null:o._bodyInit)})},e.fetch.polyfill=!0}function s(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function u(e){return"string"!=typeof e&&(e=String(e)),e}function c(e){var r={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return t.iterable&&(r[Symbol.iterator]=function(){return r}),r}function f(e){this.map={},e instanceof f?e.forEach(function(e,t){this.append(t,e)},this):Array.isArray(e)?e.forEach(function(e){this.append(e[0],e[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}function h(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function l(e){return new Promise(function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}})}function d(e){var t=new FileReader,r=l(t);return t.readAsArrayBuffer(e),r}function p(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function b(){return this.bodyUsed=!1,this._initBody=function(e){if(this._bodyInit=e,e)if("string"==typeof e)this._bodyText=e;else if(t.blob&&Blob.prototype.isPrototypeOf(e))this._bodyBlob=e;else if(t.formData&&FormData.prototype.isPrototypeOf(e))this._bodyFormData=e;else if(t.searchParams&&URLSearchParams.prototype.isPrototypeOf(e))this._bodyText=e.toString();else if(t.arrayBuffer&&t.blob&&n(e))this._bodyArrayBuffer=p(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer]);else{if(!t.arrayBuffer||!ArrayBuffer.prototype.isPrototypeOf(e)&&!i(e))throw new Error("unsupported BodyInit type");this._bodyArrayBuffer=p(e)}else this._bodyText="";this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):t.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},t.blob&&(this.blob=function(){var e=h(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?h(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(d)}),this.text=function(){var e,t,r,n=h(this);if(n)return n;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,r=l(t),t.readAsText(e),r;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),r=new Array(t.length),n=0;n-1?n:r),this.mode=t.mode||this.mode||null,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&i)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(i)}function m(e){var t=new FormData;return e.trim().split("&").forEach(function(e){if(e){var r=e.split("="),n=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");t.append(decodeURIComponent(n),decodeURIComponent(i))}}),t}function v(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new f(t.headers),this.url=t.url||"",this._initBody(e)}}(void 0!==e?e:this)}).call(n,void 0);var i=n.fetch;i.Response=n.Response,i.Request=n.Request,i.Headers=n.Headers;"object"==typeof t&&t.exports&&(t.exports=i,t.exports.default=i)},{}],97:[function(e,t,r){"use strict";r.randomBytes=r.rng=r.pseudoRandomBytes=r.prng=e("randombytes"),r.createHash=r.Hash=e("create-hash"),r.createHmac=r.Hmac=e("create-hmac");var n=e("browserify-sign/algos"),i=Object.keys(n),o=["sha1","sha224","sha256","sha384","sha512","md5","rmd160"].concat(i);r.getHashes=function(){return o};var a=e("pbkdf2");r.pbkdf2=a.pbkdf2,r.pbkdf2Sync=a.pbkdf2Sync;var s=e("browserify-cipher");r.Cipher=s.Cipher,r.createCipher=s.createCipher,r.Cipheriv=s.Cipheriv,r.createCipheriv=s.createCipheriv,r.Decipher=s.Decipher,r.createDecipher=s.createDecipher,r.Decipheriv=s.Decipheriv,r.createDecipheriv=s.createDecipheriv,r.getCiphers=s.getCiphers,r.listCiphers=s.listCiphers;var u=e("diffie-hellman");r.DiffieHellmanGroup=u.DiffieHellmanGroup,r.createDiffieHellmanGroup=u.createDiffieHellmanGroup,r.getDiffieHellman=u.getDiffieHellman,r.createDiffieHellman=u.createDiffieHellman,r.DiffieHellman=u.DiffieHellman;var c=e("browserify-sign");r.createSign=c.createSign,r.Sign=c.Sign,r.createVerify=c.createVerify,r.Verify=c.Verify,r.createECDH=e("create-ecdh");var f=e("public-encrypt");r.publicEncrypt=f.publicEncrypt,r.privateEncrypt=f.privateEncrypt,r.publicDecrypt=f.publicDecrypt,r.privateDecrypt=f.privateDecrypt;var h=e("randomfill");r.randomFill=h.randomFill,r.randomFillSync=h.randomFillSync,r.createCredentials=function(){throw new Error(["sorry, createCredentials is not implemented yet","we accept pull requests","https://github.com/crypto-browserify/crypto-browserify"].join("\n"))},r.constants={DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,NPN_ENABLED:1,ALPN_ENABLED:1,RSA_PKCS1_PADDING:1,RSA_SSLV23_PADDING:2,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,POINT_CONVERSION_COMPRESSED:2,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(e,t,r){"use strict";var n=new RegExp("%[a-f0-9]{2}","gi"),i=new RegExp("(%[a-f0-9]{2})+","gi");function o(e,t){try{return decodeURIComponent(e.join(""))}catch(e){}if(1===e.length)return e;t=t||1;var r=e.slice(0,t),n=e.slice(t);return Array.prototype.concat.call([],o(r),o(n))}function a(e){try{return decodeURIComponent(e)}catch(i){for(var t=e.match(n),r=1;r0;n--)t+=this._buffer(e,t),r+=this._flushBuffer(i,r);return t+=this._buffer(e,t),i},i.prototype.final=function(e){var t,r;return e&&(t=this.update(e)),r="encrypt"===this.type?this._finalEncrypt():this._finalDecrypt(),t?t.concat(r):r},i.prototype._pad=function(e,t){if(0===t)return!1;for(;t>>1];r=a.r28shl(r,s),i=a.r28shl(i,s),a.pc2(r,i,e.keys,o)}},u.prototype._update=function(e,t,r,n){var i=this._desState,o=a.readUInt32BE(e,t),s=a.readUInt32BE(e,t+4);a.ip(o,s,i.tmp,0),o=i.tmp[0],s=i.tmp[1],"encrypt"===this.type?this._encrypt(i,o,s,i.tmp,0):this._decrypt(i,o,s,i.tmp,0),o=i.tmp[0],s=i.tmp[1],a.writeUInt32BE(r,o,n),a.writeUInt32BE(r,s,n+4)},u.prototype._pad=function(e,t){for(var r=e.length-t,n=t;n>>0,o=l}a.rip(s,o,n,i)},u.prototype._decrypt=function(e,t,r,n,i){for(var o=r,s=t,u=e.keys.length-2;u>=0;u-=2){var c=e.keys[u],f=e.keys[u+1];a.expand(o,e.tmp,0),c^=e.tmp[0],f^=e.tmp[1];var h=a.substitute(c,f),l=o;o=(s^a.permute(h))>>>0,s=l}a.rip(o,s,n,i)}},{"../des":99,inherits:180,"minimalistic-assert":234}],103:[function(e,t,r){"use strict";var n=e("minimalistic-assert"),i=e("inherits"),o=e("../des"),a=o.Cipher,s=o.DES;function u(e){a.call(this,e);var t=new function(e,t){n.equal(t.length,24,"Invalid key length");var r=t.slice(0,8),i=t.slice(8,16),o=t.slice(16,24);this.ciphers="encrypt"===e?[s.create({type:"encrypt",key:r}),s.create({type:"decrypt",key:i}),s.create({type:"encrypt",key:o})]:[s.create({type:"decrypt",key:o}),s.create({type:"encrypt",key:i}),s.create({type:"decrypt",key:r})]}(this.type,this.options.key);this._edeState=t}i(u,a),t.exports=u,u.create=function(e){return new u(e)},u.prototype._update=function(e,t,r,n){var i=this._edeState;i.ciphers[0]._update(e,t,r,n),i.ciphers[1]._update(r,n,r,n),i.ciphers[2]._update(r,n,r,n)},u.prototype._pad=s.prototype._pad,u.prototype._unpad=s.prototype._unpad},{"../des":99,inherits:180,"minimalistic-assert":234}],104:[function(e,t,r){"use strict";r.readUInt32BE=function(e,t){return(e[0+t]<<24|e[1+t]<<16|e[2+t]<<8|e[3+t])>>>0},r.writeUInt32BE=function(e,t,r){e[0+r]=t>>>24,e[1+r]=t>>>16&255,e[2+r]=t>>>8&255,e[3+r]=255&t},r.ip=function(e,t,r,n){for(var i=0,o=0,a=6;a>=0;a-=2){for(var s=0;s<=24;s+=8)i<<=1,i|=t>>>s+a&1;for(s=0;s<=24;s+=8)i<<=1,i|=e>>>s+a&1}for(a=6;a>=0;a-=2){for(s=1;s<=25;s+=8)o<<=1,o|=t>>>s+a&1;for(s=1;s<=25;s+=8)o<<=1,o|=e>>>s+a&1}r[n+0]=i>>>0,r[n+1]=o>>>0},r.rip=function(e,t,r,n){for(var i=0,o=0,a=0;a<4;a++)for(var s=24;s>=0;s-=8)i<<=1,i|=t>>>s+a&1,i<<=1,i|=e>>>s+a&1;for(a=4;a<8;a++)for(s=24;s>=0;s-=8)o<<=1,o|=t>>>s+a&1,o<<=1,o|=e>>>s+a&1;r[n+0]=i>>>0,r[n+1]=o>>>0},r.pc1=function(e,t,r,n){for(var i=0,o=0,a=7;a>=5;a--){for(var s=0;s<=24;s+=8)i<<=1,i|=t>>s+a&1;for(s=0;s<=24;s+=8)i<<=1,i|=e>>s+a&1}for(s=0;s<=24;s+=8)i<<=1,i|=t>>s+a&1;for(a=1;a<=3;a++){for(s=0;s<=24;s+=8)o<<=1,o|=t>>s+a&1;for(s=0;s<=24;s+=8)o<<=1,o|=e>>s+a&1}for(s=0;s<=24;s+=8)o<<=1,o|=e>>s+a&1;r[n+0]=i>>>0,r[n+1]=o>>>0},r.r28shl=function(e,t){return e<>>28-t};var n=[14,11,17,4,27,23,25,0,13,22,7,18,5,9,16,24,2,20,12,21,1,8,15,26,15,4,25,19,9,1,26,16,5,11,23,8,12,7,17,0,22,3,10,14,6,20,27,24];r.pc2=function(e,t,r,i){for(var o=0,a=0,s=n.length>>>1,u=0;u>>n[u]&1;for(u=s;u>>n[u]&1;r[i+0]=o>>>0,r[i+1]=a>>>0},r.expand=function(e,t,r){var n=0,i=0;n=(1&e)<<5|e>>>27;for(var o=23;o>=15;o-=4)n<<=6,n|=e>>>o&63;for(o=11;o>=3;o-=4)i|=e>>>o&63,i<<=6;i|=(31&e)<<1|e>>>31,t[r+0]=n>>>0,t[r+1]=i>>>0};var i=[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];r.substitute=function(e,t){for(var r=0,n=0;n<4;n++){r<<=4,r|=i[64*n+(e>>>18-6*n&63)]}for(n=0;n<4;n++){r<<=4,r|=i[256+64*n+(t>>>18-6*n&63)]}return r>>>0};var o=[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];r.permute=function(e){for(var t=0,r=0;r>>o[r]&1;return t>>>0},r.padSplit=function(e,t,r){for(var n=e.toString(2);n.lengthe;)r.ishrn(1);if(r.isEven()&&r.iadd(s),r.testn(1)||r.iadd(u),t.cmp(u)){if(!t.cmp(c))for(;r.mod(f).cmp(h);)r.iadd(d)}else for(;r.mod(o).cmp(l);)r.iadd(d);if(y(p=r.shrn(1))&&y(r)&&m(p)&&m(r)&&a.test(p)&&a.test(r))return r}}},{"bn.js":53,"miller-rabin":233,randombytes:270}],108:[function(e,t,r){t.exports={modp1:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},modp2:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},modp5:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},modp14:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},modp15:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},modp16:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},modp17:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},modp18:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"}}},{}],109:[function(e,t,r){"use strict";var n=r;n.version=e("../package.json").version,n.utils=e("./elliptic/utils"),n.rand=e("brorand"),n.curve=e("./elliptic/curve"),n.curves=e("./elliptic/curves"),n.ec=e("./elliptic/ec"),n.eddsa=e("./elliptic/eddsa")},{"../package.json":124,"./elliptic/curve":112,"./elliptic/curves":115,"./elliptic/ec":116,"./elliptic/eddsa":119,"./elliptic/utils":123,brorand:54}],110:[function(e,t,r){"use strict";var n=e("bn.js"),i=e("../../elliptic").utils,o=i.getNAF,a=i.getJSF,s=i.assert;function u(e,t){this.type=e,this.p=new n(t.p,16),this.red=t.prime?n.red(t.prime):n.mont(this.p),this.zero=new n(0).toRed(this.red),this.one=new n(1).toRed(this.red),this.two=new n(2).toRed(this.red),this.n=t.n&&new n(t.n,16),this.g=t.g&&this.pointFromJSON(t.g,t.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4);var r=this.n&&this.p.div(this.n);!r||r.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}function c(e,t){this.curve=e,this.type=t,this.precomputed=null}t.exports=u,u.prototype.point=function(){throw new Error("Not implemented")},u.prototype.validate=function(){throw new Error("Not implemented")},u.prototype._fixedNafMul=function(e,t){s(e.precomputed);var r=e._getDoubles(),n=o(t,1),i=(1<=u;t--)c=(c<<1)+n[t];a.push(c)}for(var f=this.jpoint(null,null,null),h=this.jpoint(null,null,null),l=i;l>0;l--){for(u=0;u=0;c--){for(t=0;c>=0&&0===a[c];c--)t++;if(c>=0&&t++,u=u.dblp(t),c<0)break;var f=a[c];s(0!==f),u="affine"===e.type?f>0?u.mixedAdd(i[f-1>>1]):u.mixedAdd(i[-f-1>>1].neg()):f>0?u.add(i[f-1>>1]):u.add(i[-f-1>>1].neg())}return"affine"===e.type?u.toP():u},u.prototype._wnafMulAdd=function(e,t,r,n,i){for(var s=this._wnafT1,u=this._wnafT2,c=this._wnafT3,f=0,h=0;h=1;h-=2){var d=h-1,p=h;if(1===s[d]&&1===s[p]){var b=[t[d],null,null,t[p]];0===t[d].y.cmp(t[p].y)?(b[1]=t[d].add(t[p]),b[2]=t[d].toJ().mixedAdd(t[p].neg())):0===t[d].y.cmp(t[p].y.redNeg())?(b[1]=t[d].toJ().mixedAdd(t[p]),b[2]=t[d].add(t[p].neg())):(b[1]=t[d].toJ().mixedAdd(t[p]),b[2]=t[d].toJ().mixedAdd(t[p].neg()));var y=[-3,-1,-5,-7,0,7,5,1,3],m=a(r[d],r[p]);f=Math.max(m[0].length,f),c[d]=new Array(f),c[p]=new Array(f);for(var v=0;v=0;h--){for(var E=0;h>=0;){var x=!0;for(v=0;v=0&&E++,_=_.dblp(E),h<0)break;for(v=0;v0?k=u[v][S-1>>1]:S<0&&(k=u[v][-S-1>>1].neg()),_="affine"===k.type?_.mixedAdd(k):_.add(k))}}for(h=0;h=Math.ceil((e.bitLength()+1)/t.step)},c.prototype._getDoubles=function(e,t){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i":""},f.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&0===this.y.cmp(this.z)},f.prototype._extDbl=function(){var e=this.x.redSqr(),t=this.y.redSqr(),r=this.z.redSqr();r=r.redIAdd(r);var n=this.curve._mulA(e),i=this.x.redAdd(this.y).redSqr().redISub(e).redISub(t),o=n.redAdd(t),a=o.redSub(r),s=n.redSub(t),u=i.redMul(a),c=o.redMul(s),f=i.redMul(s),h=a.redMul(o);return this.curve.point(u,c,h,f)},f.prototype._projDbl=function(){var e,t,r,n=this.x.redAdd(this.y).redSqr(),i=this.x.redSqr(),o=this.y.redSqr();if(this.curve.twisted){var a=(c=this.curve._mulA(i)).redAdd(o);if(this.zOne)e=n.redSub(i).redSub(o).redMul(a.redSub(this.curve.two)),t=a.redMul(c.redSub(o)),r=a.redSqr().redSub(a).redSub(a);else{var s=this.z.redSqr(),u=a.redSub(s).redISub(s);e=n.redSub(i).redISub(o).redMul(u),t=a.redMul(c.redSub(o)),r=a.redMul(u)}}else{var c=i.redAdd(o);s=this.curve._mulC(this.c.redMul(this.z)).redSqr(),u=c.redSub(s).redSub(s);e=this.curve._mulC(n.redISub(c)).redMul(u),t=this.curve._mulC(c).redMul(i.redISub(o)),r=c.redMul(u)}return this.curve.point(e,t,r)},f.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},f.prototype._extAdd=function(e){var t=this.y.redSub(this.x).redMul(e.y.redSub(e.x)),r=this.y.redAdd(this.x).redMul(e.y.redAdd(e.x)),n=this.t.redMul(this.curve.dd).redMul(e.t),i=this.z.redMul(e.z.redAdd(e.z)),o=r.redSub(t),a=i.redSub(n),s=i.redAdd(n),u=r.redAdd(t),c=o.redMul(a),f=s.redMul(u),h=o.redMul(u),l=a.redMul(s);return this.curve.point(c,f,l,h)},f.prototype._projAdd=function(e){var t,r,n=this.z.redMul(e.z),i=n.redSqr(),o=this.x.redMul(e.x),a=this.y.redMul(e.y),s=this.curve.d.redMul(o).redMul(a),u=i.redSub(s),c=i.redAdd(s),f=this.x.redAdd(this.y).redMul(e.x.redAdd(e.y)).redISub(o).redISub(a),h=n.redMul(u).redMul(f);return this.curve.twisted?(t=n.redMul(c).redMul(a.redSub(this.curve._mulA(o))),r=u.redMul(c)):(t=n.redMul(c).redMul(a.redSub(o)),r=this.curve._mulC(u).redMul(c)),this.curve.point(h,t,r)},f.prototype.add=function(e){return this.isInfinity()?e:e.isInfinity()?this:this.curve.extended?this._extAdd(e):this._projAdd(e)},f.prototype.mul=function(e){return this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve._wnafMul(this,e)},f.prototype.mulAdd=function(e,t,r){return this.curve._wnafMulAdd(1,[this,t],[e,r],2,!1)},f.prototype.jmulAdd=function(e,t,r){return this.curve._wnafMulAdd(1,[this,t],[e,r],2,!0)},f.prototype.normalize=function(){if(this.zOne)return this;var e=this.z.redInvm();return this.x=this.x.redMul(e),this.y=this.y.redMul(e),this.t&&(this.t=this.t.redMul(e)),this.z=this.curve.one,this.zOne=!0,this},f.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},f.prototype.getX=function(){return this.normalize(),this.x.fromRed()},f.prototype.getY=function(){return this.normalize(),this.y.fromRed()},f.prototype.eq=function(e){return this===e||0===this.getX().cmp(e.getX())&&0===this.getY().cmp(e.getY())},f.prototype.eqXToP=function(e){var t=e.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(t))return!0;for(var r=e.clone(),n=this.curve.redN.redMul(this.z);;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(t.redIAdd(n),0===this.x.cmp(t))return!0}return!1},f.prototype.toP=f.prototype.normalize,f.prototype.mixedAdd=f.prototype.add},{"../../elliptic":109,"../curve":112,"bn.js":53,inherits:180}],112:[function(e,t,r){"use strict";var n=r;n.base=e("./base"),n.short=e("./short"),n.mont=e("./mont"),n.edwards=e("./edwards")},{"./base":110,"./edwards":111,"./mont":113,"./short":114}],113:[function(e,t,r){"use strict";var n=e("../curve"),i=e("bn.js"),o=e("inherits"),a=n.base,s=e("../../elliptic").utils;function u(e){a.call(this,"mont",e),this.a=new i(e.a,16).toRed(this.red),this.b=new i(e.b,16).toRed(this.red),this.i4=new i(4).toRed(this.red).redInvm(),this.two=new i(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}function c(e,t,r){a.BasePoint.call(this,e,"projective"),null===t&&null===r?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new i(t,16),this.z=new i(r,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}o(u,a),t.exports=u,u.prototype.validate=function(e){var t=e.normalize().x,r=t.redSqr(),n=r.redMul(t).redAdd(r.redMul(this.a)).redAdd(t);return 0===n.redSqrt().redSqr().cmp(n)},o(c,a.BasePoint),u.prototype.decodePoint=function(e,t){return this.point(s.toArray(e,t),1)},u.prototype.point=function(e,t){return new c(this,e,t)},u.prototype.pointFromJSON=function(e){return c.fromJSON(this,e)},c.prototype.precompute=function(){},c.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},c.fromJSON=function(e,t){return new c(e,t[0],t[1]||e.one)},c.prototype.inspect=function(){return this.isInfinity()?"":""},c.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},c.prototype.dbl=function(){var e=this.x.redAdd(this.z).redSqr(),t=this.x.redSub(this.z).redSqr(),r=e.redSub(t),n=e.redMul(t),i=r.redMul(t.redAdd(this.curve.a24.redMul(r)));return this.curve.point(n,i)},c.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.diffAdd=function(e,t){var r=this.x.redAdd(this.z),n=this.x.redSub(this.z),i=e.x.redAdd(e.z),o=e.x.redSub(e.z).redMul(r),a=i.redMul(n),s=t.z.redMul(o.redAdd(a).redSqr()),u=t.x.redMul(o.redISub(a).redSqr());return this.curve.point(s,u)},c.prototype.mul=function(e){for(var t=e.clone(),r=this,n=this.curve.point(null,null),i=[];0!==t.cmpn(0);t.iushrn(1))i.push(t.andln(1));for(var o=i.length-1;o>=0;o--)0===i[o]?(r=r.diffAdd(n,this),n=n.dbl()):(n=r.diffAdd(n,this),r=r.dbl());return n},c.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.eq=function(e){return 0===this.getX().cmp(e.getX())},c.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},c.prototype.getX=function(){return this.normalize(),this.x.fromRed()}},{"../../elliptic":109,"../curve":112,"bn.js":53,inherits:180}],114:[function(e,t,r){"use strict";var n=e("../curve"),i=e("../../elliptic"),o=e("bn.js"),a=e("inherits"),s=n.base,u=i.utils.assert;function c(e){s.call(this,"short",e),this.a=new o(e.a,16).toRed(this.red),this.b=new o(e.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=0===this.a.fromRed().cmpn(0),this.threeA=0===this.a.fromRed().sub(this.p).cmpn(-3),this.endo=this._getEndomorphism(e),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}function f(e,t,r,n){s.BasePoint.call(this,e,"affine"),null===t&&null===r?(this.x=null,this.y=null,this.inf=!0):(this.x=new o(t,16),this.y=new o(r,16),n&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}function h(e,t,r,n){s.BasePoint.call(this,e,"jacobian"),null===t&&null===r&&null===n?(this.x=this.curve.one,this.y=this.curve.one,this.z=new o(0)):(this.x=new o(t,16),this.y=new o(r,16),this.z=new o(n,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}a(c,s),t.exports=c,c.prototype._getEndomorphism=function(e){if(this.zeroA&&this.g&&this.n&&1===this.p.modn(3)){var t,r;if(e.beta)t=new o(e.beta,16).toRed(this.red);else{var n=this._getEndoRoots(this.p);t=(t=n[0].cmp(n[1])<0?n[0]:n[1]).toRed(this.red)}if(e.lambda)r=new o(e.lambda,16);else{var i=this._getEndoRoots(this.n);0===this.g.mul(i[0]).x.cmp(this.g.x.redMul(t))?r=i[0]:(r=i[1],u(0===this.g.mul(r).x.cmp(this.g.x.redMul(t))))}return{beta:t,lambda:r,basis:e.basis?e.basis.map(function(e){return{a:new o(e.a,16),b:new o(e.b,16)}}):this._getEndoBasis(r)}}},c.prototype._getEndoRoots=function(e){var t=e===this.p?this.red:o.mont(e),r=new o(2).toRed(t).redInvm(),n=r.redNeg(),i=new o(3).toRed(t).redNeg().redSqrt().redMul(r);return[n.redAdd(i).fromRed(),n.redSub(i).fromRed()]},c.prototype._getEndoBasis=function(e){for(var t,r,n,i,a,s,u,c,f,h=this.n.ushrn(Math.floor(this.n.bitLength()/2)),l=e,d=this.n.clone(),p=new o(1),b=new o(0),y=new o(0),m=new o(1),v=0;0!==l.cmpn(0);){var g=d.div(l);c=d.sub(g.mul(l)),f=y.sub(g.mul(p));var w=m.sub(g.mul(b));if(!n&&c.cmp(h)<0)t=u.neg(),r=p,n=c.neg(),i=f;else if(n&&2==++v)break;u=c,d=l,l=c,y=p,p=f,m=b,b=w}a=c.neg(),s=f;var _=n.sqr().add(i.sqr());return a.sqr().add(s.sqr()).cmp(_)>=0&&(a=t,s=r),n.negative&&(n=n.neg(),i=i.neg()),a.negative&&(a=a.neg(),s=s.neg()),[{a:n,b:i},{a:a,b:s}]},c.prototype._endoSplit=function(e){var t=this.endo.basis,r=t[0],n=t[1],i=n.b.mul(e).divRound(this.n),o=r.b.neg().mul(e).divRound(this.n),a=i.mul(r.a),s=o.mul(n.a),u=i.mul(r.b),c=o.mul(n.b);return{k1:e.sub(a).sub(s),k2:u.add(c).neg()}},c.prototype.pointFromX=function(e,t){(e=new o(e,16)).red||(e=e.toRed(this.red));var r=e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(0!==n.redSqr().redSub(r).cmp(this.zero))throw new Error("invalid point");var i=n.fromRed().isOdd();return(t&&!i||!t&&i)&&(n=n.redNeg()),this.point(e,n)},c.prototype.validate=function(e){if(e.inf)return!0;var t=e.x,r=e.y,n=this.a.redMul(t),i=t.redSqr().redMul(t).redIAdd(n).redIAdd(this.b);return 0===r.redSqr().redISub(i).cmpn(0)},c.prototype._endoWnafMulAdd=function(e,t,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,o=0;o":""},f.prototype.isInfinity=function(){return this.inf},f.prototype.add=function(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return this.curve.point(null,null);if(0===this.x.cmp(e.x))return this.curve.point(null,null);var t=this.y.redSub(e.y);0!==t.cmpn(0)&&(t=t.redMul(this.x.redSub(e.x).redInvm()));var r=t.redSqr().redISub(this.x).redISub(e.x),n=t.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},f.prototype.dbl=function(){if(this.inf)return this;var e=this.y.redAdd(this.y);if(0===e.cmpn(0))return this.curve.point(null,null);var t=this.curve.a,r=this.x.redSqr(),n=e.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(t).redMul(n),o=i.redSqr().redISub(this.x.redAdd(this.x)),a=i.redMul(this.x.redSub(o)).redISub(this.y);return this.curve.point(o,a)},f.prototype.getX=function(){return this.x.fromRed()},f.prototype.getY=function(){return this.y.fromRed()},f.prototype.mul=function(e){return e=new o(e,16),this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve.endo?this.curve._endoWnafMulAdd([this],[e]):this.curve._wnafMul(this,e)},f.prototype.mulAdd=function(e,t,r){var n=[this,t],i=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},f.prototype.jmulAdd=function(e,t,r){var n=[this,t],i=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},f.prototype.eq=function(e){return this===e||this.inf===e.inf&&(this.inf||0===this.x.cmp(e.x)&&0===this.y.cmp(e.y))},f.prototype.neg=function(e){if(this.inf)return this;var t=this.curve.point(this.x,this.y.redNeg());if(e&&this.precomputed){var r=this.precomputed,n=function(e){return e.neg()};t.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return t},f.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},a(h,s.BasePoint),c.prototype.jpoint=function(e,t,r){return new h(this,e,t,r)},h.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var e=this.z.redInvm(),t=e.redSqr(),r=this.x.redMul(t),n=this.y.redMul(t).redMul(e);return this.curve.point(r,n)},h.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},h.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(t),i=e.x.redMul(r),o=this.y.redMul(t.redMul(e.z)),a=e.y.redMul(r.redMul(this.z)),s=n.redSub(i),u=o.redSub(a);if(0===s.cmpn(0))return 0!==u.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var c=s.redSqr(),f=c.redMul(s),h=n.redMul(c),l=u.redSqr().redIAdd(f).redISub(h).redISub(h),d=u.redMul(h.redISub(l)).redISub(o.redMul(f)),p=this.z.redMul(e.z).redMul(s);return this.curve.jpoint(l,d,p)},h.prototype.mixedAdd=function(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;var t=this.z.redSqr(),r=this.x,n=e.x.redMul(t),i=this.y,o=e.y.redMul(t).redMul(this.z),a=r.redSub(n),s=i.redSub(o);if(0===a.cmpn(0))return 0!==s.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var u=a.redSqr(),c=u.redMul(a),f=r.redMul(u),h=s.redSqr().redIAdd(c).redISub(f).redISub(f),l=s.redMul(f.redISub(h)).redISub(i.redMul(c)),d=this.z.redMul(a);return this.curve.jpoint(h,l,d)},h.prototype.dblp=function(e){if(0===e)return this;if(this.isInfinity())return this;if(!e)return this.dbl();if(this.curve.zeroA||this.curve.threeA){for(var t=this,r=0;r=0)return!1;if(r.redIAdd(i),0===this.x.cmp(r))return!0}return!1},h.prototype.inspect=function(){return this.isInfinity()?"":""},h.prototype.isInfinity=function(){return 0===this.z.cmpn(0)}},{"../../elliptic":109,"../curve":112,"bn.js":53,inherits:180}],115:[function(e,t,r){"use strict";var n,i=r,o=e("hash.js"),a=e("../elliptic"),s=a.utils.assert;function u(e){"short"===e.type?this.curve=new a.curve.short(e):"edwards"===e.type?this.curve=new a.curve.edwards(e):this.curve=new a.curve.mont(e),this.g=this.curve.g,this.n=this.curve.n,this.hash=e.hash,s(this.g.validate(),"Invalid curve"),s(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}function c(e,t){Object.defineProperty(i,e,{configurable:!0,enumerable:!0,get:function(){var r=new u(t);return Object.defineProperty(i,e,{configurable:!0,enumerable:!0,value:r}),r}})}i.PresetCurve=u,c("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:o.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),c("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:o.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),c("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:o.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),c("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:o.sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),c("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:o.sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),c("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:o.sha256,gRed:!1,g:["9"]}),c("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:o.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});try{n=e("./precomputed/secp256k1")}catch(e){n=void 0}c("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:o.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",n]})},{"../elliptic":109,"./precomputed/secp256k1":122,"hash.js":162}],116:[function(e,t,r){"use strict";var n=e("bn.js"),i=e("hmac-drbg"),o=e("../../elliptic"),a=o.utils.assert,s=e("./key"),u=e("./signature");function c(e){if(!(this instanceof c))return new c(e);"string"==typeof e&&(a(o.curves.hasOwnProperty(e),"Unknown curve "+e),e=o.curves[e]),e instanceof o.curves.PresetCurve&&(e={curve:e}),this.curve=e.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=e.curve.g,this.g.precompute(e.curve.n.bitLength()+1),this.hash=e.hash||e.curve.hash}t.exports=c,c.prototype.keyPair=function(e){return new s(this,e)},c.prototype.keyFromPrivate=function(e,t){return s.fromPrivate(this,e,t)},c.prototype.keyFromPublic=function(e,t){return s.fromPublic(this,e,t)},c.prototype.genKeyPair=function(e){e||(e={});for(var t=new i({hash:this.hash,pers:e.pers,persEnc:e.persEnc||"utf8",entropy:e.entropy||o.rand(this.hash.hmacStrength),entropyEnc:e.entropy&&e.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),a=this.n.sub(new n(2));;){var s=new n(t.generate(r));if(!(s.cmp(a)>0))return s.iaddn(1),this.keyFromPrivate(s)}},c.prototype._truncateToN=function(e,t){var r=8*e.byteLength()-this.n.bitLength();return r>0&&(e=e.ushrn(r)),!t&&e.cmp(this.n)>=0?e.sub(this.n):e},c.prototype.sign=function(e,t,r,o){"object"==typeof r&&(o=r,r=null),o||(o={}),t=this.keyFromPrivate(t,r),e=this._truncateToN(new n(e,16));for(var a=this.n.byteLength(),s=t.getPrivate().toArray("be",a),c=e.toArray("be",a),f=new i({hash:this.hash,entropy:s,nonce:c,pers:o.pers,persEnc:o.persEnc||"utf8"}),h=this.n.sub(new n(1)),l=0;;l++){var d=o.k?o.k(l):new n(f.generate(this.n.byteLength()));if(!((d=this._truncateToN(d,!0)).cmpn(1)<=0||d.cmp(h)>=0)){var p=this.g.mul(d);if(!p.isInfinity()){var b=p.getX(),y=b.umod(this.n);if(0!==y.cmpn(0)){var m=d.invm(this.n).mul(y.mul(t.getPrivate()).iadd(e));if(0!==(m=m.umod(this.n)).cmpn(0)){var v=(p.getY().isOdd()?1:0)|(0!==b.cmp(y)?2:0);return o.canonical&&m.cmp(this.nh)>0&&(m=this.n.sub(m),v^=1),new u({r:y,s:m,recoveryParam:v})}}}}}},c.prototype.verify=function(e,t,r,i){e=this._truncateToN(new n(e,16)),r=this.keyFromPublic(r,i);var o=(t=new u(t,"hex")).r,a=t.s;if(o.cmpn(1)<0||o.cmp(this.n)>=0)return!1;if(a.cmpn(1)<0||a.cmp(this.n)>=0)return!1;var s,c=a.invm(this.n),f=c.mul(e).umod(this.n),h=c.mul(o).umod(this.n);return this.curve._maxwellTrick?!(s=this.g.jmulAdd(f,r.getPublic(),h)).isInfinity()&&s.eqXToP(o):!(s=this.g.mulAdd(f,r.getPublic(),h)).isInfinity()&&0===s.getX().umod(this.n).cmp(o)},c.prototype.recoverPubKey=function(e,t,r,i){a((3&r)===r,"The recovery param is more than two bits"),t=new u(t,i);var o=this.n,s=new n(e),c=t.r,f=t.s,h=1&r,l=r>>1;if(c.cmp(this.curve.p.umod(this.curve.n))>=0&&l)throw new Error("Unable to find sencond key candinate");c=l?this.curve.pointFromX(c.add(this.curve.n),h):this.curve.pointFromX(c,h);var d=t.r.invm(o),p=o.sub(s).mul(d).umod(o),b=f.mul(d).umod(o);return this.g.mulAdd(p,c,b)},c.prototype.getKeyRecoveryParam=function(e,t,r,n){if(null!==(t=new u(t,n)).recoveryParam)return t.recoveryParam;for(var i=0;i<4;i++){var o;try{o=this.recoverPubKey(e,t,i)}catch(e){continue}if(o.eq(r))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(e,t,r){"use strict";var n=e("bn.js"),i=e("../../elliptic").utils.assert;function o(e,t){this.ec=e,this.priv=null,this.pub=null,t.priv&&this._importPrivate(t.priv,t.privEnc),t.pub&&this._importPublic(t.pub,t.pubEnc)}t.exports=o,o.fromPublic=function(e,t,r){return t instanceof o?t:new o(e,{pub:t,pubEnc:r})},o.fromPrivate=function(e,t,r){return t instanceof o?t:new o(e,{priv:t,privEnc:r})},o.prototype.validate=function(){var e=this.getPublic();return e.isInfinity()?{result:!1,reason:"Invalid public key"}:e.validate()?e.mul(this.ec.curve.n).isInfinity()?{result:!0,reason:null}:{result:!1,reason:"Public key * N != O"}:{result:!1,reason:"Public key is not a point"}},o.prototype.getPublic=function(e,t){return"string"==typeof e&&(t=e,e=null),this.pub||(this.pub=this.ec.g.mul(this.priv)),t?this.pub.encode(t,e):this.pub},o.prototype.getPrivate=function(e){return"hex"===e?this.priv.toString(16,2):this.priv},o.prototype._importPrivate=function(e,t){this.priv=new n(e,t||16),this.priv=this.priv.umod(this.ec.curve.n)},o.prototype._importPublic=function(e,t){if(e.x||e.y)return"mont"===this.ec.curve.type?i(e.x,"Need x coordinate"):"short"!==this.ec.curve.type&&"edwards"!==this.ec.curve.type||i(e.x&&e.y,"Need both x and y coordinate"),void(this.pub=this.ec.curve.point(e.x,e.y));this.pub=this.ec.curve.decodePoint(e,t)},o.prototype.derive=function(e){return e.mul(this.priv).getX()},o.prototype.sign=function(e,t,r){return this.ec.sign(e,this,t,r)},o.prototype.verify=function(e,t){return this.ec.verify(e,t,this)},o.prototype.inspect=function(){return""}},{"../../elliptic":109,"bn.js":53}],118:[function(e,t,r){"use strict";var n=e("bn.js"),i=e("../../elliptic").utils,o=i.assert;function a(e,t){if(e instanceof a)return e;this._importDER(e,t)||(o(e.r&&e.s,"Signature without r or s"),this.r=new n(e.r,16),this.s=new n(e.s,16),void 0===e.recoveryParam?this.recoveryParam=null:this.recoveryParam=e.recoveryParam)}function s(e,t){var r=e[t.place++];if(!(128&r))return r;for(var n=15&r,i=0,o=0,a=t.place;o>>3);for(e.push(128|r);--r;)e.push(t>>>(r<<3)&255);e.push(t)}}t.exports=a,a.prototype._importDER=function(e,t){e=i.toArray(e,t);var r=new function(){this.place=0};if(48!==e[r.place++])return!1;if(s(e,r)+r.place!==e.length)return!1;if(2!==e[r.place++])return!1;var o=s(e,r),a=e.slice(r.place,o+r.place);if(r.place+=o,2!==e[r.place++])return!1;var u=s(e,r);if(e.length!==u+r.place)return!1;var c=e.slice(r.place,u+r.place);return 0===a[0]&&128&a[1]&&(a=a.slice(1)),0===c[0]&&128&c[1]&&(c=c.slice(1)),this.r=new n(a),this.s=new n(c),this.recoveryParam=null,!0},a.prototype.toDER=function(e){var t=this.r.toArray(),r=this.s.toArray();for(128&t[0]&&(t=[0].concat(t)),128&r[0]&&(r=[0].concat(r)),t=u(t),r=u(r);!(r[0]||128&r[1]);)r=r.slice(1);var n=[2];c(n,t.length),(n=n.concat(t)).push(2),c(n,r.length);var o=n.concat(r),a=[48];return c(a,o.length),a=a.concat(o),i.encode(a,e)}},{"../../elliptic":109,"bn.js":53}],119:[function(e,t,r){"use strict";var n=e("hash.js"),i=e("../../elliptic"),o=i.utils,a=o.assert,s=o.parseBytes,u=e("./key"),c=e("./signature");function f(e){if(a("ed25519"===e,"only tested with ed25519 so far"),!(this instanceof f))return new f(e);e=i.curves[e].curve;this.curve=e,this.g=e.g,this.g.precompute(e.n.bitLength()+1),this.pointClass=e.point().constructor,this.encodingLength=Math.ceil(e.n.bitLength()/8),this.hash=n.sha512}t.exports=f,f.prototype.sign=function(e,t){e=s(e);var r=this.keyFromSecret(t),n=this.hashInt(r.messagePrefix(),e),i=this.g.mul(n),o=this.encodePoint(i),a=this.hashInt(o,r.pubBytes(),e).mul(r.priv()),u=n.add(a).umod(this.curve.n);return this.makeSignature({R:i,S:u,Rencoded:o})},f.prototype.verify=function(e,t,r){e=s(e),t=this.makeSignature(t);var n=this.keyFromPublic(r),i=this.hashInt(t.Rencoded(),n.pubBytes(),e),o=this.g.mul(t.S());return t.R().add(n.pub().mul(i)).eq(o)},f.prototype.hashInt=function(){for(var e=this.hash(),t=0;t=0;){var o;if(i.isOdd()){var a=i.andln(n-1);o=a>(n>>1)-1?(n>>1)-a:a,i.isubn(o)}else o=0;r.push(o);for(var s=0!==i.cmpn(0)&&0===i.andln(n-1)?t+1:1,u=1;u0||t.cmpn(-i)>0;){var o,a,s,u=e.andln(3)+n&3,c=t.andln(3)+i&3;3===u&&(u=-1),3===c&&(c=-1),o=0==(1&u)?0:3!=(s=e.andln(7)+n&7)&&5!==s||2!==c?u:-u,r[0].push(o),a=0==(1&c)?0:3!=(s=t.andln(7)+i&7)&&5!==s||2!==u?c:-c,r[1].push(a),2*n===o+1&&(n=1-n),2*i===a+1&&(i=1-i),e.iushrn(1),t.iushrn(1)}return r},n.cachedProperty=function(e,t,r){var n="_"+t;e.prototype[t]=function(){return void 0!==this[n]?this[n]:this[n]=r.call(this)}},n.parseBytes=function(e){return"string"==typeof e?n.toArray(e,"hex"):e},n.intFromLE=function(e){return new i(e,"hex","le")}},{"bn.js":53,"minimalistic-assert":234,"minimalistic-crypto-utils":235}],124:[function(e,t,r){t.exports={_from:"elliptic@^6.0.0",_id:"elliptic@6.4.0",_inBundle:!1,_integrity:"sha1-ysmvh2LIWDYYcAPI3+GT5eLq5d8=",_location:"/elliptic",_phantomChildren:{},_requested:{type:"range",registry:!0,raw:"elliptic@^6.0.0",name:"elliptic",escapedName:"elliptic",rawSpec:"^6.0.0",saveSpec:null,fetchSpec:"^6.0.0"},_requiredBy:["/browserify-sign","/create-ecdh"],_resolved:"https://registry.npmjs.org/elliptic/-/elliptic-6.4.0.tgz",_shasum:"cac9af8762c85836187003c8dfe193e5e2eae5df",_spec:"elliptic@^6.0.0",_where:"/Users/alexvlasov/Blockchain/web3swift_jsproxy/node_modules/browserify-sign",author:{name:"Fedor Indutny",email:"fedor@indutny.com"},bugs:{url:"https://github.com/indutny/elliptic/issues"},bundleDependencies:!1,dependencies:{"bn.js":"^4.4.0",brorand:"^1.0.1","hash.js":"^1.0.0","hmac-drbg":"^1.0.0",inherits:"^2.0.1","minimalistic-assert":"^1.0.0","minimalistic-crypto-utils":"^1.0.0"},deprecated:!1,description:"EC cryptography",devDependencies:{brfs:"^1.4.3",coveralls:"^2.11.3",grunt:"^0.4.5","grunt-browserify":"^5.0.0","grunt-cli":"^1.2.0","grunt-contrib-connect":"^1.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^1.0.1","grunt-mocha-istanbul":"^3.0.1","grunt-saucelabs":"^8.6.2",istanbul:"^0.4.2",jscs:"^2.9.0",jshint:"^2.6.0",mocha:"^2.1.0"},files:["lib"],homepage:"https://github.com/indutny/elliptic",keywords:["EC","Elliptic","curve","Cryptography"],license:"MIT",main:"lib/elliptic.js",name:"elliptic",repository:{type:"git",url:"git+ssh://git@github.com/indutny/elliptic.git"},scripts:{jscs:"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",jshint:"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",lint:"npm run jscs && npm run jshint",test:"npm run lint && npm run unit",unit:"istanbul test _mocha --reporter=spec test/index.js",version:"grunt dist && git add dist/"},version:"6.4.0"}},{}],125:[function(e,t,r){"use strict";const n=e("ethjs-util");function i(e){let t=n.stripHexPrefix(e);for(;"0"===t[0];)t=t.substr(1);return`0x${t}`}t.exports={incrementHexNumber:function(e){return i(n.intToHex(parseInt(e,16)+1))},formatHex:i}},{"ethjs-util":155}],126:[function(e,t,r){const n=e("eth-query"),i=e("events"),o=e("pify"),a=e("./hexUtils"),s=a.incrementHexNumber,u=1e3,c=60*u;t.exports=class extends i{constructor(e={}){if(super(),!e.provider)throw new Error("RpcBlockTracker - no provider specified.");this._provider=e.provider,this._query=new n(e.provider),this._pollingInterval=e.pollingInterval||4*u,this._syncingTimeout=e.syncingTimeout||1*c,this._trackingBlock=null,this._trackingBlockTimestamp=null,this._currentBlock=null,this._isRunning=!1,this._performSync=this._performSync.bind(this),this._handleNewBlockNotification=this._handleNewBlockNotification.bind(this)}getTrackingBlock(){return this._trackingBlock}getCurrentBlock(){return this._currentBlock}async awaitCurrentBlock(){return this._currentBlock?this._currentBlock:(await new Promise(e=>this.once("latest",e)),this._currentBlock)}async start(e={}){this._isRunning||(this._isRunning=!0,e.fromBlock?await this._setTrackingBlock(await this._fetchBlockByNumber(e.fromBlock)):await this._setTrackingBlock(await this._fetchLatestBlock()),this._provider.on?await this._initSubscription():this._performSync().catch(e=>{e&&console.error(e)}))}async stop(){this._isRunning=!1,this._provider.on&&await this._removeSubscription()}async _setTrackingBlock(e){if(this._trackingBlock&&this._trackingBlock.hash===e.hash)return;const t=this._trackingBlockTimestamp,r=Date.now();t&&r-t>this._syncingTimeout?(this._trackingBlockTimestamp=null,await this._warpToLatest()):(this._trackingBlock=e,this._trackingBlockTimestamp=r,this.emit("block",e))}async _setCurrentBlock(e){if(this._currentBlock&&this._currentBlock.hash===e.hash)return;const t=this._currentBlock;this._currentBlock=e,this.emit("latest",e),this.emit("sync",{newBlock:e,oldBlock:t})}async _warpToLatest(){await this._setTrackingBlock(await this._fetchLatestBlock())}async _pollForNextBlock(){setTimeout(()=>this._performSync(),this._pollingInterval)}async _performSync(){if(!this._isRunning)return;const e=this.getTrackingBlock();if(!e)throw new Error("RpcBlockTracker - tracking block is missing");const t=s(e.number);try{const r=await this._fetchBlockByNumber(t);r?(await this._setTrackingBlock(r),this._performSync()):(await this._setCurrentBlock(e),this._pollForNextBlock())}catch(t){t.message.includes("index out of range")||t.message.includes("Couldn't find block by reference")?(await this._setCurrentBlock(e),this._pollForNextBlock()):(console.error(t),this._pollForNextBlock())}}async _handleNewBlockNotification(e,t){t.id==this._subscriptionId&&(e&&(this.emit("error",e),await this._removeSubscription()),await this._setTrackingBlock(await this._fetchBlockByNumber(t.result.number)))}async _initSubscription(){this._provider.on("data",this._handleNewBlockNotification);let e=await o(this._provider.sendAsync||this._provider.send)({jsonrpc:"2.0",id:(new Date).getTime(),method:"eth_subscribe",params:["newHeads"]});this._subscriptionId=e.result}async _removeSubscription(){if(!this._subscriptionId)throw new Error("Not subscribed.");this._provider.removeListener("data",this._handleNewBlockNotification),await o(this._provider.sendAsync||this._provider.send)({jsonrpc:"2.0",id:(new Date).getTime(),method:"eth_unsubscribe",params:[this._subscriptionId]}),delete this._subscriptionId}_fetchLatestBlock(){return o(this._query.getBlockByNumber).call(this._query,"latest",!0)}_fetchBlockByNumber(e){const t=a.formatHex(e);return o(this._query.getBlockByNumber).call(this._query,t,!0)}}},{"./hexUtils":125,"eth-query":135,events:157,pify:252}],127:[function(e,t,r){(function(t){var n=e("js-sha3").keccak_256,i=e("idna-uts46-hx");function o(e){return e?i.toUnicode(e,{useStd3ASCII:!0,transitional:!1}):e}r.hash=function(e){for(var r="",i=0;i<32;i++)r+="00";if(name=o(e),name){var a=name.split(".");for(i=a.length-1;i>=0;i--){var s=n(a[i]);r=n(new t(r+s,"hex"))}}return"0x"+r},r.normalize=o}).call(this,e("buffer").Buffer)},{buffer:84,"idna-uts46-hx":177,"js-sha3":128}],128:[function(e,t,r){(function(e,r){!function(){"use strict";var n="object"==typeof window?window:{};!n.JS_SHA3_NO_NODE_JS&&"object"==typeof e&&e.versions&&e.versions.node&&(n=r);for(var i=!n.JS_SHA3_NO_COMMON_JS&&"object"==typeof t&&t.exports,o="0123456789abcdef".split(""),a=[0,8,16,24],s=[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],u=[224,256,384,512],c=["hex","buffer","arrayBuffer","array"],f=function(e,t,r){return function(n){return new _(e,t,e).update(n)[r]()}},h=function(e,t,r){return function(n,i){return new _(e,t,i).update(n)[r]()}},l=function(e,t){var r=f(e,t,"hex");r.create=function(){return new _(e,t,e)},r.update=function(e){return r.create().update(e)};for(var n=0;n>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var n=0;n<50;++n)this.s[n]=0}_.prototype.update=function(e){var t="string"!=typeof e;t&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e));for(var r,n,i=e.length,o=this.blocks,s=this.byteCount,u=this.blockCount,c=0,f=this.s;c>2]|=e[c]<>2]|=n<>2]|=(192|n>>6)<>2]|=(128|63&n)<=57344?(o[r>>2]|=(224|n>>12)<>2]|=(128|n>>6&63)<>2]|=(128|63&n)<>2]|=(240|n>>18)<>2]|=(128|n>>12&63)<>2]|=(128|n>>6&63)<>2]|=(128|63&n)<=s){for(this.start=r-s,this.block=o[u],r=0;r>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t>4&15]+o[15&e]+o[e>>12&15]+o[e>>8&15]+o[e>>20&15]+o[e>>16&15]+o[e>>28&15]+o[e>>24&15];s%t==0&&(A(r),a=0)}return i&&(e=r[a],i>0&&(u+=o[e>>4&15]+o[15&e]),i>1&&(u+=o[e>>12&15]+o[e>>8&15]),i>2&&(u+=o[e>>20&15]+o[e>>16&15])),u},_.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,i=this.extraBytes,o=0,a=0,s=this.outputBits>>3;e=i?new ArrayBuffer(n+1<<2):new ArrayBuffer(s);for(var u=new Uint32Array(e);a>8&255,u[e+2]=t>>16&255,u[e+3]=t>>24&255;s%r==0&&A(n)}return o&&(e=s<<2,t=n[a],o>0&&(u[e]=255&t),o>1&&(u[e+1]=t>>8&255),o>2&&(u[e+2]=t>>16&255)),u};var A=function(e){var t,r,n,i,o,a,u,c,f,h,l,d,p,b,y,m,v,g,w,_,A,E,x,k,S,M,I,T,U,j,B,P,C,N,R,L,O,D,F,q,H,z,K,V,G,W,Y,X,Z,J,$,Q,ee,te,re,ne,ie,oe,ae,se,ue,ce,fe;for(n=0;n<48;n+=2)i=e[0]^e[10]^e[20]^e[30]^e[40],o=e[1]^e[11]^e[21]^e[31]^e[41],a=e[2]^e[12]^e[22]^e[32]^e[42],u=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],f=e[5]^e[15]^e[25]^e[35]^e[45],h=e[6]^e[16]^e[26]^e[36]^e[46],l=e[7]^e[17]^e[27]^e[37]^e[47],t=(d=e[8]^e[18]^e[28]^e[38]^e[48])^(a<<1|u>>>31),r=(p=e[9]^e[19]^e[29]^e[39]^e[49])^(u<<1|a>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=i^(c<<1|f>>>31),r=o^(f<<1|c>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=a^(h<<1|l>>>31),r=u^(l<<1|h>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=c^(d<<1|p>>>31),r=f^(p<<1|d>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=h^(i<<1|o>>>31),r=l^(o<<1|i>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,b=e[0],y=e[1],W=e[11]<<4|e[10]>>>28,Y=e[10]<<4|e[11]>>>28,T=e[20]<<3|e[21]>>>29,U=e[21]<<3|e[20]>>>29,se=e[31]<<9|e[30]>>>23,ue=e[30]<<9|e[31]>>>23,z=e[40]<<18|e[41]>>>14,K=e[41]<<18|e[40]>>>14,N=e[2]<<1|e[3]>>>31,R=e[3]<<1|e[2]>>>31,m=e[13]<<12|e[12]>>>20,v=e[12]<<12|e[13]>>>20,X=e[22]<<10|e[23]>>>22,Z=e[23]<<10|e[22]>>>22,j=e[33]<<13|e[32]>>>19,B=e[32]<<13|e[33]>>>19,ce=e[42]<<2|e[43]>>>30,fe=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,L=e[14]<<6|e[15]>>>26,O=e[15]<<6|e[14]>>>26,g=e[25]<<11|e[24]>>>21,w=e[24]<<11|e[25]>>>21,J=e[34]<<15|e[35]>>>17,$=e[35]<<15|e[34]>>>17,P=e[45]<<29|e[44]>>>3,C=e[44]<<29|e[45]>>>3,k=e[6]<<28|e[7]>>>4,S=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,ie=e[16]<<23|e[17]>>>9,D=e[26]<<25|e[27]>>>7,F=e[27]<<25|e[26]>>>7,_=e[36]<<21|e[37]>>>11,A=e[37]<<21|e[36]>>>11,Q=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,V=e[8]<<27|e[9]>>>5,G=e[9]<<27|e[8]>>>5,M=e[18]<<20|e[19]>>>12,I=e[19]<<20|e[18]>>>12,oe=e[29]<<7|e[28]>>>25,ae=e[28]<<7|e[29]>>>25,q=e[38]<<8|e[39]>>>24,H=e[39]<<8|e[38]>>>24,E=e[48]<<14|e[49]>>>18,x=e[49]<<14|e[48]>>>18,e[0]=b^~m&g,e[1]=y^~v&w,e[10]=k^~M&T,e[11]=S^~I&U,e[20]=N^~L&D,e[21]=R^~O&F,e[30]=V^~W&X,e[31]=G^~Y&Z,e[40]=te^~ne&oe,e[41]=re^~ie&ae,e[2]=m^~g&_,e[3]=v^~w&A,e[12]=M^~T&j,e[13]=I^~U&B,e[22]=L^~D&q,e[23]=O^~F&H,e[32]=W^~X&J,e[33]=Y^~Z&$,e[42]=ne^~oe&se,e[43]=ie^~ae&ue,e[4]=g^~_&E,e[5]=w^~A&x,e[14]=T^~j&P,e[15]=U^~B&C,e[24]=D^~q&z,e[25]=F^~H&K,e[34]=X^~J&Q,e[35]=Z^~$&ee,e[44]=oe^~se&ce,e[45]=ae^~ue&fe,e[6]=_^~E&b,e[7]=A^~x&y,e[16]=j^~P&k,e[17]=B^~C&S,e[26]=q^~z&N,e[27]=H^~K&R,e[36]=J^~Q&V,e[37]=$^~ee&G,e[46]=se^~ce&te,e[47]=ue^~fe&re,e[8]=E^~b&m,e[9]=x^~y&v,e[18]=P^~k&M,e[19]=C^~S&I,e[28]=z^~N&L,e[29]=K^~R&O,e[38]=Q^~V&W,e[39]=ee^~G&Y,e[48]=ce^~te&ne,e[49]=fe^~re&ie,e[0]^=s[n],e[1]^=s[n+1]};if(i)t.exports=p;else for(y=0;y{setTimeout(t,e)})}function c(e){const t=e.toString();return s.some(e=>t.includes(e))}async function f(e,t,r){const{fetchUrl:n,fetchParams:a}=h({network:e,req:t}),s=await o(n,a),u=await s.text();if(!s.ok)switch(s.status){case 405:throw new i.MethodNotFound;case 418:throw l("Request is being rate limited.");case 503:case 504:throw function(){let e="Gateway timeout. The request took too long to process. ";return e+="This can happen when querying logs over too wide a block range.",l("Gateway timeout. The request took too long to process. This can happen when querying logs over too wide a block range.")}();default:throw l(u)}if("eth_getBlockByNumber"===t.method&&"Not Found"===u)return void(r.result=null);const c=JSON.parse(u);r.result=c.result,r.error=c.error}function h({network:e,req:t}){const r=function(e){return{id:e.id,jsonrpc:e.jsonrpc,method:e.method,params:e.params}}(t),{method:n,params:i}=r,o={};let s=`https://api.infura.io/v1/jsonrpc/${e}`;if(a.includes(n))o.method="POST",o.headers={Accept:"application/json","Content-Type":"application/json"},o.body=JSON.stringify(r);else{o.method="GET",s+=`/${n}?params=${encodeURIComponent(JSON.stringify(i))}`}return{fetchUrl:s,fetchParams:o}}function l(e){const t=new Error(e);return new i.InternalError(t)}t.exports=function(e={}){const t=e.network||"mainnet",r=e.maxAttempts||5;if(!r)throw new Error(`Invalid value for 'maxAttempts': "${r}" (${typeof r})`);return n(async(e,n,i)=>{for(let i=1;i<=r;i++)try{await f(t,e,n);break}catch(e){if(!c(e))throw e;const t=r-i;if(!t){const t=`InfuraProvider - cannot complete request. All retries exhausted.\nOriginal Error:\n${e.toString()}\n\n`,r=new Error(t);throw r}await u(1e3)}})},t.exports.fetchConfigFromReq=h},{"cross-fetch":96,"json-rpc-engine/src/createAsyncMiddleware":187,"json-rpc-error":189}],131:[function(e,t,r){t.exports=function(e){return{sendAsync:e.handle.bind(e)}}},{}],132:[function(e,t,r){var n=function(e,t){for(var r=[],n=0;n>6|192);else{if(i>55295&&i<56320){if(++n==e.length)return null;var o=e.charCodeAt(n);if(o<56320||o>57343)return null;r+=t((i=65536+((1023&i)<<10)+(1023&o))>>18|240),r+=t(i>>12&63|128)}else r+=t(i>>12|224);r+=t(i>>6&63|128)}r+=t(63&i|128)}}return r},toString:function(e){for(var t="",r=0,o=i(e);r127){if(a>191&&a<224){if(r>=o)return null;a=(31&a)<<6|63&n(e,r)}else if(a>223&&a<240){if(r+1>=o)return null;a=(15&a)<<12|(63&n(e,r))<<6|63&n(e,++r)}else{if(!(a>239&&a<248))return null;if(r+2>=o)return null;a=(7&a)<<18|(63&n(e,r))<<12|(63&n(e,++r))<<6|63&n(e,++r)}++r}if(a<=65535)t+=String.fromCharCode(a);else{if(!(a<=1114111))return null;a-=65536,t+=String.fromCharCode(a>>10|55296),t+=String.fromCharCode(1023&a|56320)}}return t},fromNumber:function(e){var t=e.toString(16);return t.length%2==0?"0x"+t:"0x0"+t},toNumber:function(e){return parseInt(e.slice(2),16)},fromNat:function(e){return"0x0"===e?"0x":e.length%2==0?e:"0x0"+e.slice(2)},toNat:function(e){return"0"===e[2]?"0x"+e.slice(3):e},fromArray:a,toArray:o,fromUint8Array:function(e){return a([].slice.call(e,0))},toUint8Array:function(e){return new Uint8Array(o(e))}}},{"./array.js":132}],134:[function(e,t,r){var n="0123456789abcdef".split(""),i=[1,256,65536,16777216],o=[0,8,16,24],a=[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],s=function(e){var t,r,n,i,o,s,u,c,f,h,l,d,p,b,y,m,v,g,w,_,A,E,x,k,S,M,I,T,U,j,B,P,C,N,R,L,O,D,F,q,H,z,K,V,G,W,Y,X,Z,J,$,Q,ee,te,re,ne,ie,oe,ae,se,ue,ce,fe;for(n=0;n<48;n+=2)i=e[0]^e[10]^e[20]^e[30]^e[40],o=e[1]^e[11]^e[21]^e[31]^e[41],s=e[2]^e[12]^e[22]^e[32]^e[42],u=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],f=e[5]^e[15]^e[25]^e[35]^e[45],h=e[6]^e[16]^e[26]^e[36]^e[46],l=e[7]^e[17]^e[27]^e[37]^e[47],t=(d=e[8]^e[18]^e[28]^e[38]^e[48])^(s<<1|u>>>31),r=(p=e[9]^e[19]^e[29]^e[39]^e[49])^(u<<1|s>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=i^(c<<1|f>>>31),r=o^(f<<1|c>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=s^(h<<1|l>>>31),r=u^(l<<1|h>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=c^(d<<1|p>>>31),r=f^(p<<1|d>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=h^(i<<1|o>>>31),r=l^(o<<1|i>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,b=e[0],y=e[1],W=e[11]<<4|e[10]>>>28,Y=e[10]<<4|e[11]>>>28,T=e[20]<<3|e[21]>>>29,U=e[21]<<3|e[20]>>>29,se=e[31]<<9|e[30]>>>23,ue=e[30]<<9|e[31]>>>23,z=e[40]<<18|e[41]>>>14,K=e[41]<<18|e[40]>>>14,N=e[2]<<1|e[3]>>>31,R=e[3]<<1|e[2]>>>31,m=e[13]<<12|e[12]>>>20,v=e[12]<<12|e[13]>>>20,X=e[22]<<10|e[23]>>>22,Z=e[23]<<10|e[22]>>>22,j=e[33]<<13|e[32]>>>19,B=e[32]<<13|e[33]>>>19,ce=e[42]<<2|e[43]>>>30,fe=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,L=e[14]<<6|e[15]>>>26,O=e[15]<<6|e[14]>>>26,g=e[25]<<11|e[24]>>>21,w=e[24]<<11|e[25]>>>21,J=e[34]<<15|e[35]>>>17,$=e[35]<<15|e[34]>>>17,P=e[45]<<29|e[44]>>>3,C=e[44]<<29|e[45]>>>3,k=e[6]<<28|e[7]>>>4,S=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,ie=e[16]<<23|e[17]>>>9,D=e[26]<<25|e[27]>>>7,F=e[27]<<25|e[26]>>>7,_=e[36]<<21|e[37]>>>11,A=e[37]<<21|e[36]>>>11,Q=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,V=e[8]<<27|e[9]>>>5,G=e[9]<<27|e[8]>>>5,M=e[18]<<20|e[19]>>>12,I=e[19]<<20|e[18]>>>12,oe=e[29]<<7|e[28]>>>25,ae=e[28]<<7|e[29]>>>25,q=e[38]<<8|e[39]>>>24,H=e[39]<<8|e[38]>>>24,E=e[48]<<14|e[49]>>>18,x=e[49]<<14|e[48]>>>18,e[0]=b^~m&g,e[1]=y^~v&w,e[10]=k^~M&T,e[11]=S^~I&U,e[20]=N^~L&D,e[21]=R^~O&F,e[30]=V^~W&X,e[31]=G^~Y&Z,e[40]=te^~ne&oe,e[41]=re^~ie&ae,e[2]=m^~g&_,e[3]=v^~w&A,e[12]=M^~T&j,e[13]=I^~U&B,e[22]=L^~D&q,e[23]=O^~F&H,e[32]=W^~X&J,e[33]=Y^~Z&$,e[42]=ne^~oe&se,e[43]=ie^~ae&ue,e[4]=g^~_&E,e[5]=w^~A&x,e[14]=T^~j&P,e[15]=U^~B&C,e[24]=D^~q&z,e[25]=F^~H&K,e[34]=X^~J&Q,e[35]=Z^~$&ee,e[44]=oe^~se&ce,e[45]=ae^~ue&fe,e[6]=_^~E&b,e[7]=A^~x&y,e[16]=j^~P&k,e[17]=B^~C&S,e[26]=q^~z&N,e[27]=H^~K&R,e[36]=J^~Q&V,e[37]=$^~ee&G,e[46]=se^~ce&te,e[47]=ue^~fe&re,e[8]=E^~b&m,e[9]=x^~y&v,e[18]=P^~k&M,e[19]=C^~S&I,e[28]=z^~N&L,e[29]=K^~R&O,e[38]=Q^~V&W,e[39]=ee^~G&Y,e[48]=ce^~te&ne,e[49]=fe^~re&ie,e[0]^=a[n],e[1]^=a[n+1]},u=function(e){return function(t){var r;if("0x"===t.slice(0,2)){r=[];for(var a=2,u=t.length;a>2]|=t[d]<>2]|=r<>2]|=(192|r>>6)<>2]|=(128|63&r)<=57344?(u[y>>2]|=(224|r>>12)<>2]|=(128|r>>6&63)<>2]|=(128|63&r)<>2]|=(240|r>>18)<>2]|=(128|r>>12&63)<>2]|=(128|r>>6&63)<>2]|=(128|63&r)<=c){for(e.start=y-c,e.block=u[f],y=0;y>2]|=i[3&y],e.lastByteIndex===c)for(u[0]=u[f],y=1;y>4&15]+n[15&p]+n[p>>12&15]+n[p>>8&15]+n[p>>20&15]+n[p>>16&15]+n[p>>28&15]+n[p>>24&15];m%f==0&&(s(l),y=0)}return"0x"+b}(function(e){return{blocks:[],reset:!0,block:0,start:0,blockCount:1600-(e<<1)>>5,outputBlocks:e>>5,s:(t=[0,0,0,0,0,0,0,0,0,0],[].concat(t,t,t,t,t))};var t}(e),r)}};t.exports={keccak256:u(256),keccak512:u(512),keccak256s:u(256),keccak512s:u(512)}},{}],135:[function(e,t,r){const n=e("xtend"),i=e("json-rpc-random-id")();function o(e){this.currentProvider=e}function a(e){return function(){var t=[].slice.call(arguments),r=t.pop();this.sendAsync({method:e,params:t},r)}}function s(e,t){return function(){var r=[].slice.call(arguments),n=r.pop();r.lengtho)throw new Error("Elements exceed array size: "+o);for(d in h=[],e=e.slice(0,e.lastIndexOf("[")),"string"==typeof t&&(t=JSON.parse(t)),t)h.push(l(e,t[d]));if("dynamic"===o){var p=l("uint256",t.length);h.unshift(p)}return r.concat(h)}if("bytes"===e)return t=new r(t),h=r.concat([l("uint256",t.length),t]),t.length%32!=0&&(h=r.concat([h,n.zeros(32-t.length%32)])),h;if(e.startsWith("bytes")){if((o=s(e))<1||o>32)throw new Error("Invalid bytes width: "+o);return n.setLengthRight(t,32)}if(e.startsWith("uint")){if((o=s(e))%8||o<8||o>256)throw new Error("Invalid uint width: "+o);if((a=f(t)).bitLength()>o)throw new Error("Supplied uint exceeds width: "+o+" vs "+a.bitLength());if(a<0)throw new Error("Supplied uint is negative");return a.toArrayLike(r,"be",32)}if(e.startsWith("int")){if((o=s(e))%8||o<8||o>256)throw new Error("Invalid int width: "+o);if((a=f(t)).bitLength()>o)throw new Error("Supplied int exceeds width: "+o+" vs "+a.bitLength());return a.toTwos(256).toArrayLike(r,"be",32)}if(e.startsWith("ufixed")){if(o=u(e),(a=f(t))<0)throw new Error("Supplied ufixed is negative");return l("uint256",a.mul(new i(2).pow(new i(o[1]))))}if(e.startsWith("fixed"))return o=u(e),l("int256",f(t).mul(new i(2).pow(new i(o[1]))));throw new Error("Unsupported or invalid type: "+e)}function d(e,t,n){var o,a,s,u;if("string"==typeof e&&(e=p(e)),"address"===e.name)return d(e.rawType,t,n).toArrayLike(r,"be",20).toString("hex");if("bool"===e.name)return d(e.rawType,t,n).toString()===new i(1).toString();if("string"===e.name){var c=d(e.rawType,t,n);return new r(c,"utf8").toString()}if(e.isArray){for(s=[],o=e.size,"dynamic"===e.size&&(o=d("uint256",t,n=d("uint256",t,n).toNumber()).toNumber(),n+=32),u=0;ue.size)throw new Error("Decoded int exceeds width: "+e.size+" vs "+a.bitLength());return a}if(e.name.startsWith("int")){if((a=new i(t.slice(n,n+32),16,"be").fromTwos(256)).bitLength()>e.size)throw new Error("Decoded uint exceeds width: "+e.size+" vs "+a.bitLength());return a}if(e.name.startsWith("ufixed")){if(o=new i(2).pow(new i(e.size[1])),!(a=d("uint256",t,n)).mod(o).isZero())throw new Error("Decimals not supported yet");return a.div(o)}if(e.name.startsWith("fixed")){if(o=new i(2).pow(new i(e.size[1])),!(a=d("int256",t,n)).mod(o).isZero())throw new Error("Decimals not supported yet");return a.div(o)}throw new Error("Unsupported or invalid type: "+e.name)}function p(e){var t,r,n;if(y(e)){t=c(e);var i=e.slice(0,e.lastIndexOf("["));return i=p(i),r={isArray:!0,name:e,size:t,memoryUsage:"dynamic"===t?32:i.memoryUsage*t,subArray:i}}switch(e){case"address":n="uint160";break;case"bool":n="uint8";break;case"string":n="bytes"}if(r={rawType:n,name:e,memoryUsage:32},e.startsWith("bytes")&&"bytes"!==e||e.startsWith("uint")||e.startsWith("int")?r.size=s(e):(e.startsWith("ufixed")||e.startsWith("fixed"))&&(r.size=u(e)),e.startsWith("bytes")&&"bytes"!==e&&(r.size<1||r.size>32))throw new Error("Invalid bytes width: "+r.size);if((e.startsWith("uint")||e.startsWith("int"))&&(r.size%8||r.size<8||r.size>256))throw new Error("Invalid int/uint width: "+r.size);return r}function b(e){return"string"===e||"bytes"===e||"dynamic"===c(e)}function y(e){return e.lastIndexOf("]")===e.length-1}function m(e,t){return e.startsWith("address")||e.startsWith("bytes")?"0x"+t.toString("hex"):t.toString()}o.eventID=function(e,t){var i=e+"("+t.map(a).join(",")+")";return n.sha3(new r(i))},o.methodID=function(e,t){return o.eventID(e,t).slice(0,4)},o.rawEncode=function(e,t){var n=[],i=[],o=0;e.forEach(function(e){if(y(e)){var t=c(e);o+="dynamic"!==t?32*t:32}else o+=32});for(var s=0;s32)throw new Error("Invalid bytes width: "+i);u.push(n.setLengthRight(l,i))}else if(h.startsWith("uint")){if((i=s(h))%8||i<8||i>256)throw new Error("Invalid uint width: "+i);if((o=f(l)).bitLength()>i)throw new Error("Supplied uint exceeds width: "+i+" vs "+o.bitLength());u.push(o.toArrayLike(r,"be",i/8))}else{if(!h.startsWith("int"))throw new Error("Unsupported or invalid type: "+h);if((i=s(h))%8||i<8||i>256)throw new Error("Invalid int width: "+i);if((o=f(l)).bitLength()>i)throw new Error("Supplied int exceeds width: "+i+" vs "+o.bitLength());u.push(o.toTwos(i).toArrayLike(r,"be",i/8))}}return r.concat(u)},o.soliditySHA3=function(e,t){return n.sha3(o.solidityPack(e,t))},o.soliditySHA256=function(e,t){return n.sha256(o.solidityPack(e,t))},o.solidityRIPEMD160=function(e,t){return n.ripemd160(o.solidityPack(e,t),!0)},o.fromSerpent=function(e){for(var t,r=[],n=0;n="0"&&t<="9");)o+=e[a]-"0",a++;n=a-1,r.push(o)}else if("i"===i)r.push("int256");else{if("a"!==i)throw new Error("Unsupported or invalid type: "+i);r.push("int256[]")}}return r},o.toSerpent=function(e){for(var t=[],r=0;r0){var r=this.raw.slice();this.v=this._chainId,this.r=0,this.s=0,t=this.raw,this.raw=r}else t=this.raw.slice(0,6);return n.rlphash(t)},e.prototype.getChainId=function(){return this._chainId},e.prototype.getSenderAddress=function(){if(this._from)return this._from;var e=this.getSenderPublicKey();return this._from=n.publicToAddress(e),this._from},e.prototype.getSenderPublicKey=function(){if(!(this._senderPubKey&&this._senderPubKey.length||this.verifySignature()))throw new Error("Invalid Signature");return this._senderPubKey},e.prototype.verifySignature=function(){var e=this.hash(!1);if(this._homestead&&1===new o(this.s).cmp(a))return!1;try{var t=n.bufferToInt(this.v);this._chainId>0&&(t-=2*this._chainId+8),this._senderPubKey=n.ecrecover(e,t,this.r,this.s)}catch(e){return!1}return!!this._senderPubKey},e.prototype.sign=function(e){var t=this.hash(!1),r=n.ecsign(t,e);this._chainId>0&&(r.v+=2*this._chainId+8),Object.assign(this,r)},e.prototype.getDataFee=function(){for(var e=this.raw[5],t=new o(0),r=0;r0&&t.push(["gas limit is too low. Need at least "+this.getBaseFee()]),void 0===e||!1===e?0===t.length:t.join(" ")},e}();t.exports=s}).call(this,e("buffer").Buffer)},{buffer:84,"ethereum-common/params.json":137,"ethereumjs-util":141}],141:[function(e,t,r){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=e("keccak"),o=e("secp256k1"),a=e("assert"),s=e("rlp"),u=e("bn.js"),c=e("create-hash"),f=e("safe-buffer").Buffer;Object.assign(r,e("ethjs-util")),r.MAX_INTEGER=new u("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",16),r.TWO_POW256=new u("10000000000000000000000000000000000000000000000000000000000000000",16),r.KECCAK256_NULL_S="c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470",r.SHA3_NULL_S=r.KECCAK256_NULL_S,r.KECCAK256_NULL=f.from(r.KECCAK256_NULL_S,"hex"),r.SHA3_NULL=r.KECCAK256_NULL,r.KECCAK256_RLP_ARRAY_S="1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",r.SHA3_RLP_ARRAY_S=r.KECCAK256_RLP_ARRAY_S,r.KECCAK256_RLP_ARRAY=f.from(r.KECCAK256_RLP_ARRAY_S,"hex"),r.SHA3_RLP_ARRAY=r.KECCAK256_RLP_ARRAY,r.KECCAK256_RLP_S="56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",r.SHA3_RLP_S=r.KECCAK256_RLP_S,r.KECCAK256_RLP=f.from(r.KECCAK256_RLP_S,"hex"),r.SHA3_RLP=r.KECCAK256_RLP,r.BN=u,r.rlp=s,r.secp256k1=o,r.zeros=function(e){return f.allocUnsafe(e).fill(0)},r.zeroAddress=function(){var e=r.zeros(20);return r.bufferToHex(e)},r.setLengthLeft=r.setLength=function(e,t,n){var i=r.zeros(t);return e=r.toBuffer(e),n?e.length0&&"0"===t.toString();)t=(e=e.slice(1))[0];return e},r.toBuffer=function(e){if(!f.isBuffer(e))if(Array.isArray(e))e=f.from(e);else if("string"==typeof e)e=r.isHexString(e)?f.from(r.padToEven(r.stripHexPrefix(e)),"hex"):f.from(e);else if("number"==typeof e)e=r.intToBuffer(e);else if(null==e)e=f.allocUnsafe(0);else if(u.isBN(e))e=e.toArrayLike(f);else{if(!e.toArray)throw new Error("invalid type");e=f.from(e.toArray())}return e},r.bufferToInt=function(e){return new u(r.toBuffer(e)).toNumber()},r.bufferToHex=function(e){return"0x"+(e=r.toBuffer(e)).toString("hex")},r.fromSigned=function(e){return new u(e).fromTwos(256)},r.toUnsigned=function(e){return f.from(e.toTwos(256).toArray())},r.keccak=function(e,t){return e=r.toBuffer(e),t||(t=256),i("keccak"+t).update(e).digest()},r.keccak256=function(e){return r.keccak(e)},r.sha3=r.keccak,r.sha256=function(e){return e=r.toBuffer(e),c("sha256").update(e).digest()},r.ripemd160=function(e,t){e=r.toBuffer(e);var n=c("rmd160").update(e).digest();return!0===t?r.setLength(n,32):n},r.rlphash=function(e){return r.keccak(s.encode(e))},r.isValidPrivate=function(e){return o.privateKeyVerify(e)},r.isValidPublic=function(e,t){return 64===e.length?o.publicKeyVerify(f.concat([f.from([4]),e])):!!t&&o.publicKeyVerify(e)},r.pubToAddress=r.publicToAddress=function(e,t){return e=r.toBuffer(e),t&&64!==e.length&&(e=o.publicKeyConvert(e,!1).slice(1)),a(64===e.length),r.keccak(e).slice(-20)};var h=r.privateToPublic=function(e){return e=r.toBuffer(e),o.publicKeyCreate(e,!1).slice(1)};r.importPublic=function(e){return 64!==(e=r.toBuffer(e)).length&&(e=o.publicKeyConvert(e,!1).slice(1)),e},r.ecsign=function(e,t){var r=o.sign(e,t),n={};return n.r=r.signature.slice(0,32),n.s=r.signature.slice(32,64),n.v=r.recovery+27,n},r.hashPersonalMessage=function(e){var t=r.toBuffer("Ethereum Signed Message:\n"+e.length.toString());return r.keccak(f.concat([t,e]))},r.ecrecover=function(e,t,n,i){var a=f.concat([r.setLength(n,32),r.setLength(i,32)],64),s=t-27;if(0!==s&&1!==s)throw new Error("Invalid signature v value");var u=o.recover(e,a,s);return o.publicKeyConvert(u,!1).slice(1)},r.toRpcSig=function(e,t,n){if(27!==e&&28!==e)throw new Error("Invalid recovery id");return r.bufferToHex(f.concat([r.setLengthLeft(t,32),r.setLengthLeft(n,32),r.toBuffer(e-27)]))},r.fromRpcSig=function(e){if(65!==(e=r.toBuffer(e)).length)throw new Error("Invalid signature length");var t=e[64];return t<27&&(t+=27),{v:t,r:e.slice(0,32),s:e.slice(32,64)}},r.privateToAddress=function(e){return r.publicToAddress(h(e))},r.isValidAddress=function(e){return/^0x[0-9a-fA-F]{40}$/.test(e)},r.isZeroAddress=function(e){return r.zeroAddress()===r.addHexPrefix(e)},r.toChecksumAddress=function(e){e=r.stripHexPrefix(e).toLowerCase();for(var t=r.keccak(e).toString("hex"),n="0x",i=0;i=8?n+=e[i].toUpperCase():n+=e[i];return n},r.isValidChecksumAddress=function(e){return r.isValidAddress(e)&&r.toChecksumAddress(e)===e},r.generateAddress=function(e,t){return e=r.toBuffer(e),t=(t=new u(t)).isZero()?null:f.from(t.toArray()),r.rlphash([e,t]).slice(-20)},r.isPrecompiled=function(e){var t=r.unpad(e);return 1===t.length&&t[0]>=1&&t[0]<=8},r.addHexPrefix=function(e){return"string"!=typeof e?e:r.isHexPrefixed(e)?e:"0x"+e},r.isValidSignature=function(e,t,r,n){var i=new u("7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0",16),o=new u("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",16);return 32===t.length&&32===r.length&&((27===e||28===e)&&(t=new u(t),r=new u(r),!(t.isZero()||t.gt(o)||r.isZero()||r.gt(o))&&(!1!==n||1!==new u(r).cmp(i))))},r.baToJSON=function(e){if(f.isBuffer(e))return"0x"+e.toString("hex");if(e instanceof Array){for(var t=[],n=0;n=i.length,"The field "+t.name+" must not have more "+t.length+" bytes")):t.allowZero&&0===i.length||!t.length||a(t.length===i.length,"The field "+t.name+" must have byte length of "+t.length),e.raw[n]=i}e._fields.push(t.name),Object.defineProperty(e,t.name,{enumerable:!0,configurable:!0,get:i,set:o}),t.default&&(e[t.name]=t.default),t.alias&&Object.defineProperty(e,t.alias,{enumerable:!1,configurable:!0,set:o,get:i})}),i)if("string"==typeof i&&(i=f.from(r.stripHexPrefix(i),"hex")),f.isBuffer(i)&&(i=s.decode(i)),Array.isArray(i)){if(i.length>e._fields.length)throw new Error("wrong number of fields in data");i.forEach(function(t,n){e[e._fields[n]]=r.toBuffer(t)})}else{if("object"!==(void 0===i?"undefined":n(i)))throw new Error("invalid data");var o=Object.keys(i);t.forEach(function(t){-1!==o.indexOf(t.name)&&(e[t.name]=i[t.name]),-1!==o.indexOf(t.alias)&&(e[t.alias]=i[t.alias])})}}},{assert:19,"bn.js":53,"create-hash":91,"ethjs-util":155,keccak:195,rlp:289,"safe-buffer":290,secp256k1:295}],142:[function(e,t,r){arguments[4][128][0].apply(r,arguments)},{_process:257,dup:128}],143:[function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t};Object.defineProperty(r,"__esModule",{value:!0});var a=e("./address"),s=e("./bignumber"),u=e("./bytes"),c=e("./utf8"),f=e("./properties"),h=o(e("./errors")),l=new RegExp(/^bytes([0-9]*)$/),d=new RegExp(/^(u?int)([0-9]*)$/),p=new RegExp(/^(.*)\[([0-9]*)\]$/);r.defaultCoerceFunc=function(e,t){var r=e.match(d);return r&&parseInt(r[2])<=48?t.toNumber():t};var b=new RegExp("^([^)(]*)\\((.*)\\)([^)(]*)$"),y=new RegExp("^[A-Za-z_][A-Za-z0-9_]*$");function m(e){return e.match(/^uint($|[^1-9])/)?e="uint256"+e.substring(4):e.match(/^int($|[^1-9])/)&&(e="int256"+e.substring(3)),e}function v(e,t){function r(t){throw new Error('unexpected character "'+e[t]+'" at position '+t+' in "'+e+'"')}for(var n={type:"",name:"",state:{allowType:!0}},i=n,o=0;o1){var i=r[1].match(b);if(""!=i[1].trim()||""!=i[3].trim())throw new Error("unexpected tokens");L(i[2]).forEach(function(e){t.outputs.push(v(e))})}return t}(e.trim()));throw new Error("unknown signature")};var w=function(){return function(e,t,r,n,i){this.coerceFunc=e,this.name=t,this.type=r,this.localName=n,this.dynamic=i}}(),_=function(e){function t(t){var r=e.call(this,t.coerceFunc,t.name,t.type,void 0,t.dynamic)||this;return f.defineReadOnly(r,"coder",t),r}return i(t,e),t.prototype.encode=function(e){return this.coder.encode(e)},t.prototype.decode=function(e,t){return this.coder.decode(e,t)},t}(w),A=function(e){function t(t,r){return e.call(this,t,"null","",r,!1)||this}return i(t,e),t.prototype.encode=function(e){return u.arrayify([])},t.prototype.decode=function(e,t){if(t>e.length)throw new Error("invalid null");return{consumed:0,value:this.coerceFunc("null",void 0)}},t}(w),E=function(e){function t(t,r,n,i){var o=this,a=(n?"int":"uint")+8*r;return(o=e.call(this,t,a,a,i,!1)||this).size=r,o.signed=n,o}return i(t,e),t.prototype.encode=function(e){try{var t=s.bigNumberify(e);return t=t.toTwos(8*this.size).maskn(8*this.size),this.signed&&(t=t.fromTwos(8*this.size).toTwos(256)),u.padZeros(u.arrayify(t),32)}catch(t){h.throwError("invalid number value",h.INVALID_ARGUMENT,{arg:this.localName,coderType:this.name,value:e})}return null},t.prototype.decode=function(e,t){e.length32)throw new Error;t.set(r)}catch(t){h.throwError("invalid "+this.name+" value",h.INVALID_ARGUMENT,{arg:this.localName,coderType:this.name,value:t.value||e})}return t},t.prototype.decode=function(e,t){return e.length=0?n:"")+"]",s=-1===n||r.dynamic;return(o=e.call(this,t,"array",a,i,s)||this).coder=r,o.length=n,o}return i(t,e),t.prototype.encode=function(e){Array.isArray(e)||h.throwError("expected array value",h.INVALID_ARGUMENT,{arg:this.localName,coderType:"array",value:e});var t=this.length,r=new Uint8Array(0);-1===t&&(t=e.length,r=x.encode(t)),h.checkArgumentCount(t,e.length,"in coder array"+(this.localName?" "+this.localName:""));for(var n=[],i=0;i256||i%8!=0)&&h.throwError("invalid "+r[1]+" bit length",h.INVALID_ARGUMENT,{arg:"param",value:t}),new E(e,i/8,"int"===r[1],t.name);if(r=t.type.match(l))return(0===(i=parseInt(r[1]))||i>32)&&h.throwError("invalid bytes length",h.INVALID_ARGUMENT,{arg:"param",value:t}),new S(e,i,t.name);if(r=t.type.match(p)){var i=parseInt(r[2]||"-1");return(t=f.jsonCopy(t)).type=r[1],new N(e,D(e,t),i,t.name)}return"tuple"===t.type.substring(0,5)?function(e,t,r){t||(t=[]);var n=[];return t.forEach(function(t){n.push(D(e,t))}),new R(e,n,r)}(e,t.components,t.name):""===t.type?new A(e,t.name):(h.throwError("invalid type",h.INVALID_ARGUMENT,{arg:"type",value:t.type}),null)}var F=function(){function e(t){h.checkNew(this,e),t||(t=r.defaultCoerceFunc),f.defineReadOnly(this,"coerceFunc",t)}return e.prototype.encode=function(e,t){e.length!==t.length&&h.throwError("types/values length mismatch",h.INVALID_ARGUMENT,{count:{types:e.length,values:t.length},value:{types:e,values:t}});var r=[];return e.forEach(function(e){var t=null;t="string"==typeof e?v(e):e,r.push(D(this.coerceFunc,t))},this),u.hexlify(new R(this.coerceFunc,r,"_").encode(t))},e.prototype.decode=function(e,t){var r=[];return e.forEach(function(e){var t=null;t="string"==typeof e?v(e):f.jsonCopy(e),r.push(D(this.coerceFunc,t))},this),new R(this.coerceFunc,r,"_").decode(u.arrayify(t),0).value},e}();r.AbiCoder=F,r.defaultAbiCoder=new F},{"./address":144,"./bignumber":145,"./bytes":146,"./errors":147,"./properties":149,"./utf8":152}],144:[function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0});var i=n(e("bn.js")),o=e("./bytes"),a=e("./keccak256"),s=e("./rlp"),u=e("./errors");function c(e){"string"==typeof e&&e.match(/^0x[0-9A-Fa-f]{40}$/)||u.throwError("invalid address",u.INVALID_ARGUMENT,{arg:"address",value:e});for(var t=(e=e.toLowerCase()).substring(2).split(""),r=new Uint8Array(40),n=0;n<40;n++)r[n]=t[n].charCodeAt(0);r=o.arrayify(a.keccak256(r));for(var i=0;i<40;i+=2)r[i>>1]>>4>=8&&(t[i]=t[i].toUpperCase()),(15&r[i>>1])>=8&&(t[i+1]=t[i+1].toUpperCase());return"0x"+t.join("")}for(var f={},h=0;h<10;h++)f[String(h)]=String(h);for(h=0;h<26;h++)f[String.fromCharCode(65+h)]=String(10+h);var l,d=Math.floor((l=9007199254740991,Math.log10?Math.log10(l):Math.log(l)/Math.LN10));function p(e){e=(e=e.toUpperCase()).substring(4)+e.substring(0,2)+"00";var t="";for(e.split("").forEach(function(e){t+=f[e]});t.length>=d;){var r=t.substring(0,d);t=parseInt(r,10)%97+t.substring(r.length)}for(var n=String(98-parseInt(t,10)%97);n.length<2;)n="0"+n;return n}function b(e){var t=null;if("string"!=typeof e&&u.throwError("invalid address",u.INVALID_ARGUMENT,{arg:"address",value:e}),e.match(/^(0x)?[0-9a-fA-F]{40}$/))"0x"!==e.substring(0,2)&&(e="0x"+e),t=c(e),e.match(/([A-F].*[a-f])|([a-f].*[A-F])/)&&t!==e&&u.throwError("bad address checksum",u.INVALID_ARGUMENT,{arg:"address",value:e});else if(e.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){for(e.substring(2,4)!==p(e)&&u.throwError("bad icap checksum",u.INVALID_ARGUMENT,{arg:"address",value:e}),t=new i.default.BN(e.substring(4),36).toString(16);t.length<40;)t="0"+t;t=c("0x"+t)}else u.throwError("invalid address",u.INVALID_ARGUMENT,{arg:"address",value:e});return t}r.getAddress=b,r.getIcapAddress=function(e){for(var t=new i.default.BN(b(e).substring(2),16).toString(36).toUpperCase();t.length<30;)t="0"+t;return"XE"+p("XE00"+t)+t},r.getContractAddress=function(e){if(!e.from)throw new Error("missing from address");var t=e.nonce;return b("0x"+a.keccak256(s.encode([b(e.from),o.stripZeros(o.hexlify(t))])).substring(26))}},{"./bytes":146,"./errors":147,"./keccak256":148,"./rlp":150,"bn.js":53}],145:[function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t};Object.defineProperty(r,"__esModule",{value:!0});var s=o(e("bn.js")),u=e("./bytes"),c=e("./properties"),f=e("./types"),h=a(e("./errors")),l=new s.default.BN(-1);function d(e){var t=e.toString(16);return"-"===t[0]?t.length%2==0?"-0x0"+t.substring(1):"-0x"+t.substring(1):t.length%2==1?"0x0"+t:"0x"+t}function p(e){return m(e)._bn}function b(e){return new y(d(e))}var y=function(e){function t(r){var n=e.call(this)||this;if(h.checkNew(n,t),"string"==typeof r)u.isHexString(r)?("0x"==r&&(r="0x0"),c.defineReadOnly(n,"_hex",r)):"-"===r[0]&&u.isHexString(r.substring(1))?c.defineReadOnly(n,"_hex",r):r.match(/^-?[0-9]*$/)?(""==r&&(r="0"),c.defineReadOnly(n,"_hex",d(new s.default.BN(r)))):h.throwError("invalid BigNumber string value",h.INVALID_ARGUMENT,{arg:"value",value:r});else if("number"==typeof r){parseInt(String(r))!==r&&h.throwError("underflow",h.NUMERIC_FAULT,{operation:"setValue",fault:"underflow",value:r,outputValue:parseInt(String(r))});try{c.defineReadOnly(n,"_hex",d(new s.default.BN(r)))}catch(e){h.throwError("overflow",h.NUMERIC_FAULT,{operation:"setValue",fault:"overflow",details:e.message})}}else r instanceof t?c.defineReadOnly(n,"_hex",r._hex):r.toHexString?c.defineReadOnly(n,"_hex",d(p(r.toHexString()))):u.isArrayish(r)?c.defineReadOnly(n,"_hex",d(new s.default.BN(u.hexlify(r).substring(2),16))):h.throwError("invalid BigNumber value",h.INVALID_ARGUMENT,{arg:"value",value:r});return n}return i(t,e),Object.defineProperty(t.prototype,"_bn",{get:function(){return"-"===this._hex[0]?new s.default.BN(this._hex.substring(3),16).mul(l):new s.default.BN(this._hex.substring(2),16)},enumerable:!0,configurable:!0}),t.prototype.fromTwos=function(e){return b(this._bn.fromTwos(e))},t.prototype.toTwos=function(e){return b(this._bn.toTwos(e))},t.prototype.add=function(e){return b(this._bn.add(p(e)))},t.prototype.sub=function(e){return b(this._bn.sub(p(e)))},t.prototype.div=function(e){return m(e).isZero()&&h.throwError("division by zero",h.NUMERIC_FAULT,{operation:"divide",fault:"division by zero"}),b(this._bn.div(p(e)))},t.prototype.mul=function(e){return b(this._bn.mul(p(e)))},t.prototype.mod=function(e){return b(this._bn.mod(p(e)))},t.prototype.pow=function(e){return b(this._bn.pow(p(e)))},t.prototype.maskn=function(e){return b(this._bn.maskn(e))},t.prototype.eq=function(e){return this._bn.eq(p(e))},t.prototype.lt=function(e){return this._bn.lt(p(e))},t.prototype.lte=function(e){return this._bn.lte(p(e))},t.prototype.gt=function(e){return this._bn.gt(p(e))},t.prototype.gte=function(e){return this._bn.gte(p(e))},t.prototype.isZero=function(){return this._bn.isZero()},t.prototype.toNumber=function(){try{return this._bn.toNumber()}catch(e){h.throwError("overflow",h.NUMERIC_FAULT,{operation:"setValue",fault:"overflow",details:e.message})}return null},t.prototype.toString=function(){return this._bn.toString(10)},t.prototype.toHexString=function(){return this._hex},t}(f.BigNumber);function m(e){return e instanceof y?e:new y(e)}r.bigNumberify=m,r.ConstantNegativeOne=m(-1),r.ConstantZero=m(0),r.ConstantOne=m(1),r.ConstantTwo=m(2),r.ConstantWeiPerEther=m("1000000000000000000")},{"./bytes":146,"./errors":147,"./properties":149,"./types":151,"bn.js":53}],146:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("./errors");function i(e){return!!e._bn}function o(e){return e.slice?e:(e.slice=function(){var t=Array.prototype.slice.call(arguments);return new Uint8Array(Array.prototype.slice.apply(e,t))},e)}function a(e){if(!e||parseInt(String(e.length))!=e.length||"string"==typeof e)return!1;for(var t=0;t=256||parseInt(String(r))!=r)return!1}return!0}function s(e){if(null==e&&n.throwError("cannot convert null value to array",n.INVALID_ARGUMENT,{arg:"value",value:e}),i(e)&&(e=e.toHexString()),"string"==typeof e){var t=e.match(/^(0x)?[0-9a-fA-F]*$/);t||n.throwError("invalid hexidecimal string",n.INVALID_ARGUMENT,{arg:"value",value:e}),"0x"!==t[1]&&n.throwError("hex string must have 0x prefix",n.INVALID_ARGUMENT,{arg:"value",value:e}),(e=e.substring(2)).length%2&&(e="0"+e);for(var r=[],s=0;s>4]+f[15&u])}return"0x"+o.join("")}return n.throwError("invalid hexlify value",null,{arg:"value",value:e}),"never"}function l(e,t){for(c(e)||n.throwError("invalid hex string",n.INVALID_ARGUMENT,{arg:"value",value:e});e.length<2*t+2;)e="0x0"+e.substring(2);return e}function d(e){var t,r=0,i="0x",o="0x";if((t=e)&&null!=t.r&&null!=t.s){null==e.v&&null==e.recoveryParam&&n.throwError("at least on of recoveryParam or v must be specified",n.INVALID_ARGUMENT,{argument:"signature",value:e}),i=l(e.r,32),o=l(e.s,32),"string"==typeof(r=e.v)&&(r=parseInt(r,16));var a=e.recoveryParam;null==a&&null!=e.v&&(a=1-r%2),r=27+a}else{var u=s(e);if(65!==u.length)throw new Error("invalid signature");i=h(u.slice(0,32)),o=h(u.slice(32,64)),27!==(r=u[64])&&28!==r&&(r=27+r%2)}return{r:i,s:o,recoveryParam:r-27,v:r}}r.hexlify=h,r.hexDataLength=function(e){return c(e)&&e.length%2==0?(e.length-2)/2:null},r.hexDataSlice=function(e,t,r){return c(e)||n.throwError("invalid hex data",n.INVALID_ARGUMENT,{arg:"value",value:e}),e.length%2!=0&&n.throwError("hex data length must be even",n.INVALID_ARGUMENT,{arg:"value",value:e}),t=2+2*t,null!=r?"0x"+e.substring(t,t+2*r):"0x"+e.substring(t)},r.hexStripZeros=function(e){for(c(e)||n.throwError("invalid hex string",n.INVALID_ARGUMENT,{arg:"value",value:e});e.length>3&&"0x0"===e.substring(0,3);)e="0x"+e.substring(3);return e},r.hexZeroPad=l,r.splitSignature=d,r.joinSignature=function(e){return h(u([(e=d(e)).r,e.s,e.recoveryParam?"0x1c":"0x1b"]))}},{"./errors":147}],147:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.UNKNOWN_ERROR="UNKNOWN_ERROR",r.NOT_IMPLEMENTED="NOT_IMPLEMENTED",r.MISSING_NEW="MISSING_NEW",r.CALL_EXCEPTION="CALL_EXCEPTION",r.INVALID_ARGUMENT="INVALID_ARGUMENT",r.MISSING_ARGUMENT="MISSING_ARGUMENT",r.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",r.NUMERIC_FAULT="NUMERIC_FAULT",r.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION";var n=!1,i=!1;function o(e,t,n){if(i)throw new Error("unknown error");t||(t=r.UNKNOWN_ERROR),n||(n={});var o=[];Object.keys(n).forEach(function(e){try{o.push(e+"="+JSON.stringify(n[e]))}catch(t){o.push(e+"="+JSON.stringify(n[e].toString()))}});var a=e;o.length&&(e+=" ("+o.join(", ")+")");var s=new Error(e);throw s.reason=a,s.code=t,Object.keys(n).forEach(function(e){s[e]=n[e]}),s}r.throwError=o,r.checkNew=function(e,t){e instanceof t||o("missing new",r.MISSING_NEW,{name:t.name})},r.checkArgumentCount=function(e,t,n){n||(n=""),et&&o("too many arguments"+n,r.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})},r.setCensorship=function(e,t){n&&o("error censorship permanent",r.UNSUPPORTED_OPERATION,{operation:"setCersorship"}),i=!!e,n=!!t}},{}],148:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("js-sha3"),i=e("./bytes");r.keccak256=function(e){return"0x"+n.keccak_256(i.arrayify(e))}},{"./bytes":146,"js-sha3":142}],149:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.defineReadOnly=function(e,t,r){Object.defineProperty(e,t,{enumerable:!0,value:r,writable:!1})},r.defineFrozen=function(e,t,r){var n=JSON.stringify(r);Object.defineProperty(e,t,{enumerable:!0,get:function(){return JSON.parse(n)}})},r.resolveProperties=function(e){var t={},r=[];return Object.keys(e).forEach(function(n){var i=e[n];i instanceof Promise?r.push(i.then(function(e){return t[n]=e,null})):t[n]=i}),Promise.all(r).then(function(){return t})},r.shallowCopy=function(e){var t={};for(var r in e)t[r]=e[r];return t},r.jsonCopy=function(e){return JSON.parse(JSON.stringify(e))}},{}],150:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("./bytes");function i(e){for(var t=[];e;)t.unshift(255&e),e>>=8;return t}function o(e,t,r){for(var n=0,i=0;it+1+n)throw new Error("invalid rlp")}return{consumed:1+n,result:i}}function s(e,t){if(0===e.length)throw new Error("invalid rlp data");if(e[t]>=248){if(t+1+(r=e[t]-247)>e.length)throw new Error("too short");if(t+1+r+(i=o(e,t+1,r))>e.length)throw new Error("to short");return a(e,t,t+1+r,r+i)}if(e[t]>=192){if(t+1+(i=e[t]-192)>e.length)throw new Error("invalid rlp data");return a(e,t,t+1,i)}if(e[t]>=184){var r;if(t+1+(r=e[t]-183)>e.length)throw new Error("invalid rlp data");if(t+1+r+(i=o(e,t+1,r))>e.length)throw new Error("invalid rlp data");return{consumed:1+r+i,result:n.hexlify(e.slice(t+1+r,t+1+r+i))}}if(e[t]>=128){var i;if(t+1+(i=e[t]-128)>e.length)throw new Error("invlaid rlp data");return{consumed:1+i,result:n.hexlify(e.slice(t+1,t+1+i))}}return{consumed:1,result:n.hexlify(e[t])}}r.encode=function(e){return n.hexlify(function e(t){if(Array.isArray(t)){var r=[];return t.forEach(function(t){r=r.concat(e(t))}),r.length<=55?(r.unshift(192+r.length),r):((o=i(r.length)).unshift(247+o.length),o.concat(r))}var o,a=Array.prototype.slice.call(n.arrayify(t));return 1===a.length&&a[0]<=127?a:a.length<=55?(a.unshift(128+a.length),a):((o=i(a.length)).unshift(183+o.length),o.concat(a))}(e))},r.decode=function(e){var t=n.arrayify(e),r=s(t,0);if(r.consumed!==t.length)throw new Error("invalid rlp data");return r.result}},{"./bytes":146}],151:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=function(){return function(){}}();r.BigNumber=n;var i=function(){return function(){}}();r.Indexed=i;var o=function(){return function(){}}();r.MinimalProvider=o;var a=function(){return function(){}}();r.Signer=a;var s=function(){return function(){}}();r.HDNode=s},{}],152:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n,i=e("./bytes");!function(e){e.current="",e.NFC="NFC",e.NFD="NFD",e.NFKC="NFKC",e.NFKD="NFKD"}(n=r.UnicodeNormalizationForm||(r.UnicodeNormalizationForm={})),r.toUtf8Bytes=function(e,t){void 0===t&&(t=n.current),t!=n.current&&(e=e.normalize(t));for(var r=[],o=0,a=0;a>6|192,r[o++]=63&s|128):55296==(64512&s)&&a+1>18|240,r[o++]=s>>12&63|128,r[o++]=s>>6&63|128,r[o++]=63&s|128):(r[o++]=s>>12|224,r[o++]=s>>6&63|128,r[o++]=63&s|128)}return i.arrayify(r)},r.toUtf8String=function(e){e=i.arrayify(e);for(var t="",r=0;r>7!=0){if(n>>6!=2){var o=null;if(n>>5==6)o=1;else if(n>>4==14)o=2;else if(n>>3==30)o=3;else if(n>>2==62)o=4;else{if(n>>1!=126)continue;o=5}if(r+o>e.length){for(;r>6==2;r++);if(r!=e.length)continue;return t}var a,s=n&(1<<8-o-1)-1;for(a=0;a>6!=2)break;s=s<<6|63&u}a==o?s<=65535?t+=String.fromCharCode(s):(s-=65536,t+=String.fromCharCode(55296+(s>>10&1023),56320+(1023&s))):r--}}else t+=String.fromCharCode(n)}return t}},{"./bytes":146}],153:[function(e,t,r){"use strict";var n=e("bn.js"),i=e("number-to-bn"),o=new n(0),a=new n(-1),s={noether:"0",wei:"1",kwei:"1000",Kwei:"1000",babbage:"1000",femtoether:"1000",mwei:"1000000",Mwei:"1000000",lovelace:"1000000",picoether:"1000000",gwei:"1000000000",Gwei:"1000000000",shannon:"1000000000",nanoether:"1000000000",nano:"1000000000",szabo:"1000000000000",microether:"1000000000000",micro:"1000000000000",finney:"1000000000000000",milliether:"1000000000000000",milli:"1000000000000000",ether:"1000000000000000000",kether:"1000000000000000000000",grand:"1000000000000000000000",mether:"1000000000000000000000000",gether:"1000000000000000000000000000",tether:"1000000000000000000000000000000"};function u(e){var t=e?e.toLowerCase():"ether",r=s[t];if("string"!=typeof r)throw new Error("[ethjs-unit] the unit provided "+e+" doesn't exists, please use the one of the following units "+JSON.stringify(s,null,2));return new n(r,10)}function c(e){if("string"==typeof e){if(!e.match(/^-?[0-9.]+$/))throw new Error("while converting number to string, invalid number value '"+e+"', should be a number matching (^-?[0-9.]+).");return e}if("number"==typeof e)return String(e);if("object"==typeof e&&e.toString&&(e.toTwos||e.dividedToIntegerBy))return e.toPrecision?String(e.toPrecision()):e.toString(10);throw new Error("while converting number to string, invalid number value '"+e+"' type "+typeof e+".")}t.exports={unitMap:s,numberToString:c,getValueOfUnit:u,fromWei:function(e,t,r){var n=i(e),c=n.lt(o),f=u(t),h=s[t].length-1||1,l=r||{};c&&(n=n.mul(a));for(var d=n.mod(f).toString(10);d.length2)throw new Error("[ethjs-unit] while converting number "+e+" to wei, too many decimal points");var l=h[0],d=h[1];if(l||(l="0"),d||(d="0"),d.length>o)throw new Error("[ethjs-unit] while converting number "+e+" to wei, too many decimal places");for(;d.length=49&&a<=54?a-49+10:a>=17&&a<=22?a-17+10:15&a}return n}function u(e,t,r,n){for(var i=0,o=Math.min(e.length,r),a=t;a=49?s-49+10:s>=17?s-17+10:s}return i}o.isBN=function(e){return e instanceof o||null!==e&&"object"==typeof e&&e.constructor.wordSize===o.wordSize&&Array.isArray(e.words)},o.max=function(e,t){return e.cmp(t)>0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&i++,16===t?this._parseHex(e,i):this._parseBase(e,t,i),"-"===e[0]&&(this.negative=1),this.strip(),"le"===r&&this._initArray(this.toArray(),t,r)},o.prototype._initNumber=function(e,t,r){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(n(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===r&&this._initArray(this.toArray(),t,r)},o.prototype._initArray=function(e,t,r){if(n("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3)a=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[o]|=a<>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);else if("le"===r)for(i=0,o=0;i>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);return this.strip()},o.prototype._parseHex=function(e,t){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var r=0;r=t;r-=6)i=s(e,r,r+6),this.words[n]|=i<>>26-o&4194303,(o+=24)>=26&&(o-=26,n++);r+6!==t&&(i=s(e,t,r+6),this.words[n]|=i<>>26-o&4194303),this.strip()},o.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=t)n++;n--,i=i/t|0;for(var o=e.length-r,a=o%n,s=Math.min(o,o-a)+r,c=0,f=r;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},o.prototype.inspect=function(){return(this.red?""};var c=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],f=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],h=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(e,t,r){r.negative=t.negative^e.negative;var n=e.length+t.length|0;r.length=n,n=n-1|0;var i=0|e.words[0],o=0|t.words[0],a=i*o,s=67108863&a,u=a/67108864|0;r.words[0]=s;for(var c=1;c>>26,h=67108863&u,l=Math.min(c,t.length-1),d=Math.max(0,c-e.length+1);d<=l;d++){var p=c-d|0;f+=(a=(i=0|e.words[p])*(o=0|t.words[d])+h)/67108864|0,h=67108863&a}r.words[c]=0|h,u=0|f}return 0!==u?r.words[c]=0|u:r.length--,r.strip()}o.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var i=0,o=0,a=0;a>>24-i&16777215)||a!==this.length-1?c[6-u.length]+u+r:u+r,(i+=2)>=26&&(i-=26,a--)}for(0!==o&&(r=o.toString(16)+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var l=f[e],d=h[e];r="";var p=this.clone();for(p.negative=0;!p.isZero();){var b=p.modn(d).toString(e);r=(p=p.idivn(d)).isZero()?b+r:c[l-b.length]+b+r}for(this.isZero()&&(r="0"+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16)},o.prototype.toBuffer=function(e,t){return n(void 0!==a),this.toArrayLike(a,e,t)},o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},o.prototype.toArrayLike=function(e,t,r){var i=this.byteLength(),o=r||Math.max(1,i);n(i<=o,"byte array longer than desired length"),n(o>0,"Requested array length <= 0"),this.strip();var a,s,u="le"===t,c=new e(o),f=this.clone();if(u){for(s=0;!f.isZero();s++)a=f.andln(255),f.iushrn(8),c[s]=a;for(;s=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;re.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,r;this.length>e.length?(t=this,r=e):(t=e,r=this);for(var n=0;ne.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-r),this.strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,i=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<e.length?(r=this,n=e):(r=e,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;oe.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var r,n,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=e):(r=e,n=this);for(var o=0,a=0;a>26,this.words[a]=67108863&t;for(;0!==o&&a>26,this.words[a]=67108863&t;if(0===o&&a>>13,d=0|a[1],p=8191&d,b=d>>>13,y=0|a[2],m=8191&y,v=y>>>13,g=0|a[3],w=8191&g,_=g>>>13,A=0|a[4],E=8191&A,x=A>>>13,k=0|a[5],S=8191&k,M=k>>>13,I=0|a[6],T=8191&I,U=I>>>13,j=0|a[7],B=8191&j,P=j>>>13,C=0|a[8],N=8191&C,R=C>>>13,L=0|a[9],O=8191&L,D=L>>>13,F=0|s[0],q=8191&F,H=F>>>13,z=0|s[1],K=8191&z,V=z>>>13,G=0|s[2],W=8191&G,Y=G>>>13,X=0|s[3],Z=8191&X,J=X>>>13,$=0|s[4],Q=8191&$,ee=$>>>13,te=0|s[5],re=8191&te,ne=te>>>13,ie=0|s[6],oe=8191&ie,ae=ie>>>13,se=0|s[7],ue=8191&se,ce=se>>>13,fe=0|s[8],he=8191&fe,le=fe>>>13,de=0|s[9],pe=8191&de,be=de>>>13;r.negative=e.negative^t.negative,r.length=19;var ye=(c+(n=Math.imul(h,q))|0)+((8191&(i=(i=Math.imul(h,H))+Math.imul(l,q)|0))<<13)|0;c=((o=Math.imul(l,H))+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,n=Math.imul(p,q),i=(i=Math.imul(p,H))+Math.imul(b,q)|0,o=Math.imul(b,H);var me=(c+(n=n+Math.imul(h,K)|0)|0)+((8191&(i=(i=i+Math.imul(h,V)|0)+Math.imul(l,K)|0))<<13)|0;c=((o=o+Math.imul(l,V)|0)+(i>>>13)|0)+(me>>>26)|0,me&=67108863,n=Math.imul(m,q),i=(i=Math.imul(m,H))+Math.imul(v,q)|0,o=Math.imul(v,H),n=n+Math.imul(p,K)|0,i=(i=i+Math.imul(p,V)|0)+Math.imul(b,K)|0,o=o+Math.imul(b,V)|0;var ve=(c+(n=n+Math.imul(h,W)|0)|0)+((8191&(i=(i=i+Math.imul(h,Y)|0)+Math.imul(l,W)|0))<<13)|0;c=((o=o+Math.imul(l,Y)|0)+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,n=Math.imul(w,q),i=(i=Math.imul(w,H))+Math.imul(_,q)|0,o=Math.imul(_,H),n=n+Math.imul(m,K)|0,i=(i=i+Math.imul(m,V)|0)+Math.imul(v,K)|0,o=o+Math.imul(v,V)|0,n=n+Math.imul(p,W)|0,i=(i=i+Math.imul(p,Y)|0)+Math.imul(b,W)|0,o=o+Math.imul(b,Y)|0;var ge=(c+(n=n+Math.imul(h,Z)|0)|0)+((8191&(i=(i=i+Math.imul(h,J)|0)+Math.imul(l,Z)|0))<<13)|0;c=((o=o+Math.imul(l,J)|0)+(i>>>13)|0)+(ge>>>26)|0,ge&=67108863,n=Math.imul(E,q),i=(i=Math.imul(E,H))+Math.imul(x,q)|0,o=Math.imul(x,H),n=n+Math.imul(w,K)|0,i=(i=i+Math.imul(w,V)|0)+Math.imul(_,K)|0,o=o+Math.imul(_,V)|0,n=n+Math.imul(m,W)|0,i=(i=i+Math.imul(m,Y)|0)+Math.imul(v,W)|0,o=o+Math.imul(v,Y)|0,n=n+Math.imul(p,Z)|0,i=(i=i+Math.imul(p,J)|0)+Math.imul(b,Z)|0,o=o+Math.imul(b,J)|0;var we=(c+(n=n+Math.imul(h,Q)|0)|0)+((8191&(i=(i=i+Math.imul(h,ee)|0)+Math.imul(l,Q)|0))<<13)|0;c=((o=o+Math.imul(l,ee)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,n=Math.imul(S,q),i=(i=Math.imul(S,H))+Math.imul(M,q)|0,o=Math.imul(M,H),n=n+Math.imul(E,K)|0,i=(i=i+Math.imul(E,V)|0)+Math.imul(x,K)|0,o=o+Math.imul(x,V)|0,n=n+Math.imul(w,W)|0,i=(i=i+Math.imul(w,Y)|0)+Math.imul(_,W)|0,o=o+Math.imul(_,Y)|0,n=n+Math.imul(m,Z)|0,i=(i=i+Math.imul(m,J)|0)+Math.imul(v,Z)|0,o=o+Math.imul(v,J)|0,n=n+Math.imul(p,Q)|0,i=(i=i+Math.imul(p,ee)|0)+Math.imul(b,Q)|0,o=o+Math.imul(b,ee)|0;var _e=(c+(n=n+Math.imul(h,re)|0)|0)+((8191&(i=(i=i+Math.imul(h,ne)|0)+Math.imul(l,re)|0))<<13)|0;c=((o=o+Math.imul(l,ne)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,n=Math.imul(T,q),i=(i=Math.imul(T,H))+Math.imul(U,q)|0,o=Math.imul(U,H),n=n+Math.imul(S,K)|0,i=(i=i+Math.imul(S,V)|0)+Math.imul(M,K)|0,o=o+Math.imul(M,V)|0,n=n+Math.imul(E,W)|0,i=(i=i+Math.imul(E,Y)|0)+Math.imul(x,W)|0,o=o+Math.imul(x,Y)|0,n=n+Math.imul(w,Z)|0,i=(i=i+Math.imul(w,J)|0)+Math.imul(_,Z)|0,o=o+Math.imul(_,J)|0,n=n+Math.imul(m,Q)|0,i=(i=i+Math.imul(m,ee)|0)+Math.imul(v,Q)|0,o=o+Math.imul(v,ee)|0,n=n+Math.imul(p,re)|0,i=(i=i+Math.imul(p,ne)|0)+Math.imul(b,re)|0,o=o+Math.imul(b,ne)|0;var Ae=(c+(n=n+Math.imul(h,oe)|0)|0)+((8191&(i=(i=i+Math.imul(h,ae)|0)+Math.imul(l,oe)|0))<<13)|0;c=((o=o+Math.imul(l,ae)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,n=Math.imul(B,q),i=(i=Math.imul(B,H))+Math.imul(P,q)|0,o=Math.imul(P,H),n=n+Math.imul(T,K)|0,i=(i=i+Math.imul(T,V)|0)+Math.imul(U,K)|0,o=o+Math.imul(U,V)|0,n=n+Math.imul(S,W)|0,i=(i=i+Math.imul(S,Y)|0)+Math.imul(M,W)|0,o=o+Math.imul(M,Y)|0,n=n+Math.imul(E,Z)|0,i=(i=i+Math.imul(E,J)|0)+Math.imul(x,Z)|0,o=o+Math.imul(x,J)|0,n=n+Math.imul(w,Q)|0,i=(i=i+Math.imul(w,ee)|0)+Math.imul(_,Q)|0,o=o+Math.imul(_,ee)|0,n=n+Math.imul(m,re)|0,i=(i=i+Math.imul(m,ne)|0)+Math.imul(v,re)|0,o=o+Math.imul(v,ne)|0,n=n+Math.imul(p,oe)|0,i=(i=i+Math.imul(p,ae)|0)+Math.imul(b,oe)|0,o=o+Math.imul(b,ae)|0;var Ee=(c+(n=n+Math.imul(h,ue)|0)|0)+((8191&(i=(i=i+Math.imul(h,ce)|0)+Math.imul(l,ue)|0))<<13)|0;c=((o=o+Math.imul(l,ce)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,n=Math.imul(N,q),i=(i=Math.imul(N,H))+Math.imul(R,q)|0,o=Math.imul(R,H),n=n+Math.imul(B,K)|0,i=(i=i+Math.imul(B,V)|0)+Math.imul(P,K)|0,o=o+Math.imul(P,V)|0,n=n+Math.imul(T,W)|0,i=(i=i+Math.imul(T,Y)|0)+Math.imul(U,W)|0,o=o+Math.imul(U,Y)|0,n=n+Math.imul(S,Z)|0,i=(i=i+Math.imul(S,J)|0)+Math.imul(M,Z)|0,o=o+Math.imul(M,J)|0,n=n+Math.imul(E,Q)|0,i=(i=i+Math.imul(E,ee)|0)+Math.imul(x,Q)|0,o=o+Math.imul(x,ee)|0,n=n+Math.imul(w,re)|0,i=(i=i+Math.imul(w,ne)|0)+Math.imul(_,re)|0,o=o+Math.imul(_,ne)|0,n=n+Math.imul(m,oe)|0,i=(i=i+Math.imul(m,ae)|0)+Math.imul(v,oe)|0,o=o+Math.imul(v,ae)|0,n=n+Math.imul(p,ue)|0,i=(i=i+Math.imul(p,ce)|0)+Math.imul(b,ue)|0,o=o+Math.imul(b,ce)|0;var xe=(c+(n=n+Math.imul(h,he)|0)|0)+((8191&(i=(i=i+Math.imul(h,le)|0)+Math.imul(l,he)|0))<<13)|0;c=((o=o+Math.imul(l,le)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,n=Math.imul(O,q),i=(i=Math.imul(O,H))+Math.imul(D,q)|0,o=Math.imul(D,H),n=n+Math.imul(N,K)|0,i=(i=i+Math.imul(N,V)|0)+Math.imul(R,K)|0,o=o+Math.imul(R,V)|0,n=n+Math.imul(B,W)|0,i=(i=i+Math.imul(B,Y)|0)+Math.imul(P,W)|0,o=o+Math.imul(P,Y)|0,n=n+Math.imul(T,Z)|0,i=(i=i+Math.imul(T,J)|0)+Math.imul(U,Z)|0,o=o+Math.imul(U,J)|0,n=n+Math.imul(S,Q)|0,i=(i=i+Math.imul(S,ee)|0)+Math.imul(M,Q)|0,o=o+Math.imul(M,ee)|0,n=n+Math.imul(E,re)|0,i=(i=i+Math.imul(E,ne)|0)+Math.imul(x,re)|0,o=o+Math.imul(x,ne)|0,n=n+Math.imul(w,oe)|0,i=(i=i+Math.imul(w,ae)|0)+Math.imul(_,oe)|0,o=o+Math.imul(_,ae)|0,n=n+Math.imul(m,ue)|0,i=(i=i+Math.imul(m,ce)|0)+Math.imul(v,ue)|0,o=o+Math.imul(v,ce)|0,n=n+Math.imul(p,he)|0,i=(i=i+Math.imul(p,le)|0)+Math.imul(b,he)|0,o=o+Math.imul(b,le)|0;var ke=(c+(n=n+Math.imul(h,pe)|0)|0)+((8191&(i=(i=i+Math.imul(h,be)|0)+Math.imul(l,pe)|0))<<13)|0;c=((o=o+Math.imul(l,be)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,n=Math.imul(O,K),i=(i=Math.imul(O,V))+Math.imul(D,K)|0,o=Math.imul(D,V),n=n+Math.imul(N,W)|0,i=(i=i+Math.imul(N,Y)|0)+Math.imul(R,W)|0,o=o+Math.imul(R,Y)|0,n=n+Math.imul(B,Z)|0,i=(i=i+Math.imul(B,J)|0)+Math.imul(P,Z)|0,o=o+Math.imul(P,J)|0,n=n+Math.imul(T,Q)|0,i=(i=i+Math.imul(T,ee)|0)+Math.imul(U,Q)|0,o=o+Math.imul(U,ee)|0,n=n+Math.imul(S,re)|0,i=(i=i+Math.imul(S,ne)|0)+Math.imul(M,re)|0,o=o+Math.imul(M,ne)|0,n=n+Math.imul(E,oe)|0,i=(i=i+Math.imul(E,ae)|0)+Math.imul(x,oe)|0,o=o+Math.imul(x,ae)|0,n=n+Math.imul(w,ue)|0,i=(i=i+Math.imul(w,ce)|0)+Math.imul(_,ue)|0,o=o+Math.imul(_,ce)|0,n=n+Math.imul(m,he)|0,i=(i=i+Math.imul(m,le)|0)+Math.imul(v,he)|0,o=o+Math.imul(v,le)|0;var Se=(c+(n=n+Math.imul(p,pe)|0)|0)+((8191&(i=(i=i+Math.imul(p,be)|0)+Math.imul(b,pe)|0))<<13)|0;c=((o=o+Math.imul(b,be)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,n=Math.imul(O,W),i=(i=Math.imul(O,Y))+Math.imul(D,W)|0,o=Math.imul(D,Y),n=n+Math.imul(N,Z)|0,i=(i=i+Math.imul(N,J)|0)+Math.imul(R,Z)|0,o=o+Math.imul(R,J)|0,n=n+Math.imul(B,Q)|0,i=(i=i+Math.imul(B,ee)|0)+Math.imul(P,Q)|0,o=o+Math.imul(P,ee)|0,n=n+Math.imul(T,re)|0,i=(i=i+Math.imul(T,ne)|0)+Math.imul(U,re)|0,o=o+Math.imul(U,ne)|0,n=n+Math.imul(S,oe)|0,i=(i=i+Math.imul(S,ae)|0)+Math.imul(M,oe)|0,o=o+Math.imul(M,ae)|0,n=n+Math.imul(E,ue)|0,i=(i=i+Math.imul(E,ce)|0)+Math.imul(x,ue)|0,o=o+Math.imul(x,ce)|0,n=n+Math.imul(w,he)|0,i=(i=i+Math.imul(w,le)|0)+Math.imul(_,he)|0,o=o+Math.imul(_,le)|0;var Me=(c+(n=n+Math.imul(m,pe)|0)|0)+((8191&(i=(i=i+Math.imul(m,be)|0)+Math.imul(v,pe)|0))<<13)|0;c=((o=o+Math.imul(v,be)|0)+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863,n=Math.imul(O,Z),i=(i=Math.imul(O,J))+Math.imul(D,Z)|0,o=Math.imul(D,J),n=n+Math.imul(N,Q)|0,i=(i=i+Math.imul(N,ee)|0)+Math.imul(R,Q)|0,o=o+Math.imul(R,ee)|0,n=n+Math.imul(B,re)|0,i=(i=i+Math.imul(B,ne)|0)+Math.imul(P,re)|0,o=o+Math.imul(P,ne)|0,n=n+Math.imul(T,oe)|0,i=(i=i+Math.imul(T,ae)|0)+Math.imul(U,oe)|0,o=o+Math.imul(U,ae)|0,n=n+Math.imul(S,ue)|0,i=(i=i+Math.imul(S,ce)|0)+Math.imul(M,ue)|0,o=o+Math.imul(M,ce)|0,n=n+Math.imul(E,he)|0,i=(i=i+Math.imul(E,le)|0)+Math.imul(x,he)|0,o=o+Math.imul(x,le)|0;var Ie=(c+(n=n+Math.imul(w,pe)|0)|0)+((8191&(i=(i=i+Math.imul(w,be)|0)+Math.imul(_,pe)|0))<<13)|0;c=((o=o+Math.imul(_,be)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,n=Math.imul(O,Q),i=(i=Math.imul(O,ee))+Math.imul(D,Q)|0,o=Math.imul(D,ee),n=n+Math.imul(N,re)|0,i=(i=i+Math.imul(N,ne)|0)+Math.imul(R,re)|0,o=o+Math.imul(R,ne)|0,n=n+Math.imul(B,oe)|0,i=(i=i+Math.imul(B,ae)|0)+Math.imul(P,oe)|0,o=o+Math.imul(P,ae)|0,n=n+Math.imul(T,ue)|0,i=(i=i+Math.imul(T,ce)|0)+Math.imul(U,ue)|0,o=o+Math.imul(U,ce)|0,n=n+Math.imul(S,he)|0,i=(i=i+Math.imul(S,le)|0)+Math.imul(M,he)|0,o=o+Math.imul(M,le)|0;var Te=(c+(n=n+Math.imul(E,pe)|0)|0)+((8191&(i=(i=i+Math.imul(E,be)|0)+Math.imul(x,pe)|0))<<13)|0;c=((o=o+Math.imul(x,be)|0)+(i>>>13)|0)+(Te>>>26)|0,Te&=67108863,n=Math.imul(O,re),i=(i=Math.imul(O,ne))+Math.imul(D,re)|0,o=Math.imul(D,ne),n=n+Math.imul(N,oe)|0,i=(i=i+Math.imul(N,ae)|0)+Math.imul(R,oe)|0,o=o+Math.imul(R,ae)|0,n=n+Math.imul(B,ue)|0,i=(i=i+Math.imul(B,ce)|0)+Math.imul(P,ue)|0,o=o+Math.imul(P,ce)|0,n=n+Math.imul(T,he)|0,i=(i=i+Math.imul(T,le)|0)+Math.imul(U,he)|0,o=o+Math.imul(U,le)|0;var Ue=(c+(n=n+Math.imul(S,pe)|0)|0)+((8191&(i=(i=i+Math.imul(S,be)|0)+Math.imul(M,pe)|0))<<13)|0;c=((o=o+Math.imul(M,be)|0)+(i>>>13)|0)+(Ue>>>26)|0,Ue&=67108863,n=Math.imul(O,oe),i=(i=Math.imul(O,ae))+Math.imul(D,oe)|0,o=Math.imul(D,ae),n=n+Math.imul(N,ue)|0,i=(i=i+Math.imul(N,ce)|0)+Math.imul(R,ue)|0,o=o+Math.imul(R,ce)|0,n=n+Math.imul(B,he)|0,i=(i=i+Math.imul(B,le)|0)+Math.imul(P,he)|0,o=o+Math.imul(P,le)|0;var je=(c+(n=n+Math.imul(T,pe)|0)|0)+((8191&(i=(i=i+Math.imul(T,be)|0)+Math.imul(U,pe)|0))<<13)|0;c=((o=o+Math.imul(U,be)|0)+(i>>>13)|0)+(je>>>26)|0,je&=67108863,n=Math.imul(O,ue),i=(i=Math.imul(O,ce))+Math.imul(D,ue)|0,o=Math.imul(D,ce),n=n+Math.imul(N,he)|0,i=(i=i+Math.imul(N,le)|0)+Math.imul(R,he)|0,o=o+Math.imul(R,le)|0;var Be=(c+(n=n+Math.imul(B,pe)|0)|0)+((8191&(i=(i=i+Math.imul(B,be)|0)+Math.imul(P,pe)|0))<<13)|0;c=((o=o+Math.imul(P,be)|0)+(i>>>13)|0)+(Be>>>26)|0,Be&=67108863,n=Math.imul(O,he),i=(i=Math.imul(O,le))+Math.imul(D,he)|0,o=Math.imul(D,le);var Pe=(c+(n=n+Math.imul(N,pe)|0)|0)+((8191&(i=(i=i+Math.imul(N,be)|0)+Math.imul(R,pe)|0))<<13)|0;c=((o=o+Math.imul(R,be)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863;var Ce=(c+(n=Math.imul(O,pe))|0)+((8191&(i=(i=Math.imul(O,be))+Math.imul(D,pe)|0))<<13)|0;return c=((o=Math.imul(D,be))+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,u[0]=ye,u[1]=me,u[2]=ve,u[3]=ge,u[4]=we,u[5]=_e,u[6]=Ae,u[7]=Ee,u[8]=xe,u[9]=ke,u[10]=Se,u[11]=Me,u[12]=Ie,u[13]=Te,u[14]=Ue,u[15]=je,u[16]=Be,u[17]=Pe,u[18]=Ce,0!==c&&(u[19]=c,r.length++),r};function p(e,t,r){return(new b).mulp(e,t,r)}function b(e,t){this.x=e,this.y=t}Math.imul||(d=l),o.prototype.mulTo=function(e,t){var r=this.length+e.length;return 10===this.length&&10===e.length?d(this,e,t):r<63?l(this,e,t):r<1024?function(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,a&=67108863}r.words[o]=s,n=a,a=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,e,t):p(this,e,t)},b.prototype.makeRBT=function(e){for(var t=new Array(e),r=o.prototype._countBits(e)-1,n=0;n>=1;return n},b.prototype.permute=function(e,t,r,n,i,o){for(var a=0;a>>=1)i++;return 1<>>=13,r[2*a+1]=8191&o,o>>>=13;for(a=2*t;a>=26,t+=i/67108864|0,t+=o>>>26,this.words[r]=67108863&o}return 0!==t&&(this.words[r]=t,this.length++),this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),r=0;r>>i}return t}(e);if(0===t.length)return new o(1);for(var r=this,n=0;n=0);var t,r=e%26,i=(e-r)/26,o=67108863>>>26-r<<26-r;if(0!==r){var a=0;for(t=0;t>>26-r}a&&(this.words[t]=a,this.length++)}if(0!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t=0),i=t?(t-t%26)/26:0;var o=e%26,a=Math.min((e-o)/26,this.length),s=67108863^67108863>>>o<a)for(this.length-=a,c=0;c=0&&(0!==f||c>=i);c--){var h=0|this.words[c];this.words[c]=f<<26-o|h>>>o,f=h&s}return u&&0!==f&&(u.words[u.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},o.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,i=1<=0);var t=e%26,r=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var i=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(u/67108864|0),this.words[i+r]=67108863&o}for(;i>26,this.words[i+r]=67108863&o;if(0===s)return this.strip();for(n(-1===s),s=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},o.prototype._wordDiv=function(e,t){var r=(this.length,e.length),n=this.clone(),i=e,a=0|i.words[i.length-1];0!==(r=26-this._countBits(a))&&(i=i.ushln(r),n.iushln(r),a=0|i.words[i.length-1]);var s,u=n.length-i.length;if("mod"!==t){(s=new o(null)).length=u+1,s.words=new Array(s.length);for(var c=0;c=0;h--){var l=67108864*(0|n.words[i.length+h])+(0|n.words[i.length+h-1]);for(l=Math.min(l/a|0,67108863),n._ishlnsubmul(i,l,h);0!==n.negative;)l--,n.negative=0,n._ishlnsubmul(i,1,h),n.isZero()||(n.negative^=1);s&&(s.words[h]=l)}return s&&s.strip(),n.strip(),"div"!==t&&0!==r&&n.iushrn(r),{div:s||null,mod:n}},o.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(s=this.neg().divmod(e,t),"mod"!==t&&(i=s.div.neg()),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.iadd(e)),{div:i,mod:a}):0===this.negative&&0!==e.negative?(s=this.divmod(e.neg(),t),"mod"!==t&&(i=s.div.neg()),{div:i,mod:s.mod}):0!=(this.negative&e.negative)?(s=this.neg().divmod(e.neg(),t),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.isub(e)),{div:s.div,mod:a}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modn(e.words[0]))}:this._wordDiv(e,t);var i,a,s},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=0!==t.div.negative?t.mod.isub(e):t.mod,n=e.ushrn(1),i=e.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modn=function(e){n(e<=67108863);for(var t=(1<<26)%e,r=0,i=this.length-1;i>=0;i--)r=(t*r+(0|this.words[i]))%e;return r},o.prototype.idivn=function(e){n(e<=67108863);for(var t=0,r=this.length-1;r>=0;r--){var i=(0|this.words[r])+67108864*t;this.words[r]=i/e|0,t=i%e}return this.strip()},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new o(1),a=new o(0),s=new o(0),u=new o(1),c=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++c;for(var f=r.clone(),h=t.clone();!t.isZero();){for(var l=0,d=1;0==(t.words[0]&d)&&l<26;++l,d<<=1);if(l>0)for(t.iushrn(l);l-- >0;)(i.isOdd()||a.isOdd())&&(i.iadd(f),a.isub(h)),i.iushrn(1),a.iushrn(1);for(var p=0,b=1;0==(r.words[0]&b)&&p<26;++p,b<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(s.isOdd()||u.isOdd())&&(s.iadd(f),u.isub(h)),s.iushrn(1),u.iushrn(1);t.cmp(r)>=0?(t.isub(r),i.isub(s),a.isub(u)):(r.isub(t),s.isub(i),u.isub(a))}return{a:s,b:u,gcd:r.iushln(c)}},o.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,a=new o(1),s=new o(0),u=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var c=0,f=1;0==(t.words[0]&f)&&c<26;++c,f<<=1);if(c>0)for(t.iushrn(c);c-- >0;)a.isOdd()&&a.iadd(u),a.iushrn(1);for(var h=0,l=1;0==(r.words[0]&l)&&h<26;++h,l<<=1);if(h>0)for(r.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(u),s.iushrn(1);t.cmp(r)>=0?(t.isub(r),a.isub(s)):(r.isub(t),s.isub(a))}return(i=0===t.cmpn(1)?a:s).cmpn(0)<0&&i.iadd(e),i},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var n=0;t.isEven()&&r.isEven();n++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=t.cmp(r);if(i<0){var o=t;t=r,r=o}else if(0===i||0===r.cmpn(1))break;t.isub(r)}return r.iushln(n)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return 0==(1&this.words[0])},o.prototype.isOdd=function(){return 1==(1&this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,i=1<>>26,s&=67108863,this.words[a]=s}return 0!==o&&(this.words[a]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this.strip(),this.length>1)t=1;else{r&&(e=-e),n(e<=67108863,"Number is too big");var i=0|this.words[0];t=i===e?0:ie.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|e.words[r];if(n!==i){ni&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new A(e)},o.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var y={k256:null,p224:null,p192:null,p25519:null};function m(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function v(){m.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function g(){m.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function w(){m.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function _(){m.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function A(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function E(e){A.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(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)}m.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},m.prototype.ireduce=function(e){var t,r=e;do{this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(t>this.n);var n=t0?r.isub(this.p):r.strip(),r},m.prototype.split=function(e,t){e.iushrn(this.n,0,t)},m.prototype.imulK=function(e){return e.imul(this.k)},i(v,m),v.prototype.split=function(e,t){for(var r=Math.min(e.length,9),n=0;n>>22,i=o}i>>>=22,e.words[n-10]=i,0===i&&e.length>10?e.length-=10:e.length-=9},v.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r>>=26,e.words[r]=i,t=n}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(y[e])return y[e];var t;if("k256"===e)t=new v;else if("p224"===e)t=new g;else if("p192"===e)t=new w;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new _}return y[e]=t,t},A.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},A.prototype._verify2=function(e,t){n(0==(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},A.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},A.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},A.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},A.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},A.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},A.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},A.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},A.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},A.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},A.prototype.isqr=function(e){return this.imul(e,e.clone())},A.prototype.sqr=function(e){return this.mul(e,e)},A.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var r=this.m.add(new o(1)).iushrn(2);return this.pow(e,r)}for(var i=this.m.subn(1),a=0;!i.isZero()&&0===i.andln(1);)a++,i.iushrn(1);n(!i.isZero());var s=new o(1).toRed(this),u=s.redNeg(),c=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new o(2*f*f).toRed(this);0!==this.pow(f,c).cmp(u);)f.redIAdd(u);for(var h=this.pow(f,i),l=this.pow(e,i.addn(1).iushrn(1)),d=this.pow(e,i),p=a;0!==d.cmp(s);){for(var b=d,y=0;0!==b.cmp(s);y++)b=b.redSqr();n(y=0;n--){for(var c=t.words[n],f=u-1;f>=0;f--){var h=c>>f&1;i!==r[0]&&(i=this.sqr(i)),0!==h||0!==a?(a<<=1,a|=h,(4===++s||0===n&&0===f)&&(i=this.mul(i,r[a]),s=0,a=0)):s=0}u=26}return i},A.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},A.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new E(e)},i(E,A),E.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},E.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},E.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},E.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var r=e.mul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},E.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===t||t,this)},{}],155:[function(e,t,r){(function(r){"use strict";var n=e("is-hex-prefixed"),i=e("strip-hex-prefix");function o(e){var t=e;if("string"!=typeof t)throw new Error("[ethjs-util] while padding to even, value must be string, is currently "+typeof t+", while padToEven.");return t.length%2&&(t="0"+t),t}function a(e){return"0x"+e.toString(16)}t.exports={arrayContainsArray:function(e,t,r){if(!0!==Array.isArray(e))throw new Error("[ethjs-util] method arrayContainsArray requires input 'superset' to be an array got type '"+typeof e+"'");if(!0!==Array.isArray(t))throw new Error("[ethjs-util] method arrayContainsArray requires input 'subset' to be an array got type '"+typeof t+"'");return t[Boolean(r)?"some":"every"](function(t){return e.indexOf(t)>=0})},intToBuffer:function(e){var t=a(e);return new r(o(t.slice(2)),"hex")},getBinarySize:function(e){if("string"!=typeof e)throw new Error("[ethjs-util] while getting binary size, method getBinarySize requires input 'str' to be type String, got '"+typeof e+"'.");return r.byteLength(e,"utf8")},isHexPrefixed:n,stripHexPrefix:i,padToEven:o,intToHex:a,fromAscii:function(e){for(var t="",r=0;r0&&this._events[e].length>r&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(e,t){if(!i(t))throw TypeError("listener must be a function");var r=!1;function n(){this.removeListener(e,n),r||(r=!0,t.apply(this,arguments))}return n.listener=t,this.on(e,n),this},n.prototype.removeListener=function(e,t){var r,n,a,s;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(a=(r=this._events[e]).length,n=-1,r===t||i(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(o(r)){for(s=a;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){n=s;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},n.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(i(r=this._events[e]))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},n.prototype.listeners=function(e){return this._events&&this._events[e]?i(this._events[e])?[this._events[e]]:this._events[e].slice():[]},n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;if(t)return t.length}return 0},n.listenerCount=function(e,t){return e.listenerCount(t)}},{}],158:[function(e,t,r){var n=e("safe-buffer").Buffer,i=e("md5.js");t.exports=function(e,t,r,o){if(n.isBuffer(e)||(e=n.from(e,"binary")),t&&(n.isBuffer(t)||(t=n.from(t,"binary")),8!==t.length))throw new RangeError("salt should be Buffer with 8 byte length");for(var a=r/8,s=n.alloc(a),u=n.alloc(o||0),c=n.alloc(0);a>0||o>0;){var f=new i;f.update(c),f.update(e),t&&f.update(t),c=f.digest();var h=0;if(a>0){var l=s.length-a;h=Math.min(a,c.length),c.copy(s,l,0,h),a-=h}if(h0){var d=u.length-o,p=Math.min(o,c.length-h);c.copy(u,d,h,h+p),o-=p}}return c.fill(0),{key:s,iv:u}}},{"md5.js":231,"safe-buffer":290}],159:[function(e,t,r){"use strict";var n=e("is-callable"),i=Object.prototype.toString,o=Object.prototype.hasOwnProperty;t.exports=function(e,t,r){if(!n(t))throw new TypeError("iterator must be a function");var a;arguments.length>=3&&(a=r),"[object Array]"===i.call(e)?function(e,t,r){for(var n=0,i=e.length;n=this._blockSize;){for(var o=this._blockOffset;o0;++a)this._length[a]+=s,(s=this._length[a]/4294967296|0)>0&&(this._length[a]-=4294967296*s);return this},i.prototype._update=function(e){throw new Error("_update is not implemented")},i.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();return void 0!==e&&(t=t.toString(e)),t},i.prototype._digest=function(){throw new Error("_digest is not implemented")},t.exports=i}).call(this,e("buffer").Buffer)},{buffer:84,inherits:180,stream:311}],162:[function(e,t,r){var n=r;n.utils=e("./hash/utils"),n.common=e("./hash/common"),n.sha=e("./hash/sha"),n.ripemd=e("./hash/ripemd"),n.hmac=e("./hash/hmac"),n.sha1=n.sha.sha1,n.sha256=n.sha.sha256,n.sha224=n.sha.sha224,n.sha384=n.sha.sha384,n.sha512=n.sha.sha512,n.ripemd160=n.ripemd.ripemd160},{"./hash/common":163,"./hash/hmac":164,"./hash/ripemd":165,"./hash/sha":166,"./hash/utils":173}],163:[function(e,t,r){"use strict";var n=e("./utils"),i=e("minimalistic-assert");function o(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}r.BlockHash=o,o.prototype.update=function(e,t){if(e=n.toArray(e,t),this.pending?this.pending=this.pending.concat(e):this.pending=e,this.pendingTotal+=e.length,this.pending.length>=this._delta8){var r=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-r,e.length),0===this.pending.length&&(this.pending=null),e=n.join32(e,0,e.length-r,this.endian);for(var i=0;i>>24&255,n[i++]=e>>>16&255,n[i++]=e>>>8&255,n[i++]=255&e}else for(n[i++]=255&e,n[i++]=e>>>8&255,n[i++]=e>>>16&255,n[i++]=e>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,o=8;othis.blockSize&&(e=(new this.Hash).update(e).digest()),i(e.length<=this.blockSize);for(var t=e.length;t>>3},r.g1_256=function(e){return n(e,17)^n(e,19)^e>>>10}},{"../utils":173}],173:[function(e,t,r){"use strict";var n=e("minimalistic-assert"),i=e("inherits");function o(e){return(e>>>24|e>>>8&65280|e<<8&16711680|(255&e)<<24)>>>0}function a(e){return 1===e.length?"0"+e:e}function s(e){return 7===e.length?"0"+e:6===e.length?"00"+e:5===e.length?"000"+e:4===e.length?"0000"+e:3===e.length?"00000"+e:2===e.length?"000000"+e:1===e.length?"0000000"+e:e}r.inherits=i,r.toArray=function(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var r=[];if("string"==typeof e)if(t){if("hex"===t)for((e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e),n=0;n>8,a=255&i;o?r.push(o,a):r.push(a)}else for(n=0;n>>0}return a},r.split32=function(e,t){for(var r=new Array(4*e.length),n=0,i=0;n>>24,r[i+1]=o>>>16&255,r[i+2]=o>>>8&255,r[i+3]=255&o):(r[i+3]=o>>>24,r[i+2]=o>>>16&255,r[i+1]=o>>>8&255,r[i]=255&o)}return r},r.rotr32=function(e,t){return e>>>t|e<<32-t},r.rotl32=function(e,t){return e<>>32-t},r.sum32=function(e,t){return e+t>>>0},r.sum32_3=function(e,t,r){return e+t+r>>>0},r.sum32_4=function(e,t,r,n){return e+t+r+n>>>0},r.sum32_5=function(e,t,r,n,i){return e+t+r+n+i>>>0},r.sum64=function(e,t,r,n){var i=e[t],o=n+e[t+1]>>>0,a=(o>>0,e[t+1]=o},r.sum64_hi=function(e,t,r,n){return(t+n>>>0>>0},r.sum64_lo=function(e,t,r,n){return t+n>>>0},r.sum64_4_hi=function(e,t,r,n,i,o,a,s){var u=0,c=t;return u+=(c=c+n>>>0)>>0)>>0)>>0},r.sum64_4_lo=function(e,t,r,n,i,o,a,s){return t+n+o+s>>>0},r.sum64_5_hi=function(e,t,r,n,i,o,a,s,u,c){var f=0,h=t;return f+=(h=h+n>>>0)>>0)>>0)>>0)>>0},r.sum64_5_lo=function(e,t,r,n,i,o,a,s,u,c){return t+n+o+s+c>>>0},r.rotr64_hi=function(e,t,r){return(t<<32-r|e>>>r)>>>0},r.rotr64_lo=function(e,t,r){return(e<<32-r|t>>>r)>>>0},r.shr64_hi=function(e,t,r){return e>>>r},r.shr64_lo=function(e,t,r){return(e<<32-r|t>>>r)>>>0}},{inherits:180,"minimalistic-assert":234}],174:[function(e,t,r){"use strict";var n=e("hash.js"),i=e("minimalistic-crypto-utils"),o=e("minimalistic-assert");function a(e){if(!(this instanceof a))return new a(e);this.hash=e.hash,this.predResist=!!e.predResist,this.outLen=this.hash.outSize,this.minEntropy=e.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var t=i.toArray(e.entropy,e.entropyEnc||"hex"),r=i.toArray(e.nonce,e.nonceEnc||"hex"),n=i.toArray(e.pers,e.persEnc||"hex");o(t.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(t,r,n)}t.exports=a,a.prototype._init=function(e,t,r){var n=e.concat(t).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(e.concat(r||[])),this._reseed=1},a.prototype.generate=function(e,t,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof t&&(n=r,r=t,t=null),r&&(r=i.toArray(r,n||"hex"),this._update(r));for(var o=[];o.length\\$%@ءؤة\"'^|~⦅⦆・ゥャ¢£¬¦¥₩│←↑→↓■○𐐨𐐩𐐪𐐫𐐬𐐭𐐮𐐯𐐰𐐱𐐲𐐳𐐴𐐵𐐶𐐷𐐸𐐹𐐺𐐻𐐼𐐽𐐾𐐿𐑀𐑁𐑂𐑃𐑄𐑅𐑆𐑇𐑈𐑉𐑊𐑋𐑌𐑍𐑎𐑏𐓘𐓙𐓚𐓛𐓜𐓝𐓞𐓟𐓠𐓡𐓢𐓣𐓤𐓥𐓦𐓧𐓨𐓩𐓪𐓫𐓬𐓭𐓮𐓯𐓰𐓱𐓲𐓳𐓴𐓵𐓶𐓷𐓸𐓹𐓺𐓻𐳀𐳁𐳂𐳃𐳄𐳅𐳆𐳇𐳈𐳉𐳊𐳋𐳌𐳍𐳎𐳏𐳐𐳑𐳒𐳓𐳔𐳕𐳖𐳗𐳘𐳙𐳚𐳛𐳜𐳝𐳞𐳟𐳠𐳡𐳢𐳣𐳤𐳥𐳦𐳧𐳨𐳩𐳪𐳫𐳬𐳭𐳮𐳯𐳰𐳱𐳲𑣀𑣁𑣂𑣃𑣄𑣅𑣆𑣇𑣈𑣉𑣊𑣋𑣌𑣍𑣎𑣏𑣐𑣑𑣒𑣓𑣔𑣕𑣖𑣗𑣘𑣙𑣚𑣛𑣜𑣝𑣞𑣟ıȷ∇∂𞤢𞤣𞤤𞤥𞤦𞤧𞤨𞤩𞤪𞤫𞤬𞤭𞤮𞤯𞤰𞤱𞤲𞤳𞤴𞤵𞤶𞤷𞤸𞤹𞤺𞤻𞤼𞤽𞤾𞤿𞥀𞥁𞥂𞥃ٮڡٯ字双多解交映無前後再新初終販声吹演投捕遊指禁空合満申割営配得可丽丸乁𠄢你侻倂偺備像㒞𠘺兔兤具𠔜㒹內𠕋冗冤仌冬𩇟刃㓟刻剆剷㔕包匆卉博即卽卿𠨬灰及叟𠭣叫叱吆咞吸呈周咢哶唐啓啣善喫喳嗂圖圗噑噴壮城埴堍型堲報墬𡓤売壷夆夢奢𡚨𡛪姬娛娧姘婦㛮嬈嬾𡧈寃寘寳𡬘寿将㞁屠峀岍𡷤嵃𡷦嵮嵫嵼巡巢㠯巽帨帽幩㡢𢆃㡼庰庳庶𪎒𢌱舁弢㣇𣊸𦇚形彫㣣徚忍志忹悁㤺㤜𢛔惇慈慌慺憲憤憯懞戛扝抱拔捐𢬌挽拼捨掃揤𢯱搢揅掩㨮摩摾撝摷㩬敬𣀊旣書晉㬙㬈㫤冒冕最暜肭䏙朡杞杓𣏃㭉柺枅桒𣑭梎栟椔楂榣槪檨𣚣櫛㰘次𣢧歔㱎歲殟殻𣪍𡴋𣫺汎𣲼沿泍汧洖派浩浸涅𣴞洴港湮㴳滇𣻑淹潮𣽞𣾎濆瀹瀛㶖灊災灷炭𠔥煅𤉣熜爨牐𤘈犀犕𤜵𤠔獺王㺬玥㺸瑇瑜璅瓊㼛甤𤰶甾𤲒𢆟瘐𤾡𤾸𥁄㿼䀈𥃳𥃲𥄙𥄳眞真瞋䁆䂖𥐝硎䃣𥘦𥚚𥛅秫䄯穊穏𥥼𥪧䈂𥮫篆築䈧𥲀糒䊠糨糣紀𥾆絣䌁緇縂繅䌴𦈨𦉇䍙𦋙罺𦌾羕翺𦓚𦔣聠𦖨聰𣍟䏕育脃䐋脾媵𦞧𦞵𣎓𣎜舄辞䑫芑芋芝劳花芳芽苦𦬼茝荣莭茣莽菧荓菊菌菜𦰶𦵫𦳕䔫蓱蓳蔖𧏊蕤𦼬䕝䕡𦾱𧃒䕫虐虧虩蚩蚈蜎蛢蜨蝫螆蟡蠁䗹衠𧙧裗裞䘵裺㒻𧢮𧥦䚾䛇誠𧲨貫賁贛起𧼯𠠄跋趼跰𠣞軔𨗒𨗭邔郱鄑𨜮鄛鈸鋗鋘鉼鏹鐕𨯺開䦕閷𨵷䧦雃嶲霣𩅅𩈚䩮䩶韠𩐊䪲𩒖頩𩖶飢䬳餩馧駂駾䯎𩬰鱀鳽䳎䳭鵧𪃎䳸𪄅𪈎𪊑䵖黾鼅鼏鼖𪘀",mapChar:function(r){return r>=196608?r>=917760&&r<=917999?18874368:0:e[t[r>>4]][15&r]}}},"function"==typeof define&&define.amd?define([],function(){return i()}):"object"==typeof r?t.exports=i():n.uts46_map=i()},{}],177:[function(e,t,r){var n,i;n=this,i=function(e,t){function r(r,n,i){for(var o=[],a=e.ucs2.decode(r),s=0;s>23,l=f>>21&3,d=f>>5&65535,p=31&f,b=t.mapStr.substr(d,p);if(0===l||n&&1&h)throw new Error("Illegal char "+c);1===l?o.push(b):2===l?o.push(i?b:c):3===l&&o.push(c)}return o.join("").normalize("NFC")}function n(t,n,o){void 0===o&&(o=!1);var a=r(t,o,n).split(".");return(a=a.map(function(t){return t.startsWith("xn--")?i(t=e.decode(t.substring(4)),o,!1):i(t,o,n),t})).join(".")}function i(e,n,i){if("-"===e[2]&&"-"===e[3])throw new Error("Failed to validate "+e);if(e.startsWith("-")||e.endsWith("-"))throw new Error("Failed to validate "+e);if(e.includes("."))throw new Error("Failed to validate "+e);if(r(e,n,i)!==e)throw new Error("Failed to validate "+e);var o=e.codePointAt(0);if(t.mapChar(o)&2<<23)throw new Error("Label contains illegal character: "+o)}return{toUnicode:function(e,t){return void 0===t&&(t={}),n(e,!1,"useStd3ASCII"in t&&t.useStd3ASCII)},toAscii:function(t,r){void 0===r&&(r={});var i,o=!("transitional"in r)||r.transitional,a="useStd3ASCII"in r&&r.useStd3ASCII,s="verifyDnsLength"in r&&r.verifyDnsLength,u=n(t,o,a).split(".").map(e.toASCII),c=u.join(".");if(s){if(c.length<1||c.length>253)throw new Error("DNS name has wrong length: "+c);for(i=0;i63)throw new Error("DNS label has wrong length: "+f)}}return c}}},"function"==typeof define&&define.amd?define(["punycode","./idna-map"],function(e,t){return i(e,t)}):"object"==typeof r?t.exports=i(e("punycode"),e("./idna-map")):n.uts46=i(n.punycode,n.idna_map)},{"./idna-map":176,punycode:265}],178:[function(e,t,r){r.read=function(e,t,r,n,i){var o,a,s=8*i-n-1,u=(1<>1,f=-7,h=r?i-1:0,l=r?-1:1,d=e[t+h];for(h+=l,o=d&(1<<-f)-1,d>>=-f,f+=s;f>0;o=256*o+e[t+h],h+=l,f-=8);for(a=o&(1<<-f)-1,o>>=-f,f+=n;f>0;a=256*a+e[t+h],h+=l,f-=8);if(0===o)o=1-c;else{if(o===u)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,n),o-=c}return(d?-1:1)*a*Math.pow(2,o-n)},r.write=function(e,t,r,n,i,o){var a,s,u,c=8*o-i-1,f=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:o-1,p=n?1:-1,b=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=f):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+h>=1?l/u:l*Math.pow(2,1-h))*u>=2&&(a++,u/=2),a+h>=f?(s=0,a=f):a+h>=1?(s=(t*u-1)*Math.pow(2,i),a+=h):(s=t*Math.pow(2,h-1)*Math.pow(2,i),a=0));i>=8;e[r+d]=255&s,d+=p,s/=256,i-=8);for(a=a<0;e[r+d]=255&a,d+=p,a/=256,c-=8);e[r+d-p]|=128*b}},{}],179:[function(e,t,r){var n=[].indexOf;t.exports=function(e,t){if(n)return e.indexOf(t);for(var r=0;r-32e3)throw new Error("Invalid error code");if(!(this instanceof f))return new f(e);i.call(this,"Server error",e)};n(f,i),i.ParseError=o,i.InvalidRequest=a,i.MethodNotFound=s,i.InvalidParams=u,i.InternalError=c,i.ServerError=f,t.exports=i},{inherits:180}],191:[function(e,t,r){t.exports=function(e){var t=(e=e||{}).max||Number.MAX_SAFE_INTEGER,r=void 0!==e.start?e.start:Math.floor(Math.random()*t);return function(){return r%=t,r++}}},{}],192:[function(e,t,r){r.parse=e("./lib/parse"),r.stringify=e("./lib/stringify")},{"./lib/parse":193,"./lib/stringify":194}],193:[function(e,t,r){var n,i,o,a,s={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"},u=function(e){throw{name:"SyntaxError",message:e,at:n,text:o}},c=function(e){return e&&e!==i&&u("Expected '"+e+"' instead of '"+i+"'"),i=o.charAt(n),n+=1,i},f=function(){var e,t="";for("-"===i&&(t="-",c("-"));i>="0"&&i<="9";)t+=i,c();if("."===i)for(t+=".";c()&&i>="0"&&i<="9";)t+=i;if("e"===i||"E"===i)for(t+=i,c(),"-"!==i&&"+"!==i||(t+=i,c());i>="0"&&i<="9";)t+=i,c();if(e=+t,isFinite(e))return e;u("Bad number")},h=function(){var e,t,r,n="";if('"'===i)for(;c();){if('"'===i)return c(),n;if("\\"===i)if(c(),"u"===i){for(r=0,t=0;t<4&&(e=parseInt(c(),16),isFinite(e));t+=1)r=16*r+e;n+=String.fromCharCode(r)}else{if("string"!=typeof s[i])break;n+=s[i]}else n+=i}u("Bad string")},l=function(){for(;i&&i<=" ";)c()};a=function(){switch(l(),i){case"{":return function(){var e,t={};if("{"===i){if(c("{"),l(),"}"===i)return c("}"),t;for(;i;){if(e=h(),l(),c(":"),Object.hasOwnProperty.call(t,e)&&u('Duplicate key "'+e+'"'),t[e]=a(),l(),"}"===i)return c("}"),t;c(","),l()}}u("Bad object")}();case"[":return function(){var e=[];if("["===i){if(c("["),l(),"]"===i)return c("]"),e;for(;i;){if(e.push(a()),l(),"]"===i)return c("]"),e;c(","),l()}}u("Bad array")}();case'"':return h();case"-":return f();default:return i>="0"&&i<="9"?f():function(){switch(i){case"t":return c("t"),c("r"),c("u"),c("e"),!0;case"f":return c("f"),c("a"),c("l"),c("s"),c("e"),!1;case"n":return c("n"),c("u"),c("l"),c("l"),null}u("Unexpected '"+i+"'")}()}},t.exports=function(e,t){var r;return o=e,n=0,i=" ",r=a(),l(),i&&u("Syntax error"),"function"==typeof t?function e(r,n){var i,o,a=r[n];if(a&&"object"==typeof a)for(i in a)Object.prototype.hasOwnProperty.call(a,i)&&(void 0!==(o=e(a,i))?a[i]=o:delete a[i]);return t.call(r,n,a)}({"":r},""):r}},{}],194:[function(e,t,r){var n,i,o,a=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,s={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};function u(e){return a.lastIndex=0,a.test(e)?'"'+e.replace(a,function(e){var t=s[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}t.exports=function(e,t,r){var a;if(n="",i="","number"==typeof r)for(a=0;a>>31),p=l^(a<<1|o>>>31),b=e[0]^d,y=e[1]^p,m=e[10]^d,v=e[11]^p,g=e[20]^d,w=e[21]^p,_=e[30]^d,A=e[31]^p,E=e[40]^d,x=e[41]^p;d=r^(s<<1|u>>>31),p=i^(u<<1|s>>>31);var k=e[2]^d,S=e[3]^p,M=e[12]^d,I=e[13]^p,T=e[22]^d,U=e[23]^p,j=e[32]^d,B=e[33]^p,P=e[42]^d,C=e[43]^p;d=o^(c<<1|f>>>31),p=a^(f<<1|c>>>31);var N=e[4]^d,R=e[5]^p,L=e[14]^d,O=e[15]^p,D=e[24]^d,F=e[25]^p,q=e[34]^d,H=e[35]^p,z=e[44]^d,K=e[45]^p;d=s^(h<<1|l>>>31),p=u^(l<<1|h>>>31);var V=e[6]^d,G=e[7]^p,W=e[16]^d,Y=e[17]^p,X=e[26]^d,Z=e[27]^p,J=e[36]^d,$=e[37]^p,Q=e[46]^d,ee=e[47]^p;d=c^(r<<1|i>>>31),p=f^(i<<1|r>>>31);var te=e[8]^d,re=e[9]^p,ne=e[18]^d,ie=e[19]^p,oe=e[28]^d,ae=e[29]^p,se=e[38]^d,ue=e[39]^p,ce=e[48]^d,fe=e[49]^p,he=b,le=y,de=v<<4|m>>>28,pe=m<<4|v>>>28,be=g<<3|w>>>29,ye=w<<3|g>>>29,me=A<<9|_>>>23,ve=_<<9|A>>>23,ge=E<<18|x>>>14,we=x<<18|E>>>14,_e=k<<1|S>>>31,Ae=S<<1|k>>>31,Ee=I<<12|M>>>20,xe=M<<12|I>>>20,ke=T<<10|U>>>22,Se=U<<10|T>>>22,Me=B<<13|j>>>19,Ie=j<<13|B>>>19,Te=P<<2|C>>>30,Ue=C<<2|P>>>30,je=R<<30|N>>>2,Be=N<<30|R>>>2,Pe=L<<6|O>>>26,Ce=O<<6|L>>>26,Ne=F<<11|D>>>21,Re=D<<11|F>>>21,Le=q<<15|H>>>17,Oe=H<<15|q>>>17,De=K<<29|z>>>3,Fe=z<<29|K>>>3,qe=V<<28|G>>>4,He=G<<28|V>>>4,ze=Y<<23|W>>>9,Ke=W<<23|Y>>>9,Ve=X<<25|Z>>>7,Ge=Z<<25|X>>>7,We=J<<21|$>>>11,Ye=$<<21|J>>>11,Xe=ee<<24|Q>>>8,Ze=Q<<24|ee>>>8,Je=te<<27|re>>>5,$e=re<<27|te>>>5,Qe=ne<<20|ie>>>12,et=ie<<20|ne>>>12,tt=ae<<7|oe>>>25,rt=oe<<7|ae>>>25,nt=se<<8|ue>>>24,it=ue<<8|se>>>24,ot=ce<<14|fe>>>18,at=fe<<14|ce>>>18;e[0]=he^~Ee&Ne,e[1]=le^~xe&Re,e[10]=qe^~Qe&be,e[11]=He^~et&ye,e[20]=_e^~Pe&Ve,e[21]=Ae^~Ce&Ge,e[30]=Je^~de&ke,e[31]=$e^~pe&Se,e[40]=je^~ze&tt,e[41]=Be^~Ke&rt,e[2]=Ee^~Ne&We,e[3]=xe^~Re&Ye,e[12]=Qe^~be&Me,e[13]=et^~ye&Ie,e[22]=Pe^~Ve&nt,e[23]=Ce^~Ge&it,e[32]=de^~ke&Le,e[33]=pe^~Se&Oe,e[42]=ze^~tt&me,e[43]=Ke^~rt&ve,e[4]=Ne^~We&ot,e[5]=Re^~Ye&at,e[14]=be^~Me&De,e[15]=ye^~Ie&Fe,e[24]=Ve^~nt&ge,e[25]=Ge^~it&we,e[34]=ke^~Le&Xe,e[35]=Se^~Oe&Ze,e[44]=tt^~me&Te,e[45]=rt^~ve&Ue,e[6]=We^~ot&he,e[7]=Ye^~at&le,e[16]=Me^~De&qe,e[17]=Ie^~Fe&He,e[26]=nt^~ge&_e,e[27]=it^~we&Ae,e[36]=Le^~Xe&Je,e[37]=Oe^~Ze&$e,e[46]=me^~Te&je,e[47]=ve^~Ue&Be,e[8]=ot^~he&Ee,e[9]=at^~le&xe,e[18]=De^~qe&Qe,e[19]=Fe^~He&et,e[28]=ge^~_e&Pe,e[29]=we^~Ae&Ce,e[38]=Xe^~Je&de,e[39]=Ze^~$e&pe,e[48]=Te^~je&ze,e[49]=Ue^~Be&Ke,e[0]^=n[2*t],e[1]^=n[2*t+1]}}},{}],200:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("./keccak-state-unroll");function o(){this.state=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.blockSize=null,this.count=0,this.squeezing=!1}o.prototype.initialize=function(e,t){for(var r=0;r<50;++r)this.state[r]=0;this.blockSize=e/8,this.count=0,this.squeezing=!1},o.prototype.absorb=function(e){for(var t=0;t>>this.count%4*8&255,this.count+=1,this.count===this.blockSize&&(i.p1600(this.state),this.count=0);return t},o.prototype.copy=function(e){for(var t=0;t<50;++t)e.state[t]=this.state[t];e.blockSize=this.blockSize,e.count=this.count,e.squeezing=this.squeezing},t.exports=o},{"./keccak-state-unroll":199,"safe-buffer":290}],201:[function(e,t,r){var n=e("./_root").Symbol;t.exports=n},{"./_root":217}],202:[function(e,t,r){var n=e("./_baseTimes"),i=e("./isArguments"),o=e("./isArray"),a=e("./isBuffer"),s=e("./_isIndex"),u=e("./isTypedArray"),c=Object.prototype.hasOwnProperty;t.exports=function(e,t){var r=o(e),f=!r&&i(e),h=!r&&!f&&a(e),l=!r&&!f&&!h&&u(e),d=r||f||h||l,p=d?n(e.length,String):[],b=p.length;for(var y in e)!t&&!c.call(e,y)||d&&("length"==y||h&&("offset"==y||"parent"==y)||l&&("buffer"==y||"byteLength"==y||"byteOffset"==y)||s(y,b))||p.push(y);return p}},{"./_baseTimes":207,"./_isIndex":211,"./isArguments":219,"./isArray":220,"./isBuffer":222,"./isTypedArray":227}],203:[function(e,t,r){var n=e("./_Symbol"),i=e("./_getRawTag"),o=e("./_objectToString"),a="[object Null]",s="[object Undefined]",u=n?n.toStringTag:void 0;t.exports=function(e){return null==e?void 0===e?s:a:u&&u in Object(e)?i(e):o(e)}},{"./_Symbol":201,"./_getRawTag":210,"./_objectToString":215}],204:[function(e,t,r){var n=e("./_baseGetTag"),i=e("./isObjectLike"),o="[object Arguments]";t.exports=function(e){return i(e)&&n(e)==o}},{"./_baseGetTag":203,"./isObjectLike":226}],205:[function(e,t,r){var n=e("./_baseGetTag"),i=e("./isLength"),o=e("./isObjectLike"),a={};a["[object Float32Array]"]=a["[object Float64Array]"]=a["[object Int8Array]"]=a["[object Int16Array]"]=a["[object Int32Array]"]=a["[object Uint8Array]"]=a["[object Uint8ClampedArray]"]=a["[object Uint16Array]"]=a["[object Uint32Array]"]=!0,a["[object Arguments]"]=a["[object Array]"]=a["[object ArrayBuffer]"]=a["[object Boolean]"]=a["[object DataView]"]=a["[object Date]"]=a["[object Error]"]=a["[object Function]"]=a["[object Map]"]=a["[object Number]"]=a["[object Object]"]=a["[object RegExp]"]=a["[object Set]"]=a["[object String]"]=a["[object WeakMap]"]=!1,t.exports=function(e){return o(e)&&i(e.length)&&!!a[n(e)]}},{"./_baseGetTag":203,"./isLength":224,"./isObjectLike":226}],206:[function(e,t,r){var n=e("./_isPrototype"),i=e("./_nativeKeys"),o=Object.prototype.hasOwnProperty;t.exports=function(e){if(!n(e))return i(e);var t=[];for(var r in Object(e))o.call(e,r)&&"constructor"!=r&&t.push(r);return t}},{"./_isPrototype":212,"./_nativeKeys":213}],207:[function(e,t,r){t.exports=function(e,t){for(var r=-1,n=Array(e);++r-1&&e%1==0&&e-1&&e%1==0&&e<=n}},{}],225:[function(e,t,r){t.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}},{}],226:[function(e,t,r){t.exports=function(e){return null!=e&&"object"==typeof e}},{}],227:[function(e,t,r){var n=e("./_baseIsTypedArray"),i=e("./_baseUnary"),o=e("./_nodeUtil"),a=o&&o.isTypedArray,s=a?i(a):n;t.exports=s},{"./_baseIsTypedArray":205,"./_baseUnary":208,"./_nodeUtil":214}],228:[function(e,t,r){var n=e("./_arrayLikeKeys"),i=e("./_baseKeys"),o=e("./isArrayLike");t.exports=function(e){return o(e)?n(e):i(e)}},{"./_arrayLikeKeys":202,"./_baseKeys":206,"./isArrayLike":221}],229:[function(e,t,r){t.exports=function(){}},{}],230:[function(e,t,r){t.exports=function(){return!1}},{}],231:[function(e,t,r){(function(r){"use strict";var n=e("inherits"),i=e("hash-base"),o=new Array(16);function a(){i.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}function s(e,t){return e<>>32-t}function u(e,t,r,n,i,o,a){return s(e+(t&r|~t&n)+i+o|0,a)+t|0}function c(e,t,r,n,i,o,a){return s(e+(t&n|r&~n)+i+o|0,a)+t|0}function f(e,t,r,n,i,o,a){return s(e+(t^r^n)+i+o|0,a)+t|0}function h(e,t,r,n,i,o,a){return s(e+(r^(t|~n))+i+o|0,a)+t|0}n(a,i),a.prototype._update=function(){for(var e=o,t=0;t<16;++t)e[t]=this._block.readInt32LE(4*t);var r=this._a,n=this._b,i=this._c,a=this._d;n=h(n=h(n=h(n=h(n=f(n=f(n=f(n=f(n=c(n=c(n=c(n=c(n=u(n=u(n=u(n=u(n,i=u(i,a=u(a,r=u(r,n,i,a,e[0],3614090360,7),n,i,e[1],3905402710,12),r,n,e[2],606105819,17),a,r,e[3],3250441966,22),i=u(i,a=u(a,r=u(r,n,i,a,e[4],4118548399,7),n,i,e[5],1200080426,12),r,n,e[6],2821735955,17),a,r,e[7],4249261313,22),i=u(i,a=u(a,r=u(r,n,i,a,e[8],1770035416,7),n,i,e[9],2336552879,12),r,n,e[10],4294925233,17),a,r,e[11],2304563134,22),i=u(i,a=u(a,r=u(r,n,i,a,e[12],1804603682,7),n,i,e[13],4254626195,12),r,n,e[14],2792965006,17),a,r,e[15],1236535329,22),i=c(i,a=c(a,r=c(r,n,i,a,e[1],4129170786,5),n,i,e[6],3225465664,9),r,n,e[11],643717713,14),a,r,e[0],3921069994,20),i=c(i,a=c(a,r=c(r,n,i,a,e[5],3593408605,5),n,i,e[10],38016083,9),r,n,e[15],3634488961,14),a,r,e[4],3889429448,20),i=c(i,a=c(a,r=c(r,n,i,a,e[9],568446438,5),n,i,e[14],3275163606,9),r,n,e[3],4107603335,14),a,r,e[8],1163531501,20),i=c(i,a=c(a,r=c(r,n,i,a,e[13],2850285829,5),n,i,e[2],4243563512,9),r,n,e[7],1735328473,14),a,r,e[12],2368359562,20),i=f(i,a=f(a,r=f(r,n,i,a,e[5],4294588738,4),n,i,e[8],2272392833,11),r,n,e[11],1839030562,16),a,r,e[14],4259657740,23),i=f(i,a=f(a,r=f(r,n,i,a,e[1],2763975236,4),n,i,e[4],1272893353,11),r,n,e[7],4139469664,16),a,r,e[10],3200236656,23),i=f(i,a=f(a,r=f(r,n,i,a,e[13],681279174,4),n,i,e[0],3936430074,11),r,n,e[3],3572445317,16),a,r,e[6],76029189,23),i=f(i,a=f(a,r=f(r,n,i,a,e[9],3654602809,4),n,i,e[12],3873151461,11),r,n,e[15],530742520,16),a,r,e[2],3299628645,23),i=h(i,a=h(a,r=h(r,n,i,a,e[0],4096336452,6),n,i,e[7],1126891415,10),r,n,e[14],2878612391,15),a,r,e[5],4237533241,21),i=h(i,a=h(a,r=h(r,n,i,a,e[12],1700485571,6),n,i,e[3],2399980690,10),r,n,e[10],4293915773,15),a,r,e[1],2240044497,21),i=h(i,a=h(a,r=h(r,n,i,a,e[8],1873313359,6),n,i,e[15],4264355552,10),r,n,e[6],2734768916,15),a,r,e[13],1309151649,21),i=h(i,a=h(a,r=h(r,n,i,a,e[4],4149444226,6),n,i,e[11],3174756917,10),r,n,e[2],718787259,15),a,r,e[9],3951481745,21),this._a=this._a+r|0,this._b=this._b+n|0,this._c=this._c+i|0,this._d=this._d+a|0},a.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=new r(16);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e},t.exports=a}).call(this,e("buffer").Buffer)},{buffer:84,"hash-base":232,inherits:180}],232:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("stream").Transform;function o(e){i.call(this),this._block=n.allocUnsafe(e),this._blockSize=e,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}e("inherits")(o,i),o.prototype._transform=function(e,t,r){var n=null;try{this.update(e,t)}catch(e){n=e}r(n)},o.prototype._flush=function(e){var t=null;try{this.push(this.digest())}catch(e){t=e}e(t)},o.prototype.update=function(e,t){if(function(e,t){if(!n.isBuffer(e)&&"string"!=typeof e)throw new TypeError(t+" must be a string or a buffer")}(e,"Data"),this._finalized)throw new Error("Digest already called");n.isBuffer(e)||(e=n.from(e,t));for(var r=this._block,i=0;this._blockOffset+e.length-i>=this._blockSize;){for(var o=this._blockOffset;o0;++a)this._length[a]+=s,(s=this._length[a]/4294967296|0)>0&&(this._length[a]-=4294967296*s);return this},o.prototype._update=function(){throw new Error("_update is not implemented")},o.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();void 0!==e&&(t=t.toString(e)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return t},o.prototype._digest=function(){throw new Error("_digest is not implemented")},t.exports=o},{inherits:180,"safe-buffer":290,stream:311}],233:[function(e,t,r){var n=e("bn.js"),i=e("brorand");function o(e){this.rand=e||new i.Rand}t.exports=o,o.create=function(e){return new o(e)},o.prototype._randbelow=function(e){var t=e.bitLength(),r=Math.ceil(t/8);do{var i=new n(this.rand.generate(r))}while(i.cmp(e)>=0);return i},o.prototype._randrange=function(e,t){var r=t.sub(e);return e.add(this._randbelow(r))},o.prototype.test=function(e,t,r){var i=e.bitLength(),o=n.mont(e),a=new n(1).toRed(o);t||(t=Math.max(1,i/48|0));for(var s=e.subn(1),u=0;!s.testn(u);u++);for(var c=e.shrn(u),f=s.toRed(o);t>0;t--){var h=this._randrange(new n(2),s);r&&r(h);var l=h.toRed(o).redPow(c);if(0!==l.cmp(a)&&0!==l.cmp(f)){for(var d=1;d0;t--){var f=this._randrange(new n(2),a),h=e.gcd(f);if(0!==h.cmpn(1))return h;var l=f.toRed(i).redPow(u);if(0!==l.cmp(o)&&0!==l.cmp(c)){for(var d=1;d>8,a=255&i;o?r.push(o,a):r.push(a)}return r},n.zero2=i,n.toHex=o,n.encode=function(e,t){return"hex"===t?o(e):e}},{}],236:[function(e,t,r){arguments[4][154][0].apply(r,arguments)},{dup:154}],237:[function(e,t,r){var n=e("bn.js"),i=e("strip-hex-prefix");t.exports=function(e){if("string"==typeof e||"number"==typeof e){var t=new n(1),r=String(e).toLowerCase().trim(),o="0x"===r.substr(0,2)||"-0x"===r.substr(0,3),a=i(r);if("-"===a.substr(0,1)&&(a=i(a.slice(1)),t=new n(-1,10)),!(a=""===a?"0":a).match(/^-?[0-9]+$/)&&a.match(/^[0-9A-Fa-f]+$/)||a.match(/^[a-fA-F]+$/)||!0===o&&a.match(/^[0-9A-Fa-f]+$/))return new n(a,16).mul(t);if((a.match(/^-?[0-9]+$/)||""===a)&&!1===o)return new n(a,10).mul(t)}else if("object"==typeof e&&e.toString&&!e.pop&&!e.push&&e.toString(10).match(/^-?[0-9]+$/)&&(e.mul||e.dividedToIntegerBy))return new n(e.toString(10),10);throw new Error("[number-to-bn] while converting number "+JSON.stringify(e)+" 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(e,t,r){"use strict";var n=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable;t.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},r=0;r<10;r++)t["_"+String.fromCharCode(r)]=r;if("0123456789"!==Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(""))return!1;var n={};return"abcdefghijklmnopqrst".split("").forEach(function(e){n[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},n)).join("")}catch(e){return!1}}()?Object.assign:function(e,t){for(var r,a,s=function(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}(e),u=1;u0;)if(q+=r,r=e.charAt(o++),4===H?(N+=String.fromCharCode(parseInt(q,16)),H=0,c=o-1):H++,!r)break e;if('"'===r&&!L){D=F.pop()||p,N+=e.substring(c,o-1);break}if(!("\\"!==r||L||(L=!0,N+=e.substring(c,o-1),r=e.charAt(o++))))break;if(L){if(L=!1,"n"===r?N+="\n":"r"===r?N+="\r":"t"===r?N+="\t":"f"===r?N+="\f":"b"===r?N+="\b":"u"===r?(H=1,q=""):N+=r,r=e.charAt(o++),c=o-1,r)continue;break}h.lastIndex=o;var l=h.exec(e);if(!l){o=e.length+1,N+=e.substring(c,o-1);break}if(o=l.index+1,!(r=e.charAt(l.index))){N+=e.substring(c,o-1);break}}continue;case A:if(!r)continue;if("r"!==r)return W("Invalid true started with t"+r);D=E;continue;case E:if(!r)continue;if("u"!==r)return W("Invalid true started with tr"+r);D=x;continue;case x:if(!r)continue;if("e"!==r)return W("Invalid true started with tru"+r);a(!0),u(),D=F.pop()||p;continue;case k:if(!r)continue;if("a"!==r)return W("Invalid false started with f"+r);D=S;continue;case S:if(!r)continue;if("l"!==r)return W("Invalid false started with fa"+r);D=M;continue;case M:if(!r)continue;if("s"!==r)return W("Invalid false started with fal"+r);D=I;continue;case I:if(!r)continue;if("e"!==r)return W("Invalid false started with fals"+r);a(!1),u(),D=F.pop()||p;continue;case T:if(!r)continue;if("u"!==r)return W("Invalid null started with n"+r);D=U;continue;case U:if(!r)continue;if("l"!==r)return W("Invalid null started with nu"+r);D=j;continue;case j:if(!r)continue;if("l"!==r)return W("Invalid null started with nul"+r);a(null),u(),D=F.pop()||p;continue;case B:if("."!==r)return W("Leading zero not followed by .");R+=r,D=P;continue;case P:if(-1!=="0123456789".indexOf(r))R+=r;else if("."===r){if(-1!==R.indexOf("."))return W("Invalid number has two dots");R+=r}else if("e"===r||"E"===r){if(-1!==R.indexOf("e")||-1!==R.indexOf("E"))return W("Invalid number has two exponential");R+=r}else if("+"===r||"-"===r){if("e"!==n&&"E"!==n)return W("Invalid symbol in number");R+=r}else R&&(a(parseFloat(R)),u(),R=""),o--,D=F.pop()||p;continue;default:return W("Unknown state: "+D)}K>=C&&(X=0,N!==s&&N.length>f&&(W("Max buffer length exceeded: textNode"),X=Math.max(X,N.length)),R.length>f&&(W("Max buffer length exceeded: numberNode"),X=Math.max(X,R.length)),C=f-X+K);var X}),e(ce).on(function(){if(D==d)return a({}),u(),void(O=!0);D===p&&0===z||W("Unexpected end");N!==s&&(a(N),u(),N=s);O=!0})}var C,N,R,L,O,D,F,q,H,z,K,V=(C=d(function(e){return e.unshift(/^/),(t=RegExp(e.map(f("source")).join(""))).exec.bind(t);var t}),L=C(N=/(\$?)/,/([\w-_]+|\*)/,R=/(?:{([\w ]*?)})?/),O=C(N,/\["([^"]+)"\]/,R),D=C(N,/\[(\d+|\*)\]/,R),F=C(N,/()/,/{([\w ]*?)}/),q=C(/\.\./),H=C(/\./),z=C(N,/!/),K=C(/$/),function(e){return e(h(L,O,D,F),q,H,z,K)});function G(e,t){return{key:e,node:t}}var W=f("key"),Y=f("node"),X={};function Z(e){var t=e(ee).emit,r=e(te).emit,n=e(ae).emit,o=e(oe).emit;function a(e,t,r){Y(x(e))[t]=r}function s(e,r,n){e&&a(e,r,n);var i=A(G(r,n),e);return t(i),i}var u={};return u[le]=function(e,t){if(!e)return n(t),s(e,X,t);var r=function(e,t){var r=Y(x(e));return m(i,r)?s(e,v(r),t):e}(e,t),o=k(r),u=W(x(r));return a(o,u,t),A(G(u,t),o)},u[de]=function(e){return r(e),k(e)||o(Y(x(e)))},u[he]=s,u}var J=V(function(e,t,r,n,i){var a=1,s=2,f=3,l=c(W,x),d=c(Y,x);function b(e,t){return!!t[a]?p(e,x):e}function m(e){if(e==y)return y;return p(function(e){return l(e)!=X},c(e,k))}function g(){return function(e){return l(e)==X}}function w(e,t,r,n,i){var o=e(r);if(o){var a=function(e,t,r){return U(function(e,t){return t(e,r)},t,e)}(t,n,o);return i(r.substr(v(o[0])),a)}}function A(e,t){return u(w,e,t)}var E=h(A(e,M(b,function(e,t){var r=t[f];return r?p(c(u(_,S(r.split(/\W+/))),d),e):e},function(e,t){var r=t[s];return p(r&&"*"!=r?function(e){return l(e)==r}:y,e)},m)),A(t,M(function(e){if(e==y)return y;var t=g(),r=e,n=m(function(e){return i(e)}),i=h(t,r,n);return i})),A(r,M()),A(n,M(b,g)),A(i,M(function(e){return function(t){var r=e(t);return!0===r?x(t):r}})),function(e){throw o('"'+e+'" could not be tokenised')});function I(e,t){return t}function T(e,t){return E(e,t,e?T:I)}return function(e){try{return T(e,y)}catch(t){throw o('Could not compile "'+e+'" because '+t.message)}}});function $(e,t,r){var n,i;function o(e){return function(t){return t.id==e}}return{on:function(r,o){var a={listener:r,id:o||r};return t&&t.emit(e,r,a.id),n=A(a,n),i=A(r,i),this},emit:function(){!function e(t,r){t&&(x(t).apply(null,r),e(k(t),r))}(i,arguments)},un:function(t){var a;n=j(n,o(t),function(e){a=e}),a&&(i=j(i,function(e){return e==a.listener}),r&&r.emit(e,a.listener,a.id))},listeners:function(){return i},hasListener:function(e){return w(function e(t,r){return r&&(t(x(r))?x(r):e(t,k(r)))}(e?o(e):y,n))}}}var Q=1,ee=Q++,te=Q++,re=Q++,ne=Q++,ie="fail",oe=Q++,ae=Q++,se="start",ue="data",ce="end",fe=Q++,he=Q++,le=Q++,de=Q++;function pe(e,t,r){try{var n=a.parse(t)}catch(e){}return{statusCode:e,body:t,jsonBody:n,thrown:r}}function be(e,t){var r={node:e(te),path:e(ee)};function n(t,r,n){var i=e(t).emit;r.on(function(e){var t=n(e);!1!==t&&function(e,t,r){var n=B(r);e(t,I(k(T(W,n))),I(T(Y,n)))}(i,Y(t),e)},t),e("removeListener").on(function(n){n==t&&(e(n).listeners()||r.un(t))})}e("newListener").on(function(e){var i=/(node|path):(.*)/.exec(e);if(i){var o=r[i[1]];o.hasListener(e)||n(e,o,t(i[2]))}})}function ye(e,t){var r,n=/^(node|path):./,i=e(oe),o=e(ne).emit,a=e(re).emit,s=d(function(t,i){if(r[t])l(i,r[t]);else{var o=e(t),a=i[0];n.test(t)?c(o,a):o.on(a)}return r});function c(e,t,n){n=n||t;var i=f(t);return e.on(function(){var t=!1;r.forget=function(){t=!0},l(arguments,i),delete r.forget,t&&e.un(n)},n),r}function f(e){return function(){try{return e.apply(r,arguments)}catch(e){setTimeout(function(){throw e})}}}function h(t,r,n){var i;i="node"==t?function(e){return function(){var t=e.apply(this,arguments);w(t)&&(t==ge.drop?o():a(t))}}(n):n,c(function(t,r){return e(t+":"+r)}(t,r),i,n)}function p(e,t,n){return g(t)?h(e,t,n):function(e,t){for(var r in t)h(e,r,t[r])}(e,t),r}return e(ae).on(function(e){var t;r.root=(t=e,function(){return t})}),e(se).on(function(e,t){r.header=function(e){return e?t[e]:t}}),r={on:s,addListener:s,removeListener:function(t,n,o){if("done"==t)i.un(n);else if("node"==t||"path"==t)e.un(t+":"+n,o);else{var a=n;e(t).un(a)}return r},emit:e.emit,node:u(p,"node"),path:u(p,"path"),done:u(c,i),start:u(function(t,n){return e(t).on(f(n),n),r},se),fail:e(ie).on,abort:e(fe).emit,header:b,root:b,source:t}}function me(t,r,n,i,o){var a=function(){var e={},t=n("newListener"),r=n("removeListener");function n(n){return e[n]=$(n,t,r)}function i(t){return e[t]||n(t)}return["emit","on","un"].forEach(function(e){i[e]=d(function(t,r){l(r,i(t)[e])})}),i}();return r&&function(t,r,n,i,o,a,c){"use strict";var f=t(ue).emit,h=t(ie).emit,l=0,d=!0;function p(){var e=r.responseText,t=e.substr(l);t&&f(t),l=v(e)}t(fe).on(function(){r.onreadystatechange=null,r.abort()}),"onprogress"in r&&(r.onprogress=p),r.onreadystatechange=function(){function e(){try{d&&t(se).emit(r.status,(e=r.getAllResponseHeaders(),n={},e&&e.split("\r\n").forEach(function(e){var t=e.indexOf(": ");n[e.substring(0,t)]=e.substring(t+2)}),n)),d=!1}catch(e){}var e,n}switch(r.readyState){case 2:case 3:return e();case 4:e(),2==String(r.status)[0]?(p(),t(ce).emit()):h(pe(r.status,r.responseText))}};try{for(var b in r.open(n,i,!0),a)r.setRequestHeader(b,a[b]);(function(e,t){function r(t){return t.port||{"http:":80,"https:":443}[t.protocol||e.protocol]}return!!(t.protocol&&t.protocol!=e.protocol||t.host&&t.host!=e.host||t.host&&r(t)!=r(e))})(e.location,function(e){var t=/(\w+:)?(?:\/\/)([\w.-]+)?(?::(\d+))?\/?/.exec(e)||[];return{protocol:t[1]||"",host:t[2]||"",port:t[3]||""}}(i))||r.setRequestHeader("X-Requested-With","XMLHttpRequest"),r.withCredentials=c,r.send(o)}catch(t){e.setTimeout(u(h,pe(s,s,t)),0)}}(a,new XMLHttpRequest,t,r,n,i,o),P(a),function(e,t){"use strict";var r,n={};function i(e){return function(t){r=e(r,t)}}for(var o in t)e(o).on(i(t[o]),n);e(re).on(function(e){var t=x(r),n=W(t),i=k(r);i&&(Y(x(i))[n]=e)}),e(ne).on(function(){var e=x(r),t=W(e),n=k(r);n&&delete Y(x(n))[t]}),e(fe).on(function(){for(var r in t)e(r).un(n)})}(a,Z(a)),be(a,J),ye(a,r)}function ve(e,t,r,n,i,o,s){return i=i?a.parse(a.stringify(i)):{},n?g(n)||(n=a.stringify(n),i["Content-Type"]=i["Content-Type"]||"application/json"):n=null,e(r||"GET",function(e,t){return!1===t&&(-1==e.indexOf("?")?e+="?":e+="&",e+="_="+(new Date).getTime()),e}(t,s),n,i,o||!1)}function ge(e){var t=M("resume","pause","pipe"),r=u(_,t);return e?r(e)||g(e)?ve(me,e):ve(me,e.url,e.method,e.body,e.headers,e.withCredentials,e.cached):me()}ge.drop=function(){return ge.drop},"function"==typeof define&&define.amd?define("oboe",[],function(){return ge}):"object"==typeof r?t.exports=ge:e.oboe=ge}(function(){try{return window}catch(e){return self}}(),Object,Array,Error,JSON)},{}],240:[function(e,t,r){r.endianness=function(){return"LE"},r.hostname=function(){return"undefined"!=typeof location?location.hostname:""},r.loadavg=function(){return[]},r.uptime=function(){return 0},r.freemem=function(){return Number.MAX_VALUE},r.totalmem=function(){return Number.MAX_VALUE},r.cpus=function(){return[]},r.type=function(){return"Browser"},r.release=function(){return"undefined"!=typeof navigator?navigator.appVersion:""},r.networkInterfaces=r.getNetworkInterfaces=function(){return{}},r.arch=function(){return"javascript"},r.platform=function(){return"browser"},r.tmpdir=r.tmpDir=function(){return"/tmp"},r.EOL="\n",r.homedir=function(){return"/"}},{}],241:[function(e,t,r){t.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","2.16.840.1.101.3.4.1.3":"aes-128-ofb","2.16.840.1.101.3.4.1.4":"aes-128-cfb","2.16.840.1.101.3.4.1.21":"aes-192-ecb","2.16.840.1.101.3.4.1.22":"aes-192-cbc","2.16.840.1.101.3.4.1.23":"aes-192-ofb","2.16.840.1.101.3.4.1.24":"aes-192-cfb","2.16.840.1.101.3.4.1.41":"aes-256-ecb","2.16.840.1.101.3.4.1.42":"aes-256-cbc","2.16.840.1.101.3.4.1.43":"aes-256-ofb","2.16.840.1.101.3.4.1.44":"aes-256-cfb"}},{}],242:[function(e,t,r){"use strict";var n=e("asn1.js");r.certificate=e("./certificate");var i=n.define("RSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("modulus").int(),this.key("publicExponent").int(),this.key("privateExponent").int(),this.key("prime1").int(),this.key("prime2").int(),this.key("exponent1").int(),this.key("exponent2").int(),this.key("coefficient").int())});r.RSAPrivateKey=i;var o=n.define("RSAPublicKey",function(){this.seq().obj(this.key("modulus").int(),this.key("publicExponent").int())});r.RSAPublicKey=o;var a=n.define("SubjectPublicKeyInfo",function(){this.seq().obj(this.key("algorithm").use(s),this.key("subjectPublicKey").bitstr())});r.PublicKey=a;var s=n.define("AlgorithmIdentifier",function(){this.seq().obj(this.key("algorithm").objid(),this.key("none").null_().optional(),this.key("curve").objid().optional(),this.key("params").seq().obj(this.key("p").int(),this.key("q").int(),this.key("g").int()).optional())}),u=n.define("PrivateKeyInfo",function(){this.seq().obj(this.key("version").int(),this.key("algorithm").use(s),this.key("subjectPrivateKey").octstr())});r.PrivateKey=u;var c=n.define("EncryptedPrivateKeyInfo",function(){this.seq().obj(this.key("algorithm").seq().obj(this.key("id").objid(),this.key("decrypt").seq().obj(this.key("kde").seq().obj(this.key("id").objid(),this.key("kdeparams").seq().obj(this.key("salt").octstr(),this.key("iters").int())),this.key("cipher").seq().obj(this.key("algo").objid(),this.key("iv").octstr()))),this.key("subjectPrivateKey").octstr())});r.EncryptedPrivateKey=c;var f=n.define("DSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("p").int(),this.key("q").int(),this.key("g").int(),this.key("pub_key").int(),this.key("priv_key").int())});r.DSAPrivateKey=f,r.DSAparam=n.define("DSAparam",function(){this.int()});var h=n.define("ECPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").optional().explicit(0).use(l),this.key("publicKey").optional().explicit(1).bitstr())});r.ECPrivateKey=h;var l=n.define("ECParameters",function(){this.choice({namedCurve:this.objid()})});r.signature=n.define("signature",function(){this.seq().obj(this.key("r").int(),this.key("s").int())})},{"./certificate":243,"asn1.js":5}],243:[function(e,t,r){"use strict";var n=e("asn1.js"),i=n.define("Time",function(){this.choice({utcTime:this.utctime(),generalTime:this.gentime()})}),o=n.define("AttributeTypeValue",function(){this.seq().obj(this.key("type").objid(),this.key("value").any())}),a=n.define("AlgorithmIdentifier",function(){this.seq().obj(this.key("algorithm").objid(),this.key("parameters").optional())}),s=n.define("SubjectPublicKeyInfo",function(){this.seq().obj(this.key("algorithm").use(a),this.key("subjectPublicKey").bitstr())}),u=n.define("RelativeDistinguishedName",function(){this.setof(o)}),c=n.define("RDNSequence",function(){this.seqof(u)}),f=n.define("Name",function(){this.choice({rdnSequence:this.use(c)})}),h=n.define("Validity",function(){this.seq().obj(this.key("notBefore").use(i),this.key("notAfter").use(i))}),l=n.define("Extension",function(){this.seq().obj(this.key("extnID").objid(),this.key("critical").bool().def(!1),this.key("extnValue").octstr())}),d=n.define("TBSCertificate",function(){this.seq().obj(this.key("version").explicit(0).int(),this.key("serialNumber").int(),this.key("signature").use(a),this.key("issuer").use(f),this.key("validity").use(h),this.key("subject").use(f),this.key("subjectPublicKeyInfo").use(s),this.key("issuerUniqueID").implicit(1).bitstr().optional(),this.key("subjectUniqueID").implicit(2).bitstr().optional(),this.key("extensions").explicit(3).seqof(l).optional())}),p=n.define("X509Certificate",function(){this.seq().obj(this.key("tbsCertificate").use(d),this.key("signatureAlgorithm").use(a),this.key("signatureValue").bitstr())});t.exports=p},{"asn1.js":5}],244:[function(e,t,r){(function(r){var n=/Proc-Type: 4,ENCRYPTED\n\r?DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)\n\r?\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?/m,i=/^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----\n/m,o=/^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?-----END \1-----$/m,a=e("evp_bytestokey"),s=e("browserify-aes");t.exports=function(e,t){var u,c=e.toString(),f=c.match(n);if(f){var h="aes"+f[1],l=new r(f[2],"hex"),d=new r(f[3].replace(/\r?\n/g,""),"base64"),p=a(t,l.slice(0,8),parseInt(f[1],10)).key,b=[],y=s.createDecipheriv(h,p,l);b.push(y.update(d)),b.push(y.final()),u=r.concat(b)}else{var m=c.match(o);u=new r(m[2].replace(/\r?\n/g,""),"base64")}return{tag:c.match(i)[1],data:u}}}).call(this,e("buffer").Buffer)},{"browserify-aes":58,buffer:84,evp_bytestokey:158}],245:[function(e,t,r){(function(r){var n=e("./asn1"),i=e("./aesid.json"),o=e("./fixProc"),a=e("browserify-aes"),s=e("pbkdf2");function u(e){var t;"object"!=typeof e||r.isBuffer(e)||(t=e.passphrase,e=e.key),"string"==typeof e&&(e=new r(e));var u,c,f=o(e,t),h=f.tag,l=f.data;switch(h){case"CERTIFICATE":c=n.certificate.decode(l,"der").tbsCertificate.subjectPublicKeyInfo;case"PUBLIC KEY":switch(c||(c=n.PublicKey.decode(l,"der")),u=c.algorithm.algorithm.join(".")){case"1.2.840.113549.1.1.1":return n.RSAPublicKey.decode(c.subjectPublicKey.data,"der");case"1.2.840.10045.2.1":return c.subjectPrivateKey=c.subjectPublicKey,{type:"ec",data:c};case"1.2.840.10040.4.1":return c.algorithm.params.pub_key=n.DSAparam.decode(c.subjectPublicKey.data,"der"),{type:"dsa",data:c.algorithm.params};default:throw new Error("unknown key id "+u)}throw new Error("unknown key type "+h);case"ENCRYPTED PRIVATE KEY":l=function(e,t){var n=e.algorithm.decrypt.kde.kdeparams.salt,o=parseInt(e.algorithm.decrypt.kde.kdeparams.iters.toString(),10),u=i[e.algorithm.decrypt.cipher.algo.join(".")],c=e.algorithm.decrypt.cipher.iv,f=e.subjectPrivateKey,h=parseInt(u.split("-")[1],10)/8,l=s.pbkdf2Sync(t,n,o,h),d=a.createDecipheriv(u,l,c),p=[];return p.push(d.update(f)),p.push(d.final()),r.concat(p)}(l=n.EncryptedPrivateKey.decode(l,"der"),t);case"PRIVATE KEY":switch(u=(c=n.PrivateKey.decode(l,"der")).algorithm.algorithm.join(".")){case"1.2.840.113549.1.1.1":return n.RSAPrivateKey.decode(c.subjectPrivateKey,"der");case"1.2.840.10045.2.1":return{curve:c.algorithm.curve,privateKey:n.ECPrivateKey.decode(c.subjectPrivateKey,"der").privateKey};case"1.2.840.10040.4.1":return c.algorithm.params.priv_key=n.DSAparam.decode(c.subjectPrivateKey,"der"),{type:"dsa",params:c.algorithm.params};default:throw new Error("unknown key id "+u)}throw new Error("unknown key type "+h);case"RSA PUBLIC KEY":return n.RSAPublicKey.decode(l,"der");case"RSA PRIVATE KEY":return n.RSAPrivateKey.decode(l,"der");case"DSA PRIVATE KEY":return{type:"dsa",params:n.DSAPrivateKey.decode(l,"der")};case"EC PRIVATE KEY":return{curve:(l=n.ECPrivateKey.decode(l,"der")).parameters.value,privateKey:l.privateKey};default:throw new Error("unknown key type "+h)}}t.exports=u,u.signature=n.signature}).call(this,e("buffer").Buffer)},{"./aesid.json":241,"./asn1":242,"./fixProc":244,"browserify-aes":58,buffer:84,pbkdf2:247}],246:[function(e,t,r){var n=e("trim"),i=e("for-each");t.exports=function(e){if(!e)return{};var t={};return i(n(e).split("\n"),function(e){var r,i=e.indexOf(":"),o=n(e.slice(0,i)).toLowerCase(),a=n(e.slice(i+1));void 0===t[o]?t[o]=a:(r=t[o],"[object Array]"===Object.prototype.toString.call(r)?t[o].push(a):t[o]=[t[o],a])}),t}},{"for-each":159,trim:324}],247:[function(e,t,r){r.pbkdf2=e("./lib/async"),r.pbkdf2Sync=e("./lib/sync")},{"./lib/async":248,"./lib/sync":251}],248:[function(e,t,r){(function(r,n){var i,o=e("./precondition"),a=e("./default-encoding"),s=e("./sync"),u=e("safe-buffer").Buffer,c=n.crypto&&n.crypto.subtle,f={sha:"SHA-1","sha-1":"SHA-1",sha1:"SHA-1",sha256:"SHA-256","sha-256":"SHA-256",sha384:"SHA-384","sha-384":"SHA-384","sha-512":"SHA-512",sha512:"SHA-512"},h=[];function l(e,t,r,n,i){return c.importKey("raw",e,{name:"PBKDF2"},!1,["deriveBits"]).then(function(e){return c.deriveBits({name:"PBKDF2",salt:t,iterations:r,hash:{name:i}},e,n<<3)}).then(function(e){return u.from(e)})}t.exports=function(e,t,d,p,b,y){if(u.isBuffer(e)||(e=u.from(e,a)),u.isBuffer(t)||(t=u.from(t,a)),o(d,p),"function"==typeof b&&(y=b,b=void 0),"function"!=typeof y)throw new Error("No callback provided to pbkdf2");var m=f[(b=b||"sha1").toLowerCase()];if(!m||"function"!=typeof n.Promise)return r.nextTick(function(){var r;try{r=s(e,t,d,p,b)}catch(e){return y(e)}y(null,r)});!function(e,t){e.then(function(e){r.nextTick(function(){t(null,e)})},function(e){r.nextTick(function(){t(e)})})}(function(e){if(n.process&&!n.process.browser)return Promise.resolve(!1);if(!c||!c.importKey||!c.deriveBits)return Promise.resolve(!1);if(void 0!==h[e])return h[e];var t=l(i=i||u.alloc(8),i,10,128,e).then(function(){return!0}).catch(function(){return!1});return h[e]=t,t}(m).then(function(r){return r?l(e,t,d,p,m):s(e,t,d,p,b)}),y)}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./default-encoding":249,"./precondition":250,"./sync":251,_process:257,"safe-buffer":290}],249:[function(e,t,r){(function(e){var r;e.browser?r="utf-8":r=parseInt(e.version.split(".")[0].slice(1),10)>=6?"utf-8":"binary";t.exports=r}).call(this,e("_process"))},{_process:257}],250:[function(e,t,r){var n=Math.pow(2,30)-1;t.exports=function(e,t){if("number"!=typeof e)throw new TypeError("Iterations not a number");if(e<0)throw new TypeError("Bad iterations");if("number"!=typeof t)throw new TypeError("Key length not a number");if(t<0||t>n||t!=t)throw new TypeError("Bad key length")}},{}],251:[function(e,t,r){var n=e("create-hash/md5"),i=e("ripemd160"),o=e("sha.js"),a=e("./precondition"),s=e("./default-encoding"),u=e("safe-buffer").Buffer,c=u.alloc(128),f={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,rmd160:20,ripemd160:20};function h(e,t,r){var a=function(e){return"rmd160"===e||"ripemd160"===e?i:"md5"===e?n:function(t){return o(e).update(t).digest()}}(e),s="sha512"===e||"sha384"===e?128:64;t.length>s?t=a(t):t.length1)for(var r=1;rp||new a(t).cmp(d.modulus)>=0)throw new Error("decryption error");l=f?c(new a(t),d):s(t,d);var b=new r(p-l.length);if(b.fill(0),l=r.concat([b,l],p),4===h)return function(e,t){e.modulus;var n=e.modulus.byteLength(),a=(t.length,u("sha1").update(new r("")).digest()),s=a.length;if(0!==t[0])throw new Error("decryption error");var c=t.slice(1,s+1),f=t.slice(s+1),h=o(c,i(f,s)),l=o(f,i(h,n-s-1));if(function(e,t){e=new r(e),t=new r(t);var n=0,i=e.length;e.length!==t.length&&(n++,i=Math.min(e.length,t.length));var o=-1;for(;++o=t.length){o++;break}var a=t.slice(2,i-1);t.slice(i-1,i);("0002"!==n.toString("hex")&&!r||"0001"!==n.toString("hex")&&r)&&o++;a.length<8&&o++;if(o)throw new Error("decryption error");return t.slice(i)}(0,l,f);if(3===h)return l;throw new Error("unknown padding")}}).call(this,e("buffer").Buffer)},{"./mgf":260,"./withPublic":263,"./xor":264,"bn.js":53,"browserify-rsa":76,buffer:84,"create-hash":91,"parse-asn1":245}],262:[function(e,t,r){(function(r){var n=e("parse-asn1"),i=e("randombytes"),o=e("create-hash"),a=e("./mgf"),s=e("./xor"),u=e("bn.js"),c=e("./withPublic"),f=e("browserify-rsa");t.exports=function(e,t,h){var l;l=e.padding?e.padding:h?1:4;var d,p=n(e);if(4===l)d=function(e,t){var n=e.modulus.byteLength(),c=t.length,f=o("sha1").update(new r("")).digest(),h=f.length,l=2*h;if(c>n-l-2)throw new Error("message too long");var d=new r(n-c-l-2);d.fill(0);var p=n-h-1,b=i(h),y=s(r.concat([f,d,new r([1]),t],p),a(b,p)),m=s(b,a(y,h));return new u(r.concat([new r([0]),m,y],n))}(p,t);else if(1===l)d=function(e,t,n){var o,a=t.length,s=e.modulus.byteLength();if(a>s-11)throw new Error("message too long");n?(o=new r(s-a-3)).fill(255):o=function(e,t){var n,o=new r(e),a=0,s=i(2*e),u=0;for(;a=0)throw new Error("data too long for modulus")}return h?f(d,p):c(d,p)}}).call(this,e("buffer").Buffer)},{"./mgf":260,"./withPublic":263,"./xor":264,"bn.js":53,"browserify-rsa":76,buffer:84,"create-hash":91,"parse-asn1":245,randombytes:270}],263:[function(e,t,r){(function(r){var n=e("bn.js");t.exports=function(e,t){return new r(e.toRed(n.mont(t.modulus)).redPow(new n(t.publicExponent)).fromRed().toArray())}}).call(this,e("buffer").Buffer)},{"bn.js":53,buffer:84}],264:[function(e,t,r){t.exports=function(e,t){for(var r=e.length,n=-1;++n= 0x80 (not a basic code point)","invalid-input":"Invalid input"},A=f-h,E=Math.floor,x=String.fromCharCode;function k(e){throw new RangeError(_[e])}function S(e,t){for(var r=e.length,n=[];r--;)n[r]=t(e[r]);return n}function M(e,t){var r=e.split("@"),n="";return r.length>1&&(n=r[0]+"@",e=r[1]),n+S((e=e.replace(w,".")).split("."),t).join(".")}function I(e){for(var t,r,n=[],i=0,o=e.length;i=55296&&t<=56319&&i65535&&(t+=x((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=x(e)}).join("")}function U(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function j(e,t,r){var n=0;for(e=r?E(e/p):e>>1,e+=E(e/t);e>A*l>>1;n+=f)e=E(e/A);return E(n+(A+1)*e/(e+d))}function B(e){var t,r,n,i,o,a,s,u,d,p,v,g=[],w=e.length,_=0,A=y,x=b;for((r=e.lastIndexOf(m))<0&&(r=0),n=0;n=128&&k("not-basic"),g.push(e.charCodeAt(n));for(i=r>0?r+1:0;i=w&&k("invalid-input"),((u=(v=e.charCodeAt(i++))-48<10?v-22:v-65<26?v-65:v-97<26?v-97:f)>=f||u>E((c-_)/a))&&k("overflow"),_+=u*a,!(u<(d=s<=x?h:s>=x+l?l:s-x));s+=f)a>E(c/(p=f-d))&&k("overflow"),a*=p;x=j(_-o,t=g.length+1,0==o),E(_/t)>c-A&&k("overflow"),A+=E(_/t),_%=t,g.splice(_++,0,A)}return T(g)}function P(e){var t,r,n,i,o,a,s,u,d,p,v,g,w,_,A,S=[];for(g=(e=I(e)).length,t=y,r=0,o=b,a=0;a=t&&vE((c-r)/(w=n+1))&&k("overflow"),r+=(s-t)*w,t=s,a=0;ac&&k("overflow"),v==t){for(u=r,d=f;!(u<(p=d<=o?h:d>=o+l?l:d-o));d+=f)A=u-p,_=f-p,S.push(x(U(p+A%_,0))),u=E(A/_);S.push(x(U(u,0))),o=j(r,w,n==i),r=0,++n}++r,++t}return S.join("")}if(s={version:"1.4.1",ucs2:{decode:I,encode:T},decode:B,encode:P,toASCII:function(e){return M(e,function(e){return g.test(e)?"xn--"+P(e):e})},toUnicode:function(e){return M(e,function(e){return v.test(e)?B(e.slice(4).toLowerCase()):e})}},"function"==typeof define&&"object"==typeof define.amd&&define.amd)define("punycode",function(){return s});else if(i&&o)if(t.exports==i)o.exports=s;else for(u in s)s.hasOwnProperty(u)&&(i[u]=s[u]);else n.punycode=s}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],266:[function(e,t,r){"use strict";var n=e("strict-uri-encode"),i=e("object-assign"),o=e("decode-uri-component");function a(e,t){return t.encode?t.strict?n(e):encodeURIComponent(e):e}function s(e){var t=e.indexOf("?");return-1===t?"":e.slice(t+1)}function u(e,t){var r=function(e){var t;switch(e.arrayFormat){case"index":return function(e,r,n){t=/\[(\d*)\]$/.exec(e),e=e.replace(/\[\d*\]$/,""),t?(void 0===n[e]&&(n[e]={}),n[e][t[1]]=r):n[e]=r};case"bracket":return function(e,r,n){t=/(\[\])$/.exec(e),e=e.replace(/\[\]$/,""),t?void 0!==n[e]?n[e]=[].concat(n[e],r):n[e]=[r]:n[e]=r};default:return function(e,t,r){void 0!==r[e]?r[e]=[].concat(r[e],t):r[e]=t}}}(t=i({arrayFormat:"none"},t)),n=Object.create(null);return"string"!=typeof e?n:(e=e.trim().replace(/^[?#&]/,""))?(e.split("&").forEach(function(e){var t=e.replace(/\+/g," ").split("="),i=t.shift(),a=t.length>0?t.join("="):void 0;a=void 0===a?null:o(a),r(o(i),a,n)}),Object.keys(n).sort().reduce(function(e,t){var r=n[t];return Boolean(r)&&"object"==typeof r&&!Array.isArray(r)?e[t]=function e(t){return Array.isArray(t)?t.sort():"object"==typeof t?e(Object.keys(t)).sort(function(e,t){return Number(e)-Number(t)}).map(function(e){return t[e]}):t}(r):e[t]=r,e},Object.create(null))):n}r.extract=s,r.parse=u,r.stringify=function(e,t){!1===(t=i({encode:!0,strict:!0,arrayFormat:"none"},t)).sort&&(t.sort=function(){});var r=function(e){switch(e.arrayFormat){case"index":return function(t,r,n){return null===r?[a(t,e),"[",n,"]"].join(""):[a(t,e),"[",a(n,e),"]=",a(r,e)].join("")};case"bracket":return function(t,r){return null===r?a(t,e):[a(t,e),"[]=",a(r,e)].join("")};default:return function(t,r){return null===r?a(t,e):[a(t,e),"=",a(r,e)].join("")}}}(t);return e?Object.keys(e).sort(t.sort).map(function(n){var i=e[n];if(void 0===i)return"";if(null===i)return a(n,t);if(Array.isArray(i)){var o=[];return i.slice().forEach(function(e){void 0!==e&&o.push(r(n,e,o.length))}),o.join("&")}return a(n,t)+"="+a(i,t)}).filter(function(e){return e.length>0}).join("&"):""},r.parseUrl=function(e,t){return{url:e.split("?")[0]||"",query:u(s(e),t)}}},{"decode-uri-component":98,"object-assign":238,"strict-uri-encode":316}],267:[function(e,t,r){"use strict";function n(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.exports=function(e,t,r,o){t=t||"&",r=r||"=";var a={};if("string"!=typeof e||0===e.length)return a;var s=/\+/g;e=e.split(t);var u=1e3;o&&"number"==typeof o.maxKeys&&(u=o.maxKeys);var c=e.length;u>0&&c>u&&(c=u);for(var f=0;f=0?(h=b.substr(0,y),l=b.substr(y+1)):(h=b,l=""),d=decodeURIComponent(h),p=decodeURIComponent(l),n(a,d)?i(a[d])?a[d].push(p):a[d]=[a[d],p]:a[d]=p}return a};var i=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],268:[function(e,t,r){"use strict";var n=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,r,s){return t=t||"&",r=r||"=",null===e&&(e=void 0),"object"==typeof e?o(a(e),function(a){var s=encodeURIComponent(n(a))+r;return i(e[a])?o(e[a],function(e){return s+encodeURIComponent(n(e))}).join(t):s+encodeURIComponent(n(e[a]))}).join(t):s?encodeURIComponent(n(s))+r+encodeURIComponent(n(e)):""};var i=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function o(e,t){if(e.map)return e.map(t);for(var r=[],n=0;n65536)throw new Error("requested too many random bytes");var a=new n.Uint8Array(e);e>0&&o.getRandomValues(a);var s=i.from(a.buffer);if("function"==typeof t)return r.nextTick(function(){t(null,s)});return s}:t.exports=function(){throw new Error("Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11")}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:257,"safe-buffer":290}],271:[function(e,t,r){(function(t,n){"use strict";function i(){throw new Error("secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11")}var o=e("safe-buffer"),a=e("randombytes"),s=o.Buffer,u=o.kMaxLength,c=n.crypto||n.msCrypto,f=Math.pow(2,32)-1;function h(e,t){if("number"!=typeof e||e!=e)throw new TypeError("offset must be a number");if(e>f||e<0)throw new TypeError("offset must be a uint32");if(e>u||e>t)throw new RangeError("offset out of range")}function l(e,t,r){if("number"!=typeof e||e!=e)throw new TypeError("size must be a number");if(e>f||e<0)throw new TypeError("size must be a uint32");if(e+t>r||e>u)throw new RangeError("buffer too small")}function d(e,r,n,i){if(t.browser){var o=e.buffer,s=new Uint8Array(o,r,n);return c.getRandomValues(s),i?void t.nextTick(function(){i(null,e)}):e}if(!i)return a(n).copy(e,r),e;a(n,function(t,n){if(t)return i(t);n.copy(e,r),i(null,e)})}c&&c.getRandomValues||!t.browser?(r.randomFill=function(e,t,r,i){if(!(s.isBuffer(e)||e instanceof n.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');if("function"==typeof t)i=t,t=0,r=e.length;else if("function"==typeof r)i=r,r=e.length-t;else if("function"!=typeof i)throw new TypeError('"cb" argument must be a function');return h(t,e.length),l(r,t,e.length),d(e,t,r,i)},r.randomFillSync=function(e,t,r){void 0===t&&(t=0);if(!(s.isBuffer(e)||e instanceof n.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');h(t,e.length),void 0===r&&(r=e.length-t);return l(r,t,e.length),d(e,t,r)}):(r.randomFill=i,r.randomFillSync=i)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:257,randombytes:270,"safe-buffer":290}],272:[function(e,t,r){t.exports=window.crypto},{}],273:[function(e,t,r){t.exports=e("crypto")},{crypto:272}],274:[function(e,t,r){t.exports=function(t,r){var n=e("./crypto.js"),i="function"==typeof r;if(t>65536){if(!i)throw new Error("Requested too many random bytes.");r(new Error("Requested too many random bytes."))}if(void 0!==n&&n.randomBytes){if(!i)return"0x"+n.randomBytes(t).toString("hex");n.randomBytes(t,function(e,t){e?r(u):r(null,"0x"+t.toString("hex"))})}else{var o;if(void 0!==n?o=n:"undefined"!=typeof msCrypto&&(o=msCrypto),o&&o.getRandomValues){var a=o.getRandomValues(new Uint8Array(t)),s="0x"+Array.from(a).map(function(e){return e.toString(16)}).join("");if(!i)return s;r(null,s)}else{var u=new Error('No "crypto" object available. This Browser doesn\'t support generating secure random bytes.');if(!i)throw u;r(u)}}}},{"./crypto.js":273}],275:[function(e,t,r){t.exports=e("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":276}],276:[function(e,t,r){"use strict";var n=e("process-nextick-args").nextTick,i=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};t.exports=h;var o=e("core-util-is");o.inherits=e("inherits");var a=e("./_stream_readable"),s=e("./_stream_writable");o.inherits(h,a);for(var u=i(s.prototype),c=0;c0?("string"==typeof t||a.objectMode||Object.getPrototypeOf(t)===c.prototype||(t=function(e){return c.from(e)}(t)),n?a.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):_(e,a,t,!0):a.ended?e.emit("error",new Error("stream.push() after EOF")):(a.reading=!1,a.decoder&&!r?(t=a.decoder.write(t),a.objectMode||0!==t.length?_(e,a,t,!1):S(e,a)):_(e,a,t,!1))):n||(a.reading=!1));return function(e){return!e.ended&&(e.needReadable||e.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=A?e=A:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function x(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(d("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?i(k,e):k(e))}function k(e){d("emit readable"),e.emit("readable"),U(e)}function S(e,t){t.readingMore||(t.readingMore=!0,i(M,e,t))}function M(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):r=function(e,t,r){var n;eo.length?o.length:e;if(a===o.length?i+=o:i+=o.slice(0,e),0===(e-=a)){a===o.length?(++n,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=o.slice(a));break}++n}return t.length-=n,i}(e,t):function(e,t){var r=c.allocUnsafe(e),n=t.head,i=1;n.data.copy(r),e-=n.data.length;for(;n=n.next;){var o=n.data,a=e>o.length?o.length:e;if(o.copy(r,r.length-e,0,a),0===(e-=a)){a===o.length?(++i,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(a));break}++i}return t.length-=i,r}(e,t);return n}(e,t.buffer,t.decoder),r);var r}function B(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,i(P,t,e))}function P(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function C(e,t){for(var r=0,n=e.length;r=t.highWaterMark||t.ended))return d("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?B(this):x(this),null;if(0===(e=E(e,t))&&t.ended)return 0===t.length&&B(this),null;var n,i=t.needReadable;return d("need readable",i),(0===t.length||t.length-e0?j(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&B(this)),null!==n&&this.emit("data",n),n},g.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},g.prototype.pipe=function(e,t){var n=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,d("pipe count=%d opts=%j",o.pipesCount,t);var u=(!t||!1!==t.end)&&e!==r.stdout&&e!==r.stderr?f:g;function c(t,r){d("onunpipe"),t===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,d("cleanup"),e.removeListener("close",m),e.removeListener("finish",v),e.removeListener("drain",h),e.removeListener("error",y),e.removeListener("unpipe",c),n.removeListener("end",f),n.removeListener("end",g),n.removeListener("data",b),l=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||h())}function f(){d("onend"),e.end()}o.endEmitted?i(u):n.once("end",u),e.on("unpipe",c);var h=function(e){return function(){var t=e._readableState;d("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&s(e,"data")&&(t.flowing=!0,U(e))}}(n);e.on("drain",h);var l=!1;var p=!1;function b(t){d("ondata"),p=!1,!1!==e.write(t)||p||((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==C(o.pipes,e))&&!l&&(d("false write response, pause",n._readableState.awaitDrain),n._readableState.awaitDrain++,p=!0),n.pause())}function y(t){d("onerror",t),g(),e.removeListener("error",y),0===s(e,"error")&&e.emit("error",t)}function m(){e.removeListener("finish",v),g()}function v(){d("onfinish"),e.removeListener("close",m),g()}function g(){d("unpipe"),n.unpipe(e)}return n.on("data",b),function(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?a(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}(e,"error",y),e.once("close",m),e.once("finish",v),e.emit("pipe",n),o.flowing||(d("pipe resume"),n.resume()),e},g.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r),this);if(!e){var n=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o-1?setImmediate:i;m.WritableState=y;var u=e("core-util-is");u.inherits=e("inherits");var c={deprecate:e("util-deprecate")},f=e("./internal/streams/stream"),h=e("safe-buffer").Buffer,l=n.Uint8Array||function(){};var d,p=e("./internal/streams/destroy");function b(){}function y(t,r){a=a||e("./_stream_duplex"),t=t||{};var n=r instanceof a;this.objectMode=!!t.objectMode,n&&(this.objectMode=this.objectMode||!!t.writableObjectMode);var u=t.highWaterMark,c=t.writableHighWaterMark,f=this.objectMode?16:16384;this.highWaterMark=u||0===u?u:n&&(c||0===c)?c:f,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var h=!1===t.decodeStrings;this.decodeStrings=!h,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var r=e._writableState,n=r.sync,o=r.writecb;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(r),t)!function(e,t,r,n,o){--t.pendingcb,r?(i(o,n),i(E,e,t),e._writableState.errorEmitted=!0,e.emit("error",n)):(o(n),e._writableState.errorEmitted=!0,e.emit("error",n),E(e,t))}(e,r,n,t,o);else{var a=_(r);a||r.corked||r.bufferProcessing||!r.bufferedRequest||w(e,r),n?s(g,e,r,a,o):g(e,r,a,o)}}(r,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new o(this)}function m(t){if(a=a||e("./_stream_duplex"),!(d.call(m,this)||this instanceof a))return new m(t);this._writableState=new y(t,this),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),f.call(this)}function v(e,t,r,n,i,o,a){t.writelen=n,t.writecb=a,t.writing=!0,t.sync=!0,r?e._writev(i,t.onwrite):e._write(i,o,t.onwrite),t.sync=!1}function g(e,t,r,n){r||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,n(),E(e,t)}function w(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var n=t.bufferedRequestCount,i=new Array(n),a=t.corkedRequestsFree;a.entry=r;for(var s=0,u=!0;r;)i[s]=r,r.isBuf||(u=!1),r=r.next,s+=1;i.allBuffers=u,v(e,t,!0,t.length,i,"",a.finish),t.pendingcb++,t.lastBufferedRequest=null,a.next?(t.corkedRequestsFree=a.next,a.next=null):t.corkedRequestsFree=new o(t),t.bufferedRequestCount=0}else{for(;r;){var c=r.chunk,f=r.encoding,h=r.callback;if(v(e,t,!1,t.objectMode?1:c.length,c,f,h),r=r.next,t.bufferedRequestCount--,t.writing)break}null===r&&(t.lastBufferedRequest=null)}t.bufferedRequest=r,t.bufferProcessing=!1}function _(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function A(e,t){e._final(function(r){t.pendingcb--,r&&e.emit("error",r),t.prefinished=!0,e.emit("prefinish"),E(e,t)})}function E(e,t){var r=_(t);return r&&(!function(e,t){t.prefinished||t.finalCalled||("function"==typeof e._final?(t.pendingcb++,t.finalCalled=!0,i(A,e,t)):(t.prefinished=!0,e.emit("prefinish")))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"))),r}u.inherits(m,f),y.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(y.prototype,"buffer",{get:c.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(d=Function.prototype[Symbol.hasInstance],Object.defineProperty(m,Symbol.hasInstance,{value:function(e){return!!d.call(this,e)||this===m&&(e&&e._writableState instanceof y)}})):d=function(e){return e instanceof this},m.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},m.prototype.write=function(e,t,r){var n,o=this._writableState,a=!1,s=!o.objectMode&&(n=e,h.isBuffer(n)||n instanceof l);return s&&!h.isBuffer(e)&&(e=function(e){return h.from(e)}(e)),"function"==typeof t&&(r=t,t=null),s?t="buffer":t||(t=o.defaultEncoding),"function"!=typeof r&&(r=b),o.ended?function(e,t){var r=new Error("write after end");e.emit("error",r),i(t,r)}(this,r):(s||function(e,t,r,n){var o=!0,a=!1;return null===r?a=new TypeError("May not write null values to stream"):"string"==typeof r||void 0===r||t.objectMode||(a=new TypeError("Invalid non-string/buffer chunk")),a&&(e.emit("error",a),i(n,a),o=!1),o}(this,o,e,r))&&(o.pendingcb++,a=function(e,t,r,n,i,o){if(!r){var a=function(e,t,r){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=h.from(t,r));return t}(t,n,i);n!==a&&(r=!0,i="buffer",n=a)}var s=t.objectMode?1:n.length;t.length+=s;var u=t.length-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},m.prototype._write=function(e,t,r){r(new Error("_write() is not implemented"))},m.prototype._writev=null,m.prototype.end=function(e,t,r){var n=this._writableState;"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||function(e,t,r){t.ending=!0,E(e,t),r&&(t.finished?i(r):e.once("finish",r));t.ended=!0,e.writable=!1}(this,n,r)},Object.defineProperty(m.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),m.prototype.destroy=p.destroy,m.prototype._undestroy=p.undestroy,m.prototype._destroy=function(e,t){this.end(),t(e)}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?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(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("util");t.exports=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.head=null,this.tail=null,this.length=0}return e.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},e.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},e.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r},e.prototype.concat=function(e){if(0===this.length)return n.alloc(0);if(1===this.length)return this.head.data;for(var t,r,i,o=n.allocUnsafe(e>>>0),a=this.head,s=0;a;)t=a.data,r=o,i=s,t.copy(r,i),s+=a.data.length,a=a.next;return o},e}(),i&&i.inspect&&i.inspect.custom&&(t.exports.prototype[i.inspect.custom]=function(){var e=i.inspect({length:this.length});return this.constructor.name+" "+e})},{"safe-buffer":290,util:55}],282:[function(e,t,r){"use strict";var n=e("process-nextick-args").nextTick;function i(e,t){e.emit("error",t)}t.exports={destroy:function(e,t){var r=this,o=this._readableState&&this._readableState.destroyed,a=this._writableState&&this._writableState.destroyed;return o||a?(t?t(e):!e||this._writableState&&this._writableState.errorEmitted||n(i,this,e),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!t&&e?(n(i,r,e),r._writableState&&(r._writableState.errorEmitted=!0)):t&&t(e)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}}},{"process-nextick-args":256}],283:[function(e,t,r){t.exports=e("events").EventEmitter},{events:157}],284:[function(e,t,r){t.exports=e("./readable").PassThrough},{"./readable":285}],285:[function(e,t,r){(r=t.exports=e("./lib/_stream_readable.js")).Stream=r,r.Readable=r,r.Writable=e("./lib/_stream_writable.js"),r.Duplex=e("./lib/_stream_duplex.js"),r.Transform=e("./lib/_stream_transform.js"),r.PassThrough=e("./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(e,t,r){t.exports=e("./readable").Transform},{"./readable":285}],287:[function(e,t,r){t.exports=e("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":280}],288:[function(e,t,r){(function(r){"use strict";var n=e("inherits"),i=e("hash-base");function o(){i.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function a(e,t){return e<>>32-t}function s(e,t,r,n,i,o,s,u){return a(e+(t^r^n)+o+s|0,u)+i|0}function u(e,t,r,n,i,o,s,u){return a(e+(t&r|~t&n)+o+s|0,u)+i|0}function c(e,t,r,n,i,o,s,u){return a(e+((t|~r)^n)+o+s|0,u)+i|0}function f(e,t,r,n,i,o,s,u){return a(e+(t&n|r&~n)+o+s|0,u)+i|0}function h(e,t,r,n,i,o,s,u){return a(e+(t^(r|~n))+o+s|0,u)+i|0}n(o,i),o.prototype._update=function(){for(var e=new Array(16),t=0;t<16;++t)e[t]=this._block.readInt32LE(4*t);var r=this._a,n=this._b,i=this._c,o=this._d,l=this._e;l=s(l,r=s(r,n,i,o,l,e[0],0,11),n,i=a(i,10),o,e[1],0,14),n=s(n=a(n,10),i=s(i,o=s(o,l,r,n,i,e[2],0,15),l,r=a(r,10),n,e[3],0,12),o,l=a(l,10),r,e[4],0,5),o=s(o=a(o,10),l=s(l,r=s(r,n,i,o,l,e[5],0,8),n,i=a(i,10),o,e[6],0,7),r,n=a(n,10),i,e[7],0,9),r=s(r=a(r,10),n=s(n,i=s(i,o,l,r,n,e[8],0,11),o,l=a(l,10),r,e[9],0,13),i,o=a(o,10),l,e[10],0,14),i=s(i=a(i,10),o=s(o,l=s(l,r,n,i,o,e[11],0,15),r,n=a(n,10),i,e[12],0,6),l,r=a(r,10),n,e[13],0,7),l=u(l=a(l,10),r=s(r,n=s(n,i,o,l,r,e[14],0,9),i,o=a(o,10),l,e[15],0,8),n,i=a(i,10),o,e[7],1518500249,7),n=u(n=a(n,10),i=u(i,o=u(o,l,r,n,i,e[4],1518500249,6),l,r=a(r,10),n,e[13],1518500249,8),o,l=a(l,10),r,e[1],1518500249,13),o=u(o=a(o,10),l=u(l,r=u(r,n,i,o,l,e[10],1518500249,11),n,i=a(i,10),o,e[6],1518500249,9),r,n=a(n,10),i,e[15],1518500249,7),r=u(r=a(r,10),n=u(n,i=u(i,o,l,r,n,e[3],1518500249,15),o,l=a(l,10),r,e[12],1518500249,7),i,o=a(o,10),l,e[0],1518500249,12),i=u(i=a(i,10),o=u(o,l=u(l,r,n,i,o,e[9],1518500249,15),r,n=a(n,10),i,e[5],1518500249,9),l,r=a(r,10),n,e[2],1518500249,11),l=u(l=a(l,10),r=u(r,n=u(n,i,o,l,r,e[14],1518500249,7),i,o=a(o,10),l,e[11],1518500249,13),n,i=a(i,10),o,e[8],1518500249,12),n=c(n=a(n,10),i=c(i,o=c(o,l,r,n,i,e[3],1859775393,11),l,r=a(r,10),n,e[10],1859775393,13),o,l=a(l,10),r,e[14],1859775393,6),o=c(o=a(o,10),l=c(l,r=c(r,n,i,o,l,e[4],1859775393,7),n,i=a(i,10),o,e[9],1859775393,14),r,n=a(n,10),i,e[15],1859775393,9),r=c(r=a(r,10),n=c(n,i=c(i,o,l,r,n,e[8],1859775393,13),o,l=a(l,10),r,e[1],1859775393,15),i,o=a(o,10),l,e[2],1859775393,14),i=c(i=a(i,10),o=c(o,l=c(l,r,n,i,o,e[7],1859775393,8),r,n=a(n,10),i,e[0],1859775393,13),l,r=a(r,10),n,e[6],1859775393,6),l=c(l=a(l,10),r=c(r,n=c(n,i,o,l,r,e[13],1859775393,5),i,o=a(o,10),l,e[11],1859775393,12),n,i=a(i,10),o,e[5],1859775393,7),n=f(n=a(n,10),i=f(i,o=c(o,l,r,n,i,e[12],1859775393,5),l,r=a(r,10),n,e[1],2400959708,11),o,l=a(l,10),r,e[9],2400959708,12),o=f(o=a(o,10),l=f(l,r=f(r,n,i,o,l,e[11],2400959708,14),n,i=a(i,10),o,e[10],2400959708,15),r,n=a(n,10),i,e[0],2400959708,14),r=f(r=a(r,10),n=f(n,i=f(i,o,l,r,n,e[8],2400959708,15),o,l=a(l,10),r,e[12],2400959708,9),i,o=a(o,10),l,e[4],2400959708,8),i=f(i=a(i,10),o=f(o,l=f(l,r,n,i,o,e[13],2400959708,9),r,n=a(n,10),i,e[3],2400959708,14),l,r=a(r,10),n,e[7],2400959708,5),l=f(l=a(l,10),r=f(r,n=f(n,i,o,l,r,e[15],2400959708,6),i,o=a(o,10),l,e[14],2400959708,8),n,i=a(i,10),o,e[5],2400959708,6),n=h(n=a(n,10),i=f(i,o=f(o,l,r,n,i,e[6],2400959708,5),l,r=a(r,10),n,e[2],2400959708,12),o,l=a(l,10),r,e[4],2840853838,9),o=h(o=a(o,10),l=h(l,r=h(r,n,i,o,l,e[0],2840853838,15),n,i=a(i,10),o,e[5],2840853838,5),r,n=a(n,10),i,e[9],2840853838,11),r=h(r=a(r,10),n=h(n,i=h(i,o,l,r,n,e[7],2840853838,6),o,l=a(l,10),r,e[12],2840853838,8),i,o=a(o,10),l,e[2],2840853838,13),i=h(i=a(i,10),o=h(o,l=h(l,r,n,i,o,e[10],2840853838,12),r,n=a(n,10),i,e[14],2840853838,5),l,r=a(r,10),n,e[1],2840853838,12),l=h(l=a(l,10),r=h(r,n=h(n,i,o,l,r,e[3],2840853838,13),i,o=a(o,10),l,e[8],2840853838,14),n,i=a(i,10),o,e[11],2840853838,11),n=h(n=a(n,10),i=h(i,o=h(o,l,r,n,i,e[6],2840853838,8),l,r=a(r,10),n,e[15],2840853838,5),o,l=a(l,10),r,e[13],2840853838,6),o=a(o,10);var d=this._a,p=this._b,b=this._c,y=this._d,m=this._e;m=h(m,d=h(d,p,b,y,m,e[5],1352829926,8),p,b=a(b,10),y,e[14],1352829926,9),p=h(p=a(p,10),b=h(b,y=h(y,m,d,p,b,e[7],1352829926,9),m,d=a(d,10),p,e[0],1352829926,11),y,m=a(m,10),d,e[9],1352829926,13),y=h(y=a(y,10),m=h(m,d=h(d,p,b,y,m,e[2],1352829926,15),p,b=a(b,10),y,e[11],1352829926,15),d,p=a(p,10),b,e[4],1352829926,5),d=h(d=a(d,10),p=h(p,b=h(b,y,m,d,p,e[13],1352829926,7),y,m=a(m,10),d,e[6],1352829926,7),b,y=a(y,10),m,e[15],1352829926,8),b=h(b=a(b,10),y=h(y,m=h(m,d,p,b,y,e[8],1352829926,11),d,p=a(p,10),b,e[1],1352829926,14),m,d=a(d,10),p,e[10],1352829926,14),m=f(m=a(m,10),d=h(d,p=h(p,b,y,m,d,e[3],1352829926,12),b,y=a(y,10),m,e[12],1352829926,6),p,b=a(b,10),y,e[6],1548603684,9),p=f(p=a(p,10),b=f(b,y=f(y,m,d,p,b,e[11],1548603684,13),m,d=a(d,10),p,e[3],1548603684,15),y,m=a(m,10),d,e[7],1548603684,7),y=f(y=a(y,10),m=f(m,d=f(d,p,b,y,m,e[0],1548603684,12),p,b=a(b,10),y,e[13],1548603684,8),d,p=a(p,10),b,e[5],1548603684,9),d=f(d=a(d,10),p=f(p,b=f(b,y,m,d,p,e[10],1548603684,11),y,m=a(m,10),d,e[14],1548603684,7),b,y=a(y,10),m,e[15],1548603684,7),b=f(b=a(b,10),y=f(y,m=f(m,d,p,b,y,e[8],1548603684,12),d,p=a(p,10),b,e[12],1548603684,7),m,d=a(d,10),p,e[4],1548603684,6),m=f(m=a(m,10),d=f(d,p=f(p,b,y,m,d,e[9],1548603684,15),b,y=a(y,10),m,e[1],1548603684,13),p,b=a(b,10),y,e[2],1548603684,11),p=c(p=a(p,10),b=c(b,y=c(y,m,d,p,b,e[15],1836072691,9),m,d=a(d,10),p,e[5],1836072691,7),y,m=a(m,10),d,e[1],1836072691,15),y=c(y=a(y,10),m=c(m,d=c(d,p,b,y,m,e[3],1836072691,11),p,b=a(b,10),y,e[7],1836072691,8),d,p=a(p,10),b,e[14],1836072691,6),d=c(d=a(d,10),p=c(p,b=c(b,y,m,d,p,e[6],1836072691,6),y,m=a(m,10),d,e[9],1836072691,14),b,y=a(y,10),m,e[11],1836072691,12),b=c(b=a(b,10),y=c(y,m=c(m,d,p,b,y,e[8],1836072691,13),d,p=a(p,10),b,e[12],1836072691,5),m,d=a(d,10),p,e[2],1836072691,14),m=c(m=a(m,10),d=c(d,p=c(p,b,y,m,d,e[10],1836072691,13),b,y=a(y,10),m,e[0],1836072691,13),p,b=a(b,10),y,e[4],1836072691,7),p=u(p=a(p,10),b=u(b,y=c(y,m,d,p,b,e[13],1836072691,5),m,d=a(d,10),p,e[8],2053994217,15),y,m=a(m,10),d,e[6],2053994217,5),y=u(y=a(y,10),m=u(m,d=u(d,p,b,y,m,e[4],2053994217,8),p,b=a(b,10),y,e[1],2053994217,11),d,p=a(p,10),b,e[3],2053994217,14),d=u(d=a(d,10),p=u(p,b=u(b,y,m,d,p,e[11],2053994217,14),y,m=a(m,10),d,e[15],2053994217,6),b,y=a(y,10),m,e[0],2053994217,14),b=u(b=a(b,10),y=u(y,m=u(m,d,p,b,y,e[5],2053994217,6),d,p=a(p,10),b,e[12],2053994217,9),m,d=a(d,10),p,e[2],2053994217,12),m=u(m=a(m,10),d=u(d,p=u(p,b,y,m,d,e[13],2053994217,9),b,y=a(y,10),m,e[9],2053994217,12),p,b=a(b,10),y,e[7],2053994217,5),p=s(p=a(p,10),b=u(b,y=u(y,m,d,p,b,e[10],2053994217,15),m,d=a(d,10),p,e[14],2053994217,8),y,m=a(m,10),d,e[12],0,8),y=s(y=a(y,10),m=s(m,d=s(d,p,b,y,m,e[15],0,5),p,b=a(b,10),y,e[10],0,12),d,p=a(p,10),b,e[4],0,9),d=s(d=a(d,10),p=s(p,b=s(b,y,m,d,p,e[1],0,12),y,m=a(m,10),d,e[5],0,5),b,y=a(y,10),m,e[8],0,14),b=s(b=a(b,10),y=s(y,m=s(m,d,p,b,y,e[7],0,6),d,p=a(p,10),b,e[6],0,8),m,d=a(d,10),p,e[2],0,13),m=s(m=a(m,10),d=s(d,p=s(p,b,y,m,d,e[13],0,6),b,y=a(y,10),m,e[14],0,5),p,b=a(b,10),y,e[0],0,15),p=s(p=a(p,10),b=s(b,y=s(y,m,d,p,b,e[3],0,13),m,d=a(d,10),p,e[9],0,11),y,m=a(m,10),d,e[11],0,11),y=a(y,10);var v=this._b+i+y|0;this._b=this._c+o+m|0,this._c=this._d+l+d|0,this._d=this._e+r+p|0,this._e=this._a+n+b|0,this._a=v},o.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=new r(20);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e.writeInt32LE(this._e,16),e},t.exports=o}).call(this,e("buffer").Buffer)},{buffer:84,"hash-base":161,inherits:180}],289:[function(e,t,r){const n=e("assert"),i=e("safe-buffer").Buffer;function o(e,t){if("00"===e.slice(0,2))throw new Error("invalid RLP: extra zeros");return parseInt(e,t)}function a(e,t){if(e<56)return i.from([e+t]);var r=u(e),n=u(t+55+r.length/2);return i.from(n+r,"hex")}function s(e){return"0x"===e.slice(0,2)}function u(e){var t=e.toString(16);return t.length%2&&(t="0"+t),t}function c(e){if(!i.isBuffer(e))if("string"==typeof e)e=s(e)?i.from(((r="string"!=typeof(n=e)?n:s(n)?n.slice(2):n).length%2&&(r="0"+r),r),"hex"):i.from(e);else if("number"==typeof e)e?(t=u(e),e=i.from(t,"hex")):e=i.from([]);else if(null==e)e=i.from([]);else{if(!e.toArray)throw new Error("invalid type");e=i.from(e.toArray())}var t,r,n;return e}r.encode=function(e){if(e instanceof Array){for(var t=[],n=0;nt.length)throw new Error("invalid rlp: total length is larger than the data");if(0===(s=t.slice(n,h)).length)throw new Error("invalid rlp, List has a invalid length");for(;s.length;)u=e(s),c.push(u.data),s=u.remainder;return{data:c,remainder:t.slice(h)}}(e=c(e));return t?r:(n.equal(r.remainder.length,0,"invalid remainder"),r.data)},r.getLength=function(e){if(!e||0===e.length)return i.from([]);var t=(e=c(e))[0];if(t<=127)return e.length;if(t<=183)return t-127;if(t<=191)return t-182;if(t<=247)return t-191;var r=t-246;return r+o(e.slice(1,r).toString("hex"),16)}},{assert:19,"safe-buffer":290}],290:[function(e,t,r){var n=e("buffer"),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function a(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=n:(o(n,r),r.Buffer=a),o(i,a),a.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},a.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},{buffer:84}],291:[function(e,t,r){const n=e("util"),i=e("events/");var o="object"==typeof Reflect?Reflect:null,a=o&&"function"==typeof o.apply?o.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};function s(){i.call(this)}function u(e,t,r){try{a(e,t,r)}catch(e){setTimeout(()=>{throw e})}}t.exports=s,n.inherits(s,i),s.prototype.emit=function(e){for(var t=[],r=1;r0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var s=i[e];if(void 0===s)return!1;if("function"==typeof s)u(s,this,t);else{var c=s.length,f=function(e,t){for(var r=new Array(t),n=0;n0&&a.length>i&&!a.warned){a.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=a.length,s=u,console&&console.warn&&console.warn(s)}return e}function h(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=function(){for(var e=[],t=0;t0&&(a=t[0]),a instanceof Error)throw a;var s=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw s.context=a,s}var u=i[e];if(void 0===u)return!1;if("function"==typeof u)o(u,this,t);else{var c=u.length,f=p(u,c);for(r=0;r=0;o--)if(r[o]===t||r[o].listener===t){a=r[o].listener,i=o;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1=0;n--)this.removeListener(e,t[n]);return this},s.prototype.listeners=function(e){return l(this,e,!0)},s.prototype.rawListeners=function(e){return l(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):d.call(e,t)},s.prototype.listenerCount=d,s.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]}},{}],293:[function(e,t,r){t.exports=e("scryptsy")},{scryptsy:294}],294:[function(e,t,r){(function(r){var n=e("pbkdf2").pbkdf2Sync,i=2147483647;function o(e,t,n,i,o){if(r.isBuffer(e)&&r.isBuffer(n))e.copy(n,i,t,t+o);else for(;o--;)n[i++]=e[t++]}t.exports=function(e,t,a,s,u,c,f){if(0===a||0!=(a&a-1))throw Error("N must be > 0 and a power of 2");if(a>i/128/s)throw Error("Parameter N is too large");if(s>i/128/u)throw Error("Parameter r is too large");var h,l=new r(256*s),d=new r(128*s*a),p=new Int32Array(16),b=new Int32Array(16),y=new r(64),m=n(e,t,1,128*u*s,"sha256");if(f){var v=u*a*2,g=0;h=function(){++g%1e3==0&&f({current:g,total:v,percent:g/v*100})}}for(var w=0;w>>32-t}function x(e){var t;for(t=0;t<16;t++)p[t]=(255&e[4*t+0])<<0,p[t]|=(255&e[4*t+1])<<8,p[t]|=(255&e[4*t+2])<<16,p[t]|=(255&e[4*t+3])<<24;for(o(p,0,b,0,16),t=8;t>0;t-=2)b[4]^=E(b[0]+b[12],7),b[8]^=E(b[4]+b[0],9),b[12]^=E(b[8]+b[4],13),b[0]^=E(b[12]+b[8],18),b[9]^=E(b[5]+b[1],7),b[13]^=E(b[9]+b[5],9),b[1]^=E(b[13]+b[9],13),b[5]^=E(b[1]+b[13],18),b[14]^=E(b[10]+b[6],7),b[2]^=E(b[14]+b[10],9),b[6]^=E(b[2]+b[14],13),b[10]^=E(b[6]+b[2],18),b[3]^=E(b[15]+b[11],7),b[7]^=E(b[3]+b[15],9),b[11]^=E(b[7]+b[3],13),b[15]^=E(b[11]+b[7],18),b[1]^=E(b[0]+b[3],7),b[2]^=E(b[1]+b[0],9),b[3]^=E(b[2]+b[1],13),b[0]^=E(b[3]+b[2],18),b[6]^=E(b[5]+b[4],7),b[7]^=E(b[6]+b[5],9),b[4]^=E(b[7]+b[6],13),b[5]^=E(b[4]+b[7],18),b[11]^=E(b[10]+b[9],7),b[8]^=E(b[11]+b[10],9),b[9]^=E(b[8]+b[11],13),b[10]^=E(b[9]+b[8],18),b[12]^=E(b[15]+b[14],7),b[13]^=E(b[12]+b[15],9),b[14]^=E(b[13]+b[12],13),b[15]^=E(b[14]+b[13],18);for(t=0;t<16;++t)p[t]=b[t]+p[t];for(t=0;t<16;t++){var r=4*t;e[r+0]=p[t]>>0&255,e[r+1]=p[t]>>8&255,e[r+2]=p[t]>>16&255,e[r+3]=p[t]>>24&255}}function k(e,t,r,n,i){for(var o=0;o=r)throw RangeError(n)}}).call(this,{isBuffer:e("../../is-buffer/index.js")})},{"../../is-buffer/index.js":181}],297:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("bip66"),o=n.from([48,129,211,2,1,1,4,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,160,129,133,48,129,130,2,1,1,48,44,6,7,42,134,72,206,61,1,1,2,33,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,255,255,252,47,48,6,4,1,0,4,1,7,4,33,2,121,190,102,126,249,220,187,172,85,160,98,149,206,135,11,7,2,155,252,219,45,206,40,217,89,242,129,91,22,248,23,152,2,33,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,186,174,220,230,175,72,160,59,191,210,94,140,208,54,65,65,2,1,1,161,36,3,34,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),a=n.from([48,130,1,19,2,1,1,4,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,160,129,165,48,129,162,2,1,1,48,44,6,7,42,134,72,206,61,1,1,2,33,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,255,255,252,47,48,6,4,1,0,4,1,7,4,65,4,121,190,102,126,249,220,187,172,85,160,98,149,206,135,11,7,2,155,252,219,45,206,40,217,89,242,129,91,22,248,23,152,72,58,218,119,38,163,196,101,93,164,251,252,14,17,8,168,253,23,180,72,166,133,84,25,156,71,208,143,251,16,212,184,2,33,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,186,174,220,230,175,72,160,59,191,210,94,140,208,54,65,65,2,1,1,161,68,3,66,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);r.privateKeyExport=function(e,t,r){var i=n.from(r?o:a);return e.copy(i,r?8:9),t.copy(i,r?181:214),i},r.privateKeyImport=function(e){var t=e.length,r=0;if(!(t2||t1?e[r+n-2]<<8:0);if(!(t<(r+=n)+i||t32||t1&&0===t[o]&&!(128&t[o+1]);--r,++o);for(var a=n.concat([n.from([0]),e.s]),s=33,u=0;s>1&&0===a[u]&&!(128&a[u+1]);--s,++u);return i.encode(t.slice(o),a.slice(u))},r.signatureImport=function(e){var t=n.alloc(32,0),r=n.alloc(32,0);try{var o=i.decode(e);if(33===o.r.length&&0===o.r[0]&&(o.r=o.r.slice(1)),o.r.length>32)throw new Error("R length is too long");if(33===o.s.length&&0===o.s[0]&&(o.s=o.s.slice(1)),o.s.length>32)throw new Error("S length is too long")}catch(e){return}return o.r.copy(t,32-o.r.length),o.s.copy(r,32-o.s.length),{r:t,s:r}},r.signatureImportLax=function(e){var t=n.alloc(32,0),r=n.alloc(32,0),i=e.length,o=0;if(48===e[o++]){var a=e[o++];if(!(128&a&&(o+=a-128)>i)&&2===e[o++]){var s=e[o++];if(128&s){if(o+(a=s-128)>i)return;for(;a>0&&0===e[o];o+=1,a-=1);for(s=0;a>0;o+=1,a-=1)s=(s<<8)+e[o]}if(!(s>i-o)){var u=o;if(o+=s,2===e[o++]){var c=e[o++];if(128&c){if(o+(a=c-128)>i)return;for(;a>0&&0===e[o];o+=1,a-=1);for(c=0;a>0;o+=1,a-=1)c=(c<<8)+e[o]}if(!(c>i-o)){var f=o;for(o+=c;s>0&&0===e[u];s-=1,u+=1);if(!(s>32)){var h=e.slice(u,u+s);for(h.copy(t,32-h.length);c>0&&0===e[f];c-=1,f+=1);if(!(c>32)){var l=e.slice(f,f+c);return l.copy(r,32-l.length),{r:t,s:r}}}}}}}}}},{bip66:52,"safe-buffer":290}],298:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("create-hash"),o=e("bn.js"),a=e("elliptic").ec,s=e("../messages.json"),u=new a("secp256k1"),c=u.curve;function f(e){var t=e[0];switch(t){case 2:case 3:return 33!==e.length?null:function(e,t){var r=new o(t);if(r.cmp(c.p)>=0)return null;var n=(r=r.toRed(c.red)).redSqr().redIMul(r).redIAdd(c.b).redSqrt();return 3===e!==n.isOdd()&&(n=n.redNeg()),u.keyPair({pub:{x:r,y:n}})}(t,e.slice(1,33));case 4:case 6:case 7:return 65!==e.length?null:function(e,t,r){var n=new o(t),i=new o(r);if(n.cmp(c.p)>=0||i.cmp(c.p)>=0)return null;if(n=n.toRed(c.red),i=i.toRed(c.red),(6===e||7===e)&&i.isOdd()!==(7===e))return null;var a=n.redSqr().redIMul(n);return i.redSqr().redISub(a.redIAdd(c.b)).isZero()?u.keyPair({pub:{x:n,y:i}}):null}(t,e.slice(1,33),e.slice(33,65));default:return null}}r.privateKeyVerify=function(e){var t=new o(e);return t.cmp(c.n)<0&&!t.isZero()},r.privateKeyExport=function(e,t){var r=new o(e);if(r.cmp(c.n)>=0||r.isZero())throw new Error(s.EC_PRIVATE_KEY_EXPORT_DER_FAIL);return n.from(u.keyFromPrivate(e).getPublic(t,!0))},r.privateKeyNegate=function(e){var t=new o(e);return t.isZero()?n.alloc(32):c.n.sub(t).umod(c.n).toArrayLike(n,"be",32)},r.privateKeyModInverse=function(e){var t=new o(e);if(t.cmp(c.n)>=0||t.isZero())throw new Error(s.EC_PRIVATE_KEY_RANGE_INVALID);return t.invm(c.n).toArrayLike(n,"be",32)},r.privateKeyTweakAdd=function(e,t){var r=new o(t);if(r.cmp(c.n)>=0)throw new Error(s.EC_PRIVATE_KEY_TWEAK_ADD_FAIL);if(r.iadd(new o(e)),r.cmp(c.n)>=0&&r.isub(c.n),r.isZero())throw new Error(s.EC_PRIVATE_KEY_TWEAK_ADD_FAIL);return r.toArrayLike(n,"be",32)},r.privateKeyTweakMul=function(e,t){var r=new o(t);if(r.cmp(c.n)>=0||r.isZero())throw new Error(s.EC_PRIVATE_KEY_TWEAK_MUL_FAIL);return r.imul(new o(e)),r.cmp(c.n)&&(r=r.umod(c.n)),r.toArrayLike(n,"be",32)},r.publicKeyCreate=function(e,t){var r=new o(e);if(r.cmp(c.n)>=0||r.isZero())throw new Error(s.EC_PUBLIC_KEY_CREATE_FAIL);return n.from(u.keyFromPrivate(e).getPublic(t,!0))},r.publicKeyConvert=function(e,t){var r=f(e);if(null===r)throw new Error(s.EC_PUBLIC_KEY_PARSE_FAIL);return n.from(r.getPublic(t,!0))},r.publicKeyVerify=function(e){return null!==f(e)},r.publicKeyTweakAdd=function(e,t,r){var i=f(e);if(null===i)throw new Error(s.EC_PUBLIC_KEY_PARSE_FAIL);if((t=new o(t)).cmp(c.n)>=0)throw new Error(s.EC_PUBLIC_KEY_TWEAK_ADD_FAIL);return n.from(c.g.mul(t).add(i.pub).encode(!0,r))},r.publicKeyTweakMul=function(e,t,r){var i=f(e);if(null===i)throw new Error(s.EC_PUBLIC_KEY_PARSE_FAIL);if((t=new o(t)).cmp(c.n)>=0||t.isZero())throw new Error(s.EC_PUBLIC_KEY_TWEAK_MUL_FAIL);return n.from(i.pub.mul(t).encode(!0,r))},r.publicKeyCombine=function(e,t){for(var r=new Array(e.length),i=0;i=0||r.cmp(c.n)>=0)throw new Error(s.ECDSA_SIGNATURE_PARSE_FAIL);var i=n.from(e);return 1===r.cmp(u.nh)&&c.n.sub(r).toArrayLike(n,"be",32).copy(i,32),i},r.signatureExport=function(e){var t=e.slice(0,32),r=e.slice(32,64);if(new o(t).cmp(c.n)>=0||new o(r).cmp(c.n)>=0)throw new Error(s.ECDSA_SIGNATURE_PARSE_FAIL);return{r:t,s:r}},r.signatureImport=function(e){var t=new o(e.r);t.cmp(c.n)>=0&&(t=new o(0));var r=new o(e.s);return r.cmp(c.n)>=0&&(r=new o(0)),n.concat([t.toArrayLike(n,"be",32),r.toArrayLike(n,"be",32)])},r.sign=function(e,t,r,i){if("function"==typeof r){var a=r;r=function(r){var u=a(e,t,null,i,r);if(!n.isBuffer(u)||32!==u.length)throw new Error(s.ECDSA_SIGN_FAIL);return new o(u)}}var f=new o(t);if(f.cmp(c.n)>=0||f.isZero())throw new Error(s.ECDSA_SIGN_FAIL);var h=u.sign(e,t,{canonical:!0,k:r,pers:i});return{signature:n.concat([h.r.toArrayLike(n,"be",32),h.s.toArrayLike(n,"be",32)]),recovery:h.recoveryParam}},r.verify=function(e,t,r){var n={r:t.slice(0,32),s:t.slice(32,64)},i=new o(n.r),a=new o(n.s);if(i.cmp(c.n)>=0||a.cmp(c.n)>=0)throw new Error(s.ECDSA_SIGNATURE_PARSE_FAIL);if(1===a.cmp(u.nh)||i.isZero()||a.isZero())return!1;var h=f(r);if(null===h)throw new Error(s.EC_PUBLIC_KEY_PARSE_FAIL);return u.verify(e,n,{x:h.pub.x,y:h.pub.y})},r.recover=function(e,t,r,i){var a={r:t.slice(0,32),s:t.slice(32,64)},f=new o(a.r),h=new o(a.s);if(f.cmp(c.n)>=0||h.cmp(c.n)>=0)throw new Error(s.ECDSA_SIGNATURE_PARSE_FAIL);try{if(f.isZero()||h.isZero())throw new Error;var l=u.recoverPubKey(e,a,r);return n.from(l.encode(!0,i))}catch(e){throw new Error(s.ECDSA_RECOVER_FAIL)}},r.ecdh=function(e,t){var n=r.ecdhUnsafe(e,t,!0);return i("sha256").update(n).digest()},r.ecdhUnsafe=function(e,t,r){var i=f(e);if(null===i)throw new Error(s.EC_PUBLIC_KEY_PARSE_FAIL);var a=new o(t);if(a.cmp(c.n)>=0||a.isZero())throw new Error(s.ECDH_FAIL);return n.from(i.pub.mul(a).encode(!0,r))}},{"../messages.json":300,"bn.js":53,"create-hash":91,elliptic:109,"safe-buffer":290}],299:[function(e,t,r){"use strict";var n=e("./assert"),i=e("./der"),o=e("./messages.json");function a(e,t){return void 0===e?t:(n.isBoolean(e,o.COMPRESSED_TYPE_INVALID),e)}t.exports=function(e){return{privateKeyVerify:function(t){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),32===t.length&&e.privateKeyVerify(t)},privateKeyExport:function(t,r){n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),r=a(r,!0);var s=e.privateKeyExport(t,r);return i.privateKeyExport(t,s,r)},privateKeyImport:function(t){if(n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),(t=i.privateKeyImport(t))&&32===t.length&&e.privateKeyVerify(t))return t;throw new Error(o.EC_PRIVATE_KEY_IMPORT_DER_FAIL)},privateKeyNegate:function(t){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),e.privateKeyNegate(t)},privateKeyModInverse:function(t){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),e.privateKeyModInverse(t)},privateKeyTweakAdd:function(t,r){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),n.isBuffer(r,o.TWEAK_TYPE_INVALID),n.isBufferLength(r,32,o.TWEAK_LENGTH_INVALID),e.privateKeyTweakAdd(t,r)},privateKeyTweakMul:function(t,r){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),n.isBuffer(r,o.TWEAK_TYPE_INVALID),n.isBufferLength(r,32,o.TWEAK_LENGTH_INVALID),e.privateKeyTweakMul(t,r)},publicKeyCreate:function(t,r){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),r=a(r,!0),e.publicKeyCreate(t,r)},publicKeyConvert:function(t,r){return n.isBuffer(t,o.EC_PUBLIC_KEY_TYPE_INVALID),n.isBufferLength2(t,33,65,o.EC_PUBLIC_KEY_LENGTH_INVALID),r=a(r,!0),e.publicKeyConvert(t,r)},publicKeyVerify:function(t){return n.isBuffer(t,o.EC_PUBLIC_KEY_TYPE_INVALID),e.publicKeyVerify(t)},publicKeyTweakAdd:function(t,r,i){return n.isBuffer(t,o.EC_PUBLIC_KEY_TYPE_INVALID),n.isBufferLength2(t,33,65,o.EC_PUBLIC_KEY_LENGTH_INVALID),n.isBuffer(r,o.TWEAK_TYPE_INVALID),n.isBufferLength(r,32,o.TWEAK_LENGTH_INVALID),i=a(i,!0),e.publicKeyTweakAdd(t,r,i)},publicKeyTweakMul:function(t,r,i){return n.isBuffer(t,o.EC_PUBLIC_KEY_TYPE_INVALID),n.isBufferLength2(t,33,65,o.EC_PUBLIC_KEY_LENGTH_INVALID),n.isBuffer(r,o.TWEAK_TYPE_INVALID),n.isBufferLength(r,32,o.TWEAK_LENGTH_INVALID),i=a(i,!0),e.publicKeyTweakMul(t,r,i)},publicKeyCombine:function(t,r){n.isArray(t,o.EC_PUBLIC_KEYS_TYPE_INVALID),n.isLengthGTZero(t,o.EC_PUBLIC_KEYS_LENGTH_INVALID);for(var i=0;i=2&&("function"==typeof arguments[1]?r.task=arguments[1]:r.n=arguments[1]);var n=r.task;if(r.task=function(){n(t.leave)},t.current+r.n-e>t.capacity)return 1===e&&(t.current--,t.firstHere=!1),t.queue.push(r);t.current+=r.n-e,r.task(t.leave),1===e&&(t.firstHere=!1)},leave:function(e){if(e=e||1,t.current-=e,t.queue.length){var r=t.queue[0];r.n+t.current>t.capacity||(t.queue.shift(),t.current+=r.n,i(r.task))}else if(t.current<0)throw new Error("leave called too many times.")},available:function(e){return e=e||1,t.current+e<=t.capacity}};return t}void 0!==e&&e&&"function"==typeof e.nextTick&&(i=e.nextTick),"object"==typeof r?t.exports=o:"function"==typeof define&&define.amd?define(function(){return o}):n.semaphore=o}(this)}).call(this,e("_process"))},{_process:257}],302:[function(e,t,r){"use strict";t.exports="function"==typeof setImmediate?setImmediate:function(){var e=[].slice.apply(arguments);e.splice(1,0,0),setTimeout.apply(null,e)}},{}],303:[function(e,t,r){var n=e("safe-buffer").Buffer;function i(e,t){this._block=n.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}i.prototype.update=function(e,t){"string"==typeof e&&(t=t||"utf8",e=n.from(e,t));for(var r=this._block,i=this._blockSize,o=e.length,a=this._len,s=0;s=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var o=this._hash();return e?o.toString(e):o},i.prototype._update=function(){throw new Error("_update must be implemented by subclass")},t.exports=i},{"safe-buffer":290}],304:[function(e,t,r){(r=t.exports=function(e){e=e.toLowerCase();var t=r[e];if(!t)throw new Error(e+" is not supported (we accept pull requests)");return new t}).sha=e("./sha"),r.sha1=e("./sha1"),r.sha224=e("./sha224"),r.sha256=e("./sha256"),r.sha384=e("./sha384"),r.sha512=e("./sha512")},{"./sha":305,"./sha1":306,"./sha224":307,"./sha256":308,"./sha384":309,"./sha512":310}],305:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1518500249,1859775393,-1894007588,-899497514],s=new Array(80);function u(){this.init(),this._w=s,i.call(this,64,56)}function c(e){return e<<30|e>>>2}function f(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}n(u,i),u.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,h=0;h<16;++h)r[h]=e.readInt32BE(4*h);for(;h<80;++h)r[h]=r[h-3]^r[h-8]^r[h-14]^r[h-16];for(var l=0;l<80;++l){var d=~~(l/20),p=0|((t=n)<<5|t>>>27)+f(d,i,o,s)+u+r[l]+a[d];u=s,s=o,o=c(i),i=n,n=p}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},u.prototype._hash=function(){var e=o.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},t.exports=u},{"./hash":303,inherits:180,"safe-buffer":290}],306:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1518500249,1859775393,-1894007588,-899497514],s=new Array(80);function u(){this.init(),this._w=s,i.call(this,64,56)}function c(e){return e<<5|e>>>27}function f(e){return e<<30|e>>>2}function h(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}n(u,i),u.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,l=0;l<16;++l)r[l]=e.readInt32BE(4*l);for(;l<80;++l)r[l]=(t=r[l-3]^r[l-8]^r[l-14]^r[l-16])<<1|t>>>31;for(var d=0;d<80;++d){var p=~~(d/20),b=c(n)+h(p,i,o,s)+u+r[d]+a[p]|0;u=s,s=o,o=f(i),i=n,n=b}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},u.prototype._hash=function(){var e=o.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},t.exports=u},{"./hash":303,inherits:180,"safe-buffer":290}],307:[function(e,t,r){var n=e("inherits"),i=e("./sha256"),o=e("./hash"),a=e("safe-buffer").Buffer,s=new Array(64);function u(){this.init(),this._w=s,o.call(this,64,56)}n(u,i),u.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},u.prototype._hash=function(){var e=a.allocUnsafe(28);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e},t.exports=u},{"./hash":303,"./sha256":308,inherits:180,"safe-buffer":290}],308:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],s=new Array(64);function u(){this.init(),this._w=s,i.call(this,64,56)}function c(e,t,r){return r^e&(t^r)}function f(e,t,r){return e&t|r&(e|t)}function h(e){return(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function l(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function d(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}n(u,i),u.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,p=0|this._f,b=0|this._g,y=0|this._h,m=0;m<16;++m)r[m]=e.readInt32BE(4*m);for(;m<64;++m)r[m]=0|(((t=r[m-2])>>>17|t<<15)^(t>>>19|t<<13)^t>>>10)+r[m-7]+d(r[m-15])+r[m-16];for(var v=0;v<64;++v){var g=y+l(u)+c(u,p,b)+a[v]+r[v]|0,w=h(n)+f(n,i,o)|0;y=b,b=p,p=u,u=s+g|0,s=o,o=i,i=n,n=g+w|0}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0,this._f=p+this._f|0,this._g=b+this._g|0,this._h=y+this._h|0},u.prototype._hash=function(){var e=o.allocUnsafe(32);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e.writeInt32BE(this._h,28),e},t.exports=u},{"./hash":303,inherits:180,"safe-buffer":290}],309:[function(e,t,r){var n=e("inherits"),i=e("./sha512"),o=e("./hash"),a=e("safe-buffer").Buffer,s=new Array(160);function u(){this.init(),this._w=s,o.call(this,128,112)}n(u,i),u.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},u.prototype._hash=function(){var e=a.allocUnsafe(48);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e},t.exports=u},{"./hash":303,"./sha512":310,inherits:180,"safe-buffer":290}],310:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],s=new Array(160);function u(){this.init(),this._w=s,i.call(this,128,112)}function c(e,t,r){return r^e&(t^r)}function f(e,t,r){return e&t|r&(e|t)}function h(e,t){return(e>>>28|t<<4)^(t>>>2|e<<30)^(t>>>7|e<<25)}function l(e,t){return(e>>>14|t<<18)^(e>>>18|t<<14)^(t>>>9|e<<23)}function d(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^e>>>7}function p(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^(e>>>7|t<<25)}function b(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^e>>>6}function y(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^(e>>>6|t<<26)}function m(e,t){return e>>>0>>0?1:0}n(u,i),u.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},u.prototype._update=function(e){for(var t=this._w,r=0|this._ah,n=0|this._bh,i=0|this._ch,o=0|this._dh,s=0|this._eh,u=0|this._fh,v=0|this._gh,g=0|this._hh,w=0|this._al,_=0|this._bl,A=0|this._cl,E=0|this._dl,x=0|this._el,k=0|this._fl,S=0|this._gl,M=0|this._hl,I=0;I<32;I+=2)t[I]=e.readInt32BE(4*I),t[I+1]=e.readInt32BE(4*I+4);for(;I<160;I+=2){var T=t[I-30],U=t[I-30+1],j=d(T,U),B=p(U,T),P=b(T=t[I-4],U=t[I-4+1]),C=y(U,T),N=t[I-14],R=t[I-14+1],L=t[I-32],O=t[I-32+1],D=B+R|0,F=j+N+m(D,B)|0;F=(F=F+P+m(D=D+C|0,C)|0)+L+m(D=D+O|0,O)|0,t[I]=F,t[I+1]=D}for(var q=0;q<160;q+=2){F=t[q],D=t[q+1];var H=f(r,n,i),z=f(w,_,A),K=h(r,w),V=h(w,r),G=l(s,x),W=l(x,s),Y=a[q],X=a[q+1],Z=c(s,u,v),J=c(x,k,S),$=M+W|0,Q=g+G+m($,M)|0;Q=(Q=(Q=Q+Z+m($=$+J|0,J)|0)+Y+m($=$+X|0,X)|0)+F+m($=$+D|0,D)|0;var ee=V+z|0,te=K+H+m(ee,V)|0;g=v,M=S,v=u,S=k,u=s,k=x,s=o+Q+m(x=E+$|0,E)|0,o=i,E=A,i=n,A=_,n=r,_=w,r=Q+te+m(w=$+ee|0,$)|0}this._al=this._al+w|0,this._bl=this._bl+_|0,this._cl=this._cl+A|0,this._dl=this._dl+E|0,this._el=this._el+x|0,this._fl=this._fl+k|0,this._gl=this._gl+S|0,this._hl=this._hl+M|0,this._ah=this._ah+r+m(this._al,w)|0,this._bh=this._bh+n+m(this._bl,_)|0,this._ch=this._ch+i+m(this._cl,A)|0,this._dh=this._dh+o+m(this._dl,E)|0,this._eh=this._eh+s+m(this._el,x)|0,this._fh=this._fh+u+m(this._fl,k)|0,this._gh=this._gh+v+m(this._gl,S)|0,this._hh=this._hh+g+m(this._hl,M)|0},u.prototype._hash=function(){var e=o.allocUnsafe(64);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e},t.exports=u},{"./hash":303,inherits:180,"safe-buffer":290}],311:[function(e,t,r){t.exports=i;var n=e("events").EventEmitter;function i(){n.call(this)}e("inherits")(i,n),i.Readable=e("readable-stream/readable.js"),i.Writable=e("readable-stream/writable.js"),i.Duplex=e("readable-stream/duplex.js"),i.Transform=e("readable-stream/transform.js"),i.PassThrough=e("readable-stream/passthrough.js"),i.Stream=i,i.prototype.pipe=function(e,t){var r=this;function i(t){e.writable&&!1===e.write(t)&&r.pause&&r.pause()}function o(){r.readable&&r.resume&&r.resume()}r.on("data",i),e.on("drain",o),e._isStdio||t&&!1===t.end||(r.on("end",s),r.on("close",u));var a=!1;function s(){a||(a=!0,e.end())}function u(){a||(a=!0,"function"==typeof e.destroy&&e.destroy())}function c(e){if(f(),0===n.listenerCount(this,"error"))throw e}function f(){r.removeListener("data",i),e.removeListener("drain",o),r.removeListener("end",s),r.removeListener("close",u),r.removeListener("error",c),e.removeListener("error",c),r.removeListener("end",f),r.removeListener("close",f),e.removeListener("close",f)}return r.on("error",c),e.on("error",c),r.on("end",f),r.on("close",f),e.on("close",f),e.emit("pipe",r),e}},{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(e,t,r){(function(t){var n=e("./lib/request"),i=e("./lib/response"),o=e("xtend"),a=e("builtin-status-codes"),s=e("url"),u=r;u.request=function(e,r){e="string"==typeof e?s.parse(e):o(e);var i=-1===t.location.protocol.search(/^https?:$/)?"http:":"",a=e.protocol||i,u=e.hostname||e.host,c=e.port,f=e.path||"/";u&&-1!==u.indexOf(":")&&(u="["+u+"]"),e.url=(u?a+"//"+u:"")+(c?":"+c:"")+f,e.method=(e.method||"GET").toUpperCase(),e.headers=e.headers||{};var h=new n(e);return r&&h.on("response",r),h},u.get=function(e,t){var r=u.request(e,t);return r.end(),r},u.ClientRequest=n,u.IncomingMessage=i,u.Agent=function(){},u.Agent.defaultMaxSockets=4,u.STATUS_CODES=a,u.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./lib/request":314,"./lib/response":315,"builtin-status-codes":85,url:327,xtend:423}],313:[function(e,t,r){(function(e){r.fetch=s(e.fetch)&&s(e.ReadableStream),r.writableStream=s(e.WritableStream),r.abortController=s(e.AbortController),r.blobConstructor=!1;try{new Blob([new ArrayBuffer(1)]),r.blobConstructor=!0}catch(e){}var t;function n(){if(void 0!==t)return t;if(e.XMLHttpRequest){t=new e.XMLHttpRequest;try{t.open("GET",e.XDomainRequest?"/":"https://example.com")}catch(e){t=null}}else t=null;return t}function i(e){var t=n();if(!t)return!1;try{return t.responseType=e,t.responseType===e}catch(e){}return!1}var o=void 0!==e.ArrayBuffer,a=o&&s(e.ArrayBuffer.prototype.slice);function s(e){return"function"==typeof e}r.arraybuffer=r.fetch||o&&i("arraybuffer"),r.msstream=!r.fetch&&a&&i("ms-stream"),r.mozchunkedarraybuffer=!r.fetch&&o&&i("moz-chunked-arraybuffer"),r.overrideMimeType=r.fetch||!!n()&&s(n().overrideMimeType),r.vbArray=s(e.VBArray),t=null}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],314:[function(e,t,r){(function(r,n,i){var o=e("./capability"),a=e("inherits"),s=e("./response"),u=e("readable-stream"),c=e("to-arraybuffer"),f=s.IncomingMessage,h=s.readyStates;var l=t.exports=function(e){var t,r=this;u.Writable.call(r),r._opts=e,r._body=[],r._headers={},e.auth&&r.setHeader("Authorization","Basic "+new i(e.auth).toString("base64")),Object.keys(e.headers).forEach(function(t){r.setHeader(t,e.headers[t])});var n=!0;if("disable-fetch"===e.mode||"requestTimeout"in e&&!o.abortController)n=!1,t=!0;else if("prefer-streaming"===e.mode)t=!1;else if("allow-wrong-content-type"===e.mode)t=!o.overrideMimeType;else{if(e.mode&&"default"!==e.mode&&"prefer-fast"!==e.mode)throw new Error("Invalid value for opts.mode");t=!0}r._mode=function(e,t){return o.fetch&&t?"fetch":o.mozchunkedarraybuffer?"moz-chunked-arraybuffer":o.msstream?"ms-stream":o.arraybuffer&&e?"arraybuffer":o.vbArray&&e?"text:vbarray":"text"}(t,n),r.on("finish",function(){r._onFinish()})};a(l,u.Writable),l.prototype.setHeader=function(e,t){var r=e.toLowerCase();-1===d.indexOf(r)&&(this._headers[r]={name:e,value:t})},l.prototype.getHeader=function(e){var t=this._headers[e.toLowerCase()];return t?t.value:null},l.prototype.removeHeader=function(e){delete this._headers[e.toLowerCase()]},l.prototype._onFinish=function(){var e=this;if(!e._destroyed){var t=e._opts,a=e._headers,s=null;"GET"!==t.method&&"HEAD"!==t.method&&(s=o.arraybuffer?c(i.concat(e._body)):o.blobConstructor?new n.Blob(e._body.map(function(e){return c(e)}),{type:(a["content-type"]||{}).value||""}):i.concat(e._body).toString());var u=[];if(Object.keys(a).forEach(function(e){var t=a[e].name,r=a[e].value;Array.isArray(r)?r.forEach(function(e){u.push([t,e])}):u.push([t,r])}),"fetch"===e._mode){var f=null;if(o.abortController){var l=new AbortController;f=l.signal,e._fetchAbortController=l,"requestTimeout"in t&&0!==t.requestTimeout&&n.setTimeout(function(){e.emit("requestTimeout"),e._fetchAbortController&&e._fetchAbortController.abort()},t.requestTimeout)}n.fetch(e._opts.url,{method:e._opts.method,headers:u,body:s||void 0,mode:"cors",credentials:t.withCredentials?"include":"same-origin",signal:f}).then(function(t){e._fetchResponse=t,e._connect()},function(t){e.emit("error",t)})}else{var d=e._xhr=new n.XMLHttpRequest;try{d.open(e._opts.method,e._opts.url,!0)}catch(t){return void r.nextTick(function(){e.emit("error",t)})}"responseType"in d&&(d.responseType=e._mode.split(":")[0]),"withCredentials"in d&&(d.withCredentials=!!t.withCredentials),"text"===e._mode&&"overrideMimeType"in d&&d.overrideMimeType("text/plain; charset=x-user-defined"),"requestTimeout"in t&&(d.timeout=t.requestTimeout,d.ontimeout=function(){e.emit("requestTimeout")}),u.forEach(function(e){d.setRequestHeader(e[0],e[1])}),e._response=null,d.onreadystatechange=function(){switch(d.readyState){case h.LOADING:case h.DONE:e._onXHRProgress()}},"moz-chunked-arraybuffer"===e._mode&&(d.onprogress=function(){e._onXHRProgress()}),d.onerror=function(){e._destroyed||e.emit("error",new Error("XHR error"))};try{d.send(s)}catch(t){return void r.nextTick(function(){e.emit("error",t)})}}}},l.prototype._onXHRProgress=function(){(function(e){try{var t=e.status;return null!==t&&0!==t}catch(e){return!1}})(this._xhr)&&!this._destroyed&&(this._response||this._connect(),this._response._onXHRProgress())},l.prototype._connect=function(){var e=this;e._destroyed||(e._response=new f(e._xhr,e._fetchResponse,e._mode),e._response.on("error",function(t){e.emit("error",t)}),e.emit("response",e._response))},l.prototype._write=function(e,t,r){this._body.push(e),r()},l.prototype.abort=l.prototype.destroy=function(){this._destroyed=!0,this._response&&(this._response._destroyed=!0),this._xhr?this._xhr.abort():this._fetchAbortController&&this._fetchAbortController.abort()},l.prototype.end=function(e,t,r){"function"==typeof e&&(r=e,e=void 0),u.Writable.prototype.end.call(this,e,t,r)},l.prototype.flushHeaders=function(){},l.prototype.setTimeout=function(){},l.prototype.setNoDelay=function(){},l.prototype.setSocketKeepAlive=function(){};var d=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","user-agent","via"]}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"./capability":313,"./response":315,_process:257,buffer:84,inherits:180,"readable-stream":285,"to-arraybuffer":323}],315:[function(e,t,r){(function(t,n,i){var o=e("./capability"),a=e("inherits"),s=e("readable-stream"),u=r.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},c=r.IncomingMessage=function(e,r,n){var a=this;if(s.Readable.call(a),a._mode=n,a.headers={},a.rawHeaders=[],a.trailers={},a.rawTrailers=[],a.on("end",function(){t.nextTick(function(){a.emit("close")})}),"fetch"===n){if(a._fetchResponse=r,a.url=r.url,a.statusCode=r.status,a.statusMessage=r.statusText,r.headers.forEach(function(e,t){a.headers[t.toLowerCase()]=e,a.rawHeaders.push(t,e)}),o.writableStream){var u=new WritableStream({write:function(e){return new Promise(function(t,r){a._destroyed||(a.push(new i(e))?t():a._resumeFetch=t)})},close:function(){a._destroyed||a.push(null)},abort:function(e){a._destroyed||a.emit("error",e)}});try{return void r.body.pipeTo(u)}catch(e){}}var c=r.body.getReader();!function e(){c.read().then(function(t){a._destroyed||(t.done?a.push(null):(a.push(new i(t.value)),e()))}).catch(function(e){a._destroyed||a.emit("error",e)})}()}else{if(a._xhr=e,a._pos=0,a.url=e.responseURL,a.statusCode=e.status,a.statusMessage=e.statusText,e.getAllResponseHeaders().split(/\r?\n/).forEach(function(e){var t=e.match(/^([^:]+):\s*(.*)/);if(t){var r=t[1].toLowerCase();"set-cookie"===r?(void 0===a.headers[r]&&(a.headers[r]=[]),a.headers[r].push(t[2])):void 0!==a.headers[r]?a.headers[r]+=", "+t[2]:a.headers[r]=t[2],a.rawHeaders.push(t[1],t[2])}}),a._charset="x-user-defined",!o.overrideMimeType){var f=a.rawHeaders["mime-type"];if(f){var h=f.match(/;\s*charset=([^;])(;|$)/);h&&(a._charset=h[1].toLowerCase())}a._charset||(a._charset="utf-8")}}};a(c,s.Readable),c.prototype._read=function(){var e=this._resumeFetch;e&&(this._resumeFetch=null,e())},c.prototype._onXHRProgress=function(){var e=this,t=e._xhr,r=null;switch(e._mode){case"text:vbarray":if(t.readyState!==u.DONE)break;try{r=new n.VBArray(t.responseBody).toArray()}catch(e){}if(null!==r){e.push(new i(r));break}case"text":try{r=t.responseText}catch(t){e._mode="text:vbarray";break}if(r.length>e._pos){var o=r.substr(e._pos);if("x-user-defined"===e._charset){for(var a=new i(o.length),s=0;se._pos&&(e.push(new i(new Uint8Array(c.result.slice(e._pos)))),e._pos=c.result.byteLength)},c.onload=function(){e.push(null)},c.readAsArrayBuffer(r)}e._xhr.readyState===u.DONE&&"ms-stream"!==e._mode&&e.push(null)}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"./capability":313,_process:257,buffer:84,inherits:180,"readable-stream":285}],316:[function(e,t,r){"use strict";t.exports=function(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}},{}],317:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=n.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function o(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(n.isEncoding===i||!i(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=u,this.end=c,t=4;break;case"utf8":this.fillLast=s,t=4;break;case"base64":this.text=f,this.end=h,t=3;break;default:return this.write=l,void(this.end=d)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(t)}function a(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:-1}function s(e){var t=this.lastTotal-this.lastNeed,r=function(e,t,r){if(128!=(192&t[0]))return e.lastNeed=0,"�".repeat(r);if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�".repeat(r+1);if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�".repeat(r+2)}}(this,e,t);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function u(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function c(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function f(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function h(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function l(e){return e.toString(this.encoding)}function d(e){return e&&e.length?this.write(e):""}r.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0)return i>0&&(e.lastNeed=i-1),i;if(--n=0)return i>0&&(e.lastNeed=i-2),i;if(--n=0)return i>0&&(2===i?i=0:e.lastNeed=i-3),i;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)},o.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},{"safe-buffer":290}],318:[function(e,t,r){var n=e("is-hex-prefixed");t.exports=function(e){return"string"!=typeof e?e:n(e)?e.slice(2):e}},{"is-hex-prefixed":185}],319:[function(e,t,r){var n=function(){throw"This swarm.js function isn't available on the browser."},i={readFile:n},o={download:n,safeDownloadArchived:n,directoryTree:n},a={platform:n,arch:n},s={join:n,slice:n},u={spawn:n},c={lookup:n},f=e("xhr-request-promise"),h=e("eth-lib/lib/bytes"),l=e("./swarm-hash.js"),d=e("./pick.js"),p=e("./swarm");t.exports=p({fsp:i,files:o,os:a,path:s,child_process:u,defaultArchives:{},mimetype:c,request:f,downloadUrl:null,bytes:h,hash:l,pick:d})},{"./pick.js":320,"./swarm":322,"./swarm-hash.js":321,"eth-lib/lib/bytes":133,"xhr-request-promise":411}],320:[function(e,t,r){var n=function(e){return function(){return new Promise(function(t,r){var n=function(r){var n={},i=r.target.files.length,o=0;[].map.call(r.target.files,function(r){var a=new FileReader;a.onload=function(a){var s=new Uint8Array(a.target.result);if("directory"===e){var u=r.webkitRelativePath;n[u.slice(u.indexOf("/")+1)]={type:"text/plain",data:s},++o===i&&t(n)}else if("file"===e){var c=r.webkitRelativePath;t({type:mimetype.lookup(c),data:s})}else t(s)},a.readAsArrayBuffer(r)})},i=void 0;"directory"===e?((i=document.createElement("input")).addEventListener("change",n),i.type="file",i.webkitdirectory=!0,i.mozdirectory=!0,i.msdirectory=!0,i.odirectory=!0,i.directory=!0):((i=document.createElement("input")).addEventListener("change",n),i.type="file");var o=document.createEvent("MouseEvents");o.initEvent("click",!0,!1),i.dispatchEvent(o)})}};t.exports={data:n("data"),file:n("file"),directory:n("directory")}},{}],321:[function(e,t,r){var n=e("eth-lib/lib/hash").keccak256,i=e("eth-lib/lib/bytes"),o=function(e,t){var r=i.reverse(i.pad(6,i.fromNumber(e))),o=i.flatten([r,"0x0000",t]);return n(o).slice(2)};t.exports=function e(t){"string"==typeof t&&"0x"!==t.slice(0,2)?t=i.fromString(t):"string"!=typeof t&&void 0!==t.length&&(t=i.fromUint8Array(t));var r=i.length(t);if(r<=4096)return o(r,t);for(var n=4096;128*n0){var a=i.join(r,o);n.push(g(e)(t[o])(a))}return Promise.all(n).then(function(){return r})})}}},_=function(e){return function(t){return u(e+"/bzzr:/",{body:"string"==typeof t?L(t):t,method:"POST"})}},A=function(e){return function(t){return function(r){return function(n){return function i(o){var a="/"===r[0]?r:"/"+r,s=e+"/bzz:/"+t+a,c={method:"PUT",headers:{"Content-Type":n.type},body:n.data};return u(s,c).then(function(e){if(-1!==e.indexOf("error"))throw e;return e}).catch(function(e){return o>0&&i(o-1)})}(3)}}}},E=function(e){return function(t){return k(e)({"":t})}},x=function(e){return function(r){return t.readFile(r).then(function(t){return E(e)({type:a.lookup(r),data:t})})}},k=function(e){return function(t){return _(e)("{}").then(function(r){return Object.keys(t).reduce(function(r,n){return r.then(function(r){return function(n){return A(e)(n)(r)(t[r])}}(n))},Promise.resolve(r))})}},S=function(e){return function(r){return t.readFile(r).then(_(e))}},M=function(e){return function(n){return function(i){return r.directoryTree(i).then(function(e){return Promise.all(e.map(function(e){return t.readFile(e)})).then(function(t){var r=e.map(function(e){return e.slice(i.length)}),n=e.map(function(e){return a.lookup(e)||"text/plain"});return d(r)(t.map(function(e,t){return{type:n[t],data:e}}))})}).then(function(e){return(t=n?{"":e[n]}:{},function(e){var r={};for(var n in t)r[n]=t[n];for(var i in e)r[i]=e[i];return r})(e);var t}).then(k(e))}}},I=function(e){return function(t){if("data"===t.pick)return l.data().then(_(e));if("file"===t.pick)return l.file().then(E(e));if("directory"===t.pick)return l.directory().then(k(e));if(t.path)switch(t.kind){case"data":return S(e)(t.path);case"file":return x(e)(t.path);case"directory":return M(e)(t.defaultFile)(t.path)}else{if(t.length||"string"==typeof t)return _(e)(t);if(t instanceof Object)return k(e)(t)}return Promise.reject(new Error("Bad arguments"))}},T=function(e){return function(t){return function(r){return C(e)(t).then(function(n){return n?r?w(e)(t)(r):v(e)(t):r?g(e)(t)(r):b(e)(t)})}}},U=function(e,t){var i=n.platform().replace("win32","windows")+"-"+("x64"===n.arch()?"amd64":"386"),o=(t||s)[i],a=c+o.archive+".tar.gz",u=o.archiveMD5,f=o.binaryMD5;return r.safeDownloadArchived(a)(u)(f)(e)},j=function(e){return new Promise(function(t,r){var n=o.spawn,i=function(e){return function(t){return-1!==(""+t).indexOf(e)}},a=e.account,s=e.password,u=e.dataDir,c=e.ensApi,f=e.privateKey,h=0,l=n(e.binPath,["--bzzaccount",a||f,"--datadir",u,"--ens-api",c]),d=function(e){0===h&&i("Passphrase")(e)?setTimeout(function(){h=1,l.stdin.write(s+"\n")},500):i("Swarm http proxy started")(e)&&(h=2,clearTimeout(p),t(l))};l.stdout.on("data",d),l.stderr.on("data",d);var p=setTimeout(function(){return r(new Error("Couldn't start swarm process."))},2e4)})},B=function(e){return new Promise(function(t,r){e.stderr.removeAllListeners("data"),e.stdout.removeAllListeners("data"),e.stdin.removeAllListeners("error"),e.removeAllListeners("error"),e.removeAllListeners("exit"),e.kill("SIGINT");var n=setTimeout(function(){return e.kill("SIGKILL")},8e3);e.once("close",function(){clearTimeout(n),t()})})},P=function(e){return _(e)("test").then(function(e){return"c9a99c7d326dcc6316f32fe2625b311f6dc49a175e6877681ded93137d3569e7"===e}).catch(function(){return!1})},C=function(e){return function(t){return b(e)(t).then(function(e){try{return!!JSON.parse(R(e)).entries}catch(e){return!1}})}},N=function(e){return function(t,r,n,i,o){var a;return void 0!==t&&(a=e(t)),void 0!==r&&(a=e(r)),void 0!==n&&(a=e(n)),void 0!==i&&(a=e(i)),void 0!==o&&(a=e(o)),a}},R=function(e){return f.toString(f.fromUint8Array(e))},L=function(e){return f.toUint8Array(f.fromString(e))},O=function(e){return{download:function(t,r){return T(e)(t)(r)},downloadData:N(b(e)),downloadDataToDisk:N(g(e)),downloadDirectory:N(v(e)),downloadDirectoryToDisk:N(w(e)),downloadEntries:N(y(e)),downloadRoutes:N(m(e)),isAvailable:function(){return P(e)},upload:function(t){return I(e)(t)},uploadData:N(_(e)),uploadFile:N(E(e)),uploadFileFromDisk:N(E(e)),uploadDataFromDisk:N(S(e)),uploadDirectory:N(k(e)),uploadDirectoryFromDisk:N(M(e)),uploadToManifest:N(A(e)),pick:l,hash:h,fromString:L,toString:R}};return{at:O,local:function(e){return function(t){return P("http://localhost:8500").then(function(r){return r?t(O("http://localhost:8500")).then(function(){}):U(e.binPath,e.archives).onData(function(t){return(e.onProgress||function(){})(t.length)}).then(function(){return j(e)}).then(function(e){return t(O("http://localhost:8500")).then(function(){return e})}).then(B)})}},download:T,downloadBinary:U,downloadData:b,downloadDataToDisk:g,downloadDirectory:v,downloadDirectoryToDisk:w,downloadEntries:y,downloadRoutes:m,isAvailable:P,startProcess:j,stopProcess:B,upload:I,uploadData:_,uploadDataFromDisk:S,uploadFile:E,uploadFileFromDisk:x,uploadDirectory:k,uploadDirectoryFromDisk:M,uploadToManifest:A,pick:l,hash:h,fromString:L,toString:R}}},{}],323:[function(e,t,r){var n=e("buffer").Buffer;t.exports=function(e){if(e instanceof Uint8Array){if(0===e.byteOffset&&e.byteLength===e.buffer.byteLength)return e.buffer;if("function"==typeof e.buffer.slice)return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}if(n.isBuffer(e)){for(var t=new Uint8Array(e.length),r=e.length,i=0;i=0&&t<=A};function k(e){return function(t,r,n,i){r=m(r,i,4);var o=!x(t)&&y.keys(t),a=(o||t).length,s=e>0?0:a-1;return arguments.length<3&&(n=t[o?o[s]:s],s+=e),function(t,r,n,i,o,a){for(;o>=0&&o=0},y.invoke=function(e,t){var r=u.call(arguments,2),n=y.isFunction(t);return y.map(e,function(e){var i=n?t:e[t];return null==i?i:i.apply(e,r)})},y.pluck=function(e,t){return y.map(e,y.property(t))},y.where=function(e,t){return y.filter(e,y.matcher(t))},y.findWhere=function(e,t){return y.find(e,y.matcher(t))},y.max=function(e,t,r){var n,i,o=-1/0,a=-1/0;if(null==t&&null!=e)for(var s=0,u=(e=x(e)?e:y.values(e)).length;so&&(o=n);else t=v(t,r),y.each(e,function(e,r,n){((i=t(e,r,n))>a||i===-1/0&&o===-1/0)&&(o=e,a=i)});return o},y.min=function(e,t,r){var n,i,o=1/0,a=1/0;if(null==t&&null!=e)for(var s=0,u=(e=x(e)?e:y.values(e)).length;sn||void 0===r)return 1;if(r0?0:i-1;o>=0&&o0?a=o>=0?o:Math.max(o+s,a):s=o>=0?Math.min(o+1,s):o+s+1;else if(r&&o&&s)return n[o=r(n,i)]===i?o:-1;if(i!=i)return(o=t(u.call(n,a,s),y.isNaN))>=0?o+a:-1;for(o=e>0?a:s-1;o>=0&&ot?(a&&(clearTimeout(a),a=null),s=c,o=e.apply(n,i),a||(n=i=null)):a||!1===r.trailing||(a=setTimeout(u,f)),o}},y.debounce=function(e,t,r){var n,i,o,a,s,u=function(){var c=y.now()-a;c=0?n=setTimeout(u,t-c):(n=null,r||(s=e.apply(o,i),n||(o=i=null)))};return function(){o=this,i=arguments,a=y.now();var c=r&&!n;return n||(n=setTimeout(u,t)),c&&(s=e.apply(o,i),o=i=null),s}},y.wrap=function(e,t){return y.partial(t,e)},y.negate=function(e){return function(){return!e.apply(this,arguments)}},y.compose=function(){var e=arguments,t=e.length-1;return function(){for(var r=t,n=e[t].apply(this,arguments);r--;)n=e[r].call(this,n);return n}},y.after=function(e,t){return function(){if(--e<1)return t.apply(this,arguments)}},y.before=function(e,t){var r;return function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=null),r}},y.once=y.partial(y.before,2);var j=!{toString:null}.propertyIsEnumerable("toString"),B=["valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"];function P(e,t){var r=B.length,n=e.constructor,i=y.isFunction(n)&&n.prototype||o,a="constructor";for(y.has(e,a)&&!y.contains(t,a)&&t.push(a);r--;)(a=B[r])in e&&e[a]!==i[a]&&!y.contains(t,a)&&t.push(a)}y.keys=function(e){if(!y.isObject(e))return[];if(l)return l(e);var t=[];for(var r in e)y.has(e,r)&&t.push(r);return j&&P(e,t),t},y.allKeys=function(e){if(!y.isObject(e))return[];var t=[];for(var r in e)t.push(r);return j&&P(e,t),t},y.values=function(e){for(var t=y.keys(e),r=t.length,n=Array(r),i=0;i":">",'"':""","'":"'","`":"`"},R=y.invert(N),L=function(e){var t=function(t){return e[t]},r="(?:"+y.keys(e).join("|")+")",n=RegExp(r),i=RegExp(r,"g");return function(e){return e=null==e?"":""+e,n.test(e)?e.replace(i,t):e}};y.escape=L(N),y.unescape=L(R),y.result=function(e,t,r){var n=null==e?void 0:e[t];return void 0===n&&(n=r),y.isFunction(n)?n.call(e):n};var O=0;y.uniqueId=function(e){var t=++O+"";return e?e+t:t},y.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var D=/(.)^/,F={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},q=/\\|'|\r|\n|\u2028|\u2029/g,H=function(e){return"\\"+F[e]};y.template=function(e,t,r){!t&&r&&(t=r),t=y.defaults({},t,y.templateSettings);var n=RegExp([(t.escape||D).source,(t.interpolate||D).source,(t.evaluate||D).source].join("|")+"|$","g"),i=0,o="__p+='";e.replace(n,function(t,r,n,a,s){return o+=e.slice(i,s).replace(q,H),i=s+t.length,r?o+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'":n?o+="'+\n((__t=("+n+"))==null?'':__t)+\n'":a&&(o+="';\n"+a+"\n__p+='"),t}),o+="';\n",t.variable||(o="with(obj||{}){\n"+o+"}\n"),o="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+o+"return __p;\n";try{var a=new Function(t.variable||"obj","_",o)}catch(e){throw e.source=o,e}var s=function(e){return a.call(this,e,y)},u=t.variable||"obj";return s.source="function("+u+"){\n"+o+"}",s},y.chain=function(e){var t=y(e);return t._chain=!0,t};var z=function(e,t){return e._chain?y(t).chain():t};y.mixin=function(e){y.each(y.functions(e),function(t){var r=y[t]=e[t];y.prototype[t]=function(){var e=[this._wrapped];return s.apply(e,arguments),z(this,r.apply(y,e))}})},y.mixin(y),y.each(["pop","push","reverse","shift","sort","splice","unshift"],function(e){var t=i[e];y.prototype[e]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!==e&&"splice"!==e||0!==r.length||delete r[0],z(this,r)}}),y.each(["concat","join","slice"],function(e){var t=i[e];y.prototype[e]=function(){return z(this,t.apply(this._wrapped,arguments))}}),y.prototype.value=function(){return this._wrapped},y.prototype.valueOf=y.prototype.toJSON=y.prototype.value,y.prototype.toString=function(){return""+this._wrapped},"function"==typeof define&&define.amd&&define("underscore",[],function(){return y})}).call(this)},{}],326:[function(e,t,r){t.exports=function(e,t){if(t){t=(t=t.trim().replace(/^(\?|#|&)/,""))?"?"+t:t;var r=e.split(/[\?\#]/),n=r[0];t&&/\:\/\/[^\/]*$/.test(n)&&(n+="/");var i=e.match(/(\#.*)$/);e=n+t,i&&(e+=i[0])}return e}},{}],327:[function(e,t,r){"use strict";var n=e("punycode"),i=e("./util");function o(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}r.parse=g,r.resolve=function(e,t){return g(e,!1,!0).resolve(t)},r.resolveObject=function(e,t){return e?g(e,!1,!0).resolveObject(t):t},r.format=function(e){i.isString(e)&&(e=g(e));return e instanceof o?e.format():o.prototype.format.call(e)},r.Url=o;var a=/^([a-z0-9.+-]+:)/i,s=/:[0-9]*$/,u=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,c=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),f=["'"].concat(c),h=["%","/","?",";","#"].concat(f),l=["/","?","#"],d=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,b={javascript:!0,"javascript:":!0},y={javascript:!0,"javascript:":!0},m={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},v=e("querystring");function g(e,t,r){if(e&&i.isObject(e)&&e instanceof o)return e;var n=new o;return n.parse(e,t,r),n}o.prototype.parse=function(e,t,r){if(!i.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var o=e.indexOf("?"),s=-1!==o&&o127?P+="x":P+=B[C];if(!P.match(d)){var R=U.slice(0,M),L=U.slice(M+1),O=B.match(p);O&&(R.push(O[1]),L.unshift(O[2])),L.length&&(g="/"+L.join(".")+g),this.hostname=R.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),T||(this.hostname=n.toASCII(this.hostname));var D=this.port?":"+this.port:"",F=this.hostname||"";this.host=F+D,this.href+=this.host,T&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==g[0]&&(g="/"+g))}if(!b[A])for(M=0,j=f.length;M0)&&r.host.split("@"))&&(r.auth=T.shift(),r.host=r.hostname=T.shift());return r.search=e.search,r.query=e.query,i.isNull(r.pathname)&&i.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!E.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var k=E.slice(-1)[0],S=(r.host||e.host||E.length>1)&&("."===k||".."===k)||""===k,M=0,I=E.length;I>=0;I--)"."===(k=E[I])?E.splice(I,1):".."===k?(E.splice(I,1),M++):M&&(E.splice(I,1),M--);if(!_&&!A)for(;M--;M)E.unshift("..");!_||""===E[0]||E[0]&&"/"===E[0].charAt(0)||E.unshift(""),S&&"/"!==E.join("/").substr(-1)&&E.push("");var T,U=""===E[0]||E[0]&&"/"===E[0].charAt(0);x&&(r.hostname=r.host=U?"":E.length?E.shift():"",(T=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@"))&&(r.auth=T.shift(),r.host=r.hostname=T.shift()));return(_=_||r.host&&E.length)&&!U&&E.unshift(""),E.length?r.pathname=E.join("/"):(r.pathname=null,r.path=null),i.isNull(r.pathname)&&i.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=e.auth||r.auth,r.slashes=r.slashes||e.slashes,r.href=r.format(),r},o.prototype.parseHost=function(){var e=this.host,t=s.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{"./util":328,punycode:265,querystring:269}],328:[function(e,t,r){"use strict";t.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},{}],329:[function(e,t,r){(function(e){!function(n){var i="object"==typeof r&&r,o="object"==typeof t&&t&&t.exports==i&&t,a="object"==typeof e&&e;a.global!==a&&a.window!==a||(n=a);var s,u,c,f=String.fromCharCode;function h(e){for(var t,r,n=[],i=0,o=e.length;i=55296&&t<=56319&&i=55296&&e<=57343)throw Error("Lone surrogate U+"+e.toString(16).toUpperCase()+" is not a scalar value")}function d(e,t){return f(e>>t&63|128)}function p(e){if(0==(4294967168&e))return f(e);var t="";return 0==(4294965248&e)?t=f(e>>6&31|192):0==(4294901760&e)?(l(e),t=f(e>>12&15|224),t+=d(e,6)):0==(4292870144&e)&&(t=f(e>>18&7|240),t+=d(e,12),t+=d(e,6)),t+=f(63&e|128)}function b(){if(c>=u)throw Error("Invalid byte index");var e=255&s[c];if(c++,128==(192&e))return 63&e;throw Error("Invalid continuation byte")}function y(){var e,t;if(c>u)throw Error("Invalid byte index");if(c==u)return!1;if(e=255&s[c],c++,0==(128&e))return e;if(192==(224&e)){if((t=(31&e)<<6|b())>=128)return t;throw Error("Invalid continuation byte")}if(224==(240&e)){if((t=(15&e)<<12|b()<<6|b())>=2048)return l(t),t;throw Error("Invalid continuation byte")}if(240==(248&e)&&(t=(15&e)<<18|b()<<12|b()<<6|b())>=65536&&t<=1114111)return t;throw Error("Invalid UTF-8 detected")}var m={version:"2.0.0",encode:function(e){for(var t=h(e),r=t.length,n=-1,i="";++n65535&&(i+=f((t-=65536)>>>10&1023|55296),t=56320|1023&t),i+=f(t);return i}(r)}};if("function"==typeof define&&"object"==typeof define.amd&&define.amd)define(function(){return m});else if(i&&!i.nodeType)if(o)o.exports=m;else{var v={}.hasOwnProperty;for(var g in m)v.call(m,g)&&(i[g]=m[g])}else n.utf8=m}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],330:[function(e,t,r){(function(e){function r(t){try{if(!e.localStorage)return!1}catch(e){return!1}var r=e.localStorage[t];return null!=r&&"true"===String(r).toLowerCase()}t.exports=function(e,t){if(r("noDeprecation"))return e;var n=!1;return function(){if(!n){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],331:[function(e,t,r){arguments[4][180][0].apply(r,arguments)},{dup:180}],332:[function(e,t,r){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],333:[function(e,t,r){(function(t,n){var i=/%[sdj%]/g;r.format=function(e){if(!m(e)){for(var t=[],r=0;r=o)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(e){return"[Circular]"}default:return e}}),u=n[r];r=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),p(t)?n.showHidden=t:t&&r._extend(n,t),v(n.showHidden)&&(n.showHidden=!1),v(n.depth)&&(n.depth=2),v(n.colors)&&(n.colors=!1),v(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=u),f(n,e,n.depth)}function u(e,t){var r=s.styles[t];return r?"["+s.colors[r][0]+"m"+e+"["+s.colors[r][1]+"m":e}function c(e,t){return e}function f(e,t,n){if(e.customInspect&&t&&E(t.inspect)&&t.inspect!==r.inspect&&(!t.constructor||t.constructor.prototype!==t)){var i=t.inspect(n,e);return m(i)||(i=f(e,i,n)),i}var o=function(e,t){if(v(t))return e.stylize("undefined","undefined");if(m(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(y(t))return e.stylize(""+t,"number");if(p(t))return e.stylize(""+t,"boolean");if(b(t))return e.stylize("null","null")}(e,t);if(o)return o;var a=Object.keys(t),s=function(e){var t={};return e.forEach(function(e,r){t[e]=!0}),t}(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(t)),A(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return h(t);if(0===a.length){if(E(t)){var u=t.name?": "+t.name:"";return e.stylize("[Function"+u+"]","special")}if(g(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(_(t))return e.stylize(Date.prototype.toString.call(t),"date");if(A(t))return h(t)}var c,w="",x=!1,k=["{","}"];(d(t)&&(x=!0,k=["[","]"]),E(t))&&(w=" [Function"+(t.name?": "+t.name:"")+"]");return g(t)&&(w=" "+RegExp.prototype.toString.call(t)),_(t)&&(w=" "+Date.prototype.toUTCString.call(t)),A(t)&&(w=" "+h(t)),0!==a.length||x&&0!=t.length?n<0?g(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),c=x?function(e,t,r,n,i){for(var o=[],a=0,s=t.length;a=0&&0,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60)return r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1];return r[0]+t+" "+e.join(", ")+" "+r[1]}(c,w,k)):k[0]+w+k[1]}function h(e){return"["+Error.prototype.toString.call(e)+"]"}function l(e,t,r,n,i,o){var a,s,u;if((u=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]}).get?s=u.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):u.set&&(s=e.stylize("[Setter]","special")),M(n,i)||(a="["+i+"]"),s||(e.seen.indexOf(u.value)<0?(s=b(r)?f(e,u.value,null):f(e,u.value,r-1)).indexOf("\n")>-1&&(s=o?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n")):s=e.stylize("[Circular]","special")),v(a)){if(o&&i.match(/^\d+$/))return s;(a=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function d(e){return Array.isArray(e)}function p(e){return"boolean"==typeof e}function b(e){return null===e}function y(e){return"number"==typeof e}function m(e){return"string"==typeof e}function v(e){return void 0===e}function g(e){return w(e)&&"[object RegExp]"===x(e)}function w(e){return"object"==typeof e&&null!==e}function _(e){return w(e)&&"[object Date]"===x(e)}function A(e){return w(e)&&("[object Error]"===x(e)||e instanceof Error)}function E(e){return"function"==typeof e}function x(e){return Object.prototype.toString.call(e)}function k(e){return e<10?"0"+e.toString(10):e.toString(10)}r.debuglog=function(e){if(v(o)&&(o=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!a[e])if(new RegExp("\\b"+e+"\\b","i").test(o)){var n=t.pid;a[e]=function(){var t=r.format.apply(r,arguments);console.error("%s %d: %s",e,n,t)}}else a[e]=function(){};return a[e]},r.inspect=s,s.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},s.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},r.isArray=d,r.isBoolean=p,r.isNull=b,r.isNullOrUndefined=function(e){return null==e},r.isNumber=y,r.isString=m,r.isSymbol=function(e){return"symbol"==typeof e},r.isUndefined=v,r.isRegExp=g,r.isObject=w,r.isDate=_,r.isError=A,r.isFunction=E,r.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},r.isBuffer=e("./support/isBuffer");var S=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function M(e,t){return Object.prototype.hasOwnProperty.call(e,t)}r.log=function(){var e,t;console.log("%s - %s",(e=new Date,t=[k(e.getHours()),k(e.getMinutes()),k(e.getSeconds())].join(":"),[e.getDate(),S[e.getMonth()],t].join(" ")),r.format.apply(r,arguments))},r.inherits=e("inherits"),r._extend=function(e,t){if(!t||!w(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":332,_process:257,inherits:331}],334:[function(require,module,exports){var indexOf=require("indexof"),Object_keys=function(e){if(Object.keys)return Object.keys(e);var t=[];for(var r in e)t.push(r);return t},forEach=function(e,t){if(e.forEach)return e.forEach(t);for(var r=0;r1?(e[r[0]]=e[r[0]]||{},e[r[0]][r[1]]=t):e[r[0]]=t},c.prototype.getCall=function(e){return n.isFunction(this.call)?this.call(e):this.call},c.prototype.extractCallback=function(e){if(n.isFunction(e[e.length-1]))return e.pop()},c.prototype.validateArgs=function(e){if(e.length!==this.params)throw i.InvalidNumberOfParams(e.length,this.params,this.name)},c.prototype.formatInput=function(e){var t=this;return this.inputFormatter?this.inputFormatter.map(function(r,n){return r?r.call(t,e[n]):e[n]}):e},c.prototype.formatOutput=function(e){var t=this;return n.isArray(e)?e.map(function(e){return t.outputFormatter&&e?t.outputFormatter(e):e}):this.outputFormatter&&e?this.outputFormatter(e):e},c.prototype.toPayload=function(e){var t=this.getCall(e),r=this.extractCallback(e),n=this.formatInput(e);this.validateArgs(n);var i={method:t,params:n,callback:r};return this.transformPayload&&(i=this.transformPayload(i)),i},c.prototype._confirmTransaction=function(e,t,r){var i=this,f=!1,h=!0,l=0,d=0,p=null,b="",y=n.isObject(r.params[0])&&r.params[0].gas?r.params[0].gas:null,m=n.isObject(r.params[0])&&r.params[0].data&&r.params[0].from&&!r.params[0].to,v=[new c({name:"getTransactionReceipt",call:"eth_getTransactionReceipt",params:1,inputFormatter:[null],outputFormatter:o.outputTransactionReceiptFormatter}),new c({name:"getCode",call:"eth_getCode",params:2,inputFormatter:[o.inputAddressFormatter,o.inputDefaultBlockNumberFormatter]}),new u({name:"subscribe",type:"eth",subscriptions:{newBlockHeaders:{subscriptionName:"newHeads",params:0,outputFormatter:o.outputBlockFormatter}}})],g={};n.each(v,function(e){e.attachToObject(g),e.requestManager=i.requestManager});var w=function(r,n,o,u,c){if(!o)return c||(c={unsubscribe:function(){clearInterval(p)}}),(r?s.resolve(r):g.getTransactionReceipt(t)).catch(function(t){c.unsubscribe(),f=!0,a._fireError({message:"Failed to check for transaction receipt:",data:t},e.eventEmitter,e.reject)}).then(function(t){if(!t||!t.blockHash)throw new Error("Receipt missing or blockHash null");return i.extraFormatters&&i.extraFormatters.receiptFormatter&&(t=i.extraFormatters.receiptFormatter(t)),e.eventEmitter.listeners("confirmation").length>0&&(void 0!==r&&0===d||e.eventEmitter.emit("confirmation",d,t),h=!1,25===++d&&(c.unsubscribe(),e.eventEmitter.removeAllListeners())),t}).then(function(t){if(m&&!f){if(!t.contractAddress)return h&&(c.unsubscribe(),f=!0),void a._fireError(new Error("The transaction receipt didn't contain a contract address."),e.eventEmitter,e.reject);g.getCode(t.contractAddress,function(r,n){n&&(n.length>2?(e.eventEmitter.emit("receipt",t),i.extraFormatters&&i.extraFormatters.contractDeployFormatter?e.resolve(i.extraFormatters.contractDeployFormatter(t)):e.resolve(t),h&&e.eventEmitter.removeAllListeners()):a._fireError(new Error("The contract code couldn't be stored, please check your gas limit."),e.eventEmitter,e.reject),h&&c.unsubscribe(),f=!0)})}return t}).then(function(t){m||f||(t.outOfGas||y&&y===t.gasUsed||!0!==t.status&&"0x1"!==t.status&&void 0!==t.status?(b=JSON.stringify(t,null,2),!1===t.status||"0x0"===t.status?a._fireError(new Error("Transaction has been reverted by the EVM:\n"+b),e.eventEmitter,e.reject):a._fireError(new Error("Transaction ran out of gas. Please provide more gas:\n"+b),e.eventEmitter,e.reject)):(e.eventEmitter.emit("receipt",t),e.resolve(t),h&&e.eventEmitter.removeAllListeners()),h&&c.unsubscribe(),f=!0)}).catch(function(){l++,n?l-1>=750&&(c.unsubscribe(),f=!0,a._fireError(new Error("Transaction was not mined within750 seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!"),e.eventEmitter,e.reject)):l-1>=50&&(c.unsubscribe(),f=!0,a._fireError(new Error("Transaction was not mined within 50 blocks, please make sure your transaction was properly sent. Be aware that it might still be mined!"),e.eventEmitter,e.reject))});c.unsubscribe(),f=!0,a._fireError({message:"Failed to subscribe to new newBlockHeaders to confirm the transaction receipts.",data:o},e.eventEmitter,e.reject)},_=function(e){n.isFunction(this.requestManager.provider.on)?g.subscribe("newBlockHeaders",w.bind(null,e,!1)):p=setInterval(w.bind(null,e,!0),1e3)}.bind(this);g.getTransactionReceipt(t).then(function(t){t&&t.blockHash?(e.eventEmitter.listeners("confirmation").length>0&&_(t),w(t,!1)):f||_()}).catch(function(){f||_()})};var f=function(e,t){return n.isNumber(e)?t.wallet[e]:n.isObject(e)&&e.address&&e.privateKey?e:t.wallet[e.toLowerCase()]};c.prototype.buildCall=function(){var e=this,t="eth_sendTransaction"===e.call||"eth_sendRawTransaction"===e.call,r=function(){var r=s(!t),i=e.toPayload(Array.prototype.slice.call(arguments)),o=function(n,o){try{o=e.formatOutput(o)}catch(e){n=e}if(o instanceof Error&&(n=o),n)return n.error&&(n=n.error),a._fireError(n,r.eventEmitter,r.reject,i.callback);i.callback&&i.callback(null,o),t?(r.eventEmitter.emit("transactionHash",o),e._confirmTransaction(r,o,i)):n||r.resolve(o)},u=function(t){var r=n.extend({},i,{method:"eth_sendRawTransaction",params:[t.rawTransaction]});e.requestManager.send(r,o)},h=function(e,t){var i;if(t&&t.accounts&&t.accounts.wallet&&t.accounts.wallet.length)if("eth_sendTransaction"===e.method){var a=e.params[0];if((i=f(n.isObject(a)?a.from:null,t.accounts))&&i.privateKey)return t.accounts.signTransaction(n.omit(a,"from"),i.privateKey).then(u)}else if("eth_sign"===e.method){var s=e.params[1];if((i=f(e.params[0],t.accounts))&&i.privateKey){var c=t.accounts.sign(s,i.privateKey);return e.callback&&e.callback(null,c.signature),void r.resolve(c.signature)}}return t.requestManager.send(e,o)};t&&n.isObject(i.params[0])&&void 0===i.params[0].gasPrice?new c({name:"getGasPrice",call:"eth_gasPrice",params:0}).createFunction(e.requestManager)(function(t,r){r&&(i.params[0].gasPrice=r),h(i,e)}):h(i,e);return r.eventEmitter};return r.method=e,r.request=this.request.bind(this),r},c.prototype.request=function(){var e=this.toPayload(Array.prototype.slice.call(arguments));return e.format=this.formatOutput.bind(this),e},t.exports=c},{underscore:325,"web3-core-helpers":338,"web3-core-promievent":340,"web3-core-subscriptions":345,"web3-utils":403}],340:[function(e,t,r){"use strict";var n=e("eventemitter3"),i=e("any-promise"),o=function(e){var t,r,o=new i(function(){t=arguments[0],r=arguments[1]});if(e)return{resolve:t,reject:r,eventEmitter:o};var a=new n;return o._events=a._events,o.emit=a.emit,o.on=a.on,o.once=a.once,o.off=a.off,o.listeners=a.listeners,o.addListener=a.addListener,o.removeListener=a.removeListener,o.removeAllListeners=a.removeAllListeners,{resolve:t,reject:r,eventEmitter:o}};o.resolve=function(e){var t=o(!0);return t.resolve(e),t.eventEmitter},t.exports=o},{"any-promise":2,eventemitter3:156}],341:[function(e,t,r){"use strict";var n=e("./jsonrpc"),i=e("web3-core-helpers").errors,o=function(e){this.requestManager=e,this.requests=[]};o.prototype.add=function(e){this.requests.push(e)},o.prototype.execute=function(){var e=this.requests;this.requestManager.sendBatch(e,function(t,r){r=r||[],e.map(function(e,t){return r[t]||{}}).forEach(function(t,r){if(e[r].callback){if(t&&t.error)return e[r].callback(i.ErrorResponse(t));if(!n.isValidResponse(t))return e[r].callback(i.InvalidResponse(t));try{e[r].callback(null,e[r].format?e[r].format(t.result):t.result)}catch(t){e[r].callback(t)}}})})},t.exports=o},{"./jsonrpc":344,"web3-core-helpers":338}],342:[function(e,t,r){"use strict";var n=null,i=window;void 0!==i.ethereumProvider?n=i.ethereumProvider:void 0!==i.web3&&i.web3.currentProvider&&(i.web3.currentProvider.sendAsync&&(i.web3.currentProvider.send=i.web3.currentProvider.sendAsync,delete i.web3.currentProvider.sendAsync),!i.web3.currentProvider.on&&i.web3.currentProvider.connection&&"ipcProviderWrapper"===i.web3.currentProvider.connection.constructor.name&&(i.web3.currentProvider.on=function(e,t){if("function"!=typeof t)throw new Error("The second parameter callback must be a function.");switch(e){case"data":this.connection.on("data",function(e){var r="";e=e.toString();try{r=JSON.parse(e)}catch(r){return t(new Error("Couldn't parse response data"+e))}r.id||-1===r.method.indexOf("_subscription")||t(null,r)});break;default:this.connection.on(e,t)}}),n=i.web3.currentProvider),t.exports=n},{}],343:[function(e,t,r){"use strict";var n=e("underscore"),i=e("web3-core-helpers").errors,o=e("./jsonrpc.js"),a=e("./batch.js"),s=e("./givenProvider.js"),u=function e(t){this.provider=null,this.providers=e.providers,this.setProvider(t),this.subscriptions={}};u.givenProvider=s,u.providers={WebsocketProvider:e("web3-providers-ws"),HttpProvider:e("web3-providers-http"),IpcProvider:e("web3-providers-ipc")},u.prototype.setProvider=function(e,t){var r=this;if(e&&"string"==typeof e&&this.providers)if(/^http(s)?:\/\//i.test(e))e=new this.providers.HttpProvider(e);else if(/^ws(s)?:\/\//i.test(e))e=new this.providers.WebsocketProvider(e);else if(e&&"object"==typeof t&&"function"==typeof t.connect)e=new this.providers.IpcProvider(e,t);else if(e)throw new Error("Can't autodetect provider for \""+e+'"');this.provider&&this.provider.connected&&this.clearSubscriptions(),this.provider=e||null,this.provider&&this.provider.on&&this.provider.on("data",function(e,t){(e=e||t).method&&r.subscriptions[e.params.subscription]&&r.subscriptions[e.params.subscription].callback&&r.subscriptions[e.params.subscription].callback(null,e.params.result)})},u.prototype.send=function(e,t){if(t=t||function(){},!this.provider)return t(i.InvalidProvider());var r=o.toPayload(e.method,e.params);this.provider[this.provider.sendAsync?"sendAsync":"send"](r,function(e,n){return n&&n.id&&r.id!==n.id?t(new Error('Wrong response id "'+n.id+'" (expected: "'+r.id+'") in '+JSON.stringify(r))):e?t(e):n&&n.error?t(i.ErrorResponse(n)):o.isValidResponse(n)?void t(null,n.result):t(i.InvalidResponse(n))})},u.prototype.sendBatch=function(e,t){if(!this.provider)return t(i.InvalidProvider());var r=o.toBatchPayload(e);this.provider[this.provider.sendAsync?"sendAsync":"send"](r,function(e,r){return e?t(e):n.isArray(r)?void t(null,r):t(i.InvalidResponse(r))})},u.prototype.addSubscription=function(e,t,r,n){if(!this.provider.on)throw new Error("The provider doesn't support subscriptions: "+this.provider.constructor.name);this.subscriptions[e]={callback:n,type:r,name:t}},u.prototype.removeSubscription=function(e,t){this.subscriptions[e]&&(this.send({method:this.subscriptions[e].type+"_unsubscribe",params:[e]},t),delete this.subscriptions[e])},u.prototype.clearSubscriptions=function(e){var t=this;Object.keys(this.subscriptions).forEach(function(r){e&&"syncing"===t.subscriptions[r].name||t.removeSubscription(r)}),this.provider.reset&&this.provider.reset()},t.exports={Manager:u,BatchManager:a}},{"./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(e,t,r){"use strict";var n={messageId:0,toPayload:function(e,t){if(!e)throw new Error('JSONRPC method should be specified for params: "'+JSON.stringify(t)+'"!');return n.messageId++,{jsonrpc:"2.0",id:n.messageId,method:e,params:t||[]}},isValidResponse:function(e){return Array.isArray(e)?e.every(t):t(e);function t(e){return!(!e||e.error||"2.0"!==e.jsonrpc||"number"!=typeof e.id&&"string"!=typeof e.id||void 0===e.result)}},toBatchPayload:function(e){return e.map(function(e){return n.toPayload(e.method,e.params)})}};t.exports=n},{}],345:[function(e,t,r){"use strict";var n=e("./subscription.js"),i=function(e){this.name=e.name,this.type=e.type,this.subscriptions=e.subscriptions||{},this.requestManager=null};i.prototype.setRequestManager=function(e){this.requestManager=e},i.prototype.attachToObject=function(e){var t=this.buildCall(),r=this.name.split(".");r.length>1?(e[r[0]]=e[r[0]]||{},e[r[0]][r[1]]=t):e[r[0]]=t},i.prototype.buildCall=function(){var e=this;return function(){e.subscriptions[arguments[0]]||console.warn("Subscription "+JSON.stringify(arguments[0])+" doesn't exist. Subscribing anyway.");var t=new n({subscription:e.subscriptions[arguments[0]],requestManager:e.requestManager,type:e.type});return t.subscribe.apply(t,arguments)}},t.exports={subscriptions:i,subscription:n}},{"./subscription.js":346}],346:[function(e,t,r){"use strict";var n=e("underscore"),i=e("web3-core-helpers").errors,o=e("eventemitter3");function a(e){o.call(this),this.id=null,this.callback=n.identity,this.arguments=null,this._reconnectIntervalId=null,this.options={subscription:e.subscription,type:e.type,requestManager:e.requestManager}}a.prototype=Object.create(o.prototype),a.prototype.constructor=a,a.prototype._extractCallback=function(e){if(n.isFunction(e[e.length-1]))return e.pop()},a.prototype._validateArgs=function(e){var t=this.options.subscription;if(t||(t={}),t.params||(t.params=0),e.length!==t.params)throw i.InvalidNumberOfParams(e.length,t.params+1,e[0])},a.prototype._formatInput=function(e){var t=this.options.subscription;return t&&t.inputFormatter?t.inputFormatter.map(function(t,r){return t?t(e[r]):e[r]}):e},a.prototype._formatOutput=function(e){var t=this.options.subscription;return t&&t.outputFormatter&&e?t.outputFormatter(e):e},a.prototype._toPayload=function(e){var t=[];if(this.callback=this._extractCallback(e)||n.identity,this.subscriptionMethod||(this.subscriptionMethod=e.shift(),this.options.subscription.subscriptionName&&(this.subscriptionMethod=this.options.subscription.subscriptionName)),this.arguments||(this.arguments=this._formatInput(e),this._validateArgs(this.arguments),e=[]),t.push(this.subscriptionMethod),t=t.concat(this.arguments),e.length)throw new Error("Only a callback is allowed as parameter on an already instantiated subscription.");return{method:this.options.type+"_subscribe",params:t}},a.prototype.unsubscribe=function(e){this.options.requestManager.removeSubscription(this.id,e),this.id=null,this.removeAllListeners(),clearInterval(this._reconnectIntervalId)},a.prototype.subscribe=function(){var e=this,t=Array.prototype.slice.call(arguments),r=this._toPayload(t);if(!r)return this;if(!this.options.requestManager.provider){var i=new Error("No provider set.");return this.callback(i,null,this),this.emit("error",i),this}if(!this.options.requestManager.provider.on){var o=new Error("The current provider doesn't support subscriptions: "+this.options.requestManager.provider.constructor.name);return this.callback(o,null,this),this.emit("error",o),this}return this.id&&this.unsubscribe(),this.options.params=r.params[1],"logs"===r.params[0]&&n.isObject(r.params[1])&&r.params[1].hasOwnProperty("fromBlock")&&isFinite(r.params[1].fromBlock)&&this.options.requestManager.send({method:"eth_getLogs",params:[r.params[1]]},function(t,r){t?(e.callback(t,null,e),e.emit("error",t)):r.forEach(function(t){var r=e._formatOutput(t);e.callback(null,r,e),e.emit("data",r)})}),"object"==typeof r.params[1]&&delete r.params[1].fromBlock,this.options.requestManager.send(r,function(t,i){!t&&i?(e.id=i,e.options.requestManager.addSubscription(e.id,r.params[0],e.options.type,function(t,r){t?(e.options.requestManager.removeSubscription(e.id),e.options.requestManager.provider.once&&(e._reconnectIntervalId=setInterval(function(){e.options.requestManager.provider.reconnect&&e.options.requestManager.provider.reconnect()},500),e.options.requestManager.provider.once("connect",function(){clearInterval(e._reconnectIntervalId),e.subscribe(e.callback)})),e.emit("error",t),e.callback(t,null,e)):(n.isArray(r)||(r=[r]),r.forEach(function(t){var r=e._formatOutput(t);if(n.isFunction(e.options.subscription.subscriptionHandler))return e.options.subscription.subscriptionHandler.call(e,r);e.emit("data",r),e.callback(null,r,e)}))})):(e.callback(t,null,e),e.emit("error",t))}),this},t.exports=a},{eventemitter3:156,underscore:325,"web3-core-helpers":338}],347:[function(e,t,r){"use strict";var n=e("web3-core-helpers").formatters,i=e("web3-core-method"),o=e("web3-utils");t.exports=function(e){var t=function(t){var r;return t.property?(e[t.property]||(e[t.property]={}),r=e[t.property]):r=e,t.methods&&t.methods.forEach(function(t){t instanceof i||(t=new i(t)),t.attachToObject(r),t.setRequestManager(e._requestManager)}),e};return t.formatters=n,t.utils=o,t.Method=i,t}},{"web3-core-helpers":338,"web3-core-method":339,"web3-utils":403}],348:[function(e,t,r){"use strict";var n=e("web3-core-requestmanager"),i=e("./extend.js");t.exports={packageInit:function(e,t){if(t=Array.prototype.slice.call(t),!e)throw new Error('You need to instantiate using the "new" keyword.');Object.defineProperty(e,"currentProvider",{get:function(){return e._provider},set:function(t){return e.setProvider(t)},enumerable:!0,configurable:!0}),t[0]&&t[0]._requestManager?e._requestManager=new n.Manager(t[0].currentProvider):(e._requestManager=new n.Manager,e._requestManager.setProvider(t[0],t[1])),e.givenProvider=n.Manager.givenProvider,e.providers=n.Manager.providers,e._provider=e._requestManager.provider,e.setProvider||(e.setProvider=function(t,r){return e._requestManager.setProvider(t,r),e._provider=e._requestManager.provider,!0}),e.BatchRequest=n.BatchManager.bind(null,e._requestManager),e.extend=i(e)},addProviders:function(e){e.givenProvider=n.Manager.givenProvider,e.providers=n.Manager.providers}}},{"./extend.js":347,"web3-core-requestmanager":343}],349:[function(e,t,r){var n=e("underscore"),i=e("web3-utils"),o=new(0,e("ethers/utils/abi-coder").AbiCoder)(function(e,t){return!e.match(/^u?int/)||n.isArray(t)||n.isObject(t)&&"BN"===t.constructor.name?t:t.toString()});function a(){}var s=function(){};s.prototype.encodeFunctionSignature=function(e){return n.isObject(e)&&(e=i._jsonInterfaceMethodToString(e)),i.sha3(e).slice(0,10)},s.prototype.encodeEventSignature=function(e){return n.isObject(e)&&(e=i._jsonInterfaceMethodToString(e)),i.sha3(e)},s.prototype.encodeParameter=function(e,t){return this.encodeParameters([e],[t])},s.prototype.encodeParameters=function(e,t){return o.encode(this.mapTypes(e),t)},s.prototype.mapTypes=function(e){var t=this,r=[];return e.forEach(function(e){if(t.isSimplifiedStructFormat(e)){var n=Object.keys(e)[0];r.push(Object.assign(t.mapStructNameAndType(n),{components:t.mapStructToCoderFormat(e[n])}))}else r.push(e)}),r},s.prototype.isSimplifiedStructFormat=function(e){return"object"==typeof e&&void 0===e.components&&void 0===e.name},s.prototype.mapStructNameAndType=function(e){var t="tuple";return e.indexOf("[]")>-1&&(t="tuple[]",e=e.slice(0,-2)),{type:t,name:e}},s.prototype.mapStructToCoderFormat=function(e){var t=this,r=[];return Object.keys(e).forEach(function(n){"object"!=typeof e[n]?r.push({name:n,type:e[n]}):r.push(Object.assign(t.mapStructNameAndType(n),{components:t.mapStructToCoderFormat(e[n])}))}),r},s.prototype.encodeFunctionCall=function(e,t){return this.encodeFunctionSignature(e)+this.encodeParameters(e.inputs,t).replace("0x","")},s.prototype.decodeParameter=function(e,t){return this.decodeParameters([e],t)[0]},s.prototype.decodeParameters=function(e,t){if(!t||"0x"===t||"0X"===t)throw new Error("Returned values aren't valid, did it run Out of Gas?");var r=o.decode(this.mapTypes(e),"0x"+t.replace(/0x/i,"")),i=new a;return i.__length__=0,e.forEach(function(e,t){var o=r[i.__length__];o="0x"===o?null:o,i[t]=o,n.isObject(e)&&e.name&&(i[e.name]=o),i.__length__++}),i},s.prototype.decodeLog=function(e,t,r){var i=this;r=n.isArray(r)?r:[r],t=t||"";var o=[],s=[],u=0;e.forEach(function(e,t){e.indexed?(s[t]=["bool","int","uint","address","fixed","ufixed"].find(function(t){return-1!==e.type.indexOf(t)})?i.decodeParameter(e.type,r[u]):r[u],u++):o[t]=e});var c=t,f=c?this.decodeParameters(o,c):[],h=new a;return h.__length__=0,e.forEach(function(e,t){h[t]="string"===e.type?"":null,void 0!==f[t]&&(h[t]=f[t]),void 0!==s[t]&&(h[t]=s[t]),e.name&&(h[e.name]=h[t]),h.__length__++}),h};var u=new s;t.exports=u},{"ethers/utils/abi-coder":143,underscore:325,"web3-utils":403}],350:[function(e,t,r){(function(r){var n=function(){return function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var r=[],n=!0,i=!1,o=void 0;try{for(var a,s=e[Symbol.iterator]();!(n=(a=s.next()).done)&&(r.push(a.value),!t||r.length!==t);n=!0);}catch(e){i=!0,o=e}finally{try{!n&&s.return&&s.return()}finally{if(i)throw o}}return r}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),i=e("./bytes"),o=e("./nat"),a=e("elliptic"),s=(e("./rlp"),new a.ec("secp256k1")),u=e("./hash"),c=u.keccak256,f=u.keccak256s,h=function(e){for(var t=f(e.slice(2)),r="0x",n=0;n<40;n++)r+=parseInt(t[n+2],16)>7?e[n+2].toUpperCase():e[n+2];return r},l=function(e){var t=new r(e.slice(2),"hex"),n="0x"+s.keyFromPrivate(t).getPublic(!1,"hex").slice(2),i=c(n);return{address:h("0x"+i.slice(-40)),privateKey:e}},d=function(e){var t=n(e,3),r=t[0],o=i.pad(32,t[1]),a=i.pad(32,t[2]);return i.flatten([o,a,r])},p=function(e){return[i.slice(64,i.length(e),e),i.slice(0,32,e),i.slice(32,64,e)]},b=function(e){return function(t,n){var a=s.keyFromPrivate(new r(n.slice(2),"hex")).sign(new r(t.slice(2),"hex"),{canonical:!0});return d([o.fromString(i.fromNumber(e+a.recoveryParam)),i.pad(32,i.fromNat("0x"+a.r.toString(16))),i.pad(32,i.fromNat("0x"+a.s.toString(16)))])}},y=b(27);t.exports={create:function(e){var t=c(i.concat(i.random(32),e||i.random(32))),r=i.concat(i.concat(i.random(32),t),i.random(32)),n=c(r);return l(n)},toChecksum:h,fromPrivate:l,sign:y,makeSigner:b,recover:function(e,t){var n=p(t),o={v:i.toNumber(n[0]),r:n[1].slice(2),s:n[2].slice(2)},a="0x"+s.recoverPubKey(new r(e.slice(2),"hex"),o,o.v<2?o.v:1-o.v%2).encode("hex",!1).slice(2),u=c(a);return h("0x"+u.slice(-40))},encodeSignature:d,decodeSignature:p}}).call(this,e("buffer").Buffer)},{"./bytes":352,"./hash":353,"./nat":354,"./rlp":355,buffer:84,elliptic:109}],351:[function(e,t,r){arguments[4][132][0].apply(r,arguments)},{dup:132}],352:[function(e,t,r){arguments[4][133][0].apply(r,arguments)},{"./array.js":351,dup:133}],353:[function(e,t,r){arguments[4][134][0].apply(r,arguments)},{dup:134}],354:[function(e,t,r){var n=e("bn.js"),i=e("./bytes"),o=function(e){return new n(e.slice(2),16)},a=function(e){var t="0x"+("0x"===e.slice(0,2)?new n(e.slice(2),16):new n(e,10)).toString("hex");return"0x0"===t?"0x":t},s=function(e){return"string"==typeof e?/^0x/.test(e)?e:"0x"+e:"0x"+new n(e).toString("hex")},u=function(e){return o(e).toNumber()},c=function(e){return function(t,r){return"0x"+o(t)[e](o(r)).toString("hex")}},f=c("add"),h=c("mul"),l=c("div"),d=c("sub");t.exports={toString:function(e){return o(e).toString(10)},fromString:a,toNumber:u,fromNumber:s,toEther:function(e){return u(l(e,a("10000000000")))/1e8},fromEther:function(e){return h(s(Math.floor(1e8*e)),a("10000000000"))},toUint256:function(e){return i.pad(32,e)},add:f,mul:h,div:l,sub:d}},{"./bytes":352,"bn.js":53}],355:[function(e,t,r){t.exports={encode:function(e){var t=function(e){return(t=e.toString(16)).length%2==0?t:"0"+t;var t},r=function(e,r){return e<56?t(r+e):t(r+t(e).length/2+55)+t(e)};return"0x"+function e(t){if("string"==typeof t){var n=t.slice(2);return(2!=n.length||n>="80"?r(n.length/2,128):"")+n}var i=t.map(e).join("");return r(i.length/2,192)+i}(e)},decode:function(e){var t=2,r=function(){if(t>=e.length)throw"";var r=e.slice(t,t+2);return r<"80"?(t+=2,"0x"+r):r<"c0"?i():o()},n=function(){var r=parseInt(e.slice(t,t+=2),16)%64;return r<56?r:parseInt(e.slice(t,t+=2*(r-55)),16)},i=function(){var r=n();return"0x"+e.slice(t,t+=2*r)},o=function(){for(var e=2*n()+t,i=[];t>>((3&t)<<3)&255;return i}}t.exports=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],357:[function(e,t,r){for(var n=e("./rng"),i=[],o={},a=0;a<256;a++)i[a]=(a+256).toString(16).substr(1),o[i[a]]=a;function s(e,t){var r=t||0,n=i;return n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]}var u=n(),c=[1|u[0],u[1],u[2],u[3],u[4],u[5]],f=16383&(u[6]<<8|u[7]),h=0,l=0;function d(e,t,r){var i=t&&r||0;"string"==typeof e&&(t="binary"==e?new Array(16):null,e=null);var o=(e=e||{}).random||(e.rng||n)();if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,t)for(var a=0;a<16;a++)t[i+a]=o[a];return t||s(o)}var p=d;p.v1=function(e,t,r){var n=t&&r||0,i=t||[],o=void 0!==(e=e||{}).clockseq?e.clockseq:f,a=void 0!==e.msecs?e.msecs:(new Date).getTime(),u=void 0!==e.nsecs?e.nsecs:l+1,d=a-h+(u-l)/1e4;if(d<0&&void 0===e.clockseq&&(o=o+1&16383),(d<0||a>h)&&void 0===e.nsecs&&(u=0),u>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");h=a,l=u,f=o;var p=(1e4*(268435455&(a+=122192928e5))+u)%4294967296;i[n++]=p>>>24&255,i[n++]=p>>>16&255,i[n++]=p>>>8&255,i[n++]=255&p;var b=a/4294967296*1e4&268435455;i[n++]=b>>>8&255,i[n++]=255&b,i[n++]=b>>>24&15|16,i[n++]=b>>>16&255,i[n++]=o>>>8|128,i[n++]=255&o;for(var y=e.node||c,m=0;m<6;m++)i[n+m]=y[m];return t||s(i)},p.v4=d,p.parse=function(e,t,r){var n=t&&r||0,i=0;for(t=t||[],e.toLowerCase().replace(/[0-9a-f]{2}/g,function(e){i<16&&(t[n+i++]=o[e])});i<16;)t[n+i++]=0;return t},p.unparse=s,t.exports=p},{"./rng":356}],358:[function(e,t,r){(function(r,n){"use strict";var i=e("underscore"),o=e("web3-core"),a=e("web3-core-method"),s=e("any-promise"),u=e("eth-lib/lib/account"),c=e("eth-lib/lib/hash"),f=e("eth-lib/lib/rlp"),h=e("eth-lib/lib/nat"),l=e("eth-lib/lib/bytes"),d=e(void 0===r?"crypto-browserify":"crypto"),p=e("scrypt.js"),b=e("uuid"),y=e("web3-utils"),m=e("web3-core-helpers"),v=function(e){return i.isUndefined(e)||i.isNull(e)},g=function(e){for(;e&&e.startsWith("0x0");)e="0x"+e.slice(3);return e},w=function(e){return e.length%2==1&&(e=e.replace("0x","0x0")),e},_=function(){var e=this;o.packageInit(this,arguments),delete this.BatchRequest,delete this.extend;var t=[new a({name:"getId",call:"net_version",params:0,outputFormatter:y.hexToNumber}),new a({name:"getGasPrice",call:"eth_gasPrice",params:0}),new a({name:"getTransactionCount",call:"eth_getTransactionCount",params:2,inputFormatter:[function(e){if(y.isAddress(e))return e;throw new Error("Address "+e+' is not a valid address to get the "transactionCount".')},function(){return"latest"}]})];this._ethereumCall={},i.each(t,function(t){t.attachToObject(e._ethereumCall),t.setRequestManager(e._requestManager)}),this.wallet=new A(this)};function A(e){this._accounts=e,this.length=0,this.defaultKeyName="web3js_wallet"}_.prototype._addAccountFunctions=function(e){var t=this;return e.signTransaction=function(r,n){return t.signTransaction(r,e.privateKey,n)},e.sign=function(r){return t.sign(r,e.privateKey)},e.encrypt=function(r,n){return t.encrypt(e.privateKey,r,n)},e},_.prototype.create=function(e){return this._addAccountFunctions(u.create(e||y.randomHex(32)))},_.prototype.privateKeyToAccount=function(e){return this._addAccountFunctions(u.fromPrivate(e))},_.prototype.signTransaction=function(e,t,r){var n,o=!1;if(r=r||function(){},!e)return o=new Error("No transaction object given!"),r(o),s.reject(o);function a(e){if(e.gas||e.gasLimit||(o=new Error('"gas" is missing')),(e.nonce<0||e.gas<0||e.gasPrice<0||e.chainId<0)&&(o=new Error("Gas, gasPrice, nonce or chainId is lower than 0")),o)return r(o),s.reject(o);try{var i=e=m.formatters.inputCallFormatter(e);i.to=e.to||"0x",i.data=e.data||"0x",i.value=e.value||"0x",i.chainId=y.numberToHex(e.chainId);var a=f.encode([l.fromNat(i.nonce),l.fromNat(i.gasPrice),l.fromNat(i.gas),i.to.toLowerCase(),l.fromNat(i.value),i.data,l.fromNat(i.chainId||"0x1"),"0x","0x"]),d=c.keccak256(a),p=u.makeSigner(2*h.toNumber(i.chainId||"0x1")+35)(c.keccak256(a),t),b=f.decode(a).slice(0,6).concat(u.decodeSignature(p));b[6]=w(g(b[6])),b[7]=w(g(b[7])),b[8]=w(g(b[8]));var v=f.encode(b),_=f.decode(v);n={messageHash:d,v:g(_[6]),r:g(_[7]),s:g(_[8]),rawTransaction:v}}catch(e){return r(e),s.reject(e)}return r(null,n),n}return void 0!==e.nonce&&void 0!==e.chainId&&void 0!==e.gasPrice?s.resolve(a(e)):s.all([v(e.chainId)?this._ethereumCall.getId():e.chainId,v(e.gasPrice)?this._ethereumCall.getGasPrice():e.gasPrice,v(e.nonce)?this._ethereumCall.getTransactionCount(this.privateKeyToAccount(t).address):e.nonce]).then(function(t){if(v(t[0])||v(t[1])||v(t[2]))throw new Error('One of the values "chainId", "gasPrice", or "nonce" couldn\'t be fetched: '+JSON.stringify(t));return a(i.extend(e,{chainId:t[0],gasPrice:t[1],nonce:t[2]}))})},_.prototype.recoverTransaction=function(e){var t=f.decode(e),r=u.encodeSignature(t.slice(6,9)),n=l.toNumber(t[6]),i=n<35?[]:[l.fromNumber(n-35>>1),"0x","0x"],o=t.slice(0,6).concat(i),a=f.encode(o);return u.recover(c.keccak256(a),r)},_.prototype.hashMessage=function(e){var t=y.isHexStrict(e)?y.hexToBytes(e):e,r=n.from(t),i="Ethereum Signed Message:\n"+t.length,o=n.from(i),a=n.concat([o,r]);return c.keccak256s(a)},_.prototype.sign=function(e,t){var r=this.hashMessage(e),n=u.sign(r,t),i=u.decodeSignature(n);return{message:e,messageHash:r,v:i[0],r:i[1],s:i[2],signature:n}},_.prototype.recover=function(e,t,r){var n=[].slice.apply(arguments);return i.isObject(e)?this.recover(e.messageHash,u.encodeSignature([e.v,e.r,e.s]),!0):(r||(e=this.hashMessage(e)),n.length>=4?(r=n.slice(-1)[0],r=!!i.isBoolean(r)&&!!r,this.recover(e,u.encodeSignature(n.slice(1,4)),r)):u.recover(e,t))},_.prototype.decrypt=function(e,t,r){if(!i.isString(t))throw new Error("No password given.");var o,a,s=i.isObject(e)?e:JSON.parse(r?e.toLowerCase():e);if(3!==s.version)throw new Error("Not a valid V3 wallet");if("scrypt"===s.crypto.kdf)a=s.crypto.kdfparams,o=p(new n(t),new n(a.salt,"hex"),a.n,a.r,a.p,a.dklen);else{if("pbkdf2"!==s.crypto.kdf)throw new Error("Unsupported key derivation scheme");if("hmac-sha256"!==(a=s.crypto.kdfparams).prf)throw new Error("Unsupported parameters to PBKDF2");o=d.pbkdf2Sync(new n(t),new n(a.salt,"hex"),a.c,a.dklen,"sha256")}var u=new n(s.crypto.ciphertext,"hex");if(y.sha3(n.concat([o.slice(16,32),u])).replace("0x","")!==s.crypto.mac)throw new Error("Key derivation failed - possibly wrong password");var c=d.createDecipheriv(s.crypto.cipher,o.slice(0,16),new n(s.crypto.cipherparams.iv,"hex")),f="0x"+n.concat([c.update(u),c.final()]).toString("hex");return this.privateKeyToAccount(f)},_.prototype.encrypt=function(e,t,r){var i,o=this.privateKeyToAccount(e),a=(r=r||{}).salt||d.randomBytes(32),s=r.iv||d.randomBytes(16),u=r.kdf||"scrypt",c={dklen:r.dklen||32,salt:a.toString("hex")};if("pbkdf2"===u)c.c=r.c||262144,c.prf="hmac-sha256",i=d.pbkdf2Sync(new n(t),a,c.c,c.dklen,"sha256");else{if("scrypt"!==u)throw new Error("Unsupported kdf");c.n=r.n||8192,c.r=r.r||8,c.p=r.p||1,i=p(new n(t),a,c.n,c.r,c.p,c.dklen)}var f=d.createCipheriv(r.cipher||"aes-128-ctr",i.slice(0,16),s);if(!f)throw new Error("Unsupported cipher");var h=n.concat([f.update(new n(o.privateKey.replace("0x",""),"hex")),f.final()]),l=y.sha3(n.concat([i.slice(16,32),new n(h,"hex")])).replace("0x","");return{version:3,id:b.v4({random:r.uuid||d.randomBytes(16)}),address:o.address.toLowerCase().replace("0x",""),crypto:{ciphertext:h.toString("hex"),cipherparams:{iv:s.toString("hex")},cipher:r.cipher||"aes-128-ctr",kdf:u,kdfparams:c,mac:l.toString("hex")}}},A.prototype._findSafeIndex=function(e){return e=e||0,i.has(this,e)?this._findSafeIndex(e+1):e},A.prototype._currentIndexes=function(){return Object.keys(this).map(function(e){return parseInt(e)}).filter(function(e){return e<9e20})},A.prototype.create=function(e,t){for(var r=0;r=2?t.slice(2):t;var r=h.decodeParameters(e,t);return 1===r.__length__?r[0]:(delete r.__length__,r)},l.prototype.deploy=function(e,t){if((e=e||{}).arguments=e.arguments||[],!(e=this._getOrSetDefaultOptions(e)).data)return a._fireError(new Error('No "data" specified in neither the given options, nor the default options.'),null,null,t);var r=n.find(this.options.jsonInterface,function(e){return"constructor"===e.type})||{};return r.signature="constructor",this._createTxObject.apply({method:r,parent:this,deployData:e.data,_ethAccounts:this.constructor._ethAccounts},e.arguments)},l.prototype._generateEventOptions=function(){var e=Array.prototype.slice.call(arguments),t=this._getCallback(e),r=n.isObject(e[e.length-1])?e.pop():{},i=n.isString(e[0])?e[0]:"allevents";if(!(i="allevents"===i.toLowerCase()?{name:"ALLEVENTS",jsonInterface:this.options.jsonInterface}:this.options.jsonInterface.find(function(e){return"event"===e.type&&(e.name===i||e.signature==="0x"+i.replace("0x",""))})))throw new Error('Event "'+i.name+"\" doesn't exist in this contract.");if(!a.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(i,r),event:i,callback:t}},l.prototype.clone=function(){return new this.constructor(this.options.jsonInterface,this.options.address,this.options)},l.prototype.once=function(e,t,r){var i=Array.prototype.slice.call(arguments);if(!(r=this._getCallback(i)))throw new Error("Once requires a callback as the second parameter.");t&&delete t.fromBlock,this._on(e,t,function(e,t,i){i.unsubscribe(),n.isFunction(r)&&r(e,t,i)})},l.prototype._on=function(){var e=this._generateEventOptions.apply(this,arguments);this._checkListener("newListener",e.event.name,e.callback),this._checkListener("removeListener",e.event.name,e.callback);var t=new s({subscription:{params:1,inputFormatter:[u.inputLogFormatter],outputFormatter:this._decodeEventABI.bind(e.event),subscriptionHandler:function(e){e.removed?this.emit("changed",e):this.emit("data",e),n.isFunction(this.callback)&&this.callback(null,e,this)}},type:"eth",requestManager:this._requestManager});return t.subscribe("logs",e.params,e.callback||function(){}),t},l.prototype.getPastEvents=function(){var e=this._generateEventOptions.apply(this,arguments),t=new o({name:"getPastLogs",call:"eth_getLogs",params:1,inputFormatter:[u.inputLogFormatter],outputFormatter:this._decodeEventABI.bind(e.event)});t.setRequestManager(this._requestManager);var r=t.buildCall();return t=null,r(e.params,e.callback)},l.prototype._createTxObject=function(){var e=Array.prototype.slice.call(arguments),t={};if("function"===this.method.type&&(t.call=this.parent._executeMethod.bind(t,"call"),t.call.request=this.parent._executeMethod.bind(t,"call",!0)),t.send=this.parent._executeMethod.bind(t,"send"),t.send.request=this.parent._executeMethod.bind(t,"send",!0),t.encodeABI=this.parent._encodeMethodABI.bind(t),t.estimateGas=this.parent._executeMethod.bind(t,"estimate"),e&&this.method.inputs&&e.length!==this.method.inputs.length){if(this.nextMethod)return this.nextMethod.apply(null,e);throw c.InvalidNumberOfParams(e.length,this.method.inputs.length,this.method.name)}return t.arguments=e||[],t._method=this.method,t._parent=this.parent,t._ethAccounts=this.parent.constructor._ethAccounts||this._ethAccounts,this.deployData&&(t._deployData=this.deployData),t},l.prototype._processExecuteArguments=function(e,t){var r={};if(r.type=e.shift(),r.callback=this._parent._getCallback(e),"call"===r.type&&!0!==e[e.length-1]&&(n.isString(e[e.length-1])||isFinite(e[e.length-1]))&&(r.defaultBlock=e.pop()),r.options=n.isObject(e[e.length-1])?e.pop():{},r.generateRequest=!0===e[e.length-1]&&e.pop(),r.options=this._parent._getOrSetDefaultOptions(r.options),r.options.data=this.encodeABI(),!this._deployData&&!a.isAddress(this._parent.options.address))throw new Error("This contract object doesn't have address set yet, please set an address first.");return this._deployData||(r.options.to=this._parent.options.address),r.options.data?r:a._fireError(new Error("Couldn't find a matching contract method, or the number of parameters is wrong."),t.eventEmitter,t.reject,r.callback)},l.prototype._executeMethod=function(){var e=this,t=this._parent._processExecuteArguments.call(this,Array.prototype.slice.call(arguments),r),r=f("send"!==t.type),i=e.constructor._ethAccounts||e._ethAccounts;if(t.generateRequest){var s={params:[u.inputCallFormatter.call(this._parent,t.options)],callback:t.callback};return"call"===t.type?(s.params.push(u.inputDefaultBlockNumberFormatter.call(this._parent,t.defaultBlock)),s.method="eth_call",s.format=this._parent._decodeMethodReturn.bind(null,this._method.outputs)):s.method="eth_sendTransaction",s}switch(t.type){case"estimate":return new o({name:"estimateGas",call:"eth_estimateGas",params:1,inputFormatter:[u.inputCallFormatter],outputFormatter:a.hexToNumber,requestManager:e._parent._requestManager,accounts:i,defaultAccount:e._parent.defaultAccount,defaultBlock:e._parent.defaultBlock}).createFunction()(t.options,t.callback);case"call":return new o({name:"call",call:"eth_call",params:2,inputFormatter:[u.inputCallFormatter,u.inputDefaultBlockNumberFormatter],outputFormatter:function(t){return e._parent._decodeMethodReturn(e._method.outputs,t)},requestManager:e._parent._requestManager,accounts:i,defaultAccount:e._parent.defaultAccount,defaultBlock:e._parent.defaultBlock}).createFunction()(t.options,t.defaultBlock,t.callback);case"send":if(!a.isAddress(t.options.from))return a._fireError(new Error('No "from" address specified in neither the given options, nor the default options.'),r.eventEmitter,r.reject,t.callback);if(n.isBoolean(this._method.payable)&&!this._method.payable&&t.options.value&&t.options.value>0)return a._fireError(new Error("Can not send value to non-payable contract method or constructor"),r.eventEmitter,r.reject,t.callback);var c={receiptFormatter:function(t){if(n.isArray(t.logs)){var r=n.map(t.logs,function(t){return e._parent._decodeEventABI.call({name:"ALLEVENTS",jsonInterface:e._parent.options.jsonInterface},t)});t.events={};var i=0;r.forEach(function(e){e.event?t.events[e.event]?Array.isArray(t.events[e.event])?t.events[e.event].push(e):t.events[e.event]=[t.events[e.event],e]:t.events[e.event]=e:(t.events[i]=e,i++)}),delete t.logs}return t},contractDeployFormatter:function(t){var r=e._parent.clone();return r.options.address=t.contractAddress,r}};return new o({name:"sendTransaction",call:"eth_sendTransaction",params:1,inputFormatter:[u.inputTransactionFormatter],requestManager:e._parent._requestManager,accounts:e.constructor._ethAccounts||e._ethAccounts,defaultAccount:e._parent.defaultAccount,defaultBlock:e._parent.defaultBlock,extraFormatters:c}).createFunction()(t.options,t.callback)}},t.exports=l},{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(e,t,r){"use strict";var n=e("./config"),i=e("./contracts/Registry"),o=e("./lib/ResolverMethodHandler");function a(e){this.eth=e}Object.defineProperty(a.prototype,"registry",{get:function(){return new i(this)},enumerable:!0}),Object.defineProperty(a.prototype,"resolverMethodHandler",{get:function(){return new o(this.registry)},enumerable:!0}),a.prototype.resolver=function(e){return this.registry.resolver(e)},a.prototype.getAddress=function(e,t){return this.resolverMethodHandler.method(e,"addr",[]).call(t)},a.prototype.setAddress=function(e,t,r,n){return this.resolverMethodHandler.method(e,"setAddr",[t]).send(r,n)},a.prototype.getPubkey=function(e,t){return this.resolverMethodHandler.method(e,"pubkey",[],t).call(t)},a.prototype.setPubkey=function(e,t,r,n,i){return this.resolverMethodHandler.method(e,"setPubkey",[t,r]).send(n,i)},a.prototype.getContent=function(e,t){return this.resolverMethodHandler.method(e,"content",[]).call(t)},a.prototype.setContent=function(e,t,r,n){return this.resolverMethodHandler.method(e,"setContent",[t]).send(r,n)},a.prototype.getMultihash=function(e,t){return this.resolverMethodHandler.method(e,"multihash",[]).call(t)},a.prototype.setMultihash=function(e,t,r,n){return this.resolverMethodHandler.method(e,"multihash",[t]).send(r,n)},a.prototype.checkNetwork=function(){var e=this;return e.eth.getBlock("latest").then(function(t){var r=new Date/1e3-t.timestamp;if(r>3600)throw new Error("Network not synced; last block was "+r+" seconds ago");return e.eth.net.getNetworkType()}).then(function(e){var t=n.addresses[e];if(void 0===t)throw new Error("ENS is not supported on network "+e);return t})},t.exports=a},{"./config":361,"./contracts/Registry":362,"./lib/ResolverMethodHandler":364}],361:[function(e,t,r){"use strict";t.exports={addresses:{main:"0x314159265dD8dbb310642f98f50C066173C1259b",ropsten:"0x112234455c3a32fd11230c42e7bccd4a84e02010",rinkeby:"0xe7410170f87102df0055eb195163a03b7f2bff4a"}}},{}],362:[function(e,t,r){"use strict";var n=e("underscore"),i=e("web3-eth-contract"),o=e("eth-ens-namehash"),a=e("web3-core-promievent"),s=e("../ressources/ABI/Registry"),u=e("../ressources/ABI/Resolver");function c(e){var t=this;this.ens=e,this.contract=e.checkNetwork().then(function(e){var r=new i(s,e);return r.setProvider(t.ens.eth.currentProvider),r})}c.prototype.owner=function(e,t){var r=new a(!0);return this.contract.then(function(i){i.methods.owner(o.hash(e)).call().then(function(e){r.resolve(e),n.isFunction(t)&&t(e)}).catch(function(e){r.reject(e),n.isFunction(t)&&t(e)})}),r.eventEmitter},c.prototype.resolver=function(e){var t=this;return this.contract.then(function(t){return t.methods.resolver(o.hash(e)).call()}).then(function(e){var r=new i(u,e);return r.setProvider(t.ens.eth.currentProvider),r})},t.exports=c},{"../ressources/ABI/Registry":365,"../ressources/ABI/Resolver":366,"eth-ens-namehash":127,underscore:325,"web3-core-promievent":340,"web3-eth-contract":359}],363:[function(e,t,r){"use strict";var n=e("./ENS");t.exports=n},{"./ENS":360}],364:[function(e,t,r){"use strict";var n=e("web3-core-promievent"),i=e("eth-ens-namehash"),o=e("underscore");function a(e){this.registry=e}a.prototype.method=function(e,t,r,n){return{call:this.call.bind({ensName:e,methodName:t,methodArguments:r,callback:n,parent:this}),send:this.send.bind({ensName:e,methodName:t,methodArguments:r,callback:n,parent:this})}},a.prototype.call=function(e){var t=this,r=new n,i=this.parent.prepareArguments(this.ensName,this.methodArguments);return this.parent.registry.resolver(this.ensName).then(function(n){t.parent.handleCall(r,n.methods[t.methodName],i,e)}).catch(function(e){r.reject(e)}),r.eventEmitter},a.prototype.send=function(e,t){var r=this,i=new n,o=this.parent.prepareArguments(this.ensName,this.methodArguments);return this.parent.registry.resolver(this.ensName).then(function(n){r.parent.handleSend(i,n.methods[r.methodName],o,e,t)}).catch(function(e){i.reject(e)}),i.eventEmitter},a.prototype.handleCall=function(e,t,r,n){return t.apply(this,r).call().then(function(t){e.resolve(t),o.isFunction(n)&&n(t)}).catch(function(t){e.reject(t),o.isFunction(n)&&n(t)}),e},a.prototype.handleSend=function(e,t,r,n,i){return t.apply(this,r).send(n).on("transactionHash",function(t){e.eventEmitter.emit("transactionHash",t)}).on("confirmation",function(t,r){e.eventEmitter.emit("confirmation",t,r)}).on("receipt",function(t){e.eventEmitter.emit("receipt",t),e.resolve(t),o.isFunction(i)&&i(t)}).on("error",function(t){e.eventEmitter.emit("error",t),e.reject(t),o.isFunction(i)&&i(t)}),e},a.prototype.prepareArguments=function(e,t){var r=i.hash(e);return t.length>0?(t.unshift(r),t):[r]},t.exports=a},{"eth-ens-namehash":127,underscore:325,"web3-core-promievent":340}],365:[function(e,t,r){"use strict";t.exports=[{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"resolver",outputs:[{name:"",type:"address"}],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"owner",outputs:[{name:"",type:"address"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"label",type:"bytes32"},{name:"owner",type:"address"}],name:"setSubnodeOwner",outputs:[],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"ttl",type:"uint64"}],name:"setTTL",outputs:[],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"ttl",outputs:[{name:"",type:"uint64"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"resolver",type:"address"}],name:"setResolver",outputs:[],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"owner",type:"address"}],name:"setOwner",outputs:[],payable:!1,type:"function"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"owner",type:"address"}],name:"Transfer",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!0,name:"label",type:"bytes32"},{indexed:!1,name:"owner",type:"address"}],name:"NewOwner",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"resolver",type:"address"}],name:"NewResolver",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"ttl",type:"uint64"}],name:"NewTTL",type:"event"}]},{}],366:[function(e,t,r){"use strict";t.exports=[{constant:!0,inputs:[{name:"interfaceID",type:"bytes4"}],name:"supportsInterface",outputs:[{name:"",type:"bool"}],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"},{name:"contentTypes",type:"uint256"}],name:"ABI",outputs:[{name:"contentType",type:"uint256"},{name:"data",type:"bytes"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"hash",type:"bytes"}],name:"setMultihash",outputs:[],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"multihash",outputs:[{name:"",type:"bytes"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"x",type:"bytes32"},{name:"y",type:"bytes32"}],name:"setPubkey",outputs:[],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"content",outputs:[{name:"ret",type:"bytes32"}],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"addr",outputs:[{name:"ret",type:"address"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"contentType",type:"uint256"},{name:"data",type:"bytes"}],name:"setABI",outputs:[],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"name",outputs:[{name:"ret",type:"string"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"name",type:"string"}],name:"setName",outputs:[],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"hash",type:"bytes32"}],name:"setContent",outputs:[],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"pubkey",outputs:[{name:"x",type:"bytes32"},{name:"y",type:"bytes32"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"addr",type:"address"}],name:"setAddr",outputs:[],payable:!1,type:"function"},{inputs:[{name:"ensAddr",type:"address"}],payable:!1,type:"constructor"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"a",type:"address"}],name:"AddrChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"hash",type:"bytes32"}],name:"ContentChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"name",type:"string"}],name:"NameChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!0,name:"contentType",type:"uint256"}],name:"ABIChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"x",type:"bytes32"},{indexed:!1,name:"y",type:"bytes32"}],name:"PubkeyChanged",type:"event"}]},{}],367:[function(e,t,r){arguments[4][154][0].apply(r,arguments)},{dup:154}],368:[function(e,t,r){"use strict";var n=e("web3-utils"),i=e("bn.js"),o=function(e){var t="A".charCodeAt(0),r="Z".charCodeAt(0);return(e=(e=e.toUpperCase()).substr(4)+e.substr(0,4)).split("").map(function(e){var n=e.charCodeAt(0);return n>=t&&n<=r?n-t+10:e}).join("")},a=function(e){for(var t,r=e;r.length>2;)t=r.slice(0,9),r=parseInt(t,10)%97+r.slice(t.length);return parseInt(r,10)%97},s=function(e){this._iban=e};s.toAddress=function(e){if(!(e=new s(e)).isDirect())throw new Error("IBAN is indirect and can't be converted");return e.toAddress()},s.toIban=function(e){return s.fromAddress(e).toString()},s.fromAddress=function(e){if(!n.isAddress(e))throw new Error("Provided address is not a valid address: "+e);e=e.replace("0x","").replace("0X","");var t=function(e,t){for(var r=e;r.length<2*t;)r="0"+r;return r}(new i(e,16).toString(36),15);return s.fromBban(t.toUpperCase())},s.fromBban=function(e){var t=("0"+(98-a(o("XE00"+e)))).slice(-2);return new s("XE"+t+e)},s.createIndirect=function(e){return s.fromBban("ETH"+e.institution+e.identifier)},s.isValid=function(e){return new s(e).isValid()},s.prototype.isValid=function(){return/^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$/.test(this._iban)&&1===a(o(this._iban))},s.prototype.isDirect=function(){return 34===this._iban.length||35===this._iban.length},s.prototype.isIndirect=function(){return 20===this._iban.length},s.prototype.checksum=function(){return this._iban.substr(2,2)},s.prototype.institution=function(){return this.isIndirect()?this._iban.substr(7,4):""},s.prototype.client=function(){return this.isIndirect()?this._iban.substr(11):""},s.prototype.toAddress=function(){if(this.isDirect()){var e=this._iban.substr(4),t=new i(e,36);return n.toChecksumAddress(t.toString(16,20))}return""},s.prototype.toString=function(){return this._iban},t.exports=s},{"bn.js":367,"web3-utils":403}],369:[function(e,t,r){"use strict";var n=e("web3-core"),i=e("web3-core-method"),o=e("web3-utils"),a=e("web3-net"),s=e("web3-core-helpers").formatters,u=function(){var e=this;n.packageInit(this,arguments),this.net=new a(this.currentProvider);var t=null,r="latest";Object.defineProperty(this,"defaultAccount",{get:function(){return t},set:function(e){return e&&(t=o.toChecksumAddress(s.inputAddressFormatter(e))),u.forEach(function(e){e.defaultAccount=t}),e},enumerable:!0}),Object.defineProperty(this,"defaultBlock",{get:function(){return r},set:function(e){return r=e,u.forEach(function(e){e.defaultBlock=r}),e},enumerable:!0});var u=[new i({name:"getAccounts",call:"personal_listAccounts",params:0,outputFormatter:o.toChecksumAddress}),new i({name:"newAccount",call:"personal_newAccount",params:1,inputFormatter:[null],outputFormatter:o.toChecksumAddress}),new i({name:"unlockAccount",call:"personal_unlockAccount",params:3,inputFormatter:[s.inputAddressFormatter,null,null]}),new i({name:"lockAccount",call:"personal_lockAccount",params:1,inputFormatter:[s.inputAddressFormatter]}),new i({name:"importRawKey",call:"personal_importRawKey",params:2}),new i({name:"sendTransaction",call:"personal_sendTransaction",params:2,inputFormatter:[s.inputTransactionFormatter,null]}),new i({name:"signTransaction",call:"personal_signTransaction",params:2,inputFormatter:[s.inputTransactionFormatter,null]}),new i({name:"sign",call:"personal_sign",params:3,inputFormatter:[s.inputSignFormatter,s.inputAddressFormatter,null]}),new i({name:"ecRecover",call:"personal_ecRecover",params:2,inputFormatter:[s.inputSignFormatter,null]})];u.forEach(function(t){t.attachToObject(e),t.setRequestManager(e._requestManager),t.defaultBlock=e.defaultBlock,t.defaultAccount=e.defaultAccount})};n.addProviders(u),t.exports=u},{"web3-core":348,"web3-core-helpers":338,"web3-core-method":339,"web3-net":372,"web3-utils":403}],370:[function(e,t,r){"use strict";var n=e("underscore");t.exports=function(e){var t,r=this;return this.net.getId().then(function(e){return t=e,r.getBlock(0)}).then(function(r){var i="private";return"0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3"===r.hash&&1===t&&(i="main"),"0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303"===r.hash&&2===t&&(i="morden"),"0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d"===r.hash&&3===t&&(i="ropsten"),"0x6341fd3daf94b748c72ced5a5b26028f2474f5f00d824504e4fa37a75767e177"===r.hash&&4===t&&(i="rinkeby"),"0xa3c565fc15c7478862d50ccd6561e3c06b24cc509bf388941c25ea985ce32cb9"===r.hash&&42===t&&(i="kovan"),n.isFunction(e)&&e(null,i),i}).catch(function(t){if(!n.isFunction(e))throw t;e(t)})}},{underscore:325}],371:[function(e,t,r){"use strict";var n=e("underscore"),i=e("web3-core"),o=e("web3-core-helpers"),a=e("web3-core-subscriptions").subscriptions,s=e("web3-core-method"),u=e("web3-utils"),c=e("web3-net"),f=e("web3-eth-ens"),h=e("web3-eth-personal"),l=e("web3-eth-contract"),d=e("web3-eth-iban"),p=e("web3-eth-accounts"),b=e("web3-eth-abi"),y=e("./getNetworkType.js"),m=o.formatters,v=function(e){return n.isString(e[0])&&0===e[0].indexOf("0x")?"eth_getBlockByHash":"eth_getBlockByNumber"},g=function(e){return n.isString(e[0])&&0===e[0].indexOf("0x")?"eth_getTransactionByBlockHashAndIndex":"eth_getTransactionByBlockNumberAndIndex"},w=function(e){return n.isString(e[0])&&0===e[0].indexOf("0x")?"eth_getUncleByBlockHashAndIndex":"eth_getUncleByBlockNumberAndIndex"},_=function(e){return n.isString(e[0])&&0===e[0].indexOf("0x")?"eth_getBlockTransactionCountByHash":"eth_getBlockTransactionCountByNumber"},A=function(e){return n.isString(e[0])&&0===e[0].indexOf("0x")?"eth_getUncleCountByBlockHash":"eth_getUncleCountByBlockNumber"},E=function(){var e=this;i.packageInit(this,arguments);var t=this.setProvider;this.setProvider=function(){t.apply(e,arguments),e.net.setProvider.apply(e,arguments),e.personal.setProvider.apply(e,arguments),e.accounts.setProvider.apply(e,arguments),e.Contract.setProvider(e.currentProvider,e.accounts)};var r=null,o="latest";Object.defineProperty(this,"defaultAccount",{get:function(){return r},set:function(t){return t&&(r=u.toChecksumAddress(m.inputAddressFormatter(t))),e.Contract.defaultAccount=r,e.personal.defaultAccount=r,k.forEach(function(e){e.defaultAccount=r}),t},enumerable:!0}),Object.defineProperty(this,"defaultBlock",{get:function(){return o},set:function(t){return o=t,e.Contract.defaultBlock=o,e.personal.defaultBlock=o,k.forEach(function(e){e.defaultBlock=o}),t},enumerable:!0}),this.clearSubscriptions=e._requestManager.clearSubscriptions,this.net=new c(this.currentProvider),this.net.getNetworkType=y.bind(this),this.accounts=new p(this.currentProvider),this.personal=new h(this.currentProvider),this.personal.defaultAccount=this.defaultAccount;var E=this,x=function(){l.apply(this,arguments);var e=this,t=E.setProvider;E.setProvider=function(){t.apply(E,arguments),i.packageInit(e,[E.currentProvider])}};x.setProvider=function(){l.setProvider.apply(this,arguments)},(x.prototype=Object.create(l.prototype)).constructor=x,this.Contract=x,this.Contract.defaultAccount=this.defaultAccount,this.Contract.defaultBlock=this.defaultBlock,this.Contract.setProvider(this.currentProvider,this.accounts),this.Iban=d,this.abi=b,this.ens=new f(this);var k=[new s({name:"getNodeInfo",call:"web3_clientVersion"}),new s({name:"getProtocolVersion",call:"eth_protocolVersion",params:0}),new s({name:"getCoinbase",call:"eth_coinbase",params:0}),new s({name:"isMining",call:"eth_mining",params:0}),new s({name:"getHashrate",call:"eth_hashrate",params:0,outputFormatter:u.hexToNumber}),new s({name:"isSyncing",call:"eth_syncing",params:0,outputFormatter:m.outputSyncingFormatter}),new s({name:"getGasPrice",call:"eth_gasPrice",params:0,outputFormatter:m.outputBigNumberFormatter}),new s({name:"getAccounts",call:"eth_accounts",params:0,outputFormatter:u.toChecksumAddress}),new s({name:"getBlockNumber",call:"eth_blockNumber",params:0,outputFormatter:u.hexToNumber}),new s({name:"getBalance",call:"eth_getBalance",params:2,inputFormatter:[m.inputAddressFormatter,m.inputDefaultBlockNumberFormatter],outputFormatter:m.outputBigNumberFormatter}),new s({name:"getStorageAt",call:"eth_getStorageAt",params:3,inputFormatter:[m.inputAddressFormatter,u.numberToHex,m.inputDefaultBlockNumberFormatter]}),new s({name:"getCode",call:"eth_getCode",params:2,inputFormatter:[m.inputAddressFormatter,m.inputDefaultBlockNumberFormatter]}),new s({name:"getBlock",call:v,params:2,inputFormatter:[m.inputBlockNumberFormatter,function(e){return!!e}],outputFormatter:m.outputBlockFormatter}),new s({name:"getUncle",call:w,params:2,inputFormatter:[m.inputBlockNumberFormatter,u.numberToHex],outputFormatter:m.outputBlockFormatter}),new s({name:"getBlockTransactionCount",call:_,params:1,inputFormatter:[m.inputBlockNumberFormatter],outputFormatter:u.hexToNumber}),new s({name:"getBlockUncleCount",call:A,params:1,inputFormatter:[m.inputBlockNumberFormatter],outputFormatter:u.hexToNumber}),new s({name:"getTransaction",call:"eth_getTransactionByHash",params:1,inputFormatter:[null],outputFormatter:m.outputTransactionFormatter}),new s({name:"getTransactionFromBlock",call:g,params:2,inputFormatter:[m.inputBlockNumberFormatter,u.numberToHex],outputFormatter:m.outputTransactionFormatter}),new s({name:"getTransactionReceipt",call:"eth_getTransactionReceipt",params:1,inputFormatter:[null],outputFormatter:m.outputTransactionReceiptFormatter}),new s({name:"getTransactionCount",call:"eth_getTransactionCount",params:2,inputFormatter:[m.inputAddressFormatter,m.inputDefaultBlockNumberFormatter],outputFormatter:u.hexToNumber}),new s({name:"sendSignedTransaction",call:"eth_sendRawTransaction",params:1,inputFormatter:[null]}),new s({name:"signTransaction",call:"eth_signTransaction",params:1,inputFormatter:[m.inputTransactionFormatter]}),new s({name:"sendTransaction",call:"eth_sendTransaction",params:1,inputFormatter:[m.inputTransactionFormatter]}),new s({name:"sign",call:"eth_sign",params:2,inputFormatter:[m.inputSignFormatter,m.inputAddressFormatter],transformPayload:function(e){return e.params.reverse(),e}}),new s({name:"call",call:"eth_call",params:2,inputFormatter:[m.inputCallFormatter,m.inputDefaultBlockNumberFormatter]}),new s({name:"estimateGas",call:"eth_estimateGas",params:1,inputFormatter:[m.inputCallFormatter],outputFormatter:u.hexToNumber}),new s({name:"submitWork",call:"eth_submitWork",params:3}),new s({name:"getWork",call:"eth_getWork",params:0}),new s({name:"getPastLogs",call:"eth_getLogs",params:1,inputFormatter:[m.inputLogFormatter],outputFormatter:m.outputLogFormatter}),new a({name:"subscribe",type:"eth",subscriptions:{newBlockHeaders:{subscriptionName:"newHeads",params:0,outputFormatter:m.outputBlockFormatter},pendingTransactions:{subscriptionName:"newPendingTransactions",params:0},logs:{params:1,inputFormatter:[m.inputLogFormatter],outputFormatter:m.outputLogFormatter,subscriptionHandler:function(e){e.removed?this.emit("changed",e):this.emit("data",e),n.isFunction(this.callback)&&this.callback(null,e,this)}},syncing:{params:0,outputFormatter:m.outputSyncingFormatter,subscriptionHandler:function(e){var t=this;!0!==this._isSyncing?(this._isSyncing=!0,this.emit("changed",t._isSyncing),n.isFunction(this.callback)&&this.callback(null,t._isSyncing,this),setTimeout(function(){t.emit("data",e),n.isFunction(t.callback)&&t.callback(null,e,t)},0)):(this.emit("data",e),n.isFunction(t.callback)&&this.callback(null,e,this),clearTimeout(this._isSyncingTimeout),this._isSyncingTimeout=setTimeout(function(){e.currentBlock>e.highestBlock-200&&(t._isSyncing=!1,t.emit("changed",t._isSyncing),n.isFunction(t.callback)&&t.callback(null,t._isSyncing,t))},500))}}}})];k.forEach(function(t){t.attachToObject(e),t.setRequestManager(e._requestManager,e.accounts),t.defaultBlock=e.defaultBlock,t.defaultAccount=e.defaultAccount})};i.addProviders(E),t.exports=E},{"./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(e,t,r){"use strict";var n=e("web3-core"),i=e("web3-core-method"),o=e("web3-utils"),a=function(){var e=this;n.packageInit(this,arguments),[new i({name:"getId",call:"net_version",params:0,outputFormatter:o.hexToNumber}),new i({name:"isListening",call:"net_listening",params:0}),new i({name:"getPeerCount",call:"net_peerCount",params:0,outputFormatter:o.hexToNumber})].forEach(function(t){t.attachToObject(e),t.setRequestManager(e._requestManager)})};n.addProviders(a),t.exports=a},{"web3-core":348,"web3-core-method":339,"web3-utils":403}],373:[function(e,t,r){const n=e("events").EventEmitter,i=e("util").inherits,o=e("ethereumjs-util"),a=e("eth-block-tracker"),s=e("async/map"),u=e("async/eachSeries"),c=e("./util/stoplight.js");e("./util/rpc-cache-utils.js"),e("./util/create-payload.js");function f(e){const t=this;n.call(t),t.setMaxListeners(30),e=e||{};const r={sendAsync:t._handleAsync.bind(t)},i=e.blockTrackerProvider||r;t._blockTracker=e.blockTracker||new a({provider:i,pollingInterval:e.pollingInterval||4e3}),t._blockTracker.on("block",e=>{const r=function(e){return{number:o.toBuffer(e.number),hash:o.toBuffer(e.hash),parentHash:o.toBuffer(e.parentHash),nonce:o.toBuffer(e.nonce),mixHash:o.toBuffer(e.mixHash),sha3Uncles:o.toBuffer(e.sha3Uncles),logsBloom:o.toBuffer(e.logsBloom),transactionsRoot:o.toBuffer(e.transactionsRoot),stateRoot:o.toBuffer(e.stateRoot),receiptsRoot:o.toBuffer(e.receiptRoot||e.receiptsRoot),miner:o.toBuffer(e.miner),difficulty:o.toBuffer(e.difficulty),totalDifficulty:o.toBuffer(e.totalDifficulty),size:o.toBuffer(e.size),extraData:o.toBuffer(e.extraData),gasLimit:o.toBuffer(e.gasLimit),gasUsed:o.toBuffer(e.gasUsed),timestamp:o.toBuffer(e.timestamp),transactions:e.transactions}}(e);t._setCurrentBlock(r)}),t._blockTracker.on("block",t.emit.bind(t,"rawBlock")),t._blockTracker.on("sync",t.emit.bind(t,"sync")),t._blockTracker.on("latest",t.emit.bind(t,"latest")),t._ready=new c,t._blockTracker.once("block",()=>{t._ready.go()}),t.currentBlock=null,t._providers=[]}t.exports=f,i(f,n),f.prototype.start=function(e=function(){}){this._blockTracker.start().then(e).catch(e)},f.prototype.stop=function(){this._blockTracker.stop()},f.prototype.addProvider=function(e){this._providers.push(e),e.setEngine(this)},f.prototype.send=function(e){throw new Error("Web3ProviderEngine does not support synchronous requests.")},f.prototype.sendAsync=function(e,t){const r=this;r._ready.await(function(){Array.isArray(e)?s(e,r._handleAsync.bind(r),t):r._handleAsync(e,t)})},f.prototype._handleAsync=function(e,t){var r=this,n=-1,i=null,o=null,a=[];function s(r,n){o=r,i=n,u(a,function(e,t){e?e(o,i,t):t()},function(){var r={id:e.id,jsonrpc:e.jsonrpc,result:i};null!=o?(r.error={message:o.stack||o.message||o,code:-32e3},t(o,r)):t(null,r)})}!function t(i){n+=1;a.unshift(i);if(n>=r._providers.length)s(new Error('Request for method "'+e.method+'" not handled by any subprovider. Please check your subprovider configuration to ensure this method is handled.'));else try{var o=r._providers[n];o.handleRequest(e,t,s)}catch(e){s(e)}}()},f.prototype._setCurrentBlock=function(e){this.currentBlock=e,this.emit("block",e)}},{"./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(e,t,r){var n="undefined"!=typeof JSON?JSON:e("jsonify");t.exports=function(e,t){t||(t={}),"function"==typeof t&&(t={cmp:t});var r=t.space||"";"number"==typeof r&&(r=Array(r+1).join(" "));var a,s="boolean"==typeof t.cycles&&t.cycles,u=t.replacer||function(e,t){return t},c=t.cmp&&(a=t.cmp,function(e){return function(t,r){var n={key:t,value:e[t]},i={key:r,value:e[r]};return a(n,i)}}),f=[];return function e(t,a,h,l){var d=r?"\n"+new Array(l+1).join(r):"",p=r?": ":":";if(h&&h.toJSON&&"function"==typeof h.toJSON&&(h=h.toJSON()),void 0!==(h=u.call(t,a,h))){if("object"!=typeof h||null===h)return n.stringify(h);if(i(h)){for(var b=[],y=0;y dist/ProviderEngine.js","bundle-zero":"browserify -s ZeroClientProvider -e zero.js -t [ babelify --presets [ es2015 ] ] > dist/ZeroClientProvider.js",prepublish:"npm run build && npm run bundle",test:"node test/index.js"},version:"14.1.0"}},{}],376:[function(e,t,r){const n=e("util").inherits,i=e("ethereumjs-util"),o=i.BN,a=e("clone"),s=e("../util/rpc-cache-utils.js"),u=e("../util/stoplight.js"),c=e("./subprovider.js");function f(e){e=e||{},this._ready=new u,this.strategies={perma:new l({eth_getTransactionByHash:p,eth_getTransactionReceipt:p}),block:new d(this),fork:new d(this)}}function h(){var e=this;e.cache={};var t=setInterval(function(){e.cache={}},6e5);t.unref&&t.unref()}function l(e){this.strategy=new h,this.conditionals=e}function d(){this.cache={}}function p(e){if(!e)return!1;if(!e.blockHash)return!1;var t;return(t=e.blockHash,new o(i.toBuffer(t))).gt(new o(0))}t.exports=f,n(f,c),f.prototype.setEngine=function(e){const t=this;function r(e){var r=t.currentBlock;t.currentBlock=e,r&&(t.strategies.block.cacheRollOff(r),t.strategies.fork.cacheRollOff(r))}t.engine=e,e.once("block",function(n){t.currentBlock=n,t._ready.go(),e.on("block",r)})},f.prototype.handleRequest=function(e,t,r){const n=this;return e.skipCache?t():"eth_getBlockByNumber"===e.method&&"latest"===e.params[0]?t():void n._ready.await(function(){n._handleRequest(e,t,r)})},f.prototype._handleRequest=function(e,t,r){const n=this;var o=s.cacheTypeForPayload(e),a=this.strategies[o];if(!a)return t();if(!a.canCache(e))return t();var u,c=s.blockTagForPayload(e);c||(c="latest"),u="earliest"===c?"0x00":"latest"===c?i.bufferToHex(n.currentBlock.number):c,a.hitCheck(e,u,r,function(){t(function(t,r,n){if(t)return n();a.cacheResult(e,r,u,n)})})},h.prototype.hitCheck=function(e,t,r,n){var i,o,u,c,f=s.cacheIdentifierForPayload(e),h=this.cache[f];return h&&(i=t,o=h.blockNumber,u=parseInt(i,16),c=parseInt(o,16),(u===c?0:u>c?1:-1)>=0)?r(null,a(h.result)):n()},h.prototype.cacheResult=function(e,t,r,n){var i=s.cacheIdentifierForPayload(e);if(t){var o=a(t);this.cache[i]={blockNumber:r,result:o}}n()},h.prototype.canCache=function(e){return s.canCache(e)},l.prototype.hitCheck=function(e,t,r,n){return this.strategy.hitCheck(e,t,r,n)},l.prototype.cacheResult=function(e,t,r,n){var i=this.conditionals[e.method];i?i(t)?this.strategy.cacheResult(e,t,r,n):n():this.strategy.cacheResult(e,t,r,n)},l.prototype.canCache=function(e){return this.strategy.canCache(e)},d.prototype.getBlockCacheForPayload=function(e,t){const r=Number.parseInt(t,16);let n=this.cache[r];if(!n){const e={};this.cache[r]=e,n=e}return n},d.prototype.hitCheck=function(e,t,r,n){var i=this.getBlockCacheForPayload(e,t);if(!i)return n();var o=i[s.cacheIdentifierForPayload(e)];return o?r(null,o):n()},d.prototype.cacheResult=function(e,t,r,n){t&&(this.getBlockCacheForPayload(e,r)[s.cacheIdentifierForPayload(e)]=t);n()},d.prototype.canCache=function(e){return!!s.canCache(e)&&"pending"!==s.blockTagForPayload(e)},d.prototype.cacheRollOff=function(e){const t=this,r=i.bufferToHex(e.number),n=Number.parseInt(r,16);Object.keys(t.cache).map(Number).filter(e=>e<=n).forEach(e=>delete t.cache[e])}},{"../util/rpc-cache-utils.js":394,"../util/stoplight.js":396,"./subprovider.js":387,clone:87,"ethereumjs-util":141,util:333}],377:[function(e,t,r){const n=e("util").inherits,i=e("xtend"),o=e("./fixture.js"),a=e("../package.json").version;function s(e){var t=i({web3_clientVersion:"ProviderEngine/v"+a+"/javascript",net_listening:!0,eth_hashrate:"0x00",eth_mining:!1},e=e||{});o.call(this,t)}t.exports=s,n(s,o)},{"../package.json":375,"./fixture.js":380,util:333,xtend:423}],378:[function(e,t,r){const n=e("cross-fetch"),i=e("util").inherits,o=e("async/retry"),a=e("async/waterfall"),s=e("async/asyncify"),u=e("json-rpc-error"),c=e("promise-to-callback"),f=e("../util/create-payload.js"),h=e("./subprovider.js"),l=["Gateway timeout","ETIMEDOUT","SyntaxError"];function d(e){this.rpcUrl=e.rpcUrl,this.originHttpHeaderKey=e.originHttpHeaderKey}function p(e){const t=e.toString();return l.some(e=>t.includes(e))}t.exports=d,i(d,h),d.prototype.handleRequest=function(e,t,r){const n=this,i=e.origin,a=f(e);delete a.origin;const s={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(a)};n.originHttpHeaderKey&&i&&(s.headers[n.originHttpHeaderKey]=i),o({times:5,interval:1e3,errorFilter:p},e=>n._submitRequest(s,e),(e,t)=>{if(e&&p(e)){const t=`FetchSubprovider - cannot complete request. All retries exhausted.\nOriginal Error:\n${e.toString()}\n\n`,n=new Error(t);return r(n)}return r(e,t)})},d.prototype._submitRequest=function(e,t){const r=this.rpcUrl;c(n(r,e))((e,r)=>{if(e)return t(e);a([function(e){switch(r.status){case 405:return e(new u.MethodNotFound);case 418:return e(function(){const e=new Error("Request is being rate limited.");return new u.InternalError(e)}());case 503:case 504:return e(function(){let e="Gateway timeout. The request took too long to process. ";const t=new Error(e+="This can happen when querying logs over too wide a block range.");return new u.InternalError(t)}());default:return e()}},e=>c(r.text())(e),s(e=>JSON.parse(e)),function(e,t){if(200!==r.status)return t(new u.InternalError(e));if(e.error)return t(new u.InternalError(e.error));t(null,e.result)}],t)})}},{"../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(e,t,r){const n=e("async"),i=e("util").inherits,o=e("ethereumjs-util"),a=e("./subprovider.js"),s=e("../util/stoplight.js"),u=e("events").EventEmitter;function c(e){e=e||{};const t=this;t.filterIndex=0,t.filters={},t.filterDestroyHandlers={},t.asyncBlockHandlers={},t.asyncPendingBlockHandlers={},t._ready=new s,t._ready.setMaxListeners(e.maxFilters||25),t._ready.go(),t.pendingBlockTimeout=e.pendingBlockTimeout||4e3,t.checkForPendingBlocksActive=!1,setTimeout(function(){t.engine.on("block",function(e){t._ready.stop();var r=v(t.asyncBlockHandlers).map(function(t){return t.bind(null,e)});n.parallel(r,function(e){e&&console.error(e),t._ready.go()})})})}function f(e){u.apply(this),this.type="block",this.engine=e.engine,this.blockNumber=e.blockNumber,this.updates=[]}function h(e){u.apply(this),this.type="log",this.fromBlock=void 0!==e.fromBlock?e.fromBlock:"latest",this.toBlock=void 0!==e.toBlock?e.toBlock:"latest";var t=e.address&&(Array.isArray(e.address)?e.address:[e.address]);this.address=t&&t.map(d),this.topics=e.topics||[],this.updates=[],this.allResults=[]}function l(){u.apply(this),this.type="pendingTx",this.updates=[],this.allResults=[]}function d(e){return"0x"===e.slice(0,2)?e:"0x"+e}function p(e){return o.intToHex(e)}function b(e){return Number(e)}function y(e){return function(e){let t=o.stripHexPrefix(e);for(;"0"===t[0];)t=t.substr(1);return`0x${t}`}(e.toString("hex"))}function m(e){return e&&-1===["earliest","latest","pending"].indexOf(e)}function v(e){return Object.keys(e).map(function(t){return e[t]})}t.exports=c,i(c,a),c.prototype.handleRequest=function(e,t,r){const n=this;switch(e.method){case"eth_newBlockFilter":return void n.newBlockFilter(r);case"eth_newPendingTransactionFilter":return n.newPendingTransactionFilter(r),void n.checkForPendingBlocks();case"eth_newFilter":return void n.newLogFilter(e.params[0],r);case"eth_getFilterChanges":return void n._ready.await(function(){n.getFilterChanges(e.params[0],r)});case"eth_getFilterLogs":return void n._ready.await(function(){n.getFilterLogs(e.params[0],r)});case"eth_uninstallFilter":return void n._ready.await(function(){n.uninstallFilter(e.params[0],r)});default:return void t()}},c.prototype.newBlockFilter=function(e){const t=this;t._getBlockNumber(function(r,n){if(r)return e(r);var i=new f({blockNumber:n}),o=i.update.bind(i);t.engine.on("block",o);t.filterIndex++,t.filters[t.filterIndex]=i,t.filterDestroyHandlers[t.filterIndex]=function(){t.engine.removeListener("block",o)};var a=p(t.filterIndex);e(null,a)})},c.prototype.newLogFilter=function(e,t){const r=this;r._getBlockNumber(function(n,i){if(n)return t(n);var o=new h(e),a=o.update.bind(o);r.filterIndex++,r.asyncBlockHandlers[r.filterIndex]=function(e,t){r._logsForBlock(e,function(e,r){if(e)return t(e);a(r),t()})},r.filters[r.filterIndex]=o;var s=p(r.filterIndex);t(null,s)})},c.prototype.newPendingTransactionFilter=function(e){const t=this;var r=new l,n=r.update.bind(r);t.filterIndex++,t.asyncPendingBlockHandlers[t.filterIndex]=function(e,r){t._txHashesForBlock(e,function(e,t){if(e)return r(e);n(t),r()})},t.filters[t.filterIndex]=r,e(null,p(t.filterIndex))},c.prototype.getFilterChanges=function(e,t){var r=Number.parseInt(e,16),n=this.filters[r];if(n||console.warn("FilterSubprovider - no filter with that id:",e),!n)return t(null,[]);var i=n.getChanges();n.clearChanges(),t(null,i)},c.prototype.getFilterLogs=function(e,t){const r=this;var n=Number.parseInt(e,16),i=r.filters[n];if(i||console.warn("FilterSubprovider - no filter with that id:",e),!i)return t(null,[]);if("log"===i.type)r.emitPayload({method:"eth_getLogs",params:[{fromBlock:i.fromBlock,toBlock:i.toBlock,address:i.address,topics:i.topics}]},function(e,r){if(e)return t(e);t(null,r.result)});else{t(null,[])}},c.prototype.uninstallFilter=function(e,t){var r=Number.parseInt(e,16);if(this.filters[r]){this.filters[r].removeAllListeners();var n=this.filterDestroyHandlers[r];delete this.filters[r],delete this.asyncBlockHandlers[r],delete this.asyncPendingBlockHandlers[r],delete this.filterDestroyHandlers[r],n&&n(),t(null,!0)}else t(null,!1)},c.prototype.checkForPendingBlocks=function(){const e=this;e.checkForPendingBlocksActive||!!Object.keys(e.asyncPendingBlockHandlers).length&&(e.checkForPendingBlocksActive=!0,e.emitPayload({method:"eth_getBlockByNumber",params:["pending",!0]},function(t,r){if(t)return e.checkForPendingBlocksActive=!1,void console.error(t);e.onNewPendingBlock(r.result,function(t){t&&console.error(t),e.checkForPendingBlocksActive=!1,setTimeout(e.checkForPendingBlocks.bind(e),e.pendingBlockTimeout)})}))},c.prototype.onNewPendingBlock=function(e,t){var r=v(this.asyncPendingBlockHandlers).map(function(t){return t.bind(null,e)});n.parallel(r,t)},c.prototype._getBlockNumber=function(e){e(null,y(this.engine.currentBlock.number))},c.prototype._logsForBlock=function(e,t){var r=y(e.number);this.emitPayload({method:"eth_getLogs",params:[{fromBlock:r,toBlock:r}]},function(e,r){return e?t(e):r.error?t(r.error):void t(null,r.result)})},c.prototype._txHashesForBlock=function(e,t){var r=e.transactions;if(0===r.length)return t(null,[]);"string"==typeof r[0]?t(null,r):t(null,r.map(e=>e.hash))},i(f,u),f.prototype.update=function(e){var t="0x"+e.hash.toString("hex");this.updates.push(t),this.emit("data",e)},f.prototype.getChanges=function(){return this.updates},f.prototype.clearChanges=function(){this.updates=[]},i(h,u),h.prototype.validateLog=function(e){return!(m(this.fromBlock)&&b(this.fromBlock)>=b(e.blockNumber))&&(!(m(this.toBlock)&&b(this.toBlock)<=b(e.blockNumber))&&(!(this.address&&!this.address.map(e=>e.toLowerCase()).includes(e.address.toLowerCase()))&&this.topics.reduce(function(t,r,n){if(!t)return!1;if(!r)return!0;var i=e.topics[n];return!!i&&(Array.isArray(r)?r:[r]).filter(function(e){return i.toLowerCase()===e.toLowerCase()}).length>0},!0)))},h.prototype.update=function(e){const t=this;var r=[];e.forEach(function(e){t.validateLog(e)&&(r.push(e),t.updates.push(e),t.allResults.push(e))}),r.length>0&&t.emit("data",r)},h.prototype.getChanges=function(){return this.updates},h.prototype.getAllResults=function(){return this.allResults},h.prototype.clearChanges=function(){this.updates=[]},i(l,u),l.prototype.validateUnique=function(e){return-1===this.allResults.indexOf(e)},l.prototype.update=function(e){const t=this;var r=[];e.forEach(function(e){t.validateUnique(e)&&(r.push(e),t.updates.push(e),t.allResults.push(e))}),r.length>0&&t.emit("data",r)},l.prototype.getChanges=function(){return this.updates},l.prototype.getAllResults=function(){return this.allResults},l.prototype.clearChanges=function(){this.updates=[]}},{"../util/stoplight.js":396,"./subprovider.js":387,async:21,"ethereumjs-util":141,events:157,util:333}],380:[function(e,t,r){const n=e("util").inherits,i=e("./subprovider.js");function o(e){e=e||{},this.staticResponses=e}t.exports=o,n(o,i),o.prototype.handleRequest=function(e,t,r){var n=this.staticResponses[e.method];"function"==typeof n?n(e,t,r):void 0!==n?setTimeout(()=>r(null,n)):t()}},{"./subprovider.js":387,util:333}],381:[function(e,t,r){const n=e("async/waterfall"),i=e("async/parallel"),o=e("util").inherits,a=e("ethereumjs-util"),s=e("eth-sig-util"),u=e("xtend"),c=e("semaphore"),f=e("./subprovider.js"),h=e("../util/estimate-gas.js"),l=/^[0-9A-Fa-f]+$/g;function d(e){this.nonceLock=c(1),e.getAccounts&&(this.getAccounts=e.getAccounts),e.processTransaction&&(this.processTransaction=e.processTransaction),e.processMessage&&(this.processMessage=e.processMessage),e.processPersonalMessage&&(this.processPersonalMessage=e.processPersonalMessage),e.processTypedMessage&&(this.processTypedMessage=e.processTypedMessage),this.approveTransaction=e.approveTransaction||this.autoApprove,this.approveMessage=e.approveMessage||this.autoApprove,this.approvePersonalMessage=e.approvePersonalMessage||this.autoApprove,this.approveTypedMessage=e.approveTypedMessage||this.autoApprove,e.signTransaction&&(this.signTransaction=e.signTransaction||y("signTransaction")),e.signMessage&&(this.signMessage=e.signMessage||y("signMessage")),e.signPersonalMessage&&(this.signPersonalMessage=e.signPersonalMessage||y("signPersonalMessage")),e.signTypedMessage&&(this.signTypedMessage=e.signTypedMessage||y("signTypedMessage")),e.recoverPersonalSignature&&(this.recoverPersonalSignature=e.recoverPersonalSignature),e.publishTransaction&&(this.publishTransaction=e.publishTransaction)}function p(e){return e.toLowerCase()}function b(e){return"string"==typeof e&&("0x"===e.slice(0,2)&&e.slice(2).match(l))}function y(e){return function(t,r){r(new Error('ProviderEngine - HookedWalletSubprovider - Must provide "'+e+'" fn in constructor options'))}}t.exports=d,o(d,f),d.prototype.handleRequest=function(e,t,r){const i=this;let o,s,c,f,h;switch(i._parityRequests={},i._parityRequestCount=0,e.method){case"eth_coinbase":return void i.getAccounts(function(e,t){if(e)return r(e);let n=t[0]||null;r(null,n)});case"eth_accounts":return void i.getAccounts(function(e,t){if(e)return r(e);r(null,t)});case"eth_sendTransaction":return o=e.params[0],void n([e=>i.validateTransaction(o,e),e=>i.processTransaction(o,e)],r);case"eth_signTransaction":return o=e.params[0],void n([e=>i.validateTransaction(o,e),e=>i.processSignTransaction(o,e)],r);case"eth_sign":return h=e.params[0],f=e.params[1],c=e.params[2]||{},s=u(c,{from:h,data:f}),void n([e=>i.validateMessage(s,e),e=>i.processMessage(s,e)],r);case"personal_sign":const l=e.params[0];if(function(e){const t=a.addHexPrefix(e);return!a.isValidAddress(t)&&b(e)}(e.params[1])&&function(e){const t=a.addHexPrefix(e);return a.isValidAddress(t)}(l)){let t="The eth_personalSign method requires params ordered ";t+="[message, address]. This was previously handled incorrectly, ",t+="and has been corrected automatically. ",t+="Please switch this param order for smooth behavior in the future.",console.warn(t),h=e.params[0],f=e.params[1]}else f=e.params[0],h=e.params[1];return c=e.params[2]||{},s=u(c,{from:h,data:f}),void n([e=>i.validatePersonalMessage(s,e),e=>i.processPersonalMessage(s,e)],r);case"personal_ecRecover":f=e.params[0];let d=e.params[1];return c=e.params[2]||{},s=u(c,{sig:d,data:f}),void i.recoverPersonalSignature(s,r);case"eth_signTypedData":return f=e.params[0],h=e.params[1],c=e.params[2]||{},s=u(c,{from:h,data:f}),void n([e=>i.validateTypedMessage(s,e),e=>i.processTypedMessage(s,e)],r);case"parity_postTransaction":return o=e.params[0],void i.parityPostTransaction(o,r);case"parity_postSign":return h=e.params[0],f=e.params[1],void i.parityPostSign(h,f,r);case"parity_checkRequest":const p=e.params[0];return void i.parityCheckRequest(p,r);case"parity_defaultAccount":return void i.getAccounts(function(e,t){if(e)return r(e);const n=t[0]||null;r(null,n)});default:return void t()}},d.prototype.getAccounts=function(e){e(null,[])},d.prototype.processTransaction=function(e,t){const r=this;n([t=>r.approveTransaction(e,t),(e,t)=>r.checkApproval("transaction",e,t),t=>r.finalizeAndSubmitTx(e,t)],t)},d.prototype.processSignTransaction=function(e,t){const r=this;n([t=>r.approveTransaction(e,t),(e,t)=>r.checkApproval("transaction",e,t),t=>r.finalizeTx(e,t)],t)},d.prototype.processMessage=function(e,t){const r=this;n([t=>r.approveMessage(e,t),(e,t)=>r.checkApproval("message",e,t),t=>r.signMessage(e,t)],t)},d.prototype.processPersonalMessage=function(e,t){const r=this;n([t=>r.approvePersonalMessage(e,t),(e,t)=>r.checkApproval("message",e,t),t=>r.signPersonalMessage(e,t)],t)},d.prototype.processTypedMessage=function(e,t){const r=this;n([t=>r.approveTypedMessage(e,t),(e,t)=>r.checkApproval("message",e,t),t=>r.signTypedMessage(e,t)],t)},d.prototype.autoApprove=function(e,t){t(null,!0)},d.prototype.checkApproval=function(e,t,r){r(t?null:new Error("User denied "+e+" signature."))},d.prototype.parityPostTransaction=function(e,t){const r=this,n=`0x${r._parityRequestCount.toString(16)}`;r._parityRequestCount++,r.emitPayload({method:"eth_sendTransaction",params:[e]},function(e,t){if(e)return void(r._parityRequests[n]={error:e});const i=t.result;r._parityRequests[n]=i}),t(null,n)},d.prototype.parityPostSign=function(e,t,r){const n=this,i=`0x${n._parityRequestCount.toString(16)}`;n._parityRequestCount++,n.emitPayload({method:"eth_sign",params:[e,t]},function(e,t){if(e)return void(n._parityRequests[i]={error:e});const r=t.result;n._parityRequests[i]=r}),r(null,i)},d.prototype.parityCheckRequest=function(e,t){const r=this._parityRequests[e]||null;return r?r.error?t(r.error):void t(null,r):t(null,null)},d.prototype.recoverPersonalSignature=function(e,t){let r;try{r=s.recoverPersonalSignature(e)}catch(e){return t(e)}t(null,r)},d.prototype.validateTransaction=function(e,t){if(void 0===e.from)return t(new Error("Undefined address - from address required to sign transaction."));this.validateSender(e.from,function(r,n){return r?t(r):n?void t():t(new Error(`Unknown address - unable to sign transaction for this address: "${e.from}"`))})},d.prototype.validateMessage=function(e,t){if(void 0===e.from)return t(new Error("Undefined address - from address required to sign message."));this.validateSender(e.from,function(r,n){return r?t(r):n?void t():t(new Error(`Unknown address - unable to sign message for this address: "${e.from}"`))})},d.prototype.validatePersonalMessage=function(e,t){return void 0===e.from?t(new Error("Undefined address - from address required to sign personal message.")):void 0===e.data?t(new Error("Undefined message - message required to sign personal message.")):b(e.data)?void this.validateSender(e.from,function(r,n){return r?t(r):n?void t():t(new Error(`Unknown address - unable to sign message for this address: "${e.from}"`))}):t(new Error("HookedWalletSubprovider - validateMessage - message was not encoded as hex."))},d.prototype.validateTypedMessage=function(e,t){return void 0===e.from?t(new Error("Undefined address - from address required to sign typed data.")):void 0===e.data?t(new Error("Undefined data - message required to sign typed data.")):void this.validateSender(e.from,function(r,n){return r?t(r):n?void t():t(new Error(`Unknown address - unable to sign message for this address: "${e.from}"`))})},d.prototype.validateSender=function(e,t){if(!e)return t(null,!1);this.getAccounts(function(r,n){if(r)return t(r);const i=-1!==n.map(p).indexOf(e.toLowerCase());t(null,i)})},d.prototype.finalizeAndSubmitTx=function(e,t){const r=this;r.nonceLock.take(function(){n([r.fillInTxExtras.bind(r,e),r.signTransaction.bind(r),r.publishTransaction.bind(r)],function(e,n){if(r.nonceLock.leave(),e)return t(e);t(null,n)})})},d.prototype.finalizeTx=function(e,t){const r=this;r.nonceLock.take(function(){n([r.fillInTxExtras.bind(r,e),r.signTransaction.bind(r)],function(n,i){if(r.nonceLock.leave(),n)return t(n);t(null,{raw:i,tx:e})})})},d.prototype.publishTransaction=function(e,t){this.emitPayload({method:"eth_sendRawTransaction",params:[e]},function(e,r){if(e)return t(e);t(null,r.result)})},d.prototype.fillInTxExtras=function(e,t){const r=this,n=e.from,o={};void 0===e.gasPrice&&(o.gasPrice=r.emitPayload.bind(r,{method:"eth_gasPrice",params:[]})),void 0===e.nonce&&(o.nonce=r.emitPayload.bind(r,{method:"eth_getTransactionCount",params:[n,"pending"]})),void 0===e.gas&&(o.gas=h.bind(null,r.engine,function(e){return{from:e.from,to:e.to,value:e.value,data:e.data,gas:e.gas,gasPrice:e.gasPrice,nonce:e.nonce}}(e))),i(o,function(r,n){if(r)return t(r);const i={};n.gasPrice&&(i.gasPrice=n.gasPrice.result),n.nonce&&(i.nonce=n.nonce.result),n.gas&&(i.gas=n.gas),t(null,u(e,i))})}},{"../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(e,t,r){const n=e("../util/rpc-cache-utils.js").cacheIdentifierForPayload,i=e("./subprovider.js");t.exports=class extends i{constructor(e){super(),this.inflightRequests={}}addEngine(e){this.engine=e}handleRequest(e,t,r){const i=n(e,{includeBlockRef:!0});if(!i)return t();let o=this.inflightRequests[i];o?o.push(r):(o=[],this.inflightRequests[i]=o,t((e,t,r)=>{delete this.inflightRequests[i],o.forEach(r=>r(e,t)),r(e,t)}))}}},{"../util/rpc-cache-utils.js":394,"./subprovider.js":387}],383:[function(e,t,r){const n=e("eth-json-rpc-infura/src/createProvider"),i=e("./provider.js");t.exports=class extends i{constructor(e={}){super(n(e))}}},{"./provider.js":385,"eth-json-rpc-infura/src/createProvider":129}],384:[function(e,t,r){(function(r){const n=e("util").inherits,i=e("ethereumjs-tx"),o=e("ethereumjs-util"),a=e("./subprovider.js"),s=e("../util/rpc-cache-utils").blockTagForPayload;function u(e){this.nonceCache={}}t.exports=u,n(u,a),u.prototype.handleRequest=function(e,t,n){const a=this;switch(e.method){case"eth_getTransactionCount":var u=s(e),c=e.params[0].toLowerCase(),f=a.nonceCache[c];return void("pending"===u?f?n(null,f):t(function(e,t,r){if(e)return r();void 0===a.nonceCache[c]&&(a.nonceCache[c]=t),r()}):t());case"eth_sendRawTransaction":return void t(function(t,n,s){if(t)return s();var u=e.params[0],c=(o.stripHexPrefix(u),new r(o.stripHexPrefix(u),"hex"),new i(new r(o.stripHexPrefix(u),"hex"))),f="0x"+c.getSenderAddress().toString("hex").toLowerCase(),h=o.bufferToInt(c.nonce),l=(++h).toString(16);l.length%2&&(l="0"+l),l="0x"+l,a.nonceCache[f]=l,s()});default:return void t()}}}).call(this,e("buffer").Buffer)},{"../util/rpc-cache-utils":394,"./subprovider.js":387,buffer:84,"ethereumjs-tx":140,"ethereumjs-util":141,util:333}],385:[function(e,t,r){const n=e("util").inherits,i=e("./subprovider.js");function o(e){if(!e)throw new Error("ProviderSubprovider - no provider specified");if(!e.sendAsync)throw new Error("ProviderSubprovider - specified provider does not have a sendAsync method");this.provider=e}t.exports=o,n(o,i),o.prototype.handleRequest=function(e,t,r){this.provider.sendAsync(e,function(e,t){return e?r(e):t.error?r(new Error(t.error.message)):void r(null,t.result)})}},{"./subprovider.js":387,util:333}],386:[function(e,t,r){const n=e("util").inherits,i=e("./subprovider.js"),o=(e("xtend"),e("ethereumjs-util"));function a(e){}t.exports=a,n(a,i),a.prototype.handleRequest=function(e,t,r){var n=e.params[0];if("object"==typeof n&&!Array.isArray(n)){var i=function(e){return s.reduce(function(t,r){return r in e&&(Array.isArray(e[r])?t[r]=e[r].map(function(e){return u(e)}):t[r]=u(e[r])),t},{})}(n);e.params[0]=i}t()};var s=["from","to","value","data","gas","gasPrice","nonce","fromBlock","toBlock","address","topics"];function u(e){switch(e){case"latest":case"pending":case"earliest":return e;default:return"string"==typeof e?o.addHexPrefix(e.toLowerCase()):e}}},{"./subprovider.js":387,"ethereumjs-util":141,util:333,xtend:423}],387:[function(e,t,r){const n=e("../util/create-payload.js");function i(){}t.exports=i,i.prototype.setEngine=function(e){const t=this;t.engine=e,e.on("block",function(e){t.currentBlock=e})},i.prototype.handleRequest=function(e,t,r){throw new Error("Subproviders should override `handleRequest`.")},i.prototype.emitPayload=function(e,t){this.engine.sendAsync(n(e),t)}},{"../util/create-payload.js":391}],388:[function(e,t,r){const n=e("events").EventEmitter,i=e("./filters.js"),o=e("../util/rpc-hex-encoding.js"),a=e("util").inherits,s=e("ethereumjs-util");function u(e){e=e||{},n.apply(this,Array.prototype.slice.call(arguments)),i.apply(this,[e]),this.subscriptions={}}a(u,i),Object.assign(u.prototype,n.prototype),u.prototype.constructor=u,u.prototype.eth_subscribe=function(e,t){const r=this;let n=()=>{},i=e.params[0];switch(i){case"logs":let o=e.params[1];n=r.newLogFilter.bind(r,o);break;case"newPendingTransactions":n=r.newPendingTransactionFilter.bind(r);break;case"newHeads":n=r.newBlockFilter.bind(r);break;case"syncing":default:return void t(new Error("unsupported subscription type"))}n(function(e,n){if(e)return t(e);const o=Number.parseInt(n,16);r.subscriptions[o]=i,r.filters[o].on("data",function(e){Array.isArray(e)||(e=[e]);var t=r._notificationHandler.bind(r,n,i);e.forEach(t),r.filters[o].clearChanges()}),"newPendingTransactions"===i&&r.checkForPendingBlocks(),t(null,n)})},u.prototype.eth_unsubscribe=function(e,t){const r=this;let n=e.params[0];const i=Number.parseInt(n,16);if(r.subscriptions[i]){r.subscriptions[i];r.uninstallFilter(n,function(e,n){delete r.subscriptions[i],t(e,n)})}else t(new Error(`Subscription ID ${n} not found.`))},u.prototype._notificationHandler=function(e,t,r){const n=this;"newHeads"===t&&(r=n._notificationResultFromBlock(r)),n.emit("data",null,{jsonrpc:"2.0",method:"eth_subscription",params:{subscription:e,result:r}})},u.prototype._notificationResultFromBlock=function(e){return{hash:s.bufferToHex(e.hash),parentHash:s.bufferToHex(e.parentHash),sha3Uncles:s.bufferToHex(e.sha3Uncles),miner:s.bufferToHex(e.miner),stateRoot:s.bufferToHex(e.stateRoot),transactionsRoot:s.bufferToHex(e.transactionsRoot),receiptsRoot:s.bufferToHex(e.receiptsRoot),logsBloom:s.bufferToHex(e.logsBloom),difficulty:o.intToQuantityHex(s.bufferToInt(e.difficulty)),number:o.intToQuantityHex(s.bufferToInt(e.number)),gasLimit:o.intToQuantityHex(s.bufferToInt(e.gasLimit)),gasUsed:o.intToQuantityHex(s.bufferToInt(e.gasUsed)),nonce:e.nonce?s.bufferToHex(e.nonce):null,mixHash:s.bufferToHex(e.mixHash),timestamp:o.intToQuantityHex(s.bufferToInt(e.timestamp)),extraData:s.bufferToHex(e.extraData)}},u.prototype.handleRequest=function(e,t,r){switch(e.method){case"eth_subscribe":this.eth_subscribe(e,r);break;case"eth_unsubscribe":this.eth_unsubscribe(e,r);break;default:i.prototype.handleRequest.apply(this,Array.prototype.slice.call(arguments))}},t.exports=u},{"../util/rpc-hex-encoding.js":395,"./filters.js":379,"ethereumjs-util":141,events:157,util:333}],389:[function(e,t,r){(function(r){const n=e("backoff"),i=e("events"),o=(e("util").inherits,r.WebSocket||e("ws")),a=e("./subprovider"),s=e("../util/create-payload");class u extends a{constructor({rpcUrl:e,debug:t,origin:r}){super(),i.call(this),Object.defineProperties(this,{_backoff:{value:n.exponential({randomisationFactor:.2,maxDelay:5e3})},_connectTime:{value:null,writable:!0},_log:{value:t?(...e)=>console.info.apply(console,["[WSProvider]",...e]):()=>{}},_origin:{value:r},_pendingRequests:{value:new Map},_socket:{value:null,writable:!0},_unhandledRequests:{value:[]},_url:{value:e}}),this._handleSocketClose=this._handleSocketClose.bind(this),this._handleSocketMessage=this._handleSocketMessage.bind(this),this._handleSocketOpen=this._handleSocketOpen.bind(this),this._backoff.on("ready",()=>{this._openSocket()}),this._openSocket()}handleRequest(e,t,r){if(!this._socket||this._socket.readyState!==o.OPEN)return this._unhandledRequests.push(Array.from(arguments)),void this._log("Socket not open. Request queued.");this._pendingRequests.set(e.id,[e,r]);const n=s(e);delete n.origin,this._socket.send(JSON.stringify(n)),this._log(`Sent: ${n.method} #${n.id}`)}_handleSocketClose({reason:e,code:t}){this._log(`Socket closed, code ${t} (${e||"no reason"})`),this._connectTime&&Date.now()-this._connectTime>5e3&&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(e){let t;try{t=JSON.parse(e.data)}catch(e){return void this._log("Received a message that is not valid JSON:",t)}if(void 0===t.id)return this.emit("data",null,t);if(!this._pendingRequests.has(t.id))return;const[r,n]=this._pendingRequests.get(t.id);if(this._pendingRequests.delete(t.id),this._log(`Received: ${r.method} #${t.id}`),t.error)return n(new Error(t.error.message));n(null,t.result)}_handleSocketOpen(){this._log("Socket open."),this._connectTime=Date.now(),this._pendingRequests.forEach(([e,t])=>{this._unhandledRequests.push([e,null,t])}),this._pendingRequests.clear(),this._unhandledRequests.splice(0,this._unhandledRequests.length).forEach(e=>{this.handleRequest.apply(this,e)})}_openSocket(){this._log("Opening socket..."),this._socket=new o(this._url,null,{origin:this._origin}),this._socket.addEventListener("close",this._handleSocketClose),this._socket.addEventListener("message",this._handleSocketMessage),this._socket.addEventListener("open",this._handleSocketOpen)}}Object.assign(u.prototype,i.prototype),t.exports=u}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../util/create-payload":391,"./subprovider":387,backoff:45,events:157,util:333,ws:55}],390:[function(e,t,r){t.exports=function(e,t){if(!e)throw t||"Assertion failed"}},{}],391:[function(e,t,r){const n=e("./random-id.js"),i=e("xtend");t.exports=function(e){return i({id:n(),jsonrpc:"2.0",params:[]},e)}},{"./random-id.js":393,xtend:423}],392:[function(e,t,r){const n=e("./create-payload.js");t.exports=function(e,t,r){e.sendAsync(n({method:"eth_estimateGas",params:[t]}),function(e,t){if(e)return"no contract code at given address"===e.message?r(null,"0xcf08"):r(e);r(null,t.result)})}},{"./create-payload.js":391}],393:[function(e,t,r){const n=3;t.exports=function(){var e=(new Date).getTime()*Math.pow(10,n),t=Math.floor(Math.random()*Math.pow(10,n));return e+t}},{}],394:[function(e,t,r){const n=e("json-stable-stringify");function i(e){return"never"!==s(e)}function o(e){var t=a(e);return t>=e.params.length?e.params:"eth_getBlockByNumber"===e.method?e.params.slice(1):e.params.slice(0,t)}function a(e){switch(e.method){case"eth_getStorageAt":return 2;case"eth_getBalance":case"eth_getCode":case"eth_getTransactionCount":case"eth_call":case"eth_estimateGas":return 1;case"eth_getBlockByNumber":return 0;default:return}}function s(e){switch(e.method){case"web3_clientVersion":case"web3_sha3":case"eth_protocolVersion":case"eth_getBlockTransactionCountByHash":case"eth_getUncleCountByBlockHash":case"eth_getCode":case"eth_getBlockByHash":case"eth_getTransactionByHash":case"eth_getTransactionByBlockHashAndIndex":case"eth_getTransactionReceipt":case"eth_getUncleByBlockHashAndIndex":case"eth_getCompilers":case"eth_compileLLL":case"eth_compileSolidity":case"eth_compileSerpent":case"shh_version":return"perma";case"eth_getBlockByNumber":case"eth_getBlockTransactionCountByNumber":case"eth_getUncleCountByBlockNumber":case"eth_getTransactionByBlockNumberAndIndex":case"eth_getUncleByBlockNumberAndIndex":return"fork";case"eth_gasPrice":case"eth_blockNumber":case"eth_getBalance":case"eth_getStorageAt":case"eth_getTransactionCount":case"eth_call":case"eth_estimateGas":case"eth_getFilterLogs":case"eth_getLogs":case"net_peerCount":return"block";case"net_version":case"net_peerCount":case"net_listening":case"eth_syncing":case"eth_sign":case"eth_coinbase":case"eth_mining":case"eth_hashrate":case"eth_accounts":case"eth_sendTransaction":case"eth_sendRawTransaction":case"eth_newFilter":case"eth_newBlockFilter":case"eth_newPendingTransactionFilter":case"eth_uninstallFilter":case"eth_getFilterChanges":case"eth_getWork":case"eth_submitWork":case"eth_submitHashrate":case"db_putString":case"db_getString":case"db_putHex":case"db_getHex":case"shh_post":case"shh_newIdentity":case"shh_hasIdentity":case"shh_newGroup":case"shh_addToGroup":case"shh_newFilter":case"shh_uninstallFilter":case"shh_getFilterChanges":case"shh_getMessages":return"never"}}t.exports={cacheIdentifierForPayload:function(e,t={}){if(!i(e))return null;const{includeBlockRef:r}=t,a=r?e.params:o(e);return e.method+":"+n(a)},canCache:i,blockTagForPayload:function(e){var t=a(e);if(t>=e.params.length)return null;return e.params[t]},paramsWithoutBlockTag:o,blockTagParamIndex:a,cacheTypeForPayload:s}},{"json-stable-stringify":374}],395:[function(e,t,r){(function(r){const n=e("ethereumjs-util"),i=e("./assert.js");t.exports={intToQuantityHex:function(e){i("number"==typeof e&&e===Math.floor(e),"intToQuantityHex arg must be an integer");var t=n.toBuffer(e).toString("hex");"0"===t[0]&&(t=t.substring(1));return n.addHexPrefix(t)},quantityHexToInt:function(e){i("string"==typeof e,"arg to quantityHexToInt must be a string");var t=n.stripHexPrefix(e);t.length%2!=0&&(t="0"+t);var o=new r(t,"hex");return n.bufferToInt(o)}}}).call(this,e("buffer").Buffer)},{"./assert.js":390,buffer:84,"ethereumjs-util":141}],396:[function(e,t,r){const n=e("events").EventEmitter,i=e("util").inherits;function o(){n.call(this),this.isLocked=!0}t.exports=o,i(o,n),o.prototype.go=function(){this.isLocked=!1,this.emit("unlock")},o.prototype.stop=function(){this.isLocked=!0,this.emit("lock")},o.prototype.await=function(e){const t=this;t.isLocked?t.once("unlock",e):setTimeout(e)}},{events:157,util:333}],397:[function(e,t,r){const n=e("./index.js"),i=e("./subproviders/default-fixture.js"),o=e("./subproviders/nonce-tracker.js"),a=e("./subproviders/cache.js"),s=e("./subproviders/filters.js"),u=e("./subproviders/subscriptions"),c=e("./subproviders/inflight-cache"),f=e("./subproviders/hooked-wallet.js"),h=e("./subproviders/sanitizer.js"),l=e("./subproviders/infura.js"),d=e("./subproviders/fetch.js"),p=e("./subproviders/websocket.js");t.exports=function(e={}){const t=function({rpcUrl:e}){if(!e)return;switch(e.split(":")[0].toLowerCase()){case"http":case"https":return"http";case"ws":case"wss":return"ws";default:throw new Error(`ProviderEngine - unrecognized protocol in "${e}"`)}}(e),r=new n(e.engineParams),b=new i(e.static);r.addProvider(b),r.addProvider(new o);const y=new h;r.addProvider(y);const m=new a;if(r.addProvider(m),"ws"===t){const e=new s;r.addProvider(e)}else{const e=new u;e.on("data",(e,t)=>{r.emit("data",e,t)}),r.addProvider(e)}const v=new c;r.addProvider(v);const g=new f({getAccounts:e.getAccounts,processTransaction:e.processTransaction,approveTransaction:e.approveTransaction,signTransaction:e.signTransaction,publishTransaction:e.publishTransaction,processMessage:e.processMessage,approveMessage:e.approveMessage,signMessage:e.signMessage,processPersonalMessage:e.processPersonalMessage,processTypedMessage:e.processTypedMessage,approvePersonalMessage:e.approvePersonalMessage,approveTypedMessage:e.approveTypedMessage,signPersonalMessage:e.signPersonalMessage,signTypedMessage:e.signTypedMessage,personalRecoverSigner:e.personalRecoverSigner});r.addProvider(g);const w=e.dataSubprovider||function(e,t){const{rpcUrl:r,debug:n}=t;if(!e)return new l;if("http"===e)return new d({rpcUrl:r,debug:n});if("ws"===e)return new p({rpcUrl:r,debug:n});throw new Error(`ProviderEngine - unrecognized connectionType "${e}"`)}(t,e);"ws"===t&&w.on("data",(e,t)=>{r.emit("data",e,t)});r.addProvider(w),e.stopped||r.start();return r}},{"./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(e,t,r){var n=e("web3-core-helpers").errors,i=e("xhr2-cookies").XMLHttpRequest,o=e("http"),a=e("https"),s=function(e,t){t=t||{},this.host=e||"http://localhost:8545","https"===this.host.substring(0,5)?this.httpsAgent=new a.Agent({keepAlive:!0}):this.httpAgent=new o.Agent({keepAlive:!0}),this.timeout=t.timeout||0,this.headers=t.headers,this.connected=!1};s.prototype._prepareRequest=function(){var e=new i;return e.nodejsSet({httpsAgent:this.httpsAgent,httpAgent:this.httpAgent}),e.open("POST",this.host,!0),e.setRequestHeader("Content-Type","application/json"),e.timeout=this.timeout&&1!==this.timeout?this.timeout:0,e.withCredentials=!0,this.headers&&this.headers.forEach(function(t){e.setRequestHeader(t.name,t.value)}),e},s.prototype.send=function(e,t){var r=this,i=this._prepareRequest();i.onreadystatechange=function(){if(4===i.readyState&&1!==i.timeout){var e=i.responseText,o=null;try{e=JSON.parse(e)}catch(e){o=n.InvalidResponse(i.responseText)}r.connected=!0,t(o,e)}},i.ontimeout=function(){r.connected=!1,t(n.ConnectionTimeout(this.timeout))};try{i.send(JSON.stringify(e))}catch(e){this.connected=!1,t(n.InvalidConnection(this.host))}},s.prototype.disconnect=function(){},t.exports=s},{http:312,https:175,"web3-core-helpers":338,"xhr2-cookies":418}],399:[function(e,t,r){"use strict";var n=e("underscore"),i=e("web3-core-helpers").errors,o=e("oboe"),a=function(e,t){var r=this;this.responseCallbacks={},this.notificationCallbacks=[],this.path=e,this.connected=!1,this.connection=t.connect({path:this.path}),this.addDefaultEvents();var i=function(e){var t=null;n.isArray(e)?e.forEach(function(e){r.responseCallbacks[e.id]&&(t=e.id)}):t=e.id,t||-1===e.method.indexOf("_subscription")?r.responseCallbacks[t]&&(r.responseCallbacks[t](null,e),delete r.responseCallbacks[t]):r.notificationCallbacks.forEach(function(t){n.isFunction(t)&&t(e)})};"Socket"===t.constructor.name?o(this.connection).done(i):this.connection.on("data",function(e){r._parseResponse(e.toString()).forEach(i)})};a.prototype.addDefaultEvents=function(){var e=this;this.connection.on("connect",function(){e.connected=!0}),this.connection.on("close",function(){e.connected=!1}),this.connection.on("error",function(){e._timeout()}),this.connection.on("end",function(){e._timeout()}),this.connection.on("timeout",function(){e._timeout()})},a.prototype._parseResponse=function(e){var t=this,r=[];return e.replace(/\}[\n\r]?\{/g,"}|--|{").replace(/\}\][\n\r]?\[\{/g,"}]|--|[{").replace(/\}[\n\r]?\[\{/g,"}|--|[{").replace(/\}\][\n\r]?\{/g,"}]|--|{").split("|--|").forEach(function(e){t.lastChunk&&(e=t.lastChunk+e);var n=null;try{n=JSON.parse(e)}catch(r){return t.lastChunk=e,clearTimeout(t.lastChunkTimeout),void(t.lastChunkTimeout=setTimeout(function(){throw t._timeout(),i.InvalidResponse(e)},15e3))}clearTimeout(t.lastChunkTimeout),t.lastChunk=null,n&&r.push(n)}),r},a.prototype._addResponseCallback=function(e,t){var r=e.id||e[0].id,n=e.method||e[0].method;this.responseCallbacks[r]=t,this.responseCallbacks[r].method=n},a.prototype._timeout=function(){for(var e in this.responseCallbacks)this.responseCallbacks.hasOwnProperty(e)&&(this.responseCallbacks[e](i.InvalidConnection("on IPC")),delete this.responseCallbacks[e])},a.prototype.reconnect=function(){this.connection.connect({path:this.path})},a.prototype.send=function(e,t){this.connection.writable||this.connection.connect({path:this.path}),this.connection.write(JSON.stringify(e)),this._addResponseCallback(e,t)},a.prototype.on=function(e,t){if("function"!=typeof t)throw new Error("The second parameter callback must be a function.");switch(e){case"data":this.notificationCallbacks.push(t);break;default:this.connection.on(e,t)}},a.prototype.once=function(e,t){if("function"!=typeof t)throw new Error("The second parameter callback must be a function.");this.connection.once(e,t)},a.prototype.removeListener=function(e,t){var r=this;switch(e){case"data":this.notificationCallbacks.forEach(function(e,n){e===t&&r.notificationCallbacks.splice(n,1)});break;default:this.connection.removeListener(e,t)}},a.prototype.removeAllListeners=function(e){switch(e){case"data":this.notificationCallbacks=[];break;default:this.connection.removeAllListeners(e)}},a.prototype.reset=function(){this._timeout(),this.notificationCallbacks=[],this.connection.removeAllListeners("error"),this.connection.removeAllListeners("end"),this.connection.removeAllListeners("timeout"),this.addDefaultEvents()},t.exports=a},{oboe:239,underscore:325,"web3-core-helpers":338}],400:[function(e,t,r){(function(r){"use strict";var n=e("underscore"),i=e("web3-core-helpers").errors,o=null,a=null,s=null;if("undefined"!=typeof window&&void 0!==window.WebSocket)o=function(e,t){return new window.WebSocket(e,t)},a=btoa,s=function(e){return new URL(e)};else{o=e("websocket").w3cwebsocket,a=function(e){return r(e).toString("base64")};var u=e("url");if(u.URL){var c=u.URL;s=function(e){return new c(e)}}else s=e("url").parse}var f=function(e,t){var r=this;this.responseCallbacks={},this.notificationCallbacks=[],t=t||{},this._customTimeout=t.timeout;var i=s(e),u=t.headers||{},c=t.protocol||void 0;i.username&&i.password&&(u.authorization="Basic "+a(i.username+":"+i.password));var f=t.clientConfig||void 0;i.auth&&(u.authorization="Basic "+a(i.auth)),this.connection=new o(e,c,void 0,u,void 0,f),this.addDefaultEvents(),this.connection.onmessage=function(e){var t="string"==typeof e.data?e.data:"";r._parseResponse(t).forEach(function(e){var t=null;n.isArray(e)?e.forEach(function(e){r.responseCallbacks[e.id]&&(t=e.id)}):t=e.id,!t&&e&&e.method&&-1!==e.method.indexOf("_subscription")?r.notificationCallbacks.forEach(function(t){n.isFunction(t)&&t(e)}):r.responseCallbacks[t]&&(r.responseCallbacks[t](null,e),delete r.responseCallbacks[t])})},Object.defineProperty(this,"connected",{get:function(){return this.connection&&this.connection.readyState===this.connection.OPEN},enumerable:!0})};f.prototype.addDefaultEvents=function(){var e=this;this.connection.onerror=function(){e._timeout()},this.connection.onclose=function(){e._timeout(),e.reset()}},f.prototype._parseResponse=function(e){var t=this,r=[];return e.replace(/\}[\n\r]?\{/g,"}|--|{").replace(/\}\][\n\r]?\[\{/g,"}]|--|[{").replace(/\}[\n\r]?\[\{/g,"}|--|[{").replace(/\}\][\n\r]?\{/g,"}]|--|{").split("|--|").forEach(function(e){t.lastChunk&&(e=t.lastChunk+e);var n=null;try{n=JSON.parse(e)}catch(r){return t.lastChunk=e,clearTimeout(t.lastChunkTimeout),void(t.lastChunkTimeout=setTimeout(function(){throw t._timeout(),i.InvalidResponse(e)},15e3))}clearTimeout(t.lastChunkTimeout),t.lastChunk=null,n&&r.push(n)}),r},f.prototype._addResponseCallback=function(e,t){var r=e.id||e[0].id,n=e.method||e[0].method;this.responseCallbacks[r]=t,this.responseCallbacks[r].method=n;var o=this;this._customTimeout&&setTimeout(function(){o.responseCallbacks[r]&&(o.responseCallbacks[r](i.ConnectionTimeout(o._customTimeout)),delete o.responseCallbacks[r])},this._customTimeout)},f.prototype._timeout=function(){for(var e in this.responseCallbacks)this.responseCallbacks.hasOwnProperty(e)&&(this.responseCallbacks[e](i.InvalidConnection("on WS")),delete this.responseCallbacks[e])},f.prototype.send=function(e,t){var r=this;if(this.connection.readyState!==this.connection.CONNECTING){if(this.connection.readyState!==this.connection.OPEN)return console.error("connection not open on send()"),"function"==typeof this.connection.onerror?this.connection.onerror(new Error("connection not open")):console.error("no error callback"),void t(new Error("connection not open"));this.connection.send(JSON.stringify(e)),this._addResponseCallback(e,t)}else setTimeout(function(){r.send(e,t)},10)},f.prototype.on=function(e,t){if("function"!=typeof t)throw new Error("The second parameter callback must be a function.");switch(e){case"data":this.notificationCallbacks.push(t);break;case"connect":this.connection.onopen=t;break;case"end":this.connection.onclose=t;break;case"error":this.connection.onerror=t}},f.prototype.removeListener=function(e,t){var r=this;switch(e){case"data":this.notificationCallbacks.forEach(function(e,n){e===t&&r.notificationCallbacks.splice(n,1)})}},f.prototype.removeAllListeners=function(e){switch(e){case"data":this.notificationCallbacks=[];break;case"connect":this.connection.onopen=null;break;case"end":this.connection.onclose=null;break;case"error":this.connection.onerror=null}},f.prototype.reset=function(){this._timeout(),this.notificationCallbacks=[],this.addDefaultEvents()},f.prototype.disconnect=function(){this.connection&&this.connection.close()},t.exports=f}).call(this,e("buffer").Buffer)},{buffer:84,underscore:325,url:327,"web3-core-helpers":338,websocket:408}],401:[function(e,t,r){"use strict";var n=e("web3-core"),i=e("web3-core-subscriptions").subscriptions,o=e("web3-core-method"),a=e("web3-net"),s=function(){var e=this;n.packageInit(this,arguments);var t=this.setProvider;this.setProvider=function(){t.apply(e,arguments),e.net.setProvider.apply(e,arguments)},this.clearSubscriptions=e._requestManager.clearSubscriptions,this.net=new a(this.currentProvider),[new i({name:"subscribe",type:"shh",subscriptions:{messages:{params:1}}}),new o({name:"getVersion",call:"shh_version",params:0}),new o({name:"getInfo",call:"shh_info",params:0}),new o({name:"setMaxMessageSize",call:"shh_setMaxMessageSize",params:1}),new o({name:"setMinPoW",call:"shh_setMinPoW",params:1}),new o({name:"markTrustedPeer",call:"shh_markTrustedPeer",params:1}),new o({name:"newKeyPair",call:"shh_newKeyPair",params:0}),new o({name:"addPrivateKey",call:"shh_addPrivateKey",params:1}),new o({name:"deleteKeyPair",call:"shh_deleteKeyPair",params:1}),new o({name:"hasKeyPair",call:"shh_hasKeyPair",params:1}),new o({name:"getPublicKey",call:"shh_getPublicKey",params:1}),new o({name:"getPrivateKey",call:"shh_getPrivateKey",params:1}),new o({name:"newSymKey",call:"shh_newSymKey",params:0}),new o({name:"addSymKey",call:"shh_addSymKey",params:1}),new o({name:"generateSymKeyFromPassword",call:"shh_generateSymKeyFromPassword",params:1}),new o({name:"hasSymKey",call:"shh_hasSymKey",params:1}),new o({name:"getSymKey",call:"shh_getSymKey",params:1}),new o({name:"deleteSymKey",call:"shh_deleteSymKey",params:1}),new o({name:"newMessageFilter",call:"shh_newMessageFilter",params:1}),new o({name:"getFilterMessages",call:"shh_getFilterMessages",params:1}),new o({name:"deleteMessageFilter",call:"shh_deleteMessageFilter",params:1}),new o({name:"post",call:"shh_post",params:1,inputFormatter:[null]}),new o({name:"unsubscribe",call:"shh_unsubscribe",params:1})].forEach(function(t){t.attachToObject(e),t.setRequestManager(e._requestManager)})};n.addProviders(s),t.exports=s},{"web3-core":348,"web3-core-method":339,"web3-core-subscriptions":345,"web3-net":372}],402:[function(e,t,r){arguments[4][154][0].apply(r,arguments)},{dup:154}],403:[function(e,t,r){var n=e("underscore"),i=e("ethjs-unit"),o=e("./utils.js"),a=e("./soliditySha3.js"),s=e("randomhex"),u=function(e,t){var r=[];return t.forEach(function(t){if("object"==typeof t.components){if("tuple"!==t.type.substring(0,5))throw new Error("components found but type is not tuple; report on GitHub");var i="",o=t.type.indexOf("[");o>=0&&(i=t.type.substring(o));var a=u(e,t.components);n.isArray(a)&&e?r.push("tuple("+a.join(",")+")"+i):e?r.push("("+a+")"):r.push("("+a.join(",")+")"+i)}else r.push(t.type)}),r},c=function(e){if(!o.isHexStrict(e))throw new Error("The parameter must be a valid HEX string.");var t="",r=0,n=e.length;for("0x"===e.substring(0,2)&&(r=2);r7?r+=e[n].toUpperCase():r+=e[n];return r},toHex:o.toHex,toBN:o.toBN,bytesToHex:o.bytesToHex,hexToBytes:o.hexToBytes,hexToNumberString:o.hexToNumberString,hexToNumber:o.hexToNumber,toDecimal:o.hexToNumber,numberToHex:o.numberToHex,fromDecimal:o.numberToHex,hexToUtf8:o.hexToUtf8,hexToString:o.hexToUtf8,toUtf8:o.hexToUtf8,utf8ToHex:o.utf8ToHex,stringToHex:o.utf8ToHex,fromUtf8:o.utf8ToHex,hexToAscii:c,toAscii:c,asciiToHex:f,fromAscii:f,unitMap:i.unitMap,toWei:function(e,t){if(t=h(t),!o.isBN(e)&&!n.isString(e))throw new Error("Please pass numbers as strings or BigNumber objects to avoid precision errors.");return o.isBN(e)?i.toWei(e,t):i.toWei(e,t).toString(10)},fromWei:function(e,t){if(t=h(t),!o.isBN(e)&&!n.isString(e))throw new Error("Please pass numbers as strings or BigNumber objects to avoid precision errors.");return o.isBN(e)?i.fromWei(e,t):i.fromWei(e,t).toString(10)},padLeft:o.leftPad,leftPad:o.leftPad,padRight:o.rightPad,rightPad:o.rightPad,toTwosComplement:o.toTwosComplement}},{"./soliditySha3.js":404,"./utils.js":405,"ethjs-unit":153,randomhex:274,underscore:325}],404:[function(e,t,r){var n=e("underscore"),i=e("bn.js"),o=e("./utils.js"),a=function(e){var t=typeof e;if("string"===t)return o.isHexStrict(e)?new i(e.replace(/0x/i,""),16):new i(e,10);if("number"===t)return new i(e);if(o.isBigNumber(e))return new i(e.toString(10));if(o.isBN(e))return e;throw new Error(e+" is not a number")},s=function(e,t,r){var n,s,u;if("bytes"===(e=(u=e).startsWith("int[")?"int256"+u.slice(3):"int"===u?"int256":u.startsWith("uint[")?"uint256"+u.slice(4):"uint"===u?"uint256":u.startsWith("fixed[")?"fixed128x128"+u.slice(5):"fixed"===u?"fixed128x128":u.startsWith("ufixed[")?"ufixed128x128"+u.slice(6):"ufixed"===u?"ufixed128x128":u)){if(t.replace(/^0x/i,"").length%2!=0)throw new Error("Invalid bytes characters "+t.length);return t}if("string"===e)return o.utf8ToHex(t);if("bool"===e)return t?"01":"00";if(e.startsWith("address")){if(n=r?64:40,!o.isAddress(t))throw new Error(t+" is not a valid address, or the checksum is invalid.");return o.leftPad(t.toLowerCase(),n)}if(n=function(e){var t=/^\D+(\d+).*$/.exec(e);return t?parseInt(t[1],10):null}(e),e.startsWith("bytes")){if(!n)throw new Error("bytes[] not yet supported in solidity");if(r&&(n=32),n<1||n>32||n256)throw new Error("Invalid uint"+n+" size");if((s=a(t)).bitLength()>n)throw new Error("Supplied uint exceeds width: "+n+" vs "+s.bitLength());if(s.lt(new i(0)))throw new Error("Supplied uint "+s.toString()+" is negative");return n?o.leftPad(s.toString("hex"),n/8*2):s}if(e.startsWith("int")){if(n%8||n<8||n>256)throw new Error("Invalid int"+n+" size");if((s=a(t)).bitLength()>n)throw new Error("Supplied int exceeds width: "+n+" vs "+s.bitLength());return s.lt(new i(0))?s.toTwos(n).toString("hex"):n?o.leftPad(s.toString("hex"),n/8*2):s}throw new Error("Unsupported or invalid type: "+e)},u=function(e){if(n.isArray(e))throw new Error("Autodetection of array types is not supported.");var t,r,a="";if(n.isObject(e)&&(e.hasOwnProperty("v")||e.hasOwnProperty("t")||e.hasOwnProperty("value")||e.hasOwnProperty("type"))?(t=e.hasOwnProperty("t")?e.t:e.type,a=e.hasOwnProperty("v")?e.v:e.value):(t=o.toHex(e,!0),a=o.toHex(e),t.startsWith("int")||t.startsWith("uint")||(t="bytes")),!t.startsWith("int")&&!t.startsWith("uint")||"string"!=typeof a||/^(-)?0x/i.test(a)||(a=new i(a)),n.isArray(a)){if((r=function(e){var t=/^\D+\d*\[(\d+)\]$/.exec(e);return t?parseInt(t[1],10):null}(t))&&a.length!==r)throw new Error(t+" is not matching the given array "+JSON.stringify(a));r=a.length}return n.isArray(a)?a.map(function(e){return s(t,e,r).toString("hex").replace("0x","")}).join(""):s(t,a,r).toString("hex").replace("0x","")};t.exports=function(){var e=Array.prototype.slice.call(arguments),t=n.map(e,u);return o.sha3("0x"+t.join(""))}},{"./utils.js":405,"bn.js":402,underscore:325}],405:[function(e,t,r){var n=e("underscore"),i=e("bn.js"),o=e("number-to-bn"),a=e("utf8"),s=e("eth-lib/lib/hash"),u=function(e){return e instanceof i||e&&e.constructor&&"BN"===e.constructor.name},c=function(e){return e&&e.constructor&&"BigNumber"===e.constructor.name},f=function(e){try{return o.apply(null,arguments)}catch(t){throw new Error(t+' Given value: "'+e+'"')}},h=function(e){return!!/^(0x)?[0-9a-f]{40}$/i.test(e)&&(!(!/^(0x|0X)?[0-9a-f]{40}$/.test(e)&&!/^(0x|0X)?[0-9A-F]{40}$/.test(e))||l(e))},l=function(e){e=e.replace(/^0x/i,"");for(var t=m(e.toLowerCase()).replace(/^0x/i,""),r=0;r<40;r++)if(parseInt(t[r],16)>7&&e[r].toUpperCase()!==e[r]||parseInt(t[r],16)<=7&&e[r].toLowerCase()!==e[r])return!1;return!0},d=function(e){var t="";e=(e=(e=(e=(e=a.encode(e)).replace(/^(?:\u0000)*/,"")).split("").reverse().join("")).replace(/^(?:\u0000)*/,"")).split("").reverse().join("");for(var r=0;r>>4).toString(16)),t.push((15&e[r]).toString(16));return"0x"+t.join("")},isHex:function(e){return(n.isString(e)||n.isNumber(e))&&/^(-0x|0x)?[0-9a-f]*$/i.test(e)},isHexStrict:y,leftPad:function(e,t,r){var n=/^0x/i.test(e)||"number"==typeof e,i=t-(e=e.toString(16).replace(/^0x/i,"")).length+1>=0?t-e.length+1:0;return(n?"0x":"")+new Array(i).join(r||"0")+e},rightPad:function(e,t,r){var n=/^0x/i.test(e)||"number"==typeof e,i=t-(e=e.toString(16).replace(/^0x/i,"")).length+1>=0?t-e.length+1:0;return(n?"0x":"")+e+new Array(i).join(r||"0")},toTwosComplement:function(e){return"0x"+f(e).toTwos(256).toString(16,64)},sha3:m}},{"bn.js":402,"eth-lib/lib/hash":134,"number-to-bn":237,underscore:325,utf8:329}],406:[function(e,t,r){t.exports={_from:"web3@1.0.0-beta.36",_id:"web3@1.0.0-beta.36",_inBundle:!1,_integrity:"sha512-fZDunw1V0AQS27r5pUN3eOVP7u8YAvyo6vOapdgVRolAu5LgaweP7jncYyLINqIX9ZgWdS5A090bt+ymgaYHsw==",_location:"/web3",_phantomChildren:{},_requested:{type:"version",registry:!0,raw:"web3@1.0.0-beta.36",name:"web3",escapedName:"web3",rawSpec:"1.0.0-beta.36",saveSpec:null,fetchSpec:"1.0.0-beta.36"},_requiredBy:["#USER","/"],_resolved:"https://registry.npmjs.org/web3/-/web3-1.0.0-beta.36.tgz",_shasum:"2954da9e431124c88396025510d840ba731c8373",_spec:"web3@1.0.0-beta.36",_where:"/Users/alexvlasov/Blockchain/web3swift/web3swiftJSProxy",author:{name:"ethereum.org"},authors:[{name:"Fabian Vogelsteller",email:"fabian@ethereum.org",homepage:"http://frozeman.de"},{name:"Marek Kotewicz",email:"marek@parity.io",url:"https://github.com/debris"},{name:"Marian Oancea",url:"https://github.com/cubedro"},{name:"Gav Wood",email:"g@parity.io",homepage:"http://gavwood.com"},{name:"Jeffery Wilcke",email:"jeffrey.wilcke@ethereum.org",url:"https://github.com/obscuren"}],bugs:{url:"https://github.com/ethereum/web3.js/issues"},bundleDependencies:!1,dependencies:{"web3-bzz":"1.0.0-beta.36","web3-core":"1.0.0-beta.36","web3-eth":"1.0.0-beta.36","web3-eth-personal":"1.0.0-beta.36","web3-net":"1.0.0-beta.36","web3-shh":"1.0.0-beta.36","web3-utils":"1.0.0-beta.36"},deprecated:!1,description:"Ethereum JavaScript API",keywords:["Ethereum","JavaScript","API"],license:"LGPL-3.0",main:"src/index.js",name:"web3",namespace:"ethereum",repository:{type:"git",url:"https://github.com/ethereum/web3.js/tree/master/packages/web3"},version:"1.0.0-beta.36"}},{}],407:[function(e,t,r){"use strict";var n=e("../package.json").version,i=e("web3-core"),o=e("web3-eth"),a=e("web3-net"),s=e("web3-eth-personal"),u=e("web3-shh"),c=e("web3-bzz"),f=e("web3-utils"),h=function(){var e=this;i.packageInit(this,arguments),this.version=n,this.utils=f,this.eth=new o(this),this.shh=new u(this),this.bzz=new c(this);var t=this.setProvider;this.setProvider=function(r,n){return t.apply(e,arguments),this.eth.setProvider(r,n),this.shh.setProvider(r,n),this.bzz.setProvider(r),!0}};h.version=n,h.utils=f,h.modules={Eth:o,Net:a,Personal:s,Shh:u,Bzz:c},i.addProviders(h),t.exports=h},{"../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(e,t,r){var n=function(){return this||{}}(),i=n.WebSocket||n.MozWebSocket,o=e("./version");function a(e,t){return t?new i(e,t):new i(e)}i&&["CONNECTING","OPEN","CLOSING","CLOSED"].forEach(function(e){Object.defineProperty(a,e,{get:function(){return i[e]}})}),t.exports={w3cwebsocket:i?a:null,version:o}},{"./version":409}],409:[function(e,t,r){t.exports=e("../package.json").version},{"../package.json":410}],410:[function(e,t,r){t.exports={_from:"git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible",_id:"websocket@1.0.26",_inBundle:!1,_integrity:"",_location:"/websocket",_phantomChildren:{},_requested:{type:"git",raw:"websocket@git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible",name:"websocket",escapedName:"websocket",rawSpec:"git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible",saveSpec:"git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible",fetchSpec:"git://github.com/frozeman/WebSocket-Node.git",gitCommittish:"browserifyCompatible"},_requiredBy:["/web3-providers-ws"],_resolved:"git://github.com/frozeman/WebSocket-Node.git#6c72925e3f8aaaea8dc8450f97627e85263999f2",_spec:"websocket@git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible",_where:"/Users/alexvlasov/Blockchain/web3swift/web3swiftJSProxy/node_modules/web3-providers-ws",author:{name:"Brian McKelvey",email:"brian@worlize.com",url:"https://www.worlize.com/"},browser:"lib/browser.js",bugs:{url:"https://github.com/theturtle32/WebSocket-Node/issues"},bundleDependencies:!1,config:{verbose:!1},contributors:[{name:"Iñaki Baz Castillo",email:"ibc@aliax.net",url:"http://dev.sipdoc.net"}],dependencies:{debug:"^2.2.0",nan:"^2.3.3","typedarray-to-buffer":"^3.1.2",yaeti:"^0.0.6"},deprecated:!1,description:"Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.",devDependencies:{"buffer-equal":"^1.0.0",faucet:"^0.0.1",gulp:"git+https://github.com/gulpjs/gulp.git#4.0","gulp-jshint":"^2.0.4",jshint:"^2.0.0","jshint-stylish":"^2.2.1",tape:"^4.0.1"},directories:{lib:"./lib"},engines:{node:">=0.10.0"},homepage:"https://github.com/theturtle32/WebSocket-Node",keywords:["websocket","websockets","socket","networking","comet","push","RFC-6455","realtime","server","client"],license:"Apache-2.0",main:"index",name:"websocket",repository:{type:"git",url:"git+https://github.com/theturtle32/WebSocket-Node.git"},scripts:{gulp:"gulp",install:"(node-gyp rebuild 2> builderror.log) || (exit 0)",test:"faucet test/unit"},version:"1.0.26"}},{}],411:[function(e,t,r){var n=e("xhr-request");t.exports=function(e,t){return new Promise(function(r,i){n(e,t,function(e,t){e?i(e):r(t)})})}},{"xhr-request":412}],412:[function(e,t,r){var n=e("query-string"),i=e("url-set-query"),o=e("object-assign"),a=e("./lib/ensure-header.js"),s=e("./lib/request.js"),u="application/json",c=function(){};t.exports=function(e,t,r){if(!e||"string"!=typeof e)throw new TypeError("must specify a URL");"function"==typeof t&&(r=t,t={});if(r&&"function"!=typeof r)throw new TypeError("expected cb to be undefined or a function");r=r||c;var f=(t=t||{}).json?"json":"text",h=(t=o({responseType:f},t)).headers||{},l=(t.method||"GET").toUpperCase(),d=t.query;d&&("string"!=typeof d&&(d=n.stringify(d)),e=i(e,d));"json"===t.responseType&&a(h,"Accept",u);t.json&&"GET"!==l&&"HEAD"!==l&&(a(h,"Content-Type",u),t.body=JSON.stringify(t.body));return t.method=l,t.url=e,t.headers=h,delete t.query,delete t.json,s(t,r)}},{"./lib/ensure-header.js":413,"./lib/request.js":415,"object-assign":238,"query-string":266,"url-set-query":326}],413:[function(e,t,r){t.exports=function(e,t,r){var n=t.toLowerCase();e[t]||e[n]||(e[t]=r)}},{}],414:[function(e,t,r){t.exports=function(e,t){return t?{statusCode:t.statusCode,headers:t.headers,method:e.method,url:e.url,rawRequest:t.rawRequest?t.rawRequest:t}:null}},{}],415:[function(e,t,r){var n=e("xhr"),i=e("./normalize-response"),o=function(){};t.exports=function(e,t){delete e.uri;var r=!1;"json"===e.responseType&&(e.responseType="text",r=!0);var a=n(e,function(n,a,s){if(r&&!n)try{var u=a.rawRequest.responseText;s=JSON.parse(u)}catch(e){n=e}a=i(e,a),t(n,n?null:s,a),t=o}),s=a.onabort;return a.onabort=function(){var e=s.apply(a,Array.prototype.slice.call(arguments));return t(new Error("XHR Aborted")),t=o,e},a}},{"./normalize-response":414,xhr:416}],416:[function(e,t,r){"use strict";var n=e("global/window"),i=e("is-function"),o=e("parse-headers"),a=e("xtend");function s(e,t,r){var n=e;return i(t)?(r=t,"string"==typeof e&&(n={uri:e})):n=a(t,{uri:e}),n.callback=r,n}function u(e,t,r){return c(t=s(e,t,r))}function c(e){if(void 0===e.callback)throw new Error("callback argument missing");var t=!1,r=function(r,n,i){t||(t=!0,e.callback(r,n,i))};function n(e){return clearTimeout(f),e instanceof Error||(e=new Error(""+(e||"Unknown XMLHttpRequest Error"))),e.statusCode=0,r(e,m)}function i(){if(!s){var t;clearTimeout(f),t=e.useXDR&&void 0===c.status?200:1223===c.status?204:c.status;var n=m,i=null;return 0!==t?(n={body:function(){var e=void 0;if(e=c.response?c.response:c.responseText||function(e){try{if("document"===e.responseType)return e.responseXML;var t=e.responseXML&&"parsererror"===e.responseXML.documentElement.nodeName;if(""===e.responseType&&!t)return e.responseXML}catch(e){}return null}(c),y)try{e=JSON.parse(e)}catch(e){}return e}(),statusCode:t,method:l,headers:{},url:h,rawRequest:c},c.getAllResponseHeaders&&(n.headers=o(c.getAllResponseHeaders()))):i=new Error("Internal XMLHttpRequest Error"),r(i,n,n.body)}}var a,s,c=e.xhr||null;c||(c=e.cors||e.useXDR?new u.XDomainRequest:new u.XMLHttpRequest);var f,h=c.url=e.uri||e.url,l=c.method=e.method||"GET",d=e.body||e.data,p=c.headers=e.headers||{},b=!!e.sync,y=!1,m={body:void 0,headers:{},statusCode:0,method:l,url:h,rawRequest:c};if("json"in e&&!1!==e.json&&(y=!0,p.accept||p.Accept||(p.Accept="application/json"),"GET"!==l&&"HEAD"!==l&&(p["content-type"]||p["Content-Type"]||(p["Content-Type"]="application/json"),d=JSON.stringify(!0===e.json?d:e.json))),c.onreadystatechange=function(){4===c.readyState&&setTimeout(i,0)},c.onload=i,c.onerror=n,c.onprogress=function(){},c.onabort=function(){s=!0},c.ontimeout=n,c.open(l,h,!b,e.username,e.password),b||(c.withCredentials=!!e.withCredentials),!b&&e.timeout>0&&(f=setTimeout(function(){if(!s){s=!0,c.abort("timeout");var e=new Error("XMLHttpRequest timeout");e.code="ETIMEDOUT",n(e)}},e.timeout)),c.setRequestHeader)for(a in p)p.hasOwnProperty(a)&&c.setRequestHeader(a,p[a]);else if(e.headers&&!function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0}(e.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in e&&(c.responseType=e.responseType),"beforeSend"in e&&"function"==typeof e.beforeSend&&e.beforeSend(c),c.send(d||null),c}t.exports=u,t.exports.default=u,u.XMLHttpRequest=n.XMLHttpRequest||function(){},u.XDomainRequest="withCredentials"in new u.XMLHttpRequest?u.XMLHttpRequest:n.XDomainRequest,function(e,t){for(var r=0;r=0)return this._url=this._parseUrl(t.headers.location),this._method="GET",this._loweredHeaders["content-type"]&&(delete this._headers[this._loweredHeaders["content-type"]],delete this._loweredHeaders["content-type"]),null!=this._headers["Content-Type"]&&delete this._headers["Content-Type"],delete this._headers["Content-Length"],this.upload._reset(),this._finalizeHeaders(),void this._sendHxxpRequest();this._response=t,this._response.on("data",function(e){return n._onHttpResponseData(t,e)}),this._response.on("end",function(){return n._onHttpResponseEnd(t)}),this._response.on("close",function(){return n._onHttpResponseClose(t)}),this.responseUrl=this._url.href.split("#")[0],this.status=t.statusCode,this.statusText=s.STATUS_CODES[this.status],this._parseResponseHeaders(t);var i=this._responseHeaders["content-length"]||"";this._totalBytes=+i,this._lengthComputable=!!i,this._setReadyState(r.HEADERS_RECEIVED)}},r.prototype._onHttpResponseData=function(e,t){this._response===e&&(this._responseParts.push(new n(t)),this._loadedBytes+=t.length,this.readyState!==r.LOADING&&this._setReadyState(r.LOADING),this._dispatchProgress("progress"))},r.prototype._onHttpResponseEnd=function(e){this._response===e&&(this._parseResponse(),this._request=null,this._response=null,this._setReadyState(r.DONE),this._dispatchProgress("load"),this._dispatchProgress("loadend"))},r.prototype._onHttpResponseClose=function(e){if(this._response===e){var t=this._request;this._setError(),t.abort(),this._setReadyState(r.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}},r.prototype._onHttpTimeout=function(e){this._request===e&&(this._setError(),e.abort(),this._setReadyState(r.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend"))},r.prototype._onHttpRequestError=function(e,t){this._request===e&&(this._setError(),e.abort(),this._setReadyState(r.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend"))},r.prototype._dispatchProgress=function(e){var t=new r.ProgressEvent(e);t.lengthComputable=this._lengthComputable,t.loaded=this._loadedBytes,t.total=this._totalBytes,this.dispatchEvent(t)},r.prototype._setError=function(){this._request=null,this._response=null,this._responseHeaders=null,this._responseParts=null},r.prototype._parseUrl=function(e,t,r){var n=null==this.nodejsBaseUrl?e:f.resolve(this.nodejsBaseUrl,e),i=f.parse(n,!1,!0);i.hash=null;var o=(i.auth||"").split(":"),a=o[0],s=o[1];return(a||s||t||r)&&(i.auth=(t||a||"")+":"+(r||s||"")),i},r.prototype._parseResponseHeaders=function(e){for(var t in this._responseHeaders={},e.headers){var r=t.toLowerCase();this._privateHeaders[r]||(this._responseHeaders[r]=e.headers[t])}null!=this._mimeOverride&&(this._responseHeaders["content-type"]=this._mimeOverride)},r.prototype._parseResponse=function(){var e=n.concat(this._responseParts);switch(this._responseParts=null,this.responseType){case"json":this.responseText=null;try{this.response=JSON.parse(e.toString("utf-8"))}catch(e){this.response=null}return;case"buffer":return this.responseText=null,void(this.response=e);case"arraybuffer":this.responseText=null;for(var t=new ArrayBuffer(e.length),r=new Uint8Array(t),i=0;i0&&(window.web3.eth.defaultAccount=t[0])})}window.ethereum=s}}},console.log("JS bridging rpc url access"),"undefined"!=typeof window&&window.bridge?window.bridge.post("getRPCurl",{},function(e,r){r&&t(r.description,null),t(null,e.rpcURL)}):(console.log("No bridge to native code is found"),t(!0,null))}()},{"./wk.bridge":424,web3:407,"web3-provider-engine/zero.js":397}],2:[function(e,t,r){t.exports=e("./register")().Promise},{"./register":4}],3:[function(e,t,r){"use strict";var n=null;t.exports=function(e,t){return function(r,i){r=r||null;var o=!1!==(i=i||{}).global;if(null===n&&o&&(n=e["@@any-promise/REGISTRATION"]||null),null!==n&&null!==r&&n.implementation!==r)throw new Error('any-promise already defined as "'+n.implementation+'". You can only register an implementation before the first call to require("any-promise") and an implementation cannot be changed');return null===n&&(n=null!==r&&void 0!==i.Promise?{Promise:i.Promise,implementation:r}:t(r),o&&(e["@@any-promise/REGISTRATION"]=n)),n}}},{}],4:[function(e,t,r){"use strict";t.exports=e("./loader")(window,function(){if(void 0===window.Promise)throw new Error("any-promise browser requires a polyfill or explicit registration e.g: require('any-promise/register/bluebird')");return{Promise:window.Promise,implementation:"window.Promise"}})},{"./loader":3}],5:[function(e,t,r){var n=r;n.bignum=e("bn.js"),n.define=e("./asn1/api").define,n.base=e("./asn1/base"),n.constants=e("./asn1/constants"),n.decoders=e("./asn1/decoders"),n.encoders=e("./asn1/encoders")},{"./asn1/api":6,"./asn1/base":8,"./asn1/constants":12,"./asn1/decoders":14,"./asn1/encoders":17,"bn.js":53}],6:[function(e,t,r){var n=e("../asn1"),i=e("inherits");function o(e,t){this.name=e,this.body=t,this.decoders={},this.encoders={}}r.define=function(e,t){return new o(e,t)},o.prototype._createNamed=function(t){var r;try{r=e("vm").runInThisContext("(function "+this.name+"(entity) {\n this._initNamed(entity);\n})")}catch(e){r=function(e){this._initNamed(e)}}return i(r,t),r.prototype._initNamed=function(e){t.call(this,e)},new r(this)},o.prototype._getDecoder=function(e){return e=e||"der",this.decoders.hasOwnProperty(e)||(this.decoders[e]=this._createNamed(n.decoders[e])),this.decoders[e]},o.prototype.decode=function(e,t,r){return this._getDecoder(t).decode(e,r)},o.prototype._getEncoder=function(e){return e=e||"der",this.encoders.hasOwnProperty(e)||(this.encoders[e]=this._createNamed(n.encoders[e])),this.encoders[e]},o.prototype.encode=function(e,t,r){return this._getEncoder(t).encode(e,r)}},{"../asn1":5,inherits:180,vm:334}],7:[function(e,t,r){var n=e("inherits"),i=e("../base").Reporter,o=e("buffer").Buffer;function a(e,t){i.call(this,t),o.isBuffer(e)?(this.base=e,this.offset=0,this.length=e.length):this.error("Input not Buffer")}function s(e,t){if(Array.isArray(e))this.length=0,this.value=e.map(function(e){return e instanceof s||(e=new s(e,t)),this.length+=e.length,e},this);else if("number"==typeof e){if(!(0<=e&&e<=255))return t.error("non-byte EncoderBuffer value");this.value=e,this.length=1}else if("string"==typeof e)this.value=e,this.length=o.byteLength(e);else{if(!o.isBuffer(e))return t.error("Unsupported type: "+typeof e);this.value=e,this.length=e.length}}n(a,i),r.DecoderBuffer=a,a.prototype.save=function(){return{offset:this.offset,reporter:i.prototype.save.call(this)}},a.prototype.restore=function(e){var t=new a(this.base);return t.offset=e.offset,t.length=this.offset,this.offset=e.offset,i.prototype.restore.call(this,e.reporter),t},a.prototype.isEmpty=function(){return this.offset===this.length},a.prototype.readUInt8=function(e){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(e||"DecoderBuffer overrun")},a.prototype.skip=function(e,t){if(!(this.offset+e<=this.length))return this.error(t||"DecoderBuffer overrun");var r=new a(this.base);return r._reporterState=this._reporterState,r.offset=this.offset,r.length=this.offset+e,this.offset+=e,r},a.prototype.raw=function(e){return this.base.slice(e?e.offset:this.offset,this.length)},r.EncoderBuffer=s,s.prototype.join=function(e,t){return e||(e=new o(this.length)),t||(t=0),0===this.length?e:(Array.isArray(this.value)?this.value.forEach(function(r){r.join(e,t),t+=r.length}):("number"==typeof this.value?e[t]=this.value:"string"==typeof this.value?e.write(this.value,t):o.isBuffer(this.value)&&this.value.copy(e,t),t+=this.length),e)}},{"../base":8,buffer:84,inherits:180}],8:[function(e,t,r){var n=r;n.Reporter=e("./reporter").Reporter,n.DecoderBuffer=e("./buffer").DecoderBuffer,n.EncoderBuffer=e("./buffer").EncoderBuffer,n.Node=e("./node")},{"./buffer":7,"./node":9,"./reporter":10}],9:[function(e,t,r){var n=e("../base").Reporter,i=e("../base").EncoderBuffer,o=e("../base").DecoderBuffer,a=e("minimalistic-assert"),s=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],u=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(s);function c(e,t){var r={};this._baseState=r,r.enc=e,r.parent=t||null,r.children=null,r.tag=null,r.args=null,r.reverseArgs=null,r.choice=null,r.optional=!1,r.any=!1,r.obj=!1,r.use=null,r.useDecoder=null,r.key=null,r.default=null,r.explicit=null,r.implicit=null,r.contains=null,r.parent||(r.children=[],this._wrap())}t.exports=c;var f=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];c.prototype.clone=function(){var e=this._baseState,t={};f.forEach(function(r){t[r]=e[r]});var r=new this.constructor(t.parent);return r._baseState=t,r},c.prototype._wrap=function(){var e=this._baseState;u.forEach(function(t){this[t]=function(){var r=new this.constructor(this);return e.children.push(r),r[t].apply(r,arguments)}},this)},c.prototype._init=function(e){var t=this._baseState;a(null===t.parent),e.call(this),t.children=t.children.filter(function(e){return e._baseState.parent===this},this),a.equal(t.children.length,1,"Root node can have only one child")},c.prototype._useArgs=function(e){var t=this._baseState,r=e.filter(function(e){return e instanceof this.constructor},this);e=e.filter(function(e){return!(e instanceof this.constructor)},this),0!==r.length&&(a(null===t.children),t.children=r,r.forEach(function(e){e._baseState.parent=this},this)),0!==e.length&&(a(null===t.args),t.args=e,t.reverseArgs=e.map(function(e){if("object"!=typeof e||e.constructor!==Object)return e;var t={};return Object.keys(e).forEach(function(r){r==(0|r)&&(r|=0);var n=e[r];t[n]=r}),t}))},["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"].forEach(function(e){c.prototype[e]=function(){var t=this._baseState;throw new Error(e+" not implemented for encoding: "+t.enc)}}),s.forEach(function(e){c.prototype[e]=function(){var t=this._baseState,r=Array.prototype.slice.call(arguments);return a(null===t.tag),t.tag=e,this._useArgs(r),this}}),c.prototype.use=function(e){a(e);var t=this._baseState;return a(null===t.use),t.use=e,this},c.prototype.optional=function(){return this._baseState.optional=!0,this},c.prototype.def=function(e){var t=this._baseState;return a(null===t.default),t.default=e,t.optional=!0,this},c.prototype.explicit=function(e){var t=this._baseState;return a(null===t.explicit&&null===t.implicit),t.explicit=e,this},c.prototype.implicit=function(e){var t=this._baseState;return a(null===t.explicit&&null===t.implicit),t.implicit=e,this},c.prototype.obj=function(){var e=this._baseState,t=Array.prototype.slice.call(arguments);return e.obj=!0,0!==t.length&&this._useArgs(t),this},c.prototype.key=function(e){var t=this._baseState;return a(null===t.key),t.key=e,this},c.prototype.any=function(){return this._baseState.any=!0,this},c.prototype.choice=function(e){var t=this._baseState;return a(null===t.choice),t.choice=e,this._useArgs(Object.keys(e).map(function(t){return e[t]})),this},c.prototype.contains=function(e){var t=this._baseState;return a(null===t.use),t.contains=e,this},c.prototype._decode=function(e,t){var r=this._baseState;if(null===r.parent)return e.wrapResult(r.children[0]._decode(e,t));var n,i=r.default,a=!0,s=null;if(null!==r.key&&(s=e.enterKey(r.key)),r.optional){var u=null;if(null!==r.explicit?u=r.explicit:null!==r.implicit?u=r.implicit:null!==r.tag&&(u=r.tag),null!==u||r.any){if(a=this._peekTag(e,u,r.any),e.isError(a))return a}else{var c=e.save();try{null===r.choice?this._decodeGeneric(r.tag,e,t):this._decodeChoice(e,t),a=!0}catch(e){a=!1}e.restore(c)}}if(r.obj&&a&&(n=e.enterObject()),a){if(null!==r.explicit){var f=this._decodeTag(e,r.explicit);if(e.isError(f))return f;e=f}var h=e.offset;if(null===r.use&&null===r.choice){if(r.any)c=e.save();var l=this._decodeTag(e,null!==r.implicit?r.implicit:r.tag,r.any);if(e.isError(l))return l;r.any?i=e.raw(c):e=l}if(t&&t.track&&null!==r.tag&&t.track(e.path(),h,e.length,"tagged"),t&&t.track&&null!==r.tag&&t.track(e.path(),e.offset,e.length,"content"),i=r.any?i:null===r.choice?this._decodeGeneric(r.tag,e,t):this._decodeChoice(e,t),e.isError(i))return i;if(r.any||null!==r.choice||null===r.children||r.children.forEach(function(r){r._decode(e,t)}),r.contains&&("octstr"===r.tag||"bitstr"===r.tag)){var d=new o(i);i=this._getUse(r.contains,e._reporterState.obj)._decode(d,t)}}return r.obj&&a&&(i=e.leaveObject(n)),null===r.key||null===i&&!0!==a?null!==s&&e.exitKey(s):e.leaveKey(s,r.key,i),i},c.prototype._decodeGeneric=function(e,t,r){var n=this._baseState;return"seq"===e||"set"===e?null:"seqof"===e||"setof"===e?this._decodeList(t,e,n.args[0],r):/str$/.test(e)?this._decodeStr(t,e,r):"objid"===e&&n.args?this._decodeObjid(t,n.args[0],n.args[1],r):"objid"===e?this._decodeObjid(t,null,null,r):"gentime"===e||"utctime"===e?this._decodeTime(t,e,r):"null_"===e?this._decodeNull(t,r):"bool"===e?this._decodeBool(t,r):"objDesc"===e?this._decodeStr(t,e,r):"int"===e||"enum"===e?this._decodeInt(t,n.args&&n.args[0],r):null!==n.use?this._getUse(n.use,t._reporterState.obj)._decode(t,r):t.error("unknown tag: "+e)},c.prototype._getUse=function(e,t){var r=this._baseState;return r.useDecoder=this._use(e,t),a(null===r.useDecoder._baseState.parent),r.useDecoder=r.useDecoder._baseState.children[0],r.implicit!==r.useDecoder._baseState.implicit&&(r.useDecoder=r.useDecoder.clone(),r.useDecoder._baseState.implicit=r.implicit),r.useDecoder},c.prototype._decodeChoice=function(e,t){var r=this._baseState,n=null,i=!1;return Object.keys(r.choice).some(function(o){var a=e.save(),s=r.choice[o];try{var u=s._decode(e,t);if(e.isError(u))return!1;n={type:o,value:u},i=!0}catch(t){return e.restore(a),!1}return!0},this),i?n:e.error("Choice not matched")},c.prototype._createEncoderBuffer=function(e){return new i(e,this.reporter)},c.prototype._encode=function(e,t,r){var n=this._baseState;if(null===n.default||n.default!==e){var i=this._encodeValue(e,t,r);if(void 0!==i&&!this._skipDefault(i,t,r))return i}},c.prototype._encodeValue=function(e,t,r){var i=this._baseState;if(null===i.parent)return i.children[0]._encode(e,t||new n);var o=null;if(this.reporter=t,i.optional&&void 0===e){if(null===i.default)return;e=i.default}var a=null,s=!1;if(i.any)o=this._createEncoderBuffer(e);else if(i.choice)o=this._encodeChoice(e,t);else if(i.contains)a=this._getUse(i.contains,r)._encode(e,t),s=!0;else if(i.children)a=i.children.map(function(r){if("null_"===r._baseState.tag)return r._encode(null,t,e);if(null===r._baseState.key)return t.error("Child should have a key");var n=t.enterKey(r._baseState.key);if("object"!=typeof e)return t.error("Child expected, but input is not object");var i=r._encode(e[r._baseState.key],t,e);return t.leaveKey(n),i},this).filter(function(e){return e}),a=this._createEncoderBuffer(a);else if("seqof"===i.tag||"setof"===i.tag){if(!i.args||1!==i.args.length)return t.error("Too many args for : "+i.tag);if(!Array.isArray(e))return t.error("seqof/setof, but data is not Array");var u=this.clone();u._baseState.implicit=null,a=this._createEncoderBuffer(e.map(function(r){var n=this._baseState;return this._getUse(n.args[0],e)._encode(r,t)},u))}else null!==i.use?o=this._getUse(i.use,r)._encode(e,t):(a=this._encodePrimitive(i.tag,e),s=!0);if(!i.any&&null===i.choice){var c=null!==i.implicit?i.implicit:i.tag,f=null===i.implicit?"universal":"context";null===c?null===i.use&&t.error("Tag could be omitted only for .use()"):null===i.use&&(o=this._encodeComposite(c,s,f,a))}return null!==i.explicit&&(o=this._encodeComposite(i.explicit,!1,"context",o)),o},c.prototype._encodeChoice=function(e,t){var r=this._baseState,n=r.choice[e.type];return n||a(!1,e.type+" not found in "+JSON.stringify(Object.keys(r.choice))),n._encode(e.value,t)},c.prototype._encodePrimitive=function(e,t){var r=this._baseState;if(/str$/.test(e))return this._encodeStr(t,e);if("objid"===e&&r.args)return this._encodeObjid(t,r.reverseArgs[0],r.args[1]);if("objid"===e)return this._encodeObjid(t,null,null);if("gentime"===e||"utctime"===e)return this._encodeTime(t,e);if("null_"===e)return this._encodeNull();if("int"===e||"enum"===e)return this._encodeInt(t,r.args&&r.reverseArgs[0]);if("bool"===e)return this._encodeBool(t);if("objDesc"===e)return this._encodeStr(t,e);throw new Error("Unsupported tag: "+e)},c.prototype._isNumstr=function(e){return/^[0-9 ]*$/.test(e)},c.prototype._isPrintstr=function(e){return/^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(e)}},{"../base":8,"minimalistic-assert":234}],10:[function(e,t,r){var n=e("inherits");function i(e){this._reporterState={obj:null,path:[],options:e||{},errors:[]}}function o(e,t){this.path=e,this.rethrow(t)}r.Reporter=i,i.prototype.isError=function(e){return e instanceof o},i.prototype.save=function(){var e=this._reporterState;return{obj:e.obj,pathLen:e.path.length}},i.prototype.restore=function(e){var t=this._reporterState;t.obj=e.obj,t.path=t.path.slice(0,e.pathLen)},i.prototype.enterKey=function(e){return this._reporterState.path.push(e)},i.prototype.exitKey=function(e){var t=this._reporterState;t.path=t.path.slice(0,e-1)},i.prototype.leaveKey=function(e,t,r){var n=this._reporterState;this.exitKey(e),null!==n.obj&&(n.obj[t]=r)},i.prototype.path=function(){return this._reporterState.path.join("/")},i.prototype.enterObject=function(){var e=this._reporterState,t=e.obj;return e.obj={},t},i.prototype.leaveObject=function(e){var t=this._reporterState,r=t.obj;return t.obj=e,r},i.prototype.error=function(e){var t,r=this._reporterState,n=e instanceof o;if(t=n?e:new o(r.path.map(function(e){return"["+JSON.stringify(e)+"]"}).join(""),e.message||e,e.stack),!r.options.partial)throw t;return n||r.errors.push(t),t},i.prototype.wrapResult=function(e){var t=this._reporterState;return t.options.partial?{result:this.isError(e)?null:e,errors:t.errors}:e},n(o,Error),o.prototype.rethrow=function(e){if(this.message=e+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,o),!this.stack)try{throw new Error(this.message)}catch(e){this.stack=e.stack}return this}},{inherits:180}],11:[function(e,t,r){var n=e("../constants");r.tagClass={0:"universal",1:"application",2:"context",3:"private"},r.tagClassByName=n._reverse(r.tagClass),r.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},r.tagByName=n._reverse(r.tag)},{"../constants":12}],12:[function(e,t,r){var n=r;n._reverse=function(e){var t={};return Object.keys(e).forEach(function(r){(0|r)==r&&(r|=0);var n=e[r];t[n]=r}),t},n.der=e("./der")},{"./der":11}],13:[function(e,t,r){var n=e("inherits"),i=e("../../asn1"),o=i.base,a=i.bignum,s=i.constants.der;function u(e){this.enc="der",this.name=e.name,this.entity=e,this.tree=new c,this.tree._init(e.body)}function c(e){o.Node.call(this,"der",e)}function f(e,t){var r=e.readUInt8(t);if(e.isError(r))return r;var n=s.tagClass[r>>6],i=0==(32&r);if(31==(31&r)){var o=r;for(r=0;128==(128&o);){if(o=e.readUInt8(t),e.isError(o))return o;r<<=7,r|=127&o}}else r&=31;return{cls:n,primitive:i,tag:r,tagStr:s.tag[r]}}function h(e,t,r){var n=e.readUInt8(r);if(e.isError(n))return n;if(!t&&128===n)return null;if(0==(128&n))return n;var i=127&n;if(i>4)return e.error("length octect is too long");n=0;for(var o=0;o=31)return n.error("Multi-octet tag encoding unsupported");t||(i|=32);return i|=s.tagClassByName[r||"universal"]<<6}(e,t,r,this.reporter);if(n.length<128)return(o=new i(2))[0]=a,o[1]=n.length,this._createEncoderBuffer([o,n]);for(var u=1,c=n.length;c>=256;c>>=8)u++;(o=new i(2+u))[0]=a,o[1]=128|u;c=1+u;for(var f=n.length;f>0;c--,f>>=8)o[c]=255&f;return this._createEncoderBuffer([o,n])},c.prototype._encodeStr=function(e,t){if("bitstr"===t)return this._createEncoderBuffer([0|e.unused,e.data]);if("bmpstr"===t){for(var r=new i(2*e.length),n=0;n=40)return this.reporter.error("Second objid identifier OOB");e.splice(0,2,40*e[0]+e[1])}var o=0;for(n=0;n=128;a>>=7)o++}var s=new i(o),u=s.length-1;for(n=e.length-1;n>=0;n--){a=e[n];for(s[u--]=127&a;(a>>=7)>0;)s[u--]=128|127&a}return this._createEncoderBuffer(s)},c.prototype._encodeTime=function(e,t){var r,n=new Date(e);return"gentime"===t?r=[f(n.getFullYear()),f(n.getUTCMonth()+1),f(n.getUTCDate()),f(n.getUTCHours()),f(n.getUTCMinutes()),f(n.getUTCSeconds()),"Z"].join(""):"utctime"===t?r=[f(n.getFullYear()%100),f(n.getUTCMonth()+1),f(n.getUTCDate()),f(n.getUTCHours()),f(n.getUTCMinutes()),f(n.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+t+" time is not supported yet"),this._encodeStr(r,"octstr")},c.prototype._encodeNull=function(){return this._createEncoderBuffer("")},c.prototype._encodeInt=function(e,t){if("string"==typeof e){if(!t)return this.reporter.error("String int or enum given, but no values map");if(!t.hasOwnProperty(e))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(e));e=t[e]}if("number"!=typeof e&&!i.isBuffer(e)){var r=e.toArray();!e.sign&&128&r[0]&&r.unshift(0),e=new i(r)}if(i.isBuffer(e)){var n=e.length;0===e.length&&n++;var o=new i(n);return e.copy(o),0===e.length&&(o[0]=0),this._createEncoderBuffer(o)}if(e<128)return this._createEncoderBuffer(e);if(e<256)return this._createEncoderBuffer([0,e]);n=1;for(var a=e;a>=256;a>>=8)n++;for(a=(o=new Array(n)).length-1;a>=0;a--)o[a]=255&e,e>>=8;return 128&o[0]&&o.unshift(0),this._createEncoderBuffer(new i(o))},c.prototype._encodeBool=function(e){return this._createEncoderBuffer(e?255:0)},c.prototype._use=function(e,t){return"function"==typeof e&&(e=e(t)),e._getEncoder("der").tree},c.prototype._skipDefault=function(e,t,r){var n,i=this._baseState;if(null===i.default)return!1;var o=e.join();if(void 0===i.defaultBuffer&&(i.defaultBuffer=this._encodeValue(i.default,t,r).join()),o.length!==i.defaultBuffer.length)return!1;for(n=0;n=0;c--)if(f[c]!==h[c])return!1;for(c=f.length-1;c>=0;c--)if(u=f[c],!v(e[u],t[u],r,n))return!1;return!0}(e,t,r,a))}return r?e===t:e==t}function g(e){return"[object Arguments]"==Object.prototype.toString.call(e)}function w(e,t){if(!e||!t)return!1;if("[object RegExp]"==Object.prototype.toString.call(t))return t.test(e);try{if(e instanceof t)return!0}catch(e){}return!Error.isPrototypeOf(t)&&!0===t.call({},e)}function _(e,t,r,n){var i;if("function"!=typeof t)throw new TypeError('"block" argument must be a function');"string"==typeof r&&(n=r,r=null),i=function(e){var t;try{e()}catch(e){t=e}return t}(t),n=(r&&r.name?" ("+r.name+").":".")+(n?" "+n:"."),e&&!i&&y(i,r,"Missing expected exception"+n);var a="string"==typeof n,s=!e&&i&&!r;if((!e&&o.isError(i)&&a&&w(i,r)||s)&&y(i,r,"Got unwanted exception"+n),e&&i&&r&&!w(i,r)||!e&&i)throw i}h.AssertionError=function(e){var t;this.name="AssertionError",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,e.message?(this.message=e.message,this.generatedMessage=!1):(this.message=p(b((t=this).actual),128)+" "+t.operator+" "+p(b(t.expected),128),this.generatedMessage=!0);var r=e.stackStartFunction||y;if(Error.captureStackTrace)Error.captureStackTrace(this,r);else{var n=new Error;if(n.stack){var i=n.stack,o=d(r),a=i.indexOf("\n"+o);if(a>=0){var s=i.indexOf("\n",a+1);i=i.substring(s+1)}this.stack=i}}},o.inherits(h.AssertionError,Error),h.fail=y,h.ok=m,h.equal=function(e,t,r){e!=t&&y(e,t,r,"==",h.equal)},h.notEqual=function(e,t,r){e==t&&y(e,t,r,"!=",h.notEqual)},h.deepEqual=function(e,t,r){v(e,t,!1)||y(e,t,r,"deepEqual",h.deepEqual)},h.deepStrictEqual=function(e,t,r){v(e,t,!0)||y(e,t,r,"deepStrictEqual",h.deepStrictEqual)},h.notDeepEqual=function(e,t,r){v(e,t,!1)&&y(e,t,r,"notDeepEqual",h.notDeepEqual)},h.notDeepStrictEqual=function e(t,r,n){v(t,r,!0)&&y(t,r,n,"notDeepStrictEqual",e)},h.strictEqual=function(e,t,r){e!==t&&y(e,t,r,"===",h.strictEqual)},h.notStrictEqual=function(e,t,r){e===t&&y(e,t,r,"!==",h.notStrictEqual)},h.throws=function(e,t,r){_(!0,e,t,r)},h.doesNotThrow=function(e,t,r){_(!1,e,t,r)},h.ifError=function(e){if(e)throw e};var A=Object.keys||function(e){var t=[];for(var r in e)a.call(e,r)&&t.push(r);return t}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"util/":333}],20:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(function(t,r){var i;try{i=e.apply(this,t)}catch(e){return r(e)}(0,n.default)(i)&&"function"==typeof i.then?i.then(function(e){s(r,null,e)},function(e){s(r,e.message?e:new Error(e))}):r(null,i)})};var n=a(e("lodash/isObject")),i=a(e("./internal/initialParams")),o=a(e("./internal/setImmediate"));function a(e){return e&&e.__esModule?e:{default:e}}function s(e,t,r){try{e(t,r)}catch(e){(0,o.default)(u,e)}}function u(e){throw e}t.exports=r.default},{"./internal/initialParams":31,"./internal/setImmediate":37,"lodash/isObject":225}],21:[function(e,t,r){(function(e,n){!function(e,n){"object"==typeof r&&void 0!==t?n(r):"function"==typeof define&&define.amd?define(["exports"],n):n(e.async=e.async||{})}(this,function(r){"use strict";function i(e,t){t|=0;for(var r=Math.max(e.length-t,0),n=Array(r),i=0;i-1&&e%1==0&&e<=L}function D(e){return null!=e&&O(e.length)&&!function(e){if(!s(e))return!1;var t=B(e);return t==C||t==N||t==P||t==R}(e)}var F={};function q(){}function H(e){return function(){if(null!==e){var t=e;e=null,t.apply(this,arguments)}}}var z="function"==typeof Symbol&&Symbol.iterator,K=function(e){return z&&e[z]&&e[z]()};function V(e){return null!=e&&"object"==typeof e}var G="[object Arguments]";function W(e){return V(e)&&B(e)==G}var Y=Object.prototype,X=Y.hasOwnProperty,Z=Y.propertyIsEnumerable,J=W(function(){return arguments}())?W:function(e){return V(e)&&X.call(e,"callee")&&!Z.call(e,"callee")},$=Array.isArray;var Q="object"==typeof r&&r&&!r.nodeType&&r,ee=Q&&"object"==typeof t&&t&&!t.nodeType&&t,te=ee&&ee.exports===Q?A.Buffer:void 0,re=(te?te.isBuffer:void 0)||function(){return!1},ne=9007199254740991,ie=/^(?:0|[1-9]\d*)$/;function oe(e,t){return!!(t=null==t?ne:t)&&("number"==typeof e||ie.test(e))&&e>-1&&e%1==0&&e2&&(n=i(arguments,1)),t){var c={};Fe(o,function(e,t){c[t]=e}),c[e]=n,s=!0,u=Object.create(null),r(t,c)}else o[e]=n,Le(u[e]||[],function(e){e()}),d()});a++;var c=v(t[t.length-1]);t.length>1?c(o,n):c(n)}(e,t)})}function d(){if(0===c.length&&0===a)return r(null,o);for(;c.length&&a=0&&r.push(n)}),r}Fe(e,function(t,r){if(!$(t))return l(r,[t]),void f.push(r);var n=t.slice(0,t.length-1),i=n.length;if(0===i)return l(r,t),void f.push(r);h[r]=i,Le(n,function(o){if(!e[o])throw new Error("async.auto task `"+r+"` has a non-existent dependency `"+o+"` in "+n.join(", "));!function(e,t){var r=u[e];r||(r=u[e]=[]);r.push(t)}(o,function(){0===--i&&l(r,t)})})}),function(){var e,t=0;for(;f.length;)e=f.pop(),t++,Le(p(e),function(e){0==--h[e]&&f.push(e)});if(t!==n)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}(),d()};function Ke(e,t){for(var r=-1,n=null==e?0:e.length,i=Array(n);++r=n?e:function(e,t,r){var n=-1,i=e.length;t<0&&(t=-t>i?0:i+t),(r=r>i?i:r)<0&&(r+=i),i=t>r?0:r-t>>>0,t>>>=0;for(var o=Array(i);++n-1;);return r}(i,o),function(e,t){for(var r=e.length;r--&&He(t,e[r],0)>-1;);return r}(i,o)+1).join("")}var ht=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,lt=/,/,dt=/(=.+)?(\s*)$/,pt=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;function bt(e,t){var r={};Fe(e,function(e,t){var n,i,o=m(e),a=!o&&1===e.length||o&&0===e.length;if($(e))n=e.slice(0,-1),e=e[e.length-1],r[t]=n.concat(n.length>0?s:e);else if(a)r[t]=e;else{if(n=i=(i=(i=(i=(i=e).toString().replace(pt,"")).match(ht)[2].replace(" ",""))?i.split(lt):[]).map(function(e){return ft(e.replace(dt,""))}),0===e.length&&!o&&0===n.length)throw new Error("autoInject task functions require explicit parameters.");o||n.pop(),r[t]=n.concat(s)}function s(t,r){var i=Ke(n,function(e){return t[e]});i.push(r),v(e).apply(null,i)}}),ze(r,t)}function yt(){this.head=this.tail=null,this.length=0}function mt(e,t){e.length=1,e.head=e.tail=t}function vt(e,t,r){if(null==t)t=1;else if(0===t)throw new Error("Concurrency must not be zero");var n=v(e),i=0,o=[],a=!1;function s(e,t,r){if(null!=r&&"function"!=typeof r)throw new Error("task callback must be a function");if(f.started=!0,$(e)||(e=[e]),0===e.length&&f.idle())return l(function(){f.drain()});for(var n=0,i=e.length;n0&&o.splice(s,1),a.callback.apply(a,arguments),null!=t&&f.error(t,a.data)}i<=f.concurrency-f.buffer&&f.unsaturated(),f.idle()&&f.drain(),f.process()}}var c=!1,f={_tasks:new yt,concurrency:t,payload:r,saturated:q,unsaturated:q,buffer:t/4,empty:q,drain:q,error:q,started:!1,paused:!1,push:function(e,t){s(e,!1,t)},kill:function(){f.drain=q,f._tasks.empty()},unshift:function(e,t){s(e,!0,t)},remove:function(e){f._tasks.remove(e)},process:function(){if(!c){for(c=!0;!f.paused&&i2&&(o=i(arguments,1)),n[t]=o,r(e)})},function(e){r(e,n)})}function br(e,t){pr(Ie,e,t)}function yr(e,t,r){pr(Ee(t),e,r)}var mr=function(e,t){var r=v(e);return vt(function(e,t){r(e[0],t)},t,1)},vr=function(e,t){var r=mr(e,t);return r.push=function(e,t,n){if(null==n&&(n=q),"function"!=typeof n)throw new Error("task callback must be a function");if(r.started=!0,$(e)||(e=[e]),0===e.length)return l(function(){r.drain()});t=t||0;for(var i=r._tasks.head;i&&t>=i.priority;)i=i.next;for(var o=0,a=e.length;on?1:0}je(e,function(e,t){n(e,function(r,n){if(r)return t(r);t(null,{value:e,criteria:n})})},function(e,t){if(e)return r(e);r(null,Ke(t.sort(i),Zt("value")))})}function Nr(e,t,r){var n=v(e);return a(function(i,o){var a,s=!1;i.push(function(){s||(o.apply(null,arguments),clearTimeout(a))}),a=setTimeout(function(){var t=e.name||"anonymous",n=new Error('Callback function "'+t+'" timed out.');n.code="ETIMEDOUT",r&&(n.info=r),s=!0,o(n)},t),n.apply(null,i)})}var Rr=Math.ceil,Lr=Math.max;function Or(e,t,r,n){var i=v(r);Ce(function(e,t,r,n){for(var i=-1,o=Lr(Rr((t-e)/(r||1)),0),a=Array(o);o--;)a[n?o:++i]=e,e+=r;return a}(0,e,1),t,i,n)}var Dr=ke(Or,1/0),Fr=ke(Or,1);function qr(e,t,r,n){arguments.length<=3&&(n=r,r=t,t=$(e)?[]:{}),n=H(n||q);var i=v(r);Ie(e,function(e,r,n){i(t,e,r,n)},function(e){n(e,t)})}function Hr(e,t){var r,n=null;t=t||q,Kt(e,function(e,t){v(e)(function(e,o){r=arguments.length>2?i(arguments,1):o,n=e,t(!e)})},function(){t(n,r)})}function zr(e){return function(){return(e.unmemoized||e).apply(null,arguments)}}function Kr(e,t,r){r=Ae(r||q);var n=v(t);if(!e())return r(null);var o=function(t){if(t)return r(t);if(e())return n(o);var a=i(arguments,1);r.apply(null,[null].concat(a))};n(o)}function Vr(e,t,r){Kr(function(){return!e.apply(this,arguments)},t,r)}var Gr=function(e,t){if(t=H(t||q),!$(e))return t(new Error("First argument to waterfall must be an array of functions"));if(!e.length)return t();var r=0;function n(t){var n=v(e[r++]);t.push(Ae(o)),n.apply(null,t)}function o(o){if(o||r===e.length)return t.apply(null,arguments);n(i(arguments,1))}n([])},Wr={apply:o,applyEach:Be,applyEachSeries:Re,asyncify:d,auto:ze,autoInject:bt,cargo:gt,compose:Et,concat:St,concatLimit:kt,concatSeries:Mt,constant:It,detect:Bt,detectLimit:Pt,detectSeries:Ct,dir:Rt,doDuring:Lt,doUntil:Dt,doWhilst:Ot,during:Ft,each:Ht,eachLimit:zt,eachOf:Ie,eachOfLimit:xe,eachOfSeries:wt,eachSeries:Kt,ensureAsync:Vt,every:Wt,everyLimit:Yt,everySeries:Xt,filter:er,filterLimit:tr,filterSeries:rr,forever:nr,groupBy:or,groupByLimit:ir,groupBySeries:ar,log:sr,map:je,mapLimit:Ce,mapSeries:Ne,mapValues:cr,mapValuesLimit:ur,mapValuesSeries:fr,memoize:lr,nextTick:dr,parallel:br,parallelLimit:yr,priorityQueue:vr,queue:mr,race:gr,reduce:_t,reduceRight:wr,reflect:_r,reflectAll:Ar,reject:xr,rejectLimit:kr,rejectSeries:Sr,retry:Ir,retryable:Tr,seq:At,series:Ur,setImmediate:l,some:jr,someLimit:Br,someSeries:Pr,sortBy:Cr,timeout:Nr,times:Dr,timesLimit:Or,timesSeries:Fr,transform:qr,tryEach:Hr,unmemoize:zr,until:Vr,waterfall:Gr,whilst:Kr,all:Wt,allLimit:Yt,allSeries:Xt,any:jr,anyLimit:Br,anySeries:Pr,find:Bt,findLimit:Pt,findSeries:Ct,forEach:Ht,forEachSeries:Kt,forEachLimit:zt,forEachOf:Ie,forEachOfSeries:wt,forEachOfLimit:xe,inject:_t,foldl:_t,foldr:wr,select:er,selectLimit:tr,selectSeries:rr,wrapSync:d};r.default=Wr,r.apply=o,r.applyEach=Be,r.applyEachSeries=Re,r.asyncify=d,r.auto=ze,r.autoInject=bt,r.cargo=gt,r.compose=Et,r.concat=St,r.concatLimit=kt,r.concatSeries=Mt,r.constant=It,r.detect=Bt,r.detectLimit=Pt,r.detectSeries=Ct,r.dir=Rt,r.doDuring=Lt,r.doUntil=Dt,r.doWhilst=Ot,r.during=Ft,r.each=Ht,r.eachLimit=zt,r.eachOf=Ie,r.eachOfLimit=xe,r.eachOfSeries=wt,r.eachSeries=Kt,r.ensureAsync=Vt,r.every=Wt,r.everyLimit=Yt,r.everySeries=Xt,r.filter=er,r.filterLimit=tr,r.filterSeries=rr,r.forever=nr,r.groupBy=or,r.groupByLimit=ir,r.groupBySeries=ar,r.log=sr,r.map=je,r.mapLimit=Ce,r.mapSeries=Ne,r.mapValues=cr,r.mapValuesLimit=ur,r.mapValuesSeries=fr,r.memoize=lr,r.nextTick=dr,r.parallel=br,r.parallelLimit=yr,r.priorityQueue=vr,r.queue=mr,r.race=gr,r.reduce=_t,r.reduceRight=wr,r.reflect=_r,r.reflectAll=Ar,r.reject=xr,r.rejectLimit=kr,r.rejectSeries=Sr,r.retry=Ir,r.retryable=Tr,r.seq=At,r.series=Ur,r.setImmediate=l,r.some=jr,r.someLimit=Br,r.someSeries=Pr,r.sortBy=Cr,r.timeout=Nr,r.times=Dr,r.timesLimit=Or,r.timesSeries=Fr,r.transform=qr,r.tryEach=Hr,r.unmemoize=zr,r.until=Vr,r.waterfall=Gr,r.whilst=Kr,r.all=Wt,r.allLimit=Yt,r.allSeries=Xt,r.any=jr,r.anyLimit=Br,r.anySeries=Pr,r.find=Bt,r.findLimit=Pt,r.findSeries=Ct,r.forEach=Ht,r.forEachSeries=Kt,r.forEachLimit=zt,r.forEachOf=Ie,r.forEachOfSeries=wt,r.forEachOfLimit=xe,r.inject=_t,r.foldl=_t,r.foldr=wr,r.select=er,r.selectLimit=tr,r.selectSeries=rr,r.wrapSync=d,Object.defineProperty(r,"__esModule",{value:!0})})}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:257}],22:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t,r,a){(0,n.default)(t)(e,(0,i.default)((0,o.default)(r)),a)};var n=a(e("./internal/eachOfLimit")),i=a(e("./internal/withoutIndex")),o=a(e("./internal/wrapAsync"));function a(e){return e&&e.__esModule?e:{default:e}}t.exports=r.default},{"./internal/eachOfLimit":29,"./internal/withoutIndex":39,"./internal/wrapAsync":40}],23:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t,r){((0,n.default)(e)?l:d)(e,(0,f.default)(t),r)};var n=h(e("lodash/isArrayLike")),i=h(e("./internal/breakLoop")),o=h(e("./eachOfLimit")),a=h(e("./internal/doLimit")),s=h(e("lodash/noop")),u=h(e("./internal/once")),c=h(e("./internal/onlyOnce")),f=h(e("./internal/wrapAsync"));function h(e){return e&&e.__esModule?e:{default:e}}function l(e,t,r){r=(0,u.default)(r||s.default);var n=0,o=0,a=e.length;function f(e,t){e?r(e):++o!==a&&t!==i.default||r(null)}for(0===a&&r(null);n2&&(n=(0,o.default)(arguments,1)),s[t]=n,r(e)})},function(e){r(e,s)})};var n=s(e("lodash/noop")),i=s(e("lodash/isArrayLike")),o=s(e("./slice")),a=s(e("./wrapAsync"));function s(e){return e&&e.__esModule?e:{default:e}}t.exports=r.default},{"./slice":38,"./wrapAsync":40,"lodash/isArrayLike":221,"lodash/noop":229}],37:[function(e,t,r){(function(t){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.hasNextTick=r.hasSetImmediate=void 0,r.fallback=c,r.wrap=f;var n,i=e("./slice"),o=(n=i)&&n.__esModule?n:{default:n};var a,s=r.hasSetImmediate="function"==typeof setImmediate&&setImmediate,u=r.hasNextTick="object"==typeof t&&"function"==typeof t.nextTick;function c(e){setTimeout(e,0)}function f(e){return function(t){var r=(0,o.default)(arguments,1);e(function(){t.apply(null,r)})}}a=s?setImmediate:u?t.nextTick:c,r.default=f(a)}).call(this,e("_process"))},{"./slice":38,_process:257}],38:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){t|=0;for(var r=Math.max(e.length-t,0),n=Array(r),i=0;i0,"Expected a maximum number of retry greater than 0 but got %s.",e),this.maxNumberOfRetry_=e},o.prototype.backoff=function(e){i.checkState(-1===this.timeoutID_,"Backoff in progress."),this.backoffNumber_===this.maxNumberOfRetry_?(this.emit("fail",e),this.reset()):(this.backoffDelay_=this.backoffStrategy_.next(),this.timeoutID_=setTimeout(this.handlers.backoff,this.backoffDelay_),this.emit("backoff",this.backoffNumber_,this.backoffDelay_,e))},o.prototype.onBackoff_=function(){this.timeoutID_=-1,this.emit("ready",this.backoffNumber_,this.backoffDelay_),this.backoffNumber_++},o.prototype.reset=function(){this.backoffNumber_=0,this.backoffStrategy_.reset(),clearTimeout(this.timeoutID_),this.timeoutID_=-1},t.exports=o},{events:157,precond:253,util:333}],47:[function(e,t,r){var n=e("events"),i=e("precond"),o=e("util"),a=e("./backoff"),s=e("./strategy/fibonacci");function u(e,t,r){n.EventEmitter.call(this),i.checkIsFunction(e,"Expected fn to be a function."),i.checkIsArray(t,"Expected args to be an array."),i.checkIsFunction(r,"Expected callback to be a function."),this.function_=e,this.arguments_=t,this.callback_=r,this.lastResult_=[],this.numRetries_=0,this.backoff_=null,this.strategy_=null,this.failAfter_=-1,this.retryPredicate_=u.DEFAULT_RETRY_PREDICATE_,this.state_=u.State_.PENDING}o.inherits(u,n.EventEmitter),u.State_={PENDING:0,RUNNING:1,COMPLETED:2,ABORTED:3},u.DEFAULT_RETRY_PREDICATE_=function(e){return!0},u.prototype.isPending=function(){return this.state_==u.State_.PENDING},u.prototype.isRunning=function(){return this.state_==u.State_.RUNNING},u.prototype.isCompleted=function(){return this.state_==u.State_.COMPLETED},u.prototype.isAborted=function(){return this.state_==u.State_.ABORTED},u.prototype.setStrategy=function(e){return i.checkState(this.isPending(),"FunctionCall in progress."),this.strategy_=e,this},u.prototype.retryIf=function(e){return i.checkState(this.isPending(),"FunctionCall in progress."),this.retryPredicate_=e,this},u.prototype.getLastResult=function(){return this.lastResult_.concat()},u.prototype.getNumRetries=function(){return this.numRetries_},u.prototype.failAfter=function(e){return i.checkState(this.isPending(),"FunctionCall in progress."),this.failAfter_=e,this},u.prototype.abort=function(){this.isCompleted()||this.isAborted()||(this.isRunning()&&this.backoff_.reset(),this.state_=u.State_.ABORTED,this.lastResult_=[new Error("Backoff aborted.")],this.emit("abort"),this.doCallback_())},u.prototype.start=function(e){i.checkState(!this.isAborted(),"FunctionCall is aborted."),i.checkState(this.isPending(),"FunctionCall already started.");var t=this.strategy_||new s;this.backoff_=e?e(t):new a(t),this.backoff_.on("ready",this.doCall_.bind(this,!0)),this.backoff_.on("fail",this.doCallback_.bind(this)),this.backoff_.on("backoff",this.handleBackoff_.bind(this)),this.failAfter_>0&&this.backoff_.failAfter(this.failAfter_),this.state_=u.State_.RUNNING,this.doCall_(!1)},u.prototype.doCall_=function(e){e&&this.numRetries_++;var t=["call"].concat(this.arguments_);n.EventEmitter.prototype.emit.apply(this,t);var r=this.handleFunctionCallback_.bind(this);this.function_.apply(null,this.arguments_.concat(r))},u.prototype.doCallback_=function(){this.callback_.apply(null,this.lastResult_)},u.prototype.handleFunctionCallback_=function(){if(!this.isAborted()){var e=Array.prototype.slice.call(arguments);this.lastResult_=e,n.EventEmitter.prototype.emit.apply(this,["callback"].concat(e));var t=e[0];t&&this.retryPredicate_(t)?this.backoff_.backoff(t):(this.state_=u.State_.COMPLETED,this.doCallback_())}},u.prototype.handleBackoff_=function(e,t,r){this.emit("backoff",e,t,r)},t.exports=u},{"./backoff":46,"./strategy/fibonacci":49,events:157,precond:253,util:333}],48:[function(e,t,r){var n=e("util"),i=e("precond"),o=e("./strategy");function a(e){o.call(this,e),this.backoffDelay_=0,this.nextBackoffDelay_=this.getInitialDelay(),this.factor_=a.DEFAULT_FACTOR,e&&void 0!==e.factor&&(i.checkArgument(e.factor>1,"Exponential factor should be greater than 1 but got %s.",e.factor),this.factor_=e.factor)}n.inherits(a,o),a.DEFAULT_FACTOR=2,a.prototype.next_=function(){return this.backoffDelay_=Math.min(this.nextBackoffDelay_,this.getMaxDelay()),this.nextBackoffDelay_=this.backoffDelay_*this.factor_,this.backoffDelay_},a.prototype.reset_=function(){this.backoffDelay_=0,this.nextBackoffDelay_=this.getInitialDelay()},t.exports=a},{"./strategy":50,precond:253,util:333}],49:[function(e,t,r){var n=e("util"),i=e("./strategy");function o(e){i.call(this,e),this.backoffDelay_=0,this.nextBackoffDelay_=this.getInitialDelay()}n.inherits(o,i),o.prototype.next_=function(){var e=Math.min(this.nextBackoffDelay_,this.getMaxDelay());return this.nextBackoffDelay_+=this.backoffDelay_,this.backoffDelay_=e,e},o.prototype.reset_=function(){this.nextBackoffDelay_=this.getInitialDelay(),this.backoffDelay_=0},t.exports=o},{"./strategy":50,util:333}],50:[function(e,t,r){e("events"),e("util");function n(e){return null!=e}function i(e){if(n((e=e||{}).initialDelay)&&e.initialDelay<1)throw new Error("The initial timeout must be greater than 0.");if(n(e.maxDelay)&&e.maxDelay<1)throw new Error("The maximal timeout must be greater than 0.");if(this.initialDelay_=e.initialDelay||100,this.maxDelay_=e.maxDelay||1e4,this.maxDelay_<=this.initialDelay_)throw new Error("The maximal backoff delay must be greater than the initial backoff delay.");if(n(e.randomisationFactor)&&(e.randomisationFactor<0||e.randomisationFactor>1))throw new Error("The randomisation factor must be between 0 and 1.");this.randomisationFactor_=e.randomisationFactor||0}i.prototype.getMaxDelay=function(){return this.maxDelay_},i.prototype.getInitialDelay=function(){return this.initialDelay_},i.prototype.next=function(){var e=this.next_(),t=1+Math.random()*this.randomisationFactor_;return Math.round(e*t)},i.prototype.next_=function(){throw new Error("BackoffStrategy.next_() unimplemented.")},i.prototype.reset=function(){this.reset_()},i.prototype.reset_=function(){throw new Error("BackoffStrategy.reset_() unimplemented.")},t.exports=i},{events:157,util:333}],51:[function(e,t,r){"use strict";r.byteLength=function(e){return 3*e.length/4-c(e)},r.toByteArray=function(e){var t,r,n,a,s,u=e.length;a=c(e),s=new o(3*u/4-a),r=a>0?u-4:u;var f=0;for(t=0;t>16&255,s[f++]=n>>8&255,s[f++]=255&n;2===a?(n=i[e.charCodeAt(t)]<<2|i[e.charCodeAt(t+1)]>>4,s[f++]=255&n):1===a&&(n=i[e.charCodeAt(t)]<<10|i[e.charCodeAt(t+1)]<<4|i[e.charCodeAt(t+2)]>>2,s[f++]=n>>8&255,s[f++]=255&n);return s},r.fromByteArray=function(e){for(var t,r=e.length,i=r%3,o="",a=[],s=0,u=r-i;su?u:s+16383));1===i?(t=e[r-1],o+=n[t>>2],o+=n[t<<4&63],o+="=="):2===i&&(t=(e[r-2]<<8)+e[r-1],o+=n[t>>10],o+=n[t>>4&63],o+=n[t<<2&63],o+="=");return a.push(o),a.join("")};for(var n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,u=a.length;s0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===e[t-2]?2:"="===e[t-1]?1:0}function f(e,t,r){for(var i,o,a=[],s=t;s>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return a.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},{}],52:[function(e,t,r){var n=e("safe-buffer").Buffer;t.exports={check:function(e){if(e.length<8)return!1;if(e.length>72)return!1;if(48!==e[0])return!1;if(e[1]!==e.length-2)return!1;if(2!==e[2])return!1;var t=e[3];if(0===t)return!1;if(5+t>=e.length)return!1;if(2!==e[4+t])return!1;var r=e[5+t];return!(0===r||6+t+r!==e.length||128&e[4]||t>1&&0===e[4]&&!(128&e[5])||128&e[t+6]||r>1&&0===e[t+6]&&!(128&e[t+7]))},decode:function(e){if(e.length<8)throw new Error("DER sequence length is too short");if(e.length>72)throw new Error("DER sequence length is too long");if(48!==e[0])throw new Error("Expected DER sequence");if(e[1]!==e.length-2)throw new Error("DER sequence length is invalid");if(2!==e[2])throw new Error("Expected DER integer");var t=e[3];if(0===t)throw new Error("R length is zero");if(5+t>=e.length)throw new Error("R length is too long");if(2!==e[4+t])throw new Error("Expected DER integer (2)");var r=e[5+t];if(0===r)throw new Error("S length is zero");if(6+t+r!==e.length)throw new Error("S length is invalid");if(128&e[4])throw new Error("R value is negative");if(t>1&&0===e[4]&&!(128&e[5]))throw new Error("R value excessively padded");if(128&e[t+6])throw new Error("S value is negative");if(r>1&&0===e[t+6]&&!(128&e[t+7]))throw new Error("S value excessively padded");return{r:e.slice(4,4+t),s:e.slice(6+t)}},encode:function(e,t){var r=e.length,i=t.length;if(0===r)throw new Error("R length is zero");if(0===i)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(i>33)throw new Error("S length is too long");if(128&e[0])throw new Error("R value is negative");if(128&t[0])throw new Error("S value is negative");if(r>1&&0===e[0]&&!(128&e[1]))throw new Error("R value excessively padded");if(i>1&&0===t[0]&&!(128&t[1]))throw new Error("S value excessively padded");var o=n.allocUnsafe(6+r+i);return o[0]=48,o[1]=o.length-2,o[2]=2,o[3]=e.length,e.copy(o,4),o[4+r]=2,o[5+r]=t.length,t.copy(o,6+r),o}}},{"safe-buffer":290}],53:[function(e,t,r){!function(t,r){"use strict";function n(e,t){if(!e)throw new Error(t||"Assertion failed")}function i(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}function o(e,t,r){if(o.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(r=t,t=10),this._init(e||0,t||10,r||"be"))}var a;"object"==typeof t?t.exports=o:r.BN=o,o.BN=o,o.wordSize=26;try{a=e("buffer").Buffer}catch(e){}function s(e,t,r){for(var n=0,i=Math.min(e.length,r),o=t;o=49&&a<=54?a-49+10:a>=17&&a<=22?a-17+10:15&a}return n}function u(e,t,r,n){for(var i=0,o=Math.min(e.length,r),a=t;a=49?s-49+10:s>=17?s-17+10:s}return i}o.isBN=function(e){return e instanceof o||null!==e&&"object"==typeof e&&e.constructor.wordSize===o.wordSize&&Array.isArray(e.words)},o.max=function(e,t){return e.cmp(t)>0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&i++,16===t?this._parseHex(e,i):this._parseBase(e,t,i),"-"===e[0]&&(this.negative=1),this.strip(),"le"===r&&this._initArray(this.toArray(),t,r)},o.prototype._initNumber=function(e,t,r){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(n(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===r&&this._initArray(this.toArray(),t,r)},o.prototype._initArray=function(e,t,r){if(n("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3)a=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[o]|=a<>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);else if("le"===r)for(i=0,o=0;i>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);return this.strip()},o.prototype._parseHex=function(e,t){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var r=0;r=t;r-=6)i=s(e,r,r+6),this.words[n]|=i<>>26-o&4194303,(o+=24)>=26&&(o-=26,n++);r+6!==t&&(i=s(e,t,r+6),this.words[n]|=i<>>26-o&4194303),this.strip()},o.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=t)n++;n--,i=i/t|0;for(var o=e.length-r,a=o%n,s=Math.min(o,o-a)+r,c=0,f=r;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},o.prototype.inspect=function(){return(this.red?""};var c=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],f=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],h=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(e,t,r){r.negative=t.negative^e.negative;var n=e.length+t.length|0;r.length=n,n=n-1|0;var i=0|e.words[0],o=0|t.words[0],a=i*o,s=67108863&a,u=a/67108864|0;r.words[0]=s;for(var c=1;c>>26,h=67108863&u,l=Math.min(c,t.length-1),d=Math.max(0,c-e.length+1);d<=l;d++){var p=c-d|0;f+=(a=(i=0|e.words[p])*(o=0|t.words[d])+h)/67108864|0,h=67108863&a}r.words[c]=0|h,u=0|f}return 0!==u?r.words[c]=0|u:r.length--,r.strip()}o.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var i=0,o=0,a=0;a>>24-i&16777215)||a!==this.length-1?c[6-u.length]+u+r:u+r,(i+=2)>=26&&(i-=26,a--)}for(0!==o&&(r=o.toString(16)+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var l=f[e],d=h[e];r="";var p=this.clone();for(p.negative=0;!p.isZero();){var b=p.modn(d).toString(e);r=(p=p.idivn(d)).isZero()?b+r:c[l-b.length]+b+r}for(this.isZero()&&(r="0"+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16)},o.prototype.toBuffer=function(e,t){return n(void 0!==a),this.toArrayLike(a,e,t)},o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},o.prototype.toArrayLike=function(e,t,r){var i=this.byteLength(),o=r||Math.max(1,i);n(i<=o,"byte array longer than desired length"),n(o>0,"Requested array length <= 0"),this.strip();var a,s,u="le"===t,c=new e(o),f=this.clone();if(u){for(s=0;!f.isZero();s++)a=f.andln(255),f.iushrn(8),c[s]=a;for(;s=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;re.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,r;this.length>e.length?(t=this,r=e):(t=e,r=this);for(var n=0;ne.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-r),this.strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,i=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<e.length?(r=this,n=e):(r=e,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;oe.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var r,n,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=e):(r=e,n=this);for(var o=0,a=0;a>26,this.words[a]=67108863&t;for(;0!==o&&a>26,this.words[a]=67108863&t;if(0===o&&a>>13,d=0|a[1],p=8191&d,b=d>>>13,y=0|a[2],m=8191&y,v=y>>>13,g=0|a[3],w=8191&g,_=g>>>13,A=0|a[4],E=8191&A,x=A>>>13,k=0|a[5],S=8191&k,M=k>>>13,I=0|a[6],T=8191&I,U=I>>>13,j=0|a[7],B=8191&j,P=j>>>13,C=0|a[8],N=8191&C,R=C>>>13,L=0|a[9],O=8191&L,D=L>>>13,F=0|s[0],q=8191&F,H=F>>>13,z=0|s[1],K=8191&z,V=z>>>13,G=0|s[2],W=8191&G,Y=G>>>13,X=0|s[3],Z=8191&X,J=X>>>13,$=0|s[4],Q=8191&$,ee=$>>>13,te=0|s[5],re=8191&te,ne=te>>>13,ie=0|s[6],oe=8191&ie,ae=ie>>>13,se=0|s[7],ue=8191&se,ce=se>>>13,fe=0|s[8],he=8191&fe,le=fe>>>13,de=0|s[9],pe=8191&de,be=de>>>13;r.negative=e.negative^t.negative,r.length=19;var ye=(c+(n=Math.imul(h,q))|0)+((8191&(i=(i=Math.imul(h,H))+Math.imul(l,q)|0))<<13)|0;c=((o=Math.imul(l,H))+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,n=Math.imul(p,q),i=(i=Math.imul(p,H))+Math.imul(b,q)|0,o=Math.imul(b,H);var me=(c+(n=n+Math.imul(h,K)|0)|0)+((8191&(i=(i=i+Math.imul(h,V)|0)+Math.imul(l,K)|0))<<13)|0;c=((o=o+Math.imul(l,V)|0)+(i>>>13)|0)+(me>>>26)|0,me&=67108863,n=Math.imul(m,q),i=(i=Math.imul(m,H))+Math.imul(v,q)|0,o=Math.imul(v,H),n=n+Math.imul(p,K)|0,i=(i=i+Math.imul(p,V)|0)+Math.imul(b,K)|0,o=o+Math.imul(b,V)|0;var ve=(c+(n=n+Math.imul(h,W)|0)|0)+((8191&(i=(i=i+Math.imul(h,Y)|0)+Math.imul(l,W)|0))<<13)|0;c=((o=o+Math.imul(l,Y)|0)+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,n=Math.imul(w,q),i=(i=Math.imul(w,H))+Math.imul(_,q)|0,o=Math.imul(_,H),n=n+Math.imul(m,K)|0,i=(i=i+Math.imul(m,V)|0)+Math.imul(v,K)|0,o=o+Math.imul(v,V)|0,n=n+Math.imul(p,W)|0,i=(i=i+Math.imul(p,Y)|0)+Math.imul(b,W)|0,o=o+Math.imul(b,Y)|0;var ge=(c+(n=n+Math.imul(h,Z)|0)|0)+((8191&(i=(i=i+Math.imul(h,J)|0)+Math.imul(l,Z)|0))<<13)|0;c=((o=o+Math.imul(l,J)|0)+(i>>>13)|0)+(ge>>>26)|0,ge&=67108863,n=Math.imul(E,q),i=(i=Math.imul(E,H))+Math.imul(x,q)|0,o=Math.imul(x,H),n=n+Math.imul(w,K)|0,i=(i=i+Math.imul(w,V)|0)+Math.imul(_,K)|0,o=o+Math.imul(_,V)|0,n=n+Math.imul(m,W)|0,i=(i=i+Math.imul(m,Y)|0)+Math.imul(v,W)|0,o=o+Math.imul(v,Y)|0,n=n+Math.imul(p,Z)|0,i=(i=i+Math.imul(p,J)|0)+Math.imul(b,Z)|0,o=o+Math.imul(b,J)|0;var we=(c+(n=n+Math.imul(h,Q)|0)|0)+((8191&(i=(i=i+Math.imul(h,ee)|0)+Math.imul(l,Q)|0))<<13)|0;c=((o=o+Math.imul(l,ee)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,n=Math.imul(S,q),i=(i=Math.imul(S,H))+Math.imul(M,q)|0,o=Math.imul(M,H),n=n+Math.imul(E,K)|0,i=(i=i+Math.imul(E,V)|0)+Math.imul(x,K)|0,o=o+Math.imul(x,V)|0,n=n+Math.imul(w,W)|0,i=(i=i+Math.imul(w,Y)|0)+Math.imul(_,W)|0,o=o+Math.imul(_,Y)|0,n=n+Math.imul(m,Z)|0,i=(i=i+Math.imul(m,J)|0)+Math.imul(v,Z)|0,o=o+Math.imul(v,J)|0,n=n+Math.imul(p,Q)|0,i=(i=i+Math.imul(p,ee)|0)+Math.imul(b,Q)|0,o=o+Math.imul(b,ee)|0;var _e=(c+(n=n+Math.imul(h,re)|0)|0)+((8191&(i=(i=i+Math.imul(h,ne)|0)+Math.imul(l,re)|0))<<13)|0;c=((o=o+Math.imul(l,ne)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,n=Math.imul(T,q),i=(i=Math.imul(T,H))+Math.imul(U,q)|0,o=Math.imul(U,H),n=n+Math.imul(S,K)|0,i=(i=i+Math.imul(S,V)|0)+Math.imul(M,K)|0,o=o+Math.imul(M,V)|0,n=n+Math.imul(E,W)|0,i=(i=i+Math.imul(E,Y)|0)+Math.imul(x,W)|0,o=o+Math.imul(x,Y)|0,n=n+Math.imul(w,Z)|0,i=(i=i+Math.imul(w,J)|0)+Math.imul(_,Z)|0,o=o+Math.imul(_,J)|0,n=n+Math.imul(m,Q)|0,i=(i=i+Math.imul(m,ee)|0)+Math.imul(v,Q)|0,o=o+Math.imul(v,ee)|0,n=n+Math.imul(p,re)|0,i=(i=i+Math.imul(p,ne)|0)+Math.imul(b,re)|0,o=o+Math.imul(b,ne)|0;var Ae=(c+(n=n+Math.imul(h,oe)|0)|0)+((8191&(i=(i=i+Math.imul(h,ae)|0)+Math.imul(l,oe)|0))<<13)|0;c=((o=o+Math.imul(l,ae)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,n=Math.imul(B,q),i=(i=Math.imul(B,H))+Math.imul(P,q)|0,o=Math.imul(P,H),n=n+Math.imul(T,K)|0,i=(i=i+Math.imul(T,V)|0)+Math.imul(U,K)|0,o=o+Math.imul(U,V)|0,n=n+Math.imul(S,W)|0,i=(i=i+Math.imul(S,Y)|0)+Math.imul(M,W)|0,o=o+Math.imul(M,Y)|0,n=n+Math.imul(E,Z)|0,i=(i=i+Math.imul(E,J)|0)+Math.imul(x,Z)|0,o=o+Math.imul(x,J)|0,n=n+Math.imul(w,Q)|0,i=(i=i+Math.imul(w,ee)|0)+Math.imul(_,Q)|0,o=o+Math.imul(_,ee)|0,n=n+Math.imul(m,re)|0,i=(i=i+Math.imul(m,ne)|0)+Math.imul(v,re)|0,o=o+Math.imul(v,ne)|0,n=n+Math.imul(p,oe)|0,i=(i=i+Math.imul(p,ae)|0)+Math.imul(b,oe)|0,o=o+Math.imul(b,ae)|0;var Ee=(c+(n=n+Math.imul(h,ue)|0)|0)+((8191&(i=(i=i+Math.imul(h,ce)|0)+Math.imul(l,ue)|0))<<13)|0;c=((o=o+Math.imul(l,ce)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,n=Math.imul(N,q),i=(i=Math.imul(N,H))+Math.imul(R,q)|0,o=Math.imul(R,H),n=n+Math.imul(B,K)|0,i=(i=i+Math.imul(B,V)|0)+Math.imul(P,K)|0,o=o+Math.imul(P,V)|0,n=n+Math.imul(T,W)|0,i=(i=i+Math.imul(T,Y)|0)+Math.imul(U,W)|0,o=o+Math.imul(U,Y)|0,n=n+Math.imul(S,Z)|0,i=(i=i+Math.imul(S,J)|0)+Math.imul(M,Z)|0,o=o+Math.imul(M,J)|0,n=n+Math.imul(E,Q)|0,i=(i=i+Math.imul(E,ee)|0)+Math.imul(x,Q)|0,o=o+Math.imul(x,ee)|0,n=n+Math.imul(w,re)|0,i=(i=i+Math.imul(w,ne)|0)+Math.imul(_,re)|0,o=o+Math.imul(_,ne)|0,n=n+Math.imul(m,oe)|0,i=(i=i+Math.imul(m,ae)|0)+Math.imul(v,oe)|0,o=o+Math.imul(v,ae)|0,n=n+Math.imul(p,ue)|0,i=(i=i+Math.imul(p,ce)|0)+Math.imul(b,ue)|0,o=o+Math.imul(b,ce)|0;var xe=(c+(n=n+Math.imul(h,he)|0)|0)+((8191&(i=(i=i+Math.imul(h,le)|0)+Math.imul(l,he)|0))<<13)|0;c=((o=o+Math.imul(l,le)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,n=Math.imul(O,q),i=(i=Math.imul(O,H))+Math.imul(D,q)|0,o=Math.imul(D,H),n=n+Math.imul(N,K)|0,i=(i=i+Math.imul(N,V)|0)+Math.imul(R,K)|0,o=o+Math.imul(R,V)|0,n=n+Math.imul(B,W)|0,i=(i=i+Math.imul(B,Y)|0)+Math.imul(P,W)|0,o=o+Math.imul(P,Y)|0,n=n+Math.imul(T,Z)|0,i=(i=i+Math.imul(T,J)|0)+Math.imul(U,Z)|0,o=o+Math.imul(U,J)|0,n=n+Math.imul(S,Q)|0,i=(i=i+Math.imul(S,ee)|0)+Math.imul(M,Q)|0,o=o+Math.imul(M,ee)|0,n=n+Math.imul(E,re)|0,i=(i=i+Math.imul(E,ne)|0)+Math.imul(x,re)|0,o=o+Math.imul(x,ne)|0,n=n+Math.imul(w,oe)|0,i=(i=i+Math.imul(w,ae)|0)+Math.imul(_,oe)|0,o=o+Math.imul(_,ae)|0,n=n+Math.imul(m,ue)|0,i=(i=i+Math.imul(m,ce)|0)+Math.imul(v,ue)|0,o=o+Math.imul(v,ce)|0,n=n+Math.imul(p,he)|0,i=(i=i+Math.imul(p,le)|0)+Math.imul(b,he)|0,o=o+Math.imul(b,le)|0;var ke=(c+(n=n+Math.imul(h,pe)|0)|0)+((8191&(i=(i=i+Math.imul(h,be)|0)+Math.imul(l,pe)|0))<<13)|0;c=((o=o+Math.imul(l,be)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,n=Math.imul(O,K),i=(i=Math.imul(O,V))+Math.imul(D,K)|0,o=Math.imul(D,V),n=n+Math.imul(N,W)|0,i=(i=i+Math.imul(N,Y)|0)+Math.imul(R,W)|0,o=o+Math.imul(R,Y)|0,n=n+Math.imul(B,Z)|0,i=(i=i+Math.imul(B,J)|0)+Math.imul(P,Z)|0,o=o+Math.imul(P,J)|0,n=n+Math.imul(T,Q)|0,i=(i=i+Math.imul(T,ee)|0)+Math.imul(U,Q)|0,o=o+Math.imul(U,ee)|0,n=n+Math.imul(S,re)|0,i=(i=i+Math.imul(S,ne)|0)+Math.imul(M,re)|0,o=o+Math.imul(M,ne)|0,n=n+Math.imul(E,oe)|0,i=(i=i+Math.imul(E,ae)|0)+Math.imul(x,oe)|0,o=o+Math.imul(x,ae)|0,n=n+Math.imul(w,ue)|0,i=(i=i+Math.imul(w,ce)|0)+Math.imul(_,ue)|0,o=o+Math.imul(_,ce)|0,n=n+Math.imul(m,he)|0,i=(i=i+Math.imul(m,le)|0)+Math.imul(v,he)|0,o=o+Math.imul(v,le)|0;var Se=(c+(n=n+Math.imul(p,pe)|0)|0)+((8191&(i=(i=i+Math.imul(p,be)|0)+Math.imul(b,pe)|0))<<13)|0;c=((o=o+Math.imul(b,be)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,n=Math.imul(O,W),i=(i=Math.imul(O,Y))+Math.imul(D,W)|0,o=Math.imul(D,Y),n=n+Math.imul(N,Z)|0,i=(i=i+Math.imul(N,J)|0)+Math.imul(R,Z)|0,o=o+Math.imul(R,J)|0,n=n+Math.imul(B,Q)|0,i=(i=i+Math.imul(B,ee)|0)+Math.imul(P,Q)|0,o=o+Math.imul(P,ee)|0,n=n+Math.imul(T,re)|0,i=(i=i+Math.imul(T,ne)|0)+Math.imul(U,re)|0,o=o+Math.imul(U,ne)|0,n=n+Math.imul(S,oe)|0,i=(i=i+Math.imul(S,ae)|0)+Math.imul(M,oe)|0,o=o+Math.imul(M,ae)|0,n=n+Math.imul(E,ue)|0,i=(i=i+Math.imul(E,ce)|0)+Math.imul(x,ue)|0,o=o+Math.imul(x,ce)|0,n=n+Math.imul(w,he)|0,i=(i=i+Math.imul(w,le)|0)+Math.imul(_,he)|0,o=o+Math.imul(_,le)|0;var Me=(c+(n=n+Math.imul(m,pe)|0)|0)+((8191&(i=(i=i+Math.imul(m,be)|0)+Math.imul(v,pe)|0))<<13)|0;c=((o=o+Math.imul(v,be)|0)+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863,n=Math.imul(O,Z),i=(i=Math.imul(O,J))+Math.imul(D,Z)|0,o=Math.imul(D,J),n=n+Math.imul(N,Q)|0,i=(i=i+Math.imul(N,ee)|0)+Math.imul(R,Q)|0,o=o+Math.imul(R,ee)|0,n=n+Math.imul(B,re)|0,i=(i=i+Math.imul(B,ne)|0)+Math.imul(P,re)|0,o=o+Math.imul(P,ne)|0,n=n+Math.imul(T,oe)|0,i=(i=i+Math.imul(T,ae)|0)+Math.imul(U,oe)|0,o=o+Math.imul(U,ae)|0,n=n+Math.imul(S,ue)|0,i=(i=i+Math.imul(S,ce)|0)+Math.imul(M,ue)|0,o=o+Math.imul(M,ce)|0,n=n+Math.imul(E,he)|0,i=(i=i+Math.imul(E,le)|0)+Math.imul(x,he)|0,o=o+Math.imul(x,le)|0;var Ie=(c+(n=n+Math.imul(w,pe)|0)|0)+((8191&(i=(i=i+Math.imul(w,be)|0)+Math.imul(_,pe)|0))<<13)|0;c=((o=o+Math.imul(_,be)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,n=Math.imul(O,Q),i=(i=Math.imul(O,ee))+Math.imul(D,Q)|0,o=Math.imul(D,ee),n=n+Math.imul(N,re)|0,i=(i=i+Math.imul(N,ne)|0)+Math.imul(R,re)|0,o=o+Math.imul(R,ne)|0,n=n+Math.imul(B,oe)|0,i=(i=i+Math.imul(B,ae)|0)+Math.imul(P,oe)|0,o=o+Math.imul(P,ae)|0,n=n+Math.imul(T,ue)|0,i=(i=i+Math.imul(T,ce)|0)+Math.imul(U,ue)|0,o=o+Math.imul(U,ce)|0,n=n+Math.imul(S,he)|0,i=(i=i+Math.imul(S,le)|0)+Math.imul(M,he)|0,o=o+Math.imul(M,le)|0;var Te=(c+(n=n+Math.imul(E,pe)|0)|0)+((8191&(i=(i=i+Math.imul(E,be)|0)+Math.imul(x,pe)|0))<<13)|0;c=((o=o+Math.imul(x,be)|0)+(i>>>13)|0)+(Te>>>26)|0,Te&=67108863,n=Math.imul(O,re),i=(i=Math.imul(O,ne))+Math.imul(D,re)|0,o=Math.imul(D,ne),n=n+Math.imul(N,oe)|0,i=(i=i+Math.imul(N,ae)|0)+Math.imul(R,oe)|0,o=o+Math.imul(R,ae)|0,n=n+Math.imul(B,ue)|0,i=(i=i+Math.imul(B,ce)|0)+Math.imul(P,ue)|0,o=o+Math.imul(P,ce)|0,n=n+Math.imul(T,he)|0,i=(i=i+Math.imul(T,le)|0)+Math.imul(U,he)|0,o=o+Math.imul(U,le)|0;var Ue=(c+(n=n+Math.imul(S,pe)|0)|0)+((8191&(i=(i=i+Math.imul(S,be)|0)+Math.imul(M,pe)|0))<<13)|0;c=((o=o+Math.imul(M,be)|0)+(i>>>13)|0)+(Ue>>>26)|0,Ue&=67108863,n=Math.imul(O,oe),i=(i=Math.imul(O,ae))+Math.imul(D,oe)|0,o=Math.imul(D,ae),n=n+Math.imul(N,ue)|0,i=(i=i+Math.imul(N,ce)|0)+Math.imul(R,ue)|0,o=o+Math.imul(R,ce)|0,n=n+Math.imul(B,he)|0,i=(i=i+Math.imul(B,le)|0)+Math.imul(P,he)|0,o=o+Math.imul(P,le)|0;var je=(c+(n=n+Math.imul(T,pe)|0)|0)+((8191&(i=(i=i+Math.imul(T,be)|0)+Math.imul(U,pe)|0))<<13)|0;c=((o=o+Math.imul(U,be)|0)+(i>>>13)|0)+(je>>>26)|0,je&=67108863,n=Math.imul(O,ue),i=(i=Math.imul(O,ce))+Math.imul(D,ue)|0,o=Math.imul(D,ce),n=n+Math.imul(N,he)|0,i=(i=i+Math.imul(N,le)|0)+Math.imul(R,he)|0,o=o+Math.imul(R,le)|0;var Be=(c+(n=n+Math.imul(B,pe)|0)|0)+((8191&(i=(i=i+Math.imul(B,be)|0)+Math.imul(P,pe)|0))<<13)|0;c=((o=o+Math.imul(P,be)|0)+(i>>>13)|0)+(Be>>>26)|0,Be&=67108863,n=Math.imul(O,he),i=(i=Math.imul(O,le))+Math.imul(D,he)|0,o=Math.imul(D,le);var Pe=(c+(n=n+Math.imul(N,pe)|0)|0)+((8191&(i=(i=i+Math.imul(N,be)|0)+Math.imul(R,pe)|0))<<13)|0;c=((o=o+Math.imul(R,be)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863;var Ce=(c+(n=Math.imul(O,pe))|0)+((8191&(i=(i=Math.imul(O,be))+Math.imul(D,pe)|0))<<13)|0;return c=((o=Math.imul(D,be))+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,u[0]=ye,u[1]=me,u[2]=ve,u[3]=ge,u[4]=we,u[5]=_e,u[6]=Ae,u[7]=Ee,u[8]=xe,u[9]=ke,u[10]=Se,u[11]=Me,u[12]=Ie,u[13]=Te,u[14]=Ue,u[15]=je,u[16]=Be,u[17]=Pe,u[18]=Ce,0!==c&&(u[19]=c,r.length++),r};function p(e,t,r){return(new b).mulp(e,t,r)}function b(e,t){this.x=e,this.y=t}Math.imul||(d=l),o.prototype.mulTo=function(e,t){var r=this.length+e.length;return 10===this.length&&10===e.length?d(this,e,t):r<63?l(this,e,t):r<1024?function(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,a&=67108863}r.words[o]=s,n=a,a=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,e,t):p(this,e,t)},b.prototype.makeRBT=function(e){for(var t=new Array(e),r=o.prototype._countBits(e)-1,n=0;n>=1;return n},b.prototype.permute=function(e,t,r,n,i,o){for(var a=0;a>>=1)i++;return 1<>>=13,r[2*a+1]=8191&o,o>>>=13;for(a=2*t;a>=26,t+=i/67108864|0,t+=o>>>26,this.words[r]=67108863&o}return 0!==t&&(this.words[r]=t,this.length++),this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),r=0;r>>i}return t}(e);if(0===t.length)return new o(1);for(var r=this,n=0;n=0);var t,r=e%26,i=(e-r)/26,o=67108863>>>26-r<<26-r;if(0!==r){var a=0;for(t=0;t>>26-r}a&&(this.words[t]=a,this.length++)}if(0!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t=0),i=t?(t-t%26)/26:0;var o=e%26,a=Math.min((e-o)/26,this.length),s=67108863^67108863>>>o<a)for(this.length-=a,c=0;c=0&&(0!==f||c>=i);c--){var h=0|this.words[c];this.words[c]=f<<26-o|h>>>o,f=h&s}return u&&0!==f&&(u.words[u.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},o.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,i=1<=0);var t=e%26,r=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var i=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(u/67108864|0),this.words[i+r]=67108863&o}for(;i>26,this.words[i+r]=67108863&o;if(0===s)return this.strip();for(n(-1===s),s=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},o.prototype._wordDiv=function(e,t){var r=(this.length,e.length),n=this.clone(),i=e,a=0|i.words[i.length-1];0!==(r=26-this._countBits(a))&&(i=i.ushln(r),n.iushln(r),a=0|i.words[i.length-1]);var s,u=n.length-i.length;if("mod"!==t){(s=new o(null)).length=u+1,s.words=new Array(s.length);for(var c=0;c=0;h--){var l=67108864*(0|n.words[i.length+h])+(0|n.words[i.length+h-1]);for(l=Math.min(l/a|0,67108863),n._ishlnsubmul(i,l,h);0!==n.negative;)l--,n.negative=0,n._ishlnsubmul(i,1,h),n.isZero()||(n.negative^=1);s&&(s.words[h]=l)}return s&&s.strip(),n.strip(),"div"!==t&&0!==r&&n.iushrn(r),{div:s||null,mod:n}},o.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(s=this.neg().divmod(e,t),"mod"!==t&&(i=s.div.neg()),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.iadd(e)),{div:i,mod:a}):0===this.negative&&0!==e.negative?(s=this.divmod(e.neg(),t),"mod"!==t&&(i=s.div.neg()),{div:i,mod:s.mod}):0!=(this.negative&e.negative)?(s=this.neg().divmod(e.neg(),t),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.isub(e)),{div:s.div,mod:a}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modn(e.words[0]))}:this._wordDiv(e,t);var i,a,s},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=0!==t.div.negative?t.mod.isub(e):t.mod,n=e.ushrn(1),i=e.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modn=function(e){n(e<=67108863);for(var t=(1<<26)%e,r=0,i=this.length-1;i>=0;i--)r=(t*r+(0|this.words[i]))%e;return r},o.prototype.idivn=function(e){n(e<=67108863);for(var t=0,r=this.length-1;r>=0;r--){var i=(0|this.words[r])+67108864*t;this.words[r]=i/e|0,t=i%e}return this.strip()},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new o(1),a=new o(0),s=new o(0),u=new o(1),c=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++c;for(var f=r.clone(),h=t.clone();!t.isZero();){for(var l=0,d=1;0==(t.words[0]&d)&&l<26;++l,d<<=1);if(l>0)for(t.iushrn(l);l-- >0;)(i.isOdd()||a.isOdd())&&(i.iadd(f),a.isub(h)),i.iushrn(1),a.iushrn(1);for(var p=0,b=1;0==(r.words[0]&b)&&p<26;++p,b<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(s.isOdd()||u.isOdd())&&(s.iadd(f),u.isub(h)),s.iushrn(1),u.iushrn(1);t.cmp(r)>=0?(t.isub(r),i.isub(s),a.isub(u)):(r.isub(t),s.isub(i),u.isub(a))}return{a:s,b:u,gcd:r.iushln(c)}},o.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,a=new o(1),s=new o(0),u=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var c=0,f=1;0==(t.words[0]&f)&&c<26;++c,f<<=1);if(c>0)for(t.iushrn(c);c-- >0;)a.isOdd()&&a.iadd(u),a.iushrn(1);for(var h=0,l=1;0==(r.words[0]&l)&&h<26;++h,l<<=1);if(h>0)for(r.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(u),s.iushrn(1);t.cmp(r)>=0?(t.isub(r),a.isub(s)):(r.isub(t),s.isub(a))}return(i=0===t.cmpn(1)?a:s).cmpn(0)<0&&i.iadd(e),i},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var n=0;t.isEven()&&r.isEven();n++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=t.cmp(r);if(i<0){var o=t;t=r,r=o}else if(0===i||0===r.cmpn(1))break;t.isub(r)}return r.iushln(n)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return 0==(1&this.words[0])},o.prototype.isOdd=function(){return 1==(1&this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,i=1<>>26,s&=67108863,this.words[a]=s}return 0!==o&&(this.words[a]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this.strip(),this.length>1)t=1;else{r&&(e=-e),n(e<=67108863,"Number is too big");var i=0|this.words[0];t=i===e?0:ie.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|e.words[r];if(n!==i){ni&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new A(e)},o.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var y={k256:null,p224:null,p192:null,p25519:null};function m(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function v(){m.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function g(){m.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function w(){m.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function _(){m.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function A(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function E(e){A.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(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)}m.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},m.prototype.ireduce=function(e){var t,r=e;do{this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(t>this.n);var n=t0?r.isub(this.p):r.strip(),r},m.prototype.split=function(e,t){e.iushrn(this.n,0,t)},m.prototype.imulK=function(e){return e.imul(this.k)},i(v,m),v.prototype.split=function(e,t){for(var r=Math.min(e.length,9),n=0;n>>22,i=o}i>>>=22,e.words[n-10]=i,0===i&&e.length>10?e.length-=10:e.length-=9},v.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r>>=26,e.words[r]=i,t=n}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(y[e])return y[e];var t;if("k256"===e)t=new v;else if("p224"===e)t=new g;else if("p192"===e)t=new w;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new _}return y[e]=t,t},A.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},A.prototype._verify2=function(e,t){n(0==(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},A.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},A.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},A.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},A.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},A.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},A.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},A.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},A.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},A.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},A.prototype.isqr=function(e){return this.imul(e,e.clone())},A.prototype.sqr=function(e){return this.mul(e,e)},A.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var r=this.m.add(new o(1)).iushrn(2);return this.pow(e,r)}for(var i=this.m.subn(1),a=0;!i.isZero()&&0===i.andln(1);)a++,i.iushrn(1);n(!i.isZero());var s=new o(1).toRed(this),u=s.redNeg(),c=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new o(2*f*f).toRed(this);0!==this.pow(f,c).cmp(u);)f.redIAdd(u);for(var h=this.pow(f,i),l=this.pow(e,i.addn(1).iushrn(1)),d=this.pow(e,i),p=a;0!==d.cmp(s);){for(var b=d,y=0;0!==b.cmp(s);y++)b=b.redSqr();n(y=0;n--){for(var c=t.words[n],f=u-1;f>=0;f--){var h=c>>f&1;i!==r[0]&&(i=this.sqr(i)),0!==h||0!==a?(a<<=1,a|=h,(4===++s||0===n&&0===f)&&(i=this.mul(i,r[a]),s=0,a=0)):s=0}u=26}return i},A.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},A.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new E(e)},i(E,A),E.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},E.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},E.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},E.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var r=e.mul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},E.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===t||t,this)},{buffer:55}],54:[function(e,t,r){var n;function i(e){this.rand=e}if(t.exports=function(e){return n||(n=new i(null)),n.generate(e)},t.exports.Rand=i,i.prototype.generate=function(e){return this._rand(e)},i.prototype._rand=function(e){if(this.rand.getBytes)return this.rand.getBytes(e);for(var t=new Uint8Array(e),r=0;r>>24]^f[p>>>16&255]^h[b>>>8&255]^l[255&y]^t[m++],a=c[p>>>24]^f[b>>>16&255]^h[y>>>8&255]^l[255&d]^t[m++],s=c[b>>>24]^f[y>>>16&255]^h[d>>>8&255]^l[255&p]^t[m++],u=c[y>>>24]^f[d>>>16&255]^h[p>>>8&255]^l[255&b]^t[m++],d=o,p=a,b=s,y=u;return o=(n[d>>>24]<<24|n[p>>>16&255]<<16|n[b>>>8&255]<<8|n[255&y])^t[m++],a=(n[p>>>24]<<24|n[b>>>16&255]<<16|n[y>>>8&255]<<8|n[255&d])^t[m++],s=(n[b>>>24]<<24|n[y>>>16&255]<<16|n[d>>>8&255]<<8|n[255&p])^t[m++],u=(n[y>>>24]<<24|n[d>>>16&255]<<16|n[p>>>8&255]<<8|n[255&b])^t[m++],[o>>>=0,a>>>=0,s>>>=0,u>>>=0]}var s=[0,1,2,4,8,16,32,64,128,27,54],u=function(){for(var e=new Array(256),t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;for(var r=[],n=[],i=[[],[],[],[]],o=[[],[],[],[]],a=0,s=0,u=0;u<256;++u){var c=s^s<<1^s<<2^s<<3^s<<4;c=c>>>8^255&c^99,r[a]=c,n[c]=a;var f=e[a],h=e[f],l=e[h],d=257*e[c]^16843008*c;i[0][a]=d<<24|d>>>8,i[1][a]=d<<16|d>>>16,i[2][a]=d<<8|d>>>24,i[3][a]=d,d=16843009*l^65537*h^257*f^16843008*a,o[0][c]=d<<24|d>>>8,o[1][c]=d<<16|d>>>16,o[2][c]=d<<8|d>>>24,o[3][c]=d,0===a?a=s=1:(a=f^e[e[e[l^f]]],s^=e[e[s]])}return{SBOX:r,INV_SBOX:n,SUB_MIX:i,INV_SUB_MIX:o}}();function c(e){this._key=i(e),this._reset()}c.blockSize=16,c.keySize=32,c.prototype.blockSize=c.blockSize,c.prototype.keySize=c.keySize,c.prototype._reset=function(){for(var e=this._key,t=e.length,r=t+6,n=4*(r+1),i=[],o=0;o>>24,a=u.SBOX[a>>>24]<<24|u.SBOX[a>>>16&255]<<16|u.SBOX[a>>>8&255]<<8|u.SBOX[255&a],a^=s[o/t|0]<<24):t>6&&o%t==4&&(a=u.SBOX[a>>>24]<<24|u.SBOX[a>>>16&255]<<16|u.SBOX[a>>>8&255]<<8|u.SBOX[255&a]),i[o]=i[o-t]^a}for(var c=[],f=0;f>>24]]^u.INV_SUB_MIX[1][u.SBOX[l>>>16&255]]^u.INV_SUB_MIX[2][u.SBOX[l>>>8&255]]^u.INV_SUB_MIX[3][u.SBOX[255&l]]}this._nRounds=r,this._keySchedule=i,this._invKeySchedule=c},c.prototype.encryptBlockRaw=function(e){return a(e=i(e),this._keySchedule,u.SUB_MIX,u.SBOX,this._nRounds)},c.prototype.encryptBlock=function(e){var t=this.encryptBlockRaw(e),r=n.allocUnsafe(16);return r.writeUInt32BE(t[0],0),r.writeUInt32BE(t[1],4),r.writeUInt32BE(t[2],8),r.writeUInt32BE(t[3],12),r},c.prototype.decryptBlock=function(e){var t=(e=i(e))[1];e[1]=e[3],e[3]=t;var r=a(e,this._invKeySchedule,u.INV_SUB_MIX,u.INV_SBOX,this._nRounds),o=n.allocUnsafe(16);return o.writeUInt32BE(r[0],0),o.writeUInt32BE(r[3],4),o.writeUInt32BE(r[2],8),o.writeUInt32BE(r[1],12),o},c.prototype.scrub=function(){o(this._keySchedule),o(this._invKeySchedule),o(this._key)},t.exports.AES=c},{"safe-buffer":290}],57:[function(e,t,r){var n=e("./aes"),i=e("safe-buffer").Buffer,o=e("cipher-base"),a=e("inherits"),s=e("./ghash"),u=e("buffer-xor"),c=e("./incr32");function f(e,t,r,a){o.call(this);var u=i.alloc(4,0);this._cipher=new n.AES(t);var f=this._cipher.encryptBlock(u);this._ghash=new s(f),r=function(e,t,r){if(12===t.length)return e._finID=i.concat([t,i.from([0,0,0,1])]),i.concat([t,i.from([0,0,0,2])]);var n=new s(r),o=t.length,a=o%16;n.update(t),a&&(a=16-a,n.update(i.alloc(a,0))),n.update(i.alloc(8,0));var u=8*o,f=i.alloc(8);f.writeUIntBE(u,0,8),n.update(f),e._finID=n.state;var h=i.from(e._finID);return c(h),h}(this,r,f),this._prev=i.from(r),this._cache=i.allocUnsafe(0),this._secCache=i.allocUnsafe(0),this._decrypt=a,this._alen=0,this._len=0,this._mode=e,this._authTag=null,this._called=!1}a(f,o),f.prototype._update=function(e){if(!this._called&&this._alen){var t=16-this._alen%16;t<16&&(t=i.alloc(t,0),this._ghash.update(t))}this._called=!0;var r=this._mode.encrypt(this,e);return this._decrypt?this._ghash.update(e):this._ghash.update(r),this._len+=e.length,r},f.prototype._final=function(){if(this._decrypt&&!this._authTag)throw new Error("Unsupported state or unable to authenticate data");var e=u(this._ghash.final(8*this._alen,8*this._len),this._cipher.encryptBlock(this._finID));if(this._decrypt&&function(e,t){var r=0;e.length!==t.length&&r++;for(var n=Math.min(e.length,t.length),i=0;i16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t}else if(this.cache.length>=16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t;return null},h.prototype.flush=function(){if(this.cache.length)return this.cache},r.createDecipher=function(e,t){var r=o[e.toLowerCase()];if(!r)throw new TypeError("invalid suite type");var n=c(t,!1,r.key,r.iv);return l(e,n.key,n.iv)},r.createDecipheriv=l},{"./aes":56,"./authCipher":57,"./modes":69,"./streamCipher":72,"cipher-base":86,evp_bytestokey:158,inherits:180,"safe-buffer":290}],60:[function(e,t,r){var n=e("./modes"),i=e("./authCipher"),o=e("safe-buffer").Buffer,a=e("./streamCipher"),s=e("cipher-base"),u=e("./aes"),c=e("evp_bytestokey");function f(e,t,r){s.call(this),this._cache=new l,this._cipher=new u.AES(t),this._prev=o.from(r),this._mode=e,this._autopadding=!0}e("inherits")(f,s),f.prototype._update=function(e){var t,r;this._cache.add(e);for(var n=[];t=this._cache.get();)r=this._mode.encrypt(this,t),n.push(r);return o.concat(n)};var h=o.alloc(16,16);function l(){this.cache=o.allocUnsafe(0)}function d(e,t,r){var s=n[e.toLowerCase()];if(!s)throw new TypeError("invalid suite type");if("string"==typeof t&&(t=o.from(t)),t.length!==s.key/8)throw new TypeError("invalid key length "+t.length);if("string"==typeof r&&(r=o.from(r)),"GCM"!==s.mode&&r.length!==s.iv)throw new TypeError("invalid iv length "+r.length);return"stream"===s.type?new a(s.module,t,r):"auth"===s.type?new i(s.module,t,r):new f(s.module,t,r)}f.prototype._final=function(){var e=this._cache.flush();if(this._autopadding)return e=this._mode.encrypt(this,e),this._cipher.scrub(),e;if(!e.equals(h))throw this._cipher.scrub(),new Error("data not multiple of block length")},f.prototype.setAutoPadding=function(e){return this._autopadding=!!e,this},l.prototype.add=function(e){this.cache=o.concat([this.cache,e])},l.prototype.get=function(){if(this.cache.length>15){var e=this.cache.slice(0,16);return this.cache=this.cache.slice(16),e}return null},l.prototype.flush=function(){for(var e=16-this.cache.length,t=o.allocUnsafe(e),r=-1;++r>>0,0),t.writeUInt32BE(e[1]>>>0,4),t.writeUInt32BE(e[2]>>>0,8),t.writeUInt32BE(e[3]>>>0,12),t}function a(e){this.h=e,this.state=n.alloc(16,0),this.cache=n.allocUnsafe(0)}a.prototype.ghash=function(e){for(var t=-1;++t0;t--)n[t]=n[t]>>>1|(1&n[t-1])<<31;n[0]=n[0]>>>1,r&&(n[0]=n[0]^225<<24)}this.state=o(i)},a.prototype.update=function(e){var t;for(this.cache=n.concat([this.cache,e]);this.cache.length>=16;)t=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(t)},a.prototype.final=function(e,t){return this.cache.length&&this.ghash(n.concat([this.cache,i],16)),this.ghash(o([0,e,0,t])),this.state},t.exports=a},{"safe-buffer":290}],62:[function(e,t,r){t.exports=function(e){for(var t,r=e.length;r--;){if(255!==(t=e.readUInt8(r))){t++,e.writeUInt8(t,r);break}e.writeUInt8(0,r)}}},{}],63:[function(e,t,r){var n=e("buffer-xor");r.encrypt=function(e,t){var r=n(t,e._prev);return e._prev=e._cipher.encryptBlock(r),e._prev},r.decrypt=function(e,t){var r=e._prev;e._prev=t;var i=e._cipher.decryptBlock(t);return n(i,r)}},{"buffer-xor":83}],64:[function(e,t,r){var n=e("safe-buffer").Buffer,i=e("buffer-xor");function o(e,t,r){var o=t.length,a=i(t,e._cache);return e._cache=e._cache.slice(o),e._prev=n.concat([e._prev,r?t:a]),a}r.encrypt=function(e,t,r){for(var i,a=n.allocUnsafe(0);t.length;){if(0===e._cache.length&&(e._cache=e._cipher.encryptBlock(e._prev),e._prev=n.allocUnsafe(0)),!(e._cache.length<=t.length)){a=n.concat([a,o(e,t,r)]);break}i=e._cache.length,a=n.concat([a,o(e,t.slice(0,i),r)]),t=t.slice(i)}return a}},{"buffer-xor":83,"safe-buffer":290}],65:[function(e,t,r){var n=e("safe-buffer").Buffer;function i(e,t,r){for(var n,i,a=-1,s=0;++a<8;)n=t&1<<7-a?128:0,s+=(128&(i=e._cipher.encryptBlock(e._prev)[0]^n))>>a%8,e._prev=o(e._prev,r?n:i);return s}function o(e,t){var r=e.length,i=-1,o=n.allocUnsafe(e.length);for(e=n.concat([e,n.from([t])]);++i>7;return o}r.encrypt=function(e,t,r){for(var o=t.length,a=n.allocUnsafe(o),s=-1;++s=0||!r.umod(e.prime1)||!r.umod(e.prime2);)r=new n(i(t));return r}t.exports=o,o.getr=a}).call(this,e("buffer").Buffer)},{"bn.js":53,buffer:84,randombytes:270}],77:[function(e,t,r){t.exports=e("./browser/algorithms.json")},{"./browser/algorithms.json":78}],78:[function(e,t,r){t.exports={sha224WithRSAEncryption:{sign:"rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},"RSA-SHA224":{sign:"ecdsa/rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},sha256WithRSAEncryption:{sign:"rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},"RSA-SHA256":{sign:"ecdsa/rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},sha384WithRSAEncryption:{sign:"rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},"RSA-SHA384":{sign:"ecdsa/rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},sha512WithRSAEncryption:{sign:"rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA512":{sign:"ecdsa/rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA1":{sign:"rsa",hash:"sha1",id:"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{sign:"ecdsa",hash:"sha1",id:""},sha256:{sign:"ecdsa",hash:"sha256",id:""},sha224:{sign:"ecdsa",hash:"sha224",id:""},sha384:{sign:"ecdsa",hash:"sha384",id:""},sha512:{sign:"ecdsa",hash:"sha512",id:""},"DSA-SHA":{sign:"dsa",hash:"sha1",id:""},"DSA-SHA1":{sign:"dsa",hash:"sha1",id:""},DSA:{sign:"dsa",hash:"sha1",id:""},"DSA-WITH-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-WITH-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-WITH-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-WITH-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-RIPEMD160":{sign:"dsa",hash:"rmd160",id:""},ripemd160WithRSA:{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},"RSA-RIPEMD160":{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},md5WithRSAEncryption:{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"},"RSA-MD5":{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"}}},{}],79:[function(e,t,r){t.exports={"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"}},{}],80:[function(e,t,r){(function(r){var n=e("create-hash"),i=e("stream"),o=e("inherits"),a=e("./sign"),s=e("./verify"),u=e("./algorithms.json");function c(e){i.Writable.call(this);var t=u[e];if(!t)throw new Error("Unknown message digest");this._hashType=t.hash,this._hash=n(t.hash),this._tag=t.id,this._signType=t.sign}function f(e){i.Writable.call(this);var t=u[e];if(!t)throw new Error("Unknown message digest");this._hash=n(t.hash),this._tag=t.id,this._signType=t.sign}function h(e){return new c(e)}function l(e){return new f(e)}Object.keys(u).forEach(function(e){u[e].id=new r(u[e].id,"hex"),u[e.toLowerCase()]=u[e]}),o(c,i.Writable),c.prototype._write=function(e,t,r){this._hash.update(e),r()},c.prototype.update=function(e,t){return"string"==typeof e&&(e=new r(e,t)),this._hash.update(e),this},c.prototype.sign=function(e,t){this.end();var r=this._hash.digest(),n=a(r,e,this._hashType,this._signType,this._tag);return t?n.toString(t):n},o(f,i.Writable),f.prototype._write=function(e,t,r){this._hash.update(e),r()},f.prototype.update=function(e,t){return"string"==typeof e&&(e=new r(e,t)),this._hash.update(e),this},f.prototype.verify=function(e,t,n){"string"==typeof t&&(t=new r(t,n)),this.end();var i=this._hash.digest();return s(t,i,e,this._signType,this._tag)},t.exports={Sign:h,Verify:l,createSign:h,createVerify:l}}).call(this,e("buffer").Buffer)},{"./algorithms.json":78,"./sign":81,"./verify":82,buffer:84,"create-hash":91,inherits:180,stream:311}],81:[function(e,t,r){(function(r){var n=e("create-hmac"),i=e("browserify-rsa"),o=e("elliptic").ec,a=e("bn.js"),s=e("parse-asn1"),u=e("./curves.json");function c(e,t,i,o){if((e=new r(e.toArray())).length0&&r.ishrn(n),r}function h(e,t,i){var o,a;do{for(o=new r(0);8*o.length=t)throw new Error("invalid sig")}t.exports=function(e,t,u,c,f){var h=o(u);if("ec"===h.type){if("ecdsa"!==c&&"ecdsa/rsa"!==c)throw new Error("wrong public key type");return function(e,t,r){var n=a[r.data.algorithm.curve.join(".")];if(!n)throw new Error("unknown curve "+r.data.algorithm.curve.join("."));var o=new i(n),s=r.data.subjectPrivateKey.data;return o.verify(t,e,s)}(e,t,h)}if("dsa"===h.type){if("dsa"!==c)throw new Error("wrong public key type");return function(e,t,r){var i=r.data.p,a=r.data.q,u=r.data.g,c=r.data.pub_key,f=o.signature.decode(e,"der"),h=f.s,l=f.r;s(h,a),s(l,a);var d=n.mont(i),p=h.invm(a);return 0===u.toRed(d).redPow(new n(t).mul(p).mod(a)).fromRed().mul(c.toRed(d).redPow(l.mul(p).mod(a)).fromRed()).mod(i).mod(a).cmp(l)}(e,t,h)}if("rsa"!==c&&"ecdsa/rsa"!==c)throw new Error("wrong public key type");t=r.concat([f,t]);for(var l=h.modulus.byteLength(),d=[1],p=0;t.length+d.length+2o)throw new RangeError("Invalid typed array length");var t=new Uint8Array(e);return t.__proto__=s.prototype,t}function s(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return f(e)}return u(e,t,r)}function u(e,t,r){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return F(e)?function(e,t,r){if(t<0||e.byteLength=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function d(e,t){if(s.isBuffer(e))return e.length;if(q(e)||F(e))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return L(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return O(e).length;default:if(n)return L(e).length;t=(""+t).toLowerCase(),n=!0}}function p(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function b(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),H(r=+r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=s.from(t,n)),s.isBuffer(t))return 0===t.length?-1:y(e,t,r,n,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):y(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function y(e,t,r,n,i){var o,a=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,r/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(i){var f=-1;for(o=r;os&&(r=s-u),o=r;o>=0;o--){for(var h=!0,l=0;li&&(n=i):n=i;var o=t.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var a=0;a>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function E(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function x(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i239?4:c>223?3:c>191?2:1;if(i+h<=r)switch(h){case 1:c<128&&(f=c);break;case 2:128==(192&(o=e[i+1]))&&(u=(31&c)<<6|63&o)>127&&(f=u);break;case 3:o=e[i+1],a=e[i+2],128==(192&o)&&128==(192&a)&&(u=(15&c)<<12|(63&o)<<6|63&a)>2047&&(u<55296||u>57343)&&(f=u);break;case 4:o=e[i+1],a=e[i+2],s=e[i+3],128==(192&o)&&128==(192&a)&&128==(192&s)&&(u=(15&c)<<18|(63&o)<<12|(63&a)<<6|63&s)>65535&&u<1114112&&(f=u)}null===f?(f=65533,h=1):f>65535&&(f-=65536,n.push(f>>>10&1023|55296),f=56320|1023&f),n.push(f),i+=h}return function(e){var t=e.length;if(t<=k)return String.fromCharCode.apply(String,e);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return I(this,t,r);case"utf8":case"utf-8":return x(this,t,r);case"ascii":return S(this,t,r);case"latin1":case"binary":return M(this,t,r);case"base64":return E(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}.apply(this,arguments)},s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.prototype.inspect=function(){var e="",t=r.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},s.prototype.compare=function(e,t,r,n,i){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;for(var o=(i>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0),u=Math.min(o,a),c=this.slice(n,i),f=e.slice(t,r),h=0;h>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return m(this,e,t,r);case"utf8":case"utf-8":return v(this,e,t,r);case"ascii":return g(this,e,t,r);case"latin1":case"binary":return w(this,e,t,r);case"base64":return _(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var k=4096;function S(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;in)&&(r=n);for(var i="",o=t;or)throw new RangeError("Trying to access beyond buffer length")}function j(e,t,r,n,i,o){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function B(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function P(e,t,r,n,o){return t=+t,r>>>=0,o||B(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function C(e,t,r,n,o){return t=+t,r>>>=0,o||B(e,0,r,8),i.write(e,t,r,n,52,8),r+8}s.prototype.slice=function(e,t){var r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||U(e,t,this.length);for(var n=this[e],i=1,o=0;++o>>=0,t>>>=0,r||U(e,t,this.length);for(var n=this[e+--t],i=1;t>0&&(i*=256);)n+=this[e+--t]*i;return n},s.prototype.readUInt8=function(e,t){return e>>>=0,t||U(e,1,this.length),this[e]},s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||U(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||U(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||U(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||U(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);for(var n=this[e],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*t)),n},s.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);for(var n=t,i=1,o=this[e+--n];n>0&&(i*=256);)o+=this[e+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*t)),o},s.prototype.readInt8=function(e,t){return e>>>=0,t||U(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||U(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt16BE=function(e,t){e>>>=0,t||U(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||U(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||U(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readFloatLE=function(e,t){return e>>>=0,t||U(e,4,this.length),i.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||U(e,4,this.length),i.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||U(e,8,this.length),i.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||U(e,8,this.length),i.read(this,e,!1,52,8)},s.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t>>>=0,r>>>=0,n)||j(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[t]=255&e;++o>>=0,r>>>=0,n)||j(this,e,t,r,Math.pow(2,8*r)-1,0);var i=r-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r},s.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);j(this,e,t,r,i-1,-i)}var o=0,a=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+r},s.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);j(this,e,t,r,i-1,-i)}var o=r-1,a=1,s=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a>>0)-s&255;return t+r},s.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeFloatLE=function(e,t,r){return P(this,e,t,!0,r)},s.prototype.writeFloatBE=function(e,t,r){return P(this,e,t,!1,r)},s.prototype.writeDoubleLE=function(e,t,r){return C(this,e,t,!0,r)},s.prototype.writeDoubleBE=function(e,t,r){return C(this,e,t,!1,r)},s.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--i)e[i+t]=this[i+r];else if(o<1e3)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function O(e){return n.toByteArray(function(e){if((e=e.trim().replace(N,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function D(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function F(e){return e instanceof ArrayBuffer||null!=e&&null!=e.constructor&&"ArrayBuffer"===e.constructor.name&&"number"==typeof e.byteLength}function q(e){return"function"==typeof ArrayBuffer.isView&&ArrayBuffer.isView(e)}function H(e){return e!=e}},{"base64-js":51,ieee754:178}],85:[function(e,t,r){t.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}},{}],86:[function(e,t,r){var n=e("safe-buffer").Buffer,i=e("stream").Transform,o=e("string_decoder").StringDecoder;function a(e){i.call(this),this.hashMode="string"==typeof e,this.hashMode?this[e]=this._finalOrDigest:this.final=this._finalOrDigest,this._final&&(this.__final=this._final,this._final=null),this._decoder=null,this._encoding=null}e("inherits")(a,i),a.prototype.update=function(e,t,r){"string"==typeof e&&(e=n.from(e,t));var i=this._update(e);return this.hashMode?this:(r&&(i=this._toString(i,r)),i)},a.prototype.setAutoPadding=function(){},a.prototype.getAuthTag=function(){throw new Error("trying to get auth tag in unsupported state")},a.prototype.setAuthTag=function(){throw new Error("trying to set auth tag in unsupported state")},a.prototype.setAAD=function(){throw new Error("trying to set aad in unsupported state")},a.prototype._transform=function(e,t,r){var n;try{this.hashMode?this._update(e):this.push(this._update(e))}catch(e){n=e}finally{r(n)}},a.prototype._flush=function(e){var t;try{this.push(this.__final())}catch(e){t=e}e(t)},a.prototype._finalOrDigest=function(e){var t=this.__final()||n.alloc(0);return e&&(t=this._toString(t,e,!0)),t},a.prototype._toString=function(e,t,r){if(this._decoder||(this._decoder=new o(t),this._encoding=t),this._encoding!==t)throw new Error("can't switch encodings");var n=this._decoder.write(e);return r&&(n+=this._decoder.end()),n},t.exports=a},{inherits:180,"safe-buffer":290,stream:311,string_decoder:317}],87:[function(e,t,r){(function(e){var r=function(){"use strict";function t(e,t){return null!=t&&e instanceof t}var r,n,i;try{r=Map}catch(e){r=function(){}}try{n=Set}catch(e){n=function(){}}try{i=Promise}catch(e){i=function(){}}function o(a,u,c,f,h){"object"==typeof u&&(c=u.depth,f=u.prototype,h=u.includeNonEnumerable,u=u.circular);var l=[],d=[],p=void 0!==e;return void 0===u&&(u=!0),void 0===c&&(c=1/0),function a(c,b){if(null===c)return null;if(0===b)return c;var y,m;if("object"!=typeof c)return c;if(t(c,r))y=new r;else if(t(c,n))y=new n;else if(t(c,i))y=new i(function(e,t){c.then(function(t){e(a(t,b-1))},function(e){t(a(e,b-1))})});else if(o.__isArray(c))y=[];else if(o.__isRegExp(c))y=new RegExp(c.source,s(c)),c.lastIndex&&(y.lastIndex=c.lastIndex);else if(o.__isDate(c))y=new Date(c.getTime());else{if(p&&e.isBuffer(c))return y=e.allocUnsafe?e.allocUnsafe(c.length):new e(c.length),c.copy(y),y;t(c,Error)?y=Object.create(c):void 0===f?(m=Object.getPrototypeOf(c),y=Object.create(m)):(y=Object.create(f),m=f)}if(u){var v=l.indexOf(c);if(-1!=v)return d[v];l.push(c),d.push(y)}for(var g in t(c,r)&&c.forEach(function(e,t){var r=a(t,b-1),n=a(e,b-1);y.set(r,n)}),t(c,n)&&c.forEach(function(e){var t=a(e,b-1);y.add(t)}),c){var w;m&&(w=Object.getOwnPropertyDescriptor(m,g)),w&&null==w.set||(y[g]=a(c[g],b-1))}if(Object.getOwnPropertySymbols){var _=Object.getOwnPropertySymbols(c);for(g=0;g<_.length;g++){var A=_[g];(!(x=Object.getOwnPropertyDescriptor(c,A))||x.enumerable||h)&&(y[A]=a(c[A],b-1),x.enumerable||Object.defineProperty(y,A,{enumerable:!1}))}}if(h){var E=Object.getOwnPropertyNames(c);for(g=0;g>>2),a=0,s=0;a>5]|=128<>>9<<4)]=t;for(var r=1732584193,n=-271733879,i=-1732584194,o=271733878,h=0;h>>32-s,r);var a,s}function a(e,t,r,n,i,a,s){return o(t&r|~t&n,e,t,i,a,s)}function s(e,t,r,n,i,a,s){return o(t&n|r&~n,e,t,i,a,s)}function u(e,t,r,n,i,a,s){return o(t^r^n,e,t,i,a,s)}function c(e,t,r,n,i,a,s){return o(r^(t|~n),e,t,i,a,s)}function f(e,t){var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}t.exports=function(e){return n(e,i)}},{"./make-hash":92}],94:[function(e,t,r){"use strict";var n=e("inherits"),i=e("./legacy"),o=e("cipher-base"),a=e("safe-buffer").Buffer,s=e("create-hash/md5"),u=e("ripemd160"),c=e("sha.js"),f=a.alloc(128);function h(e,t){o.call(this,"digest"),"string"==typeof t&&(t=a.from(t));var r="sha512"===e||"sha384"===e?128:64;(this._alg=e,this._key=t,t.length>r)?t=("rmd160"===e?new u:c(e)).update(t).digest():t.lengths?t=e(t):t.length-1};f.prototype.append=function(e,t){e=s(e),t=u(t);var r=this.map[e];this.map[e]=r?r+","+t:t},f.prototype.delete=function(e){delete this.map[s(e)]},f.prototype.get=function(e){return e=s(e),this.has(e)?this.map[e]:null},f.prototype.has=function(e){return this.map.hasOwnProperty(s(e))},f.prototype.set=function(e,t){this.map[s(e)]=u(t)},f.prototype.forEach=function(e,t){for(var r in this.map)this.map.hasOwnProperty(r)&&e.call(t,this.map[r],r,this)},f.prototype.keys=function(){var e=[];return this.forEach(function(t,r){e.push(r)}),c(e)},f.prototype.values=function(){var e=[];return this.forEach(function(t){e.push(t)}),c(e)},f.prototype.entries=function(){var e=[];return this.forEach(function(t,r){e.push([r,t])}),c(e)},t.iterable&&(f.prototype[Symbol.iterator]=f.prototype.entries);var o=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];y.prototype.clone=function(){return new y(this,{body:this._bodyInit})},b.call(y.prototype),b.call(v.prototype),v.prototype.clone=function(){return new v(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new f(this.headers),url:this.url})},v.error=function(){var e=new v(null,{status:0,statusText:""});return e.type="error",e};var a=[301,302,303,307,308];v.redirect=function(e,t){if(-1===a.indexOf(t))throw new RangeError("Invalid status code");return new v(null,{status:t,headers:{location:e}})},e.Headers=f,e.Request=y,e.Response=v,e.fetch=function(e,r){return new Promise(function(n,i){var o=new y(e,r),a=new XMLHttpRequest;a.onload=function(){var e,t,r={status:a.status,statusText:a.statusText,headers:(e=a.getAllResponseHeaders()||"",t=new f,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach(function(e){var r=e.split(":"),n=r.shift().trim();if(n){var i=r.join(":").trim();t.append(n,i)}}),t)};r.url="responseURL"in a?a.responseURL:r.headers.get("X-Request-URL");var i="response"in a?a.response:a.responseText;n(new v(i,r))},a.onerror=function(){i(new TypeError("Network request failed"))},a.ontimeout=function(){i(new TypeError("Network request failed"))},a.open(o.method,o.url,!0),"include"===o.credentials?a.withCredentials=!0:"omit"===o.credentials&&(a.withCredentials=!1),"responseType"in a&&t.blob&&(a.responseType="blob"),o.headers.forEach(function(e,t){a.setRequestHeader(t,e)}),a.send(void 0===o._bodyInit?null:o._bodyInit)})},e.fetch.polyfill=!0}function s(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function u(e){return"string"!=typeof e&&(e=String(e)),e}function c(e){var r={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return t.iterable&&(r[Symbol.iterator]=function(){return r}),r}function f(e){this.map={},e instanceof f?e.forEach(function(e,t){this.append(t,e)},this):Array.isArray(e)?e.forEach(function(e){this.append(e[0],e[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}function h(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function l(e){return new Promise(function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}})}function d(e){var t=new FileReader,r=l(t);return t.readAsArrayBuffer(e),r}function p(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function b(){return this.bodyUsed=!1,this._initBody=function(e){if(this._bodyInit=e,e)if("string"==typeof e)this._bodyText=e;else if(t.blob&&Blob.prototype.isPrototypeOf(e))this._bodyBlob=e;else if(t.formData&&FormData.prototype.isPrototypeOf(e))this._bodyFormData=e;else if(t.searchParams&&URLSearchParams.prototype.isPrototypeOf(e))this._bodyText=e.toString();else if(t.arrayBuffer&&t.blob&&n(e))this._bodyArrayBuffer=p(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer]);else{if(!t.arrayBuffer||!ArrayBuffer.prototype.isPrototypeOf(e)&&!i(e))throw new Error("unsupported BodyInit type");this._bodyArrayBuffer=p(e)}else this._bodyText="";this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):t.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},t.blob&&(this.blob=function(){var e=h(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?h(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(d)}),this.text=function(){var e,t,r,n=h(this);if(n)return n;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,r=l(t),t.readAsText(e),r;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),r=new Array(t.length),n=0;n-1?n:r),this.mode=t.mode||this.mode||null,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&i)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(i)}function m(e){var t=new FormData;return e.trim().split("&").forEach(function(e){if(e){var r=e.split("="),n=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");t.append(decodeURIComponent(n),decodeURIComponent(i))}}),t}function v(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new f(t.headers),this.url=t.url||"",this._initBody(e)}}(void 0!==e?e:this)}).call(n,void 0);var i=n.fetch;i.Response=n.Response,i.Request=n.Request,i.Headers=n.Headers;"object"==typeof t&&t.exports&&(t.exports=i,t.exports.default=i)},{}],97:[function(e,t,r){"use strict";r.randomBytes=r.rng=r.pseudoRandomBytes=r.prng=e("randombytes"),r.createHash=r.Hash=e("create-hash"),r.createHmac=r.Hmac=e("create-hmac");var n=e("browserify-sign/algos"),i=Object.keys(n),o=["sha1","sha224","sha256","sha384","sha512","md5","rmd160"].concat(i);r.getHashes=function(){return o};var a=e("pbkdf2");r.pbkdf2=a.pbkdf2,r.pbkdf2Sync=a.pbkdf2Sync;var s=e("browserify-cipher");r.Cipher=s.Cipher,r.createCipher=s.createCipher,r.Cipheriv=s.Cipheriv,r.createCipheriv=s.createCipheriv,r.Decipher=s.Decipher,r.createDecipher=s.createDecipher,r.Decipheriv=s.Decipheriv,r.createDecipheriv=s.createDecipheriv,r.getCiphers=s.getCiphers,r.listCiphers=s.listCiphers;var u=e("diffie-hellman");r.DiffieHellmanGroup=u.DiffieHellmanGroup,r.createDiffieHellmanGroup=u.createDiffieHellmanGroup,r.getDiffieHellman=u.getDiffieHellman,r.createDiffieHellman=u.createDiffieHellman,r.DiffieHellman=u.DiffieHellman;var c=e("browserify-sign");r.createSign=c.createSign,r.Sign=c.Sign,r.createVerify=c.createVerify,r.Verify=c.Verify,r.createECDH=e("create-ecdh");var f=e("public-encrypt");r.publicEncrypt=f.publicEncrypt,r.privateEncrypt=f.privateEncrypt,r.publicDecrypt=f.publicDecrypt,r.privateDecrypt=f.privateDecrypt;var h=e("randomfill");r.randomFill=h.randomFill,r.randomFillSync=h.randomFillSync,r.createCredentials=function(){throw new Error(["sorry, createCredentials is not implemented yet","we accept pull requests","https://github.com/crypto-browserify/crypto-browserify"].join("\n"))},r.constants={DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,NPN_ENABLED:1,ALPN_ENABLED:1,RSA_PKCS1_PADDING:1,RSA_SSLV23_PADDING:2,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,POINT_CONVERSION_COMPRESSED:2,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(e,t,r){"use strict";var n=new RegExp("%[a-f0-9]{2}","gi"),i=new RegExp("(%[a-f0-9]{2})+","gi");function o(e,t){try{return decodeURIComponent(e.join(""))}catch(e){}if(1===e.length)return e;t=t||1;var r=e.slice(0,t),n=e.slice(t);return Array.prototype.concat.call([],o(r),o(n))}function a(e){try{return decodeURIComponent(e)}catch(i){for(var t=e.match(n),r=1;r0;n--)t+=this._buffer(e,t),r+=this._flushBuffer(i,r);return t+=this._buffer(e,t),i},i.prototype.final=function(e){var t,r;return e&&(t=this.update(e)),r="encrypt"===this.type?this._finalEncrypt():this._finalDecrypt(),t?t.concat(r):r},i.prototype._pad=function(e,t){if(0===t)return!1;for(;t>>1];r=a.r28shl(r,s),i=a.r28shl(i,s),a.pc2(r,i,e.keys,o)}},u.prototype._update=function(e,t,r,n){var i=this._desState,o=a.readUInt32BE(e,t),s=a.readUInt32BE(e,t+4);a.ip(o,s,i.tmp,0),o=i.tmp[0],s=i.tmp[1],"encrypt"===this.type?this._encrypt(i,o,s,i.tmp,0):this._decrypt(i,o,s,i.tmp,0),o=i.tmp[0],s=i.tmp[1],a.writeUInt32BE(r,o,n),a.writeUInt32BE(r,s,n+4)},u.prototype._pad=function(e,t){for(var r=e.length-t,n=t;n>>0,o=l}a.rip(s,o,n,i)},u.prototype._decrypt=function(e,t,r,n,i){for(var o=r,s=t,u=e.keys.length-2;u>=0;u-=2){var c=e.keys[u],f=e.keys[u+1];a.expand(o,e.tmp,0),c^=e.tmp[0],f^=e.tmp[1];var h=a.substitute(c,f),l=o;o=(s^a.permute(h))>>>0,s=l}a.rip(o,s,n,i)}},{"../des":99,inherits:180,"minimalistic-assert":234}],103:[function(e,t,r){"use strict";var n=e("minimalistic-assert"),i=e("inherits"),o=e("../des"),a=o.Cipher,s=o.DES;function u(e){a.call(this,e);var t=new function(e,t){n.equal(t.length,24,"Invalid key length");var r=t.slice(0,8),i=t.slice(8,16),o=t.slice(16,24);this.ciphers="encrypt"===e?[s.create({type:"encrypt",key:r}),s.create({type:"decrypt",key:i}),s.create({type:"encrypt",key:o})]:[s.create({type:"decrypt",key:o}),s.create({type:"encrypt",key:i}),s.create({type:"decrypt",key:r})]}(this.type,this.options.key);this._edeState=t}i(u,a),t.exports=u,u.create=function(e){return new u(e)},u.prototype._update=function(e,t,r,n){var i=this._edeState;i.ciphers[0]._update(e,t,r,n),i.ciphers[1]._update(r,n,r,n),i.ciphers[2]._update(r,n,r,n)},u.prototype._pad=s.prototype._pad,u.prototype._unpad=s.prototype._unpad},{"../des":99,inherits:180,"minimalistic-assert":234}],104:[function(e,t,r){"use strict";r.readUInt32BE=function(e,t){return(e[0+t]<<24|e[1+t]<<16|e[2+t]<<8|e[3+t])>>>0},r.writeUInt32BE=function(e,t,r){e[0+r]=t>>>24,e[1+r]=t>>>16&255,e[2+r]=t>>>8&255,e[3+r]=255&t},r.ip=function(e,t,r,n){for(var i=0,o=0,a=6;a>=0;a-=2){for(var s=0;s<=24;s+=8)i<<=1,i|=t>>>s+a&1;for(s=0;s<=24;s+=8)i<<=1,i|=e>>>s+a&1}for(a=6;a>=0;a-=2){for(s=1;s<=25;s+=8)o<<=1,o|=t>>>s+a&1;for(s=1;s<=25;s+=8)o<<=1,o|=e>>>s+a&1}r[n+0]=i>>>0,r[n+1]=o>>>0},r.rip=function(e,t,r,n){for(var i=0,o=0,a=0;a<4;a++)for(var s=24;s>=0;s-=8)i<<=1,i|=t>>>s+a&1,i<<=1,i|=e>>>s+a&1;for(a=4;a<8;a++)for(s=24;s>=0;s-=8)o<<=1,o|=t>>>s+a&1,o<<=1,o|=e>>>s+a&1;r[n+0]=i>>>0,r[n+1]=o>>>0},r.pc1=function(e,t,r,n){for(var i=0,o=0,a=7;a>=5;a--){for(var s=0;s<=24;s+=8)i<<=1,i|=t>>s+a&1;for(s=0;s<=24;s+=8)i<<=1,i|=e>>s+a&1}for(s=0;s<=24;s+=8)i<<=1,i|=t>>s+a&1;for(a=1;a<=3;a++){for(s=0;s<=24;s+=8)o<<=1,o|=t>>s+a&1;for(s=0;s<=24;s+=8)o<<=1,o|=e>>s+a&1}for(s=0;s<=24;s+=8)o<<=1,o|=e>>s+a&1;r[n+0]=i>>>0,r[n+1]=o>>>0},r.r28shl=function(e,t){return e<>>28-t};var n=[14,11,17,4,27,23,25,0,13,22,7,18,5,9,16,24,2,20,12,21,1,8,15,26,15,4,25,19,9,1,26,16,5,11,23,8,12,7,17,0,22,3,10,14,6,20,27,24];r.pc2=function(e,t,r,i){for(var o=0,a=0,s=n.length>>>1,u=0;u>>n[u]&1;for(u=s;u>>n[u]&1;r[i+0]=o>>>0,r[i+1]=a>>>0},r.expand=function(e,t,r){var n=0,i=0;n=(1&e)<<5|e>>>27;for(var o=23;o>=15;o-=4)n<<=6,n|=e>>>o&63;for(o=11;o>=3;o-=4)i|=e>>>o&63,i<<=6;i|=(31&e)<<1|e>>>31,t[r+0]=n>>>0,t[r+1]=i>>>0};var i=[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];r.substitute=function(e,t){for(var r=0,n=0;n<4;n++){r<<=4,r|=i[64*n+(e>>>18-6*n&63)]}for(n=0;n<4;n++){r<<=4,r|=i[256+64*n+(t>>>18-6*n&63)]}return r>>>0};var o=[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];r.permute=function(e){for(var t=0,r=0;r>>o[r]&1;return t>>>0},r.padSplit=function(e,t,r){for(var n=e.toString(2);n.lengthe;)r.ishrn(1);if(r.isEven()&&r.iadd(s),r.testn(1)||r.iadd(u),t.cmp(u)){if(!t.cmp(c))for(;r.mod(f).cmp(h);)r.iadd(d)}else for(;r.mod(o).cmp(l);)r.iadd(d);if(y(p=r.shrn(1))&&y(r)&&m(p)&&m(r)&&a.test(p)&&a.test(r))return r}}},{"bn.js":53,"miller-rabin":233,randombytes:270}],108:[function(e,t,r){t.exports={modp1:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},modp2:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},modp5:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},modp14:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},modp15:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},modp16:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},modp17:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},modp18:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"}}},{}],109:[function(e,t,r){"use strict";var n=r;n.version=e("../package.json").version,n.utils=e("./elliptic/utils"),n.rand=e("brorand"),n.curve=e("./elliptic/curve"),n.curves=e("./elliptic/curves"),n.ec=e("./elliptic/ec"),n.eddsa=e("./elliptic/eddsa")},{"../package.json":124,"./elliptic/curve":112,"./elliptic/curves":115,"./elliptic/ec":116,"./elliptic/eddsa":119,"./elliptic/utils":123,brorand:54}],110:[function(e,t,r){"use strict";var n=e("bn.js"),i=e("../../elliptic").utils,o=i.getNAF,a=i.getJSF,s=i.assert;function u(e,t){this.type=e,this.p=new n(t.p,16),this.red=t.prime?n.red(t.prime):n.mont(this.p),this.zero=new n(0).toRed(this.red),this.one=new n(1).toRed(this.red),this.two=new n(2).toRed(this.red),this.n=t.n&&new n(t.n,16),this.g=t.g&&this.pointFromJSON(t.g,t.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4);var r=this.n&&this.p.div(this.n);!r||r.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}function c(e,t){this.curve=e,this.type=t,this.precomputed=null}t.exports=u,u.prototype.point=function(){throw new Error("Not implemented")},u.prototype.validate=function(){throw new Error("Not implemented")},u.prototype._fixedNafMul=function(e,t){s(e.precomputed);var r=e._getDoubles(),n=o(t,1),i=(1<=u;t--)c=(c<<1)+n[t];a.push(c)}for(var f=this.jpoint(null,null,null),h=this.jpoint(null,null,null),l=i;l>0;l--){for(u=0;u=0;c--){for(t=0;c>=0&&0===a[c];c--)t++;if(c>=0&&t++,u=u.dblp(t),c<0)break;var f=a[c];s(0!==f),u="affine"===e.type?f>0?u.mixedAdd(i[f-1>>1]):u.mixedAdd(i[-f-1>>1].neg()):f>0?u.add(i[f-1>>1]):u.add(i[-f-1>>1].neg())}return"affine"===e.type?u.toP():u},u.prototype._wnafMulAdd=function(e,t,r,n,i){for(var s=this._wnafT1,u=this._wnafT2,c=this._wnafT3,f=0,h=0;h=1;h-=2){var d=h-1,p=h;if(1===s[d]&&1===s[p]){var b=[t[d],null,null,t[p]];0===t[d].y.cmp(t[p].y)?(b[1]=t[d].add(t[p]),b[2]=t[d].toJ().mixedAdd(t[p].neg())):0===t[d].y.cmp(t[p].y.redNeg())?(b[1]=t[d].toJ().mixedAdd(t[p]),b[2]=t[d].add(t[p].neg())):(b[1]=t[d].toJ().mixedAdd(t[p]),b[2]=t[d].toJ().mixedAdd(t[p].neg()));var y=[-3,-1,-5,-7,0,7,5,1,3],m=a(r[d],r[p]);f=Math.max(m[0].length,f),c[d]=new Array(f),c[p]=new Array(f);for(var v=0;v=0;h--){for(var E=0;h>=0;){var x=!0;for(v=0;v=0&&E++,_=_.dblp(E),h<0)break;for(v=0;v0?k=u[v][S-1>>1]:S<0&&(k=u[v][-S-1>>1].neg()),_="affine"===k.type?_.mixedAdd(k):_.add(k))}}for(h=0;h=Math.ceil((e.bitLength()+1)/t.step)},c.prototype._getDoubles=function(e,t){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i":""},f.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&0===this.y.cmp(this.z)},f.prototype._extDbl=function(){var e=this.x.redSqr(),t=this.y.redSqr(),r=this.z.redSqr();r=r.redIAdd(r);var n=this.curve._mulA(e),i=this.x.redAdd(this.y).redSqr().redISub(e).redISub(t),o=n.redAdd(t),a=o.redSub(r),s=n.redSub(t),u=i.redMul(a),c=o.redMul(s),f=i.redMul(s),h=a.redMul(o);return this.curve.point(u,c,h,f)},f.prototype._projDbl=function(){var e,t,r,n=this.x.redAdd(this.y).redSqr(),i=this.x.redSqr(),o=this.y.redSqr();if(this.curve.twisted){var a=(c=this.curve._mulA(i)).redAdd(o);if(this.zOne)e=n.redSub(i).redSub(o).redMul(a.redSub(this.curve.two)),t=a.redMul(c.redSub(o)),r=a.redSqr().redSub(a).redSub(a);else{var s=this.z.redSqr(),u=a.redSub(s).redISub(s);e=n.redSub(i).redISub(o).redMul(u),t=a.redMul(c.redSub(o)),r=a.redMul(u)}}else{var c=i.redAdd(o);s=this.curve._mulC(this.c.redMul(this.z)).redSqr(),u=c.redSub(s).redSub(s);e=this.curve._mulC(n.redISub(c)).redMul(u),t=this.curve._mulC(c).redMul(i.redISub(o)),r=c.redMul(u)}return this.curve.point(e,t,r)},f.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},f.prototype._extAdd=function(e){var t=this.y.redSub(this.x).redMul(e.y.redSub(e.x)),r=this.y.redAdd(this.x).redMul(e.y.redAdd(e.x)),n=this.t.redMul(this.curve.dd).redMul(e.t),i=this.z.redMul(e.z.redAdd(e.z)),o=r.redSub(t),a=i.redSub(n),s=i.redAdd(n),u=r.redAdd(t),c=o.redMul(a),f=s.redMul(u),h=o.redMul(u),l=a.redMul(s);return this.curve.point(c,f,l,h)},f.prototype._projAdd=function(e){var t,r,n=this.z.redMul(e.z),i=n.redSqr(),o=this.x.redMul(e.x),a=this.y.redMul(e.y),s=this.curve.d.redMul(o).redMul(a),u=i.redSub(s),c=i.redAdd(s),f=this.x.redAdd(this.y).redMul(e.x.redAdd(e.y)).redISub(o).redISub(a),h=n.redMul(u).redMul(f);return this.curve.twisted?(t=n.redMul(c).redMul(a.redSub(this.curve._mulA(o))),r=u.redMul(c)):(t=n.redMul(c).redMul(a.redSub(o)),r=this.curve._mulC(u).redMul(c)),this.curve.point(h,t,r)},f.prototype.add=function(e){return this.isInfinity()?e:e.isInfinity()?this:this.curve.extended?this._extAdd(e):this._projAdd(e)},f.prototype.mul=function(e){return this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve._wnafMul(this,e)},f.prototype.mulAdd=function(e,t,r){return this.curve._wnafMulAdd(1,[this,t],[e,r],2,!1)},f.prototype.jmulAdd=function(e,t,r){return this.curve._wnafMulAdd(1,[this,t],[e,r],2,!0)},f.prototype.normalize=function(){if(this.zOne)return this;var e=this.z.redInvm();return this.x=this.x.redMul(e),this.y=this.y.redMul(e),this.t&&(this.t=this.t.redMul(e)),this.z=this.curve.one,this.zOne=!0,this},f.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},f.prototype.getX=function(){return this.normalize(),this.x.fromRed()},f.prototype.getY=function(){return this.normalize(),this.y.fromRed()},f.prototype.eq=function(e){return this===e||0===this.getX().cmp(e.getX())&&0===this.getY().cmp(e.getY())},f.prototype.eqXToP=function(e){var t=e.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(t))return!0;for(var r=e.clone(),n=this.curve.redN.redMul(this.z);;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(t.redIAdd(n),0===this.x.cmp(t))return!0}return!1},f.prototype.toP=f.prototype.normalize,f.prototype.mixedAdd=f.prototype.add},{"../../elliptic":109,"../curve":112,"bn.js":53,inherits:180}],112:[function(e,t,r){"use strict";var n=r;n.base=e("./base"),n.short=e("./short"),n.mont=e("./mont"),n.edwards=e("./edwards")},{"./base":110,"./edwards":111,"./mont":113,"./short":114}],113:[function(e,t,r){"use strict";var n=e("../curve"),i=e("bn.js"),o=e("inherits"),a=n.base,s=e("../../elliptic").utils;function u(e){a.call(this,"mont",e),this.a=new i(e.a,16).toRed(this.red),this.b=new i(e.b,16).toRed(this.red),this.i4=new i(4).toRed(this.red).redInvm(),this.two=new i(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}function c(e,t,r){a.BasePoint.call(this,e,"projective"),null===t&&null===r?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new i(t,16),this.z=new i(r,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}o(u,a),t.exports=u,u.prototype.validate=function(e){var t=e.normalize().x,r=t.redSqr(),n=r.redMul(t).redAdd(r.redMul(this.a)).redAdd(t);return 0===n.redSqrt().redSqr().cmp(n)},o(c,a.BasePoint),u.prototype.decodePoint=function(e,t){return this.point(s.toArray(e,t),1)},u.prototype.point=function(e,t){return new c(this,e,t)},u.prototype.pointFromJSON=function(e){return c.fromJSON(this,e)},c.prototype.precompute=function(){},c.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},c.fromJSON=function(e,t){return new c(e,t[0],t[1]||e.one)},c.prototype.inspect=function(){return this.isInfinity()?"":""},c.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},c.prototype.dbl=function(){var e=this.x.redAdd(this.z).redSqr(),t=this.x.redSub(this.z).redSqr(),r=e.redSub(t),n=e.redMul(t),i=r.redMul(t.redAdd(this.curve.a24.redMul(r)));return this.curve.point(n,i)},c.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.diffAdd=function(e,t){var r=this.x.redAdd(this.z),n=this.x.redSub(this.z),i=e.x.redAdd(e.z),o=e.x.redSub(e.z).redMul(r),a=i.redMul(n),s=t.z.redMul(o.redAdd(a).redSqr()),u=t.x.redMul(o.redISub(a).redSqr());return this.curve.point(s,u)},c.prototype.mul=function(e){for(var t=e.clone(),r=this,n=this.curve.point(null,null),i=[];0!==t.cmpn(0);t.iushrn(1))i.push(t.andln(1));for(var o=i.length-1;o>=0;o--)0===i[o]?(r=r.diffAdd(n,this),n=n.dbl()):(n=r.diffAdd(n,this),r=r.dbl());return n},c.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.eq=function(e){return 0===this.getX().cmp(e.getX())},c.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},c.prototype.getX=function(){return this.normalize(),this.x.fromRed()}},{"../../elliptic":109,"../curve":112,"bn.js":53,inherits:180}],114:[function(e,t,r){"use strict";var n=e("../curve"),i=e("../../elliptic"),o=e("bn.js"),a=e("inherits"),s=n.base,u=i.utils.assert;function c(e){s.call(this,"short",e),this.a=new o(e.a,16).toRed(this.red),this.b=new o(e.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=0===this.a.fromRed().cmpn(0),this.threeA=0===this.a.fromRed().sub(this.p).cmpn(-3),this.endo=this._getEndomorphism(e),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}function f(e,t,r,n){s.BasePoint.call(this,e,"affine"),null===t&&null===r?(this.x=null,this.y=null,this.inf=!0):(this.x=new o(t,16),this.y=new o(r,16),n&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}function h(e,t,r,n){s.BasePoint.call(this,e,"jacobian"),null===t&&null===r&&null===n?(this.x=this.curve.one,this.y=this.curve.one,this.z=new o(0)):(this.x=new o(t,16),this.y=new o(r,16),this.z=new o(n,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}a(c,s),t.exports=c,c.prototype._getEndomorphism=function(e){if(this.zeroA&&this.g&&this.n&&1===this.p.modn(3)){var t,r;if(e.beta)t=new o(e.beta,16).toRed(this.red);else{var n=this._getEndoRoots(this.p);t=(t=n[0].cmp(n[1])<0?n[0]:n[1]).toRed(this.red)}if(e.lambda)r=new o(e.lambda,16);else{var i=this._getEndoRoots(this.n);0===this.g.mul(i[0]).x.cmp(this.g.x.redMul(t))?r=i[0]:(r=i[1],u(0===this.g.mul(r).x.cmp(this.g.x.redMul(t))))}return{beta:t,lambda:r,basis:e.basis?e.basis.map(function(e){return{a:new o(e.a,16),b:new o(e.b,16)}}):this._getEndoBasis(r)}}},c.prototype._getEndoRoots=function(e){var t=e===this.p?this.red:o.mont(e),r=new o(2).toRed(t).redInvm(),n=r.redNeg(),i=new o(3).toRed(t).redNeg().redSqrt().redMul(r);return[n.redAdd(i).fromRed(),n.redSub(i).fromRed()]},c.prototype._getEndoBasis=function(e){for(var t,r,n,i,a,s,u,c,f,h=this.n.ushrn(Math.floor(this.n.bitLength()/2)),l=e,d=this.n.clone(),p=new o(1),b=new o(0),y=new o(0),m=new o(1),v=0;0!==l.cmpn(0);){var g=d.div(l);c=d.sub(g.mul(l)),f=y.sub(g.mul(p));var w=m.sub(g.mul(b));if(!n&&c.cmp(h)<0)t=u.neg(),r=p,n=c.neg(),i=f;else if(n&&2==++v)break;u=c,d=l,l=c,y=p,p=f,m=b,b=w}a=c.neg(),s=f;var _=n.sqr().add(i.sqr());return a.sqr().add(s.sqr()).cmp(_)>=0&&(a=t,s=r),n.negative&&(n=n.neg(),i=i.neg()),a.negative&&(a=a.neg(),s=s.neg()),[{a:n,b:i},{a:a,b:s}]},c.prototype._endoSplit=function(e){var t=this.endo.basis,r=t[0],n=t[1],i=n.b.mul(e).divRound(this.n),o=r.b.neg().mul(e).divRound(this.n),a=i.mul(r.a),s=o.mul(n.a),u=i.mul(r.b),c=o.mul(n.b);return{k1:e.sub(a).sub(s),k2:u.add(c).neg()}},c.prototype.pointFromX=function(e,t){(e=new o(e,16)).red||(e=e.toRed(this.red));var r=e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(0!==n.redSqr().redSub(r).cmp(this.zero))throw new Error("invalid point");var i=n.fromRed().isOdd();return(t&&!i||!t&&i)&&(n=n.redNeg()),this.point(e,n)},c.prototype.validate=function(e){if(e.inf)return!0;var t=e.x,r=e.y,n=this.a.redMul(t),i=t.redSqr().redMul(t).redIAdd(n).redIAdd(this.b);return 0===r.redSqr().redISub(i).cmpn(0)},c.prototype._endoWnafMulAdd=function(e,t,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,o=0;o":""},f.prototype.isInfinity=function(){return this.inf},f.prototype.add=function(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return this.curve.point(null,null);if(0===this.x.cmp(e.x))return this.curve.point(null,null);var t=this.y.redSub(e.y);0!==t.cmpn(0)&&(t=t.redMul(this.x.redSub(e.x).redInvm()));var r=t.redSqr().redISub(this.x).redISub(e.x),n=t.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},f.prototype.dbl=function(){if(this.inf)return this;var e=this.y.redAdd(this.y);if(0===e.cmpn(0))return this.curve.point(null,null);var t=this.curve.a,r=this.x.redSqr(),n=e.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(t).redMul(n),o=i.redSqr().redISub(this.x.redAdd(this.x)),a=i.redMul(this.x.redSub(o)).redISub(this.y);return this.curve.point(o,a)},f.prototype.getX=function(){return this.x.fromRed()},f.prototype.getY=function(){return this.y.fromRed()},f.prototype.mul=function(e){return e=new o(e,16),this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve.endo?this.curve._endoWnafMulAdd([this],[e]):this.curve._wnafMul(this,e)},f.prototype.mulAdd=function(e,t,r){var n=[this,t],i=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},f.prototype.jmulAdd=function(e,t,r){var n=[this,t],i=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},f.prototype.eq=function(e){return this===e||this.inf===e.inf&&(this.inf||0===this.x.cmp(e.x)&&0===this.y.cmp(e.y))},f.prototype.neg=function(e){if(this.inf)return this;var t=this.curve.point(this.x,this.y.redNeg());if(e&&this.precomputed){var r=this.precomputed,n=function(e){return e.neg()};t.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return t},f.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},a(h,s.BasePoint),c.prototype.jpoint=function(e,t,r){return new h(this,e,t,r)},h.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var e=this.z.redInvm(),t=e.redSqr(),r=this.x.redMul(t),n=this.y.redMul(t).redMul(e);return this.curve.point(r,n)},h.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},h.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(t),i=e.x.redMul(r),o=this.y.redMul(t.redMul(e.z)),a=e.y.redMul(r.redMul(this.z)),s=n.redSub(i),u=o.redSub(a);if(0===s.cmpn(0))return 0!==u.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var c=s.redSqr(),f=c.redMul(s),h=n.redMul(c),l=u.redSqr().redIAdd(f).redISub(h).redISub(h),d=u.redMul(h.redISub(l)).redISub(o.redMul(f)),p=this.z.redMul(e.z).redMul(s);return this.curve.jpoint(l,d,p)},h.prototype.mixedAdd=function(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;var t=this.z.redSqr(),r=this.x,n=e.x.redMul(t),i=this.y,o=e.y.redMul(t).redMul(this.z),a=r.redSub(n),s=i.redSub(o);if(0===a.cmpn(0))return 0!==s.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var u=a.redSqr(),c=u.redMul(a),f=r.redMul(u),h=s.redSqr().redIAdd(c).redISub(f).redISub(f),l=s.redMul(f.redISub(h)).redISub(i.redMul(c)),d=this.z.redMul(a);return this.curve.jpoint(h,l,d)},h.prototype.dblp=function(e){if(0===e)return this;if(this.isInfinity())return this;if(!e)return this.dbl();if(this.curve.zeroA||this.curve.threeA){for(var t=this,r=0;r=0)return!1;if(r.redIAdd(i),0===this.x.cmp(r))return!0}return!1},h.prototype.inspect=function(){return this.isInfinity()?"":""},h.prototype.isInfinity=function(){return 0===this.z.cmpn(0)}},{"../../elliptic":109,"../curve":112,"bn.js":53,inherits:180}],115:[function(e,t,r){"use strict";var n,i=r,o=e("hash.js"),a=e("../elliptic"),s=a.utils.assert;function u(e){"short"===e.type?this.curve=new a.curve.short(e):"edwards"===e.type?this.curve=new a.curve.edwards(e):this.curve=new a.curve.mont(e),this.g=this.curve.g,this.n=this.curve.n,this.hash=e.hash,s(this.g.validate(),"Invalid curve"),s(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}function c(e,t){Object.defineProperty(i,e,{configurable:!0,enumerable:!0,get:function(){var r=new u(t);return Object.defineProperty(i,e,{configurable:!0,enumerable:!0,value:r}),r}})}i.PresetCurve=u,c("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:o.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),c("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:o.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),c("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:o.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),c("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:o.sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),c("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:o.sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),c("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:o.sha256,gRed:!1,g:["9"]}),c("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:o.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});try{n=e("./precomputed/secp256k1")}catch(e){n=void 0}c("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:o.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",n]})},{"../elliptic":109,"./precomputed/secp256k1":122,"hash.js":162}],116:[function(e,t,r){"use strict";var n=e("bn.js"),i=e("hmac-drbg"),o=e("../../elliptic"),a=o.utils.assert,s=e("./key"),u=e("./signature");function c(e){if(!(this instanceof c))return new c(e);"string"==typeof e&&(a(o.curves.hasOwnProperty(e),"Unknown curve "+e),e=o.curves[e]),e instanceof o.curves.PresetCurve&&(e={curve:e}),this.curve=e.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=e.curve.g,this.g.precompute(e.curve.n.bitLength()+1),this.hash=e.hash||e.curve.hash}t.exports=c,c.prototype.keyPair=function(e){return new s(this,e)},c.prototype.keyFromPrivate=function(e,t){return s.fromPrivate(this,e,t)},c.prototype.keyFromPublic=function(e,t){return s.fromPublic(this,e,t)},c.prototype.genKeyPair=function(e){e||(e={});for(var t=new i({hash:this.hash,pers:e.pers,persEnc:e.persEnc||"utf8",entropy:e.entropy||o.rand(this.hash.hmacStrength),entropyEnc:e.entropy&&e.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),a=this.n.sub(new n(2));;){var s=new n(t.generate(r));if(!(s.cmp(a)>0))return s.iaddn(1),this.keyFromPrivate(s)}},c.prototype._truncateToN=function(e,t){var r=8*e.byteLength()-this.n.bitLength();return r>0&&(e=e.ushrn(r)),!t&&e.cmp(this.n)>=0?e.sub(this.n):e},c.prototype.sign=function(e,t,r,o){"object"==typeof r&&(o=r,r=null),o||(o={}),t=this.keyFromPrivate(t,r),e=this._truncateToN(new n(e,16));for(var a=this.n.byteLength(),s=t.getPrivate().toArray("be",a),c=e.toArray("be",a),f=new i({hash:this.hash,entropy:s,nonce:c,pers:o.pers,persEnc:o.persEnc||"utf8"}),h=this.n.sub(new n(1)),l=0;;l++){var d=o.k?o.k(l):new n(f.generate(this.n.byteLength()));if(!((d=this._truncateToN(d,!0)).cmpn(1)<=0||d.cmp(h)>=0)){var p=this.g.mul(d);if(!p.isInfinity()){var b=p.getX(),y=b.umod(this.n);if(0!==y.cmpn(0)){var m=d.invm(this.n).mul(y.mul(t.getPrivate()).iadd(e));if(0!==(m=m.umod(this.n)).cmpn(0)){var v=(p.getY().isOdd()?1:0)|(0!==b.cmp(y)?2:0);return o.canonical&&m.cmp(this.nh)>0&&(m=this.n.sub(m),v^=1),new u({r:y,s:m,recoveryParam:v})}}}}}},c.prototype.verify=function(e,t,r,i){e=this._truncateToN(new n(e,16)),r=this.keyFromPublic(r,i);var o=(t=new u(t,"hex")).r,a=t.s;if(o.cmpn(1)<0||o.cmp(this.n)>=0)return!1;if(a.cmpn(1)<0||a.cmp(this.n)>=0)return!1;var s,c=a.invm(this.n),f=c.mul(e).umod(this.n),h=c.mul(o).umod(this.n);return this.curve._maxwellTrick?!(s=this.g.jmulAdd(f,r.getPublic(),h)).isInfinity()&&s.eqXToP(o):!(s=this.g.mulAdd(f,r.getPublic(),h)).isInfinity()&&0===s.getX().umod(this.n).cmp(o)},c.prototype.recoverPubKey=function(e,t,r,i){a((3&r)===r,"The recovery param is more than two bits"),t=new u(t,i);var o=this.n,s=new n(e),c=t.r,f=t.s,h=1&r,l=r>>1;if(c.cmp(this.curve.p.umod(this.curve.n))>=0&&l)throw new Error("Unable to find sencond key candinate");c=l?this.curve.pointFromX(c.add(this.curve.n),h):this.curve.pointFromX(c,h);var d=t.r.invm(o),p=o.sub(s).mul(d).umod(o),b=f.mul(d).umod(o);return this.g.mulAdd(p,c,b)},c.prototype.getKeyRecoveryParam=function(e,t,r,n){if(null!==(t=new u(t,n)).recoveryParam)return t.recoveryParam;for(var i=0;i<4;i++){var o;try{o=this.recoverPubKey(e,t,i)}catch(e){continue}if(o.eq(r))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(e,t,r){"use strict";var n=e("bn.js"),i=e("../../elliptic").utils.assert;function o(e,t){this.ec=e,this.priv=null,this.pub=null,t.priv&&this._importPrivate(t.priv,t.privEnc),t.pub&&this._importPublic(t.pub,t.pubEnc)}t.exports=o,o.fromPublic=function(e,t,r){return t instanceof o?t:new o(e,{pub:t,pubEnc:r})},o.fromPrivate=function(e,t,r){return t instanceof o?t:new o(e,{priv:t,privEnc:r})},o.prototype.validate=function(){var e=this.getPublic();return e.isInfinity()?{result:!1,reason:"Invalid public key"}:e.validate()?e.mul(this.ec.curve.n).isInfinity()?{result:!0,reason:null}:{result:!1,reason:"Public key * N != O"}:{result:!1,reason:"Public key is not a point"}},o.prototype.getPublic=function(e,t){return"string"==typeof e&&(t=e,e=null),this.pub||(this.pub=this.ec.g.mul(this.priv)),t?this.pub.encode(t,e):this.pub},o.prototype.getPrivate=function(e){return"hex"===e?this.priv.toString(16,2):this.priv},o.prototype._importPrivate=function(e,t){this.priv=new n(e,t||16),this.priv=this.priv.umod(this.ec.curve.n)},o.prototype._importPublic=function(e,t){if(e.x||e.y)return"mont"===this.ec.curve.type?i(e.x,"Need x coordinate"):"short"!==this.ec.curve.type&&"edwards"!==this.ec.curve.type||i(e.x&&e.y,"Need both x and y coordinate"),void(this.pub=this.ec.curve.point(e.x,e.y));this.pub=this.ec.curve.decodePoint(e,t)},o.prototype.derive=function(e){return e.mul(this.priv).getX()},o.prototype.sign=function(e,t,r){return this.ec.sign(e,this,t,r)},o.prototype.verify=function(e,t){return this.ec.verify(e,t,this)},o.prototype.inspect=function(){return""}},{"../../elliptic":109,"bn.js":53}],118:[function(e,t,r){"use strict";var n=e("bn.js"),i=e("../../elliptic").utils,o=i.assert;function a(e,t){if(e instanceof a)return e;this._importDER(e,t)||(o(e.r&&e.s,"Signature without r or s"),this.r=new n(e.r,16),this.s=new n(e.s,16),void 0===e.recoveryParam?this.recoveryParam=null:this.recoveryParam=e.recoveryParam)}function s(e,t){var r=e[t.place++];if(!(128&r))return r;for(var n=15&r,i=0,o=0,a=t.place;o>>3);for(e.push(128|r);--r;)e.push(t>>>(r<<3)&255);e.push(t)}}t.exports=a,a.prototype._importDER=function(e,t){e=i.toArray(e,t);var r=new function(){this.place=0};if(48!==e[r.place++])return!1;if(s(e,r)+r.place!==e.length)return!1;if(2!==e[r.place++])return!1;var o=s(e,r),a=e.slice(r.place,o+r.place);if(r.place+=o,2!==e[r.place++])return!1;var u=s(e,r);if(e.length!==u+r.place)return!1;var c=e.slice(r.place,u+r.place);return 0===a[0]&&128&a[1]&&(a=a.slice(1)),0===c[0]&&128&c[1]&&(c=c.slice(1)),this.r=new n(a),this.s=new n(c),this.recoveryParam=null,!0},a.prototype.toDER=function(e){var t=this.r.toArray(),r=this.s.toArray();for(128&t[0]&&(t=[0].concat(t)),128&r[0]&&(r=[0].concat(r)),t=u(t),r=u(r);!(r[0]||128&r[1]);)r=r.slice(1);var n=[2];c(n,t.length),(n=n.concat(t)).push(2),c(n,r.length);var o=n.concat(r),a=[48];return c(a,o.length),a=a.concat(o),i.encode(a,e)}},{"../../elliptic":109,"bn.js":53}],119:[function(e,t,r){"use strict";var n=e("hash.js"),i=e("../../elliptic"),o=i.utils,a=o.assert,s=o.parseBytes,u=e("./key"),c=e("./signature");function f(e){if(a("ed25519"===e,"only tested with ed25519 so far"),!(this instanceof f))return new f(e);e=i.curves[e].curve;this.curve=e,this.g=e.g,this.g.precompute(e.n.bitLength()+1),this.pointClass=e.point().constructor,this.encodingLength=Math.ceil(e.n.bitLength()/8),this.hash=n.sha512}t.exports=f,f.prototype.sign=function(e,t){e=s(e);var r=this.keyFromSecret(t),n=this.hashInt(r.messagePrefix(),e),i=this.g.mul(n),o=this.encodePoint(i),a=this.hashInt(o,r.pubBytes(),e).mul(r.priv()),u=n.add(a).umod(this.curve.n);return this.makeSignature({R:i,S:u,Rencoded:o})},f.prototype.verify=function(e,t,r){e=s(e),t=this.makeSignature(t);var n=this.keyFromPublic(r),i=this.hashInt(t.Rencoded(),n.pubBytes(),e),o=this.g.mul(t.S());return t.R().add(n.pub().mul(i)).eq(o)},f.prototype.hashInt=function(){for(var e=this.hash(),t=0;t=0;){var o;if(i.isOdd()){var a=i.andln(n-1);o=a>(n>>1)-1?(n>>1)-a:a,i.isubn(o)}else o=0;r.push(o);for(var s=0!==i.cmpn(0)&&0===i.andln(n-1)?t+1:1,u=1;u0||t.cmpn(-i)>0;){var o,a,s,u=e.andln(3)+n&3,c=t.andln(3)+i&3;3===u&&(u=-1),3===c&&(c=-1),o=0==(1&u)?0:3!=(s=e.andln(7)+n&7)&&5!==s||2!==c?u:-u,r[0].push(o),a=0==(1&c)?0:3!=(s=t.andln(7)+i&7)&&5!==s||2!==u?c:-c,r[1].push(a),2*n===o+1&&(n=1-n),2*i===a+1&&(i=1-i),e.iushrn(1),t.iushrn(1)}return r},n.cachedProperty=function(e,t,r){var n="_"+t;e.prototype[t]=function(){return void 0!==this[n]?this[n]:this[n]=r.call(this)}},n.parseBytes=function(e){return"string"==typeof e?n.toArray(e,"hex"):e},n.intFromLE=function(e){return new i(e,"hex","le")}},{"bn.js":53,"minimalistic-assert":234,"minimalistic-crypto-utils":235}],124:[function(e,t,r){t.exports={_from:"elliptic@^6.0.0",_id:"elliptic@6.4.0",_inBundle:!1,_integrity:"sha1-ysmvh2LIWDYYcAPI3+GT5eLq5d8=",_location:"/elliptic",_phantomChildren:{},_requested:{type:"range",registry:!0,raw:"elliptic@^6.0.0",name:"elliptic",escapedName:"elliptic",rawSpec:"^6.0.0",saveSpec:null,fetchSpec:"^6.0.0"},_requiredBy:["/browserify-sign","/create-ecdh"],_resolved:"https://registry.npmjs.org/elliptic/-/elliptic-6.4.0.tgz",_shasum:"cac9af8762c85836187003c8dfe193e5e2eae5df",_spec:"elliptic@^6.0.0",_where:"/Users/alexvlasov/Blockchain/web3swift_jsproxy/node_modules/browserify-sign",author:{name:"Fedor Indutny",email:"fedor@indutny.com"},bugs:{url:"https://github.com/indutny/elliptic/issues"},bundleDependencies:!1,dependencies:{"bn.js":"^4.4.0",brorand:"^1.0.1","hash.js":"^1.0.0","hmac-drbg":"^1.0.0",inherits:"^2.0.1","minimalistic-assert":"^1.0.0","minimalistic-crypto-utils":"^1.0.0"},deprecated:!1,description:"EC cryptography",devDependencies:{brfs:"^1.4.3",coveralls:"^2.11.3",grunt:"^0.4.5","grunt-browserify":"^5.0.0","grunt-cli":"^1.2.0","grunt-contrib-connect":"^1.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^1.0.1","grunt-mocha-istanbul":"^3.0.1","grunt-saucelabs":"^8.6.2",istanbul:"^0.4.2",jscs:"^2.9.0",jshint:"^2.6.0",mocha:"^2.1.0"},files:["lib"],homepage:"https://github.com/indutny/elliptic",keywords:["EC","Elliptic","curve","Cryptography"],license:"MIT",main:"lib/elliptic.js",name:"elliptic",repository:{type:"git",url:"git+ssh://git@github.com/indutny/elliptic.git"},scripts:{jscs:"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",jshint:"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",lint:"npm run jscs && npm run jshint",test:"npm run lint && npm run unit",unit:"istanbul test _mocha --reporter=spec test/index.js",version:"grunt dist && git add dist/"},version:"6.4.0"}},{}],125:[function(e,t,r){"use strict";const n=e("ethjs-util");function i(e){let t=n.stripHexPrefix(e);for(;"0"===t[0];)t=t.substr(1);return`0x${t}`}t.exports={incrementHexNumber:function(e){return i(n.intToHex(parseInt(e,16)+1))},formatHex:i}},{"ethjs-util":155}],126:[function(e,t,r){const n=e("eth-query"),i=e("events"),o=e("pify"),a=e("./hexUtils"),s=a.incrementHexNumber,u=1e3,c=60*u;t.exports=class extends i{constructor(e={}){if(super(),!e.provider)throw new Error("RpcBlockTracker - no provider specified.");this._provider=e.provider,this._query=new n(e.provider),this._pollingInterval=e.pollingInterval||4*u,this._syncingTimeout=e.syncingTimeout||1*c,this._trackingBlock=null,this._trackingBlockTimestamp=null,this._currentBlock=null,this._isRunning=!1,this._performSync=this._performSync.bind(this),this._handleNewBlockNotification=this._handleNewBlockNotification.bind(this)}getTrackingBlock(){return this._trackingBlock}getCurrentBlock(){return this._currentBlock}async awaitCurrentBlock(){return this._currentBlock?this._currentBlock:(await new Promise(e=>this.once("latest",e)),this._currentBlock)}async start(e={}){this._isRunning||(this._isRunning=!0,e.fromBlock?await this._setTrackingBlock(await this._fetchBlockByNumber(e.fromBlock)):await this._setTrackingBlock(await this._fetchLatestBlock()),this._provider.on?await this._initSubscription():this._performSync().catch(e=>{e&&console.error(e)}))}async stop(){this._isRunning=!1,this._provider.on&&await this._removeSubscription()}async _setTrackingBlock(e){if(this._trackingBlock&&this._trackingBlock.hash===e.hash)return;const t=this._trackingBlockTimestamp,r=Date.now();t&&r-t>this._syncingTimeout?(this._trackingBlockTimestamp=null,await this._warpToLatest()):(this._trackingBlock=e,this._trackingBlockTimestamp=r,this.emit("block",e))}async _setCurrentBlock(e){if(this._currentBlock&&this._currentBlock.hash===e.hash)return;const t=this._currentBlock;this._currentBlock=e,this.emit("latest",e),this.emit("sync",{newBlock:e,oldBlock:t})}async _warpToLatest(){await this._setTrackingBlock(await this._fetchLatestBlock())}async _pollForNextBlock(){setTimeout(()=>this._performSync(),this._pollingInterval)}async _performSync(){if(!this._isRunning)return;const e=this.getTrackingBlock();if(!e)throw new Error("RpcBlockTracker - tracking block is missing");const t=s(e.number);try{const r=await this._fetchBlockByNumber(t);r?(await this._setTrackingBlock(r),this._performSync()):(await this._setCurrentBlock(e),this._pollForNextBlock())}catch(t){t.message.includes("index out of range")||t.message.includes("Couldn't find block by reference")?(await this._setCurrentBlock(e),this._pollForNextBlock()):(console.error(t),this._pollForNextBlock())}}async _handleNewBlockNotification(e,t){t.id==this._subscriptionId&&(e&&(this.emit("error",e),await this._removeSubscription()),await this._setTrackingBlock(await this._fetchBlockByNumber(t.result.number)))}async _initSubscription(){this._provider.on("data",this._handleNewBlockNotification);let e=await o(this._provider.sendAsync||this._provider.send)({jsonrpc:"2.0",id:(new Date).getTime(),method:"eth_subscribe",params:["newHeads"]});this._subscriptionId=e.result}async _removeSubscription(){if(!this._subscriptionId)throw new Error("Not subscribed.");this._provider.removeListener("data",this._handleNewBlockNotification),await o(this._provider.sendAsync||this._provider.send)({jsonrpc:"2.0",id:(new Date).getTime(),method:"eth_unsubscribe",params:[this._subscriptionId]}),delete this._subscriptionId}_fetchLatestBlock(){return o(this._query.getBlockByNumber).call(this._query,"latest",!0)}_fetchBlockByNumber(e){const t=a.formatHex(e);return o(this._query.getBlockByNumber).call(this._query,t,!0)}}},{"./hexUtils":125,"eth-query":135,events:157,pify:252}],127:[function(e,t,r){(function(t){var n=e("js-sha3").keccak_256,i=e("idna-uts46-hx");function o(e){return e?i.toUnicode(e,{useStd3ASCII:!0,transitional:!1}):e}r.hash=function(e){for(var r="",i=0;i<32;i++)r+="00";if(name=o(e),name){var a=name.split(".");for(i=a.length-1;i>=0;i--){var s=n(a[i]);r=n(new t(r+s,"hex"))}}return"0x"+r},r.normalize=o}).call(this,e("buffer").Buffer)},{buffer:84,"idna-uts46-hx":177,"js-sha3":128}],128:[function(e,t,r){(function(e,r){!function(){"use strict";var n="object"==typeof window?window:{};!n.JS_SHA3_NO_NODE_JS&&"object"==typeof e&&e.versions&&e.versions.node&&(n=r);for(var i=!n.JS_SHA3_NO_COMMON_JS&&"object"==typeof t&&t.exports,o="0123456789abcdef".split(""),a=[0,8,16,24],s=[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],u=[224,256,384,512],c=["hex","buffer","arrayBuffer","array"],f=function(e,t,r){return function(n){return new _(e,t,e).update(n)[r]()}},h=function(e,t,r){return function(n,i){return new _(e,t,i).update(n)[r]()}},l=function(e,t){var r=f(e,t,"hex");r.create=function(){return new _(e,t,e)},r.update=function(e){return r.create().update(e)};for(var n=0;n>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var n=0;n<50;++n)this.s[n]=0}_.prototype.update=function(e){var t="string"!=typeof e;t&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e));for(var r,n,i=e.length,o=this.blocks,s=this.byteCount,u=this.blockCount,c=0,f=this.s;c>2]|=e[c]<>2]|=n<>2]|=(192|n>>6)<>2]|=(128|63&n)<=57344?(o[r>>2]|=(224|n>>12)<>2]|=(128|n>>6&63)<>2]|=(128|63&n)<>2]|=(240|n>>18)<>2]|=(128|n>>12&63)<>2]|=(128|n>>6&63)<>2]|=(128|63&n)<=s){for(this.start=r-s,this.block=o[u],r=0;r>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t>4&15]+o[15&e]+o[e>>12&15]+o[e>>8&15]+o[e>>20&15]+o[e>>16&15]+o[e>>28&15]+o[e>>24&15];s%t==0&&(A(r),a=0)}return i&&(e=r[a],i>0&&(u+=o[e>>4&15]+o[15&e]),i>1&&(u+=o[e>>12&15]+o[e>>8&15]),i>2&&(u+=o[e>>20&15]+o[e>>16&15])),u},_.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,i=this.extraBytes,o=0,a=0,s=this.outputBits>>3;e=i?new ArrayBuffer(n+1<<2):new ArrayBuffer(s);for(var u=new Uint32Array(e);a>8&255,u[e+2]=t>>16&255,u[e+3]=t>>24&255;s%r==0&&A(n)}return o&&(e=s<<2,t=n[a],o>0&&(u[e]=255&t),o>1&&(u[e+1]=t>>8&255),o>2&&(u[e+2]=t>>16&255)),u};var A=function(e){var t,r,n,i,o,a,u,c,f,h,l,d,p,b,y,m,v,g,w,_,A,E,x,k,S,M,I,T,U,j,B,P,C,N,R,L,O,D,F,q,H,z,K,V,G,W,Y,X,Z,J,$,Q,ee,te,re,ne,ie,oe,ae,se,ue,ce,fe;for(n=0;n<48;n+=2)i=e[0]^e[10]^e[20]^e[30]^e[40],o=e[1]^e[11]^e[21]^e[31]^e[41],a=e[2]^e[12]^e[22]^e[32]^e[42],u=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],f=e[5]^e[15]^e[25]^e[35]^e[45],h=e[6]^e[16]^e[26]^e[36]^e[46],l=e[7]^e[17]^e[27]^e[37]^e[47],t=(d=e[8]^e[18]^e[28]^e[38]^e[48])^(a<<1|u>>>31),r=(p=e[9]^e[19]^e[29]^e[39]^e[49])^(u<<1|a>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=i^(c<<1|f>>>31),r=o^(f<<1|c>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=a^(h<<1|l>>>31),r=u^(l<<1|h>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=c^(d<<1|p>>>31),r=f^(p<<1|d>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=h^(i<<1|o>>>31),r=l^(o<<1|i>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,b=e[0],y=e[1],W=e[11]<<4|e[10]>>>28,Y=e[10]<<4|e[11]>>>28,T=e[20]<<3|e[21]>>>29,U=e[21]<<3|e[20]>>>29,se=e[31]<<9|e[30]>>>23,ue=e[30]<<9|e[31]>>>23,z=e[40]<<18|e[41]>>>14,K=e[41]<<18|e[40]>>>14,N=e[2]<<1|e[3]>>>31,R=e[3]<<1|e[2]>>>31,m=e[13]<<12|e[12]>>>20,v=e[12]<<12|e[13]>>>20,X=e[22]<<10|e[23]>>>22,Z=e[23]<<10|e[22]>>>22,j=e[33]<<13|e[32]>>>19,B=e[32]<<13|e[33]>>>19,ce=e[42]<<2|e[43]>>>30,fe=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,L=e[14]<<6|e[15]>>>26,O=e[15]<<6|e[14]>>>26,g=e[25]<<11|e[24]>>>21,w=e[24]<<11|e[25]>>>21,J=e[34]<<15|e[35]>>>17,$=e[35]<<15|e[34]>>>17,P=e[45]<<29|e[44]>>>3,C=e[44]<<29|e[45]>>>3,k=e[6]<<28|e[7]>>>4,S=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,ie=e[16]<<23|e[17]>>>9,D=e[26]<<25|e[27]>>>7,F=e[27]<<25|e[26]>>>7,_=e[36]<<21|e[37]>>>11,A=e[37]<<21|e[36]>>>11,Q=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,V=e[8]<<27|e[9]>>>5,G=e[9]<<27|e[8]>>>5,M=e[18]<<20|e[19]>>>12,I=e[19]<<20|e[18]>>>12,oe=e[29]<<7|e[28]>>>25,ae=e[28]<<7|e[29]>>>25,q=e[38]<<8|e[39]>>>24,H=e[39]<<8|e[38]>>>24,E=e[48]<<14|e[49]>>>18,x=e[49]<<14|e[48]>>>18,e[0]=b^~m&g,e[1]=y^~v&w,e[10]=k^~M&T,e[11]=S^~I&U,e[20]=N^~L&D,e[21]=R^~O&F,e[30]=V^~W&X,e[31]=G^~Y&Z,e[40]=te^~ne&oe,e[41]=re^~ie&ae,e[2]=m^~g&_,e[3]=v^~w&A,e[12]=M^~T&j,e[13]=I^~U&B,e[22]=L^~D&q,e[23]=O^~F&H,e[32]=W^~X&J,e[33]=Y^~Z&$,e[42]=ne^~oe&se,e[43]=ie^~ae&ue,e[4]=g^~_&E,e[5]=w^~A&x,e[14]=T^~j&P,e[15]=U^~B&C,e[24]=D^~q&z,e[25]=F^~H&K,e[34]=X^~J&Q,e[35]=Z^~$&ee,e[44]=oe^~se&ce,e[45]=ae^~ue&fe,e[6]=_^~E&b,e[7]=A^~x&y,e[16]=j^~P&k,e[17]=B^~C&S,e[26]=q^~z&N,e[27]=H^~K&R,e[36]=J^~Q&V,e[37]=$^~ee&G,e[46]=se^~ce&te,e[47]=ue^~fe&re,e[8]=E^~b&m,e[9]=x^~y&v,e[18]=P^~k&M,e[19]=C^~S&I,e[28]=z^~N&L,e[29]=K^~R&O,e[38]=Q^~V&W,e[39]=ee^~G&Y,e[48]=ce^~te&ne,e[49]=fe^~re&ie,e[0]^=s[n],e[1]^=s[n+1]};if(i)t.exports=p;else for(y=0;y{setTimeout(t,e)})}function c(e){const t=e.toString();return s.some(e=>t.includes(e))}async function f(e,t,r){const{fetchUrl:n,fetchParams:a}=h({network:e,req:t}),s=await o(n,a),u=await s.text();if(!s.ok)switch(s.status){case 405:throw new i.MethodNotFound;case 418:throw l("Request is being rate limited.");case 503:case 504:throw function(){let e="Gateway timeout. The request took too long to process. ";return e+="This can happen when querying logs over too wide a block range.",l("Gateway timeout. The request took too long to process. This can happen when querying logs over too wide a block range.")}();default:throw l(u)}if("eth_getBlockByNumber"===t.method&&"Not Found"===u)return void(r.result=null);const c=JSON.parse(u);r.result=c.result,r.error=c.error}function h({network:e,req:t}){const r=function(e){return{id:e.id,jsonrpc:e.jsonrpc,method:e.method,params:e.params}}(t),{method:n,params:i}=r,o={};let s=`https://api.infura.io/v1/jsonrpc/${e}`;if(a.includes(n))o.method="POST",o.headers={Accept:"application/json","Content-Type":"application/json"},o.body=JSON.stringify(r);else{o.method="GET",s+=`/${n}?params=${encodeURIComponent(JSON.stringify(i))}`}return{fetchUrl:s,fetchParams:o}}function l(e){const t=new Error(e);return new i.InternalError(t)}t.exports=function(e={}){const t=e.network||"mainnet",r=e.maxAttempts||5;if(!r)throw new Error(`Invalid value for 'maxAttempts': "${r}" (${typeof r})`);return n(async(e,n,i)=>{for(let i=1;i<=r;i++)try{await f(t,e,n);break}catch(e){if(!c(e))throw e;const t=r-i;if(!t){const t=`InfuraProvider - cannot complete request. All retries exhausted.\nOriginal Error:\n${e.toString()}\n\n`,r=new Error(t);throw r}await u(1e3)}})},t.exports.fetchConfigFromReq=h},{"cross-fetch":96,"json-rpc-engine/src/createAsyncMiddleware":187,"json-rpc-error":189}],131:[function(e,t,r){t.exports=function(e){return{sendAsync:e.handle.bind(e)}}},{}],132:[function(e,t,r){var n=function(e,t){for(var r=[],n=0;n>6|192);else{if(i>55295&&i<56320){if(++n==e.length)return null;var o=e.charCodeAt(n);if(o<56320||o>57343)return null;r+=t((i=65536+((1023&i)<<10)+(1023&o))>>18|240),r+=t(i>>12&63|128)}else r+=t(i>>12|224);r+=t(i>>6&63|128)}r+=t(63&i|128)}}return r},toString:function(e){for(var t="",r=0,o=i(e);r127){if(a>191&&a<224){if(r>=o)return null;a=(31&a)<<6|63&n(e,r)}else if(a>223&&a<240){if(r+1>=o)return null;a=(15&a)<<12|(63&n(e,r))<<6|63&n(e,++r)}else{if(!(a>239&&a<248))return null;if(r+2>=o)return null;a=(7&a)<<18|(63&n(e,r))<<12|(63&n(e,++r))<<6|63&n(e,++r)}++r}if(a<=65535)t+=String.fromCharCode(a);else{if(!(a<=1114111))return null;a-=65536,t+=String.fromCharCode(a>>10|55296),t+=String.fromCharCode(1023&a|56320)}}return t},fromNumber:function(e){var t=e.toString(16);return t.length%2==0?"0x"+t:"0x0"+t},toNumber:function(e){return parseInt(e.slice(2),16)},fromNat:function(e){return"0x0"===e?"0x":e.length%2==0?e:"0x0"+e.slice(2)},toNat:function(e){return"0"===e[2]?"0x"+e.slice(3):e},fromArray:a,toArray:o,fromUint8Array:function(e){return a([].slice.call(e,0))},toUint8Array:function(e){return new Uint8Array(o(e))}}},{"./array.js":132}],134:[function(e,t,r){var n="0123456789abcdef".split(""),i=[1,256,65536,16777216],o=[0,8,16,24],a=[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],s=function(e){var t,r,n,i,o,s,u,c,f,h,l,d,p,b,y,m,v,g,w,_,A,E,x,k,S,M,I,T,U,j,B,P,C,N,R,L,O,D,F,q,H,z,K,V,G,W,Y,X,Z,J,$,Q,ee,te,re,ne,ie,oe,ae,se,ue,ce,fe;for(n=0;n<48;n+=2)i=e[0]^e[10]^e[20]^e[30]^e[40],o=e[1]^e[11]^e[21]^e[31]^e[41],s=e[2]^e[12]^e[22]^e[32]^e[42],u=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],f=e[5]^e[15]^e[25]^e[35]^e[45],h=e[6]^e[16]^e[26]^e[36]^e[46],l=e[7]^e[17]^e[27]^e[37]^e[47],t=(d=e[8]^e[18]^e[28]^e[38]^e[48])^(s<<1|u>>>31),r=(p=e[9]^e[19]^e[29]^e[39]^e[49])^(u<<1|s>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=i^(c<<1|f>>>31),r=o^(f<<1|c>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=s^(h<<1|l>>>31),r=u^(l<<1|h>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=c^(d<<1|p>>>31),r=f^(p<<1|d>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=h^(i<<1|o>>>31),r=l^(o<<1|i>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,b=e[0],y=e[1],W=e[11]<<4|e[10]>>>28,Y=e[10]<<4|e[11]>>>28,T=e[20]<<3|e[21]>>>29,U=e[21]<<3|e[20]>>>29,se=e[31]<<9|e[30]>>>23,ue=e[30]<<9|e[31]>>>23,z=e[40]<<18|e[41]>>>14,K=e[41]<<18|e[40]>>>14,N=e[2]<<1|e[3]>>>31,R=e[3]<<1|e[2]>>>31,m=e[13]<<12|e[12]>>>20,v=e[12]<<12|e[13]>>>20,X=e[22]<<10|e[23]>>>22,Z=e[23]<<10|e[22]>>>22,j=e[33]<<13|e[32]>>>19,B=e[32]<<13|e[33]>>>19,ce=e[42]<<2|e[43]>>>30,fe=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,L=e[14]<<6|e[15]>>>26,O=e[15]<<6|e[14]>>>26,g=e[25]<<11|e[24]>>>21,w=e[24]<<11|e[25]>>>21,J=e[34]<<15|e[35]>>>17,$=e[35]<<15|e[34]>>>17,P=e[45]<<29|e[44]>>>3,C=e[44]<<29|e[45]>>>3,k=e[6]<<28|e[7]>>>4,S=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,ie=e[16]<<23|e[17]>>>9,D=e[26]<<25|e[27]>>>7,F=e[27]<<25|e[26]>>>7,_=e[36]<<21|e[37]>>>11,A=e[37]<<21|e[36]>>>11,Q=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,V=e[8]<<27|e[9]>>>5,G=e[9]<<27|e[8]>>>5,M=e[18]<<20|e[19]>>>12,I=e[19]<<20|e[18]>>>12,oe=e[29]<<7|e[28]>>>25,ae=e[28]<<7|e[29]>>>25,q=e[38]<<8|e[39]>>>24,H=e[39]<<8|e[38]>>>24,E=e[48]<<14|e[49]>>>18,x=e[49]<<14|e[48]>>>18,e[0]=b^~m&g,e[1]=y^~v&w,e[10]=k^~M&T,e[11]=S^~I&U,e[20]=N^~L&D,e[21]=R^~O&F,e[30]=V^~W&X,e[31]=G^~Y&Z,e[40]=te^~ne&oe,e[41]=re^~ie&ae,e[2]=m^~g&_,e[3]=v^~w&A,e[12]=M^~T&j,e[13]=I^~U&B,e[22]=L^~D&q,e[23]=O^~F&H,e[32]=W^~X&J,e[33]=Y^~Z&$,e[42]=ne^~oe&se,e[43]=ie^~ae&ue,e[4]=g^~_&E,e[5]=w^~A&x,e[14]=T^~j&P,e[15]=U^~B&C,e[24]=D^~q&z,e[25]=F^~H&K,e[34]=X^~J&Q,e[35]=Z^~$&ee,e[44]=oe^~se&ce,e[45]=ae^~ue&fe,e[6]=_^~E&b,e[7]=A^~x&y,e[16]=j^~P&k,e[17]=B^~C&S,e[26]=q^~z&N,e[27]=H^~K&R,e[36]=J^~Q&V,e[37]=$^~ee&G,e[46]=se^~ce&te,e[47]=ue^~fe&re,e[8]=E^~b&m,e[9]=x^~y&v,e[18]=P^~k&M,e[19]=C^~S&I,e[28]=z^~N&L,e[29]=K^~R&O,e[38]=Q^~V&W,e[39]=ee^~G&Y,e[48]=ce^~te&ne,e[49]=fe^~re&ie,e[0]^=a[n],e[1]^=a[n+1]},u=function(e){return function(t){var r;if("0x"===t.slice(0,2)){r=[];for(var a=2,u=t.length;a>2]|=t[d]<>2]|=r<>2]|=(192|r>>6)<>2]|=(128|63&r)<=57344?(u[y>>2]|=(224|r>>12)<>2]|=(128|r>>6&63)<>2]|=(128|63&r)<>2]|=(240|r>>18)<>2]|=(128|r>>12&63)<>2]|=(128|r>>6&63)<>2]|=(128|63&r)<=c){for(e.start=y-c,e.block=u[f],y=0;y>2]|=i[3&y],e.lastByteIndex===c)for(u[0]=u[f],y=1;y>4&15]+n[15&p]+n[p>>12&15]+n[p>>8&15]+n[p>>20&15]+n[p>>16&15]+n[p>>28&15]+n[p>>24&15];m%f==0&&(s(l),y=0)}return"0x"+b}(function(e){return{blocks:[],reset:!0,block:0,start:0,blockCount:1600-(e<<1)>>5,outputBlocks:e>>5,s:(t=[0,0,0,0,0,0,0,0,0,0],[].concat(t,t,t,t,t))};var t}(e),r)}};t.exports={keccak256:u(256),keccak512:u(512),keccak256s:u(256),keccak512s:u(512)}},{}],135:[function(e,t,r){const n=e("xtend"),i=e("json-rpc-random-id")();function o(e){this.currentProvider=e}function a(e){return function(){var t=[].slice.call(arguments),r=t.pop();this.sendAsync({method:e,params:t},r)}}function s(e,t){return function(){var r=[].slice.call(arguments),n=r.pop();r.lengtho)throw new Error("Elements exceed array size: "+o);for(d in h=[],e=e.slice(0,e.lastIndexOf("[")),"string"==typeof t&&(t=JSON.parse(t)),t)h.push(l(e,t[d]));if("dynamic"===o){var p=l("uint256",t.length);h.unshift(p)}return r.concat(h)}if("bytes"===e)return t=new r(t),h=r.concat([l("uint256",t.length),t]),t.length%32!=0&&(h=r.concat([h,n.zeros(32-t.length%32)])),h;if(e.startsWith("bytes")){if((o=s(e))<1||o>32)throw new Error("Invalid bytes width: "+o);return n.setLengthRight(t,32)}if(e.startsWith("uint")){if((o=s(e))%8||o<8||o>256)throw new Error("Invalid uint width: "+o);if((a=f(t)).bitLength()>o)throw new Error("Supplied uint exceeds width: "+o+" vs "+a.bitLength());if(a<0)throw new Error("Supplied uint is negative");return a.toArrayLike(r,"be",32)}if(e.startsWith("int")){if((o=s(e))%8||o<8||o>256)throw new Error("Invalid int width: "+o);if((a=f(t)).bitLength()>o)throw new Error("Supplied int exceeds width: "+o+" vs "+a.bitLength());return a.toTwos(256).toArrayLike(r,"be",32)}if(e.startsWith("ufixed")){if(o=u(e),(a=f(t))<0)throw new Error("Supplied ufixed is negative");return l("uint256",a.mul(new i(2).pow(new i(o[1]))))}if(e.startsWith("fixed"))return o=u(e),l("int256",f(t).mul(new i(2).pow(new i(o[1]))));throw new Error("Unsupported or invalid type: "+e)}function d(e,t,n){var o,a,s,u;if("string"==typeof e&&(e=p(e)),"address"===e.name)return d(e.rawType,t,n).toArrayLike(r,"be",20).toString("hex");if("bool"===e.name)return d(e.rawType,t,n).toString()===new i(1).toString();if("string"===e.name){var c=d(e.rawType,t,n);return new r(c,"utf8").toString()}if(e.isArray){for(s=[],o=e.size,"dynamic"===e.size&&(o=d("uint256",t,n=d("uint256",t,n).toNumber()).toNumber(),n+=32),u=0;ue.size)throw new Error("Decoded int exceeds width: "+e.size+" vs "+a.bitLength());return a}if(e.name.startsWith("int")){if((a=new i(t.slice(n,n+32),16,"be").fromTwos(256)).bitLength()>e.size)throw new Error("Decoded uint exceeds width: "+e.size+" vs "+a.bitLength());return a}if(e.name.startsWith("ufixed")){if(o=new i(2).pow(new i(e.size[1])),!(a=d("uint256",t,n)).mod(o).isZero())throw new Error("Decimals not supported yet");return a.div(o)}if(e.name.startsWith("fixed")){if(o=new i(2).pow(new i(e.size[1])),!(a=d("int256",t,n)).mod(o).isZero())throw new Error("Decimals not supported yet");return a.div(o)}throw new Error("Unsupported or invalid type: "+e.name)}function p(e){var t,r,n;if(y(e)){t=c(e);var i=e.slice(0,e.lastIndexOf("["));return i=p(i),r={isArray:!0,name:e,size:t,memoryUsage:"dynamic"===t?32:i.memoryUsage*t,subArray:i}}switch(e){case"address":n="uint160";break;case"bool":n="uint8";break;case"string":n="bytes"}if(r={rawType:n,name:e,memoryUsage:32},e.startsWith("bytes")&&"bytes"!==e||e.startsWith("uint")||e.startsWith("int")?r.size=s(e):(e.startsWith("ufixed")||e.startsWith("fixed"))&&(r.size=u(e)),e.startsWith("bytes")&&"bytes"!==e&&(r.size<1||r.size>32))throw new Error("Invalid bytes width: "+r.size);if((e.startsWith("uint")||e.startsWith("int"))&&(r.size%8||r.size<8||r.size>256))throw new Error("Invalid int/uint width: "+r.size);return r}function b(e){return"string"===e||"bytes"===e||"dynamic"===c(e)}function y(e){return e.lastIndexOf("]")===e.length-1}function m(e,t){return e.startsWith("address")||e.startsWith("bytes")?"0x"+t.toString("hex"):t.toString()}o.eventID=function(e,t){var i=e+"("+t.map(a).join(",")+")";return n.sha3(new r(i))},o.methodID=function(e,t){return o.eventID(e,t).slice(0,4)},o.rawEncode=function(e,t){var n=[],i=[],o=0;e.forEach(function(e){if(y(e)){var t=c(e);o+="dynamic"!==t?32*t:32}else o+=32});for(var s=0;s32)throw new Error("Invalid bytes width: "+i);u.push(n.setLengthRight(l,i))}else if(h.startsWith("uint")){if((i=s(h))%8||i<8||i>256)throw new Error("Invalid uint width: "+i);if((o=f(l)).bitLength()>i)throw new Error("Supplied uint exceeds width: "+i+" vs "+o.bitLength());u.push(o.toArrayLike(r,"be",i/8))}else{if(!h.startsWith("int"))throw new Error("Unsupported or invalid type: "+h);if((i=s(h))%8||i<8||i>256)throw new Error("Invalid int width: "+i);if((o=f(l)).bitLength()>i)throw new Error("Supplied int exceeds width: "+i+" vs "+o.bitLength());u.push(o.toTwos(i).toArrayLike(r,"be",i/8))}}return r.concat(u)},o.soliditySHA3=function(e,t){return n.sha3(o.solidityPack(e,t))},o.soliditySHA256=function(e,t){return n.sha256(o.solidityPack(e,t))},o.solidityRIPEMD160=function(e,t){return n.ripemd160(o.solidityPack(e,t),!0)},o.fromSerpent=function(e){for(var t,r=[],n=0;n="0"&&t<="9");)o+=e[a]-"0",a++;n=a-1,r.push(o)}else if("i"===i)r.push("int256");else{if("a"!==i)throw new Error("Unsupported or invalid type: "+i);r.push("int256[]")}}return r},o.toSerpent=function(e){for(var t=[],r=0;r0){var r=this.raw.slice();this.v=this._chainId,this.r=0,this.s=0,t=this.raw,this.raw=r}else t=this.raw.slice(0,6);return n.rlphash(t)},e.prototype.getChainId=function(){return this._chainId},e.prototype.getSenderAddress=function(){if(this._from)return this._from;var e=this.getSenderPublicKey();return this._from=n.publicToAddress(e),this._from},e.prototype.getSenderPublicKey=function(){if(!(this._senderPubKey&&this._senderPubKey.length||this.verifySignature()))throw new Error("Invalid Signature");return this._senderPubKey},e.prototype.verifySignature=function(){var e=this.hash(!1);if(this._homestead&&1===new o(this.s).cmp(a))return!1;try{var t=n.bufferToInt(this.v);this._chainId>0&&(t-=2*this._chainId+8),this._senderPubKey=n.ecrecover(e,t,this.r,this.s)}catch(e){return!1}return!!this._senderPubKey},e.prototype.sign=function(e){var t=this.hash(!1),r=n.ecsign(t,e);this._chainId>0&&(r.v+=2*this._chainId+8),Object.assign(this,r)},e.prototype.getDataFee=function(){for(var e=this.raw[5],t=new o(0),r=0;r0&&t.push(["gas limit is too low. Need at least "+this.getBaseFee()]),void 0===e||!1===e?0===t.length:t.join(" ")},e}();t.exports=s}).call(this,e("buffer").Buffer)},{buffer:84,"ethereum-common/params.json":137,"ethereumjs-util":141}],141:[function(e,t,r){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=e("keccak"),o=e("secp256k1"),a=e("assert"),s=e("rlp"),u=e("bn.js"),c=e("create-hash"),f=e("safe-buffer").Buffer;Object.assign(r,e("ethjs-util")),r.MAX_INTEGER=new u("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",16),r.TWO_POW256=new u("10000000000000000000000000000000000000000000000000000000000000000",16),r.KECCAK256_NULL_S="c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470",r.SHA3_NULL_S=r.KECCAK256_NULL_S,r.KECCAK256_NULL=f.from(r.KECCAK256_NULL_S,"hex"),r.SHA3_NULL=r.KECCAK256_NULL,r.KECCAK256_RLP_ARRAY_S="1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",r.SHA3_RLP_ARRAY_S=r.KECCAK256_RLP_ARRAY_S,r.KECCAK256_RLP_ARRAY=f.from(r.KECCAK256_RLP_ARRAY_S,"hex"),r.SHA3_RLP_ARRAY=r.KECCAK256_RLP_ARRAY,r.KECCAK256_RLP_S="56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",r.SHA3_RLP_S=r.KECCAK256_RLP_S,r.KECCAK256_RLP=f.from(r.KECCAK256_RLP_S,"hex"),r.SHA3_RLP=r.KECCAK256_RLP,r.BN=u,r.rlp=s,r.secp256k1=o,r.zeros=function(e){return f.allocUnsafe(e).fill(0)},r.zeroAddress=function(){var e=r.zeros(20);return r.bufferToHex(e)},r.setLengthLeft=r.setLength=function(e,t,n){var i=r.zeros(t);return e=r.toBuffer(e),n?e.length0&&"0"===t.toString();)t=(e=e.slice(1))[0];return e},r.toBuffer=function(e){if(!f.isBuffer(e))if(Array.isArray(e))e=f.from(e);else if("string"==typeof e)e=r.isHexString(e)?f.from(r.padToEven(r.stripHexPrefix(e)),"hex"):f.from(e);else if("number"==typeof e)e=r.intToBuffer(e);else if(null==e)e=f.allocUnsafe(0);else if(u.isBN(e))e=e.toArrayLike(f);else{if(!e.toArray)throw new Error("invalid type");e=f.from(e.toArray())}return e},r.bufferToInt=function(e){return new u(r.toBuffer(e)).toNumber()},r.bufferToHex=function(e){return"0x"+(e=r.toBuffer(e)).toString("hex")},r.fromSigned=function(e){return new u(e).fromTwos(256)},r.toUnsigned=function(e){return f.from(e.toTwos(256).toArray())},r.keccak=function(e,t){return e=r.toBuffer(e),t||(t=256),i("keccak"+t).update(e).digest()},r.keccak256=function(e){return r.keccak(e)},r.sha3=r.keccak,r.sha256=function(e){return e=r.toBuffer(e),c("sha256").update(e).digest()},r.ripemd160=function(e,t){e=r.toBuffer(e);var n=c("rmd160").update(e).digest();return!0===t?r.setLength(n,32):n},r.rlphash=function(e){return r.keccak(s.encode(e))},r.isValidPrivate=function(e){return o.privateKeyVerify(e)},r.isValidPublic=function(e,t){return 64===e.length?o.publicKeyVerify(f.concat([f.from([4]),e])):!!t&&o.publicKeyVerify(e)},r.pubToAddress=r.publicToAddress=function(e,t){return e=r.toBuffer(e),t&&64!==e.length&&(e=o.publicKeyConvert(e,!1).slice(1)),a(64===e.length),r.keccak(e).slice(-20)};var h=r.privateToPublic=function(e){return e=r.toBuffer(e),o.publicKeyCreate(e,!1).slice(1)};r.importPublic=function(e){return 64!==(e=r.toBuffer(e)).length&&(e=o.publicKeyConvert(e,!1).slice(1)),e},r.ecsign=function(e,t){var r=o.sign(e,t),n={};return n.r=r.signature.slice(0,32),n.s=r.signature.slice(32,64),n.v=r.recovery+27,n},r.hashPersonalMessage=function(e){var t=r.toBuffer("Ethereum Signed Message:\n"+e.length.toString());return r.keccak(f.concat([t,e]))},r.ecrecover=function(e,t,n,i){var a=f.concat([r.setLength(n,32),r.setLength(i,32)],64),s=t-27;if(0!==s&&1!==s)throw new Error("Invalid signature v value");var u=o.recover(e,a,s);return o.publicKeyConvert(u,!1).slice(1)},r.toRpcSig=function(e,t,n){if(27!==e&&28!==e)throw new Error("Invalid recovery id");return r.bufferToHex(f.concat([r.setLengthLeft(t,32),r.setLengthLeft(n,32),r.toBuffer(e-27)]))},r.fromRpcSig=function(e){if(65!==(e=r.toBuffer(e)).length)throw new Error("Invalid signature length");var t=e[64];return t<27&&(t+=27),{v:t,r:e.slice(0,32),s:e.slice(32,64)}},r.privateToAddress=function(e){return r.publicToAddress(h(e))},r.isValidAddress=function(e){return/^0x[0-9a-fA-F]{40}$/.test(e)},r.isZeroAddress=function(e){return r.zeroAddress()===r.addHexPrefix(e)},r.toChecksumAddress=function(e){e=r.stripHexPrefix(e).toLowerCase();for(var t=r.keccak(e).toString("hex"),n="0x",i=0;i=8?n+=e[i].toUpperCase():n+=e[i];return n},r.isValidChecksumAddress=function(e){return r.isValidAddress(e)&&r.toChecksumAddress(e)===e},r.generateAddress=function(e,t){return e=r.toBuffer(e),t=(t=new u(t)).isZero()?null:f.from(t.toArray()),r.rlphash([e,t]).slice(-20)},r.isPrecompiled=function(e){var t=r.unpad(e);return 1===t.length&&t[0]>=1&&t[0]<=8},r.addHexPrefix=function(e){return"string"!=typeof e?e:r.isHexPrefixed(e)?e:"0x"+e},r.isValidSignature=function(e,t,r,n){var i=new u("7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0",16),o=new u("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",16);return 32===t.length&&32===r.length&&((27===e||28===e)&&(t=new u(t),r=new u(r),!(t.isZero()||t.gt(o)||r.isZero()||r.gt(o))&&(!1!==n||1!==new u(r).cmp(i))))},r.baToJSON=function(e){if(f.isBuffer(e))return"0x"+e.toString("hex");if(e instanceof Array){for(var t=[],n=0;n=i.length,"The field "+t.name+" must not have more "+t.length+" bytes")):t.allowZero&&0===i.length||!t.length||a(t.length===i.length,"The field "+t.name+" must have byte length of "+t.length),e.raw[n]=i}e._fields.push(t.name),Object.defineProperty(e,t.name,{enumerable:!0,configurable:!0,get:i,set:o}),t.default&&(e[t.name]=t.default),t.alias&&Object.defineProperty(e,t.alias,{enumerable:!1,configurable:!0,set:o,get:i})}),i)if("string"==typeof i&&(i=f.from(r.stripHexPrefix(i),"hex")),f.isBuffer(i)&&(i=s.decode(i)),Array.isArray(i)){if(i.length>e._fields.length)throw new Error("wrong number of fields in data");i.forEach(function(t,n){e[e._fields[n]]=r.toBuffer(t)})}else{if("object"!==(void 0===i?"undefined":n(i)))throw new Error("invalid data");var o=Object.keys(i);t.forEach(function(t){-1!==o.indexOf(t.name)&&(e[t.name]=i[t.name]),-1!==o.indexOf(t.alias)&&(e[t.alias]=i[t.alias])})}}},{assert:19,"bn.js":53,"create-hash":91,"ethjs-util":155,keccak:195,rlp:289,"safe-buffer":290,secp256k1:295}],142:[function(e,t,r){arguments[4][128][0].apply(r,arguments)},{_process:257,dup:128}],143:[function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t};Object.defineProperty(r,"__esModule",{value:!0});var a=e("./address"),s=e("./bignumber"),u=e("./bytes"),c=e("./utf8"),f=e("./properties"),h=o(e("./errors")),l=new RegExp(/^bytes([0-9]*)$/),d=new RegExp(/^(u?int)([0-9]*)$/),p=new RegExp(/^(.*)\[([0-9]*)\]$/);r.defaultCoerceFunc=function(e,t){var r=e.match(d);return r&&parseInt(r[2])<=48?t.toNumber():t};var b=new RegExp("^([^)(]*)\\((.*)\\)([^)(]*)$"),y=new RegExp("^[A-Za-z_][A-Za-z0-9_]*$");function m(e){return e.match(/^uint($|[^1-9])/)?e="uint256"+e.substring(4):e.match(/^int($|[^1-9])/)&&(e="int256"+e.substring(3)),e}function v(e,t){function r(t){throw new Error('unexpected character "'+e[t]+'" at position '+t+' in "'+e+'"')}for(var n={type:"",name:"",state:{allowType:!0}},i=n,o=0;o1){var i=r[1].match(b);if(""!=i[1].trim()||""!=i[3].trim())throw new Error("unexpected tokens");L(i[2]).forEach(function(e){t.outputs.push(v(e))})}return t}(e.trim()));throw new Error("unknown signature")};var w=function(){return function(e,t,r,n,i){this.coerceFunc=e,this.name=t,this.type=r,this.localName=n,this.dynamic=i}}(),_=function(e){function t(t){var r=e.call(this,t.coerceFunc,t.name,t.type,void 0,t.dynamic)||this;return f.defineReadOnly(r,"coder",t),r}return i(t,e),t.prototype.encode=function(e){return this.coder.encode(e)},t.prototype.decode=function(e,t){return this.coder.decode(e,t)},t}(w),A=function(e){function t(t,r){return e.call(this,t,"null","",r,!1)||this}return i(t,e),t.prototype.encode=function(e){return u.arrayify([])},t.prototype.decode=function(e,t){if(t>e.length)throw new Error("invalid null");return{consumed:0,value:this.coerceFunc("null",void 0)}},t}(w),E=function(e){function t(t,r,n,i){var o=this,a=(n?"int":"uint")+8*r;return(o=e.call(this,t,a,a,i,!1)||this).size=r,o.signed=n,o}return i(t,e),t.prototype.encode=function(e){try{var t=s.bigNumberify(e);return t=t.toTwos(8*this.size).maskn(8*this.size),this.signed&&(t=t.fromTwos(8*this.size).toTwos(256)),u.padZeros(u.arrayify(t),32)}catch(t){h.throwError("invalid number value",h.INVALID_ARGUMENT,{arg:this.localName,coderType:this.name,value:e})}return null},t.prototype.decode=function(e,t){e.length32)throw new Error;t.set(r)}catch(t){h.throwError("invalid "+this.name+" value",h.INVALID_ARGUMENT,{arg:this.localName,coderType:this.name,value:t.value||e})}return t},t.prototype.decode=function(e,t){return e.length=0?n:"")+"]",s=-1===n||r.dynamic;return(o=e.call(this,t,"array",a,i,s)||this).coder=r,o.length=n,o}return i(t,e),t.prototype.encode=function(e){Array.isArray(e)||h.throwError("expected array value",h.INVALID_ARGUMENT,{arg:this.localName,coderType:"array",value:e});var t=this.length,r=new Uint8Array(0);-1===t&&(t=e.length,r=x.encode(t)),h.checkArgumentCount(t,e.length,"in coder array"+(this.localName?" "+this.localName:""));for(var n=[],i=0;i256||i%8!=0)&&h.throwError("invalid "+r[1]+" bit length",h.INVALID_ARGUMENT,{arg:"param",value:t}),new E(e,i/8,"int"===r[1],t.name);if(r=t.type.match(l))return(0===(i=parseInt(r[1]))||i>32)&&h.throwError("invalid bytes length",h.INVALID_ARGUMENT,{arg:"param",value:t}),new S(e,i,t.name);if(r=t.type.match(p)){var i=parseInt(r[2]||"-1");return(t=f.jsonCopy(t)).type=r[1],new N(e,D(e,t),i,t.name)}return"tuple"===t.type.substring(0,5)?function(e,t,r){t||(t=[]);var n=[];return t.forEach(function(t){n.push(D(e,t))}),new R(e,n,r)}(e,t.components,t.name):""===t.type?new A(e,t.name):(h.throwError("invalid type",h.INVALID_ARGUMENT,{arg:"type",value:t.type}),null)}var F=function(){function e(t){h.checkNew(this,e),t||(t=r.defaultCoerceFunc),f.defineReadOnly(this,"coerceFunc",t)}return e.prototype.encode=function(e,t){e.length!==t.length&&h.throwError("types/values length mismatch",h.INVALID_ARGUMENT,{count:{types:e.length,values:t.length},value:{types:e,values:t}});var r=[];return e.forEach(function(e){var t=null;t="string"==typeof e?v(e):e,r.push(D(this.coerceFunc,t))},this),u.hexlify(new R(this.coerceFunc,r,"_").encode(t))},e.prototype.decode=function(e,t){var r=[];return e.forEach(function(e){var t=null;t="string"==typeof e?v(e):f.jsonCopy(e),r.push(D(this.coerceFunc,t))},this),new R(this.coerceFunc,r,"_").decode(u.arrayify(t),0).value},e}();r.AbiCoder=F,r.defaultAbiCoder=new F},{"./address":144,"./bignumber":145,"./bytes":146,"./errors":147,"./properties":149,"./utf8":152}],144:[function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0});var i=n(e("bn.js")),o=e("./bytes"),a=e("./keccak256"),s=e("./rlp"),u=e("./errors");function c(e){"string"==typeof e&&e.match(/^0x[0-9A-Fa-f]{40}$/)||u.throwError("invalid address",u.INVALID_ARGUMENT,{arg:"address",value:e});for(var t=(e=e.toLowerCase()).substring(2).split(""),r=new Uint8Array(40),n=0;n<40;n++)r[n]=t[n].charCodeAt(0);r=o.arrayify(a.keccak256(r));for(var i=0;i<40;i+=2)r[i>>1]>>4>=8&&(t[i]=t[i].toUpperCase()),(15&r[i>>1])>=8&&(t[i+1]=t[i+1].toUpperCase());return"0x"+t.join("")}for(var f={},h=0;h<10;h++)f[String(h)]=String(h);for(h=0;h<26;h++)f[String.fromCharCode(65+h)]=String(10+h);var l,d=Math.floor((l=9007199254740991,Math.log10?Math.log10(l):Math.log(l)/Math.LN10));function p(e){e=(e=e.toUpperCase()).substring(4)+e.substring(0,2)+"00";var t="";for(e.split("").forEach(function(e){t+=f[e]});t.length>=d;){var r=t.substring(0,d);t=parseInt(r,10)%97+t.substring(r.length)}for(var n=String(98-parseInt(t,10)%97);n.length<2;)n="0"+n;return n}function b(e){var t=null;if("string"!=typeof e&&u.throwError("invalid address",u.INVALID_ARGUMENT,{arg:"address",value:e}),e.match(/^(0x)?[0-9a-fA-F]{40}$/))"0x"!==e.substring(0,2)&&(e="0x"+e),t=c(e),e.match(/([A-F].*[a-f])|([a-f].*[A-F])/)&&t!==e&&u.throwError("bad address checksum",u.INVALID_ARGUMENT,{arg:"address",value:e});else if(e.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){for(e.substring(2,4)!==p(e)&&u.throwError("bad icap checksum",u.INVALID_ARGUMENT,{arg:"address",value:e}),t=new i.default.BN(e.substring(4),36).toString(16);t.length<40;)t="0"+t;t=c("0x"+t)}else u.throwError("invalid address",u.INVALID_ARGUMENT,{arg:"address",value:e});return t}r.getAddress=b,r.getIcapAddress=function(e){for(var t=new i.default.BN(b(e).substring(2),16).toString(36).toUpperCase();t.length<30;)t="0"+t;return"XE"+p("XE00"+t)+t},r.getContractAddress=function(e){if(!e.from)throw new Error("missing from address");var t=e.nonce;return b("0x"+a.keccak256(s.encode([b(e.from),o.stripZeros(o.hexlify(t))])).substring(26))}},{"./bytes":146,"./errors":147,"./keccak256":148,"./rlp":150,"bn.js":53}],145:[function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t};Object.defineProperty(r,"__esModule",{value:!0});var s=o(e("bn.js")),u=e("./bytes"),c=e("./properties"),f=e("./types"),h=a(e("./errors")),l=new s.default.BN(-1);function d(e){var t=e.toString(16);return"-"===t[0]?t.length%2==0?"-0x0"+t.substring(1):"-0x"+t.substring(1):t.length%2==1?"0x0"+t:"0x"+t}function p(e){return m(e)._bn}function b(e){return new y(d(e))}var y=function(e){function t(r){var n=e.call(this)||this;if(h.checkNew(n,t),"string"==typeof r)u.isHexString(r)?("0x"==r&&(r="0x0"),c.defineReadOnly(n,"_hex",r)):"-"===r[0]&&u.isHexString(r.substring(1))?c.defineReadOnly(n,"_hex",r):r.match(/^-?[0-9]*$/)?(""==r&&(r="0"),c.defineReadOnly(n,"_hex",d(new s.default.BN(r)))):h.throwError("invalid BigNumber string value",h.INVALID_ARGUMENT,{arg:"value",value:r});else if("number"==typeof r){parseInt(String(r))!==r&&h.throwError("underflow",h.NUMERIC_FAULT,{operation:"setValue",fault:"underflow",value:r,outputValue:parseInt(String(r))});try{c.defineReadOnly(n,"_hex",d(new s.default.BN(r)))}catch(e){h.throwError("overflow",h.NUMERIC_FAULT,{operation:"setValue",fault:"overflow",details:e.message})}}else r instanceof t?c.defineReadOnly(n,"_hex",r._hex):r.toHexString?c.defineReadOnly(n,"_hex",d(p(r.toHexString()))):u.isArrayish(r)?c.defineReadOnly(n,"_hex",d(new s.default.BN(u.hexlify(r).substring(2),16))):h.throwError("invalid BigNumber value",h.INVALID_ARGUMENT,{arg:"value",value:r});return n}return i(t,e),Object.defineProperty(t.prototype,"_bn",{get:function(){return"-"===this._hex[0]?new s.default.BN(this._hex.substring(3),16).mul(l):new s.default.BN(this._hex.substring(2),16)},enumerable:!0,configurable:!0}),t.prototype.fromTwos=function(e){return b(this._bn.fromTwos(e))},t.prototype.toTwos=function(e){return b(this._bn.toTwos(e))},t.prototype.add=function(e){return b(this._bn.add(p(e)))},t.prototype.sub=function(e){return b(this._bn.sub(p(e)))},t.prototype.div=function(e){return m(e).isZero()&&h.throwError("division by zero",h.NUMERIC_FAULT,{operation:"divide",fault:"division by zero"}),b(this._bn.div(p(e)))},t.prototype.mul=function(e){return b(this._bn.mul(p(e)))},t.prototype.mod=function(e){return b(this._bn.mod(p(e)))},t.prototype.pow=function(e){return b(this._bn.pow(p(e)))},t.prototype.maskn=function(e){return b(this._bn.maskn(e))},t.prototype.eq=function(e){return this._bn.eq(p(e))},t.prototype.lt=function(e){return this._bn.lt(p(e))},t.prototype.lte=function(e){return this._bn.lte(p(e))},t.prototype.gt=function(e){return this._bn.gt(p(e))},t.prototype.gte=function(e){return this._bn.gte(p(e))},t.prototype.isZero=function(){return this._bn.isZero()},t.prototype.toNumber=function(){try{return this._bn.toNumber()}catch(e){h.throwError("overflow",h.NUMERIC_FAULT,{operation:"setValue",fault:"overflow",details:e.message})}return null},t.prototype.toString=function(){return this._bn.toString(10)},t.prototype.toHexString=function(){return this._hex},t}(f.BigNumber);function m(e){return e instanceof y?e:new y(e)}r.bigNumberify=m,r.ConstantNegativeOne=m(-1),r.ConstantZero=m(0),r.ConstantOne=m(1),r.ConstantTwo=m(2),r.ConstantWeiPerEther=m("1000000000000000000")},{"./bytes":146,"./errors":147,"./properties":149,"./types":151,"bn.js":53}],146:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("./errors");function i(e){return!!e._bn}function o(e){return e.slice?e:(e.slice=function(){var t=Array.prototype.slice.call(arguments);return new Uint8Array(Array.prototype.slice.apply(e,t))},e)}function a(e){if(!e||parseInt(String(e.length))!=e.length||"string"==typeof e)return!1;for(var t=0;t=256||parseInt(String(r))!=r)return!1}return!0}function s(e){if(null==e&&n.throwError("cannot convert null value to array",n.INVALID_ARGUMENT,{arg:"value",value:e}),i(e)&&(e=e.toHexString()),"string"==typeof e){var t=e.match(/^(0x)?[0-9a-fA-F]*$/);t||n.throwError("invalid hexidecimal string",n.INVALID_ARGUMENT,{arg:"value",value:e}),"0x"!==t[1]&&n.throwError("hex string must have 0x prefix",n.INVALID_ARGUMENT,{arg:"value",value:e}),(e=e.substring(2)).length%2&&(e="0"+e);for(var r=[],s=0;s>4]+f[15&u])}return"0x"+o.join("")}return n.throwError("invalid hexlify value",null,{arg:"value",value:e}),"never"}function l(e,t){for(c(e)||n.throwError("invalid hex string",n.INVALID_ARGUMENT,{arg:"value",value:e});e.length<2*t+2;)e="0x0"+e.substring(2);return e}function d(e){var t,r=0,i="0x",o="0x";if((t=e)&&null!=t.r&&null!=t.s){null==e.v&&null==e.recoveryParam&&n.throwError("at least on of recoveryParam or v must be specified",n.INVALID_ARGUMENT,{argument:"signature",value:e}),i=l(e.r,32),o=l(e.s,32),"string"==typeof(r=e.v)&&(r=parseInt(r,16));var a=e.recoveryParam;null==a&&null!=e.v&&(a=1-r%2),r=27+a}else{var u=s(e);if(65!==u.length)throw new Error("invalid signature");i=h(u.slice(0,32)),o=h(u.slice(32,64)),27!==(r=u[64])&&28!==r&&(r=27+r%2)}return{r:i,s:o,recoveryParam:r-27,v:r}}r.hexlify=h,r.hexDataLength=function(e){return c(e)&&e.length%2==0?(e.length-2)/2:null},r.hexDataSlice=function(e,t,r){return c(e)||n.throwError("invalid hex data",n.INVALID_ARGUMENT,{arg:"value",value:e}),e.length%2!=0&&n.throwError("hex data length must be even",n.INVALID_ARGUMENT,{arg:"value",value:e}),t=2+2*t,null!=r?"0x"+e.substring(t,t+2*r):"0x"+e.substring(t)},r.hexStripZeros=function(e){for(c(e)||n.throwError("invalid hex string",n.INVALID_ARGUMENT,{arg:"value",value:e});e.length>3&&"0x0"===e.substring(0,3);)e="0x"+e.substring(3);return e},r.hexZeroPad=l,r.splitSignature=d,r.joinSignature=function(e){return h(u([(e=d(e)).r,e.s,e.recoveryParam?"0x1c":"0x1b"]))}},{"./errors":147}],147:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.UNKNOWN_ERROR="UNKNOWN_ERROR",r.NOT_IMPLEMENTED="NOT_IMPLEMENTED",r.MISSING_NEW="MISSING_NEW",r.CALL_EXCEPTION="CALL_EXCEPTION",r.INVALID_ARGUMENT="INVALID_ARGUMENT",r.MISSING_ARGUMENT="MISSING_ARGUMENT",r.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",r.NUMERIC_FAULT="NUMERIC_FAULT",r.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION";var n=!1,i=!1;function o(e,t,n){if(i)throw new Error("unknown error");t||(t=r.UNKNOWN_ERROR),n||(n={});var o=[];Object.keys(n).forEach(function(e){try{o.push(e+"="+JSON.stringify(n[e]))}catch(t){o.push(e+"="+JSON.stringify(n[e].toString()))}});var a=e;o.length&&(e+=" ("+o.join(", ")+")");var s=new Error(e);throw s.reason=a,s.code=t,Object.keys(n).forEach(function(e){s[e]=n[e]}),s}r.throwError=o,r.checkNew=function(e,t){e instanceof t||o("missing new",r.MISSING_NEW,{name:t.name})},r.checkArgumentCount=function(e,t,n){n||(n=""),et&&o("too many arguments"+n,r.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})},r.setCensorship=function(e,t){n&&o("error censorship permanent",r.UNSUPPORTED_OPERATION,{operation:"setCersorship"}),i=!!e,n=!!t}},{}],148:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("js-sha3"),i=e("./bytes");r.keccak256=function(e){return"0x"+n.keccak_256(i.arrayify(e))}},{"./bytes":146,"js-sha3":142}],149:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.defineReadOnly=function(e,t,r){Object.defineProperty(e,t,{enumerable:!0,value:r,writable:!1})},r.defineFrozen=function(e,t,r){var n=JSON.stringify(r);Object.defineProperty(e,t,{enumerable:!0,get:function(){return JSON.parse(n)}})},r.resolveProperties=function(e){var t={},r=[];return Object.keys(e).forEach(function(n){var i=e[n];i instanceof Promise?r.push(i.then(function(e){return t[n]=e,null})):t[n]=i}),Promise.all(r).then(function(){return t})},r.shallowCopy=function(e){var t={};for(var r in e)t[r]=e[r];return t},r.jsonCopy=function(e){return JSON.parse(JSON.stringify(e))}},{}],150:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("./bytes");function i(e){for(var t=[];e;)t.unshift(255&e),e>>=8;return t}function o(e,t,r){for(var n=0,i=0;it+1+n)throw new Error("invalid rlp")}return{consumed:1+n,result:i}}function s(e,t){if(0===e.length)throw new Error("invalid rlp data");if(e[t]>=248){if(t+1+(r=e[t]-247)>e.length)throw new Error("too short");if(t+1+r+(i=o(e,t+1,r))>e.length)throw new Error("to short");return a(e,t,t+1+r,r+i)}if(e[t]>=192){if(t+1+(i=e[t]-192)>e.length)throw new Error("invalid rlp data");return a(e,t,t+1,i)}if(e[t]>=184){var r;if(t+1+(r=e[t]-183)>e.length)throw new Error("invalid rlp data");if(t+1+r+(i=o(e,t+1,r))>e.length)throw new Error("invalid rlp data");return{consumed:1+r+i,result:n.hexlify(e.slice(t+1+r,t+1+r+i))}}if(e[t]>=128){var i;if(t+1+(i=e[t]-128)>e.length)throw new Error("invlaid rlp data");return{consumed:1+i,result:n.hexlify(e.slice(t+1,t+1+i))}}return{consumed:1,result:n.hexlify(e[t])}}r.encode=function(e){return n.hexlify(function e(t){if(Array.isArray(t)){var r=[];return t.forEach(function(t){r=r.concat(e(t))}),r.length<=55?(r.unshift(192+r.length),r):((o=i(r.length)).unshift(247+o.length),o.concat(r))}var o,a=Array.prototype.slice.call(n.arrayify(t));return 1===a.length&&a[0]<=127?a:a.length<=55?(a.unshift(128+a.length),a):((o=i(a.length)).unshift(183+o.length),o.concat(a))}(e))},r.decode=function(e){var t=n.arrayify(e),r=s(t,0);if(r.consumed!==t.length)throw new Error("invalid rlp data");return r.result}},{"./bytes":146}],151:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=function(){return function(){}}();r.BigNumber=n;var i=function(){return function(){}}();r.Indexed=i;var o=function(){return function(){}}();r.MinimalProvider=o;var a=function(){return function(){}}();r.Signer=a;var s=function(){return function(){}}();r.HDNode=s},{}],152:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n,i=e("./bytes");!function(e){e.current="",e.NFC="NFC",e.NFD="NFD",e.NFKC="NFKC",e.NFKD="NFKD"}(n=r.UnicodeNormalizationForm||(r.UnicodeNormalizationForm={})),r.toUtf8Bytes=function(e,t){void 0===t&&(t=n.current),t!=n.current&&(e=e.normalize(t));for(var r=[],o=0,a=0;a>6|192,r[o++]=63&s|128):55296==(64512&s)&&a+1>18|240,r[o++]=s>>12&63|128,r[o++]=s>>6&63|128,r[o++]=63&s|128):(r[o++]=s>>12|224,r[o++]=s>>6&63|128,r[o++]=63&s|128)}return i.arrayify(r)},r.toUtf8String=function(e){e=i.arrayify(e);for(var t="",r=0;r>7!=0){if(n>>6!=2){var o=null;if(n>>5==6)o=1;else if(n>>4==14)o=2;else if(n>>3==30)o=3;else if(n>>2==62)o=4;else{if(n>>1!=126)continue;o=5}if(r+o>e.length){for(;r>6==2;r++);if(r!=e.length)continue;return t}var a,s=n&(1<<8-o-1)-1;for(a=0;a>6!=2)break;s=s<<6|63&u}a==o?s<=65535?t+=String.fromCharCode(s):(s-=65536,t+=String.fromCharCode(55296+(s>>10&1023),56320+(1023&s))):r--}}else t+=String.fromCharCode(n)}return t}},{"./bytes":146}],153:[function(e,t,r){"use strict";var n=e("bn.js"),i=e("number-to-bn"),o=new n(0),a=new n(-1),s={noether:"0",wei:"1",kwei:"1000",Kwei:"1000",babbage:"1000",femtoether:"1000",mwei:"1000000",Mwei:"1000000",lovelace:"1000000",picoether:"1000000",gwei:"1000000000",Gwei:"1000000000",shannon:"1000000000",nanoether:"1000000000",nano:"1000000000",szabo:"1000000000000",microether:"1000000000000",micro:"1000000000000",finney:"1000000000000000",milliether:"1000000000000000",milli:"1000000000000000",ether:"1000000000000000000",kether:"1000000000000000000000",grand:"1000000000000000000000",mether:"1000000000000000000000000",gether:"1000000000000000000000000000",tether:"1000000000000000000000000000000"};function u(e){var t=e?e.toLowerCase():"ether",r=s[t];if("string"!=typeof r)throw new Error("[ethjs-unit] the unit provided "+e+" doesn't exists, please use the one of the following units "+JSON.stringify(s,null,2));return new n(r,10)}function c(e){if("string"==typeof e){if(!e.match(/^-?[0-9.]+$/))throw new Error("while converting number to string, invalid number value '"+e+"', should be a number matching (^-?[0-9.]+).");return e}if("number"==typeof e)return String(e);if("object"==typeof e&&e.toString&&(e.toTwos||e.dividedToIntegerBy))return e.toPrecision?String(e.toPrecision()):e.toString(10);throw new Error("while converting number to string, invalid number value '"+e+"' type "+typeof e+".")}t.exports={unitMap:s,numberToString:c,getValueOfUnit:u,fromWei:function(e,t,r){var n=i(e),c=n.lt(o),f=u(t),h=s[t].length-1||1,l=r||{};c&&(n=n.mul(a));for(var d=n.mod(f).toString(10);d.length2)throw new Error("[ethjs-unit] while converting number "+e+" to wei, too many decimal points");var l=h[0],d=h[1];if(l||(l="0"),d||(d="0"),d.length>o)throw new Error("[ethjs-unit] while converting number "+e+" to wei, too many decimal places");for(;d.length=49&&a<=54?a-49+10:a>=17&&a<=22?a-17+10:15&a}return n}function u(e,t,r,n){for(var i=0,o=Math.min(e.length,r),a=t;a=49?s-49+10:s>=17?s-17+10:s}return i}o.isBN=function(e){return e instanceof o||null!==e&&"object"==typeof e&&e.constructor.wordSize===o.wordSize&&Array.isArray(e.words)},o.max=function(e,t){return e.cmp(t)>0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&i++,16===t?this._parseHex(e,i):this._parseBase(e,t,i),"-"===e[0]&&(this.negative=1),this.strip(),"le"===r&&this._initArray(this.toArray(),t,r)},o.prototype._initNumber=function(e,t,r){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(n(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===r&&this._initArray(this.toArray(),t,r)},o.prototype._initArray=function(e,t,r){if(n("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3)a=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[o]|=a<>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);else if("le"===r)for(i=0,o=0;i>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);return this.strip()},o.prototype._parseHex=function(e,t){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var r=0;r=t;r-=6)i=s(e,r,r+6),this.words[n]|=i<>>26-o&4194303,(o+=24)>=26&&(o-=26,n++);r+6!==t&&(i=s(e,t,r+6),this.words[n]|=i<>>26-o&4194303),this.strip()},o.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=t)n++;n--,i=i/t|0;for(var o=e.length-r,a=o%n,s=Math.min(o,o-a)+r,c=0,f=r;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},o.prototype.inspect=function(){return(this.red?""};var c=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],f=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],h=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(e,t,r){r.negative=t.negative^e.negative;var n=e.length+t.length|0;r.length=n,n=n-1|0;var i=0|e.words[0],o=0|t.words[0],a=i*o,s=67108863&a,u=a/67108864|0;r.words[0]=s;for(var c=1;c>>26,h=67108863&u,l=Math.min(c,t.length-1),d=Math.max(0,c-e.length+1);d<=l;d++){var p=c-d|0;f+=(a=(i=0|e.words[p])*(o=0|t.words[d])+h)/67108864|0,h=67108863&a}r.words[c]=0|h,u=0|f}return 0!==u?r.words[c]=0|u:r.length--,r.strip()}o.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var i=0,o=0,a=0;a>>24-i&16777215)||a!==this.length-1?c[6-u.length]+u+r:u+r,(i+=2)>=26&&(i-=26,a--)}for(0!==o&&(r=o.toString(16)+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var l=f[e],d=h[e];r="";var p=this.clone();for(p.negative=0;!p.isZero();){var b=p.modn(d).toString(e);r=(p=p.idivn(d)).isZero()?b+r:c[l-b.length]+b+r}for(this.isZero()&&(r="0"+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16)},o.prototype.toBuffer=function(e,t){return n(void 0!==a),this.toArrayLike(a,e,t)},o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},o.prototype.toArrayLike=function(e,t,r){var i=this.byteLength(),o=r||Math.max(1,i);n(i<=o,"byte array longer than desired length"),n(o>0,"Requested array length <= 0"),this.strip();var a,s,u="le"===t,c=new e(o),f=this.clone();if(u){for(s=0;!f.isZero();s++)a=f.andln(255),f.iushrn(8),c[s]=a;for(;s=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;re.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,r;this.length>e.length?(t=this,r=e):(t=e,r=this);for(var n=0;ne.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-r),this.strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,i=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<e.length?(r=this,n=e):(r=e,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;oe.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var r,n,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=e):(r=e,n=this);for(var o=0,a=0;a>26,this.words[a]=67108863&t;for(;0!==o&&a>26,this.words[a]=67108863&t;if(0===o&&a>>13,d=0|a[1],p=8191&d,b=d>>>13,y=0|a[2],m=8191&y,v=y>>>13,g=0|a[3],w=8191&g,_=g>>>13,A=0|a[4],E=8191&A,x=A>>>13,k=0|a[5],S=8191&k,M=k>>>13,I=0|a[6],T=8191&I,U=I>>>13,j=0|a[7],B=8191&j,P=j>>>13,C=0|a[8],N=8191&C,R=C>>>13,L=0|a[9],O=8191&L,D=L>>>13,F=0|s[0],q=8191&F,H=F>>>13,z=0|s[1],K=8191&z,V=z>>>13,G=0|s[2],W=8191&G,Y=G>>>13,X=0|s[3],Z=8191&X,J=X>>>13,$=0|s[4],Q=8191&$,ee=$>>>13,te=0|s[5],re=8191&te,ne=te>>>13,ie=0|s[6],oe=8191&ie,ae=ie>>>13,se=0|s[7],ue=8191&se,ce=se>>>13,fe=0|s[8],he=8191&fe,le=fe>>>13,de=0|s[9],pe=8191&de,be=de>>>13;r.negative=e.negative^t.negative,r.length=19;var ye=(c+(n=Math.imul(h,q))|0)+((8191&(i=(i=Math.imul(h,H))+Math.imul(l,q)|0))<<13)|0;c=((o=Math.imul(l,H))+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,n=Math.imul(p,q),i=(i=Math.imul(p,H))+Math.imul(b,q)|0,o=Math.imul(b,H);var me=(c+(n=n+Math.imul(h,K)|0)|0)+((8191&(i=(i=i+Math.imul(h,V)|0)+Math.imul(l,K)|0))<<13)|0;c=((o=o+Math.imul(l,V)|0)+(i>>>13)|0)+(me>>>26)|0,me&=67108863,n=Math.imul(m,q),i=(i=Math.imul(m,H))+Math.imul(v,q)|0,o=Math.imul(v,H),n=n+Math.imul(p,K)|0,i=(i=i+Math.imul(p,V)|0)+Math.imul(b,K)|0,o=o+Math.imul(b,V)|0;var ve=(c+(n=n+Math.imul(h,W)|0)|0)+((8191&(i=(i=i+Math.imul(h,Y)|0)+Math.imul(l,W)|0))<<13)|0;c=((o=o+Math.imul(l,Y)|0)+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,n=Math.imul(w,q),i=(i=Math.imul(w,H))+Math.imul(_,q)|0,o=Math.imul(_,H),n=n+Math.imul(m,K)|0,i=(i=i+Math.imul(m,V)|0)+Math.imul(v,K)|0,o=o+Math.imul(v,V)|0,n=n+Math.imul(p,W)|0,i=(i=i+Math.imul(p,Y)|0)+Math.imul(b,W)|0,o=o+Math.imul(b,Y)|0;var ge=(c+(n=n+Math.imul(h,Z)|0)|0)+((8191&(i=(i=i+Math.imul(h,J)|0)+Math.imul(l,Z)|0))<<13)|0;c=((o=o+Math.imul(l,J)|0)+(i>>>13)|0)+(ge>>>26)|0,ge&=67108863,n=Math.imul(E,q),i=(i=Math.imul(E,H))+Math.imul(x,q)|0,o=Math.imul(x,H),n=n+Math.imul(w,K)|0,i=(i=i+Math.imul(w,V)|0)+Math.imul(_,K)|0,o=o+Math.imul(_,V)|0,n=n+Math.imul(m,W)|0,i=(i=i+Math.imul(m,Y)|0)+Math.imul(v,W)|0,o=o+Math.imul(v,Y)|0,n=n+Math.imul(p,Z)|0,i=(i=i+Math.imul(p,J)|0)+Math.imul(b,Z)|0,o=o+Math.imul(b,J)|0;var we=(c+(n=n+Math.imul(h,Q)|0)|0)+((8191&(i=(i=i+Math.imul(h,ee)|0)+Math.imul(l,Q)|0))<<13)|0;c=((o=o+Math.imul(l,ee)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,n=Math.imul(S,q),i=(i=Math.imul(S,H))+Math.imul(M,q)|0,o=Math.imul(M,H),n=n+Math.imul(E,K)|0,i=(i=i+Math.imul(E,V)|0)+Math.imul(x,K)|0,o=o+Math.imul(x,V)|0,n=n+Math.imul(w,W)|0,i=(i=i+Math.imul(w,Y)|0)+Math.imul(_,W)|0,o=o+Math.imul(_,Y)|0,n=n+Math.imul(m,Z)|0,i=(i=i+Math.imul(m,J)|0)+Math.imul(v,Z)|0,o=o+Math.imul(v,J)|0,n=n+Math.imul(p,Q)|0,i=(i=i+Math.imul(p,ee)|0)+Math.imul(b,Q)|0,o=o+Math.imul(b,ee)|0;var _e=(c+(n=n+Math.imul(h,re)|0)|0)+((8191&(i=(i=i+Math.imul(h,ne)|0)+Math.imul(l,re)|0))<<13)|0;c=((o=o+Math.imul(l,ne)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,n=Math.imul(T,q),i=(i=Math.imul(T,H))+Math.imul(U,q)|0,o=Math.imul(U,H),n=n+Math.imul(S,K)|0,i=(i=i+Math.imul(S,V)|0)+Math.imul(M,K)|0,o=o+Math.imul(M,V)|0,n=n+Math.imul(E,W)|0,i=(i=i+Math.imul(E,Y)|0)+Math.imul(x,W)|0,o=o+Math.imul(x,Y)|0,n=n+Math.imul(w,Z)|0,i=(i=i+Math.imul(w,J)|0)+Math.imul(_,Z)|0,o=o+Math.imul(_,J)|0,n=n+Math.imul(m,Q)|0,i=(i=i+Math.imul(m,ee)|0)+Math.imul(v,Q)|0,o=o+Math.imul(v,ee)|0,n=n+Math.imul(p,re)|0,i=(i=i+Math.imul(p,ne)|0)+Math.imul(b,re)|0,o=o+Math.imul(b,ne)|0;var Ae=(c+(n=n+Math.imul(h,oe)|0)|0)+((8191&(i=(i=i+Math.imul(h,ae)|0)+Math.imul(l,oe)|0))<<13)|0;c=((o=o+Math.imul(l,ae)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,n=Math.imul(B,q),i=(i=Math.imul(B,H))+Math.imul(P,q)|0,o=Math.imul(P,H),n=n+Math.imul(T,K)|0,i=(i=i+Math.imul(T,V)|0)+Math.imul(U,K)|0,o=o+Math.imul(U,V)|0,n=n+Math.imul(S,W)|0,i=(i=i+Math.imul(S,Y)|0)+Math.imul(M,W)|0,o=o+Math.imul(M,Y)|0,n=n+Math.imul(E,Z)|0,i=(i=i+Math.imul(E,J)|0)+Math.imul(x,Z)|0,o=o+Math.imul(x,J)|0,n=n+Math.imul(w,Q)|0,i=(i=i+Math.imul(w,ee)|0)+Math.imul(_,Q)|0,o=o+Math.imul(_,ee)|0,n=n+Math.imul(m,re)|0,i=(i=i+Math.imul(m,ne)|0)+Math.imul(v,re)|0,o=o+Math.imul(v,ne)|0,n=n+Math.imul(p,oe)|0,i=(i=i+Math.imul(p,ae)|0)+Math.imul(b,oe)|0,o=o+Math.imul(b,ae)|0;var Ee=(c+(n=n+Math.imul(h,ue)|0)|0)+((8191&(i=(i=i+Math.imul(h,ce)|0)+Math.imul(l,ue)|0))<<13)|0;c=((o=o+Math.imul(l,ce)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,n=Math.imul(N,q),i=(i=Math.imul(N,H))+Math.imul(R,q)|0,o=Math.imul(R,H),n=n+Math.imul(B,K)|0,i=(i=i+Math.imul(B,V)|0)+Math.imul(P,K)|0,o=o+Math.imul(P,V)|0,n=n+Math.imul(T,W)|0,i=(i=i+Math.imul(T,Y)|0)+Math.imul(U,W)|0,o=o+Math.imul(U,Y)|0,n=n+Math.imul(S,Z)|0,i=(i=i+Math.imul(S,J)|0)+Math.imul(M,Z)|0,o=o+Math.imul(M,J)|0,n=n+Math.imul(E,Q)|0,i=(i=i+Math.imul(E,ee)|0)+Math.imul(x,Q)|0,o=o+Math.imul(x,ee)|0,n=n+Math.imul(w,re)|0,i=(i=i+Math.imul(w,ne)|0)+Math.imul(_,re)|0,o=o+Math.imul(_,ne)|0,n=n+Math.imul(m,oe)|0,i=(i=i+Math.imul(m,ae)|0)+Math.imul(v,oe)|0,o=o+Math.imul(v,ae)|0,n=n+Math.imul(p,ue)|0,i=(i=i+Math.imul(p,ce)|0)+Math.imul(b,ue)|0,o=o+Math.imul(b,ce)|0;var xe=(c+(n=n+Math.imul(h,he)|0)|0)+((8191&(i=(i=i+Math.imul(h,le)|0)+Math.imul(l,he)|0))<<13)|0;c=((o=o+Math.imul(l,le)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,n=Math.imul(O,q),i=(i=Math.imul(O,H))+Math.imul(D,q)|0,o=Math.imul(D,H),n=n+Math.imul(N,K)|0,i=(i=i+Math.imul(N,V)|0)+Math.imul(R,K)|0,o=o+Math.imul(R,V)|0,n=n+Math.imul(B,W)|0,i=(i=i+Math.imul(B,Y)|0)+Math.imul(P,W)|0,o=o+Math.imul(P,Y)|0,n=n+Math.imul(T,Z)|0,i=(i=i+Math.imul(T,J)|0)+Math.imul(U,Z)|0,o=o+Math.imul(U,J)|0,n=n+Math.imul(S,Q)|0,i=(i=i+Math.imul(S,ee)|0)+Math.imul(M,Q)|0,o=o+Math.imul(M,ee)|0,n=n+Math.imul(E,re)|0,i=(i=i+Math.imul(E,ne)|0)+Math.imul(x,re)|0,o=o+Math.imul(x,ne)|0,n=n+Math.imul(w,oe)|0,i=(i=i+Math.imul(w,ae)|0)+Math.imul(_,oe)|0,o=o+Math.imul(_,ae)|0,n=n+Math.imul(m,ue)|0,i=(i=i+Math.imul(m,ce)|0)+Math.imul(v,ue)|0,o=o+Math.imul(v,ce)|0,n=n+Math.imul(p,he)|0,i=(i=i+Math.imul(p,le)|0)+Math.imul(b,he)|0,o=o+Math.imul(b,le)|0;var ke=(c+(n=n+Math.imul(h,pe)|0)|0)+((8191&(i=(i=i+Math.imul(h,be)|0)+Math.imul(l,pe)|0))<<13)|0;c=((o=o+Math.imul(l,be)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,n=Math.imul(O,K),i=(i=Math.imul(O,V))+Math.imul(D,K)|0,o=Math.imul(D,V),n=n+Math.imul(N,W)|0,i=(i=i+Math.imul(N,Y)|0)+Math.imul(R,W)|0,o=o+Math.imul(R,Y)|0,n=n+Math.imul(B,Z)|0,i=(i=i+Math.imul(B,J)|0)+Math.imul(P,Z)|0,o=o+Math.imul(P,J)|0,n=n+Math.imul(T,Q)|0,i=(i=i+Math.imul(T,ee)|0)+Math.imul(U,Q)|0,o=o+Math.imul(U,ee)|0,n=n+Math.imul(S,re)|0,i=(i=i+Math.imul(S,ne)|0)+Math.imul(M,re)|0,o=o+Math.imul(M,ne)|0,n=n+Math.imul(E,oe)|0,i=(i=i+Math.imul(E,ae)|0)+Math.imul(x,oe)|0,o=o+Math.imul(x,ae)|0,n=n+Math.imul(w,ue)|0,i=(i=i+Math.imul(w,ce)|0)+Math.imul(_,ue)|0,o=o+Math.imul(_,ce)|0,n=n+Math.imul(m,he)|0,i=(i=i+Math.imul(m,le)|0)+Math.imul(v,he)|0,o=o+Math.imul(v,le)|0;var Se=(c+(n=n+Math.imul(p,pe)|0)|0)+((8191&(i=(i=i+Math.imul(p,be)|0)+Math.imul(b,pe)|0))<<13)|0;c=((o=o+Math.imul(b,be)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,n=Math.imul(O,W),i=(i=Math.imul(O,Y))+Math.imul(D,W)|0,o=Math.imul(D,Y),n=n+Math.imul(N,Z)|0,i=(i=i+Math.imul(N,J)|0)+Math.imul(R,Z)|0,o=o+Math.imul(R,J)|0,n=n+Math.imul(B,Q)|0,i=(i=i+Math.imul(B,ee)|0)+Math.imul(P,Q)|0,o=o+Math.imul(P,ee)|0,n=n+Math.imul(T,re)|0,i=(i=i+Math.imul(T,ne)|0)+Math.imul(U,re)|0,o=o+Math.imul(U,ne)|0,n=n+Math.imul(S,oe)|0,i=(i=i+Math.imul(S,ae)|0)+Math.imul(M,oe)|0,o=o+Math.imul(M,ae)|0,n=n+Math.imul(E,ue)|0,i=(i=i+Math.imul(E,ce)|0)+Math.imul(x,ue)|0,o=o+Math.imul(x,ce)|0,n=n+Math.imul(w,he)|0,i=(i=i+Math.imul(w,le)|0)+Math.imul(_,he)|0,o=o+Math.imul(_,le)|0;var Me=(c+(n=n+Math.imul(m,pe)|0)|0)+((8191&(i=(i=i+Math.imul(m,be)|0)+Math.imul(v,pe)|0))<<13)|0;c=((o=o+Math.imul(v,be)|0)+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863,n=Math.imul(O,Z),i=(i=Math.imul(O,J))+Math.imul(D,Z)|0,o=Math.imul(D,J),n=n+Math.imul(N,Q)|0,i=(i=i+Math.imul(N,ee)|0)+Math.imul(R,Q)|0,o=o+Math.imul(R,ee)|0,n=n+Math.imul(B,re)|0,i=(i=i+Math.imul(B,ne)|0)+Math.imul(P,re)|0,o=o+Math.imul(P,ne)|0,n=n+Math.imul(T,oe)|0,i=(i=i+Math.imul(T,ae)|0)+Math.imul(U,oe)|0,o=o+Math.imul(U,ae)|0,n=n+Math.imul(S,ue)|0,i=(i=i+Math.imul(S,ce)|0)+Math.imul(M,ue)|0,o=o+Math.imul(M,ce)|0,n=n+Math.imul(E,he)|0,i=(i=i+Math.imul(E,le)|0)+Math.imul(x,he)|0,o=o+Math.imul(x,le)|0;var Ie=(c+(n=n+Math.imul(w,pe)|0)|0)+((8191&(i=(i=i+Math.imul(w,be)|0)+Math.imul(_,pe)|0))<<13)|0;c=((o=o+Math.imul(_,be)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,n=Math.imul(O,Q),i=(i=Math.imul(O,ee))+Math.imul(D,Q)|0,o=Math.imul(D,ee),n=n+Math.imul(N,re)|0,i=(i=i+Math.imul(N,ne)|0)+Math.imul(R,re)|0,o=o+Math.imul(R,ne)|0,n=n+Math.imul(B,oe)|0,i=(i=i+Math.imul(B,ae)|0)+Math.imul(P,oe)|0,o=o+Math.imul(P,ae)|0,n=n+Math.imul(T,ue)|0,i=(i=i+Math.imul(T,ce)|0)+Math.imul(U,ue)|0,o=o+Math.imul(U,ce)|0,n=n+Math.imul(S,he)|0,i=(i=i+Math.imul(S,le)|0)+Math.imul(M,he)|0,o=o+Math.imul(M,le)|0;var Te=(c+(n=n+Math.imul(E,pe)|0)|0)+((8191&(i=(i=i+Math.imul(E,be)|0)+Math.imul(x,pe)|0))<<13)|0;c=((o=o+Math.imul(x,be)|0)+(i>>>13)|0)+(Te>>>26)|0,Te&=67108863,n=Math.imul(O,re),i=(i=Math.imul(O,ne))+Math.imul(D,re)|0,o=Math.imul(D,ne),n=n+Math.imul(N,oe)|0,i=(i=i+Math.imul(N,ae)|0)+Math.imul(R,oe)|0,o=o+Math.imul(R,ae)|0,n=n+Math.imul(B,ue)|0,i=(i=i+Math.imul(B,ce)|0)+Math.imul(P,ue)|0,o=o+Math.imul(P,ce)|0,n=n+Math.imul(T,he)|0,i=(i=i+Math.imul(T,le)|0)+Math.imul(U,he)|0,o=o+Math.imul(U,le)|0;var Ue=(c+(n=n+Math.imul(S,pe)|0)|0)+((8191&(i=(i=i+Math.imul(S,be)|0)+Math.imul(M,pe)|0))<<13)|0;c=((o=o+Math.imul(M,be)|0)+(i>>>13)|0)+(Ue>>>26)|0,Ue&=67108863,n=Math.imul(O,oe),i=(i=Math.imul(O,ae))+Math.imul(D,oe)|0,o=Math.imul(D,ae),n=n+Math.imul(N,ue)|0,i=(i=i+Math.imul(N,ce)|0)+Math.imul(R,ue)|0,o=o+Math.imul(R,ce)|0,n=n+Math.imul(B,he)|0,i=(i=i+Math.imul(B,le)|0)+Math.imul(P,he)|0,o=o+Math.imul(P,le)|0;var je=(c+(n=n+Math.imul(T,pe)|0)|0)+((8191&(i=(i=i+Math.imul(T,be)|0)+Math.imul(U,pe)|0))<<13)|0;c=((o=o+Math.imul(U,be)|0)+(i>>>13)|0)+(je>>>26)|0,je&=67108863,n=Math.imul(O,ue),i=(i=Math.imul(O,ce))+Math.imul(D,ue)|0,o=Math.imul(D,ce),n=n+Math.imul(N,he)|0,i=(i=i+Math.imul(N,le)|0)+Math.imul(R,he)|0,o=o+Math.imul(R,le)|0;var Be=(c+(n=n+Math.imul(B,pe)|0)|0)+((8191&(i=(i=i+Math.imul(B,be)|0)+Math.imul(P,pe)|0))<<13)|0;c=((o=o+Math.imul(P,be)|0)+(i>>>13)|0)+(Be>>>26)|0,Be&=67108863,n=Math.imul(O,he),i=(i=Math.imul(O,le))+Math.imul(D,he)|0,o=Math.imul(D,le);var Pe=(c+(n=n+Math.imul(N,pe)|0)|0)+((8191&(i=(i=i+Math.imul(N,be)|0)+Math.imul(R,pe)|0))<<13)|0;c=((o=o+Math.imul(R,be)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863;var Ce=(c+(n=Math.imul(O,pe))|0)+((8191&(i=(i=Math.imul(O,be))+Math.imul(D,pe)|0))<<13)|0;return c=((o=Math.imul(D,be))+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,u[0]=ye,u[1]=me,u[2]=ve,u[3]=ge,u[4]=we,u[5]=_e,u[6]=Ae,u[7]=Ee,u[8]=xe,u[9]=ke,u[10]=Se,u[11]=Me,u[12]=Ie,u[13]=Te,u[14]=Ue,u[15]=je,u[16]=Be,u[17]=Pe,u[18]=Ce,0!==c&&(u[19]=c,r.length++),r};function p(e,t,r){return(new b).mulp(e,t,r)}function b(e,t){this.x=e,this.y=t}Math.imul||(d=l),o.prototype.mulTo=function(e,t){var r=this.length+e.length;return 10===this.length&&10===e.length?d(this,e,t):r<63?l(this,e,t):r<1024?function(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,a&=67108863}r.words[o]=s,n=a,a=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,e,t):p(this,e,t)},b.prototype.makeRBT=function(e){for(var t=new Array(e),r=o.prototype._countBits(e)-1,n=0;n>=1;return n},b.prototype.permute=function(e,t,r,n,i,o){for(var a=0;a>>=1)i++;return 1<>>=13,r[2*a+1]=8191&o,o>>>=13;for(a=2*t;a>=26,t+=i/67108864|0,t+=o>>>26,this.words[r]=67108863&o}return 0!==t&&(this.words[r]=t,this.length++),this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),r=0;r>>i}return t}(e);if(0===t.length)return new o(1);for(var r=this,n=0;n=0);var t,r=e%26,i=(e-r)/26,o=67108863>>>26-r<<26-r;if(0!==r){var a=0;for(t=0;t>>26-r}a&&(this.words[t]=a,this.length++)}if(0!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t=0),i=t?(t-t%26)/26:0;var o=e%26,a=Math.min((e-o)/26,this.length),s=67108863^67108863>>>o<a)for(this.length-=a,c=0;c=0&&(0!==f||c>=i);c--){var h=0|this.words[c];this.words[c]=f<<26-o|h>>>o,f=h&s}return u&&0!==f&&(u.words[u.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},o.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,i=1<=0);var t=e%26,r=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var i=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(u/67108864|0),this.words[i+r]=67108863&o}for(;i>26,this.words[i+r]=67108863&o;if(0===s)return this.strip();for(n(-1===s),s=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},o.prototype._wordDiv=function(e,t){var r=(this.length,e.length),n=this.clone(),i=e,a=0|i.words[i.length-1];0!==(r=26-this._countBits(a))&&(i=i.ushln(r),n.iushln(r),a=0|i.words[i.length-1]);var s,u=n.length-i.length;if("mod"!==t){(s=new o(null)).length=u+1,s.words=new Array(s.length);for(var c=0;c=0;h--){var l=67108864*(0|n.words[i.length+h])+(0|n.words[i.length+h-1]);for(l=Math.min(l/a|0,67108863),n._ishlnsubmul(i,l,h);0!==n.negative;)l--,n.negative=0,n._ishlnsubmul(i,1,h),n.isZero()||(n.negative^=1);s&&(s.words[h]=l)}return s&&s.strip(),n.strip(),"div"!==t&&0!==r&&n.iushrn(r),{div:s||null,mod:n}},o.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(s=this.neg().divmod(e,t),"mod"!==t&&(i=s.div.neg()),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.iadd(e)),{div:i,mod:a}):0===this.negative&&0!==e.negative?(s=this.divmod(e.neg(),t),"mod"!==t&&(i=s.div.neg()),{div:i,mod:s.mod}):0!=(this.negative&e.negative)?(s=this.neg().divmod(e.neg(),t),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.isub(e)),{div:s.div,mod:a}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modn(e.words[0]))}:this._wordDiv(e,t);var i,a,s},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=0!==t.div.negative?t.mod.isub(e):t.mod,n=e.ushrn(1),i=e.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modn=function(e){n(e<=67108863);for(var t=(1<<26)%e,r=0,i=this.length-1;i>=0;i--)r=(t*r+(0|this.words[i]))%e;return r},o.prototype.idivn=function(e){n(e<=67108863);for(var t=0,r=this.length-1;r>=0;r--){var i=(0|this.words[r])+67108864*t;this.words[r]=i/e|0,t=i%e}return this.strip()},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new o(1),a=new o(0),s=new o(0),u=new o(1),c=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++c;for(var f=r.clone(),h=t.clone();!t.isZero();){for(var l=0,d=1;0==(t.words[0]&d)&&l<26;++l,d<<=1);if(l>0)for(t.iushrn(l);l-- >0;)(i.isOdd()||a.isOdd())&&(i.iadd(f),a.isub(h)),i.iushrn(1),a.iushrn(1);for(var p=0,b=1;0==(r.words[0]&b)&&p<26;++p,b<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(s.isOdd()||u.isOdd())&&(s.iadd(f),u.isub(h)),s.iushrn(1),u.iushrn(1);t.cmp(r)>=0?(t.isub(r),i.isub(s),a.isub(u)):(r.isub(t),s.isub(i),u.isub(a))}return{a:s,b:u,gcd:r.iushln(c)}},o.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,a=new o(1),s=new o(0),u=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var c=0,f=1;0==(t.words[0]&f)&&c<26;++c,f<<=1);if(c>0)for(t.iushrn(c);c-- >0;)a.isOdd()&&a.iadd(u),a.iushrn(1);for(var h=0,l=1;0==(r.words[0]&l)&&h<26;++h,l<<=1);if(h>0)for(r.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(u),s.iushrn(1);t.cmp(r)>=0?(t.isub(r),a.isub(s)):(r.isub(t),s.isub(a))}return(i=0===t.cmpn(1)?a:s).cmpn(0)<0&&i.iadd(e),i},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var n=0;t.isEven()&&r.isEven();n++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=t.cmp(r);if(i<0){var o=t;t=r,r=o}else if(0===i||0===r.cmpn(1))break;t.isub(r)}return r.iushln(n)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return 0==(1&this.words[0])},o.prototype.isOdd=function(){return 1==(1&this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,i=1<>>26,s&=67108863,this.words[a]=s}return 0!==o&&(this.words[a]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this.strip(),this.length>1)t=1;else{r&&(e=-e),n(e<=67108863,"Number is too big");var i=0|this.words[0];t=i===e?0:ie.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|e.words[r];if(n!==i){ni&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new A(e)},o.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var y={k256:null,p224:null,p192:null,p25519:null};function m(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function v(){m.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function g(){m.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function w(){m.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function _(){m.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function A(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function E(e){A.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(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)}m.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},m.prototype.ireduce=function(e){var t,r=e;do{this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(t>this.n);var n=t0?r.isub(this.p):r.strip(),r},m.prototype.split=function(e,t){e.iushrn(this.n,0,t)},m.prototype.imulK=function(e){return e.imul(this.k)},i(v,m),v.prototype.split=function(e,t){for(var r=Math.min(e.length,9),n=0;n>>22,i=o}i>>>=22,e.words[n-10]=i,0===i&&e.length>10?e.length-=10:e.length-=9},v.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r>>=26,e.words[r]=i,t=n}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(y[e])return y[e];var t;if("k256"===e)t=new v;else if("p224"===e)t=new g;else if("p192"===e)t=new w;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new _}return y[e]=t,t},A.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},A.prototype._verify2=function(e,t){n(0==(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},A.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},A.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},A.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},A.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},A.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},A.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},A.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},A.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},A.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},A.prototype.isqr=function(e){return this.imul(e,e.clone())},A.prototype.sqr=function(e){return this.mul(e,e)},A.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var r=this.m.add(new o(1)).iushrn(2);return this.pow(e,r)}for(var i=this.m.subn(1),a=0;!i.isZero()&&0===i.andln(1);)a++,i.iushrn(1);n(!i.isZero());var s=new o(1).toRed(this),u=s.redNeg(),c=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new o(2*f*f).toRed(this);0!==this.pow(f,c).cmp(u);)f.redIAdd(u);for(var h=this.pow(f,i),l=this.pow(e,i.addn(1).iushrn(1)),d=this.pow(e,i),p=a;0!==d.cmp(s);){for(var b=d,y=0;0!==b.cmp(s);y++)b=b.redSqr();n(y=0;n--){for(var c=t.words[n],f=u-1;f>=0;f--){var h=c>>f&1;i!==r[0]&&(i=this.sqr(i)),0!==h||0!==a?(a<<=1,a|=h,(4===++s||0===n&&0===f)&&(i=this.mul(i,r[a]),s=0,a=0)):s=0}u=26}return i},A.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},A.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new E(e)},i(E,A),E.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},E.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},E.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},E.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var r=e.mul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},E.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===t||t,this)},{}],155:[function(e,t,r){(function(r){"use strict";var n=e("is-hex-prefixed"),i=e("strip-hex-prefix");function o(e){var t=e;if("string"!=typeof t)throw new Error("[ethjs-util] while padding to even, value must be string, is currently "+typeof t+", while padToEven.");return t.length%2&&(t="0"+t),t}function a(e){return"0x"+e.toString(16)}t.exports={arrayContainsArray:function(e,t,r){if(!0!==Array.isArray(e))throw new Error("[ethjs-util] method arrayContainsArray requires input 'superset' to be an array got type '"+typeof e+"'");if(!0!==Array.isArray(t))throw new Error("[ethjs-util] method arrayContainsArray requires input 'subset' to be an array got type '"+typeof t+"'");return t[Boolean(r)?"some":"every"](function(t){return e.indexOf(t)>=0})},intToBuffer:function(e){var t=a(e);return new r(o(t.slice(2)),"hex")},getBinarySize:function(e){if("string"!=typeof e)throw new Error("[ethjs-util] while getting binary size, method getBinarySize requires input 'str' to be type String, got '"+typeof e+"'.");return r.byteLength(e,"utf8")},isHexPrefixed:n,stripHexPrefix:i,padToEven:o,intToHex:a,fromAscii:function(e){for(var t="",r=0;r0&&this._events[e].length>r&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(e,t){if(!i(t))throw TypeError("listener must be a function");var r=!1;function n(){this.removeListener(e,n),r||(r=!0,t.apply(this,arguments))}return n.listener=t,this.on(e,n),this},n.prototype.removeListener=function(e,t){var r,n,a,s;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(a=(r=this._events[e]).length,n=-1,r===t||i(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(o(r)){for(s=a;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){n=s;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},n.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(i(r=this._events[e]))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},n.prototype.listeners=function(e){return this._events&&this._events[e]?i(this._events[e])?[this._events[e]]:this._events[e].slice():[]},n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;if(t)return t.length}return 0},n.listenerCount=function(e,t){return e.listenerCount(t)}},{}],158:[function(e,t,r){var n=e("safe-buffer").Buffer,i=e("md5.js");t.exports=function(e,t,r,o){if(n.isBuffer(e)||(e=n.from(e,"binary")),t&&(n.isBuffer(t)||(t=n.from(t,"binary")),8!==t.length))throw new RangeError("salt should be Buffer with 8 byte length");for(var a=r/8,s=n.alloc(a),u=n.alloc(o||0),c=n.alloc(0);a>0||o>0;){var f=new i;f.update(c),f.update(e),t&&f.update(t),c=f.digest();var h=0;if(a>0){var l=s.length-a;h=Math.min(a,c.length),c.copy(s,l,0,h),a-=h}if(h0){var d=u.length-o,p=Math.min(o,c.length-h);c.copy(u,d,h,h+p),o-=p}}return c.fill(0),{key:s,iv:u}}},{"md5.js":231,"safe-buffer":290}],159:[function(e,t,r){"use strict";var n=e("is-callable"),i=Object.prototype.toString,o=Object.prototype.hasOwnProperty;t.exports=function(e,t,r){if(!n(t))throw new TypeError("iterator must be a function");var a;arguments.length>=3&&(a=r),"[object Array]"===i.call(e)?function(e,t,r){for(var n=0,i=e.length;n=this._blockSize;){for(var o=this._blockOffset;o0;++a)this._length[a]+=s,(s=this._length[a]/4294967296|0)>0&&(this._length[a]-=4294967296*s);return this},i.prototype._update=function(e){throw new Error("_update is not implemented")},i.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();return void 0!==e&&(t=t.toString(e)),t},i.prototype._digest=function(){throw new Error("_digest is not implemented")},t.exports=i}).call(this,e("buffer").Buffer)},{buffer:84,inherits:180,stream:311}],162:[function(e,t,r){var n=r;n.utils=e("./hash/utils"),n.common=e("./hash/common"),n.sha=e("./hash/sha"),n.ripemd=e("./hash/ripemd"),n.hmac=e("./hash/hmac"),n.sha1=n.sha.sha1,n.sha256=n.sha.sha256,n.sha224=n.sha.sha224,n.sha384=n.sha.sha384,n.sha512=n.sha.sha512,n.ripemd160=n.ripemd.ripemd160},{"./hash/common":163,"./hash/hmac":164,"./hash/ripemd":165,"./hash/sha":166,"./hash/utils":173}],163:[function(e,t,r){"use strict";var n=e("./utils"),i=e("minimalistic-assert");function o(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}r.BlockHash=o,o.prototype.update=function(e,t){if(e=n.toArray(e,t),this.pending?this.pending=this.pending.concat(e):this.pending=e,this.pendingTotal+=e.length,this.pending.length>=this._delta8){var r=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-r,e.length),0===this.pending.length&&(this.pending=null),e=n.join32(e,0,e.length-r,this.endian);for(var i=0;i>>24&255,n[i++]=e>>>16&255,n[i++]=e>>>8&255,n[i++]=255&e}else for(n[i++]=255&e,n[i++]=e>>>8&255,n[i++]=e>>>16&255,n[i++]=e>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,o=8;othis.blockSize&&(e=(new this.Hash).update(e).digest()),i(e.length<=this.blockSize);for(var t=e.length;t>>3},r.g1_256=function(e){return n(e,17)^n(e,19)^e>>>10}},{"../utils":173}],173:[function(e,t,r){"use strict";var n=e("minimalistic-assert"),i=e("inherits");function o(e){return(e>>>24|e>>>8&65280|e<<8&16711680|(255&e)<<24)>>>0}function a(e){return 1===e.length?"0"+e:e}function s(e){return 7===e.length?"0"+e:6===e.length?"00"+e:5===e.length?"000"+e:4===e.length?"0000"+e:3===e.length?"00000"+e:2===e.length?"000000"+e:1===e.length?"0000000"+e:e}r.inherits=i,r.toArray=function(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var r=[];if("string"==typeof e)if(t){if("hex"===t)for((e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e),n=0;n>8,a=255&i;o?r.push(o,a):r.push(a)}else for(n=0;n>>0}return a},r.split32=function(e,t){for(var r=new Array(4*e.length),n=0,i=0;n>>24,r[i+1]=o>>>16&255,r[i+2]=o>>>8&255,r[i+3]=255&o):(r[i+3]=o>>>24,r[i+2]=o>>>16&255,r[i+1]=o>>>8&255,r[i]=255&o)}return r},r.rotr32=function(e,t){return e>>>t|e<<32-t},r.rotl32=function(e,t){return e<>>32-t},r.sum32=function(e,t){return e+t>>>0},r.sum32_3=function(e,t,r){return e+t+r>>>0},r.sum32_4=function(e,t,r,n){return e+t+r+n>>>0},r.sum32_5=function(e,t,r,n,i){return e+t+r+n+i>>>0},r.sum64=function(e,t,r,n){var i=e[t],o=n+e[t+1]>>>0,a=(o>>0,e[t+1]=o},r.sum64_hi=function(e,t,r,n){return(t+n>>>0>>0},r.sum64_lo=function(e,t,r,n){return t+n>>>0},r.sum64_4_hi=function(e,t,r,n,i,o,a,s){var u=0,c=t;return u+=(c=c+n>>>0)>>0)>>0)>>0},r.sum64_4_lo=function(e,t,r,n,i,o,a,s){return t+n+o+s>>>0},r.sum64_5_hi=function(e,t,r,n,i,o,a,s,u,c){var f=0,h=t;return f+=(h=h+n>>>0)>>0)>>0)>>0)>>0},r.sum64_5_lo=function(e,t,r,n,i,o,a,s,u,c){return t+n+o+s+c>>>0},r.rotr64_hi=function(e,t,r){return(t<<32-r|e>>>r)>>>0},r.rotr64_lo=function(e,t,r){return(e<<32-r|t>>>r)>>>0},r.shr64_hi=function(e,t,r){return e>>>r},r.shr64_lo=function(e,t,r){return(e<<32-r|t>>>r)>>>0}},{inherits:180,"minimalistic-assert":234}],174:[function(e,t,r){"use strict";var n=e("hash.js"),i=e("minimalistic-crypto-utils"),o=e("minimalistic-assert");function a(e){if(!(this instanceof a))return new a(e);this.hash=e.hash,this.predResist=!!e.predResist,this.outLen=this.hash.outSize,this.minEntropy=e.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var t=i.toArray(e.entropy,e.entropyEnc||"hex"),r=i.toArray(e.nonce,e.nonceEnc||"hex"),n=i.toArray(e.pers,e.persEnc||"hex");o(t.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(t,r,n)}t.exports=a,a.prototype._init=function(e,t,r){var n=e.concat(t).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(e.concat(r||[])),this._reseed=1},a.prototype.generate=function(e,t,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof t&&(n=r,r=t,t=null),r&&(r=i.toArray(r,n||"hex"),this._update(r));for(var o=[];o.length\\$%@ءؤة\"'^|~⦅⦆・ゥャ¢£¬¦¥₩│←↑→↓■○𐐨𐐩𐐪𐐫𐐬𐐭𐐮𐐯𐐰𐐱𐐲𐐳𐐴𐐵𐐶𐐷𐐸𐐹𐐺𐐻𐐼𐐽𐐾𐐿𐑀𐑁𐑂𐑃𐑄𐑅𐑆𐑇𐑈𐑉𐑊𐑋𐑌𐑍𐑎𐑏𐓘𐓙𐓚𐓛𐓜𐓝𐓞𐓟𐓠𐓡𐓢𐓣𐓤𐓥𐓦𐓧𐓨𐓩𐓪𐓫𐓬𐓭𐓮𐓯𐓰𐓱𐓲𐓳𐓴𐓵𐓶𐓷𐓸𐓹𐓺𐓻𐳀𐳁𐳂𐳃𐳄𐳅𐳆𐳇𐳈𐳉𐳊𐳋𐳌𐳍𐳎𐳏𐳐𐳑𐳒𐳓𐳔𐳕𐳖𐳗𐳘𐳙𐳚𐳛𐳜𐳝𐳞𐳟𐳠𐳡𐳢𐳣𐳤𐳥𐳦𐳧𐳨𐳩𐳪𐳫𐳬𐳭𐳮𐳯𐳰𐳱𐳲𑣀𑣁𑣂𑣃𑣄𑣅𑣆𑣇𑣈𑣉𑣊𑣋𑣌𑣍𑣎𑣏𑣐𑣑𑣒𑣓𑣔𑣕𑣖𑣗𑣘𑣙𑣚𑣛𑣜𑣝𑣞𑣟ıȷ∇∂𞤢𞤣𞤤𞤥𞤦𞤧𞤨𞤩𞤪𞤫𞤬𞤭𞤮𞤯𞤰𞤱𞤲𞤳𞤴𞤵𞤶𞤷𞤸𞤹𞤺𞤻𞤼𞤽𞤾𞤿𞥀𞥁𞥂𞥃ٮڡٯ字双多解交映無前後再新初終販声吹演投捕遊指禁空合満申割営配得可丽丸乁𠄢你侻倂偺備像㒞𠘺兔兤具𠔜㒹內𠕋冗冤仌冬𩇟刃㓟刻剆剷㔕包匆卉博即卽卿𠨬灰及叟𠭣叫叱吆咞吸呈周咢哶唐啓啣善喫喳嗂圖圗噑噴壮城埴堍型堲報墬𡓤売壷夆夢奢𡚨𡛪姬娛娧姘婦㛮嬈嬾𡧈寃寘寳𡬘寿将㞁屠峀岍𡷤嵃𡷦嵮嵫嵼巡巢㠯巽帨帽幩㡢𢆃㡼庰庳庶𪎒𢌱舁弢㣇𣊸𦇚形彫㣣徚忍志忹悁㤺㤜𢛔惇慈慌慺憲憤憯懞戛扝抱拔捐𢬌挽拼捨掃揤𢯱搢揅掩㨮摩摾撝摷㩬敬𣀊旣書晉㬙㬈㫤冒冕最暜肭䏙朡杞杓𣏃㭉柺枅桒𣑭梎栟椔楂榣槪檨𣚣櫛㰘次𣢧歔㱎歲殟殻𣪍𡴋𣫺汎𣲼沿泍汧洖派浩浸涅𣴞洴港湮㴳滇𣻑淹潮𣽞𣾎濆瀹瀛㶖灊災灷炭𠔥煅𤉣熜爨牐𤘈犀犕𤜵𤠔獺王㺬玥㺸瑇瑜璅瓊㼛甤𤰶甾𤲒𢆟瘐𤾡𤾸𥁄㿼䀈𥃳𥃲𥄙𥄳眞真瞋䁆䂖𥐝硎䃣𥘦𥚚𥛅秫䄯穊穏𥥼𥪧䈂𥮫篆築䈧𥲀糒䊠糨糣紀𥾆絣䌁緇縂繅䌴𦈨𦉇䍙𦋙罺𦌾羕翺𦓚𦔣聠𦖨聰𣍟䏕育脃䐋脾媵𦞧𦞵𣎓𣎜舄辞䑫芑芋芝劳花芳芽苦𦬼茝荣莭茣莽菧荓菊菌菜𦰶𦵫𦳕䔫蓱蓳蔖𧏊蕤𦼬䕝䕡𦾱𧃒䕫虐虧虩蚩蚈蜎蛢蜨蝫螆蟡蠁䗹衠𧙧裗裞䘵裺㒻𧢮𧥦䚾䛇誠𧲨貫賁贛起𧼯𠠄跋趼跰𠣞軔𨗒𨗭邔郱鄑𨜮鄛鈸鋗鋘鉼鏹鐕𨯺開䦕閷𨵷䧦雃嶲霣𩅅𩈚䩮䩶韠𩐊䪲𩒖頩𩖶飢䬳餩馧駂駾䯎𩬰鱀鳽䳎䳭鵧𪃎䳸𪄅𪈎𪊑䵖黾鼅鼏鼖𪘀",mapChar:function(r){return r>=196608?r>=917760&&r<=917999?18874368:0:e[t[r>>4]][15&r]}}},"function"==typeof define&&define.amd?define([],function(){return i()}):"object"==typeof r?t.exports=i():n.uts46_map=i()},{}],177:[function(e,t,r){var n,i;n=this,i=function(e,t){function r(r,n,i){for(var o=[],a=e.ucs2.decode(r),s=0;s>23,l=f>>21&3,d=f>>5&65535,p=31&f,b=t.mapStr.substr(d,p);if(0===l||n&&1&h)throw new Error("Illegal char "+c);1===l?o.push(b):2===l?o.push(i?b:c):3===l&&o.push(c)}return o.join("").normalize("NFC")}function n(t,n,o){void 0===o&&(o=!1);var a=r(t,o,n).split(".");return(a=a.map(function(t){return t.startsWith("xn--")?i(t=e.decode(t.substring(4)),o,!1):i(t,o,n),t})).join(".")}function i(e,n,i){if("-"===e[2]&&"-"===e[3])throw new Error("Failed to validate "+e);if(e.startsWith("-")||e.endsWith("-"))throw new Error("Failed to validate "+e);if(e.includes("."))throw new Error("Failed to validate "+e);if(r(e,n,i)!==e)throw new Error("Failed to validate "+e);var o=e.codePointAt(0);if(t.mapChar(o)&2<<23)throw new Error("Label contains illegal character: "+o)}return{toUnicode:function(e,t){return void 0===t&&(t={}),n(e,!1,"useStd3ASCII"in t&&t.useStd3ASCII)},toAscii:function(t,r){void 0===r&&(r={});var i,o=!("transitional"in r)||r.transitional,a="useStd3ASCII"in r&&r.useStd3ASCII,s="verifyDnsLength"in r&&r.verifyDnsLength,u=n(t,o,a).split(".").map(e.toASCII),c=u.join(".");if(s){if(c.length<1||c.length>253)throw new Error("DNS name has wrong length: "+c);for(i=0;i63)throw new Error("DNS label has wrong length: "+f)}}return c}}},"function"==typeof define&&define.amd?define(["punycode","./idna-map"],function(e,t){return i(e,t)}):"object"==typeof r?t.exports=i(e("punycode"),e("./idna-map")):n.uts46=i(n.punycode,n.idna_map)},{"./idna-map":176,punycode:265}],178:[function(e,t,r){r.read=function(e,t,r,n,i){var o,a,s=8*i-n-1,u=(1<>1,f=-7,h=r?i-1:0,l=r?-1:1,d=e[t+h];for(h+=l,o=d&(1<<-f)-1,d>>=-f,f+=s;f>0;o=256*o+e[t+h],h+=l,f-=8);for(a=o&(1<<-f)-1,o>>=-f,f+=n;f>0;a=256*a+e[t+h],h+=l,f-=8);if(0===o)o=1-c;else{if(o===u)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,n),o-=c}return(d?-1:1)*a*Math.pow(2,o-n)},r.write=function(e,t,r,n,i,o){var a,s,u,c=8*o-i-1,f=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:o-1,p=n?1:-1,b=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=f):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+h>=1?l/u:l*Math.pow(2,1-h))*u>=2&&(a++,u/=2),a+h>=f?(s=0,a=f):a+h>=1?(s=(t*u-1)*Math.pow(2,i),a+=h):(s=t*Math.pow(2,h-1)*Math.pow(2,i),a=0));i>=8;e[r+d]=255&s,d+=p,s/=256,i-=8);for(a=a<0;e[r+d]=255&a,d+=p,a/=256,c-=8);e[r+d-p]|=128*b}},{}],179:[function(e,t,r){var n=[].indexOf;t.exports=function(e,t){if(n)return e.indexOf(t);for(var r=0;r-32e3)throw new Error("Invalid error code");if(!(this instanceof f))return new f(e);i.call(this,"Server error",e)};n(f,i),i.ParseError=o,i.InvalidRequest=a,i.MethodNotFound=s,i.InvalidParams=u,i.InternalError=c,i.ServerError=f,t.exports=i},{inherits:180}],191:[function(e,t,r){t.exports=function(e){var t=(e=e||{}).max||Number.MAX_SAFE_INTEGER,r=void 0!==e.start?e.start:Math.floor(Math.random()*t);return function(){return r%=t,r++}}},{}],192:[function(e,t,r){r.parse=e("./lib/parse"),r.stringify=e("./lib/stringify")},{"./lib/parse":193,"./lib/stringify":194}],193:[function(e,t,r){var n,i,o,a,s={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"},u=function(e){throw{name:"SyntaxError",message:e,at:n,text:o}},c=function(e){return e&&e!==i&&u("Expected '"+e+"' instead of '"+i+"'"),i=o.charAt(n),n+=1,i},f=function(){var e,t="";for("-"===i&&(t="-",c("-"));i>="0"&&i<="9";)t+=i,c();if("."===i)for(t+=".";c()&&i>="0"&&i<="9";)t+=i;if("e"===i||"E"===i)for(t+=i,c(),"-"!==i&&"+"!==i||(t+=i,c());i>="0"&&i<="9";)t+=i,c();if(e=+t,isFinite(e))return e;u("Bad number")},h=function(){var e,t,r,n="";if('"'===i)for(;c();){if('"'===i)return c(),n;if("\\"===i)if(c(),"u"===i){for(r=0,t=0;t<4&&(e=parseInt(c(),16),isFinite(e));t+=1)r=16*r+e;n+=String.fromCharCode(r)}else{if("string"!=typeof s[i])break;n+=s[i]}else n+=i}u("Bad string")},l=function(){for(;i&&i<=" ";)c()};a=function(){switch(l(),i){case"{":return function(){var e,t={};if("{"===i){if(c("{"),l(),"}"===i)return c("}"),t;for(;i;){if(e=h(),l(),c(":"),Object.hasOwnProperty.call(t,e)&&u('Duplicate key "'+e+'"'),t[e]=a(),l(),"}"===i)return c("}"),t;c(","),l()}}u("Bad object")}();case"[":return function(){var e=[];if("["===i){if(c("["),l(),"]"===i)return c("]"),e;for(;i;){if(e.push(a()),l(),"]"===i)return c("]"),e;c(","),l()}}u("Bad array")}();case'"':return h();case"-":return f();default:return i>="0"&&i<="9"?f():function(){switch(i){case"t":return c("t"),c("r"),c("u"),c("e"),!0;case"f":return c("f"),c("a"),c("l"),c("s"),c("e"),!1;case"n":return c("n"),c("u"),c("l"),c("l"),null}u("Unexpected '"+i+"'")}()}},t.exports=function(e,t){var r;return o=e,n=0,i=" ",r=a(),l(),i&&u("Syntax error"),"function"==typeof t?function e(r,n){var i,o,a=r[n];if(a&&"object"==typeof a)for(i in a)Object.prototype.hasOwnProperty.call(a,i)&&(void 0!==(o=e(a,i))?a[i]=o:delete a[i]);return t.call(r,n,a)}({"":r},""):r}},{}],194:[function(e,t,r){var n,i,o,a=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,s={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};function u(e){return a.lastIndex=0,a.test(e)?'"'+e.replace(a,function(e){var t=s[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}t.exports=function(e,t,r){var a;if(n="",i="","number"==typeof r)for(a=0;a>>31),p=l^(a<<1|o>>>31),b=e[0]^d,y=e[1]^p,m=e[10]^d,v=e[11]^p,g=e[20]^d,w=e[21]^p,_=e[30]^d,A=e[31]^p,E=e[40]^d,x=e[41]^p;d=r^(s<<1|u>>>31),p=i^(u<<1|s>>>31);var k=e[2]^d,S=e[3]^p,M=e[12]^d,I=e[13]^p,T=e[22]^d,U=e[23]^p,j=e[32]^d,B=e[33]^p,P=e[42]^d,C=e[43]^p;d=o^(c<<1|f>>>31),p=a^(f<<1|c>>>31);var N=e[4]^d,R=e[5]^p,L=e[14]^d,O=e[15]^p,D=e[24]^d,F=e[25]^p,q=e[34]^d,H=e[35]^p,z=e[44]^d,K=e[45]^p;d=s^(h<<1|l>>>31),p=u^(l<<1|h>>>31);var V=e[6]^d,G=e[7]^p,W=e[16]^d,Y=e[17]^p,X=e[26]^d,Z=e[27]^p,J=e[36]^d,$=e[37]^p,Q=e[46]^d,ee=e[47]^p;d=c^(r<<1|i>>>31),p=f^(i<<1|r>>>31);var te=e[8]^d,re=e[9]^p,ne=e[18]^d,ie=e[19]^p,oe=e[28]^d,ae=e[29]^p,se=e[38]^d,ue=e[39]^p,ce=e[48]^d,fe=e[49]^p,he=b,le=y,de=v<<4|m>>>28,pe=m<<4|v>>>28,be=g<<3|w>>>29,ye=w<<3|g>>>29,me=A<<9|_>>>23,ve=_<<9|A>>>23,ge=E<<18|x>>>14,we=x<<18|E>>>14,_e=k<<1|S>>>31,Ae=S<<1|k>>>31,Ee=I<<12|M>>>20,xe=M<<12|I>>>20,ke=T<<10|U>>>22,Se=U<<10|T>>>22,Me=B<<13|j>>>19,Ie=j<<13|B>>>19,Te=P<<2|C>>>30,Ue=C<<2|P>>>30,je=R<<30|N>>>2,Be=N<<30|R>>>2,Pe=L<<6|O>>>26,Ce=O<<6|L>>>26,Ne=F<<11|D>>>21,Re=D<<11|F>>>21,Le=q<<15|H>>>17,Oe=H<<15|q>>>17,De=K<<29|z>>>3,Fe=z<<29|K>>>3,qe=V<<28|G>>>4,He=G<<28|V>>>4,ze=Y<<23|W>>>9,Ke=W<<23|Y>>>9,Ve=X<<25|Z>>>7,Ge=Z<<25|X>>>7,We=J<<21|$>>>11,Ye=$<<21|J>>>11,Xe=ee<<24|Q>>>8,Ze=Q<<24|ee>>>8,Je=te<<27|re>>>5,$e=re<<27|te>>>5,Qe=ne<<20|ie>>>12,et=ie<<20|ne>>>12,tt=ae<<7|oe>>>25,rt=oe<<7|ae>>>25,nt=se<<8|ue>>>24,it=ue<<8|se>>>24,ot=ce<<14|fe>>>18,at=fe<<14|ce>>>18;e[0]=he^~Ee&Ne,e[1]=le^~xe&Re,e[10]=qe^~Qe&be,e[11]=He^~et&ye,e[20]=_e^~Pe&Ve,e[21]=Ae^~Ce&Ge,e[30]=Je^~de&ke,e[31]=$e^~pe&Se,e[40]=je^~ze&tt,e[41]=Be^~Ke&rt,e[2]=Ee^~Ne&We,e[3]=xe^~Re&Ye,e[12]=Qe^~be&Me,e[13]=et^~ye&Ie,e[22]=Pe^~Ve&nt,e[23]=Ce^~Ge&it,e[32]=de^~ke&Le,e[33]=pe^~Se&Oe,e[42]=ze^~tt&me,e[43]=Ke^~rt&ve,e[4]=Ne^~We&ot,e[5]=Re^~Ye&at,e[14]=be^~Me&De,e[15]=ye^~Ie&Fe,e[24]=Ve^~nt&ge,e[25]=Ge^~it&we,e[34]=ke^~Le&Xe,e[35]=Se^~Oe&Ze,e[44]=tt^~me&Te,e[45]=rt^~ve&Ue,e[6]=We^~ot&he,e[7]=Ye^~at&le,e[16]=Me^~De&qe,e[17]=Ie^~Fe&He,e[26]=nt^~ge&_e,e[27]=it^~we&Ae,e[36]=Le^~Xe&Je,e[37]=Oe^~Ze&$e,e[46]=me^~Te&je,e[47]=ve^~Ue&Be,e[8]=ot^~he&Ee,e[9]=at^~le&xe,e[18]=De^~qe&Qe,e[19]=Fe^~He&et,e[28]=ge^~_e&Pe,e[29]=we^~Ae&Ce,e[38]=Xe^~Je&de,e[39]=Ze^~$e&pe,e[48]=Te^~je&ze,e[49]=Ue^~Be&Ke,e[0]^=n[2*t],e[1]^=n[2*t+1]}}},{}],200:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("./keccak-state-unroll");function o(){this.state=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.blockSize=null,this.count=0,this.squeezing=!1}o.prototype.initialize=function(e,t){for(var r=0;r<50;++r)this.state[r]=0;this.blockSize=e/8,this.count=0,this.squeezing=!1},o.prototype.absorb=function(e){for(var t=0;t>>this.count%4*8&255,this.count+=1,this.count===this.blockSize&&(i.p1600(this.state),this.count=0);return t},o.prototype.copy=function(e){for(var t=0;t<50;++t)e.state[t]=this.state[t];e.blockSize=this.blockSize,e.count=this.count,e.squeezing=this.squeezing},t.exports=o},{"./keccak-state-unroll":199,"safe-buffer":290}],201:[function(e,t,r){var n=e("./_root").Symbol;t.exports=n},{"./_root":217}],202:[function(e,t,r){var n=e("./_baseTimes"),i=e("./isArguments"),o=e("./isArray"),a=e("./isBuffer"),s=e("./_isIndex"),u=e("./isTypedArray"),c=Object.prototype.hasOwnProperty;t.exports=function(e,t){var r=o(e),f=!r&&i(e),h=!r&&!f&&a(e),l=!r&&!f&&!h&&u(e),d=r||f||h||l,p=d?n(e.length,String):[],b=p.length;for(var y in e)!t&&!c.call(e,y)||d&&("length"==y||h&&("offset"==y||"parent"==y)||l&&("buffer"==y||"byteLength"==y||"byteOffset"==y)||s(y,b))||p.push(y);return p}},{"./_baseTimes":207,"./_isIndex":211,"./isArguments":219,"./isArray":220,"./isBuffer":222,"./isTypedArray":227}],203:[function(e,t,r){var n=e("./_Symbol"),i=e("./_getRawTag"),o=e("./_objectToString"),a="[object Null]",s="[object Undefined]",u=n?n.toStringTag:void 0;t.exports=function(e){return null==e?void 0===e?s:a:u&&u in Object(e)?i(e):o(e)}},{"./_Symbol":201,"./_getRawTag":210,"./_objectToString":215}],204:[function(e,t,r){var n=e("./_baseGetTag"),i=e("./isObjectLike"),o="[object Arguments]";t.exports=function(e){return i(e)&&n(e)==o}},{"./_baseGetTag":203,"./isObjectLike":226}],205:[function(e,t,r){var n=e("./_baseGetTag"),i=e("./isLength"),o=e("./isObjectLike"),a={};a["[object Float32Array]"]=a["[object Float64Array]"]=a["[object Int8Array]"]=a["[object Int16Array]"]=a["[object Int32Array]"]=a["[object Uint8Array]"]=a["[object Uint8ClampedArray]"]=a["[object Uint16Array]"]=a["[object Uint32Array]"]=!0,a["[object Arguments]"]=a["[object Array]"]=a["[object ArrayBuffer]"]=a["[object Boolean]"]=a["[object DataView]"]=a["[object Date]"]=a["[object Error]"]=a["[object Function]"]=a["[object Map]"]=a["[object Number]"]=a["[object Object]"]=a["[object RegExp]"]=a["[object Set]"]=a["[object String]"]=a["[object WeakMap]"]=!1,t.exports=function(e){return o(e)&&i(e.length)&&!!a[n(e)]}},{"./_baseGetTag":203,"./isLength":224,"./isObjectLike":226}],206:[function(e,t,r){var n=e("./_isPrototype"),i=e("./_nativeKeys"),o=Object.prototype.hasOwnProperty;t.exports=function(e){if(!n(e))return i(e);var t=[];for(var r in Object(e))o.call(e,r)&&"constructor"!=r&&t.push(r);return t}},{"./_isPrototype":212,"./_nativeKeys":213}],207:[function(e,t,r){t.exports=function(e,t){for(var r=-1,n=Array(e);++r-1&&e%1==0&&e-1&&e%1==0&&e<=n}},{}],225:[function(e,t,r){t.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}},{}],226:[function(e,t,r){t.exports=function(e){return null!=e&&"object"==typeof e}},{}],227:[function(e,t,r){var n=e("./_baseIsTypedArray"),i=e("./_baseUnary"),o=e("./_nodeUtil"),a=o&&o.isTypedArray,s=a?i(a):n;t.exports=s},{"./_baseIsTypedArray":205,"./_baseUnary":208,"./_nodeUtil":214}],228:[function(e,t,r){var n=e("./_arrayLikeKeys"),i=e("./_baseKeys"),o=e("./isArrayLike");t.exports=function(e){return o(e)?n(e):i(e)}},{"./_arrayLikeKeys":202,"./_baseKeys":206,"./isArrayLike":221}],229:[function(e,t,r){t.exports=function(){}},{}],230:[function(e,t,r){t.exports=function(){return!1}},{}],231:[function(e,t,r){(function(r){"use strict";var n=e("inherits"),i=e("hash-base"),o=new Array(16);function a(){i.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}function s(e,t){return e<>>32-t}function u(e,t,r,n,i,o,a){return s(e+(t&r|~t&n)+i+o|0,a)+t|0}function c(e,t,r,n,i,o,a){return s(e+(t&n|r&~n)+i+o|0,a)+t|0}function f(e,t,r,n,i,o,a){return s(e+(t^r^n)+i+o|0,a)+t|0}function h(e,t,r,n,i,o,a){return s(e+(r^(t|~n))+i+o|0,a)+t|0}n(a,i),a.prototype._update=function(){for(var e=o,t=0;t<16;++t)e[t]=this._block.readInt32LE(4*t);var r=this._a,n=this._b,i=this._c,a=this._d;n=h(n=h(n=h(n=h(n=f(n=f(n=f(n=f(n=c(n=c(n=c(n=c(n=u(n=u(n=u(n=u(n,i=u(i,a=u(a,r=u(r,n,i,a,e[0],3614090360,7),n,i,e[1],3905402710,12),r,n,e[2],606105819,17),a,r,e[3],3250441966,22),i=u(i,a=u(a,r=u(r,n,i,a,e[4],4118548399,7),n,i,e[5],1200080426,12),r,n,e[6],2821735955,17),a,r,e[7],4249261313,22),i=u(i,a=u(a,r=u(r,n,i,a,e[8],1770035416,7),n,i,e[9],2336552879,12),r,n,e[10],4294925233,17),a,r,e[11],2304563134,22),i=u(i,a=u(a,r=u(r,n,i,a,e[12],1804603682,7),n,i,e[13],4254626195,12),r,n,e[14],2792965006,17),a,r,e[15],1236535329,22),i=c(i,a=c(a,r=c(r,n,i,a,e[1],4129170786,5),n,i,e[6],3225465664,9),r,n,e[11],643717713,14),a,r,e[0],3921069994,20),i=c(i,a=c(a,r=c(r,n,i,a,e[5],3593408605,5),n,i,e[10],38016083,9),r,n,e[15],3634488961,14),a,r,e[4],3889429448,20),i=c(i,a=c(a,r=c(r,n,i,a,e[9],568446438,5),n,i,e[14],3275163606,9),r,n,e[3],4107603335,14),a,r,e[8],1163531501,20),i=c(i,a=c(a,r=c(r,n,i,a,e[13],2850285829,5),n,i,e[2],4243563512,9),r,n,e[7],1735328473,14),a,r,e[12],2368359562,20),i=f(i,a=f(a,r=f(r,n,i,a,e[5],4294588738,4),n,i,e[8],2272392833,11),r,n,e[11],1839030562,16),a,r,e[14],4259657740,23),i=f(i,a=f(a,r=f(r,n,i,a,e[1],2763975236,4),n,i,e[4],1272893353,11),r,n,e[7],4139469664,16),a,r,e[10],3200236656,23),i=f(i,a=f(a,r=f(r,n,i,a,e[13],681279174,4),n,i,e[0],3936430074,11),r,n,e[3],3572445317,16),a,r,e[6],76029189,23),i=f(i,a=f(a,r=f(r,n,i,a,e[9],3654602809,4),n,i,e[12],3873151461,11),r,n,e[15],530742520,16),a,r,e[2],3299628645,23),i=h(i,a=h(a,r=h(r,n,i,a,e[0],4096336452,6),n,i,e[7],1126891415,10),r,n,e[14],2878612391,15),a,r,e[5],4237533241,21),i=h(i,a=h(a,r=h(r,n,i,a,e[12],1700485571,6),n,i,e[3],2399980690,10),r,n,e[10],4293915773,15),a,r,e[1],2240044497,21),i=h(i,a=h(a,r=h(r,n,i,a,e[8],1873313359,6),n,i,e[15],4264355552,10),r,n,e[6],2734768916,15),a,r,e[13],1309151649,21),i=h(i,a=h(a,r=h(r,n,i,a,e[4],4149444226,6),n,i,e[11],3174756917,10),r,n,e[2],718787259,15),a,r,e[9],3951481745,21),this._a=this._a+r|0,this._b=this._b+n|0,this._c=this._c+i|0,this._d=this._d+a|0},a.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=new r(16);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e},t.exports=a}).call(this,e("buffer").Buffer)},{buffer:84,"hash-base":232,inherits:180}],232:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("stream").Transform;function o(e){i.call(this),this._block=n.allocUnsafe(e),this._blockSize=e,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}e("inherits")(o,i),o.prototype._transform=function(e,t,r){var n=null;try{this.update(e,t)}catch(e){n=e}r(n)},o.prototype._flush=function(e){var t=null;try{this.push(this.digest())}catch(e){t=e}e(t)},o.prototype.update=function(e,t){if(function(e,t){if(!n.isBuffer(e)&&"string"!=typeof e)throw new TypeError(t+" must be a string or a buffer")}(e,"Data"),this._finalized)throw new Error("Digest already called");n.isBuffer(e)||(e=n.from(e,t));for(var r=this._block,i=0;this._blockOffset+e.length-i>=this._blockSize;){for(var o=this._blockOffset;o0;++a)this._length[a]+=s,(s=this._length[a]/4294967296|0)>0&&(this._length[a]-=4294967296*s);return this},o.prototype._update=function(){throw new Error("_update is not implemented")},o.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();void 0!==e&&(t=t.toString(e)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return t},o.prototype._digest=function(){throw new Error("_digest is not implemented")},t.exports=o},{inherits:180,"safe-buffer":290,stream:311}],233:[function(e,t,r){var n=e("bn.js"),i=e("brorand");function o(e){this.rand=e||new i.Rand}t.exports=o,o.create=function(e){return new o(e)},o.prototype._randbelow=function(e){var t=e.bitLength(),r=Math.ceil(t/8);do{var i=new n(this.rand.generate(r))}while(i.cmp(e)>=0);return i},o.prototype._randrange=function(e,t){var r=t.sub(e);return e.add(this._randbelow(r))},o.prototype.test=function(e,t,r){var i=e.bitLength(),o=n.mont(e),a=new n(1).toRed(o);t||(t=Math.max(1,i/48|0));for(var s=e.subn(1),u=0;!s.testn(u);u++);for(var c=e.shrn(u),f=s.toRed(o);t>0;t--){var h=this._randrange(new n(2),s);r&&r(h);var l=h.toRed(o).redPow(c);if(0!==l.cmp(a)&&0!==l.cmp(f)){for(var d=1;d0;t--){var f=this._randrange(new n(2),a),h=e.gcd(f);if(0!==h.cmpn(1))return h;var l=f.toRed(i).redPow(u);if(0!==l.cmp(o)&&0!==l.cmp(c)){for(var d=1;d>8,a=255&i;o?r.push(o,a):r.push(a)}return r},n.zero2=i,n.toHex=o,n.encode=function(e,t){return"hex"===t?o(e):e}},{}],236:[function(e,t,r){arguments[4][154][0].apply(r,arguments)},{dup:154}],237:[function(e,t,r){var n=e("bn.js"),i=e("strip-hex-prefix");t.exports=function(e){if("string"==typeof e||"number"==typeof e){var t=new n(1),r=String(e).toLowerCase().trim(),o="0x"===r.substr(0,2)||"-0x"===r.substr(0,3),a=i(r);if("-"===a.substr(0,1)&&(a=i(a.slice(1)),t=new n(-1,10)),!(a=""===a?"0":a).match(/^-?[0-9]+$/)&&a.match(/^[0-9A-Fa-f]+$/)||a.match(/^[a-fA-F]+$/)||!0===o&&a.match(/^[0-9A-Fa-f]+$/))return new n(a,16).mul(t);if((a.match(/^-?[0-9]+$/)||""===a)&&!1===o)return new n(a,10).mul(t)}else if("object"==typeof e&&e.toString&&!e.pop&&!e.push&&e.toString(10).match(/^-?[0-9]+$/)&&(e.mul||e.dividedToIntegerBy))return new n(e.toString(10),10);throw new Error("[number-to-bn] while converting number "+JSON.stringify(e)+" 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(e,t,r){"use strict";var n=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable;t.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},r=0;r<10;r++)t["_"+String.fromCharCode(r)]=r;if("0123456789"!==Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(""))return!1;var n={};return"abcdefghijklmnopqrst".split("").forEach(function(e){n[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},n)).join("")}catch(e){return!1}}()?Object.assign:function(e,t){for(var r,a,s=function(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}(e),u=1;u0;)if(q+=r,r=e.charAt(o++),4===H?(N+=String.fromCharCode(parseInt(q,16)),H=0,c=o-1):H++,!r)break e;if('"'===r&&!L){D=F.pop()||p,N+=e.substring(c,o-1);break}if(!("\\"!==r||L||(L=!0,N+=e.substring(c,o-1),r=e.charAt(o++))))break;if(L){if(L=!1,"n"===r?N+="\n":"r"===r?N+="\r":"t"===r?N+="\t":"f"===r?N+="\f":"b"===r?N+="\b":"u"===r?(H=1,q=""):N+=r,r=e.charAt(o++),c=o-1,r)continue;break}h.lastIndex=o;var l=h.exec(e);if(!l){o=e.length+1,N+=e.substring(c,o-1);break}if(o=l.index+1,!(r=e.charAt(l.index))){N+=e.substring(c,o-1);break}}continue;case A:if(!r)continue;if("r"!==r)return W("Invalid true started with t"+r);D=E;continue;case E:if(!r)continue;if("u"!==r)return W("Invalid true started with tr"+r);D=x;continue;case x:if(!r)continue;if("e"!==r)return W("Invalid true started with tru"+r);a(!0),u(),D=F.pop()||p;continue;case k:if(!r)continue;if("a"!==r)return W("Invalid false started with f"+r);D=S;continue;case S:if(!r)continue;if("l"!==r)return W("Invalid false started with fa"+r);D=M;continue;case M:if(!r)continue;if("s"!==r)return W("Invalid false started with fal"+r);D=I;continue;case I:if(!r)continue;if("e"!==r)return W("Invalid false started with fals"+r);a(!1),u(),D=F.pop()||p;continue;case T:if(!r)continue;if("u"!==r)return W("Invalid null started with n"+r);D=U;continue;case U:if(!r)continue;if("l"!==r)return W("Invalid null started with nu"+r);D=j;continue;case j:if(!r)continue;if("l"!==r)return W("Invalid null started with nul"+r);a(null),u(),D=F.pop()||p;continue;case B:if("."!==r)return W("Leading zero not followed by .");R+=r,D=P;continue;case P:if(-1!=="0123456789".indexOf(r))R+=r;else if("."===r){if(-1!==R.indexOf("."))return W("Invalid number has two dots");R+=r}else if("e"===r||"E"===r){if(-1!==R.indexOf("e")||-1!==R.indexOf("E"))return W("Invalid number has two exponential");R+=r}else if("+"===r||"-"===r){if("e"!==n&&"E"!==n)return W("Invalid symbol in number");R+=r}else R&&(a(parseFloat(R)),u(),R=""),o--,D=F.pop()||p;continue;default:return W("Unknown state: "+D)}K>=C&&(X=0,N!==s&&N.length>f&&(W("Max buffer length exceeded: textNode"),X=Math.max(X,N.length)),R.length>f&&(W("Max buffer length exceeded: numberNode"),X=Math.max(X,R.length)),C=f-X+K);var X}),e(ce).on(function(){if(D==d)return a({}),u(),void(O=!0);D===p&&0===z||W("Unexpected end");N!==s&&(a(N),u(),N=s);O=!0})}var C,N,R,L,O,D,F,q,H,z,K,V=(C=d(function(e){return e.unshift(/^/),(t=RegExp(e.map(f("source")).join(""))).exec.bind(t);var t}),L=C(N=/(\$?)/,/([\w-_]+|\*)/,R=/(?:{([\w ]*?)})?/),O=C(N,/\["([^"]+)"\]/,R),D=C(N,/\[(\d+|\*)\]/,R),F=C(N,/()/,/{([\w ]*?)}/),q=C(/\.\./),H=C(/\./),z=C(N,/!/),K=C(/$/),function(e){return e(h(L,O,D,F),q,H,z,K)});function G(e,t){return{key:e,node:t}}var W=f("key"),Y=f("node"),X={};function Z(e){var t=e(ee).emit,r=e(te).emit,n=e(ae).emit,o=e(oe).emit;function a(e,t,r){Y(x(e))[t]=r}function s(e,r,n){e&&a(e,r,n);var i=A(G(r,n),e);return t(i),i}var u={};return u[le]=function(e,t){if(!e)return n(t),s(e,X,t);var r=function(e,t){var r=Y(x(e));return m(i,r)?s(e,v(r),t):e}(e,t),o=k(r),u=W(x(r));return a(o,u,t),A(G(u,t),o)},u[de]=function(e){return r(e),k(e)||o(Y(x(e)))},u[he]=s,u}var J=V(function(e,t,r,n,i){var a=1,s=2,f=3,l=c(W,x),d=c(Y,x);function b(e,t){return!!t[a]?p(e,x):e}function m(e){if(e==y)return y;return p(function(e){return l(e)!=X},c(e,k))}function g(){return function(e){return l(e)==X}}function w(e,t,r,n,i){var o=e(r);if(o){var a=function(e,t,r){return U(function(e,t){return t(e,r)},t,e)}(t,n,o);return i(r.substr(v(o[0])),a)}}function A(e,t){return u(w,e,t)}var E=h(A(e,M(b,function(e,t){var r=t[f];return r?p(c(u(_,S(r.split(/\W+/))),d),e):e},function(e,t){var r=t[s];return p(r&&"*"!=r?function(e){return l(e)==r}:y,e)},m)),A(t,M(function(e){if(e==y)return y;var t=g(),r=e,n=m(function(e){return i(e)}),i=h(t,r,n);return i})),A(r,M()),A(n,M(b,g)),A(i,M(function(e){return function(t){var r=e(t);return!0===r?x(t):r}})),function(e){throw o('"'+e+'" could not be tokenised')});function I(e,t){return t}function T(e,t){return E(e,t,e?T:I)}return function(e){try{return T(e,y)}catch(t){throw o('Could not compile "'+e+'" because '+t.message)}}});function $(e,t,r){var n,i;function o(e){return function(t){return t.id==e}}return{on:function(r,o){var a={listener:r,id:o||r};return t&&t.emit(e,r,a.id),n=A(a,n),i=A(r,i),this},emit:function(){!function e(t,r){t&&(x(t).apply(null,r),e(k(t),r))}(i,arguments)},un:function(t){var a;n=j(n,o(t),function(e){a=e}),a&&(i=j(i,function(e){return e==a.listener}),r&&r.emit(e,a.listener,a.id))},listeners:function(){return i},hasListener:function(e){return w(function e(t,r){return r&&(t(x(r))?x(r):e(t,k(r)))}(e?o(e):y,n))}}}var Q=1,ee=Q++,te=Q++,re=Q++,ne=Q++,ie="fail",oe=Q++,ae=Q++,se="start",ue="data",ce="end",fe=Q++,he=Q++,le=Q++,de=Q++;function pe(e,t,r){try{var n=a.parse(t)}catch(e){}return{statusCode:e,body:t,jsonBody:n,thrown:r}}function be(e,t){var r={node:e(te),path:e(ee)};function n(t,r,n){var i=e(t).emit;r.on(function(e){var t=n(e);!1!==t&&function(e,t,r){var n=B(r);e(t,I(k(T(W,n))),I(T(Y,n)))}(i,Y(t),e)},t),e("removeListener").on(function(n){n==t&&(e(n).listeners()||r.un(t))})}e("newListener").on(function(e){var i=/(node|path):(.*)/.exec(e);if(i){var o=r[i[1]];o.hasListener(e)||n(e,o,t(i[2]))}})}function ye(e,t){var r,n=/^(node|path):./,i=e(oe),o=e(ne).emit,a=e(re).emit,s=d(function(t,i){if(r[t])l(i,r[t]);else{var o=e(t),a=i[0];n.test(t)?c(o,a):o.on(a)}return r});function c(e,t,n){n=n||t;var i=f(t);return e.on(function(){var t=!1;r.forget=function(){t=!0},l(arguments,i),delete r.forget,t&&e.un(n)},n),r}function f(e){return function(){try{return e.apply(r,arguments)}catch(e){setTimeout(function(){throw e})}}}function h(t,r,n){var i;i="node"==t?function(e){return function(){var t=e.apply(this,arguments);w(t)&&(t==ge.drop?o():a(t))}}(n):n,c(function(t,r){return e(t+":"+r)}(t,r),i,n)}function p(e,t,n){return g(t)?h(e,t,n):function(e,t){for(var r in t)h(e,r,t[r])}(e,t),r}return e(ae).on(function(e){var t;r.root=(t=e,function(){return t})}),e(se).on(function(e,t){r.header=function(e){return e?t[e]:t}}),r={on:s,addListener:s,removeListener:function(t,n,o){if("done"==t)i.un(n);else if("node"==t||"path"==t)e.un(t+":"+n,o);else{var a=n;e(t).un(a)}return r},emit:e.emit,node:u(p,"node"),path:u(p,"path"),done:u(c,i),start:u(function(t,n){return e(t).on(f(n),n),r},se),fail:e(ie).on,abort:e(fe).emit,header:b,root:b,source:t}}function me(t,r,n,i,o){var a=function(){var e={},t=n("newListener"),r=n("removeListener");function n(n){return e[n]=$(n,t,r)}function i(t){return e[t]||n(t)}return["emit","on","un"].forEach(function(e){i[e]=d(function(t,r){l(r,i(t)[e])})}),i}();return r&&function(t,r,n,i,o,a,c){"use strict";var f=t(ue).emit,h=t(ie).emit,l=0,d=!0;function p(){var e=r.responseText,t=e.substr(l);t&&f(t),l=v(e)}t(fe).on(function(){r.onreadystatechange=null,r.abort()}),"onprogress"in r&&(r.onprogress=p),r.onreadystatechange=function(){function e(){try{d&&t(se).emit(r.status,(e=r.getAllResponseHeaders(),n={},e&&e.split("\r\n").forEach(function(e){var t=e.indexOf(": ");n[e.substring(0,t)]=e.substring(t+2)}),n)),d=!1}catch(e){}var e,n}switch(r.readyState){case 2:case 3:return e();case 4:e(),2==String(r.status)[0]?(p(),t(ce).emit()):h(pe(r.status,r.responseText))}};try{for(var b in r.open(n,i,!0),a)r.setRequestHeader(b,a[b]);(function(e,t){function r(t){return t.port||{"http:":80,"https:":443}[t.protocol||e.protocol]}return!!(t.protocol&&t.protocol!=e.protocol||t.host&&t.host!=e.host||t.host&&r(t)!=r(e))})(e.location,function(e){var t=/(\w+:)?(?:\/\/)([\w.-]+)?(?::(\d+))?\/?/.exec(e)||[];return{protocol:t[1]||"",host:t[2]||"",port:t[3]||""}}(i))||r.setRequestHeader("X-Requested-With","XMLHttpRequest"),r.withCredentials=c,r.send(o)}catch(t){e.setTimeout(u(h,pe(s,s,t)),0)}}(a,new XMLHttpRequest,t,r,n,i,o),P(a),function(e,t){"use strict";var r,n={};function i(e){return function(t){r=e(r,t)}}for(var o in t)e(o).on(i(t[o]),n);e(re).on(function(e){var t=x(r),n=W(t),i=k(r);i&&(Y(x(i))[n]=e)}),e(ne).on(function(){var e=x(r),t=W(e),n=k(r);n&&delete Y(x(n))[t]}),e(fe).on(function(){for(var r in t)e(r).un(n)})}(a,Z(a)),be(a,J),ye(a,r)}function ve(e,t,r,n,i,o,s){return i=i?a.parse(a.stringify(i)):{},n?g(n)||(n=a.stringify(n),i["Content-Type"]=i["Content-Type"]||"application/json"):n=null,e(r||"GET",function(e,t){return!1===t&&(-1==e.indexOf("?")?e+="?":e+="&",e+="_="+(new Date).getTime()),e}(t,s),n,i,o||!1)}function ge(e){var t=M("resume","pause","pipe"),r=u(_,t);return e?r(e)||g(e)?ve(me,e):ve(me,e.url,e.method,e.body,e.headers,e.withCredentials,e.cached):me()}ge.drop=function(){return ge.drop},"function"==typeof define&&define.amd?define("oboe",[],function(){return ge}):"object"==typeof r?t.exports=ge:e.oboe=ge}(function(){try{return window}catch(e){return self}}(),Object,Array,Error,JSON)},{}],240:[function(e,t,r){r.endianness=function(){return"LE"},r.hostname=function(){return"undefined"!=typeof location?location.hostname:""},r.loadavg=function(){return[]},r.uptime=function(){return 0},r.freemem=function(){return Number.MAX_VALUE},r.totalmem=function(){return Number.MAX_VALUE},r.cpus=function(){return[]},r.type=function(){return"Browser"},r.release=function(){return"undefined"!=typeof navigator?navigator.appVersion:""},r.networkInterfaces=r.getNetworkInterfaces=function(){return{}},r.arch=function(){return"javascript"},r.platform=function(){return"browser"},r.tmpdir=r.tmpDir=function(){return"/tmp"},r.EOL="\n",r.homedir=function(){return"/"}},{}],241:[function(e,t,r){t.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","2.16.840.1.101.3.4.1.3":"aes-128-ofb","2.16.840.1.101.3.4.1.4":"aes-128-cfb","2.16.840.1.101.3.4.1.21":"aes-192-ecb","2.16.840.1.101.3.4.1.22":"aes-192-cbc","2.16.840.1.101.3.4.1.23":"aes-192-ofb","2.16.840.1.101.3.4.1.24":"aes-192-cfb","2.16.840.1.101.3.4.1.41":"aes-256-ecb","2.16.840.1.101.3.4.1.42":"aes-256-cbc","2.16.840.1.101.3.4.1.43":"aes-256-ofb","2.16.840.1.101.3.4.1.44":"aes-256-cfb"}},{}],242:[function(e,t,r){"use strict";var n=e("asn1.js");r.certificate=e("./certificate");var i=n.define("RSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("modulus").int(),this.key("publicExponent").int(),this.key("privateExponent").int(),this.key("prime1").int(),this.key("prime2").int(),this.key("exponent1").int(),this.key("exponent2").int(),this.key("coefficient").int())});r.RSAPrivateKey=i;var o=n.define("RSAPublicKey",function(){this.seq().obj(this.key("modulus").int(),this.key("publicExponent").int())});r.RSAPublicKey=o;var a=n.define("SubjectPublicKeyInfo",function(){this.seq().obj(this.key("algorithm").use(s),this.key("subjectPublicKey").bitstr())});r.PublicKey=a;var s=n.define("AlgorithmIdentifier",function(){this.seq().obj(this.key("algorithm").objid(),this.key("none").null_().optional(),this.key("curve").objid().optional(),this.key("params").seq().obj(this.key("p").int(),this.key("q").int(),this.key("g").int()).optional())}),u=n.define("PrivateKeyInfo",function(){this.seq().obj(this.key("version").int(),this.key("algorithm").use(s),this.key("subjectPrivateKey").octstr())});r.PrivateKey=u;var c=n.define("EncryptedPrivateKeyInfo",function(){this.seq().obj(this.key("algorithm").seq().obj(this.key("id").objid(),this.key("decrypt").seq().obj(this.key("kde").seq().obj(this.key("id").objid(),this.key("kdeparams").seq().obj(this.key("salt").octstr(),this.key("iters").int())),this.key("cipher").seq().obj(this.key("algo").objid(),this.key("iv").octstr()))),this.key("subjectPrivateKey").octstr())});r.EncryptedPrivateKey=c;var f=n.define("DSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("p").int(),this.key("q").int(),this.key("g").int(),this.key("pub_key").int(),this.key("priv_key").int())});r.DSAPrivateKey=f,r.DSAparam=n.define("DSAparam",function(){this.int()});var h=n.define("ECPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").optional().explicit(0).use(l),this.key("publicKey").optional().explicit(1).bitstr())});r.ECPrivateKey=h;var l=n.define("ECParameters",function(){this.choice({namedCurve:this.objid()})});r.signature=n.define("signature",function(){this.seq().obj(this.key("r").int(),this.key("s").int())})},{"./certificate":243,"asn1.js":5}],243:[function(e,t,r){"use strict";var n=e("asn1.js"),i=n.define("Time",function(){this.choice({utcTime:this.utctime(),generalTime:this.gentime()})}),o=n.define("AttributeTypeValue",function(){this.seq().obj(this.key("type").objid(),this.key("value").any())}),a=n.define("AlgorithmIdentifier",function(){this.seq().obj(this.key("algorithm").objid(),this.key("parameters").optional())}),s=n.define("SubjectPublicKeyInfo",function(){this.seq().obj(this.key("algorithm").use(a),this.key("subjectPublicKey").bitstr())}),u=n.define("RelativeDistinguishedName",function(){this.setof(o)}),c=n.define("RDNSequence",function(){this.seqof(u)}),f=n.define("Name",function(){this.choice({rdnSequence:this.use(c)})}),h=n.define("Validity",function(){this.seq().obj(this.key("notBefore").use(i),this.key("notAfter").use(i))}),l=n.define("Extension",function(){this.seq().obj(this.key("extnID").objid(),this.key("critical").bool().def(!1),this.key("extnValue").octstr())}),d=n.define("TBSCertificate",function(){this.seq().obj(this.key("version").explicit(0).int(),this.key("serialNumber").int(),this.key("signature").use(a),this.key("issuer").use(f),this.key("validity").use(h),this.key("subject").use(f),this.key("subjectPublicKeyInfo").use(s),this.key("issuerUniqueID").implicit(1).bitstr().optional(),this.key("subjectUniqueID").implicit(2).bitstr().optional(),this.key("extensions").explicit(3).seqof(l).optional())}),p=n.define("X509Certificate",function(){this.seq().obj(this.key("tbsCertificate").use(d),this.key("signatureAlgorithm").use(a),this.key("signatureValue").bitstr())});t.exports=p},{"asn1.js":5}],244:[function(e,t,r){(function(r){var n=/Proc-Type: 4,ENCRYPTED\n\r?DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)\n\r?\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?/m,i=/^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----\n/m,o=/^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?-----END \1-----$/m,a=e("evp_bytestokey"),s=e("browserify-aes");t.exports=function(e,t){var u,c=e.toString(),f=c.match(n);if(f){var h="aes"+f[1],l=new r(f[2],"hex"),d=new r(f[3].replace(/\r?\n/g,""),"base64"),p=a(t,l.slice(0,8),parseInt(f[1],10)).key,b=[],y=s.createDecipheriv(h,p,l);b.push(y.update(d)),b.push(y.final()),u=r.concat(b)}else{var m=c.match(o);u=new r(m[2].replace(/\r?\n/g,""),"base64")}return{tag:c.match(i)[1],data:u}}}).call(this,e("buffer").Buffer)},{"browserify-aes":58,buffer:84,evp_bytestokey:158}],245:[function(e,t,r){(function(r){var n=e("./asn1"),i=e("./aesid.json"),o=e("./fixProc"),a=e("browserify-aes"),s=e("pbkdf2");function u(e){var t;"object"!=typeof e||r.isBuffer(e)||(t=e.passphrase,e=e.key),"string"==typeof e&&(e=new r(e));var u,c,f=o(e,t),h=f.tag,l=f.data;switch(h){case"CERTIFICATE":c=n.certificate.decode(l,"der").tbsCertificate.subjectPublicKeyInfo;case"PUBLIC KEY":switch(c||(c=n.PublicKey.decode(l,"der")),u=c.algorithm.algorithm.join(".")){case"1.2.840.113549.1.1.1":return n.RSAPublicKey.decode(c.subjectPublicKey.data,"der");case"1.2.840.10045.2.1":return c.subjectPrivateKey=c.subjectPublicKey,{type:"ec",data:c};case"1.2.840.10040.4.1":return c.algorithm.params.pub_key=n.DSAparam.decode(c.subjectPublicKey.data,"der"),{type:"dsa",data:c.algorithm.params};default:throw new Error("unknown key id "+u)}throw new Error("unknown key type "+h);case"ENCRYPTED PRIVATE KEY":l=function(e,t){var n=e.algorithm.decrypt.kde.kdeparams.salt,o=parseInt(e.algorithm.decrypt.kde.kdeparams.iters.toString(),10),u=i[e.algorithm.decrypt.cipher.algo.join(".")],c=e.algorithm.decrypt.cipher.iv,f=e.subjectPrivateKey,h=parseInt(u.split("-")[1],10)/8,l=s.pbkdf2Sync(t,n,o,h),d=a.createDecipheriv(u,l,c),p=[];return p.push(d.update(f)),p.push(d.final()),r.concat(p)}(l=n.EncryptedPrivateKey.decode(l,"der"),t);case"PRIVATE KEY":switch(u=(c=n.PrivateKey.decode(l,"der")).algorithm.algorithm.join(".")){case"1.2.840.113549.1.1.1":return n.RSAPrivateKey.decode(c.subjectPrivateKey,"der");case"1.2.840.10045.2.1":return{curve:c.algorithm.curve,privateKey:n.ECPrivateKey.decode(c.subjectPrivateKey,"der").privateKey};case"1.2.840.10040.4.1":return c.algorithm.params.priv_key=n.DSAparam.decode(c.subjectPrivateKey,"der"),{type:"dsa",params:c.algorithm.params};default:throw new Error("unknown key id "+u)}throw new Error("unknown key type "+h);case"RSA PUBLIC KEY":return n.RSAPublicKey.decode(l,"der");case"RSA PRIVATE KEY":return n.RSAPrivateKey.decode(l,"der");case"DSA PRIVATE KEY":return{type:"dsa",params:n.DSAPrivateKey.decode(l,"der")};case"EC PRIVATE KEY":return{curve:(l=n.ECPrivateKey.decode(l,"der")).parameters.value,privateKey:l.privateKey};default:throw new Error("unknown key type "+h)}}t.exports=u,u.signature=n.signature}).call(this,e("buffer").Buffer)},{"./aesid.json":241,"./asn1":242,"./fixProc":244,"browserify-aes":58,buffer:84,pbkdf2:247}],246:[function(e,t,r){var n=e("trim"),i=e("for-each");t.exports=function(e){if(!e)return{};var t={};return i(n(e).split("\n"),function(e){var r,i=e.indexOf(":"),o=n(e.slice(0,i)).toLowerCase(),a=n(e.slice(i+1));void 0===t[o]?t[o]=a:(r=t[o],"[object Array]"===Object.prototype.toString.call(r)?t[o].push(a):t[o]=[t[o],a])}),t}},{"for-each":159,trim:324}],247:[function(e,t,r){r.pbkdf2=e("./lib/async"),r.pbkdf2Sync=e("./lib/sync")},{"./lib/async":248,"./lib/sync":251}],248:[function(e,t,r){(function(r,n){var i,o=e("./precondition"),a=e("./default-encoding"),s=e("./sync"),u=e("safe-buffer").Buffer,c=n.crypto&&n.crypto.subtle,f={sha:"SHA-1","sha-1":"SHA-1",sha1:"SHA-1",sha256:"SHA-256","sha-256":"SHA-256",sha384:"SHA-384","sha-384":"SHA-384","sha-512":"SHA-512",sha512:"SHA-512"},h=[];function l(e,t,r,n,i){return c.importKey("raw",e,{name:"PBKDF2"},!1,["deriveBits"]).then(function(e){return c.deriveBits({name:"PBKDF2",salt:t,iterations:r,hash:{name:i}},e,n<<3)}).then(function(e){return u.from(e)})}t.exports=function(e,t,d,p,b,y){if(u.isBuffer(e)||(e=u.from(e,a)),u.isBuffer(t)||(t=u.from(t,a)),o(d,p),"function"==typeof b&&(y=b,b=void 0),"function"!=typeof y)throw new Error("No callback provided to pbkdf2");var m=f[(b=b||"sha1").toLowerCase()];if(!m||"function"!=typeof n.Promise)return r.nextTick(function(){var r;try{r=s(e,t,d,p,b)}catch(e){return y(e)}y(null,r)});!function(e,t){e.then(function(e){r.nextTick(function(){t(null,e)})},function(e){r.nextTick(function(){t(e)})})}(function(e){if(n.process&&!n.process.browser)return Promise.resolve(!1);if(!c||!c.importKey||!c.deriveBits)return Promise.resolve(!1);if(void 0!==h[e])return h[e];var t=l(i=i||u.alloc(8),i,10,128,e).then(function(){return!0}).catch(function(){return!1});return h[e]=t,t}(m).then(function(r){return r?l(e,t,d,p,m):s(e,t,d,p,b)}),y)}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./default-encoding":249,"./precondition":250,"./sync":251,_process:257,"safe-buffer":290}],249:[function(e,t,r){(function(e){var r;e.browser?r="utf-8":r=parseInt(e.version.split(".")[0].slice(1),10)>=6?"utf-8":"binary";t.exports=r}).call(this,e("_process"))},{_process:257}],250:[function(e,t,r){var n=Math.pow(2,30)-1;t.exports=function(e,t){if("number"!=typeof e)throw new TypeError("Iterations not a number");if(e<0)throw new TypeError("Bad iterations");if("number"!=typeof t)throw new TypeError("Key length not a number");if(t<0||t>n||t!=t)throw new TypeError("Bad key length")}},{}],251:[function(e,t,r){var n=e("create-hash/md5"),i=e("ripemd160"),o=e("sha.js"),a=e("./precondition"),s=e("./default-encoding"),u=e("safe-buffer").Buffer,c=u.alloc(128),f={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,rmd160:20,ripemd160:20};function h(e,t,r){var a=function(e){return"rmd160"===e||"ripemd160"===e?i:"md5"===e?n:function(t){return o(e).update(t).digest()}}(e),s="sha512"===e||"sha384"===e?128:64;t.length>s?t=a(t):t.length1)for(var r=1;rp||new a(t).cmp(d.modulus)>=0)throw new Error("decryption error");l=f?c(new a(t),d):s(t,d);var b=new r(p-l.length);if(b.fill(0),l=r.concat([b,l],p),4===h)return function(e,t){e.modulus;var n=e.modulus.byteLength(),a=(t.length,u("sha1").update(new r("")).digest()),s=a.length;if(0!==t[0])throw new Error("decryption error");var c=t.slice(1,s+1),f=t.slice(s+1),h=o(c,i(f,s)),l=o(f,i(h,n-s-1));if(function(e,t){e=new r(e),t=new r(t);var n=0,i=e.length;e.length!==t.length&&(n++,i=Math.min(e.length,t.length));var o=-1;for(;++o=t.length){o++;break}var a=t.slice(2,i-1);t.slice(i-1,i);("0002"!==n.toString("hex")&&!r||"0001"!==n.toString("hex")&&r)&&o++;a.length<8&&o++;if(o)throw new Error("decryption error");return t.slice(i)}(0,l,f);if(3===h)return l;throw new Error("unknown padding")}}).call(this,e("buffer").Buffer)},{"./mgf":260,"./withPublic":263,"./xor":264,"bn.js":53,"browserify-rsa":76,buffer:84,"create-hash":91,"parse-asn1":245}],262:[function(e,t,r){(function(r){var n=e("parse-asn1"),i=e("randombytes"),o=e("create-hash"),a=e("./mgf"),s=e("./xor"),u=e("bn.js"),c=e("./withPublic"),f=e("browserify-rsa");t.exports=function(e,t,h){var l;l=e.padding?e.padding:h?1:4;var d,p=n(e);if(4===l)d=function(e,t){var n=e.modulus.byteLength(),c=t.length,f=o("sha1").update(new r("")).digest(),h=f.length,l=2*h;if(c>n-l-2)throw new Error("message too long");var d=new r(n-c-l-2);d.fill(0);var p=n-h-1,b=i(h),y=s(r.concat([f,d,new r([1]),t],p),a(b,p)),m=s(b,a(y,h));return new u(r.concat([new r([0]),m,y],n))}(p,t);else if(1===l)d=function(e,t,n){var o,a=t.length,s=e.modulus.byteLength();if(a>s-11)throw new Error("message too long");n?(o=new r(s-a-3)).fill(255):o=function(e,t){var n,o=new r(e),a=0,s=i(2*e),u=0;for(;a=0)throw new Error("data too long for modulus")}return h?f(d,p):c(d,p)}}).call(this,e("buffer").Buffer)},{"./mgf":260,"./withPublic":263,"./xor":264,"bn.js":53,"browserify-rsa":76,buffer:84,"create-hash":91,"parse-asn1":245,randombytes:270}],263:[function(e,t,r){(function(r){var n=e("bn.js");t.exports=function(e,t){return new r(e.toRed(n.mont(t.modulus)).redPow(new n(t.publicExponent)).fromRed().toArray())}}).call(this,e("buffer").Buffer)},{"bn.js":53,buffer:84}],264:[function(e,t,r){t.exports=function(e,t){for(var r=e.length,n=-1;++n= 0x80 (not a basic code point)","invalid-input":"Invalid input"},A=f-h,E=Math.floor,x=String.fromCharCode;function k(e){throw new RangeError(_[e])}function S(e,t){for(var r=e.length,n=[];r--;)n[r]=t(e[r]);return n}function M(e,t){var r=e.split("@"),n="";return r.length>1&&(n=r[0]+"@",e=r[1]),n+S((e=e.replace(w,".")).split("."),t).join(".")}function I(e){for(var t,r,n=[],i=0,o=e.length;i=55296&&t<=56319&&i65535&&(t+=x((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=x(e)}).join("")}function U(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function j(e,t,r){var n=0;for(e=r?E(e/p):e>>1,e+=E(e/t);e>A*l>>1;n+=f)e=E(e/A);return E(n+(A+1)*e/(e+d))}function B(e){var t,r,n,i,o,a,s,u,d,p,v,g=[],w=e.length,_=0,A=y,x=b;for((r=e.lastIndexOf(m))<0&&(r=0),n=0;n=128&&k("not-basic"),g.push(e.charCodeAt(n));for(i=r>0?r+1:0;i=w&&k("invalid-input"),((u=(v=e.charCodeAt(i++))-48<10?v-22:v-65<26?v-65:v-97<26?v-97:f)>=f||u>E((c-_)/a))&&k("overflow"),_+=u*a,!(u<(d=s<=x?h:s>=x+l?l:s-x));s+=f)a>E(c/(p=f-d))&&k("overflow"),a*=p;x=j(_-o,t=g.length+1,0==o),E(_/t)>c-A&&k("overflow"),A+=E(_/t),_%=t,g.splice(_++,0,A)}return T(g)}function P(e){var t,r,n,i,o,a,s,u,d,p,v,g,w,_,A,S=[];for(g=(e=I(e)).length,t=y,r=0,o=b,a=0;a=t&&vE((c-r)/(w=n+1))&&k("overflow"),r+=(s-t)*w,t=s,a=0;ac&&k("overflow"),v==t){for(u=r,d=f;!(u<(p=d<=o?h:d>=o+l?l:d-o));d+=f)A=u-p,_=f-p,S.push(x(U(p+A%_,0))),u=E(A/_);S.push(x(U(u,0))),o=j(r,w,n==i),r=0,++n}++r,++t}return S.join("")}if(s={version:"1.4.1",ucs2:{decode:I,encode:T},decode:B,encode:P,toASCII:function(e){return M(e,function(e){return g.test(e)?"xn--"+P(e):e})},toUnicode:function(e){return M(e,function(e){return v.test(e)?B(e.slice(4).toLowerCase()):e})}},"function"==typeof define&&"object"==typeof define.amd&&define.amd)define("punycode",function(){return s});else if(i&&o)if(t.exports==i)o.exports=s;else for(u in s)s.hasOwnProperty(u)&&(i[u]=s[u]);else n.punycode=s}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],266:[function(e,t,r){"use strict";var n=e("strict-uri-encode"),i=e("object-assign"),o=e("decode-uri-component");function a(e,t){return t.encode?t.strict?n(e):encodeURIComponent(e):e}function s(e){var t=e.indexOf("?");return-1===t?"":e.slice(t+1)}function u(e,t){var r=function(e){var t;switch(e.arrayFormat){case"index":return function(e,r,n){t=/\[(\d*)\]$/.exec(e),e=e.replace(/\[\d*\]$/,""),t?(void 0===n[e]&&(n[e]={}),n[e][t[1]]=r):n[e]=r};case"bracket":return function(e,r,n){t=/(\[\])$/.exec(e),e=e.replace(/\[\]$/,""),t?void 0!==n[e]?n[e]=[].concat(n[e],r):n[e]=[r]:n[e]=r};default:return function(e,t,r){void 0!==r[e]?r[e]=[].concat(r[e],t):r[e]=t}}}(t=i({arrayFormat:"none"},t)),n=Object.create(null);return"string"!=typeof e?n:(e=e.trim().replace(/^[?#&]/,""))?(e.split("&").forEach(function(e){var t=e.replace(/\+/g," ").split("="),i=t.shift(),a=t.length>0?t.join("="):void 0;a=void 0===a?null:o(a),r(o(i),a,n)}),Object.keys(n).sort().reduce(function(e,t){var r=n[t];return Boolean(r)&&"object"==typeof r&&!Array.isArray(r)?e[t]=function e(t){return Array.isArray(t)?t.sort():"object"==typeof t?e(Object.keys(t)).sort(function(e,t){return Number(e)-Number(t)}).map(function(e){return t[e]}):t}(r):e[t]=r,e},Object.create(null))):n}r.extract=s,r.parse=u,r.stringify=function(e,t){!1===(t=i({encode:!0,strict:!0,arrayFormat:"none"},t)).sort&&(t.sort=function(){});var r=function(e){switch(e.arrayFormat){case"index":return function(t,r,n){return null===r?[a(t,e),"[",n,"]"].join(""):[a(t,e),"[",a(n,e),"]=",a(r,e)].join("")};case"bracket":return function(t,r){return null===r?a(t,e):[a(t,e),"[]=",a(r,e)].join("")};default:return function(t,r){return null===r?a(t,e):[a(t,e),"=",a(r,e)].join("")}}}(t);return e?Object.keys(e).sort(t.sort).map(function(n){var i=e[n];if(void 0===i)return"";if(null===i)return a(n,t);if(Array.isArray(i)){var o=[];return i.slice().forEach(function(e){void 0!==e&&o.push(r(n,e,o.length))}),o.join("&")}return a(n,t)+"="+a(i,t)}).filter(function(e){return e.length>0}).join("&"):""},r.parseUrl=function(e,t){return{url:e.split("?")[0]||"",query:u(s(e),t)}}},{"decode-uri-component":98,"object-assign":238,"strict-uri-encode":316}],267:[function(e,t,r){"use strict";function n(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.exports=function(e,t,r,o){t=t||"&",r=r||"=";var a={};if("string"!=typeof e||0===e.length)return a;var s=/\+/g;e=e.split(t);var u=1e3;o&&"number"==typeof o.maxKeys&&(u=o.maxKeys);var c=e.length;u>0&&c>u&&(c=u);for(var f=0;f=0?(h=b.substr(0,y),l=b.substr(y+1)):(h=b,l=""),d=decodeURIComponent(h),p=decodeURIComponent(l),n(a,d)?i(a[d])?a[d].push(p):a[d]=[a[d],p]:a[d]=p}return a};var i=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],268:[function(e,t,r){"use strict";var n=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,r,s){return t=t||"&",r=r||"=",null===e&&(e=void 0),"object"==typeof e?o(a(e),function(a){var s=encodeURIComponent(n(a))+r;return i(e[a])?o(e[a],function(e){return s+encodeURIComponent(n(e))}).join(t):s+encodeURIComponent(n(e[a]))}).join(t):s?encodeURIComponent(n(s))+r+encodeURIComponent(n(e)):""};var i=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function o(e,t){if(e.map)return e.map(t);for(var r=[],n=0;n65536)throw new Error("requested too many random bytes");var a=new n.Uint8Array(e);e>0&&o.getRandomValues(a);var s=i.from(a.buffer);if("function"==typeof t)return r.nextTick(function(){t(null,s)});return s}:t.exports=function(){throw new Error("Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11")}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:257,"safe-buffer":290}],271:[function(e,t,r){(function(t,n){"use strict";function i(){throw new Error("secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11")}var o=e("safe-buffer"),a=e("randombytes"),s=o.Buffer,u=o.kMaxLength,c=n.crypto||n.msCrypto,f=Math.pow(2,32)-1;function h(e,t){if("number"!=typeof e||e!=e)throw new TypeError("offset must be a number");if(e>f||e<0)throw new TypeError("offset must be a uint32");if(e>u||e>t)throw new RangeError("offset out of range")}function l(e,t,r){if("number"!=typeof e||e!=e)throw new TypeError("size must be a number");if(e>f||e<0)throw new TypeError("size must be a uint32");if(e+t>r||e>u)throw new RangeError("buffer too small")}function d(e,r,n,i){if(t.browser){var o=e.buffer,s=new Uint8Array(o,r,n);return c.getRandomValues(s),i?void t.nextTick(function(){i(null,e)}):e}if(!i)return a(n).copy(e,r),e;a(n,function(t,n){if(t)return i(t);n.copy(e,r),i(null,e)})}c&&c.getRandomValues||!t.browser?(r.randomFill=function(e,t,r,i){if(!(s.isBuffer(e)||e instanceof n.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');if("function"==typeof t)i=t,t=0,r=e.length;else if("function"==typeof r)i=r,r=e.length-t;else if("function"!=typeof i)throw new TypeError('"cb" argument must be a function');return h(t,e.length),l(r,t,e.length),d(e,t,r,i)},r.randomFillSync=function(e,t,r){void 0===t&&(t=0);if(!(s.isBuffer(e)||e instanceof n.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');h(t,e.length),void 0===r&&(r=e.length-t);return l(r,t,e.length),d(e,t,r)}):(r.randomFill=i,r.randomFillSync=i)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:257,randombytes:270,"safe-buffer":290}],272:[function(e,t,r){t.exports=window.crypto},{}],273:[function(e,t,r){t.exports=e("crypto")},{crypto:272}],274:[function(e,t,r){t.exports=function(t,r){var n=e("./crypto.js"),i="function"==typeof r;if(t>65536){if(!i)throw new Error("Requested too many random bytes.");r(new Error("Requested too many random bytes."))}if(void 0!==n&&n.randomBytes){if(!i)return"0x"+n.randomBytes(t).toString("hex");n.randomBytes(t,function(e,t){e?r(u):r(null,"0x"+t.toString("hex"))})}else{var o;if(void 0!==n?o=n:"undefined"!=typeof msCrypto&&(o=msCrypto),o&&o.getRandomValues){var a=o.getRandomValues(new Uint8Array(t)),s="0x"+Array.from(a).map(function(e){return e.toString(16)}).join("");if(!i)return s;r(null,s)}else{var u=new Error('No "crypto" object available. This Browser doesn\'t support generating secure random bytes.');if(!i)throw u;r(u)}}}},{"./crypto.js":273}],275:[function(e,t,r){t.exports=e("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":276}],276:[function(e,t,r){"use strict";var n=e("process-nextick-args").nextTick,i=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};t.exports=h;var o=e("core-util-is");o.inherits=e("inherits");var a=e("./_stream_readable"),s=e("./_stream_writable");o.inherits(h,a);for(var u=i(s.prototype),c=0;c0?("string"==typeof t||a.objectMode||Object.getPrototypeOf(t)===c.prototype||(t=function(e){return c.from(e)}(t)),n?a.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):_(e,a,t,!0):a.ended?e.emit("error",new Error("stream.push() after EOF")):(a.reading=!1,a.decoder&&!r?(t=a.decoder.write(t),a.objectMode||0!==t.length?_(e,a,t,!1):S(e,a)):_(e,a,t,!1))):n||(a.reading=!1));return function(e){return!e.ended&&(e.needReadable||e.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=A?e=A:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function x(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(d("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?i(k,e):k(e))}function k(e){d("emit readable"),e.emit("readable"),U(e)}function S(e,t){t.readingMore||(t.readingMore=!0,i(M,e,t))}function M(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):r=function(e,t,r){var n;eo.length?o.length:e;if(a===o.length?i+=o:i+=o.slice(0,e),0===(e-=a)){a===o.length?(++n,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=o.slice(a));break}++n}return t.length-=n,i}(e,t):function(e,t){var r=c.allocUnsafe(e),n=t.head,i=1;n.data.copy(r),e-=n.data.length;for(;n=n.next;){var o=n.data,a=e>o.length?o.length:e;if(o.copy(r,r.length-e,0,a),0===(e-=a)){a===o.length?(++i,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(a));break}++i}return t.length-=i,r}(e,t);return n}(e,t.buffer,t.decoder),r);var r}function B(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,i(P,t,e))}function P(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function C(e,t){for(var r=0,n=e.length;r=t.highWaterMark||t.ended))return d("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?B(this):x(this),null;if(0===(e=E(e,t))&&t.ended)return 0===t.length&&B(this),null;var n,i=t.needReadable;return d("need readable",i),(0===t.length||t.length-e0?j(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&B(this)),null!==n&&this.emit("data",n),n},g.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},g.prototype.pipe=function(e,t){var n=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,d("pipe count=%d opts=%j",o.pipesCount,t);var u=(!t||!1!==t.end)&&e!==r.stdout&&e!==r.stderr?f:g;function c(t,r){d("onunpipe"),t===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,d("cleanup"),e.removeListener("close",m),e.removeListener("finish",v),e.removeListener("drain",h),e.removeListener("error",y),e.removeListener("unpipe",c),n.removeListener("end",f),n.removeListener("end",g),n.removeListener("data",b),l=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||h())}function f(){d("onend"),e.end()}o.endEmitted?i(u):n.once("end",u),e.on("unpipe",c);var h=function(e){return function(){var t=e._readableState;d("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&s(e,"data")&&(t.flowing=!0,U(e))}}(n);e.on("drain",h);var l=!1;var p=!1;function b(t){d("ondata"),p=!1,!1!==e.write(t)||p||((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==C(o.pipes,e))&&!l&&(d("false write response, pause",n._readableState.awaitDrain),n._readableState.awaitDrain++,p=!0),n.pause())}function y(t){d("onerror",t),g(),e.removeListener("error",y),0===s(e,"error")&&e.emit("error",t)}function m(){e.removeListener("finish",v),g()}function v(){d("onfinish"),e.removeListener("close",m),g()}function g(){d("unpipe"),n.unpipe(e)}return n.on("data",b),function(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?a(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}(e,"error",y),e.once("close",m),e.once("finish",v),e.emit("pipe",n),o.flowing||(d("pipe resume"),n.resume()),e},g.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r),this);if(!e){var n=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o-1?setImmediate:i;m.WritableState=y;var u=e("core-util-is");u.inherits=e("inherits");var c={deprecate:e("util-deprecate")},f=e("./internal/streams/stream"),h=e("safe-buffer").Buffer,l=n.Uint8Array||function(){};var d,p=e("./internal/streams/destroy");function b(){}function y(t,r){a=a||e("./_stream_duplex"),t=t||{};var n=r instanceof a;this.objectMode=!!t.objectMode,n&&(this.objectMode=this.objectMode||!!t.writableObjectMode);var u=t.highWaterMark,c=t.writableHighWaterMark,f=this.objectMode?16:16384;this.highWaterMark=u||0===u?u:n&&(c||0===c)?c:f,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var h=!1===t.decodeStrings;this.decodeStrings=!h,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var r=e._writableState,n=r.sync,o=r.writecb;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(r),t)!function(e,t,r,n,o){--t.pendingcb,r?(i(o,n),i(E,e,t),e._writableState.errorEmitted=!0,e.emit("error",n)):(o(n),e._writableState.errorEmitted=!0,e.emit("error",n),E(e,t))}(e,r,n,t,o);else{var a=_(r);a||r.corked||r.bufferProcessing||!r.bufferedRequest||w(e,r),n?s(g,e,r,a,o):g(e,r,a,o)}}(r,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new o(this)}function m(t){if(a=a||e("./_stream_duplex"),!(d.call(m,this)||this instanceof a))return new m(t);this._writableState=new y(t,this),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),f.call(this)}function v(e,t,r,n,i,o,a){t.writelen=n,t.writecb=a,t.writing=!0,t.sync=!0,r?e._writev(i,t.onwrite):e._write(i,o,t.onwrite),t.sync=!1}function g(e,t,r,n){r||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,n(),E(e,t)}function w(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var n=t.bufferedRequestCount,i=new Array(n),a=t.corkedRequestsFree;a.entry=r;for(var s=0,u=!0;r;)i[s]=r,r.isBuf||(u=!1),r=r.next,s+=1;i.allBuffers=u,v(e,t,!0,t.length,i,"",a.finish),t.pendingcb++,t.lastBufferedRequest=null,a.next?(t.corkedRequestsFree=a.next,a.next=null):t.corkedRequestsFree=new o(t),t.bufferedRequestCount=0}else{for(;r;){var c=r.chunk,f=r.encoding,h=r.callback;if(v(e,t,!1,t.objectMode?1:c.length,c,f,h),r=r.next,t.bufferedRequestCount--,t.writing)break}null===r&&(t.lastBufferedRequest=null)}t.bufferedRequest=r,t.bufferProcessing=!1}function _(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function A(e,t){e._final(function(r){t.pendingcb--,r&&e.emit("error",r),t.prefinished=!0,e.emit("prefinish"),E(e,t)})}function E(e,t){var r=_(t);return r&&(!function(e,t){t.prefinished||t.finalCalled||("function"==typeof e._final?(t.pendingcb++,t.finalCalled=!0,i(A,e,t)):(t.prefinished=!0,e.emit("prefinish")))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"))),r}u.inherits(m,f),y.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(y.prototype,"buffer",{get:c.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(d=Function.prototype[Symbol.hasInstance],Object.defineProperty(m,Symbol.hasInstance,{value:function(e){return!!d.call(this,e)||this===m&&(e&&e._writableState instanceof y)}})):d=function(e){return e instanceof this},m.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},m.prototype.write=function(e,t,r){var n,o=this._writableState,a=!1,s=!o.objectMode&&(n=e,h.isBuffer(n)||n instanceof l);return s&&!h.isBuffer(e)&&(e=function(e){return h.from(e)}(e)),"function"==typeof t&&(r=t,t=null),s?t="buffer":t||(t=o.defaultEncoding),"function"!=typeof r&&(r=b),o.ended?function(e,t){var r=new Error("write after end");e.emit("error",r),i(t,r)}(this,r):(s||function(e,t,r,n){var o=!0,a=!1;return null===r?a=new TypeError("May not write null values to stream"):"string"==typeof r||void 0===r||t.objectMode||(a=new TypeError("Invalid non-string/buffer chunk")),a&&(e.emit("error",a),i(n,a),o=!1),o}(this,o,e,r))&&(o.pendingcb++,a=function(e,t,r,n,i,o){if(!r){var a=function(e,t,r){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=h.from(t,r));return t}(t,n,i);n!==a&&(r=!0,i="buffer",n=a)}var s=t.objectMode?1:n.length;t.length+=s;var u=t.length-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},m.prototype._write=function(e,t,r){r(new Error("_write() is not implemented"))},m.prototype._writev=null,m.prototype.end=function(e,t,r){var n=this._writableState;"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||function(e,t,r){t.ending=!0,E(e,t),r&&(t.finished?i(r):e.once("finish",r));t.ended=!0,e.writable=!1}(this,n,r)},Object.defineProperty(m.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),m.prototype.destroy=p.destroy,m.prototype._undestroy=p.undestroy,m.prototype._destroy=function(e,t){this.end(),t(e)}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?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(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("util");t.exports=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.head=null,this.tail=null,this.length=0}return e.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},e.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},e.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r},e.prototype.concat=function(e){if(0===this.length)return n.alloc(0);if(1===this.length)return this.head.data;for(var t,r,i,o=n.allocUnsafe(e>>>0),a=this.head,s=0;a;)t=a.data,r=o,i=s,t.copy(r,i),s+=a.data.length,a=a.next;return o},e}(),i&&i.inspect&&i.inspect.custom&&(t.exports.prototype[i.inspect.custom]=function(){var e=i.inspect({length:this.length});return this.constructor.name+" "+e})},{"safe-buffer":290,util:55}],282:[function(e,t,r){"use strict";var n=e("process-nextick-args").nextTick;function i(e,t){e.emit("error",t)}t.exports={destroy:function(e,t){var r=this,o=this._readableState&&this._readableState.destroyed,a=this._writableState&&this._writableState.destroyed;return o||a?(t?t(e):!e||this._writableState&&this._writableState.errorEmitted||n(i,this,e),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!t&&e?(n(i,r,e),r._writableState&&(r._writableState.errorEmitted=!0)):t&&t(e)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}}},{"process-nextick-args":256}],283:[function(e,t,r){t.exports=e("events").EventEmitter},{events:157}],284:[function(e,t,r){t.exports=e("./readable").PassThrough},{"./readable":285}],285:[function(e,t,r){(r=t.exports=e("./lib/_stream_readable.js")).Stream=r,r.Readable=r,r.Writable=e("./lib/_stream_writable.js"),r.Duplex=e("./lib/_stream_duplex.js"),r.Transform=e("./lib/_stream_transform.js"),r.PassThrough=e("./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(e,t,r){t.exports=e("./readable").Transform},{"./readable":285}],287:[function(e,t,r){t.exports=e("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":280}],288:[function(e,t,r){(function(r){"use strict";var n=e("inherits"),i=e("hash-base");function o(){i.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function a(e,t){return e<>>32-t}function s(e,t,r,n,i,o,s,u){return a(e+(t^r^n)+o+s|0,u)+i|0}function u(e,t,r,n,i,o,s,u){return a(e+(t&r|~t&n)+o+s|0,u)+i|0}function c(e,t,r,n,i,o,s,u){return a(e+((t|~r)^n)+o+s|0,u)+i|0}function f(e,t,r,n,i,o,s,u){return a(e+(t&n|r&~n)+o+s|0,u)+i|0}function h(e,t,r,n,i,o,s,u){return a(e+(t^(r|~n))+o+s|0,u)+i|0}n(o,i),o.prototype._update=function(){for(var e=new Array(16),t=0;t<16;++t)e[t]=this._block.readInt32LE(4*t);var r=this._a,n=this._b,i=this._c,o=this._d,l=this._e;l=s(l,r=s(r,n,i,o,l,e[0],0,11),n,i=a(i,10),o,e[1],0,14),n=s(n=a(n,10),i=s(i,o=s(o,l,r,n,i,e[2],0,15),l,r=a(r,10),n,e[3],0,12),o,l=a(l,10),r,e[4],0,5),o=s(o=a(o,10),l=s(l,r=s(r,n,i,o,l,e[5],0,8),n,i=a(i,10),o,e[6],0,7),r,n=a(n,10),i,e[7],0,9),r=s(r=a(r,10),n=s(n,i=s(i,o,l,r,n,e[8],0,11),o,l=a(l,10),r,e[9],0,13),i,o=a(o,10),l,e[10],0,14),i=s(i=a(i,10),o=s(o,l=s(l,r,n,i,o,e[11],0,15),r,n=a(n,10),i,e[12],0,6),l,r=a(r,10),n,e[13],0,7),l=u(l=a(l,10),r=s(r,n=s(n,i,o,l,r,e[14],0,9),i,o=a(o,10),l,e[15],0,8),n,i=a(i,10),o,e[7],1518500249,7),n=u(n=a(n,10),i=u(i,o=u(o,l,r,n,i,e[4],1518500249,6),l,r=a(r,10),n,e[13],1518500249,8),o,l=a(l,10),r,e[1],1518500249,13),o=u(o=a(o,10),l=u(l,r=u(r,n,i,o,l,e[10],1518500249,11),n,i=a(i,10),o,e[6],1518500249,9),r,n=a(n,10),i,e[15],1518500249,7),r=u(r=a(r,10),n=u(n,i=u(i,o,l,r,n,e[3],1518500249,15),o,l=a(l,10),r,e[12],1518500249,7),i,o=a(o,10),l,e[0],1518500249,12),i=u(i=a(i,10),o=u(o,l=u(l,r,n,i,o,e[9],1518500249,15),r,n=a(n,10),i,e[5],1518500249,9),l,r=a(r,10),n,e[2],1518500249,11),l=u(l=a(l,10),r=u(r,n=u(n,i,o,l,r,e[14],1518500249,7),i,o=a(o,10),l,e[11],1518500249,13),n,i=a(i,10),o,e[8],1518500249,12),n=c(n=a(n,10),i=c(i,o=c(o,l,r,n,i,e[3],1859775393,11),l,r=a(r,10),n,e[10],1859775393,13),o,l=a(l,10),r,e[14],1859775393,6),o=c(o=a(o,10),l=c(l,r=c(r,n,i,o,l,e[4],1859775393,7),n,i=a(i,10),o,e[9],1859775393,14),r,n=a(n,10),i,e[15],1859775393,9),r=c(r=a(r,10),n=c(n,i=c(i,o,l,r,n,e[8],1859775393,13),o,l=a(l,10),r,e[1],1859775393,15),i,o=a(o,10),l,e[2],1859775393,14),i=c(i=a(i,10),o=c(o,l=c(l,r,n,i,o,e[7],1859775393,8),r,n=a(n,10),i,e[0],1859775393,13),l,r=a(r,10),n,e[6],1859775393,6),l=c(l=a(l,10),r=c(r,n=c(n,i,o,l,r,e[13],1859775393,5),i,o=a(o,10),l,e[11],1859775393,12),n,i=a(i,10),o,e[5],1859775393,7),n=f(n=a(n,10),i=f(i,o=c(o,l,r,n,i,e[12],1859775393,5),l,r=a(r,10),n,e[1],2400959708,11),o,l=a(l,10),r,e[9],2400959708,12),o=f(o=a(o,10),l=f(l,r=f(r,n,i,o,l,e[11],2400959708,14),n,i=a(i,10),o,e[10],2400959708,15),r,n=a(n,10),i,e[0],2400959708,14),r=f(r=a(r,10),n=f(n,i=f(i,o,l,r,n,e[8],2400959708,15),o,l=a(l,10),r,e[12],2400959708,9),i,o=a(o,10),l,e[4],2400959708,8),i=f(i=a(i,10),o=f(o,l=f(l,r,n,i,o,e[13],2400959708,9),r,n=a(n,10),i,e[3],2400959708,14),l,r=a(r,10),n,e[7],2400959708,5),l=f(l=a(l,10),r=f(r,n=f(n,i,o,l,r,e[15],2400959708,6),i,o=a(o,10),l,e[14],2400959708,8),n,i=a(i,10),o,e[5],2400959708,6),n=h(n=a(n,10),i=f(i,o=f(o,l,r,n,i,e[6],2400959708,5),l,r=a(r,10),n,e[2],2400959708,12),o,l=a(l,10),r,e[4],2840853838,9),o=h(o=a(o,10),l=h(l,r=h(r,n,i,o,l,e[0],2840853838,15),n,i=a(i,10),o,e[5],2840853838,5),r,n=a(n,10),i,e[9],2840853838,11),r=h(r=a(r,10),n=h(n,i=h(i,o,l,r,n,e[7],2840853838,6),o,l=a(l,10),r,e[12],2840853838,8),i,o=a(o,10),l,e[2],2840853838,13),i=h(i=a(i,10),o=h(o,l=h(l,r,n,i,o,e[10],2840853838,12),r,n=a(n,10),i,e[14],2840853838,5),l,r=a(r,10),n,e[1],2840853838,12),l=h(l=a(l,10),r=h(r,n=h(n,i,o,l,r,e[3],2840853838,13),i,o=a(o,10),l,e[8],2840853838,14),n,i=a(i,10),o,e[11],2840853838,11),n=h(n=a(n,10),i=h(i,o=h(o,l,r,n,i,e[6],2840853838,8),l,r=a(r,10),n,e[15],2840853838,5),o,l=a(l,10),r,e[13],2840853838,6),o=a(o,10);var d=this._a,p=this._b,b=this._c,y=this._d,m=this._e;m=h(m,d=h(d,p,b,y,m,e[5],1352829926,8),p,b=a(b,10),y,e[14],1352829926,9),p=h(p=a(p,10),b=h(b,y=h(y,m,d,p,b,e[7],1352829926,9),m,d=a(d,10),p,e[0],1352829926,11),y,m=a(m,10),d,e[9],1352829926,13),y=h(y=a(y,10),m=h(m,d=h(d,p,b,y,m,e[2],1352829926,15),p,b=a(b,10),y,e[11],1352829926,15),d,p=a(p,10),b,e[4],1352829926,5),d=h(d=a(d,10),p=h(p,b=h(b,y,m,d,p,e[13],1352829926,7),y,m=a(m,10),d,e[6],1352829926,7),b,y=a(y,10),m,e[15],1352829926,8),b=h(b=a(b,10),y=h(y,m=h(m,d,p,b,y,e[8],1352829926,11),d,p=a(p,10),b,e[1],1352829926,14),m,d=a(d,10),p,e[10],1352829926,14),m=f(m=a(m,10),d=h(d,p=h(p,b,y,m,d,e[3],1352829926,12),b,y=a(y,10),m,e[12],1352829926,6),p,b=a(b,10),y,e[6],1548603684,9),p=f(p=a(p,10),b=f(b,y=f(y,m,d,p,b,e[11],1548603684,13),m,d=a(d,10),p,e[3],1548603684,15),y,m=a(m,10),d,e[7],1548603684,7),y=f(y=a(y,10),m=f(m,d=f(d,p,b,y,m,e[0],1548603684,12),p,b=a(b,10),y,e[13],1548603684,8),d,p=a(p,10),b,e[5],1548603684,9),d=f(d=a(d,10),p=f(p,b=f(b,y,m,d,p,e[10],1548603684,11),y,m=a(m,10),d,e[14],1548603684,7),b,y=a(y,10),m,e[15],1548603684,7),b=f(b=a(b,10),y=f(y,m=f(m,d,p,b,y,e[8],1548603684,12),d,p=a(p,10),b,e[12],1548603684,7),m,d=a(d,10),p,e[4],1548603684,6),m=f(m=a(m,10),d=f(d,p=f(p,b,y,m,d,e[9],1548603684,15),b,y=a(y,10),m,e[1],1548603684,13),p,b=a(b,10),y,e[2],1548603684,11),p=c(p=a(p,10),b=c(b,y=c(y,m,d,p,b,e[15],1836072691,9),m,d=a(d,10),p,e[5],1836072691,7),y,m=a(m,10),d,e[1],1836072691,15),y=c(y=a(y,10),m=c(m,d=c(d,p,b,y,m,e[3],1836072691,11),p,b=a(b,10),y,e[7],1836072691,8),d,p=a(p,10),b,e[14],1836072691,6),d=c(d=a(d,10),p=c(p,b=c(b,y,m,d,p,e[6],1836072691,6),y,m=a(m,10),d,e[9],1836072691,14),b,y=a(y,10),m,e[11],1836072691,12),b=c(b=a(b,10),y=c(y,m=c(m,d,p,b,y,e[8],1836072691,13),d,p=a(p,10),b,e[12],1836072691,5),m,d=a(d,10),p,e[2],1836072691,14),m=c(m=a(m,10),d=c(d,p=c(p,b,y,m,d,e[10],1836072691,13),b,y=a(y,10),m,e[0],1836072691,13),p,b=a(b,10),y,e[4],1836072691,7),p=u(p=a(p,10),b=u(b,y=c(y,m,d,p,b,e[13],1836072691,5),m,d=a(d,10),p,e[8],2053994217,15),y,m=a(m,10),d,e[6],2053994217,5),y=u(y=a(y,10),m=u(m,d=u(d,p,b,y,m,e[4],2053994217,8),p,b=a(b,10),y,e[1],2053994217,11),d,p=a(p,10),b,e[3],2053994217,14),d=u(d=a(d,10),p=u(p,b=u(b,y,m,d,p,e[11],2053994217,14),y,m=a(m,10),d,e[15],2053994217,6),b,y=a(y,10),m,e[0],2053994217,14),b=u(b=a(b,10),y=u(y,m=u(m,d,p,b,y,e[5],2053994217,6),d,p=a(p,10),b,e[12],2053994217,9),m,d=a(d,10),p,e[2],2053994217,12),m=u(m=a(m,10),d=u(d,p=u(p,b,y,m,d,e[13],2053994217,9),b,y=a(y,10),m,e[9],2053994217,12),p,b=a(b,10),y,e[7],2053994217,5),p=s(p=a(p,10),b=u(b,y=u(y,m,d,p,b,e[10],2053994217,15),m,d=a(d,10),p,e[14],2053994217,8),y,m=a(m,10),d,e[12],0,8),y=s(y=a(y,10),m=s(m,d=s(d,p,b,y,m,e[15],0,5),p,b=a(b,10),y,e[10],0,12),d,p=a(p,10),b,e[4],0,9),d=s(d=a(d,10),p=s(p,b=s(b,y,m,d,p,e[1],0,12),y,m=a(m,10),d,e[5],0,5),b,y=a(y,10),m,e[8],0,14),b=s(b=a(b,10),y=s(y,m=s(m,d,p,b,y,e[7],0,6),d,p=a(p,10),b,e[6],0,8),m,d=a(d,10),p,e[2],0,13),m=s(m=a(m,10),d=s(d,p=s(p,b,y,m,d,e[13],0,6),b,y=a(y,10),m,e[14],0,5),p,b=a(b,10),y,e[0],0,15),p=s(p=a(p,10),b=s(b,y=s(y,m,d,p,b,e[3],0,13),m,d=a(d,10),p,e[9],0,11),y,m=a(m,10),d,e[11],0,11),y=a(y,10);var v=this._b+i+y|0;this._b=this._c+o+m|0,this._c=this._d+l+d|0,this._d=this._e+r+p|0,this._e=this._a+n+b|0,this._a=v},o.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=new r(20);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e.writeInt32LE(this._e,16),e},t.exports=o}).call(this,e("buffer").Buffer)},{buffer:84,"hash-base":161,inherits:180}],289:[function(e,t,r){const n=e("assert"),i=e("safe-buffer").Buffer;function o(e,t){if("00"===e.slice(0,2))throw new Error("invalid RLP: extra zeros");return parseInt(e,t)}function a(e,t){if(e<56)return i.from([e+t]);var r=u(e),n=u(t+55+r.length/2);return i.from(n+r,"hex")}function s(e){return"0x"===e.slice(0,2)}function u(e){var t=e.toString(16);return t.length%2&&(t="0"+t),t}function c(e){if(!i.isBuffer(e))if("string"==typeof e)e=s(e)?i.from(((r="string"!=typeof(n=e)?n:s(n)?n.slice(2):n).length%2&&(r="0"+r),r),"hex"):i.from(e);else if("number"==typeof e)e?(t=u(e),e=i.from(t,"hex")):e=i.from([]);else if(null==e)e=i.from([]);else{if(!e.toArray)throw new Error("invalid type");e=i.from(e.toArray())}var t,r,n;return e}r.encode=function(e){if(e instanceof Array){for(var t=[],n=0;nt.length)throw new Error("invalid rlp: total length is larger than the data");if(0===(s=t.slice(n,h)).length)throw new Error("invalid rlp, List has a invalid length");for(;s.length;)u=e(s),c.push(u.data),s=u.remainder;return{data:c,remainder:t.slice(h)}}(e=c(e));return t?r:(n.equal(r.remainder.length,0,"invalid remainder"),r.data)},r.getLength=function(e){if(!e||0===e.length)return i.from([]);var t=(e=c(e))[0];if(t<=127)return e.length;if(t<=183)return t-127;if(t<=191)return t-182;if(t<=247)return t-191;var r=t-246;return r+o(e.slice(1,r).toString("hex"),16)}},{assert:19,"safe-buffer":290}],290:[function(e,t,r){var n=e("buffer"),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function a(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=n:(o(n,r),r.Buffer=a),o(i,a),a.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},a.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},{buffer:84}],291:[function(e,t,r){const n=e("util"),i=e("events/");var o="object"==typeof Reflect?Reflect:null,a=o&&"function"==typeof o.apply?o.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};function s(){i.call(this)}function u(e,t,r){try{a(e,t,r)}catch(e){setTimeout(()=>{throw e})}}t.exports=s,n.inherits(s,i),s.prototype.emit=function(e){for(var t=[],r=1;r0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var s=i[e];if(void 0===s)return!1;if("function"==typeof s)u(s,this,t);else{var c=s.length,f=function(e,t){for(var r=new Array(t),n=0;n0&&a.length>i&&!a.warned){a.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=a.length,s=u,console&&console.warn&&console.warn(s)}return e}function h(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=function(){for(var e=[],t=0;t0&&(a=t[0]),a instanceof Error)throw a;var s=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw s.context=a,s}var u=i[e];if(void 0===u)return!1;if("function"==typeof u)o(u,this,t);else{var c=u.length,f=p(u,c);for(r=0;r=0;o--)if(r[o]===t||r[o].listener===t){a=r[o].listener,i=o;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1=0;n--)this.removeListener(e,t[n]);return this},s.prototype.listeners=function(e){return l(this,e,!0)},s.prototype.rawListeners=function(e){return l(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):d.call(e,t)},s.prototype.listenerCount=d,s.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]}},{}],293:[function(e,t,r){t.exports=e("scryptsy")},{scryptsy:294}],294:[function(e,t,r){(function(r){var n=e("pbkdf2").pbkdf2Sync,i=2147483647;function o(e,t,n,i,o){if(r.isBuffer(e)&&r.isBuffer(n))e.copy(n,i,t,t+o);else for(;o--;)n[i++]=e[t++]}t.exports=function(e,t,a,s,u,c,f){if(0===a||0!=(a&a-1))throw Error("N must be > 0 and a power of 2");if(a>i/128/s)throw Error("Parameter N is too large");if(s>i/128/u)throw Error("Parameter r is too large");var h,l=new r(256*s),d=new r(128*s*a),p=new Int32Array(16),b=new Int32Array(16),y=new r(64),m=n(e,t,1,128*u*s,"sha256");if(f){var v=u*a*2,g=0;h=function(){++g%1e3==0&&f({current:g,total:v,percent:g/v*100})}}for(var w=0;w>>32-t}function x(e){var t;for(t=0;t<16;t++)p[t]=(255&e[4*t+0])<<0,p[t]|=(255&e[4*t+1])<<8,p[t]|=(255&e[4*t+2])<<16,p[t]|=(255&e[4*t+3])<<24;for(o(p,0,b,0,16),t=8;t>0;t-=2)b[4]^=E(b[0]+b[12],7),b[8]^=E(b[4]+b[0],9),b[12]^=E(b[8]+b[4],13),b[0]^=E(b[12]+b[8],18),b[9]^=E(b[5]+b[1],7),b[13]^=E(b[9]+b[5],9),b[1]^=E(b[13]+b[9],13),b[5]^=E(b[1]+b[13],18),b[14]^=E(b[10]+b[6],7),b[2]^=E(b[14]+b[10],9),b[6]^=E(b[2]+b[14],13),b[10]^=E(b[6]+b[2],18),b[3]^=E(b[15]+b[11],7),b[7]^=E(b[3]+b[15],9),b[11]^=E(b[7]+b[3],13),b[15]^=E(b[11]+b[7],18),b[1]^=E(b[0]+b[3],7),b[2]^=E(b[1]+b[0],9),b[3]^=E(b[2]+b[1],13),b[0]^=E(b[3]+b[2],18),b[6]^=E(b[5]+b[4],7),b[7]^=E(b[6]+b[5],9),b[4]^=E(b[7]+b[6],13),b[5]^=E(b[4]+b[7],18),b[11]^=E(b[10]+b[9],7),b[8]^=E(b[11]+b[10],9),b[9]^=E(b[8]+b[11],13),b[10]^=E(b[9]+b[8],18),b[12]^=E(b[15]+b[14],7),b[13]^=E(b[12]+b[15],9),b[14]^=E(b[13]+b[12],13),b[15]^=E(b[14]+b[13],18);for(t=0;t<16;++t)p[t]=b[t]+p[t];for(t=0;t<16;t++){var r=4*t;e[r+0]=p[t]>>0&255,e[r+1]=p[t]>>8&255,e[r+2]=p[t]>>16&255,e[r+3]=p[t]>>24&255}}function k(e,t,r,n,i){for(var o=0;o=r)throw RangeError(n)}}).call(this,{isBuffer:e("../../is-buffer/index.js")})},{"../../is-buffer/index.js":181}],297:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("bip66"),o=n.from([48,129,211,2,1,1,4,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,160,129,133,48,129,130,2,1,1,48,44,6,7,42,134,72,206,61,1,1,2,33,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,255,255,252,47,48,6,4,1,0,4,1,7,4,33,2,121,190,102,126,249,220,187,172,85,160,98,149,206,135,11,7,2,155,252,219,45,206,40,217,89,242,129,91,22,248,23,152,2,33,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,186,174,220,230,175,72,160,59,191,210,94,140,208,54,65,65,2,1,1,161,36,3,34,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),a=n.from([48,130,1,19,2,1,1,4,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,160,129,165,48,129,162,2,1,1,48,44,6,7,42,134,72,206,61,1,1,2,33,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,255,255,252,47,48,6,4,1,0,4,1,7,4,65,4,121,190,102,126,249,220,187,172,85,160,98,149,206,135,11,7,2,155,252,219,45,206,40,217,89,242,129,91,22,248,23,152,72,58,218,119,38,163,196,101,93,164,251,252,14,17,8,168,253,23,180,72,166,133,84,25,156,71,208,143,251,16,212,184,2,33,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,186,174,220,230,175,72,160,59,191,210,94,140,208,54,65,65,2,1,1,161,68,3,66,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);r.privateKeyExport=function(e,t,r){var i=n.from(r?o:a);return e.copy(i,r?8:9),t.copy(i,r?181:214),i},r.privateKeyImport=function(e){var t=e.length,r=0;if(!(t2||t1?e[r+n-2]<<8:0);if(!(t<(r+=n)+i||t32||t1&&0===t[o]&&!(128&t[o+1]);--r,++o);for(var a=n.concat([n.from([0]),e.s]),s=33,u=0;s>1&&0===a[u]&&!(128&a[u+1]);--s,++u);return i.encode(t.slice(o),a.slice(u))},r.signatureImport=function(e){var t=n.alloc(32,0),r=n.alloc(32,0);try{var o=i.decode(e);if(33===o.r.length&&0===o.r[0]&&(o.r=o.r.slice(1)),o.r.length>32)throw new Error("R length is too long");if(33===o.s.length&&0===o.s[0]&&(o.s=o.s.slice(1)),o.s.length>32)throw new Error("S length is too long")}catch(e){return}return o.r.copy(t,32-o.r.length),o.s.copy(r,32-o.s.length),{r:t,s:r}},r.signatureImportLax=function(e){var t=n.alloc(32,0),r=n.alloc(32,0),i=e.length,o=0;if(48===e[o++]){var a=e[o++];if(!(128&a&&(o+=a-128)>i)&&2===e[o++]){var s=e[o++];if(128&s){if(o+(a=s-128)>i)return;for(;a>0&&0===e[o];o+=1,a-=1);for(s=0;a>0;o+=1,a-=1)s=(s<<8)+e[o]}if(!(s>i-o)){var u=o;if(o+=s,2===e[o++]){var c=e[o++];if(128&c){if(o+(a=c-128)>i)return;for(;a>0&&0===e[o];o+=1,a-=1);for(c=0;a>0;o+=1,a-=1)c=(c<<8)+e[o]}if(!(c>i-o)){var f=o;for(o+=c;s>0&&0===e[u];s-=1,u+=1);if(!(s>32)){var h=e.slice(u,u+s);for(h.copy(t,32-h.length);c>0&&0===e[f];c-=1,f+=1);if(!(c>32)){var l=e.slice(f,f+c);return l.copy(r,32-l.length),{r:t,s:r}}}}}}}}}},{bip66:52,"safe-buffer":290}],298:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("create-hash"),o=e("bn.js"),a=e("elliptic").ec,s=e("../messages.json"),u=new a("secp256k1"),c=u.curve;function f(e){var t=e[0];switch(t){case 2:case 3:return 33!==e.length?null:function(e,t){var r=new o(t);if(r.cmp(c.p)>=0)return null;var n=(r=r.toRed(c.red)).redSqr().redIMul(r).redIAdd(c.b).redSqrt();return 3===e!==n.isOdd()&&(n=n.redNeg()),u.keyPair({pub:{x:r,y:n}})}(t,e.slice(1,33));case 4:case 6:case 7:return 65!==e.length?null:function(e,t,r){var n=new o(t),i=new o(r);if(n.cmp(c.p)>=0||i.cmp(c.p)>=0)return null;if(n=n.toRed(c.red),i=i.toRed(c.red),(6===e||7===e)&&i.isOdd()!==(7===e))return null;var a=n.redSqr().redIMul(n);return i.redSqr().redISub(a.redIAdd(c.b)).isZero()?u.keyPair({pub:{x:n,y:i}}):null}(t,e.slice(1,33),e.slice(33,65));default:return null}}r.privateKeyVerify=function(e){var t=new o(e);return t.cmp(c.n)<0&&!t.isZero()},r.privateKeyExport=function(e,t){var r=new o(e);if(r.cmp(c.n)>=0||r.isZero())throw new Error(s.EC_PRIVATE_KEY_EXPORT_DER_FAIL);return n.from(u.keyFromPrivate(e).getPublic(t,!0))},r.privateKeyNegate=function(e){var t=new o(e);return t.isZero()?n.alloc(32):c.n.sub(t).umod(c.n).toArrayLike(n,"be",32)},r.privateKeyModInverse=function(e){var t=new o(e);if(t.cmp(c.n)>=0||t.isZero())throw new Error(s.EC_PRIVATE_KEY_RANGE_INVALID);return t.invm(c.n).toArrayLike(n,"be",32)},r.privateKeyTweakAdd=function(e,t){var r=new o(t);if(r.cmp(c.n)>=0)throw new Error(s.EC_PRIVATE_KEY_TWEAK_ADD_FAIL);if(r.iadd(new o(e)),r.cmp(c.n)>=0&&r.isub(c.n),r.isZero())throw new Error(s.EC_PRIVATE_KEY_TWEAK_ADD_FAIL);return r.toArrayLike(n,"be",32)},r.privateKeyTweakMul=function(e,t){var r=new o(t);if(r.cmp(c.n)>=0||r.isZero())throw new Error(s.EC_PRIVATE_KEY_TWEAK_MUL_FAIL);return r.imul(new o(e)),r.cmp(c.n)&&(r=r.umod(c.n)),r.toArrayLike(n,"be",32)},r.publicKeyCreate=function(e,t){var r=new o(e);if(r.cmp(c.n)>=0||r.isZero())throw new Error(s.EC_PUBLIC_KEY_CREATE_FAIL);return n.from(u.keyFromPrivate(e).getPublic(t,!0))},r.publicKeyConvert=function(e,t){var r=f(e);if(null===r)throw new Error(s.EC_PUBLIC_KEY_PARSE_FAIL);return n.from(r.getPublic(t,!0))},r.publicKeyVerify=function(e){return null!==f(e)},r.publicKeyTweakAdd=function(e,t,r){var i=f(e);if(null===i)throw new Error(s.EC_PUBLIC_KEY_PARSE_FAIL);if((t=new o(t)).cmp(c.n)>=0)throw new Error(s.EC_PUBLIC_KEY_TWEAK_ADD_FAIL);return n.from(c.g.mul(t).add(i.pub).encode(!0,r))},r.publicKeyTweakMul=function(e,t,r){var i=f(e);if(null===i)throw new Error(s.EC_PUBLIC_KEY_PARSE_FAIL);if((t=new o(t)).cmp(c.n)>=0||t.isZero())throw new Error(s.EC_PUBLIC_KEY_TWEAK_MUL_FAIL);return n.from(i.pub.mul(t).encode(!0,r))},r.publicKeyCombine=function(e,t){for(var r=new Array(e.length),i=0;i=0||r.cmp(c.n)>=0)throw new Error(s.ECDSA_SIGNATURE_PARSE_FAIL);var i=n.from(e);return 1===r.cmp(u.nh)&&c.n.sub(r).toArrayLike(n,"be",32).copy(i,32),i},r.signatureExport=function(e){var t=e.slice(0,32),r=e.slice(32,64);if(new o(t).cmp(c.n)>=0||new o(r).cmp(c.n)>=0)throw new Error(s.ECDSA_SIGNATURE_PARSE_FAIL);return{r:t,s:r}},r.signatureImport=function(e){var t=new o(e.r);t.cmp(c.n)>=0&&(t=new o(0));var r=new o(e.s);return r.cmp(c.n)>=0&&(r=new o(0)),n.concat([t.toArrayLike(n,"be",32),r.toArrayLike(n,"be",32)])},r.sign=function(e,t,r,i){if("function"==typeof r){var a=r;r=function(r){var u=a(e,t,null,i,r);if(!n.isBuffer(u)||32!==u.length)throw new Error(s.ECDSA_SIGN_FAIL);return new o(u)}}var f=new o(t);if(f.cmp(c.n)>=0||f.isZero())throw new Error(s.ECDSA_SIGN_FAIL);var h=u.sign(e,t,{canonical:!0,k:r,pers:i});return{signature:n.concat([h.r.toArrayLike(n,"be",32),h.s.toArrayLike(n,"be",32)]),recovery:h.recoveryParam}},r.verify=function(e,t,r){var n={r:t.slice(0,32),s:t.slice(32,64)},i=new o(n.r),a=new o(n.s);if(i.cmp(c.n)>=0||a.cmp(c.n)>=0)throw new Error(s.ECDSA_SIGNATURE_PARSE_FAIL);if(1===a.cmp(u.nh)||i.isZero()||a.isZero())return!1;var h=f(r);if(null===h)throw new Error(s.EC_PUBLIC_KEY_PARSE_FAIL);return u.verify(e,n,{x:h.pub.x,y:h.pub.y})},r.recover=function(e,t,r,i){var a={r:t.slice(0,32),s:t.slice(32,64)},f=new o(a.r),h=new o(a.s);if(f.cmp(c.n)>=0||h.cmp(c.n)>=0)throw new Error(s.ECDSA_SIGNATURE_PARSE_FAIL);try{if(f.isZero()||h.isZero())throw new Error;var l=u.recoverPubKey(e,a,r);return n.from(l.encode(!0,i))}catch(e){throw new Error(s.ECDSA_RECOVER_FAIL)}},r.ecdh=function(e,t){var n=r.ecdhUnsafe(e,t,!0);return i("sha256").update(n).digest()},r.ecdhUnsafe=function(e,t,r){var i=f(e);if(null===i)throw new Error(s.EC_PUBLIC_KEY_PARSE_FAIL);var a=new o(t);if(a.cmp(c.n)>=0||a.isZero())throw new Error(s.ECDH_FAIL);return n.from(i.pub.mul(a).encode(!0,r))}},{"../messages.json":300,"bn.js":53,"create-hash":91,elliptic:109,"safe-buffer":290}],299:[function(e,t,r){"use strict";var n=e("./assert"),i=e("./der"),o=e("./messages.json");function a(e,t){return void 0===e?t:(n.isBoolean(e,o.COMPRESSED_TYPE_INVALID),e)}t.exports=function(e){return{privateKeyVerify:function(t){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),32===t.length&&e.privateKeyVerify(t)},privateKeyExport:function(t,r){n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),r=a(r,!0);var s=e.privateKeyExport(t,r);return i.privateKeyExport(t,s,r)},privateKeyImport:function(t){if(n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),(t=i.privateKeyImport(t))&&32===t.length&&e.privateKeyVerify(t))return t;throw new Error(o.EC_PRIVATE_KEY_IMPORT_DER_FAIL)},privateKeyNegate:function(t){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),e.privateKeyNegate(t)},privateKeyModInverse:function(t){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),e.privateKeyModInverse(t)},privateKeyTweakAdd:function(t,r){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),n.isBuffer(r,o.TWEAK_TYPE_INVALID),n.isBufferLength(r,32,o.TWEAK_LENGTH_INVALID),e.privateKeyTweakAdd(t,r)},privateKeyTweakMul:function(t,r){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),n.isBuffer(r,o.TWEAK_TYPE_INVALID),n.isBufferLength(r,32,o.TWEAK_LENGTH_INVALID),e.privateKeyTweakMul(t,r)},publicKeyCreate:function(t,r){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),r=a(r,!0),e.publicKeyCreate(t,r)},publicKeyConvert:function(t,r){return n.isBuffer(t,o.EC_PUBLIC_KEY_TYPE_INVALID),n.isBufferLength2(t,33,65,o.EC_PUBLIC_KEY_LENGTH_INVALID),r=a(r,!0),e.publicKeyConvert(t,r)},publicKeyVerify:function(t){return n.isBuffer(t,o.EC_PUBLIC_KEY_TYPE_INVALID),e.publicKeyVerify(t)},publicKeyTweakAdd:function(t,r,i){return n.isBuffer(t,o.EC_PUBLIC_KEY_TYPE_INVALID),n.isBufferLength2(t,33,65,o.EC_PUBLIC_KEY_LENGTH_INVALID),n.isBuffer(r,o.TWEAK_TYPE_INVALID),n.isBufferLength(r,32,o.TWEAK_LENGTH_INVALID),i=a(i,!0),e.publicKeyTweakAdd(t,r,i)},publicKeyTweakMul:function(t,r,i){return n.isBuffer(t,o.EC_PUBLIC_KEY_TYPE_INVALID),n.isBufferLength2(t,33,65,o.EC_PUBLIC_KEY_LENGTH_INVALID),n.isBuffer(r,o.TWEAK_TYPE_INVALID),n.isBufferLength(r,32,o.TWEAK_LENGTH_INVALID),i=a(i,!0),e.publicKeyTweakMul(t,r,i)},publicKeyCombine:function(t,r){n.isArray(t,o.EC_PUBLIC_KEYS_TYPE_INVALID),n.isLengthGTZero(t,o.EC_PUBLIC_KEYS_LENGTH_INVALID);for(var i=0;i=2&&("function"==typeof arguments[1]?r.task=arguments[1]:r.n=arguments[1]);var n=r.task;if(r.task=function(){n(t.leave)},t.current+r.n-e>t.capacity)return 1===e&&(t.current--,t.firstHere=!1),t.queue.push(r);t.current+=r.n-e,r.task(t.leave),1===e&&(t.firstHere=!1)},leave:function(e){if(e=e||1,t.current-=e,t.queue.length){var r=t.queue[0];r.n+t.current>t.capacity||(t.queue.shift(),t.current+=r.n,i(r.task))}else if(t.current<0)throw new Error("leave called too many times.")},available:function(e){return e=e||1,t.current+e<=t.capacity}};return t}void 0!==e&&e&&"function"==typeof e.nextTick&&(i=e.nextTick),"object"==typeof r?t.exports=o:"function"==typeof define&&define.amd?define(function(){return o}):n.semaphore=o}(this)}).call(this,e("_process"))},{_process:257}],302:[function(e,t,r){"use strict";t.exports="function"==typeof setImmediate?setImmediate:function(){var e=[].slice.apply(arguments);e.splice(1,0,0),setTimeout.apply(null,e)}},{}],303:[function(e,t,r){var n=e("safe-buffer").Buffer;function i(e,t){this._block=n.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}i.prototype.update=function(e,t){"string"==typeof e&&(t=t||"utf8",e=n.from(e,t));for(var r=this._block,i=this._blockSize,o=e.length,a=this._len,s=0;s=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var o=this._hash();return e?o.toString(e):o},i.prototype._update=function(){throw new Error("_update must be implemented by subclass")},t.exports=i},{"safe-buffer":290}],304:[function(e,t,r){(r=t.exports=function(e){e=e.toLowerCase();var t=r[e];if(!t)throw new Error(e+" is not supported (we accept pull requests)");return new t}).sha=e("./sha"),r.sha1=e("./sha1"),r.sha224=e("./sha224"),r.sha256=e("./sha256"),r.sha384=e("./sha384"),r.sha512=e("./sha512")},{"./sha":305,"./sha1":306,"./sha224":307,"./sha256":308,"./sha384":309,"./sha512":310}],305:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1518500249,1859775393,-1894007588,-899497514],s=new Array(80);function u(){this.init(),this._w=s,i.call(this,64,56)}function c(e){return e<<30|e>>>2}function f(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}n(u,i),u.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,h=0;h<16;++h)r[h]=e.readInt32BE(4*h);for(;h<80;++h)r[h]=r[h-3]^r[h-8]^r[h-14]^r[h-16];for(var l=0;l<80;++l){var d=~~(l/20),p=0|((t=n)<<5|t>>>27)+f(d,i,o,s)+u+r[l]+a[d];u=s,s=o,o=c(i),i=n,n=p}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},u.prototype._hash=function(){var e=o.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},t.exports=u},{"./hash":303,inherits:180,"safe-buffer":290}],306:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1518500249,1859775393,-1894007588,-899497514],s=new Array(80);function u(){this.init(),this._w=s,i.call(this,64,56)}function c(e){return e<<5|e>>>27}function f(e){return e<<30|e>>>2}function h(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}n(u,i),u.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,l=0;l<16;++l)r[l]=e.readInt32BE(4*l);for(;l<80;++l)r[l]=(t=r[l-3]^r[l-8]^r[l-14]^r[l-16])<<1|t>>>31;for(var d=0;d<80;++d){var p=~~(d/20),b=c(n)+h(p,i,o,s)+u+r[d]+a[p]|0;u=s,s=o,o=f(i),i=n,n=b}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},u.prototype._hash=function(){var e=o.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},t.exports=u},{"./hash":303,inherits:180,"safe-buffer":290}],307:[function(e,t,r){var n=e("inherits"),i=e("./sha256"),o=e("./hash"),a=e("safe-buffer").Buffer,s=new Array(64);function u(){this.init(),this._w=s,o.call(this,64,56)}n(u,i),u.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},u.prototype._hash=function(){var e=a.allocUnsafe(28);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e},t.exports=u},{"./hash":303,"./sha256":308,inherits:180,"safe-buffer":290}],308:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],s=new Array(64);function u(){this.init(),this._w=s,i.call(this,64,56)}function c(e,t,r){return r^e&(t^r)}function f(e,t,r){return e&t|r&(e|t)}function h(e){return(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function l(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function d(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}n(u,i),u.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,p=0|this._f,b=0|this._g,y=0|this._h,m=0;m<16;++m)r[m]=e.readInt32BE(4*m);for(;m<64;++m)r[m]=0|(((t=r[m-2])>>>17|t<<15)^(t>>>19|t<<13)^t>>>10)+r[m-7]+d(r[m-15])+r[m-16];for(var v=0;v<64;++v){var g=y+l(u)+c(u,p,b)+a[v]+r[v]|0,w=h(n)+f(n,i,o)|0;y=b,b=p,p=u,u=s+g|0,s=o,o=i,i=n,n=g+w|0}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0,this._f=p+this._f|0,this._g=b+this._g|0,this._h=y+this._h|0},u.prototype._hash=function(){var e=o.allocUnsafe(32);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e.writeInt32BE(this._h,28),e},t.exports=u},{"./hash":303,inherits:180,"safe-buffer":290}],309:[function(e,t,r){var n=e("inherits"),i=e("./sha512"),o=e("./hash"),a=e("safe-buffer").Buffer,s=new Array(160);function u(){this.init(),this._w=s,o.call(this,128,112)}n(u,i),u.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},u.prototype._hash=function(){var e=a.allocUnsafe(48);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e},t.exports=u},{"./hash":303,"./sha512":310,inherits:180,"safe-buffer":290}],310:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],s=new Array(160);function u(){this.init(),this._w=s,i.call(this,128,112)}function c(e,t,r){return r^e&(t^r)}function f(e,t,r){return e&t|r&(e|t)}function h(e,t){return(e>>>28|t<<4)^(t>>>2|e<<30)^(t>>>7|e<<25)}function l(e,t){return(e>>>14|t<<18)^(e>>>18|t<<14)^(t>>>9|e<<23)}function d(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^e>>>7}function p(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^(e>>>7|t<<25)}function b(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^e>>>6}function y(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^(e>>>6|t<<26)}function m(e,t){return e>>>0>>0?1:0}n(u,i),u.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},u.prototype._update=function(e){for(var t=this._w,r=0|this._ah,n=0|this._bh,i=0|this._ch,o=0|this._dh,s=0|this._eh,u=0|this._fh,v=0|this._gh,g=0|this._hh,w=0|this._al,_=0|this._bl,A=0|this._cl,E=0|this._dl,x=0|this._el,k=0|this._fl,S=0|this._gl,M=0|this._hl,I=0;I<32;I+=2)t[I]=e.readInt32BE(4*I),t[I+1]=e.readInt32BE(4*I+4);for(;I<160;I+=2){var T=t[I-30],U=t[I-30+1],j=d(T,U),B=p(U,T),P=b(T=t[I-4],U=t[I-4+1]),C=y(U,T),N=t[I-14],R=t[I-14+1],L=t[I-32],O=t[I-32+1],D=B+R|0,F=j+N+m(D,B)|0;F=(F=F+P+m(D=D+C|0,C)|0)+L+m(D=D+O|0,O)|0,t[I]=F,t[I+1]=D}for(var q=0;q<160;q+=2){F=t[q],D=t[q+1];var H=f(r,n,i),z=f(w,_,A),K=h(r,w),V=h(w,r),G=l(s,x),W=l(x,s),Y=a[q],X=a[q+1],Z=c(s,u,v),J=c(x,k,S),$=M+W|0,Q=g+G+m($,M)|0;Q=(Q=(Q=Q+Z+m($=$+J|0,J)|0)+Y+m($=$+X|0,X)|0)+F+m($=$+D|0,D)|0;var ee=V+z|0,te=K+H+m(ee,V)|0;g=v,M=S,v=u,S=k,u=s,k=x,s=o+Q+m(x=E+$|0,E)|0,o=i,E=A,i=n,A=_,n=r,_=w,r=Q+te+m(w=$+ee|0,$)|0}this._al=this._al+w|0,this._bl=this._bl+_|0,this._cl=this._cl+A|0,this._dl=this._dl+E|0,this._el=this._el+x|0,this._fl=this._fl+k|0,this._gl=this._gl+S|0,this._hl=this._hl+M|0,this._ah=this._ah+r+m(this._al,w)|0,this._bh=this._bh+n+m(this._bl,_)|0,this._ch=this._ch+i+m(this._cl,A)|0,this._dh=this._dh+o+m(this._dl,E)|0,this._eh=this._eh+s+m(this._el,x)|0,this._fh=this._fh+u+m(this._fl,k)|0,this._gh=this._gh+v+m(this._gl,S)|0,this._hh=this._hh+g+m(this._hl,M)|0},u.prototype._hash=function(){var e=o.allocUnsafe(64);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e},t.exports=u},{"./hash":303,inherits:180,"safe-buffer":290}],311:[function(e,t,r){t.exports=i;var n=e("events").EventEmitter;function i(){n.call(this)}e("inherits")(i,n),i.Readable=e("readable-stream/readable.js"),i.Writable=e("readable-stream/writable.js"),i.Duplex=e("readable-stream/duplex.js"),i.Transform=e("readable-stream/transform.js"),i.PassThrough=e("readable-stream/passthrough.js"),i.Stream=i,i.prototype.pipe=function(e,t){var r=this;function i(t){e.writable&&!1===e.write(t)&&r.pause&&r.pause()}function o(){r.readable&&r.resume&&r.resume()}r.on("data",i),e.on("drain",o),e._isStdio||t&&!1===t.end||(r.on("end",s),r.on("close",u));var a=!1;function s(){a||(a=!0,e.end())}function u(){a||(a=!0,"function"==typeof e.destroy&&e.destroy())}function c(e){if(f(),0===n.listenerCount(this,"error"))throw e}function f(){r.removeListener("data",i),e.removeListener("drain",o),r.removeListener("end",s),r.removeListener("close",u),r.removeListener("error",c),e.removeListener("error",c),r.removeListener("end",f),r.removeListener("close",f),e.removeListener("close",f)}return r.on("error",c),e.on("error",c),r.on("end",f),r.on("close",f),e.on("close",f),e.emit("pipe",r),e}},{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(e,t,r){(function(t){var n=e("./lib/request"),i=e("./lib/response"),o=e("xtend"),a=e("builtin-status-codes"),s=e("url"),u=r;u.request=function(e,r){e="string"==typeof e?s.parse(e):o(e);var i=-1===t.location.protocol.search(/^https?:$/)?"http:":"",a=e.protocol||i,u=e.hostname||e.host,c=e.port,f=e.path||"/";u&&-1!==u.indexOf(":")&&(u="["+u+"]"),e.url=(u?a+"//"+u:"")+(c?":"+c:"")+f,e.method=(e.method||"GET").toUpperCase(),e.headers=e.headers||{};var h=new n(e);return r&&h.on("response",r),h},u.get=function(e,t){var r=u.request(e,t);return r.end(),r},u.ClientRequest=n,u.IncomingMessage=i,u.Agent=function(){},u.Agent.defaultMaxSockets=4,u.STATUS_CODES=a,u.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./lib/request":314,"./lib/response":315,"builtin-status-codes":85,url:327,xtend:423}],313:[function(e,t,r){(function(e){r.fetch=s(e.fetch)&&s(e.ReadableStream),r.writableStream=s(e.WritableStream),r.abortController=s(e.AbortController),r.blobConstructor=!1;try{new Blob([new ArrayBuffer(1)]),r.blobConstructor=!0}catch(e){}var t;function n(){if(void 0!==t)return t;if(e.XMLHttpRequest){t=new e.XMLHttpRequest;try{t.open("GET",e.XDomainRequest?"/":"https://example.com")}catch(e){t=null}}else t=null;return t}function i(e){var t=n();if(!t)return!1;try{return t.responseType=e,t.responseType===e}catch(e){}return!1}var o=void 0!==e.ArrayBuffer,a=o&&s(e.ArrayBuffer.prototype.slice);function s(e){return"function"==typeof e}r.arraybuffer=r.fetch||o&&i("arraybuffer"),r.msstream=!r.fetch&&a&&i("ms-stream"),r.mozchunkedarraybuffer=!r.fetch&&o&&i("moz-chunked-arraybuffer"),r.overrideMimeType=r.fetch||!!n()&&s(n().overrideMimeType),r.vbArray=s(e.VBArray),t=null}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],314:[function(e,t,r){(function(r,n,i){var o=e("./capability"),a=e("inherits"),s=e("./response"),u=e("readable-stream"),c=e("to-arraybuffer"),f=s.IncomingMessage,h=s.readyStates;var l=t.exports=function(e){var t,r=this;u.Writable.call(r),r._opts=e,r._body=[],r._headers={},e.auth&&r.setHeader("Authorization","Basic "+new i(e.auth).toString("base64")),Object.keys(e.headers).forEach(function(t){r.setHeader(t,e.headers[t])});var n=!0;if("disable-fetch"===e.mode||"requestTimeout"in e&&!o.abortController)n=!1,t=!0;else if("prefer-streaming"===e.mode)t=!1;else if("allow-wrong-content-type"===e.mode)t=!o.overrideMimeType;else{if(e.mode&&"default"!==e.mode&&"prefer-fast"!==e.mode)throw new Error("Invalid value for opts.mode");t=!0}r._mode=function(e,t){return o.fetch&&t?"fetch":o.mozchunkedarraybuffer?"moz-chunked-arraybuffer":o.msstream?"ms-stream":o.arraybuffer&&e?"arraybuffer":o.vbArray&&e?"text:vbarray":"text"}(t,n),r.on("finish",function(){r._onFinish()})};a(l,u.Writable),l.prototype.setHeader=function(e,t){var r=e.toLowerCase();-1===d.indexOf(r)&&(this._headers[r]={name:e,value:t})},l.prototype.getHeader=function(e){var t=this._headers[e.toLowerCase()];return t?t.value:null},l.prototype.removeHeader=function(e){delete this._headers[e.toLowerCase()]},l.prototype._onFinish=function(){var e=this;if(!e._destroyed){var t=e._opts,a=e._headers,s=null;"GET"!==t.method&&"HEAD"!==t.method&&(s=o.arraybuffer?c(i.concat(e._body)):o.blobConstructor?new n.Blob(e._body.map(function(e){return c(e)}),{type:(a["content-type"]||{}).value||""}):i.concat(e._body).toString());var u=[];if(Object.keys(a).forEach(function(e){var t=a[e].name,r=a[e].value;Array.isArray(r)?r.forEach(function(e){u.push([t,e])}):u.push([t,r])}),"fetch"===e._mode){var f=null;if(o.abortController){var l=new AbortController;f=l.signal,e._fetchAbortController=l,"requestTimeout"in t&&0!==t.requestTimeout&&n.setTimeout(function(){e.emit("requestTimeout"),e._fetchAbortController&&e._fetchAbortController.abort()},t.requestTimeout)}n.fetch(e._opts.url,{method:e._opts.method,headers:u,body:s||void 0,mode:"cors",credentials:t.withCredentials?"include":"same-origin",signal:f}).then(function(t){e._fetchResponse=t,e._connect()},function(t){e.emit("error",t)})}else{var d=e._xhr=new n.XMLHttpRequest;try{d.open(e._opts.method,e._opts.url,!0)}catch(t){return void r.nextTick(function(){e.emit("error",t)})}"responseType"in d&&(d.responseType=e._mode.split(":")[0]),"withCredentials"in d&&(d.withCredentials=!!t.withCredentials),"text"===e._mode&&"overrideMimeType"in d&&d.overrideMimeType("text/plain; charset=x-user-defined"),"requestTimeout"in t&&(d.timeout=t.requestTimeout,d.ontimeout=function(){e.emit("requestTimeout")}),u.forEach(function(e){d.setRequestHeader(e[0],e[1])}),e._response=null,d.onreadystatechange=function(){switch(d.readyState){case h.LOADING:case h.DONE:e._onXHRProgress()}},"moz-chunked-arraybuffer"===e._mode&&(d.onprogress=function(){e._onXHRProgress()}),d.onerror=function(){e._destroyed||e.emit("error",new Error("XHR error"))};try{d.send(s)}catch(t){return void r.nextTick(function(){e.emit("error",t)})}}}},l.prototype._onXHRProgress=function(){(function(e){try{var t=e.status;return null!==t&&0!==t}catch(e){return!1}})(this._xhr)&&!this._destroyed&&(this._response||this._connect(),this._response._onXHRProgress())},l.prototype._connect=function(){var e=this;e._destroyed||(e._response=new f(e._xhr,e._fetchResponse,e._mode),e._response.on("error",function(t){e.emit("error",t)}),e.emit("response",e._response))},l.prototype._write=function(e,t,r){this._body.push(e),r()},l.prototype.abort=l.prototype.destroy=function(){this._destroyed=!0,this._response&&(this._response._destroyed=!0),this._xhr?this._xhr.abort():this._fetchAbortController&&this._fetchAbortController.abort()},l.prototype.end=function(e,t,r){"function"==typeof e&&(r=e,e=void 0),u.Writable.prototype.end.call(this,e,t,r)},l.prototype.flushHeaders=function(){},l.prototype.setTimeout=function(){},l.prototype.setNoDelay=function(){},l.prototype.setSocketKeepAlive=function(){};var d=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","user-agent","via"]}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"./capability":313,"./response":315,_process:257,buffer:84,inherits:180,"readable-stream":285,"to-arraybuffer":323}],315:[function(e,t,r){(function(t,n,i){var o=e("./capability"),a=e("inherits"),s=e("readable-stream"),u=r.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},c=r.IncomingMessage=function(e,r,n){var a=this;if(s.Readable.call(a),a._mode=n,a.headers={},a.rawHeaders=[],a.trailers={},a.rawTrailers=[],a.on("end",function(){t.nextTick(function(){a.emit("close")})}),"fetch"===n){if(a._fetchResponse=r,a.url=r.url,a.statusCode=r.status,a.statusMessage=r.statusText,r.headers.forEach(function(e,t){a.headers[t.toLowerCase()]=e,a.rawHeaders.push(t,e)}),o.writableStream){var u=new WritableStream({write:function(e){return new Promise(function(t,r){a._destroyed||(a.push(new i(e))?t():a._resumeFetch=t)})},close:function(){a._destroyed||a.push(null)},abort:function(e){a._destroyed||a.emit("error",e)}});try{return void r.body.pipeTo(u)}catch(e){}}var c=r.body.getReader();!function e(){c.read().then(function(t){a._destroyed||(t.done?a.push(null):(a.push(new i(t.value)),e()))}).catch(function(e){a._destroyed||a.emit("error",e)})}()}else{if(a._xhr=e,a._pos=0,a.url=e.responseURL,a.statusCode=e.status,a.statusMessage=e.statusText,e.getAllResponseHeaders().split(/\r?\n/).forEach(function(e){var t=e.match(/^([^:]+):\s*(.*)/);if(t){var r=t[1].toLowerCase();"set-cookie"===r?(void 0===a.headers[r]&&(a.headers[r]=[]),a.headers[r].push(t[2])):void 0!==a.headers[r]?a.headers[r]+=", "+t[2]:a.headers[r]=t[2],a.rawHeaders.push(t[1],t[2])}}),a._charset="x-user-defined",!o.overrideMimeType){var f=a.rawHeaders["mime-type"];if(f){var h=f.match(/;\s*charset=([^;])(;|$)/);h&&(a._charset=h[1].toLowerCase())}a._charset||(a._charset="utf-8")}}};a(c,s.Readable),c.prototype._read=function(){var e=this._resumeFetch;e&&(this._resumeFetch=null,e())},c.prototype._onXHRProgress=function(){var e=this,t=e._xhr,r=null;switch(e._mode){case"text:vbarray":if(t.readyState!==u.DONE)break;try{r=new n.VBArray(t.responseBody).toArray()}catch(e){}if(null!==r){e.push(new i(r));break}case"text":try{r=t.responseText}catch(t){e._mode="text:vbarray";break}if(r.length>e._pos){var o=r.substr(e._pos);if("x-user-defined"===e._charset){for(var a=new i(o.length),s=0;se._pos&&(e.push(new i(new Uint8Array(c.result.slice(e._pos)))),e._pos=c.result.byteLength)},c.onload=function(){e.push(null)},c.readAsArrayBuffer(r)}e._xhr.readyState===u.DONE&&"ms-stream"!==e._mode&&e.push(null)}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"./capability":313,_process:257,buffer:84,inherits:180,"readable-stream":285}],316:[function(e,t,r){"use strict";t.exports=function(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}},{}],317:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=n.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function o(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(n.isEncoding===i||!i(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=u,this.end=c,t=4;break;case"utf8":this.fillLast=s,t=4;break;case"base64":this.text=f,this.end=h,t=3;break;default:return this.write=l,void(this.end=d)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(t)}function a(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:-1}function s(e){var t=this.lastTotal-this.lastNeed,r=function(e,t,r){if(128!=(192&t[0]))return e.lastNeed=0,"�".repeat(r);if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�".repeat(r+1);if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�".repeat(r+2)}}(this,e,t);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function u(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function c(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function f(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function h(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function l(e){return e.toString(this.encoding)}function d(e){return e&&e.length?this.write(e):""}r.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0)return i>0&&(e.lastNeed=i-1),i;if(--n=0)return i>0&&(e.lastNeed=i-2),i;if(--n=0)return i>0&&(2===i?i=0:e.lastNeed=i-3),i;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)},o.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},{"safe-buffer":290}],318:[function(e,t,r){var n=e("is-hex-prefixed");t.exports=function(e){return"string"!=typeof e?e:n(e)?e.slice(2):e}},{"is-hex-prefixed":185}],319:[function(e,t,r){var n=function(){throw"This swarm.js function isn't available on the browser."},i={readFile:n},o={download:n,safeDownloadArchived:n,directoryTree:n},a={platform:n,arch:n},s={join:n,slice:n},u={spawn:n},c={lookup:n},f=e("xhr-request-promise"),h=e("eth-lib/lib/bytes"),l=e("./swarm-hash.js"),d=e("./pick.js"),p=e("./swarm");t.exports=p({fsp:i,files:o,os:a,path:s,child_process:u,defaultArchives:{},mimetype:c,request:f,downloadUrl:null,bytes:h,hash:l,pick:d})},{"./pick.js":320,"./swarm":322,"./swarm-hash.js":321,"eth-lib/lib/bytes":133,"xhr-request-promise":411}],320:[function(e,t,r){var n=function(e){return function(){return new Promise(function(t,r){var n=function(r){var n={},i=r.target.files.length,o=0;[].map.call(r.target.files,function(r){var a=new FileReader;a.onload=function(a){var s=new Uint8Array(a.target.result);if("directory"===e){var u=r.webkitRelativePath;n[u.slice(u.indexOf("/")+1)]={type:"text/plain",data:s},++o===i&&t(n)}else if("file"===e){var c=r.webkitRelativePath;t({type:mimetype.lookup(c),data:s})}else t(s)},a.readAsArrayBuffer(r)})},i=void 0;"directory"===e?((i=document.createElement("input")).addEventListener("change",n),i.type="file",i.webkitdirectory=!0,i.mozdirectory=!0,i.msdirectory=!0,i.odirectory=!0,i.directory=!0):((i=document.createElement("input")).addEventListener("change",n),i.type="file");var o=document.createEvent("MouseEvents");o.initEvent("click",!0,!1),i.dispatchEvent(o)})}};t.exports={data:n("data"),file:n("file"),directory:n("directory")}},{}],321:[function(e,t,r){var n=e("eth-lib/lib/hash").keccak256,i=e("eth-lib/lib/bytes"),o=function(e,t){var r=i.reverse(i.pad(6,i.fromNumber(e))),o=i.flatten([r,"0x0000",t]);return n(o).slice(2)};t.exports=function e(t){"string"==typeof t&&"0x"!==t.slice(0,2)?t=i.fromString(t):"string"!=typeof t&&void 0!==t.length&&(t=i.fromUint8Array(t));var r=i.length(t);if(r<=4096)return o(r,t);for(var n=4096;128*n0){var a=i.join(r,o);n.push(g(e)(t[o])(a))}return Promise.all(n).then(function(){return r})})}}},_=function(e){return function(t){return u(e+"/bzzr:/",{body:"string"==typeof t?L(t):t,method:"POST"})}},A=function(e){return function(t){return function(r){return function(n){return function i(o){var a="/"===r[0]?r:"/"+r,s=e+"/bzz:/"+t+a,c={method:"PUT",headers:{"Content-Type":n.type},body:n.data};return u(s,c).then(function(e){if(-1!==e.indexOf("error"))throw e;return e}).catch(function(e){return o>0&&i(o-1)})}(3)}}}},E=function(e){return function(t){return k(e)({"":t})}},x=function(e){return function(r){return t.readFile(r).then(function(t){return E(e)({type:a.lookup(r),data:t})})}},k=function(e){return function(t){return _(e)("{}").then(function(r){return Object.keys(t).reduce(function(r,n){return r.then(function(r){return function(n){return A(e)(n)(r)(t[r])}}(n))},Promise.resolve(r))})}},S=function(e){return function(r){return t.readFile(r).then(_(e))}},M=function(e){return function(n){return function(i){return r.directoryTree(i).then(function(e){return Promise.all(e.map(function(e){return t.readFile(e)})).then(function(t){var r=e.map(function(e){return e.slice(i.length)}),n=e.map(function(e){return a.lookup(e)||"text/plain"});return d(r)(t.map(function(e,t){return{type:n[t],data:e}}))})}).then(function(e){return(t=n?{"":e[n]}:{},function(e){var r={};for(var n in t)r[n]=t[n];for(var i in e)r[i]=e[i];return r})(e);var t}).then(k(e))}}},I=function(e){return function(t){if("data"===t.pick)return l.data().then(_(e));if("file"===t.pick)return l.file().then(E(e));if("directory"===t.pick)return l.directory().then(k(e));if(t.path)switch(t.kind){case"data":return S(e)(t.path);case"file":return x(e)(t.path);case"directory":return M(e)(t.defaultFile)(t.path)}else{if(t.length||"string"==typeof t)return _(e)(t);if(t instanceof Object)return k(e)(t)}return Promise.reject(new Error("Bad arguments"))}},T=function(e){return function(t){return function(r){return C(e)(t).then(function(n){return n?r?w(e)(t)(r):v(e)(t):r?g(e)(t)(r):b(e)(t)})}}},U=function(e,t){var i=n.platform().replace("win32","windows")+"-"+("x64"===n.arch()?"amd64":"386"),o=(t||s)[i],a=c+o.archive+".tar.gz",u=o.archiveMD5,f=o.binaryMD5;return r.safeDownloadArchived(a)(u)(f)(e)},j=function(e){return new Promise(function(t,r){var n=o.spawn,i=function(e){return function(t){return-1!==(""+t).indexOf(e)}},a=e.account,s=e.password,u=e.dataDir,c=e.ensApi,f=e.privateKey,h=0,l=n(e.binPath,["--bzzaccount",a||f,"--datadir",u,"--ens-api",c]),d=function(e){0===h&&i("Passphrase")(e)?setTimeout(function(){h=1,l.stdin.write(s+"\n")},500):i("Swarm http proxy started")(e)&&(h=2,clearTimeout(p),t(l))};l.stdout.on("data",d),l.stderr.on("data",d);var p=setTimeout(function(){return r(new Error("Couldn't start swarm process."))},2e4)})},B=function(e){return new Promise(function(t,r){e.stderr.removeAllListeners("data"),e.stdout.removeAllListeners("data"),e.stdin.removeAllListeners("error"),e.removeAllListeners("error"),e.removeAllListeners("exit"),e.kill("SIGINT");var n=setTimeout(function(){return e.kill("SIGKILL")},8e3);e.once("close",function(){clearTimeout(n),t()})})},P=function(e){return _(e)("test").then(function(e){return"c9a99c7d326dcc6316f32fe2625b311f6dc49a175e6877681ded93137d3569e7"===e}).catch(function(){return!1})},C=function(e){return function(t){return b(e)(t).then(function(e){try{return!!JSON.parse(R(e)).entries}catch(e){return!1}})}},N=function(e){return function(t,r,n,i,o){var a;return void 0!==t&&(a=e(t)),void 0!==r&&(a=e(r)),void 0!==n&&(a=e(n)),void 0!==i&&(a=e(i)),void 0!==o&&(a=e(o)),a}},R=function(e){return f.toString(f.fromUint8Array(e))},L=function(e){return f.toUint8Array(f.fromString(e))},O=function(e){return{download:function(t,r){return T(e)(t)(r)},downloadData:N(b(e)),downloadDataToDisk:N(g(e)),downloadDirectory:N(v(e)),downloadDirectoryToDisk:N(w(e)),downloadEntries:N(y(e)),downloadRoutes:N(m(e)),isAvailable:function(){return P(e)},upload:function(t){return I(e)(t)},uploadData:N(_(e)),uploadFile:N(E(e)),uploadFileFromDisk:N(E(e)),uploadDataFromDisk:N(S(e)),uploadDirectory:N(k(e)),uploadDirectoryFromDisk:N(M(e)),uploadToManifest:N(A(e)),pick:l,hash:h,fromString:L,toString:R}};return{at:O,local:function(e){return function(t){return P("http://localhost:8500").then(function(r){return r?t(O("http://localhost:8500")).then(function(){}):U(e.binPath,e.archives).onData(function(t){return(e.onProgress||function(){})(t.length)}).then(function(){return j(e)}).then(function(e){return t(O("http://localhost:8500")).then(function(){return e})}).then(B)})}},download:T,downloadBinary:U,downloadData:b,downloadDataToDisk:g,downloadDirectory:v,downloadDirectoryToDisk:w,downloadEntries:y,downloadRoutes:m,isAvailable:P,startProcess:j,stopProcess:B,upload:I,uploadData:_,uploadDataFromDisk:S,uploadFile:E,uploadFileFromDisk:x,uploadDirectory:k,uploadDirectoryFromDisk:M,uploadToManifest:A,pick:l,hash:h,fromString:L,toString:R}}},{}],323:[function(e,t,r){var n=e("buffer").Buffer;t.exports=function(e){if(e instanceof Uint8Array){if(0===e.byteOffset&&e.byteLength===e.buffer.byteLength)return e.buffer;if("function"==typeof e.buffer.slice)return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}if(n.isBuffer(e)){for(var t=new Uint8Array(e.length),r=e.length,i=0;i=0&&t<=A};function k(e){return function(t,r,n,i){r=m(r,i,4);var o=!x(t)&&y.keys(t),a=(o||t).length,s=e>0?0:a-1;return arguments.length<3&&(n=t[o?o[s]:s],s+=e),function(t,r,n,i,o,a){for(;o>=0&&o=0},y.invoke=function(e,t){var r=u.call(arguments,2),n=y.isFunction(t);return y.map(e,function(e){var i=n?t:e[t];return null==i?i:i.apply(e,r)})},y.pluck=function(e,t){return y.map(e,y.property(t))},y.where=function(e,t){return y.filter(e,y.matcher(t))},y.findWhere=function(e,t){return y.find(e,y.matcher(t))},y.max=function(e,t,r){var n,i,o=-1/0,a=-1/0;if(null==t&&null!=e)for(var s=0,u=(e=x(e)?e:y.values(e)).length;so&&(o=n);else t=v(t,r),y.each(e,function(e,r,n){((i=t(e,r,n))>a||i===-1/0&&o===-1/0)&&(o=e,a=i)});return o},y.min=function(e,t,r){var n,i,o=1/0,a=1/0;if(null==t&&null!=e)for(var s=0,u=(e=x(e)?e:y.values(e)).length;sn||void 0===r)return 1;if(r0?0:i-1;o>=0&&o0?a=o>=0?o:Math.max(o+s,a):s=o>=0?Math.min(o+1,s):o+s+1;else if(r&&o&&s)return n[o=r(n,i)]===i?o:-1;if(i!=i)return(o=t(u.call(n,a,s),y.isNaN))>=0?o+a:-1;for(o=e>0?a:s-1;o>=0&&ot?(a&&(clearTimeout(a),a=null),s=c,o=e.apply(n,i),a||(n=i=null)):a||!1===r.trailing||(a=setTimeout(u,f)),o}},y.debounce=function(e,t,r){var n,i,o,a,s,u=function(){var c=y.now()-a;c=0?n=setTimeout(u,t-c):(n=null,r||(s=e.apply(o,i),n||(o=i=null)))};return function(){o=this,i=arguments,a=y.now();var c=r&&!n;return n||(n=setTimeout(u,t)),c&&(s=e.apply(o,i),o=i=null),s}},y.wrap=function(e,t){return y.partial(t,e)},y.negate=function(e){return function(){return!e.apply(this,arguments)}},y.compose=function(){var e=arguments,t=e.length-1;return function(){for(var r=t,n=e[t].apply(this,arguments);r--;)n=e[r].call(this,n);return n}},y.after=function(e,t){return function(){if(--e<1)return t.apply(this,arguments)}},y.before=function(e,t){var r;return function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=null),r}},y.once=y.partial(y.before,2);var j=!{toString:null}.propertyIsEnumerable("toString"),B=["valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"];function P(e,t){var r=B.length,n=e.constructor,i=y.isFunction(n)&&n.prototype||o,a="constructor";for(y.has(e,a)&&!y.contains(t,a)&&t.push(a);r--;)(a=B[r])in e&&e[a]!==i[a]&&!y.contains(t,a)&&t.push(a)}y.keys=function(e){if(!y.isObject(e))return[];if(l)return l(e);var t=[];for(var r in e)y.has(e,r)&&t.push(r);return j&&P(e,t),t},y.allKeys=function(e){if(!y.isObject(e))return[];var t=[];for(var r in e)t.push(r);return j&&P(e,t),t},y.values=function(e){for(var t=y.keys(e),r=t.length,n=Array(r),i=0;i":">",'"':""","'":"'","`":"`"},R=y.invert(N),L=function(e){var t=function(t){return e[t]},r="(?:"+y.keys(e).join("|")+")",n=RegExp(r),i=RegExp(r,"g");return function(e){return e=null==e?"":""+e,n.test(e)?e.replace(i,t):e}};y.escape=L(N),y.unescape=L(R),y.result=function(e,t,r){var n=null==e?void 0:e[t];return void 0===n&&(n=r),y.isFunction(n)?n.call(e):n};var O=0;y.uniqueId=function(e){var t=++O+"";return e?e+t:t},y.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var D=/(.)^/,F={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},q=/\\|'|\r|\n|\u2028|\u2029/g,H=function(e){return"\\"+F[e]};y.template=function(e,t,r){!t&&r&&(t=r),t=y.defaults({},t,y.templateSettings);var n=RegExp([(t.escape||D).source,(t.interpolate||D).source,(t.evaluate||D).source].join("|")+"|$","g"),i=0,o="__p+='";e.replace(n,function(t,r,n,a,s){return o+=e.slice(i,s).replace(q,H),i=s+t.length,r?o+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'":n?o+="'+\n((__t=("+n+"))==null?'':__t)+\n'":a&&(o+="';\n"+a+"\n__p+='"),t}),o+="';\n",t.variable||(o="with(obj||{}){\n"+o+"}\n"),o="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+o+"return __p;\n";try{var a=new Function(t.variable||"obj","_",o)}catch(e){throw e.source=o,e}var s=function(e){return a.call(this,e,y)},u=t.variable||"obj";return s.source="function("+u+"){\n"+o+"}",s},y.chain=function(e){var t=y(e);return t._chain=!0,t};var z=function(e,t){return e._chain?y(t).chain():t};y.mixin=function(e){y.each(y.functions(e),function(t){var r=y[t]=e[t];y.prototype[t]=function(){var e=[this._wrapped];return s.apply(e,arguments),z(this,r.apply(y,e))}})},y.mixin(y),y.each(["pop","push","reverse","shift","sort","splice","unshift"],function(e){var t=i[e];y.prototype[e]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!==e&&"splice"!==e||0!==r.length||delete r[0],z(this,r)}}),y.each(["concat","join","slice"],function(e){var t=i[e];y.prototype[e]=function(){return z(this,t.apply(this._wrapped,arguments))}}),y.prototype.value=function(){return this._wrapped},y.prototype.valueOf=y.prototype.toJSON=y.prototype.value,y.prototype.toString=function(){return""+this._wrapped},"function"==typeof define&&define.amd&&define("underscore",[],function(){return y})}).call(this)},{}],326:[function(e,t,r){t.exports=function(e,t){if(t){t=(t=t.trim().replace(/^(\?|#|&)/,""))?"?"+t:t;var r=e.split(/[\?\#]/),n=r[0];t&&/\:\/\/[^\/]*$/.test(n)&&(n+="/");var i=e.match(/(\#.*)$/);e=n+t,i&&(e+=i[0])}return e}},{}],327:[function(e,t,r){"use strict";var n=e("punycode"),i=e("./util");function o(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}r.parse=g,r.resolve=function(e,t){return g(e,!1,!0).resolve(t)},r.resolveObject=function(e,t){return e?g(e,!1,!0).resolveObject(t):t},r.format=function(e){i.isString(e)&&(e=g(e));return e instanceof o?e.format():o.prototype.format.call(e)},r.Url=o;var a=/^([a-z0-9.+-]+:)/i,s=/:[0-9]*$/,u=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,c=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),f=["'"].concat(c),h=["%","/","?",";","#"].concat(f),l=["/","?","#"],d=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,b={javascript:!0,"javascript:":!0},y={javascript:!0,"javascript:":!0},m={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},v=e("querystring");function g(e,t,r){if(e&&i.isObject(e)&&e instanceof o)return e;var n=new o;return n.parse(e,t,r),n}o.prototype.parse=function(e,t,r){if(!i.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var o=e.indexOf("?"),s=-1!==o&&o127?P+="x":P+=B[C];if(!P.match(d)){var R=U.slice(0,M),L=U.slice(M+1),O=B.match(p);O&&(R.push(O[1]),L.unshift(O[2])),L.length&&(g="/"+L.join(".")+g),this.hostname=R.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),T||(this.hostname=n.toASCII(this.hostname));var D=this.port?":"+this.port:"",F=this.hostname||"";this.host=F+D,this.href+=this.host,T&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==g[0]&&(g="/"+g))}if(!b[A])for(M=0,j=f.length;M0)&&r.host.split("@"))&&(r.auth=T.shift(),r.host=r.hostname=T.shift());return r.search=e.search,r.query=e.query,i.isNull(r.pathname)&&i.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!E.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var k=E.slice(-1)[0],S=(r.host||e.host||E.length>1)&&("."===k||".."===k)||""===k,M=0,I=E.length;I>=0;I--)"."===(k=E[I])?E.splice(I,1):".."===k?(E.splice(I,1),M++):M&&(E.splice(I,1),M--);if(!_&&!A)for(;M--;M)E.unshift("..");!_||""===E[0]||E[0]&&"/"===E[0].charAt(0)||E.unshift(""),S&&"/"!==E.join("/").substr(-1)&&E.push("");var T,U=""===E[0]||E[0]&&"/"===E[0].charAt(0);x&&(r.hostname=r.host=U?"":E.length?E.shift():"",(T=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@"))&&(r.auth=T.shift(),r.host=r.hostname=T.shift()));return(_=_||r.host&&E.length)&&!U&&E.unshift(""),E.length?r.pathname=E.join("/"):(r.pathname=null,r.path=null),i.isNull(r.pathname)&&i.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=e.auth||r.auth,r.slashes=r.slashes||e.slashes,r.href=r.format(),r},o.prototype.parseHost=function(){var e=this.host,t=s.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{"./util":328,punycode:265,querystring:269}],328:[function(e,t,r){"use strict";t.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},{}],329:[function(e,t,r){(function(e){!function(n){var i="object"==typeof r&&r,o="object"==typeof t&&t&&t.exports==i&&t,a="object"==typeof e&&e;a.global!==a&&a.window!==a||(n=a);var s,u,c,f=String.fromCharCode;function h(e){for(var t,r,n=[],i=0,o=e.length;i=55296&&t<=56319&&i=55296&&e<=57343)throw Error("Lone surrogate U+"+e.toString(16).toUpperCase()+" is not a scalar value")}function d(e,t){return f(e>>t&63|128)}function p(e){if(0==(4294967168&e))return f(e);var t="";return 0==(4294965248&e)?t=f(e>>6&31|192):0==(4294901760&e)?(l(e),t=f(e>>12&15|224),t+=d(e,6)):0==(4292870144&e)&&(t=f(e>>18&7|240),t+=d(e,12),t+=d(e,6)),t+=f(63&e|128)}function b(){if(c>=u)throw Error("Invalid byte index");var e=255&s[c];if(c++,128==(192&e))return 63&e;throw Error("Invalid continuation byte")}function y(){var e,t;if(c>u)throw Error("Invalid byte index");if(c==u)return!1;if(e=255&s[c],c++,0==(128&e))return e;if(192==(224&e)){if((t=(31&e)<<6|b())>=128)return t;throw Error("Invalid continuation byte")}if(224==(240&e)){if((t=(15&e)<<12|b()<<6|b())>=2048)return l(t),t;throw Error("Invalid continuation byte")}if(240==(248&e)&&(t=(15&e)<<18|b()<<12|b()<<6|b())>=65536&&t<=1114111)return t;throw Error("Invalid UTF-8 detected")}var m={version:"2.0.0",encode:function(e){for(var t=h(e),r=t.length,n=-1,i="";++n65535&&(i+=f((t-=65536)>>>10&1023|55296),t=56320|1023&t),i+=f(t);return i}(r)}};if("function"==typeof define&&"object"==typeof define.amd&&define.amd)define(function(){return m});else if(i&&!i.nodeType)if(o)o.exports=m;else{var v={}.hasOwnProperty;for(var g in m)v.call(m,g)&&(i[g]=m[g])}else n.utf8=m}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],330:[function(e,t,r){(function(e){function r(t){try{if(!e.localStorage)return!1}catch(e){return!1}var r=e.localStorage[t];return null!=r&&"true"===String(r).toLowerCase()}t.exports=function(e,t){if(r("noDeprecation"))return e;var n=!1;return function(){if(!n){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],331:[function(e,t,r){arguments[4][180][0].apply(r,arguments)},{dup:180}],332:[function(e,t,r){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],333:[function(e,t,r){(function(t,n){var i=/%[sdj%]/g;r.format=function(e){if(!m(e)){for(var t=[],r=0;r=o)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(e){return"[Circular]"}default:return e}}),u=n[r];r=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),p(t)?n.showHidden=t:t&&r._extend(n,t),v(n.showHidden)&&(n.showHidden=!1),v(n.depth)&&(n.depth=2),v(n.colors)&&(n.colors=!1),v(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=u),f(n,e,n.depth)}function u(e,t){var r=s.styles[t];return r?"["+s.colors[r][0]+"m"+e+"["+s.colors[r][1]+"m":e}function c(e,t){return e}function f(e,t,n){if(e.customInspect&&t&&E(t.inspect)&&t.inspect!==r.inspect&&(!t.constructor||t.constructor.prototype!==t)){var i=t.inspect(n,e);return m(i)||(i=f(e,i,n)),i}var o=function(e,t){if(v(t))return e.stylize("undefined","undefined");if(m(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(y(t))return e.stylize(""+t,"number");if(p(t))return e.stylize(""+t,"boolean");if(b(t))return e.stylize("null","null")}(e,t);if(o)return o;var a=Object.keys(t),s=function(e){var t={};return e.forEach(function(e,r){t[e]=!0}),t}(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(t)),A(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return h(t);if(0===a.length){if(E(t)){var u=t.name?": "+t.name:"";return e.stylize("[Function"+u+"]","special")}if(g(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(_(t))return e.stylize(Date.prototype.toString.call(t),"date");if(A(t))return h(t)}var c,w="",x=!1,k=["{","}"];(d(t)&&(x=!0,k=["[","]"]),E(t))&&(w=" [Function"+(t.name?": "+t.name:"")+"]");return g(t)&&(w=" "+RegExp.prototype.toString.call(t)),_(t)&&(w=" "+Date.prototype.toUTCString.call(t)),A(t)&&(w=" "+h(t)),0!==a.length||x&&0!=t.length?n<0?g(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),c=x?function(e,t,r,n,i){for(var o=[],a=0,s=t.length;a=0&&0,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60)return r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1];return r[0]+t+" "+e.join(", ")+" "+r[1]}(c,w,k)):k[0]+w+k[1]}function h(e){return"["+Error.prototype.toString.call(e)+"]"}function l(e,t,r,n,i,o){var a,s,u;if((u=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]}).get?s=u.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):u.set&&(s=e.stylize("[Setter]","special")),M(n,i)||(a="["+i+"]"),s||(e.seen.indexOf(u.value)<0?(s=b(r)?f(e,u.value,null):f(e,u.value,r-1)).indexOf("\n")>-1&&(s=o?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n")):s=e.stylize("[Circular]","special")),v(a)){if(o&&i.match(/^\d+$/))return s;(a=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function d(e){return Array.isArray(e)}function p(e){return"boolean"==typeof e}function b(e){return null===e}function y(e){return"number"==typeof e}function m(e){return"string"==typeof e}function v(e){return void 0===e}function g(e){return w(e)&&"[object RegExp]"===x(e)}function w(e){return"object"==typeof e&&null!==e}function _(e){return w(e)&&"[object Date]"===x(e)}function A(e){return w(e)&&("[object Error]"===x(e)||e instanceof Error)}function E(e){return"function"==typeof e}function x(e){return Object.prototype.toString.call(e)}function k(e){return e<10?"0"+e.toString(10):e.toString(10)}r.debuglog=function(e){if(v(o)&&(o=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!a[e])if(new RegExp("\\b"+e+"\\b","i").test(o)){var n=t.pid;a[e]=function(){var t=r.format.apply(r,arguments);console.error("%s %d: %s",e,n,t)}}else a[e]=function(){};return a[e]},r.inspect=s,s.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},s.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},r.isArray=d,r.isBoolean=p,r.isNull=b,r.isNullOrUndefined=function(e){return null==e},r.isNumber=y,r.isString=m,r.isSymbol=function(e){return"symbol"==typeof e},r.isUndefined=v,r.isRegExp=g,r.isObject=w,r.isDate=_,r.isError=A,r.isFunction=E,r.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},r.isBuffer=e("./support/isBuffer");var S=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function M(e,t){return Object.prototype.hasOwnProperty.call(e,t)}r.log=function(){var e,t;console.log("%s - %s",(e=new Date,t=[k(e.getHours()),k(e.getMinutes()),k(e.getSeconds())].join(":"),[e.getDate(),S[e.getMonth()],t].join(" ")),r.format.apply(r,arguments))},r.inherits=e("inherits"),r._extend=function(e,t){if(!t||!w(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":332,_process:257,inherits:331}],334:[function(require,module,exports){var indexOf=require("indexof"),Object_keys=function(e){if(Object.keys)return Object.keys(e);var t=[];for(var r in e)t.push(r);return t},forEach=function(e,t){if(e.forEach)return e.forEach(t);for(var r=0;r1?(e[r[0]]=e[r[0]]||{},e[r[0]][r[1]]=t):e[r[0]]=t},c.prototype.getCall=function(e){return n.isFunction(this.call)?this.call(e):this.call},c.prototype.extractCallback=function(e){if(n.isFunction(e[e.length-1]))return e.pop()},c.prototype.validateArgs=function(e){if(e.length!==this.params)throw i.InvalidNumberOfParams(e.length,this.params,this.name)},c.prototype.formatInput=function(e){var t=this;return this.inputFormatter?this.inputFormatter.map(function(r,n){return r?r.call(t,e[n]):e[n]}):e},c.prototype.formatOutput=function(e){var t=this;return n.isArray(e)?e.map(function(e){return t.outputFormatter&&e?t.outputFormatter(e):e}):this.outputFormatter&&e?this.outputFormatter(e):e},c.prototype.toPayload=function(e){var t=this.getCall(e),r=this.extractCallback(e),n=this.formatInput(e);this.validateArgs(n);var i={method:t,params:n,callback:r};return this.transformPayload&&(i=this.transformPayload(i)),i},c.prototype._confirmTransaction=function(e,t,r){var i=this,f=!1,h=!0,l=0,d=0,p=null,b="",y=n.isObject(r.params[0])&&r.params[0].gas?r.params[0].gas:null,m=n.isObject(r.params[0])&&r.params[0].data&&r.params[0].from&&!r.params[0].to,v=[new c({name:"getTransactionReceipt",call:"eth_getTransactionReceipt",params:1,inputFormatter:[null],outputFormatter:o.outputTransactionReceiptFormatter}),new c({name:"getCode",call:"eth_getCode",params:2,inputFormatter:[o.inputAddressFormatter,o.inputDefaultBlockNumberFormatter]}),new u({name:"subscribe",type:"eth",subscriptions:{newBlockHeaders:{subscriptionName:"newHeads",params:0,outputFormatter:o.outputBlockFormatter}}})],g={};n.each(v,function(e){e.attachToObject(g),e.requestManager=i.requestManager});var w=function(r,n,o,u,c){if(!o)return c||(c={unsubscribe:function(){clearInterval(p)}}),(r?s.resolve(r):g.getTransactionReceipt(t)).catch(function(t){c.unsubscribe(),f=!0,a._fireError({message:"Failed to check for transaction receipt:",data:t},e.eventEmitter,e.reject)}).then(function(t){if(!t||!t.blockHash)throw new Error("Receipt missing or blockHash null");return i.extraFormatters&&i.extraFormatters.receiptFormatter&&(t=i.extraFormatters.receiptFormatter(t)),e.eventEmitter.listeners("confirmation").length>0&&(void 0!==r&&0===d||e.eventEmitter.emit("confirmation",d,t),h=!1,25===++d&&(c.unsubscribe(),e.eventEmitter.removeAllListeners())),t}).then(function(t){if(m&&!f){if(!t.contractAddress)return h&&(c.unsubscribe(),f=!0),void a._fireError(new Error("The transaction receipt didn't contain a contract address."),e.eventEmitter,e.reject);g.getCode(t.contractAddress,function(r,n){n&&(n.length>2?(e.eventEmitter.emit("receipt",t),i.extraFormatters&&i.extraFormatters.contractDeployFormatter?e.resolve(i.extraFormatters.contractDeployFormatter(t)):e.resolve(t),h&&e.eventEmitter.removeAllListeners()):a._fireError(new Error("The contract code couldn't be stored, please check your gas limit."),e.eventEmitter,e.reject),h&&c.unsubscribe(),f=!0)})}return t}).then(function(t){m||f||(t.outOfGas||y&&y===t.gasUsed||!0!==t.status&&"0x1"!==t.status&&void 0!==t.status?(b=JSON.stringify(t,null,2),!1===t.status||"0x0"===t.status?a._fireError(new Error("Transaction has been reverted by the EVM:\n"+b),e.eventEmitter,e.reject):a._fireError(new Error("Transaction ran out of gas. Please provide more gas:\n"+b),e.eventEmitter,e.reject)):(e.eventEmitter.emit("receipt",t),e.resolve(t),h&&e.eventEmitter.removeAllListeners()),h&&c.unsubscribe(),f=!0)}).catch(function(){l++,n?l-1>=750&&(c.unsubscribe(),f=!0,a._fireError(new Error("Transaction was not mined within750 seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!"),e.eventEmitter,e.reject)):l-1>=50&&(c.unsubscribe(),f=!0,a._fireError(new Error("Transaction was not mined within 50 blocks, please make sure your transaction was properly sent. Be aware that it might still be mined!"),e.eventEmitter,e.reject))});c.unsubscribe(),f=!0,a._fireError({message:"Failed to subscribe to new newBlockHeaders to confirm the transaction receipts.",data:o},e.eventEmitter,e.reject)},_=function(e){n.isFunction(this.requestManager.provider.on)?g.subscribe("newBlockHeaders",w.bind(null,e,!1)):p=setInterval(w.bind(null,e,!0),1e3)}.bind(this);g.getTransactionReceipt(t).then(function(t){t&&t.blockHash?(e.eventEmitter.listeners("confirmation").length>0&&_(t),w(t,!1)):f||_()}).catch(function(){f||_()})};var f=function(e,t){return n.isNumber(e)?t.wallet[e]:n.isObject(e)&&e.address&&e.privateKey?e:t.wallet[e.toLowerCase()]};c.prototype.buildCall=function(){var e=this,t="eth_sendTransaction"===e.call||"eth_sendRawTransaction"===e.call,r=function(){var r=s(!t),i=e.toPayload(Array.prototype.slice.call(arguments)),o=function(n,o){try{o=e.formatOutput(o)}catch(e){n=e}if(o instanceof Error&&(n=o),n)return n.error&&(n=n.error),a._fireError(n,r.eventEmitter,r.reject,i.callback);i.callback&&i.callback(null,o),t?(r.eventEmitter.emit("transactionHash",o),e._confirmTransaction(r,o,i)):n||r.resolve(o)},u=function(t){var r=n.extend({},i,{method:"eth_sendRawTransaction",params:[t.rawTransaction]});e.requestManager.send(r,o)},h=function(e,t){var i;if(t&&t.accounts&&t.accounts.wallet&&t.accounts.wallet.length)if("eth_sendTransaction"===e.method){var a=e.params[0];if((i=f(n.isObject(a)?a.from:null,t.accounts))&&i.privateKey)return t.accounts.signTransaction(n.omit(a,"from"),i.privateKey).then(u)}else if("eth_sign"===e.method){var s=e.params[1];if((i=f(e.params[0],t.accounts))&&i.privateKey){var c=t.accounts.sign(s,i.privateKey);return e.callback&&e.callback(null,c.signature),void r.resolve(c.signature)}}return t.requestManager.send(e,o)};t&&n.isObject(i.params[0])&&void 0===i.params[0].gasPrice?new c({name:"getGasPrice",call:"eth_gasPrice",params:0}).createFunction(e.requestManager)(function(t,r){r&&(i.params[0].gasPrice=r),h(i,e)}):h(i,e);return r.eventEmitter};return r.method=e,r.request=this.request.bind(this),r},c.prototype.request=function(){var e=this.toPayload(Array.prototype.slice.call(arguments));return e.format=this.formatOutput.bind(this),e},t.exports=c},{underscore:325,"web3-core-helpers":338,"web3-core-promievent":340,"web3-core-subscriptions":345,"web3-utils":403}],340:[function(e,t,r){"use strict";var n=e("eventemitter3"),i=e("any-promise"),o=function(e){var t,r,o=new i(function(){t=arguments[0],r=arguments[1]});if(e)return{resolve:t,reject:r,eventEmitter:o};var a=new n;return o._events=a._events,o.emit=a.emit,o.on=a.on,o.once=a.once,o.off=a.off,o.listeners=a.listeners,o.addListener=a.addListener,o.removeListener=a.removeListener,o.removeAllListeners=a.removeAllListeners,{resolve:t,reject:r,eventEmitter:o}};o.resolve=function(e){var t=o(!0);return t.resolve(e),t.eventEmitter},t.exports=o},{"any-promise":2,eventemitter3:156}],341:[function(e,t,r){"use strict";var n=e("./jsonrpc"),i=e("web3-core-helpers").errors,o=function(e){this.requestManager=e,this.requests=[]};o.prototype.add=function(e){this.requests.push(e)},o.prototype.execute=function(){var e=this.requests;this.requestManager.sendBatch(e,function(t,r){r=r||[],e.map(function(e,t){return r[t]||{}}).forEach(function(t,r){if(e[r].callback){if(t&&t.error)return e[r].callback(i.ErrorResponse(t));if(!n.isValidResponse(t))return e[r].callback(i.InvalidResponse(t));try{e[r].callback(null,e[r].format?e[r].format(t.result):t.result)}catch(t){e[r].callback(t)}}})})},t.exports=o},{"./jsonrpc":344,"web3-core-helpers":338}],342:[function(e,t,r){"use strict";var n=null,i=window;void 0!==i.ethereumProvider?n=i.ethereumProvider:void 0!==i.web3&&i.web3.currentProvider&&(i.web3.currentProvider.sendAsync&&(i.web3.currentProvider.send=i.web3.currentProvider.sendAsync,delete i.web3.currentProvider.sendAsync),!i.web3.currentProvider.on&&i.web3.currentProvider.connection&&"ipcProviderWrapper"===i.web3.currentProvider.connection.constructor.name&&(i.web3.currentProvider.on=function(e,t){if("function"!=typeof t)throw new Error("The second parameter callback must be a function.");switch(e){case"data":this.connection.on("data",function(e){var r="";e=e.toString();try{r=JSON.parse(e)}catch(r){return t(new Error("Couldn't parse response data"+e))}r.id||-1===r.method.indexOf("_subscription")||t(null,r)});break;default:this.connection.on(e,t)}}),n=i.web3.currentProvider),t.exports=n},{}],343:[function(e,t,r){"use strict";var n=e("underscore"),i=e("web3-core-helpers").errors,o=e("./jsonrpc.js"),a=e("./batch.js"),s=e("./givenProvider.js"),u=function e(t){this.provider=null,this.providers=e.providers,this.setProvider(t),this.subscriptions={}};u.givenProvider=s,u.providers={WebsocketProvider:e("web3-providers-ws"),HttpProvider:e("web3-providers-http"),IpcProvider:e("web3-providers-ipc")},u.prototype.setProvider=function(e,t){var r=this;if(e&&"string"==typeof e&&this.providers)if(/^http(s)?:\/\//i.test(e))e=new this.providers.HttpProvider(e);else if(/^ws(s)?:\/\//i.test(e))e=new this.providers.WebsocketProvider(e);else if(e&&"object"==typeof t&&"function"==typeof t.connect)e=new this.providers.IpcProvider(e,t);else if(e)throw new Error("Can't autodetect provider for \""+e+'"');this.provider&&this.provider.connected&&this.clearSubscriptions(),this.provider=e||null,this.provider&&this.provider.on&&this.provider.on("data",function(e,t){(e=e||t).method&&r.subscriptions[e.params.subscription]&&r.subscriptions[e.params.subscription].callback&&r.subscriptions[e.params.subscription].callback(null,e.params.result)})},u.prototype.send=function(e,t){if(t=t||function(){},!this.provider)return t(i.InvalidProvider());var r=o.toPayload(e.method,e.params);this.provider[this.provider.sendAsync?"sendAsync":"send"](r,function(e,n){return n&&n.id&&r.id!==n.id?t(new Error('Wrong response id "'+n.id+'" (expected: "'+r.id+'") in '+JSON.stringify(r))):e?t(e):n&&n.error?t(i.ErrorResponse(n)):o.isValidResponse(n)?void t(null,n.result):t(i.InvalidResponse(n))})},u.prototype.sendBatch=function(e,t){if(!this.provider)return t(i.InvalidProvider());var r=o.toBatchPayload(e);this.provider[this.provider.sendAsync?"sendAsync":"send"](r,function(e,r){return e?t(e):n.isArray(r)?void t(null,r):t(i.InvalidResponse(r))})},u.prototype.addSubscription=function(e,t,r,n){if(!this.provider.on)throw new Error("The provider doesn't support subscriptions: "+this.provider.constructor.name);this.subscriptions[e]={callback:n,type:r,name:t}},u.prototype.removeSubscription=function(e,t){this.subscriptions[e]&&(this.send({method:this.subscriptions[e].type+"_unsubscribe",params:[e]},t),delete this.subscriptions[e])},u.prototype.clearSubscriptions=function(e){var t=this;Object.keys(this.subscriptions).forEach(function(r){e&&"syncing"===t.subscriptions[r].name||t.removeSubscription(r)}),this.provider.reset&&this.provider.reset()},t.exports={Manager:u,BatchManager:a}},{"./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(e,t,r){"use strict";var n={messageId:0,toPayload:function(e,t){if(!e)throw new Error('JSONRPC method should be specified for params: "'+JSON.stringify(t)+'"!');return n.messageId++,{jsonrpc:"2.0",id:n.messageId,method:e,params:t||[]}},isValidResponse:function(e){return Array.isArray(e)?e.every(t):t(e);function t(e){return!(!e||e.error||"2.0"!==e.jsonrpc||"number"!=typeof e.id&&"string"!=typeof e.id||void 0===e.result)}},toBatchPayload:function(e){return e.map(function(e){return n.toPayload(e.method,e.params)})}};t.exports=n},{}],345:[function(e,t,r){"use strict";var n=e("./subscription.js"),i=function(e){this.name=e.name,this.type=e.type,this.subscriptions=e.subscriptions||{},this.requestManager=null};i.prototype.setRequestManager=function(e){this.requestManager=e},i.prototype.attachToObject=function(e){var t=this.buildCall(),r=this.name.split(".");r.length>1?(e[r[0]]=e[r[0]]||{},e[r[0]][r[1]]=t):e[r[0]]=t},i.prototype.buildCall=function(){var e=this;return function(){e.subscriptions[arguments[0]]||console.warn("Subscription "+JSON.stringify(arguments[0])+" doesn't exist. Subscribing anyway.");var t=new n({subscription:e.subscriptions[arguments[0]],requestManager:e.requestManager,type:e.type});return t.subscribe.apply(t,arguments)}},t.exports={subscriptions:i,subscription:n}},{"./subscription.js":346}],346:[function(e,t,r){"use strict";var n=e("underscore"),i=e("web3-core-helpers").errors,o=e("eventemitter3");function a(e){o.call(this),this.id=null,this.callback=n.identity,this.arguments=null,this._reconnectIntervalId=null,this.options={subscription:e.subscription,type:e.type,requestManager:e.requestManager}}a.prototype=Object.create(o.prototype),a.prototype.constructor=a,a.prototype._extractCallback=function(e){if(n.isFunction(e[e.length-1]))return e.pop()},a.prototype._validateArgs=function(e){var t=this.options.subscription;if(t||(t={}),t.params||(t.params=0),e.length!==t.params)throw i.InvalidNumberOfParams(e.length,t.params+1,e[0])},a.prototype._formatInput=function(e){var t=this.options.subscription;return t&&t.inputFormatter?t.inputFormatter.map(function(t,r){return t?t(e[r]):e[r]}):e},a.prototype._formatOutput=function(e){var t=this.options.subscription;return t&&t.outputFormatter&&e?t.outputFormatter(e):e},a.prototype._toPayload=function(e){var t=[];if(this.callback=this._extractCallback(e)||n.identity,this.subscriptionMethod||(this.subscriptionMethod=e.shift(),this.options.subscription.subscriptionName&&(this.subscriptionMethod=this.options.subscription.subscriptionName)),this.arguments||(this.arguments=this._formatInput(e),this._validateArgs(this.arguments),e=[]),t.push(this.subscriptionMethod),t=t.concat(this.arguments),e.length)throw new Error("Only a callback is allowed as parameter on an already instantiated subscription.");return{method:this.options.type+"_subscribe",params:t}},a.prototype.unsubscribe=function(e){this.options.requestManager.removeSubscription(this.id,e),this.id=null,this.removeAllListeners(),clearInterval(this._reconnectIntervalId)},a.prototype.subscribe=function(){var e=this,t=Array.prototype.slice.call(arguments),r=this._toPayload(t);if(!r)return this;if(!this.options.requestManager.provider){var i=new Error("No provider set.");return this.callback(i,null,this),this.emit("error",i),this}if(!this.options.requestManager.provider.on){var o=new Error("The current provider doesn't support subscriptions: "+this.options.requestManager.provider.constructor.name);return this.callback(o,null,this),this.emit("error",o),this}return this.id&&this.unsubscribe(),this.options.params=r.params[1],"logs"===r.params[0]&&n.isObject(r.params[1])&&r.params[1].hasOwnProperty("fromBlock")&&isFinite(r.params[1].fromBlock)&&this.options.requestManager.send({method:"eth_getLogs",params:[r.params[1]]},function(t,r){t?(e.callback(t,null,e),e.emit("error",t)):r.forEach(function(t){var r=e._formatOutput(t);e.callback(null,r,e),e.emit("data",r)})}),"object"==typeof r.params[1]&&delete r.params[1].fromBlock,this.options.requestManager.send(r,function(t,i){!t&&i?(e.id=i,e.options.requestManager.addSubscription(e.id,r.params[0],e.options.type,function(t,r){t?(e.options.requestManager.removeSubscription(e.id),e.options.requestManager.provider.once&&(e._reconnectIntervalId=setInterval(function(){e.options.requestManager.provider.reconnect&&e.options.requestManager.provider.reconnect()},500),e.options.requestManager.provider.once("connect",function(){clearInterval(e._reconnectIntervalId),e.subscribe(e.callback)})),e.emit("error",t),e.callback(t,null,e)):(n.isArray(r)||(r=[r]),r.forEach(function(t){var r=e._formatOutput(t);if(n.isFunction(e.options.subscription.subscriptionHandler))return e.options.subscription.subscriptionHandler.call(e,r);e.emit("data",r),e.callback(null,r,e)}))})):(e.callback(t,null,e),e.emit("error",t))}),this},t.exports=a},{eventemitter3:156,underscore:325,"web3-core-helpers":338}],347:[function(e,t,r){"use strict";var n=e("web3-core-helpers").formatters,i=e("web3-core-method"),o=e("web3-utils");t.exports=function(e){var t=function(t){var r;return t.property?(e[t.property]||(e[t.property]={}),r=e[t.property]):r=e,t.methods&&t.methods.forEach(function(t){t instanceof i||(t=new i(t)),t.attachToObject(r),t.setRequestManager(e._requestManager)}),e};return t.formatters=n,t.utils=o,t.Method=i,t}},{"web3-core-helpers":338,"web3-core-method":339,"web3-utils":403}],348:[function(e,t,r){"use strict";var n=e("web3-core-requestmanager"),i=e("./extend.js");t.exports={packageInit:function(e,t){if(t=Array.prototype.slice.call(t),!e)throw new Error('You need to instantiate using the "new" keyword.');Object.defineProperty(e,"currentProvider",{get:function(){return e._provider},set:function(t){return e.setProvider(t)},enumerable:!0,configurable:!0}),t[0]&&t[0]._requestManager?e._requestManager=new n.Manager(t[0].currentProvider):(e._requestManager=new n.Manager,e._requestManager.setProvider(t[0],t[1])),e.givenProvider=n.Manager.givenProvider,e.providers=n.Manager.providers,e._provider=e._requestManager.provider,e.setProvider||(e.setProvider=function(t,r){return e._requestManager.setProvider(t,r),e._provider=e._requestManager.provider,!0}),e.BatchRequest=n.BatchManager.bind(null,e._requestManager),e.extend=i(e)},addProviders:function(e){e.givenProvider=n.Manager.givenProvider,e.providers=n.Manager.providers}}},{"./extend.js":347,"web3-core-requestmanager":343}],349:[function(e,t,r){var n=e("underscore"),i=e("web3-utils"),o=new(0,e("ethers/utils/abi-coder").AbiCoder)(function(e,t){return!e.match(/^u?int/)||n.isArray(t)||n.isObject(t)&&"BN"===t.constructor.name?t:t.toString()});function a(){}var s=function(){};s.prototype.encodeFunctionSignature=function(e){return n.isObject(e)&&(e=i._jsonInterfaceMethodToString(e)),i.sha3(e).slice(0,10)},s.prototype.encodeEventSignature=function(e){return n.isObject(e)&&(e=i._jsonInterfaceMethodToString(e)),i.sha3(e)},s.prototype.encodeParameter=function(e,t){return this.encodeParameters([e],[t])},s.prototype.encodeParameters=function(e,t){return o.encode(this.mapTypes(e),t)},s.prototype.mapTypes=function(e){var t=this,r=[];return e.forEach(function(e){if(t.isSimplifiedStructFormat(e)){var n=Object.keys(e)[0];r.push(Object.assign(t.mapStructNameAndType(n),{components:t.mapStructToCoderFormat(e[n])}))}else r.push(e)}),r},s.prototype.isSimplifiedStructFormat=function(e){return"object"==typeof e&&void 0===e.components&&void 0===e.name},s.prototype.mapStructNameAndType=function(e){var t="tuple";return e.indexOf("[]")>-1&&(t="tuple[]",e=e.slice(0,-2)),{type:t,name:e}},s.prototype.mapStructToCoderFormat=function(e){var t=this,r=[];return Object.keys(e).forEach(function(n){"object"!=typeof e[n]?r.push({name:n,type:e[n]}):r.push(Object.assign(t.mapStructNameAndType(n),{components:t.mapStructToCoderFormat(e[n])}))}),r},s.prototype.encodeFunctionCall=function(e,t){return this.encodeFunctionSignature(e)+this.encodeParameters(e.inputs,t).replace("0x","")},s.prototype.decodeParameter=function(e,t){return this.decodeParameters([e],t)[0]},s.prototype.decodeParameters=function(e,t){if(!t||"0x"===t||"0X"===t)throw new Error("Returned values aren't valid, did it run Out of Gas?");var r=o.decode(this.mapTypes(e),"0x"+t.replace(/0x/i,"")),i=new a;return i.__length__=0,e.forEach(function(e,t){var o=r[i.__length__];o="0x"===o?null:o,i[t]=o,n.isObject(e)&&e.name&&(i[e.name]=o),i.__length__++}),i},s.prototype.decodeLog=function(e,t,r){var i=this;r=n.isArray(r)?r:[r],t=t||"";var o=[],s=[],u=0;e.forEach(function(e,t){e.indexed?(s[t]=["bool","int","uint","address","fixed","ufixed"].find(function(t){return-1!==e.type.indexOf(t)})?i.decodeParameter(e.type,r[u]):r[u],u++):o[t]=e});var c=t,f=c?this.decodeParameters(o,c):[],h=new a;return h.__length__=0,e.forEach(function(e,t){h[t]="string"===e.type?"":null,void 0!==f[t]&&(h[t]=f[t]),void 0!==s[t]&&(h[t]=s[t]),e.name&&(h[e.name]=h[t]),h.__length__++}),h};var u=new s;t.exports=u},{"ethers/utils/abi-coder":143,underscore:325,"web3-utils":403}],350:[function(e,t,r){(function(r){var n=function(){return function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var r=[],n=!0,i=!1,o=void 0;try{for(var a,s=e[Symbol.iterator]();!(n=(a=s.next()).done)&&(r.push(a.value),!t||r.length!==t);n=!0);}catch(e){i=!0,o=e}finally{try{!n&&s.return&&s.return()}finally{if(i)throw o}}return r}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),i=e("./bytes"),o=e("./nat"),a=e("elliptic"),s=(e("./rlp"),new a.ec("secp256k1")),u=e("./hash"),c=u.keccak256,f=u.keccak256s,h=function(e){for(var t=f(e.slice(2)),r="0x",n=0;n<40;n++)r+=parseInt(t[n+2],16)>7?e[n+2].toUpperCase():e[n+2];return r},l=function(e){var t=new r(e.slice(2),"hex"),n="0x"+s.keyFromPrivate(t).getPublic(!1,"hex").slice(2),i=c(n);return{address:h("0x"+i.slice(-40)),privateKey:e}},d=function(e){var t=n(e,3),r=t[0],o=i.pad(32,t[1]),a=i.pad(32,t[2]);return i.flatten([o,a,r])},p=function(e){return[i.slice(64,i.length(e),e),i.slice(0,32,e),i.slice(32,64,e)]},b=function(e){return function(t,n){var a=s.keyFromPrivate(new r(n.slice(2),"hex")).sign(new r(t.slice(2),"hex"),{canonical:!0});return d([o.fromString(i.fromNumber(e+a.recoveryParam)),i.pad(32,i.fromNat("0x"+a.r.toString(16))),i.pad(32,i.fromNat("0x"+a.s.toString(16)))])}},y=b(27);t.exports={create:function(e){var t=c(i.concat(i.random(32),e||i.random(32))),r=i.concat(i.concat(i.random(32),t),i.random(32)),n=c(r);return l(n)},toChecksum:h,fromPrivate:l,sign:y,makeSigner:b,recover:function(e,t){var n=p(t),o={v:i.toNumber(n[0]),r:n[1].slice(2),s:n[2].slice(2)},a="0x"+s.recoverPubKey(new r(e.slice(2),"hex"),o,o.v<2?o.v:1-o.v%2).encode("hex",!1).slice(2),u=c(a);return h("0x"+u.slice(-40))},encodeSignature:d,decodeSignature:p}}).call(this,e("buffer").Buffer)},{"./bytes":352,"./hash":353,"./nat":354,"./rlp":355,buffer:84,elliptic:109}],351:[function(e,t,r){arguments[4][132][0].apply(r,arguments)},{dup:132}],352:[function(e,t,r){arguments[4][133][0].apply(r,arguments)},{"./array.js":351,dup:133}],353:[function(e,t,r){arguments[4][134][0].apply(r,arguments)},{dup:134}],354:[function(e,t,r){var n=e("bn.js"),i=e("./bytes"),o=function(e){return new n(e.slice(2),16)},a=function(e){var t="0x"+("0x"===e.slice(0,2)?new n(e.slice(2),16):new n(e,10)).toString("hex");return"0x0"===t?"0x":t},s=function(e){return"string"==typeof e?/^0x/.test(e)?e:"0x"+e:"0x"+new n(e).toString("hex")},u=function(e){return o(e).toNumber()},c=function(e){return function(t,r){return"0x"+o(t)[e](o(r)).toString("hex")}},f=c("add"),h=c("mul"),l=c("div"),d=c("sub");t.exports={toString:function(e){return o(e).toString(10)},fromString:a,toNumber:u,fromNumber:s,toEther:function(e){return u(l(e,a("10000000000")))/1e8},fromEther:function(e){return h(s(Math.floor(1e8*e)),a("10000000000"))},toUint256:function(e){return i.pad(32,e)},add:f,mul:h,div:l,sub:d}},{"./bytes":352,"bn.js":53}],355:[function(e,t,r){t.exports={encode:function(e){var t=function(e){return(t=e.toString(16)).length%2==0?t:"0"+t;var t},r=function(e,r){return e<56?t(r+e):t(r+t(e).length/2+55)+t(e)};return"0x"+function e(t){if("string"==typeof t){var n=t.slice(2);return(2!=n.length||n>="80"?r(n.length/2,128):"")+n}var i=t.map(e).join("");return r(i.length/2,192)+i}(e)},decode:function(e){var t=2,r=function(){if(t>=e.length)throw"";var r=e.slice(t,t+2);return r<"80"?(t+=2,"0x"+r):r<"c0"?i():o()},n=function(){var r=parseInt(e.slice(t,t+=2),16)%64;return r<56?r:parseInt(e.slice(t,t+=2*(r-55)),16)},i=function(){var r=n();return"0x"+e.slice(t,t+=2*r)},o=function(){for(var e=2*n()+t,i=[];t>>((3&t)<<3)&255;return i}}t.exports=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],357:[function(e,t,r){for(var n=e("./rng"),i=[],o={},a=0;a<256;a++)i[a]=(a+256).toString(16).substr(1),o[i[a]]=a;function s(e,t){var r=t||0,n=i;return n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]}var u=n(),c=[1|u[0],u[1],u[2],u[3],u[4],u[5]],f=16383&(u[6]<<8|u[7]),h=0,l=0;function d(e,t,r){var i=t&&r||0;"string"==typeof e&&(t="binary"==e?new Array(16):null,e=null);var o=(e=e||{}).random||(e.rng||n)();if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,t)for(var a=0;a<16;a++)t[i+a]=o[a];return t||s(o)}var p=d;p.v1=function(e,t,r){var n=t&&r||0,i=t||[],o=void 0!==(e=e||{}).clockseq?e.clockseq:f,a=void 0!==e.msecs?e.msecs:(new Date).getTime(),u=void 0!==e.nsecs?e.nsecs:l+1,d=a-h+(u-l)/1e4;if(d<0&&void 0===e.clockseq&&(o=o+1&16383),(d<0||a>h)&&void 0===e.nsecs&&(u=0),u>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");h=a,l=u,f=o;var p=(1e4*(268435455&(a+=122192928e5))+u)%4294967296;i[n++]=p>>>24&255,i[n++]=p>>>16&255,i[n++]=p>>>8&255,i[n++]=255&p;var b=a/4294967296*1e4&268435455;i[n++]=b>>>8&255,i[n++]=255&b,i[n++]=b>>>24&15|16,i[n++]=b>>>16&255,i[n++]=o>>>8|128,i[n++]=255&o;for(var y=e.node||c,m=0;m<6;m++)i[n+m]=y[m];return t||s(i)},p.v4=d,p.parse=function(e,t,r){var n=t&&r||0,i=0;for(t=t||[],e.toLowerCase().replace(/[0-9a-f]{2}/g,function(e){i<16&&(t[n+i++]=o[e])});i<16;)t[n+i++]=0;return t},p.unparse=s,t.exports=p},{"./rng":356}],358:[function(e,t,r){(function(r,n){"use strict";var i=e("underscore"),o=e("web3-core"),a=e("web3-core-method"),s=e("any-promise"),u=e("eth-lib/lib/account"),c=e("eth-lib/lib/hash"),f=e("eth-lib/lib/rlp"),h=e("eth-lib/lib/nat"),l=e("eth-lib/lib/bytes"),d=e(void 0===r?"crypto-browserify":"crypto"),p=e("scrypt.js"),b=e("uuid"),y=e("web3-utils"),m=e("web3-core-helpers"),v=function(e){return i.isUndefined(e)||i.isNull(e)},g=function(e){for(;e&&e.startsWith("0x0");)e="0x"+e.slice(3);return e},w=function(e){return e.length%2==1&&(e=e.replace("0x","0x0")),e},_=function(){var e=this;o.packageInit(this,arguments),delete this.BatchRequest,delete this.extend;var t=[new a({name:"getId",call:"net_version",params:0,outputFormatter:y.hexToNumber}),new a({name:"getGasPrice",call:"eth_gasPrice",params:0}),new a({name:"getTransactionCount",call:"eth_getTransactionCount",params:2,inputFormatter:[function(e){if(y.isAddress(e))return e;throw new Error("Address "+e+' is not a valid address to get the "transactionCount".')},function(){return"latest"}]})];this._ethereumCall={},i.each(t,function(t){t.attachToObject(e._ethereumCall),t.setRequestManager(e._requestManager)}),this.wallet=new A(this)};function A(e){this._accounts=e,this.length=0,this.defaultKeyName="web3js_wallet"}_.prototype._addAccountFunctions=function(e){var t=this;return e.signTransaction=function(r,n){return t.signTransaction(r,e.privateKey,n)},e.sign=function(r){return t.sign(r,e.privateKey)},e.encrypt=function(r,n){return t.encrypt(e.privateKey,r,n)},e},_.prototype.create=function(e){return this._addAccountFunctions(u.create(e||y.randomHex(32)))},_.prototype.privateKeyToAccount=function(e){return this._addAccountFunctions(u.fromPrivate(e))},_.prototype.signTransaction=function(e,t,r){var n,o=!1;if(r=r||function(){},!e)return o=new Error("No transaction object given!"),r(o),s.reject(o);function a(e){if(e.gas||e.gasLimit||(o=new Error('"gas" is missing')),(e.nonce<0||e.gas<0||e.gasPrice<0||e.chainId<0)&&(o=new Error("Gas, gasPrice, nonce or chainId is lower than 0")),o)return r(o),s.reject(o);try{var i=e=m.formatters.inputCallFormatter(e);i.to=e.to||"0x",i.data=e.data||"0x",i.value=e.value||"0x",i.chainId=y.numberToHex(e.chainId);var a=f.encode([l.fromNat(i.nonce),l.fromNat(i.gasPrice),l.fromNat(i.gas),i.to.toLowerCase(),l.fromNat(i.value),i.data,l.fromNat(i.chainId||"0x1"),"0x","0x"]),d=c.keccak256(a),p=u.makeSigner(2*h.toNumber(i.chainId||"0x1")+35)(c.keccak256(a),t),b=f.decode(a).slice(0,6).concat(u.decodeSignature(p));b[6]=w(g(b[6])),b[7]=w(g(b[7])),b[8]=w(g(b[8]));var v=f.encode(b),_=f.decode(v);n={messageHash:d,v:g(_[6]),r:g(_[7]),s:g(_[8]),rawTransaction:v}}catch(e){return r(e),s.reject(e)}return r(null,n),n}return void 0!==e.nonce&&void 0!==e.chainId&&void 0!==e.gasPrice?s.resolve(a(e)):s.all([v(e.chainId)?this._ethereumCall.getId():e.chainId,v(e.gasPrice)?this._ethereumCall.getGasPrice():e.gasPrice,v(e.nonce)?this._ethereumCall.getTransactionCount(this.privateKeyToAccount(t).address):e.nonce]).then(function(t){if(v(t[0])||v(t[1])||v(t[2]))throw new Error('One of the values "chainId", "gasPrice", or "nonce" couldn\'t be fetched: '+JSON.stringify(t));return a(i.extend(e,{chainId:t[0],gasPrice:t[1],nonce:t[2]}))})},_.prototype.recoverTransaction=function(e){var t=f.decode(e),r=u.encodeSignature(t.slice(6,9)),n=l.toNumber(t[6]),i=n<35?[]:[l.fromNumber(n-35>>1),"0x","0x"],o=t.slice(0,6).concat(i),a=f.encode(o);return u.recover(c.keccak256(a),r)},_.prototype.hashMessage=function(e){var t=y.isHexStrict(e)?y.hexToBytes(e):e,r=n.from(t),i="Ethereum Signed Message:\n"+t.length,o=n.from(i),a=n.concat([o,r]);return c.keccak256s(a)},_.prototype.sign=function(e,t){var r=this.hashMessage(e),n=u.sign(r,t),i=u.decodeSignature(n);return{message:e,messageHash:r,v:i[0],r:i[1],s:i[2],signature:n}},_.prototype.recover=function(e,t,r){var n=[].slice.apply(arguments);return i.isObject(e)?this.recover(e.messageHash,u.encodeSignature([e.v,e.r,e.s]),!0):(r||(e=this.hashMessage(e)),n.length>=4?(r=n.slice(-1)[0],r=!!i.isBoolean(r)&&!!r,this.recover(e,u.encodeSignature(n.slice(1,4)),r)):u.recover(e,t))},_.prototype.decrypt=function(e,t,r){if(!i.isString(t))throw new Error("No password given.");var o,a,s=i.isObject(e)?e:JSON.parse(r?e.toLowerCase():e);if(3!==s.version)throw new Error("Not a valid V3 wallet");if("scrypt"===s.crypto.kdf)a=s.crypto.kdfparams,o=p(new n(t),new n(a.salt,"hex"),a.n,a.r,a.p,a.dklen);else{if("pbkdf2"!==s.crypto.kdf)throw new Error("Unsupported key derivation scheme");if("hmac-sha256"!==(a=s.crypto.kdfparams).prf)throw new Error("Unsupported parameters to PBKDF2");o=d.pbkdf2Sync(new n(t),new n(a.salt,"hex"),a.c,a.dklen,"sha256")}var u=new n(s.crypto.ciphertext,"hex");if(y.sha3(n.concat([o.slice(16,32),u])).replace("0x","")!==s.crypto.mac)throw new Error("Key derivation failed - possibly wrong password");var c=d.createDecipheriv(s.crypto.cipher,o.slice(0,16),new n(s.crypto.cipherparams.iv,"hex")),f="0x"+n.concat([c.update(u),c.final()]).toString("hex");return this.privateKeyToAccount(f)},_.prototype.encrypt=function(e,t,r){var i,o=this.privateKeyToAccount(e),a=(r=r||{}).salt||d.randomBytes(32),s=r.iv||d.randomBytes(16),u=r.kdf||"scrypt",c={dklen:r.dklen||32,salt:a.toString("hex")};if("pbkdf2"===u)c.c=r.c||262144,c.prf="hmac-sha256",i=d.pbkdf2Sync(new n(t),a,c.c,c.dklen,"sha256");else{if("scrypt"!==u)throw new Error("Unsupported kdf");c.n=r.n||8192,c.r=r.r||8,c.p=r.p||1,i=p(new n(t),a,c.n,c.r,c.p,c.dklen)}var f=d.createCipheriv(r.cipher||"aes-128-ctr",i.slice(0,16),s);if(!f)throw new Error("Unsupported cipher");var h=n.concat([f.update(new n(o.privateKey.replace("0x",""),"hex")),f.final()]),l=y.sha3(n.concat([i.slice(16,32),new n(h,"hex")])).replace("0x","");return{version:3,id:b.v4({random:r.uuid||d.randomBytes(16)}),address:o.address.toLowerCase().replace("0x",""),crypto:{ciphertext:h.toString("hex"),cipherparams:{iv:s.toString("hex")},cipher:r.cipher||"aes-128-ctr",kdf:u,kdfparams:c,mac:l.toString("hex")}}},A.prototype._findSafeIndex=function(e){return e=e||0,i.has(this,e)?this._findSafeIndex(e+1):e},A.prototype._currentIndexes=function(){return Object.keys(this).map(function(e){return parseInt(e)}).filter(function(e){return e<9e20})},A.prototype.create=function(e,t){for(var r=0;r=2?t.slice(2):t;var r=h.decodeParameters(e,t);return 1===r.__length__?r[0]:(delete r.__length__,r)},l.prototype.deploy=function(e,t){if((e=e||{}).arguments=e.arguments||[],!(e=this._getOrSetDefaultOptions(e)).data)return a._fireError(new Error('No "data" specified in neither the given options, nor the default options.'),null,null,t);var r=n.find(this.options.jsonInterface,function(e){return"constructor"===e.type})||{};return r.signature="constructor",this._createTxObject.apply({method:r,parent:this,deployData:e.data,_ethAccounts:this.constructor._ethAccounts},e.arguments)},l.prototype._generateEventOptions=function(){var e=Array.prototype.slice.call(arguments),t=this._getCallback(e),r=n.isObject(e[e.length-1])?e.pop():{},i=n.isString(e[0])?e[0]:"allevents";if(!(i="allevents"===i.toLowerCase()?{name:"ALLEVENTS",jsonInterface:this.options.jsonInterface}:this.options.jsonInterface.find(function(e){return"event"===e.type&&(e.name===i||e.signature==="0x"+i.replace("0x",""))})))throw new Error('Event "'+i.name+"\" doesn't exist in this contract.");if(!a.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(i,r),event:i,callback:t}},l.prototype.clone=function(){return new this.constructor(this.options.jsonInterface,this.options.address,this.options)},l.prototype.once=function(e,t,r){var i=Array.prototype.slice.call(arguments);if(!(r=this._getCallback(i)))throw new Error("Once requires a callback as the second parameter.");t&&delete t.fromBlock,this._on(e,t,function(e,t,i){i.unsubscribe(),n.isFunction(r)&&r(e,t,i)})},l.prototype._on=function(){var e=this._generateEventOptions.apply(this,arguments);this._checkListener("newListener",e.event.name,e.callback),this._checkListener("removeListener",e.event.name,e.callback);var t=new s({subscription:{params:1,inputFormatter:[u.inputLogFormatter],outputFormatter:this._decodeEventABI.bind(e.event),subscriptionHandler:function(e){e.removed?this.emit("changed",e):this.emit("data",e),n.isFunction(this.callback)&&this.callback(null,e,this)}},type:"eth",requestManager:this._requestManager});return t.subscribe("logs",e.params,e.callback||function(){}),t},l.prototype.getPastEvents=function(){var e=this._generateEventOptions.apply(this,arguments),t=new o({name:"getPastLogs",call:"eth_getLogs",params:1,inputFormatter:[u.inputLogFormatter],outputFormatter:this._decodeEventABI.bind(e.event)});t.setRequestManager(this._requestManager);var r=t.buildCall();return t=null,r(e.params,e.callback)},l.prototype._createTxObject=function(){var e=Array.prototype.slice.call(arguments),t={};if("function"===this.method.type&&(t.call=this.parent._executeMethod.bind(t,"call"),t.call.request=this.parent._executeMethod.bind(t,"call",!0)),t.send=this.parent._executeMethod.bind(t,"send"),t.send.request=this.parent._executeMethod.bind(t,"send",!0),t.encodeABI=this.parent._encodeMethodABI.bind(t),t.estimateGas=this.parent._executeMethod.bind(t,"estimate"),e&&this.method.inputs&&e.length!==this.method.inputs.length){if(this.nextMethod)return this.nextMethod.apply(null,e);throw c.InvalidNumberOfParams(e.length,this.method.inputs.length,this.method.name)}return t.arguments=e||[],t._method=this.method,t._parent=this.parent,t._ethAccounts=this.parent.constructor._ethAccounts||this._ethAccounts,this.deployData&&(t._deployData=this.deployData),t},l.prototype._processExecuteArguments=function(e,t){var r={};if(r.type=e.shift(),r.callback=this._parent._getCallback(e),"call"===r.type&&!0!==e[e.length-1]&&(n.isString(e[e.length-1])||isFinite(e[e.length-1]))&&(r.defaultBlock=e.pop()),r.options=n.isObject(e[e.length-1])?e.pop():{},r.generateRequest=!0===e[e.length-1]&&e.pop(),r.options=this._parent._getOrSetDefaultOptions(r.options),r.options.data=this.encodeABI(),!this._deployData&&!a.isAddress(this._parent.options.address))throw new Error("This contract object doesn't have address set yet, please set an address first.");return this._deployData||(r.options.to=this._parent.options.address),r.options.data?r:a._fireError(new Error("Couldn't find a matching contract method, or the number of parameters is wrong."),t.eventEmitter,t.reject,r.callback)},l.prototype._executeMethod=function(){var e=this,t=this._parent._processExecuteArguments.call(this,Array.prototype.slice.call(arguments),r),r=f("send"!==t.type),i=e.constructor._ethAccounts||e._ethAccounts;if(t.generateRequest){var s={params:[u.inputCallFormatter.call(this._parent,t.options)],callback:t.callback};return"call"===t.type?(s.params.push(u.inputDefaultBlockNumberFormatter.call(this._parent,t.defaultBlock)),s.method="eth_call",s.format=this._parent._decodeMethodReturn.bind(null,this._method.outputs)):s.method="eth_sendTransaction",s}switch(t.type){case"estimate":return new o({name:"estimateGas",call:"eth_estimateGas",params:1,inputFormatter:[u.inputCallFormatter],outputFormatter:a.hexToNumber,requestManager:e._parent._requestManager,accounts:i,defaultAccount:e._parent.defaultAccount,defaultBlock:e._parent.defaultBlock}).createFunction()(t.options,t.callback);case"call":return new o({name:"call",call:"eth_call",params:2,inputFormatter:[u.inputCallFormatter,u.inputDefaultBlockNumberFormatter],outputFormatter:function(t){return e._parent._decodeMethodReturn(e._method.outputs,t)},requestManager:e._parent._requestManager,accounts:i,defaultAccount:e._parent.defaultAccount,defaultBlock:e._parent.defaultBlock}).createFunction()(t.options,t.defaultBlock,t.callback);case"send":if(!a.isAddress(t.options.from))return a._fireError(new Error('No "from" address specified in neither the given options, nor the default options.'),r.eventEmitter,r.reject,t.callback);if(n.isBoolean(this._method.payable)&&!this._method.payable&&t.options.value&&t.options.value>0)return a._fireError(new Error("Can not send value to non-payable contract method or constructor"),r.eventEmitter,r.reject,t.callback);var c={receiptFormatter:function(t){if(n.isArray(t.logs)){var r=n.map(t.logs,function(t){return e._parent._decodeEventABI.call({name:"ALLEVENTS",jsonInterface:e._parent.options.jsonInterface},t)});t.events={};var i=0;r.forEach(function(e){e.event?t.events[e.event]?Array.isArray(t.events[e.event])?t.events[e.event].push(e):t.events[e.event]=[t.events[e.event],e]:t.events[e.event]=e:(t.events[i]=e,i++)}),delete t.logs}return t},contractDeployFormatter:function(t){var r=e._parent.clone();return r.options.address=t.contractAddress,r}};return new o({name:"sendTransaction",call:"eth_sendTransaction",params:1,inputFormatter:[u.inputTransactionFormatter],requestManager:e._parent._requestManager,accounts:e.constructor._ethAccounts||e._ethAccounts,defaultAccount:e._parent.defaultAccount,defaultBlock:e._parent.defaultBlock,extraFormatters:c}).createFunction()(t.options,t.callback)}},t.exports=l},{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(e,t,r){"use strict";var n=e("./config"),i=e("./contracts/Registry"),o=e("./lib/ResolverMethodHandler");function a(e){this.eth=e}Object.defineProperty(a.prototype,"registry",{get:function(){return new i(this)},enumerable:!0}),Object.defineProperty(a.prototype,"resolverMethodHandler",{get:function(){return new o(this.registry)},enumerable:!0}),a.prototype.resolver=function(e){return this.registry.resolver(e)},a.prototype.getAddress=function(e,t){return this.resolverMethodHandler.method(e,"addr",[]).call(t)},a.prototype.setAddress=function(e,t,r,n){return this.resolverMethodHandler.method(e,"setAddr",[t]).send(r,n)},a.prototype.getPubkey=function(e,t){return this.resolverMethodHandler.method(e,"pubkey",[],t).call(t)},a.prototype.setPubkey=function(e,t,r,n,i){return this.resolverMethodHandler.method(e,"setPubkey",[t,r]).send(n,i)},a.prototype.getContent=function(e,t){return this.resolverMethodHandler.method(e,"content",[]).call(t)},a.prototype.setContent=function(e,t,r,n){return this.resolverMethodHandler.method(e,"setContent",[t]).send(r,n)},a.prototype.getMultihash=function(e,t){return this.resolverMethodHandler.method(e,"multihash",[]).call(t)},a.prototype.setMultihash=function(e,t,r,n){return this.resolverMethodHandler.method(e,"multihash",[t]).send(r,n)},a.prototype.checkNetwork=function(){var e=this;return e.eth.getBlock("latest").then(function(t){var r=new Date/1e3-t.timestamp;if(r>3600)throw new Error("Network not synced; last block was "+r+" seconds ago");return e.eth.net.getNetworkType()}).then(function(e){var t=n.addresses[e];if(void 0===t)throw new Error("ENS is not supported on network "+e);return t})},t.exports=a},{"./config":361,"./contracts/Registry":362,"./lib/ResolverMethodHandler":364}],361:[function(e,t,r){"use strict";t.exports={addresses:{main:"0x314159265dD8dbb310642f98f50C066173C1259b",ropsten:"0x112234455c3a32fd11230c42e7bccd4a84e02010",rinkeby:"0xe7410170f87102df0055eb195163a03b7f2bff4a"}}},{}],362:[function(e,t,r){"use strict";var n=e("underscore"),i=e("web3-eth-contract"),o=e("eth-ens-namehash"),a=e("web3-core-promievent"),s=e("../ressources/ABI/Registry"),u=e("../ressources/ABI/Resolver");function c(e){var t=this;this.ens=e,this.contract=e.checkNetwork().then(function(e){var r=new i(s,e);return r.setProvider(t.ens.eth.currentProvider),r})}c.prototype.owner=function(e,t){var r=new a(!0);return this.contract.then(function(i){i.methods.owner(o.hash(e)).call().then(function(e){r.resolve(e),n.isFunction(t)&&t(e)}).catch(function(e){r.reject(e),n.isFunction(t)&&t(e)})}),r.eventEmitter},c.prototype.resolver=function(e){var t=this;return this.contract.then(function(t){return t.methods.resolver(o.hash(e)).call()}).then(function(e){var r=new i(u,e);return r.setProvider(t.ens.eth.currentProvider),r})},t.exports=c},{"../ressources/ABI/Registry":365,"../ressources/ABI/Resolver":366,"eth-ens-namehash":127,underscore:325,"web3-core-promievent":340,"web3-eth-contract":359}],363:[function(e,t,r){"use strict";var n=e("./ENS");t.exports=n},{"./ENS":360}],364:[function(e,t,r){"use strict";var n=e("web3-core-promievent"),i=e("eth-ens-namehash"),o=e("underscore");function a(e){this.registry=e}a.prototype.method=function(e,t,r,n){return{call:this.call.bind({ensName:e,methodName:t,methodArguments:r,callback:n,parent:this}),send:this.send.bind({ensName:e,methodName:t,methodArguments:r,callback:n,parent:this})}},a.prototype.call=function(e){var t=this,r=new n,i=this.parent.prepareArguments(this.ensName,this.methodArguments);return this.parent.registry.resolver(this.ensName).then(function(n){t.parent.handleCall(r,n.methods[t.methodName],i,e)}).catch(function(e){r.reject(e)}),r.eventEmitter},a.prototype.send=function(e,t){var r=this,i=new n,o=this.parent.prepareArguments(this.ensName,this.methodArguments);return this.parent.registry.resolver(this.ensName).then(function(n){r.parent.handleSend(i,n.methods[r.methodName],o,e,t)}).catch(function(e){i.reject(e)}),i.eventEmitter},a.prototype.handleCall=function(e,t,r,n){return t.apply(this,r).call().then(function(t){e.resolve(t),o.isFunction(n)&&n(t)}).catch(function(t){e.reject(t),o.isFunction(n)&&n(t)}),e},a.prototype.handleSend=function(e,t,r,n,i){return t.apply(this,r).send(n).on("transactionHash",function(t){e.eventEmitter.emit("transactionHash",t)}).on("confirmation",function(t,r){e.eventEmitter.emit("confirmation",t,r)}).on("receipt",function(t){e.eventEmitter.emit("receipt",t),e.resolve(t),o.isFunction(i)&&i(t)}).on("error",function(t){e.eventEmitter.emit("error",t),e.reject(t),o.isFunction(i)&&i(t)}),e},a.prototype.prepareArguments=function(e,t){var r=i.hash(e);return t.length>0?(t.unshift(r),t):[r]},t.exports=a},{"eth-ens-namehash":127,underscore:325,"web3-core-promievent":340}],365:[function(e,t,r){"use strict";t.exports=[{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"resolver",outputs:[{name:"",type:"address"}],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"owner",outputs:[{name:"",type:"address"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"label",type:"bytes32"},{name:"owner",type:"address"}],name:"setSubnodeOwner",outputs:[],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"ttl",type:"uint64"}],name:"setTTL",outputs:[],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"ttl",outputs:[{name:"",type:"uint64"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"resolver",type:"address"}],name:"setResolver",outputs:[],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"owner",type:"address"}],name:"setOwner",outputs:[],payable:!1,type:"function"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"owner",type:"address"}],name:"Transfer",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!0,name:"label",type:"bytes32"},{indexed:!1,name:"owner",type:"address"}],name:"NewOwner",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"resolver",type:"address"}],name:"NewResolver",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"ttl",type:"uint64"}],name:"NewTTL",type:"event"}]},{}],366:[function(e,t,r){"use strict";t.exports=[{constant:!0,inputs:[{name:"interfaceID",type:"bytes4"}],name:"supportsInterface",outputs:[{name:"",type:"bool"}],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"},{name:"contentTypes",type:"uint256"}],name:"ABI",outputs:[{name:"contentType",type:"uint256"},{name:"data",type:"bytes"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"hash",type:"bytes"}],name:"setMultihash",outputs:[],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"multihash",outputs:[{name:"",type:"bytes"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"x",type:"bytes32"},{name:"y",type:"bytes32"}],name:"setPubkey",outputs:[],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"content",outputs:[{name:"ret",type:"bytes32"}],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"addr",outputs:[{name:"ret",type:"address"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"contentType",type:"uint256"},{name:"data",type:"bytes"}],name:"setABI",outputs:[],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"name",outputs:[{name:"ret",type:"string"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"name",type:"string"}],name:"setName",outputs:[],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"hash",type:"bytes32"}],name:"setContent",outputs:[],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"pubkey",outputs:[{name:"x",type:"bytes32"},{name:"y",type:"bytes32"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"addr",type:"address"}],name:"setAddr",outputs:[],payable:!1,type:"function"},{inputs:[{name:"ensAddr",type:"address"}],payable:!1,type:"constructor"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"a",type:"address"}],name:"AddrChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"hash",type:"bytes32"}],name:"ContentChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"name",type:"string"}],name:"NameChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!0,name:"contentType",type:"uint256"}],name:"ABIChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"x",type:"bytes32"},{indexed:!1,name:"y",type:"bytes32"}],name:"PubkeyChanged",type:"event"}]},{}],367:[function(e,t,r){arguments[4][154][0].apply(r,arguments)},{dup:154}],368:[function(e,t,r){"use strict";var n=e("web3-utils"),i=e("bn.js"),o=function(e){var t="A".charCodeAt(0),r="Z".charCodeAt(0);return(e=(e=e.toUpperCase()).substr(4)+e.substr(0,4)).split("").map(function(e){var n=e.charCodeAt(0);return n>=t&&n<=r?n-t+10:e}).join("")},a=function(e){for(var t,r=e;r.length>2;)t=r.slice(0,9),r=parseInt(t,10)%97+r.slice(t.length);return parseInt(r,10)%97},s=function(e){this._iban=e};s.toAddress=function(e){if(!(e=new s(e)).isDirect())throw new Error("IBAN is indirect and can't be converted");return e.toAddress()},s.toIban=function(e){return s.fromAddress(e).toString()},s.fromAddress=function(e){if(!n.isAddress(e))throw new Error("Provided address is not a valid address: "+e);e=e.replace("0x","").replace("0X","");var t=function(e,t){for(var r=e;r.length<2*t;)r="0"+r;return r}(new i(e,16).toString(36),15);return s.fromBban(t.toUpperCase())},s.fromBban=function(e){var t=("0"+(98-a(o("XE00"+e)))).slice(-2);return new s("XE"+t+e)},s.createIndirect=function(e){return s.fromBban("ETH"+e.institution+e.identifier)},s.isValid=function(e){return new s(e).isValid()},s.prototype.isValid=function(){return/^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$/.test(this._iban)&&1===a(o(this._iban))},s.prototype.isDirect=function(){return 34===this._iban.length||35===this._iban.length},s.prototype.isIndirect=function(){return 20===this._iban.length},s.prototype.checksum=function(){return this._iban.substr(2,2)},s.prototype.institution=function(){return this.isIndirect()?this._iban.substr(7,4):""},s.prototype.client=function(){return this.isIndirect()?this._iban.substr(11):""},s.prototype.toAddress=function(){if(this.isDirect()){var e=this._iban.substr(4),t=new i(e,36);return n.toChecksumAddress(t.toString(16,20))}return""},s.prototype.toString=function(){return this._iban},t.exports=s},{"bn.js":367,"web3-utils":403}],369:[function(e,t,r){"use strict";var n=e("web3-core"),i=e("web3-core-method"),o=e("web3-utils"),a=e("web3-net"),s=e("web3-core-helpers").formatters,u=function(){var e=this;n.packageInit(this,arguments),this.net=new a(this.currentProvider);var t=null,r="latest";Object.defineProperty(this,"defaultAccount",{get:function(){return t},set:function(e){return e&&(t=o.toChecksumAddress(s.inputAddressFormatter(e))),u.forEach(function(e){e.defaultAccount=t}),e},enumerable:!0}),Object.defineProperty(this,"defaultBlock",{get:function(){return r},set:function(e){return r=e,u.forEach(function(e){e.defaultBlock=r}),e},enumerable:!0});var u=[new i({name:"getAccounts",call:"personal_listAccounts",params:0,outputFormatter:o.toChecksumAddress}),new i({name:"newAccount",call:"personal_newAccount",params:1,inputFormatter:[null],outputFormatter:o.toChecksumAddress}),new i({name:"unlockAccount",call:"personal_unlockAccount",params:3,inputFormatter:[s.inputAddressFormatter,null,null]}),new i({name:"lockAccount",call:"personal_lockAccount",params:1,inputFormatter:[s.inputAddressFormatter]}),new i({name:"importRawKey",call:"personal_importRawKey",params:2}),new i({name:"sendTransaction",call:"personal_sendTransaction",params:2,inputFormatter:[s.inputTransactionFormatter,null]}),new i({name:"signTransaction",call:"personal_signTransaction",params:2,inputFormatter:[s.inputTransactionFormatter,null]}),new i({name:"sign",call:"personal_sign",params:3,inputFormatter:[s.inputSignFormatter,s.inputAddressFormatter,null]}),new i({name:"ecRecover",call:"personal_ecRecover",params:2,inputFormatter:[s.inputSignFormatter,null]})];u.forEach(function(t){t.attachToObject(e),t.setRequestManager(e._requestManager),t.defaultBlock=e.defaultBlock,t.defaultAccount=e.defaultAccount})};n.addProviders(u),t.exports=u},{"web3-core":348,"web3-core-helpers":338,"web3-core-method":339,"web3-net":372,"web3-utils":403}],370:[function(e,t,r){"use strict";var n=e("underscore");t.exports=function(e){var t,r=this;return this.net.getId().then(function(e){return t=e,r.getBlock(0)}).then(function(r){var i="private";return"0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3"===r.hash&&1===t&&(i="main"),"0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303"===r.hash&&2===t&&(i="morden"),"0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d"===r.hash&&3===t&&(i="ropsten"),"0x6341fd3daf94b748c72ced5a5b26028f2474f5f00d824504e4fa37a75767e177"===r.hash&&4===t&&(i="rinkeby"),"0xa3c565fc15c7478862d50ccd6561e3c06b24cc509bf388941c25ea985ce32cb9"===r.hash&&42===t&&(i="kovan"),n.isFunction(e)&&e(null,i),i}).catch(function(t){if(!n.isFunction(e))throw t;e(t)})}},{underscore:325}],371:[function(e,t,r){"use strict";var n=e("underscore"),i=e("web3-core"),o=e("web3-core-helpers"),a=e("web3-core-subscriptions").subscriptions,s=e("web3-core-method"),u=e("web3-utils"),c=e("web3-net"),f=e("web3-eth-ens"),h=e("web3-eth-personal"),l=e("web3-eth-contract"),d=e("web3-eth-iban"),p=e("web3-eth-accounts"),b=e("web3-eth-abi"),y=e("./getNetworkType.js"),m=o.formatters,v=function(e){return n.isString(e[0])&&0===e[0].indexOf("0x")?"eth_getBlockByHash":"eth_getBlockByNumber"},g=function(e){return n.isString(e[0])&&0===e[0].indexOf("0x")?"eth_getTransactionByBlockHashAndIndex":"eth_getTransactionByBlockNumberAndIndex"},w=function(e){return n.isString(e[0])&&0===e[0].indexOf("0x")?"eth_getUncleByBlockHashAndIndex":"eth_getUncleByBlockNumberAndIndex"},_=function(e){return n.isString(e[0])&&0===e[0].indexOf("0x")?"eth_getBlockTransactionCountByHash":"eth_getBlockTransactionCountByNumber"},A=function(e){return n.isString(e[0])&&0===e[0].indexOf("0x")?"eth_getUncleCountByBlockHash":"eth_getUncleCountByBlockNumber"},E=function(){var e=this;i.packageInit(this,arguments);var t=this.setProvider;this.setProvider=function(){t.apply(e,arguments),e.net.setProvider.apply(e,arguments),e.personal.setProvider.apply(e,arguments),e.accounts.setProvider.apply(e,arguments),e.Contract.setProvider(e.currentProvider,e.accounts)};var r=null,o="latest";Object.defineProperty(this,"defaultAccount",{get:function(){return r},set:function(t){return t&&(r=u.toChecksumAddress(m.inputAddressFormatter(t))),e.Contract.defaultAccount=r,e.personal.defaultAccount=r,k.forEach(function(e){e.defaultAccount=r}),t},enumerable:!0}),Object.defineProperty(this,"defaultBlock",{get:function(){return o},set:function(t){return o=t,e.Contract.defaultBlock=o,e.personal.defaultBlock=o,k.forEach(function(e){e.defaultBlock=o}),t},enumerable:!0}),this.clearSubscriptions=e._requestManager.clearSubscriptions,this.net=new c(this.currentProvider),this.net.getNetworkType=y.bind(this),this.accounts=new p(this.currentProvider),this.personal=new h(this.currentProvider),this.personal.defaultAccount=this.defaultAccount;var E=this,x=function(){l.apply(this,arguments);var e=this,t=E.setProvider;E.setProvider=function(){t.apply(E,arguments),i.packageInit(e,[E.currentProvider])}};x.setProvider=function(){l.setProvider.apply(this,arguments)},(x.prototype=Object.create(l.prototype)).constructor=x,this.Contract=x,this.Contract.defaultAccount=this.defaultAccount,this.Contract.defaultBlock=this.defaultBlock,this.Contract.setProvider(this.currentProvider,this.accounts),this.Iban=d,this.abi=b,this.ens=new f(this);var k=[new s({name:"getNodeInfo",call:"web3_clientVersion"}),new s({name:"getProtocolVersion",call:"eth_protocolVersion",params:0}),new s({name:"getCoinbase",call:"eth_coinbase",params:0}),new s({name:"isMining",call:"eth_mining",params:0}),new s({name:"getHashrate",call:"eth_hashrate",params:0,outputFormatter:u.hexToNumber}),new s({name:"isSyncing",call:"eth_syncing",params:0,outputFormatter:m.outputSyncingFormatter}),new s({name:"getGasPrice",call:"eth_gasPrice",params:0,outputFormatter:m.outputBigNumberFormatter}),new s({name:"getAccounts",call:"eth_accounts",params:0,outputFormatter:u.toChecksumAddress}),new s({name:"getBlockNumber",call:"eth_blockNumber",params:0,outputFormatter:u.hexToNumber}),new s({name:"getBalance",call:"eth_getBalance",params:2,inputFormatter:[m.inputAddressFormatter,m.inputDefaultBlockNumberFormatter],outputFormatter:m.outputBigNumberFormatter}),new s({name:"getStorageAt",call:"eth_getStorageAt",params:3,inputFormatter:[m.inputAddressFormatter,u.numberToHex,m.inputDefaultBlockNumberFormatter]}),new s({name:"getCode",call:"eth_getCode",params:2,inputFormatter:[m.inputAddressFormatter,m.inputDefaultBlockNumberFormatter]}),new s({name:"getBlock",call:v,params:2,inputFormatter:[m.inputBlockNumberFormatter,function(e){return!!e}],outputFormatter:m.outputBlockFormatter}),new s({name:"getUncle",call:w,params:2,inputFormatter:[m.inputBlockNumberFormatter,u.numberToHex],outputFormatter:m.outputBlockFormatter}),new s({name:"getBlockTransactionCount",call:_,params:1,inputFormatter:[m.inputBlockNumberFormatter],outputFormatter:u.hexToNumber}),new s({name:"getBlockUncleCount",call:A,params:1,inputFormatter:[m.inputBlockNumberFormatter],outputFormatter:u.hexToNumber}),new s({name:"getTransaction",call:"eth_getTransactionByHash",params:1,inputFormatter:[null],outputFormatter:m.outputTransactionFormatter}),new s({name:"getTransactionFromBlock",call:g,params:2,inputFormatter:[m.inputBlockNumberFormatter,u.numberToHex],outputFormatter:m.outputTransactionFormatter}),new s({name:"getTransactionReceipt",call:"eth_getTransactionReceipt",params:1,inputFormatter:[null],outputFormatter:m.outputTransactionReceiptFormatter}),new s({name:"getTransactionCount",call:"eth_getTransactionCount",params:2,inputFormatter:[m.inputAddressFormatter,m.inputDefaultBlockNumberFormatter],outputFormatter:u.hexToNumber}),new s({name:"sendSignedTransaction",call:"eth_sendRawTransaction",params:1,inputFormatter:[null]}),new s({name:"signTransaction",call:"eth_signTransaction",params:1,inputFormatter:[m.inputTransactionFormatter]}),new s({name:"sendTransaction",call:"eth_sendTransaction",params:1,inputFormatter:[m.inputTransactionFormatter]}),new s({name:"sign",call:"eth_sign",params:2,inputFormatter:[m.inputSignFormatter,m.inputAddressFormatter],transformPayload:function(e){return e.params.reverse(),e}}),new s({name:"call",call:"eth_call",params:2,inputFormatter:[m.inputCallFormatter,m.inputDefaultBlockNumberFormatter]}),new s({name:"estimateGas",call:"eth_estimateGas",params:1,inputFormatter:[m.inputCallFormatter],outputFormatter:u.hexToNumber}),new s({name:"submitWork",call:"eth_submitWork",params:3}),new s({name:"getWork",call:"eth_getWork",params:0}),new s({name:"getPastLogs",call:"eth_getLogs",params:1,inputFormatter:[m.inputLogFormatter],outputFormatter:m.outputLogFormatter}),new a({name:"subscribe",type:"eth",subscriptions:{newBlockHeaders:{subscriptionName:"newHeads",params:0,outputFormatter:m.outputBlockFormatter},pendingTransactions:{subscriptionName:"newPendingTransactions",params:0},logs:{params:1,inputFormatter:[m.inputLogFormatter],outputFormatter:m.outputLogFormatter,subscriptionHandler:function(e){e.removed?this.emit("changed",e):this.emit("data",e),n.isFunction(this.callback)&&this.callback(null,e,this)}},syncing:{params:0,outputFormatter:m.outputSyncingFormatter,subscriptionHandler:function(e){var t=this;!0!==this._isSyncing?(this._isSyncing=!0,this.emit("changed",t._isSyncing),n.isFunction(this.callback)&&this.callback(null,t._isSyncing,this),setTimeout(function(){t.emit("data",e),n.isFunction(t.callback)&&t.callback(null,e,t)},0)):(this.emit("data",e),n.isFunction(t.callback)&&this.callback(null,e,this),clearTimeout(this._isSyncingTimeout),this._isSyncingTimeout=setTimeout(function(){e.currentBlock>e.highestBlock-200&&(t._isSyncing=!1,t.emit("changed",t._isSyncing),n.isFunction(t.callback)&&t.callback(null,t._isSyncing,t))},500))}}}})];k.forEach(function(t){t.attachToObject(e),t.setRequestManager(e._requestManager,e.accounts),t.defaultBlock=e.defaultBlock,t.defaultAccount=e.defaultAccount})};i.addProviders(E),t.exports=E},{"./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(e,t,r){"use strict";var n=e("web3-core"),i=e("web3-core-method"),o=e("web3-utils"),a=function(){var e=this;n.packageInit(this,arguments),[new i({name:"getId",call:"net_version",params:0,outputFormatter:o.hexToNumber}),new i({name:"isListening",call:"net_listening",params:0}),new i({name:"getPeerCount",call:"net_peerCount",params:0,outputFormatter:o.hexToNumber})].forEach(function(t){t.attachToObject(e),t.setRequestManager(e._requestManager)})};n.addProviders(a),t.exports=a},{"web3-core":348,"web3-core-method":339,"web3-utils":403}],373:[function(e,t,r){const n=e("events").EventEmitter,i=e("util").inherits,o=e("ethereumjs-util"),a=e("eth-block-tracker"),s=e("async/map"),u=e("async/eachSeries"),c=e("./util/stoplight.js");e("./util/rpc-cache-utils.js"),e("./util/create-payload.js");function f(e){const t=this;n.call(t),t.setMaxListeners(30),e=e||{};const r={sendAsync:t._handleAsync.bind(t)},i=e.blockTrackerProvider||r;t._blockTracker=e.blockTracker||new a({provider:i,pollingInterval:e.pollingInterval||4e3}),t._blockTracker.on("block",e=>{const r=function(e){return{number:o.toBuffer(e.number),hash:o.toBuffer(e.hash),parentHash:o.toBuffer(e.parentHash),nonce:o.toBuffer(e.nonce),mixHash:o.toBuffer(e.mixHash),sha3Uncles:o.toBuffer(e.sha3Uncles),logsBloom:o.toBuffer(e.logsBloom),transactionsRoot:o.toBuffer(e.transactionsRoot),stateRoot:o.toBuffer(e.stateRoot),receiptsRoot:o.toBuffer(e.receiptRoot||e.receiptsRoot),miner:o.toBuffer(e.miner),difficulty:o.toBuffer(e.difficulty),totalDifficulty:o.toBuffer(e.totalDifficulty),size:o.toBuffer(e.size),extraData:o.toBuffer(e.extraData),gasLimit:o.toBuffer(e.gasLimit),gasUsed:o.toBuffer(e.gasUsed),timestamp:o.toBuffer(e.timestamp),transactions:e.transactions}}(e);t._setCurrentBlock(r)}),t._blockTracker.on("block",t.emit.bind(t,"rawBlock")),t._blockTracker.on("sync",t.emit.bind(t,"sync")),t._blockTracker.on("latest",t.emit.bind(t,"latest")),t._ready=new c,t._blockTracker.once("block",()=>{t._ready.go()}),t.currentBlock=null,t._providers=[]}t.exports=f,i(f,n),f.prototype.start=function(e=function(){}){this._blockTracker.start().then(e).catch(e)},f.prototype.stop=function(){this._blockTracker.stop()},f.prototype.addProvider=function(e){this._providers.push(e),e.setEngine(this)},f.prototype.send=function(e){throw new Error("Web3ProviderEngine does not support synchronous requests.")},f.prototype.sendAsync=function(e,t){const r=this;r._ready.await(function(){Array.isArray(e)?s(e,r._handleAsync.bind(r),t):r._handleAsync(e,t)})},f.prototype._handleAsync=function(e,t){var r=this,n=-1,i=null,o=null,a=[];function s(r,n){o=r,i=n,u(a,function(e,t){e?e(o,i,t):t()},function(){var r={id:e.id,jsonrpc:e.jsonrpc,result:i};null!=o?(r.error={message:o.stack||o.message||o,code:-32e3},t(o,r)):t(null,r)})}!function t(i){n+=1;a.unshift(i);if(n>=r._providers.length)s(new Error('Request for method "'+e.method+'" not handled by any subprovider. Please check your subprovider configuration to ensure this method is handled.'));else try{var o=r._providers[n];o.handleRequest(e,t,s)}catch(e){s(e)}}()},f.prototype._setCurrentBlock=function(e){this.currentBlock=e,this.emit("block",e)}},{"./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(e,t,r){var n="undefined"!=typeof JSON?JSON:e("jsonify");t.exports=function(e,t){t||(t={}),"function"==typeof t&&(t={cmp:t});var r=t.space||"";"number"==typeof r&&(r=Array(r+1).join(" "));var a,s="boolean"==typeof t.cycles&&t.cycles,u=t.replacer||function(e,t){return t},c=t.cmp&&(a=t.cmp,function(e){return function(t,r){var n={key:t,value:e[t]},i={key:r,value:e[r]};return a(n,i)}}),f=[];return function e(t,a,h,l){var d=r?"\n"+new Array(l+1).join(r):"",p=r?": ":":";if(h&&h.toJSON&&"function"==typeof h.toJSON&&(h=h.toJSON()),void 0!==(h=u.call(t,a,h))){if("object"!=typeof h||null===h)return n.stringify(h);if(i(h)){for(var b=[],y=0;y dist/ProviderEngine.js","bundle-zero":"browserify -s ZeroClientProvider -e zero.js -t [ babelify --presets [ es2015 ] ] > dist/ZeroClientProvider.js",prepublish:"npm run build && npm run bundle",test:"node test/index.js"},version:"14.1.0"}},{}],376:[function(e,t,r){const n=e("util").inherits,i=e("ethereumjs-util"),o=i.BN,a=e("clone"),s=e("../util/rpc-cache-utils.js"),u=e("../util/stoplight.js"),c=e("./subprovider.js");function f(e){e=e||{},this._ready=new u,this.strategies={perma:new l({eth_getTransactionByHash:p,eth_getTransactionReceipt:p}),block:new d(this),fork:new d(this)}}function h(){var e=this;e.cache={};var t=setInterval(function(){e.cache={}},6e5);t.unref&&t.unref()}function l(e){this.strategy=new h,this.conditionals=e}function d(){this.cache={}}function p(e){if(!e)return!1;if(!e.blockHash)return!1;var t;return(t=e.blockHash,new o(i.toBuffer(t))).gt(new o(0))}t.exports=f,n(f,c),f.prototype.setEngine=function(e){const t=this;function r(e){var r=t.currentBlock;t.currentBlock=e,r&&(t.strategies.block.cacheRollOff(r),t.strategies.fork.cacheRollOff(r))}t.engine=e,e.once("block",function(n){t.currentBlock=n,t._ready.go(),e.on("block",r)})},f.prototype.handleRequest=function(e,t,r){const n=this;return e.skipCache?t():"eth_getBlockByNumber"===e.method&&"latest"===e.params[0]?t():void n._ready.await(function(){n._handleRequest(e,t,r)})},f.prototype._handleRequest=function(e,t,r){const n=this;var o=s.cacheTypeForPayload(e),a=this.strategies[o];if(!a)return t();if(!a.canCache(e))return t();var u,c=s.blockTagForPayload(e);c||(c="latest"),u="earliest"===c?"0x00":"latest"===c?i.bufferToHex(n.currentBlock.number):c,a.hitCheck(e,u,r,function(){t(function(t,r,n){if(t)return n();a.cacheResult(e,r,u,n)})})},h.prototype.hitCheck=function(e,t,r,n){var i,o,u,c,f=s.cacheIdentifierForPayload(e),h=this.cache[f];return h&&(i=t,o=h.blockNumber,u=parseInt(i,16),c=parseInt(o,16),(u===c?0:u>c?1:-1)>=0)?r(null,a(h.result)):n()},h.prototype.cacheResult=function(e,t,r,n){var i=s.cacheIdentifierForPayload(e);if(t){var o=a(t);this.cache[i]={blockNumber:r,result:o}}n()},h.prototype.canCache=function(e){return s.canCache(e)},l.prototype.hitCheck=function(e,t,r,n){return this.strategy.hitCheck(e,t,r,n)},l.prototype.cacheResult=function(e,t,r,n){var i=this.conditionals[e.method];i?i(t)?this.strategy.cacheResult(e,t,r,n):n():this.strategy.cacheResult(e,t,r,n)},l.prototype.canCache=function(e){return this.strategy.canCache(e)},d.prototype.getBlockCacheForPayload=function(e,t){const r=Number.parseInt(t,16);let n=this.cache[r];if(!n){const e={};this.cache[r]=e,n=e}return n},d.prototype.hitCheck=function(e,t,r,n){var i=this.getBlockCacheForPayload(e,t);if(!i)return n();var o=i[s.cacheIdentifierForPayload(e)];return o?r(null,o):n()},d.prototype.cacheResult=function(e,t,r,n){t&&(this.getBlockCacheForPayload(e,r)[s.cacheIdentifierForPayload(e)]=t);n()},d.prototype.canCache=function(e){return!!s.canCache(e)&&"pending"!==s.blockTagForPayload(e)},d.prototype.cacheRollOff=function(e){const t=this,r=i.bufferToHex(e.number),n=Number.parseInt(r,16);Object.keys(t.cache).map(Number).filter(e=>e<=n).forEach(e=>delete t.cache[e])}},{"../util/rpc-cache-utils.js":394,"../util/stoplight.js":396,"./subprovider.js":387,clone:87,"ethereumjs-util":141,util:333}],377:[function(e,t,r){const n=e("util").inherits,i=e("xtend"),o=e("./fixture.js"),a=e("../package.json").version;function s(e){var t=i({web3_clientVersion:"ProviderEngine/v"+a+"/javascript",net_listening:!0,eth_hashrate:"0x00",eth_mining:!1},e=e||{});o.call(this,t)}t.exports=s,n(s,o)},{"../package.json":375,"./fixture.js":380,util:333,xtend:423}],378:[function(e,t,r){const n=e("cross-fetch"),i=e("util").inherits,o=e("async/retry"),a=e("async/waterfall"),s=e("async/asyncify"),u=e("json-rpc-error"),c=e("promise-to-callback"),f=e("../util/create-payload.js"),h=e("./subprovider.js"),l=["Gateway timeout","ETIMEDOUT","SyntaxError"];function d(e){this.rpcUrl=e.rpcUrl,this.originHttpHeaderKey=e.originHttpHeaderKey}function p(e){const t=e.toString();return l.some(e=>t.includes(e))}t.exports=d,i(d,h),d.prototype.handleRequest=function(e,t,r){const n=this,i=e.origin,a=f(e);delete a.origin;const s={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(a)};n.originHttpHeaderKey&&i&&(s.headers[n.originHttpHeaderKey]=i),o({times:5,interval:1e3,errorFilter:p},e=>n._submitRequest(s,e),(e,t)=>{if(e&&p(e)){const t=`FetchSubprovider - cannot complete request. All retries exhausted.\nOriginal Error:\n${e.toString()}\n\n`,n=new Error(t);return r(n)}return r(e,t)})},d.prototype._submitRequest=function(e,t){const r=this.rpcUrl;c(n(r,e))((e,r)=>{if(e)return t(e);a([function(e){switch(r.status){case 405:return e(new u.MethodNotFound);case 418:return e(function(){const e=new Error("Request is being rate limited.");return new u.InternalError(e)}());case 503:case 504:return e(function(){let e="Gateway timeout. The request took too long to process. ";const t=new Error(e+="This can happen when querying logs over too wide a block range.");return new u.InternalError(t)}());default:return e()}},e=>c(r.text())(e),s(e=>JSON.parse(e)),function(e,t){if(200!==r.status)return t(new u.InternalError(e));if(e.error)return t(new u.InternalError(e.error));t(null,e.result)}],t)})}},{"../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(e,t,r){const n=e("async"),i=e("util").inherits,o=e("ethereumjs-util"),a=e("./subprovider.js"),s=e("../util/stoplight.js"),u=e("events").EventEmitter;function c(e){e=e||{};const t=this;t.filterIndex=0,t.filters={},t.filterDestroyHandlers={},t.asyncBlockHandlers={},t.asyncPendingBlockHandlers={},t._ready=new s,t._ready.setMaxListeners(e.maxFilters||25),t._ready.go(),t.pendingBlockTimeout=e.pendingBlockTimeout||4e3,t.checkForPendingBlocksActive=!1,setTimeout(function(){t.engine.on("block",function(e){t._ready.stop();var r=v(t.asyncBlockHandlers).map(function(t){return t.bind(null,e)});n.parallel(r,function(e){e&&console.error(e),t._ready.go()})})})}function f(e){u.apply(this),this.type="block",this.engine=e.engine,this.blockNumber=e.blockNumber,this.updates=[]}function h(e){u.apply(this),this.type="log",this.fromBlock=void 0!==e.fromBlock?e.fromBlock:"latest",this.toBlock=void 0!==e.toBlock?e.toBlock:"latest";var t=e.address&&(Array.isArray(e.address)?e.address:[e.address]);this.address=t&&t.map(d),this.topics=e.topics||[],this.updates=[],this.allResults=[]}function l(){u.apply(this),this.type="pendingTx",this.updates=[],this.allResults=[]}function d(e){return"0x"===e.slice(0,2)?e:"0x"+e}function p(e){return o.intToHex(e)}function b(e){return Number(e)}function y(e){return function(e){let t=o.stripHexPrefix(e);for(;"0"===t[0];)t=t.substr(1);return`0x${t}`}(e.toString("hex"))}function m(e){return e&&-1===["earliest","latest","pending"].indexOf(e)}function v(e){return Object.keys(e).map(function(t){return e[t]})}t.exports=c,i(c,a),c.prototype.handleRequest=function(e,t,r){const n=this;switch(e.method){case"eth_newBlockFilter":return void n.newBlockFilter(r);case"eth_newPendingTransactionFilter":return n.newPendingTransactionFilter(r),void n.checkForPendingBlocks();case"eth_newFilter":return void n.newLogFilter(e.params[0],r);case"eth_getFilterChanges":return void n._ready.await(function(){n.getFilterChanges(e.params[0],r)});case"eth_getFilterLogs":return void n._ready.await(function(){n.getFilterLogs(e.params[0],r)});case"eth_uninstallFilter":return void n._ready.await(function(){n.uninstallFilter(e.params[0],r)});default:return void t()}},c.prototype.newBlockFilter=function(e){const t=this;t._getBlockNumber(function(r,n){if(r)return e(r);var i=new f({blockNumber:n}),o=i.update.bind(i);t.engine.on("block",o);t.filterIndex++,t.filters[t.filterIndex]=i,t.filterDestroyHandlers[t.filterIndex]=function(){t.engine.removeListener("block",o)};var a=p(t.filterIndex);e(null,a)})},c.prototype.newLogFilter=function(e,t){const r=this;r._getBlockNumber(function(n,i){if(n)return t(n);var o=new h(e),a=o.update.bind(o);r.filterIndex++,r.asyncBlockHandlers[r.filterIndex]=function(e,t){r._logsForBlock(e,function(e,r){if(e)return t(e);a(r),t()})},r.filters[r.filterIndex]=o;var s=p(r.filterIndex);t(null,s)})},c.prototype.newPendingTransactionFilter=function(e){const t=this;var r=new l,n=r.update.bind(r);t.filterIndex++,t.asyncPendingBlockHandlers[t.filterIndex]=function(e,r){t._txHashesForBlock(e,function(e,t){if(e)return r(e);n(t),r()})},t.filters[t.filterIndex]=r,e(null,p(t.filterIndex))},c.prototype.getFilterChanges=function(e,t){var r=Number.parseInt(e,16),n=this.filters[r];if(n||console.warn("FilterSubprovider - no filter with that id:",e),!n)return t(null,[]);var i=n.getChanges();n.clearChanges(),t(null,i)},c.prototype.getFilterLogs=function(e,t){const r=this;var n=Number.parseInt(e,16),i=r.filters[n];if(i||console.warn("FilterSubprovider - no filter with that id:",e),!i)return t(null,[]);if("log"===i.type)r.emitPayload({method:"eth_getLogs",params:[{fromBlock:i.fromBlock,toBlock:i.toBlock,address:i.address,topics:i.topics}]},function(e,r){if(e)return t(e);t(null,r.result)});else{t(null,[])}},c.prototype.uninstallFilter=function(e,t){var r=Number.parseInt(e,16);if(this.filters[r]){this.filters[r].removeAllListeners();var n=this.filterDestroyHandlers[r];delete this.filters[r],delete this.asyncBlockHandlers[r],delete this.asyncPendingBlockHandlers[r],delete this.filterDestroyHandlers[r],n&&n(),t(null,!0)}else t(null,!1)},c.prototype.checkForPendingBlocks=function(){const e=this;e.checkForPendingBlocksActive||!!Object.keys(e.asyncPendingBlockHandlers).length&&(e.checkForPendingBlocksActive=!0,e.emitPayload({method:"eth_getBlockByNumber",params:["pending",!0]},function(t,r){if(t)return e.checkForPendingBlocksActive=!1,void console.error(t);e.onNewPendingBlock(r.result,function(t){t&&console.error(t),e.checkForPendingBlocksActive=!1,setTimeout(e.checkForPendingBlocks.bind(e),e.pendingBlockTimeout)})}))},c.prototype.onNewPendingBlock=function(e,t){var r=v(this.asyncPendingBlockHandlers).map(function(t){return t.bind(null,e)});n.parallel(r,t)},c.prototype._getBlockNumber=function(e){e(null,y(this.engine.currentBlock.number))},c.prototype._logsForBlock=function(e,t){var r=y(e.number);this.emitPayload({method:"eth_getLogs",params:[{fromBlock:r,toBlock:r}]},function(e,r){return e?t(e):r.error?t(r.error):void t(null,r.result)})},c.prototype._txHashesForBlock=function(e,t){var r=e.transactions;if(0===r.length)return t(null,[]);"string"==typeof r[0]?t(null,r):t(null,r.map(e=>e.hash))},i(f,u),f.prototype.update=function(e){var t="0x"+e.hash.toString("hex");this.updates.push(t),this.emit("data",e)},f.prototype.getChanges=function(){return this.updates},f.prototype.clearChanges=function(){this.updates=[]},i(h,u),h.prototype.validateLog=function(e){return!(m(this.fromBlock)&&b(this.fromBlock)>=b(e.blockNumber))&&(!(m(this.toBlock)&&b(this.toBlock)<=b(e.blockNumber))&&(!(this.address&&!this.address.map(e=>e.toLowerCase()).includes(e.address.toLowerCase()))&&this.topics.reduce(function(t,r,n){if(!t)return!1;if(!r)return!0;var i=e.topics[n];return!!i&&(Array.isArray(r)?r:[r]).filter(function(e){return i.toLowerCase()===e.toLowerCase()}).length>0},!0)))},h.prototype.update=function(e){const t=this;var r=[];e.forEach(function(e){t.validateLog(e)&&(r.push(e),t.updates.push(e),t.allResults.push(e))}),r.length>0&&t.emit("data",r)},h.prototype.getChanges=function(){return this.updates},h.prototype.getAllResults=function(){return this.allResults},h.prototype.clearChanges=function(){this.updates=[]},i(l,u),l.prototype.validateUnique=function(e){return-1===this.allResults.indexOf(e)},l.prototype.update=function(e){const t=this;var r=[];e.forEach(function(e){t.validateUnique(e)&&(r.push(e),t.updates.push(e),t.allResults.push(e))}),r.length>0&&t.emit("data",r)},l.prototype.getChanges=function(){return this.updates},l.prototype.getAllResults=function(){return this.allResults},l.prototype.clearChanges=function(){this.updates=[]}},{"../util/stoplight.js":396,"./subprovider.js":387,async:21,"ethereumjs-util":141,events:157,util:333}],380:[function(e,t,r){const n=e("util").inherits,i=e("./subprovider.js");function o(e){e=e||{},this.staticResponses=e}t.exports=o,n(o,i),o.prototype.handleRequest=function(e,t,r){var n=this.staticResponses[e.method];"function"==typeof n?n(e,t,r):void 0!==n?setTimeout(()=>r(null,n)):t()}},{"./subprovider.js":387,util:333}],381:[function(e,t,r){const n=e("async/waterfall"),i=e("async/parallel"),o=e("util").inherits,a=e("ethereumjs-util"),s=e("eth-sig-util"),u=e("xtend"),c=e("semaphore"),f=e("./subprovider.js"),h=e("../util/estimate-gas.js"),l=/^[0-9A-Fa-f]+$/g;function d(e){this.nonceLock=c(1),e.getAccounts&&(this.getAccounts=e.getAccounts),e.processTransaction&&(this.processTransaction=e.processTransaction),e.processMessage&&(this.processMessage=e.processMessage),e.processPersonalMessage&&(this.processPersonalMessage=e.processPersonalMessage),e.processTypedMessage&&(this.processTypedMessage=e.processTypedMessage),this.approveTransaction=e.approveTransaction||this.autoApprove,this.approveMessage=e.approveMessage||this.autoApprove,this.approvePersonalMessage=e.approvePersonalMessage||this.autoApprove,this.approveTypedMessage=e.approveTypedMessage||this.autoApprove,e.signTransaction&&(this.signTransaction=e.signTransaction||y("signTransaction")),e.signMessage&&(this.signMessage=e.signMessage||y("signMessage")),e.signPersonalMessage&&(this.signPersonalMessage=e.signPersonalMessage||y("signPersonalMessage")),e.signTypedMessage&&(this.signTypedMessage=e.signTypedMessage||y("signTypedMessage")),e.recoverPersonalSignature&&(this.recoverPersonalSignature=e.recoverPersonalSignature),e.publishTransaction&&(this.publishTransaction=e.publishTransaction)}function p(e){return e.toLowerCase()}function b(e){return"string"==typeof e&&("0x"===e.slice(0,2)&&e.slice(2).match(l))}function y(e){return function(t,r){r(new Error('ProviderEngine - HookedWalletSubprovider - Must provide "'+e+'" fn in constructor options'))}}t.exports=d,o(d,f),d.prototype.handleRequest=function(e,t,r){const i=this;let o,s,c,f,h;switch(i._parityRequests={},i._parityRequestCount=0,e.method){case"eth_coinbase":return void i.getAccounts(function(e,t){if(e)return r(e);let n=t[0]||null;r(null,n)});case"eth_accounts":return void i.getAccounts(function(e,t){if(e)return r(e);r(null,t)});case"eth_sendTransaction":return o=e.params[0],void n([e=>i.validateTransaction(o,e),e=>i.processTransaction(o,e)],r);case"eth_signTransaction":return o=e.params[0],void n([e=>i.validateTransaction(o,e),e=>i.processSignTransaction(o,e)],r);case"eth_sign":return h=e.params[0],f=e.params[1],c=e.params[2]||{},s=u(c,{from:h,data:f}),void n([e=>i.validateMessage(s,e),e=>i.processMessage(s,e)],r);case"personal_sign":const l=e.params[0];if(function(e){const t=a.addHexPrefix(e);return!a.isValidAddress(t)&&b(e)}(e.params[1])&&function(e){const t=a.addHexPrefix(e);return a.isValidAddress(t)}(l)){let t="The eth_personalSign method requires params ordered ";t+="[message, address]. This was previously handled incorrectly, ",t+="and has been corrected automatically. ",t+="Please switch this param order for smooth behavior in the future.",console.warn(t),h=e.params[0],f=e.params[1]}else f=e.params[0],h=e.params[1];return c=e.params[2]||{},s=u(c,{from:h,data:f}),void n([e=>i.validatePersonalMessage(s,e),e=>i.processPersonalMessage(s,e)],r);case"personal_ecRecover":f=e.params[0];let d=e.params[1];return c=e.params[2]||{},s=u(c,{sig:d,data:f}),void i.recoverPersonalSignature(s,r);case"eth_signTypedData":return f=e.params[0],h=e.params[1],c=e.params[2]||{},s=u(c,{from:h,data:f}),void n([e=>i.validateTypedMessage(s,e),e=>i.processTypedMessage(s,e)],r);case"parity_postTransaction":return o=e.params[0],void i.parityPostTransaction(o,r);case"parity_postSign":return h=e.params[0],f=e.params[1],void i.parityPostSign(h,f,r);case"parity_checkRequest":const p=e.params[0];return void i.parityCheckRequest(p,r);case"parity_defaultAccount":return void i.getAccounts(function(e,t){if(e)return r(e);const n=t[0]||null;r(null,n)});default:return void t()}},d.prototype.getAccounts=function(e){e(null,[])},d.prototype.processTransaction=function(e,t){const r=this;n([t=>r.approveTransaction(e,t),(e,t)=>r.checkApproval("transaction",e,t),t=>r.finalizeAndSubmitTx(e,t)],t)},d.prototype.processSignTransaction=function(e,t){const r=this;n([t=>r.approveTransaction(e,t),(e,t)=>r.checkApproval("transaction",e,t),t=>r.finalizeTx(e,t)],t)},d.prototype.processMessage=function(e,t){const r=this;n([t=>r.approveMessage(e,t),(e,t)=>r.checkApproval("message",e,t),t=>r.signMessage(e,t)],t)},d.prototype.processPersonalMessage=function(e,t){const r=this;n([t=>r.approvePersonalMessage(e,t),(e,t)=>r.checkApproval("message",e,t),t=>r.signPersonalMessage(e,t)],t)},d.prototype.processTypedMessage=function(e,t){const r=this;n([t=>r.approveTypedMessage(e,t),(e,t)=>r.checkApproval("message",e,t),t=>r.signTypedMessage(e,t)],t)},d.prototype.autoApprove=function(e,t){t(null,!0)},d.prototype.checkApproval=function(e,t,r){r(t?null:new Error("User denied "+e+" signature."))},d.prototype.parityPostTransaction=function(e,t){const r=this,n=`0x${r._parityRequestCount.toString(16)}`;r._parityRequestCount++,r.emitPayload({method:"eth_sendTransaction",params:[e]},function(e,t){if(e)return void(r._parityRequests[n]={error:e});const i=t.result;r._parityRequests[n]=i}),t(null,n)},d.prototype.parityPostSign=function(e,t,r){const n=this,i=`0x${n._parityRequestCount.toString(16)}`;n._parityRequestCount++,n.emitPayload({method:"eth_sign",params:[e,t]},function(e,t){if(e)return void(n._parityRequests[i]={error:e});const r=t.result;n._parityRequests[i]=r}),r(null,i)},d.prototype.parityCheckRequest=function(e,t){const r=this._parityRequests[e]||null;return r?r.error?t(r.error):void t(null,r):t(null,null)},d.prototype.recoverPersonalSignature=function(e,t){let r;try{r=s.recoverPersonalSignature(e)}catch(e){return t(e)}t(null,r)},d.prototype.validateTransaction=function(e,t){if(void 0===e.from)return t(new Error("Undefined address - from address required to sign transaction."));this.validateSender(e.from,function(r,n){return r?t(r):n?void t():t(new Error(`Unknown address - unable to sign transaction for this address: "${e.from}"`))})},d.prototype.validateMessage=function(e,t){if(void 0===e.from)return t(new Error("Undefined address - from address required to sign message."));this.validateSender(e.from,function(r,n){return r?t(r):n?void t():t(new Error(`Unknown address - unable to sign message for this address: "${e.from}"`))})},d.prototype.validatePersonalMessage=function(e,t){return void 0===e.from?t(new Error("Undefined address - from address required to sign personal message.")):void 0===e.data?t(new Error("Undefined message - message required to sign personal message.")):b(e.data)?void this.validateSender(e.from,function(r,n){return r?t(r):n?void t():t(new Error(`Unknown address - unable to sign message for this address: "${e.from}"`))}):t(new Error("HookedWalletSubprovider - validateMessage - message was not encoded as hex."))},d.prototype.validateTypedMessage=function(e,t){return void 0===e.from?t(new Error("Undefined address - from address required to sign typed data.")):void 0===e.data?t(new Error("Undefined data - message required to sign typed data.")):void this.validateSender(e.from,function(r,n){return r?t(r):n?void t():t(new Error(`Unknown address - unable to sign message for this address: "${e.from}"`))})},d.prototype.validateSender=function(e,t){if(!e)return t(null,!1);this.getAccounts(function(r,n){if(r)return t(r);const i=-1!==n.map(p).indexOf(e.toLowerCase());t(null,i)})},d.prototype.finalizeAndSubmitTx=function(e,t){const r=this;r.nonceLock.take(function(){n([r.fillInTxExtras.bind(r,e),r.signTransaction.bind(r),r.publishTransaction.bind(r)],function(e,n){if(r.nonceLock.leave(),e)return t(e);t(null,n)})})},d.prototype.finalizeTx=function(e,t){const r=this;r.nonceLock.take(function(){n([r.fillInTxExtras.bind(r,e),r.signTransaction.bind(r)],function(n,i){if(r.nonceLock.leave(),n)return t(n);t(null,{raw:i,tx:e})})})},d.prototype.publishTransaction=function(e,t){this.emitPayload({method:"eth_sendRawTransaction",params:[e]},function(e,r){if(e)return t(e);t(null,r.result)})},d.prototype.fillInTxExtras=function(e,t){const r=this,n=e.from,o={};void 0===e.gasPrice&&(o.gasPrice=r.emitPayload.bind(r,{method:"eth_gasPrice",params:[]})),void 0===e.nonce&&(o.nonce=r.emitPayload.bind(r,{method:"eth_getTransactionCount",params:[n,"pending"]})),void 0===e.gas&&(o.gas=h.bind(null,r.engine,function(e){return{from:e.from,to:e.to,value:e.value,data:e.data,gas:e.gas,gasPrice:e.gasPrice,nonce:e.nonce}}(e))),i(o,function(r,n){if(r)return t(r);const i={};n.gasPrice&&(i.gasPrice=n.gasPrice.result),n.nonce&&(i.nonce=n.nonce.result),n.gas&&(i.gas=n.gas),t(null,u(e,i))})}},{"../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(e,t,r){const n=e("../util/rpc-cache-utils.js").cacheIdentifierForPayload,i=e("./subprovider.js");t.exports=class extends i{constructor(e){super(),this.inflightRequests={}}addEngine(e){this.engine=e}handleRequest(e,t,r){const i=n(e,{includeBlockRef:!0});if(!i)return t();let o=this.inflightRequests[i];o?o.push(r):(o=[],this.inflightRequests[i]=o,t((e,t,r)=>{delete this.inflightRequests[i],o.forEach(r=>r(e,t)),r(e,t)}))}}},{"../util/rpc-cache-utils.js":394,"./subprovider.js":387}],383:[function(e,t,r){const n=e("eth-json-rpc-infura/src/createProvider"),i=e("./provider.js");t.exports=class extends i{constructor(e={}){super(n(e))}}},{"./provider.js":385,"eth-json-rpc-infura/src/createProvider":129}],384:[function(e,t,r){(function(r){const n=e("util").inherits,i=e("ethereumjs-tx"),o=e("ethereumjs-util"),a=e("./subprovider.js"),s=e("../util/rpc-cache-utils").blockTagForPayload;function u(e){this.nonceCache={}}t.exports=u,n(u,a),u.prototype.handleRequest=function(e,t,n){const a=this;switch(e.method){case"eth_getTransactionCount":var u=s(e),c=e.params[0].toLowerCase(),f=a.nonceCache[c];return void("pending"===u?f?n(null,f):t(function(e,t,r){if(e)return r();void 0===a.nonceCache[c]&&(a.nonceCache[c]=t),r()}):t());case"eth_sendRawTransaction":return void t(function(t,n,s){if(t)return s();var u=e.params[0],c=(o.stripHexPrefix(u),new r(o.stripHexPrefix(u),"hex"),new i(new r(o.stripHexPrefix(u),"hex"))),f="0x"+c.getSenderAddress().toString("hex").toLowerCase(),h=o.bufferToInt(c.nonce),l=(++h).toString(16);l.length%2&&(l="0"+l),l="0x"+l,a.nonceCache[f]=l,s()});default:return void t()}}}).call(this,e("buffer").Buffer)},{"../util/rpc-cache-utils":394,"./subprovider.js":387,buffer:84,"ethereumjs-tx":140,"ethereumjs-util":141,util:333}],385:[function(e,t,r){const n=e("util").inherits,i=e("./subprovider.js");function o(e){if(!e)throw new Error("ProviderSubprovider - no provider specified");if(!e.sendAsync)throw new Error("ProviderSubprovider - specified provider does not have a sendAsync method");this.provider=e}t.exports=o,n(o,i),o.prototype.handleRequest=function(e,t,r){this.provider.sendAsync(e,function(e,t){return e?r(e):t.error?r(new Error(t.error.message)):void r(null,t.result)})}},{"./subprovider.js":387,util:333}],386:[function(e,t,r){const n=e("util").inherits,i=e("./subprovider.js"),o=(e("xtend"),e("ethereumjs-util"));function a(e){}t.exports=a,n(a,i),a.prototype.handleRequest=function(e,t,r){var n=e.params[0];if("object"==typeof n&&!Array.isArray(n)){var i=function(e){return s.reduce(function(t,r){return r in e&&(Array.isArray(e[r])?t[r]=e[r].map(function(e){return u(e)}):t[r]=u(e[r])),t},{})}(n);e.params[0]=i}t()};var s=["from","to","value","data","gas","gasPrice","nonce","fromBlock","toBlock","address","topics"];function u(e){switch(e){case"latest":case"pending":case"earliest":return e;default:return"string"==typeof e?o.addHexPrefix(e.toLowerCase()):e}}},{"./subprovider.js":387,"ethereumjs-util":141,util:333,xtend:423}],387:[function(e,t,r){const n=e("../util/create-payload.js");function i(){}t.exports=i,i.prototype.setEngine=function(e){const t=this;t.engine=e,e.on("block",function(e){t.currentBlock=e})},i.prototype.handleRequest=function(e,t,r){throw new Error("Subproviders should override `handleRequest`.")},i.prototype.emitPayload=function(e,t){this.engine.sendAsync(n(e),t)}},{"../util/create-payload.js":391}],388:[function(e,t,r){const n=e("events").EventEmitter,i=e("./filters.js"),o=e("../util/rpc-hex-encoding.js"),a=e("util").inherits,s=e("ethereumjs-util");function u(e){e=e||{},n.apply(this,Array.prototype.slice.call(arguments)),i.apply(this,[e]),this.subscriptions={}}a(u,i),Object.assign(u.prototype,n.prototype),u.prototype.constructor=u,u.prototype.eth_subscribe=function(e,t){const r=this;let n=()=>{},i=e.params[0];switch(i){case"logs":let o=e.params[1];n=r.newLogFilter.bind(r,o);break;case"newPendingTransactions":n=r.newPendingTransactionFilter.bind(r);break;case"newHeads":n=r.newBlockFilter.bind(r);break;case"syncing":default:return void t(new Error("unsupported subscription type"))}n(function(e,n){if(e)return t(e);const o=Number.parseInt(n,16);r.subscriptions[o]=i,r.filters[o].on("data",function(e){Array.isArray(e)||(e=[e]);var t=r._notificationHandler.bind(r,n,i);e.forEach(t),r.filters[o].clearChanges()}),"newPendingTransactions"===i&&r.checkForPendingBlocks(),t(null,n)})},u.prototype.eth_unsubscribe=function(e,t){const r=this;let n=e.params[0];const i=Number.parseInt(n,16);if(r.subscriptions[i]){r.subscriptions[i];r.uninstallFilter(n,function(e,n){delete r.subscriptions[i],t(e,n)})}else t(new Error(`Subscription ID ${n} not found.`))},u.prototype._notificationHandler=function(e,t,r){const n=this;"newHeads"===t&&(r=n._notificationResultFromBlock(r)),n.emit("data",null,{jsonrpc:"2.0",method:"eth_subscription",params:{subscription:e,result:r}})},u.prototype._notificationResultFromBlock=function(e){return{hash:s.bufferToHex(e.hash),parentHash:s.bufferToHex(e.parentHash),sha3Uncles:s.bufferToHex(e.sha3Uncles),miner:s.bufferToHex(e.miner),stateRoot:s.bufferToHex(e.stateRoot),transactionsRoot:s.bufferToHex(e.transactionsRoot),receiptsRoot:s.bufferToHex(e.receiptsRoot),logsBloom:s.bufferToHex(e.logsBloom),difficulty:o.intToQuantityHex(s.bufferToInt(e.difficulty)),number:o.intToQuantityHex(s.bufferToInt(e.number)),gasLimit:o.intToQuantityHex(s.bufferToInt(e.gasLimit)),gasUsed:o.intToQuantityHex(s.bufferToInt(e.gasUsed)),nonce:e.nonce?s.bufferToHex(e.nonce):null,mixHash:s.bufferToHex(e.mixHash),timestamp:o.intToQuantityHex(s.bufferToInt(e.timestamp)),extraData:s.bufferToHex(e.extraData)}},u.prototype.handleRequest=function(e,t,r){switch(e.method){case"eth_subscribe":this.eth_subscribe(e,r);break;case"eth_unsubscribe":this.eth_unsubscribe(e,r);break;default:i.prototype.handleRequest.apply(this,Array.prototype.slice.call(arguments))}},t.exports=u},{"../util/rpc-hex-encoding.js":395,"./filters.js":379,"ethereumjs-util":141,events:157,util:333}],389:[function(e,t,r){(function(r){const n=e("backoff"),i=e("events"),o=(e("util").inherits,r.WebSocket||e("ws")),a=e("./subprovider"),s=e("../util/create-payload");class u extends a{constructor({rpcUrl:e,debug:t,origin:r}){super(),i.call(this),Object.defineProperties(this,{_backoff:{value:n.exponential({randomisationFactor:.2,maxDelay:5e3})},_connectTime:{value:null,writable:!0},_log:{value:t?(...e)=>console.info.apply(console,["[WSProvider]",...e]):()=>{}},_origin:{value:r},_pendingRequests:{value:new Map},_socket:{value:null,writable:!0},_unhandledRequests:{value:[]},_url:{value:e}}),this._handleSocketClose=this._handleSocketClose.bind(this),this._handleSocketMessage=this._handleSocketMessage.bind(this),this._handleSocketOpen=this._handleSocketOpen.bind(this),this._backoff.on("ready",()=>{this._openSocket()}),this._openSocket()}handleRequest(e,t,r){if(!this._socket||this._socket.readyState!==o.OPEN)return this._unhandledRequests.push(Array.from(arguments)),void this._log("Socket not open. Request queued.");this._pendingRequests.set(e.id,[e,r]);const n=s(e);delete n.origin,this._socket.send(JSON.stringify(n)),this._log(`Sent: ${n.method} #${n.id}`)}_handleSocketClose({reason:e,code:t}){this._log(`Socket closed, code ${t} (${e||"no reason"})`),this._connectTime&&Date.now()-this._connectTime>5e3&&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(e){let t;try{t=JSON.parse(e.data)}catch(e){return void this._log("Received a message that is not valid JSON:",t)}if(void 0===t.id)return this.emit("data",null,t);if(!this._pendingRequests.has(t.id))return;const[r,n]=this._pendingRequests.get(t.id);if(this._pendingRequests.delete(t.id),this._log(`Received: ${r.method} #${t.id}`),t.error)return n(new Error(t.error.message));n(null,t.result)}_handleSocketOpen(){this._log("Socket open."),this._connectTime=Date.now(),this._pendingRequests.forEach(([e,t])=>{this._unhandledRequests.push([e,null,t])}),this._pendingRequests.clear(),this._unhandledRequests.splice(0,this._unhandledRequests.length).forEach(e=>{this.handleRequest.apply(this,e)})}_openSocket(){this._log("Opening socket..."),this._socket=new o(this._url,null,{origin:this._origin}),this._socket.addEventListener("close",this._handleSocketClose),this._socket.addEventListener("message",this._handleSocketMessage),this._socket.addEventListener("open",this._handleSocketOpen)}}Object.assign(u.prototype,i.prototype),t.exports=u}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../util/create-payload":391,"./subprovider":387,backoff:45,events:157,util:333,ws:55}],390:[function(e,t,r){t.exports=function(e,t){if(!e)throw t||"Assertion failed"}},{}],391:[function(e,t,r){const n=e("./random-id.js"),i=e("xtend");t.exports=function(e){return i({id:n(),jsonrpc:"2.0",params:[]},e)}},{"./random-id.js":393,xtend:423}],392:[function(e,t,r){const n=e("./create-payload.js");t.exports=function(e,t,r){e.sendAsync(n({method:"eth_estimateGas",params:[t]}),function(e,t){if(e)return"no contract code at given address"===e.message?r(null,"0xcf08"):r(e);r(null,t.result)})}},{"./create-payload.js":391}],393:[function(e,t,r){const n=3;t.exports=function(){var e=(new Date).getTime()*Math.pow(10,n),t=Math.floor(Math.random()*Math.pow(10,n));return e+t}},{}],394:[function(e,t,r){const n=e("json-stable-stringify");function i(e){return"never"!==s(e)}function o(e){var t=a(e);return t>=e.params.length?e.params:"eth_getBlockByNumber"===e.method?e.params.slice(1):e.params.slice(0,t)}function a(e){switch(e.method){case"eth_getStorageAt":return 2;case"eth_getBalance":case"eth_getCode":case"eth_getTransactionCount":case"eth_call":case"eth_estimateGas":return 1;case"eth_getBlockByNumber":return 0;default:return}}function s(e){switch(e.method){case"web3_clientVersion":case"web3_sha3":case"eth_protocolVersion":case"eth_getBlockTransactionCountByHash":case"eth_getUncleCountByBlockHash":case"eth_getCode":case"eth_getBlockByHash":case"eth_getTransactionByHash":case"eth_getTransactionByBlockHashAndIndex":case"eth_getTransactionReceipt":case"eth_getUncleByBlockHashAndIndex":case"eth_getCompilers":case"eth_compileLLL":case"eth_compileSolidity":case"eth_compileSerpent":case"shh_version":return"perma";case"eth_getBlockByNumber":case"eth_getBlockTransactionCountByNumber":case"eth_getUncleCountByBlockNumber":case"eth_getTransactionByBlockNumberAndIndex":case"eth_getUncleByBlockNumberAndIndex":return"fork";case"eth_gasPrice":case"eth_blockNumber":case"eth_getBalance":case"eth_getStorageAt":case"eth_getTransactionCount":case"eth_call":case"eth_estimateGas":case"eth_getFilterLogs":case"eth_getLogs":case"net_peerCount":return"block";case"net_version":case"net_peerCount":case"net_listening":case"eth_syncing":case"eth_sign":case"eth_coinbase":case"eth_mining":case"eth_hashrate":case"eth_accounts":case"eth_sendTransaction":case"eth_sendRawTransaction":case"eth_newFilter":case"eth_newBlockFilter":case"eth_newPendingTransactionFilter":case"eth_uninstallFilter":case"eth_getFilterChanges":case"eth_getWork":case"eth_submitWork":case"eth_submitHashrate":case"db_putString":case"db_getString":case"db_putHex":case"db_getHex":case"shh_post":case"shh_newIdentity":case"shh_hasIdentity":case"shh_newGroup":case"shh_addToGroup":case"shh_newFilter":case"shh_uninstallFilter":case"shh_getFilterChanges":case"shh_getMessages":return"never"}}t.exports={cacheIdentifierForPayload:function(e,t={}){if(!i(e))return null;const{includeBlockRef:r}=t,a=r?e.params:o(e);return e.method+":"+n(a)},canCache:i,blockTagForPayload:function(e){var t=a(e);if(t>=e.params.length)return null;return e.params[t]},paramsWithoutBlockTag:o,blockTagParamIndex:a,cacheTypeForPayload:s}},{"json-stable-stringify":374}],395:[function(e,t,r){(function(r){const n=e("ethereumjs-util"),i=e("./assert.js");t.exports={intToQuantityHex:function(e){i("number"==typeof e&&e===Math.floor(e),"intToQuantityHex arg must be an integer");var t=n.toBuffer(e).toString("hex");"0"===t[0]&&(t=t.substring(1));return n.addHexPrefix(t)},quantityHexToInt:function(e){i("string"==typeof e,"arg to quantityHexToInt must be a string");var t=n.stripHexPrefix(e);t.length%2!=0&&(t="0"+t);var o=new r(t,"hex");return n.bufferToInt(o)}}}).call(this,e("buffer").Buffer)},{"./assert.js":390,buffer:84,"ethereumjs-util":141}],396:[function(e,t,r){const n=e("events").EventEmitter,i=e("util").inherits;function o(){n.call(this),this.isLocked=!0}t.exports=o,i(o,n),o.prototype.go=function(){this.isLocked=!1,this.emit("unlock")},o.prototype.stop=function(){this.isLocked=!0,this.emit("lock")},o.prototype.await=function(e){const t=this;t.isLocked?t.once("unlock",e):setTimeout(e)}},{events:157,util:333}],397:[function(e,t,r){const n=e("./index.js"),i=e("./subproviders/default-fixture.js"),o=e("./subproviders/nonce-tracker.js"),a=e("./subproviders/cache.js"),s=e("./subproviders/filters.js"),u=e("./subproviders/subscriptions"),c=e("./subproviders/inflight-cache"),f=e("./subproviders/hooked-wallet.js"),h=e("./subproviders/sanitizer.js"),l=e("./subproviders/infura.js"),d=e("./subproviders/fetch.js"),p=e("./subproviders/websocket.js");t.exports=function(e={}){const t=function({rpcUrl:e}){if(!e)return;switch(e.split(":")[0].toLowerCase()){case"http":case"https":return"http";case"ws":case"wss":return"ws";default:throw new Error(`ProviderEngine - unrecognized protocol in "${e}"`)}}(e),r=new n(e.engineParams),b=new i(e.static);r.addProvider(b),r.addProvider(new o);const y=new h;r.addProvider(y);const m=new a;if(r.addProvider(m),"ws"===t){const e=new s;r.addProvider(e)}else{const e=new u;e.on("data",(e,t)=>{r.emit("data",e,t)}),r.addProvider(e)}const v=new c;r.addProvider(v);const g=new f({getAccounts:e.getAccounts,processTransaction:e.processTransaction,approveTransaction:e.approveTransaction,signTransaction:e.signTransaction,publishTransaction:e.publishTransaction,processMessage:e.processMessage,approveMessage:e.approveMessage,signMessage:e.signMessage,processPersonalMessage:e.processPersonalMessage,processTypedMessage:e.processTypedMessage,approvePersonalMessage:e.approvePersonalMessage,approveTypedMessage:e.approveTypedMessage,signPersonalMessage:e.signPersonalMessage,signTypedMessage:e.signTypedMessage,personalRecoverSigner:e.personalRecoverSigner});r.addProvider(g);const w=e.dataSubprovider||function(e,t){const{rpcUrl:r,debug:n}=t;if(!e)return new l;if("http"===e)return new d({rpcUrl:r,debug:n});if("ws"===e)return new p({rpcUrl:r,debug:n});throw new Error(`ProviderEngine - unrecognized connectionType "${e}"`)}(t,e);"ws"===t&&w.on("data",(e,t)=>{r.emit("data",e,t)});r.addProvider(w),e.stopped||r.start();return r}},{"./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(e,t,r){var n=e("web3-core-helpers").errors,i=e("xhr2-cookies").XMLHttpRequest,o=e("http"),a=e("https"),s=function(e,t){t=t||{},this.host=e||"http://localhost:8545","https"===this.host.substring(0,5)?this.httpsAgent=new a.Agent({keepAlive:!0}):this.httpAgent=new o.Agent({keepAlive:!0}),this.timeout=t.timeout||0,this.headers=t.headers,this.connected=!1};s.prototype._prepareRequest=function(){var e=new i;return e.nodejsSet({httpsAgent:this.httpsAgent,httpAgent:this.httpAgent}),e.open("POST",this.host,!0),e.setRequestHeader("Content-Type","application/json"),e.timeout=this.timeout&&1!==this.timeout?this.timeout:0,e.withCredentials=!0,this.headers&&this.headers.forEach(function(t){e.setRequestHeader(t.name,t.value)}),e},s.prototype.send=function(e,t){var r=this,i=this._prepareRequest();i.onreadystatechange=function(){if(4===i.readyState&&1!==i.timeout){var e=i.responseText,o=null;try{e=JSON.parse(e)}catch(e){o=n.InvalidResponse(i.responseText)}r.connected=!0,t(o,e)}},i.ontimeout=function(){r.connected=!1,t(n.ConnectionTimeout(this.timeout))};try{i.send(JSON.stringify(e))}catch(e){this.connected=!1,t(n.InvalidConnection(this.host))}},s.prototype.disconnect=function(){},t.exports=s},{http:312,https:175,"web3-core-helpers":338,"xhr2-cookies":418}],399:[function(e,t,r){"use strict";var n=e("underscore"),i=e("web3-core-helpers").errors,o=e("oboe"),a=function(e,t){var r=this;this.responseCallbacks={},this.notificationCallbacks=[],this.path=e,this.connected=!1,this.connection=t.connect({path:this.path}),this.addDefaultEvents();var i=function(e){var t=null;n.isArray(e)?e.forEach(function(e){r.responseCallbacks[e.id]&&(t=e.id)}):t=e.id,t||-1===e.method.indexOf("_subscription")?r.responseCallbacks[t]&&(r.responseCallbacks[t](null,e),delete r.responseCallbacks[t]):r.notificationCallbacks.forEach(function(t){n.isFunction(t)&&t(e)})};"Socket"===t.constructor.name?o(this.connection).done(i):this.connection.on("data",function(e){r._parseResponse(e.toString()).forEach(i)})};a.prototype.addDefaultEvents=function(){var e=this;this.connection.on("connect",function(){e.connected=!0}),this.connection.on("close",function(){e.connected=!1}),this.connection.on("error",function(){e._timeout()}),this.connection.on("end",function(){e._timeout()}),this.connection.on("timeout",function(){e._timeout()})},a.prototype._parseResponse=function(e){var t=this,r=[];return e.replace(/\}[\n\r]?\{/g,"}|--|{").replace(/\}\][\n\r]?\[\{/g,"}]|--|[{").replace(/\}[\n\r]?\[\{/g,"}|--|[{").replace(/\}\][\n\r]?\{/g,"}]|--|{").split("|--|").forEach(function(e){t.lastChunk&&(e=t.lastChunk+e);var n=null;try{n=JSON.parse(e)}catch(r){return t.lastChunk=e,clearTimeout(t.lastChunkTimeout),void(t.lastChunkTimeout=setTimeout(function(){throw t._timeout(),i.InvalidResponse(e)},15e3))}clearTimeout(t.lastChunkTimeout),t.lastChunk=null,n&&r.push(n)}),r},a.prototype._addResponseCallback=function(e,t){var r=e.id||e[0].id,n=e.method||e[0].method;this.responseCallbacks[r]=t,this.responseCallbacks[r].method=n},a.prototype._timeout=function(){for(var e in this.responseCallbacks)this.responseCallbacks.hasOwnProperty(e)&&(this.responseCallbacks[e](i.InvalidConnection("on IPC")),delete this.responseCallbacks[e])},a.prototype.reconnect=function(){this.connection.connect({path:this.path})},a.prototype.send=function(e,t){this.connection.writable||this.connection.connect({path:this.path}),this.connection.write(JSON.stringify(e)),this._addResponseCallback(e,t)},a.prototype.on=function(e,t){if("function"!=typeof t)throw new Error("The second parameter callback must be a function.");switch(e){case"data":this.notificationCallbacks.push(t);break;default:this.connection.on(e,t)}},a.prototype.once=function(e,t){if("function"!=typeof t)throw new Error("The second parameter callback must be a function.");this.connection.once(e,t)},a.prototype.removeListener=function(e,t){var r=this;switch(e){case"data":this.notificationCallbacks.forEach(function(e,n){e===t&&r.notificationCallbacks.splice(n,1)});break;default:this.connection.removeListener(e,t)}},a.prototype.removeAllListeners=function(e){switch(e){case"data":this.notificationCallbacks=[];break;default:this.connection.removeAllListeners(e)}},a.prototype.reset=function(){this._timeout(),this.notificationCallbacks=[],this.connection.removeAllListeners("error"),this.connection.removeAllListeners("end"),this.connection.removeAllListeners("timeout"),this.addDefaultEvents()},t.exports=a},{oboe:239,underscore:325,"web3-core-helpers":338}],400:[function(e,t,r){(function(r){"use strict";var n=e("underscore"),i=e("web3-core-helpers").errors,o=null,a=null,s=null;if("undefined"!=typeof window&&void 0!==window.WebSocket)o=function(e,t){return new window.WebSocket(e,t)},a=btoa,s=function(e){return new URL(e)};else{o=e("websocket").w3cwebsocket,a=function(e){return r(e).toString("base64")};var u=e("url");if(u.URL){var c=u.URL;s=function(e){return new c(e)}}else s=e("url").parse}var f=function(e,t){var r=this;this.responseCallbacks={},this.notificationCallbacks=[],t=t||{},this._customTimeout=t.timeout;var i=s(e),u=t.headers||{},c=t.protocol||void 0;i.username&&i.password&&(u.authorization="Basic "+a(i.username+":"+i.password));var f=t.clientConfig||void 0;i.auth&&(u.authorization="Basic "+a(i.auth)),this.connection=new o(e,c,void 0,u,void 0,f),this.addDefaultEvents(),this.connection.onmessage=function(e){var t="string"==typeof e.data?e.data:"";r._parseResponse(t).forEach(function(e){var t=null;n.isArray(e)?e.forEach(function(e){r.responseCallbacks[e.id]&&(t=e.id)}):t=e.id,!t&&e&&e.method&&-1!==e.method.indexOf("_subscription")?r.notificationCallbacks.forEach(function(t){n.isFunction(t)&&t(e)}):r.responseCallbacks[t]&&(r.responseCallbacks[t](null,e),delete r.responseCallbacks[t])})},Object.defineProperty(this,"connected",{get:function(){return this.connection&&this.connection.readyState===this.connection.OPEN},enumerable:!0})};f.prototype.addDefaultEvents=function(){var e=this;this.connection.onerror=function(){e._timeout()},this.connection.onclose=function(){e._timeout(),e.reset()}},f.prototype._parseResponse=function(e){var t=this,r=[];return e.replace(/\}[\n\r]?\{/g,"}|--|{").replace(/\}\][\n\r]?\[\{/g,"}]|--|[{").replace(/\}[\n\r]?\[\{/g,"}|--|[{").replace(/\}\][\n\r]?\{/g,"}]|--|{").split("|--|").forEach(function(e){t.lastChunk&&(e=t.lastChunk+e);var n=null;try{n=JSON.parse(e)}catch(r){return t.lastChunk=e,clearTimeout(t.lastChunkTimeout),void(t.lastChunkTimeout=setTimeout(function(){throw t._timeout(),i.InvalidResponse(e)},15e3))}clearTimeout(t.lastChunkTimeout),t.lastChunk=null,n&&r.push(n)}),r},f.prototype._addResponseCallback=function(e,t){var r=e.id||e[0].id,n=e.method||e[0].method;this.responseCallbacks[r]=t,this.responseCallbacks[r].method=n;var o=this;this._customTimeout&&setTimeout(function(){o.responseCallbacks[r]&&(o.responseCallbacks[r](i.ConnectionTimeout(o._customTimeout)),delete o.responseCallbacks[r])},this._customTimeout)},f.prototype._timeout=function(){for(var e in this.responseCallbacks)this.responseCallbacks.hasOwnProperty(e)&&(this.responseCallbacks[e](i.InvalidConnection("on WS")),delete this.responseCallbacks[e])},f.prototype.send=function(e,t){var r=this;if(this.connection.readyState!==this.connection.CONNECTING){if(this.connection.readyState!==this.connection.OPEN)return console.error("connection not open on send()"),"function"==typeof this.connection.onerror?this.connection.onerror(new Error("connection not open")):console.error("no error callback"),void t(new Error("connection not open"));this.connection.send(JSON.stringify(e)),this._addResponseCallback(e,t)}else setTimeout(function(){r.send(e,t)},10)},f.prototype.on=function(e,t){if("function"!=typeof t)throw new Error("The second parameter callback must be a function.");switch(e){case"data":this.notificationCallbacks.push(t);break;case"connect":this.connection.onopen=t;break;case"end":this.connection.onclose=t;break;case"error":this.connection.onerror=t}},f.prototype.removeListener=function(e,t){var r=this;switch(e){case"data":this.notificationCallbacks.forEach(function(e,n){e===t&&r.notificationCallbacks.splice(n,1)})}},f.prototype.removeAllListeners=function(e){switch(e){case"data":this.notificationCallbacks=[];break;case"connect":this.connection.onopen=null;break;case"end":this.connection.onclose=null;break;case"error":this.connection.onerror=null}},f.prototype.reset=function(){this._timeout(),this.notificationCallbacks=[],this.addDefaultEvents()},f.prototype.disconnect=function(){this.connection&&this.connection.close()},t.exports=f}).call(this,e("buffer").Buffer)},{buffer:84,underscore:325,url:327,"web3-core-helpers":338,websocket:408}],401:[function(e,t,r){"use strict";var n=e("web3-core"),i=e("web3-core-subscriptions").subscriptions,o=e("web3-core-method"),a=e("web3-net"),s=function(){var e=this;n.packageInit(this,arguments);var t=this.setProvider;this.setProvider=function(){t.apply(e,arguments),e.net.setProvider.apply(e,arguments)},this.clearSubscriptions=e._requestManager.clearSubscriptions,this.net=new a(this.currentProvider),[new i({name:"subscribe",type:"shh",subscriptions:{messages:{params:1}}}),new o({name:"getVersion",call:"shh_version",params:0}),new o({name:"getInfo",call:"shh_info",params:0}),new o({name:"setMaxMessageSize",call:"shh_setMaxMessageSize",params:1}),new o({name:"setMinPoW",call:"shh_setMinPoW",params:1}),new o({name:"markTrustedPeer",call:"shh_markTrustedPeer",params:1}),new o({name:"newKeyPair",call:"shh_newKeyPair",params:0}),new o({name:"addPrivateKey",call:"shh_addPrivateKey",params:1}),new o({name:"deleteKeyPair",call:"shh_deleteKeyPair",params:1}),new o({name:"hasKeyPair",call:"shh_hasKeyPair",params:1}),new o({name:"getPublicKey",call:"shh_getPublicKey",params:1}),new o({name:"getPrivateKey",call:"shh_getPrivateKey",params:1}),new o({name:"newSymKey",call:"shh_newSymKey",params:0}),new o({name:"addSymKey",call:"shh_addSymKey",params:1}),new o({name:"generateSymKeyFromPassword",call:"shh_generateSymKeyFromPassword",params:1}),new o({name:"hasSymKey",call:"shh_hasSymKey",params:1}),new o({name:"getSymKey",call:"shh_getSymKey",params:1}),new o({name:"deleteSymKey",call:"shh_deleteSymKey",params:1}),new o({name:"newMessageFilter",call:"shh_newMessageFilter",params:1}),new o({name:"getFilterMessages",call:"shh_getFilterMessages",params:1}),new o({name:"deleteMessageFilter",call:"shh_deleteMessageFilter",params:1}),new o({name:"post",call:"shh_post",params:1,inputFormatter:[null]}),new o({name:"unsubscribe",call:"shh_unsubscribe",params:1})].forEach(function(t){t.attachToObject(e),t.setRequestManager(e._requestManager)})};n.addProviders(s),t.exports=s},{"web3-core":348,"web3-core-method":339,"web3-core-subscriptions":345,"web3-net":372}],402:[function(e,t,r){arguments[4][154][0].apply(r,arguments)},{dup:154}],403:[function(e,t,r){var n=e("underscore"),i=e("ethjs-unit"),o=e("./utils.js"),a=e("./soliditySha3.js"),s=e("randomhex"),u=function(e,t){var r=[];return t.forEach(function(t){if("object"==typeof t.components){if("tuple"!==t.type.substring(0,5))throw new Error("components found but type is not tuple; report on GitHub");var i="",o=t.type.indexOf("[");o>=0&&(i=t.type.substring(o));var a=u(e,t.components);n.isArray(a)&&e?r.push("tuple("+a.join(",")+")"+i):e?r.push("("+a+")"):r.push("("+a.join(",")+")"+i)}else r.push(t.type)}),r},c=function(e){if(!o.isHexStrict(e))throw new Error("The parameter must be a valid HEX string.");var t="",r=0,n=e.length;for("0x"===e.substring(0,2)&&(r=2);r7?r+=e[n].toUpperCase():r+=e[n];return r},toHex:o.toHex,toBN:o.toBN,bytesToHex:o.bytesToHex,hexToBytes:o.hexToBytes,hexToNumberString:o.hexToNumberString,hexToNumber:o.hexToNumber,toDecimal:o.hexToNumber,numberToHex:o.numberToHex,fromDecimal:o.numberToHex,hexToUtf8:o.hexToUtf8,hexToString:o.hexToUtf8,toUtf8:o.hexToUtf8,utf8ToHex:o.utf8ToHex,stringToHex:o.utf8ToHex,fromUtf8:o.utf8ToHex,hexToAscii:c,toAscii:c,asciiToHex:f,fromAscii:f,unitMap:i.unitMap,toWei:function(e,t){if(t=h(t),!o.isBN(e)&&!n.isString(e))throw new Error("Please pass numbers as strings or BigNumber objects to avoid precision errors.");return o.isBN(e)?i.toWei(e,t):i.toWei(e,t).toString(10)},fromWei:function(e,t){if(t=h(t),!o.isBN(e)&&!n.isString(e))throw new Error("Please pass numbers as strings or BigNumber objects to avoid precision errors.");return o.isBN(e)?i.fromWei(e,t):i.fromWei(e,t).toString(10)},padLeft:o.leftPad,leftPad:o.leftPad,padRight:o.rightPad,rightPad:o.rightPad,toTwosComplement:o.toTwosComplement}},{"./soliditySha3.js":404,"./utils.js":405,"ethjs-unit":153,randomhex:274,underscore:325}],404:[function(e,t,r){var n=e("underscore"),i=e("bn.js"),o=e("./utils.js"),a=function(e){var t=typeof e;if("string"===t)return o.isHexStrict(e)?new i(e.replace(/0x/i,""),16):new i(e,10);if("number"===t)return new i(e);if(o.isBigNumber(e))return new i(e.toString(10));if(o.isBN(e))return e;throw new Error(e+" is not a number")},s=function(e,t,r){var n,s,u;if("bytes"===(e=(u=e).startsWith("int[")?"int256"+u.slice(3):"int"===u?"int256":u.startsWith("uint[")?"uint256"+u.slice(4):"uint"===u?"uint256":u.startsWith("fixed[")?"fixed128x128"+u.slice(5):"fixed"===u?"fixed128x128":u.startsWith("ufixed[")?"ufixed128x128"+u.slice(6):"ufixed"===u?"ufixed128x128":u)){if(t.replace(/^0x/i,"").length%2!=0)throw new Error("Invalid bytes characters "+t.length);return t}if("string"===e)return o.utf8ToHex(t);if("bool"===e)return t?"01":"00";if(e.startsWith("address")){if(n=r?64:40,!o.isAddress(t))throw new Error(t+" is not a valid address, or the checksum is invalid.");return o.leftPad(t.toLowerCase(),n)}if(n=function(e){var t=/^\D+(\d+).*$/.exec(e);return t?parseInt(t[1],10):null}(e),e.startsWith("bytes")){if(!n)throw new Error("bytes[] not yet supported in solidity");if(r&&(n=32),n<1||n>32||n256)throw new Error("Invalid uint"+n+" size");if((s=a(t)).bitLength()>n)throw new Error("Supplied uint exceeds width: "+n+" vs "+s.bitLength());if(s.lt(new i(0)))throw new Error("Supplied uint "+s.toString()+" is negative");return n?o.leftPad(s.toString("hex"),n/8*2):s}if(e.startsWith("int")){if(n%8||n<8||n>256)throw new Error("Invalid int"+n+" size");if((s=a(t)).bitLength()>n)throw new Error("Supplied int exceeds width: "+n+" vs "+s.bitLength());return s.lt(new i(0))?s.toTwos(n).toString("hex"):n?o.leftPad(s.toString("hex"),n/8*2):s}throw new Error("Unsupported or invalid type: "+e)},u=function(e){if(n.isArray(e))throw new Error("Autodetection of array types is not supported.");var t,r,a="";if(n.isObject(e)&&(e.hasOwnProperty("v")||e.hasOwnProperty("t")||e.hasOwnProperty("value")||e.hasOwnProperty("type"))?(t=e.hasOwnProperty("t")?e.t:e.type,a=e.hasOwnProperty("v")?e.v:e.value):(t=o.toHex(e,!0),a=o.toHex(e),t.startsWith("int")||t.startsWith("uint")||(t="bytes")),!t.startsWith("int")&&!t.startsWith("uint")||"string"!=typeof a||/^(-)?0x/i.test(a)||(a=new i(a)),n.isArray(a)){if((r=function(e){var t=/^\D+\d*\[(\d+)\]$/.exec(e);return t?parseInt(t[1],10):null}(t))&&a.length!==r)throw new Error(t+" is not matching the given array "+JSON.stringify(a));r=a.length}return n.isArray(a)?a.map(function(e){return s(t,e,r).toString("hex").replace("0x","")}).join(""):s(t,a,r).toString("hex").replace("0x","")};t.exports=function(){var e=Array.prototype.slice.call(arguments),t=n.map(e,u);return o.sha3("0x"+t.join(""))}},{"./utils.js":405,"bn.js":402,underscore:325}],405:[function(e,t,r){var n=e("underscore"),i=e("bn.js"),o=e("number-to-bn"),a=e("utf8"),s=e("eth-lib/lib/hash"),u=function(e){return e instanceof i||e&&e.constructor&&"BN"===e.constructor.name},c=function(e){return e&&e.constructor&&"BigNumber"===e.constructor.name},f=function(e){try{return o.apply(null,arguments)}catch(t){throw new Error(t+' Given value: "'+e+'"')}},h=function(e){return!!/^(0x)?[0-9a-f]{40}$/i.test(e)&&(!(!/^(0x|0X)?[0-9a-f]{40}$/.test(e)&&!/^(0x|0X)?[0-9A-F]{40}$/.test(e))||l(e))},l=function(e){e=e.replace(/^0x/i,"");for(var t=m(e.toLowerCase()).replace(/^0x/i,""),r=0;r<40;r++)if(parseInt(t[r],16)>7&&e[r].toUpperCase()!==e[r]||parseInt(t[r],16)<=7&&e[r].toLowerCase()!==e[r])return!1;return!0},d=function(e){var t="";e=(e=(e=(e=(e=a.encode(e)).replace(/^(?:\u0000)*/,"")).split("").reverse().join("")).replace(/^(?:\u0000)*/,"")).split("").reverse().join("");for(var r=0;r>>4).toString(16)),t.push((15&e[r]).toString(16));return"0x"+t.join("")},isHex:function(e){return(n.isString(e)||n.isNumber(e))&&/^(-0x|0x)?[0-9a-f]*$/i.test(e)},isHexStrict:y,leftPad:function(e,t,r){var n=/^0x/i.test(e)||"number"==typeof e,i=t-(e=e.toString(16).replace(/^0x/i,"")).length+1>=0?t-e.length+1:0;return(n?"0x":"")+new Array(i).join(r||"0")+e},rightPad:function(e,t,r){var n=/^0x/i.test(e)||"number"==typeof e,i=t-(e=e.toString(16).replace(/^0x/i,"")).length+1>=0?t-e.length+1:0;return(n?"0x":"")+e+new Array(i).join(r||"0")},toTwosComplement:function(e){return"0x"+f(e).toTwos(256).toString(16,64)},sha3:m}},{"bn.js":402,"eth-lib/lib/hash":134,"number-to-bn":237,underscore:325,utf8:329}],406:[function(e,t,r){t.exports={_from:"web3@1.0.0-beta.36",_id:"web3@1.0.0-beta.36",_inBundle:!1,_integrity:"sha512-fZDunw1V0AQS27r5pUN3eOVP7u8YAvyo6vOapdgVRolAu5LgaweP7jncYyLINqIX9ZgWdS5A090bt+ymgaYHsw==",_location:"/web3",_phantomChildren:{},_requested:{type:"version",registry:!0,raw:"web3@1.0.0-beta.36",name:"web3",escapedName:"web3",rawSpec:"1.0.0-beta.36",saveSpec:null,fetchSpec:"1.0.0-beta.36"},_requiredBy:["#USER","/"],_resolved:"https://registry.npmjs.org/web3/-/web3-1.0.0-beta.36.tgz",_shasum:"2954da9e431124c88396025510d840ba731c8373",_spec:"web3@1.0.0-beta.36",_where:"/Users/alexvlasov/Blockchain/web3swift/web3swiftJSProxy",author:{name:"ethereum.org"},authors:[{name:"Fabian Vogelsteller",email:"fabian@ethereum.org",homepage:"http://frozeman.de"},{name:"Marek Kotewicz",email:"marek@parity.io",url:"https://github.com/debris"},{name:"Marian Oancea",url:"https://github.com/cubedro"},{name:"Gav Wood",email:"g@parity.io",homepage:"http://gavwood.com"},{name:"Jeffery Wilcke",email:"jeffrey.wilcke@ethereum.org",url:"https://github.com/obscuren"}],bugs:{url:"https://github.com/ethereum/web3.js/issues"},bundleDependencies:!1,dependencies:{"web3-bzz":"1.0.0-beta.36","web3-core":"1.0.0-beta.36","web3-eth":"1.0.0-beta.36","web3-eth-personal":"1.0.0-beta.36","web3-net":"1.0.0-beta.36","web3-shh":"1.0.0-beta.36","web3-utils":"1.0.0-beta.36"},deprecated:!1,description:"Ethereum JavaScript API",keywords:["Ethereum","JavaScript","API"],license:"LGPL-3.0",main:"src/index.js",name:"web3",namespace:"ethereum",repository:{type:"git",url:"https://github.com/ethereum/web3.js/tree/master/packages/web3"},version:"1.0.0-beta.36"}},{}],407:[function(e,t,r){"use strict";var n=e("../package.json").version,i=e("web3-core"),o=e("web3-eth"),a=e("web3-net"),s=e("web3-eth-personal"),u=e("web3-shh"),c=e("web3-bzz"),f=e("web3-utils"),h=function(){var e=this;i.packageInit(this,arguments),this.version=n,this.utils=f,this.eth=new o(this),this.shh=new u(this),this.bzz=new c(this);var t=this.setProvider;this.setProvider=function(r,n){return t.apply(e,arguments),this.eth.setProvider(r,n),this.shh.setProvider(r,n),this.bzz.setProvider(r),!0}};h.version=n,h.utils=f,h.modules={Eth:o,Net:a,Personal:s,Shh:u,Bzz:c},i.addProviders(h),t.exports=h},{"../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(e,t,r){var n=function(){return this||{}}(),i=n.WebSocket||n.MozWebSocket,o=e("./version");function a(e,t){return t?new i(e,t):new i(e)}i&&["CONNECTING","OPEN","CLOSING","CLOSED"].forEach(function(e){Object.defineProperty(a,e,{get:function(){return i[e]}})}),t.exports={w3cwebsocket:i?a:null,version:o}},{"./version":409}],409:[function(e,t,r){t.exports=e("../package.json").version},{"../package.json":410}],410:[function(e,t,r){t.exports={_from:"git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible",_id:"websocket@1.0.26",_inBundle:!1,_integrity:"",_location:"/websocket",_phantomChildren:{},_requested:{type:"git",raw:"websocket@git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible",name:"websocket",escapedName:"websocket",rawSpec:"git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible",saveSpec:"git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible",fetchSpec:"git://github.com/frozeman/WebSocket-Node.git",gitCommittish:"browserifyCompatible"},_requiredBy:["/web3-providers-ws"],_resolved:"git://github.com/frozeman/WebSocket-Node.git#6c72925e3f8aaaea8dc8450f97627e85263999f2",_spec:"websocket@git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible",_where:"/Users/alexvlasov/Blockchain/web3swift/web3swiftJSProxy/node_modules/web3-providers-ws",author:{name:"Brian McKelvey",email:"brian@worlize.com",url:"https://www.worlize.com/"},browser:"lib/browser.js",bugs:{url:"https://github.com/theturtle32/WebSocket-Node/issues"},bundleDependencies:!1,config:{verbose:!1},contributors:[{name:"Iñaki Baz Castillo",email:"ibc@aliax.net",url:"http://dev.sipdoc.net"}],dependencies:{debug:"^2.2.0",nan:"^2.3.3","typedarray-to-buffer":"^3.1.2",yaeti:"^0.0.6"},deprecated:!1,description:"Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.",devDependencies:{"buffer-equal":"^1.0.0",faucet:"^0.0.1",gulp:"git+https://github.com/gulpjs/gulp.git#4.0","gulp-jshint":"^2.0.4",jshint:"^2.0.0","jshint-stylish":"^2.2.1",tape:"^4.0.1"},directories:{lib:"./lib"},engines:{node:">=0.10.0"},homepage:"https://github.com/theturtle32/WebSocket-Node",keywords:["websocket","websockets","socket","networking","comet","push","RFC-6455","realtime","server","client"],license:"Apache-2.0",main:"index",name:"websocket",repository:{type:"git",url:"git+https://github.com/theturtle32/WebSocket-Node.git"},scripts:{gulp:"gulp",install:"(node-gyp rebuild 2> builderror.log) || (exit 0)",test:"faucet test/unit"},version:"1.0.26"}},{}],411:[function(e,t,r){var n=e("xhr-request");t.exports=function(e,t){return new Promise(function(r,i){n(e,t,function(e,t){e?i(e):r(t)})})}},{"xhr-request":412}],412:[function(e,t,r){var n=e("query-string"),i=e("url-set-query"),o=e("object-assign"),a=e("./lib/ensure-header.js"),s=e("./lib/request.js"),u="application/json",c=function(){};t.exports=function(e,t,r){if(!e||"string"!=typeof e)throw new TypeError("must specify a URL");"function"==typeof t&&(r=t,t={});if(r&&"function"!=typeof r)throw new TypeError("expected cb to be undefined or a function");r=r||c;var f=(t=t||{}).json?"json":"text",h=(t=o({responseType:f},t)).headers||{},l=(t.method||"GET").toUpperCase(),d=t.query;d&&("string"!=typeof d&&(d=n.stringify(d)),e=i(e,d));"json"===t.responseType&&a(h,"Accept",u);t.json&&"GET"!==l&&"HEAD"!==l&&(a(h,"Content-Type",u),t.body=JSON.stringify(t.body));return t.method=l,t.url=e,t.headers=h,delete t.query,delete t.json,s(t,r)}},{"./lib/ensure-header.js":413,"./lib/request.js":415,"object-assign":238,"query-string":266,"url-set-query":326}],413:[function(e,t,r){t.exports=function(e,t,r){var n=t.toLowerCase();e[t]||e[n]||(e[t]=r)}},{}],414:[function(e,t,r){t.exports=function(e,t){return t?{statusCode:t.statusCode,headers:t.headers,method:e.method,url:e.url,rawRequest:t.rawRequest?t.rawRequest:t}:null}},{}],415:[function(e,t,r){var n=e("xhr"),i=e("./normalize-response"),o=function(){};t.exports=function(e,t){delete e.uri;var r=!1;"json"===e.responseType&&(e.responseType="text",r=!0);var a=n(e,function(n,a,s){if(r&&!n)try{var u=a.rawRequest.responseText;s=JSON.parse(u)}catch(e){n=e}a=i(e,a),t(n,n?null:s,a),t=o}),s=a.onabort;return a.onabort=function(){var e=s.apply(a,Array.prototype.slice.call(arguments));return t(new Error("XHR Aborted")),t=o,e},a}},{"./normalize-response":414,xhr:416}],416:[function(e,t,r){"use strict";var n=e("global/window"),i=e("is-function"),o=e("parse-headers"),a=e("xtend");function s(e,t,r){var n=e;return i(t)?(r=t,"string"==typeof e&&(n={uri:e})):n=a(t,{uri:e}),n.callback=r,n}function u(e,t,r){return c(t=s(e,t,r))}function c(e){if(void 0===e.callback)throw new Error("callback argument missing");var t=!1,r=function(r,n,i){t||(t=!0,e.callback(r,n,i))};function n(e){return clearTimeout(f),e instanceof Error||(e=new Error(""+(e||"Unknown XMLHttpRequest Error"))),e.statusCode=0,r(e,m)}function i(){if(!s){var t;clearTimeout(f),t=e.useXDR&&void 0===c.status?200:1223===c.status?204:c.status;var n=m,i=null;return 0!==t?(n={body:function(){var e=void 0;if(e=c.response?c.response:c.responseText||function(e){try{if("document"===e.responseType)return e.responseXML;var t=e.responseXML&&"parsererror"===e.responseXML.documentElement.nodeName;if(""===e.responseType&&!t)return e.responseXML}catch(e){}return null}(c),y)try{e=JSON.parse(e)}catch(e){}return e}(),statusCode:t,method:l,headers:{},url:h,rawRequest:c},c.getAllResponseHeaders&&(n.headers=o(c.getAllResponseHeaders()))):i=new Error("Internal XMLHttpRequest Error"),r(i,n,n.body)}}var a,s,c=e.xhr||null;c||(c=e.cors||e.useXDR?new u.XDomainRequest:new u.XMLHttpRequest);var f,h=c.url=e.uri||e.url,l=c.method=e.method||"GET",d=e.body||e.data,p=c.headers=e.headers||{},b=!!e.sync,y=!1,m={body:void 0,headers:{},statusCode:0,method:l,url:h,rawRequest:c};if("json"in e&&!1!==e.json&&(y=!0,p.accept||p.Accept||(p.Accept="application/json"),"GET"!==l&&"HEAD"!==l&&(p["content-type"]||p["Content-Type"]||(p["Content-Type"]="application/json"),d=JSON.stringify(!0===e.json?d:e.json))),c.onreadystatechange=function(){4===c.readyState&&setTimeout(i,0)},c.onload=i,c.onerror=n,c.onprogress=function(){},c.onabort=function(){s=!0},c.ontimeout=n,c.open(l,h,!b,e.username,e.password),b||(c.withCredentials=!!e.withCredentials),!b&&e.timeout>0&&(f=setTimeout(function(){if(!s){s=!0,c.abort("timeout");var e=new Error("XMLHttpRequest timeout");e.code="ETIMEDOUT",n(e)}},e.timeout)),c.setRequestHeader)for(a in p)p.hasOwnProperty(a)&&c.setRequestHeader(a,p[a]);else if(e.headers&&!function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0}(e.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in e&&(c.responseType=e.responseType),"beforeSend"in e&&"function"==typeof e.beforeSend&&e.beforeSend(c),c.send(d||null),c}t.exports=u,t.exports.default=u,u.XMLHttpRequest=n.XMLHttpRequest||function(){},u.XDomainRequest="withCredentials"in new u.XMLHttpRequest?u.XMLHttpRequest:n.XDomainRequest,function(e,t){for(var r=0;r=0)return this._url=this._parseUrl(t.headers.location),this._method="GET",this._loweredHeaders["content-type"]&&(delete this._headers[this._loweredHeaders["content-type"]],delete this._loweredHeaders["content-type"]),null!=this._headers["Content-Type"]&&delete this._headers["Content-Type"],delete this._headers["Content-Length"],this.upload._reset(),this._finalizeHeaders(),void this._sendHxxpRequest();this._response=t,this._response.on("data",function(e){return n._onHttpResponseData(t,e)}),this._response.on("end",function(){return n._onHttpResponseEnd(t)}),this._response.on("close",function(){return n._onHttpResponseClose(t)}),this.responseUrl=this._url.href.split("#")[0],this.status=t.statusCode,this.statusText=s.STATUS_CODES[this.status],this._parseResponseHeaders(t);var i=this._responseHeaders["content-length"]||"";this._totalBytes=+i,this._lengthComputable=!!i,this._setReadyState(r.HEADERS_RECEIVED)}},r.prototype._onHttpResponseData=function(e,t){this._response===e&&(this._responseParts.push(new n(t)),this._loadedBytes+=t.length,this.readyState!==r.LOADING&&this._setReadyState(r.LOADING),this._dispatchProgress("progress"))},r.prototype._onHttpResponseEnd=function(e){this._response===e&&(this._parseResponse(),this._request=null,this._response=null,this._setReadyState(r.DONE),this._dispatchProgress("load"),this._dispatchProgress("loadend"))},r.prototype._onHttpResponseClose=function(e){if(this._response===e){var t=this._request;this._setError(),t.abort(),this._setReadyState(r.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}},r.prototype._onHttpTimeout=function(e){this._request===e&&(this._setError(),e.abort(),this._setReadyState(r.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend"))},r.prototype._onHttpRequestError=function(e,t){this._request===e&&(this._setError(),e.abort(),this._setReadyState(r.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend"))},r.prototype._dispatchProgress=function(e){var t=new r.ProgressEvent(e);t.lengthComputable=this._lengthComputable,t.loaded=this._loadedBytes,t.total=this._totalBytes,this.dispatchEvent(t)},r.prototype._setError=function(){this._request=null,this._response=null,this._responseHeaders=null,this._responseParts=null},r.prototype._parseUrl=function(e,t,r){var n=null==this.nodejsBaseUrl?e:f.resolve(this.nodejsBaseUrl,e),i=f.parse(n,!1,!0);i.hash=null;var o=(i.auth||"").split(":"),a=o[0],s=o[1];return(a||s||t||r)&&(i.auth=(t||a||"")+":"+(r||s||"")),i},r.prototype._parseResponseHeaders=function(e){for(var t in this._responseHeaders={},e.headers){var r=t.toLowerCase();this._privateHeaders[r]||(this._responseHeaders[r]=e.headers[t])}null!=this._mimeOverride&&(this._responseHeaders["content-type"]=this._mimeOverride)},r.prototype._parseResponse=function(){var e=n.concat(this._responseParts);switch(this._responseParts=null,this.responseType){case"json":this.responseText=null;try{this.response=JSON.parse(e.toString("utf-8"))}catch(e){this.response=null}return;case"buffer":return this.responseText=null,void(this.response=e);case"arraybuffer":this.responseText=null;for(var t=new ArrayBuffer(e.length),r=new Uint8Array(t),i=0;i{ <# print parameters, error #> }); */ +/* var unregisterHandler = window.bridge.on('userDidLogin', (parameters) => { <# receive notify from native #> } ); Call unregisterHandler() when cancel a listen. */ diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Contract/ComparisonExtensions.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Contract/ComparisonExtensions.swift new file mode 100755 index 000000000..33f525ff6 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Contract/ComparisonExtensions.swift @@ -0,0 +1,95 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +extension BigUInt: EventFilterComparable { + public func isEqualTo(_ other: AnyObject) -> Bool { + switch other { + case let oth as BigUInt: + return self == oth + case let oth as BigInt: + return self.magnitude == oth.magnitude && self.signum() == oth.signum() + default: + return false + } + } +} + +extension BigInt: EventFilterComparable { + public func isEqualTo(_ other: AnyObject) -> Bool { + switch other { + case let oth as BigInt: + return self == oth + case let oth as BigUInt: + return self.magnitude == oth.magnitude && self.signum() == oth.signum() + default: + return false + } + } +} + +extension String: EventFilterComparable { + public func isEqualTo(_ other: AnyObject) -> Bool { + switch other { + case let oth as String: + guard let data = self.data(using: .utf8) else {return false} + guard let otherData = oth.data(using: .utf8) else {return false} + let hash = data.sha3(.keccak256) + let otherHash = otherData.sha3(.keccak256) + return hash == otherHash + case let oth as Data: + guard let data = self.data(using: .utf8) else {return false} + let hash = data.sha3(.keccak256) + let otherHash = oth.sha3(.keccak256) + return hash == otherHash + default: + return false + } + } +} + +extension Data: EventFilterComparable { + public func isEqualTo(_ other: AnyObject) -> Bool { + switch other { + case let oth as String: + guard let data = Data.fromHex(oth) else {return false} + if self == data { + return true + } + let hash = data.sha3(.keccak256) + return self == hash + case let oth as Data: + if self == oth { + return true + } + let hash = oth.sha3(.keccak256) + return self == hash + default: + return false + } + } +} + +extension EthereumAddress: EventFilterComparable { + public func isEqualTo(_ other: AnyObject) -> Bool { + switch other { + case let oth as String: + let addr = EthereumAddress(oth) + return self == addr + case let oth as Data: + let addr = EthereumAddress(oth) + return self == addr + case let oth as EthereumAddress: + return self == oth + default: + return false + } + } +} + diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Contract/ContractProtocol.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Contract/ContractProtocol.swift new file mode 100755 index 000000000..60a31251d --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Contract/ContractProtocol.swift @@ -0,0 +1,109 @@ +// +// ContractProtocol.swift +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +public protocol ContractProtocol { + var address: EthereumAddress? {get set} + var transactionOptions: TransactionOptions? {get set} + var allMethods: [String] {get} + var allEvents: [String] {get} + func deploy(bytecode:Data, parameters: [AnyObject], extraData: Data) -> EthereumTransaction? + func method(_ method:String, parameters: [AnyObject], extraData: Data) -> EthereumTransaction? + init?(_ abiString: String, at: EthereumAddress?) + func decodeReturnData(_ method:String, data: Data) -> [String:Any]? + func decodeInputData(_ method:String, data: Data) -> [String:Any]? + func decodeInputData(_ data: Data) -> [String:Any]? + func parseEvent(_ eventLog: EventLog) -> (eventName:String?, eventData:[String:Any]?) + func testBloomForEventPrecence(eventName: String, bloom: EthereumBloomFilter) -> Bool? +} + +public protocol EventFilterComparable { + func isEqualTo(_ other: AnyObject) -> Bool +} + +public protocol EventFilterEncodable { + func eventFilterEncoded() -> String? +} + +public protocol EventFilterable: EventFilterComparable, EventFilterEncodable { + +} + +extension BigUInt: EventFilterable { +} +extension BigInt: EventFilterable { +} +extension Data: EventFilterable { +} +extension String: EventFilterable { +} +extension EthereumAddress: EventFilterable { +} + + +public struct EventFilter { + public enum Block { + case latest + case pending + case blockNumber(UInt64) + + var encoded: String { + switch self { + case .latest: + return "latest" + case .pending: + return "pending" + case .blockNumber(let number): + return String(number, radix: 16).addHexPrefix() + } + } + } + + public init() { + + } + + public init(fromBlock: Block?, toBlock: Block?, + addresses: [EthereumAddress]? = nil, + parameterFilters: [[EventFilterable]?]? = nil) { + self.fromBlock = fromBlock + self.toBlock = toBlock + self.addresses = addresses + self.parameterFilters = parameterFilters + } + + public var fromBlock: Block? + public var toBlock: Block? + public var addresses: [EthereumAddress]? + public var parameterFilters: [[EventFilterable]?]? + + public func rpcPreEncode() -> EventFilterParameters { + var encoding = EventFilterParameters() + if self.fromBlock != nil { + encoding.fromBlock = self.fromBlock!.encoded + } + if self.toBlock != nil { + encoding.toBlock = self.toBlock!.encoded + } + if self.addresses != nil { + if self.addresses!.count == 1 { + encoding.address = [self.addresses![0].address] + } else { + var encodedAddresses = [String?]() + for addr in self.addresses! { + encodedAddresses.append(addr.address) + } + encoding.address = encodedAddresses + } + } + return encoding + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Contract/EthereumContract.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Contract/EthereumContract.swift new file mode 100755 index 000000000..203c51519 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Contract/EthereumContract.swift @@ -0,0 +1,297 @@ +// +// Created by Alexander Vlasov. +// Copyright © 2018 Alexander Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress +//import EthereumABI + +public struct EthereumContract:ContractProtocol { + public var transactionOptions: TransactionOptions? = TransactionOptions.defaultOptions + public var address: EthereumAddress? = nil + + var _abi: [ABI.Element] + + public var allEvents: [String] { + return events.keys.compactMap({ (s) -> String in + return s + }) + } + + public var allMethods: [String] { + return methods.keys.compactMap({ (s) -> String in + return s + }) + } + + public struct EventFilter { + public var parameterName: String + public var parameterValues: [AnyObject] + } + + public var methods: [String: ABI.Element] { + var toReturn = [String: ABI.Element]() + for m in self._abi { + switch m { + case .function(let function): + guard let name = function.name else {continue} + toReturn[name] = m + default: + continue + } + } + return toReturn + } + + public var constructor: ABI.Element? { + var toReturn : ABI.Element? = nil + for m in self._abi { + if toReturn != nil { + break + } + switch m { + case .constructor(_): + toReturn = m + break + default: + continue + } + } + if toReturn == nil { + let defaultConstructor = ABI.Element.constructor(ABI.Element.Constructor(inputs: [], constant: false, payable: false)) + return defaultConstructor + } + return toReturn + } + + public var events: [String: ABI.Element.Event] { + var toReturn = [String: ABI.Element.Event]() + for m in self._abi { + switch m { + case .event(let event): + let name = event.name + toReturn[name] = event + default: + continue + } + } + return toReturn + } + + public init?(_ abiString: String, at: EthereumAddress? = nil) { + do { + let jsonData = abiString.data(using: .utf8) + let abi = try JSONDecoder().decode([ABI.Record].self, from: jsonData!) + let abiNative = try abi.map({ (record) -> ABI.Element in + return try record.parse() + }) + _abi = abiNative + if at != nil { + self.address = at + } + } + catch{ + return nil + } + } + + public init(abi: [ABI.Element]) { + _abi = abi + } + + public init(abi: [ABI.Element], at: EthereumAddress) { + _abi = abi + address = at + } + +// public func deploy(bytecode:Data, parameters: [AnyObject] = [AnyObject](), extraData: Data = Data(), options: Web3Options?) -> EthereumTransaction? { +// let to:EthereumAddress = EthereumAddress.contractDeploymentAddress() +// let mergedOptions = Web3Options.merge(self.options, with: options) +// var gasLimit:BigUInt +// if let gasInOptions = mergedOptions?.gasLimit { +// gasLimit = gasInOptions +// } else { +// return nil +// } +// +// var gasPrice:BigUInt +// if let gasPriceInOptions = mergedOptions?.gasPrice { +// gasPrice = gasPriceInOptions +// } else { +// return nil +// } +// +// var value:BigUInt +// if let valueInOptions = mergedOptions?.value { +// value = valueInOptions +// } else { +// value = BigUInt(0) +// } +// guard let constructor = self.constructor else {return nil} +// guard let encodedData = constructor.encodeParameters(parameters) else {return nil} +// var fullData = bytecode +// if encodedData != Data() { +// fullData.append(encodedData) +// } else if extraData != Data() { +// fullData.append(extraData) +// } +// let transaction = EthereumTransaction(gasPrice: gasPrice, gasLimit: gasLimit, to: to, value: value, data: fullData) +// return transaction +// } + + public func deploy(bytecode:Data, parameters: [AnyObject] = [AnyObject](), extraData: Data = Data()) -> EthereumTransaction? { + let to:EthereumAddress = EthereumAddress.contractDeploymentAddress() + guard let constructor = self.constructor else {return nil} + guard let encodedData = constructor.encodeParameters(parameters) else {return nil} + var fullData = bytecode + if encodedData != Data() { + fullData.append(encodedData) + } else if extraData != Data() { + fullData.append(extraData) + } + let transaction = EthereumTransaction(gasPrice: BigUInt(0), gasLimit: BigUInt(0), to: to, value: BigUInt(0), data: fullData) + return transaction + } + +// public func method(_ method:String = "fallback", parameters: [AnyObject] = [AnyObject](), extraData: Data = Data(), options: Web3Options?) -> EthereumTransaction? { +// var to:EthereumAddress +// let mergedOptions = Web3Options.merge(self.options, with: options) +// if (self.address != nil) { +// to = self.address! +// } else if let toFound = mergedOptions?.to, toFound.isValid { +// to = toFound +// } else { +// return nil +// } +// +// var gasLimit:BigUInt +// if let gasInOptions = mergedOptions?.gasLimit { +// gasLimit = gasInOptions +// } else { +// return nil +// } +// +// var gasPrice:BigUInt +// if let gasPriceInOptions = mergedOptions?.gasPrice { +// gasPrice = gasPriceInOptions +// } else { +// return nil +// } +// +// var value:BigUInt +// if let valueInOptions = mergedOptions?.value { +// value = valueInOptions +// } else { +// value = BigUInt(0) +// } +// +// if (method == "fallback") { +// let transaction = EthereumTransaction(gasPrice: gasPrice, gasLimit: gasLimit, to: to, value: value, data: extraData) +// return transaction +// } +// let foundMethod = self.methods.filter { (key, value) -> Bool in +// return key == method +// } +// guard foundMethod.count == 1 else {return nil} +// let abiMethod = foundMethod[method] +// guard let encodedData = abiMethod?.encodeParameters(parameters) else {return nil} +// let transaction = EthereumTransaction(gasPrice: gasPrice, gasLimit: gasLimit, to: to, value: value, data: encodedData) +// return transaction +// } + + public func method(_ method:String = "fallback", parameters: [AnyObject] = [AnyObject](), extraData: Data = Data()) -> EthereumTransaction? { + guard let to = self.address else {return nil} + + if (method == "fallback") { + let transaction = EthereumTransaction(gasPrice: BigUInt(0), gasLimit: BigUInt(0), to: to, value: BigUInt(0), data: extraData) + return transaction + } + let foundMethod = self.methods.filter { (key, value) -> Bool in + return key == method + } + guard foundMethod.count == 1 else {return nil} + let abiMethod = foundMethod[method] + guard let encodedData = abiMethod?.encodeParameters(parameters) else {return nil} + let transaction = EthereumTransaction(gasPrice: BigUInt(0), gasLimit: BigUInt(0), to: to, value: BigUInt(0), data: encodedData) + return transaction + } + + public func parseEvent(_ eventLog: EventLog) -> (eventName:String?, eventData:[String:Any]?) { + for (eName, ev) in self.events { + if (!ev.anonymous) { + if eventLog.topics[0] != ev.topic { + continue + } + else { + let logTopics = eventLog.topics + let logData = eventLog.data + let parsed = ev.decodeReturnedLogs(eventLogTopics: logTopics, eventLogData: logData) + if parsed != nil { + return (eName, parsed!) + } + } + } else { + let logTopics = eventLog.topics + let logData = eventLog.data + let parsed = ev.decodeReturnedLogs(eventLogTopics: logTopics, eventLogData: logData) + if parsed != nil { + return (eName, parsed!) + } + } + } + return (nil, nil) + } + + public func testBloomForEventPrecence(eventName: String, bloom: EthereumBloomFilter) -> Bool? { + guard let event = events[eventName] else {return nil} + if event.anonymous { + return true + } + let eventOfSuchTypeIsPresent = bloom.test(topic: event.topic) + return eventOfSuchTypeIsPresent + } + + public func decodeReturnData(_ method:String, data: Data) -> [String:Any]? { + if method == "fallback" { + return [String:Any]() + } + guard let function = methods[method] else {return nil} + guard case .function(_) = function else {return nil} + return function.decodeReturnData(data) + } + + public func decodeInputData(_ method: String, data: Data) -> [String : Any]? { + if method == "fallback" { + return nil + } + guard let function = methods[method] else {return nil} + switch function { + case .function(_): + return function.decodeInputData(data) + case .constructor(_): + return function.decodeInputData(data) + default: + return nil + } + } + + public func decodeInputData(_ data: Data) -> [String:Any]? { + guard data.count % 32 == 4 else {return nil} + let methodSignature = data[0..<4] + let foundFunction = self._abi.filter { (m) -> Bool in + switch m { + case .function(let function): + return function.methodEncoding == methodSignature + default: + return false + } + } + guard foundFunction.count == 1 else { + return nil + } + let function = foundFunction[0] + return function.decodeInputData(Data(data[4 ..< data.count])) + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Contract/EthereumFilterEncodingExtensions.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Contract/EthereumFilterEncodingExtensions.swift new file mode 100755 index 000000000..d590a87d9 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Contract/EthereumFilterEncodingExtensions.swift @@ -0,0 +1,44 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +extension BigUInt: EventFilterEncodable { + public func eventFilterEncoded() -> String? { + return self.abiEncode(bits: 256)?.toHexString().addHexPrefix() + } +} + +extension BigInt: EventFilterEncodable { + public func eventFilterEncoded() -> String? { + return self.abiEncode(bits: 256)?.toHexString().addHexPrefix() + } +} + +extension Data: EventFilterEncodable { + public func eventFilterEncoded() -> String? { + guard let padded = self.setLengthLeft(32) else {return nil} + return padded.toHexString().addHexPrefix() + } +} + +extension EthereumAddress: EventFilterEncodable { + public func eventFilterEncoded() -> String? { + guard let padded = self.addressData.setLengthLeft(32) else {return nil} + return padded.toHexString().addHexPrefix() + } +} + +extension String: EventFilterEncodable { + public func eventFilterEncoded() -> String? { + guard let data = self.data(using: .utf8) else {return nil} + return data.sha3(.keccak256).toHexString().addHexPrefix() + } +} + + diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Contract/EventFiltering.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Contract/EventFiltering.swift new file mode 100755 index 000000000..b170285c7 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Contract/EventFiltering.swift @@ -0,0 +1,170 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +//import EthereumABI +//import EthereumAddress + +internal func filterLogs(decodedLogs: [EventParserResultProtocol], eventFilter: EventFilter) -> [EventParserResultProtocol] { + let filteredLogs = decodedLogs.filter { (result) -> Bool in + if eventFilter.addresses == nil { + return true + } else { + if eventFilter.addresses!.contains(result.contractAddress) { + return true + } else { + return false + } + } + }.filter { (result) -> Bool in + if eventFilter.parameterFilters == nil { + return true + } else { + let keys = result.decodedResult.keys.filter({ (key) -> Bool in + if let _ = UInt64(key) { + return true + } + return false + }) + if keys.count < eventFilter.parameterFilters!.count { + return false + } + for i in 0 ..< eventFilter.parameterFilters!.count { + let allowedValues = eventFilter.parameterFilters![i] + let actualValue = result.decodedResult["\(i)"] + if actualValue == nil { + return false + } + if allowedValues == nil { + continue + } + var inAllowed = false + for value in allowedValues! { + if value.isEqualTo(actualValue! as AnyObject) { + inAllowed = true + break + } + } + if !inAllowed { + return false + } + } + return true + } + } + return filteredLogs +} + +internal func encodeTopicToGetLogs(contract: EthereumContract, eventName: String?, filter: EventFilter) -> EventFilterParameters? { + var eventTopic: Data? = nil + var event: ABI.Element.Event? = nil + if eventName != nil { + guard let ev = contract.events[eventName!] else {return nil} + event = ev + eventTopic = ev.topic + } + var topics = [[String?]?]() + if eventTopic != nil { + topics.append([eventTopic!.toHexString().addHexPrefix()]) + } else { + topics.append(nil as [String?]?) + } + if filter.parameterFilters != nil { + if event == nil {return nil} + var lastNonemptyFilter = -1 + for i in 0 ..< filter.parameterFilters!.count { + let filterValue = filter.parameterFilters![i] + if filterValue != nil { + lastNonemptyFilter = i + } + } + if lastNonemptyFilter >= 0 { + guard lastNonemptyFilter <= event!.inputs.count else {return nil} + for i in 0 ... lastNonemptyFilter { + let filterValues = filter.parameterFilters![i] + if filterValues != nil { + var isFound = false + var targetIndexedPosition = i + for j in 0 ..< event!.inputs.count{ + if event!.inputs[j].indexed { + if targetIndexedPosition == 0 { + isFound = true + break + } + targetIndexedPosition -= 1 + } + } + + if !isFound {return nil} + } + if filterValues == nil { + topics.append(nil as [String?]?) + continue + } + var encodings = [String]() + for val in filterValues! { + guard let enc = val.eventFilterEncoded() else {return nil} + encodings.append(enc) + } + topics.append(encodings) + } + } + } + var preEncoding = filter.rpcPreEncode() + preEncoding.topics = topics + return preEncoding +} + +internal func parseReceiptForLogs(receipt: TransactionReceipt, contract: ContractProtocol, eventName: String, filter: EventFilter?) -> [EventParserResultProtocol]? { + guard let bloom = receipt.logsBloom else {return nil} + if contract.address != nil { + let addressPresent = bloom.test(topic: contract.address!.addressData) + if (addressPresent != true) { + return [EventParserResultProtocol]() + } + } + if filter != nil, let filterAddresses = filter?.addresses { + var oneIsPresent = false + for addr in filterAddresses { + let addressPresent = bloom.test(topic: addr.addressData) + if (addressPresent == true) { + oneIsPresent = true + break + } + } + if (oneIsPresent != true) { + return [EventParserResultProtocol]() + } + } + guard let eventOfSuchTypeIsPresent = contract.testBloomForEventPrecence(eventName: eventName, bloom: bloom) else {return nil} + if (!eventOfSuchTypeIsPresent) { + return [EventParserResultProtocol]() + } + var allLogs = receipt.logs + if (contract.address != nil) { + allLogs = receipt.logs.filter({ (log) -> Bool in + log.address == contract.address + }) + } + let decodedLogs = allLogs.compactMap({ (log) -> EventParserResultProtocol? in + let (n, d) = contract.parseEvent(log) + guard let evName = n, let evData = d else {return nil} + var result = EventParserResult(eventName: evName, transactionReceipt: receipt, contractAddress: log.address, decodedResult: evData) + result.eventLog = log + return result + }).filter { (res:EventParserResultProtocol?) -> Bool in + return res != nil && res?.eventName == eventName + } + var allResults = [EventParserResultProtocol]() + if (filter != nil) { + let eventFilter = filter! + let filteredLogs = filterLogs(decodedLogs: decodedLogs, eventFilter: eventFilter) + allResults = filteredLogs + } else { + allResults = decodedLogs + } + return allResults +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Array+Extension.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Array+Extension.swift new file mode 100755 index 000000000..3fc7e80f2 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Array+Extension.swift @@ -0,0 +1,16 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +extension Array { + public func split(intoChunksOf chunkSize: Int) -> [[Element]] { + return stride(from: 0, to: self.count, by: chunkSize).map { + let endIndex = ($0.advanced(by: chunkSize) > self.count) ? self.count - $0 : chunkSize + return Array(self[$0..<$0.advanced(by: endIndex)]) + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Base58.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Base58.swift new file mode 100755 index 000000000..397b389cd --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Base58.swift @@ -0,0 +1,170 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +struct Base58 { + static let base58Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + + // Encode + static func base58FromBytes(_ bytes: [UInt8]) -> String { + var bytes = bytes + var zerosCount = 0 + var length = 0 + + for b in bytes { + if b != 0 { break } + zerosCount += 1 + } + + bytes.removeFirst(zerosCount) + + let size = bytes.count * 138 / 100 + 1 + + var base58: [UInt8] = Array(repeating: 0, count: size) + for b in bytes { + var carry = Int(b) + var i = 0 + + for j in 0...base58.count-1 where carry != 0 || i < length { + carry += 256 * Int(base58[base58.count - j - 1]) + base58[base58.count - j - 1] = UInt8(carry % 58) + carry /= 58 + i += 1 + } + + assert(carry == 0) + + length = i + } + + // skip leading zeros + var zerosToRemove = 0 + var str = "" + for b in base58 { + if b != 0 { break } + zerosToRemove += 1 + } + base58.removeFirst(zerosToRemove) + + while 0 < zerosCount { + str = "\(str)1" + zerosCount -= 1 + } + + for b in base58 { + //str = "\(str)\(base58Alphabet[String.Index(encodedOffset: Int(b))])" + str = "\(str)\(base58Alphabet[String.Index(utf16Offset: Int(b), in: base58Alphabet)])" + } + + return str + } + + // Decode + static func bytesFromBase58(_ base58: String) -> [UInt8] { + // remove leading and trailing whitespaces + let string = base58.trimmingCharacters(in: CharacterSet.whitespaces) + + guard !string.isEmpty else { return [] } + + var zerosCount = 0 + var length = 0 + for c in string { + if c != "1" { break } + zerosCount += 1 + } + + let size = string.lengthOfBytes(using: String.Encoding.utf8) * 733 / 1000 + 1 - zerosCount + var base58: [UInt8] = Array(repeating: 0, count: size) + for c in string where c != " " { + // search for base58 character + guard let base58Index = base58Alphabet.index(of: c) else { return [] } + +// var carry = base58Index.encodedOffset + var carry = base58Index.utf16Offset(in: base58Alphabet) + var i = 0 + for j in 0...base58.count where carry != 0 || i < length { + carry += 58 * Int(base58[base58.count - j - 1]) + base58[base58.count - j - 1] = UInt8(carry % 256) + carry /= 256 + i += 1 + } + + assert(carry == 0) + length = i + } + + // skip leading zeros + var zerosToRemove = 0 + + for b in base58 { + if b != 0 { break } + zerosToRemove += 1 + } + base58.removeFirst(zerosToRemove) + + var result: [UInt8] = Array(repeating: 0, count: zerosCount) + for b in base58 { + result.append(b) + } + return result + } +} + + + +extension Array where Element == UInt8 { + public var base58EncodedString: String { + guard !self.isEmpty else { return "" } + return Base58.base58FromBytes(self) + } + + public var base58CheckEncodedString: String { + var bytes = self + let checksum = [UInt8](bytes.sha256().sha256()[0..<4]) + + bytes.append(contentsOf: checksum) + + return Base58.base58FromBytes(bytes) + } +} + +extension String { + public var base58EncodedString: String { + return [UInt8](utf8).base58EncodedString + } + + public var base58DecodedData: Data? { + let bytes = Base58.bytesFromBase58(self) + return Data(bytes) + } + + public var base58CheckDecodedData: Data? { + guard let bytes = self.base58CheckDecodedBytes else { return nil } + return Data(bytes) + } + + public var base58CheckDecodedBytes: [UInt8]? { + var bytes = Base58.bytesFromBase58(self) + guard 4 <= bytes.count else { return nil } + + let checksum = [UInt8](bytes[bytes.count-4..(_ value: T) -> [UInt8] { + var value = value + return withUnsafeBytes(of: &value) { Array($0) } +} + +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} + return Data(result) +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Data+Extension.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Data+Extension.swift new file mode 100755 index 000000000..fb2d4aeb4 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Data+Extension.swift @@ -0,0 +1,142 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +public extension Data { + + init(fromArray values: [T]) { + var values = values + self.init(buffer: UnsafeBufferPointer(start: &values, count: values.count)) + } + + func toArray(type: T.Type) throws -> [T] { + return try self.withUnsafeBytes { (body: UnsafeRawBufferPointer) in + if let bodyAddress = body.baseAddress, body.count > 0 { + let pointer = bodyAddress.assumingMemoryBound(to: T.self) + return [T](UnsafeBufferPointer(start: pointer, count: self.count/MemoryLayout.stride)) + } else { + throw Web3Error.dataError + } + } + } + + // func toArray(type: T.Type) throws -> [T] { + // return try self.withUnsafeBytes { (body: UnsafeRawBufferPointer) in + // if let bodyAddress = body.baseAddress, body.count > 0 { + // let pointer = bodyAddress.assumingMemoryBound(to: T.self) + // return [T](UnsafeBufferPointer(start: pointer, count: self.count/MemoryLayout.stride)) + // } else { + // throw Web3Error.dataError + // } + // } + // } + + func constantTimeComparisonTo(_ other:Data?) -> Bool { + guard let rhs = other else {return false} + guard self.count == rhs.count else {return false} + var difference = UInt8(0x00) + for i in 0.. Data? { + for _ in 0...1024 { + var data = Data(repeating: 0, count: length) + let result = data.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) -> Int32? in + if let bodyAddress = body.baseAddress, body.count > 0 { + let pointer = bodyAddress.assumingMemoryBound(to: UInt8.self) + return SecRandomCopyBytes(kSecRandomDefault, 32, pointer) + } else { + return nil + } + } + if let notNilResult = result, notNilResult == errSecSuccess { + return data + } + } + return nil + } + + // static func randomBytes(length: Int) -> Data? { + // for _ in 0...1024 { + // var data = Data(repeating: 0, count: length) + // let result = data.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) -> Int32? in + // if let bodyAddress = body.baseAddress, body.count > 0 { + // let pointer = bodyAddress.assumingMemoryBound(to: UInt8.self) + // return SecRandomCopyBytes(kSecRandomDefault, 32, pointer) + // } else { + // return nil + // } + // } + // if let notNilResult = result, notNilResult == errSecSuccess { + // return data + // } + // } + // return nil + // } + + static func fromHex(_ hex: String) -> Data? { + let string = hex.lowercased().stripHexPrefix() + let array = Array(hex: string) + if (array.count == 0) { + if (hex == "0x" || hex == "") { + return Data() + } else { + return nil + } + } + return Data(array) + } + + 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} + 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} + let pointee = padded.withUnsafeBytes { (body: UnsafeRawBufferPointer) in + body.baseAddress?.assumingMemoryBound(to: UInt64.self).pointee + } + guard let ptee = pointee else {return nil} + var uintRepresentation = UInt64(bigEndian: ptee) + uintRepresentation = uintRepresentation << (startingBit % 8) + uintRepresentation = uintRepresentation >> UInt64(64 - length) + return uintRepresentation + } + + // 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} + // 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} + // let pointee = padded.withUnsafeBytes { (body: UnsafeRawBufferPointer) in + // body.baseAddress?.assumingMemoryBound(to: UInt64.self).pointee + // } + // guard let ptee = pointee else {return nil} + // var uintRepresentation = UInt64(bigEndian: ptee) + // uintRepresentation = uintRepresentation << (startingBit % 8) + // uintRepresentation = uintRepresentation >> UInt64(64 - length) + // return uintRepresentation + // } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Decodable+Extensions.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Decodable+Extensions.swift new file mode 100644 index 000000000..59f82fb0a --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Decodable+Extensions.swift @@ -0,0 +1,146 @@ +// +// DecodingContainer+AnyCollection.swift +// AnyDecodable +// +// Created by levantAJ on 1/18/19. +// Copyright © 2019 levantAJ. All rights reserved. +// +import Foundation + +struct AnyCodingKey: CodingKey { + var stringValue: String + var intValue: Int? + + init?(stringValue: String) { + self.stringValue = stringValue + } + + init?(intValue: Int) { + self.intValue = intValue + self.stringValue = String(intValue) + } +} + +extension KeyedDecodingContainer { + /// Decodes a value of the given type for the given key. + /// + /// - parameter type: The type of value to decode. + /// - parameter key: The key that the decoded value is associated with. + /// - returns: A value of the requested type, if present for the given key + /// and convertible to the requested type. + /// - throws: `DecodingError.typeMismatch` if the encountered encoded value + /// is not convertible to the requested type. + /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry + /// for the given key. + /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for + /// the given key. + public func decode(_ type: [Any].Type, forKey key: KeyedDecodingContainer.Key) throws -> [Any] { + var values = try nestedUnkeyedContainer(forKey: key) + return try values.decode(type) + } + + /// Decodes a value of the given type for the given key. + /// + /// - parameter type: The type of value to decode. + /// - parameter key: The key that the decoded value is associated with. + /// - returns: A value of the requested type, if present for the given key + /// and convertible to the requested type. + /// - throws: `DecodingError.typeMismatch` if the encountered encoded value + /// is not convertible to the requested type. + /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry + /// for the given key. + /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for + /// the given key. + public func decode(_ type: [String: Any].Type, forKey key: KeyedDecodingContainer.Key) throws -> [String: Any] { + let values = try nestedContainer(keyedBy: AnyCodingKey.self, forKey: key) + return try values.decode(type) + } + + /// Decodes a value of the given type for the given key, if present. + /// + /// This method returns `nil` if the container does not have a value + /// associated with `key`, or if the value is null. The difference between + /// these states can be distinguished with a `contains(_:)` call. + /// + /// - parameter type: The type of value to decode. + /// - parameter key: The key that the decoded value is associated with. + /// - returns: A decoded value of the requested type, or `nil` if the + /// `Decoder` does not have an entry associated with the given key, or if + /// the value is a null value. + /// - throws: `DecodingError.typeMismatch` if the encountered encoded value + /// is not convertible to the requested type. + public func decodeIfPresent(_ type: [Any].Type, forKey key: KeyedDecodingContainer.Key) throws -> [Any]? { + guard contains(key), + try decodeNil(forKey: key) == false else { return nil } + return try decode(type, forKey: key) + } + + /// Decodes a value of the given type for the given key, if present. + /// + /// This method returns `nil` if the container does not have a value + /// associated with `key`, or if the value is null. The difference between + /// these states can be distinguished with a `contains(_:)` call. + /// + /// - parameter type: The type of value to decode. + /// - parameter key: The key that the decoded value is associated with. + /// - returns: A decoded value of the requested type, or `nil` if the + /// `Decoder` does not have an entry associated with the given key, or if + /// the value is a null value. + /// - throws: `DecodingError.typeMismatch` if the encountered encoded value + /// is not convertible to the requested type. + public func decodeIfPresent(_ type: [String: Any].Type, forKey key: KeyedDecodingContainer.Key) throws -> [String: Any]? { + guard contains(key), + try decodeNil(forKey: key) == false else { return nil } + return try decode(type, forKey: key) + } +} + +private extension KeyedDecodingContainer { + func decode(_ type: [String: Any].Type) throws -> [String: Any] { + var dictionary: [String: Any] = [:] + for key in allKeys { + if try decodeNil(forKey: key) { + dictionary[key.stringValue] = NSNull() + } else if let bool = try? decode(Bool.self, forKey: key) { + dictionary[key.stringValue] = bool + } else if let string = try? decode(String.self, forKey: key) { + dictionary[key.stringValue] = string + } else if let int = try? decode(Int.self, forKey: key) { + dictionary[key.stringValue] = int + } else if let double = try? decode(Double.self, forKey: key) { + dictionary[key.stringValue] = double + } else if let dict = try? decode([String: Any].self, forKey: key) { + dictionary[key.stringValue] = dict + } else if let array = try? decode([Any].self, forKey: key) { + dictionary[key.stringValue] = array + } + } + return dictionary + } +} + +private extension UnkeyedDecodingContainer { + mutating func decode(_ type: [Any].Type) throws -> [Any] { + var elements: [Any] = [] + while !isAtEnd { + if try decodeNil() { + elements.append(NSNull()) + } else if let int = try? decode(Int.self) { + elements.append(int) + } else if let bool = try? decode(Bool.self) { + elements.append(bool) + } else if let double = try? decode(Double.self) { + elements.append(double) + } else if let string = try? decode(String.self) { + elements.append(string) + } else if let values = try? nestedContainer(keyedBy: AnyCodingKey.self), + let element = try? values.decode([String: Any].self) { + elements.append(element) + } else if var values = try? nestedUnkeyedContainer(), + let element = try? values.decode([Any].self) { + elements.append(element) + } + } + return elements + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Dictionary+Extension.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Dictionary+Extension.swift new file mode 100755 index 000000000..ee1a68133 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Dictionary+Extension.swift @@ -0,0 +1,18 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +extension Dictionary where Key == String, Value: Equatable { + func keyForValue(value : Value) -> String? { + for key in self.keys { + if self[key] == value { + return key + } + } + return nil + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Encodable+Extensions.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Encodable+Extensions.swift new file mode 100644 index 000000000..84bad03eb --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/Encodable+Extensions.swift @@ -0,0 +1,130 @@ +// +// EncodingContainer+AnyCollection.swift +// AnyDecodable +// +// Created by ShopBack on 1/19/19. +// Copyright © 2019 levantAJ. All rights reserved. +// +import Foundation + +extension KeyedEncodingContainer { + /// Encodes the given value for the given key. + /// + /// - parameter value: The value to encode. + /// - parameter key: The key to associate the value with. + /// - throws: `EncodingError.invalidValue` if the given value is invalid in + /// the current context for this format. + public mutating func encode(_ value: [String: Any], forKey key: KeyedEncodingContainer.Key) throws { + var container = nestedContainer(keyedBy: AnyCodingKey.self, forKey: key) + try container.encode(value) + } + + /// Encodes the given value for the given key. + /// + /// - parameter value: The value to encode. + /// - parameter key: The key to associate the value with. + /// - throws: `EncodingError.invalidValue` if the given value is invalid in + /// the current context for this format. + public mutating func encode(_ value: [Any], forKey key: KeyedEncodingContainer.Key) throws { + var container = nestedUnkeyedContainer(forKey: key) + try container.encode(value) + } + + /// Encodes the given value for the given key if it is not `nil`. + /// + /// - parameter value: The value to encode. + /// - parameter key: The key to associate the value with. + /// - throws: `EncodingError.invalidValue` if the given value is invalid in + /// the current context for this format. + public mutating func encodeIfPresent(_ value: [String: Any]?, forKey key: KeyedEncodingContainer.Key) throws { + if let value = value { + var container = nestedContainer(keyedBy: AnyCodingKey.self, forKey: key) + try container.encode(value) + } else { + try encodeNil(forKey: key) + } + } + + /// Encodes the given value for the given key if it is not `nil`. + /// + /// - parameter value: The value to encode. + /// - parameter key: The key to associate the value with. + /// - throws: `EncodingError.invalidValue` if the given value is invalid in + /// the current context for this format. + public mutating func encodeIfPresent(_ value: [Any]?, forKey key: KeyedEncodingContainer.Key) throws { + if let value = value { + var container = nestedUnkeyedContainer(forKey: key) + try container.encode(value) + } else { + try encodeNil(forKey: key) + } + } +} + +private extension KeyedEncodingContainer where K == AnyCodingKey { + mutating func encode(_ value: [String: Any]) throws { + for (k, v) in value { + let key = AnyCodingKey(stringValue: k)! + switch v { + case is NSNull: + try encodeNil(forKey: key) + case let string as String: + try encode(string, forKey: key) + case let int as Int: + try encode(int, forKey: key) + case let bool as Bool: + try encode(bool, forKey: key) + case let double as Double: + try encode(double, forKey: key) + case let dict as [String: Any]: + try encode(dict, forKey: key) + case let array as [Any]: + try encode(array, forKey: key) + default: + debugPrint("⚠️ Unsuported type!", v) + continue + } + } + } +} + +private extension UnkeyedEncodingContainer { + /// Encodes the given value. + /// + /// - parameter value: The value to encode. + /// - throws: `EncodingError.invalidValue` if the given value is invalid in + /// the current context for this format. + mutating func encode(_ value: [Any]) throws { + for v in value { + switch v { + case is NSNull: + try encodeNil() + case let string as String: + try encode(string) + case let int as Int: + try encode(int) + case let bool as Bool: + try encode(bool) + case let double as Double: + try encode(double) + case let dict as [String: Any]: + try encode(dict) + case let array as [Any]: + var values = nestedUnkeyedContainer() + try values.encode(array) + default: + debugPrint("⚠️ Unsuported type!", v) + } + } + } + + /// Encodes the given value. + /// + /// - parameter value: The value to encode. + /// - throws: `EncodingError.invalidValue` if the given value is invalid in + /// the current context for this format. + mutating func encode(_ value: [String: Any]) throws { + var container = self.nestedContainer(keyedBy: AnyCodingKey.self) + try container.encode(value) + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/NSRegularExpressionExtension.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/NSRegularExpressionExtension.swift new file mode 100755 index 000000000..1b511a627 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/NSRegularExpressionExtension.swift @@ -0,0 +1,83 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + + +import Foundation + + +extension NSRegularExpression { + typealias GroupNamesSearchResult = (NSTextCheckingResult, NSTextCheckingResult, Int) + + private func textCheckingResultsOfNamedCaptureGroups() -> [String:GroupNamesSearchResult] { + var groupnames = [String:GroupNamesSearchResult]() + + guard let greg = try? NSRegularExpression(pattern: "^\\(\\?<([\\w\\a_-]*)>$", options: NSRegularExpression.Options.dotMatchesLineSeparators) else { + // This never happens but the alternative is to make this method throwing + return groupnames + } + guard let reg = try? NSRegularExpression(pattern: "\\(.*?>", options: NSRegularExpression.Options.dotMatchesLineSeparators) else { + // This never happens but the alternative is to make this method throwing + return groupnames + } + let m = reg.matches(in: self.pattern, options: NSRegularExpression.MatchingOptions.withTransparentBounds, range: NSRange(location: 0, length: self.pattern.utf16.count)) + for (n,g) in m.enumerated() { + let r = self.pattern.range(from: g.range(at: 0)) + let gstring = String(self.pattern[r!]) + let gmatch = greg.matches(in: gstring, options: NSRegularExpression.MatchingOptions.anchored, range: NSRange(location: 0, length: gstring.utf16.count)) + if gmatch.count > 0{ + let r2 = gstring.range(from: gmatch[0].range(at: 1))! + groupnames[String(gstring[r2])] = (g, gmatch[0],n) + } + + } + return groupnames + } + + func indexOfNamedCaptureGroups() throws -> [String:Int] { + var groupnames = [String:Int]() + for (name,(_,_,n)) in self.textCheckingResultsOfNamedCaptureGroups() { + groupnames[name] = n + 1 + } + return groupnames + } + + func rangesOfNamedCaptureGroups(match:NSTextCheckingResult) throws -> [String:Range] { + var ranges = [String:Range]() + for (name,(_,_,n)) in self.textCheckingResultsOfNamedCaptureGroups() { + ranges[name] = Range(match.range(at: n+1)) + } + return ranges + } + + private func nameForIndex(_ index: Int, from: [String:GroupNamesSearchResult]) -> String? { + for (name,(_,_,n)) in from { + if (n + 1) == index { + return name + } + } + return nil + } + + func captureGroups(string: String, options: NSRegularExpression.MatchingOptions = []) -> [String:String] { + return captureGroups(string: string, options: options, range: NSRange(location: 0, length: string.utf16.count)) + } + + func captureGroups(string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> [String:String] { + var dict = [String:String]() + let matchResult = matches(in: string, options: options, range: range) + let names = self.textCheckingResultsOfNamedCaptureGroups() + for (_,m) in matchResult.enumerated() { + for i in (0.. Data? { + let existingLength = UInt64(self.count) + if (existingLength == toBytes) { + return Data(self) + } else if (existingLength > toBytes) { + return nil + } + var data:Data + if (isNegative) { + data = Data(repeating: UInt8(255), count: Int(toBytes - existingLength)) + } else { + data = Data(repeating: UInt8(0), count: Int(toBytes - existingLength)) + } + data.append(self) + return data + } + + func setLengthRight(_ toBytes: UInt64, isNegative:Bool = false ) -> Data? { + let existingLength = UInt64(self.count) + if (existingLength == toBytes) { + return Data(self) + } else if (existingLength > toBytes) { + return nil + } + var data:Data = Data() + data.append(self) + if (isNegative) { + data.append(Data(repeating: UInt8(255), count: Int(toBytes - existingLength))) + } else { + data.append(Data(repeating: UInt8(0), count:Int(toBytes - existingLength))) + } + return data + } +} + +extension BigInt { + func toTwosComplement() -> Data { + if (self.sign == BigInt.Sign.plus) { + return self.magnitude.serialize() + } else { + let serializedLength = self.magnitude.serialize().count + let MAX = BigUInt(1) << (serializedLength*8) + let twoComplement = MAX - self.magnitude + return twoComplement.serialize() + } + } +} + +extension BigUInt { + func abiEncode(bits: UInt64) -> Data? { + let data = self.serialize() + let paddedLength = UInt64(ceil((Double(bits)/8.0))) + let padded = data.setLengthLeft(paddedLength) + return padded + } +} + +extension BigInt { + func abiEncode(bits: UInt64) -> Data? { + let isNegative = self < (BigInt(0)) + let data = self.toTwosComplement() + let paddedLength = UInt64(ceil((Double(bits)/8.0))) + let padded = data.setLengthLeft(paddedLength, isNegative: isNegative) + return padded + } +} + +extension BigInt { + static func fromTwosComplement(data: Data) -> BigInt { + let isPositive = ((data[0] & 128) >> 7) == 0 + if (isPositive) { + let magnitude = BigUInt(data) + return BigInt(magnitude) + } else { + let MAX = (BigUInt(1) << (data.count*8)) + let magnitude = MAX - BigUInt(data) + let bigint = BigInt(0) - BigInt(magnitude) + return bigint + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/RIPEMD160+StackOveflow.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/RIPEMD160+StackOveflow.swift new file mode 100755 index 000000000..df4cfb3c7 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/RIPEMD160+StackOveflow.swift @@ -0,0 +1,534 @@ +// +// RIPEMD160_SO.swift +// web3swift +// +// Created by Alexander Vlasov on 10.01.2018. +// + +//From https://stackoverflow.com/questions/43091858/swift-hash-a-string-using-hash-hmac-with-ripemd160/43191938 + +import Foundation + +public struct RIPEMD160 { + + private var MDbuf: (UInt32, UInt32, UInt32, UInt32, UInt32) + private var buffer: Data + private var count: Int64 // Total # of bytes processed. + + public init() { + MDbuf = (0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0) + buffer = Data() + count = 0 + } + + private mutating func compress(_ X: UnsafePointer) { + + // *** Helper functions (originally macros in rmd160.h) *** + + /* ROL(x, n) cyclically rotates x over n bits to the left */ + /* x must be of an unsigned 32 bits type and 0 <= n < 32. */ + func ROL(_ x: UInt32, _ n: UInt32) -> UInt32 { + return (x << n) | ( x >> (32 - n)) + } + + /* the five basic functions F(), G() and H() */ + + func F(_ x: UInt32, _ y: UInt32, _ z: UInt32) -> UInt32 { + return x ^ y ^ z + } + + func G(_ x: UInt32, _ y: UInt32, _ z: UInt32) -> UInt32 { + return (x & y) | (~x & z) + } + + func H(_ x: UInt32, _ y: UInt32, _ z: UInt32) -> UInt32 { + return (x | ~y) ^ z + } + + func I(_ x: UInt32, _ y: UInt32, _ z: UInt32) -> UInt32 { + return (x & z) | (y & ~z) + } + + func J(_ x: UInt32, _ y: UInt32, _ z: UInt32) -> UInt32 { + return x ^ (y | ~z) + } + + /* the ten basic operations FF() through III() */ + + func FF(_ a: inout UInt32, _ b: UInt32, _ c: inout UInt32, _ d: UInt32, _ e: UInt32, _ x: UInt32, _ s: UInt32) { + a = a &+ F(b, c, d) &+ x + a = ROL(a, s) &+ e + c = ROL(c, 10) + } + + func GG(_ a: inout UInt32, _ b: UInt32, _ c: inout UInt32, _ d: UInt32, _ e: UInt32, _ x: UInt32, _ s: UInt32) { + a = a &+ G(b, c, d) &+ x &+ 0x5a827999 + a = ROL(a, s) &+ e + c = ROL(c, 10) + } + + func HH(_ a: inout UInt32, _ b: UInt32, _ c: inout UInt32, _ d: UInt32, _ e: UInt32, _ x: UInt32, _ s: UInt32) { + a = a &+ H(b, c, d) &+ x &+ 0x6ed9eba1 + a = ROL(a, s) &+ e + c = ROL(c, 10) + } + + func II(_ a: inout UInt32, _ b: UInt32, _ c: inout UInt32, _ d: UInt32, _ e: UInt32, _ x: UInt32, _ s: UInt32) { + a = a &+ I(b, c, d) &+ x &+ 0x8f1bbcdc + a = ROL(a, s) &+ e + c = ROL(c, 10) + } + + func JJ(_ a: inout UInt32, _ b: UInt32, _ c: inout UInt32, _ d: UInt32, _ e: UInt32, _ x: UInt32, _ s: UInt32) { + a = a &+ J(b, c, d) &+ x &+ 0xa953fd4e + a = ROL(a, s) &+ e + c = ROL(c, 10) + } + + func FFF(_ a: inout UInt32, _ b: UInt32, _ c: inout UInt32, _ d: UInt32, _ e: UInt32, _ x: UInt32, _ s: UInt32) { + a = a &+ F(b, c, d) &+ x + a = ROL(a, s) &+ e + c = ROL(c, 10) + } + + func GGG(_ a: inout UInt32, _ b: UInt32, _ c: inout UInt32, _ d: UInt32, _ e: UInt32, _ x: UInt32, _ s: UInt32) { + a = a &+ G(b, c, d) &+ x &+ 0x7a6d76e9 + a = ROL(a, s) &+ e + c = ROL(c, 10) + } + + func HHH(_ a: inout UInt32, _ b: UInt32, _ c: inout UInt32, _ d: UInt32, _ e: UInt32, _ x: UInt32, _ s: UInt32) { + a = a &+ H(b, c, d) &+ x &+ 0x6d703ef3 + a = ROL(a, s) &+ e + c = ROL(c, 10) + } + + func III(_ a: inout UInt32, _ b: UInt32, _ c: inout UInt32, _ d: UInt32, _ e: UInt32, _ x: UInt32, _ s: UInt32) { + a = a &+ I(b, c, d) &+ x &+ 0x5c4dd124 + a = ROL(a, s) &+ e + c = ROL(c, 10) + } + + func JJJ(_ a: inout UInt32, _ b: UInt32, _ c: inout UInt32, _ d: UInt32, _ e: UInt32, _ x: UInt32, _ s: UInt32) { + a = a &+ J(b, c, d) &+ x &+ 0x50a28be6 + a = ROL(a, s) &+ e + c = ROL(c, 10) + } + + // *** The function starts here *** + + var (aa, bb, cc, dd, ee) = MDbuf + var (aaa, bbb, ccc, ddd, eee) = MDbuf + + /* round 1 */ + FF(&aa, bb, &cc, dd, ee, X[ 0], 11) + FF(&ee, aa, &bb, cc, dd, X[ 1], 14) + FF(&dd, ee, &aa, bb, cc, X[ 2], 15) + FF(&cc, dd, &ee, aa, bb, X[ 3], 12) + FF(&bb, cc, &dd, ee, aa, X[ 4], 5) + FF(&aa, bb, &cc, dd, ee, X[ 5], 8) + FF(&ee, aa, &bb, cc, dd, X[ 6], 7) + FF(&dd, ee, &aa, bb, cc, X[ 7], 9) + FF(&cc, dd, &ee, aa, bb, X[ 8], 11) + FF(&bb, cc, &dd, ee, aa, X[ 9], 13) + FF(&aa, bb, &cc, dd, ee, X[10], 14) + FF(&ee, aa, &bb, cc, dd, X[11], 15) + FF(&dd, ee, &aa, bb, cc, X[12], 6) + FF(&cc, dd, &ee, aa, bb, X[13], 7) + FF(&bb, cc, &dd, ee, aa, X[14], 9) + FF(&aa, bb, &cc, dd, ee, X[15], 8) + + /* round 2 */ + GG(&ee, aa, &bb, cc, dd, X[ 7], 7) + GG(&dd, ee, &aa, bb, cc, X[ 4], 6) + GG(&cc, dd, &ee, aa, bb, X[13], 8) + GG(&bb, cc, &dd, ee, aa, X[ 1], 13) + GG(&aa, bb, &cc, dd, ee, X[10], 11) + GG(&ee, aa, &bb, cc, dd, X[ 6], 9) + GG(&dd, ee, &aa, bb, cc, X[15], 7) + GG(&cc, dd, &ee, aa, bb, X[ 3], 15) + GG(&bb, cc, &dd, ee, aa, X[12], 7) + GG(&aa, bb, &cc, dd, ee, X[ 0], 12) + GG(&ee, aa, &bb, cc, dd, X[ 9], 15) + GG(&dd, ee, &aa, bb, cc, X[ 5], 9) + GG(&cc, dd, &ee, aa, bb, X[ 2], 11) + GG(&bb, cc, &dd, ee, aa, X[14], 7) + GG(&aa, bb, &cc, dd, ee, X[11], 13) + GG(&ee, aa, &bb, cc, dd, X[ 8], 12) + + /* round 3 */ + HH(&dd, ee, &aa, bb, cc, X[ 3], 11) + HH(&cc, dd, &ee, aa, bb, X[10], 13) + HH(&bb, cc, &dd, ee, aa, X[14], 6) + HH(&aa, bb, &cc, dd, ee, X[ 4], 7) + HH(&ee, aa, &bb, cc, dd, X[ 9], 14) + HH(&dd, ee, &aa, bb, cc, X[15], 9) + HH(&cc, dd, &ee, aa, bb, X[ 8], 13) + HH(&bb, cc, &dd, ee, aa, X[ 1], 15) + HH(&aa, bb, &cc, dd, ee, X[ 2], 14) + HH(&ee, aa, &bb, cc, dd, X[ 7], 8) + HH(&dd, ee, &aa, bb, cc, X[ 0], 13) + HH(&cc, dd, &ee, aa, bb, X[ 6], 6) + HH(&bb, cc, &dd, ee, aa, X[13], 5) + HH(&aa, bb, &cc, dd, ee, X[11], 12) + HH(&ee, aa, &bb, cc, dd, X[ 5], 7) + HH(&dd, ee, &aa, bb, cc, X[12], 5) + + /* round 4 */ + II(&cc, dd, &ee, aa, bb, X[ 1], 11) + II(&bb, cc, &dd, ee, aa, X[ 9], 12) + II(&aa, bb, &cc, dd, ee, X[11], 14) + II(&ee, aa, &bb, cc, dd, X[10], 15) + II(&dd, ee, &aa, bb, cc, X[ 0], 14) + II(&cc, dd, &ee, aa, bb, X[ 8], 15) + II(&bb, cc, &dd, ee, aa, X[12], 9) + II(&aa, bb, &cc, dd, ee, X[ 4], 8) + II(&ee, aa, &bb, cc, dd, X[13], 9) + II(&dd, ee, &aa, bb, cc, X[ 3], 14) + II(&cc, dd, &ee, aa, bb, X[ 7], 5) + II(&bb, cc, &dd, ee, aa, X[15], 6) + II(&aa, bb, &cc, dd, ee, X[14], 8) + II(&ee, aa, &bb, cc, dd, X[ 5], 6) + II(&dd, ee, &aa, bb, cc, X[ 6], 5) + II(&cc, dd, &ee, aa, bb, X[ 2], 12) + + /* round 5 */ + JJ(&bb, cc, &dd, ee, aa, X[ 4], 9) + JJ(&aa, bb, &cc, dd, ee, X[ 0], 15) + JJ(&ee, aa, &bb, cc, dd, X[ 5], 5) + JJ(&dd, ee, &aa, bb, cc, X[ 9], 11) + JJ(&cc, dd, &ee, aa, bb, X[ 7], 6) + JJ(&bb, cc, &dd, ee, aa, X[12], 8) + JJ(&aa, bb, &cc, dd, ee, X[ 2], 13) + JJ(&ee, aa, &bb, cc, dd, X[10], 12) + JJ(&dd, ee, &aa, bb, cc, X[14], 5) + JJ(&cc, dd, &ee, aa, bb, X[ 1], 12) + JJ(&bb, cc, &dd, ee, aa, X[ 3], 13) + JJ(&aa, bb, &cc, dd, ee, X[ 8], 14) + JJ(&ee, aa, &bb, cc, dd, X[11], 11) + JJ(&dd, ee, &aa, bb, cc, X[ 6], 8) + JJ(&cc, dd, &ee, aa, bb, X[15], 5) + JJ(&bb, cc, &dd, ee, aa, X[13], 6) + + /* parallel round 1 */ + JJJ(&aaa, bbb, &ccc, ddd, eee, X[ 5], 8) + JJJ(&eee, aaa, &bbb, ccc, ddd, X[14], 9) + JJJ(&ddd, eee, &aaa, bbb, ccc, X[ 7], 9) + JJJ(&ccc, ddd, &eee, aaa, bbb, X[ 0], 11) + JJJ(&bbb, ccc, &ddd, eee, aaa, X[ 9], 13) + JJJ(&aaa, bbb, &ccc, ddd, eee, X[ 2], 15) + JJJ(&eee, aaa, &bbb, ccc, ddd, X[11], 15) + JJJ(&ddd, eee, &aaa, bbb, ccc, X[ 4], 5) + JJJ(&ccc, ddd, &eee, aaa, bbb, X[13], 7) + JJJ(&bbb, ccc, &ddd, eee, aaa, X[ 6], 7) + JJJ(&aaa, bbb, &ccc, ddd, eee, X[15], 8) + JJJ(&eee, aaa, &bbb, ccc, ddd, X[ 8], 11) + JJJ(&ddd, eee, &aaa, bbb, ccc, X[ 1], 14) + JJJ(&ccc, ddd, &eee, aaa, bbb, X[10], 14) + JJJ(&bbb, ccc, &ddd, eee, aaa, X[ 3], 12) + JJJ(&aaa, bbb, &ccc, ddd, eee, X[12], 6) + + /* parallel round 2 */ + III(&eee, aaa, &bbb, ccc, ddd, X[ 6], 9) + III(&ddd, eee, &aaa, bbb, ccc, X[11], 13) + III(&ccc, ddd, &eee, aaa, bbb, X[ 3], 15) + III(&bbb, ccc, &ddd, eee, aaa, X[ 7], 7) + III(&aaa, bbb, &ccc, ddd, eee, X[ 0], 12) + III(&eee, aaa, &bbb, ccc, ddd, X[13], 8) + III(&ddd, eee, &aaa, bbb, ccc, X[ 5], 9) + III(&ccc, ddd, &eee, aaa, bbb, X[10], 11) + III(&bbb, ccc, &ddd, eee, aaa, X[14], 7) + III(&aaa, bbb, &ccc, ddd, eee, X[15], 7) + III(&eee, aaa, &bbb, ccc, ddd, X[ 8], 12) + III(&ddd, eee, &aaa, bbb, ccc, X[12], 7) + III(&ccc, ddd, &eee, aaa, bbb, X[ 4], 6) + III(&bbb, ccc, &ddd, eee, aaa, X[ 9], 15) + III(&aaa, bbb, &ccc, ddd, eee, X[ 1], 13) + III(&eee, aaa, &bbb, ccc, ddd, X[ 2], 11) + + /* parallel round 3 */ + HHH(&ddd, eee, &aaa, bbb, ccc, X[15], 9) + HHH(&ccc, ddd, &eee, aaa, bbb, X[ 5], 7) + HHH(&bbb, ccc, &ddd, eee, aaa, X[ 1], 15) + HHH(&aaa, bbb, &ccc, ddd, eee, X[ 3], 11) + HHH(&eee, aaa, &bbb, ccc, ddd, X[ 7], 8) + HHH(&ddd, eee, &aaa, bbb, ccc, X[14], 6) + HHH(&ccc, ddd, &eee, aaa, bbb, X[ 6], 6) + HHH(&bbb, ccc, &ddd, eee, aaa, X[ 9], 14) + HHH(&aaa, bbb, &ccc, ddd, eee, X[11], 12) + HHH(&eee, aaa, &bbb, ccc, ddd, X[ 8], 13) + HHH(&ddd, eee, &aaa, bbb, ccc, X[12], 5) + HHH(&ccc, ddd, &eee, aaa, bbb, X[ 2], 14) + HHH(&bbb, ccc, &ddd, eee, aaa, X[10], 13) + HHH(&aaa, bbb, &ccc, ddd, eee, X[ 0], 13) + HHH(&eee, aaa, &bbb, ccc, ddd, X[ 4], 7) + HHH(&ddd, eee, &aaa, bbb, ccc, X[13], 5) + + /* parallel round 4 */ + GGG(&ccc, ddd, &eee, aaa, bbb, X[ 8], 15) + GGG(&bbb, ccc, &ddd, eee, aaa, X[ 6], 5) + GGG(&aaa, bbb, &ccc, ddd, eee, X[ 4], 8) + GGG(&eee, aaa, &bbb, ccc, ddd, X[ 1], 11) + GGG(&ddd, eee, &aaa, bbb, ccc, X[ 3], 14) + GGG(&ccc, ddd, &eee, aaa, bbb, X[11], 14) + GGG(&bbb, ccc, &ddd, eee, aaa, X[15], 6) + GGG(&aaa, bbb, &ccc, ddd, eee, X[ 0], 14) + GGG(&eee, aaa, &bbb, ccc, ddd, X[ 5], 6) + GGG(&ddd, eee, &aaa, bbb, ccc, X[12], 9) + GGG(&ccc, ddd, &eee, aaa, bbb, X[ 2], 12) + GGG(&bbb, ccc, &ddd, eee, aaa, X[13], 9) + GGG(&aaa, bbb, &ccc, ddd, eee, X[ 9], 12) + GGG(&eee, aaa, &bbb, ccc, ddd, X[ 7], 5) + GGG(&ddd, eee, &aaa, bbb, ccc, X[10], 15) + GGG(&ccc, ddd, &eee, aaa, bbb, X[14], 8) + + /* parallel round 5 */ + FFF(&bbb, ccc, &ddd, eee, aaa, X[12] , 8) + FFF(&aaa, bbb, &ccc, ddd, eee, X[15] , 5) + FFF(&eee, aaa, &bbb, ccc, ddd, X[10] , 12) + FFF(&ddd, eee, &aaa, bbb, ccc, X[ 4] , 9) + FFF(&ccc, ddd, &eee, aaa, bbb, X[ 1] , 12) + FFF(&bbb, ccc, &ddd, eee, aaa, X[ 5] , 5) + FFF(&aaa, bbb, &ccc, ddd, eee, X[ 8] , 14) + FFF(&eee, aaa, &bbb, ccc, ddd, X[ 7] , 6) + FFF(&ddd, eee, &aaa, bbb, ccc, X[ 6] , 8) + FFF(&ccc, ddd, &eee, aaa, bbb, X[ 2] , 13) + FFF(&bbb, ccc, &ddd, eee, aaa, X[13] , 6) + FFF(&aaa, bbb, &ccc, ddd, eee, X[14] , 5) + FFF(&eee, aaa, &bbb, ccc, ddd, X[ 0] , 15) + FFF(&ddd, eee, &aaa, bbb, ccc, X[ 3] , 13) + FFF(&ccc, ddd, &eee, aaa, bbb, X[ 9] , 11) + FFF(&bbb, ccc, &ddd, eee, aaa, X[11] , 11) + + /* combine results */ + MDbuf = (MDbuf.1 &+ cc &+ ddd, + MDbuf.2 &+ dd &+ eee, + MDbuf.3 &+ ee &+ aaa, + MDbuf.4 &+ aa &+ bbb, + MDbuf.0 &+ bb &+ ccc) + } + + public mutating func update(data: Data) throws { + try data.withUnsafeBytes { (body: UnsafeRawBufferPointer) in + if let bodyAddress = body.baseAddress, body.count > 0 { + var ptr = bodyAddress.assumingMemoryBound(to: UInt8.self) + var length = data.count + var X = [UInt32](repeating: 0, count: 16) + + // Process remaining bytes from last call: + if buffer.count > 0 && buffer.count + length >= 64 { + let amount = 64 - buffer.count + buffer.append(ptr, count: amount) + try buffer.withUnsafeBytes { (body: UnsafeRawBufferPointer) in + if let bodyAddress = body.baseAddress, body.count > 0 { + let pointer = bodyAddress.assumingMemoryBound(to: Void.self) + _ = memcpy(&X, pointer, 64) + } else { + throw Web3Error.dataError + } + } + compress(X) + ptr += amount + length -= amount + } + // Process 64 byte chunks: + while length >= 64 { + memcpy(&X, ptr, 64) + compress(X) + ptr += 64 + length -= 64 + } + // Save remaining unprocessed bytes: + buffer = Data(bytes: ptr, count: length) + } else { + throw Web3Error.dataError + } + } + count += Int64(data.count) + } + + public mutating func finalize() throws -> Data { + var X = [UInt32](repeating: 0, count: 16) + /* append the bit m_n == 1 */ + buffer.append(0x80) + try buffer.withUnsafeBytes { (body: UnsafeRawBufferPointer) in + if let bodyAddress = body.baseAddress, body.count > 0 { + let pointer = bodyAddress.assumingMemoryBound(to: Void.self) + _ = memcpy(&X, pointer, buffer.count) + } else { + throw Web3Error.dataError + } + } + + if (count & 63) > 55 { + /* length goes to next block */ + compress(X) + X = [UInt32](repeating: 0, count: 16) + } + + /* append length in bits */ + let lswlen = UInt32(truncatingIfNeeded: count) + let mswlen = UInt32(UInt64(count) >> 32) + X[14] = lswlen << 3 + X[15] = (lswlen >> 29) | (mswlen << 3) + compress(X) + + var data = Data(count: 20) + try data.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) in + if let bodyAddress = body.baseAddress, body.count > 0 { + let pointer = bodyAddress.assumingMemoryBound(to: UInt32.self) + pointer[0] = MDbuf.0 + pointer[1] = MDbuf.1 + pointer[2] = MDbuf.2 + pointer[3] = MDbuf.3 + pointer[4] = MDbuf.4 + } else { + throw Web3Error.dataError + } + } + + buffer = Data() + + return data + } + + // public mutating func update(data: Data) throws { + // try data.withUnsafeBytes { (body: UnsafeRawBufferPointer) in + // + // if let bodyAddress = body.baseAddress, body.count > 0 { + // var ptr = bodyAddress.assumingMemoryBound(to: UInt8.self) + // var length = data.count + // var X = [UInt32](repeating: 0, count: 16) + // + // // Process remaining bytes from last call: + // if buffer.count > 0 && buffer.count + length >= 64 { + // let amount = 64 - buffer.count + // buffer.append(ptr, count: amount) + // try buffer.withUnsafeBytes { (body: UnsafeRawBufferPointer) in + // if let bodyAddress = body.baseAddress, body.count > 0 { + // let pointer = bodyAddress.assumingMemoryBound(to: Void.self) + // _ = memcpy(&X, pointer, 64) + // } else { + // throw Web3Error.dataError + // } + // } + // compress(X) + // ptr += amount + // length -= amount + // } + // // Process 64 byte chunks: + // while length >= 64 { + // memcpy(&X, ptr, 64) + // compress(X) + // ptr += 64 + // length -= 64 + // } + // // Save remaining unprocessed bytes: + // buffer = Data(bytes: ptr, count: length) + // } else { + // throw Web3Error.dataError + // } + // + // } + // count += Int64(data.count) + // } + // + // public mutating func finalize() throws -> Data { + // var X = [UInt32](repeating: 0, count: 16) + // /* append the bit m_n == 1 */ + // buffer.append(0x80) + // try buffer.withUnsafeBytes { (body: UnsafeRawBufferPointer) in + // if let bodyAddress = body.baseAddress, body.count > 0 { + // let pointer = bodyAddress.assumingMemoryBound(to: Void.self) + // _ = memcpy(&X, pointer, buffer.count) + // } else { + // throw Web3Error.dataError + // } + // } + // + // if (count & 63) > 55 { + // /* length goes to next block */ + // compress(X) + // X = [UInt32](repeating: 0, count: 16) + // } + // + // /* append length in bits */ + // let lswlen = UInt32(truncatingIfNeeded: count) + // let mswlen = UInt32(UInt64(count) >> 32) + // X[14] = lswlen << 3 + // X[15] = (lswlen >> 29) | (mswlen << 3) + // compress(X) + // + // var data = Data(count: 20) + // try data.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) in + // if let bodyAddress = body.baseAddress, body.count > 0 { + // let pointer = bodyAddress.assumingMemoryBound(to: UInt32.self) + // pointer[0] = MDbuf.0 + // pointer[1] = MDbuf.1 + // pointer[2] = MDbuf.2 + // pointer[3] = MDbuf.3 + // pointer[4] = MDbuf.4 + // } else { + // throw Web3Error.dataError + // } + // } + // + // buffer = Data() + // + // return data + // } +} + +public extension RIPEMD160 { + + static func hash(message: Data) throws -> Data { + var md = RIPEMD160() + try md.update(data: message) + return try md.finalize() + // return try md.finalize() + } + + static func hash(message: String) throws -> Data { + return try RIPEMD160.hash(message: message.data(using: .utf8)!) + // return try RIPEMD160.hash(message: message.data(using: .utf8)!) + } +} + +public extension RIPEMD160 { + + static func hmac(key: Data, message: Data) throws -> Data { + + var key = key + key.count = 64 // Truncate to 64 bytes or fill-up with zeros. + + // let outerKeyPad = Data(bytes: key.map { $0 ^ 0x5c }) + // let innerKeyPad = Data(bytes: key.map { $0 ^ 0x36 }) + let outerKeyPad = Data(key.map { $0 ^ 0x5c }) + let innerKeyPad = Data(key.map { $0 ^ 0x36 }) + + var innerMd = RIPEMD160() + try innerMd.update(data: innerKeyPad) + try innerMd.update(data: message) + // try innerMd.update(data: innerKeyPad) + // try innerMd.update(data: message) + + var outerMd = RIPEMD160() + try outerMd.update(data: outerKeyPad) + try outerMd.update(data: innerMd.finalize()) + // try outerMd.update(data: outerKeyPad) + // try outerMd.update(data: innerMd.finalize()) + + return try outerMd.finalize() + // return try outerMd.finalize() + } + + static func hmac(key: Data, message: String) throws -> Data { + return try RIPEMD160.hmac(key: key, message: message.data(using: .utf8)!) + // return try RIPEMD160.hmac(key: key, message: message.data(using: .utf8)!) + } + + static func hmac(key: String, message: String) throws -> Data { + return try RIPEMD160.hmac(key: key.data(using: .utf8)!, message: message) + // return try RIPEMD160.hmac(key: key.data(using: .utf8)!, message: message) + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/SECP256k1.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/SECP256k1.swift new file mode 100755 index 000000000..800a44765 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Convenience/SECP256k1.swift @@ -0,0 +1,385 @@ +// +// secp256k1.swift +// secp256k1_swift +// +// Created by Alexander Vlasov on 30.05.2018. +// Copyright © 2018 Alexander Vlasov. All rights reserved. +// + +import Foundation +import secp256k1 + +public struct SECP256K1 { + public struct UnmarshaledSignature{ + public var v: UInt8 = 0 + public var r = Data(repeating: 0, count: 32) + public var s = Data(repeating: 0, count: 32) + + public init(v: UInt8, r: Data, s: Data) { + self.v = v + self.r = r + self.s = s + } + } +} + +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 !SECP256K1.verifyPrivateKey(privateKey: privateKey) { + return (nil, nil) + } + for _ in 0...1024 { + guard var recoverableSignature = SECP256K1.recoverableSign(hash: hash, privateKey: privateKey, useExtraEntropy: useExtraEntropy) else { + continue + } + guard let truePublicKey = SECP256K1.privateKeyToPublicKey(privateKey: privateKey) else {continue} + guard let recoveredPublicKey = SECP256K1.recoverPublicKey(hash: hash, recoverableSignature: &recoverableSignature) else {continue} + if !SECP256K1.constantTimeComparison(Data(toByteArray(truePublicKey.data)), Data(toByteArray(recoveredPublicKey.data))) { + continue + } + guard let serializedSignature = SECP256K1.serializeSignature(recoverableSignature: &recoverableSignature) else {continue} + let rawSignature = Data(toByteArray(recoverableSignature)) + return (serializedSignature, rawSignature) + } + return (nil, nil) + } + + 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} + return serializedKey + } + + public static func combineSerializedPublicKeys(keys: [Data], outputCompressed: Bool = false) -> Data? { + let numToCombine = keys.count + guard numToCombine >= 1 else { return nil} + var storage = ContiguousArray() + let arrayOfPointers = UnsafeMutablePointer< UnsafePointer? >.allocate(capacity: numToCombine) + defer { + arrayOfPointers.deinitialize(count: numToCombine) + arrayOfPointers.deallocate() + } + for i in 0 ..< numToCombine { + let key = keys[i] + guard let pubkey = SECP256K1.parsePublicKey(serializedKey: key) else {return nil} + storage.append(pubkey) + } + for i in 0 ..< numToCombine { + withUnsafePointer(to: &storage[i]) { (ptr) -> Void in + arrayOfPointers.advanced(by: i).pointee = ptr + } + } + 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) + return res + } + if result == 0 { + return nil + } + let serializedKey = SECP256K1.serializePublicKey(publicKey: &publicKey, compressed: outputCompressed) + return serializedKey + } + + + internal static func recoverPublicKey(hash: Data, recoverableSignature: inout secp256k1_ecdsa_recoverable_signature) -> secp256k1_pubkey? { + guard hash.count == 32 else {return nil} + var publicKey: secp256k1_pubkey = secp256k1_pubkey() + 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 res + }) + }) + } else { + return nil + } + }) + guard let res = result, res != 0 else { + return nil + } + return publicKey + } + + internal static func privateKeyToPublicKey(privateKey: Data) -> secp256k1_pubkey? { + 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!, UnsafeMutablePointer(&publicKey), privateKeyPointer) + return res + } else { + return nil + } + } + guard let res = result, res != 0 else { + return nil + } + return publicKey + } + + public static func serializePublicKey(publicKey: inout secp256k1_pubkey, compressed: Bool = false) -> Data? { + 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 res + }) + }) + } else { + return nil + } + } + guard let res = result, res != 0 else { + return nil + } + return Data(serializedPubkey) + } + + internal static func parsePublicKey(serializedKey: Data) -> secp256k1_pubkey? { + guard serializedKey.count == 33 || serializedKey.count == 65 else { + return nil + } + let keyLen: Int = Int(serializedKey.count) + var publicKey = secp256k1_pubkey() + 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!, UnsafeMutablePointer(&publicKey), serializedKeyPointer, keyLen) + return res + } else { + return nil + } + } + guard let res = result, res != 0 else { + return nil + } + return publicKey + } + + public static func parseSignature(signature: Data) -> secp256k1_ecdsa_recoverable_signature? { + guard 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]) + if v >= 27 && v <= 30 { + v -= 27 + } else if v >= 31 && v <= 34 { + v -= 31 + } else if v >= 35 && v <= 38 { + v -= 35 + } + 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 res + }) + } else { + return nil + } + } + guard let res = result, res != 0 else { + return nil + } + return recoverableSignature + } + + internal static func serializeSignature(recoverableSignature: inout secp256k1_ecdsa_recoverable_signature) -> Data? { + 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) + return res + }) + } + } else { + return nil + } + } + guard let res = result, res != 0 else { + return nil + } + if (v == 0 || v == 27 || v == 31 || v == 35) { + serializedSignature.append(0x1b) + } else if (v == 1 || v == 28 || v == 32 || v == 36) { + serializedSignature.append(0x1c) + } else { + return nil + } + return Data(serializedSignature) + } + + internal static func recoverableSign(hash: Data, privateKey: Data, useExtraEntropy: Bool = false) -> secp256k1_ecdsa_recoverable_signature? { + if (hash.count != 32 || privateKey.count != 32) { + return nil + } + if !SECP256K1.verifyPrivateKey(privateKey: privateKey) { + return nil + } + var recoverableSignature: secp256k1_ecdsa_recoverable_signature = secp256k1_ecdsa_recoverable_signature(); + 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 + if let privateKeyRPointer = privateKeyRBPointer.baseAddress, privateKeyRBPointer.count > 0 { + let privateKeyPointer = privateKeyRPointer.assumingMemoryBound(to: UInt8.self) + 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 res + }) + } else { + return nil + } + }) + } else { + return nil + } + }) + } else { + return nil + } + } + guard let res = result, res != 0 else { + print("Failed to sign!") + return nil + } + return recoverableSignature + } + + 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} + return serializedKey + } + + + public static func verifyPrivateKey(privateKey: Data) -> Bool { + if (privateKey.count != 32) {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) + return res + } else { + return nil + } + } + guard let res = result, res == 1 else { + return false + } + return true + } + + public static func generatePrivateKey() -> Data? { + for _ in 0...1024 { + guard let keyData = SECP256K1.randomBytes(length: 32) else { + continue + } + guard SECP256K1.verifyPrivateKey(privateKey: keyData) else { + continue + } + return keyData + } + return nil + } + + public static func unmarshalSignature(signatureData:Data) -> UnmarshaledSignature? { + if (signatureData.count != 65) {return nil} + let v = signatureData[64] + let r = Data(signatureData[0..<32]) + let s = Data(signatureData[32..<64]) + return UnmarshaledSignature(v: v, r: r, s: s) + } + + public static func marshalSignature(v: UInt8, r: [UInt8], s: [UInt8]) -> Data? { + guard r.count == 32, s.count == 32 else {return nil} + var completeSignature = Data(r) + completeSignature.append(Data(s)) + completeSignature.append(Data([v])) + return completeSignature + } + + public static func marshalSignature(v: Data, r: Data, s: Data) -> Data? { + guard r.count == 32, s.count == 32 else {return nil} + var completeSignature = Data(r) + completeSignature.append(s) + completeSignature.append(v) + return completeSignature + } + + internal static func randomBytes(length: Int) -> Data? { + for _ in 0...1024 { + var data = Data(repeating: 0, count: length) + let result = data.withUnsafeMutableBytes { (mutableRBBytes) -> Int32? in + if let mutableRBytes = mutableRBBytes.baseAddress, mutableRBBytes.count > 0 { + let mutableBytes = mutableRBytes.assumingMemoryBound(to: UInt8.self) + return SecRandomCopyBytes(kSecRandomDefault, 32, mutableBytes) + } else { + return nil + } + } + if let res = result, res == errSecSuccess { + return data + } else { + continue + } + } + return nil + } + + internal static func toByteArray(_ value: T) -> [UInt8] { + var value = value + return withUnsafeBytes(of: &value) { Array($0) } + } + + internal static func fromByteArray(_ value: [UInt8], _: T.Type) -> T { + return value.withUnsafeBytes { + $0.baseAddress!.load(as: T.self) + } + } + + internal static func constantTimeComparison(_ lhs: Data, _ rhs:Data) -> Bool { + guard lhs.count == rhs.count else {return false} + var difference = UInt8(0x00) + for i in 0.. { + return startIndex.. Index? { + guard let range = range(of: String(char)) else { + return nil + } + return range.lowerBound + } + + func split(intoChunksOf chunkSize: Int) -> [String] { + var output = [String]() + let splittedString = self + .map { $0 } + .split(intoChunksOf: chunkSize) + splittedString.forEach { + output.append($0.map { String($0) }.joined(separator: "")) + } + return output + } + + subscript (bounds: CountableClosedRange) -> String { + let start = index(self.startIndex, offsetBy: bounds.lowerBound) + let end = index(self.startIndex, offsetBy: bounds.upperBound) + return String(self[start...end]) + } + + subscript (bounds: CountableRange) -> String { + let start = index(self.startIndex, offsetBy: bounds.lowerBound) + let end = index(self.startIndex, offsetBy: bounds.upperBound) + return String(self[start..) -> String { + let start = index(self.startIndex, offsetBy: bounds.lowerBound) + let end = self.endIndex + return String(self[start.. String { + let stringLength = self.count + if stringLength < toLength { + return String(repeatElement(character, count: toLength - stringLength)) + self + } else { + return String(self.suffix(toLength)) + } + } + + func interpretAsBinaryData() -> Data? { + let padded = self.padding(toLength: ((self.count + 7) / 8) * 8, withPad: "0", startingAt: 0) + let byteArray = padded.split(intoChunksOf: 8).map { UInt8(strtoul($0, nil, 2)) } + return Data(byteArray) + } + + func hasHexPrefix() -> Bool { + return self.hasPrefix("0x") + } + + func stripHexPrefix() -> String { + if self.hasPrefix("0x") { + let indexStart = self.index(self.startIndex, offsetBy: 2) + return String(self[indexStart...]) + } + return self + } + + func addHexPrefix() -> String { + if !self.hasPrefix("0x") { + return "0x" + self + } + return self + } + + func stripLeadingZeroes() -> String? { + let hex = self.addHexPrefix() + guard let matcher = try? NSRegularExpression(pattern: "^(?0x)0*(?[0-9a-fA-F]*)$", options: NSRegularExpression.Options.dotMatchesLineSeparators) else {return nil} + let match = matcher.captureGroups(string: hex, options: NSRegularExpression.MatchingOptions.anchored) + guard let prefix = match["prefix"] else {return nil} + guard let end = match["end"] else {return nil} + if (end != "") { + return prefix + end + } + return "0x0" + } + + func matchingStrings(regex: String) -> [[String]] { + guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] } + let nsString = self as NSString + let results = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length)) + return results.map { result in + (0.. Range? { + guard + let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex), + let to16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location + nsRange.length, limitedBy: utf16.endIndex), + let from = from16.samePosition(in: self), + let to = to16.samePosition(in: self) + else { return nil } + return from ..< to + } + + var asciiValue: Int { + get { + let s = self.unicodeScalars + return Int(s[s.startIndex].value) + } + } +} + +extension Character { + var asciiValue: Int { + get { + let s = String(self).unicodeScalars + return Int(s[s.startIndex].value) + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABI.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABI.swift new file mode 100755 index 000000000..d139fd3b0 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABI.swift @@ -0,0 +1,28 @@ +// +// Created by Alex Vlasov on 25/10/2018. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +public struct ABI { + +} + +protocol ABIElementPropertiesProtocol { + var isStatic: Bool {get} + var isArray: Bool {get} + var isTuple: Bool {get} + var arraySize: ABI.Element.ArraySize {get} + var subtype: ABI.Element.ParameterType? {get} + var memoryUsage: UInt64 {get} + var emptyValue: Any {get} +} + +protocol ABIEncoding { + var abiRepresentation: String {get} +} + +protocol ABIValidation { + var isValid: Bool {get} +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABIDecoding.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABIDecoding.swift new file mode 100755 index 000000000..eae5c332b --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABIDecoding.swift @@ -0,0 +1,286 @@ +// +// Created by Alex Vlasov on 25/10/2018. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt + +public struct ABIDecoder { + +} + +extension ABIDecoder { + public static func decode(types: [ABI.Element.InOut], data: Data) -> [AnyObject]? { + let params = types.compactMap { (el) -> ABI.Element.ParameterType in + return el.type + } + return decode(types: params, data: data) + } + + public static func decode(types: [ABI.Element.ParameterType], data: Data) -> [AnyObject]? { + // print("Full data: \n" + data.toHexString()) + var toReturn = [AnyObject]() + var consumed: UInt64 = 0 + for i in 0 ..< types.count { + let (v, c) = decodeSignleType(type: types[i], data: data, pointer: consumed) + guard let valueUnwrapped = v, let consumedUnwrapped = c else {return nil} + toReturn.append(valueUnwrapped) + consumed = consumed + consumedUnwrapped + } + guard toReturn.count == types.count else {return nil} + return toReturn + } + + public static func decodeSignleType(type: ABI.Element.ParameterType, data: Data, pointer: UInt64 = 0) -> (value: AnyObject?, bytesConsumed: UInt64?) { + let (elData, nextPtr) = followTheData(type: type, data: data, pointer: pointer) + guard let elementItself = elData, let nextElementPointer = nextPtr else { + return (nil, nil) + } + switch type { + case .uint(let bits): + // print("Uint256 element itself: \n" + elementItself.toHexString()) + guard elementItself.count >= 32 else {break} + let mod = BigUInt(1) << bits + let dataSlice = elementItself[0 ..< 32] + let v = BigUInt(dataSlice) % mod + // print("Uint256 element is: \n" + String(v)) + return (v as AnyObject, type.memoryUsage) + case .int(let bits): + // print("Int256 element itself: \n" + elementItself.toHexString()) + guard elementItself.count >= 32 else {break} + let mod = BigInt(1) << bits + let dataSlice = elementItself[0 ..< 32] + let v = BigInt.fromTwosComplement(data: dataSlice) % mod + // print("Int256 element is: \n" + String(v)) + return (v as AnyObject, type.memoryUsage) + case .address: + // print("Address element itself: \n" + elementItself.toHexString()) + guard elementItself.count >= 32 else {break} + let dataSlice = elementItself[12 ..< 32] + let address = EthereumAddress(dataSlice) + // print("Address element is: \n" + String(address.address)) + return (address as AnyObject, type.memoryUsage) + case .bool: + // print("Bool element itself: \n" + elementItself.toHexString()) + guard elementItself.count >= 32 else {break} + let dataSlice = elementItself[0 ..< 32] + let v = BigUInt(dataSlice) + // print("Address element is: \n" + String(v)) + if v == BigUInt(36) || + v == BigUInt(32) || + v == BigUInt(28) || + v == BigUInt(1) { + return (true as AnyObject, type.memoryUsage) + } else if v == BigUInt(35) || + v == BigUInt(31) || + v == BigUInt(27) || + v == BigUInt(0) { + return (false as AnyObject, type.memoryUsage) + } + case .bytes(let length): + // print("Bytes32 element itself: \n" + elementItself.toHexString()) + guard elementItself.count >= 32 else {break} + let dataSlice = elementItself[0 ..< length] + // print("Bytes32 element is: \n" + String(dataSlice.toHexString())) + return (dataSlice as AnyObject, type.memoryUsage) + case .string: + // print("String element itself: \n" + elementItself.toHexString()) + guard elementItself.count >= 32 else {break} + var dataSlice = elementItself[0 ..< 32] + let length = UInt64(BigUInt(dataSlice)) + guard elementItself.count >= 32+length else {break} + dataSlice = elementItself[32 ..< 32 + length] + guard let string = String(data: dataSlice, encoding: .utf8) else {break} + // print("String element is: \n" + String(string)) + return (string as AnyObject, type.memoryUsage) + case .dynamicBytes: + // print("Bytes element itself: \n" + elementItself.toHexString()) + guard elementItself.count >= 32 else {break} + var dataSlice = elementItself[0 ..< 32] + let length = UInt64(BigUInt(dataSlice)) + guard elementItself.count >= 32+length else {break} + dataSlice = elementItself[32 ..< 32 + length] + // print("Bytes element is: \n" + String(dataSlice.toHexString())) + return (dataSlice as AnyObject, type.memoryUsage) + case .array(type: let subType, length: let length): + switch type.arraySize { + case .dynamicSize: + // print("Dynamic array element itself: \n" + elementItself.toHexString()) + if subType.isStatic { + // uint[] like, expect length and elements + guard elementItself.count >= 32 else {break} + var dataSlice = elementItself[0 ..< 32] + let length = UInt64(BigUInt(dataSlice)) + guard elementItself.count >= 32 + subType.memoryUsage*length else {break} + dataSlice = elementItself[32 ..< 32 + subType.memoryUsage*length] + var subpointer: UInt64 = 32; + var toReturn = [AnyObject]() + for _ in 0 ..< length { + let (v, c) = decodeSignleType(type: subType, data: elementItself, pointer: subpointer) + guard let valueUnwrapped = v, let consumedUnwrapped = c else {break} + toReturn.append(valueUnwrapped) + subpointer = subpointer + consumedUnwrapped + } + return (toReturn as AnyObject, type.memoryUsage) + } else { + // in principle is true for tuple[], so will work for string[] too + guard elementItself.count >= 32 else {break} + var dataSlice = elementItself[0 ..< 32] + let length = UInt64(BigUInt(dataSlice)) + guard elementItself.count >= 32 else {break} + dataSlice = Data(elementItself[32 ..< elementItself.count]) + var subpointer: UInt64 = 0; + var toReturn = [AnyObject]() + // print("Dynamic array sub element itself: \n" + dataSlice.toHexString()) + for _ in 0 ..< length { + let (v, c) = decodeSignleType(type: subType, data: dataSlice, pointer: subpointer) + guard let valueUnwrapped = v, let consumedUnwrapped = c else {break} + toReturn.append(valueUnwrapped) + subpointer = subpointer + consumedUnwrapped + } + return (toReturn as AnyObject, nextElementPointer) + } + case .staticSize(let staticLength): + // print("Static array element itself: \n" + elementItself.toHexString()) + guard length == staticLength else {break} + var toReturn = [AnyObject]() + var consumed:UInt64 = 0 + for _ in 0 ..< length { + let (v, c) = decodeSignleType(type: subType, data: elementItself, pointer: consumed) + guard let valueUnwrapped = v, let consumedUnwrapped = c else {return (nil, nil)} + toReturn.append(valueUnwrapped) + consumed = consumed + consumedUnwrapped + } + if subType.isStatic { + return (toReturn as AnyObject, consumed) + } else { + return (toReturn as AnyObject, nextElementPointer) + } + case .notArray: + break + } + case .tuple(types: let subTypes): + // print("Tuple element itself: \n" + elementItself.toHexString()) + var toReturn = [AnyObject]() + var consumed:UInt64 = 0 + for i in 0 ..< subTypes.count { + let (v, c) = decodeSignleType(type: subTypes[i], data: elementItself, pointer: consumed) + guard let valueUnwrapped = v, let consumedUnwrapped = c else {return (nil, nil)} + toReturn.append(valueUnwrapped) + consumed = consumed + consumedUnwrapped + } + // print("Tuple element is: \n" + String(describing: toReturn)) + if type.isStatic { + return (toReturn as AnyObject, consumed) + } else { + return (toReturn as AnyObject, nextElementPointer) + } + case .function: + // print("Function element itself: \n" + elementItself.toHexString()) + guard elementItself.count >= 32 else {break} + let dataSlice = elementItself[8 ..< 32] + // print("Function element is: \n" + String(dataSlice.toHexString())) + return (dataSlice as AnyObject, type.memoryUsage) + } + return (nil, nil) + } + + fileprivate static func followTheData(type: ABI.Element.ParameterType, data: Data, pointer: UInt64 = 0) -> (elementEncoding: Data?, nextElementPointer: UInt64?) { + // print("Follow the data: \n" + data.toHexString()) + // print("At pointer: \n" + String(pointer)) + if type.isStatic { + guard data.count >= pointer + type.memoryUsage else {return (nil, nil)} + let elementItself = data[pointer ..< pointer + type.memoryUsage] + let nextElement = pointer + type.memoryUsage + // print("Got element itself: \n" + elementItself.toHexString()) + // print("Next element pointer: \n" + String(nextElement)) + return (Data(elementItself), nextElement) + } else { + guard data.count >= pointer + type.memoryUsage else {return (nil, nil)} + let dataSlice = data[pointer ..< pointer + type.memoryUsage] + let bn = BigUInt(dataSlice) + if bn > UINT64_MAX || bn >= data.count { + // there are ERC20 contracts that use bytes32 intead of string. Let's be optimistic and return some data + if case .string = type { + let nextElement = pointer + type.memoryUsage + let preambula = BigUInt(32).abiEncode(bits: 256)! + return (preambula + Data(dataSlice), nextElement) + } else if case .dynamicBytes = type { + let nextElement = pointer + type.memoryUsage + let preambula = BigUInt(32).abiEncode(bits: 256)! + return (preambula + Data(dataSlice), nextElement) + } + return (nil, nil) + } + let elementPointer = UInt64(bn) + let elementItself = data[elementPointer ..< UInt64(data.count)] + let nextElement = pointer + type.memoryUsage + // print("Got element itself: \n" + elementItself.toHexString()) + // print("Next element pointer: \n" + String(nextElement)) + return (Data(elementItself), nextElement) + } + } + + public static func decodeLog(event: ABI.Element.Event, eventLogTopics: [Data], eventLogData: Data) -> [String:Any]? { + if event.topic != eventLogTopics[0] && !event.anonymous { + return nil + } + var eventContent = [String: Any]() + eventContent["name"]=event.name + let logs = eventLogTopics + let dataForProcessing = eventLogData + let indexedInputs = event.inputs.filter { (inp) -> Bool in + return inp.indexed + } + if (logs.count == 1 && indexedInputs.count > 0) { + return nil + } + let nonIndexedInputs = event.inputs.filter { (inp) -> Bool in + return !inp.indexed + } + let nonIndexedTypes = nonIndexedInputs.compactMap { (inp) -> ABI.Element.ParameterType in + return inp.type + } + guard logs.count == indexedInputs.count + 1 else {return nil} + var indexedValues = [AnyObject]() + 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.decodeSignleType(type: .bytes(length: 32), data: data) + guard let valueUnwrapped = v else {return nil} + indexedValues.append(valueUnwrapped) + } else { + let (v, _) = ABIDecoder.decodeSignleType(type: input.type, data: data) + 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} + var indexedInputCounter = 0 + var nonIndexedInputCounter = 0 + for i in 0 ..< event.inputs.count { + let el = event.inputs[i] + if el.indexed { + let name = "\(i)" + let value = indexedValues[indexedInputCounter] + eventContent[name] = value + if el.name != "" { + eventContent[el.name] = value + } + indexedInputCounter = indexedInputCounter + 1 + } else { + let name = "\(i)" + let value = nonIndexedValues[nonIndexedInputCounter] + eventContent[name] = value + if el.name != "" { + eventContent[el.name] = value + } + nonIndexedInputCounter = nonIndexedInputCounter + 1 + } + } + return eventContent + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABIElements.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABIElements.swift new file mode 100755 index 000000000..7f76012f6 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABIElements.swift @@ -0,0 +1,286 @@ +// +// Created by Alex Vlasov on 25/10/2018. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt + +public extension ABI { + // JSON Decoding + struct Input: Decodable { + public var name: String? + public var type: String + public var indexed: Bool? + public var components: [Input]? + } + + struct Output: Decodable { + public var name: String? + public var type: String + public var components: [Output]? + } + + struct Record: Decodable { + public var name: String? + public var type: String? + public var payable: Bool? + public var constant: Bool? + public var stateMutability: String? + public var inputs: [ABI.Input]? + public var outputs: [ABI.Output]? + public var anonymous: Bool? + } + + enum Element { + public enum ArraySize { //bytes for convenience + case staticSize(UInt64) + case dynamicSize + case notArray + } + + case function(Function) + case constructor(Constructor) + case fallback(Fallback) + case event(Event) + + public enum StateMutability { + case payable + case mutating + case view + case pure + + var isConstant: Bool { + switch self { + case .payable: + return false + case .mutating: + return false + default: + return true + } + } + + var isPayable: Bool { + switch self { + case .payable: + return true + default: + return false + } + } + } + + public struct InOut { + public let name: String + public let type: ParameterType + + public init(name: String, type: ParameterType) { + self.name = name + self.type = type + } + } + + public struct Function { + public let name: String? + public let inputs: [InOut] + public let outputs: [InOut] + public let stateMutability: StateMutability? = nil + public let constant: Bool + public let payable: Bool + + public init(name: String?, inputs: [InOut], outputs: [InOut], constant: Bool, payable: Bool) { + self.name = name + self.inputs = inputs + self.outputs = outputs + self.constant = constant + self.payable = payable + } + } + + public struct Constructor { + public let inputs: [InOut] + public let constant: Bool + public let payable: Bool + public init(inputs: [InOut], constant: Bool, payable: Bool) { + self.inputs = inputs + self.constant = constant + self.payable = payable + } + } + + public struct Fallback { + public let constant: Bool + public let payable: Bool + + public init(constant: Bool, payable: Bool) { + self.constant = constant + self.payable = payable + } + } + + public struct Event { + public let name: String + public let inputs: [Input] + public let anonymous: Bool + + public init(name: String, inputs: [Input], anonymous: Bool) { + self.name = name + self.inputs = inputs + self.anonymous = anonymous + } + + public struct Input { + public let name: String + public let type: ParameterType + public let indexed: Bool + + public init(name: String, type: ParameterType, indexed: Bool) { + self.name = name + self.type = type + self.indexed = indexed + } + } + } + } +} + +extension ABI.Element { + public func encodeParameters(_ parameters: [AnyObject]) -> Data? { + switch self { + case .constructor(let constructor): + guard parameters.count == constructor.inputs.count else {return nil} + guard let data = ABIEncoder.encode(types: constructor.inputs, values: parameters) else {return nil} + return data + case .event(_): + return nil + case .fallback(_): + return nil + case .function(let function): + guard parameters.count == function.inputs.count else {return nil} + let signature = function.methodEncoding + guard let data = ABIEncoder.encode(types: function.inputs, values: parameters) else {return nil} + return signature + data + } + } +} + +extension ABI.Element { + public func decodeReturnData(_ data: Data) -> [String:Any]? { + switch self { + case .constructor(_): + return nil + case .event(_): + return nil + case .fallback(_): + return nil + case .function(let function): + if (data.count == 0 && function.outputs.count == 1) { + let name = "0" + let value = function.outputs[0].type.emptyValue + var returnArray = [String:Any]() + returnArray[name] = value + if function.outputs[0].name != "" { + returnArray[function.outputs[0].name] = value + } + return returnArray + } + + guard function.outputs.count*32 <= data.count else {return nil} + var returnArray = [String:Any]() + var i = 0; + guard let values = ABIDecoder.decode(types: function.outputs, data: data) else {return nil} + for output in function.outputs { + let name = "\(i)" + returnArray[name] = values[i] + if output.name != "" { + returnArray[output.name] = values[i] + } + i = i + 1 + } + return returnArray + } + } + + public func decodeInputData(_ rawData: Data) -> [String: Any]? { + var data = rawData + var sig: Data? = nil + switch rawData.count % 32 { + case 0: + break + case 4: + sig = rawData[0 ..< 4] + data = Data(rawData[4 ..< rawData.count]) + default: + return nil + } + switch self { + case .constructor(let function): + if (data.count == 0 && function.inputs.count == 1) { + let name = "0" + let value = function.inputs[0].type.emptyValue + var returnArray = [String:Any]() + returnArray[name] = value + if function.inputs[0].name != "" { + returnArray[function.inputs[0].name] = value + } + return returnArray + } + + guard function.inputs.count*32 <= data.count else {return nil} + var returnArray = [String:Any]() + var i = 0; + guard let values = ABIDecoder.decode(types: function.inputs, data: data) else {return nil} + for input in function.inputs { + let name = "\(i)" + returnArray[name] = values[i] + if input.name != "" { + returnArray[input.name] = values[i] + } + i = i + 1 + } + return returnArray + case .event(_): + return nil + case .fallback(_): + return nil + case .function(let function): + if sig != nil && sig != function.methodEncoding { + return nil + } + if (data.count == 0 && function.inputs.count == 1) { + let name = "0" + let value = function.inputs[0].type.emptyValue + var returnArray = [String:Any]() + returnArray[name] = value + if function.inputs[0].name != "" { + returnArray[function.inputs[0].name] = value + } + return returnArray + } + + guard function.inputs.count*32 <= data.count else {return nil} + var returnArray = [String:Any]() + var i = 0; + guard let values = ABIDecoder.decode(types: function.inputs, data: data) else {return nil} + for input in function.inputs { + let name = "\(i)" + returnArray[name] = values[i] + if input.name != "" { + returnArray[input.name] = values[i] + } + i = i + 1 + } + return returnArray + } + } +} + +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} + return eventContent + } +} + + diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABIEncoding.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABIEncoding.swift new file mode 100755 index 000000000..16c358f91 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABIEncoding.swift @@ -0,0 +1,388 @@ +// +// Created by Alex Vlasov on 25/10/2018. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt + +public struct ABIEncoder { + +} + +extension ABIEncoder { + public static func convertToBigUInt(_ value: AnyObject) -> BigUInt? { + switch value { + case let v as BigUInt: + return v + case let v as BigInt: + switch v.sign { + case .minus: + return nil + case .plus: + return v.magnitude + } + case let v as String: + let base10 = BigUInt(v, radix: 10) + if base10 != nil { + return base10! + } + let base16 = BigUInt(v.stripHexPrefix(), radix: 16) + if base16 != nil { + return base16! + } + break + case let v as UInt: + return BigUInt(v) + case let v as UInt8: + return BigUInt(v) + case let v as UInt16: + return BigUInt(v) + case let v as UInt32: + return BigUInt(v) + case let v as UInt64: + return BigUInt(v) + case let v as Int: + return BigUInt(v) + case let v as Int8: + return BigUInt(v) + case let v as Int16: + return BigUInt(v) + case let v as Int32: + return BigUInt(v) + case let v as Int64: + return BigUInt(v) + default: + return nil + } + return nil + } + + public static func convertToBigInt(_ value: AnyObject) -> BigInt? { + switch value { + case let v as BigUInt: + return BigInt(v) + case let v as BigInt: + return v + case let v as String: + let base10 = BigInt(v, radix: 10) + if base10 != nil { + return base10 + } + let base16 = BigInt(v.stripHexPrefix(), radix: 16) + if base16 != nil { + return base16 + } + break + case let v as UInt: + return BigInt(v) + case let v as UInt8: + return BigInt(v) + case let v as UInt16: + return BigInt(v) + case let v as UInt32: + return BigInt(v) + case let v as UInt64: + return BigInt(v) + case let v as Int: + return BigInt(v) + case let v as Int8: + return BigInt(v) + case let v as Int16: + return BigInt(v) + case let v as Int32: + return BigInt(v) + case let v as Int64: + return BigInt(v) + default: + return nil + } + return nil + } + + public static func convertToData(_ value: AnyObject) -> Data? { + switch value { + case let d as Data: + return d + case let d as String: + if d.hasHexPrefix() { + let hex = Data.fromHex(d) + if hex != nil { + return hex + } + } + let str = d.data(using: .utf8) + if str != nil { + return str + } + case let d as [UInt8]: + return Data(d) + case let d as EthereumAddress: + return d.addressData + case let d as [IntegerLiteralType]: + var bytesArray = [UInt8]() + for el in d { + guard el >= 0, el <= 255 else {return nil} + bytesArray.append(UInt8(el)) + } + return Data(bytesArray) + default: + return nil + } + return nil + } + + + public static func encode(types: [ABI.Element.InOut], values: [AnyObject]) -> Data? { + guard types.count == values.count else {return nil} + let params = types.compactMap { (el) -> ABI.Element.ParameterType in + return el.type + } + return encode(types: params, values: values) + } + + public static func encode(types: [ABI.Element.ParameterType], values: [AnyObject]) -> Data? { + 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} + if types[i].isStatic { + heads.append(encoding) + tails.append(Data()) + } else { + heads.append(Data(repeating: 0x0, count: 32)) + tails.append(encoding) + } + } + var headsConcatenated = Data() + for h in heads { + headsConcatenated.append(h) + } + var tailsPointer = BigUInt(headsConcatenated.count) + headsConcatenated = Data() + var tailsConcatenated = Data() + for i in 0 ..< types.count { + let head = heads[i] + let tail = tails[i] + if !types[i].isStatic { + guard let newHead = tailsPointer.abiEncode(bits: 256) else {return nil} + headsConcatenated.append(newHead) + tailsConcatenated.append(tail) + tailsPointer = tailsPointer + BigUInt(tail.count) + } else { + headsConcatenated.append(head) + tailsConcatenated.append(tail) + } + } + return headsConcatenated + tailsConcatenated + } + + public static func encodeSingleType(type: ABI.Element.ParameterType, value: AnyObject) -> Data? { + switch type { + case .uint(_): + if let biguint = convertToBigUInt(value) { + return biguint.abiEncode(bits: 256) + } + if let bigint = convertToBigInt(value) { + return bigint.abiEncode(bits: 256) + } + case .int(_): + if let biguint = convertToBigUInt(value) { + return biguint.abiEncode(bits: 256) + } + if let bigint = convertToBigInt(value) { + return bigint.abiEncode(bits: 256) + } + case .address: + if let string = value as? String { + guard let address = EthereumAddress(string) else {return nil} + let data = address.addressData + return data.setLengthLeft(32) + } else if let address = value as? EthereumAddress { + guard address.isValid else {break} + let data = address.addressData + return data.setLengthLeft(32) + } else if let data = value as? Data { + return data.setLengthLeft(32) + } + case .bool: + if let bool = value as? Bool { + if (bool) { + return BigUInt(1).abiEncode(bits: 256) + } else { + return BigUInt(0).abiEncode(bits: 256) + } + } + case .bytes(let length): + guard let data = convertToData(value) else {break} + if data.count > length {break} + return data.setLengthRight(32) + case .string: + if let string = value as? String { + var dataGuess: Data? + if string.hasHexPrefix() { + dataGuess = Data.fromHex(string.lowercased().stripHexPrefix()) + } + else { + dataGuess = string.data(using: .utf8) + } + guard let data = dataGuess else {break} + let minLength = ((data.count + 31) / 32)*32 + guard let paddedData = data.setLengthRight(UInt64(minLength)) else {break} + let length = BigUInt(data.count) + guard let head = length.abiEncode(bits: 256) else {break} + let total = head+paddedData + return total + } + case .dynamicBytes: + guard let data = convertToData(value) else {break} + let minLength = ((data.count + 31) / 32)*32 + guard let paddedData = data.setLengthRight(UInt64(minLength)) else {break} + let length = BigUInt(data.count) + guard let head = length.abiEncode(bits: 256) else {break} + let total = head+paddedData + return total + case .array(type: let subType, length: let length): + switch type.arraySize { + case .dynamicSize: + guard length == 0 else {break} + guard let val = value as? [AnyObject] else {break} + guard let lengthEncoding = BigUInt(val.count).abiEncode(bits: 256) else {break} + if subType.isStatic { + // work in a previous context + var toReturn = Data() + for i in 0 ..< val.count { + let enc = encodeSingleType(type: subType, value: val[i]) + guard let encoding = enc else {break} + toReturn.append(encoding) + } + let total = lengthEncoding + toReturn + // print("Dynamic array of static types encoding :\n" + String(total.toHexString())) + return total + } else { + // create new context + var tails = [Data]() + var heads = [Data]() + for i in 0 ..< val.count { + let enc = encodeSingleType(type: subType, value: val[i]) + guard let encoding = enc else {return nil} + heads.append(Data(repeating: 0x0, count: 32)) + tails.append(encoding) + } + var headsConcatenated = Data() + for h in heads { + headsConcatenated.append(h) + } + var tailsPointer = BigUInt(headsConcatenated.count) + headsConcatenated = Data() + var tailsConcatenated = Data() + for i in 0 ..< val.count { + let head = heads[i] + let tail = tails[i] + if tail != Data() { + guard let newHead = tailsPointer.abiEncode(bits: 256) else {return nil} + headsConcatenated.append(newHead) + tailsConcatenated.append(tail) + tailsPointer = tailsPointer + BigUInt(tail.count) + } else { + headsConcatenated.append(head) + tailsConcatenated.append(tail) + } + } + let total = lengthEncoding + headsConcatenated + tailsConcatenated + // print("Dynamic array of dynamic types encoding :\n" + String(total.toHexString())) + return total + } + case .staticSize(let staticLength): + guard staticLength != 0 else {break} + guard let val = value as? [AnyObject] else {break} + guard staticLength == val.count else {break} + if subType.isStatic { + // work in a previous context + var toReturn = Data() + for i in 0 ..< val.count { + let enc = encodeSingleType(type: subType, value: val[i]) + guard let encoding = enc else {break} + toReturn.append(encoding) + } + // print("Static array of static types encoding :\n" + String(toReturn.toHexString())) + let total = toReturn + return total + } else { + // create new context + var tails = [Data]() + var heads = [Data]() + for i in 0 ..< val.count { + let enc = encodeSingleType(type: subType, value: val[i]) + guard let encoding = enc else {return nil} + heads.append(Data(repeating: 0x0, count: 32)) + tails.append(encoding) + } + var headsConcatenated = Data() + for h in heads { + headsConcatenated.append(h) + } + var tailsPointer = BigUInt(headsConcatenated.count) + headsConcatenated = Data() + var tailsConcatenated = Data() + for i in 0 ..< val.count { + let tail = tails[i] + guard let newHead = tailsPointer.abiEncode(bits: 256) else {return nil} + headsConcatenated.append(newHead) + tailsConcatenated.append(tail) + tailsPointer = tailsPointer + BigUInt(tail.count) + } + let total = headsConcatenated + tailsConcatenated + // print("Static array of dynamic types encoding :\n" + String(total.toHexString())) + return total + } + case .notArray: + break + } + case .tuple(types: let subTypes): + var tails = [Data]() + var heads = [Data]() + guard let val = value as? [AnyObject] else {break} + for i in 0 ..< subTypes.count { + let enc = encodeSingleType(type: subTypes[i], value: val[i]) + guard let encoding = enc else {return nil} + if subTypes[i].isStatic { + heads.append(encoding) + tails.append(Data()) + } else { + heads.append(Data(repeating: 0x0, count: 32)) + tails.append(encoding) + } + } + var headsConcatenated = Data() + for h in heads { + headsConcatenated.append(h) + } + var tailsPointer = BigUInt(headsConcatenated.count) + headsConcatenated = Data() + var tailsConcatenated = Data() + for i in 0 ..< subTypes.count { + let head = heads[i] + let tail = tails[i] + if !subTypes[i].isStatic { + guard let newHead = tailsPointer.abiEncode(bits: 256) else {return nil} + headsConcatenated.append(newHead) + tailsConcatenated.append(tail) + tailsPointer = tailsPointer + BigUInt(tail.count) + } else { + headsConcatenated.append(head) + tailsConcatenated.append(tail) + } + } + let total = headsConcatenated + tailsConcatenated + return total + case .function: + if let data = value as? Data { + return data.setLengthLeft(32) + } + } + return nil + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABIParameterTypes.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABIParameterTypes.swift new file mode 100755 index 000000000..0bbd8038b --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABIParameterTypes.swift @@ -0,0 +1,250 @@ +// +// Created by Alex Vlasov on 25/10/2018. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt + +extension ABI.Element { + + /// Specifies the type that parameters in a contract have. + public enum ParameterType: ABIElementPropertiesProtocol { + case uint(bits: UInt64) + case int(bits: UInt64) + case address + case function + case bool + case bytes(length: UInt64) + indirect case array(type: ParameterType, length: UInt64) + case dynamicBytes + case string + indirect case tuple(types: [ParameterType]) + + var isStatic: Bool { + switch self { + case .string: + return false + case .dynamicBytes: + return false + case .array(type: let type, length: let length): + if (length == 0) { + return false + } + if (!type.isStatic) { + return false + } + return true + case .tuple(types: let types): + for t in types { + if (!t.isStatic) { + return false + } + } + return true + case .bytes(length: _): + return true + default: + return true + } + } + + var isArray: Bool { + switch self { + case .array(type: _, length: _): + return true + default: + return false + } + } + + var isTuple: Bool { + switch self { + case .tuple(_): + return true + default: + return false + } + } + + var subtype: ABI.Element.ParameterType? { + switch self { + case .array(type: let type, length: _): + return type + default: + return nil + } + } + + var memoryUsage: UInt64 { + switch self { + case .array(_, length: let length): + if length == 0 { + return 32 + } + if self.isStatic { + return 32*length + } + return 32 + case .tuple(types: let types): + if !self.isStatic { + return 32 + } + var sum: UInt64 = 0; + for t in types { + sum = sum + t.memoryUsage + } + return sum + default: + return 32 + } + } + + var emptyValue: Any { + switch self { + case .uint(bits: _): + return BigUInt(0) + case .int(bits: _): + return BigUInt(0) + case .address: + return EthereumAddress("0x0000000000000000000000000000000000000000")! + case .function: + return Data(repeating: 0x00, count: 24) + case .bool: + return false + case .bytes(length: let length): + return Data(repeating: 0x00, count: Int(length)) + case .array(type: let type, length: let length): + let emptyValueOfType = type.emptyValue + return Array.init(repeating: emptyValueOfType, count: Int(length)) + case .dynamicBytes: + return Data() + case .string: + return "" + case .tuple(types: _): + return [Any]() + } + } + + var arraySize: ABI.Element.ArraySize { + switch self { + case .array(type: _, length: let length): + if (length == 0) { + return ArraySize.dynamicSize + } + return ArraySize.staticSize(length) + default: + return ArraySize.notArray + } + } + } + + +} + +extension ABI.Element.ParameterType: Equatable { + public static func ==(lhs: ABI.Element.ParameterType, rhs: ABI.Element.ParameterType) -> Bool { + switch (lhs, rhs) { + case let (.uint(length1), .uint(length2)): + return length1 == length2 + case let (.int(length1), .int(length2)): + return length1 == length2 + case (.address, .address): + return true + case (.bool, .bool): + return true + case let (.bytes(length1), .bytes(length2)): + return length1 == length2 + case (.function, .function): + return true + case let (.array(type1, length1), .array(type2, length2)): + return type1 == type2 && length1 == length2 + case (.dynamicBytes, .dynamicBytes): + return true + case (.string, .string): + return true + default: + return false + } + } +} + +extension ABI.Element.Function { + public var signature: String { + return "\(name ?? "")(\(inputs.map { $0.type.abiRepresentation }.joined(separator: ",")))" + } + + public var methodString: String { + return String(signature.sha3(.keccak256).prefix(8)) + } + + public var methodEncoding: Data { + return signature.data(using: .ascii)!.sha3(.keccak256)[0...3] + } +} + +// MARK: - Event topic +extension ABI.Element.Event { + public var signature: String { + return "\(name)(\(inputs.map { $0.type.abiRepresentation }.joined(separator: ",")))" + } + + public var topic: Data { + return signature.data(using: .ascii)!.sha3(.keccak256) + } +} + + +extension ABI.Element.ParameterType: ABIEncoding { + public var abiRepresentation: String { + switch self { + case .uint(let bits): + return "uint\(bits)" + case .int(let bits): + return "int\(bits)" + case .address: + return "address" + case .bool: + return "bool" + case .bytes(let length): + return "bytes\(length)" + case .dynamicBytes: + return "bytes" + case .function: + return "function" + case .array(type: let type, length: let length): + if (length == 0) { + return "\(type.abiRepresentation)[]" + } + return "\(type.abiRepresentation)[\(length)]" + case .tuple(types: let types): + let typesRepresentation = types.map({return $0.abiRepresentation}) + let typesJoined = typesRepresentation.joined(separator: ",") + return "tuple(\(typesJoined))" + case .string: + return "string" + } + } +} + +extension ABI.Element.ParameterType: ABIValidation { + public var isValid: Bool { + switch self { + case .uint(let bits), .int(let bits): + return bits > 0 && bits <= 256 && bits % 8 == 0 + case .bytes(let length): + return length > 0 && length <= 32 + case .array(type: let type, _): + return type.isValid + case .tuple(types: let types): + for t in types { + if (!t.isValid) { + return false + } + } + return true + default: + return true + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABIParsing.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABIParsing.swift new file mode 100755 index 000000000..bc4610d08 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABIParsing.swift @@ -0,0 +1,186 @@ +// +// Created by Alex Vlasov on 25/10/2018. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +extension ABI { + + public enum ParsingError: Swift.Error { + case invalidJsonFile + case elementTypeInvalid + case elementNameInvalid + case functionInputInvalid + case functionOutputInvalid + case eventInputInvalid + case parameterTypeInvalid + case parameterTypeNotFound + case abiInvalid + } + + enum TypeParsingExpressions { + static var typeEatingRegex = "^((u?int|bytes)([1-9][0-9]*)|(address|bool|string|tuple|bytes)|(\\[([1-9][0-9]*)\\]))" + static var arrayEatingRegex = "^(\\[([1-9][0-9]*)?\\])?.*$" + } + + + fileprivate enum ElementType: String { + case function + case constructor + case fallback + case event + } + +} + +extension ABI.Record { + public func parse() throws -> ABI.Element { + let typeString = self.type != nil ? self.type! : "function" + guard let type = ABI.ElementType(rawValue: typeString) else { + throw ABI.ParsingError.elementTypeInvalid + } + return try parseToElement(from: self, type: type) + } +} + +fileprivate func parseToElement(from abiRecord: ABI.Record, type: ABI.ElementType) throws -> ABI.Element { + switch type { + case .function: + let function = try parseFunction(abiRecord: abiRecord) + return ABI.Element.function(function) + case .constructor: + let constructor = try parseConstructor(abiRecord: abiRecord) + return ABI.Element.constructor(constructor) + case .fallback: + let fallback = try parseFallback(abiRecord: abiRecord) + return ABI.Element.fallback(fallback) + case .event: + let event = try parseEvent(abiRecord: abiRecord) + return ABI.Element.event(event) + } + +} + +fileprivate func parseFunction(abiRecord:ABI.Record) throws -> ABI.Element.Function { + let inputs = try abiRecord.inputs?.map({ (input:ABI.Input) throws -> ABI.Element.InOut in + let nativeInput = try input.parse() + return nativeInput + }) + let abiInputs = inputs != nil ? inputs! : [ABI.Element.InOut]() + let outputs = try abiRecord.outputs?.map({ (output:ABI.Output) throws -> ABI.Element.InOut in + let nativeOutput = try output.parse() + return nativeOutput + }) + let abiOutputs = outputs != nil ? outputs! : [ABI.Element.InOut]() + let name = abiRecord.name != nil ? abiRecord.name! : "" + let payable = abiRecord.stateMutability != nil ? + (abiRecord.stateMutability == "payable" || abiRecord.payable!) : false + let constant = (abiRecord.constant == true || abiRecord.stateMutability == "view" || abiRecord.stateMutability == "pure") + let functionElement = ABI.Element.Function(name: name, inputs: abiInputs, outputs: abiOutputs, constant: constant, payable: payable) + return functionElement +} + +fileprivate func parseFallback(abiRecord:ABI.Record) throws -> ABI.Element.Fallback { + let payable = (abiRecord.stateMutability == "payable" || abiRecord.payable!) + var constant = abiRecord.constant == true + if (abiRecord.stateMutability == "view" || abiRecord.stateMutability == "pure") { + constant = true + } + let functionElement = ABI.Element.Fallback(constant: constant, payable: payable) + return functionElement +} + +fileprivate func parseConstructor(abiRecord:ABI.Record) throws -> ABI.Element.Constructor { + let inputs = try abiRecord.inputs?.map({ (input:ABI.Input) throws -> ABI.Element.InOut in + let nativeInput = try input.parse() + return nativeInput + }) + let abiInputs = inputs != nil ? inputs! : [ABI.Element.InOut]() + var payable = false + if (abiRecord.payable != nil) { + payable = abiRecord.payable! + } + if (abiRecord.stateMutability == "payable") { + payable = true + } + let constant = false + let functionElement = ABI.Element.Constructor(inputs: abiInputs, constant: constant, payable: payable) + return functionElement +} + +fileprivate func parseEvent(abiRecord:ABI.Record) throws -> ABI.Element.Event { + let inputs = try abiRecord.inputs?.map({ (input:ABI.Input) throws -> ABI.Element.Event.Input in + let nativeInput = try input.parseForEvent() + return nativeInput + }) + let abiInputs = inputs != nil ? inputs! : [ABI.Element.Event.Input]() + let name = abiRecord.name != nil ? abiRecord.name! : "" + let anonymous = abiRecord.anonymous != nil ? abiRecord.anonymous! : false + let functionElement = ABI.Element.Event(name: name, inputs: abiInputs, anonymous: anonymous) + return functionElement +} + +extension ABI.Input { + func parse() throws -> ABI.Element.InOut { + let name = self.name != nil ? self.name! : "" + let parameterType = try ABITypeParser.parseTypeString(self.type) + if case .tuple(types: _) = parameterType { + let components = try self.components?.compactMap({ (inp: ABI.Input) throws -> ABI.Element.ParameterType in + let input = try inp.parse() + return input.type + }) + let type = ABI.Element.ParameterType.tuple(types: components!) + let nativeInput = ABI.Element.InOut(name: name, type: type) + return nativeInput + } + else { + let nativeInput = ABI.Element.InOut(name: name, type: parameterType) + return nativeInput + } + } + + func parseForEvent() throws -> ABI.Element.Event.Input{ + let name = self.name != nil ? self.name! : "" + let parameterType = try ABITypeParser.parseTypeString(self.type) + let indexed = self.indexed == true + return ABI.Element.Event.Input(name:name, type: parameterType, indexed: indexed) + } +} + +extension ABI.Output { + func parse() throws -> ABI.Element.InOut { + let name = self.name != nil ? self.name! : "" + let parameterType = try ABITypeParser.parseTypeString(self.type) + switch parameterType { + case .tuple(types: _): + let components = try self.components?.compactMap({ (inp: ABI.Output) throws -> ABI.Element.ParameterType in + let input = try inp.parse() + return input.type + }) + let type = ABI.Element.ParameterType.tuple(types: components!) + let nativeInput = ABI.Element.InOut(name: name, type: type) + return nativeInput + case .array(type: let subtype, length: let length): + switch subtype { + case .tuple(types: _): + let components = try self.components?.compactMap({ (inp: ABI.Output) throws -> ABI.Element.ParameterType in + let input = try inp.parse() + return input.type + }) + let nestedSubtype = ABI.Element.ParameterType.tuple(types: components!) + let properType = ABI.Element.ParameterType.array(type: nestedSubtype, length: length) + let nativeInput = ABI.Element.InOut(name: name, type: properType) + return nativeInput + default: + let nativeInput = ABI.Element.InOut(name: name, type: parameterType) + return nativeInput + } + default: + let nativeInput = ABI.Element.InOut(name: name, type: parameterType) + return nativeInput + } + } +} + + diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABITypeParser.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABITypeParser.swift new file mode 100755 index 000000000..274712471 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumABI/ABITypeParser.swift @@ -0,0 +1,110 @@ +// +// Created by Alex Vlasov on 25/10/2018. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +public struct ABITypeParser { + + private enum BaseParameterType: String { + case address + case uint + case int + case bool + case function + case bytes + case string + case tuple + } + + static func baseTypeMatch(from string: String, length: UInt64 = 0) -> ABI.Element.ParameterType? { + switch BaseParameterType(rawValue: string) { + case .address?: + return .address + case .uint?: + return .uint(bits: length == 0 ? 256: length) + case .int?: + return .int(bits: length == 0 ? 256: length) + case .bool?: + return .bool + case .function?: + return .function + case .bytes?: + if length == 0 { + return .dynamicBytes + } + return .bytes(length: length) + case .string?: + return .string + case .tuple?: + return .tuple(types: [ABI.Element.ParameterType]()) + default: + return nil + } + } + + public static func parseTypeString(_ string:String) throws -> ABI.Element.ParameterType { + let (type, tail) = recursiveParseType(string) + guard let t = type, tail == nil else {throw ABI.ParsingError.elementTypeInvalid} + return t + } + + static func recursiveParseType(_ string: String) -> (type: ABI.Element.ParameterType?, tail: String?) { + let matcher = try! NSRegularExpression(pattern: ABI.TypeParsingExpressions.typeEatingRegex, options: NSRegularExpression.Options.dotMatchesLineSeparators) + let match = matcher.matches(in: string, options: NSRegularExpression.MatchingOptions.anchored, range: string.fullNSRange) + guard match.count == 1 else { + return (nil, nil) + } + var tail: String = "" + var type: ABI.Element.ParameterType? + guard match[0].numberOfRanges >= 1 else {return (nil, nil)} + guard let baseTypeRange = Range(match[0].range(at: 1), in: string) else {return (nil, nil)} + let baseTypeString = String(string[baseTypeRange]) + if match[0].numberOfRanges >= 2, let exactTypeRange = Range(match[0].range(at: 2), in: string) { + let typeString = String(string[exactTypeRange]) + if match[0].numberOfRanges >= 3, let lengthRange = Range(match[0].range(at: 3), in: string) { + let lengthString = String(string[lengthRange]) + guard let typeLength = UInt64(lengthString) else {return (nil, nil)} + guard let baseType = baseTypeMatch(from: typeString, length: typeLength) else {return (nil, nil)} + type = baseType + } else { + guard let baseType = baseTypeMatch(from: typeString, length: 0) else {return (nil, nil)} + type = baseType + } + } else { + guard let baseType = baseTypeMatch(from: baseTypeString, length: 0) else {return (nil, nil)} + type = baseType + } + tail = string.replacingCharacters(in: string.range(of: baseTypeString)!, with: "") + if (tail == "") { + return (type, nil) + } + return recursiveParseArray(baseType: type!, string: tail) + } + + static func recursiveParseArray(baseType: ABI.Element.ParameterType, string: String) -> (type: ABI.Element.ParameterType?, tail: String?) { + let matcher = try! NSRegularExpression(pattern: ABI.TypeParsingExpressions.arrayEatingRegex, options: NSRegularExpression.Options.dotMatchesLineSeparators) + let match = matcher.matches(in: string, options: NSRegularExpression.MatchingOptions.anchored, range: string.fullNSRange) + guard match.count == 1 else {return (nil, nil)} + var tail: String = "" + var type: ABI.Element.ParameterType? + guard match[0].numberOfRanges >= 1 else {return (nil, nil)} + guard let baseArrayRange = Range(match[0].range(at: 1), in: string) else {return (nil, nil)} + let baseArrayString = String(string[baseArrayRange]) + if match[0].numberOfRanges >= 2, let exactArrayRange = Range(match[0].range(at: 2), in: string) { + let lengthString = String(string[exactArrayRange]) + guard let arrayLength = UInt64(lengthString) else {return (nil, nil)} + let baseType = ABI.Element.ParameterType.array(type: baseType, length: arrayLength) + type = baseType + } else { + let baseType = ABI.Element.ParameterType.array(type: baseType, length: 0) + type = baseType + } + tail = string.replacingCharacters(in: string.range(of: baseArrayString)!, with: "") + if (tail == "") { + return (type, nil) + } + return recursiveParseArray(baseType: type!, string: tail) + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumAddress/EthereumAddress.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumAddress/EthereumAddress.swift new file mode 100755 index 000000000..da47d982c --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumAddress/EthereumAddress.swift @@ -0,0 +1,136 @@ +// +// EthereumAddress.swift +// EthereumAddress +// +// Created by Alex Vlasov on 25/10/2018. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import CryptoSwift + +public struct EthereumAddress: Equatable { + public enum AddressType { + case normal + case contractDeployment + } + + public var isValid: Bool { + get { + switch self.type { + case .normal: + return (self.addressData.count == 20) + case .contractDeployment: + return true + } + + } + } + var _address: String + public var type: AddressType = .normal + public static func ==(lhs: EthereumAddress, rhs: EthereumAddress) -> Bool { + return lhs.addressData == rhs.addressData && lhs.type == rhs.type + // return lhs.address.lowercased() == rhs.address.lowercased() && lhs.type == rhs.type + } + + public var addressData: Data { + get { + switch self.type { + case .normal: + guard let dataArray = Data.fromHex(_address) else {return Data()} + return dataArray + // guard let d = dataArray.setLengthLeft(20) else { return Data()} + // return d + case .contractDeployment: + return Data() + } + } + } + public var address:String { + switch self.type { + case .normal: + return EthereumAddress.toChecksumAddress(_address)! + case .contractDeployment: + return "0x" + } + } + + 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} + var ret = "0x" + + for (i,char) in address.enumerated() { + let startIdx = hash.index(hash.startIndex, offsetBy: i) + let endIdx = hash.index(hash.startIndex, offsetBy: i+1) + let hashChar = String(hash[startIdx..= 8) { + ret += c.uppercased() + } else { + ret += c + } + } + return ret + } + + 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} + if !addressString.hasHexPrefix() { + return nil + } + if (!ignoreChecksum) { + // check for checksum + if data.toHexString() == addressString.stripHexPrefix() { + self._address = data.toHexString().addHexPrefix() + self.type = .normal + return + } else if data.toHexString().uppercased() == addressString.stripHexPrefix() { + self._address = data.toHexString().addHexPrefix() + self.type = .normal + return + } else { + let checksummedAddress = EthereumAddress.toChecksumAddress(data.toHexString().addHexPrefix()) + guard checksummedAddress == addressString else {return nil} + self._address = data.toHexString().addHexPrefix() + self.type = .normal + return + } + } else { + self._address = data.toHexString().addHexPrefix() + self.type = .normal + return + } + case .contractDeployment: + self._address = "0x" + self.type = .contractDeployment + } + } + + public init?(_ addressData:Data, type: AddressType = .normal) { + guard addressData.count == 20 else {return nil} + self._address = addressData.toHexString().addHexPrefix() + self.type = type + } + + public static func contractDeploymentAddress() -> EthereumAddress { + return EthereumAddress("0x", type: .contractDeployment)! + } + + // public static func fromIBAN(_ iban: String) -> EthereumAddress { + // + // } + +} + +extension EthereumAddress: Hashable { + +} + + + + diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumAddress/Extensions.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumAddress/Extensions.swift new file mode 100755 index 000000000..f82edee10 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/EthereumAddress/Extensions.swift @@ -0,0 +1,60 @@ +// +// Extensions.swift +// EthereumAddress +// +// Created by Alex Vlasov on 25/10/2018. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +extension Array where Element == UInt8 { + init(hex: String) { + self.init() + self.reserveCapacity(hex.unicodeScalars.lazy.underestimatedCount) + var buffer: UInt8? + var skip = hex.hasPrefix("0x") ? 2 : 0 + for char in hex.unicodeScalars.lazy { + guard skip == 0 else { + skip -= 1 + continue + } + guard char.value >= 48 && char.value <= 102 else { + removeAll() + return + } + let v: UInt8 + let c: UInt8 = UInt8(char.value) + switch c { + case let c where c <= 57: + v = c - 48 + case let c where c >= 65 && c <= 70: + v = c - 55 + case let c where c >= 97: + v = c - 87 + default: + removeAll() + return + } + if let b = buffer { + append(b << 4 | v) + buffer = nil + } else { + buffer = v + } + } + if let b = buffer { + append(b) + } + } + + func toHexString() -> String { + return `lazy`.reduce("") { + var s = String($1, radix: 16) + if s.count == 1 { + s = "0" + s + } + return $0 + s + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/HookedFunctions/Web3+BrowserFunctions.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/HookedFunctions/Web3+BrowserFunctions.swift new file mode 100755 index 000000000..ed1576a3b --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/HookedFunctions/Web3+BrowserFunctions.swift @@ -0,0 +1,209 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import secp256k1_swift +//import EthereumAddress + +extension web3.BrowserFunctions { + + public func getAccounts() -> [String]? { + do { + let accounts = try self.web3.eth.getAccounts() + return accounts.compactMap({$0.address}) + } catch { + return [String]() + } + } + + public func getCoinbase() -> String? { + guard let addresses = self.getAccounts() else {return nil} + guard addresses.count > 0 else {return nil} + return addresses[0] + } + + public func personalSign(_ personalMessage: String, account: String, password: String = "web3swift") -> String? { + return self.sign(personalMessage, account: account, password: password) + } + + public func sign(_ personalMessage: String, account: String, password: String = "web3swift") -> String? { + 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 = "web3swift") -> 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} + return signature.toHexString().addHexPrefix() + } + catch{ + print(error) + return nil + } + } + + 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} + return self.personalECRecover(data, signature:sig) + } + + public func personalECRecover(_ personalMessage: Data, signature: Data) -> String? { + 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 = Web3.Utils.hashPersonalMessage(personalMessage) else {return nil} + guard let publicKey = SECP256K1.recoverPublicKey(hash: hash, signature: signatureData) else {return nil} + return Web3.Utils.publicToAddressString(publicKey) + } + + + public func sendTransaction(_ transactionJSON: [String: Any], password: String = "web3swift") -> [String:Any]? { + guard let transaction = EthereumTransaction.fromJSON(transactionJSON) else {return nil} + guard let options = TransactionOptions.fromJSON(transactionJSON) else {return nil} + var transactionOptions = TransactionOptions() + transactionOptions.from = options.from + transactionOptions.to = options.to + transactionOptions.value = options.value != nil ? options.value! : BigUInt(0) + transactionOptions.gasLimit = options.gasLimit != nil ? options.gasLimit! : .automatic + transactionOptions.gasPrice = options.gasPrice != nil ? options.gasPrice! : .automatic + return self.sendTransaction(transaction, transactionOptions: transactionOptions, password: password) + } + + public func sendTransaction(_ transaction: EthereumTransaction, transactionOptions: TransactionOptions, password: String = "web3swift") -> [String:Any]? { + do { + let result = try self.web3.eth.sendTransaction(transaction, transactionOptions: transactionOptions, password: password) + return ["txhash": result.hash] + } catch { + return nil + } + } + + public func estimateGas(_ transactionJSON: [String: Any]) -> BigUInt? { + guard let transaction = EthereumTransaction.fromJSON(transactionJSON) else {return nil} + guard let options = TransactionOptions.fromJSON(transactionJSON) else {return nil} + var transactionOptions = TransactionOptions() + transactionOptions.from = options.from + transactionOptions.to = options.to + transactionOptions.value = options.value != nil ? options.value! : BigUInt(0) + transactionOptions.gasLimit = .automatic + transactionOptions.gasPrice = options.gasPrice != nil ? options.gasPrice! : .automatic + return self.estimateGas(transaction, transactionOptions: transactionOptions) + } + + public func estimateGas(_ transaction: EthereumTransaction, transactionOptions: TransactionOptions) -> BigUInt? { + do { + let result = try self.web3.eth.estimateGas(transaction, transactionOptions: transactionOptions) + return result + } catch { + return nil + } + } + + public func prepareTxForApproval(_ transactionJSON: [String: Any]) -> (transaction: EthereumTransaction?, options: TransactionOptions?) { + guard let transaction = EthereumTransaction.fromJSON(transactionJSON) else {return (nil, nil)} + guard let options = TransactionOptions.fromJSON(transactionJSON) else {return (nil, nil)} + do { + return try self.prepareTxForApproval(transaction, options: options) + } catch { + return (nil, nil) + } + } + + public func prepareTxForApproval(_ trans: EthereumTransaction, options opts: TransactionOptions) throws -> (transaction: EthereumTransaction?, options: TransactionOptions?) { + do { + var transaction = trans + var options = opts + guard let _ = options.from else {return (nil, nil)} + let gasPrice = try self.web3.eth.getGasPrice() + transaction.gasPrice = gasPrice + options.gasPrice = .manual(gasPrice) + guard let gasEstimate = self.estimateGas(transaction, transactionOptions: options) else {return (nil, nil)} + transaction.gasLimit = gasEstimate + options.gasLimit = .limited(gasEstimate) + print(transaction) + return (transaction, options) + } catch { + return (nil, nil) + } + } + + public func signTransaction(_ transactionJSON: [String: Any], password: String = "web3swift") -> String? { + guard let transaction = EthereumTransaction.fromJSON(transactionJSON) else {return nil} + guard let options = TransactionOptions.fromJSON(transactionJSON) else {return nil} + var transactionOptions = TransactionOptions() + transactionOptions.from = options.from + transactionOptions.to = options.to + transactionOptions.value = options.value != nil ? options.value! : BigUInt(0) + transactionOptions.gasLimit = options.gasLimit != nil ? options.gasLimit! : .automatic + transactionOptions.gasPrice = options.gasPrice != nil ? options.gasPrice! : .automatic + if let nonceString = transactionJSON["nonce"] as? String, let nonce = BigUInt(nonceString.stripHexPrefix(), radix: 16) { + transactionOptions.nonce = .manual(nonce) + } else { + transactionOptions.nonce = .pending + } + return self.signTransaction(transaction, transactionOptions: transactionOptions, password: password) + } + + public func signTransaction(_ trans: EthereumTransaction, transactionOptions: TransactionOptions, password: String = "web3swift") -> String? { + do { + var transaction = trans + guard let from = transactionOptions.from else {return nil} + guard let keystoreManager = self.web3.provider.attachedKeystoreManager else {return nil} + guard let gasPricePolicy = transactionOptions.gasPrice else {return nil} + guard let gasLimitPolicy = transactionOptions.gasLimit else {return nil} + guard let noncePolicy = transactionOptions.nonce else {return nil} + switch gasPricePolicy { + case .manual(let gasPrice): + transaction.gasPrice = gasPrice + default: + let gasPrice = try self.web3.eth.getGasPrice() + transaction.gasPrice = gasPrice + } + + switch gasLimitPolicy { + case .manual(let gasLimit): + transaction.gasLimit = gasLimit + default: + let gasLimit = try self.web3.eth.estimateGas(transaction, transactionOptions: transactionOptions) + transaction.gasLimit = gasLimit + } + + switch noncePolicy { + case .manual(let nonce): + transaction.nonce = nonce + default: + let nonce = try self.web3.eth.getTransactionCount(address: from, onBlock: "pending") + transaction.nonce = nonce + } + + if (self.web3.provider.network != nil) { + transaction.chainID = self.web3.provider.network?.chainID + } + + 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(forSignature: false, chainID: nil)?.toHexString().addHexPrefix() + return signedData + } + catch { + return nil + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/HookedFunctions/Web3+Wallet.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/HookedFunctions/Web3+Wallet.swift new file mode 100755 index 000000000..c7b0e8c44 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/HookedFunctions/Web3+Wallet.swift @@ -0,0 +1,73 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +extension web3.Web3Wallet { + + public func getAccounts() throws -> [EthereumAddress] { + guard let keystoreManager = self.web3.provider.attachedKeystoreManager else { + throw Web3Error.walletError + } + guard let ethAddresses = keystoreManager.addresses else { + throw Web3Error.walletError + } + return ethAddresses + } + + public func getCoinbase() throws -> EthereumAddress { + let addresses = try self.getAccounts() + guard addresses.count > 0 else { + throw Web3Error.walletError + } + return addresses[0] + } + + public func signTX(transaction:inout EthereumTransaction, account: EthereumAddress, password: String = "web3swift") throws -> Bool { + do { + guard let keystoreManager = self.web3.provider.attachedKeystoreManager else { + throw Web3Error.walletError + } + try Web3Signer.signTX(transaction: &transaction, keystore: keystoreManager, account: account, password: password) + return true + } catch { + if error is AbstractKeystoreError { + throw Web3Error.keystoreError(err: error as! AbstractKeystoreError) + } + throw Web3Error.generalError(err: error) + } + } + + public func signPersonalMessage(_ personalMessage: String, account: EthereumAddress, password: String = "web3swift") throws -> Data { + guard let data = Data.fromHex(personalMessage) else + { + throw Web3Error.dataError + } + return try self.signPersonalMessage(data, account: account, password: password) + } + + public func signPersonalMessage(_ personalMessage: Data, account: EthereumAddress, password: String = "web3swift") throws -> Data { + do { + guard let keystoreManager = self.web3.provider.attachedKeystoreManager else + { + throw Web3Error.walletError + } + guard let data = try Web3Signer.signPersonalMessage(personalMessage, keystore: keystoreManager, account: account, password: password) else { + throw Web3Error.walletError + } + return data + } + catch{ + if error is AbstractKeystoreError { + throw Web3Error.keystoreError(err: error as! AbstractKeystoreError) + } + throw Web3Error.generalError(err: error) + } + } + +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/AbstractKeystore.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/AbstractKeystore.swift new file mode 100755 index 000000000..d8a19f97d --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/AbstractKeystore.swift @@ -0,0 +1,23 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +//import EthereumAddress + +public protocol AbstractKeystore { + var addresses: [EthereumAddress]? {get} + var isHDKeystore: Bool {get} + func UNSAFE_getPrivateKeyData(password: String, account: EthereumAddress) throws -> Data +} + +public enum AbstractKeystoreError: Error { + case noEntropyError + case keyDerivationError + case aesError + case invalidAccountError + case invalidPasswordError + case encryptionError(String) +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32HDNode.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32HDNode.swift new file mode 100755 index 000000000..267b7f024 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32HDNode.swift @@ -0,0 +1,302 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import CryptoSwift +//import secp256k1_swift + +extension UInt32 { + public func serialize32() -> Data { + let uint32 = UInt32(self) + var bigEndian = uint32.bigEndian + let count = MemoryLayout.size + let bytePtr = withUnsafePointer(to: &bigEndian) { + $0.withMemoryRebound(to: UInt8.self, capacity: count) { + UnsafeBufferPointer(start: $0, count: count) + } + } + let byteArray = Array(bytePtr) + return Data(byteArray) + } +} + +public class HDNode { + public struct HDversion{ + public var privatePrefix: Data = Data.fromHex("0x0488ADE4")! + public var publicPrefix: Data = Data.fromHex("0x0488B21E")! + public init() { + + } + } + public var path: String? = "m" + public var privateKey: Data? = nil + public var publicKey: Data + public var chaincode: Data + public var depth: UInt8 + 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) + } + } + public var index: UInt32 { + get { + if self.isHardened { + return self.childNumber - (UInt32(1) << 31) + } else { + return self.childNumber + } + } + } + public var hasPrivate:Bool { + get { + return privateKey != nil + } + } + + init() { + publicKey = Data() + chaincode = Data() + depth = UInt8(0) + } + + public convenience init?(_ serializedString: String) { + let data = Data(Base58.bytesFromBase58(serializedString)) + self.init(data) + } + + public init?(_ data: Data) { + guard data.count == 82 else {return nil} + let header = data[0..<4] + var serializePrivate = false + if header == HDNode.HDversion().privatePrefix { + serializePrivate = true + } + depth = data[4..<5].bytes[0] + parentFingerprint = data[5..<9] + let cNum = data[9..<13].bytes + childNumber = UnsafePointer(cNum).withMemoryRebound(to: UInt32.self, capacity: 1) { + $0.pointee + } + chaincode = data[13..<45] + if serializePrivate { + privateKey = data[46..<78] + guard let pubKey = Web3.Utils.privateToPublic(privateKey!, compressed: true) else {return nil} + if pubKey[0] != 0x02 && pubKey[0] != 0x03 {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} + } + + public init?(seed: Data) { + guard seed.count >= 16 else {return nil} + let hmacKey = "Bitcoin seed".data(using: .ascii)! + let hmac:Authenticator = HMAC(key: hmacKey.bytes, variant: HMAC.Variant.sha512) + guard let entropy = try? hmac.authenticate(seed.bytes) else {return nil} + guard 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} + publicKey = pubKeyCandidate + privateKey = privKeyCandidate + depth = 0x00 + childNumber = UInt32(0) + } + + private static var curveOrder = BigUInt("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", radix: 16)! + 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" + public static var defaultPathMetamaskPrefix: String = "m/44'/60'/0'/0" + public static var hardenedIndexPrefix: UInt32 = (UInt32(1) << 31) +} + +extension 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:Array + 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: .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: .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:Array // 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: .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 = pubKeyCandidate + 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 + } + } + + public func derive (path: String, derivePrivateKey: Bool = true) -> HDNode? { + let components = path.components(separatedBy: "/") + var currentNode:HDNode = self + var firstComponent = 0 + if path.hasPrefix("m") { + firstComponent = 1 + } + for component in components[firstComponent ..< components.count] { + var hardened = false + 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} + currentNode = newNode + } + return currentNode + } + + 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 + } + + public func serialize(serializePublic: Bool = true, version: HDversion = HDversion()) -> Data? { + var data = Data() + if (!serializePublic && !self.hasPrivate) {return nil} + if serializePublic { + data.append(version.publicPrefix) + } else { + 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: [0x00]) + data.append(self.privateKey!) + } + let hashedData = data.sha256().sha256() + let checksum = hashedData[0..<4] + data.append(checksum) + return data + } + +} + diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32Keystore.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32Keystore.swift new file mode 100755 index 000000000..79a3c3784 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32Keystore.swift @@ -0,0 +1,279 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import CryptoSwift +import Foundation +//import EthereumAddress + +public class BIP32Keystore: AbstractKeystore { + // Protocol + + public var addresses: [EthereumAddress]? { + get { + if self.paths.count == 0 { + return nil + } + var allAccounts = [EthereumAddress]() + for (_, address) in paths { + allAccounts.append(address) + } + return allAccounts + } + } + + public var isHDKeystore: Bool = true + + public func UNSAFE_getPrivateKeyData(password: String, account: EthereumAddress) throws -> Data { + if let key = self.paths.keyForValue(value: account) { + guard let decryptedRootNode = try? self.getPrefixNodeData(password) else {throw AbstractKeystoreError.encryptionError("Failed to decrypt a keystore")} + guard let rootNode = HDNode(decryptedRootNode) else {throw AbstractKeystoreError.encryptionError("Failed to deserialize a root node")} + guard rootNode.depth == (self.rootPrefix.components(separatedBy: "/").count - 1) else {throw AbstractKeystoreError.encryptionError("Derivation depth mismatch")} +// guard rootNode.depth == HDNode.defaultPathPrefix.components(separatedBy: "/").count - 1 else {throw AbstractKeystoreError.encryptionError("Derivation depth mismatch")} + guard let index = UInt32(key.components(separatedBy: "/").last!) else {throw AbstractKeystoreError.encryptionError("Derivation depth mismatch")} + guard let keyNode = rootNode.derive(index: index, derivePrivateKey: true) else {throw AbstractKeystoreError.encryptionError("Derivation failed")} + guard let privateKey = keyNode.privateKey else {throw AbstractKeystoreError.invalidAccountError} + return privateKey + } + throw AbstractKeystoreError.invalidAccountError + } + + // -------------- + + public var keystoreParams: KeystoreParamsBIP32? + public var paths: [String:EthereumAddress] = [String:EthereumAddress]() + public var rootPrefix: String + public convenience init?(_ jsonString: String) { + let lowercaseJSON = jsonString.lowercased() + guard let jsonData = lowercaseJSON.data(using: .utf8) else {return nil} + self.init(jsonData) + } + + public init?(_ jsonData: Data) { + guard var keystorePars = try? JSONDecoder().decode(KeystoreParamsBIP32.self, from: jsonData) else {return nil} + if (keystorePars.version != 3) {return nil} + if (keystorePars.crypto.version != nil && keystorePars.crypto.version != "1") {return nil} + if (!keystorePars.isHDWallet) {return nil} + for (p, ad) in keystorePars.pathToAddress { + paths[p] = EthereumAddress(ad) + } + if keystorePars.rootPath == nil { + keystorePars.rootPath = HDNode.defaultPathPrefix + } + keystoreParams = keystorePars + rootPrefix = keystoreParams!.rootPath! + } + + public convenience init? (mnemonics: String, password: String = "web3swift", mnemonicsPassword: String = "", language: BIP39Language = BIP39Language.english, prefixPath: String = HDNode.defaultPathMetamaskPrefix, aesMode: String = "aes-128-cbc") throws { + guard var seed = BIP39.seedFromMmemonics(mnemonics, password: mnemonicsPassword, language: language) else {throw AbstractKeystoreError.noEntropyError} + defer{ Data.zero(&seed) } + try self.init(seed: seed, password: password, prefixPath: prefixPath, aesMode: aesMode) + } + + public init? (seed: Data, password: String = "web3swift", prefixPath: String = HDNode.defaultPathMetamaskPrefix, aesMode: String = "aes-128-cbc") throws { + 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 {throw AbstractKeystoreError.keyDerivationError} + try encryptDataToStorage(password, data: serializedRootNode, aesMode: aesMode) + } + + public func createNewChildAccount(password: String = "web3swift") throws { + guard let decryptedRootNode = try? self.getPrefixNodeData(password) else {throw AbstractKeystoreError.encryptionError("Failed to decrypt a keystore")} + guard let rootNode = HDNode(decryptedRootNode) else {throw AbstractKeystoreError.encryptionError("Failed to deserialize a root node")} + let prefixPath = self.rootPrefix + guard rootNode.depth == prefixPath.components(separatedBy: "/").count - 1 else {throw AbstractKeystoreError.encryptionError("Derivation depth mismatch")} + try createNewAccount(parentNode: rootNode, password: password) + guard let serializedRootNode = rootNode.serialize(serializePublic: false) else {throw AbstractKeystoreError.keyDerivationError} + try encryptDataToStorage(password, data: serializedRootNode, aesMode: self.keystoreParams!.crypto.cipher) + } + + func createNewAccount(parentNode: HDNode, password: String = "web3swift") throws { + var newIndex = UInt32(0) + for (p, _) in paths { + guard let idx = UInt32(p.components(separatedBy: "/").last!) else {continue} + if idx >= newIndex { + newIndex = idx + 1 + } + } + guard let newNode = parentNode.derive(index: newIndex, derivePrivateKey: true, hardened: false) else {throw AbstractKeystoreError.keyDerivationError} + guard let newAddress = Web3.Utils.publicToAddress(newNode.publicKey) else {throw AbstractKeystoreError.keyDerivationError} + let prefixPath = self.rootPrefix + var newPath:String + if newNode.isHardened { + newPath = prefixPath + "/" + String(newNode.index % HDNode.hardenedIndexPrefix) + "'" + } else { + newPath = prefixPath + "/" + String(newNode.index) + } + paths[newPath] = newAddress + } + + public func createNewCustomChildAccount(password: String = "web3swift", path: String) throws { + guard let decryptedRootNode = try? self.getPrefixNodeData(password) else {throw AbstractKeystoreError.encryptionError("Failed to decrypt a keystore")} + guard let rootNode = HDNode(decryptedRootNode) else {throw AbstractKeystoreError.encryptionError("Failed to deserialize a root node")} + let prefixPath = self.rootPrefix + var pathAppendix: String? = nil + if path.hasPrefix(prefixPath) { + pathAppendix = String(path[path.index(after: (path.range(of: prefixPath)?.upperBound)!)]) + guard pathAppendix != nil else { + throw AbstractKeystoreError.encryptionError("Derivation depth mismatch") + } + if pathAppendix!.hasPrefix("/") { + pathAppendix = pathAppendix?.trimmingCharacters(in: CharacterSet.init(charactersIn: "/")) + } + } else { + if path.hasPrefix("/") { + pathAppendix = path.trimmingCharacters(in: CharacterSet.init(charactersIn: "/")) + } + } + guard pathAppendix != nil else { + throw AbstractKeystoreError.encryptionError("Derivation depth mismatch") + } + guard rootNode.depth == prefixPath.components(separatedBy: "/").count - 1 else {throw AbstractKeystoreError.encryptionError("Derivation depth mismatch")} + guard let newNode = rootNode.derive(path: pathAppendix!, derivePrivateKey: true) else { + throw AbstractKeystoreError.keyDerivationError + } + guard let newAddress = Web3.Utils.publicToAddress(newNode.publicKey) else {throw AbstractKeystoreError.keyDerivationError} + var newPath:String + if newNode.isHardened { + newPath = prefixPath + "/" + pathAppendix!.trimmingCharacters(in: CharacterSet.init(charactersIn: "'")) + "'" + } else { + newPath = prefixPath + "/" + pathAppendix! + } + paths[newPath] = newAddress + guard let serializedRootNode = rootNode.serialize(serializePublic: false) else {throw AbstractKeystoreError.keyDerivationError} + try encryptDataToStorage(password, data: serializedRootNode, aesMode: self.keystoreParams!.crypto.cipher) + } + + fileprivate func encryptDataToStorage(_ password: String, data: Data?, dkLen: Int=32, N: Int = 4096, R: Int = 6, P: Int = 1, aesMode: String = "aes-128-cbc") throws { + if (data == nil) { + throw AbstractKeystoreError.encryptionError("Encryption without key data") + } + if (data!.count != 82) { + throw AbstractKeystoreError.encryptionError("Invalid expected data length") + } + let saltLen = 32; + guard let saltData = Data.randomBytes(length: saltLen) else {throw AbstractKeystoreError.noEntropyError} + guard let derivedKey = scrypt(password: password, salt: saltData, length: dkLen, N: N, R: R, P: P) else {throw AbstractKeystoreError.keyDerivationError} + let last16bytes = derivedKey[(derivedKey.count - 16)...(derivedKey.count-1)] + let encryptionKey = derivedKey[0...15] + guard let IV = Data.randomBytes(length: 16) else {throw AbstractKeystoreError.noEntropyError} + var aesCipher : AES? + switch aesMode { + case "aes-128-cbc": + aesCipher = try? AES(key: encryptionKey.bytes, blockMode: CBC(iv: IV.bytes), padding: .pkcs7) + case "aes-128-ctr": + aesCipher = try? AES(key: encryptionKey.bytes, blockMode: CTR(iv: IV.bytes), padding: .pkcs7) + default: + aesCipher = nil + } + if aesCipher == nil { + throw AbstractKeystoreError.aesError + } + guard let encryptedKey = try aesCipher?.encrypt(data!.bytes) else {throw AbstractKeystoreError.aesError} +// let encryptedKeyData = Data(bytes:encryptedKey) Data(encryptedKey) + let encryptedKeyData = Data(encryptedKey) + var dataForMAC = Data() + dataForMAC.append(last16bytes) + dataForMAC.append(encryptedKeyData) + let mac = dataForMAC.sha3(.keccak256) + let kdfparams = KdfParamsV3(salt: saltData.toHexString(), dklen: dkLen, n: N, p: P, r: R, c: nil, prf: nil) + let cipherparams = CipherParamsV3(iv: IV.toHexString()) + let crypto = CryptoParamsV3(ciphertext: encryptedKeyData.toHexString(), cipher: aesMode, cipherparams: cipherparams, kdf: "scrypt", kdfparams: kdfparams, mac: mac.toHexString(), version: nil) + var pathToAddress = [String:String]() + for (path, address) in paths { + pathToAddress[path] = address.address + } + var keystorePars = KeystoreParamsBIP32(crypto: crypto, id: UUID().uuidString.lowercased(), version: 3) + keystorePars.pathToAddress = pathToAddress + keystorePars.rootPath = self.rootPrefix + keystoreParams = keystorePars + } + + public func regenerate(oldPassword: String, newPassword: String, dkLen: Int=32, N: Int = 4096, R: Int = 6, P: Int = 1) throws { + var keyData = try self.getPrefixNodeData(oldPassword) + if keyData == nil { + throw AbstractKeystoreError.encryptionError("Failed to decrypt a keystore") + } + defer {Data.zero(&keyData!)} + try self.encryptDataToStorage(newPassword, data: keyData!, aesMode: self.keystoreParams!.crypto.cipher) + } + + fileprivate func getPrefixNodeData(_ password: String) throws -> Data? { + guard let keystorePars = keystoreParams else {return nil} + guard let saltData = Data.fromHex(keystorePars.crypto.kdfparams.salt) else {return nil} + let derivedLen = keystorePars.crypto.kdfparams.dklen + var passwordDerivedKey:Data? + switch keystorePars.crypto.kdf { + case "scrypt": + guard let N = keystorePars.crypto.kdfparams.n else {return nil} + guard let P = keystorePars.crypto.kdfparams.p else {return nil} + guard let R = keystorePars.crypto.kdfparams.r else {return nil} + passwordDerivedKey = scrypt(password: password, salt: saltData, length: derivedLen, N: N, R: R, P: P) + case "pbkdf2": + guard let algo = keystorePars.crypto.kdfparams.prf else {return nil} + var hashVariant:HMAC.Variant?; + switch algo { + case "hmac-sha256" : + hashVariant = HMAC.Variant.sha256 + case "hmac-sha384" : + hashVariant = HMAC.Variant.sha384 + case "hmac-sha512" : + hashVariant = HMAC.Variant.sha512 + default: + hashVariant = nil + } + guard (hashVariant != nil) else {return nil} + guard let c = keystorePars.crypto.kdfparams.c else {return nil} + guard let passData = password.data(using: .utf8) else {return nil} + guard let derivedArray = try? PKCS5.PBKDF2(password: passData.bytes, salt: saltData.bytes, iterations: c, keyLength: derivedLen, variant: hashVariant!).calculate() else {return nil} +// passwordDerivedKey = Data(bytes:derivedArray) + passwordDerivedKey = Data(derivedArray) + default: + return nil + } + guard let derivedKey = passwordDerivedKey else {return nil} + var dataForMAC = Data() + let derivedKeyLast16bytes = derivedKey[(derivedKey.count - 16)...(derivedKey.count - 1)] + dataForMAC.append(derivedKeyLast16bytes) + guard let cipherText = Data.fromHex(keystorePars.crypto.ciphertext) else {return nil} + guard (cipherText.count.isMultiple(of: 32)) else {return nil} + dataForMAC.append(cipherText) + let mac = dataForMAC.sha3(.keccak256) + guard let calculatedMac = Data.fromHex(keystorePars.crypto.mac), mac.constantTimeComparisonTo(calculatedMac) else {return nil} + let cipher = keystorePars.crypto.cipher + let decryptionKey = derivedKey[0...15] + guard let IV = Data.fromHex(keystorePars.crypto.cipherparams.iv) else {return nil} + var decryptedPK:Array? + switch cipher { + case "aes-128-ctr": + guard let aesCipher = try? AES(key: decryptionKey.bytes, blockMode: CTR(iv: IV.bytes), padding: .pkcs7) else {return nil} + decryptedPK = try aesCipher.decrypt(cipherText.bytes) + case "aes-128-cbc": + guard let aesCipher = try? AES(key: decryptionKey.bytes, blockMode: CBC(iv: IV.bytes), padding: .pkcs7) else {return nil} + decryptedPK = try? aesCipher.decrypt(cipherText.bytes) + default: + return nil + } + guard decryptedPK != nil else {return nil} + guard decryptedPK?.count == 82 else {return nil} +// return Data(bytes:decryptedPK!) + return Data(decryptedPK!) + } + + public func serialize() throws -> Data? { + guard let params = self.keystoreParams else {return nil} + let data = try JSONEncoder().encode(params) + return data + } + + public func serializeRootNodeToString(password: String = "web3swift") throws -> String { + guard let decryptedRootNode = try? self.getPrefixNodeData(password) else {throw AbstractKeystoreError.encryptionError("Failed to decrypt a keystore")} + guard let rootNode = HDNode(decryptedRootNode) else {throw AbstractKeystoreError.encryptionError("Failed to deserialize a root node")} + guard let string = rootNode.serializeToString(serializePublic: false) else {throw AbstractKeystoreError.encryptionError("Failed to deserialize a root node")} + return string + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32KeystoreJSONStructure.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32KeystoreJSONStructure.swift new file mode 100755 index 000000000..97a253345 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32KeystoreJSONStructure.swift @@ -0,0 +1,26 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +public struct KeystoreParamsBIP32: Decodable, Encodable { + var crypto: CryptoParamsV3 + var id: String? + var version: Int = 32 + var isHDWallet: Bool + var pathToAddress: [String:String] + var rootPath: String? + + public init(crypto cr: CryptoParamsV3, id i: String, version ver: Int, rootPath: String? = nil) { + crypto = cr + id = i + version = ver + isHDWallet = true + pathToAddress = [String:String]() + self.rootPath = rootPath + } + +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP39+WordLists.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP39+WordLists.swift new file mode 100755 index 000000000..79b68efcb --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP39+WordLists.swift @@ -0,0 +1,35 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + + +extension BIP39Language { + var englishWords: [String] { + return "abandon ability able about above absent absorb abstract absurd abuse access accident account accuse achieve acid acoustic acquire across act action actor actress actual adapt add addict address adjust admit adult advance advice aerobic affair afford afraid again age agent agree ahead aim air airport aisle alarm album alcohol alert alien all alley allow almost alone alpha already also alter always amateur amazing among amount amused analyst anchor ancient anger angle angry animal ankle announce annual another answer antenna antique anxiety any apart apology appear apple approve april arch arctic area arena argue arm armed armor army around arrange arrest arrive arrow art artefact artist artwork ask aspect assault asset assist assume asthma athlete atom attack attend attitude attract auction audit august aunt author auto autumn average avocado avoid awake aware away awesome awful awkward axis baby bachelor bacon badge bag balance balcony ball bamboo banana banner bar barely bargain barrel base basic basket battle beach bean beauty because become beef before begin behave behind believe below belt bench benefit best betray better between beyond bicycle bid bike bind biology bird birth bitter black blade blame blanket blast bleak bless blind blood blossom blouse blue blur blush board boat body boil bomb bone bonus book boost border boring borrow boss bottom bounce box boy bracket brain brand brass brave bread breeze brick bridge brief bright bring brisk broccoli broken bronze broom brother brown brush bubble buddy budget buffalo build bulb bulk bullet bundle bunker burden burger burst bus business busy butter buyer buzz cabbage cabin cable cactus cage cake call calm camera camp can canal cancel candy cannon canoe canvas canyon capable capital captain car carbon card cargo carpet carry cart case cash casino castle casual cat catalog catch category cattle caught cause caution cave ceiling celery cement census century cereal certain chair chalk champion change chaos chapter charge chase chat cheap check cheese chef cherry chest chicken chief child chimney choice choose chronic chuckle chunk churn cigar cinnamon circle citizen city civil claim clap clarify claw clay clean clerk clever click client cliff climb clinic clip clock clog close cloth cloud clown club clump cluster clutch coach coast coconut code coffee coil coin collect color column combine come comfort comic common company concert conduct confirm congress connect consider control convince cook cool copper copy coral core corn correct cost cotton couch country couple course cousin cover coyote crack cradle craft cram crane crash crater crawl crazy cream credit creek crew cricket crime crisp critic crop cross crouch crowd crucial cruel cruise crumble crunch crush cry crystal cube culture cup cupboard curious current curtain curve cushion custom cute cycle dad damage damp dance danger daring dash daughter dawn day deal debate debris decade december decide decline decorate decrease deer defense define defy degree delay deliver demand demise denial dentist deny depart depend deposit depth deputy derive describe desert design desk despair destroy detail detect develop device devote diagram dial diamond diary dice diesel diet differ digital dignity dilemma dinner dinosaur direct dirt disagree discover disease dish dismiss disorder display distance divert divide divorce dizzy doctor document dog doll dolphin domain donate donkey donor door dose double dove draft dragon drama drastic draw dream dress drift drill drink drip drive drop drum dry duck dumb dune during dust dutch duty dwarf dynamic eager eagle early earn earth easily east easy echo ecology economy edge edit educate effort egg eight either elbow elder electric elegant element elephant elevator elite else embark embody embrace emerge emotion employ empower empty enable enact end endless endorse enemy energy enforce engage engine enhance enjoy enlist enough enrich enroll ensure enter entire entry envelope episode equal equip era erase erode erosion error erupt escape essay essence estate eternal ethics evidence evil evoke evolve exact example excess exchange excite exclude excuse execute exercise exhaust exhibit exile exist exit exotic expand expect expire explain expose express extend extra eye eyebrow fabric face faculty fade faint faith fall false fame family famous fan fancy fantasy farm fashion fat fatal father fatigue fault favorite feature february federal fee feed feel female fence festival fetch fever few fiber fiction field figure file film filter final find fine finger finish fire firm first fiscal fish fit fitness fix flag flame flash flat flavor flee flight flip float flock floor flower fluid flush fly foam focus fog foil fold follow food foot force forest forget fork fortune forum forward fossil foster found fox fragile frame frequent fresh friend fringe frog front frost frown frozen fruit fuel fun funny furnace fury future gadget gain galaxy gallery game gap garage garbage garden garlic garment gas gasp gate gather gauge gaze general genius genre gentle genuine gesture ghost giant gift giggle ginger giraffe girl give glad glance glare glass glide glimpse globe gloom glory glove glow glue goat goddess gold good goose gorilla gospel gossip govern gown grab grace grain grant grape grass gravity great green grid grief grit grocery group grow grunt guard guess guide guilt guitar gun gym habit hair half hammer hamster hand happy harbor hard harsh harvest hat have hawk hazard head health heart heavy hedgehog height hello helmet help hen hero hidden high hill hint hip hire history hobby hockey hold hole holiday hollow home honey hood hope horn horror horse hospital host hotel hour hover hub huge human humble humor hundred hungry hunt hurdle hurry hurt husband hybrid ice icon idea identify idle ignore ill illegal illness image imitate immense immune impact impose improve impulse inch include income increase index indicate indoor industry infant inflict inform inhale inherit initial inject injury inmate inner innocent input inquiry insane insect inside inspire install intact interest into invest invite involve iron island isolate issue item ivory jacket jaguar jar jazz jealous jeans jelly jewel job join joke journey joy judge juice jump jungle junior junk just kangaroo keen keep ketchup key kick kid kidney kind kingdom kiss kit kitchen kite kitten kiwi knee knife knock know lab label labor ladder lady lake lamp language laptop large later latin laugh laundry lava law lawn lawsuit layer lazy leader leaf learn leave lecture left leg legal legend leisure lemon lend length lens leopard lesson letter level liar liberty library license life lift light like limb limit link lion liquid list little live lizard load loan lobster local lock logic lonely long loop lottery loud lounge love loyal lucky luggage lumber lunar lunch luxury lyrics machine mad magic magnet maid mail main major make mammal man manage mandate mango mansion manual maple marble march margin marine market marriage mask mass master match material math matrix matter maximum maze meadow mean measure meat mechanic medal media melody melt member memory mention menu mercy merge merit merry mesh message metal method middle midnight milk million mimic mind minimum minor minute miracle mirror misery miss mistake mix mixed mixture mobile model modify mom moment monitor monkey monster month moon moral more morning mosquito mother motion motor mountain mouse move movie much muffin mule multiply muscle museum mushroom music must mutual myself mystery myth naive name napkin narrow nasty nation nature near neck need negative neglect neither nephew nerve nest net network neutral never news next nice night noble noise nominee noodle normal north nose notable note nothing notice novel now nuclear number nurse nut oak obey object oblige obscure observe obtain obvious occur ocean october odor off offer office often oil okay old olive olympic omit once one onion online only open opera opinion oppose option orange orbit orchard order ordinary organ orient original orphan ostrich other outdoor outer output outside oval oven over own owner oxygen oyster ozone pact paddle page pair palace palm panda panel panic panther paper parade parent park parrot party pass patch path patient patrol pattern pause pave payment peace peanut pear peasant pelican pen penalty pencil people pepper perfect permit person pet phone photo phrase physical piano picnic picture piece pig pigeon pill pilot pink pioneer pipe pistol pitch pizza place planet plastic plate play please pledge pluck plug plunge poem poet point polar pole police pond pony pool popular portion position possible post potato pottery poverty powder power practice praise predict prefer prepare present pretty prevent price pride primary print priority prison private prize problem process produce profit program project promote proof property prosper protect proud provide public pudding pull pulp pulse pumpkin punch pupil puppy purchase purity purpose purse push put puzzle pyramid quality quantum quarter question quick quit quiz quote rabbit raccoon race rack radar radio rail rain raise rally ramp ranch random range rapid rare rate rather raven raw razor ready real reason rebel rebuild recall receive recipe record recycle reduce reflect reform refuse region regret regular reject relax release relief rely remain remember remind remove render renew rent reopen repair repeat replace report require rescue resemble resist resource response result retire retreat return reunion reveal review reward rhythm rib ribbon rice rich ride ridge rifle right rigid ring riot ripple risk ritual rival river road roast robot robust rocket romance roof rookie room rose rotate rough round route royal rubber rude rug rule run runway rural sad saddle sadness safe sail salad salmon salon salt salute same sample sand satisfy satoshi sauce sausage save say scale scan scare scatter scene scheme school science scissors scorpion scout scrap screen script scrub sea search season seat second secret section security seed seek segment select sell seminar senior sense sentence series service session settle setup seven shadow shaft shallow share shed shell sheriff shield shift shine ship shiver shock shoe shoot shop short shoulder shove shrimp shrug shuffle shy sibling sick side siege sight sign silent silk silly silver similar simple since sing siren sister situate six size skate sketch ski skill skin skirt skull slab slam sleep slender slice slide slight slim slogan slot slow slush small smart smile smoke smooth snack snake snap sniff snow soap soccer social sock soda soft solar soldier solid solution solve someone song soon sorry sort soul sound soup source south space spare spatial spawn speak special speed spell spend sphere spice spider spike spin spirit split spoil sponsor spoon sport spot spray spread spring spy square squeeze squirrel stable stadium staff stage stairs stamp stand start state stay steak steel stem step stereo stick still sting stock stomach stone stool story stove strategy street strike strong struggle student stuff stumble style subject submit subway success such sudden suffer sugar suggest suit summer sun sunny sunset super supply supreme sure surface surge surprise surround survey suspect sustain swallow swamp swap swarm swear sweet swift swim swing switch sword symbol symptom syrup system table tackle tag tail talent talk tank tape target task taste tattoo taxi teach team tell ten tenant tennis tent term test text thank that theme then theory there they thing this thought three thrive throw thumb thunder ticket tide tiger tilt timber time tiny tip tired tissue title toast tobacco today toddler toe together toilet token tomato tomorrow tone tongue tonight tool tooth top topic topple torch tornado tortoise toss total tourist toward tower town toy track trade traffic tragic train transfer trap trash travel tray treat tree trend trial tribe trick trigger trim trip trophy trouble truck true truly trumpet trust truth try tube tuition tumble tuna tunnel turkey turn turtle twelve twenty twice twin twist two type typical ugly umbrella unable unaware uncle uncover under undo unfair unfold unhappy uniform unique unit universe unknown unlock until unusual unveil update upgrade uphold upon upper upset urban urge usage use used useful useless usual utility vacant vacuum vague valid valley valve van vanish vapor various vast vault vehicle velvet vendor venture venue verb verify version very vessel veteran viable vibrant vicious victory video view village vintage violin virtual virus visa visit visual vital vivid vocal voice void volcano volume vote voyage wage wagon wait walk wall walnut want warfare warm warrior wash wasp waste water wave way wealth weapon wear weasel weather web wedding weekend weird welcome west wet whale what wheat wheel when where whip whisper wide width wife wild will win window wine wing wink winner winter wire wisdom wise wish witness wolf woman wonder wood wool word work world worry worth wrap wreck wrestle wrist write wrong yard year yellow you young youth zebra zero zone zoo".components(separatedBy: " ") + } + var simplifiedchineseWords: [String] { + return "的 一 是 在 不 了 有 和 人 这 中 大 为 上 个 国 我 以 要 他 时 来 用 们 生 到 作 地 于 出 就 分 对 成 会 可 主 发 年 动 同 工 也 能 下 过 子 说 产 种 面 而 方 后 多 定 行 学 法 所 民 得 经 十 三 之 进 着 等 部 度 家 电 力 里 如 水 化 高 自 二 理 起 小 物 现 实 加 量 都 两 体 制 机 当 使 点 从 业 本 去 把 性 好 应 开 它 合 还 因 由 其 些 然 前 外 天 政 四 日 那 社 义 事 平 形 相 全 表 间 样 与 关 各 重 新 线 内 数 正 心 反 你 明 看 原 又 么 利 比 或 但 质 气 第 向 道 命 此 变 条 只 没 结 解 问 意 建 月 公 无 系 军 很 情 者 最 立 代 想 已 通 并 提 直 题 党 程 展 五 果 料 象 员 革 位 入 常 文 总 次 品 式 活 设 及 管 特 件 长 求 老 头 基 资 边 流 路 级 少 图 山 统 接 知 较 将 组 见 计 别 她 手 角 期 根 论 运 农 指 几 九 区 强 放 决 西 被 干 做 必 战 先 回 则 任 取 据 处 队 南 给 色 光 门 即 保 治 北 造 百 规 热 领 七 海 口 东 导 器 压 志 世 金 增 争 济 阶 油 思 术 极 交 受 联 什 认 六 共 权 收 证 改 清 美 再 采 转 更 单 风 切 打 白 教 速 花 带 安 场 身 车 例 真 务 具 万 每 目 至 达 走 积 示 议 声 报 斗 完 类 八 离 华 名 确 才 科 张 信 马 节 话 米 整 空 元 况 今 集 温 传 土 许 步 群 广 石 记 需 段 研 界 拉 林 律 叫 且 究 观 越 织 装 影 算 低 持 音 众 书 布 复 容 儿 须 际 商 非 验 连 断 深 难 近 矿 千 周 委 素 技 备 半 办 青 省 列 习 响 约 支 般 史 感 劳 便 团 往 酸 历 市 克 何 除 消 构 府 称 太 准 精 值 号 率 族 维 划 选 标 写 存 候 毛 亲 快 效 斯 院 查 江 型 眼 王 按 格 养 易 置 派 层 片 始 却 专 状 育 厂 京 识 适 属 圆 包 火 住 调 满 县 局 照 参 红 细 引 听 该 铁 价 严 首 底 液 官 德 随 病 苏 失 尔 死 讲 配 女 黄 推 显 谈 罪 神 艺 呢 席 含 企 望 密 批 营 项 防 举 球 英 氧 势 告 李 台 落 木 帮 轮 破 亚 师 围 注 远 字 材 排 供 河 态 封 另 施 减 树 溶 怎 止 案 言 士 均 武 固 叶 鱼 波 视 仅 费 紧 爱 左 章 早 朝 害 续 轻 服 试 食 充 兵 源 判 护 司 足 某 练 差 致 板 田 降 黑 犯 负 击 范 继 兴 似 余 坚 曲 输 修 故 城 夫 够 送 笔 船 占 右 财 吃 富 春 职 觉 汉 画 功 巴 跟 虽 杂 飞 检 吸 助 升 阳 互 初 创 抗 考 投 坏 策 古 径 换 未 跑 留 钢 曾 端 责 站 简 述 钱 副 尽 帝 射 草 冲 承 独 令 限 阿 宣 环 双 请 超 微 让 控 州 良 轴 找 否 纪 益 依 优 顶 础 载 倒 房 突 坐 粉 敌 略 客 袁 冷 胜 绝 析 块 剂 测 丝 协 诉 念 陈 仍 罗 盐 友 洋 错 苦 夜 刑 移 频 逐 靠 混 母 短 皮 终 聚 汽 村 云 哪 既 距 卫 停 烈 央 察 烧 迅 境 若 印 洲 刻 括 激 孔 搞 甚 室 待 核 校 散 侵 吧 甲 游 久 菜 味 旧 模 湖 货 损 预 阻 毫 普 稳 乙 妈 植 息 扩 银 语 挥 酒 守 拿 序 纸 医 缺 雨 吗 针 刘 啊 急 唱 误 训 愿 审 附 获 茶 鲜 粮 斤 孩 脱 硫 肥 善 龙 演 父 渐 血 欢 械 掌 歌 沙 刚 攻 谓 盾 讨 晚 粒 乱 燃 矛 乎 杀 药 宁 鲁 贵 钟 煤 读 班 伯 香 介 迫 句 丰 培 握 兰 担 弦 蛋 沉 假 穿 执 答 乐 谁 顺 烟 缩 征 脸 喜 松 脚 困 异 免 背 星 福 买 染 井 概 慢 怕 磁 倍 祖 皇 促 静 补 评 翻 肉 践 尼 衣 宽 扬 棉 希 伤 操 垂 秋 宜 氢 套 督 振 架 亮 末 宪 庆 编 牛 触 映 雷 销 诗 座 居 抓 裂 胞 呼 娘 景 威 绿 晶 厚 盟 衡 鸡 孙 延 危 胶 屋 乡 临 陆 顾 掉 呀 灯 岁 措 束 耐 剧 玉 赵 跳 哥 季 课 凯 胡 额 款 绍 卷 齐 伟 蒸 殖 永 宗 苗 川 炉 岩 弱 零 杨 奏 沿 露 杆 探 滑 镇 饭 浓 航 怀 赶 库 夺 伊 灵 税 途 灭 赛 归 召 鼓 播 盘 裁 险 康 唯 录 菌 纯 借 糖 盖 横 符 私 努 堂 域 枪 润 幅 哈 竟 熟 虫 泽 脑 壤 碳 欧 遍 侧 寨 敢 彻 虑 斜 薄 庭 纳 弹 饲 伸 折 麦 湿 暗 荷 瓦 塞 床 筑 恶 户 访 塔 奇 透 梁 刀 旋 迹 卡 氯 遇 份 毒 泥 退 洗 摆 灰 彩 卖 耗 夏 择 忙 铜 献 硬 予 繁 圈 雪 函 亦 抽 篇 阵 阴 丁 尺 追 堆 雄 迎 泛 爸 楼 避 谋 吨 野 猪 旗 累 偏 典 馆 索 秦 脂 潮 爷 豆 忽 托 惊 塑 遗 愈 朱 替 纤 粗 倾 尚 痛 楚 谢 奋 购 磨 君 池 旁 碎 骨 监 捕 弟 暴 割 贯 殊 释 词 亡 壁 顿 宝 午 尘 闻 揭 炮 残 冬 桥 妇 警 综 招 吴 付 浮 遭 徐 您 摇 谷 赞 箱 隔 订 男 吹 园 纷 唐 败 宋 玻 巨 耕 坦 荣 闭 湾 键 凡 驻 锅 救 恩 剥 凝 碱 齿 截 炼 麻 纺 禁 废 盛 版 缓 净 睛 昌 婚 涉 筒 嘴 插 岸 朗 庄 街 藏 姑 贸 腐 奴 啦 惯 乘 伙 恢 匀 纱 扎 辩 耳 彪 臣 亿 璃 抵 脉 秀 萨 俄 网 舞 店 喷 纵 寸 汗 挂 洪 贺 闪 柬 爆 烯 津 稻 墙 软 勇 像 滚 厘 蒙 芳 肯 坡 柱 荡 腿 仪 旅 尾 轧 冰 贡 登 黎 削 钻 勒 逃 障 氨 郭 峰 币 港 伏 轨 亩 毕 擦 莫 刺 浪 秘 援 株 健 售 股 岛 甘 泡 睡 童 铸 汤 阀 休 汇 舍 牧 绕 炸 哲 磷 绩 朋 淡 尖 启 陷 柴 呈 徒 颜 泪 稍 忘 泵 蓝 拖 洞 授 镜 辛 壮 锋 贫 虚 弯 摩 泰 幼 廷 尊 窗 纲 弄 隶 疑 氏 宫 姐 震 瑞 怪 尤 琴 循 描 膜 违 夹 腰 缘 珠 穷 森 枝 竹 沟 催 绳 忆 邦 剩 幸 浆 栏 拥 牙 贮 礼 滤 钠 纹 罢 拍 咱 喊 袖 埃 勤 罚 焦 潜 伍 墨 欲 缝 姓 刊 饱 仿 奖 铝 鬼 丽 跨 默 挖 链 扫 喝 袋 炭 污 幕 诸 弧 励 梅 奶 洁 灾 舟 鉴 苯 讼 抱 毁 懂 寒 智 埔 寄 届 跃 渡 挑 丹 艰 贝 碰 拔 爹 戴 码 梦 芽 熔 赤 渔 哭 敬 颗 奔 铅 仲 虎 稀 妹 乏 珍 申 桌 遵 允 隆 螺 仓 魏 锐 晓 氮 兼 隐 碍 赫 拨 忠 肃 缸 牵 抢 博 巧 壳 兄 杜 讯 诚 碧 祥 柯 页 巡 矩 悲 灌 龄 伦 票 寻 桂 铺 圣 恐 恰 郑 趣 抬 荒 腾 贴 柔 滴 猛 阔 辆 妻 填 撤 储 签 闹 扰 紫 砂 递 戏 吊 陶 伐 喂 疗 瓶 婆 抚 臂 摸 忍 虾 蜡 邻 胸 巩 挤 偶 弃 槽 劲 乳 邓 吉 仁 烂 砖 租 乌 舰 伴 瓜 浅 丙 暂 燥 橡 柳 迷 暖 牌 秧 胆 详 簧 踏 瓷 谱 呆 宾 糊 洛 辉 愤 竞 隙 怒 粘 乃 绪 肩 籍 敏 涂 熙 皆 侦 悬 掘 享 纠 醒 狂 锁 淀 恨 牲 霸 爬 赏 逆 玩 陵 祝 秒 浙 貌 役 彼 悉 鸭 趋 凤 晨 畜 辈 秩 卵 署 梯 炎 滩 棋 驱 筛 峡 冒 啥 寿 译 浸 泉 帽 迟 硅 疆 贷 漏 稿 冠 嫩 胁 芯 牢 叛 蚀 奥 鸣 岭 羊 凭 串 塘 绘 酵 融 盆 锡 庙 筹 冻 辅 摄 袭 筋 拒 僚 旱 钾 鸟 漆 沈 眉 疏 添 棒 穗 硝 韩 逼 扭 侨 凉 挺 碗 栽 炒 杯 患 馏 劝 豪 辽 勃 鸿 旦 吏 拜 狗 埋 辊 掩 饮 搬 骂 辞 勾 扣 估 蒋 绒 雾 丈 朵 姆 拟 宇 辑 陕 雕 偿 蓄 崇 剪 倡 厅 咬 驶 薯 刷 斥 番 赋 奉 佛 浇 漫 曼 扇 钙 桃 扶 仔 返 俗 亏 腔 鞋 棱 覆 框 悄 叔 撞 骗 勘 旺 沸 孤 吐 孟 渠 屈 疾 妙 惜 仰 狠 胀 谐 抛 霉 桑 岗 嘛 衰 盗 渗 脏 赖 涌 甜 曹 阅 肌 哩 厉 烃 纬 毅 昨 伪 症 煮 叹 钉 搭 茎 笼 酷 偷 弓 锥 恒 杰 坑 鼻 翼 纶 叙 狱 逮 罐 络 棚 抑 膨 蔬 寺 骤 穆 冶 枯 册 尸 凸 绅 坯 牺 焰 轰 欣 晋 瘦 御 锭 锦 丧 旬 锻 垄 搜 扑 邀 亭 酯 迈 舒 脆 酶 闲 忧 酚 顽 羽 涨 卸 仗 陪 辟 惩 杭 姚 肚 捉 飘 漂 昆 欺 吾 郎 烷 汁 呵 饰 萧 雅 邮 迁 燕 撒 姻 赴 宴 烦 债 帐 斑 铃 旨 醇 董 饼 雏 姿 拌 傅 腹 妥 揉 贤 拆 歪 葡 胺 丢 浩 徽 昂 垫 挡 览 贪 慰 缴 汪 慌 冯 诺 姜 谊 凶 劣 诬 耀 昏 躺 盈 骑 乔 溪 丛 卢 抹 闷 咨 刮 驾 缆 悟 摘 铒 掷 颇 幻 柄 惠 惨 佳 仇 腊 窝 涤 剑 瞧 堡 泼 葱 罩 霍 捞 胎 苍 滨 俩 捅 湘 砍 霞 邵 萄 疯 淮 遂 熊 粪 烘 宿 档 戈 驳 嫂 裕 徙 箭 捐 肠 撑 晒 辨 殿 莲 摊 搅 酱 屏 疫 哀 蔡 堵 沫 皱 畅 叠 阁 莱 敲 辖 钩 痕 坝 巷 饿 祸 丘 玄 溜 曰 逻 彭 尝 卿 妨 艇 吞 韦 怨 矮 歇".components(separatedBy: " ") + } + var traditionalchineseWords: [String] { + return "的 一 是 在 不 了 有 和 人 這 中 大 為 上 個 國 我 以 要 他 時 來 用 們 生 到 作 地 於 出 就 分 對 成 會 可 主 發 年 動 同 工 也 能 下 過 子 說 產 種 面 而 方 後 多 定 行 學 法 所 民 得 經 十 三 之 進 著 等 部 度 家 電 力 裡 如 水 化 高 自 二 理 起 小 物 現 實 加 量 都 兩 體 制 機 當 使 點 從 業 本 去 把 性 好 應 開 它 合 還 因 由 其 些 然 前 外 天 政 四 日 那 社 義 事 平 形 相 全 表 間 樣 與 關 各 重 新 線 內 數 正 心 反 你 明 看 原 又 麼 利 比 或 但 質 氣 第 向 道 命 此 變 條 只 沒 結 解 問 意 建 月 公 無 系 軍 很 情 者 最 立 代 想 已 通 並 提 直 題 黨 程 展 五 果 料 象 員 革 位 入 常 文 總 次 品 式 活 設 及 管 特 件 長 求 老 頭 基 資 邊 流 路 級 少 圖 山 統 接 知 較 將 組 見 計 別 她 手 角 期 根 論 運 農 指 幾 九 區 強 放 決 西 被 幹 做 必 戰 先 回 則 任 取 據 處 隊 南 給 色 光 門 即 保 治 北 造 百 規 熱 領 七 海 口 東 導 器 壓 志 世 金 增 爭 濟 階 油 思 術 極 交 受 聯 什 認 六 共 權 收 證 改 清 美 再 採 轉 更 單 風 切 打 白 教 速 花 帶 安 場 身 車 例 真 務 具 萬 每 目 至 達 走 積 示 議 聲 報 鬥 完 類 八 離 華 名 確 才 科 張 信 馬 節 話 米 整 空 元 況 今 集 溫 傳 土 許 步 群 廣 石 記 需 段 研 界 拉 林 律 叫 且 究 觀 越 織 裝 影 算 低 持 音 眾 書 布 复 容 兒 須 際 商 非 驗 連 斷 深 難 近 礦 千 週 委 素 技 備 半 辦 青 省 列 習 響 約 支 般 史 感 勞 便 團 往 酸 歷 市 克 何 除 消 構 府 稱 太 準 精 值 號 率 族 維 劃 選 標 寫 存 候 毛 親 快 效 斯 院 查 江 型 眼 王 按 格 養 易 置 派 層 片 始 卻 專 狀 育 廠 京 識 適 屬 圓 包 火 住 調 滿 縣 局 照 參 紅 細 引 聽 該 鐵 價 嚴 首 底 液 官 德 隨 病 蘇 失 爾 死 講 配 女 黃 推 顯 談 罪 神 藝 呢 席 含 企 望 密 批 營 項 防 舉 球 英 氧 勢 告 李 台 落 木 幫 輪 破 亞 師 圍 注 遠 字 材 排 供 河 態 封 另 施 減 樹 溶 怎 止 案 言 士 均 武 固 葉 魚 波 視 僅 費 緊 愛 左 章 早 朝 害 續 輕 服 試 食 充 兵 源 判 護 司 足 某 練 差 致 板 田 降 黑 犯 負 擊 范 繼 興 似 餘 堅 曲 輸 修 故 城 夫 夠 送 筆 船 佔 右 財 吃 富 春 職 覺 漢 畫 功 巴 跟 雖 雜 飛 檢 吸 助 昇 陽 互 初 創 抗 考 投 壞 策 古 徑 換 未 跑 留 鋼 曾 端 責 站 簡 述 錢 副 盡 帝 射 草 衝 承 獨 令 限 阿 宣 環 雙 請 超 微 讓 控 州 良 軸 找 否 紀 益 依 優 頂 礎 載 倒 房 突 坐 粉 敵 略 客 袁 冷 勝 絕 析 塊 劑 測 絲 協 訴 念 陳 仍 羅 鹽 友 洋 錯 苦 夜 刑 移 頻 逐 靠 混 母 短 皮 終 聚 汽 村 雲 哪 既 距 衛 停 烈 央 察 燒 迅 境 若 印 洲 刻 括 激 孔 搞 甚 室 待 核 校 散 侵 吧 甲 遊 久 菜 味 舊 模 湖 貨 損 預 阻 毫 普 穩 乙 媽 植 息 擴 銀 語 揮 酒 守 拿 序 紙 醫 缺 雨 嗎 針 劉 啊 急 唱 誤 訓 願 審 附 獲 茶 鮮 糧 斤 孩 脫 硫 肥 善 龍 演 父 漸 血 歡 械 掌 歌 沙 剛 攻 謂 盾 討 晚 粒 亂 燃 矛 乎 殺 藥 寧 魯 貴 鐘 煤 讀 班 伯 香 介 迫 句 豐 培 握 蘭 擔 弦 蛋 沉 假 穿 執 答 樂 誰 順 煙 縮 徵 臉 喜 松 腳 困 異 免 背 星 福 買 染 井 概 慢 怕 磁 倍 祖 皇 促 靜 補 評 翻 肉 踐 尼 衣 寬 揚 棉 希 傷 操 垂 秋 宜 氫 套 督 振 架 亮 末 憲 慶 編 牛 觸 映 雷 銷 詩 座 居 抓 裂 胞 呼 娘 景 威 綠 晶 厚 盟 衡 雞 孫 延 危 膠 屋 鄉 臨 陸 顧 掉 呀 燈 歲 措 束 耐 劇 玉 趙 跳 哥 季 課 凱 胡 額 款 紹 卷 齊 偉 蒸 殖 永 宗 苗 川 爐 岩 弱 零 楊 奏 沿 露 桿 探 滑 鎮 飯 濃 航 懷 趕 庫 奪 伊 靈 稅 途 滅 賽 歸 召 鼓 播 盤 裁 險 康 唯 錄 菌 純 借 糖 蓋 橫 符 私 努 堂 域 槍 潤 幅 哈 竟 熟 蟲 澤 腦 壤 碳 歐 遍 側 寨 敢 徹 慮 斜 薄 庭 納 彈 飼 伸 折 麥 濕 暗 荷 瓦 塞 床 築 惡 戶 訪 塔 奇 透 梁 刀 旋 跡 卡 氯 遇 份 毒 泥 退 洗 擺 灰 彩 賣 耗 夏 擇 忙 銅 獻 硬 予 繁 圈 雪 函 亦 抽 篇 陣 陰 丁 尺 追 堆 雄 迎 泛 爸 樓 避 謀 噸 野 豬 旗 累 偏 典 館 索 秦 脂 潮 爺 豆 忽 托 驚 塑 遺 愈 朱 替 纖 粗 傾 尚 痛 楚 謝 奮 購 磨 君 池 旁 碎 骨 監 捕 弟 暴 割 貫 殊 釋 詞 亡 壁 頓 寶 午 塵 聞 揭 炮 殘 冬 橋 婦 警 綜 招 吳 付 浮 遭 徐 您 搖 谷 贊 箱 隔 訂 男 吹 園 紛 唐 敗 宋 玻 巨 耕 坦 榮 閉 灣 鍵 凡 駐 鍋 救 恩 剝 凝 鹼 齒 截 煉 麻 紡 禁 廢 盛 版 緩 淨 睛 昌 婚 涉 筒 嘴 插 岸 朗 莊 街 藏 姑 貿 腐 奴 啦 慣 乘 夥 恢 勻 紗 扎 辯 耳 彪 臣 億 璃 抵 脈 秀 薩 俄 網 舞 店 噴 縱 寸 汗 掛 洪 賀 閃 柬 爆 烯 津 稻 牆 軟 勇 像 滾 厘 蒙 芳 肯 坡 柱 盪 腿 儀 旅 尾 軋 冰 貢 登 黎 削 鑽 勒 逃 障 氨 郭 峰 幣 港 伏 軌 畝 畢 擦 莫 刺 浪 秘 援 株 健 售 股 島 甘 泡 睡 童 鑄 湯 閥 休 匯 舍 牧 繞 炸 哲 磷 績 朋 淡 尖 啟 陷 柴 呈 徒 顏 淚 稍 忘 泵 藍 拖 洞 授 鏡 辛 壯 鋒 貧 虛 彎 摩 泰 幼 廷 尊 窗 綱 弄 隸 疑 氏 宮 姐 震 瑞 怪 尤 琴 循 描 膜 違 夾 腰 緣 珠 窮 森 枝 竹 溝 催 繩 憶 邦 剩 幸 漿 欄 擁 牙 貯 禮 濾 鈉 紋 罷 拍 咱 喊 袖 埃 勤 罰 焦 潛 伍 墨 欲 縫 姓 刊 飽 仿 獎 鋁 鬼 麗 跨 默 挖 鏈 掃 喝 袋 炭 污 幕 諸 弧 勵 梅 奶 潔 災 舟 鑑 苯 訟 抱 毀 懂 寒 智 埔 寄 屆 躍 渡 挑 丹 艱 貝 碰 拔 爹 戴 碼 夢 芽 熔 赤 漁 哭 敬 顆 奔 鉛 仲 虎 稀 妹 乏 珍 申 桌 遵 允 隆 螺 倉 魏 銳 曉 氮 兼 隱 礙 赫 撥 忠 肅 缸 牽 搶 博 巧 殼 兄 杜 訊 誠 碧 祥 柯 頁 巡 矩 悲 灌 齡 倫 票 尋 桂 鋪 聖 恐 恰 鄭 趣 抬 荒 騰 貼 柔 滴 猛 闊 輛 妻 填 撤 儲 簽 鬧 擾 紫 砂 遞 戲 吊 陶 伐 餵 療 瓶 婆 撫 臂 摸 忍 蝦 蠟 鄰 胸 鞏 擠 偶 棄 槽 勁 乳 鄧 吉 仁 爛 磚 租 烏 艦 伴 瓜 淺 丙 暫 燥 橡 柳 迷 暖 牌 秧 膽 詳 簧 踏 瓷 譜 呆 賓 糊 洛 輝 憤 競 隙 怒 粘 乃 緒 肩 籍 敏 塗 熙 皆 偵 懸 掘 享 糾 醒 狂 鎖 淀 恨 牲 霸 爬 賞 逆 玩 陵 祝 秒 浙 貌 役 彼 悉 鴨 趨 鳳 晨 畜 輩 秩 卵 署 梯 炎 灘 棋 驅 篩 峽 冒 啥 壽 譯 浸 泉 帽 遲 矽 疆 貸 漏 稿 冠 嫩 脅 芯 牢 叛 蝕 奧 鳴 嶺 羊 憑 串 塘 繪 酵 融 盆 錫 廟 籌 凍 輔 攝 襲 筋 拒 僚 旱 鉀 鳥 漆 沈 眉 疏 添 棒 穗 硝 韓 逼 扭 僑 涼 挺 碗 栽 炒 杯 患 餾 勸 豪 遼 勃 鴻 旦 吏 拜 狗 埋 輥 掩 飲 搬 罵 辭 勾 扣 估 蔣 絨 霧 丈 朵 姆 擬 宇 輯 陝 雕 償 蓄 崇 剪 倡 廳 咬 駛 薯 刷 斥 番 賦 奉 佛 澆 漫 曼 扇 鈣 桃 扶 仔 返 俗 虧 腔 鞋 棱 覆 框 悄 叔 撞 騙 勘 旺 沸 孤 吐 孟 渠 屈 疾 妙 惜 仰 狠 脹 諧 拋 黴 桑 崗 嘛 衰 盜 滲 臟 賴 湧 甜 曹 閱 肌 哩 厲 烴 緯 毅 昨 偽 症 煮 嘆 釘 搭 莖 籠 酷 偷 弓 錐 恆 傑 坑 鼻 翼 綸 敘 獄 逮 罐 絡 棚 抑 膨 蔬 寺 驟 穆 冶 枯 冊 屍 凸 紳 坯 犧 焰 轟 欣 晉 瘦 禦 錠 錦 喪 旬 鍛 壟 搜 撲 邀 亭 酯 邁 舒 脆 酶 閒 憂 酚 頑 羽 漲 卸 仗 陪 闢 懲 杭 姚 肚 捉 飄 漂 昆 欺 吾 郎 烷 汁 呵 飾 蕭 雅 郵 遷 燕 撒 姻 赴 宴 煩 債 帳 斑 鈴 旨 醇 董 餅 雛 姿 拌 傅 腹 妥 揉 賢 拆 歪 葡 胺 丟 浩 徽 昂 墊 擋 覽 貪 慰 繳 汪 慌 馮 諾 姜 誼 兇 劣 誣 耀 昏 躺 盈 騎 喬 溪 叢 盧 抹 悶 諮 刮 駕 纜 悟 摘 鉺 擲 頗 幻 柄 惠 慘 佳 仇 臘 窩 滌 劍 瞧 堡 潑 蔥 罩 霍 撈 胎 蒼 濱 倆 捅 湘 砍 霞 邵 萄 瘋 淮 遂 熊 糞 烘 宿 檔 戈 駁 嫂 裕 徙 箭 捐 腸 撐 曬 辨 殿 蓮 攤 攪 醬 屏 疫 哀 蔡 堵 沫 皺 暢 疊 閣 萊 敲 轄 鉤 痕 壩 巷 餓 禍 丘 玄 溜 曰 邏 彭 嘗 卿 妨 艇 吞 韋 怨 矮 歇".components(separatedBy: " ") + } + var japaneseWords: [String] { + return "あいこくしん あいさつ あいだ あおぞら あかちゃん あきる あけがた あける あこがれる あさい あさひ あしあと あじわう あずかる あずき あそぶ あたえる あたためる あたりまえ あたる あつい あつかう あっしゅく あつまり あつめる あてな あてはまる あひる あぶら あぶる あふれる あまい あまど あまやかす あまり あみもの あめりか あやまる あゆむ あらいぐま あらし あらすじ あらためる あらゆる あらわす ありがとう あわせる あわてる あんい あんがい あんこ あんぜん あんてい あんない あんまり いいだす いおん いがい いがく いきおい いきなり いきもの いきる いくじ いくぶん いけばな いけん いこう いこく いこつ いさましい いさん いしき いじゅう いじょう いじわる いずみ いずれ いせい いせえび いせかい いせき いぜん いそうろう いそがしい いだい いだく いたずら いたみ いたりあ いちおう いちじ いちど いちば いちぶ いちりゅう いつか いっしゅん いっせい いっそう いったん いっち いってい いっぽう いてざ いてん いどう いとこ いない いなか いねむり いのち いのる いはつ いばる いはん いびき いひん いふく いへん いほう いみん いもうと いもたれ いもり いやがる いやす いよかん いよく いらい いらすと いりぐち いりょう いれい いれもの いれる いろえんぴつ いわい いわう いわかん いわば いわゆる いんげんまめ いんさつ いんしょう いんよう うえき うえる うおざ うがい うかぶ うかべる うきわ うくらいな うくれれ うけたまわる うけつけ うけとる うけもつ うける うごかす うごく うこん うさぎ うしなう うしろがみ うすい うすぎ うすぐらい うすめる うせつ うちあわせ うちがわ うちき うちゅう うっかり うつくしい うったえる うつる うどん うなぎ うなじ うなずく うなる うねる うのう うぶげ うぶごえ うまれる うめる うもう うやまう うよく うらがえす うらぐち うらない うりあげ うりきれ うるさい うれしい うれゆき うれる うろこ うわき うわさ うんこう うんちん うんてん うんどう えいえん えいが えいきょう えいご えいせい えいぶん えいよう えいわ えおり えがお えがく えきたい えくせる えしゃく えすて えつらん えのぐ えほうまき えほん えまき えもじ えもの えらい えらぶ えりあ えんえん えんかい えんぎ えんげき えんしゅう えんぜつ えんそく えんちょう えんとつ おいかける おいこす おいしい おいつく おうえん おうさま おうじ おうせつ おうたい おうふく おうべい おうよう おえる おおい おおう おおどおり おおや おおよそ おかえり おかず おがむ おかわり おぎなう おきる おくさま おくじょう おくりがな おくる おくれる おこす おこなう おこる おさえる おさない おさめる おしいれ おしえる おじぎ おじさん おしゃれ おそらく おそわる おたがい おたく おだやか おちつく おっと おつり おでかけ おとしもの おとなしい おどり おどろかす おばさん おまいり おめでとう おもいで おもう おもたい おもちゃ おやつ おやゆび およぼす おらんだ おろす おんがく おんけい おんしゃ おんせん おんだん おんちゅう おんどけい かあつ かいが がいき がいけん がいこう かいさつ かいしゃ かいすいよく かいぜん かいぞうど かいつう かいてん かいとう かいふく がいへき かいほう かいよう がいらい かいわ かえる かおり かかえる かがく かがし かがみ かくご かくとく かざる がぞう かたい かたち がちょう がっきゅう がっこう がっさん がっしょう かなざわし かのう がはく かぶか かほう かほご かまう かまぼこ かめれおん かゆい かようび からい かるい かろう かわく かわら がんか かんけい かんこう かんしゃ かんそう かんたん かんち がんばる きあい きあつ きいろ ぎいん きうい きうん きえる きおう きおく きおち きおん きかい きかく きかんしゃ ききて きくばり きくらげ きけんせい きこう きこえる きこく きさい きさく きさま きさらぎ ぎじかがく ぎしき ぎじたいけん ぎじにってい ぎじゅつしゃ きすう きせい きせき きせつ きそう きぞく きぞん きたえる きちょう きつえん ぎっちり きつつき きつね きてい きどう きどく きない きなが きなこ きぬごし きねん きのう きのした きはく きびしい きひん きふく きぶん きぼう きほん きまる きみつ きむずかしい きめる きもだめし きもち きもの きゃく きやく ぎゅうにく きよう きょうりゅう きらい きらく きりん きれい きれつ きろく ぎろん きわめる ぎんいろ きんかくじ きんじょ きんようび ぐあい くいず くうかん くうき くうぐん くうこう ぐうせい くうそう ぐうたら くうふく くうぼ くかん くきょう くげん ぐこう くさい くさき くさばな くさる くしゃみ くしょう くすのき くすりゆび くせげ くせん ぐたいてき くださる くたびれる くちこみ くちさき くつした ぐっすり くつろぐ くとうてん くどく くなん くねくね くのう くふう くみあわせ くみたてる くめる くやくしょ くらす くらべる くるま くれる くろう くわしい ぐんかん ぐんしょく ぐんたい ぐんて けあな けいかく けいけん けいこ けいさつ げいじゅつ けいたい げいのうじん けいれき けいろ けおとす けおりもの げきか げきげん げきだん げきちん げきとつ げきは げきやく げこう げこくじょう げざい けさき げざん けしき けしごむ けしょう げすと けたば けちゃっぷ けちらす けつあつ けつい けつえき けっこん けつじょ けっせき けってい けつまつ げつようび げつれい けつろん げどく けとばす けとる けなげ けなす けなみ けぬき げねつ けねん けはい げひん けぶかい げぼく けまり けみかる けむし けむり けもの けらい けろけろ けわしい けんい けんえつ けんお けんか げんき けんげん けんこう けんさく けんしゅう けんすう げんそう けんちく けんてい けんとう けんない けんにん げんぶつ けんま けんみん けんめい けんらん けんり こあくま こいぬ こいびと ごうい こうえん こうおん こうかん ごうきゅう ごうけい こうこう こうさい こうじ こうすい ごうせい こうそく こうたい こうちゃ こうつう こうてい こうどう こうない こうはい ごうほう ごうまん こうもく こうりつ こえる こおり ごかい ごがつ ごかん こくご こくさい こくとう こくない こくはく こぐま こけい こける ここのか こころ こさめ こしつ こすう こせい こせき こぜん こそだて こたい こたえる こたつ こちょう こっか こつこつ こつばん こつぶ こてい こてん ことがら ことし ことば ことり こなごな こねこね このまま このみ このよ ごはん こひつじ こふう こふん こぼれる ごまあぶら こまかい ごますり こまつな こまる こむぎこ こもじ こもち こもの こもん こやく こやま こゆう こゆび こよい こよう こりる これくしょん ころっけ こわもて こわれる こんいん こんかい こんき こんしゅう こんすい こんだて こんとん こんなん こんびに こんぽん こんまけ こんや こんれい こんわく ざいえき さいかい さいきん ざいげん ざいこ さいしょ さいせい ざいたく ざいちゅう さいてき ざいりょう さうな さかいし さがす さかな さかみち さがる さぎょう さくし さくひん さくら さこく さこつ さずかる ざせき さたん さつえい ざつおん ざっか ざつがく さっきょく ざっし さつじん ざっそう さつたば さつまいも さてい さといも さとう さとおや さとし さとる さのう さばく さびしい さべつ さほう さほど さます さみしい さみだれ さむけ さめる さやえんどう さゆう さよう さよく さらだ ざるそば さわやか さわる さんいん さんか さんきゃく さんこう さんさい ざんしょ さんすう さんせい さんそ さんち さんま さんみ さんらん しあい しあげ しあさって しあわせ しいく しいん しうち しえい しおけ しかい しかく じかん しごと しすう じだい したうけ したぎ したて したみ しちょう しちりん しっかり しつじ しつもん してい してき してつ じてん じどう しなぎれ しなもの しなん しねま しねん しのぐ しのぶ しはい しばかり しはつ しはらい しはん しひょう しふく じぶん しへい しほう しほん しまう しまる しみん しむける じむしょ しめい しめる しもん しゃいん しゃうん しゃおん じゃがいも しやくしょ しゃくほう しゃけん しゃこ しゃざい しゃしん しゃせん しゃそう しゃたい しゃちょう しゃっきん じゃま しゃりん しゃれい じゆう じゅうしょ しゅくはく じゅしん しゅっせき しゅみ しゅらば じゅんばん しょうかい しょくたく しょっけん しょどう しょもつ しらせる しらべる しんか しんこう じんじゃ しんせいじ しんちく しんりん すあげ すあし すあな ずあん すいえい すいか すいとう ずいぶん すいようび すうがく すうじつ すうせん すおどり すきま すくう すくない すける すごい すこし ずさん すずしい すすむ すすめる すっかり ずっしり ずっと すてき すてる すねる すのこ すはだ すばらしい ずひょう ずぶぬれ すぶり すふれ すべて すべる ずほう すぼん すまい すめし すもう すやき すらすら するめ すれちがう すろっと すわる すんぜん すんぽう せあぶら せいかつ せいげん せいじ せいよう せおう せかいかん せきにん せきむ せきゆ せきらんうん せけん せこう せすじ せたい せたけ せっかく せっきゃく ぜっく せっけん せっこつ せっさたくま せつぞく せつだん せつでん せっぱん せつび せつぶん せつめい せつりつ せなか せのび せはば せびろ せぼね せまい せまる せめる せもたれ せりふ ぜんあく せんい せんえい せんか せんきょ せんく せんげん ぜんご せんさい せんしゅ せんすい せんせい せんぞ せんたく せんちょう せんてい せんとう せんぬき せんねん せんぱい ぜんぶ ぜんぽう せんむ せんめんじょ せんもん せんやく せんゆう せんよう ぜんら ぜんりゃく せんれい せんろ そあく そいとげる そいね そうがんきょう そうき そうご そうしん そうだん そうなん そうび そうめん そうり そえもの そえん そがい そげき そこう そこそこ そざい そしな そせい そせん そそぐ そだてる そつう そつえん そっかん そつぎょう そっけつ そっこう そっせん そっと そとがわ そとづら そなえる そなた そふぼ そぼく そぼろ そまつ そまる そむく そむりえ そめる そもそも そよかぜ そらまめ そろう そんかい そんけい そんざい そんしつ そんぞく そんちょう ぞんび ぞんぶん そんみん たあい たいいん たいうん たいえき たいおう だいがく たいき たいぐう たいけん たいこ たいざい だいじょうぶ だいすき たいせつ たいそう だいたい たいちょう たいてい だいどころ たいない たいねつ たいのう たいはん だいひょう たいふう たいへん たいほ たいまつばな たいみんぐ たいむ たいめん たいやき たいよう たいら たいりょく たいる たいわん たうえ たえる たおす たおる たおれる たかい たかね たきび たくさん たこく たこやき たさい たしざん だじゃれ たすける たずさわる たそがれ たたかう たたく ただしい たたみ たちばな だっかい だっきゃく だっこ だっしゅつ だったい たてる たとえる たなばた たにん たぬき たのしみ たはつ たぶん たべる たぼう たまご たまる だむる ためいき ためす ためる たもつ たやすい たよる たらす たりきほんがん たりょう たりる たると たれる たれんと たろっと たわむれる だんあつ たんい たんおん たんか たんき たんけん たんご たんさん たんじょうび だんせい たんそく たんたい だんち たんてい たんとう だんな たんにん だんねつ たんのう たんぴん だんぼう たんまつ たんめい だんれつ だんろ だんわ ちあい ちあん ちいき ちいさい ちえん ちかい ちから ちきゅう ちきん ちけいず ちけん ちこく ちさい ちしき ちしりょう ちせい ちそう ちたい ちたん ちちおや ちつじょ ちてき ちてん ちぬき ちぬり ちのう ちひょう ちへいせん ちほう ちまた ちみつ ちみどろ ちめいど ちゃんこなべ ちゅうい ちゆりょく ちょうし ちょさくけん ちらし ちらみ ちりがみ ちりょう ちるど ちわわ ちんたい ちんもく ついか ついたち つうか つうじょう つうはん つうわ つかう つかれる つくね つくる つけね つける つごう つたえる つづく つつじ つつむ つとめる つながる つなみ つねづね つのる つぶす つまらない つまる つみき つめたい つもり つもる つよい つるぼ つるみく つわもの つわり てあし てあて てあみ ていおん ていか ていき ていけい ていこく ていさつ ていし ていせい ていたい ていど ていねい ていひょう ていへん ていぼう てうち ておくれ てきとう てくび でこぼこ てさぎょう てさげ てすり てそう てちがい てちょう てつがく てつづき でっぱ てつぼう てつや でぬかえ てぬき てぬぐい てのひら てはい てぶくろ てふだ てほどき てほん てまえ てまきずし てみじか てみやげ てらす てれび てわけ てわたし でんあつ てんいん てんかい てんき てんぐ てんけん てんごく てんさい てんし てんすう でんち てんてき てんとう てんない てんぷら てんぼうだい てんめつ てんらんかい でんりょく でんわ どあい といれ どうかん とうきゅう どうぐ とうし とうむぎ とおい とおか とおく とおす とおる とかい とかす ときおり ときどき とくい とくしゅう とくてん とくに とくべつ とけい とける とこや とさか としょかん とそう とたん とちゅう とっきゅう とっくん とつぜん とつにゅう とどける ととのえる とない となえる となり とのさま とばす どぶがわ とほう とまる とめる ともだち ともる どようび とらえる とんかつ どんぶり ないかく ないこう ないしょ ないす ないせん ないそう なおす ながい なくす なげる なこうど なさけ なたでここ なっとう なつやすみ ななおし なにごと なにもの なにわ なのか なふだ なまいき なまえ なまみ なみだ なめらか なめる なやむ ならう ならび ならぶ なれる なわとび なわばり にあう にいがた にうけ におい にかい にがて にきび にくしみ にくまん にげる にさんかたんそ にしき にせもの にちじょう にちようび にっか にっき にっけい にっこう にっさん にっしょく にっすう にっせき にってい になう にほん にまめ にもつ にやり にゅういん にりんしゃ にわとり にんい にんか にんき にんげん にんしき にんずう にんそう にんたい にんち にんてい にんにく にんぷ にんまり にんむ にんめい にんよう ぬいくぎ ぬかす ぬぐいとる ぬぐう ぬくもり ぬすむ ぬまえび ぬめり ぬらす ぬんちゃく ねあげ ねいき ねいる ねいろ ねぐせ ねくたい ねくら ねこぜ ねこむ ねさげ ねすごす ねそべる ねだん ねつい ねっしん ねつぞう ねったいぎょ ねぶそく ねふだ ねぼう ねほりはほり ねまき ねまわし ねみみ ねむい ねむたい ねもと ねらう ねわざ ねんいり ねんおし ねんかん ねんきん ねんぐ ねんざ ねんし ねんちゃく ねんど ねんぴ ねんぶつ ねんまつ ねんりょう ねんれい のいず のおづま のがす のきなみ のこぎり のこす のこる のせる のぞく のぞむ のたまう のちほど のっく のばす のはら のべる のぼる のみもの のやま のらいぬ のらねこ のりもの のりゆき のれん のんき ばあい はあく ばあさん ばいか ばいく はいけん はいご はいしん はいすい はいせん はいそう はいち ばいばい はいれつ はえる はおる はかい ばかり はかる はくしゅ はけん はこぶ はさみ はさん はしご ばしょ はしる はせる ぱそこん はそん はたん はちみつ はつおん はっかく はづき はっきり はっくつ はっけん はっこう はっさん はっしん はったつ はっちゅう はってん はっぴょう はっぽう はなす はなび はにかむ はぶらし はみがき はむかう はめつ はやい はやし はらう はろうぃん はわい はんい はんえい はんおん はんかく はんきょう ばんぐみ はんこ はんしゃ はんすう はんだん ぱんち ぱんつ はんてい はんとし はんのう はんぱ はんぶん はんぺん はんぼうき はんめい はんらん はんろん ひいき ひうん ひえる ひかく ひかり ひかる ひかん ひくい ひけつ ひこうき ひこく ひさい ひさしぶり ひさん びじゅつかん ひしょ ひそか ひそむ ひたむき ひだり ひたる ひつぎ ひっこし ひっし ひつじゅひん ひっす ひつぜん ぴったり ぴっちり ひつよう ひてい ひとごみ ひなまつり ひなん ひねる ひはん ひびく ひひょう ひほう ひまわり ひまん ひみつ ひめい ひめじし ひやけ ひやす ひよう びょうき ひらがな ひらく ひりつ ひりょう ひるま ひるやすみ ひれい ひろい ひろう ひろき ひろゆき ひんかく ひんけつ ひんこん ひんしゅ ひんそう ぴんち ひんぱん びんぼう ふあん ふいうち ふうけい ふうせん ぷうたろう ふうとう ふうふ ふえる ふおん ふかい ふきん ふくざつ ふくぶくろ ふこう ふさい ふしぎ ふじみ ふすま ふせい ふせぐ ふそく ぶたにく ふたん ふちょう ふつう ふつか ふっかつ ふっき ふっこく ぶどう ふとる ふとん ふのう ふはい ふひょう ふへん ふまん ふみん ふめつ ふめん ふよう ふりこ ふりる ふるい ふんいき ぶんがく ぶんぐ ふんしつ ぶんせき ふんそう ぶんぽう へいあん へいおん へいがい へいき へいげん へいこう へいさ へいしゃ へいせつ へいそ へいたく へいてん へいねつ へいわ へきが へこむ べにいろ べにしょうが へらす へんかん べんきょう べんごし へんさい へんたい べんり ほあん ほいく ぼうぎょ ほうこく ほうそう ほうほう ほうもん ほうりつ ほえる ほおん ほかん ほきょう ぼきん ほくろ ほけつ ほけん ほこう ほこる ほしい ほしつ ほしゅ ほしょう ほせい ほそい ほそく ほたて ほたる ぽちぶくろ ほっきょく ほっさ ほったん ほとんど ほめる ほんい ほんき ほんけ ほんしつ ほんやく まいにち まかい まかせる まがる まける まこと まさつ まじめ ますく まぜる まつり まとめ まなぶ まぬけ まねく まほう まもる まゆげ まよう まろやか まわす まわり まわる まんが まんきつ まんぞく まんなか みいら みうち みえる みがく みかた みかん みけん みこん みじかい みすい みすえる みせる みっか みつかる みつける みてい みとめる みなと みなみかさい みねらる みのう みのがす みほん みもと みやげ みらい みりょく みわく みんか みんぞく むいか むえき むえん むかい むかう むかえ むかし むぎちゃ むける むげん むさぼる むしあつい むしば むじゅん むしろ むすう むすこ むすぶ むすめ むせる むせん むちゅう むなしい むのう むやみ むよう むらさき むりょう むろん めいあん めいうん めいえん めいかく めいきょく めいさい めいし めいそう めいぶつ めいれい めいわく めぐまれる めざす めした めずらしい めだつ めまい めやす めんきょ めんせき めんどう もうしあげる もうどうけん もえる もくし もくてき もくようび もちろん もどる もらう もんく もんだい やおや やける やさい やさしい やすい やすたろう やすみ やせる やそう やたい やちん やっと やっぱり やぶる やめる ややこしい やよい やわらかい ゆうき ゆうびんきょく ゆうべ ゆうめい ゆけつ ゆしゅつ ゆせん ゆそう ゆたか ゆちゃく ゆでる ゆにゅう ゆびわ ゆらい ゆれる ようい ようか ようきゅう ようじ ようす ようちえん よかぜ よかん よきん よくせい よくぼう よけい よごれる よさん よしゅう よそう よそく よっか よてい よどがわく よねつ よやく よゆう よろこぶ よろしい らいう らくがき らくご らくさつ らくだ らしんばん らせん らぞく らたい らっか られつ りえき りかい りきさく りきせつ りくぐん りくつ りけん りこう りせい りそう りそく りてん りねん りゆう りゅうがく りよう りょうり りょかん りょくちゃ りょこう りりく りれき りろん りんご るいけい るいさい るいじ るいせき るすばん るりがわら れいかん れいぎ れいせい れいぞうこ れいとう れいぼう れきし れきだい れんあい れんけい れんこん れんさい れんしゅう れんぞく れんらく ろうか ろうご ろうじん ろうそく ろくが ろこつ ろじうら ろしゅつ ろせん ろてん ろめん ろれつ ろんぎ ろんぱ ろんぶん ろんり わかす わかめ わかやま わかれる わしつ わじまし わすれもの わらう われる".components(separatedBy: " ") + } + var koreanWords: [String] { + return "가격 가끔 가난 가능 가득 가르침 가뭄 가방 가상 가슴 가운데 가을 가이드 가입 가장 가정 가족 가죽 각오 각자 간격 간부 간섭 간장 간접 간판 갈등 갈비 갈색 갈증 감각 감기 감소 감수성 감자 감정 갑자기 강남 강당 강도 강력히 강변 강북 강사 강수량 강아지 강원도 강의 강제 강조 같이 개구리 개나리 개방 개별 개선 개성 개인 객관적 거실 거액 거울 거짓 거품 걱정 건강 건물 건설 건조 건축 걸음 검사 검토 게시판 게임 겨울 견해 결과 결국 결론 결석 결승 결심 결정 결혼 경계 경고 경기 경력 경복궁 경비 경상도 경영 경우 경쟁 경제 경주 경찰 경치 경향 경험 계곡 계단 계란 계산 계속 계약 계절 계층 계획 고객 고구려 고궁 고급 고등학생 고무신 고민 고양이 고장 고전 고집 고춧가루 고통 고향 곡식 골목 골짜기 골프 공간 공개 공격 공군 공급 공기 공동 공무원 공부 공사 공식 공업 공연 공원 공장 공짜 공책 공통 공포 공항 공휴일 과목 과일 과장 과정 과학 관객 관계 관광 관념 관람 관련 관리 관습 관심 관점 관찰 광경 광고 광장 광주 괴로움 굉장히 교과서 교문 교복 교실 교양 교육 교장 교직 교통 교환 교훈 구경 구름 구멍 구별 구분 구석 구성 구속 구역 구입 구청 구체적 국가 국기 국내 국립 국물 국민 국수 국어 국왕 국적 국제 국회 군대 군사 군인 궁극적 권리 권위 권투 귀국 귀신 규정 규칙 균형 그날 그냥 그늘 그러나 그룹 그릇 그림 그제서야 그토록 극복 극히 근거 근교 근래 근로 근무 근본 근원 근육 근처 글씨 글자 금강산 금고 금년 금메달 금액 금연 금요일 금지 긍정적 기간 기관 기념 기능 기독교 기둥 기록 기름 기법 기본 기분 기쁨 기숙사 기술 기억 기업 기온 기운 기원 기적 기준 기침 기혼 기획 긴급 긴장 길이 김밥 김치 김포공항 깍두기 깜빡 깨달음 깨소금 껍질 꼭대기 꽃잎 나들이 나란히 나머지 나물 나침반 나흘 낙엽 난방 날개 날씨 날짜 남녀 남대문 남매 남산 남자 남편 남학생 낭비 낱말 내년 내용 내일 냄비 냄새 냇물 냉동 냉면 냉방 냉장고 넥타이 넷째 노동 노란색 노력 노인 녹음 녹차 녹화 논리 논문 논쟁 놀이 농구 농담 농민 농부 농업 농장 농촌 높이 눈동자 눈물 눈썹 뉴욕 느낌 늑대 능동적 능력 다방 다양성 다음 다이어트 다행 단계 단골 단독 단맛 단순 단어 단위 단점 단체 단추 단편 단풍 달걀 달러 달력 달리 닭고기 담당 담배 담요 담임 답변 답장 당근 당분간 당연히 당장 대규모 대낮 대단히 대답 대도시 대략 대량 대륙 대문 대부분 대신 대응 대장 대전 대접 대중 대책 대출 대충 대통령 대학 대한민국 대합실 대형 덩어리 데이트 도대체 도덕 도둑 도망 도서관 도심 도움 도입 도자기 도저히 도전 도중 도착 독감 독립 독서 독일 독창적 동화책 뒷모습 뒷산 딸아이 마누라 마늘 마당 마라톤 마련 마무리 마사지 마약 마요네즈 마을 마음 마이크 마중 마지막 마찬가지 마찰 마흔 막걸리 막내 막상 만남 만두 만세 만약 만일 만점 만족 만화 많이 말기 말씀 말투 맘대로 망원경 매년 매달 매력 매번 매스컴 매일 매장 맥주 먹이 먼저 먼지 멀리 메일 며느리 며칠 면담 멸치 명단 명령 명예 명의 명절 명칭 명함 모금 모니터 모델 모든 모범 모습 모양 모임 모조리 모집 모퉁이 목걸이 목록 목사 목소리 목숨 목적 목표 몰래 몸매 몸무게 몸살 몸속 몸짓 몸통 몹시 무관심 무궁화 무더위 무덤 무릎 무슨 무엇 무역 무용 무조건 무지개 무척 문구 문득 문법 문서 문제 문학 문화 물가 물건 물결 물고기 물론 물리학 물음 물질 물체 미국 미디어 미사일 미술 미역 미용실 미움 미인 미팅 미혼 민간 민족 민주 믿음 밀가루 밀리미터 밑바닥 바가지 바구니 바나나 바늘 바닥 바닷가 바람 바이러스 바탕 박물관 박사 박수 반대 반드시 반말 반발 반성 반응 반장 반죽 반지 반찬 받침 발가락 발걸음 발견 발달 발레 발목 발바닥 발생 발음 발자국 발전 발톱 발표 밤하늘 밥그릇 밥맛 밥상 밥솥 방금 방면 방문 방바닥 방법 방송 방식 방안 방울 방지 방학 방해 방향 배경 배꼽 배달 배드민턴 백두산 백색 백성 백인 백제 백화점 버릇 버섯 버튼 번개 번역 번지 번호 벌금 벌레 벌써 범위 범인 범죄 법률 법원 법적 법칙 베이징 벨트 변경 변동 변명 변신 변호사 변화 별도 별명 별일 병실 병아리 병원 보관 보너스 보라색 보람 보름 보상 보안 보자기 보장 보전 보존 보통 보편적 보험 복도 복사 복숭아 복습 볶음 본격적 본래 본부 본사 본성 본인 본질 볼펜 봉사 봉지 봉투 부근 부끄러움 부담 부동산 부문 부분 부산 부상 부엌 부인 부작용 부장 부정 부족 부지런히 부친 부탁 부품 부회장 북부 북한 분노 분량 분리 분명 분석 분야 분위기 분필 분홍색 불고기 불과 불교 불꽃 불만 불법 불빛 불안 불이익 불행 브랜드 비극 비난 비닐 비둘기 비디오 비로소 비만 비명 비밀 비바람 비빔밥 비상 비용 비율 비중 비타민 비판 빌딩 빗물 빗방울 빗줄기 빛깔 빨간색 빨래 빨리 사건 사계절 사나이 사냥 사람 사랑 사립 사모님 사물 사방 사상 사생활 사설 사슴 사실 사업 사용 사월 사장 사전 사진 사촌 사춘기 사탕 사투리 사흘 산길 산부인과 산업 산책 살림 살인 살짝 삼계탕 삼국 삼십 삼월 삼촌 상관 상금 상대 상류 상반기 상상 상식 상업 상인 상자 상점 상처 상추 상태 상표 상품 상황 새벽 색깔 색연필 생각 생명 생물 생방송 생산 생선 생신 생일 생활 서랍 서른 서명 서민 서비스 서양 서울 서적 서점 서쪽 서클 석사 석유 선거 선물 선배 선생 선수 선원 선장 선전 선택 선풍기 설거지 설날 설렁탕 설명 설문 설사 설악산 설치 설탕 섭씨 성공 성당 성명 성별 성인 성장 성적 성질 성함 세금 세미나 세상 세월 세종대왕 세탁 센터 센티미터 셋째 소규모 소극적 소금 소나기 소년 소득 소망 소문 소설 소속 소아과 소용 소원 소음 소중히 소지품 소질 소풍 소형 속담 속도 속옷 손가락 손길 손녀 손님 손등 손목 손뼉 손실 손질 손톱 손해 솔직히 솜씨 송아지 송이 송편 쇠고기 쇼핑 수건 수년 수단 수돗물 수동적 수면 수명 수박 수상 수석 수술 수시로 수업 수염 수영 수입 수준 수집 수출 수컷 수필 수학 수험생 수화기 숙녀 숙소 숙제 순간 순서 순수 순식간 순위 숟가락 술병 술집 숫자 스님 스물 스스로 스승 스웨터 스위치 스케이트 스튜디오 스트레스 스포츠 슬쩍 슬픔 습관 습기 승객 승리 승부 승용차 승진 시각 시간 시골 시금치 시나리오 시댁 시리즈 시멘트 시민 시부모 시선 시설 시스템 시아버지 시어머니 시월 시인 시일 시작 시장 시절 시점 시중 시즌 시집 시청 시합 시험 식구 식기 식당 식량 식료품 식물 식빵 식사 식생활 식초 식탁 식품 신고 신규 신념 신문 신발 신비 신사 신세 신용 신제품 신청 신체 신화 실감 실내 실력 실례 실망 실수 실습 실시 실장 실정 실질적 실천 실체 실컷 실태 실패 실험 실현 심리 심부름 심사 심장 심정 심판 쌍둥이 씨름 씨앗 아가씨 아나운서 아드님 아들 아쉬움 아스팔트 아시아 아울러 아저씨 아줌마 아직 아침 아파트 아프리카 아픔 아홉 아흔 악기 악몽 악수 안개 안경 안과 안내 안녕 안동 안방 안부 안주 알루미늄 알코올 암시 암컷 압력 앞날 앞문 애인 애정 액수 앨범 야간 야단 야옹 약간 약국 약속 약수 약점 약품 약혼녀 양념 양력 양말 양배추 양주 양파 어둠 어려움 어른 어젯밤 어쨌든 어쩌다가 어쩐지 언니 언덕 언론 언어 얼굴 얼른 얼음 얼핏 엄마 업무 업종 업체 엉덩이 엉망 엉터리 엊그제 에너지 에어컨 엔진 여건 여고생 여관 여군 여권 여대생 여덟 여동생 여든 여론 여름 여섯 여성 여왕 여인 여전히 여직원 여학생 여행 역사 역시 역할 연결 연구 연극 연기 연락 연설 연세 연속 연습 연애 연예인 연인 연장 연주 연출 연필 연합 연휴 열기 열매 열쇠 열심히 열정 열차 열흘 염려 엽서 영국 영남 영상 영양 영역 영웅 영원히 영하 영향 영혼 영화 옆구리 옆방 옆집 예감 예금 예방 예산 예상 예선 예술 예습 예식장 예약 예전 예절 예정 예컨대 옛날 오늘 오락 오랫동안 오렌지 오로지 오른발 오븐 오십 오염 오월 오전 오직 오징어 오페라 오피스텔 오히려 옥상 옥수수 온갖 온라인 온몸 온종일 온통 올가을 올림픽 올해 옷차림 와이셔츠 와인 완성 완전 왕비 왕자 왜냐하면 왠지 외갓집 외국 외로움 외삼촌 외출 외침 외할머니 왼발 왼손 왼쪽 요금 요일 요즘 요청 용기 용서 용어 우산 우선 우승 우연히 우정 우체국 우편 운동 운명 운반 운전 운행 울산 울음 움직임 웃어른 웃음 워낙 원고 원래 원서 원숭이 원인 원장 원피스 월급 월드컵 월세 월요일 웨이터 위반 위법 위성 위원 위험 위협 윗사람 유난히 유럽 유명 유물 유산 유적 유치원 유학 유행 유형 육군 육상 육십 육체 은행 음력 음료 음반 음성 음식 음악 음주 의견 의논 의문 의복 의식 의심 의외로 의욕 의원 의학 이것 이곳 이념 이놈 이달 이대로 이동 이렇게 이력서 이론적 이름 이민 이발소 이별 이불 이빨 이상 이성 이슬 이야기 이용 이웃 이월 이윽고 이익 이전 이중 이튿날 이틀 이혼 인간 인격 인공 인구 인근 인기 인도 인류 인물 인생 인쇄 인연 인원 인재 인종 인천 인체 인터넷 인하 인형 일곱 일기 일단 일대 일등 일반 일본 일부 일상 일생 일손 일요일 일월 일정 일종 일주일 일찍 일체 일치 일행 일회용 임금 임무 입대 입력 입맛 입사 입술 입시 입원 입장 입학 자가용 자격 자극 자동 자랑 자부심 자식 자신 자연 자원 자율 자전거 자정 자존심 자판 작가 작년 작성 작업 작용 작은딸 작품 잔디 잔뜩 잔치 잘못 잠깐 잠수함 잠시 잠옷 잠자리 잡지 장관 장군 장기간 장래 장례 장르 장마 장면 장모 장미 장비 장사 장소 장식 장애인 장인 장점 장차 장학금 재능 재빨리 재산 재생 재작년 재정 재채기 재판 재학 재활용 저것 저고리 저곳 저녁 저런 저렇게 저번 저울 저절로 저축 적극 적당히 적성 적용 적응 전개 전공 전기 전달 전라도 전망 전문 전반 전부 전세 전시 전용 전자 전쟁 전주 전철 전체 전통 전혀 전후 절대 절망 절반 절약 절차 점검 점수 점심 점원 점점 점차 접근 접시 접촉 젓가락 정거장 정도 정류장 정리 정말 정면 정문 정반대 정보 정부 정비 정상 정성 정오 정원 정장 정지 정치 정확히 제공 제과점 제대로 제목 제발 제법 제삿날 제안 제일 제작 제주도 제출 제품 제한 조각 조건 조금 조깅 조명 조미료 조상 조선 조용히 조절 조정 조직 존댓말 존재 졸업 졸음 종교 종로 종류 종소리 종업원 종종 종합 좌석 죄인 주관적 주름 주말 주머니 주먹 주문 주민 주방 주변 주식 주인 주일 주장 주전자 주택 준비 줄거리 줄기 줄무늬 중간 중계방송 중국 중년 중단 중독 중반 중부 중세 중소기업 중순 중앙 중요 중학교 즉석 즉시 즐거움 증가 증거 증권 증상 증세 지각 지갑 지경 지극히 지금 지급 지능 지름길 지리산 지방 지붕 지식 지역 지우개 지원 지적 지점 지진 지출 직선 직업 직원 직장 진급 진동 진로 진료 진리 진짜 진찰 진출 진통 진행 질문 질병 질서 짐작 집단 집안 집중 짜증 찌꺼기 차남 차라리 차량 차림 차별 차선 차츰 착각 찬물 찬성 참가 참기름 참새 참석 참여 참외 참조 찻잔 창가 창고 창구 창문 창밖 창작 창조 채널 채점 책가방 책방 책상 책임 챔피언 처벌 처음 천국 천둥 천장 천재 천천히 철도 철저히 철학 첫날 첫째 청년 청바지 청소 청춘 체계 체력 체온 체육 체중 체험 초등학생 초반 초밥 초상화 초순 초여름 초원 초저녁 초점 초청 초콜릿 촛불 총각 총리 총장 촬영 최근 최상 최선 최신 최악 최종 추석 추억 추진 추천 추측 축구 축소 축제 축하 출근 출발 출산 출신 출연 출입 출장 출판 충격 충고 충돌 충분히 충청도 취업 취직 취향 치약 친구 친척 칠십 칠월 칠판 침대 침묵 침실 칫솔 칭찬 카메라 카운터 칼국수 캐릭터 캠퍼스 캠페인 커튼 컨디션 컬러 컴퓨터 코끼리 코미디 콘서트 콜라 콤플렉스 콩나물 쾌감 쿠데타 크림 큰길 큰딸 큰소리 큰아들 큰어머니 큰일 큰절 클래식 클럽 킬로 타입 타자기 탁구 탁자 탄생 태권도 태양 태풍 택시 탤런트 터널 터미널 테니스 테스트 테이블 텔레비전 토론 토마토 토요일 통계 통과 통로 통신 통역 통일 통장 통제 통증 통합 통화 퇴근 퇴원 퇴직금 튀김 트럭 특급 특별 특성 특수 특징 특히 튼튼히 티셔츠 파란색 파일 파출소 판결 판단 판매 판사 팔십 팔월 팝송 패션 팩스 팩시밀리 팬티 퍼센트 페인트 편견 편의 편지 편히 평가 평균 평생 평소 평양 평일 평화 포스터 포인트 포장 포함 표면 표정 표준 표현 품목 품질 풍경 풍속 풍습 프랑스 프린터 플라스틱 피곤 피망 피아노 필름 필수 필요 필자 필통 핑계 하느님 하늘 하드웨어 하룻밤 하반기 하숙집 하순 하여튼 하지만 하천 하품 하필 학과 학교 학급 학기 학년 학력 학번 학부모 학비 학생 학술 학습 학용품 학원 학위 학자 학점 한계 한글 한꺼번에 한낮 한눈 한동안 한때 한라산 한마디 한문 한번 한복 한식 한여름 한쪽 할머니 할아버지 할인 함께 함부로 합격 합리적 항공 항구 항상 항의 해결 해군 해답 해당 해물 해석 해설 해수욕장 해안 핵심 핸드백 햄버거 햇볕 햇살 행동 행복 행사 행운 행위 향기 향상 향수 허락 허용 헬기 현관 현금 현대 현상 현실 현장 현재 현지 혈액 협력 형부 형사 형수 형식 형제 형태 형편 혜택 호기심 호남 호랑이 호박 호텔 호흡 혹시 홀로 홈페이지 홍보 홍수 홍차 화면 화분 화살 화요일 화장 화학 확보 확인 확장 확정 환갑 환경 환영 환율 환자 활기 활동 활발히 활용 활짝 회견 회관 회복 회색 회원 회장 회전 횟수 횡단보도 효율적 후반 후춧가루 훈련 훨씬 휴식 휴일 흉내 흐름 흑백 흑인 흔적 흔히 흥미 흥분 희곡 희망 희생 흰색 힘껏".components(separatedBy: " ") + } + var frenchWords: [String] { + return "abaisser abandon abdiquer abeille abolir aborder aboutir aboyer abrasif abreuver abriter abroger abrupt absence absolu absurde abusif abyssal académie acajou acarien accabler accepter acclamer accolade accroche accuser acerbe achat acheter aciduler acier acompte acquérir acronyme acteur actif actuel adepte adéquat adhésif adjectif adjuger admettre admirer adopter adorer adoucir adresse adroit adulte adverbe aérer aéronef affaire affecter affiche affreux affubler agacer agencer agile agiter agrafer agréable agrume aider aiguille ailier aimable aisance ajouter ajuster alarmer alchimie alerte algèbre algue aliéner aliment alléger alliage allouer allumer alourdir alpaga altesse alvéole amateur ambigu ambre aménager amertume amidon amiral amorcer amour amovible amphibie ampleur amusant analyse anaphore anarchie anatomie ancien anéantir angle angoisse anguleux animal annexer annonce annuel anodin anomalie anonyme anormal antenne antidote anxieux apaiser apéritif aplanir apologie appareil appeler apporter appuyer aquarium aqueduc arbitre arbuste ardeur ardoise argent arlequin armature armement armoire armure arpenter arracher arriver arroser arsenic artériel article aspect asphalte aspirer assaut asservir assiette associer assurer asticot astre astuce atelier atome atrium atroce attaque attentif attirer attraper aubaine auberge audace audible augurer aurore automne autruche avaler avancer avarice avenir averse aveugle aviateur avide avion aviser avoine avouer avril axial axiome badge bafouer bagage baguette baignade balancer balcon baleine balisage bambin bancaire bandage banlieue bannière banquier barbier baril baron barque barrage bassin bastion bataille bateau batterie baudrier bavarder belette bélier belote bénéfice berceau berger berline bermuda besace besogne bétail beurre biberon bicycle bidule bijou bilan bilingue billard binaire biologie biopsie biotype biscuit bison bistouri bitume bizarre blafard blague blanchir blessant blinder blond bloquer blouson bobard bobine boire boiser bolide bonbon bondir bonheur bonifier bonus bordure borne botte boucle boueux bougie boulon bouquin bourse boussole boutique boxeur branche brasier brave brebis brèche breuvage bricoler brigade brillant brioche brique brochure broder bronzer brousse broyeur brume brusque brutal bruyant buffle buisson bulletin bureau burin bustier butiner butoir buvable buvette cabanon cabine cachette cadeau cadre caféine caillou caisson calculer calepin calibre calmer calomnie calvaire camarade caméra camion campagne canal caneton canon cantine canular capable caporal caprice capsule capter capuche carabine carbone caresser caribou carnage carotte carreau carton cascade casier casque cassure causer caution cavalier caverne caviar cédille ceinture céleste cellule cendrier censurer central cercle cérébral cerise cerner cerveau cesser chagrin chaise chaleur chambre chance chapitre charbon chasseur chaton chausson chavirer chemise chenille chéquier chercher cheval chien chiffre chignon chimère chiot chlorure chocolat choisir chose chouette chrome chute cigare cigogne cimenter cinéma cintrer circuler cirer cirque citerne citoyen citron civil clairon clameur claquer classe clavier client cligner climat clivage cloche clonage cloporte cobalt cobra cocasse cocotier coder codifier coffre cogner cohésion coiffer coincer colère colibri colline colmater colonel combat comédie commande compact concert conduire confier congeler connoter consonne contact convexe copain copie corail corbeau cordage corniche corpus correct cortège cosmique costume coton coude coupure courage couteau couvrir coyote crabe crainte cravate crayon créature créditer crémeux creuser crevette cribler crier cristal critère croire croquer crotale crucial cruel crypter cubique cueillir cuillère cuisine cuivre culminer cultiver cumuler cupide curatif curseur cyanure cycle cylindre cynique daigner damier danger danseur dauphin débattre débiter déborder débrider débutant décaler décembre déchirer décider déclarer décorer décrire décupler dédale déductif déesse défensif défiler défrayer dégager dégivrer déglutir dégrafer déjeuner délice déloger demander demeurer démolir dénicher dénouer dentelle dénuder départ dépenser déphaser déplacer déposer déranger dérober désastre descente désert désigner désobéir dessiner destrier détacher détester détourer détresse devancer devenir deviner devoir diable dialogue diamant dicter différer digérer digital digne diluer dimanche diminuer dioxyde directif diriger discuter disposer dissiper distance divertir diviser docile docteur dogme doigt domaine domicile dompter donateur donjon donner dopamine dortoir dorure dosage doseur dossier dotation douanier double douceur douter doyen dragon draper dresser dribbler droiture duperie duplexe durable durcir dynastie éblouir écarter écharpe échelle éclairer éclipse éclore écluse école économie écorce écouter écraser écrémer écrivain écrou écume écureuil édifier éduquer effacer effectif effigie effort effrayer effusion égaliser égarer éjecter élaborer élargir électron élégant éléphant élève éligible élitisme éloge élucider éluder emballer embellir embryon émeraude émission emmener émotion émouvoir empereur employer emporter emprise émulsion encadrer enchère enclave encoche endiguer endosser endroit enduire énergie enfance enfermer enfouir engager engin englober énigme enjamber enjeu enlever ennemi ennuyeux enrichir enrobage enseigne entasser entendre entier entourer entraver énumérer envahir enviable envoyer enzyme éolien épaissir épargne épatant épaule épicerie épidémie épier épilogue épine épisode épitaphe époque épreuve éprouver épuisant équerre équipe ériger érosion erreur éruption escalier espadon espèce espiègle espoir esprit esquiver essayer essence essieu essorer estime estomac estrade étagère étaler étanche étatique éteindre étendoir éternel éthanol éthique ethnie étirer étoffer étoile étonnant étourdir étrange étroit étude euphorie évaluer évasion éventail évidence éviter évolutif évoquer exact exagérer exaucer exceller excitant exclusif excuse exécuter exemple exercer exhaler exhorter exigence exiler exister exotique expédier explorer exposer exprimer exquis extensif extraire exulter fable fabuleux facette facile facture faiblir falaise fameux famille farceur farfelu farine farouche fasciner fatal fatigue faucon fautif faveur favori fébrile féconder fédérer félin femme fémur fendoir féodal fermer féroce ferveur festival feuille feutre février fiasco ficeler fictif fidèle figure filature filetage filière filleul filmer filou filtrer financer finir fiole firme fissure fixer flairer flamme flasque flatteur fléau flèche fleur flexion flocon flore fluctuer fluide fluvial folie fonderie fongible fontaine forcer forgeron formuler fortune fossile foudre fougère fouiller foulure fourmi fragile fraise franchir frapper frayeur frégate freiner frelon frémir frénésie frère friable friction frisson frivole froid fromage frontal frotter fruit fugitif fuite fureur furieux furtif fusion futur gagner galaxie galerie gambader garantir gardien garnir garrigue gazelle gazon géant gélatine gélule gendarme général génie genou gentil géologie géomètre géranium germe gestuel geyser gibier gicler girafe givre glace glaive glisser globe gloire glorieux golfeur gomme gonfler gorge gorille goudron gouffre goulot goupille gourmand goutte graduel graffiti graine grand grappin gratuit gravir grenat griffure griller grimper grogner gronder grotte groupe gruger grutier gruyère guépard guerrier guide guimauve guitare gustatif gymnaste gyrostat habitude hachoir halte hameau hangar hanneton haricot harmonie harpon hasard hélium hématome herbe hérisson hermine héron hésiter heureux hiberner hibou hilarant histoire hiver homard hommage homogène honneur honorer honteux horde horizon horloge hormone horrible houleux housse hublot huileux humain humble humide humour hurler hydromel hygiène hymne hypnose idylle ignorer iguane illicite illusion image imbiber imiter immense immobile immuable impact impérial implorer imposer imprimer imputer incarner incendie incident incliner incolore indexer indice inductif inédit ineptie inexact infini infliger informer infusion ingérer inhaler inhiber injecter injure innocent inoculer inonder inscrire insecte insigne insolite inspirer instinct insulter intact intense intime intrigue intuitif inutile invasion inventer inviter invoquer ironique irradier irréel irriter isoler ivoire ivresse jaguar jaillir jambe janvier jardin jauger jaune javelot jetable jeton jeudi jeunesse joindre joncher jongler joueur jouissif journal jovial joyau joyeux jubiler jugement junior jupon juriste justice juteux juvénile kayak kimono kiosque label labial labourer lacérer lactose lagune laine laisser laitier lambeau lamelle lampe lanceur langage lanterne lapin largeur larme laurier lavabo lavoir lecture légal léger légume lessive lettre levier lexique lézard liasse libérer libre licence licorne liège lièvre ligature ligoter ligue limer limite limonade limpide linéaire lingot lionceau liquide lisière lister lithium litige littoral livreur logique lointain loisir lombric loterie louer lourd loutre louve loyal lubie lucide lucratif lueur lugubre luisant lumière lunaire lundi luron lutter luxueux machine magasin magenta magique maigre maillon maintien mairie maison majorer malaxer maléfice malheur malice mallette mammouth mandater maniable manquant manteau manuel marathon marbre marchand mardi maritime marqueur marron marteler mascotte massif matériel matière matraque maudire maussade mauve maximal méchant méconnu médaille médecin méditer méduse meilleur mélange mélodie membre mémoire menacer mener menhir mensonge mentor mercredi mérite merle messager mesure métal météore méthode métier meuble miauler microbe miette mignon migrer milieu million mimique mince minéral minimal minorer minute miracle miroiter missile mixte mobile moderne moelleux mondial moniteur monnaie monotone monstre montagne monument moqueur morceau morsure mortier moteur motif mouche moufle moulin mousson mouton mouvant multiple munition muraille murène murmure muscle muséum musicien mutation muter mutuel myriade myrtille mystère mythique nageur nappe narquois narrer natation nation nature naufrage nautique navire nébuleux nectar néfaste négation négliger négocier neige nerveux nettoyer neurone neutron neveu niche nickel nitrate niveau noble nocif nocturne noirceur noisette nomade nombreux nommer normatif notable notifier notoire nourrir nouveau novateur novembre novice nuage nuancer nuire nuisible numéro nuptial nuque nutritif obéir objectif obliger obscur observer obstacle obtenir obturer occasion occuper océan octobre octroyer octupler oculaire odeur odorant offenser officier offrir ogive oiseau oisillon olfactif olivier ombrage omettre onctueux onduler onéreux onirique opale opaque opérer opinion opportun opprimer opter optique orageux orange orbite ordonner oreille organe orgueil orifice ornement orque ortie osciller osmose ossature otarie ouragan ourson outil outrager ouvrage ovation oxyde oxygène ozone paisible palace palmarès palourde palper panache panda pangolin paniquer panneau panorama pantalon papaye papier papoter papyrus paradoxe parcelle paresse parfumer parler parole parrain parsemer partager parure parvenir passion pastèque paternel patience patron pavillon pavoiser payer paysage peigne peintre pelage pélican pelle pelouse peluche pendule pénétrer pénible pensif pénurie pépite péplum perdrix perforer période permuter perplexe persil perte peser pétale petit pétrir peuple pharaon phobie phoque photon phrase physique piano pictural pièce pierre pieuvre pilote pinceau pipette piquer pirogue piscine piston pivoter pixel pizza placard plafond plaisir planer plaque plastron plateau pleurer plexus pliage plomb plonger pluie plumage pochette poésie poète pointe poirier poisson poivre polaire policier pollen polygone pommade pompier ponctuel pondérer poney portique position posséder posture potager poteau potion pouce poulain poumon pourpre poussin pouvoir prairie pratique précieux prédire préfixe prélude prénom présence prétexte prévoir primitif prince prison priver problème procéder prodige profond progrès proie projeter prologue promener propre prospère protéger prouesse proverbe prudence pruneau psychose public puceron puiser pulpe pulsar punaise punitif pupitre purifier puzzle pyramide quasar querelle question quiétude quitter quotient racine raconter radieux ragondin raideur raisin ralentir rallonge ramasser rapide rasage ratisser ravager ravin rayonner réactif réagir réaliser réanimer recevoir réciter réclamer récolter recruter reculer recycler rédiger redouter refaire réflexe réformer refrain refuge régalien région réglage régulier réitérer rejeter rejouer relatif relever relief remarque remède remise remonter remplir remuer renard renfort renifler renoncer rentrer renvoi replier reporter reprise reptile requin réserve résineux résoudre respect rester résultat rétablir retenir réticule retomber retracer réunion réussir revanche revivre révolte révulsif richesse rideau rieur rigide rigoler rincer riposter risible risque rituel rival rivière rocheux romance rompre ronce rondin roseau rosier rotatif rotor rotule rouge rouille rouleau routine royaume ruban rubis ruche ruelle rugueux ruiner ruisseau ruser rustique rythme sabler saboter sabre sacoche safari sagesse saisir salade salive salon saluer samedi sanction sanglier sarcasme sardine saturer saugrenu saumon sauter sauvage savant savonner scalpel scandale scélérat scénario sceptre schéma science scinder score scrutin sculpter séance sécable sécher secouer sécréter sédatif séduire seigneur séjour sélectif semaine sembler semence séminal sénateur sensible sentence séparer séquence serein sergent sérieux serrure sérum service sésame sévir sevrage sextuple sidéral siècle siéger siffler sigle signal silence silicium simple sincère sinistre siphon sirop sismique situer skier social socle sodium soigneux soldat soleil solitude soluble sombre sommeil somnoler sonde songeur sonnette sonore sorcier sortir sosie sottise soucieux soudure souffle soulever soupape source soutirer souvenir spacieux spatial spécial sphère spiral stable station sternum stimulus stipuler strict studieux stupeur styliste sublime substrat subtil subvenir succès sucre suffixe suggérer suiveur sulfate superbe supplier surface suricate surmener surprise sursaut survie suspect syllabe symbole symétrie synapse syntaxe système tabac tablier tactile tailler talent talisman talonner tambour tamiser tangible tapis taquiner tarder tarif tartine tasse tatami tatouage taupe taureau taxer témoin temporel tenaille tendre teneur tenir tension terminer terne terrible tétine texte thème théorie thérapie thorax tibia tiède timide tirelire tiroir tissu titane titre tituber toboggan tolérant tomate tonique tonneau toponyme torche tordre tornade torpille torrent torse tortue totem toucher tournage tousser toxine traction trafic tragique trahir train trancher travail trèfle tremper trésor treuil triage tribunal tricoter trilogie triomphe tripler triturer trivial trombone tronc tropical troupeau tuile tulipe tumulte tunnel turbine tuteur tutoyer tuyau tympan typhon typique tyran ubuesque ultime ultrason unanime unifier union unique unitaire univers uranium urbain urticant usage usine usuel usure utile utopie vacarme vaccin vagabond vague vaillant vaincre vaisseau valable valise vallon valve vampire vanille vapeur varier vaseux vassal vaste vecteur vedette végétal véhicule veinard véloce vendredi vénérer venger venimeux ventouse verdure vérin vernir verrou verser vertu veston vétéran vétuste vexant vexer viaduc viande victoire vidange vidéo vignette vigueur vilain village vinaigre violon vipère virement virtuose virus visage viseur vision visqueux visuel vital vitesse viticole vitrine vivace vivipare vocation voguer voile voisin voiture volaille volcan voltiger volume vorace vortex voter vouloir voyage voyelle wagon xénon yacht zèbre zénith zeste zoologie".components(separatedBy: " ") + } + var italianWords: [String] { + return "abaco abbaglio abbinato abete abisso abolire abrasivo abrogato accadere accenno accusato acetone achille acido acqua acre acrilico acrobata acuto adagio addebito addome adeguato aderire adipe adottare adulare affabile affetto affisso affranto aforisma afoso africano agave agente agevole aggancio agire agitare agonismo agricolo agrumeto aguzzo alabarda alato albatro alberato albo albume alce alcolico alettone alfa algebra aliante alibi alimento allagato allegro allievo allodola allusivo almeno alogeno alpaca alpestre altalena alterno alticcio altrove alunno alveolo alzare amalgama amanita amarena ambito ambrato ameba america ametista amico ammasso ammenda ammirare ammonito amore ampio ampliare amuleto anacardo anagrafe analista anarchia anatra anca ancella ancora andare andrea anello angelo angolare angusto anima annegare annidato anno annuncio anonimo anticipo anzi apatico apertura apode apparire appetito appoggio approdo appunto aprile arabica arachide aragosta araldica arancio aratura arazzo arbitro archivio ardito arenile argento argine arguto aria armonia arnese arredato arringa arrosto arsenico arso artefice arzillo asciutto ascolto asepsi asettico asfalto asino asola aspirato aspro assaggio asse assoluto assurdo asta astenuto astice astratto atavico ateismo atomico atono attesa attivare attorno attrito attuale ausilio austria autista autonomo autunno avanzato avere avvenire avviso avvolgere azione azoto azzimo azzurro babele baccano bacino baco badessa badilata bagnato baita balcone baldo balena ballata balzano bambino bandire baraonda barbaro barca baritono barlume barocco basilico basso batosta battuto baule bava bavosa becco beffa belgio belva benda benevole benigno benzina bere berlina beta bibita bici bidone bifido biga bilancia bimbo binocolo biologo bipede bipolare birbante birra biscotto bisesto bisnonno bisonte bisturi bizzarro blando blatta bollito bonifico bordo bosco botanico bottino bozzolo braccio bradipo brama branca bravura bretella brevetto brezza briglia brillante brindare broccolo brodo bronzina brullo bruno bubbone buca budino buffone buio bulbo buono burlone burrasca bussola busta cadetto caduco calamaro calcolo calesse calibro calmo caloria cambusa camerata camicia cammino camola campale canapa candela cane canino canotto cantina capace capello capitolo capogiro cappero capra capsula carapace carcassa cardo carisma carovana carretto cartolina casaccio cascata caserma caso cassone castello casuale catasta catena catrame cauto cavillo cedibile cedrata cefalo celebre cellulare cena cenone centesimo ceramica cercare certo cerume cervello cesoia cespo ceto chela chiaro chicca chiedere chimera china chirurgo chitarra ciao ciclismo cifrare cigno cilindro ciottolo circa cirrosi citrico cittadino ciuffo civetta civile classico clinica cloro cocco codardo codice coerente cognome collare colmato colore colposo coltivato colza coma cometa commando comodo computer comune conciso condurre conferma congelare coniuge connesso conoscere consumo continuo convegno coperto copione coppia copricapo corazza cordata coricato cornice corolla corpo corredo corsia cortese cosmico costante cottura covato cratere cravatta creato credere cremoso crescita creta criceto crinale crisi critico croce cronaca crostata cruciale crusca cucire cuculo cugino cullato cupola curatore cursore curvo cuscino custode dado daino dalmata damerino daniela dannoso danzare datato davanti davvero debutto decennio deciso declino decollo decreto dedicato definito deforme degno delegare delfino delirio delta demenza denotato dentro deposito derapata derivare deroga descritto deserto desiderio desumere detersivo devoto diametro dicembre diedro difeso diffuso digerire digitale diluvio dinamico dinnanzi dipinto diploma dipolo diradare dire dirotto dirupo disagio discreto disfare disgelo disposto distanza disumano dito divano divelto dividere divorato doblone docente doganale dogma dolce domato domenica dominare dondolo dono dormire dote dottore dovuto dozzina drago druido dubbio dubitare ducale duna duomo duplice duraturo ebano eccesso ecco eclissi economia edera edicola edile editoria educare egemonia egli egoismo egregio elaborato elargire elegante elencato eletto elevare elfico elica elmo elsa eluso emanato emblema emesso emiro emotivo emozione empirico emulo endemico enduro energia enfasi enoteca entrare enzima epatite epilogo episodio epocale eppure equatore erario erba erboso erede eremita erigere ermetico eroe erosivo errante esagono esame esanime esaudire esca esempio esercito esibito esigente esistere esito esofago esortato esoso espanso espresso essenza esso esteso estimare estonia estroso esultare etilico etnico etrusco etto euclideo europa evaso evidenza evitato evoluto evviva fabbrica faccenda fachiro falco famiglia fanale fanfara fango fantasma fare farfalla farinoso farmaco fascia fastoso fasullo faticare fato favoloso febbre fecola fede fegato felpa feltro femmina fendere fenomeno fermento ferro fertile fessura festivo fetta feudo fiaba fiducia fifa figurato filo finanza finestra finire fiore fiscale fisico fiume flacone flamenco flebo flemma florido fluente fluoro fobico focaccia focoso foderato foglio folata folclore folgore fondente fonetico fonia fontana forbito forchetta foresta formica fornaio foro fortezza forzare fosfato fosso fracasso frana frassino fratello freccetta frenata fresco frigo frollino fronde frugale frutta fucilata fucsia fuggente fulmine fulvo fumante fumetto fumoso fune funzione fuoco furbo furgone furore fuso futile gabbiano gaffe galateo gallina galoppo gambero gamma garanzia garbo garofano garzone gasdotto gasolio gastrico gatto gaudio gazebo gazzella geco gelatina gelso gemello gemmato gene genitore gennaio genotipo gergo ghepardo ghiaccio ghisa giallo gilda ginepro giocare gioiello giorno giove girato girone gittata giudizio giurato giusto globulo glutine gnomo gobba golf gomito gommone gonfio gonna governo gracile grado grafico grammo grande grattare gravoso grazia greca gregge grifone grigio grinza grotta gruppo guadagno guaio guanto guardare gufo guidare ibernato icona identico idillio idolo idra idrico idrogeno igiene ignaro ignorato ilare illeso illogico illudere imballo imbevuto imbocco imbuto immane immerso immolato impacco impeto impiego importo impronta inalare inarcare inattivo incanto incendio inchino incisivo incluso incontro incrocio incubo indagine india indole inedito infatti infilare inflitto ingaggio ingegno inglese ingordo ingrosso innesco inodore inoltrare inondato insano insetto insieme insonnia insulina intasato intero intonaco intuito inumidire invalido invece invito iperbole ipnotico ipotesi ippica iride irlanda ironico irrigato irrorare isolato isotopo isterico istituto istrice italia iterare labbro labirinto lacca lacerato lacrima lacuna laddove lago lampo lancetta lanterna lardoso larga laringe lastra latenza latino lattuga lavagna lavoro legale leggero lembo lentezza lenza leone lepre lesivo lessato lesto letterale leva levigato libero lido lievito lilla limatura limitare limpido lineare lingua liquido lira lirica lisca lite litigio livrea locanda lode logica lombare londra longevo loquace lorenzo loto lotteria luce lucidato lumaca luminoso lungo lupo luppolo lusinga lusso lutto macabro macchina macero macinato madama magico maglia magnete magro maiolica malafede malgrado malinteso malsano malto malumore mana mancia mandorla mangiare manifesto mannaro manovra mansarda mantide manubrio mappa maratona marcire maretta marmo marsupio maschera massaia mastino materasso matricola mattone maturo mazurca meandro meccanico mecenate medesimo meditare mega melassa melis melodia meninge meno mensola mercurio merenda merlo meschino mese messere mestolo metallo metodo mettere miagolare mica micelio michele microbo midollo miele migliore milano milite mimosa minerale mini minore mirino mirtillo miscela missiva misto misurare mitezza mitigare mitra mittente mnemonico modello modifica modulo mogano mogio mole molosso monastero monco mondina monetario monile monotono monsone montato monviso mora mordere morsicato mostro motivato motosega motto movenza movimento mozzo mucca mucosa muffa mughetto mugnaio mulatto mulinello multiplo mummia munto muovere murale musa muscolo musica mutevole muto nababbo nafta nanometro narciso narice narrato nascere nastrare naturale nautica naviglio nebulosa necrosi negativo negozio nemmeno neofita neretto nervo nessuno nettuno neutrale neve nevrotico nicchia ninfa nitido nobile nocivo nodo nome nomina nordico normale norvegese nostrano notare notizia notturno novella nucleo nulla numero nuovo nutrire nuvola nuziale oasi obbedire obbligo obelisco oblio obolo obsoleto occasione occhio occidente occorrere occultare ocra oculato odierno odorare offerta offrire offuscato oggetto oggi ognuno olandese olfatto oliato oliva ologramma oltre omaggio ombelico ombra omega omissione ondoso onere onice onnivoro onorevole onta operato opinione opposto oracolo orafo ordine orecchino orefice orfano organico origine orizzonte orma ormeggio ornativo orologio orrendo orribile ortensia ortica orzata orzo osare oscurare osmosi ospedale ospite ossa ossidare ostacolo oste otite otre ottagono ottimo ottobre ovale ovest ovino oviparo ovocito ovunque ovviare ozio pacchetto pace pacifico padella padrone paese paga pagina palazzina palesare pallido palo palude pandoro pannello paolo paonazzo paprica parabola parcella parere pargolo pari parlato parola partire parvenza parziale passivo pasticca patacca patologia pattume pavone peccato pedalare pedonale peggio peloso penare pendice penisola pennuto penombra pensare pentola pepe pepita perbene percorso perdonato perforare pergamena periodo permesso perno perplesso persuaso pertugio pervaso pesatore pesista peso pestifero petalo pettine petulante pezzo piacere pianta piattino piccino picozza piega pietra piffero pigiama pigolio pigro pila pilifero pillola pilota pimpante pineta pinna pinolo pioggia piombo piramide piretico pirite pirolisi pitone pizzico placebo planare plasma platano plenario pochezza poderoso podismo poesia poggiare polenta poligono pollice polmonite polpetta polso poltrona polvere pomice pomodoro ponte popoloso porfido poroso porpora porre portata posa positivo possesso postulato potassio potere pranzo prassi pratica precluso predica prefisso pregiato prelievo premere prenotare preparato presenza pretesto prevalso prima principe privato problema procura produrre profumo progetto prolunga promessa pronome proposta proroga proteso prova prudente prugna prurito psiche pubblico pudica pugilato pugno pulce pulito pulsante puntare pupazzo pupilla puro quadro qualcosa quasi querela quota raccolto raddoppio radicale radunato raffica ragazzo ragione ragno ramarro ramingo ramo randagio rantolare rapato rapina rappreso rasatura raschiato rasente rassegna rastrello rata ravveduto reale recepire recinto recluta recondito recupero reddito redimere regalato registro regola regresso relazione remare remoto renna replica reprimere reputare resa residente responso restauro rete retina retorica rettifica revocato riassunto ribadire ribelle ribrezzo ricarica ricco ricevere riciclato ricordo ricreduto ridicolo ridurre rifasare riflesso riforma rifugio rigare rigettato righello rilassato rilevato rimanere rimbalzo rimedio rimorchio rinascita rincaro rinforzo rinnovo rinomato rinsavito rintocco rinuncia rinvenire riparato ripetuto ripieno riportare ripresa ripulire risata rischio riserva risibile riso rispetto ristoro risultato risvolto ritardo ritegno ritmico ritrovo riunione riva riverso rivincita rivolto rizoma roba robotico robusto roccia roco rodaggio rodere roditore rogito rollio romantico rompere ronzio rosolare rospo rotante rotondo rotula rovescio rubizzo rubrica ruga rullino rumine rumoroso ruolo rupe russare rustico sabato sabbiare sabotato sagoma salasso saldatura salgemma salivare salmone salone saltare saluto salvo sapere sapido saporito saraceno sarcasmo sarto sassoso satellite satira satollo saturno savana savio saziato sbadiglio sbalzo sbancato sbarra sbattere sbavare sbendare sbirciare sbloccato sbocciato sbrinare sbruffone sbuffare scabroso scadenza scala scambiare scandalo scapola scarso scatenare scavato scelto scenico scettro scheda schiena sciarpa scienza scindere scippo sciroppo scivolo sclerare scodella scolpito scomparto sconforto scoprire scorta scossone scozzese scriba scrollare scrutinio scuderia scultore scuola scuro scusare sdebitare sdoganare seccatura secondo sedano seggiola segnalato segregato seguito selciato selettivo sella selvaggio semaforo sembrare seme seminato sempre senso sentire sepolto sequenza serata serbato sereno serio serpente serraglio servire sestina setola settimana sfacelo sfaldare sfamato sfarzoso sfaticato sfera sfida sfilato sfinge sfocato sfoderare sfogo sfoltire sforzato sfratto sfruttato sfuggito sfumare sfuso sgabello sgarbato sgonfiare sgorbio sgrassato sguardo sibilo siccome sierra sigla signore silenzio sillaba simbolo simpatico simulato sinfonia singolo sinistro sino sintesi sinusoide sipario sisma sistole situato slitta slogatura sloveno smarrito smemorato smentito smeraldo smilzo smontare smottato smussato snellire snervato snodo sobbalzo sobrio soccorso sociale sodale soffitto sogno soldato solenne solido sollazzo solo solubile solvente somatico somma sonda sonetto sonnifero sopire soppeso sopra sorgere sorpasso sorriso sorso sorteggio sorvolato sospiro sosta sottile spada spalla spargere spatola spavento spazzola specie spedire spegnere spelatura speranza spessore spettrale spezzato spia spigoloso spillato spinoso spirale splendido sportivo sposo spranga sprecare spronato spruzzo spuntino squillo sradicare srotolato stabile stacco staffa stagnare stampato stantio starnuto stasera statuto stelo steppa sterzo stiletto stima stirpe stivale stizzoso stonato storico strappo stregato stridulo strozzare strutto stuccare stufo stupendo subentro succoso sudore suggerito sugo sultano suonare superbo supporto surgelato surrogato sussurro sutura svagare svedese sveglio svelare svenuto svezia sviluppo svista svizzera svolta svuotare tabacco tabulato tacciare taciturno tale talismano tampone tannino tara tardivo targato tariffa tarpare tartaruga tasto tattico taverna tavolata tazza teca tecnico telefono temerario tempo temuto tendone tenero tensione tentacolo teorema terme terrazzo terzetto tesi tesserato testato tetro tettoia tifare tigella timbro tinto tipico tipografo tiraggio tiro titanio titolo titubante tizio tizzone toccare tollerare tolto tombola tomo tonfo tonsilla topazio topologia toppa torba tornare torrone tortora toscano tossire tostatura totano trabocco trachea trafila tragedia tralcio tramonto transito trapano trarre trasloco trattato trave treccia tremolio trespolo tributo tricheco trifoglio trillo trincea trio tristezza triturato trivella tromba trono troppo trottola trovare truccato tubatura tuffato tulipano tumulto tunisia turbare turchino tuta tutela ubicato uccello uccisore udire uditivo uffa ufficio uguale ulisse ultimato umano umile umorismo uncinetto ungere ungherese unicorno unificato unisono unitario unte uovo upupa uragano urgenza urlo usanza usato uscito usignolo usuraio utensile utilizzo utopia vacante vaccinato vagabondo vagliato valanga valgo valico valletta valoroso valutare valvola vampata vangare vanitoso vano vantaggio vanvera vapore varano varcato variante vasca vedetta vedova veduto vegetale veicolo velcro velina velluto veloce venato vendemmia vento verace verbale vergogna verifica vero verruca verticale vescica vessillo vestale veterano vetrina vetusto viandante vibrante vicenda vichingo vicinanza vidimare vigilia vigneto vigore vile villano vimini vincitore viola vipera virgola virologo virulento viscoso visione vispo vissuto visura vita vitello vittima vivanda vivido viziare voce voga volatile volere volpe voragine vulcano zampogna zanna zappato zattera zavorra zefiro zelante zelo zenzero zerbino zibetto zinco zircone zitto zolla zotico zucchero zufolo zulu zuppa".components(separatedBy: " ") + } + var spanishWords: [String] { + return "ábaco abdomen abeja abierto abogado abono aborto abrazo abrir abuelo abuso acabar academia acceso acción aceite acelga acento aceptar ácido aclarar acné acoger acoso activo acto actriz actuar acudir acuerdo acusar adicto admitir adoptar adorno aduana adulto aéreo afectar afición afinar afirmar ágil agitar agonía agosto agotar agregar agrio agua agudo águila aguja ahogo ahorro aire aislar ajedrez ajeno ajuste alacrán alambre alarma alba álbum alcalde aldea alegre alejar alerta aleta alfiler alga algodón aliado aliento alivio alma almeja almíbar altar alteza altivo alto altura alumno alzar amable amante amapola amargo amasar ámbar ámbito ameno amigo amistad amor amparo amplio ancho anciano ancla andar andén anemia ángulo anillo ánimo anís anotar antena antiguo antojo anual anular anuncio añadir añejo año apagar aparato apetito apio aplicar apodo aporte apoyo aprender aprobar apuesta apuro arado araña arar árbitro árbol arbusto archivo arco arder ardilla arduo área árido aries armonía arnés aroma arpa arpón arreglo arroz arruga arte artista asa asado asalto ascenso asegurar aseo asesor asiento asilo asistir asno asombro áspero astilla astro astuto asumir asunto atajo ataque atar atento ateo ático atleta átomo atraer atroz atún audaz audio auge aula aumento ausente autor aval avance avaro ave avellana avena avestruz avión aviso ayer ayuda ayuno azafrán azar azote azúcar azufre azul baba babor bache bahía baile bajar balanza balcón balde bambú banco banda baño barba barco barniz barro báscula bastón basura batalla batería batir batuta baúl bazar bebé bebida bello besar beso bestia bicho bien bingo blanco bloque blusa boa bobina bobo boca bocina boda bodega boina bola bolero bolsa bomba bondad bonito bono bonsái borde borrar bosque bote botín bóveda bozal bravo brazo brecha breve brillo brinco brisa broca broma bronce brote bruja brusco bruto buceo bucle bueno buey bufanda bufón búho buitre bulto burbuja burla burro buscar butaca buzón caballo cabeza cabina cabra cacao cadáver cadena caer café caída caimán caja cajón cal calamar calcio caldo calidad calle calma calor calvo cama cambio camello camino campo cáncer candil canela canguro canica canto caña cañón caoba caos capaz capitán capote captar capucha cara carbón cárcel careta carga cariño carne carpeta carro carta casa casco casero caspa castor catorce catre caudal causa cazo cebolla ceder cedro celda célebre celoso célula cemento ceniza centro cerca cerdo cereza cero cerrar certeza césped cetro chacal chaleco champú chancla chapa charla chico chiste chivo choque choza chuleta chupar ciclón ciego cielo cien cierto cifra cigarro cima cinco cine cinta ciprés circo ciruela cisne cita ciudad clamor clan claro clase clave cliente clima clínica cobre cocción cochino cocina coco código codo cofre coger cohete cojín cojo cola colcha colegio colgar colina collar colmo columna combate comer comida cómodo compra conde conejo conga conocer consejo contar copa copia corazón corbata corcho cordón corona correr coser cosmos costa cráneo cráter crear crecer creído crema cría crimen cripta crisis cromo crónica croqueta crudo cruz cuadro cuarto cuatro cubo cubrir cuchara cuello cuento cuerda cuesta cueva cuidar culebra culpa culto cumbre cumplir cuna cuneta cuota cupón cúpula curar curioso curso curva cutis dama danza dar dardo dátil deber débil década decir dedo defensa definir dejar delfín delgado delito demora denso dental deporte derecho derrota desayuno deseo desfile desnudo destino desvío detalle detener deuda día diablo diadema diamante diana diario dibujo dictar diente dieta diez difícil digno dilema diluir dinero directo dirigir disco diseño disfraz diva divino doble doce dolor domingo don donar dorado dormir dorso dos dosis dragón droga ducha duda duelo dueño dulce dúo duque durar dureza duro ébano ebrio echar eco ecuador edad edición edificio editor educar efecto eficaz eje ejemplo elefante elegir elemento elevar elipse élite elixir elogio eludir embudo emitir emoción empate empeño empleo empresa enano encargo enchufe encía enemigo enero enfado enfermo engaño enigma enlace enorme enredo ensayo enseñar entero entrar envase envío época equipo erizo escala escena escolar escribir escudo esencia esfera esfuerzo espada espejo espía esposa espuma esquí estar este estilo estufa etapa eterno ética etnia evadir evaluar evento evitar exacto examen exceso excusa exento exigir exilio existir éxito experto explicar exponer extremo fábrica fábula fachada fácil factor faena faja falda fallo falso faltar fama familia famoso faraón farmacia farol farsa fase fatiga fauna favor fax febrero fecha feliz feo feria feroz fértil fervor festín fiable fianza fiar fibra ficción ficha fideo fiebre fiel fiera fiesta figura fijar fijo fila filete filial filtro fin finca fingir finito firma flaco flauta flecha flor flota fluir flujo flúor fobia foca fogata fogón folio folleto fondo forma forro fortuna forzar fosa foto fracaso frágil franja frase fraude freír freno fresa frío frito fruta fuego fuente fuerza fuga fumar función funda furgón furia fusil fútbol futuro gacela gafas gaita gajo gala galería gallo gamba ganar gancho ganga ganso garaje garza gasolina gastar gato gavilán gemelo gemir gen género genio gente geranio gerente germen gesto gigante gimnasio girar giro glaciar globo gloria gol golfo goloso golpe goma gordo gorila gorra gota goteo gozar grada gráfico grano grasa gratis grave grieta grillo gripe gris grito grosor grúa grueso grumo grupo guante guapo guardia guerra guía guiño guion guiso guitarra gusano gustar haber hábil hablar hacer hacha hada hallar hamaca harina haz hazaña hebilla hebra hecho helado helio hembra herir hermano héroe hervir hielo hierro hígado higiene hijo himno historia hocico hogar hoguera hoja hombre hongo honor honra hora hormiga horno hostil hoyo hueco huelga huerta hueso huevo huida huir humano húmedo humilde humo hundir huracán hurto icono ideal idioma ídolo iglesia iglú igual ilegal ilusión imagen imán imitar impar imperio imponer impulso incapaz índice inerte infiel informe ingenio inicio inmenso inmune innato insecto instante interés íntimo intuir inútil invierno ira iris ironía isla islote jabalí jabón jamón jarabe jardín jarra jaula jazmín jefe jeringa jinete jornada joroba joven joya juerga jueves juez jugador jugo juguete juicio junco jungla junio juntar júpiter jurar justo juvenil juzgar kilo koala labio lacio lacra lado ladrón lagarto lágrima laguna laico lamer lámina lámpara lana lancha langosta lanza lápiz largo larva lástima lata látex latir laurel lavar lazo leal lección leche lector leer legión legumbre lejano lengua lento leña león leopardo lesión letal letra leve leyenda libertad libro licor líder lidiar lienzo liga ligero lima límite limón limpio lince lindo línea lingote lino linterna líquido liso lista litera litio litro llaga llama llanto llave llegar llenar llevar llorar llover lluvia lobo loción loco locura lógica logro lombriz lomo lonja lote lucha lucir lugar lujo luna lunes lupa lustro luto luz maceta macho madera madre maduro maestro mafia magia mago maíz maldad maleta malla malo mamá mambo mamut manco mando manejar manga maniquí manjar mano manso manta mañana mapa máquina mar marco marea marfil margen marido mármol marrón martes marzo masa máscara masivo matar materia matiz matriz máximo mayor mazorca mecha medalla medio médula mejilla mejor melena melón memoria menor mensaje mente menú mercado merengue mérito mes mesón meta meter método metro mezcla miedo miel miembro miga mil milagro militar millón mimo mina minero mínimo minuto miope mirar misa miseria misil mismo mitad mito mochila moción moda modelo moho mojar molde moler molino momento momia monarca moneda monja monto moño morada morder moreno morir morro morsa mortal mosca mostrar motivo mover móvil mozo mucho mudar mueble muela muerte muestra mugre mujer mula muleta multa mundo muñeca mural muro músculo museo musgo música muslo nácar nación nadar naipe naranja nariz narrar nasal natal nativo natural náusea naval nave navidad necio néctar negar negocio negro neón nervio neto neutro nevar nevera nicho nido niebla nieto niñez niño nítido nivel nobleza noche nómina noria norma norte nota noticia novato novela novio nube nuca núcleo nudillo nudo nuera nueve nuez nulo número nutria oasis obeso obispo objeto obra obrero observar obtener obvio oca ocaso océano ochenta ocho ocio ocre octavo octubre oculto ocupar ocurrir odiar odio odisea oeste ofensa oferta oficio ofrecer ogro oído oír ojo ola oleada olfato olivo olla olmo olor olvido ombligo onda onza opaco opción ópera opinar oponer optar óptica opuesto oración orador oral órbita orca orden oreja órgano orgía orgullo oriente origen orilla oro orquesta oruga osadía oscuro osezno oso ostra otoño otro oveja óvulo óxido oxígeno oyente ozono pacto padre paella página pago país pájaro palabra palco paleta pálido palma paloma palpar pan panal pánico pantera pañuelo papá papel papilla paquete parar parcela pared parir paro párpado parque párrafo parte pasar paseo pasión paso pasta pata patio patria pausa pauta pavo payaso peatón pecado pecera pecho pedal pedir pegar peine pelar peldaño pelea peligro pellejo pelo peluca pena pensar peñón peón peor pepino pequeño pera percha perder pereza perfil perico perla permiso perro persona pesa pesca pésimo pestaña pétalo petróleo pez pezuña picar pichón pie piedra pierna pieza pijama pilar piloto pimienta pino pintor pinza piña piojo pipa pirata pisar piscina piso pista pitón pizca placa plan plata playa plaza pleito pleno plomo pluma plural pobre poco poder podio poema poesía poeta polen policía pollo polvo pomada pomelo pomo pompa poner porción portal posada poseer posible poste potencia potro pozo prado precoz pregunta premio prensa preso previo primo príncipe prisión privar proa probar proceso producto proeza profesor programa prole promesa pronto propio próximo prueba público puchero pudor pueblo puerta puesto pulga pulir pulmón pulpo pulso puma punto puñal puño pupa pupila puré quedar queja quemar querer queso quieto química quince quitar rábano rabia rabo ración radical raíz rama rampa rancho rango rapaz rápido rapto rasgo raspa rato rayo raza razón reacción realidad rebaño rebote recaer receta rechazo recoger recreo recto recurso red redondo reducir reflejo reforma refrán refugio regalo regir regla regreso rehén reino reír reja relato relevo relieve relleno reloj remar remedio remo rencor rendir renta reparto repetir reposo reptil res rescate resina respeto resto resumen retiro retorno retrato reunir revés revista rey rezar rico riego rienda riesgo rifa rígido rigor rincón riñón río riqueza risa ritmo rito rizo roble roce rociar rodar rodeo rodilla roer rojizo rojo romero romper ron ronco ronda ropa ropero rosa rosca rostro rotar rubí rubor rudo rueda rugir ruido ruina ruleta rulo rumbo rumor ruptura ruta rutina sábado saber sabio sable sacar sagaz sagrado sala saldo salero salir salmón salón salsa salto salud salvar samba sanción sandía sanear sangre sanidad sano santo sapo saque sardina sartén sastre satán sauna saxofón sección seco secreto secta sed seguir seis sello selva semana semilla senda sensor señal señor separar sepia sequía ser serie sermón servir sesenta sesión seta setenta severo sexo sexto sidra siesta siete siglo signo sílaba silbar silencio silla símbolo simio sirena sistema sitio situar sobre socio sodio sol solapa soldado soledad sólido soltar solución sombra sondeo sonido sonoro sonrisa sopa soplar soporte sordo sorpresa sorteo sostén sótano suave subir suceso sudor suegra suelo sueño suerte sufrir sujeto sultán sumar superar suplir suponer supremo sur surco sureño surgir susto sutil tabaco tabique tabla tabú taco tacto tajo talar talco talento talla talón tamaño tambor tango tanque tapa tapete tapia tapón taquilla tarde tarea tarifa tarjeta tarot tarro tarta tatuaje tauro taza tazón teatro techo tecla técnica tejado tejer tejido tela teléfono tema temor templo tenaz tender tener tenis tenso teoría terapia terco término ternura terror tesis tesoro testigo tetera texto tez tibio tiburón tiempo tienda tierra tieso tigre tijera tilde timbre tímido timo tinta tío típico tipo tira tirón titán títere título tiza toalla tobillo tocar tocino todo toga toldo tomar tono tonto topar tope toque tórax torero tormenta torneo toro torpedo torre torso tortuga tos tosco toser tóxico trabajo tractor traer tráfico trago traje tramo trance trato trauma trazar trébol tregua treinta tren trepar tres tribu trigo tripa triste triunfo trofeo trompa tronco tropa trote trozo truco trueno trufa tubería tubo tuerto tumba tumor túnel túnica turbina turismo turno tutor ubicar úlcera umbral unidad unir universo uno untar uña urbano urbe urgente urna usar usuario útil utopía uva vaca vacío vacuna vagar vago vaina vajilla vale válido valle valor válvula vampiro vara variar varón vaso vecino vector vehículo veinte vejez vela velero veloz vena vencer venda veneno vengar venir venta venus ver verano verbo verde vereda verja verso verter vía viaje vibrar vicio víctima vida vídeo vidrio viejo viernes vigor vil villa vinagre vino viñedo violín viral virgo virtud visor víspera vista vitamina viudo vivaz vivero vivir vivo volcán volumen volver voraz votar voto voz vuelo vulgar yacer yate yegua yema yerno yeso yodo yoga yogur zafiro zanja zapato zarza zona zorro zumo zurdo".components(separatedBy: " ") + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP39.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP39.swift new file mode 100755 index 000000000..5ce5238a3 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP39.swift @@ -0,0 +1,164 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import CryptoSwift + +public enum BIP39Language { + case english + case chinese_simplified + case chinese_traditional + case japanese + case korean + case french + case italian + case spanish + public var words: [String] { + switch self { + case .english: + return englishWords + case .chinese_simplified: + return simplifiedchineseWords + case .chinese_traditional: + return traditionalchineseWords + case .japanese: + return japaneseWords + case .korean: + return koreanWords + case.french: + return frenchWords + case .italian: + return italianWords + case .spanish: + return spanishWords + } + } + public var separator: String { + switch self { + case .japanese: + return "\u{3000}" + default: + return " " + } + } + + init?(language: String) { + switch language { + case "english": + self = .english + case "chinese_simplified": + self = .chinese_simplified + case "chinese_traditional": + self = .chinese_traditional + case "japanese": + self = .japanese + case "korean": + self = .korean + case "french": + self = .french + case "italian": + self = .italian + case "spanish": + self = .spanish + default: + return nil + } + } +} + +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} + let checksum = entropy.sha256() + let checksumBits = entropy.count*8/32 + var fullEntropy = Data() + fullEntropy.append(entropy) + 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} + let index = Int(bits) + guard language.words.count > index else {return nil} + let word = language.words[index] + wordList.append(word) + } + let separator = language.separator + return wordList.joined(separator: separator) + } + + /** + Initializes a new mnemonics set with the provided bitsOfEntropy. + + - Parameters: + - bitsOfEntropy: 128 - 12 words, 192 - 18 words , 256 - 24 words in output. + - language: words language, default english + + - Returns: random 12-24 words, that represent new Mnemonic phrase. + */ + + /// Initializes a new mnemonics set with the provided bitsOfEntropy. + /// - Parameters: + /// - bitsOfEntropy: 128 - 12 words, 192 - 18 words , 256 - 24 words in output. + /// - language: words language, default english + 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 let entropy = Data.randomBytes(length: bitsOfEntropy/8) else {throw AbstractKeystoreError.noEntropyError} + return BIP39.generateMnemonicsFromEntropy(entropy: entropy, language: language) + + } + + static public func mnemonicsToEntropy(_ mnemonics: String, language: BIP39Language = BIP39Language.english) -> Data? { + let wordList = mnemonics.components(separatedBy: " ") + guard wordList.count >= 12 && wordList.count.isMultiple(of: 4) else {return nil} + var bitString = "" + for word in wordList { +// let idx = language.words.index(of: word) + let idx = language.words.firstIndex(of: word) + if (idx == nil) { + return nil + } + let idxAsInt = language.words.startIndex.distance(to: idx!) + let stringForm = String(UInt16(idxAsInt), radix: 2).leftPadding(toLength: 11, withPad: "0") + bitString.append(stringForm) + } + let stringCount = bitString.count + if !stringCount.isMultiple(of: 33) { + return nil + } + let entropyBits = bitString[0 ..< (bitString.count - bitString.count/33)] + let checksumBits = bitString[(bitString.count - bitString.count/33) ..< bitString.count] + guard let entropy = entropyBits.interpretAsBinaryData() else { + return nil + } + let checksum = String(entropy.sha256().bitsInRange(0, checksumBits.count)!, radix: 2).leftPadding(toLength: checksumBits.count, withPad: "0") + if checksum != checksumBits { + return nil + } + return entropy + } + + static public func seedFromMmemonics(_ mnemonics: String, password: String = "", language: BIP39Language = BIP39Language.english) -> Data? { + let valid = BIP39.mnemonicsToEntropy(mnemonics, language: language) != nil + if (!valid) { + 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.sha512).calculate() else {return nil} +// let seed = Data(bytes:seedArray) + let seed = Data(seedArray) + return seed + } + + static public func seedFromEntropy(_ entropy: Data, password: String = "", language: BIP39Language = BIP39Language.english) -> Data? { + guard let mnemonics = BIP39.generateMnemonicsFromEntropy(entropy: entropy, language: language) else { + return nil + } + return BIP39.seedFromMmemonics(mnemonics, password: password, language: language) + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/EthereumKeystoreV3.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/EthereumKeystoreV3.swift new file mode 100755 index 000000000..db03f98b3 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/EthereumKeystoreV3.swift @@ -0,0 +1,193 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import CryptoSwift +import Foundation +//import secp256k1_swift +//import EthereumAddress + +public class EthereumKeystoreV3: AbstractKeystore { + // Class + + public func getAddress() -> EthereumAddress? { + return self.address + } + + // Protocol + + public var addresses: [EthereumAddress]? { + get { + if self.address != nil { + return [self.address!] + } + return nil + } + } + public var isHDKeystore: Bool = false + + public func UNSAFE_getPrivateKeyData(password: String, account: EthereumAddress) throws -> Data { + if self.addresses?.count == 1 && account == self.addresses?.last { + guard let privateKey = try? self.getKeyData(password) else {throw AbstractKeystoreError.invalidPasswordError} + return privateKey + } + throw AbstractKeystoreError.invalidAccountError + } + + + // -------------- + private var address: EthereumAddress? + public var keystoreParams: KeystoreParamsV3? + + public convenience init?(_ jsonString: String) { + let lowercaseJSON = jsonString.lowercased() + guard let jsonData = lowercaseJSON.data(using: .utf8) else {return nil} + self.init(jsonData) + } + + public convenience init?(_ jsonData: Data) { + guard let keystoreParams = try? JSONDecoder().decode(KeystoreParamsV3.self, from: jsonData) else {return nil} + self.init(keystoreParams) + } + + public init?(_ keystoreParams: KeystoreParamsV3) { + if (keystoreParams.version != 3) {return nil} + if (keystoreParams.crypto.version != nil && keystoreParams.crypto.version != "1") {return nil} + self.keystoreParams = keystoreParams + if keystoreParams.address != nil { + self.address = EthereumAddress(keystoreParams.address!.addHexPrefix()) + } else { + return nil + } + } + + public init? (password: String = "web3swift", aesMode: String = "aes-128-cbc") throws { + guard var newPrivateKey = SECP256K1.generatePrivateKey() else {return nil} + defer {Data.zero(&newPrivateKey)} + try encryptDataToStorage(password, keyData: newPrivateKey, aesMode: aesMode) + } + + public init? (privateKey: Data, password: String = "web3swift", aesMode: String = "aes-128-cbc") throws { + guard privateKey.count == 32 else {return nil} + guard SECP256K1.verifyPrivateKey(privateKey: privateKey) else {return nil} + try encryptDataToStorage(password, keyData: privateKey, aesMode: aesMode) + } + + fileprivate func encryptDataToStorage(_ password: String, keyData: Data?, dkLen: Int=32, N: Int = 4096, R: Int = 6, P: Int = 1, aesMode: String = "aes-128-cbc") throws { + if (keyData == nil) { + throw AbstractKeystoreError.encryptionError("Encryption without key data") + } + let saltLen = 32; + guard let saltData = Data.randomBytes(length: saltLen) else {throw AbstractKeystoreError.noEntropyError} + guard let derivedKey = scrypt(password: password, salt: saltData, length: dkLen, N: N, R: R, P: P) else {throw AbstractKeystoreError.keyDerivationError} + let last16bytes = Data(derivedKey[(derivedKey.count - 16)...(derivedKey.count-1)]) + let encryptionKey = Data(derivedKey[0...15]) + guard let IV = Data.randomBytes(length: 16) else {throw AbstractKeystoreError.noEntropyError} + var aesCipher : AES? + switch aesMode { + case "aes-128-cbc": + aesCipher = try? AES(key: encryptionKey.bytes, blockMode: CBC(iv: IV.bytes), padding: .noPadding) + case "aes-128-ctr": + aesCipher = try? AES(key: encryptionKey.bytes, blockMode: CTR(iv: IV.bytes), padding: .noPadding) + default: + aesCipher = nil + } + if aesCipher == nil { + throw AbstractKeystoreError.aesError + } + guard let encryptedKey = try aesCipher?.encrypt(keyData!.bytes) else {throw AbstractKeystoreError.aesError} +// let encryptedKeyData = Data(bytes:encryptedKey) + let encryptedKeyData = Data(encryptedKey) + var dataForMAC = Data() + dataForMAC.append(last16bytes) + dataForMAC.append(encryptedKeyData) + let mac = dataForMAC.sha3(.keccak256) + let kdfparams = KdfParamsV3(salt: saltData.toHexString(), dklen: dkLen, n: N, p: P, r: R, c: nil, prf: nil) + let cipherparams = CipherParamsV3(iv: IV.toHexString()) + let crypto = CryptoParamsV3(ciphertext: encryptedKeyData.toHexString(), cipher: aesMode, cipherparams: cipherparams, kdf: "scrypt", kdfparams: kdfparams, mac: mac.toHexString(), version: nil) + guard let pubKey = Web3.Utils.privateToPublic(keyData!) else {throw AbstractKeystoreError.keyDerivationError} + guard let addr = Web3.Utils.publicToAddress(pubKey) else {throw AbstractKeystoreError.keyDerivationError} + self.address = addr + let keystoreparams = KeystoreParamsV3(address: addr.address.lowercased(), crypto: crypto, id: UUID().uuidString.lowercased(), version: 3) + self.keystoreParams = keystoreparams + } + + public func regenerate(oldPassword: String, newPassword: String, dkLen: Int=32, N: Int = 4096, R: Int = 6, P: Int = 1) throws { + var keyData = try self.getKeyData(oldPassword) + if keyData == nil { + throw AbstractKeystoreError.encryptionError("Failed to decrypt a keystore") + } + defer {Data.zero(&keyData!)} + try self.encryptDataToStorage(newPassword, keyData: keyData!, aesMode: self.keystoreParams!.crypto.cipher) + } + + fileprivate func getKeyData(_ password: String) throws -> Data? { + guard let keystoreParams = self.keystoreParams else {return nil} + guard let saltData = Data.fromHex(keystoreParams.crypto.kdfparams.salt) else {return nil} + let derivedLen = keystoreParams.crypto.kdfparams.dklen + var passwordDerivedKey:Data? + switch keystoreParams.crypto.kdf { + case "scrypt": + guard let N = keystoreParams.crypto.kdfparams.n else {return nil} + guard let P = keystoreParams.crypto.kdfparams.p else {return nil} + guard let R = keystoreParams.crypto.kdfparams.r else {return nil} + passwordDerivedKey = scrypt(password: password, salt: saltData, length: derivedLen, N: N, R: R, P: P) + case "pbkdf2": + guard let algo = keystoreParams.crypto.kdfparams.prf else {return nil} + var hashVariant:HMAC.Variant?; + switch algo { + case "hmac-sha256" : + hashVariant = HMAC.Variant.sha256 + case "hmac-sha384" : + hashVariant = HMAC.Variant.sha384 + case "hmac-sha512" : + hashVariant = HMAC.Variant.sha512 + default: + hashVariant = nil + } + guard hashVariant != nil else {return nil} + guard let c = keystoreParams.crypto.kdfparams.c else {return nil} + guard let passData = password.data(using: .utf8) else {return nil} + guard let derivedArray = try? PKCS5.PBKDF2(password: passData.bytes, salt: saltData.bytes, iterations: c, keyLength: derivedLen, variant: hashVariant!).calculate() else {return nil} +// passwordDerivedKey = Data(bytes:derivedArray) + passwordDerivedKey = Data(derivedArray) + default: + return nil + } + guard let derivedKey = passwordDerivedKey else {return nil} + var dataForMAC = Data() + let derivedKeyLast16bytes = Data(derivedKey[(derivedKey.count - 16)...(derivedKey.count - 1)]) + dataForMAC.append(derivedKeyLast16bytes) + guard let cipherText = Data.fromHex(keystoreParams.crypto.ciphertext) else {return nil} + if (cipherText.count != 32) {return nil} + dataForMAC.append(cipherText) + let mac = dataForMAC.sha3(.keccak256) + guard let calculatedMac = Data.fromHex(keystoreParams.crypto.mac), mac.constantTimeComparisonTo(calculatedMac) else {return nil} + let cipher = keystoreParams.crypto.cipher + let decryptionKey = derivedKey[0...15] + guard let IV = Data.fromHex(keystoreParams.crypto.cipherparams.iv) else {return nil} + var decryptedPK:Array? + switch cipher { + case "aes-128-ctr": + guard let aesCipher = try? AES(key: decryptionKey.bytes, blockMode: CTR(iv: IV.bytes), padding: .noPadding) else {return nil} + decryptedPK = try aesCipher.decrypt(cipherText.bytes) + case "aes-128-cbc": + guard let aesCipher = try? AES(key: decryptionKey.bytes, blockMode: CBC(iv: IV.bytes), padding: .noPadding) else {return nil} + decryptedPK = try? aesCipher.decrypt(cipherText.bytes) + default: + return nil + } + guard decryptedPK != nil else {return nil} +// return Data(bytes:decryptedPK!) + return Data(decryptedPK!) + } + + public func serialize() throws -> Data? { + guard let params = self.keystoreParams else {return nil} + let data = try JSONEncoder().encode(params) + return data + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/IBAN.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/IBAN.swift new file mode 100755 index 000000000..500f9560a --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/IBAN.swift @@ -0,0 +1,138 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +public struct ICAP { + public var asset: String + public var institution: String + public var client: String +} + +public struct IBAN { + public var iban: String + + public var isDirect: Bool { + return self.iban.count == 34 || self.iban.count == 35 + } + + public var isIndirect: Bool { + return self.iban.count == 20 + } + + public var checksum: String { + return self.iban[2..<4]; + } + + public var asset: String { + if (self.isIndirect) { + return self.iban[4..<7] + } else { + return "" + } + } + + public var institution : String { + if (self.isIndirect) { + return self.iban[7..<11] + } else { + return "" + } + } + + public var client : String { + if self.isIndirect { + return self.iban[11...] + } else { + return "" + } + } + + + public func toEthereumAddress() -> EthereumAddress? { + if self.isDirect { + let base36 = self.iban[4...]; + guard let asBigNumber = BigUInt(base36, radix: 36) else {return nil} + let addressString = String(asBigNumber, radix: 16).leftPadding(toLength: 40, withPad: "0") + return EthereumAddress(addressString.addHexPrefix()) + } else { + return nil + } + } + + internal static func decodeToInts(_ iban: String) -> String { +// let codePointForA = "A".asciiValue +// let codePointForZ = "Z".asciiValue + + let uppercasedIBAN = iban.replacingOccurrences(of: " ", with: "").uppercased() + let begining = String(uppercasedIBAN[0..<4]) + let end = String(uppercasedIBAN[4...]) + let IBAN = end + begining + var arrayOfInts = [Int]() + for ch in IBAN { + guard let dataPoint = String(ch).data(using: .ascii) else {return ""} + guard dataPoint.count == 1 else {return ""} + let code = Int(dataPoint[0]) + if code >= 65 && code <= 90 { + arrayOfInts.append(code - 65 + 10) + } else { + arrayOfInts.append(code - 48) + } + } + let joinedString = arrayOfInts.map({ (intCh) -> String in + return String(intCh) + }).joined() + return joinedString + } + + internal static func calculateChecksumMod97(_ preparedString: String) -> Int { + var m = 0 + for digit in preparedString.split(intoChunksOf: 1) { + m = m * 10 + m = m + Int(digit)! + m = m % 97 + } + return m + } + + public static func isValidIBANaddress(_ iban: String, noValidityCheck: Bool = false) -> Bool { + let regex = "^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$" + let matcher = try! NSRegularExpression(pattern: regex, options: NSRegularExpression.Options.dotMatchesLineSeparators) + let match = matcher.matches(in: iban, options: NSRegularExpression.MatchingOptions.anchored, range: iban.fullNSRange) + guard match.count == 1 else { + return false + } + if (iban.hasPrefix("XE") && !noValidityCheck) { + let remainder = calculateChecksumMod97(decodeToInts(iban)) + return remainder == 1 + } else { + return true + } + } + + public init?(_ ibanString: String) { + let matched = ibanString.replacingOccurrences(of: " ", with: "").uppercased() + 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} + let base36EncodedString = String(bigNumber, radix: 36); + 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)); + let checkDigits = "0" + String(98 - remainder) + let twoDigits = checkDigits[checkDigits.count-2.. Data { + guard let keystore = self.walletForAddress(account) else {throw AbstractKeystoreError.invalidAccountError} + return try keystore.UNSAFE_getPrivateKeyData(password: password, account: account) + } + + public static var allManagers = [KeystoreManager]() + public static var defaultManager : KeystoreManager? { + if KeystoreManager.allManagers.count == 0 { + return nil + } + return KeystoreManager.allManagers[0] + } + + public static func managerForPath(_ path: String, scanForHDwallets: Bool = false, suffix: String? = nil) -> KeystoreManager? { + guard let manager = try? KeystoreManager(path, scanForHDwallets: scanForHDwallets, suffix: suffix) else {return nil} + return manager + } + + public var path: String + + public func walletForAddress(_ address: EthereumAddress) -> AbstractKeystore? { + for keystore in _keystores { + guard let key = keystore.addresses?.first else {continue} + if key == address && key.isValid { + return keystore as AbstractKeystore? + } + } + for keystore in _bip32keystores { + guard let allAddresses = keystore.addresses else {continue} + for addr in allAddresses { + if addr == address && addr.isValid { + return keystore as AbstractKeystore? + } + } + } + for keystore in _plainKeystores { + guard let key = keystore.addresses?.first else {continue} + if key == address && key.isValid { + return keystore as AbstractKeystore? + } + } + return nil + } + + var _keystores:[EthereumKeystoreV3] = [EthereumKeystoreV3]() + var _bip32keystores: [BIP32Keystore] = [BIP32Keystore]() + var _plainKeystores: [PlainKeystore] = [PlainKeystore]() + + public var keystores:[EthereumKeystoreV3] { + get { + return self._keystores + } + } + + public var bip32keystores:[BIP32Keystore] { + get { + return self._bip32keystores + } + } + + public var plainKeystores:[PlainKeystore] { + get { + return self._plainKeystores + } + } + + public init(_ keystores: [EthereumKeystoreV3]) { + self.isHDKeystore = false + self._keystores = keystores + self.path = "" + } + + public init(_ keystores: [BIP32Keystore]) { + self.isHDKeystore = true + self._bip32keystores = keystores + self.path = "bip32" + } + + public init(_ keystores: [PlainKeystore]) { + self.isHDKeystore = false + self._plainKeystores = keystores + self.path="plain" + } + + private init?(_ path: String, scanForHDwallets: Bool = false, suffix: String? = nil) throws { + if (scanForHDwallets) { + self.isHDKeystore = true + } + self.path = path + let fileManager = FileManager.default + var isDir : ObjCBool = false + var exists = fileManager.fileExists(atPath: path, isDirectory: &isDir) + if (!exists && !isDir.boolValue){ + try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil) + exists = fileManager.fileExists(atPath: path, isDirectory: &isDir) + } + if (!isDir.boolValue) { + return nil + } + let allFiles = try fileManager.contentsOfDirectory(atPath: path) + if (suffix != nil) { + for file in allFiles where file.hasSuffix(suffix!) { + var filePath = path + if (!path.hasSuffix("/")){ + filePath = path + "/" + } + filePath = filePath + file + guard let content = fileManager.contents(atPath: filePath) else {continue} + if (!scanForHDwallets) { + guard let keystore = EthereumKeystoreV3(content) else {continue} + _keystores.append(keystore) + } else { + guard let bipkeystore = BIP32Keystore(content) else {continue} + _bip32keystores.append(bipkeystore) + } + } + } else { + for file in allFiles { + var filePath = path + if (!path.hasSuffix("/")){ + filePath = path + "/" + } + filePath = filePath + file + guard let content = fileManager.contents(atPath: filePath) else {continue} + if (!scanForHDwallets) { + guard let keystore = EthereumKeystoreV3(content) else {continue} + _keystores.append(keystore) + } else { + guard let bipkeystore = BIP32Keystore(content) else {continue} + _bip32keystores.append(bipkeystore) + } + } + } + + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/KeystoreV3JSONStructure.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/KeystoreV3JSONStructure.swift new file mode 100755 index 000000000..8ab80e570 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/KeystoreV3JSONStructure.swift @@ -0,0 +1,46 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +public struct KdfParamsV3: Decodable, Encodable { + var salt: String + var dklen: Int + var n: Int? + var p: Int? + var r: Int? + var c: Int? + var prf: String? +} + +public struct CipherParamsV3: Decodable, Encodable { + var iv: String +} + +public struct CryptoParamsV3: Decodable, Encodable { + var ciphertext: String + var cipher: String + var cipherparams: CipherParamsV3 + var kdf: String + var kdfparams: KdfParamsV3 + var mac: String + var version: String? +} + +public struct KeystoreParamsV3: Decodable, Encodable { + var address: String? + var crypto: CryptoParamsV3 + var id: String? + var version: Int + + public init(address ad: String?, crypto cr: CryptoParamsV3, id i: String, version ver: Int) { + address = ad + crypto = cr + id = i + version = ver + } + +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/PlainKeystore.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/PlainKeystore.swift new file mode 100755 index 000000000..25ee86ff6 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/KeystoreManager/PlainKeystore.swift @@ -0,0 +1,36 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +//import secp256k1_swift + +//import EthereumAddress + +public class PlainKeystore: AbstractKeystore { + private var privateKey: Data + + public var addresses: [EthereumAddress]? + + public var isHDKeystore: Bool = false + + public func UNSAFE_getPrivateKeyData(password: String = "", account: EthereumAddress) throws -> Data { + return self.privateKey + } + + public convenience init?(privateKey: String) { + 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 = Web3.Utils.privateToPublic(privateKey, compressed: false) else {return nil} + guard let address = Web3.Utils.publicToAddress(publicKey) else {return nil} + self.addresses = [address] + self.privateKey = privateKey + } + +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Batching.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Batching.swift new file mode 100755 index 000000000..0d2184580 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Batching.swift @@ -0,0 +1,139 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import PromiseKit + +public class JSONRPCrequestDispatcher { + public var MAX_WAIT_TIME: TimeInterval = 0.1 + public var policy: DispatchPolicy + public var queue: DispatchQueue + + private var provider: Web3Provider + private var lockQueue: DispatchQueue + private var batches: [Batch] = [Batch]() + + public init(provider: Web3Provider, queue: DispatchQueue, policy: DispatchPolicy) { + self.provider = provider + self.queue = queue + self.policy = policy + self.lockQueue = DispatchQueue.init(label: "batchingQueue") // serial simplest queue +// DispatchQueue(label: "batchingQueue", qos: .userInitiated) + self.batches.append(Batch(provider: self.provider, capacity: 32, queue: self.queue, lockQueue: self.lockQueue)) + } + + internal final class Batch { + var capacity: Int + var promisesDict: [UInt64: (promise: Promise, resolver: Resolver)] = [UInt64: (promise: Promise, resolver: Resolver)]() + var requests: [JSONRPCrequest] = [JSONRPCrequest]() + var pendingTrigger: Guarantee? + var provider: Web3Provider + var queue: DispatchQueue + var lockQueue : DispatchQueue + var triggered : Bool = false + func add(_ request: JSONRPCrequest, maxWaitTime: TimeInterval) throws -> Promise { + if self.triggered { + throw Web3Error.nodeError(desc: "Batch is already in flight") + } + let requestID = request.id + let promiseToReturn = Promise.pending() + self.lockQueue.async { + if self.promisesDict[requestID] != nil { + promiseToReturn.resolver.reject(Web3Error.processingError(desc: "Request ID collision")) + } + self.promisesDict[requestID] = promiseToReturn + self.requests.append(request) + if self.pendingTrigger == nil { + self.pendingTrigger = after(seconds: maxWaitTime).done(on: self.queue) { + self.trigger() + } + } + if self.requests.count == self.capacity { + self.trigger() + } + } + return promiseToReturn.promise + } + + func trigger() { + self.lockQueue.async { + if self.triggered { + return + } + self.triggered = true + let requestsBatch = JSONRPCrequestBatch(requests: self.requests) + _ = self.provider.sendAsync(requestsBatch, queue: self.queue).done(on: self.queue){batch in + for response in batch.responses { + if self.promisesDict[UInt64(response.id)] == nil { + for k in self.promisesDict.keys { + self.promisesDict[k]?.resolver.reject(Web3Error.nodeError(desc: "Unknown request id")) + } + return + } + } + for response in batch.responses { + let promise = self.promisesDict[UInt64(response.id)]! + promise.resolver.fulfill(response) + } + }.catch(on:self.queue) {err in + for k in self.promisesDict.keys { + self.promisesDict[k]?.resolver.reject(err) + } + } + } + } + + init (provider: Web3Provider, capacity: Int, queue: DispatchQueue, lockQueue: DispatchQueue) { + self.provider = provider + self.capacity = capacity + self.queue = queue + self.lockQueue = lockQueue + } + } + + func getBatch() throws -> Batch { + guard case .Batch(let batchLength) = self.policy else { + throw Web3Error.inputError(desc: "Trying to batch a request when policy is not to batch") + } + let currentBatch = self.batches.last! + if currentBatch.requests.count.isMultiple(of: batchLength) || currentBatch.triggered { + let newBatch = Batch(provider: self.provider, capacity: Int(batchLength), queue: self.queue, lockQueue: self.lockQueue) + self.batches.append(newBatch) + return newBatch + } + return currentBatch + } + + public enum DispatchPolicy { + case Batch(Int) + case NoBatching + } + + func addToQueue(request: JSONRPCrequest) -> Promise { + switch self.policy { + case .NoBatching: + return self.provider.sendAsync(request, queue: self.queue) + case .Batch(_): + let promise = Promise { + seal in + self.lockQueue.async { + do { + let batch = try self.getBatch() + let internalPromise = try batch.add(request, maxWaitTime: self.MAX_WAIT_TIME) + internalPromise.done(on: self.queue) {resp in + seal.fulfill(resp) + }.catch(on: self.queue){err in + seal.reject(err) + } + } catch { + seal.reject(error) + } + } + } + return promise + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+HttpProvider.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+HttpProvider.swift new file mode 100755 index 000000000..94b1b5a50 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+HttpProvider.swift @@ -0,0 +1,109 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import PromiseKit + +extension Web3HttpProvider { + + static func post(_ request: JSONRPCrequest, providerURL: URL, queue: DispatchQueue = .main, session: URLSession) -> Promise { + let rp = Promise.pending() + var task: URLSessionTask? = nil + queue.async { + do { + let encoder = JSONEncoder() + let requestData = try encoder.encode(request) + var urlRequest = URLRequest(url: providerURL, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData) + urlRequest.httpMethod = "POST" + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + urlRequest.setValue("application/json", forHTTPHeaderField: "Accept") + urlRequest.httpBody = requestData +// let debugValue = try JSONSerialization.jsonObject(with: requestData, options: JSONSerialization.ReadingOptions(rawValue: 0)) +// print(debugValue) +// let debugString = String(data: requestData, encoding: .utf8) +// print(debugString) + task = session.dataTask(with: urlRequest){ (data, response, error) in + guard error == nil else { + rp.resolver.reject(error!) + return + } + guard data != nil else { + rp.resolver.reject(Web3Error.nodeError(desc: "Node response is empty")) + return + } + rp.resolver.fulfill(data!) + } + task?.resume() + } catch { + rp.resolver.reject(error) + } + } + return rp.promise.ensure(on: queue) { + task = nil + }.map(on: queue){ (data: Data) throws -> JSONRPCresponse in + let parsedResponse = try JSONDecoder().decode(JSONRPCresponse.self, from: data) + if parsedResponse.error != nil { + throw Web3Error.nodeError(desc: "Received an error message from node\n" + String(describing: parsedResponse.error!)) + } + return parsedResponse + } + } + + static func post(_ request: JSONRPCrequestBatch, providerURL: URL, queue: DispatchQueue = .main, session: URLSession) -> Promise { + let rp = Promise.pending() + var task: URLSessionTask? = nil + queue.async { + do { + let encoder = JSONEncoder() + let requestData = try encoder.encode(request) + var urlRequest = URLRequest(url: providerURL, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData) + urlRequest.httpMethod = "POST" + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + urlRequest.setValue("application/json", forHTTPHeaderField: "Accept") + urlRequest.httpBody = requestData +// let debugValue = try JSONSerialization.jsonObject(with: requestData, options: JSONSerialization.ReadingOptions(rawValue: 0)) +// print(debugValue) +// let debugString = String(data: requestData, encoding: .utf8) +// print(debugString) + task = session.dataTask(with: urlRequest){ (data, response, error) in + guard error == nil else { + rp.resolver.reject(error!) + return + } + guard data != nil, data!.count != 0 else { + rp.resolver.reject(Web3Error.nodeError(desc: "Node response is empty")) + return + } + rp.resolver.fulfill(data!) + } + task?.resume() + } catch { + rp.resolver.reject(error) + } + } + return rp.promise.ensure(on: queue) { + task = nil + }.map(on: queue){ (data: Data) throws -> JSONRPCresponseBatch in +// let debugValue = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)) +// print(debugValue) + let parsedResponse = try JSONDecoder().decode(JSONRPCresponseBatch.self, from: data) + return parsedResponse + } + } + + public func sendAsync(_ request: JSONRPCrequest, queue: DispatchQueue = .main) -> Promise { + if request.method == nil { + return Promise(error: Web3Error.nodeError(desc: "RPC method is nill")) + } + + return Web3HttpProvider.post(request, providerURL: self.url, queue: queue, session: self.session) + } + + public func sendAsync(_ requests: JSONRPCrequestBatch, queue: DispatchQueue = .main) -> Promise { + return Web3HttpProvider.post(requests, providerURL: self.url, queue: queue, session: self.session) + } +} + diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Contract+GetIndexedEvents.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Contract+GetIndexedEvents.swift new file mode 100755 index 000000000..66391e1fe --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Contract+GetIndexedEvents.swift @@ -0,0 +1,11 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + + +// placeholder + + + diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+Call.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+Call.swift new file mode 100755 index 000000000..ee206b341 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+Call.swift @@ -0,0 +1,36 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import PromiseKit + +extension web3.Eth { + + public func callPromise(_ transaction: EthereumTransaction, transactionOptions: TransactionOptions?) -> Promise{ + let queue = web3.requestDispatcher.queue + do { + guard let request = EthereumTransaction.createRequest(method: .call, transaction: transaction, transactionOptions: transactionOptions) else { + throw Web3Error.processingError(desc: "Transaction is invalid") + } + let rp = web3.dispatch(request) + return rp.map(on: queue ) { response in + guard let value: Data = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } catch { + let returnPromise = Promise.pending() + queue.async { + returnPromise.resolver.reject(error) + } + return returnPromise.promise + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+EstimateGas.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+EstimateGas.swift new file mode 100755 index 000000000..7c2a68bfa --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+EstimateGas.swift @@ -0,0 +1,38 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit + +extension web3.Eth { + + public func estimateGasPromise(_ transaction: EthereumTransaction, transactionOptions: TransactionOptions?) -> Promise{ + let queue = web3.requestDispatcher.queue + do { + guard let request = EthereumTransaction.createRequest(method: .estimateGas, transaction: transaction, transactionOptions: transactionOptions) else { + throw Web3Error.processingError(desc: "Transaction is invalid") + } + let rp = web3.dispatch(request) + return rp.map(on: queue ) { response in + guard let value: BigUInt = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } catch { + let returnPromise = Promise.pending() + queue.async { + returnPromise.resolver.reject(error) + } + return returnPromise.promise + } + } +} + diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetAccounts.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetAccounts.swift new file mode 100755 index 000000000..f8ccd0cd1 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetAccounts.swift @@ -0,0 +1,39 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +//import EthereumAddress + +extension web3.Eth { + public func getAccountsPromise() -> Promise<[EthereumAddress]> { + let queue = web3.requestDispatcher.queue + if (self.web3.provider.attachedKeystoreManager != nil) { + let promise = Promise<[EthereumAddress]>.pending() + queue.async { + do { + let allAccounts = try self.web3.wallet.getAccounts() + promise.resolver.fulfill(allAccounts) + } catch { + promise.resolver.reject(error) + } + } + return promise.promise + } + let request = JSONRPCRequestFabric.prepareRequest(.getAccounts, parameters: []) + let rp = web3.dispatch(request) + return rp.map(on: queue ) { response in + guard let value: [EthereumAddress] = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBalance.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBalance.swift new file mode 100755 index 000000000..5bdb60305 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBalance.swift @@ -0,0 +1,31 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import PromiseKit +import BigInt +//import EthereumAddress + +extension web3.Eth { + public func getBalancePromise(address: EthereumAddress, onBlock: String = "latest") -> Promise { + let addr = address.address + return getBalancePromise(address: addr, onBlock: onBlock) + } + public func getBalancePromise(address: String, onBlock: String = "latest") -> Promise { + let request = JSONRPCRequestFabric.prepareRequest(.getBalance, parameters: [address.lowercased(), onBlock]) + let rp = web3.dispatch(request) + let queue = web3.requestDispatcher.queue + return rp.map(on: queue ) { response in + guard let value: BigUInt = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByHash.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByHash.swift new file mode 100755 index 000000000..90710d4fb --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByHash.swift @@ -0,0 +1,31 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit + +extension web3.Eth { + public func getBlockByHashPromise(_ hash: Data, fullTransactions: Bool = false) -> Promise { + let hashString = hash.toHexString().addHexPrefix() + return getBlockByHashPromise(hashString, fullTransactions: fullTransactions) + } + + public func getBlockByHashPromise(_ hash: String, fullTransactions: Bool = false) -> Promise { + let request = JSONRPCRequestFabric.prepareRequest(.getBlockByHash, parameters: [hash, fullTransactions]) + let rp = web3.dispatch(request) + let queue = web3.requestDispatcher.queue + return rp.map(on: queue ) { response in + guard let value: Block = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByNumber.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByNumber.swift new file mode 100755 index 000000000..ac92584e5 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByNumber.swift @@ -0,0 +1,36 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit + +extension web3.Eth { + public func getBlockByNumberPromise(_ number: UInt64, fullTransactions: Bool = false) -> Promise { + let block = String(number, radix: 16).addHexPrefix() + return getBlockByNumberPromise(block, fullTransactions: fullTransactions) + } + + public func getBlockByNumberPromise(_ number: BigUInt, fullTransactions: Bool = false) -> Promise { + let block = String(number, radix: 16).addHexPrefix() + return getBlockByNumberPromise(block, fullTransactions: fullTransactions) + } + + public func getBlockByNumberPromise(_ number: String, fullTransactions: Bool = false) -> Promise { + let request = JSONRPCRequestFabric.prepareRequest(.getBlockByNumber, parameters: [number, fullTransactions]) + let rp = web3.dispatch(request) + let queue = web3.requestDispatcher.queue + return rp.map(on: queue ) { response in + guard let value: Block = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockNumber.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockNumber.swift new file mode 100755 index 000000000..e8bc2676d --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockNumber.swift @@ -0,0 +1,26 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit + +extension web3.Eth { + public func getBlockNumberPromise() -> Promise { + let request = JSONRPCRequestFabric.prepareRequest(.blockNumber, parameters: []) + let rp = web3.dispatch(request) + let queue = web3.requestDispatcher.queue + return rp.map(on: queue ) { response in + guard let value: BigUInt = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetGasPrice.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetGasPrice.swift new file mode 100755 index 000000000..fbda2ace7 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetGasPrice.swift @@ -0,0 +1,26 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit + +extension web3.Eth { + public func getGasPricePromise() -> Promise { + let request = JSONRPCRequestFabric.prepareRequest(.gasPrice, parameters: []) + let rp = web3.dispatch(request) + let queue = web3.requestDispatcher.queue + return rp.map(on: queue ) { response in + guard let value: BigUInt = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionCount.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionCount.swift new file mode 100755 index 000000000..cbd1f4708 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionCount.swift @@ -0,0 +1,32 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +//import EthereumAddress + +extension web3.Eth { + public func getTransactionCountPromise(address: EthereumAddress, onBlock: String = "latest") -> Promise { + let addr = address.address + return getTransactionCountPromise(address: addr, onBlock: onBlock) + } + + public func getTransactionCountPromise(address: String, onBlock: String = "latest") -> Promise { + let request = JSONRPCRequestFabric.prepareRequest(.getTransactionCount, parameters: [address.lowercased(), onBlock]) + let rp = web3.dispatch(request) + let queue = web3.requestDispatcher.queue + return rp.map(on: queue ) { response in + guard let value: BigUInt = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionDetails.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionDetails.swift new file mode 100755 index 000000000..522f04307 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionDetails.swift @@ -0,0 +1,31 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit + +extension web3.Eth { + public func getTransactionDetailsPromise(_ txhash: Data) -> Promise { + let hashString = txhash.toHexString().addHexPrefix() + return self.getTransactionDetailsPromise(hashString) + } + + public func getTransactionDetailsPromise(_ txhash: String) -> Promise { + let request = JSONRPCRequestFabric.prepareRequest(.getTransactionByHash, parameters: [txhash]) + let rp = web3.dispatch(request) + let queue = web3.requestDispatcher.queue + return rp.map(on: queue ) { response in + guard let value: TransactionDetails = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionReceipt.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionReceipt.swift new file mode 100755 index 000000000..517a007ee --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionReceipt.swift @@ -0,0 +1,31 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit + +extension web3.Eth { + public func getTransactionReceiptPromise(_ txhash: Data) -> Promise { + let hashString = txhash.toHexString().addHexPrefix() + return self.getTransactionReceiptPromise(hashString) + } + + public func getTransactionReceiptPromise(_ txhash: String) -> Promise { + let request = JSONRPCRequestFabric.prepareRequest(.getTransactionReceipt, parameters: [txhash]) + let rp = web3.dispatch(request) + let queue = web3.requestDispatcher.queue + return rp.map(on: queue ) { response in + guard let value: TransactionReceipt = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+SendRawTransaction.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+SendRawTransaction.swift new file mode 100755 index 000000000..7aa3b83a6 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+SendRawTransaction.swift @@ -0,0 +1,51 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import PromiseKit + +extension web3.Eth { + public func sendRawTransactionPromise(_ transaction: Data) -> Promise { + guard let deserializedTX = EthereumTransaction.fromRaw(transaction) else { + let promise = Promise.pending() + promise.resolver.reject(Web3Error.processingError(desc: "Serialized TX is invalid")) + return promise.promise + } + return sendRawTransactionPromise(deserializedTX) + } + + public func sendRawTransactionPromise(_ transaction: EthereumTransaction) -> Promise{ +// print(transaction) + let queue = web3.requestDispatcher.queue + do { + guard let request = EthereumTransaction.createRawTransaction(transaction: transaction) else { + throw Web3Error.processingError(desc: "Transaction is invalid") + } + let rp = web3.dispatch(request) + return rp.map(on: queue ) { response in + guard let value: String = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + let result = TransactionSendingResult(transaction: transaction, hash: value) + for hook in self.web3.postSubmissionHooks { + hook.queue.async { + hook.function(result) + } + } + return result + } + } catch { + let returnPromise = Promise.pending() + queue.async { + returnPromise.resolver.reject(error) + } + return returnPromise.promise + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+SendTransaction.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+SendTransaction.swift new file mode 100755 index 000000000..7fe53fd98 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+SendTransaction.swift @@ -0,0 +1,79 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit + +extension web3.Eth { + + public func sendTransactionPromise(_ transaction: EthereumTransaction, transactionOptions: TransactionOptions? = nil, password:String = "web3swift") -> Promise { +// print(transaction) + var assembledTransaction : EthereumTransaction = transaction // .mergedWithOptions(transactionOptions) + let queue = web3.requestDispatcher.queue + do { + var mergedOptions = self.web3.transactionOptions.merge(transactionOptions) + + var forAssemblyPipeline : (EthereumTransaction, TransactionOptions) = (assembledTransaction, mergedOptions) + + for hook in self.web3.preSubmissionHooks { + let prom : Promise = Promise {seal in + hook.queue.async { + let hookResult = hook.function(forAssemblyPipeline) + if hookResult.2 { + forAssemblyPipeline = (hookResult.0, hookResult.1) + } + seal.fulfill(hookResult.2) + } + } + let shouldContinue = try prom.wait() + if !shouldContinue { + throw Web3Error.processingError(desc: "Transaction is canceled by middleware") + } + } + + assembledTransaction = forAssemblyPipeline.0 + mergedOptions = forAssemblyPipeline.1 + + if self.web3.provider.attachedKeystoreManager == nil { + guard let request = EthereumTransaction.createRequest(method: .sendTransaction, transaction: assembledTransaction, transactionOptions: mergedOptions) else + { + throw Web3Error.processingError(desc: "Failed to create a request to send transaction") + } + return self.web3.dispatch(request).map(on: queue) {response in + guard let value: String = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + let result = TransactionSendingResult(transaction: assembledTransaction, hash: value) + for hook in self.web3.postSubmissionHooks { + hook.queue.async { + hook.function(result) + } + } + return result + } + } + guard let from = mergedOptions.from else { + throw Web3Error.inputError(desc: "No 'from' field provided") + } + do { + try Web3Signer.signTX(transaction: &assembledTransaction, keystore: self.web3.provider.attachedKeystoreManager!, account: from, password: password) + } catch { + throw Web3Error.inputError(desc: "Failed to locally sign a transaction") + } + return self.web3.eth.sendRawTransactionPromise(assembledTransaction) + } catch { + let returnPromise = Promise.pending() + queue.async { + returnPromise.resolver.reject(error) + } + return returnPromise.promise + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+CreateAccount.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+CreateAccount.swift new file mode 100755 index 000000000..e5e83d556 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+CreateAccount.swift @@ -0,0 +1,37 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +//import EthereumAddress + +extension web3.Personal { + public func createAccountPromise(password:String = "web3swift") -> Promise { + let queue = web3.requestDispatcher.queue + do { + if self.web3.provider.attachedKeystoreManager == nil { + let request = JSONRPCRequestFabric.prepareRequest(.createAccount, parameters: [password]) + return self.web3.dispatch(request).map(on: queue) {response in + guard let value: EthereumAddress = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } + throw Web3Error.inputError(desc: "Creating account in a local keystore with this method is not supported") + } catch { + let returnPromise = Promise.pending() + queue.async { + returnPromise.resolver.reject(error) + } + return returnPromise.promise + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+Sign.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+Sign.swift new file mode 100755 index 000000000..bf71b10c1 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+Sign.swift @@ -0,0 +1,44 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +//import EthereumAddress + +extension web3.Personal { + + public func signPersonalMessagePromise(message: Data, from: EthereumAddress, password:String = "web3swift") -> Promise { + let queue = web3.requestDispatcher.queue + do { + if self.web3.provider.attachedKeystoreManager == nil { + let hexData = message.toHexString().addHexPrefix() + let request = JSONRPCRequestFabric.prepareRequest(.personalSign, parameters: [from.address.lowercased(), hexData]) + return self.web3.dispatch(request).map(on: queue) {response in + guard let value: Data = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } + guard let signature = try Web3Signer.signPersonalMessage(message, keystore: self.web3.provider.attachedKeystoreManager!, account: from, password: password) else { throw Web3Error.inputError(desc: "Failed to locally sign a message") } + let returnPromise = Promise.pending() + queue.async { + returnPromise.resolver.fulfill(signature) + } + return returnPromise.promise + } catch { + let returnPromise = Promise.pending() + queue.async { + returnPromise.resolver.reject(error) + } + return returnPromise.promise + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+UnlockAccount.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+UnlockAccount.swift new file mode 100755 index 000000000..62512f6d4 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+UnlockAccount.swift @@ -0,0 +1,43 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +//import EthereumAddress + +extension web3.Personal { + public func unlockAccountPromise(account: EthereumAddress, password:String = "web3swift", seconds: UInt64 = 300) -> Promise { + let addr = account.address + return unlockAccountPromise(account: addr, password: password, seconds: seconds) + } + + + public func unlockAccountPromise(account: String, password:String = "web3swift", seconds: UInt64 = 300) -> Promise { + let queue = web3.requestDispatcher.queue + do { + if self.web3.provider.attachedKeystoreManager == nil { + let request = JSONRPCRequestFabric.prepareRequest(.unlockAccount, parameters: [account.lowercased(), password, seconds]) + return self.web3.dispatch(request).map(on: queue) {response in + guard let value: Bool = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } + throw Web3Error.inputError(desc: "Can not unlock a local keystore") + } catch { + let returnPromise = Promise.pending() + queue.async { + returnPromise.resolver.reject(error) + } + return returnPromise.promise + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+TxPool.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+TxPool.swift new file mode 100755 index 000000000..996fae706 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+TxPool.swift @@ -0,0 +1,56 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit + +extension web3.TxPool { + public func getInspectPromise() -> Promise<[String:[String:[String:String]]]> { + let request = JSONRPCRequestFabric.prepareRequest(.getTxPoolInspect, parameters: []) + let rp = web3.dispatch(request) + let queue = web3.requestDispatcher.queue + return rp.map(on: queue ) { response in + guard let value: [String:[String:[String:String]]] = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } + + public func getStatusPromise() -> Promise { + let request = JSONRPCRequestFabric.prepareRequest(.getTxPoolStatus, parameters: []) + let rp = web3.dispatch(request) + let queue = web3.requestDispatcher.queue + return rp.map(on: queue ) { response in + guard let value: TxPoolStatus = response.result as? TxPoolStatus else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } + + public func getContentPromise() -> Promise { + let request = JSONRPCRequestFabric.prepareRequest(.getTxPoolContent, parameters: []) + let rp = web3.dispatch(request) + let queue = web3.requestDispatcher.queue + return rp.map(on: queue ) { response in + guard let value: TxPoolContent = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/SwiftRLP/RLP.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/SwiftRLP/RLP.swift new file mode 100755 index 000000000..e9f904ad6 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/SwiftRLP/RLP.swift @@ -0,0 +1,320 @@ +// +// RLP.swift +// SwiftRLP +// +// Created by Alex Vlasov on 04/10/2018. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt + +//protocol ArrayType {} +//extension Array : ArrayType {} +public struct RLP { + enum Error: Swift.Error { + case encodingError + case decodingError + } + + static var length56 = BigUInt(UInt(56)) + static var lengthMax = (BigUInt(UInt(1)) << 256) + + internal static func encode(_ element: AnyObject) -> Data? { + if let string = element as? String { + return encode(string) + + } else if let data = element as? Data { + return encode(data) + } + else if let biguint = element as? BigUInt { + return encode(biguint) + } + return nil; + } + + internal static func encode(_ string: String) -> Data? { + if let hexData = Data.fromHex(string) { + return encode(hexData) + } + 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} + let uint = UInt(number) + return encode(uint) + } + + internal static func encode(_ number: UInt) -> Data? { + let biguint = BigUInt(number) + return encode(biguint) + } + + internal static func encode(_ number: BigUInt) -> Data? { + let encoded = number.serialize() + return encode(encoded) + } + + internal static func encode(_ data: Data) -> Data? { + if (data.count == 1 && data.bytes[0] < UInt8(0x80)) { + return data + } else { + guard let length = encodeLength(data.count, offset: UInt8(0x80)) else {return nil} + var encoded = Data() + encoded.append(length) + encoded.append(data) + return encoded + } + } + + internal static func encodeLength(_ length: Int, offset: UInt8) -> Data? { + if (length < 0) { + return nil; + } + let bigintLength = BigUInt(UInt(length)) + return encodeLength(bigintLength, offset: offset) + } + + 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} + 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} + let lengthPrefix = prefix + offset + UInt8(55) + var encoded = Data([lengthPrefix]) + encoded.append(encodedLength) + return encoded + } + return nil + } + + internal static func lengthToBinary(_ length: BigUInt) -> UInt8? { + if (length == 0) { + return UInt8(0) + } + let divisor = BigUInt(256) + var encoded = Data() + guard let prefix = lengthToBinary(length/divisor) else {return nil} + let suffix = length % divisor + + var prefixData = Data([prefix]) + if (prefix == UInt8(0)) { + prefixData = Data() + } + let suffixData = suffix.serialize() + + encoded.append(prefixData) + encoded.append(suffixData) + guard encoded.count == 1 else {return nil} + return encoded.bytes[0] + } + + public static func encode(_ elements: Array) -> Data? { + var encodedData = Data() + for e in elements { + if let encoded = encode(e) { + encodedData.append(encoded) + } else { + guard let asArray = e as? Array 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} + if (encodedLength != Data()) { + encodedLength.append(encodedData) + } + return encodedLength + } + + public static func decode(_ raw: String) -> RLPItem? { + guard let rawData = Data.fromHex(raw) else {return nil} + return decode(rawData) + } + + public static func decode(_ raw: Data) -> RLPItem? { + if raw.count == 0 { + return RLPItem.noItem + } + var outputArray = [RLPItem]() + 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} + switch type { + case .empty: + break + case .data: + 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} + switch inside.content { + case .data(_): + return nil + default: + outputArray.append(inside) + } + } + guard let tail = try? slice(data: bytesToParse, start: offset + dataLength) else {return nil} + bytesToParse = tail + } + return RLPItem.init(content: .list(outputArray, 0, Data(raw))) + } + + public struct RLPItem { + + enum UnderlyingType { + case empty + case data + case list + } + + public enum RLPContent { + case noItem + case data(Data) + indirect case list([RLPItem], Int, Data) + } + + public var content: RLPContent + + public var isData: Bool { + switch self.content { + case .noItem: + return false + case .data(_): + return true + case .list(_, _, _): + return false + } + } + + public var isList: Bool { + switch self.content { + case .noItem: + return false + case .data(_): + return false + case .list(_,_,_): + return true + } + } + public var count: Int? { + switch self.content { + case .noItem: + return nil + case .data(_): + return nil + case .list(let list, _, _): + return list.count + } + } + // public var hasNext: Bool { + // switch self.content { + // case .noItem: + // return false + // case .data(_): + // return false + // case .list(let list, let counter, _): + // return list.count > counter + // } + // } + + public subscript(index: Int) -> RLPItem? { + get { + // guard self.hasNext else {return nil} + guard case .list(let list, _, _) = self.content else {return nil} + let item = list[index] + return item + } + } + + public var data: Data? { + return self.getData() + } + + public func getData() -> Data? { + if self.isList { + guard case .list(_, _, let rawContent) = self.content else {return nil} + return rawContent + } + guard case .data(let data) = self.content else {return nil} + return data + } + + public static var noItem: RLPItem { + return RLPItem.init(content: .noItem) + } + } + + internal static func decodeLength(_ input: Data) -> (offset: BigUInt?, length: BigUInt?, type: RLPItem.UnderlyingType?) { + do { + let length = BigUInt(input.count) + if (length == BigUInt(0)) { + return (0, 0, .empty) + } + let prefixByte = input[0] + if prefixByte <= 0x7f { + return (BigUInt(0), BigUInt(1), .data) + }else if prefixByte <= 0xb7 && length > BigUInt(prefixByte - 0x80) { + let dataLength = BigUInt(prefixByte - 0x80) + return (BigUInt(1), dataLength, .data) + } else if try prefixByte <= 0xbf && length > BigUInt(prefixByte - 0xb7) && length > BigUInt(prefixByte - 0xb7) + toBigUInt(slice(data: input, offset: BigUInt(1), length: BigUInt(prefixByte - 0xb7))) { + let lengthOfLength = BigUInt(prefixByte - 0xb7) + let dataLength = try toBigUInt(slice(data: input, offset: BigUInt(1), length: BigUInt(prefixByte - 0xb7))) + return (1 + lengthOfLength, dataLength, .data) + } else if prefixByte <= 0xf7 && length > BigUInt(prefixByte - 0xc0) { + let listLen = BigUInt(prefixByte - 0xc0) + return (1, listLen, .list) + } else if try prefixByte <= 0xff && length > BigUInt(prefixByte - 0xf7) && length > BigUInt(prefixByte - 0xf7) + toBigUInt(slice(data: input, offset: BigUInt(1), length: BigUInt(prefixByte - 0xf7))) { + let lengthOfListLength = BigUInt(prefixByte - 0xf7) + let listLength = try toBigUInt(slice(data: input, offset: BigUInt(1), length: BigUInt(prefixByte - 0xf7))) + return (1 + lengthOfListLength, listLength, .list) + } else { + return (nil, nil, nil) + } + } catch { + return (nil, nil, nil) + } + } + + internal static func slice(data: Data, offset: BigUInt, length: BigUInt) throws -> Data { + if BigUInt(data.count) < offset + length {throw Error.encodingError} + let slice = data[UInt64(offset) ..< UInt64(offset + length)] + return Data(slice) + } + + internal static func slice(data: Data, start: BigUInt) throws -> Data { + if BigUInt(data.count) < start {throw Error.encodingError} + let slice = data[UInt64(start) ..< UInt64(data.count)] + return Data(slice) + } + + internal static func toBigUInt(_ raw: Data) throws -> BigUInt { + if raw.count == 0 { + throw Error.encodingError + } else if raw.count == 1 { + return BigUInt.init(raw) + } else { + let slice = raw[0 ..< raw.count - 1] + return try BigUInt(raw[raw.count-1]) + toBigUInt(slice)*256 + } + } +} + +fileprivate extension Data { + + var bytes: Array { + return Array(self) + } +} + diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1155/Web3+ERC1155.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1155/Web3+ERC1155.swift new file mode 100644 index 000000000..2daebddbe --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1155/Web3+ERC1155.swift @@ -0,0 +1,147 @@ +// +// Web3+ERC1155.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 20/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +//import EthereumAddress + +//Multi Token Standard +protocol IERC1155: IERC165 { + + func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, id: BigUInt, value: BigUInt, data: [UInt8]) throws -> WriteTransaction + + func safeBatchTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, ids: [BigUInt], values: [BigUInt], data: [UInt8]) throws -> WriteTransaction + + func balanceOf(account: EthereumAddress, id: BigUInt) throws -> BigUInt + + func setApprovalForAll(from: EthereumAddress, operator user: EthereumAddress, approved: Bool, scope: Data) throws -> WriteTransaction + + func isApprovedForAll(owner: EthereumAddress, operator user: EthereumAddress, scope: Data) throws -> Bool +} + +protocol IERC1155Metadata { + func uri(id: BigUInt) throws -> String + func name(id: BigUInt) throws -> String +} + +public class ERC1155: IERC1155 { + + private var _tokenId: BigUInt? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc1155ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var tokenId: BigUInt { + self.readProperties() + if self._tokenId != nil { + return self._tokenId! + } + return 0 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + + guard let tokenIdPromise = contract.read("id", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [tokenIdPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let tokenIdResult) = resolvedPromises[0] else {return} + guard let tokenId = tokenIdResult["0"] as? BigUInt else {return} + self._tokenId = tokenId + + self._hasReadProperties = true + }.wait() + } + + func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, id: BigUInt, value: BigUInt, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("safeTransferFrom", parameters: [originalOwner, to, id, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func safeBatchTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, ids: [BigUInt], values: [BigUInt], data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("safeBatchTransferFrom", parameters: [originalOwner, to, ids, values, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func balanceOf(account: EthereumAddress, id: BigUInt) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account, id] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + + func setApprovalForAll(from: EthereumAddress, operator user: EthereumAddress, approved: Bool, scope: Data) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("setApprovalForAll", parameters: [user, approved, scope] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func isApprovedForAll(owner: EthereumAddress, operator user: EthereumAddress, scope: Data) throws -> Bool { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.callOnBlock = .latest + let result = try contract.read("isApprovedForAll", parameters: [owner, user, scope] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + + func supportsInterface(interfaceID: String) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + transactionOptions.gasLimit = .manual(30000) + let result = try contract.read("supportsInterface", parameters: [interfaceID] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1376/Web3+ERC1376.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1376/Web3+ERC1376.swift new file mode 100644 index 000000000..7e1c6b943 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1376/Web3+ERC1376.swift @@ -0,0 +1,502 @@ +// +// Web3+ERC1376.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 20/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress +import PromiseKit + +public enum IERC1376DelegateMode: UInt { + case PublicMsgSender = 0 + case PublicTxOrigin = 1 + case PrivateMsgSender = 2 + case PrivateTxOrigin = 3 +} + +public struct DirectDebitInfo { + let amount: BigUInt + let startTime: BigUInt + let interval: BigUInt +} + +public struct DirectDebit { + let info: DirectDebitInfo + let epoch: BigUInt +} + +extension DirectDebit: Hashable { +} + +extension DirectDebitInfo: Hashable { +} + +//Service-Friendly Token Standard +protocol IERC1376: IERC20 { + func approve(from: EthereumAddress, spender: EthereumAddress, expectedValue: String, newValue: String) throws -> WriteTransaction + func increaseAllowance(from: EthereumAddress, spender: EthereumAddress, value: String) throws -> WriteTransaction + func decreaseAllowance(from: EthereumAddress, spender: EthereumAddress, value: String, strict: Bool) throws -> WriteTransaction + func setERC20ApproveChecking(from: EthereumAddress, approveChecking: Bool) throws -> WriteTransaction + + func spendableAllowance(owner: EthereumAddress, spender: EthereumAddress) throws -> BigUInt + func transfer(from: EthereumAddress, data: String) throws -> WriteTransaction + func transferAndCall(from: EthereumAddress, to: EthereumAddress, value: String, data: [UInt8]) throws -> WriteTransaction + + func nonceOf(owner: EthereumAddress) throws -> BigUInt + func increaseNonce(from: EthereumAddress) throws -> WriteTransaction + func delegateTransferAndCall(from: EthereumAddress, + nonce: BigUInt, + fee: BigUInt, + gasAmount: BigUInt, + to: EthereumAddress, + value: String, + data: [UInt8], + mode: IERC1376DelegateMode, + v: UInt8, + r: Data, + s: Data) throws -> WriteTransaction + + func directDebit(debtor: EthereumAddress, receiver: EthereumAddress) throws -> DirectDebit + func setupDirectDebit(from: EthereumAddress, receiver: EthereumAddress, info: DirectDebitInfo) throws -> WriteTransaction + func terminateDirectDebit(from: EthereumAddress, receiver: EthereumAddress) throws -> WriteTransaction + func withdrawDirectDebit(from: EthereumAddress, debtor: EthereumAddress) throws -> WriteTransaction + func withdrawDirectDebit(from: EthereumAddress, debtors: [EthereumAddress], strict: Bool) throws -> WriteTransaction +} + +public class ERC1376: IERC1376 { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc1376ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 255 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("allowance", parameters: [originalOwner, delegate] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(newAmount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("setAllowance", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func approve(from: EthereumAddress, spender: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + + func approve(from: EthereumAddress, spender: EthereumAddress, expectedValue: String, newValue: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 eValue = Web3.Utils.parseToBigUInt(expectedValue, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + guard let nValue = Web3.Utils.parseToBigUInt(newValue, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, eValue, nValue] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func increaseAllowance(from: EthereumAddress, spender: EthereumAddress, value: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 amount = Web3.Utils.parseToBigUInt(value, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("increaseAllowance", parameters: [spender, amount] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func decreaseAllowance(from: EthereumAddress, spender: EthereumAddress, value: String, strict: Bool) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 amount = Web3.Utils.parseToBigUInt(value, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("decreaseAllowance", parameters: [spender, amount, strict] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func setERC20ApproveChecking(from: EthereumAddress, approveChecking: Bool) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("setERC20ApproveChecking", parameters: [approveChecking] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func spendableAllowance(owner: EthereumAddress, spender: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("spendableAllowance", parameters: [owner, spender] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + + func transfer(from: EthereumAddress, data: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(data, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func transferAndCall(from: EthereumAddress, to: EthereumAddress, value: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 amount = Web3.Utils.parseToBigUInt(value, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transferAndCall", parameters: [to, amount, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func nonceOf(owner: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("nonceOf", parameters: [owner] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + + func increaseNonce(from: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + let tx = contract.write("increaseNonce", parameters: [] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func delegateTransferAndCall(from: EthereumAddress, nonce: BigUInt, fee: BigUInt, gasAmount: BigUInt, to: EthereumAddress, value: String, data: [UInt8], mode: IERC1376DelegateMode, v: UInt8, r: Data, s: Data) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 amount = Web3.Utils.parseToBigUInt(value, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let modeValue = mode.rawValue + + let tx = contract.write("delegateTransferAndCall", parameters: [nonce, fee, gasAmount, to, amount, data, modeValue, v, r, s] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func directDebit(debtor: EthereumAddress, receiver: EthereumAddress) throws -> DirectDebit { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("directDebit", parameters: [debtor, receiver] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + guard let res = result["0"] as? DirectDebit else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + return res + } + + func setupDirectDebit(from: EthereumAddress, receiver: EthereumAddress, info: DirectDebitInfo) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("setupDirectDebit", parameters: [receiver, info] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func terminateDirectDebit(from: EthereumAddress, receiver: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("terminateDirectDebit", parameters: [receiver] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func withdrawDirectDebit(from: EthereumAddress, debtor: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("withdrawDirectDebit", parameters: [debtor] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func withdrawDirectDebit(from: EthereumAddress, debtors: [EthereumAddress], strict: Bool) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("withdrawDirectDebit", parameters: [debtors, strict] as [AnyObject], transactionOptions: basicOptions)! + return tx + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1400/Web3+ERC1400.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1400/Web3+ERC1400.swift new file mode 100644 index 000000000..8db216c47 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1400/Web3+ERC1400.swift @@ -0,0 +1,931 @@ +// +// Web3+ERC1400.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 14/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// +import Foundation +import BigInt +//import EthereumAddress +import PromiseKit + +//Security Token Standard +protocol IERC1400: IERC20 { + + // Document Management + func getDocument(name: Data) throws -> (String, Data) + func setDocument(from: EthereumAddress, name: Data, uri: String, documentHash: Data) throws -> WriteTransaction + + // Token Information + func balanceOfByPartition(partition: Data, tokenHolder: EthereumAddress) throws -> BigUInt + func partitionsOf(tokenHolder: EthereumAddress) throws -> [Data] + + // Transfers + func transferWithData(from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + func transferFromWithData(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + + // Partition Token Transfers + func transferByPartition(partition: Data, from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + func operatorTransferByPartition(partition: Data, from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction + + // Controller Operation + func isControllable() throws -> Bool + func controllerTransfer(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction + func controllerRedeem(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction + + // Operator Management + func authorizeOperator(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction + func revokeOperator(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction + func authorizeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) throws -> WriteTransaction + func revokeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) throws -> WriteTransaction + + // Operator Information + func isOperator(operator user: EthereumAddress, tokenHolder: EthereumAddress) throws -> Bool + func isOperatorForPartition(partition: Data, operator user: EthereumAddress, tokenHolder: EthereumAddress) throws -> Bool + + // Token Issuance + func isIssuable() throws -> Bool + func issue(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + func issueByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + + // Token Redemption + func redeem(from: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + func redeemFrom(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + func redeemByPartition(from: EthereumAddress, partition: Data, amount: String, data: [UInt8]) throws -> WriteTransaction + func operatorRedeemByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, operatorData: [UInt8]) throws -> WriteTransaction + + // Transfer Validity + func canTransfer(to: EthereumAddress, amount: String, data: [UInt8]) throws -> ([UInt8], Data) + func canTransferFrom(originalOwner: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) throws -> ([UInt8], Data) + func canTransferByPartition(originalOwner: EthereumAddress, to: EthereumAddress, partition: Data, amount: String, data: [UInt8]) throws -> ([UInt8], Data, Data) +} + +// This namespace contains functions to work with ERC1400 tokens. +// variables are lazyly evaluated or global token information (name, ticker, total supply) +// can be imperatively read and saved +public class ERC1400: IERC1400 { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc1400ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 255 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("allowance", parameters: [originalOwner, delegate] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(newAmount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("setAllowance", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + //ERC1400 methods + public func getDocument(name: Data) throws -> (String, Data) { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("getDocument", parameters: [name] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("setDocument", parameters: [name, uri, documentHash] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func balanceOfByPartition(partition: Data, tokenHolder: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOfByPartition", parameters: [partition, tokenHolder] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> [Data] { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("partitionsOf", parameters: [tokenHolder] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferWithData", parameters: [to, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFromWithData(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFromWithData", parameters: [originalOwner, to, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferByPartition(partition: Data, from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferByPartition", parameters: [partition, to, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func operatorTransferByPartition(partition: Data, from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("operatorTransferByPartition", parameters: [partition, originalOwner, to, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func isControllable() throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("isControllable", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("controllerTransfer", parameters: [originalOwner, to, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func controllerRedeem(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("controllerRedeem", parameters: [tokenHolder, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func authorizeOperator(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("authorizeOperator", parameters: [user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func revokeOperator(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("revokeOperator", parameters: [user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func authorizeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("authorizeOperatorByPartition", parameters: [partition, user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func revokeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("revokeOperatorByPartition", parameters: [partition, user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func isOperator(operator user: EthereumAddress, tokenHolder: EthereumAddress) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("isOperator", parameters: [user, tokenHolder] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("isOperatorForPartition", parameters: [partition, user, tokenHolder] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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() throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("isIssuable", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("issue", parameters: [tokenHolder, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func issueByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("issueByPartition", parameters: [partition, tokenHolder, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func redeem(from: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("redeem", parameters: [value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func redeemFrom(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("redeemFrom", parameters: [tokenHolder, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func redeemByPartition(from: EthereumAddress, partition: Data, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("redeemByPartition", parameters: [partition, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func operatorRedeemByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("operatorRedeemByPartition", parameters: [partition, tokenHolder, value, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func canTransfer(to: EthereumAddress, amount: String, data: [UInt8]) throws -> ([UInt8], Data) { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: transactionOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let result = try contract.read("canTransfer", parameters: [to, value, data] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> ([UInt8], Data) { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: transactionOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let result = try contract.read("canTransfer", parameters: [originalOwner, to, value, data] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> ([UInt8], Data, Data) { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: transactionOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let result = try contract.read("canTransfer", parameters: [originalOwner, to, partition, value, data] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } +} + +extension ERC1400: IERC777 { + public func canImplementInterfaceForAddress(interfaceHash: Data, addr: EthereumAddress) throws -> Data { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("canImplementInterfaceForAddress", parameters: [interfaceHash, addr] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> EthereumAddress { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("getInterfaceImplementer", parameters: [addr, interfaceHash] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("setInterfaceImplementer", parameters: [addr, interfaceHash, implementer] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setManager(from: EthereumAddress, addr: EthereumAddress, newManager: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("setManager", parameters: [addr, newManager] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func interfaceHash(interfaceName: String) throws -> Data { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("interfaceHash", parameters: [interfaceName] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("updateERC165Cache", parameters: [contract, interfaceId] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func supportsInterface(interfaceID: String) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + transactionOptions.gasLimit = .manual(30000) + let result = try contract.read("supportsInterface", parameters: [interfaceID] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("granularity", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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() throws -> [EthereumAddress] { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("defaultOperators", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + let tx = contract.write("authorizeOperator", parameters: [user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func revoke(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + let tx = contract.write("revokeOperator", parameters: [user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func isOperatorFor(operator user: EthereumAddress, tokenHolder: EthereumAddress) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("isOperatorFor", parameters: [user, tokenHolder] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("send", parameters: [to, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func operatorSend(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("operatorSend", parameters: [originalOwner, to, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func burn(from: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("burn", parameters: [value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func operatorBurn(from: EthereumAddress, amount: String, originalOwner: EthereumAddress, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("burn", parameters: [originalOwner, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1410/Web3+ERC1410.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1410/Web3+ERC1410.swift new file mode 100644 index 000000000..836dcdf69 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1410/Web3+ERC1410.swift @@ -0,0 +1,664 @@ +// +// Web3+ERC1410.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 19/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress +import PromiseKit + +//Partially Fungible Token Standard +protocol IERC1410: IERC20 { + + // Token Information + func getBalance(account: EthereumAddress) throws -> BigUInt + func balanceOfByPartition(partition: Data, tokenHolder: EthereumAddress) throws -> BigUInt + func partitionsOf(tokenHolder: EthereumAddress) throws -> [Data] + func totalSupply() throws -> BigUInt + + // Token Transfers + func transferByPartition(partition: Data, from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + func operatorTransferByPartition(partition: Data, from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction + func canTransferByPartition(originalOwner: EthereumAddress, to: EthereumAddress, partition: Data, amount: String, data: [UInt8]) throws -> ([UInt8], Data, Data) + + // Operator Information + func isOperator(operator user: EthereumAddress, tokenHolder: EthereumAddress) throws -> Bool + func isOperatorForPartition(partition: Data, operator user: EthereumAddress, tokenHolder: EthereumAddress) throws -> Bool + + // Operator Management + func authorizeOperator(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction + func revokeOperator(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction + func authorizeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) throws -> WriteTransaction + func revokeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) throws -> WriteTransaction + + // Issuance / Redemption + func issueByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + func redeemByPartition(from: EthereumAddress, partition: Data, amount: String, data: [UInt8]) throws -> WriteTransaction + func operatorRedeemByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, operatorData: [UInt8]) throws -> WriteTransaction + +} + +public class ERC1410: IERC1410 { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + private var _totalSupply: BigUInt? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc1410ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 255 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("allowance", parameters: [originalOwner, delegate] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(newAmount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("setAllowance", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + //ERC1410 methods + public func balanceOfByPartition(partition: Data, tokenHolder: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOfByPartition", parameters: [partition, tokenHolder] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> [Data] { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("partitionsOf", parameters: [tokenHolder] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferByPartition", parameters: [partition, to, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func operatorTransferByPartition(partition: Data, from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("operatorTransferByPartition", parameters: [partition, originalOwner, to, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func canTransferByPartition(originalOwner: EthereumAddress, to: EthereumAddress, partition: Data, amount: String, data: [UInt8]) throws -> ([UInt8], Data, Data) { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: transactionOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let result = try contract.read("canTransfer", parameters: [originalOwner, to, partition, value, data] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("isOperator", parameters: [user, tokenHolder] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("isOperatorForPartition", parameters: [partition, user, tokenHolder] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("authorizeOperator", parameters: [user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func revokeOperator(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("revokeOperator", parameters: [user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func authorizeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("authorizeOperatorByPartition", parameters: [partition, user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func revokeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("revokeOperatorByPartition", parameters: [partition, user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func issueByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("issueByPartition", parameters: [partition, tokenHolder, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func redeemByPartition(from: EthereumAddress, partition: Data, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("redeemByPartition", parameters: [partition, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func operatorRedeemByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("operatorRedeemByPartition", parameters: [partition, tokenHolder, value, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } +} + +extension ERC1410: IERC777 { + public func canImplementInterfaceForAddress(interfaceHash: Data, addr: EthereumAddress) throws -> Data { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("canImplementInterfaceForAddress", parameters: [interfaceHash, addr] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> EthereumAddress { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("getInterfaceImplementer", parameters: [addr, interfaceHash] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + + let tx = contract.write("setInterfaceImplementer", parameters: [addr, interfaceHash, implementer] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setManager(from: EthereumAddress, addr: EthereumAddress, newManager: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + + let tx = contract.write("setManager", parameters: [addr, newManager] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func interfaceHash(interfaceName: String) throws -> Data { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("interfaceHash", parameters: [interfaceName] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + + let tx = contract.write("updateERC165Cache", parameters: [contract, interfaceId] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func supportsInterface(interfaceID: String) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + transactionOptions.gasLimit = .manual(30000) + let result = try contract.read("supportsInterface", parameters: [interfaceID] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.callOnBlock = .latest + + let tx = contract.write("authorizeOperator", parameters: [user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func revoke(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.callOnBlock = .latest + + let tx = contract.write("revokeOperator", parameters: [user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func isOperatorFor(operator user: EthereumAddress, tokenHolder: EthereumAddress) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("isOperatorFor", parameters: [user, tokenHolder] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("send", parameters: [to, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func operatorSend(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("operatorSend", parameters: [originalOwner, to, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func burn(from: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("burn", parameters: [value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func operatorBurn(from: EthereumAddress, amount: String, originalOwner: EthereumAddress, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("burn", parameters: [originalOwner, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func getGranularity() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("granularity", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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() throws -> [EthereumAddress] { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("defaultOperators", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1594/Web3+ERC1594.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1594/Web3+ERC1594.swift new file mode 100644 index 000000000..7e8b94616 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1594/Web3+ERC1594.swift @@ -0,0 +1,409 @@ +// +// Web3+ERC1594.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 19/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress +import PromiseKit + +//Core Security Token Standard +protocol IERC1594: IERC20 { + + // Transfers + func transferWithData(from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + func transferFromWithData(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + + // Token Issuance + func isIssuable() throws -> Bool + func issue(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + + // Token Redemption + func redeem(from: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + func redeemFrom(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + + // Transfer Validity + func canTransfer(to: EthereumAddress, amount: String, data: [UInt8]) throws -> ([UInt8], Data) + func canTransferFrom(originalOwner: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) throws -> ([UInt8], Data) + +} + +public class ERC1594: IERC1594 { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc1594ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 255 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("allowance", parameters: [originalOwner, delegate] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(newAmount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("setAllowance", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + //ERC1594 + public func transferWithData(from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferWithData", parameters: [to, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFromWithData(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFromWithData", parameters: [originalOwner, to, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func isIssuable() throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("isIssuable", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("issue", parameters: [tokenHolder, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func redeem(from: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("redeem", parameters: [value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func redeemFrom(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("redeemFrom", parameters: [tokenHolder, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func canTransfer(to: EthereumAddress, amount: String, data: [UInt8]) throws -> ([UInt8], Data) { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: transactionOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let result = try contract.read("canTransfer", parameters: [to, value, data] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> ([UInt8], Data) { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: transactionOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let result = try contract.read("canTransfer", parameters: [originalOwner, to, value, data] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } +} + + diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1633/Web3+ERC1633.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1633/Web3+ERC1633.swift new file mode 100644 index 000000000..13ccdaf48 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1633/Web3+ERC1633.swift @@ -0,0 +1,254 @@ +// +// Web3+ERC1634.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 20/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress +import PromiseKit + +///Re-Fungible Token Standard (RFT) +protocol IERC1633: IERC20, IERC165 { + + func parentToken() throws -> EthereumAddress + func parentTokenId() throws -> BigUInt + +} + +public class ERC1633: IERC1633 { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc1633ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 255 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("allowance", parameters: [originalOwner, delegate] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(newAmount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("setAllowance", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func parentToken() throws -> EthereumAddress { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("parentToken", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("parentTokenId", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + transactionOptions.gasLimit = .manual(30000) + let result = try contract.read("supportsInterface", parameters: [interfaceID] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1643/Web3+ERC1643.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1643/Web3+ERC1643.swift new file mode 100644 index 000000000..e18bbead8 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1643/Web3+ERC1643.swift @@ -0,0 +1,267 @@ +// +// Web3+ERC1643.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 19/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress +import PromiseKit + +//Document Management Standard +protocol IERC1643: IERC20 { + + // Document Management + func getDocument(name: Data) throws -> (String, Data) + func setDocument(from: EthereumAddress, name: Data, uri: String, documentHash: Data) throws -> WriteTransaction + func removeDocument(from: EthereumAddress, name: Data) throws -> WriteTransaction + func getAllDocuments() throws -> [Data] + +} + +public class ERC1643: IERC1643 { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc1643ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 255 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("allowance", parameters: [originalOwner, delegate] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(newAmount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("setAllowance", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + //ERC1643 methods + public func getDocument(name: Data) throws -> (String, Data) { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("getDocument", parameters: [name] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("setDocument", parameters: [name, uri, documentHash] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func removeDocument(from: EthereumAddress, name: Data) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("removeDocument", parameters: [name] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func getAllDocuments() throws -> [Data] { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("getAllDocuments", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1644/Web3+ERC1644.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1644/Web3+ERC1644.swift new file mode 100644 index 000000000..fffbe6609 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC1644/Web3+ERC1644.swift @@ -0,0 +1,283 @@ +// +// Web3+ERC1644.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 19/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress +import PromiseKit + +//Controller Token Operation Standard +protocol IERC1644: IERC20 { + + // Controller Operation + func isControllable() throws -> Bool + func controllerTransfer(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction + func controllerRedeem(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction + +} + +public class ERC1644: IERC1644 { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc1644ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 255 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("allowance", parameters: [originalOwner, delegate] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(newAmount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("setAllowance", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + //ERC1644 + public func isControllable() throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("isControllable", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("controllerTransfer", parameters: [originalOwner, to, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func controllerRedeem(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("controllerRedeem", parameters: [tokenHolder, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC165/Web3+ERC165.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC165/Web3+ERC165.swift new file mode 100644 index 000000000..5abd3e955 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC165/Web3+ERC165.swift @@ -0,0 +1,16 @@ +// +// Web3+ERC165.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 15/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// + +import Foundation + +//Standard Interface Detection +protocol IERC165 { + + func supportsInterface(interfaceID: String) throws -> Bool + +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC20/Web3+ERC20.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC20/Web3+ERC20.swift new file mode 100644 index 000000000..f3000f57b --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC20/Web3+ERC20.swift @@ -0,0 +1,228 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress +import PromiseKit + +//Token Standard +protocol IERC20 { + func getBalance(account: EthereumAddress) throws -> BigUInt + func getAllowance(originalOwner: EthereumAddress, delegate: EthereumAddress) throws -> BigUInt + func transfer(from: EthereumAddress, to: EthereumAddress, amount: String) throws -> WriteTransaction + func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction + func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction + func approve(from: EthereumAddress, spender: EthereumAddress, amount: String) throws -> WriteTransaction + func totalSupply() throws -> BigUInt +} + +// This namespace contains functions to work with ERC20 tokens. +// variables are lazyly evaluated or global token information (name, ticker, total supply) +// can be imperatively read and saved +public class ERC20: IERC20 { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(Web3.Utils.erc20ABI, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 255 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("allowance", parameters: [originalOwner, delegate] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(newAmount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("setAllowance", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func approve(from: EthereumAddress, spender: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC721/Web3+ERC721.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC721/Web3+ERC721.swift new file mode 100644 index 000000000..08dba2cd5 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC721/Web3+ERC721.swift @@ -0,0 +1,280 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +//import EthereumAddress + +//Non-Fungible Token Standard +protocol IERC721: IERC165 { + + func getBalance(account: EthereumAddress) throws -> BigUInt + + func getOwner(tokenId: BigUInt) throws -> EthereumAddress + + func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction + + func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction + + func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt, data: [UInt8]) throws -> WriteTransaction + + func transfer(from: EthereumAddress, to: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction + + func approve(from: EthereumAddress, approved: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction + + func setApprovalForAll(from: EthereumAddress, operator user: EthereumAddress, approved: Bool) throws -> WriteTransaction + + func getApproved(tokenId: BigUInt) throws -> EthereumAddress + + func isApprovedForAll(owner: EthereumAddress, operator user: EthereumAddress) throws -> Bool +} + +protocol IERC721Metadata { + + func name() throws -> String + + func symbol() throws -> String + + func tokenURI(tokenId: BigUInt) throws -> String + +} + +protocol IERC721Enumerable { + + func totalSupply() throws -> BigUInt + + func tokenByIndex(index: BigUInt) throws -> BigUInt + + func tokenOfOwnerByIndex(owner: EthereumAddress, index: BigUInt) throws -> BigUInt +} + +// This namespace contains functions to work with ERC721 tokens. +// can be imperatively read and saved +public class ERC721: IERC721 { + + private var _tokenId: BigUInt? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(Web3.Utils.erc721ABI, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.transactionOptions = mergedOptions + } + + public var tokenId: BigUInt { + self.readProperties() + if self._tokenId != nil { + return self._tokenId! + } + return 0 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + + guard let tokenIdPromise = contract.read("tokenId", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [tokenIdPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let tokenIdResult) = resolvedPromises[0] else {return} + guard let tokenId = tokenIdResult["0"] as? BigUInt else {return} + self._tokenId = tokenId + + self._hasReadProperties = true + }.wait() + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 getOwner(tokenId: BigUInt) throws -> EthereumAddress { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("ownerOf", parameters: [tokenId] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 getApproved(tokenId: BigUInt) throws -> EthereumAddress { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("getApproved", parameters: [tokenId] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 transfer(from: EthereumAddress, to: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("transfer", parameters: [to, tokenId] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, tokenId] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("safeTransferFrom", parameters: [originalOwner, to, tokenId] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("safeTransferFrom", parameters: [originalOwner, to, tokenId, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func approve(from: EthereumAddress, approved: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("approve", parameters: [approved, tokenId] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setApprovalForAll(from: EthereumAddress, operator user: EthereumAddress, approved: Bool) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("setApprovalForAll", parameters: [user, approved] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func isApprovedForAll(owner: EthereumAddress, operator user: EthereumAddress) throws -> Bool { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.callOnBlock = .latest + let result = try contract.read("isApprovedForAll", parameters: [owner, user] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + transactionOptions.gasLimit = .manual(30000) + let result = try contract.read("supportsInterface", parameters: [interfaceID] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + +} + +extension ERC721: IERC721Enumerable { + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 tokenByIndex(index: BigUInt) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("tokenByIndex", parameters: [index] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 tokenOfOwnerByIndex(owner: EthereumAddress, index: BigUInt) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("tokenOfOwnerByIndex", parameters: [owner, index] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + +} + +extension ERC721: IERC721Metadata { + + public func name() throws -> String { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("name", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + guard let res = result["0"] as? String else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + return res + } + + public func symbol() throws -> String { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("symbol", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + guard let res = result["0"] as? String else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + return res + } + + public func tokenURI(tokenId: BigUInt) throws -> String { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("tokenId", parameters: [tokenId] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + guard let res = result["0"] as? String else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + return res + } + +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC721x/Web3+ERC721x.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC721x/Web3+ERC721x.swift new file mode 100644 index 000000000..94e9f5713 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC721x/Web3+ERC721x.swift @@ -0,0 +1,332 @@ +// +// Web3+ERC721x.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 20/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +//import EthereumAddress + +///A Smarter Token for the Future of Crypto Collectibles +///ERC721x is an extension of ERC721 that adds support for multi-fungible tokens and batch transfers, while being fully backward-compatible. + +protocol IERC721x: IERC721, IERC721Metadata, IERC721Enumerable { + func implementsERC721X() throws -> Bool + func getOwner(tokenId: BigUInt) throws -> EthereumAddress + func getBalance(account: EthereumAddress) throws -> BigUInt + func getBalance(account: EthereumAddress, tokenId: BigUInt) throws -> BigUInt + + func tokensOwned(account: EthereumAddress) throws -> ([BigUInt], [BigUInt]) + + func transfer(from: EthereumAddress, to: EthereumAddress, tokenId: BigUInt, quantity: BigUInt) throws -> WriteTransaction + func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt, quantity: BigUInt) throws -> WriteTransaction + + // Fungible Safe Transfer From + func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt, amount: BigUInt) throws -> WriteTransaction + func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt, amount: BigUInt, data: [UInt8]) throws -> WriteTransaction + + // Batch Safe Transfer From + func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenIds: [BigUInt], amounts: [BigUInt], data: [UInt8]) throws -> WriteTransaction + + func name() throws -> String + func symbol() throws -> String +} + +public class ERC721x: IERC721x { + + private var _tokenId: BigUInt? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc721xABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var tokenId: BigUInt { + self.readProperties() + if self._tokenId != nil { + return self._tokenId! + } + return 0 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + + guard let tokenIdPromise = contract.read("tokenId", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [tokenIdPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let tokenIdResult) = resolvedPromises[0] else {return} + guard let tokenId = tokenIdResult["0"] as? BigUInt else {return} + self._tokenId = tokenId + + self._hasReadProperties = true + }.wait() + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 getOwner(tokenId: BigUInt) throws -> EthereumAddress { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("ownerOf", parameters: [tokenId] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 getApproved(tokenId: BigUInt) throws -> EthereumAddress { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("getApproved", parameters: [tokenId] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 transfer(from: EthereumAddress, to: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("transfer", parameters: [to, tokenId] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, tokenId] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("safeTransferFrom", parameters: [originalOwner, to, tokenId] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("safeTransferFrom", parameters: [originalOwner, to, tokenId, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func approve(from: EthereumAddress, approved: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("approve", parameters: [approved, tokenId] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setApprovalForAll(from: EthereumAddress, operator user: EthereumAddress, approved: Bool) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("setApprovalForAll", parameters: [user, approved] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func isApprovedForAll(owner: EthereumAddress, operator user: EthereumAddress) throws -> Bool { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.callOnBlock = .latest + let result = try contract.read("isApprovedForAll", parameters: [owner, user] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + transactionOptions.gasLimit = .manual(30000) + let result = try contract.read("supportsInterface", parameters: [interfaceID] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 tokenByIndex(index: BigUInt) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("tokenByIndex", parameters: [index] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 tokenOfOwnerByIndex(owner: EthereumAddress, index: BigUInt) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("tokenOfOwnerByIndex", parameters: [owner, index] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 name() throws -> String { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("name", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + guard let res = result["0"] as? String else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + return res + } + + public func symbol() throws -> String { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("symbol", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + guard let res = result["0"] as? String else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + return res + } + + public func tokenURI(tokenId: BigUInt) throws -> String { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("tokenId", parameters: [tokenId] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + guard let res = result["0"] as? String else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + return res + } + + func implementsERC721X() throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("implementsERC721X", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + + func getBalance(account: EthereumAddress, tokenId: BigUInt) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account, tokenId] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + + func tokensOwned(account: EthereumAddress) throws -> ([BigUInt], [BigUInt]) { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("tokensOwned", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + guard let res = result["0"] as? ([BigUInt], [BigUInt]) else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + return res + } + + func transfer(from: EthereumAddress, to: EthereumAddress, tokenId: BigUInt, quantity: BigUInt) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("transfer", parameters: [to, tokenId, quantity] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt, quantity: BigUInt) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, tokenId, quantity] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt, amount: BigUInt) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("safeTransferFrom", parameters: [originalOwner, to, tokenId, amount] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt, amount: BigUInt, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("safeTransferFrom", parameters: [originalOwner, to, tokenId, amount, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenIds: [BigUInt], amounts: [BigUInt], data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("safeTransferFrom", parameters: [originalOwner, to, tokenIds, amounts, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC777/Web3+ERC777.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC777/Web3+ERC777.swift new file mode 100644 index 000000000..775ff9c15 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC777/Web3+ERC777.swift @@ -0,0 +1,445 @@ +// +// Web3+ERC777.swift +// web3swift +// +// Created by Anton Grigorev on 07/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// +import Foundation +import BigInt +import PromiseKit +//import EthereumAddress + +//A New Advanced Token Standard +protocol IERC777: IERC20, IERC820 { + func getDefaultOperators() throws -> [EthereumAddress] + func getGranularity() throws -> BigUInt + func getBalance(account: EthereumAddress) throws -> BigUInt + func getAllowance(originalOwner: EthereumAddress, delegate: EthereumAddress) throws -> BigUInt + func transfer(from: EthereumAddress, to: EthereumAddress, amount: String) throws -> WriteTransaction + func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction + func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction + func authorize(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction + func revoke(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction + func isOperatorFor(operator user: EthereumAddress, tokenHolder: EthereumAddress) throws -> Bool + func send(from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + func operatorSend(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction + func burn(from: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + func operatorBurn(from: EthereumAddress, amount: String, originalOwner: EthereumAddress, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction +} + +// This namespace contains functions to work with ERC777 tokens. +// can be imperatively read and saved +public class ERC777: IERC777 { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc777ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + /// Must be 18! + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 18 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + public func getGranularity() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("granularity", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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() throws -> [EthereumAddress] { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("defaultOperators", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("allowance", parameters: [originalOwner, delegate] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(newAmount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("setAllowance", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + + /// ERC777 methods + public func authorize(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + let tx = contract.write("authorizeOperator", parameters: [user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func revoke(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + let tx = contract.write("revokeOperator", parameters: [user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func isOperatorFor(operator user: EthereumAddress, tokenHolder: EthereumAddress) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("isOperatorFor", parameters: [user, tokenHolder] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("send", parameters: [to, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func operatorSend(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("operatorSend", parameters: [originalOwner, to, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func burn(from: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("burn", parameters: [value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func operatorBurn(from: EthereumAddress, amount: String, originalOwner: EthereumAddress, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("burn", parameters: [originalOwner, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func canImplementInterfaceForAddress(interfaceHash: Data, addr: EthereumAddress) throws -> Data { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("canImplementInterfaceForAddress", parameters: [interfaceHash, addr] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> EthereumAddress { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("getInterfaceImplementer", parameters: [addr, interfaceHash] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("setInterfaceImplementer", parameters: [addr, interfaceHash, implementer] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setManager(from: EthereumAddress, addr: EthereumAddress, newManager: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("setManager", parameters: [addr, newManager] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func interfaceHash(interfaceName: String) throws -> Data { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("interfaceHash", parameters: [interfaceName] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("updateERC165Cache", parameters: [contract, interfaceId] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func approve(from: EthereumAddress, spender: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func supportsInterface(interfaceID: String) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + transactionOptions.gasLimit = .manual(30000) + let result = try contract.read("supportsInterface", parameters: [interfaceID] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC820/Web3+ERC820.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC820/Web3+ERC820.swift new file mode 100644 index 000000000..4e805e9a2 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC820/Web3+ERC820.swift @@ -0,0 +1,20 @@ +// +// Web3+ERC820.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 15/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// + +import Foundation +//import EthereumAddress + +//Pseudo-introspection using a registry contract +protocol IERC820: IERC165 { + func canImplementInterfaceForAddress(interfaceHash: Data, addr: EthereumAddress) throws -> Data + func getInterfaceImplementer(addr: EthereumAddress, interfaceHash: Data) throws -> EthereumAddress + func setInterfaceImplementer(from: EthereumAddress, addr: EthereumAddress, interfaceHash: Data, implementer: EthereumAddress) throws -> WriteTransaction + func setManager(from: EthereumAddress, addr: EthereumAddress, newManager: EthereumAddress) throws -> WriteTransaction + func interfaceHash(interfaceName: String) throws -> Data + func updateERC165Cache(from: EthereumAddress, contract: EthereumAddress, interfaceId: [UInt8]) throws -> WriteTransaction +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC888/Web3+ERC888.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC888/Web3+ERC888.swift new file mode 100644 index 000000000..ce98f9b7c --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ERC888/Web3+ERC888.swift @@ -0,0 +1,138 @@ +// +// Web3+ERC888.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 15/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress +import PromiseKit + +//MultiDimensional Token Standard +protocol IERC888 { + func getBalance(account: EthereumAddress) throws -> BigUInt + func transfer(from: EthereumAddress, to: EthereumAddress, amount: String) throws -> WriteTransaction +} + +public class ERC888: IERC888 { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc888ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 255 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + +} + diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ST20/Web3+ST20.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ST20/Web3+ST20.swift new file mode 100644 index 000000000..cc6b77344 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ST20/Web3+ST20.swift @@ -0,0 +1,314 @@ +// +// Web3+ST20.swift +// web3swift +// +// Created by Anton on 05/03/2019. +// Copyright © 2019 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +//import EthereumAddress + +//NPolymath Token Standard +protocol IST20: IERC20 { + // off-chain hash + func tokenDetails() throws -> [UInt32] + + //transfer, transferFrom must respect the result of verifyTransfer + func verifyTransfer(from: EthereumAddress, originalOwner: EthereumAddress, to: EthereumAddress, amount: String) throws -> WriteTransaction + + //used to create tokens + func mint(from: EthereumAddress, investor: EthereumAddress, amount: String) throws -> WriteTransaction + + //Burn function used to burn the securityToken + func burn(from: EthereumAddress, amount: String) throws -> WriteTransaction +} + +// This namespace contains functions to work with ST-20 tokens. +// can be imperatively read and saved +public class ST20: IST20 { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.st20ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + /// Must be 18! + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 18 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + func tokenDetails() throws -> [UInt32] { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("tokenDetails", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("verifyTransfer", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func mint(from: EthereumAddress, investor: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("mint", parameters: [investor, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func burn(from: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("burn", parameters: [value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("allowance", parameters: [originalOwner, delegate] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(newAmount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("setAllowance", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func approve(from: EthereumAddress, spender: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ST20/Web3+SecurityToken.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ST20/Web3+SecurityToken.swift new file mode 100644 index 000000000..2412616d4 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Tokens/ST20/Web3+SecurityToken.swift @@ -0,0 +1,473 @@ +// +// Web3+SecurityToken.swift +// web3swift +// +// Created by Anton on 05/03/2019. +// Copyright © 2019 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +//import EthereumAddress + +//The Ownable contract has an owner address, and provides basic authorization control functions, this simplifies the implementation of "user permissions". +protocol IOwnable { + //Allows the current owner to relinquish control of the contract. + func renounceOwnership(from: EthereumAddress) throws -> WriteTransaction + + //Allows the current owner to transfer control of the contract to a newOwner. + func transferOwnership(from: EthereumAddress, newOwner: EthereumAddress) throws -> WriteTransaction +} + +//Security token interface +protocol ISecurityToken: IST20, IOwnable { + // Value of current checkpoint + func currentCheckpointId() throws -> BigUInt + + func getGranularity() throws -> BigUInt + + // Total number of non-zero token holders + func investorCount() throws -> BigUInt + + // List of token holders + func investors() throws -> [EthereumAddress] + + // Permissions this to a Permission module, which has a key of 1 + // If no Permission return false - note that IModule withPerm will allow ST owner all permissions anyway + // this allows individual modules to override this logic if needed (to not allow ST owner all permissions) + func checkPermission(delegate: EthereumAddress, module: EthereumAddress, perm: [UInt32]) throws -> Bool + + //returns module list for a module type + //params: + //- moduleType is which type of module we are trying to remove + //- moduleIndex is the index of the module within the chosen type + func getModule(moduleType: UInt8, moduleIndex: UInt8) throws -> ([UInt32], EthereumAddress) + + //returns module list for a module name - will return first match + //params: + //- moduleType is which type of module we are trying to remove + //- name is the name of the module within the chosen type + func getModuleByName(moduleType: UInt8, name: [UInt32]) throws -> ([UInt32], EthereumAddress) + + //Queries totalSupply as of a defined checkpoint + func totalSupplyAt(checkpointId: BigUInt) throws -> BigUInt + + //Queries balances as of a defined checkpoint + func balanceOfAt(investor: EthereumAddress, checkpointId: BigUInt) throws -> BigUInt + + //Creates a checkpoint that can be used to query historical balances / totalSuppy + func createCheckpoint(from: EthereumAddress) throws -> WriteTransaction + + //gets length of investors array + func getInvestorsLength() throws -> BigUInt +} + +public class SecurityToken: ISecurityToken { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.st20ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + /// Must be 18! + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 18 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + func tokenDetails() throws -> [UInt32] { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("tokenDetails", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("verifyTransfer", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func mint(from: EthereumAddress, investor: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("mint", parameters: [investor, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func burn(from: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("burn", parameters: [value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("allowance", parameters: [originalOwner, delegate] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(newAmount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("setAllowance", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func approve(from: EthereumAddress, spender: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 renounceOwnership(from: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + let tx = contract.write("renounceOwnership", parameters: [AnyObject](), transactionOptions: basicOptions)! + return tx + } + + public func transferOwnership(from: EthereumAddress, newOwner: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + let tx = contract.write("transferOwnership", parameters: [newOwner] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func currentCheckpointId() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("currentCheckpointId", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 getGranularity() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("granularity", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 investorCount() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("investorCount", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 investors() throws -> [EthereumAddress] { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("investors", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 checkPermission(delegate: EthereumAddress, module: EthereumAddress, perm: [UInt32]) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("checkPermission", parameters: [delegate, module, perm] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 getModule(moduleType: UInt8, moduleIndex: UInt8) throws -> ([UInt32], EthereumAddress) { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("getModule", parameters: [moduleType, moduleIndex] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + guard let moduleList = result["0"] as? [UInt32] else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + guard let moduleAddress = result["1"] as? EthereumAddress else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + return (moduleList, moduleAddress) + } + + public func getModuleByName(moduleType: UInt8, name: [UInt32]) throws -> ([UInt32], EthereumAddress) { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("getModuleByName", parameters: [moduleType, name] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + guard let moduleList = result["0"] as? [UInt32] else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + guard let moduleAddress = result["1"] as? EthereumAddress else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + return (moduleList, moduleAddress) + } + + public func totalSupplyAt(checkpointId: BigUInt) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupplyAt", parameters: [checkpointId] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 balanceOfAt(investor: EthereumAddress, checkpointId: BigUInt) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOfAt", parameters: [investor, checkpointId] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 createCheckpoint(from: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + let tx = contract.write("createCheckpoint", parameters: [AnyObject](), transactionOptions: basicOptions)! + return tx + } + + public func getInvestorsLength() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("getInvestorsLength", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Transaction/BloomFilter.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Transaction/BloomFilter.swift new file mode 100755 index 000000000..4daded407 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Transaction/BloomFilter.swift @@ -0,0 +1,110 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import CryptoSwift +//import EthereumAddress + +public struct EthereumBloomFilter{ + public var bytes = Data(repeatElement(UInt8(0), count: 256)) + public init?(_ biguint: BigUInt) { + guard let data = biguint.serialize().setLengthLeft(256) else {return nil} + bytes = data + } + public init() {} + public init(_ data: Data) { + let padding = Data(repeatElement(UInt8(0), count: 256 - data.count)) + bytes = padding + data + } + public func asBigUInt() -> BigUInt { + return BigUInt(self.bytes) + } +} + +extension EthereumBloomFilter { + + static func bloom9(_ biguint: BigUInt) -> BigUInt { + return EthereumBloomFilter.bloom9(biguint.serialize()) + } + + static func bloom9(_ data: Data) -> BigUInt { + let b = data.sha3(.keccak256) + var r = BigUInt(0) + let mask = BigUInt(2047) + for i in stride(from: 0, to: 6, by: 2) { + var t = BigUInt(1) + let num = (BigUInt(b[i+1]) + (BigUInt(b[i]) << 8)) & mask +// b = num.serialize().setLengthLeft(8)! + t = t << num + r = r | t + } + return r + } + + static func logsToBloom(_ logs: [EventLog]) -> BigUInt { + var bin = BigUInt(0) + for log in logs { + bin = bin | bloom9(log.address.addressData) + for topic in log.topics { + bin = bin | bloom9(topic) + } + } + return bin + } + + public static func createBloom(_ receipts: [TransactionReceipt]) -> EthereumBloomFilter? { + var bin = BigUInt(0) + for receipt in receipts { + bin = bin | EthereumBloomFilter.logsToBloom(receipt.logs) + } + return EthereumBloomFilter(bin) + } + + public func test(topic: Data) -> Bool { + let bin = self.asBigUInt() + let comparison = EthereumBloomFilter.bloom9(topic) + return bin & comparison == comparison + } + + public func test(topic: BigUInt) -> Bool { + return self.test(topic: topic.serialize()) + } + + public static func bloomLookup(_ bloom: EthereumBloomFilter, topic:Data) -> Bool { + let bin = bloom.asBigUInt() + let comparison = bloom9(topic) + return bin & comparison == comparison + } + + public static func bloomLookup(_ bloom: EthereumBloomFilter, topic:BigUInt) -> Bool { + return EthereumBloomFilter.bloomLookup(bloom, topic: topic.serialize()) + } + + public mutating func add(_ biguint: BigUInt) { + var bin = BigUInt(self.bytes) + bin = bin | EthereumBloomFilter.bloom9(biguint) + setBytes(bin.serialize()) + } + + public mutating func add(_ data: Data) { + var bin = BigUInt(self.bytes) + bin = bin | EthereumBloomFilter.bloom9(data) + setBytes(bin.serialize()) + } + + public func lookup (_ topic: Data) -> Bool { + return EthereumBloomFilter.bloomLookup(self, topic: topic) + } + + mutating func setBytes(_ data: Data) { + if (self.bytes.count < data.count) { + fatalError("bloom bytes are too big") + } + self.bytes = self.bytes[0 ..< data.count] + data + } + +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Transaction/EthereumTransaction.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Transaction/EthereumTransaction.swift new file mode 100755 index 000000000..d799d3ab7 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Transaction/EthereumTransaction.swift @@ -0,0 +1,403 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import SwiftRLP +//import secp256k1_swift +//import EthereumAddress + +public struct EthereumTransaction: CustomStringConvertible { + public var nonce: BigUInt + public var gasPrice: BigUInt = BigUInt(0) + public var gasLimit: BigUInt = BigUInt(0) + // The destination address of the message, left undefined for a contract-creation transaction. + public var to: EthereumAddress + // (optional) The value transferred for the transaction in wei, also the endowment if it’s a contract-creation transaction. + // TODO - split EthereumTransaction to two classes: with optional and required value property, depends on type of transaction + public var value: BigUInt? + public var data: Data + public var v: BigUInt = BigUInt(1) + public var r: BigUInt = BigUInt(0) + public var s: BigUInt = BigUInt(0) + var chainID: BigUInt? = nil + + public var inferedChainID: BigUInt? { + get{ + if (self.r == BigUInt(0) && self.s == BigUInt(0)) { + return self.v + } else if (self.v == BigUInt(27) || self.v == BigUInt(28)) { + return nil + } else { + return ((self.v - BigUInt(1)) / BigUInt(2)) - BigUInt(17) + } + } + } + + public var intrinsicChainID: BigUInt? { + get{ + return self.chainID + } + } + + public mutating func UNSAFE_setChainID(_ chainID: BigUInt?) { + self.chainID = chainID + } + + public var hash: Data? { + var encoded: Data + let inferedChainID = self.inferedChainID + if inferedChainID != nil { + guard let enc = self.self.encode(forSignature: false, chainID: inferedChainID) else {return nil} + encoded = enc + } else { + guard let enc = self.self.encode(forSignature: false, chainID: self.chainID) else {return nil} + encoded = enc + } + let hash = encoded.sha3(.keccak256) + return hash + } + + public init(gasPrice: BigUInt, gasLimit: BigUInt, to: EthereumAddress, value: BigUInt, data: Data) { + self.nonce = BigUInt(0) + self.gasPrice = gasPrice + self.gasLimit = gasLimit + self.value = value + self.data = data + self.to = to + } + + + public init (nonce: BigUInt, gasPrice: BigUInt, gasLimit: BigUInt, to: EthereumAddress, value: BigUInt, data: Data, v: BigUInt, r: BigUInt, s: BigUInt) { + self.nonce = nonce + self.gasPrice = gasPrice + self.gasLimit = gasLimit + self.to = to + self.value = value + self.data = data + self.v = v + self.r = r + self.s = s + } + + public var description: String { + get { + var toReturn = "" + toReturn = toReturn + "Transaction" + "\n" + toReturn = toReturn + "Nonce: " + String(self.nonce) + "\n" + toReturn = toReturn + "Gas price: " + String(self.gasPrice) + "\n" + toReturn = toReturn + "Gas limit: " + String(describing: self.gasLimit) + "\n" + toReturn = toReturn + "To: " + self.to.address + "\n" + toReturn = toReturn + "Value: " + String(self.value ?? "nil") + "\n" + toReturn = toReturn + "Data: " + self.data.toHexString().addHexPrefix().lowercased() + "\n" + toReturn = toReturn + "v: " + String(self.v) + "\n" + toReturn = toReturn + "r: " + String(self.r) + "\n" + toReturn = toReturn + "s: " + String(self.s) + "\n" + toReturn = toReturn + "Intrinsic chainID: " + String(describing:self.chainID) + "\n" + toReturn = toReturn + "Infered chainID: " + String(describing:self.inferedChainID) + "\n" + toReturn = toReturn + "sender: " + String(describing: self.sender?.address) + "\n" + toReturn = toReturn + "hash: " + String(describing: self.hash?.toHexString().addHexPrefix()) + "\n" + return toReturn + } + + } + public var sender: EthereumAddress? { + get { + guard let publicKey = self.recoverPublicKey() else {return nil} + return Web3.Utils.publicToAddress(publicKey) + } + } + + public func recoverPublicKey() -> Data? { + if (self.r == BigUInt(0) && self.s == BigUInt(0)) { + return nil + } + var normalizedV:BigUInt = BigUInt(27) + let inferedChainID = self.inferedChainID + var d = BigUInt(0) + if self.v >= 35 && self.v <= 38 { + d = BigUInt(35) + } else if self.v >= 31 && self.v <= 34 { + d = BigUInt(31) + } else if self.v >= 27 && self.v <= 30 { + d = BigUInt(27) + } + if (self.chainID != nil && self.chainID != BigUInt(0)) { + normalizedV = self.v - d - self.chainID! - self.chainID! + } else if (inferedChainID != nil) { + normalizedV = self.v - d - inferedChainID! - inferedChainID! + } else { + normalizedV = self.v - d + } + guard let vData = normalizedV.serialize().setLengthLeft(1) else {return nil} + guard let rData = r.serialize().setLengthLeft(32) else {return nil} + guard let sData = s.serialize().setLengthLeft(32) else {return nil} + guard let signatureData = SECP256K1.marshalSignature(v: vData, r: rData, s: sData) else {return nil} + var hash: Data + if inferedChainID != nil { + guard let h = self.hashForSignature(chainID: inferedChainID) else {return nil} + hash = h + } else { + guard let h = self.hashForSignature(chainID: self.chainID) else {return nil} + hash = h + } + guard let publicKey = SECP256K1.recoverPublicKey(hash: hash, signature: signatureData) else {return nil} + return publicKey + } + + public var txhash: String? { + get{ + guard self.sender != nil else {return nil} + guard let hash = self.hash else {return nil} + let txid = hash.toHexString().addHexPrefix().lowercased() + return txid + } + } + + public var txid: String? { + get { + return self.txhash + } + } + + public func encode(forSignature:Bool = false, chainID: BigUInt? = nil) -> Data? { + if (forSignature) { + if chainID != nil { + let fields = [self.nonce, self.gasPrice, self.gasLimit, self.to.addressData, self.value!, self.data, chainID!, BigUInt(0), BigUInt(0)] as [AnyObject] + return RLP.encode(fields) + } + else if self.chainID != nil { + let fields = [self.nonce, self.gasPrice, self.gasLimit, self.to.addressData, self.value!, self.data, self.chainID!, BigUInt(0), BigUInt(0)] as [AnyObject] + return RLP.encode(fields) + } else { + let fields = [self.nonce, self.gasPrice, self.gasLimit, self.to.addressData, self.value!, self.data] as [AnyObject] + return RLP.encode(fields) + } + } else { + let fields = [self.nonce, self.gasPrice, self.gasLimit, self.to.addressData, self.value!, self.data, self.v, self.r, self.s] as [AnyObject] + return RLP.encode(fields) + } + } + + public func encodeAsDictionary(from: EthereumAddress? = nil) -> TransactionParameters? { + var toString: String? = nil + switch self.to.type { + case .normal: + toString = self.to.address.lowercased() + case .contractDeployment: + break + } + var params = TransactionParameters(from: from?.address.lowercased(), + to: toString) + let gasEncoding = self.gasLimit.abiEncode(bits: 256) + params.gas = gasEncoding?.toHexString().addHexPrefix().stripLeadingZeroes() + let gasPriceEncoding = self.gasPrice.abiEncode(bits: 256) + params.gasPrice = gasPriceEncoding?.toHexString().addHexPrefix().stripLeadingZeroes() + let valueEncoding = self.value?.abiEncode(bits: 256) + params.value = valueEncoding?.toHexString().addHexPrefix().stripLeadingZeroes() + if (self.data != Data()) { + params.data = self.data.toHexString().addHexPrefix() + } else { + params.data = "0x" + } + return params + } + + public func hashForSignature(chainID: BigUInt? = nil) -> Data? { + guard let encoded = self.encode(forSignature: true, chainID: chainID) else {return nil} + let hash = encoded.sha3(.keccak256) + return hash + } + + public static func fromRaw(_ raw: Data) -> EthereumTransaction? { + guard let totalItem = RLP.decode(raw) else {return nil} + guard let rlpItem = totalItem[0] else {return nil} + switch rlpItem.count { + case 9?: + guard let nonceData = rlpItem[0]!.data else {return nil} + let nonce = BigUInt(nonceData) + guard let gasPriceData = rlpItem[1]!.data else {return nil} + let gasPrice = BigUInt(gasPriceData) + guard let gasLimitData = rlpItem[2]!.data else {return nil} + let gasLimit = BigUInt(gasLimitData) + var to:EthereumAddress + switch rlpItem[3]!.content { + case .noItem: + to = EthereumAddress.contractDeploymentAddress() + case .data(let addressData): + if addressData.count == 0 { + to = EthereumAddress.contractDeploymentAddress() + } else if addressData.count == 20 { + guard let addr = EthereumAddress(addressData) else {return nil} + to = addr + } else { + return nil + } + case .list(_, _, _): + return nil + } + guard let valueData = rlpItem[4]!.data else {return nil} + let value = BigUInt(valueData) + guard let transactionData = rlpItem[5]!.data else {return nil} + guard let vData = rlpItem[6]!.data else {return nil} + let v = BigUInt(vData) + guard let rData = rlpItem[7]!.data else {return nil} + let r = BigUInt(rData) + guard let sData = rlpItem[8]!.data else {return nil} + let s = BigUInt(sData) + return EthereumTransaction.init(nonce: nonce, gasPrice: gasPrice, gasLimit: gasLimit, to: to, value: value, data: transactionData, v: v, r: r, s: s) + case 6?: + return nil + default: + return nil + } + } + + static func createRequest(method: JSONRPCmethod, transaction: EthereumTransaction, transactionOptions: TransactionOptions?) -> JSONRPCrequest? { + let onBlock = transactionOptions?.callOnBlock?.stringValue + var request = JSONRPCrequest() +// var tx = transaction + request.method = method + let from = transactionOptions?.from + guard var txParams = transaction.encodeAsDictionary(from: from) else {return nil} + if method == .estimateGas || transactionOptions?.gasLimit == nil { + txParams.gas = nil + } + var params = [txParams] as Array + if method.requiredNumOfParameters == 2 && onBlock != nil { + params.append(onBlock as Encodable) + } + let pars = JSONRPCparams(params: params) + request.params = pars + if !request.isValid {return nil} + return request + } + + static func createRawTransaction(transaction: EthereumTransaction) -> JSONRPCrequest? { + guard transaction.sender != nil else {return nil} + guard let encodedData = transaction.encode() else {return nil} + let hex = encodedData.toHexString().addHexPrefix().lowercased() + var request = JSONRPCrequest() + request.method = JSONRPCmethod.sendRawTransaction + let params = [hex] as Array + let pars = JSONRPCparams(params: params) + request.params = pars + if !request.isValid {return nil} + return request + } +} + +public extension EthereumTransaction { + init(to: EthereumAddress, data: Data, options: TransactionOptions) { + let defaults = TransactionOptions.defaultOptions + let merged = defaults.merge(options) + self.nonce = BigUInt(0) + + if let gP = merged.gasPrice { + switch gP { + case .manual(let value): + self.gasPrice = value + default: + self.gasPrice = BigUInt("5000000000") + } + } + + if let gL = merged.gasLimit { + switch gL { + case .manual(let value): + self.gasLimit = value + default: + self.gasLimit = BigUInt(UInt64(21000)) + } + } + + if let value = merged.value { + self.value = value + } + + self.to = to + self.data = data + } + + func mergedWithOptions(_ options: TransactionOptions) -> EthereumTransaction { + var tx = self; + + if let gP = options.gasPrice { + switch gP { + case .manual(let value): + tx.gasPrice = value + default: + tx.gasPrice = BigUInt("5000000000") + } + } + + if let gL = options.gasLimit { + switch gL { + case .manual(let value): + tx.gasLimit = value + case .limited(let value): + tx.gasLimit = value + default: + tx.gasLimit = BigUInt(UInt64(21000)) + } + } + + if options.value != nil { + tx.value = options.value! + } + if options.to != nil { + tx.to = options.to! + } + return tx + } + + static func fromJSON(_ json: [String: Any]) -> EthereumTransaction? { + guard let options = TransactionOptions.fromJSON(json) else {return nil} + guard let toString = json["to"] as? String else {return nil} + var to: EthereumAddress + if toString == "0x" || toString == "0x0" { + to = EthereumAddress.contractDeploymentAddress() + } else { + guard let ethAddr = EthereumAddress(toString) else {return nil} + to = ethAddr + } + // if (!to.isValid) { + // return nil + // } + var dataString = json["data"] as? String + if (dataString == nil) { + dataString = json["input"] as? String + } + guard dataString != nil, let data = Data.fromHex(dataString!) else {return nil} + var transaction = EthereumTransaction(to: to, data: data, options: options) + if let nonceString = json["nonce"] as? String { + guard let nonce = BigUInt(nonceString.stripHexPrefix(), radix: 16) else {return nil} + transaction.nonce = nonce + } + if let vString = json["v"] as? String { + guard let v = BigUInt(vString.stripHexPrefix(), radix: 16) else {return nil} + transaction.v = v + } + if let rString = json["r"] as? String { + guard let r = BigUInt(rString.stripHexPrefix(), radix: 16) else {return nil} + transaction.r = r + } + if let sString = json["s"] as? String { + guard let s = BigUInt(sString.stripHexPrefix(), radix: 16) else {return nil} + transaction.s = s + } + if let valueString = json["value"] as? String { + guard let value = BigUInt(valueString.stripHexPrefix(), radix: 16) else {return nil} + transaction.value = value + } + let inferedChainID = transaction.inferedChainID + if (transaction.inferedChainID != nil && transaction.v >= BigUInt(37)) { + transaction.chainID = inferedChainID + } + return transaction + } + +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Transaction/TransactionSigner.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Transaction/TransactionSigner.swift new file mode 100755 index 000000000..52ab27be9 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Transaction/TransactionSigner.swift @@ -0,0 +1,118 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import secp256k1_swift +//import EthereumAddress + +public enum TransactionSignerError: Error { + case signatureError(String) +} + +public struct Web3Signer { + public static func signTX(transaction:inout EthereumTransaction, keystore: AbstractKeystore, account: EthereumAddress, password: String, useExtraEntropy: Bool = false) throws { + var privateKey = try keystore.UNSAFE_getPrivateKeyData(password: password, account: account) + defer {Data.zero(&privateKey)} + if (transaction.chainID != nil) { + try EIP155Signer.sign(transaction: &transaction, privateKey: privateKey, useExtraEntropy: useExtraEntropy) + } else { + try FallbackSigner.sign(transaction: &transaction, privateKey: privateKey, useExtraEntropy: useExtraEntropy) + } + } + + public static func signPersonalMessage(_ personalMessage: Data, keystore: AbstractKeystore, account: EthereumAddress, password: String, useExtraEntropy: Bool = false) throws -> Data? { + var privateKey = try keystore.UNSAFE_getPrivateKeyData(password: password, account: account) + defer {Data.zero(&privateKey)} + guard let hash = Web3.Utils.hashPersonalMessage(personalMessage) else {return nil} + let (compressedSignature, _) = SECP256K1.signForRecovery(hash: hash, privateKey: privateKey, useExtraEntropy: useExtraEntropy) + return compressedSignature + } + + public struct EIP155Signer { + public static func sign(transaction:inout EthereumTransaction, privateKey: Data, useExtraEntropy: Bool = false) throws { + for _ in 0..<1024 { + let result = self.attemptSignature(transaction: &transaction, privateKey: privateKey, useExtraEntropy: useExtraEntropy) + if (result) { + return + } + } + throw AbstractKeystoreError.invalidAccountError + } + + private static func attemptSignature(transaction:inout EthereumTransaction, privateKey: Data, useExtraEntropy: Bool = false) -> Bool { + guard let chainID = transaction.chainID else {return false} + guard let hash = transaction.hashForSignature(chainID: chainID) else {return false} + let signature = SECP256K1.signForRecovery(hash: hash, privateKey: privateKey, useExtraEntropy: useExtraEntropy) + guard let serializedSignature = signature.serializedSignature else {return false} + guard let unmarshalledSignature = SECP256K1.unmarshalSignature(signatureData: serializedSignature) else { + return false + } + let originalPublicKey = SECP256K1.privateToPublic(privateKey: privateKey) + var d = BigUInt(0) + if unmarshalledSignature.v >= 0 && unmarshalledSignature.v <= 3 { + d = BigUInt(35) + } else if unmarshalledSignature.v >= 27 && unmarshalledSignature.v <= 30 { + d = BigUInt(8) + } else if unmarshalledSignature.v >= 31 && unmarshalledSignature.v <= 34 { + d = BigUInt(4) + } + transaction.v = BigUInt(unmarshalledSignature.v) + d + chainID + chainID + transaction.r = BigUInt(Data(unmarshalledSignature.r)) + transaction.s = BigUInt(Data(unmarshalledSignature.s)) + let recoveredPublicKey = transaction.recoverPublicKey() + if (!(originalPublicKey!.constantTimeComparisonTo(recoveredPublicKey))) { + return false + } + return true + } + } + + public struct FallbackSigner { + public static func sign(transaction:inout EthereumTransaction, privateKey: Data, useExtraEntropy: Bool = false) throws { + for _ in 0..<1024 { + let result = self.attemptSignature(transaction: &transaction, privateKey: privateKey) + if (result) { + return + } + } + throw AbstractKeystoreError.invalidAccountError + } + + private static func attemptSignature(transaction:inout EthereumTransaction, privateKey: Data, useExtraEntropy: Bool = false) -> Bool { + guard let hash = transaction.hashForSignature(chainID: nil) else {return false} + let signature = SECP256K1.signForRecovery(hash: hash, privateKey: privateKey, useExtraEntropy: useExtraEntropy) + guard let serializedSignature = signature.serializedSignature else {return false} + guard let unmarshalledSignature = SECP256K1.unmarshalSignature(signatureData: serializedSignature) else { + return false + } + let originalPublicKey = SECP256K1.privateToPublic(privateKey: privateKey) + transaction.chainID = nil + var d = BigUInt(0) + var a = BigUInt(0) + if unmarshalledSignature.v >= 0 && unmarshalledSignature.v <= 3 { + d = BigUInt(27) + } else if unmarshalledSignature.v >= 31 && unmarshalledSignature.v <= 34 { + a = BigUInt(4) + } else if unmarshalledSignature.v >= 35 && unmarshalledSignature.v <= 38 { + a = BigUInt(8) + } + transaction.v = BigUInt(unmarshalledSignature.v) + d - a + transaction.r = BigUInt(Data(unmarshalledSignature.r)) + transaction.s = BigUInt(Data(unmarshalledSignature.s)) + let recoveredPublicKey = transaction.recoverPublicKey() + if (!(originalPublicKey!.constantTimeComparisonTo(recoveredPublicKey))) { + return false + } + return true + } + } + +} + + + + diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/EIP/EIP67Code.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/EIP/EIP67Code.swift new file mode 100755 index 000000000..39ad909d8 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/EIP/EIP67Code.swift @@ -0,0 +1,138 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import CoreImage +import BigInt +//import EthereumAddress +//import EthereumABI + +extension Web3 { + + public struct EIP67Code { + public var address: EthereumAddress + public var gasLimit: BigUInt? + public var amount: BigUInt? + public var data: DataType? + + public enum DataType { + case data(Data) + case function(Function) + } + public struct Function { + public var method: String + public var parameters: [(ABI.Element.ParameterType, AnyObject)] + + public func toString() -> String? { + 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 { + return el.0.abiRepresentation + " " + String(number, radix: 10) + } else if let number = el.1 as? BigInt { + return el.0.abiRepresentation + " " + String(number, radix: 10) + } else if let data = el.1 as? Data { + return el.0.abiRepresentation + " " + data.toHexString().addHexPrefix() + } + return "" + }).joined(separator: ", ") + ")" + return encoding + } + } + + public init (address : EthereumAddress) { + self.address = address + } + + public init? (address : String) { + guard let addr = EthereumAddress(address) else {return nil} + self.address = addr + } + + public func toString() -> String { + var urlComponents = URLComponents() + let mainPart = "ethereum:"+self.address.address.lowercased() + var queryItems = [URLQueryItem]() + if let amount = self.amount { + queryItems.append(URLQueryItem(name: "value", value: String(amount, radix: 10))) + } + if let gasLimit = self.gasLimit { + queryItems.append(URLQueryItem(name: "gas", value: String(gasLimit, radix: 10))) + } + if let data = self.data { + switch data { + case .data(let d): + queryItems.append(URLQueryItem(name: "data", value: d.toHexString().addHexPrefix())) + case .function(let f): + if let enc = f.toString() { + queryItems.append(URLQueryItem(name: "function", value: enc)) + } + } + } + urlComponents.queryItems = queryItems + if let url = urlComponents.url { + return mainPart + url.absoluteString + } + return mainPart + } + + public func toImage(scale: Double = 1.0) -> CIImage { + return EIP67CodeGenerator.createImage(from: self, scale: scale) + } + } + + public struct EIP67CodeGenerator { + + public static func createImage(from: EIP67Code, scale: Double = 1.0) -> CIImage { + guard let string = from.toString().addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) else {return CIImage()} + guard let data = string.data(using: .utf8, allowLossyConversion: false) else {return CIImage()} + let filter = CIFilter(name: "CIQRCodeGenerator", parameters: ["inputMessage" : data, "inputCorrectionLevel":"L"]) + guard var image = filter?.outputImage else {return CIImage()} + let transformation = CGAffineTransform(scaleX: CGFloat(scale), y: CGFloat(scale)) + image = image.transformed(by: transformation) + return image + } + } + + public struct EIP67CodeParser { + public static func parse(_ data: Data) -> EIP67Code? { + 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} + 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} + var code = EIP67Code(address: address) + guard let components = URLComponents(string: encoding)?.queryItems else {return code} + 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} + code.amount = val + case "gas": + guard let value = comp.value else {return nil} + guard let val = BigUInt(value, radix: 10) else {return nil} + code.gasLimit = val + case "data": + guard let value = comp.value else {return nil} + guard let data = Data.fromHex(value) else {return nil} + code.data = EIP67Code.DataType.data(data) + case "function": + continue + default: + continue + } + } + return code + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/EIP/EIP681.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/EIP/EIP681.swift new file mode 100755 index 000000000..d00e76ba1 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/EIP/EIP681.swift @@ -0,0 +1,232 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress +//import EthereumABI + +extension Web3 { + +// request = "ethereum" ":" [ "pay-" ]target_address [ "@" chain_id ] [ "/" function_name ] [ "?" parameters ] +// target_address = ethereum_address +// chain_id = 1*DIGIT +// function_name = STRING +// ethereum_address = ( "0x" 40*40HEXDIG ) / ENS_NAME +// parameters = parameter *( "&" parameter ) +// parameter = key "=" value +// key = "value" / "gas" / "gasLimit" / "gasPrice" / TYPE +// value = number / ethereum_address / STRING +// number = [ "-" / "+" ] *DIGIT [ "." 1*DIGIT ] [ ( "e" / "E" ) [ 1*DIGIT ] [ "+" UNIT ] + + public struct EIP681Code { + public struct EIP681Parameter { + public var type: ABI.Element.ParameterType + public var value: AnyObject + } + public var isPayRequest: Bool + public var targetAddress: TargetAddress + public var chainID: BigUInt? + public var functionName: String? + public var parameters: [EIP681Parameter] = [EIP681Parameter]() + public var gasLimit: BigUInt? + public var gasPrice: BigUInt? + public var amount: BigUInt? + public var function: ABI.Element.Function? + + public enum TargetAddress { + case ethereumAddress(EthereumAddress) + case ensAddress(String) + public init(_ string: String) { + if let ethereumAddress = EthereumAddress(string) { + self = TargetAddress.ethereumAddress(ethereumAddress) + } else { + self = TargetAddress.ensAddress(string) + } + } + } + + public init(_ targetAddress: TargetAddress, isPayRequest: Bool = false) { + self.isPayRequest = isPayRequest + self.targetAddress = targetAddress + } + } + + public struct EIP681CodeParser { +// static var addressRegex = "^(pay-)?([0-9a-zA-Z]+)(@[0-9]+)?" + static var addressRegex = "^(pay-)?([0-9a-zA-Z.]+)(@[0-9]+)?\\/?(.*)?$" + + public static func parse(_ data: Data) -> EIP681Code? { + guard let string = String(data: data, encoding: .utf8) else {return nil} + return parse(string) + } + + public static func parse(_ string: String) -> EIP681Code? { + 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} + let matcher = try! NSRegularExpression(pattern: addressRegex, options: NSRegularExpression.Options.dotMatchesLineSeparators) + let match = matcher.matches(in: encoding, options: NSRegularExpression.MatchingOptions.anchored, range: encoding.fullNSRange) + guard match.count == 1 else {return nil} + guard match[0].numberOfRanges == 5 else {return nil} + var addressString: String? = nil + var chainIDString: String? = nil + var tail: String? = nil +// if let payModifierRange = Range(match[0].range(at: 1), in: encoding) { +// let payModifierString = String(encoding[payModifierRange]) +// print(payModifierString) +// } + if let addressRange = Range(match[0].range(at: 2), in: encoding) { + addressString = String(encoding[addressRange]) + } + if let chainIDRange = Range(match[0].range(at: 3), in: encoding) { + chainIDString = String(encoding[chainIDRange]) + } + if let tailRange = Range(match[0].range(at: 4), in: encoding) { + tail = String(encoding[tailRange]) + } + guard let address = addressString else {return nil} + let targetAddress = EIP681Code.TargetAddress(address) + + var code = EIP681Code(targetAddress) + if chainIDString != nil { + chainIDString!.remove(at: chainIDString!.startIndex) + code.chainID = BigUInt(chainIDString!) + } + if tail == nil { + return code + } + guard let components = URLComponents(string: tail!) else {return code} + if components.path == "" { + code.isPayRequest = true + } else { + code.functionName = components.path + } + guard let queryItems = components.queryItems else {return code} + var inputNumber: Int = 0 + var inputs = [ABI.Element.InOut]() + for comp in queryItems { + if let inputType = try? ABITypeParser.parseTypeString(comp.name) { + guard let value = comp.value else {continue} + var nativeValue: AnyObject? = nil + switch inputType { + case .address: + let val = EIP681Code.TargetAddress(value) + switch val { + case .ethereumAddress(let ethereumAddress): + nativeValue = ethereumAddress as AnyObject +// default: +// return nil + case .ensAddress(let ens): + do { + let web = web3(provider: InfuraProvider(Networks.fromInt(Int(code.chainID ?? 1)) ?? Networks.Mainnet)!) + let ensModel = ENS(web3: web) + try ensModel?.setENSResolver(withDomain: ens) + let address = try ensModel?.getAddress(forNode: ens) + nativeValue = address as AnyObject + } catch { + return nil + } + } + case .uint(bits: _): + if let val = BigUInt(value, radix: 10) { + nativeValue = val as AnyObject + } else if let val = BigUInt(value.stripHexPrefix(), radix: 16) { + nativeValue = val as AnyObject + } + case .int(bits: _): + if let val = BigInt(value, radix: 10) { + nativeValue = val as AnyObject + } else if let val = BigInt(value.stripHexPrefix(), radix: 16) { + nativeValue = val as AnyObject + } + case .string: + nativeValue = value as AnyObject + case .dynamicBytes: + if let val = Data.fromHex(value) { + nativeValue = val as AnyObject + } else if let val = value.data(using: .utf8) { + nativeValue = val as AnyObject + } + case .bytes(length: _): + if let val = Data.fromHex(value) { + nativeValue = val as AnyObject + } else if let val = value.data(using: .utf8) { + nativeValue = val as AnyObject + } + case .bool: + switch value { + case "true","True", "TRUE", "1": + nativeValue = true as AnyObject + case "false", "False", "FALSE", "0": + nativeValue = false as AnyObject + default: + nativeValue = true as AnyObject + } + default: + continue + } + if nativeValue != nil { + inputs.append(ABI.Element.InOut(name: String(inputNumber), type: inputType)) + code.parameters.append(EIP681Code.EIP681Parameter(type: inputType, value: nativeValue!)) + inputNumber = inputNumber + 1 + } else { + return nil + } + } else { + switch comp.name { + case "value": + guard let value = comp.value else {return nil} + let splittedValue = value.split(separator: "e") + if splittedValue.count <= 1 { + guard let val = BigUInt(value, radix: 10) else {return nil } + code.amount = val + } else if splittedValue.count == 2 { + guard let power = Double(splittedValue[1]) else { return nil } + let splittedNumber = String(splittedValue[0]).replacingOccurrences(of: ",", with: ".").split(separator: ".") + var a = BigUInt(pow(10, power)) + if splittedNumber.count == 1 { + guard let number = BigUInt(splittedNumber[0], radix: 10) else { return nil } + code.amount = number * a + } else if splittedNumber.count == 2 { + let stringNumber = String(splittedNumber[0]) + String(splittedNumber[1]) + let am = BigUInt(pow(10, Double(splittedNumber[1].count))) + a = a / am + guard let number = BigUInt(stringNumber, radix: 10) else { return nil } + code.amount = number * a + } else { return nil } + } else { return nil } + + case "gas": + guard let value = comp.value else {return nil} + guard let val = BigUInt(value, radix: 10) else {return nil} + code.gasLimit = val + case "gasLimit": + guard let value = comp.value else {return nil} + guard let val = BigUInt(value, radix: 10) else {return nil} + code.gasLimit = val + case "gasPrice": + guard let value = comp.value else {return nil} + guard let val = BigUInt(value, radix: 10) else {return nil} + code.gasPrice = val + default: + continue + } + } + } + + if code.functionName != nil { + let functionEncoding = ABI.Element.Function(name: code.functionName!, inputs: inputs, outputs: [ABI.Element.InOut](), constant: false, payable: code.amount != nil) + code.function = functionEncoding + } + + print(code) + return code + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ENS.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ENS.swift new file mode 100755 index 000000000..ec8af0c23 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ENS.swift @@ -0,0 +1,286 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +public class ENS { + + public let web3: web3 + public var registry: Registry + public var resolver: Resolver? = nil + public var baseRegistrar: BaseRegistrar? = nil + public var registrarController: ETHRegistrarController? = nil + public var reverseRegistrar: ReverseRegistrar? = nil + + public init?(web3: web3) { + self.web3 = web3 + guard let registry = Registry(web3: web3) else { + return nil + } + self.registry = registry + } + + public func setENSResolver(_ resolver: Resolver) throws { + guard resolver.web3.provider.url == self.web3.provider.url else { + throw Web3Error.processingError(desc: "Resolver should use same provider as ENS") + } + self.resolver = resolver + } + + public func setENSResolver(withDomain domain: String) throws { + guard let resolver = try? self.registry.getResolver(forDomain: domain) else { + throw Web3Error.processingError(desc: "No resolver for this domain") + } + self.resolver = resolver + } + + public func setBaseRegistrar(_ baseRegistrar: BaseRegistrar) throws { + guard baseRegistrar.web3.provider.url == self.web3.provider.url else { + throw Web3Error.processingError(desc: "Base registrar should use same provider as ENS") + } + self.baseRegistrar = baseRegistrar + } + + public func setBaseRegistrar(withAddress address: EthereumAddress) { + let baseRegistrar = BaseRegistrar(web3: web3, address: address) + self.baseRegistrar = baseRegistrar + } + + public func setRegistrarController(_ registrarController: ETHRegistrarController) throws { + guard registrarController.web3.provider.url == self.web3.provider.url else { + throw Web3Error.processingError(desc: "Registrar controller should use same provider as ENS") + } + self.registrarController = registrarController + } + + public func setRegistrarController(withAddress address: EthereumAddress) { + let registrarController = ETHRegistrarController(web3: web3, address: address) + self.registrarController = registrarController + } + + public func setReverseRegistrar(_ reverseRegistrar: ReverseRegistrar) throws { + guard reverseRegistrar.web3.provider.url == self.web3.provider.url else { + throw Web3Error.processingError(desc: "Registrar controller should use same provider as ENS") + } + self.reverseRegistrar = reverseRegistrar + } + + public func setReverseRegistrar(withAddress address: EthereumAddress) { + let reverseRegistrar = ReverseRegistrar(web3: web3, address: address) + self.reverseRegistrar = reverseRegistrar + } + + lazy var defaultOptions: TransactionOptions = { + return TransactionOptions.defaultOptions + }() + + //MARK: - Convenience public resolver methods + public func getAddress(forNode node: String) throws -> EthereumAddress { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isAddrSupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.addr.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isAddrSupports else { + throw Web3Error.processingError(desc: "Address isn't supported") + } + guard let addr = try? resolver.getAddress(forNode: node) else { + throw Web3Error.processingError(desc: "Can't get address") + } + return addr + } + + public func setAddress(forNode node: String, address: EthereumAddress, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isAddrSupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.addr.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isAddrSupports else { + throw Web3Error.processingError(desc: "Address isn't supported") + } + var options = options ?? defaultOptions + options.to = resolver.resolverContractAddress + guard let result = try? resolver.setAddress(forNode: node, address: address, options: options, password: password) else { + throw Web3Error.processingError(desc: "Can't get result") + } + return result + } + + public func getName(forNode node: String) throws -> String { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isNameSupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.name.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isNameSupports else { + throw Web3Error.processingError(desc: "Name isn't supported") + } + guard let name = try? resolver.getCanonicalName(forNode: node) else { + throw Web3Error.processingError(desc: "Can't get name") + } + return name + } + + public func setName(forNode node: String, name: String, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isNameSupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.name.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isNameSupports else { + throw Web3Error.processingError(desc: "Name isn't supported") + } + var options = options ?? defaultOptions + options.to = resolver.resolverContractAddress + guard let result = try? resolver.setCanonicalName(forNode: node, name: name, options: options, password: password) else { + throw Web3Error.processingError(desc: "Can't get result") + } + return result + } + + public func getContent(forNode node: String) throws -> String { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isContentSupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.content.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isContentSupports else { + throw Web3Error.processingError(desc: "Content isn't supported") + } + guard let content = try? resolver.getContentHash(forNode: node) else { + throw Web3Error.processingError(desc: "Can't get content") + } + return content + } + + public func setContent(forNode node: String, hash: String, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isContentSupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.content.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isContentSupports else { + throw Web3Error.processingError(desc: "Content isn't supported") + } + var options = options ?? defaultOptions + options.to = resolver.resolverContractAddress + guard let result = try? resolver.setContentHash(forNode: node, hash: hash, options: options, password: password) else { + throw Web3Error.processingError(desc: "Can't get result") + } + return result + } + + public func getABI(forNode node: String, contentType: ENS.Resolver.ContentType) throws -> (BigUInt, Data) { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isABISupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.ABI.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isABISupports else { + throw Web3Error.processingError(desc: "ABI isn't supported") + } + guard let abi = try? resolver.getContractABI(forNode: node, contentType: contentType) else { + throw Web3Error.processingError(desc: "Can't get ABI") + } + return abi + } + + public func setABI(forNode node: String, contentType: ENS.Resolver.ContentType, data: Data, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isABISupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.ABI.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isABISupports else { + throw Web3Error.processingError(desc: "ABI isn't supported") + } + var options = options ?? defaultOptions + options.to = resolver.resolverContractAddress + guard let result = try? resolver.setContractABI(forNode: node, contentType: contentType, data: data, options: options, password: password) else { + throw Web3Error.processingError(desc: "Can't get result") + } + return result + } + + public func getPublicKey(forNode node: String) throws -> PublicKey { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isPKSupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.pubkey.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isPKSupports else { + throw Web3Error.processingError(desc: "Public Key isn't supported") + } + guard let pk = try? resolver.getPublicKey(forNode: node) else { + throw Web3Error.processingError(desc: "Can't get Public Key") + } + return pk + } + + public func setPublicKey(forNode node: String, publicKey: PublicKey, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isPKSupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.pubkey.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isPKSupports else { + throw Web3Error.processingError(desc: "Public Key isn't supported") + } + var options = options ?? defaultOptions + options.to = resolver.resolverContractAddress + guard let result = try? resolver.setPublicKey(forNode: node, publicKey: publicKey, options: options, password: password) else { + throw Web3Error.processingError(desc: "Can't get result") + } + return result + } + + public func getText(forNode node: String, key: String) throws -> String { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isTextSupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.text.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isTextSupports else { + throw Web3Error.processingError(desc: "Text isn't supported") + } + guard let text = try? resolver.getTextData(forNode: node, key: key) else { + throw Web3Error.processingError(desc: "Can't get text") + } + return text + } + + public func setText(forNode node: String, key: String, value: String, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isTextSupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.text.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isTextSupports else { + throw Web3Error.processingError(desc: "Text isn't supported") + } + var options = options ?? defaultOptions + options.to = resolver.resolverContractAddress + guard let result = try? resolver.setTextData(forNode: node, key: key, value: value, options: options, password: password) else { + throw Web3Error.processingError(desc: "Can't get result") + } + return result + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSBaseRegistrar.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSBaseRegistrar.swift new file mode 100644 index 000000000..4c1c89879 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSBaseRegistrar.swift @@ -0,0 +1,82 @@ +// +// BaseRegistrar.swift +// web3swift +// +// Created by Anton on 15/04/2019. +// Copyright © 2019 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +public extension ENS { + class BaseRegistrar: ERC721 { + lazy var defaultOptions: TransactionOptions = { + return TransactionOptions.defaultOptions + }() + + public init(web3: web3, address: EthereumAddress) { + super.init(web3: web3, provider: web3.provider, address: address) + guard let contract = self.web3.contract(Web3.Utils.baseRegistrarABI, at: self.address, abiVersion: 2) else { + return + } + self.contract = contract + } + + override public init(web3: web3, provider: Web3Provider, address: EthereumAddress) { + super.init(web3: web3, provider: provider, address: address) + guard let contract = self.web3.contract(Web3.Utils.baseRegistrarABI, at: self.address, abiVersion: 2) else { + return + } + self.contract = contract + } + + @available(*, message: "Available for only owner") + public func addController(from: EthereumAddress, controllerAddress: EthereumAddress) throws -> WriteTransaction { + defaultOptions.from = from + defaultOptions.to = self.address + guard let transaction = self.contract.write("addController", parameters: [controllerAddress as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + return transaction + } + + @available(*, message: "Available for only owner") + public func removeController(from: EthereumAddress, controllerAddress: EthereumAddress) throws -> WriteTransaction { + defaultOptions.from = from + defaultOptions.to = self.address + guard let transaction = self.contract.write("removeController", parameters: [controllerAddress as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + return transaction + } + + @available(*, message: "Available for only owner") + public func setResolver(from: EthereumAddress, resolverAddress: EthereumAddress) throws -> WriteTransaction { + defaultOptions.from = from + defaultOptions.to = self.address + guard let transaction = self.contract.write("setResolver", parameters: [resolverAddress as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + return transaction + } + + public func getNameExpirity(name: BigUInt) throws -> BigUInt { + guard let transaction = self.contract.read("nameExpires", parameters: [name as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let expirity = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Can't get answer")} + return expirity + } + + @available(*, message: "This function should not be used to check if a name can be registered by a user. To check if a name can be registered by a user, check name availablility via the controller") + public func isNameAvailable(name: BigUInt) throws -> Bool { + guard let transaction = self.contract.read("available", parameters: [name as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) 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 reclaim(from: EthereumAddress, record: BigUInt) throws -> WriteTransaction { + defaultOptions.from = from + defaultOptions.to = self.address + guard let transaction = self.contract.write("reclaim", parameters: [record as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + return transaction + } + + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSRegistry.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSRegistry.swift new file mode 100644 index 000000000..b89f05086 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSRegistry.swift @@ -0,0 +1,110 @@ +// +// ENSRegistry.swift +// web3swift +// +// Created by Anton on 17/04/2019. +// Copyright © 2019 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +public extension ENS { + class Registry { + public let web3: web3 + public let registryContractAddress: EthereumAddress? + + public init?(web3: web3) { + self.web3 = web3 + switch web3.provider.network { + case .Mainnet?: + registryContractAddress = EthereumAddress("0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e") + case .Rinkeby?: + registryContractAddress = EthereumAddress("0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e") + case .Ropsten?: + registryContractAddress = EthereumAddress("0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e") + default: + let url = web3.provider.url.absoluteString + if url.contains("https://rpc.goerli.mudit.blog") + || url.contains("http://goerli.blockscout.com") + || url.contains("http://goerli.prylabs.net") + || url.contains("https://rpc.slock.it/goerli") { + registryContractAddress = EthereumAddress("0x112234455c3a32fd11230c42e7bccd4a84e02010") + } + return nil + } + } + + lazy var defaultOptions: TransactionOptions = { + return TransactionOptions.defaultOptions + }() + + lazy var registryContract: web3.web3contract = { + let contract = self.web3.contract(Web3.Utils.ensRegistryABI, at: self.registryContractAddress, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public func getOwner(node: String) throws -> EthereumAddress { + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.registryContract.read("owner", parameters: [nameHash as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let address = result["0"] as? EthereumAddress else {throw Web3Error.processingError(desc: "No address in result")} + return address + } + + public func getResolver(forDomain domain: String) throws -> Resolver { + guard let nameHash = NameHash.nameHash(domain) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.registryContract.read("resolver", parameters: [nameHash as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let resolverAddress = result["0"] as? EthereumAddress else {throw Web3Error.processingError(desc: "No address in result")} + return Resolver(web3: self.web3, resolverContractAddress: resolverAddress) + } + + public func getTTL(node: String) throws -> BigUInt { + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.registryContract.read("ttl", parameters: [nameHash as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let ans = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "No answer in result")} + return ans + } + + public func setOwner(node: String, owner: EthereumAddress, options: TransactionOptions?, password: String? = nil) throws -> TransactionSendingResult { + var options = options ?? defaultOptions + options.to = self.registryContractAddress + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.registryContract.write("setOwner", parameters: [nameHash, owner] as [AnyObject], extraData: Data(), transactionOptions: options) else {throw Web3Error.transactionSerializationError} + guard let result = password == nil ? try? transaction.send() : try? transaction.send(password: password!, transactionOptions: options) else {throw Web3Error.processingError(desc: "Can't send transaction")} + return result + } + + public func setSubnodeOwner(node: String, label: String, owner: EthereumAddress, options: TransactionOptions?, password: String? = nil) throws -> TransactionSendingResult { + var options = options ?? defaultOptions + options.to = self.registryContractAddress + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let labelHash = NameHash.nameHash(label) else {throw Web3Error.processingError(desc: "Failed to get label hash")} + guard let transaction = self.registryContract.write("setSubnodeOwner", parameters: [nameHash, labelHash, owner] as [AnyObject], extraData: Data(), transactionOptions: options) else {throw Web3Error.transactionSerializationError} + guard let result = password == nil ? try? transaction.send() : try? transaction.send(password: password!, transactionOptions: options) else {throw Web3Error.processingError(desc: "Can't send transaction")} + return result + } + + public func setResolver(node: String, resolver: EthereumAddress, options: TransactionOptions?, password: String? = nil) throws -> TransactionSendingResult { + var options = options ?? defaultOptions + options.to = self.registryContractAddress + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.registryContract.write("setResolver", parameters: [nameHash, resolver] as [AnyObject], extraData: Data(), transactionOptions: options) else {throw Web3Error.transactionSerializationError} + guard let result = password == nil ? try? transaction.send() : try? transaction.send(password: password!, transactionOptions: options) else {throw Web3Error.processingError(desc: "Can't send transaction")} + return result + } + + public func setTTL(node: String, ttl: BigUInt, options: TransactionOptions?, password: String? = nil) throws -> TransactionSendingResult { + var options = options ?? defaultOptions + options.to = self.registryContractAddress + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.registryContract.write("setTTL", parameters: [nameHash, ttl] as [AnyObject], extraData: Data(), transactionOptions: options) else {throw Web3Error.transactionSerializationError} + guard let result = password == nil ? try? transaction.send() : try? transaction.send(password: password!, transactionOptions: options) else {throw Web3Error.processingError(desc: "Can't send transaction")} + return result + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSResolver.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSResolver.swift new file mode 100755 index 000000000..67176af8d --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSResolver.swift @@ -0,0 +1,196 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +public extension ENS { + class Resolver { + public let web3: web3 + public let resolverContractAddress: EthereumAddress + + public enum ContentType: BigUInt { + case JSON = 1 + case zlibCompressedJSON = 2 + case CBOR = 4 + case URI = 8 + } + + public enum InterfaceName { + case addr + case name + case content + case ABI + case pubkey + case text + + func hash() -> String { + switch self { + case .addr: + return "0x3b3b57de" + case .name: + return "0x691f3431" + case .content: + return "0xbc1c58d1" + case .ABI: + return "0x2203ab56" + case .pubkey: + return "0xc8690233" + case .text: + return "0x59d1d43c" + } + } + } + + lazy var resolverContract: web3.web3contract = { + let contract = self.web3.contract(Web3.Utils.resolverABI, at: self.resolverContractAddress, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + lazy var defaultOptions: TransactionOptions = { + return TransactionOptions.defaultOptions + }() + + public init(web3: web3, resolverContractAddress: EthereumAddress) { + self.web3 = web3 + self.resolverContractAddress = resolverContractAddress + } + + public func supportsInterface(interfaceID: Data) throws -> Bool { + guard let supports = try? supportsInterface(interfaceID: interfaceID.toHexString()) else {throw Web3Error.processingError(desc: "Can't get answer")} + return supports + } + + public func supportsInterface(interfaceID: String) throws -> Bool { + guard let transaction = self.resolverContract.read("supportsInterface", parameters: [interfaceID as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let supports = result["0"] as? Bool else {throw Web3Error.processingError(desc: "Can't get answer")} + return supports + } + + public func interfaceImplementer(forNode node: String, interfaceID: String) throws -> EthereumAddress { + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.read("interfaceImplementer", parameters: [nameHash, interfaceID] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let address = result["0"] as? EthereumAddress else {throw Web3Error.processingError(desc: "Can't get address")} + return address + } + + public func getAddress(forNode node: String) throws -> EthereumAddress { + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.read("addr", parameters: [nameHash as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let address = result["0"] as? EthereumAddress else {throw Web3Error.processingError(desc: "Can't get address")} + return address + } + + @available(*, message: "Available for only owner") + public func setAddress(forNode node: String, address: EthereumAddress, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + var options = options ?? defaultOptions + options.to = self.resolverContractAddress + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.write("setAddr", parameters: [nameHash, address] as [AnyObject], extraData: Data(), transactionOptions: options) else {throw Web3Error.transactionSerializationError} + guard let result = password == nil ? try? transaction.send() : try? transaction.send(password: password!, transactionOptions: options) else {throw Web3Error.processingError(desc: "Can't send transaction")} + return result + } + + public func getCanonicalName(forNode node: String) throws -> String { + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.read("name", parameters: [nameHash as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let name = result["0"] as? String else {throw Web3Error.processingError(desc: "Can't get name")} + return name + } + + @available(*, message: "Available for only owner") + func setCanonicalName(forNode node: String, name: String, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + var options = options ?? defaultOptions + options.to = self.resolverContractAddress + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.write("setName", parameters: [nameHash, name] as [AnyObject], extraData: Data(), transactionOptions: options) else {throw Web3Error.transactionSerializationError} + guard let result = password == nil ? try? transaction.send() : try? transaction.send(password: password!, transactionOptions: options) else {throw Web3Error.processingError(desc: "Can't send transaction")} + return result + } + + func getContentHash(forNode node: String) throws -> String { + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.read("contenthash", parameters: [nameHash] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let content = result["0"] as? String else {throw Web3Error.processingError(desc: "Can't get content")} + return content + } + + @available(*, message: "Available for only owner") + func setContentHash(forNode node: String, hash: String, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + var options = options ?? defaultOptions + options.to = self.resolverContractAddress + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.write("setContenthash", parameters: [nameHash, hash] as [AnyObject], extraData: Data(), transactionOptions: options) else {throw Web3Error.transactionSerializationError} + guard let result = password == nil ? try? transaction.send() : try? transaction.send(password: password!, transactionOptions: options) else {throw Web3Error.processingError(desc: "Can't send transaction")} + return result + } + + public func getContractABI(forNode node: String, contentType: ENS.Resolver.ContentType) throws -> (BigUInt, Data) { + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.read("ABI", parameters: [nameHash, contentType.rawValue] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let encoding = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Can't get encoding")} + guard let data = result["1"] as? Data else {throw Web3Error.processingError(desc: "Can't get data")} + return (encoding, data) + } + + @available(*, message: "Available for only owner") + func setContractABI(forNode node: String, contentType: ENS.Resolver.ContentType, data: Data, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + var options = options ?? defaultOptions + options.to = self.resolverContractAddress + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.write("setABI", parameters: [nameHash, contentType.rawValue, data] as [AnyObject], extraData: Data(), transactionOptions: options) else {throw Web3Error.transactionSerializationError} + guard let result = password == nil ? try? transaction.send() : try? transaction.send(password: password!, transactionOptions: options) else {throw Web3Error.processingError(desc: "Can't send transaction")} + return result + } + + public func getPublicKey(forNode node: String) throws -> PublicKey { + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.read("pubkey", parameters: [nameHash as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let x = result["x"] as? Data else {throw Web3Error.processingError(desc: "Can't get x")} + guard let y = result["y"] as? Data else {throw Web3Error.processingError(desc: "Can't get y")} + let pubkey = PublicKey(x: "0x" + x.toHexString(), y: "0x" + y.toHexString()) + return pubkey + } + + @available(*, message: "Available for only owner") + public func setPublicKey(forNode node: String, publicKey: PublicKey, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + var options = options ?? defaultOptions + options.to = self.resolverContractAddress + let pubkeyWithoutPrefix = publicKey.getComponentsWithoutPrefix() + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.write("setPubkey", parameters: [nameHash, pubkeyWithoutPrefix.x, pubkeyWithoutPrefix.y] as [AnyObject], extraData: Data(), transactionOptions: options) else {throw Web3Error.transactionSerializationError} + guard let result = password == nil ? try? transaction.send() : try? transaction.send(password: password!, transactionOptions: options) else {throw Web3Error.processingError(desc: "Can't send transaction")} + return result + } + + public func getTextData(forNode node: String, key: String) throws -> String { + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.read("text", parameters: [nameHash, key] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let text = result["0"] as? String else {throw Web3Error.processingError(desc: "Can't get text")} + return text + } + + @available(*, message: "Available for only owner") + public func setTextData(forNode node: String, key: String, value: String, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + var options = options ?? defaultOptions + options.to = self.resolverContractAddress + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.write("setText", parameters: [nameHash, key, value] as [AnyObject], extraData: Data(), transactionOptions: options) else {throw Web3Error.transactionSerializationError} + guard let result = password == nil ? try? transaction.send() : try? transaction.send(password: password!, transactionOptions: options) else {throw Web3Error.processingError(desc: "Can't send transaction")} + return result + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSReverseRegistrar.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSReverseRegistrar.swift new file mode 100644 index 000000000..b6440a0c9 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSReverseRegistrar.swift @@ -0,0 +1,68 @@ +// +// ENSReverseRegistrar.swift +// web3swift +// +// Created by Anton on 20/04/2019. +// Copyright © 2019 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +public extension ENS { + class ReverseRegistrar { + public let web3: web3 + public let address: EthereumAddress + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(Web3.Utils.reverseRegistrarABI, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + lazy var defaultOptions: TransactionOptions = { + return TransactionOptions.defaultOptions + }() + + public init(web3: web3, address: EthereumAddress) { + self.web3 = web3 + self.address = address + } + + public func claimAddress(from: EthereumAddress, owner: EthereumAddress) throws -> WriteTransaction { + defaultOptions.from = from + defaultOptions.to = self.address + guard let transaction = self.contract.write("claim", parameters: [owner as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + return transaction + } + + public func claimAddressWithResolver(from: EthereumAddress, owner: EthereumAddress, resolver: EthereumAddress) throws -> WriteTransaction { + defaultOptions.from = from + defaultOptions.to = self.address + guard let transaction = self.contract.write("claimWithResolver", parameters: [owner, resolver] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + return transaction + } + + public func setName(from: EthereumAddress, name: String) throws -> WriteTransaction { + defaultOptions.from = from + defaultOptions.to = self.address + guard let transaction = self.contract.write("setName", parameters: [name] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + return transaction + } + + public func getReverseRecordName(address: EthereumAddress) throws -> Data { + guard let transaction = self.contract.read("node", parameters: [address] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) 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 + } + + public func getDefaultResolver() throws -> EthereumAddress { + guard let transaction = self.contract.read("defaultResolver", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) 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/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ETHRegistrarController.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ETHRegistrarController.swift new file mode 100644 index 000000000..88c8a7f83 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/ETHRegistrarController.swift @@ -0,0 +1,93 @@ +// +// RegistrarController.swift +// web3swift +// +// Created by Anton on 15/04/2019. +// Copyright © 2019 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt + +public extension ENS { + class ETHRegistrarController { + public let web3: web3 + public let address: EthereumAddress + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(Web3.Utils.ethRegistrarControllerABI, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + lazy var defaultOptions: TransactionOptions = { + return TransactionOptions.defaultOptions + }() + + public init(web3: web3, address: EthereumAddress) { + self.web3 = web3 + self.address = address + } + + public func getRentPrice(name: String, duration: UInt) throws -> BigUInt { + guard let transaction = self.contract.read("rentPrice", parameters: [name, duration] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) 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) throws -> Bool { + guard let transaction = self.contract.read("valid", parameters: [name] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) 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) throws -> Bool { + guard let transaction = self.contract.read("available", parameters: [name as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) 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) throws -> Data { + guard let transaction = self.contract.read("makeCommitment", parameters: [name, owner.address, secret] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) 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 -> WriteTransaction { + defaultOptions.from = from + defaultOptions.to = self.address + guard let transaction = self.contract.write("commit", parameters: [commitment as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + return transaction + } + + public func registerName(from: EthereumAddress, name: String, owner: EthereumAddress, duration: UInt, secret: String, price: String) throws -> WriteTransaction { + guard let amount = Web3.Utils.parseToBigUInt(price, units: .eth) else {throw Web3Error.inputError(desc: "Wrong price: no way for parsing to ether units")} + defaultOptions.value = amount + defaultOptions.from = from + defaultOptions.to = self.address + guard let transaction = self.contract.write("register", parameters: [name, owner.address, duration, secret] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + return transaction + } + + public func extendNameRegistration(from: EthereumAddress, name: String, duration: UInt32, price: String) throws -> WriteTransaction { + guard let amount = Web3.Utils.parseToBigUInt(price, units: .eth) else {throw Web3Error.inputError(desc: "Wrong price: no way for parsing to ether units")} + defaultOptions.value = amount + defaultOptions.from = from + defaultOptions.to = self.address + guard let transaction = self.contract.write("renew", parameters: [name, duration] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + return transaction + } + + @available(*, message: "Available for only owner") + public func withdraw(from: EthereumAddress) throws -> WriteTransaction { + defaultOptions.from = from + defaultOptions.to = self.address + guard let transaction = self.contract.write("withdraw", parameters: [AnyObject](), extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + return transaction + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/NameHash.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/NameHash.swift new file mode 100755 index 000000000..2a96a9ca4 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/NameHash.swift @@ -0,0 +1,52 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import CryptoSwift + +public struct NameHash { + public static func normalizeDomainName(_ domain: String) -> String? { + // TODO use ICU4C library later for domain name normalization, althoug f**k it for now, it's few megabytes large piece + let normalized = domain.lowercased() + return normalized + } + + public static func nameHash(_ domain: String) -> Data? { + guard let normalized = NameHash.normalizeDomainName(domain) else {return nil} + return namehash(normalized) + } + + static func namehash(_ name: String) -> Data? { + if name == "" { + return Data(repeating: 0, count: 32) + } + let parts = name.split(separator: ".") + guard parts.count > 0 else { + return nil + } + guard let lowerLevel = parts.first else { + return nil + } + var remainder = "" + if parts.count > 1 { + remainder = parts[1 ..< parts.count].joined(separator: ".") + } + // TODO here some better normalization can happen + var hashData = Data() + guard let remainderHash = namehash(remainder) else { + return nil + } + guard let labelData = lowerLevel.data(using: .utf8) else { + return nil + } + hashData.append(remainderHash) + hashData.append(labelData.sha3(.keccak256)) + let hash = hashData.sha3(.keccak256) + print(name) + print(hash.toHexString()) + return hash + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/PublicKey.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/PublicKey.swift new file mode 100644 index 000000000..f7b000d40 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/ENS/PublicKey.swift @@ -0,0 +1,26 @@ +// +// PublicKey.swift +// web3swift +// +// Created by Anton on 17/04/2019. +// Copyright © 2019 The Matter Inc. All rights reserved. +// + +import Foundation + +public struct PublicKey { + public let x: String + public let y: String + + public func getComponentsWithoutPrefix() -> PublicKey { + var x = self.x + var y = self.y + if x.hasHexPrefix() { + x.removeFirst(2) + } + if y.hasHexPrefix() { + y.removeFirst(2) + } + return PublicKey(x: x, y: y) + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/Hooks/NonceMiddleware.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/Hooks/NonceMiddleware.swift new file mode 100755 index 000000000..127f302f6 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Utils/Hooks/NonceMiddleware.swift @@ -0,0 +1,111 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +//import EthereumAddress +import BigInt +import PromiseKit + +extension Web3.Utils { + + fileprivate typealias AssemblyHook = web3.AssemblyHook + fileprivate typealias SubmissionResultHook = web3.SubmissionResultHook + + public class NonceMiddleware: EventLoopRunnableProtocol { + var web3: web3? + var nonceLookups: [EthereumAddress: BigUInt] = [EthereumAddress: BigUInt]() + public var name: String = "Nonce lookup middleware" + public let queue: DispatchQueue = DispatchQueue(label: "Nonce middleware queue") + public var synchronizationPeriod: TimeInterval = 300.0 // 5 minutes + var lastSyncTime: Date = Date() + + public func functionToRun() { + guard let w3 = self.web3 else {return} + var allPromises = [Promise]() + allPromises.reserveCapacity(self.nonceLookups.keys.count) + let knownKeys = Array(self.nonceLookups.keys) + for k in knownKeys { + let promise = w3.eth.getTransactionCountPromise(address: k, onBlock: "latest") + allPromises.append(promise) + } + when(resolved: allPromises).done(on: w3.requestDispatcher.queue) {results in + self.queue.async { + var i = 0 + for res in results { + switch res { + case .fulfilled(let newNonce): + let key = knownKeys[i] + self.nonceLookups[key] = newNonce + i = i + 1 + default: + i = i + 1 + } + } + } + + } + } + + public init() { + + } + + func preAssemblyFunction(tx: EthereumTransaction, contract: EthereumContract, transactionOptions: TransactionOptions) -> (EthereumTransaction, EthereumContract, TransactionOptions, Bool) { + guard let from = transactionOptions.from else { + // do nothing + return (tx, contract, transactionOptions, true) + } + guard let knownNonce = self.nonceLookups[from] else { + return (tx, contract, transactionOptions, true) + } + + let newNonce = knownNonce + 1 + + self.queue.async { + self.nonceLookups[from] = newNonce + } + // var modifiedTX = tx + // modifiedTX.nonce = newNonce + var newOptions = transactionOptions + newOptions.nonce = .manual(newNonce) + return (tx, contract, newOptions, true) + } + + func postSubmissionFunction(result: TransactionSendingResult) { + guard let from = result.transaction.sender else { + // do nothing + return + } + + let newNonce = result.transaction.nonce + + if let knownNonce = self.nonceLookups[from] { + if knownNonce != newNonce { + self.queue.async { + self.nonceLookups[from] = newNonce + } + } + return + } + self.queue.async { + self.nonceLookups[from] = newNonce + } + return + } + + public func attach(_ web3: web3) { + self.web3 = web3 + web3.eventLoop.monitoredUserFunctions.append(self) + let preHook = AssemblyHook(queue: web3.requestDispatcher.queue, function: self.preAssemblyFunction) + web3.preAssemblyHooks.append(preHook) + let postHook = SubmissionResultHook(queue: web3.requestDispatcher.queue, function: self.postSubmissionFunction) + web3.postSubmissionHooks.append(postHook) + } + + } + + +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Constants.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Constants.swift new file mode 100644 index 000000000..e975b617e --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Constants.swift @@ -0,0 +1,15 @@ +// +// Web3+Constants.swift +// web3swift +// +// Created by Anton on 24/06/2019. +// Copyright © 2019 Matter Labs. All rights reserved. +// + +import Foundation + +struct Constants { + static let infuraHttpScheme = ".infura.io/v3/" + static let infuraWsScheme = ".infura.io/ws/v3/" + static let infuraToken = "4406c3acf862426c83991f1752c46dd8" +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Contract.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Contract.swift new file mode 100755 index 000000000..93e49f3a6 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Contract.swift @@ -0,0 +1,116 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +extension web3 { + + /// The contract instance. Initialized in runtime from ABI string (that is a JSON array). In addition an existing contract address can be supplied to provide the default "to" address in all the following requests. ABI version is 2 by default and should not be changed. + public func contract(_ abiString: String, at: EthereumAddress? = nil, abiVersion: Int = 2) -> web3contract? { + return web3contract(web3: self, abiString: abiString, at: at, transactionOptions: self.transactionOptions, abiVersion: abiVersion) + } + + /// Web3 instance bound contract instance. + public class web3contract { + var contract: EthereumContract + var web3 : web3 + public var transactionOptions: TransactionOptions? = nil + + + /// Initialize the bound contract instance by supplying the Web3 provider bound object, ABI, Ethereum address and some default + /// options for further function calls. By default the contract inherits options from the web3 object. Additionally supplied "options" + /// do override inherited ones. + public init?(web3 web3Instance:web3, abiString: String, at: EthereumAddress? = nil, transactionOptions: TransactionOptions? = nil, abiVersion: Int = 2) { + self.web3 = web3Instance + self.transactionOptions = web3.transactionOptions + switch abiVersion { + case 1: + print("ABIv1 bound contract is now deprecated") + return nil + case 2: + guard let c = EthereumContract(abiString, at: at) else {return nil} + contract = c + default: + return nil + } + var mergedOptions = self.transactionOptions?.merge(transactionOptions) + if at != nil { + contract.address = at + mergedOptions?.to = at + } else if let addr = mergedOptions?.to { + contract.address = addr + } + self.transactionOptions = mergedOptions + } + + /// Deploys a constact instance using the previously provided (at initialization) ABI, some bytecode, constructor parameters and options. + /// If extraData is supplied it is appended to encoded bytecode and constructor parameters. + /// + /// Returns a "Transaction intermediate" object. + public func deploy(bytecode: Data, parameters: [AnyObject] = [AnyObject](), extraData: Data = Data(), transactionOptions: TransactionOptions? = nil) -> WriteTransaction? { + let mergedOptions = self.transactionOptions?.merge(transactionOptions) + guard var tx = self.contract.deploy(bytecode: bytecode, parameters: parameters, extraData: extraData) else {return nil} + tx.chainID = self.web3.provider.network?.chainID + let writeTX = WriteTransaction.init(transaction: tx, web3: self.web3, contract: self.contract, method: "fallback", transactionOptions: mergedOptions) + return writeTX + } + + /// Creates and object responsible for calling a particular function of the contract. If method name is not found in ABI - returns nil. + /// If extraData is supplied it is appended to encoded function parameters. Can be usefull if one wants to call + /// the function not listed in ABI. "Parameters" should be an array corresponding to the list of parameters of the function. + /// Elements of "parameters" can be other arrays or instances of String, Data, BigInt, BigUInt, Int or EthereumAddress. + /// + /// Returns a "Transaction intermediate" object. + public func method(_ method:String = "fallback", parameters: [AnyObject] = [AnyObject](), extraData: Data = Data(), transactionOptions: TransactionOptions? = nil) -> WriteTransaction? { + let mergedOptions = self.transactionOptions?.merge(transactionOptions) + guard var tx = self.contract.method(method, parameters: parameters, extraData: extraData) else {return nil} + tx.chainID = self.web3.provider.network?.chainID + let writeTX = WriteTransaction.init(transaction: tx, web3: self.web3, contract: self.contract, method: method, transactionOptions: mergedOptions) + return writeTX + } + + /// Creates and object responsible for calling a particular function of the contract. If method name is not found in ABI - returns nil. + /// If extraData is supplied it is appended to encoded function parameters. Can be usefull if one wants to call + /// the function not listed in ABI. "Parameters" should be an array corresponding to the list of parameters of the function. + /// Elements of "parameters" can be other arrays or instances of String, Data, BigInt, BigUInt, Int or EthereumAddress. + /// + /// Returns a "Transaction intermediate" object. + public func read(_ method:String = "fallback", parameters: [AnyObject] = [AnyObject](), extraData: Data = Data(), transactionOptions: TransactionOptions? = nil) -> ReadTransaction? { + let mergedOptions = self.transactionOptions?.merge(transactionOptions) + guard var tx = self.contract.method(method, parameters: parameters, extraData: extraData) else {return nil} + tx.chainID = self.web3.provider.network?.chainID + let writeTX = ReadTransaction.init(transaction: tx, web3: self.web3, contract: self.contract, method: method, transactionOptions: mergedOptions) + return writeTX + } + + /// Creates and object responsible for calling a particular function of the contract. If method name is not found in ABI - returns nil. + /// If extraData is supplied it is appended to encoded function parameters. Can be usefull if one wants to call + /// the function not listed in ABI. "Parameters" should be an array corresponding to the list of parameters of the function. + /// Elements of "parameters" can be other arrays or instances of String, Data, BigInt, BigUInt, Int or EthereumAddress. + /// + /// Returns a "Transaction intermediate" object. + public func write(_ method:String = "fallback", parameters: [AnyObject] = [AnyObject](), extraData: Data = Data(), transactionOptions: TransactionOptions? = nil) -> WriteTransaction? { + let mergedOptions = self.transactionOptions?.merge(transactionOptions) + guard var tx = self.contract.method(method, parameters: parameters, extraData: extraData) else {return nil} + tx.chainID = self.web3.provider.network?.chainID + let writeTX = WriteTransaction.init(transaction: tx, web3: self.web3, contract: self.contract, method: method, transactionOptions: mergedOptions) + return writeTX + } + + /// Parses an EventLog object by using a description from the contract's ABI. + public func parseEvent(_ eventLog: EventLog) -> (eventName:String?, eventData:[String:Any]?) { + return self.contract.parseEvent(eventLog) + } + + /// Creates an "EventParserProtocol" compliant object to use it for parsing particular block or transaction for events. + public func createEventParser(_ eventName:String, filter:EventFilter?) -> EventParserProtocol? { + let parser = EventParser(web3: self.web3, eventName: eventName, contract: self.contract, filter: filter) + return parser + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Eth+Websocket.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Eth+Websocket.swift new file mode 100644 index 000000000..46d76146b --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Eth+Websocket.swift @@ -0,0 +1,42 @@ +// +// Web3+Eth+Websocket.swift +// web3swift +// +// Created by Anton on 03/04/2019. +// Copyright © 2019 The Matter Inc. All rights reserved. +// +import Foundation +import BigInt +import PromiseKit +import Starscream + + +extension web3.Eth { + + public func getWebsocketProvider(forDelegate delegate: Web3SocketDelegate) throws -> InfuraWebsocketProvider { + var infuraWSProvider: InfuraWebsocketProvider + if !(provider is InfuraWebsocketProvider) { + guard let infuraNetwork = provider.network else { + throw Web3Error.processingError(desc: "Wrong network") + } + guard let infuraProvider = InfuraWebsocketProvider(infuraNetwork, delegate: delegate, keystoreManager: provider.attachedKeystoreManager) else { + throw Web3Error.processingError(desc: "Wrong network") + } + infuraWSProvider = infuraProvider + } else { + infuraWSProvider = provider as! InfuraWebsocketProvider + } + infuraWSProvider.connectSocket() + return infuraWSProvider + } + + public func getLatestPendingTransactions(forDelegate delegate: Web3SocketDelegate) throws { + let provider = try getWebsocketProvider(forDelegate: delegate) + try provider.setFilterAndGetChanges(method: .newPendingTransactionFilter) + } + + public func subscribeOnPendingTransactions(forDelegate delegate: Web3SocketDelegate) throws { + let provider = try getWebsocketProvider(forDelegate: delegate) + try provider.subscribeOnNewPendingTransactions() + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Eth.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Eth.swift new file mode 100755 index 000000000..134791c1d --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Eth.swift @@ -0,0 +1,358 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +extension web3.Eth { + + /// Send an EthereumTransaction object to the network. Transaction is either signed locally if there is a KeystoreManager + /// object bound to the web3 instance, or sent unsigned to the node. For local signing the password is required. + /// + /// "options" object can override the "to", "gasPrice", "gasLimit" and "value" parameters is pre-formed transaction. + /// "from" field in "options" is mandatory for both local and remote signing. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func sendTransaction(_ transaction: EthereumTransaction, transactionOptions: TransactionOptions, password:String = "web3swift") throws -> TransactionSendingResult { + let result = try self.sendTransactionPromise(transaction, transactionOptions: transactionOptions, password: password).wait() + return result + } + + /// Performs a non-mutating "call" to some smart-contract. EthereumTransaction bears all function parameters required for the call. + /// Does NOT decode the data returned from the smart-contract. + /// "options" object can override the "to", "gasPrice", "gasLimit" and "value" parameters is pre-formed transaction. + /// "from" field in "options" is mandatory for both local and remote signing. + /// + /// "onString" field determines if value is returned based on the state of a blockchain on the latest mined block ("latest") + /// or the expected state after all the transactions in memory pool are applied ("pending"). + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + func call(_ transaction: EthereumTransaction, transactionOptions: TransactionOptions) throws -> Data { + let result = try self.callPromise(transaction, transactionOptions: transactionOptions).wait() + return result + } + + /// Send raw Ethereum transaction data to the network. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func sendRawTransaction(_ transaction: Data) throws -> TransactionSendingResult { + let result = try self.sendRawTransactionPromise(transaction).wait() + return result + } + + /// Send raw Ethereum transaction data to the network by first serializing the EthereumTransaction object. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func sendRawTransaction(_ transaction: EthereumTransaction) throws -> TransactionSendingResult { + let result = try self.sendRawTransactionPromise(transaction).wait() + return result + } + + /// Returns a total number of transactions sent by the particular Ethereum address. + /// + /// "onBlock" field determines if value is returned based on the state of a blockchain on the latest mined block ("latest") + /// or the expected state after all the transactions in memory pool are applied ("pending"). + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getTransactionCount(address: EthereumAddress, onBlock: String = "latest") throws -> BigUInt { + let result = try self.getTransactionCountPromise(address: address, onBlock: onBlock).wait() + return result + } + + /// Returns a balance of particular Ethereum address in Wei units (1 ETH = 10^18 Wei). + /// + /// "onString" field determines if value is returned based on the state of a blockchain on the latest mined block ("latest") + /// or the expected state after all the transactions in memory pool are applied ("pending"). + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getBalance(address: EthereumAddress, onBlock: String = "latest") throws -> BigUInt { + let result = try self.getBalancePromise(address: address, onBlock: onBlock).wait() + return result + } + + /// Returns a block number of the last mined block that Ethereum node knows about. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getBlockNumber() throws -> BigUInt { + let result = try self.getBlockNumberPromise().wait() + return result + } + + /// Returns a current gas price in the units of Wei. The node has internal algorithms for averaging over the last few blocks. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getGasPrice() throws -> BigUInt { + let result = try self.getGasPricePromise().wait() + return result + } + + /// Returns transaction details for particular transaction hash. Details indicate position of the transaction in a particular block, + /// as well as original transaction details such as value, gas limit, gas price, etc. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getTransactionDetails(_ txhash: Data) throws -> TransactionDetails { + let result = try self.getTransactionDetailsPromise(txhash).wait() + return result + } + + /// Returns transaction details for particular transaction hash. Details indicate position of the transaction in a particular block, + /// as well as original transaction details such as value, gas limit, gas price, etc. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getTransactionDetails(_ txhash: String) throws -> TransactionDetails { + let result = try self.getTransactionDetailsPromise(txhash).wait() + return result + } + + /// Returns transaction receipt for particular transaction hash. Receipt indicate what has happened when the transaction + /// was included in block, so it contains logs and status, such as succesful or failed transaction. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getTransactionReceipt(_ txhash: Data) throws -> TransactionReceipt { + let result = try self.getTransactionReceiptPromise(txhash).wait() + return result + } + + /// Returns transaction receipt for particular transaction hash. Receipt indicate what has happened when the transaction + /// was included in block, so it contains logs and status, such as succesful or failed transaction. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getTransactionReceipt(_ txhash: String) throws -> TransactionReceipt { + let result = try self.getTransactionReceiptPromise(txhash).wait() + return result + } + + /// Estimates a minimal amount of gas required to run a transaction. To do it the Ethereum node tries to run it and counts + /// how much gas it consumes for computations. Setting the transaction gas limit lower than the estimate will most likely + /// result in a failing transaction. + /// + /// "onString" field determines if value is returned based on the state of a blockchain on the latest mined block ("latest") + /// or the expected state after all the transactions in memory pool are applied ("pending"). + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + /// Error can also indicate that transaction is invalid in the current state, so formally it's gas limit is infinite. + /// An example of such transaction can be sending an amount of ETH that is larger than the current account balance. + public func estimateGas(_ transaction: EthereumTransaction, transactionOptions: TransactionOptions?) throws -> BigUInt { + let result = try self.estimateGasPromise(transaction, transactionOptions: transactionOptions).wait() + return result + } + + /// Get a list of Ethereum accounts that a node knows about. + /// If one has attached a Keystore Manager to the web3 object it returns accounts known to the keystore. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getAccounts() throws -> [EthereumAddress] { + let result = try self.getAccountsPromise().wait() + return result + } + + + /// Get information about the particular block in Ethereum network. If "fullTransactions" parameter is set to "true" + /// this call fill do a virtual join and fetch not just transaction hashes from this block, + /// but full decoded EthereumTransaction objects. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getBlockByHash(_ hash: String, fullTransactions: Bool = false) throws -> Block { + let result = try self.getBlockByHashPromise(hash, fullTransactions: fullTransactions).wait() + return result + } + + /// Get information about the particular block in Ethereum network. If "fullTransactions" parameter is set to "true" + /// this call fill do a virtual join and fetch not just transaction hashes from this block, + /// but full decoded EthereumTransaction objects. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getBlockByHash(_ hash: Data, fullTransactions: Bool = false) throws -> Block { + let result = try self.getBlockByHashPromise(hash, fullTransactions: fullTransactions).wait() + return result + } + + /// Get information about the particular block in Ethereum network. If "fullTransactions" parameter is set to "true" + /// this call fill do a virtual join and fetch not just transaction hashes from this block, + /// but full decoded EthereumTransaction objects. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getBlockByNumber(_ number: UInt64, fullTransactions: Bool = false) throws -> Block { + let result = try self.getBlockByNumberPromise(number, fullTransactions: fullTransactions).wait() + return result + } + + /// Get information about the particular block in Ethereum network. If "fullTransactions" parameter is set to "true" + /// this call fill do a virtual join and fetch not just transaction hashes from this block, + /// but full decoded EthereumTransaction objects. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getBlockByNumber(_ number: BigUInt, fullTransactions: Bool = false) throws -> Block { + let result = try self.getBlockByNumberPromise(number, fullTransactions: fullTransactions).wait() + return result + } + + /// Get information about the particular block in Ethereum network. If "fullTransactions" parameter is set to "true" + /// this call fill do a virtual join and fetch not just transaction hashes from this block, + /// but full decoded EthereumTransaction objects. + /// + /// This function is synchronous! + /// + /// + public func getBlockByNumber(_ block:String, fullTransactions: Bool = false) throws -> Block { + let result = try self.getBlockByNumberPromise(block, fullTransactions: fullTransactions).wait() + return result + } + + + /** + Convenience wrapper to send Ethereum to another address. Internally it creates a virtual contract and encodes all the options and data. + - Parameters: + - to: EthereumAddress to send funds to + - amount: BigUInt indicating the amount in wei + - extraData: Additional data to attach to the transaction + - options: Web3Options to override the default gas price, gas limit. "Value" field of the options is ignored and the "amount" parameter is used instead + + - returns: + - TransactionIntermediate object + + */ + public func sendETH(to: EthereumAddress, amount: BigUInt, extraData: Data = Data(), transactionOptions: TransactionOptions? = nil) -> WriteTransaction? { + let contract = self.web3.contract(Web3.Utils.coldWalletABI, at: to, abiVersion: 2) + var mergedOptions = self.web3.transactionOptions.merge(transactionOptions) + mergedOptions.value = amount + let writeTX = contract?.write("fallback", extraData: extraData, transactionOptions: mergedOptions) + return writeTX + } + + /** + *Convenience wrapper to send Ethereum to another address. Internally it creates a virtual contract and encodes all the options and data.* + + - parameters: + - to: EthereumAddress to send funds to + - amount: String in "units" demonimation. It can contain either "," or "." decimal separator. + - units: Ethereum units indicating the denomination of amout about + - extraData: Additional data to attach to the transaction + - options: Web3Options to override the default gas price, gas limit. "Value" field of the options is ignored and the "amount" parameter is used instead + + - returns: + - TransactionIntermediate object + + * String "1.01" and units: .eth will result in sending 1.01 ETH to another address* + */ + public func sendETH(to: EthereumAddress, amount: String, units: Web3.Utils.Units = .eth, extraData: Data = Data(), transactionOptions: TransactionOptions? = nil) -> WriteTransaction? { + guard let value = Web3.Utils.parseToBigUInt(amount, units: .eth) else {return nil} + return sendETH(to: to, amount: value, extraData: extraData, transactionOptions: transactionOptions) + } + + /** + *Convenience wrapper to send Ethereum to another address. Internally it creates a virtual contract and encodes all the options and data.* + + - parameters: + - from: EthereumAddress to send funds from + - to: EthereumAddress to send funds to + - amount: String in "units" demonimation. It can contain either "," or "." decimal separator. + - units: Ethereum units indicating the denomination of amout about + - extraData: Additional data to attach to the transaction + - options: Web3Options to override the default gas price, gas limit. "Value" field of the options is ignored and the "amount" parameter is used instead. "From" parameter is also ignored. + + - returns: + - TransactionIntermediate object + + * String "1.01" and units: .eth will result in sending 1.01 ETH to another address* + */ + public func sendETH(from: EthereumAddress, to: EthereumAddress, amount: String, units: Web3.Utils.Units = .eth, extraData: Data = Data(), transactionOptions: TransactionOptions? = nil) -> WriteTransaction? { + guard let value = Web3.Utils.parseToBigUInt(amount, units: .eth) else {return nil} + var mergedOptions = self.web3.transactionOptions.merge(transactionOptions) + mergedOptions.from = from + return sendETH(to: to, amount: value, extraData: extraData, transactionOptions: mergedOptions) + } + + /** + *Convenience wrapper to send ERC20 tokens to another address. Internally it creates a virtual contract and encodes all the options and data. Assumes that the sender knows the decimal units of the underlying token.* + + - parameters: + - tokenAddress: EthereumAddress of the token contract + - from: EthereumAddress to send tokens from + - to: EthereumAddress to send tokens to + - amount: BigUInt indicating the number of tokens in the the smallest indivisible units (mind that sender knows the number of decimals) + - options: Web3Options to override the default gas price, gas limit. "Value" field of the options is ignored and the "amount" parameter is used instead. "From" parameter is also ignored. + + - returns: + - TransactionIntermediate object + + */ + public func sendERC20tokensWithKnownDecimals(tokenAddress: EthereumAddress, from: EthereumAddress, to: EthereumAddress, amount: BigUInt, transactionOptions: TransactionOptions? = nil) -> WriteTransaction? { + let contract = self.web3.contract(Web3.Utils.erc20ABI, at: tokenAddress, abiVersion: 2) + var mergedOptions = self.web3.transactionOptions.merge(transactionOptions) + mergedOptions.from = from + guard let writeTX = contract?.write("transfer", parameters: [to, amount] as [AnyObject], transactionOptions: mergedOptions) else {return nil} + return writeTX + } + + /** + *Convenience wrapper to send ERC20 tokens to another address. Internally it creates a virtual contract and encodes all the options and data. Pulls the number of decimals of the token under the hood.* + + - parameters: + - tokenAddress: EthereumAddress of the token contract + - from: EthereumAddress to send tokens from + - to: EthereumAddress to send tokens to + - amount: String in "natura" demonimation. It can contain either "," or "." decimal separator. + - options: Web3Options to override the default gas price, gas limit. "Value" field of the options is ignored and the "amount" parameter is used instead. "From" parameter is also ignored. + + - returns: + - TransactionIntermediate object + + - important: This call is synchronous + + * If the amount is "1.01" and token has 9 decimals it will result in sending 1010000000 of the smallest invidisible token units.* + */ + public func sendERC20tokensWithNaturalUnits(tokenAddress: EthereumAddress, from: EthereumAddress, to: EthereumAddress, amount: String, transactionOptions: TransactionOptions? = nil) throws -> WriteTransaction? { + let contract = self.web3.contract(Web3.Utils.erc20ABI, at: tokenAddress, abiVersion: 2) + var mergedOptions = self.web3.transactionOptions.merge(transactionOptions) + mergedOptions.from = from + let resp = try contract?.read("decimals", transactionOptions: mergedOptions)?.callPromise().wait() + var decimals = BigUInt(0) + guard let response = resp, let dec = response["0"], let decTyped = dec as? BigUInt else {return nil} + decimals = decTyped + let intDecimals = Int(decimals) + guard let value = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else {return nil} + return sendERC20tokensWithKnownDecimals(tokenAddress: tokenAddress, from: from, to: to, amount: value, transactionOptions: mergedOptions) + } + +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+EventParser.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+EventParser.swift new file mode 100755 index 000000000..2d22054f4 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+EventParser.swift @@ -0,0 +1,307 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +fileprivate typealias PromiseResult = PromiseKit.Result + +extension web3.web3contract { + /// An event parser to fetch events produced by smart-contract related transactions. Should not be constructed manually, but rather by calling the corresponding function on the web3contract object. + public struct EventParser: EventParserProtocol { + + public var contract: ContractProtocol + public var eventName: String + public var filter: EventFilter? + var web3: web3 + public init? (web3 web3Instance: web3, eventName: String, contract: ContractProtocol, filter: EventFilter? = nil) { +// guard let _ = contract.allEvents.index(of: eventName) else {return nil} + guard let _ = contract.allEvents.firstIndex(of: eventName) else {return nil} + self.eventName = eventName + self.web3 = web3Instance + self.contract = contract + self.filter = filter + } + + /** + *Parses the block for events matching the EventParser settings.* + + - parameters: + - blockNumber: Ethereum network block number + + - returns: + - Result object + + - important: This call is synchronous + + */ + public func parseBlockByNumber(_ blockNumber: UInt64) throws -> [EventParserResultProtocol] { + let result = try self.parseBlockByNumberPromise(blockNumber).wait() + return result + } + + /** + *Parses the block for events matching the EventParser settings.* + + - parameters: + - block: Native web3swift block object + + - returns: + - Result object + + - important: This call is synchronous + + */ + public func parseBlock(_ block: Block) throws -> [EventParserResultProtocol] { + let result = try self.parseBlockPromise(block).wait() + return result + } + + /** + *Parses the transaction for events matching the EventParser settings.* + + - parameters: + - hash: Transaction hash + + - returns: + - Result object + + - important: This call is synchronous + + */ + public func parseTransactionByHash(_ hash: Data) throws -> [EventParserResultProtocol] { + let result = try self.parseTransactionByHashPromise(hash).wait() + return result + } + + /** + *Parses the transaction for events matching the EventParser settings.* + + - parameters: + - transaction: web3swift native EthereumTransaction object + + - returns: + - Result object + + - important: This call is synchronous + + */ + public func parseTransaction(_ transaction: EthereumTransaction) throws -> [EventParserResultProtocol] { + let result = try self.parseTransactionPromise(transaction).wait() + return result + } + } +} + +extension web3.web3contract.EventParser { + public func parseTransactionPromise(_ transaction: EthereumTransaction) -> Promise<[EventParserResultProtocol]> { + let queue = self.web3.requestDispatcher.queue + do { + guard let hash = transaction.hash else { + throw Web3Error.processingError(desc: "Failed to get transaction hash")} + return self.parseTransactionByHashPromise(hash) + } catch { + let returnPromise = Promise<[EventParserResultProtocol]>.pending() + queue.async { + returnPromise.resolver.reject(error) + } + return returnPromise.promise + } + } + + public func parseTransactionByHashPromise(_ hash: Data) -> Promise<[EventParserResultProtocol]> { + let queue = self.web3.requestDispatcher.queue + return self.web3.eth.getTransactionReceiptPromise(hash).map(on:queue) {receipt throws -> [EventParserResultProtocol] in + guard let results = parseReceiptForLogs(receipt: receipt, contract: self.contract, eventName: self.eventName, filter: self.filter) else { + throw Web3Error.processingError(desc: "Failed to parse receipt for events") + } + return results + } + } + + public func parseBlockByNumberPromise(_ blockNumber: UInt64) -> Promise<[EventParserResultProtocol]> { + let queue = self.web3.requestDispatcher.queue + do { + if self.filter != nil && (self.filter?.fromBlock != nil || self.filter?.toBlock != nil) { + throw Web3Error.inputError(desc: "Can not mix parsing specific block and using block range filter") + } + return self.web3.eth.getBlockByNumberPromise(blockNumber).then(on: queue) {res in + return self.parseBlockPromise(res) + } + } catch { + let returnPromise = Promise<[EventParserResultProtocol]>.pending() + queue.async { + returnPromise.resolver.reject(error) + } + return returnPromise.promise + } + } + + public func parseBlockPromise(_ block: Block) -> Promise<[EventParserResultProtocol]> { + let queue = self.web3.requestDispatcher.queue + do { + guard let bloom = block.logsBloom else { + throw Web3Error.processingError(desc: "Block doesn't have a bloom filter log") + } + if self.contract.address != nil { + let addressPresent = block.logsBloom?.test(topic: self.contract.address!.addressData) + if (addressPresent != true) { + let returnPromise = Promise<[EventParserResultProtocol]>.pending() + queue.async { + returnPromise.resolver.fulfill([EventParserResultProtocol]()) + } + return returnPromise.promise + } + } + guard let eventOfSuchTypeIsPresent = self.contract.testBloomForEventPrecence(eventName: self.eventName, bloom: bloom) else { + throw Web3Error.processingError(desc: "Error processing bloom for events") + } + if (!eventOfSuchTypeIsPresent) { + let returnPromise = Promise<[EventParserResultProtocol]>.pending() + queue.async { + returnPromise.resolver.fulfill([EventParserResultProtocol]()) + } + return returnPromise.promise + } + return Promise {seal in + + var pendingEvents : [Promise<[EventParserResultProtocol]>] = [Promise<[EventParserResultProtocol]>]() + for transaction in block.transactions { + switch transaction { + case .null: + seal.reject(Web3Error.processingError(desc: "No information about transactions in block")) + return + case .transaction(let tx): + guard let hash = tx.hash else { + seal.reject(Web3Error.processingError(desc: "Failed to get transaction hash")) + return + } + let subresultPromise = self.parseTransactionByHashPromise(hash) + pendingEvents.append(subresultPromise) + case .hash(let hash): + let subresultPromise = self.parseTransactionByHashPromise(hash) + pendingEvents.append(subresultPromise) + } + } + when(resolved: pendingEvents).done(on: queue){ (results:[PromiseResult<[EventParserResultProtocol]>]) throws in + var allResults = [EventParserResultProtocol]() + for res in results { + guard case .fulfilled(let subresult) = res else { + throw Web3Error.processingError(desc: "Failed to parse event for one transaction in block") + } + allResults.append(contentsOf: subresult) + } + seal.fulfill(allResults) + }.catch(on:queue) {err in + seal.reject(err) + } + } + } catch { +// let returnPromise = Promise<[EventParserResultProtocol]>.pending() +// queue.async { +// returnPromise.resolver.fulfill([EventParserResultProtocol]()) +// } +// return returnPromise.promise + let returnPromise = Promise<[EventParserResultProtocol]>.pending() + queue.async { + returnPromise.resolver.reject(error) + } + return returnPromise.promise + } + } + +} + +extension web3.web3contract { + + /** + *Fetches events by doing a lookup on "indexed" parameters of the event. Smart-contract developer can make some of event values "indexed" for such fast queries.* + + - parameters: + - eventName: Event name, should be present in ABI interface of the contract + - filter: EventFilter object setting the block limits for query + - joinWithReceipts: Bool indicating whether TransactionReceipt should be fetched separately for every matched transaction + + - returns: + - Result object + + - important: This call is synchronous + + */ + public func getIndexedEvents(eventName: String?, filter: EventFilter, joinWithReceipts: Bool = false) throws -> [EventParserResultProtocol] { + let result = try self.getIndexedEventsPromise(eventName: eventName, filter: filter, joinWithReceipts: joinWithReceipts).wait() + return result + } +} + +extension web3.web3contract { + public func getIndexedEventsPromise(eventName: String?, filter: EventFilter, joinWithReceipts: Bool = false) -> Promise<[EventParserResultProtocol]> { + let queue = self.web3.requestDispatcher.queue + do { + let rawContract = self.contract + guard let preEncoding = encodeTopicToGetLogs(contract: rawContract, eventName: eventName, filter: filter) else { + throw Web3Error.processingError(desc: "Failed to encode topic for request") + } + + if eventName != nil { + guard let _ = rawContract.events[eventName!] else { + throw Web3Error.processingError(desc: "No such event in a contract") + } + } + let request = JSONRPCRequestFabric.prepareRequest(.getLogs, parameters: [preEncoding]) + let fetchLogsPromise = self.web3.dispatch(request).map(on: queue) {response throws -> [EventParserResult] in + guard let value: [EventLog] = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Empty or malformed response") + } + let allLogs = value + let decodedLogs = allLogs.compactMap({ (log) -> EventParserResult? in + let (n, d) = self.contract.parseEvent(log) + 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 + }).filter{ (res:EventParserResult?) -> Bool in + if eventName != nil { + if res != nil && res?.eventName == eventName && res!.eventLog != nil { + return true + } + } else { + if res != nil && res!.eventLog != nil { + return true + } + } + return false + } + return decodedLogs + } + if (!joinWithReceipts) { + return fetchLogsPromise.mapValues(on: queue) {res -> EventParserResultProtocol in + return res as EventParserResultProtocol + } + } + return fetchLogsPromise.thenMap(on:queue) {singleEvent in + return self.web3.eth.getTransactionReceiptPromise(singleEvent.eventLog!.transactionHash).map(on: queue) { receipt in + var joinedEvent = singleEvent + joinedEvent.transactionReceipt = receipt + return joinedEvent as EventParserResultProtocol + } + } + } catch { + let returnPromise = Promise<[EventParserResultProtocol]>.pending() + queue.async { + returnPromise.resolver.reject(error) + } + return returnPromise.promise + } + } +} + + + + diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Eventloop.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Eventloop.swift new file mode 100755 index 000000000..d59a0e9e4 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Eventloop.swift @@ -0,0 +1,103 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +extension web3.Eventloop { + +// @available(iOS 10.0, *) + public func start(_ timeInterval: TimeInterval) { + if self.timer != nil { + self.timer!.suspend() + self.timer = nil + } + let queue = self.web3.requestDispatcher.queue + queue.async { + self.timer = RepeatingTimer(timeInterval: timeInterval) + self.timer?.eventHandler = self.runnable + self.timer?.resume() + } + } + + public func stop() { + if self.timer != nil { + self.timer!.suspend() + self.timer = nil + } + } + + func runnable() { + for prop in self.monitoredProperties { + let queue = prop.queue + let function = prop.calledFunction + queue.async { + function(self.web3) + } + } + + for prop in self.monitoredUserFunctions { + let queue = prop.queue + queue.async { + prop.functionToRun() + } + } + } +} + +// Thank you https://medium.com/@danielgalasko/a-background-repeating-timer-in-swift-412cecfd2ef9 +class RepeatingTimer { + + let timeInterval: TimeInterval + + init(timeInterval: TimeInterval) { + self.timeInterval = timeInterval + } + + private lazy var timer: DispatchSourceTimer = { + let t = DispatchSource.makeTimerSource() + t.schedule(deadline: .now() + self.timeInterval, repeating: self.timeInterval) + t.setEventHandler(handler: { [weak self] in + self?.eventHandler?() + }) + return t + }() + + var eventHandler: (() -> Void)? + + private enum State { + case suspended + case resumed + } + + private var state: State = .suspended + + deinit { + timer.setEventHandler {} + timer.cancel() + /* + If the timer is suspended, calling cancel without resuming + triggers a crash. This is documented here https://forums.developer.apple.com/thread/15902 + */ + resume() + eventHandler = nil + } + + func resume() { + if state == .resumed { + return + } + state = .resumed + timer.resume() + } + + func suspend() { + if state == .suspended { + return + } + state = .suspended + timer.suspend() + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+HttpProvider.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+HttpProvider.swift new file mode 100755 index 000000000..683f7d36e --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+HttpProvider.swift @@ -0,0 +1,57 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit + +/// Providers abstraction for custom providers (websockets, other custom private key managers). At the moment should not be used. +public protocol Web3Provider { + func sendAsync(_ request: JSONRPCrequest, queue: DispatchQueue) -> Promise + func sendAsync(_ requests: JSONRPCrequestBatch, queue: DispatchQueue) -> Promise + var network: Networks? {get set} + var attachedKeystoreManager: KeystoreManager? {get set} + var url: URL {get} + var session: URLSession {get} +} + + +/// The default http provider. +public class Web3HttpProvider: Web3Provider { + public var url: URL + public var network: Networks? + public var attachedKeystoreManager: KeystoreManager? = nil + public var session: URLSession = {() -> URLSession in + let config = URLSessionConfiguration.default + let urlSession = URLSession(configuration: config) + return urlSession + }() + public init?(_ httpProviderURL: URL, network net: Networks? = nil, keystoreManager manager: KeystoreManager? = nil) { + do { + guard httpProviderURL.scheme == "http" || httpProviderURL.scheme == "https" else {return nil} + url = httpProviderURL + if net == nil { + let request = JSONRPCRequestFabric.prepareRequest(.getNetwork, parameters: []) + let response = try Web3HttpProvider.post(request, providerURL: httpProviderURL, queue: DispatchQueue.global(qos: .userInteractive), session: session).wait() + if response.error != nil { + if response.message != nil { + print(response.message!) + } + return nil + } + guard let result: String = response.getValue(), let intNetworkNumber = Int(result) else {return nil} + network = Networks.fromInt(intNetworkNumber) + if network == nil {return nil} + } else { + network = net + } + } catch { + return nil + } + attachedKeystoreManager = manager + } +} + diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+InfuraProviders.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+InfuraProviders.swift new file mode 100755 index 000000000..a3a26ace4 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+InfuraProviders.swift @@ -0,0 +1,275 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// +import Foundation +import BigInt +import Starscream + +public enum BlockNumber { + case pending + case latest + case earliest + case exact(BigUInt) + + public var stringValue: String { + switch self { + case .pending: + return "pending" + case .latest: + return "latest" + case .earliest: + return "earliest" + case .exact(let number): + return String(number, radix: 16).addHexPrefix() + } + } +} + +/// Custom Web3 HTTP provider of Infura nodes. +public final class InfuraProvider: Web3HttpProvider { + public init?(_ net:Networks, accessToken token: String? = nil, keystoreManager manager: KeystoreManager? = nil) { + var requestURLstring = "https://" + net.name + Constants.infuraHttpScheme + requestURLstring += token != nil ? token! : Constants.infuraToken + let providerURL = URL(string: requestURLstring) + super.init(providerURL!, network: net, keystoreManager: manager) + } +} + +/// Custom Websocket provider of Infura nodes. +public final class InfuraWebsocketProvider: WebsocketProvider { + public var filterID: String? + public var subscriptionIDs = Set() + private var subscriptionIDforUnsubscribing: String? = nil + private var filterTimer: Timer? + + public init?(_ network: Networks, + delegate: Web3SocketDelegate, + projectId: String? = nil, + keystoreManager manager: KeystoreManager? = nil) { + guard network == Networks.Kovan + || network == Networks.Rinkeby + || network == Networks.Ropsten + || network == Networks.Mainnet else {return nil} + let networkName = network.name + let urlString = "wss://" + networkName + Constants.infuraWsScheme + guard URL(string: urlString) != nil else {return nil} + super.init(urlString, + delegate: delegate, + projectId: projectId, + keystoreManager: manager, + network: network) + } + + public init?(_ endpoint: String, + delegate: Web3SocketDelegate, + projectId: String? = nil, + keystoreManager manager: KeystoreManager? = nil) { + guard URL(string: endpoint) != nil else {return nil} + super.init(endpoint, + delegate: delegate, + projectId: projectId, + keystoreManager: manager) + } + + public init?(_ endpoint: URL, + delegate: Web3SocketDelegate, + projectId: String? = nil, + keystoreManager manager: KeystoreManager? = nil) { + super.init(endpoint, + delegate: delegate, + projectId: projectId, + keystoreManager: manager) + } + + override public class func connectToSocket(_ endpoint: String, + delegate: Web3SocketDelegate, + projectId: String? = nil, + keystoreManager manager: KeystoreManager? = nil, + network net: Networks? = nil) -> WebsocketProvider? { + guard let socketProvider = InfuraWebsocketProvider(endpoint, + delegate: delegate, + projectId: projectId, + keystoreManager: manager) else {return nil} + socketProvider.connectSocket() + return socketProvider + } + + override public class func connectToSocket(_ endpoint: URL, + delegate: Web3SocketDelegate, + projectId: String? = nil, + keystoreManager manager: KeystoreManager? = nil, + network net: Networks? = nil) -> WebsocketProvider? { + guard let socketProvider = InfuraWebsocketProvider(endpoint, + delegate: delegate, + projectId: projectId, + keystoreManager: manager) else {return nil} + socketProvider.connectSocket() + return socketProvider + } + + public static func connectToInfuraSocket(_ network: Networks, + delegate: Web3SocketDelegate, + projectId: String? = nil, + keystoreManager manager: KeystoreManager? = nil) -> InfuraWebsocketProvider? { + guard let socketProvider = InfuraWebsocketProvider(network, + delegate: delegate, + projectId: projectId, + keystoreManager: manager) else {return nil} + socketProvider.connectSocket() + return socketProvider + } + + public func writeMessage(method: InfuraWebsocketMethod, params: [Encodable]) throws { + let request = JSONRPCRequestFabric.prepareRequest(method, parameters: params) + let encoder = JSONEncoder() + let requestData = try encoder.encode(request) + print(String(decoding: requestData, as: UTF8.self)) + writeMessage(requestData) + } + + public func setFilterAndGetChanges(method: InfuraWebsocketMethod, params: [Encodable]? = nil) throws { + filterTimer?.invalidate() + filterID = nil + let params = params ?? [] + let paramsCount = params.count + guard method.requiredNumOfParameters == paramsCount || method.requiredNumOfParameters == nil else { + throw Web3Error.inputError(desc: "Wrong number of params: need - \(method.requiredNumOfParameters!), got - \(paramsCount)") + } + try writeMessage(method: method, params: params) + filterTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(getFilterChanges), userInfo: nil, repeats: true) + } + + public func setFilterAndGetChanges(method: InfuraWebsocketMethod, address: EthereumAddress? = nil, fromBlock: BlockNumber? = nil, toBlock: BlockNumber? = nil, topics: [String]? = nil) throws { + let filterParams = EventFilterParameters(fromBlock: fromBlock?.stringValue, toBlock: toBlock?.stringValue, topics: [topics], address: [address?.address]) + try setFilterAndGetChanges(method: method, params: [filterParams]) + } + + public func setFilterAndGetLogs(method: InfuraWebsocketMethod, params: [Encodable]? = nil) throws { + filterTimer?.invalidate() + filterID = nil + let params = params ?? [] + let paramsCount = params.count + guard method.requiredNumOfParameters == paramsCount || method.requiredNumOfParameters == nil else { + throw Web3Error.inputError(desc: "Wrong number of params: need - \(method.requiredNumOfParameters!), got - \(paramsCount)") + } + try writeMessage(method: method, params: params) + filterTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(getFilterLogs), userInfo: nil, repeats: true) + } + + public func setFilterAndGetLogs(method: InfuraWebsocketMethod, address: EthereumAddress? = nil, fromBlock: BlockNumber? = nil, toBlock: BlockNumber? = nil, topics: [String]? = nil) throws { + let filterParams = EventFilterParameters(fromBlock: fromBlock?.stringValue, toBlock: toBlock?.stringValue, topics: [topics], address: [address?.address]) + try setFilterAndGetLogs(method: method, params: [filterParams]) + } + + @objc public func getFilterChanges() throws { + if let id = filterID { + filterTimer?.invalidate() + let method = InfuraWebsocketMethod.getFilterChanges + try writeMessage(method: method, params: [id]) + } + } + + @objc public func getFilterLogs() throws { + if let id = filterID { + filterTimer?.invalidate() + let method = InfuraWebsocketMethod.getFilterLogs + try writeMessage(method: method, params: [id]) + } + } + + public func getFilterLogs(address: EthereumAddress? = nil, fromBlock: BlockNumber? = nil, toBlock: BlockNumber? = nil, topics: [String]? = nil) throws { + if let id = filterID { + let filterParams = EventFilterParameters(fromBlock: fromBlock?.stringValue, toBlock: toBlock?.stringValue, topics: [topics], address: [address?.address]) + let method = InfuraWebsocketMethod.getFilterLogs + try writeMessage(method: method, params: [id, filterParams]) + } + } + + public func unistallFilter() throws { + if let id = filterID { + filterID = nil + let method = InfuraWebsocketMethod.uninstallFilter + try writeMessage(method: method, params: [id]) + } else { + throw Web3Error.nodeError(desc: "No filter set") + } + } + + public func subscribe(params: [Encodable]) throws { + let method = InfuraWebsocketMethod.subscribe + try writeMessage(method: method, params: params) + } + + public func unsubscribe(subscriptionID: String) throws { + let method = InfuraWebsocketMethod.unsubscribe + subscriptionIDforUnsubscribing = subscriptionID + try writeMessage(method: method, params: [subscriptionID]) + } + + public func subscribeOnNewHeads() throws { + let method = InfuraWebsocketMethod.subscribe + let params = ["newHeads"] + try writeMessage(method: method, params: params) + } + + public func subscribeOnLogs(addresses: [EthereumAddress]? = nil, topics: [String]? = nil) throws { + let method = InfuraWebsocketMethod.subscribe + var stringAddresses = [String]() + if let addrs = addresses { + for addr in addrs { + stringAddresses.append(addr.address) + } + } +// let ts = topics == nil ? nil : [topics!] + let filterParams = EventFilterParameters(fromBlock: nil, toBlock: nil, topics: [topics], address: stringAddresses) + try writeMessage(method: method, params: ["logs", filterParams]) + } + + public func subscribeOnNewPendingTransactions() throws { + let method = InfuraWebsocketMethod.subscribe + let params = ["newPendingTransactions"] + try writeMessage(method: method, params: params) + } + + public func subscribeOnSyncing() throws { + guard network != Networks.Kovan else { + throw Web3Error.inputError(desc: "Can't sync on Kovan") + } + let method = InfuraWebsocketMethod.subscribe + let params = ["syncing"] + try writeMessage(method: method, params: params) + } + + override public func websocketDidReceiveMessage(socket: WebSocketClient, text: String) { + if let data = text.data(using: String.Encoding.utf8), + let dictionary = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] { + if filterID == nil, + let result = dictionary["result"] as? String { + // setting filter id + filterID = result + } else if let params = dictionary["params"] as? [String: Any], + let subscription = params["subscription"] as? String, + let result = params["result"] { + // subscription result + subscriptionIDs.insert(subscription) + delegate.received(message: result) + } else if let unsubscribed = dictionary["result"] as? Bool { + // unsubsribe result + if unsubscribed == true, let id = subscriptionIDforUnsubscribing { + subscriptionIDs.remove(id) + } else if let id = subscriptionIDforUnsubscribing { + delegate.gotError(error: Web3Error.processingError(desc: "Can\'t unsubscribe \(id)")) + } else { + delegate.received(message: unsubscribed) + } + } else if let message = dictionary["result"] { + // filter result + delegate.received(message: message) + } else { + delegate.gotError(error: Web3Error.processingError(desc: "Can\'t get known result. Message is: \(text)")) + } + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Instance.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Instance.swift new file mode 100755 index 000000000..f87c354c5 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Instance.swift @@ -0,0 +1,229 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit + +/// A web3 instance bound to provider. All further functionality is provided under web.*. namespaces. +public class web3 { + public var provider : Web3Provider + public var transactionOptions: TransactionOptions = TransactionOptions.defaultOptions + public var defaultBlock = "latest" + public var requestDispatcher: JSONRPCrequestDispatcher + + /// Add a provider request to the dispatch queue. + public func dispatch(_ request: JSONRPCrequest) -> Promise { + return self.requestDispatcher.addToQueue(request: request) + } + + /// Raw initializer using a Web3Provider protocol object, dispatch queue and request dispatcher. + public init(provider prov: Web3Provider, queue: OperationQueue? = nil, requestDispatcher: JSONRPCrequestDispatcher? = nil) { + provider = prov + if requestDispatcher == nil { + self.requestDispatcher = JSONRPCrequestDispatcher(provider: provider, queue: DispatchQueue.global(qos: .userInteractive), policy: .Batch(32)) + } else { + self.requestDispatcher = requestDispatcher! + } + } + + /// Keystore manager can be bound to Web3 instance. If some manager is bound all further account related functions, such + /// as account listing, transaction signing, etc. are done locally using private keys and accounts found in a manager. + public func addKeystoreManager(_ manager: KeystoreManager?) { + self.provider.attachedKeystoreManager = manager + } + + var ethInstance: web3.Eth? + + /// Public web3.eth.* namespace. + public var eth: web3.Eth { + if (self.ethInstance != nil) { + return self.ethInstance! + } + self.ethInstance = web3.Eth(provider : self.provider, web3: self) + return self.ethInstance! + } + + public class Eth:TransactionOptionsInheritable { + var provider:Web3Provider +// weak var web3: web3? + var web3: web3 + public var transactionOptions: TransactionOptions { + return self.web3.transactionOptions + } + public init(provider prov: Web3Provider, web3 web3instance: web3) { + provider = prov + web3 = web3instance + } + } + + var personalInstance: web3.Personal? + + /// 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! + } + + public class Personal:TransactionOptionsInheritable { + var provider:Web3Provider + // weak var web3: web3? + var web3: web3 + public var transactionOptions: TransactionOptions { + return self.web3.transactionOptions + } + public init(provider prov: Web3Provider, web3 web3instance: web3) { + provider = prov + web3 = web3instance + } + } + + var txPoolInstance: web3.TxPool? + + /// 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! + } + + public class TxPool: TransactionOptionsInheritable { + var provider:Web3Provider + // weak var web3: web3? + var web3: web3 + public var transactionOptions: TransactionOptions { + return self.web3.transactionOptions + } + public init(provider prov: Web3Provider, web3 web3instance: web3) { + provider = prov + web3 = web3instance + } + } + + var walletInstance: web3.Web3Wallet? + + /// 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! + } + + public class Web3Wallet { + var provider:Web3Provider +// weak var web3: web3? + var web3: web3 + public init(provider prov: Web3Provider, web3 web3instance: web3) { + provider = prov + web3 = web3instance + } + } + + var browserFunctionsInstance: web3.BrowserFunctions? + + /// 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! + } + + public class BrowserFunctions:TransactionOptionsInheritable { + var provider:Web3Provider + // weak var web3: web3? + var web3: web3 + public var transactionOptions: TransactionOptions { + return self.web3.transactionOptions + } + public init(provider prov: Web3Provider, web3 web3instance: web3) { + provider = prov + web3 = web3instance + } + } + + var eventLoopInstance: web3.Eventloop? + + /// 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! + } + + public class Eventloop: TransactionOptionsInheritable { + + public typealias EventLoopCall = (web3) -> Void + public typealias EventLoopContractCall = (web3contract) -> Void + + public struct MonitoredProperty { + public var name: String + public var queue: DispatchQueue + public var calledFunction: EventLoopCall + } + +// public struct MonitoredContract { +// public var name: String +// public var queue: DispatchQueue +// public var calledFunction: EventLoopContractCall +// } + + var provider:Web3Provider + // weak var web3: web3? + var web3: web3 + var timer: RepeatingTimer? = nil + + public var monitoredProperties: [MonitoredProperty] = [MonitoredProperty]() +// public var monitoredContracts: [MonitoredContract] = [MonitoredContract]() + public var monitoredUserFunctions: [EventLoopRunnableProtocol] = [EventLoopRunnableProtocol]() + + public var transactionOptions: TransactionOptions { + return self.web3.transactionOptions + } + public init(provider prov: Web3Provider, web3 web3instance: web3) { + provider = prov + web3 = web3instance + } + } + + public typealias AssemblyHookFunction = ((EthereumTransaction, EthereumContract, TransactionOptions)) -> (EthereumTransaction, EthereumContract, TransactionOptions, Bool) + + public typealias SubmissionHookFunction = ((EthereumTransaction, TransactionOptions)) -> (EthereumTransaction, TransactionOptions, Bool) + + public typealias SubmissionResultHookFunction = (TransactionSendingResult) -> () + + public struct AssemblyHook { + public var queue: DispatchQueue + public var function: AssemblyHookFunction + } + + public struct SubmissionHook { + public var queue: DispatchQueue + public var function: SubmissionHookFunction + } + + public struct SubmissionResultHook { + public var queue: DispatchQueue + 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/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+JSONRPC.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+JSONRPC.swift new file mode 100755 index 000000000..283ecbaf6 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+JSONRPC.swift @@ -0,0 +1,278 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +/// Global counter object to enumerate JSON RPC requests. +public struct Counter { + public static var counter = UInt64(1) + public static var lockQueue = DispatchQueue(label: "counterQueue") + public static func increment() -> UInt64 { + var c:UInt64 = 0 + lockQueue.sync { + c = Counter.counter + Counter.counter = Counter.counter + 1 + } + return c + } +} + +/// JSON RPC request structure for serialization and deserialization purposes. +public struct JSONRPCrequest: Encodable { + public var jsonrpc: String = "2.0" + public var method: JSONRPCmethod? + public var params: JSONRPCparams? + public var id: UInt64 = Counter.increment() + + enum CodingKeys: String, CodingKey { + case jsonrpc + case method + case params + case id + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(jsonrpc, forKey: .jsonrpc) + try container.encode(method?.rawValue, forKey: .method) + try container.encode(params, forKey: .params) + try container.encode(id, forKey: .id) + } + + public var isValid: Bool { + get { + if self.method == nil { + return false + } + guard let method = self.method else {return false} + return method.requiredNumOfParameters == self.params?.params.count + } + } +} + +/// JSON RPC batch request structure for serialization and deserialization purposes. +public struct JSONRPCrequestBatch: Encodable { + var requests: [JSONRPCrequest] + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(self.requests) + } +} + +/// JSON RPC response structure for serialization and deserialization purposes. +public struct JSONRPCresponse: Decodable{ + public var id: Int + public var jsonrpc = "2.0" + public var result: Any? + public var error: ErrorMessage? + public var message: String? + + enum JSONRPCresponseKeys: String, CodingKey { + case id = "id" + case jsonrpc = "jsonrpc" + case result = "result" + case error = "error" + } + + public init(id: Int, jsonrpc: String, result: Any?, error: ErrorMessage?) { + self.id = id + self.jsonrpc = jsonrpc + self.result = result + self.error = error + } + + public struct ErrorMessage: Decodable { + public var code: Int + public var message: String + } + + internal var decodableTypes: [Decodable.Type] = [[EventLog].self, + [TransactionDetails].self, + [TransactionReceipt].self, + [Block].self, + [String].self, + [Int].self, + [Bool].self, + EventLog.self, + TransactionDetails.self, + TransactionReceipt.self, + Block.self, + String.self, + Int.self, + Bool.self, + [String:String].self, + [String:Int].self, + [String:[String:[String:[String]]]].self] + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: JSONRPCresponseKeys.self) + let id: Int = try container.decode(Int.self, forKey: .id) + let jsonrpc: String = try container.decode(String.self, forKey: .jsonrpc) + let errorMessage = try container.decodeIfPresent(ErrorMessage.self, forKey: .error) + if errorMessage != nil { + self.init(id: id, jsonrpc: jsonrpc, result: nil, error: errorMessage) + return + } + var result: Any? = nil + if let rawValue = try? container.decodeIfPresent(String.self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent(Int.self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent(Bool.self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent(EventLog.self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent(Block.self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent(TransactionReceipt.self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent(TransactionDetails.self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent([EventLog].self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent([Block].self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent([TransactionReceipt].self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent([TransactionDetails].self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent(TxPoolStatus.self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent(TxPoolContent.self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent([Bool].self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent([Int].self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent([String].self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent([String: String].self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent([String: Int].self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent([String:[String:[String:String]]].self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent([String:[String:[String:[String:String?]]]].self, forKey: .result) { + result = rawValue + } + self.init(id: id, jsonrpc: jsonrpc, result: result, error: nil) + } + + /// Get the JSON RCP reponse value by deserializing it into some native class. + /// + /// Returns nil if serialization fails + public func getValue() -> T? { + let slf = T.self + if slf == BigUInt.self { + guard let string = self.result as? String else {return nil} + guard let value = BigUInt(string.stripHexPrefix(), radix: 16) else {return nil} + return value as? T + } else if slf == BigInt.self { + guard let string = self.result as? String else {return nil} + guard let value = BigInt(string.stripHexPrefix(), radix: 16) else {return nil} + return value as? T + } else if slf == Data.self { + guard let string = self.result as? String else {return nil} + guard let value = Data.fromHex(string) else {return nil} + return value as? T + } else if slf == EthereumAddress.self { + guard let string = self.result as? String else {return nil} + guard let value = EthereumAddress(string, ignoreChecksum: true) else {return nil} + return value as? T + } +// else if slf == String.self { +// guard let value = self.result as? T else {return nil} +// return value +// } else if slf == Int.self { +// guard let value = self.result as? T else {return nil} +// return value +// } + else if slf == [BigUInt].self { + guard let string = self.result as? [String] else {return nil} + let values = string.compactMap { (str) -> BigUInt? in + return BigUInt(str.stripHexPrefix(), radix: 16) + } + return values as? T + } else if slf == [BigInt].self { + guard let string = self.result as? [String] else {return nil} + let values = string.compactMap { (str) -> BigInt? in + return BigInt(str.stripHexPrefix(), radix: 16) + } + return values as? T + } else if slf == [Data].self { + guard let string = self.result as? [String] else {return nil} + let values = string.compactMap { (str) -> Data? in + return Data.fromHex(str) + } + return values as? T + } else if slf == [EthereumAddress].self { + guard let string = self.result as? [String] else {return nil} + let values = string.compactMap { (str) -> EthereumAddress? in + return EthereumAddress(str, ignoreChecksum: true) + } + return values as? T + } + guard let value = self.result as? T else {return nil} + return value + } +} + +/// JSON RPC batch response structure for serialization and deserialization purposes. +public struct JSONRPCresponseBatch: Decodable { + var responses: [JSONRPCresponse] + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + let responses = try container.decode([JSONRPCresponse].self) + self.responses = responses + } +} + +/// Transaction parameters JSON structure for interaction with Ethereum node. +public struct TransactionParameters: Codable { + public var data: String? + public var from: String? + public var gas: String? + public var gasPrice: String? + public var to: String? + public var value: String? = "0x0" + + public init(from _from:String?, to _to:String?) { + from = _from + to = _to + } +} + +/// Event filter parameters JSON structure for interaction with Ethereum node. +public struct EventFilterParameters: Codable { + public var fromBlock: String? + public var toBlock: String? + public var topics: [[String?]?]? + public var address: [String?]? +} + +/// Raw JSON RCP 2.0 internal flattening wrapper. +public struct JSONRPCparams: Encodable{ + public var params = [Any]() + + public func encode(to encoder: Encoder) throws { + var container = encoder.unkeyedContainer() + for par in params { + if let p = par as? TransactionParameters { + try container.encode(p) + } else if let p = par as? String { + try container.encode(p) + } else if let p = par as? Bool { + try container.encode(p) + } else if let p = par as? EventFilterParameters { + try container.encode(p) + } + } + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Methods.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Methods.swift new file mode 100755 index 000000000..f3ab0f28b --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Methods.swift @@ -0,0 +1,90 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +public enum JSONRPCmethod: String, Encodable { + + case gasPrice = "eth_gasPrice" + case blockNumber = "eth_blockNumber" + case getNetwork = "net_version" + case sendRawTransaction = "eth_sendRawTransaction" + case sendTransaction = "eth_sendTransaction" + case estimateGas = "eth_estimateGas" + case call = "eth_call" + case getTransactionCount = "eth_getTransactionCount" + case getBalance = "eth_getBalance" + case getCode = "eth_getCode" + case getStorageAt = "eth_getStorageAt" + case getTransactionByHash = "eth_getTransactionByHash" + case getTransactionReceipt = "eth_getTransactionReceipt" + case getAccounts = "eth_accounts" + case getBlockByHash = "eth_getBlockByHash" + case getBlockByNumber = "eth_getBlockByNumber" + case personalSign = "eth_sign" + case unlockAccount = "personal_unlockAccount" + case createAccount = "personal_createAccount" + case getLogs = "eth_getLogs" + case getTxPoolInspect = "txpool_inspect" + case getTxPoolStatus = "txpool_status" + case getTxPoolContent = "txpool_content" + + + public var requiredNumOfParameters: Int { + get { + switch self { + case .call: + return 2 + case .getTransactionCount: + return 2 + case .getBalance: + return 2 + case .getStorageAt: + return 2 + case .getCode: + return 2 + case .getBlockByHash: + return 2 + case .getBlockByNumber: + return 2 + case .gasPrice: + return 0 + case .blockNumber: + return 0 + case .getNetwork: + return 0 + case .getAccounts: + return 0 + case .getTxPoolStatus: + return 0 + case .getTxPoolContent: + return 0 + case .getTxPoolInspect: + return 0 + default: + return 1 + } + } + } +} + +public struct JSONRPCRequestFabric { + public static func prepareRequest(_ method: JSONRPCmethod, parameters: [Encodable]) -> JSONRPCrequest { + var request = JSONRPCrequest() + request.method = method + let pars = JSONRPCparams(params: parameters) + request.params = pars + return request + } + + public static func prepareRequest(_ method: InfuraWebsocketMethod, parameters: [Encodable]) -> InfuraWebsocketRequest { + var request = InfuraWebsocketRequest() + request.method = method + let pars = JSONRPCparams(params: parameters) + request.params = pars + return request + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+MutatingTransaction.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+MutatingTransaction.swift new file mode 100755 index 000000000..75bfc87e1 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+MutatingTransaction.swift @@ -0,0 +1,170 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +fileprivate typealias PromiseResult = PromiseKit.Result +//import EthereumAddress + +public class WriteTransaction: ReadTransaction { + + public func assemblePromise(transactionOptions: TransactionOptions? = nil) -> Promise { + var assembledTransaction : EthereumTransaction = self.transaction + let queue = self.web3.requestDispatcher.queue + let returnPromise = Promise { seal in + if self.method != "fallback" { + let m = self.contract.methods[self.method] + if m == nil { + seal.reject(Web3Error.inputError(desc: "Contract's ABI does not have such method")) + return + } + switch m! { + case .function(let function): + if function.constant { + seal.reject(Web3Error.inputError(desc: "Trying to transact to the constant function")) + return + } + case .constructor(_): + break + default: + seal.reject(Web3Error.inputError(desc: "Contract's ABI does not have such method")) + return + } + } + + var mergedOptions = self.transactionOptions.merge(transactionOptions) + if mergedOptions.value != nil { + assembledTransaction.value = mergedOptions.value! + } + var forAssemblyPipeline : (EthereumTransaction, EthereumContract, TransactionOptions) = (assembledTransaction, self.contract, mergedOptions) + + for hook in self.web3.preAssemblyHooks { + let prom : Promise = Promise {seal in + hook.queue.async { + let hookResult = hook.function(forAssemblyPipeline) + if hookResult.3 { + forAssemblyPipeline = (hookResult.0, hookResult.1, hookResult.2) + } + seal.fulfill(hookResult.3) + } + } + let shouldContinue = try prom.wait() + if !shouldContinue { + seal.reject(Web3Error.processingError(desc: "Transaction is canceled by middleware")) + return + } + } + + assembledTransaction = forAssemblyPipeline.0 + mergedOptions = forAssemblyPipeline.2 + + guard let from = mergedOptions.from else { + seal.reject(Web3Error.inputError(desc: "No 'from' field provided")) + return + } + + // assemble promise for gas estimation + var optionsForGasEstimation = TransactionOptions() + optionsForGasEstimation.from = mergedOptions.from + optionsForGasEstimation.to = mergedOptions.to + optionsForGasEstimation.value = mergedOptions.value + optionsForGasEstimation.callOnBlock = mergedOptions.callOnBlock + let gasEstimatePromise : Promise = self.web3.eth.estimateGasPromise(assembledTransaction, transactionOptions: optionsForGasEstimation) + + // assemble promise for nonce + var getNoncePromise: Promise? + guard let noncePolicy = mergedOptions.nonce else { + seal.reject(Web3Error.inputError(desc: "No nonce policy provided")) + return + } + switch noncePolicy { + case .latest: + getNoncePromise = self.web3.eth.getTransactionCountPromise(address: from, onBlock: "latest") + case .pending: + getNoncePromise = self.web3.eth.getTransactionCountPromise(address: from, onBlock: "pending") + case .manual(let nonce): + getNoncePromise = Promise.value(nonce) + } + + let gasPricePromise : Promise = self.web3.eth.getGasPricePromise() + var promisesToFulfill: [Promise] = [getNoncePromise!, gasPricePromise, gasPricePromise] + when(resolved: getNoncePromise!, gasEstimatePromise, gasPricePromise).map(on: queue, { (results:[PromiseResult]) throws -> EthereumTransaction in + + promisesToFulfill.removeAll() + guard case .fulfilled(let nonce) = results[0] else { + throw Web3Error.processingError(desc: "Failed to fetch nonce") + } + guard case .fulfilled(let gasEstimate) = results[1] else { + throw Web3Error.processingError(desc: "Failed to fetch gas estimate") + } + guard case .fulfilled(let gasPrice) = results[2] else { + throw Web3Error.processingError(desc: "Failed to fetch gas price") + } + + guard let estimate = mergedOptions.resolveGasLimit(gasEstimate) else { + throw Web3Error.processingError(desc: "Failed to calculate gas estimate that satisfied options") + } + + guard let finalGasPrice = mergedOptions.resolveGasPrice(gasPrice) else { + throw Web3Error.processingError(desc: "Missing parameter of gas price for transaction") + } + + + assembledTransaction.nonce = nonce + assembledTransaction.gasLimit = estimate + assembledTransaction.gasPrice = finalGasPrice + + forAssemblyPipeline = (assembledTransaction, self.contract, mergedOptions) + + for hook in self.web3.postAssemblyHooks { + let prom : Promise = Promise {seal in + hook.queue.async { + let hookResult = hook.function(forAssemblyPipeline) + if hookResult.3 { + forAssemblyPipeline = (hookResult.0, hookResult.1, hookResult.2) + } + seal.fulfill(hookResult.3) + } + } + let shouldContinue = try prom.wait() + if !shouldContinue { + throw Web3Error.processingError(desc: "Transaction is canceled by middleware") + } + } + + assembledTransaction = forAssemblyPipeline.0 + mergedOptions = forAssemblyPipeline.2 + + return assembledTransaction + }).done(on: queue) {tx in + seal.fulfill(tx) + }.catch(on: queue) {err in + seal.reject(err) + } + } + return returnPromise + } + + public func sendPromise(password:String = "web3swift", transactionOptions: TransactionOptions? = nil) -> Promise{ + let queue = self.web3.requestDispatcher.queue + return self.assemblePromise(transactionOptions: transactionOptions).then(on: queue) { transaction throws -> Promise in + let mergedOptions = self.transactionOptions.merge(transactionOptions) + var cleanedOptions = TransactionOptions() + cleanedOptions.from = mergedOptions.from + cleanedOptions.to = mergedOptions.to + return self.web3.eth.sendTransactionPromise(transaction, transactionOptions: cleanedOptions, password: password) + } + } + + public func send(password:String = "web3swift", transactionOptions: TransactionOptions? = nil) throws -> TransactionSendingResult { + return try self.sendPromise(password: password, transactionOptions: transactionOptions).wait() + } + + public func assemble(transactionOptions: TransactionOptions? = nil) throws -> EthereumTransaction { + return try self.assemblePromise(transactionOptions: transactionOptions).wait() + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Options.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Options.swift new file mode 100755 index 000000000..d9a9b7f55 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Options.swift @@ -0,0 +1,246 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +public protocol TransactionOptionsInheritable { + var transactionOptions: TransactionOptions {get} +} + +/// Options for sending or calling a particular Ethereum transaction +public struct TransactionOptions { + /// Sets the transaction destination. It can either be a contract address or a private key controlled wallet address. + /// + /// Usually should never be nil, left undefined for a contract-creation transaction. + public var to: EthereumAddress? = nil + /// Sets from what account a transaction should be sent. Used only internally as the sender of Ethereum transaction + /// is determined purely from the transaction signature. Indicates to the Ethereum node or to the local keystore what private key + /// should be used to sign a transaction. + /// + /// Can be nil if one reads the information from the blockchain. + public var from: EthereumAddress? = nil + + public enum GasLimitPolicy { + case automatic + case manual(BigUInt) + case limited(BigUInt) + case withMargin(Double) + } + public var gasLimit: GasLimitPolicy? + + public enum GasPricePolicy { + case automatic + case manual(BigUInt) + case withMargin(Double) + } + public var gasPrice: GasPricePolicy? + + /// The value transferred for the transaction in wei, also the endowment if it’s a contract-creation transaction. + public var value: BigUInt? = nil + + public enum NoncePolicy { + case pending + case latest + case manual(BigUInt) + } + public var nonce: NoncePolicy? + + public enum CallingBlockPolicy { + case pending + case latest + case exactBlockNumber(BigUInt) + + var stringValue: String { + switch self { + case .pending: + return "pending" + case .latest: + return "latest" + case .exactBlockNumber(let number): + return String(number, radix: 16).addHexPrefix() + } + } + } + public var callOnBlock: CallingBlockPolicy? + + public init() { + } + + public static var defaultOptions: TransactionOptions { + var opts = TransactionOptions() + opts.callOnBlock = .pending + opts.nonce = .pending + opts.gasLimit = .automatic + opts.gasPrice = .automatic + return opts + } + + public func resolveGasPrice(_ suggestedByNode: BigUInt) -> BigUInt? { + guard let gasPricePolicy = self.gasPrice else {return nil} + switch gasPricePolicy { + case .automatic: + return suggestedByNode + case .manual(let value): + return value + case .withMargin(_): + return suggestedByNode + } + } + + public func resolveGasLimit(_ suggestedByNode: BigUInt) -> BigUInt? { + guard let gasLimitPolicy = self.gasLimit else {return nil} + switch gasLimitPolicy { + case .automatic: + return suggestedByNode + case .manual(let value): + return value + case .withMargin(_): + return suggestedByNode + case .limited(let limit): + if limit <= suggestedByNode { + return suggestedByNode + } + return nil + } + } + + public func merge(_ otherOptions: TransactionOptions?) -> TransactionOptions { + guard let other = otherOptions else {return self} + var opts = TransactionOptions() + opts.from = mergeIfNotNil(first: self.from, second: other.from) + opts.to = mergeIfNotNil(first: self.to, second: other.to) + opts.gasLimit = mergeIfNotNil(first: self.gasLimit, second: other.gasLimit) + opts.gasPrice = mergeIfNotNil(first: self.gasPrice, second: other.gasPrice) + opts.value = mergeIfNotNil(first: self.value, second: other.value) + opts.nonce = mergeIfNotNil(first: self.nonce, second: other.nonce) + opts.callOnBlock = mergeIfNotNil(first: self.callOnBlock, second: other.callOnBlock) + return opts + } + + public static func fromJSON(_ json: [String: Any]) -> TransactionOptions? { + var options = TransactionOptions() + if let gas = json["gas"] as? String, let gasBiguint = BigUInt(gas.stripHexPrefix().lowercased(), radix: 16) { + options.gasLimit = .limited(gasBiguint) + } else if let gasLimit = json["gasLimit"] as? String, let gasgasLimitBiguint = BigUInt(gasLimit.stripHexPrefix().lowercased(), radix: 16) { + options.gasLimit = .limited(gasgasLimitBiguint) + } else { + options.gasLimit = .automatic + } + if let gasPrice = json["gasPrice"] as? String, let gasPriceBiguint = BigUInt(gasPrice.stripHexPrefix().lowercased(), radix: 16) { + options.gasPrice = .manual(gasPriceBiguint) + } else { + options.gasPrice = .automatic + } + if let value = json["value"] as? String, let valueBiguint = BigUInt(value.stripHexPrefix().lowercased(), radix: 16) { + options.value = valueBiguint + } + if let toString = json["to"] as? String { + guard let addressTo = EthereumAddress(toString) else {return nil} + options.to = addressTo + } + if let fromString = json["from"] as? String { + guard let addressFrom = EthereumAddress(fromString) else {return nil} + options.from = addressFrom + } + if let nonceString = json["nonce"] as? String, let nonce = BigUInt(nonceString.stripHexPrefix(), radix: 16) { + options.nonce = .manual(nonce) + } else { + options.nonce = .pending + } + if let callOnBlockString = json["callOnBlock"] as? String, let callOnBlock = BigUInt(callOnBlockString.stripHexPrefix(), radix: 16) { + options.callOnBlock = .exactBlockNumber(callOnBlock) + } else { + options.callOnBlock = .pending + } + return options + } + + /// Merges two sets of topions by overriding the parameters from the first set by parameters from the second + /// set if those are not nil. + /// + /// Returns default options if both parameters are nil. + public static func merge(_ options:TransactionOptions?, with other:TransactionOptions?) -> TransactionOptions? { + if (other == nil && options == nil) { + return TransactionOptions.defaultOptions + } + var newOptions = TransactionOptions.defaultOptions + if (other?.to != nil) { + newOptions.to = other?.to + } else { + newOptions.to = options?.to + } + if (other?.from != nil) { + newOptions.from = other?.from + } else { + newOptions.from = options?.from + } + if (other?.gasLimit != nil) { + newOptions.gasLimit = other?.gasLimit + } else { + newOptions.gasLimit = options?.gasLimit + } + if (other?.gasPrice != nil) { + newOptions.gasPrice = other?.gasPrice + } else { + newOptions.gasPrice = options?.gasPrice + } + if (other?.value != nil) { + newOptions.value = other?.value + } else { + newOptions.value = options?.value + } + return newOptions + } +// +// /// merges two sets of options along with a gas estimate to try to guess the final gas limit value required by user. +// /// +// /// Please refer to the source code for a logic. +// public static func smartMergeGasLimit(originalOptions: Web3Options?, extraOptions: Web3Options?, gasEstimate: BigUInt) -> BigUInt? { +// guard let mergedOptions = Web3Options.merge(originalOptions, with: extraOptions) else {return nil} //just require any non-nils +// if mergedOptions.gasLimit == nil { +// return gasEstimate // for user's convenience we just use an estimate +// // return nil // there is no opinion from user, so we can not proceed +// } else { +// if originalOptions != nil, originalOptions!.gasLimit != nil, originalOptions!.gasLimit! < gasEstimate { // original gas estimate was less than what's required, so we check extra options +// if extraOptions != nil, extraOptions!.gasLimit != nil, extraOptions!.gasLimit! >= gasEstimate { +// return extraOptions!.gasLimit! +// } else { +// return gasEstimate // for user's convenience we just use an estimate +// // return nil // estimate is lower than allowed +// } +// } else { +// if extraOptions != nil, extraOptions!.gasLimit != nil, extraOptions!.gasLimit! >= gasEstimate { +// return extraOptions!.gasLimit! +// } else { +// return gasEstimate // for user's convenience we just use an estimate +// // return nil // estimate is lower than allowed +// } +// } +// } +// } +// +// public static func smartMergeGasPrice(originalOptions: Web3Options?, extraOptions: Web3Options?, priceEstimate: BigUInt) -> BigUInt? { +// guard let mergedOptions = Web3Options.merge(originalOptions, with: extraOptions) else {return nil} //just require any non-nils +// if mergedOptions.gasPrice == nil { +// return priceEstimate +// } else if mergedOptions.gasPrice == 0 { +// return priceEstimate +// } else { +// return mergedOptions.gasPrice! +// } +// } +} + +fileprivate func mergeIfNotNil(first: T?, second: T?) -> T? { + if second != nil { + return second + } else if first != nil { + return first + } + return nil +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Personal.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Personal.swift new file mode 100755 index 000000000..73029fd14 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Personal.swift @@ -0,0 +1,86 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +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 + + */ + public func signPersonalMessage(message: Data, from: EthereumAddress, password:String = "web3swift") throws -> Data { + let result = try self.signPersonalMessagePromise(message: message, from: from, password: password).wait() + 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 inteval before automatic account lock by Ethereum node + + - returns: + - Result object + + - important: This call is synchronous. Does nothing if private keys are stored locally. + + */ + public func unlockAccount(account: EthereumAddress, password:String = "web3swift", seconds: UInt64 = 300) throws -> Bool { + let result = try self.unlockAccountPromise(account: account).wait() + 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 + + */ + public func ecrecover(personalMessage: Data, signature: Data) throws -> EthereumAddress { + guard let recovered = Web3.Utils.personalECRecover(personalMessage, signature: signature) else { + throw Web3Error.dataError + } + return recovered + } + + /** + *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 + + */ + public func ecrecover(hash: Data, signature: Data) throws -> EthereumAddress { + guard let recovered = Web3.Utils.hashECRecover(hash: hash, signature: signature) else { + throw Web3Error.dataError + } + return recovered + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Protocols.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Protocols.swift new file mode 100755 index 000000000..42745d8e9 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Protocols.swift @@ -0,0 +1,90 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import class PromiseKit.Promise +//import EthereumAddress + +/// Protocol for generic Ethereum event parsing results +public protocol EventParserResultProtocol { + var eventName: String {get} + var decodedResult: [String:Any] {get} + var contractAddress: EthereumAddress {get} + var transactionReceipt: TransactionReceipt? {get} + var eventLog: EventLog? {get} +} + +/// Protocol for generic Ethereum event parser +public protocol EventParserProtocol { + func parseTransaction(_ transaction: EthereumTransaction) throws -> [EventParserResultProtocol] + func parseTransactionByHash(_ hash: Data) throws -> [EventParserResultProtocol] + func parseBlock(_ block: Block) throws -> [EventParserResultProtocol] + func parseBlockByNumber(_ blockNumber: UInt64) throws -> [EventParserResultProtocol] + func parseTransactionPromise(_ transaction: EthereumTransaction) -> Promise<[EventParserResultProtocol]> + func parseTransactionByHashPromise(_ hash: Data) -> Promise<[EventParserResultProtocol]> + func parseBlockByNumberPromise(_ blockNumber: UInt64) -> Promise<[EventParserResultProtocol]> + func parseBlockPromise(_ block: Block) -> Promise<[EventParserResultProtocol]> +} + +/// Enum for the most-used Ethereum networks. Network ID is crucial for EIP155 support +public enum Networks { + case Rinkeby + case Mainnet + case Ropsten + case Kovan + case Custom(networkID: BigUInt) + + public var name: String { + switch self { + case .Rinkeby: return "rinkeby" + case .Ropsten: return "ropsten" + case .Mainnet: return "mainnet" + case .Kovan: return "kovan" + case .Custom: return "" + } + } + + public var chainID: BigUInt { + switch self { + case .Custom(let networkID): return networkID + case .Mainnet: return BigUInt(1) + case .Ropsten: return BigUInt(3) + case .Rinkeby: return BigUInt(4) + case .Kovan: return BigUInt(42) + } + } + + static let allValues = [Mainnet, Ropsten, Kovan, Rinkeby] + + static func fromInt(_ networkID:Int) -> Networks? { + switch networkID { + case 1: + return Networks.Mainnet + case 3: + return Networks.Ropsten + case 4: + return Networks.Rinkeby + case 42: + return Networks.Kovan + default: + return Networks.Custom(networkID: BigUInt(networkID)) + } + } +} + +extension Networks: Equatable { + public static func ==(lhs: Networks, rhs: Networks) -> Bool { + return lhs.chainID == rhs.chainID + && lhs.name == rhs.name + } +} + +public protocol EventLoopRunnableProtocol { + var name: String {get} + var queue: DispatchQueue {get} + func functionToRun() +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+ReadingTransaction.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+ReadingTransaction.swift new file mode 100755 index 000000000..0effcba13 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+ReadingTransaction.swift @@ -0,0 +1,109 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +fileprivate typealias PromiseResult = PromiseKit.Result +//import EthereumAddress + +public class ReadTransaction { + public var transaction:EthereumTransaction + public var contract: EthereumContract + public var method: String + public var transactionOptions: TransactionOptions = TransactionOptions.defaultOptions + + var web3: web3 + + public init (transaction: EthereumTransaction, web3 web3Instance: web3, contract: EthereumContract, method: String, transactionOptions: TransactionOptions?) { + self.transaction = transaction + self.web3 = web3Instance + self.contract = contract + self.method = method + self.transactionOptions = self.transactionOptions.merge(transactionOptions) + if self.web3.provider.network != nil { + self.transaction.chainID = self.web3.provider.network?.chainID + } + } + + public func callPromise(transactionOptions: TransactionOptions? = nil) -> Promise<[String: Any]> { + var assembledTransaction : EthereumTransaction = self.transaction + let queue = self.web3.requestDispatcher.queue + let returnPromise = Promise<[String:Any]> { seal in + let mergedOptions = self.transactionOptions.merge(transactionOptions) + var optionsForCall = TransactionOptions() + optionsForCall.from = mergedOptions.from + optionsForCall.to = mergedOptions.to + optionsForCall.value = mergedOptions.value + optionsForCall.callOnBlock = mergedOptions.callOnBlock + if mergedOptions.value != nil { + assembledTransaction.value = mergedOptions.value! + } + let callPromise : Promise = self.web3.eth.callPromise(assembledTransaction, transactionOptions: optionsForCall) + callPromise.done(on: queue) {(data:Data) throws in + do { + if (self.method == "fallback") { + let resultHex = data.toHexString().addHexPrefix() + seal.fulfill(["result": resultHex as Any]) + return + } + guard let decodedData = self.contract.decodeReturnData(self.method, data: data) else + { + throw Web3Error.processingError(desc: "Can not decode returned parameters") + } + seal.fulfill(decodedData) + } catch{ + seal.reject(error) + } + }.catch(on: queue) {err in + seal.reject(err) + } + } + return returnPromise + } + + public func estimateGasPromise(transactionOptions: TransactionOptions? = nil) -> Promise{ + var assembledTransaction : EthereumTransaction = self.transaction + let queue = self.web3.requestDispatcher.queue + let returnPromise = Promise { seal in + let mergedOptions = self.transactionOptions.merge(transactionOptions) + var optionsForGasEstimation = TransactionOptions() + optionsForGasEstimation.from = mergedOptions.from + optionsForGasEstimation.to = mergedOptions.to + optionsForGasEstimation.value = mergedOptions.value + + // MARK: - Fixing estimate gas problem: gas price param shouldn't be nil + if let gasPricePolicy = mergedOptions.gasPrice { + switch gasPricePolicy { + case .manual( _): + optionsForGasEstimation.gasPrice = gasPricePolicy + default: + optionsForGasEstimation.gasPrice = .manual(1) // 1 wei to fix wrong estimating gas problem + } + } + + optionsForGasEstimation.callOnBlock = mergedOptions.callOnBlock + if mergedOptions.value != nil { + assembledTransaction.value = mergedOptions.value! + } + let promise = self.web3.eth.estimateGasPromise(assembledTransaction, transactionOptions: optionsForGasEstimation) + promise.done(on: queue) {(estimate: BigUInt) in + seal.fulfill(estimate) + }.catch(on: queue) {err in + seal.reject(err) + } + } + return returnPromise + } + + public func estimateGas(transactionOptions: TransactionOptions? = nil) throws -> BigUInt { + return try self.estimateGasPromise(transactionOptions: transactionOptions).wait() + } + + public func call(transactionOptions: TransactionOptions? = nil) throws -> [String: Any] { + return try self.callPromise(transactionOptions: transactionOptions).wait() + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Structures.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Structures.swift new file mode 100755 index 000000000..32180fbcc --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Structures.swift @@ -0,0 +1,691 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +fileprivate func decodeHexToData(_ container: KeyedDecodingContainer, key: KeyedDecodingContainer.Key, allowOptional:Bool = false) throws -> Data? { + if (allowOptional) { + let string = try? container.decode(String.self, forKey: key) + if string != nil { + guard let data = Data.fromHex(string!) else {throw Web3Error.dataError} + return data + } + return nil + } else { + let string = try container.decode(String.self, forKey: key) + guard let data = Data.fromHex(string) else {throw Web3Error.dataError} + return data + } +} + +fileprivate func decodeHexToBigUInt(_ container: KeyedDecodingContainer, key: KeyedDecodingContainer.Key, allowOptional:Bool = false) throws -> BigUInt? { + if (allowOptional) { + let string = try? container.decode(String.self, forKey: key) + if string != nil { + guard let number = BigUInt(string!.stripHexPrefix(), radix: 16) else {throw Web3Error.dataError} + return number + } + return nil + } else { + let string = try container.decode(String.self, forKey: key) + guard let number = BigUInt(string.stripHexPrefix(), radix: 16) else {throw Web3Error.dataError} + return number + } +} + +extension TransactionOptions: Decodable { + enum CodingKeys: String, CodingKey + { + case from + case to + case gasPrice + case gas + case value + case nonce + case callOnBlock + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + if let gasLimit = try decodeHexToBigUInt(container, key: .gas) { + self.gasLimit = .manual(gasLimit) + } else { + self.gasLimit = .automatic + } + + if let gasPrice = try decodeHexToBigUInt(container, key: .gasPrice) { + self.gasPrice = .manual(gasPrice) + } else { + self.gasPrice = .automatic + } + + let toString = try container.decode(String?.self, forKey: .to) + var to: EthereumAddress? + if toString == nil || toString == "0x" || toString == "0x0" { + to = EthereumAddress.contractDeploymentAddress() + } else { + guard let addressString = toString else {throw Web3Error.dataError} + guard let ethAddr = EthereumAddress(addressString) else {throw Web3Error.dataError} + to = ethAddr + } + self.to = to + let from = try container.decodeIfPresent(EthereumAddress.self, forKey: .to) + // var from: EthereumAddress? + // if fromString != nil { + // guard let ethAddr = EthereumAddress(toString) else {throw Web3Error.dataError} + // from = ethAddr + // } + self.from = from + + let value = try decodeHexToBigUInt(container, key: .value) + self.value = value + + if let nonce = try decodeHexToBigUInt(container, key: .nonce) { + self.nonce = .manual(nonce) + } else { + self.nonce = .pending + } + + if let callOnBlock = try decodeHexToBigUInt(container, key: .nonce) { + self.callOnBlock = .exactBlockNumber(callOnBlock) + } else { + self.callOnBlock = .pending + } + } +} + +extension EthereumTransaction:Decodable { + enum CodingKeys: String, CodingKey + { + case to + case data + case input + case nonce + case v + case r + case s + case value + } + + public init(from decoder: Decoder) throws { + let options = try TransactionOptions(from: decoder) + let container = try decoder.container(keyedBy: CodingKeys.self) + + var data = try decodeHexToData(container, key: .data, allowOptional: true) + if data != nil { + self.data = data! + } else { + data = try decodeHexToData(container, key: .input, allowOptional: true) + if data != nil { + self.data = data! + } else { + throw Web3Error.dataError + } + } + + guard let nonce = try decodeHexToBigUInt(container, key: .nonce) else {throw Web3Error.dataError} + self.nonce = nonce + + guard let v = try decodeHexToBigUInt(container, key: .v) else {throw Web3Error.dataError} + self.v = v + + guard let r = try decodeHexToBigUInt(container, key: .r) else {throw Web3Error.dataError} + self.r = r + + guard let s = try decodeHexToBigUInt(container, key: .s) else {throw Web3Error.dataError} + self.s = s + + if options.value == nil || options.to == nil || options.gasLimit == nil || options.gasPrice == nil{ + throw Web3Error.dataError + } + self.value = options.value! + self.to = options.to! + + if let gP = options.gasPrice { + switch gP { + case .manual(let value): + self.gasPrice = value + default: + self.gasPrice = BigUInt("5000000000") + } + } + + if let gL = options.gasLimit { + switch gL { + case .manual(let value): + self.gasLimit = value + default: + self.gasLimit = BigUInt(21000) + } + } + + let inferedChainID = self.inferedChainID + if (self.inferedChainID != nil && self.v >= BigUInt(37)) { + self.chainID = inferedChainID + } + } +} + +public struct TransactionDetails: Decodable { + public var blockHash: Data? + public var blockNumber: BigUInt? + public var transactionIndex: BigUInt? + public var transaction: EthereumTransaction + + enum CodingKeys: String, CodingKey + { + case blockHash + case blockNumber + case transactionIndex + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let blockNumber = try decodeHexToBigUInt(container, key: .blockNumber, allowOptional: true) + self.blockNumber = blockNumber + + let blockHash = try decodeHexToData(container, key: .blockHash, allowOptional: true) + self.blockHash = blockHash + + let transactionIndex = try decodeHexToBigUInt(container, key: .blockNumber, allowOptional: true) + self.transactionIndex = transactionIndex + + let transaction = try EthereumTransaction(from: decoder) + self.transaction = transaction + } + + public init? (_ json: [String: AnyObject]) { + let bh = json["blockHash"] as? String + if (bh != nil) { + guard let blockHash = Data.fromHex(bh!) else {return nil} + self.blockHash = blockHash + } + let bn = json["blockNumber"] as? String + let ti = json["transactionIndex"] as? String + + guard let transaction = EthereumTransaction.fromJSON(json) else {return nil} + self.transaction = transaction + if bn != nil { + blockNumber = BigUInt(bn!.stripHexPrefix(), radix: 16) + } + if ti != nil { + transactionIndex = BigUInt(ti!.stripHexPrefix(), radix: 16) + } + } +} + +public struct TransactionReceipt: Decodable { + public var transactionHash: Data + public var blockHash: Data + public var blockNumber: BigUInt + public var transactionIndex: BigUInt + public var contractAddress: EthereumAddress? + public var cumulativeGasUsed: BigUInt + public var gasUsed: BigUInt + public var logs: [EventLog] + public var status: TXStatus + public var logsBloom: EthereumBloomFilter? + + public enum TXStatus { + case ok + case failed + case notYetProcessed + } + + enum CodingKeys: String, CodingKey + { + case blockHash + case blockNumber + case transactionHash + case transactionIndex + case contractAddress + case cumulativeGasUsed + case gasUsed + case logs + case logsBloom + case status + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + guard let blockNumber = try decodeHexToBigUInt(container, key: .blockNumber) else {throw Web3Error.dataError} + self.blockNumber = blockNumber + + guard let blockHash = try decodeHexToData(container, key: .blockHash) else {throw Web3Error.dataError} + self.blockHash = blockHash + + guard let transactionIndex = try decodeHexToBigUInt(container, key: .transactionIndex) else {throw Web3Error.dataError} + self.transactionIndex = transactionIndex + + guard let transactionHash = try decodeHexToData(container, key: .transactionHash) else {throw Web3Error.dataError} + self.transactionHash = transactionHash + + let contractAddress = try container.decodeIfPresent(EthereumAddress.self, forKey: .contractAddress) + if contractAddress != nil { + self.contractAddress = contractAddress + } + + guard let cumulativeGasUsed = try decodeHexToBigUInt(container, key: .cumulativeGasUsed) else {throw Web3Error.dataError} + self.cumulativeGasUsed = cumulativeGasUsed + + guard let gasUsed = try decodeHexToBigUInt(container, key: .gasUsed) else {throw Web3Error.dataError} + self.gasUsed = gasUsed + + + let status = try decodeHexToBigUInt(container, key: .status, allowOptional: true) + if (status == nil) { + self.status = TXStatus.notYetProcessed + } else if status == 1 { + self.status = TXStatus.ok + } else { + self.status = TXStatus.failed + } + + let logsData = try decodeHexToData(container, key: .logsBloom, allowOptional: true) + if logsData != nil && logsData!.count > 0 { + self.logsBloom = EthereumBloomFilter(logsData!) + } + + let logs = try container.decode([EventLog].self, forKey: .logs) + self.logs = logs + } + + + public init(transactionHash: Data, blockHash: Data, blockNumber: BigUInt, transactionIndex: BigUInt, contractAddress: EthereumAddress?, cumulativeGasUsed: BigUInt, gasUsed: BigUInt, logs: [EventLog], status: TXStatus, logsBloom: EthereumBloomFilter?) { + self.transactionHash = transactionHash + self.blockHash = blockHash + self.blockNumber = blockNumber + self.transactionIndex = transactionIndex + self.contractAddress = contractAddress + self.cumulativeGasUsed = cumulativeGasUsed + self.gasUsed = gasUsed + self.logs = logs + self.status = status + self.logsBloom = logsBloom + } + + static func notProcessed(transactionHash: Data) -> TransactionReceipt { + let receipt = TransactionReceipt.init(transactionHash: transactionHash, blockHash: Data(), blockNumber: BigUInt(0), transactionIndex: BigUInt(0), contractAddress: nil, cumulativeGasUsed: BigUInt(0), gasUsed: BigUInt(0), logs: [EventLog](), status: .notYetProcessed, logsBloom: nil) + return receipt + } +} + +extension EthereumAddress: Decodable, Encodable { + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + let stringValue = try container.decode(String.self) + self.init(stringValue)! + } + public func encode(to encoder: Encoder) throws { + let value = self.address.lowercased() + var signleValuedCont = encoder.singleValueContainer() + try signleValuedCont.encode(value) + } +} + +public struct EventLog : Decodable { + public var address: EthereumAddress + public var blockHash: Data + public var blockNumber: BigUInt + public var data: Data + public var logIndex: BigUInt + public var removed: Bool + public var topics: [Data] + public var transactionHash: Data + public var transactionIndex: BigUInt + + +// address = 0x53066cddbc0099eb6c96785d9b3df2aaeede5da3; +// blockHash = 0x779c1f08f2b5252873f08fd6ec62d75bb54f956633bbb59d33bd7c49f1a3d389; +// blockNumber = 0x4f58f8; +// data = 0x0000000000000000000000000000000000000000000000004563918244f40000; +// logIndex = 0x84; +// removed = 0; +// topics = ( +// 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, +// 0x000000000000000000000000efdcf2c36f3756ce7247628afdb632fa4ee12ec5, +// 0x000000000000000000000000d5395c132c791a7f46fa8fc27f0ab6bacd824484 +// ); +// transactionHash = 0x9f7bb2633abb3192d35f65e50a96f9f7ca878fa2ee7bf5d3fca489c0c60dc79a; +// transactionIndex = 0x99; + + enum CodingKeys: String, CodingKey + { + case address + case blockHash + case blockNumber + case data + case logIndex + case removed + case topics + case transactionHash + case transactionIndex + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + let address = try container.decode(EthereumAddress.self, forKey: .address) + self.address = address + + guard let blockNumber = try decodeHexToBigUInt(container, key: .blockNumber) else {throw Web3Error.dataError} + self.blockNumber = blockNumber + + guard let blockHash = try decodeHexToData(container, key: .blockHash) else {throw Web3Error.dataError} + self.blockHash = blockHash + + guard let transactionIndex = try decodeHexToBigUInt(container, key: .transactionIndex) else {throw Web3Error.dataError} + self.transactionIndex = transactionIndex + + guard let transactionHash = try decodeHexToData(container, key: .transactionHash) else {throw Web3Error.dataError} + self.transactionHash = transactionHash + + guard let data = try decodeHexToData(container, key: .data) else {throw Web3Error.dataError} + self.data = data + + guard let logIndex = try decodeHexToBigUInt(container, key: .logIndex) else {throw Web3Error.dataError} + self.logIndex = logIndex + + let removed = try decodeHexToBigUInt(container, key: .removed, allowOptional: true) + if (removed == 1) { + self.removed = true + } else { + self.removed = false + } + + let topicsStrings = try container.decode([String].self, forKey: .topics) + var allTopics = [Data]() + for top in topicsStrings { + guard let topic = Data.fromHex(top) else {throw Web3Error.dataError} + allTopics.append(topic) + } + self.topics = allTopics + } +} + +public enum TransactionInBlock:Decodable { + case hash(Data) + case transaction(EthereumTransaction) + case null + + public init(from decoder: Decoder) throws { + let value = try decoder.singleValueContainer() + if let string = try? value.decode(String.self) { + guard let d = Data.fromHex(string) else {throw Web3Error.dataError} + self = .hash(d) + } else if let dict = try? value.decode([String:String].self) { +// guard let t = try? EthereumTransaction(from: decoder) else {throw Web3Error.dataError} + guard let t = EthereumTransaction.fromJSON(dict) else {throw Web3Error.dataError} + self = .transaction(t) + } else { + self = .null + } + } + + + public init?(_ data: AnyObject) { + if let string = data as? String { + guard let d = Data.fromHex(string) else {return nil} + self = .hash(d) + } else if let dict = data as? [String:AnyObject] { + guard let t = EthereumTransaction.fromJSON(dict) else {return nil} + self = .transaction(t) + } else { + return nil + } + } +} + +public struct Block:Decodable { + public var number: BigUInt + public var hash: Data + public var parentHash: Data + public var nonce: Data? + public var sha3Uncles: Data + public var logsBloom: EthereumBloomFilter? + public var transactionsRoot: Data + public var stateRoot: Data + public var receiptsRoot: Data + public var miner: EthereumAddress? + public var difficulty: BigUInt + public var totalDifficulty: BigUInt + public var extraData: Data + public var size: BigUInt + public var gasLimit: BigUInt + public var gasUsed: BigUInt + public var timestamp: Date + public var transactions: [TransactionInBlock] + public var uncles: [Data] + + enum CodingKeys: String, CodingKey + { + case number + case hash + case parentHash + case nonce + case sha3Uncles + case logsBloom + case transactionsRoot + case stateRoot + case receiptsRoot + case miner + case difficulty + case totalDifficulty + case extraData + case size + case gasLimit + case gasUsed + case timestamp + case transactions + case uncles + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + guard let number = try decodeHexToBigUInt(container, key: .number) else {throw Web3Error.dataError} + self.number = number + + guard let hash = try decodeHexToData(container, key: .hash) else {throw Web3Error.dataError} + self.hash = hash + + guard let parentHash = try decodeHexToData(container, key: .parentHash) else {throw Web3Error.dataError} + self.parentHash = parentHash + + let nonce = try decodeHexToData(container, key: .nonce, allowOptional: true) + self.nonce = nonce + + guard let sha3Uncles = try decodeHexToData(container, key: .sha3Uncles) else {throw Web3Error.dataError} + self.sha3Uncles = sha3Uncles + + let logsBloomData = try decodeHexToData(container, key: .logsBloom, allowOptional: true) + var bloom:EthereumBloomFilter? + if logsBloomData != nil { + bloom = EthereumBloomFilter(logsBloomData!) + } + self.logsBloom = bloom + + guard let transactionsRoot = try decodeHexToData(container, key: .transactionsRoot) else {throw Web3Error.dataError} + self.transactionsRoot = transactionsRoot + + guard let stateRoot = try decodeHexToData(container, key: .stateRoot) else {throw Web3Error.dataError} + self.stateRoot = stateRoot + + guard let receiptsRoot = try decodeHexToData(container, key: .receiptsRoot) else {throw Web3Error.dataError} + self.receiptsRoot = receiptsRoot + + let minerAddress = try? container.decode(String.self, forKey: .miner) + var miner:EthereumAddress? + if minerAddress != nil { + guard let minr = EthereumAddress(minerAddress!) else {throw Web3Error.dataError} + miner = minr + } + self.miner = miner + + guard let difficulty = try decodeHexToBigUInt(container, key: .difficulty) else {throw Web3Error.dataError} + self.difficulty = difficulty + + guard let totalDifficulty = try decodeHexToBigUInt(container, key: .totalDifficulty) else {throw Web3Error.dataError} + self.totalDifficulty = totalDifficulty + + guard let extraData = try decodeHexToData(container, key: .extraData) else {throw Web3Error.dataError} + self.extraData = extraData + + guard let size = try decodeHexToBigUInt(container, key: .size) else {throw Web3Error.dataError} + self.size = size + + guard let gasLimit = try decodeHexToBigUInt(container, key: .gasLimit) else {throw Web3Error.dataError} + self.gasLimit = gasLimit + + guard let gasUsed = try decodeHexToBigUInt(container, key: .gasUsed) else {throw Web3Error.dataError} + self.gasUsed = gasUsed + + let timestampString = try container.decode(String.self, forKey: .timestamp).stripHexPrefix() + guard let timestampInt = UInt64(timestampString, radix: 16) else {throw Web3Error.dataError} + let timestamp = Date(timeIntervalSince1970: TimeInterval(timestampInt)) + self.timestamp = timestamp + + let transactions = try container.decode([TransactionInBlock].self, forKey: .transactions) + self.transactions = transactions + + let unclesStrings = try container.decode([String].self, forKey: .uncles) + var uncles = [Data]() + for str in unclesStrings { + guard let d = Data.fromHex(str) else {throw Web3Error.dataError} + uncles.append(d) + } + self.uncles = uncles + } +} + +public struct EventParserResult:EventParserResultProtocol { + public var eventName: String + public var transactionReceipt: TransactionReceipt? + public var contractAddress: EthereumAddress + public var decodedResult: [String:Any] + public var eventLog: EventLog? + + public init (eventName: String, transactionReceipt: TransactionReceipt?, contractAddress: EthereumAddress, decodedResult: [String:Any]) { + self.eventName = eventName + self.transactionReceipt = transactionReceipt + self.contractAddress = contractAddress + self.decodedResult = decodedResult + self.eventLog = nil + } +} + +public struct TransactionSendingResult { + public var transaction: EthereumTransaction + public var hash: String +} + +public struct TxPoolStatus : Decodable { + public var pending: BigUInt + public var queued: BigUInt + + enum CodingKeys: String, CodingKey + { + case pending + case queued + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + guard let pending = try decodeHexToBigUInt(container, key: .pending) else {throw Web3Error.dataError} + self.pending = pending + guard let queued = try decodeHexToBigUInt(container, key: .queued) else {throw Web3Error.dataError} + self.queued = queued + } +} + +public struct TxPoolContent : Decodable { + public var pending: [EthereumAddress: [TxPoolContentForNonce]] + public var queued: [EthereumAddress: [TxPoolContentForNonce]] + + enum CodingKeys: String, CodingKey + { + case pending + case queued + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let pending = try TxPoolContent.decodePoolContentForKey(container: container, key: .pending) + self.pending = pending + let queued = try TxPoolContent.decodePoolContentForKey(container: container, key: .queued) + self.queued = queued + } + + fileprivate static func decodePoolContentForKey(container: KeyedDecodingContainer, key: KeyedDecodingContainer.Key) throws -> [EthereumAddress: [TxPoolContentForNonce]] { + let raw = try container.nestedContainer(keyedBy: AdditionalDataCodingKeys.self, forKey: key) + var result = [EthereumAddress: [TxPoolContentForNonce]]() + for addressKey in raw.allKeys { + let addressString = addressKey.stringValue + guard let address = EthereumAddress(addressString, type: .normal, ignoreChecksum: true) else { + throw Web3Error.dataError + } + let nestedContainer = try raw.nestedContainer(keyedBy: AdditionalDataCodingKeys.self, forKey: addressKey) + var perNonceInformation = [TxPoolContentForNonce]() + perNonceInformation.reserveCapacity(nestedContainer.allKeys.count) + for nonceKey in nestedContainer.allKeys { + guard let nonce = BigUInt(nonceKey.stringValue) else { + throw Web3Error.dataError + } + let n = try? nestedContainer.nestedUnkeyedContainer(forKey: nonceKey) + if n != nil { + let details = try nestedContainer.decode([TransactionDetails].self, forKey: nonceKey) + let content = TxPoolContentForNonce(nonce: nonce, details: details) + perNonceInformation.append(content) + } else { + let detail = try nestedContainer.decode(TransactionDetails.self, forKey: nonceKey) + let content = TxPoolContentForNonce(nonce: nonce, details: [detail]) + perNonceInformation.append(content) + } + } + result[address] = perNonceInformation + } + return result + } + + + fileprivate struct AdditionalDataCodingKeys: CodingKey + { + var stringValue: String + init?(stringValue: String) + { + self.stringValue = stringValue + } + + var intValue: Int? + init?(intValue: Int) + { + return nil + } + } +} + +//public struct TxPoolContentForAddress : Decodable { +// public var address: EthereumAddress +// public var content: [TxPoolContentForNonce] +// +// public init(from decoder: Decoder) throws { +// let container = try decoder.singleValueContainer() +// let addressString = container.codingPath[0].stringValue +// guard let address = EthereumAddress(addressString, type: .normal, ignoreChecksum: true) else { +// throw Web3Error.dataError +// } +// self.address = address +// +// let content = try container.decode([TxPoolContentForNonce].self) +// self.content = content +// } +//} + +public struct TxPoolContentForNonce { + public var nonce: BigUInt + public var details: [TransactionDetails] +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+TxPool.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+TxPool.swift new file mode 100755 index 000000000..ccf9efc51 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+TxPool.swift @@ -0,0 +1,25 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt + +extension web3.TxPool { + public func getInspect() throws -> [String:[String:[String:String]]] { + let result = try self.getInspectPromise().wait() + return result + } + + public func getStatus() throws -> TxPoolStatus { + let result = try self.getStatusPromise().wait() + return result + } + + public func getContent() throws -> TxPoolContent { + let result = try self.getContentPromise().wait() + return result + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Utils.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Utils.swift new file mode 100755 index 000000000..82ca74a74 --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+Utils.swift @@ -0,0 +1,6212 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import CryptoSwift +//import SwiftRLP +//import secp256k1_swift +//import EthereumAddress + +public typealias Web3Utils = Web3.Utils + +extension Web3 { + + /// Namespaced Utils functions. Are not bound to particular web3 instance, so capitalization matters. + public struct Utils { + + typealias Iban = IBAN + } +} + +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 calcualteContractAddress(from: EthereumAddress, nonce: BigUInt) -> EthereumAddress? { + guard let normalizedAddress = from.addressData.setLengthLeft(32) else {return nil} + guard let data = RLP.encode([normalizedAddress, nonce] as [AnyObject]) else {return nil} + guard let contractAddressData = Web3.Utils.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 { + case eth + case wei + case Kwei + case Mwei + case Gwei + case Microether + 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 + } + } + } + } + + // Precoded API for testing estimate gas fix + public static var estimateGasTestABI = """ +[{"constant":true,"inputs":[],"name":"a","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"foo","type":"uint256"}],"name":"test","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"b","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}] +""" + + /// Precoded "cold wallet" (private key controlled) address. Basically - only a payable fallback function. + public static var coldWalletABI = "[{\"payable\":true,\"type\":\"fallback\"}]" + + /// Precoded ST20 contracts ABI. Output parameters are named for ease of use. + public static var st20ABI = """ +[{"constant":false,"inputs":[],"name":"freezeTransfers","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"investorListed","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_moduleType","type":"uint8"},{"name":"_moduleIndex","type":"uint8"}],"name":"removeModule","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"finishMintingSTO","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_granularity","type":"uint256"}],"name":"changeGranularity","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"finishedSTOMinting","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","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,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"tokenBurner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"tickerRegistry","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"unfreezeTransfers","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"securityTokenVersion","outputs":[{"name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"investors","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_investor","type":"address"},{"name":"_amount","type":"uint256"}],"name":"mint","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_value","type":"uint256"}],"name":"burn","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_moduleType","type":"uint8"},{"name":"_moduleIndex","type":"uint256"}],"name":"getModule","outputs":[{"name":"","type":"bytes32"},{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_investors","type":"address[]"},{"name":"_amounts","type":"uint256[]"}],"name":"mintMulti","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_investor","type":"address"},{"name":"_checkpointId","type":"uint256"}],"name":"balanceOfAt","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"currentCheckpointId","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"granularity","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"MAX_MODULES","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_moduleType","type":"uint8"},{"name":"_moduleIndex","type":"uint8"},{"name":"_budget","type":"uint256"}],"name":"changeModuleBudget","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"freeze","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"STO_KEY","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_subtractedValue","type":"uint256"}],"name":"decreaseApproval","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"polyToken","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"renounceOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint8"},{"name":"","type":"uint256"}],"name":"modules","outputs":[{"name":"name","type":"bytes32"},{"name":"moduleAddress","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_newTokenDetails","type":"string"}],"name":"updateTokenDetails","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"polymathRegistry","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"checkpointTotalSupply","outputs":[{"name":"checkpointId","type":"uint256"},{"name":"value","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_delegate","type":"address"},{"name":"_module","type":"address"},{"name":"_perm","type":"bytes32"}],"name":"checkPermission","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"TRANSFERMANAGER_KEY","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_checkpointId","type":"uint256"}],"name":"totalSupplyAt","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_amount","type":"uint256"}],"name":"verifyTransfer","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"finishedIssuerMinting","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_moduleType","type":"uint8"},{"name":"_name","type":"bytes32"}],"name":"getModuleByName","outputs":[{"name":"","type":"bytes32"},{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"finishMintingIssuer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"PERMISSIONMANAGER_KEY","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_tokenBurner","type":"address"}],"name":"setTokenBurner","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"moduleRegistry","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"CHECKPOINT_KEY","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_start","type":"uint256"},{"name":"_iters","type":"uint256"}],"name":"pruneInvestors","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"securityTokenRegistry","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"tokenDetails","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_addedValue","type":"uint256"}],"name":"increaseApproval","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"investorCount","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getInvestorsLength","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"updateFromRegistry","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_moduleFactory","type":"address"},{"name":"_data","type":"bytes"},{"name":"_maxCost","type":"uint256"},{"name":"_budget","type":"uint256"}],"name":"addModule","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_amount","type":"uint256"}],"name":"withdrawPoly","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"uint256"}],"name":"checkpointBalances","outputs":[{"name":"checkpointId","type":"uint256"},{"name":"value","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"createCheckpoint","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"_name","type":"string"},{"name":"_symbol","type":"string"},{"name":"_decimals","type":"uint8"},{"name":"_granularity","type":"uint256"},{"name":"_tokenDetails","type":"string"},{"name":"_polymathRegistry","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_type","type":"uint8"},{"indexed":false,"name":"_name","type":"bytes32"},{"indexed":false,"name":"_moduleFactory","type":"address"},{"indexed":false,"name":"_module","type":"address"},{"indexed":false,"name":"_moduleCost","type":"uint256"},{"indexed":false,"name":"_budget","type":"uint256"},{"indexed":false,"name":"_timestamp","type":"uint256"}],"name":"LogModuleAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_oldDetails","type":"string"},{"indexed":false,"name":"_newDetails","type":"string"}],"name":"LogUpdateTokenDetails","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_oldGranularity","type":"uint256"},{"indexed":false,"name":"_newGranularity","type":"uint256"}],"name":"LogGranularityChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_type","type":"uint8"},{"indexed":false,"name":"_module","type":"address"},{"indexed":false,"name":"_timestamp","type":"uint256"}],"name":"LogModuleRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_moduleType","type":"uint8"},{"indexed":false,"name":"_module","type":"address"},{"indexed":false,"name":"_budget","type":"uint256"}],"name":"LogModuleBudgetChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_freeze","type":"bool"},{"indexed":false,"name":"_timestamp","type":"uint256"}],"name":"LogFreezeTransfers","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_checkpointId","type":"uint256"},{"indexed":false,"name":"_timestamp","type":"uint256"}],"name":"LogCheckpointCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_timestamp","type":"uint256"}],"name":"LogFinishMintingIssuer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_timestamp","type":"uint256"}],"name":"LogFinishMintingSTO","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_oldAddress","type":"address"},{"indexed":true,"name":"_newAddress","type":"address"}],"name":"LogChangeSTRAddress","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"previousOwner","type":"address"}],"name":"OwnershipRenounced","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"previousOwner","type":"address"},{"indexed":true,"name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"Minted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_burner","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Burnt","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"},{"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"}] +""" + + /// TODO: - Need to make it right + /// Precoded ERC888 contracts ABI. Output parameters are named for ease of use. + public static var erc888ABI = "[{\"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\"},]" + + /// TODO: - need to fix. + public static var erc1376ABI = "[{\"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\"},]" + + /// Precoded ERC20 contracts ABI. Output parameters are named for ease of use. + public static var erc20ABI = "[{\"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\"},]" + + public static var erc721ABI = "[{\"constant\":true,\"inputs\":[{\"name\":\"interfaceID\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"_name\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"getApproved\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_approved\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_index\",\"type\":\"uint256\"}],\"name\":\"tokenOfOwnerByIndex\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_index\",\"type\":\"uint256\"}],\"name\":\"tokenByIndex\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"ownerOf\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"_symbol\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_operator\",\"type\":\"address\"},{\"name\":\"_approved\",\"type\":\"bool\"}],\"name\":\"setApprovalForAll\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"},{\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"tokenURI\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_operator\",\"type\":\"address\"}],\"name\":\"isApprovedForAll\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_approved\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_operator\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_approved\",\"type\":\"bool\"}],\"name\":\"ApprovalForAll\",\"type\":\"event\"}]" + + // TODO: - Need to fix + public static var erc721xABI = "[{\"constant\":true,\"inputs\":[{\"name\":\"interfaceID\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"_name\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"getApproved\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_approved\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_index\",\"type\":\"uint256\"}],\"name\":\"tokenOfOwnerByIndex\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_index\",\"type\":\"uint256\"}],\"name\":\"tokenByIndex\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"ownerOf\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"_symbol\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_operator\",\"type\":\"address\"},{\"name\":\"_approved\",\"type\":\"bool\"}],\"name\":\"setApprovalForAll\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"},{\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"tokenURI\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_operator\",\"type\":\"address\"}],\"name\":\"isApprovedForAll\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_approved\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_operator\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_approved\",\"type\":\"bool\"}],\"name\":\"ApprovalForAll\",\"type\":\"event\"}]" + + // TODO: - Need to fix + public static var erc1155ABI = "[{\"constant\":true,\"inputs\":[{\"name\":\"interfaceID\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"_name\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"getApproved\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_approved\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_index\",\"type\":\"uint256\"}],\"name\":\"tokenOfOwnerByIndex\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_index\",\"type\":\"uint256\"}],\"name\":\"tokenByIndex\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"ownerOf\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"_symbol\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_operator\",\"type\":\"address\"},{\"name\":\"_approved\",\"type\":\"bool\"}],\"name\":\"setApprovalForAll\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"},{\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"tokenURI\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_operator\",\"type\":\"address\"}],\"name\":\"isApprovedForAll\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_approved\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_operator\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_approved\",\"type\":\"bool\"}],\"name\":\"ApprovalForAll\",\"type\":\"event\"}]" + + /// Precoded ERC777 contracts ABI. Output parameters are named for ease of use. + public static var erc777ABI = """ +[ + { + "constant": true, + "inputs": [], + "name": "name", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "spender", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + } + ], + "name": "approve", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "totalSupply", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "from", + "type": "address" + }, + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + } + ], + "name": "transferFrom", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "decimals", + "outputs": [ + { + "name": "", + "type": "uint8" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "owner", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "symbol", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + } + ], + "name": "transfer", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "owner", + "type": "address" + }, + { + "name": "spender", + "type": "address" + } + ], + "name": "allowance", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + } + ], + "name": "Transfer", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "owner", + "type": "address" + }, + { + "indexed": true, + "name": "spender", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + } + ], + "name": "Approval", + "type": "event" + }, + { + "constant": true, + "inputs": [], + "name": "defaultOperators", + "outputs": [ + { + "name": "", + "type": "address[]" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "name", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "totalSupply", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "granularity", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_from", + "type": "address" + }, + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + }, + { + "name": "_operatorData", + "type": "bytes" + } + ], + "name": "operatorSend", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "_tokenHolder", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_operator", + "type": "address" + } + ], + "name": "authorizeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "symbol", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + } + ], + "name": "send", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "_operator", + "type": "address" + }, + { + "name": "_tokenHolder", + "type": "address" + } + ], + "name": "isOperatorFor", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_operator", + "type": "address" + } + ], + "name": "revokeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_tokenHolder", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + }, + { + "name": "_operatorData", + "type": "bytes" + } + ], + "name": "operatorBurn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + } + ], + "name": "burn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "name": "_name", + "type": "string" + }, + { + "name": "_symbol", + "type": "string" + }, + { + "name": "_granularity", + "type": "uint256" + }, + { + "name": "_defaultOperators", + "type": "address[]" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Sent", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Minted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Burned", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "AuthorizedOperator", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "RevokedOperator", + "type": "event" + }, + { + "constant": true, + "inputs": [], + "name": "defaultOperators", + "outputs": [ + { + "name": "", + "type": "address[]" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "name", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_spender", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + } + ], + "name": "approve", + "outputs": [ + { + "name": "success", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "totalSupply", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_from", + "type": "address" + }, + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + } + ], + "name": "transferFrom", + "outputs": [ + { + "name": "success", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "decimals", + "outputs": [ + { + "name": "", + "type": "uint8" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "granularity", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_from", + "type": "address" + }, + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + }, + { + "name": "_operatorData", + "type": "bytes" + } + ], + "name": "operatorSend", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "_tokenHolder", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_operator", + "type": "address" + } + ], + "name": "authorizeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "symbol", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + } + ], + "name": "send", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + } + ], + "name": "transfer", + "outputs": [ + { + "name": "success", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "_operator", + "type": "address" + }, + { + "name": "_tokenHolder", + "type": "address" + } + ], + "name": "isOperatorFor", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "_owner", + "type": "address" + }, + { + "name": "_spender", + "type": "address" + } + ], + "name": "allowance", + "outputs": [ + { + "name": "remaining", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_operator", + "type": "address" + } + ], + "name": "revokeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_tokenHolder", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + }, + { + "name": "_operatorData", + "type": "bytes" + } + ], + "name": "operatorBurn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + } + ], + "name": "burn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "name": "_name", + "type": "string" + }, + { + "name": "_symbol", + "type": "string" + }, + { + "name": "_granularity", + "type": "uint256" + }, + { + "name": "_defaultOperators", + "type": "address[]" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Sent", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Minted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Burned", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "AuthorizedOperator", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "RevokedOperator", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + } + ], + "name": "Transfer", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "owner", + "type": "address" + }, + { + "indexed": true, + "name": "spender", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + } + ], + "name": "Approval", + "type": "event" + }, + { + "constant": true, + "inputs": [], + "name": "defaultOperators", + "outputs": [ + { + "name": "", + "type": "address[]" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "name", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "totalSupply", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "granularity", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "from", + "type": "address" + }, + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + }, + { + "name": "operatorData", + "type": "bytes" + } + ], + "name": "operatorSend", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "owner", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "operator", + "type": "address" + } + ], + "name": "authorizeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "symbol", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + } + ], + "name": "send", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "operator", + "type": "address" + }, + { + "name": "tokenHolder", + "type": "address" + } + ], + "name": "isOperatorFor", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "operator", + "type": "address" + } + ], + "name": "revokeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "from", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + }, + { + "name": "operatorData", + "type": "bytes" + } + ], + "name": "operatorBurn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "amount", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + } + ], + "name": "burn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Sent", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Minted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Burned", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "AuthorizedOperator", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "RevokedOperator", + "type": "event" + }, + { + "constant": false, + "inputs": [ + { + "name": "operator", + "type": "address" + }, + { + "name": "from", + "type": "address" + }, + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + }, + { + "name": "operatorData", + "type": "bytes" + } + ], + "name": "tokensReceived", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "operator", + "type": "address" + }, + { + "name": "from", + "type": "address" + }, + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + }, + { + "name": "userData", + "type": "bytes" + }, + { + "name": "operatorData", + "type": "bytes" + } + ], + "name": "tokensToSend", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "addr", + "type": "address" + }, + { + "name": "iHash", + "type": "bytes32" + }, + { + "name": "implementer", + "type": "address" + } + ], + "name": "setInterfaceImplementer", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "addr", + "type": "address" + } + ], + "name": "getManager", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "addr", + "type": "address" + }, + { + "name": "newManager", + "type": "address" + } + ], + "name": "setManager", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "addr", + "type": "address" + }, + { + "name": "iHash", + "type": "bytes32" + } + ], + "name": "getInterfaceImplementer", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "new_address", + "type": "address" + } + ], + "name": "upgrade", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "last_completed_migration", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "owner", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "completed", + "type": "uint256" + } + ], + "name": "setCompleted", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "constructor" + } +] +""" + /// TODO: - Make it right + /// Precoded ERC1633 contracts ABI. Output parameters are named for ease of use. + public static var erc1633ABI = """ +[ + { + "constant": true, + "inputs": [], + "name": "name", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "spender", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + } + ], + "name": "approve", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "totalSupply", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "from", + "type": "address" + }, + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + } + ], + "name": "transferFrom", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "decimals", + "outputs": [ + { + "name": "", + "type": "uint8" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "owner", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "symbol", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + } + ], + "name": "transfer", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "owner", + "type": "address" + }, + { + "name": "spender", + "type": "address" + } + ], + "name": "allowance", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + } + ], + "name": "Transfer", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "owner", + "type": "address" + }, + { + "indexed": true, + "name": "spender", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + } + ], + "name": "Approval", + "type": "event" + }, + { + "constant": true, + "inputs": [], + "name": "defaultOperators", + "outputs": [ + { + "name": "", + "type": "address[]" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "name", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "totalSupply", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "granularity", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_from", + "type": "address" + }, + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + }, + { + "name": "_operatorData", + "type": "bytes" + } + ], + "name": "operatorSend", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "_tokenHolder", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_operator", + "type": "address" + } + ], + "name": "authorizeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "symbol", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + } + ], + "name": "send", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "_operator", + "type": "address" + }, + { + "name": "_tokenHolder", + "type": "address" + } + ], + "name": "isOperatorFor", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_operator", + "type": "address" + } + ], + "name": "revokeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_tokenHolder", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + }, + { + "name": "_operatorData", + "type": "bytes" + } + ], + "name": "operatorBurn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + } + ], + "name": "burn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "name": "_name", + "type": "string" + }, + { + "name": "_symbol", + "type": "string" + }, + { + "name": "_granularity", + "type": "uint256" + }, + { + "name": "_defaultOperators", + "type": "address[]" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Sent", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Minted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Burned", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "AuthorizedOperator", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "RevokedOperator", + "type": "event" + }, + { + "constant": true, + "inputs": [], + "name": "defaultOperators", + "outputs": [ + { + "name": "", + "type": "address[]" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "name", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_spender", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + } + ], + "name": "approve", + "outputs": [ + { + "name": "success", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "totalSupply", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_from", + "type": "address" + }, + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + } + ], + "name": "transferFrom", + "outputs": [ + { + "name": "success", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "decimals", + "outputs": [ + { + "name": "", + "type": "uint8" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "granularity", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_from", + "type": "address" + }, + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + }, + { + "name": "_operatorData", + "type": "bytes" + } + ], + "name": "operatorSend", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "_tokenHolder", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_operator", + "type": "address" + } + ], + "name": "authorizeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "symbol", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + } + ], + "name": "send", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + } + ], + "name": "transfer", + "outputs": [ + { + "name": "success", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "_operator", + "type": "address" + }, + { + "name": "_tokenHolder", + "type": "address" + } + ], + "name": "isOperatorFor", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "_owner", + "type": "address" + }, + { + "name": "_spender", + "type": "address" + } + ], + "name": "allowance", + "outputs": [ + { + "name": "remaining", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_operator", + "type": "address" + } + ], + "name": "revokeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_tokenHolder", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + }, + { + "name": "_operatorData", + "type": "bytes" + } + ], + "name": "operatorBurn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + } + ], + "name": "burn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "name": "_name", + "type": "string" + }, + { + "name": "_symbol", + "type": "string" + }, + { + "name": "_granularity", + "type": "uint256" + }, + { + "name": "_defaultOperators", + "type": "address[]" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Sent", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Minted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Burned", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "AuthorizedOperator", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "RevokedOperator", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + } + ], + "name": "Transfer", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "owner", + "type": "address" + }, + { + "indexed": true, + "name": "spender", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + } + ], + "name": "Approval", + "type": "event" + }, + { + "constant": true, + "inputs": [], + "name": "defaultOperators", + "outputs": [ + { + "name": "", + "type": "address[]" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "name", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "totalSupply", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "granularity", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "from", + "type": "address" + }, + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + }, + { + "name": "operatorData", + "type": "bytes" + } + ], + "name": "operatorSend", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "owner", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "operator", + "type": "address" + } + ], + "name": "authorizeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "symbol", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + } + ], + "name": "send", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "operator", + "type": "address" + }, + { + "name": "tokenHolder", + "type": "address" + } + ], + "name": "isOperatorFor", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "operator", + "type": "address" + } + ], + "name": "revokeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "from", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + }, + { + "name": "operatorData", + "type": "bytes" + } + ], + "name": "operatorBurn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "amount", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + } + ], + "name": "burn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Sent", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Minted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Burned", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "AuthorizedOperator", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "RevokedOperator", + "type": "event" + }, + { + "constant": false, + "inputs": [ + { + "name": "operator", + "type": "address" + }, + { + "name": "from", + "type": "address" + }, + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + }, + { + "name": "operatorData", + "type": "bytes" + } + ], + "name": "tokensReceived", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "operator", + "type": "address" + }, + { + "name": "from", + "type": "address" + }, + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + }, + { + "name": "userData", + "type": "bytes" + }, + { + "name": "operatorData", + "type": "bytes" + } + ], + "name": "tokensToSend", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "addr", + "type": "address" + }, + { + "name": "iHash", + "type": "bytes32" + }, + { + "name": "implementer", + "type": "address" + } + ], + "name": "setInterfaceImplementer", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "addr", + "type": "address" + } + ], + "name": "getManager", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "addr", + "type": "address" + }, + { + "name": "newManager", + "type": "address" + } + ], + "name": "setManager", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "addr", + "type": "address" + }, + { + "name": "iHash", + "type": "bytes32" + } + ], + "name": "getInterfaceImplementer", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "new_address", + "type": "address" + } + ], + "name": "upgrade", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "last_completed_migration", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "owner", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "completed", + "type": "uint256" + } + ], + "name": "setCompleted", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "constructor" + } +] +""" + public static var ensRegistryABI = """ +[{"constant":true,"inputs":[{"name":"node","type":"bytes32"}],"name":"resolver","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"node","type":"bytes32"}],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"node","type":"bytes32"},{"name":"label","type":"bytes32"},{"name":"owner","type":"address"}],"name":"setSubnodeOwner","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"node","type":"bytes32"},{"name":"ttl","type":"uint64"}],"name":"setTTL","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"node","type":"bytes32"}],"name":"ttl","outputs":[{"name":"","type":"uint64"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"node","type":"bytes32"},{"name":"resolver","type":"address"}],"name":"setResolver","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"node","type":"bytes32"},{"name":"owner","type":"address"}],"name":"setOwner","outputs":[],"payable":false,"type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"name":"node","type":"bytes32"},{"indexed":false,"name":"owner","type":"address"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"node","type":"bytes32"},{"indexed":true,"name":"label","type":"bytes32"},{"indexed":false,"name":"owner","type":"address"}],"name":"NewOwner","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"node","type":"bytes32"},{"indexed":false,"name":"resolver","type":"address"}],"name":"NewResolver","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"node","type":"bytes32"},{"indexed":false,"name":"ttl","type":"uint64"}],"name":"NewTTL","type":"event"}] +""" + /// TODO: - Need to add correct ABI for ERC1400 + /// Precoded ERC1400 contracts ABI. Output parameters are named for ease of use. + public static var erc1400ABI = "[{\"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\"},]" + + /// TODO: - Need to add correct ABI for ERC1410 + /// Precoded ERC1410 contracts ABI. Output parameters are named for ease of use. + public static var erc1410ABI = "[{\"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\"},]" + + /// TODO: - Need to add correct ABI for ERC1594 + /// Precoded ERC1594 contracts ABI. Output parameters are named for ease of use. + public static var erc1594ABI = "[{\"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\"},]" + + /// TODO: - Need to add correct ABI for ERC1644 + /// Precoded ERC1644 contracts ABI. Output parameters are named for ease of use. + public static var erc1644ABI = "[{\"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\"},]" + + /// TODO: - Need to add correct ABI for ERC1644 + /// Precoded ERC1643 contracts ABI. Output parameters are named for ease of use. + public static var erc1643ABI = "[{\"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\"},]" + + public static var deedABI = """ + [{"constant":true,"inputs":[],"name":"creationDate","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"destroyDeed","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"setOwner","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"registrar","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"value","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"previousOwner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newValue","type":"uint256"},{"name":"throwOnFailure","type":"bool"}],"name":"setBalance","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"refundRatio","type":"uint256"}],"name":"closeDeed","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newRegistrar","type":"address"}],"name":"setRegistrar","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_owner","type":"address"}],"payable":true,"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"newOwner","type":"address"}],"name":"OwnerChanged","type":"event"},{"anonymous":false,"inputs":[],"name":"DeedClosed","type":"event"}] + """ + + public static var registrarABI = """ + [{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"releaseDeed","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"getAllowedTime","outputs":[{"name":"timestamp","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"unhashedName","type":"string"}],"name":"invalidateName","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"hash","type":"bytes32"},{"name":"owner","type":"address"},{"name":"value","type":"uint256"},{"name":"salt","type":"bytes32"}],"name":"shaBid","outputs":[{"name":"sealedBid","type":"bytes32"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"bidder","type":"address"},{"name":"seal","type":"bytes32"}],"name":"cancelBid","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"entries","outputs":[{"name":"","type":"uint8"},{"name":"","type":"address"},{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"ens","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"},{"name":"_value","type":"uint256"},{"name":"_salt","type":"bytes32"}],"name":"unsealBid","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"transferRegistrars","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"bytes32"}],"name":"sealedBids","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"state","outputs":[{"name":"","type":"uint8"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"},{"name":"newOwner","type":"address"}],"name":"transfer","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_hash","type":"bytes32"},{"name":"_timestamp","type":"uint256"}],"name":"isAllowed","outputs":[{"name":"allowed","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"finalizeAuction","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"registryStarted","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"sealedBid","type":"bytes32"}],"name":"newBid","outputs":[],"payable":true,"type":"function"},{"constant":false,"inputs":[{"name":"labels","type":"bytes32[]"}],"name":"eraseNode","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_hashes","type":"bytes32[]"}],"name":"startAuctions","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"hash","type":"bytes32"},{"name":"deed","type":"address"},{"name":"registrationDate","type":"uint256"}],"name":"acceptRegistrarTransfer","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"startAuction","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"rootNode","outputs":[{"name":"","type":"bytes32"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"hashes","type":"bytes32[]"},{"name":"sealedBid","type":"bytes32"}],"name":"startAuctionsAndBid","outputs":[],"payable":true,"type":"function"},{"inputs":[{"name":"_ens","type":"address"},{"name":"_rootNode","type":"bytes32"},{"name":"_startDate","type":"uint256"}],"payable":false,"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":false,"name":"registrationDate","type":"uint256"}],"name":"AuctionStarted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":true,"name":"bidder","type":"address"},{"indexed":false,"name":"deposit","type":"uint256"}],"name":"NewBid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":true,"name":"owner","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"status","type":"uint8"}],"name":"BidRevealed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":true,"name":"owner","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"registrationDate","type":"uint256"}],"name":"HashRegistered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":false,"name":"value","type":"uint256"}],"name":"HashReleased","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":true,"name":"name","type":"string"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"registrationDate","type":"uint256"}],"name":"HashInvalidated","type":"event"}] + """ + + public static var ethRegistrarControllerABI = """ +[ + { + "constant": true, + "inputs": [ + { + "name": "interfaceID", + "type": "bytes4" + } + ], + "name": "supportsInterface", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "pure", + "type": "function" + }, + { + "constant": false, + "inputs": [], + "name": "withdraw", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_prices", + "type": "address" + } + ], + "name": "setPriceOracle", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [], + "name": "renounceOwnership", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_minCommitmentAge", + "type": "uint256" + }, + { + "name": "_maxCommitmentAge", + "type": "uint256" + } + ], + "name": "setCommitmentAges", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "", + "type": "bytes32" + } + ], + "name": "commitments", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "name", + "type": "string" + }, + { + "name": "duration", + "type": "uint256" + } + ], + "name": "rentPrice", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "name", + "type": "string" + }, + { + "name": "owner", + "type": "address" + }, + { + "name": "duration", + "type": "uint256" + }, + { + "name": "secret", + "type": "bytes32" + } + ], + "name": "register", + "outputs": [], + "payable": true, + "stateMutability": "payable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "MIN_REGISTRATION_DURATION", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "minCommitmentAge", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "owner", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "isOwner", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "name", + "type": "string" + } + ], + "name": "valid", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "name", + "type": "string" + }, + { + "name": "duration", + "type": "uint256" + } + ], + "name": "renew", + "outputs": [], + "payable": true, + "stateMutability": "payable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "name", + "type": "string" + } + ], + "name": "available", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "maxCommitmentAge", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "commitment", + "type": "bytes32" + } + ], + "name": "commit", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "newOwner", + "type": "address" + } + ], + "name": "transferOwnership", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "name", + "type": "string" + }, + { + "name": "owner", + "type": "address" + }, + { + "name": "secret", + "type": "bytes32" + } + ], + "name": "makeCommitment", + "outputs": [ + { + "name": "", + "type": "bytes32" + } + ], + "payable": false, + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "name": "_base", + "type": "address" + }, + { + "name": "_prices", + "type": "address" + }, + { + "name": "_minCommitmentAge", + "type": "uint256" + }, + { + "name": "_maxCommitmentAge", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "name": "name", + "type": "string" + }, + { + "indexed": true, + "name": "label", + "type": "bytes32" + }, + { + "indexed": true, + "name": "owner", + "type": "address" + }, + { + "indexed": false, + "name": "cost", + "type": "uint256" + }, + { + "indexed": false, + "name": "expires", + "type": "uint256" + } + ], + "name": "NameRegistered", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "name": "name", + "type": "string" + }, + { + "indexed": true, + "name": "label", + "type": "bytes32" + }, + { + "indexed": false, + "name": "cost", + "type": "uint256" + }, + { + "indexed": false, + "name": "expires", + "type": "uint256" + } + ], + "name": "NameRenewed", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "oracle", + "type": "address" + } + ], + "name": "NewPriceOracle", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "previousOwner", + "type": "address" + }, + { + "indexed": true, + "name": "newOwner", + "type": "address" + } + ], + "name": "OwnershipTransferred", + "type": "event" + } +] +""" + + public static var baseRegistrarABI = """ +[ + { + "constant": true, + "inputs": [ + { + "name": "interfaceID", + "type": "bytes4" + } + ], + "name": "supportsInterface", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "tokenId", + "type": "uint256" + } + ], + "name": "getApproved", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "to", + "type": "address" + }, + { + "name": "tokenId", + "type": "uint256" + } + ], + "name": "approve", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "from", + "type": "address" + }, + { + "name": "to", + "type": "address" + }, + { + "name": "tokenId", + "type": "uint256" + } + ], + "name": "transferFrom", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "id", + "type": "uint256" + } + ], + "name": "reclaim", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "ens", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "from", + "type": "address" + }, + { + "name": "to", + "type": "address" + }, + { + "name": "tokenId", + "type": "uint256" + } + ], + "name": "safeTransferFrom", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "transferPeriodEnds", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "resolver", + "type": "address" + } + ], + "name": "setResolver", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "tokenId", + "type": "uint256" + } + ], + "name": "ownerOf", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "MIGRATION_LOCK_PERIOD", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "owner", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [], + "name": "renounceOwnership", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "owner", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "isOwner", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "id", + "type": "uint256" + } + ], + "name": "available", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "to", + "type": "address" + }, + { + "name": "approved", + "type": "bool" + } + ], + "name": "setApprovalForAll", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "controller", + "type": "address" + } + ], + "name": "addController", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "previousRegistrar", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "from", + "type": "address" + }, + { + "name": "to", + "type": "address" + }, + { + "name": "tokenId", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + } + ], + "name": "safeTransferFrom", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "GRACE_PERIOD", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "id", + "type": "uint256" + }, + { + "name": "duration", + "type": "uint256" + } + ], + "name": "renew", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "id", + "type": "uint256" + } + ], + "name": "nameExpires", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "", + "type": "address" + } + ], + "name": "controllers", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "baseNode", + "outputs": [ + { + "name": "", + "type": "bytes32" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "owner", + "type": "address" + }, + { + "name": "operator", + "type": "address" + } + ], + "name": "isApprovedForAll", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "label", + "type": "bytes32" + }, + { + "name": "deed", + "type": "address" + }, + { + "name": "", + "type": "uint256" + } + ], + "name": "acceptRegistrarTransfer", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "newOwner", + "type": "address" + } + ], + "name": "transferOwnership", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "controller", + "type": "address" + } + ], + "name": "removeController", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "id", + "type": "uint256" + }, + { + "name": "owner", + "type": "address" + }, + { + "name": "duration", + "type": "uint256" + } + ], + "name": "register", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "name": "_ens", + "type": "address" + }, + { + "name": "_previousRegistrar", + "type": "address" + }, + { + "name": "_baseNode", + "type": "bytes32" + }, + { + "name": "_transferPeriodEnds", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "controller", + "type": "address" + } + ], + "name": "ControllerAdded", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "controller", + "type": "address" + } + ], + "name": "ControllerRemoved", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "id", + "type": "uint256" + }, + { + "indexed": true, + "name": "owner", + "type": "address" + }, + { + "indexed": false, + "name": "expires", + "type": "uint256" + } + ], + "name": "NameMigrated", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "id", + "type": "uint256" + }, + { + "indexed": true, + "name": "owner", + "type": "address" + }, + { + "indexed": false, + "name": "expires", + "type": "uint256" + } + ], + "name": "NameRegistered", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "id", + "type": "uint256" + }, + { + "indexed": false, + "name": "expires", + "type": "uint256" + } + ], + "name": "NameRenewed", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "previousOwner", + "type": "address" + }, + { + "indexed": true, + "name": "newOwner", + "type": "address" + } + ], + "name": "OwnershipTransferred", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": true, + "name": "tokenId", + "type": "uint256" + } + ], + "name": "Transfer", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "owner", + "type": "address" + }, + { + "indexed": true, + "name": "approved", + "type": "address" + }, + { + "indexed": true, + "name": "tokenId", + "type": "uint256" + } + ], + "name": "Approval", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "owner", + "type": "address" + }, + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": false, + "name": "approved", + "type": "bool" + } + ], + "name": "ApprovalForAll", + "type": "event" + } +] +""" + + public static var reverseRegistrarABI = """ +[ + { + "constant": false, + "inputs": [ + { + "name": "owner", + "type": "address" + }, + { + "name": "resolver", + "type": "address" + } + ], + "name": "claimWithResolver", + "outputs": [ + { + "name": "", + "type": "bytes32" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "owner", + "type": "address" + } + ], + "name": "claim", + "outputs": [ + { + "name": "", + "type": "bytes32" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "ens", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "ADDR_REVERSE_NODE", + "outputs": [ + { + "name": "", + "type": "bytes32" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "defaultResolver", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "addr", + "type": "address" + } + ], + "name": "node", + "outputs": [ + { + "name": "", + "type": "bytes32" + } + ], + "payable": false, + "stateMutability": "pure", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "name", + "type": "string" + } + ], + "name": "setName", + "outputs": [ + { + "name": "", + "type": "bytes32" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "name": "ensAddr", + "type": "address" + }, + { + "name": "resolverAddr", + "type": "address" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "constructor" + } +] +""" + + //function setAddr(bytes32 node, address addr) + public static var legacyResolverABI = """ +[ + { + "constant": true, + "inputs": [ + { + "name": "interfaceID", + "type": "bytes4" + } + ], + "name": "supportsInterface", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "pure", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "key", + "type": "string" + }, + { + "name": "value", + "type": "string" + } + ], + "name": "setText", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "contentTypes", + "type": "uint256" + } + ], + "name": "ABI", + "outputs": [ + { + "name": "contentType", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "x", + "type": "bytes32" + }, + { + "name": "y", + "type": "bytes32" + } + ], + "name": "setPubkey", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "content", + "outputs": [ + { + "name": "", + "type": "bytes32" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "addr", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "key", + "type": "string" + } + ], + "name": "text", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "contentType", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + } + ], + "name": "setABI", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "name", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "name", + "type": "string" + } + ], + "name": "setName", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "hash", + "type": "bytes" + } + ], + "name": "setMultihash", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "hash", + "type": "bytes32" + } + ], + "name": "setContent", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "pubkey", + "outputs": [ + { + "name": "x", + "type": "bytes32" + }, + { + "name": "y", + "type": "bytes32" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "addr", + "type": "address" + } + ], + "name": "setAddr", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "multihash", + "outputs": [ + { + "name": "", + "type": "bytes" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "name": "ensAddr", + "type": "address" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "a", + "type": "address" + } + ], + "name": "AddrChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "hash", + "type": "bytes32" + } + ], + "name": "ContentChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "name", + "type": "string" + } + ], + "name": "NameChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": true, + "name": "contentType", + "type": "uint256" + } + ], + "name": "ABIChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "x", + "type": "bytes32" + }, + { + "indexed": false, + "name": "y", + "type": "bytes32" + } + ], + "name": "PubkeyChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "indexedKey", + "type": "string" + }, + { + "indexed": false, + "name": "key", + "type": "string" + } + ], + "name": "TextChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "hash", + "type": "bytes" + } + ], + "name": "MultihashChanged", + "type": "event" + } +] +""" + + public static var resolverABI = """ +[ + { + "constant": true, + "inputs": + [ + { + "name": "interfaceID", + "type": "bytes4" + } + ], + "name": "supportsInterface", + "outputs": + [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "pure", + "type": "function" + }, + { + "constant": false, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "key", + "type": "string" + }, + { + "name": "value", + "type": "string" + } + ], + "name": "setText", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "interfaceID", + "type": "bytes4" + } + ], + "name": "interfaceImplementer", + "outputs": + [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "contentTypes", + "type": "uint256" + } + ], + "name": "ABI", + "outputs": + [ + { + "name": "", + "type": "uint256" + }, + { + "name": "", + "type": "bytes" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "x", + "type": "bytes32" + }, + { + "name": "y", + "type": "bytes32" + } + ], + "name": "setPubkey", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "hash", + "type": "bytes" + } + ], + "name": "setContenthash", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "addr", + "outputs": + [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "key", + "type": "string" + } + ], + "name": "text", + "outputs": + [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "contentType", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + } + ], + "name": "setABI", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "name", + "outputs": + [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [], + "name": "renounceOwnership", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "name", + "type": "string" + } + ], + "name": "setName", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "owner", + "outputs": + [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "isOwner", + "outputs": + [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "contenthash", + "outputs": + [ + { + "name": "", + "type": "bytes" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "pubkey", + "outputs": + [ + { + "name": "x", + "type": "bytes32" + }, + { + "name": "y", + "type": "bytes32" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "addr", + "type": "address" + } + ], + "name": "setAddr", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "interfaceID", + "type": "bytes4" + }, + { + "name": "implementer", + "type": "address" + } + ], + "name": "setInterface", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": + [ + { + "name": "newOwner", + "type": "address" + } + ], + "name": "transferOwnership", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "anonymous": false, + "inputs": + [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "indexedKey", + "type": "string" + }, + { + "indexed": false, + "name": "key", + "type": "string" + } + ], + "name": "TextChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": + [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "x", + "type": "bytes32" + }, + { + "indexed": false, + "name": "y", + "type": "bytes32" + } + ], + "name": "PubkeyChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": + [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "name", + "type": "string" + } + ], + "name": "NameChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": + [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": true, + "name": "interfaceID", + "type": "bytes4" + }, + { + "indexed": false, + "name": "implementer", + "type": "address" + } + ], + "name": "InterfaceChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": + [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "hash", + "type": "bytes" + } + ], + "name": "ContenthashChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": + [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "a", + "type": "address" + } + ], + "name": "AddrChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": + [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": true, + "name": "contentType", + "type": "uint256" + } + ], + "name": "ABIChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": + [ + { + "indexed": true, + "name": "previousOwner", + "type": "address" + }, + { + "indexed": true, + "name": "newOwner", + "type": "address" + } + ], + "name": "OwnershipTransferred", + "type": "event" + } +] +""" + +} + +extension Web3.Utils { + + /// 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} + return publicKey + } + + /// Convert a public key to the corresponding EthereumAddress. Accepts public keys in compressed (33 bytes), non-compressed (65 bytes) + /// or raw concat(X,Y) (64 bytes) format. + /// + /// Returns 20 bytes of address data. + public static func publicToAddressData(_ publicKey: Data) -> Data? { + if publicKey.count == 33 { + guard let decompressedKey = SECP256K1.combineSerializedPublicKeys(keys: [publicKey], outputCompressed: false) else {return nil} + return publicToAddressData(decompressedKey) + } + var stipped = publicKey + if (stipped.count == 65) { + if (stipped[0] != 4) { + return nil + } + stipped = stipped[1...64] + } + if (stipped.count != 64) { + return nil + } + let sha3 = stipped.sha3(.keccak256) + let addressData = sha3[12...31] + return addressData + } + + /// Convert a public key to the corresponding EthereumAddress. Accepts public keys in compressed (33 bytes), non-compressed (65 bytes) + /// or raw concat(X,Y) (64 bytes) format. + /// + /// Returns the EthereumAddress object. + public static func publicToAddress(_ publicKey: Data) -> EthereumAddress? { + guard let addressData = Web3.Utils.publicToAddressData(publicKey) else {return nil} + let address = addressData.toHexString().addHexPrefix().lowercased() + return EthereumAddress(address) + } + + /// Convert a public key to the corresponding EthereumAddress. Accepts public keys in compressed (33 bytes), non-compressed (65 bytes) + /// or raw concat(X,Y) (64 bytes) format. + /// + /// Returns a 0x prefixed hex string. + public static func publicToAddressString(_ publicKey: Data) -> String? { + guard let addressData = Web3.Utils.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. + public static func addressDataToString(_ addressData: Data) -> String? { + guard addressData.count == 20 else {return nil} + return addressData.toHexString().addHexPrefix().lowercased() + } + + /// Hashes a personal message by first padding it with the "\u{19}Ethereum Signed Message:\n" string and message length string. + /// Should be used if some arbitrary information should be hashed and signed to prevent signing an Ethereum transaction + /// by accident. + 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} + var data = Data() + if personalMessage.count >= prefixData.count && prefixData == personalMessage[0 ..< prefixData.count] { + data.append(personalMessage) + } else { + data.append(prefixData) + data.append(personalMessage) + } + let hash = data.sha3(.keccak256) + return hash + } + + /// Parse a user-supplied string using the number of decimals for particular Ethereum unit. + /// If input is non-numeric or precision is not sufficient - returns nil. + /// Allowed decimal separators are ".", ",". + public static func parseToBigUInt(_ amount: String, units: Web3.Utils.Units = .eth) -> BigUInt? { + let unitDecimals = units.decimals + return parseToBigUInt(amount, decimals: unitDecimals) + } + + /// Parse a user-supplied 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} + let unitDecimals = decimals + 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 + } + return mainPart + } + + /// Formats a BigInt object to String. The supplied number is first divided into integer and decimal part based on "toUnits", + /// then limit the decimal part to "decimals" symbols and uses a "decimalSeparator" as a separator. + /// + /// Returns nil of formatting is not possible to satisfy. + public static func formatToEthereumUnits(_ bigNumber: BigInt, toUnits: Web3.Utils.Units = .eth, decimals: Int = 4, decimalSeparator: String = ".") -> String? { + let magnitude = bigNumber.magnitude + guard let formatted = formatToEthereumUnits(magnitude, toUnits: toUnits, decimals: decimals, decimalSeparator: decimalSeparator) else {return nil} + switch bigNumber.sign { + case .plus: + return formatted + case .minus: + return "-" + formatted + } + } + + /// Formats a BigInt object to String. The supplied number is first divided into integer and decimal part based on "toUnits", + /// then limit the decimal part to "decimals" 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. + public static func formatToPrecision(_ bigNumber: BigInt, numberDecimals: Int = 18, formattingDecimals: Int = 4, decimalSeparator: String = ".", fallbackToScientific: Bool = false) -> String? { + let magnitude = bigNumber.magnitude + guard let formatted = formatToPrecision(magnitude, numberDecimals: numberDecimals, formattingDecimals: formattingDecimals, decimalSeparator: decimalSeparator, fallbackToScientific: fallbackToScientific) else {return nil} + switch bigNumber.sign { + case .plus: + return formatted + case .minus: + return "-" + formatted + } + } + + /// Formats a BigUInt object to String. The supplied number is first divided into integer and decimal part based on "toUnits", + /// then limit the decimal part to "decimals" symbols and uses a "decimalSeparator" as a separator. + /// + /// Returns nil of formatting is not possible to satisfy. + public static func formatToEthereumUnits(_ bigNumber: BigUInt, toUnits: Web3.Utils.Units = .eth, decimals: Int = 4, decimalSeparator: String = ".", fallbackToScientific: Bool = false) -> String? { + return formatToPrecision(bigNumber, numberDecimals: toUnits.decimals, formattingDecimals: decimals, decimalSeparator: decimalSeparator, fallbackToScientific: fallbackToScientific); + } + + /// Formats a BigUInt object to String. The supplied number is first divided into integer and decimal part based on "numberDecimals", + /// 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. + public static func formatToPrecision(_ bigNumber: BigUInt, numberDecimals: Int = 18, formattingDecimals: Int = 4, decimalSeparator: String = ".", fallbackToScientific: Bool = false) -> String? { + if bigNumber == 0 { + return "0" + } + let unitDecimals = numberDecimals + var toDecimals = formattingDecimals + if unitDecimals < toDecimals { + toDecimals = unitDecimals + } + let divisor = BigUInt(10).power(unitDecimals) + let (quotient, remainder) = bigNumber.quotientAndRemainder(dividingBy: divisor) + var fullRemainder = String(remainder); + let fullPaddedRemainder = fullRemainder.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) + } + } + if (toDecimals == 0) { + return String(quotient) + } + return String(quotient) + decimalSeparator + remainderPadded + } + + /// 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 public 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} + return Web3.Utils.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. + static public 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 = Web3.Utils.hashPersonalMessage(personalMessage) else {return nil} + guard let publicKey = SECP256K1.recoverPublicKey(hash: hash, signature: signatureData) else {return nil} + return Web3.Utils.publicToAddress(publicKey) + } + + + /// 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. + static public func hashECRecover(hash: 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 publicKey = SECP256K1.recoverPublicKey(hash: hash, signature: signatureData) else {return nil} + return Web3.Utils.publicToAddress(publicKey) + } + + /// returns Ethereum variant of sha3 (keccak256) of data. Returns nil is data is empty + static public func keccak256(_ data: Data) -> Data? { + 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 public func sha3(_ data: Data) -> Data? { + if data.count == 0 {return nil} + return data.sha3(.keccak256) + } + + /// returns sha256 of data. Returns nil is data is empty + static public func sha256(_ data: Data) -> Data? { + 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} + let bytes = signatureData.bytes + let r = Array(bytes[0..<32]) + let s = Array(bytes[32..<64]) + return SECP256K1.UnmarshaledSignature(v: bytes[64], r: Data(r), s: Data(s)) + } + + /// 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} + var completeSignature = Data(r) + completeSignature.append(Data(s)) + completeSignature.append(Data([v])) +// var completeSignature = Data(bytes: r) +// completeSignature.append(Data(bytes: s)) +// completeSignature.append(Data(bytes: [v])) + return completeSignature + } + + /// Marshals internal signature structure into a 65 byte recoverable EC signature. + static func marshalSignature(unmarshalledSignature: SECP256K1.UnmarshaledSignature) -> Data { + var completeSignature = Data(unmarshalledSignature.r) + completeSignature.append(Data(unmarshalledSignature.s)) +// completeSignature.append(Data(bytes: [unmarshalledSignature.v])) + completeSignature.append(Data([unmarshalledSignature.v])) + return completeSignature + } + + public static func hexToData(_ string: String) -> Data? { + return Data.fromHex(string) + } + + public static func hexToBigUInt(_ string: String) -> BigUInt? { + return BigUInt(string.stripHexPrefix(), radix: 16) + } + + public static func randomBytes(length: Int) -> Data? { + return Data.randomBytes(length:length) + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+WebsocketProvider.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+WebsocketProvider.swift new file mode 100644 index 000000000..e25122ace --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3+WebsocketProvider.swift @@ -0,0 +1,300 @@ +// +// Web3+WebsocketProvider.swift +// web3swift-iOS +// +// Created by Anton on 01/04/2019. +// Copyright © 2019 The Matter Inc. All rights reserved. +// +import Starscream +import PromiseKit +import BigInt +import Foundation + +public protocol IWebsocketProvider { + var socket: WebSocket {get} + var delegate: Web3SocketDelegate {get set} + func connectSocket() throws + func disconnectSocket() throws + func writeMessage(_ message: T) +} + +public enum InfuraWebsocketMethod: String, Encodable { + + case newPendingTransactionFilter = "eth_newPendingTransactionFilter" + case getFilterChanges = "eth_getFilterChanges" + case newFilter = "eth_newFilter" + case newBlockFilter = "eth_newBlockFilter" + case getFilterLogs = "eth_getFilterLogs" + case uninstallFilter = "eth_uninstallFilter" + case subscribe = "eth_subscribe" + case unsubscribe = "eth_unsubscribe" + + public var requiredNumOfParameters: Int? { + get { + switch self { + case .newPendingTransactionFilter: + return 0 + case .getFilterChanges: + return 1 + case .newFilter: + return nil + case .newBlockFilter: + return 0 + case .getFilterLogs: + return nil + case .uninstallFilter: + return 1 + case .subscribe: + return nil + case .unsubscribe: + return 1 + } + } + } +} + +public struct InfuraWebsocketRequest: Encodable { + public var jsonrpc: String = "2.0" + public var method: InfuraWebsocketMethod? + public var params: JSONRPCparams? + public var id: UInt64 = Counter.increment() + + enum CodingKeys: String, CodingKey { + case jsonrpc + case method + case params + case id + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(jsonrpc, forKey: .jsonrpc) + try container.encode(method?.rawValue, forKey: .method) + try container.encode(params, forKey: .params) + try container.encode(id, forKey: .id) + } + + public var isValid: Bool { + get { + if self.method == nil { + return false + } + guard let method = self.method else {return false} + return method.requiredNumOfParameters == self.params?.params.count + } + } +} + +public protocol Web3SocketDelegate { + func received(message: Any) + func gotError(error: Error) +} + +/// The default websocket provider. +public class WebsocketProvider: Web3Provider, IWebsocketProvider, WebSocketDelegate { + public func sendAsync(_ request: JSONRPCrequest, queue: DispatchQueue) -> Promise { + return Promise(error: Web3Error.inputError(desc: "Sending is unsupported for Websocket provider. Please, use \'sendMessage\'")) + } + + public func sendAsync(_ requests: JSONRPCrequestBatch, queue: DispatchQueue) -> Promise { + return Promise(error: Web3Error.inputError(desc: "Sending is unsupported for Websocket provider. Please, use \'sendMessage\'")) + } + + public var network: Networks? + public var url: URL + public var session: URLSession = {() -> URLSession in + let config = URLSessionConfiguration.default + let urlSession = URLSession(configuration: config) + return urlSession + }() + public var attachedKeystoreManager: KeystoreManager? = nil + + public var socket: WebSocket + public var delegate: Web3SocketDelegate + + private var websocketConnected: Bool = false + private var writeTimer: Timer? = nil + private var messagesStringToWrite: [String] = [] + private var messagesDataToWrite: [Data] = [] + + public init?(_ endpoint: URL, + delegate wsdelegate: Web3SocketDelegate, + projectId: String? = nil, + keystoreManager manager: KeystoreManager? = nil, + network net: Networks? = nil) { + websocketConnected = false + var endpointString = endpoint.absoluteString + if !(endpointString.hasPrefix("wss://") || endpointString.hasPrefix("ws://")) { + return nil + } + if endpointString.hasPrefix("wss://") && endpointString.hasSuffix(Constants.infuraWsScheme) { + if net == nil { + let networkString = endpointString.replacingOccurrences(of: "wss://", with: "") + .replacingOccurrences(of: Constants.infuraWsScheme, with: "") + switch networkString { + case "mainnet": + network = Networks.Mainnet + case "rinkeby": + network = Networks.Rinkeby + case "ropsten": + network = Networks.Ropsten + case "kovan": + network = Networks.Kovan + default: + break + } + } else { + network = net + } + if network != nil { + endpointString += projectId ?? Constants.infuraToken + } + } + url = URL(string: endpointString)! + delegate = wsdelegate + attachedKeystoreManager = manager + socket = WebSocket(url: url) + socket.delegate = self + } + + public init?(_ endpoint: String, + delegate wsdelegate: Web3SocketDelegate, + projectId: String? = nil, + keystoreManager manager: KeystoreManager? = nil, + network net: Networks? = nil) { + guard URL(string: endpoint) != nil else {return nil} + var finalEndpoint = endpoint + websocketConnected = false + if !(endpoint.hasPrefix("wss://") || endpoint.hasPrefix("ws://")) { + return nil + } + if endpoint.hasPrefix("wss://") && endpoint.hasSuffix(Constants.infuraWsScheme) { + if net == nil { + let networkString = endpoint.replacingOccurrences(of: "wss://", with: "") + .replacingOccurrences(of: Constants.infuraWsScheme, with: "") + switch networkString { + case "mainnet": + network = Networks.Mainnet + case "rinkeby": + network = Networks.Rinkeby + case "ropsten": + network = Networks.Ropsten + case "kovan": + network = Networks.Kovan + default: + break + } + } else { + network = net + } + if network != nil { + finalEndpoint += projectId ?? Constants.infuraToken + } + } + url = URL(string: finalEndpoint)! + delegate = wsdelegate + attachedKeystoreManager = manager + socket = WebSocket(url: url) + socket.delegate = self + } + + deinit { + writeTimer?.invalidate() + } + + public func connectSocket() { + writeTimer?.invalidate() + socket.connect() + } + + public func disconnectSocket() { + writeTimer?.invalidate() + socket.disconnect() + } + + public class func connectToSocket(_ endpoint: String, + delegate: Web3SocketDelegate, + projectId: String? = nil, + keystoreManager manager: KeystoreManager? = nil, + network net: Networks? = nil) -> WebsocketProvider? { + guard let socketProvider = WebsocketProvider(endpoint, + delegate: delegate, + projectId: projectId, + keystoreManager: manager, + network: net) else { + return nil + } + socketProvider.connectSocket() + return socketProvider + } + + public class func connectToSocket(_ endpoint: URL, + delegate: Web3SocketDelegate, + projectId: String? = nil, + keystoreManager manager: KeystoreManager? = nil, + network net: Networks? = nil) -> WebsocketProvider? { + guard let socketProvider = WebsocketProvider(endpoint, + delegate: delegate, + projectId: projectId, + keystoreManager: manager, + network: net) else { + return nil + } + socketProvider.connectSocket() + return socketProvider + } + + public func writeMessage(_ message: T) { + var sMessage: String? = nil + var dMessage: Data? = nil + if !(message.self is String) && !(message.self is Data) { + sMessage = "\(message)" + } else if message.self is String { + sMessage = message as? String + } else if message.self is Data { + dMessage = message as? Data + } + if sMessage != nil { + self.messagesStringToWrite.append(sMessage!) + } else if dMessage != nil { + self.messagesDataToWrite.append(dMessage!) + } + writeTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(performWriteOperations), userInfo: nil, repeats: true) + } + + @objc private func performWriteOperations() { + if websocketConnected { + writeTimer?.invalidate() + for s in messagesStringToWrite { + socket.write(string: s) + } + for d in messagesDataToWrite { + socket.write(data: d) + } + } + } + + public func websocketDidReceiveMessage(socket: WebSocketClient, text: String) { + print("got some text: \(text)") + delegate.received(message: text) + } + + public func websocketDidReceiveData(socket: WebSocketClient, data: Data) { + print("got some data: \(data.count)") + delegate.received(message: data) + } + + public func websocketDidConnect(socket: WebSocketClient) { + print("websocket is connected") + websocketConnected = true + } + + public func websocketDidDisconnect(socket: WebSocketClient, error: Error?) { + print("websocket is disconnected with \(error?.localizedDescription ?? "no error")") + websocketConnected = false + } + + public func websocketDidReceivePong(socket: WebSocketClient, data: Data?) { + print("Got pong! Maybe some data: \(String(describing: data?.count))") + } +} diff --git a/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3.swift b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3.swift new file mode 100755 index 000000000..91ab2d54f --- /dev/null +++ b/Example/Web3supportBrowser/Pods/web3swift/Sources/web3swift/Web3/Web3.swift @@ -0,0 +1,79 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +public enum Web3Error: Error { + case transactionSerializationError + case connectionError + case dataError + case walletError + case inputError(desc:String) + case nodeError(desc:String) + case processingError(desc:String) + case keystoreError(err:AbstractKeystoreError) + case generalError(err:Error) + case unknownError + + public var errorDescription: String { + switch self { + + case .transactionSerializationError: + return "Transaction Serialization Error" + case .connectionError: + return "Connection Error" + case .dataError: + return "Data Error" + case .walletError: + return "Wallet Error" + case .inputError(let desc): + return desc + case .nodeError(let desc): + return desc + case .processingError(let desc): + return desc + case .keystoreError(let err): + return err.localizedDescription + case .generalError(let err): + return err.localizedDescription + case .unknownError: + return "Unknown Error" + } + } +} + +/// An arbitary Web3 object. Is used only to construct provider bound fully functional object by either supplying provider URL +/// or using pre-coded Infura nodes +public struct 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) throws -> web3 { + guard let provider = Web3HttpProvider(providerURL) else { + throw Web3Error.inputError(desc: "Wrong provider - should be Web3HttpProvider with endpoint scheme http or https") + } + return web3(provider: provider) + } + + /// Initialized Web3 instance bound to Infura's mainnet provider. + public static func InfuraMainnetWeb3(accessToken: String? = nil) -> web3 { + let infura = InfuraProvider(Networks.Mainnet, accessToken: accessToken)! + return web3(provider: infura) + } + + /// Initialized Web3 instance bound to Infura's rinkeby provider. + public static func InfuraRinkebyWeb3(accessToken: String? = nil) -> web3 { + let infura = InfuraProvider(Networks.Rinkeby, accessToken: accessToken)! + return web3(provider: infura) + } + + /// Initialized Web3 instance bound to Infura's ropsten provider. + public static func InfuraRopstenWeb3(accessToken: String? = nil) -> web3 { + let infura = InfuraProvider(Networks.Ropsten, accessToken: accessToken)! + return web3(provider: infura) + } + +} diff --git a/Example/Web3supportBrowser/Web3support.xcodeproj/project.pbxproj b/Example/Web3supportBrowser/Web3support.xcodeproj/project.pbxproj new file mode 100644 index 000000000..74ef4e9ab --- /dev/null +++ b/Example/Web3supportBrowser/Web3support.xcodeproj/project.pbxproj @@ -0,0 +1,768 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 51; + objects = { + +/* Begin PBXBuildFile section */ + 0D82D9B524144A20070A380A /* Pods_Web3supportTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D37FDD79B097544BA415C888 /* Pods_Web3supportTests.framework */; }; + 2FE7079C27F12F5890D59B2C /* Pods_Web3support_Web3supportUITests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 443B479AC12792B4697E499F /* Pods_Web3support_Web3supportUITests.framework */; }; + 97E61EDD7D6DF6BD5B5CF77C /* Pods_Web3support.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6EA6A6E3FB92A4AD5AC4F840 /* Pods_Web3support.framework */; }; + FA66096A26C1649000B52AD3 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA66096926C1649000B52AD3 /* AppDelegate.swift */; }; + FA66096C26C1649000B52AD3 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA66096B26C1649000B52AD3 /* SceneDelegate.swift */; }; + FA66096E26C1649000B52AD3 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA66096D26C1649000B52AD3 /* ViewController.swift */; }; + FA66097126C1649000B52AD3 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = FA66096F26C1649000B52AD3 /* Main.storyboard */; }; + FA66097326C1649200B52AD3 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = FA66097226C1649200B52AD3 /* Assets.xcassets */; }; + FA66097626C1649200B52AD3 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = FA66097426C1649200B52AD3 /* LaunchScreen.storyboard */; }; + FA66098126C1649200B52AD3 /* Web3supportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA66098026C1649200B52AD3 /* Web3supportTests.swift */; }; + FA66098C26C1649200B52AD3 /* Web3supportUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA66098B26C1649200B52AD3 /* Web3supportUITests.swift */; }; + FA66099A26C165D000B52AD3 /* FeatureTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA66099926C165D000B52AD3 /* FeatureTableViewCell.swift */; }; + FA66099D26C1688B00B52AD3 /* DappViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA66099C26C1688B00B52AD3 /* DappViewController.swift */; }; + FA66099F26C1956300B52AD3 /* BrowserViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA66099E26C1956300B52AD3 /* BrowserViewController.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + FA66097D26C1649200B52AD3 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = FA66095E26C1649000B52AD3 /* Project object */; + proxyType = 1; + remoteGlobalIDString = FA66096526C1649000B52AD3; + remoteInfo = Web3support; + }; + FA66098826C1649200B52AD3 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = FA66095E26C1649000B52AD3 /* Project object */; + proxyType = 1; + remoteGlobalIDString = FA66096526C1649000B52AD3; + remoteInfo = Web3support; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 035E27BB44A3A36210EFA49B /* Pods-Web3supportTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Web3supportTests.debug.xcconfig"; path = "Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests.debug.xcconfig"; sourceTree = ""; }; + 385348B861E9373EA372A587 /* Pods-Web3support-Web3supportUITests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Web3support-Web3supportUITests.debug.xcconfig"; path = "Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests.debug.xcconfig"; sourceTree = ""; }; + 443B479AC12792B4697E499F /* Pods_Web3support_Web3supportUITests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Web3support_Web3supportUITests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 6EA6A6E3FB92A4AD5AC4F840 /* Pods_Web3support.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Web3support.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 944E1C0A4E6497E06E79E736 /* Pods-Web3support-Web3supportUITests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Web3support-Web3supportUITests.release.xcconfig"; path = "Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests.release.xcconfig"; sourceTree = ""; }; + 9F3FEAD26D9D5BE05454C1BD /* Pods-Web3support.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Web3support.debug.xcconfig"; path = "Target Support Files/Pods-Web3support/Pods-Web3support.debug.xcconfig"; sourceTree = ""; }; + D1F887C2A2E528DF0D1893A4 /* Pods-Web3supportTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Web3supportTests.release.xcconfig"; path = "Target Support Files/Pods-Web3supportTests/Pods-Web3supportTests.release.xcconfig"; sourceTree = ""; }; + D37FDD79B097544BA415C888 /* Pods_Web3supportTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Web3supportTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + D7EACA43F06F3FEAC61E7239 /* Pods-Web3support.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Web3support.release.xcconfig"; path = "Target Support Files/Pods-Web3support/Pods-Web3support.release.xcconfig"; sourceTree = ""; }; + FA66096626C1649000B52AD3 /* Web3support.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Web3support.app; sourceTree = BUILT_PRODUCTS_DIR; }; + FA66096926C1649000B52AD3 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + FA66096B26C1649000B52AD3 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + FA66096D26C1649000B52AD3 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; + FA66097026C1649000B52AD3 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + FA66097226C1649200B52AD3 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + FA66097526C1649200B52AD3 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + FA66097726C1649200B52AD3 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + FA66097C26C1649200B52AD3 /* Web3supportTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = Web3supportTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + FA66098026C1649200B52AD3 /* Web3supportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Web3supportTests.swift; sourceTree = ""; }; + FA66098226C1649200B52AD3 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + FA66098726C1649200B52AD3 /* Web3supportUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = Web3supportUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + FA66098B26C1649200B52AD3 /* Web3supportUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Web3supportUITests.swift; sourceTree = ""; }; + FA66098D26C1649200B52AD3 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + FA66099926C165D000B52AD3 /* FeatureTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FeatureTableViewCell.swift; sourceTree = ""; }; + FA66099C26C1688B00B52AD3 /* DappViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DappViewController.swift; sourceTree = ""; }; + FA66099E26C1956300B52AD3 /* BrowserViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserViewController.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + FA66096326C1649000B52AD3 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 97E61EDD7D6DF6BD5B5CF77C /* Pods_Web3support.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FA66097926C1649200B52AD3 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 0D82D9B524144A20070A380A /* Pods_Web3supportTests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FA66098426C1649200B52AD3 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 2FE7079C27F12F5890D59B2C /* Pods_Web3support_Web3supportUITests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 1F784B381D107BBFC308CF39 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 6EA6A6E3FB92A4AD5AC4F840 /* Pods_Web3support.framework */, + 443B479AC12792B4697E499F /* Pods_Web3support_Web3supportUITests.framework */, + D37FDD79B097544BA415C888 /* Pods_Web3supportTests.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 612D4F5BBD952AD73CC5BEA4 /* Pods */ = { + isa = PBXGroup; + children = ( + 9F3FEAD26D9D5BE05454C1BD /* Pods-Web3support.debug.xcconfig */, + D7EACA43F06F3FEAC61E7239 /* Pods-Web3support.release.xcconfig */, + 385348B861E9373EA372A587 /* Pods-Web3support-Web3supportUITests.debug.xcconfig */, + 944E1C0A4E6497E06E79E736 /* Pods-Web3support-Web3supportUITests.release.xcconfig */, + 035E27BB44A3A36210EFA49B /* Pods-Web3supportTests.debug.xcconfig */, + D1F887C2A2E528DF0D1893A4 /* Pods-Web3supportTests.release.xcconfig */, + ); + path = Pods; + sourceTree = ""; + }; + FA66095D26C1649000B52AD3 = { + isa = PBXGroup; + children = ( + FA66096826C1649000B52AD3 /* Web3support */, + FA66097F26C1649200B52AD3 /* Web3supportTests */, + FA66098A26C1649200B52AD3 /* Web3supportUITests */, + FA66096726C1649000B52AD3 /* Products */, + 612D4F5BBD952AD73CC5BEA4 /* Pods */, + 1F784B381D107BBFC308CF39 /* Frameworks */, + ); + sourceTree = ""; + }; + FA66096726C1649000B52AD3 /* Products */ = { + isa = PBXGroup; + children = ( + FA66096626C1649000B52AD3 /* Web3support.app */, + FA66097C26C1649200B52AD3 /* Web3supportTests.xctest */, + FA66098726C1649200B52AD3 /* Web3supportUITests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + FA66096826C1649000B52AD3 /* Web3support */ = { + isa = PBXGroup; + children = ( + FA66099B26C1687A00B52AD3 /* ViewController */, + FA66096926C1649000B52AD3 /* AppDelegate.swift */, + FA66096B26C1649000B52AD3 /* SceneDelegate.swift */, + FA66099926C165D000B52AD3 /* FeatureTableViewCell.swift */, + FA66096D26C1649000B52AD3 /* ViewController.swift */, + FA66096F26C1649000B52AD3 /* Main.storyboard */, + FA66097226C1649200B52AD3 /* Assets.xcassets */, + FA66097426C1649200B52AD3 /* LaunchScreen.storyboard */, + FA66097726C1649200B52AD3 /* Info.plist */, + ); + path = Web3support; + sourceTree = ""; + }; + FA66097F26C1649200B52AD3 /* Web3supportTests */ = { + isa = PBXGroup; + children = ( + FA66098026C1649200B52AD3 /* Web3supportTests.swift */, + FA66098226C1649200B52AD3 /* Info.plist */, + ); + path = Web3supportTests; + sourceTree = ""; + }; + FA66098A26C1649200B52AD3 /* Web3supportUITests */ = { + isa = PBXGroup; + children = ( + FA66098B26C1649200B52AD3 /* Web3supportUITests.swift */, + FA66098D26C1649200B52AD3 /* Info.plist */, + ); + path = Web3supportUITests; + sourceTree = ""; + }; + FA66099B26C1687A00B52AD3 /* ViewController */ = { + isa = PBXGroup; + children = ( + FA66099C26C1688B00B52AD3 /* DappViewController.swift */, + FA66099E26C1956300B52AD3 /* BrowserViewController.swift */, + ); + path = ViewController; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + FA66096526C1649000B52AD3 /* Web3support */ = { + isa = PBXNativeTarget; + buildConfigurationList = FA66099026C1649200B52AD3 /* Build configuration list for PBXNativeTarget "Web3support" */; + buildPhases = ( + CE3012BEFBC8D1300A1A459C /* [CP] Check Pods Manifest.lock */, + FA66096226C1649000B52AD3 /* Sources */, + FA66096326C1649000B52AD3 /* Frameworks */, + FA66096426C1649000B52AD3 /* Resources */, + E6721A1B4B3EFF288E8A89EC /* [CP] Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Web3support; + productName = Web3support; + productReference = FA66096626C1649000B52AD3 /* Web3support.app */; + productType = "com.apple.product-type.application"; + }; + FA66097B26C1649200B52AD3 /* Web3supportTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = FA66099326C1649200B52AD3 /* Build configuration list for PBXNativeTarget "Web3supportTests" */; + buildPhases = ( + 94852A812754E9AA06B4658C /* [CP] Check Pods Manifest.lock */, + FA66097826C1649200B52AD3 /* Sources */, + FA66097926C1649200B52AD3 /* Frameworks */, + FA66097A26C1649200B52AD3 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + FA66097E26C1649200B52AD3 /* PBXTargetDependency */, + ); + name = Web3supportTests; + productName = Web3supportTests; + productReference = FA66097C26C1649200B52AD3 /* Web3supportTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + FA66098626C1649200B52AD3 /* Web3supportUITests */ = { + isa = PBXNativeTarget; + buildConfigurationList = FA66099626C1649200B52AD3 /* Build configuration list for PBXNativeTarget "Web3supportUITests" */; + buildPhases = ( + CF90CC4D779B8B15D5E87AD8 /* [CP] Check Pods Manifest.lock */, + FA66098326C1649200B52AD3 /* Sources */, + FA66098426C1649200B52AD3 /* Frameworks */, + FA66098526C1649200B52AD3 /* Resources */, + 872FC1A14C13C6C95D3DDE75 /* [CP] Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + FA66098926C1649200B52AD3 /* PBXTargetDependency */, + ); + name = Web3supportUITests; + productName = Web3supportUITests; + productReference = FA66098726C1649200B52AD3 /* Web3supportUITests.xctest */; + productType = "com.apple.product-type.bundle.ui-testing"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + FA66095E26C1649000B52AD3 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1250; + LastUpgradeCheck = 1250; + TargetAttributes = { + FA66096526C1649000B52AD3 = { + CreatedOnToolsVersion = 12.5.1; + }; + FA66097B26C1649200B52AD3 = { + CreatedOnToolsVersion = 12.5.1; + TestTargetID = FA66096526C1649000B52AD3; + }; + FA66098626C1649200B52AD3 = { + CreatedOnToolsVersion = 12.5.1; + TestTargetID = FA66096526C1649000B52AD3; + }; + }; + }; + buildConfigurationList = FA66096126C1649000B52AD3 /* Build configuration list for PBXProject "Web3support" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = FA66095D26C1649000B52AD3; + productRefGroup = FA66096726C1649000B52AD3 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + FA66096526C1649000B52AD3 /* Web3support */, + FA66097B26C1649200B52AD3 /* Web3supportTests */, + FA66098626C1649200B52AD3 /* Web3supportUITests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + FA66096426C1649000B52AD3 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + FA66097626C1649200B52AD3 /* LaunchScreen.storyboard in Resources */, + FA66097326C1649200B52AD3 /* Assets.xcassets in Resources */, + FA66097126C1649000B52AD3 /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FA66097A26C1649200B52AD3 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FA66098526C1649200B52AD3 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 872FC1A14C13C6C95D3DDE75 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Web3support-Web3supportUITests/Pods-Web3support-Web3supportUITests-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 94852A812754E9AA06B4658C /* [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-Web3supportTests-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; + }; + CE3012BEFBC8D1300A1A459C /* [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-Web3support-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; + }; + CF90CC4D779B8B15D5E87AD8 /* [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-Web3support-Web3supportUITests-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; + }; + E6721A1B4B3EFF288E8A89EC /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Web3support/Pods-Web3support-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + FA66096226C1649000B52AD3 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + FA66099A26C165D000B52AD3 /* FeatureTableViewCell.swift in Sources */, + FA66099F26C1956300B52AD3 /* BrowserViewController.swift in Sources */, + FA66096E26C1649000B52AD3 /* ViewController.swift in Sources */, + FA66096A26C1649000B52AD3 /* AppDelegate.swift in Sources */, + FA66099D26C1688B00B52AD3 /* DappViewController.swift in Sources */, + FA66096C26C1649000B52AD3 /* SceneDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FA66097826C1649200B52AD3 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + FA66098126C1649200B52AD3 /* Web3supportTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FA66098326C1649200B52AD3 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + FA66098C26C1649200B52AD3 /* Web3supportUITests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + FA66097E26C1649200B52AD3 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = FA66096526C1649000B52AD3 /* Web3support */; + targetProxy = FA66097D26C1649200B52AD3 /* PBXContainerItemProxy */; + }; + FA66098926C1649200B52AD3 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = FA66096526C1649000B52AD3 /* Web3support */; + targetProxy = FA66098826C1649200B52AD3 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + FA66096F26C1649000B52AD3 /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + FA66097026C1649000B52AD3 /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + FA66097426C1649200B52AD3 /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + FA66097526C1649200B52AD3 /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + FA66098E26C1649200B52AD3 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 14.5; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + FA66098F26C1649200B52AD3 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 14.5; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + FA66099126C1649200B52AD3 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9F3FEAD26D9D5BE05454C1BD /* Pods-Web3support.debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + INFOPLIST_FILE = Web3support/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 12.1; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = greenboxip.Web3support; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + FA66099226C1649200B52AD3 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D7EACA43F06F3FEAC61E7239 /* Pods-Web3support.release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + INFOPLIST_FILE = Web3support/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 12.1; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = greenboxip.Web3support; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; + FA66099426C1649200B52AD3 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 035E27BB44A3A36210EFA49B /* Pods-Web3supportTests.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + INFOPLIST_FILE = Web3supportTests/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 14.5; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = greenboxip.Web3supportTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Web3support.app/Web3support"; + }; + name = Debug; + }; + FA66099526C1649200B52AD3 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D1F887C2A2E528DF0D1893A4 /* Pods-Web3supportTests.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + INFOPLIST_FILE = Web3supportTests/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 14.5; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = greenboxip.Web3supportTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Web3support.app/Web3support"; + }; + name = Release; + }; + FA66099726C1649200B52AD3 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 385348B861E9373EA372A587 /* Pods-Web3support-Web3supportUITests.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + CODE_SIGN_STYLE = Automatic; + INFOPLIST_FILE = Web3supportUITests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = greenboxip.Web3supportUITests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_TARGET_NAME = Web3support; + }; + name = Debug; + }; + FA66099826C1649200B52AD3 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 944E1C0A4E6497E06E79E736 /* Pods-Web3support-Web3supportUITests.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + CODE_SIGN_STYLE = Automatic; + INFOPLIST_FILE = Web3supportUITests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = greenboxip.Web3supportUITests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_TARGET_NAME = Web3support; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + FA66096126C1649000B52AD3 /* Build configuration list for PBXProject "Web3support" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + FA66098E26C1649200B52AD3 /* Debug */, + FA66098F26C1649200B52AD3 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + FA66099026C1649200B52AD3 /* Build configuration list for PBXNativeTarget "Web3support" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + FA66099126C1649200B52AD3 /* Debug */, + FA66099226C1649200B52AD3 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + FA66099326C1649200B52AD3 /* Build configuration list for PBXNativeTarget "Web3supportTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + FA66099426C1649200B52AD3 /* Debug */, + FA66099526C1649200B52AD3 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + FA66099626C1649200B52AD3 /* Build configuration list for PBXNativeTarget "Web3supportUITests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + FA66099726C1649200B52AD3 /* Debug */, + FA66099826C1649200B52AD3 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = FA66095E26C1649000B52AD3 /* Project object */; +} diff --git a/Example/Web3supportBrowser/Web3support.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Example/Web3supportBrowser/Web3support.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..919434a62 --- /dev/null +++ b/Example/Web3supportBrowser/Web3support.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/Example/Web3supportBrowser/Web3support.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Example/Web3supportBrowser/Web3support.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/Example/Web3supportBrowser/Web3support.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/Example/Web3supportBrowser/Web3support.xcworkspace/contents.xcworkspacedata b/Example/Web3supportBrowser/Web3support.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..9ce6c1b26 --- /dev/null +++ b/Example/Web3supportBrowser/Web3support.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/Example/Web3supportBrowser/Web3support.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Example/Web3supportBrowser/Web3support.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/Example/Web3supportBrowser/Web3support.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/Example/Web3supportBrowser/Web3support.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/Example/Web3supportBrowser/Web3support.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 000000000..f9b0d7c5e --- /dev/null +++ b/Example/Web3supportBrowser/Web3support.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/Example/Web3supportBrowser/Web3support/AppDelegate.swift b/Example/Web3supportBrowser/Web3support/AppDelegate.swift new file mode 100644 index 000000000..fe602aa9f --- /dev/null +++ b/Example/Web3supportBrowser/Web3support/AppDelegate.swift @@ -0,0 +1,38 @@ +// +// AppDelegate.swift +// Web3support +// +// Created by Ravi Ranjan on 09/08/21. +// + +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 + } + + // MARK: UISceneSession Lifecycle + + @available(iOS 13.0, *) + func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { + // Called when a new scene session is being created. + // Use this method to select a configuration to create the new scene with. + return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) + } + + @available(iOS 13.0, *) + func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set) { + // Called when the user discards a scene session. + // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. + // Use this method to release any resources that were specific to the discarded scenes, as they will not return. + } + + +} + diff --git a/Example/Web3supportBrowser/Web3support/Assets.xcassets/AccentColor.colorset/Contents.json b/Example/Web3supportBrowser/Web3support/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 000000000..eb8789700 --- /dev/null +++ b/Example/Web3supportBrowser/Web3support/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,11 @@ +{ + "colors" : [ + { + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Example/Web3supportBrowser/Web3support/Assets.xcassets/AppIcon.appiconset/Contents.json b/Example/Web3supportBrowser/Web3support/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 000000000..9221b9bb1 --- /dev/null +++ b/Example/Web3supportBrowser/Web3support/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,98 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "20x20" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "20x20" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "29x29" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "29x29" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "40x40" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "40x40" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "60x60" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "60x60" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "20x20" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "20x20" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "29x29" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "29x29" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "40x40" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "40x40" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "76x76" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "76x76" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "83.5x83.5" + }, + { + "idiom" : "ios-marketing", + "scale" : "1x", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Example/Web3supportBrowser/Web3support/Assets.xcassets/Contents.json b/Example/Web3supportBrowser/Web3support/Assets.xcassets/Contents.json new file mode 100644 index 000000000..73c00596a --- /dev/null +++ b/Example/Web3supportBrowser/Web3support/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Example/Web3supportBrowser/Web3support/Base.lproj/LaunchScreen.storyboard b/Example/Web3supportBrowser/Web3support/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 000000000..356b2ddeb --- /dev/null +++ b/Example/Web3supportBrowser/Web3support/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Example/Web3supportBrowser/Web3support/Base.lproj/Main.storyboard b/Example/Web3supportBrowser/Web3support/Base.lproj/Main.storyboard new file mode 100644 index 000000000..a6ebf11e2 --- /dev/null +++ b/Example/Web3supportBrowser/Web3support/Base.lproj/Main.storyboard @@ -0,0 +1,112 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Example/Web3supportBrowser/Web3support/FeatureTableViewCell.swift b/Example/Web3supportBrowser/Web3support/FeatureTableViewCell.swift new file mode 100644 index 000000000..53851bd83 --- /dev/null +++ b/Example/Web3supportBrowser/Web3support/FeatureTableViewCell.swift @@ -0,0 +1,23 @@ +// +// FeatureTableViewCell.swift +// Web3support +// +// Created by Ravi Ranjan on 09/08/21. +// + +import UIKit + +class FeatureTableViewCell: UITableViewCell { + + override func awakeFromNib() { + super.awakeFromNib() + // Initialization code + } + + override func setSelected(_ selected: Bool, animated: Bool) { + super.setSelected(selected, animated: animated) + + // Configure the view for the selected state + } + +} diff --git a/Example/Web3supportBrowser/Web3support/Info.plist b/Example/Web3supportBrowser/Web3support/Info.plist new file mode 100644 index 000000000..5b531f7b2 --- /dev/null +++ b/Example/Web3supportBrowser/Web3support/Info.plist @@ -0,0 +1,66 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + $(PRODUCT_BUNDLE_PACKAGE_TYPE) + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneConfigurationName + Default Configuration + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UIApplicationSupportsIndirectInputEvents + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/Example/Web3supportBrowser/Web3support/SceneDelegate.swift b/Example/Web3supportBrowser/Web3support/SceneDelegate.swift new file mode 100644 index 000000000..895bf7624 --- /dev/null +++ b/Example/Web3supportBrowser/Web3support/SceneDelegate.swift @@ -0,0 +1,58 @@ +// +// SceneDelegate.swift +// Web3support +// +// Created by Ravi Ranjan on 09/08/21. +// + +import UIKit + +class SceneDelegate: UIResponder, UIWindowSceneDelegate { + + var window: UIWindow? + + + @available(iOS 13.0, *) + 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. + // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). + guard let _ = (scene as? UIWindowScene) else { return } + } + + @available(iOS 13.0, *) + func sceneDidDisconnect(_ scene: UIScene) { + // Called as the scene is being released by the system. + // This occurs shortly after the scene enters the background, or when its session is discarded. + // Release any resources associated with this scene that can be re-created the next time the scene connects. + // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). + } + + @available(iOS 13.0, *) + func sceneDidBecomeActive(_ scene: UIScene) { + // Called when the scene has moved from an inactive state to an active state. + // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. + } + + @available(iOS 13.0, *) + func sceneWillResignActive(_ scene: UIScene) { + // Called when the scene will move from an active state to an inactive state. + // This may occur due to temporary interruptions (ex. an incoming phone call). + } + + @available(iOS 13.0, *) + func sceneWillEnterForeground(_ scene: UIScene) { + // Called as the scene transitions from the background to the foreground. + // Use this method to undo the changes made on entering the background. + } + + @available(iOS 13.0, *) + func sceneDidEnterBackground(_ scene: UIScene) { + // Called as the scene transitions from the foreground to the background. + // Use this method to save data, release shared resources, and store enough scene-specific state information + // to restore the scene back to its current state. + } + + +} + diff --git a/Example/Web3supportBrowser/Web3support/ViewController.swift b/Example/Web3supportBrowser/Web3support/ViewController.swift new file mode 100644 index 000000000..df23f685d --- /dev/null +++ b/Example/Web3supportBrowser/Web3support/ViewController.swift @@ -0,0 +1,57 @@ +// +// ViewController.swift +// Web3support +// +// Created by Ravi Ranjan on 09/08/21. +// + +import UIKit + +class ViewController: UIViewController { + + @IBOutlet weak var featureTableView: UITableView! + override func viewDidLoad() { + super.viewDidLoad() + // Do any additional setup after loading the view. + self.conrollerInit() + + } + + + func conrollerInit() { + self.featureTableView.delegate = self + self.featureTableView.dataSource = self + + } + + fileprivate func featureOptions() -> [String] { + return ["dAPp"] + } +} + +extension ViewController: UITableViewDelegate, UITableViewDataSource { + func numberOfSections(in tableView: UITableView) -> Int { + 1 + } + func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + return featureOptions().count + } + func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + guard let featureCell = tableView.dequeueReusableCell(withIdentifier: "FeatureTableViewCell") as? FeatureTableViewCell else { + return UITableViewCell() + } + featureCell.textLabel?.text = featureOptions()[indexPath.row] + return featureCell + } + func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + switch indexPath.row { + case 0: + guard let dAppScreen = self.storyboard?.instantiateViewController(withIdentifier: "DappViewController") as? DappViewController else { + return + } + self.navigationController?.pushViewController(dAppScreen, animated: true) + default: + return + } + } +} diff --git a/Example/Web3supportBrowser/Web3support/ViewController/BrowserViewController.swift b/Example/Web3supportBrowser/Web3support/ViewController/BrowserViewController.swift new file mode 100644 index 000000000..91a591d1e --- /dev/null +++ b/Example/Web3supportBrowser/Web3support/ViewController/BrowserViewController.swift @@ -0,0 +1,130 @@ +// +// BrowserViewController.swift +// Web3support +// +// Created by Ravi Ranjan on 09/08/21. +// + +import UIKit + +import web3swift +import WebKit + +open class BrowserViewController: UIViewController { + + public enum Method: String { + case getAccounts + case signTransaction + case signMessage + case signPersonalMessage + case publishTransaction + case approveTransaction + } + + public lazy var webView: WKWebView = { + let websiteDataTypes = NSSet(array: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache]) + let date = NSDate(timeIntervalSince1970: 0) + + WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes as! Set, modifiedSince: date as Date, completionHandler:{ }) + let webView = WKWebView( + frame: .zero, + configuration: self.config + ) + webView.allowsBackForwardNavigationGestures = true + webView.scrollView.isScrollEnabled = true + webView.navigationDelegate = self + webView.configuration.preferences.setValue(true, forKey: "developerExtrasEnabled") + return webView + }() + + lazy var config: WKWebViewConfiguration = { + let config = WKWebViewConfiguration() + + var js = "" + + if let filepath = Bundle.main.path(forResource: "browser.min", ofType: "js") { + do { + js += try String(contentsOfFile: filepath) + NSLog("Loaded browser.js") + } catch { + NSLog("Failed to load web.js") + } + } else { + NSLog("web3.js not found in bundle") + } + let userScript = WKUserScript(source: js, injectionTime: .atDocumentStart, forMainFrameOnly: false) + config.userContentController.addUserScript(userScript) + return config + }() + + public func registerBridges(for web3: web3) { + self.webView.bridge.register({ (parameters, completion) in + let url = web3.provider.url.absoluteString + completion(.success(["rpcURL": url as Any])) + }, for: "getRPCurl") + + self.webView.bridge.register({ (parameters, completion) in + let allAccounts = web3.browserFunctions.getAccounts() + completion(.success(["accounts": allAccounts as Any])) + }, for: "eth_getAccounts") + + self.webView.bridge.register({ (parameters, completion) in + let coinbase = web3.browserFunctions.getCoinbase() + completion(.success(["coinbase": coinbase as Any])) + }, for: "eth_coinbase") + + self.webView.bridge.register({ (parameters, completion) in + if parameters == nil { + completion(.failure(Bridge.JSError(code: 0, description: "No parameters provided"))) + return + } + let payload = parameters!["payload"] as? [String:Any] + if payload == nil { + completion(.failure(Bridge.JSError(code: 0, description: "No parameters provided"))) + return + } + let personalMessage = payload!["data"] as? String + let account = payload!["from"] as? String + if personalMessage == nil || account == nil { + completion(.failure(Bridge.JSError(code: 0, description: "Not enough parameters provided"))) + return + } + let result = web3.browserFunctions.personalSign(personalMessage!, account: account!) + if result == nil { + completion(.failure(Bridge.JSError(code: 0, description: "Account or data is invalid"))) + return + } + completion(.success(["signedMessage": result as Any])) + }, for: "eth_sign") + + self.webView.bridge.register({ (parameters, completion) in + if parameters == nil { + completion(.failure(Bridge.JSError(code: 0, description: "No parameters provided"))) + return + } + let transaction = parameters!["transaction"] as? [String:Any] + if transaction == nil { + completion(.failure(Bridge.JSError(code: 0, description: "Not enough parameters provided"))) + return + } + let result = web3.browserFunctions.signTransaction(transaction!) + if result == nil { + completion(.failure(Bridge.JSError(code: 0, description: "Data is invalid"))) + return + } + completion(.success(["signedTransaction": result as Any])) + }, for: "eth_signTransaction") + } +} + +extension BrowserViewController: WKNavigationDelegate { + public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { + + } +} + +extension BrowserViewController: WKScriptMessageHandler { + public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { + NSLog("message \(message.body)") + } +} diff --git a/Example/Web3supportBrowser/Web3support/ViewController/DappViewController.swift b/Example/Web3supportBrowser/Web3support/ViewController/DappViewController.swift new file mode 100644 index 000000000..75568f510 --- /dev/null +++ b/Example/Web3supportBrowser/Web3support/ViewController/DappViewController.swift @@ -0,0 +1,61 @@ +// +// DappViewController.swift +// Web3support +// +// Created by Ravi Ranjan on 09/08/21. +// + +import UIKit +import WebKit +import web3swift +class DappViewController: BrowserViewController { + + @IBOutlet weak var dappWebKitScreen: WKWebView! + override func viewDidLoad() { + super.viewDidLoad() + var urlToOpen = "https://1inch.exchange/" + urlToOpen = "https://app.compound.finance" +// urlToOpen = "https://app.uniswap.org" +// urlToOpen = "https://exchange.pancakeswap.finance/#/swap" + + + + dappWebKitScreen.load(URLRequest(url: URL(string: urlToOpen)!)) + + let web3 = Web3.InfuraMainnetWeb3() + web3.addKeystoreManager(FilestoreWrapper.getKeystoreManager()) + + self.registerBridges(for: web3) + + + // Do any additional setup after loading the view. + } + + + + +} +class FilestoreWrapper: NSObject { + /// Get KeyStore manager Instance + /// + /// - Parameters: nil + /// - Returns: Key store manager + static func getKeystoreManager () -> KeystoreManager? { + let userDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + let path = userDir+"/keystore/" + let userLoginType = UserDefaults.standard.value(forKey: "KeyConstants.UserDefaults.kUserLoginType") as? String ?? "create" + if userLoginType == "create" { + return KeystoreManager.managerForPath(path, scanForHDwallets: true, suffix: "json") + } else { + return KeystoreManager.managerForPath(path) + } + } + /// Get Wallet address + /// + /// - Parameters: + /// - Returns: Current wallet address + static func getWalletAddress () -> String? { + return getKeystoreManager()?.addresses?.first?.address + } + +} diff --git a/Example/Web3supportBrowser/Web3supportTests/Info.plist b/Example/Web3supportBrowser/Web3supportTests/Info.plist new file mode 100644 index 000000000..64d65ca49 --- /dev/null +++ b/Example/Web3supportBrowser/Web3supportTests/Info.plist @@ -0,0 +1,22 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + $(PRODUCT_BUNDLE_PACKAGE_TYPE) + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + + diff --git a/Example/Web3supportBrowser/Web3supportTests/Web3supportTests.swift b/Example/Web3supportBrowser/Web3supportTests/Web3supportTests.swift new file mode 100644 index 000000000..314f4ae66 --- /dev/null +++ b/Example/Web3supportBrowser/Web3supportTests/Web3supportTests.swift @@ -0,0 +1,33 @@ +// +// Web3supportTests.swift +// Web3supportTests +// +// Created by Ravi Ranjan on 09/08/21. +// + +import XCTest +@testable import Web3support + +class Web3supportTests: XCTestCase { + + override func setUpWithError() throws { + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + override func tearDownWithError() throws { + // Put teardown code here. This method is called after the invocation of each test method in the class. + } + + func testExample() throws { + // This is an example of a functional test case. + // Use XCTAssert and related functions to verify your tests produce the correct results. + } + + func testPerformanceExample() throws { + // This is an example of a performance test case. + self.measure { + // Put the code you want to measure the time of here. + } + } + +} diff --git a/Example/Web3supportBrowser/Web3supportUITests/Info.plist b/Example/Web3supportBrowser/Web3supportUITests/Info.plist new file mode 100644 index 000000000..64d65ca49 --- /dev/null +++ b/Example/Web3supportBrowser/Web3supportUITests/Info.plist @@ -0,0 +1,22 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + $(PRODUCT_BUNDLE_PACKAGE_TYPE) + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + + diff --git a/Example/Web3supportBrowser/Web3supportUITests/Web3supportUITests.swift b/Example/Web3supportBrowser/Web3supportUITests/Web3supportUITests.swift new file mode 100644 index 000000000..b71d0aca6 --- /dev/null +++ b/Example/Web3supportBrowser/Web3supportUITests/Web3supportUITests.swift @@ -0,0 +1,42 @@ +// +// Web3supportUITests.swift +// Web3supportUITests +// +// Created by Ravi Ranjan on 09/08/21. +// + +import XCTest + +class Web3supportUITests: XCTestCase { + + override func setUpWithError() throws { + // Put setup code here. This method is called before the invocation of each test method in the class. + + // In UI tests it is usually best to stop immediately when a failure occurs. + continueAfterFailure = false + + // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. + } + + override func tearDownWithError() throws { + // Put teardown code here. This method is called after the invocation of each test method in the class. + } + + func testExample() throws { + // UI tests must launch the application that they test. + let app = XCUIApplication() + app.launch() + + // Use recording to get started writing UI tests. + // Use XCTAssert and related functions to verify your tests produce the correct results. + } + + func testLaunchPerformance() throws { + if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) { + // This measures how long it takes to launch your application. + measure(metrics: [XCTApplicationLaunchMetric()]) { + XCUIApplication().launch() + } + } + } +} From d91e44427def82ed27811251ef08fbf393a32901 Mon Sep 17 00:00:00 2001 From: Ravi Ranjan Date: Tue, 10 Aug 2021 23:34:34 +0530 Subject: [PATCH 02/12] Dapp Isseue solved Example with Issue number #338 #337 #321 #304 #303 --- .../Web3support/AppDelegate.swift | 1 - .../ViewController/BrowserViewController.swift | 15 +++++++-------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/Example/Web3supportBrowser/Web3support/AppDelegate.swift b/Example/Web3supportBrowser/Web3support/AppDelegate.swift index fe602aa9f..e2553d695 100644 --- a/Example/Web3supportBrowser/Web3support/AppDelegate.swift +++ b/Example/Web3supportBrowser/Web3support/AppDelegate.swift @@ -11,7 +11,6 @@ import UIKit class AppDelegate: UIResponder, UIApplicationDelegate { - func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true diff --git a/Example/Web3supportBrowser/Web3support/ViewController/BrowserViewController.swift b/Example/Web3supportBrowser/Web3support/ViewController/BrowserViewController.swift index 91a591d1e..dad88bbe1 100644 --- a/Example/Web3supportBrowser/Web3support/ViewController/BrowserViewController.swift +++ b/Example/Web3supportBrowser/Web3support/ViewController/BrowserViewController.swift @@ -6,7 +6,6 @@ // import UIKit - import web3swift import WebKit @@ -26,15 +25,15 @@ open class BrowserViewController: UIViewController { let date = NSDate(timeIntervalSince1970: 0) WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes as! Set, modifiedSince: date as Date, completionHandler:{ }) - let webView = WKWebView( + let webKitView = WKWebView( frame: .zero, configuration: self.config ) - webView.allowsBackForwardNavigationGestures = true - webView.scrollView.isScrollEnabled = true - webView.navigationDelegate = self - webView.configuration.preferences.setValue(true, forKey: "developerExtrasEnabled") - return webView + webKitView.allowsBackForwardNavigationGestures = true + webKitView.scrollView.isScrollEnabled = true + webKitView.navigationDelegate = self + webKitView.configuration.preferences.setValue(true, forKey: "developerExtrasEnabled") + return webKitView }() lazy var config: WKWebViewConfiguration = { @@ -119,7 +118,7 @@ open class BrowserViewController: UIViewController { extension BrowserViewController: WKNavigationDelegate { public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { - + print("Navigation is completed") } } From f794d34ec62d508030c2dbd143649d5aba3199ea Mon Sep 17 00:00:00 2001 From: Ravi Ranjan Date: Sun, 22 Aug 2021 01:18:18 +0530 Subject: [PATCH 03/12] Updated wallet creat and Private key get helper method --- HelperMethodsForApp/CreateWalletWrapper.swift | 58 +++++++++++++++++++ HelperMethodsForApp/KeystoreWrapper.swift | 32 ++++++++++ 2 files changed, 90 insertions(+) create mode 100644 HelperMethodsForApp/CreateWalletWrapper.swift create mode 100644 HelperMethodsForApp/KeystoreWrapper.swift diff --git a/HelperMethodsForApp/CreateWalletWrapper.swift b/HelperMethodsForApp/CreateWalletWrapper.swift new file mode 100644 index 000000000..d6ba297f7 --- /dev/null +++ b/HelperMethodsForApp/CreateWalletWrapper.swift @@ -0,0 +1,58 @@ +// +// CreateWalletWrapper.swift +// Wallet +// +// Created by Ravi Ranjan on 22/08/21. +// Copyright © 2021 oodlesTechnologies_r.ranjanchn@gmail.com. All rights reserved. +// + +import Foundation +import Foundation +import web3swift +class CreateWalletWrapper: NSObject { + /* + Create wallet method + */ + var prefixPath: String + init(prefixPath:String) { + self.prefixPath = prefixPath + } + + public func createWallet() throws { + + var web3KeyStore: BIP32Keystore? + let userDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + let web3KeystoreManager = KeystoreManager.managerForPath(userDir + "/keystore") + do { + if (web3KeystoreManager?.addresses.count ?? 0 >= 0) { + let web3Mnemonics = Mnemonics(entropySize: EntropySize.b128, language: .english) + print(web3Mnemonics.description) + /* + save Mnemonics for later user also it can be stored some other place + */ + UserDefaults.standard.set(web3Mnemonics.description, forKey: KeyConstants.UserDefaults.kUserMnemonics) + web3KeyStore = try BIP32Keystore(mnemonics: web3Mnemonics, prefixPath: prefixPath) + print("keystore", web3KeyStore as Any) + guard let kStore = web3KeyStore else { + return + } + let address = kStore.addresses.first + let param = kStore.keystoreParams + #if DEBUG + print("Mnemonics :-> ", web3Mnemonics.description) + print("Address :::>>>>> ", address as Any) + print("Address :::>>>>> ", kStore.addresses as Any) + let privatKey = try kStore.UNSAFE_getPrivateKeyData(password: "", account: address!) + print(privatKey, "Is the private key") + #endif + let keyData = try? JSONEncoder().encode(param) + FileManager.default.createFile(atPath: userDir + "/keystore"+"/key.json", contents: keyData, attributes: nil) + } else { + web3KeyStore = web3KeystoreManager?.walletForAddress((web3KeystoreManager?.addresses[0])!) as? BIP32Keystore + } + } catch { + throw WalletCreationError.error + } + } + +} diff --git a/HelperMethodsForApp/KeystoreWrapper.swift b/HelperMethodsForApp/KeystoreWrapper.swift new file mode 100644 index 000000000..8c924eee0 --- /dev/null +++ b/HelperMethodsForApp/KeystoreWrapper.swift @@ -0,0 +1,32 @@ +// +// KeystoreWrapper.swift +// Wethio Wallet +// +// Created by Ravi Ranjan on 22/08/21. +// Copyright © 2021 oodlesTechnologies_r.ranjanchn@gmail.com. All rights reserved. +// + +import Foundation +import web3swift + +class KeystoreWrapper: NSObject { + /// Get KeyStore manager Instance + /// + /// - Parameters: nil + /// - Returns: Key store manager + + static func getKeystoreManager () -> KeystoreManager? { + let userDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + let path = userDir+"/keystore/" + return KeystoreManager.managerForPath(path, scanForHDwallets: true, suffix: "json") + + } + /// Get Wallet address + /// + /// - Parameters: + /// - Returns: Current wallet address + static func getWalletAddress () -> String? { + return getKeystoreManager()?.addresses.first?.address + } + +} From 83c6d322348f2f13cfb40a35be4c2e9e71a62a98 Mon Sep 17 00:00:00 2001 From: Ravi Ranjan Date: Thu, 2 Sep 2021 16:10:11 +0530 Subject: [PATCH 04/12] Uniswap connect with formattc connect, temp account given in dAppviewcontroller --- .../ViewController/DappViewController.swift | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Example/Web3supportBrowser/Web3support/ViewController/DappViewController.swift b/Example/Web3supportBrowser/Web3support/ViewController/DappViewController.swift index 75568f510..59eb9c485 100644 --- a/Example/Web3supportBrowser/Web3support/ViewController/DappViewController.swift +++ b/Example/Web3supportBrowser/Web3support/ViewController/DappViewController.swift @@ -14,8 +14,12 @@ class DappViewController: BrowserViewController { override func viewDidLoad() { super.viewDidLoad() var urlToOpen = "https://1inch.exchange/" - urlToOpen = "https://app.compound.finance" -// urlToOpen = "https://app.uniswap.org" +// urlToOpen = "https://app.compound.finance" + urlToOpen = "https://app.uniswap.org" + + //Connect with formatic connect +// email:ravi@yopmail.com +// pasword: Gauransh7 // urlToOpen = "https://exchange.pancakeswap.finance/#/swap" @@ -30,10 +34,6 @@ class DappViewController: BrowserViewController { // Do any additional setup after loading the view. } - - - - } class FilestoreWrapper: NSObject { /// Get KeyStore manager Instance From 7c8cd92122b9d6296a5f04e4aa4d08d822d7549a Mon Sep 17 00:00:00 2001 From: Ravi Ranjan Date: Mon, 4 Oct 2021 00:58:56 +0530 Subject: [PATCH 05/12] Updated major version of Promise Kit, Big INt --- Package.resolved | 25 ++++++++----------------- Package.swift | 6 +++--- 2 files changed, 11 insertions(+), 20 deletions(-) diff --git a/Package.resolved b/Package.resolved index 6cba9e215..36c60218e 100755 --- a/Package.resolved +++ b/Package.resolved @@ -6,8 +6,8 @@ "repositoryURL": "https://github.com/attaswift/BigInt.git", "state": { "branch": null, - "revision": "889a1ecacd73ccc189c5cb29288048f186c44ed9", - "version": "5.2.1" + "revision": "0ed110f7555c34ff468e72e1686e59721f2b0da6", + "version": "5.3.0" } }, { @@ -15,8 +15,8 @@ "repositoryURL": "https://github.com/krzyzanowskim/CryptoSwift.git", "state": { "branch": null, - "revision": "4e31051c63cc0ddf10a25cf5318856c510cf77f4", - "version": "1.4.0" + "revision": "4b0565384d3c4c588af09e660535b2c7c9bf5b39", + "version": "1.4.2" } }, { @@ -24,8 +24,8 @@ "repositoryURL": "https://github.com/mxcl/PromiseKit.git", "state": { "branch": null, - "revision": "d2f7ba14bcdc45e18f4f60ad9df883fb9055f081", - "version": "6.15.3" + "revision": "2ff97931d2721ecae9f94d8cbf4cf853a7d79180", + "version": "6.16.0" } }, { @@ -33,17 +33,8 @@ "repositoryURL": "https://github.com/daltoniam/Starscream.git", "state": { "branch": null, - "revision": "e6b65c6d9077ea48b4a7bdda8994a1d3c6969c8d", - "version": "3.1.1" - } - }, - { - "package": "swift-nio-zlib-support", - "repositoryURL": "https://github.com/apple/swift-nio-zlib-support.git", - "state": { - "branch": null, - "revision": "37760e9a52030bb9011972c5213c3350fa9d41fd", - "version": "1.0.0" + "revision": "df8d82047f6654d8e4b655d1b1525c64e1059d21", + "version": "4.0.4" } } ] diff --git a/Package.swift b/Package.swift index 2d2466274..1a87656a4 100755 --- a/Package.swift +++ b/Package.swift @@ -14,10 +14,10 @@ let package = Package( ], dependencies: [ - .package(url: "https://github.com/attaswift/BigInt.git", from: "5.2.0"), - .package(url: "https://github.com/mxcl/PromiseKit.git", from: "6.15.3"), + .package(url: "https://github.com/attaswift/BigInt.git", from: "5.3.0"), + .package(url: "https://github.com/mxcl/PromiseKit.git", from: "6.15.4"), .package(url: "https://github.com/daltoniam/Starscream.git", from: "4.0.4"), - .package(url: "https://github.com/krzyzanowskim/CryptoSwift.git", from: "1.4.0"), + .package(url: "https://github.com/krzyzanowskim/CryptoSwift.git", from: "1.4.2"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. From 8011bf1847667b12d9a428c47e9e814d48d375ed Mon Sep 17 00:00:00 2001 From: Veer Chauhan Date: Thu, 21 Oct 2021 21:43:01 +0530 Subject: [PATCH 06/12] Update Podfile --- Example/Web3supportBrowser/Podfile | 1 + 1 file changed, 1 insertion(+) diff --git a/Example/Web3supportBrowser/Podfile b/Example/Web3supportBrowser/Podfile index 57eaae961..6a40725d7 100644 --- a/Example/Web3supportBrowser/Podfile +++ b/Example/Web3supportBrowser/Podfile @@ -1,4 +1,5 @@ # Uncomment the next line to define a global platform for your project +# fixes all problems with CocoaPods on M1 macs: source 'https://github.com/CocoaPods/Specs.git' # platform :ios, '9.0' target 'Web3support' do From ba6bee23767026c737c34c9c3e5d9798f41089c1 Mon Sep 17 00:00:00 2001 From: Veer Chauhan Date: Thu, 21 Oct 2021 21:50:24 +0530 Subject: [PATCH 07/12] Update Podfile --- Example/Web3supportBrowser/Podfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Example/Web3supportBrowser/Podfile b/Example/Web3supportBrowser/Podfile index 6a40725d7..ed8c660de 100644 --- a/Example/Web3supportBrowser/Podfile +++ b/Example/Web3supportBrowser/Podfile @@ -1,5 +1,5 @@ # Uncomment the next line to define a global platform for your project -# fixes all problems with CocoaPods on M1 macs: source 'https://github.com/CocoaPods/Specs.git' +fixes all problems with CocoaPods on M1 macs: source 'https://github.com/CocoaPods/Specs.git' # platform :ios, '9.0' target 'Web3support' do From 2b78567b50b0b7631014828b78e26bc1242efbdd Mon Sep 17 00:00:00 2001 From: Veer Chauhan Date: Thu, 21 Oct 2021 21:52:57 +0530 Subject: [PATCH 08/12] Update Podfile --- Example/Web3supportBrowser/Podfile | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Example/Web3supportBrowser/Podfile b/Example/Web3supportBrowser/Podfile index ed8c660de..b4945c02d 100644 --- a/Example/Web3supportBrowser/Podfile +++ b/Example/Web3supportBrowser/Podfile @@ -1,7 +1,8 @@ # Uncomment the next line to define a global platform for your project -fixes all problems with CocoaPods on M1 macs: source 'https://github.com/CocoaPods/Specs.git' # platform :ios, '9.0' +source 'https://github.com/CocoaPods/Specs.git' + target 'Web3support' do # Comment the next line if you don't want to use dynamic frameworks use_frameworks! From d05a569a1dbb43b3770832cfa2be703ec26ca894 Mon Sep 17 00:00:00 2001 From: Veer Chauhan Date: Thu, 21 Oct 2021 22:23:31 +0530 Subject: [PATCH 09/12] Update Web3+Utils.swift Typo Fix --- Sources/web3swift/Web3/Web3+Utils.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/web3swift/Web3/Web3+Utils.swift b/Sources/web3swift/Web3/Web3+Utils.swift index 82ca74a74..ed130482e 100755 --- a/Sources/web3swift/Web3/Web3+Utils.swift +++ b/Sources/web3swift/Web3/Web3+Utils.swift @@ -26,7 +26,7 @@ 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 calcualteContractAddress(from: EthereumAddress, nonce: BigUInt) -> EthereumAddress? { + 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] as [AnyObject]) else {return nil} guard let contractAddressData = Web3.Utils.sha3(data)?[12..<32] else {return nil} From ab77d467137edfa97c28075891a0698c8c65cf96 Mon Sep 17 00:00:00 2001 From: Ravi Ranjan Date: Fri, 22 Oct 2021 02:41:21 +0530 Subject: [PATCH 10/12] Updated wallet example for mac M! chip --- Example/myWeb3Wallet/Podfile | 21 + Example/myWeb3Wallet/Podfile.lock | 53 + Example/myWeb3Wallet/Pods/BigInt/LICENSE.md | 20 + Example/myWeb3Wallet/Pods/BigInt/README.md | 430 + .../Pods/BigInt/Sources/Addition.swift | 126 + .../Pods/BigInt/Sources/BigInt.swift | 74 + .../Pods/BigInt/Sources/BigUInt.swift | 386 + .../Pods/BigInt/Sources/Bitwise Ops.swift | 121 + .../Pods/BigInt/Sources/Codable.swift | 155 + .../Pods/BigInt/Sources/Comparable.swift | 63 + .../Pods/BigInt/Sources/Data Conversion.swift | 179 + .../Pods/BigInt/Sources/Division.swift | 374 + .../Pods/BigInt/Sources/Exponentiation.swift | 119 + .../Sources/Floating Point Conversion.swift | 73 + .../Pods/BigInt/Sources/GCD.swift | 80 + .../Pods/BigInt/Sources/Hashable.swift | 26 + .../BigInt/Sources/Integer Conversion.swift | 89 + .../Pods/BigInt/Sources/Multiplication.swift | 165 + .../Pods/BigInt/Sources/Prime Test.swift | 153 + .../Pods/BigInt/Sources/Random.swift | 101 + .../Pods/BigInt/Sources/Shifts.swift | 211 + .../Pods/BigInt/Sources/Square Root.swift | 41 + .../Pods/BigInt/Sources/Strideable.swift | 38 + .../BigInt/Sources/String Conversion.swift | 236 + .../Pods/BigInt/Sources/Subtraction.swift | 169 + .../Pods/BigInt/Sources/Words and Bits.swift | 202 + Example/myWeb3Wallet/Pods/CryptoSwift/LICENSE | 11 + .../myWeb3Wallet/Pods/CryptoSwift/README.md | 551 + .../Sources/CryptoSwift/AEAD/AEAD.swift | 40 + .../AEAD/AEADChaCha20Poly1305.swift | 59 + .../Sources/CryptoSwift/AES.Cryptors.swift | 39 + .../CryptoSwift/Sources/CryptoSwift/AES.swift | 556 + .../Sources/CryptoSwift/Array+Extension.swift | 150 + .../Sources/CryptoSwift/Authenticator.swift | 20 + .../CryptoSwift/BatchedCollection.swift | 81 + .../CryptoSwift/Sources/CryptoSwift/Bit.swift | 26 + .../Sources/CryptoSwift/BlockCipher.swift | 18 + .../Sources/CryptoSwift/BlockDecryptor.swift | 98 + .../Sources/CryptoSwift/BlockEncryptor.swift | 62 + .../CryptoSwift/BlockMode/BlockMode.swift | 26 + .../BlockMode/BlockModeOptions.swift | 34 + .../Sources/CryptoSwift/BlockMode/CBC.swift | 76 + .../Sources/CryptoSwift/BlockMode/CCM.swift | 365 + .../Sources/CryptoSwift/BlockMode/CFB.swift | 102 + .../Sources/CryptoSwift/BlockMode/CTR.swift | 138 + .../BlockMode/CipherModeWorker.swift | 64 + .../Sources/CryptoSwift/BlockMode/ECB.swift | 53 + .../Sources/CryptoSwift/BlockMode/GCM.swift | 374 + .../Sources/CryptoSwift/BlockMode/OCB.swift | 398 + .../Sources/CryptoSwift/BlockMode/OFB.swift | 73 + .../Sources/CryptoSwift/BlockMode/PCBC.swift | 74 + .../Sources/CryptoSwift/Blowfish.swift | 537 + .../Sources/CryptoSwift/CBCMAC.swift | 30 + .../Sources/CryptoSwift/CMAC.swift | 106 + .../Sources/CryptoSwift/ChaCha20.swift | 347 + .../Sources/CryptoSwift/Checksum.swift | 208 + .../Sources/CryptoSwift/Cipher.swift | 47 + .../CryptoSwift/Collection+Extension.swift | 61 + .../Sources/CryptoSwift/CompactMap.swift | 25 + .../Sources/CryptoSwift/Cryptor.swift | 22 + .../Sources/CryptoSwift/Cryptors.swift | 44 + .../Sources/CryptoSwift/Digest.swift | 78 + .../Sources/CryptoSwift/DigestType.swift | 18 + .../Foundation/AES+Foundation.swift | 32 + .../Foundation/Array+Foundation.swift | 32 + .../Foundation/Blowfish+Foundation.swift | 23 + .../Foundation/ChaCha20+Foundation.swift | 22 + .../Foundation/Data+Extension.swift | 92 + .../Foundation/HMAC+Foundation.swift | 22 + .../Foundation/Rabbit+Foundation.swift | 26 + .../String+FoundationExtension.swift | 41 + .../Foundation/Utils+Foundation.swift | 27 + .../Sources/CryptoSwift/Generics.swift | 43 + .../Sources/CryptoSwift/HKDF.swift | 86 + .../Sources/CryptoSwift/HMAC.swift | 124 + .../Sources/CryptoSwift/ISO10126Padding.swift | 56 + .../Sources/CryptoSwift/ISO78164Padding.swift | 44 + .../Sources/CryptoSwift/Int+Extension.swift | 33 + .../CryptoSwift/Sources/CryptoSwift/MD5.swift | 161 + .../Sources/CryptoSwift/NoPadding.swift | 27 + .../Sources/CryptoSwift/Operators.swift | 32 + .../Sources/CryptoSwift/PKCS/PBKDF1.swift | 97 + .../Sources/CryptoSwift/PKCS/PBKDF2.swift | 118 + .../Sources/CryptoSwift/PKCS/PKCS5.swift | 22 + .../Sources/CryptoSwift/PKCS/PKCS7.swift | 18 + .../CryptoSwift/PKCS/PKCS7Padding.swift | 62 + .../Sources/CryptoSwift/Padding.swift | 57 + .../Sources/CryptoSwift/Poly1305.swift | 165 + .../Sources/CryptoSwift/Rabbit.swift | 221 + .../Sources/CryptoSwift/SHA1.swift | 158 + .../Sources/CryptoSwift/SHA2.swift | 368 + .../Sources/CryptoSwift/SHA3.swift | 299 + .../Sources/CryptoSwift/Scrypt.swift | 256 + .../Sources/CryptoSwift/SecureBytes.swift | 87 + .../Sources/CryptoSwift/StreamDecryptor.swift | 92 + .../Sources/CryptoSwift/StreamEncryptor.swift | 68 + .../CryptoSwift/String+Extension.swift | 96 + .../Sources/CryptoSwift/UInt128.swift | 90 + .../CryptoSwift/UInt16+Extension.swift | 37 + .../CryptoSwift/UInt32+Extension.swift | 51 + .../CryptoSwift/UInt64+Extension.swift | 44 + .../Sources/CryptoSwift/UInt8+Extension.swift | 74 + .../Sources/CryptoSwift/Updatable.swift | 107 + .../Sources/CryptoSwift/Utils.swift | 117 + .../Sources/CryptoSwift/ZeroPadding.swift | 40 + .../Local Podspecs/web3swift.podspec.json | 53 + Example/myWeb3Wallet/Pods/Manifest.lock | 53 + .../Pods/Pods.xcodeproj/project.pbxproj | 3443 + .../Sources/NSNotificationCenter+AnyPromise.h | 44 + .../Sources/NSNotificationCenter+AnyPromise.m | 18 + .../NSNotificationCenter+Promise.swift | 33 + .../Foundation/Sources/NSObject+Promise.swift | 57 + .../Foundation/Sources/NSTask+AnyPromise.h | 53 + .../Foundation/Sources/NSTask+AnyPromise.m | 59 + .../Sources/NSURLSession+AnyPromise.h | 79 + .../Sources/NSURLSession+AnyPromise.m | 113 + .../Sources/NSURLSession+Promise.swift | 246 + .../Foundation/Sources/PMKFoundation.h | 3 + .../Foundation/Sources/Process+Promise.swift | 190 + .../Foundation/Sources/afterlife.swift | 26 + .../Extensions/UIKit/Sources/PMKUIKit.h | 8 + .../UIKit/Sources/UIView+AnyPromise.h | 80 + .../UIKit/Sources/UIView+AnyPromise.m | 64 + .../UIKit/Sources/UIView+Promise.swift | 115 + .../Sources/UIViewController+AnyPromise.h | 71 + .../Sources/UIViewController+AnyPromise.m | 140 + .../UIViewPropertyAnimator+Promise.swift | 14 + Example/myWeb3Wallet/Pods/PromiseKit/LICENSE | 20 + .../myWeb3Wallet/Pods/PromiseKit/README.md | 211 + .../PromiseKit/Sources/AnyPromise+Private.h | 32 + .../Pods/PromiseKit/Sources/AnyPromise.h | 308 + .../Pods/PromiseKit/Sources/AnyPromise.m | 179 + .../Pods/PromiseKit/Sources/AnyPromise.swift | 224 + .../Pods/PromiseKit/Sources/Box.swift | 101 + .../Pods/PromiseKit/Sources/Catchable.swift | 256 + .../PromiseKit/Sources/Configuration.swift | 35 + .../Sources/CustomStringConvertible.swift | 44 + .../PromiseKit/Sources/Deprecations.swift | 93 + .../Pods/PromiseKit/Sources/Error.swift | 111 + .../Pods/PromiseKit/Sources/Guarantee.swift | 390 + .../Pods/PromiseKit/Sources/LogEvent.swift | 30 + .../Sources/NSMethodSignatureForBlock.m | 77 + .../PromiseKit/Sources/PMKCallVariadicBlock.m | 120 + .../Pods/PromiseKit/Sources/Promise.swift | 184 + .../Pods/PromiseKit/Sources/PromiseKit.h | 7 + .../Pods/PromiseKit/Sources/Resolver.swift | 111 + .../Pods/PromiseKit/Sources/Thenable.swift | 533 + .../Pods/PromiseKit/Sources/after.m | 14 + .../Pods/PromiseKit/Sources/after.swift | 46 + .../PromiseKit/Sources/dispatch_promise.m | 10 + .../Pods/PromiseKit/Sources/firstly.swift | 39 + .../Pods/PromiseKit/Sources/fwd.h | 165 + .../Pods/PromiseKit/Sources/hang.m | 29 + .../Pods/PromiseKit/Sources/hang.swift | 55 + .../Pods/PromiseKit/Sources/join.m | 54 + .../Pods/PromiseKit/Sources/race.m | 9 + .../Pods/PromiseKit/Sources/race.swift | 102 + .../Pods/PromiseKit/Sources/when.m | 107 + .../Pods/PromiseKit/Sources/when.swift | 363 + Example/myWeb3Wallet/Pods/Starscream/LICENSE | 176 + .../myWeb3Wallet/Pods/Starscream/README.md | 308 + .../Sources/Compression/Compression.swift | 29 + .../Sources/Compression/WSCompression.swift | 247 + .../Sources/DataBytes/Data+Extensions.swift | 53 + .../Starscream/Sources/Engine/Engine.swift | 22 + .../Sources/Engine/NativeEngine.swift | 96 + .../Starscream/Sources/Engine/WSEngine.swift | 234 + .../Framer/FoundationHTTPHandler.swift | 123 + .../Framer/FoundationHTTPServerHandler.swift | 99 + .../Sources/Framer/FrameCollector.swift | 107 + .../Starscream/Sources/Framer/Framer.swift | 365 + .../Sources/Framer/HTTPHandler.swift | 148 + .../Sources/Framer/StringHTTPHandler.swift | 143 + .../Sources/Security/FoundationSecurity.swift | 101 + .../Sources/Security/Security.swift | 45 + .../Starscream/Sources/Server/Server.swift | 56 + .../Sources/Server/WebSocketServer.swift | 196 + .../Sources/Starscream/WebSocket.swift | 178 + .../Transport/FoundationTransport.swift | 218 + .../Sources/Transport/TCPTransport.swift | 159 + .../Sources/Transport/Transport.swift | 55 + .../BigInt/BigInt-Info.plist | 26 + .../BigInt/BigInt-dummy.m | 5 + .../BigInt/BigInt-prefix.pch | 12 + .../BigInt/BigInt-umbrella.h | 16 + .../BigInt/BigInt.debug.xcconfig | 13 + .../BigInt/BigInt.modulemap | 6 + .../BigInt/BigInt.release.xcconfig | 13 + .../CryptoSwift/CryptoSwift-Info.plist | 26 + .../CryptoSwift/CryptoSwift-dummy.m | 5 + .../CryptoSwift/CryptoSwift-prefix.pch | 12 + .../CryptoSwift/CryptoSwift-umbrella.h | 16 + .../CryptoSwift/CryptoSwift.debug.xcconfig | 13 + .../CryptoSwift/CryptoSwift.modulemap | 6 + .../CryptoSwift/CryptoSwift.release.xcconfig | 13 + ...yWeb3Wallet-myWeb3WalletUITests-Info.plist | 26 + ...eb3WalletUITests-acknowledgements.markdown | 475 + ...myWeb3WalletUITests-acknowledgements.plist | 537 + ...s-myWeb3Wallet-myWeb3WalletUITests-dummy.m | 5 + ...ts-frameworks-Debug-input-files.xcfilelist | 7 + ...s-frameworks-Debug-output-files.xcfilelist | 6 + ...-frameworks-Release-input-files.xcfilelist | 7 + ...frameworks-Release-output-files.xcfilelist | 6 + ...b3Wallet-myWeb3WalletUITests-frameworks.sh | 196 + ...yWeb3Wallet-myWeb3WalletUITests-umbrella.h | 16 + ...3Wallet-myWeb3WalletUITests.debug.xcconfig | 15 + ...myWeb3Wallet-myWeb3WalletUITests.modulemap | 6 + ...allet-myWeb3WalletUITests.release.xcconfig | 15 + .../Pods-myWeb3Wallet-Info.plist | 26 + ...ods-myWeb3Wallet-acknowledgements.markdown | 475 + .../Pods-myWeb3Wallet-acknowledgements.plist | 537 + .../Pods-myWeb3Wallet-dummy.m | 5 + ...et-frameworks-Debug-input-files.xcfilelist | 7 + ...t-frameworks-Debug-output-files.xcfilelist | 6 + ...-frameworks-Release-input-files.xcfilelist | 7 + ...frameworks-Release-output-files.xcfilelist | 6 + .../Pods-myWeb3Wallet-frameworks.sh | 196 + .../Pods-myWeb3Wallet-umbrella.h | 16 + .../Pods-myWeb3Wallet.debug.xcconfig | 15 + .../Pods-myWeb3Wallet.modulemap | 6 + .../Pods-myWeb3Wallet.release.xcconfig | 15 + .../Pods-myWeb3WalletTests-Info.plist | 26 + ...yWeb3WalletTests-acknowledgements.markdown | 3 + ...s-myWeb3WalletTests-acknowledgements.plist | 29 + .../Pods-myWeb3WalletTests-dummy.m | 5 + .../Pods-myWeb3WalletTests-umbrella.h | 16 + .../Pods-myWeb3WalletTests.debug.xcconfig | 11 + .../Pods-myWeb3WalletTests.modulemap | 6 + .../Pods-myWeb3WalletTests.release.xcconfig | 11 + .../PromiseKit/PromiseKit-Info.plist | 26 + .../PromiseKit/PromiseKit-dummy.m | 5 + .../PromiseKit/PromiseKit-prefix.pch | 12 + .../PromiseKit/PromiseKit-umbrella.h | 26 + .../PromiseKit/PromiseKit.debug.xcconfig | 14 + .../PromiseKit/PromiseKit.modulemap | 6 + .../PromiseKit/PromiseKit.release.xcconfig | 14 + .../Starscream/Starscream-Info.plist | 26 + .../Starscream/Starscream-dummy.m | 5 + .../Starscream/Starscream-prefix.pch | 12 + .../Starscream/Starscream-umbrella.h | 16 + .../Starscream/Starscream.debug.xcconfig | 13 + .../Starscream/Starscream.modulemap | 6 + .../Starscream/Starscream.release.xcconfig | 13 + .../secp256k1.c/secp256k1.c-Info.plist | 26 + .../secp256k1.c/secp256k1.c-dummy.m | 5 + .../secp256k1.c/secp256k1.c-prefix.pch | 12 + .../secp256k1.c/secp256k1.c-umbrella.h | 17 + .../secp256k1.c/secp256k1.c.debug.xcconfig | 13 + .../secp256k1.c/secp256k1.c.modulemap | 6 + .../secp256k1.c/secp256k1.c.release.xcconfig | 13 + ...esourceBundle-Browser-web3swift-Info.plist | 24 + .../web3swift/web3swift-Info.plist | 26 + .../web3swift/web3swift-dummy.m | 5 + .../web3swift/web3swift-prefix.pch | 12 + .../web3swift/web3swift-umbrella.h | 16 + .../web3swift/web3swift.debug.xcconfig | 15 + .../web3swift/web3swift.modulemap | 6 + .../web3swift/web3swift.release.xcconfig | 15 + .../myWeb3Wallet/Pods/secp256k1.c/License.md | 19 + .../Pods/secp256k1.c/secp256k1/basic-config.h | 33 + .../Pods/secp256k1.c/secp256k1/ecdh_impl.h | 54 + .../Pods/secp256k1.c/secp256k1/ecdsa.h | 21 + .../Pods/secp256k1.c/secp256k1/ecdsa_impl.h | 313 + .../Pods/secp256k1.c/secp256k1/eckey.h | 25 + .../Pods/secp256k1.c/secp256k1/eckey_impl.h | 100 + .../Pods/secp256k1.c/secp256k1/ecmult.h | 47 + .../Pods/secp256k1.c/secp256k1/ecmult_const.h | 17 + .../secp256k1.c/secp256k1/ecmult_const_impl.h | 257 + .../Pods/secp256k1.c/secp256k1/ecmult_gen.h | 43 + .../secp256k1.c/secp256k1/ecmult_gen_impl.h | 210 + .../Pods/secp256k1.c/secp256k1/ecmult_impl.h | 1027 + .../Pods/secp256k1.c/secp256k1/field.h | 130 + .../Pods/secp256k1.c/secp256k1/field_10x26.h | 48 + .../secp256k1.c/secp256k1/field_10x26_impl.h | 1161 + .../Pods/secp256k1.c/secp256k1/field_5x52.h | 47 + .../secp256k1/field_5x52_asm_impl.h | 502 + .../secp256k1.c/secp256k1/field_5x52_impl.h | 494 + .../secp256k1/field_5x52_int128_impl.h | 277 + .../Pods/secp256k1.c/secp256k1/field_impl.h | 313 + .../Pods/secp256k1.c/secp256k1/group.h | 147 + .../Pods/secp256k1.c/secp256k1/group_impl.h | 706 + .../Pods/secp256k1.c/secp256k1/hash.h | 41 + .../Pods/secp256k1.c/secp256k1/hash_impl.h | 282 + .../secp256k1.c/secp256k1/include/secp256k1.h | 767 + .../Pods/secp256k1.c/secp256k1/num.h | 72 + .../Pods/secp256k1.c/secp256k1/num_gmp.h | 20 + .../Pods/secp256k1.c/secp256k1/num_gmp_impl.h | 288 + .../Pods/secp256k1.c/secp256k1/num_impl.h | 22 + .../secp256k1.c/secp256k1/recovery_impl.h | 193 + .../Pods/secp256k1.c/secp256k1/scalar.h | 104 + .../Pods/secp256k1.c/secp256k1/scalar_4x64.h | 19 + .../secp256k1.c/secp256k1/scalar_4x64_impl.h | 949 + .../Pods/secp256k1.c/secp256k1/scalar_8x32.h | 19 + .../secp256k1.c/secp256k1/scalar_8x32_impl.h | 721 + .../Pods/secp256k1.c/secp256k1/scalar_impl.h | 331 + .../Pods/secp256k1.c/secp256k1/scalar_low.h | 15 + .../secp256k1.c/secp256k1/scalar_low_impl.h | 114 + .../Pods/secp256k1.c/secp256k1/scratch.h | 39 + .../Pods/secp256k1.c/secp256k1/scratch_impl.h | 86 + .../secp256k1.c/secp256k1/secp256k1-config.h | 169 + .../Pods/secp256k1.c/secp256k1/secp256k1.c | 597 + .../secp256k1_ec_mult_static_context.h | 1160 + .../secp256k1.c/secp256k1/secp256k1_main.h | 5 + .../Pods/secp256k1.c/secp256k1/util.h | 119 + .../myWeb3Wallet/Pods/web3swift/LICENSE.md | 203 + Example/myWeb3Wallet/Pods/web3swift/README.md | 426 + .../Sources/web3swift/Browser/Bridge.swift | 250 + .../Browser/BrowserViewController.swift | 128 + .../Sources/web3swift/Browser/browser.js | 68351 ++++++++++++++++ .../Sources/web3swift/Browser/browser.min.js | 2 + .../web3swift/Browser/wk.bridge.min.js | 5 + .../Contract/ComparisonExtensions.swift | 95 + .../web3swift/Contract/ContractProtocol.swift | 109 + .../web3swift/Contract/EthereumContract.swift | 297 + .../EthereumFilterEncodingExtensions.swift | 44 + .../web3swift/Contract/EventFiltering.swift | 170 + .../Convenience/Array+Extension.swift | 16 + .../web3swift/Convenience/Base58.swift | 170 + .../Convenience/BigUInt+Extensions.swift | 16 + .../Convenience/CryptoExtensions.swift | 20 + .../Convenience/Data+Extension.swift | 142 + .../Convenience/Decodable+Extensions.swift | 146 + .../Convenience/Dictionary+Extension.swift | 18 + .../Convenience/Encodable+Extensions.swift | 130 + .../NSRegularExpressionExtension.swift | 83 + .../NativeTypesEncoding+Extensions.swift | 91 + .../Convenience/RIPEMD160+StackOveflow.swift | 534 + .../web3swift/Convenience/SECP256k1.swift | 385 + .../Convenience/String+Extension.swift | 137 + .../Sources/web3swift/EthereumABI/ABI.swift | 28 + .../web3swift/EthereumABI/ABIDecoding.swift | 286 + .../web3swift/EthereumABI/ABIElements.swift | 286 + .../web3swift/EthereumABI/ABIEncoding.swift | 388 + .../EthereumABI/ABIParameterTypes.swift | 250 + .../web3swift/EthereumABI/ABIParsing.swift | 186 + .../web3swift/EthereumABI/ABITypeParser.swift | 110 + .../EthereumAddress/EthereumAddress.swift | 136 + .../EthereumAddress/Extensions.swift | 60 + .../Web3+BrowserFunctions.swift | 209 + .../HookedFunctions/Web3+Wallet.swift | 73 + .../KeystoreManager/AbstractKeystore.swift | 24 + .../KeystoreManager/BIP32HDNode.swift | 302 + .../KeystoreManager/BIP32Keystore.swift | 401 + .../KeystoreManager/BIP39+WordLists.swift | 35 + .../web3swift/KeystoreManager/BIP39.swift | 165 + .../KeystoreManager/EthereumKeystoreV3.swift | 261 + .../web3swift/KeystoreManager/IBAN.swift | 138 + .../KeystoreManager/KeystoreManager.swift | 202 + .../KeystoreManager/KeystoreParams.swift | 79 + .../KeystoreManager/PlainKeystore.swift | 37 + .../web3swift/Promises/Promise+Batching.swift | 139 + .../Promises/Promise+HttpProvider.swift | 109 + ...omise+Web3+Contract+GetIndexedEvents.swift | 11 + .../Promises/Promise+Web3+Eth+Call.swift | 36 + .../Promise+Web3+Eth+EstimateGas.swift | 53 + .../Promise+Web3+Eth+GetAccounts.swift | 39 + .../Promise+Web3+Eth+GetBalance.swift | 31 + .../Promise+Web3+Eth+GetBlockByHash.swift | 31 + .../Promise+Web3+Eth+GetBlockByNumber.swift | 36 + .../Promise+Web3+Eth+GetBlockNumber.swift | 26 + .../Promise+Web3+Eth+GetGasPrice.swift | 26 + ...Promise+Web3+Eth+GetTransactionCount.swift | 32 + ...omise+Web3+Eth+GetTransactionDetails.swift | 31 + ...omise+Web3+Eth+GetTransactionReceipt.swift | 31 + .../Promise+Web3+Eth+SendRawTransaction.swift | 51 + .../Promise+Web3+Eth+SendTransaction.swift | 79 + .../Promise+Web3+Personal+CreateAccount.swift | 37 + .../Promises/Promise+Web3+Personal+Sign.swift | 44 + .../Promise+Web3+Personal+UnlockAccount.swift | 43 + .../Promises/Promise+Web3+TxPool.swift | 56 + .../Sources/web3swift/SwiftRLP/RLP.swift | 320 + .../Tokens/ERC1155/Web3+ERC1155.swift | 147 + .../Tokens/ERC1376/Web3+ERC1376.swift | 502 + .../Tokens/ERC1400/Web3+ERC1400.swift | 931 + .../Tokens/ERC1410/Web3+ERC1410.swift | 664 + .../Tokens/ERC1594/Web3+ERC1594.swift | 409 + .../Tokens/ERC1633/Web3+ERC1633.swift | 254 + .../Tokens/ERC1643/Web3+ERC1643.swift | 267 + .../Tokens/ERC1644/Web3+ERC1644.swift | 283 + .../web3swift/Tokens/ERC165/Web3+ERC165.swift | 16 + .../web3swift/Tokens/ERC20/Web3+ERC20.swift | 228 + .../web3swift/Tokens/ERC721/Web3+ERC721.swift | 280 + .../Tokens/ERC721x/Web3+ERC721x.swift | 332 + .../web3swift/Tokens/ERC777/Web3+ERC777.swift | 445 + .../web3swift/Tokens/ERC820/Web3+ERC820.swift | 20 + .../web3swift/Tokens/ERC888/Web3+ERC888.swift | 138 + .../web3swift/Tokens/ST20/Web3+ST20.swift | 314 + .../Tokens/ST20/Web3+SecurityToken.swift | 473 + .../web3swift/Transaction/BloomFilter.swift | 110 + .../Transaction/EthereumTransaction.swift | 403 + .../Transaction/TransactionSigner.swift | 118 + .../web3swift/Utils/EIP/EIP67Code.swift | 138 + .../Sources/web3swift/Utils/EIP/EIP681.swift | 232 + .../Sources/web3swift/Utils/ENS/ENS.swift | 286 + .../Utils/ENS/ENSBaseRegistrar.swift | 82 + .../web3swift/Utils/ENS/ENSRegistry.swift | 110 + .../web3swift/Utils/ENS/ENSResolver.swift | 196 + .../Utils/ENS/ENSReverseRegistrar.swift | 68 + .../Utils/ENS/ETHRegistrarController.swift | 93 + .../web3swift/Utils/ENS/NameHash.swift | 52 + .../web3swift/Utils/ENS/PublicKey.swift | 26 + .../Utils/Hooks/NonceMiddleware.swift | 111 + .../web3swift/Web3/Web3+Constants.swift | 15 + .../web3swift/Web3/Web3+Contract.swift | 116 + .../web3swift/Web3/Web3+Eth+Websocket.swift | 42 + .../Sources/web3swift/Web3/Web3+Eth.swift | 358 + .../web3swift/Web3/Web3+EventParser.swift | 307 + .../web3swift/Web3/Web3+Eventloop.swift | 103 + .../web3swift/Web3/Web3+HttpProvider.swift | 57 + .../web3swift/Web3/Web3+InfuraProviders.swift | 275 + .../web3swift/Web3/Web3+Instance.swift | 229 + .../Sources/web3swift/Web3/Web3+JSONRPC.swift | 278 + .../Sources/web3swift/Web3/Web3+Methods.swift | 90 + .../Web3/Web3+MutatingTransaction.swift | 194 + .../Sources/web3swift/Web3/Web3+Options.swift | 246 + .../web3swift/Web3/Web3+Personal.swift | 86 + .../web3swift/Web3/Web3+Protocols.swift | 90 + .../Web3/Web3+ReadingTransaction.swift | 109 + .../web3swift/Web3/Web3+Structures.swift | 691 + .../Sources/web3swift/Web3/Web3+TxPool.swift | 25 + .../Sources/web3swift/Web3/Web3+Utils.swift | 6212 ++ .../Web3/Web3+WebsocketProvider.swift | 307 + .../Sources/web3swift/Web3/Web3.swift | 85 + .../myWeb3Wallet.xcodeproj/project.pbxproj | 815 + .../contents.xcworkspacedata | 7 + .../xcshareddata/IDEWorkspaceChecks.plist | 8 + .../contents.xcworkspacedata | 10 + .../xcshareddata/IDEWorkspaceChecks.plist | 8 + .../Appdelegate/AppDelegate.swift | 36 + .../Appdelegate/SceneDelegate.swift | 52 + .../AccentColor.colorset/Contents.json | 11 + .../AppIcon.appiconset/Contents.json | 98 + .../Assets.xcassets/Contents.json | 6 + .../Base.lproj/LaunchScreen.storyboard | 25 + .../myWeb3Wallet/Base.lproj/Main.storyboard | 141 + Example/myWeb3Wallet/myWeb3Wallet/Info.plist | 25 + .../myWeb3Wallet/SplashViewController.swift | 28 + .../myWeb3Wallet/ViewController.swift | 19 + .../WalletViewController.swift | 128 + .../myWeb3WalletTests/myWeb3WalletTests.swift | 33 + .../myWeb3WalletUITests.swift | 42 + .../myWeb3WalletUITestsLaunchTests.swift | 32 + 442 files changed, 136065 insertions(+) create mode 100644 Example/myWeb3Wallet/Podfile create mode 100644 Example/myWeb3Wallet/Podfile.lock create mode 100644 Example/myWeb3Wallet/Pods/BigInt/LICENSE.md create mode 100644 Example/myWeb3Wallet/Pods/BigInt/README.md create mode 100644 Example/myWeb3Wallet/Pods/BigInt/Sources/Addition.swift create mode 100644 Example/myWeb3Wallet/Pods/BigInt/Sources/BigInt.swift create mode 100644 Example/myWeb3Wallet/Pods/BigInt/Sources/BigUInt.swift create mode 100644 Example/myWeb3Wallet/Pods/BigInt/Sources/Bitwise Ops.swift create mode 100644 Example/myWeb3Wallet/Pods/BigInt/Sources/Codable.swift create mode 100644 Example/myWeb3Wallet/Pods/BigInt/Sources/Comparable.swift create mode 100644 Example/myWeb3Wallet/Pods/BigInt/Sources/Data Conversion.swift create mode 100644 Example/myWeb3Wallet/Pods/BigInt/Sources/Division.swift create mode 100644 Example/myWeb3Wallet/Pods/BigInt/Sources/Exponentiation.swift create mode 100644 Example/myWeb3Wallet/Pods/BigInt/Sources/Floating Point Conversion.swift create mode 100644 Example/myWeb3Wallet/Pods/BigInt/Sources/GCD.swift create mode 100644 Example/myWeb3Wallet/Pods/BigInt/Sources/Hashable.swift create mode 100644 Example/myWeb3Wallet/Pods/BigInt/Sources/Integer Conversion.swift create mode 100644 Example/myWeb3Wallet/Pods/BigInt/Sources/Multiplication.swift create mode 100644 Example/myWeb3Wallet/Pods/BigInt/Sources/Prime Test.swift create mode 100644 Example/myWeb3Wallet/Pods/BigInt/Sources/Random.swift create mode 100644 Example/myWeb3Wallet/Pods/BigInt/Sources/Shifts.swift create mode 100644 Example/myWeb3Wallet/Pods/BigInt/Sources/Square Root.swift create mode 100644 Example/myWeb3Wallet/Pods/BigInt/Sources/Strideable.swift create mode 100644 Example/myWeb3Wallet/Pods/BigInt/Sources/String Conversion.swift create mode 100644 Example/myWeb3Wallet/Pods/BigInt/Sources/Subtraction.swift create mode 100644 Example/myWeb3Wallet/Pods/BigInt/Sources/Words and Bits.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/LICENSE create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/README.md create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEAD.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEADChaCha20Poly1305.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/AES.Cryptors.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/AES.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Array+Extension.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Authenticator.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BatchedCollection.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Bit.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockCipher.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockDecryptor.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockEncryptor.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/BlockMode.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/BlockModeOptions.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CBC.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CCM.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CFB.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CTR.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CipherModeWorker.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/ECB.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/GCM.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/OCB.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/OFB.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/PCBC.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Blowfish.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/CBCMAC.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/CMAC.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/ChaCha20.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Checksum.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Cipher.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Collection+Extension.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/CompactMap.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Cryptor.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Cryptors.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Digest.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/DigestType.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/AES+Foundation.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Array+Foundation.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Blowfish+Foundation.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/ChaCha20+Foundation.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Data+Extension.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/HMAC+Foundation.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Rabbit+Foundation.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/String+FoundationExtension.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Utils+Foundation.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Generics.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/HKDF.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/HMAC.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/ISO10126Padding.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/ISO78164Padding.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Int+Extension.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/MD5.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/NoPadding.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Operators.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PBKDF1.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PBKDF2.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS5.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS7.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS7Padding.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Padding.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Poly1305.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Rabbit.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/SHA1.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/SHA2.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/SHA3.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Scrypt.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/SecureBytes.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/StreamDecryptor.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/StreamEncryptor.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/String+Extension.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/UInt128.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/UInt16+Extension.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/UInt32+Extension.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/UInt64+Extension.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/UInt8+Extension.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Updatable.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Utils.swift create mode 100644 Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/ZeroPadding.swift create mode 100644 Example/myWeb3Wallet/Pods/Local Podspecs/web3swift.podspec.json create mode 100644 Example/myWeb3Wallet/Pods/Manifest.lock create mode 100644 Example/myWeb3Wallet/Pods/Pods.xcodeproj/project.pbxproj create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.h create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.m create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+Promise.swift create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSObject+Promise.swift create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.h create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.m create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.h create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.m create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+Promise.swift create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/PMKFoundation.h create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/Process+Promise.swift create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/afterlife.swift create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/PMKUIKit.h create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.h create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.m create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+Promise.swift create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.h create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.m create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewPropertyAnimator+Promise.swift create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/LICENSE create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/README.md create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/AnyPromise+Private.h create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/AnyPromise.h create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/AnyPromise.m create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/AnyPromise.swift create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/Box.swift create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/Catchable.swift create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/Configuration.swift create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/CustomStringConvertible.swift create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/Deprecations.swift create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/Error.swift create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/Guarantee.swift create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/LogEvent.swift create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/NSMethodSignatureForBlock.m create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/PMKCallVariadicBlock.m create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/Promise.swift create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/PromiseKit.h create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/Resolver.swift create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/Thenable.swift create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/after.m create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/after.swift create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/dispatch_promise.m create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/firstly.swift create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/fwd.h create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/hang.m create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/hang.swift create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/join.m create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/race.m create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/race.swift create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/when.m create mode 100644 Example/myWeb3Wallet/Pods/PromiseKit/Sources/when.swift create mode 100644 Example/myWeb3Wallet/Pods/Starscream/LICENSE create mode 100644 Example/myWeb3Wallet/Pods/Starscream/README.md create mode 100644 Example/myWeb3Wallet/Pods/Starscream/Sources/Compression/Compression.swift create mode 100644 Example/myWeb3Wallet/Pods/Starscream/Sources/Compression/WSCompression.swift create mode 100644 Example/myWeb3Wallet/Pods/Starscream/Sources/DataBytes/Data+Extensions.swift create mode 100644 Example/myWeb3Wallet/Pods/Starscream/Sources/Engine/Engine.swift create mode 100644 Example/myWeb3Wallet/Pods/Starscream/Sources/Engine/NativeEngine.swift create mode 100644 Example/myWeb3Wallet/Pods/Starscream/Sources/Engine/WSEngine.swift create mode 100644 Example/myWeb3Wallet/Pods/Starscream/Sources/Framer/FoundationHTTPHandler.swift create mode 100644 Example/myWeb3Wallet/Pods/Starscream/Sources/Framer/FoundationHTTPServerHandler.swift create mode 100644 Example/myWeb3Wallet/Pods/Starscream/Sources/Framer/FrameCollector.swift create mode 100644 Example/myWeb3Wallet/Pods/Starscream/Sources/Framer/Framer.swift create mode 100644 Example/myWeb3Wallet/Pods/Starscream/Sources/Framer/HTTPHandler.swift create mode 100644 Example/myWeb3Wallet/Pods/Starscream/Sources/Framer/StringHTTPHandler.swift create mode 100644 Example/myWeb3Wallet/Pods/Starscream/Sources/Security/FoundationSecurity.swift create mode 100644 Example/myWeb3Wallet/Pods/Starscream/Sources/Security/Security.swift create mode 100644 Example/myWeb3Wallet/Pods/Starscream/Sources/Server/Server.swift create mode 100644 Example/myWeb3Wallet/Pods/Starscream/Sources/Server/WebSocketServer.swift create mode 100644 Example/myWeb3Wallet/Pods/Starscream/Sources/Starscream/WebSocket.swift create mode 100644 Example/myWeb3Wallet/Pods/Starscream/Sources/Transport/FoundationTransport.swift create mode 100644 Example/myWeb3Wallet/Pods/Starscream/Sources/Transport/TCPTransport.swift create mode 100644 Example/myWeb3Wallet/Pods/Starscream/Sources/Transport/Transport.swift create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt-Info.plist create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt-dummy.m create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt-prefix.pch create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt-umbrella.h create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt.debug.xcconfig create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt.modulemap create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt.release.xcconfig create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift-Info.plist create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift-dummy.m create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift-prefix.pch create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift-umbrella.h create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift.debug.xcconfig create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift.modulemap create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift.release.xcconfig create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-Info.plist create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-acknowledgements.markdown create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-acknowledgements.plist create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-dummy.m create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks-Debug-input-files.xcfilelist create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks-Debug-output-files.xcfilelist create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks-Release-input-files.xcfilelist create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks-Release-output-files.xcfilelist create mode 100755 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks.sh create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-umbrella.h create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests.debug.xcconfig create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests.modulemap create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests.release.xcconfig create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-Info.plist create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-acknowledgements.markdown create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-acknowledgements.plist create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-dummy.m create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks-Debug-input-files.xcfilelist create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks-Debug-output-files.xcfilelist create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks-Release-input-files.xcfilelist create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks-Release-output-files.xcfilelist create mode 100755 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks.sh create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-umbrella.h create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet.debug.xcconfig create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet.modulemap create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet.release.xcconfig create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests-Info.plist create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests-acknowledgements.markdown create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests-acknowledgements.plist create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests-dummy.m create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests-umbrella.h create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests.debug.xcconfig create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests.modulemap create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests.release.xcconfig create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit-Info.plist create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit-dummy.m create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit-prefix.pch create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit-umbrella.h create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit.debug.xcconfig create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit.modulemap create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit.release.xcconfig create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream-Info.plist create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream-dummy.m create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream-prefix.pch create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream-umbrella.h create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream.debug.xcconfig create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream.modulemap create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream.release.xcconfig create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c-Info.plist create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c-dummy.m create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c-prefix.pch create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c-umbrella.h create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c.debug.xcconfig create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c.modulemap create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c.release.xcconfig create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/web3swift/ResourceBundle-Browser-web3swift-Info.plist create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift-Info.plist create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift-dummy.m create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift-prefix.pch create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift-umbrella.h create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift.debug.xcconfig create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift.modulemap create mode 100644 Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift.release.xcconfig create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/License.md create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/basic-config.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecdh_impl.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecdsa.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecdsa_impl.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/eckey.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/eckey_impl.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult_const.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult_const_impl.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult_gen.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult_gen_impl.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult_impl.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_10x26.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_10x26_impl.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_5x52.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_5x52_asm_impl.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_5x52_impl.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_5x52_int128_impl.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_impl.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/group.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/group_impl.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/hash.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/hash_impl.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/include/secp256k1.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/num.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/num_gmp.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/num_gmp_impl.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/num_impl.h create mode 100755 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/recovery_impl.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_4x64.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_4x64_impl.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_8x32.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_8x32_impl.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_impl.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_low.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_low_impl.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scratch.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scratch_impl.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/secp256k1-config.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/secp256k1.c create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/secp256k1_ec_mult_static_context.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/secp256k1_main.h create mode 100644 Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/util.h create mode 100755 Example/myWeb3Wallet/Pods/web3swift/LICENSE.md create mode 100755 Example/myWeb3Wallet/Pods/web3swift/README.md create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Browser/Bridge.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Browser/BrowserViewController.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Browser/browser.js create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Browser/browser.min.js create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Browser/wk.bridge.min.js create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Contract/ComparisonExtensions.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Contract/ContractProtocol.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Contract/EthereumContract.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Contract/EthereumFilterEncodingExtensions.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Contract/EventFiltering.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Array+Extension.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Base58.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/BigUInt+Extensions.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/CryptoExtensions.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Data+Extension.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Decodable+Extensions.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Dictionary+Extension.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Encodable+Extensions.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/NSRegularExpressionExtension.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/NativeTypesEncoding+Extensions.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/RIPEMD160+StackOveflow.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/SECP256k1.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/String+Extension.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABI.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABIDecoding.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABIElements.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABIEncoding.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABIParameterTypes.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABIParsing.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABITypeParser.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumAddress/EthereumAddress.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumAddress/Extensions.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/HookedFunctions/Web3+BrowserFunctions.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/HookedFunctions/Web3+Wallet.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/AbstractKeystore.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32HDNode.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32Keystore.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP39+WordLists.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP39.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/EthereumKeystoreV3.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/IBAN.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/KeystoreManager.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/KeystoreParams.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/PlainKeystore.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Batching.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+HttpProvider.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Contract+GetIndexedEvents.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+Call.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+EstimateGas.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetAccounts.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBalance.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByHash.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByNumber.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockNumber.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetGasPrice.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionCount.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionDetails.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionReceipt.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+SendRawTransaction.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+SendTransaction.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+CreateAccount.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+Sign.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+UnlockAccount.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+TxPool.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/SwiftRLP/RLP.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1155/Web3+ERC1155.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1376/Web3+ERC1376.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1400/Web3+ERC1400.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1410/Web3+ERC1410.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1594/Web3+ERC1594.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1633/Web3+ERC1633.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1643/Web3+ERC1643.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1644/Web3+ERC1644.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC165/Web3+ERC165.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC20/Web3+ERC20.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC721/Web3+ERC721.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC721x/Web3+ERC721x.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC777/Web3+ERC777.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC820/Web3+ERC820.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC888/Web3+ERC888.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ST20/Web3+ST20.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ST20/Web3+SecurityToken.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Transaction/BloomFilter.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Transaction/EthereumTransaction.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Transaction/TransactionSigner.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/EIP/EIP67Code.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/EIP/EIP681.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ENS.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSBaseRegistrar.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSRegistry.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSResolver.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSReverseRegistrar.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ETHRegistrarController.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/NameHash.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/PublicKey.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/Hooks/NonceMiddleware.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Constants.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Contract.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Eth+Websocket.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Eth.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+EventParser.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Eventloop.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+HttpProvider.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+InfuraProviders.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Instance.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+JSONRPC.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Methods.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+MutatingTransaction.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Options.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Personal.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Protocols.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+ReadingTransaction.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Structures.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+TxPool.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Utils.swift create mode 100644 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+WebsocketProvider.swift create mode 100755 Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3.swift create mode 100644 Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.pbxproj create mode 100644 Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.xcworkspace/contents.xcworkspacedata create mode 100644 Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist create mode 100644 Example/myWeb3Wallet/myWeb3Wallet.xcworkspace/contents.xcworkspacedata create mode 100644 Example/myWeb3Wallet/myWeb3Wallet.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist create mode 100644 Example/myWeb3Wallet/myWeb3Wallet/Appdelegate/AppDelegate.swift create mode 100644 Example/myWeb3Wallet/myWeb3Wallet/Appdelegate/SceneDelegate.swift create mode 100644 Example/myWeb3Wallet/myWeb3Wallet/Assets.xcassets/AccentColor.colorset/Contents.json create mode 100644 Example/myWeb3Wallet/myWeb3Wallet/Assets.xcassets/AppIcon.appiconset/Contents.json create mode 100644 Example/myWeb3Wallet/myWeb3Wallet/Assets.xcassets/Contents.json create mode 100644 Example/myWeb3Wallet/myWeb3Wallet/Base.lproj/LaunchScreen.storyboard create mode 100644 Example/myWeb3Wallet/myWeb3Wallet/Base.lproj/Main.storyboard create mode 100644 Example/myWeb3Wallet/myWeb3Wallet/Info.plist create mode 100644 Example/myWeb3Wallet/myWeb3Wallet/SplashViewController.swift create mode 100644 Example/myWeb3Wallet/myWeb3Wallet/ViewController.swift create mode 100644 Example/myWeb3Wallet/myWeb3Wallet/ViewController/WalletController/WalletViewController.swift create mode 100644 Example/myWeb3Wallet/myWeb3WalletTests/myWeb3WalletTests.swift create mode 100644 Example/myWeb3Wallet/myWeb3WalletUITests/myWeb3WalletUITests.swift create mode 100644 Example/myWeb3Wallet/myWeb3WalletUITests/myWeb3WalletUITestsLaunchTests.swift diff --git a/Example/myWeb3Wallet/Podfile b/Example/myWeb3Wallet/Podfile new file mode 100644 index 000000000..744899237 --- /dev/null +++ b/Example/myWeb3Wallet/Podfile @@ -0,0 +1,21 @@ +# Uncomment the next line to define a global platform for your project +# platform :ios, '9.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 diff --git a/Example/myWeb3Wallet/Podfile.lock b/Example/myWeb3Wallet/Podfile.lock new file mode 100644 index 000000000..5fd352276 --- /dev/null +++ b/Example/myWeb3Wallet/Podfile.lock @@ -0,0 +1,53 @@ +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/Pods/BigInt/LICENSE.md b/Example/myWeb3Wallet/Pods/BigInt/LICENSE.md new file mode 100644 index 000000000..18cefd118 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/LICENSE.md @@ -0,0 +1,20 @@ + +Copyright (c) 2016-2017 Károly Lőrentey + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Example/myWeb3Wallet/Pods/BigInt/README.md b/Example/myWeb3Wallet/Pods/BigInt/README.md new file mode 100644 index 000000000..2256249cd --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/README.md @@ -0,0 +1,430 @@ +[![BigInt](https://github.com/attaswift/BigInt/raw/master/images/banner.png)](https://github.com/attaswift/BigInt) + +* [Overview](#overview) +* [API Documentation](#api) +* [License](#license) +* [Requirements and Integration](#integration) +* [Implementation Notes](#notes) + * [Full-width multiplication and division primitives](#fullwidth) + * [Why is there no generic `BigInt` type?](#generics) +* [Calculation Samples](#samples) + * [Obligatory factorial demo](#factorial) + * [RSA Cryptography](#rsa) + * [Calculating the Digits of π](#pi) + +[![Swift 3](https://img.shields.io/badge/Swift-5-blue.svg)](https://developer.apple.com/swift/) +[![License](https://img.shields.io/badge/licence-MIT-blue.svg)](http://cocoapods.org/pods/BigInt) +[![Platform](https://img.shields.io/cocoapods/p/BigInt.svg)](http://cocoapods.org/pods/BigInt) + +[![Build Status](https://travis-ci.org/attaswift/BigInt.svg?branch=master)](https://travis-ci.org/attaswift/BigInt) +[![Code Coverage](https://codecov.io/github/attaswift/BigInt/coverage.svg?branch=master)](https://codecov.io/github/attaswift/BigInt?branch=master) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg)](https://github.com/Carthage/Carthage) +[![Version](https://img.shields.io/cocoapods/v/BigInt.svg)](http://cocoapods.org/pods/BigInt) + +## Overview + +This repository provides [integer types of arbitrary width][wiki] implemented +in 100% pure Swift. The underlying representation is in base 2^64, using `Array`. + +[wiki]: https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic + +This module is handy when you need an integer type that's wider than `UIntMax`, but +you don't want to add [The GNU Multiple Precision Arithmetic Library][GMP] +as a dependency. + +[GMP]: https://gmplib.org + +Two big integer types are included: [`BigUInt`][BigUInt] and [`BigInt`][BigInt], +the latter being the signed variant. +Both of these are Swift structs with copy-on-write value semantics, and they can be used much +like any other integer type. + +The library provides implementations for some of the most frequently useful functions on +big integers, including + +- All functionality from [`Comparable`][comparison] and [`Hashable`][hashing] + +- [The full set of arithmetic operators][addition]: `+`, `-`, `*`, `/`, `%`, `+=`, `-=`, `*=`, `/=`, `%=` + - [Addition][addition] and [subtraction][subtraction] have variants that allow for + shifting the digits of the second operand on the fly. + - Unsigned subtraction will trap when the result would be negative. + ([There are variants][subtraction] that return an overflow flag.) + - [Multiplication][mul] uses brute force for numbers up to 1024 digits, then switches to Karatsuba's recursive method. + (This limit is configurable, see `BigUInt.directMultiplicationLimit`.) + - A [fused multiply-add][fused] method is also available, along with other [special-case variants][multiplication]. + - [Division][division] uses Knuth's Algorithm D, with its 3/2 digits wide quotient approximation. + It will trap when the divisor is zero. + - [`BigUInt.divide`][divide] returns the quotient and + remainder at once; this is faster than calculating them separately. + +- [Bitwise operators][bitwise]: `~`, `|`, `&`, `^`, `|=`, `&=`, `^=`, plus the following read-only properties: + - [`width`][width]: the minimum number of bits required to store the integer, + - [`trailingZeroBitCount`][trailingZeroBitCount]: the number of trailing zero bits in the binary representation, + - [`leadingZeroBitCount`][leadingZeroBitCount]: the number of leading zero bits (when the last digit isn't full), + +- [Shift operators][shift]: `>>`, `<<`, `>>=`, `<<=` + +- Methods to [convert `NSData` to big integers][data] and vice versa. + +- Support for [generating random integers][random] of specified maximum width or magnitude. + +- Radix conversion to/from [`String`s][radix1] and [big integers][radix2] up to base 36 (using repeated divisions). + - Big integers use this to implement `StringLiteralConvertible` (in base 10). + +- [`sqrt(n)`][sqrt]: The square root of an integer (using Newton's method). + +- [`BigUInt.gcd(n, m)`][GCD]: The greatest common divisor of two integers (Stein's algorithm). + +- [`base.power(exponent, modulus)`][powmod]: Modular exponentiation (right-to-left binary method). + [Vanilla exponentiation][power] is also available. +- [`n.inverse(modulus)`][inverse]: Multiplicative inverse in modulo arithmetic (extended Euclidean algorithm). +- [`n.isPrime()`][prime]: Miller–Rabin primality test. + +The implementations are intended to be reasonably efficient, but they are unlikely to be +competitive with GMP at all, even when I happened to implement an algorithm with same asymptotic +behavior as GMP. (I haven't performed a comparison benchmark, though.) + +The library has 100% unit test coverage. Sadly this does not imply that there are no bugs +in it. + +## API Documentation + +Generated API docs are available at http://attaswift.github.io/BigInt/. + +## License + +BigInt can be used, distributed and modified under [the MIT license][license]. + +## Requirements and Integration + +BigInt 4.0.0 requires Swift 4.2 (The last version with support for Swift 3.x was BigInt 2.1.0. +The last version with support for Swift 2 was BigInt 1.3.0.) + +| Swift Version | last BigInt Version| +| ------------- |:-------------------| +| 3.x | 2.1.0 | +| 4.0 | 3.1.0 | +| 4.2 | 4.0.0 | +| 5.0 | 5.0.0 | + +BigInt deploys to macOS 10.10, iOS 9, watchOS 2 and tvOS 9. +It has been tested on the latest OS releases only---however, as the module uses very few platform-provided APIs, +there should be very few issues with earlier versions. + +BigInt uses no APIs specific to Apple platforms, so +it should be easy to port it to other operating systems. + +Setup instructions: + +- **Swift Package Manager:** + Although the Package Manager is still in its infancy, BigInt provides experimental support for it. + Add this to the dependency section of your `Package.swift` manifest: + + ```Swift + .package(url: "https://github.com/attaswift/BigInt.git", from: "5.0.0") + ``` + +- **CocoaPods:** Put this in your `Podfile`: + + ```Ruby + pod 'BigInt', '~> 5.0' + ``` + +- **Carthage:** Put this in your `Cartfile`: + + ``` + github "attaswift/BigInt" ~> 5.0 + ``` + +## Implementation notes + +[`BigUInt`][BigUInt] is a `MutableCollectionType` of its 64-bit digits, with the least significant +digit at index 0. As a convenience, [`BigUInt`][BigUInt] allows you to subscript it with indexes at +or above its `count`. [The subscript operator][subscript] returns 0 for out-of-bound `get`s and +automatically extends the array on out-of-bound `set`s. This makes memory management simpler. + +[`BigInt`][BigInt] is just a tiny wrapper around a `BigUInt` [absolute value][abs] and a +[sign bit][negative], both of which are accessible as public read-write properties. + +### Why is there no generic `BigInt` type? + +The types provided by `BigInt` are not parametric—this is very much intentional, as +Swift generics cost us dearly at runtime in this use case. In every approach I tried, +making arbitrary-precision arithmetic operations work with a generic `Digit` type parameter +resulted in code that was literally *ten times slower*. If you can make the algorithms generic +without such a huge performance hit, [please enlighten me][twitter]! + +This is an area that I plan to investigate more, as it would be useful to have generic +implementations for arbitrary-width arithmetic operations. (Polynomial division and decimal bases +are two examples.) The library already implements double-digit multiplication and division as +extension methods on a protocol with an associated type requirement; this has not measurably affected +performance. Unfortunately, the same is not true for `BigUInt`'s methods. + +Of course, as a last resort, we could just duplicate the code to create a separate +generic variant that was slower but more flexible. + +[license]: https://github.com/attaswift/BigInt/blob/master/LICENSE.md +[twitter]: https://twitter.com/lorentey +[BigUInt]: http://attaswift.github.io/BigInt/Structs/BigUInt.html +[BigInt]: http://attaswift.github.io/BigInt/Structs/BigInt.html +[comparison]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/Comparison +[hashing]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/Hashing +[addition]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/Addition +[subtraction]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/Subtraction +[mul]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/s:ZFV6BigInt7BigUIntoi1mFTS0_S0__S0_ +[fused]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/s:FV6BigInt7BigUInt14multiplyAndAddFTS0_Vs6UInt6410atPositionSi_T_ +[multiplication]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/Multiplication +[division]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/Division +[divide]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/s:FV6BigInt7BigUInt7dividedFT2byS0__T8quotientS0_9remainderS0__ +[bitwise]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/Bitwise%20Operations +[width]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/s:vV6BigInt7BigUInt5widthSi +[leadingZeroBitCount]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/s:vV6BigInt7BigUInt13leadingZeroBitCountSi +[trailingZeroBitCount]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/s:vV6BigInt7BigUInt14trailingZeroBitCountSi +[shift]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/Shift%20Operators +[data]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/NSData%20Conversion +[random]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/Random%20Integers +[radix1]: http://attaswift.github.io/BigInt/Extensions/String.html#/s:FE6BigIntSScFTVS_7BigUInt5radixSi9uppercaseSb_SS +[radix2]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/s:FV6BigInt7BigUIntcFTSS5radixSi_GSqS0__ +[sqrt]: http://attaswift.github.io/BigInt/Functions.html#/s:F6BigInt4sqrtFVS_7BigUIntS0_ +[GCD]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/s:ZFV6BigInt7BigUInt3gcdFTS0_S0__S0_ +[powmod]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/s:FV6BigInt7BigUInt5powerFTS0_7modulusS0__S0_ +[power]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/s:FV6BigInt7BigUInt5powerFSiS0_ +[inverse]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/s:FV6BigInt7BigUInt7inverseFS0_GSqS0__ +[prime]: http://attaswift.github.io/BigInt/Structs/BigUInt.html#/Primality%20Testing +[abs]: http://attaswift.github.io/BigInt/Structs/BigInt.html#/s:vV6BigInt6BigInt3absVS_7BigUInt +[negative]: http://attaswift.github.io/BigInt/Structs/BigInt.html#/s:vV6BigInt6BigInt8negativeSb +[subscript]: https://github.com/attaswift/BigInt/blob/v2.0.0/Sources/BigUInt.swift#L216-L239 +[fullmuldiv]: https://github.com/attaswift/BigInt/blob/v2.0.0/Sources/BigDigit.swift#L96-L167 + + +## Calculation Samples + +### Obligatory Factorial Demo + +It is easy to use `BigInt` to calculate the factorial function for any integer: + +```Swift +import BigInt + +func factorial(_ n: Int) -> BigInt { + return (1 ... n).map { BigInt($0) }.reduce(BigInt(1), *) +} + +print(factorial(10)) +==> 362880 + +print(factorial(100)) +==> 93326215443944152681699238856266700490715968264381621468592963895217599993229915 + 6089414639761565182862536979208272237582511852109168640000000000000000000000 + +print(factorial(1000)) +==> 40238726007709377354370243392300398571937486421071463254379991042993851239862902 + 05920442084869694048004799886101971960586316668729948085589013238296699445909974 + 24504087073759918823627727188732519779505950995276120874975462497043601418278094 + 64649629105639388743788648733711918104582578364784997701247663288983595573543251 + 31853239584630755574091142624174743493475534286465766116677973966688202912073791 + 43853719588249808126867838374559731746136085379534524221586593201928090878297308 + 43139284440328123155861103697680135730421616874760967587134831202547858932076716 + 91324484262361314125087802080002616831510273418279777047846358681701643650241536 + 91398281264810213092761244896359928705114964975419909342221566832572080821333186 + 11681155361583654698404670897560290095053761647584772842188967964624494516076535 + 34081989013854424879849599533191017233555566021394503997362807501378376153071277 + 61926849034352625200015888535147331611702103968175921510907788019393178114194545 + 25722386554146106289218796022383897147608850627686296714667469756291123408243920 + 81601537808898939645182632436716167621791689097799119037540312746222899880051954 + 44414282012187361745992642956581746628302955570299024324153181617210465832036786 + 90611726015878352075151628422554026517048330422614397428693306169089796848259012 + 54583271682264580665267699586526822728070757813918581788896522081643483448259932 + 66043367660176999612831860788386150279465955131156552036093988180612138558600301 + 43569452722420634463179746059468257310379008402443243846565724501440282188525247 + 09351906209290231364932734975655139587205596542287497740114133469627154228458623 + 77387538230483865688976461927383814900140767310446640259899490222221765904339901 + 88601856652648506179970235619389701786004081188972991831102117122984590164192106 + 88843871218556461249607987229085192968193723886426148396573822911231250241866493 + 53143970137428531926649875337218940694281434118520158014123344828015051399694290 + 15348307764456909907315243327828826986460278986432113908350621709500259738986355 + 42771967428222487575867657523442202075736305694988250879689281627538488633969099 + 59826280956121450994871701244516461260379029309120889086942028510640182154399457 + 15680594187274899809425474217358240106367740459574178516082923013535808184009699 + 63725242305608559037006242712434169090041536901059339838357779394109700277534720 + 00000000000000000000000000000000000000000000000000000000000000000000000000000000 + 00000000000000000000000000000000000000000000000000000000000000000000000000000000 + 00000000000000000000000000000000000000000000000000000000000000000000000000000000 + 00000 +``` + +Well, I guess that's all right, but it's not very interesting. Let's try something more useful. + +### RSA Cryptography + +The `BigInt` module provides all necessary parts to implement an (overly) +simple [RSA cryptography system][RSA]. + +[RSA]: https://en.wikipedia.org/wiki/RSA_(cryptosystem) + +Let's start with a simple function that generates a random n-bit prime. The module +includes a function to generate random integers of a specific size, and also an +`isPrime` method that performs the Miller–Rabin primality test. These are all we need: + +```Swift +func generatePrime(_ width: Int) -> BigUInt { + while true { + var random = BigUInt.randomInteger(withExactWidth: width) + random |= BigUInt(1) + if random.isPrime() { + return random + } + } +} + +let p = generatePrime(1024) +==> 13308187650642192396256419911012544845370493728424936791561478318443071617242872 + 81980956747087187419914435169914161116601678883358611076800743580556055714173922 + 08406194264346635072293912609713085260354070700055888678514690878149253177960273 + 775659537560220378850112471985434373425534121373466492101182463962031 + +let q = generatePrime(1024) +==> 17072954422657145489547308812333368925007949054501204983863958355897172093173783 + 10108226596943999553784252564650624766276133157586733504784616138305701168410157 + 80784336308507083874651158029602582993233111593356512531869546706885170044355115 + 669728424124141763799008880327106952436883614887277350838425336156327 +``` + +Cool! Now that we have two large primes, we can produce an RSA public/private keypair +out of them. + +```Swift +typealias Key = (modulus: BigUInt, exponent: BigUInt) + +let n = p * q +==> 22721008120758282530010953362926306641542233757318103044313144976976529789946696 + 15454966720907712515917481418981591379647635391260569349099666410127279690367978 + 81184375533755888994370640857883754985364288413796100527262763202679037134021810 + 57933883525572232242690805678883227791774442041516929419640051653934584376704034 + 63953169772816907280591934423237977258358097846511079947337857778137177570668391 + 57455417707100275487770399281417352829897118140972240757708561027087217205975220 + 02207275447810167397968435583004676293892340103729490987263776871467057582629588 + 916498579594964478080508868267360515953225283461208420137 + +let e: BigUInt = 65537 +let phi = (p - 1) * (q - 1) +let d = e.inverse(phi)! // d * e % phi == 1 +==> 13964664343869014759736350480776837992604500903989703383202366291905558996277719 + 77822086142456362972689566985925179681282432115598451765899180050962461295573831 + 37069237934291884106584820998146965085531433195106686745474222222620986858696591 + 69836532468835154412554521152103642453158895363417640676611704542784576974374954 + 45789456921660619938185093118762690200980720312508614337759620606992462563490422 + 76669559556568917533268479190948959560397579572761529852891246283539604545691244 + 89999692877158676643042118662613875863504016129837099223040687512684532694527109 + 80742873307409704484365002175294665608486688146261327793 + +let publicKey: Key = (n, e) +let privateKey: Key = (n, d) +``` + +In RSA, modular exponentiation is used to encrypt (and decrypt) messages. + +```Swift +func encrypt(_ message: BigUInt, key: Key) -> BigUInt { + return message.power(key.exponent, modulus: key.modulus) +} +``` + +Let's try out our new keypair by converting a string into UTF-8, interpreting +the resulting binary representation as a big integer, and encrypting it with the +public key. `BigUInt` has an initializer that takes an `NSData`, so this is pretty +easy to do: + +```Swift +let secret: BigUInt = BigUInt("Arbitrary precision arithmetic is fun!".dataUsingEncoding(NSUTF8StringEncoding)!) +==> 83323446846105976078466731524728681905293067701804838925389198929123912971229457 + 68818568737 + +let cyphertext = encrypt(secret, key: publicKey) +==> 95186982543485985200666516508066093880038842892337880561554910904277290917831453 + 54854954722744805432145474047391353716305176389470779020645959135298322520888633 + 61674945129099575943384767330342554525120384485469428048962027149169876127890306 + 77028183904699491962050888974524603226290836984166164759586952419343589385279641 + 47999991283152843977988979846238236160274201261075188190509539751990119132013021 + 74866638595734222867005089157198503204192264814750832072844208520394603054901706 + 06024394731371973402595826456435944968439153664617188570808940022471990638468783 + 49208193955207336172861151720299024935127021719852700882 +``` + +Well, it looks encrypted all right, but can we get the original message back? +In theory, encrypting the cyphertext with the private key returns the original message. +Let's see: + +```Swift +let plaintext = encrypt(cyphertext, key: privateKey) +==> 83323446846105976078466731524728681905293067701804838925389198929123912971229457 + 68818568737 + +let received = String(data: plaintext.serialize(), encoding: NSUTF8StringEncoding) +==> "Arbitrary precision arithmetic is fun!" +``` + +Yay! This is truly terrific, but please don't use this example code in an actual +cryptography system. RSA has lots of subtle (and some not so subtle) complications +that we ignored to keep this example short. + +### Calculating the Digits of π + +Another fun activity to try with `BigInt`s is to generate the digits of π. +Let's try implementing [Jeremy Gibbon's spigot algorithm][spigot]. +This is a rather slow algorithm as π-generators go, but it makes up for it with its grooviness +factor: it's remarkably short, it only uses (big) integer arithmetic, and every iteration +produces a single new digit in the base-10 representation of π. This naturally leads to an +implementation as an infinite `GeneratorType`: + +[spigot]: http://www.cs.ox.ac.uk/jeremy.gibbons/publications/spigot.pdf + +```Swift +func digitsOfPi() -> AnyGenerator { + var q: BigUInt = 1 + var r: BigUInt = 180 + var t: BigUInt = 60 + var i: UInt64 = 2 // Does not overflow until digit #826_566_842 + return AnyIterator { + let u: UInt64 = 3 * (3 * i + 1) * (3 * i + 2) + let y = (q.multiplied(byDigit: 27 * i - 12) + 5 * r) / (5 * t) + (q, r, t) = ( + 10 * q.multiplied(byDigit: i * (2 * i - 1)), + 10 * (q.multiplied(byDigit: 5 * i - 2) + r - y * t).multiplied(byDigit: u), + t.multiplied(byDigit: u)) + i += 1 + return Int(y[0]) + } +} +``` + +Well, that was surprisingly easy. But does it work? Of course it does! + +```Swift +var digits = "π ≈ " +var count = 0 +for digit in digitsOfPi() { + assert(digit < 10) + digits += String(digit) + count += 1 + if count == 1 { digits += "." } + if count == 1000 { break } +} + +digits +==> π ≈ 3.14159265358979323846264338327950288419716939937510582097494459230781640628 + 62089986280348253421170679821480865132823066470938446095505822317253594081284811 + 17450284102701938521105559644622948954930381964428810975665933446128475648233786 + 78316527120190914564856692346034861045432664821339360726024914127372458700660631 + 55881748815209209628292540917153643678925903600113305305488204665213841469519415 + 11609433057270365759591953092186117381932611793105118548074462379962749567351885 + 75272489122793818301194912983367336244065664308602139494639522473719070217986094 + 37027705392171762931767523846748184676694051320005681271452635608277857713427577 + 89609173637178721468440901224953430146549585371050792279689258923542019956112129 + 02196086403441815981362977477130996051870721134999999837297804995105973173281609 + 63185950244594553469083026425223082533446850352619311881710100031378387528865875 + 33208381420617177669147303598253490428755468731159562863882353787593751957781857 + 780532171226806613001927876611195909216420198 +``` + +Now go and have some fun with big integers on your own! diff --git a/Example/myWeb3Wallet/Pods/BigInt/Sources/Addition.swift b/Example/myWeb3Wallet/Pods/BigInt/Sources/Addition.swift new file mode 100644 index 000000000..34f4d44e8 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/Sources/Addition.swift @@ -0,0 +1,126 @@ +// +// Addition.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension BigUInt { + //MARK: Addition + + /// Add `word` to this integer in place. + /// `word` is shifted `shift` words to the left before being added. + /// + /// - Complexity: O(max(count, shift)) + internal mutating func addWord(_ word: Word, shiftedBy shift: Int = 0) { + precondition(shift >= 0) + var carry = word + var i = shift + while carry > 0 { + let (d, c) = self[i].addingReportingOverflow(carry) + self[i] = d + carry = (c ? 1 : 0) + i += 1 + } + } + + /// Add the digit `d` to this integer and return the result. + /// `d` is shifted `shift` words to the left before being added. + /// + /// - Complexity: O(max(count, shift)) + internal func addingWord(_ word: Word, shiftedBy shift: Int = 0) -> BigUInt { + var r = self + r.addWord(word, shiftedBy: shift) + return r + } + + /// Add `b` to this integer in place. + /// `b` is shifted `shift` words to the left before being added. + /// + /// - Complexity: O(max(count, b.count + shift)) + internal mutating func add(_ b: BigUInt, shiftedBy shift: Int = 0) { + precondition(shift >= 0) + var carry = false + var bi = 0 + let bc = b.count + while bi < bc || carry { + let ai = shift + bi + let (d, c) = self[ai].addingReportingOverflow(b[bi]) + if carry { + let (d2, c2) = d.addingReportingOverflow(1) + self[ai] = d2 + carry = c || c2 + } + else { + self[ai] = d + carry = c + } + bi += 1 + } + } + + /// Add `b` to this integer and return the result. + /// `b` is shifted `shift` words to the left before being added. + /// + /// - Complexity: O(max(count, b.count + shift)) + internal func adding(_ b: BigUInt, shiftedBy shift: Int = 0) -> BigUInt { + var r = self + r.add(b, shiftedBy: shift) + return r + } + + /// Increment this integer by one. If `shift` is non-zero, it selects + /// the word that is to be incremented. + /// + /// - Complexity: O(count + shift) + internal mutating func increment(shiftedBy shift: Int = 0) { + self.addWord(1, shiftedBy: shift) + } + + /// Add `a` and `b` together and return the result. + /// + /// - Complexity: O(max(a.count, b.count)) + public static func +(a: BigUInt, b: BigUInt) -> BigUInt { + return a.adding(b) + } + + /// Add `a` and `b` together, and store the sum in `a`. + /// + /// - Complexity: O(max(a.count, b.count)) + public static func +=(a: inout BigUInt, b: BigUInt) { + a.add(b, shiftedBy: 0) + } +} + +extension BigInt { + /// Add `a` to `b` and return the result. + public static func +(a: BigInt, b: BigInt) -> BigInt { + switch (a.sign, b.sign) { + case (.plus, .plus): + return BigInt(sign: .plus, magnitude: a.magnitude + b.magnitude) + case (.minus, .minus): + return BigInt(sign: .minus, magnitude: a.magnitude + b.magnitude) + case (.plus, .minus): + if a.magnitude >= b.magnitude { + return BigInt(sign: .plus, magnitude: a.magnitude - b.magnitude) + } + else { + return BigInt(sign: .minus, magnitude: b.magnitude - a.magnitude) + } + case (.minus, .plus): + if b.magnitude >= a.magnitude { + return BigInt(sign: .plus, magnitude: b.magnitude - a.magnitude) + } + else { + return BigInt(sign: .minus, magnitude: a.magnitude - b.magnitude) + } + } + } + + /// Add `b` to `a` in place. + public static func +=(a: inout BigInt, b: BigInt) { + a = a + b + } +} + diff --git a/Example/myWeb3Wallet/Pods/BigInt/Sources/BigInt.swift b/Example/myWeb3Wallet/Pods/BigInt/Sources/BigInt.swift new file mode 100644 index 000000000..11318ffcc --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/Sources/BigInt.swift @@ -0,0 +1,74 @@ +// +// BigInt.swift +// BigInt +// +// Created by Károly Lőrentey on 2015-12-27. +// Copyright © 2016-2017 Károly Lőrentey. +// + +//MARK: BigInt + +/// An arbitary precision signed integer type, also known as a "big integer". +/// +/// Operations on big integers never overflow, but they might take a long time to execute. +/// The amount of memory (and address space) available is the only constraint to the magnitude of these numbers. +/// +/// This particular big integer type uses base-2^64 digits to represent integers. +/// +/// `BigInt` is essentially a tiny wrapper that extends `BigUInt` with a sign bit and provides signed integer +/// operations. Both the underlying absolute value and the negative/positive flag are available as read-write +/// properties. +/// +/// Not all algorithms of `BigUInt` are available for `BigInt` values; for example, there is no square root or +/// primality test for signed integers. When you need to call one of these, just extract the absolute value: +/// +/// ```Swift +/// BigInt(255).abs.isPrime() // Returns false +/// ``` +/// +public struct BigInt: SignedInteger { + public enum Sign { + case plus + case minus + } + + public typealias Magnitude = BigUInt + + /// The type representing a digit in `BigInt`'s underlying number system. + public typealias Word = BigUInt.Word + + public static var isSigned: Bool { + return true + } + + /// The absolute value of this integer. + public var magnitude: BigUInt + + /// True iff the value of this integer is negative. + public var sign: Sign + + /// Initializes a new big integer with the provided absolute number and sign flag. + public init(sign: Sign, magnitude: BigUInt) { + self.sign = (magnitude.isZero ? .plus : sign) + self.magnitude = magnitude + } + + /// Return true iff this integer is zero. + /// + /// - Complexity: O(1) + public var isZero: Bool { + return magnitude.isZero + } + + /// Returns `-1` if this value is negative and `1` if it’s positive; otherwise, `0`. + /// + /// - Returns: The sign of this number, expressed as an integer of the same type. + public func signum() -> BigInt { + switch sign { + case .plus: + return isZero ? 0 : 1 + case .minus: + return -1 + } + } +} diff --git a/Example/myWeb3Wallet/Pods/BigInt/Sources/BigUInt.swift b/Example/myWeb3Wallet/Pods/BigInt/Sources/BigUInt.swift new file mode 100644 index 000000000..81aa9a837 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/Sources/BigUInt.swift @@ -0,0 +1,386 @@ +// +// BigUInt.swift +// BigInt +// +// Created by Károly Lőrentey on 2015-12-26. +// Copyright © 2016-2017 Károly Lőrentey. +// + +/// An arbitary precision unsigned integer type, also known as a "big integer". +/// +/// Operations on big integers never overflow, but they may take a long time to execute. +/// The amount of memory (and address space) available is the only constraint to the magnitude of these numbers. +/// +/// This particular big integer type uses base-2^64 digits to represent integers; you can think of it as a wrapper +/// around `Array`. (In fact, `BigUInt` only uses an array if there are more than two digits.) +public struct BigUInt: UnsignedInteger { + /// The type representing a digit in `BigUInt`'s underlying number system. + public typealias Word = UInt + + /// The storage variants of a `BigUInt`. + enum Kind { + /// Value consists of the two specified words (low and high). Either or both words may be zero. + case inline(Word, Word) + /// Words are stored in a slice of the storage array. + case slice(from: Int, to: Int) + /// Words are stored in the storage array. + case array + } + + internal fileprivate (set) var kind: Kind // Internal for testing only + internal fileprivate (set) var storage: [Word] // Internal for testing only; stored separately to prevent COW copies + + /// Initializes a new BigUInt with value 0. + public init() { + self.kind = .inline(0, 0) + self.storage = [] + } + + internal init(word: Word) { + self.kind = .inline(word, 0) + self.storage = [] + } + + internal init(low: Word, high: Word) { + self.kind = .inline(low, high) + self.storage = [] + } + + /// Initializes a new BigUInt with the specified digits. The digits are ordered from least to most significant. + public init(words: [Word]) { + self.kind = .array + self.storage = words + normalize() + } + + internal init(words: [Word], from startIndex: Int, to endIndex: Int) { + self.kind = .slice(from: startIndex, to: endIndex) + self.storage = words + normalize() + } +} + +extension BigUInt { + public static var isSigned: Bool { + return false + } + + /// Return true iff this integer is zero. + /// + /// - Complexity: O(1) + var isZero: Bool { + switch kind { + case .inline(0, 0): return true + case .array: return storage.isEmpty + default: + return false + } + } + + /// Returns `1` if this value is, positive; otherwise, `0`. + /// + /// - Returns: The sign of this number, expressed as an integer of the same type. + public func signum() -> BigUInt { + return isZero ? 0 : 1 + } +} + +extension BigUInt { + mutating func ensureArray() { + switch kind { + case let .inline(w0, w1): + kind = .array + storage = w1 != 0 ? [w0, w1] + : w0 != 0 ? [w0] + : [] + case let .slice(from: start, to: end): + kind = .array + storage = Array(storage[start ..< end]) + case .array: + break + } + } + + var capacity: Int { + guard case .array = kind else { return 0 } + return storage.capacity + } + + mutating func reserveCapacity(_ minimumCapacity: Int) { + switch kind { + case let .inline(w0, w1): + kind = .array + storage.reserveCapacity(minimumCapacity) + if w1 != 0 { + storage.append(w0) + storage.append(w1) + } + else if w0 != 0 { + storage.append(w0) + } + case let .slice(from: start, to: end): + kind = .array + var words: [Word] = [] + words.reserveCapacity(Swift.max(end - start, minimumCapacity)) + words.append(contentsOf: storage[start ..< end]) + storage = words + case .array: + storage.reserveCapacity(minimumCapacity) + } + } + + /// Gets rid of leading zero digits in the digit array and converts slices into inline digits when possible. + internal mutating func normalize() { + switch kind { + case .slice(from: let start, to: var end): + assert(start >= 0 && end <= storage.count && start <= end) + while start < end, storage[end - 1] == 0 { + end -= 1 + } + switch end - start { + case 0: + kind = .inline(0, 0) + storage = [] + case 1: + kind = .inline(storage[start], 0) + storage = [] + case 2: + kind = .inline(storage[start], storage[start + 1]) + storage = [] + case storage.count: + assert(start == 0) + kind = .array + default: + kind = .slice(from: start, to: end) + } + case .array where storage.last == 0: + while storage.last == 0 { + storage.removeLast() + } + default: + break + } + } + + /// Set this integer to 0 without releasing allocated storage capacity (if any). + mutating func clear() { + self.load(0) + } + + /// Set this integer to `value` by copying its digits without releasing allocated storage capacity (if any). + mutating func load(_ value: BigUInt) { + switch kind { + case .inline, .slice: + self = value + case .array: + self.storage.removeAll(keepingCapacity: true) + self.storage.append(contentsOf: value.words) + } + } +} + +extension BigUInt { + //MARK: Collection-like members + + /// The number of digits in this integer, excluding leading zero digits. + var count: Int { + switch kind { + case let .inline(w0, w1): + return w1 != 0 ? 2 + : w0 != 0 ? 1 + : 0 + case let .slice(from: start, to: end): + return end - start + case .array: + return storage.count + } + } + + /// Get or set a digit at a given index. + /// + /// - Note: Unlike a normal collection, it is OK for the index to be greater than or equal to `endIndex`. + /// The subscripting getter returns zero for indexes beyond the most significant digit. + /// Setting these extended digits automatically appends new elements to the underlying digit array. + /// - Requires: index >= 0 + /// - Complexity: The getter is O(1). The setter is O(1) if the conditions below are true; otherwise it's O(count). + /// - The integer's storage is not shared with another integer + /// - The integer wasn't created as a slice of another integer + /// - `index < count` + subscript(_ index: Int) -> Word { + get { + precondition(index >= 0) + switch (kind, index) { + case (.inline(let w0, _), 0): return w0 + case (.inline(_, let w1), 1): return w1 + case (.slice(from: let start, to: let end), _) where index < end - start: + return storage[start + index] + case (.array, _) where index < storage.count: + return storage[index] + default: + return 0 + } + } + set(word) { + precondition(index >= 0) + switch (kind, index) { + case let (.inline(_, w1), 0): + kind = .inline(word, w1) + case let (.inline(w0, _), 1): + kind = .inline(w0, word) + case let (.slice(from: start, to: end), _) where index < end - start: + replace(at: index, with: word) + case (.array, _) where index < storage.count: + replace(at: index, with: word) + default: + extend(at: index, with: word) + } + } + } + + private mutating func replace(at index: Int, with word: Word) { + ensureArray() + precondition(index < storage.count) + storage[index] = word + if word == 0, index == storage.count - 1 { + normalize() + } + } + + private mutating func extend(at index: Int, with word: Word) { + guard word != 0 else { return } + reserveCapacity(index + 1) + precondition(index >= storage.count) + storage.append(contentsOf: repeatElement(0, count: index - storage.count)) + storage.append(word) + } + + /// Returns an integer built from the digits of this integer in the given range. + internal func extract(_ bounds: Range) -> BigUInt { + switch kind { + case let .inline(w0, w1): + let bounds = bounds.clamped(to: 0 ..< 2) + if bounds == 0 ..< 2 { + return BigUInt(low: w0, high: w1) + } + else if bounds == 0 ..< 1 { + return BigUInt(word: w0) + } + else if bounds == 1 ..< 2 { + return BigUInt(word: w1) + } + else { + return BigUInt() + } + case let .slice(from: start, to: end): + let s = Swift.min(end, start + Swift.max(bounds.lowerBound, 0)) + let e = Swift.max(s, (bounds.upperBound > end - start ? end : start + bounds.upperBound)) + return BigUInt(words: storage, from: s, to: e) + case .array: + let b = bounds.clamped(to: storage.startIndex ..< storage.endIndex) + return BigUInt(words: storage, from: b.lowerBound, to: b.upperBound) + } + } + + internal func extract(_ bounds: Bounds) -> BigUInt where Bounds.Bound == Int { + return self.extract(bounds.relative(to: 0 ..< Int.max)) + } +} + +extension BigUInt { + internal mutating func shiftRight(byWords amount: Int) { + assert(amount >= 0) + guard amount > 0 else { return } + switch kind { + case let .inline(_, w1) where amount == 1: + kind = .inline(w1, 0) + case .inline(_, _): + kind = .inline(0, 0) + case let .slice(from: start, to: end): + let s = start + amount + if s >= end { + kind = .inline(0, 0) + } + else { + kind = .slice(from: s, to: end) + normalize() + } + case .array: + if amount >= storage.count { + storage.removeAll(keepingCapacity: true) + } + else { + storage.removeFirst(amount) + } + } + } + + internal mutating func shiftLeft(byWords amount: Int) { + assert(amount >= 0) + guard amount > 0 else { return } + guard !isZero else { return } + switch kind { + case let .inline(w0, 0) where amount == 1: + kind = .inline(0, w0) + case let .inline(w0, w1): + let c = (w1 == 0 ? 1 : 2) + storage.reserveCapacity(amount + c) + storage.append(contentsOf: repeatElement(0, count: amount)) + storage.append(w0) + if w1 != 0 { + storage.append(w1) + } + kind = .array + case let .slice(from: start, to: end): + var words: [Word] = [] + words.reserveCapacity(amount + count) + words.append(contentsOf: repeatElement(0, count: amount)) + words.append(contentsOf: storage[start ..< end]) + storage = words + kind = .array + case .array: + storage.insert(contentsOf: repeatElement(0, count: amount), at: 0) + } + } +} + +extension BigUInt { + //MARK: Low and High + + /// Split this integer into a high-order and a low-order part. + /// + /// - Requires: count > 1 + /// - Returns: `(low, high)` such that + /// - `self == low.add(high, shiftedBy: middleIndex)` + /// - `high.width <= floor(width / 2)` + /// - `low.width <= ceil(width / 2)` + /// - Complexity: Typically O(1), but O(count) in the worst case, because high-order zero digits need to be removed after the split. + internal var split: (high: BigUInt, low: BigUInt) { + precondition(count > 1) + let mid = middleIndex + return (self.extract(mid...), self.extract(.. 1 + internal var low: BigUInt { + return self.extract(0 ..< middleIndex) + } + + /// The high-order half of this BigUInt. + /// + /// - Returns: `self[middleIndex ..< count]` + /// - Requires: count > 1 + internal var high: BigUInt { + return self.extract(middleIndex ..< count) + } +} + diff --git a/Example/myWeb3Wallet/Pods/BigInt/Sources/Bitwise Ops.swift b/Example/myWeb3Wallet/Pods/BigInt/Sources/Bitwise Ops.swift new file mode 100644 index 000000000..0d00148bd --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/Sources/Bitwise Ops.swift @@ -0,0 +1,121 @@ +// +// Bitwise Ops.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +//MARK: Bitwise Operations + +extension BigUInt { + /// Return the ones' complement of `a`. + /// + /// - Complexity: O(a.count) + public static prefix func ~(a: BigUInt) -> BigUInt { + return BigUInt(words: a.words.map { ~$0 }) + } + + /// Calculate the bitwise OR of `a` and `b`, and store the result in `a`. + /// + /// - Complexity: O(max(a.count, b.count)) + public static func |= (a: inout BigUInt, b: BigUInt) { + a.reserveCapacity(b.count) + for i in 0 ..< b.count { + a[i] |= b[i] + } + } + + /// Calculate the bitwise AND of `a` and `b` and return the result. + /// + /// - Complexity: O(max(a.count, b.count)) + public static func &= (a: inout BigUInt, b: BigUInt) { + for i in 0 ..< Swift.max(a.count, b.count) { + a[i] &= b[i] + } + } + + /// Calculate the bitwise XOR of `a` and `b` and return the result. + /// + /// - Complexity: O(max(a.count, b.count)) + public static func ^= (a: inout BigUInt, b: BigUInt) { + a.reserveCapacity(b.count) + for i in 0 ..< b.count { + a[i] ^= b[i] + } + } +} + +extension BigInt { + public static prefix func ~(x: BigInt) -> BigInt { + switch x.sign { + case .plus: + return BigInt(sign: .minus, magnitude: x.magnitude + 1) + case .minus: + return BigInt(sign: .plus, magnitude: x.magnitude - 1) + } + } + + public static func &(lhs: inout BigInt, rhs: BigInt) -> BigInt { + let left = lhs.words + let right = rhs.words + // Note we aren't using left.count/right.count here; we account for the sign bit separately later. + let count = Swift.max(lhs.magnitude.count, rhs.magnitude.count) + var words: [UInt] = [] + words.reserveCapacity(count) + for i in 0 ..< count { + words.append(left[i] & right[i]) + } + if lhs.sign == .minus && rhs.sign == .minus { + words.twosComplement() + return BigInt(sign: .minus, magnitude: BigUInt(words: words)) + } + return BigInt(sign: .plus, magnitude: BigUInt(words: words)) + } + + public static func |(lhs: inout BigInt, rhs: BigInt) -> BigInt { + let left = lhs.words + let right = rhs.words + // Note we aren't using left.count/right.count here; we account for the sign bit separately later. + let count = Swift.max(lhs.magnitude.count, rhs.magnitude.count) + var words: [UInt] = [] + words.reserveCapacity(count) + for i in 0 ..< count { + words.append(left[i] | right[i]) + } + if lhs.sign == .minus || rhs.sign == .minus { + words.twosComplement() + return BigInt(sign: .minus, magnitude: BigUInt(words: words)) + } + return BigInt(sign: .plus, magnitude: BigUInt(words: words)) + } + + public static func ^(lhs: inout BigInt, rhs: BigInt) -> BigInt { + let left = lhs.words + let right = rhs.words + // Note we aren't using left.count/right.count here; we account for the sign bit separately later. + let count = Swift.max(lhs.magnitude.count, rhs.magnitude.count) + var words: [UInt] = [] + words.reserveCapacity(count) + for i in 0 ..< count { + words.append(left[i] ^ right[i]) + } + if (lhs.sign == .minus) != (rhs.sign == .minus) { + words.twosComplement() + return BigInt(sign: .minus, magnitude: BigUInt(words: words)) + } + return BigInt(sign: .plus, magnitude: BigUInt(words: words)) + } + + public static func &=(lhs: inout BigInt, rhs: BigInt) { + lhs = lhs & rhs + } + + public static func |=(lhs: inout BigInt, rhs: BigInt) { + lhs = lhs | rhs + } + + public static func ^=(lhs: inout BigInt, rhs: BigInt) { + lhs = lhs ^ rhs + } +} diff --git a/Example/myWeb3Wallet/Pods/BigInt/Sources/Codable.swift b/Example/myWeb3Wallet/Pods/BigInt/Sources/Codable.swift new file mode 100644 index 000000000..b53b30be5 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/Sources/Codable.swift @@ -0,0 +1,155 @@ +// +// Codable.swift +// BigInt +// +// Created by Károly Lőrentey on 2017-8-11. +// Copyright © 2016-2017 Károly Lőrentey. +// + + +// Little-endian to big-endian +struct Units: RandomAccessCollection +where Words.Element: FixedWidthInteger, Words.Index == Int { + typealias Word = Words.Element + let words: Words + init(of type: Unit.Type, _ words: Words) { + precondition(Word.bitWidth % Unit.bitWidth == 0 || Unit.bitWidth % Word.bitWidth == 0) + self.words = words + } + var count: Int { return (words.count * Word.bitWidth + Unit.bitWidth - 1) / Unit.bitWidth } + var startIndex: Int { return 0 } + var endIndex: Int { return count } + subscript(_ index: Int) -> Unit { + let index = count - 1 - index + if Unit.bitWidth == Word.bitWidth { + return Unit(words[index]) + } + else if Unit.bitWidth > Word.bitWidth { + let c = Unit.bitWidth / Word.bitWidth + var unit: Unit = 0 + var j = 0 + for i in (c * index) ..< Swift.min(c * (index + 1), words.endIndex) { + unit |= Unit(words[i]) << j + j += Word.bitWidth + } + return unit + } + // Unit.bitWidth < Word.bitWidth + let c = Word.bitWidth / Unit.bitWidth + let i = index / c + let j = index % c + return Unit(truncatingIfNeeded: words[i] >> (j * Unit.bitWidth)) + } +} + +extension Array where Element: FixedWidthInteger { + // Big-endian to little-endian + init(count: Int?, generator: () throws -> Unit?) rethrows { + typealias Word = Element + precondition(Word.bitWidth % Unit.bitWidth == 0 || Unit.bitWidth % Word.bitWidth == 0) + self = [] + if Unit.bitWidth == Word.bitWidth { + if let count = count { + self.reserveCapacity(count) + } + while let unit = try generator() { + self.append(Word(unit)) + } + } + else if Unit.bitWidth > Word.bitWidth { + let wordsPerUnit = Unit.bitWidth / Word.bitWidth + if let count = count { + self.reserveCapacity(count * wordsPerUnit) + } + while let unit = try generator() { + var shift = Unit.bitWidth - Word.bitWidth + while shift >= 0 { + self.append(Word(truncatingIfNeeded: unit >> shift)) + shift -= Word.bitWidth + } + } + } + else { + let unitsPerWord = Word.bitWidth / Unit.bitWidth + if let count = count { + self.reserveCapacity((count + unitsPerWord - 1) / unitsPerWord) + } + var word: Word = 0 + var c = 0 + while let unit = try generator() { + word <<= Unit.bitWidth + word |= Word(unit) + c += Unit.bitWidth + if c == Word.bitWidth { + self.append(word) + word = 0 + c = 0 + } + } + if c > 0 { + self.append(word << c) + var shifted: Word = 0 + for i in self.indices { + let word = self[i] + self[i] = shifted | (word >> c) + shifted = word << (Word.bitWidth - c) + } + } + } + self.reverse() + } +} + +extension BigInt: Codable { + public init(from decoder: Decoder) throws { + var container = try decoder.unkeyedContainer() + + // Decode sign + let sign: BigInt.Sign + switch try container.decode(String.self) { + case "+": + sign = .plus + case "-": + sign = .minus + default: + throw DecodingError.dataCorrupted(.init(codingPath: container.codingPath, + debugDescription: "Invalid big integer sign")) + } + + // Decode magnitude + let words = try [UInt](count: container.count?.advanced(by: -1)) { () -> UInt64? in + guard !container.isAtEnd else { return nil } + return try container.decode(UInt64.self) + } + let magnitude = BigUInt(words: words) + + self.init(sign: sign, magnitude: magnitude) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.unkeyedContainer() + try container.encode(sign == .plus ? "+" : "-") + let units = Units(of: UInt64.self, self.magnitude.words) + if units.isEmpty { + try container.encode(0 as UInt64) + } + else { + try container.encode(contentsOf: units) + } + } +} + +extension BigUInt: Codable { + public init(from decoder: Decoder) throws { + let value = try BigInt(from: decoder) + guard value.sign == .plus else { + throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, + debugDescription: "BigUInt cannot hold a negative value")) + } + self = value.magnitude + } + + public func encode(to encoder: Encoder) throws { + try BigInt(sign: .plus, magnitude: self).encode(to: encoder) + } +} diff --git a/Example/myWeb3Wallet/Pods/BigInt/Sources/Comparable.swift b/Example/myWeb3Wallet/Pods/BigInt/Sources/Comparable.swift new file mode 100644 index 000000000..d9ab87e7e --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/Sources/Comparable.swift @@ -0,0 +1,63 @@ +// +// Comparable.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +import Foundation + +extension BigUInt: Comparable { + //MARK: Comparison + + /// Compare `a` to `b` and return an `NSComparisonResult` indicating their order. + /// + /// - Complexity: O(count) + public static func compare(_ a: BigUInt, _ b: BigUInt) -> ComparisonResult { + if a.count != b.count { return a.count > b.count ? .orderedDescending : .orderedAscending } + for i in (0 ..< a.count).reversed() { + let ad = a[i] + let bd = b[i] + if ad != bd { return ad > bd ? .orderedDescending : .orderedAscending } + } + return .orderedSame + } + + /// Return true iff `a` is equal to `b`. + /// + /// - Complexity: O(count) + public static func ==(a: BigUInt, b: BigUInt) -> Bool { + return BigUInt.compare(a, b) == .orderedSame + } + + /// Return true iff `a` is less than `b`. + /// + /// - Complexity: O(count) + public static func <(a: BigUInt, b: BigUInt) -> Bool { + return BigUInt.compare(a, b) == .orderedAscending + } +} + +extension BigInt { + /// Return true iff `a` is equal to `b`. + public static func ==(a: BigInt, b: BigInt) -> Bool { + return a.sign == b.sign && a.magnitude == b.magnitude + } + + /// Return true iff `a` is less than `b`. + public static func <(a: BigInt, b: BigInt) -> Bool { + switch (a.sign, b.sign) { + case (.plus, .plus): + return a.magnitude < b.magnitude + case (.plus, .minus): + return false + case (.minus, .plus): + return true + case (.minus, .minus): + return a.magnitude > b.magnitude + } + } +} + + diff --git a/Example/myWeb3Wallet/Pods/BigInt/Sources/Data Conversion.swift b/Example/myWeb3Wallet/Pods/BigInt/Sources/Data Conversion.swift new file mode 100644 index 000000000..25c65521d --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/Sources/Data Conversion.swift @@ -0,0 +1,179 @@ +// +// Data Conversion.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-04. +// Copyright © 2016-2017 Károly Lőrentey. +// + +import Foundation + +extension BigUInt { + //MARK: NSData Conversion + + /// Initialize a BigInt from bytes accessed from an UnsafeRawBufferPointer + public init(_ buffer: UnsafeRawBufferPointer) { + // This assumes Word is binary. + precondition(Word.bitWidth % 8 == 0) + + self.init() + + let length = buffer.count + guard length > 0 else { return } + let bytesPerDigit = Word.bitWidth / 8 + var index = length / bytesPerDigit + var c = bytesPerDigit - length % bytesPerDigit + if c == bytesPerDigit { + c = 0 + index -= 1 + } + + var word: Word = 0 + for byte in buffer { + word <<= 8 + word += Word(byte) + c += 1 + if c == bytesPerDigit { + self[index] = word + index -= 1 + c = 0 + word = 0 + } + } + assert(c == 0 && word == 0 && index == -1) + } + + + /// Initializes an integer from the bits stored inside a piece of `Data`. + /// The data is assumed to be in network (big-endian) byte order. + public init(_ data: Data) { + // This assumes Word is binary. + precondition(Word.bitWidth % 8 == 0) + + self.init() + + let length = data.count + guard length > 0 else { return } + let bytesPerDigit = Word.bitWidth / 8 + var index = length / bytesPerDigit + var c = bytesPerDigit - length % bytesPerDigit + if c == bytesPerDigit { + c = 0 + index -= 1 + } + let word: Word = data.withUnsafeBytes { buffPtr in + var word: Word = 0 + let p = buffPtr.bindMemory(to: UInt8.self) + for byte in p { + word <<= 8 + word += Word(byte) + c += 1 + if c == bytesPerDigit { + self[index] = word + index -= 1 + c = 0 + word = 0 + } + } + return word + } + assert(c == 0 && word == 0 && index == -1) + } + + /// Return a `Data` value that contains the base-256 representation of this integer, in network (big-endian) byte order. + public func serialize() -> Data { + // This assumes Digit is binary. + precondition(Word.bitWidth % 8 == 0) + + let byteCount = (self.bitWidth + 7) / 8 + + guard byteCount > 0 else { return Data() } + + var data = Data(count: byteCount) + data.withUnsafeMutableBytes { buffPtr in + let p = buffPtr.bindMemory(to: UInt8.self) + var i = byteCount - 1 + for var word in self.words { + for _ in 0 ..< Word.bitWidth / 8 { + p[i] = UInt8(word & 0xFF) + word >>= 8 + if i == 0 { + assert(word == 0) + break + } + i -= 1 + } + } + } + return data + } +} + +extension BigInt { + + /// Initialize a BigInt from bytes accessed from an UnsafeRawBufferPointer, + /// where the first byte indicates sign (0 for positive, 1 for negative) + public init(_ buffer: UnsafeRawBufferPointer) { + // This assumes Word is binary. + precondition(Word.bitWidth % 8 == 0) + + self.init() + + let length = buffer.count + + // Serialized data for a BigInt should contain at least 2 bytes: one representing + // the sign, and another for the non-zero magnitude. Zero is represented by an + // empty Data struct, and negative zero is not supported. + guard length > 1, let firstByte = buffer.first else { return } + + // The first byte gives the sign + // This byte is compared to a bitmask to allow additional functionality to be added + // to this byte in the future. + self.sign = firstByte & 0b1 == 0 ? .plus : .minus + + self.magnitude = BigUInt(UnsafeRawBufferPointer(rebasing: buffer.dropFirst(1))) + } + + /// Initializes an integer from the bits stored inside a piece of `Data`. + /// The data is assumed to be in network (big-endian) byte order with a first + /// byte to represent the sign (0 for positive, 1 for negative) + public init(_ data: Data) { + // This assumes Word is binary. + // This is the same assumption made when initializing BigUInt from Data + precondition(Word.bitWidth % 8 == 0) + + self.init() + + // Serialized data for a BigInt should contain at least 2 bytes: one representing + // the sign, and another for the non-zero magnitude. Zero is represented by an + // empty Data struct, and negative zero is not supported. + guard data.count > 1, let firstByte = data.first else { return } + + // The first byte gives the sign + // This byte is compared to a bitmask to allow additional functionality to be added + // to this byte in the future. + self.sign = firstByte & 0b1 == 0 ? .plus : .minus + + // The remaining bytes are read and stored as the magnitude + self.magnitude = BigUInt(data.dropFirst(1)) + } + + /// Return a `Data` value that contains the base-256 representation of this integer, in network (big-endian) byte order and a prepended byte to indicate the sign (0 for positive, 1 for negative) + public func serialize() -> Data { + // Create a data object for the magnitude portion of the BigInt + let magnitudeData = self.magnitude.serialize() + + // Similar to BigUInt, a value of 0 should return an initialized, empty Data struct + guard magnitudeData.count > 0 else { return magnitudeData } + + // Create a new Data struct for the signed BigInt value + var data = Data(capacity: magnitudeData.count + 1) + + // The first byte should be 0 for a positive value, or 1 for a negative value + // i.e., the sign bit is the LSB + data.append(self.sign == .plus ? 0 : 1) + + data.append(magnitudeData) + return data + } +} diff --git a/Example/myWeb3Wallet/Pods/BigInt/Sources/Division.swift b/Example/myWeb3Wallet/Pods/BigInt/Sources/Division.swift new file mode 100644 index 000000000..4393f52e9 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/Sources/Division.swift @@ -0,0 +1,374 @@ +// +// Division.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +//MARK: Full-width multiplication and division + +extension FixedWidthInteger where Magnitude == Self { + private var halfShift: Self { + return Self(Self.bitWidth / 2) + + } + private var high: Self { + return self &>> halfShift + } + + private var low: Self { + let mask: Self = 1 &<< halfShift - 1 + return self & mask + } + + private var upshifted: Self { + return self &<< halfShift + } + + private var split: (high: Self, low: Self) { + return (self.high, self.low) + } + + private init(_ value: (high: Self, low: Self)) { + self = value.high.upshifted + value.low + } + + /// Divide the double-width integer `dividend` by `self` and return the quotient and remainder. + /// + /// - Requires: `dividend.high < self`, so that the result will fit in a single digit. + /// - Complexity: O(1) with 2 divisions, 6 multiplications and ~12 or so additions/subtractions. + internal func fastDividingFullWidth(_ dividend: (high: Self, low: Self.Magnitude)) -> (quotient: Self, remainder: Self) { + // Division is complicated; doing it with single-digit operations is maddeningly complicated. + // This is a Swift adaptation for "divlu2" in Hacker's Delight, + // which is in turn a C adaptation of Knuth's Algorithm D (TAOCP vol 2, 4.3.1). + precondition(dividend.high < self) + + // This replaces the implementation in stdlib, which is much slower. + // FIXME: Speed up stdlib. It should use full-width idiv on Intel processors, and + // fall back to a reasonably fast algorithm elsewhere. + + // The trick here is that we're actually implementing a 4/2 long division using half-words, + // with the long division loop unrolled into two 3/2 half-word divisions. + // Luckily, 3/2 half-word division can be approximated by a single full-word division operation + // that, when the divisor is normalized, differs from the correct result by at most 2. + + /// Find the half-word quotient in `u / vn`, which must be normalized. + /// `u` contains three half-words in the two halves of `u.high` and the lower half of + /// `u.low`. (The weird distribution makes for a slightly better fit with the input.) + /// `vn` contains the normalized divisor, consisting of two half-words. + /// + /// - Requires: u.high < vn && u.low.high == 0 && vn.leadingZeroBitCount == 0 + func quotient(dividing u: (high: Self, low: Self), by vn: Self) -> Self { + let (vn1, vn0) = vn.split + // Get approximate quotient. + let (q, r) = u.high.quotientAndRemainder(dividingBy: vn1) + let p = q * vn0 + // q is often already correct, but sometimes the approximation overshoots by at most 2. + // The code that follows checks for this while being careful to only perform single-digit operations. + if q.high == 0 && p <= r.upshifted + u.low { return q } + let r2 = r + vn1 + if r2.high != 0 { return q - 1 } + if (q - 1).high == 0 && p - vn0 <= r2.upshifted + u.low { return q - 1 } + //assert((r + 2 * vn1).high != 0 || p - 2 * vn0 <= (r + 2 * vn1).upshifted + u.low) + return q - 2 + } + /// Divide 3 half-digits by 2 half-digits to get a half-digit quotient and a full-digit remainder. + /// + /// - Requires: u.high < v && u.low.high == 0 && vn.width = width(Digit) + func quotientAndRemainder(dividing u: (high: Self, low: Self), by v: Self) -> (quotient: Self, remainder: Self) { + let q = quotient(dividing: u, by: v) + // Note that `uh.low` masks off a couple of bits, and `q * v` and the + // subtraction are likely to overflow. Despite this, the end result (remainder) will + // still be correct and it will fit inside a single (full) Digit. + let r = Self(u) &- q &* v + assert(r < v) + return (q, r) + } + + // Normalize the dividend and the divisor (self) such that the divisor has no leading zeroes. + let z = Self(self.leadingZeroBitCount) + let w = Self(Self.bitWidth) - z + let vn = self << z + + let un32 = (z == 0 ? dividend.high : (dividend.high &<< z) | (dividend.low &>> w)) // No bits are lost + let un10 = dividend.low &<< z + let (un1, un0) = un10.split + + // Divide `(un32,un10)` by `vn`, splitting the full 4/2 division into two 3/2 ones. + let (q1, un21) = quotientAndRemainder(dividing: (un32, un1), by: vn) + let (q0, rn) = quotientAndRemainder(dividing: (un21, un0), by: vn) + + // Undo normalization of the remainder and combine the two halves of the quotient. + let mod = rn >> z + let div = Self((q1, q0)) + return (div, mod) + } + + /// Return the quotient of the 3/2-word division `x/y` as a single word. + /// + /// - Requires: (x.0, x.1) <= y && y.0.high != 0 + /// - Returns: The exact value when it fits in a single word, otherwise `Self`. + static func approximateQuotient(dividing x: (Self, Self, Self), by y: (Self, Self)) -> Self { + // Start with q = (x.0, x.1) / y.0, (or Word.max on overflow) + var q: Self + var r: Self + if x.0 == y.0 { + q = Self.max + let (s, o) = x.0.addingReportingOverflow(x.1) + if o { return q } + r = s + } + else { + (q, r) = y.0.fastDividingFullWidth((x.0, x.1)) + } + // Now refine q by considering x.2 and y.1. + // Note that since y is normalized, q * y - x is between 0 and 2. + let (ph, pl) = q.multipliedFullWidth(by: y.1) + if ph < r || (ph == r && pl <= x.2) { return q } + + let (r1, ro) = r.addingReportingOverflow(y.0) + if ro { return q - 1 } + + let (pl1, so) = pl.subtractingReportingOverflow(y.1) + let ph1 = (so ? ph - 1 : ph) + + if ph1 < r1 || (ph1 == r1 && pl1 <= x.2) { return q - 1 } + return q - 2 + } +} + +extension BigUInt { + //MARK: Division + + /// Divide this integer by the word `y`, leaving the quotient in its place and returning the remainder. + /// + /// - Requires: y > 0 + /// - Complexity: O(count) + internal mutating func divide(byWord y: Word) -> Word { + precondition(y > 0) + if y == 1 { return 0 } + + var remainder: Word = 0 + for i in (0 ..< count).reversed() { + let u = self[i] + (self[i], remainder) = y.fastDividingFullWidth((remainder, u)) + } + return remainder + } + + /// Divide this integer by the word `y` and return the resulting quotient and remainder. + /// + /// - Requires: y > 0 + /// - Returns: (quotient, remainder) where quotient = floor(x/y), remainder = x - quotient * y + /// - Complexity: O(x.count) + internal func quotientAndRemainder(dividingByWord y: Word) -> (quotient: BigUInt, remainder: Word) { + var div = self + let mod = div.divide(byWord: y) + return (div, mod) + } + + /// Divide `x` by `y`, putting the quotient in `x` and the remainder in `y`. + /// Reusing integers like this reduces the number of allocations during the calculation. + static func divide(_ x: inout BigUInt, by y: inout BigUInt) { + // This is a Swift adaptation of "divmnu" from Hacker's Delight, which is in + // turn a C adaptation of Knuth's Algorithm D (TAOCP vol 2, 4.3.1). + + precondition(!y.isZero) + + // First, let's take care of the easy cases. + if x < y { + (x, y) = (0, x) + return + } + if y.count == 1 { + // The single-word case reduces to a simpler loop. + y = BigUInt(x.divide(byWord: y[0])) + return + } + + // In the hard cases, we will perform the long division algorithm we learned in school. + // It works by successively calculating the single-word quotient of the top y.count + 1 + // words of x divided by y, replacing the top of x with the remainder, and repeating + // the process one word lower. + // + // The tricky part is that the algorithm needs to be able to do n+1/n word divisions, + // but we only have a primitive for dividing two words by a single + // word. (Remember that this step is also tricky when we do it on paper!) + // + // The solution is that the long division can be approximated by a single full division + // using just the most significant words. We can then use multiplications and + // subtractions to refine the approximation until we get the correct quotient word. + // + // We could do this by doing a simple 2/1 full division, but Knuth goes one step further, + // and implements a 3/2 division. This results in an exact approximation in the + // vast majority of cases, eliminating an extra subtraction over big integers. + // + // The function `approximateQuotient` above implements Knuth's 3/2 division algorithm. + // It requires that the divisor's most significant word is larger than + // Word.max / 2. This ensures that the approximation has tiny error bounds, + // which is what makes this entire approach viable. + // To satisfy this requirement, we will normalize the division by multiplying + // both the divisor and the dividend by the same (small) factor. + let z = y.leadingZeroBitCount + y <<= z + x <<= z // We'll calculate the remainder in the normalized dividend. + var quotient = BigUInt() + assert(y.leadingZeroBitCount == 0) + + // We're ready to start the long division! + let dc = y.count + let d1 = y[dc - 1] + let d0 = y[dc - 2] + var product: BigUInt = 0 + for j in (dc ... x.count).reversed() { + // Approximate dividing the top dc+1 words of `remainder` using the topmost 3/2 words. + let r2 = x[j] + let r1 = x[j - 1] + let r0 = x[j - 2] + let q = Word.approximateQuotient(dividing: (r2, r1, r0), by: (d1, d0)) + + // Multiply the entire divisor with `q` and subtract the result from remainder. + // Normalization ensures the 3/2 quotient will either be exact for the full division, or + // it may overshoot by at most 1, in which case the product will be greater + // than the remainder. + product.load(y) + product.multiply(byWord: q) + if product <= x.extract(j - dc ..< j + 1) { + x.subtract(product, shiftedBy: j - dc) + quotient[j - dc] = q + } + else { + // This case is extremely rare -- it has a probability of 1/2^(Word.bitWidth - 1). + x.add(y, shiftedBy: j - dc) + x.subtract(product, shiftedBy: j - dc) + quotient[j - dc] = q - 1 + } + } + // The remainder's normalization needs to be undone, but otherwise we're done. + x >>= z + y = x + x = quotient + } + + /// Divide `x` by `y`, putting the remainder in `x`. + mutating func formRemainder(dividingBy y: BigUInt, normalizedBy shift: Int) { + precondition(!y.isZero) + assert(y.leadingZeroBitCount == 0) + if y.count == 1 { + let remainder = self.divide(byWord: y[0] >> shift) + self.load(BigUInt(remainder)) + return + } + self <<= shift + if self >= y { + let dc = y.count + let d1 = y[dc - 1] + let d0 = y[dc - 2] + var product: BigUInt = 0 + for j in (dc ... self.count).reversed() { + let r2 = self[j] + let r1 = self[j - 1] + let r0 = self[j - 2] + let q = Word.approximateQuotient(dividing: (r2, r1, r0), by: (d1, d0)) + product.load(y) + product.multiply(byWord: q) + if product <= self.extract(j - dc ..< j + 1) { + self.subtract(product, shiftedBy: j - dc) + } + else { + self.add(y, shiftedBy: j - dc) + self.subtract(product, shiftedBy: j - dc) + } + } + } + self >>= shift + } + + + /// Divide this integer by `y` and return the resulting quotient and remainder. + /// + /// - Requires: `y > 0` + /// - Returns: `(quotient, remainder)` where `quotient = floor(self/y)`, `remainder = self - quotient * y` + /// - Complexity: O(count^2) + public func quotientAndRemainder(dividingBy y: BigUInt) -> (quotient: BigUInt, remainder: BigUInt) { + var x = self + var y = y + BigUInt.divide(&x, by: &y) + return (x, y) + } + + /// Divide `x` by `y` and return the quotient. + /// + /// - Note: Use `divided(by:)` if you also need the remainder. + public static func /(x: BigUInt, y: BigUInt) -> BigUInt { + return x.quotientAndRemainder(dividingBy: y).quotient + } + + /// Divide `x` by `y` and return the remainder. + /// + /// - Note: Use `divided(by:)` if you also need the remainder. + public static func %(x: BigUInt, y: BigUInt) -> BigUInt { + var x = x + let shift = y.leadingZeroBitCount + x.formRemainder(dividingBy: y << shift, normalizedBy: shift) + return x + } + + /// Divide `x` by `y` and store the quotient in `x`. + /// + /// - Note: Use `divided(by:)` if you also need the remainder. + public static func /=(x: inout BigUInt, y: BigUInt) { + var y = y + BigUInt.divide(&x, by: &y) + } + + /// Divide `x` by `y` and store the remainder in `x`. + /// + /// - Note: Use `divided(by:)` if you also need the remainder. + public static func %=(x: inout BigUInt, y: BigUInt) { + let shift = y.leadingZeroBitCount + x.formRemainder(dividingBy: y << shift, normalizedBy: shift) + } +} + +extension BigInt { + /// Divide this integer by `y` and return the resulting quotient and remainder. + /// + /// - Requires: `y > 0` + /// - Returns: `(quotient, remainder)` where `quotient = floor(self/y)`, `remainder = self - quotient * y` + /// - Complexity: O(count^2) + public func quotientAndRemainder(dividingBy y: BigInt) -> (quotient: BigInt, remainder: BigInt) { + var a = self.magnitude + var b = y.magnitude + BigUInt.divide(&a, by: &b) + return (BigInt(sign: self.sign == y.sign ? .plus : .minus, magnitude: a), + BigInt(sign: self.sign, magnitude: b)) + } + + /// Divide `a` by `b` and return the quotient. Traps if `b` is zero. + public static func /(a: BigInt, b: BigInt) -> BigInt { + return BigInt(sign: a.sign == b.sign ? .plus : .minus, magnitude: a.magnitude / b.magnitude) + } + + /// Divide `a` by `b` and return the remainder. The result has the same sign as `a`. + public static func %(a: BigInt, b: BigInt) -> BigInt { + return BigInt(sign: a.sign, magnitude: a.magnitude % b.magnitude) + } + + /// Return the result of `a` mod `b`. The result is always a nonnegative integer that is less than the absolute value of `b`. + public func modulus(_ mod: BigInt) -> BigInt { + let remainder = self.magnitude % mod.magnitude + return BigInt( + self.sign == .minus && !remainder.isZero + ? mod.magnitude - remainder + : remainder) + } +} + +extension BigInt { + /// Divide `a` by `b` storing the quotient in `a`. + public static func /=(a: inout BigInt, b: BigInt) { a = a / b } + /// Divide `a` by `b` storing the remainder in `a`. + public static func %=(a: inout BigInt, b: BigInt) { a = a % b } +} diff --git a/Example/myWeb3Wallet/Pods/BigInt/Sources/Exponentiation.swift b/Example/myWeb3Wallet/Pods/BigInt/Sources/Exponentiation.swift new file mode 100644 index 000000000..9d7ee85da --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/Sources/Exponentiation.swift @@ -0,0 +1,119 @@ +// +// Exponentiation.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension BigUInt { + //MARK: Exponentiation + + /// Returns this integer raised to the power `exponent`. + /// + /// This function calculates the result by [successively squaring the base while halving the exponent][expsqr]. + /// + /// [expsqr]: https://en.wikipedia.org/wiki/Exponentiation_by_squaring + /// + /// - Note: This function can be unreasonably expensive for large exponents, which is why `exponent` is + /// a simple integer value. If you want to calculate big exponents, you'll probably need to use + /// the modulo arithmetic variant. + /// - Returns: 1 if `exponent == 0`, otherwise `self` raised to `exponent`. (This implies that `0.power(0) == 1`.) + /// - SeeAlso: `BigUInt.power(_:, modulus:)` + /// - Complexity: O((exponent * self.count)^log2(3)) or somesuch. The result may require a large amount of memory, too. + public func power(_ exponent: Int) -> BigUInt { + if exponent == 0 { return 1 } + if exponent == 1 { return self } + if exponent < 0 { + precondition(!self.isZero) + return self == 1 ? 1 : 0 + } + if self <= 1 { return self } + var result = BigUInt(1) + var b = self + var e = exponent + while e > 0 { + if e & 1 == 1 { + result *= b + } + e >>= 1 + b *= b + } + return result + } + + /// Returns the remainder of this integer raised to the power `exponent` in modulo arithmetic under `modulus`. + /// + /// Uses the [right-to-left binary method][rtlb]. + /// + /// [rtlb]: https://en.wikipedia.org/wiki/Modular_exponentiation#Right-to-left_binary_method + /// + /// - Complexity: O(exponent.count * modulus.count^log2(3)) or somesuch + public func power(_ exponent: BigUInt, modulus: BigUInt) -> BigUInt { + precondition(!modulus.isZero) + if modulus == (1 as BigUInt) { return 0 } + let shift = modulus.leadingZeroBitCount + let normalizedModulus = modulus << shift + var result = BigUInt(1) + var b = self + b.formRemainder(dividingBy: normalizedModulus, normalizedBy: shift) + for var e in exponent.words { + for _ in 0 ..< Word.bitWidth { + if e & 1 == 1 { + result *= b + result.formRemainder(dividingBy: normalizedModulus, normalizedBy: shift) + } + e >>= 1 + b *= b + b.formRemainder(dividingBy: normalizedModulus, normalizedBy: shift) + } + } + return result + } +} + +extension BigInt { + /// Returns this integer raised to the power `exponent`. + /// + /// This function calculates the result by [successively squaring the base while halving the exponent][expsqr]. + /// + /// [expsqr]: https://en.wikipedia.org/wiki/Exponentiation_by_squaring + /// + /// - Note: This function can be unreasonably expensive for large exponents, which is why `exponent` is + /// a simple integer value. If you want to calculate big exponents, you'll probably need to use + /// the modulo arithmetic variant. + /// - Returns: 1 if `exponent == 0`, otherwise `self` raised to `exponent`. (This implies that `0.power(0) == 1`.) + /// - SeeAlso: `BigUInt.power(_:, modulus:)` + /// - Complexity: O((exponent * self.count)^log2(3)) or somesuch. The result may require a large amount of memory, too. + public func power(_ exponent: Int) -> BigInt { + return BigInt(sign: self.sign == .minus && exponent & 1 != 0 ? .minus : .plus, + magnitude: self.magnitude.power(exponent)) + } + + /// Returns the remainder of this integer raised to the power `exponent` in modulo arithmetic under `modulus`. + /// + /// Uses the [right-to-left binary method][rtlb]. + /// + /// [rtlb]: https://en.wikipedia.org/wiki/Modular_exponentiation#Right-to-left_binary_method + /// + /// - Complexity: O(exponent.count * modulus.count^log2(3)) or somesuch + public func power(_ exponent: BigInt, modulus: BigInt) -> BigInt { + precondition(!modulus.isZero) + if modulus.magnitude == 1 { return 0 } + if exponent.isZero { return 1 } + if exponent == 1 { return self.modulus(modulus) } + if exponent < 0 { + precondition(!self.isZero) + guard magnitude == 1 else { return 0 } + guard sign == .minus else { return 1 } + guard exponent.magnitude[0] & 1 != 0 else { return 1 } + return BigInt(modulus.magnitude - 1) + } + let power = self.magnitude.power(exponent.magnitude, + modulus: modulus.magnitude) + if self.sign == .plus || exponent.magnitude[0] & 1 == 0 || power.isZero { + return BigInt(power) + } + return BigInt(modulus.magnitude - power) + } +} diff --git a/Example/myWeb3Wallet/Pods/BigInt/Sources/Floating Point Conversion.swift b/Example/myWeb3Wallet/Pods/BigInt/Sources/Floating Point Conversion.swift new file mode 100644 index 000000000..6c2395a31 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/Sources/Floating Point Conversion.swift @@ -0,0 +1,73 @@ +// +// Floating Point Conversion.swift +// BigInt +// +// Created by Károly Lőrentey on 2017-08-11. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension BigUInt { + public init?(exactly source: T) { + guard source.isFinite else { return nil } + guard !source.isZero else { self = 0; return } + guard source.sign == .plus else { return nil } + let value = source.rounded(.towardZero) + guard value == source else { return nil } + assert(value.floatingPointClass == .positiveNormal) + assert(value.exponent >= 0) + let significand = value.significandBitPattern + self = (BigUInt(1) << value.exponent) + BigUInt(significand) >> (T.significandBitCount - Int(value.exponent)) + } + + public init(_ source: T) { + self.init(exactly: source.rounded(.towardZero))! + } +} + +extension BigInt { + public init?(exactly source: T) { + switch source.sign{ + case .plus: + guard let magnitude = BigUInt(exactly: source) else { return nil } + self = BigInt(sign: .plus, magnitude: magnitude) + case .minus: + guard let magnitude = BigUInt(exactly: -source) else { return nil } + self = BigInt(sign: .minus, magnitude: magnitude) + } + } + + public init(_ source: T) { + self.init(exactly: source.rounded(.towardZero))! + } +} + +extension BinaryFloatingPoint where RawExponent: FixedWidthInteger, RawSignificand: FixedWidthInteger { + public init(_ value: BigInt) { + guard !value.isZero else { self = 0; return } + let v = value.magnitude + let bitWidth = v.bitWidth + var exponent = bitWidth - 1 + let shift = bitWidth - Self.significandBitCount - 1 + var significand = value.magnitude >> (shift - 1) + if significand[0] & 3 == 3 { // Handle rounding + significand >>= 1 + significand += 1 + if significand.trailingZeroBitCount >= Self.significandBitCount { + exponent += 1 + } + } + else { + significand >>= 1 + } + let bias = 1 << (Self.exponentBitCount - 1) - 1 + guard exponent <= bias else { self = Self.infinity; return } + significand &= 1 << Self.significandBitCount - 1 + self = Self.init(sign: value.sign == .plus ? .plus : .minus, + exponentBitPattern: RawExponent(bias + exponent), + significandBitPattern: RawSignificand(significand)) + } + + public init(_ value: BigUInt) { + self.init(BigInt(sign: .plus, magnitude: value)) + } +} diff --git a/Example/myWeb3Wallet/Pods/BigInt/Sources/GCD.swift b/Example/myWeb3Wallet/Pods/BigInt/Sources/GCD.swift new file mode 100644 index 000000000..d55605dce --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/Sources/GCD.swift @@ -0,0 +1,80 @@ +// +// GCD.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension BigUInt { + //MARK: Greatest Common Divisor + + /// Returns the greatest common divisor of `self` and `b`. + /// + /// - Complexity: O(count^2) where count = max(self.count, b.count) + public func greatestCommonDivisor(with b: BigUInt) -> BigUInt { + // This is Stein's algorithm: https://en.wikipedia.org/wiki/Binary_GCD_algorithm + if self.isZero { return b } + if b.isZero { return self } + + let az = self.trailingZeroBitCount + let bz = b.trailingZeroBitCount + let twos = Swift.min(az, bz) + + var (x, y) = (self >> az, b >> bz) + if x < y { swap(&x, &y) } + + while !x.isZero { + x >>= x.trailingZeroBitCount + if x < y { swap(&x, &y) } + x -= y + } + return y << twos + } + + /// Returns the [multiplicative inverse of this integer in modulo `modulus` arithmetic][inverse], + /// or `nil` if there is no such number. + /// + /// [inverse]: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Modular_integers + /// + /// - Returns: If `gcd(self, modulus) == 1`, the value returned is an integer `a < modulus` such that `(a * self) % modulus == 1`. If `self` and `modulus` aren't coprime, the return value is `nil`. + /// - Requires: modulus > 1 + /// - Complexity: O(count^3) + public func inverse(_ modulus: BigUInt) -> BigUInt? { + precondition(modulus > 1) + var t1 = BigInt(0) + var t2 = BigInt(1) + var r1 = modulus + var r2 = self + while !r2.isZero { + let quotient = r1 / r2 + (t1, t2) = (t2, t1 - BigInt(quotient) * t2) + (r1, r2) = (r2, r1 - quotient * r2) + } + if r1 > 1 { return nil } + if t1.sign == .minus { return modulus - t1.magnitude } + return t1.magnitude + } +} + +extension BigInt { + /// Returns the greatest common divisor of `a` and `b`. + /// + /// - Complexity: O(count^2) where count = max(a.count, b.count) + public func greatestCommonDivisor(with b: BigInt) -> BigInt { + return BigInt(self.magnitude.greatestCommonDivisor(with: b.magnitude)) + } + + /// Returns the [multiplicative inverse of this integer in modulo `modulus` arithmetic][inverse], + /// or `nil` if there is no such number. + /// + /// [inverse]: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Modular_integers + /// + /// - Returns: If `gcd(self, modulus) == 1`, the value returned is an integer `a < modulus` such that `(a * self) % modulus == 1`. If `self` and `modulus` aren't coprime, the return value is `nil`. + /// - Requires: modulus.magnitude > 1 + /// - Complexity: O(count^3) + public func inverse(_ modulus: BigInt) -> BigInt? { + guard let inv = self.magnitude.inverse(modulus.magnitude) else { return nil } + return BigInt(self.sign == .plus || inv.isZero ? inv : modulus.magnitude - inv) + } +} diff --git a/Example/myWeb3Wallet/Pods/BigInt/Sources/Hashable.swift b/Example/myWeb3Wallet/Pods/BigInt/Sources/Hashable.swift new file mode 100644 index 000000000..c5dc0e642 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/Sources/Hashable.swift @@ -0,0 +1,26 @@ +// +// Hashable.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension BigUInt: Hashable { + //MARK: Hashing + + /// Append this `BigUInt` to the specified hasher. + public func hash(into hasher: inout Hasher) { + for word in self.words { + hasher.combine(word) + } + } +} + +extension BigInt: Hashable { + /// Append this `BigInt` to the specified hasher. + public func hash(into hasher: inout Hasher) { + hasher.combine(sign) + hasher.combine(magnitude) + } +} diff --git a/Example/myWeb3Wallet/Pods/BigInt/Sources/Integer Conversion.swift b/Example/myWeb3Wallet/Pods/BigInt/Sources/Integer Conversion.swift new file mode 100644 index 000000000..9a210e4a4 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/Sources/Integer Conversion.swift @@ -0,0 +1,89 @@ +// +// Integer Conversion.swift +// BigInt +// +// Created by Károly Lőrentey on 2017-08-11. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension BigUInt { + public init?(exactly source: T) { + guard source >= (0 as T) else { return nil } + if source.bitWidth <= 2 * Word.bitWidth { + var it = source.words.makeIterator() + self.init(low: it.next() ?? 0, high: it.next() ?? 0) + precondition(it.next() == nil, "Length of BinaryInteger.words is greater than its bitWidth") + } + else { + self.init(words: source.words) + } + } + + public init(_ source: T) { + precondition(source >= (0 as T), "BigUInt cannot represent negative values") + self.init(exactly: source)! + } + + public init(truncatingIfNeeded source: T) { + self.init(words: source.words) + } + + public init(clamping source: T) { + if source <= (0 as T) { + self.init() + } + else { + self.init(words: source.words) + } + } +} + +extension BigInt { + public init() { + self.init(sign: .plus, magnitude: 0) + } + + /// Initializes a new signed big integer with the same value as the specified unsigned big integer. + public init(_ integer: BigUInt) { + self.magnitude = integer + self.sign = .plus + } + + public init(_ source: T) where T : BinaryInteger { + if source >= (0 as T) { + self.init(sign: .plus, magnitude: BigUInt(source)) + } + else { + var words = Array(source.words) + words.twosComplement() + self.init(sign: .minus, magnitude: BigUInt(words: words)) + } + } + + public init?(exactly source: T) where T : BinaryInteger { + self.init(source) + } + + public init(clamping source: T) where T : BinaryInteger { + self.init(source) + } + + public init(truncatingIfNeeded source: T) where T : BinaryInteger { + self.init(source) + } +} + +extension BigUInt: ExpressibleByIntegerLiteral { + /// Initialize a new big integer from an integer literal. + public init(integerLiteral value: UInt64) { + self.init(value) + } +} + +extension BigInt: ExpressibleByIntegerLiteral { + /// Initialize a new big integer from an integer literal. + public init(integerLiteral value: Int64) { + self.init(value) + } +} + diff --git a/Example/myWeb3Wallet/Pods/BigInt/Sources/Multiplication.swift b/Example/myWeb3Wallet/Pods/BigInt/Sources/Multiplication.swift new file mode 100644 index 000000000..635c36a5f --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/Sources/Multiplication.swift @@ -0,0 +1,165 @@ +// +// Multiplication.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension BigUInt { + + //MARK: Multiplication + + /// Multiply this big integer by a single word, and store the result in place of the original big integer. + /// + /// - Complexity: O(count) + public mutating func multiply(byWord y: Word) { + guard y != 0 else { self = 0; return } + guard y != 1 else { return } + var carry: Word = 0 + let c = self.count + for i in 0 ..< c { + let (h, l) = self[i].multipliedFullWidth(by: y) + let (low, o) = l.addingReportingOverflow(carry) + self[i] = low + carry = (o ? h + 1 : h) + } + self[c] = carry + } + + /// Multiply this big integer by a single Word, and return the result. + /// + /// - Complexity: O(count) + public func multiplied(byWord y: Word) -> BigUInt { + var r = self + r.multiply(byWord: y) + return r + } + + /// Multiply `x` by `y`, and add the result to this integer, optionally shifted `shift` words to the left. + /// + /// - Note: This is the fused multiply/shift/add operation; it is more efficient than doing the components + /// individually. (The fused operation doesn't need to allocate space for temporary big integers.) + /// - Returns: `self` is set to `self + (x * y) << (shift * 2^Word.bitWidth)` + /// - Complexity: O(count) + public mutating func multiplyAndAdd(_ x: BigUInt, _ y: Word, shiftedBy shift: Int = 0) { + precondition(shift >= 0) + guard y != 0 && x.count > 0 else { return } + guard y != 1 else { self.add(x, shiftedBy: shift); return } + var mulCarry: Word = 0 + var addCarry = false + let xc = x.count + var xi = 0 + while xi < xc || addCarry || mulCarry > 0 { + let (h, l) = x[xi].multipliedFullWidth(by: y) + let (low, o) = l.addingReportingOverflow(mulCarry) + mulCarry = (o ? h + 1 : h) + + let ai = shift + xi + let (sum1, so1) = self[ai].addingReportingOverflow(low) + if addCarry { + let (sum2, so2) = sum1.addingReportingOverflow(1) + self[ai] = sum2 + addCarry = so1 || so2 + } + else { + self[ai] = sum1 + addCarry = so1 + } + xi += 1 + } + } + + /// Multiply this integer by `y` and return the result. + /// + /// - Note: This uses the naive O(n^2) multiplication algorithm unless both arguments have more than + /// `BigUInt.directMultiplicationLimit` words. + /// - Complexity: O(n^log2(3)) + public func multiplied(by y: BigUInt) -> BigUInt { + // This method is mostly defined for symmetry with the rest of the arithmetic operations. + return self * y + } + + /// Multiplication switches to an asymptotically better recursive algorithm when arguments have more words than this limit. + public static var directMultiplicationLimit: Int = 1024 + + /// Multiply `a` by `b` and return the result. + /// + /// - Note: This uses the naive O(n^2) multiplication algorithm unless both arguments have more than + /// `BigUInt.directMultiplicationLimit` words. + /// - Complexity: O(n^log2(3)) + public static func *(x: BigUInt, y: BigUInt) -> BigUInt { + let xc = x.count + let yc = y.count + if xc == 0 { return BigUInt() } + if yc == 0 { return BigUInt() } + if yc == 1 { return x.multiplied(byWord: y[0]) } + if xc == 1 { return y.multiplied(byWord: x[0]) } + + if Swift.min(xc, yc) <= BigUInt.directMultiplicationLimit { + // Long multiplication. + let left = (xc < yc ? y : x) + let right = (xc < yc ? x : y) + var result = BigUInt() + for i in (0 ..< right.count).reversed() { + result.multiplyAndAdd(left, right[i], shiftedBy: i) + } + return result + } + + if yc < xc { + let (xh, xl) = x.split + var r = xl * y + r.add(xh * y, shiftedBy: x.middleIndex) + return r + } + else if xc < yc { + let (yh, yl) = y.split + var r = yl * x + r.add(yh * x, shiftedBy: y.middleIndex) + return r + } + + let shift = x.middleIndex + + // Karatsuba multiplication: + // x * y = * = (ignoring carry) + let (a, b) = x.split + let (c, d) = y.split + + let high = a * c + let low = b * d + let xp = a >= b + let yp = c >= d + let xm = (xp ? a - b : b - a) + let ym = (yp ? c - d : d - c) + let m = xm * ym + + var r = low + r.add(high, shiftedBy: 2 * shift) + r.add(low, shiftedBy: shift) + r.add(high, shiftedBy: shift) + if xp == yp { + r.subtract(m, shiftedBy: shift) + } + else { + r.add(m, shiftedBy: shift) + } + return r + } + + /// Multiply `a` by `b` and store the result in `a`. + public static func *=(a: inout BigUInt, b: BigUInt) { + a = a * b + } +} + +extension BigInt { + /// Multiply `a` with `b` and return the result. + public static func *(a: BigInt, b: BigInt) -> BigInt { + return BigInt(sign: a.sign == b.sign ? .plus : .minus, magnitude: a.magnitude * b.magnitude) + } + + /// Multiply `a` with `b` in place. + public static func *=(a: inout BigInt, b: BigInt) { a = a * b } +} diff --git a/Example/myWeb3Wallet/Pods/BigInt/Sources/Prime Test.swift b/Example/myWeb3Wallet/Pods/BigInt/Sources/Prime Test.swift new file mode 100644 index 000000000..7f1871104 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/Sources/Prime Test.swift @@ -0,0 +1,153 @@ +// +// Prime Test.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-04. +// Copyright © 2016-2017 Károly Lőrentey. +// + +/// The first several [prime numbers][primes]. +/// +/// [primes]: https://oeis.org/A000040 +let primes: [BigUInt.Word] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41] + +/// The ith element in this sequence is the smallest composite number that passes the strong probable prime test +/// for all of the first (i+1) primes. +/// +/// This is sequence [A014233](http://oeis.org/A014233) on the [Online Encyclopaedia of Integer Sequences](http://oeis.org). +let pseudoPrimes: [BigUInt] = [ + /* 2 */ 2_047, + /* 3 */ 1_373_653, + /* 5 */ 25_326_001, + /* 7 */ 3_215_031_751, + /* 11 */ 2_152_302_898_747, + /* 13 */ 3_474_749_660_383, + /* 17 */ 341_550_071_728_321, + /* 19 */ 341_550_071_728_321, + /* 23 */ 3_825_123_056_546_413_051, + /* 29 */ 3_825_123_056_546_413_051, + /* 31 */ 3_825_123_056_546_413_051, + /* 37 */ "318665857834031151167461", + /* 41 */ "3317044064679887385961981", +] + +extension BigUInt { + //MARK: Primality Testing + + /// Returns true iff this integer passes the [strong probable prime test][sppt] for the specified base. + /// + /// [sppt]: https://en.wikipedia.org/wiki/Probable_prime + public func isStrongProbablePrime(_ base: BigUInt) -> Bool { + precondition(base > (1 as BigUInt)) + precondition(self > (0 as BigUInt)) + let dec = self - 1 + + let r = dec.trailingZeroBitCount + let d = dec >> r + + var test = base.power(d, modulus: self) + if test == 1 || test == dec { return true } + + if r > 0 { + let shift = self.leadingZeroBitCount + let normalized = self << shift + for _ in 1 ..< r { + test *= test + test.formRemainder(dividingBy: normalized, normalizedBy: shift) + if test == 1 { + return false + } + if test == dec { return true } + } + } + return false + } + + /// Returns true if this integer is probably prime. Returns false if this integer is definitely not prime. + /// + /// This function performs a probabilistic [Miller-Rabin Primality Test][mrpt], consisting of `rounds` iterations, + /// each calculating the strong probable prime test for a random base. The number of rounds is 10 by default, + /// but you may specify your own choice. + /// + /// To speed things up, the function checks if `self` is divisible by the first few prime numbers before + /// diving into (slower) Miller-Rabin testing. + /// + /// Also, when `self` is less than 82 bits wide, `isPrime` does a deterministic test that is guaranteed to + /// return a correct result. + /// + /// [mrpt]: https://en.wikipedia.org/wiki/Miller–Rabin_primality_test + public func isPrime(rounds: Int = 10) -> Bool { + if count <= 1 && self[0] < 2 { return false } + if count == 1 && self[0] < 4 { return true } + + // Even numbers above 2 aren't prime. + if self[0] & 1 == 0 { return false } + + // Quickly check for small primes. + for i in 1 ..< primes.count { + let p = primes[i] + if self.count == 1 && self[0] == p { + return true + } + if self.quotientAndRemainder(dividingByWord: p).remainder == 0 { + return false + } + } + + /// Give an exact answer when we can. + if self < pseudoPrimes.last! { + for i in 0 ..< pseudoPrimes.count { + guard isStrongProbablePrime(BigUInt(primes[i])) else { + break + } + if self < pseudoPrimes[i] { + // `self` is below the lowest pseudoprime corresponding to the prime bases we tested. It's a prime! + return true + } + } + return false + } + + /// Otherwise do as many rounds of random SPPT as required. + for _ in 0 ..< rounds { + let random = BigUInt.randomInteger(lessThan: self - 2) + 2 + guard isStrongProbablePrime(random) else { + return false + } + } + + // Well, it smells primey to me. + return true + } +} + +extension BigInt { + //MARK: Primality Testing + + /// Returns true iff this integer passes the [strong probable prime test][sppt] for the specified base. + /// + /// [sppt]: https://en.wikipedia.org/wiki/Probable_prime + public func isStrongProbablePrime(_ base: BigInt) -> Bool { + precondition(base.sign == .plus) + if self.sign == .minus { return false } + return self.magnitude.isStrongProbablePrime(base.magnitude) + } + + /// Returns true if this integer is probably prime. Returns false if this integer is definitely not prime. + /// + /// This function performs a probabilistic [Miller-Rabin Primality Test][mrpt], consisting of `rounds` iterations, + /// each calculating the strong probable prime test for a random base. The number of rounds is 10 by default, + /// but you may specify your own choice. + /// + /// To speed things up, the function checks if `self` is divisible by the first few prime numbers before + /// diving into (slower) Miller-Rabin testing. + /// + /// Also, when `self` is less than 82 bits wide, `isPrime` does a deterministic test that is guaranteed to + /// return a correct result. + /// + /// [mrpt]: https://en.wikipedia.org/wiki/Miller–Rabin_primality_test + public func isPrime(rounds: Int = 10) -> Bool { + if self.sign == .minus { return false } + return self.magnitude.isPrime(rounds: rounds) + } +} diff --git a/Example/myWeb3Wallet/Pods/BigInt/Sources/Random.swift b/Example/myWeb3Wallet/Pods/BigInt/Sources/Random.swift new file mode 100644 index 000000000..bea98caf0 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/Sources/Random.swift @@ -0,0 +1,101 @@ +// +// Random.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-04. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension BigUInt { + /// Create a big unsigned integer consisting of `width` uniformly distributed random bits. + /// + /// - Parameter width: The maximum number of one bits in the result. + /// - Parameter generator: The source of randomness. + /// - Returns: A big unsigned integer less than `1 << width`. + public static func randomInteger(withMaximumWidth width: Int, using generator: inout RNG) -> BigUInt { + var result = BigUInt.zero + var bitsLeft = width + var i = 0 + let wordsNeeded = (width + Word.bitWidth - 1) / Word.bitWidth + if wordsNeeded > 2 { + result.reserveCapacity(wordsNeeded) + } + while bitsLeft >= Word.bitWidth { + result[i] = generator.next() + i += 1 + bitsLeft -= Word.bitWidth + } + if bitsLeft > 0 { + let mask: Word = (1 << bitsLeft) - 1 + result[i] = (generator.next() as Word) & mask + } + return result + } + + /// Create a big unsigned integer consisting of `width` uniformly distributed random bits. + /// + /// - Note: I use a `SystemRandomGeneratorGenerator` as the source of randomness. + /// + /// - Parameter width: The maximum number of one bits in the result. + /// - Returns: A big unsigned integer less than `1 << width`. + public static func randomInteger(withMaximumWidth width: Int) -> BigUInt { + var rng = SystemRandomNumberGenerator() + return randomInteger(withMaximumWidth: width, using: &rng) + } + + /// Create a big unsigned integer consisting of `width-1` uniformly distributed random bits followed by a one bit. + /// + /// - Note: If `width` is zero, the result is zero. + /// + /// - Parameter width: The number of bits required to represent the answer. + /// - Parameter generator: The source of randomness. + /// - Returns: A random big unsigned integer whose width is `width`. + public static func randomInteger(withExactWidth width: Int, using generator: inout RNG) -> BigUInt { + // width == 0 -> return 0 because there is no room for a one bit. + // width == 1 -> return 1 because there is no room for any random bits. + guard width > 1 else { return BigUInt(width) } + var result = randomInteger(withMaximumWidth: width - 1, using: &generator) + result[(width - 1) / Word.bitWidth] |= 1 << Word((width - 1) % Word.bitWidth) + return result + } + + /// Create a big unsigned integer consisting of `width-1` uniformly distributed random bits followed by a one bit. + /// + /// - Note: If `width` is zero, the result is zero. + /// - Note: I use a `SystemRandomGeneratorGenerator` as the source of randomness. + /// + /// - Returns: A random big unsigned integer whose width is `width`. + public static func randomInteger(withExactWidth width: Int) -> BigUInt { + var rng = SystemRandomNumberGenerator() + return randomInteger(withExactWidth: width, using: &rng) + } + + /// Create a uniformly distributed random unsigned integer that's less than the specified limit. + /// + /// - Precondition: `limit > 0`. + /// + /// - Parameter limit: The upper bound on the result. + /// - Parameter generator: The source of randomness. + /// - Returns: A random big unsigned integer that is less than `limit`. + public static func randomInteger(lessThan limit: BigUInt, using generator: inout RNG) -> BigUInt { + precondition(limit > 0, "\(#function): 0 is not a valid limit") + let width = limit.bitWidth + var random = randomInteger(withMaximumWidth: width, using: &generator) + while random >= limit { + random = randomInteger(withMaximumWidth: width, using: &generator) + } + return random + } + + /// Create a uniformly distributed random unsigned integer that's less than the specified limit. + /// + /// - Precondition: `limit > 0`. + /// - Note: I use a `SystemRandomGeneratorGenerator` as the source of randomness. + /// + /// - Parameter limit: The upper bound on the result. + /// - Returns: A random big unsigned integer that is less than `limit`. + public static func randomInteger(lessThan limit: BigUInt) -> BigUInt { + var rng = SystemRandomNumberGenerator() + return randomInteger(lessThan: limit, using: &rng) + } +} diff --git a/Example/myWeb3Wallet/Pods/BigInt/Sources/Shifts.swift b/Example/myWeb3Wallet/Pods/BigInt/Sources/Shifts.swift new file mode 100644 index 000000000..e676e4143 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/Sources/Shifts.swift @@ -0,0 +1,211 @@ +// +// Shifts.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension BigUInt { + + //MARK: Shift Operators + + internal func shiftedLeft(by amount: Word) -> BigUInt { + guard amount > 0 else { return self } + + let ext = Int(amount / Word(Word.bitWidth)) // External shift amount (new words) + let up = Word(amount % Word(Word.bitWidth)) // Internal shift amount (subword shift) + let down = Word(Word.bitWidth) - up + + var result = BigUInt() + if up > 0 { + var i = 0 + var lowbits: Word = 0 + while i < self.count || lowbits > 0 { + let word = self[i] + result[i + ext] = word << up | lowbits + lowbits = word >> down + i += 1 + } + } + else { + for i in 0 ..< self.count { + result[i + ext] = self[i] + } + } + return result + } + + internal mutating func shiftLeft(by amount: Word) { + guard amount > 0 else { return } + + let ext = Int(amount / Word(Word.bitWidth)) // External shift amount (new words) + let up = Word(amount % Word(Word.bitWidth)) // Internal shift amount (subword shift) + let down = Word(Word.bitWidth) - up + + if up > 0 { + var i = 0 + var lowbits: Word = 0 + while i < self.count || lowbits > 0 { + let word = self[i] + self[i] = word << up | lowbits + lowbits = word >> down + i += 1 + } + } + if ext > 0 && self.count > 0 { + self.shiftLeft(byWords: ext) + } + } + + internal func shiftedRight(by amount: Word) -> BigUInt { + guard amount > 0 else { return self } + guard amount < self.bitWidth else { return 0 } + + let ext = Int(amount / Word(Word.bitWidth)) // External shift amount (new words) + let down = Word(amount % Word(Word.bitWidth)) // Internal shift amount (subword shift) + let up = Word(Word.bitWidth) - down + + var result = BigUInt() + if down > 0 { + var highbits: Word = 0 + for i in (ext ..< self.count).reversed() { + let word = self[i] + result[i - ext] = highbits | word >> down + highbits = word << up + } + } + else { + for i in (ext ..< self.count).reversed() { + result[i - ext] = self[i] + } + } + return result + } + + internal mutating func shiftRight(by amount: Word) { + guard amount > 0 else { return } + guard amount < self.bitWidth else { self.clear(); return } + + let ext = Int(amount / Word(Word.bitWidth)) // External shift amount (new words) + let down = Word(amount % Word(Word.bitWidth)) // Internal shift amount (subword shift) + let up = Word(Word.bitWidth) - down + + if ext > 0 { + self.shiftRight(byWords: ext) + } + if down > 0 { + var i = self.count - 1 + var highbits: Word = 0 + while i >= 0 { + let word = self[i] + self[i] = highbits | word >> down + highbits = word << up + i -= 1 + } + } + } + + public static func >>=(lhs: inout BigUInt, rhs: Other) { + if rhs < (0 as Other) { + lhs <<= (0 - rhs) + } + else if rhs >= lhs.bitWidth { + lhs.clear() + } + else { + lhs.shiftRight(by: UInt(rhs)) + } + } + + public static func <<=(lhs: inout BigUInt, rhs: Other) { + if rhs < (0 as Other) { + lhs >>= (0 - rhs) + return + } + lhs.shiftLeft(by: Word(exactly: rhs)!) + } + + public static func >>(lhs: BigUInt, rhs: Other) -> BigUInt { + if rhs < (0 as Other) { + return lhs << (0 - rhs) + } + if rhs > Word.max { + return 0 + } + return lhs.shiftedRight(by: UInt(rhs)) + } + + public static func <<(lhs: BigUInt, rhs: Other) -> BigUInt { + if rhs < (0 as Other) { + return lhs >> (0 - rhs) + } + return lhs.shiftedLeft(by: Word(exactly: rhs)!) + } +} + +extension BigInt { + func shiftedLeft(by amount: Word) -> BigInt { + return BigInt(sign: self.sign, magnitude: self.magnitude.shiftedLeft(by: amount)) + } + + mutating func shiftLeft(by amount: Word) { + self.magnitude.shiftLeft(by: amount) + } + + func shiftedRight(by amount: Word) -> BigInt { + let m = self.magnitude.shiftedRight(by: amount) + return BigInt(sign: self.sign, magnitude: self.sign == .minus && m.isZero ? 1 : m) + } + + mutating func shiftRight(by amount: Word) { + magnitude.shiftRight(by: amount) + if sign == .minus, magnitude.isZero { + magnitude.load(1) + } + } + + public static func &<<(left: BigInt, right: BigInt) -> BigInt { + return left.shiftedLeft(by: right.words[0]) + } + + public static func &<<=(left: inout BigInt, right: BigInt) { + left.shiftLeft(by: right.words[0]) + } + + public static func &>>(left: BigInt, right: BigInt) -> BigInt { + return left.shiftedRight(by: right.words[0]) + } + + public static func &>>=(left: inout BigInt, right: BigInt) { + left.shiftRight(by: right.words[0]) + } + + public static func <<(lhs: BigInt, rhs: Other) -> BigInt { + guard rhs >= (0 as Other) else { return lhs >> (0 - rhs) } + return lhs.shiftedLeft(by: Word(rhs)) + } + + public static func <<=(lhs: inout BigInt, rhs: Other) { + if rhs < (0 as Other) { + lhs >>= (0 - rhs) + } + else { + lhs.shiftLeft(by: Word(rhs)) + } + } + + public static func >>(lhs: BigInt, rhs: Other) -> BigInt { + guard rhs >= (0 as Other) else { return lhs << (0 - rhs) } + return lhs.shiftedRight(by: Word(rhs)) + } + + public static func >>=(lhs: inout BigInt, rhs: Other) { + if rhs < (0 as Other) { + lhs <<= (0 - rhs) + } + else { + lhs.shiftRight(by: Word(rhs)) + } + } +} diff --git a/Example/myWeb3Wallet/Pods/BigInt/Sources/Square Root.swift b/Example/myWeb3Wallet/Pods/BigInt/Sources/Square Root.swift new file mode 100644 index 000000000..68db0691c --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/Sources/Square Root.swift @@ -0,0 +1,41 @@ +// +// Square Root.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +//MARK: Square Root + +extension BigUInt { + /// Returns the integer square root of a big integer; i.e., the largest integer whose square isn't greater than `value`. + /// + /// - Returns: floor(sqrt(self)) + public func squareRoot() -> BigUInt { + // This implementation uses Newton's method. + guard !self.isZero else { return BigUInt() } + var x = BigUInt(1) << ((self.bitWidth + 1) / 2) + var y: BigUInt = 0 + while true { + y.load(self) + y /= x + y += x + y >>= 1 + if x == y || x == y - 1 { break } + x = y + } + return x + } +} + +extension BigInt { + /// Returns the integer square root of a big integer; i.e., the largest integer whose square isn't greater than `value`. + /// + /// - Requires: self >= 0 + /// - Returns: floor(sqrt(self)) + public func squareRoot() -> BigInt { + precondition(self.sign == .plus) + return BigInt(sign: .plus, magnitude: self.magnitude.squareRoot()) + } +} diff --git a/Example/myWeb3Wallet/Pods/BigInt/Sources/Strideable.swift b/Example/myWeb3Wallet/Pods/BigInt/Sources/Strideable.swift new file mode 100644 index 000000000..2b79babd1 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/Sources/Strideable.swift @@ -0,0 +1,38 @@ +// +// Strideable.swift +// BigInt +// +// Created by Károly Lőrentey on 2017-08-11. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension BigUInt: Strideable { + /// A type that can represent the distance between two values ofa `BigUInt`. + public typealias Stride = BigInt + + /// Adds `n` to `self` and returns the result. Traps if the result would be less than zero. + public func advanced(by n: BigInt) -> BigUInt { + return n.sign == .minus ? self - n.magnitude : self + n.magnitude + } + + /// Returns the (potentially negative) difference between `self` and `other` as a `BigInt`. Never traps. + public func distance(to other: BigUInt) -> BigInt { + return BigInt(other) - BigInt(self) + } +} + +extension BigInt: Strideable { + public typealias Stride = BigInt + + /// Returns `self + n`. + public func advanced(by n: Stride) -> BigInt { + return self + n + } + + /// Returns `other - self`. + public func distance(to other: BigInt) -> Stride { + return other - self + } +} + + diff --git a/Example/myWeb3Wallet/Pods/BigInt/Sources/String Conversion.swift b/Example/myWeb3Wallet/Pods/BigInt/Sources/String Conversion.swift new file mode 100644 index 000000000..d6f340c93 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/Sources/String Conversion.swift @@ -0,0 +1,236 @@ +// +// String Conversion.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension BigUInt { + + //MARK: String Conversion + + /// Calculates the number of numerals in a given radix that fit inside a single `Word`. + /// + /// - Returns: (chars, power) where `chars` is highest that satisfy `radix^chars <= 2^Word.bitWidth`. `power` is zero + /// if radix is a power of two; otherwise `power == radix^chars`. + fileprivate static func charsPerWord(forRadix radix: Int) -> (chars: Int, power: Word) { + var power: Word = 1 + var overflow = false + var count = 0 + while !overflow { + let (p, o) = power.multipliedReportingOverflow(by: Word(radix)) + overflow = o + if !o || p == 0 { + count += 1 + power = p + } + } + return (count, power) + } + + /// Initialize a big integer from an ASCII representation in a given radix. Numerals above `9` are represented by + /// letters from the English alphabet. + /// + /// - Requires: `radix > 1 && radix < 36` + /// - Parameter `text`: A string consisting of characters corresponding to numerals in the given radix. (0-9, a-z, A-Z) + /// - Parameter `radix`: The base of the number system to use, or 10 if unspecified. + /// - Returns: The integer represented by `text`, or nil if `text` contains a character that does not represent a numeral in `radix`. + public init?(_ text: S, radix: Int = 10) { + precondition(radix > 1) + let (charsPerWord, power) = BigUInt.charsPerWord(forRadix: radix) + + var words: [Word] = [] + var end = text.endIndex + var start = end + var count = 0 + while start != text.startIndex { + start = text.index(before: start) + count += 1 + if count == charsPerWord { + guard let d = Word.init(text[start ..< end], radix: radix) else { return nil } + words.append(d) + end = start + count = 0 + } + } + if start != end { + guard let d = Word.init(text[start ..< end], radix: radix) else { return nil } + words.append(d) + } + + if power == 0 { + self.init(words: words) + } + else { + self.init() + for d in words.reversed() { + self.multiply(byWord: power) + self.addWord(d) + } + } + } +} + +extension BigInt { + /// Initialize a big integer from an ASCII representation in a given radix. Numerals above `9` are represented by + /// letters from the English alphabet. + /// + /// - Requires: `radix > 1 && radix < 36` + /// - Parameter `text`: A string optionally starting with "-" or "+" followed by characters corresponding to numerals in the given radix. (0-9, a-z, A-Z) + /// - Parameter `radix`: The base of the number system to use, or 10 if unspecified. + /// - Returns: The integer represented by `text`, or nil if `text` contains a character that does not represent a numeral in `radix`. + public init?(_ text: S, radix: Int = 10) { + var magnitude: BigUInt? + var sign: Sign = .plus + if text.first == "-" { + sign = .minus + let text = text.dropFirst() + magnitude = BigUInt(text, radix: radix) + } + else if text.first == "+" { + let text = text.dropFirst() + magnitude = BigUInt(text, radix: radix) + } + else { + magnitude = BigUInt(text, radix: radix) + } + guard let m = magnitude else { return nil } + self.magnitude = m + self.sign = sign + } +} + +extension String { + /// Initialize a new string with the base-10 representation of an unsigned big integer. + /// + /// - Complexity: O(v.count^2) + public init(_ v: BigUInt) { self.init(v, radix: 10, uppercase: false) } + + /// Initialize a new string representing an unsigned big integer in the given radix (base). + /// + /// Numerals greater than 9 are represented as letters from the English alphabet, + /// starting with `a` if `uppercase` is false or `A` otherwise. + /// + /// - Requires: radix > 1 && radix <= 36 + /// - Complexity: O(count) when radix is a power of two; otherwise O(count^2). + public init(_ v: BigUInt, radix: Int, uppercase: Bool = false) { + precondition(radix > 1) + let (charsPerWord, power) = BigUInt.charsPerWord(forRadix: radix) + + guard !v.isZero else { self = "0"; return } + + var parts: [String] + if power == 0 { + parts = v.words.map { String($0, radix: radix, uppercase: uppercase) } + } + else { + parts = [] + var rest = v + while !rest.isZero { + let mod = rest.divide(byWord: power) + parts.append(String(mod, radix: radix, uppercase: uppercase)) + } + } + assert(!parts.isEmpty) + + self = "" + var first = true + for part in parts.reversed() { + let zeroes = charsPerWord - part.count + assert(zeroes >= 0) + if !first && zeroes > 0 { + // Insert leading zeroes for mid-Words + self += String(repeating: "0", count: zeroes) + } + first = false + self += part + } + } + + /// Initialize a new string representing a signed big integer in the given radix (base). + /// + /// Numerals greater than 9 are represented as letters from the English alphabet, + /// starting with `a` if `uppercase` is false or `A` otherwise. + /// + /// - Requires: radix > 1 && radix <= 36 + /// - Complexity: O(count) when radix is a power of two; otherwise O(count^2). + public init(_ value: BigInt, radix: Int = 10, uppercase: Bool = false) { + self = String(value.magnitude, radix: radix, uppercase: uppercase) + if value.sign == .minus { + self = "-" + self + } + } +} + +extension BigUInt: ExpressibleByStringLiteral { + /// Initialize a new big integer from a Unicode scalar. + /// The scalar must represent a decimal digit. + public init(unicodeScalarLiteral value: UnicodeScalar) { + self = BigUInt(String(value), radix: 10)! + } + + /// Initialize a new big integer from an extended grapheme cluster. + /// The cluster must consist of a decimal digit. + public init(extendedGraphemeClusterLiteral value: String) { + self = BigUInt(value, radix: 10)! + } + + /// Initialize a new big integer from a decimal number represented by a string literal of arbitrary length. + /// The string must contain only decimal digits. + public init(stringLiteral value: StringLiteralType) { + self = BigUInt(value, radix: 10)! + } +} + +extension BigInt: ExpressibleByStringLiteral { + /// Initialize a new big integer from a Unicode scalar. + /// The scalar must represent a decimal digit. + public init(unicodeScalarLiteral value: UnicodeScalar) { + self = BigInt(String(value), radix: 10)! + } + + /// Initialize a new big integer from an extended grapheme cluster. + /// The cluster must consist of a decimal digit. + public init(extendedGraphemeClusterLiteral value: String) { + self = BigInt(value, radix: 10)! + } + + /// Initialize a new big integer from a decimal number represented by a string literal of arbitrary length. + /// The string must contain only decimal digits. + public init(stringLiteral value: StringLiteralType) { + self = BigInt(value, radix: 10)! + } +} + +extension BigUInt: CustomStringConvertible { + /// Return the decimal representation of this integer. + public var description: String { + return String(self, radix: 10) + } +} + +extension BigInt: CustomStringConvertible { + /// Return the decimal representation of this integer. + public var description: String { + return String(self, radix: 10) + } +} + +extension BigUInt: CustomPlaygroundDisplayConvertible { + + /// Return the playground quick look representation of this integer. + public var playgroundDescription: Any { + let text = String(self) + return text + " (\(self.bitWidth) bits)" + } +} + +extension BigInt: CustomPlaygroundDisplayConvertible { + + /// Return the playground quick look representation of this integer. + public var playgroundDescription: Any { + let text = String(self) + return text + " (\(self.magnitude.bitWidth) bits)" + } +} diff --git a/Example/myWeb3Wallet/Pods/BigInt/Sources/Subtraction.swift b/Example/myWeb3Wallet/Pods/BigInt/Sources/Subtraction.swift new file mode 100644 index 000000000..5ac872e65 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/Sources/Subtraction.swift @@ -0,0 +1,169 @@ +// +// Subtraction.swift +// BigInt +// +// Created by Károly Lőrentey on 2016-01-03. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension BigUInt { + //MARK: Subtraction + + /// Subtract `word` from this integer in place, returning a flag indicating if the operation + /// caused an arithmetic overflow. `word` is shifted `shift` words to the left before being subtracted. + /// + /// - Note: If the result indicates an overflow, then `self` becomes the two's complement of the absolute difference. + /// - Complexity: O(count) + internal mutating func subtractWordReportingOverflow(_ word: Word, shiftedBy shift: Int = 0) -> Bool { + precondition(shift >= 0) + var carry: Word = word + var i = shift + let count = self.count + while carry > 0 && i < count { + let (d, c) = self[i].subtractingReportingOverflow(carry) + self[i] = d + carry = (c ? 1 : 0) + i += 1 + } + return carry > 0 + } + + /// Subtract `word` from this integer, returning the difference and a flag that is true if the operation + /// caused an arithmetic overflow. `word` is shifted `shift` words to the left before being subtracted. + /// + /// - Note: If `overflow` is true, then the returned value is the two's complement of the absolute difference. + /// - Complexity: O(count) + internal func subtractingWordReportingOverflow(_ word: Word, shiftedBy shift: Int = 0) -> (partialValue: BigUInt, overflow: Bool) { + var result = self + let overflow = result.subtractWordReportingOverflow(word, shiftedBy: shift) + return (result, overflow) + } + + /// Subtract a digit `d` from this integer in place. + /// `d` is shifted `shift` digits to the left before being subtracted. + /// + /// - Requires: self >= d * 2^shift + /// - Complexity: O(count) + internal mutating func subtractWord(_ word: Word, shiftedBy shift: Int = 0) { + let overflow = subtractWordReportingOverflow(word, shiftedBy: shift) + precondition(!overflow) + } + + /// Subtract a digit `d` from this integer and return the result. + /// `d` is shifted `shift` digits to the left before being subtracted. + /// + /// - Requires: self >= d * 2^shift + /// - Complexity: O(count) + internal func subtractingWord(_ word: Word, shiftedBy shift: Int = 0) -> BigUInt { + var result = self + result.subtractWord(word, shiftedBy: shift) + return result + } + + /// Subtract `other` from this integer in place, and return a flag indicating if the operation caused an + /// arithmetic overflow. `other` is shifted `shift` digits to the left before being subtracted. + /// + /// - Note: If the result indicates an overflow, then `self` becomes the twos' complement of the absolute difference. + /// - Complexity: O(count) + public mutating func subtractReportingOverflow(_ b: BigUInt, shiftedBy shift: Int = 0) -> Bool { + precondition(shift >= 0) + var carry = false + var bi = 0 + let bc = b.count + let count = self.count + while bi < bc || (shift + bi < count && carry) { + let ai = shift + bi + let (d, c) = self[ai].subtractingReportingOverflow(b[bi]) + if carry { + let (d2, c2) = d.subtractingReportingOverflow(1) + self[ai] = d2 + carry = c || c2 + } + else { + self[ai] = d + carry = c + } + bi += 1 + } + return carry + } + + /// Subtract `other` from this integer, returning the difference and a flag indicating arithmetic overflow. + /// `other` is shifted `shift` digits to the left before being subtracted. + /// + /// - Note: If `overflow` is true, then the result value is the twos' complement of the absolute value of the difference. + /// - Complexity: O(count) + public func subtractingReportingOverflow(_ other: BigUInt, shiftedBy shift: Int) -> (partialValue: BigUInt, overflow: Bool) { + var result = self + let overflow = result.subtractReportingOverflow(other, shiftedBy: shift) + return (result, overflow) + } + + /// Subtracts `other` from `self`, returning the result and a flag indicating arithmetic overflow. + /// + /// - Note: When the operation overflows, then `partialValue` is the twos' complement of the absolute value of the difference. + /// - Complexity: O(count) + public func subtractingReportingOverflow(_ other: BigUInt) -> (partialValue: BigUInt, overflow: Bool) { + return self.subtractingReportingOverflow(other, shiftedBy: 0) + } + + /// Subtract `other` from this integer in place. + /// `other` is shifted `shift` digits to the left before being subtracted. + /// + /// - Requires: self >= other * 2^shift + /// - Complexity: O(count) + public mutating func subtract(_ other: BigUInt, shiftedBy shift: Int = 0) { + let overflow = subtractReportingOverflow(other, shiftedBy: shift) + precondition(!overflow) + } + + /// Subtract `b` from this integer, and return the difference. + /// `b` is shifted `shift` digits to the left before being subtracted. + /// + /// - Requires: self >= b * 2^shift + /// - Complexity: O(count) + public func subtracting(_ other: BigUInt, shiftedBy shift: Int = 0) -> BigUInt { + var result = self + result.subtract(other, shiftedBy: shift) + return result + } + + /// Decrement this integer by one. + /// + /// - Requires: !isZero + /// - Complexity: O(count) + public mutating func decrement(shiftedBy shift: Int = 0) { + self.subtract(1, shiftedBy: shift) + } + + /// Subtract `b` from `a` and return the result. + /// + /// - Requires: a >= b + /// - Complexity: O(a.count) + public static func -(a: BigUInt, b: BigUInt) -> BigUInt { + return a.subtracting(b) + } + + /// Subtract `b` from `a` and store the result in `a`. + /// + /// - Requires: a >= b + /// - Complexity: O(a.count) + public static func -=(a: inout BigUInt, b: BigUInt) { + a.subtract(b) + } +} + +extension BigInt { + public mutating func negate() { + guard !magnitude.isZero else { return } + self.sign = self.sign == .plus ? .minus : .plus + } + + /// Subtract `b` from `a` and return the result. + public static func -(a: BigInt, b: BigInt) -> BigInt { + return a + -b + } + + /// Subtract `b` from `a` in place. + public static func -=(a: inout BigInt, b: BigInt) { a = a - b } +} diff --git a/Example/myWeb3Wallet/Pods/BigInt/Sources/Words and Bits.swift b/Example/myWeb3Wallet/Pods/BigInt/Sources/Words and Bits.swift new file mode 100644 index 000000000..4543c1bc8 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/BigInt/Sources/Words and Bits.swift @@ -0,0 +1,202 @@ +// +// Words and Bits.swift +// BigInt +// +// Created by Károly Lőrentey on 2017-08-11. +// Copyright © 2016-2017 Károly Lőrentey. +// + +extension Array where Element == UInt { + mutating func twosComplement() { + var increment = true + for i in 0 ..< self.count { + if increment { + (self[i], increment) = (~self[i]).addingReportingOverflow(1) + } + else { + self[i] = ~self[i] + } + } + } +} + +extension BigUInt { + public subscript(bitAt index: Int) -> Bool { + get { + precondition(index >= 0) + let (i, j) = index.quotientAndRemainder(dividingBy: Word.bitWidth) + return self[i] & (1 << j) != 0 + } + set { + precondition(index >= 0) + let (i, j) = index.quotientAndRemainder(dividingBy: Word.bitWidth) + if newValue { + self[i] |= 1 << j + } + else { + self[i] &= ~(1 << j) + } + } + } +} + +extension BigUInt { + /// The minimum number of bits required to represent this integer in binary. + /// + /// - Returns: floor(log2(2 * self + 1)) + /// - Complexity: O(1) + public var bitWidth: Int { + guard count > 0 else { return 0 } + return count * Word.bitWidth - self[count - 1].leadingZeroBitCount + } + + /// The number of leading zero bits in the binary representation of this integer in base `2^(Word.bitWidth)`. + /// This is useful when you need to normalize a `BigUInt` such that the top bit of its most significant word is 1. + /// + /// - Note: 0 is considered to have zero leading zero bits. + /// - Returns: A value in `0...(Word.bitWidth - 1)`. + /// - SeeAlso: width + /// - Complexity: O(1) + public var leadingZeroBitCount: Int { + guard count > 0 else { return 0 } + return self[count - 1].leadingZeroBitCount + } + + /// The number of trailing zero bits in the binary representation of this integer. + /// + /// - Note: 0 is considered to have zero trailing zero bits. + /// - Returns: A value in `0...width`. + /// - Complexity: O(count) + public var trailingZeroBitCount: Int { + guard count > 0 else { return 0 } + let i = self.words.firstIndex { $0 != 0 }! + return i * Word.bitWidth + self[i].trailingZeroBitCount + } +} + +extension BigInt { + public var bitWidth: Int { + guard !magnitude.isZero else { return 0 } + return magnitude.bitWidth + 1 + } + + public var trailingZeroBitCount: Int { + // Amazingly, this works fine for negative numbers + return magnitude.trailingZeroBitCount + } +} + +extension BigUInt { + public struct Words: RandomAccessCollection { + private let value: BigUInt + + fileprivate init(_ value: BigUInt) { self.value = value } + + public var startIndex: Int { return 0 } + public var endIndex: Int { return value.count } + + public subscript(_ index: Int) -> Word { + return value[index] + } + } + + public var words: Words { return Words(self) } + + public init(words: Words) where Words.Element == Word { + let uc = words.underestimatedCount + if uc > 2 { + self.init(words: Array(words)) + } + else { + var it = words.makeIterator() + guard let w0 = it.next() else { + self.init() + return + } + guard let w1 = it.next() else { + self.init(word: w0) + return + } + if let w2 = it.next() { + var words: [UInt] = [] + words.reserveCapacity(Swift.max(3, uc)) + words.append(w0) + words.append(w1) + words.append(w2) + while let word = it.next() { + words.append(word) + } + self.init(words: words) + } + else { + self.init(low: w0, high: w1) + } + } + } +} + +extension BigInt { + public struct Words: RandomAccessCollection { + public typealias Indices = CountableRange + + private let value: BigInt + private let decrementLimit: Int + + fileprivate init(_ value: BigInt) { + self.value = value + switch value.sign { + case .plus: + self.decrementLimit = 0 + case .minus: + assert(!value.magnitude.isZero) + self.decrementLimit = value.magnitude.words.firstIndex(where: { $0 != 0 })! + } + } + + public var count: Int { + switch value.sign { + case .plus: + if let high = value.magnitude.words.last, high >> (Word.bitWidth - 1) != 0 { + return value.magnitude.count + 1 + } + return value.magnitude.count + case .minus: + let high = value.magnitude.words.last! + if high >> (Word.bitWidth - 1) != 0 { + return value.magnitude.count + 1 + } + return value.magnitude.count + } + } + + public var indices: Indices { return 0 ..< count } + public var startIndex: Int { return 0 } + public var endIndex: Int { return count } + + public subscript(_ index: Int) -> UInt { + // Note that indices above `endIndex` are accepted. + if value.sign == .plus { + return value.magnitude[index] + } + if index <= decrementLimit { + return ~(value.magnitude[index] &- 1) + } + return ~value.magnitude[index] + } + } + + public var words: Words { + return Words(self) + } + + public init(words: S) where S.Element == Word { + var words = Array(words) + if (words.last ?? 0) >> (Word.bitWidth - 1) == 0 { + self.init(sign: .plus, magnitude: BigUInt(words: words)) + } + else { + words.twosComplement() + self.init(sign: .minus, magnitude: BigUInt(words: words)) + } + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/LICENSE b/Example/myWeb3Wallet/Pods/CryptoSwift/LICENSE new file mode 100644 index 000000000..e52af7df6 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/LICENSE @@ -0,0 +1,11 @@ +Copyright (C) 2014-2017 Marcin Krzyżanowski +This software is provided 'as-is', without any express or implied warranty. + +In no event will the authors be held liable for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: + +- The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +- Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +- This notice may not be removed or altered from any source or binary distribution. +- Redistributions of any form whatsoever must retain the following acknowledgment: 'This product includes software developed by the "Marcin Krzyzanowski" (http://krzyzanowskim.com/).' diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/README.md b/Example/myWeb3Wallet/Pods/CryptoSwift/README.md new file mode 100644 index 000000000..2343660b1 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/README.md @@ -0,0 +1,551 @@ +[![Platform](https://img.shields.io/badge/Platforms-iOS%20%7C%20Android%20%7CmacOS%20%7C%20watchOS%20%7C%20tvOS%20%7C%20Linux-4E4E4E.svg?colorA=28a745)](#installation) + +[![Swift support](https://img.shields.io/badge/Swift-3.1%20%7C%203.2%20%7C%204.0%20%7C%204.1%20%7C%204.2%20%7C%205.0-lightgrey.svg?colorA=28a745&colorB=4E4E4E)](#swift-versions-support) +[![Swift Package Manager compatible](https://img.shields.io/badge/SPM-compatible-brightgreen.svg?style=flat&colorA=28a745&&colorB=4E4E4E)](https://github.com/apple/swift-package-manager) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/CryptoSwift.svg?style=flat&label=CocoaPods&colorA=28a745&&colorB=4E4E4E)](https://cocoapods.org/pods/CryptoSwift) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-brightgreen.svg?style=flat&colorA=28a745&&colorB=4E4E4E)](https://github.com/Carthage/Carthage) + +# CryptoSwift + +Crypto related functions and helpers for [Swift](https://swift.org) implemented in Swift. ([#PureSwift](https://twitter.com/hashtag/pureswift)) + +**Note**: The `master` branch follows the latest currently released **version of Swift**. If you need an earlier version for an older version of Swift, you can specify its version in your `Podfile` or use the code on the branch for that version. Older branches are unsupported. Check [versions](#swift-versions-support) for details. + +--- + +[Requirements](#requirements) | [Features](#features) | [Contribution](#contribution) | [Installation](#installation) | [Swift versions](#swift-versions-support) | [How-to](#how-to) | [Author](#author) | [License](#license) | [Changelog](#changelog) + +## Sponsorship + +It takes some time to keep it all for your convenience, so maybe spare $1, so I can keep working on that. There are more than 8000 clones daily. If I'd get $1/month from each company that uses my work here, I'd say we're even. Hurry up, find the [Sponsorship](https://github.com/users/krzyzanowskim/sponsorship) button, and fulfill your duty. + +CryptoSwift isn't backed by any big company and is developer in my spare time that I also use to as a freelancer. + +[![Twitter](https://img.shields.io/badge/Twitter-@krzyzanowskim-blue.svg?style=flat)](http://twitter.com/krzyzanowskim) + +## Requirements +Good mood + +## Features + +- Easy to use +- Convenient extensions for String and Data +- Support for incremental updates (stream, ...) +- iOS, Android, macOS, AppleTV, watchOS, Linux support + +#### Hash (Digest) + [MD5](http://tools.ietf.org/html/rfc1321) +| [SHA1](http://tools.ietf.org/html/rfc3174) +| [SHA2-224](http://tools.ietf.org/html/rfc6234) +| [SHA2-256](http://tools.ietf.org/html/rfc6234) +| [SHA2-384](http://tools.ietf.org/html/rfc6234) +| [SHA2-512](http://tools.ietf.org/html/rfc6234) +| [SHA3](http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf) + +#### Cyclic Redundancy Check (CRC) + [CRC32](http://en.wikipedia.org/wiki/Cyclic_redundancy_check) +| [CRC32C](http://en.wikipedia.org/wiki/Cyclic_redundancy_check) +| [CRC16](http://en.wikipedia.org/wiki/Cyclic_redundancy_check) + +#### Cipher + [AES-128, AES-192, AES-256](http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf) +| [ChaCha20](http://cr.yp.to/chacha/chacha-20080128.pdf) +| [Rabbit](https://tools.ietf.org/html/rfc4503) +| [Blowfish](https://www.schneier.com/academic/blowfish/) + +#### Message authenticators + [Poly1305](http://cr.yp.to/mac/poly1305-20050329.pdf) +| [HMAC (MD5, SHA1, SHA256)](https://www.ietf.org/rfc/rfc2104.txt) +| [CMAC](https://tools.ietf.org/html/rfc4493) +| [CBC-MAC](https://en.wikipedia.org/wiki/CBC-MAC) + +#### Cipher mode of operation +- Electronic codebook ([ECB](http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_codebook_.28ECB.29)) +- Cipher-block chaining ([CBC](http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher-block_chaining_.28CBC.29)) +- Propagating Cipher Block Chaining ([PCBC](http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Propagating_Cipher_Block_Chaining_.28PCBC.29)) +- Cipher feedback ([CFB](http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_feedback_.28CFB.29)) +- Output Feedback ([OFB](http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Output_Feedback_.28OFB.29)) +- Counter Mode ([CTR](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_.28CTR.29)) +- Galois/Counter Mode ([GCM](https://csrc.nist.gov/publications/detail/sp/800-38d/final)) +- Counter with Cipher Block Chaining-Message Authentication Code ([CCM](https://csrc.nist.gov/publications/detail/sp/800-38c/final)) +- OCB Authenticated-Encryption Algorithm ([OCB](https://tools.ietf.org/html/rfc7253)) + +#### Password-Based Key Derivation Function +- [PBKDF1](http://tools.ietf.org/html/rfc2898#section-5.1) (Password-Based Key Derivation Function 1) +- [PBKDF2](http://tools.ietf.org/html/rfc2898#section-5.2) (Password-Based Key Derivation Function 2) +- [HKDF](https://tools.ietf.org/html/rfc5869) (HMAC-based Extract-and-Expand Key Derivation Function) +- [Scrypt](https://tools.ietf.org/html/rfc7914) (The scrypt Password-Based Key Derivation Function) + +#### Data padding + PKCS#5 +| [PKCS#7](http://tools.ietf.org/html/rfc5652#section-6.3) +| [Zero padding](https://en.wikipedia.org/wiki/Padding_(cryptography)#Zero_padding) +| [ISO78164](http://www.embedx.com/pdfs/ISO_STD_7816/info_isoiec7816-4%7Bed21.0%7Den.pdf) +| [ISO10126](https://en.wikipedia.org/wiki/Padding_(cryptography)#ISO_10126) +| No padding + +#### Authenticated Encryption with Associated Data (AEAD) +- [AEAD\_CHACHA20\_POLY1305](https://tools.ietf.org/html/rfc7539#section-2.8) + +## Why +[Why?](https://github.com/krzyzanowskim/CryptoSwift/issues/5) [Because I can](https://github.com/krzyzanowskim/CryptoSwift/issues/5#issuecomment-53379391). + +## How do I get involved? + +You want to help, great! Go ahead and fork our repo, make your changes and send us a pull request. + +## Contribution + +Check out [CONTRIBUTING.md](CONTRIBUTING.md) for more information on how to help with CryptoSwift. + +- If you found a bug, [open an issue](https://github.com/krzyzanowskim/CryptoSwift/issues). +- If you have a feature request, [open an issue](https://github.com/krzyzanowskim/CryptoSwift/issues). + +## Installation + +### Hardened Runtime (macOS) and Xcode + +Binary CryptoSwift.xcframework (Used by Swift Package Manager package integration) won't load properly in your app if the app uses **Sign to Run Locally** Signing Certificate with Hardened Runtime enabled. It is possible to setup Xcode like this. To solve the problem you have two options: +- Use proper Signing Certificate, eg. *Development* <- this is the proper action +- Use `Disable Library Validation` aka `com.apple.security.cs.disable-library-validation` entitlement + +#### Xcode Project + +To install CryptoSwift, add it as a submodule to your project (on the top level project directory): + + git submodule add https://github.com/krzyzanowskim/CryptoSwift.git + +It is recommended to enable [Whole-Module Optimization](https://swift.org/blog/whole-module-optimizations/) to gain better performance. Non-optimized build results in significantly worse performance. + +#### Swift Package Manager + +You can use [Swift Package Manager](https://swift.org/package-manager/) and specify dependency in `Package.swift` by adding this: + +```swift +.package(url: "https://github.com/krzyzanowskim/CryptoSwift.git", .upToNextMajor(from: "1.4.2")) +``` + +See: [Package.swift - manual](http://blog.krzyzanowskim.com/2016/08/09/package-swift-manual/) + +Notice: Swift Package Manager uses debug configuration for debug Xcode build, that may result in significant (up to x10000) worse performance. Performance characteristic is different in Release build. To overcome this prolem, consider embed `CryptoSwift.xcframework` described below. + +#### CocoaPods + +You can use [CocoaPods](https://cocoapods.org/pods/CryptoSwift). + +```ruby +pod 'CryptoSwift', '~> 1.4.1' +``` + +Bear in mind that CocoaPods will build CryptoSwift without [Whole-Module Optimization](https://swift.org/blog/whole-module-optimizations/) that may impact performance. You can change it manually after installation, or use [cocoapods-wholemodule](https://github.com/jedlewison/cocoapods-wholemodule) plugin. + +#### Carthage + +You can use [Carthage](https://github.com/Carthage/Carthage). +Specify in Cartfile: + +```ruby +github "krzyzanowskim/CryptoSwift" +``` + +Run `carthage` to build the framework and drag the built CryptoSwift.framework into your Xcode project. Follow [build instructions](https://github.com/Carthage/Carthage#getting-started). [Common issues](https://github.com/krzyzanowskim/CryptoSwift/issues/492#issuecomment-330822874). + +#### XCFramework + +XCFrameworks require Xcode 11 or later and they can be integrated similarly to how we’re used to integrating the `.framework` format. +Please use script [scripts/build-framework.sh](scripts/build-framework.sh) to generate binary `CryptoSwift.xcframework` archive that you can use as a dependency in Xcode. + +CryptoSwift.xcframework is a Release (Optimized) binary that offer best available Swift code performance. + +Screen Shot 2020-10-27 at 00 06 32 + +#### Embedded Framework + +Embedded frameworks require a minimum deployment target of iOS 9 or macOS Sierra (10.12). Drag the `CryptoSwift.xcodeproj` file into your Xcode project, and add appropriate framework as a dependency to your target. Now select your App and choose the General tab for the app target. Find *Embedded Binaries* and press "+", then select `CryptoSwift.framework` (iOS, macOS, watchOS or tvOS) + +![](https://cloud.githubusercontent.com/assets/758033/10834511/25a26852-7e9a-11e5-8c01-6cc8f1838459.png) + +Sometimes "embedded framework" option is not available. In that case, you have to add new build phase for the target. + +![](https://cloud.githubusercontent.com/assets/758033/18415615/d5edabb0-77f8-11e6-8c94-f41d9fc2b8cb.png) + +##### iOS, macOS, watchOS, tvOS + +In the project, you'll find [single scheme](https://mxcl.dev/PromiseKit/news/2016/08/Multiplatform-Single-Scheme-Xcode-Projects/) for all platforms: +- CryptoSwift + +#### Swift versions support + +- Swift 1.2: branch [swift12](https://github.com/krzyzanowskim/CryptoSwift/tree/swift12) version <= 0.0.13 +- Swift 2.1: branch [swift21](https://github.com/krzyzanowskim/CryptoSwift/tree/swift21) version <= 0.2.3 +- Swift 2.2, 2.3: branch [swift2](https://github.com/krzyzanowskim/CryptoSwift/tree/swift2) version <= 0.5.2 +- Swift 3.1, branch [swift3](https://github.com/krzyzanowskim/CryptoSwift/tree/swift3) version <= 0.6.9 +- Swift 3.2, branch [swift32](https://github.com/krzyzanowskim/CryptoSwift/tree/swift32) version = 0.7.0 +- Swift 4.0, branch [swift4](https://github.com/krzyzanowskim/CryptoSwift/tree/swift4) version <= 0.12.0 +- Swift 4.2, branch [swift42](https://github.com/krzyzanowskim/CryptoSwift/tree/swift42) version <= 0.15.0 +- Swift 5.0, branch [swift5](https://github.com/krzyzanowskim/CryptoSwift/tree/swift5) version <= 1.2.0 +- Swift 5.1, branch [swift5](https://github.com/krzyzanowskim/CryptoSwift/tree/swift51) version <= 1.3.3 +- Swift 5.3 and newer, branch [master](https://github.com/krzyzanowskim/CryptoSwift/tree/master) + +## How-to + +* [Basics (data types, conversion, ...)](#basics) +* [Digest (MD5, SHA...)](#calculate-digest) +* [Message authenticators (HMAC, CMAC...)](#message-authenticators-1) +* [Password-Based Key Derivation Function (PBKDF2, ...)](#password-based-key-derivation-functions) +* [HMAC-based Key Derivation Function (HKDF)](#hmac-based-key-derivation-function) +* [Data Padding](#data-padding) +* [ChaCha20](#chacha20) +* [Rabbit](#rabbit) +* [Blowfish](#blowfish) +* [AES - Advanced Encryption Standard](#aes) +* [AES-GCM](#aes-gcm) +* [Authenticated Encryption with Associated Data (AEAD)](#aead) + +##### Basics + +```swift +import CryptoSwift +``` + +CryptoSwift uses array of bytes aka `Array` as a base type for all operations. Every data may be converted to a stream of bytes. You will find convenience functions that accept `String` or `Data`, and it will be internally converted to the array of bytes. + +##### Data types conversion + +For your convenience, **CryptoSwift** provides two functions to easily convert an array of bytes to `Data` or `Data` to an array of bytes: + +Data from bytes: + +```swift +let data = Data( [0x01, 0x02, 0x03]) +``` + +`Data` to `Array` + +```swift +let bytes = data.bytes // [1,2,3] +``` + +[Hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal) encoding: + +```swift +let bytes = Array(hex: "0x010203") // [1,2,3] +let hex = bytes.toHexString() // "010203" +``` + +Build bytes out of `String` +```swift +let bytes: Array = "cipherkey".bytes // Array("cipherkey".utf8) +``` + +Also... check out helpers that work with **Base64** encoded data: +```swift +"aPf/i9th9iX+vf49eR7PYk2q7S5xmm3jkRLejgzHNJs=".decryptBase64ToString(cipher) +"aPf/i9th9iX+vf49eR7PYk2q7S5xmm3jkRLejgzHNJs=".decryptBase64(cipher) +bytes.toBase64() +``` + +##### Calculate Digest + +Hashing a data or array of bytes (aka `Array`) +```swift +/* Hash struct usage */ +let bytes: Array = [0x01, 0x02, 0x03] +let digest = input.md5() +let digest = Digest.md5(bytes) +``` + +```swift +let data = Data([0x01, 0x02, 0x03]) + +let hash = data.md5() +let hash = data.sha1() +let hash = data.sha224() +let hash = data.sha256() +let hash = data.sha384() +let hash = data.sha512() +``` +```swift +do { + var digest = MD5() + let partial1 = try digest.update(withBytes: [0x31, 0x32]) + let partial2 = try digest.update(withBytes: [0x33]) + let result = try digest.finish() +} catch { } +``` + +Hashing a String and printing result + +```swift +let hash = "123".md5() // "123".bytes.md5() +``` + +##### Calculate CRC + +```swift +bytes.crc16() +data.crc16() + +bytes.crc32() +data.crc32() +``` + +##### Message authenticators + +```swift +// Calculate Message Authentication Code (MAC) for message +let key: Array = [1,2,3,4,5,6,7,8,9,10,...] + +try Poly1305(key: key).authenticate(bytes) +try HMAC(key: key, variant: .sha256).authenticate(bytes) +try CMAC(key: key).authenticate(bytes) +``` + +##### Password-Based Key Derivation Functions + +```swift +let password: Array = Array("s33krit".utf8) +let salt: Array = Array("nacllcan".utf8) + +let key = try PKCS5.PBKDF2(password: password, salt: salt, iterations: 4096, keyLength: 32, variant: .sha256).calculate() +``` + +```swift +let password: Array = Array("s33krit".utf8) +let salt: Array = Array("nacllcan".utf8) +// Scrypt implementation does not implement work parallelization, so `p` parameter will +// increase the work time even in multicore systems +let key = try Scrypt(password: password, salt: salt, dkLen: 64, N: 16384, r: 8, p: 1).calculate() +``` + +##### HMAC-based Key Derivation Function + +```swift +let password: Array = Array("s33krit".utf8) +let salt: Array = Array("nacllcan".utf8) + +let key = try HKDF(password: password, salt: salt, variant: .sha256).calculate() +``` + + +##### Data Padding + +Some content-encryption algorithms assume the input length is a multiple of `k` octets, where `k` is greater than one. For such algorithms, the input shall be padded. + +```swift +Padding.pkcs7.add(to: bytes, blockSize: AES.blockSize) +``` + +#### Working with Ciphers +##### ChaCha20 + +```swift +let encrypted = try ChaCha20(key: key, iv: iv).encrypt(message) +let decrypted = try ChaCha20(key: key, iv: iv).decrypt(encrypted) +``` + +##### Rabbit + +```swift +let encrypted = try Rabbit(key: key, iv: iv).encrypt(message) +let decrypted = try Rabbit(key: key, iv: iv).decrypt(encrypted) +``` +##### Blowfish + +```swift +let encrypted = try Blowfish(key: key, blockMode: CBC(iv: iv), padding: .pkcs7).encrypt(message) +let decrypted = try Blowfish(key: key, blockMode: CBC(iv: iv), padding: .pkcs7).decrypt(encrypted) +``` + +##### AES + +Notice regarding padding: *Manual padding of data is optional, and CryptoSwift is using PKCS7 padding by default. If you need to manually disable/enable padding, you can do this by setting parameter for __AES__ class* + +Variant of AES encryption (AES-128, AES-192, AES-256) depends on given key length: + +- AES-128 = 16 bytes +- AES-192 = 24 bytes +- AES-256 = 32 bytes + +AES-256 example + +```swift +let encryptedBytes = try AES(key: [1,2,3,...,32], blockMode: CBC(iv: [1,2,3,...,16]), padding: .pkcs7) +``` + +Full example: + +```swift +let password: [UInt8] = Array("s33krit".utf8) +let salt: [UInt8] = Array("nacllcan".utf8) + +/* Generate a key from a `password`. Optional if you already have a key */ +let key = try PKCS5.PBKDF2( + password: password, + salt: salt, + iterations: 4096, + keyLength: 32, /* AES-256 */ + variant: .sha256 +).calculate() + +/* Generate random IV value. IV is public value. Either need to generate, or get it from elsewhere */ +let iv = AES.randomIV(AES.blockSize) + +/* AES cryptor instance */ +let aes = try AES(key: key, blockMode: CBC(iv: iv), padding: .pkcs7) + +/* Encrypt Data */ +let inputData = Data() +let encryptedBytes = try aes.encrypt(inputData.bytes) +let encryptedData = Data(encryptedBytes) + +/* Decrypt Data */ +let decryptedBytes = try aes.decrypt(encryptedData.bytes) +let decryptedData = Data(decryptedBytes) +``` + +###### All at once +```swift +do { + let aes = try AES(key: "keykeykeykeykeyk", iv: "drowssapdrowssap") // aes128 + let ciphertext = try aes.encrypt(Array("Nullam quis risus eget urna mollis ornare vel eu leo.".utf8)) +} catch { } +``` + +###### Incremental updates + +Incremental operations use instance of Cryptor and encrypt/decrypt one part at a time, this way you can save on memory for large files. + +```swift +do { + var encryptor = try AES(key: "keykeykeykeykeyk", iv: "drowssapdrowssap").makeEncryptor() + + var ciphertext = Array() + // aggregate partial results + ciphertext += try encryptor.update(withBytes: Array("Nullam quis risus ".utf8)) + ciphertext += try encryptor.update(withBytes: Array("eget urna mollis ".utf8)) + ciphertext += try encryptor.update(withBytes: Array("ornare vel eu leo.".utf8)) + // finish at the end + ciphertext += try encryptor.finish() + + print(ciphertext.toHexString()) +} catch { + print(error) +} +``` + +###### AES Advanced usage +```swift +let input: Array = [0,1,2,3,4,5,6,7,8,9] + +let key: Array = [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00] +let iv: Array = // Random bytes of `AES.blockSize` length + +do { + let encrypted = try AES(key: key, blockMode: CBC(iv: iv), padding: .pkcs7).encrypt(input) + let decrypted = try AES(key: key, blockMode: CBC(iv: iv), padding: .pkcs7).decrypt(encrypted) +} catch { + print(error) +} +``` + +AES without data padding + +```swift +let input: Array = [0,1,2,3,4,5,6,7,8,9] +let encrypted: Array = try! AES(key: Array("secret0key000000".utf8), blockMode: CBC(iv: Array("0123456789012345".utf8)), padding: .noPadding).encrypt(input) +``` + +Using convenience extensions + +```swift +let plain = Data([0x01, 0x02, 0x03]) +let encrypted = try! plain.encrypt(ChaCha20(key: key, iv: iv)) +let decrypted = try! encrypted.decrypt(ChaCha20(key: key, iv: iv)) +``` + +##### AES-GCM + +The result of Galois/Counter Mode (GCM) encryption is ciphertext and **authentication tag**, that is later used to decryption. + +encryption + +```swift +do { + // In combined mode, the authentication tag is directly appended to the encrypted message. This is usually what you want. + let gcm = GCM(iv: iv, mode: .combined) + let aes = try AES(key: key, blockMode: gcm, padding: .noPadding) + let encrypted = try aes.encrypt(plaintext) + let tag = gcm.authenticationTag +} catch { + // failed +} +``` + +decryption + +```swift +do { + // In combined mode, the authentication tag is appended to the encrypted message. This is usually what you want. + let gcm = GCM(iv: iv, mode: .combined) + let aes = try AES(key: key, blockMode: gcm, padding: .noPadding) + return try aes.decrypt(encrypted) +} catch { + // failed +} +``` + +**Note**: GCM instance is not intended to be reused. So you can't use the same `GCM` instance from encoding to also perform decoding. + +##### AES-CCM + +The result of Counter with Cipher Block Chaining-Message Authentication Code encryption is ciphertext and **authentication tag**, that is later used to decryption. + +```swift +do { + // The authentication tag is appended to the encrypted message. + let tagLength = 8 + let ccm = CCM(iv: iv, tagLength: tagLength, messageLength: ciphertext.count - tagLength, additionalAuthenticatedData: data) + let aes = try AES(key: key, blockMode: ccm, padding: .noPadding) + return try aes.decrypt(encrypted) +} catch { + // failed +} +``` + +Check documentation or CCM specification for valid parameters for CCM. + +##### AEAD + +```swift +let encrypt = try AEADChaCha20Poly1305.encrypt(plaintext, key: key, iv: nonce, authenticationHeader: header) +let decrypt = try AEADChaCha20Poly1305.decrypt(ciphertext, key: key, iv: nonce, authenticationHeader: header, authenticationTag: tagArr: tag) +``` + +## Author + +CryptoSwift is owned and maintained by [Marcin Krzyżanowski](http://www.krzyzanowskim.com) + +You can follow me on Twitter at [@krzyzanowskim](http://twitter.com/krzyzanowskim) for project updates and releases. + +# Cryptography Notice + +This distribution includes cryptographic software. The country in which you currently reside may have restrictions on the import, possession, use, and/or re-export to another country, of encryption software. BEFORE using any encryption software, please check your country's laws, regulations and policies concerning the import, possession, or use, and re-export of encryption software, to see if this is permitted. See http://www.wassenaar.org/ for more information. + +## License + +Copyright (C) 2014-2021 Marcin Krzyżanowski +This software is provided 'as-is', without any express or implied warranty. + +In no event will the authors be held liable for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: + +- The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, **an acknowledgment in the product documentation is required**. +- Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +- This notice may not be removed or altered from any source or binary distribution. +- Redistributions of any form whatsoever must retain the following acknowledgment: 'This product includes software developed by the "Marcin Krzyzanowski" (http://krzyzanowskim.com/).' + +## Changelog + +See [CHANGELOG](./CHANGELOG) file. diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEAD.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEAD.swift new file mode 100644 index 000000000..3b45ab44f --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEAD.swift @@ -0,0 +1,40 @@ +// +// AEAD.swift +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// +// + +// https://www.iana.org/assignments/aead-parameters/aead-parameters.xhtml + +/// Authenticated Encryption with Associated Data (AEAD) +public protocol AEAD { + static var kLen: Int { get } // key length + static var ivRange: Range { get } // nonce length +} + +extension AEAD { + static func calculateAuthenticationTag(authenticator: Authenticator, cipherText: Array, authenticationHeader: Array) throws -> Array { + let headerPadding = ((16 - (authenticationHeader.count & 0xf)) & 0xf) + let cipherPadding = ((16 - (cipherText.count & 0xf)) & 0xf) + + var mac = authenticationHeader + mac += Array(repeating: 0, count: headerPadding) + mac += cipherText + mac += Array(repeating: 0, count: cipherPadding) + mac += UInt64(bigEndian: UInt64(authenticationHeader.count)).bytes() + mac += UInt64(bigEndian: UInt64(cipherText.count)).bytes() + + return try authenticator.authenticate(mac) + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEADChaCha20Poly1305.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEADChaCha20Poly1305.swift new file mode 100644 index 000000000..b4c9aeb0f --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEADChaCha20Poly1305.swift @@ -0,0 +1,59 @@ +// +// ChaCha20Poly1305.swift +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// +// +// https://tools.ietf.org/html/rfc7539#section-2.8.1 + +/// AEAD_CHACHA20_POLY1305 +public final class AEADChaCha20Poly1305: AEAD { + public static let kLen = 32 // key length + public static var ivRange = Range(12...12) + + /// Authenticated encryption + public static func encrypt(_ plainText: Array, key: Array, iv: Array, authenticationHeader: Array) throws -> (cipherText: Array, authenticationTag: Array) { + let cipher = try ChaCha20(key: key, iv: iv) + + var polykey = Array(repeating: 0, count: kLen) + var toEncrypt = polykey + polykey = try cipher.encrypt(polykey) + toEncrypt += polykey + toEncrypt += plainText + + let fullCipherText = try cipher.encrypt(toEncrypt) + let cipherText = Array(fullCipherText.dropFirst(64)) + + let tag = try calculateAuthenticationTag(authenticator: Poly1305(key: polykey), cipherText: cipherText, authenticationHeader: authenticationHeader) + return (cipherText, tag) + } + + /// Authenticated decryption + public static func decrypt(_ cipherText: Array, key: Array, iv: Array, authenticationHeader: Array, authenticationTag: Array) throws -> (plainText: Array, success: Bool) { + let chacha = try ChaCha20(key: key, iv: iv) + + let polykey = try chacha.encrypt(Array(repeating: 0, count: self.kLen)) + let mac = try calculateAuthenticationTag(authenticator: Poly1305(key: polykey), cipherText: cipherText, authenticationHeader: authenticationHeader) + guard mac == authenticationTag else { + return (cipherText, false) + } + + var toDecrypt = Array(reserveCapacity: cipherText.count + 64) + toDecrypt += polykey + toDecrypt += polykey + toDecrypt += cipherText + let fullPlainText = try chacha.decrypt(toDecrypt) + let plainText = Array(fullPlainText.dropFirst(64)) + return (plainText, true) + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/AES.Cryptors.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/AES.Cryptors.swift new file mode 100644 index 000000000..f84c92bcd --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/AES.Cryptors.swift @@ -0,0 +1,39 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// MARK: Cryptors + +extension AES: Cryptors { + @inlinable + public func makeEncryptor() throws -> Cryptor & Updatable { + let blockSize = blockMode.customBlockSize ?? AES.blockSize + let worker = try blockMode.worker(blockSize: blockSize, cipherOperation: encrypt, encryptionOperation: encrypt) + if worker is StreamModeWorker { + return try StreamEncryptor(blockSize: blockSize, padding: padding, worker) + } + return try BlockEncryptor(blockSize: blockSize, padding: padding, worker) + } + + @inlinable + public func makeDecryptor() throws -> Cryptor & Updatable { + let blockSize = blockMode.customBlockSize ?? AES.blockSize + let cipherOperation: CipherOperationOnBlock = blockMode.options.contains(.useEncryptToDecrypt) == true ? encrypt : decrypt + let worker = try blockMode.worker(blockSize: blockSize, cipherOperation: cipherOperation, encryptionOperation: encrypt) + if worker is StreamModeWorker { + return try StreamDecryptor(blockSize: blockSize, padding: padding, worker) + } + return try BlockDecryptor(blockSize: blockSize, padding: padding, worker) + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/AES.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/AES.swift new file mode 100644 index 000000000..211bda6d2 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/AES.swift @@ -0,0 +1,556 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// Implementation of Gladman algorithm http://www.gladman.me.uk/AES +// + +/// The Advanced Encryption Standard (AES) +public final class AES: BlockCipher { + public enum Error: Swift.Error { + /// Invalid key + case invalidKeySize + /// Data padding is required + case dataPaddingRequired + /// Invalid Data + case invalidData + } + + public enum Variant: Int { + case aes128 = 1, aes192, aes256 + + var Nk: Int { // Nk words + [4, 6, 8][self.rawValue - 1] + } + + var Nb: Int { // Nb words + 4 + } + + var Nr: Int { // Nr + self.Nk + 6 + } + } + + @usableFromInline + internal let variantNr: Int + + @usableFromInline + internal let variantNb: Int + + @usableFromInline + internal let variantNk: Int + + public static let blockSize: Int = 16 // 128 /8 + public let keySize: Int + + /// AES Variant + public let variant: Variant + + // Parameters + let key: Key + + @usableFromInline + let blockMode: BlockMode + + @usableFromInline + let padding: Padding + + // + @usableFromInline + internal lazy var expandedKey: Array> = self.expandKey(self.key, variant: self.variant) + + @usableFromInline + internal lazy var expandedKeyInv: Array> = self.expandKeyInv(self.key, variant: self.variant) + + private lazy var sBoxes: (sBox: Array, invSBox: Array) = self.calculateSBox() + private lazy var sBox: Array = self.sBoxes.sBox + private lazy var sBoxInv: Array = self.sBoxes.invSBox + + // Parameters for Linear Congruence Generators + private static let Rcon: Array = [ + 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, + 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, + 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, + 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, + 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, + 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, + 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, + 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, + 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, + 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, + 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, + 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, + 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, + 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, + 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, + 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d + ] + + @usableFromInline static let T0: Array = [0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0xdf2f2ff, 0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x3010102, 0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d, 0x9a7676ec, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa, 0x15fafaef, 0xeb5959b2, 0xc947478e, 0xbf0f0fb, 0xecadad41, 0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453, 0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d, 0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x2f7f7f5, 0x4fcccc83, 0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x8f1f1f9, 0x937171e2, 0x73d8d8ab, 0x53313162, 0x3f15152a, 0xc040408, 0x52c7c795, 0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0xf05050a, 0xb59a9a2f, 0x907070e, 0x36121224, 0x9b80801b, 0x3de2e2df, 0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912, 0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc, 0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7, 0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413, 0xf55353a6, 0x68d1d1b9, 0x0, 0x2cededc1, 0x60202040, 0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d, 0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0, 0x4acfcf85, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed, 0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a, 0x10f9f9e9, 0x6020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78, 0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d, 0xc0404080, 0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x4f5f5f1, 0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020, 0x1affffe5, 0xef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18, 0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488, 0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a, 0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0xa06060c0, 0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54, 0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b, 0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad, 0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992, 0xa06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd, 0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3, 0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda, 0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8, 0xfa5656ac, 0x7f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4, 0xe9aeae47, 0x18080810, 0xd5baba6f, 0x887878f0, 0x6f25254a, 0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697, 0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96, 0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c, 0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x5030306, 0x1f6f6f7, 0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969, 0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0x38e1e1d9, 0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9, 0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715, 0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5, 0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65, 0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929, 0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d, 0x3a16162c] + @usableFromInline static let T0_INV: Array = [0x50a7f451, 0x5365417e, 0xc3a4171a, 0x965e273a, 0xcb6bab3b, 0xf1459d1f, 0xab58faac, 0x9303e34b, 0x55fa3020, 0xf66d76ad, 0x9176cc88, 0x254c02f5, 0xfcd7e54f, 0xd7cb2ac5, 0x80443526, 0x8fa362b5, 0x495ab1de, 0x671bba25, 0x980eea45, 0xe1c0fe5d, 0x2752fc3, 0x12f04c81, 0xa397468d, 0xc6f9d36b, 0xe75f8f03, 0x959c9215, 0xeb7a6dbf, 0xda595295, 0x2d83bed4, 0xd3217458, 0x2969e049, 0x44c8c98e, 0x6a89c275, 0x78798ef4, 0x6b3e5899, 0xdd71b927, 0xb64fe1be, 0x17ad88f0, 0x66ac20c9, 0xb43ace7d, 0x184adf63, 0x82311ae5, 0x60335197, 0x457f5362, 0xe07764b1, 0x84ae6bbb, 0x1ca081fe, 0x942b08f9, 0x58684870, 0x19fd458f, 0x876cde94, 0xb7f87b52, 0x23d373ab, 0xe2024b72, 0x578f1fe3, 0x2aab5566, 0x728ebb2, 0x3c2b52f, 0x9a7bc586, 0xa50837d3, 0xf2872830, 0xb2a5bf23, 0xba6a0302, 0x5c8216ed, 0x2b1ccf8a, 0x92b479a7, 0xf0f207f3, 0xa1e2694e, 0xcdf4da65, 0xd5be0506, 0x1f6234d1, 0x8afea6c4, 0x9d532e34, 0xa055f3a2, 0x32e18a05, 0x75ebf6a4, 0x39ec830b, 0xaaef6040, 0x69f715e, 0x51106ebd, 0xf98a213e, 0x3d06dd96, 0xae053edd, 0x46bde64d, 0xb58d5491, 0x55dc471, 0x6fd40604, 0xff155060, 0x24fb9819, 0x97e9bdd6, 0xcc434089, 0x779ed967, 0xbd42e8b0, 0x888b8907, 0x385b19e7, 0xdbeec879, 0x470a7ca1, 0xe90f427c, 0xc91e84f8, 0x0, 0x83868009, 0x48ed2b32, 0xac70111e, 0x4e725a6c, 0xfbff0efd, 0x5638850f, 0x1ed5ae3d, 0x27392d36, 0x64d90f0a, 0x21a65c68, 0xd1545b9b, 0x3a2e3624, 0xb1670a0c, 0xfe75793, 0xd296eeb4, 0x9e919b1b, 0x4fc5c080, 0xa220dc61, 0x694b775a, 0x161a121c, 0xaba93e2, 0xe52aa0c0, 0x43e0223c, 0x1d171b12, 0xb0d090e, 0xadc78bf2, 0xb9a8b62d, 0xc8a91e14, 0x8519f157, 0x4c0775af, 0xbbdd99ee, 0xfd607fa3, 0x9f2601f7, 0xbcf5725c, 0xc53b6644, 0x347efb5b, 0x7629438b, 0xdcc623cb, 0x68fcedb6, 0x63f1e4b8, 0xcadc31d7, 0x10856342, 0x40229713, 0x2011c684, 0x7d244a85, 0xf83dbbd2, 0x1132f9ae, 0x6da129c7, 0x4b2f9e1d, 0xf330b2dc, 0xec52860d, 0xd0e3c177, 0x6c16b32b, 0x99b970a9, 0xfa489411, 0x2264e947, 0xc48cfca8, 0x1a3ff0a0, 0xd82c7d56, 0xef903322, 0xc74e4987, 0xc1d138d9, 0xfea2ca8c, 0x360bd498, 0xcf81f5a6, 0x28de7aa5, 0x268eb7da, 0xa4bfad3f, 0xe49d3a2c, 0xd927850, 0x9bcc5f6a, 0x62467e54, 0xc2138df6, 0xe8b8d890, 0x5ef7392e, 0xf5afc382, 0xbe805d9f, 0x7c93d069, 0xa92dd56f, 0xb31225cf, 0x3b99acc8, 0xa77d1810, 0x6e639ce8, 0x7bbb3bdb, 0x97826cd, 0xf418596e, 0x1b79aec, 0xa89a4f83, 0x656e95e6, 0x7ee6ffaa, 0x8cfbc21, 0xe6e815ef, 0xd99be7ba, 0xce366f4a, 0xd4099fea, 0xd67cb029, 0xafb2a431, 0x31233f2a, 0x3094a5c6, 0xc066a235, 0x37bc4e74, 0xa6ca82fc, 0xb0d090e0, 0x15d8a733, 0x4a9804f1, 0xf7daec41, 0xe50cd7f, 0x2ff69117, 0x8dd64d76, 0x4db0ef43, 0x544daacc, 0xdf0496e4, 0xe3b5d19e, 0x1b886a4c, 0xb81f2cc1, 0x7f516546, 0x4ea5e9d, 0x5d358c01, 0x737487fa, 0x2e410bfb, 0x5a1d67b3, 0x52d2db92, 0x335610e9, 0x1347d66d, 0x8c61d79a, 0x7a0ca137, 0x8e14f859, 0x893c13eb, 0xee27a9ce, 0x35c961b7, 0xede51ce1, 0x3cb1477a, 0x59dfd29c, 0x3f73f255, 0x79ce1418, 0xbf37c773, 0xeacdf753, 0x5baafd5f, 0x146f3ddf, 0x86db4478, 0x81f3afca, 0x3ec468b9, 0x2c342438, 0x5f40a3c2, 0x72c31d16, 0xc25e2bc, 0x8b493c28, 0x41950dff, 0x7101a839, 0xdeb30c08, 0x9ce4b4d8, 0x90c15664, 0x6184cb7b, 0x70b632d5, 0x745c6c48, 0x4257b8d0] + @usableFromInline static let T1: Array = [0x6363c6a5, 0x7c7cf884, 0x7777ee99, 0x7b7bf68d, 0xf2f2ff0d, 0x6b6bd6bd, 0x6f6fdeb1, 0xc5c59154, 0x30306050, 0x1010203, 0x6767cea9, 0x2b2b567d, 0xfefee719, 0xd7d7b562, 0xabab4de6, 0x7676ec9a, 0xcaca8f45, 0x82821f9d, 0xc9c98940, 0x7d7dfa87, 0xfafaef15, 0x5959b2eb, 0x47478ec9, 0xf0f0fb0b, 0xadad41ec, 0xd4d4b367, 0xa2a25ffd, 0xafaf45ea, 0x9c9c23bf, 0xa4a453f7, 0x7272e496, 0xc0c09b5b, 0xb7b775c2, 0xfdfde11c, 0x93933dae, 0x26264c6a, 0x36366c5a, 0x3f3f7e41, 0xf7f7f502, 0xcccc834f, 0x3434685c, 0xa5a551f4, 0xe5e5d134, 0xf1f1f908, 0x7171e293, 0xd8d8ab73, 0x31316253, 0x15152a3f, 0x404080c, 0xc7c79552, 0x23234665, 0xc3c39d5e, 0x18183028, 0x969637a1, 0x5050a0f, 0x9a9a2fb5, 0x7070e09, 0x12122436, 0x80801b9b, 0xe2e2df3d, 0xebebcd26, 0x27274e69, 0xb2b27fcd, 0x7575ea9f, 0x909121b, 0x83831d9e, 0x2c2c5874, 0x1a1a342e, 0x1b1b362d, 0x6e6edcb2, 0x5a5ab4ee, 0xa0a05bfb, 0x5252a4f6, 0x3b3b764d, 0xd6d6b761, 0xb3b37dce, 0x2929527b, 0xe3e3dd3e, 0x2f2f5e71, 0x84841397, 0x5353a6f5, 0xd1d1b968, 0x0, 0xededc12c, 0x20204060, 0xfcfce31f, 0xb1b179c8, 0x5b5bb6ed, 0x6a6ad4be, 0xcbcb8d46, 0xbebe67d9, 0x3939724b, 0x4a4a94de, 0x4c4c98d4, 0x5858b0e8, 0xcfcf854a, 0xd0d0bb6b, 0xefefc52a, 0xaaaa4fe5, 0xfbfbed16, 0x434386c5, 0x4d4d9ad7, 0x33336655, 0x85851194, 0x45458acf, 0xf9f9e910, 0x2020406, 0x7f7ffe81, 0x5050a0f0, 0x3c3c7844, 0x9f9f25ba, 0xa8a84be3, 0x5151a2f3, 0xa3a35dfe, 0x404080c0, 0x8f8f058a, 0x92923fad, 0x9d9d21bc, 0x38387048, 0xf5f5f104, 0xbcbc63df, 0xb6b677c1, 0xdadaaf75, 0x21214263, 0x10102030, 0xffffe51a, 0xf3f3fd0e, 0xd2d2bf6d, 0xcdcd814c, 0xc0c1814, 0x13132635, 0xececc32f, 0x5f5fbee1, 0x979735a2, 0x444488cc, 0x17172e39, 0xc4c49357, 0xa7a755f2, 0x7e7efc82, 0x3d3d7a47, 0x6464c8ac, 0x5d5dbae7, 0x1919322b, 0x7373e695, 0x6060c0a0, 0x81811998, 0x4f4f9ed1, 0xdcdca37f, 0x22224466, 0x2a2a547e, 0x90903bab, 0x88880b83, 0x46468cca, 0xeeeec729, 0xb8b86bd3, 0x1414283c, 0xdedea779, 0x5e5ebce2, 0xb0b161d, 0xdbdbad76, 0xe0e0db3b, 0x32326456, 0x3a3a744e, 0xa0a141e, 0x494992db, 0x6060c0a, 0x2424486c, 0x5c5cb8e4, 0xc2c29f5d, 0xd3d3bd6e, 0xacac43ef, 0x6262c4a6, 0x919139a8, 0x959531a4, 0xe4e4d337, 0x7979f28b, 0xe7e7d532, 0xc8c88b43, 0x37376e59, 0x6d6ddab7, 0x8d8d018c, 0xd5d5b164, 0x4e4e9cd2, 0xa9a949e0, 0x6c6cd8b4, 0x5656acfa, 0xf4f4f307, 0xeaeacf25, 0x6565caaf, 0x7a7af48e, 0xaeae47e9, 0x8081018, 0xbaba6fd5, 0x7878f088, 0x25254a6f, 0x2e2e5c72, 0x1c1c3824, 0xa6a657f1, 0xb4b473c7, 0xc6c69751, 0xe8e8cb23, 0xdddda17c, 0x7474e89c, 0x1f1f3e21, 0x4b4b96dd, 0xbdbd61dc, 0x8b8b0d86, 0x8a8a0f85, 0x7070e090, 0x3e3e7c42, 0xb5b571c4, 0x6666ccaa, 0x484890d8, 0x3030605, 0xf6f6f701, 0xe0e1c12, 0x6161c2a3, 0x35356a5f, 0x5757aef9, 0xb9b969d0, 0x86861791, 0xc1c19958, 0x1d1d3a27, 0x9e9e27b9, 0xe1e1d938, 0xf8f8eb13, 0x98982bb3, 0x11112233, 0x6969d2bb, 0xd9d9a970, 0x8e8e0789, 0x949433a7, 0x9b9b2db6, 0x1e1e3c22, 0x87871592, 0xe9e9c920, 0xcece8749, 0x5555aaff, 0x28285078, 0xdfdfa57a, 0x8c8c038f, 0xa1a159f8, 0x89890980, 0xd0d1a17, 0xbfbf65da, 0xe6e6d731, 0x424284c6, 0x6868d0b8, 0x414182c3, 0x999929b0, 0x2d2d5a77, 0xf0f1e11, 0xb0b07bcb, 0x5454a8fc, 0xbbbb6dd6, 0x16162c3a] + @usableFromInline static let T1_INV: Array = [0xa7f45150, 0x65417e53, 0xa4171ac3, 0x5e273a96, 0x6bab3bcb, 0x459d1ff1, 0x58faacab, 0x3e34b93, 0xfa302055, 0x6d76adf6, 0x76cc8891, 0x4c02f525, 0xd7e54ffc, 0xcb2ac5d7, 0x44352680, 0xa362b58f, 0x5ab1de49, 0x1bba2567, 0xeea4598, 0xc0fe5de1, 0x752fc302, 0xf04c8112, 0x97468da3, 0xf9d36bc6, 0x5f8f03e7, 0x9c921595, 0x7a6dbfeb, 0x595295da, 0x83bed42d, 0x217458d3, 0x69e04929, 0xc8c98e44, 0x89c2756a, 0x798ef478, 0x3e58996b, 0x71b927dd, 0x4fe1beb6, 0xad88f017, 0xac20c966, 0x3ace7db4, 0x4adf6318, 0x311ae582, 0x33519760, 0x7f536245, 0x7764b1e0, 0xae6bbb84, 0xa081fe1c, 0x2b08f994, 0x68487058, 0xfd458f19, 0x6cde9487, 0xf87b52b7, 0xd373ab23, 0x24b72e2, 0x8f1fe357, 0xab55662a, 0x28ebb207, 0xc2b52f03, 0x7bc5869a, 0x837d3a5, 0x872830f2, 0xa5bf23b2, 0x6a0302ba, 0x8216ed5c, 0x1ccf8a2b, 0xb479a792, 0xf207f3f0, 0xe2694ea1, 0xf4da65cd, 0xbe0506d5, 0x6234d11f, 0xfea6c48a, 0x532e349d, 0x55f3a2a0, 0xe18a0532, 0xebf6a475, 0xec830b39, 0xef6040aa, 0x9f715e06, 0x106ebd51, 0x8a213ef9, 0x6dd963d, 0x53eddae, 0xbde64d46, 0x8d5491b5, 0x5dc47105, 0xd406046f, 0x155060ff, 0xfb981924, 0xe9bdd697, 0x434089cc, 0x9ed96777, 0x42e8b0bd, 0x8b890788, 0x5b19e738, 0xeec879db, 0xa7ca147, 0xf427ce9, 0x1e84f8c9, 0x0, 0x86800983, 0xed2b3248, 0x70111eac, 0x725a6c4e, 0xff0efdfb, 0x38850f56, 0xd5ae3d1e, 0x392d3627, 0xd90f0a64, 0xa65c6821, 0x545b9bd1, 0x2e36243a, 0x670a0cb1, 0xe757930f, 0x96eeb4d2, 0x919b1b9e, 0xc5c0804f, 0x20dc61a2, 0x4b775a69, 0x1a121c16, 0xba93e20a, 0x2aa0c0e5, 0xe0223c43, 0x171b121d, 0xd090e0b, 0xc78bf2ad, 0xa8b62db9, 0xa91e14c8, 0x19f15785, 0x775af4c, 0xdd99eebb, 0x607fa3fd, 0x2601f79f, 0xf5725cbc, 0x3b6644c5, 0x7efb5b34, 0x29438b76, 0xc623cbdc, 0xfcedb668, 0xf1e4b863, 0xdc31d7ca, 0x85634210, 0x22971340, 0x11c68420, 0x244a857d, 0x3dbbd2f8, 0x32f9ae11, 0xa129c76d, 0x2f9e1d4b, 0x30b2dcf3, 0x52860dec, 0xe3c177d0, 0x16b32b6c, 0xb970a999, 0x489411fa, 0x64e94722, 0x8cfca8c4, 0x3ff0a01a, 0x2c7d56d8, 0x903322ef, 0x4e4987c7, 0xd138d9c1, 0xa2ca8cfe, 0xbd49836, 0x81f5a6cf, 0xde7aa528, 0x8eb7da26, 0xbfad3fa4, 0x9d3a2ce4, 0x9278500d, 0xcc5f6a9b, 0x467e5462, 0x138df6c2, 0xb8d890e8, 0xf7392e5e, 0xafc382f5, 0x805d9fbe, 0x93d0697c, 0x2dd56fa9, 0x1225cfb3, 0x99acc83b, 0x7d1810a7, 0x639ce86e, 0xbb3bdb7b, 0x7826cd09, 0x18596ef4, 0xb79aec01, 0x9a4f83a8, 0x6e95e665, 0xe6ffaa7e, 0xcfbc2108, 0xe815efe6, 0x9be7bad9, 0x366f4ace, 0x99fead4, 0x7cb029d6, 0xb2a431af, 0x233f2a31, 0x94a5c630, 0x66a235c0, 0xbc4e7437, 0xca82fca6, 0xd090e0b0, 0xd8a73315, 0x9804f14a, 0xdaec41f7, 0x50cd7f0e, 0xf691172f, 0xd64d768d, 0xb0ef434d, 0x4daacc54, 0x496e4df, 0xb5d19ee3, 0x886a4c1b, 0x1f2cc1b8, 0x5165467f, 0xea5e9d04, 0x358c015d, 0x7487fa73, 0x410bfb2e, 0x1d67b35a, 0xd2db9252, 0x5610e933, 0x47d66d13, 0x61d79a8c, 0xca1377a, 0x14f8598e, 0x3c13eb89, 0x27a9ceee, 0xc961b735, 0xe51ce1ed, 0xb1477a3c, 0xdfd29c59, 0x73f2553f, 0xce141879, 0x37c773bf, 0xcdf753ea, 0xaafd5f5b, 0x6f3ddf14, 0xdb447886, 0xf3afca81, 0xc468b93e, 0x3424382c, 0x40a3c25f, 0xc31d1672, 0x25e2bc0c, 0x493c288b, 0x950dff41, 0x1a83971, 0xb30c08de, 0xe4b4d89c, 0xc1566490, 0x84cb7b61, 0xb632d570, 0x5c6c4874, 0x57b8d042] + @usableFromInline static let T2: Array = [0x63c6a563, 0x7cf8847c, 0x77ee9977, 0x7bf68d7b, 0xf2ff0df2, 0x6bd6bd6b, 0x6fdeb16f, 0xc59154c5, 0x30605030, 0x1020301, 0x67cea967, 0x2b567d2b, 0xfee719fe, 0xd7b562d7, 0xab4de6ab, 0x76ec9a76, 0xca8f45ca, 0x821f9d82, 0xc98940c9, 0x7dfa877d, 0xfaef15fa, 0x59b2eb59, 0x478ec947, 0xf0fb0bf0, 0xad41ecad, 0xd4b367d4, 0xa25ffda2, 0xaf45eaaf, 0x9c23bf9c, 0xa453f7a4, 0x72e49672, 0xc09b5bc0, 0xb775c2b7, 0xfde11cfd, 0x933dae93, 0x264c6a26, 0x366c5a36, 0x3f7e413f, 0xf7f502f7, 0xcc834fcc, 0x34685c34, 0xa551f4a5, 0xe5d134e5, 0xf1f908f1, 0x71e29371, 0xd8ab73d8, 0x31625331, 0x152a3f15, 0x4080c04, 0xc79552c7, 0x23466523, 0xc39d5ec3, 0x18302818, 0x9637a196, 0x50a0f05, 0x9a2fb59a, 0x70e0907, 0x12243612, 0x801b9b80, 0xe2df3de2, 0xebcd26eb, 0x274e6927, 0xb27fcdb2, 0x75ea9f75, 0x9121b09, 0x831d9e83, 0x2c58742c, 0x1a342e1a, 0x1b362d1b, 0x6edcb26e, 0x5ab4ee5a, 0xa05bfba0, 0x52a4f652, 0x3b764d3b, 0xd6b761d6, 0xb37dceb3, 0x29527b29, 0xe3dd3ee3, 0x2f5e712f, 0x84139784, 0x53a6f553, 0xd1b968d1, 0x0, 0xedc12ced, 0x20406020, 0xfce31ffc, 0xb179c8b1, 0x5bb6ed5b, 0x6ad4be6a, 0xcb8d46cb, 0xbe67d9be, 0x39724b39, 0x4a94de4a, 0x4c98d44c, 0x58b0e858, 0xcf854acf, 0xd0bb6bd0, 0xefc52aef, 0xaa4fe5aa, 0xfbed16fb, 0x4386c543, 0x4d9ad74d, 0x33665533, 0x85119485, 0x458acf45, 0xf9e910f9, 0x2040602, 0x7ffe817f, 0x50a0f050, 0x3c78443c, 0x9f25ba9f, 0xa84be3a8, 0x51a2f351, 0xa35dfea3, 0x4080c040, 0x8f058a8f, 0x923fad92, 0x9d21bc9d, 0x38704838, 0xf5f104f5, 0xbc63dfbc, 0xb677c1b6, 0xdaaf75da, 0x21426321, 0x10203010, 0xffe51aff, 0xf3fd0ef3, 0xd2bf6dd2, 0xcd814ccd, 0xc18140c, 0x13263513, 0xecc32fec, 0x5fbee15f, 0x9735a297, 0x4488cc44, 0x172e3917, 0xc49357c4, 0xa755f2a7, 0x7efc827e, 0x3d7a473d, 0x64c8ac64, 0x5dbae75d, 0x19322b19, 0x73e69573, 0x60c0a060, 0x81199881, 0x4f9ed14f, 0xdca37fdc, 0x22446622, 0x2a547e2a, 0x903bab90, 0x880b8388, 0x468cca46, 0xeec729ee, 0xb86bd3b8, 0x14283c14, 0xdea779de, 0x5ebce25e, 0xb161d0b, 0xdbad76db, 0xe0db3be0, 0x32645632, 0x3a744e3a, 0xa141e0a, 0x4992db49, 0x60c0a06, 0x24486c24, 0x5cb8e45c, 0xc29f5dc2, 0xd3bd6ed3, 0xac43efac, 0x62c4a662, 0x9139a891, 0x9531a495, 0xe4d337e4, 0x79f28b79, 0xe7d532e7, 0xc88b43c8, 0x376e5937, 0x6ddab76d, 0x8d018c8d, 0xd5b164d5, 0x4e9cd24e, 0xa949e0a9, 0x6cd8b46c, 0x56acfa56, 0xf4f307f4, 0xeacf25ea, 0x65caaf65, 0x7af48e7a, 0xae47e9ae, 0x8101808, 0xba6fd5ba, 0x78f08878, 0x254a6f25, 0x2e5c722e, 0x1c38241c, 0xa657f1a6, 0xb473c7b4, 0xc69751c6, 0xe8cb23e8, 0xdda17cdd, 0x74e89c74, 0x1f3e211f, 0x4b96dd4b, 0xbd61dcbd, 0x8b0d868b, 0x8a0f858a, 0x70e09070, 0x3e7c423e, 0xb571c4b5, 0x66ccaa66, 0x4890d848, 0x3060503, 0xf6f701f6, 0xe1c120e, 0x61c2a361, 0x356a5f35, 0x57aef957, 0xb969d0b9, 0x86179186, 0xc19958c1, 0x1d3a271d, 0x9e27b99e, 0xe1d938e1, 0xf8eb13f8, 0x982bb398, 0x11223311, 0x69d2bb69, 0xd9a970d9, 0x8e07898e, 0x9433a794, 0x9b2db69b, 0x1e3c221e, 0x87159287, 0xe9c920e9, 0xce8749ce, 0x55aaff55, 0x28507828, 0xdfa57adf, 0x8c038f8c, 0xa159f8a1, 0x89098089, 0xd1a170d, 0xbf65dabf, 0xe6d731e6, 0x4284c642, 0x68d0b868, 0x4182c341, 0x9929b099, 0x2d5a772d, 0xf1e110f, 0xb07bcbb0, 0x54a8fc54, 0xbb6dd6bb, 0x162c3a16] + @usableFromInline static let T2_INV: Array = [0xf45150a7, 0x417e5365, 0x171ac3a4, 0x273a965e, 0xab3bcb6b, 0x9d1ff145, 0xfaacab58, 0xe34b9303, 0x302055fa, 0x76adf66d, 0xcc889176, 0x2f5254c, 0xe54ffcd7, 0x2ac5d7cb, 0x35268044, 0x62b58fa3, 0xb1de495a, 0xba25671b, 0xea45980e, 0xfe5de1c0, 0x2fc30275, 0x4c8112f0, 0x468da397, 0xd36bc6f9, 0x8f03e75f, 0x9215959c, 0x6dbfeb7a, 0x5295da59, 0xbed42d83, 0x7458d321, 0xe0492969, 0xc98e44c8, 0xc2756a89, 0x8ef47879, 0x58996b3e, 0xb927dd71, 0xe1beb64f, 0x88f017ad, 0x20c966ac, 0xce7db43a, 0xdf63184a, 0x1ae58231, 0x51976033, 0x5362457f, 0x64b1e077, 0x6bbb84ae, 0x81fe1ca0, 0x8f9942b, 0x48705868, 0x458f19fd, 0xde94876c, 0x7b52b7f8, 0x73ab23d3, 0x4b72e202, 0x1fe3578f, 0x55662aab, 0xebb20728, 0xb52f03c2, 0xc5869a7b, 0x37d3a508, 0x2830f287, 0xbf23b2a5, 0x302ba6a, 0x16ed5c82, 0xcf8a2b1c, 0x79a792b4, 0x7f3f0f2, 0x694ea1e2, 0xda65cdf4, 0x506d5be, 0x34d11f62, 0xa6c48afe, 0x2e349d53, 0xf3a2a055, 0x8a0532e1, 0xf6a475eb, 0x830b39ec, 0x6040aaef, 0x715e069f, 0x6ebd5110, 0x213ef98a, 0xdd963d06, 0x3eddae05, 0xe64d46bd, 0x5491b58d, 0xc471055d, 0x6046fd4, 0x5060ff15, 0x981924fb, 0xbdd697e9, 0x4089cc43, 0xd967779e, 0xe8b0bd42, 0x8907888b, 0x19e7385b, 0xc879dbee, 0x7ca1470a, 0x427ce90f, 0x84f8c91e, 0x0, 0x80098386, 0x2b3248ed, 0x111eac70, 0x5a6c4e72, 0xefdfbff, 0x850f5638, 0xae3d1ed5, 0x2d362739, 0xf0a64d9, 0x5c6821a6, 0x5b9bd154, 0x36243a2e, 0xa0cb167, 0x57930fe7, 0xeeb4d296, 0x9b1b9e91, 0xc0804fc5, 0xdc61a220, 0x775a694b, 0x121c161a, 0x93e20aba, 0xa0c0e52a, 0x223c43e0, 0x1b121d17, 0x90e0b0d, 0x8bf2adc7, 0xb62db9a8, 0x1e14c8a9, 0xf1578519, 0x75af4c07, 0x99eebbdd, 0x7fa3fd60, 0x1f79f26, 0x725cbcf5, 0x6644c53b, 0xfb5b347e, 0x438b7629, 0x23cbdcc6, 0xedb668fc, 0xe4b863f1, 0x31d7cadc, 0x63421085, 0x97134022, 0xc6842011, 0x4a857d24, 0xbbd2f83d, 0xf9ae1132, 0x29c76da1, 0x9e1d4b2f, 0xb2dcf330, 0x860dec52, 0xc177d0e3, 0xb32b6c16, 0x70a999b9, 0x9411fa48, 0xe9472264, 0xfca8c48c, 0xf0a01a3f, 0x7d56d82c, 0x3322ef90, 0x4987c74e, 0x38d9c1d1, 0xca8cfea2, 0xd498360b, 0xf5a6cf81, 0x7aa528de, 0xb7da268e, 0xad3fa4bf, 0x3a2ce49d, 0x78500d92, 0x5f6a9bcc, 0x7e546246, 0x8df6c213, 0xd890e8b8, 0x392e5ef7, 0xc382f5af, 0x5d9fbe80, 0xd0697c93, 0xd56fa92d, 0x25cfb312, 0xacc83b99, 0x1810a77d, 0x9ce86e63, 0x3bdb7bbb, 0x26cd0978, 0x596ef418, 0x9aec01b7, 0x4f83a89a, 0x95e6656e, 0xffaa7ee6, 0xbc2108cf, 0x15efe6e8, 0xe7bad99b, 0x6f4ace36, 0x9fead409, 0xb029d67c, 0xa431afb2, 0x3f2a3123, 0xa5c63094, 0xa235c066, 0x4e7437bc, 0x82fca6ca, 0x90e0b0d0, 0xa73315d8, 0x4f14a98, 0xec41f7da, 0xcd7f0e50, 0x91172ff6, 0x4d768dd6, 0xef434db0, 0xaacc544d, 0x96e4df04, 0xd19ee3b5, 0x6a4c1b88, 0x2cc1b81f, 0x65467f51, 0x5e9d04ea, 0x8c015d35, 0x87fa7374, 0xbfb2e41, 0x67b35a1d, 0xdb9252d2, 0x10e93356, 0xd66d1347, 0xd79a8c61, 0xa1377a0c, 0xf8598e14, 0x13eb893c, 0xa9ceee27, 0x61b735c9, 0x1ce1ede5, 0x477a3cb1, 0xd29c59df, 0xf2553f73, 0x141879ce, 0xc773bf37, 0xf753eacd, 0xfd5f5baa, 0x3ddf146f, 0x447886db, 0xafca81f3, 0x68b93ec4, 0x24382c34, 0xa3c25f40, 0x1d1672c3, 0xe2bc0c25, 0x3c288b49, 0xdff4195, 0xa8397101, 0xc08deb3, 0xb4d89ce4, 0x566490c1, 0xcb7b6184, 0x32d570b6, 0x6c48745c, 0xb8d04257] + @usableFromInline static let T3: Array = [0xc6a56363, 0xf8847c7c, 0xee997777, 0xf68d7b7b, 0xff0df2f2, 0xd6bd6b6b, 0xdeb16f6f, 0x9154c5c5, 0x60503030, 0x2030101, 0xcea96767, 0x567d2b2b, 0xe719fefe, 0xb562d7d7, 0x4de6abab, 0xec9a7676, 0x8f45caca, 0x1f9d8282, 0x8940c9c9, 0xfa877d7d, 0xef15fafa, 0xb2eb5959, 0x8ec94747, 0xfb0bf0f0, 0x41ecadad, 0xb367d4d4, 0x5ffda2a2, 0x45eaafaf, 0x23bf9c9c, 0x53f7a4a4, 0xe4967272, 0x9b5bc0c0, 0x75c2b7b7, 0xe11cfdfd, 0x3dae9393, 0x4c6a2626, 0x6c5a3636, 0x7e413f3f, 0xf502f7f7, 0x834fcccc, 0x685c3434, 0x51f4a5a5, 0xd134e5e5, 0xf908f1f1, 0xe2937171, 0xab73d8d8, 0x62533131, 0x2a3f1515, 0x80c0404, 0x9552c7c7, 0x46652323, 0x9d5ec3c3, 0x30281818, 0x37a19696, 0xa0f0505, 0x2fb59a9a, 0xe090707, 0x24361212, 0x1b9b8080, 0xdf3de2e2, 0xcd26ebeb, 0x4e692727, 0x7fcdb2b2, 0xea9f7575, 0x121b0909, 0x1d9e8383, 0x58742c2c, 0x342e1a1a, 0x362d1b1b, 0xdcb26e6e, 0xb4ee5a5a, 0x5bfba0a0, 0xa4f65252, 0x764d3b3b, 0xb761d6d6, 0x7dceb3b3, 0x527b2929, 0xdd3ee3e3, 0x5e712f2f, 0x13978484, 0xa6f55353, 0xb968d1d1, 0x0, 0xc12ceded, 0x40602020, 0xe31ffcfc, 0x79c8b1b1, 0xb6ed5b5b, 0xd4be6a6a, 0x8d46cbcb, 0x67d9bebe, 0x724b3939, 0x94de4a4a, 0x98d44c4c, 0xb0e85858, 0x854acfcf, 0xbb6bd0d0, 0xc52aefef, 0x4fe5aaaa, 0xed16fbfb, 0x86c54343, 0x9ad74d4d, 0x66553333, 0x11948585, 0x8acf4545, 0xe910f9f9, 0x4060202, 0xfe817f7f, 0xa0f05050, 0x78443c3c, 0x25ba9f9f, 0x4be3a8a8, 0xa2f35151, 0x5dfea3a3, 0x80c04040, 0x58a8f8f, 0x3fad9292, 0x21bc9d9d, 0x70483838, 0xf104f5f5, 0x63dfbcbc, 0x77c1b6b6, 0xaf75dada, 0x42632121, 0x20301010, 0xe51affff, 0xfd0ef3f3, 0xbf6dd2d2, 0x814ccdcd, 0x18140c0c, 0x26351313, 0xc32fecec, 0xbee15f5f, 0x35a29797, 0x88cc4444, 0x2e391717, 0x9357c4c4, 0x55f2a7a7, 0xfc827e7e, 0x7a473d3d, 0xc8ac6464, 0xbae75d5d, 0x322b1919, 0xe6957373, 0xc0a06060, 0x19988181, 0x9ed14f4f, 0xa37fdcdc, 0x44662222, 0x547e2a2a, 0x3bab9090, 0xb838888, 0x8cca4646, 0xc729eeee, 0x6bd3b8b8, 0x283c1414, 0xa779dede, 0xbce25e5e, 0x161d0b0b, 0xad76dbdb, 0xdb3be0e0, 0x64563232, 0x744e3a3a, 0x141e0a0a, 0x92db4949, 0xc0a0606, 0x486c2424, 0xb8e45c5c, 0x9f5dc2c2, 0xbd6ed3d3, 0x43efacac, 0xc4a66262, 0x39a89191, 0x31a49595, 0xd337e4e4, 0xf28b7979, 0xd532e7e7, 0x8b43c8c8, 0x6e593737, 0xdab76d6d, 0x18c8d8d, 0xb164d5d5, 0x9cd24e4e, 0x49e0a9a9, 0xd8b46c6c, 0xacfa5656, 0xf307f4f4, 0xcf25eaea, 0xcaaf6565, 0xf48e7a7a, 0x47e9aeae, 0x10180808, 0x6fd5baba, 0xf0887878, 0x4a6f2525, 0x5c722e2e, 0x38241c1c, 0x57f1a6a6, 0x73c7b4b4, 0x9751c6c6, 0xcb23e8e8, 0xa17cdddd, 0xe89c7474, 0x3e211f1f, 0x96dd4b4b, 0x61dcbdbd, 0xd868b8b, 0xf858a8a, 0xe0907070, 0x7c423e3e, 0x71c4b5b5, 0xccaa6666, 0x90d84848, 0x6050303, 0xf701f6f6, 0x1c120e0e, 0xc2a36161, 0x6a5f3535, 0xaef95757, 0x69d0b9b9, 0x17918686, 0x9958c1c1, 0x3a271d1d, 0x27b99e9e, 0xd938e1e1, 0xeb13f8f8, 0x2bb39898, 0x22331111, 0xd2bb6969, 0xa970d9d9, 0x7898e8e, 0x33a79494, 0x2db69b9b, 0x3c221e1e, 0x15928787, 0xc920e9e9, 0x8749cece, 0xaaff5555, 0x50782828, 0xa57adfdf, 0x38f8c8c, 0x59f8a1a1, 0x9808989, 0x1a170d0d, 0x65dabfbf, 0xd731e6e6, 0x84c64242, 0xd0b86868, 0x82c34141, 0x29b09999, 0x5a772d2d, 0x1e110f0f, 0x7bcbb0b0, 0xa8fc5454, 0x6dd6bbbb, 0x2c3a1616] + @usableFromInline static let T3_INV: Array = [0x5150a7f4, 0x7e536541, 0x1ac3a417, 0x3a965e27, 0x3bcb6bab, 0x1ff1459d, 0xacab58fa, 0x4b9303e3, 0x2055fa30, 0xadf66d76, 0x889176cc, 0xf5254c02, 0x4ffcd7e5, 0xc5d7cb2a, 0x26804435, 0xb58fa362, 0xde495ab1, 0x25671bba, 0x45980eea, 0x5de1c0fe, 0xc302752f, 0x8112f04c, 0x8da39746, 0x6bc6f9d3, 0x3e75f8f, 0x15959c92, 0xbfeb7a6d, 0x95da5952, 0xd42d83be, 0x58d32174, 0x492969e0, 0x8e44c8c9, 0x756a89c2, 0xf478798e, 0x996b3e58, 0x27dd71b9, 0xbeb64fe1, 0xf017ad88, 0xc966ac20, 0x7db43ace, 0x63184adf, 0xe582311a, 0x97603351, 0x62457f53, 0xb1e07764, 0xbb84ae6b, 0xfe1ca081, 0xf9942b08, 0x70586848, 0x8f19fd45, 0x94876cde, 0x52b7f87b, 0xab23d373, 0x72e2024b, 0xe3578f1f, 0x662aab55, 0xb20728eb, 0x2f03c2b5, 0x869a7bc5, 0xd3a50837, 0x30f28728, 0x23b2a5bf, 0x2ba6a03, 0xed5c8216, 0x8a2b1ccf, 0xa792b479, 0xf3f0f207, 0x4ea1e269, 0x65cdf4da, 0x6d5be05, 0xd11f6234, 0xc48afea6, 0x349d532e, 0xa2a055f3, 0x532e18a, 0xa475ebf6, 0xb39ec83, 0x40aaef60, 0x5e069f71, 0xbd51106e, 0x3ef98a21, 0x963d06dd, 0xddae053e, 0x4d46bde6, 0x91b58d54, 0x71055dc4, 0x46fd406, 0x60ff1550, 0x1924fb98, 0xd697e9bd, 0x89cc4340, 0x67779ed9, 0xb0bd42e8, 0x7888b89, 0xe7385b19, 0x79dbeec8, 0xa1470a7c, 0x7ce90f42, 0xf8c91e84, 0x0, 0x9838680, 0x3248ed2b, 0x1eac7011, 0x6c4e725a, 0xfdfbff0e, 0xf563885, 0x3d1ed5ae, 0x3627392d, 0xa64d90f, 0x6821a65c, 0x9bd1545b, 0x243a2e36, 0xcb1670a, 0x930fe757, 0xb4d296ee, 0x1b9e919b, 0x804fc5c0, 0x61a220dc, 0x5a694b77, 0x1c161a12, 0xe20aba93, 0xc0e52aa0, 0x3c43e022, 0x121d171b, 0xe0b0d09, 0xf2adc78b, 0x2db9a8b6, 0x14c8a91e, 0x578519f1, 0xaf4c0775, 0xeebbdd99, 0xa3fd607f, 0xf79f2601, 0x5cbcf572, 0x44c53b66, 0x5b347efb, 0x8b762943, 0xcbdcc623, 0xb668fced, 0xb863f1e4, 0xd7cadc31, 0x42108563, 0x13402297, 0x842011c6, 0x857d244a, 0xd2f83dbb, 0xae1132f9, 0xc76da129, 0x1d4b2f9e, 0xdcf330b2, 0xdec5286, 0x77d0e3c1, 0x2b6c16b3, 0xa999b970, 0x11fa4894, 0x472264e9, 0xa8c48cfc, 0xa01a3ff0, 0x56d82c7d, 0x22ef9033, 0x87c74e49, 0xd9c1d138, 0x8cfea2ca, 0x98360bd4, 0xa6cf81f5, 0xa528de7a, 0xda268eb7, 0x3fa4bfad, 0x2ce49d3a, 0x500d9278, 0x6a9bcc5f, 0x5462467e, 0xf6c2138d, 0x90e8b8d8, 0x2e5ef739, 0x82f5afc3, 0x9fbe805d, 0x697c93d0, 0x6fa92dd5, 0xcfb31225, 0xc83b99ac, 0x10a77d18, 0xe86e639c, 0xdb7bbb3b, 0xcd097826, 0x6ef41859, 0xec01b79a, 0x83a89a4f, 0xe6656e95, 0xaa7ee6ff, 0x2108cfbc, 0xefe6e815, 0xbad99be7, 0x4ace366f, 0xead4099f, 0x29d67cb0, 0x31afb2a4, 0x2a31233f, 0xc63094a5, 0x35c066a2, 0x7437bc4e, 0xfca6ca82, 0xe0b0d090, 0x3315d8a7, 0xf14a9804, 0x41f7daec, 0x7f0e50cd, 0x172ff691, 0x768dd64d, 0x434db0ef, 0xcc544daa, 0xe4df0496, 0x9ee3b5d1, 0x4c1b886a, 0xc1b81f2c, 0x467f5165, 0x9d04ea5e, 0x15d358c, 0xfa737487, 0xfb2e410b, 0xb35a1d67, 0x9252d2db, 0xe9335610, 0x6d1347d6, 0x9a8c61d7, 0x377a0ca1, 0x598e14f8, 0xeb893c13, 0xceee27a9, 0xb735c961, 0xe1ede51c, 0x7a3cb147, 0x9c59dfd2, 0x553f73f2, 0x1879ce14, 0x73bf37c7, 0x53eacdf7, 0x5f5baafd, 0xdf146f3d, 0x7886db44, 0xca81f3af, 0xb93ec468, 0x382c3424, 0xc25f40a3, 0x1672c31d, 0xbc0c25e2, 0x288b493c, 0xff41950d, 0x397101a8, 0x8deb30c, 0xd89ce4b4, 0x6490c156, 0x7b6184cb, 0xd570b632, 0x48745c6c, 0xd04257b8] + @usableFromInline static let U1: Array = [0x0, 0xb0d090e, 0x161a121c, 0x1d171b12, 0x2c342438, 0x27392d36, 0x3a2e3624, 0x31233f2a, 0x58684870, 0x5365417e, 0x4e725a6c, 0x457f5362, 0x745c6c48, 0x7f516546, 0x62467e54, 0x694b775a, 0xb0d090e0, 0xbbdd99ee, 0xa6ca82fc, 0xadc78bf2, 0x9ce4b4d8, 0x97e9bdd6, 0x8afea6c4, 0x81f3afca, 0xe8b8d890, 0xe3b5d19e, 0xfea2ca8c, 0xf5afc382, 0xc48cfca8, 0xcf81f5a6, 0xd296eeb4, 0xd99be7ba, 0x7bbb3bdb, 0x70b632d5, 0x6da129c7, 0x66ac20c9, 0x578f1fe3, 0x5c8216ed, 0x41950dff, 0x4a9804f1, 0x23d373ab, 0x28de7aa5, 0x35c961b7, 0x3ec468b9, 0xfe75793, 0x4ea5e9d, 0x19fd458f, 0x12f04c81, 0xcb6bab3b, 0xc066a235, 0xdd71b927, 0xd67cb029, 0xe75f8f03, 0xec52860d, 0xf1459d1f, 0xfa489411, 0x9303e34b, 0x980eea45, 0x8519f157, 0x8e14f859, 0xbf37c773, 0xb43ace7d, 0xa92dd56f, 0xa220dc61, 0xf66d76ad, 0xfd607fa3, 0xe07764b1, 0xeb7a6dbf, 0xda595295, 0xd1545b9b, 0xcc434089, 0xc74e4987, 0xae053edd, 0xa50837d3, 0xb81f2cc1, 0xb31225cf, 0x82311ae5, 0x893c13eb, 0x942b08f9, 0x9f2601f7, 0x46bde64d, 0x4db0ef43, 0x50a7f451, 0x5baafd5f, 0x6a89c275, 0x6184cb7b, 0x7c93d069, 0x779ed967, 0x1ed5ae3d, 0x15d8a733, 0x8cfbc21, 0x3c2b52f, 0x32e18a05, 0x39ec830b, 0x24fb9819, 0x2ff69117, 0x8dd64d76, 0x86db4478, 0x9bcc5f6a, 0x90c15664, 0xa1e2694e, 0xaaef6040, 0xb7f87b52, 0xbcf5725c, 0xd5be0506, 0xdeb30c08, 0xc3a4171a, 0xc8a91e14, 0xf98a213e, 0xf2872830, 0xef903322, 0xe49d3a2c, 0x3d06dd96, 0x360bd498, 0x2b1ccf8a, 0x2011c684, 0x1132f9ae, 0x1a3ff0a0, 0x728ebb2, 0xc25e2bc, 0x656e95e6, 0x6e639ce8, 0x737487fa, 0x78798ef4, 0x495ab1de, 0x4257b8d0, 0x5f40a3c2, 0x544daacc, 0xf7daec41, 0xfcd7e54f, 0xe1c0fe5d, 0xeacdf753, 0xdbeec879, 0xd0e3c177, 0xcdf4da65, 0xc6f9d36b, 0xafb2a431, 0xa4bfad3f, 0xb9a8b62d, 0xb2a5bf23, 0x83868009, 0x888b8907, 0x959c9215, 0x9e919b1b, 0x470a7ca1, 0x4c0775af, 0x51106ebd, 0x5a1d67b3, 0x6b3e5899, 0x60335197, 0x7d244a85, 0x7629438b, 0x1f6234d1, 0x146f3ddf, 0x97826cd, 0x2752fc3, 0x335610e9, 0x385b19e7, 0x254c02f5, 0x2e410bfb, 0x8c61d79a, 0x876cde94, 0x9a7bc586, 0x9176cc88, 0xa055f3a2, 0xab58faac, 0xb64fe1be, 0xbd42e8b0, 0xd4099fea, 0xdf0496e4, 0xc2138df6, 0xc91e84f8, 0xf83dbbd2, 0xf330b2dc, 0xee27a9ce, 0xe52aa0c0, 0x3cb1477a, 0x37bc4e74, 0x2aab5566, 0x21a65c68, 0x10856342, 0x1b886a4c, 0x69f715e, 0xd927850, 0x64d90f0a, 0x6fd40604, 0x72c31d16, 0x79ce1418, 0x48ed2b32, 0x43e0223c, 0x5ef7392e, 0x55fa3020, 0x1b79aec, 0xaba93e2, 0x17ad88f0, 0x1ca081fe, 0x2d83bed4, 0x268eb7da, 0x3b99acc8, 0x3094a5c6, 0x59dfd29c, 0x52d2db92, 0x4fc5c080, 0x44c8c98e, 0x75ebf6a4, 0x7ee6ffaa, 0x63f1e4b8, 0x68fcedb6, 0xb1670a0c, 0xba6a0302, 0xa77d1810, 0xac70111e, 0x9d532e34, 0x965e273a, 0x8b493c28, 0x80443526, 0xe90f427c, 0xe2024b72, 0xff155060, 0xf418596e, 0xc53b6644, 0xce366f4a, 0xd3217458, 0xd82c7d56, 0x7a0ca137, 0x7101a839, 0x6c16b32b, 0x671bba25, 0x5638850f, 0x5d358c01, 0x40229713, 0x4b2f9e1d, 0x2264e947, 0x2969e049, 0x347efb5b, 0x3f73f255, 0xe50cd7f, 0x55dc471, 0x184adf63, 0x1347d66d, 0xcadc31d7, 0xc1d138d9, 0xdcc623cb, 0xd7cb2ac5, 0xe6e815ef, 0xede51ce1, 0xf0f207f3, 0xfbff0efd, 0x92b479a7, 0x99b970a9, 0x84ae6bbb, 0x8fa362b5, 0xbe805d9f, 0xb58d5491, 0xa89a4f83, 0xa397468d] + @usableFromInline static let U2: Array = [0x0, 0xd090e0b, 0x1a121c16, 0x171b121d, 0x3424382c, 0x392d3627, 0x2e36243a, 0x233f2a31, 0x68487058, 0x65417e53, 0x725a6c4e, 0x7f536245, 0x5c6c4874, 0x5165467f, 0x467e5462, 0x4b775a69, 0xd090e0b0, 0xdd99eebb, 0xca82fca6, 0xc78bf2ad, 0xe4b4d89c, 0xe9bdd697, 0xfea6c48a, 0xf3afca81, 0xb8d890e8, 0xb5d19ee3, 0xa2ca8cfe, 0xafc382f5, 0x8cfca8c4, 0x81f5a6cf, 0x96eeb4d2, 0x9be7bad9, 0xbb3bdb7b, 0xb632d570, 0xa129c76d, 0xac20c966, 0x8f1fe357, 0x8216ed5c, 0x950dff41, 0x9804f14a, 0xd373ab23, 0xde7aa528, 0xc961b735, 0xc468b93e, 0xe757930f, 0xea5e9d04, 0xfd458f19, 0xf04c8112, 0x6bab3bcb, 0x66a235c0, 0x71b927dd, 0x7cb029d6, 0x5f8f03e7, 0x52860dec, 0x459d1ff1, 0x489411fa, 0x3e34b93, 0xeea4598, 0x19f15785, 0x14f8598e, 0x37c773bf, 0x3ace7db4, 0x2dd56fa9, 0x20dc61a2, 0x6d76adf6, 0x607fa3fd, 0x7764b1e0, 0x7a6dbfeb, 0x595295da, 0x545b9bd1, 0x434089cc, 0x4e4987c7, 0x53eddae, 0x837d3a5, 0x1f2cc1b8, 0x1225cfb3, 0x311ae582, 0x3c13eb89, 0x2b08f994, 0x2601f79f, 0xbde64d46, 0xb0ef434d, 0xa7f45150, 0xaafd5f5b, 0x89c2756a, 0x84cb7b61, 0x93d0697c, 0x9ed96777, 0xd5ae3d1e, 0xd8a73315, 0xcfbc2108, 0xc2b52f03, 0xe18a0532, 0xec830b39, 0xfb981924, 0xf691172f, 0xd64d768d, 0xdb447886, 0xcc5f6a9b, 0xc1566490, 0xe2694ea1, 0xef6040aa, 0xf87b52b7, 0xf5725cbc, 0xbe0506d5, 0xb30c08de, 0xa4171ac3, 0xa91e14c8, 0x8a213ef9, 0x872830f2, 0x903322ef, 0x9d3a2ce4, 0x6dd963d, 0xbd49836, 0x1ccf8a2b, 0x11c68420, 0x32f9ae11, 0x3ff0a01a, 0x28ebb207, 0x25e2bc0c, 0x6e95e665, 0x639ce86e, 0x7487fa73, 0x798ef478, 0x5ab1de49, 0x57b8d042, 0x40a3c25f, 0x4daacc54, 0xdaec41f7, 0xd7e54ffc, 0xc0fe5de1, 0xcdf753ea, 0xeec879db, 0xe3c177d0, 0xf4da65cd, 0xf9d36bc6, 0xb2a431af, 0xbfad3fa4, 0xa8b62db9, 0xa5bf23b2, 0x86800983, 0x8b890788, 0x9c921595, 0x919b1b9e, 0xa7ca147, 0x775af4c, 0x106ebd51, 0x1d67b35a, 0x3e58996b, 0x33519760, 0x244a857d, 0x29438b76, 0x6234d11f, 0x6f3ddf14, 0x7826cd09, 0x752fc302, 0x5610e933, 0x5b19e738, 0x4c02f525, 0x410bfb2e, 0x61d79a8c, 0x6cde9487, 0x7bc5869a, 0x76cc8891, 0x55f3a2a0, 0x58faacab, 0x4fe1beb6, 0x42e8b0bd, 0x99fead4, 0x496e4df, 0x138df6c2, 0x1e84f8c9, 0x3dbbd2f8, 0x30b2dcf3, 0x27a9ceee, 0x2aa0c0e5, 0xb1477a3c, 0xbc4e7437, 0xab55662a, 0xa65c6821, 0x85634210, 0x886a4c1b, 0x9f715e06, 0x9278500d, 0xd90f0a64, 0xd406046f, 0xc31d1672, 0xce141879, 0xed2b3248, 0xe0223c43, 0xf7392e5e, 0xfa302055, 0xb79aec01, 0xba93e20a, 0xad88f017, 0xa081fe1c, 0x83bed42d, 0x8eb7da26, 0x99acc83b, 0x94a5c630, 0xdfd29c59, 0xd2db9252, 0xc5c0804f, 0xc8c98e44, 0xebf6a475, 0xe6ffaa7e, 0xf1e4b863, 0xfcedb668, 0x670a0cb1, 0x6a0302ba, 0x7d1810a7, 0x70111eac, 0x532e349d, 0x5e273a96, 0x493c288b, 0x44352680, 0xf427ce9, 0x24b72e2, 0x155060ff, 0x18596ef4, 0x3b6644c5, 0x366f4ace, 0x217458d3, 0x2c7d56d8, 0xca1377a, 0x1a83971, 0x16b32b6c, 0x1bba2567, 0x38850f56, 0x358c015d, 0x22971340, 0x2f9e1d4b, 0x64e94722, 0x69e04929, 0x7efb5b34, 0x73f2553f, 0x50cd7f0e, 0x5dc47105, 0x4adf6318, 0x47d66d13, 0xdc31d7ca, 0xd138d9c1, 0xc623cbdc, 0xcb2ac5d7, 0xe815efe6, 0xe51ce1ed, 0xf207f3f0, 0xff0efdfb, 0xb479a792, 0xb970a999, 0xae6bbb84, 0xa362b58f, 0x805d9fbe, 0x8d5491b5, 0x9a4f83a8, 0x97468da3] + @usableFromInline static let U3: Array = [0x0, 0x90e0b0d, 0x121c161a, 0x1b121d17, 0x24382c34, 0x2d362739, 0x36243a2e, 0x3f2a3123, 0x48705868, 0x417e5365, 0x5a6c4e72, 0x5362457f, 0x6c48745c, 0x65467f51, 0x7e546246, 0x775a694b, 0x90e0b0d0, 0x99eebbdd, 0x82fca6ca, 0x8bf2adc7, 0xb4d89ce4, 0xbdd697e9, 0xa6c48afe, 0xafca81f3, 0xd890e8b8, 0xd19ee3b5, 0xca8cfea2, 0xc382f5af, 0xfca8c48c, 0xf5a6cf81, 0xeeb4d296, 0xe7bad99b, 0x3bdb7bbb, 0x32d570b6, 0x29c76da1, 0x20c966ac, 0x1fe3578f, 0x16ed5c82, 0xdff4195, 0x4f14a98, 0x73ab23d3, 0x7aa528de, 0x61b735c9, 0x68b93ec4, 0x57930fe7, 0x5e9d04ea, 0x458f19fd, 0x4c8112f0, 0xab3bcb6b, 0xa235c066, 0xb927dd71, 0xb029d67c, 0x8f03e75f, 0x860dec52, 0x9d1ff145, 0x9411fa48, 0xe34b9303, 0xea45980e, 0xf1578519, 0xf8598e14, 0xc773bf37, 0xce7db43a, 0xd56fa92d, 0xdc61a220, 0x76adf66d, 0x7fa3fd60, 0x64b1e077, 0x6dbfeb7a, 0x5295da59, 0x5b9bd154, 0x4089cc43, 0x4987c74e, 0x3eddae05, 0x37d3a508, 0x2cc1b81f, 0x25cfb312, 0x1ae58231, 0x13eb893c, 0x8f9942b, 0x1f79f26, 0xe64d46bd, 0xef434db0, 0xf45150a7, 0xfd5f5baa, 0xc2756a89, 0xcb7b6184, 0xd0697c93, 0xd967779e, 0xae3d1ed5, 0xa73315d8, 0xbc2108cf, 0xb52f03c2, 0x8a0532e1, 0x830b39ec, 0x981924fb, 0x91172ff6, 0x4d768dd6, 0x447886db, 0x5f6a9bcc, 0x566490c1, 0x694ea1e2, 0x6040aaef, 0x7b52b7f8, 0x725cbcf5, 0x506d5be, 0xc08deb3, 0x171ac3a4, 0x1e14c8a9, 0x213ef98a, 0x2830f287, 0x3322ef90, 0x3a2ce49d, 0xdd963d06, 0xd498360b, 0xcf8a2b1c, 0xc6842011, 0xf9ae1132, 0xf0a01a3f, 0xebb20728, 0xe2bc0c25, 0x95e6656e, 0x9ce86e63, 0x87fa7374, 0x8ef47879, 0xb1de495a, 0xb8d04257, 0xa3c25f40, 0xaacc544d, 0xec41f7da, 0xe54ffcd7, 0xfe5de1c0, 0xf753eacd, 0xc879dbee, 0xc177d0e3, 0xda65cdf4, 0xd36bc6f9, 0xa431afb2, 0xad3fa4bf, 0xb62db9a8, 0xbf23b2a5, 0x80098386, 0x8907888b, 0x9215959c, 0x9b1b9e91, 0x7ca1470a, 0x75af4c07, 0x6ebd5110, 0x67b35a1d, 0x58996b3e, 0x51976033, 0x4a857d24, 0x438b7629, 0x34d11f62, 0x3ddf146f, 0x26cd0978, 0x2fc30275, 0x10e93356, 0x19e7385b, 0x2f5254c, 0xbfb2e41, 0xd79a8c61, 0xde94876c, 0xc5869a7b, 0xcc889176, 0xf3a2a055, 0xfaacab58, 0xe1beb64f, 0xe8b0bd42, 0x9fead409, 0x96e4df04, 0x8df6c213, 0x84f8c91e, 0xbbd2f83d, 0xb2dcf330, 0xa9ceee27, 0xa0c0e52a, 0x477a3cb1, 0x4e7437bc, 0x55662aab, 0x5c6821a6, 0x63421085, 0x6a4c1b88, 0x715e069f, 0x78500d92, 0xf0a64d9, 0x6046fd4, 0x1d1672c3, 0x141879ce, 0x2b3248ed, 0x223c43e0, 0x392e5ef7, 0x302055fa, 0x9aec01b7, 0x93e20aba, 0x88f017ad, 0x81fe1ca0, 0xbed42d83, 0xb7da268e, 0xacc83b99, 0xa5c63094, 0xd29c59df, 0xdb9252d2, 0xc0804fc5, 0xc98e44c8, 0xf6a475eb, 0xffaa7ee6, 0xe4b863f1, 0xedb668fc, 0xa0cb167, 0x302ba6a, 0x1810a77d, 0x111eac70, 0x2e349d53, 0x273a965e, 0x3c288b49, 0x35268044, 0x427ce90f, 0x4b72e202, 0x5060ff15, 0x596ef418, 0x6644c53b, 0x6f4ace36, 0x7458d321, 0x7d56d82c, 0xa1377a0c, 0xa8397101, 0xb32b6c16, 0xba25671b, 0x850f5638, 0x8c015d35, 0x97134022, 0x9e1d4b2f, 0xe9472264, 0xe0492969, 0xfb5b347e, 0xf2553f73, 0xcd7f0e50, 0xc471055d, 0xdf63184a, 0xd66d1347, 0x31d7cadc, 0x38d9c1d1, 0x23cbdcc6, 0x2ac5d7cb, 0x15efe6e8, 0x1ce1ede5, 0x7f3f0f2, 0xefdfbff, 0x79a792b4, 0x70a999b9, 0x6bbb84ae, 0x62b58fa3, 0x5d9fbe80, 0x5491b58d, 0x4f83a89a, 0x468da397] + @usableFromInline static let U4: Array = [0x0, 0xe0b0d09, 0x1c161a12, 0x121d171b, 0x382c3424, 0x3627392d, 0x243a2e36, 0x2a31233f, 0x70586848, 0x7e536541, 0x6c4e725a, 0x62457f53, 0x48745c6c, 0x467f5165, 0x5462467e, 0x5a694b77, 0xe0b0d090, 0xeebbdd99, 0xfca6ca82, 0xf2adc78b, 0xd89ce4b4, 0xd697e9bd, 0xc48afea6, 0xca81f3af, 0x90e8b8d8, 0x9ee3b5d1, 0x8cfea2ca, 0x82f5afc3, 0xa8c48cfc, 0xa6cf81f5, 0xb4d296ee, 0xbad99be7, 0xdb7bbb3b, 0xd570b632, 0xc76da129, 0xc966ac20, 0xe3578f1f, 0xed5c8216, 0xff41950d, 0xf14a9804, 0xab23d373, 0xa528de7a, 0xb735c961, 0xb93ec468, 0x930fe757, 0x9d04ea5e, 0x8f19fd45, 0x8112f04c, 0x3bcb6bab, 0x35c066a2, 0x27dd71b9, 0x29d67cb0, 0x3e75f8f, 0xdec5286, 0x1ff1459d, 0x11fa4894, 0x4b9303e3, 0x45980eea, 0x578519f1, 0x598e14f8, 0x73bf37c7, 0x7db43ace, 0x6fa92dd5, 0x61a220dc, 0xadf66d76, 0xa3fd607f, 0xb1e07764, 0xbfeb7a6d, 0x95da5952, 0x9bd1545b, 0x89cc4340, 0x87c74e49, 0xddae053e, 0xd3a50837, 0xc1b81f2c, 0xcfb31225, 0xe582311a, 0xeb893c13, 0xf9942b08, 0xf79f2601, 0x4d46bde6, 0x434db0ef, 0x5150a7f4, 0x5f5baafd, 0x756a89c2, 0x7b6184cb, 0x697c93d0, 0x67779ed9, 0x3d1ed5ae, 0x3315d8a7, 0x2108cfbc, 0x2f03c2b5, 0x532e18a, 0xb39ec83, 0x1924fb98, 0x172ff691, 0x768dd64d, 0x7886db44, 0x6a9bcc5f, 0x6490c156, 0x4ea1e269, 0x40aaef60, 0x52b7f87b, 0x5cbcf572, 0x6d5be05, 0x8deb30c, 0x1ac3a417, 0x14c8a91e, 0x3ef98a21, 0x30f28728, 0x22ef9033, 0x2ce49d3a, 0x963d06dd, 0x98360bd4, 0x8a2b1ccf, 0x842011c6, 0xae1132f9, 0xa01a3ff0, 0xb20728eb, 0xbc0c25e2, 0xe6656e95, 0xe86e639c, 0xfa737487, 0xf478798e, 0xde495ab1, 0xd04257b8, 0xc25f40a3, 0xcc544daa, 0x41f7daec, 0x4ffcd7e5, 0x5de1c0fe, 0x53eacdf7, 0x79dbeec8, 0x77d0e3c1, 0x65cdf4da, 0x6bc6f9d3, 0x31afb2a4, 0x3fa4bfad, 0x2db9a8b6, 0x23b2a5bf, 0x9838680, 0x7888b89, 0x15959c92, 0x1b9e919b, 0xa1470a7c, 0xaf4c0775, 0xbd51106e, 0xb35a1d67, 0x996b3e58, 0x97603351, 0x857d244a, 0x8b762943, 0xd11f6234, 0xdf146f3d, 0xcd097826, 0xc302752f, 0xe9335610, 0xe7385b19, 0xf5254c02, 0xfb2e410b, 0x9a8c61d7, 0x94876cde, 0x869a7bc5, 0x889176cc, 0xa2a055f3, 0xacab58fa, 0xbeb64fe1, 0xb0bd42e8, 0xead4099f, 0xe4df0496, 0xf6c2138d, 0xf8c91e84, 0xd2f83dbb, 0xdcf330b2, 0xceee27a9, 0xc0e52aa0, 0x7a3cb147, 0x7437bc4e, 0x662aab55, 0x6821a65c, 0x42108563, 0x4c1b886a, 0x5e069f71, 0x500d9278, 0xa64d90f, 0x46fd406, 0x1672c31d, 0x1879ce14, 0x3248ed2b, 0x3c43e022, 0x2e5ef739, 0x2055fa30, 0xec01b79a, 0xe20aba93, 0xf017ad88, 0xfe1ca081, 0xd42d83be, 0xda268eb7, 0xc83b99ac, 0xc63094a5, 0x9c59dfd2, 0x9252d2db, 0x804fc5c0, 0x8e44c8c9, 0xa475ebf6, 0xaa7ee6ff, 0xb863f1e4, 0xb668fced, 0xcb1670a, 0x2ba6a03, 0x10a77d18, 0x1eac7011, 0x349d532e, 0x3a965e27, 0x288b493c, 0x26804435, 0x7ce90f42, 0x72e2024b, 0x60ff1550, 0x6ef41859, 0x44c53b66, 0x4ace366f, 0x58d32174, 0x56d82c7d, 0x377a0ca1, 0x397101a8, 0x2b6c16b3, 0x25671bba, 0xf563885, 0x15d358c, 0x13402297, 0x1d4b2f9e, 0x472264e9, 0x492969e0, 0x5b347efb, 0x553f73f2, 0x7f0e50cd, 0x71055dc4, 0x63184adf, 0x6d1347d6, 0xd7cadc31, 0xd9c1d138, 0xcbdcc623, 0xc5d7cb2a, 0xefe6e815, 0xe1ede51c, 0xf3f0f207, 0xfdfbff0e, 0xa792b479, 0xa999b970, 0xbb84ae6b, 0xb58fa362, 0x9fbe805d, 0x91b58d54, 0x83a89a4f, 0x8da39746] + + /// Initialize AES with variant calculated out of key length: + /// - 16 bytes (AES-128) + /// - 24 bytes (AES-192) + /// - 32 bytes (AES-256) + /// + /// - parameter key: Key. Length of the key decides on AES variant. + /// - parameter iv: Initialization Vector (Optional for some blockMode values) + /// - parameter blockMode: Cipher mode of operation + /// - parameter padding: Padding method. .pkcs7, .noPadding, .zeroPadding, ... + /// + /// - throws: AES.Error + /// + /// - returns: Instance + public init(key: Array, blockMode: BlockMode, padding: Padding = .pkcs7) throws { + self.key = Key(bytes: key) + self.blockMode = blockMode + self.padding = padding + self.keySize = self.key.count + + // Validate key size + switch self.keySize * 8 { + case 128: + self.variant = .aes128 + case 192: + self.variant = .aes192 + case 256: + self.variant = .aes256 + default: + throw Error.invalidKeySize + } + + self.variantNb = self.variant.Nb + self.variantNk = self.variant.Nk + self.variantNr = self.variant.Nr + } + + @inlinable + internal func encrypt(block: ArraySlice) -> Array? { + if self.blockMode.options.contains(.paddingRequired) && block.count != AES.blockSize { + return Array(block) + } + + let rounds = self.variantNr + let rk = self.expandedKey + + let b00 = UInt32(block[block.startIndex.advanced(by: 0)]) + let b01 = UInt32(block[block.startIndex.advanced(by: 1)]) << 8 + let b02 = UInt32(block[block.startIndex.advanced(by: 2)]) << 16 + let b03 = UInt32(block[block.startIndex.advanced(by: 3)]) << 24 + var b0 = b00 | b01 | b02 | b03 + + let b10 = UInt32(block[block.startIndex.advanced(by: 4)]) + let b11 = UInt32(block[block.startIndex.advanced(by: 5)]) << 8 + let b12 = UInt32(block[block.startIndex.advanced(by: 6)]) << 16 + let b13 = UInt32(block[block.startIndex.advanced(by: 7)]) << 24 + var b1 = b10 | b11 | b12 | b13 + + let b20 = UInt32(block[block.startIndex.advanced(by: 8)]) + let b21 = UInt32(block[block.startIndex.advanced(by: 9)]) << 8 + let b22 = UInt32(block[block.startIndex.advanced(by: 10)]) << 16 + let b23 = UInt32(block[block.startIndex.advanced(by: 11)]) << 24 + var b2 = b20 | b21 | b22 | b23 + + let b30 = UInt32(block[block.startIndex.advanced(by: 12)]) + let b31 = UInt32(block[block.startIndex.advanced(by: 13)]) << 8 + let b32 = UInt32(block[block.startIndex.advanced(by: 14)]) << 16 + let b33 = UInt32(block[block.startIndex.advanced(by: 15)]) << 24 + var b3 = b30 | b31 | b32 | b33 + + let tLength = 4 + let t = UnsafeMutablePointer.allocate(capacity: tLength) + t.initialize(repeating: 0, count: tLength) + defer { + t.deinitialize(count: tLength) + t.deallocate() + } + + for r in 0..> 8) & 0xff)] + let lb02 = AES.T2[Int((t[2] >> 16) & 0xff)] + let lb03 = AES.T3[Int(t[3] >> 24)] + b0 = lb00 ^ lb01 ^ lb02 ^ lb03 + + let lb10 = AES.T0[Int(t[1] & 0xff)] + let lb11 = AES.T1[Int((t[2] >> 8) & 0xff)] + let lb12 = AES.T2[Int((t[3] >> 16) & 0xff)] + let lb13 = AES.T3[Int(t[0] >> 24)] + b1 = lb10 ^ lb11 ^ lb12 ^ lb13 + + let lb20 = AES.T0[Int(t[2] & 0xff)] + let lb21 = AES.T1[Int((t[3] >> 8) & 0xff)] + let lb22 = AES.T2[Int((t[0] >> 16) & 0xff)] + let lb23 = AES.T3[Int(t[1] >> 24)] + b2 = lb20 ^ lb21 ^ lb22 ^ lb23 + + let lb30 = AES.T0[Int(t[3] & 0xff)] + let lb31 = AES.T1[Int((t[0] >> 8) & 0xff)] + let lb32 = AES.T2[Int((t[1] >> 16) & 0xff)] + let lb33 = AES.T3[Int(t[2] >> 24)] + b3 = lb30 ^ lb31 ^ lb32 ^ lb33 + } + + // last round + let r = rounds - 1 + + t[0] = b0 ^ rk[r][0] + t[1] = b1 ^ rk[r][1] + t[2] = b2 ^ rk[r][2] + t[3] = b3 ^ rk[r][3] + + // rounds + b0 = F1(t[0], t[1], t[2], t[3]) ^ rk[rounds][0] + b1 = F1(t[1], t[2], t[3], t[0]) ^ rk[rounds][1] + b2 = F1(t[2], t[3], t[0], t[1]) ^ rk[rounds][2] + b3 = F1(t[3], t[0], t[1], t[2]) ^ rk[rounds][3] + + let encrypted: Array = [ + UInt8(b0 & 0xff), UInt8((b0 >> 8) & 0xff), UInt8((b0 >> 16) & 0xff), UInt8((b0 >> 24) & 0xff), + UInt8(b1 & 0xff), UInt8((b1 >> 8) & 0xff), UInt8((b1 >> 16) & 0xff), UInt8((b1 >> 24) & 0xff), + UInt8(b2 & 0xff), UInt8((b2 >> 8) & 0xff), UInt8((b2 >> 16) & 0xff), UInt8((b2 >> 24) & 0xff), + UInt8(b3 & 0xff), UInt8((b3 >> 8) & 0xff), UInt8((b3 >> 16) & 0xff), UInt8((b3 >> 24) & 0xff) + ] + return encrypted + } + + @usableFromInline + internal func decrypt(block: ArraySlice) -> Array? { + if self.blockMode.options.contains(.paddingRequired) && block.count != AES.blockSize { + return Array(block) + } + + let rounds = self.variantNr + let rk = self.expandedKeyInv + + // Save miliseconds by not using `block.toUInt32Array()` + let b00 = UInt32(block[block.startIndex.advanced(by: 0)]) + let b01 = UInt32(block[block.startIndex.advanced(by: 1)]) << 8 + let b02 = UInt32(block[block.startIndex.advanced(by: 2)]) << 16 + let b03 = UInt32(block[block.startIndex.advanced(by: 3)]) << 24 + var b0 = b00 | b01 | b02 | b03 + + let b10 = UInt32(block[block.startIndex.advanced(by: 4)]) + let b11 = UInt32(block[block.startIndex.advanced(by: 5)]) << 8 + let b12 = UInt32(block[block.startIndex.advanced(by: 6)]) << 16 + let b13 = UInt32(block[block.startIndex.advanced(by: 7)]) << 24 + var b1 = b10 | b11 | b12 | b13 + + let b20 = UInt32(block[block.startIndex.advanced(by: 8)]) + let b21 = UInt32(block[block.startIndex.advanced(by: 9)]) << 8 + let b22 = UInt32(block[block.startIndex.advanced(by: 10)]) << 16 + let b23 = UInt32(block[block.startIndex.advanced(by: 11)]) << 24 + var b2 = b20 | b21 | b22 | b23 + + let b30 = UInt32(block[block.startIndex.advanced(by: 12)]) + let b31 = UInt32(block[block.startIndex.advanced(by: 13)]) << 8 + let b32 = UInt32(block[block.startIndex.advanced(by: 14)]) << 16 + let b33 = UInt32(block[block.startIndex.advanced(by: 15)]) << 24 + var b3 = b30 | b31 | b32 | b33 + + let tLength = 4 + let t = UnsafeMutablePointer.allocate(capacity: tLength) + t.initialize(repeating: 0, count: tLength) + defer { + t.deinitialize(count: tLength) + t.deallocate() + } + + for r in (2...rounds).reversed() { + t[0] = b0 ^ rk[r][0] + t[1] = b1 ^ rk[r][1] + t[2] = b2 ^ rk[r][2] + t[3] = b3 ^ rk[r][3] + + let b00 = AES.T0_INV[Int(t[0] & 0xff)] + let b01 = AES.T1_INV[Int((t[3] >> 8) & 0xff)] + let b02 = AES.T2_INV[Int((t[2] >> 16) & 0xff)] + let b03 = AES.T3_INV[Int(t[1] >> 24)] + b0 = b00 ^ b01 ^ b02 ^ b03 + + let b10 = AES.T0_INV[Int(t[1] & 0xff)] + let b11 = AES.T1_INV[Int((t[0] >> 8) & 0xff)] + let b12 = AES.T2_INV[Int((t[3] >> 16) & 0xff)] + let b13 = AES.T3_INV[Int(t[2] >> 24)] + b1 = b10 ^ b11 ^ b12 ^ b13 + + let b20 = AES.T0_INV[Int(t[2] & 0xff)] + let b21 = AES.T1_INV[Int((t[1] >> 8) & 0xff)] + let b22 = AES.T2_INV[Int((t[0] >> 16) & 0xff)] + let b23 = AES.T3_INV[Int(t[3] >> 24)] + b2 = b20 ^ b21 ^ b22 ^ b23 + + let b30 = AES.T0_INV[Int(t[3] & 0xff)] + let b31 = AES.T1_INV[Int((t[2] >> 8) & 0xff)] + let b32 = AES.T2_INV[Int((t[1] >> 16) & 0xff)] + let b33 = AES.T3_INV[Int(t[0] >> 24)] + b3 = b30 ^ b31 ^ b32 ^ b33 + } + + // last round + t[0] = b0 ^ rk[1][0] + t[1] = b1 ^ rk[1][1] + t[2] = b2 ^ rk[1][2] + t[3] = b3 ^ rk[1][3] + + // rounds + + let lb00 = self.sBoxInv[Int(B0(t[0]))] + let lb01 = (sBoxInv[Int(B1(t[3]))] << 8) + let lb02 = (sBoxInv[Int(B2(t[2]))] << 16) + let lb03 = (sBoxInv[Int(B3(t[1]))] << 24) + b0 = lb00 | lb01 | lb02 | lb03 ^ rk[0][0] + + let lb10 = self.sBoxInv[Int(B0(t[1]))] + let lb11 = (sBoxInv[Int(B1(t[0]))] << 8) + let lb12 = (sBoxInv[Int(B2(t[3]))] << 16) + let lb13 = (sBoxInv[Int(B3(t[2]))] << 24) + b1 = lb10 | lb11 | lb12 | lb13 ^ rk[0][1] + + let lb20 = self.sBoxInv[Int(B0(t[2]))] + let lb21 = (sBoxInv[Int(B1(t[1]))] << 8) + let lb22 = (sBoxInv[Int(B2(t[0]))] << 16) + let lb23 = (sBoxInv[Int(B3(t[3]))] << 24) + b2 = lb20 | lb21 | lb22 | lb23 ^ rk[0][2] + + let lb30 = self.sBoxInv[Int(B0(t[3]))] + let lb31 = (sBoxInv[Int(B1(t[2]))] << 8) + let lb32 = (sBoxInv[Int(B2(t[1]))] << 16) + let lb33 = (sBoxInv[Int(B3(t[0]))] << 24) + b3 = lb30 | lb31 | lb32 | lb33 ^ rk[0][3] + + let result: Array = [ + UInt8(b0 & 0xff), UInt8((b0 >> 8) & 0xff), UInt8((b0 >> 16) & 0xff), UInt8((b0 >> 24) & 0xff), + UInt8(b1 & 0xff), UInt8((b1 >> 8) & 0xff), UInt8((b1 >> 16) & 0xff), UInt8((b1 >> 24) & 0xff), + UInt8(b2 & 0xff), UInt8((b2 >> 8) & 0xff), UInt8((b2 >> 16) & 0xff), UInt8((b2 >> 24) & 0xff), + UInt8(b3 & 0xff), UInt8((b3 >> 8) & 0xff), UInt8((b3 >> 16) & 0xff), UInt8((b3 >> 24) & 0xff) + ] + return result + } +} + +extension AES { + private func expandKeyInv(_ key: Key, variant: Variant) -> Array> { + let rounds = self.variantNr + var rk2: Array> = self.expandKey(key, variant: variant) + + for r in 1.. Array> { + func convertExpandedKey(_ expanded: Array) -> Array> { + expanded.batched(by: 4).map({ UInt32(bytes: $0.reversed()) }).batched(by: 4).map { Array($0) } + } + + /* + * Function used in the Key Expansion routine that takes a four-byte + * input word and applies an S-box to each of the four bytes to + * produce an output word. + */ + func subWord(_ word: Array) -> Array { + precondition(word.count == 4) + + var result = word + for i in 0..<4 { + result[i] = UInt8(self.sBox[Int(word[i])]) + } + return result + } + + @inline(__always) + func subWordInPlace(_ word: inout Array) { + precondition(word.count == 4) + word[0] = UInt8(self.sBox[Int(word[0])]) + word[1] = UInt8(self.sBox[Int(word[1])]) + word[2] = UInt8(self.sBox[Int(word[2])]) + word[3] = UInt8(self.sBox[Int(word[3])]) + } + + let wLength = self.variantNb * (self.variantNr + 1) * 4 + let w = UnsafeMutablePointer.allocate(capacity: wLength) + w.initialize(repeating: 0, count: wLength) + defer { + w.deinitialize(count: wLength) + w.deallocate() + } + + for i in 0.. + + for i in self.variantNk..(repeating: 0, count: 4) + + for wordIdx in 0..<4 { + tmp[wordIdx] = w[4 * (i - 1) + wordIdx] + } + if (i % self.variantNk) == 0 { + tmp = subWord(rotateLeft(UInt32(bytes: tmp), by: 8).bytes(totalBytes: 4)) + tmp[0] = tmp.first! ^ AES.Rcon[i / variantNk] + } else if self.variantNk > 6 && (i % self.variantNk) == 4 { + subWordInPlace(&tmp) + } + + // xor array of bytes + for wordIdx in 0..<4 { + w[4 * i + wordIdx] = w[4 * (i - variantNk) + wordIdx] ^ tmp[wordIdx] + } + } + return convertExpandedKey(Array(UnsafeBufferPointer(start: w, count: wLength))) + } + + @inline(__always) + private func B0(_ x: UInt32) -> UInt32 { + x & 0xff + } + + @inline(__always) + private func B1(_ x: UInt32) -> UInt32 { + (x >> 8) & 0xff + } + + @inline(__always) + private func B2(_ x: UInt32) -> UInt32 { + (x >> 16) & 0xff + } + + @inline(__always) + private func B3(_ x: UInt32) -> UInt32 { + (x >> 24) & 0xff + } + + @inline(__always) @usableFromInline + internal func F1(_ x0: UInt32, _ x1: UInt32, _ x2: UInt32, _ x3: UInt32) -> UInt32 { + var result: UInt32 = 0 + result |= UInt32(self.B1(AES.T0[Int(x0 & 255)])) + result |= UInt32(self.B1(AES.T0[Int((x1 >> 8) & 255)])) << 8 + result |= UInt32(self.B1(AES.T0[Int((x2 >> 16) & 255)])) << 16 + result |= UInt32(self.B1(AES.T0[Int(x3 >> 24)])) << 24 + return result + } + + private func calculateSBox() -> (sBox: Array, invSBox: Array) { + let sboxLength = 256 + let sbox = UnsafeMutablePointer.allocate(capacity: sboxLength) + let invsbox = UnsafeMutablePointer.allocate(capacity: sboxLength) + sbox.initialize(repeating: 0, count: sboxLength) + invsbox.initialize(repeating: 0, count: sboxLength) + defer { + sbox.deinitialize(count: sboxLength) + sbox.deallocate() + invsbox.deinitialize(count: sboxLength) + invsbox.deallocate() + } + + sbox[0] = 0x63 + + var p: UInt8 = 1, q: UInt8 = 1 + + repeat { + p = p ^ (UInt8(truncatingIfNeeded: Int(p) << 1) ^ ((p & 0x80) == 0x80 ? 0x1b : 0)) + q ^= q << 1 + q ^= q << 2 + q ^= q << 4 + q ^= (q & 0x80) == 0x80 ? 0x09 : 0 + + let s = 0x63 ^ q ^ rotateLeft(q, by: 1) ^ rotateLeft(q, by: 2) ^ rotateLeft(q, by: 3) ^ rotateLeft(q, by: 4) + + sbox[Int(p)] = UInt32(s) + invsbox[Int(s)] = UInt32(p) + } while p != 1 + + return (sBox: Array(UnsafeBufferPointer(start: sbox, count: sboxLength)), invSBox: Array(UnsafeBufferPointer(start: invsbox, count: sboxLength))) + } +} + +// MARK: Cipher + +extension AES: Cipher { + @inlinable + public func encrypt(_ bytes: ArraySlice) throws -> Array { + let blockSize = self.blockMode.customBlockSize ?? AES.blockSize + let chunks = bytes.batched(by: blockSize) + + var oneTimeCryptor = try makeEncryptor() + var out = Array(reserveCapacity: bytes.count) + for chunk in chunks { + out += try oneTimeCryptor.update(withBytes: chunk, isLast: false) + } + // Padding may be added at the very end + out += try oneTimeCryptor.finish() + + if self.blockMode.options.contains(.paddingRequired) && (out.count % AES.blockSize != 0) { + throw Error.dataPaddingRequired + } + + return out + } + + @inlinable + public func decrypt(_ bytes: ArraySlice) throws -> Array { + if self.blockMode.options.contains(.paddingRequired) && (bytes.count % AES.blockSize != 0) { + throw Error.dataPaddingRequired + } + + var oneTimeCryptor = try makeDecryptor() + let chunks = bytes.batched(by: AES.blockSize) + if chunks.isEmpty { + throw Error.invalidData + } + + var out = Array(reserveCapacity: bytes.count) + + var lastIdx = chunks.startIndex + chunks.indices.formIndex(&lastIdx, offsetBy: chunks.count - 1) + + // To properly remove padding, `isLast` has to be known when called with the last chunk of ciphertext + // Last chunk of ciphertext may contains padded data so next call to update(..) won't be able to remove it + for idx in chunks.indices { + out += try oneTimeCryptor.update(withBytes: chunks[idx], isLast: idx == lastIdx) + } + return out + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Array+Extension.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Array+Extension.swift new file mode 100644 index 000000000..6ae3601a7 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Array+Extension.swift @@ -0,0 +1,150 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +extension Array { + @inlinable + init(reserveCapacity: Int) { + self = Array() + self.reserveCapacity(reserveCapacity) + } + + @inlinable + var slice: ArraySlice { + self[self.startIndex ..< self.endIndex] + } +} + +extension Array where Element == UInt8 { + public init(hex: String) { + self.init(reserveCapacity: hex.unicodeScalars.lazy.underestimatedCount) + var buffer: UInt8? + var skip = hex.hasPrefix("0x") ? 2 : 0 + for char in hex.unicodeScalars.lazy { + guard skip == 0 else { + skip -= 1 + continue + } + guard char.value >= 48 && char.value <= 102 else { + removeAll() + return + } + let v: UInt8 + let c: UInt8 = UInt8(char.value) + switch c { + case let c where c <= 57: + v = c - 48 + case let c where c >= 65 && c <= 70: + v = c - 55 + case let c where c >= 97: + v = c - 87 + default: + removeAll() + return + } + if let b = buffer { + append(b << 4 | v) + buffer = nil + } else { + buffer = v + } + } + if let b = buffer { + append(b) + } + } + + public func toHexString() -> String { + `lazy`.reduce(into: "") { + var s = String($1, radix: 16) + if s.count == 1 { + s = "0" + s + } + $0 += s + } + } +} + +extension Array where Element == UInt8 { + /// split in chunks with given chunk size + @available(*, deprecated) + public func chunks(size chunksize: Int) -> Array> { + var words = Array>() + words.reserveCapacity(count / chunksize) + for idx in stride(from: chunksize, through: count, by: chunksize) { + words.append(Array(self[idx - chunksize ..< idx])) // slow for large table + } + let remainder = suffix(count % chunksize) + if !remainder.isEmpty { + words.append(Array(remainder)) + } + return words + } + + public func md5() -> [Element] { + Digest.md5(self) + } + + public func sha1() -> [Element] { + Digest.sha1(self) + } + + public func sha224() -> [Element] { + Digest.sha224(self) + } + + public func sha256() -> [Element] { + Digest.sha256(self) + } + + public func sha384() -> [Element] { + Digest.sha384(self) + } + + public func sha512() -> [Element] { + Digest.sha512(self) + } + + public func sha2(_ variant: SHA2.Variant) -> [Element] { + Digest.sha2(self, variant: variant) + } + + public func sha3(_ variant: SHA3.Variant) -> [Element] { + Digest.sha3(self, variant: variant) + } + + public func crc32(seed: UInt32? = nil, reflect: Bool = true) -> UInt32 { + Checksum.crc32(self, seed: seed, reflect: reflect) + } + + public func crc32c(seed: UInt32? = nil, reflect: Bool = true) -> UInt32 { + Checksum.crc32c(self, seed: seed, reflect: reflect) + } + + public func crc16(seed: UInt16? = nil) -> UInt16 { + Checksum.crc16(self, seed: seed) + } + + public func encrypt(cipher: Cipher) throws -> [Element] { + try cipher.encrypt(self.slice) + } + + public func decrypt(cipher: Cipher) throws -> [Element] { + try cipher.decrypt(self.slice) + } + + public func authenticate(with authenticator: A) throws -> [Element] { + try authenticator.authenticate(self) + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Authenticator.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Authenticator.swift new file mode 100644 index 000000000..fd0ad4bcd --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Authenticator.swift @@ -0,0 +1,20 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +/// Message authentication code. +public protocol Authenticator { + /// Calculate Message Authentication Code (MAC) for message. + func authenticate(_ bytes: Array) throws -> Array +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BatchedCollection.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BatchedCollection.swift new file mode 100644 index 000000000..8d55d0a9d --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BatchedCollection.swift @@ -0,0 +1,81 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +@usableFromInline +struct BatchedCollectionIndex { + let range: Range +} + +extension BatchedCollectionIndex: Comparable { + @usableFromInline + static func == (lhs: BatchedCollectionIndex, rhs: BatchedCollectionIndex) -> Bool { + lhs.range.lowerBound == rhs.range.lowerBound + } + + @usableFromInline + static func < (lhs: BatchedCollectionIndex, rhs: BatchedCollectionIndex) -> Bool { + lhs.range.lowerBound < rhs.range.lowerBound + } +} + +protocol BatchedCollectionType: Collection { + associatedtype Base: Collection +} + +@usableFromInline +struct BatchedCollection: Collection { + let base: Base + let size: Int + + @usableFromInline + init(base: Base, size: Int) { + self.base = base + self.size = size + } + + @usableFromInline + typealias Index = BatchedCollectionIndex + + private func nextBreak(after idx: Base.Index) -> Base.Index { + self.base.index(idx, offsetBy: self.size, limitedBy: self.base.endIndex) ?? self.base.endIndex + } + + @usableFromInline + var startIndex: Index { + Index(range: self.base.startIndex.. Index { + Index(range: idx.range.upperBound.. Base.SubSequence { + self.base[idx.range] + } +} + +extension Collection { + @inlinable + func batched(by size: Int) -> BatchedCollection { + BatchedCollection(base: self, size: size) + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Bit.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Bit.swift new file mode 100644 index 000000000..f1ec5b79e --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Bit.swift @@ -0,0 +1,26 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public enum Bit: Int { + case zero + case one +} + +extension Bit { + @inlinable + func inverted() -> Bit { + self == .zero ? .one : .zero + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockCipher.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockCipher.swift new file mode 100644 index 000000000..f79117802 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockCipher.swift @@ -0,0 +1,18 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +protocol BlockCipher: Cipher { + static var blockSize: Int { get } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockDecryptor.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockDecryptor.swift new file mode 100644 index 000000000..935cdfa32 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockDecryptor.swift @@ -0,0 +1,98 @@ +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public class BlockDecryptor: Cryptor, Updatable { + @usableFromInline + let blockSize: Int + + @usableFromInline + let padding: Padding + + @usableFromInline + var worker: CipherModeWorker + + @usableFromInline + var accumulated = Array() + + @usableFromInline + init(blockSize: Int, padding: Padding, _ worker: CipherModeWorker) throws { + self.blockSize = blockSize + self.padding = padding + self.worker = worker + } + + @inlinable + public func update(withBytes bytes: ArraySlice, isLast: Bool = false) throws -> Array { + self.accumulated += bytes + + // If a worker (eg GCM) can combine ciphertext + tag + // we need to remove tag from the ciphertext. + if !isLast && self.accumulated.count < self.blockSize + self.worker.additionalBufferSize { + return [] + } + + let accumulatedWithoutSuffix: Array + if self.worker.additionalBufferSize > 0 { + // FIXME: how slow is that? + accumulatedWithoutSuffix = Array(self.accumulated.prefix(self.accumulated.count - self.worker.additionalBufferSize)) + } else { + accumulatedWithoutSuffix = self.accumulated + } + + var processedBytesCount = 0 + var plaintext = Array(reserveCapacity: accumulatedWithoutSuffix.count) + // Processing in a block-size manner. It's good for block modes, but bad for stream modes. + for var chunk in accumulatedWithoutSuffix.batched(by: self.blockSize) { + if isLast || (accumulatedWithoutSuffix.count - processedBytesCount) >= blockSize { + let isLastChunk = processedBytesCount + chunk.count == accumulatedWithoutSuffix.count + + if isLast, isLastChunk, var finalizingWorker = worker as? FinalizingDecryptModeWorker { + chunk = try finalizingWorker.willDecryptLast(bytes: chunk + accumulated.suffix(worker.additionalBufferSize)) // tag size + } + + if !chunk.isEmpty { + plaintext += worker.decrypt(block: chunk) + } + + if isLast, isLastChunk, var finalizingWorker = worker as? FinalizingDecryptModeWorker { + plaintext = Array(try finalizingWorker.didDecryptLast(bytes: plaintext.slice)) + } + + processedBytesCount += chunk.count + } + } + accumulated.removeFirst(processedBytesCount) // super-slow + + if isLast { + if accumulatedWithoutSuffix.isEmpty, var finalizingWorker = worker as? FinalizingDecryptModeWorker { + try finalizingWorker.willDecryptLast(bytes: self.accumulated.suffix(self.worker.additionalBufferSize)) + plaintext = Array(try finalizingWorker.didDecryptLast(bytes: plaintext.slice)) + } + plaintext = self.padding.remove(from: plaintext, blockSize: self.blockSize) + } + + return plaintext + } + + public func seek(to position: Int) throws { + guard var worker = self.worker as? SeekableModeWorker else { + fatalError("Not supported") + } + + try worker.seek(to: position) + self.worker = worker + + accumulated = [] + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockEncryptor.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockEncryptor.swift new file mode 100644 index 000000000..0ab1ed61a --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockEncryptor.swift @@ -0,0 +1,62 @@ +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +@usableFromInline +final class BlockEncryptor: Cryptor, Updatable { + private let blockSize: Int + private var worker: CipherModeWorker + private let padding: Padding + // Accumulated bytes. Not all processed bytes. + private var accumulated = Array(reserveCapacity: 16) + + private var lastBlockRemainder = 0 + + @usableFromInline + init(blockSize: Int, padding: Padding, _ worker: CipherModeWorker) throws { + self.blockSize = blockSize + self.padding = padding + self.worker = worker + } + + // MARK: Updatable + + public func update(withBytes bytes: ArraySlice, isLast: Bool) throws -> Array { + self.accumulated += bytes + + if isLast { + self.accumulated = self.padding.add(to: self.accumulated, blockSize: self.blockSize) + } + + var encrypted = Array(reserveCapacity: accumulated.count) + for chunk in self.accumulated.batched(by: self.blockSize) { + if isLast || chunk.count == self.blockSize { + encrypted += self.worker.encrypt(block: chunk) + } + } + + // Stream encrypts all, so it removes all elements + self.accumulated.removeFirst(encrypted.count) + + if var finalizingWorker = worker as? FinalizingEncryptModeWorker, isLast == true { + encrypted = Array(try finalizingWorker.finalize(encrypt: encrypted.slice)) + } + + return encrypted + } + + @usableFromInline + func seek(to: Int) throws { + fatalError("Not supported") + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/BlockMode.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/BlockMode.swift new file mode 100644 index 000000000..ff410d7a2 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/BlockMode.swift @@ -0,0 +1,26 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public typealias CipherOperationOnBlock = (_ block: ArraySlice) -> Array? + +public protocol BlockMode { + var options: BlockModeOption { get } + //TODO: doesn't have to be public + @inlinable func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock, encryptionOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker + + var customBlockSize: Int? { get } +} + +typealias StreamMode = BlockMode diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/BlockModeOptions.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/BlockModeOptions.swift new file mode 100644 index 000000000..a21dd8951 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/BlockModeOptions.swift @@ -0,0 +1,34 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public struct BlockModeOption: OptionSet { + public let rawValue: Int + + public init(rawValue: Int) { + self.rawValue = rawValue + } + + @usableFromInline + static let none = BlockModeOption(rawValue: 1 << 0) + + @usableFromInline + static let initializationVectorRequired = BlockModeOption(rawValue: 1 << 1) + + @usableFromInline + static let paddingRequired = BlockModeOption(rawValue: 1 << 2) + + @usableFromInline + static let useEncryptToDecrypt = BlockModeOption(rawValue: 1 << 3) +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CBC.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CBC.swift new file mode 100644 index 000000000..ca5d6462f --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CBC.swift @@ -0,0 +1,76 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// Cipher-block chaining (CBC) +// + +public struct CBC: BlockMode { + public enum Error: Swift.Error { + /// Invalid IV + case invalidInitializationVector + } + + public let options: BlockModeOption = [.initializationVectorRequired, .paddingRequired] + + private let iv: Array + + public let customBlockSize: Int? = nil + + public init(iv: Array) { + self.iv = iv + } + + public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock, encryptionOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker { + if self.iv.count != blockSize { + throw Error.invalidInitializationVector + } + + return CBCModeWorker(blockSize: blockSize, iv: self.iv.slice, cipherOperation: cipherOperation) + } +} + +struct CBCModeWorker: BlockModeWorker { + let cipherOperation: CipherOperationOnBlock + var blockSize: Int + let additionalBufferSize: Int = 0 + private let iv: ArraySlice + private var prev: ArraySlice? + + @inlinable + init(blockSize: Int, iv: ArraySlice, cipherOperation: @escaping CipherOperationOnBlock) { + self.blockSize = blockSize + self.iv = iv + self.cipherOperation = cipherOperation + } + + @inlinable + mutating func encrypt(block plaintext: ArraySlice) -> Array { + guard let ciphertext = cipherOperation(xor(prev ?? iv, plaintext)) else { + return Array(plaintext) + } + self.prev = ciphertext.slice + return ciphertext + } + + @inlinable + mutating func decrypt(block ciphertext: ArraySlice) -> Array { + guard let plaintext = cipherOperation(ciphertext) else { + return Array(ciphertext) + } + let result: Array = xor(prev ?? self.iv, plaintext) + self.prev = ciphertext + return result + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CCM.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CCM.swift new file mode 100644 index 000000000..a42cbbfac --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CCM.swift @@ -0,0 +1,365 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// CCM mode combines the well known CBC-MAC with the well known counter mode of encryption. +// https://tools.ietf.org/html/rfc3610 +// https://csrc.nist.gov/publications/detail/sp/800-38c/final + +#if canImport(Darwin) +import Darwin +#elseif canImport(Glibc) +import Glibc +#elseif canImport(ucrt) +import ucrt +#endif + +/// Counter with Cipher Block Chaining-Message Authentication Code +public struct CCM: StreamMode { + public enum Error: Swift.Error { + /// Invalid IV + case invalidInitializationVector + case invalidParameter + case fail + } + + public let options: BlockModeOption = [.initializationVectorRequired, .useEncryptToDecrypt] + private let nonce: Array + private let additionalAuthenticatedData: Array? + private let tagLength: Int + private let messageLength: Int // total message length. need to know in advance + public let customBlockSize: Int? = nil + + // `authenticationTag` nil for encryption, known tag for decryption + /// For encryption, the value is set at the end of the encryption. + /// For decryption, this is a known Tag to validate against. + public var authenticationTag: Array? + + /// Initialize CCM + /// + /// - Parameters: + /// - iv: Initialization vector. Nonce. Valid length between 7 and 13 bytes. + /// - tagLength: Authentication tag length, in bytes. Value of {4, 6, 8, 10, 12, 14, 16}. + /// - messageLength: Plaintext message length (excluding tag if attached). Length have to be provided in advance. + /// - additionalAuthenticatedData: Additional authenticated data. + public init(iv: Array, tagLength: Int, messageLength: Int, additionalAuthenticatedData: Array? = nil) { + self.nonce = iv + self.tagLength = tagLength + self.additionalAuthenticatedData = additionalAuthenticatedData + self.messageLength = messageLength // - tagLength + } + + /// Initialize CCM + /// + /// - Parameters: + /// - iv: Initialization vector. Nonce. Valid length between 7 and 13 bytes. + /// - tagLength: Authentication tag length, in bytes. Value of {4, 6, 8, 10, 12, 14, 16}. + /// - messageLength: Plaintext message length (excluding tag if attached). Length have to be provided in advance. + /// - authenticationTag: Authentication Tag value if not concatenated to ciphertext. + /// - additionalAuthenticatedData: Additional authenticated data. + public init(iv: Array, tagLength: Int, messageLength: Int, authenticationTag: Array, additionalAuthenticatedData: Array? = nil) { + self.init(iv: iv, tagLength: tagLength, messageLength: messageLength, additionalAuthenticatedData: additionalAuthenticatedData) + self.authenticationTag = authenticationTag + } + + public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock, encryptionOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker { + if self.nonce.isEmpty { + throw Error.invalidInitializationVector + } + + return CCMModeWorker(blockSize: blockSize, nonce: self.nonce.slice, messageLength: self.messageLength, additionalAuthenticatedData: self.additionalAuthenticatedData, tagLength: self.tagLength, cipherOperation: cipherOperation) + } +} + +class CCMModeWorker: StreamModeWorker, SeekableModeWorker, CounterModeWorker, FinalizingEncryptModeWorker, FinalizingDecryptModeWorker { + typealias Counter = Int + var counter = 0 + + let cipherOperation: CipherOperationOnBlock + let blockSize: Int + private let tagLength: Int + private let messageLength: Int // total message length. need to know in advance + private let q: UInt8 + + let additionalBufferSize: Int + private var keystreamPosIdx = 0 + private let nonce: Array + private var last_y: ArraySlice = [] + private var keystream: Array = [] + // Known Tag used to validate during decryption + private var expectedTag: Array? + + public enum Error: Swift.Error { + case invalidParameter + } + + init(blockSize: Int, nonce: ArraySlice, messageLength: Int, additionalAuthenticatedData: [UInt8]?, expectedTag: Array? = nil, tagLength: Int, cipherOperation: @escaping CipherOperationOnBlock) { + self.blockSize = 16 // CCM is defined for 128 block size + self.tagLength = tagLength + self.additionalBufferSize = tagLength + self.messageLength = messageLength + self.expectedTag = expectedTag + self.cipherOperation = cipherOperation + self.nonce = Array(nonce) + self.q = UInt8(15 - nonce.count) // n = 15-q + + let hasAssociatedData = additionalAuthenticatedData != nil && !additionalAuthenticatedData!.isEmpty + self.processControlInformation(nonce: self.nonce, tagLength: tagLength, hasAssociatedData: hasAssociatedData) + + if let aad = additionalAuthenticatedData, hasAssociatedData { + self.process(aad: aad) + } + } + + // For the very first time setup new IV (aka y0) from the block0 + private func processControlInformation(nonce: [UInt8], tagLength: Int, hasAssociatedData: Bool) { + let block0 = try! format(nonce: nonce, Q: UInt32(self.messageLength), q: self.q, t: UInt8(tagLength), hasAssociatedData: hasAssociatedData).slice + let y0 = self.cipherOperation(block0)!.slice + self.last_y = y0 + } + + private func process(aad: [UInt8]) { + let encodedAAD = format(aad: aad) + + for block_i in encodedAAD.batched(by: 16) { + let y_i = self.cipherOperation(xor(block_i, self.last_y))!.slice + self.last_y = y_i + } + } + + private func S(i: Int) throws -> [UInt8] { + let ctr = try format(counter: i, nonce: nonce, q: q) + return self.cipherOperation(ctr.slice)! + } + + @inlinable + func seek(to position: Int) throws { + self.counter = position + self.keystream = try self.S(i: position) + let offset = position % self.blockSize + self.keystreamPosIdx = offset + } + + func encrypt(block plaintext: ArraySlice) -> Array { + var result = Array(reserveCapacity: plaintext.count) + + var processed = 0 + while processed < plaintext.count { + // Need a full block here to update keystream and do CBC + if self.keystream.isEmpty || self.keystreamPosIdx == self.blockSize { + // y[i], where i is the counter. Can encrypt 1 block at a time + self.counter += 1 + guard let S = try? S(i: counter) else { return Array(plaintext) } + let plaintextP = addPadding(Array(plaintext), blockSize: blockSize) + guard let y = cipherOperation(xor(last_y, plaintextP)) else { return Array(plaintext) } + self.last_y = y.slice + + self.keystream = S + self.keystreamPosIdx = 0 + } + + let xored: Array = xor(plaintext[plaintext.startIndex.advanced(by: processed)...], keystream[keystreamPosIdx...]) + keystreamPosIdx += xored.count + processed += xored.count + result += xored + } + return result + } + + @inlinable + func finalize(encrypt ciphertext: ArraySlice) throws -> ArraySlice { + // concatenate T at the end + guard let S0 = try? S(i: 0) else { return ciphertext } + + let computedTag = xor(last_y.prefix(self.tagLength), S0) as ArraySlice + return ciphertext + computedTag + } + + // Decryption is stream + // CBC is block + private var accumulatedPlaintext: [UInt8] = [] + + func decrypt(block ciphertext: ArraySlice) -> Array { + var output = Array(reserveCapacity: ciphertext.count) + + do { + var currentCounter = self.counter + var processed = 0 + while processed < ciphertext.count { + // Need a full block here to update keystream and do CBC + // New keystream for a new block + if self.keystream.isEmpty || self.keystreamPosIdx == self.blockSize { + currentCounter += 1 + guard let S = try? S(i: currentCounter) else { return Array(ciphertext) } + self.keystream = S + self.keystreamPosIdx = 0 + } + + let xored: Array = xor(ciphertext[ciphertext.startIndex.advanced(by: processed)...], keystream[keystreamPosIdx...]) // plaintext + keystreamPosIdx += xored.count + processed += xored.count + output += xored + self.counter = currentCounter + } + } + + // Accumulate plaintext for the MAC calculations at the end. + // It would be good to process it together though, here. + self.accumulatedPlaintext += output + + // Shouldn't return plaintext until validate tag. + // With incremental update, can't validate tag until all block are processed. + return output + } + + @inlinable + func finalize(decrypt plaintext: ArraySlice) throws -> ArraySlice { + // concatenate T at the end + let computedTag = Array(last_y.prefix(self.tagLength)) + guard let expectedTag = self.expectedTag, expectedTag == computedTag else { + throw CCM.Error.fail + } + + return plaintext + } + + @discardableResult + func willDecryptLast(bytes ciphertext: ArraySlice) throws -> ArraySlice { + // get tag of additionalBufferSize size + // `ciphertext` contains at least additionalBufferSize bytes + // overwrite expectedTag property used later for verification + guard let S0 = try? S(i: 0) else { return ciphertext } + self.expectedTag = xor(ciphertext.suffix(self.tagLength), S0) as [UInt8] + return ciphertext[ciphertext.startIndex..) throws -> ArraySlice { + + // Calculate Tag, from the last CBC block, for accumulated plaintext. + var processed = 0 + for block in self.accumulatedPlaintext.batched(by: self.blockSize) { + let blockP = addPadding(Array(block), blockSize: blockSize) + guard let y = cipherOperation(xor(last_y, blockP)) else { return plaintext } + self.last_y = y.slice + processed += block.count + } + self.accumulatedPlaintext.removeFirst(processed) + return plaintext + } +} + +// Q - octet length of P +// q - octet length of Q. Maximum length (in octets) of payload. An element of {2,3,4,5,6,7,8} +// t - octet length of T (MAC length). An element of {4,6,8,10,12,14,16} +private func format(nonce N: [UInt8], Q: UInt32, q: UInt8, t: UInt8, hasAssociatedData: Bool) throws -> [UInt8] { + var flags0: UInt8 = 0 + + if hasAssociatedData { + // 7 bit + flags0 |= (1 << 6) + } + + // 6,5,4 bit is t in 3 bits + flags0 |= (((t - 2) / 2) & 0x07) << 3 + + // 3,2,1 bit is q in 3 bits + flags0 |= ((q - 1) & 0x07) << 0 + + var block0: [UInt8] = Array(repeating: 0, count: 16) + block0[0] = flags0 + + // N in 1...(15-q) octets, n = 15-q + // n is an element of {7,8,9,10,11,12,13} + let n = 15 - Int(q) + guard (n + Int(q)) == 15 else { + // n+q == 15 + throw CCMModeWorker.Error.invalidParameter + } + block0[1...n] = N[0...(n - 1)] + + // Q in (16-q)...15 octets + block0[(16 - Int(q))...15] = Q.bytes(totalBytes: Int(q)).slice + + return block0 +} + +/// Formatting of the Counter Blocks. Ctr[i] +/// The counter generation function. +/// Q - octet length of P +/// q - octet length of Q. Maximum length (in octets) of payload. An element of {2,3,4,5,6,7,8} +private func format(counter i: Int, nonce N: [UInt8], q: UInt8) throws -> [UInt8] { + var flags0: UInt8 = 0 + + // bit 8,7 is Reserved + // bit 4,5,6 shall be set to 0 + // 3,2,1 bit is q in 3 bits + flags0 |= ((q - 1) & 0x07) << 0 + + var block = Array(repeating: 0, count: 16) // block[0] + block[0] = flags0 + + // N in 1...(15-q) octets, n = 15-q + // n is an element of {7,8,9,10,11,12,13} + let n = 15 - Int(q) + guard (n + Int(q)) == 15 else { + // n+q == 15 + throw CCMModeWorker.Error.invalidParameter + } + block[1...n] = N[0...(n - 1)] + + // [i]8q in (16-q)...15 octets + block[(16 - Int(q))...15] = i.bytes(totalBytes: Int(q)).slice + + return block +} + +/// Resulting can be partitioned into 16-octet blocks +private func format(aad: [UInt8]) -> [UInt8] { + let a = aad.count + + switch Double(a) { + case 0..<65280: // 2^16-2^8 + // [a]16 + return addPadding(a.bytes(totalBytes: 2) + aad, blockSize: 16) + case 65280..<4_294_967_296: // 2^32 + // [a]32 + return addPadding([0xFF, 0xFE] + a.bytes(totalBytes: 4) + aad, blockSize: 16) + case 4_294_967_296.., blockSize: Int) -> Array { + if bytes.isEmpty { + return Array(repeating: 0, count: blockSize) + } + + let remainder = bytes.count % blockSize + if remainder == 0 { + return bytes + } + + let paddingCount = blockSize - remainder + if paddingCount > 0 { + return bytes + Array(repeating: 0, count: paddingCount) + } + return bytes +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CFB.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CFB.swift new file mode 100644 index 000000000..95e91add7 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CFB.swift @@ -0,0 +1,102 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// Cipher feedback (CFB) +// + +public struct CFB: BlockMode { + public enum Error: Swift.Error { + /// Invalid IV + case invalidInitializationVector + } + + public enum SegmentSize: Int { + case cfb8 = 1 // Encrypt byte per byte + case cfb128 = 16 // Encrypt 16 bytes per 16 bytes (default) + } + + public let options: BlockModeOption = [.initializationVectorRequired, .useEncryptToDecrypt] + private let iv: Array + private let segmentSize: SegmentSize + public let customBlockSize: Int? + + public init(iv: Array, segmentSize: SegmentSize = .cfb128) { + self.iv = iv + self.segmentSize = segmentSize + self.customBlockSize = segmentSize.rawValue + } + + public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock, encryptionOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker { + if !(self.iv.count == blockSize || (segmentSize == .cfb8 && self.iv.count == AES.blockSize)) { + throw Error.invalidInitializationVector + } + + return CFBModeWorker(blockSize: blockSize, iv: self.iv.slice, segmentSize: segmentSize, cipherOperation: cipherOperation) + } +} + +struct CFBModeWorker: BlockModeWorker { + let cipherOperation: CipherOperationOnBlock + let blockSize: Int + let additionalBufferSize: Int = 0 + private let iv: ArraySlice + private let segmentSize: CFB.SegmentSize + private var prev: ArraySlice? + + init(blockSize: Int, iv: ArraySlice, segmentSize: CFB.SegmentSize, cipherOperation: @escaping CipherOperationOnBlock) { + self.blockSize = blockSize + self.iv = iv + self.segmentSize = segmentSize + self.cipherOperation = cipherOperation + } + + @inlinable + mutating func encrypt(block plaintext: ArraySlice) -> Array { + switch segmentSize { + case .cfb128: + guard let ciphertext = cipherOperation(prev ?? iv) else { + return Array(plaintext) + } + self.prev = xor(plaintext, ciphertext.slice) + return Array(self.prev ?? []) + case .cfb8: + guard let ciphertext = cipherOperation(prev ?? iv) else { + return Array(plaintext) + } + let result = [Array(plaintext)[0] ^ Array(ciphertext)[0]] + self.prev = Array((prev ?? iv).dropFirst()) + [result[0]] + return result + } + } + + @inlinable + mutating func decrypt(block ciphertext: ArraySlice) -> Array { + switch segmentSize { + case .cfb128: + guard let plaintext = cipherOperation(prev ?? iv) else { + return Array(ciphertext) + } + let result: Array = xor(plaintext, ciphertext) + prev = ciphertext + return result + case .cfb8: + guard let plaintext = cipherOperation(prev ?? iv) else { + return Array(ciphertext) + } + self.prev = Array((prev ?? iv).dropFirst()) + [Array(ciphertext)[0]] + return [Array(ciphertext)[0] ^ Array(plaintext)[0]] + } + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CTR.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CTR.swift new file mode 100644 index 000000000..f0074ae4d --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CTR.swift @@ -0,0 +1,138 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// Counter (CTR) + +public struct CTR: StreamMode { + public enum Error: Swift.Error { + /// Invalid IV + case invalidInitializationVector + } + + public let options: BlockModeOption = [.initializationVectorRequired, .useEncryptToDecrypt] + private let iv: Array + private let counter: Int + public let customBlockSize: Int? = nil + + public init(iv: Array, counter: Int = 0) { + self.iv = iv + self.counter = counter + } + + public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock, encryptionOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker { + if self.iv.count != blockSize { + throw Error.invalidInitializationVector + } + + return CTRModeWorker(blockSize: blockSize, iv: self.iv.slice, counter: self.counter, cipherOperation: cipherOperation) + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +struct CTRModeWorker: StreamModeWorker, SeekableModeWorker, CounterModeWorker { + typealias Counter = CTRCounter + + final class CTRCounter { + private let constPrefix: Array + private var value: UInt64 + //TODO: make it an updatable value, computing is too slow + var bytes: Array { + self.constPrefix + self.value.bytes() + } + + @inlinable + init(_ initialValue: Array) { + let halfIndex = initialValue.startIndex.advanced(by: initialValue.count / 2) + self.constPrefix = Array(initialValue[initialValue.startIndex.., startAt index: Int) { + self.init(buildCounterValue(nonce, counter: UInt64(index))) + } + + static func += (lhs: CTRCounter, rhs: Int) { + lhs.value += UInt64(rhs) + } + } + + let cipherOperation: CipherOperationOnBlock + let additionalBufferSize: Int = 0 + let iv: Array + var counter: CTRCounter + + private let blockSize: Int + + // The same keystream is used for the block length plaintext + // As new data is added, keystream suffix is used to xor operation. + private var keystream: Array + private var keystreamPosIdx = 0 + + init(blockSize: Int, iv: ArraySlice, counter: Int, cipherOperation: @escaping CipherOperationOnBlock) { + self.cipherOperation = cipherOperation + self.blockSize = blockSize + self.iv = Array(iv) + + // the first keystream is calculated from the nonce = initial value of counter + self.counter = CTRCounter(nonce: Array(iv), startAt: counter) + self.keystream = Array(cipherOperation(self.counter.bytes.slice)!) + } + + @inlinable + mutating func seek(to position: Int) throws { + let offset = position % self.blockSize + self.counter = CTRCounter(nonce: self.iv, startAt: position / self.blockSize) + self.keystream = Array(self.cipherOperation(self.counter.bytes.slice)!) + self.keystreamPosIdx = offset + } + + // plaintext is at most blockSize long + @inlinable + mutating func encrypt(block plaintext: ArraySlice) -> Array { + var result = Array(reserveCapacity: plaintext.count) + + var processed = 0 + while processed < plaintext.count { + // Update keystream + if self.keystreamPosIdx == self.blockSize { + self.counter += 1 + self.keystream = Array(self.cipherOperation(self.counter.bytes.slice)!) + self.keystreamPosIdx = 0 + } + + let xored: Array = xor(plaintext[plaintext.startIndex.advanced(by: processed)...], keystream[keystreamPosIdx...]) + keystreamPosIdx += xored.count + processed += xored.count + result += xored + } + + return result + } + + mutating func decrypt(block ciphertext: ArraySlice) -> Array { + self.encrypt(block: ciphertext) + } +} + +private func buildCounterValue(_ iv: Array, counter: UInt64) -> Array { + let noncePartLen = iv.count / 2 + let noncePrefix = iv[iv.startIndex.. +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public protocol CipherModeWorker { + var cipherOperation: CipherOperationOnBlock { get } + + // Additional space needed when incrementally process data + // eg. for GCM combined mode + var additionalBufferSize: Int { get } + + @inlinable + mutating func encrypt(block plaintext: ArraySlice) -> Array + + @inlinable + mutating func decrypt(block ciphertext: ArraySlice) -> Array +} + +/// Block workers use `BlockEncryptor` +public protocol BlockModeWorker: CipherModeWorker { + var blockSize: Int { get } +} + +public protocol CounterModeWorker: CipherModeWorker { + associatedtype Counter + var counter: Counter { get set } +} + +public protocol SeekableModeWorker: CipherModeWorker { + mutating func seek(to position: Int) throws +} + +/// Stream workers use `StreamEncryptor` +public protocol StreamModeWorker: CipherModeWorker { +} + +public protocol FinalizingEncryptModeWorker: CipherModeWorker { + // Any final calculations, eg. calculate tag + // Called after the last block is encrypted + mutating func finalize(encrypt ciphertext: ArraySlice) throws -> ArraySlice +} + +public protocol FinalizingDecryptModeWorker: CipherModeWorker { + // Called before decryption, hence input is ciphertext. + // ciphertext is either a last block, or a tag (for stream workers) + @discardableResult + mutating func willDecryptLast(bytes ciphertext: ArraySlice) throws -> ArraySlice + // Called after decryption, hence input is ciphertext + mutating func didDecryptLast(bytes plaintext: ArraySlice) throws -> ArraySlice + // Any final calculations, eg. calculate tag + // Called after the last block is encrypted + mutating func finalize(decrypt plaintext: ArraySlice) throws -> ArraySlice +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/ECB.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/ECB.swift new file mode 100644 index 000000000..4e8f9ba03 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/ECB.swift @@ -0,0 +1,53 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// Electronic codebook (ECB) +// + +public struct ECB: BlockMode { + public let options: BlockModeOption = .paddingRequired + public let customBlockSize: Int? = nil + + public init() { + } + + public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock, encryptionOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker { + ECBModeWorker(blockSize: blockSize, cipherOperation: cipherOperation) + } +} + +struct ECBModeWorker: BlockModeWorker { + typealias Element = Array + let cipherOperation: CipherOperationOnBlock + let blockSize: Int + let additionalBufferSize: Int = 0 + + init(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) { + self.blockSize = blockSize + self.cipherOperation = cipherOperation + } + + @inlinable + mutating func encrypt(block plaintext: ArraySlice) -> Array { + guard let ciphertext = cipherOperation(plaintext) else { + return Array(plaintext) + } + return ciphertext + } + + mutating func decrypt(block ciphertext: ArraySlice) -> Array { + self.encrypt(block: ciphertext) + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/GCM.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/GCM.swift new file mode 100644 index 000000000..2aaeb3422 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/GCM.swift @@ -0,0 +1,374 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// Galois/Counter Mode (GCM) +// https://csrc.nist.gov/publications/detail/sp/800-38d/final +// ref: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.694.695&rep=rep1&type=pdf +// + +public final class GCM: BlockMode { + public enum Mode { + /// In combined mode, the authentication tag is directly appended to the encrypted message. This is usually what you want. + case combined + /// Some applications may need to store the authentication tag and the encrypted message at different locations. + case detached + } + + public let options: BlockModeOption = [.initializationVectorRequired, .useEncryptToDecrypt] + + public enum Error: Swift.Error { + /// Invalid IV + case invalidInitializationVector + /// Special symbol FAIL that indicates that the inputs are not authentic. + case fail + } + + private let iv: Array + private let additionalAuthenticatedData: Array? + private let mode: Mode + public let customBlockSize: Int? = nil + + /// Length of authentication tag, in bytes. + /// For encryption, the value is given as init parameter. + /// For decryption, the length of given authentication tag is used. + private let tagLength: Int + + // `authenticationTag` nil for encryption, known tag for decryption + /// For encryption, the value is set at the end of the encryption. + /// For decryption, this is a known Tag to validate against. + public var authenticationTag: Array? + + // encrypt + /// Possible tag lengths: 4,8,12,13,14,15,16 + public init(iv: Array, additionalAuthenticatedData: Array? = nil, tagLength: Int = 16, mode: Mode = .detached) { + self.iv = iv + self.additionalAuthenticatedData = additionalAuthenticatedData + self.mode = mode + self.tagLength = tagLength + } + + // decrypt + public convenience init(iv: Array, authenticationTag: Array, additionalAuthenticatedData: Array? = nil, mode: Mode = .detached) { + self.init(iv: iv, additionalAuthenticatedData: additionalAuthenticatedData, tagLength: authenticationTag.count, mode: mode) + self.authenticationTag = authenticationTag + } + + public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock, encryptionOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker { + if self.iv.isEmpty { + throw Error.invalidInitializationVector + } + + let worker = GCMModeWorker(iv: iv.slice, aad: self.additionalAuthenticatedData?.slice, expectedTag: self.authenticationTag, tagLength: self.tagLength, mode: self.mode, cipherOperation: cipherOperation) + worker.didCalculateTag = { [weak self] tag in + self?.authenticationTag = tag + } + return worker + } +} + +// MARK: - Worker + +final class GCMModeWorker: BlockModeWorker, FinalizingEncryptModeWorker, FinalizingDecryptModeWorker { + let cipherOperation: CipherOperationOnBlock + + // Callback called when authenticationTag is ready + var didCalculateTag: ((Array) -> Void)? + + private let tagLength: Int + // GCM nonce is 96-bits by default. It's the most effective length for the IV + private static let nonceSize = 12 + + // GCM is designed for 128-bit ciphers like AES (but not really for Blowfish). 64-bit mode is not implemented. + let blockSize = 16 // 128 bit + let additionalBufferSize: Int + private let iv: ArraySlice + private let mode: GCM.Mode + private var counter: UInt128 + private let eky0: UInt128 // move to GF? + private let h: UInt128 + + // Additional authenticated data + private let aad: ArraySlice? + // Known Tag used to validate during decryption + private var expectedTag: Array? + + // Note: need new worker to reset instance + // Use empty aad if not specified. AAD is optional. + private lazy var gf: GF = { + if let aad = aad { + return GF(aad: Array(aad), h: h, blockSize: blockSize) + } + return GF(aad: [UInt8](), h: h, blockSize: blockSize) + }() + + init(iv: ArraySlice, aad: ArraySlice? = nil, expectedTag: Array? = nil, tagLength: Int, mode: GCM.Mode, cipherOperation: @escaping CipherOperationOnBlock) { + self.cipherOperation = cipherOperation + self.iv = iv + self.mode = mode + self.aad = aad + self.expectedTag = expectedTag + self.tagLength = tagLength + self.h = UInt128(cipherOperation(Array(repeating: 0, count: self.blockSize).slice)!) // empty block + + if mode == .combined { + self.additionalBufferSize = tagLength + } else { + self.additionalBufferSize = 0 + } + + // Assume nonce is 12 bytes long, otherwise initial counter would be calulated from GHASH + // counter = GF.ghash(aad: [UInt8](), ciphertext: nonce) + if iv.count == GCMModeWorker.nonceSize { + self.counter = makeCounter(nonce: Array(self.iv)) + } else { + self.counter = GF.ghash(h: self.h, aad: [UInt8](), ciphertext: Array(iv), blockSize: self.blockSize) + } + + // Set constants + self.eky0 = UInt128(cipherOperation(self.counter.bytes.slice)!) + } + + func encrypt(block plaintext: ArraySlice) -> Array { + self.counter = incrementCounter(self.counter) + + guard let ekyN = cipherOperation(counter.bytes.slice) else { + return Array(plaintext) + } + + // plaintext block ^ ek1 + let ciphertext = xor(plaintext, ekyN) as Array + + // update ghash incrementally + gf.ghashUpdate(block: ciphertext) + + return Array(ciphertext) + } + + @inlinable + func finalize(encrypt ciphertext: ArraySlice) throws -> ArraySlice { + // Calculate MAC tag. + let ghash = self.gf.ghashFinish() + let tag = Array((ghash ^ self.eky0).bytes.prefix(self.tagLength)) + + // Notify handler + self.didCalculateTag?(tag) + + switch self.mode { + case .combined: + return (ciphertext + tag).slice + case .detached: + return ciphertext + } + } + + @inlinable + func decrypt(block ciphertext: ArraySlice) -> Array { + self.counter = incrementCounter(self.counter) + + // update ghash incrementally + self.gf.ghashUpdate(block: Array(ciphertext)) + + guard let ekN = cipherOperation(counter.bytes.slice) else { + return Array(ciphertext) + } + + // ciphertext block ^ ek1 + let plaintext = xor(ciphertext, ekN) as Array + return plaintext + } + + // The authenticated decryption operation has five inputs: K, IV , C, A, and T. It has only a single + // output, either the plaintext value P or a special symbol FAIL that indicates that the inputs are not + // authentic. + @discardableResult + func willDecryptLast(bytes ciphertext: ArraySlice) throws -> ArraySlice { + // Validate tag + switch self.mode { + case .combined: + // overwrite expectedTag property used later for verification + self.expectedTag = Array(ciphertext.suffix(self.tagLength)) + return ciphertext[ciphertext.startIndex..) throws -> ArraySlice { + // Calculate MAC tag. + let ghash = self.gf.ghashFinish() + let computedTag = Array((ghash ^ self.eky0).bytes.prefix(self.tagLength)) + + // Validate tag + guard let expectedTag = self.expectedTag, computedTag == expectedTag else { + throw GCM.Error.fail + } + + return plaintext + } + + func finalize(decrypt plaintext: ArraySlice) throws -> ArraySlice { + // do nothing + plaintext + } +} + +// MARK: - Local utils + +private func makeCounter(nonce: Array) -> UInt128 { + UInt128(nonce + [0, 0, 0, 1]) +} + +// Successive counter values are generated using the function incr(), which treats the rightmost 32 +// bits of its argument as a nonnegative integer with the least significant bit on the right +private func incrementCounter(_ counter: UInt128) -> UInt128 { + let b = counter.i.b + 1 + let a = (b == 0 ? counter.i.a + 1 : counter.i.a) + return UInt128((a, b)) +} + +// If data is not a multiple of block size bytes long then the remainder is zero padded +// Note: It's similar to ZeroPadding, but it's not the same. +private func addPadding(_ bytes: Array, blockSize: Int) -> Array { + if bytes.isEmpty { + return Array(repeating: 0, count: blockSize) + } + + let remainder = bytes.count % blockSize + if remainder == 0 { + return bytes + } + + let paddingCount = blockSize - remainder + if paddingCount > 0 { + return bytes + Array(repeating: 0, count: paddingCount) + } + return bytes +} + +// MARK: - GF + +/// The Field GF(2^128) +private final class GF { + static let r = UInt128(a: 0xE100000000000000, b: 0) + + let blockSize: Int + let h: UInt128 + + // AAD won't change + let aadLength: Int + + // Updated for every consumed block + var ciphertextLength: Int + + // Start with 0 + var x: UInt128 + + init(aad: [UInt8], h: UInt128, blockSize: Int) { + self.blockSize = blockSize + self.aadLength = aad.count + self.ciphertextLength = 0 + self.h = h + self.x = 0 + + // Calculate for AAD at the begining + self.x = GF.calculateX(aad: aad, x: self.x, h: h, blockSize: blockSize) + } + + @discardableResult + func ghashUpdate(block ciphertextBlock: Array) -> UInt128 { + self.ciphertextLength += ciphertextBlock.count + self.x = GF.calculateX(block: addPadding(ciphertextBlock, blockSize: self.blockSize), x: self.x, h: self.h, blockSize: self.blockSize) + return self.x + } + + func ghashFinish() -> UInt128 { + // len(A) || len(C) + let len = UInt128(a: UInt64(aadLength * 8), b: UInt64(ciphertextLength * 8)) + x = GF.multiply(self.x ^ len, self.h) + return self.x + } + + // GHASH. One-time calculation + static func ghash(x startx: UInt128 = 0, h: UInt128, aad: Array, ciphertext: Array, blockSize: Int) -> UInt128 { + var x = self.calculateX(aad: aad, x: startx, h: h, blockSize: blockSize) + x = self.calculateX(ciphertext: ciphertext, x: x, h: h, blockSize: blockSize) + + // len(aad) || len(ciphertext) + let len = UInt128(a: UInt64(aad.count * 8), b: UInt64(ciphertext.count * 8)) + x = self.multiply(x ^ len, h) + + return x + } + + // Calculate Ciphertext part, for all blocks + // Not used with incremental calculation. + private static func calculateX(ciphertext: [UInt8], x startx: UInt128, h: UInt128, blockSize: Int) -> UInt128 { + let pciphertext = addPadding(ciphertext, blockSize: blockSize) + let blocksCount = pciphertext.count / blockSize + + var x = startx + for i in 0.., x: UInt128, h: UInt128, blockSize: Int) -> UInt128 { + let k = x ^ UInt128(ciphertextBlock) + return self.multiply(k, h) + } + + // Calculate AAD part, for all blocks + private static func calculateX(aad: [UInt8], x startx: UInt128, h: UInt128, blockSize: Int) -> UInt128 { + let paad = addPadding(aad, blockSize: blockSize) + let blocksCount = paad.count / blockSize + + var x = startx + for i in 0.. UInt128 { + var z: UInt128 = 0 + var v = x + var k = UInt128(a: 1 << 63, b: 0) + + for _ in 0..<128 { + if y & k == k { + z = z ^ v + } + + if v & 1 != 1 { + v = v >> 1 + } else { + v = (v >> 1) ^ self.r + } + + k = k >> 1 + } + + return z + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/OCB.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/OCB.swift new file mode 100644 index 000000000..4741793c7 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/OCB.swift @@ -0,0 +1,398 @@ +// +// CryptoSwift +// +// Copyright (C) Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// The OCB Authenticated-Encryption Algorithm +// https://tools.ietf.org/html/rfc7253 +// + +public final class OCB: BlockMode { + + public enum Mode { + /// In combined mode, the authentication tag is directly appended to the encrypted message. This is usually what you want. + case combined + /// Some applications may need to store the authentication tag and the encrypted message at different locations. + case detached + } + + public let options: BlockModeOption = [.initializationVectorRequired] + + public enum Error: Swift.Error { + case invalidNonce + case fail + } + + private let N: Array + private let additionalAuthenticatedData: Array? + private let mode: Mode + public let customBlockSize: Int? = nil + + /// Length of authentication tag, in bytes. + /// For encryption, the value is given as init parameter. + /// For decryption, the length of given authentication tag is used. + private let tagLength: Int + + // `authenticationTag` nil for encryption, known tag for decryption + /// For encryption, the value is set at the end of the encryption. + /// For decryption, this is a known Tag to validate against. + public var authenticationTag: Array? + + // encrypt + public init(nonce N: Array, additionalAuthenticatedData: Array? = nil, tagLength: Int = 16, mode: Mode = .detached) { + self.N = N + self.additionalAuthenticatedData = additionalAuthenticatedData + self.mode = mode + self.tagLength = tagLength + } + + // decrypt + @inlinable + public convenience init(nonce N: Array, authenticationTag: Array, additionalAuthenticatedData: Array? = nil, mode: Mode = .detached) { + self.init(nonce: N, additionalAuthenticatedData: additionalAuthenticatedData, tagLength: authenticationTag.count, mode: mode) + self.authenticationTag = authenticationTag + } + + public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock, encryptionOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker { + if self.N.isEmpty || self.N.count > 15 { + throw Error.invalidNonce + } + + let worker = OCBModeWorker(N: N.slice, aad: self.additionalAuthenticatedData?.slice, expectedTag: self.authenticationTag, tagLength: self.tagLength, mode: self.mode, cipherOperation: cipherOperation, encryptionOperation: encryptionOperation) + worker.didCalculateTag = { [weak self] tag in + self?.authenticationTag = tag + } + return worker + } +} + +// MARK: - Worker + +final class OCBModeWorker: BlockModeWorker, FinalizingEncryptModeWorker, FinalizingDecryptModeWorker { + + let cipherOperation: CipherOperationOnBlock + var hashOperation: CipherOperationOnBlock! + + // Callback called when authenticationTag is ready + var didCalculateTag: ((Array) -> Void)? + + private let tagLength: Int + + let blockSize = 16 // 128 bit + var additionalBufferSize: Int + private let mode: OCB.Mode + + // Additional authenticated data + private let aad: ArraySlice? + // Known Tag used to validate during decryption + private var expectedTag: Array? + + /* + * KEY-DEPENDENT + */ + // NOTE: elements are lazily calculated + private var l = [Array]() + private var lAsterisk: Array + private var lDollar: Array + + /* + * PER-ENCRYPTION/DECRYPTION + */ + private var mainBlockCount: UInt64 + private var offsetMain: Array + private var checksum: Array + + init(N: ArraySlice, aad: ArraySlice? = nil, expectedTag: Array? = nil, tagLength: Int, mode: OCB.Mode, cipherOperation: @escaping CipherOperationOnBlock, encryptionOperation: @escaping CipherOperationOnBlock) { + + self.cipherOperation = cipherOperation + self.hashOperation = encryptionOperation + self.mode = mode + self.aad = aad + self.expectedTag = expectedTag + self.tagLength = tagLength + + if mode == .combined { + self.additionalBufferSize = tagLength + } else { + self.additionalBufferSize = 0 + } + + /* + * KEY-DEPENDENT INITIALIZATION + */ + + let zeros = Array(repeating: 0, count: self.blockSize) + self.lAsterisk = self.hashOperation(zeros.slice)! /// L_* = ENCIPHER(K, zeros(128)) + self.lDollar = double(self.lAsterisk) /// L_$ = double(L_*) + self.l.append(double(self.lDollar)) /// L_0 = double(L_$) + + /* + * NONCE-DEPENDENT AND PER-ENCRYPTION/DECRYPTION INITIALIZATION + */ + + /// Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N + var nonce = Array(repeating: 0, count: blockSize) + nonce[(nonce.count - N.count)...] = N + nonce[0] = UInt8(tagLength) << 4 + nonce[blockSize - 1 - N.count] |= 1 + + /// bottom = str2num(Nonce[123..128]) + let bottom = nonce[15] & 0x3F + + /// Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6)) + nonce[15] &= 0xC0 + let Ktop = self.hashOperation(nonce.slice)! + + /// Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72]) + let Stretch = Ktop + xor(Ktop[0..<8], Ktop[1..<9]) + + /// Offset_0 = Stretch[1+bottom..128+bottom] + var offsetMAIN_0 = Array(repeating: 0, count: blockSize) + let bits = bottom % 8 + let bytes = Int(bottom / 8) + if bits == 0 { + offsetMAIN_0[0..> (8 - bits))) + } + } + + self.mainBlockCount = 0 + self.offsetMain = Array(offsetMAIN_0.slice) + self.checksum = Array(repeating: 0, count: self.blockSize) /// Checksum_0 = zeros(128) + } + + /// L_i = double(L_{i-1}) for every integer i > 0 + func getLSub(_ n: Int) -> Array { + while n >= self.l.count { + self.l.append(double(self.l.last!)) + } + return self.l[n] + } + + func computeTag() -> Array { + + let sum = self.hashAAD() + + /// Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A) + return xor(self.hashOperation(xor(xor(self.checksum, self.offsetMain).slice, self.lDollar))!, sum) + } + + func hashAAD() -> Array { + var sum = Array(repeating: 0, count: blockSize) + + guard let aad = self.aad else { + return sum + } + + var offset = Array(repeating: 0, count: blockSize) + var blockCount: UInt64 = 1 + for aadBlock in aad.batched(by: self.blockSize) { + + if aadBlock.count == self.blockSize { + + /// Offset_i = Offset_{i-1} xor L_{ntz(i)} + offset = xor(offset, self.getLSub(ntz(blockCount))) + + /// Sum_i = Sum_{i-1} xor ENCIPHER(K, A_i xor Offset_i) + sum = xor(sum, self.hashOperation(xor(aadBlock, offset))!) + } else { + if !aadBlock.isEmpty { + + /// Offset_* = Offset_m xor L_* + offset = xor(offset, self.lAsterisk) + + /// CipherInput = (A_* || 1 || zeros(127-bitlen(A_*))) xor Offset_* + let cipherInput: Array = xor(extend(aadBlock, size: blockSize), offset) + + /// Sum = Sum_m xor ENCIPHER(K, CipherInput) + sum = xor(sum, self.hashOperation(cipherInput.slice)!) + } + } + blockCount += 1 + } + + return sum + } + + func encrypt(block plaintext: ArraySlice) -> Array { + + if plaintext.count == self.blockSize { + return self.processBlock(block: plaintext, forEncryption: true) + } else { + return self.processFinalBlock(block: plaintext, forEncryption: true) + } + } + + func finalize(encrypt ciphertext: ArraySlice) throws -> ArraySlice { + + let tag = self.computeTag() + + self.didCalculateTag?(tag) + + switch self.mode { + case .combined: + return ciphertext + tag + case .detached: + return ciphertext + } + } + + func decrypt(block ciphertext: ArraySlice) -> Array { + + if ciphertext.count == self.blockSize { + return self.processBlock(block: ciphertext, forEncryption: false) + } else { + return self.processFinalBlock(block: ciphertext, forEncryption: false) + } + } + + func finalize(decrypt plaintext: ArraySlice) throws -> ArraySlice { + // do nothing + plaintext + } + + private func processBlock(block: ArraySlice, forEncryption: Bool) -> Array { + + /* + * OCB-ENCRYPT/OCB-DECRYPT: Process any whole blocks + */ + + self.mainBlockCount += 1 + + /// Offset_i = Offset_{i-1} xor L_{ntz(i)} + self.offsetMain = xor(self.offsetMain, self.getLSub(ntz(self.mainBlockCount))) + + /// C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i) + /// P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i) + var mainBlock = Array(block) + mainBlock = xor(mainBlock, offsetMain) + mainBlock = self.cipherOperation(mainBlock.slice)! + mainBlock = xor(mainBlock, self.offsetMain) + + /// Checksum_i = Checksum_{i-1} xor P_i + if forEncryption { + self.checksum = xor(self.checksum, block) + } else { + self.checksum = xor(self.checksum, mainBlock) + } + + return mainBlock + } + + private func processFinalBlock(block: ArraySlice, forEncryption: Bool) -> Array { + + let out: Array + + if block.isEmpty { + /// C_* = + /// P_* = + out = [] + + } else { + + /// Offset_* = Offset_m xor L_* + self.offsetMain = xor(self.offsetMain, self.lAsterisk) + + /// Pad = ENCIPHER(K, Offset_*) + let Pad = self.hashOperation(self.offsetMain.slice)! + + /// C_* = P_* xor Pad[1..bitlen(P_*)] + /// P_* = C_* xor Pad[1..bitlen(C_*)] + out = xor(block, Pad[0..) throws -> ArraySlice { + // Validate tag + switch self.mode { + case .combined: + // overwrite expectedTag property used later for verification + self.expectedTag = Array(ciphertext.suffix(self.tagLength)) + return ciphertext[ciphertext.startIndex..) throws -> ArraySlice { + // Calculate MAC tag. + let computedTag = self.computeTag() + + // Validate tag + guard let expectedTag = self.expectedTag, computedTag == expectedTag else { + throw OCB.Error.fail + } + + return plaintext + } +} + +// MARK: - Local utils + +private func ntz(_ x: UInt64) -> Int { + if x == 0 { + return 64 + } + + var xv = x + var n = 0 + while (xv & 1) == 0 { + n += 1 + xv = xv >> 1 + } + return n +} + +private func double(_ block: Array) -> Array { + var ( carry, result) = shiftLeft(block) + + /* + * NOTE: This construction is an attempt at a constant-time implementation. + */ + result[15] ^= (0x87 >> ((1 - carry) << 3)) + + return result +} + +private func shiftLeft(_ block: Array) -> (UInt8, Array) { + var output = Array(repeating: 0, count: block.count) + + var bit: UInt8 = 0 + + for i in 0..> 7) & 1 + } + return (bit, output) +} + +private func extend(_ block: ArraySlice, size: Int) -> Array { + var output = Array(repeating: 0, count: size) + output[0.. +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// Output Feedback (OFB) +// + +public struct OFB: BlockMode { + public enum Error: Swift.Error { + /// Invalid IV + case invalidInitializationVector + } + + public let options: BlockModeOption = [.initializationVectorRequired, .useEncryptToDecrypt] + private let iv: Array + public let customBlockSize: Int? = nil + + public init(iv: Array) { + self.iv = iv + } + + public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock, encryptionOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker { + if self.iv.count != blockSize { + throw Error.invalidInitializationVector + } + + return OFBModeWorker(blockSize: blockSize, iv: self.iv.slice, cipherOperation: cipherOperation) + } +} + +struct OFBModeWorker: BlockModeWorker { + let cipherOperation: CipherOperationOnBlock + let blockSize: Int + let additionalBufferSize: Int = 0 + private let iv: ArraySlice + private var prev: ArraySlice? + + init(blockSize: Int, iv: ArraySlice, cipherOperation: @escaping CipherOperationOnBlock) { + self.blockSize = blockSize + self.iv = iv + self.cipherOperation = cipherOperation + } + + @inlinable + mutating func encrypt(block plaintext: ArraySlice) -> Array { + guard let ciphertext = cipherOperation(prev ?? iv) else { + return Array(plaintext) + } + self.prev = ciphertext.slice + return xor(plaintext, ciphertext) + } + + @inlinable + mutating func decrypt(block ciphertext: ArraySlice) -> Array { + guard let decrypted = cipherOperation(prev ?? iv) else { + return Array(ciphertext) + } + let plaintext: Array = xor(decrypted, ciphertext) + prev = decrypted.slice + return plaintext + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/PCBC.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/PCBC.swift new file mode 100644 index 000000000..c6092475a --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/PCBC.swift @@ -0,0 +1,74 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// Propagating Cipher Block Chaining (PCBC) +// + +public struct PCBC: BlockMode { + public enum Error: Swift.Error { + /// Invalid IV + case invalidInitializationVector + } + + public let options: BlockModeOption = [.initializationVectorRequired, .paddingRequired] + private let iv: Array + public let customBlockSize: Int? = nil + + public init(iv: Array) { + self.iv = iv + } + + public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock, encryptionOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker { + if self.iv.count != blockSize { + throw Error.invalidInitializationVector + } + + return PCBCModeWorker(blockSize: blockSize, iv: self.iv.slice, cipherOperation: cipherOperation) + } +} + +struct PCBCModeWorker: BlockModeWorker { + let cipherOperation: CipherOperationOnBlock + var blockSize: Int + let additionalBufferSize: Int = 0 + private let iv: ArraySlice + private var prev: ArraySlice? + + @inlinable + init(blockSize: Int, iv: ArraySlice, cipherOperation: @escaping CipherOperationOnBlock) { + self.blockSize = blockSize + self.iv = iv + self.cipherOperation = cipherOperation + } + + @inlinable + mutating func encrypt(block plaintext: ArraySlice) -> Array { + guard let ciphertext = cipherOperation(xor(prev ?? iv, plaintext)) else { + return Array(plaintext) + } + self.prev = xor(plaintext, ciphertext.slice) + return ciphertext + } + + @inlinable + mutating func decrypt(block ciphertext: ArraySlice) -> Array { + guard let plaintext = cipherOperation(ciphertext) else { + return Array(ciphertext) + } + let result: Array = xor(prev ?? self.iv, plaintext) + self.prev = xor(plaintext.slice, ciphertext) + return result + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Blowfish.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Blowfish.swift new file mode 100644 index 000000000..8876fca2f --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Blowfish.swift @@ -0,0 +1,537 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// https://en.wikipedia.org/wiki/Blowfish_(cipher) +// Based on Paul Kocher implementation +// + +public final class Blowfish { + public enum Error: Swift.Error { + /// Data padding is required + case dataPaddingRequired + /// Invalid key or IV + case invalidKeyOrInitializationVector + /// Invalid IV + case invalidInitializationVector + /// Invalid block mode + case invalidBlockMode + } + + public static let blockSize: Int = 8 // 64 bit + public let keySize: Int + + private let blockMode: BlockMode + private let padding: Padding + private var decryptWorker: CipherModeWorker! + private var encryptWorker: CipherModeWorker! + + private let N = 16 // rounds + private var P: Array + private var S: Array> + private let origP: Array = [ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, + 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, + 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, + 0xb5470917, 0x9216d5d9, 0x8979fb1b + ] + + private let origS: Array> = [ + [ + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, + 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, + 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, + 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, + 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, + 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, + 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, + 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, + 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, + 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, + 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, + 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, + 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, + 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, + 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, + 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, + 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, + 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, + 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, + 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, + 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, + 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, + 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, + 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, + 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, + 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, + 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, + 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, + 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, + 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, + 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, + 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, + 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, + 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, + 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, + 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, + 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, + 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, + 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, + 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, + 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, + 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, + 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, + 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, + 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, + 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, + 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, + 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, + 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, + 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a + ], + [ + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, + 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, + 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, + 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, + 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, + 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, + 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, + 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, + 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, + 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, + 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, + 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, + 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, + 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, + 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, + 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, + 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, + 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, + 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, + 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, + 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, + 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, + 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, + 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, + 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, + 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, + 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, + 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, + 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, + 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, + 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, + 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, + 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, + 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, + 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, + 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, + 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, + 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, + 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, + 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, + 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, + 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, + 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 + ], + [ + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, + 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, + 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, + 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, + 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, + 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, + 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, + 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, + 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, + 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, + 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, + 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, + 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, + 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, + 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, + 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, + 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, + 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, + 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, + 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, + 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, + 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, + 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, + 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, + 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, + 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, + 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, + 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, + 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, + 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, + 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, + 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, + 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, + 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, + 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, + 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, + 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, + 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, + 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, + 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, + 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, + 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, + 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, + 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, + 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, + 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, + 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, + 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, + 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, + 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0 + ], + [ + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, + 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, + 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, + 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, + 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, + 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, + 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, + 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, + 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, + 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, + 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, + 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, + 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, + 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, + 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, + 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, + 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, + 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, + 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, + 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, + 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, + 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, + 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, + 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, + 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, + 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, + 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, + 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, + 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, + 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, + 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, + 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, + 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, + 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, + 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, + 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, + 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, + 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, + 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, + 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, + 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, + 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, + 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, + 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, + 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, + 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, + 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, + 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, + 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, + 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, + 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 + ] + ] + + public init(key: Array, blockMode: BlockMode = CBC(iv: Array(repeating: 0, count: Blowfish.blockSize)), padding: Padding) throws { + precondition(key.count >= 5 && key.count <= 56) + + self.blockMode = blockMode + self.padding = padding + self.keySize = key.count + + self.S = self.origS + self.P = self.origP + + self.expandKey(key: key) + try self.setupBlockModeWorkers() + } + + private func setupBlockModeWorkers() throws { + self.encryptWorker = try self.blockMode.worker(blockSize: Blowfish.blockSize, cipherOperation: self.encrypt, encryptionOperation: self.encrypt) + + if self.blockMode.options.contains(.useEncryptToDecrypt) { + self.decryptWorker = try self.blockMode.worker(blockSize: Blowfish.blockSize, cipherOperation: self.encrypt, encryptionOperation: self.encrypt) + } else { + self.decryptWorker = try self.blockMode.worker(blockSize: Blowfish.blockSize, cipherOperation: self.decrypt, encryptionOperation: self.encrypt) + } + } + + private func reset() { + self.S = self.origS + self.P = self.origP + // todo expand key + } + + private func expandKey(key: Array) { + var j = 0 + for i in 0..<(self.N + 2) { + var data: UInt32 = 0x0 + for _ in 0..<4 { + data = (data << 8) | UInt32(key[j]) + j += 1 + if j >= key.count { + j = 0 + } + } + self.P[i] ^= data + } + + var datal: UInt32 = 0 + var datar: UInt32 = 0 + + for i in stride(from: 0, to: self.N + 2, by: 2) { + self.encryptBlowfishBlock(l: &datal, r: &datar) + self.P[i] = datal + self.P[i + 1] = datar + } + + for i in 0..<4 { + for j in stride(from: 0, to: 256, by: 2) { + self.encryptBlowfishBlock(l: &datal, r: &datar) + self.S[i][j] = datal + self.S[i][j + 1] = datar + } + } + } + + fileprivate func encrypt(block: ArraySlice) -> Array? { + var result = Array() + + var l = UInt32(bytes: block[block.startIndex..> 24) & 0xff), + UInt8((l >> 16) & 0xff) + ] + result += [ + UInt8((l >> 8) & 0xff), + UInt8((l >> 0) & 0xff) + ] + result += [ + UInt8((r >> 24) & 0xff), + UInt8((r >> 16) & 0xff) + ] + result += [ + UInt8((r >> 8) & 0xff), + UInt8((r >> 0) & 0xff) + ] + + return result + } + + fileprivate func decrypt(block: ArraySlice) -> Array? { + var result = Array() + + var l = UInt32(bytes: block[block.startIndex..> 24) & 0xff), + UInt8((l >> 16) & 0xff) + ] + result += [ + UInt8((l >> 8) & 0xff), + UInt8((l >> 0) & 0xff) + ] + result += [ + UInt8((r >> 24) & 0xff), + UInt8((r >> 16) & 0xff) + ] + result += [ + UInt8((r >> 8) & 0xff), + UInt8((r >> 0) & 0xff) + ] + return result + } + + /// Encrypts the 8-byte padded buffer + /// + /// - Parameters: + /// - l: left half + /// - r: right half + private func encryptBlowfishBlock(l: inout UInt32, r: inout UInt32) { + var Xl = l + var Xr = r + + for i in 0.. UInt32 { + let f1 = self.S[0][Int(x >> 24) & 0xff] + let f2 = self.S[1][Int(x >> 16) & 0xff] + let f3 = self.S[2][Int(x >> 8) & 0xff] + let f4 = self.S[3][Int(x & 0xff)] + return ((f1 &+ f2) ^ f3) &+ f4 + } +} + +extension Blowfish: Cipher { + /// Encrypt the 8-byte padded buffer, block by block. Note that for amounts of data larger than a block, it is not safe to just call encrypt() on successive blocks. + /// + /// - Parameter bytes: Plaintext data + /// - Returns: Encrypted data + public func encrypt(_ bytes: C) throws -> Array where C.Element == UInt8, C.Index == Int { + let bytes = self.padding.add(to: Array(bytes), blockSize: Blowfish.blockSize) // FIXME: Array(bytes) copies + + var out = Array() + out.reserveCapacity(bytes.count) + + for chunk in bytes.batched(by: Blowfish.blockSize) { + out += self.encryptWorker.encrypt(block: chunk) + } + + if self.blockMode.options.contains(.paddingRequired) && (out.count % Blowfish.blockSize != 0) { + throw Error.dataPaddingRequired + } + + return out + } + + /// Decrypt the 8-byte padded buffer + /// + /// - Parameter bytes: Ciphertext data + /// - Returns: Plaintext data + public func decrypt(_ bytes: C) throws -> Array where C.Element == UInt8, C.Index == Int { + if self.blockMode.options.contains(.paddingRequired) && (bytes.count % Blowfish.blockSize != 0) { + throw Error.dataPaddingRequired + } + + var out = Array() + out.reserveCapacity(bytes.count) + + for chunk in Array(bytes).batched(by: Blowfish.blockSize) { + out += self.decryptWorker.decrypt(block: chunk) // FIXME: copying here is innefective + } + + out = self.padding.remove(from: out, blockSize: Blowfish.blockSize) + + return out + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/CBCMAC.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/CBCMAC.swift new file mode 100644 index 000000000..941e4d1fa --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/CBCMAC.swift @@ -0,0 +1,30 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public final class CBCMAC: CMAC { + public override func authenticate(_ bytes: Array) throws -> Array { + var inBytes = bytes + bitPadding(to: &inBytes, blockSize: CMAC.BlockSize) + let blocks = inBytes.batched(by: CMAC.BlockSize) + + var lastBlockEncryptionResult: [UInt8] = CBCMAC.Zero + try blocks.forEach { block in + let aes = try AES(key: Array(key), blockMode: CBC(iv: lastBlockEncryptionResult), padding: .noPadding) + lastBlockEncryptionResult = try aes.encrypt(block) + } + + return lastBlockEncryptionResult + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/CMAC.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/CMAC.swift new file mode 100644 index 000000000..f0e691cda --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/CMAC.swift @@ -0,0 +1,106 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public class CMAC: Authenticator { + public enum Error: Swift.Error { + case wrongKeyLength + } + + internal let key: SecureBytes + + internal static let BlockSize: Int = 16 + internal static let Zero: Array = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] + private static let Rb: Array = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87] + + public init(key: Array) throws { + self.key = SecureBytes(bytes: key) + } + + // MARK: Authenticator + + // AES-CMAC + public func authenticate(_ bytes: Array) throws -> Array { + let cipher = try AES(key: Array(key), blockMode: CBC(iv: CMAC.Zero), padding: .noPadding) + return try self.authenticate(bytes, cipher: cipher) + } + + // CMAC using a Cipher + public func authenticate(_ bytes: Array, cipher: Cipher) throws -> Array { + let l = try cipher.encrypt(CMAC.Zero) + var subKey1 = self.leftShiftOneBit(l) + if (l[0] & 0x80) != 0 { + subKey1 = xor(CMAC.Rb, subKey1) + } + var subKey2 = self.leftShiftOneBit(subKey1) + if (subKey1[0] & 0x80) != 0 { + subKey2 = xor(CMAC.Rb, subKey2) + } + + let lastBlockComplete: Bool + let blockCount = (bytes.count + CMAC.BlockSize - 1) / CMAC.BlockSize + if blockCount == 0 { + lastBlockComplete = false + } else { + lastBlockComplete = bytes.count % CMAC.BlockSize == 0 + } + var paddedBytes = bytes + if !lastBlockComplete { + bitPadding(to: &paddedBytes, blockSize: CMAC.BlockSize) + } + + var blocks = Array(paddedBytes.batched(by: CMAC.BlockSize)) + var lastBlock = blocks.popLast()! + if lastBlockComplete { + lastBlock = xor(lastBlock, subKey1) + } else { + lastBlock = xor(lastBlock, subKey2) + } + + var x = Array(repeating: 0x00, count: CMAC.BlockSize) + var y = Array(repeating: 0x00, count: CMAC.BlockSize) + for block in blocks { + y = xor(block, x) + x = try cipher.encrypt(y) + } + // the difference between CMAC and CBC-MAC is that CMAC xors the final block with a secret value + y = self.process(lastBlock: lastBlock, with: x) + return try cipher.encrypt(y) + } + + func process(lastBlock: ArraySlice, with x: [UInt8]) -> [UInt8] { + xor(lastBlock, x) + } + + // MARK: Helper methods + + /** + Performs left shift by one bit to the bit string aquired after concatenating al bytes in the byte array + - parameters: + - bytes: byte array + - returns: bit shifted bit string split again in array of bytes + */ + private func leftShiftOneBit(_ bytes: Array) -> Array { + var shifted = Array(repeating: 0x00, count: bytes.count) + let last = bytes.count - 1 + for index in 0.. +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// https://tools.ietf.org/html/rfc7539 +// + +public final class ChaCha20: BlockCipher { + public enum Error: Swift.Error { + case invalidKeyOrInitializationVector + case notSupported + } + + public static let blockSize = 64 // 512 / 8 + public let keySize: Int + + fileprivate let key: Key + fileprivate var counter: Array + + public init(key: Array, iv nonce: Array) throws { + precondition(nonce.count == 12 || nonce.count == 8) + + if key.count != 32 { + throw Error.invalidKeyOrInitializationVector + } + + self.key = Key(bytes: key) + self.keySize = self.key.count + + if nonce.count == 8 { + self.counter = [0, 0, 0, 0, 0, 0, 0, 0] + nonce + } else { + self.counter = [0, 0, 0, 0] + nonce + } + + assert(self.counter.count == 16) + } + + /// https://tools.ietf.org/html/rfc7539#section-2.3. + fileprivate func core(block: inout Array, counter: Array, key: Array) { + precondition(block.count == ChaCha20.blockSize) + precondition(counter.count == 16) + precondition(key.count == 32) + + let j0: UInt32 = 0x61707865 + let j1: UInt32 = 0x3320646e // 0x3620646e sigma/tau + let j2: UInt32 = 0x79622d32 + let j3: UInt32 = 0x6b206574 + let j4: UInt32 = UInt32(bytes: key[0..<4]).bigEndian + let j5: UInt32 = UInt32(bytes: key[4..<8]).bigEndian + let j6: UInt32 = UInt32(bytes: key[8..<12]).bigEndian + let j7: UInt32 = UInt32(bytes: key[12..<16]).bigEndian + let j8: UInt32 = UInt32(bytes: key[16..<20]).bigEndian + let j9: UInt32 = UInt32(bytes: key[20..<24]).bigEndian + let j10: UInt32 = UInt32(bytes: key[24..<28]).bigEndian + let j11: UInt32 = UInt32(bytes: key[28..<32]).bigEndian + let j12: UInt32 = UInt32(bytes: counter[0..<4]).bigEndian + let j13: UInt32 = UInt32(bytes: counter[4..<8]).bigEndian + let j14: UInt32 = UInt32(bytes: counter[8..<12]).bigEndian + let j15: UInt32 = UInt32(bytes: counter[12..<16]).bigEndian + + var (x0, x1, x2, x3, x4, x5, x6, x7) = (j0, j1, j2, j3, j4, j5, j6, j7) + var (x8, x9, x10, x11, x12, x13, x14, x15) = (j8, j9, j10, j11, j12, j13, j14, j15) + + for _ in 0..<10 { // 20 rounds + x0 = x0 &+ x4 + x12 ^= x0 + x12 = (x12 << 16) | (x12 >> 16) + x8 = x8 &+ x12 + x4 ^= x8 + x4 = (x4 << 12) | (x4 >> 20) + x0 = x0 &+ x4 + x12 ^= x0 + x12 = (x12 << 8) | (x12 >> 24) + x8 = x8 &+ x12 + x4 ^= x8 + x4 = (x4 << 7) | (x4 >> 25) + x1 = x1 &+ x5 + x13 ^= x1 + x13 = (x13 << 16) | (x13 >> 16) + x9 = x9 &+ x13 + x5 ^= x9 + x5 = (x5 << 12) | (x5 >> 20) + x1 = x1 &+ x5 + x13 ^= x1 + x13 = (x13 << 8) | (x13 >> 24) + x9 = x9 &+ x13 + x5 ^= x9 + x5 = (x5 << 7) | (x5 >> 25) + x2 = x2 &+ x6 + x14 ^= x2 + x14 = (x14 << 16) | (x14 >> 16) + x10 = x10 &+ x14 + x6 ^= x10 + x6 = (x6 << 12) | (x6 >> 20) + x2 = x2 &+ x6 + x14 ^= x2 + x14 = (x14 << 8) | (x14 >> 24) + x10 = x10 &+ x14 + x6 ^= x10 + x6 = (x6 << 7) | (x6 >> 25) + x3 = x3 &+ x7 + x15 ^= x3 + x15 = (x15 << 16) | (x15 >> 16) + x11 = x11 &+ x15 + x7 ^= x11 + x7 = (x7 << 12) | (x7 >> 20) + x3 = x3 &+ x7 + x15 ^= x3 + x15 = (x15 << 8) | (x15 >> 24) + x11 = x11 &+ x15 + x7 ^= x11 + x7 = (x7 << 7) | (x7 >> 25) + x0 = x0 &+ x5 + x15 ^= x0 + x15 = (x15 << 16) | (x15 >> 16) + x10 = x10 &+ x15 + x5 ^= x10 + x5 = (x5 << 12) | (x5 >> 20) + x0 = x0 &+ x5 + x15 ^= x0 + x15 = (x15 << 8) | (x15 >> 24) + x10 = x10 &+ x15 + x5 ^= x10 + x5 = (x5 << 7) | (x5 >> 25) + x1 = x1 &+ x6 + x12 ^= x1 + x12 = (x12 << 16) | (x12 >> 16) + x11 = x11 &+ x12 + x6 ^= x11 + x6 = (x6 << 12) | (x6 >> 20) + x1 = x1 &+ x6 + x12 ^= x1 + x12 = (x12 << 8) | (x12 >> 24) + x11 = x11 &+ x12 + x6 ^= x11 + x6 = (x6 << 7) | (x6 >> 25) + x2 = x2 &+ x7 + x13 ^= x2 + x13 = (x13 << 16) | (x13 >> 16) + x8 = x8 &+ x13 + x7 ^= x8 + x7 = (x7 << 12) | (x7 >> 20) + x2 = x2 &+ x7 + x13 ^= x2 + x13 = (x13 << 8) | (x13 >> 24) + x8 = x8 &+ x13 + x7 ^= x8 + x7 = (x7 << 7) | (x7 >> 25) + x3 = x3 &+ x4 + x14 ^= x3 + x14 = (x14 << 16) | (x14 >> 16) + x9 = x9 &+ x14 + x4 ^= x9 + x4 = (x4 << 12) | (x4 >> 20) + x3 = x3 &+ x4 + x14 ^= x3 + x14 = (x14 << 8) | (x14 >> 24) + x9 = x9 &+ x14 + x4 ^= x9 + x4 = (x4 << 7) | (x4 >> 25) + } + + x0 = x0 &+ j0 + x1 = x1 &+ j1 + x2 = x2 &+ j2 + x3 = x3 &+ j3 + x4 = x4 &+ j4 + x5 = x5 &+ j5 + x6 = x6 &+ j6 + x7 = x7 &+ j7 + x8 = x8 &+ j8 + x9 = x9 &+ j9 + x10 = x10 &+ j10 + x11 = x11 &+ j11 + x12 = x12 &+ j12 + x13 = x13 &+ j13 + x14 = x14 &+ j14 + x15 = x15 &+ j15 + + block.replaceSubrange(0..<4, with: x0.bigEndian.bytes()) + block.replaceSubrange(4..<8, with: x1.bigEndian.bytes()) + block.replaceSubrange(8..<12, with: x2.bigEndian.bytes()) + block.replaceSubrange(12..<16, with: x3.bigEndian.bytes()) + block.replaceSubrange(16..<20, with: x4.bigEndian.bytes()) + block.replaceSubrange(20..<24, with: x5.bigEndian.bytes()) + block.replaceSubrange(24..<28, with: x6.bigEndian.bytes()) + block.replaceSubrange(28..<32, with: x7.bigEndian.bytes()) + block.replaceSubrange(32..<36, with: x8.bigEndian.bytes()) + block.replaceSubrange(36..<40, with: x9.bigEndian.bytes()) + block.replaceSubrange(40..<44, with: x10.bigEndian.bytes()) + block.replaceSubrange(44..<48, with: x11.bigEndian.bytes()) + block.replaceSubrange(48..<52, with: x12.bigEndian.bytes()) + block.replaceSubrange(52..<56, with: x13.bigEndian.bytes()) + block.replaceSubrange(56..<60, with: x14.bigEndian.bytes()) + block.replaceSubrange(60..<64, with: x15.bigEndian.bytes()) + } + + // XORKeyStream + func process(bytes: ArraySlice, counter: inout Array, key: Array) -> Array { + precondition(counter.count == 16) + precondition(key.count == 32) + + var block = Array(repeating: 0, count: ChaCha20.blockSize) + var bytesSlice = bytes + var out = Array(reserveCapacity: bytesSlice.count) + + while bytesSlice.count >= ChaCha20.blockSize { + self.core(block: &block, counter: counter, key: key) + for (i, x) in block.enumerated() { + out.append(bytesSlice[bytesSlice.startIndex + i] ^ x) + } + var u: UInt32 = 1 + for i in 0..<4 { + u += UInt32(counter[i]) + counter[i] = UInt8(u & 0xff) + u >>= 8 + } + bytesSlice = bytesSlice[bytesSlice.startIndex + ChaCha20.blockSize..) throws -> Array { + self.process(bytes: bytes, counter: &self.counter, key: Array(self.key)) + } + + public func decrypt(_ bytes: ArraySlice) throws -> Array { + try self.encrypt(bytes) + } +} + +// MARK: Encryptor + +extension ChaCha20 { + public struct ChaChaEncryptor: Cryptor, Updatable { + private var accumulated = Array() + private let chacha: ChaCha20 + + init(chacha: ChaCha20) { + self.chacha = chacha + } + + public mutating func update(withBytes bytes: ArraySlice, isLast: Bool = false) throws -> Array { + self.accumulated += bytes + + var encrypted = Array() + encrypted.reserveCapacity(self.accumulated.count) + for chunk in self.accumulated.batched(by: ChaCha20.blockSize) { + if isLast || self.accumulated.count >= ChaCha20.blockSize { + encrypted += try self.chacha.encrypt(chunk) + self.accumulated.removeFirst(chunk.count) // TODO: improve performance + } + } + return encrypted + } + + public func seek(to: Int) throws { + throw Error.notSupported + } + } +} + +// MARK: Decryptor + +extension ChaCha20 { + public struct ChaChaDecryptor: Cryptor, Updatable { + private var accumulated = Array() + + private var offset: Int = 0 + private var offsetToRemove: Int = 0 + private let chacha: ChaCha20 + + init(chacha: ChaCha20) { + self.chacha = chacha + } + + public mutating func update(withBytes bytes: ArraySlice, isLast: Bool = true) throws -> Array { + // prepend "offset" number of bytes at the beginning + if self.offset > 0 { + self.accumulated += Array(repeating: 0, count: self.offset) + bytes + self.offsetToRemove = self.offset + self.offset = 0 + } else { + self.accumulated += bytes + } + + var plaintext = Array() + plaintext.reserveCapacity(self.accumulated.count) + for chunk in self.accumulated.batched(by: ChaCha20.blockSize) { + if isLast || self.accumulated.count >= ChaCha20.blockSize { + plaintext += try self.chacha.decrypt(chunk) + + // remove "offset" from the beginning of first chunk + if self.offsetToRemove > 0 { + plaintext.removeFirst(self.offsetToRemove) // TODO: improve performance + self.offsetToRemove = 0 + } + + self.accumulated.removeFirst(chunk.count) + } + } + + return plaintext + } + + public func seek(to: Int) throws { + throw Error.notSupported + } + } +} + +// MARK: Cryptors + +extension ChaCha20: Cryptors { + //TODO: Use BlockEncryptor/BlockDecryptor + + public func makeEncryptor() -> Cryptor & Updatable { + ChaCha20.ChaChaEncryptor(chacha: self) + } + + public func makeDecryptor() -> Cryptor & Updatable { + ChaCha20.ChaChaDecryptor(chacha: self) + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Checksum.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Checksum.swift new file mode 100644 index 000000000..26ec12882 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Checksum.swift @@ -0,0 +1,208 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +/// CRC - cyclic redundancy check code. +public final class Checksum { + + @usableFromInline + static let table32: Array = [ + 0x0000_0000, 0x7707_3096, 0xEE0E_612C, 0x9909_51BA, 0x076D_C419, 0x706A_F48F, 0xE963_A535, 0x9E64_95A3, + 0x0EDB_8832, 0x79DC_B8A4, 0xE0D5_E91E, 0x97D2_D988, 0x09B6_4C2B, 0x7EB1_7CBD, 0xE7B8_2D07, 0x90BF_1D91, + 0x1DB7_1064, 0x6AB0_20F2, 0xF3B9_7148, 0x84BE_41DE, 0x1ADA_D47D, 0x6DDD_E4EB, 0xF4D4_B551, 0x83D3_85C7, + 0x136C_9856, 0x646B_A8C0, 0xFD62_F97A, 0x8A65_C9EC, 0x1401_5C4F, 0x6306_6CD9, 0xFA0F_3D63, 0x8D08_0DF5, + 0x3B6E_20C8, 0x4C69_105E, 0xD560_41E4, 0xA267_7172, 0x3C03_E4D1, 0x4B04_D447, 0xD20D_85FD, 0xA50A_B56B, + 0x35B5_A8FA, 0x42B2_986C, 0xDBBB_C9D6, 0xACBC_F940, 0x32D8_6CE3, 0x45DF_5C75, 0xDCD6_0DCF, 0xABD1_3D59, + 0x26D9_30AC, 0x51DE_003A, 0xC8D7_5180, 0xBFD0_6116, 0x21B4_F4B5, 0x56B3_C423, 0xCFBA_9599, 0xB8BD_A50F, + 0x2802_B89E, 0x5F05_8808, 0xC60C_D9B2, 0xB10B_E924, 0x2F6F_7C87, 0x5868_4C11, 0xC161_1DAB, 0xB666_2D3D, + 0x76DC_4190, 0x01DB_7106, 0x98D2_20BC, 0xEFD5_102A, 0x71B1_8589, 0x06B6_B51F, 0x9FBF_E4A5, 0xE8B8_D433, + 0x7807_C9A2, 0x0F00_F934, 0x9609_A88E, 0xE10E_9818, 0x7F6A_0DBB, 0x086D_3D2D, 0x9164_6C97, 0xE663_5C01, + 0x6B6B_51F4, 0x1C6C_6162, 0x8565_30D8, 0xF262_004E, 0x6C06_95ED, 0x1B01_A57B, 0x8208_F4C1, 0xF50F_C457, + 0x65B0_D9C6, 0x12B7_E950, 0x8BBE_B8EA, 0xFCB9_887C, 0x62DD_1DDF, 0x15DA_2D49, 0x8CD3_7CF3, 0xFBD4_4C65, + 0x4DB2_6158, 0x3AB5_51CE, 0xA3BC_0074, 0xD4BB_30E2, 0x4ADF_A541, 0x3DD8_95D7, 0xA4D1_C46D, 0xD3D6_F4FB, + 0x4369_E96A, 0x346E_D9FC, 0xAD67_8846, 0xDA60_B8D0, 0x4404_2D73, 0x3303_1DE5, 0xAA0A_4C5F, 0xDD0D_7CC9, + 0x5005_713C, 0x2702_41AA, 0xBE0B_1010, 0xC90C_2086, 0x5768_B525, 0x206F_85B3, 0xB966_D409, 0xCE61_E49F, + 0x5EDE_F90E, 0x29D9_C998, 0xB0D0_9822, 0xC7D7_A8B4, 0x59B3_3D17, 0x2EB4_0D81, 0xB7BD_5C3B, 0xC0BA_6CAD, + 0xEDB8_8320, 0x9ABF_B3B6, 0x03B6_E20C, 0x74B1_D29A, 0xEAD5_4739, 0x9DD2_77AF, 0x04DB_2615, 0x73DC_1683, + 0xE363_0B12, 0x9464_3B84, 0x0D6D_6A3E, 0x7A6A_5AA8, 0xE40E_CF0B, 0x9309_FF9D, 0x0A00_AE27, 0x7D07_9EB1, + 0xF00F_9344, 0x8708_A3D2, 0x1E01_F268, 0x6906_C2FE, 0xF762_575D, 0x8065_67CB, 0x196C_3671, 0x6E6B_06E7, + 0xFED4_1B76, 0x89D3_2BE0, 0x10DA_7A5A, 0x67DD_4ACC, 0xF9B9_DF6F, 0x8EBE_EFF9, 0x17B7_BE43, 0x60B0_8ED5, + 0xD6D6_A3E8, 0xA1D1_937E, 0x38D8_C2C4, 0x4FDF_F252, 0xD1BB_67F1, 0xA6BC_5767, 0x3FB5_06DD, 0x48B2_364B, + 0xD80D_2BDA, 0xAF0A_1B4C, 0x3603_4AF6, 0x4104_7A60, 0xDF60_EFC3, 0xA867_DF55, 0x316E_8EEF, 0x4669_BE79, + 0xCB61_B38C, 0xBC66_831A, 0x256F_D2A0, 0x5268_E236, 0xCC0C_7795, 0xBB0B_4703, 0x2202_16B9, 0x5505_262F, + 0xC5BA_3BBE, 0xB2BD_0B28, 0x2BB4_5A92, 0x5CB3_6A04, 0xC2D7_FFA7, 0xB5D0_CF31, 0x2CD9_9E8B, 0x5BDE_AE1D, + 0x9B64_C2B0, 0xEC63_F226, 0x756A_A39C, 0x026D_930A, 0x9C09_06A9, 0xEB0E_363F, 0x7207_6785, 0x0500_5713, + 0x95BF_4A82, 0xE2B8_7A14, 0x7BB1_2BAE, 0x0CB6_1B38, 0x92D2_8E9B, 0xE5D5_BE0D, 0x7CDC_EFB7, 0x0BDB_DF21, + 0x86D3_D2D4, 0xF1D4_E242, 0x68DD_B3F8, 0x1FDA_836E, 0x81BE_16CD, 0xF6B9_265B, 0x6FB0_77E1, 0x18B7_4777, + 0x8808_5AE6, 0xFF0F_6A70, 0x6606_3BCA, 0x1101_0B5C, 0x8F65_9EFF, 0xF862_AE69, 0x616B_FFD3, 0x166C_CF45, + 0xA00A_E278, 0xD70D_D2EE, 0x4E04_8354, 0x3903_B3C2, 0xA767_2661, 0xD060_16F7, 0x4969_474D, 0x3E6E_77DB, + 0xAED1_6A4A, 0xD9D6_5ADC, 0x40DF_0B66, 0x37D8_3BF0, 0xA9BC_AE53, 0xDEBB_9EC5, 0x47B2_CF7F, 0x30B5_FFE9, + 0xBDBD_F21C, 0xCABA_C28A, 0x53B3_9330, 0x24B4_A3A6, 0xBAD0_3605, 0xCDD7_0693, 0x54DE_5729, 0x23D9_67BF, + 0xB366_7A2E, 0xC461_4AB8, 0x5D68_1B02, 0x2A6F_2B94, 0xB40B_BE37, 0xC30C_8EA1, 0x5A05_DF1B, 0x2D02_EF8D + ] + + @usableFromInline + static let table32c: Array = [ + 0x0000_0000, 0xF26B_8303, 0xE13B_70F7, 0x1350_F3F4, 0xC79A_971F, 0x35F1_141C, 0x26A1_E7E8, 0xD4CA_64EB, + 0x8AD9_58CF, 0x78B2_DBCC, 0x6BE2_2838, 0x9989_AB3B, 0x4D43_CFD0, 0xBF28_4CD3, 0xAC78_BF27, 0x5E13_3C24, + 0x105E_C76F, 0xE235_446C, 0xF165_B798, 0x030E_349B, 0xD7C4_5070, 0x25AF_D373, 0x36FF_2087, 0xC494_A384, + 0x9A87_9FA0, 0x68EC_1CA3, 0x7BBC_EF57, 0x89D7_6C54, 0x5D1D_08BF, 0xAF76_8BBC, 0xBC26_7848, 0x4E4D_FB4B, + 0x20BD_8EDE, 0xD2D6_0DDD, 0xC186_FE29, 0x33ED_7D2A, 0xE727_19C1, 0x154C_9AC2, 0x061C_6936, 0xF477_EA35, + 0xAA64_D611, 0x580F_5512, 0x4B5F_A6E6, 0xB934_25E5, 0x6DFE_410E, 0x9F95_C20D, 0x8CC5_31F9, 0x7EAE_B2FA, + 0x30E3_49B1, 0xC288_CAB2, 0xD1D8_3946, 0x23B3_BA45, 0xF779_DEAE, 0x0512_5DAD, 0x1642_AE59, 0xE429_2D5A, + 0xBA3A_117E, 0x4851_927D, 0x5B01_6189, 0xA96A_E28A, 0x7DA0_8661, 0x8FCB_0562, 0x9C9B_F696, 0x6EF0_7595, + 0x417B_1DBC, 0xB310_9EBF, 0xA040_6D4B, 0x522B_EE48, 0x86E1_8AA3, 0x748A_09A0, 0x67DA_FA54, 0x95B1_7957, + 0xCBA2_4573, 0x39C9_C670, 0x2A99_3584, 0xD8F2_B687, 0x0C38_D26C, 0xFE53_516F, 0xED03_A29B, 0x1F68_2198, + 0x5125_DAD3, 0xA34E_59D0, 0xB01E_AA24, 0x4275_2927, 0x96BF_4DCC, 0x64D4_CECF, 0x7784_3D3B, 0x85EF_BE38, + 0xDBFC_821C, 0x2997_011F, 0x3AC7_F2EB, 0xC8AC_71E8, 0x1C66_1503, 0xEE0D_9600, 0xFD5D_65F4, 0x0F36_E6F7, + 0x61C6_9362, 0x93AD_1061, 0x80FD_E395, 0x7296_6096, 0xA65C_047D, 0x5437_877E, 0x4767_748A, 0xB50C_F789, + 0xEB1F_CBAD, 0x1974_48AE, 0x0A24_BB5A, 0xF84F_3859, 0x2C85_5CB2, 0xDEEE_DFB1, 0xCDBE_2C45, 0x3FD5_AF46, + 0x7198_540D, 0x83F3_D70E, 0x90A3_24FA, 0x62C8_A7F9, 0xB602_C312, 0x4469_4011, 0x5739_B3E5, 0xA552_30E6, + 0xFB41_0CC2, 0x092A_8FC1, 0x1A7A_7C35, 0xE811_FF36, 0x3CDB_9BDD, 0xCEB0_18DE, 0xDDE0_EB2A, 0x2F8B_6829, + 0x82F6_3B78, 0x709D_B87B, 0x63CD_4B8F, 0x91A6_C88C, 0x456C_AC67, 0xB707_2F64, 0xA457_DC90, 0x563C_5F93, + 0x082F_63B7, 0xFA44_E0B4, 0xE914_1340, 0x1B7F_9043, 0xCFB5_F4A8, 0x3DDE_77AB, 0x2E8E_845F, 0xDCE5_075C, + 0x92A8_FC17, 0x60C3_7F14, 0x7393_8CE0, 0x81F8_0FE3, 0x5532_6B08, 0xA759_E80B, 0xB409_1BFF, 0x4662_98FC, + 0x1871_A4D8, 0xEA1A_27DB, 0xF94A_D42F, 0x0B21_572C, 0xDFEB_33C7, 0x2D80_B0C4, 0x3ED0_4330, 0xCCBB_C033, + 0xA24B_B5A6, 0x5020_36A5, 0x4370_C551, 0xB11B_4652, 0x65D1_22B9, 0x97BA_A1BA, 0x84EA_524E, 0x7681_D14D, + 0x2892_ED69, 0xDAF9_6E6A, 0xC9A9_9D9E, 0x3BC2_1E9D, 0xEF08_7A76, 0x1D63_F975, 0x0E33_0A81, 0xFC58_8982, + 0xB215_72C9, 0x407E_F1CA, 0x532E_023E, 0xA145_813D, 0x758F_E5D6, 0x87E4_66D5, 0x94B4_9521, 0x66DF_1622, + 0x38CC_2A06, 0xCAA7_A905, 0xD9F7_5AF1, 0x2B9C_D9F2, 0xFF56_BD19, 0x0D3D_3E1A, 0x1E6D_CDEE, 0xEC06_4EED, + 0xC38D_26C4, 0x31E6_A5C7, 0x22B6_5633, 0xD0DD_D530, 0x0417_B1DB, 0xF67C_32D8, 0xE52C_C12C, 0x1747_422F, + 0x4954_7E0B, 0xBB3F_FD08, 0xA86F_0EFC, 0x5A04_8DFF, 0x8ECE_E914, 0x7CA5_6A17, 0x6FF5_99E3, 0x9D9E_1AE0, + 0xD3D3_E1AB, 0x21B8_62A8, 0x32E8_915C, 0xC083_125F, 0x1449_76B4, 0xE622_F5B7, 0xF572_0643, 0x0719_8540, + 0x590A_B964, 0xAB61_3A67, 0xB831_C993, 0x4A5A_4A90, 0x9E90_2E7B, 0x6CFB_AD78, 0x7FAB_5E8C, 0x8DC0_DD8F, + 0xE330_A81A, 0x115B_2B19, 0x020B_D8ED, 0xF060_5BEE, 0x24AA_3F05, 0xD6C1_BC06, 0xC591_4FF2, 0x37FA_CCF1, + 0x69E9_F0D5, 0x9B82_73D6, 0x88D2_8022, 0x7AB9_0321, 0xAE73_67CA, 0x5C18_E4C9, 0x4F48_173D, 0xBD23_943E, + 0xF36E_6F75, 0x0105_EC76, 0x1255_1F82, 0xE03E_9C81, 0x34F4_F86A, 0xC69F_7B69, 0xD5CF_889D, 0x27A4_0B9E, + 0x79B7_37BA, 0x8BDC_B4B9, 0x988C_474D, 0x6AE7_C44E, 0xBE2D_A0A5, 0x4C46_23A6, 0x5F16_D052, 0xAD7D_5351 + ] + + @usableFromInline + static let table16: Array = [ + 0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241, + 0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440, + 0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40, + 0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841, + 0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40, + 0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41, + 0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641, + 0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040, + 0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240, + 0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441, + 0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41, + 0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840, + 0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41, + 0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40, + 0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640, + 0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041, + 0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240, + 0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441, + 0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41, + 0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840, + 0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41, + 0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40, + 0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640, + 0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041, + 0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241, + 0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440, + 0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40, + 0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841, + 0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40, + 0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41, + 0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641, + 0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040 + ] + + @usableFromInline + init() { + // + } + + /// Polynomial: 0xEDB88320 (Reversed) - IEEE + @inlinable + func crc32(_ message: Array, seed: UInt32? = nil, reflect: Bool = true) -> UInt32 { + var crc: UInt32 = seed != nil ? seed! : 0xFFFF_FFFF + for chunk in message.batched(by: 256) { + for b in chunk { + let idx = Int((crc ^ UInt32(reflect ? b : reversed(b))) & 0xFF) + crc = (crc >> 8) ^ Checksum.table32[idx] + } + } + return (reflect ? crc : reversed(crc)) ^ 0xFFFF_FFFF + } + + /// Polynomial: 0x82F63B78 (Reversed) - Castagnoli + @inlinable + func crc32c(_ message: Array, seed: UInt32? = nil, reflect: Bool = true) -> UInt32 { + var crc: UInt32 = seed != nil ? seed! : 0xFFFF_FFFF + for chunk in message.batched(by: 256) { + for b in chunk { + let idx = Int((crc ^ UInt32(reflect ? b : reversed(b))) & 0xFF) + crc = (crc >> 8) ^ Checksum.table32c[idx] + } + } + return (reflect ? crc : reversed(crc)) ^ 0xFFFF_FFFF + } + + /// Polynomial: 0xA001 (Reversed) - IBM + @inlinable + func crc16(_ message: Array, seed: UInt16? = nil) -> UInt16 { + var crc: UInt16 = seed != nil ? seed! : 0x0000 + for chunk in message.batched(by: 256) { + for b in chunk { + crc = (crc >> 8) ^ Checksum.table16[Int((crc ^ UInt16(b)) & 0xFF)] + } + } + return crc + } +} + +// MARK: Public interface + +public extension Checksum { + /// Calculate CRC32. + /// + /// - parameter message: Message + /// - parameter seed: Seed value (Optional) + /// - parameter reflect: is reflect (default true) + /// + /// - returns: Calculated code + @inlinable + static func crc32(_ message: Array, seed: UInt32? = nil, reflect: Bool = true) -> UInt32 { + Checksum().crc32(message, seed: seed, reflect: reflect) + } + + /// Calculate CRC32C + /// + /// - parameter message: Message + /// - parameter seed: Seed value (Optional) + /// - parameter reflect: is reflect (default true) + /// + /// - returns: Calculated code + @inlinable + static func crc32c(_ message: Array, seed: UInt32? = nil, reflect: Bool = true) -> UInt32 { + Checksum().crc32c(message, seed: seed, reflect: reflect) + } + + /// Calculate CRC16 + /// + /// - parameter message: Message + /// - parameter seed: Seed value (Optional) + /// + /// - returns: Calculated code + @inlinable + static func crc16(_ message: Array, seed: UInt16? = nil) -> UInt16 { + Checksum().crc16(message, seed: seed) + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Cipher.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Cipher.swift new file mode 100644 index 000000000..d7e669acb --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Cipher.swift @@ -0,0 +1,47 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public enum CipherError: Error { + case encrypt + case decrypt +} + +public protocol Cipher: AnyObject { + var keySize: Int { get } + + /// Encrypt given bytes at once + /// + /// - parameter bytes: Plaintext data + /// - returns: Encrypted data + func encrypt(_ bytes: ArraySlice) throws -> Array + func encrypt(_ bytes: Array) throws -> Array + + /// Decrypt given bytes at once + /// + /// - parameter bytes: Ciphertext data + /// - returns: Plaintext data + func decrypt(_ bytes: ArraySlice) throws -> Array + func decrypt(_ bytes: Array) throws -> Array +} + +extension Cipher { + public func encrypt(_ bytes: Array) throws -> Array { + try self.encrypt(bytes.slice) + } + + public func decrypt(_ bytes: Array) throws -> Array { + try self.decrypt(bytes.slice) + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Collection+Extension.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Collection+Extension.swift new file mode 100644 index 000000000..a1b7d92d7 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Collection+Extension.swift @@ -0,0 +1,61 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// +extension Collection where Self.Element == UInt8, Self.Index == Int { + // Big endian order + @inlinable + func toUInt32Array() -> Array { + guard !isEmpty else { + return [] + } + + let c = strideCount(from: startIndex, to: endIndex, by: 4) + return Array(unsafeUninitializedCapacity: c) { buf, count in + var counter = 0 + for idx in stride(from: startIndex, to: endIndex, by: 4) { + let val = UInt32(bytes: self, fromIndex: idx).bigEndian + buf[counter] = val + counter += 1 + } + count = counter + assert(counter == c) + } + } + + // Big endian order + @inlinable + func toUInt64Array() -> Array { + guard !isEmpty else { + return [] + } + + let c = strideCount(from: startIndex, to: endIndex, by: 8) + return Array(unsafeUninitializedCapacity: c) { buf, count in + var counter = 0 + for idx in stride(from: startIndex, to: endIndex, by: 8) { + let val = UInt64(bytes: self, fromIndex: idx).bigEndian + buf[counter] = val + counter += 1 + } + count = counter + assert(counter == c) + } + } +} + +@usableFromInline +func strideCount(from: Int, to: Int, by: Int) -> Int { + let count = to - from + return count / by + (count % by > 0 ? 1 : 0) +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/CompactMap.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/CompactMap.swift new file mode 100644 index 000000000..34a1a439e --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/CompactMap.swift @@ -0,0 +1,25 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +#if swift(>=4.1) +// TODO: remove this file when Xcode 9.2 is no longer used +#else + extension Sequence { + @inlinable + public func compactMap(_ transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] { + try flatMap(transform) + } + } +#endif diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Cryptor.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Cryptor.swift new file mode 100644 index 000000000..25fd135cf --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Cryptor.swift @@ -0,0 +1,22 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +/// Cryptor (Encryptor or Decryptor) +public protocol Cryptor { + /// Seek to position in file, if block mode allows random access. + /// + /// - parameter to: new value of counter + mutating func seek(to: Int) throws +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Cryptors.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Cryptors.swift new file mode 100644 index 000000000..2c22dde99 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Cryptors.swift @@ -0,0 +1,44 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +#if canImport(Darwin) +import Darwin +#elseif canImport(Glibc) +import Glibc +#elseif canImport(ucrt) +import ucrt +#endif + +/// Worker cryptor/decryptor of `Updatable` types +public protocol Cryptors: AnyObject { + + /// Cryptor suitable for encryption + func makeEncryptor() throws -> Cryptor & Updatable + + /// Cryptor suitable for decryption + func makeDecryptor() throws -> Cryptor & Updatable + + /// Generate array of random bytes. Helper function. + static func randomIV(_ blockSize: Int) -> Array +} + +extension Cryptors { + /// Generate array of random values. + /// Convenience helper that uses `Swift.RandomNumberGenerator`. + /// - Parameter count: Length of array + public static func randomIV(_ count: Int) -> Array { + (0.. +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +@available(*, renamed: "Digest") +public typealias Hash = Digest + +/// Hash functions to calculate Digest. +public struct Digest { + /// Calculate MD5 Digest + /// - parameter bytes: input message + /// - returns: Digest bytes + public static func md5(_ bytes: Array) -> Array { + MD5().calculate(for: bytes) + } + + /// Calculate SHA1 Digest + /// - parameter bytes: input message + /// - returns: Digest bytes + public static func sha1(_ bytes: Array) -> Array { + SHA1().calculate(for: bytes) + } + + /// Calculate SHA2-224 Digest + /// - parameter bytes: input message + /// - returns: Digest bytes + public static func sha224(_ bytes: Array) -> Array { + self.sha2(bytes, variant: .sha224) + } + + /// Calculate SHA2-256 Digest + /// - parameter bytes: input message + /// - returns: Digest bytes + public static func sha256(_ bytes: Array) -> Array { + self.sha2(bytes, variant: .sha256) + } + + /// Calculate SHA2-384 Digest + /// - parameter bytes: input message + /// - returns: Digest bytes + public static func sha384(_ bytes: Array) -> Array { + self.sha2(bytes, variant: .sha384) + } + + /// Calculate SHA2-512 Digest + /// - parameter bytes: input message + /// - returns: Digest bytes + public static func sha512(_ bytes: Array) -> Array { + self.sha2(bytes, variant: .sha512) + } + + /// Calculate SHA2 Digest + /// - parameter bytes: input message + /// - parameter variant: SHA-2 variant + /// - returns: Digest bytes + public static func sha2(_ bytes: Array, variant: SHA2.Variant) -> Array { + SHA2(variant: variant).calculate(for: bytes) + } + + /// Calculate SHA3 Digest + /// - parameter bytes: input message + /// - parameter variant: SHA-3 variant + /// - returns: Digest bytes + public static func sha3(_ bytes: Array, variant: SHA3.Variant) -> Array { + SHA3(variant: variant).calculate(for: bytes) + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/DigestType.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/DigestType.swift new file mode 100644 index 000000000..c99f081ff --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/DigestType.swift @@ -0,0 +1,18 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +internal protocol DigestType { + func calculate(for bytes: Array) -> Array +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/AES+Foundation.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/AES+Foundation.swift new file mode 100644 index 000000000..3c6055c7b --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/AES+Foundation.swift @@ -0,0 +1,32 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +import Foundation + +extension AES { + /// Initialize with CBC block mode. + /// + /// - Parameters: + /// - key: Key as a String. + /// - iv: IV as a String. + /// - padding: Padding + /// - Throws: Error + /// + /// The input is a String, that is treat as sequence of bytes made directly out of String. + /// If input is Base64 encoded data (which is a String technically) it is not decoded automatically for you. + public convenience init(key: String, iv: String, padding: Padding = .pkcs7) throws { + try self.init(key: key.bytes, blockMode: CBC(iv: iv.bytes), padding: padding) + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Array+Foundation.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Array+Foundation.swift new file mode 100644 index 000000000..64f7f116e --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Array+Foundation.swift @@ -0,0 +1,32 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +import Foundation + +public extension Array where Element == UInt8 { + func toBase64() -> String { + Data(self).base64EncodedString() + } + + init(base64: String) { + self.init() + + guard let decodedData = Data(base64Encoded: base64) else { + return + } + + append(contentsOf: decodedData.bytes) + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Blowfish+Foundation.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Blowfish+Foundation.swift new file mode 100644 index 000000000..57c1eea7b --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Blowfish+Foundation.swift @@ -0,0 +1,23 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +import Foundation + +extension Blowfish { + /// Initialize with CBC block mode. + public convenience init(key: String, iv: String, padding: Padding = .pkcs7) throws { + try self.init(key: key.bytes, blockMode: CBC(iv: iv.bytes), padding: padding) + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/ChaCha20+Foundation.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/ChaCha20+Foundation.swift new file mode 100644 index 000000000..347f45887 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/ChaCha20+Foundation.swift @@ -0,0 +1,22 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +import Foundation + +extension ChaCha20 { + public convenience init(key: String, iv: String) throws { + try self.init(key: key.bytes, iv: iv.bytes) + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Data+Extension.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Data+Extension.swift new file mode 100644 index 000000000..3a9e2c951 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Data+Extension.swift @@ -0,0 +1,92 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +import Foundation + +extension Data { + /// Two octet checksum as defined in RFC-4880. Sum of all octets, mod 65536 + public func checksum() -> UInt16 { + let s = self.withUnsafeBytes { buf in + return buf.lazy.map(UInt32.init).reduce(UInt32(0), +) + } + return UInt16(s % 65535) + } + + public func md5() -> Data { + Data( Digest.md5(bytes)) + } + + public func sha1() -> Data { + Data( Digest.sha1(bytes)) + } + + public func sha224() -> Data { + Data( Digest.sha224(bytes)) + } + + public func sha256() -> Data { + Data( Digest.sha256(bytes)) + } + + public func sha384() -> Data { + Data( Digest.sha384(bytes)) + } + + public func sha512() -> Data { + Data( Digest.sha512(bytes)) + } + + public func sha3(_ variant: SHA3.Variant) -> Data { + Data( Digest.sha3(bytes, variant: variant)) + } + + public func crc32(seed: UInt32? = nil, reflect: Bool = true) -> Data { + Data( Checksum.crc32(bytes, seed: seed, reflect: reflect).bytes()) + } + + public func crc32c(seed: UInt32? = nil, reflect: Bool = true) -> Data { + Data( Checksum.crc32c(bytes, seed: seed, reflect: reflect).bytes()) + } + + public func crc16(seed: UInt16? = nil) -> Data { + Data( Checksum.crc16(bytes, seed: seed).bytes()) + } + + public func encrypt(cipher: Cipher) throws -> Data { + Data( try cipher.encrypt(bytes.slice)) + } + + public func decrypt(cipher: Cipher) throws -> Data { + Data( try cipher.decrypt(bytes.slice)) + } + + public func authenticate(with authenticator: Authenticator) throws -> Data { + Data( try authenticator.authenticate(bytes)) + } +} + +extension Data { + public init(hex: String) { + self.init(Array(hex: hex)) + } + + public var bytes: Array { + Array(self) + } + + public func toHexString() -> String { + self.bytes.toHexString() + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/HMAC+Foundation.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/HMAC+Foundation.swift new file mode 100644 index 000000000..99b7b6270 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/HMAC+Foundation.swift @@ -0,0 +1,22 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +import Foundation + +extension HMAC { + public convenience init(key: String, variant: HMAC.Variant = .md5) throws { + self.init(key: key.bytes, variant: variant) + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Rabbit+Foundation.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Rabbit+Foundation.swift new file mode 100644 index 000000000..d3543b2f6 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Rabbit+Foundation.swift @@ -0,0 +1,26 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +import Foundation + +extension Rabbit { + public convenience init(key: String) throws { + try self.init(key: key.bytes) + } + + public convenience init(key: String, iv: String) throws { + try self.init(key: key.bytes, iv: iv.bytes) + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/String+FoundationExtension.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/String+FoundationExtension.swift new file mode 100644 index 000000000..89a846498 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/String+FoundationExtension.swift @@ -0,0 +1,41 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +import Foundation + +extension String { + /// Return Base64 back to String + public func decryptBase64ToString(cipher: Cipher) throws -> String { + guard let decodedData = Data(base64Encoded: self, options: []) else { + throw CipherError.decrypt + } + + let decrypted = try decodedData.decrypt(cipher: cipher) + + if let decryptedString = String(data: decrypted, encoding: String.Encoding.utf8) { + return decryptedString + } + + throw CipherError.decrypt + } + + public func decryptBase64(cipher: Cipher) throws -> Array { + guard let decodedData = Data(base64Encoded: self, options: []) else { + throw CipherError.decrypt + } + + return try decodedData.decrypt(cipher: cipher).bytes + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Utils+Foundation.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Utils+Foundation.swift new file mode 100644 index 000000000..f146cf765 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Utils+Foundation.swift @@ -0,0 +1,27 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +import Foundation + +func perf(_ text: String, closure: () -> Void) { + let measurementStart = Date() + + closure() + + let measurementStop = Date() + let executionTime = measurementStop.timeIntervalSince(measurementStart) + + print("\(text) \(executionTime)") +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Generics.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Generics.swift new file mode 100644 index 000000000..dfd90bbe3 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Generics.swift @@ -0,0 +1,43 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +/// Array of bytes. Caution: don't use directly because generic is slow. +/// +/// - parameter value: integer value +/// - parameter length: length of output array. By default size of value type +/// +/// - returns: Array of bytes +@_specialize(where T == Int) +@_specialize(where T == UInt) +@_specialize(where T == UInt8) +@_specialize(where T == UInt16) +@_specialize(where T == UInt32) +@_specialize(where T == UInt64) +@inlinable +func arrayOfBytes(value: T, length totalBytes: Int = MemoryLayout.size) -> Array { + let valuePointer = UnsafeMutablePointer.allocate(capacity: 1) + valuePointer.pointee = value + + let bytesPointer = UnsafeMutablePointer(OpaquePointer(valuePointer)) + var bytes = Array(repeating: 0, count: totalBytes) + for j in 0...size, totalBytes) { + bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee + } + + valuePointer.deinitialize(count: 1) + valuePointer.deallocate() + + return bytes +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/HKDF.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/HKDF.swift new file mode 100644 index 000000000..5f48c0a6c --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/HKDF.swift @@ -0,0 +1,86 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// https://www.ietf.org/rfc/rfc5869.txt +// + +#if canImport(Darwin) +import Darwin +#elseif canImport(Glibc) +import Glibc +#elseif canImport(ucrt) +import ucrt +#endif + +/// A key derivation function. +/// +/// HKDF - HMAC-based Extract-and-Expand Key Derivation Function. +public struct HKDF { + public enum Error: Swift.Error { + case invalidInput + case derivedKeyTooLong + } + + private let numBlocks: Int // l + private let dkLen: Int + private let info: Array + private let prk: Array + private let variant: HMAC.Variant + + /// - parameters: + /// - variant: hash variant + /// - salt: optional salt (if not provided, it is set to a sequence of variant.digestLength zeros) + /// - info: optional context and application specific information + /// - keyLength: intended length of derived key + public init(password: Array, salt: Array? = nil, info: Array? = nil, keyLength: Int? = nil /* dkLen */, variant: HMAC.Variant = .sha2(.sha256)) throws { + guard !password.isEmpty else { + throw Error.invalidInput + } + + let dkLen = keyLength ?? variant.digestLength + let keyLengthFinal = Double(dkLen) + let hLen = Double(variant.digestLength) + let numBlocks = Int(ceil(keyLengthFinal / hLen)) // l = ceil(keyLength / hLen) + guard numBlocks <= 255 else { + throw Error.derivedKeyTooLong + } + + /// HKDF-Extract(salt, password) -> PRK + /// - PRK - a pseudo-random key; it is used by calculate() + self.prk = try HMAC(key: salt ?? [], variant: variant).authenticate(password) + self.info = info ?? [] + self.variant = variant + self.dkLen = dkLen + self.numBlocks = numBlocks + } + + public func calculate() throws -> Array { + let hmac = HMAC(key: prk, variant: variant) + var ret = Array() + ret.reserveCapacity(self.numBlocks * self.variant.digestLength) + var value = Array() + for i in 1...self.numBlocks { + value.append(contentsOf: self.info) + value.append(UInt8(i)) + + let bytes = try hmac.authenticate(value) + ret.append(contentsOf: bytes) + + /// update value to use it as input for next iteration + value = bytes + } + return Array(ret.prefix(self.dkLen)) + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/HMAC.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/HMAC.swift new file mode 100644 index 000000000..d86413133 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/HMAC.swift @@ -0,0 +1,124 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public final class HMAC: Authenticator { + public enum Error: Swift.Error { + case authenticateError + case invalidInput + } + + public enum Variant { + case md5 + case sha1 + case sha2(SHA2.Variant) + case sha3(SHA3.Variant) + + @available(*, deprecated, message: "Use sha2(variant) instead.") + case sha256, sha384, sha512 + + var digestLength: Int { + switch self { + case .sha1: + return SHA1.digestLength + case .sha256: + return SHA2.Variant.sha256.digestLength + case .sha384: + return SHA2.Variant.sha384.digestLength + case .sha512: + return SHA2.Variant.sha512.digestLength + case .sha2(let variant): + return variant.digestLength + case .sha3(let variant): + return variant.digestLength + case .md5: + return MD5.digestLength + } + } + + func calculateHash(_ bytes: Array) -> Array { + switch self { + case .sha1: + return Digest.sha1(bytes) + case .sha256: + return Digest.sha256(bytes) + case .sha384: + return Digest.sha384(bytes) + case .sha512: + return Digest.sha512(bytes) + case .sha2(let variant): + return Digest.sha2(bytes, variant: variant) + case .sha3(let variant): + return Digest.sha3(bytes, variant: variant) + case .md5: + return Digest.md5(bytes) + } + } + + func blockSize() -> Int { + switch self { + case .md5: + return MD5.blockSize + case .sha1: + return SHA1.blockSize + case .sha256: + return SHA2.Variant.sha256.blockSize + case .sha384: + return SHA2.Variant.sha384.blockSize + case .sha512: + return SHA2.Variant.sha512.blockSize + case .sha2(let variant): + return variant.blockSize + case .sha3(let variant): + return variant.blockSize + } + } + } + + var key: Array + let variant: Variant + + public init(key: Array, variant: HMAC.Variant = .md5) { + self.variant = variant + self.key = key + + if key.count > variant.blockSize() { + let hash = variant.calculateHash(key) + self.key = hash + } + + if key.count < variant.blockSize() { + self.key = ZeroPadding().add(to: key, blockSize: variant.blockSize()) + } + } + + // MARK: Authenticator + + public func authenticate(_ bytes: Array) throws -> Array { + var opad = Array(repeating: 0x5c, count: variant.blockSize()) + for idx in self.key.indices { + opad[idx] = self.key[idx] ^ opad[idx] + } + var ipad = Array(repeating: 0x36, count: variant.blockSize()) + for idx in self.key.indices { + ipad[idx] = self.key[idx] ^ ipad[idx] + } + + let ipadAndMessageHash = self.variant.calculateHash(ipad + bytes) + let result = self.variant.calculateHash(opad + ipadAndMessageHash) + + // return Array(result[0..<10]) // 80 bits + return result + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/ISO10126Padding.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/ISO10126Padding.swift new file mode 100644 index 000000000..8aebd1140 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/ISO10126Padding.swift @@ -0,0 +1,56 @@ +// +// CryptoSwift +// +// Copyright (C) Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +import Foundation + +/// Padding with random bytes, ending with the number of added bytes. +/// Read the [Wikipedia](https://en.wikipedia.org/wiki/Padding_(cryptography)#ISO_10126) +/// and [Crypto-IT](http://www.crypto-it.net/eng/theory/padding.html) articles for more info. +struct ISO10126Padding: PaddingProtocol { + init() { + } + + @inlinable + func add(to bytes: Array, blockSize: Int) -> Array { + let padding = UInt8(blockSize - (bytes.count % blockSize)) + var withPadding = bytes + if padding > 0 { + withPadding += (0..<(padding - 1)).map { _ in UInt8.random(in: 0...255) } + [padding] + } + return withPadding + } + + @inlinable + func remove(from bytes: Array, blockSize: Int?) -> Array { + guard !bytes.isEmpty, let lastByte = bytes.last else { + return bytes + } + + assert(!bytes.isEmpty, "Need bytes to remove padding") + + let padding = Int(lastByte) // last byte + let finalLength = bytes.count - padding + + if finalLength < 0 { + return bytes + } + + if padding >= 1 { + return Array(bytes[0.. +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +import Foundation + +// First byte is 0x80, rest is zero padding +// http://www.crypto-it.net/eng/theory/padding.html +// http://www.embedx.com/pdfs/ISO_STD_7816/info_isoiec7816-4%7Bed21.0%7Den.pdf +struct ISO78164Padding: PaddingProtocol { + init() { + } + + @inlinable + func add(to bytes: Array, blockSize: Int) -> Array { + var padded = Array(bytes) + padded.append(0x80) + + while (padded.count % blockSize) != 0 { + padded.append(0x00) + } + return padded + } + + @inlinable + func remove(from bytes: Array, blockSize _: Int?) -> Array { + if let idx = bytes.lastIndex(of: 0x80) { + return Array(bytes[.. +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +#if canImport(Darwin) +import Darwin +#elseif canImport(Glibc) +import Glibc +#elseif canImport(ucrt) +import ucrt +#endif + +extension FixedWidthInteger { + @inlinable + func bytes(totalBytes: Int = MemoryLayout.size) -> Array { + arrayOfBytes(value: self.littleEndian, length: totalBytes) + // TODO: adjust bytes order + // var value = self.littleEndian + // return withUnsafeBytes(of: &value, Array.init).reversed() + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/MD5.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/MD5.swift new file mode 100644 index 000000000..bd7925f1a --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/MD5.swift @@ -0,0 +1,161 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public final class MD5: DigestType { + static let blockSize: Int = 64 + static let digestLength: Int = 16 // 128 / 8 + fileprivate static let hashInitialValue: Array = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] + + fileprivate var accumulated = Array() + fileprivate var processedBytesTotalCount: Int = 0 + fileprivate var accumulatedHash: Array = MD5.hashInitialValue + + /** specifies the per-round shift amounts */ + private let s: Array = [ + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, + 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, + 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, + 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21 + ] + + /** binary integer part of the sines of integers (Radians) */ + private let k: Array = [ + 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, + 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, + 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, + 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, + 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, + 0xd62f105d, 0x2441453, 0xd8a1e681, 0xe7d3fbc8, + 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, + 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, + 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, + 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, + 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05, + 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, + 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, + 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, + 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, + 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 + ] + + public init() { + } + + public func calculate(for bytes: Array) -> Array { + do { + return try update(withBytes: bytes.slice, isLast: true) + } catch { + fatalError() + } + } + + // mutating currentHash in place is way faster than returning new result + fileprivate func process(block chunk: ArraySlice, currentHash: inout Array) { + assert(chunk.count == 16 * 4) + + // Initialize hash value for this chunk: + var A: UInt32 = currentHash[0] + var B: UInt32 = currentHash[1] + var C: UInt32 = currentHash[2] + var D: UInt32 = currentHash[3] + + var dTemp: UInt32 = 0 + + // Main loop + for j in 0.., isLast: Bool = false) throws -> Array { + self.accumulated += bytes + + if isLast { + let lengthInBits = (processedBytesTotalCount + self.accumulated.count) * 8 + let lengthBytes = lengthInBits.bytes(totalBytes: 64 / 8) // A 64-bit representation of b + + // Step 1. Append padding + bitPadding(to: &self.accumulated, blockSize: MD5.blockSize, allowance: 64 / 8) + + // Step 2. Append Length a 64-bit representation of lengthInBits + self.accumulated += lengthBytes.reversed() + } + + var processedBytes = 0 + for chunk in self.accumulated.batched(by: MD5.blockSize) { + if isLast || (self.accumulated.count - processedBytes) >= MD5.blockSize { + self.process(block: chunk, currentHash: &self.accumulatedHash) + processedBytes += chunk.count + } + } + self.accumulated.removeFirst(processedBytes) + self.processedBytesTotalCount += processedBytes + + // output current hash + var result = Array() + result.reserveCapacity(MD5.digestLength) + + for hElement in self.accumulatedHash { + let hLE = hElement.littleEndian + result += Array(arrayLiteral: UInt8(hLE & 0xff), UInt8((hLE >> 8) & 0xff), UInt8((hLE >> 16) & 0xff), UInt8((hLE >> 24) & 0xff)) + } + + // reset hash value for instance + if isLast { + self.accumulatedHash = MD5.hashInitialValue + } + + return result + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/NoPadding.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/NoPadding.swift new file mode 100644 index 000000000..9c75f6f3a --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/NoPadding.swift @@ -0,0 +1,27 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +struct NoPadding: PaddingProtocol { + init() { + } + + func add(to data: Array, blockSize _: Int) -> Array { + data + } + + func remove(from data: Array, blockSize _: Int?) -> Array { + data + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Operators.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Operators.swift new file mode 100644 index 000000000..cee442d95 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Operators.swift @@ -0,0 +1,32 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +/* + Bit shifting with overflow protection using overflow operator "&". + Approach is consistent with standard overflow operators &+, &-, &*, &/ + and introduce new overflow operators for shifting: &<<, &>> + + Note: Works with unsigned integers values only + + Usage + + var i = 1 // init + var j = i &<< 2 //shift left + j &<<= 2 //shift left and assign + + @see: https://medium.com/@krzyzanowskim/swiftly-shift-bits-and-protect-yourself-be33016ce071 + + This fuctonality is now implemented as part of Swift 3, SE-0104 https://github.com/apple/swift-evolution/blob/master/proposals/0104-improved-integers.md + */ diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PBKDF1.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PBKDF1.swift new file mode 100644 index 000000000..b7e8e70bf --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PBKDF1.swift @@ -0,0 +1,97 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public extension PKCS5 { + /// A key derivation function. + /// + /// PBKDF1 is recommended only for compatibility with existing + /// applications since the keys it produces may not be large enough for + /// some applications. + struct PBKDF1 { + public enum Error: Swift.Error { + case invalidInput + case derivedKeyTooLong + } + + public enum Variant { + case md5, sha1 + + @usableFromInline + var size: Int { + switch self { + case .md5: + return MD5.digestLength + case .sha1: + return SHA1.digestLength + } + } + + @usableFromInline + func calculateHash(_ bytes: Array) -> Array { + switch self { + case .sha1: + return Digest.sha1(bytes) + case .md5: + return Digest.md5(bytes) + } + } + } + + @usableFromInline + let iterations: Int // c + + @usableFromInline + let variant: Variant + + @usableFromInline + let keyLength: Int + + @usableFromInline + let t1: Array + + /// - parameters: + /// - salt: salt, an eight-bytes + /// - variant: hash variant + /// - iterations: iteration count, a positive integer + /// - keyLength: intended length of derived key + public init(password: Array, salt: Array, variant: Variant = .sha1, iterations: Int = 4096 /* c */, keyLength: Int? = nil /* dkLen */ ) throws { + precondition(iterations > 0) + precondition(salt.count == 8) + + let keyLength = keyLength ?? variant.size + + if keyLength > variant.size { + throw Error.derivedKeyTooLong + } + + let t1 = variant.calculateHash(password + salt) + + self.iterations = iterations + self.variant = variant + self.keyLength = keyLength + self.t1 = t1 + } + + /// Apply the underlying hash function Hash for c iterations + @inlinable + public func calculate() -> Array { + var t = self.t1 + for _ in 2...self.iterations { + t = self.variant.calculateHash(t) + } + return Array(t[0.. +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// https://www.ietf.org/rfc/rfc2898.txt +// + +#if canImport(Darwin) +import Darwin +#elseif canImport(Glibc) +import Glibc +#elseif canImport(ucrt) +import ucrt +#endif + +public extension PKCS5 { + /// A key derivation function. + /// + /// PBKDF2 - Password-Based Key Derivation Function 2. Key stretching technique. + /// DK = PBKDF2(PRF, Password, Salt, c, dkLen) + struct PBKDF2 { + public enum Error: Swift.Error { + case invalidInput + case derivedKeyTooLong + } + + private let salt: Array // S + fileprivate let iterations: Int // c + private let numBlocks: Int // l + private let dkLen: Int + fileprivate let prf: HMAC + + /// - parameters: + /// - salt: salt + /// - variant: hash variant + /// - iterations: iteration count, a positive integer + /// - keyLength: intended length of derived key + /// - variant: MAC variant. Defaults to SHA256 + public init(password: Array, salt: Array, iterations: Int = 4096 /* c */, keyLength: Int? = nil /* dkLen */, variant: HMAC.Variant = .sha2(.sha256)) throws { + precondition(iterations > 0) + + let prf = HMAC(key: password, variant: variant) + + guard iterations > 0 && !salt.isEmpty else { + throw Error.invalidInput + } + + self.dkLen = keyLength ?? variant.digestLength + let keyLengthFinal = Double(dkLen) + let hLen = Double(prf.variant.digestLength) + if keyLengthFinal > (pow(2, 32) - 1) * hLen { + throw Error.derivedKeyTooLong + } + + self.salt = salt + self.iterations = iterations + self.prf = prf + + self.numBlocks = Int(ceil(Double(keyLengthFinal) / hLen)) // l = ceil(keyLength / hLen) + } + + public func calculate() throws -> Array { + var ret = Array() + ret.reserveCapacity(self.numBlocks * self.prf.variant.digestLength) + for i in 1...self.numBlocks { + // for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter + if let value = try calculateBlock(self.salt, blockNum: i) { + ret.append(contentsOf: value) + } + } + return Array(ret.prefix(self.dkLen)) + } + } +} + +private extension PKCS5.PBKDF2 { + func ARR(_ i: Int) -> Array { + var inti = Array(repeating: 0, count: 4) + inti[0] = UInt8((i >> 24) & 0xff) + inti[1] = UInt8((i >> 16) & 0xff) + inti[2] = UInt8((i >> 8) & 0xff) + inti[3] = UInt8(i & 0xff) + return inti + } + + // F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c + // U_1 = PRF (P, S || INT (i)) + func calculateBlock(_ salt: Array, blockNum: Int) throws -> Array? { + guard let u1 = try? prf.authenticate(salt + ARR(blockNum)) else { // blockNum.bytes() is slower + return nil + } + + var u = u1 + var ret = u + if iterations > 1 { + // U_2 = PRF (P, U_1) , + // U_c = PRF (P, U_{c-1}) . + for _ in 2...iterations { + u = try prf.authenticate(u) + for x in 0.. +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// PKCS is a group of public-key cryptography standards devised +// and published by RSA Security Inc, starting in the early 1990s. +// + +public enum PKCS5 { + typealias Padding = PKCS7Padding +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS7.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS7.swift new file mode 100644 index 000000000..2831c3713 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS7.swift @@ -0,0 +1,18 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public enum PKCS7 { + typealias Padding = PKCS7Padding +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS7Padding.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS7Padding.swift new file mode 100644 index 000000000..cb97917a3 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS7Padding.swift @@ -0,0 +1,62 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// PKCS is a group of public-key cryptography standards devised +// and published by RSA Security Inc, starting in the early 1990s. +// + +struct PKCS7Padding: PaddingProtocol { + enum Error: Swift.Error { + case invalidPaddingValue + } + + init() { + } + + @inlinable + func add(to bytes: Array, blockSize: Int) -> Array { + let padding = UInt8(blockSize - (bytes.count % blockSize)) + var withPadding = bytes + if padding == 0 { + // If the original data is a multiple of N bytes, then an extra block of bytes with value N is added. + withPadding += Array(repeating: UInt8(blockSize), count: Int(blockSize)) + } else { + // The value of each added byte is the number of bytes that are added + withPadding += Array(repeating: padding, count: Int(padding)) + } + return withPadding + } + + @inlinable + func remove(from bytes: Array, blockSize _: Int?) -> Array { + guard !bytes.isEmpty, let lastByte = bytes.last else { + return bytes + } + + assert(!bytes.isEmpty, "Need bytes to remove padding") + + let padding = Int(lastByte) // last byte + let finalLength = bytes.count - padding + + if finalLength < 0 { + return bytes + } + + if padding >= 1 { + return Array(bytes[0.. +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public protocol PaddingProtocol { + func add(to: Array, blockSize: Int) -> Array + func remove(from: Array, blockSize: Int?) -> Array +} + +public enum Padding: PaddingProtocol { + case noPadding, zeroPadding, pkcs7, pkcs5, iso78164, iso10126 + + public func add(to: Array, blockSize: Int) -> Array { + switch self { + case .noPadding: + return to // NoPadding().add(to: to, blockSize: blockSize) + case .zeroPadding: + return ZeroPadding().add(to: to, blockSize: blockSize) + case .pkcs7: + return PKCS7.Padding().add(to: to, blockSize: blockSize) + case .pkcs5: + return PKCS5.Padding().add(to: to, blockSize: blockSize) + case .iso78164: + return ISO78164Padding().add(to: to, blockSize: blockSize) + case .iso10126: + return ISO10126Padding().add(to: to, blockSize: blockSize) + } + } + + public func remove(from: Array, blockSize: Int?) -> Array { + switch self { + case .noPadding: + return from //NoPadding().remove(from: from, blockSize: blockSize) + case .zeroPadding: + return ZeroPadding().remove(from: from, blockSize: blockSize) + case .pkcs7: + return PKCS7.Padding().remove(from: from, blockSize: blockSize) + case .pkcs5: + return PKCS5.Padding().remove(from: from, blockSize: blockSize) + case .iso78164: + return ISO78164Padding().remove(from: from, blockSize: blockSize) + case .iso10126: + return ISO10126Padding().remove(from: from, blockSize: blockSize) + } + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Poly1305.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Poly1305.swift new file mode 100644 index 000000000..3e8f7a3d6 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Poly1305.swift @@ -0,0 +1,165 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// http://tools.ietf.org/html/draft-agl-tls-chacha20poly1305-04#section-4 +// nacl/crypto_onetimeauth/poly1305/ref/auth.c +// +/// Poly1305 takes a 32-byte, one-time key and a message and produces a 16-byte tag that authenticates the +/// message such that an attacker has a negligible chance of producing a valid tag for an inauthentic message. + +public final class Poly1305: Authenticator { + public enum Error: Swift.Error { + case authenticateError + } + + public static let blockSize: Int = 16 + + private let key: SecureBytes + + /// - parameter key: 32-byte key + public init(key: Array) { + self.key = SecureBytes(bytes: key) + } + + private func squeeze(h: inout Array) { + assert(h.count == 17) + var u: UInt32 = 0 + for j in 0..<16 { + u = u &+ h[j] + h[j] = u & 255 + u = u >> 8 + } + + u = u &+ h[16] + h[16] = u & 3 + u = 5 * (u >> 2) + + for j in 0..<16 { + u = u &+ h[j] + h[j] = u & 255 + u = u >> 8 + } + + u = u &+ h[16] + h[16] = u + } + + private func add(h: inout Array, c: Array) { + assert(h.count == 17 && c.count == 17) + + var u: UInt32 = 0 + for j in 0..<17 { + u = u &+ (h[j] &+ c[j]) + h[j] = u & 255 + u = u >> 8 + } + } + + private func mulmod(h: inout Array, r: Array) { + var hr = Array(repeating: 0, count: 17) + var u: UInt32 = 0 + for i in 0..<17 { + u = 0 + for j in 0...i { + u = u &+ (h[j] * r[i &- j]) + } + for j in (i + 1)..<17 { + u = u &+ (320 * h[j] * r[i &+ 17 &- j]) + } + hr[i] = u + } + h = hr + self.squeeze(h: &h) + } + + private func freeze(h: inout Array) { + let horig = h + self.add(h: &h, c: [5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 252]) + let negative = UInt32(bitPattern: -Int32(h[16] >> 7)) + for j in 0..<17 { + h[j] ^= negative & (horig[j] ^ h[j]) + } + } + + /// the key is partitioned into two parts, called "r" and "s" + fileprivate func onetimeauth(message input: Array, key k: Array) -> Array { + // clamp + var r = Array(repeating: 0, count: 17) + var h = Array(repeating: 0, count: 17) + var c = Array(repeating: 0, count: 17) + + r[0] = UInt32(k[0]) + r[1] = UInt32(k[1]) + r[2] = UInt32(k[2]) + r[3] = UInt32(k[3] & 15) + r[4] = UInt32(k[4] & 252) + r[5] = UInt32(k[5]) + r[6] = UInt32(k[6]) + r[7] = UInt32(k[7] & 15) + r[8] = UInt32(k[8] & 252) + r[9] = UInt32(k[9]) + r[10] = UInt32(k[10]) + r[11] = UInt32(k[11] & 15) + r[12] = UInt32(k[12] & 252) + r[13] = UInt32(k[13]) + r[14] = UInt32(k[14]) + r[15] = UInt32(k[15] & 15) + r[16] = 0 + + var inlen = input.count + var inpos = 0 + while inlen > 0 { + for j in 0..) throws -> Array { + self.onetimeauth(message: bytes, key: Array(self.key)) + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Rabbit.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Rabbit.swift new file mode 100644 index 000000000..ad0303cb4 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Rabbit.swift @@ -0,0 +1,221 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public final class Rabbit: BlockCipher { + public enum Error: Swift.Error { + case invalidKeyOrInitializationVector + } + + /// Size of IV in bytes + public static let ivSize = 64 / 8 + + /// Size of key in bytes + public static let keySize = 128 / 8 + + /// Size of block in bytes + public static let blockSize = 128 / 8 + + public var keySize: Int { + self.key.count + } + + /// Key + private let key: Key + + /// IV (optional) + private let iv: Array? + + /// State variables + private var x = Array(repeating: 0, count: 8) + + /// Counter variables + private var c = Array(repeating: 0, count: 8) + + /// Counter carry + private var p7: UInt32 = 0 + + /// 'a' constants + private var a: Array = [ + 0x4d34d34d, + 0xd34d34d3, + 0x34d34d34, + 0x4d34d34d, + 0xd34d34d3, + 0x34d34d34, + 0x4d34d34d, + 0xd34d34d3 + ] + + // MARK: - Initializers + + public convenience init(key: Array) throws { + try self.init(key: key, iv: nil) + } + + public init(key: Array, iv: Array?) throws { + self.key = Key(bytes: key) + self.iv = iv + + guard key.count == Rabbit.keySize && (iv == nil || iv!.count == Rabbit.ivSize) else { + throw Error.invalidKeyOrInitializationVector + } + } + + // MARK: - + + fileprivate func setup() { + self.p7 = 0 + + // Key divided into 8 subkeys + let k = Array(unsafeUninitializedCapacity: 8) { buf, count in + for j in 0..<8 { + buf[j] = UInt32(self.key[Rabbit.blockSize - (2 * j + 1)]) | (UInt32(self.key[Rabbit.blockSize - (2 * j + 2)]) << 8) + } + count = 8 + } + + // Initialize state and counter variables from subkeys + for j in 0..<8 { + if j % 2 == 0 { + self.x[j] = (k[(j + 1) % 8] << 16) | k[j] + self.c[j] = (k[(j + 4) % 8] << 16) | k[(j + 5) % 8] + } else { + self.x[j] = (k[(j + 5) % 8] << 16) | k[(j + 4) % 8] + self.c[j] = (k[j] << 16) | k[(j + 1) % 8] + } + } + + // Iterate system four times + self.nextState() + self.nextState() + self.nextState() + self.nextState() + + // Reinitialize counter variables + for j in 0..<8 { + self.c[j] = self.c[j] ^ self.x[(j + 4) % 8] + } + + if let iv = iv { + self.setupIV(iv) + } + } + + private func setupIV(_ iv: Array) { + // 63...56 55...48 47...40 39...32 31...24 23...16 15...8 7...0 IV bits + // 0 1 2 3 4 5 6 7 IV bytes in array + let iv0 = UInt32(bytes: [iv[4], iv[5], iv[6], iv[7]]) + let iv1 = UInt32(bytes: [iv[0], iv[1], iv[4], iv[5]]) + let iv2 = UInt32(bytes: [iv[0], iv[1], iv[2], iv[3]]) + let iv3 = UInt32(bytes: [iv[2], iv[3], iv[6], iv[7]]) + + // Modify the counter state as function of the IV + c[0] = self.c[0] ^ iv0 + self.c[1] = self.c[1] ^ iv1 + self.c[2] = self.c[2] ^ iv2 + self.c[3] = self.c[3] ^ iv3 + self.c[4] = self.c[4] ^ iv0 + self.c[5] = self.c[5] ^ iv1 + self.c[6] = self.c[6] ^ iv2 + self.c[7] = self.c[7] ^ iv3 + + // Iterate system four times + self.nextState() + self.nextState() + self.nextState() + self.nextState() + } + + private func nextState() { + // Before an iteration the counters are incremented + var carry = self.p7 + for j in 0..<8 { + let prev = self.c[j] + self.c[j] = prev &+ self.a[j] &+ carry + carry = prev > self.c[j] ? 1 : 0 // detect overflow + } + self.p7 = carry // save last carry bit + + // Iteration of the system + self.x = Array(unsafeUninitializedCapacity: 8) { newX, count in + newX[0] = self.g(0) &+ rotateLeft(self.g(7), by: 16) &+ rotateLeft(self.g(6), by: 16) + newX[1] = self.g(1) &+ rotateLeft(self.g(0), by: 8) &+ self.g(7) + newX[2] = self.g(2) &+ rotateLeft(self.g(1), by: 16) &+ rotateLeft(self.g(0), by: 16) + newX[3] = self.g(3) &+ rotateLeft(self.g(2), by: 8) &+ self.g(1) + newX[4] = self.g(4) &+ rotateLeft(self.g(3), by: 16) &+ rotateLeft(self.g(2), by: 16) + newX[5] = self.g(5) &+ rotateLeft(self.g(4), by: 8) &+ self.g(3) + newX[6] = self.g(6) &+ rotateLeft(self.g(5), by: 16) &+ rotateLeft(self.g(4), by: 16) + newX[7] = self.g(7) &+ rotateLeft(self.g(6), by: 8) &+ self.g(5) + count = 8 + } + } + + private func g(_ j: Int) -> UInt32 { + let sum = self.x[j] &+ self.c[j] + let square = UInt64(sum) * UInt64(sum) + return UInt32(truncatingIfNeeded: square ^ (square >> 32)) + } + + fileprivate func nextOutput() -> Array { + self.nextState() + + var output16 = Array(repeating: 0, count: Rabbit.blockSize / 2) + output16[7] = UInt16(truncatingIfNeeded: self.x[0]) ^ UInt16(truncatingIfNeeded: self.x[5] >> 16) + output16[6] = UInt16(truncatingIfNeeded: self.x[0] >> 16) ^ UInt16(truncatingIfNeeded: self.x[3]) + output16[5] = UInt16(truncatingIfNeeded: self.x[2]) ^ UInt16(truncatingIfNeeded: self.x[7] >> 16) + output16[4] = UInt16(truncatingIfNeeded: self.x[2] >> 16) ^ UInt16(truncatingIfNeeded: self.x[5]) + output16[3] = UInt16(truncatingIfNeeded: self.x[4]) ^ UInt16(truncatingIfNeeded: self.x[1] >> 16) + output16[2] = UInt16(truncatingIfNeeded: self.x[4] >> 16) ^ UInt16(truncatingIfNeeded: self.x[7]) + output16[1] = UInt16(truncatingIfNeeded: self.x[6]) ^ UInt16(truncatingIfNeeded: self.x[3] >> 16) + output16[0] = UInt16(truncatingIfNeeded: self.x[6] >> 16) ^ UInt16(truncatingIfNeeded: self.x[1]) + + var output8 = Array(repeating: 0, count: Rabbit.blockSize) + for j in 0..> 8) + output8[j * 2 + 1] = UInt8(truncatingIfNeeded: output16[j]) + } + return output8 + } +} + +// MARK: Cipher + +extension Rabbit: Cipher { + public func encrypt(_ bytes: ArraySlice) throws -> Array { + self.setup() + + return Array(unsafeUninitializedCapacity: bytes.count) { result, count in + var output = self.nextOutput() + var byteIdx = 0 + var outputIdx = 0 + while byteIdx < bytes.count { + if outputIdx == Rabbit.blockSize { + output = self.nextOutput() + outputIdx = 0 + } + + result[byteIdx] = bytes[byteIdx] ^ output[outputIdx] + + byteIdx += 1 + outputIdx += 1 + } + count = bytes.count + } + } + + public func decrypt(_ bytes: ArraySlice) throws -> Array { + try self.encrypt(bytes) + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/SHA1.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/SHA1.swift new file mode 100644 index 000000000..59cabefcf --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/SHA1.swift @@ -0,0 +1,158 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +public final class SHA1: DigestType { + + @usableFromInline + static let digestLength: Int = 20 // 160 / 8 + + @usableFromInline + static let blockSize: Int = 64 + + @usableFromInline + static let hashInitialValue: ContiguousArray = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0] + + @usableFromInline + var accumulated = Array() + + @usableFromInline + var processedBytesTotalCount: Int = 0 + + @usableFromInline + var accumulatedHash: ContiguousArray = SHA1.hashInitialValue + + public init() { + } + + @inlinable + public func calculate(for bytes: Array) -> Array { + do { + return try update(withBytes: bytes.slice, isLast: true) + } catch { + return [] + } + } + + @usableFromInline + func process(block chunk: ArraySlice, currentHash hh: inout ContiguousArray) { + // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian + // Extend the sixteen 32-bit words into eighty 32-bit words: + let M = UnsafeMutablePointer.allocate(capacity: 80) + M.initialize(repeating: 0, count: 80) + defer { + M.deinitialize(count: 80) + M.deallocate() + } + + for x in 0..<80 { + switch x { + case 0...15: + let start = chunk.startIndex.advanced(by: x * 4) // * MemoryLayout.size + M[x] = UInt32(bytes: chunk, fromIndex: start) + default: + M[x] = rotateLeft(M[x - 3] ^ M[x - 8] ^ M[x - 14] ^ M[x - 16], by: 1) + } + } + + var A = hh[0] + var B = hh[1] + var C = hh[2] + var D = hh[3] + var E = hh[4] + + // Main loop + for j in 0...79 { + var f: UInt32 = 0 + var k: UInt32 = 0 + + switch j { + case 0...19: + f = (B & C) | ((~B) & D) + k = 0x5a827999 + case 20...39: + f = B ^ C ^ D + k = 0x6ed9eba1 + case 40...59: + f = (B & C) | (B & D) | (C & D) + k = 0x8f1bbcdc + case 60...79: + f = B ^ C ^ D + k = 0xca62c1d6 + default: + break + } + + let temp = rotateLeft(A, by: 5) &+ f &+ E &+ M[j] &+ k + E = D + D = C + C = rotateLeft(B, by: 30) + B = A + A = temp + } + + hh[0] = hh[0] &+ A + hh[1] = hh[1] &+ B + hh[2] = hh[2] &+ C + hh[3] = hh[3] &+ D + hh[4] = hh[4] &+ E + } +} + +extension SHA1: Updatable { + @discardableResult @inlinable + public func update(withBytes bytes: ArraySlice, isLast: Bool = false) throws -> Array { + self.accumulated += bytes + + if isLast { + let lengthInBits = (processedBytesTotalCount + self.accumulated.count) * 8 + let lengthBytes = lengthInBits.bytes(totalBytes: 64 / 8) // A 64-bit representation of b + + // Step 1. Append padding + bitPadding(to: &self.accumulated, blockSize: SHA1.blockSize, allowance: 64 / 8) + + // Step 2. Append Length a 64-bit representation of lengthInBits + self.accumulated += lengthBytes + } + + var processedBytes = 0 + for chunk in self.accumulated.batched(by: SHA1.blockSize) { + if isLast || (self.accumulated.count - processedBytes) >= SHA1.blockSize { + self.process(block: chunk, currentHash: &self.accumulatedHash) + processedBytes += chunk.count + } + } + self.accumulated.removeFirst(processedBytes) + self.processedBytesTotalCount += processedBytes + + // output current hash + var result = Array(repeating: 0, count: SHA1.digestLength) + var pos = 0 + for idx in 0..> 24) & 0xff) + result[pos + 1] = UInt8((h >> 16) & 0xff) + result[pos + 2] = UInt8((h >> 8) & 0xff) + result[pos + 3] = UInt8(h & 0xff) + pos += 4 + } + + // reset hash value for instance + if isLast { + self.accumulatedHash = SHA1.hashInitialValue + } + + return result + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/SHA2.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/SHA2.swift new file mode 100644 index 000000000..e5f84de95 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/SHA2.swift @@ -0,0 +1,368 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// TODO: generic for process32/64 (UInt32/UInt64) +// + +public final class SHA2: DigestType { + @usableFromInline + let variant: Variant + + @usableFromInline + let size: Int + + @usableFromInline + let blockSize: Int + + @usableFromInline + let digestLength: Int + + private let k: Array + + @usableFromInline + var accumulated = Array() + + @usableFromInline + var processedBytesTotalCount: Int = 0 + + @usableFromInline + var accumulatedHash32 = Array() + + @usableFromInline + var accumulatedHash64 = Array() + + @frozen + public enum Variant: RawRepresentable { + case sha224, sha256, sha384, sha512 + + public var digestLength: Int { + self.rawValue / 8 + } + + public var blockSize: Int { + switch self { + case .sha224, .sha256: + return 64 + case .sha384, .sha512: + return 128 + } + } + + public typealias RawValue = Int + public var rawValue: RawValue { + switch self { + case .sha224: + return 224 + case .sha256: + return 256 + case .sha384: + return 384 + case .sha512: + return 512 + } + } + + public init?(rawValue: RawValue) { + switch rawValue { + case 224: + self = .sha224 + case 256: + self = .sha256 + case 384: + self = .sha384 + case 512: + self = .sha512 + default: + return nil + } + } + + @usableFromInline + var h: Array { + switch self { + case .sha224: + return [0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4] + case .sha256: + return [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19] + case .sha384: + return [0xcbbb9d5dc1059ed8, 0x629a292a367cd507, 0x9159015a3070dd17, 0x152fecd8f70e5939, 0x67332667ffc00b31, 0x8eb44a8768581511, 0xdb0c2e0d64f98fa7, 0x47b5481dbefa4fa4] + case .sha512: + return [0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179] + } + } + + @usableFromInline + var finalLength: Int { + switch self { + case .sha224: + return 7 + case .sha384: + return 6 + default: + return Int.max + } + } + } + + public init(variant: SHA2.Variant) { + self.variant = variant + switch self.variant { + case .sha224, .sha256: + self.accumulatedHash32 = variant.h.map { UInt32($0) } // FIXME: UInt64 for process64 + self.blockSize = variant.blockSize + self.size = variant.rawValue + self.digestLength = variant.digestLength + self.k = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 + ] + case .sha384, .sha512: + self.accumulatedHash64 = variant.h + self.blockSize = variant.blockSize + self.size = variant.rawValue + self.digestLength = variant.digestLength + self.k = [ + 0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538, + 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe, + 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, + 0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65, + 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab, + 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725, + 0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, + 0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b, + 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218, + 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, + 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, + 0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec, + 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c, + 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6, + 0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, + 0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817 + ] + } + } + + @inlinable + public func calculate(for bytes: Array) -> Array { + do { + return try update(withBytes: bytes.slice, isLast: true) + } catch { + return [] + } + } + + @usableFromInline + func process64(block chunk: ArraySlice, currentHash hh: inout Array) { + // break chunk into sixteen 64-bit words M[j], 0 ≤ j ≤ 15, big-endian + // Extend the sixteen 64-bit words into eighty 64-bit words: + let M = UnsafeMutablePointer.allocate(capacity: self.k.count) + M.initialize(repeating: 0, count: self.k.count) + defer { + M.deinitialize(count: self.k.count) + M.deallocate() + } + for x in 0...size + M[x] = UInt64(bytes: chunk, fromIndex: start) + default: + let s0 = rotateRight(M[x - 15], by: 1) ^ rotateRight(M[x - 15], by: 8) ^ (M[x - 15] >> 7) + let s1 = rotateRight(M[x - 2], by: 19) ^ rotateRight(M[x - 2], by: 61) ^ (M[x - 2] >> 6) + M[x] = M[x - 16] &+ s0 &+ M[x - 7] &+ s1 + } + } + + var A = hh[0] + var B = hh[1] + var C = hh[2] + var D = hh[3] + var E = hh[4] + var F = hh[5] + var G = hh[6] + var H = hh[7] + + // Main loop + for j in 0.., currentHash hh: inout Array) { + // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian + // Extend the sixteen 32-bit words into sixty-four 32-bit words: + let M = UnsafeMutablePointer.allocate(capacity: self.k.count) + M.initialize(repeating: 0, count: self.k.count) + defer { + M.deinitialize(count: self.k.count) + M.deallocate() + } + + for x in 0...size + M[x] = UInt32(bytes: chunk, fromIndex: start) + default: + let s0 = rotateRight(M[x - 15], by: 7) ^ rotateRight(M[x - 15], by: 18) ^ (M[x - 15] >> 3) + let s1 = rotateRight(M[x - 2], by: 17) ^ rotateRight(M[x - 2], by: 19) ^ (M[x - 2] >> 10) + M[x] = M[x - 16] &+ s0 &+ M[x - 7] &+ s1 + } + } + + var A = hh[0] + var B = hh[1] + var C = hh[2] + var D = hh[3] + var E = hh[4] + var F = hh[5] + var G = hh[6] + var H = hh[7] + + // Main loop + for j in 0.., isLast: Bool = false) throws -> Array { + self.accumulated += bytes + + if isLast { + let lengthInBits = (processedBytesTotalCount + self.accumulated.count) * 8 + let lengthBytes = lengthInBits.bytes(totalBytes: self.blockSize / 8) // A 64-bit/128-bit representation of b. blockSize fit by accident. + + // Step 1. Append padding + bitPadding(to: &self.accumulated, blockSize: self.blockSize, allowance: self.blockSize / 8) + + // Step 2. Append Length a 64-bit representation of lengthInBits + self.accumulated += lengthBytes + } + + var processedBytes = 0 + for chunk in self.accumulated.batched(by: self.blockSize) { + if isLast || (self.accumulated.count - processedBytes) >= self.blockSize { + switch self.variant { + case .sha224, .sha256: + self.process32(block: chunk, currentHash: &self.accumulatedHash32) + case .sha384, .sha512: + self.process64(block: chunk, currentHash: &self.accumulatedHash64) + } + processedBytes += chunk.count + } + } + self.accumulated.removeFirst(processedBytes) + self.processedBytesTotalCount += processedBytes + + // output current hash + var result = Array(repeating: 0, count: variant.digestLength) + switch self.variant { + case .sha224, .sha256: + var pos = 0 + for idx in 0..> 24) & 0xff) + result[pos + 1] = UInt8((h >> 16) & 0xff) + result[pos + 2] = UInt8((h >> 8) & 0xff) + result[pos + 3] = UInt8(h & 0xff) + pos += 4 + } + case .sha384, .sha512: + var pos = 0 + for idx in 0..> 56) & 0xff) + result[pos + 1] = UInt8((h >> 48) & 0xff) + result[pos + 2] = UInt8((h >> 40) & 0xff) + result[pos + 3] = UInt8((h >> 32) & 0xff) + result[pos + 4] = UInt8((h >> 24) & 0xff) + result[pos + 5] = UInt8((h >> 16) & 0xff) + result[pos + 6] = UInt8((h >> 8) & 0xff) + result[pos + 7] = UInt8(h & 0xff) + pos += 8 + } + } + + // reset hash value for instance + if isLast { + switch self.variant { + case .sha224, .sha256: + self.accumulatedHash32 = self.variant.h.lazy.map { UInt32($0) } // FIXME: UInt64 for process64 + case .sha384, .sha512: + self.accumulatedHash64 = self.variant.h + } + } + + return result + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/SHA3.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/SHA3.swift new file mode 100644 index 000000000..dc57504e6 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/SHA3.swift @@ -0,0 +1,299 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf +// http://keccak.noekeon.org/specs_summary.html +// + +#if canImport(Darwin) +import Darwin +#elseif canImport(Glibc) +import Glibc +#elseif canImport(ucrt) +import ucrt +#endif + +public final class SHA3: DigestType { + let round_constants: Array = [ + 0x0000000000000001, 0x0000000000008082, 0x800000000000808a, 0x8000000080008000, + 0x000000000000808b, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009, + 0x000000000000008a, 0x0000000000000088, 0x0000000080008009, 0x000000008000000a, + 0x000000008000808b, 0x800000000000008b, 0x8000000000008089, 0x8000000000008003, + 0x8000000000008002, 0x8000000000000080, 0x000000000000800a, 0x800000008000000a, + 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008 + ] + + public let blockSize: Int + public let digestLength: Int + public let markByte: UInt8 + + @usableFromInline + var accumulated = Array() + + + @usableFromInline + var accumulatedHash: Array + + public enum Variant { + case sha224, sha256, sha384, sha512, keccak224, keccak256, keccak384, keccak512 + + var digestLength: Int { + 100 - (self.blockSize / 2) + } + + var blockSize: Int { + (1600 - self.outputLength * 2) / 8 + } + + var markByte: UInt8 { + switch self { + case .sha224, .sha256, .sha384, .sha512: + return 0x06 // 0x1F for SHAKE + case .keccak224, .keccak256, .keccak384, .keccak512: + return 0x01 + } + } + + public var outputLength: Int { + switch self { + case .sha224, .keccak224: + return 224 + case .sha256, .keccak256: + return 256 + case .sha384, .keccak384: + return 384 + case .sha512, .keccak512: + return 512 + } + } + } + + public init(variant: SHA3.Variant) { + self.blockSize = variant.blockSize + self.digestLength = variant.digestLength + self.markByte = variant.markByte + self.accumulatedHash = Array(repeating: 0, count: self.digestLength) + } + + @inlinable + public func calculate(for bytes: Array) -> Array { + do { + return try update(withBytes: bytes.slice, isLast: true) + } catch { + return [] + } + } + + /// 1. For all pairs (x,z) such that 0≤x<5 and 0≤z) { + let c = UnsafeMutablePointer.allocate(capacity: 5) + c.initialize(repeating: 0, count: 5) + defer { + c.deinitialize(count: 5) + c.deallocate() + } + let d = UnsafeMutablePointer.allocate(capacity: 5) + d.initialize(repeating: 0, count: 5) + defer { + d.deinitialize(count: 5) + d.deallocate() + } + + for i in 0..<5 { + c[i] = a[i] ^ a[i &+ 5] ^ a[i &+ 10] ^ a[i &+ 15] ^ a[i &+ 20] + } + + d[0] = rotateLeft(c[1], by: 1) ^ c[4] + d[1] = rotateLeft(c[2], by: 1) ^ c[0] + d[2] = rotateLeft(c[3], by: 1) ^ c[1] + d[3] = rotateLeft(c[4], by: 1) ^ c[2] + d[4] = rotateLeft(c[0], by: 1) ^ c[3] + + for i in 0..<5 { + a[i] ^= d[i] + a[i &+ 5] ^= d[i] + a[i &+ 10] ^= d[i] + a[i &+ 15] ^= d[i] + a[i &+ 20] ^= d[i] + } + } + + /// A′[x, y, z]=A[(x &+ 3y) mod 5, x, z] + private func π(_ a: inout Array) { + let a1 = a[1] + a[1] = a[6] + a[6] = a[9] + a[9] = a[22] + a[22] = a[14] + a[14] = a[20] + a[20] = a[2] + a[2] = a[12] + a[12] = a[13] + a[13] = a[19] + a[19] = a[23] + a[23] = a[15] + a[15] = a[4] + a[4] = a[24] + a[24] = a[21] + a[21] = a[8] + a[8] = a[16] + a[16] = a[5] + a[5] = a[3] + a[3] = a[18] + a[18] = a[17] + a[17] = a[11] + a[11] = a[7] + a[7] = a[10] + a[10] = a1 + } + + /// For all triples (x, y, z) such that 0≤x<5, 0≤y<5, and 0≤z) { + for i in stride(from: 0, to: 25, by: 5) { + let a0 = a[0 &+ i] + let a1 = a[1 &+ i] + a[0 &+ i] ^= ~a1 & a[2 &+ i] + a[1 &+ i] ^= ~a[2 &+ i] & a[3 &+ i] + a[2 &+ i] ^= ~a[3 &+ i] & a[4 &+ i] + a[3 &+ i] ^= ~a[4 &+ i] & a0 + a[4 &+ i] ^= ~a0 & a1 + } + } + + private func ι(_ a: inout Array, round: Int) { + a[0] ^= self.round_constants[round] + } + + @usableFromInline + func process(block chunk: ArraySlice, currentHash hh: inout Array) { + // expand + hh[0] ^= chunk[0].littleEndian + hh[1] ^= chunk[1].littleEndian + hh[2] ^= chunk[2].littleEndian + hh[3] ^= chunk[3].littleEndian + hh[4] ^= chunk[4].littleEndian + hh[5] ^= chunk[5].littleEndian + hh[6] ^= chunk[6].littleEndian + hh[7] ^= chunk[7].littleEndian + hh[8] ^= chunk[8].littleEndian + if self.blockSize > 72 { // 72 / 8, sha-512 + hh[9] ^= chunk[9].littleEndian + hh[10] ^= chunk[10].littleEndian + hh[11] ^= chunk[11].littleEndian + hh[12] ^= chunk[12].littleEndian + if self.blockSize > 104 { // 104 / 8, sha-384 + hh[13] ^= chunk[13].littleEndian + hh[14] ^= chunk[14].littleEndian + hh[15] ^= chunk[15].littleEndian + hh[16] ^= chunk[16].littleEndian + if self.blockSize > 136 { // 136 / 8, sha-256 + hh[17] ^= chunk[17].littleEndian + // FULL_SHA3_FAMILY_SUPPORT + if self.blockSize > 144 { // 144 / 8, sha-224 + hh[18] ^= chunk[18].littleEndian + hh[19] ^= chunk[19].littleEndian + hh[20] ^= chunk[20].littleEndian + hh[21] ^= chunk[21].littleEndian + hh[22] ^= chunk[22].littleEndian + hh[23] ^= chunk[23].littleEndian + hh[24] ^= chunk[24].littleEndian + } + } + } + } + + // Keccak-f + for round in 0..<24 { + self.θ(&hh) + + hh[1] = rotateLeft(hh[1], by: 1) + hh[2] = rotateLeft(hh[2], by: 62) + hh[3] = rotateLeft(hh[3], by: 28) + hh[4] = rotateLeft(hh[4], by: 27) + hh[5] = rotateLeft(hh[5], by: 36) + hh[6] = rotateLeft(hh[6], by: 44) + hh[7] = rotateLeft(hh[7], by: 6) + hh[8] = rotateLeft(hh[8], by: 55) + hh[9] = rotateLeft(hh[9], by: 20) + hh[10] = rotateLeft(hh[10], by: 3) + hh[11] = rotateLeft(hh[11], by: 10) + hh[12] = rotateLeft(hh[12], by: 43) + hh[13] = rotateLeft(hh[13], by: 25) + hh[14] = rotateLeft(hh[14], by: 39) + hh[15] = rotateLeft(hh[15], by: 41) + hh[16] = rotateLeft(hh[16], by: 45) + hh[17] = rotateLeft(hh[17], by: 15) + hh[18] = rotateLeft(hh[18], by: 21) + hh[19] = rotateLeft(hh[19], by: 8) + hh[20] = rotateLeft(hh[20], by: 18) + hh[21] = rotateLeft(hh[21], by: 2) + hh[22] = rotateLeft(hh[22], by: 61) + hh[23] = rotateLeft(hh[23], by: 56) + hh[24] = rotateLeft(hh[24], by: 14) + + self.π(&hh) + self.χ(&hh) + self.ι(&hh, round: round) + } + } +} + +extension SHA3: Updatable { + + @inlinable + public func update(withBytes bytes: ArraySlice, isLast: Bool = false) throws -> Array { + self.accumulated += bytes + + if isLast { + // Add padding + let markByteIndex = self.accumulated.count + + // We need to always pad the input. Even if the input is a multiple of blockSize. + let r = self.blockSize * 8 + let q = (r / 8) - (accumulated.count % (r / 8)) + self.accumulated += Array(repeating: 0, count: q) + + self.accumulated[markByteIndex] |= self.markByte + self.accumulated[self.accumulated.count - 1] |= 0x80 + } + + var processedBytes = 0 + for chunk in self.accumulated.batched(by: self.blockSize) { + if isLast || (self.accumulated.count - processedBytes) >= self.blockSize { + self.process(block: chunk.toUInt64Array().slice, currentHash: &self.accumulatedHash) + processedBytes += chunk.count + } + } + self.accumulated.removeFirst(processedBytes) + + // TODO: verify performance, reduce vs for..in + let result = self.accumulatedHash.reduce(into: Array()) { (result, value) in + result += value.bigEndian.bytes() + } + + // reset hash value for instance + if isLast { + self.accumulatedHash = Array(repeating: 0, count: self.digestLength) + } + + return Array(result[0.. +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +// +// https://tools.ietf.org/html/rfc7914 +// + +/// Implementation of the scrypt key derivation function. +public final class Scrypt { + enum Error: Swift.Error { + case nIsTooLarge + case rIsTooLarge + case nMustBeAPowerOf2GreaterThan1 + case invalidInput + } + + /// Configuration parameters. + private let salt: SecureBytes + private let password: SecureBytes + private let blocksize: Int // 128 * r + private let salsaBlock = UnsafeMutableRawPointer.allocate(byteCount: 64, alignment: 64) + private let dkLen: Int + private let N: Int + private let r: Int + private let p: Int + + /// - parameters: + /// - password: password + /// - salt: salt + /// - dkLen: output length + /// - N: determines extra memory used + /// - r: determines a block size + /// - p: determines parallelicity degree + public init(password: Array, salt: Array, dkLen: Int, N: Int, r: Int, p: Int) throws { + precondition(dkLen > 0) + precondition(N > 0) + precondition(r > 0) + precondition(p > 0) + + guard !(N < 2 || (N & (N - 1)) != 0) else { throw Error.nMustBeAPowerOf2GreaterThan1 } + + guard N <= .max / 128 / r else { throw Error.nIsTooLarge } + guard r <= .max / 128 / p else { throw Error.rIsTooLarge } + + guard !salt.isEmpty else { + throw Error.invalidInput + } + + self.blocksize = 128 * r + self.N = N + self.r = r + self.p = p + self.password = SecureBytes(bytes: password) + self.salt = SecureBytes(bytes: salt) + self.dkLen = dkLen + } + + /// Runs the key derivation function with a specific password. + public func calculate() throws -> [UInt8] { + // Allocate memory (as bytes for now) for further use in mixing steps + let B = UnsafeMutableRawPointer.allocate(byteCount: 128 * self.r * self.p, alignment: 64) + let XY = UnsafeMutableRawPointer.allocate(byteCount: 256 * self.r + 64, alignment: 64) + let V = UnsafeMutableRawPointer.allocate(byteCount: 128 * self.r * self.N, alignment: 64) + + // Deallocate memory when done + defer { + B.deallocate() + XY.deallocate() + V.deallocate() + } + + /* 1: (B_0 ... B_{p-1}) <-- PBKDF2(P, S, 1, p * MFLen) */ + // Expand the initial key + let barray = try PKCS5.PBKDF2(password: Array(self.password), salt: Array(self.salt), iterations: 1, keyLength: self.p * 128 * self.r, variant: .sha2(.sha256)).calculate() + barray.withUnsafeBytes { p in + B.copyMemory(from: p.baseAddress!, byteCount: barray.count) + } + + /* 2: for i = 0 to p - 1 do */ + // do the mixing + for i in 0 ..< self.p { + /* 3: B_i <-- MF(B_i, N) */ + smix(B + i * 128 * self.r, V.assumingMemoryBound(to: UInt32.self), XY.assumingMemoryBound(to: UInt32.self)) + } + + /* 5: DK <-- PBKDF2(P, B, 1, dkLen) */ + let pointer = B.assumingMemoryBound(to: UInt8.self) + let bufferPointer = UnsafeBufferPointer(start: pointer, count: p * 128 * self.r) + let block = [UInt8](bufferPointer) + return try PKCS5.PBKDF2(password: Array(self.password), salt: block, iterations: 1, keyLength: self.dkLen, variant: .sha2(.sha256)).calculate() + } +} + +private extension Scrypt { + /// Computes `B = SMix_r(B, N)`. + /// + /// The input `block` must be `128*r` bytes in length; the temporary storage `v` must be `128*r*n` bytes in length; + /// the temporary storage `xy` must be `256*r + 64` bytes in length. The arrays `block`, `v`, and `xy` must be + /// aligned to a multiple of 64 bytes. + @inline(__always) func smix(_ block: UnsafeMutableRawPointer, _ v: UnsafeMutablePointer, _ xy: UnsafeMutablePointer) { + let X = xy + let Y = xy + 32 * self.r + let Z = xy + 64 * self.r + + /* 1: X <-- B */ + let typedBlock = block.assumingMemoryBound(to: UInt32.self) + X.assign(from: typedBlock, count: 32 * self.r) + + /* 2: for i = 0 to N - 1 do */ + for i in stride(from: 0, to: self.N, by: 2) { + /* 3: V_i <-- X */ + UnsafeMutableRawPointer(v + i * (32 * self.r)).copyMemory(from: X, byteCount: 128 * self.r) + + /* 4: X <-- H(X) */ + self.blockMixSalsa8(X, Y, Z) + + /* 3: V_i <-- X */ + UnsafeMutableRawPointer(v + (i + 1) * (32 * self.r)).copyMemory(from: Y, byteCount: 128 * self.r) + + /* 4: X <-- H(X) */ + self.blockMixSalsa8(Y, X, Z) + } + + /* 6: for i = 0 to N - 1 do */ + for _ in stride(from: 0, to: self.N, by: 2) { + /* + 7: j <-- Integerify (X) mod N + where Integerify (B[0] ... B[2 * r - 1]) is defined + as the result of interpreting B[2 * r - 1] as a little-endian integer. + */ + var j = Int(integerify(X) & UInt64(self.N - 1)) + + /* 8: X <-- H(X \xor V_j) */ + self.blockXor(X, v + j * 32 * self.r, 128 * self.r) + self.blockMixSalsa8(X, Y, Z) + + /* 7: j <-- Integerify(X) mod N */ + j = Int(self.integerify(Y) & UInt64(self.N - 1)) + + /* 8: X <-- H(X \xor V_j) */ + self.blockXor(Y, v + j * 32 * self.r, 128 * self.r) + self.blockMixSalsa8(Y, X, Z) + } + + /* 10: B' <-- X */ + for k in 0 ..< 32 * self.r { + UnsafeMutableRawPointer(block + 4 * k).storeBytes(of: X[k], as: UInt32.self) + } + } + + /// Returns the result of parsing `B_{2r-1}` as a little-endian integer. + @inline(__always) func integerify(_ block: UnsafeRawPointer) -> UInt64 { + let bi = block + (2 * self.r - 1) * 64 + return bi.load(as: UInt64.self).littleEndian + } + + /// Compute `bout = BlockMix_{salsa20/8, r}(bin)`. + /// + /// The input `bin` must be `128*r` bytes in length; the output `bout` must also be the same size. The temporary + /// space `x` must be 64 bytes. + @inline(__always) func blockMixSalsa8(_ bin: UnsafePointer, _ bout: UnsafeMutablePointer, _ x: UnsafeMutablePointer) { + /* 1: X <-- B_{2r - 1} */ + UnsafeMutableRawPointer(x).copyMemory(from: bin + (2 * self.r - 1) * 16, byteCount: 64) + + /* 2: for i = 0 to 2r - 1 do */ + for i in stride(from: 0, to: 2 * self.r, by: 2) { + /* 3: X <-- H(X \xor B_i) */ + self.blockXor(x, bin + i * 16, 64) + self.salsa20_8_typed(x) + + /* 4: Y_i <-- X */ + /* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */ + UnsafeMutableRawPointer(bout + i * 8).copyMemory(from: x, byteCount: 64) + + /* 3: X <-- H(X \xor B_i) */ + self.blockXor(x, bin + i * 16 + 16, 64) + self.salsa20_8_typed(x) + + /* 4: Y_i <-- X */ + /* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */ + UnsafeMutableRawPointer(bout + i * 8 + self.r * 16).copyMemory(from: x, byteCount: 64) + } + } + + @inline(__always) func salsa20_8_typed(_ block: UnsafeMutablePointer) { + self.salsaBlock.copyMemory(from: UnsafeRawPointer(block), byteCount: 64) + let salsaBlockTyped = self.salsaBlock.assumingMemoryBound(to: UInt32.self) + + for _ in stride(from: 0, to: 8, by: 2) { + salsaBlockTyped[4] ^= rotateLeft(salsaBlockTyped[0] &+ salsaBlockTyped[12], by: 7) + salsaBlockTyped[8] ^= rotateLeft(salsaBlockTyped[4] &+ salsaBlockTyped[0], by: 9) + salsaBlockTyped[12] ^= rotateLeft(salsaBlockTyped[8] &+ salsaBlockTyped[4], by: 13) + salsaBlockTyped[0] ^= rotateLeft(salsaBlockTyped[12] &+ salsaBlockTyped[8], by: 18) + + salsaBlockTyped[9] ^= rotateLeft(salsaBlockTyped[5] &+ salsaBlockTyped[1], by: 7) + salsaBlockTyped[13] ^= rotateLeft(salsaBlockTyped[9] &+ salsaBlockTyped[5], by: 9) + salsaBlockTyped[1] ^= rotateLeft(salsaBlockTyped[13] &+ salsaBlockTyped[9], by: 13) + salsaBlockTyped[5] ^= rotateLeft(salsaBlockTyped[1] &+ salsaBlockTyped[13], by: 18) + + salsaBlockTyped[14] ^= rotateLeft(salsaBlockTyped[10] &+ salsaBlockTyped[6], by: 7) + salsaBlockTyped[2] ^= rotateLeft(salsaBlockTyped[14] &+ salsaBlockTyped[10], by: 9) + salsaBlockTyped[6] ^= rotateLeft(salsaBlockTyped[2] &+ salsaBlockTyped[14], by: 13) + salsaBlockTyped[10] ^= rotateLeft(salsaBlockTyped[6] &+ salsaBlockTyped[2], by: 18) + + salsaBlockTyped[3] ^= rotateLeft(salsaBlockTyped[15] &+ salsaBlockTyped[11], by: 7) + salsaBlockTyped[7] ^= rotateLeft(salsaBlockTyped[3] &+ salsaBlockTyped[15], by: 9) + salsaBlockTyped[11] ^= rotateLeft(salsaBlockTyped[7] &+ salsaBlockTyped[3], by: 13) + salsaBlockTyped[15] ^= rotateLeft(salsaBlockTyped[11] &+ salsaBlockTyped[7], by: 18) + + salsaBlockTyped[1] ^= rotateLeft(salsaBlockTyped[0] &+ salsaBlockTyped[3], by: 7) + salsaBlockTyped[2] ^= rotateLeft(salsaBlockTyped[1] &+ salsaBlockTyped[0], by: 9) + salsaBlockTyped[3] ^= rotateLeft(salsaBlockTyped[2] &+ salsaBlockTyped[1], by: 13) + salsaBlockTyped[0] ^= rotateLeft(salsaBlockTyped[3] &+ salsaBlockTyped[2], by: 18) + + salsaBlockTyped[6] ^= rotateLeft(salsaBlockTyped[5] &+ salsaBlockTyped[4], by: 7) + salsaBlockTyped[7] ^= rotateLeft(salsaBlockTyped[6] &+ salsaBlockTyped[5], by: 9) + salsaBlockTyped[4] ^= rotateLeft(salsaBlockTyped[7] &+ salsaBlockTyped[6], by: 13) + salsaBlockTyped[5] ^= rotateLeft(salsaBlockTyped[4] &+ salsaBlockTyped[7], by: 18) + + salsaBlockTyped[11] ^= rotateLeft(salsaBlockTyped[10] &+ salsaBlockTyped[9], by: 7) + salsaBlockTyped[8] ^= rotateLeft(salsaBlockTyped[11] &+ salsaBlockTyped[10], by: 9) + salsaBlockTyped[9] ^= rotateLeft(salsaBlockTyped[8] &+ salsaBlockTyped[11], by: 13) + salsaBlockTyped[10] ^= rotateLeft(salsaBlockTyped[9] &+ salsaBlockTyped[8], by: 18) + + salsaBlockTyped[12] ^= rotateLeft(salsaBlockTyped[15] &+ salsaBlockTyped[14], by: 7) + salsaBlockTyped[13] ^= rotateLeft(salsaBlockTyped[12] &+ salsaBlockTyped[15], by: 9) + salsaBlockTyped[14] ^= rotateLeft(salsaBlockTyped[13] &+ salsaBlockTyped[12], by: 13) + salsaBlockTyped[15] ^= rotateLeft(salsaBlockTyped[14] &+ salsaBlockTyped[13], by: 18) + } + for i in 0 ..< 16 { + block[i] = block[i] &+ salsaBlockTyped[i] + } + } + + @inline(__always) func blockXor(_ dest: UnsafeMutableRawPointer, _ src: UnsafeRawPointer, _ len: Int) { + let D = dest.assumingMemoryBound(to: UInt64.self) + let S = src.assumingMemoryBound(to: UInt64.self) + let L = len / MemoryLayout.size + + for i in 0 ..< L { + D[i] ^= S[i] + } + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/SecureBytes.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/SecureBytes.swift new file mode 100644 index 000000000..9d80fca8d --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/SecureBytes.swift @@ -0,0 +1,87 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +#if canImport(Darwin) +import Darwin +#elseif canImport(Glibc) +import Glibc +#elseif canImport(WinSDK) +import WinSDK +#endif + +typealias Key = SecureBytes + +/// Keeps bytes in memory. Because this is class, bytes are not copied +/// and memory area is locked as long as referenced, then unlocked on deinit +final class SecureBytes { + private let bytes: Array + let count: Int + + init(bytes: Array) { + self.bytes = bytes + self.count = bytes.count + self.bytes.withUnsafeBufferPointer { (pointer) -> Void in + #if os(Windows) + VirtualLock(UnsafeMutableRawPointer(mutating: pointer.baseAddress), SIZE_T(pointer.count)) + #else + mlock(pointer.baseAddress, pointer.count) + #endif + } + } + + deinit { + self.bytes.withUnsafeBufferPointer { (pointer) -> Void in + #if os(Windows) + VirtualUnlock(UnsafeMutableRawPointer(mutating: pointer.baseAddress), SIZE_T(pointer.count)) + #else + munlock(pointer.baseAddress, pointer.count) + #endif + } + } +} + +extension SecureBytes: Collection { + typealias Index = Int + + var endIndex: Int { + self.bytes.endIndex + } + + var startIndex: Int { + self.bytes.startIndex + } + + subscript(position: Index) -> UInt8 { + self.bytes[position] + } + + subscript(bounds: Range) -> ArraySlice { + self.bytes[bounds] + } + + func formIndex(after i: inout Int) { + self.bytes.formIndex(after: &i) + } + + func index(after i: Int) -> Int { + self.bytes.index(after: i) + } +} + +extension SecureBytes: ExpressibleByArrayLiteral { + public convenience init(arrayLiteral elements: UInt8...) { + self.init(bytes: elements) + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/StreamDecryptor.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/StreamDecryptor.swift new file mode 100644 index 000000000..88802b56b --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/StreamDecryptor.swift @@ -0,0 +1,92 @@ +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +@usableFromInline +final class StreamDecryptor: Cryptor, Updatable { + + @usableFromInline + internal let blockSize: Int + + @usableFromInline + internal var worker: CipherModeWorker + + @usableFromInline + internal let padding: Padding + + @usableFromInline + internal var accumulated = Array() + + @usableFromInline + internal var lastBlockRemainder = 0 + + @usableFromInline + init(blockSize: Int, padding: Padding, _ worker: CipherModeWorker) throws { + self.blockSize = blockSize + self.padding = padding + self.worker = worker + } + + // MARK: Updatable + + @inlinable + public func update(withBytes bytes: ArraySlice, isLast: Bool) throws -> Array { + self.accumulated += bytes + + let toProcess = self.accumulated.prefix(max(self.accumulated.count - self.worker.additionalBufferSize, 0)) + + if var finalizingWorker = worker as? FinalizingDecryptModeWorker, isLast == true { + // will truncate suffix if needed + try finalizingWorker.willDecryptLast(bytes: self.accumulated.slice) + } + + var processedBytesCount = 0 + var plaintext = Array(reserveCapacity: bytes.count + self.worker.additionalBufferSize) + for chunk in toProcess.batched(by: self.blockSize) { + plaintext += self.worker.decrypt(block: chunk) + processedBytesCount += chunk.count + } + + if var finalizingWorker = worker as? FinalizingDecryptModeWorker, isLast == true { + plaintext = Array(try finalizingWorker.didDecryptLast(bytes: plaintext.slice)) + } + + // omit unecessary calculation if not needed + if self.padding != .noPadding { + self.lastBlockRemainder = plaintext.count.quotientAndRemainder(dividingBy: self.blockSize).remainder + } + + if isLast { + // CTR doesn't need padding. Really. Add padding to the last block if really want. but... don't. + plaintext = self.padding.remove(from: plaintext, blockSize: self.blockSize - self.lastBlockRemainder) + } + + self.accumulated.removeFirst(processedBytesCount) // super-slow + + if var finalizingWorker = worker as? FinalizingDecryptModeWorker, isLast == true { + plaintext = Array(try finalizingWorker.finalize(decrypt: plaintext.slice)) + } + + return plaintext + } + + @inlinable + public func seek(to position: Int) throws { + guard var worker = self.worker as? SeekableModeWorker else { + fatalError("Not supported") + } + + try worker.seek(to: position) + self.worker = worker + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/StreamEncryptor.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/StreamEncryptor.swift new file mode 100644 index 000000000..10ce7b1af --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/StreamEncryptor.swift @@ -0,0 +1,68 @@ +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +@usableFromInline +final class StreamEncryptor: Cryptor, Updatable { + + @usableFromInline + internal let blockSize: Int + + @usableFromInline + internal var worker: CipherModeWorker + + @usableFromInline + internal let padding: Padding + + @usableFromInline + internal var lastBlockRemainder = 0 + + @usableFromInline + init(blockSize: Int, padding: Padding, _ worker: CipherModeWorker) throws { + self.blockSize = blockSize + self.padding = padding + self.worker = worker + } + + // MARK: Updatable + + @inlinable + public func update(withBytes bytes: ArraySlice, isLast: Bool) throws -> Array { + var accumulated = Array(bytes) + if isLast { + // CTR doesn't need padding. Really. Add padding to the last block if really want. but... don't. + accumulated = self.padding.add(to: accumulated, blockSize: self.blockSize - self.lastBlockRemainder) + } + + var encrypted = Array(reserveCapacity: bytes.count) + for chunk in accumulated.batched(by: self.blockSize) { + encrypted += self.worker.encrypt(block: chunk) + } + + // omit unecessary calculation if not needed + if self.padding != .noPadding { + self.lastBlockRemainder = encrypted.count.quotientAndRemainder(dividingBy: self.blockSize).remainder + } + + if var finalizingWorker = worker as? FinalizingEncryptModeWorker, isLast == true { + encrypted = Array(try finalizingWorker.finalize(encrypt: encrypted.slice)) + } + + return encrypted + } + + @usableFromInline + func seek(to: Int) throws { + fatalError("Not supported") + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/String+Extension.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/String+Extension.swift new file mode 100644 index 000000000..dc979ce3b --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/String+Extension.swift @@ -0,0 +1,96 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +/** String extension */ +extension String { + + @inlinable + public var bytes: Array { + data(using: String.Encoding.utf8, allowLossyConversion: true)?.bytes ?? Array(utf8) + } + + @inlinable + public func md5() -> String { + self.bytes.md5().toHexString() + } + + @inlinable + public func sha1() -> String { + self.bytes.sha1().toHexString() + } + + @inlinable + public func sha224() -> String { + self.bytes.sha224().toHexString() + } + + @inlinable + public func sha256() -> String { + self.bytes.sha256().toHexString() + } + + @inlinable + public func sha384() -> String { + self.bytes.sha384().toHexString() + } + + @inlinable + public func sha512() -> String { + self.bytes.sha512().toHexString() + } + + @inlinable + public func sha3(_ variant: SHA3.Variant) -> String { + self.bytes.sha3(variant).toHexString() + } + + @inlinable + public func crc32(seed: UInt32? = nil, reflect: Bool = true) -> String { + self.bytes.crc32(seed: seed, reflect: reflect).bytes().toHexString() + } + + @inlinable + public func crc32c(seed: UInt32? = nil, reflect: Bool = true) -> String { + self.bytes.crc32c(seed: seed, reflect: reflect).bytes().toHexString() + } + + @inlinable + public func crc16(seed: UInt16? = nil) -> String { + self.bytes.crc16(seed: seed).bytes().toHexString() + } + + /// - parameter cipher: Instance of `Cipher` + /// - returns: hex string of bytes + @inlinable + public func encrypt(cipher: Cipher) throws -> String { + try self.bytes.encrypt(cipher: cipher).toHexString() + } + + /// - parameter cipher: Instance of `Cipher` + /// - returns: base64 encoded string of encrypted bytes + @inlinable + public func encryptToBase64(cipher: Cipher) throws -> String { + try self.bytes.encrypt(cipher: cipher).toBase64() + } + + // decrypt() does not make sense for String + + /// - parameter authenticator: Instance of `Authenticator` + /// - returns: hex string of string + @inlinable + public func authenticate(with authenticator: A) throws -> String { + try self.bytes.authenticate(with: authenticator).toHexString() + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/UInt128.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/UInt128.swift new file mode 100644 index 000000000..abc249331 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/UInt128.swift @@ -0,0 +1,90 @@ +// +// UInt128.swift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +import Foundation + +struct UInt128: Equatable, ExpressibleByIntegerLiteral { + let i: (a: UInt64, b: UInt64) + + typealias IntegerLiteralType = UInt64 + + init(integerLiteral value: IntegerLiteralType) { + self = UInt128(value) + } + + init(_ raw: Array) { + self = raw.prefix(MemoryLayout.stride).withUnsafeBytes({ (rawBufferPointer) -> UInt128 in + let arr = rawBufferPointer.bindMemory(to: UInt64.self) + return UInt128((arr[0].bigEndian, arr[1].bigEndian)) + }) + } + + init(_ raw: ArraySlice) { + self.init(Array(raw)) + } + + init(_ i: (a: UInt64, b: UInt64)) { + self.i = i + } + + init(a: UInt64, b: UInt64) { + self.init((a, b)) + } + + init(_ b: UInt64) { + self.init((0, b)) + } + + // Bytes + var bytes: Array { + var at = self.i.a.bigEndian + var bt = self.i.b.bigEndian + + let ar = Data(bytes: &at, count: MemoryLayout.size(ofValue: at)) + let br = Data(bytes: &bt, count: MemoryLayout.size(ofValue: bt)) + + var result = Data() + result.append(ar) + result.append(br) + return result.bytes + } + + static func ^ (n1: UInt128, n2: UInt128) -> UInt128 { + UInt128((n1.i.a ^ n2.i.a, n1.i.b ^ n2.i.b)) + } + + static func & (n1: UInt128, n2: UInt128) -> UInt128 { + UInt128((n1.i.a & n2.i.a, n1.i.b & n2.i.b)) + } + + static func >> (value: UInt128, by: Int) -> UInt128 { + var result = value + for _ in 0..> 1 + let b = result.i.b >> 1 + ((result.i.a & 1) << 63) + result = UInt128((a, b)) + } + return result + } + + // Equatable. + static func == (lhs: UInt128, rhs: UInt128) -> Bool { + lhs.i == rhs.i + } + + static func != (lhs: UInt128, rhs: UInt128) -> Bool { + !(lhs == rhs) + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/UInt16+Extension.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/UInt16+Extension.swift new file mode 100644 index 000000000..777bd980a --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/UInt16+Extension.swift @@ -0,0 +1,37 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +/** array of bytes */ +extension UInt16 { + @_specialize(where T == ArraySlice) + init(bytes: T) where T.Element == UInt8, T.Index == Int { + self = UInt16(bytes: bytes, fromIndex: bytes.startIndex) + } + + @_specialize(where T == ArraySlice) + init(bytes: T, fromIndex index: T.Index) where T.Element == UInt8, T.Index == Int { + if bytes.isEmpty { + self = 0 + return + } + + let count = bytes.count + + let val0 = count > 0 ? UInt16(bytes[index.advanced(by: 0)]) << 8 : 0 + let val1 = count > 1 ? UInt16(bytes[index.advanced(by: 1)]) : 0 + + self = val0 | val1 + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/UInt32+Extension.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/UInt32+Extension.swift new file mode 100644 index 000000000..915586929 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/UInt32+Extension.swift @@ -0,0 +1,51 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +#if canImport(Darwin) +import Darwin +#elseif canImport(Glibc) +import Glibc +#elseif canImport(ucrt) +import ucrt +#endif + +protocol _UInt32Type {} +extension UInt32: _UInt32Type {} + +/** array of bytes */ +extension UInt32 { + @_specialize(where T == ArraySlice) + init(bytes: T) where T.Element == UInt8, T.Index == Int { + self = UInt32(bytes: bytes, fromIndex: bytes.startIndex) + } + + @_specialize(where T == ArraySlice) + @inlinable + init(bytes: T, fromIndex index: T.Index) where T.Element == UInt8, T.Index == Int { + if bytes.isEmpty { + self = 0 + return + } + + let count = bytes.count + + let val0 = count > 0 ? UInt32(bytes[index.advanced(by: 0)]) << 24 : 0 + let val1 = count > 1 ? UInt32(bytes[index.advanced(by: 1)]) << 16 : 0 + let val2 = count > 2 ? UInt32(bytes[index.advanced(by: 2)]) << 8 : 0 + let val3 = count > 3 ? UInt32(bytes[index.advanced(by: 3)]) : 0 + + self = val0 | val1 | val2 | val3 + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/UInt64+Extension.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/UInt64+Extension.swift new file mode 100644 index 000000000..224f71730 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/UInt64+Extension.swift @@ -0,0 +1,44 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +/** array of bytes */ +extension UInt64 { + @_specialize(where T == ArraySlice) + init(bytes: T) where T.Element == UInt8, T.Index == Int { + self = UInt64(bytes: bytes, fromIndex: bytes.startIndex) + } + + @_specialize(where T == ArraySlice) + @inlinable + init(bytes: T, fromIndex index: T.Index) where T.Element == UInt8, T.Index == Int { + if bytes.isEmpty { + self = 0 + return + } + + let count = bytes.count + + let val0 = count > 0 ? UInt64(bytes[index.advanced(by: 0)]) << 56 : 0 + let val1 = count > 1 ? UInt64(bytes[index.advanced(by: 1)]) << 48 : 0 + let val2 = count > 2 ? UInt64(bytes[index.advanced(by: 2)]) << 40 : 0 + let val3 = count > 3 ? UInt64(bytes[index.advanced(by: 3)]) << 32 : 0 + let val4 = count > 4 ? UInt64(bytes[index.advanced(by: 4)]) << 24 : 0 + let val5 = count > 5 ? UInt64(bytes[index.advanced(by: 5)]) << 16 : 0 + let val6 = count > 6 ? UInt64(bytes[index.advanced(by: 6)]) << 8 : 0 + let val7 = count > 7 ? UInt64(bytes[index.advanced(by: 7)]) : 0 + + self = val0 | val1 | val2 | val3 | val4 | val5 | val6 | val7 + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/UInt8+Extension.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/UInt8+Extension.swift new file mode 100644 index 000000000..906a9ded1 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/UInt8+Extension.swift @@ -0,0 +1,74 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +#if canImport(Darwin) +import Darwin +#elseif canImport(Glibc) +import Glibc +#elseif canImport(ucrt) +import ucrt +#endif + +public protocol _UInt8Type {} +extension UInt8: _UInt8Type {} + +/** casting */ +extension UInt8 { + /** cast because UInt8() because std initializer crash if value is > byte */ + static func with(value: UInt64) -> UInt8 { + let tmp = value & 0xff + return UInt8(tmp) + } + + static func with(value: UInt32) -> UInt8 { + let tmp = value & 0xff + return UInt8(tmp) + } + + static func with(value: UInt16) -> UInt8 { + let tmp = value & 0xff + return UInt8(tmp) + } +} + +/** Bits */ +extension UInt8 { + /** array of bits */ + public func bits() -> [Bit] { + let totalBitsCount = MemoryLayout.size * 8 + + var bitsArray = [Bit](repeating: Bit.zero, count: totalBitsCount) + + for j in 0.. String { + var s = String() + let arr: [Bit] = self.bits() + for idx in arr.indices { + s += (arr[idx] == Bit.one ? "1" : "0") + if idx.advanced(by: 1) % 8 == 0 { s += " " } + } + return s + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Updatable.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Updatable.swift new file mode 100644 index 000000000..22031ad6e --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Updatable.swift @@ -0,0 +1,107 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +/// A type that supports incremental updates. For example Digest or Cipher may be updatable +/// and calculate result incerementally. +public protocol Updatable { + /// Update given bytes in chunks. + /// + /// - parameter bytes: Bytes to process. + /// - parameter isLast: Indicate if given chunk is the last one. No more updates after this call. + /// - returns: Processed partial result data or empty array. + mutating func update(withBytes bytes: ArraySlice, isLast: Bool) throws -> Array + + /// Update given bytes in chunks. + /// + /// - Parameters: + /// - bytes: Bytes to process. + /// - isLast: Indicate if given chunk is the last one. No more updates after this call. + /// - output: Resulting bytes callback. + /// - Returns: Processed partial result data or empty array. + mutating func update(withBytes bytes: ArraySlice, isLast: Bool, output: (_ bytes: Array) -> Void) throws +} + +extension Updatable { + @inlinable + public mutating func update(withBytes bytes: ArraySlice, isLast: Bool = false, output: (_ bytes: Array) -> Void) throws { + let processed = try update(withBytes: bytes, isLast: isLast) + if !processed.isEmpty { + output(processed) + } + } + + @inlinable + public mutating func update(withBytes bytes: ArraySlice, isLast: Bool = false) throws -> Array { + try self.update(withBytes: bytes, isLast: isLast) + } + + @inlinable + public mutating func update(withBytes bytes: Array, isLast: Bool = false) throws -> Array { + try self.update(withBytes: bytes.slice, isLast: isLast) + } + + @inlinable + public mutating func update(withBytes bytes: Array, isLast: Bool = false, output: (_ bytes: Array) -> Void) throws { + try self.update(withBytes: bytes.slice, isLast: isLast, output: output) + } + + /// Finish updates. This may apply padding. + /// - parameter bytes: Bytes to process + /// - returns: Processed data. + @inlinable + public mutating func finish(withBytes bytes: ArraySlice) throws -> Array { + try self.update(withBytes: bytes, isLast: true) + } + + @inlinable + public mutating func finish(withBytes bytes: Array) throws -> Array { + try self.finish(withBytes: bytes.slice) + } + + /// Finish updates. May add padding. + /// + /// - Returns: Processed data + /// - Throws: Error + @inlinable + public mutating func finish() throws -> Array { + try self.update(withBytes: [], isLast: true) + } + + /// Finish updates. This may apply padding. + /// - parameter bytes: Bytes to process + /// - parameter output: Resulting data + /// - returns: Processed data. + @inlinable + public mutating func finish(withBytes bytes: ArraySlice, output: (_ bytes: Array) -> Void) throws { + let processed = try update(withBytes: bytes, isLast: true) + if !processed.isEmpty { + output(processed) + } + } + + @inlinable + public mutating func finish(withBytes bytes: Array, output: (_ bytes: Array) -> Void) throws { + try self.finish(withBytes: bytes.slice, output: output) + } + + /// Finish updates. May add padding. + /// + /// - Parameter output: Processed data + /// - Throws: Error + @inlinable + public mutating func finish(output: (Array) -> Void) throws { + try self.finish(withBytes: [], output: output) + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Utils.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Utils.swift new file mode 100644 index 000000000..7afca0b4d --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/Utils.swift @@ -0,0 +1,117 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +@inlinable +func rotateLeft(_ value: UInt8, by: UInt8) -> UInt8 { + ((value << by) & 0xff) | (value >> (8 - by)) +} + +@inlinable +func rotateLeft(_ value: UInt16, by: UInt16) -> UInt16 { + ((value << by) & 0xffff) | (value >> (16 - by)) +} + +@inlinable +func rotateLeft(_ value: UInt32, by: UInt32) -> UInt32 { + ((value << by) & 0xffffffff) | (value >> (32 - by)) +} + +@inlinable +func rotateLeft(_ value: UInt64, by: UInt64) -> UInt64 { + (value << by) | (value >> (64 - by)) +} + +@inlinable +func rotateRight(_ value: UInt16, by: UInt16) -> UInt16 { + (value >> by) | (value << (16 - by)) +} + +@inlinable +func rotateRight(_ value: UInt32, by: UInt32) -> UInt32 { + (value >> by) | (value << (32 - by)) +} + +@inlinable +func rotateRight(_ value: UInt64, by: UInt64) -> UInt64 { + ((value >> by) | (value << (64 - by))) +} + +@inlinable +func reversed(_ uint8: UInt8) -> UInt8 { + var v = uint8 + v = (v & 0xf0) >> 4 | (v & 0x0f) << 4 + v = (v & 0xcc) >> 2 | (v & 0x33) << 2 + v = (v & 0xaa) >> 1 | (v & 0x55) << 1 + return v +} + +@inlinable +func reversed(_ uint32: UInt32) -> UInt32 { + var v = uint32 + v = ((v >> 1) & 0x55555555) | ((v & 0x55555555) << 1) + v = ((v >> 2) & 0x33333333) | ((v & 0x33333333) << 2) + v = ((v >> 4) & 0x0f0f0f0f) | ((v & 0x0f0f0f0f) << 4) + v = ((v >> 8) & 0x00ff00ff) | ((v & 0x00ff00ff) << 8) + v = ((v >> 16) & 0xffff) | ((v & 0xffff) << 16) + return v +} + +@inlinable +func xor(_ left: T, _ right: V) -> ArraySlice where T: RandomAccessCollection, V: RandomAccessCollection, T.Element == UInt8, T.Index == Int, V.Element == UInt8, V.Index == Int { + return xor(left, right).slice +} + +@inlinable +func xor(_ left: T, _ right: V) -> Array where T: RandomAccessCollection, V: RandomAccessCollection, T.Element == UInt8, T.Index == Int, V.Element == UInt8, V.Index == Int { + let length = Swift.min(left.count, right.count) + + let buf = UnsafeMutablePointer.allocate(capacity: length) + buf.initialize(repeating: 0, count: length) + defer { + buf.deinitialize(count: length) + buf.deallocate() + } + + // xor + for i in 0.., blockSize: Int, allowance: Int = 0) { + let msgLength = data.count + // Step 1. Append Padding Bits + // append one bit (UInt8 with one bit) to message + data.append(0x80) + + // Step 2. append "0" bit until message length in bits ≡ 448 (mod 512) + let max = blockSize - allowance // 448, 986 + if msgLength % blockSize < max { // 448 + data += Array(repeating: 0, count: max - 1 - (msgLength % blockSize)) + } else { + data += Array(repeating: 0, count: blockSize + max - 1 - (msgLength % blockSize)) + } +} diff --git a/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/ZeroPadding.swift b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/ZeroPadding.swift new file mode 100644 index 000000000..b1b67dd45 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/CryptoSwift/Sources/CryptoSwift/ZeroPadding.swift @@ -0,0 +1,40 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2021 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +/// All the bytes that are required to be padded are padded with zero. +/// Zero padding may not be reversible if the original file ends with one or more zero bytes. +struct ZeroPadding: PaddingProtocol { + init() { + } + + @inlinable + func add(to bytes: Array, blockSize: Int) -> Array { + let paddingCount = blockSize - (bytes.count % blockSize) + if paddingCount > 0 { + return bytes + Array(repeating: 0, count: paddingCount) + } + return bytes + } + + @inlinable + func remove(from bytes: Array, blockSize _: Int?) -> Array { + for (idx, value) in bytes.reversed().enumerated() { + if value != 0 { + return Array(bytes[0.. 5.2" + ], + "Starscream": [ + "~> 4.0.4" + ], + "CryptoSwift": [ + "~> 1.4.0" + ], + "secp256k1.c": [ + "~> 0.1" + ], + "PromiseKit": [ + "~> 6.15.3" + ] + }, + "swift_version": "5.0" +} diff --git a/Example/myWeb3Wallet/Pods/Manifest.lock b/Example/myWeb3Wallet/Pods/Manifest.lock new file mode 100644 index 000000000..5fd352276 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Manifest.lock @@ -0,0 +1,53 @@ +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/Pods/Pods.xcodeproj/project.pbxproj b/Example/myWeb3Wallet/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 000000000..d932bd39a --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,3443 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 55; + objects = { + +/* Begin PBXBuildFile section */ + 0064D372D96A53E5C7173A6DF531097B /* BlockEncryptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = EBD47F770D42CED6B265DC5BDAD568EC /* BlockEncryptor.swift */; }; + 00C22009B3BEB45AE5A45805DEDCC316 /* Words and Bits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C8F369ECC895BB94124AC2173EB80ED /* Words and Bits.swift */; }; + 00C9C2E54995B3BEA1C999016833A58B /* Starscream-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 5773F22FF0BADB57519B5A58AC0A3246 /* Starscream-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 01E6F9B981C5D8D89F1FD6AB0BC859B9 /* Encodable+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30F6DD109D1E925101993EF13CC1B6DD /* Encodable+Extensions.swift */; }; + 02015E32C1E060B9432843635FAAD128 /* ISO78164Padding.swift in Sources */ = {isa = PBXBuildFile; fileRef = F16994E06B05BA83DEC77EB28F001644 /* ISO78164Padding.swift */; }; + 02EB7AB3F167348018915AA1D80B7A3C /* Bridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = FACA054A990CABAF7B4E5BDC81A86B97 /* Bridge.swift */; }; + 03804F779AD26607550ABB2C65DA16F3 /* util.h in Headers */ = {isa = PBXBuildFile; fileRef = 12CFBD6C81A2CE71BA2C4F590B5D5927 /* util.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 046AC7AA224C78A31C0A8FACB11D2D28 /* StringHTTPHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = E76D73543A413D250E98C170B65439FE /* StringHTTPHandler.swift */; }; + 04CFB084C47424C66DEA6F2EF4245180 /* scalar_4x64_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = CDC065C0E64F5101BC23C8AC17738F7E /* scalar_4x64_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 05C452094C81519037F382ACFD15493D /* AbstractKeystore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0050F742D824A11AEB8424E0DD2C63DE /* AbstractKeystore.swift */; }; + 05C6B1FE4CFF7D189F0250C3777A30F0 /* Promise+Web3+Eth+GetBlockNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = C05291B76391595ED8B3B285B79F78EC /* Promise+Web3+Eth+GetBlockNumber.swift */; }; + 071F45A06E37AE61A8E282DBE683C72A /* NativeTypesEncoding+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 581816AC6AB72D6754E7F5AA6BEEEBDE /* NativeTypesEncoding+Extensions.swift */; }; + 0933E9216A313795C94BEC005FD9DDE1 /* Operators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0D72EEA6CB2ED51D9CD581441D934A96 /* Operators.swift */; }; + 09D23FBC23D8C4443D11C3837C9AA33A /* BIP32HDNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6B57FF8149DACE439778C727600D5548 /* BIP32HDNode.swift */; }; + 0AF42FC09546096529FCE1002124E5B8 /* Array+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C474592AE45D1B74EC342FF072BA03E /* Array+Extension.swift */; }; + 0BBE8EF207B633F9DEEB7A6CE93B7DA2 /* Poly1305.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C662BE19BE125813C43B2C2F34A06A4 /* Poly1305.swift */; }; + 0C3B8A0993483F89626BBCF38A90F62A /* scalar_8x32.h in Headers */ = {isa = PBXBuildFile; fileRef = EA8D86F1746BB6B64518FC1D508E67F4 /* scalar_8x32.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 0F3F5EDC823447A95939F6C52D45E342 /* Web3+Instance.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5F4F7EFAF476543587E0F3608C9CA8B /* Web3+Instance.swift */; }; + 0F673A9D29EC5B75BD8DC0B796040F2D /* Web3+Eventloop.swift in Sources */ = {isa = PBXBuildFile; fileRef = C19976C618B5991508555766A6C58D33 /* Web3+Eventloop.swift */; }; + 11090FE18EB7578CE49394EBB95A661A /* field_5x52_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 7239B0649BFDF00625943FEDFAD57C9B /* field_5x52_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 111FC0F6882063120869EF91908DF16F /* UIView+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 28AEFC12990DE5857B6C8C3DD151EE7F /* UIView+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1152E8C62683CC15F069961C6E5FDA7A /* Web3+ERC1410.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4D2746F0470DC43876ADAF60BDEF00E /* Web3+ERC1410.swift */; }; + 1189311320B549605D358D44697761C7 /* EthereumAddress.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7E95C968FFABFDA532F2638C4F909A4 /* EthereumAddress.swift */; }; + 11EA2C9D241AB9B6E1EE8B5E1B9DA27F /* HKDF.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E0AD3992F79794304FDD80D8F1AF7D5 /* HKDF.swift */; }; + 1206729EEB0C6684BCCB2F23EAA222D1 /* scalar_low_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = BF02184566636520F4D8470933669F05 /* scalar_low_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 1525B8EE9316C18DEB58EEA8A75664D2 /* num.h in Headers */ = {isa = PBXBuildFile; fileRef = C560E0C20A6F6E769700B4AB346EEBDC /* num.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 15EDD300B82F48DAB59A670647F30518 /* ABIDecoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2456150E4EBA655122DFE457A3B16411 /* ABIDecoding.swift */; }; + 1769CFA2DB5E0CF635CAFDAF134CFFD0 /* ZeroPadding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CC9E23320B8991F34BC31A01FB21A1C /* ZeroPadding.swift */; }; + 17C20D68963C252E9991CD7361723892 /* Codable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C1F8F8C962B269D1B535A7E69211345 /* Codable.swift */; }; + 1895D0230B557364AF8E4225FB4C4ABB /* Array+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33D9C3E44151CA8DAEC4B95DEEE84E07 /* Array+Extension.swift */; }; + 199B4DEFE236E08AA698E8283BA44F8E /* UIViewController+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = EE4EAD1D53584CBDC586BA9499EE0D68 /* UIViewController+AnyPromise.m */; }; + 199B84AB82B3544540CFC8CD3C755B82 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5C9BF60EE9C79C985DCC648B95156DC4 /* Foundation.framework */; }; + 1ADC5BA227C82B9DDF4DE68343EFC40D /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 67DE942FB3DAA92CE782989AF2C19632 /* UIKit.framework */; }; + 1C69EAC3F56DA086FD3A08EA63ADF06F /* BatchedCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFBAD5703C2622CB9475778D3FF7684B /* BatchedCollection.swift */; }; + 1D691C9D33B859BCF205B302404CF87E /* Collection+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4EA0D117684CE8DF071445A5482A3E60 /* Collection+Extension.swift */; }; + 1DF180C51265159F9619D1C5EF26316D /* Web3+EventParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DA6D1A7D4E05E1D0AD507800C434815 /* Web3+EventParser.swift */; }; + 1FB5D15B825E0D9A6123C2BA2E710A3E /* IBAN.swift in Sources */ = {isa = PBXBuildFile; fileRef = B913B0C1A0F49DC0B7ADA73EC64F3E7B /* IBAN.swift */; }; + 2084D75E97F44D8DAE091C7739B06E01 /* CBC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 55A821C8C1FC6F68C023E2E81651B18B /* CBC.swift */; }; + 20B46048A49C3DD9704C96BCA4565A64 /* Checksum.swift in Sources */ = {isa = PBXBuildFile; fileRef = 173FD7EFF45980B448F92A8F6A1CE154 /* Checksum.swift */; }; + 23258679FEADA6931877999C19B8D386 /* Promise+Web3+Eth+GetTransactionDetails.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2969A6F4F3AB1FF9852CF5B8BBFF0981 /* Promise+Web3+Eth+GetTransactionDetails.swift */; }; + 235DC2A2B0A33F450025E3A48D4E0EE7 /* Web3+BrowserFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD267E54D7018E6BD14F7FF243347A4F /* Web3+BrowserFunctions.swift */; }; + 236A65DB9D500C79D40C220C70377A89 /* EIP681.swift in Sources */ = {isa = PBXBuildFile; fileRef = BAD73345F8FD30B964FB9152047D4B8C /* EIP681.swift */; }; + 23845E588BE52974DCE35EA857812D17 /* Cryptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = C190B059191445A1D285D4CE9ABFCC0A /* Cryptor.swift */; }; + 2402753327A88FCFBBA79809A123F324 /* CCM.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10B43E5A8E435E74A39AC5722CC5A271 /* CCM.swift */; }; + 24C10118785187B6AAA9A679CBE8E545 /* race.m in Sources */ = {isa = PBXBuildFile; fileRef = AE35160BC5311A2CFE1E6257480BF4D1 /* race.m */; }; + 250A73D3EDFC531315F6574D341A8B8D /* num_gmp.h in Headers */ = {isa = PBXBuildFile; fileRef = 6185835291CFC5AA4425DEBC5841A13C /* num_gmp.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 25EAD62FC5B8B10618A50D8710CA6FFF /* ecmult_gen.h in Headers */ = {isa = PBXBuildFile; fileRef = 02604971270B936C3550FF9F7FAE7132 /* ecmult_gen.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 2698FAD459869510BE11DCE9C1AA4D92 /* Promise+Web3+Eth+GetTransactionCount.swift in Sources */ = {isa = PBXBuildFile; fileRef = A24FCB02E998E133E5325631033AF027 /* Promise+Web3+Eth+GetTransactionCount.swift */; }; + 2705DCE2E76CF7C762E862A4DE090602 /* Promise+Web3+Contract+GetIndexedEvents.swift in Sources */ = {isa = PBXBuildFile; fileRef = F34633B7A646EC054D00CF51B9CFEDAF /* Promise+Web3+Contract+GetIndexedEvents.swift */; }; + 273196B0B3608A30286680B9C02EEAF5 /* NSObject+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36EB9FBA8F61ABE90D34ACAAE90DE61A /* NSObject+Promise.swift */; }; + 27CBC2848BD67A27962F94ADFB6EE9F1 /* AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 442EC95B2C112C5C782CE9612DE57E07 /* AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 29678514660C9E368CA5CD6BDD64492C /* RLP.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0E7FE0B9D0DF6B91966F07D6D2282738 /* RLP.swift */; }; + 29EB7FC5FCB017B10C7A56EEC67B6C87 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 694009935F1F74664D4B4E938B5F1490 /* Utils.swift */; }; + 29EBEF45DCEC1D6568413032FA8FB2DB /* BlockCipher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2DDB8CD09F1100772FC894971E35ECF6 /* BlockCipher.swift */; }; + 2BE32B9D65CE57739A7E27AB57E38A4F /* RIPEMD160+StackOveflow.swift in Sources */ = {isa = PBXBuildFile; fileRef = B2D684B79FC7FFF779E5AF645F1E8129 /* RIPEMD160+StackOveflow.swift */; }; + 2DB4D0E8314E75FF3989BE61CB9EBD9C /* KeystoreParams.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4DCC4A6DDDF04697E091B17F02A5660E /* KeystoreParams.swift */; }; + 2E62C0CDB26CE9A152EA03ED4DD226C0 /* Data+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9CDA08FC40E440445F5B1C2087699FA4 /* Data+Extension.swift */; }; + 2E88A7E1C99C8976E83D584B459DBD91 /* Promise+Web3+Eth+GetGasPrice.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9DBB832EE6B1A46B6B06C03F1FB46839 /* Promise+Web3+Eth+GetGasPrice.swift */; }; + 2EF5C6A10700B5ACBD45F9D0461389A5 /* OFB.swift in Sources */ = {isa = PBXBuildFile; fileRef = BCEEABD2FC5B664CD01F65462355E766 /* OFB.swift */; }; + 2F460F00F9A33B5ED6C40151ECD9BEAA /* BIP39.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00C245DA669E6E0BBAFA3115D6823007 /* BIP39.swift */; }; + 2FCC2C2EE5BA2372F3CCF70DAA028085 /* PKCS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC4CF0C81A7F4E6F47BFB9B293C8B441 /* PKCS5.swift */; }; + 30EC1D1D6D674E8A411967FB331A1F1B /* field_5x52_int128_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 4B6B955D7B2A183ACD0B6B950B5C893B /* field_5x52_int128_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 3146A3C48334D88815AA965667D730E9 /* field_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 499E0FE2E6CAD14D5EA32EE544804F2C /* field_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 316108AAD17DFF1BF756D47548EBB77D /* ENSBaseRegistrar.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA8F1F5587506D634EFF2229CAE76FE8 /* ENSBaseRegistrar.swift */; }; + 32DF053AF55490DBBCC8F5A4135E7A48 /* CryptoSwift-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F95A6F75823EC4EF200AAEC1DCF80F46 /* CryptoSwift-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 334D28B6349CDD6C4851C6ED56DFF411 /* Rabbit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B876EF576BCF48712B2FE0B58425831 /* Rabbit.swift */; }; + 33C71989B6C635864EC5E4862AFAAE8A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5C9BF60EE9C79C985DCC648B95156DC4 /* Foundation.framework */; }; + 342027080905184D5B5D28DCA694FD70 /* Web3+ERC1643.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3402BA34F808F411E48E41CD59F05FCE /* Web3+ERC1643.swift */; }; + 353721D2B910AE4F9B8196D7277242ED /* Data+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 752098116910D32A020C6FA1EB9F38AA /* Data+Extension.swift */; }; + 356CD819C1A9BB628BF2E2069D60E9E3 /* PromiseKit.h in Headers */ = {isa = PBXBuildFile; fileRef = 75ED9FE60BF10CD99C97EABEB33FF1CF /* PromiseKit.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 35D72B56E9BC4ACB7F5BE95D51CB99DB /* web3swift-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 65E6BD3495BF0509B852B4FD92DF2989 /* web3swift-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 35DE8211AD1CC534C07D3F4C19554DAE /* secp256k1-config.h in Headers */ = {isa = PBXBuildFile; fileRef = AF96BD26A8980F3C83466AD777577DB3 /* secp256k1-config.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 36740BCB909B105FD0A557ED6B765FD7 /* CryptoExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 52B4F7541C12ABF10C884449E0032938 /* CryptoExtensions.swift */; }; + 3677C4124E6F08101341038E13D12D6A /* Pods-myWeb3WalletTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 48ECBEC5D1CFAE5AD46BEFF89E4ACC60 /* Pods-myWeb3WalletTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 36CFCB8A8BE261FBAC0B909211F757F9 /* hash_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 10F4B4430DB29EA7B5DF0FF1637E5B75 /* hash_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 37107A9CADEE7783B6E9F32D2005B90B /* Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 414DA9E2B626DAD1AB851A395D42E446 /* Promise.swift */; }; + 37DDF94A9347F39C3890C375B13CAB97 /* Promise+Batching.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7509ED605AC6A0930966F33117BB9895 /* Promise+Batching.swift */; }; + 381D42ECF079E81454D3418F6DCC3B0B /* String Conversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 407155CEAA8C92477629A14B47475F1D /* String Conversion.swift */; }; + 386CB0388B7BFA54D25DEAD77795EE6A /* Process+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54F51094F339B9E2A49C1D43EFBDB098 /* Process+Promise.swift */; }; + 38F306041876680482840B39633C0994 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5C9BF60EE9C79C985DCC648B95156DC4 /* Foundation.framework */; }; + 38F5A67EF31AD4A7571F62E24C92DFB8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5C9BF60EE9C79C985DCC648B95156DC4 /* Foundation.framework */; }; + 3903D867E1B04DF17B5ACB08E4D496F5 /* PBKDF1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8552720D720D203E2444F5263C6A4021 /* PBKDF1.swift */; }; + 39480C33D789611BB90F3B3C12712A8C /* when.m in Sources */ = {isa = PBXBuildFile; fileRef = 98E59BC358BEF788BF007F56FA3381D1 /* when.m */; }; + 3A655D6817E99F062266BB601B0EEEDF /* Starscream-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = D50122651622201633327B4D22B90560 /* Starscream-dummy.m */; }; + 3BF80B98213E4900761B8E9C6FD57947 /* ISO10126Padding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79BCFCB28731207C5F021A408D5A1EEC /* ISO10126Padding.swift */; }; + 3C9B4A7F40A52FF015F77982686268B4 /* dispatch_promise.m in Sources */ = {isa = PBXBuildFile; fileRef = 3D6311A0CAB052B65B5FC50B1A76C0C8 /* dispatch_promise.m */; }; + 3CE0032C005BB386FA1298F7DBE3B367 /* Web3+ERC20.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B00321B0B14B4FF897F2CF5B6415C3C /* Web3+ERC20.swift */; }; + 3D62BBA23B2EA2EE05F1F669B0490009 /* Web3+ERC1644.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6CAA05940EADD5E5A01859B5B9BA567F /* Web3+ERC1644.swift */; }; + 3D689F2BA6C364CDE2ADDEF739BCCDB3 /* BloomFilter.swift in Sources */ = {isa = PBXBuildFile; fileRef = D444BC3C307070B4F5F3F480423838AD /* BloomFilter.swift */; }; + 3F13BADB5C20FB262EE3775E63BBE651 /* Box.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F202231EF82E4F2909CFEDE889D0C7A /* Box.swift */; }; + 3F3E9C6FF4BCB6F4FF18D9121CC3E42F /* WebSocketServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 38E0F1A25A1345D8458B0FA85EF949FD /* WebSocketServer.swift */; }; + 403F7C30995445B23F464E67189CCA5A /* Promise+Web3+Eth+GetTransactionReceipt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 98DDDE228F4BC29D191AE78AD7AD59C6 /* Promise+Web3+Eth+GetTransactionReceipt.swift */; }; + 404352DB694F722F24156E60DAAEF79E /* TransactionSigner.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9D6042684BC5248A7F2102E84D57D44 /* TransactionSigner.swift */; }; + 408E22C229EAAA6DD10DF76E76D43D5C /* ABIParameterTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B5918B5A16C03780E709CF2CDD1104C /* ABIParameterTypes.swift */; }; + 40A09F5E948345A60B856BB7C3BB5FE3 /* Subtraction.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9BED5D4428FA6E60B2D58D86DACD87E /* Subtraction.swift */; }; + 42A7EF29E4ED3462980668F7D1A314F0 /* NSNotificationCenter+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = E06008D189FECE45B3935D3DF48E676A /* NSNotificationCenter+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 433BD28C8C82DD91ECF97ACF42737303 /* PlainKeystore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0C4C834F49C3454D3ED6140F8761E5EE /* PlainKeystore.swift */; }; + 4356CD1634561030CB85A67D18712860 /* Promise+Web3+Personal+CreateAccount.swift in Sources */ = {isa = PBXBuildFile; fileRef = 513ACAB2D90C7668D5C441E7F44CD9F1 /* Promise+Web3+Personal+CreateAccount.swift */; }; + 44A337C99C192862AC3E83D633178550 /* Generics.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6380C10D44B994D4547641ADFCA08B5 /* Generics.swift */; }; + 44FBA29463E2DB758F97EF275BAD82F2 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5C9BF60EE9C79C985DCC648B95156DC4 /* Foundation.framework */; }; + 455293CB3237E60314F28FC940E2E19E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5C9BF60EE9C79C985DCC648B95156DC4 /* Foundation.framework */; }; + 45670E07AAFDE8877911FA0FA180E8C8 /* AEADChaCha20Poly1305.swift in Sources */ = {isa = PBXBuildFile; fileRef = 408F64023EB56273BB42761F929B897B /* AEADChaCha20Poly1305.swift */; }; + 46C113C932265323297D3C3145C5E638 /* field_5x52_asm_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = D0FF9C21D8BBE37AEAA3240D6DBB2CA2 /* field_5x52_asm_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 4764DB91CAEF26CA6EED99CB71389637 /* AES+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0AC66155707B85F45580BC854DAA5E8C /* AES+Foundation.swift */; }; + 4788461CD9B764A0C5E1E8A7E7304C6D /* BlockModeOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF16FB6DF72A1700811D95947F7D6278 /* BlockModeOptions.swift */; }; + 483EB89DCAC11F3DE7417CB7C1347B30 /* after.swift in Sources */ = {isa = PBXBuildFile; fileRef = AAA635D78BC74313670E92DFD4464F7F /* after.swift */; }; + 489EF4A7D4992C47CF590AEF9AA418FC /* FoundationTransport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4B5D14DD6AF865E5CDA4F6D296D7766C /* FoundationTransport.swift */; }; + 48AA519849266C20CF080A37887CFC4E /* PromiseKit-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = D77426DA53B5BAC9390B9F12C1142183 /* PromiseKit-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4A2FBA2940ED4665F72CD57ECB29D7C3 /* Pods-myWeb3Wallet-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 14105AEFAD47B97BBFD0A972AA98DF35 /* Pods-myWeb3Wallet-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4A3B1BE129FDA231AC217E1C6DB2B8C8 /* Transport.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD85842A42223204E3C0C2184192C905 /* Transport.swift */; }; + 4A649680EC213DCD0700A1A284EB25D5 /* LogEvent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F3F31CC12709B9BCB4DC9A0AB32FCC3 /* LogEvent.swift */; }; + 4AB6FCF35B998F60ED9EB100542EEA31 /* FoundationHTTPHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F1ACC0AA6AEE873BA635D09E510F5F1 /* FoundationHTTPHandler.swift */; }; + 4D2EED25A8F8E2CAFF4EA51EAF389911 /* Web3+InfuraProviders.swift in Sources */ = {isa = PBXBuildFile; fileRef = 98821C698CAE291DB7FC2E6A72ECB7D4 /* Web3+InfuraProviders.swift */; }; + 4E6D61DF8A85976F8076223E5E0801BF /* ABIEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3339301FC43964D4764CDC289EBDD39E /* ABIEncoding.swift */; }; + 4FE2DECEC9EEB3F66A00D2644ED4D109 /* EthereumKeystoreV3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1659BBB217FF5D75D1A83A1CCB87541C /* EthereumKeystoreV3.swift */; }; + 5006DD4B60A05AF56EA0706A680BABF6 /* FoundationHTTPServerHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9AA32BC8F1750426BE685F2689370B7 /* FoundationHTTPServerHandler.swift */; }; + 506CB45161F5B9A01351C0AD278C4AC0 /* NSTask+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 97603D675B6C3596041F441A64D65A89 /* NSTask+AnyPromise.m */; }; + 51331CE2712BD9887D38954D56431D43 /* Web3+ST20.swift in Sources */ = {isa = PBXBuildFile; fileRef = 771143AE964D2F3B727D81EADA6425C6 /* Web3+ST20.swift */; }; + 515AA56FAACC390CF7CD1454FA0B31B3 /* num_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = DF6FE3C89D52B8B8E8AD67EC8CD632F4 /* num_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 51BE8B11021A003A1BD4BF7F36262A50 /* Web3+ERC1155.swift in Sources */ = {isa = PBXBuildFile; fileRef = CDDD26AA5A7B20DAE7F39D14BDC4C092 /* Web3+ERC1155.swift */; }; + 5281197FE8CC6E6954315F11B8F553D0 /* FoundationSecurity.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0A6F2A78FDE414D85D2A8DC74021C1B /* FoundationSecurity.swift */; }; + 52920F9B47B44052ACA15A9ACD9B3FFE /* Web3+ERC165.swift in Sources */ = {isa = PBXBuildFile; fileRef = 492109BF7BF2C0FF599C257507DF3FF0 /* Web3+ERC165.swift */; }; + 53042D9D194CD8BE861A5DD3781EF261 /* BlockDecryptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD4F76F68EB476ECF93172F941394A64 /* BlockDecryptor.swift */; }; + 5376E6AC063434D54E81D9C74D63339F /* String+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = BCC3DC989D5E95AE5DFB7CEF5F4A6825 /* String+Extension.swift */; }; + 53BF0FE77A91BC99F2CBA559D91F105F /* PBKDF2.swift in Sources */ = {isa = PBXBuildFile; fileRef = F98CC07D9AD78B8CDF70154F9443A978 /* PBKDF2.swift */; }; + 53D3204D6826AF6FA93D8D2D6BF672E8 /* Web3+Structures.swift in Sources */ = {isa = PBXBuildFile; fileRef = 196F8D0679C136F9CB5DEDA32CE39FA4 /* Web3+Structures.swift */; }; + 540CC89836D830624883860F4AD3EAB0 /* Floating Point Conversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7C21A8D4CE9BE9389B1B027A7F1684A /* Floating Point Conversion.swift */; }; + 542C9E8C1561679C2B9596C7653D375E /* SHA2.swift in Sources */ = {isa = PBXBuildFile; fileRef = C10E9CF99CBE40D30321A9990E3780F3 /* SHA2.swift */; }; + 55018C7112A943BE15FB9735839CB8AE /* Int+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = A6224520D335600BCB2E7747D6687B8A /* Int+Extension.swift */; }; + 55D3C00883F2CA52FE8F11468E97CB50 /* Division.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2AEB64E397C62A9D958096179BE64189 /* Division.swift */; }; + 55F3D8488C5D52A1CE1E7278815FFB6A /* Web3+ERC1594.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2E188E17AF245DF4E409CBCCAA53A13 /* Web3+ERC1594.swift */; }; + 56706731EFD3AF6092CDAF8359B039B8 /* CipherModeWorker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1786CFA34F2534AD545031FF7EBA4538 /* CipherModeWorker.swift */; }; + 59AD3E0E5518053D78B7059A0D9333A6 /* ABI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61D906C63EE673FDF08E44B02D695E83 /* ABI.swift */; }; + 5BCFACCBC191DBB0BBBC20E1CA669EBF /* Promise+Web3+Eth+SendRawTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6016EF1F606FED15790DC99D24384C6E /* Promise+Web3+Eth+SendRawTransaction.swift */; }; + 5C51E4EF06F496800E089CB1EE79DAD2 /* PromiseKit-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = B87DE6711B6E12078EA7C872582DA976 /* PromiseKit-dummy.m */; }; + 5CF32D784CCDEF1DE36C794BEB15381C /* group_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = D7459ACC386268D5B3B45D2F4EB04631 /* group_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 5D924D51FD5DB39A62A16D0A476D81E2 /* DigestType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5D37615679E9A1E496ED4D603AEE02C3 /* DigestType.swift */; }; + 5E25E52634BBF945012D22B59F98F00B /* scalar_4x64.h in Headers */ = {isa = PBXBuildFile; fileRef = 047C81A9AD59EDA23DBD28F67EA44F3D /* scalar_4x64.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 5EEB85730244814F4A58FC258568C9D4 /* String+FoundationExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = C158F576B708193B339431561C565F0A /* String+FoundationExtension.swift */; }; + 61AFA71D5ECCF93F2B7F2E177E6C4DA6 /* SHA3.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA1FF168A47F7A82F2DFBA4040E00A10 /* SHA3.swift */; }; + 61FD8163938789077FD24D6DBF71267D /* ecmult.h in Headers */ = {isa = PBXBuildFile; fileRef = 138407359512A2D920EEDD6C7AEDDF81 /* ecmult.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 62FC151E3A49F866DD74CBDE849D27F8 /* Web3+ERC721x.swift in Sources */ = {isa = PBXBuildFile; fileRef = 605DCE9468F1ECAB3DE8DB3907D53C1D /* Web3+ERC721x.swift */; }; + 631654C419F62FE0270E1DF79CCF6F8B /* Data+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 94D92C0E313BED051BC11C45A95CCFFF /* Data+Extensions.swift */; }; + 63B2F0E7E22199EE517A3F49AA875795 /* field_10x26.h in Headers */ = {isa = PBXBuildFile; fileRef = 812A3FAA807BBF520E834E8177CDA805 /* field_10x26.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 6400D521667A6DE758C821E3ED5B2694 /* HMAC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C143EFCB8668F769B0C2692D4D882B4 /* HMAC.swift */; }; + 64115A6A941ABF1FC52D487A931F89C0 /* Promise+Web3+Eth+Call.swift in Sources */ = {isa = PBXBuildFile; fileRef = B373FED6638B961B7A97AABD5280E615 /* Promise+Web3+Eth+Call.swift */; }; + 654E6F39AD57C689A52E12BB51DDD88C /* Web3+MutatingTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 699F27F269D20FAD83C7D3B79A5C5074 /* Web3+MutatingTransaction.swift */; }; + 656274DD559533E013F7A7507EA5D8D3 /* Base58.swift in Sources */ = {isa = PBXBuildFile; fileRef = 665EC9936D9FB294CDFDD2B00D996F69 /* Base58.swift */; }; + 665964C5782D23DD55BD1D2B807E4740 /* SecureBytes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3617B0E86D0A093AA4BC7F0006FD0413 /* SecureBytes.swift */; }; + 66645A63BDFEE73F49F5CB02A5651857 /* ABIElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4F1BDCD30EFA57E3CA28CD4CF2D7CCF /* ABIElements.swift */; }; + 669DEC50D4E1FE534D887EABA096B324 /* Promise+Web3+Eth+GetBlockByNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1CBAF4C9C1F1D95FC1A9EE6D61DF7BB /* Promise+Web3+Eth+GetBlockByNumber.swift */; }; + 6722DCA670229327597ADC3D81BB492B /* BigInt-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 69C28A10F48C7D37E1E65B1E626C6782 /* BigInt-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6734003FBEA6A85E5E906CB2C0FF303B /* Web3+ERC1376.swift in Sources */ = {isa = PBXBuildFile; fileRef = ACF496E6C59563E3B2D37AFF0647AA5E /* Web3+ERC1376.swift */; }; + 67ABC00CE97CC79EAB5277F6E007D78A /* EventFiltering.swift in Sources */ = {isa = PBXBuildFile; fileRef = A546A1EBF9CE4405F7461B4753D53B47 /* EventFiltering.swift */; }; + 67DC631DEB505ECF30C138922C25067F /* scalar_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 35BAB9DEB6B862BBA80319A779593939 /* scalar_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 6803A39AC3E9B559343724A39AE87122 /* ecmult_const_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = F7C0A6F898A3FC267475D1DAA9F64305 /* ecmult_const_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 69A591F2BDE4941B391C102F4C26B115 /* Security.swift in Sources */ = {isa = PBXBuildFile; fileRef = 21DA00ACD8F03D5A27C632034D5215B3 /* Security.swift */; }; + 6A644E230F20B1B3F66C24820E6CE1F5 /* EthereumFilterEncodingExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F95702E2ECA0FE6E67FCF95250B5373 /* EthereumFilterEncodingExtensions.swift */; }; + 6A6D768A74F8BFBABED2364907A2DF0C /* BigUInt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8907A4B63AEF5B00260E490E38ACCE3E /* BigUInt.swift */; }; + 6BEBB9F7819614C8DBB686D19050CA7A /* UInt32+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 686CF63072B25624DF5326A314DB59DB /* UInt32+Extension.swift */; }; + 6C0DACBE00A34619DEDB9A65CB959BA5 /* TCPTransport.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD500378BD304B7A5348A9CB1F342D3B /* TCPTransport.swift */; }; + 6CCA055AE1F2015447DE2CD4AC0980AE /* HMAC+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 94EDD79DD8C072828820F9310A7F25AB /* HMAC+Foundation.swift */; }; + 6D581D7F06643EF7F7BDFE0220D642F9 /* CoreImage.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C51800E5F54721AF0D7AEE62A916CB2F /* CoreImage.framework */; }; + 6D96B4C120F0167A273818693354AA17 /* Web3+Options.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4861BBBBB34E78E9429D35409F2D1E5F /* Web3+Options.swift */; }; + 6EFD6CAA2430FCC24D44C8F00BBBCFF5 /* StreamEncryptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1F3A004CC4748F6083D6F5E3CCAAAB6 /* StreamEncryptor.swift */; }; + 6F3BEBAC10EAF8A5905743446825E679 /* NSTask+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 0349201509342BC7491FA1ED83CDE2F7 /* NSTask+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6FD99909460DF1443891CAD15B044F57 /* EthereumContract.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5064BE1943B37DFB8BD781A4F88B7360 /* EthereumContract.swift */; }; + 7090F68043DADD044880B9A4DDB571E7 /* BigInt-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = DE2C000707EBAC73CB8E4D1AC182433D /* BigInt-dummy.m */; }; + 714C406971A7F2B5ABF94E4205D2BADC /* NSRegularExpressionExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1610DC37FC079B6D1D83472DBA4DA12 /* NSRegularExpressionExtension.swift */; }; + 72C2B622F9A4E6A107CFFF3702FA1CF8 /* Web3+ERC1400.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09783897421F576EDE46857412E8265C /* Web3+ERC1400.swift */; }; + 732B28B03918D36B68BD44C77D4BE887 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE044572A30D307268519834DCA2D378 /* Error.swift */; }; + 73E1178AD16F91C80A718FB778F3534A /* Strideable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 586F3C5571C6E148E0D1950D6CBF1949 /* Strideable.swift */; }; + 73E5BA7EB3657E29A685099252150C87 /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78FCD380A8DC8B60B8940546BA368A71 /* Extensions.swift */; }; + 73FD1A5FE33F66C7A009C6EDB22D9FEB /* num_gmp_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 861A826AE843EA63A9502FDE98A45BB7 /* num_gmp_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 740428CF593D2EFC7C536FB684255CD1 /* Cryptors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 11657185FCE37F7674E70752DFF319F7 /* Cryptors.swift */; }; + 75CD48978521FCCA27757CBB4C9B6545 /* Dictionary+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0C706E0E7E64CC2DDFF946B173F6E937 /* Dictionary+Extension.swift */; }; + 75D390E13DBF964D209460FE9823C8A8 /* CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A02DDEC9858A78BEA9C9EAED811BC17 /* CompactMap.swift */; }; + 761FF2D686D4CDDFEB9228CC18C2C8A7 /* secp256k1_main.h in Headers */ = {isa = PBXBuildFile; fileRef = 80E520F4DA45AF0A1A997471995473E8 /* secp256k1_main.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 770635827551A8B7C42C7BC958A55138 /* MD5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED783EBC23A40B546A9CE880D97D376 /* MD5.swift */; }; + 77651F160816E699EC490DD9D3F9BE02 /* Shifts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79E64ADA63C8893846700495EA1FC27C /* Shifts.swift */; }; + 777E977F2C1ED28B2CBFC455C41243B3 /* SHA1.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4805A323ED852FBABCD0E37CF9864E7 /* SHA1.swift */; }; + 77B82372C309D4425D9DD35D2E8DA711 /* Promise+Web3+Eth+EstimateGas.swift in Sources */ = {isa = PBXBuildFile; fileRef = D78518CF508AF000188545E3388F00CC /* Promise+Web3+Eth+EstimateGas.swift */; }; + 7A4790EFF61624332A869DB5B4632948 /* ContractProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = FBDDE8545CBE1DD3E62A0FAACA1566C7 /* ContractProtocol.swift */; }; + 7AD846FD5AA7B41459E986CB1F8892AB /* browser.min.js in Resources */ = {isa = PBXBuildFile; fileRef = B3B83F5426FCB99B70C9BA58611231F2 /* browser.min.js */; }; + 7BA954F43FEC18BC48D0B6645C0DB9AF /* secp256k1.c-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = AA032FABD784E8D9C3094CCA56F9FAAE /* secp256k1.c-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7C40298985F6A3FD96484E34B683A197 /* Web3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4FA623E4738AB357087E678F3C2B8B80 /* Web3.swift */; }; + 7C6E7A96CFFB53597A42061B79927BA0 /* Web3+HttpProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = D52E15043DB745FE9026A43E0E10B902 /* Web3+HttpProvider.swift */; }; + 7DDEA2F73F2A02D88D5164B46BA2C7E8 /* HTTPHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8AA0DDDD58D43515BE066493834EE7F7 /* HTTPHandler.swift */; }; + 7E55502F0987E7318FF739C9DDAC7387 /* GCM.swift in Sources */ = {isa = PBXBuildFile; fileRef = 141B6AEB28CFF06BE48234968D5F6490 /* GCM.swift */; }; + 7F279180DF50A0D4CD17049A0D96F251 /* secp256k1_ec_mult_static_context.h in Headers */ = {isa = PBXBuildFile; fileRef = 629BF4D4B84DA533D5B163D4E919D015 /* secp256k1_ec_mult_static_context.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 7F4EC5B61AB392C6B9F3A6D34CE21E1E /* when.swift in Sources */ = {isa = PBXBuildFile; fileRef = D81298FD65A20CC32C6FCEA447C6F8B3 /* when.swift */; }; + 7FD4224D8A662AAE276FF6805C6C000F /* Promise+Web3+TxPool.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0A930E640D89DFE4D0E110591FB7076 /* Promise+Web3+TxPool.swift */; }; + 804059882A1C76A538EAED6E464A7DCE /* ECB.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17AAAF47166CDEF7CB91711009CC9DB3 /* ECB.swift */; }; + 817DC6B99063211DC0E1B9C2740882F1 /* ecmult_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 8D144717D9392F89398A95CE943E7FCD /* ecmult_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 8194B9F767F5E98AC6290833A2CFD773 /* race.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7BC8ACC3ACEA679C2AAC22532DEBE18F /* race.swift */; }; + 81DEE0975FD2488D5C61D099F17DC3FA /* BigInt.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA2CE9B55293B0E2D65F19AB1EC631B0 /* BigInt.swift */; }; + 81F5F30E31C813D81A5817F7E7E365A6 /* eckey_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 2CA6A6221D6CA8057D71BA60A8DAF0EF /* eckey_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 836A1A276D6FDED27563FD5AEE92CE74 /* Web3+SecurityToken.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB758BE37B19325C036A0DBACBEA6C27 /* Web3+SecurityToken.swift */; }; + 83EA6B046238B37ED950FC865BB09333 /* hang.swift in Sources */ = {isa = PBXBuildFile; fileRef = E03C16A97E869AFA5CD8C861D0F30A3E /* hang.swift */; }; + 8409D5F7623FD7CBC3D928CA463A69E1 /* UIViewPropertyAnimator+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18E0CD9ADEB45DAE398F37822641499A /* UIViewPropertyAnimator+Promise.swift */; }; + 84F7E0BA0554DF5310C76651797593AF /* wk.bridge.min.js in Resources */ = {isa = PBXBuildFile; fileRef = 2D1CFEA76FE44A2E6511787F74D0794C /* wk.bridge.min.js */; }; + 8581F08BC311452D4C2E78935C50A840 /* NSURLSession+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = E77EA545335C3D935F993E0EC64F9B1D /* NSURLSession+Promise.swift */; }; + 86954D3235BD19D7B94330AC9CA0D5AB /* Web3+ReadingTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61329F3723A6B1ABEF3BBCD12675C0C1 /* Web3+ReadingTransaction.swift */; }; + 86AC32BC3900B807699D31D22C06A16C /* Web3+Personal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D7BC9EE36F90A14659788AD767DB322 /* Web3+Personal.swift */; }; + 8919A8100FF0A5D62AB5D254FC884684 /* afterlife.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB23B3EF1286E7A0B48DF6ED3428E86B /* afterlife.swift */; }; + 89516187419F3D7FC4037DC8931E2A2A /* web3swift-Browser in Resources */ = {isa = PBXBuildFile; fileRef = 12DC6A0FDF284A2C935F5EA9F6111B0B /* web3swift-Browser */; }; + 899599790D1F3E0DE49CA1985E123C35 /* UIView+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 3C843E59BC22FDE9FDA54491D8F3ECCC /* UIView+AnyPromise.m */; }; + 89F43849392A22634685D2CC339648EA /* AES.swift in Sources */ = {isa = PBXBuildFile; fileRef = 889E3ECE5439BC9C800DFD88ED2F04BD /* AES.swift */; }; + 8A6DA5FBD77B428568A3F4C38F6B0DE1 /* scalar.h in Headers */ = {isa = PBXBuildFile; fileRef = C798B4F4D8097C83111B844CBB1C3CE6 /* scalar.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 8AD89F5F4C9B4D6FA444D3D9805306E9 /* Pods-myWeb3Wallet-myWeb3WalletUITests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = A35804F1DCE3C2A4931790E77FC2F701 /* Pods-myWeb3Wallet-myWeb3WalletUITests-dummy.m */; }; + 8BFE8E6BDEFBF870C1D0732BDF8F6967 /* UInt128.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6CDD67904C46443626098D12FE447EB /* UInt128.swift */; }; + 8CC3ADAFC76BEC761852976026B52758 /* Web3+Eth.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5E9C274FE23EF9CD989D4081E5A80DAB /* Web3+Eth.swift */; }; + 8DA36E33306EFAA1275D13B978BB8666 /* AEAD.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6B7F37C23C7BD91529AFC9D9C3B89350 /* AEAD.swift */; }; + 8DFD0B804F18ADF14E578F6D17536319 /* Web3+ERC1633.swift in Sources */ = {isa = PBXBuildFile; fileRef = CFC32DF7FA786FBF7FC7BF4877244E6A /* Web3+ERC1633.swift */; }; + 8E561C5734860F21E00521B7821122C0 /* ENSReverseRegistrar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9DA7F20BAF89DD9B24B85E9A1A2B4FD2 /* ENSReverseRegistrar.swift */; }; + 9018A1C77BC4F878B1C45B7B672A0D73 /* Promise+Web3+Personal+UnlockAccount.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35FE95CCAA2CF6A2C0218E951A57232D /* Promise+Web3+Personal+UnlockAccount.swift */; }; + 90917685A8320E6EA465DD4A26710930 /* ecmult_const.h in Headers */ = {isa = PBXBuildFile; fileRef = FBD58974667368F7E5904A021A7598D3 /* ecmult_const.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 92142DA2DDD277195E9C53C0078B5BF0 /* ENSRegistry.swift in Sources */ = {isa = PBXBuildFile; fileRef = E0091FDB283E431BE460158D80868E12 /* ENSRegistry.swift */; }; + 92D3DA8C66C63AD5AB2FB84F76591AA5 /* PKCS7Padding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 830413FA8967EA278558006C271B1D16 /* PKCS7Padding.swift */; }; + 95DDEA387C9E5E0FE454158A6175FA88 /* StreamDecryptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3976F596C64EC42D19A8CCF74B70DBF8 /* StreamDecryptor.swift */; }; + 97A2734DE747032D6ECDFEF6EC98A2F0 /* Promise+Web3+Eth+GetAccounts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B72CCFE3D10F1F6A2457EC5730BA509 /* Promise+Web3+Eth+GetAccounts.swift */; }; + 97BF3CCB628215A7A6336B907EDD84D8 /* Utils+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = E725C147A5A1C727AA89210D74D57CBF /* Utils+Foundation.swift */; }; + 97F86BC6C70FFFEA6793B21EF6A7BBFF /* ChaCha20.swift in Sources */ = {isa = PBXBuildFile; fileRef = 616F9AB4DE59A05019261F9A89028DC5 /* ChaCha20.swift */; }; + 9845537646543D7DC920C2AD80F8EF9E /* NSURLSession+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 252A09EFA13237E19D66BDFA6A54DDA5 /* NSURLSession+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 98BD0C2567194580042F4196CFD3C861 /* Resolver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 82B356B37EA2E9BF9C51583849D37CAD /* Resolver.swift */; }; + 993A37B49B1F029A7230A422C32010CC /* AnyPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6C196FA6A48283DE5A44E4FCB71252E8 /* AnyPromise.swift */; }; + 9AD01F25B759252CEDDB74549327971D /* scalar_8x32_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 242D4C1FB3E0059C3577A41C22EB527A /* scalar_8x32_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 9B97A0473C8550F7DEA98DE7AFE25561 /* NSNotificationCenter+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B86157CBD2724B6E4ADD3456BF9A70B /* NSNotificationCenter+Promise.swift */; }; + 9E1EB59875B9875193013A10277645FD /* Blowfish+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7336340A26FA144CE8DC399BD961DE2 /* Blowfish+Foundation.swift */; }; + 9F4816004ABE829D5241033DD39EB4EE /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5C9BF60EE9C79C985DCC648B95156DC4 /* Foundation.framework */; }; + 9FCF9B2D72AA2BCEB8DAB43D4B4C1A69 /* Web3+Eth+Websocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 127BE2CFB3F3A1C174D216B55D11EBAD /* Web3+Eth+Websocket.swift */; }; + A010171CFA2A6782E83B75D63BC34B13 /* String+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 662915FBC8EFD87F9F690D0B12FC9D41 /* String+Extension.swift */; }; + A06894CA00AB9F73142B07C0AEA4AE18 /* BigUInt+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4B9AE90348C0654C1AB4D4690A073401 /* BigUInt+Extensions.swift */; }; + A29D76A39413F75087F969B6CFDE7EB4 /* ComparisonExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A751A1E4864468D4E52A81FC5BDDFDB /* ComparisonExtensions.swift */; }; + A424AF99404EDCFA95671E906356927C /* NonceMiddleware.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18BD9B0B5F5F103741EE858C4D318E00 /* NonceMiddleware.swift */; }; + A4C89AF3E56A327DCF0EB2DD8BBE7D4A /* ENSResolver.swift in Sources */ = {isa = PBXBuildFile; fileRef = AED149E8CB2E262FF979BFD4E5640005 /* ENSResolver.swift */; }; + A4EBBD918D6392B45FF2E3D6ED17C7D1 /* Web3+Methods.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50A8ABDB2A97CBECD57C02DF7D555AD4 /* Web3+Methods.swift */; }; + A5D3E40DA041B9B570227F4D8EA1F8E1 /* PKCS7.swift in Sources */ = {isa = PBXBuildFile; fileRef = AFADECE767F8B6CE7D6F0151072D9120 /* PKCS7.swift */; }; + A6F2904CBA08087504F4507A93D6663C /* hash.h in Headers */ = {isa = PBXBuildFile; fileRef = B3CA76593B24771BFE57E65E82FABF4D /* hash.h */; settings = {ATTRIBUTES = (Project, ); }; }; + A7DC2835A09739C4122A91C072760F98 /* Decodable+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = F558200F0F69A8C32906EE13B19FE77E /* Decodable+Extensions.swift */; }; + A81D0F710AFFC62E73BE7DA8858D621F /* join.m in Sources */ = {isa = PBXBuildFile; fileRef = ED6D439006671F4009638764B9C56EA1 /* join.m */; }; + A81F5E7AC6A31EA09FB5B0CD5ECBA22E /* Exponentiation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 53D054812BB57BDE3069179B7945A4A4 /* Exponentiation.swift */; }; + A8C8165B930AEA0CC08F04D97CDB3434 /* SECP256k1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 194E21E099159CC519476AA1C0E9CD52 /* SECP256k1.swift */; }; + AD485B7D9A894C44A57593FE64BD654E /* UInt64+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6D89670A08E932CCAC385CCADC3E3F7 /* UInt64+Extension.swift */; }; + ADBA50B933B7B857BC80FD659DA51DE9 /* NoPadding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2701E866DF92794F0A7792C7BE838E7D /* NoPadding.swift */; }; + AE063EB21C8E759BC6A01A8736902A88 /* Web3+WebsocketProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9229E35F43D257E448471062DE690D6 /* Web3+WebsocketProvider.swift */; }; + AF2BB4FA178564DBB1D24B5EFBD63951 /* Pods-myWeb3Wallet-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 2819B7319BF925F641E9D256396B3F27 /* Pods-myWeb3Wallet-dummy.m */; }; + B082BF273B13F5F29830AE9BF2547566 /* EIP67Code.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1DF43A48C95155896DC1F3F4407706C /* EIP67Code.swift */; }; + B20CD5B9D658110F9C374648D8FE753E /* PCBC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CF0BA54E2B65D2328C3139726AB3F4B /* PCBC.swift */; }; + B29AC5F4B9E29FE84776B139653182CA /* Web3+ERC888.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9DFDD8684C07E988EE7BEF8AB894F1C3 /* Web3+ERC888.swift */; }; + B2AF71C08A4349665AEA3D6EC7F4A2C8 /* CryptoSwift-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 73EA7956B330A45808E9440BEF76D6D7 /* CryptoSwift-dummy.m */; }; + B327423CEDE6ADD621FDDE4EB64CA187 /* KeystoreManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = B516CBBE190C154B351A76809BF9B33B /* KeystoreManager.swift */; }; + B4370097668317938388822CCCB98FA7 /* after.m in Sources */ = {isa = PBXBuildFile; fileRef = 8DC49762D0D20DA70D0F705EC08E302F /* after.m */; }; + B44349C69B2C0AF407B678B20DC9CB80 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37808DC2E27049822F0681074BF7D960 /* WebSocket.swift */; }; + B563F57CA44978152ED30C459DBC60AE /* NSNotificationCenter+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 60D9A3E52DF6179AF354672295718C6B /* NSNotificationCenter+AnyPromise.m */; }; + B5BB95D002BE731F12AE07C27F14B375 /* PMKUIKit.h in Headers */ = {isa = PBXBuildFile; fileRef = 856EEADEDD158D4873F666AE218DE570 /* PMKUIKit.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B710B3A9760EA48DD6C222EB5DB31C20 /* ecmult_gen_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 2717173A9BD140D3E2D2F0546753746A /* ecmult_gen_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + B7B6E51E810DB18BFE07548B182B6B3C /* field_10x26_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 6CF1331659E806368CFFAD37192BA01A /* field_10x26_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + B96BCDA4AF618BF171AA502CC84FCD8F /* Data Conversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B6DFC9E27C5C2579817751B89E04F28 /* Data Conversion.swift */; }; + B9D1270EAADE0A1F38D25EC5ABC096F0 /* Bit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 82FB779DA3F23E81B13234AB52617EF6 /* Bit.swift */; }; + BADBCBC40AF8A7B54273A943CE95B566 /* ABIParsing.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7DD12C61F348A063E8ADC23768D4327 /* ABIParsing.swift */; }; + BAF082E2C779B6367E8D10E3433AB145 /* PMKFoundation.h in Headers */ = {isa = PBXBuildFile; fileRef = 9272051904F9CDACCBD8DE527C05C8A0 /* PMKFoundation.h */; settings = {ATTRIBUTES = (Public, ); }; }; + BB056B9351B1BE41C2703393F69623DD /* WSEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3B81B518FB1855580F5B38EBB277693E /* WSEngine.swift */; }; + BB1518E2CACEF26E121AAE6BE6DD8096 /* Web3+JSONRPC.swift in Sources */ = {isa = PBXBuildFile; fileRef = E367D31EF999AF507211E8538ED28182 /* Web3+JSONRPC.swift */; }; + BD7B5B59593F5A42A4315FC7FEE94DE4 /* EthereumTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = FACCAD5B5F220165EBCE30AAE936EAD1 /* EthereumTransaction.swift */; }; + BE3E77E8C72C1192A5B316858A54D179 /* Web3+ERC820.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3511CE45081A21C5D78AEA0873840821 /* Web3+ERC820.swift */; }; + C10AEAE3170856A4A6ED972AF8CCFF4A /* BlockMode.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9418ED7506E09852282E4C0298F4CF2 /* BlockMode.swift */; }; + C1560D479D2C4290339F2153A1009695 /* Digest.swift in Sources */ = {isa = PBXBuildFile; fileRef = D263F99BE4CC8113CEC0DF611249ADB8 /* Digest.swift */; }; + C28A0006DD1C9AB062763C8FA2B3F93D /* NativeEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C3AD67954329D1C955D54EF41C4508F /* NativeEngine.swift */; }; + C31C553CC452563D5E1B3E2EB53E6CB3 /* scratch.h in Headers */ = {isa = PBXBuildFile; fileRef = F19B311741AA54433FA1A285E0537076 /* scratch.h */; settings = {ATTRIBUTES = (Project, ); }; }; + C3244A82259871FF39B6AD13D0925DBE /* secp256k1.h in Headers */ = {isa = PBXBuildFile; fileRef = 61F9291E88C2B8D95351C63BBAC5A220 /* secp256k1.h */; settings = {ATTRIBUTES = (Public, ); }; }; + C3AD5637CD16B453B6BEDC56EFE74130 /* scalar_low.h in Headers */ = {isa = PBXBuildFile; fileRef = A8BBEB50E65BE6B493DCFE9A2BCCE825 /* scalar_low.h */; settings = {ATTRIBUTES = (Project, ); }; }; + C4BBCF72974CC3BD3B521B32EC37647B /* secp256k1.c in Sources */ = {isa = PBXBuildFile; fileRef = 85D99C55C6D2A7368634E17D0FC07D22 /* secp256k1.c */; }; + C5DDDCCA557F626F4124A8F58E299EEF /* scratch_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = AD0E7C344DBA5BB5BD963F05B4DC42F0 /* scratch_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + C6251BBAFFC461D3EA4A3D845B4EA44D /* PublicKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18234DDB0733F3EF948EF77D54D10904 /* PublicKey.swift */; }; + C820C6095101F683B6C0ACEEFC39E26A /* ENS.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1086E5EB59F24E36E2556B3270BE06F /* ENS.swift */; }; + C8B562CF6E6CD3D1CF98D9E9F5B606C8 /* Promise+HttpProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = B283E7DB525627BCDF8B64F25F729738 /* Promise+HttpProvider.swift */; }; + C8B899C850EC6CB3C9BF2841FB08713F /* fwd.h in Headers */ = {isa = PBXBuildFile; fileRef = A4F1C951C5378C2C015177FE8E9BBF92 /* fwd.h */; settings = {ATTRIBUTES = (Public, ); }; }; + CA088D37EFE8AD4496EDC4FA6A1FBE8D /* Promise+Web3+Eth+GetBalance.swift in Sources */ = {isa = PBXBuildFile; fileRef = CAC7EB22892368AC2FB24D3C9A74B5BF /* Promise+Web3+Eth+GetBalance.swift */; }; + CB1A9A8A033409BF5D585EF62A7254E9 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5C9BF60EE9C79C985DCC648B95156DC4 /* Foundation.framework */; }; + CBC2CC340CD4CFCD60F9A30BC9E0955C /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5C9BF60EE9C79C985DCC648B95156DC4 /* Foundation.framework */; }; + CC235941F0CF9FA8C0FA3323A0D18203 /* Framer.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8C128F18673E79A6E143D83ECDB3AEB /* Framer.swift */; }; + CC95169162908F93F653A92A59E440D5 /* UInt16+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 824063EF324B04F2AADFB9E47CDA422A /* UInt16+Extension.swift */; }; + CE7A68CDFD3FC58EF21CC7C08D24CA55 /* CFB.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9763CCFBEDDC125312CD1FF164DB1DA5 /* CFB.swift */; }; + CFA3A9074716531683DA2E55B301B9CE /* Pods-myWeb3Wallet-myWeb3WalletUITests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F9295022CA4AA205D97FA9E845A976C7 /* Pods-myWeb3Wallet-myWeb3WalletUITests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D10D625D7F4AAA29A79D695BC3A94A00 /* Web3+Protocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2ED9A418D702E70593766E47BF84FA5 /* Web3+Protocols.swift */; }; + D1691005C5FF403516FCA539B0E8038E /* Multiplication.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6F928DE9F728F034C42EF3E84EBB5B6A /* Multiplication.swift */; }; + D2D4D144266F4423CD3653BCBE240D07 /* field_5x52.h in Headers */ = {isa = PBXBuildFile; fileRef = 6D011B0CEC9AC062DC89BC9C1EC05806 /* field_5x52.h */; settings = {ATTRIBUTES = (Project, ); }; }; + D3E9E3F249E8D3D98C4E51836BDC4954 /* Cipher.swift in Sources */ = {isa = PBXBuildFile; fileRef = E55E8B81407082884426231F92E19AED /* Cipher.swift */; }; + D4135E6CF7800B813179A4DFB88BB112 /* ChaCha20+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5781B6CBB88661F6F9E634C0914094C /* ChaCha20+Foundation.swift */; }; + D618594A60716C12B8FBAA73F18EC31C /* OCB.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3EBD086332607B408BD6F878EA9A500 /* OCB.swift */; }; + D633C149E87E57031FD51E4D9FCE331D /* Web3+Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = ABC21DF8C117534CE67E549DA43A59F6 /* Web3+Utils.swift */; }; + D6412C05ED65D3E6FB4B101125AC47CA /* Promise+Web3+Personal+Sign.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF9BF56B15E811B9D10946DD368C9411 /* Promise+Web3+Personal+Sign.swift */; }; + D64729DEA5CA52814AA8B431714ABDAF /* CustomStringConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = C563C261B9470D2D28A526E4BF747E2C /* CustomStringConvertible.swift */; }; + D6BEA1C18AB70DC0B64169E0FA48F2D7 /* Web3+Wallet.swift in Sources */ = {isa = PBXBuildFile; fileRef = F91048DD1C7E59A1DD091512416C06A4 /* Web3+Wallet.swift */; }; + D6BF0D382E2E68028AAF3CA080E941E8 /* Addition.swift in Sources */ = {isa = PBXBuildFile; fileRef = E00B9DD5F289EBCC20B485163A92C9CE /* Addition.swift */; }; + D7543F214A383F50E45721F7E959CE93 /* ETHRegistrarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = CBC606D4D73D4D6373FD43179F3DF3C5 /* ETHRegistrarController.swift */; }; + D86D490CF982E629A578DED0E89F146F /* Authenticator.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7B8332B6EEE60574C9B4CB468B81524 /* Authenticator.swift */; }; + D8C85DE0B332878402530E6886BF4C87 /* BIP32Keystore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6DF004A0692AE90EAC3F6F16BDF07740 /* BIP32Keystore.swift */; }; + DA5F6B91BDDA4FE3C6104DCEC0866921 /* basic-config.h in Headers */ = {isa = PBXBuildFile; fileRef = E6C3B21AB95E51A2D26F2C42C0A2C164 /* basic-config.h */; settings = {ATTRIBUTES = (Project, ); }; }; + DA6EDABF74C3C6E9F9997B698195D6A2 /* Prime Test.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C95BF67289C881540C0022C3E712E2C /* Prime Test.swift */; }; + DAF534C4544B6E5EAD5C4AD44709E385 /* Pods-myWeb3WalletTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 8C020773045EBAC1BB6CC4DCF9CF70E8 /* Pods-myWeb3WalletTests-dummy.m */; }; + DC538415218A5989D1CE2A5134CBC050 /* browser.js in Resources */ = {isa = PBXBuildFile; fileRef = E71A523B7024293D61E1102B9CC22823 /* browser.js */; }; + DCFC2730C2AB6CA444EFE289DC32F045 /* NSURLSession+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 8456FEA753DE9A90D304EA54DFD5DAD3 /* NSURLSession+AnyPromise.m */; }; + DDA8E54FFAA6DFF7E15F15A52AB7C662 /* Hashable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C1C57972351C9020E941D25D57CF959 /* Hashable.swift */; }; + DE39DBC5AAF719AFBCB7BB50025A772B /* Blowfish.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4C26BFD4C4F0041CB43065B7C15190C /* Blowfish.swift */; }; + DE3C93B4089CA412BCEB4EF302BB4FD0 /* web3swift-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = F499FD6C54B3145BB4C4FAC810F4B15D /* web3swift-dummy.m */; }; + DEA8679395E5618A8513EA80D9772EEC /* Catchable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DC1F5BA0194E3F08E0C6652CB89C9D /* Catchable.swift */; }; + DF9BE4B3E95B007977780C9EFDA3EFBE /* Server.swift in Sources */ = {isa = PBXBuildFile; fileRef = FC11C1CC2479584E9A41405F284BF604 /* Server.swift */; }; + DFA2736CE4B16FD4D82450863EC58507 /* Compression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 807F4EF0F6896F7BEB55DDE65E4CB28F /* Compression.swift */; }; + E0137D6D9AE5B6786272CFEE12EE329F /* Updatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F37ABE5C51720188832DE43FE27AA1B /* Updatable.swift */; }; + E046D9CFF7D48145B6149CB307FF0DFE /* Promise+Web3+Eth+SendTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 69B470CEFDB78B1B81B0DAF2D4FBDBA4 /* Promise+Web3+Eth+SendTransaction.swift */; }; + E080D5147262BC05559D3F88A251D496 /* ecdsa_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 1B1FB7A40FA73B490F40C882A36FDC44 /* ecdsa_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + E13C4DBE0EB7FBE696A0E3ACDE40699E /* Web3+ERC721.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEE308A0279FEF1970F5AE55A59B0784 /* Web3+ERC721.swift */; }; + E1D133E30A0D32065EE248F784F8020D /* Guarantee.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4D4496F8FBCD773F8A25A49F635CC63C /* Guarantee.swift */; }; + E21CF0BAEC9DC901D45DDCEEA2C44E45 /* ecdh_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 95E71976E5850018C27C15AC878DC296 /* ecdh_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + E256732DB3DBDEE4FD44CD303C1DE53A /* UIView+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 43B7747EAA000C9B48B5D7B826AE8AA9 /* UIView+Promise.swift */; }; + E3D6C010B605EA8EDF757BB7965A18F5 /* ecdsa.h in Headers */ = {isa = PBXBuildFile; fileRef = 4E304701AA575E1B30297A9335082B9C /* ecdsa.h */; settings = {ATTRIBUTES = (Project, ); }; }; + E4A7207A022D9584CD9B7D29381C8454 /* GCD.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCAEE90730AA63BAC2B8BA0C11298D49 /* GCD.swift */; }; + E5C5FBE36369E20E6913EA8FA5E4874D /* secp256k1.c-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 494245F16C74B7E11B629E6D698264E8 /* secp256k1.c-dummy.m */; }; + E65FCA7A3C97C063DCDB2B15787E7BC7 /* field.h in Headers */ = {isa = PBXBuildFile; fileRef = 5931D9D39B790BA48631057F24CE6AAC /* field.h */; settings = {ATTRIBUTES = (Project, ); }; }; + E6D66EE992F5F92BBF5D7C9D9DBB1D70 /* group.h in Headers */ = {isa = PBXBuildFile; fileRef = DFB72A7E5ADC684FA4CD2AD37D7D0B3B /* group.h */; settings = {ATTRIBUTES = (Project, ); }; }; + E70F74FB30DAEB297AA089C8BCCCA4EB /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7902A028BC075F44A5B91EA5C782640 /* Configuration.swift */; }; + E793B49B0F4F9444C35C938A84919D59 /* Rabbit+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A26062C707AB96E5E13A0125B15FE06 /* Rabbit+Foundation.swift */; }; + E7D5EAA730340EF382A7A87B70232C90 /* recovery_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = D5BEDCE22D40961DE68C60CB6AE573A7 /* recovery_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; + E85A27344F3B51082781DB3E11724E36 /* hang.m in Sources */ = {isa = PBXBuildFile; fileRef = BB6A86B206A38FF5301C697059CED678 /* hang.m */; }; + E9B1EE521C74E68921DD97D24EDC388A /* AES.Cryptors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8AFCDD28CDD4C6AB23094990AABE6DE9 /* AES.Cryptors.swift */; }; + EB0FA8A87893F91A83545E5D76C55345 /* Promise+Web3+Eth+GetBlockByHash.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2351A3019723AF864F03D66DEFDAA1CC /* Promise+Web3+Eth+GetBlockByHash.swift */; }; + EB347652A3DBB0D1DDD97E0B2EAC4090 /* Web3+Contract.swift in Sources */ = {isa = PBXBuildFile; fileRef = C513F6340AD8C6EF588154BB1FBB30DB /* Web3+Contract.swift */; }; + EB5C3537AD21658D3EC873A4A4AFDE30 /* FrameCollector.swift in Sources */ = {isa = PBXBuildFile; fileRef = C321EB417B11D2E05909E2F4DBF30D9A /* FrameCollector.swift */; }; + EC13DCF1271C181C1E7B6E1FF203F587 /* Web3+ERC777.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D47AE3AEBABE33FF5939852216CAA95 /* Web3+ERC777.swift */; }; + EC1939718B30E2C224E107770EFA15E8 /* UIViewController+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 45780CFDD8941B525B61D0A0EFBAC14C /* UIViewController+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EC7222CB5D2208398F18AAE16373D49A /* Array+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 459691924762DB7278BDA1860FC51C8E /* Array+Foundation.swift */; }; + EC95784DCA76E26345C1E5090C1B1850 /* Bitwise Ops.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3241E63D9616921B2EB997B33DA65015 /* Bitwise Ops.swift */; }; + ECA87472345DEE9383C99B94132989C8 /* firstly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 89E3E5798A0F9C8B82F89E4AA1C9B933 /* firstly.swift */; }; + ED6E80F590AC3940E9DAEA8DA0AB5A4B /* BrowserViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A7C267F2A6E93388DE89B4D3D823E13 /* BrowserViewController.swift */; }; + F260472C8FC1056456D14073C24E1B54 /* NameHash.swift in Sources */ = {isa = PBXBuildFile; fileRef = 03FB8D39BDF0D05A9BF5951DAD5C5623 /* NameHash.swift */; }; + F41028D4E0E43E885ED9ADDFABBE1ED3 /* Comparable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 91E170E8B0E46F448434AEDA45BE7201 /* Comparable.swift */; }; + F5088E4F43A46473DEAC73F7CC841395 /* Web3+TxPool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4FCECB2399C85B352286D927376CCC94 /* Web3+TxPool.swift */; }; + F51D20305F49B5ECF5C06EF8C156BADA /* Web3+Constants.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2194F52EA9713769E689181030DF7B4 /* Web3+Constants.swift */; }; + F54936D6E4E4D8360799608587FBE650 /* CMAC.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8A625D05EC1B896D29CA0FCFF4B4395 /* CMAC.swift */; }; + F5F0562EFC8A4222EB84980F223E6C15 /* Random.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83EB318EEB278287224355CBE3049A48 /* Random.swift */; }; + F63C0FC83982E1034CB316A7EA644E6E /* Deprecations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 074712D83C2147040D6DBDC8B41CAEC3 /* Deprecations.swift */; }; + F7462C6596BBFFFF4EFB9DC8BA39B18F /* Padding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0249C3548513926775493A932FE6EA90 /* Padding.swift */; }; + F7B5F76F363F06CC58B18C19A4132205 /* CTR.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9E59212A5A8295E5F180ED605A1CDE7 /* CTR.swift */; }; + F81E16CDC41BE1CB2C103F910F5FFC70 /* Square Root.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E5F6F994922528B6B9B3A5BB5E2DA3A /* Square Root.swift */; }; + F9087DABB154530427BC4540C43E5853 /* Thenable.swift in Sources */ = {isa = PBXBuildFile; fileRef = A788EBC997CC72DFE928373C05F3C475 /* Thenable.swift */; }; + F95103DB3CDE985249C0B9E4CD464BA0 /* Integer Conversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B580076A33C54363F117FC48118156B /* Integer Conversion.swift */; }; + F9787C205394000FA66B667A2AC04FD6 /* eckey.h in Headers */ = {isa = PBXBuildFile; fileRef = 4D50E33E27CBB4C4D9F7EBAE3849B7A5 /* eckey.h */; settings = {ATTRIBUTES = (Project, ); }; }; + FA0502B3678EC835EAEAB000529D762E /* Scrypt.swift in Sources */ = {isa = PBXBuildFile; fileRef = A131EC03EF93B5304C3DB4E559307C3B /* Scrypt.swift */; }; + FA2A3CCAE01CF0108D2FDB7C8108B988 /* WSCompression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93782C7F3F539959B04BE436295FD94A /* WSCompression.swift */; }; + FA846FE4D4519D64A27097EB46DD1D3F /* BIP39+WordLists.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BD1F43673C0FBEB88F290755398E0BF /* BIP39+WordLists.swift */; }; + FAF9F208C87105DBB01C49B39CA7F6E5 /* UInt8+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB7B5E4ADA577B5E93F2C0FC6E8843FC /* UInt8+Extension.swift */; }; + FAFD54F649DC5D69DD05D517A0131968 /* Engine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C3A07D69D081152A01DECBBDF98D24A /* Engine.swift */; }; + FBCD6D8D56A2086EF53DA7228F7382A6 /* CBCMAC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 457220DE54FCFECF49D27D4F0494EB51 /* CBCMAC.swift */; }; + FF3F808C427F7277B5EBDD62E3322B77 /* AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 61F1F5C6B7C7A8680F81CDEB5CDD4D8B /* AnyPromise.m */; }; + FF46419E6ED54F61278B20902A49162C /* ABITypeParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 94545F2C1973B711F0E957917ED7B36E /* ABITypeParser.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 0F1AB7F16B1489C0A9376FA250FA1E43 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 99364D9FB07EF3FA5DFE1237001805EC; + remoteInfo = web3swift; + }; + 1AA24238F1760F9C69F6C5F85EDB0E55 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 09DD83B7D075842A3A5105AD410BD38A; + remoteInfo = BigInt; + }; + 213875A730C40CBF46083A20A1BE357B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 8CDD759A6130CA265C6D157F4407C39B; + remoteInfo = "web3swift-Browser"; + }; + 2718FE1B45CEBB0916BB88BA064F4933 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 7C579CE66A1E7A9AA33CA5F97F9C22C5; + remoteInfo = PromiseKit; + }; + 3CF61B40DA8701A404561C8BB3906C64 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 161C26511FC920CB146236AB7295D5E0; + remoteInfo = secp256k1.c; + }; + 4E09EE4197617974D331E8FD4C46E31B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 9B78EE4AF6AE03E79D88886319853FF7; + remoteInfo = Starscream; + }; + 50AD90732DFB53A74A40446FCAB7A28A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 9B78EE4AF6AE03E79D88886319853FF7; + remoteInfo = Starscream; + }; + 5BA6C4D904CAA10678B6150A0C0226BE /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 09DD83B7D075842A3A5105AD410BD38A; + remoteInfo = BigInt; + }; + 6AEC58EE30DAC0EFC0DBDE54F71AFBF6 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 161C26511FC920CB146236AB7295D5E0; + remoteInfo = secp256k1.c; + }; + 7DE5DE6920D96531E3702842566D4B18 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 99313990C1D76A6D1D017868B6975CC8; + remoteInfo = CryptoSwift; + }; + 8130DEB78F04D6BB1AFDA6CD21C2566B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 9B78EE4AF6AE03E79D88886319853FF7; + remoteInfo = Starscream; + }; + A84A86AF1C834FE3CCE7EF4A28AC8923 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 7C579CE66A1E7A9AA33CA5F97F9C22C5; + remoteInfo = PromiseKit; + }; + AAAB261AD53885F4EC04F8178139736C /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 99364D9FB07EF3FA5DFE1237001805EC; + remoteInfo = web3swift; + }; + C995D076E7B0E0958B346D5104531D7C /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 161C26511FC920CB146236AB7295D5E0; + remoteInfo = secp256k1.c; + }; + CE67F1BCE310A5D970E09D05453873C8 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 99313990C1D76A6D1D017868B6975CC8; + remoteInfo = CryptoSwift; + }; + D0937854CA7F3934D850A6B12504123F /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 09DD83B7D075842A3A5105AD410BD38A; + remoteInfo = BigInt; + }; + D5D3007741958562AC65E03C4C1896C0 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 99313990C1D76A6D1D017868B6975CC8; + remoteInfo = CryptoSwift; + }; + F6219F5A6A73436B4AC67ABFC9BCF49A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = D89A752AFCCF1B411FDB91762F626B42; + remoteInfo = "Pods-myWeb3Wallet"; + }; + F9F390AD37B4AFE468B203D739018ED0 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 7C579CE66A1E7A9AA33CA5F97F9C22C5; + remoteInfo = PromiseKit; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 002B1E88BA14EBF633CD66EBFBA107E9 /* PromiseKit */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = PromiseKit; path = PromiseKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 0050F742D824A11AEB8424E0DD2C63DE /* AbstractKeystore.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AbstractKeystore.swift; path = Sources/web3swift/KeystoreManager/AbstractKeystore.swift; sourceTree = ""; }; + 00C245DA669E6E0BBAFA3115D6823007 /* BIP39.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BIP39.swift; path = Sources/web3swift/KeystoreManager/BIP39.swift; sourceTree = ""; }; + 01316651403CC05C86D98D47F9CF04B3 /* Starscream-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Starscream-prefix.pch"; sourceTree = ""; }; + 0249C3548513926775493A932FE6EA90 /* Padding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Padding.swift; path = Sources/CryptoSwift/Padding.swift; sourceTree = ""; }; + 02604971270B936C3550FF9F7FAE7132 /* ecmult_gen.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecmult_gen.h; path = secp256k1/ecmult_gen.h; sourceTree = ""; }; + 0349201509342BC7491FA1ED83CDE2F7 /* NSTask+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSTask+AnyPromise.h"; path = "Extensions/Foundation/Sources/NSTask+AnyPromise.h"; sourceTree = ""; }; + 03FB8D39BDF0D05A9BF5951DAD5C5623 /* NameHash.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NameHash.swift; path = Sources/web3swift/Utils/ENS/NameHash.swift; sourceTree = ""; }; + 047C81A9AD59EDA23DBD28F67EA44F3D /* scalar_4x64.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar_4x64.h; path = secp256k1/scalar_4x64.h; sourceTree = ""; }; + 074712D83C2147040D6DBDC8B41CAEC3 /* Deprecations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Deprecations.swift; path = Sources/Deprecations.swift; sourceTree = ""; }; + 08A8472B9823BC68472175977392F4B9 /* Pods-myWeb3Wallet */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = "Pods-myWeb3Wallet"; path = Pods_myWeb3Wallet.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 09783897421F576EDE46857412E8265C /* Web3+ERC1400.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1400.swift"; path = "Sources/web3swift/Tokens/ERC1400/Web3+ERC1400.swift"; sourceTree = ""; }; + 0AC66155707B85F45580BC854DAA5E8C /* AES+Foundation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "AES+Foundation.swift"; path = "Sources/CryptoSwift/Foundation/AES+Foundation.swift"; sourceTree = ""; }; + 0BC7C885678FE3B4FE04CA4488F4B953 /* Pods-myWeb3Wallet-myWeb3WalletUITests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-myWeb3Wallet-myWeb3WalletUITests-acknowledgements.markdown"; sourceTree = ""; }; + 0C3130C87D960B3C5DC4BE2B9448DC1B /* Pods-myWeb3Wallet-myWeb3WalletUITests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-myWeb3Wallet-myWeb3WalletUITests.modulemap"; sourceTree = ""; }; + 0C4C834F49C3454D3ED6140F8761E5EE /* PlainKeystore.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PlainKeystore.swift; path = Sources/web3swift/KeystoreManager/PlainKeystore.swift; sourceTree = ""; }; + 0C706E0E7E64CC2DDFF946B173F6E937 /* Dictionary+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Dictionary+Extension.swift"; path = "Sources/web3swift/Convenience/Dictionary+Extension.swift"; sourceTree = ""; }; + 0CDD25924C64FF376F842253501355D4 /* BigInt-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "BigInt-prefix.pch"; sourceTree = ""; }; + 0D72EEA6CB2ED51D9CD581441D934A96 /* Operators.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Operators.swift; path = Sources/CryptoSwift/Operators.swift; sourceTree = ""; }; + 0E7FE0B9D0DF6B91966F07D6D2282738 /* RLP.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RLP.swift; path = Sources/web3swift/SwiftRLP/RLP.swift; sourceTree = ""; }; + 10362E3628CDA7ABAD35AB9B2A1093E5 /* CryptoSwift.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = CryptoSwift.modulemap; sourceTree = ""; }; + 10B43E5A8E435E74A39AC5722CC5A271 /* CCM.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CCM.swift; path = Sources/CryptoSwift/BlockMode/CCM.swift; sourceTree = ""; }; + 10F4B4430DB29EA7B5DF0FF1637E5B75 /* hash_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = hash_impl.h; path = secp256k1/hash_impl.h; sourceTree = ""; }; + 11103C5C5CFDD9B3B2EA4E84B98049A8 /* Pods-myWeb3WalletTests */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = "Pods-myWeb3WalletTests"; path = Pods_myWeb3WalletTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 11657185FCE37F7674E70752DFF319F7 /* Cryptors.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Cryptors.swift; path = Sources/CryptoSwift/Cryptors.swift; sourceTree = ""; }; + 127BE2CFB3F3A1C174D216B55D11EBAD /* Web3+Eth+Websocket.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Eth+Websocket.swift"; path = "Sources/web3swift/Web3/Web3+Eth+Websocket.swift"; sourceTree = ""; }; + 12CFBD6C81A2CE71BA2C4F590B5D5927 /* util.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = util.h; path = secp256k1/util.h; sourceTree = ""; }; + 12DC6A0FDF284A2C935F5EA9F6111B0B /* web3swift-Browser */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; name = "web3swift-Browser"; path = Browser.bundle; sourceTree = BUILT_PRODUCTS_DIR; }; + 138407359512A2D920EEDD6C7AEDDF81 /* ecmult.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecmult.h; path = secp256k1/ecmult.h; sourceTree = ""; }; + 14105AEFAD47B97BBFD0A972AA98DF35 /* Pods-myWeb3Wallet-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-myWeb3Wallet-umbrella.h"; sourceTree = ""; }; + 141B6AEB28CFF06BE48234968D5F6490 /* GCM.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GCM.swift; path = Sources/CryptoSwift/BlockMode/GCM.swift; sourceTree = ""; }; + 1659BBB217FF5D75D1A83A1CCB87541C /* EthereumKeystoreV3.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EthereumKeystoreV3.swift; path = Sources/web3swift/KeystoreManager/EthereumKeystoreV3.swift; sourceTree = ""; }; + 166F18C437FFEE4629AC9EDD147F272A /* web3swift-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "web3swift-prefix.pch"; sourceTree = ""; }; + 173FD7EFF45980B448F92A8F6A1CE154 /* Checksum.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Checksum.swift; path = Sources/CryptoSwift/Checksum.swift; sourceTree = ""; }; + 1786CFA34F2534AD545031FF7EBA4538 /* CipherModeWorker.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CipherModeWorker.swift; path = Sources/CryptoSwift/BlockMode/CipherModeWorker.swift; sourceTree = ""; }; + 17AAAF47166CDEF7CB91711009CC9DB3 /* ECB.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ECB.swift; path = Sources/CryptoSwift/BlockMode/ECB.swift; sourceTree = ""; }; + 18234DDB0733F3EF948EF77D54D10904 /* PublicKey.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PublicKey.swift; path = Sources/web3swift/Utils/ENS/PublicKey.swift; sourceTree = ""; }; + 18BD9B0B5F5F103741EE858C4D318E00 /* NonceMiddleware.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NonceMiddleware.swift; path = Sources/web3swift/Utils/Hooks/NonceMiddleware.swift; sourceTree = ""; }; + 18DBFFB3E63974D7C0824367EFCAC013 /* BigInt.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = BigInt.release.xcconfig; sourceTree = ""; }; + 18E0CD9ADEB45DAE398F37822641499A /* UIViewPropertyAnimator+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIViewPropertyAnimator+Promise.swift"; path = "Extensions/UIKit/Sources/UIViewPropertyAnimator+Promise.swift"; sourceTree = ""; }; + 194E21E099159CC519476AA1C0E9CD52 /* SECP256k1.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SECP256k1.swift; path = Sources/web3swift/Convenience/SECP256k1.swift; sourceTree = ""; }; + 196F8D0679C136F9CB5DEDA32CE39FA4 /* Web3+Structures.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Structures.swift"; path = "Sources/web3swift/Web3/Web3+Structures.swift"; sourceTree = ""; }; + 1B1FB7A40FA73B490F40C882A36FDC44 /* ecdsa_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecdsa_impl.h; path = secp256k1/ecdsa_impl.h; sourceTree = ""; }; + 1B86157CBD2724B6E4ADD3456BF9A70B /* NSNotificationCenter+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSNotificationCenter+Promise.swift"; path = "Extensions/Foundation/Sources/NSNotificationCenter+Promise.swift"; sourceTree = ""; }; + 1B876EF576BCF48712B2FE0B58425831 /* Rabbit.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Rabbit.swift; path = Sources/CryptoSwift/Rabbit.swift; sourceTree = ""; }; + 1C1C57972351C9020E941D25D57CF959 /* Hashable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Hashable.swift; path = Sources/Hashable.swift; sourceTree = ""; }; + 1C662BE19BE125813C43B2C2F34A06A4 /* Poly1305.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Poly1305.swift; path = Sources/CryptoSwift/Poly1305.swift; sourceTree = ""; }; + 1D7BC9EE36F90A14659788AD767DB322 /* Web3+Personal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Personal.swift"; path = "Sources/web3swift/Web3/Web3+Personal.swift"; sourceTree = ""; }; + 21DA00ACD8F03D5A27C632034D5215B3 /* Security.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Security.swift; path = Sources/Security/Security.swift; sourceTree = ""; }; + 2351A3019723AF864F03D66DEFDAA1CC /* Promise+Web3+Eth+GetBlockByHash.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+GetBlockByHash.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByHash.swift"; sourceTree = ""; }; + 23C909CF58C1C172D843DF0B9927E7E1 /* PromiseKit.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PromiseKit.debug.xcconfig; sourceTree = ""; }; + 242D4C1FB3E0059C3577A41C22EB527A /* scalar_8x32_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar_8x32_impl.h; path = secp256k1/scalar_8x32_impl.h; sourceTree = ""; }; + 243018B29E2BCD800923B34F993D9B28 /* secp256k1.c-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "secp256k1.c-prefix.pch"; sourceTree = ""; }; + 2456150E4EBA655122DFE457A3B16411 /* ABIDecoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ABIDecoding.swift; path = Sources/web3swift/EthereumABI/ABIDecoding.swift; sourceTree = ""; }; + 252A09EFA13237E19D66BDFA6A54DDA5 /* NSURLSession+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSURLSession+AnyPromise.h"; path = "Extensions/Foundation/Sources/NSURLSession+AnyPromise.h"; sourceTree = ""; }; + 2701E866DF92794F0A7792C7BE838E7D /* NoPadding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NoPadding.swift; path = Sources/CryptoSwift/NoPadding.swift; sourceTree = ""; }; + 2717173A9BD140D3E2D2F0546753746A /* ecmult_gen_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecmult_gen_impl.h; path = secp256k1/ecmult_gen_impl.h; sourceTree = ""; }; + 274E8BA3AEB35AB17FA088333816830A /* web3swift.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = web3swift.debug.xcconfig; sourceTree = ""; }; + 2819B7319BF925F641E9D256396B3F27 /* Pods-myWeb3Wallet-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-myWeb3Wallet-dummy.m"; sourceTree = ""; }; + 28AEFC12990DE5857B6C8C3DD151EE7F /* UIView+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIView+AnyPromise.h"; path = "Extensions/UIKit/Sources/UIView+AnyPromise.h"; sourceTree = ""; }; + 2969A6F4F3AB1FF9852CF5B8BBFF0981 /* Promise+Web3+Eth+GetTransactionDetails.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+GetTransactionDetails.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionDetails.swift"; sourceTree = ""; }; + 2AEB64E397C62A9D958096179BE64189 /* Division.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Division.swift; path = Sources/Division.swift; sourceTree = ""; }; + 2B5918B5A16C03780E709CF2CDD1104C /* ABIParameterTypes.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ABIParameterTypes.swift; path = Sources/web3swift/EthereumABI/ABIParameterTypes.swift; sourceTree = ""; }; + 2CA6A6221D6CA8057D71BA60A8DAF0EF /* eckey_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = eckey_impl.h; path = secp256k1/eckey_impl.h; sourceTree = ""; }; + 2D1CFEA76FE44A2E6511787F74D0794C /* wk.bridge.min.js */ = {isa = PBXFileReference; includeInIndex = 1; name = wk.bridge.min.js; path = Sources/web3swift/Browser/wk.bridge.min.js; sourceTree = ""; }; + 2DDB8CD09F1100772FC894971E35ECF6 /* BlockCipher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BlockCipher.swift; path = Sources/CryptoSwift/BlockCipher.swift; sourceTree = ""; }; + 2E5F6F994922528B6B9B3A5BB5E2DA3A /* Square Root.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Square Root.swift"; path = "Sources/Square Root.swift"; sourceTree = ""; }; + 307663AAE1B15058CDCC30A8C3B476C6 /* PromiseKit-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "PromiseKit-Info.plist"; sourceTree = ""; }; + 30F6DD109D1E925101993EF13CC1B6DD /* Encodable+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Encodable+Extensions.swift"; path = "Sources/web3swift/Convenience/Encodable+Extensions.swift"; sourceTree = ""; }; + 3241E63D9616921B2EB997B33DA65015 /* Bitwise Ops.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Bitwise Ops.swift"; path = "Sources/Bitwise Ops.swift"; sourceTree = ""; }; + 332A47430CFF99501D563788C7AAF1D2 /* secp256k1.c */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = secp256k1.c; path = secp256k1.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 3339301FC43964D4764CDC289EBDD39E /* ABIEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ABIEncoding.swift; path = Sources/web3swift/EthereumABI/ABIEncoding.swift; sourceTree = ""; }; + 33D9C3E44151CA8DAEC4B95DEEE84E07 /* Array+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Array+Extension.swift"; path = "Sources/CryptoSwift/Array+Extension.swift"; sourceTree = ""; }; + 3402BA34F808F411E48E41CD59F05FCE /* Web3+ERC1643.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1643.swift"; path = "Sources/web3swift/Tokens/ERC1643/Web3+ERC1643.swift"; sourceTree = ""; }; + 3511CE45081A21C5D78AEA0873840821 /* Web3+ERC820.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC820.swift"; path = "Sources/web3swift/Tokens/ERC820/Web3+ERC820.swift"; sourceTree = ""; }; + 35BAB9DEB6B862BBA80319A779593939 /* scalar_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar_impl.h; path = secp256k1/scalar_impl.h; sourceTree = ""; }; + 35FE95CCAA2CF6A2C0218E951A57232D /* Promise+Web3+Personal+UnlockAccount.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Personal+UnlockAccount.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Personal+UnlockAccount.swift"; sourceTree = ""; }; + 3617B0E86D0A093AA4BC7F0006FD0413 /* SecureBytes.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SecureBytes.swift; path = Sources/CryptoSwift/SecureBytes.swift; sourceTree = ""; }; + 36EB9FBA8F61ABE90D34ACAAE90DE61A /* NSObject+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSObject+Promise.swift"; path = "Extensions/Foundation/Sources/NSObject+Promise.swift"; sourceTree = ""; }; + 37808DC2E27049822F0681074BF7D960 /* WebSocket.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WebSocket.swift; path = Sources/Starscream/WebSocket.swift; sourceTree = ""; }; + 3806AFE4E13D3ED1C2FD088F8F101839 /* CryptoSwift-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "CryptoSwift-Info.plist"; sourceTree = ""; }; + 38E0F1A25A1345D8458B0FA85EF949FD /* WebSocketServer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WebSocketServer.swift; path = Sources/Server/WebSocketServer.swift; sourceTree = ""; }; + 3976F596C64EC42D19A8CCF74B70DBF8 /* StreamDecryptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StreamDecryptor.swift; path = Sources/CryptoSwift/StreamDecryptor.swift; sourceTree = ""; }; + 3B81B518FB1855580F5B38EBB277693E /* WSEngine.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WSEngine.swift; path = Sources/Engine/WSEngine.swift; sourceTree = ""; }; + 3BD1F43673C0FBEB88F290755398E0BF /* BIP39+WordLists.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "BIP39+WordLists.swift"; path = "Sources/web3swift/KeystoreManager/BIP39+WordLists.swift"; sourceTree = ""; }; + 3C3624803E3D83147D2CE9BD951D7CCA /* PromiseKit.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = PromiseKit.modulemap; sourceTree = ""; }; + 3C843E59BC22FDE9FDA54491D8F3ECCC /* UIView+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIView+AnyPromise.m"; path = "Extensions/UIKit/Sources/UIView+AnyPromise.m"; sourceTree = ""; }; + 3D6311A0CAB052B65B5FC50B1A76C0C8 /* dispatch_promise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = dispatch_promise.m; path = Sources/dispatch_promise.m; sourceTree = ""; }; + 3F3F31CC12709B9BCB4DC9A0AB32FCC3 /* LogEvent.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LogEvent.swift; path = Sources/LogEvent.swift; sourceTree = ""; }; + 407155CEAA8C92477629A14B47475F1D /* String Conversion.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "String Conversion.swift"; path = "Sources/String Conversion.swift"; sourceTree = ""; }; + 408F64023EB56273BB42761F929B897B /* AEADChaCha20Poly1305.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AEADChaCha20Poly1305.swift; path = Sources/CryptoSwift/AEAD/AEADChaCha20Poly1305.swift; sourceTree = ""; }; + 414DA9E2B626DAD1AB851A395D42E446 /* Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Promise.swift; path = Sources/Promise.swift; sourceTree = ""; }; + 43B7747EAA000C9B48B5D7B826AE8AA9 /* UIView+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIView+Promise.swift"; path = "Extensions/UIKit/Sources/UIView+Promise.swift"; sourceTree = ""; }; + 442EC95B2C112C5C782CE9612DE57E07 /* AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AnyPromise.h; path = Sources/AnyPromise.h; sourceTree = ""; }; + 457220DE54FCFECF49D27D4F0494EB51 /* CBCMAC.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CBCMAC.swift; path = Sources/CryptoSwift/CBCMAC.swift; sourceTree = ""; }; + 45780CFDD8941B525B61D0A0EFBAC14C /* UIViewController+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIViewController+AnyPromise.h"; path = "Extensions/UIKit/Sources/UIViewController+AnyPromise.h"; sourceTree = ""; }; + 459691924762DB7278BDA1860FC51C8E /* Array+Foundation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Array+Foundation.swift"; path = "Sources/CryptoSwift/Foundation/Array+Foundation.swift"; sourceTree = ""; }; + 4861BBBBB34E78E9429D35409F2D1E5F /* Web3+Options.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Options.swift"; path = "Sources/web3swift/Web3/Web3+Options.swift"; sourceTree = ""; }; + 48ECBEC5D1CFAE5AD46BEFF89E4ACC60 /* Pods-myWeb3WalletTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-myWeb3WalletTests-umbrella.h"; sourceTree = ""; }; + 492109BF7BF2C0FF599C257507DF3FF0 /* Web3+ERC165.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC165.swift"; path = "Sources/web3swift/Tokens/ERC165/Web3+ERC165.swift"; sourceTree = ""; }; + 494245F16C74B7E11B629E6D698264E8 /* secp256k1.c-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "secp256k1.c-dummy.m"; sourceTree = ""; }; + 499E0FE2E6CAD14D5EA32EE544804F2C /* field_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = field_impl.h; path = secp256k1/field_impl.h; sourceTree = ""; }; + 4A26062C707AB96E5E13A0125B15FE06 /* Rabbit+Foundation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Rabbit+Foundation.swift"; path = "Sources/CryptoSwift/Foundation/Rabbit+Foundation.swift"; sourceTree = ""; }; + 4B5D14DD6AF865E5CDA4F6D296D7766C /* FoundationTransport.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FoundationTransport.swift; path = Sources/Transport/FoundationTransport.swift; sourceTree = ""; }; + 4B6B955D7B2A183ACD0B6B950B5C893B /* field_5x52_int128_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = field_5x52_int128_impl.h; path = secp256k1/field_5x52_int128_impl.h; sourceTree = ""; }; + 4B9AE90348C0654C1AB4D4690A073401 /* BigUInt+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "BigUInt+Extensions.swift"; path = "Sources/web3swift/Convenience/BigUInt+Extensions.swift"; sourceTree = ""; }; + 4BE80D171181BA01FFD025A4FC4D6B4E /* Pods-myWeb3WalletTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-myWeb3WalletTests-acknowledgements.markdown"; sourceTree = ""; }; + 4C143EFCB8668F769B0C2692D4D882B4 /* HMAC.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HMAC.swift; path = Sources/CryptoSwift/HMAC.swift; sourceTree = ""; }; + 4C3A07D69D081152A01DECBBDF98D24A /* Engine.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Engine.swift; path = Sources/Engine/Engine.swift; sourceTree = ""; }; + 4D4496F8FBCD773F8A25A49F635CC63C /* Guarantee.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Guarantee.swift; path = Sources/Guarantee.swift; sourceTree = ""; }; + 4D50E33E27CBB4C4D9F7EBAE3849B7A5 /* eckey.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = eckey.h; path = secp256k1/eckey.h; sourceTree = ""; }; + 4DCC4A6DDDF04697E091B17F02A5660E /* KeystoreParams.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KeystoreParams.swift; path = Sources/web3swift/KeystoreManager/KeystoreParams.swift; sourceTree = ""; }; + 4E304701AA575E1B30297A9335082B9C /* ecdsa.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecdsa.h; path = secp256k1/ecdsa.h; sourceTree = ""; }; + 4EA0D117684CE8DF071445A5482A3E60 /* Collection+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Collection+Extension.swift"; path = "Sources/CryptoSwift/Collection+Extension.swift"; sourceTree = ""; }; + 4ED783EBC23A40B546A9CE880D97D376 /* MD5.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MD5.swift; path = Sources/CryptoSwift/MD5.swift; sourceTree = ""; }; + 4F202231EF82E4F2909CFEDE889D0C7A /* Box.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Box.swift; path = Sources/Box.swift; sourceTree = ""; }; + 4F865A846EA340AC2ACFF87476EC2E60 /* BigInt.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = BigInt.modulemap; sourceTree = ""; }; + 4F95702E2ECA0FE6E67FCF95250B5373 /* EthereumFilterEncodingExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EthereumFilterEncodingExtensions.swift; path = Sources/web3swift/Contract/EthereumFilterEncodingExtensions.swift; sourceTree = ""; }; + 4FA623E4738AB357087E678F3C2B8B80 /* Web3.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Web3.swift; path = Sources/web3swift/Web3/Web3.swift; sourceTree = ""; }; + 4FCECB2399C85B352286D927376CCC94 /* Web3+TxPool.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+TxPool.swift"; path = "Sources/web3swift/Web3/Web3+TxPool.swift"; sourceTree = ""; }; + 5064BE1943B37DFB8BD781A4F88B7360 /* EthereumContract.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EthereumContract.swift; path = Sources/web3swift/Contract/EthereumContract.swift; sourceTree = ""; }; + 50A8ABDB2A97CBECD57C02DF7D555AD4 /* Web3+Methods.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Methods.swift"; path = "Sources/web3swift/Web3/Web3+Methods.swift"; sourceTree = ""; }; + 513ACAB2D90C7668D5C441E7F44CD9F1 /* Promise+Web3+Personal+CreateAccount.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Personal+CreateAccount.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Personal+CreateAccount.swift"; sourceTree = ""; }; + 52B4F7541C12ABF10C884449E0032938 /* CryptoExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CryptoExtensions.swift; path = Sources/web3swift/Convenience/CryptoExtensions.swift; sourceTree = ""; }; + 53D054812BB57BDE3069179B7945A4A4 /* Exponentiation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Exponentiation.swift; path = Sources/Exponentiation.swift; sourceTree = ""; }; + 54F51094F339B9E2A49C1D43EFBDB098 /* Process+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Process+Promise.swift"; path = "Extensions/Foundation/Sources/Process+Promise.swift"; sourceTree = ""; }; + 55A821C8C1FC6F68C023E2E81651B18B /* CBC.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CBC.swift; path = Sources/CryptoSwift/BlockMode/CBC.swift; sourceTree = ""; }; + 56B11BC0240F751088C917372E40132A /* web3swift.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = web3swift.modulemap; sourceTree = ""; }; + 56DC1F5BA0194E3F08E0C6652CB89C9D /* Catchable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Catchable.swift; path = Sources/Catchable.swift; sourceTree = ""; }; + 5723B9D6A8FF3DBE29B669D7E3759A3B /* Pods-myWeb3WalletTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-myWeb3WalletTests-acknowledgements.plist"; sourceTree = ""; }; + 5773F22FF0BADB57519B5A58AC0A3246 /* Starscream-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Starscream-umbrella.h"; sourceTree = ""; }; + 57F0814F80E4EAB8D02ADA337CCECBA3 /* secp256k1.c-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "secp256k1.c-Info.plist"; sourceTree = ""; }; + 581816AC6AB72D6754E7F5AA6BEEEBDE /* NativeTypesEncoding+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NativeTypesEncoding+Extensions.swift"; path = "Sources/web3swift/Convenience/NativeTypesEncoding+Extensions.swift"; sourceTree = ""; }; + 586F3C5571C6E148E0D1950D6CBF1949 /* Strideable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Strideable.swift; path = Sources/Strideable.swift; sourceTree = ""; }; + 5931D9D39B790BA48631057F24CE6AAC /* field.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = field.h; path = secp256k1/field.h; sourceTree = ""; }; + 5C3AD67954329D1C955D54EF41C4508F /* NativeEngine.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NativeEngine.swift; path = Sources/Engine/NativeEngine.swift; sourceTree = ""; }; + 5C8F369ECC895BB94124AC2173EB80ED /* Words and Bits.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Words and Bits.swift"; path = "Sources/Words and Bits.swift"; sourceTree = ""; }; + 5C95BF67289C881540C0022C3E712E2C /* Prime Test.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Prime Test.swift"; path = "Sources/Prime Test.swift"; sourceTree = ""; }; + 5C9BF60EE9C79C985DCC648B95156DC4 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + 5CC9E23320B8991F34BC31A01FB21A1C /* ZeroPadding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ZeroPadding.swift; path = Sources/CryptoSwift/ZeroPadding.swift; sourceTree = ""; }; + 5CF0BA54E2B65D2328C3139726AB3F4B /* PCBC.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PCBC.swift; path = Sources/CryptoSwift/BlockMode/PCBC.swift; sourceTree = ""; }; + 5D37615679E9A1E496ED4D603AEE02C3 /* DigestType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DigestType.swift; path = Sources/CryptoSwift/DigestType.swift; sourceTree = ""; }; + 5DA6D1A7D4E05E1D0AD507800C434815 /* Web3+EventParser.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+EventParser.swift"; path = "Sources/web3swift/Web3/Web3+EventParser.swift"; sourceTree = ""; }; + 5E9C274FE23EF9CD989D4081E5A80DAB /* Web3+Eth.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Eth.swift"; path = "Sources/web3swift/Web3/Web3+Eth.swift"; sourceTree = ""; }; + 5EA7B564CF61E01CB14859E71ABA04D6 /* Pods-myWeb3Wallet-myWeb3WalletUITests-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-myWeb3Wallet-myWeb3WalletUITests-Info.plist"; sourceTree = ""; }; + 5F1ACC0AA6AEE873BA635D09E510F5F1 /* FoundationHTTPHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FoundationHTTPHandler.swift; path = Sources/Framer/FoundationHTTPHandler.swift; sourceTree = ""; }; + 5F37ABE5C51720188832DE43FE27AA1B /* Updatable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Updatable.swift; path = Sources/CryptoSwift/Updatable.swift; sourceTree = ""; }; + 6016EF1F606FED15790DC99D24384C6E /* Promise+Web3+Eth+SendRawTransaction.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+SendRawTransaction.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+SendRawTransaction.swift"; sourceTree = ""; }; + 605DCE9468F1ECAB3DE8DB3907D53C1D /* Web3+ERC721x.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC721x.swift"; path = "Sources/web3swift/Tokens/ERC721x/Web3+ERC721x.swift"; sourceTree = ""; }; + 60D9A3E52DF6179AF354672295718C6B /* NSNotificationCenter+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSNotificationCenter+AnyPromise.m"; path = "Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.m"; sourceTree = ""; }; + 61329F3723A6B1ABEF3BBCD12675C0C1 /* Web3+ReadingTransaction.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ReadingTransaction.swift"; path = "Sources/web3swift/Web3/Web3+ReadingTransaction.swift"; sourceTree = ""; }; + 616F9AB4DE59A05019261F9A89028DC5 /* ChaCha20.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ChaCha20.swift; path = Sources/CryptoSwift/ChaCha20.swift; sourceTree = ""; }; + 6185835291CFC5AA4425DEBC5841A13C /* num_gmp.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = num_gmp.h; path = secp256k1/num_gmp.h; sourceTree = ""; }; + 61D906C63EE673FDF08E44B02D695E83 /* ABI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ABI.swift; path = Sources/web3swift/EthereumABI/ABI.swift; sourceTree = ""; }; + 61F1F5C6B7C7A8680F81CDEB5CDD4D8B /* AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AnyPromise.m; path = Sources/AnyPromise.m; sourceTree = ""; }; + 61F9291E88C2B8D95351C63BBAC5A220 /* secp256k1.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = secp256k1.h; path = secp256k1/include/secp256k1.h; sourceTree = ""; }; + 629BF4D4B84DA533D5B163D4E919D015 /* secp256k1_ec_mult_static_context.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = secp256k1_ec_mult_static_context.h; path = secp256k1/secp256k1_ec_mult_static_context.h; sourceTree = ""; }; + 65E6BD3495BF0509B852B4FD92DF2989 /* web3swift-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "web3swift-umbrella.h"; sourceTree = ""; }; + 662915FBC8EFD87F9F690D0B12FC9D41 /* String+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "String+Extension.swift"; path = "Sources/CryptoSwift/String+Extension.swift"; sourceTree = ""; }; + 665EC9936D9FB294CDFDD2B00D996F69 /* Base58.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Base58.swift; path = Sources/web3swift/Convenience/Base58.swift; sourceTree = ""; }; + 67DE942FB3DAA92CE782989AF2C19632 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; }; + 67E49E4C0BCA77B52DCEAFDAF884CD2C /* PromiseKit-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PromiseKit-prefix.pch"; sourceTree = ""; }; + 686CF63072B25624DF5326A314DB59DB /* UInt32+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UInt32+Extension.swift"; path = "Sources/CryptoSwift/UInt32+Extension.swift"; sourceTree = ""; }; + 694009935F1F74664D4B4E938B5F1490 /* Utils.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Utils.swift; path = Sources/CryptoSwift/Utils.swift; sourceTree = ""; }; + 699F27F269D20FAD83C7D3B79A5C5074 /* Web3+MutatingTransaction.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+MutatingTransaction.swift"; path = "Sources/web3swift/Web3/Web3+MutatingTransaction.swift"; sourceTree = ""; }; + 69B470CEFDB78B1B81B0DAF2D4FBDBA4 /* Promise+Web3+Eth+SendTransaction.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+SendTransaction.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+SendTransaction.swift"; sourceTree = ""; }; + 69C28A10F48C7D37E1E65B1E626C6782 /* BigInt-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "BigInt-umbrella.h"; sourceTree = ""; }; + 6A4DE7CB1EA88AC3E3FD9EC3D87BB04D /* ResourceBundle-Browser-web3swift-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "ResourceBundle-Browser-web3swift-Info.plist"; sourceTree = ""; }; + 6B57FF8149DACE439778C727600D5548 /* BIP32HDNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BIP32HDNode.swift; path = Sources/web3swift/KeystoreManager/BIP32HDNode.swift; sourceTree = ""; }; + 6B7F37C23C7BD91529AFC9D9C3B89350 /* AEAD.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AEAD.swift; path = Sources/CryptoSwift/AEAD/AEAD.swift; sourceTree = ""; }; + 6C196FA6A48283DE5A44E4FCB71252E8 /* AnyPromise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyPromise.swift; path = Sources/AnyPromise.swift; sourceTree = ""; }; + 6CAA05940EADD5E5A01859B5B9BA567F /* Web3+ERC1644.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1644.swift"; path = "Sources/web3swift/Tokens/ERC1644/Web3+ERC1644.swift"; sourceTree = ""; }; + 6CF1331659E806368CFFAD37192BA01A /* field_10x26_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = field_10x26_impl.h; path = secp256k1/field_10x26_impl.h; sourceTree = ""; }; + 6D011B0CEC9AC062DC89BC9C1EC05806 /* field_5x52.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = field_5x52.h; path = secp256k1/field_5x52.h; sourceTree = ""; }; + 6D47AE3AEBABE33FF5939852216CAA95 /* Web3+ERC777.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC777.swift"; path = "Sources/web3swift/Tokens/ERC777/Web3+ERC777.swift"; sourceTree = ""; }; + 6DF004A0692AE90EAC3F6F16BDF07740 /* BIP32Keystore.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BIP32Keystore.swift; path = Sources/web3swift/KeystoreManager/BIP32Keystore.swift; sourceTree = ""; }; + 6F928DE9F728F034C42EF3E84EBB5B6A /* Multiplication.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Multiplication.swift; path = Sources/Multiplication.swift; sourceTree = ""; }; + 700FBEA2D7EAA32E60481668BFC38F17 /* CryptoSwift.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = CryptoSwift.debug.xcconfig; sourceTree = ""; }; + 7239B0649BFDF00625943FEDFAD57C9B /* field_5x52_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = field_5x52_impl.h; path = secp256k1/field_5x52_impl.h; sourceTree = ""; }; + 735CD37CFC646A0F0361C7EFB6F5B8BE /* Pods-myWeb3WalletTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-myWeb3WalletTests.modulemap"; sourceTree = ""; }; + 73EA7956B330A45808E9440BEF76D6D7 /* CryptoSwift-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "CryptoSwift-dummy.m"; sourceTree = ""; }; + 7509ED605AC6A0930966F33117BB9895 /* Promise+Batching.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Batching.swift"; path = "Sources/web3swift/Promises/Promise+Batching.swift"; sourceTree = ""; }; + 752098116910D32A020C6FA1EB9F38AA /* Data+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Data+Extension.swift"; path = "Sources/CryptoSwift/Foundation/Data+Extension.swift"; sourceTree = ""; }; + 758935E87C6104A90D397DA9D6DE0FD9 /* Pods-myWeb3Wallet-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-myWeb3Wallet-acknowledgements.markdown"; sourceTree = ""; }; + 75ED9FE60BF10CD99C97EABEB33FF1CF /* PromiseKit.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PromiseKit.h; path = Sources/PromiseKit.h; sourceTree = ""; }; + 771143AE964D2F3B727D81EADA6425C6 /* Web3+ST20.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ST20.swift"; path = "Sources/web3swift/Tokens/ST20/Web3+ST20.swift"; sourceTree = ""; }; + 78FCD380A8DC8B60B8940546BA368A71 /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Extensions.swift; path = Sources/web3swift/EthereumAddress/Extensions.swift; sourceTree = ""; }; + 79BCFCB28731207C5F021A408D5A1EEC /* ISO10126Padding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ISO10126Padding.swift; path = Sources/CryptoSwift/ISO10126Padding.swift; sourceTree = ""; }; + 79E64ADA63C8893846700495EA1FC27C /* Shifts.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Shifts.swift; path = Sources/Shifts.swift; sourceTree = ""; }; + 7A751A1E4864468D4E52A81FC5BDDFDB /* ComparisonExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ComparisonExtensions.swift; path = Sources/web3swift/Contract/ComparisonExtensions.swift; sourceTree = ""; }; + 7A9073374C5D843FB300330AAAC2ECF1 /* web3swift-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "web3swift-Info.plist"; sourceTree = ""; }; + 7B6DFC9E27C5C2579817751B89E04F28 /* Data Conversion.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Data Conversion.swift"; path = "Sources/Data Conversion.swift"; sourceTree = ""; }; + 7BC2E55A1BE5983AEEDFFB5B980A621C /* Starscream.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Starscream.debug.xcconfig; sourceTree = ""; }; + 7BC8ACC3ACEA679C2AAC22532DEBE18F /* race.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = race.swift; path = Sources/race.swift; sourceTree = ""; }; + 7C474592AE45D1B74EC342FF072BA03E /* Array+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Array+Extension.swift"; path = "Sources/web3swift/Convenience/Array+Extension.swift"; sourceTree = ""; }; + 7E0AD3992F79794304FDD80D8F1AF7D5 /* HKDF.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HKDF.swift; path = Sources/CryptoSwift/HKDF.swift; sourceTree = ""; }; + 7E1E65378BE014016F6FA3C48DB5D9EA /* BigInt-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "BigInt-Info.plist"; sourceTree = ""; }; + 807F4EF0F6896F7BEB55DDE65E4CB28F /* Compression.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Compression.swift; path = Sources/Compression/Compression.swift; sourceTree = ""; }; + 80E520F4DA45AF0A1A997471995473E8 /* secp256k1_main.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = secp256k1_main.h; path = secp256k1/secp256k1_main.h; sourceTree = ""; }; + 812A3FAA807BBF520E834E8177CDA805 /* field_10x26.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = field_10x26.h; path = secp256k1/field_10x26.h; sourceTree = ""; }; + 824063EF324B04F2AADFB9E47CDA422A /* UInt16+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UInt16+Extension.swift"; path = "Sources/CryptoSwift/UInt16+Extension.swift"; sourceTree = ""; }; + 82B356B37EA2E9BF9C51583849D37CAD /* Resolver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Resolver.swift; path = Sources/Resolver.swift; sourceTree = ""; }; + 82FB779DA3F23E81B13234AB52617EF6 /* Bit.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Bit.swift; path = Sources/CryptoSwift/Bit.swift; sourceTree = ""; }; + 830413FA8967EA278558006C271B1D16 /* PKCS7Padding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PKCS7Padding.swift; path = Sources/CryptoSwift/PKCS/PKCS7Padding.swift; sourceTree = ""; }; + 83EB318EEB278287224355CBE3049A48 /* Random.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Random.swift; path = Sources/Random.swift; sourceTree = ""; }; + 8456FEA753DE9A90D304EA54DFD5DAD3 /* NSURLSession+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSURLSession+AnyPromise.m"; path = "Extensions/Foundation/Sources/NSURLSession+AnyPromise.m"; sourceTree = ""; }; + 8552720D720D203E2444F5263C6A4021 /* PBKDF1.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PBKDF1.swift; path = Sources/CryptoSwift/PKCS/PBKDF1.swift; sourceTree = ""; }; + 856EEADEDD158D4873F666AE218DE570 /* PMKUIKit.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PMKUIKit.h; path = Extensions/UIKit/Sources/PMKUIKit.h; sourceTree = ""; }; + 85D99C55C6D2A7368634E17D0FC07D22 /* secp256k1.c */ = {isa = PBXFileReference; includeInIndex = 1; name = secp256k1.c; path = secp256k1/secp256k1.c; sourceTree = ""; }; + 861A826AE843EA63A9502FDE98A45BB7 /* num_gmp_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = num_gmp_impl.h; path = secp256k1/num_gmp_impl.h; sourceTree = ""; }; + 871B8E61AECB22BF7E4F511683743783 /* Pods-myWeb3Wallet-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-myWeb3Wallet-Info.plist"; sourceTree = ""; }; + 878D77F928A64BCC11C2A541B02CA9F2 /* Pods-myWeb3Wallet.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-myWeb3Wallet.release.xcconfig"; sourceTree = ""; }; + 889E3ECE5439BC9C800DFD88ED2F04BD /* AES.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AES.swift; path = Sources/CryptoSwift/AES.swift; sourceTree = ""; }; + 8907A4B63AEF5B00260E490E38ACCE3E /* BigUInt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BigUInt.swift; path = Sources/BigUInt.swift; sourceTree = ""; }; + 891B2270823847ED23F2ECFC28F935EC /* Starscream */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Starscream; path = Starscream.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 89216AD64050A687049C2812AE6F2D3D /* secp256k1.c.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = secp256k1.c.modulemap; sourceTree = ""; }; + 89E3E5798A0F9C8B82F89E4AA1C9B933 /* firstly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = firstly.swift; path = Sources/firstly.swift; sourceTree = ""; }; + 8A2449DF78D58AD33A7C7504BB3F38A0 /* web3swift */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = web3swift; path = web3swift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 8AA0DDDD58D43515BE066493834EE7F7 /* HTTPHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HTTPHandler.swift; path = Sources/Framer/HTTPHandler.swift; sourceTree = ""; }; + 8AFCDD28CDD4C6AB23094990AABE6DE9 /* AES.Cryptors.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AES.Cryptors.swift; path = Sources/CryptoSwift/AES.Cryptors.swift; sourceTree = ""; }; + 8C020773045EBAC1BB6CC4DCF9CF70E8 /* Pods-myWeb3WalletTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-myWeb3WalletTests-dummy.m"; sourceTree = ""; }; + 8D144717D9392F89398A95CE943E7FCD /* ecmult_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecmult_impl.h; path = secp256k1/ecmult_impl.h; sourceTree = ""; }; + 8DB09F270FE9B4BDA5AFBD4357E646CE /* Pods-myWeb3Wallet-myWeb3WalletUITests */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = "Pods-myWeb3Wallet-myWeb3WalletUITests"; path = Pods_myWeb3Wallet_myWeb3WalletUITests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 8DC49762D0D20DA70D0F705EC08E302F /* after.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = after.m; path = Sources/after.m; sourceTree = ""; }; + 91BB24BA472AF523E913108C9AA301F2 /* BigInt */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = BigInt; path = BigInt.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 91E170E8B0E46F448434AEDA45BE7201 /* Comparable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Comparable.swift; path = Sources/Comparable.swift; sourceTree = ""; }; + 9217736E16B090E354FA8D7B1F16A693 /* BigInt.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = BigInt.debug.xcconfig; sourceTree = ""; }; + 9272051904F9CDACCBD8DE527C05C8A0 /* PMKFoundation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PMKFoundation.h; path = Extensions/Foundation/Sources/PMKFoundation.h; sourceTree = ""; }; + 92BD1F11AAB93E6E693F70645ACCB9D3 /* Starscream.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Starscream.release.xcconfig; sourceTree = ""; }; + 93782C7F3F539959B04BE436295FD94A /* WSCompression.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WSCompression.swift; path = Sources/Compression/WSCompression.swift; sourceTree = ""; }; + 93B89C94E972705C6809F63A2BE2EAAE /* web3swift.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = web3swift.release.xcconfig; sourceTree = ""; }; + 93E56996042925D46F3368CAD4474742 /* Pods-myWeb3Wallet-myWeb3WalletUITests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-myWeb3Wallet-myWeb3WalletUITests-acknowledgements.plist"; sourceTree = ""; }; + 94545F2C1973B711F0E957917ED7B36E /* ABITypeParser.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ABITypeParser.swift; path = Sources/web3swift/EthereumABI/ABITypeParser.swift; sourceTree = ""; }; + 94D92C0E313BED051BC11C45A95CCFFF /* Data+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Data+Extensions.swift"; path = "Sources/DataBytes/Data+Extensions.swift"; sourceTree = ""; }; + 94EDD79DD8C072828820F9310A7F25AB /* HMAC+Foundation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "HMAC+Foundation.swift"; path = "Sources/CryptoSwift/Foundation/HMAC+Foundation.swift"; sourceTree = ""; }; + 95E71976E5850018C27C15AC878DC296 /* ecdh_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecdh_impl.h; path = secp256k1/ecdh_impl.h; sourceTree = ""; }; + 97603D675B6C3596041F441A64D65A89 /* NSTask+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSTask+AnyPromise.m"; path = "Extensions/Foundation/Sources/NSTask+AnyPromise.m"; sourceTree = ""; }; + 9763CCFBEDDC125312CD1FF164DB1DA5 /* CFB.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CFB.swift; path = Sources/CryptoSwift/BlockMode/CFB.swift; sourceTree = ""; }; + 98821C698CAE291DB7FC2E6A72ECB7D4 /* Web3+InfuraProviders.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+InfuraProviders.swift"; path = "Sources/web3swift/Web3/Web3+InfuraProviders.swift"; sourceTree = ""; }; + 98DDDE228F4BC29D191AE78AD7AD59C6 /* Promise+Web3+Eth+GetTransactionReceipt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+GetTransactionReceipt.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionReceipt.swift"; sourceTree = ""; }; + 98E59BC358BEF788BF007F56FA3381D1 /* when.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = when.m; path = Sources/when.m; sourceTree = ""; }; + 9A02DDEC9858A78BEA9C9EAED811BC17 /* CompactMap.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CompactMap.swift; path = Sources/CryptoSwift/CompactMap.swift; sourceTree = ""; }; + 9A7C267F2A6E93388DE89B4D3D823E13 /* BrowserViewController.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BrowserViewController.swift; path = Sources/web3swift/Browser/BrowserViewController.swift; sourceTree = ""; }; + 9B00321B0B14B4FF897F2CF5B6415C3C /* Web3+ERC20.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC20.swift"; path = "Sources/web3swift/Tokens/ERC20/Web3+ERC20.swift"; sourceTree = ""; }; + 9B580076A33C54363F117FC48118156B /* Integer Conversion.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Integer Conversion.swift"; path = "Sources/Integer Conversion.swift"; sourceTree = ""; }; + 9B72CCFE3D10F1F6A2457EC5730BA509 /* Promise+Web3+Eth+GetAccounts.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+GetAccounts.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+GetAccounts.swift"; sourceTree = ""; }; + 9C1F8F8C962B269D1B535A7E69211345 /* Codable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Codable.swift; path = Sources/Codable.swift; sourceTree = ""; }; + 9CDA08FC40E440445F5B1C2087699FA4 /* Data+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Data+Extension.swift"; path = "Sources/web3swift/Convenience/Data+Extension.swift"; sourceTree = ""; }; + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 9DA7F20BAF89DD9B24B85E9A1A2B4FD2 /* ENSReverseRegistrar.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ENSReverseRegistrar.swift; path = Sources/web3swift/Utils/ENS/ENSReverseRegistrar.swift; sourceTree = ""; }; + 9DBB832EE6B1A46B6B06C03F1FB46839 /* Promise+Web3+Eth+GetGasPrice.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+GetGasPrice.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+GetGasPrice.swift"; sourceTree = ""; }; + 9DFDD8684C07E988EE7BEF8AB894F1C3 /* Web3+ERC888.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC888.swift"; path = "Sources/web3swift/Tokens/ERC888/Web3+ERC888.swift"; sourceTree = ""; }; + 9F0B4B1C5D1772BD09B1E3478511FBC6 /* Starscream.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Starscream.modulemap; sourceTree = ""; }; + A1086E5EB59F24E36E2556B3270BE06F /* ENS.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ENS.swift; path = Sources/web3swift/Utils/ENS/ENS.swift; sourceTree = ""; }; + A131EC03EF93B5304C3DB4E559307C3B /* Scrypt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Scrypt.swift; path = Sources/CryptoSwift/Scrypt.swift; sourceTree = ""; }; + A24FCB02E998E133E5325631033AF027 /* Promise+Web3+Eth+GetTransactionCount.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+GetTransactionCount.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionCount.swift"; sourceTree = ""; }; + A2ED9A418D702E70593766E47BF84FA5 /* Web3+Protocols.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Protocols.swift"; path = "Sources/web3swift/Web3/Web3+Protocols.swift"; sourceTree = ""; }; + A35804F1DCE3C2A4931790E77FC2F701 /* Pods-myWeb3Wallet-myWeb3WalletUITests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-myWeb3Wallet-myWeb3WalletUITests-dummy.m"; sourceTree = ""; }; + A3EBD086332607B408BD6F878EA9A500 /* OCB.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = OCB.swift; path = Sources/CryptoSwift/BlockMode/OCB.swift; sourceTree = ""; }; + A4F1C951C5378C2C015177FE8E9BBF92 /* fwd.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = fwd.h; path = Sources/fwd.h; sourceTree = ""; }; + A524EF14F2890814986F7449EAA84F7F /* Pods-myWeb3WalletTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-myWeb3WalletTests.debug.xcconfig"; sourceTree = ""; }; + A546A1EBF9CE4405F7461B4753D53B47 /* EventFiltering.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EventFiltering.swift; path = Sources/web3swift/Contract/EventFiltering.swift; sourceTree = ""; }; + A5F4F7EFAF476543587E0F3608C9CA8B /* Web3+Instance.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Instance.swift"; path = "Sources/web3swift/Web3/Web3+Instance.swift"; sourceTree = ""; }; + A6224520D335600BCB2E7747D6687B8A /* Int+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Int+Extension.swift"; path = "Sources/CryptoSwift/Int+Extension.swift"; sourceTree = ""; }; + A788EBC997CC72DFE928373C05F3C475 /* Thenable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Thenable.swift; path = Sources/Thenable.swift; sourceTree = ""; }; + A8BBEB50E65BE6B493DCFE9A2BCCE825 /* scalar_low.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar_low.h; path = secp256k1/scalar_low.h; sourceTree = ""; }; + AA032FABD784E8D9C3094CCA56F9FAAE /* secp256k1.c-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "secp256k1.c-umbrella.h"; sourceTree = ""; }; + AA1FF168A47F7A82F2DFBA4040E00A10 /* SHA3.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SHA3.swift; path = Sources/CryptoSwift/SHA3.swift; sourceTree = ""; }; + AA8F1F5587506D634EFF2229CAE76FE8 /* ENSBaseRegistrar.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ENSBaseRegistrar.swift; path = Sources/web3swift/Utils/ENS/ENSBaseRegistrar.swift; sourceTree = ""; }; + AAA635D78BC74313670E92DFD4464F7F /* after.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = after.swift; path = Sources/after.swift; sourceTree = ""; }; + ABC21DF8C117534CE67E549DA43A59F6 /* Web3+Utils.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Utils.swift"; path = "Sources/web3swift/Web3/Web3+Utils.swift"; sourceTree = ""; }; + ACF496E6C59563E3B2D37AFF0647AA5E /* Web3+ERC1376.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1376.swift"; path = "Sources/web3swift/Tokens/ERC1376/Web3+ERC1376.swift"; sourceTree = ""; }; + AD0E7C344DBA5BB5BD963F05B4DC42F0 /* scratch_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scratch_impl.h; path = secp256k1/scratch_impl.h; sourceTree = ""; }; + AE2FF8CBBE01A4A94FF02974852301FD /* secp256k1.c.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = secp256k1.c.release.xcconfig; sourceTree = ""; }; + AE35160BC5311A2CFE1E6257480BF4D1 /* race.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = race.m; path = Sources/race.m; sourceTree = ""; }; + AED149E8CB2E262FF979BFD4E5640005 /* ENSResolver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ENSResolver.swift; path = Sources/web3swift/Utils/ENS/ENSResolver.swift; sourceTree = ""; }; + AF96BD26A8980F3C83466AD777577DB3 /* secp256k1-config.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "secp256k1-config.h"; path = "secp256k1/secp256k1-config.h"; sourceTree = ""; }; + AFADECE767F8B6CE7D6F0151072D9120 /* PKCS7.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PKCS7.swift; path = Sources/CryptoSwift/PKCS/PKCS7.swift; sourceTree = ""; }; + B1610DC37FC079B6D1D83472DBA4DA12 /* NSRegularExpressionExtension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NSRegularExpressionExtension.swift; path = Sources/web3swift/Convenience/NSRegularExpressionExtension.swift; sourceTree = ""; }; + B283E7DB525627BCDF8B64F25F729738 /* Promise+HttpProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+HttpProvider.swift"; path = "Sources/web3swift/Promises/Promise+HttpProvider.swift"; sourceTree = ""; }; + B2D684B79FC7FFF779E5AF645F1E8129 /* RIPEMD160+StackOveflow.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "RIPEMD160+StackOveflow.swift"; path = "Sources/web3swift/Convenience/RIPEMD160+StackOveflow.swift"; sourceTree = ""; }; + B373FED6638B961B7A97AABD5280E615 /* Promise+Web3+Eth+Call.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+Call.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+Call.swift"; sourceTree = ""; }; + B3B83F5426FCB99B70C9BA58611231F2 /* browser.min.js */ = {isa = PBXFileReference; includeInIndex = 1; name = browser.min.js; path = Sources/web3swift/Browser/browser.min.js; sourceTree = ""; }; + B3CA76593B24771BFE57E65E82FABF4D /* hash.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = hash.h; path = secp256k1/hash.h; sourceTree = ""; }; + B4C26BFD4C4F0041CB43065B7C15190C /* Blowfish.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Blowfish.swift; path = Sources/CryptoSwift/Blowfish.swift; sourceTree = ""; }; + B4FC29C6A531D0517444640A0FDF354E /* Pods-myWeb3Wallet-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-myWeb3Wallet-acknowledgements.plist"; sourceTree = ""; }; + B516CBBE190C154B351A76809BF9B33B /* KeystoreManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KeystoreManager.swift; path = Sources/web3swift/KeystoreManager/KeystoreManager.swift; sourceTree = ""; }; + B7E95C968FFABFDA532F2638C4F909A4 /* EthereumAddress.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EthereumAddress.swift; path = Sources/web3swift/EthereumAddress/EthereumAddress.swift; sourceTree = ""; }; + B7F3600020FB93358C3041F0C10FA382 /* Pods-myWeb3Wallet-myWeb3WalletUITests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-myWeb3Wallet-myWeb3WalletUITests.debug.xcconfig"; sourceTree = ""; }; + B87DE6711B6E12078EA7C872582DA976 /* PromiseKit-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PromiseKit-dummy.m"; sourceTree = ""; }; + B913B0C1A0F49DC0B7ADA73EC64F3E7B /* IBAN.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = IBAN.swift; path = Sources/web3swift/KeystoreManager/IBAN.swift; sourceTree = ""; }; + B9418ED7506E09852282E4C0298F4CF2 /* BlockMode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BlockMode.swift; path = Sources/CryptoSwift/BlockMode/BlockMode.swift; sourceTree = ""; }; + BAD73345F8FD30B964FB9152047D4B8C /* EIP681.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EIP681.swift; path = Sources/web3swift/Utils/EIP/EIP681.swift; sourceTree = ""; }; + BB6A86B206A38FF5301C697059CED678 /* hang.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = hang.m; path = Sources/hang.m; sourceTree = ""; }; + BB758BE37B19325C036A0DBACBEA6C27 /* Web3+SecurityToken.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+SecurityToken.swift"; path = "Sources/web3swift/Tokens/ST20/Web3+SecurityToken.swift"; sourceTree = ""; }; + BB7B5E4ADA577B5E93F2C0FC6E8843FC /* UInt8+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UInt8+Extension.swift"; path = "Sources/CryptoSwift/UInt8+Extension.swift"; sourceTree = ""; }; + BC4CF0C81A7F4E6F47BFB9B293C8B441 /* PKCS5.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PKCS5.swift; path = Sources/CryptoSwift/PKCS/PKCS5.swift; sourceTree = ""; }; + BCC3DC989D5E95AE5DFB7CEF5F4A6825 /* String+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "String+Extension.swift"; path = "Sources/web3swift/Convenience/String+Extension.swift"; sourceTree = ""; }; + BCEEABD2FC5B664CD01F65462355E766 /* OFB.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = OFB.swift; path = Sources/CryptoSwift/BlockMode/OFB.swift; sourceTree = ""; }; + BD500378BD304B7A5348A9CB1F342D3B /* TCPTransport.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TCPTransport.swift; path = Sources/Transport/TCPTransport.swift; sourceTree = ""; }; + BD85842A42223204E3C0C2184192C905 /* Transport.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Transport.swift; path = Sources/Transport/Transport.swift; sourceTree = ""; }; + BDBC9ABAC77FB39A9D79EFB025FD3C04 /* CryptoSwift-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "CryptoSwift-prefix.pch"; sourceTree = ""; }; + BE044572A30D307268519834DCA2D378 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Sources/Error.swift; sourceTree = ""; }; + BEA93987C60BB062C9F16D11BB8D27AB /* Pods-myWeb3Wallet-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-myWeb3Wallet-frameworks.sh"; sourceTree = ""; }; + BF02184566636520F4D8470933669F05 /* scalar_low_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar_low_impl.h; path = secp256k1/scalar_low_impl.h; sourceTree = ""; }; + BF9BF56B15E811B9D10946DD368C9411 /* Promise+Web3+Personal+Sign.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Personal+Sign.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Personal+Sign.swift"; sourceTree = ""; }; + BFBAD5703C2622CB9475778D3FF7684B /* BatchedCollection.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BatchedCollection.swift; path = Sources/CryptoSwift/BatchedCollection.swift; sourceTree = ""; }; + C05291B76391595ED8B3B285B79F78EC /* Promise+Web3+Eth+GetBlockNumber.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+GetBlockNumber.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockNumber.swift"; sourceTree = ""; }; + C10E9CF99CBE40D30321A9990E3780F3 /* SHA2.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SHA2.swift; path = Sources/CryptoSwift/SHA2.swift; sourceTree = ""; }; + C158F576B708193B339431561C565F0A /* String+FoundationExtension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "String+FoundationExtension.swift"; path = "Sources/CryptoSwift/Foundation/String+FoundationExtension.swift"; sourceTree = ""; }; + C190B059191445A1D285D4CE9ABFCC0A /* Cryptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Cryptor.swift; path = Sources/CryptoSwift/Cryptor.swift; sourceTree = ""; }; + C19976C618B5991508555766A6C58D33 /* Web3+Eventloop.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Eventloop.swift"; path = "Sources/web3swift/Web3/Web3+Eventloop.swift"; sourceTree = ""; }; + C1CBAF4C9C1F1D95FC1A9EE6D61DF7BB /* Promise+Web3+Eth+GetBlockByNumber.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+GetBlockByNumber.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByNumber.swift"; sourceTree = ""; }; + C1DF43A48C95155896DC1F3F4407706C /* EIP67Code.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EIP67Code.swift; path = Sources/web3swift/Utils/EIP/EIP67Code.swift; sourceTree = ""; }; + C2194F52EA9713769E689181030DF7B4 /* Web3+Constants.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Constants.swift"; path = "Sources/web3swift/Web3/Web3+Constants.swift"; sourceTree = ""; }; + C2E188E17AF245DF4E409CBCCAA53A13 /* Web3+ERC1594.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1594.swift"; path = "Sources/web3swift/Tokens/ERC1594/Web3+ERC1594.swift"; sourceTree = ""; }; + C321EB417B11D2E05909E2F4DBF30D9A /* FrameCollector.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FrameCollector.swift; path = Sources/Framer/FrameCollector.swift; sourceTree = ""; }; + C3D558C8C4FC4AADF09ED9EA94D9D6A9 /* CryptoSwift.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = CryptoSwift.release.xcconfig; sourceTree = ""; }; + C513F6340AD8C6EF588154BB1FBB30DB /* Web3+Contract.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Contract.swift"; path = "Sources/web3swift/Web3/Web3+Contract.swift"; sourceTree = ""; }; + C51800E5F54721AF0D7AEE62A916CB2F /* CoreImage.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreImage.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/CoreImage.framework; sourceTree = DEVELOPER_DIR; }; + C560E0C20A6F6E769700B4AB346EEBDC /* num.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = num.h; path = secp256k1/num.h; sourceTree = ""; }; + C563C261B9470D2D28A526E4BF747E2C /* CustomStringConvertible.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CustomStringConvertible.swift; path = Sources/CustomStringConvertible.swift; sourceTree = ""; }; + C6E9D7C085E89CCA54E04610C615C155 /* Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks.sh"; sourceTree = ""; }; + C798B4F4D8097C83111B844CBB1C3CE6 /* scalar.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar.h; path = secp256k1/scalar.h; sourceTree = ""; }; + C7DD12C61F348A063E8ADC23768D4327 /* ABIParsing.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ABIParsing.swift; path = Sources/web3swift/EthereumABI/ABIParsing.swift; sourceTree = ""; }; + C9AA32BC8F1750426BE685F2689370B7 /* FoundationHTTPServerHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FoundationHTTPServerHandler.swift; path = Sources/Framer/FoundationHTTPServerHandler.swift; sourceTree = ""; }; + CAC7EB22892368AC2FB24D3C9A74B5BF /* Promise+Web3+Eth+GetBalance.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+GetBalance.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+GetBalance.swift"; sourceTree = ""; }; + CBC606D4D73D4D6373FD43179F3DF3C5 /* ETHRegistrarController.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ETHRegistrarController.swift; path = Sources/web3swift/Utils/ENS/ETHRegistrarController.swift; sourceTree = ""; }; + CD4F76F68EB476ECF93172F941394A64 /* BlockDecryptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BlockDecryptor.swift; path = Sources/CryptoSwift/BlockDecryptor.swift; sourceTree = ""; }; + CDC065C0E64F5101BC23C8AC17738F7E /* scalar_4x64_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar_4x64_impl.h; path = secp256k1/scalar_4x64_impl.h; sourceTree = ""; }; + CDDD26AA5A7B20DAE7F39D14BDC4C092 /* Web3+ERC1155.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1155.swift"; path = "Sources/web3swift/Tokens/ERC1155/Web3+ERC1155.swift"; sourceTree = ""; }; + CEE308A0279FEF1970F5AE55A59B0784 /* Web3+ERC721.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC721.swift"; path = "Sources/web3swift/Tokens/ERC721/Web3+ERC721.swift"; sourceTree = ""; }; + CFC32DF7FA786FBF7FC7BF4877244E6A /* Web3+ERC1633.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1633.swift"; path = "Sources/web3swift/Tokens/ERC1633/Web3+ERC1633.swift"; sourceTree = ""; }; + D0A930E640D89DFE4D0E110591FB7076 /* Promise+Web3+TxPool.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+TxPool.swift"; path = "Sources/web3swift/Promises/Promise+Web3+TxPool.swift"; sourceTree = ""; }; + D0FF9C21D8BBE37AEAA3240D6DBB2CA2 /* field_5x52_asm_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = field_5x52_asm_impl.h; path = secp256k1/field_5x52_asm_impl.h; sourceTree = ""; }; + D1A344D248E1F69564A9F80880BF7F1B /* Pods-myWeb3Wallet.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-myWeb3Wallet.modulemap"; sourceTree = ""; }; + D263F99BE4CC8113CEC0DF611249ADB8 /* Digest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Digest.swift; path = Sources/CryptoSwift/Digest.swift; sourceTree = ""; }; + D295F0B7EA16BF13CF0BBFAF36C10963 /* Starscream-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Starscream-Info.plist"; sourceTree = ""; }; + D444BC3C307070B4F5F3F480423838AD /* BloomFilter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BloomFilter.swift; path = Sources/web3swift/Transaction/BloomFilter.swift; sourceTree = ""; }; + D4D2746F0470DC43876ADAF60BDEF00E /* Web3+ERC1410.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1410.swift"; path = "Sources/web3swift/Tokens/ERC1410/Web3+ERC1410.swift"; sourceTree = ""; }; + D4F1BDCD30EFA57E3CA28CD4CF2D7CCF /* ABIElements.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ABIElements.swift; path = Sources/web3swift/EthereumABI/ABIElements.swift; sourceTree = ""; }; + D50122651622201633327B4D22B90560 /* Starscream-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Starscream-dummy.m"; sourceTree = ""; }; + D52E15043DB745FE9026A43E0E10B902 /* Web3+HttpProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+HttpProvider.swift"; path = "Sources/web3swift/Web3/Web3+HttpProvider.swift"; sourceTree = ""; }; + D5BEDCE22D40961DE68C60CB6AE573A7 /* recovery_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = recovery_impl.h; path = secp256k1/recovery_impl.h; sourceTree = ""; }; + D7459ACC386268D5B3B45D2F4EB04631 /* group_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = group_impl.h; path = secp256k1/group_impl.h; sourceTree = ""; }; + D77426DA53B5BAC9390B9F12C1142183 /* PromiseKit-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PromiseKit-umbrella.h"; sourceTree = ""; }; + D78518CF508AF000188545E3388F00CC /* Promise+Web3+Eth+EstimateGas.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+EstimateGas.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+EstimateGas.swift"; sourceTree = ""; }; + D7B8332B6EEE60574C9B4CB468B81524 /* Authenticator.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Authenticator.swift; path = Sources/CryptoSwift/Authenticator.swift; sourceTree = ""; }; + D81298FD65A20CC32C6FCEA447C6F8B3 /* when.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = when.swift; path = Sources/when.swift; sourceTree = ""; }; + D9BED5D4428FA6E60B2D58D86DACD87E /* Subtraction.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Subtraction.swift; path = Sources/Subtraction.swift; sourceTree = ""; }; + D9E59212A5A8295E5F180ED605A1CDE7 /* CTR.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CTR.swift; path = Sources/CryptoSwift/BlockMode/CTR.swift; sourceTree = ""; }; + DA2CE9B55293B0E2D65F19AB1EC631B0 /* BigInt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BigInt.swift; path = Sources/BigInt.swift; sourceTree = ""; }; + DCAEE90730AA63BAC2B8BA0C11298D49 /* GCD.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GCD.swift; path = Sources/GCD.swift; sourceTree = ""; }; + DE2C000707EBAC73CB8E4D1AC182433D /* BigInt-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "BigInt-dummy.m"; sourceTree = ""; }; + DF6FE3C89D52B8B8E8AD67EC8CD632F4 /* num_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = num_impl.h; path = secp256k1/num_impl.h; sourceTree = ""; }; + DFB72A7E5ADC684FA4CD2AD37D7D0B3B /* group.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = group.h; path = secp256k1/group.h; sourceTree = ""; }; + DFFFFE9315605246B13122B6E47B748B /* Pods-myWeb3Wallet.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-myWeb3Wallet.debug.xcconfig"; sourceTree = ""; }; + E0091FDB283E431BE460158D80868E12 /* ENSRegistry.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ENSRegistry.swift; path = Sources/web3swift/Utils/ENS/ENSRegistry.swift; sourceTree = ""; }; + E00B9DD5F289EBCC20B485163A92C9CE /* Addition.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Addition.swift; path = Sources/Addition.swift; sourceTree = ""; }; + E03C16A97E869AFA5CD8C861D0F30A3E /* hang.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = hang.swift; path = Sources/hang.swift; sourceTree = ""; }; + E06008D189FECE45B3935D3DF48E676A /* NSNotificationCenter+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSNotificationCenter+AnyPromise.h"; path = "Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.h"; sourceTree = ""; }; + E1F3A004CC4748F6083D6F5E3CCAAAB6 /* StreamEncryptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StreamEncryptor.swift; path = Sources/CryptoSwift/StreamEncryptor.swift; sourceTree = ""; }; + E367D31EF999AF507211E8538ED28182 /* Web3+JSONRPC.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+JSONRPC.swift"; path = "Sources/web3swift/Web3/Web3+JSONRPC.swift"; sourceTree = ""; }; + E4A02AC333F90D23C1B6F38D7E3EAFD0 /* Pods-myWeb3WalletTests-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-myWeb3WalletTests-Info.plist"; sourceTree = ""; }; + E55E8B81407082884426231F92E19AED /* Cipher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Cipher.swift; path = Sources/CryptoSwift/Cipher.swift; sourceTree = ""; }; + E6C3B21AB95E51A2D26F2C42C0A2C164 /* basic-config.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "basic-config.h"; path = "secp256k1/basic-config.h"; sourceTree = ""; }; + E71A523B7024293D61E1102B9CC22823 /* browser.js */ = {isa = PBXFileReference; includeInIndex = 1; name = browser.js; path = Sources/web3swift/Browser/browser.js; sourceTree = ""; }; + E725C147A5A1C727AA89210D74D57CBF /* Utils+Foundation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Utils+Foundation.swift"; path = "Sources/CryptoSwift/Foundation/Utils+Foundation.swift"; sourceTree = ""; }; + E76D73543A413D250E98C170B65439FE /* StringHTTPHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StringHTTPHandler.swift; path = Sources/Framer/StringHTTPHandler.swift; sourceTree = ""; }; + E77EA545335C3D935F993E0EC64F9B1D /* NSURLSession+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSURLSession+Promise.swift"; path = "Extensions/Foundation/Sources/NSURLSession+Promise.swift"; sourceTree = ""; }; + E7F85271DD855957A69EABBE94D318D3 /* Pods-myWeb3WalletTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-myWeb3WalletTests.release.xcconfig"; sourceTree = ""; }; + E9229E35F43D257E448471062DE690D6 /* Web3+WebsocketProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+WebsocketProvider.swift"; path = "Sources/web3swift/Web3/Web3+WebsocketProvider.swift"; sourceTree = ""; }; + E9D6042684BC5248A7F2102E84D57D44 /* TransactionSigner.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TransactionSigner.swift; path = Sources/web3swift/Transaction/TransactionSigner.swift; sourceTree = ""; }; + EA8D86F1746BB6B64518FC1D508E67F4 /* scalar_8x32.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar_8x32.h; path = secp256k1/scalar_8x32.h; sourceTree = ""; }; + EBD47F770D42CED6B265DC5BDAD568EC /* BlockEncryptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BlockEncryptor.swift; path = Sources/CryptoSwift/BlockEncryptor.swift; sourceTree = ""; }; + ED6D439006671F4009638764B9C56EA1 /* join.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = join.m; path = Sources/join.m; sourceTree = ""; }; + EE4EAD1D53584CBDC586BA9499EE0D68 /* UIViewController+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIViewController+AnyPromise.m"; path = "Extensions/UIKit/Sources/UIViewController+AnyPromise.m"; sourceTree = ""; }; + EF16FB6DF72A1700811D95947F7D6278 /* BlockModeOptions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BlockModeOptions.swift; path = Sources/CryptoSwift/BlockMode/BlockModeOptions.swift; sourceTree = ""; }; + F0A6F2A78FDE414D85D2A8DC74021C1B /* FoundationSecurity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FoundationSecurity.swift; path = Sources/Security/FoundationSecurity.swift; sourceTree = ""; }; + F16994E06B05BA83DEC77EB28F001644 /* ISO78164Padding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ISO78164Padding.swift; path = Sources/CryptoSwift/ISO78164Padding.swift; sourceTree = ""; }; + F19B311741AA54433FA1A285E0537076 /* scratch.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scratch.h; path = secp256k1/scratch.h; sourceTree = ""; }; + F34633B7A646EC054D00CF51B9CFEDAF /* Promise+Web3+Contract+GetIndexedEvents.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Contract+GetIndexedEvents.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Contract+GetIndexedEvents.swift"; sourceTree = ""; }; + F3FE70C0B549742469D7A9041DAC6F8B /* PromiseKit.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PromiseKit.release.xcconfig; sourceTree = ""; }; + F4805A323ED852FBABCD0E37CF9864E7 /* SHA1.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SHA1.swift; path = Sources/CryptoSwift/SHA1.swift; sourceTree = ""; }; + F499FD6C54B3145BB4C4FAC810F4B15D /* web3swift-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "web3swift-dummy.m"; sourceTree = ""; }; + F558200F0F69A8C32906EE13B19FE77E /* Decodable+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Decodable+Extensions.swift"; path = "Sources/web3swift/Convenience/Decodable+Extensions.swift"; sourceTree = ""; }; + F5781B6CBB88661F6F9E634C0914094C /* ChaCha20+Foundation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ChaCha20+Foundation.swift"; path = "Sources/CryptoSwift/Foundation/ChaCha20+Foundation.swift"; sourceTree = ""; }; + F6380C10D44B994D4547641ADFCA08B5 /* Generics.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Generics.swift; path = Sources/CryptoSwift/Generics.swift; sourceTree = ""; }; + F6CDD67904C46443626098D12FE447EB /* UInt128.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = UInt128.swift; path = Sources/CryptoSwift/UInt128.swift; sourceTree = ""; }; + F6D89670A08E932CCAC385CCADC3E3F7 /* UInt64+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UInt64+Extension.swift"; path = "Sources/CryptoSwift/UInt64+Extension.swift"; sourceTree = ""; }; + F7336340A26FA144CE8DC399BD961DE2 /* Blowfish+Foundation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Blowfish+Foundation.swift"; path = "Sources/CryptoSwift/Foundation/Blowfish+Foundation.swift"; sourceTree = ""; }; + F7902A028BC075F44A5B91EA5C782640 /* Configuration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Configuration.swift; path = Sources/Configuration.swift; sourceTree = ""; }; + F7C0A6F898A3FC267475D1DAA9F64305 /* ecmult_const_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecmult_const_impl.h; path = secp256k1/ecmult_const_impl.h; sourceTree = ""; }; + F7C21A8D4CE9BE9389B1B027A7F1684A /* Floating Point Conversion.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Floating Point Conversion.swift"; path = "Sources/Floating Point Conversion.swift"; sourceTree = ""; }; + F81274EDB681F11E7CB05F7DCA2BB33C /* CryptoSwift */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = CryptoSwift; path = CryptoSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + F8A625D05EC1B896D29CA0FCFF4B4395 /* CMAC.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CMAC.swift; path = Sources/CryptoSwift/CMAC.swift; sourceTree = ""; }; + F8C128F18673E79A6E143D83ECDB3AEB /* Framer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Framer.swift; path = Sources/Framer/Framer.swift; sourceTree = ""; }; + F91048DD1C7E59A1DD091512416C06A4 /* Web3+Wallet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Wallet.swift"; path = "Sources/web3swift/HookedFunctions/Web3+Wallet.swift"; sourceTree = ""; }; + F9295022CA4AA205D97FA9E845A976C7 /* Pods-myWeb3Wallet-myWeb3WalletUITests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-myWeb3Wallet-myWeb3WalletUITests-umbrella.h"; sourceTree = ""; }; + F95A6F75823EC4EF200AAEC1DCF80F46 /* CryptoSwift-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "CryptoSwift-umbrella.h"; sourceTree = ""; }; + F98CC07D9AD78B8CDF70154F9443A978 /* PBKDF2.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PBKDF2.swift; path = Sources/CryptoSwift/PKCS/PBKDF2.swift; sourceTree = ""; }; + FACA054A990CABAF7B4E5BDC81A86B97 /* Bridge.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Bridge.swift; path = Sources/web3swift/Browser/Bridge.swift; sourceTree = ""; }; + FACCAD5B5F220165EBCE30AAE936EAD1 /* EthereumTransaction.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EthereumTransaction.swift; path = Sources/web3swift/Transaction/EthereumTransaction.swift; sourceTree = ""; }; + FB23B3EF1286E7A0B48DF6ED3428E86B /* afterlife.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = afterlife.swift; path = Extensions/Foundation/Sources/afterlife.swift; sourceTree = ""; }; + FB92F1919C898290E81EC454E6484876 /* secp256k1.c.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = secp256k1.c.debug.xcconfig; sourceTree = ""; }; + FBD58974667368F7E5904A021A7598D3 /* ecmult_const.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecmult_const.h; path = secp256k1/ecmult_const.h; sourceTree = ""; }; + FBDDE8545CBE1DD3E62A0FAACA1566C7 /* ContractProtocol.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ContractProtocol.swift; path = Sources/web3swift/Contract/ContractProtocol.swift; sourceTree = ""; }; + FC11C1CC2479584E9A41405F284BF604 /* Server.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Server.swift; path = Sources/Server/Server.swift; sourceTree = ""; }; + FD267E54D7018E6BD14F7FF243347A4F /* Web3+BrowserFunctions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+BrowserFunctions.swift"; path = "Sources/web3swift/HookedFunctions/Web3+BrowserFunctions.swift"; sourceTree = ""; }; + FDDCBC928625AE704E65A6F7DED8B74B /* Pods-myWeb3Wallet-myWeb3WalletUITests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-myWeb3Wallet-myWeb3WalletUITests.release.xcconfig"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 11379356021538EC61B49D0E27E3FEE9 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + CBC2CC340CD4CFCD60F9A30BC9E0955C /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 1DD57ED84B39C7D18075D5049C2BAFAE /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 38F5A67EF31AD4A7571F62E24C92DFB8 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 22579CC44F871C4C542FC182B991B33C /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 33C71989B6C635864EC5E4862AFAAE8A /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2999E7F81F8757C3D08FFF9F9F7FEAEC /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + CB1A9A8A033409BF5D585EF62A7254E9 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2BDC8040898B74CED208461196194B59 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 6D581D7F06643EF7F7BDFE0220D642F9 /* CoreImage.framework in Frameworks */, + 38F306041876680482840B39633C0994 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5648DAEA2334E42B6530BAD0A78B94F3 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 199B84AB82B3544540CFC8CD3C755B82 /* Foundation.framework in Frameworks */, + 1ADC5BA227C82B9DDF4DE68343EFC40D /* UIKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 786D2BEBB917377ADEA762CD9F9E20D6 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 455293CB3237E60314F28FC940E2E19E /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7B3773E0103304DCF4AE1B4BC37BAFAD /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 44FBA29463E2DB758F97EF275BAD82F2 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9DCB20D57B46BAC0FF156D5A84727D99 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C62F957CA0152686080C49F0278A3D8C /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 9F4816004ABE829D5241033DD39EB4EE /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 03C5C200A0787E300053CFA8F53CA094 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 91EA2938AF2680F49C2E66FD567BD49A /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + 082C8F286796C763F0BD95658CA41A54 /* CorePromise */ = { + isa = PBXGroup; + children = ( + 8DC49762D0D20DA70D0F705EC08E302F /* after.m */, + AAA635D78BC74313670E92DFD4464F7F /* after.swift */, + 442EC95B2C112C5C782CE9612DE57E07 /* AnyPromise.h */, + 61F1F5C6B7C7A8680F81CDEB5CDD4D8B /* AnyPromise.m */, + 6C196FA6A48283DE5A44E4FCB71252E8 /* AnyPromise.swift */, + 4F202231EF82E4F2909CFEDE889D0C7A /* Box.swift */, + 56DC1F5BA0194E3F08E0C6652CB89C9D /* Catchable.swift */, + F7902A028BC075F44A5B91EA5C782640 /* Configuration.swift */, + C563C261B9470D2D28A526E4BF747E2C /* CustomStringConvertible.swift */, + 074712D83C2147040D6DBDC8B41CAEC3 /* Deprecations.swift */, + 3D6311A0CAB052B65B5FC50B1A76C0C8 /* dispatch_promise.m */, + BE044572A30D307268519834DCA2D378 /* Error.swift */, + 89E3E5798A0F9C8B82F89E4AA1C9B933 /* firstly.swift */, + A4F1C951C5378C2C015177FE8E9BBF92 /* fwd.h */, + 4D4496F8FBCD773F8A25A49F635CC63C /* Guarantee.swift */, + BB6A86B206A38FF5301C697059CED678 /* hang.m */, + E03C16A97E869AFA5CD8C861D0F30A3E /* hang.swift */, + ED6D439006671F4009638764B9C56EA1 /* join.m */, + 3F3F31CC12709B9BCB4DC9A0AB32FCC3 /* LogEvent.swift */, + 414DA9E2B626DAD1AB851A395D42E446 /* Promise.swift */, + 75ED9FE60BF10CD99C97EABEB33FF1CF /* PromiseKit.h */, + AE35160BC5311A2CFE1E6257480BF4D1 /* race.m */, + 7BC8ACC3ACEA679C2AAC22532DEBE18F /* race.swift */, + 82B356B37EA2E9BF9C51583849D37CAD /* Resolver.swift */, + A788EBC997CC72DFE928373C05F3C475 /* Thenable.swift */, + 98E59BC358BEF788BF007F56FA3381D1 /* when.m */, + D81298FD65A20CC32C6FCEA447C6F8B3 /* when.swift */, + ); + name = CorePromise; + sourceTree = ""; + }; + 09C6E4118FE886A901E8C60D5DBB45DB /* Foundation */ = { + isa = PBXGroup; + children = ( + FB23B3EF1286E7A0B48DF6ED3428E86B /* afterlife.swift */, + E06008D189FECE45B3935D3DF48E676A /* NSNotificationCenter+AnyPromise.h */, + 60D9A3E52DF6179AF354672295718C6B /* NSNotificationCenter+AnyPromise.m */, + 1B86157CBD2724B6E4ADD3456BF9A70B /* NSNotificationCenter+Promise.swift */, + 36EB9FBA8F61ABE90D34ACAAE90DE61A /* NSObject+Promise.swift */, + 0349201509342BC7491FA1ED83CDE2F7 /* NSTask+AnyPromise.h */, + 97603D675B6C3596041F441A64D65A89 /* NSTask+AnyPromise.m */, + 252A09EFA13237E19D66BDFA6A54DDA5 /* NSURLSession+AnyPromise.h */, + 8456FEA753DE9A90D304EA54DFD5DAD3 /* NSURLSession+AnyPromise.m */, + E77EA545335C3D935F993E0EC64F9B1D /* NSURLSession+Promise.swift */, + 9272051904F9CDACCBD8DE527C05C8A0 /* PMKFoundation.h */, + 54F51094F339B9E2A49C1D43EFBDB098 /* Process+Promise.swift */, + ); + name = Foundation; + sourceTree = ""; + }; + 0DF01B081E3CE50BBDCBDC81675BF37D /* Products */ = { + isa = PBXGroup; + children = ( + 91BB24BA472AF523E913108C9AA301F2 /* BigInt */, + F81274EDB681F11E7CB05F7DCA2BB33C /* CryptoSwift */, + 08A8472B9823BC68472175977392F4B9 /* Pods-myWeb3Wallet */, + 8DB09F270FE9B4BDA5AFBD4357E646CE /* Pods-myWeb3Wallet-myWeb3WalletUITests */, + 11103C5C5CFDD9B3B2EA4E84B98049A8 /* Pods-myWeb3WalletTests */, + 002B1E88BA14EBF633CD66EBFBA107E9 /* PromiseKit */, + 332A47430CFF99501D563788C7AAF1D2 /* secp256k1.c */, + 891B2270823847ED23F2ECFC28F935EC /* Starscream */, + 8A2449DF78D58AD33A7C7504BB3F38A0 /* web3swift */, + 12DC6A0FDF284A2C935F5EA9F6111B0B /* web3swift-Browser */, + ); + name = Products; + sourceTree = ""; + }; + 1DE6FAA609C485D46D33025D8815325B /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + A022B8E5CB4F5AE3DFF5318FEB2DDD57 /* Pods-myWeb3Wallet */, + 43CFE4FD496060925212158FBF756509 /* Pods-myWeb3Wallet-myWeb3WalletUITests */, + C98F03581D3EDF065761447C9644190B /* Pods-myWeb3WalletTests */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + 37EB84EB9EE271BE501D87C519F8420A /* Resources */ = { + isa = PBXGroup; + children = ( + E71A523B7024293D61E1102B9CC22823 /* browser.js */, + B3B83F5426FCB99B70C9BA58611231F2 /* browser.min.js */, + 2D1CFEA76FE44A2E6511787F74D0794C /* wk.bridge.min.js */, + ); + name = Resources; + sourceTree = ""; + }; + 38FF7B99E4C0BC8A75F62E500F3A8994 /* Support Files */ = { + isa = PBXGroup; + children = ( + 9F0B4B1C5D1772BD09B1E3478511FBC6 /* Starscream.modulemap */, + D50122651622201633327B4D22B90560 /* Starscream-dummy.m */, + D295F0B7EA16BF13CF0BBFAF36C10963 /* Starscream-Info.plist */, + 01316651403CC05C86D98D47F9CF04B3 /* Starscream-prefix.pch */, + 5773F22FF0BADB57519B5A58AC0A3246 /* Starscream-umbrella.h */, + 7BC2E55A1BE5983AEEDFFB5B980A621C /* Starscream.debug.xcconfig */, + 92BD1F11AAB93E6E693F70645ACCB9D3 /* Starscream.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/Starscream"; + sourceTree = ""; + }; + 43CFE4FD496060925212158FBF756509 /* Pods-myWeb3Wallet-myWeb3WalletUITests */ = { + isa = PBXGroup; + children = ( + 0C3130C87D960B3C5DC4BE2B9448DC1B /* Pods-myWeb3Wallet-myWeb3WalletUITests.modulemap */, + 0BC7C885678FE3B4FE04CA4488F4B953 /* Pods-myWeb3Wallet-myWeb3WalletUITests-acknowledgements.markdown */, + 93E56996042925D46F3368CAD4474742 /* Pods-myWeb3Wallet-myWeb3WalletUITests-acknowledgements.plist */, + A35804F1DCE3C2A4931790E77FC2F701 /* Pods-myWeb3Wallet-myWeb3WalletUITests-dummy.m */, + C6E9D7C085E89CCA54E04610C615C155 /* Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks.sh */, + 5EA7B564CF61E01CB14859E71ABA04D6 /* Pods-myWeb3Wallet-myWeb3WalletUITests-Info.plist */, + F9295022CA4AA205D97FA9E845A976C7 /* Pods-myWeb3Wallet-myWeb3WalletUITests-umbrella.h */, + B7F3600020FB93358C3041F0C10FA382 /* Pods-myWeb3Wallet-myWeb3WalletUITests.debug.xcconfig */, + FDDCBC928625AE704E65A6F7DED8B74B /* Pods-myWeb3Wallet-myWeb3WalletUITests.release.xcconfig */, + ); + name = "Pods-myWeb3Wallet-myWeb3WalletUITests"; + path = "Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests"; + sourceTree = ""; + }; + 4FA755BC662B391E20D9C601F408FC81 /* Support Files */ = { + isa = PBXGroup; + children = ( + 89216AD64050A687049C2812AE6F2D3D /* secp256k1.c.modulemap */, + 494245F16C74B7E11B629E6D698264E8 /* secp256k1.c-dummy.m */, + 57F0814F80E4EAB8D02ADA337CCECBA3 /* secp256k1.c-Info.plist */, + 243018B29E2BCD800923B34F993D9B28 /* secp256k1.c-prefix.pch */, + AA032FABD784E8D9C3094CCA56F9FAAE /* secp256k1.c-umbrella.h */, + FB92F1919C898290E81EC454E6484876 /* secp256k1.c.debug.xcconfig */, + AE2FF8CBBE01A4A94FF02974852301FD /* secp256k1.c.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/secp256k1.c"; + sourceTree = ""; + }; + 572EDFECC902962660EEB1CB04EA2F19 /* Support Files */ = { + isa = PBXGroup; + children = ( + 6A4DE7CB1EA88AC3E3FD9EC3D87BB04D /* ResourceBundle-Browser-web3swift-Info.plist */, + 56B11BC0240F751088C917372E40132A /* web3swift.modulemap */, + F499FD6C54B3145BB4C4FAC810F4B15D /* web3swift-dummy.m */, + 7A9073374C5D843FB300330AAAC2ECF1 /* web3swift-Info.plist */, + 166F18C437FFEE4629AC9EDD147F272A /* web3swift-prefix.pch */, + 65E6BD3495BF0509B852B4FD92DF2989 /* web3swift-umbrella.h */, + 274E8BA3AEB35AB17FA088333816830A /* web3swift.debug.xcconfig */, + 93B89C94E972705C6809F63A2BE2EAAE /* web3swift.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/web3swift"; + sourceTree = ""; + }; + 6E37A82C82960834B94CA5600A2C6DEE /* Pods */ = { + isa = PBXGroup; + children = ( + EA617AD493EDC04B65EFFFC557881C4C /* BigInt */, + 9C0A4FA3752D5E4997AF4DE735FEA438 /* CryptoSwift */, + 7492892CF370AC7881ADF9EC3F65B942 /* PromiseKit */, + AD50EA202D7DFCB270DCCEB88B476C1D /* secp256k1.c */, + F3546E2E51E644ABBE0B8ED0EDF59D41 /* Starscream */, + A2BDB3ECB2BC5C9037CDBAB599998928 /* web3swift */, + ); + name = Pods; + sourceTree = ""; + }; + 7492892CF370AC7881ADF9EC3F65B942 /* PromiseKit */ = { + isa = PBXGroup; + children = ( + 082C8F286796C763F0BD95658CA41A54 /* CorePromise */, + 09C6E4118FE886A901E8C60D5DBB45DB /* Foundation */, + C3548788EB8345E15691BB5699B8300D /* Support Files */, + E4252E85FC6716FF11013746B8F44E37 /* UIKit */, + ); + name = PromiseKit; + path = PromiseKit; + sourceTree = ""; + }; + 80B7A94A648E0A02BA2B76640AFA293F /* Support Files */ = { + isa = PBXGroup; + children = ( + 4F865A846EA340AC2ACFF87476EC2E60 /* BigInt.modulemap */, + DE2C000707EBAC73CB8E4D1AC182433D /* BigInt-dummy.m */, + 7E1E65378BE014016F6FA3C48DB5D9EA /* BigInt-Info.plist */, + 0CDD25924C64FF376F842253501355D4 /* BigInt-prefix.pch */, + 69C28A10F48C7D37E1E65B1E626C6782 /* BigInt-umbrella.h */, + 9217736E16B090E354FA8D7B1F16A693 /* BigInt.debug.xcconfig */, + 18DBFFB3E63974D7C0824367EFCAC013 /* BigInt.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/BigInt"; + sourceTree = ""; + }; + 91EA2938AF2680F49C2E66FD567BD49A /* iOS */ = { + isa = PBXGroup; + children = ( + C51800E5F54721AF0D7AEE62A916CB2F /* CoreImage.framework */, + 5C9BF60EE9C79C985DCC648B95156DC4 /* Foundation.framework */, + 67DE942FB3DAA92CE782989AF2C19632 /* UIKit.framework */, + ); + name = iOS; + sourceTree = ""; + }; + 9C0A4FA3752D5E4997AF4DE735FEA438 /* CryptoSwift */ = { + isa = PBXGroup; + children = ( + 6B7F37C23C7BD91529AFC9D9C3B89350 /* AEAD.swift */, + 408F64023EB56273BB42761F929B897B /* AEADChaCha20Poly1305.swift */, + 889E3ECE5439BC9C800DFD88ED2F04BD /* AES.swift */, + 0AC66155707B85F45580BC854DAA5E8C /* AES+Foundation.swift */, + 8AFCDD28CDD4C6AB23094990AABE6DE9 /* AES.Cryptors.swift */, + 33D9C3E44151CA8DAEC4B95DEEE84E07 /* Array+Extension.swift */, + 459691924762DB7278BDA1860FC51C8E /* Array+Foundation.swift */, + D7B8332B6EEE60574C9B4CB468B81524 /* Authenticator.swift */, + BFBAD5703C2622CB9475778D3FF7684B /* BatchedCollection.swift */, + 82FB779DA3F23E81B13234AB52617EF6 /* Bit.swift */, + 2DDB8CD09F1100772FC894971E35ECF6 /* BlockCipher.swift */, + CD4F76F68EB476ECF93172F941394A64 /* BlockDecryptor.swift */, + EBD47F770D42CED6B265DC5BDAD568EC /* BlockEncryptor.swift */, + B9418ED7506E09852282E4C0298F4CF2 /* BlockMode.swift */, + EF16FB6DF72A1700811D95947F7D6278 /* BlockModeOptions.swift */, + B4C26BFD4C4F0041CB43065B7C15190C /* Blowfish.swift */, + F7336340A26FA144CE8DC399BD961DE2 /* Blowfish+Foundation.swift */, + 55A821C8C1FC6F68C023E2E81651B18B /* CBC.swift */, + 457220DE54FCFECF49D27D4F0494EB51 /* CBCMAC.swift */, + 10B43E5A8E435E74A39AC5722CC5A271 /* CCM.swift */, + 9763CCFBEDDC125312CD1FF164DB1DA5 /* CFB.swift */, + 616F9AB4DE59A05019261F9A89028DC5 /* ChaCha20.swift */, + F5781B6CBB88661F6F9E634C0914094C /* ChaCha20+Foundation.swift */, + 173FD7EFF45980B448F92A8F6A1CE154 /* Checksum.swift */, + E55E8B81407082884426231F92E19AED /* Cipher.swift */, + 1786CFA34F2534AD545031FF7EBA4538 /* CipherModeWorker.swift */, + F8A625D05EC1B896D29CA0FCFF4B4395 /* CMAC.swift */, + 4EA0D117684CE8DF071445A5482A3E60 /* Collection+Extension.swift */, + 9A02DDEC9858A78BEA9C9EAED811BC17 /* CompactMap.swift */, + C190B059191445A1D285D4CE9ABFCC0A /* Cryptor.swift */, + 11657185FCE37F7674E70752DFF319F7 /* Cryptors.swift */, + D9E59212A5A8295E5F180ED605A1CDE7 /* CTR.swift */, + 752098116910D32A020C6FA1EB9F38AA /* Data+Extension.swift */, + D263F99BE4CC8113CEC0DF611249ADB8 /* Digest.swift */, + 5D37615679E9A1E496ED4D603AEE02C3 /* DigestType.swift */, + 17AAAF47166CDEF7CB91711009CC9DB3 /* ECB.swift */, + 141B6AEB28CFF06BE48234968D5F6490 /* GCM.swift */, + F6380C10D44B994D4547641ADFCA08B5 /* Generics.swift */, + 7E0AD3992F79794304FDD80D8F1AF7D5 /* HKDF.swift */, + 4C143EFCB8668F769B0C2692D4D882B4 /* HMAC.swift */, + 94EDD79DD8C072828820F9310A7F25AB /* HMAC+Foundation.swift */, + A6224520D335600BCB2E7747D6687B8A /* Int+Extension.swift */, + 79BCFCB28731207C5F021A408D5A1EEC /* ISO10126Padding.swift */, + F16994E06B05BA83DEC77EB28F001644 /* ISO78164Padding.swift */, + 4ED783EBC23A40B546A9CE880D97D376 /* MD5.swift */, + 2701E866DF92794F0A7792C7BE838E7D /* NoPadding.swift */, + A3EBD086332607B408BD6F878EA9A500 /* OCB.swift */, + BCEEABD2FC5B664CD01F65462355E766 /* OFB.swift */, + 0D72EEA6CB2ED51D9CD581441D934A96 /* Operators.swift */, + 0249C3548513926775493A932FE6EA90 /* Padding.swift */, + 8552720D720D203E2444F5263C6A4021 /* PBKDF1.swift */, + F98CC07D9AD78B8CDF70154F9443A978 /* PBKDF2.swift */, + 5CF0BA54E2B65D2328C3139726AB3F4B /* PCBC.swift */, + BC4CF0C81A7F4E6F47BFB9B293C8B441 /* PKCS5.swift */, + AFADECE767F8B6CE7D6F0151072D9120 /* PKCS7.swift */, + 830413FA8967EA278558006C271B1D16 /* PKCS7Padding.swift */, + 1C662BE19BE125813C43B2C2F34A06A4 /* Poly1305.swift */, + 1B876EF576BCF48712B2FE0B58425831 /* Rabbit.swift */, + 4A26062C707AB96E5E13A0125B15FE06 /* Rabbit+Foundation.swift */, + A131EC03EF93B5304C3DB4E559307C3B /* Scrypt.swift */, + 3617B0E86D0A093AA4BC7F0006FD0413 /* SecureBytes.swift */, + F4805A323ED852FBABCD0E37CF9864E7 /* SHA1.swift */, + C10E9CF99CBE40D30321A9990E3780F3 /* SHA2.swift */, + AA1FF168A47F7A82F2DFBA4040E00A10 /* SHA3.swift */, + 3976F596C64EC42D19A8CCF74B70DBF8 /* StreamDecryptor.swift */, + E1F3A004CC4748F6083D6F5E3CCAAAB6 /* StreamEncryptor.swift */, + 662915FBC8EFD87F9F690D0B12FC9D41 /* String+Extension.swift */, + C158F576B708193B339431561C565F0A /* String+FoundationExtension.swift */, + F6CDD67904C46443626098D12FE447EB /* UInt128.swift */, + 824063EF324B04F2AADFB9E47CDA422A /* UInt16+Extension.swift */, + 686CF63072B25624DF5326A314DB59DB /* UInt32+Extension.swift */, + F6D89670A08E932CCAC385CCADC3E3F7 /* UInt64+Extension.swift */, + BB7B5E4ADA577B5E93F2C0FC6E8843FC /* UInt8+Extension.swift */, + 5F37ABE5C51720188832DE43FE27AA1B /* Updatable.swift */, + 694009935F1F74664D4B4E938B5F1490 /* Utils.swift */, + E725C147A5A1C727AA89210D74D57CBF /* Utils+Foundation.swift */, + 5CC9E23320B8991F34BC31A01FB21A1C /* ZeroPadding.swift */, + B1F341B2BE61C900DD9EA2A9B56A8FB9 /* Support Files */, + ); + name = CryptoSwift; + path = CryptoSwift; + sourceTree = ""; + }; + A022B8E5CB4F5AE3DFF5318FEB2DDD57 /* Pods-myWeb3Wallet */ = { + isa = PBXGroup; + children = ( + D1A344D248E1F69564A9F80880BF7F1B /* Pods-myWeb3Wallet.modulemap */, + 758935E87C6104A90D397DA9D6DE0FD9 /* Pods-myWeb3Wallet-acknowledgements.markdown */, + B4FC29C6A531D0517444640A0FDF354E /* Pods-myWeb3Wallet-acknowledgements.plist */, + 2819B7319BF925F641E9D256396B3F27 /* Pods-myWeb3Wallet-dummy.m */, + BEA93987C60BB062C9F16D11BB8D27AB /* Pods-myWeb3Wallet-frameworks.sh */, + 871B8E61AECB22BF7E4F511683743783 /* Pods-myWeb3Wallet-Info.plist */, + 14105AEFAD47B97BBFD0A972AA98DF35 /* Pods-myWeb3Wallet-umbrella.h */, + DFFFFE9315605246B13122B6E47B748B /* Pods-myWeb3Wallet.debug.xcconfig */, + 878D77F928A64BCC11C2A541B02CA9F2 /* Pods-myWeb3Wallet.release.xcconfig */, + ); + name = "Pods-myWeb3Wallet"; + path = "Target Support Files/Pods-myWeb3Wallet"; + sourceTree = ""; + }; + A2BDB3ECB2BC5C9037CDBAB599998928 /* web3swift */ = { + isa = PBXGroup; + children = ( + 61D906C63EE673FDF08E44B02D695E83 /* ABI.swift */, + 2456150E4EBA655122DFE457A3B16411 /* ABIDecoding.swift */, + D4F1BDCD30EFA57E3CA28CD4CF2D7CCF /* ABIElements.swift */, + 3339301FC43964D4764CDC289EBDD39E /* ABIEncoding.swift */, + 2B5918B5A16C03780E709CF2CDD1104C /* ABIParameterTypes.swift */, + C7DD12C61F348A063E8ADC23768D4327 /* ABIParsing.swift */, + 94545F2C1973B711F0E957917ED7B36E /* ABITypeParser.swift */, + 0050F742D824A11AEB8424E0DD2C63DE /* AbstractKeystore.swift */, + 7C474592AE45D1B74EC342FF072BA03E /* Array+Extension.swift */, + 665EC9936D9FB294CDFDD2B00D996F69 /* Base58.swift */, + 4B9AE90348C0654C1AB4D4690A073401 /* BigUInt+Extensions.swift */, + 6B57FF8149DACE439778C727600D5548 /* BIP32HDNode.swift */, + 6DF004A0692AE90EAC3F6F16BDF07740 /* BIP32Keystore.swift */, + 00C245DA669E6E0BBAFA3115D6823007 /* BIP39.swift */, + 3BD1F43673C0FBEB88F290755398E0BF /* BIP39+WordLists.swift */, + D444BC3C307070B4F5F3F480423838AD /* BloomFilter.swift */, + FACA054A990CABAF7B4E5BDC81A86B97 /* Bridge.swift */, + 9A7C267F2A6E93388DE89B4D3D823E13 /* BrowserViewController.swift */, + 7A751A1E4864468D4E52A81FC5BDDFDB /* ComparisonExtensions.swift */, + FBDDE8545CBE1DD3E62A0FAACA1566C7 /* ContractProtocol.swift */, + 52B4F7541C12ABF10C884449E0032938 /* CryptoExtensions.swift */, + 9CDA08FC40E440445F5B1C2087699FA4 /* Data+Extension.swift */, + F558200F0F69A8C32906EE13B19FE77E /* Decodable+Extensions.swift */, + 0C706E0E7E64CC2DDFF946B173F6E937 /* Dictionary+Extension.swift */, + C1DF43A48C95155896DC1F3F4407706C /* EIP67Code.swift */, + BAD73345F8FD30B964FB9152047D4B8C /* EIP681.swift */, + 30F6DD109D1E925101993EF13CC1B6DD /* Encodable+Extensions.swift */, + A1086E5EB59F24E36E2556B3270BE06F /* ENS.swift */, + AA8F1F5587506D634EFF2229CAE76FE8 /* ENSBaseRegistrar.swift */, + E0091FDB283E431BE460158D80868E12 /* ENSRegistry.swift */, + AED149E8CB2E262FF979BFD4E5640005 /* ENSResolver.swift */, + 9DA7F20BAF89DD9B24B85E9A1A2B4FD2 /* ENSReverseRegistrar.swift */, + B7E95C968FFABFDA532F2638C4F909A4 /* EthereumAddress.swift */, + 5064BE1943B37DFB8BD781A4F88B7360 /* EthereumContract.swift */, + 4F95702E2ECA0FE6E67FCF95250B5373 /* EthereumFilterEncodingExtensions.swift */, + 1659BBB217FF5D75D1A83A1CCB87541C /* EthereumKeystoreV3.swift */, + FACCAD5B5F220165EBCE30AAE936EAD1 /* EthereumTransaction.swift */, + CBC606D4D73D4D6373FD43179F3DF3C5 /* ETHRegistrarController.swift */, + A546A1EBF9CE4405F7461B4753D53B47 /* EventFiltering.swift */, + 78FCD380A8DC8B60B8940546BA368A71 /* Extensions.swift */, + B913B0C1A0F49DC0B7ADA73EC64F3E7B /* IBAN.swift */, + B516CBBE190C154B351A76809BF9B33B /* KeystoreManager.swift */, + 4DCC4A6DDDF04697E091B17F02A5660E /* KeystoreParams.swift */, + 03FB8D39BDF0D05A9BF5951DAD5C5623 /* NameHash.swift */, + 581816AC6AB72D6754E7F5AA6BEEEBDE /* NativeTypesEncoding+Extensions.swift */, + 18BD9B0B5F5F103741EE858C4D318E00 /* NonceMiddleware.swift */, + B1610DC37FC079B6D1D83472DBA4DA12 /* NSRegularExpressionExtension.swift */, + 0C4C834F49C3454D3ED6140F8761E5EE /* PlainKeystore.swift */, + 7509ED605AC6A0930966F33117BB9895 /* Promise+Batching.swift */, + B283E7DB525627BCDF8B64F25F729738 /* Promise+HttpProvider.swift */, + F34633B7A646EC054D00CF51B9CFEDAF /* Promise+Web3+Contract+GetIndexedEvents.swift */, + B373FED6638B961B7A97AABD5280E615 /* Promise+Web3+Eth+Call.swift */, + D78518CF508AF000188545E3388F00CC /* Promise+Web3+Eth+EstimateGas.swift */, + 9B72CCFE3D10F1F6A2457EC5730BA509 /* Promise+Web3+Eth+GetAccounts.swift */, + CAC7EB22892368AC2FB24D3C9A74B5BF /* Promise+Web3+Eth+GetBalance.swift */, + 2351A3019723AF864F03D66DEFDAA1CC /* Promise+Web3+Eth+GetBlockByHash.swift */, + C1CBAF4C9C1F1D95FC1A9EE6D61DF7BB /* Promise+Web3+Eth+GetBlockByNumber.swift */, + C05291B76391595ED8B3B285B79F78EC /* Promise+Web3+Eth+GetBlockNumber.swift */, + 9DBB832EE6B1A46B6B06C03F1FB46839 /* Promise+Web3+Eth+GetGasPrice.swift */, + A24FCB02E998E133E5325631033AF027 /* Promise+Web3+Eth+GetTransactionCount.swift */, + 2969A6F4F3AB1FF9852CF5B8BBFF0981 /* Promise+Web3+Eth+GetTransactionDetails.swift */, + 98DDDE228F4BC29D191AE78AD7AD59C6 /* Promise+Web3+Eth+GetTransactionReceipt.swift */, + 6016EF1F606FED15790DC99D24384C6E /* Promise+Web3+Eth+SendRawTransaction.swift */, + 69B470CEFDB78B1B81B0DAF2D4FBDBA4 /* Promise+Web3+Eth+SendTransaction.swift */, + 513ACAB2D90C7668D5C441E7F44CD9F1 /* Promise+Web3+Personal+CreateAccount.swift */, + BF9BF56B15E811B9D10946DD368C9411 /* Promise+Web3+Personal+Sign.swift */, + 35FE95CCAA2CF6A2C0218E951A57232D /* Promise+Web3+Personal+UnlockAccount.swift */, + D0A930E640D89DFE4D0E110591FB7076 /* Promise+Web3+TxPool.swift */, + 18234DDB0733F3EF948EF77D54D10904 /* PublicKey.swift */, + B2D684B79FC7FFF779E5AF645F1E8129 /* RIPEMD160+StackOveflow.swift */, + 0E7FE0B9D0DF6B91966F07D6D2282738 /* RLP.swift */, + 194E21E099159CC519476AA1C0E9CD52 /* SECP256k1.swift */, + BCC3DC989D5E95AE5DFB7CEF5F4A6825 /* String+Extension.swift */, + E9D6042684BC5248A7F2102E84D57D44 /* TransactionSigner.swift */, + 4FA623E4738AB357087E678F3C2B8B80 /* Web3.swift */, + FD267E54D7018E6BD14F7FF243347A4F /* Web3+BrowserFunctions.swift */, + C2194F52EA9713769E689181030DF7B4 /* Web3+Constants.swift */, + C513F6340AD8C6EF588154BB1FBB30DB /* Web3+Contract.swift */, + CDDD26AA5A7B20DAE7F39D14BDC4C092 /* Web3+ERC1155.swift */, + ACF496E6C59563E3B2D37AFF0647AA5E /* Web3+ERC1376.swift */, + 09783897421F576EDE46857412E8265C /* Web3+ERC1400.swift */, + D4D2746F0470DC43876ADAF60BDEF00E /* Web3+ERC1410.swift */, + C2E188E17AF245DF4E409CBCCAA53A13 /* Web3+ERC1594.swift */, + CFC32DF7FA786FBF7FC7BF4877244E6A /* Web3+ERC1633.swift */, + 3402BA34F808F411E48E41CD59F05FCE /* Web3+ERC1643.swift */, + 6CAA05940EADD5E5A01859B5B9BA567F /* Web3+ERC1644.swift */, + 492109BF7BF2C0FF599C257507DF3FF0 /* Web3+ERC165.swift */, + 9B00321B0B14B4FF897F2CF5B6415C3C /* Web3+ERC20.swift */, + CEE308A0279FEF1970F5AE55A59B0784 /* Web3+ERC721.swift */, + 605DCE9468F1ECAB3DE8DB3907D53C1D /* Web3+ERC721x.swift */, + 6D47AE3AEBABE33FF5939852216CAA95 /* Web3+ERC777.swift */, + 3511CE45081A21C5D78AEA0873840821 /* Web3+ERC820.swift */, + 9DFDD8684C07E988EE7BEF8AB894F1C3 /* Web3+ERC888.swift */, + 5E9C274FE23EF9CD989D4081E5A80DAB /* Web3+Eth.swift */, + 127BE2CFB3F3A1C174D216B55D11EBAD /* Web3+Eth+Websocket.swift */, + C19976C618B5991508555766A6C58D33 /* Web3+Eventloop.swift */, + 5DA6D1A7D4E05E1D0AD507800C434815 /* Web3+EventParser.swift */, + D52E15043DB745FE9026A43E0E10B902 /* Web3+HttpProvider.swift */, + 98821C698CAE291DB7FC2E6A72ECB7D4 /* Web3+InfuraProviders.swift */, + A5F4F7EFAF476543587E0F3608C9CA8B /* Web3+Instance.swift */, + E367D31EF999AF507211E8538ED28182 /* Web3+JSONRPC.swift */, + 50A8ABDB2A97CBECD57C02DF7D555AD4 /* Web3+Methods.swift */, + 699F27F269D20FAD83C7D3B79A5C5074 /* Web3+MutatingTransaction.swift */, + 4861BBBBB34E78E9429D35409F2D1E5F /* Web3+Options.swift */, + 1D7BC9EE36F90A14659788AD767DB322 /* Web3+Personal.swift */, + A2ED9A418D702E70593766E47BF84FA5 /* Web3+Protocols.swift */, + 61329F3723A6B1ABEF3BBCD12675C0C1 /* Web3+ReadingTransaction.swift */, + BB758BE37B19325C036A0DBACBEA6C27 /* Web3+SecurityToken.swift */, + 771143AE964D2F3B727D81EADA6425C6 /* Web3+ST20.swift */, + 196F8D0679C136F9CB5DEDA32CE39FA4 /* Web3+Structures.swift */, + 4FCECB2399C85B352286D927376CCC94 /* Web3+TxPool.swift */, + ABC21DF8C117534CE67E549DA43A59F6 /* Web3+Utils.swift */, + F91048DD1C7E59A1DD091512416C06A4 /* Web3+Wallet.swift */, + E9229E35F43D257E448471062DE690D6 /* Web3+WebsocketProvider.swift */, + 37EB84EB9EE271BE501D87C519F8420A /* Resources */, + 572EDFECC902962660EEB1CB04EA2F19 /* Support Files */, + ); + name = web3swift; + path = web3swift; + sourceTree = ""; + }; + AD50EA202D7DFCB270DCCEB88B476C1D /* secp256k1.c */ = { + isa = PBXGroup; + children = ( + E6C3B21AB95E51A2D26F2C42C0A2C164 /* basic-config.h */, + 95E71976E5850018C27C15AC878DC296 /* ecdh_impl.h */, + 4E304701AA575E1B30297A9335082B9C /* ecdsa.h */, + 1B1FB7A40FA73B490F40C882A36FDC44 /* ecdsa_impl.h */, + 4D50E33E27CBB4C4D9F7EBAE3849B7A5 /* eckey.h */, + 2CA6A6221D6CA8057D71BA60A8DAF0EF /* eckey_impl.h */, + 138407359512A2D920EEDD6C7AEDDF81 /* ecmult.h */, + FBD58974667368F7E5904A021A7598D3 /* ecmult_const.h */, + F7C0A6F898A3FC267475D1DAA9F64305 /* ecmult_const_impl.h */, + 02604971270B936C3550FF9F7FAE7132 /* ecmult_gen.h */, + 2717173A9BD140D3E2D2F0546753746A /* ecmult_gen_impl.h */, + 8D144717D9392F89398A95CE943E7FCD /* ecmult_impl.h */, + 5931D9D39B790BA48631057F24CE6AAC /* field.h */, + 812A3FAA807BBF520E834E8177CDA805 /* field_10x26.h */, + 6CF1331659E806368CFFAD37192BA01A /* field_10x26_impl.h */, + 6D011B0CEC9AC062DC89BC9C1EC05806 /* field_5x52.h */, + D0FF9C21D8BBE37AEAA3240D6DBB2CA2 /* field_5x52_asm_impl.h */, + 7239B0649BFDF00625943FEDFAD57C9B /* field_5x52_impl.h */, + 4B6B955D7B2A183ACD0B6B950B5C893B /* field_5x52_int128_impl.h */, + 499E0FE2E6CAD14D5EA32EE544804F2C /* field_impl.h */, + DFB72A7E5ADC684FA4CD2AD37D7D0B3B /* group.h */, + D7459ACC386268D5B3B45D2F4EB04631 /* group_impl.h */, + B3CA76593B24771BFE57E65E82FABF4D /* hash.h */, + 10F4B4430DB29EA7B5DF0FF1637E5B75 /* hash_impl.h */, + C560E0C20A6F6E769700B4AB346EEBDC /* num.h */, + 6185835291CFC5AA4425DEBC5841A13C /* num_gmp.h */, + 861A826AE843EA63A9502FDE98A45BB7 /* num_gmp_impl.h */, + DF6FE3C89D52B8B8E8AD67EC8CD632F4 /* num_impl.h */, + D5BEDCE22D40961DE68C60CB6AE573A7 /* recovery_impl.h */, + C798B4F4D8097C83111B844CBB1C3CE6 /* scalar.h */, + 047C81A9AD59EDA23DBD28F67EA44F3D /* scalar_4x64.h */, + CDC065C0E64F5101BC23C8AC17738F7E /* scalar_4x64_impl.h */, + EA8D86F1746BB6B64518FC1D508E67F4 /* scalar_8x32.h */, + 242D4C1FB3E0059C3577A41C22EB527A /* scalar_8x32_impl.h */, + 35BAB9DEB6B862BBA80319A779593939 /* scalar_impl.h */, + A8BBEB50E65BE6B493DCFE9A2BCCE825 /* scalar_low.h */, + BF02184566636520F4D8470933669F05 /* scalar_low_impl.h */, + F19B311741AA54433FA1A285E0537076 /* scratch.h */, + AD0E7C344DBA5BB5BD963F05B4DC42F0 /* scratch_impl.h */, + 85D99C55C6D2A7368634E17D0FC07D22 /* secp256k1.c */, + 61F9291E88C2B8D95351C63BBAC5A220 /* secp256k1.h */, + AF96BD26A8980F3C83466AD777577DB3 /* secp256k1-config.h */, + 629BF4D4B84DA533D5B163D4E919D015 /* secp256k1_ec_mult_static_context.h */, + 80E520F4DA45AF0A1A997471995473E8 /* secp256k1_main.h */, + 12CFBD6C81A2CE71BA2C4F590B5D5927 /* util.h */, + 4FA755BC662B391E20D9C601F408FC81 /* Support Files */, + ); + name = secp256k1.c; + path = secp256k1.c; + sourceTree = ""; + }; + B1F341B2BE61C900DD9EA2A9B56A8FB9 /* Support Files */ = { + isa = PBXGroup; + children = ( + 10362E3628CDA7ABAD35AB9B2A1093E5 /* CryptoSwift.modulemap */, + 73EA7956B330A45808E9440BEF76D6D7 /* CryptoSwift-dummy.m */, + 3806AFE4E13D3ED1C2FD088F8F101839 /* CryptoSwift-Info.plist */, + BDBC9ABAC77FB39A9D79EFB025FD3C04 /* CryptoSwift-prefix.pch */, + F95A6F75823EC4EF200AAEC1DCF80F46 /* CryptoSwift-umbrella.h */, + 700FBEA2D7EAA32E60481668BFC38F17 /* CryptoSwift.debug.xcconfig */, + C3D558C8C4FC4AADF09ED9EA94D9D6A9 /* CryptoSwift.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/CryptoSwift"; + sourceTree = ""; + }; + C3548788EB8345E15691BB5699B8300D /* Support Files */ = { + isa = PBXGroup; + children = ( + 3C3624803E3D83147D2CE9BD951D7CCA /* PromiseKit.modulemap */, + B87DE6711B6E12078EA7C872582DA976 /* PromiseKit-dummy.m */, + 307663AAE1B15058CDCC30A8C3B476C6 /* PromiseKit-Info.plist */, + 67E49E4C0BCA77B52DCEAFDAF884CD2C /* PromiseKit-prefix.pch */, + D77426DA53B5BAC9390B9F12C1142183 /* PromiseKit-umbrella.h */, + 23C909CF58C1C172D843DF0B9927E7E1 /* PromiseKit.debug.xcconfig */, + F3FE70C0B549742469D7A9041DAC6F8B /* PromiseKit.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/PromiseKit"; + sourceTree = ""; + }; + C98F03581D3EDF065761447C9644190B /* Pods-myWeb3WalletTests */ = { + isa = PBXGroup; + children = ( + 735CD37CFC646A0F0361C7EFB6F5B8BE /* Pods-myWeb3WalletTests.modulemap */, + 4BE80D171181BA01FFD025A4FC4D6B4E /* Pods-myWeb3WalletTests-acknowledgements.markdown */, + 5723B9D6A8FF3DBE29B669D7E3759A3B /* Pods-myWeb3WalletTests-acknowledgements.plist */, + 8C020773045EBAC1BB6CC4DCF9CF70E8 /* Pods-myWeb3WalletTests-dummy.m */, + E4A02AC333F90D23C1B6F38D7E3EAFD0 /* Pods-myWeb3WalletTests-Info.plist */, + 48ECBEC5D1CFAE5AD46BEFF89E4ACC60 /* Pods-myWeb3WalletTests-umbrella.h */, + A524EF14F2890814986F7449EAA84F7F /* Pods-myWeb3WalletTests.debug.xcconfig */, + E7F85271DD855957A69EABBE94D318D3 /* Pods-myWeb3WalletTests.release.xcconfig */, + ); + name = "Pods-myWeb3WalletTests"; + path = "Target Support Files/Pods-myWeb3WalletTests"; + sourceTree = ""; + }; + CF1408CF629C7361332E53B88F7BD30C = { + isa = PBXGroup; + children = ( + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */, + 03C5C200A0787E300053CFA8F53CA094 /* Frameworks */, + 6E37A82C82960834B94CA5600A2C6DEE /* Pods */, + 0DF01B081E3CE50BBDCBDC81675BF37D /* Products */, + 1DE6FAA609C485D46D33025D8815325B /* Targets Support Files */, + ); + sourceTree = ""; + }; + E4252E85FC6716FF11013746B8F44E37 /* UIKit */ = { + isa = PBXGroup; + children = ( + 856EEADEDD158D4873F666AE218DE570 /* PMKUIKit.h */, + 28AEFC12990DE5857B6C8C3DD151EE7F /* UIView+AnyPromise.h */, + 3C843E59BC22FDE9FDA54491D8F3ECCC /* UIView+AnyPromise.m */, + 43B7747EAA000C9B48B5D7B826AE8AA9 /* UIView+Promise.swift */, + 45780CFDD8941B525B61D0A0EFBAC14C /* UIViewController+AnyPromise.h */, + EE4EAD1D53584CBDC586BA9499EE0D68 /* UIViewController+AnyPromise.m */, + 18E0CD9ADEB45DAE398F37822641499A /* UIViewPropertyAnimator+Promise.swift */, + ); + name = UIKit; + sourceTree = ""; + }; + EA617AD493EDC04B65EFFFC557881C4C /* BigInt */ = { + isa = PBXGroup; + children = ( + E00B9DD5F289EBCC20B485163A92C9CE /* Addition.swift */, + DA2CE9B55293B0E2D65F19AB1EC631B0 /* BigInt.swift */, + 8907A4B63AEF5B00260E490E38ACCE3E /* BigUInt.swift */, + 3241E63D9616921B2EB997B33DA65015 /* Bitwise Ops.swift */, + 9C1F8F8C962B269D1B535A7E69211345 /* Codable.swift */, + 91E170E8B0E46F448434AEDA45BE7201 /* Comparable.swift */, + 7B6DFC9E27C5C2579817751B89E04F28 /* Data Conversion.swift */, + 2AEB64E397C62A9D958096179BE64189 /* Division.swift */, + 53D054812BB57BDE3069179B7945A4A4 /* Exponentiation.swift */, + F7C21A8D4CE9BE9389B1B027A7F1684A /* Floating Point Conversion.swift */, + DCAEE90730AA63BAC2B8BA0C11298D49 /* GCD.swift */, + 1C1C57972351C9020E941D25D57CF959 /* Hashable.swift */, + 9B580076A33C54363F117FC48118156B /* Integer Conversion.swift */, + 6F928DE9F728F034C42EF3E84EBB5B6A /* Multiplication.swift */, + 5C95BF67289C881540C0022C3E712E2C /* Prime Test.swift */, + 83EB318EEB278287224355CBE3049A48 /* Random.swift */, + 79E64ADA63C8893846700495EA1FC27C /* Shifts.swift */, + 2E5F6F994922528B6B9B3A5BB5E2DA3A /* Square Root.swift */, + 586F3C5571C6E148E0D1950D6CBF1949 /* Strideable.swift */, + 407155CEAA8C92477629A14B47475F1D /* String Conversion.swift */, + D9BED5D4428FA6E60B2D58D86DACD87E /* Subtraction.swift */, + 5C8F369ECC895BB94124AC2173EB80ED /* Words and Bits.swift */, + 80B7A94A648E0A02BA2B76640AFA293F /* Support Files */, + ); + name = BigInt; + path = BigInt; + sourceTree = ""; + }; + F3546E2E51E644ABBE0B8ED0EDF59D41 /* Starscream */ = { + isa = PBXGroup; + children = ( + 807F4EF0F6896F7BEB55DDE65E4CB28F /* Compression.swift */, + 94D92C0E313BED051BC11C45A95CCFFF /* Data+Extensions.swift */, + 4C3A07D69D081152A01DECBBDF98D24A /* Engine.swift */, + 5F1ACC0AA6AEE873BA635D09E510F5F1 /* FoundationHTTPHandler.swift */, + C9AA32BC8F1750426BE685F2689370B7 /* FoundationHTTPServerHandler.swift */, + F0A6F2A78FDE414D85D2A8DC74021C1B /* FoundationSecurity.swift */, + 4B5D14DD6AF865E5CDA4F6D296D7766C /* FoundationTransport.swift */, + C321EB417B11D2E05909E2F4DBF30D9A /* FrameCollector.swift */, + F8C128F18673E79A6E143D83ECDB3AEB /* Framer.swift */, + 8AA0DDDD58D43515BE066493834EE7F7 /* HTTPHandler.swift */, + 5C3AD67954329D1C955D54EF41C4508F /* NativeEngine.swift */, + 21DA00ACD8F03D5A27C632034D5215B3 /* Security.swift */, + FC11C1CC2479584E9A41405F284BF604 /* Server.swift */, + E76D73543A413D250E98C170B65439FE /* StringHTTPHandler.swift */, + BD500378BD304B7A5348A9CB1F342D3B /* TCPTransport.swift */, + BD85842A42223204E3C0C2184192C905 /* Transport.swift */, + 37808DC2E27049822F0681074BF7D960 /* WebSocket.swift */, + 38E0F1A25A1345D8458B0FA85EF949FD /* WebSocketServer.swift */, + 93782C7F3F539959B04BE436295FD94A /* WSCompression.swift */, + 3B81B518FB1855580F5B38EBB277693E /* WSEngine.swift */, + 38FF7B99E4C0BC8A75F62E500F3A8994 /* Support Files */, + ); + name = Starscream; + path = Starscream; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 32DA596662685778F05D01D89B471955 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 6722DCA670229327597ADC3D81BB492B /* BigInt-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 3CBD0F9C48772E87C2F80436B70E099E /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 00C9C2E54995B3BEA1C999016833A58B /* Starscream-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 43499B31101B3D326A23A3AB5D53BCDD /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 27CBC2848BD67A27962F94ADFB6EE9F1 /* AnyPromise.h in Headers */, + C8B899C850EC6CB3C9BF2841FB08713F /* fwd.h in Headers */, + 42A7EF29E4ED3462980668F7D1A314F0 /* NSNotificationCenter+AnyPromise.h in Headers */, + 6F3BEBAC10EAF8A5905743446825E679 /* NSTask+AnyPromise.h in Headers */, + 9845537646543D7DC920C2AD80F8EF9E /* NSURLSession+AnyPromise.h in Headers */, + BAF082E2C779B6367E8D10E3433AB145 /* PMKFoundation.h in Headers */, + B5BB95D002BE731F12AE07C27F14B375 /* PMKUIKit.h in Headers */, + 356CD819C1A9BB628BF2E2069D60E9E3 /* PromiseKit.h in Headers */, + 48AA519849266C20CF080A37887CFC4E /* PromiseKit-umbrella.h in Headers */, + 111FC0F6882063120869EF91908DF16F /* UIView+AnyPromise.h in Headers */, + EC1939718B30E2C224E107770EFA15E8 /* UIViewController+AnyPromise.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 54CC29BEDAD947BB22E2EFB39A59BA83 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 35D72B56E9BC4ACB7F5BE95D51CB99DB /* web3swift-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 68D420E85BF80DB1A608AF60ABDB947E /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 4A2FBA2940ED4665F72CD57ECB29D7C3 /* Pods-myWeb3Wallet-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6A7BB6AF36FCE03733D028661957DB1E /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 32DF053AF55490DBBCC8F5A4135E7A48 /* CryptoSwift-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 84BD713068F962FA94F8782B4FBD7D0D /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + DA5F6B91BDDA4FE3C6104DCEC0866921 /* basic-config.h in Headers */, + E21CF0BAEC9DC901D45DDCEEA2C44E45 /* ecdh_impl.h in Headers */, + E3D6C010B605EA8EDF757BB7965A18F5 /* ecdsa.h in Headers */, + E080D5147262BC05559D3F88A251D496 /* ecdsa_impl.h in Headers */, + F9787C205394000FA66B667A2AC04FD6 /* eckey.h in Headers */, + 81F5F30E31C813D81A5817F7E7E365A6 /* eckey_impl.h in Headers */, + 61FD8163938789077FD24D6DBF71267D /* ecmult.h in Headers */, + 90917685A8320E6EA465DD4A26710930 /* ecmult_const.h in Headers */, + 6803A39AC3E9B559343724A39AE87122 /* ecmult_const_impl.h in Headers */, + 25EAD62FC5B8B10618A50D8710CA6FFF /* ecmult_gen.h in Headers */, + B710B3A9760EA48DD6C222EB5DB31C20 /* ecmult_gen_impl.h in Headers */, + 817DC6B99063211DC0E1B9C2740882F1 /* ecmult_impl.h in Headers */, + E65FCA7A3C97C063DCDB2B15787E7BC7 /* field.h in Headers */, + 63B2F0E7E22199EE517A3F49AA875795 /* field_10x26.h in Headers */, + B7B6E51E810DB18BFE07548B182B6B3C /* field_10x26_impl.h in Headers */, + D2D4D144266F4423CD3653BCBE240D07 /* field_5x52.h in Headers */, + 46C113C932265323297D3C3145C5E638 /* field_5x52_asm_impl.h in Headers */, + 11090FE18EB7578CE49394EBB95A661A /* field_5x52_impl.h in Headers */, + 30EC1D1D6D674E8A411967FB331A1F1B /* field_5x52_int128_impl.h in Headers */, + 3146A3C48334D88815AA965667D730E9 /* field_impl.h in Headers */, + E6D66EE992F5F92BBF5D7C9D9DBB1D70 /* group.h in Headers */, + 5CF32D784CCDEF1DE36C794BEB15381C /* group_impl.h in Headers */, + A6F2904CBA08087504F4507A93D6663C /* hash.h in Headers */, + 36CFCB8A8BE261FBAC0B909211F757F9 /* hash_impl.h in Headers */, + 1525B8EE9316C18DEB58EEA8A75664D2 /* num.h in Headers */, + 250A73D3EDFC531315F6574D341A8B8D /* num_gmp.h in Headers */, + 73FD1A5FE33F66C7A009C6EDB22D9FEB /* num_gmp_impl.h in Headers */, + 515AA56FAACC390CF7CD1454FA0B31B3 /* num_impl.h in Headers */, + E7D5EAA730340EF382A7A87B70232C90 /* recovery_impl.h in Headers */, + 8A6DA5FBD77B428568A3F4C38F6B0DE1 /* scalar.h in Headers */, + 5E25E52634BBF945012D22B59F98F00B /* scalar_4x64.h in Headers */, + 04CFB084C47424C66DEA6F2EF4245180 /* scalar_4x64_impl.h in Headers */, + 0C3B8A0993483F89626BBCF38A90F62A /* scalar_8x32.h in Headers */, + 9AD01F25B759252CEDDB74549327971D /* scalar_8x32_impl.h in Headers */, + 67DC631DEB505ECF30C138922C25067F /* scalar_impl.h in Headers */, + C3AD5637CD16B453B6BEDC56EFE74130 /* scalar_low.h in Headers */, + 1206729EEB0C6684BCCB2F23EAA222D1 /* scalar_low_impl.h in Headers */, + C31C553CC452563D5E1B3E2EB53E6CB3 /* scratch.h in Headers */, + C5DDDCCA557F626F4124A8F58E299EEF /* scratch_impl.h in Headers */, + C3244A82259871FF39B6AD13D0925DBE /* secp256k1.h in Headers */, + 35DE8211AD1CC534C07D3F4C19554DAE /* secp256k1-config.h in Headers */, + 7BA954F43FEC18BC48D0B6645C0DB9AF /* secp256k1.c-umbrella.h in Headers */, + 7F279180DF50A0D4CD17049A0D96F251 /* secp256k1_ec_mult_static_context.h in Headers */, + 761FF2D686D4CDDFEB9228CC18C2C8A7 /* secp256k1_main.h in Headers */, + 03804F779AD26607550ABB2C65DA16F3 /* util.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8F164BEB2185C19B32229F4183B5BB99 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 3677C4124E6F08101341038E13D12D6A /* Pods-myWeb3WalletTests-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E8C9A46B10567DD46F2C7B065D9EBCC2 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + CFA3A9074716531683DA2E55B301B9CE /* Pods-myWeb3Wallet-myWeb3WalletUITests-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 01B7BE33AF0E815732B54D742D28919B /* Pods-myWeb3WalletTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = E6AF999F03FA681AA8CB1291CE5AED0F /* Build configuration list for PBXNativeTarget "Pods-myWeb3WalletTests" */; + buildPhases = ( + 8F164BEB2185C19B32229F4183B5BB99 /* Headers */, + DFD2A1446AD3B5EBD8804208A1158398 /* Sources */, + 2999E7F81F8757C3D08FFF9F9F7FEAEC /* Frameworks */, + 49089828ABA8F484711EB0F28D23C188 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 3086A555869F80DA53A2BBB80DD88499 /* PBXTargetDependency */, + ); + name = "Pods-myWeb3WalletTests"; + productName = Pods_myWeb3WalletTests; + productReference = 11103C5C5CFDD9B3B2EA4E84B98049A8 /* Pods-myWeb3WalletTests */; + productType = "com.apple.product-type.framework"; + }; + 09DD83B7D075842A3A5105AD410BD38A /* BigInt */ = { + isa = PBXNativeTarget; + buildConfigurationList = 6C696C8CA41BB855C8D3F30C1B2DEF51 /* Build configuration list for PBXNativeTarget "BigInt" */; + buildPhases = ( + 32DA596662685778F05D01D89B471955 /* Headers */, + 3B4BFA6C78E7E27765466DEF2EBB6DA9 /* Sources */, + 11379356021538EC61B49D0E27E3FEE9 /* Frameworks */, + C776F6A64A073BE88CD07D9069E3346C /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = BigInt; + productName = BigInt; + productReference = 91BB24BA472AF523E913108C9AA301F2 /* BigInt */; + productType = "com.apple.product-type.framework"; + }; + 161C26511FC920CB146236AB7295D5E0 /* secp256k1.c */ = { + isa = PBXNativeTarget; + buildConfigurationList = D756344E005625A3A276DA3970106F9A /* Build configuration list for PBXNativeTarget "secp256k1.c" */; + buildPhases = ( + 84BD713068F962FA94F8782B4FBD7D0D /* Headers */, + F227B85FED12DE69DD97C29CE2DAC9C5 /* Sources */, + C62F957CA0152686080C49F0278A3D8C /* Frameworks */, + B225869BD1EE8CAD4CEDB616FF00648C /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = secp256k1.c; + productName = secp256k1; + productReference = 332A47430CFF99501D563788C7AAF1D2 /* secp256k1.c */; + productType = "com.apple.product-type.framework"; + }; + 7C579CE66A1E7A9AA33CA5F97F9C22C5 /* PromiseKit */ = { + isa = PBXNativeTarget; + buildConfigurationList = 6B19066629BE27A8DFEB4831975D91D9 /* Build configuration list for PBXNativeTarget "PromiseKit" */; + buildPhases = ( + 43499B31101B3D326A23A3AB5D53BCDD /* Headers */, + 489A4CAFE02BDB0955D99B1ECEE4C89C /* Sources */, + 5648DAEA2334E42B6530BAD0A78B94F3 /* Frameworks */, + DAF961E85CA273DC3709F051EFD89CDE /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = PromiseKit; + productName = PromiseKit; + productReference = 002B1E88BA14EBF633CD66EBFBA107E9 /* PromiseKit */; + productType = "com.apple.product-type.framework"; + }; + 8CDD759A6130CA265C6D157F4407C39B /* web3swift-Browser */ = { + isa = PBXNativeTarget; + buildConfigurationList = 2734E633ACE1F1D41E7843894EDCFD74 /* Build configuration list for PBXNativeTarget "web3swift-Browser" */; + buildPhases = ( + 8C702DEB16B94580E348F78E93064EB7 /* Sources */, + 9DCB20D57B46BAC0FF156D5A84727D99 /* Frameworks */, + C91790E0FD596EC59E991C501A25BC7E /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "web3swift-Browser"; + productName = Browser; + productReference = 12DC6A0FDF284A2C935F5EA9F6111B0B /* web3swift-Browser */; + productType = "com.apple.product-type.bundle"; + }; + 99313990C1D76A6D1D017868B6975CC8 /* CryptoSwift */ = { + isa = PBXNativeTarget; + buildConfigurationList = 1D8A228996DBC2C7D966D9172843C34A /* Build configuration list for PBXNativeTarget "CryptoSwift" */; + buildPhases = ( + 6A7BB6AF36FCE03733D028661957DB1E /* Headers */, + 6A2C2598D12411E934808B8ED3C7FB49 /* Sources */, + 786D2BEBB917377ADEA762CD9F9E20D6 /* Frameworks */, + 5BB9A0249DF492C4BAB8BC913F4991A0 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = CryptoSwift; + productName = CryptoSwift; + productReference = F81274EDB681F11E7CB05F7DCA2BB33C /* CryptoSwift */; + productType = "com.apple.product-type.framework"; + }; + 99364D9FB07EF3FA5DFE1237001805EC /* web3swift */ = { + isa = PBXNativeTarget; + buildConfigurationList = 735BBB520ABA2DF1E93DB75A450177A8 /* Build configuration list for PBXNativeTarget "web3swift" */; + buildPhases = ( + 54CC29BEDAD947BB22E2EFB39A59BA83 /* Headers */, + 9F391305229D1ABBFE0E5A3D6D2D38B3 /* Sources */, + 2BDC8040898B74CED208461196194B59 /* Frameworks */, + C6DF0A3D09BA9091AE0ED4FB28B66D5C /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 74A25246C32631145B8838160ED36C92 /* PBXTargetDependency */, + 63D170EE39D5092F7426150E640DD281 /* PBXTargetDependency */, + 9746A010E0BC1FD85524A71F8F8C1A7A /* PBXTargetDependency */, + 89BEF22CC5ACFF215A0FFC4DD05EE88D /* PBXTargetDependency */, + 0CE786DB75401B50279902C8690DDC2D /* PBXTargetDependency */, + 9ED29C136CB3A4EBB334873ED0F6C9B8 /* PBXTargetDependency */, + ); + name = web3swift; + productName = web3swift; + productReference = 8A2449DF78D58AD33A7C7504BB3F38A0 /* web3swift */; + productType = "com.apple.product-type.framework"; + }; + 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */ = { + isa = PBXNativeTarget; + buildConfigurationList = 5E342B11DDD91D2A8D5CEC382A58F29D /* Build configuration list for PBXNativeTarget "Starscream" */; + buildPhases = ( + 3CBD0F9C48772E87C2F80436B70E099E /* Headers */, + 3CBD844312542615DF274F62D22D823A /* Sources */, + 22579CC44F871C4C542FC182B991B33C /* Frameworks */, + 6D93F8ECBEC0B1B601F31CAB9D03FAA2 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Starscream; + productName = Starscream; + productReference = 891B2270823847ED23F2ECFC28F935EC /* Starscream */; + productType = "com.apple.product-type.framework"; + }; + A3E8E30CED7400C4962623E6F83EC78E /* Pods-myWeb3Wallet-myWeb3WalletUITests */ = { + isa = PBXNativeTarget; + buildConfigurationList = D728746CE0580C7EEAFD661D5F19A9FA /* Build configuration list for PBXNativeTarget "Pods-myWeb3Wallet-myWeb3WalletUITests" */; + buildPhases = ( + E8C9A46B10567DD46F2C7B065D9EBCC2 /* Headers */, + D4E5535E2B0318F44A991BAAAA2DDF03 /* Sources */, + 1DD57ED84B39C7D18075D5049C2BAFAE /* Frameworks */, + 46906B25F2E1D625154604BD1A76B60B /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + E0450CA8268C6456684BA11141374A51 /* PBXTargetDependency */, + 20C85CF454F1DDE661349F885F7FD2C7 /* PBXTargetDependency */, + E9775AFCC98177929A8AE3120B308389 /* PBXTargetDependency */, + 2425DF0705E44B7444CF653B14385A29 /* PBXTargetDependency */, + 433FDD8CBF083DB1BE68D05B5BF77265 /* PBXTargetDependency */, + 9A43BD2A3C1F62F8E117C2734F6AC403 /* PBXTargetDependency */, + ); + name = "Pods-myWeb3Wallet-myWeb3WalletUITests"; + productName = Pods_myWeb3Wallet_myWeb3WalletUITests; + productReference = 8DB09F270FE9B4BDA5AFBD4357E646CE /* Pods-myWeb3Wallet-myWeb3WalletUITests */; + productType = "com.apple.product-type.framework"; + }; + D89A752AFCCF1B411FDB91762F626B42 /* Pods-myWeb3Wallet */ = { + isa = PBXNativeTarget; + buildConfigurationList = 95EAF2FFD6A9EBA4F314D141A882DCAA /* Build configuration list for PBXNativeTarget "Pods-myWeb3Wallet" */; + buildPhases = ( + 68D420E85BF80DB1A608AF60ABDB947E /* Headers */, + 50611CC9A5470C1258496BE25102EB37 /* Sources */, + 7B3773E0103304DCF4AE1B4BC37BAFAD /* Frameworks */, + EC13F6837E065DDCF70A15186BB64DFA /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 0A319787049075842C826957A1837D87 /* PBXTargetDependency */, + 5CCFA49E1B6DFBC27A8BDF86CBDE7265 /* PBXTargetDependency */, + D89ED8CB4BFE5C0381163C63C9B2800D /* PBXTargetDependency */, + 2888DACD43CFAC618AF1676A71461439 /* PBXTargetDependency */, + 07213640700D764F2448129740400674 /* PBXTargetDependency */, + 88A0B3215CDCA0FEF74CF84893F25E35 /* PBXTargetDependency */, + ); + name = "Pods-myWeb3Wallet"; + productName = Pods_myWeb3Wallet; + productReference = 08A8472B9823BC68472175977392F4B9 /* Pods-myWeb3Wallet */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + BFDFE7DC352907FC980B868725387E98 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1240; + LastUpgradeCheck = 1240; + }; + buildConfigurationList = 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 13.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + Base, + en, + ); + mainGroup = CF1408CF629C7361332E53B88F7BD30C; + productRefGroup = 0DF01B081E3CE50BBDCBDC81675BF37D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 09DD83B7D075842A3A5105AD410BD38A /* BigInt */, + 99313990C1D76A6D1D017868B6975CC8 /* CryptoSwift */, + D89A752AFCCF1B411FDB91762F626B42 /* Pods-myWeb3Wallet */, + A3E8E30CED7400C4962623E6F83EC78E /* Pods-myWeb3Wallet-myWeb3WalletUITests */, + 01B7BE33AF0E815732B54D742D28919B /* Pods-myWeb3WalletTests */, + 7C579CE66A1E7A9AA33CA5F97F9C22C5 /* PromiseKit */, + 161C26511FC920CB146236AB7295D5E0 /* secp256k1.c */, + 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */, + 99364D9FB07EF3FA5DFE1237001805EC /* web3swift */, + 8CDD759A6130CA265C6D157F4407C39B /* web3swift-Browser */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 46906B25F2E1D625154604BD1A76B60B /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 49089828ABA8F484711EB0F28D23C188 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5BB9A0249DF492C4BAB8BC913F4991A0 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6D93F8ECBEC0B1B601F31CAB9D03FAA2 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B225869BD1EE8CAD4CEDB616FF00648C /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C6DF0A3D09BA9091AE0ED4FB28B66D5C /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 89516187419F3D7FC4037DC8931E2A2A /* web3swift-Browser in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C776F6A64A073BE88CD07D9069E3346C /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C91790E0FD596EC59E991C501A25BC7E /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + DC538415218A5989D1CE2A5134CBC050 /* browser.js in Resources */, + 7AD846FD5AA7B41459E986CB1F8892AB /* browser.min.js in Resources */, + 84F7E0BA0554DF5310C76651797593AF /* wk.bridge.min.js in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + DAF961E85CA273DC3709F051EFD89CDE /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EC13F6837E065DDCF70A15186BB64DFA /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 3B4BFA6C78E7E27765466DEF2EBB6DA9 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + D6BF0D382E2E68028AAF3CA080E941E8 /* Addition.swift in Sources */, + 81DEE0975FD2488D5C61D099F17DC3FA /* BigInt.swift in Sources */, + 7090F68043DADD044880B9A4DDB571E7 /* BigInt-dummy.m in Sources */, + 6A6D768A74F8BFBABED2364907A2DF0C /* BigUInt.swift in Sources */, + EC95784DCA76E26345C1E5090C1B1850 /* Bitwise Ops.swift in Sources */, + 17C20D68963C252E9991CD7361723892 /* Codable.swift in Sources */, + F41028D4E0E43E885ED9ADDFABBE1ED3 /* Comparable.swift in Sources */, + B96BCDA4AF618BF171AA502CC84FCD8F /* Data Conversion.swift in Sources */, + 55D3C00883F2CA52FE8F11468E97CB50 /* Division.swift in Sources */, + A81F5E7AC6A31EA09FB5B0CD5ECBA22E /* Exponentiation.swift in Sources */, + 540CC89836D830624883860F4AD3EAB0 /* Floating Point Conversion.swift in Sources */, + E4A7207A022D9584CD9B7D29381C8454 /* GCD.swift in Sources */, + DDA8E54FFAA6DFF7E15F15A52AB7C662 /* Hashable.swift in Sources */, + F95103DB3CDE985249C0B9E4CD464BA0 /* Integer Conversion.swift in Sources */, + D1691005C5FF403516FCA539B0E8038E /* Multiplication.swift in Sources */, + DA6EDABF74C3C6E9F9997B698195D6A2 /* Prime Test.swift in Sources */, + F5F0562EFC8A4222EB84980F223E6C15 /* Random.swift in Sources */, + 77651F160816E699EC490DD9D3F9BE02 /* Shifts.swift in Sources */, + F81E16CDC41BE1CB2C103F910F5FFC70 /* Square Root.swift in Sources */, + 73E1178AD16F91C80A718FB778F3534A /* Strideable.swift in Sources */, + 381D42ECF079E81454D3418F6DCC3B0B /* String Conversion.swift in Sources */, + 40A09F5E948345A60B856BB7C3BB5FE3 /* Subtraction.swift in Sources */, + 00C22009B3BEB45AE5A45805DEDCC316 /* Words and Bits.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 3CBD844312542615DF274F62D22D823A /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + DFA2736CE4B16FD4D82450863EC58507 /* Compression.swift in Sources */, + 631654C419F62FE0270E1DF79CCF6F8B /* Data+Extensions.swift in Sources */, + FAFD54F649DC5D69DD05D517A0131968 /* Engine.swift in Sources */, + 4AB6FCF35B998F60ED9EB100542EEA31 /* FoundationHTTPHandler.swift in Sources */, + 5006DD4B60A05AF56EA0706A680BABF6 /* FoundationHTTPServerHandler.swift in Sources */, + 5281197FE8CC6E6954315F11B8F553D0 /* FoundationSecurity.swift in Sources */, + 489EF4A7D4992C47CF590AEF9AA418FC /* FoundationTransport.swift in Sources */, + EB5C3537AD21658D3EC873A4A4AFDE30 /* FrameCollector.swift in Sources */, + CC235941F0CF9FA8C0FA3323A0D18203 /* Framer.swift in Sources */, + 7DDEA2F73F2A02D88D5164B46BA2C7E8 /* HTTPHandler.swift in Sources */, + C28A0006DD1C9AB062763C8FA2B3F93D /* NativeEngine.swift in Sources */, + 69A591F2BDE4941B391C102F4C26B115 /* Security.swift in Sources */, + DF9BE4B3E95B007977780C9EFDA3EFBE /* Server.swift in Sources */, + 3A655D6817E99F062266BB601B0EEEDF /* Starscream-dummy.m in Sources */, + 046AC7AA224C78A31C0A8FACB11D2D28 /* StringHTTPHandler.swift in Sources */, + 6C0DACBE00A34619DEDB9A65CB959BA5 /* TCPTransport.swift in Sources */, + 4A3B1BE129FDA231AC217E1C6DB2B8C8 /* Transport.swift in Sources */, + B44349C69B2C0AF407B678B20DC9CB80 /* WebSocket.swift in Sources */, + 3F3E9C6FF4BCB6F4FF18D9121CC3E42F /* WebSocketServer.swift in Sources */, + FA2A3CCAE01CF0108D2FDB7C8108B988 /* WSCompression.swift in Sources */, + BB056B9351B1BE41C2703393F69623DD /* WSEngine.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 489A4CAFE02BDB0955D99B1ECEE4C89C /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + B4370097668317938388822CCCB98FA7 /* after.m in Sources */, + 483EB89DCAC11F3DE7417CB7C1347B30 /* after.swift in Sources */, + 8919A8100FF0A5D62AB5D254FC884684 /* afterlife.swift in Sources */, + FF3F808C427F7277B5EBDD62E3322B77 /* AnyPromise.m in Sources */, + 993A37B49B1F029A7230A422C32010CC /* AnyPromise.swift in Sources */, + 3F13BADB5C20FB262EE3775E63BBE651 /* Box.swift in Sources */, + DEA8679395E5618A8513EA80D9772EEC /* Catchable.swift in Sources */, + E70F74FB30DAEB297AA089C8BCCCA4EB /* Configuration.swift in Sources */, + D64729DEA5CA52814AA8B431714ABDAF /* CustomStringConvertible.swift in Sources */, + F63C0FC83982E1034CB316A7EA644E6E /* Deprecations.swift in Sources */, + 3C9B4A7F40A52FF015F77982686268B4 /* dispatch_promise.m in Sources */, + 732B28B03918D36B68BD44C77D4BE887 /* Error.swift in Sources */, + ECA87472345DEE9383C99B94132989C8 /* firstly.swift in Sources */, + E1D133E30A0D32065EE248F784F8020D /* Guarantee.swift in Sources */, + E85A27344F3B51082781DB3E11724E36 /* hang.m in Sources */, + 83EA6B046238B37ED950FC865BB09333 /* hang.swift in Sources */, + A81D0F710AFFC62E73BE7DA8858D621F /* join.m in Sources */, + 4A649680EC213DCD0700A1A284EB25D5 /* LogEvent.swift in Sources */, + B563F57CA44978152ED30C459DBC60AE /* NSNotificationCenter+AnyPromise.m in Sources */, + 9B97A0473C8550F7DEA98DE7AFE25561 /* NSNotificationCenter+Promise.swift in Sources */, + 273196B0B3608A30286680B9C02EEAF5 /* NSObject+Promise.swift in Sources */, + 506CB45161F5B9A01351C0AD278C4AC0 /* NSTask+AnyPromise.m in Sources */, + DCFC2730C2AB6CA444EFE289DC32F045 /* NSURLSession+AnyPromise.m in Sources */, + 8581F08BC311452D4C2E78935C50A840 /* NSURLSession+Promise.swift in Sources */, + 386CB0388B7BFA54D25DEAD77795EE6A /* Process+Promise.swift in Sources */, + 37107A9CADEE7783B6E9F32D2005B90B /* Promise.swift in Sources */, + 5C51E4EF06F496800E089CB1EE79DAD2 /* PromiseKit-dummy.m in Sources */, + 24C10118785187B6AAA9A679CBE8E545 /* race.m in Sources */, + 8194B9F767F5E98AC6290833A2CFD773 /* race.swift in Sources */, + 98BD0C2567194580042F4196CFD3C861 /* Resolver.swift in Sources */, + F9087DABB154530427BC4540C43E5853 /* Thenable.swift in Sources */, + 899599790D1F3E0DE49CA1985E123C35 /* UIView+AnyPromise.m in Sources */, + E256732DB3DBDEE4FD44CD303C1DE53A /* UIView+Promise.swift in Sources */, + 199B4DEFE236E08AA698E8283BA44F8E /* UIViewController+AnyPromise.m in Sources */, + 8409D5F7623FD7CBC3D928CA463A69E1 /* UIViewPropertyAnimator+Promise.swift in Sources */, + 39480C33D789611BB90F3B3C12712A8C /* when.m in Sources */, + 7F4EC5B61AB392C6B9F3A6D34CE21E1E /* when.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 50611CC9A5470C1258496BE25102EB37 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + AF2BB4FA178564DBB1D24B5EFBD63951 /* Pods-myWeb3Wallet-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6A2C2598D12411E934808B8ED3C7FB49 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 8DA36E33306EFAA1275D13B978BB8666 /* AEAD.swift in Sources */, + 45670E07AAFDE8877911FA0FA180E8C8 /* AEADChaCha20Poly1305.swift in Sources */, + 89F43849392A22634685D2CC339648EA /* AES.swift in Sources */, + 4764DB91CAEF26CA6EED99CB71389637 /* AES+Foundation.swift in Sources */, + E9B1EE521C74E68921DD97D24EDC388A /* AES.Cryptors.swift in Sources */, + 1895D0230B557364AF8E4225FB4C4ABB /* Array+Extension.swift in Sources */, + EC7222CB5D2208398F18AAE16373D49A /* Array+Foundation.swift in Sources */, + D86D490CF982E629A578DED0E89F146F /* Authenticator.swift in Sources */, + 1C69EAC3F56DA086FD3A08EA63ADF06F /* BatchedCollection.swift in Sources */, + B9D1270EAADE0A1F38D25EC5ABC096F0 /* Bit.swift in Sources */, + 29EBEF45DCEC1D6568413032FA8FB2DB /* BlockCipher.swift in Sources */, + 53042D9D194CD8BE861A5DD3781EF261 /* BlockDecryptor.swift in Sources */, + 0064D372D96A53E5C7173A6DF531097B /* BlockEncryptor.swift in Sources */, + C10AEAE3170856A4A6ED972AF8CCFF4A /* BlockMode.swift in Sources */, + 4788461CD9B764A0C5E1E8A7E7304C6D /* BlockModeOptions.swift in Sources */, + DE39DBC5AAF719AFBCB7BB50025A772B /* Blowfish.swift in Sources */, + 9E1EB59875B9875193013A10277645FD /* Blowfish+Foundation.swift in Sources */, + 2084D75E97F44D8DAE091C7739B06E01 /* CBC.swift in Sources */, + FBCD6D8D56A2086EF53DA7228F7382A6 /* CBCMAC.swift in Sources */, + 2402753327A88FCFBBA79809A123F324 /* CCM.swift in Sources */, + CE7A68CDFD3FC58EF21CC7C08D24CA55 /* CFB.swift in Sources */, + 97F86BC6C70FFFEA6793B21EF6A7BBFF /* ChaCha20.swift in Sources */, + D4135E6CF7800B813179A4DFB88BB112 /* ChaCha20+Foundation.swift in Sources */, + 20B46048A49C3DD9704C96BCA4565A64 /* Checksum.swift in Sources */, + D3E9E3F249E8D3D98C4E51836BDC4954 /* Cipher.swift in Sources */, + 56706731EFD3AF6092CDAF8359B039B8 /* CipherModeWorker.swift in Sources */, + F54936D6E4E4D8360799608587FBE650 /* CMAC.swift in Sources */, + 1D691C9D33B859BCF205B302404CF87E /* Collection+Extension.swift in Sources */, + 75D390E13DBF964D209460FE9823C8A8 /* CompactMap.swift in Sources */, + 23845E588BE52974DCE35EA857812D17 /* Cryptor.swift in Sources */, + 740428CF593D2EFC7C536FB684255CD1 /* Cryptors.swift in Sources */, + B2AF71C08A4349665AEA3D6EC7F4A2C8 /* CryptoSwift-dummy.m in Sources */, + F7B5F76F363F06CC58B18C19A4132205 /* CTR.swift in Sources */, + 353721D2B910AE4F9B8196D7277242ED /* Data+Extension.swift in Sources */, + C1560D479D2C4290339F2153A1009695 /* Digest.swift in Sources */, + 5D924D51FD5DB39A62A16D0A476D81E2 /* DigestType.swift in Sources */, + 804059882A1C76A538EAED6E464A7DCE /* ECB.swift in Sources */, + 7E55502F0987E7318FF739C9DDAC7387 /* GCM.swift in Sources */, + 44A337C99C192862AC3E83D633178550 /* Generics.swift in Sources */, + 11EA2C9D241AB9B6E1EE8B5E1B9DA27F /* HKDF.swift in Sources */, + 6400D521667A6DE758C821E3ED5B2694 /* HMAC.swift in Sources */, + 6CCA055AE1F2015447DE2CD4AC0980AE /* HMAC+Foundation.swift in Sources */, + 55018C7112A943BE15FB9735839CB8AE /* Int+Extension.swift in Sources */, + 3BF80B98213E4900761B8E9C6FD57947 /* ISO10126Padding.swift in Sources */, + 02015E32C1E060B9432843635FAAD128 /* ISO78164Padding.swift in Sources */, + 770635827551A8B7C42C7BC958A55138 /* MD5.swift in Sources */, + ADBA50B933B7B857BC80FD659DA51DE9 /* NoPadding.swift in Sources */, + D618594A60716C12B8FBAA73F18EC31C /* OCB.swift in Sources */, + 2EF5C6A10700B5ACBD45F9D0461389A5 /* OFB.swift in Sources */, + 0933E9216A313795C94BEC005FD9DDE1 /* Operators.swift in Sources */, + F7462C6596BBFFFF4EFB9DC8BA39B18F /* Padding.swift in Sources */, + 3903D867E1B04DF17B5ACB08E4D496F5 /* PBKDF1.swift in Sources */, + 53BF0FE77A91BC99F2CBA559D91F105F /* PBKDF2.swift in Sources */, + B20CD5B9D658110F9C374648D8FE753E /* PCBC.swift in Sources */, + 2FCC2C2EE5BA2372F3CCF70DAA028085 /* PKCS5.swift in Sources */, + A5D3E40DA041B9B570227F4D8EA1F8E1 /* PKCS7.swift in Sources */, + 92D3DA8C66C63AD5AB2FB84F76591AA5 /* PKCS7Padding.swift in Sources */, + 0BBE8EF207B633F9DEEB7A6CE93B7DA2 /* Poly1305.swift in Sources */, + 334D28B6349CDD6C4851C6ED56DFF411 /* Rabbit.swift in Sources */, + E793B49B0F4F9444C35C938A84919D59 /* Rabbit+Foundation.swift in Sources */, + FA0502B3678EC835EAEAB000529D762E /* Scrypt.swift in Sources */, + 665964C5782D23DD55BD1D2B807E4740 /* SecureBytes.swift in Sources */, + 777E977F2C1ED28B2CBFC455C41243B3 /* SHA1.swift in Sources */, + 542C9E8C1561679C2B9596C7653D375E /* SHA2.swift in Sources */, + 61AFA71D5ECCF93F2B7F2E177E6C4DA6 /* SHA3.swift in Sources */, + 95DDEA387C9E5E0FE454158A6175FA88 /* StreamDecryptor.swift in Sources */, + 6EFD6CAA2430FCC24D44C8F00BBBCFF5 /* StreamEncryptor.swift in Sources */, + A010171CFA2A6782E83B75D63BC34B13 /* String+Extension.swift in Sources */, + 5EEB85730244814F4A58FC258568C9D4 /* String+FoundationExtension.swift in Sources */, + 8BFE8E6BDEFBF870C1D0732BDF8F6967 /* UInt128.swift in Sources */, + CC95169162908F93F653A92A59E440D5 /* UInt16+Extension.swift in Sources */, + 6BEBB9F7819614C8DBB686D19050CA7A /* UInt32+Extension.swift in Sources */, + AD485B7D9A894C44A57593FE64BD654E /* UInt64+Extension.swift in Sources */, + FAF9F208C87105DBB01C49B39CA7F6E5 /* UInt8+Extension.swift in Sources */, + E0137D6D9AE5B6786272CFEE12EE329F /* Updatable.swift in Sources */, + 29EB7FC5FCB017B10C7A56EEC67B6C87 /* Utils.swift in Sources */, + 97BF3CCB628215A7A6336B907EDD84D8 /* Utils+Foundation.swift in Sources */, + 1769CFA2DB5E0CF635CAFDAF134CFFD0 /* ZeroPadding.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8C702DEB16B94580E348F78E93064EB7 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9F391305229D1ABBFE0E5A3D6D2D38B3 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 59AD3E0E5518053D78B7059A0D9333A6 /* ABI.swift in Sources */, + 15EDD300B82F48DAB59A670647F30518 /* ABIDecoding.swift in Sources */, + 66645A63BDFEE73F49F5CB02A5651857 /* ABIElements.swift in Sources */, + 4E6D61DF8A85976F8076223E5E0801BF /* ABIEncoding.swift in Sources */, + 408E22C229EAAA6DD10DF76E76D43D5C /* ABIParameterTypes.swift in Sources */, + BADBCBC40AF8A7B54273A943CE95B566 /* ABIParsing.swift in Sources */, + FF46419E6ED54F61278B20902A49162C /* ABITypeParser.swift in Sources */, + 05C452094C81519037F382ACFD15493D /* AbstractKeystore.swift in Sources */, + 0AF42FC09546096529FCE1002124E5B8 /* Array+Extension.swift in Sources */, + 656274DD559533E013F7A7507EA5D8D3 /* Base58.swift in Sources */, + A06894CA00AB9F73142B07C0AEA4AE18 /* BigUInt+Extensions.swift in Sources */, + 09D23FBC23D8C4443D11C3837C9AA33A /* BIP32HDNode.swift in Sources */, + D8C85DE0B332878402530E6886BF4C87 /* BIP32Keystore.swift in Sources */, + 2F460F00F9A33B5ED6C40151ECD9BEAA /* BIP39.swift in Sources */, + FA846FE4D4519D64A27097EB46DD1D3F /* BIP39+WordLists.swift in Sources */, + 3D689F2BA6C364CDE2ADDEF739BCCDB3 /* BloomFilter.swift in Sources */, + 02EB7AB3F167348018915AA1D80B7A3C /* Bridge.swift in Sources */, + ED6E80F590AC3940E9DAEA8DA0AB5A4B /* BrowserViewController.swift in Sources */, + A29D76A39413F75087F969B6CFDE7EB4 /* ComparisonExtensions.swift in Sources */, + 7A4790EFF61624332A869DB5B4632948 /* ContractProtocol.swift in Sources */, + 36740BCB909B105FD0A557ED6B765FD7 /* CryptoExtensions.swift in Sources */, + 2E62C0CDB26CE9A152EA03ED4DD226C0 /* Data+Extension.swift in Sources */, + A7DC2835A09739C4122A91C072760F98 /* Decodable+Extensions.swift in Sources */, + 75CD48978521FCCA27757CBB4C9B6545 /* Dictionary+Extension.swift in Sources */, + B082BF273B13F5F29830AE9BF2547566 /* EIP67Code.swift in Sources */, + 236A65DB9D500C79D40C220C70377A89 /* EIP681.swift in Sources */, + 01E6F9B981C5D8D89F1FD6AB0BC859B9 /* Encodable+Extensions.swift in Sources */, + C820C6095101F683B6C0ACEEFC39E26A /* ENS.swift in Sources */, + 316108AAD17DFF1BF756D47548EBB77D /* ENSBaseRegistrar.swift in Sources */, + 92142DA2DDD277195E9C53C0078B5BF0 /* ENSRegistry.swift in Sources */, + A4C89AF3E56A327DCF0EB2DD8BBE7D4A /* ENSResolver.swift in Sources */, + 8E561C5734860F21E00521B7821122C0 /* ENSReverseRegistrar.swift in Sources */, + 1189311320B549605D358D44697761C7 /* EthereumAddress.swift in Sources */, + 6FD99909460DF1443891CAD15B044F57 /* EthereumContract.swift in Sources */, + 6A644E230F20B1B3F66C24820E6CE1F5 /* EthereumFilterEncodingExtensions.swift in Sources */, + 4FE2DECEC9EEB3F66A00D2644ED4D109 /* EthereumKeystoreV3.swift in Sources */, + BD7B5B59593F5A42A4315FC7FEE94DE4 /* EthereumTransaction.swift in Sources */, + D7543F214A383F50E45721F7E959CE93 /* ETHRegistrarController.swift in Sources */, + 67ABC00CE97CC79EAB5277F6E007D78A /* EventFiltering.swift in Sources */, + 73E5BA7EB3657E29A685099252150C87 /* Extensions.swift in Sources */, + 1FB5D15B825E0D9A6123C2BA2E710A3E /* IBAN.swift in Sources */, + B327423CEDE6ADD621FDDE4EB64CA187 /* KeystoreManager.swift in Sources */, + 2DB4D0E8314E75FF3989BE61CB9EBD9C /* KeystoreParams.swift in Sources */, + F260472C8FC1056456D14073C24E1B54 /* NameHash.swift in Sources */, + 071F45A06E37AE61A8E282DBE683C72A /* NativeTypesEncoding+Extensions.swift in Sources */, + A424AF99404EDCFA95671E906356927C /* NonceMiddleware.swift in Sources */, + 714C406971A7F2B5ABF94E4205D2BADC /* NSRegularExpressionExtension.swift in Sources */, + 433BD28C8C82DD91ECF97ACF42737303 /* PlainKeystore.swift in Sources */, + 37DDF94A9347F39C3890C375B13CAB97 /* Promise+Batching.swift in Sources */, + C8B562CF6E6CD3D1CF98D9E9F5B606C8 /* Promise+HttpProvider.swift in Sources */, + 2705DCE2E76CF7C762E862A4DE090602 /* Promise+Web3+Contract+GetIndexedEvents.swift in Sources */, + 64115A6A941ABF1FC52D487A931F89C0 /* Promise+Web3+Eth+Call.swift in Sources */, + 77B82372C309D4425D9DD35D2E8DA711 /* Promise+Web3+Eth+EstimateGas.swift in Sources */, + 97A2734DE747032D6ECDFEF6EC98A2F0 /* Promise+Web3+Eth+GetAccounts.swift in Sources */, + CA088D37EFE8AD4496EDC4FA6A1FBE8D /* Promise+Web3+Eth+GetBalance.swift in Sources */, + EB0FA8A87893F91A83545E5D76C55345 /* Promise+Web3+Eth+GetBlockByHash.swift in Sources */, + 669DEC50D4E1FE534D887EABA096B324 /* Promise+Web3+Eth+GetBlockByNumber.swift in Sources */, + 05C6B1FE4CFF7D189F0250C3777A30F0 /* Promise+Web3+Eth+GetBlockNumber.swift in Sources */, + 2E88A7E1C99C8976E83D584B459DBD91 /* Promise+Web3+Eth+GetGasPrice.swift in Sources */, + 2698FAD459869510BE11DCE9C1AA4D92 /* Promise+Web3+Eth+GetTransactionCount.swift in Sources */, + 23258679FEADA6931877999C19B8D386 /* Promise+Web3+Eth+GetTransactionDetails.swift in Sources */, + 403F7C30995445B23F464E67189CCA5A /* Promise+Web3+Eth+GetTransactionReceipt.swift in Sources */, + 5BCFACCBC191DBB0BBBC20E1CA669EBF /* Promise+Web3+Eth+SendRawTransaction.swift in Sources */, + E046D9CFF7D48145B6149CB307FF0DFE /* Promise+Web3+Eth+SendTransaction.swift in Sources */, + 4356CD1634561030CB85A67D18712860 /* Promise+Web3+Personal+CreateAccount.swift in Sources */, + D6412C05ED65D3E6FB4B101125AC47CA /* Promise+Web3+Personal+Sign.swift in Sources */, + 9018A1C77BC4F878B1C45B7B672A0D73 /* Promise+Web3+Personal+UnlockAccount.swift in Sources */, + 7FD4224D8A662AAE276FF6805C6C000F /* Promise+Web3+TxPool.swift in Sources */, + C6251BBAFFC461D3EA4A3D845B4EA44D /* PublicKey.swift in Sources */, + 2BE32B9D65CE57739A7E27AB57E38A4F /* RIPEMD160+StackOveflow.swift in Sources */, + 29678514660C9E368CA5CD6BDD64492C /* RLP.swift in Sources */, + A8C8165B930AEA0CC08F04D97CDB3434 /* SECP256k1.swift in Sources */, + 5376E6AC063434D54E81D9C74D63339F /* String+Extension.swift in Sources */, + 404352DB694F722F24156E60DAAEF79E /* TransactionSigner.swift in Sources */, + 7C40298985F6A3FD96484E34B683A197 /* Web3.swift in Sources */, + 235DC2A2B0A33F450025E3A48D4E0EE7 /* Web3+BrowserFunctions.swift in Sources */, + F51D20305F49B5ECF5C06EF8C156BADA /* Web3+Constants.swift in Sources */, + EB347652A3DBB0D1DDD97E0B2EAC4090 /* Web3+Contract.swift in Sources */, + 51BE8B11021A003A1BD4BF7F36262A50 /* Web3+ERC1155.swift in Sources */, + 6734003FBEA6A85E5E906CB2C0FF303B /* Web3+ERC1376.swift in Sources */, + 72C2B622F9A4E6A107CFFF3702FA1CF8 /* Web3+ERC1400.swift in Sources */, + 1152E8C62683CC15F069961C6E5FDA7A /* Web3+ERC1410.swift in Sources */, + 55F3D8488C5D52A1CE1E7278815FFB6A /* Web3+ERC1594.swift in Sources */, + 8DFD0B804F18ADF14E578F6D17536319 /* Web3+ERC1633.swift in Sources */, + 342027080905184D5B5D28DCA694FD70 /* Web3+ERC1643.swift in Sources */, + 3D62BBA23B2EA2EE05F1F669B0490009 /* Web3+ERC1644.swift in Sources */, + 52920F9B47B44052ACA15A9ACD9B3FFE /* Web3+ERC165.swift in Sources */, + 3CE0032C005BB386FA1298F7DBE3B367 /* Web3+ERC20.swift in Sources */, + E13C4DBE0EB7FBE696A0E3ACDE40699E /* Web3+ERC721.swift in Sources */, + 62FC151E3A49F866DD74CBDE849D27F8 /* Web3+ERC721x.swift in Sources */, + EC13DCF1271C181C1E7B6E1FF203F587 /* Web3+ERC777.swift in Sources */, + BE3E77E8C72C1192A5B316858A54D179 /* Web3+ERC820.swift in Sources */, + B29AC5F4B9E29FE84776B139653182CA /* Web3+ERC888.swift in Sources */, + 8CC3ADAFC76BEC761852976026B52758 /* Web3+Eth.swift in Sources */, + 9FCF9B2D72AA2BCEB8DAB43D4B4C1A69 /* Web3+Eth+Websocket.swift in Sources */, + 0F673A9D29EC5B75BD8DC0B796040F2D /* Web3+Eventloop.swift in Sources */, + 1DF180C51265159F9619D1C5EF26316D /* Web3+EventParser.swift in Sources */, + 7C6E7A96CFFB53597A42061B79927BA0 /* Web3+HttpProvider.swift in Sources */, + 4D2EED25A8F8E2CAFF4EA51EAF389911 /* Web3+InfuraProviders.swift in Sources */, + 0F3F5EDC823447A95939F6C52D45E342 /* Web3+Instance.swift in Sources */, + BB1518E2CACEF26E121AAE6BE6DD8096 /* Web3+JSONRPC.swift in Sources */, + A4EBBD918D6392B45FF2E3D6ED17C7D1 /* Web3+Methods.swift in Sources */, + 654E6F39AD57C689A52E12BB51DDD88C /* Web3+MutatingTransaction.swift in Sources */, + 6D96B4C120F0167A273818693354AA17 /* Web3+Options.swift in Sources */, + 86AC32BC3900B807699D31D22C06A16C /* Web3+Personal.swift in Sources */, + D10D625D7F4AAA29A79D695BC3A94A00 /* Web3+Protocols.swift in Sources */, + 86954D3235BD19D7B94330AC9CA0D5AB /* Web3+ReadingTransaction.swift in Sources */, + 836A1A276D6FDED27563FD5AEE92CE74 /* Web3+SecurityToken.swift in Sources */, + 51331CE2712BD9887D38954D56431D43 /* Web3+ST20.swift in Sources */, + 53D3204D6826AF6FA93D8D2D6BF672E8 /* Web3+Structures.swift in Sources */, + F5088E4F43A46473DEAC73F7CC841395 /* Web3+TxPool.swift in Sources */, + D633C149E87E57031FD51E4D9FCE331D /* Web3+Utils.swift in Sources */, + D6BEA1C18AB70DC0B64169E0FA48F2D7 /* Web3+Wallet.swift in Sources */, + AE063EB21C8E759BC6A01A8736902A88 /* Web3+WebsocketProvider.swift in Sources */, + DE3C93B4089CA412BCEB4EF302BB4FD0 /* web3swift-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + D4E5535E2B0318F44A991BAAAA2DDF03 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 8AD89F5F4C9B4D6FA444D3D9805306E9 /* Pods-myWeb3Wallet-myWeb3WalletUITests-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + DFD2A1446AD3B5EBD8804208A1158398 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + DAF534C4544B6E5EAD5C4AD44709E385 /* Pods-myWeb3WalletTests-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F227B85FED12DE69DD97C29CE2DAC9C5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + C4BBCF72974CC3BD3B521B32EC37647B /* secp256k1.c in Sources */, + E5C5FBE36369E20E6913EA8FA5E4874D /* secp256k1.c-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 07213640700D764F2448129740400674 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = secp256k1.c; + target = 161C26511FC920CB146236AB7295D5E0 /* secp256k1.c */; + targetProxy = 6AEC58EE30DAC0EFC0DBDE54F71AFBF6 /* PBXContainerItemProxy */; + }; + 0A319787049075842C826957A1837D87 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = BigInt; + target = 09DD83B7D075842A3A5105AD410BD38A /* BigInt */; + targetProxy = D0937854CA7F3934D850A6B12504123F /* PBXContainerItemProxy */; + }; + 0CE786DB75401B50279902C8690DDC2D /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = secp256k1.c; + target = 161C26511FC920CB146236AB7295D5E0 /* secp256k1.c */; + targetProxy = 3CF61B40DA8701A404561C8BB3906C64 /* PBXContainerItemProxy */; + }; + 20C85CF454F1DDE661349F885F7FD2C7 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = CryptoSwift; + target = 99313990C1D76A6D1D017868B6975CC8 /* CryptoSwift */; + targetProxy = CE67F1BCE310A5D970E09D05453873C8 /* PBXContainerItemProxy */; + }; + 2425DF0705E44B7444CF653B14385A29 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Starscream; + target = 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */; + targetProxy = 50AD90732DFB53A74A40446FCAB7A28A /* PBXContainerItemProxy */; + }; + 2888DACD43CFAC618AF1676A71461439 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Starscream; + target = 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */; + targetProxy = 4E09EE4197617974D331E8FD4C46E31B /* PBXContainerItemProxy */; + }; + 3086A555869F80DA53A2BBB80DD88499 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "Pods-myWeb3Wallet"; + target = D89A752AFCCF1B411FDB91762F626B42 /* Pods-myWeb3Wallet */; + targetProxy = F6219F5A6A73436B4AC67ABFC9BCF49A /* PBXContainerItemProxy */; + }; + 433FDD8CBF083DB1BE68D05B5BF77265 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = secp256k1.c; + target = 161C26511FC920CB146236AB7295D5E0 /* secp256k1.c */; + targetProxy = C995D076E7B0E0958B346D5104531D7C /* PBXContainerItemProxy */; + }; + 5CCFA49E1B6DFBC27A8BDF86CBDE7265 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = CryptoSwift; + target = 99313990C1D76A6D1D017868B6975CC8 /* CryptoSwift */; + targetProxy = D5D3007741958562AC65E03C4C1896C0 /* PBXContainerItemProxy */; + }; + 63D170EE39D5092F7426150E640DD281 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = CryptoSwift; + target = 99313990C1D76A6D1D017868B6975CC8 /* CryptoSwift */; + targetProxy = 7DE5DE6920D96531E3702842566D4B18 /* PBXContainerItemProxy */; + }; + 74A25246C32631145B8838160ED36C92 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = BigInt; + target = 09DD83B7D075842A3A5105AD410BD38A /* BigInt */; + targetProxy = 1AA24238F1760F9C69F6C5F85EDB0E55 /* PBXContainerItemProxy */; + }; + 88A0B3215CDCA0FEF74CF84893F25E35 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = web3swift; + target = 99364D9FB07EF3FA5DFE1237001805EC /* web3swift */; + targetProxy = AAAB261AD53885F4EC04F8178139736C /* PBXContainerItemProxy */; + }; + 89BEF22CC5ACFF215A0FFC4DD05EE88D /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Starscream; + target = 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */; + targetProxy = 8130DEB78F04D6BB1AFDA6CD21C2566B /* PBXContainerItemProxy */; + }; + 9746A010E0BC1FD85524A71F8F8C1A7A /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = PromiseKit; + target = 7C579CE66A1E7A9AA33CA5F97F9C22C5 /* PromiseKit */; + targetProxy = F9F390AD37B4AFE468B203D739018ED0 /* PBXContainerItemProxy */; + }; + 9A43BD2A3C1F62F8E117C2734F6AC403 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = web3swift; + target = 99364D9FB07EF3FA5DFE1237001805EC /* web3swift */; + targetProxy = 0F1AB7F16B1489C0A9376FA250FA1E43 /* PBXContainerItemProxy */; + }; + 9ED29C136CB3A4EBB334873ED0F6C9B8 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "web3swift-Browser"; + target = 8CDD759A6130CA265C6D157F4407C39B /* web3swift-Browser */; + targetProxy = 213875A730C40CBF46083A20A1BE357B /* PBXContainerItemProxy */; + }; + D89ED8CB4BFE5C0381163C63C9B2800D /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = PromiseKit; + target = 7C579CE66A1E7A9AA33CA5F97F9C22C5 /* PromiseKit */; + targetProxy = 2718FE1B45CEBB0916BB88BA064F4933 /* PBXContainerItemProxy */; + }; + E0450CA8268C6456684BA11141374A51 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = BigInt; + target = 09DD83B7D075842A3A5105AD410BD38A /* BigInt */; + targetProxy = 5BA6C4D904CAA10678B6150A0C0226BE /* PBXContainerItemProxy */; + }; + E9775AFCC98177929A8AE3120B308389 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = PromiseKit; + target = 7C579CE66A1E7A9AA33CA5F97F9C22C5 /* PromiseKit */; + targetProxy = A84A86AF1C834FE3CCE7EF4A28AC8923 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 031169016BFDBA32C6D62E700DC77A13 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E7F85271DD855957A69EABBE94D318D3 /* Pods-myWeb3WalletTests.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 278F96E0D6F022FB40BD828F51E94D99 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 18DBFFB3E63974D7C0824367EFCAC013 /* BigInt.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/BigInt/BigInt-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/BigInt/BigInt-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/BigInt/BigInt.modulemap"; + PRODUCT_MODULE_NAME = BigInt; + PRODUCT_NAME = BigInt; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 38297573901D1CF02E874C8CAA42162F /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DFFFFE9315605246B13122B6E47B748B /* Pods-myWeb3Wallet.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 39A6AB7EB7469153EF167FF603BAA833 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 700FBEA2D7EAA32E60481668BFC38F17 /* CryptoSwift.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/CryptoSwift/CryptoSwift-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/CryptoSwift/CryptoSwift-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/CryptoSwift/CryptoSwift.modulemap"; + PRODUCT_MODULE_NAME = CryptoSwift; + PRODUCT_NAME = CryptoSwift; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.3; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 449A8F16B681E6B0D4B41DA23BE5C8AC /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = AE2FF8CBBE01A4A94FF02974852301FD /* secp256k1.c.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/secp256k1.c/secp256k1.c-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/secp256k1.c/secp256k1.c-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/secp256k1.c/secp256k1.c.modulemap"; + PRODUCT_MODULE_NAME = secp256k1; + PRODUCT_NAME = secp256k1; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 45265EC3592C9EF4A46D7BE6E0BAF092 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 93B89C94E972705C6809F63A2BE2EAAE /* web3swift.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/web3swift/web3swift-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/web3swift/web3swift-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/web3swift/web3swift.modulemap"; + PRODUCT_MODULE_NAME = web3swift; + PRODUCT_NAME = web3swift; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 4F51244FB0CE8BCA93C69B67284743F0 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 878D77F928A64BCC11C2A541B02CA9F2 /* Pods-myWeb3Wallet.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 54DC0CFD264D7DE1E167CC8559302582 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 274E8BA3AEB35AB17FA088333816830A /* web3swift.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/web3swift/web3swift-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/web3swift/web3swift-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/web3swift/web3swift.modulemap"; + PRODUCT_MODULE_NAME = web3swift; + PRODUCT_NAME = web3swift; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 68E10F3C83482CEF084AA764A400B9CA /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = FDDCBC928625AE704E65A6F7DED8B74B /* Pods-myWeb3Wallet-myWeb3WalletUITests.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 78D5511EA17419A5928B82B2542A80EF /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9217736E16B090E354FA8D7B1F16A693 /* BigInt.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/BigInt/BigInt-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/BigInt/BigInt-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/BigInt/BigInt.modulemap"; + PRODUCT_MODULE_NAME = BigInt; + PRODUCT_NAME = BigInt; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 7AA09C068EEE2BA7E9D7251B207CD265 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 274E8BA3AEB35AB17FA088333816830A /* web3swift.debug.xcconfig */; + buildSettings = { + CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/web3swift"; + IBSC_MODULE = web3swift; + INFOPLIST_FILE = "Target Support Files/web3swift/ResourceBundle-Browser-web3swift-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + PRODUCT_NAME = Browser; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + WRAPPER_EXTENSION = bundle; + }; + name = Debug; + }; + 7BF26030620FEA002CFDB3EC1196EA7C /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = F3FE70C0B549742469D7A9041DAC6F8B /* PromiseKit.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/PromiseKit/PromiseKit-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PromiseKit/PromiseKit-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/PromiseKit/PromiseKit.modulemap"; + PRODUCT_MODULE_NAME = PromiseKit; + PRODUCT_NAME = PromiseKit; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.4; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 86732952182378F58A3B10599CFBC71F /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 23C909CF58C1C172D843DF0B9927E7E1 /* PromiseKit.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/PromiseKit/PromiseKit-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/PromiseKit/PromiseKit-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/PromiseKit/PromiseKit.modulemap"; + PRODUCT_MODULE_NAME = PromiseKit; + PRODUCT_NAME = PromiseKit; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.4; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 89DDD25DB9130670FEDC5E0AD0F46AE7 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7BC2E55A1BE5983AEEDFFB5B980A621C /* Starscream.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/Starscream/Starscream-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Starscream/Starscream-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Starscream/Starscream.modulemap"; + PRODUCT_MODULE_NAME = Starscream; + PRODUCT_NAME = Starscream; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 90D4D09BCB6A4660E43ACBE9ECB6FE9A /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_DEBUG=1", + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + 9553C89E183877A5CB2F3C6801BEC129 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_RELEASE=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + SWIFT_VERSION = 5.0; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Release; + }; + AA9DDCDF2B3941BE5EC43210D31CAA8D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = FB92F1919C898290E81EC454E6484876 /* secp256k1.c.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/secp256k1.c/secp256k1.c-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/secp256k1.c/secp256k1.c-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/secp256k1.c/secp256k1.c.modulemap"; + PRODUCT_MODULE_NAME = secp256k1; + PRODUCT_NAME = secp256k1; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + ACD84B0422B67CD3596F56D78073CBD1 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 93B89C94E972705C6809F63A2BE2EAAE /* web3swift.release.xcconfig */; + buildSettings = { + CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/web3swift"; + IBSC_MODULE = web3swift; + INFOPLIST_FILE = "Target Support Files/web3swift/ResourceBundle-Browser-web3swift-Info.plist"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + PRODUCT_NAME = Browser; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + WRAPPER_EXTENSION = bundle; + }; + name = Release; + }; + CC66474D42F4DE32770AC3115C19B7CA /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 92BD1F11AAB93E6E693F70645ACCB9D3 /* Starscream.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/Starscream/Starscream-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Starscream/Starscream-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Starscream/Starscream.modulemap"; + PRODUCT_MODULE_NAME = Starscream; + PRODUCT_NAME = Starscream; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + DCA63F5913871BDB23F45D022C324AFF /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A524EF14F2890814986F7449EAA84F7F /* Pods-myWeb3WalletTests.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + EBC27D99A07710CB1BE42D216EB2D1A7 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = B7F3600020FB93358C3041F0C10FA382 /* Pods-myWeb3Wallet-myWeb3WalletUITests.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + F5B64C0EBAF5B347D605DBBA563B9409 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = C3D558C8C4FC4AADF09ED9EA94D9D6A9 /* CryptoSwift.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/CryptoSwift/CryptoSwift-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/CryptoSwift/CryptoSwift-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/CryptoSwift/CryptoSwift.modulemap"; + PRODUCT_MODULE_NAME = CryptoSwift; + PRODUCT_NAME = CryptoSwift; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.3; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 1D8A228996DBC2C7D966D9172843C34A /* Build configuration list for PBXNativeTarget "CryptoSwift" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 39A6AB7EB7469153EF167FF603BAA833 /* Debug */, + F5B64C0EBAF5B347D605DBBA563B9409 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2734E633ACE1F1D41E7843894EDCFD74 /* Build configuration list for PBXNativeTarget "web3swift-Browser" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 7AA09C068EEE2BA7E9D7251B207CD265 /* Debug */, + ACD84B0422B67CD3596F56D78073CBD1 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 90D4D09BCB6A4660E43ACBE9ECB6FE9A /* Debug */, + 9553C89E183877A5CB2F3C6801BEC129 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 5E342B11DDD91D2A8D5CEC382A58F29D /* Build configuration list for PBXNativeTarget "Starscream" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 89DDD25DB9130670FEDC5E0AD0F46AE7 /* Debug */, + CC66474D42F4DE32770AC3115C19B7CA /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 6B19066629BE27A8DFEB4831975D91D9 /* Build configuration list for PBXNativeTarget "PromiseKit" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 86732952182378F58A3B10599CFBC71F /* Debug */, + 7BF26030620FEA002CFDB3EC1196EA7C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 6C696C8CA41BB855C8D3F30C1B2DEF51 /* Build configuration list for PBXNativeTarget "BigInt" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 78D5511EA17419A5928B82B2542A80EF /* Debug */, + 278F96E0D6F022FB40BD828F51E94D99 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 735BBB520ABA2DF1E93DB75A450177A8 /* Build configuration list for PBXNativeTarget "web3swift" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 54DC0CFD264D7DE1E167CC8559302582 /* Debug */, + 45265EC3592C9EF4A46D7BE6E0BAF092 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 95EAF2FFD6A9EBA4F314D141A882DCAA /* Build configuration list for PBXNativeTarget "Pods-myWeb3Wallet" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 38297573901D1CF02E874C8CAA42162F /* Debug */, + 4F51244FB0CE8BCA93C69B67284743F0 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + D728746CE0580C7EEAFD661D5F19A9FA /* Build configuration list for PBXNativeTarget "Pods-myWeb3Wallet-myWeb3WalletUITests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + EBC27D99A07710CB1BE42D216EB2D1A7 /* Debug */, + 68E10F3C83482CEF084AA764A400B9CA /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + D756344E005625A3A276DA3970106F9A /* Build configuration list for PBXNativeTarget "secp256k1.c" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + AA9DDCDF2B3941BE5EC43210D31CAA8D /* Debug */, + 449A8F16B681E6B0D4B41DA23BE5C8AC /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + E6AF999F03FA681AA8CB1291CE5AED0F /* Build configuration list for PBXNativeTarget "Pods-myWeb3WalletTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + DCA63F5913871BDB23F45D022C324AFF /* Debug */, + 031169016BFDBA32C6D62E700DC77A13 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = BFDFE7DC352907FC980B868725387E98 /* Project object */; +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.h b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.h new file mode 100644 index 000000000..351a93b97 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.h @@ -0,0 +1,44 @@ +#import +#import + + +/** + To import the `NSNotificationCenter` category: + + use_frameworks! + pod "PromiseKit/Foundation" + + Or `NSNotificationCenter` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + #import +*/ +@interface NSNotificationCenter (PromiseKit) +/** + Observe the named notification once. + + [NSNotificationCenter once:UIKeyboardWillShowNotification].then(^(id note, id userInfo){ + UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue]; + CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue]; + + return [UIView promiseWithDuration:duration delay:0.0 options:(curve << 16) animations:^{ + + }]; + }); + + @warning *Important* Promises only resolve once. If you need your block to execute more than once then use `-addObserverForName:object:queue:usingBlock:`. + + @param notificationName The name of the notification for which to register the observer. + + @return A promise that fulfills with two parameters: + + 1. The NSNotification object. + 2. The NSNotification’s userInfo property. +*/ ++ (AnyPromise *)once:(NSString *)notificationName NS_REFINED_FOR_SWIFT; + +@end diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.m b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.m new file mode 100644 index 000000000..f8aee7109 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.m @@ -0,0 +1,18 @@ +#import +#import +#import "PMKFoundation.h" + +@implementation NSNotificationCenter (PromiseKit) + ++ (AnyPromise *)once:(NSString *)name { + return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { + __block id identifier; + identifier = [[NSNotificationCenter defaultCenter] addObserverForName:name object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) { + [[NSNotificationCenter defaultCenter] removeObserver:identifier name:name object:nil]; + identifier = nil; + resolve(PMKManifold(note, note.userInfo)); + }]; + }]; +} + +@end diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+Promise.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+Promise.swift new file mode 100644 index 000000000..3b7f84345 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+Promise.swift @@ -0,0 +1,33 @@ +import Foundation +#if !PMKCocoaPods +import PromiseKit +#endif + +/** + To import the `NSNotificationCenter` category: + + use_frameworks! + pod "PromiseKit/Foundation" + + Or `NSNotificationCenter` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + import PromiseKit +*/ +extension NotificationCenter { + /// Observe the named notification once + public func observe(once name: Notification.Name, object: Any? = nil) -> Guarantee { + let (promise, fulfill) = Guarantee.pending() + #if os(Linux) && ((swift(>=4.0) && !swift(>=4.0.1)) || (swift(>=3.0) && !swift(>=3.2.1))) + let id = addObserver(forName: name, object: object, queue: nil, usingBlock: fulfill) + #else + let id = addObserver(forName: name, object: object, queue: nil, using: fulfill) + #endif + promise.done { _ in self.removeObserver(id) } + return promise + } +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSObject+Promise.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSObject+Promise.swift new file mode 100644 index 000000000..135719bf6 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSObject+Promise.swift @@ -0,0 +1,57 @@ +import Foundation +#if !PMKCocoaPods +import PromiseKit +#endif + +/** + To import the `NSObject` category: + + use_frameworks! + pod "PromiseKit/Foundation" + + Or `NSObject` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + import PromiseKit +*/ +extension NSObject { + /** + - Returns: A promise that resolves when the provided keyPath changes. + - Warning: *Important* The promise must not outlive the object under observation. + - SeeAlso: Apple’s KVO documentation. + */ + public func observe(_: PMKNamespacer, keyPath: String) -> Guarantee { + return Guarantee { KVOProxy(observee: self, keyPath: keyPath, resolve: $0) } + } +} + +private class KVOProxy: NSObject { + var retainCycle: KVOProxy? + let fulfill: (Any?) -> Void + + @discardableResult + init(observee: NSObject, keyPath: String, resolve: @escaping (Any?) -> Void) { + fulfill = resolve + super.init() + observee.addObserver(self, forKeyPath: keyPath, options: NSKeyValueObservingOptions.new, context: pointer) + retainCycle = self + } + + fileprivate override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { + if let change = change, context == pointer { + defer { retainCycle = nil } + fulfill(change[NSKeyValueChangeKey.newKey]) + if let object = object as? NSObject, let keyPath = keyPath { + object.removeObserver(self, forKeyPath: keyPath) + } + } + } + + private lazy var pointer: UnsafeMutableRawPointer = { + return Unmanaged.passUnretained(self).toOpaque() + }() +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.h b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.h new file mode 100644 index 000000000..603689778 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.h @@ -0,0 +1,53 @@ +#if TARGET_OS_MAC && !TARGET_OS_EMBEDDED && !TARGET_OS_SIMULATOR && !TARGET_OS_UIKITFORMAC + +#import +#import + +#define PMKTaskErrorLaunchPathKey @"PMKTaskErrorLaunchPathKey" +#define PMKTaskErrorArgumentsKey @"PMKTaskErrorArgumentsKey" +#define PMKTaskErrorStandardOutputKey @"PMKTaskErrorStandardOutputKey" +#define PMKTaskErrorStandardErrorKey @"PMKTaskErrorStandardErrorKey" +#define PMKTaskErrorExitStatusKey @"PMKTaskErrorExitStatusKey" + +/** + To import the `NSTask` category: + + use_frameworks! + pod "PromiseKit/Foundation" + + Or `NSTask` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + #import +*/ +@interface NSTask (PromiseKit) + +/** + Launches the receiver and resolves when it exits. + + If the task fails the promise is rejected with code `PMKTaskError`, and + `userInfo` keys: `PMKTaskErrorStandardOutputKey`, + `PMKTaskErrorStandardErrorKey` and `PMKTaskErrorExitStatusKey`. + + NSTask *task = [NSTask new]; + task.launchPath = @"/usr/bin/basename"; + task.arguments = @[@"/usr/bin/sleep"]; + [task promise].then(^(NSString *stdout){ + //… + }); + + @return A promise that fulfills with three parameters: + + 1) The stdout interpreted as a UTF8 string. + 2) The stderr interpreted as a UTF8 string. + 3) The stdout as `NSData`. +*/ +- (AnyPromise *)promise NS_REFINED_FOR_SWIFT; + +@end + +#endif diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.m b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.m new file mode 100644 index 000000000..fa291d36c --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.m @@ -0,0 +1,59 @@ +#import +#import +#import +#import +#import + +#if TARGET_OS_MAC && !TARGET_OS_EMBEDDED && !TARGET_OS_SIMULATOR && !TARGET_OS_UIKITFORMAC + +#import "NSTask+AnyPromise.h" + +@implementation NSTask (PromiseKit) + +- (AnyPromise *)promise { + return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { + self.standardOutput = [NSPipe pipe]; + self.standardError = [NSPipe pipe]; + self.terminationHandler = ^(NSTask *task){ + id stdoutData = [[task.standardOutput fileHandleForReading] readDataToEndOfFile]; + id stdoutString = [[NSString alloc] initWithData:stdoutData encoding:NSUTF8StringEncoding]; + id stderrData = [[task.standardError fileHandleForReading] readDataToEndOfFile]; + id stderrString = [[NSString alloc] initWithData:stderrData encoding:NSUTF8StringEncoding]; + + if (task.terminationReason == NSTaskTerminationReasonExit && self.terminationStatus == 0) { + resolve(PMKManifold(stdoutString, stderrString, stdoutData)); + } else { + id cmd = [NSMutableArray arrayWithObject:task.launchPath]; + [cmd addObjectsFromArray:task.arguments]; + cmd = [cmd componentsJoinedByString:@" "]; + + id info = @{ + NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Failed executing: %@.", cmd], + PMKTaskErrorStandardOutputKey: stdoutString, + PMKTaskErrorStandardErrorKey: stderrString, + PMKTaskErrorExitStatusKey: @(task.terminationStatus), + }; + + resolve([NSError errorWithDomain:PMKErrorDomain code:PMKTaskError userInfo:info]); + } + }; + + #if __clang_major__ >= 9 + if (@available(macOS 10.13, *)) { + NSError *error = nil; + + if (![self launchAndReturnError:&error]) { + resolve(error); + } + } else { + [self launch]; + } + #else + [self launch]; // might @throw + #endif + }]; +} + +@end + +#endif diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.h b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.h new file mode 100644 index 000000000..71952d48c --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.h @@ -0,0 +1,79 @@ +#import +#import +#import +#import + +#define PMKURLErrorFailingURLResponseKey @"PMKURLErrorFailingURLResponseKey" +#define PMKURLErrorFailingDataKey @"PMKURLErrorFailingDataKey" +#define PMKURLErrorFailingStringKey @"PMKURLErrorFailingStringKey" +#define PMKJSONErrorJSONObjectKey @"PMKJSONErrorJSONObjectKey" + +/** + Really we shouldn’t assume JSON for (application|text)/(x-)javascript, + really we should return a String of Javascript. However in practice + for the apps we write it *will be* JSON. Thus if you actually want + a Javascript String, use the promise variant of our category functions. + */ +#define PMKHTTPURLResponseIsJSON(rsp) [@[@"application/json", @"text/json", @"text/javascript", @"application/x-javascript", @"application/javascript"] containsObject:[rsp MIMEType]] +#define PMKHTTPURLResponseIsImage(rsp) [@[@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap"] containsObject:[rsp MIMEType]] +#define PMKHTTPURLResponseIsText(rsp) [[rsp MIMEType] hasPrefix:@"text/"] + +#define PMKJSONDeserializationOptions ((NSJSONReadingOptions)(NSJSONReadingAllowFragments | NSJSONReadingMutableContainers)) + + +/** + To import the `NSURLSession` category: + + use_frameworks! + pod "PromiseKit/Foundation" + + Or `NSURLConnection` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + #import +*/ +@interface NSURLSession (PromiseKit) + +/** + Creates a task that retrieves the contents of a URL based on the + specified URL request object. + + PromiseKit automatically deserializes the raw HTTP data response into the + appropriate rich data type based on the mime type the server provides. + Thus if the response is JSON you will get the deserialized JSON response. + PromiseKit supports decoding into strings, JSON and UIImages. + + However if your server does not provide a rich content-type, you will + just get `NSData`. This is rare, but a good example we came across was + downloading files from Dropbox. + + PromiseKit goes to quite some lengths to provide good `NSError` objects + for error conditions at all stages of the HTTP to rich-data type + pipeline. We provide the following additional `userInfo` keys as + appropriate: + + - `PMKURLErrorFailingDataKey` + - `PMKURLErrorFailingStringKey` + - `PMKURLErrorFailingURLResponseKey` + + [[NSURLConnection sharedSession] promiseDataTaskWithRequest:rq].then(^(id response){ + // response is probably an NSDictionary deserialized from JSON + }); + + @param request The URL request. + + @return A promise that fulfills with three parameters: + + 1) The deserialized data response. + 2) The `NSHTTPURLResponse`. + 3) The raw `NSData` response. + + @see https://github.com/mxcl/OMGHTTPURLRQ +*/ +- (AnyPromise *)promiseDataTaskWithRequest:(NSURLRequest *)request NS_REFINED_FOR_SWIFT; + +@end diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.m b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.m new file mode 100644 index 000000000..901eb2813 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.m @@ -0,0 +1,113 @@ +#import +#import +#import +#import "NSURLSession+AnyPromise.h" +#import +#import +#import +#import +#import +#import +#import +#import + +@implementation NSURLSession (PromiseKit) + +- (AnyPromise *)promiseDataTaskWithRequest:(NSURLRequest *)rq { + return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { + [[self dataTaskWithRequest:rq completionHandler:^(NSData *data, id rsp, NSError *urlError){ + assert(![NSThread isMainThread]); + + PMKResolver fulfiller = ^(id responseObject){ + resolve(PMKManifold(responseObject, rsp, data)); + }; + PMKResolver rejecter = ^(NSError *error){ + id userInfo = error.userInfo.mutableCopy ?: [NSMutableDictionary new]; + if (data) userInfo[PMKURLErrorFailingDataKey] = data; + if (rsp) userInfo[PMKURLErrorFailingURLResponseKey] = rsp; + error = [NSError errorWithDomain:error.domain code:error.code userInfo:userInfo]; + resolve(error); + }; + + NSStringEncoding (^stringEncoding)(void) = ^NSStringEncoding{ + id encodingName = [rsp textEncodingName]; + if (encodingName) { + CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)encodingName); + if (encoding != kCFStringEncodingInvalidId) + return CFStringConvertEncodingToNSStringEncoding(encoding); + } + return NSUTF8StringEncoding; + }; + + if (urlError) { + rejecter(urlError); + } else if (![rsp isKindOfClass:[NSHTTPURLResponse class]]) { + fulfiller(data); + } else if ([rsp statusCode] < 200 || [rsp statusCode] >= 300) { + id info = @{ + NSLocalizedDescriptionKey: @"The server returned a bad HTTP response code", + NSURLErrorFailingURLStringErrorKey: rq.URL.absoluteString, + NSURLErrorFailingURLErrorKey: rq.URL + }; + id err = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadServerResponse userInfo:info]; + rejecter(err); + } else if (PMKHTTPURLResponseIsJSON(rsp)) { + // work around ever-so-common Rails workaround: https://github.com/rails/rails/issues/1742 + if ([rsp expectedContentLength] == 1 && [data isEqualToData:[NSData dataWithBytes:" " length:1]]) + return fulfiller(nil); + + NSError *err = nil; + id json = [NSJSONSerialization JSONObjectWithData:data options:PMKJSONDeserializationOptions error:&err]; + if (!err) { + fulfiller(json); + } else { + id userInfo = err.userInfo.mutableCopy; + if (data) { + NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding()]; + if (string) + userInfo[PMKURLErrorFailingStringKey] = string; + } + long long length = [rsp expectedContentLength]; + id bytes = length <= 0 ? @"" : [NSString stringWithFormat:@"%lld bytes", length]; + id fmt = @"The server claimed a %@ JSON response, but decoding failed with: %@"; + userInfo[NSLocalizedDescriptionKey] = [NSString stringWithFormat:fmt, bytes, userInfo[NSLocalizedDescriptionKey]]; + err = [NSError errorWithDomain:err.domain code:err.code userInfo:userInfo]; + rejecter(err); + } + #ifdef UIKIT_EXTERN + } else if (PMKHTTPURLResponseIsImage(rsp)) { + UIImage *image = [[UIImage alloc] initWithData:data]; + image = [[UIImage alloc] initWithCGImage:[image CGImage] scale:image.scale orientation:image.imageOrientation]; + if (image) + fulfiller(image); + else { + id info = @{ + NSLocalizedDescriptionKey: @"The server returned invalid image data", + NSURLErrorFailingURLStringErrorKey: rq.URL.absoluteString, + NSURLErrorFailingURLErrorKey: rq.URL + }; + id err = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:info]; + rejecter(err); + } + #endif + } else if (PMKHTTPURLResponseIsText(rsp)) { + id str = [[NSString alloc] initWithData:data encoding:stringEncoding()]; + if (str) + fulfiller(str); + else { + id info = @{ + NSLocalizedDescriptionKey: @"The server returned invalid string data", + NSURLErrorFailingURLStringErrorKey: rq.URL.absoluteString, + NSURLErrorFailingURLErrorKey: rq.URL + }; + id err = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:info]; + rejecter(err); + } + } else { + fulfiller(data); + } + }] resume]; + }]; +} + +@end diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+Promise.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+Promise.swift new file mode 100644 index 000000000..150654fb0 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+Promise.swift @@ -0,0 +1,246 @@ +import Foundation +#if !PMKCocoaPods +import PromiseKit +#endif +#if swift(>=4.1) +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif +#endif + +/** + To import the `NSURLSession` category: + + use_frameworks! + pod "PromiseKit/Foundation" + + Or `NSURLSession` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + import PromiseKit +*/ +extension URLSession { + /** + Example usage: + + firstly { + URLSession.shared.dataTask(.promise, with: rq) + }.compactMap { data, _ in + try JSONSerialization.jsonObject(with: data) as? [String: Any] + }.then { json in + //… + } + + We recommend the use of [OMGHTTPURLRQ] which allows you to construct correct REST requests: + + firstly { + let rq = OMGHTTPURLRQ.POST(url, json: parameters) + URLSession.shared.dataTask(.promise, with: rq) + }.then { data, urlResponse in + //… + } + + We provide a convenience initializer for `String` specifically for this promise: + + firstly { + URLSession.shared.dataTask(.promise, with: rq) + }.compactMap(String.init).then { string in + // decoded per the string encoding specified by the server + }.then { string in + print("response: string") + } + + Other common types can be easily decoded using compactMap also: + + firstly { + URLSession.shared.dataTask(.promise, with: rq) + }.compactMap { + UIImage(data: $0) + }.then { + self.imageView.image = $0 + } + + Though if you do decode the image this way, we recommend inflating it on a background thread + first as this will improve main thread performance when rendering the image: + + firstly { + URLSession.shared.dataTask(.promise, with: rq) + }.compactMap(on: QoS.userInitiated) { data, _ in + guard let img = UIImage(data: data) else { return nil } + _ = cgImage?.dataProvider?.data + return img + }.then { + self.imageView.image = $0 + } + + - Parameter convertible: A URL or URLRequest. + - Returns: A promise that represents the URL request. + - SeeAlso: [OMGHTTPURLRQ] + - Remark: We deliberately don’t provide a `URLRequestConvertible` for `String` because in our experience, you should be explicit with this error path to make good apps. + + [OMGHTTPURLRQ]: https://github.com/mxcl/OMGHTTPURLRQ + */ + public func dataTask(_: PMKNamespacer, with convertible: URLRequestConvertible) -> Promise<(data: Data, response: URLResponse)> { + return Promise { dataTask(with: convertible.pmkRequest, completionHandler: adapter($0)).resume() } + } + + public func uploadTask(_: PMKNamespacer, with convertible: URLRequestConvertible, from data: Data) -> Promise<(data: Data, response: URLResponse)> { + return Promise { uploadTask(with: convertible.pmkRequest, from: data, completionHandler: adapter($0)).resume() } + } + + public func uploadTask(_: PMKNamespacer, with convertible: URLRequestConvertible, fromFile file: URL) -> Promise<(data: Data, response: URLResponse)> { + return Promise { uploadTask(with: convertible.pmkRequest, fromFile: file, completionHandler: adapter($0)).resume() } + } + + /// - Remark: we force a `to` parameter because Apple deletes the downloaded file immediately after the underyling completion handler returns. + /// - Note: we do not create the destination directory for you, because we move the file with FileManager.moveItem which changes it behavior depending on the directory status of the URL you provide. So create your own directory first! + public func downloadTask(_: PMKNamespacer, with convertible: URLRequestConvertible, to saveLocation: URL) -> Promise<(saveLocation: URL, response: URLResponse)> { + return Promise { seal in + downloadTask(with: convertible.pmkRequest, completionHandler: { tmp, rsp, err in + if let error = err { + seal.reject(error) + } else if let rsp = rsp, let tmp = tmp { + do { + try FileManager.default.moveItem(at: tmp, to: saveLocation) + seal.fulfill((saveLocation, rsp)) + } catch { + seal.reject(error) + } + } else { + seal.reject(PMKError.invalidCallingConvention) + } + }).resume() + } + } +} + + +public protocol URLRequestConvertible { + var pmkRequest: URLRequest { get } +} +extension URLRequest: URLRequestConvertible { + public var pmkRequest: URLRequest { return self } +} +extension URL: URLRequestConvertible { + public var pmkRequest: URLRequest { return URLRequest(url: self) } +} + + +#if !os(Linux) +public extension String { + /** + - Remark: useful when converting a `URLSession` response into a `String` + + firstly { + URLSession.shared.dataTask(.promise, with: rq) + }.map(String.init).done { + print($0) + } + */ + init?(data: Data, urlResponse: URLResponse) { + guard let str = String(bytes: data, encoding: urlResponse.stringEncoding ?? .utf8) else { + return nil + } + self.init(str) + } +} + +private extension URLResponse { + var stringEncoding: String.Encoding? { + guard let encodingName = textEncodingName else { return nil } + let encoding = CFStringConvertIANACharSetNameToEncoding(encodingName as CFString) + guard encoding != kCFStringEncodingInvalidId else { return nil } + return String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(encoding)) + } +} +#endif + +private func adapter(_ seal: Resolver<(data: T, response: U)>) -> (T?, U?, Error?) -> Void { + return { t, u, e in + if let t = t, let u = u { + seal.fulfill((t, u)) + } else if let e = e { + seal.reject(e) + } else { + seal.reject(PMKError.invalidCallingConvention) + } + } +} + + +#if swift(>=3.1) +public enum PMKHTTPError: Error, LocalizedError, CustomStringConvertible { + case badStatusCode(Int, Data, HTTPURLResponse) + + public var errorDescription: String? { + func url(_ rsp: URLResponse) -> String { + return rsp.url?.absoluteString ?? "nil" + } + switch self { + case .badStatusCode(401, _, let response): + return "Unauthorized (\(url(response))" + case .badStatusCode(let code, _, let response): + return "Invalid HTTP response (\(code)) for \(url(response))." + } + } + +#if swift(>=4.0) + public func decodeResponse(_ t: T.Type, decoder: JSONDecoder = JSONDecoder()) -> T? { + switch self { + case .badStatusCode(_, let data, _): + return try? decoder.decode(t, from: data) + } + } +#endif + + //TODO rename responseJSON + public var jsonDictionary: Any? { + switch self { + case .badStatusCode(_, let data, _): + return try? JSONSerialization.jsonObject(with: data) + } + } + + var responseBodyString: String? { + switch self { + case .badStatusCode(_, let data, _): + return String(data: data, encoding: .utf8) + } + } + + public var failureReason: String? { + return responseBodyString + } + + public var description: String { + switch self { + case .badStatusCode(let code, let data, let response): + var dict: [String: Any] = [ + "Status Code": code, + "Body": String(data: data, encoding: .utf8) ?? "\(data.count) bytes" + ] + dict["URL"] = response.url + dict["Headers"] = response.allHeaderFields + return " \(NSDictionary(dictionary: dict))" // as NSDictionary makes the output look like NSHTTPURLResponse looks + } + } +} + +public extension Promise where T == (data: Data, response: URLResponse) { + func validate() -> Promise { + return map { + guard let response = $0.response as? HTTPURLResponse else { return $0 } + switch response.statusCode { + case 200..<300: + return $0 + case let code: + throw PMKHTTPError.badStatusCode(code, $0.data, response) + } + } + } +} +#endif diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/PMKFoundation.h b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/PMKFoundation.h new file mode 100644 index 000000000..8796c0d11 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/PMKFoundation.h @@ -0,0 +1,3 @@ +#import "NSNotificationCenter+AnyPromise.h" +#import "NSURLSession+AnyPromise.h" +#import "NSTask+AnyPromise.h" diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/Process+Promise.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/Process+Promise.swift new file mode 100644 index 000000000..03cab3cfe --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/Process+Promise.swift @@ -0,0 +1,190 @@ +import Foundation +#if !PMKCocoaPods +import PromiseKit +#endif + +#if os(macOS) + +/** + To import the `Process` category: + + use_frameworks! + pod "PromiseKit/Foundation" + + Or `Process` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + import PromiseKit + */ +extension Process { + /** + Launches the receiver and resolves when it exits. + + let proc = Process() + proc.launchPath = "/bin/ls" + proc.arguments = ["/bin"] + proc.launch(.promise).compactMap { std in + String(data: std.out.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) + }.then { stdout in + print(str) + } + */ + public func launch(_: PMKNamespacer) -> Promise<(out: Pipe, err: Pipe)> { + let (stdout, stderr) = (Pipe(), Pipe()) + + do { + standardOutput = stdout + standardError = stderr + + #if swift(>=4.0) + if #available(OSX 10.13, *) { + try run() + } else if let path = launchPath, FileManager.default.isExecutableFile(atPath: path) { + launch() + } else { + throw PMKError.notExecutable(launchPath) + } + #else + guard let path = launchPath, FileManager.default.isExecutableFile(atPath: path) else { + throw PMKError.notExecutable(launchPath) + } + launch() + #endif + } catch { + return Promise(error: error) + } + + + var q: DispatchQueue { + if #available(macOS 10.10, iOS 8.0, tvOS 9.0, watchOS 2.0, *) { + return DispatchQueue.global(qos: .default) + } else { + return DispatchQueue.global(priority: .default) + } + } + + return Promise { seal in + q.async { + self.waitUntilExit() + + guard self.terminationReason == .exit, self.terminationStatus == 0 else { + let stdoutData = try? self.readDataFromPipe(stdout) + let stderrData = try? self.readDataFromPipe(stderr) + + let stdoutString = stdoutData.flatMap { (data: Data) -> String? in String(data: data, encoding: .utf8) } + let stderrString = stderrData.flatMap { (data: Data) -> String? in String(data: data, encoding: .utf8) } + + return seal.reject(PMKError.execution(process: self, standardOutput: stdoutString, standardError: stderrString)) + } + seal.fulfill((stdout, stderr)) + } + } + } + + private func readDataFromPipe(_ pipe: Pipe) throws -> Data { + let handle = pipe.fileHandleForReading + defer { handle.closeFile() } + + // Someday, NSFileHandle will probably be updated with throwing equivalents to its read and write methods, + // as NSTask has, to avoid raising exceptions and crashing the app. + // Unfortunately that day has not yet come, so use the underlying BSD calls for now. + + let fd = handle.fileDescriptor + + let bufsize = 1024 * 8 + let buf = UnsafeMutablePointer.allocate(capacity: bufsize) + + #if swift(>=4.1) + defer { buf.deallocate() } + #else + defer { buf.deallocate(capacity: bufsize) } + #endif + + var data = Data() + + while true { + let bytesRead = read(fd, buf, bufsize) + + if bytesRead == 0 { + break + } + + if bytesRead < 0 { + throw POSIXError.Code(rawValue: errno).map { POSIXError($0) } ?? CocoaError(.fileReadUnknown) + } + + data.append(buf, count: bytesRead) + } + + return data + } + + /** + The error generated by PromiseKit’s `Process` extension + */ + public enum PMKError { + /// NOT AVAILABLE ON 10.13 and above because Apple provide this error handling themselves + case notExecutable(String?) + case execution(process: Process, standardOutput: String?, standardError: String?) + } +} + + +extension Process.PMKError: LocalizedError { + public var errorDescription: String? { + switch self { + case .notExecutable(let path?): + return "File not executable: \(path)" + case .notExecutable(nil): + return "No launch path specified" + case .execution(process: let task, standardOutput: _, standardError: _): + return "Failed executing: `\(task)` (\(task.terminationStatus))." + } + } +} + +public extension Promise where T == (out: Pipe, err: Pipe) { + func print() -> Promise { + return tap { result in + switch result { + case .fulfilled(let raw): + let stdout = String(data: raw.out.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) + let stderr = String(data: raw.err.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) + Swift.print("stdout: `\(stdout ?? "")`") + Swift.print("stderr: `\(stderr ?? "")`") + case .rejected(let err): + Swift.print(err) + } + } + } +} + +extension Process { + /// Provided because Foundation’s is USELESS + open override var description: String { + let launchPath = self.launchPath ?? "$0" + var args = [launchPath] + arguments.flatMap{ args += $0 } + return args.map { arg in + let contains: Bool + #if swift(>=3.2) + contains = arg.contains(" ") + #else + contains = arg.characters.contains(" ") + #endif + if contains { + return "\"\(arg)\"" + } else if arg == "" { + return "\"\"" + } else { + return arg + } + }.joined(separator: " ") + } +} + +#endif diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/afterlife.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/afterlife.swift new file mode 100644 index 000000000..232c8da90 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/Foundation/Sources/afterlife.swift @@ -0,0 +1,26 @@ +import Foundation +#if !PMKCocoaPods +import PromiseKit +#endif + +/** + - Returns: A promise that resolves when the provided object deallocates + - Important: The promise is not guarenteed to resolve immediately when the provided object is deallocated. So you cannot write code that depends on exact timing. + */ +public func after(life object: NSObject) -> Guarantee { + var reaper = objc_getAssociatedObject(object, &handle) as? GrimReaper + if reaper == nil { + reaper = GrimReaper() + objc_setAssociatedObject(object, &handle, reaper, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + return reaper!.promise +} + +private var handle: UInt8 = 0 + +private class GrimReaper: NSObject { + deinit { + fulfill(()) + } + let (promise, fulfill) = Guarantee.pending() +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/PMKUIKit.h b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/PMKUIKit.h new file mode 100644 index 000000000..75cbf90f0 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/PMKUIKit.h @@ -0,0 +1,8 @@ +#import "UIView+AnyPromise.h" +#import "UIViewController+AnyPromise.h" + +typedef NS_OPTIONS(NSInteger, PMKAnimationOptions) { + PMKAnimationOptionsNone = 1 << 0, + PMKAnimationOptionsAppear = 1 << 1, + PMKAnimationOptionsDisappear = 1 << 2, +}; diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.h b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.h new file mode 100644 index 000000000..0a19cd6fe --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.h @@ -0,0 +1,80 @@ +#import +#import + +// Created by Masafumi Yoshida on 2014/07/11. +// Copyright (c) 2014年 DeNA. All rights reserved. + +/** + To import the `UIView` category: + + use_frameworks! + pod "PromiseKit/UIKit" + + Or `UIKit` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + @import PromiseKit; +*/ +@interface UIView (PromiseKit) + +/** + Animate changes to one or more views using the specified duration. + + @param duration The total duration of the animations, measured in + seconds. If you specify a negative value or 0, the changes are made + without animating them. + + @param animations A block object containing the changes to commit to the + views. + + @return A promise that fulfills with a boolean NSNumber indicating + whether or not the animations actually finished. +*/ ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations NS_REFINED_FOR_SWIFT; + +/** + Animate changes to one or more views using the specified duration, delay, + options, and completion handler. + + @param duration The total duration of the animations, measured in + seconds. If you specify a negative value or 0, the changes are made + without animating them. + + @param delay The amount of time (measured in seconds) to wait before + beginning the animations. Specify a value of 0 to begin the animations + immediately. + + @param options A mask of options indicating how you want to perform the + animations. For a list of valid constants, see UIViewAnimationOptions. + + @param animations A block object containing the changes to commit to the + views. + + @return A promise that fulfills with a boolean NSNumber indicating + whether or not the animations actually finished. +*/ ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void (^)(void))animations NS_REFINED_FOR_SWIFT; + +/** + Performs a view animation using a timing curve corresponding to the + motion of a physical spring. + + @return A promise that fulfills with a boolean NSNumber indicating + whether or not the animations actually finished. +*/ ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay usingSpringWithDamping:(CGFloat)dampingRatio initialSpringVelocity:(CGFloat)velocity options:(UIViewAnimationOptions)options animations:(void (^)(void))animations NS_REFINED_FOR_SWIFT; + +/** + Creates an animation block object that can be used to set up + keyframe-based animations for the current view. + + @return A promise that fulfills with a boolean NSNumber indicating + whether or not the animations actually finished. +*/ ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewKeyframeAnimationOptions)options keyframeAnimations:(void (^)(void))animations NS_REFINED_FOR_SWIFT; + +@end diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.m b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.m new file mode 100644 index 000000000..04ee94035 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.m @@ -0,0 +1,64 @@ +// +// UIView+PromiseKit_UIAnimation.m +// YahooDenaStudy +// +// Created by Masafumi Yoshida on 2014/07/11. +// Copyright (c) 2014年 DeNA. All rights reserved. +// + +#import +#import "UIView+AnyPromise.h" + + +#define CopyPasta \ + NSAssert([NSThread isMainThread], @"UIKit animation must be performed on the main thread"); \ + \ + if (![NSThread isMainThread]) { \ + id error = [NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:@{NSLocalizedDescriptionKey: @"Animation was attempted on a background thread"}]; \ + return [AnyPromise promiseWithValue:error]; \ + } \ + \ + PMKResolver resolve = nil; \ + AnyPromise *promise = [[AnyPromise alloc] initWithResolver:&resolve]; + + +@implementation UIView (PromiseKit) + ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations { + return [self promiseWithDuration:duration delay:0 options:0 animations:animations]; +} + ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void(^)(void))animations +{ + CopyPasta; + + [UIView animateWithDuration:duration delay:delay options:options animations:animations completion:^(BOOL finished) { + resolve(@(finished)); + }]; + + return promise; +} + ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay usingSpringWithDamping:(CGFloat)dampingRatio initialSpringVelocity:(CGFloat)velocity options:(UIViewAnimationOptions)options animations:(void(^)(void))animations +{ + CopyPasta; + + [UIView animateWithDuration:duration delay:delay usingSpringWithDamping:dampingRatio initialSpringVelocity:velocity options:options animations:animations completion:^(BOOL finished) { + resolve(@(finished)); + }]; + + return promise; +} + ++ (AnyPromise *)promiseWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewKeyframeAnimationOptions)options keyframeAnimations:(void(^)(void))animations +{ + CopyPasta; + + [UIView animateKeyframesWithDuration:duration delay:delay options:options animations:animations completion:^(BOOL finished) { + resolve(@(finished)); + }]; + + return promise; +} + +@end diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+Promise.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+Promise.swift new file mode 100644 index 000000000..1bbb8c649 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+Promise.swift @@ -0,0 +1,115 @@ +import UIKit.UIView +#if !PMKCocoaPods +import PromiseKit +#endif + +/** + To import the `UIView` category: + + use_frameworks! + pod "PromiseKit/UIKit" + + Or `UIKit` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + import PromiseKit +*/ +public extension UIView { +#if swift(>=4.2) +/** + Animate changes to one or more views using the specified duration, delay, + options, and completion handler. + + - Parameter duration: The total duration of the animations, measured in + seconds. If you specify a negative value or 0, the changes are made + without animating them. + + - Parameter delay: The amount of time (measured in seconds) to wait before + beginning the animations. Specify a value of 0 to begin the animations + immediately. + + - Parameter options: A mask of options indicating how you want to perform the + animations. For a list of valid constants, see UIViewAnimationOptions. + + - Parameter animations: A block object containing the changes to commit to the + views. + + - Returns: A promise that fulfills with a boolean NSNumber indicating + whether or not the animations actually finished. + */ + @discardableResult + static func animate(_: PMKNamespacer, duration: TimeInterval, delay: TimeInterval = 0, options: UIView.AnimationOptions = [], animations: @escaping () -> Void) -> Guarantee { + return Guarantee { animate(withDuration: duration, delay: delay, options: options, animations: animations, completion: $0) } + } + + @discardableResult + static func animate(_: PMKNamespacer, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping damping: CGFloat, initialSpringVelocity: CGFloat, options: UIView.AnimationOptions = [], animations: @escaping () -> Void) -> Guarantee { + return Guarantee { animate(withDuration: duration, delay: delay, usingSpringWithDamping: damping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: $0) } + } + + @discardableResult + static func transition(_: PMKNamespacer, with view: UIView, duration: TimeInterval, options: UIView.AnimationOptions = [], animations: (() -> Void)?) -> Guarantee { + return Guarantee { transition(with: view, duration: duration, options: options, animations: animations, completion: $0) } + } + + @discardableResult + static func transition(_: PMKNamespacer, from: UIView, to: UIView, duration: TimeInterval, options: UIView.AnimationOptions = []) -> Guarantee { + return Guarantee { transition(from: from, to: to, duration: duration, options: options, completion: $0) } + } + + @discardableResult + static func perform(_: PMKNamespacer, animation: UIView.SystemAnimation, on views: [UIView], options: UIView.AnimationOptions = [], animations: (() -> Void)?) -> Guarantee { + return Guarantee { perform(animation, on: views, options: options, animations: animations, completion: $0) } + } +#else + /** + Animate changes to one or more views using the specified duration, delay, + options, and completion handler. + + - Parameter duration: The total duration of the animations, measured in + seconds. If you specify a negative value or 0, the changes are made + without animating them. + + - Parameter delay: The amount of time (measured in seconds) to wait before + beginning the animations. Specify a value of 0 to begin the animations + immediately. + + - Parameter options: A mask of options indicating how you want to perform the + animations. For a list of valid constants, see UIViewAnimationOptions. + + - Parameter animations: A block object containing the changes to commit to the + views. + + - Returns: A promise that fulfills with a boolean NSNumber indicating + whether or not the animations actually finished. + */ + @discardableResult + static func animate(_: PMKNamespacer, duration: TimeInterval, delay: TimeInterval = 0, options: UIViewAnimationOptions = [], animations: @escaping () -> Void) -> Guarantee { + return Guarantee { animate(withDuration: duration, delay: delay, options: options, animations: animations, completion: $0) } + } + + @discardableResult + static func animate(_: PMKNamespacer, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping damping: CGFloat, initialSpringVelocity: CGFloat, options: UIViewAnimationOptions = [], animations: @escaping () -> Void) -> Guarantee { + return Guarantee { animate(withDuration: duration, delay: delay, usingSpringWithDamping: damping, initialSpringVelocity: initialSpringVelocity, options: options, animations: animations, completion: $0) } + } + + @discardableResult + static func transition(_: PMKNamespacer, with view: UIView, duration: TimeInterval, options: UIViewAnimationOptions = [], animations: (() -> Void)?) -> Guarantee { + return Guarantee { transition(with: view, duration: duration, options: options, animations: animations, completion: $0) } + } + + @discardableResult + static func transition(_: PMKNamespacer, from: UIView, to: UIView, duration: TimeInterval, options: UIViewAnimationOptions = []) -> Guarantee { + return Guarantee { transition(from: from, to: to, duration: duration, options: options, completion: $0) } + } + + @discardableResult + static func perform(_: PMKNamespacer, animation: UISystemAnimation, on views: [UIView], options: UIViewAnimationOptions = [], animations: (() -> Void)?) -> Guarantee { + return Guarantee { perform(animation, on: views, options: options, animations: animations, completion: $0) } + } +#endif +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.h b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.h new file mode 100644 index 000000000..0e60ca9e7 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.h @@ -0,0 +1,71 @@ +#import +#import + +/** + To import the `UIViewController` category: + + use_frameworks! + pod "PromiseKit/UIKit" + + Or `UIKit` is one of the categories imported by the umbrella pod: + + use_frameworks! + pod "PromiseKit" + + And then in your sources: + + @import PromiseKit; +*/ +@interface UIViewController (PromiseKit) + +/** + Presents a view controller modally. + + If the view controller is one of the following: + + - MFMailComposeViewController + - MFMessageComposeViewController + - UIImagePickerController + - SLComposeViewController + + Then PromiseKit presents the view controller returning a promise that is + resolved as per the documentation for those classes. Eg. if you present a + `UIImagePickerController` the view controller will be presented for you + and the returned promise will resolve with the media the user selected. + + [self promiseViewController:[MFMailComposeViewController new] animated:YES completion:nil].then(^{ + //… + }); + + Otherwise PromiseKit expects your view controller to implement a + `promise` property. This promise will be returned from this method and + presentation and dismissal of the presented view controller will be + managed for you. + + \@interface MyViewController: UIViewController + @property (readonly) AnyPromise *promise; + @end + + @implementation MyViewController { + PMKResolver resolve; + } + + - (void)viewDidLoad { + _promise = [[AnyPromise alloc] initWithResolver:&resolve]; + } + + - (void)later { + resolve(@"some fulfilled value"); + } + + @end + + [self promiseViewController:[MyViewController new] aniamted:YES completion:nil].then(^(id value){ + // value == @"some fulfilled value" + }); + + @return A promise that can be resolved by the presented view controller. +*/ +- (AnyPromise *)promiseViewController:(UIViewController *)vc animated:(BOOL)animated completion:(void (^)(void))block NS_REFINED_FOR_SWIFT; + +@end diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.m b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.m new file mode 100644 index 000000000..5231e55bf --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.m @@ -0,0 +1,140 @@ +#import +#import "UIViewController+AnyPromise.h" +#import + +#if PMKImagePickerController +#import +#endif + +@interface PMKGenericDelegate : NSObject { +@public + PMKResolver resolve; +} ++ (instancetype)delegateWithPromise:(AnyPromise **)promise; +@end + +@interface UIViewController () +- (AnyPromise*) promise; +@end + +@implementation UIViewController (PromiseKit) + +- (AnyPromise *)promiseViewController:(UIViewController *)vc animated:(BOOL)animated completion:(void (^)(void))block { + __kindof UIViewController *vc2present = vc; + AnyPromise *promise = nil; + + if ([vc isKindOfClass:NSClassFromString(@"MFMailComposeViewController")]) { + PMKGenericDelegate *delegate = [PMKGenericDelegate delegateWithPromise:&promise]; + [vc setValue:delegate forKey:@"mailComposeDelegate"]; + } + else if ([vc isKindOfClass:NSClassFromString(@"MFMessageComposeViewController")]) { + PMKGenericDelegate *delegate = [PMKGenericDelegate delegateWithPromise:&promise]; + [vc setValue:delegate forKey:@"messageComposeDelegate"]; + } +#ifdef PMKImagePickerController + else if ([vc isKindOfClass:[UIImagePickerController class]]) { + PMKGenericDelegate *delegate = [PMKGenericDelegate delegateWithPromise:&promise]; + [vc setValue:delegate forKey:@"delegate"]; + } +#endif + else if ([vc isKindOfClass:NSClassFromString(@"SLComposeViewController")]) { + PMKResolver resolve; + promise = [[AnyPromise alloc] initWithResolver:&resolve]; + [vc setValue:^(NSInteger result){ + if (result == 0) { + resolve([NSError errorWithDomain:NSCocoaErrorDomain code:NSUserCancelledError userInfo:nil]); + } else { + resolve(@(result)); + } + } forKey:@"completionHandler"]; + } + else if ([vc isKindOfClass:[UINavigationController class]]) + vc = [(id)vc viewControllers].firstObject; + + if (!vc) { + id userInfo = @{NSLocalizedDescriptionKey: @"nil or effective nil passed to promiseViewController"}; + id err = [NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:userInfo]; + return [AnyPromise promiseWithValue:err]; + } + + if (!promise) { + if (![vc respondsToSelector:@selector(promise)]) { + id userInfo = @{NSLocalizedDescriptionKey: @"ViewController is not promisable"}; + id err = [NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:userInfo]; + return [AnyPromise promiseWithValue:err]; + } + + promise = [vc valueForKey:@"promise"]; + + if (![promise isKindOfClass:[AnyPromise class]]) { + id userInfo = @{NSLocalizedDescriptionKey: @"The promise property is nil or not of type AnyPromise"}; + id err = [NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:userInfo]; + return [AnyPromise promiseWithValue:err]; + } + } + + if (!promise.pending) + return promise; + + [self presentViewController:vc2present animated:animated completion:block]; + + promise.ensure(^{ + [vc2present.presentingViewController dismissViewControllerAnimated:animated completion:nil]; + }); + + return promise; +} + +@end + + + +@implementation PMKGenericDelegate { + id retainCycle; +} + ++ (instancetype)delegateWithPromise:(AnyPromise **)promise; { + PMKGenericDelegate *d = [PMKGenericDelegate new]; + d->retainCycle = d; + *promise = [[AnyPromise alloc] initWithResolver:&d->resolve]; + return d; +} + +- (void)mailComposeController:(id)controller didFinishWithResult:(int)result error:(NSError *)error { + if (error != nil) { + resolve(error); + } else if (result == 0) { + resolve([NSError errorWithDomain:NSCocoaErrorDomain code:NSUserCancelledError userInfo:nil]); + } else { + resolve(@(result)); + } + retainCycle = nil; +} + +- (void)messageComposeViewController:(id)controller didFinishWithResult:(int)result { + if (result == 2) { + id userInfo = @{NSLocalizedDescriptionKey: @"The attempt to save or send the message was unsuccessful."}; + id error = [NSError errorWithDomain:PMKErrorDomain code:PMKOperationFailed userInfo:userInfo]; + resolve(error); + } else { + resolve(@(result)); + } + retainCycle = nil; +} + +#ifdef PMKImagePickerController + +- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { + id img = info[UIImagePickerControllerEditedImage] ?: info[UIImagePickerControllerOriginalImage]; + resolve(PMKManifold(img, info)); + retainCycle = nil; +} + +- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { + resolve([NSError errorWithDomain:NSCocoaErrorDomain code:NSUserCancelledError userInfo:nil]); + retainCycle = nil; +} + +#endif + +@end diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewPropertyAnimator+Promise.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewPropertyAnimator+Promise.swift new file mode 100644 index 000000000..34ee14084 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewPropertyAnimator+Promise.swift @@ -0,0 +1,14 @@ +#if !PMKCocoaPods +import PromiseKit +#endif +import UIKit + +@available(iOS 10, tvOS 10, *) +public extension UIViewPropertyAnimator { + func startAnimation(_: PMKNamespacer) -> Guarantee { + return Guarantee { + addCompletion($0) + startAnimation() + } + } +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/LICENSE b/Example/myWeb3Wallet/Pods/PromiseKit/LICENSE new file mode 100644 index 000000000..50f758c89 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/LICENSE @@ -0,0 +1,20 @@ +Copyright 2016-present, Max Howell; mxcl@me.com + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/README.md b/Example/myWeb3Wallet/Pods/PromiseKit/README.md new file mode 100644 index 000000000..d4b675d84 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/README.md @@ -0,0 +1,211 @@ +![PromiseKit](../gh-pages/public/img/logo-tight.png) + +[![badge-pod][]][cocoapods] ![badge-languages][] ![badge-pms][] ![badge-platforms][] [![badge-travis][]][travis] + +--- + +Promises simplify asynchronous programming, freeing you up to focus on the more +important things. They are easy to learn, easy to master and result in clearer, +more readable code. Your co-workers will thank you. + +```swift +UIApplication.shared.isNetworkActivityIndicatorVisible = true + +let fetchImage = URLSession.shared.dataTask(.promise, with: url).compactMap{ UIImage(data: $0.data) } +let fetchLocation = CLLocationManager.requestLocation().lastValue + +firstly { + when(fulfilled: fetchImage, fetchLocation) +}.done { image, location in + self.imageView.image = image + self.label.text = "\(location)" +}.ensure { + UIApplication.shared.isNetworkActivityIndicatorVisible = false +}.catch { error in + self.show(UIAlertController(for: error), sender: self) +} +``` + +PromiseKit is a thoughtful and complete implementation of promises for any +platform that has a `swiftc`. It has *excellent* Objective-C bridging and +*delightful* specializations for iOS, macOS, tvOS and watchOS. It is a top-100 +pod used in many of the most popular apps in the world. + +[![codecov](https://codecov.io/gh/mxcl/PromiseKit/branch/master/graph/badge.svg)](https://codecov.io/gh/mxcl/PromiseKit) + +# PromiseKit 7 Alpha + +We are testing PromiseKit 7 alpha, it is Swift 5 only. It is tagged and thus +importable in all package managers. + +# PromiseKit 6 + +[Release notes and migration guide][PMK6]. + +# Quick Start + +In your [Podfile]: + +```ruby +use_frameworks! + +target "Change Me!" do + pod "PromiseKit", "~> 6.8" +end +``` + +> The above gives an Xcode warning? See our [Installation Guide]. + +PromiseKit 6, 5 and 4 support Xcode 8.3, 9.x and 10.0; Swift 3.1, +3.2, 3.3, 3.4, 4.0, 4.1, 4.2, 4.3 and 5.0 (development snapshots); iOS, macOS, +tvOS, watchOS, Linux and Android; CocoaPods, Carthage and SwiftPM; +([CI Matrix](https://travis-ci.org/mxcl/PromiseKit)). + +For Carthage, SwiftPM, Accio, etc., or for instructions when using older Swifts or Xcodes, see our [Installation Guide]. We recommend +[Carthage](https://github.com/Carthage/Carthage) or +[Accio](https://github.com/JamitLabs/Accio). + +# Professionally Supported PromiseKit is Now Available + +TideLift gives software development teams a single source for purchasing +and maintaining their software, with professional grade assurances from +the experts who know it best, while seamlessly integrating with existing +tools. + +[Get Professional Support for PromiseKit with TideLift](https://tidelift.com/subscription/pkg/cocoapods-promisekit?utm_source=cocoapods-promisekit&utm_medium=referral&utm_campaign=readme). + +# PromiseKit is Thousands of Hours of Work + +Hey there, I’m Max Howell. I’m a prolific producer of open source software and +probably you already use some of it (I created [`brew`]). I work full-time on +open source and it’s hard; currently *I earn less than minimum wage*. Please +help me continue my work, I appreciate it 🙏🏻 + + + + + +[Other ways to say thanks](http://mxcl.dev/#donate). + +[`brew`]: https://brew.sh + +# Documentation + +* Handbook + * [Getting Started](Documentation/GettingStarted.md) + * [Promises: Common Patterns](Documentation/CommonPatterns.md) + * [Frequently Asked Questions](Documentation/FAQ.md) +* Manual + * [Installation Guide](Documentation/Installation.md) + * [Objective-C Guide](Documentation/ObjectiveC.md) + * [Troubleshooting](Documentation/Troubleshooting.md) (e.g., solutions to common compile errors) + * [Appendix](Documentation/Appendix.md) +* [API Reference](https://mxcl.dev/PromiseKit/reference/v6/Classes/Promise.html) + +# Extensions + +Promises are only as useful as the asynchronous tasks they represent. Thus, we +have converted (almost) all of Apple’s APIs to promises. The default CocoaPod +provides Promises and the extensions for Foundation and UIKit. The other +extensions are available by specifying additional subspecs in your `Podfile`, +e.g.: + +```ruby +pod "PromiseKit/MapKit" # MKDirections().calculate().then { /*…*/ } +pod "PromiseKit/CoreLocation" # CLLocationManager.requestLocation().then { /*…*/ } +``` + +All our extensions are separate repositories at the [PromiseKit organization]. + +## I don't want the extensions! + +Then don’t have them: + +```ruby +pod "PromiseKit/CorePromise", "~> 6.8" +``` + +> *Note:* Carthage installations come with no extensions by default. + +## Choose Your Networking Library + +Promise chains commonly start with a network operation. Thus, we offer +extensions for `URLSession`: + +```swift +// pod 'PromiseKit/Foundation' # https://github.com/PromiseKit/Foundation + +firstly { + URLSession.shared.dataTask(.promise, with: try makeUrlRequest()).validate() + // ^^ we provide `.validate()` so that eg. 404s get converted to errors +}.map { + try JSONDecoder().decode(Foo.self, with: $0.data) +}.done { foo in + //… +}.catch { error in + //… +} + +func makeUrlRequest() throws -> URLRequest { + var rq = URLRequest(url: url) + rq.httpMethod = "POST" + rq.addValue("application/json", forHTTPHeaderField: "Content-Type") + rq.addValue("application/json", forHTTPHeaderField: "Accept") + rq.httpBody = try JSONEncoder().encode(obj) + return rq +} +``` + +And [Alamofire]: + +```swift +// pod 'PromiseKit/Alamofire' # https://github.com/PromiseKit/Alamofire- + +firstly { + Alamofire + .request("http://example.com", method: .post, parameters: params) + .responseDecodable(Foo.self) +}.done { foo in + //… +}.catch { error in + //… +} +``` + +Nowadays, considering that: + +* We almost always POST JSON +* We now have `JSONDecoder` +* PromiseKit now has `map` and other functional primitives +* PromiseKit (like Alamofire, but not raw-`URLSession`) also defaults to having + callbacks go to the main thread + +We recommend vanilla `URLSession`. It uses fewer black boxes and sticks closer to the metal. Alamofire was essential until the three bullet points above +became true, but nowadays it isn’t really necessary. + +# Support + +Please check our [Troubleshooting Guide](Documentation/Troubleshooting.md), and +if after that you still have a question, ask at our [Gitter chat channel] or on [our bug tracker]. + +## Security & Vulnerability Reporting or Disclosure + +https://tidelift.com/security + + +[badge-pod]: https://img.shields.io/cocoapods/v/PromiseKit.svg?label=version +[badge-pms]: https://img.shields.io/badge/supports-CocoaPods%20%7C%20Carthage%20%7C%20Accio%20%7C%20SwiftPM-green.svg +[badge-languages]: https://img.shields.io/badge/languages-Swift%20%7C%20ObjC-orange.svg +[badge-platforms]: https://img.shields.io/badge/platforms-macOS%20%7C%20iOS%20%7C%20watchOS%20%7C%20tvOS%20%7C%20Linux-lightgrey.svg +[badge-mit]: https://img.shields.io/badge/license-MIT-blue.svg +[OMGHTTPURLRQ]: https://github.com/PromiseKit/OMGHTTPURLRQ +[Alamofire]: http://github.com/PromiseKit/Alamofire- +[PromiseKit organization]: https://github.com/PromiseKit +[Gitter chat channel]: https://gitter.im/mxcl/PromiseKit +[our bug tracker]: https://github.com/mxcl/PromiseKit/issues/new +[Podfile]: https://guides.cocoapods.org/syntax/podfile.html +[PMK6]: http://mxcl.dev/PromiseKit/news/2018/02/PromiseKit-6.0-Released/ +[Installation Guide]: Documentation/Installation.md +[badge-travis]: https://travis-ci.org/mxcl/PromiseKit.svg?branch=master +[travis]: https://travis-ci.org/mxcl/PromiseKit +[cocoapods]: https://cocoapods.org/pods/PromiseKit diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/AnyPromise+Private.h b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/AnyPromise+Private.h new file mode 100644 index 000000000..cd28c4183 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/AnyPromise+Private.h @@ -0,0 +1,32 @@ +@import Foundation.NSError; +@import Foundation.NSPointerArray; + +#if TARGET_OS_IPHONE + #define NSPointerArrayMake(N) ({ \ + NSPointerArray *aa = [NSPointerArray strongObjectsPointerArray]; \ + aa.count = N; \ + aa; \ + }) +#else + static inline NSPointerArray * __nonnull NSPointerArrayMake(NSUInteger count) { + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wdeprecated-declarations" + NSPointerArray *aa = [[NSPointerArray class] respondsToSelector:@selector(strongObjectsPointerArray)] + ? [NSPointerArray strongObjectsPointerArray] + : [NSPointerArray pointerArrayWithStrongObjects]; + #pragma clang diagnostic pop + aa.count = count; + return aa; + } +#endif + +#define IsError(o) [o isKindOfClass:[NSError class]] +#define IsPromise(o) [o isKindOfClass:[AnyPromise class]] + +#import "AnyPromise.h" + +@class PMKArray; + +@interface AnyPromise () +- (void)__pipe:(void(^ __nonnull)(__nullable id))block NS_REFINED_FOR_SWIFT; +@end diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/AnyPromise.h b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/AnyPromise.h new file mode 100644 index 000000000..75352d55c --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/AnyPromise.h @@ -0,0 +1,308 @@ +#import +#import +#import + +/// INTERNAL DO NOT USE +@class __AnyPromise; + +/// Provided to simplify some usage sites +typedef void (^PMKResolver)(id __nullable) NS_REFINED_FOR_SWIFT; + + +/// An Objective-C implementation of the promise pattern. +@interface AnyPromise: NSObject + +/** + Create a new promise that resolves with the provided block. + + Use this method when wrapping asynchronous code that does *not* use promises so that this code can be used in promise chains. + + If `resolve` is called with an `NSError` object, the promise is rejected, otherwise the promise is fulfilled. + + Don’t use this method if you already have promises! Instead, just return your promise. + + Should you need to fulfill a promise but have no sensical value to use: your promise is a `void` promise: fulfill with `nil`. + + The block you pass is executed immediately on the calling thread. + + - Parameter block: The provided block is immediately executed, inside the block call `resolve` to resolve this promise and cause any attached handlers to execute. If you are wrapping a delegate-based system, we recommend instead to use: initWithResolver: + - Returns: A new promise. + - Warning: Resolving a promise with `nil` fulfills it. + - SeeAlso: https://github.com/mxcl/PromiseKit/blob/master/Documentation/GettingStarted.md#making-promises + - SeeAlso: https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#wrapping-delegate-systems + */ ++ (instancetype __nonnull)promiseWithResolverBlock:(void (^ __nonnull)(__nonnull PMKResolver))resolveBlock NS_REFINED_FOR_SWIFT; + + +/// INTERNAL DO NOT USE +- (instancetype __nonnull)initWith__D:(__AnyPromise * __nonnull)d; + +/** + Creates a resolved promise. + + When developing your own promise systems, it is occasionally useful to be able to return an already resolved promise. + + - Parameter value: The value with which to resolve this promise. Passing an `NSError` will cause the promise to be rejected, passing an AnyPromise will return a new AnyPromise bound to that promise, otherwise the promise will be fulfilled with the value passed. + - Returns: A resolved promise. + */ ++ (instancetype __nonnull)promiseWithValue:(__nullable id)value NS_REFINED_FOR_SWIFT; + +/** + The value of the asynchronous task this promise represents. + + A promise has `nil` value if the asynchronous task it represents has not finished. If the value is `nil` the promise is still `pending`. + + - Warning: *Note* Our Swift variant’s value property returns nil if the promise is rejected where AnyPromise will return the error object. This fits with the pattern where AnyPromise is not strictly typed and is more dynamic, but you should be aware of the distinction. + + - Note: If the AnyPromise was fulfilled with a `PMKManifold`, returns only the first fulfillment object. + + - Returns: The value with which this promise was resolved or `nil` if this promise is pending. + */ +@property (nonatomic, readonly) __nullable id value NS_REFINED_FOR_SWIFT; + +/// - Returns: if the promise is pending resolution. +@property (nonatomic, readonly) BOOL pending NS_REFINED_FOR_SWIFT; + +/// - Returns: if the promise is resolved and fulfilled. +@property (nonatomic, readonly) BOOL fulfilled NS_REFINED_FOR_SWIFT; + +/// - Returns: if the promise is resolved and rejected. +@property (nonatomic, readonly) BOOL rejected NS_REFINED_FOR_SWIFT; + + +/** + The provided block is executed when its receiver is fulfilled. + + If you provide a block that takes a parameter, the value of the receiver will be passed as that parameter. + + [NSURLSession GET:url].then(^(NSData *data){ + // do something with data + }); + + @return A new promise that is resolved with the value returned from the provided block. For example: + + [NSURLSession GET:url].then(^(NSData *data){ + return data.length; + }).then(^(NSNumber *number){ + //… + }); + + @warning *Important* The block passed to `then` may take zero, one, two or three arguments, and return an object or return nothing. This flexibility is why the method signature for then is `id`, which means you will not get completion for the block parameter, and must type it yourself. It is safe to type any block syntax here, so to start with try just: `^{}`. + + @warning *Important* If an `NSError` or `NSString` is thrown inside your block, or you return an `NSError` object the next `Promise` will be rejected. See `catch` for documentation on error handling. + + @warning *Important* `then` is always executed on the main queue. + + @see thenOn + @see thenInBackground +*/ +- (AnyPromise * __nonnull (^ __nonnull)(id __nonnull))then NS_REFINED_FOR_SWIFT; + + +/** + The provided block is executed on the default queue when the receiver is fulfilled. + + This method is provided as a convenience for `thenOn`. + + @see then + @see thenOn +*/ +- (AnyPromise * __nonnull(^ __nonnull)(id __nonnull))thenInBackground NS_REFINED_FOR_SWIFT; + +/** + The provided block is executed on the dispatch queue of your choice when the receiver is fulfilled. + + @see then + @see thenInBackground +*/ +- (AnyPromise * __nonnull(^ __nonnull)(dispatch_queue_t __nonnull, id __nonnull))thenOn NS_REFINED_FOR_SWIFT; + +#ifndef __cplusplus +/** + The provided block is executed when the receiver is rejected. + + Provide a block of form `^(NSError *){}` or simply `^{}`. The parameter has type `id` to give you the freedom to choose either. + + The provided block always runs on the main queue. + + @warning *Note* Cancellation errors are not caught. + + @warning *Note* Since catch is a c++ keyword, this method is not available in Objective-C++ files. Instead use catchOn. + + @see catchOn + @see catchInBackground +*/ +- (AnyPromise * __nonnull(^ __nonnull)(id __nonnull))catch NS_REFINED_FOR_SWIFT; +#endif + +/** + The provided block is executed when the receiver is rejected. + + Provide a block of form `^(NSError *){}` or simply `^{}`. The parameter has type `id` to give you the freedom to choose either. + + The provided block always runs on the global background queue. + + @warning *Note* Cancellation errors are not caught. + + @warning *Note* Since catch is a c++ keyword, this method is not available in Objective-C++ files. Instead use catchWithPolicy. + + @see catch + @see catchOn + */ +- (AnyPromise * __nonnull(^ __nonnull)(id __nonnull))catchInBackground NS_REFINED_FOR_SWIFT; + + +/** + The provided block is executed when the receiver is rejected. + + Provide a block of form `^(NSError *){}` or simply `^{}`. The parameter has type `id` to give you the freedom to choose either. + + The provided block always runs on queue provided. + + @warning *Note* Cancellation errors are not caught. + + @see catch + @see catchInBackground + */ +- (AnyPromise * __nonnull(^ __nonnull)(dispatch_queue_t __nonnull, id __nonnull))catchOn NS_REFINED_FOR_SWIFT; + +/** + The provided block is executed when the receiver is resolved. + + The provided block always runs on the main queue. + + @see ensureOn +*/ +- (AnyPromise * __nonnull(^ __nonnull)(dispatch_block_t __nonnull))ensure NS_REFINED_FOR_SWIFT; + +/** + The provided block is executed on the dispatch queue of your choice when the receiver is resolved. + + @see ensure + */ +- (AnyPromise * __nonnull(^ __nonnull)(dispatch_queue_t __nonnull, dispatch_block_t __nonnull))ensureOn NS_REFINED_FOR_SWIFT; + +/** + Wait until the promise is resolved. + + @return Value if fulfilled or error if rejected. + */ +- (id __nullable)wait NS_REFINED_FOR_SWIFT; + +/** + Create a new promise with an associated resolver. + + Use this method when wrapping asynchronous code that does *not* use + promises so that this code can be used in promise chains. Generally, + prefer `promiseWithResolverBlock:` as the resulting code is more elegant. + + PMKResolver resolve; + AnyPromise *promise = [[AnyPromise alloc] initWithResolver:&resolve]; + + // later + resolve(@"foo"); + + @param resolver A reference to a block pointer of PMKResolver type. + You can then call your resolver to resolve this promise. + + @return A new promise. + + @warning *Important* The resolver strongly retains the promise. + + @see promiseWithResolverBlock: +*/ +- (instancetype __nonnull)initWithResolver:(PMKResolver __strong __nonnull * __nonnull)resolver NS_REFINED_FOR_SWIFT; + +/** + Unavailable methods + */ + +- (instancetype __nonnull)init __attribute__((unavailable("It is illegal to create an unresolvable promise."))); ++ (instancetype __nonnull)new __attribute__((unavailable("It is illegal to create an unresolvable promise."))); +- (AnyPromise * __nonnull(^ __nonnull)(dispatch_block_t __nonnull))always __attribute__((unavailable("See -ensure"))); +- (AnyPromise * __nonnull(^ __nonnull)(dispatch_block_t __nonnull))alwaysOn __attribute__((unavailable("See -ensureOn"))); +- (AnyPromise * __nonnull(^ __nonnull)(dispatch_block_t __nonnull))finally __attribute__((unavailable("See -ensure"))); +- (AnyPromise * __nonnull(^ __nonnull)(dispatch_block_t __nonnull, dispatch_block_t __nonnull))finallyOn __attribute__((unavailable("See -ensureOn"))); + +@end + + +typedef void (^PMKAdapter)(id __nullable, NSError * __nullable) NS_REFINED_FOR_SWIFT; +typedef void (^PMKIntegerAdapter)(NSInteger, NSError * __nullable) NS_REFINED_FOR_SWIFT; +typedef void (^PMKBooleanAdapter)(BOOL, NSError * __nullable) NS_REFINED_FOR_SWIFT; + + +@interface AnyPromise (Adapters) + +/** + Create a new promise by adapting an existing asynchronous system. + + The pattern of a completion block that passes two parameters, the first + the result and the second an `NSError` object is so common that we + provide this convenience adapter to make wrapping such systems more + elegant. + + return [PMKPromise promiseWithAdapterBlock:^(PMKAdapter adapter){ + PFQuery *query = [PFQuery …]; + [query findObjectsInBackgroundWithBlock:adapter]; + }]; + + @warning *Important* If both parameters are nil, the promise fulfills, + if both are non-nil the promise rejects. This is per the convention. + + @see https://github.com/mxcl/PromiseKit/blob/master/Documentation/GettingStarted.md#making-promises + */ ++ (instancetype __nonnull)promiseWithAdapterBlock:(void (^ __nonnull)(PMKAdapter __nonnull adapter))block NS_REFINED_FOR_SWIFT; + +/** + Create a new promise by adapting an existing asynchronous system. + + Adapts asynchronous systems that complete with `^(NSInteger, NSError *)`. + NSInteger will cast to enums provided the enum has been wrapped with + `NS_ENUM`. All of Apple’s enums are, so if you find one that hasn’t you + may need to make a pull-request. + + @see promiseWithAdapter + */ ++ (instancetype __nonnull)promiseWithIntegerAdapterBlock:(void (^ __nonnull)(PMKIntegerAdapter __nonnull adapter))block NS_REFINED_FOR_SWIFT; + +/** + Create a new promise by adapting an existing asynchronous system. + + Adapts asynchronous systems that complete with `^(BOOL, NSError *)`. + + @see promiseWithAdapter + */ ++ (instancetype __nonnull)promiseWithBooleanAdapterBlock:(void (^ __nonnull)(PMKBooleanAdapter __nonnull adapter))block NS_REFINED_FOR_SWIFT; + +@end + + +#ifdef __cplusplus +extern "C" { +#endif + +/** + Whenever resolving a promise you may resolve with a tuple, eg. + returning from a `then` or `catch` handler or resolving a new promise. + + Consumers of your Promise are not compelled to consume any arguments and + in fact will often only consume the first parameter. Thus ensure the + order of parameters is: from most-important to least-important. + + Currently PromiseKit limits you to THREE parameters to the manifold. +*/ +#define PMKManifold(...) __PMKManifold(__VA_ARGS__, 3, 2, 1) +#define __PMKManifold(_1, _2, _3, N, ...) __PMKArrayWithCount(N, _1, _2, _3) +extern id __nonnull __PMKArrayWithCount(NSUInteger, ...); + +#ifdef __cplusplus +} // Extern C +#endif + + + + +__attribute__((unavailable("See AnyPromise"))) +@interface PMKPromise +@end diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/AnyPromise.m b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/AnyPromise.m new file mode 100644 index 000000000..3725beacd --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/AnyPromise.m @@ -0,0 +1,179 @@ +#if __has_include("PromiseKit-Swift.h") + #import "PromiseKit-Swift.h" +#else + #import +#endif +#import "PMKCallVariadicBlock.m" +#import "AnyPromise+Private.h" +#import "AnyPromise.h" + +NSString *const PMKErrorDomain = @"PMKErrorDomain"; + + +@implementation AnyPromise { + __AnyPromise *d; +} + +- (instancetype)initWith__D:(__AnyPromise *)dd { + self = [super init]; + if (self) self->d = dd; + return self; +} + +- (instancetype)initWithResolver:(PMKResolver __strong *)resolver { + self = [super init]; + if (self) + d = [[__AnyPromise alloc] initWithResolver:^(void (^resolve)(id)) { + *resolver = resolve; + }]; + return self; +} + ++ (instancetype)promiseWithResolverBlock:(void (^)(PMKResolver _Nonnull))resolveBlock { + id d = [[__AnyPromise alloc] initWithResolver:resolveBlock]; + return [[self alloc] initWith__D:d]; +} + ++ (instancetype)promiseWithValue:(id)value { + //TODO provide a more efficient route for sealed promises + id d = [[__AnyPromise alloc] initWithResolver:^(void (^resolve)(id)) { + resolve(value); + }]; + return [[self alloc] initWith__D:d]; +} + +//TODO remove if possible, but used by when.m +- (void)__pipe:(void (^)(id _Nullable))block { + [d __pipe:block]; +} + +//NOTE used by AnyPromise.swift +- (id)__d { + return d; +} + +- (AnyPromise *(^)(id))then { + return ^(id block) { + return [self->d __thenOn:dispatch_get_main_queue() execute:^(id obj) { + return PMKCallVariadicBlock(block, obj); + }]; + }; +} + +- (AnyPromise *(^)(dispatch_queue_t, id))thenOn { + return ^(dispatch_queue_t queue, id block) { + return [self->d __thenOn:queue execute:^(id obj) { + return PMKCallVariadicBlock(block, obj); + }]; + }; +} + +- (AnyPromise *(^)(id))thenInBackground { + return ^(id block) { + return [self->d __thenOn:dispatch_get_global_queue(0, 0) execute:^(id obj) { + return PMKCallVariadicBlock(block, obj); + }]; + }; +} + +- (AnyPromise *(^)(dispatch_queue_t, id))catchOn { + return ^(dispatch_queue_t q, id block) { + return [self->d __catchOn:q execute:^(id obj) { + return PMKCallVariadicBlock(block, obj); + }]; + }; +} + +- (AnyPromise *(^)(id))catch { + return ^(id block) { + return [self->d __catchOn:dispatch_get_main_queue() execute:^(id obj) { + return PMKCallVariadicBlock(block, obj); + }]; + }; +} + +- (AnyPromise *(^)(id))catchInBackground { + return ^(id block) { + return [self->d __catchOn:dispatch_get_global_queue(0, 0) execute:^(id obj) { + return PMKCallVariadicBlock(block, obj); + }]; + }; +} + +- (AnyPromise *(^)(dispatch_block_t))ensure { + return ^(dispatch_block_t block) { + return [self->d __ensureOn:dispatch_get_main_queue() execute:block]; + }; +} + +- (AnyPromise *(^)(dispatch_queue_t, dispatch_block_t))ensureOn { + return ^(dispatch_queue_t queue, dispatch_block_t block) { + return [self->d __ensureOn:queue execute:block]; + }; +} + +- (id)wait { + return [d __wait]; +} + +- (BOOL)pending { + return [[d valueForKey:@"__pending"] boolValue]; +} + +- (BOOL)rejected { + return IsError([d __value]); +} + +- (BOOL)fulfilled { + return !self.rejected; +} + +- (id)value { + id obj = [d __value]; + + if ([obj isKindOfClass:[PMKArray class]]) { + return obj[0]; + } else { + return obj; + } +} + +@end + + + +@implementation AnyPromise (Adapters) + ++ (instancetype)promiseWithAdapterBlock:(void (^)(PMKAdapter))block { + return [self promiseWithResolverBlock:^(PMKResolver resolve) { + block(^(id value, id error){ + resolve(error ?: value); + }); + }]; +} + ++ (instancetype)promiseWithIntegerAdapterBlock:(void (^)(PMKIntegerAdapter))block { + return [self promiseWithResolverBlock:^(PMKResolver resolve) { + block(^(NSInteger value, id error){ + if (error) { + resolve(error); + } else { + resolve(@(value)); + } + }); + }]; +} + ++ (instancetype)promiseWithBooleanAdapterBlock:(void (^)(PMKBooleanAdapter adapter))block { + return [self promiseWithResolverBlock:^(PMKResolver resolve) { + block(^(BOOL value, id error){ + if (error) { + resolve(error); + } else { + resolve(@(value)); + } + }); + }]; +} + +@end diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/AnyPromise.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/AnyPromise.swift new file mode 100644 index 000000000..d7e575d2d --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/AnyPromise.swift @@ -0,0 +1,224 @@ +import Foundation + +/** + __AnyPromise is an implementation detail. + + Because of how ObjC/Swift compatibility work we have to compose our AnyPromise + with this internal object, however this is still part of the public interface. + Sadly. Please don’t use it. +*/ +@objc(__AnyPromise) public class __AnyPromise: NSObject { + fileprivate let box: Box + + @objc public init(resolver body: (@escaping (Any?) -> Void) -> Void) { + box = EmptyBox() + super.init() + body { + if let p = $0 as? AnyPromise { + p.d.__pipe(self.box.seal) + } else { + self.box.seal($0) + } + } + } + + @objc public func __thenOn(_ q: DispatchQueue, execute: @escaping (Any?) -> Any?) -> AnyPromise { + return AnyPromise(__D: __AnyPromise(resolver: { resolve in + self.__pipe { obj in + if !(obj is NSError) { + q.async { + resolve(execute(obj)) + } + } else { + resolve(obj) + } + } + })) + } + + @objc public func __catchOn(_ q: DispatchQueue, execute: @escaping (Any?) -> Any?) -> AnyPromise { + return AnyPromise(__D: __AnyPromise(resolver: { resolve in + self.__pipe { obj in + if obj is NSError { + q.async { + resolve(execute(obj)) + } + } else { + resolve(obj) + } + } + })) + } + + @objc public func __ensureOn(_ q: DispatchQueue, execute: @escaping () -> Void) -> AnyPromise { + return AnyPromise(__D: __AnyPromise(resolver: { resolve in + self.__pipe { obj in + q.async { + execute() + resolve(obj) + } + } + })) + } + + @objc public func __wait() -> Any? { + if Thread.isMainThread { + conf.logHandler(.waitOnMainThread) + } + + var result = __value + + if result == nil { + let group = DispatchGroup() + group.enter() + self.__pipe { obj in + result = obj + group.leave() + } + group.wait() + } + + return result + } + + /// Internal, do not use! Some behaviors undefined. + @objc public func __pipe(_ to: @escaping (Any?) -> Void) { + let to = { (obj: Any?) -> Void in + if obj is NSError { + to(obj) // or we cannot determine if objects are errors in objc land + } else { + to(obj) + } + } + switch box.inspect() { + case .pending: + box.inspect { + switch $0 { + case .pending(let handlers): + handlers.append { obj in + to(obj) + } + case .resolved(let obj): + to(obj) + } + } + case .resolved(let obj): + to(obj) + } + } + + @objc public var __value: Any? { + switch box.inspect() { + case .resolved(let obj): + return obj + default: + return nil + } + } + + @objc public var __pending: Bool { + switch box.inspect() { + case .pending: + return true + case .resolved: + return false + } + } +} + +extension AnyPromise: Thenable, CatchMixin { + + /// - Returns: A new `AnyPromise` bound to a `Promise`. + public convenience init(_ bridge: U) { + self.init(__D: __AnyPromise(resolver: { resolve in + bridge.pipe { + switch $0 { + case .rejected(let error): + resolve(error as NSError) + case .fulfilled(let value): + resolve(value) + } + } + })) + } + + public func pipe(to body: @escaping (Result) -> Void) { + + func fulfill() { + // calling through to the ObjC `value` property unwraps (any) PMKManifold + // and considering this is the Swift pipe; we want that. + body(.fulfilled(self.value(forKey: "value"))) + } + + switch box.inspect() { + case .pending: + box.inspect { + switch $0 { + case .pending(let handlers): + handlers.append { + if let error = $0 as? Error { + body(.rejected(error)) + } else { + fulfill() + } + } + case .resolved(let error as Error): + body(.rejected(error)) + case .resolved: + fulfill() + } + } + case .resolved(let error as Error): + body(.rejected(error)) + case .resolved: + fulfill() + } + } + + fileprivate var d: __AnyPromise { + return value(forKey: "__d") as! __AnyPromise + } + + var box: Box { + return d.box + } + + public var result: Result? { + guard let value = __value else { + return nil + } + if let error = value as? Error { + return .rejected(error) + } else { + return .fulfilled(value) + } + } + + public typealias T = Any? +} + + +#if swift(>=3.1) +public extension Promise where T == Any? { + convenience init(_ anyPromise: AnyPromise) { + self.init { + anyPromise.pipe(to: $0.resolve) + } + } +} +#else +extension AnyPromise { + public func asPromise() -> Promise { + return Promise(.pending, resolver: { resolve in + pipe { result in + switch result { + case .rejected(let error): + resolve.reject(error) + case .fulfilled(let obj): + resolve.fulfill(obj) + } + } + }) + } +} +#endif diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Box.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Box.swift new file mode 100644 index 000000000..43cd3d1b0 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Box.swift @@ -0,0 +1,101 @@ +import Dispatch + +enum Sealant { + case pending(Handlers) + case resolved(R) +} + +final class Handlers { + var bodies: [(R) -> Void] = [] + func append(_ item: @escaping(R) -> Void) { bodies.append(item) } +} + +/// - Remark: not protocol ∵ http://www.russbishop.net/swift-associated-types-cont +class Box { + func inspect() -> Sealant { fatalError() } + func inspect(_: (Sealant) -> Void) { fatalError() } + func seal(_: T) {} +} + +final class SealedBox: Box { + let value: T + + init(value: T) { + self.value = value + } + + override func inspect() -> Sealant { + return .resolved(value) + } +} + +class EmptyBox: Box { + private var sealant = Sealant.pending(.init()) + private let barrier = DispatchQueue(label: "org.promisekit.barrier", attributes: .concurrent) + + override func seal(_ value: T) { + var handlers: Handlers! + barrier.sync(flags: .barrier) { + guard case .pending(let _handlers) = self.sealant else { + return // already fulfilled! + } + handlers = _handlers + self.sealant = .resolved(value) + } + + //FIXME we are resolved so should `pipe(to:)` be called at this instant, “thens are called in order” would be invalid + //NOTE we don’t do this in the above `sync` because that could potentially deadlock + //THOUGH since `then` etc. typically invoke after a run-loop cycle, this issue is somewhat less severe + + if let handlers = handlers { + handlers.bodies.forEach{ $0(value) } + } + + //TODO solution is an unfortunate third state “sealed” where then's get added + // to a separate handler pool for that state + // any other solution has potential races + } + + override func inspect() -> Sealant { + var rv: Sealant! + barrier.sync { + rv = self.sealant + } + return rv + } + + override func inspect(_ body: (Sealant) -> Void) { + var sealed = false + barrier.sync(flags: .barrier) { + switch sealant { + case .pending: + // body will append to handlers, so we must stay barrier’d + body(sealant) + case .resolved: + sealed = true + } + } + if sealed { + // we do this outside the barrier to prevent potential deadlocks + // it's safe because we never transition away from this state + body(sealant) + } + } +} + + +extension Optional where Wrapped: DispatchQueue { + @inline(__always) + func async(flags: DispatchWorkItemFlags?, _ body: @escaping() -> Void) { + switch self { + case .none: + body() + case .some(let q): + if let flags = flags { + q.async(flags: flags, execute: body) + } else { + q.async(execute: body) + } + } + } +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Catchable.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Catchable.swift new file mode 100644 index 000000000..596abdcba --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Catchable.swift @@ -0,0 +1,256 @@ +import Dispatch + +/// Provides `catch` and `recover` to your object that conforms to `Thenable` +public protocol CatchMixin: Thenable +{} + +public extension CatchMixin { + + /** + The provided closure executes when this promise rejects. + + Rejecting a promise cascades: rejecting all subsequent promises (unless + recover is invoked) thus you will typically place your catch at the end + of a chain. Often utility promises will not have a catch, instead + delegating the error handling to the caller. + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter policy: The default policy does not execute your handler for cancellation errors. + - Parameter execute: The handler to execute if this promise is rejected. + - Returns: A promise finalizer. + - SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation) + */ + @discardableResult + func `catch`(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, policy: CatchPolicy = conf.catchPolicy, _ body: @escaping(Error) -> Void) -> PMKFinalizer { + let finalizer = PMKFinalizer() + pipe { + switch $0 { + case .rejected(let error): + guard policy == .allErrors || !error.isCancelled else { + fallthrough + } + on.async(flags: flags) { + body(error) + finalizer.pending.resolve(()) + } + case .fulfilled: + finalizer.pending.resolve(()) + } + } + return finalizer + } +} + +public class PMKFinalizer { + let pending = Guarantee.pending() + + /// `finally` is the same as `ensure`, but it is not chainable + public func finally(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping () -> Void) { + pending.guarantee.done(on: on, flags: flags) { + body() + } + } +} + + +public extension CatchMixin { + + /** + The provided closure executes when this promise rejects. + + Unlike `catch`, `recover` continues the chain. + Use `recover` in circumstances where recovering the chain from certain errors is a possibility. For example: + + firstly { + CLLocationManager.requestLocation() + }.recover { error in + guard error == CLError.unknownLocation else { throw error } + return .value(CLLocation.chicago) + } + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter body: The handler to execute if this promise is rejected. + - SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation) + */ + func recover(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, policy: CatchPolicy = conf.catchPolicy, _ body: @escaping(Error) throws -> U) -> Promise where U.T == T { + let rp = Promise(.pending) + pipe { + switch $0 { + case .fulfilled(let value): + rp.box.seal(.fulfilled(value)) + case .rejected(let error): + if policy == .allErrors || !error.isCancelled { + on.async(flags: flags) { + do { + let rv = try body(error) + guard rv !== rp else { throw PMKError.returnedSelf } + rv.pipe(to: rp.box.seal) + } catch { + rp.box.seal(.rejected(error)) + } + } + } else { + rp.box.seal(.rejected(error)) + } + } + } + return rp + } + + /** + The provided closure executes when this promise rejects. + This variant of `recover` requires the handler to return a Guarantee, thus it returns a Guarantee itself and your closure cannot `throw`. + - Note it is logically impossible for this to take a `catchPolicy`, thus `allErrors` are handled. + - Parameter on: The queue to which the provided closure dispatches. + - Parameter body: The handler to execute if this promise is rejected. + - SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation) + */ + @discardableResult + func recover(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(Error) -> Guarantee) -> Guarantee { + let rg = Guarantee(.pending) + pipe { + switch $0 { + case .fulfilled(let value): + rg.box.seal(value) + case .rejected(let error): + on.async(flags: flags) { + body(error).pipe(to: rg.box.seal) + } + } + } + return rg + } + + /** + The provided closure executes when this promise resolves, whether it rejects or not. + + firstly { + UIApplication.shared.networkActivityIndicatorVisible = true + }.done { + //… + }.ensure { + UIApplication.shared.networkActivityIndicatorVisible = false + }.catch { + //… + } + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter body: The closure that executes when this promise resolves. + - Returns: A new promise, resolved with this promise’s resolution. + */ + func ensure(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping () -> Void) -> Promise { + let rp = Promise(.pending) + pipe { result in + on.async(flags: flags) { + body() + rp.box.seal(result) + } + } + return rp + } + + /** + The provided closure executes when this promise resolves, whether it rejects or not. + The chain waits on the returned `Guarantee`. + + firstly { + setup() + }.done { + //… + }.ensureThen { + teardown() // -> Guarante + }.catch { + //… + } + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter body: The closure that executes when this promise resolves. + - Returns: A new promise, resolved with this promise’s resolution. + */ + func ensureThen(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping () -> Guarantee) -> Promise { + let rp = Promise(.pending) + pipe { result in + on.async(flags: flags) { + body().done { + rp.box.seal(result) + } + } + } + return rp + } + + + + /** + Consumes the Swift unused-result warning. + - Note: You should `catch`, but in situations where you know you don’t need a `catch`, `cauterize` makes your intentions clear. + */ + @discardableResult + func cauterize() -> PMKFinalizer { + return self.catch { + conf.logHandler(.cauterized($0)) + } + } +} + + +public extension CatchMixin where T == Void { + + /** + The provided closure executes when this promise rejects. + + This variant of `recover` is specialized for `Void` promises and de-errors your chain returning a `Guarantee`, thus you cannot `throw` and you must handle all errors including cancellation. + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter body: The handler to execute if this promise is rejected. + - SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation) + */ + @discardableResult + func recover(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(Error) -> Void) -> Guarantee { + let rg = Guarantee(.pending) + pipe { + switch $0 { + case .fulfilled: + rg.box.seal(()) + case .rejected(let error): + on.async(flags: flags) { + body(error) + rg.box.seal(()) + } + } + } + return rg + } + + /** + The provided closure executes when this promise rejects. + + This variant of `recover` ensures that no error is thrown from the handler and allows specifying a catch policy. + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter body: The handler to execute if this promise is rejected. + - SeeAlso: [Cancellation](https://github.com/mxcl/PromiseKit/blob/master/Documentation/CommonPatterns.md#cancellation) + */ + func recover(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, policy: CatchPolicy = conf.catchPolicy, _ body: @escaping(Error) throws -> Void) -> Promise { + let rg = Promise(.pending) + pipe { + switch $0 { + case .fulfilled: + rg.box.seal(.fulfilled(())) + case .rejected(let error): + if policy == .allErrors || !error.isCancelled { + on.async(flags: flags) { + do { + rg.box.seal(.fulfilled(try body(error))) + } catch { + rg.box.seal(.rejected(error)) + } + } + } else { + rg.box.seal(.rejected(error)) + } + } + } + return rg + } +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Configuration.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Configuration.swift new file mode 100644 index 000000000..4db523237 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Configuration.swift @@ -0,0 +1,35 @@ +import Dispatch + +/** + PromiseKit’s configurable parameters. + + Do not change these after any Promise machinery executes as the configuration object is not thread-safe. + + We would like it to be, but sadly `Swift` does not expose `dispatch_once` et al. which is what we used to use in order to make the configuration immutable once first used. +*/ +public struct PMKConfiguration { + /// The default queues that promises handlers dispatch to + public var Q: (map: DispatchQueue?, return: DispatchQueue?) = (map: DispatchQueue.main, return: DispatchQueue.main) + + /// The default catch-policy for all `catch` and `resolve` + public var catchPolicy = CatchPolicy.allErrorsExceptCancellation + + /// The closure used to log PromiseKit events. + /// Not thread safe; change before processing any promises. + /// - Note: The default handler calls `print()` + public var logHandler: (LogEvent) -> Void = { event in + switch event { + case .waitOnMainThread: + print("PromiseKit: warning: `wait()` called on main thread!") + case .pendingPromiseDeallocated: + print("PromiseKit: warning: pending promise deallocated") + case .pendingGuaranteeDeallocated: + print("PromiseKit: warning: pending guarantee deallocated") + case .cauterized (let error): + print("PromiseKit:cauterized-error: \(error)") + } + } +} + +/// Modify this as soon as possible in your application’s lifetime +public var conf = PMKConfiguration() diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/CustomStringConvertible.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/CustomStringConvertible.swift new file mode 100644 index 000000000..eee0b020a --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/CustomStringConvertible.swift @@ -0,0 +1,44 @@ + +extension Promise: CustomStringConvertible { + /// - Returns: A description of the state of this promise. + public var description: String { + switch result { + case nil: + return "Promise(…\(T.self))" + case .rejected(let error)?: + return "Promise(\(error))" + case .fulfilled(let value)?: + return "Promise(\(value))" + } + } +} + +extension Promise: CustomDebugStringConvertible { + /// - Returns: A debug-friendly description of the state of this promise. + public var debugDescription: String { + switch box.inspect() { + case .pending(let handlers): + return "Promise<\(T.self)>.pending(handlers: \(handlers.bodies.count))" + case .resolved(.rejected(let error)): + return "Promise<\(T.self)>.rejected(\(type(of: error)).\(error))" + case .resolved(.fulfilled(let value)): + return "Promise<\(T.self)>.fulfilled(\(value))" + } + } +} + +#if !SWIFT_PACKAGE +extension AnyPromise { + /// - Returns: A description of the state of this promise. + override open var description: String { + switch box.inspect() { + case .pending: + return "AnyPromise(…)" + case .resolved(let obj?): + return "AnyPromise(\(obj))" + case .resolved(nil): + return "AnyPromise(nil)" + } + } +} +#endif diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Deprecations.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Deprecations.swift new file mode 100644 index 000000000..a837dcb8d --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Deprecations.swift @@ -0,0 +1,93 @@ +import Dispatch + +@available(*, deprecated, message: "See `init(resolver:)`") +public func wrap(_ body: (@escaping (T?, Error?) -> Void) throws -> Void) -> Promise { + return Promise { seal in + try body(seal.resolve) + } +} + +@available(*, deprecated, message: "See `init(resolver:)`") +public func wrap(_ body: (@escaping (T, Error?) -> Void) throws -> Void) -> Promise { + return Promise { seal in + try body(seal.resolve) + } +} + +@available(*, deprecated, message: "See `init(resolver:)`") +public func wrap(_ body: (@escaping (Error?, T?) -> Void) throws -> Void) -> Promise { + return Promise { seal in + try body(seal.resolve) + } +} + +@available(*, deprecated, message: "See `init(resolver:)`") +public func wrap(_ body: (@escaping (Error?) -> Void) throws -> Void) -> Promise { + return Promise { seal in + try body(seal.resolve) + } +} + +@available(*, deprecated, message: "See `init(resolver:)`") +public func wrap(_ body: (@escaping (T) -> Void) throws -> Void) -> Promise { + return Promise { seal in + try body(seal.fulfill) + } +} + +public extension Promise { + @available(*, deprecated, message: "See `ensure`") + func always(on q: DispatchQueue = .main, execute body: @escaping () -> Void) -> Promise { + return ensure(on: q, body) + } +} + +public extension Thenable { +#if PMKFullDeprecations + /// disabled due to ambiguity with the other `.flatMap` + @available(*, deprecated, message: "See: `compactMap`") + func flatMap(on: DispatchQueue? = conf.Q.map, _ transform: @escaping(T) throws -> U?) -> Promise { + return compactMap(on: on, transform) + } +#endif +} + +public extension Thenable where T: Sequence { +#if PMKFullDeprecations + /// disabled due to ambiguity with the other `.map` + @available(*, deprecated, message: "See: `mapValues`") + func map(on: DispatchQueue? = conf.Q.map, _ transform: @escaping(T.Iterator.Element) throws -> U) -> Promise<[U]> { + return mapValues(on: on, transform) + } + + /// disabled due to ambiguity with the other `.flatMap` + @available(*, deprecated, message: "See: `flatMapValues`") + func flatMap(on: DispatchQueue? = conf.Q.map, _ transform: @escaping(T.Iterator.Element) throws -> U) -> Promise<[U.Iterator.Element]> { + return flatMapValues(on: on, transform) + } +#endif + + @available(*, deprecated, message: "See: `filterValues`") + func filter(on: DispatchQueue? = conf.Q.map, test: @escaping (T.Iterator.Element) -> Bool) -> Promise<[T.Iterator.Element]> { + return filterValues(on: on, test) + } +} + +public extension Thenable where T: Collection { + @available(*, deprecated, message: "See: `firstValue`") + var first: Promise { + return firstValue + } + + @available(*, deprecated, message: "See: `lastValue`") + var last: Promise { + return lastValue + } +} + +public extension Thenable where T: Sequence, T.Iterator.Element: Comparable { + @available(*, deprecated, message: "See: `sortedValues`") + func sorted(on: DispatchQueue? = conf.Q.map) -> Promise<[T.Iterator.Element]> { + return sortedValues(on: on) + } +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Error.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Error.swift new file mode 100644 index 000000000..be22f6b4b --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Error.swift @@ -0,0 +1,111 @@ +import Foundation + +public enum PMKError: Error { + /** + The completionHandler with form `(T?, Error?)` was called with `(nil, nil)`. + This is invalid as per Cocoa/Apple calling conventions. + */ + case invalidCallingConvention + + /** + A handler returned its own promise. 99% of the time, this is likely a + programming error. It is also invalid per Promises/A+. + */ + case returnedSelf + + /** `when()`, `race()` etc. were called with invalid parameters, eg. an empty array. */ + case badInput + + /// The operation was cancelled + case cancelled + + /// `nil` was returned from `flatMap` + @available(*, deprecated, message: "See: `compactMap`") + case flatMap(Any, Any.Type) + + /// `nil` was returned from `compactMap` + case compactMap(Any, Any.Type) + + /** + The lastValue or firstValue of a sequence was requested but the sequence was empty. + + Also used if all values of this collection failed the test passed to `firstValue(where:)`. + */ + case emptySequence + + /// no winner in `race(fulfilled:)` + case noWinner +} + +extension PMKError: CustomDebugStringConvertible { + public var debugDescription: String { + switch self { + case .flatMap(let obj, let type): + return "Could not `flatMap<\(type)>`: \(obj)" + case .compactMap(let obj, let type): + return "Could not `compactMap<\(type)>`: \(obj)" + case .invalidCallingConvention: + return "A closure was called with an invalid calling convention, probably (nil, nil)" + case .returnedSelf: + return "A promise handler returned itself" + case .badInput: + return "Bad input was provided to a PromiseKit function" + case .cancelled: + return "The asynchronous sequence was cancelled" + case .emptySequence: + return "The first or last element was requested for an empty sequence" + case .noWinner: + return "All thenables passed to race(fulfilled:) were rejected" + } + } +} + +extension PMKError: LocalizedError { + public var errorDescription: String? { + return debugDescription + } +} + + +//////////////////////////////////////////////////////////// Cancellation + +/// An error that may represent the cancelled condition +public protocol CancellableError: Error { + /// returns true if this Error represents a cancelled condition + var isCancelled: Bool { get } +} + +extension Error { + public var isCancelled: Bool { + do { + throw self + } catch PMKError.cancelled { + return true + } catch let error as CancellableError { + return error.isCancelled + } catch URLError.cancelled { + return true + } catch CocoaError.userCancelled { + return true + } catch let error as NSError { + #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) + let domain = error.domain + let code = error.code + return ("SKErrorDomain", 2) == (domain, code) + #else + return false + #endif + } catch { + return false + } + } +} + +/// Used by `catch` and `recover` +public enum CatchPolicy { + /// Indicates that `catch` or `recover` handle all error types including cancellable-errors. + case allErrors + + /// Indicates that `catch` or `recover` handle all error except cancellable-errors. + case allErrorsExceptCancellation +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Guarantee.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Guarantee.swift new file mode 100644 index 000000000..ce887cdc3 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Guarantee.swift @@ -0,0 +1,390 @@ +import class Foundation.Thread +import Dispatch + +/** + A `Guarantee` is a functional abstraction around an asynchronous operation that cannot error. + - See: `Thenable` +*/ +public final class Guarantee: Thenable { + let box: PromiseKit.Box + + fileprivate init(box: SealedBox) { + self.box = box + } + + /// Returns a `Guarantee` sealed with the provided value. + public static func value(_ value: T) -> Guarantee { + return .init(box: SealedBox(value: value)) + } + + /// Returns a pending `Guarantee` that can be resolved with the provided closure’s parameter. + public init(resolver body: (@escaping(T) -> Void) -> Void) { + box = Box() + body(box.seal) + } + + /// - See: `Thenable.pipe` + public func pipe(to: @escaping(Result) -> Void) { + pipe{ to(.fulfilled($0)) } + } + + func pipe(to: @escaping(T) -> Void) { + switch box.inspect() { + case .pending: + box.inspect { + switch $0 { + case .pending(let handlers): + handlers.append(to) + case .resolved(let value): + to(value) + } + } + case .resolved(let value): + to(value) + } + } + + /// - See: `Thenable.result` + public var result: Result? { + switch box.inspect() { + case .pending: + return nil + case .resolved(let value): + return .fulfilled(value) + } + } + + final private class Box: EmptyBox { + deinit { + switch inspect() { + case .pending: + PromiseKit.conf.logHandler(.pendingGuaranteeDeallocated) + case .resolved: + break + } + } + } + + init(_: PMKUnambiguousInitializer) { + box = Box() + } + + /// Returns a tuple of a pending `Guarantee` and a function that resolves it. + public class func pending() -> (guarantee: Guarantee, resolve: (T) -> Void) { + return { ($0, $0.box.seal) }(Guarantee(.pending)) + } +} + +public extension Guarantee { + @discardableResult + func done(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(T) -> Void) -> Guarantee { + let rg = Guarantee(.pending) + pipe { (value: T) in + on.async(flags: flags) { + body(value) + rg.box.seal(()) + } + } + return rg + } + + func get(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping (T) -> Void) -> Guarantee { + return map(on: on, flags: flags) { + body($0) + return $0 + } + } + + func map(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(T) -> U) -> Guarantee { + let rg = Guarantee(.pending) + pipe { value in + on.async(flags: flags) { + rg.box.seal(body(value)) + } + } + return rg + } + + #if swift(>=4) && !swift(>=5.2) + func map(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ keyPath: KeyPath) -> Guarantee { + let rg = Guarantee(.pending) + pipe { value in + on.async(flags: flags) { + rg.box.seal(value[keyPath: keyPath]) + } + } + return rg + } + #endif + + @discardableResult + func then(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(T) -> Guarantee) -> Guarantee { + let rg = Guarantee(.pending) + pipe { value in + on.async(flags: flags) { + body(value).pipe(to: rg.box.seal) + } + } + return rg + } + + func asVoid() -> Guarantee { + return map(on: nil) { _ in } + } + + /** + Blocks this thread, so you know, don’t call this on a serial thread that + any part of your chain may use. Like the main thread for example. + */ + func wait() -> T { + + if Thread.isMainThread { + conf.logHandler(.waitOnMainThread) + } + + var result = value + + if result == nil { + let group = DispatchGroup() + group.enter() + pipe { (foo: T) in result = foo; group.leave() } + group.wait() + } + + return result! + } +} + +public extension Guarantee where T: Sequence { + /** + `Guarantee<[T]>` => `T` -> `U` => `Guarantee<[U]>` + + Guarantee.value([1,2,3]) + .mapValues { integer in integer * 2 } + .done { + // $0 => [2,4,6] + } + */ + func mapValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) -> U) -> Guarantee<[U]> { + return map(on: on, flags: flags) { $0.map(transform) } + } + + #if swift(>=4) && !swift(>=5.2) + /** + `Guarantee<[T]>` => `KeyPath` => `Guarantee<[U]>` + + Guarantee.value([Person(name: "Max"), Person(name: "Roman"), Person(name: "John")]) + .mapValues(\.name) + .done { + // $0 => ["Max", "Roman", "John"] + } + */ + func mapValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ keyPath: KeyPath) -> Guarantee<[U]> { + return map(on: on, flags: flags) { $0.map { $0[keyPath: keyPath] } } + } + #endif + + /** + `Guarantee<[T]>` => `T` -> `[U]` => `Guarantee<[U]>` + + Guarantee.value([1,2,3]) + .flatMapValues { integer in [integer, integer] } + .done { + // $0 => [1,1,2,2,3,3] + } + */ + func flatMapValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) -> U) -> Guarantee<[U.Iterator.Element]> { + return map(on: on, flags: flags) { (foo: T) in + foo.flatMap { transform($0) } + } + } + + /** + `Guarantee<[T]>` => `T` -> `U?` => `Guarantee<[U]>` + + Guarantee.value(["1","2","a","3"]) + .compactMapValues { Int($0) } + .done { + // $0 => [1,2,3] + } + */ + func compactMapValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) -> U?) -> Guarantee<[U]> { + return map(on: on, flags: flags) { foo -> [U] in + #if !swift(>=3.3) || (swift(>=4) && !swift(>=4.1)) + return foo.flatMap(transform) + #else + return foo.compactMap(transform) + #endif + } + } + + #if swift(>=4) && !swift(>=5.2) + /** + `Guarantee<[T]>` => `KeyPath` => `Guarantee<[U]>` + + Guarantee.value([Person(name: "Max"), Person(name: "Roman", age: 26), Person(name: "John", age: 23)]) + .compactMapValues(\.age) + .done { + // $0 => [26, 23] + } + */ + func compactMapValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ keyPath: KeyPath) -> Guarantee<[U]> { + return map(on: on, flags: flags) { foo -> [U] in + #if !swift(>=4.1) + return foo.flatMap { $0[keyPath: keyPath] } + #else + return foo.compactMap { $0[keyPath: keyPath] } + #endif + } + } + #endif + + /** + `Guarantee<[T]>` => `T` -> `Guarantee` => `Guaranetee<[U]>` + + Guarantee.value([1,2,3]) + .thenMap { .value($0 * 2) } + .done { + // $0 => [2,4,6] + } + */ + func thenMap(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) -> Guarantee) -> Guarantee<[U]> { + return then(on: on, flags: flags) { + when(fulfilled: $0.map(transform)) + }.recover { + // if happens then is bug inside PromiseKit + fatalError(String(describing: $0)) + } + } + + /** + `Guarantee<[T]>` => `T` -> `Guarantee<[U]>` => `Guarantee<[U]>` + + Guarantee.value([1,2,3]) + .thenFlatMap { integer in .value([integer, integer]) } + .done { + // $0 => [1,1,2,2,3,3] + } + */ + func thenFlatMap(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) -> U) -> Guarantee<[U.T.Iterator.Element]> where U.T: Sequence { + return then(on: on, flags: flags) { + when(fulfilled: $0.map(transform)) + }.map(on: nil) { + $0.flatMap { $0 } + }.recover { + // if happens then is bug inside PromiseKit + fatalError(String(describing: $0)) + } + } + + /** + `Guarantee<[T]>` => `T` -> Bool => `Guarantee<[T]>` + + Guarantee.value([1,2,3]) + .filterValues { $0 > 1 } + .done { + // $0 => [2,3] + } + */ + func filterValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ isIncluded: @escaping(T.Iterator.Element) -> Bool) -> Guarantee<[T.Iterator.Element]> { + return map(on: on, flags: flags) { + $0.filter(isIncluded) + } + } + + #if swift(>=4) && !swift(>=5.2) + /** + `Guarantee<[T]>` => `KeyPath` => `Guarantee<[T]>` + + Guarantee.value([Person(name: "Max"), Person(name: "Roman", age: 26, isStudent: false), Person(name: "John", age: 23, isStudent: true)]) + .filterValues(\.isStudent) + .done { + // $0 => [Person(name: "John", age: 23, isStudent: true)] + } + */ + func filterValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ keyPath: KeyPath) -> Guarantee<[T.Iterator.Element]> { + return map(on: on, flags: flags) { + $0.filter { $0[keyPath: keyPath] } + } + } + #endif + + /** + `Guarantee<[T]>` => (`T`, `T`) -> Bool => `Guarantee<[T]>` + + Guarantee.value([5,2,3,4,1]) + .sortedValues { $0 > $1 } + .done { + // $0 => [5,4,3,2,1] + } + */ + func sortedValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ areInIncreasingOrder: @escaping(T.Iterator.Element, T.Iterator.Element) -> Bool) -> Guarantee<[T.Iterator.Element]> { + return map(on: on, flags: flags) { + $0.sorted(by: areInIncreasingOrder) + } + } +} + +public extension Guarantee where T: Sequence, T.Iterator.Element: Comparable { + /** + `Guarantee<[T]>` => `Guarantee<[T]>` + + Guarantee.value([5,2,3,4,1]) + .sortedValues() + .done { + // $0 => [1,2,3,4,5] + } + */ + func sortedValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil) -> Guarantee<[T.Iterator.Element]> { + return map(on: on, flags: flags) { $0.sorted() } + } +} + +#if swift(>=3.1) +public extension Guarantee where T == Void { + convenience init() { + self.init(box: SealedBox(value: Void())) + } + + static var value: Guarantee { + return .value(Void()) + } +} +#endif + + +public extension DispatchQueue { + /** + Asynchronously executes the provided closure on a dispatch queue. + + DispatchQueue.global().async(.promise) { + md5(input) + }.done { md5 in + //… + } + + - Parameter body: The closure that resolves this promise. + - Returns: A new `Guarantee` resolved by the result of the provided closure. + - Note: There is no Promise/Thenable version of this due to Swift compiler ambiguity issues. + */ + @available(macOS 10.10, iOS 2.0, tvOS 10.0, watchOS 2.0, *) + final func async(_: PMKNamespacer, group: DispatchGroup? = nil, qos: DispatchQoS = .default, flags: DispatchWorkItemFlags = [], execute body: @escaping () -> T) -> Guarantee { + let rg = Guarantee(.pending) + async(group: group, qos: qos, flags: flags) { + rg.box.seal(body()) + } + return rg + } +} + + +#if os(Linux) +import func CoreFoundation._CFIsMainThread + +extension Thread { + // `isMainThread` is not implemented yet in swift-corelibs-foundation. + static var isMainThread: Bool { + return _CFIsMainThread() + } +} +#endif diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/LogEvent.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/LogEvent.swift new file mode 100644 index 000000000..99683bdb6 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/LogEvent.swift @@ -0,0 +1,30 @@ +/** + The PromiseKit events which may be logged. + + ```` + /// A promise or guarantee has blocked the main thread + case waitOnMainThread + + /// A promise has been deallocated without being resolved + case pendingPromiseDeallocated + + /// An error which occurred while fulfilling a promise was swallowed + case cauterized(Error) + + /// Errors which give a string error message + case misc (String) + ```` +*/ +public enum LogEvent { + /// A promise or guarantee has blocked the main thread + case waitOnMainThread + + /// A promise has been deallocated without being resolved + case pendingPromiseDeallocated + + /// A guarantee has been deallocated without being resolved + case pendingGuaranteeDeallocated + + /// An error which occurred while resolving a promise was swallowed + case cauterized(Error) +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/NSMethodSignatureForBlock.m b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/NSMethodSignatureForBlock.m new file mode 100644 index 000000000..700c1b37e --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/NSMethodSignatureForBlock.m @@ -0,0 +1,77 @@ +#import + +struct PMKBlockLiteral { + void *isa; // initialized to &_NSConcreteStackBlock or &_NSConcreteGlobalBlock + int flags; + int reserved; + void (*invoke)(void *, ...); + struct block_descriptor { + unsigned long int reserved; // NULL + unsigned long int size; // sizeof(struct Block_literal_1) + // optional helper functions + void (*copy_helper)(void *dst, void *src); // IFF (1<<25) + void (*dispose_helper)(void *src); // IFF (1<<25) + // required ABI.2010.3.16 + const char *signature; // IFF (1<<30) + } *descriptor; + // imported variables +}; + +typedef NS_OPTIONS(NSUInteger, PMKBlockDescriptionFlags) { + PMKBlockDescriptionFlagsHasCopyDispose = (1 << 25), + PMKBlockDescriptionFlagsHasCtor = (1 << 26), // helpers have C++ code + PMKBlockDescriptionFlagsIsGlobal = (1 << 28), + PMKBlockDescriptionFlagsHasStret = (1 << 29), // IFF BLOCK_HAS_SIGNATURE + PMKBlockDescriptionFlagsHasSignature = (1 << 30) +}; + +// It appears 10.7 doesn't support quotes in method signatures. Remove them +// via @rabovik's method. See https://github.com/OliverLetterer/SLObjectiveCRuntimeAdditions/pull/2 +#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_8 +NS_INLINE static const char * pmk_removeQuotesFromMethodSignature(const char *str){ + char *result = malloc(strlen(str) + 1); + BOOL skip = NO; + char *to = result; + char c; + while ((c = *str++)) { + if ('"' == c) { + skip = !skip; + continue; + } + if (skip) continue; + *to++ = c; + } + *to = '\0'; + return result; +} +#endif + +static NSMethodSignature *NSMethodSignatureForBlock(id block) { + if (!block) + return nil; + + struct PMKBlockLiteral *blockRef = (__bridge struct PMKBlockLiteral *)block; + PMKBlockDescriptionFlags flags = (PMKBlockDescriptionFlags)blockRef->flags; + + if (flags & PMKBlockDescriptionFlagsHasSignature) { + void *signatureLocation = blockRef->descriptor; + signatureLocation += sizeof(unsigned long int); + signatureLocation += sizeof(unsigned long int); + + if (flags & PMKBlockDescriptionFlagsHasCopyDispose) { + signatureLocation += sizeof(void(*)(void *dst, void *src)); + signatureLocation += sizeof(void (*)(void *src)); + } + + const char *signature = (*(const char **)signatureLocation); +#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_8 + signature = pmk_removeQuotesFromMethodSignature(signature); + NSMethodSignature *nsSignature = [NSMethodSignature signatureWithObjCTypes:signature]; + free((void *)signature); + + return nsSignature; +#endif + return [NSMethodSignature signatureWithObjCTypes:signature]; + } + return 0; +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/PMKCallVariadicBlock.m b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/PMKCallVariadicBlock.m new file mode 100644 index 000000000..1453a7d26 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/PMKCallVariadicBlock.m @@ -0,0 +1,120 @@ +#import "NSMethodSignatureForBlock.m" +#import +#import +#import "AnyPromise+Private.h" +#import +#import +#import + +#ifndef PMKLog +#define PMKLog NSLog +#endif + +@interface PMKArray : NSObject { +@public + id objs[3]; + NSUInteger count; +} @end + +@implementation PMKArray + +- (id)objectAtIndexedSubscript:(NSUInteger)idx { + if (count <= idx) { + // this check is necessary due to lack of checks in `pmk_safely_call_block` + return nil; + } + return objs[idx]; +} + +@end + +id __PMKArrayWithCount(NSUInteger count, ...) { + PMKArray *this = [PMKArray new]; + this->count = count; + va_list args; + va_start(args, count); + for (NSUInteger x = 0; x < count; ++x) + this->objs[x] = va_arg(args, id); + va_end(args); + return this; +} + + +static inline id _PMKCallVariadicBlock(id frock, id result) { + NSCAssert(frock, @""); + + NSMethodSignature *sig = NSMethodSignatureForBlock(frock); + const NSUInteger nargs = sig.numberOfArguments; + const char rtype = sig.methodReturnType[0]; + + #define call_block_with_rtype(type) ({^type{ \ + switch (nargs) { \ + case 1: \ + return ((type(^)(void))frock)(); \ + case 2: { \ + const id arg = [result class] == [PMKArray class] ? result[0] : result; \ + return ((type(^)(id))frock)(arg); \ + } \ + case 3: { \ + type (^block)(id, id) = frock; \ + return [result class] == [PMKArray class] \ + ? block(result[0], result[1]) \ + : block(result, nil); \ + } \ + case 4: { \ + type (^block)(id, id, id) = frock; \ + return [result class] == [PMKArray class] \ + ? block(result[0], result[1], result[2]) \ + : block(result, nil, nil); \ + } \ + default: \ + @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"PromiseKit: The provided block’s argument count is unsupported." userInfo:nil]; \ + }}();}) + + switch (rtype) { + case 'v': + call_block_with_rtype(void); + return nil; + case '@': + return call_block_with_rtype(id) ?: nil; + case '*': { + char *str = call_block_with_rtype(char *); + return str ? @(str) : nil; + } + case 'c': return @(call_block_with_rtype(char)); + case 'i': return @(call_block_with_rtype(int)); + case 's': return @(call_block_with_rtype(short)); + case 'l': return @(call_block_with_rtype(long)); + case 'q': return @(call_block_with_rtype(long long)); + case 'C': return @(call_block_with_rtype(unsigned char)); + case 'I': return @(call_block_with_rtype(unsigned int)); + case 'S': return @(call_block_with_rtype(unsigned short)); + case 'L': return @(call_block_with_rtype(unsigned long)); + case 'Q': return @(call_block_with_rtype(unsigned long long)); + case 'f': return @(call_block_with_rtype(float)); + case 'd': return @(call_block_with_rtype(double)); + case 'B': return @(call_block_with_rtype(_Bool)); + case '^': + if (strcmp(sig.methodReturnType, "^v") == 0) { + call_block_with_rtype(void); + return nil; + } + // else fall through! + default: + @throw [NSException exceptionWithName:@"PromiseKit" reason:@"PromiseKit: Unsupported method signature." userInfo:nil]; + } +} + +static id PMKCallVariadicBlock(id frock, id result) { + @try { + return _PMKCallVariadicBlock(frock, result); + } @catch (id thrown) { + if ([thrown isKindOfClass:[NSString class]]) + return thrown; + if ([thrown isKindOfClass:[NSError class]]) + return thrown; + + // we don’t catch objc exceptions: they are meant to crash your app + @throw thrown; + } +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Promise.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Promise.swift new file mode 100644 index 000000000..ef5735224 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Promise.swift @@ -0,0 +1,184 @@ +import class Foundation.Thread +import Dispatch + +/** + A `Promise` is a functional abstraction around a failable asynchronous operation. + - See: `Thenable` + */ +public final class Promise: Thenable, CatchMixin { + let box: Box> + + fileprivate init(box: SealedBox>) { + self.box = box + } + + /** + Initialize a new fulfilled promise. + + We do not provide `init(value:)` because Swift is “greedy” + and would pick that initializer in cases where it should pick + one of the other more specific options leading to Promises with + `T` that is eg: `Error` or worse `(T->Void,Error->Void)` for + uses of our PMK < 4 pending initializer due to Swift trailing + closure syntax (nothing good comes without pain!). + + Though often easy to detect, sometimes these issues would be + hidden by other type inference leading to some nasty bugs in + production. + + In PMK5 we tried to work around this by making the pending + initializer take the form `Promise(.pending)` but this led to + bad migration errors for PMK4 users. Hence instead we quickly + released PMK6 and now only provide this initializer for making + sealed & fulfilled promises. + + Usage is still (usually) good: + + guard foo else { + return .value(bar) + } + */ + public static func value(_ value: T) -> Promise { + return Promise(box: SealedBox(value: .fulfilled(value))) + } + + /// Initialize a new rejected promise. + public init(error: Error) { + box = SealedBox(value: .rejected(error)) + } + + /// Initialize a new promise bound to the provided `Thenable`. + public init(_ bridge: U) where U.T == T { + box = EmptyBox() + bridge.pipe(to: box.seal) + } + + /// Initialize a new promise that can be resolved with the provided `Resolver`. + public init(resolver body: (Resolver) throws -> Void) { + box = EmptyBox() + let resolver = Resolver(box) + do { + try body(resolver) + } catch { + resolver.reject(error) + } + } + + /// - Returns: a tuple of a new pending promise and its `Resolver`. + public class func pending() -> (promise: Promise, resolver: Resolver) { + return { ($0, Resolver($0.box)) }(Promise(.pending)) + } + + /// - See: `Thenable.pipe` + public func pipe(to: @escaping(Result) -> Void) { + switch box.inspect() { + case .pending: + box.inspect { + switch $0 { + case .pending(let handlers): + handlers.append(to) + case .resolved(let value): + to(value) + } + } + case .resolved(let value): + to(value) + } + } + + /// - See: `Thenable.result` + public var result: Result? { + switch box.inspect() { + case .pending: + return nil + case .resolved(let result): + return result + } + } + + init(_: PMKUnambiguousInitializer) { + box = EmptyBox() + } +} + +public extension Promise { + /** + Blocks this thread, so—you know—don’t call this on a serial thread that + any part of your chain may use. Like the main thread for example. + */ + func wait() throws -> T { + + if Thread.isMainThread { + conf.logHandler(LogEvent.waitOnMainThread) + } + + var result = self.result + + if result == nil { + let group = DispatchGroup() + group.enter() + pipe { result = $0; group.leave() } + group.wait() + } + + switch result! { + case .rejected(let error): + throw error + case .fulfilled(let value): + return value + } + } +} + +#if swift(>=3.1) +extension Promise where T == Void { + /// Initializes a new promise fulfilled with `Void` + public convenience init() { + self.init(box: SealedBox(value: .fulfilled(Void()))) + } + + /// Returns a new promise fulfilled with `Void` + public static var value: Promise { + return .value(Void()) + } +} +#endif + + +public extension DispatchQueue { + /** + Asynchronously executes the provided closure on a dispatch queue. + + DispatchQueue.global().async(.promise) { + try md5(input) + }.done { md5 in + //… + } + + - Parameter body: The closure that resolves this promise. + - Returns: A new `Promise` resolved by the result of the provided closure. + - Note: There is no Promise/Thenable version of this due to Swift compiler ambiguity issues. + */ + @available(macOS 10.10, iOS 8.0, tvOS 9.0, watchOS 2.0, *) + final func async(_: PMKNamespacer, group: DispatchGroup? = nil, qos: DispatchQoS = .default, flags: DispatchWorkItemFlags = [], execute body: @escaping () throws -> T) -> Promise { + let promise = Promise(.pending) + async(group: group, qos: qos, flags: flags) { + do { + promise.box.seal(.fulfilled(try body())) + } catch { + promise.box.seal(.rejected(error)) + } + } + return promise + } +} + + +/// used by our extensions to provide unambiguous functions with the same name as the original function +public enum PMKNamespacer { + case promise +} + +enum PMKUnambiguousInitializer { + case pending +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/PromiseKit.h b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/PromiseKit.h new file mode 100644 index 000000000..c30d9376a --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/PromiseKit.h @@ -0,0 +1,7 @@ +#import +#import + +#import // `FOUNDATION_EXPORT` + +FOUNDATION_EXPORT double PromiseKitVersionNumber; +FOUNDATION_EXPORT const unsigned char PromiseKitVersionString[]; diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Resolver.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Resolver.swift new file mode 100644 index 000000000..c6b339fcd --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Resolver.swift @@ -0,0 +1,111 @@ +/// An object for resolving promises +public final class Resolver { + let box: Box> + + init(_ box: Box>) { + self.box = box + } + + deinit { + if case .pending = box.inspect() { + conf.logHandler(.pendingPromiseDeallocated) + } + } +} + +public extension Resolver { + /// Fulfills the promise with the provided value + func fulfill(_ value: T) { + box.seal(.fulfilled(value)) + } + + /// Rejects the promise with the provided error + func reject(_ error: Error) { + box.seal(.rejected(error)) + } + + /// Resolves the promise with the provided result + func resolve(_ result: Result) { + box.seal(result) + } + + /// Resolves the promise with the provided value or error + func resolve(_ obj: T?, _ error: Error?) { + if let error = error { + reject(error) + } else if let obj = obj { + fulfill(obj) + } else { + reject(PMKError.invalidCallingConvention) + } + } + + /// Fulfills the promise with the provided value unless the provided error is non-nil + func resolve(_ obj: T, _ error: Error?) { + if let error = error { + reject(error) + } else { + fulfill(obj) + } + } + + /// Resolves the promise, provided for non-conventional value-error ordered completion handlers. + func resolve(_ error: Error?, _ obj: T?) { + resolve(obj, error) + } +} + +#if swift(>=3.1) +extension Resolver where T == Void { + /// Fulfills the promise unless error is non-nil + public func resolve(_ error: Error?) { + if let error = error { + reject(error) + } else { + fulfill(()) + } + } +#if false + // disabled ∵ https://github.com/mxcl/PromiseKit/issues/990 + + /// Fulfills the promise + public func fulfill() { + self.fulfill(()) + } +#else + /// Fulfills the promise + /// - Note: underscore is present due to: https://github.com/mxcl/PromiseKit/issues/990 + public func fulfill_() { + self.fulfill(()) + } +#endif +} +#endif + +#if swift(>=5.0) +extension Resolver { + /// Resolves the promise with the provided result + public func resolve(_ result: Swift.Result) { + switch result { + case .failure(let error): self.reject(error) + case .success(let value): self.fulfill(value) + } + } +} +#endif + +public enum Result { + case fulfilled(T) + case rejected(Error) +} + +public extension PromiseKit.Result { + var isFulfilled: Bool { + switch self { + case .fulfilled: + return true + case .rejected: + return false + } + } +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Thenable.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Thenable.swift new file mode 100644 index 000000000..7d88ea6e8 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/Thenable.swift @@ -0,0 +1,533 @@ +import Dispatch + +/// Thenable represents an asynchronous operation that can be chained. +public protocol Thenable: AnyObject { + /// The type of the wrapped value + associatedtype T + + /// `pipe` is immediately executed when this `Thenable` is resolved + func pipe(to: @escaping(Result) -> Void) + + /// The resolved result or nil if pending. + var result: Result? { get } +} + +public extension Thenable { + /** + The provided closure executes when this promise is fulfilled. + + This allows chaining promises. The promise returned by the provided closure is resolved before the promise returned by this closure resolves. + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter body: The closure that executes when this promise is fulfilled. It must return a promise. + - Returns: A new promise that resolves when the promise returned from the provided closure resolves. For example: + + firstly { + URLSession.shared.dataTask(.promise, with: url1) + }.then { response in + transform(data: response.data) + }.done { transformation in + //… + } + */ + func then(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(T) throws -> U) -> Promise { + let rp = Promise(.pending) + pipe { + switch $0 { + case .fulfilled(let value): + on.async(flags: flags) { + do { + let rv = try body(value) + guard rv !== rp else { throw PMKError.returnedSelf } + rv.pipe(to: rp.box.seal) + } catch { + rp.box.seal(.rejected(error)) + } + } + case .rejected(let error): + rp.box.seal(.rejected(error)) + } + } + return rp + } + + /** + The provided closure is executed when this promise is fulfilled. + + This is like `then` but it requires the closure to return a non-promise. + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter transform: The closure that is executed when this Promise is fulfilled. It must return a non-promise. + - Returns: A new promise that is fulfilled with the value returned from the provided closure or rejected if the provided closure throws. For example: + + firstly { + URLSession.shared.dataTask(.promise, with: url1) + }.map { response in + response.data.length + }.done { length in + //… + } + */ + func map(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T) throws -> U) -> Promise { + let rp = Promise(.pending) + pipe { + switch $0 { + case .fulfilled(let value): + on.async(flags: flags) { + do { + rp.box.seal(.fulfilled(try transform(value))) + } catch { + rp.box.seal(.rejected(error)) + } + } + case .rejected(let error): + rp.box.seal(.rejected(error)) + } + } + return rp + } + + #if swift(>=4) && !swift(>=5.2) + /** + Similar to func `map(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T) throws -> U) -> Promise`, but accepts a key path instead of a closure. + + - Parameter on: The queue to which the provided key path for value dispatches. + - Parameter keyPath: The key path to the value that is using when this Promise is fulfilled. + - Returns: A new promise that is fulfilled with the value for the provided key path. + */ + func map(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ keyPath: KeyPath) -> Promise { + let rp = Promise(.pending) + pipe { + switch $0 { + case .fulfilled(let value): + on.async(flags: flags) { + rp.box.seal(.fulfilled(value[keyPath: keyPath])) + } + case .rejected(let error): + rp.box.seal(.rejected(error)) + } + } + return rp + } + #endif + + /** + The provided closure is executed when this promise is fulfilled. + + In your closure return an `Optional`, if you return `nil` the resulting promise is rejected with `PMKError.compactMap`, otherwise the promise is fulfilled with the unwrapped value. + + firstly { + URLSession.shared.dataTask(.promise, with: url) + }.compactMap { + try JSONSerialization.jsonObject(with: $0.data) as? [String: String] + }.done { dictionary in + //… + }.catch { + // either `PMKError.compactMap` or a `JSONError` + } + */ + func compactMap(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T) throws -> U?) -> Promise { + let rp = Promise(.pending) + pipe { + switch $0 { + case .fulfilled(let value): + on.async(flags: flags) { + do { + if let rv = try transform(value) { + rp.box.seal(.fulfilled(rv)) + } else { + throw PMKError.compactMap(value, U.self) + } + } catch { + rp.box.seal(.rejected(error)) + } + } + case .rejected(let error): + rp.box.seal(.rejected(error)) + } + } + return rp + } + + #if swift(>=4) && !swift(>=5.2) + /** + Similar to func `compactMap(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T) throws -> U?) -> Promise`, but accepts a key path instead of a closure. + + - Parameter on: The queue to which the provided key path for value dispatches. + - Parameter keyPath: The key path to the value that is using when this Promise is fulfilled. If the value for `keyPath` is `nil` the resulting promise is rejected with `PMKError.compactMap`. + - Returns: A new promise that is fulfilled with the value for the provided key path. + */ + func compactMap(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ keyPath: KeyPath) -> Promise { + let rp = Promise(.pending) + pipe { + switch $0 { + case .fulfilled(let value): + on.async(flags: flags) { + do { + if let rv = value[keyPath: keyPath] { + rp.box.seal(.fulfilled(rv)) + } else { + throw PMKError.compactMap(value, U.self) + } + } catch { + rp.box.seal(.rejected(error)) + } + } + case .rejected(let error): + rp.box.seal(.rejected(error)) + } + } + return rp + } + #endif + + /** + The provided closure is executed when this promise is fulfilled. + + Equivalent to `map { x -> Void in`, but since we force the `Void` return Swift + is happier and gives you less hassle about your closure’s qualification. + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter body: The closure that is executed when this Promise is fulfilled. + - Returns: A new promise fulfilled as `Void` or rejected if the provided closure throws. + + firstly { + URLSession.shared.dataTask(.promise, with: url) + }.done { response in + print(response.data) + } + */ + func done(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(T) throws -> Void) -> Promise { + let rp = Promise(.pending) + pipe { + switch $0 { + case .fulfilled(let value): + on.async(flags: flags) { + do { + try body(value) + rp.box.seal(.fulfilled(())) + } catch { + rp.box.seal(.rejected(error)) + } + } + case .rejected(let error): + rp.box.seal(.rejected(error)) + } + } + return rp + } + + /** + The provided closure is executed when this promise is fulfilled. + + This is like `done` but it returns the same value that the handler is fed. + `get` immutably accesses the fulfilled value; the returned Promise maintains that value. + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter body: The closure that is executed when this Promise is fulfilled. + - Returns: A new promise that is fulfilled with the value that the handler is fed or rejected if the provided closure throws. For example: + + firstly { + .value(1) + }.get { foo in + print(foo, " is 1") + }.done { foo in + print(foo, " is 1") + }.done { foo in + print(foo, " is Void") + } + */ + func get(on: DispatchQueue? = conf.Q.return, flags: DispatchWorkItemFlags? = nil, _ body: @escaping (T) throws -> Void) -> Promise { + return map(on: on, flags: flags) { + try body($0) + return $0 + } + } + + /** + The provided closure is executed with promise result. + + This is like `get` but provides the Result of the Promise so you can inspect the value of the chain at this point without causing any side effects. + + - Parameter on: The queue to which the provided closure dispatches. + - Parameter body: The closure that is executed with Result of Promise. + - Returns: A new promise that is resolved with the result that the handler is fed. For example: + + promise.tap{ print($0) }.then{ /*…*/ } + */ + func tap(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ body: @escaping(Result) -> Void) -> Promise { + return Promise { seal in + pipe { result in + on.async(flags: flags) { + body(result) + seal.resolve(result) + } + } + } + } + + /// - Returns: a new promise chained off this promise but with its value discarded. + func asVoid() -> Promise { + return map(on: nil) { _ in } + } +} + +public extension Thenable { + /** + - Returns: The error with which this promise was rejected; `nil` if this promise is not rejected. + */ + var error: Error? { + switch result { + case .none: + return nil + case .some(.fulfilled): + return nil + case .some(.rejected(let error)): + return error + } + } + + /** + - Returns: `true` if the promise has not yet resolved. + */ + var isPending: Bool { + return result == nil + } + + /** + - Returns: `true` if the promise has resolved. + */ + var isResolved: Bool { + return !isPending + } + + /** + - Returns: `true` if the promise was fulfilled. + */ + var isFulfilled: Bool { + return value != nil + } + + /** + - Returns: `true` if the promise was rejected. + */ + var isRejected: Bool { + return error != nil + } + + /** + - Returns: The value with which this promise was fulfilled or `nil` if this promise is pending or rejected. + */ + var value: T? { + switch result { + case .none: + return nil + case .some(.fulfilled(let value)): + return value + case .some(.rejected): + return nil + } + } +} + +public extension Thenable where T: Sequence { + /** + `Promise<[T]>` => `T` -> `U` => `Promise<[U]>` + + firstly { + .value([1,2,3]) + }.mapValues { integer in + integer * 2 + }.done { + // $0 => [2,4,6] + } + */ + func mapValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) throws -> U) -> Promise<[U]> { + return map(on: on, flags: flags){ try $0.map(transform) } + } + + #if swift(>=4) && !swift(>=5.2) + /** + `Promise<[T]>` => `KeyPath` => `Promise<[U]>` + + firstly { + .value([Person(name: "Max"), Person(name: "Roman"), Person(name: "John")]) + }.mapValues(\.name).done { + // $0 => ["Max", "Roman", "John"] + } + */ + func mapValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ keyPath: KeyPath) -> Promise<[U]> { + return map(on: on, flags: flags){ $0.map { $0[keyPath: keyPath] } } + } + #endif + + /** + `Promise<[T]>` => `T` -> `[U]` => `Promise<[U]>` + + firstly { + .value([1,2,3]) + }.flatMapValues { integer in + [integer, integer] + }.done { + // $0 => [1,1,2,2,3,3] + } + */ + func flatMapValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) throws -> U) -> Promise<[U.Iterator.Element]> { + return map(on: on, flags: flags){ (foo: T) in + try foo.flatMap{ try transform($0) } + } + } + + /** + `Promise<[T]>` => `T` -> `U?` => `Promise<[U]>` + + firstly { + .value(["1","2","a","3"]) + }.compactMapValues { + Int($0) + }.done { + // $0 => [1,2,3] + } + */ + func compactMapValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) throws -> U?) -> Promise<[U]> { + return map(on: on, flags: flags) { foo -> [U] in + #if !swift(>=3.3) || (swift(>=4) && !swift(>=4.1)) + return try foo.flatMap(transform) + #else + return try foo.compactMap(transform) + #endif + } + } + + #if swift(>=4) && !swift(>=5.2) + /** + `Promise<[T]>` => `KeyPath` => `Promise<[U]>` + + firstly { + .value([Person(name: "Max"), Person(name: "Roman", age: 26), Person(name: "John", age: 23)]) + }.compactMapValues(\.age).done { + // $0 => [26, 23] + } + */ + func compactMapValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ keyPath: KeyPath) -> Promise<[U]> { + return map(on: on, flags: flags) { foo -> [U] in + #if !swift(>=4.1) + return foo.flatMap { $0[keyPath: keyPath] } + #else + return foo.compactMap { $0[keyPath: keyPath] } + #endif + } + } + #endif + + /** + `Promise<[T]>` => `T` -> `Promise` => `Promise<[U]>` + + firstly { + .value([1,2,3]) + }.thenMap { integer in + .value(integer * 2) + }.done { + // $0 => [2,4,6] + } + */ + func thenMap(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) throws -> U) -> Promise<[U.T]> { + return then(on: on, flags: flags) { + when(fulfilled: try $0.map(transform)) + } + } + + /** + `Promise<[T]>` => `T` -> `Promise<[U]>` => `Promise<[U]>` + + firstly { + .value([1,2,3]) + }.thenFlatMap { integer in + .value([integer, integer]) + }.done { + // $0 => [1,1,2,2,3,3] + } + */ + func thenFlatMap(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ transform: @escaping(T.Iterator.Element) throws -> U) -> Promise<[U.T.Iterator.Element]> where U.T: Sequence { + return then(on: on, flags: flags) { + when(fulfilled: try $0.map(transform)) + }.map(on: nil) { + $0.flatMap{ $0 } + } + } + + /** + `Promise<[T]>` => `T` -> Bool => `Promise<[T]>` + + firstly { + .value([1,2,3]) + }.filterValues { + $0 > 1 + }.done { + // $0 => [2,3] + } + */ + func filterValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ isIncluded: @escaping (T.Iterator.Element) -> Bool) -> Promise<[T.Iterator.Element]> { + return map(on: on, flags: flags) { + $0.filter(isIncluded) + } + } + + #if swift(>=4) && !swift(>=5.2) + /** + `Promise<[T]>` => `KeyPath` => `Promise<[T]>` + + firstly { + .value([Person(name: "Max"), Person(name: "Roman", age: 26, isStudent: false), Person(name: "John", age: 23, isStudent: true)]) + }.filterValues(\.isStudent).done { + // $0 => [Person(name: "John", age: 23, isStudent: true)] + } + */ + func filterValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, _ keyPath: KeyPath) -> Promise<[T.Iterator.Element]> { + return map(on: on, flags: flags) { + $0.filter { $0[keyPath: keyPath] } + } + } + #endif +} + +public extension Thenable where T: Collection { + /// - Returns: a promise fulfilled with the first value of this `Collection` or, if empty, a promise rejected with PMKError.emptySequence. + var firstValue: Promise { + return map(on: nil) { aa in + if let a1 = aa.first { + return a1 + } else { + throw PMKError.emptySequence + } + } + } + + func firstValue(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil, where test: @escaping (T.Iterator.Element) -> Bool) -> Promise { + return map(on: on, flags: flags) { + for x in $0 where test(x) { + return x + } + throw PMKError.emptySequence + } + } + + /// - Returns: a promise fulfilled with the last value of this `Collection` or, if empty, a promise rejected with PMKError.emptySequence. + var lastValue: Promise { + return map(on: nil) { aa in + if aa.isEmpty { + throw PMKError.emptySequence + } else { + let i = aa.index(aa.endIndex, offsetBy: -1) + return aa[i] + } + } + } +} + +public extension Thenable where T: Sequence, T.Iterator.Element: Comparable { + /// - Returns: a promise fulfilled with the sorted values of this `Sequence`. + func sortedValues(on: DispatchQueue? = conf.Q.map, flags: DispatchWorkItemFlags? = nil) -> Promise<[T.Iterator.Element]> { + return map(on: on, flags: flags){ $0.sorted() } + } +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/after.m b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/after.m new file mode 100644 index 000000000..25f9966fc --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/after.m @@ -0,0 +1,14 @@ +#import "AnyPromise.h" +@import Dispatch; +@import Foundation.NSDate; +@import Foundation.NSValue; + +/// @return A promise that fulfills after the specified duration. +AnyPromise *PMKAfter(NSTimeInterval duration) { + return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { + dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)); + dispatch_after(time, dispatch_get_global_queue(0, 0), ^{ + resolve(@(duration)); + }); + }]; +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/after.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/after.swift new file mode 100644 index 000000000..cdaeccd9e --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/after.swift @@ -0,0 +1,46 @@ +import struct Foundation.TimeInterval +import Dispatch + +/** + after(seconds: 1.5).then { + //… + } + +- Returns: A guarantee that resolves after the specified duration. +*/ +public func after(seconds: TimeInterval) -> Guarantee { + let (rg, seal) = Guarantee.pending() + let when = DispatchTime.now() + seconds +#if swift(>=4.0) + q.asyncAfter(deadline: when) { seal(()) } +#else + q.asyncAfter(deadline: when, execute: seal) +#endif + return rg +} + +/** + after(.seconds(2)).then { + //… + } + + - Returns: A guarantee that resolves after the specified duration. +*/ +public func after(_ interval: DispatchTimeInterval) -> Guarantee { + let (rg, seal) = Guarantee.pending() + let when = DispatchTime.now() + interval +#if swift(>=4.0) + q.asyncAfter(deadline: when) { seal(()) } +#else + q.asyncAfter(deadline: when, execute: seal) +#endif + return rg +} + +private var q: DispatchQueue { + if #available(macOS 10.10, iOS 8.0, tvOS 9.0, watchOS 2.0, *) { + return DispatchQueue.global(qos: .default) + } else { + return DispatchQueue.global(priority: .default) + } +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/dispatch_promise.m b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/dispatch_promise.m new file mode 100644 index 000000000..ecb89f711 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/dispatch_promise.m @@ -0,0 +1,10 @@ +#import "AnyPromise.h" +@import Dispatch; + +AnyPromise *dispatch_promise_on(dispatch_queue_t queue, id block) { + return [AnyPromise promiseWithValue:nil].thenOn(queue, block); +} + +AnyPromise *dispatch_promise(id block) { + return dispatch_promise_on(dispatch_get_global_queue(0, 0), block); +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/firstly.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/firstly.swift new file mode 100644 index 000000000..4bfc03858 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/firstly.swift @@ -0,0 +1,39 @@ +import Dispatch + +/** + Judicious use of `firstly` *may* make chains more readable. + + Compare: + + URLSession.shared.dataTask(url: url1).then { + URLSession.shared.dataTask(url: url2) + }.then { + URLSession.shared.dataTask(url: url3) + } + + With: + + firstly { + URLSession.shared.dataTask(url: url1) + }.then { + URLSession.shared.dataTask(url: url2) + }.then { + URLSession.shared.dataTask(url: url3) + } + + - Note: the block you pass executes immediately on the current thread/queue. + */ +public func firstly(execute body: () throws -> U) -> Promise { + do { + let rp = Promise(.pending) + try body().pipe(to: rp.box.seal) + return rp + } catch { + return Promise(error: error) + } +} + +/// - See: firstly() +public func firstly(execute body: () -> Guarantee) -> Guarantee { + return body() +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/fwd.h b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/fwd.h new file mode 100644 index 000000000..480d1480e --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/fwd.h @@ -0,0 +1,165 @@ +#import +#import + +@class AnyPromise; +extern NSString * __nonnull const PMKErrorDomain; + +#define PMKFailingPromiseIndexKey @"PMKFailingPromiseIndexKey" +#define PMKJoinPromisesKey @"PMKJoinPromisesKey" + +#define PMKUnexpectedError 1l +#define PMKInvalidUsageError 3l +#define PMKAccessDeniedError 4l +#define PMKOperationFailed 8l +#define PMKTaskError 9l +#define PMKJoinError 10l + + +#ifdef __cplusplus +extern "C" { +#endif + +/** + @return A new promise that resolves after the specified duration. + + @parameter duration The duration in seconds to wait before this promise is resolve. + + For example: + + PMKAfter(1).then(^{ + //… + }); +*/ +extern AnyPromise * __nonnull PMKAfter(NSTimeInterval duration) NS_REFINED_FOR_SWIFT; + + + +/** + `when` is a mechanism for waiting more than one asynchronous task and responding when they are all complete. + + `PMKWhen` accepts varied input. If an array is passed then when those promises fulfill, when’s promise fulfills with an array of fulfillment values. If a dictionary is passed then the same occurs, but when’s promise fulfills with a dictionary of fulfillments keyed as per the input. + + Interestingly, if a single promise is passed then when waits on that single promise, and if a single non-promise object is passed then when fulfills immediately with that object. If the array or dictionary that is passed contains objects that are not promises, then these objects are considered fulfilled promises. The reason we do this is to allow a pattern know as "abstracting away asynchronicity". + + If *any* of the provided promises reject, the returned promise is immediately rejected with that promise’s rejection. The error’s `userInfo` object is supplemented with `PMKFailingPromiseIndexKey`. + + For example: + + PMKWhen(@[promise1, promise2]).then(^(NSArray *results){ + //… + }); + + @warning *Important* In the event of rejection the other promises will continue to resolve and as per any other promise will either fulfill or reject. This is the right pattern for `getter` style asynchronous tasks, but often for `setter` tasks (eg. storing data on a server), you most likely will need to wait on all tasks and then act based on which have succeeded and which have failed. In such situations use `PMKJoin`. + + @param input The input upon which to wait before resolving this promise. + + @return A promise that is resolved with either: + + 1. An array of values from the provided array of promises. + 2. The value from the provided promise. + 3. The provided non-promise object. + + @see PMKJoin + +*/ +extern AnyPromise * __nonnull PMKWhen(id __nonnull input) NS_REFINED_FOR_SWIFT; + + + +/** + Creates a new promise that resolves only when all provided promises have resolved. + + Typically, you should use `PMKWhen`. + + For example: + + PMKJoin(@[promise1, promise2]).then(^(NSArray *resultingValues){ + //… + }).catch(^(NSError *error){ + assert(error.domain == PMKErrorDomain); + assert(error.code == PMKJoinError); + + NSArray *promises = error.userInfo[PMKJoinPromisesKey]; + for (AnyPromise *promise in promises) { + if (promise.rejected) { + //… + } + } + }); + + @param promises An array of promises. + + @return A promise that thens three parameters: + + 1) An array of mixed values and errors from the resolved input. + 2) An array of values from the promises that fulfilled. + 3) An array of errors from the promises that rejected or nil if all promises fulfilled. + + @see when +*/ +AnyPromise *__nonnull PMKJoin(NSArray * __nonnull promises) NS_REFINED_FOR_SWIFT; + + + +/** + Literally hangs this thread until the promise has resolved. + + Do not use hang… unless you are testing, playing or debugging. + + If you use it in production code I will literally and honestly cry like a child. + + @return The resolved value of the promise. + + @warning T SAFE. IT IS NOT SAFE. IT IS NOT SAFE. IT IS NOT SAFE. IT IS NO +*/ +extern id __nullable PMKHang(AnyPromise * __nonnull promise); + + + +/** + Executes the provided block on a background queue. + + dispatch_promise is a convenient way to start a promise chain where the + first step needs to run synchronously on a background queue. + + dispatch_promise(^{ + return md5(input); + }).then(^(NSString *md5){ + NSLog(@"md5: %@", md5); + }); + + @param block The block to be executed in the background. Returning an `NSError` will reject the promise, everything else (including void) fulfills the promise. + + @return A promise resolved with the return value of the provided block. + + @see dispatch_async +*/ +extern AnyPromise * __nonnull dispatch_promise(id __nonnull block) NS_SWIFT_UNAVAILABLE("Use our `DispatchQueue.async` override instead"); + + + +/** + Executes the provided block on the specified background queue. + + dispatch_promise_on(myDispatchQueue, ^{ + return md5(input); + }).then(^(NSString *md5){ + NSLog(@"md5: %@", md5); + }); + + @param block The block to be executed in the background. Returning an `NSError` will reject the promise, everything else (including void) fulfills the promise. + + @return A promise resolved with the return value of the provided block. + + @see dispatch_promise +*/ +extern AnyPromise * __nonnull dispatch_promise_on(dispatch_queue_t __nonnull queue, id __nonnull block) NS_SWIFT_UNAVAILABLE("Use our `DispatchQueue.async` override instead"); + +/** + Returns a new promise that resolves when the value of the first resolved promise in the provided array of promises. +*/ +extern AnyPromise * __nonnull PMKRace(NSArray * __nonnull promises) NS_REFINED_FOR_SWIFT; + +#ifdef __cplusplus +} // Extern C +#endif diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/hang.m b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/hang.m new file mode 100644 index 000000000..913339e51 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/hang.m @@ -0,0 +1,29 @@ +#import "AnyPromise.h" +#import "AnyPromise+Private.h" +@import CoreFoundation.CFRunLoop; + +/** + Suspends the active thread waiting on the provided promise. + + @return The value of the provided promise once resolved. + */ +id PMKHang(AnyPromise *promise) { + if (promise.pending) { + static CFRunLoopSourceContext context; + + CFRunLoopRef runLoop = CFRunLoopGetCurrent(); + CFRunLoopSourceRef runLoopSource = CFRunLoopSourceCreate(NULL, 0, &context); + CFRunLoopAddSource(runLoop, runLoopSource, kCFRunLoopDefaultMode); + + promise.ensure(^{ + CFRunLoopStop(runLoop); + }); + while (promise.pending) { + CFRunLoopRun(); + } + CFRunLoopRemoveSource(runLoop, runLoopSource, kCFRunLoopDefaultMode); + CFRelease(runLoopSource); + } + + return promise.value; +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/hang.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/hang.swift new file mode 100644 index 000000000..1022dcad7 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/hang.swift @@ -0,0 +1,55 @@ +import Foundation +import CoreFoundation + +/** + Runs the active run-loop until the provided promise resolves. + + This is for debug and is not a generally safe function to use in your applications. We mostly provide it for use in testing environments. + + Still if you like, study how it works (by reading the sources!) and use at your own risk. + + - Returns: The value of the resolved promise + - Throws: An error, should the promise be rejected + - See: `wait()` +*/ +public func hang(_ promise: Promise) throws -> T { +#if os(Linux) || os(Android) +#if swift(>=4) + let runLoopMode: CFRunLoopMode = kCFRunLoopDefaultMode +#else + // isMainThread is not yet implemented on Linux. + let runLoopModeRaw = RunLoopMode.defaultRunLoopMode.rawValue._bridgeToObjectiveC() + let runLoopMode: CFString = unsafeBitCast(runLoopModeRaw, to: CFString.self) +#endif +#else + guard Thread.isMainThread else { + // hang doesn't make sense on threads that aren't the main thread. + // use `.wait()` on those threads. + fatalError("Only call hang() on the main thread.") + } + let runLoopMode: CFRunLoopMode = CFRunLoopMode.defaultMode +#endif + + if promise.isPending { + var context = CFRunLoopSourceContext() + let runLoop = CFRunLoopGetCurrent() + let runLoopSource = CFRunLoopSourceCreate(nil, 0, &context) + CFRunLoopAddSource(runLoop, runLoopSource, runLoopMode) + + _ = promise.ensure { + CFRunLoopStop(runLoop) + } + + while promise.isPending { + CFRunLoopRun() + } + CFRunLoopRemoveSource(runLoop, runLoopSource, runLoopMode) + } + + switch promise.result! { + case .rejected(let error): + throw error + case .fulfilled(let value): + return value + } +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/join.m b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/join.m new file mode 100644 index 000000000..979f092df --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/join.m @@ -0,0 +1,54 @@ +@import Foundation.NSDictionary; +#import "AnyPromise+Private.h" +#import +@import Foundation.NSError; +@import Foundation.NSNull; +#import "PromiseKit.h" +#import + +/** + Waits on all provided promises. + + `PMKWhen` rejects as soon as one of the provided promises rejects. `PMKJoin` waits on all provided promises, then rejects if any of those promises rejects, otherwise it fulfills with values from the provided promises. + + - Returns: A new promise that resolves once all the provided promises resolve. +*/ +AnyPromise *PMKJoin(NSArray *promises) { + if (promises == nil) + return [AnyPromise promiseWithValue:[NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:@{NSLocalizedDescriptionKey: @"PMKJoin(nil)"}]]; + + if (promises.count == 0) + return [AnyPromise promiseWithValue:promises]; + + return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { + NSPointerArray *results = NSPointerArrayMake(promises.count); + __block atomic_int countdown = promises.count; + __block BOOL rejected = NO; + + [promises enumerateObjectsUsingBlock:^(AnyPromise *promise, NSUInteger ii, BOOL *stop) { + [promise __pipe:^(id value) { + + if (IsError(value)) { + rejected = YES; + } + + //FIXME surely this isn't thread safe on multiple cores? + [results replacePointerAtIndex:ii withPointer:(__bridge void *)(value ?: [NSNull null])]; + + atomic_fetch_sub_explicit(&countdown, 1, memory_order_relaxed); + + if (countdown == 0) { + if (!rejected) { + resolve(results.allObjects); + } else { + id userInfo = @{PMKJoinPromisesKey: promises}; + id err = [NSError errorWithDomain:PMKErrorDomain code:PMKJoinError userInfo:userInfo]; + resolve(err); + } + } + }]; + + (void) stop; + }]; + }]; +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/race.m b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/race.m new file mode 100644 index 000000000..cab38ec19 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/race.m @@ -0,0 +1,9 @@ +#import "AnyPromise+Private.h" + +AnyPromise *PMKRace(NSArray *promises) { + return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { + for (AnyPromise *promise in promises) { + [promise __pipe:resolve]; + } + }]; +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/race.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/race.swift new file mode 100644 index 000000000..76ae96d06 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/race.swift @@ -0,0 +1,102 @@ +import Dispatch + +@inline(__always) +private func _race(_ thenables: [U]) -> Promise { + let rp = Promise(.pending) + for thenable in thenables { + thenable.pipe(to: rp.box.seal) + } + return rp +} + +/** + Waits for one promise to resolve + + race(promise1, promise2, promise3).then { winner in + //… + } + + - Returns: The promise that resolves first + - Warning: If the first resolution is a rejection, the returned promise is rejected +*/ +public func race(_ thenables: U...) -> Promise { + return _race(thenables) +} + +/** + Waits for one promise to resolve + + race(promise1, promise2, promise3).then { winner in + //… + } + + - Returns: The promise that resolves first + - Warning: If the first resolution is a rejection, the returned promise is rejected + - Remark: If the provided array is empty the returned promise is rejected with PMKError.badInput +*/ +public func race(_ thenables: [U]) -> Promise { + guard !thenables.isEmpty else { + return Promise(error: PMKError.badInput) + } + return _race(thenables) +} + +/** + Waits for one guarantee to resolve + + race(promise1, promise2, promise3).then { winner in + //… + } + + - Returns: The guarantee that resolves first +*/ +public func race(_ guarantees: Guarantee...) -> Guarantee { + let rg = Guarantee(.pending) + for guarantee in guarantees { + guarantee.pipe(to: rg.box.seal) + } + return rg +} + +/** + Waits for one promise to fulfill + + race(fulfilled: [promise1, promise2, promise3]).then { winner in + //… + } + + - Returns: The promise that was fulfilled first. + - Warning: Skips all rejected promises. + - Remark: If the provided array is empty, the returned promise is rejected with `PMKError.badInput`. If there are no fulfilled promises, the returned promise is rejected with `PMKError.noWinner`. +*/ +public func race(fulfilled thenables: [U]) -> Promise { + var countdown = thenables.count + guard countdown > 0 else { + return Promise(error: PMKError.badInput) + } + + let rp = Promise(.pending) + + let barrier = DispatchQueue(label: "org.promisekit.barrier.race", attributes: .concurrent) + + for promise in thenables { + promise.pipe { result in + barrier.sync(flags: .barrier) { + switch result { + case .rejected: + guard rp.isPending else { return } + countdown -= 1 + if countdown == 0 { + rp.box.seal(.rejected(PMKError.noWinner)) + } + case .fulfilled(let value): + guard rp.isPending else { return } + countdown = 0 + rp.box.seal(.fulfilled(value)) + } + } + } + } + + return rp +} diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/when.m b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/when.m new file mode 100644 index 000000000..43e5feddc --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/when.m @@ -0,0 +1,107 @@ +@import Foundation.NSDictionary; +#import "AnyPromise+Private.h" +@import Foundation.NSProgress; +#import +@import Foundation.NSError; +@import Foundation.NSNull; +#import "PromiseKit.h" + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +// ^^ OSAtomicDecrement32 is deprecated on watchOS + + +// NSProgress resources: +// * https://robots.thoughtbot.com/asynchronous-nsprogress +// * http://oleb.net/blog/2014/03/nsprogress/ +// NSProgress! Beware! +// * https://github.com/AFNetworking/AFNetworking/issues/2261 + +/** + Wait for all promises in a set to resolve. + + @note If *any* of the provided promises reject, the returned promise is immediately rejected with that error. + @warning In the event of rejection the other promises will continue to resolve and, as per any other promise, will either fulfill or reject. This is the right pattern for `getter` style asynchronous tasks, but often for `setter` tasks (eg. storing data on a server), you most likely will need to wait on all tasks and then act based on which have succeeded and which have failed, in such situations use `when(resolved:)`. + @param promises The promises upon which to wait before the returned promise resolves. + @note PMKWhen provides NSProgress. + @return A new promise that resolves when all the provided promises fulfill or one of the provided promises rejects. +*/ +AnyPromise *PMKWhen(id promises) { + if (promises == nil) + return [AnyPromise promiseWithValue:[NSError errorWithDomain:PMKErrorDomain code:PMKInvalidUsageError userInfo:@{NSLocalizedDescriptionKey: @"PMKWhen(nil)"}]]; + + if ([promises isKindOfClass:[NSArray class]] || [promises isKindOfClass:[NSDictionary class]]) { + if ([promises count] == 0) + return [AnyPromise promiseWithValue:promises]; + } else if ([promises isKindOfClass:[AnyPromise class]]) { + promises = @[promises]; + } else { + return [AnyPromise promiseWithValue:promises]; + } + +#ifndef PMKDisableProgress + NSProgress *progress = [NSProgress progressWithTotalUnitCount:(int64_t)[promises count]]; + progress.pausable = NO; + progress.cancellable = NO; +#else + struct PMKProgress { + int completedUnitCount; + int totalUnitCount; + double fractionCompleted; + }; + __block struct PMKProgress progress; +#endif + + __block int32_t countdown = (int32_t)[promises count]; + BOOL const isdict = [promises isKindOfClass:[NSDictionary class]]; + + return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { + NSInteger index = 0; + + for (__strong id key in promises) { + AnyPromise *promise = isdict ? promises[key] : key; + if (!isdict) key = @(index); + + if (![promise isKindOfClass:[AnyPromise class]]) + promise = [AnyPromise promiseWithValue:promise]; + + [promise __pipe:^(id value){ + if (progress.fractionCompleted >= 1) + return; + + if (IsError(value)) { + progress.completedUnitCount = progress.totalUnitCount; + + NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:[(NSError *)value userInfo] ?: @{}]; + userInfo[PMKFailingPromiseIndexKey] = key; + [userInfo setObject:value forKey:NSUnderlyingErrorKey]; + id err = [[NSError alloc] initWithDomain:[value domain] code:[value code] userInfo:userInfo]; + resolve(err); + } + else if (OSAtomicDecrement32(&countdown) == 0) { + progress.completedUnitCount = progress.totalUnitCount; + + id results; + if (isdict) { + results = [NSMutableDictionary new]; + for (id key in promises) { + id promise = promises[key]; + results[key] = IsPromise(promise) ? ((AnyPromise *)promise).value : promise; + } + } else { + results = [NSMutableArray new]; + for (AnyPromise *promise in promises) { + id value = IsPromise(promise) ? (promise.value ?: [NSNull null]) : promise; + [results addObject:value]; + } + } + resolve(results); + } else { + progress.completedUnitCount++; + } + }]; + } + }]; +} + +#pragma GCC diagnostic pop diff --git a/Example/myWeb3Wallet/Pods/PromiseKit/Sources/when.swift b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/when.swift new file mode 100644 index 000000000..44335b84f --- /dev/null +++ b/Example/myWeb3Wallet/Pods/PromiseKit/Sources/when.swift @@ -0,0 +1,363 @@ +import Foundation +import Dispatch + +private func _when(_ thenables: [U]) -> Promise { + var countdown = thenables.count + guard countdown > 0 else { + return .value(Void()) + } + + let rp = Promise(.pending) + +#if PMKDisableProgress || os(Linux) + var progress: (completedUnitCount: Int, totalUnitCount: Int) = (0, 0) +#else + let progress = Progress(totalUnitCount: Int64(thenables.count)) + progress.isCancellable = false + progress.isPausable = false +#endif + + let barrier = DispatchQueue(label: "org.promisekit.barrier.when", attributes: .concurrent) + + for promise in thenables { + promise.pipe { result in + barrier.sync(flags: .barrier) { + switch result { + case .rejected(let error): + if rp.isPending { + progress.completedUnitCount = progress.totalUnitCount + rp.box.seal(.rejected(error)) + } + case .fulfilled: + guard rp.isPending else { return } + progress.completedUnitCount += 1 + countdown -= 1 + if countdown == 0 { + rp.box.seal(.fulfilled(())) + } + } + } + } + } + + return rp +} + +/** + Wait for all promises in a set to fulfill. + + For example: + + when(fulfilled: promise1, promise2).then { results in + //… + }.catch { error in + switch error { + case URLError.notConnectedToInternet: + //… + case CLError.denied: + //… + } + } + + - Note: If *any* of the provided promises reject, the returned promise is immediately rejected with that error. + - Warning: In the event of rejection the other promises will continue to resolve and, as per any other promise, will either fulfill or reject. This is the right pattern for `getter` style asynchronous tasks, but often for `setter` tasks (eg. storing data on a server), you most likely will need to wait on all tasks and then act based on which have succeeded and which have failed, in such situations use `when(resolved:)`. + - Parameter promises: The promises upon which to wait before the returned promise resolves. + - Returns: A new promise that resolves when all the provided promises fulfill or one of the provided promises rejects. + - Note: `when` provides `NSProgress`. + - SeeAlso: `when(resolved:)` +*/ +public func when(fulfilled thenables: [U]) -> Promise<[U.T]> { + return _when(thenables).map(on: nil) { thenables.map{ $0.value! } } +} + +/// Wait for all promises in a set to fulfill. +public func when(fulfilled promises: U...) -> Promise where U.T == Void { + return _when(promises) +} + +/// Wait for all promises in a set to fulfill. +public func when(fulfilled promises: [U]) -> Promise where U.T == Void { + return _when(promises) +} + +/// Wait for all promises in a set to fulfill. +public func when(fulfilled pu: U, _ pv: V) -> Promise<(U.T, V.T)> { + return _when([pu.asVoid(), pv.asVoid()]).map(on: nil) { (pu.value!, pv.value!) } +} + +/// Wait for all promises in a set to fulfill. +public func when(fulfilled pu: U, _ pv: V, _ pw: W) -> Promise<(U.T, V.T, W.T)> { + return _when([pu.asVoid(), pv.asVoid(), pw.asVoid()]).map(on: nil) { (pu.value!, pv.value!, pw.value!) } +} + +/// Wait for all promises in a set to fulfill. +public func when(fulfilled pu: U, _ pv: V, _ pw: W, _ px: X) -> Promise<(U.T, V.T, W.T, X.T)> { + return _when([pu.asVoid(), pv.asVoid(), pw.asVoid(), px.asVoid()]).map(on: nil) { (pu.value!, pv.value!, pw.value!, px.value!) } +} + +/// Wait for all promises in a set to fulfill. +public func when(fulfilled pu: U, _ pv: V, _ pw: W, _ px: X, _ py: Y) -> Promise<(U.T, V.T, W.T, X.T, Y.T)> { + return _when([pu.asVoid(), pv.asVoid(), pw.asVoid(), px.asVoid(), py.asVoid()]).map(on: nil) { (pu.value!, pv.value!, pw.value!, px.value!, py.value!) } +} + +/** + Generate promises at a limited rate and wait for all to fulfill. + + For example: + + func downloadFile(url: URL) -> Promise { + // ... + } + + let urls: [URL] = /*…*/ + let urlGenerator = urls.makeIterator() + + let generator = AnyIterator> { + guard url = urlGenerator.next() else { + return nil + } + return downloadFile(url) + } + + when(generator, concurrently: 3).done { datas in + // ... + } + + No more than three downloads will occur simultaneously. + + - Note: The generator is called *serially* on a *background* queue. + - Warning: Refer to the warnings on `when(fulfilled:)` + - Parameter promiseGenerator: Generator of promises. + - Returns: A new promise that resolves when all the provided promises fulfill or one of the provided promises rejects. + - SeeAlso: `when(resolved:)` + */ + +public func when(fulfilled promiseIterator: It, concurrently: Int) -> Promise<[It.Element.T]> where It.Element: Thenable { + + guard concurrently > 0 else { + return Promise(error: PMKError.badInput) + } + + var generator = promiseIterator + let root = Promise<[It.Element.T]>.pending() + var pendingPromises = 0 + var promises: [It.Element] = [] + + let barrier = DispatchQueue(label: "org.promisekit.barrier.when", attributes: [.concurrent]) + + func dequeue() { + guard root.promise.isPending else { return } // don’t continue dequeueing if root has been rejected + + var shouldDequeue = false + barrier.sync { + shouldDequeue = pendingPromises < concurrently + } + guard shouldDequeue else { return } + + var promise: It.Element! + + barrier.sync(flags: .barrier) { + guard let next = generator.next() else { return } + promise = next + pendingPromises += 1 + promises.append(next) + } + + func testDone() { + barrier.sync { + if pendingPromises == 0 { + #if !swift(>=3.3) || (swift(>=4) && !swift(>=4.1)) + root.resolver.fulfill(promises.flatMap{ $0.value }) + #else + root.resolver.fulfill(promises.compactMap{ $0.value }) + #endif + } + } + } + + guard promise != nil else { + return testDone() + } + + promise.pipe { resolution in + barrier.sync(flags: .barrier) { + pendingPromises -= 1 + } + + switch resolution { + case .fulfilled: + dequeue() + testDone() + case .rejected(let error): + root.resolver.reject(error) + } + } + + dequeue() + } + + dequeue() + + return root.promise +} + +/** + Waits on all provided promises. + + `when(fulfilled:)` rejects as soon as one of the provided promises rejects. `when(resolved:)` waits on all provided promises whatever their result, and then provides an array of `Result` so you can individually inspect the results. As a consequence this function returns a `Guarantee`, ie. errors are lifted from the individual promises into the results array of the returned `Guarantee`. + + when(resolved: promise1, promise2, promise3).then { results in + for result in results where case .fulfilled(let value) { + //… + } + }.catch { error in + // invalid! Never rejects + } + + - Returns: A new promise that resolves once all the provided promises resolve. The array is ordered the same as the input, ie. the result order is *not* resolution order. + - Note: we do not provide tuple variants for `when(resolved:)` but will accept a pull-request + - Remark: Doesn't take Thenable due to protocol `associatedtype` paradox +*/ +public func when(resolved promises: Promise...) -> Guarantee<[Result]> { + return when(resolved: promises) +} + +/// - See: `when(resolved: Promise...)` +public func when(resolved promises: [Promise]) -> Guarantee<[Result]> { + guard !promises.isEmpty else { + return .value([]) + } + + var countdown = promises.count + let barrier = DispatchQueue(label: "org.promisekit.barrier.join", attributes: .concurrent) + + let rg = Guarantee<[Result]>(.pending) + for promise in promises { + promise.pipe { result in + barrier.sync(flags: .barrier) { + countdown -= 1 + } + barrier.sync { + if countdown == 0 { + rg.box.seal(promises.map{ $0.result! }) + } + } + } + } + return rg +} + +/** +Generate promises at a limited rate and wait for all to resolve. + +For example: + + func downloadFile(url: URL) -> Promise { + // ... + } + + let urls: [URL] = /*…*/ + let urlGenerator = urls.makeIterator() + + let generator = AnyIterator> { + guard url = urlGenerator.next() else { + return nil + } + return downloadFile(url) + } + + when(resolved: generator, concurrently: 3).done { results in + // ... + } + +No more than three downloads will occur simultaneously. Downloads will continue if one of them fails + +- Note: The generator is called *serially* on a *background* queue. +- Warning: Refer to the warnings on `when(resolved:)` +- Parameter promiseGenerator: Generator of promises. +- Returns: A new promise that resolves once all the provided promises resolve. The array is ordered the same as the input, ie. the result order is *not* resolution order. +- SeeAlso: `when(resolved:)` +*/ +#if swift(>=5.3) +public func when(resolved promiseIterator: It, concurrently: Int) + -> Guarantee<[Result]> where It.Element: Thenable { + guard concurrently > 0 else { + return Guarantee.value([Result.rejected(PMKError.badInput)]) + } + + var generator = promiseIterator + let root = Guarantee<[Result]>.pending() + var pendingPromises = 0 + var promises: [It.Element] = [] + + let barrier = DispatchQueue(label: "org.promisekit.barrier.when", attributes: [.concurrent]) + + func dequeue() { + guard root.guarantee.isPending else { + return + } // don’t continue dequeueing if root has been rejected + + var shouldDequeue = false + barrier.sync { + shouldDequeue = pendingPromises < concurrently + } + guard shouldDequeue else { + return + } + + var promise: It.Element! + + barrier.sync(flags: .barrier) { + guard let next = generator.next() else { + return + } + + promise = next + + pendingPromises += 1 + promises.append(next) + } + + func testDone() { + barrier.sync { + if pendingPromises == 0 { + #if !swift(>=3.3) || (swift(>=4) && !swift(>=4.1)) + root.resolve(promises.flatMap { $0.result }) + #else + root.resolve(promises.compactMap { $0.result }) + #endif + } + } + } + + guard promise != nil else { + return testDone() + } + + promise.pipe { _ in + barrier.sync(flags: .barrier) { + pendingPromises -= 1 + } + + dequeue() + testDone() + } + + dequeue() + } + + dequeue() + + return root.guarantee +} +#endif + +/// Waits on all provided Guarantees. +public func when(_ guarantees: Guarantee...) -> Guarantee { + return when(guarantees: guarantees) +} + +// Waits on all provided Guarantees. +public func when(guarantees: [Guarantee]) -> Guarantee { + return when(fulfilled: guarantees).recover{ _ in }.asVoid() +} diff --git a/Example/myWeb3Wallet/Pods/Starscream/LICENSE b/Example/myWeb3Wallet/Pods/Starscream/LICENSE new file mode 100644 index 000000000..d6ab2f1f7 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Starscream/LICENSE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + Copyright (c) 2014-2016 Dalton Cherry. + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. \ No newline at end of file diff --git a/Example/myWeb3Wallet/Pods/Starscream/README.md b/Example/myWeb3Wallet/Pods/Starscream/README.md new file mode 100644 index 000000000..634723aa3 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Starscream/README.md @@ -0,0 +1,308 @@ +![starscream](https://raw.githubusercontent.com/daltoniam/starscream/assets/starscream.jpg) + +Starscream is a conforming WebSocket ([RFC 6455](http://tools.ietf.org/html/rfc6455)) library in Swift. + +## Features + +- Conforms to all of the base [Autobahn test suite](https://crossbar.io/autobahn/). +- Nonblocking. Everything happens in the background, thanks to GCD. +- TLS/WSS support. +- Compression Extensions support ([RFC 7692](https://tools.ietf.org/html/rfc7692)) + +### Import the framework + +First thing is to import the framework. See the Installation instructions on how to add the framework to your project. + +```swift +import Starscream +``` + +### Connect to the WebSocket Server + +Once imported, you can open a connection to your WebSocket server. Note that `socket` is probably best as a property, so it doesn't get deallocated right after being setup. + +```swift +var request = URLRequest(url: URL(string: "http://localhost:8080")!) +request.timeoutInterval = 5 +socket = WebSocket(request: request) +socket.delegate = self +socket.connect() +``` + +After you are connected, there is either a delegate or closure you can use for process WebSocket events. + +### Receiving data from a WebSocket + +`didReceive` receives all the WebSocket events in a single easy to handle enum. + +```swift +func didReceive(event: WebSocketEvent, client: WebSocket) { + switch event { + case .connected(let headers): + isConnected = true + print("websocket is connected: \(headers)") + case .disconnected(let reason, let code): + isConnected = false + print("websocket is disconnected: \(reason) with code: \(code)") + case .text(let string): + print("Received text: \(string)") + case .binary(let data): + print("Received data: \(data.count)") + case .ping(_): + break + case .pong(_): + break + case .viabilityChanged(_): + break + case .reconnectSuggested(_): + break + case .cancelled: + isConnected = false + case .error(let error): + isConnected = false + handleError(error) + } +} +``` + +The closure of this would be: + +```swift +socket.onEvent = { event in + switch event { + // handle events just like above... + } +} +``` + +### Writing to a WebSocket + +### write a binary frame + +The writeData method gives you a simple way to send `Data` (binary) data to the server. + +```swift +socket.write(data: data) //write some Data over the socket! +``` + +### write a string frame + +The writeString method is the same as writeData, but sends text/string. + +```swift +socket.write(string: "Hi Server!") //example on how to write text over the socket! +``` + +### write a ping frame + +The writePing method is the same as write, but sends a ping control frame. + +```swift +socket.write(ping: Data()) //example on how to write a ping control frame over the socket! +``` + +### write a pong frame + + +the writePong method is the same as writePing, but sends a pong control frame. + +```swift +socket.write(pong: Data()) //example on how to write a pong control frame over the socket! +``` + +Starscream will automatically respond to incoming `ping` control frames so you do not need to manually send `pong`s. + +However if for some reason you need to control this process you can turn off the automatic `ping` response by disabling `respondToPingWithPong`. + +```swift +socket.respondToPingWithPong = false //Do not automaticaly respond to incoming pings with pongs. +``` + +In most cases you will not need to do this. + +### disconnect + +The disconnect method does what you would expect and closes the socket. + +```swift +socket.disconnect() +``` + +The disconnect method can also send a custom close code if desired. + +```swift +socket.disconnect(closeCode: CloseCode.normal.rawValue) +``` + +### Custom Headers, Protocols and Timeout + +You can override the default websocket headers, add your own custom ones and set a timeout: + +```swift +var request = URLRequest(url: URL(string: "ws://localhost:8080/")!) +request.timeoutInterval = 5 // Sets the timeout for the connection +request.setValue("someother protocols", forHTTPHeaderField: "Sec-WebSocket-Protocol") +request.setValue("14", forHTTPHeaderField: "Sec-WebSocket-Version") +request.setValue("chat,superchat", forHTTPHeaderField: "Sec-WebSocket-Protocol") +request.setValue("Everything is Awesome!", forHTTPHeaderField: "My-Awesome-Header") +let socket = WebSocket(request: request) +``` + +### SSL Pinning + +SSL Pinning is also supported in Starscream. + + +Allow Self-signed certificates: + +```swift +var request = URLRequest(url: URL(string: "ws://localhost:8080/")!) +let pinner = FoundationSecurity(allowSelfSigned: true) // don't validate SSL certificates +let socket = WebSocket(request: request, certPinner: pinner) +``` + +TODO: Update docs on how to load certificates and public keys into an app bundle, use the builtin pinner and TrustKit. + +### Compression Extensions + +Compression Extensions ([RFC 7692](https://tools.ietf.org/html/rfc7692)) is supported in Starscream. Compression is enabled by default, however compression will only be used if it is supported by the server as well. You may enable or disable compression via the `.enableCompression` property: + +```swift +var request = URLRequest(url: URL(string: "ws://localhost:8080/")!) +let compression = WSCompression() +let socket = WebSocket(request: request, compressionHandler: compression) +``` + +Compression should be disabled if your application is transmitting already-compressed, random, or other uncompressable data. + +### Custom Queue + +A custom queue can be specified when delegate methods are called. By default `DispatchQueue.main` is used, thus making all delegate methods calls run on the main thread. It is important to note that all WebSocket processing is done on a background thread, only the delegate method calls are changed when modifying the queue. The actual processing is always on a background thread and will not pause your app. + +```swift +socket = WebSocket(url: URL(string: "ws://localhost:8080/")!, protocols: ["chat","superchat"]) +//create a custom queue +socket.callbackQueue = DispatchQueue(label: "com.vluxe.starscream.myapp") +``` + +## Example Project + +Check out the SimpleTest project in the examples directory to see how to setup a simple connection to a WebSocket server. + +## Requirements + +Starscream works with iOS 8/10.10 or above for CocoaPods/framework support. To use Starscream with a project targeting iOS 7, you must include all Swift files directly in your project. + +## Installation + +### CocoaPods + +Check out [Get Started](http://cocoapods.org/) tab on [cocoapods.org](http://cocoapods.org/). + +To use Starscream in your project add the following 'Podfile' to your project + + source 'https://github.com/CocoaPods/Specs.git' + platform :ios, '9.0' + use_frameworks! + + pod 'Starscream', '~> 4.0.0' + +Then run: + + pod install + +### Carthage + +Check out the [Carthage](https://github.com/Carthage/Carthage) docs on how to add a install. The `Starscream` framework is already setup with shared schemes. + +[Carthage Install](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application) + +You can install Carthage with [Homebrew](http://brew.sh/) using the following command: + +```bash +$ brew update +$ brew install carthage +``` + +To integrate Starscream into your Xcode project using Carthage, specify it in your `Cartfile`: + +``` +github "daltoniam/Starscream" >= 4.0.0 +``` + +### Accio + +Check out the [Accio](https://github.com/JamitLabs/Accio) docs on how to add a install. + +Add the following to your Package.swift: + +```swift +.package(url: "https://github.com/daltoniam/Starscream.git", .upToNextMajor(from: "4.0.0")), +``` + +Next, add `Starscream` to your App targets dependencies like so: + +```swift +.target( + name: "App", + dependencies: [ + "Starscream", + ] +), +``` + +Then run `accio update`. + +### Rogue + +First see the [installation docs](https://github.com/acmacalister/Rogue) for how to install Rogue. + +To install Starscream run the command below in the directory you created the rogue file. + +``` +rogue add https://github.com/daltoniam/Starscream +``` + +Next open the `libs` folder and add the `Starscream.xcodeproj` to your Xcode project. Once that is complete, in your "Build Phases" add the `Starscream.framework` to your "Link Binary with Libraries" phase. Make sure to add the `libs` folder to your `.gitignore` file. + +### Swift Package Manager + +The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. + +Once you have your Swift package set up, adding Starscream as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. + +```swift +dependencies: [ + .Package(url: "https://github.com/daltoniam/Starscream.git", majorVersion: 4) +] +``` + +### Other + +Simply grab the framework (either via git submodule or another package manager). + +Add the `Starscream.xcodeproj` to your Xcode project. Once that is complete, in your "Build Phases" add the `Starscream.framework` to your "Link Binary with Libraries" phase. + +### Add Copy Frameworks Phase + +If you are running this in an OSX app or on a physical iOS device you will need to make sure you add the `Starscream.framework` to be included in your app bundle. To do this, in Xcode, navigate to the target configuration window by clicking on the blue project icon, and selecting the application target under the "Targets" heading in the sidebar. In the tab bar at the top of that window, open the "Build Phases" panel. Expand the "Link Binary with Libraries" group, and add `Starscream.framework`. Click on the + button at the top left of the panel and select "New Copy Files Phase". Rename this new phase to "Copy Frameworks", set the "Destination" to "Frameworks", and add `Starscream.framework` respectively. + +## TODOs + +- [ ] Proxy support + +## License + +Starscream is licensed under the Apache v2 License. + +## Contact + +### Dalton Cherry +* https://github.com/daltoniam +* http://twitter.com/daltoniam +* http://daltoniam.com + +### Austin Cherry ### +* https://github.com/acmacalister +* http://twitter.com/acmacalister +* http://austincherry.me diff --git a/Example/myWeb3Wallet/Pods/Starscream/Sources/Compression/Compression.swift b/Example/myWeb3Wallet/Pods/Starscream/Sources/Compression/Compression.swift new file mode 100644 index 000000000..0e7fae5aa --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Starscream/Sources/Compression/Compression.swift @@ -0,0 +1,29 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Compression.swift +// Starscream +// +// Created by Dalton Cherry on 2/4/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation + +public protocol CompressionHandler { + func load(headers: [String: String]) + func decompress(data: Data, isFinal: Bool) -> Data? + func compress(data: Data) -> Data? +} diff --git a/Example/myWeb3Wallet/Pods/Starscream/Sources/Compression/WSCompression.swift b/Example/myWeb3Wallet/Pods/Starscream/Sources/Compression/WSCompression.swift new file mode 100644 index 000000000..212958417 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Starscream/Sources/Compression/WSCompression.swift @@ -0,0 +1,247 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// WSCompression.swift +// +// Created by Joseph Ross on 7/16/14. +// Copyright © 2017 Joseph Ross & Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Compression implementation is implemented in conformance with RFC 7692 Compression Extensions +// for WebSocket: https://tools.ietf.org/html/rfc7692 +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation +import zlib + +public class WSCompression: CompressionHandler { + let headerWSExtensionName = "Sec-WebSocket-Extensions" + var decompressor: Decompressor? + var compressor: Compressor? + var decompressorTakeOver = false + var compressorTakeOver = false + + public init() { + + } + + public func load(headers: [String: String]) { + guard let extensionHeader = headers[headerWSExtensionName] else { return } + decompressorTakeOver = false + compressorTakeOver = false + + let parts = extensionHeader.components(separatedBy: ";") + for p in parts { + let part = p.trimmingCharacters(in: .whitespaces) + if part.hasPrefix("server_max_window_bits=") { + let valString = part.components(separatedBy: "=")[1] + if let val = Int(valString.trimmingCharacters(in: .whitespaces)) { + decompressor = Decompressor(windowBits: val) + } + } else if part.hasPrefix("client_max_window_bits=") { + let valString = part.components(separatedBy: "=")[1] + if let val = Int(valString.trimmingCharacters(in: .whitespaces)) { + compressor = Compressor(windowBits: val) + } + } else if part == "client_no_context_takeover" { + compressorTakeOver = true + } else if part == "server_no_context_takeover" { + decompressorTakeOver = true + } + } + } + + public func decompress(data: Data, isFinal: Bool) -> Data? { + guard let decompressor = decompressor else { return nil } + do { + let decompressedData = try decompressor.decompress(data, finish: isFinal) + if decompressorTakeOver { + try decompressor.reset() + } + return decompressedData + } catch { + //do nothing with the error for now + } + return nil + } + + public func compress(data: Data) -> Data? { + guard let compressor = compressor else { return nil } + do { + let compressedData = try compressor.compress(data) + if compressorTakeOver { + try compressor.reset() + } + return compressedData + } catch { + //do nothing with the error for now + } + return nil + } + + +} + +class Decompressor { + private var strm = z_stream() + private var buffer = [UInt8](repeating: 0, count: 0x2000) + private var inflateInitialized = false + private let windowBits: Int + + init?(windowBits: Int) { + self.windowBits = windowBits + guard initInflate() else { return nil } + } + + private func initInflate() -> Bool { + if Z_OK == inflateInit2_(&strm, -CInt(windowBits), + ZLIB_VERSION, CInt(MemoryLayout.size)) + { + inflateInitialized = true + return true + } + return false + } + + func reset() throws { + teardownInflate() + guard initInflate() else { throw WSError(type: .compressionError, message: "Error for decompressor on reset", code: 0) } + } + + func decompress(_ data: Data, finish: Bool) throws -> Data { + return try data.withUnsafeBytes { (bytes: UnsafePointer) -> Data in + return try decompress(bytes: bytes, count: data.count, finish: finish) + } + } + + func decompress(bytes: UnsafePointer, count: Int, finish: Bool) throws -> Data { + var decompressed = Data() + try decompress(bytes: bytes, count: count, out: &decompressed) + + if finish { + let tail:[UInt8] = [0x00, 0x00, 0xFF, 0xFF] + try decompress(bytes: tail, count: tail.count, out: &decompressed) + } + + return decompressed + } + + private func decompress(bytes: UnsafePointer, count: Int, out: inout Data) throws { + var res: CInt = 0 + strm.next_in = UnsafeMutablePointer(mutating: bytes) + strm.avail_in = CUnsignedInt(count) + + repeat { + buffer.withUnsafeMutableBytes { (bufferPtr) in + strm.next_out = bufferPtr.bindMemory(to: UInt8.self).baseAddress + strm.avail_out = CUnsignedInt(bufferPtr.count) + + res = inflate(&strm, 0) + } + + let byteCount = buffer.count - Int(strm.avail_out) + out.append(buffer, count: byteCount) + } while res == Z_OK && strm.avail_out == 0 + + guard (res == Z_OK && strm.avail_out > 0) + || (res == Z_BUF_ERROR && Int(strm.avail_out) == buffer.count) + else { + throw WSError(type: .compressionError, message: "Error on decompressing", code: 0) + } + } + + private func teardownInflate() { + if inflateInitialized, Z_OK == inflateEnd(&strm) { + inflateInitialized = false + } + } + + deinit { + teardownInflate() + } +} + +class Compressor { + private var strm = z_stream() + private var buffer = [UInt8](repeating: 0, count: 0x2000) + private var deflateInitialized = false + private let windowBits: Int + + init?(windowBits: Int) { + self.windowBits = windowBits + guard initDeflate() else { return nil } + } + + private func initDeflate() -> Bool { + if Z_OK == deflateInit2_(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, + -CInt(windowBits), 8, Z_DEFAULT_STRATEGY, + ZLIB_VERSION, CInt(MemoryLayout.size)) + { + deflateInitialized = true + return true + } + return false + } + + func reset() throws { + teardownDeflate() + guard initDeflate() else { throw WSError(type: .compressionError, message: "Error for compressor on reset", code: 0) } + } + + func compress(_ data: Data) throws -> Data { + var compressed = Data() + var res: CInt = 0 + data.withUnsafeBytes { (ptr:UnsafePointer) -> Void in + strm.next_in = UnsafeMutablePointer(mutating: ptr) + strm.avail_in = CUnsignedInt(data.count) + + repeat { + buffer.withUnsafeMutableBytes { (bufferPtr) in + strm.next_out = bufferPtr.bindMemory(to: UInt8.self).baseAddress + strm.avail_out = CUnsignedInt(bufferPtr.count) + + res = deflate(&strm, Z_SYNC_FLUSH) + } + + let byteCount = buffer.count - Int(strm.avail_out) + compressed.append(buffer, count: byteCount) + } + while res == Z_OK && strm.avail_out == 0 + + } + + guard res == Z_OK && strm.avail_out > 0 + || (res == Z_BUF_ERROR && Int(strm.avail_out) == buffer.count) + else { + throw WSError(type: .compressionError, message: "Error on compressing", code: 0) + } + + compressed.removeLast(4) + return compressed + } + + private func teardownDeflate() { + if deflateInitialized, Z_OK == deflateEnd(&strm) { + deflateInitialized = false + } + } + + deinit { + teardownDeflate() + } +} diff --git a/Example/myWeb3Wallet/Pods/Starscream/Sources/DataBytes/Data+Extensions.swift b/Example/myWeb3Wallet/Pods/Starscream/Sources/DataBytes/Data+Extensions.swift new file mode 100644 index 000000000..1d0852d7c --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Starscream/Sources/DataBytes/Data+Extensions.swift @@ -0,0 +1,53 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Data+Extensions.swift +// Starscream +// +// Created by Dalton Cherry on 3/27/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Fix for deprecation warnings +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation + +internal extension Data { + struct ByteError: Swift.Error {} + + #if swift(>=5.0) + func withUnsafeBytes(_ completion: (UnsafePointer) throws -> ResultType) rethrows -> ResultType { + return try withUnsafeBytes { + if let baseAddress = $0.baseAddress, $0.count > 0 { + return try completion(baseAddress.assumingMemoryBound(to: ContentType.self)) + } else { + throw ByteError() + } + } + } + #endif + + #if swift(>=5.0) + mutating func withUnsafeMutableBytes(_ completion: (UnsafeMutablePointer) throws -> ResultType) rethrows -> ResultType { + return try withUnsafeMutableBytes { + if let baseAddress = $0.baseAddress, $0.count > 0 { + return try completion(baseAddress.assumingMemoryBound(to: ContentType.self)) + } else { + throw ByteError() + } + } + } + #endif +} diff --git a/Example/myWeb3Wallet/Pods/Starscream/Sources/Engine/Engine.swift b/Example/myWeb3Wallet/Pods/Starscream/Sources/Engine/Engine.swift new file mode 100644 index 000000000..a60ef7e81 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Starscream/Sources/Engine/Engine.swift @@ -0,0 +1,22 @@ +// +// Engine.swift +// Starscream +// +// Created by Dalton Cherry on 6/15/19. +// Copyright © 2019 Vluxe. All rights reserved. +// + +import Foundation + +public protocol EngineDelegate: class { + func didReceive(event: WebSocketEvent) +} + +public protocol Engine { + func register(delegate: EngineDelegate) + func start(request: URLRequest) + func stop(closeCode: UInt16) + func forceStop() + func write(data: Data, opcode: FrameOpCode, completion: (() -> ())?) + func write(string: String, completion: (() -> ())?) +} diff --git a/Example/myWeb3Wallet/Pods/Starscream/Sources/Engine/NativeEngine.swift b/Example/myWeb3Wallet/Pods/Starscream/Sources/Engine/NativeEngine.swift new file mode 100644 index 000000000..7294e364f --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Starscream/Sources/Engine/NativeEngine.swift @@ -0,0 +1,96 @@ +// +// NativeEngine.swift +// Starscream +// +// Created by Dalton Cherry on 6/15/19. +// Copyright © 2019 Vluxe. All rights reserved. +// + +import Foundation + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public class NativeEngine: NSObject, Engine, URLSessionDataDelegate, URLSessionWebSocketDelegate { + private var task: URLSessionWebSocketTask? + weak var delegate: EngineDelegate? + + public func register(delegate: EngineDelegate) { + self.delegate = delegate + } + + public func start(request: URLRequest) { + let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil) + task = session.webSocketTask(with: request) + doRead() + task?.resume() + } + + public func stop(closeCode: UInt16) { + let closeCode = URLSessionWebSocketTask.CloseCode(rawValue: Int(closeCode)) ?? .normalClosure + task?.cancel(with: closeCode, reason: nil) + } + + public func forceStop() { + stop(closeCode: UInt16(URLSessionWebSocketTask.CloseCode.abnormalClosure.rawValue)) + } + + public func write(string: String, completion: (() -> ())?) { + task?.send(.string(string), completionHandler: { (error) in + completion?() + }) + } + + public func write(data: Data, opcode: FrameOpCode, completion: (() -> ())?) { + switch opcode { + case .binaryFrame: + task?.send(.data(data), completionHandler: { (error) in + completion?() + }) + case .textFrame: + let text = String(data: data, encoding: .utf8)! + write(string: text, completion: completion) + case .ping: + task?.sendPing(pongReceiveHandler: { (error) in + completion?() + }) + default: + break //unsupported + } + } + + private func doRead() { + task?.receive { [weak self] (result) in + switch result { + case .success(let message): + switch message { + case .string(let string): + self?.broadcast(event: .text(string)) + case .data(let data): + self?.broadcast(event: .binary(data)) + @unknown default: + break + } + break + case .failure(let error): + self?.broadcast(event: .error(error)) + } + self?.doRead() + } + } + + private func broadcast(event: WebSocketEvent) { + delegate?.didReceive(event: event) + } + + public func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) { + let p = `protocol` ?? "" + broadcast(event: .connected([HTTPWSHeader.protocolName: p])) + } + + public func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) { + var r = "" + if let d = reason { + r = String(data: d, encoding: .utf8) ?? "" + } + broadcast(event: .disconnected(r, UInt16(closeCode.rawValue))) + } +} diff --git a/Example/myWeb3Wallet/Pods/Starscream/Sources/Engine/WSEngine.swift b/Example/myWeb3Wallet/Pods/Starscream/Sources/Engine/WSEngine.swift new file mode 100644 index 000000000..decca6413 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Starscream/Sources/Engine/WSEngine.swift @@ -0,0 +1,234 @@ +// +// WSEngine.swift +// Starscream +// +// Created by Dalton Cherry on 6/15/19. +// Copyright © 2019 Vluxe. All rights reserved. +// + +import Foundation + +public class WSEngine: Engine, TransportEventClient, FramerEventClient, +FrameCollectorDelegate, HTTPHandlerDelegate { + private let transport: Transport + private let framer: Framer + private let httpHandler: HTTPHandler + private let compressionHandler: CompressionHandler? + private let certPinner: CertificatePinning? + private let headerChecker: HeaderValidator + private var request: URLRequest! + + private let frameHandler = FrameCollector() + private var didUpgrade = false + private var secKeyValue = "" + private let writeQueue = DispatchQueue(label: "com.vluxe.starscream.writequeue") + private let mutex = DispatchSemaphore(value: 1) + private var canSend = false + + weak var delegate: EngineDelegate? + public var respondToPingWithPong: Bool = true + + public init(transport: Transport, + certPinner: CertificatePinning? = nil, + headerValidator: HeaderValidator = FoundationSecurity(), + httpHandler: HTTPHandler = FoundationHTTPHandler(), + framer: Framer = WSFramer(), + compressionHandler: CompressionHandler? = nil) { + self.transport = transport + self.framer = framer + self.httpHandler = httpHandler + self.certPinner = certPinner + self.headerChecker = headerValidator + self.compressionHandler = compressionHandler + framer.updateCompression(supports: compressionHandler != nil) + frameHandler.delegate = self + } + + public func register(delegate: EngineDelegate) { + self.delegate = delegate + } + + public func start(request: URLRequest) { + mutex.wait() + let isConnected = canSend + mutex.signal() + if isConnected { + return + } + + self.request = request + transport.register(delegate: self) + framer.register(delegate: self) + httpHandler.register(delegate: self) + frameHandler.delegate = self + guard let url = request.url else { + return + } + transport.connect(url: url, timeout: request.timeoutInterval, certificatePinning: certPinner) + } + + public func stop(closeCode: UInt16 = CloseCode.normal.rawValue) { + let capacity = MemoryLayout.size + var pointer = [UInt8](repeating: 0, count: capacity) + writeUint16(&pointer, offset: 0, value: closeCode) + let payload = Data(bytes: pointer, count: MemoryLayout.size) + write(data: payload, opcode: .connectionClose, completion: { [weak self] in + self?.reset() + self?.forceStop() + }) + } + + public func forceStop() { + transport.disconnect() + } + + public func write(string: String, completion: (() -> ())?) { + let data = string.data(using: .utf8)! + write(data: data, opcode: .textFrame, completion: completion) + } + + public func write(data: Data, opcode: FrameOpCode, completion: (() -> ())?) { + writeQueue.async { [weak self] in + guard let s = self else { return } + s.mutex.wait() + let canWrite = s.canSend + s.mutex.signal() + if !canWrite { + return + } + + var isCompressed = false + var sendData = data + if let compressedData = s.compressionHandler?.compress(data: data) { + sendData = compressedData + isCompressed = true + } + + let frameData = s.framer.createWriteFrame(opcode: opcode, payload: sendData, isCompressed: isCompressed) + s.transport.write(data: frameData, completion: {_ in + completion?() + }) + } + } + + // MARK: - TransportEventClient + + public func connectionChanged(state: ConnectionState) { + switch state { + case .connected: + secKeyValue = HTTPWSHeader.generateWebSocketKey() + let wsReq = HTTPWSHeader.createUpgrade(request: request, supportsCompression: framer.supportsCompression(), secKeyValue: secKeyValue) + let data = httpHandler.convert(request: wsReq) + transport.write(data: data, completion: {_ in }) + case .waiting: + break + case .failed(let error): + handleError(error) + case .viability(let isViable): + broadcast(event: .viabilityChanged(isViable)) + case .shouldReconnect(let status): + broadcast(event: .reconnectSuggested(status)) + case .receive(let data): + if didUpgrade { + framer.add(data: data) + } else { + let offset = httpHandler.parse(data: data) + if offset > 0 { + let extraData = data.subdata(in: offset.. Data? { + return compressionHandler?.decompress(data: data, isFinal: isFinal) + } + + public func didForm(event: FrameCollector.Event) { + switch event { + case .text(let string): + broadcast(event: .text(string)) + case .binary(let data): + broadcast(event: .binary(data)) + case .pong(let data): + broadcast(event: .pong(data)) + case .ping(let data): + broadcast(event: .ping(data)) + if respondToPingWithPong { + write(data: data ?? Data(), opcode: .pong, completion: nil) + } + case .closed(let reason, let code): + broadcast(event: .disconnected(reason, code)) + stop(closeCode: code) + case .error(let error): + handleError(error) + } + } + + private func broadcast(event: WebSocketEvent) { + delegate?.didReceive(event: event) + } + + //This call can be coming from a lot of different queues/threads. + //be aware of that when modifying shared variables + private func handleError(_ error: Error?) { + if let wsError = error as? WSError { + stop(closeCode: wsError.code) + } else { + stop() + } + + delegate?.didReceive(event: .error(error)) + } + + private func reset() { + mutex.wait() + canSend = false + didUpgrade = false + mutex.signal() + } + + +} diff --git a/Example/myWeb3Wallet/Pods/Starscream/Sources/Framer/FoundationHTTPHandler.swift b/Example/myWeb3Wallet/Pods/Starscream/Sources/Framer/FoundationHTTPHandler.swift new file mode 100644 index 000000000..fb024aaac --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Starscream/Sources/Framer/FoundationHTTPHandler.swift @@ -0,0 +1,123 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// FoundationHTTPHandler.swift +// Starscream +// +// Created by Dalton Cherry on 1/25/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation +#if os(watchOS) +public typealias FoundationHTTPHandler = StringHTTPHandler +#else +public class FoundationHTTPHandler: HTTPHandler { + + var buffer = Data() + weak var delegate: HTTPHandlerDelegate? + + public init() { + + } + + public func convert(request: URLRequest) -> Data { + let msg = CFHTTPMessageCreateRequest(kCFAllocatorDefault, request.httpMethod! as CFString, + request.url! as CFURL, kCFHTTPVersion1_1).takeRetainedValue() + if let headers = request.allHTTPHeaderFields { + for (aKey, aValue) in headers { + CFHTTPMessageSetHeaderFieldValue(msg, aKey as CFString, aValue as CFString) + } + } + if let body = request.httpBody { + CFHTTPMessageSetBody(msg, body as CFData) + } + guard let data = CFHTTPMessageCopySerializedMessage(msg) else { + return Data() + } + return data.takeRetainedValue() as Data + } + + public func parse(data: Data) -> Int { + let offset = findEndOfHTTP(data: data) + if offset > 0 { + buffer.append(data.subdata(in: 0.. Bool { + var pointer = [UInt8]() + data.withUnsafeBytes { pointer.append(contentsOf: $0) } + + let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue() + if !CFHTTPMessageAppendBytes(response, pointer, data.count) { + return false //not enough data, wait for more + } + if !CFHTTPMessageIsHeaderComplete(response) { + return false //not enough data, wait for more + } + + let code = CFHTTPMessageGetResponseStatusCode(response) + if code != HTTPWSHeader.switchProtocolCode { + delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.notAnUpgrade(code))) + return true + } + + if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) { + let nsHeaders = cfHeaders.takeRetainedValue() as NSDictionary + var headers = [String: String]() + for (key, value) in nsHeaders { + if let key = key as? String, let value = value as? String { + headers[key] = value + } + } + delegate?.didReceiveHTTP(event: .success(headers)) + return true + } + + delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.invalidData)) + return true + } + + public func register(delegate: HTTPHandlerDelegate) { + self.delegate = delegate + } + + private func findEndOfHTTP(data: Data) -> Int { + let endBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")] + var pointer = [UInt8]() + data.withUnsafeBytes { pointer.append(contentsOf: $0) } + var k = 0 + for i in 0.. Data { + #if os(watchOS) + //TODO: build response header + return Data() + #else + let response = CFHTTPMessageCreateResponse(kCFAllocatorDefault, HTTPWSHeader.switchProtocolCode, + nil, kCFHTTPVersion1_1).takeRetainedValue() + + //TODO: add other values to make a proper response here... + //TODO: also sec key thing (Sec-WebSocket-Key) + for (key, value) in headers { + CFHTTPMessageSetHeaderFieldValue(response, key as CFString, value as CFString) + } + guard let cfData = CFHTTPMessageCopySerializedMessage(response)?.takeRetainedValue() else { + return Data() + } + return cfData as Data + #endif + } + + public func parse(data: Data) { + buffer.append(data) + if parseContent(data: buffer) { + buffer = Data() + } + } + + //returns true when the buffer should be cleared + func parseContent(data: Data) -> Bool { + var pointer = [UInt8]() + data.withUnsafeBytes { pointer.append(contentsOf: $0) } + #if os(watchOS) + //TODO: parse data + return false + #else + let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, true).takeRetainedValue() + if !CFHTTPMessageAppendBytes(response, pointer, data.count) { + return false //not enough data, wait for more + } + if !CFHTTPMessageIsHeaderComplete(response) { + return false //not enough data, wait for more + } + if let method = CFHTTPMessageCopyRequestMethod(response)?.takeRetainedValue() { + if (method as NSString) != getVerb { + delegate?.didReceive(event: .failure(HTTPUpgradeError.invalidData)) + return true + } + } + + if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) { + let nsHeaders = cfHeaders.takeRetainedValue() as NSDictionary + var headers = [String: String]() + for (key, value) in nsHeaders { + if let key = key as? String, let value = value as? String { + headers[key] = value + } + } + delegate?.didReceive(event: .success(headers)) + return true + } + + delegate?.didReceive(event: .failure(HTTPUpgradeError.invalidData)) + return true + #endif + } +} diff --git a/Example/myWeb3Wallet/Pods/Starscream/Sources/Framer/FrameCollector.swift b/Example/myWeb3Wallet/Pods/Starscream/Sources/Framer/FrameCollector.swift new file mode 100644 index 000000000..3ec1084c7 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Starscream/Sources/Framer/FrameCollector.swift @@ -0,0 +1,107 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// FrameCollector.swift +// Starscream +// +// Created by Dalton Cherry on 1/24/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation + +public protocol FrameCollectorDelegate: class { + func didForm(event: FrameCollector.Event) + func decompress(data: Data, isFinal: Bool) -> Data? +} + +public class FrameCollector { + public enum Event { + case text(String) + case binary(Data) + case pong(Data?) + case ping(Data?) + case error(Error) + case closed(String, UInt16) + } + weak var delegate: FrameCollectorDelegate? + var buffer = Data() + var frameCount = 0 + var isText = false //was the first frame a text frame or a binary frame? + var needsDecompression = false + + public func add(frame: Frame) { + //check single frame action and out of order frames + if frame.opcode == .connectionClose { + var code = frame.closeCode + var reason = "connection closed by server" + if let customCloseReason = String(data: frame.payload, encoding: .utf8) { + reason = customCloseReason + } else { + code = CloseCode.protocolError.rawValue + } + delegate?.didForm(event: .closed(reason, code)) + return + } else if frame.opcode == .pong { + delegate?.didForm(event: .pong(frame.payload)) + return + } else if frame.opcode == .ping { + delegate?.didForm(event: .ping(frame.payload)) + return + } else if frame.opcode == .continueFrame && frameCount == 0 { + let errCode = CloseCode.protocolError.rawValue + delegate?.didForm(event: .error(WSError(type: .protocolError, message: "first frame can't be a continue frame", code: errCode))) + reset() + return + } else if frameCount > 0 && frame.opcode != .continueFrame { + let errCode = CloseCode.protocolError.rawValue + delegate?.didForm(event: .error(WSError(type: .protocolError, message: "second and beyond of fragment message must be a continue frame", code: errCode))) + reset() + return + } + if frameCount == 0 { + isText = frame.opcode == .textFrame + needsDecompression = frame.needsDecompression + } + + let payload: Data + if needsDecompression { + payload = delegate?.decompress(data: frame.payload, isFinal: frame.isFin) ?? frame.payload + } else { + payload = frame.payload + } + buffer.append(payload) + frameCount += 1 + + if frame.isFin { + if isText { + if let string = String(data: buffer, encoding: .utf8) { + delegate?.didForm(event: .text(string)) + } else { + let errCode = CloseCode.protocolError.rawValue + delegate?.didForm(event: .error(WSError(type: .protocolError, message: "not valid UTF-8 data", code: errCode))) + } + } else { + delegate?.didForm(event: .binary(buffer)) + } + reset() + } + } + + func reset() { + buffer = Data() + frameCount = 0 + } +} diff --git a/Example/myWeb3Wallet/Pods/Starscream/Sources/Framer/Framer.swift b/Example/myWeb3Wallet/Pods/Starscream/Sources/Framer/Framer.swift new file mode 100644 index 000000000..f77d5b80e --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Starscream/Sources/Framer/Framer.swift @@ -0,0 +1,365 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Framer.swift +// Starscream +// +// Created by Dalton Cherry on 1/23/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation + +let FinMask: UInt8 = 0x80 +let OpCodeMask: UInt8 = 0x0F +let RSVMask: UInt8 = 0x70 +let RSV1Mask: UInt8 = 0x40 +let MaskMask: UInt8 = 0x80 +let PayloadLenMask: UInt8 = 0x7F +let MaxFrameSize: Int = 32 + +// Standard WebSocket close codes +public enum CloseCode: UInt16 { + case normal = 1000 + case goingAway = 1001 + case protocolError = 1002 + case protocolUnhandledType = 1003 + // 1004 reserved. + case noStatusReceived = 1005 + //1006 reserved. + case encoding = 1007 + case policyViolated = 1008 + case messageTooBig = 1009 +} + +public enum FrameOpCode: UInt8 { + case continueFrame = 0x0 + case textFrame = 0x1 + case binaryFrame = 0x2 + // 3-7 are reserved. + case connectionClose = 0x8 + case ping = 0x9 + case pong = 0xA + // B-F reserved. + case unknown = 100 +} + +public struct Frame { + let isFin: Bool + let needsDecompression: Bool + let isMasked: Bool + let opcode: FrameOpCode + let payloadLength: UInt64 + let payload: Data + let closeCode: UInt16 //only used by connectionClose opcode +} + +public enum FrameEvent { + case frame(Frame) + case error(Error) +} + +public protocol FramerEventClient: class { + func frameProcessed(event: FrameEvent) +} + +public protocol Framer { + func add(data: Data) + func register(delegate: FramerEventClient) + func createWriteFrame(opcode: FrameOpCode, payload: Data, isCompressed: Bool) -> Data + func updateCompression(supports: Bool) + func supportsCompression() -> Bool +} + +public class WSFramer: Framer { + private let queue = DispatchQueue(label: "com.vluxe.starscream.wsframer", attributes: []) + private weak var delegate: FramerEventClient? + private var buffer = Data() + public var compressionEnabled = false + private let isServer: Bool + + public init(isServer: Bool = false) { + self.isServer = isServer + } + + public func updateCompression(supports: Bool) { + compressionEnabled = supports + } + + public func supportsCompression() -> Bool { + return compressionEnabled + } + + enum ProcessEvent { + case needsMoreData + case processedFrame(Frame, Int) + case failed(Error) + } + + public func add(data: Data) { + queue.async { [weak self] in + self?.buffer.append(data) + while(true) { + let event = self?.process() ?? .needsMoreData + switch event { + case .needsMoreData: + return + case .processedFrame(let frame, let split): + guard let s = self else { return } + s.delegate?.frameProcessed(event: .frame(frame)) + if split >= s.buffer.count { + s.buffer = Data() + return + } + s.buffer = s.buffer.advanced(by: split) + case .failed(let error): + self?.delegate?.frameProcessed(event: .error(error)) + self?.buffer = Data() + return + } + } + } + } + + public func register(delegate: FramerEventClient) { + self.delegate = delegate + } + + private func process() -> ProcessEvent { + if buffer.count < 2 { + return .needsMoreData + } + var pointer = [UInt8]() + buffer.withUnsafeBytes { pointer.append(contentsOf: $0) } + + let isFin = (FinMask & pointer[0]) + let opcodeRawValue = (OpCodeMask & pointer[0]) + let opcode = FrameOpCode(rawValue: opcodeRawValue) ?? .unknown + let isMasked = (MaskMask & pointer[1]) + let payloadLen = (PayloadLenMask & pointer[1]) + let RSV1 = (RSVMask & pointer[0]) + var needsDecompression = false + + if compressionEnabled && opcode != .continueFrame { + needsDecompression = (RSV1Mask & pointer[0]) > 0 + } + if !isServer && (isMasked > 0 || RSV1 > 0) && opcode != .pong && !needsDecompression { + let errCode = CloseCode.protocolError.rawValue + return .failed(WSError(type: .protocolError, message: "masked and rsv data is not currently supported", code: errCode)) + } + let isControlFrame = (opcode == .connectionClose || opcode == .ping) + if !isControlFrame && (opcode != .binaryFrame && opcode != .continueFrame && + opcode != .textFrame && opcode != .pong) { + let errCode = CloseCode.protocolError.rawValue + return .failed(WSError(type: .protocolError, message: "unknown opcode: \(opcodeRawValue)", code: errCode)) + } + if isControlFrame && isFin == 0 { + let errCode = CloseCode.protocolError.rawValue + return .failed(WSError(type: .protocolError, message: "control frames can't be fragmented", code: errCode)) + } + + var offset = 2 + + if isControlFrame && payloadLen > 125 { + return .failed(WSError(type: .protocolError, message: "payload length is longer than allowed for a control frame", code: CloseCode.protocolError.rawValue)) + } + + var dataLength = UInt64(payloadLen) + var closeCode = CloseCode.normal.rawValue + if opcode == .connectionClose { + if payloadLen == 1 { + closeCode = CloseCode.protocolError.rawValue + dataLength = 0 + } else if payloadLen > 1 { + if pointer.count < 4 { + return .needsMoreData + } + let size = MemoryLayout.size + closeCode = pointer.readUint16(offset: offset) + offset += size + dataLength -= UInt64(size) + if closeCode < 1000 || (closeCode > 1003 && closeCode < 1007) || (closeCode > 1013 && closeCode < 3000) { + closeCode = CloseCode.protocolError.rawValue + } + } + } + + if payloadLen == 127 { + let size = MemoryLayout.size + if size + offset > pointer.count { + return .needsMoreData + } + dataLength = pointer.readUint64(offset: offset) + offset += size + } else if payloadLen == 126 { + let size = MemoryLayout.size + if size + offset > pointer.count { + return .needsMoreData + } + dataLength = UInt64(pointer.readUint16(offset: offset)) + offset += size + } + + let maskStart = offset + if isServer { + offset += MemoryLayout.size + } + + if dataLength > (pointer.count - offset) { + return .needsMoreData + } + + //I don't like this cast, but Data's count returns an Int. + //Might be a problem with huge payloads. Need to revisit. + let readDataLength = Int(dataLength) + + let payload: Data + if readDataLength == 0 { + payload = Data() + } else { + if isServer { + payload = pointer.unmaskData(maskStart: maskStart, offset: offset, length: readDataLength) + } else { + let end = offset + readDataLength + payload = Data(pointer[offset.. 0, needsDecompression: needsDecompression, isMasked: isMasked > 0, opcode: opcode, payloadLength: dataLength, payload: payload, closeCode: closeCode) + return .processedFrame(frame, offset) + } + + public func createWriteFrame(opcode: FrameOpCode, payload: Data, isCompressed: Bool) -> Data { + let payloadLength = payload.count + + let capacity = payloadLength + MaxFrameSize + var pointer = [UInt8](repeating: 0, count: capacity) + + //set the framing info + pointer[0] = FinMask | opcode.rawValue + if isCompressed { + pointer[0] |= RSV1Mask + } + + var offset = 2 //skip pass the framing info + if payloadLength < 126 { + pointer[1] = UInt8(payloadLength) + } else if payloadLength <= Int(UInt16.max) { + pointer[1] = 126 + writeUint16(&pointer, offset: offset, value: UInt16(payloadLength)) + offset += MemoryLayout.size + } else { + pointer[1] = 127 + writeUint64(&pointer, offset: offset, value: UInt64(payloadLength)) + offset += MemoryLayout.size + } + + //clients are required to mask the payload data, but server don't according to the RFC + if !isServer { + pointer[1] |= MaskMask + + //write the random mask key in + let maskKey: UInt32 = UInt32.random(in: 0...UInt32.max) + + writeUint32(&pointer, offset: offset, value: maskKey) + let maskStart = offset + offset += MemoryLayout.size + + //now write the payload data in + for i in 0...size)] + offset += 1 + } + } else { + for i in 0.. UInt16 { + return (UInt16(self[offset + 0]) << 8) | UInt16(self[offset + 1]) + } + + /** + Read a UInt64 from a buffer. + - parameter offset: is the offset index to start the read from (e.g. buffer[0], buffer[1], etc). + - returns: a UInt64 of the value from the buffer + */ + func readUint64(offset: Int) -> UInt64 { + var value = UInt64(0) + for i in 0...7 { + value = (value << 8) | UInt64(self[offset + i]) + } + return value + } + + func unmaskData(maskStart: Int, offset: Int, length: Int) -> Data { + var unmaskedBytes = [UInt8](repeating: 0, count: length) + let maskSize = MemoryLayout.size + for i in 0..> 8) + buffer[offset + 1] = UInt8(value & 0xff) +} + +/** + Write a UInt32 to the buffer. It fills the 4 array "slots" of the UInt8 array. + - parameter buffer: is the UInt8 array (pointer) to write the value too. + - parameter offset: is the offset index to start the write from (e.g. buffer[0], buffer[1], etc). + */ +public func writeUint32( _ buffer: inout [UInt8], offset: Int, value: UInt32) { + for i in 0...3 { + buffer[offset + i] = UInt8((value >> (8*UInt32(3 - i))) & 0xff) + } +} + +/** + Write a UInt64 to the buffer. It fills the 8 array "slots" of the UInt8 array. + - parameter buffer: is the UInt8 array (pointer) to write the value too. + - parameter offset: is the offset index to start the write from (e.g. buffer[0], buffer[1], etc). + */ +public func writeUint64( _ buffer: inout [UInt8], offset: Int, value: UInt64) { + for i in 0...7 { + buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff) + } +} diff --git a/Example/myWeb3Wallet/Pods/Starscream/Sources/Framer/HTTPHandler.swift b/Example/myWeb3Wallet/Pods/Starscream/Sources/Framer/HTTPHandler.swift new file mode 100644 index 000000000..70941e75c --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Starscream/Sources/Framer/HTTPHandler.swift @@ -0,0 +1,148 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// HTTPHandler.swift +// Starscream +// +// Created by Dalton Cherry on 1/24/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation + +public enum HTTPUpgradeError: Error { + case notAnUpgrade(Int) + case invalidData +} + +public struct HTTPWSHeader { + static let upgradeName = "Upgrade" + static let upgradeValue = "websocket" + static let hostName = "Host" + static let connectionName = "Connection" + static let connectionValue = "Upgrade" + static let protocolName = "Sec-WebSocket-Protocol" + static let versionName = "Sec-WebSocket-Version" + static let versionValue = "13" + static let extensionName = "Sec-WebSocket-Extensions" + static let keyName = "Sec-WebSocket-Key" + static let originName = "Origin" + static let acceptName = "Sec-WebSocket-Accept" + static let switchProtocolCode = 101 + static let defaultSSLSchemes = ["wss", "https"] + + /// Creates a new URLRequest based off the source URLRequest. + /// - Parameter request: the request to "upgrade" the WebSocket request by adding headers. + /// - Parameter supportsCompression: set if the client support text compression. + /// - Parameter secKeyName: the security key to use in the WebSocket request. https://tools.ietf.org/html/rfc6455#section-1.3 + /// - returns: A URLRequest request to be converted to data and sent to the server. + public static func createUpgrade(request: URLRequest, supportsCompression: Bool, secKeyValue: String) -> URLRequest { + guard let url = request.url, let parts = url.getParts() else { + return request + } + + var req = request + if request.value(forHTTPHeaderField: HTTPWSHeader.originName) == nil { + var origin = url.absoluteString + if let hostUrl = URL (string: "/", relativeTo: url) { + origin = hostUrl.absoluteString + origin.remove(at: origin.index(before: origin.endIndex)) + } + req.setValue(origin, forHTTPHeaderField: HTTPWSHeader.originName) + } + req.setValue(HTTPWSHeader.upgradeValue, forHTTPHeaderField: HTTPWSHeader.upgradeName) + req.setValue(HTTPWSHeader.connectionValue, forHTTPHeaderField: HTTPWSHeader.connectionName) + req.setValue(HTTPWSHeader.versionValue, forHTTPHeaderField: HTTPWSHeader.versionName) + req.setValue(secKeyValue, forHTTPHeaderField: HTTPWSHeader.keyName) + + if let cookies = HTTPCookieStorage.shared.cookies(for: url), !cookies.isEmpty { + let headers = HTTPCookie.requestHeaderFields(with: cookies) + for (key, val) in headers { + req.setValue(val, forHTTPHeaderField: key) + } + } + + if supportsCompression { + let val = "permessage-deflate; client_max_window_bits; server_max_window_bits=15" + req.setValue(val, forHTTPHeaderField: HTTPWSHeader.extensionName) + } + let hostValue = req.allHTTPHeaderFields?[HTTPWSHeader.hostName] ?? "\(parts.host):\(parts.port)" + req.setValue(hostValue, forHTTPHeaderField: HTTPWSHeader.hostName) + return req + } + + // generateWebSocketKey 16 random characters between a-z and return them as a base64 string + public static func generateWebSocketKey() -> String { + return Data((0..<16).map{ _ in UInt8.random(in: 97...122) }).base64EncodedString() + } +} + +public enum HTTPEvent { + case success([String: String]) + case failure(Error) +} + +public protocol HTTPHandlerDelegate: class { + func didReceiveHTTP(event: HTTPEvent) +} + +public protocol HTTPHandler { + func register(delegate: HTTPHandlerDelegate) + func convert(request: URLRequest) -> Data + func parse(data: Data) -> Int +} + +public protocol HTTPServerDelegate: class { + func didReceive(event: HTTPEvent) +} + +public protocol HTTPServerHandler { + func register(delegate: HTTPServerDelegate) + func parse(data: Data) + func createResponse(headers: [String: String]) -> Data +} + +public struct URLParts { + let port: Int + let host: String + let isTLS: Bool +} + +public extension URL { + /// isTLSScheme returns true if the scheme is https or wss + var isTLSScheme: Bool { + guard let scheme = self.scheme else { + return false + } + return HTTPWSHeader.defaultSSLSchemes.contains(scheme) + } + + /// getParts pulls host and port from the url. + func getParts() -> URLParts? { + guard let host = self.host else { + return nil // no host, this isn't a valid url + } + let isTLS = isTLSScheme + var port = self.port ?? 0 + if self.port == nil { + if isTLS { + port = 443 + } else { + port = 80 + } + } + return URLParts(port: port, host: host, isTLS: isTLS) + } +} diff --git a/Example/myWeb3Wallet/Pods/Starscream/Sources/Framer/StringHTTPHandler.swift b/Example/myWeb3Wallet/Pods/Starscream/Sources/Framer/StringHTTPHandler.swift new file mode 100644 index 000000000..33f5f9be0 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Starscream/Sources/Framer/StringHTTPHandler.swift @@ -0,0 +1,143 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// StringHTTPHandler.swift +// Starscream +// +// Created by Dalton Cherry on 8/25/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation + +public class StringHTTPHandler: HTTPHandler { + + var buffer = Data() + weak var delegate: HTTPHandlerDelegate? + + public init() { + + } + + public func convert(request: URLRequest) -> Data { + guard let url = request.url else { + return Data() + } + + var path = url.absoluteString + let offset = (url.scheme?.count ?? 2) + 3 + path = String(path[path.index(path.startIndex, offsetBy: offset).. Int { + let offset = findEndOfHTTP(data: data) + if offset > 0 { + buffer.append(data.subdata(in: 0.. Bool { + guard let str = String(data: data, encoding: .utf8) else { + delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.invalidData)) + return true + } + let splitArr = str.components(separatedBy: "\r\n") + var code = -1 + var i = 0 + var headers = [String: String]() + for str in splitArr { + if i == 0 { + let responseSplit = str.components(separatedBy: .whitespaces) + guard responseSplit.count > 1 else { + delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.invalidData)) + return true + } + if let c = Int(responseSplit[1]) { + code = c + } + } else { + guard let separatorIndex = str.firstIndex(of: ":") else { break } + let key = str.prefix(upTo: separatorIndex).trimmingCharacters(in: .whitespaces) + let val = str.suffix(from: str.index(after: separatorIndex)).trimmingCharacters(in: .whitespaces) + headers[key.lowercased()] = val + } + i += 1 + } + + if code != HTTPWSHeader.switchProtocolCode { + delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.notAnUpgrade(code))) + return true + } + + delegate?.didReceiveHTTP(event: .success(headers)) + return true + } + + public func register(delegate: HTTPHandlerDelegate) { + self.delegate = delegate + } + + private func findEndOfHTTP(data: Data) -> Int { + let endBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")] + var pointer = [UInt8]() + data.withUnsafeBytes { pointer.append(contentsOf: $0) } + var k = 0 + for i in 0.. ())) { + if allowSelfSigned { + completion(.success) + return + } + + if let validateDomain = domain { + SecTrustSetPolicies(trust, SecPolicyCreateSSL(true, validateDomain as NSString?)) + } + + handleSecurityTrust(trust: trust, completion: completion) + } + + private func handleSecurityTrust(trust: SecTrust, completion: ((PinningState) -> ())) { + if #available(iOS 12.0, OSX 10.14, watchOS 5.0, tvOS 12.0, *) { + var error: CFError? + if SecTrustEvaluateWithError(trust, &error) { + completion(.success) + } else { + completion(.failed(error)) + } + } else { + handleOldSecurityTrust(trust: trust, completion: completion) + } + } + + private func handleOldSecurityTrust(trust: SecTrust, completion: ((PinningState) -> ())) { + var result: SecTrustResultType = .unspecified + SecTrustEvaluate(trust, &result) + if result == .unspecified || result == .proceed { + completion(.success) + } else { + let e = CFErrorCreate(kCFAllocatorDefault, "FoundationSecurityError" as NSString?, Int(result.rawValue), nil) + completion(.failed(e)) + } + } +} + +extension FoundationSecurity: HeaderValidator { + public func validate(headers: [String: String], key: String) -> Error? { + if let acceptKey = headers[HTTPWSHeader.acceptName] { + let sha = "\(key)258EAFA5-E914-47DA-95CA-C5AB0DC85B11".sha1Base64() + if sha != acceptKey { + return WSError(type: .securityError, message: "accept header doesn't match", code: SecurityErrorCode.acceptFailed.rawValue) + } + } + return nil + } +} + +private extension String { + func sha1Base64() -> String { + let data = self.data(using: .utf8)! + let pointer = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in + var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH)) + CC_SHA1(bytes.baseAddress, CC_LONG(data.count), &digest) + return digest + } + return Data(pointer).base64EncodedString() + } +} diff --git a/Example/myWeb3Wallet/Pods/Starscream/Sources/Security/Security.swift b/Example/myWeb3Wallet/Pods/Starscream/Sources/Security/Security.swift new file mode 100644 index 000000000..a64a7713e --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Starscream/Sources/Security/Security.swift @@ -0,0 +1,45 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Security.swift +// Starscream +// +// Created by Dalton Cherry on 3/16/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation + +public enum SecurityErrorCode: UInt16 { + case acceptFailed = 1 + case pinningFailed = 2 +} + +public enum PinningState { + case success + case failed(CFError?) +} + +// CertificatePinning protocol provides an interface for Transports to handle Certificate +// or Public Key Pinning. +public protocol CertificatePinning: class { + func evaluateTrust(trust: SecTrust, domain: String?, completion: ((PinningState) -> ())) +} + +// validates the "Sec-WebSocket-Accept" header as defined 1.3 of the RFC 6455 +// https://tools.ietf.org/html/rfc6455#section-1.3 +public protocol HeaderValidator: class { + func validate(headers: [String: String], key: String) -> Error? +} diff --git a/Example/myWeb3Wallet/Pods/Starscream/Sources/Server/Server.swift b/Example/myWeb3Wallet/Pods/Starscream/Sources/Server/Server.swift new file mode 100644 index 000000000..527c851df --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Starscream/Sources/Server/Server.swift @@ -0,0 +1,56 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Server.swift +// Starscream +// +// Created by Dalton Cherry on 4/2/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation + +public enum ConnectionEvent { + case connected([String: String]) + case disconnected(String, UInt16) + case text(String) + case binary(Data) + case pong(Data?) + case ping(Data?) + case error(Error) +} + +public protocol Connection { + func write(data: Data, opcode: FrameOpCode) +} + +public protocol ConnectionDelegate: class { + func didReceive(event: ServerEvent) +} + +public enum ServerEvent { + case connected(Connection, [String: String]) + case disconnected(Connection, String, UInt16) + case text(Connection, String) + case binary(Connection, Data) + case pong(Connection, Data?) + case ping(Connection, Data?) +} + +public protocol Server { + func start(address: String, port: UInt16) -> Error? +} + + diff --git a/Example/myWeb3Wallet/Pods/Starscream/Sources/Server/WebSocketServer.swift b/Example/myWeb3Wallet/Pods/Starscream/Sources/Server/WebSocketServer.swift new file mode 100644 index 000000000..4d3b9af5c --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Starscream/Sources/Server/WebSocketServer.swift @@ -0,0 +1,196 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// WebSocketServer.swift +// Starscream +// +// Created by Dalton Cherry on 4/5/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +#if canImport(Network) +import Foundation +import Network + +/// WebSocketServer is a Network.framework implementation of a WebSocket server +@available(watchOS, unavailable) +@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) +public class WebSocketServer: Server, ConnectionDelegate { + public var onEvent: ((ServerEvent) -> Void)? + private var connections = [String: ServerConnection]() + private var listener: NWListener? + private let queue = DispatchQueue(label: "com.vluxe.starscream.server.networkstream", attributes: []) + + public init() { + + } + + public func start(address: String, port: UInt16) -> Error? { + //TODO: support TLS cert adding/binding + let parameters = NWParameters(tls: nil, tcp: NWProtocolTCP.Options()) + let p = NWEndpoint.Port(rawValue: port)! + parameters.requiredLocalEndpoint = NWEndpoint.hostPort(host: NWEndpoint.Host.name(address, nil), port: p) + + guard let listener = try? NWListener(using: parameters, on: p) else { + return WSError(type: .serverError, message: "unable to start the listener at: \(address):\(port)", code: 0) + } + listener.newConnectionHandler = {[weak self] conn in + let transport = TCPTransport(connection: conn) + let c = ServerConnection(transport: transport) + c.delegate = self + self?.connections[c.uuid] = c + } +// listener.stateUpdateHandler = { state in +// switch state { +// case .ready: +// print("ready to get sockets!") +// case .setup: +// print("setup to get sockets!") +// case .cancelled: +// print("server cancelled!") +// case .waiting(let error): +// print("waiting error: \(error)") +// case .failed(let error): +// print("server failed: \(error)") +// @unknown default: +// print("wat?") +// } +// } + self.listener = listener + listener.start(queue: queue) + return nil + } + + public func didReceive(event: ServerEvent) { + onEvent?(event) + switch event { + case .disconnected(let conn, _, _): + guard let conn = conn as? ServerConnection else { + return + } + connections.removeValue(forKey: conn.uuid) + default: + break + } + } +} + +@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) +public class ServerConnection: Connection, HTTPServerDelegate, FramerEventClient, FrameCollectorDelegate, TransportEventClient { + let transport: TCPTransport + private let httpHandler = FoundationHTTPServerHandler() + private let framer = WSFramer(isServer: true) + private let frameHandler = FrameCollector() + private var didUpgrade = false + public var onEvent: ((ConnectionEvent) -> Void)? + public weak var delegate: ConnectionDelegate? + private let id: String + var uuid: String { + return id + } + + init(transport: TCPTransport) { + self.id = UUID().uuidString + self.transport = transport + transport.register(delegate: self) + httpHandler.register(delegate: self) + framer.register(delegate: self) + frameHandler.delegate = self + } + + public func write(data: Data, opcode: FrameOpCode) { + let wsData = framer.createWriteFrame(opcode: opcode, payload: data, isCompressed: false) + transport.write(data: wsData, completion: {_ in }) + } + + // MARK: - TransportEventClient + + public func connectionChanged(state: ConnectionState) { + switch state { + case .connected: + break + case .waiting: + break + case .failed(let error): + print("server connection error: \(error ?? WSError(type: .protocolError, message: "default error, no extra data", code: 0))") //handleError(error) + case .viability(_): + break + case .shouldReconnect(_): + break + case .receive(let data): + if didUpgrade { + framer.add(data: data) + } else { + httpHandler.parse(data: data) + } + case .cancelled: + print("server connection cancelled!") + //broadcast(event: .cancelled) + } + } + + /// MARK: - HTTPServerDelegate + + public func didReceive(event: HTTPEvent) { + switch event { + case .success(let headers): + didUpgrade = true + let response = httpHandler.createResponse(headers: [:]) + transport.write(data: response, completion: {_ in }) + delegate?.didReceive(event: .connected(self, headers)) + onEvent?(.connected(headers)) + case .failure(let error): + onEvent?(.error(error)) + } + } + + /// MARK: - FrameCollectorDelegate + + public func frameProcessed(event: FrameEvent) { + switch event { + case .frame(let frame): + frameHandler.add(frame: frame) + case .error(let error): + onEvent?(.error(error)) + } + } + + public func didForm(event: FrameCollector.Event) { + switch event { + case .text(let string): + delegate?.didReceive(event: .text(self, string)) + onEvent?(.text(string)) + case .binary(let data): + delegate?.didReceive(event: .binary(self, data)) + onEvent?(.binary(data)) + case .pong(let data): + delegate?.didReceive(event: .pong(self, data)) + onEvent?(.pong(data)) + case .ping(let data): + delegate?.didReceive(event: .ping(self, data)) + onEvent?(.ping(data)) + case .closed(let reason, let code): + delegate?.didReceive(event: .disconnected(self, reason, code)) + onEvent?(.disconnected(reason, code)) + case .error(let error): + onEvent?(.error(error)) + } + } + + public func decompress(data: Data, isFinal: Bool) -> Data? { + return nil + } +} +#endif diff --git a/Example/myWeb3Wallet/Pods/Starscream/Sources/Starscream/WebSocket.swift b/Example/myWeb3Wallet/Pods/Starscream/Sources/Starscream/WebSocket.swift new file mode 100644 index 000000000..1d3545c3c --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Starscream/Sources/Starscream/WebSocket.swift @@ -0,0 +1,178 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Websocket.swift +// Starscream +// +// Created by Dalton Cherry on 7/16/14. +// Copyright (c) 2014-2019 Dalton Cherry. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation + +public enum ErrorType: Error { + case compressionError + case securityError + case protocolError //There was an error parsing the WebSocket frames + case serverError +} + +public struct WSError: Error { + public let type: ErrorType + public let message: String + public let code: UInt16 + + public init(type: ErrorType, message: String, code: UInt16) { + self.type = type + self.message = message + self.code = code + } +} + +public protocol WebSocketClient: class { + func connect() + func disconnect(closeCode: UInt16) + func write(string: String, completion: (() -> ())?) + func write(stringData: Data, completion: (() -> ())?) + func write(data: Data, completion: (() -> ())?) + func write(ping: Data, completion: (() -> ())?) + func write(pong: Data, completion: (() -> ())?) +} + +//implements some of the base behaviors +extension WebSocketClient { + public func write(string: String) { + write(string: string, completion: nil) + } + + public func write(data: Data) { + write(data: data, completion: nil) + } + + public func write(ping: Data) { + write(ping: ping, completion: nil) + } + + public func write(pong: Data) { + write(pong: pong, completion: nil) + } + + public func disconnect() { + disconnect(closeCode: CloseCode.normal.rawValue) + } +} + +public enum WebSocketEvent { + case connected([String: String]) + case disconnected(String, UInt16) + case text(String) + case binary(Data) + case pong(Data?) + case ping(Data?) + case error(Error?) + case viabilityChanged(Bool) + case reconnectSuggested(Bool) + case cancelled +} + +public protocol WebSocketDelegate: class { + func didReceive(event: WebSocketEvent, client: WebSocket) +} + +open class WebSocket: WebSocketClient, EngineDelegate { + private let engine: Engine + public weak var delegate: WebSocketDelegate? + public var onEvent: ((WebSocketEvent) -> Void)? + + public var request: URLRequest + // Where the callback is executed. It defaults to the main UI thread queue. + public var callbackQueue = DispatchQueue.main + public var respondToPingWithPong: Bool { + set { + guard let e = engine as? WSEngine else { return } + e.respondToPingWithPong = newValue + } + get { + guard let e = engine as? WSEngine else { return true } + return e.respondToPingWithPong + } + } + + // serial write queue to ensure writes happen in order + private let writeQueue = DispatchQueue(label: "com.vluxe.starscream.writequeue") + private var canSend = false + private let mutex = DispatchSemaphore(value: 1) + + public init(request: URLRequest, engine: Engine) { + self.request = request + self.engine = engine + } + + public convenience init(request: URLRequest, certPinner: CertificatePinning? = FoundationSecurity(), compressionHandler: CompressionHandler? = nil, useCustomEngine: Bool = true) { + if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *), !useCustomEngine { + self.init(request: request, engine: NativeEngine()) + } else if #available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) { + self.init(request: request, engine: WSEngine(transport: TCPTransport(), certPinner: certPinner, compressionHandler: compressionHandler)) + } else { + self.init(request: request, engine: WSEngine(transport: FoundationTransport(), certPinner: certPinner, compressionHandler: compressionHandler)) + } + } + + public func connect() { + engine.register(delegate: self) + engine.start(request: request) + } + + public func disconnect(closeCode: UInt16 = CloseCode.normal.rawValue) { + engine.stop(closeCode: closeCode) + } + + public func forceDisconnect() { + engine.forceStop() + } + + public func write(data: Data, completion: (() -> ())?) { + write(data: data, opcode: .binaryFrame, completion: completion) + } + + public func write(string: String, completion: (() -> ())?) { + engine.write(string: string, completion: completion) + } + + public func write(stringData: Data, completion: (() -> ())?) { + write(data: stringData, opcode: .textFrame, completion: completion) + } + + public func write(ping: Data, completion: (() -> ())?) { + write(data: ping, opcode: .ping, completion: completion) + } + + public func write(pong: Data, completion: (() -> ())?) { + write(data: pong, opcode: .pong, completion: completion) + } + + private func write(data: Data, opcode: FrameOpCode, completion: (() -> ())?) { + engine.write(data: data, opcode: opcode, completion: completion) + } + + // MARK: - EngineDelegate + public func didReceive(event: WebSocketEvent) { + callbackQueue.async { [weak self] in + guard let s = self else { return } + s.delegate?.didReceive(event: event, client: s) + s.onEvent?(event) + } + } +} diff --git a/Example/myWeb3Wallet/Pods/Starscream/Sources/Transport/FoundationTransport.swift b/Example/myWeb3Wallet/Pods/Starscream/Sources/Transport/FoundationTransport.swift new file mode 100644 index 000000000..8d304f885 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Starscream/Sources/Transport/FoundationTransport.swift @@ -0,0 +1,218 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// FoundationTransport.swift +// Starscream +// +// Created by Dalton Cherry on 1/23/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation + +public enum FoundationTransportError: Error { + case invalidRequest + case invalidOutputStream + case timeout +} + +public class FoundationTransport: NSObject, Transport, StreamDelegate { + private weak var delegate: TransportEventClient? + private let workQueue = DispatchQueue(label: "com.vluxe.starscream.websocket", attributes: []) + private var inputStream: InputStream? + private var outputStream: OutputStream? + private var isOpen = false + private var onConnect: ((InputStream, OutputStream) -> Void)? + private var isTLS = false + private var certPinner: CertificatePinning? + + public var usingTLS: Bool { + return self.isTLS + } + + public init(streamConfiguration: ((InputStream, OutputStream) -> Void)? = nil) { + super.init() + onConnect = streamConfiguration + } + + deinit { + inputStream?.delegate = nil + outputStream?.delegate = nil + } + + public func connect(url: URL, timeout: Double = 10, certificatePinning: CertificatePinning? = nil) { + guard let parts = url.getParts() else { + delegate?.connectionChanged(state: .failed(FoundationTransportError.invalidRequest)) + return + } + self.certPinner = certificatePinning + self.isTLS = parts.isTLS + var readStream: Unmanaged? + var writeStream: Unmanaged? + let h = parts.host as NSString + CFStreamCreatePairWithSocketToHost(nil, h, UInt32(parts.port), &readStream, &writeStream) + inputStream = readStream!.takeRetainedValue() + outputStream = writeStream!.takeRetainedValue() + guard let inStream = inputStream, let outStream = outputStream else { + return + } + inStream.delegate = self + outStream.delegate = self + + if isTLS { + let key = CFStreamPropertyKey(rawValue: kCFStreamPropertySocketSecurityLevel) + CFReadStreamSetProperty(inStream, key, kCFStreamSocketSecurityLevelNegotiatedSSL) + CFWriteStreamSetProperty(outStream, key, kCFStreamSocketSecurityLevelNegotiatedSSL) + } + + onConnect?(inStream, outStream) + + isOpen = false + CFReadStreamSetDispatchQueue(inStream, workQueue) + CFWriteStreamSetDispatchQueue(outStream, workQueue) + inStream.open() + outStream.open() + + + workQueue.asyncAfter(deadline: .now() + timeout, execute: { [weak self] in + guard let s = self else { return } + if !s.isOpen { + s.delegate?.connectionChanged(state: .failed(FoundationTransportError.timeout)) + } + }) + } + + public func disconnect() { + if let stream = inputStream { + stream.delegate = nil + CFReadStreamSetDispatchQueue(stream, nil) + stream.close() + } + if let stream = outputStream { + stream.delegate = nil + CFWriteStreamSetDispatchQueue(stream, nil) + stream.close() + } + isOpen = false + outputStream = nil + inputStream = nil + } + + public func register(delegate: TransportEventClient) { + self.delegate = delegate + } + + public func write(data: Data, completion: @escaping ((Error?) -> ())) { + guard let outStream = outputStream else { + completion(FoundationTransportError.invalidOutputStream) + return + } + var total = 0 + let buffer = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self) + //NOTE: this might need to be dispatched to the work queue instead of being written inline. TBD. + while total < data.count { + let written = outStream.write(buffer, maxLength: data.count) + if written < 0 { + completion(FoundationTransportError.invalidOutputStream) + return + } + total += written + } + completion(nil) + } + + private func getSecurityData() -> (SecTrust?, String?) { + #if os(watchOS) + return (nil, nil) + #else + guard let outputStream = outputStream else { + return (nil, nil) + } + let trust = outputStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as! SecTrust? + var domain = outputStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as! String? + + if domain == nil, + let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? { + var peerNameLen: Int = 0 + SSLGetPeerDomainNameLength(sslContextOut, &peerNameLen) + var peerName = Data(count: peerNameLen) + let _ = peerName.withUnsafeMutableBytes { (peerNamePtr: UnsafeMutablePointer) in + SSLGetPeerDomainName(sslContextOut, peerNamePtr, &peerNameLen) + } + if let peerDomain = String(bytes: peerName, encoding: .utf8), peerDomain.count > 0 { + domain = peerDomain + } + } + return (trust, domain) + #endif + } + + private func read() { + guard let stream = inputStream else { + return + } + let maxBuffer = 4096 + let buf = NSMutableData(capacity: maxBuffer) + let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self) + let length = stream.read(buffer, maxLength: maxBuffer) + if length < 1 { + return + } + let data = Data(bytes: buffer, count: length) + delegate?.connectionChanged(state: .receive(data)) + } + + // MARK: - StreamDelegate + + open func stream(_ aStream: Stream, handle eventCode: Stream.Event) { + switch eventCode { + case .hasBytesAvailable: + if aStream == inputStream { + read() + } + case .errorOccurred: + delegate?.connectionChanged(state: .failed(aStream.streamError)) + case .endEncountered: + if aStream == inputStream { + delegate?.connectionChanged(state: .cancelled) + } + case .openCompleted: + if aStream == inputStream { + let (trust, domain) = getSecurityData() + if let pinner = certPinner, let trust = trust { + pinner.evaluateTrust(trust: trust, domain: domain, completion: { [weak self] (state) in + switch state { + case .success: + self?.isOpen = true + self?.delegate?.connectionChanged(state: .connected) + case .failed(let error): + self?.delegate?.connectionChanged(state: .failed(error)) + } + + }) + } else { + isOpen = true + delegate?.connectionChanged(state: .connected) + } + } + case .endEncountered: + if aStream == inputStream { + delegate?.connectionChanged(state: .cancelled) + } + default: + break + } + } +} diff --git a/Example/myWeb3Wallet/Pods/Starscream/Sources/Transport/TCPTransport.swift b/Example/myWeb3Wallet/Pods/Starscream/Sources/Transport/TCPTransport.swift new file mode 100644 index 000000000..459cb2ed0 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Starscream/Sources/Transport/TCPTransport.swift @@ -0,0 +1,159 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// HTTPTransport.swift +// Starscream +// +// Created by Dalton Cherry on 1/23/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +#if canImport(Network) +import Foundation +import Network + +public enum TCPTransportError: Error { + case invalidRequest +} + +@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) +public class TCPTransport: Transport { + private var connection: NWConnection? + private let queue = DispatchQueue(label: "com.vluxe.starscream.networkstream", attributes: []) + private weak var delegate: TransportEventClient? + private var isRunning = false + private var isTLS = false + + public var usingTLS: Bool { + return self.isTLS + } + + public init(connection: NWConnection) { + self.connection = connection + start() + } + + public init() { + //normal connection, will use the "connect" method below + } + + public func connect(url: URL, timeout: Double = 10, certificatePinning: CertificatePinning? = nil) { + guard let parts = url.getParts() else { + delegate?.connectionChanged(state: .failed(TCPTransportError.invalidRequest)) + return + } + self.isTLS = parts.isTLS + let options = NWProtocolTCP.Options() + options.connectionTimeout = Int(timeout.rounded(.up)) + + let tlsOptions = isTLS ? NWProtocolTLS.Options() : nil + if let tlsOpts = tlsOptions { + sec_protocol_options_set_verify_block(tlsOpts.securityProtocolOptions, { (sec_protocol_metadata, sec_trust, sec_protocol_verify_complete) in + let trust = sec_trust_copy_ref(sec_trust).takeRetainedValue() + guard let pinner = certificatePinning else { + sec_protocol_verify_complete(true) + return + } + pinner.evaluateTrust(trust: trust, domain: parts.host, completion: { (state) in + switch state { + case .success: + sec_protocol_verify_complete(true) + case .failed(_): + sec_protocol_verify_complete(false) + } + }) + }, queue) + } + let parameters = NWParameters(tls: tlsOptions, tcp: options) + let conn = NWConnection(host: NWEndpoint.Host.name(parts.host, nil), port: NWEndpoint.Port(rawValue: UInt16(parts.port))!, using: parameters) + connection = conn + start() + } + + public func disconnect() { + isRunning = false + connection?.cancel() + } + + public func register(delegate: TransportEventClient) { + self.delegate = delegate + } + + public func write(data: Data, completion: @escaping ((Error?) -> ())) { + connection?.send(content: data, completion: .contentProcessed { (error) in + completion(error) + }) + } + + private func start() { + guard let conn = connection else { + return + } + conn.stateUpdateHandler = { [weak self] (newState) in + switch newState { + case .ready: + self?.delegate?.connectionChanged(state: .connected) + case .waiting: + self?.delegate?.connectionChanged(state: .waiting) + case .cancelled: + self?.delegate?.connectionChanged(state: .cancelled) + case .failed(let error): + self?.delegate?.connectionChanged(state: .failed(error)) + case .setup, .preparing: + break + @unknown default: + break + } + } + + conn.viabilityUpdateHandler = { [weak self] (isViable) in + self?.delegate?.connectionChanged(state: .viability(isViable)) + } + + conn.betterPathUpdateHandler = { [weak self] (isBetter) in + self?.delegate?.connectionChanged(state: .shouldReconnect(isBetter)) + } + + conn.start(queue: queue) + isRunning = true + readLoop() + } + + //readLoop keeps reading from the connection to get the latest content + private func readLoop() { + if !isRunning { + return + } + connection?.receive(minimumIncompleteLength: 2, maximumLength: 4096, completion: {[weak self] (data, context, isComplete, error) in + guard let s = self else {return} + if let data = data { + s.delegate?.connectionChanged(state: .receive(data)) + } + + // Refer to https://developer.apple.com/documentation/network/implementing_netcat_with_network_framework + if let context = context, context.isFinal, isComplete { + return + } + + if error == nil { + s.readLoop() + } + + }) + } +} +#else +typealias TCPTransport = FoundationTransport +#endif diff --git a/Example/myWeb3Wallet/Pods/Starscream/Sources/Transport/Transport.swift b/Example/myWeb3Wallet/Pods/Starscream/Sources/Transport/Transport.swift new file mode 100644 index 000000000..e645651ff --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Starscream/Sources/Transport/Transport.swift @@ -0,0 +1,55 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Transport.swift +// Starscream +// +// Created by Dalton Cherry on 1/23/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation + +public enum ConnectionState { + case connected + case waiting + case cancelled + case failed(Error?) + + //the viability (connection status) of the connection has updated + //e.g. connection is down, connection came back up, etc + case viability(Bool) + + //the connection has upgrade to wifi from cellular. + //you should consider reconnecting to take advantage of this + case shouldReconnect(Bool) + + //the connection receive data + case receive(Data) +} + +public protocol TransportEventClient: class { + func connectionChanged(state: ConnectionState) +} + +public protocol Transport: class { + func register(delegate: TransportEventClient) + func connect(url: URL, timeout: Double, certificatePinning: CertificatePinning?) + func disconnect() + func write(data: Data, completion: @escaping ((Error?) -> ())) + var usingTLS: Bool { get } +} diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt-Info.plist b/Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt-Info.plist new file mode 100644 index 000000000..82c355f54 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 5.2.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt-dummy.m b/Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt-dummy.m new file mode 100644 index 000000000..7367f8606 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_BigInt : NSObject +@end +@implementation PodsDummy_BigInt +@end diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt-prefix.pch b/Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt-prefix.pch new file mode 100644 index 000000000..beb2a2441 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt-umbrella.h b/Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt-umbrella.h new file mode 100644 index 000000000..e3d2506e1 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double BigIntVersionNumber; +FOUNDATION_EXPORT const unsigned char BigIntVersionString[]; + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt.debug.xcconfig b/Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt.debug.xcconfig new file mode 100644 index 000000000..3900220c8 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt.debug.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/BigInt +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/BigInt +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt.modulemap b/Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt.modulemap new file mode 100644 index 000000000..48a38d1cb --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt.modulemap @@ -0,0 +1,6 @@ +framework module BigInt { + umbrella header "BigInt-umbrella.h" + + export * + module * { export * } +} diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt.release.xcconfig b/Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt.release.xcconfig new file mode 100644 index 000000000..3900220c8 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/BigInt/BigInt.release.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/BigInt +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/BigInt +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift-Info.plist b/Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift-Info.plist new file mode 100644 index 000000000..78afe084b --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.4.2 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift-dummy.m b/Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift-dummy.m new file mode 100644 index 000000000..657061bc6 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_CryptoSwift : NSObject +@end +@implementation PodsDummy_CryptoSwift +@end diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift-prefix.pch b/Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift-prefix.pch new file mode 100644 index 000000000..beb2a2441 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift-umbrella.h b/Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift-umbrella.h new file mode 100644 index 000000000..e93efa884 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double CryptoSwiftVersionNumber; +FOUNDATION_EXPORT const unsigned char CryptoSwiftVersionString[]; + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift.debug.xcconfig b/Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift.debug.xcconfig new file mode 100644 index 000000000..548e99783 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift.debug.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/CryptoSwift +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift.modulemap b/Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift.modulemap new file mode 100644 index 000000000..f090f6a33 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift.modulemap @@ -0,0 +1,6 @@ +framework module CryptoSwift { + umbrella header "CryptoSwift-umbrella.h" + + export * + module * { export * } +} diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift.release.xcconfig b/Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift.release.xcconfig new file mode 100644 index 000000000..548e99783 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/CryptoSwift/CryptoSwift.release.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/CryptoSwift +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-Info.plist b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-Info.plist new file mode 100644 index 000000000..2243fe6e2 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-acknowledgements.markdown b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-acknowledgements.markdown new file mode 100644 index 000000000..11cd22293 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-acknowledgements.markdown @@ -0,0 +1,475 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## BigInt + + +Copyright (c) 2016-2017 Károly Lőrentey + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +## CryptoSwift + +Copyright (C) 2014-2017 Marcin Krzyżanowski +This software is provided 'as-is', without any express or implied warranty. + +In no event will the authors be held liable for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: + +- The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +- Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +- This notice may not be removed or altered from any source or binary distribution. +- Redistributions of any form whatsoever must retain the following acknowledgment: 'This product includes software developed by the "Marcin Krzyzanowski" (http://krzyzanowskim.com/).' + + +## PromiseKit + +Copyright 2016-present, Max Howell; mxcl@me.com + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +## Starscream + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + Copyright (c) 2014-2016 Dalton Cherry. + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +## secp256k1.c + +Copyright (c) 2013 Pieter Wuille + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +## web3swift + +Copyright (c) 2018 Aleksandr Vlasov, + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018 Aleksandr Vlasov + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +Generated by CocoaPods - https://cocoapods.org diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-acknowledgements.plist b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-acknowledgements.plist new file mode 100644 index 000000000..c02e55e8b --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-acknowledgements.plist @@ -0,0 +1,537 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + +Copyright (c) 2016-2017 Károly Lőrentey + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + License + MIT + Title + BigInt + Type + PSGroupSpecifier + + + FooterText + Copyright (C) 2014-2017 Marcin Krzyżanowski <marcin.krzyzanowski@gmail.com> +This software is provided 'as-is', without any express or implied warranty. + +In no event will the authors be held liable for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: + +- The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +- Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +- This notice may not be removed or altered from any source or binary distribution. +- Redistributions of any form whatsoever must retain the following acknowledgment: 'This product includes software developed by the "Marcin Krzyzanowski" (http://krzyzanowskim.com/).' + + License + Attribution + Title + CryptoSwift + Type + PSGroupSpecifier + + + FooterText + Copyright 2016-present, Max Howell; mxcl@me.com + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + License + MIT + Title + PromiseKit + Type + PSGroupSpecifier + + + FooterText + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + Copyright (c) 2014-2016 Dalton Cherry. + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + License + Apache License, Version 2.0 + Title + Starscream + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2013 Pieter Wuille + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + License + Apache License 2.0 + Title + secp256k1.c + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2018 Aleksandr Vlasov, <alex.m.vlasov@gmail.com> + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018 Aleksandr Vlasov + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + License + Apache License 2.0 + Title + web3swift + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-dummy.m b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-dummy.m new file mode 100644 index 000000000..e538c0499 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_myWeb3Wallet_myWeb3WalletUITests : NSObject +@end +@implementation PodsDummy_Pods_myWeb3Wallet_myWeb3WalletUITests +@end diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks-Debug-input-files.xcfilelist b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks-Debug-input-files.xcfilelist new file mode 100644 index 000000000..a771409d2 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks-Debug-input-files.xcfilelist @@ -0,0 +1,7 @@ +${PODS_ROOT}/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks.sh +${BUILT_PRODUCTS_DIR}/BigInt/BigInt.framework +${BUILT_PRODUCTS_DIR}/CryptoSwift/CryptoSwift.framework +${BUILT_PRODUCTS_DIR}/PromiseKit/PromiseKit.framework +${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework +${BUILT_PRODUCTS_DIR}/secp256k1.c/secp256k1.framework +${BUILT_PRODUCTS_DIR}/web3swift/web3swift.framework \ No newline at end of file diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks-Debug-output-files.xcfilelist b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks-Debug-output-files.xcfilelist new file mode 100644 index 000000000..02d4d0015 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks-Debug-output-files.xcfilelist @@ -0,0 +1,6 @@ +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/BigInt.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/CryptoSwift.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PromiseKit.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Starscream.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/secp256k1.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/web3swift.framework \ No newline at end of file diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks-Release-input-files.xcfilelist b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks-Release-input-files.xcfilelist new file mode 100644 index 000000000..a771409d2 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks-Release-input-files.xcfilelist @@ -0,0 +1,7 @@ +${PODS_ROOT}/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks.sh +${BUILT_PRODUCTS_DIR}/BigInt/BigInt.framework +${BUILT_PRODUCTS_DIR}/CryptoSwift/CryptoSwift.framework +${BUILT_PRODUCTS_DIR}/PromiseKit/PromiseKit.framework +${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework +${BUILT_PRODUCTS_DIR}/secp256k1.c/secp256k1.framework +${BUILT_PRODUCTS_DIR}/web3swift/web3swift.framework \ No newline at end of file diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks-Release-output-files.xcfilelist b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks-Release-output-files.xcfilelist new file mode 100644 index 000000000..02d4d0015 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks-Release-output-files.xcfilelist @@ -0,0 +1,6 @@ +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/BigInt.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/CryptoSwift.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PromiseKit.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Starscream.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/secp256k1.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/web3swift.framework \ No newline at end of file diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks.sh b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks.sh new file mode 100755 index 000000000..3567561a7 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks.sh @@ -0,0 +1,196 @@ +#!/bin/sh +set -e +set -u +set -o pipefail + +function on_error { + echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" +} +trap 'on_error $LINENO' ERR + +if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then + # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy + # frameworks to, so exit 0 (signalling the script phase was successful). + exit 0 +fi + +echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" +SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" +BCSYMBOLMAP_DIR="BCSymbolMaps" + + +# This protects against multiple targets copying the same framework dependency at the same time. The solution +# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html +RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") + +# Copies and strips a vendored framework +install_framework() +{ + if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then + local source="${BUILT_PRODUCTS_DIR}/$1" + elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then + local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" + elif [ -r "$1" ]; then + local source="$1" + fi + + local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + + if [ -L "${source}" ]; then + echo "Symlinked..." + source="$(readlink "${source}")" + fi + + if [ -d "${source}/${BCSYMBOLMAP_DIR}" ]; then + # Locate and install any .bcsymbolmaps if present, and remove them from the .framework before the framework is copied + find "${source}/${BCSYMBOLMAP_DIR}" -name "*.bcsymbolmap"|while read f; do + echo "Installing $f" + install_bcsymbolmap "$f" "$destination" + rm "$f" + done + rmdir "${source}/${BCSYMBOLMAP_DIR}" + fi + + # Use filter instead of exclude so missing patterns don't throw errors. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" + + local basename + basename="$(basename -s .framework "$1")" + binary="${destination}/${basename}.framework/${basename}" + + if ! [ -r "$binary" ]; then + binary="${destination}/${basename}" + elif [ -L "${binary}" ]; then + echo "Destination binary is symlinked..." + dirname="$(dirname "${binary}")" + binary="${dirname}/$(readlink "${binary}")" + fi + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then + strip_invalid_archs "$binary" + fi + + # Resign the code if required by the build settings to avoid unstable apps + code_sign_if_enabled "${destination}/$(basename "$1")" + + # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. + if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then + local swift_runtime_libs + swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) + for lib in $swift_runtime_libs; do + echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" + rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" + code_sign_if_enabled "${destination}/${lib}" + done + fi +} +# Copies and strips a vendored dSYM +install_dsym() { + local source="$1" + warn_missing_arch=${2:-true} + if [ -r "$source" ]; then + # Copy the dSYM into the targets temp dir. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" + + local basename + basename="$(basename -s .dSYM "$source")" + binary_name="$(ls "$source/Contents/Resources/DWARF")" + binary="${DERIVED_FILES_DIR}/${basename}.dSYM/Contents/Resources/DWARF/${binary_name}" + + # Strip invalid architectures from the dSYM. + if [[ "$(file "$binary")" == *"Mach-O "*"dSYM companion"* ]]; then + strip_invalid_archs "$binary" "$warn_missing_arch" + fi + if [[ $STRIP_BINARY_RETVAL == 0 ]]; then + # Move the stripped file into its final destination. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.dSYM" "${DWARF_DSYM_FOLDER_PATH}" + else + # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. + mkdir -p "${DWARF_DSYM_FOLDER_PATH}" + touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.dSYM" + fi + fi +} + +# Used as a return value for each invocation of `strip_invalid_archs` function. +STRIP_BINARY_RETVAL=0 + +# Strip invalid architectures +strip_invalid_archs() { + binary="$1" + warn_missing_arch=${2:-true} + # Get architectures for current target binary + binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" + # Intersect them with the architectures we are building for + intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" + # If there are no archs supported by this binary then warn the user + if [[ -z "$intersected_archs" ]]; then + if [[ "$warn_missing_arch" == "true" ]]; then + echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." + fi + STRIP_BINARY_RETVAL=1 + return + fi + stripped="" + for arch in $binary_archs; do + if ! [[ "${ARCHS}" == *"$arch"* ]]; then + # Strip non-valid architectures in-place + lipo -remove "$arch" -output "$binary" "$binary" + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi + STRIP_BINARY_RETVAL=0 +} + +# Copies the bcsymbolmap files of a vendored framework +install_bcsymbolmap() { + local bcsymbolmap_path="$1" + local destination="${BUILT_PRODUCTS_DIR}" + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}" +} + +# Signs a framework with the provided identity +code_sign_if_enabled() { + if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then + # Use the current code_sign_identity + echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" + local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" + + if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + code_sign_cmd="$code_sign_cmd &" + fi + echo "$code_sign_cmd" + eval "$code_sign_cmd" + fi +} + +if [[ "$CONFIGURATION" == "Debug" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/BigInt/BigInt.framework" + install_framework "${BUILT_PRODUCTS_DIR}/CryptoSwift/CryptoSwift.framework" + install_framework "${BUILT_PRODUCTS_DIR}/PromiseKit/PromiseKit.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework" + install_framework "${BUILT_PRODUCTS_DIR}/secp256k1.c/secp256k1.framework" + install_framework "${BUILT_PRODUCTS_DIR}/web3swift/web3swift.framework" +fi +if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/BigInt/BigInt.framework" + install_framework "${BUILT_PRODUCTS_DIR}/CryptoSwift/CryptoSwift.framework" + install_framework "${BUILT_PRODUCTS_DIR}/PromiseKit/PromiseKit.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework" + install_framework "${BUILT_PRODUCTS_DIR}/secp256k1.c/secp256k1.framework" + install_framework "${BUILT_PRODUCTS_DIR}/web3swift/web3swift.framework" +fi +if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + wait +fi diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-umbrella.h b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-umbrella.h new file mode 100644 index 000000000..10c2be55f --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double Pods_myWeb3Wallet_myWeb3WalletUITestsVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_myWeb3Wallet_myWeb3WalletUITestsVersionString[]; + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests.debug.xcconfig b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests.debug.xcconfig new file mode 100644 index 000000000..3e8b71b56 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests.debug.xcconfig @@ -0,0 +1,15 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt/BigInt.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift/CryptoSwift.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit/PromiseKit.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream/Starscream.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c/secp256k1.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift/web3swift.framework/Headers" +LD_RUNPATH_SEARCH_PATHS = $(inherited) /usr/lib/swift "$(PLATFORM_DIR)/Developer/Library/Frameworks" '@executable_path/Frameworks' '@loader_path/Frameworks' +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "BigInt" -framework "CoreImage" -framework "CryptoSwift" -framework "Foundation" -framework "PromiseKit" -framework "Starscream" -framework "UIKit" -framework "secp256k1" -framework "web3swift" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests.modulemap b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests.modulemap new file mode 100644 index 000000000..a45beb073 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests.modulemap @@ -0,0 +1,6 @@ +framework module Pods_myWeb3Wallet_myWeb3WalletUITests { + umbrella header "Pods-myWeb3Wallet-myWeb3WalletUITests-umbrella.h" + + export * + module * { export * } +} diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests.release.xcconfig b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests.release.xcconfig new file mode 100644 index 000000000..3e8b71b56 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests.release.xcconfig @@ -0,0 +1,15 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt/BigInt.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift/CryptoSwift.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit/PromiseKit.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream/Starscream.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c/secp256k1.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift/web3swift.framework/Headers" +LD_RUNPATH_SEARCH_PATHS = $(inherited) /usr/lib/swift "$(PLATFORM_DIR)/Developer/Library/Frameworks" '@executable_path/Frameworks' '@loader_path/Frameworks' +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "BigInt" -framework "CoreImage" -framework "CryptoSwift" -framework "Foundation" -framework "PromiseKit" -framework "Starscream" -framework "UIKit" -framework "secp256k1" -framework "web3swift" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-Info.plist b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-Info.plist new file mode 100644 index 000000000..2243fe6e2 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-acknowledgements.markdown b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-acknowledgements.markdown new file mode 100644 index 000000000..11cd22293 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-acknowledgements.markdown @@ -0,0 +1,475 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## BigInt + + +Copyright (c) 2016-2017 Károly Lőrentey + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +## CryptoSwift + +Copyright (C) 2014-2017 Marcin Krzyżanowski +This software is provided 'as-is', without any express or implied warranty. + +In no event will the authors be held liable for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: + +- The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +- Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +- This notice may not be removed or altered from any source or binary distribution. +- Redistributions of any form whatsoever must retain the following acknowledgment: 'This product includes software developed by the "Marcin Krzyzanowski" (http://krzyzanowskim.com/).' + + +## PromiseKit + +Copyright 2016-present, Max Howell; mxcl@me.com + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +## Starscream + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + Copyright (c) 2014-2016 Dalton Cherry. + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +## secp256k1.c + +Copyright (c) 2013 Pieter Wuille + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +## web3swift + +Copyright (c) 2018 Aleksandr Vlasov, + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018 Aleksandr Vlasov + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +Generated by CocoaPods - https://cocoapods.org diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-acknowledgements.plist b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-acknowledgements.plist new file mode 100644 index 000000000..c02e55e8b --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-acknowledgements.plist @@ -0,0 +1,537 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + +Copyright (c) 2016-2017 Károly Lőrentey + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + License + MIT + Title + BigInt + Type + PSGroupSpecifier + + + FooterText + Copyright (C) 2014-2017 Marcin Krzyżanowski <marcin.krzyzanowski@gmail.com> +This software is provided 'as-is', without any express or implied warranty. + +In no event will the authors be held liable for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: + +- The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +- Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +- This notice may not be removed or altered from any source or binary distribution. +- Redistributions of any form whatsoever must retain the following acknowledgment: 'This product includes software developed by the "Marcin Krzyzanowski" (http://krzyzanowskim.com/).' + + License + Attribution + Title + CryptoSwift + Type + PSGroupSpecifier + + + FooterText + Copyright 2016-present, Max Howell; mxcl@me.com + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + License + MIT + Title + PromiseKit + Type + PSGroupSpecifier + + + FooterText + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + Copyright (c) 2014-2016 Dalton Cherry. + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + License + Apache License, Version 2.0 + Title + Starscream + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2013 Pieter Wuille + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + License + Apache License 2.0 + Title + secp256k1.c + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2018 Aleksandr Vlasov, <alex.m.vlasov@gmail.com> + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018 Aleksandr Vlasov + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + License + Apache License 2.0 + Title + web3swift + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-dummy.m b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-dummy.m new file mode 100644 index 000000000..033e858cd --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_myWeb3Wallet : NSObject +@end +@implementation PodsDummy_Pods_myWeb3Wallet +@end diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks-Debug-input-files.xcfilelist b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks-Debug-input-files.xcfilelist new file mode 100644 index 000000000..52065e2bb --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks-Debug-input-files.xcfilelist @@ -0,0 +1,7 @@ +${PODS_ROOT}/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks.sh +${BUILT_PRODUCTS_DIR}/BigInt/BigInt.framework +${BUILT_PRODUCTS_DIR}/CryptoSwift/CryptoSwift.framework +${BUILT_PRODUCTS_DIR}/PromiseKit/PromiseKit.framework +${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework +${BUILT_PRODUCTS_DIR}/secp256k1.c/secp256k1.framework +${BUILT_PRODUCTS_DIR}/web3swift/web3swift.framework \ No newline at end of file diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks-Debug-output-files.xcfilelist b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks-Debug-output-files.xcfilelist new file mode 100644 index 000000000..02d4d0015 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks-Debug-output-files.xcfilelist @@ -0,0 +1,6 @@ +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/BigInt.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/CryptoSwift.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PromiseKit.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Starscream.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/secp256k1.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/web3swift.framework \ No newline at end of file diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks-Release-input-files.xcfilelist b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks-Release-input-files.xcfilelist new file mode 100644 index 000000000..52065e2bb --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks-Release-input-files.xcfilelist @@ -0,0 +1,7 @@ +${PODS_ROOT}/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks.sh +${BUILT_PRODUCTS_DIR}/BigInt/BigInt.framework +${BUILT_PRODUCTS_DIR}/CryptoSwift/CryptoSwift.framework +${BUILT_PRODUCTS_DIR}/PromiseKit/PromiseKit.framework +${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework +${BUILT_PRODUCTS_DIR}/secp256k1.c/secp256k1.framework +${BUILT_PRODUCTS_DIR}/web3swift/web3swift.framework \ No newline at end of file diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks-Release-output-files.xcfilelist b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks-Release-output-files.xcfilelist new file mode 100644 index 000000000..02d4d0015 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks-Release-output-files.xcfilelist @@ -0,0 +1,6 @@ +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/BigInt.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/CryptoSwift.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PromiseKit.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Starscream.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/secp256k1.framework +${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/web3swift.framework \ No newline at end of file diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks.sh b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks.sh new file mode 100755 index 000000000..3567561a7 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks.sh @@ -0,0 +1,196 @@ +#!/bin/sh +set -e +set -u +set -o pipefail + +function on_error { + echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" +} +trap 'on_error $LINENO' ERR + +if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then + # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy + # frameworks to, so exit 0 (signalling the script phase was successful). + exit 0 +fi + +echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" +SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" +BCSYMBOLMAP_DIR="BCSymbolMaps" + + +# This protects against multiple targets copying the same framework dependency at the same time. The solution +# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html +RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") + +# Copies and strips a vendored framework +install_framework() +{ + if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then + local source="${BUILT_PRODUCTS_DIR}/$1" + elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then + local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" + elif [ -r "$1" ]; then + local source="$1" + fi + + local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + + if [ -L "${source}" ]; then + echo "Symlinked..." + source="$(readlink "${source}")" + fi + + if [ -d "${source}/${BCSYMBOLMAP_DIR}" ]; then + # Locate and install any .bcsymbolmaps if present, and remove them from the .framework before the framework is copied + find "${source}/${BCSYMBOLMAP_DIR}" -name "*.bcsymbolmap"|while read f; do + echo "Installing $f" + install_bcsymbolmap "$f" "$destination" + rm "$f" + done + rmdir "${source}/${BCSYMBOLMAP_DIR}" + fi + + # Use filter instead of exclude so missing patterns don't throw errors. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" + + local basename + basename="$(basename -s .framework "$1")" + binary="${destination}/${basename}.framework/${basename}" + + if ! [ -r "$binary" ]; then + binary="${destination}/${basename}" + elif [ -L "${binary}" ]; then + echo "Destination binary is symlinked..." + dirname="$(dirname "${binary}")" + binary="${dirname}/$(readlink "${binary}")" + fi + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then + strip_invalid_archs "$binary" + fi + + # Resign the code if required by the build settings to avoid unstable apps + code_sign_if_enabled "${destination}/$(basename "$1")" + + # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. + if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then + local swift_runtime_libs + swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) + for lib in $swift_runtime_libs; do + echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" + rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" + code_sign_if_enabled "${destination}/${lib}" + done + fi +} +# Copies and strips a vendored dSYM +install_dsym() { + local source="$1" + warn_missing_arch=${2:-true} + if [ -r "$source" ]; then + # Copy the dSYM into the targets temp dir. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" + + local basename + basename="$(basename -s .dSYM "$source")" + binary_name="$(ls "$source/Contents/Resources/DWARF")" + binary="${DERIVED_FILES_DIR}/${basename}.dSYM/Contents/Resources/DWARF/${binary_name}" + + # Strip invalid architectures from the dSYM. + if [[ "$(file "$binary")" == *"Mach-O "*"dSYM companion"* ]]; then + strip_invalid_archs "$binary" "$warn_missing_arch" + fi + if [[ $STRIP_BINARY_RETVAL == 0 ]]; then + # Move the stripped file into its final destination. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.dSYM" "${DWARF_DSYM_FOLDER_PATH}" + else + # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. + mkdir -p "${DWARF_DSYM_FOLDER_PATH}" + touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.dSYM" + fi + fi +} + +# Used as a return value for each invocation of `strip_invalid_archs` function. +STRIP_BINARY_RETVAL=0 + +# Strip invalid architectures +strip_invalid_archs() { + binary="$1" + warn_missing_arch=${2:-true} + # Get architectures for current target binary + binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" + # Intersect them with the architectures we are building for + intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" + # If there are no archs supported by this binary then warn the user + if [[ -z "$intersected_archs" ]]; then + if [[ "$warn_missing_arch" == "true" ]]; then + echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." + fi + STRIP_BINARY_RETVAL=1 + return + fi + stripped="" + for arch in $binary_archs; do + if ! [[ "${ARCHS}" == *"$arch"* ]]; then + # Strip non-valid architectures in-place + lipo -remove "$arch" -output "$binary" "$binary" + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi + STRIP_BINARY_RETVAL=0 +} + +# Copies the bcsymbolmap files of a vendored framework +install_bcsymbolmap() { + local bcsymbolmap_path="$1" + local destination="${BUILT_PRODUCTS_DIR}" + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}" +} + +# Signs a framework with the provided identity +code_sign_if_enabled() { + if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then + # Use the current code_sign_identity + echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" + local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" + + if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + code_sign_cmd="$code_sign_cmd &" + fi + echo "$code_sign_cmd" + eval "$code_sign_cmd" + fi +} + +if [[ "$CONFIGURATION" == "Debug" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/BigInt/BigInt.framework" + install_framework "${BUILT_PRODUCTS_DIR}/CryptoSwift/CryptoSwift.framework" + install_framework "${BUILT_PRODUCTS_DIR}/PromiseKit/PromiseKit.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework" + install_framework "${BUILT_PRODUCTS_DIR}/secp256k1.c/secp256k1.framework" + install_framework "${BUILT_PRODUCTS_DIR}/web3swift/web3swift.framework" +fi +if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/BigInt/BigInt.framework" + install_framework "${BUILT_PRODUCTS_DIR}/CryptoSwift/CryptoSwift.framework" + install_framework "${BUILT_PRODUCTS_DIR}/PromiseKit/PromiseKit.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Starscream/Starscream.framework" + install_framework "${BUILT_PRODUCTS_DIR}/secp256k1.c/secp256k1.framework" + install_framework "${BUILT_PRODUCTS_DIR}/web3swift/web3swift.framework" +fi +if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + wait +fi diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-umbrella.h b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-umbrella.h new file mode 100644 index 000000000..284a9e893 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double Pods_myWeb3WalletVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_myWeb3WalletVersionString[]; + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet.debug.xcconfig b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet.debug.xcconfig new file mode 100644 index 000000000..373646d6e --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet.debug.xcconfig @@ -0,0 +1,15 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt/BigInt.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift/CryptoSwift.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit/PromiseKit.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream/Starscream.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c/secp256k1.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift/web3swift.framework/Headers" +LD_RUNPATH_SEARCH_PATHS = $(inherited) /usr/lib/swift '@executable_path/Frameworks' '@loader_path/Frameworks' +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "BigInt" -framework "CoreImage" -framework "CryptoSwift" -framework "Foundation" -framework "PromiseKit" -framework "Starscream" -framework "UIKit" -framework "secp256k1" -framework "web3swift" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet.modulemap b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet.modulemap new file mode 100644 index 000000000..18ab52cda --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet.modulemap @@ -0,0 +1,6 @@ +framework module Pods_myWeb3Wallet { + umbrella header "Pods-myWeb3Wallet-umbrella.h" + + export * + module * { export * } +} diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet.release.xcconfig b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet.release.xcconfig new file mode 100644 index 000000000..373646d6e --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet.release.xcconfig @@ -0,0 +1,15 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt/BigInt.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift/CryptoSwift.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit/PromiseKit.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream/Starscream.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c/secp256k1.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift/web3swift.framework/Headers" +LD_RUNPATH_SEARCH_PATHS = $(inherited) /usr/lib/swift '@executable_path/Frameworks' '@loader_path/Frameworks' +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "BigInt" -framework "CoreImage" -framework "CryptoSwift" -framework "Foundation" -framework "PromiseKit" -framework "Starscream" -framework "UIKit" -framework "secp256k1" -framework "web3swift" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests-Info.plist b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests-Info.plist new file mode 100644 index 000000000..2243fe6e2 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests-acknowledgements.markdown b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests-acknowledgements.markdown new file mode 100644 index 000000000..102af7538 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests-acknowledgements.markdown @@ -0,0 +1,3 @@ +# Acknowledgements +This application makes use of the following third party libraries: +Generated by CocoaPods - https://cocoapods.org diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests-acknowledgements.plist b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests-acknowledgements.plist new file mode 100644 index 000000000..7acbad1ea --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests-acknowledgements.plist @@ -0,0 +1,29 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests-dummy.m b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests-dummy.m new file mode 100644 index 000000000..21f68e3e1 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_myWeb3WalletTests : NSObject +@end +@implementation PodsDummy_Pods_myWeb3WalletTests +@end diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests-umbrella.h b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests-umbrella.h new file mode 100644 index 000000000..3f71cc252 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double Pods_myWeb3WalletTestsVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_myWeb3WalletTestsVersionString[]; + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests.debug.xcconfig b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests.debug.xcconfig new file mode 100644 index 000000000..a93533830 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests.debug.xcconfig @@ -0,0 +1,11 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt/BigInt.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift/CryptoSwift.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit/PromiseKit.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream/Starscream.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c/secp256k1.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift/web3swift.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "BigInt" -framework "CoreImage" -framework "CryptoSwift" -framework "Foundation" -framework "PromiseKit" -framework "Starscream" -framework "UIKit" -framework "secp256k1" -framework "web3swift" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests.modulemap b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests.modulemap new file mode 100644 index 000000000..c57f0966f --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests.modulemap @@ -0,0 +1,6 @@ +framework module Pods_myWeb3WalletTests { + umbrella header "Pods-myWeb3WalletTests-umbrella.h" + + export * + module * { export * } +} diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests.release.xcconfig b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests.release.xcconfig new file mode 100644 index 000000000..a93533830 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests.release.xcconfig @@ -0,0 +1,11 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt/BigInt.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift/CryptoSwift.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit/PromiseKit.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream/Starscream.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c/secp256k1.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift/web3swift.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "BigInt" -framework "CoreImage" -framework "CryptoSwift" -framework "Foundation" -framework "PromiseKit" -framework "Starscream" -framework "UIKit" -framework "secp256k1" -framework "web3swift" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit-Info.plist b/Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit-Info.plist new file mode 100644 index 000000000..5ba796168 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 6.15.3 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit-dummy.m b/Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit-dummy.m new file mode 100644 index 000000000..ce9245130 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_PromiseKit : NSObject +@end +@implementation PodsDummy_PromiseKit +@end diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit-prefix.pch b/Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit-prefix.pch new file mode 100644 index 000000000..beb2a2441 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit-umbrella.h b/Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit-umbrella.h new file mode 100644 index 000000000..4a0b02de6 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit-umbrella.h @@ -0,0 +1,26 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "fwd.h" +#import "AnyPromise.h" +#import "PromiseKit.h" +#import "NSURLSession+AnyPromise.h" +#import "NSTask+AnyPromise.h" +#import "NSNotificationCenter+AnyPromise.h" +#import "PMKFoundation.h" +#import "PMKUIKit.h" +#import "UIView+AnyPromise.h" +#import "UIViewController+AnyPromise.h" + +FOUNDATION_EXPORT double PromiseKitVersionNumber; +FOUNDATION_EXPORT const unsigned char PromiseKitVersionString[]; + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit.debug.xcconfig b/Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit.debug.xcconfig new file mode 100644 index 000000000..4774c3cc0 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit.debug.xcconfig @@ -0,0 +1,14 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "Foundation" -framework "UIKit" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -DPMKCocoaPods +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/PromiseKit +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit.modulemap b/Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit.modulemap new file mode 100644 index 000000000..2b26033e4 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit.modulemap @@ -0,0 +1,6 @@ +framework module PromiseKit { + umbrella header "PromiseKit-umbrella.h" + + export * + module * { export * } +} diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit.release.xcconfig b/Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit.release.xcconfig new file mode 100644 index 000000000..4774c3cc0 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/PromiseKit/PromiseKit.release.xcconfig @@ -0,0 +1,14 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "Foundation" -framework "UIKit" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -DPMKCocoaPods +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/PromiseKit +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream-Info.plist b/Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream-Info.plist new file mode 100644 index 000000000..f78cea60d --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 4.0.4 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream-dummy.m b/Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream-dummy.m new file mode 100644 index 000000000..94456b3b0 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Starscream : NSObject +@end +@implementation PodsDummy_Starscream +@end diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream-prefix.pch b/Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream-prefix.pch new file mode 100644 index 000000000..beb2a2441 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream-umbrella.h b/Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream-umbrella.h new file mode 100644 index 000000000..7bffee0b3 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double StarscreamVersionNumber; +FOUNDATION_EXPORT const unsigned char StarscreamVersionString[]; + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream.debug.xcconfig b/Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream.debug.xcconfig new file mode 100644 index 000000000..90e77b706 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream.debug.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Starscream +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Starscream +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream.modulemap b/Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream.modulemap new file mode 100644 index 000000000..2b9097079 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream.modulemap @@ -0,0 +1,6 @@ +framework module Starscream { + umbrella header "Starscream-umbrella.h" + + export * + module * { export * } +} diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream.release.xcconfig b/Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream.release.xcconfig new file mode 100644 index 000000000..90e77b706 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/Starscream/Starscream.release.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Starscream +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Starscream +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c-Info.plist b/Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c-Info.plist new file mode 100644 index 000000000..7c241fa96 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 0.1.2 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c-dummy.m b/Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c-dummy.m new file mode 100644 index 000000000..965dbb1b9 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_secp256k1_c : NSObject +@end +@implementation PodsDummy_secp256k1_c +@end diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c-prefix.pch b/Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c-prefix.pch new file mode 100644 index 000000000..beb2a2441 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c-umbrella.h b/Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c-umbrella.h new file mode 100644 index 000000000..6943b49f3 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c-umbrella.h @@ -0,0 +1,17 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "secp256k1.h" + +FOUNDATION_EXPORT double secp256k1VersionNumber; +FOUNDATION_EXPORT const unsigned char secp256k1VersionString[]; + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c.debug.xcconfig b/Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c.debug.xcconfig new file mode 100644 index 000000000..93ba0a8c7 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c.debug.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/secp256k1" +OTHER_CFLAGS = $(inherited) -pedantic -Wall -Wextra -Wcast-align -Wnested-externs -Wshadow -Wstrict-prototypes -Wno-shorten-64-to-32 -Wno-conditional-uninitialized -Wno-unused-function -Wno-long-long -Wno-overlength-strings -O3 +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/secp256k1.c +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c.modulemap b/Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c.modulemap new file mode 100644 index 000000000..94da377c2 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c.modulemap @@ -0,0 +1,6 @@ +framework module secp256k1 { + umbrella header "secp256k1.c-umbrella.h" + + export * + module * { export * } +} diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c.release.xcconfig b/Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c.release.xcconfig new file mode 100644 index 000000000..93ba0a8c7 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/secp256k1.c/secp256k1.c.release.xcconfig @@ -0,0 +1,13 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/secp256k1" +OTHER_CFLAGS = $(inherited) -pedantic -Wall -Wextra -Wcast-align -Wnested-externs -Wshadow -Wstrict-prototypes -Wno-shorten-64-to-32 -Wno-conditional-uninitialized -Wno-unused-function -Wno-long-long -Wno-overlength-strings -O3 +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/secp256k1.c +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/ResourceBundle-Browser-web3swift-Info.plist b/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/ResourceBundle-Browser-web3swift-Info.plist new file mode 100644 index 000000000..86717ece9 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/ResourceBundle-Browser-web3swift-Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + BNDL + CFBundleShortVersionString + 2.3.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + NSPrincipalClass + + + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift-Info.plist b/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift-Info.plist new file mode 100644 index 000000000..d135faf18 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 2.3.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift-dummy.m b/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift-dummy.m new file mode 100644 index 000000000..ee2665c93 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_web3swift : NSObject +@end +@implementation PodsDummy_web3swift +@end diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift-prefix.pch b/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift-prefix.pch new file mode 100644 index 000000000..beb2a2441 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift-umbrella.h b/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift-umbrella.h new file mode 100644 index 000000000..9ec6a0b48 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double web3swiftVersionNumber; +FOUNDATION_EXPORT const unsigned char web3swiftVersionString[]; + diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift.debug.xcconfig b/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift.debug.xcconfig new file mode 100644 index 000000000..8ffb39adb --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift.debug.xcconfig @@ -0,0 +1,15 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/web3swift +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "BigInt" -framework "CoreImage" -framework "CryptoSwift" -framework "Foundation" -framework "PromiseKit" -framework "Starscream" -framework "UIKit" -framework "secp256k1" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/web3swift +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift.modulemap b/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift.modulemap new file mode 100644 index 000000000..241e217a4 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift.modulemap @@ -0,0 +1,6 @@ +framework module web3swift { + umbrella header "web3swift-umbrella.h" + + export * + module * { export * } +} diff --git a/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift.release.xcconfig b/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift.release.xcconfig new file mode 100644 index 000000000..8ffb39adb --- /dev/null +++ b/Example/myWeb3Wallet/Pods/Target Support Files/web3swift/web3swift.release.xcconfig @@ -0,0 +1,15 @@ +CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/web3swift +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BigInt" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LIBRARY_SEARCH_PATHS = $(inherited) "${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" /usr/lib/swift +OTHER_LDFLAGS = $(inherited) -framework "BigInt" -framework "CoreImage" -framework "CryptoSwift" -framework "Foundation" -framework "PromiseKit" -framework "Starscream" -framework "UIKit" -framework "secp256k1" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/web3swift +PODS_XCFRAMEWORKS_BUILD_DIR = $(PODS_CONFIGURATION_BUILD_DIR)/XCFrameworkIntermediates +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/License.md b/Example/myWeb3Wallet/Pods/secp256k1.c/License.md new file mode 100644 index 000000000..4522a5990 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/License.md @@ -0,0 +1,19 @@ +Copyright (c) 2013 Pieter Wuille + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/basic-config.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/basic-config.h new file mode 100644 index 000000000..fc588061c --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/basic-config.h @@ -0,0 +1,33 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_BASIC_CONFIG_H +#define SECP256K1_BASIC_CONFIG_H + +#ifdef USE_BASIC_CONFIG + +#undef USE_ASM_X86_64 +#undef USE_ENDOMORPHISM +#undef USE_FIELD_10X26 +#undef USE_FIELD_5X52 +#undef USE_FIELD_INV_BUILTIN +#undef USE_FIELD_INV_NUM +#undef USE_NUM_GMP +#undef USE_NUM_NONE +#undef USE_SCALAR_4X64 +#undef USE_SCALAR_8X32 +#undef USE_SCALAR_INV_BUILTIN +#undef USE_SCALAR_INV_NUM + +#define USE_NUM_NONE 1 +#define USE_FIELD_INV_BUILTIN 1 +#define USE_SCALAR_INV_BUILTIN 1 +#define USE_FIELD_10X26 1 +#define USE_SCALAR_8X32 1 + +#endif /* USE_BASIC_CONFIG */ + +#endif /* SECP256K1_BASIC_CONFIG_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecdh_impl.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecdh_impl.h new file mode 100644 index 000000000..c6820b8c5 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecdh_impl.h @@ -0,0 +1,54 @@ +/********************************************************************** + * Copyright (c) 2015 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_MODULE_ECDH_MAIN_H +#define SECP256K1_MODULE_ECDH_MAIN_H + +#include "secp256k1.h" +#include "ecmult_const_impl.h" + +int secp256k1_ecdh(const secp256k1_context* ctx, unsigned char *result, const secp256k1_pubkey *point, const unsigned char *scalar) { + int ret = 0; + int overflow = 0; + secp256k1_gej res; + secp256k1_ge pt; + secp256k1_scalar s; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(result != NULL); + ARG_CHECK(point != NULL); + ARG_CHECK(scalar != NULL); + + secp256k1_pubkey_load(ctx, &pt, point); + secp256k1_scalar_set_b32(&s, scalar, &overflow); + if (overflow || secp256k1_scalar_is_zero(&s)) { + ret = 0; + } else { + unsigned char x[32]; + unsigned char y[1]; + secp256k1_sha256 sha; + + secp256k1_ecmult_const(&res, &pt, &s, 256); + secp256k1_ge_set_gej(&pt, &res); + /* Compute a hash of the point in compressed form + * Note we cannot use secp256k1_eckey_pubkey_serialize here since it does not + * expect its output to be secret and has a timing sidechannel. */ + secp256k1_fe_normalize(&pt.x); + secp256k1_fe_normalize(&pt.y); + secp256k1_fe_get_b32(x, &pt.x); + y[0] = 0x02 | secp256k1_fe_is_odd(&pt.y); + + secp256k1_sha256_initialize(&sha); + secp256k1_sha256_write(&sha, y, sizeof(y)); + secp256k1_sha256_write(&sha, x, sizeof(x)); + secp256k1_sha256_finalize(&sha, result); + ret = 1; + } + + secp256k1_scalar_clear(&s); + return ret; +} + +#endif /* SECP256K1_MODULE_ECDH_MAIN_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecdsa.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecdsa.h new file mode 100644 index 000000000..80590c7cc --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecdsa.h @@ -0,0 +1,21 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECDSA_H +#define SECP256K1_ECDSA_H + +#include + +#include "scalar.h" +#include "group.h" +#include "ecmult.h" + +static int secp256k1_ecdsa_sig_parse(secp256k1_scalar *r, secp256k1_scalar *s, const unsigned char *sig, size_t size); +static int secp256k1_ecdsa_sig_serialize(unsigned char *sig, size_t *size, const secp256k1_scalar *r, const secp256k1_scalar *s); +static int secp256k1_ecdsa_sig_verify(const secp256k1_ecmult_context *ctx, const secp256k1_scalar* r, const secp256k1_scalar* s, const secp256k1_ge *pubkey, const secp256k1_scalar *message); +static int secp256k1_ecdsa_sig_sign(const secp256k1_ecmult_gen_context *ctx, secp256k1_scalar* r, secp256k1_scalar* s, const secp256k1_scalar *seckey, const secp256k1_scalar *message, const secp256k1_scalar *nonce, int *recid); + +#endif /* SECP256K1_ECDSA_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecdsa_impl.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecdsa_impl.h new file mode 100644 index 000000000..31a4c0d4a --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecdsa_impl.h @@ -0,0 +1,313 @@ +/********************************************************************** + * Copyright (c) 2013-2015 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + + +#ifndef SECP256K1_ECDSA_IMPL_H +#define SECP256K1_ECDSA_IMPL_H + +#include "scalar.h" +#include "field.h" +#include "group.h" +#include "ecmult.h" +#include "ecmult_gen.h" +#include "ecdsa.h" + +/** Group order for secp256k1 defined as 'n' in "Standards for Efficient Cryptography" (SEC2) 2.7.1 + * sage: for t in xrange(1023, -1, -1): + * .. p = 2**256 - 2**32 - t + * .. if p.is_prime(): + * .. print '%x'%p + * .. break + * 'fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f' + * sage: a = 0 + * sage: b = 7 + * sage: F = FiniteField (p) + * sage: '%x' % (EllipticCurve ([F (a), F (b)]).order()) + * 'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141' + */ +static const secp256k1_fe secp256k1_ecdsa_const_order_as_fe = SECP256K1_FE_CONST( + 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFEUL, + 0xBAAEDCE6UL, 0xAF48A03BUL, 0xBFD25E8CUL, 0xD0364141UL +); + +/** Difference between field and order, values 'p' and 'n' values defined in + * "Standards for Efficient Cryptography" (SEC2) 2.7.1. + * sage: p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F + * sage: a = 0 + * sage: b = 7 + * sage: F = FiniteField (p) + * sage: '%x' % (p - EllipticCurve ([F (a), F (b)]).order()) + * '14551231950b75fc4402da1722fc9baee' + */ +static const secp256k1_fe secp256k1_ecdsa_const_p_minus_order = SECP256K1_FE_CONST( + 0, 0, 0, 1, 0x45512319UL, 0x50B75FC4UL, 0x402DA172UL, 0x2FC9BAEEUL +); + +static int secp256k1_der_read_len(const unsigned char **sigp, const unsigned char *sigend) { + int lenleft, b1; + size_t ret = 0; + if (*sigp >= sigend) { + return -1; + } + b1 = *((*sigp)++); + if (b1 == 0xFF) { + /* X.690-0207 8.1.3.5.c the value 0xFF shall not be used. */ + return -1; + } + if ((b1 & 0x80) == 0) { + /* X.690-0207 8.1.3.4 short form length octets */ + return b1; + } + if (b1 == 0x80) { + /* Indefinite length is not allowed in DER. */ + return -1; + } + /* X.690-207 8.1.3.5 long form length octets */ + lenleft = b1 & 0x7F; + if (lenleft > sigend - *sigp) { + return -1; + } + if (**sigp == 0) { + /* Not the shortest possible length encoding. */ + return -1; + } + if ((size_t)lenleft > sizeof(size_t)) { + /* The resulting length would exceed the range of a size_t, so + * certainly longer than the passed array size. + */ + return -1; + } + while (lenleft > 0) { + ret = (ret << 8) | **sigp; + if (ret + lenleft > (size_t)(sigend - *sigp)) { + /* Result exceeds the length of the passed array. */ + return -1; + } + (*sigp)++; + lenleft--; + } + if (ret < 128) { + /* Not the shortest possible length encoding. */ + return -1; + } + return (int)ret; +} + +static int secp256k1_der_parse_integer(secp256k1_scalar *r, const unsigned char **sig, const unsigned char *sigend) { + int overflow = 0; + unsigned char ra[32] = {0}; + int rlen; + + if (*sig == sigend || **sig != 0x02) { + /* Not a primitive integer (X.690-0207 8.3.1). */ + return 0; + } + (*sig)++; + rlen = secp256k1_der_read_len(sig, sigend); + if (rlen <= 0 || (*sig) + rlen > sigend) { + /* Exceeds bounds or not at least length 1 (X.690-0207 8.3.1). */ + return 0; + } + if (**sig == 0x00 && rlen > 1 && (((*sig)[1]) & 0x80) == 0x00) { + /* Excessive 0x00 padding. */ + return 0; + } + if (**sig == 0xFF && rlen > 1 && (((*sig)[1]) & 0x80) == 0x80) { + /* Excessive 0xFF padding. */ + return 0; + } + if ((**sig & 0x80) == 0x80) { + /* Negative. */ + overflow = 1; + } + while (rlen > 0 && **sig == 0) { + /* Skip leading zero bytes */ + rlen--; + (*sig)++; + } + if (rlen > 32) { + overflow = 1; + } + if (!overflow) { + memcpy(ra + 32 - rlen, *sig, rlen); + secp256k1_scalar_set_b32(r, ra, &overflow); + } + if (overflow) { + secp256k1_scalar_set_int(r, 0); + } + (*sig) += rlen; + return 1; +} + +static int secp256k1_ecdsa_sig_parse(secp256k1_scalar *rr, secp256k1_scalar *rs, const unsigned char *sig, size_t size) { + const unsigned char *sigend = sig + size; + int rlen; + if (sig == sigend || *(sig++) != 0x30) { + /* The encoding doesn't start with a constructed sequence (X.690-0207 8.9.1). */ + return 0; + } + rlen = secp256k1_der_read_len(&sig, sigend); + if (rlen < 0 || sig + rlen > sigend) { + /* Tuple exceeds bounds */ + return 0; + } + if (sig + rlen != sigend) { + /* Garbage after tuple. */ + return 0; + } + + if (!secp256k1_der_parse_integer(rr, &sig, sigend)) { + return 0; + } + if (!secp256k1_der_parse_integer(rs, &sig, sigend)) { + return 0; + } + + if (sig != sigend) { + /* Trailing garbage inside tuple. */ + return 0; + } + + return 1; +} + +static int secp256k1_ecdsa_sig_serialize(unsigned char *sig, size_t *size, const secp256k1_scalar* ar, const secp256k1_scalar* as) { + unsigned char r[33] = {0}, s[33] = {0}; + unsigned char *rp = r, *sp = s; + size_t lenR = 33, lenS = 33; + secp256k1_scalar_get_b32(&r[1], ar); + secp256k1_scalar_get_b32(&s[1], as); + while (lenR > 1 && rp[0] == 0 && rp[1] < 0x80) { lenR--; rp++; } + while (lenS > 1 && sp[0] == 0 && sp[1] < 0x80) { lenS--; sp++; } + if (*size < 6+lenS+lenR) { + *size = 6 + lenS + lenR; + return 0; + } + *size = 6 + lenS + lenR; + sig[0] = 0x30; + sig[1] = 4 + lenS + lenR; + sig[2] = 0x02; + sig[3] = lenR; + memcpy(sig+4, rp, lenR); + sig[4+lenR] = 0x02; + sig[5+lenR] = lenS; + memcpy(sig+lenR+6, sp, lenS); + return 1; +} + +static int secp256k1_ecdsa_sig_verify(const secp256k1_ecmult_context *ctx, const secp256k1_scalar *sigr, const secp256k1_scalar *sigs, const secp256k1_ge *pubkey, const secp256k1_scalar *message) { + unsigned char c[32]; + secp256k1_scalar sn, u1, u2; +#if !defined(EXHAUSTIVE_TEST_ORDER) + secp256k1_fe xr; +#endif + secp256k1_gej pubkeyj; + secp256k1_gej pr; + + if (secp256k1_scalar_is_zero(sigr) || secp256k1_scalar_is_zero(sigs)) { + return 0; + } + + secp256k1_scalar_inverse_var(&sn, sigs); + secp256k1_scalar_mul(&u1, &sn, message); + secp256k1_scalar_mul(&u2, &sn, sigr); + secp256k1_gej_set_ge(&pubkeyj, pubkey); + secp256k1_ecmult(ctx, &pr, &pubkeyj, &u2, &u1); + if (secp256k1_gej_is_infinity(&pr)) { + return 0; + } + +#if defined(EXHAUSTIVE_TEST_ORDER) +{ + secp256k1_scalar computed_r; + secp256k1_ge pr_ge; + secp256k1_ge_set_gej(&pr_ge, &pr); + secp256k1_fe_normalize(&pr_ge.x); + + secp256k1_fe_get_b32(c, &pr_ge.x); + secp256k1_scalar_set_b32(&computed_r, c, NULL); + return secp256k1_scalar_eq(sigr, &computed_r); +} +#else + secp256k1_scalar_get_b32(c, sigr); + secp256k1_fe_set_b32(&xr, c); + + /** We now have the recomputed R point in pr, and its claimed x coordinate (modulo n) + * in xr. Naively, we would extract the x coordinate from pr (requiring a inversion modulo p), + * compute the remainder modulo n, and compare it to xr. However: + * + * xr == X(pr) mod n + * <=> exists h. (xr + h * n < p && xr + h * n == X(pr)) + * [Since 2 * n > p, h can only be 0 or 1] + * <=> (xr == X(pr)) || (xr + n < p && xr + n == X(pr)) + * [In Jacobian coordinates, X(pr) is pr.x / pr.z^2 mod p] + * <=> (xr == pr.x / pr.z^2 mod p) || (xr + n < p && xr + n == pr.x / pr.z^2 mod p) + * [Multiplying both sides of the equations by pr.z^2 mod p] + * <=> (xr * pr.z^2 mod p == pr.x) || (xr + n < p && (xr + n) * pr.z^2 mod p == pr.x) + * + * Thus, we can avoid the inversion, but we have to check both cases separately. + * secp256k1_gej_eq_x implements the (xr * pr.z^2 mod p == pr.x) test. + */ + if (secp256k1_gej_eq_x_var(&xr, &pr)) { + /* xr * pr.z^2 mod p == pr.x, so the signature is valid. */ + return 1; + } + if (secp256k1_fe_cmp_var(&xr, &secp256k1_ecdsa_const_p_minus_order) >= 0) { + /* xr + n >= p, so we can skip testing the second case. */ + return 0; + } + secp256k1_fe_add(&xr, &secp256k1_ecdsa_const_order_as_fe); + if (secp256k1_gej_eq_x_var(&xr, &pr)) { + /* (xr + n) * pr.z^2 mod p == pr.x, so the signature is valid. */ + return 1; + } + return 0; +#endif +} + +static int secp256k1_ecdsa_sig_sign(const secp256k1_ecmult_gen_context *ctx, secp256k1_scalar *sigr, secp256k1_scalar *sigs, const secp256k1_scalar *seckey, const secp256k1_scalar *message, const secp256k1_scalar *nonce, int *recid) { + unsigned char b[32]; + secp256k1_gej rp; + secp256k1_ge r; + secp256k1_scalar n; + int overflow = 0; + + secp256k1_ecmult_gen(ctx, &rp, nonce); + secp256k1_ge_set_gej(&r, &rp); + secp256k1_fe_normalize(&r.x); + secp256k1_fe_normalize(&r.y); + secp256k1_fe_get_b32(b, &r.x); + secp256k1_scalar_set_b32(sigr, b, &overflow); + /* These two conditions should be checked before calling */ + VERIFY_CHECK(!secp256k1_scalar_is_zero(sigr)); + VERIFY_CHECK(overflow == 0); + + if (recid) { + /* The overflow condition is cryptographically unreachable as hitting it requires finding the discrete log + * of some P where P.x >= order, and only 1 in about 2^127 points meet this criteria. + */ + *recid = (overflow ? 2 : 0) | (secp256k1_fe_is_odd(&r.y) ? 1 : 0); + } + secp256k1_scalar_mul(&n, sigr, seckey); + secp256k1_scalar_add(&n, &n, message); + secp256k1_scalar_inverse(sigs, nonce); + secp256k1_scalar_mul(sigs, sigs, &n); + secp256k1_scalar_clear(&n); + secp256k1_gej_clear(&rp); + secp256k1_ge_clear(&r); + if (secp256k1_scalar_is_zero(sigs)) { + return 0; + } + if (secp256k1_scalar_is_high(sigs)) { + secp256k1_scalar_negate(sigs, sigs); + if (recid) { + *recid ^= 1; + } + } + return 1; +} + +#endif /* SECP256K1_ECDSA_IMPL_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/eckey.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/eckey.h new file mode 100644 index 000000000..b621f1e6c --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/eckey.h @@ -0,0 +1,25 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECKEY_H +#define SECP256K1_ECKEY_H + +#include + +#include "group.h" +#include "scalar.h" +#include "ecmult.h" +#include "ecmult_gen.h" + +static int secp256k1_eckey_pubkey_parse(secp256k1_ge *elem, const unsigned char *pub, size_t size); +static int secp256k1_eckey_pubkey_serialize(secp256k1_ge *elem, unsigned char *pub, size_t *size, int compressed); + +static int secp256k1_eckey_privkey_tweak_add(secp256k1_scalar *key, const secp256k1_scalar *tweak); +static int secp256k1_eckey_pubkey_tweak_add(const secp256k1_ecmult_context *ctx, secp256k1_ge *key, const secp256k1_scalar *tweak); +static int secp256k1_eckey_privkey_tweak_mul(secp256k1_scalar *key, const secp256k1_scalar *tweak); +static int secp256k1_eckey_pubkey_tweak_mul(const secp256k1_ecmult_context *ctx, secp256k1_ge *key, const secp256k1_scalar *tweak); + +#endif /* SECP256K1_ECKEY_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/eckey_impl.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/eckey_impl.h new file mode 100644 index 000000000..1ab9a68ec --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/eckey_impl.h @@ -0,0 +1,100 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECKEY_IMPL_H +#define SECP256K1_ECKEY_IMPL_H + +#include "eckey.h" + +#include "scalar.h" +#include "field.h" +#include "group.h" +#include "ecmult_gen.h" + +static int secp256k1_eckey_pubkey_parse(secp256k1_ge *elem, const unsigned char *pub, size_t size) { + if (size == 33 && (pub[0] == SECP256K1_TAG_PUBKEY_EVEN || pub[0] == SECP256K1_TAG_PUBKEY_ODD)) { + secp256k1_fe x; + return secp256k1_fe_set_b32(&x, pub+1) && secp256k1_ge_set_xo_var(elem, &x, pub[0] == SECP256K1_TAG_PUBKEY_ODD); + } else if (size == 65 && (pub[0] == 0x04 || pub[0] == 0x06 || pub[0] == 0x07)) { + secp256k1_fe x, y; + if (!secp256k1_fe_set_b32(&x, pub+1) || !secp256k1_fe_set_b32(&y, pub+33)) { + return 0; + } + secp256k1_ge_set_xy(elem, &x, &y); + if ((pub[0] == SECP256K1_TAG_PUBKEY_HYBRID_EVEN || pub[0] == SECP256K1_TAG_PUBKEY_HYBRID_ODD) && + secp256k1_fe_is_odd(&y) != (pub[0] == SECP256K1_TAG_PUBKEY_HYBRID_ODD)) { + return 0; + } + return secp256k1_ge_is_valid_var(elem); + } else { + return 0; + } +} + +static int secp256k1_eckey_pubkey_serialize(secp256k1_ge *elem, unsigned char *pub, size_t *size, int compressed) { + if (secp256k1_ge_is_infinity(elem)) { + return 0; + } + secp256k1_fe_normalize_var(&elem->x); + secp256k1_fe_normalize_var(&elem->y); + secp256k1_fe_get_b32(&pub[1], &elem->x); + if (compressed) { + *size = 33; + pub[0] = secp256k1_fe_is_odd(&elem->y) ? SECP256K1_TAG_PUBKEY_ODD : SECP256K1_TAG_PUBKEY_EVEN; + } else { + *size = 65; + pub[0] = SECP256K1_TAG_PUBKEY_UNCOMPRESSED; + secp256k1_fe_get_b32(&pub[33], &elem->y); + } + return 1; +} + +static int secp256k1_eckey_privkey_tweak_add(secp256k1_scalar *key, const secp256k1_scalar *tweak) { + secp256k1_scalar_add(key, key, tweak); + if (secp256k1_scalar_is_zero(key)) { + return 0; + } + return 1; +} + +static int secp256k1_eckey_pubkey_tweak_add(const secp256k1_ecmult_context *ctx, secp256k1_ge *key, const secp256k1_scalar *tweak) { + secp256k1_gej pt; + secp256k1_scalar one; + secp256k1_gej_set_ge(&pt, key); + secp256k1_scalar_set_int(&one, 1); + secp256k1_ecmult(ctx, &pt, &pt, &one, tweak); + + if (secp256k1_gej_is_infinity(&pt)) { + return 0; + } + secp256k1_ge_set_gej(key, &pt); + return 1; +} + +static int secp256k1_eckey_privkey_tweak_mul(secp256k1_scalar *key, const secp256k1_scalar *tweak) { + if (secp256k1_scalar_is_zero(tweak)) { + return 0; + } + + secp256k1_scalar_mul(key, key, tweak); + return 1; +} + +static int secp256k1_eckey_pubkey_tweak_mul(const secp256k1_ecmult_context *ctx, secp256k1_ge *key, const secp256k1_scalar *tweak) { + secp256k1_scalar zero; + secp256k1_gej pt; + if (secp256k1_scalar_is_zero(tweak)) { + return 0; + } + + secp256k1_scalar_set_int(&zero, 0); + secp256k1_gej_set_ge(&pt, key); + secp256k1_ecmult(ctx, &pt, &pt, tweak, &zero); + secp256k1_ge_set_gej(key, &pt); + return 1; +} + +#endif /* SECP256K1_ECKEY_IMPL_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult.h new file mode 100644 index 000000000..ea1cd8a21 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult.h @@ -0,0 +1,47 @@ +/********************************************************************** + * Copyright (c) 2013, 2014, 2017 Pieter Wuille, Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECMULT_H +#define SECP256K1_ECMULT_H + +#include "num.h" +#include "group.h" +#include "scalar.h" +#include "scratch.h" + +typedef struct { + /* For accelerating the computation of a*P + b*G: */ + secp256k1_ge_storage (*pre_g)[]; /* odd multiples of the generator */ +#ifdef USE_ENDOMORPHISM + secp256k1_ge_storage (*pre_g_128)[]; /* odd multiples of 2^128*generator */ +#endif +} secp256k1_ecmult_context; + +static void secp256k1_ecmult_context_init(secp256k1_ecmult_context *ctx); +static void secp256k1_ecmult_context_build(secp256k1_ecmult_context *ctx, const secp256k1_callback *cb); +static void secp256k1_ecmult_context_clone(secp256k1_ecmult_context *dst, + const secp256k1_ecmult_context *src, const secp256k1_callback *cb); +static void secp256k1_ecmult_context_clear(secp256k1_ecmult_context *ctx); +static int secp256k1_ecmult_context_is_built(const secp256k1_ecmult_context *ctx); + +/** Double multiply: R = na*A + ng*G */ +static void secp256k1_ecmult(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_scalar *na, const secp256k1_scalar *ng); + +typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); + +/** + * Multi-multiply: R = inp_g_sc * G + sum_i ni * Ai. + * Chooses the right algorithm for a given number of points and scratch space + * size. Resets and overwrites the given scratch space. If the points do not + * fit in the scratch space the algorithm is repeatedly run with batches of + * points. + * Returns: 1 on success (including when inp_g_sc is NULL and n is 0) + * 0 if there is not enough scratch space for a single point or + * callback returns 0 + */ +static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); + +#endif /* SECP256K1_ECMULT_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult_const.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult_const.h new file mode 100644 index 000000000..d4804b8b6 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult_const.h @@ -0,0 +1,17 @@ +/********************************************************************** + * Copyright (c) 2015 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECMULT_CONST_H +#define SECP256K1_ECMULT_CONST_H + +#include "scalar.h" +#include "group.h" + +/* Here `bits` should be set to the maximum bitlength of the _absolute value_ of `q`, plus + * one because we internally sometimes add 2 to the number during the WNAF conversion. */ +static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, const secp256k1_scalar *q, int bits); + +#endif /* SECP256K1_ECMULT_CONST_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult_const_impl.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult_const_impl.h new file mode 100644 index 000000000..f4c36a1fa --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult_const_impl.h @@ -0,0 +1,257 @@ +/********************************************************************** + * Copyright (c) 2015 Pieter Wuille, Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECMULT_CONST_IMPL_H +#define SECP256K1_ECMULT_CONST_IMPL_H + +#include "scalar.h" +#include "group.h" +#include "ecmult_const.h" +#include "ecmult_impl.h" + +/* This is like `ECMULT_TABLE_GET_GE` but is constant time */ +#define ECMULT_CONST_TABLE_GET_GE(r,pre,n,w) do { \ + int m; \ + int abs_n = (n) * (((n) > 0) * 2 - 1); \ + int idx_n = abs_n / 2; \ + secp256k1_fe neg_y; \ + VERIFY_CHECK(((n) & 1) == 1); \ + VERIFY_CHECK((n) >= -((1 << ((w)-1)) - 1)); \ + VERIFY_CHECK((n) <= ((1 << ((w)-1)) - 1)); \ + VERIFY_SETUP(secp256k1_fe_clear(&(r)->x)); \ + VERIFY_SETUP(secp256k1_fe_clear(&(r)->y)); \ + for (m = 0; m < ECMULT_TABLE_SIZE(w); m++) { \ + /* This loop is used to avoid secret data in array indices. See + * the comment in ecmult_gen_impl.h for rationale. */ \ + secp256k1_fe_cmov(&(r)->x, &(pre)[m].x, m == idx_n); \ + secp256k1_fe_cmov(&(r)->y, &(pre)[m].y, m == idx_n); \ + } \ + (r)->infinity = 0; \ + secp256k1_fe_negate(&neg_y, &(r)->y, 1); \ + secp256k1_fe_cmov(&(r)->y, &neg_y, (n) != abs_n); \ +} while(0) + + +/** Convert a number to WNAF notation. + * The number becomes represented by sum(2^{wi} * wnaf[i], i=0..WNAF_SIZE(w)+1) - return_val. + * It has the following guarantees: + * - each wnaf[i] an odd integer between -(1 << w) and (1 << w) + * - each wnaf[i] is nonzero + * - the number of words set is always WNAF_SIZE(w) + 1 + * + * Adapted from `The Width-w NAF Method Provides Small Memory and Fast Elliptic Scalar + * Multiplications Secure against Side Channel Attacks`, Okeya and Tagaki. M. Joye (Ed.) + * CT-RSA 2003, LNCS 2612, pp. 328-443, 2003. Springer-Verlagy Berlin Heidelberg 2003 + * + * Numbers reference steps of `Algorithm SPA-resistant Width-w NAF with Odd Scalar` on pp. 335 + */ +static int secp256k1_wnaf_const(int *wnaf, secp256k1_scalar s, int w, int size) { + int global_sign; + int skew = 0; + int word = 0; + + /* 1 2 3 */ + int u_last; + int u = 0; + + int flip; + int bit; + secp256k1_scalar neg_s; + int not_neg_one; + /* Note that we cannot handle even numbers by negating them to be odd, as is + * done in other implementations, since if our scalars were specified to have + * width < 256 for performance reasons, their negations would have width 256 + * and we'd lose any performance benefit. Instead, we use a technique from + * Section 4.2 of the Okeya/Tagaki paper, which is to add either 1 (for even) + * or 2 (for odd) to the number we are encoding, returning a skew value indicating + * this, and having the caller compensate after doing the multiplication. + * + * In fact, we _do_ want to negate numbers to minimize their bit-lengths (and in + * particular, to ensure that the outputs from the endomorphism-split fit into + * 128 bits). If we negate, the parity of our number flips, inverting which of + * {1, 2} we want to add to the scalar when ensuring that it's odd. Further + * complicating things, -1 interacts badly with `secp256k1_scalar_cadd_bit` and + * we need to special-case it in this logic. */ + flip = secp256k1_scalar_is_high(&s); + /* We add 1 to even numbers, 2 to odd ones, noting that negation flips parity */ + bit = flip ^ !secp256k1_scalar_is_even(&s); + /* We check for negative one, since adding 2 to it will cause an overflow */ + secp256k1_scalar_negate(&neg_s, &s); + not_neg_one = !secp256k1_scalar_is_one(&neg_s); + secp256k1_scalar_cadd_bit(&s, bit, not_neg_one); + /* If we had negative one, flip == 1, s.d[0] == 0, bit == 1, so caller expects + * that we added two to it and flipped it. In fact for -1 these operations are + * identical. We only flipped, but since skewing is required (in the sense that + * the skew must be 1 or 2, never zero) and flipping is not, we need to change + * our flags to claim that we only skewed. */ + global_sign = secp256k1_scalar_cond_negate(&s, flip); + global_sign *= not_neg_one * 2 - 1; + skew = 1 << bit; + + /* 4 */ + u_last = secp256k1_scalar_shr_int(&s, w); + while (word * w < size) { + int sign; + int even; + + /* 4.1 4.4 */ + u = secp256k1_scalar_shr_int(&s, w); + /* 4.2 */ + even = ((u & 1) == 0); + sign = 2 * (u_last > 0) - 1; + u += sign * even; + u_last -= sign * even * (1 << w); + + /* 4.3, adapted for global sign change */ + wnaf[word++] = u_last * global_sign; + + u_last = u; + } + wnaf[word] = u * global_sign; + + VERIFY_CHECK(secp256k1_scalar_is_zero(&s)); + VERIFY_CHECK(word == WNAF_SIZE_BITS(size, w)); + return skew; +} + +static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, const secp256k1_scalar *scalar, int size) { + secp256k1_ge pre_a[ECMULT_TABLE_SIZE(WINDOW_A)]; + secp256k1_ge tmpa; + secp256k1_fe Z; + + int skew_1; +#ifdef USE_ENDOMORPHISM + secp256k1_ge pre_a_lam[ECMULT_TABLE_SIZE(WINDOW_A)]; + int wnaf_lam[1 + WNAF_SIZE(WINDOW_A - 1)]; + int skew_lam; + secp256k1_scalar q_1, q_lam; +#endif + int wnaf_1[1 + WNAF_SIZE(WINDOW_A - 1)]; + + int i; + secp256k1_scalar sc = *scalar; + + /* build wnaf representation for q. */ + int rsize = size; +#ifdef USE_ENDOMORPHISM + if (size > 128) { + rsize = 128; + /* split q into q_1 and q_lam (where q = q_1 + q_lam*lambda, and q_1 and q_lam are ~128 bit) */ + secp256k1_scalar_split_lambda(&q_1, &q_lam, &sc); + skew_1 = secp256k1_wnaf_const(wnaf_1, q_1, WINDOW_A - 1, 128); + skew_lam = secp256k1_wnaf_const(wnaf_lam, q_lam, WINDOW_A - 1, 128); + } else +#endif + { + skew_1 = secp256k1_wnaf_const(wnaf_1, sc, WINDOW_A - 1, size); +#ifdef USE_ENDOMORPHISM + skew_lam = 0; +#endif + } + + /* Calculate odd multiples of a. + * All multiples are brought to the same Z 'denominator', which is stored + * in Z. Due to secp256k1' isomorphism we can do all operations pretending + * that the Z coordinate was 1, use affine addition formulae, and correct + * the Z coordinate of the result once at the end. + */ + secp256k1_gej_set_ge(r, a); + secp256k1_ecmult_odd_multiples_table_globalz_windowa(pre_a, &Z, r); + for (i = 0; i < ECMULT_TABLE_SIZE(WINDOW_A); i++) { + secp256k1_fe_normalize_weak(&pre_a[i].y); + } +#ifdef USE_ENDOMORPHISM + if (size > 128) { + for (i = 0; i < ECMULT_TABLE_SIZE(WINDOW_A); i++) { + secp256k1_ge_mul_lambda(&pre_a_lam[i], &pre_a[i]); + } + } +#endif + + /* first loop iteration (separated out so we can directly set r, rather + * than having it start at infinity, get doubled several times, then have + * its new value added to it) */ + i = wnaf_1[WNAF_SIZE_BITS(rsize, WINDOW_A - 1)]; + VERIFY_CHECK(i != 0); + ECMULT_CONST_TABLE_GET_GE(&tmpa, pre_a, i, WINDOW_A); + secp256k1_gej_set_ge(r, &tmpa); +#ifdef USE_ENDOMORPHISM + if (size > 128) { + i = wnaf_lam[WNAF_SIZE_BITS(rsize, WINDOW_A - 1)]; + VERIFY_CHECK(i != 0); + ECMULT_CONST_TABLE_GET_GE(&tmpa, pre_a_lam, i, WINDOW_A); + secp256k1_gej_add_ge(r, r, &tmpa); + } +#endif + /* remaining loop iterations */ + for (i = WNAF_SIZE_BITS(rsize, WINDOW_A - 1) - 1; i >= 0; i--) { + int n; + int j; + for (j = 0; j < WINDOW_A - 1; ++j) { + secp256k1_gej_double_nonzero(r, r, NULL); + } + + n = wnaf_1[i]; + ECMULT_CONST_TABLE_GET_GE(&tmpa, pre_a, n, WINDOW_A); + VERIFY_CHECK(n != 0); + secp256k1_gej_add_ge(r, r, &tmpa); +#ifdef USE_ENDOMORPHISM + if (size > 128) { + n = wnaf_lam[i]; + ECMULT_CONST_TABLE_GET_GE(&tmpa, pre_a_lam, n, WINDOW_A); + VERIFY_CHECK(n != 0); + secp256k1_gej_add_ge(r, r, &tmpa); + } +#endif + } + + secp256k1_fe_mul(&r->z, &r->z, &Z); + + { + /* Correct for wNAF skew */ + secp256k1_ge correction = *a; + secp256k1_ge_storage correction_1_stor; +#ifdef USE_ENDOMORPHISM + secp256k1_ge_storage correction_lam_stor; +#endif + secp256k1_ge_storage a2_stor; + secp256k1_gej tmpj; + secp256k1_gej_set_ge(&tmpj, &correction); + secp256k1_gej_double_var(&tmpj, &tmpj, NULL); + secp256k1_ge_set_gej(&correction, &tmpj); + secp256k1_ge_to_storage(&correction_1_stor, a); +#ifdef USE_ENDOMORPHISM + if (size > 128) { + secp256k1_ge_to_storage(&correction_lam_stor, a); + } +#endif + secp256k1_ge_to_storage(&a2_stor, &correction); + + /* For odd numbers this is 2a (so replace it), for even ones a (so no-op) */ + secp256k1_ge_storage_cmov(&correction_1_stor, &a2_stor, skew_1 == 2); +#ifdef USE_ENDOMORPHISM + if (size > 128) { + secp256k1_ge_storage_cmov(&correction_lam_stor, &a2_stor, skew_lam == 2); + } +#endif + + /* Apply the correction */ + secp256k1_ge_from_storage(&correction, &correction_1_stor); + secp256k1_ge_neg(&correction, &correction); + secp256k1_gej_add_ge(r, r, &correction); + +#ifdef USE_ENDOMORPHISM + if (size > 128) { + secp256k1_ge_from_storage(&correction, &correction_lam_stor); + secp256k1_ge_neg(&correction, &correction); + secp256k1_ge_mul_lambda(&correction, &correction); + secp256k1_gej_add_ge(r, r, &correction); + } +#endif + } +} + +#endif /* SECP256K1_ECMULT_CONST_IMPL_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult_gen.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult_gen.h new file mode 100644 index 000000000..7564b7015 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult_gen.h @@ -0,0 +1,43 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECMULT_GEN_H +#define SECP256K1_ECMULT_GEN_H + +#include "scalar.h" +#include "group.h" + +typedef struct { + /* For accelerating the computation of a*G: + * To harden against timing attacks, use the following mechanism: + * * Break up the multiplicand into groups of 4 bits, called n_0, n_1, n_2, ..., n_63. + * * Compute sum(n_i * 16^i * G + U_i, i=0..63), where: + * * U_i = U * 2^i (for i=0..62) + * * U_i = U * (1-2^63) (for i=63) + * where U is a point with no known corresponding scalar. Note that sum(U_i, i=0..63) = 0. + * For each i, and each of the 16 possible values of n_i, (n_i * 16^i * G + U_i) is + * precomputed (call it prec(i, n_i)). The formula now becomes sum(prec(i, n_i), i=0..63). + * None of the resulting prec group elements have a known scalar, and neither do any of + * the intermediate sums while computing a*G. + */ + secp256k1_ge_storage (*prec)[64][16]; /* prec[j][i] = 16^j * i * G + U_i */ + secp256k1_scalar blind; + secp256k1_gej initial; +} secp256k1_ecmult_gen_context; + +static void secp256k1_ecmult_gen_context_init(secp256k1_ecmult_gen_context* ctx); +static void secp256k1_ecmult_gen_context_build(secp256k1_ecmult_gen_context* ctx, const secp256k1_callback* cb); +static void secp256k1_ecmult_gen_context_clone(secp256k1_ecmult_gen_context *dst, + const secp256k1_ecmult_gen_context* src, const secp256k1_callback* cb); +static void secp256k1_ecmult_gen_context_clear(secp256k1_ecmult_gen_context* ctx); +static int secp256k1_ecmult_gen_context_is_built(const secp256k1_ecmult_gen_context* ctx); + +/** Multiply with the generator: R = a*G */ +static void secp256k1_ecmult_gen(const secp256k1_ecmult_gen_context* ctx, secp256k1_gej *r, const secp256k1_scalar *a); + +static void secp256k1_ecmult_gen_blind(secp256k1_ecmult_gen_context *ctx, const unsigned char *seed32); + +#endif /* SECP256K1_ECMULT_GEN_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult_gen_impl.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult_gen_impl.h new file mode 100644 index 000000000..f99be8c92 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult_gen_impl.h @@ -0,0 +1,210 @@ +/********************************************************************** + * Copyright (c) 2013, 2014, 2015 Pieter Wuille, Gregory Maxwell * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECMULT_GEN_IMPL_H +#define SECP256K1_ECMULT_GEN_IMPL_H + +#include "scalar.h" +#include "group.h" +#include "ecmult_gen.h" +#include "hash_impl.h" +#ifdef USE_ECMULT_STATIC_PRECOMPUTATION +#include "secp256k1_ec_mult_static_context.h" +#endif +static void secp256k1_ecmult_gen_context_init(secp256k1_ecmult_gen_context *ctx) { + ctx->prec = NULL; +} + +static void secp256k1_ecmult_gen_context_build(secp256k1_ecmult_gen_context *ctx, const secp256k1_callback* cb) { +#ifndef USE_ECMULT_STATIC_PRECOMPUTATION + secp256k1_ge prec[1024]; + secp256k1_gej gj; + secp256k1_gej nums_gej; + int i, j; +#endif + + if (ctx->prec != NULL) { + return; + } +#ifndef USE_ECMULT_STATIC_PRECOMPUTATION + ctx->prec = (secp256k1_ge_storage (*)[64][16])checked_malloc(cb, sizeof(*ctx->prec)); + + /* get the generator */ + secp256k1_gej_set_ge(&gj, &secp256k1_ge_const_g); + + /* Construct a group element with no known corresponding scalar (nothing up my sleeve). */ + { + static const unsigned char nums_b32[33] = "The scalar for this x is unknown"; + secp256k1_fe nums_x; + secp256k1_ge nums_ge; + int r; + r = secp256k1_fe_set_b32(&nums_x, nums_b32); + (void)r; + VERIFY_CHECK(r); + r = secp256k1_ge_set_xo_var(&nums_ge, &nums_x, 0); + (void)r; + VERIFY_CHECK(r); + secp256k1_gej_set_ge(&nums_gej, &nums_ge); + /* Add G to make the bits in x uniformly distributed. */ + secp256k1_gej_add_ge_var(&nums_gej, &nums_gej, &secp256k1_ge_const_g, NULL); + } + + /* compute prec. */ + { + secp256k1_gej precj[1024]; /* Jacobian versions of prec. */ + secp256k1_gej gbase; + secp256k1_gej numsbase; + gbase = gj; /* 16^j * G */ + numsbase = nums_gej; /* 2^j * nums. */ + for (j = 0; j < 64; j++) { + /* Set precj[j*16 .. j*16+15] to (numsbase, numsbase + gbase, ..., numsbase + 15*gbase). */ + precj[j*16] = numsbase; + for (i = 1; i < 16; i++) { + secp256k1_gej_add_var(&precj[j*16 + i], &precj[j*16 + i - 1], &gbase, NULL); + } + /* Multiply gbase by 16. */ + for (i = 0; i < 4; i++) { + secp256k1_gej_double_var(&gbase, &gbase, NULL); + } + /* Multiply numbase by 2. */ + secp256k1_gej_double_var(&numsbase, &numsbase, NULL); + if (j == 62) { + /* In the last iteration, numsbase is (1 - 2^j) * nums instead. */ + secp256k1_gej_neg(&numsbase, &numsbase); + secp256k1_gej_add_var(&numsbase, &numsbase, &nums_gej, NULL); + } + } + secp256k1_ge_set_all_gej_var(prec, precj, 1024, cb); + } + for (j = 0; j < 64; j++) { + for (i = 0; i < 16; i++) { + secp256k1_ge_to_storage(&(*ctx->prec)[j][i], &prec[j*16 + i]); + } + } +#else + (void)cb; + ctx->prec = (secp256k1_ge_storage (*)[64][16])secp256k1_ecmult_static_context; +#endif + secp256k1_ecmult_gen_blind(ctx, NULL); +} + +static int secp256k1_ecmult_gen_context_is_built(const secp256k1_ecmult_gen_context* ctx) { + return ctx->prec != NULL; +} + +static void secp256k1_ecmult_gen_context_clone(secp256k1_ecmult_gen_context *dst, + const secp256k1_ecmult_gen_context *src, const secp256k1_callback* cb) { + if (src->prec == NULL) { + dst->prec = NULL; + } else { +#ifndef USE_ECMULT_STATIC_PRECOMPUTATION + dst->prec = (secp256k1_ge_storage (*)[64][16])checked_malloc(cb, sizeof(*dst->prec)); + memcpy(dst->prec, src->prec, sizeof(*dst->prec)); +#else + (void)cb; + dst->prec = src->prec; +#endif + dst->initial = src->initial; + dst->blind = src->blind; + } +} + +static void secp256k1_ecmult_gen_context_clear(secp256k1_ecmult_gen_context *ctx) { +#ifndef USE_ECMULT_STATIC_PRECOMPUTATION + free(ctx->prec); +#endif + secp256k1_scalar_clear(&ctx->blind); + secp256k1_gej_clear(&ctx->initial); + ctx->prec = NULL; +} + +static void secp256k1_ecmult_gen(const secp256k1_ecmult_gen_context *ctx, secp256k1_gej *r, const secp256k1_scalar *gn) { + secp256k1_ge add; + secp256k1_ge_storage adds; + secp256k1_scalar gnb; + int bits; + int i, j; + memset(&adds, 0, sizeof(adds)); + *r = ctx->initial; + /* Blind scalar/point multiplication by computing (n-b)G + bG instead of nG. */ + secp256k1_scalar_add(&gnb, gn, &ctx->blind); + add.infinity = 0; + for (j = 0; j < 64; j++) { + bits = secp256k1_scalar_get_bits(&gnb, j * 4, 4); + for (i = 0; i < 16; i++) { + /** This uses a conditional move to avoid any secret data in array indexes. + * _Any_ use of secret indexes has been demonstrated to result in timing + * sidechannels, even when the cache-line access patterns are uniform. + * See also: + * "A word of warning", CHES 2013 Rump Session, by Daniel J. Bernstein and Peter Schwabe + * (https://cryptojedi.org/peter/data/chesrump-20130822.pdf) and + * "Cache Attacks and Countermeasures: the Case of AES", RSA 2006, + * by Dag Arne Osvik, Adi Shamir, and Eran Tromer + * (http://www.tau.ac.il/~tromer/papers/cache.pdf) + */ + secp256k1_ge_storage_cmov(&adds, &(*ctx->prec)[j][i], i == bits); + } + secp256k1_ge_from_storage(&add, &adds); + secp256k1_gej_add_ge(r, r, &add); + } + bits = 0; + secp256k1_ge_clear(&add); + secp256k1_scalar_clear(&gnb); +} + +/* Setup blinding values for secp256k1_ecmult_gen. */ +static void secp256k1_ecmult_gen_blind(secp256k1_ecmult_gen_context *ctx, const unsigned char *seed32) { + secp256k1_scalar b; + secp256k1_gej gb; + secp256k1_fe s; + unsigned char nonce32[32]; + secp256k1_rfc6979_hmac_sha256 rng; + int retry; + unsigned char keydata[64] = {0}; + if (seed32 == NULL) { + /* When seed is NULL, reset the initial point and blinding value. */ + secp256k1_gej_set_ge(&ctx->initial, &secp256k1_ge_const_g); + secp256k1_gej_neg(&ctx->initial, &ctx->initial); + secp256k1_scalar_set_int(&ctx->blind, 1); + } + /* The prior blinding value (if not reset) is chained forward by including it in the hash. */ + secp256k1_scalar_get_b32(nonce32, &ctx->blind); + /** Using a CSPRNG allows a failure free interface, avoids needing large amounts of random data, + * and guards against weak or adversarial seeds. This is a simpler and safer interface than + * asking the caller for blinding values directly and expecting them to retry on failure. + */ + memcpy(keydata, nonce32, 32); + if (seed32 != NULL) { + memcpy(keydata + 32, seed32, 32); + } + secp256k1_rfc6979_hmac_sha256_initialize(&rng, keydata, seed32 ? 64 : 32); + memset(keydata, 0, sizeof(keydata)); + /* Retry for out of range results to achieve uniformity. */ + do { + secp256k1_rfc6979_hmac_sha256_generate(&rng, nonce32, 32); + retry = !secp256k1_fe_set_b32(&s, nonce32); + retry |= secp256k1_fe_is_zero(&s); + } while (retry); /* This branch true is cryptographically unreachable. Requires sha256_hmac output > Fp. */ + /* Randomize the projection to defend against multiplier sidechannels. */ + secp256k1_gej_rescale(&ctx->initial, &s); + secp256k1_fe_clear(&s); + do { + secp256k1_rfc6979_hmac_sha256_generate(&rng, nonce32, 32); + secp256k1_scalar_set_b32(&b, nonce32, &retry); + /* A blinding value of 0 works, but would undermine the projection hardening. */ + retry |= secp256k1_scalar_is_zero(&b); + } while (retry); /* This branch true is cryptographically unreachable. Requires sha256_hmac output > order. */ + secp256k1_rfc6979_hmac_sha256_finalize(&rng); + memset(nonce32, 0, 32); + secp256k1_ecmult_gen(ctx, &gb, &b); + secp256k1_scalar_negate(&b, &b); + ctx->blind = b; + ctx->initial = gb; + secp256k1_scalar_clear(&b); + secp256k1_gej_clear(&gb); +} + +#endif /* SECP256K1_ECMULT_GEN_IMPL_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult_impl.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult_impl.h new file mode 100644 index 000000000..feab1b741 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/ecmult_impl.h @@ -0,0 +1,1027 @@ +/***************************************************************************** + * Copyright (c) 2013, 2014, 2017 Pieter Wuille, Andrew Poelstra, Jonas Nick * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php. * + *****************************************************************************/ + +#ifndef SECP256K1_ECMULT_IMPL_H +#define SECP256K1_ECMULT_IMPL_H + +#include +#include + +#include "group.h" +#include "scalar.h" +#include "ecmult.h" + +#if defined(EXHAUSTIVE_TEST_ORDER) +/* We need to lower these values for exhaustive tests because + * the tables cannot have infinities in them (this breaks the + * affine-isomorphism stuff which tracks z-ratios) */ +# if EXHAUSTIVE_TEST_ORDER > 128 +# define WINDOW_A 5 +# define WINDOW_G 8 +# elif EXHAUSTIVE_TEST_ORDER > 8 +# define WINDOW_A 4 +# define WINDOW_G 4 +# else +# define WINDOW_A 2 +# define WINDOW_G 2 +# endif +#else +/* optimal for 128-bit and 256-bit exponents. */ +#define WINDOW_A 5 +/** larger numbers may result in slightly better performance, at the cost of + exponentially larger precomputed tables. */ +#ifdef USE_ENDOMORPHISM +/** Two tables for window size 15: 1.375 MiB. */ +#define WINDOW_G 15 +#else +/** One table for window size 16: 1.375 MiB. */ +#define WINDOW_G 16 +#endif +#endif + +#ifdef USE_ENDOMORPHISM + #define WNAF_BITS 128 +#else + #define WNAF_BITS 256 +#endif +#define WNAF_SIZE_BITS(bits, w) (((bits) + (w) - 1) / (w)) +#define WNAF_SIZE(w) WNAF_SIZE_BITS(WNAF_BITS, w) + +/** The number of entries a table with precomputed multiples needs to have. */ +#define ECMULT_TABLE_SIZE(w) (1 << ((w)-2)) + +/* The number of objects allocated on the scratch space for ecmult_multi algorithms */ +#define PIPPENGER_SCRATCH_OBJECTS 6 +#define STRAUSS_SCRATCH_OBJECTS 6 + +#define PIPPENGER_MAX_BUCKET_WINDOW 12 + +/* Minimum number of points for which pippenger_wnaf is faster than strauss wnaf */ +#ifdef USE_ENDOMORPHISM + #define ECMULT_PIPPENGER_THRESHOLD 88 +#else + #define ECMULT_PIPPENGER_THRESHOLD 160 +#endif + +#ifdef USE_ENDOMORPHISM + #define ECMULT_MAX_POINTS_PER_BATCH 5000000 +#else + #define ECMULT_MAX_POINTS_PER_BATCH 10000000 +#endif + +/** Fill a table 'prej' with precomputed odd multiples of a. Prej will contain + * the values [1*a,3*a,...,(2*n-1)*a], so it space for n values. zr[0] will + * contain prej[0].z / a.z. The other zr[i] values = prej[i].z / prej[i-1].z. + * Prej's Z values are undefined, except for the last value. + */ +static void secp256k1_ecmult_odd_multiples_table(int n, secp256k1_gej *prej, secp256k1_fe *zr, const secp256k1_gej *a) { + secp256k1_gej d; + secp256k1_ge a_ge, d_ge; + int i; + + VERIFY_CHECK(!a->infinity); + + secp256k1_gej_double_var(&d, a, NULL); + + /* + * Perform the additions on an isomorphism where 'd' is affine: drop the z coordinate + * of 'd', and scale the 1P starting value's x/y coordinates without changing its z. + */ + d_ge.x = d.x; + d_ge.y = d.y; + d_ge.infinity = 0; + + secp256k1_ge_set_gej_zinv(&a_ge, a, &d.z); + prej[0].x = a_ge.x; + prej[0].y = a_ge.y; + prej[0].z = a->z; + prej[0].infinity = 0; + + zr[0] = d.z; + for (i = 1; i < n; i++) { + secp256k1_gej_add_ge_var(&prej[i], &prej[i-1], &d_ge, &zr[i]); + } + + /* + * Each point in 'prej' has a z coordinate too small by a factor of 'd.z'. Only + * the final point's z coordinate is actually used though, so just update that. + */ + secp256k1_fe_mul(&prej[n-1].z, &prej[n-1].z, &d.z); +} + +/** Fill a table 'pre' with precomputed odd multiples of a. + * + * There are two versions of this function: + * - secp256k1_ecmult_odd_multiples_table_globalz_windowa which brings its + * resulting point set to a single constant Z denominator, stores the X and Y + * coordinates as ge_storage points in pre, and stores the global Z in rz. + * It only operates on tables sized for WINDOW_A wnaf multiples. + * - secp256k1_ecmult_odd_multiples_table_storage_var, which converts its + * resulting point set to actually affine points, and stores those in pre. + * It operates on tables of any size, but uses heap-allocated temporaries. + * + * To compute a*P + b*G, we compute a table for P using the first function, + * and for G using the second (which requires an inverse, but it only needs to + * happen once). + */ +static void secp256k1_ecmult_odd_multiples_table_globalz_windowa(secp256k1_ge *pre, secp256k1_fe *globalz, const secp256k1_gej *a) { + secp256k1_gej prej[ECMULT_TABLE_SIZE(WINDOW_A)]; + secp256k1_fe zr[ECMULT_TABLE_SIZE(WINDOW_A)]; + + /* Compute the odd multiples in Jacobian form. */ + secp256k1_ecmult_odd_multiples_table(ECMULT_TABLE_SIZE(WINDOW_A), prej, zr, a); + /* Bring them to the same Z denominator. */ + secp256k1_ge_globalz_set_table_gej(ECMULT_TABLE_SIZE(WINDOW_A), pre, globalz, prej, zr); +} + +static void secp256k1_ecmult_odd_multiples_table_storage_var(int n, secp256k1_ge_storage *pre, const secp256k1_gej *a, const secp256k1_callback *cb) { + secp256k1_gej *prej = (secp256k1_gej*)checked_malloc(cb, sizeof(secp256k1_gej) * n); + secp256k1_ge *prea = (secp256k1_ge*)checked_malloc(cb, sizeof(secp256k1_ge) * n); + secp256k1_fe *zr = (secp256k1_fe*)checked_malloc(cb, sizeof(secp256k1_fe) * n); + int i; + + /* Compute the odd multiples in Jacobian form. */ + secp256k1_ecmult_odd_multiples_table(n, prej, zr, a); + /* Convert them in batch to affine coordinates. */ + secp256k1_ge_set_table_gej_var(prea, prej, zr, n); + /* Convert them to compact storage form. */ + for (i = 0; i < n; i++) { + secp256k1_ge_to_storage(&pre[i], &prea[i]); + } + + free(prea); + free(prej); + free(zr); +} + +/** The following two macro retrieves a particular odd multiple from a table + * of precomputed multiples. */ +#define ECMULT_TABLE_GET_GE(r,pre,n,w) do { \ + VERIFY_CHECK(((n) & 1) == 1); \ + VERIFY_CHECK((n) >= -((1 << ((w)-1)) - 1)); \ + VERIFY_CHECK((n) <= ((1 << ((w)-1)) - 1)); \ + if ((n) > 0) { \ + *(r) = (pre)[((n)-1)/2]; \ + } else { \ + secp256k1_ge_neg((r), &(pre)[(-(n)-1)/2]); \ + } \ +} while(0) + +#define ECMULT_TABLE_GET_GE_STORAGE(r,pre,n,w) do { \ + VERIFY_CHECK(((n) & 1) == 1); \ + VERIFY_CHECK((n) >= -((1 << ((w)-1)) - 1)); \ + VERIFY_CHECK((n) <= ((1 << ((w)-1)) - 1)); \ + if ((n) > 0) { \ + secp256k1_ge_from_storage((r), &(pre)[((n)-1)/2]); \ + } else { \ + secp256k1_ge_from_storage((r), &(pre)[(-(n)-1)/2]); \ + secp256k1_ge_neg((r), (r)); \ + } \ +} while(0) + +static void secp256k1_ecmult_context_init(secp256k1_ecmult_context *ctx) { + ctx->pre_g = NULL; +#ifdef USE_ENDOMORPHISM + ctx->pre_g_128 = NULL; +#endif +} + +static void secp256k1_ecmult_context_build(secp256k1_ecmult_context *ctx, const secp256k1_callback *cb) { + secp256k1_gej gj; + + if (ctx->pre_g != NULL) { + return; + } + + /* get the generator */ + secp256k1_gej_set_ge(&gj, &secp256k1_ge_const_g); + + ctx->pre_g = (secp256k1_ge_storage (*)[])checked_malloc(cb, sizeof((*ctx->pre_g)[0]) * ECMULT_TABLE_SIZE(WINDOW_G)); + + /* precompute the tables with odd multiples */ + secp256k1_ecmult_odd_multiples_table_storage_var(ECMULT_TABLE_SIZE(WINDOW_G), *ctx->pre_g, &gj, cb); + +#ifdef USE_ENDOMORPHISM + { + secp256k1_gej g_128j; + int i; + + ctx->pre_g_128 = (secp256k1_ge_storage (*)[])checked_malloc(cb, sizeof((*ctx->pre_g_128)[0]) * ECMULT_TABLE_SIZE(WINDOW_G)); + + /* calculate 2^128*generator */ + g_128j = gj; + for (i = 0; i < 128; i++) { + secp256k1_gej_double_var(&g_128j, &g_128j, NULL); + } + secp256k1_ecmult_odd_multiples_table_storage_var(ECMULT_TABLE_SIZE(WINDOW_G), *ctx->pre_g_128, &g_128j, cb); + } +#endif +} + +static void secp256k1_ecmult_context_clone(secp256k1_ecmult_context *dst, + const secp256k1_ecmult_context *src, const secp256k1_callback *cb) { + if (src->pre_g == NULL) { + dst->pre_g = NULL; + } else { + size_t size = sizeof((*dst->pre_g)[0]) * ECMULT_TABLE_SIZE(WINDOW_G); + dst->pre_g = (secp256k1_ge_storage (*)[])checked_malloc(cb, size); + memcpy(dst->pre_g, src->pre_g, size); + } +#ifdef USE_ENDOMORPHISM + if (src->pre_g_128 == NULL) { + dst->pre_g_128 = NULL; + } else { + size_t size = sizeof((*dst->pre_g_128)[0]) * ECMULT_TABLE_SIZE(WINDOW_G); + dst->pre_g_128 = (secp256k1_ge_storage (*)[])checked_malloc(cb, size); + memcpy(dst->pre_g_128, src->pre_g_128, size); + } +#endif +} + +static int secp256k1_ecmult_context_is_built(const secp256k1_ecmult_context *ctx) { + return ctx->pre_g != NULL; +} + +static void secp256k1_ecmult_context_clear(secp256k1_ecmult_context *ctx) { + free(ctx->pre_g); +#ifdef USE_ENDOMORPHISM + free(ctx->pre_g_128); +#endif + secp256k1_ecmult_context_init(ctx); +} + +/** Convert a number to WNAF notation. The number becomes represented by sum(2^i * wnaf[i], i=0..bits), + * with the following guarantees: + * - each wnaf[i] is either 0, or an odd integer between -(1<<(w-1) - 1) and (1<<(w-1) - 1) + * - two non-zero entries in wnaf are separated by at least w-1 zeroes. + * - the number of set values in wnaf is returned. This number is at most 256, and at most one more + * than the number of bits in the (absolute value) of the input. + */ +static int secp256k1_ecmult_wnaf(int *wnaf, int len, const secp256k1_scalar *a, int w) { + secp256k1_scalar s = *a; + int last_set_bit = -1; + int bit = 0; + int sign = 1; + int carry = 0; + + VERIFY_CHECK(wnaf != NULL); + VERIFY_CHECK(0 <= len && len <= 256); + VERIFY_CHECK(a != NULL); + VERIFY_CHECK(2 <= w && w <= 31); + + memset(wnaf, 0, len * sizeof(wnaf[0])); + + if (secp256k1_scalar_get_bits(&s, 255, 1)) { + secp256k1_scalar_negate(&s, &s); + sign = -1; + } + + while (bit < len) { + int now; + int word; + if (secp256k1_scalar_get_bits(&s, bit, 1) == (unsigned int)carry) { + bit++; + continue; + } + + now = w; + if (now > len - bit) { + now = len - bit; + } + + word = secp256k1_scalar_get_bits_var(&s, bit, now) + carry; + + carry = (word >> (w-1)) & 1; + word -= carry << w; + + wnaf[bit] = sign * word; + last_set_bit = bit; + + bit += now; + } +#ifdef VERIFY + CHECK(carry == 0); + while (bit < 256) { + CHECK(secp256k1_scalar_get_bits(&s, bit++, 1) == 0); + } +#endif + return last_set_bit + 1; +} + +struct secp256k1_strauss_point_state { +#ifdef USE_ENDOMORPHISM + secp256k1_scalar na_1, na_lam; + int wnaf_na_1[130]; + int wnaf_na_lam[130]; + int bits_na_1; + int bits_na_lam; +#else + int wnaf_na[256]; + int bits_na; +#endif + size_t input_pos; +}; + +struct secp256k1_strauss_state { + secp256k1_gej* prej; + secp256k1_fe* zr; + secp256k1_ge* pre_a; +#ifdef USE_ENDOMORPHISM + secp256k1_ge* pre_a_lam; +#endif + struct secp256k1_strauss_point_state* ps; +}; + +static void secp256k1_ecmult_strauss_wnaf(const secp256k1_ecmult_context *ctx, const struct secp256k1_strauss_state *state, secp256k1_gej *r, int num, const secp256k1_gej *a, const secp256k1_scalar *na, const secp256k1_scalar *ng) { + secp256k1_ge tmpa; + secp256k1_fe Z; +#ifdef USE_ENDOMORPHISM + /* Splitted G factors. */ + secp256k1_scalar ng_1, ng_128; + int wnaf_ng_1[129]; + int bits_ng_1 = 0; + int wnaf_ng_128[129]; + int bits_ng_128 = 0; +#else + int wnaf_ng[256]; + int bits_ng = 0; +#endif + int i; + int bits = 0; + int np; + int no = 0; + + for (np = 0; np < num; ++np) { + if (secp256k1_scalar_is_zero(&na[np]) || secp256k1_gej_is_infinity(&a[np])) { + continue; + } + state->ps[no].input_pos = np; +#ifdef USE_ENDOMORPHISM + /* split na into na_1 and na_lam (where na = na_1 + na_lam*lambda, and na_1 and na_lam are ~128 bit) */ + secp256k1_scalar_split_lambda(&state->ps[no].na_1, &state->ps[no].na_lam, &na[np]); + + /* build wnaf representation for na_1 and na_lam. */ + state->ps[no].bits_na_1 = secp256k1_ecmult_wnaf(state->ps[no].wnaf_na_1, 130, &state->ps[no].na_1, WINDOW_A); + state->ps[no].bits_na_lam = secp256k1_ecmult_wnaf(state->ps[no].wnaf_na_lam, 130, &state->ps[no].na_lam, WINDOW_A); + VERIFY_CHECK(state->ps[no].bits_na_1 <= 130); + VERIFY_CHECK(state->ps[no].bits_na_lam <= 130); + if (state->ps[no].bits_na_1 > bits) { + bits = state->ps[no].bits_na_1; + } + if (state->ps[no].bits_na_lam > bits) { + bits = state->ps[no].bits_na_lam; + } +#else + /* build wnaf representation for na. */ + state->ps[no].bits_na = secp256k1_ecmult_wnaf(state->ps[no].wnaf_na, 256, &na[np], WINDOW_A); + if (state->ps[no].bits_na > bits) { + bits = state->ps[no].bits_na; + } +#endif + ++no; + } + + /* Calculate odd multiples of a. + * All multiples are brought to the same Z 'denominator', which is stored + * in Z. Due to secp256k1' isomorphism we can do all operations pretending + * that the Z coordinate was 1, use affine addition formulae, and correct + * the Z coordinate of the result once at the end. + * The exception is the precomputed G table points, which are actually + * affine. Compared to the base used for other points, they have a Z ratio + * of 1/Z, so we can use secp256k1_gej_add_zinv_var, which uses the same + * isomorphism to efficiently add with a known Z inverse. + */ + if (no > 0) { + /* Compute the odd multiples in Jacobian form. */ + secp256k1_ecmult_odd_multiples_table(ECMULT_TABLE_SIZE(WINDOW_A), state->prej, state->zr, &a[state->ps[0].input_pos]); + for (np = 1; np < no; ++np) { + secp256k1_gej tmp = a[state->ps[np].input_pos]; +#ifdef VERIFY + secp256k1_fe_normalize_var(&(state->prej[(np - 1) * ECMULT_TABLE_SIZE(WINDOW_A) + ECMULT_TABLE_SIZE(WINDOW_A) - 1].z)); +#endif + secp256k1_gej_rescale(&tmp, &(state->prej[(np - 1) * ECMULT_TABLE_SIZE(WINDOW_A) + ECMULT_TABLE_SIZE(WINDOW_A) - 1].z)); + secp256k1_ecmult_odd_multiples_table(ECMULT_TABLE_SIZE(WINDOW_A), state->prej + np * ECMULT_TABLE_SIZE(WINDOW_A), state->zr + np * ECMULT_TABLE_SIZE(WINDOW_A), &tmp); + secp256k1_fe_mul(state->zr + np * ECMULT_TABLE_SIZE(WINDOW_A), state->zr + np * ECMULT_TABLE_SIZE(WINDOW_A), &(a[state->ps[np].input_pos].z)); + } + /* Bring them to the same Z denominator. */ + secp256k1_ge_globalz_set_table_gej(ECMULT_TABLE_SIZE(WINDOW_A) * no, state->pre_a, &Z, state->prej, state->zr); + } else { + secp256k1_fe_set_int(&Z, 1); + } + +#ifdef USE_ENDOMORPHISM + for (np = 0; np < no; ++np) { + for (i = 0; i < ECMULT_TABLE_SIZE(WINDOW_A); i++) { + secp256k1_ge_mul_lambda(&state->pre_a_lam[np * ECMULT_TABLE_SIZE(WINDOW_A) + i], &state->pre_a[np * ECMULT_TABLE_SIZE(WINDOW_A) + i]); + } + } + + if (ng) { + /* split ng into ng_1 and ng_128 (where gn = gn_1 + gn_128*2^128, and gn_1 and gn_128 are ~128 bit) */ + secp256k1_scalar_split_128(&ng_1, &ng_128, ng); + + /* Build wnaf representation for ng_1 and ng_128 */ + bits_ng_1 = secp256k1_ecmult_wnaf(wnaf_ng_1, 129, &ng_1, WINDOW_G); + bits_ng_128 = secp256k1_ecmult_wnaf(wnaf_ng_128, 129, &ng_128, WINDOW_G); + if (bits_ng_1 > bits) { + bits = bits_ng_1; + } + if (bits_ng_128 > bits) { + bits = bits_ng_128; + } + } +#else + if (ng) { + bits_ng = secp256k1_ecmult_wnaf(wnaf_ng, 256, ng, WINDOW_G); + if (bits_ng > bits) { + bits = bits_ng; + } + } +#endif + + secp256k1_gej_set_infinity(r); + + for (i = bits - 1; i >= 0; i--) { + int n; + secp256k1_gej_double_var(r, r, NULL); +#ifdef USE_ENDOMORPHISM + for (np = 0; np < no; ++np) { + if (i < state->ps[np].bits_na_1 && (n = state->ps[np].wnaf_na_1[i])) { + ECMULT_TABLE_GET_GE(&tmpa, state->pre_a + np * ECMULT_TABLE_SIZE(WINDOW_A), n, WINDOW_A); + secp256k1_gej_add_ge_var(r, r, &tmpa, NULL); + } + if (i < state->ps[np].bits_na_lam && (n = state->ps[np].wnaf_na_lam[i])) { + ECMULT_TABLE_GET_GE(&tmpa, state->pre_a_lam + np * ECMULT_TABLE_SIZE(WINDOW_A), n, WINDOW_A); + secp256k1_gej_add_ge_var(r, r, &tmpa, NULL); + } + } + if (i < bits_ng_1 && (n = wnaf_ng_1[i])) { + ECMULT_TABLE_GET_GE_STORAGE(&tmpa, *ctx->pre_g, n, WINDOW_G); + secp256k1_gej_add_zinv_var(r, r, &tmpa, &Z); + } + if (i < bits_ng_128 && (n = wnaf_ng_128[i])) { + ECMULT_TABLE_GET_GE_STORAGE(&tmpa, *ctx->pre_g_128, n, WINDOW_G); + secp256k1_gej_add_zinv_var(r, r, &tmpa, &Z); + } +#else + for (np = 0; np < no; ++np) { + if (i < state->ps[np].bits_na && (n = state->ps[np].wnaf_na[i])) { + ECMULT_TABLE_GET_GE(&tmpa, state->pre_a + np * ECMULT_TABLE_SIZE(WINDOW_A), n, WINDOW_A); + secp256k1_gej_add_ge_var(r, r, &tmpa, NULL); + } + } + if (i < bits_ng && (n = wnaf_ng[i])) { + ECMULT_TABLE_GET_GE_STORAGE(&tmpa, *ctx->pre_g, n, WINDOW_G); + secp256k1_gej_add_zinv_var(r, r, &tmpa, &Z); + } +#endif + } + + if (!r->infinity) { + secp256k1_fe_mul(&r->z, &r->z, &Z); + } +} + +static void secp256k1_ecmult(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_scalar *na, const secp256k1_scalar *ng) { + secp256k1_gej prej[ECMULT_TABLE_SIZE(WINDOW_A)]; + secp256k1_fe zr[ECMULT_TABLE_SIZE(WINDOW_A)]; + secp256k1_ge pre_a[ECMULT_TABLE_SIZE(WINDOW_A)]; + struct secp256k1_strauss_point_state ps[1]; +#ifdef USE_ENDOMORPHISM + secp256k1_ge pre_a_lam[ECMULT_TABLE_SIZE(WINDOW_A)]; +#endif + struct secp256k1_strauss_state state; + + state.prej = prej; + state.zr = zr; + state.pre_a = pre_a; +#ifdef USE_ENDOMORPHISM + state.pre_a_lam = pre_a_lam; +#endif + state.ps = ps; + secp256k1_ecmult_strauss_wnaf(ctx, &state, r, 1, a, na, ng); +} + +static size_t secp256k1_strauss_scratch_size(size_t n_points) { +#ifdef USE_ENDOMORPHISM + static const size_t point_size = (2 * sizeof(secp256k1_ge) + sizeof(secp256k1_gej) + sizeof(secp256k1_fe)) * ECMULT_TABLE_SIZE(WINDOW_A) + sizeof(struct secp256k1_strauss_point_state) + sizeof(secp256k1_gej) + sizeof(secp256k1_scalar); +#else + static const size_t point_size = (sizeof(secp256k1_ge) + sizeof(secp256k1_gej) + sizeof(secp256k1_fe)) * ECMULT_TABLE_SIZE(WINDOW_A) + sizeof(struct secp256k1_strauss_point_state) + sizeof(secp256k1_gej) + sizeof(secp256k1_scalar); +#endif + return n_points*point_size; +} + +static int secp256k1_ecmult_strauss_batch(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n_points, size_t cb_offset) { + secp256k1_gej* points; + secp256k1_scalar* scalars; + struct secp256k1_strauss_state state; + size_t i; + + secp256k1_gej_set_infinity(r); + if (inp_g_sc == NULL && n_points == 0) { + return 1; + } + + if (!secp256k1_scratch_allocate_frame(scratch, secp256k1_strauss_scratch_size(n_points), STRAUSS_SCRATCH_OBJECTS)) { + return 0; + } + points = (secp256k1_gej*)secp256k1_scratch_alloc(scratch, n_points * sizeof(secp256k1_gej)); + scalars = (secp256k1_scalar*)secp256k1_scratch_alloc(scratch, n_points * sizeof(secp256k1_scalar)); + state.prej = (secp256k1_gej*)secp256k1_scratch_alloc(scratch, n_points * ECMULT_TABLE_SIZE(WINDOW_A) * sizeof(secp256k1_gej)); + state.zr = (secp256k1_fe*)secp256k1_scratch_alloc(scratch, n_points * ECMULT_TABLE_SIZE(WINDOW_A) * sizeof(secp256k1_fe)); +#ifdef USE_ENDOMORPHISM + state.pre_a = (secp256k1_ge*)secp256k1_scratch_alloc(scratch, n_points * 2 * ECMULT_TABLE_SIZE(WINDOW_A) * sizeof(secp256k1_ge)); + state.pre_a_lam = state.pre_a + n_points * ECMULT_TABLE_SIZE(WINDOW_A); +#else + state.pre_a = (secp256k1_ge*)secp256k1_scratch_alloc(scratch, n_points * ECMULT_TABLE_SIZE(WINDOW_A) * sizeof(secp256k1_ge)); +#endif + state.ps = (struct secp256k1_strauss_point_state*)secp256k1_scratch_alloc(scratch, n_points * sizeof(struct secp256k1_strauss_point_state)); + + for (i = 0; i < n_points; i++) { + secp256k1_ge point; + if (!cb(&scalars[i], &point, i+cb_offset, cbdata)) { + secp256k1_scratch_deallocate_frame(scratch); + return 0; + } + secp256k1_gej_set_ge(&points[i], &point); + } + secp256k1_ecmult_strauss_wnaf(ctx, &state, r, (int)n_points, points, scalars, inp_g_sc); + secp256k1_scratch_deallocate_frame(scratch); + return 1; +} + +/* Wrapper for secp256k1_ecmult_multi_func interface */ +static int secp256k1_ecmult_strauss_batch_single(const secp256k1_ecmult_context *actx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) { + return secp256k1_ecmult_strauss_batch(actx, scratch, r, inp_g_sc, cb, cbdata, n, 0); +} + +static size_t secp256k1_strauss_max_points(secp256k1_scratch *scratch) { + return secp256k1_scratch_max_allocation(scratch, STRAUSS_SCRATCH_OBJECTS) / secp256k1_strauss_scratch_size(1); +} + +/** Convert a number to WNAF notation. + * The number becomes represented by sum(2^{wi} * wnaf[i], i=0..WNAF_SIZE(w)+1) - return_val. + * It has the following guarantees: + * - each wnaf[i] is either 0 or an odd integer between -(1 << w) and (1 << w) + * - the number of words set is always WNAF_SIZE(w) + * - the returned skew is 0 or 1 + */ +static int secp256k1_wnaf_fixed(int *wnaf, const secp256k1_scalar *s, int w) { + int skew = 0; + int pos; + int max_pos; + int last_w; + const secp256k1_scalar *work = s; + + if (secp256k1_scalar_is_zero(s)) { + for (pos = 0; pos < WNAF_SIZE(w); pos++) { + wnaf[pos] = 0; + } + return 0; + } + + if (secp256k1_scalar_is_even(s)) { + skew = 1; + } + + wnaf[0] = secp256k1_scalar_get_bits_var(work, 0, w) + skew; + /* Compute last window size. Relevant when window size doesn't divide the + * number of bits in the scalar */ + last_w = WNAF_BITS - (WNAF_SIZE(w) - 1) * w; + + /* Store the position of the first nonzero word in max_pos to allow + * skipping leading zeros when calculating the wnaf. */ + for (pos = WNAF_SIZE(w) - 1; pos > 0; pos--) { + int val = secp256k1_scalar_get_bits_var(work, pos * w, pos == WNAF_SIZE(w)-1 ? last_w : w); + if(val != 0) { + break; + } + wnaf[pos] = 0; + } + max_pos = pos; + pos = 1; + + while (pos <= max_pos) { + int val = secp256k1_scalar_get_bits_var(work, pos * w, pos == WNAF_SIZE(w)-1 ? last_w : w); + if ((val & 1) == 0) { + wnaf[pos - 1] -= (1 << w); + wnaf[pos] = (val + 1); + } else { + wnaf[pos] = val; + } + /* Set a coefficient to zero if it is 1 or -1 and the proceeding digit + * is strictly negative or strictly positive respectively. Only change + * coefficients at previous positions because above code assumes that + * wnaf[pos - 1] is odd. + */ + if (pos >= 2 && ((wnaf[pos - 1] == 1 && wnaf[pos - 2] < 0) || (wnaf[pos - 1] == -1 && wnaf[pos - 2] > 0))) { + if (wnaf[pos - 1] == 1) { + wnaf[pos - 2] += 1 << w; + } else { + wnaf[pos - 2] -= 1 << w; + } + wnaf[pos - 1] = 0; + } + ++pos; + } + + return skew; +} + +struct secp256k1_pippenger_point_state { + int skew_na; + size_t input_pos; +}; + +struct secp256k1_pippenger_state { + int *wnaf_na; + struct secp256k1_pippenger_point_state* ps; +}; + +/* + * pippenger_wnaf computes the result of a multi-point multiplication as + * follows: The scalars are brought into wnaf with n_wnaf elements each. Then + * for every i < n_wnaf, first each point is added to a "bucket" corresponding + * to the point's wnaf[i]. Second, the buckets are added together such that + * r += 1*bucket[0] + 3*bucket[1] + 5*bucket[2] + ... + */ +static int secp256k1_ecmult_pippenger_wnaf(secp256k1_gej *buckets, int bucket_window, struct secp256k1_pippenger_state *state, secp256k1_gej *r, const secp256k1_scalar *sc, const secp256k1_ge *pt, size_t num) { + size_t n_wnaf = WNAF_SIZE(bucket_window+1); + size_t np; + size_t no = 0; + int i; + int j; + + for (np = 0; np < num; ++np) { + if (secp256k1_scalar_is_zero(&sc[np]) || secp256k1_ge_is_infinity(&pt[np])) { + continue; + } + state->ps[no].input_pos = np; + state->ps[no].skew_na = secp256k1_wnaf_fixed(&state->wnaf_na[no*n_wnaf], &sc[np], bucket_window+1); + no++; + } + secp256k1_gej_set_infinity(r); + + if (no == 0) { + return 1; + } + + for (i = (int)n_wnaf - 1; i >= 0; i--) { + secp256k1_gej running_sum; + + for(j = 0; j < ECMULT_TABLE_SIZE(bucket_window+2); j++) { + secp256k1_gej_set_infinity(&buckets[j]); + } + + for (np = 0; np < no; ++np) { + int n = state->wnaf_na[np*n_wnaf + i]; + struct secp256k1_pippenger_point_state point_state = state->ps[np]; + secp256k1_ge tmp; + int idx; + + if (i == 0) { + /* correct for wnaf skew */ + int skew = point_state.skew_na; + if (skew) { + secp256k1_ge_neg(&tmp, &pt[point_state.input_pos]); + secp256k1_gej_add_ge_var(&buckets[0], &buckets[0], &tmp, NULL); + } + } + if (n > 0) { + idx = (n - 1)/2; + secp256k1_gej_add_ge_var(&buckets[idx], &buckets[idx], &pt[point_state.input_pos], NULL); + } else if (n < 0) { + idx = -(n + 1)/2; + secp256k1_ge_neg(&tmp, &pt[point_state.input_pos]); + secp256k1_gej_add_ge_var(&buckets[idx], &buckets[idx], &tmp, NULL); + } + } + + for(j = 0; j < bucket_window; j++) { + secp256k1_gej_double_var(r, r, NULL); + } + + secp256k1_gej_set_infinity(&running_sum); + /* Accumulate the sum: bucket[0] + 3*bucket[1] + 5*bucket[2] + 7*bucket[3] + ... + * = bucket[0] + bucket[1] + bucket[2] + bucket[3] + ... + * + 2 * (bucket[1] + 2*bucket[2] + 3*bucket[3] + ...) + * using an intermediate running sum: + * running_sum = bucket[0] + bucket[1] + bucket[2] + ... + * + * The doubling is done implicitly by deferring the final window doubling (of 'r'). + */ + for(j = ECMULT_TABLE_SIZE(bucket_window+2) - 1; j > 0; j--) { + secp256k1_gej_add_var(&running_sum, &running_sum, &buckets[j], NULL); + secp256k1_gej_add_var(r, r, &running_sum, NULL); + } + + secp256k1_gej_add_var(&running_sum, &running_sum, &buckets[0], NULL); + secp256k1_gej_double_var(r, r, NULL); + secp256k1_gej_add_var(r, r, &running_sum, NULL); + } + return 1; +} + +/** + * Returns optimal bucket_window (number of bits of a scalar represented by a + * set of buckets) for a given number of points. + */ +static int secp256k1_pippenger_bucket_window(size_t n) { +#ifdef USE_ENDOMORPHISM + if (n <= 1) { + return 1; + } else if (n <= 4) { + return 2; + } else if (n <= 20) { + return 3; + } else if (n <= 57) { + return 4; + } else if (n <= 136) { + return 5; + } else if (n <= 235) { + return 6; + } else if (n <= 1260) { + return 7; + } else if (n <= 4420) { + return 9; + } else if (n <= 7880) { + return 10; + } else if (n <= 16050) { + return 11; + } else { + return PIPPENGER_MAX_BUCKET_WINDOW; + } +#else + if (n <= 1) { + return 1; + } else if (n <= 11) { + return 2; + } else if (n <= 45) { + return 3; + } else if (n <= 100) { + return 4; + } else if (n <= 275) { + return 5; + } else if (n <= 625) { + return 6; + } else if (n <= 1850) { + return 7; + } else if (n <= 3400) { + return 8; + } else if (n <= 9630) { + return 9; + } else if (n <= 17900) { + return 10; + } else if (n <= 32800) { + return 11; + } else { + return PIPPENGER_MAX_BUCKET_WINDOW; + } +#endif +} + +/** + * Returns the maximum optimal number of points for a bucket_window. + */ +static size_t secp256k1_pippenger_bucket_window_inv(int bucket_window) { + switch(bucket_window) { +#ifdef USE_ENDOMORPHISM + case 1: return 1; + case 2: return 4; + case 3: return 20; + case 4: return 57; + case 5: return 136; + case 6: return 235; + case 7: return 1260; + case 8: return 1260; + case 9: return 4420; + case 10: return 7880; + case 11: return 16050; + case PIPPENGER_MAX_BUCKET_WINDOW: return SIZE_MAX; +#else + case 1: return 1; + case 2: return 11; + case 3: return 45; + case 4: return 100; + case 5: return 275; + case 6: return 625; + case 7: return 1850; + case 8: return 3400; + case 9: return 9630; + case 10: return 17900; + case 11: return 32800; + case PIPPENGER_MAX_BUCKET_WINDOW: return SIZE_MAX; +#endif + } + return 0; +} + + +#ifdef USE_ENDOMORPHISM +SECP256K1_INLINE static void secp256k1_ecmult_endo_split(secp256k1_scalar *s1, secp256k1_scalar *s2, secp256k1_ge *p1, secp256k1_ge *p2) { + secp256k1_scalar tmp = *s1; + secp256k1_scalar_split_lambda(s1, s2, &tmp); + secp256k1_ge_mul_lambda(p2, p1); + + if (secp256k1_scalar_is_high(s1)) { + secp256k1_scalar_negate(s1, s1); + secp256k1_ge_neg(p1, p1); + } + if (secp256k1_scalar_is_high(s2)) { + secp256k1_scalar_negate(s2, s2); + secp256k1_ge_neg(p2, p2); + } +} +#endif + +/** + * Returns the scratch size required for a given number of points (excluding + * base point G) without considering alignment. + */ +static size_t secp256k1_pippenger_scratch_size(size_t n_points, int bucket_window) { +#ifdef USE_ENDOMORPHISM + size_t entries = 2*n_points + 2; +#else + size_t entries = n_points + 1; +#endif + size_t entry_size = sizeof(secp256k1_ge) + sizeof(secp256k1_scalar) + sizeof(struct secp256k1_pippenger_point_state) + (WNAF_SIZE(bucket_window+1)+1)*sizeof(int); + return ((1<ps = (struct secp256k1_pippenger_point_state *) secp256k1_scratch_alloc(scratch, entries * sizeof(*state_space->ps)); + state_space->wnaf_na = (int *) secp256k1_scratch_alloc(scratch, entries*(WNAF_SIZE(bucket_window+1)) * sizeof(int)); + buckets = (secp256k1_gej *) secp256k1_scratch_alloc(scratch, (1<ps[i].skew_na = 0; + for(j = 0; j < WNAF_SIZE(bucket_window+1); j++) { + state_space->wnaf_na[i * WNAF_SIZE(bucket_window+1) + j] = 0; + } + } + for(i = 0; i < 1< max_alloc) { + break; + } + space_for_points = max_alloc - space_overhead; + + n_points = space_for_points/entry_size; + n_points = n_points > max_points ? max_points : n_points; + if (n_points > res) { + res = n_points; + } + if (n_points < max_points) { + /* A larger bucket_window may support even more points. But if we + * would choose that then the caller couldn't safely use any number + * smaller than what this function returns */ + break; + } + } + return res; +} + +typedef int (*secp256k1_ecmult_multi_func)(const secp256k1_ecmult_context*, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t); +static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) { + size_t i; + + int (*f)(const secp256k1_ecmult_context*, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t, size_t); + size_t max_points; + size_t n_batches; + size_t n_batch_points; + + secp256k1_gej_set_infinity(r); + if (inp_g_sc == NULL && n == 0) { + return 1; + } else if (n == 0) { + secp256k1_scalar szero; + secp256k1_scalar_set_int(&szero, 0); + secp256k1_ecmult(ctx, r, r, &szero, inp_g_sc); + return 1; + } + + max_points = secp256k1_pippenger_max_points(scratch); + if (max_points == 0) { + return 0; + } else if (max_points > ECMULT_MAX_POINTS_PER_BATCH) { + max_points = ECMULT_MAX_POINTS_PER_BATCH; + } + n_batches = (n+max_points-1)/max_points; + n_batch_points = (n+n_batches-1)/n_batches; + + if (n_batch_points >= ECMULT_PIPPENGER_THRESHOLD) { + f = secp256k1_ecmult_pippenger_batch; + } else { + max_points = secp256k1_strauss_max_points(scratch); + if (max_points == 0) { + return 0; + } + n_batches = (n+max_points-1)/max_points; + n_batch_points = (n+n_batches-1)/n_batches; + f = secp256k1_ecmult_strauss_batch; + } + for(i = 0; i < n_batches; i++) { + size_t nbp = n < n_batch_points ? n : n_batch_points; + size_t offset = n_batch_points*i; + secp256k1_gej tmp; + if (!f(ctx, scratch, &tmp, i == 0 ? inp_g_sc : NULL, cb, cbdata, nbp, offset)) { + return 0; + } + secp256k1_gej_add_var(r, r, &tmp, NULL); + n -= nbp; + } + return 1; +} + +#endif /* SECP256K1_ECMULT_IMPL_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field.h new file mode 100644 index 000000000..ce3aa462c --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field.h @@ -0,0 +1,130 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_FIELD_H +#define SECP256K1_FIELD_H + +/** Field element module. + * + * Field elements can be represented in several ways, but code accessing + * it (and implementations) need to take certain properties into account: + * - Each field element can be normalized or not. + * - Each field element has a magnitude, which represents how far away + * its representation is away from normalization. Normalized elements + * always have a magnitude of 1, but a magnitude of 1 doesn't imply + * normality. + */ + +#include "secp256k1-config.h" + +#if defined(USE_FIELD_10X26) +#include "field_10x26.h" +#elif defined(USE_FIELD_5X52) +#include "field_5x52.h" +#else +#error "Please select field implementation" +#endif + +#include "util.h" + +/** Normalize a field element. */ +static void secp256k1_fe_normalize(secp256k1_fe *r); + +/** Weakly normalize a field element: reduce it magnitude to 1, but don't fully normalize. */ +static void secp256k1_fe_normalize_weak(secp256k1_fe *r); + +/** Normalize a field element, without constant-time guarantee. */ +static void secp256k1_fe_normalize_var(secp256k1_fe *r); + +/** Verify whether a field element represents zero i.e. would normalize to a zero value. The field + * implementation may optionally normalize the input, but this should not be relied upon. */ +static int secp256k1_fe_normalizes_to_zero(secp256k1_fe *r); + +/** Verify whether a field element represents zero i.e. would normalize to a zero value. The field + * implementation may optionally normalize the input, but this should not be relied upon. */ +static int secp256k1_fe_normalizes_to_zero_var(secp256k1_fe *r); + +/** Set a field element equal to a small integer. Resulting field element is normalized. */ +static void secp256k1_fe_set_int(secp256k1_fe *r, int a); + +/** Sets a field element equal to zero, initializing all fields. */ +static void secp256k1_fe_clear(secp256k1_fe *a); + +/** Verify whether a field element is zero. Requires the input to be normalized. */ +static int secp256k1_fe_is_zero(const secp256k1_fe *a); + +/** Check the "oddness" of a field element. Requires the input to be normalized. */ +static int secp256k1_fe_is_odd(const secp256k1_fe *a); + +/** Compare two field elements. Requires magnitude-1 inputs. */ +static int secp256k1_fe_equal(const secp256k1_fe *a, const secp256k1_fe *b); + +/** Same as secp256k1_fe_equal, but may be variable time. */ +static int secp256k1_fe_equal_var(const secp256k1_fe *a, const secp256k1_fe *b); + +/** Compare two field elements. Requires both inputs to be normalized */ +static int secp256k1_fe_cmp_var(const secp256k1_fe *a, const secp256k1_fe *b); + +/** Set a field element equal to 32-byte big endian value. If successful, the resulting field element is normalized. */ +static int secp256k1_fe_set_b32(secp256k1_fe *r, const unsigned char *a); + +/** Convert a field element to a 32-byte big endian value. Requires the input to be normalized */ +static void secp256k1_fe_get_b32(unsigned char *r, const secp256k1_fe *a); + +/** Set a field element equal to the additive inverse of another. Takes a maximum magnitude of the input + * as an argument. The magnitude of the output is one higher. */ +static void secp256k1_fe_negate(secp256k1_fe *r, const secp256k1_fe *a, int m); + +/** Multiplies the passed field element with a small integer constant. Multiplies the magnitude by that + * small integer. */ +static void secp256k1_fe_mul_int(secp256k1_fe *r, int a); + +/** Adds a field element to another. The result has the sum of the inputs' magnitudes as magnitude. */ +static void secp256k1_fe_add(secp256k1_fe *r, const secp256k1_fe *a); + +/** Sets a field element to be the product of two others. Requires the inputs' magnitudes to be at most 8. + * The output magnitude is 1 (but not guaranteed to be normalized). */ +static void secp256k1_fe_mul(secp256k1_fe *r, const secp256k1_fe *a, const secp256k1_fe * SECP256K1_RESTRICT b); + +/** Sets a field element to be the square of another. Requires the input's magnitude to be at most 8. + * The output magnitude is 1 (but not guaranteed to be normalized). */ +static void secp256k1_fe_sqr(secp256k1_fe *r, const secp256k1_fe *a); + +/** If a has a square root, it is computed in r and 1 is returned. If a does not + * have a square root, the root of its negation is computed and 0 is returned. + * The input's magnitude can be at most 8. The output magnitude is 1 (but not + * guaranteed to be normalized). The result in r will always be a square + * itself. */ +static int secp256k1_fe_sqrt(secp256k1_fe *r, const secp256k1_fe *a); + +/** Checks whether a field element is a quadratic residue. */ +static int secp256k1_fe_is_quad_var(const secp256k1_fe *a); + +/** Sets a field element to be the (modular) inverse of another. Requires the input's magnitude to be + * at most 8. The output magnitude is 1 (but not guaranteed to be normalized). */ +static void secp256k1_fe_inv(secp256k1_fe *r, const secp256k1_fe *a); + +/** Potentially faster version of secp256k1_fe_inv, without constant-time guarantee. */ +static void secp256k1_fe_inv_var(secp256k1_fe *r, const secp256k1_fe *a); + +/** Calculate the (modular) inverses of a batch of field elements. Requires the inputs' magnitudes to be + * at most 8. The output magnitudes are 1 (but not guaranteed to be normalized). The inputs and + * outputs must not overlap in memory. */ +static void secp256k1_fe_inv_all_var(secp256k1_fe *r, const secp256k1_fe *a, size_t len); + +/** Convert a field element to the storage type. */ +static void secp256k1_fe_to_storage(secp256k1_fe_storage *r, const secp256k1_fe *a); + +/** Convert a field element back from the storage type. */ +static void secp256k1_fe_from_storage(secp256k1_fe *r, const secp256k1_fe_storage *a); + +/** If flag is true, set *r equal to *a; otherwise leave it. Constant-time. */ +static void secp256k1_fe_storage_cmov(secp256k1_fe_storage *r, const secp256k1_fe_storage *a, int flag); + +/** If flag is true, set *r equal to *a; otherwise leave it. Constant-time. */ +static void secp256k1_fe_cmov(secp256k1_fe *r, const secp256k1_fe *a, int flag); + +#endif /* SECP256K1_FIELD_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_10x26.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_10x26.h new file mode 100644 index 000000000..727c5267f --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_10x26.h @@ -0,0 +1,48 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_FIELD_REPR_H +#define SECP256K1_FIELD_REPR_H + +#include + +typedef struct { + /* X = sum(i=0..9, elem[i]*2^26) mod n */ + uint32_t n[10]; +#ifdef VERIFY + int magnitude; + int normalized; +#endif +} secp256k1_fe; + +/* Unpacks a constant into a overlapping multi-limbed FE element. */ +#define SECP256K1_FE_CONST_INNER(d7, d6, d5, d4, d3, d2, d1, d0) { \ + (d0) & 0x3FFFFFFUL, \ + (((uint32_t)d0) >> 26) | (((uint32_t)(d1) & 0xFFFFFUL) << 6), \ + (((uint32_t)d1) >> 20) | (((uint32_t)(d2) & 0x3FFFUL) << 12), \ + (((uint32_t)d2) >> 14) | (((uint32_t)(d3) & 0xFFUL) << 18), \ + (((uint32_t)d3) >> 8) | (((uint32_t)(d4) & 0x3UL) << 24), \ + (((uint32_t)d4) >> 2) & 0x3FFFFFFUL, \ + (((uint32_t)d4) >> 28) | (((uint32_t)(d5) & 0x3FFFFFUL) << 4), \ + (((uint32_t)d5) >> 22) | (((uint32_t)(d6) & 0xFFFFUL) << 10), \ + (((uint32_t)d6) >> 16) | (((uint32_t)(d7) & 0x3FFUL) << 16), \ + (((uint32_t)d7) >> 10) \ +} + +#ifdef VERIFY +#define SECP256K1_FE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {SECP256K1_FE_CONST_INNER((d7), (d6), (d5), (d4), (d3), (d2), (d1), (d0)), 1, 1} +#else +#define SECP256K1_FE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {SECP256K1_FE_CONST_INNER((d7), (d6), (d5), (d4), (d3), (d2), (d1), (d0))} +#endif + +typedef struct { + uint32_t n[8]; +} secp256k1_fe_storage; + +#define SECP256K1_FE_STORAGE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{ (d0), (d1), (d2), (d3), (d4), (d5), (d6), (d7) }} +#define SECP256K1_FE_STORAGE_CONST_GET(d) d.n[7], d.n[6], d.n[5], d.n[4],d.n[3], d.n[2], d.n[1], d.n[0] + +#endif /* SECP256K1_FIELD_REPR_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_10x26_impl.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_10x26_impl.h new file mode 100644 index 000000000..06be299c4 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_10x26_impl.h @@ -0,0 +1,1161 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_FIELD_REPR_IMPL_H +#define SECP256K1_FIELD_REPR_IMPL_H + +#include "util.h" +#include "num.h" +#include "field.h" + +#ifdef VERIFY +static void secp256k1_fe_verify(const secp256k1_fe *a) { + const uint32_t *d = a->n; + int m = a->normalized ? 1 : 2 * a->magnitude, r = 1; + r &= (d[0] <= 0x3FFFFFFUL * m); + r &= (d[1] <= 0x3FFFFFFUL * m); + r &= (d[2] <= 0x3FFFFFFUL * m); + r &= (d[3] <= 0x3FFFFFFUL * m); + r &= (d[4] <= 0x3FFFFFFUL * m); + r &= (d[5] <= 0x3FFFFFFUL * m); + r &= (d[6] <= 0x3FFFFFFUL * m); + r &= (d[7] <= 0x3FFFFFFUL * m); + r &= (d[8] <= 0x3FFFFFFUL * m); + r &= (d[9] <= 0x03FFFFFUL * m); + r &= (a->magnitude >= 0); + r &= (a->magnitude <= 32); + if (a->normalized) { + r &= (a->magnitude <= 1); + if (r && (d[9] == 0x03FFFFFUL)) { + uint32_t mid = d[8] & d[7] & d[6] & d[5] & d[4] & d[3] & d[2]; + if (mid == 0x3FFFFFFUL) { + r &= ((d[1] + 0x40UL + ((d[0] + 0x3D1UL) >> 26)) <= 0x3FFFFFFUL); + } + } + } + VERIFY_CHECK(r == 1); +} +#endif + +static void secp256k1_fe_normalize(secp256k1_fe *r) { + uint32_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4], + t5 = r->n[5], t6 = r->n[6], t7 = r->n[7], t8 = r->n[8], t9 = r->n[9]; + + /* Reduce t9 at the start so there will be at most a single carry from the first pass */ + uint32_t m; + uint32_t x = t9 >> 22; t9 &= 0x03FFFFFUL; + + /* The first pass ensures the magnitude is 1, ... */ + t0 += x * 0x3D1UL; t1 += (x << 6); + t1 += (t0 >> 26); t0 &= 0x3FFFFFFUL; + t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL; + t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL; m = t2; + t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL; m &= t3; + t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL; m &= t4; + t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL; m &= t5; + t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL; m &= t6; + t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL; m &= t7; + t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL; m &= t8; + + /* ... except for a possible carry at bit 22 of t9 (i.e. bit 256 of the field element) */ + VERIFY_CHECK(t9 >> 23 == 0); + + /* At most a single final reduction is needed; check if the value is >= the field characteristic */ + x = (t9 >> 22) | ((t9 == 0x03FFFFFUL) & (m == 0x3FFFFFFUL) + & ((t1 + 0x40UL + ((t0 + 0x3D1UL) >> 26)) > 0x3FFFFFFUL)); + + /* Apply the final reduction (for constant-time behaviour, we do it always) */ + t0 += x * 0x3D1UL; t1 += (x << 6); + t1 += (t0 >> 26); t0 &= 0x3FFFFFFUL; + t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL; + t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL; + t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL; + t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL; + t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL; + t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL; + t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL; + t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL; + + /* If t9 didn't carry to bit 22 already, then it should have after any final reduction */ + VERIFY_CHECK(t9 >> 22 == x); + + /* Mask off the possible multiple of 2^256 from the final reduction */ + t9 &= 0x03FFFFFUL; + + r->n[0] = t0; r->n[1] = t1; r->n[2] = t2; r->n[3] = t3; r->n[4] = t4; + r->n[5] = t5; r->n[6] = t6; r->n[7] = t7; r->n[8] = t8; r->n[9] = t9; + +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 1; + secp256k1_fe_verify(r); +#endif +} + +static void secp256k1_fe_normalize_weak(secp256k1_fe *r) { + uint32_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4], + t5 = r->n[5], t6 = r->n[6], t7 = r->n[7], t8 = r->n[8], t9 = r->n[9]; + + /* Reduce t9 at the start so there will be at most a single carry from the first pass */ + uint32_t x = t9 >> 22; t9 &= 0x03FFFFFUL; + + /* The first pass ensures the magnitude is 1, ... */ + t0 += x * 0x3D1UL; t1 += (x << 6); + t1 += (t0 >> 26); t0 &= 0x3FFFFFFUL; + t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL; + t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL; + t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL; + t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL; + t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL; + t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL; + t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL; + t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL; + + /* ... except for a possible carry at bit 22 of t9 (i.e. bit 256 of the field element) */ + VERIFY_CHECK(t9 >> 23 == 0); + + r->n[0] = t0; r->n[1] = t1; r->n[2] = t2; r->n[3] = t3; r->n[4] = t4; + r->n[5] = t5; r->n[6] = t6; r->n[7] = t7; r->n[8] = t8; r->n[9] = t9; + +#ifdef VERIFY + r->magnitude = 1; + secp256k1_fe_verify(r); +#endif +} + +static void secp256k1_fe_normalize_var(secp256k1_fe *r) { + uint32_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4], + t5 = r->n[5], t6 = r->n[6], t7 = r->n[7], t8 = r->n[8], t9 = r->n[9]; + + /* Reduce t9 at the start so there will be at most a single carry from the first pass */ + uint32_t m; + uint32_t x = t9 >> 22; t9 &= 0x03FFFFFUL; + + /* The first pass ensures the magnitude is 1, ... */ + t0 += x * 0x3D1UL; t1 += (x << 6); + t1 += (t0 >> 26); t0 &= 0x3FFFFFFUL; + t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL; + t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL; m = t2; + t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL; m &= t3; + t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL; m &= t4; + t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL; m &= t5; + t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL; m &= t6; + t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL; m &= t7; + t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL; m &= t8; + + /* ... except for a possible carry at bit 22 of t9 (i.e. bit 256 of the field element) */ + VERIFY_CHECK(t9 >> 23 == 0); + + /* At most a single final reduction is needed; check if the value is >= the field characteristic */ + x = (t9 >> 22) | ((t9 == 0x03FFFFFUL) & (m == 0x3FFFFFFUL) + & ((t1 + 0x40UL + ((t0 + 0x3D1UL) >> 26)) > 0x3FFFFFFUL)); + + if (x) { + t0 += 0x3D1UL; t1 += (x << 6); + t1 += (t0 >> 26); t0 &= 0x3FFFFFFUL; + t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL; + t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL; + t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL; + t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL; + t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL; + t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL; + t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL; + t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL; + + /* If t9 didn't carry to bit 22 already, then it should have after any final reduction */ + VERIFY_CHECK(t9 >> 22 == x); + + /* Mask off the possible multiple of 2^256 from the final reduction */ + t9 &= 0x03FFFFFUL; + } + + r->n[0] = t0; r->n[1] = t1; r->n[2] = t2; r->n[3] = t3; r->n[4] = t4; + r->n[5] = t5; r->n[6] = t6; r->n[7] = t7; r->n[8] = t8; r->n[9] = t9; + +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 1; + secp256k1_fe_verify(r); +#endif +} + +static int secp256k1_fe_normalizes_to_zero(secp256k1_fe *r) { + uint32_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4], + t5 = r->n[5], t6 = r->n[6], t7 = r->n[7], t8 = r->n[8], t9 = r->n[9]; + + /* z0 tracks a possible raw value of 0, z1 tracks a possible raw value of P */ + uint32_t z0, z1; + + /* Reduce t9 at the start so there will be at most a single carry from the first pass */ + uint32_t x = t9 >> 22; t9 &= 0x03FFFFFUL; + + /* The first pass ensures the magnitude is 1, ... */ + t0 += x * 0x3D1UL; t1 += (x << 6); + t1 += (t0 >> 26); t0 &= 0x3FFFFFFUL; z0 = t0; z1 = t0 ^ 0x3D0UL; + t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL; z0 |= t1; z1 &= t1 ^ 0x40UL; + t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL; z0 |= t2; z1 &= t2; + t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL; z0 |= t3; z1 &= t3; + t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL; z0 |= t4; z1 &= t4; + t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL; z0 |= t5; z1 &= t5; + t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL; z0 |= t6; z1 &= t6; + t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL; z0 |= t7; z1 &= t7; + t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL; z0 |= t8; z1 &= t8; + z0 |= t9; z1 &= t9 ^ 0x3C00000UL; + + /* ... except for a possible carry at bit 22 of t9 (i.e. bit 256 of the field element) */ + VERIFY_CHECK(t9 >> 23 == 0); + + return (z0 == 0) | (z1 == 0x3FFFFFFUL); +} + +static int secp256k1_fe_normalizes_to_zero_var(secp256k1_fe *r) { + uint32_t t0, t1, t2, t3, t4, t5, t6, t7, t8, t9; + uint32_t z0, z1; + uint32_t x; + + t0 = r->n[0]; + t9 = r->n[9]; + + /* Reduce t9 at the start so there will be at most a single carry from the first pass */ + x = t9 >> 22; + + /* The first pass ensures the magnitude is 1, ... */ + t0 += x * 0x3D1UL; + + /* z0 tracks a possible raw value of 0, z1 tracks a possible raw value of P */ + z0 = t0 & 0x3FFFFFFUL; + z1 = z0 ^ 0x3D0UL; + + /* Fast return path should catch the majority of cases */ + if ((z0 != 0UL) & (z1 != 0x3FFFFFFUL)) { + return 0; + } + + t1 = r->n[1]; + t2 = r->n[2]; + t3 = r->n[3]; + t4 = r->n[4]; + t5 = r->n[5]; + t6 = r->n[6]; + t7 = r->n[7]; + t8 = r->n[8]; + + t9 &= 0x03FFFFFUL; + t1 += (x << 6); + + t1 += (t0 >> 26); + t2 += (t1 >> 26); t1 &= 0x3FFFFFFUL; z0 |= t1; z1 &= t1 ^ 0x40UL; + t3 += (t2 >> 26); t2 &= 0x3FFFFFFUL; z0 |= t2; z1 &= t2; + t4 += (t3 >> 26); t3 &= 0x3FFFFFFUL; z0 |= t3; z1 &= t3; + t5 += (t4 >> 26); t4 &= 0x3FFFFFFUL; z0 |= t4; z1 &= t4; + t6 += (t5 >> 26); t5 &= 0x3FFFFFFUL; z0 |= t5; z1 &= t5; + t7 += (t6 >> 26); t6 &= 0x3FFFFFFUL; z0 |= t6; z1 &= t6; + t8 += (t7 >> 26); t7 &= 0x3FFFFFFUL; z0 |= t7; z1 &= t7; + t9 += (t8 >> 26); t8 &= 0x3FFFFFFUL; z0 |= t8; z1 &= t8; + z0 |= t9; z1 &= t9 ^ 0x3C00000UL; + + /* ... except for a possible carry at bit 22 of t9 (i.e. bit 256 of the field element) */ + VERIFY_CHECK(t9 >> 23 == 0); + + return (z0 == 0) | (z1 == 0x3FFFFFFUL); +} + +SECP256K1_INLINE static void secp256k1_fe_set_int(secp256k1_fe *r, int a) { + r->n[0] = a; + r->n[1] = r->n[2] = r->n[3] = r->n[4] = r->n[5] = r->n[6] = r->n[7] = r->n[8] = r->n[9] = 0; +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 1; + secp256k1_fe_verify(r); +#endif +} + +SECP256K1_INLINE static int secp256k1_fe_is_zero(const secp256k1_fe *a) { + const uint32_t *t = a->n; +#ifdef VERIFY + VERIFY_CHECK(a->normalized); + secp256k1_fe_verify(a); +#endif + return (t[0] | t[1] | t[2] | t[3] | t[4] | t[5] | t[6] | t[7] | t[8] | t[9]) == 0; +} + +SECP256K1_INLINE static int secp256k1_fe_is_odd(const secp256k1_fe *a) { +#ifdef VERIFY + VERIFY_CHECK(a->normalized); + secp256k1_fe_verify(a); +#endif + return a->n[0] & 1; +} + +SECP256K1_INLINE static void secp256k1_fe_clear(secp256k1_fe *a) { + int i; +#ifdef VERIFY + a->magnitude = 0; + a->normalized = 1; +#endif + for (i=0; i<10; i++) { + a->n[i] = 0; + } +} + +static int secp256k1_fe_cmp_var(const secp256k1_fe *a, const secp256k1_fe *b) { + int i; +#ifdef VERIFY + VERIFY_CHECK(a->normalized); + VERIFY_CHECK(b->normalized); + secp256k1_fe_verify(a); + secp256k1_fe_verify(b); +#endif + for (i = 9; i >= 0; i--) { + if (a->n[i] > b->n[i]) { + return 1; + } + if (a->n[i] < b->n[i]) { + return -1; + } + } + return 0; +} + +static int secp256k1_fe_set_b32(secp256k1_fe *r, const unsigned char *a) { + r->n[0] = (uint32_t)a[31] | ((uint32_t)a[30] << 8) | ((uint32_t)a[29] << 16) | ((uint32_t)(a[28] & 0x3) << 24); + r->n[1] = (uint32_t)((a[28] >> 2) & 0x3f) | ((uint32_t)a[27] << 6) | ((uint32_t)a[26] << 14) | ((uint32_t)(a[25] & 0xf) << 22); + r->n[2] = (uint32_t)((a[25] >> 4) & 0xf) | ((uint32_t)a[24] << 4) | ((uint32_t)a[23] << 12) | ((uint32_t)(a[22] & 0x3f) << 20); + r->n[3] = (uint32_t)((a[22] >> 6) & 0x3) | ((uint32_t)a[21] << 2) | ((uint32_t)a[20] << 10) | ((uint32_t)a[19] << 18); + r->n[4] = (uint32_t)a[18] | ((uint32_t)a[17] << 8) | ((uint32_t)a[16] << 16) | ((uint32_t)(a[15] & 0x3) << 24); + r->n[5] = (uint32_t)((a[15] >> 2) & 0x3f) | ((uint32_t)a[14] << 6) | ((uint32_t)a[13] << 14) | ((uint32_t)(a[12] & 0xf) << 22); + r->n[6] = (uint32_t)((a[12] >> 4) & 0xf) | ((uint32_t)a[11] << 4) | ((uint32_t)a[10] << 12) | ((uint32_t)(a[9] & 0x3f) << 20); + r->n[7] = (uint32_t)((a[9] >> 6) & 0x3) | ((uint32_t)a[8] << 2) | ((uint32_t)a[7] << 10) | ((uint32_t)a[6] << 18); + r->n[8] = (uint32_t)a[5] | ((uint32_t)a[4] << 8) | ((uint32_t)a[3] << 16) | ((uint32_t)(a[2] & 0x3) << 24); + r->n[9] = (uint32_t)((a[2] >> 2) & 0x3f) | ((uint32_t)a[1] << 6) | ((uint32_t)a[0] << 14); + + if (r->n[9] == 0x3FFFFFUL && (r->n[8] & r->n[7] & r->n[6] & r->n[5] & r->n[4] & r->n[3] & r->n[2]) == 0x3FFFFFFUL && (r->n[1] + 0x40UL + ((r->n[0] + 0x3D1UL) >> 26)) > 0x3FFFFFFUL) { + return 0; + } +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 1; + secp256k1_fe_verify(r); +#endif + return 1; +} + +/** Convert a field element to a 32-byte big endian value. Requires the input to be normalized */ +static void secp256k1_fe_get_b32(unsigned char *r, const secp256k1_fe *a) { +#ifdef VERIFY + VERIFY_CHECK(a->normalized); + secp256k1_fe_verify(a); +#endif + r[0] = (a->n[9] >> 14) & 0xff; + r[1] = (a->n[9] >> 6) & 0xff; + r[2] = ((a->n[9] & 0x3F) << 2) | ((a->n[8] >> 24) & 0x3); + r[3] = (a->n[8] >> 16) & 0xff; + r[4] = (a->n[8] >> 8) & 0xff; + r[5] = a->n[8] & 0xff; + r[6] = (a->n[7] >> 18) & 0xff; + r[7] = (a->n[7] >> 10) & 0xff; + r[8] = (a->n[7] >> 2) & 0xff; + r[9] = ((a->n[7] & 0x3) << 6) | ((a->n[6] >> 20) & 0x3f); + r[10] = (a->n[6] >> 12) & 0xff; + r[11] = (a->n[6] >> 4) & 0xff; + r[12] = ((a->n[6] & 0xf) << 4) | ((a->n[5] >> 22) & 0xf); + r[13] = (a->n[5] >> 14) & 0xff; + r[14] = (a->n[5] >> 6) & 0xff; + r[15] = ((a->n[5] & 0x3f) << 2) | ((a->n[4] >> 24) & 0x3); + r[16] = (a->n[4] >> 16) & 0xff; + r[17] = (a->n[4] >> 8) & 0xff; + r[18] = a->n[4] & 0xff; + r[19] = (a->n[3] >> 18) & 0xff; + r[20] = (a->n[3] >> 10) & 0xff; + r[21] = (a->n[3] >> 2) & 0xff; + r[22] = ((a->n[3] & 0x3) << 6) | ((a->n[2] >> 20) & 0x3f); + r[23] = (a->n[2] >> 12) & 0xff; + r[24] = (a->n[2] >> 4) & 0xff; + r[25] = ((a->n[2] & 0xf) << 4) | ((a->n[1] >> 22) & 0xf); + r[26] = (a->n[1] >> 14) & 0xff; + r[27] = (a->n[1] >> 6) & 0xff; + r[28] = ((a->n[1] & 0x3f) << 2) | ((a->n[0] >> 24) & 0x3); + r[29] = (a->n[0] >> 16) & 0xff; + r[30] = (a->n[0] >> 8) & 0xff; + r[31] = a->n[0] & 0xff; +} + +SECP256K1_INLINE static void secp256k1_fe_negate(secp256k1_fe *r, const secp256k1_fe *a, int m) { +#ifdef VERIFY + VERIFY_CHECK(a->magnitude <= m); + secp256k1_fe_verify(a); +#endif + r->n[0] = 0x3FFFC2FUL * 2 * (m + 1) - a->n[0]; + r->n[1] = 0x3FFFFBFUL * 2 * (m + 1) - a->n[1]; + r->n[2] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[2]; + r->n[3] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[3]; + r->n[4] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[4]; + r->n[5] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[5]; + r->n[6] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[6]; + r->n[7] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[7]; + r->n[8] = 0x3FFFFFFUL * 2 * (m + 1) - a->n[8]; + r->n[9] = 0x03FFFFFUL * 2 * (m + 1) - a->n[9]; +#ifdef VERIFY + r->magnitude = m + 1; + r->normalized = 0; + secp256k1_fe_verify(r); +#endif +} + +SECP256K1_INLINE static void secp256k1_fe_mul_int(secp256k1_fe *r, int a) { + r->n[0] *= a; + r->n[1] *= a; + r->n[2] *= a; + r->n[3] *= a; + r->n[4] *= a; + r->n[5] *= a; + r->n[6] *= a; + r->n[7] *= a; + r->n[8] *= a; + r->n[9] *= a; +#ifdef VERIFY + r->magnitude *= a; + r->normalized = 0; + secp256k1_fe_verify(r); +#endif +} + +SECP256K1_INLINE static void secp256k1_fe_add(secp256k1_fe *r, const secp256k1_fe *a) { +#ifdef VERIFY + secp256k1_fe_verify(a); +#endif + r->n[0] += a->n[0]; + r->n[1] += a->n[1]; + r->n[2] += a->n[2]; + r->n[3] += a->n[3]; + r->n[4] += a->n[4]; + r->n[5] += a->n[5]; + r->n[6] += a->n[6]; + r->n[7] += a->n[7]; + r->n[8] += a->n[8]; + r->n[9] += a->n[9]; +#ifdef VERIFY + r->magnitude += a->magnitude; + r->normalized = 0; + secp256k1_fe_verify(r); +#endif +} + +#if defined(USE_EXTERNAL_ASM) + +/* External assembler implementation */ +void secp256k1_fe_mul_inner(uint32_t *r, const uint32_t *a, const uint32_t * SECP256K1_RESTRICT b); +void secp256k1_fe_sqr_inner(uint32_t *r, const uint32_t *a); + +#else + +#ifdef VERIFY +#define VERIFY_BITS(x, n) VERIFY_CHECK(((x) >> (n)) == 0) +#else +#define VERIFY_BITS(x, n) do { } while(0) +#endif + +SECP256K1_INLINE static void secp256k1_fe_mul_inner(uint32_t *r, const uint32_t *a, const uint32_t * SECP256K1_RESTRICT b) { + uint64_t c, d; + uint64_t u0, u1, u2, u3, u4, u5, u6, u7, u8; + uint32_t t9, t1, t0, t2, t3, t4, t5, t6, t7; + const uint32_t M = 0x3FFFFFFUL, R0 = 0x3D10UL, R1 = 0x400UL; + + VERIFY_BITS(a[0], 30); + VERIFY_BITS(a[1], 30); + VERIFY_BITS(a[2], 30); + VERIFY_BITS(a[3], 30); + VERIFY_BITS(a[4], 30); + VERIFY_BITS(a[5], 30); + VERIFY_BITS(a[6], 30); + VERIFY_BITS(a[7], 30); + VERIFY_BITS(a[8], 30); + VERIFY_BITS(a[9], 26); + VERIFY_BITS(b[0], 30); + VERIFY_BITS(b[1], 30); + VERIFY_BITS(b[2], 30); + VERIFY_BITS(b[3], 30); + VERIFY_BITS(b[4], 30); + VERIFY_BITS(b[5], 30); + VERIFY_BITS(b[6], 30); + VERIFY_BITS(b[7], 30); + VERIFY_BITS(b[8], 30); + VERIFY_BITS(b[9], 26); + + /** [... a b c] is a shorthand for ... + a<<52 + b<<26 + c<<0 mod n. + * px is a shorthand for sum(a[i]*b[x-i], i=0..x). + * Note that [x 0 0 0 0 0 0 0 0 0 0] = [x*R1 x*R0]. + */ + + d = (uint64_t)a[0] * b[9] + + (uint64_t)a[1] * b[8] + + (uint64_t)a[2] * b[7] + + (uint64_t)a[3] * b[6] + + (uint64_t)a[4] * b[5] + + (uint64_t)a[5] * b[4] + + (uint64_t)a[6] * b[3] + + (uint64_t)a[7] * b[2] + + (uint64_t)a[8] * b[1] + + (uint64_t)a[9] * b[0]; + /* VERIFY_BITS(d, 64); */ + /* [d 0 0 0 0 0 0 0 0 0] = [p9 0 0 0 0 0 0 0 0 0] */ + t9 = d & M; d >>= 26; + VERIFY_BITS(t9, 26); + VERIFY_BITS(d, 38); + /* [d t9 0 0 0 0 0 0 0 0 0] = [p9 0 0 0 0 0 0 0 0 0] */ + + c = (uint64_t)a[0] * b[0]; + VERIFY_BITS(c, 60); + /* [d t9 0 0 0 0 0 0 0 0 c] = [p9 0 0 0 0 0 0 0 0 p0] */ + d += (uint64_t)a[1] * b[9] + + (uint64_t)a[2] * b[8] + + (uint64_t)a[3] * b[7] + + (uint64_t)a[4] * b[6] + + (uint64_t)a[5] * b[5] + + (uint64_t)a[6] * b[4] + + (uint64_t)a[7] * b[3] + + (uint64_t)a[8] * b[2] + + (uint64_t)a[9] * b[1]; + VERIFY_BITS(d, 63); + /* [d t9 0 0 0 0 0 0 0 0 c] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ + u0 = d & M; d >>= 26; c += u0 * R0; + VERIFY_BITS(u0, 26); + VERIFY_BITS(d, 37); + VERIFY_BITS(c, 61); + /* [d u0 t9 0 0 0 0 0 0 0 0 c-u0*R0] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ + t0 = c & M; c >>= 26; c += u0 * R1; + VERIFY_BITS(t0, 26); + VERIFY_BITS(c, 37); + /* [d u0 t9 0 0 0 0 0 0 0 c-u0*R1 t0-u0*R0] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ + /* [d 0 t9 0 0 0 0 0 0 0 c t0] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ + + c += (uint64_t)a[0] * b[1] + + (uint64_t)a[1] * b[0]; + VERIFY_BITS(c, 62); + /* [d 0 t9 0 0 0 0 0 0 0 c t0] = [p10 p9 0 0 0 0 0 0 0 p1 p0] */ + d += (uint64_t)a[2] * b[9] + + (uint64_t)a[3] * b[8] + + (uint64_t)a[4] * b[7] + + (uint64_t)a[5] * b[6] + + (uint64_t)a[6] * b[5] + + (uint64_t)a[7] * b[4] + + (uint64_t)a[8] * b[3] + + (uint64_t)a[9] * b[2]; + VERIFY_BITS(d, 63); + /* [d 0 t9 0 0 0 0 0 0 0 c t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ + u1 = d & M; d >>= 26; c += u1 * R0; + VERIFY_BITS(u1, 26); + VERIFY_BITS(d, 37); + VERIFY_BITS(c, 63); + /* [d u1 0 t9 0 0 0 0 0 0 0 c-u1*R0 t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ + t1 = c & M; c >>= 26; c += u1 * R1; + VERIFY_BITS(t1, 26); + VERIFY_BITS(c, 38); + /* [d u1 0 t9 0 0 0 0 0 0 c-u1*R1 t1-u1*R0 t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ + /* [d 0 0 t9 0 0 0 0 0 0 c t1 t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ + + c += (uint64_t)a[0] * b[2] + + (uint64_t)a[1] * b[1] + + (uint64_t)a[2] * b[0]; + VERIFY_BITS(c, 62); + /* [d 0 0 t9 0 0 0 0 0 0 c t1 t0] = [p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ + d += (uint64_t)a[3] * b[9] + + (uint64_t)a[4] * b[8] + + (uint64_t)a[5] * b[7] + + (uint64_t)a[6] * b[6] + + (uint64_t)a[7] * b[5] + + (uint64_t)a[8] * b[4] + + (uint64_t)a[9] * b[3]; + VERIFY_BITS(d, 63); + /* [d 0 0 t9 0 0 0 0 0 0 c t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ + u2 = d & M; d >>= 26; c += u2 * R0; + VERIFY_BITS(u2, 26); + VERIFY_BITS(d, 37); + VERIFY_BITS(c, 63); + /* [d u2 0 0 t9 0 0 0 0 0 0 c-u2*R0 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ + t2 = c & M; c >>= 26; c += u2 * R1; + VERIFY_BITS(t2, 26); + VERIFY_BITS(c, 38); + /* [d u2 0 0 t9 0 0 0 0 0 c-u2*R1 t2-u2*R0 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ + /* [d 0 0 0 t9 0 0 0 0 0 c t2 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ + + c += (uint64_t)a[0] * b[3] + + (uint64_t)a[1] * b[2] + + (uint64_t)a[2] * b[1] + + (uint64_t)a[3] * b[0]; + VERIFY_BITS(c, 63); + /* [d 0 0 0 t9 0 0 0 0 0 c t2 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ + d += (uint64_t)a[4] * b[9] + + (uint64_t)a[5] * b[8] + + (uint64_t)a[6] * b[7] + + (uint64_t)a[7] * b[6] + + (uint64_t)a[8] * b[5] + + (uint64_t)a[9] * b[4]; + VERIFY_BITS(d, 63); + /* [d 0 0 0 t9 0 0 0 0 0 c t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ + u3 = d & M; d >>= 26; c += u3 * R0; + VERIFY_BITS(u3, 26); + VERIFY_BITS(d, 37); + /* VERIFY_BITS(c, 64); */ + /* [d u3 0 0 0 t9 0 0 0 0 0 c-u3*R0 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ + t3 = c & M; c >>= 26; c += u3 * R1; + VERIFY_BITS(t3, 26); + VERIFY_BITS(c, 39); + /* [d u3 0 0 0 t9 0 0 0 0 c-u3*R1 t3-u3*R0 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ + /* [d 0 0 0 0 t9 0 0 0 0 c t3 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ + + c += (uint64_t)a[0] * b[4] + + (uint64_t)a[1] * b[3] + + (uint64_t)a[2] * b[2] + + (uint64_t)a[3] * b[1] + + (uint64_t)a[4] * b[0]; + VERIFY_BITS(c, 63); + /* [d 0 0 0 0 t9 0 0 0 0 c t3 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ + d += (uint64_t)a[5] * b[9] + + (uint64_t)a[6] * b[8] + + (uint64_t)a[7] * b[7] + + (uint64_t)a[8] * b[6] + + (uint64_t)a[9] * b[5]; + VERIFY_BITS(d, 62); + /* [d 0 0 0 0 t9 0 0 0 0 c t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ + u4 = d & M; d >>= 26; c += u4 * R0; + VERIFY_BITS(u4, 26); + VERIFY_BITS(d, 36); + /* VERIFY_BITS(c, 64); */ + /* [d u4 0 0 0 0 t9 0 0 0 0 c-u4*R0 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ + t4 = c & M; c >>= 26; c += u4 * R1; + VERIFY_BITS(t4, 26); + VERIFY_BITS(c, 39); + /* [d u4 0 0 0 0 t9 0 0 0 c-u4*R1 t4-u4*R0 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 t9 0 0 0 c t4 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ + + c += (uint64_t)a[0] * b[5] + + (uint64_t)a[1] * b[4] + + (uint64_t)a[2] * b[3] + + (uint64_t)a[3] * b[2] + + (uint64_t)a[4] * b[1] + + (uint64_t)a[5] * b[0]; + VERIFY_BITS(c, 63); + /* [d 0 0 0 0 0 t9 0 0 0 c t4 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ + d += (uint64_t)a[6] * b[9] + + (uint64_t)a[7] * b[8] + + (uint64_t)a[8] * b[7] + + (uint64_t)a[9] * b[6]; + VERIFY_BITS(d, 62); + /* [d 0 0 0 0 0 t9 0 0 0 c t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ + u5 = d & M; d >>= 26; c += u5 * R0; + VERIFY_BITS(u5, 26); + VERIFY_BITS(d, 36); + /* VERIFY_BITS(c, 64); */ + /* [d u5 0 0 0 0 0 t9 0 0 0 c-u5*R0 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ + t5 = c & M; c >>= 26; c += u5 * R1; + VERIFY_BITS(t5, 26); + VERIFY_BITS(c, 39); + /* [d u5 0 0 0 0 0 t9 0 0 c-u5*R1 t5-u5*R0 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 0 t9 0 0 c t5 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ + + c += (uint64_t)a[0] * b[6] + + (uint64_t)a[1] * b[5] + + (uint64_t)a[2] * b[4] + + (uint64_t)a[3] * b[3] + + (uint64_t)a[4] * b[2] + + (uint64_t)a[5] * b[1] + + (uint64_t)a[6] * b[0]; + VERIFY_BITS(c, 63); + /* [d 0 0 0 0 0 0 t9 0 0 c t5 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ + d += (uint64_t)a[7] * b[9] + + (uint64_t)a[8] * b[8] + + (uint64_t)a[9] * b[7]; + VERIFY_BITS(d, 61); + /* [d 0 0 0 0 0 0 t9 0 0 c t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ + u6 = d & M; d >>= 26; c += u6 * R0; + VERIFY_BITS(u6, 26); + VERIFY_BITS(d, 35); + /* VERIFY_BITS(c, 64); */ + /* [d u6 0 0 0 0 0 0 t9 0 0 c-u6*R0 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ + t6 = c & M; c >>= 26; c += u6 * R1; + VERIFY_BITS(t6, 26); + VERIFY_BITS(c, 39); + /* [d u6 0 0 0 0 0 0 t9 0 c-u6*R1 t6-u6*R0 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 0 0 t9 0 c t6 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ + + c += (uint64_t)a[0] * b[7] + + (uint64_t)a[1] * b[6] + + (uint64_t)a[2] * b[5] + + (uint64_t)a[3] * b[4] + + (uint64_t)a[4] * b[3] + + (uint64_t)a[5] * b[2] + + (uint64_t)a[6] * b[1] + + (uint64_t)a[7] * b[0]; + /* VERIFY_BITS(c, 64); */ + VERIFY_CHECK(c <= 0x8000007C00000007ULL); + /* [d 0 0 0 0 0 0 0 t9 0 c t6 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ + d += (uint64_t)a[8] * b[9] + + (uint64_t)a[9] * b[8]; + VERIFY_BITS(d, 58); + /* [d 0 0 0 0 0 0 0 t9 0 c t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ + u7 = d & M; d >>= 26; c += u7 * R0; + VERIFY_BITS(u7, 26); + VERIFY_BITS(d, 32); + /* VERIFY_BITS(c, 64); */ + VERIFY_CHECK(c <= 0x800001703FFFC2F7ULL); + /* [d u7 0 0 0 0 0 0 0 t9 0 c-u7*R0 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ + t7 = c & M; c >>= 26; c += u7 * R1; + VERIFY_BITS(t7, 26); + VERIFY_BITS(c, 38); + /* [d u7 0 0 0 0 0 0 0 t9 c-u7*R1 t7-u7*R0 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 0 0 0 t9 c t7 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ + + c += (uint64_t)a[0] * b[8] + + (uint64_t)a[1] * b[7] + + (uint64_t)a[2] * b[6] + + (uint64_t)a[3] * b[5] + + (uint64_t)a[4] * b[4] + + (uint64_t)a[5] * b[3] + + (uint64_t)a[6] * b[2] + + (uint64_t)a[7] * b[1] + + (uint64_t)a[8] * b[0]; + /* VERIFY_BITS(c, 64); */ + VERIFY_CHECK(c <= 0x9000007B80000008ULL); + /* [d 0 0 0 0 0 0 0 0 t9 c t7 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + d += (uint64_t)a[9] * b[9]; + VERIFY_BITS(d, 57); + /* [d 0 0 0 0 0 0 0 0 t9 c t7 t6 t5 t4 t3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + u8 = d & M; d >>= 26; c += u8 * R0; + VERIFY_BITS(u8, 26); + VERIFY_BITS(d, 31); + /* VERIFY_BITS(c, 64); */ + VERIFY_CHECK(c <= 0x9000016FBFFFC2F8ULL); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 t5 t4 t3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + + r[3] = t3; + VERIFY_BITS(r[3], 26); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 t5 t4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[4] = t4; + VERIFY_BITS(r[4], 26); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 t5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[5] = t5; + VERIFY_BITS(r[5], 26); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[6] = t6; + VERIFY_BITS(r[6], 26); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[7] = t7; + VERIFY_BITS(r[7], 26); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + + r[8] = c & M; c >>= 26; c += u8 * R1; + VERIFY_BITS(r[8], 26); + VERIFY_BITS(c, 39); + /* [d u8 0 0 0 0 0 0 0 0 t9+c-u8*R1 r8-u8*R0 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 0 0 0 0 t9+c r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + c += d * R0 + t9; + VERIFY_BITS(c, 45); + /* [d 0 0 0 0 0 0 0 0 0 c-d*R0 r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[9] = c & (M >> 4); c >>= 22; c += d * (R1 << 4); + VERIFY_BITS(r[9], 22); + VERIFY_BITS(c, 46); + /* [d 0 0 0 0 0 0 0 0 r9+((c-d*R1<<4)<<22)-d*R0 r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 0 0 -d*R1 r9+(c<<22)-d*R0 r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + + d = c * (R0 >> 4) + t0; + VERIFY_BITS(d, 56); + /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 t1 d-c*R0>>4] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[0] = d & M; d >>= 26; + VERIFY_BITS(r[0], 26); + VERIFY_BITS(d, 30); + /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 t1+d r0-c*R0>>4] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + d += c * (R1 >> 4) + t1; + VERIFY_BITS(d, 53); + VERIFY_CHECK(d <= 0x10000003FFFFBFULL); + /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 d-c*R1>>4 r0-c*R0>>4] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + /* [r9 r8 r7 r6 r5 r4 r3 t2 d r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[1] = d & M; d >>= 26; + VERIFY_BITS(r[1], 26); + VERIFY_BITS(d, 27); + VERIFY_CHECK(d <= 0x4000000ULL); + /* [r9 r8 r7 r6 r5 r4 r3 t2+d r1 r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + d += t2; + VERIFY_BITS(d, 27); + /* [r9 r8 r7 r6 r5 r4 r3 d r1 r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[2] = (uint32_t)(uint32_t)(uint32_t)(uint32_t)(uint32_t)(uint32_t)d; + VERIFY_BITS(r[2], 27); + /* [r9 r8 r7 r6 r5 r4 r3 r2 r1 r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ +} + +SECP256K1_INLINE static void secp256k1_fe_sqr_inner(uint32_t *r, const uint32_t *a) { + uint64_t c, d; + uint64_t u0, u1, u2, u3, u4, u5, u6, u7, u8; + uint32_t t9, t0, t1, t2, t3, t4, t5, t6, t7; + const uint32_t M = 0x3FFFFFFUL, R0 = 0x3D10UL, R1 = 0x400UL; + + VERIFY_BITS(a[0], 30); + VERIFY_BITS(a[1], 30); + VERIFY_BITS(a[2], 30); + VERIFY_BITS(a[3], 30); + VERIFY_BITS(a[4], 30); + VERIFY_BITS(a[5], 30); + VERIFY_BITS(a[6], 30); + VERIFY_BITS(a[7], 30); + VERIFY_BITS(a[8], 30); + VERIFY_BITS(a[9], 26); + + /** [... a b c] is a shorthand for ... + a<<52 + b<<26 + c<<0 mod n. + * px is a shorthand for sum(a[i]*a[x-i], i=0..x). + * Note that [x 0 0 0 0 0 0 0 0 0 0] = [x*R1 x*R0]. + */ + + d = (uint64_t)(a[0]*2) * a[9] + + (uint64_t)(a[1]*2) * a[8] + + (uint64_t)(a[2]*2) * a[7] + + (uint64_t)(a[3]*2) * a[6] + + (uint64_t)(a[4]*2) * a[5]; + /* VERIFY_BITS(d, 64); */ + /* [d 0 0 0 0 0 0 0 0 0] = [p9 0 0 0 0 0 0 0 0 0] */ + t9 = d & M; d >>= 26; + VERIFY_BITS(t9, 26); + VERIFY_BITS(d, 38); + /* [d t9 0 0 0 0 0 0 0 0 0] = [p9 0 0 0 0 0 0 0 0 0] */ + + c = (uint64_t)a[0] * a[0]; + VERIFY_BITS(c, 60); + /* [d t9 0 0 0 0 0 0 0 0 c] = [p9 0 0 0 0 0 0 0 0 p0] */ + d += (uint64_t)(a[1]*2) * a[9] + + (uint64_t)(a[2]*2) * a[8] + + (uint64_t)(a[3]*2) * a[7] + + (uint64_t)(a[4]*2) * a[6] + + (uint64_t)a[5] * a[5]; + VERIFY_BITS(d, 63); + /* [d t9 0 0 0 0 0 0 0 0 c] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ + u0 = d & M; d >>= 26; c += u0 * R0; + VERIFY_BITS(u0, 26); + VERIFY_BITS(d, 37); + VERIFY_BITS(c, 61); + /* [d u0 t9 0 0 0 0 0 0 0 0 c-u0*R0] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ + t0 = c & M; c >>= 26; c += u0 * R1; + VERIFY_BITS(t0, 26); + VERIFY_BITS(c, 37); + /* [d u0 t9 0 0 0 0 0 0 0 c-u0*R1 t0-u0*R0] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ + /* [d 0 t9 0 0 0 0 0 0 0 c t0] = [p10 p9 0 0 0 0 0 0 0 0 p0] */ + + c += (uint64_t)(a[0]*2) * a[1]; + VERIFY_BITS(c, 62); + /* [d 0 t9 0 0 0 0 0 0 0 c t0] = [p10 p9 0 0 0 0 0 0 0 p1 p0] */ + d += (uint64_t)(a[2]*2) * a[9] + + (uint64_t)(a[3]*2) * a[8] + + (uint64_t)(a[4]*2) * a[7] + + (uint64_t)(a[5]*2) * a[6]; + VERIFY_BITS(d, 63); + /* [d 0 t9 0 0 0 0 0 0 0 c t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ + u1 = d & M; d >>= 26; c += u1 * R0; + VERIFY_BITS(u1, 26); + VERIFY_BITS(d, 37); + VERIFY_BITS(c, 63); + /* [d u1 0 t9 0 0 0 0 0 0 0 c-u1*R0 t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ + t1 = c & M; c >>= 26; c += u1 * R1; + VERIFY_BITS(t1, 26); + VERIFY_BITS(c, 38); + /* [d u1 0 t9 0 0 0 0 0 0 c-u1*R1 t1-u1*R0 t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ + /* [d 0 0 t9 0 0 0 0 0 0 c t1 t0] = [p11 p10 p9 0 0 0 0 0 0 0 p1 p0] */ + + c += (uint64_t)(a[0]*2) * a[2] + + (uint64_t)a[1] * a[1]; + VERIFY_BITS(c, 62); + /* [d 0 0 t9 0 0 0 0 0 0 c t1 t0] = [p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ + d += (uint64_t)(a[3]*2) * a[9] + + (uint64_t)(a[4]*2) * a[8] + + (uint64_t)(a[5]*2) * a[7] + + (uint64_t)a[6] * a[6]; + VERIFY_BITS(d, 63); + /* [d 0 0 t9 0 0 0 0 0 0 c t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ + u2 = d & M; d >>= 26; c += u2 * R0; + VERIFY_BITS(u2, 26); + VERIFY_BITS(d, 37); + VERIFY_BITS(c, 63); + /* [d u2 0 0 t9 0 0 0 0 0 0 c-u2*R0 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ + t2 = c & M; c >>= 26; c += u2 * R1; + VERIFY_BITS(t2, 26); + VERIFY_BITS(c, 38); + /* [d u2 0 0 t9 0 0 0 0 0 c-u2*R1 t2-u2*R0 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ + /* [d 0 0 0 t9 0 0 0 0 0 c t2 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 0 p2 p1 p0] */ + + c += (uint64_t)(a[0]*2) * a[3] + + (uint64_t)(a[1]*2) * a[2]; + VERIFY_BITS(c, 63); + /* [d 0 0 0 t9 0 0 0 0 0 c t2 t1 t0] = [p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ + d += (uint64_t)(a[4]*2) * a[9] + + (uint64_t)(a[5]*2) * a[8] + + (uint64_t)(a[6]*2) * a[7]; + VERIFY_BITS(d, 63); + /* [d 0 0 0 t9 0 0 0 0 0 c t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ + u3 = d & M; d >>= 26; c += u3 * R0; + VERIFY_BITS(u3, 26); + VERIFY_BITS(d, 37); + /* VERIFY_BITS(c, 64); */ + /* [d u3 0 0 0 t9 0 0 0 0 0 c-u3*R0 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ + t3 = c & M; c >>= 26; c += u3 * R1; + VERIFY_BITS(t3, 26); + VERIFY_BITS(c, 39); + /* [d u3 0 0 0 t9 0 0 0 0 c-u3*R1 t3-u3*R0 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ + /* [d 0 0 0 0 t9 0 0 0 0 c t3 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 0 p3 p2 p1 p0] */ + + c += (uint64_t)(a[0]*2) * a[4] + + (uint64_t)(a[1]*2) * a[3] + + (uint64_t)a[2] * a[2]; + VERIFY_BITS(c, 63); + /* [d 0 0 0 0 t9 0 0 0 0 c t3 t2 t1 t0] = [p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ + d += (uint64_t)(a[5]*2) * a[9] + + (uint64_t)(a[6]*2) * a[8] + + (uint64_t)a[7] * a[7]; + VERIFY_BITS(d, 62); + /* [d 0 0 0 0 t9 0 0 0 0 c t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ + u4 = d & M; d >>= 26; c += u4 * R0; + VERIFY_BITS(u4, 26); + VERIFY_BITS(d, 36); + /* VERIFY_BITS(c, 64); */ + /* [d u4 0 0 0 0 t9 0 0 0 0 c-u4*R0 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ + t4 = c & M; c >>= 26; c += u4 * R1; + VERIFY_BITS(t4, 26); + VERIFY_BITS(c, 39); + /* [d u4 0 0 0 0 t9 0 0 0 c-u4*R1 t4-u4*R0 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 t9 0 0 0 c t4 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 0 p4 p3 p2 p1 p0] */ + + c += (uint64_t)(a[0]*2) * a[5] + + (uint64_t)(a[1]*2) * a[4] + + (uint64_t)(a[2]*2) * a[3]; + VERIFY_BITS(c, 63); + /* [d 0 0 0 0 0 t9 0 0 0 c t4 t3 t2 t1 t0] = [p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ + d += (uint64_t)(a[6]*2) * a[9] + + (uint64_t)(a[7]*2) * a[8]; + VERIFY_BITS(d, 62); + /* [d 0 0 0 0 0 t9 0 0 0 c t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ + u5 = d & M; d >>= 26; c += u5 * R0; + VERIFY_BITS(u5, 26); + VERIFY_BITS(d, 36); + /* VERIFY_BITS(c, 64); */ + /* [d u5 0 0 0 0 0 t9 0 0 0 c-u5*R0 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ + t5 = c & M; c >>= 26; c += u5 * R1; + VERIFY_BITS(t5, 26); + VERIFY_BITS(c, 39); + /* [d u5 0 0 0 0 0 t9 0 0 c-u5*R1 t5-u5*R0 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 0 t9 0 0 c t5 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 0 p5 p4 p3 p2 p1 p0] */ + + c += (uint64_t)(a[0]*2) * a[6] + + (uint64_t)(a[1]*2) * a[5] + + (uint64_t)(a[2]*2) * a[4] + + (uint64_t)a[3] * a[3]; + VERIFY_BITS(c, 63); + /* [d 0 0 0 0 0 0 t9 0 0 c t5 t4 t3 t2 t1 t0] = [p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ + d += (uint64_t)(a[7]*2) * a[9] + + (uint64_t)a[8] * a[8]; + VERIFY_BITS(d, 61); + /* [d 0 0 0 0 0 0 t9 0 0 c t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ + u6 = d & M; d >>= 26; c += u6 * R0; + VERIFY_BITS(u6, 26); + VERIFY_BITS(d, 35); + /* VERIFY_BITS(c, 64); */ + /* [d u6 0 0 0 0 0 0 t9 0 0 c-u6*R0 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ + t6 = c & M; c >>= 26; c += u6 * R1; + VERIFY_BITS(t6, 26); + VERIFY_BITS(c, 39); + /* [d u6 0 0 0 0 0 0 t9 0 c-u6*R1 t6-u6*R0 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 0 0 t9 0 c t6 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 0 p6 p5 p4 p3 p2 p1 p0] */ + + c += (uint64_t)(a[0]*2) * a[7] + + (uint64_t)(a[1]*2) * a[6] + + (uint64_t)(a[2]*2) * a[5] + + (uint64_t)(a[3]*2) * a[4]; + /* VERIFY_BITS(c, 64); */ + VERIFY_CHECK(c <= 0x8000007C00000007ULL); + /* [d 0 0 0 0 0 0 0 t9 0 c t6 t5 t4 t3 t2 t1 t0] = [p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ + d += (uint64_t)(a[8]*2) * a[9]; + VERIFY_BITS(d, 58); + /* [d 0 0 0 0 0 0 0 t9 0 c t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ + u7 = d & M; d >>= 26; c += u7 * R0; + VERIFY_BITS(u7, 26); + VERIFY_BITS(d, 32); + /* VERIFY_BITS(c, 64); */ + VERIFY_CHECK(c <= 0x800001703FFFC2F7ULL); + /* [d u7 0 0 0 0 0 0 0 t9 0 c-u7*R0 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ + t7 = c & M; c >>= 26; c += u7 * R1; + VERIFY_BITS(t7, 26); + VERIFY_BITS(c, 38); + /* [d u7 0 0 0 0 0 0 0 t9 c-u7*R1 t7-u7*R0 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 0 0 0 t9 c t7 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 0 p7 p6 p5 p4 p3 p2 p1 p0] */ + + c += (uint64_t)(a[0]*2) * a[8] + + (uint64_t)(a[1]*2) * a[7] + + (uint64_t)(a[2]*2) * a[6] + + (uint64_t)(a[3]*2) * a[5] + + (uint64_t)a[4] * a[4]; + /* VERIFY_BITS(c, 64); */ + VERIFY_CHECK(c <= 0x9000007B80000008ULL); + /* [d 0 0 0 0 0 0 0 0 t9 c t7 t6 t5 t4 t3 t2 t1 t0] = [p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + d += (uint64_t)a[9] * a[9]; + VERIFY_BITS(d, 57); + /* [d 0 0 0 0 0 0 0 0 t9 c t7 t6 t5 t4 t3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + u8 = d & M; d >>= 26; c += u8 * R0; + VERIFY_BITS(u8, 26); + VERIFY_BITS(d, 31); + /* VERIFY_BITS(c, 64); */ + VERIFY_CHECK(c <= 0x9000016FBFFFC2F8ULL); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 t5 t4 t3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + + r[3] = t3; + VERIFY_BITS(r[3], 26); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 t5 t4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[4] = t4; + VERIFY_BITS(r[4], 26); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 t5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[5] = t5; + VERIFY_BITS(r[5], 26); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 t6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[6] = t6; + VERIFY_BITS(r[6], 26); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 t7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[7] = t7; + VERIFY_BITS(r[7], 26); + /* [d u8 0 0 0 0 0 0 0 0 t9 c-u8*R0 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + + r[8] = c & M; c >>= 26; c += u8 * R1; + VERIFY_BITS(r[8], 26); + VERIFY_BITS(c, 39); + /* [d u8 0 0 0 0 0 0 0 0 t9+c-u8*R1 r8-u8*R0 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 0 0 0 0 t9+c r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + c += d * R0 + t9; + VERIFY_BITS(c, 45); + /* [d 0 0 0 0 0 0 0 0 0 c-d*R0 r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[9] = c & (M >> 4); c >>= 22; c += d * (R1 << 4); + VERIFY_BITS(r[9], 22); + VERIFY_BITS(c, 46); + /* [d 0 0 0 0 0 0 0 0 r9+((c-d*R1<<4)<<22)-d*R0 r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + /* [d 0 0 0 0 0 0 0 -d*R1 r9+(c<<22)-d*R0 r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 t1 t0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + + d = c * (R0 >> 4) + t0; + VERIFY_BITS(d, 56); + /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 t1 d-c*R0>>4] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[0] = d & M; d >>= 26; + VERIFY_BITS(r[0], 26); + VERIFY_BITS(d, 30); + /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 t1+d r0-c*R0>>4] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + d += c * (R1 >> 4) + t1; + VERIFY_BITS(d, 53); + VERIFY_CHECK(d <= 0x10000003FFFFBFULL); + /* [r9+(c<<22) r8 r7 r6 r5 r4 r3 t2 d-c*R1>>4 r0-c*R0>>4] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + /* [r9 r8 r7 r6 r5 r4 r3 t2 d r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[1] = d & M; d >>= 26; + VERIFY_BITS(r[1], 26); + VERIFY_BITS(d, 27); + VERIFY_CHECK(d <= 0x4000000ULL); + /* [r9 r8 r7 r6 r5 r4 r3 t2+d r1 r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + d += t2; + VERIFY_BITS(d, 27); + /* [r9 r8 r7 r6 r5 r4 r3 d r1 r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[2] = (uint32_t)d; + VERIFY_BITS(r[2], 27); + /* [r9 r8 r7 r6 r5 r4 r3 r2 r1 r0] = [p18 p17 p16 p15 p14 p13 p12 p11 p10 p9 p8 p7 p6 p5 p4 p3 p2 p1 p0] */ +} +#endif + +static void secp256k1_fe_mul(secp256k1_fe *r, const secp256k1_fe *a, const secp256k1_fe * SECP256K1_RESTRICT b) { +#ifdef VERIFY + VERIFY_CHECK(a->magnitude <= 8); + VERIFY_CHECK(b->magnitude <= 8); + secp256k1_fe_verify(a); + secp256k1_fe_verify(b); + VERIFY_CHECK(r != b); +#endif + secp256k1_fe_mul_inner(r->n, a->n, b->n); +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 0; + secp256k1_fe_verify(r); +#endif +} + +static void secp256k1_fe_sqr(secp256k1_fe *r, const secp256k1_fe *a) { +#ifdef VERIFY + VERIFY_CHECK(a->magnitude <= 8); + secp256k1_fe_verify(a); +#endif + secp256k1_fe_sqr_inner(r->n, a->n); +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 0; + secp256k1_fe_verify(r); +#endif +} + +static SECP256K1_INLINE void secp256k1_fe_cmov(secp256k1_fe *r, const secp256k1_fe *a, int flag) { + uint32_t mask0, mask1; + mask0 = flag + ~((uint32_t)0); + mask1 = ~mask0; + r->n[0] = (r->n[0] & mask0) | (a->n[0] & mask1); + r->n[1] = (r->n[1] & mask0) | (a->n[1] & mask1); + r->n[2] = (r->n[2] & mask0) | (a->n[2] & mask1); + r->n[3] = (r->n[3] & mask0) | (a->n[3] & mask1); + r->n[4] = (r->n[4] & mask0) | (a->n[4] & mask1); + r->n[5] = (r->n[5] & mask0) | (a->n[5] & mask1); + r->n[6] = (r->n[6] & mask0) | (a->n[6] & mask1); + r->n[7] = (r->n[7] & mask0) | (a->n[7] & mask1); + r->n[8] = (r->n[8] & mask0) | (a->n[8] & mask1); + r->n[9] = (r->n[9] & mask0) | (a->n[9] & mask1); +#ifdef VERIFY + if (a->magnitude > r->magnitude) { + r->magnitude = a->magnitude; + } + r->normalized &= a->normalized; +#endif +} + +static SECP256K1_INLINE void secp256k1_fe_storage_cmov(secp256k1_fe_storage *r, const secp256k1_fe_storage *a, int flag) { + uint32_t mask0, mask1; + mask0 = flag + ~((uint32_t)0); + mask1 = ~mask0; + r->n[0] = (r->n[0] & mask0) | (a->n[0] & mask1); + r->n[1] = (r->n[1] & mask0) | (a->n[1] & mask1); + r->n[2] = (r->n[2] & mask0) | (a->n[2] & mask1); + r->n[3] = (r->n[3] & mask0) | (a->n[3] & mask1); + r->n[4] = (r->n[4] & mask0) | (a->n[4] & mask1); + r->n[5] = (r->n[5] & mask0) | (a->n[5] & mask1); + r->n[6] = (r->n[6] & mask0) | (a->n[6] & mask1); + r->n[7] = (r->n[7] & mask0) | (a->n[7] & mask1); +} + +static void secp256k1_fe_to_storage(secp256k1_fe_storage *r, const secp256k1_fe *a) { +#ifdef VERIFY + VERIFY_CHECK(a->normalized); +#endif + r->n[0] = a->n[0] | a->n[1] << 26; + r->n[1] = a->n[1] >> 6 | a->n[2] << 20; + r->n[2] = a->n[2] >> 12 | a->n[3] << 14; + r->n[3] = a->n[3] >> 18 | a->n[4] << 8; + r->n[4] = a->n[4] >> 24 | a->n[5] << 2 | a->n[6] << 28; + r->n[5] = a->n[6] >> 4 | a->n[7] << 22; + r->n[6] = a->n[7] >> 10 | a->n[8] << 16; + r->n[7] = a->n[8] >> 16 | a->n[9] << 10; +} + +static SECP256K1_INLINE void secp256k1_fe_from_storage(secp256k1_fe *r, const secp256k1_fe_storage *a) { + r->n[0] = a->n[0] & 0x3FFFFFFUL; + r->n[1] = a->n[0] >> 26 | ((a->n[1] << 6) & 0x3FFFFFFUL); + r->n[2] = a->n[1] >> 20 | ((a->n[2] << 12) & 0x3FFFFFFUL); + r->n[3] = a->n[2] >> 14 | ((a->n[3] << 18) & 0x3FFFFFFUL); + r->n[4] = a->n[3] >> 8 | ((a->n[4] << 24) & 0x3FFFFFFUL); + r->n[5] = (a->n[4] >> 2) & 0x3FFFFFFUL; + r->n[6] = a->n[4] >> 28 | ((a->n[5] << 4) & 0x3FFFFFFUL); + r->n[7] = a->n[5] >> 22 | ((a->n[6] << 10) & 0x3FFFFFFUL); + r->n[8] = a->n[6] >> 16 | ((a->n[7] << 16) & 0x3FFFFFFUL); + r->n[9] = a->n[7] >> 10; +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 1; +#endif +} + +#endif /* SECP256K1_FIELD_REPR_IMPL_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_5x52.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_5x52.h new file mode 100644 index 000000000..bccd8feb4 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_5x52.h @@ -0,0 +1,47 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_FIELD_REPR_H +#define SECP256K1_FIELD_REPR_H + +#include + +typedef struct { + /* X = sum(i=0..4, elem[i]*2^52) mod n */ + uint64_t n[5]; +#ifdef VERIFY + int magnitude; + int normalized; +#endif +} secp256k1_fe; + +/* Unpacks a constant into a overlapping multi-limbed FE element. */ +#define SECP256K1_FE_CONST_INNER(d7, d6, d5, d4, d3, d2, d1, d0) { \ + (d0) | (((uint64_t)(d1) & 0xFFFFFUL) << 32), \ + ((uint64_t)(d1) >> 20) | (((uint64_t)(d2)) << 12) | (((uint64_t)(d3) & 0xFFUL) << 44), \ + ((uint64_t)(d3) >> 8) | (((uint64_t)(d4) & 0xFFFFFFFUL) << 24), \ + ((uint64_t)(d4) >> 28) | (((uint64_t)(d5)) << 4) | (((uint64_t)(d6) & 0xFFFFUL) << 36), \ + ((uint64_t)(d6) >> 16) | (((uint64_t)(d7)) << 16) \ +} + +#ifdef VERIFY +#define SECP256K1_FE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {SECP256K1_FE_CONST_INNER((d7), (d6), (d5), (d4), (d3), (d2), (d1), (d0)), 1, 1} +#else +#define SECP256K1_FE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {SECP256K1_FE_CONST_INNER((d7), (d6), (d5), (d4), (d3), (d2), (d1), (d0))} +#endif + +typedef struct { + uint64_t n[4]; +} secp256k1_fe_storage; + +#define SECP256K1_FE_STORAGE_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{ \ + (d0) | (((uint64_t)(d1)) << 32), \ + (d2) | (((uint64_t)(d3)) << 32), \ + (d4) | (((uint64_t)(d5)) << 32), \ + (d6) | (((uint64_t)(d7)) << 32) \ +}} + +#endif /* SECP256K1_FIELD_REPR_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_5x52_asm_impl.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_5x52_asm_impl.h new file mode 100644 index 000000000..1fc3171f6 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_5x52_asm_impl.h @@ -0,0 +1,502 @@ +/********************************************************************** + * Copyright (c) 2013-2014 Diederik Huys, Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +/** + * Changelog: + * - March 2013, Diederik Huys: original version + * - November 2014, Pieter Wuille: updated to use Peter Dettman's parallel multiplication algorithm + * - December 2014, Pieter Wuille: converted from YASM to GCC inline assembly + */ + +#ifndef SECP256K1_FIELD_INNER5X52_IMPL_H +#define SECP256K1_FIELD_INNER5X52_IMPL_H + +SECP256K1_INLINE static void secp256k1_fe_mul_inner(uint64_t *r, const uint64_t *a, const uint64_t * SECP256K1_RESTRICT b) { +/** + * Registers: rdx:rax = multiplication accumulator + * r9:r8 = c + * r15:rcx = d + * r10-r14 = a0-a4 + * rbx = b + * rdi = r + * rsi = a / t? + */ + uint64_t tmp1, tmp2, tmp3; +__asm__ __volatile__( + "movq 0(%%rsi),%%r10\n" + "movq 8(%%rsi),%%r11\n" + "movq 16(%%rsi),%%r12\n" + "movq 24(%%rsi),%%r13\n" + "movq 32(%%rsi),%%r14\n" + + /* d += a3 * b0 */ + "movq 0(%%rbx),%%rax\n" + "mulq %%r13\n" + "movq %%rax,%%rcx\n" + "movq %%rdx,%%r15\n" + /* d += a2 * b1 */ + "movq 8(%%rbx),%%rax\n" + "mulq %%r12\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += a1 * b2 */ + "movq 16(%%rbx),%%rax\n" + "mulq %%r11\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d = a0 * b3 */ + "movq 24(%%rbx),%%rax\n" + "mulq %%r10\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* c = a4 * b4 */ + "movq 32(%%rbx),%%rax\n" + "mulq %%r14\n" + "movq %%rax,%%r8\n" + "movq %%rdx,%%r9\n" + /* d += (c & M) * R */ + "movq $0xfffffffffffff,%%rdx\n" + "andq %%rdx,%%rax\n" + "movq $0x1000003d10,%%rdx\n" + "mulq %%rdx\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* c >>= 52 (%%r8 only) */ + "shrdq $52,%%r9,%%r8\n" + /* t3 (tmp1) = d & M */ + "movq %%rcx,%%rsi\n" + "movq $0xfffffffffffff,%%rdx\n" + "andq %%rdx,%%rsi\n" + "movq %%rsi,%q1\n" + /* d >>= 52 */ + "shrdq $52,%%r15,%%rcx\n" + "xorq %%r15,%%r15\n" + /* d += a4 * b0 */ + "movq 0(%%rbx),%%rax\n" + "mulq %%r14\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += a3 * b1 */ + "movq 8(%%rbx),%%rax\n" + "mulq %%r13\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += a2 * b2 */ + "movq 16(%%rbx),%%rax\n" + "mulq %%r12\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += a1 * b3 */ + "movq 24(%%rbx),%%rax\n" + "mulq %%r11\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += a0 * b4 */ + "movq 32(%%rbx),%%rax\n" + "mulq %%r10\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += c * R */ + "movq %%r8,%%rax\n" + "movq $0x1000003d10,%%rdx\n" + "mulq %%rdx\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* t4 = d & M (%%rsi) */ + "movq %%rcx,%%rsi\n" + "movq $0xfffffffffffff,%%rdx\n" + "andq %%rdx,%%rsi\n" + /* d >>= 52 */ + "shrdq $52,%%r15,%%rcx\n" + "xorq %%r15,%%r15\n" + /* tx = t4 >> 48 (tmp3) */ + "movq %%rsi,%%rax\n" + "shrq $48,%%rax\n" + "movq %%rax,%q3\n" + /* t4 &= (M >> 4) (tmp2) */ + "movq $0xffffffffffff,%%rax\n" + "andq %%rax,%%rsi\n" + "movq %%rsi,%q2\n" + /* c = a0 * b0 */ + "movq 0(%%rbx),%%rax\n" + "mulq %%r10\n" + "movq %%rax,%%r8\n" + "movq %%rdx,%%r9\n" + /* d += a4 * b1 */ + "movq 8(%%rbx),%%rax\n" + "mulq %%r14\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += a3 * b2 */ + "movq 16(%%rbx),%%rax\n" + "mulq %%r13\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += a2 * b3 */ + "movq 24(%%rbx),%%rax\n" + "mulq %%r12\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += a1 * b4 */ + "movq 32(%%rbx),%%rax\n" + "mulq %%r11\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* u0 = d & M (%%rsi) */ + "movq %%rcx,%%rsi\n" + "movq $0xfffffffffffff,%%rdx\n" + "andq %%rdx,%%rsi\n" + /* d >>= 52 */ + "shrdq $52,%%r15,%%rcx\n" + "xorq %%r15,%%r15\n" + /* u0 = (u0 << 4) | tx (%%rsi) */ + "shlq $4,%%rsi\n" + "movq %q3,%%rax\n" + "orq %%rax,%%rsi\n" + /* c += u0 * (R >> 4) */ + "movq $0x1000003d1,%%rax\n" + "mulq %%rsi\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* r[0] = c & M */ + "movq %%r8,%%rax\n" + "movq $0xfffffffffffff,%%rdx\n" + "andq %%rdx,%%rax\n" + "movq %%rax,0(%%rdi)\n" + /* c >>= 52 */ + "shrdq $52,%%r9,%%r8\n" + "xorq %%r9,%%r9\n" + /* c += a1 * b0 */ + "movq 0(%%rbx),%%rax\n" + "mulq %%r11\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* c += a0 * b1 */ + "movq 8(%%rbx),%%rax\n" + "mulq %%r10\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* d += a4 * b2 */ + "movq 16(%%rbx),%%rax\n" + "mulq %%r14\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += a3 * b3 */ + "movq 24(%%rbx),%%rax\n" + "mulq %%r13\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += a2 * b4 */ + "movq 32(%%rbx),%%rax\n" + "mulq %%r12\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* c += (d & M) * R */ + "movq %%rcx,%%rax\n" + "movq $0xfffffffffffff,%%rdx\n" + "andq %%rdx,%%rax\n" + "movq $0x1000003d10,%%rdx\n" + "mulq %%rdx\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* d >>= 52 */ + "shrdq $52,%%r15,%%rcx\n" + "xorq %%r15,%%r15\n" + /* r[1] = c & M */ + "movq %%r8,%%rax\n" + "movq $0xfffffffffffff,%%rdx\n" + "andq %%rdx,%%rax\n" + "movq %%rax,8(%%rdi)\n" + /* c >>= 52 */ + "shrdq $52,%%r9,%%r8\n" + "xorq %%r9,%%r9\n" + /* c += a2 * b0 */ + "movq 0(%%rbx),%%rax\n" + "mulq %%r12\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* c += a1 * b1 */ + "movq 8(%%rbx),%%rax\n" + "mulq %%r11\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* c += a0 * b2 (last use of %%r10 = a0) */ + "movq 16(%%rbx),%%rax\n" + "mulq %%r10\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* fetch t3 (%%r10, overwrites a0), t4 (%%rsi) */ + "movq %q2,%%rsi\n" + "movq %q1,%%r10\n" + /* d += a4 * b3 */ + "movq 24(%%rbx),%%rax\n" + "mulq %%r14\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* d += a3 * b4 */ + "movq 32(%%rbx),%%rax\n" + "mulq %%r13\n" + "addq %%rax,%%rcx\n" + "adcq %%rdx,%%r15\n" + /* c += (d & M) * R */ + "movq %%rcx,%%rax\n" + "movq $0xfffffffffffff,%%rdx\n" + "andq %%rdx,%%rax\n" + "movq $0x1000003d10,%%rdx\n" + "mulq %%rdx\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* d >>= 52 (%%rcx only) */ + "shrdq $52,%%r15,%%rcx\n" + /* r[2] = c & M */ + "movq %%r8,%%rax\n" + "movq $0xfffffffffffff,%%rdx\n" + "andq %%rdx,%%rax\n" + "movq %%rax,16(%%rdi)\n" + /* c >>= 52 */ + "shrdq $52,%%r9,%%r8\n" + "xorq %%r9,%%r9\n" + /* c += t3 */ + "addq %%r10,%%r8\n" + /* c += d * R */ + "movq %%rcx,%%rax\n" + "movq $0x1000003d10,%%rdx\n" + "mulq %%rdx\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* r[3] = c & M */ + "movq %%r8,%%rax\n" + "movq $0xfffffffffffff,%%rdx\n" + "andq %%rdx,%%rax\n" + "movq %%rax,24(%%rdi)\n" + /* c >>= 52 (%%r8 only) */ + "shrdq $52,%%r9,%%r8\n" + /* c += t4 (%%r8 only) */ + "addq %%rsi,%%r8\n" + /* r[4] = c */ + "movq %%r8,32(%%rdi)\n" +: "+S"(a), "=m"(tmp1), "=m"(tmp2), "=m"(tmp3) +: "b"(b), "D"(r) +: "%rax", "%rcx", "%rdx", "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15", "cc", "memory" +); +} + +SECP256K1_INLINE static void secp256k1_fe_sqr_inner(uint64_t *r, const uint64_t *a) { +/** + * Registers: rdx:rax = multiplication accumulator + * r9:r8 = c + * rcx:rbx = d + * r10-r14 = a0-a4 + * r15 = M (0xfffffffffffff) + * rdi = r + * rsi = a / t? + */ + uint64_t tmp1, tmp2, tmp3; +__asm__ __volatile__( + "movq 0(%%rsi),%%r10\n" + "movq 8(%%rsi),%%r11\n" + "movq 16(%%rsi),%%r12\n" + "movq 24(%%rsi),%%r13\n" + "movq 32(%%rsi),%%r14\n" + "movq $0xfffffffffffff,%%r15\n" + + /* d = (a0*2) * a3 */ + "leaq (%%r10,%%r10,1),%%rax\n" + "mulq %%r13\n" + "movq %%rax,%%rbx\n" + "movq %%rdx,%%rcx\n" + /* d += (a1*2) * a2 */ + "leaq (%%r11,%%r11,1),%%rax\n" + "mulq %%r12\n" + "addq %%rax,%%rbx\n" + "adcq %%rdx,%%rcx\n" + /* c = a4 * a4 */ + "movq %%r14,%%rax\n" + "mulq %%r14\n" + "movq %%rax,%%r8\n" + "movq %%rdx,%%r9\n" + /* d += (c & M) * R */ + "andq %%r15,%%rax\n" + "movq $0x1000003d10,%%rdx\n" + "mulq %%rdx\n" + "addq %%rax,%%rbx\n" + "adcq %%rdx,%%rcx\n" + /* c >>= 52 (%%r8 only) */ + "shrdq $52,%%r9,%%r8\n" + /* t3 (tmp1) = d & M */ + "movq %%rbx,%%rsi\n" + "andq %%r15,%%rsi\n" + "movq %%rsi,%q1\n" + /* d >>= 52 */ + "shrdq $52,%%rcx,%%rbx\n" + "xorq %%rcx,%%rcx\n" + /* a4 *= 2 */ + "addq %%r14,%%r14\n" + /* d += a0 * a4 */ + "movq %%r10,%%rax\n" + "mulq %%r14\n" + "addq %%rax,%%rbx\n" + "adcq %%rdx,%%rcx\n" + /* d+= (a1*2) * a3 */ + "leaq (%%r11,%%r11,1),%%rax\n" + "mulq %%r13\n" + "addq %%rax,%%rbx\n" + "adcq %%rdx,%%rcx\n" + /* d += a2 * a2 */ + "movq %%r12,%%rax\n" + "mulq %%r12\n" + "addq %%rax,%%rbx\n" + "adcq %%rdx,%%rcx\n" + /* d += c * R */ + "movq %%r8,%%rax\n" + "movq $0x1000003d10,%%rdx\n" + "mulq %%rdx\n" + "addq %%rax,%%rbx\n" + "adcq %%rdx,%%rcx\n" + /* t4 = d & M (%%rsi) */ + "movq %%rbx,%%rsi\n" + "andq %%r15,%%rsi\n" + /* d >>= 52 */ + "shrdq $52,%%rcx,%%rbx\n" + "xorq %%rcx,%%rcx\n" + /* tx = t4 >> 48 (tmp3) */ + "movq %%rsi,%%rax\n" + "shrq $48,%%rax\n" + "movq %%rax,%q3\n" + /* t4 &= (M >> 4) (tmp2) */ + "movq $0xffffffffffff,%%rax\n" + "andq %%rax,%%rsi\n" + "movq %%rsi,%q2\n" + /* c = a0 * a0 */ + "movq %%r10,%%rax\n" + "mulq %%r10\n" + "movq %%rax,%%r8\n" + "movq %%rdx,%%r9\n" + /* d += a1 * a4 */ + "movq %%r11,%%rax\n" + "mulq %%r14\n" + "addq %%rax,%%rbx\n" + "adcq %%rdx,%%rcx\n" + /* d += (a2*2) * a3 */ + "leaq (%%r12,%%r12,1),%%rax\n" + "mulq %%r13\n" + "addq %%rax,%%rbx\n" + "adcq %%rdx,%%rcx\n" + /* u0 = d & M (%%rsi) */ + "movq %%rbx,%%rsi\n" + "andq %%r15,%%rsi\n" + /* d >>= 52 */ + "shrdq $52,%%rcx,%%rbx\n" + "xorq %%rcx,%%rcx\n" + /* u0 = (u0 << 4) | tx (%%rsi) */ + "shlq $4,%%rsi\n" + "movq %q3,%%rax\n" + "orq %%rax,%%rsi\n" + /* c += u0 * (R >> 4) */ + "movq $0x1000003d1,%%rax\n" + "mulq %%rsi\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* r[0] = c & M */ + "movq %%r8,%%rax\n" + "andq %%r15,%%rax\n" + "movq %%rax,0(%%rdi)\n" + /* c >>= 52 */ + "shrdq $52,%%r9,%%r8\n" + "xorq %%r9,%%r9\n" + /* a0 *= 2 */ + "addq %%r10,%%r10\n" + /* c += a0 * a1 */ + "movq %%r10,%%rax\n" + "mulq %%r11\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* d += a2 * a4 */ + "movq %%r12,%%rax\n" + "mulq %%r14\n" + "addq %%rax,%%rbx\n" + "adcq %%rdx,%%rcx\n" + /* d += a3 * a3 */ + "movq %%r13,%%rax\n" + "mulq %%r13\n" + "addq %%rax,%%rbx\n" + "adcq %%rdx,%%rcx\n" + /* c += (d & M) * R */ + "movq %%rbx,%%rax\n" + "andq %%r15,%%rax\n" + "movq $0x1000003d10,%%rdx\n" + "mulq %%rdx\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* d >>= 52 */ + "shrdq $52,%%rcx,%%rbx\n" + "xorq %%rcx,%%rcx\n" + /* r[1] = c & M */ + "movq %%r8,%%rax\n" + "andq %%r15,%%rax\n" + "movq %%rax,8(%%rdi)\n" + /* c >>= 52 */ + "shrdq $52,%%r9,%%r8\n" + "xorq %%r9,%%r9\n" + /* c += a0 * a2 (last use of %%r10) */ + "movq %%r10,%%rax\n" + "mulq %%r12\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* fetch t3 (%%r10, overwrites a0),t4 (%%rsi) */ + "movq %q2,%%rsi\n" + "movq %q1,%%r10\n" + /* c += a1 * a1 */ + "movq %%r11,%%rax\n" + "mulq %%r11\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* d += a3 * a4 */ + "movq %%r13,%%rax\n" + "mulq %%r14\n" + "addq %%rax,%%rbx\n" + "adcq %%rdx,%%rcx\n" + /* c += (d & M) * R */ + "movq %%rbx,%%rax\n" + "andq %%r15,%%rax\n" + "movq $0x1000003d10,%%rdx\n" + "mulq %%rdx\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* d >>= 52 (%%rbx only) */ + "shrdq $52,%%rcx,%%rbx\n" + /* r[2] = c & M */ + "movq %%r8,%%rax\n" + "andq %%r15,%%rax\n" + "movq %%rax,16(%%rdi)\n" + /* c >>= 52 */ + "shrdq $52,%%r9,%%r8\n" + "xorq %%r9,%%r9\n" + /* c += t3 */ + "addq %%r10,%%r8\n" + /* c += d * R */ + "movq %%rbx,%%rax\n" + "movq $0x1000003d10,%%rdx\n" + "mulq %%rdx\n" + "addq %%rax,%%r8\n" + "adcq %%rdx,%%r9\n" + /* r[3] = c & M */ + "movq %%r8,%%rax\n" + "andq %%r15,%%rax\n" + "movq %%rax,24(%%rdi)\n" + /* c >>= 52 (%%r8 only) */ + "shrdq $52,%%r9,%%r8\n" + /* c += t4 (%%r8 only) */ + "addq %%rsi,%%r8\n" + /* r[4] = c */ + "movq %%r8,32(%%rdi)\n" +: "+S"(a), "=m"(tmp1), "=m"(tmp2), "=m"(tmp3) +: "D"(r) +: "%rax", "%rbx", "%rcx", "%rdx", "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15", "cc", "memory" +); +} + +#endif /* SECP256K1_FIELD_INNER5X52_IMPL_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_5x52_impl.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_5x52_impl.h new file mode 100644 index 000000000..004dd8bd1 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_5x52_impl.h @@ -0,0 +1,494 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_FIELD_REPR_IMPL_H +#define SECP256K1_FIELD_REPR_IMPL_H + +#include "secp256k1-config.h" + +#include "util.h" +#include "num.h" +#include "field.h" + +#if defined(USE_ASM_X86_64) +#include "field_5x52_asm_impl.h" +#else +#include "field_5x52_int128_impl.h" +#endif + +/** Implements arithmetic modulo FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE FFFFFC2F, + * represented as 5 uint64_t's in base 2^52. The values are allowed to contain >52 each. In particular, + * each FieldElem has a 'magnitude' associated with it. Internally, a magnitude M means each element + * is at most M*(2^53-1), except the most significant one, which is limited to M*(2^49-1). All operations + * accept any input with magnitude at most M, and have different rules for propagating magnitude to their + * output. + */ + +#ifdef VERIFY +static void secp256k1_fe_verify(const secp256k1_fe *a) { + const uint64_t *d = a->n; + int m = a->normalized ? 1 : 2 * a->magnitude, r = 1; + /* secp256k1 'p' value defined in "Standards for Efficient Cryptography" (SEC2) 2.7.1. */ + r &= (d[0] <= 0xFFFFFFFFFFFFFULL * m); + r &= (d[1] <= 0xFFFFFFFFFFFFFULL * m); + r &= (d[2] <= 0xFFFFFFFFFFFFFULL * m); + r &= (d[3] <= 0xFFFFFFFFFFFFFULL * m); + r &= (d[4] <= 0x0FFFFFFFFFFFFULL * m); + r &= (a->magnitude >= 0); + r &= (a->magnitude <= 2048); + if (a->normalized) { + r &= (a->magnitude <= 1); + if (r && (d[4] == 0x0FFFFFFFFFFFFULL) && ((d[3] & d[2] & d[1]) == 0xFFFFFFFFFFFFFULL)) { + r &= (d[0] < 0xFFFFEFFFFFC2FULL); + } + } + VERIFY_CHECK(r == 1); +} +#endif + +static void secp256k1_fe_normalize(secp256k1_fe *r) { + uint64_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4]; + + /* Reduce t4 at the start so there will be at most a single carry from the first pass */ + uint64_t m; + uint64_t x = t4 >> 48; t4 &= 0x0FFFFFFFFFFFFULL; + + /* The first pass ensures the magnitude is 1, ... */ + t0 += x * 0x1000003D1ULL; + t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL; + t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL; m = t1; + t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL; m &= t2; + t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL; m &= t3; + + /* ... except for a possible carry at bit 48 of t4 (i.e. bit 256 of the field element) */ + VERIFY_CHECK(t4 >> 49 == 0); + + /* At most a single final reduction is needed; check if the value is >= the field characteristic */ + x = (t4 >> 48) | ((t4 == 0x0FFFFFFFFFFFFULL) & (m == 0xFFFFFFFFFFFFFULL) + & (t0 >= 0xFFFFEFFFFFC2FULL)); + + /* Apply the final reduction (for constant-time behaviour, we do it always) */ + t0 += x * 0x1000003D1ULL; + t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL; + t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL; + t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL; + t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL; + + /* If t4 didn't carry to bit 48 already, then it should have after any final reduction */ + VERIFY_CHECK(t4 >> 48 == x); + + /* Mask off the possible multiple of 2^256 from the final reduction */ + t4 &= 0x0FFFFFFFFFFFFULL; + + r->n[0] = t0; r->n[1] = t1; r->n[2] = t2; r->n[3] = t3; r->n[4] = t4; + +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 1; + secp256k1_fe_verify(r); +#endif +} + +static void secp256k1_fe_normalize_weak(secp256k1_fe *r) { + uint64_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4]; + + /* Reduce t4 at the start so there will be at most a single carry from the first pass */ + uint64_t x = t4 >> 48; t4 &= 0x0FFFFFFFFFFFFULL; + + /* The first pass ensures the magnitude is 1, ... */ + t0 += x * 0x1000003D1ULL; + t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL; + t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL; + t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL; + t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL; + + /* ... except for a possible carry at bit 48 of t4 (i.e. bit 256 of the field element) */ + VERIFY_CHECK(t4 >> 49 == 0); + + r->n[0] = t0; r->n[1] = t1; r->n[2] = t2; r->n[3] = t3; r->n[4] = t4; + +#ifdef VERIFY + r->magnitude = 1; + secp256k1_fe_verify(r); +#endif +} + +static void secp256k1_fe_normalize_var(secp256k1_fe *r) { + uint64_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4]; + + /* Reduce t4 at the start so there will be at most a single carry from the first pass */ + uint64_t m; + uint64_t x = t4 >> 48; t4 &= 0x0FFFFFFFFFFFFULL; + + /* The first pass ensures the magnitude is 1, ... */ + t0 += x * 0x1000003D1ULL; + t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL; + t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL; m = t1; + t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL; m &= t2; + t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL; m &= t3; + + /* ... except for a possible carry at bit 48 of t4 (i.e. bit 256 of the field element) */ + VERIFY_CHECK(t4 >> 49 == 0); + + /* At most a single final reduction is needed; check if the value is >= the field characteristic */ + x = (t4 >> 48) | ((t4 == 0x0FFFFFFFFFFFFULL) & (m == 0xFFFFFFFFFFFFFULL) + & (t0 >= 0xFFFFEFFFFFC2FULL)); + + if (x) { + t0 += 0x1000003D1ULL; + t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL; + t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL; + t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL; + t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL; + + /* If t4 didn't carry to bit 48 already, then it should have after any final reduction */ + VERIFY_CHECK(t4 >> 48 == x); + + /* Mask off the possible multiple of 2^256 from the final reduction */ + t4 &= 0x0FFFFFFFFFFFFULL; + } + + r->n[0] = t0; r->n[1] = t1; r->n[2] = t2; r->n[3] = t3; r->n[4] = t4; + +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 1; + secp256k1_fe_verify(r); +#endif +} + +static int secp256k1_fe_normalizes_to_zero(secp256k1_fe *r) { + uint64_t t0 = r->n[0], t1 = r->n[1], t2 = r->n[2], t3 = r->n[3], t4 = r->n[4]; + + /* z0 tracks a possible raw value of 0, z1 tracks a possible raw value of P */ + uint64_t z0, z1; + + /* Reduce t4 at the start so there will be at most a single carry from the first pass */ + uint64_t x = t4 >> 48; t4 &= 0x0FFFFFFFFFFFFULL; + + /* The first pass ensures the magnitude is 1, ... */ + t0 += x * 0x1000003D1ULL; + t1 += (t0 >> 52); t0 &= 0xFFFFFFFFFFFFFULL; z0 = t0; z1 = t0 ^ 0x1000003D0ULL; + t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL; z0 |= t1; z1 &= t1; + t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL; z0 |= t2; z1 &= t2; + t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL; z0 |= t3; z1 &= t3; + z0 |= t4; z1 &= t4 ^ 0xF000000000000ULL; + + /* ... except for a possible carry at bit 48 of t4 (i.e. bit 256 of the field element) */ + VERIFY_CHECK(t4 >> 49 == 0); + + return (z0 == 0) | (z1 == 0xFFFFFFFFFFFFFULL); +} + +static int secp256k1_fe_normalizes_to_zero_var(secp256k1_fe *r) { + uint64_t t0, t1, t2, t3, t4; + uint64_t z0, z1; + uint64_t x; + + t0 = r->n[0]; + t4 = r->n[4]; + + /* Reduce t4 at the start so there will be at most a single carry from the first pass */ + x = t4 >> 48; + + /* The first pass ensures the magnitude is 1, ... */ + t0 += x * 0x1000003D1ULL; + + /* z0 tracks a possible raw value of 0, z1 tracks a possible raw value of P */ + z0 = t0 & 0xFFFFFFFFFFFFFULL; + z1 = z0 ^ 0x1000003D0ULL; + + /* Fast return path should catch the majority of cases */ + if ((z0 != 0ULL) & (z1 != 0xFFFFFFFFFFFFFULL)) { + return 0; + } + + t1 = r->n[1]; + t2 = r->n[2]; + t3 = r->n[3]; + + t4 &= 0x0FFFFFFFFFFFFULL; + + t1 += (t0 >> 52); + t2 += (t1 >> 52); t1 &= 0xFFFFFFFFFFFFFULL; z0 |= t1; z1 &= t1; + t3 += (t2 >> 52); t2 &= 0xFFFFFFFFFFFFFULL; z0 |= t2; z1 &= t2; + t4 += (t3 >> 52); t3 &= 0xFFFFFFFFFFFFFULL; z0 |= t3; z1 &= t3; + z0 |= t4; z1 &= t4 ^ 0xF000000000000ULL; + + /* ... except for a possible carry at bit 48 of t4 (i.e. bit 256 of the field element) */ + VERIFY_CHECK(t4 >> 49 == 0); + + return (z0 == 0) | (z1 == 0xFFFFFFFFFFFFFULL); +} + +SECP256K1_INLINE static void secp256k1_fe_set_int(secp256k1_fe *r, int a) { + r->n[0] = a; + r->n[1] = r->n[2] = r->n[3] = r->n[4] = 0; +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 1; + secp256k1_fe_verify(r); +#endif +} + +SECP256K1_INLINE static int secp256k1_fe_is_zero(const secp256k1_fe *a) { + const uint64_t *t = a->n; +#ifdef VERIFY + VERIFY_CHECK(a->normalized); + secp256k1_fe_verify(a); +#endif + return (t[0] | t[1] | t[2] | t[3] | t[4]) == 0; +} + +SECP256K1_INLINE static int secp256k1_fe_is_odd(const secp256k1_fe *a) { +#ifdef VERIFY + VERIFY_CHECK(a->normalized); + secp256k1_fe_verify(a); +#endif + return a->n[0] & 1; +} + +SECP256K1_INLINE static void secp256k1_fe_clear(secp256k1_fe *a) { + int i; +#ifdef VERIFY + a->magnitude = 0; + a->normalized = 1; +#endif + for (i=0; i<5; i++) { + a->n[i] = 0; + } +} + +static int secp256k1_fe_cmp_var(const secp256k1_fe *a, const secp256k1_fe *b) { + int i; +#ifdef VERIFY + VERIFY_CHECK(a->normalized); + VERIFY_CHECK(b->normalized); + secp256k1_fe_verify(a); + secp256k1_fe_verify(b); +#endif + for (i = 4; i >= 0; i--) { + if (a->n[i] > b->n[i]) { + return 1; + } + if (a->n[i] < b->n[i]) { + return -1; + } + } + return 0; +} + +static int secp256k1_fe_set_b32(secp256k1_fe *r, const unsigned char *a) { + r->n[0] = (uint64_t)a[31] + | ((uint64_t)a[30] << 8) + | ((uint64_t)a[29] << 16) + | ((uint64_t)a[28] << 24) + | ((uint64_t)a[27] << 32) + | ((uint64_t)a[26] << 40) + | ((uint64_t)(a[25] & 0xF) << 48); + r->n[1] = (uint64_t)((a[25] >> 4) & 0xF) + | ((uint64_t)a[24] << 4) + | ((uint64_t)a[23] << 12) + | ((uint64_t)a[22] << 20) + | ((uint64_t)a[21] << 28) + | ((uint64_t)a[20] << 36) + | ((uint64_t)a[19] << 44); + r->n[2] = (uint64_t)a[18] + | ((uint64_t)a[17] << 8) + | ((uint64_t)a[16] << 16) + | ((uint64_t)a[15] << 24) + | ((uint64_t)a[14] << 32) + | ((uint64_t)a[13] << 40) + | ((uint64_t)(a[12] & 0xF) << 48); + r->n[3] = (uint64_t)((a[12] >> 4) & 0xF) + | ((uint64_t)a[11] << 4) + | ((uint64_t)a[10] << 12) + | ((uint64_t)a[9] << 20) + | ((uint64_t)a[8] << 28) + | ((uint64_t)a[7] << 36) + | ((uint64_t)a[6] << 44); + r->n[4] = (uint64_t)a[5] + | ((uint64_t)a[4] << 8) + | ((uint64_t)a[3] << 16) + | ((uint64_t)a[2] << 24) + | ((uint64_t)a[1] << 32) + | ((uint64_t)a[0] << 40); + if (r->n[4] == 0x0FFFFFFFFFFFFULL && (r->n[3] & r->n[2] & r->n[1]) == 0xFFFFFFFFFFFFFULL && r->n[0] >= 0xFFFFEFFFFFC2FULL) { + return 0; + } +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 1; + secp256k1_fe_verify(r); +#endif + return 1; +} + +/** Convert a field element to a 32-byte big endian value. Requires the input to be normalized */ +static void secp256k1_fe_get_b32(unsigned char *r, const secp256k1_fe *a) { +#ifdef VERIFY + VERIFY_CHECK(a->normalized); + secp256k1_fe_verify(a); +#endif + r[0] = (a->n[4] >> 40) & 0xFF; + r[1] = (a->n[4] >> 32) & 0xFF; + r[2] = (a->n[4] >> 24) & 0xFF; + r[3] = (a->n[4] >> 16) & 0xFF; + r[4] = (a->n[4] >> 8) & 0xFF; + r[5] = a->n[4] & 0xFF; + r[6] = (a->n[3] >> 44) & 0xFF; + r[7] = (a->n[3] >> 36) & 0xFF; + r[8] = (a->n[3] >> 28) & 0xFF; + r[9] = (a->n[3] >> 20) & 0xFF; + r[10] = (a->n[3] >> 12) & 0xFF; + r[11] = (a->n[3] >> 4) & 0xFF; + r[12] = ((a->n[2] >> 48) & 0xF) | ((a->n[3] & 0xF) << 4); + r[13] = (a->n[2] >> 40) & 0xFF; + r[14] = (a->n[2] >> 32) & 0xFF; + r[15] = (a->n[2] >> 24) & 0xFF; + r[16] = (a->n[2] >> 16) & 0xFF; + r[17] = (a->n[2] >> 8) & 0xFF; + r[18] = a->n[2] & 0xFF; + r[19] = (a->n[1] >> 44) & 0xFF; + r[20] = (a->n[1] >> 36) & 0xFF; + r[21] = (a->n[1] >> 28) & 0xFF; + r[22] = (a->n[1] >> 20) & 0xFF; + r[23] = (a->n[1] >> 12) & 0xFF; + r[24] = (a->n[1] >> 4) & 0xFF; + r[25] = ((a->n[0] >> 48) & 0xF) | ((a->n[1] & 0xF) << 4); + r[26] = (a->n[0] >> 40) & 0xFF; + r[27] = (a->n[0] >> 32) & 0xFF; + r[28] = (a->n[0] >> 24) & 0xFF; + r[29] = (a->n[0] >> 16) & 0xFF; + r[30] = (a->n[0] >> 8) & 0xFF; + r[31] = a->n[0] & 0xFF; +} + +SECP256K1_INLINE static void secp256k1_fe_negate(secp256k1_fe *r, const secp256k1_fe *a, int m) { +#ifdef VERIFY + VERIFY_CHECK(a->magnitude <= m); + secp256k1_fe_verify(a); +#endif + r->n[0] = 0xFFFFEFFFFFC2FULL * 2 * (m + 1) - a->n[0]; + r->n[1] = 0xFFFFFFFFFFFFFULL * 2 * (m + 1) - a->n[1]; + r->n[2] = 0xFFFFFFFFFFFFFULL * 2 * (m + 1) - a->n[2]; + r->n[3] = 0xFFFFFFFFFFFFFULL * 2 * (m + 1) - a->n[3]; + r->n[4] = 0x0FFFFFFFFFFFFULL * 2 * (m + 1) - a->n[4]; +#ifdef VERIFY + r->magnitude = m + 1; + r->normalized = 0; + secp256k1_fe_verify(r); +#endif +} + +SECP256K1_INLINE static void secp256k1_fe_mul_int(secp256k1_fe *r, int a) { + r->n[0] *= a; + r->n[1] *= a; + r->n[2] *= a; + r->n[3] *= a; + r->n[4] *= a; +#ifdef VERIFY + r->magnitude *= a; + r->normalized = 0; + secp256k1_fe_verify(r); +#endif +} + +SECP256K1_INLINE static void secp256k1_fe_add(secp256k1_fe *r, const secp256k1_fe *a) { +#ifdef VERIFY + secp256k1_fe_verify(a); +#endif + r->n[0] += a->n[0]; + r->n[1] += a->n[1]; + r->n[2] += a->n[2]; + r->n[3] += a->n[3]; + r->n[4] += a->n[4]; +#ifdef VERIFY + r->magnitude += a->magnitude; + r->normalized = 0; + secp256k1_fe_verify(r); +#endif +} + +static void secp256k1_fe_mul(secp256k1_fe *r, const secp256k1_fe *a, const secp256k1_fe * SECP256K1_RESTRICT b) { +#ifdef VERIFY + VERIFY_CHECK(a->magnitude <= 8); + VERIFY_CHECK(b->magnitude <= 8); + secp256k1_fe_verify(a); + secp256k1_fe_verify(b); + VERIFY_CHECK(r != b); +#endif + secp256k1_fe_mul_inner(r->n, a->n, b->n); +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 0; + secp256k1_fe_verify(r); +#endif +} + +static void secp256k1_fe_sqr(secp256k1_fe *r, const secp256k1_fe *a) { +#ifdef VERIFY + VERIFY_CHECK(a->magnitude <= 8); + secp256k1_fe_verify(a); +#endif + secp256k1_fe_sqr_inner(r->n, a->n); +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 0; + secp256k1_fe_verify(r); +#endif +} + +static SECP256K1_INLINE void secp256k1_fe_cmov(secp256k1_fe *r, const secp256k1_fe *a, int flag) { + uint64_t mask0, mask1; + mask0 = flag + ~((uint64_t)0); + mask1 = ~mask0; + r->n[0] = (r->n[0] & mask0) | (a->n[0] & mask1); + r->n[1] = (r->n[1] & mask0) | (a->n[1] & mask1); + r->n[2] = (r->n[2] & mask0) | (a->n[2] & mask1); + r->n[3] = (r->n[3] & mask0) | (a->n[3] & mask1); + r->n[4] = (r->n[4] & mask0) | (a->n[4] & mask1); +#ifdef VERIFY + if (a->magnitude > r->magnitude) { + r->magnitude = a->magnitude; + } + r->normalized &= a->normalized; +#endif +} + +static SECP256K1_INLINE void secp256k1_fe_storage_cmov(secp256k1_fe_storage *r, const secp256k1_fe_storage *a, int flag) { + uint64_t mask0, mask1; + mask0 = flag + ~((uint64_t)0); + mask1 = ~mask0; + r->n[0] = (r->n[0] & mask0) | (a->n[0] & mask1); + r->n[1] = (r->n[1] & mask0) | (a->n[1] & mask1); + r->n[2] = (r->n[2] & mask0) | (a->n[2] & mask1); + r->n[3] = (r->n[3] & mask0) | (a->n[3] & mask1); +} + +static void secp256k1_fe_to_storage(secp256k1_fe_storage *r, const secp256k1_fe *a) { +#ifdef VERIFY + VERIFY_CHECK(a->normalized); +#endif + r->n[0] = a->n[0] | a->n[1] << 52; + r->n[1] = a->n[1] >> 12 | a->n[2] << 40; + r->n[2] = a->n[2] >> 24 | a->n[3] << 28; + r->n[3] = a->n[3] >> 36 | a->n[4] << 16; +} + +static SECP256K1_INLINE void secp256k1_fe_from_storage(secp256k1_fe *r, const secp256k1_fe_storage *a) { + r->n[0] = a->n[0] & 0xFFFFFFFFFFFFFULL; + r->n[1] = a->n[0] >> 52 | ((a->n[1] << 12) & 0xFFFFFFFFFFFFFULL); + r->n[2] = a->n[1] >> 40 | ((a->n[2] << 24) & 0xFFFFFFFFFFFFFULL); + r->n[3] = a->n[2] >> 28 | ((a->n[3] << 36) & 0xFFFFFFFFFFFFFULL); + r->n[4] = a->n[3] >> 16; +#ifdef VERIFY + r->magnitude = 1; + r->normalized = 1; +#endif +} + +#endif /* SECP256K1_FIELD_REPR_IMPL_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_5x52_int128_impl.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_5x52_int128_impl.h new file mode 100644 index 000000000..95a0d1791 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_5x52_int128_impl.h @@ -0,0 +1,277 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_FIELD_INNER5X52_IMPL_H +#define SECP256K1_FIELD_INNER5X52_IMPL_H + +#include + +#ifdef VERIFY +#define VERIFY_BITS(x, n) VERIFY_CHECK(((x) >> (n)) == 0) +#else +#define VERIFY_BITS(x, n) do { } while(0) +#endif + +SECP256K1_INLINE static void secp256k1_fe_mul_inner(uint64_t *r, const uint64_t *a, const uint64_t * SECP256K1_RESTRICT b) { + uint128_t c, d; + uint64_t t3, t4, tx, u0; + uint64_t a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4]; + const uint64_t M = 0xFFFFFFFFFFFFFULL, R = 0x1000003D10ULL; + + VERIFY_BITS(a[0], 56); + VERIFY_BITS(a[1], 56); + VERIFY_BITS(a[2], 56); + VERIFY_BITS(a[3], 56); + VERIFY_BITS(a[4], 52); + VERIFY_BITS(b[0], 56); + VERIFY_BITS(b[1], 56); + VERIFY_BITS(b[2], 56); + VERIFY_BITS(b[3], 56); + VERIFY_BITS(b[4], 52); + VERIFY_CHECK(r != b); + + /* [... a b c] is a shorthand for ... + a<<104 + b<<52 + c<<0 mod n. + * px is a shorthand for sum(a[i]*b[x-i], i=0..x). + * Note that [x 0 0 0 0 0] = [x*R]. + */ + + d = (uint128_t)a0 * b[3] + + (uint128_t)a1 * b[2] + + (uint128_t)a2 * b[1] + + (uint128_t)a3 * b[0]; + VERIFY_BITS(d, 114); + /* [d 0 0 0] = [p3 0 0 0] */ + c = (uint128_t)a4 * b[4]; + VERIFY_BITS(c, 112); + /* [c 0 0 0 0 d 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */ + d += (c & M) * R; c >>= 52; + VERIFY_BITS(d, 115); + VERIFY_BITS(c, 60); + /* [c 0 0 0 0 0 d 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */ + t3 = d & M; d >>= 52; + VERIFY_BITS(t3, 52); + VERIFY_BITS(d, 63); + /* [c 0 0 0 0 d t3 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */ + + d += (uint128_t)a0 * b[4] + + (uint128_t)a1 * b[3] + + (uint128_t)a2 * b[2] + + (uint128_t)a3 * b[1] + + (uint128_t)a4 * b[0]; + VERIFY_BITS(d, 115); + /* [c 0 0 0 0 d t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */ + d += c * R; + VERIFY_BITS(d, 116); + /* [d t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */ + t4 = d & M; d >>= 52; + VERIFY_BITS(t4, 52); + VERIFY_BITS(d, 64); + /* [d t4 t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */ + tx = (t4 >> 48); t4 &= (M >> 4); + VERIFY_BITS(tx, 4); + VERIFY_BITS(t4, 48); + /* [d t4+(tx<<48) t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */ + + c = (uint128_t)a0 * b[0]; + VERIFY_BITS(c, 112); + /* [d t4+(tx<<48) t3 0 0 c] = [p8 0 0 0 p4 p3 0 0 p0] */ + d += (uint128_t)a1 * b[4] + + (uint128_t)a2 * b[3] + + (uint128_t)a3 * b[2] + + (uint128_t)a4 * b[1]; + VERIFY_BITS(d, 115); + /* [d t4+(tx<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */ + u0 = d & M; d >>= 52; + VERIFY_BITS(u0, 52); + VERIFY_BITS(d, 63); + /* [d u0 t4+(tx<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */ + /* [d 0 t4+(tx<<48)+(u0<<52) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */ + u0 = (u0 << 4) | tx; + VERIFY_BITS(u0, 56); + /* [d 0 t4+(u0<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */ + c += (uint128_t)u0 * (R >> 4); + VERIFY_BITS(c, 115); + /* [d 0 t4 t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */ + r[0] = c & M; c >>= 52; + VERIFY_BITS(r[0], 52); + VERIFY_BITS(c, 61); + /* [d 0 t4 t3 0 c r0] = [p8 0 0 p5 p4 p3 0 0 p0] */ + + c += (uint128_t)a0 * b[1] + + (uint128_t)a1 * b[0]; + VERIFY_BITS(c, 114); + /* [d 0 t4 t3 0 c r0] = [p8 0 0 p5 p4 p3 0 p1 p0] */ + d += (uint128_t)a2 * b[4] + + (uint128_t)a3 * b[3] + + (uint128_t)a4 * b[2]; + VERIFY_BITS(d, 114); + /* [d 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */ + c += (d & M) * R; d >>= 52; + VERIFY_BITS(c, 115); + VERIFY_BITS(d, 62); + /* [d 0 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */ + r[1] = c & M; c >>= 52; + VERIFY_BITS(r[1], 52); + VERIFY_BITS(c, 63); + /* [d 0 0 t4 t3 c r1 r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */ + + c += (uint128_t)a0 * b[2] + + (uint128_t)a1 * b[1] + + (uint128_t)a2 * b[0]; + VERIFY_BITS(c, 114); + /* [d 0 0 t4 t3 c r1 r0] = [p8 0 p6 p5 p4 p3 p2 p1 p0] */ + d += (uint128_t)a3 * b[4] + + (uint128_t)a4 * b[3]; + VERIFY_BITS(d, 114); + /* [d 0 0 t4 t3 c t1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + c += (d & M) * R; d >>= 52; + VERIFY_BITS(c, 115); + VERIFY_BITS(d, 62); + /* [d 0 0 0 t4 t3 c r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + + /* [d 0 0 0 t4 t3 c r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[2] = c & M; c >>= 52; + VERIFY_BITS(r[2], 52); + VERIFY_BITS(c, 63); + /* [d 0 0 0 t4 t3+c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + c += d * R + t3; + VERIFY_BITS(c, 100); + /* [t4 c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[3] = c & M; c >>= 52; + VERIFY_BITS(r[3], 52); + VERIFY_BITS(c, 48); + /* [t4+c r3 r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + c += t4; + VERIFY_BITS(c, 49); + /* [c r3 r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[4] = c; + VERIFY_BITS(r[4], 49); + /* [r4 r3 r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ +} + +SECP256K1_INLINE static void secp256k1_fe_sqr_inner(uint64_t *r, const uint64_t *a) { + uint128_t c, d; + uint64_t a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4]; + int64_t t3, t4, tx, u0; + const uint64_t M = 0xFFFFFFFFFFFFFULL, R = 0x1000003D10ULL; + + VERIFY_BITS(a[0], 56); + VERIFY_BITS(a[1], 56); + VERIFY_BITS(a[2], 56); + VERIFY_BITS(a[3], 56); + VERIFY_BITS(a[4], 52); + + /** [... a b c] is a shorthand for ... + a<<104 + b<<52 + c<<0 mod n. + * px is a shorthand for sum(a[i]*a[x-i], i=0..x). + * Note that [x 0 0 0 0 0] = [x*R]. + */ + + d = (uint128_t)(a0*2) * a3 + + (uint128_t)(a1*2) * a2; + VERIFY_BITS(d, 114); + /* [d 0 0 0] = [p3 0 0 0] */ + c = (uint128_t)a4 * a4; + VERIFY_BITS(c, 112); + /* [c 0 0 0 0 d 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */ + d += (c & M) * R; c >>= 52; + VERIFY_BITS(d, 115); + VERIFY_BITS(c, 60); + /* [c 0 0 0 0 0 d 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */ + t3 = d & M; d >>= 52; + VERIFY_BITS(t3, 52); + VERIFY_BITS(d, 63); + /* [c 0 0 0 0 d t3 0 0 0] = [p8 0 0 0 0 p3 0 0 0] */ + + a4 *= 2; + d += (uint128_t)a0 * a4 + + (uint128_t)(a1*2) * a3 + + (uint128_t)a2 * a2; + VERIFY_BITS(d, 115); + /* [c 0 0 0 0 d t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */ + d += c * R; + VERIFY_BITS(d, 116); + /* [d t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */ + t4 = d & M; d >>= 52; + VERIFY_BITS(t4, 52); + VERIFY_BITS(d, 64); + /* [d t4 t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */ + tx = (t4 >> 48); t4 &= (M >> 4); + VERIFY_BITS(tx, 4); + VERIFY_BITS(t4, 48); + /* [d t4+(tx<<48) t3 0 0 0] = [p8 0 0 0 p4 p3 0 0 0] */ + + c = (uint128_t)a0 * a0; + VERIFY_BITS(c, 112); + /* [d t4+(tx<<48) t3 0 0 c] = [p8 0 0 0 p4 p3 0 0 p0] */ + d += (uint128_t)a1 * a4 + + (uint128_t)(a2*2) * a3; + VERIFY_BITS(d, 114); + /* [d t4+(tx<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */ + u0 = d & M; d >>= 52; + VERIFY_BITS(u0, 52); + VERIFY_BITS(d, 62); + /* [d u0 t4+(tx<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */ + /* [d 0 t4+(tx<<48)+(u0<<52) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */ + u0 = (u0 << 4) | tx; + VERIFY_BITS(u0, 56); + /* [d 0 t4+(u0<<48) t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */ + c += (uint128_t)u0 * (R >> 4); + VERIFY_BITS(c, 113); + /* [d 0 t4 t3 0 0 c] = [p8 0 0 p5 p4 p3 0 0 p0] */ + r[0] = c & M; c >>= 52; + VERIFY_BITS(r[0], 52); + VERIFY_BITS(c, 61); + /* [d 0 t4 t3 0 c r0] = [p8 0 0 p5 p4 p3 0 0 p0] */ + + a0 *= 2; + c += (uint128_t)a0 * a1; + VERIFY_BITS(c, 114); + /* [d 0 t4 t3 0 c r0] = [p8 0 0 p5 p4 p3 0 p1 p0] */ + d += (uint128_t)a2 * a4 + + (uint128_t)a3 * a3; + VERIFY_BITS(d, 114); + /* [d 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */ + c += (d & M) * R; d >>= 52; + VERIFY_BITS(c, 115); + VERIFY_BITS(d, 62); + /* [d 0 0 t4 t3 0 c r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */ + r[1] = c & M; c >>= 52; + VERIFY_BITS(r[1], 52); + VERIFY_BITS(c, 63); + /* [d 0 0 t4 t3 c r1 r0] = [p8 0 p6 p5 p4 p3 0 p1 p0] */ + + c += (uint128_t)a0 * a2 + + (uint128_t)a1 * a1; + VERIFY_BITS(c, 114); + /* [d 0 0 t4 t3 c r1 r0] = [p8 0 p6 p5 p4 p3 p2 p1 p0] */ + d += (uint128_t)a3 * a4; + VERIFY_BITS(d, 114); + /* [d 0 0 t4 t3 c r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + c += (d & M) * R; d >>= 52; + VERIFY_BITS(c, 115); + VERIFY_BITS(d, 62); + /* [d 0 0 0 t4 t3 c r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[2] = c & M; c >>= 52; + VERIFY_BITS(r[2], 52); + VERIFY_BITS(c, 63); + /* [d 0 0 0 t4 t3+c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + + c += d * R + t3; + VERIFY_BITS(c, 100); + /* [t4 c r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[3] = c & M; c >>= 52; + VERIFY_BITS(r[3], 52); + VERIFY_BITS(c, 48); + /* [t4+c r3 r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + c += t4; + VERIFY_BITS(c, 49); + /* [c r3 r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ + r[4] = c; + VERIFY_BITS(r[4], 49); + /* [r4 r3 r2 r1 r0] = [p8 p7 p6 p5 p4 p3 p2 p1 p0] */ +} + +#endif /* SECP256K1_FIELD_INNER5X52_IMPL_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_impl.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_impl.h new file mode 100644 index 000000000..685e74b72 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/field_impl.h @@ -0,0 +1,313 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_FIELD_IMPL_H +#define SECP256K1_FIELD_IMPL_H + +#include "secp256k1-config.h" + +#include "util.h" + +#if defined(USE_FIELD_10X26) +#include "field_10x26_impl.h" +#elif defined(USE_FIELD_5X52) +#include "field_5x52_impl.h" +#else +#error "Please select field implementation" +#endif + +SECP256K1_INLINE static int secp256k1_fe_equal(const secp256k1_fe *a, const secp256k1_fe *b) { + secp256k1_fe na; + secp256k1_fe_negate(&na, a, 1); + secp256k1_fe_add(&na, b); + return secp256k1_fe_normalizes_to_zero(&na); +} + +SECP256K1_INLINE static int secp256k1_fe_equal_var(const secp256k1_fe *a, const secp256k1_fe *b) { + secp256k1_fe na; + secp256k1_fe_negate(&na, a, 1); + secp256k1_fe_add(&na, b); + return secp256k1_fe_normalizes_to_zero_var(&na); +} + +static int secp256k1_fe_sqrt(secp256k1_fe *r, const secp256k1_fe *a) { + /** Given that p is congruent to 3 mod 4, we can compute the square root of + * a mod p as the (p+1)/4'th power of a. + * + * As (p+1)/4 is an even number, it will have the same result for a and for + * (-a). Only one of these two numbers actually has a square root however, + * so we test at the end by squaring and comparing to the input. + * Also because (p+1)/4 is an even number, the computed square root is + * itself always a square (a ** ((p+1)/4) is the square of a ** ((p+1)/8)). + */ + secp256k1_fe x2, x3, x6, x9, x11, x22, x44, x88, x176, x220, x223, t1; + int j; + + /** The binary representation of (p + 1)/4 has 3 blocks of 1s, with lengths in + * { 2, 22, 223 }. Use an addition chain to calculate 2^n - 1 for each block: + * 1, [2], 3, 6, 9, 11, [22], 44, 88, 176, 220, [223] + */ + + secp256k1_fe_sqr(&x2, a); + secp256k1_fe_mul(&x2, &x2, a); + + secp256k1_fe_sqr(&x3, &x2); + secp256k1_fe_mul(&x3, &x3, a); + + x6 = x3; + for (j=0; j<3; j++) { + secp256k1_fe_sqr(&x6, &x6); + } + secp256k1_fe_mul(&x6, &x6, &x3); + + x9 = x6; + for (j=0; j<3; j++) { + secp256k1_fe_sqr(&x9, &x9); + } + secp256k1_fe_mul(&x9, &x9, &x3); + + x11 = x9; + for (j=0; j<2; j++) { + secp256k1_fe_sqr(&x11, &x11); + } + secp256k1_fe_mul(&x11, &x11, &x2); + + x22 = x11; + for (j=0; j<11; j++) { + secp256k1_fe_sqr(&x22, &x22); + } + secp256k1_fe_mul(&x22, &x22, &x11); + + x44 = x22; + for (j=0; j<22; j++) { + secp256k1_fe_sqr(&x44, &x44); + } + secp256k1_fe_mul(&x44, &x44, &x22); + + x88 = x44; + for (j=0; j<44; j++) { + secp256k1_fe_sqr(&x88, &x88); + } + secp256k1_fe_mul(&x88, &x88, &x44); + + x176 = x88; + for (j=0; j<88; j++) { + secp256k1_fe_sqr(&x176, &x176); + } + secp256k1_fe_mul(&x176, &x176, &x88); + + x220 = x176; + for (j=0; j<44; j++) { + secp256k1_fe_sqr(&x220, &x220); + } + secp256k1_fe_mul(&x220, &x220, &x44); + + x223 = x220; + for (j=0; j<3; j++) { + secp256k1_fe_sqr(&x223, &x223); + } + secp256k1_fe_mul(&x223, &x223, &x3); + + /* The final result is then assembled using a sliding window over the blocks. */ + + t1 = x223; + for (j=0; j<23; j++) { + secp256k1_fe_sqr(&t1, &t1); + } + secp256k1_fe_mul(&t1, &t1, &x22); + for (j=0; j<6; j++) { + secp256k1_fe_sqr(&t1, &t1); + } + secp256k1_fe_mul(&t1, &t1, &x2); + secp256k1_fe_sqr(&t1, &t1); + secp256k1_fe_sqr(r, &t1); + + /* Check that a square root was actually calculated */ + + secp256k1_fe_sqr(&t1, r); + return secp256k1_fe_equal(&t1, a); +} + +static void secp256k1_fe_inv(secp256k1_fe *r, const secp256k1_fe *a) { + secp256k1_fe x2, x3, x6, x9, x11, x22, x44, x88, x176, x220, x223, t1; + int j; + + /** The binary representation of (p - 2) has 5 blocks of 1s, with lengths in + * { 1, 2, 22, 223 }. Use an addition chain to calculate 2^n - 1 for each block: + * [1], [2], 3, 6, 9, 11, [22], 44, 88, 176, 220, [223] + */ + + secp256k1_fe_sqr(&x2, a); + secp256k1_fe_mul(&x2, &x2, a); + + secp256k1_fe_sqr(&x3, &x2); + secp256k1_fe_mul(&x3, &x3, a); + + x6 = x3; + for (j=0; j<3; j++) { + secp256k1_fe_sqr(&x6, &x6); + } + secp256k1_fe_mul(&x6, &x6, &x3); + + x9 = x6; + for (j=0; j<3; j++) { + secp256k1_fe_sqr(&x9, &x9); + } + secp256k1_fe_mul(&x9, &x9, &x3); + + x11 = x9; + for (j=0; j<2; j++) { + secp256k1_fe_sqr(&x11, &x11); + } + secp256k1_fe_mul(&x11, &x11, &x2); + + x22 = x11; + for (j=0; j<11; j++) { + secp256k1_fe_sqr(&x22, &x22); + } + secp256k1_fe_mul(&x22, &x22, &x11); + + x44 = x22; + for (j=0; j<22; j++) { + secp256k1_fe_sqr(&x44, &x44); + } + secp256k1_fe_mul(&x44, &x44, &x22); + + x88 = x44; + for (j=0; j<44; j++) { + secp256k1_fe_sqr(&x88, &x88); + } + secp256k1_fe_mul(&x88, &x88, &x44); + + x176 = x88; + for (j=0; j<88; j++) { + secp256k1_fe_sqr(&x176, &x176); + } + secp256k1_fe_mul(&x176, &x176, &x88); + + x220 = x176; + for (j=0; j<44; j++) { + secp256k1_fe_sqr(&x220, &x220); + } + secp256k1_fe_mul(&x220, &x220, &x44); + + x223 = x220; + for (j=0; j<3; j++) { + secp256k1_fe_sqr(&x223, &x223); + } + secp256k1_fe_mul(&x223, &x223, &x3); + + /* The final result is then assembled using a sliding window over the blocks. */ + + t1 = x223; + for (j=0; j<23; j++) { + secp256k1_fe_sqr(&t1, &t1); + } + secp256k1_fe_mul(&t1, &t1, &x22); + for (j=0; j<5; j++) { + secp256k1_fe_sqr(&t1, &t1); + } + secp256k1_fe_mul(&t1, &t1, a); + for (j=0; j<3; j++) { + secp256k1_fe_sqr(&t1, &t1); + } + secp256k1_fe_mul(&t1, &t1, &x2); + for (j=0; j<2; j++) { + secp256k1_fe_sqr(&t1, &t1); + } + secp256k1_fe_mul(r, a, &t1); +} + +static void secp256k1_fe_inv_var(secp256k1_fe *r, const secp256k1_fe *a) { +#if defined(USE_FIELD_INV_BUILTIN) + secp256k1_fe_inv(r, a); +#elif defined(USE_FIELD_INV_NUM) + secp256k1_num n, m; + static const secp256k1_fe negone = SECP256K1_FE_CONST( + 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, + 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFEUL, 0xFFFFFC2EUL + ); + /* secp256k1 field prime, value p defined in "Standards for Efficient Cryptography" (SEC2) 2.7.1. */ + static const unsigned char prime[32] = { + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F + }; + unsigned char b[32]; + int res; + secp256k1_fe c = *a; + secp256k1_fe_normalize_var(&c); + secp256k1_fe_get_b32(b, &c); + secp256k1_num_set_bin(&n, b, 32); + secp256k1_num_set_bin(&m, prime, 32); + secp256k1_num_mod_inverse(&n, &n, &m); + secp256k1_num_get_bin(b, 32, &n); + res = secp256k1_fe_set_b32(r, b); + (void)res; + VERIFY_CHECK(res); + /* Verify the result is the (unique) valid inverse using non-GMP code. */ + secp256k1_fe_mul(&c, &c, r); + secp256k1_fe_add(&c, &negone); + CHECK(secp256k1_fe_normalizes_to_zero_var(&c)); +#else +#error "Please select field inverse implementation" +#endif +} + +static void secp256k1_fe_inv_all_var(secp256k1_fe *r, const secp256k1_fe *a, size_t len) { + secp256k1_fe u; + size_t i; + if (len < 1) { + return; + } + + VERIFY_CHECK((r + len <= a) || (a + len <= r)); + + r[0] = a[0]; + + i = 0; + while (++i < len) { + secp256k1_fe_mul(&r[i], &r[i - 1], &a[i]); + } + + secp256k1_fe_inv_var(&u, &r[--i]); + + while (i > 0) { + size_t j = i--; + secp256k1_fe_mul(&r[j], &r[i], &u); + secp256k1_fe_mul(&u, &u, &a[j]); + } + + r[0] = u; +} + +static int secp256k1_fe_is_quad_var(const secp256k1_fe *a) { +#ifndef USE_NUM_NONE + unsigned char b[32]; + secp256k1_num n; + secp256k1_num m; + /* secp256k1 field prime, value p defined in "Standards for Efficient Cryptography" (SEC2) 2.7.1. */ + static const unsigned char prime[32] = { + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F + }; + + secp256k1_fe c = *a; + secp256k1_fe_normalize_var(&c); + secp256k1_fe_get_b32(b, &c); + secp256k1_num_set_bin(&n, b, 32); + secp256k1_num_set_bin(&m, prime, 32); + return secp256k1_num_jacobi(&n, &m) >= 0; +#else + secp256k1_fe r; + return secp256k1_fe_sqrt(&r, a); +#endif +} + +#endif /* SECP256K1_FIELD_IMPL_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/group.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/group.h new file mode 100644 index 000000000..3947ea2dd --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/group.h @@ -0,0 +1,147 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_GROUP_H +#define SECP256K1_GROUP_H + +#include "num.h" +#include "field.h" + +/** A group element of the secp256k1 curve, in affine coordinates. */ +typedef struct { + secp256k1_fe x; + secp256k1_fe y; + int infinity; /* whether this represents the point at infinity */ +} secp256k1_ge; + +#define SECP256K1_GE_CONST(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) {SECP256K1_FE_CONST((a),(b),(c),(d),(e),(f),(g),(h)), SECP256K1_FE_CONST((i),(j),(k),(l),(m),(n),(o),(p)), 0} +#define SECP256K1_GE_CONST_INFINITY {SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 0), SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 0), 1} + +/** A group element of the secp256k1 curve, in jacobian coordinates. */ +typedef struct { + secp256k1_fe x; /* actual X: x/z^2 */ + secp256k1_fe y; /* actual Y: y/z^3 */ + secp256k1_fe z; + int infinity; /* whether this represents the point at infinity */ +} secp256k1_gej; + +#define SECP256K1_GEJ_CONST(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) {SECP256K1_FE_CONST((a),(b),(c),(d),(e),(f),(g),(h)), SECP256K1_FE_CONST((i),(j),(k),(l),(m),(n),(o),(p)), SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 1), 0} +#define SECP256K1_GEJ_CONST_INFINITY {SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 0), SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 0), SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 0), 1} + +typedef struct { + secp256k1_fe_storage x; + secp256k1_fe_storage y; +} secp256k1_ge_storage; + +#define SECP256K1_GE_STORAGE_CONST(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) {SECP256K1_FE_STORAGE_CONST((a),(b),(c),(d),(e),(f),(g),(h)), SECP256K1_FE_STORAGE_CONST((i),(j),(k),(l),(m),(n),(o),(p))} + +#define SECP256K1_GE_STORAGE_CONST_GET(t) SECP256K1_FE_STORAGE_CONST_GET(t.x), SECP256K1_FE_STORAGE_CONST_GET(t.y) + +/** Set a group element equal to the point with given X and Y coordinates */ +static void secp256k1_ge_set_xy(secp256k1_ge *r, const secp256k1_fe *x, const secp256k1_fe *y); + +/** Set a group element (affine) equal to the point with the given X coordinate + * and a Y coordinate that is a quadratic residue modulo p. The return value + * is true iff a coordinate with the given X coordinate exists. + */ +static int secp256k1_ge_set_xquad(secp256k1_ge *r, const secp256k1_fe *x); + +/** Set a group element (affine) equal to the point with the given X coordinate, and given oddness + * for Y. Return value indicates whether the result is valid. */ +static int secp256k1_ge_set_xo_var(secp256k1_ge *r, const secp256k1_fe *x, int odd); + +/** Check whether a group element is the point at infinity. */ +static int secp256k1_ge_is_infinity(const secp256k1_ge *a); + +/** Check whether a group element is valid (i.e., on the curve). */ +static int secp256k1_ge_is_valid_var(const secp256k1_ge *a); + +static void secp256k1_ge_neg(secp256k1_ge *r, const secp256k1_ge *a); + +/** Set a group element equal to another which is given in jacobian coordinates */ +static void secp256k1_ge_set_gej(secp256k1_ge *r, secp256k1_gej *a); + +/** Set a batch of group elements equal to the inputs given in jacobian coordinates */ +static void secp256k1_ge_set_all_gej_var(secp256k1_ge *r, const secp256k1_gej *a, size_t len, const secp256k1_callback *cb); + +/** Set a batch of group elements equal to the inputs given in jacobian + * coordinates (with known z-ratios). zr must contain the known z-ratios such + * that mul(a[i].z, zr[i+1]) == a[i+1].z. zr[0] is ignored. */ +static void secp256k1_ge_set_table_gej_var(secp256k1_ge *r, const secp256k1_gej *a, const secp256k1_fe *zr, size_t len); + +/** Bring a batch inputs given in jacobian coordinates (with known z-ratios) to + * the same global z "denominator". zr must contain the known z-ratios such + * that mul(a[i].z, zr[i+1]) == a[i+1].z. zr[0] is ignored. The x and y + * coordinates of the result are stored in r, the common z coordinate is + * stored in globalz. */ +static void secp256k1_ge_globalz_set_table_gej(size_t len, secp256k1_ge *r, secp256k1_fe *globalz, const secp256k1_gej *a, const secp256k1_fe *zr); + +/** Set a group element (affine) equal to the point at infinity. */ +static void secp256k1_ge_set_infinity(secp256k1_ge *r); + +/** Set a group element (jacobian) equal to the point at infinity. */ +static void secp256k1_gej_set_infinity(secp256k1_gej *r); + +/** Set a group element (jacobian) equal to another which is given in affine coordinates. */ +static void secp256k1_gej_set_ge(secp256k1_gej *r, const secp256k1_ge *a); + +/** Compare the X coordinate of a group element (jacobian). */ +static int secp256k1_gej_eq_x_var(const secp256k1_fe *x, const secp256k1_gej *a); + +/** Set r equal to the inverse of a (i.e., mirrored around the X axis) */ +static void secp256k1_gej_neg(secp256k1_gej *r, const secp256k1_gej *a); + +/** Check whether a group element is the point at infinity. */ +static int secp256k1_gej_is_infinity(const secp256k1_gej *a); + +/** Check whether a group element's y coordinate is a quadratic residue. */ +static int secp256k1_gej_has_quad_y_var(const secp256k1_gej *a); + +/** Set r equal to the double of a. If rzr is not-NULL, r->z = a->z * *rzr (where infinity means an implicit z = 0). + * a may not be zero. Constant time. */ +static void secp256k1_gej_double_nonzero(secp256k1_gej *r, const secp256k1_gej *a, secp256k1_fe *rzr); + +/** Set r equal to the double of a. If rzr is not-NULL, r->z = a->z * *rzr (where infinity means an implicit z = 0). */ +static void secp256k1_gej_double_var(secp256k1_gej *r, const secp256k1_gej *a, secp256k1_fe *rzr); + +/** Set r equal to the sum of a and b. If rzr is non-NULL, r->z = a->z * *rzr (a cannot be infinity in that case). */ +static void secp256k1_gej_add_var(secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_gej *b, secp256k1_fe *rzr); + +/** Set r equal to the sum of a and b (with b given in affine coordinates, and not infinity). */ +static void secp256k1_gej_add_ge(secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_ge *b); + +/** Set r equal to the sum of a and b (with b given in affine coordinates). This is more efficient + than secp256k1_gej_add_var. It is identical to secp256k1_gej_add_ge but without constant-time + guarantee, and b is allowed to be infinity. If rzr is non-NULL, r->z = a->z * *rzr (a cannot be infinity in that case). */ +static void secp256k1_gej_add_ge_var(secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_ge *b, secp256k1_fe *rzr); + +/** Set r equal to the sum of a and b (with the inverse of b's Z coordinate passed as bzinv). */ +static void secp256k1_gej_add_zinv_var(secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_ge *b, const secp256k1_fe *bzinv); + +#ifdef USE_ENDOMORPHISM +/** Set r to be equal to lambda times a, where lambda is chosen in a way such that this is very fast. */ +static void secp256k1_ge_mul_lambda(secp256k1_ge *r, const secp256k1_ge *a); +#endif + +/** Clear a secp256k1_gej to prevent leaking sensitive information. */ +static void secp256k1_gej_clear(secp256k1_gej *r); + +/** Clear a secp256k1_ge to prevent leaking sensitive information. */ +static void secp256k1_ge_clear(secp256k1_ge *r); + +/** Convert a group element to the storage type. */ +static void secp256k1_ge_to_storage(secp256k1_ge_storage *r, const secp256k1_ge *a); + +/** Convert a group element back from the storage type. */ +static void secp256k1_ge_from_storage(secp256k1_ge *r, const secp256k1_ge_storage *a); + +/** If flag is true, set *r equal to *a; otherwise leave it. Constant-time. */ +static void secp256k1_ge_storage_cmov(secp256k1_ge_storage *r, const secp256k1_ge_storage *a, int flag); + +/** Rescale a jacobian point by b which must be non-zero. Constant-time. */ +static void secp256k1_gej_rescale(secp256k1_gej *r, const secp256k1_fe *b); + +#endif /* SECP256K1_GROUP_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/group_impl.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/group_impl.h new file mode 100644 index 000000000..b1ace87b6 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/group_impl.h @@ -0,0 +1,706 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_GROUP_IMPL_H +#define SECP256K1_GROUP_IMPL_H + +#include "num.h" +#include "field.h" +#include "group.h" + +/* These points can be generated in sage as follows: + * + * 0. Setup a worksheet with the following parameters. + * b = 4 # whatever CURVE_B will be set to + * F = FiniteField (0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F) + * C = EllipticCurve ([F (0), F (b)]) + * + * 1. Determine all the small orders available to you. (If there are + * no satisfactory ones, go back and change b.) + * print C.order().factor(limit=1000) + * + * 2. Choose an order as one of the prime factors listed in the above step. + * (You can also multiply some to get a composite order, though the + * tests will crash trying to invert scalars during signing.) We take a + * random point and scale it to drop its order to the desired value. + * There is some probability this won't work; just try again. + * order = 199 + * P = C.random_point() + * P = (int(P.order()) / int(order)) * P + * assert(P.order() == order) + * + * 3. Print the values. You'll need to use a vim macro or something to + * split the hex output into 4-byte chunks. + * print "%x %x" % P.xy() + */ +#if defined(EXHAUSTIVE_TEST_ORDER) +# if EXHAUSTIVE_TEST_ORDER == 199 +const secp256k1_ge secp256k1_ge_const_g = SECP256K1_GE_CONST( + 0xFA7CC9A7, 0x0737F2DB, 0xA749DD39, 0x2B4FB069, + 0x3B017A7D, 0xA808C2F1, 0xFB12940C, 0x9EA66C18, + 0x78AC123A, 0x5ED8AEF3, 0x8732BC91, 0x1F3A2868, + 0x48DF246C, 0x808DAE72, 0xCFE52572, 0x7F0501ED +); + +const int CURVE_B = 4; +# elif EXHAUSTIVE_TEST_ORDER == 13 +const secp256k1_ge secp256k1_ge_const_g = SECP256K1_GE_CONST( + 0xedc60018, 0xa51a786b, 0x2ea91f4d, 0x4c9416c0, + 0x9de54c3b, 0xa1316554, 0x6cf4345c, 0x7277ef15, + 0x54cb1b6b, 0xdc8c1273, 0x087844ea, 0x43f4603e, + 0x0eaf9a43, 0xf6effe55, 0x939f806d, 0x37adf8ac +); +const int CURVE_B = 2; +# else +# error No known generator for the specified exhaustive test group order. +# endif +#else +/** Generator for secp256k1, value 'g' defined in + * "Standards for Efficient Cryptography" (SEC2) 2.7.1. + */ +static const secp256k1_ge secp256k1_ge_const_g = SECP256K1_GE_CONST( + 0x79BE667EUL, 0xF9DCBBACUL, 0x55A06295UL, 0xCE870B07UL, + 0x029BFCDBUL, 0x2DCE28D9UL, 0x59F2815BUL, 0x16F81798UL, + 0x483ADA77UL, 0x26A3C465UL, 0x5DA4FBFCUL, 0x0E1108A8UL, + 0xFD17B448UL, 0xA6855419UL, 0x9C47D08FUL, 0xFB10D4B8UL +); + +const int CURVE_B = 7; +#endif + +static void secp256k1_ge_set_gej_zinv(secp256k1_ge *r, const secp256k1_gej *a, const secp256k1_fe *zi) { + secp256k1_fe zi2; + secp256k1_fe zi3; + secp256k1_fe_sqr(&zi2, zi); + secp256k1_fe_mul(&zi3, &zi2, zi); + secp256k1_fe_mul(&r->x, &a->x, &zi2); + secp256k1_fe_mul(&r->y, &a->y, &zi3); + r->infinity = a->infinity; +} + +static void secp256k1_ge_set_xy(secp256k1_ge *r, const secp256k1_fe *x, const secp256k1_fe *y) { + r->infinity = 0; + r->x = *x; + r->y = *y; +} + +static int secp256k1_ge_is_infinity(const secp256k1_ge *a) { + return a->infinity; +} + +static void secp256k1_ge_neg(secp256k1_ge *r, const secp256k1_ge *a) { + *r = *a; + secp256k1_fe_normalize_weak(&r->y); + secp256k1_fe_negate(&r->y, &r->y, 1); +} + +static void secp256k1_ge_set_gej(secp256k1_ge *r, secp256k1_gej *a) { + secp256k1_fe z2, z3; + r->infinity = a->infinity; + secp256k1_fe_inv(&a->z, &a->z); + secp256k1_fe_sqr(&z2, &a->z); + secp256k1_fe_mul(&z3, &a->z, &z2); + secp256k1_fe_mul(&a->x, &a->x, &z2); + secp256k1_fe_mul(&a->y, &a->y, &z3); + secp256k1_fe_set_int(&a->z, 1); + r->x = a->x; + r->y = a->y; +} + +static void secp256k1_ge_set_gej_var(secp256k1_ge *r, secp256k1_gej *a) { + secp256k1_fe z2, z3; + r->infinity = a->infinity; + if (a->infinity) { + return; + } + secp256k1_fe_inv_var(&a->z, &a->z); + secp256k1_fe_sqr(&z2, &a->z); + secp256k1_fe_mul(&z3, &a->z, &z2); + secp256k1_fe_mul(&a->x, &a->x, &z2); + secp256k1_fe_mul(&a->y, &a->y, &z3); + secp256k1_fe_set_int(&a->z, 1); + r->x = a->x; + r->y = a->y; +} + +static void secp256k1_ge_set_all_gej_var(secp256k1_ge *r, const secp256k1_gej *a, size_t len, const secp256k1_callback *cb) { + secp256k1_fe *az; + secp256k1_fe *azi; + size_t i; + size_t count = 0; + az = (secp256k1_fe *)checked_malloc(cb, sizeof(secp256k1_fe) * len); + for (i = 0; i < len; i++) { + if (!a[i].infinity) { + az[count++] = a[i].z; + } + } + + azi = (secp256k1_fe *)checked_malloc(cb, sizeof(secp256k1_fe) * count); + secp256k1_fe_inv_all_var(azi, az, count); + free(az); + + count = 0; + for (i = 0; i < len; i++) { + r[i].infinity = a[i].infinity; + if (!a[i].infinity) { + secp256k1_ge_set_gej_zinv(&r[i], &a[i], &azi[count++]); + } + } + free(azi); +} + +static void secp256k1_ge_set_table_gej_var(secp256k1_ge *r, const secp256k1_gej *a, const secp256k1_fe *zr, size_t len) { + size_t i = len - 1; + secp256k1_fe zi; + + if (len > 0) { + /* Compute the inverse of the last z coordinate, and use it to compute the last affine output. */ + secp256k1_fe_inv(&zi, &a[i].z); + secp256k1_ge_set_gej_zinv(&r[i], &a[i], &zi); + + /* Work out way backwards, using the z-ratios to scale the x/y values. */ + while (i > 0) { + secp256k1_fe_mul(&zi, &zi, &zr[i]); + i--; + secp256k1_ge_set_gej_zinv(&r[i], &a[i], &zi); + } + } +} + +static void secp256k1_ge_globalz_set_table_gej(size_t len, secp256k1_ge *r, secp256k1_fe *globalz, const secp256k1_gej *a, const secp256k1_fe *zr) { + size_t i = len - 1; + secp256k1_fe zs; + + if (len > 0) { + /* The z of the final point gives us the "global Z" for the table. */ + r[i].x = a[i].x; + r[i].y = a[i].y; + *globalz = a[i].z; + r[i].infinity = 0; + zs = zr[i]; + + /* Work our way backwards, using the z-ratios to scale the x/y values. */ + while (i > 0) { + if (i != len - 1) { + secp256k1_fe_mul(&zs, &zs, &zr[i]); + } + i--; + secp256k1_ge_set_gej_zinv(&r[i], &a[i], &zs); + } + } +} + +static void secp256k1_gej_set_infinity(secp256k1_gej *r) { + r->infinity = 1; + secp256k1_fe_clear(&r->x); + secp256k1_fe_clear(&r->y); + secp256k1_fe_clear(&r->z); +} + +static void secp256k1_ge_set_infinity(secp256k1_ge *r) { + r->infinity = 1; + secp256k1_fe_clear(&r->x); + secp256k1_fe_clear(&r->y); +} + +static void secp256k1_gej_clear(secp256k1_gej *r) { + r->infinity = 0; + secp256k1_fe_clear(&r->x); + secp256k1_fe_clear(&r->y); + secp256k1_fe_clear(&r->z); +} + +static void secp256k1_ge_clear(secp256k1_ge *r) { + r->infinity = 0; + secp256k1_fe_clear(&r->x); + secp256k1_fe_clear(&r->y); +} + +static int secp256k1_ge_set_xquad(secp256k1_ge *r, const secp256k1_fe *x) { + secp256k1_fe x2, x3, c; + r->x = *x; + secp256k1_fe_sqr(&x2, x); + secp256k1_fe_mul(&x3, x, &x2); + r->infinity = 0; + secp256k1_fe_set_int(&c, CURVE_B); + secp256k1_fe_add(&c, &x3); + return secp256k1_fe_sqrt(&r->y, &c); +} + +static int secp256k1_ge_set_xo_var(secp256k1_ge *r, const secp256k1_fe *x, int odd) { + if (!secp256k1_ge_set_xquad(r, x)) { + return 0; + } + secp256k1_fe_normalize_var(&r->y); + if (secp256k1_fe_is_odd(&r->y) != odd) { + secp256k1_fe_negate(&r->y, &r->y, 1); + } + return 1; + +} + +static void secp256k1_gej_set_ge(secp256k1_gej *r, const secp256k1_ge *a) { + r->infinity = a->infinity; + r->x = a->x; + r->y = a->y; + secp256k1_fe_set_int(&r->z, 1); +} + +static int secp256k1_gej_eq_x_var(const secp256k1_fe *x, const secp256k1_gej *a) { + secp256k1_fe r, r2; + VERIFY_CHECK(!a->infinity); + secp256k1_fe_sqr(&r, &a->z); secp256k1_fe_mul(&r, &r, x); + r2 = a->x; secp256k1_fe_normalize_weak(&r2); + return secp256k1_fe_equal_var(&r, &r2); +} + +static void secp256k1_gej_neg(secp256k1_gej *r, const secp256k1_gej *a) { + r->infinity = a->infinity; + r->x = a->x; + r->y = a->y; + r->z = a->z; + secp256k1_fe_normalize_weak(&r->y); + secp256k1_fe_negate(&r->y, &r->y, 1); +} + +static int secp256k1_gej_is_infinity(const secp256k1_gej *a) { + return a->infinity; +} + +static int secp256k1_gej_is_valid_var(const secp256k1_gej *a) { + secp256k1_fe y2, x3, z2, z6; + if (a->infinity) { + return 0; + } + /** y^2 = x^3 + 7 + * (Y/Z^3)^2 = (X/Z^2)^3 + 7 + * Y^2 / Z^6 = X^3 / Z^6 + 7 + * Y^2 = X^3 + 7*Z^6 + */ + secp256k1_fe_sqr(&y2, &a->y); + secp256k1_fe_sqr(&x3, &a->x); secp256k1_fe_mul(&x3, &x3, &a->x); + secp256k1_fe_sqr(&z2, &a->z); + secp256k1_fe_sqr(&z6, &z2); secp256k1_fe_mul(&z6, &z6, &z2); + secp256k1_fe_mul_int(&z6, CURVE_B); + secp256k1_fe_add(&x3, &z6); + secp256k1_fe_normalize_weak(&x3); + return secp256k1_fe_equal_var(&y2, &x3); +} + +static int secp256k1_ge_is_valid_var(const secp256k1_ge *a) { + secp256k1_fe y2, x3, c; + if (a->infinity) { + return 0; + } + /* y^2 = x^3 + 7 */ + secp256k1_fe_sqr(&y2, &a->y); + secp256k1_fe_sqr(&x3, &a->x); secp256k1_fe_mul(&x3, &x3, &a->x); + secp256k1_fe_set_int(&c, CURVE_B); + secp256k1_fe_add(&x3, &c); + secp256k1_fe_normalize_weak(&x3); + return secp256k1_fe_equal_var(&y2, &x3); +} + +static void secp256k1_gej_double_var(secp256k1_gej *r, const secp256k1_gej *a, secp256k1_fe *rzr) { + /* Operations: 3 mul, 4 sqr, 0 normalize, 12 mul_int/add/negate. + * + * Note that there is an implementation described at + * https://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l + * which trades a multiply for a square, but in practice this is actually slower, + * mainly because it requires more normalizations. + */ + secp256k1_fe t1,t2,t3,t4; + /** For secp256k1, 2Q is infinity if and only if Q is infinity. This is because if 2Q = infinity, + * Q must equal -Q, or that Q.y == -(Q.y), or Q.y is 0. For a point on y^2 = x^3 + 7 to have + * y=0, x^3 must be -7 mod p. However, -7 has no cube root mod p. + * + * Having said this, if this function receives a point on a sextic twist, e.g. by + * a fault attack, it is possible for y to be 0. This happens for y^2 = x^3 + 6, + * since -6 does have a cube root mod p. For this point, this function will not set + * the infinity flag even though the point doubles to infinity, and the result + * point will be gibberish (z = 0 but infinity = 0). + */ + r->infinity = a->infinity; + if (r->infinity) { + if (rzr != NULL) { + secp256k1_fe_set_int(rzr, 1); + } + return; + } + + if (rzr != NULL) { + *rzr = a->y; + secp256k1_fe_normalize_weak(rzr); + secp256k1_fe_mul_int(rzr, 2); + } + + secp256k1_fe_mul(&r->z, &a->z, &a->y); + secp256k1_fe_mul_int(&r->z, 2); /* Z' = 2*Y*Z (2) */ + secp256k1_fe_sqr(&t1, &a->x); + secp256k1_fe_mul_int(&t1, 3); /* T1 = 3*X^2 (3) */ + secp256k1_fe_sqr(&t2, &t1); /* T2 = 9*X^4 (1) */ + secp256k1_fe_sqr(&t3, &a->y); + secp256k1_fe_mul_int(&t3, 2); /* T3 = 2*Y^2 (2) */ + secp256k1_fe_sqr(&t4, &t3); + secp256k1_fe_mul_int(&t4, 2); /* T4 = 8*Y^4 (2) */ + secp256k1_fe_mul(&t3, &t3, &a->x); /* T3 = 2*X*Y^2 (1) */ + r->x = t3; + secp256k1_fe_mul_int(&r->x, 4); /* X' = 8*X*Y^2 (4) */ + secp256k1_fe_negate(&r->x, &r->x, 4); /* X' = -8*X*Y^2 (5) */ + secp256k1_fe_add(&r->x, &t2); /* X' = 9*X^4 - 8*X*Y^2 (6) */ + secp256k1_fe_negate(&t2, &t2, 1); /* T2 = -9*X^4 (2) */ + secp256k1_fe_mul_int(&t3, 6); /* T3 = 12*X*Y^2 (6) */ + secp256k1_fe_add(&t3, &t2); /* T3 = 12*X*Y^2 - 9*X^4 (8) */ + secp256k1_fe_mul(&r->y, &t1, &t3); /* Y' = 36*X^3*Y^2 - 27*X^6 (1) */ + secp256k1_fe_negate(&t2, &t4, 2); /* T2 = -8*Y^4 (3) */ + secp256k1_fe_add(&r->y, &t2); /* Y' = 36*X^3*Y^2 - 27*X^6 - 8*Y^4 (4) */ +} + +static SECP256K1_INLINE void secp256k1_gej_double_nonzero(secp256k1_gej *r, const secp256k1_gej *a, secp256k1_fe *rzr) { + VERIFY_CHECK(!secp256k1_gej_is_infinity(a)); + secp256k1_gej_double_var(r, a, rzr); +} + +static void secp256k1_gej_add_var(secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_gej *b, secp256k1_fe *rzr) { + /* Operations: 12 mul, 4 sqr, 2 normalize, 12 mul_int/add/negate */ + secp256k1_fe z22, z12, u1, u2, s1, s2, h, i, i2, h2, h3, t; + + if (a->infinity) { + VERIFY_CHECK(rzr == NULL); + *r = *b; + return; + } + + if (b->infinity) { + if (rzr != NULL) { + secp256k1_fe_set_int(rzr, 1); + } + *r = *a; + return; + } + + r->infinity = 0; + secp256k1_fe_sqr(&z22, &b->z); + secp256k1_fe_sqr(&z12, &a->z); + secp256k1_fe_mul(&u1, &a->x, &z22); + secp256k1_fe_mul(&u2, &b->x, &z12); + secp256k1_fe_mul(&s1, &a->y, &z22); secp256k1_fe_mul(&s1, &s1, &b->z); + secp256k1_fe_mul(&s2, &b->y, &z12); secp256k1_fe_mul(&s2, &s2, &a->z); + secp256k1_fe_negate(&h, &u1, 1); secp256k1_fe_add(&h, &u2); + secp256k1_fe_negate(&i, &s1, 1); secp256k1_fe_add(&i, &s2); + if (secp256k1_fe_normalizes_to_zero_var(&h)) { + if (secp256k1_fe_normalizes_to_zero_var(&i)) { + secp256k1_gej_double_var(r, a, rzr); + } else { + if (rzr != NULL) { + secp256k1_fe_set_int(rzr, 0); + } + r->infinity = 1; + } + return; + } + secp256k1_fe_sqr(&i2, &i); + secp256k1_fe_sqr(&h2, &h); + secp256k1_fe_mul(&h3, &h, &h2); + secp256k1_fe_mul(&h, &h, &b->z); + if (rzr != NULL) { + *rzr = h; + } + secp256k1_fe_mul(&r->z, &a->z, &h); + secp256k1_fe_mul(&t, &u1, &h2); + r->x = t; secp256k1_fe_mul_int(&r->x, 2); secp256k1_fe_add(&r->x, &h3); secp256k1_fe_negate(&r->x, &r->x, 3); secp256k1_fe_add(&r->x, &i2); + secp256k1_fe_negate(&r->y, &r->x, 5); secp256k1_fe_add(&r->y, &t); secp256k1_fe_mul(&r->y, &r->y, &i); + secp256k1_fe_mul(&h3, &h3, &s1); secp256k1_fe_negate(&h3, &h3, 1); + secp256k1_fe_add(&r->y, &h3); +} + +static void secp256k1_gej_add_ge_var(secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_ge *b, secp256k1_fe *rzr) { + /* 8 mul, 3 sqr, 4 normalize, 12 mul_int/add/negate */ + secp256k1_fe z12, u1, u2, s1, s2, h, i, i2, h2, h3, t; + if (a->infinity) { + VERIFY_CHECK(rzr == NULL); + secp256k1_gej_set_ge(r, b); + return; + } + if (b->infinity) { + if (rzr != NULL) { + secp256k1_fe_set_int(rzr, 1); + } + *r = *a; + return; + } + r->infinity = 0; + + secp256k1_fe_sqr(&z12, &a->z); + u1 = a->x; secp256k1_fe_normalize_weak(&u1); + secp256k1_fe_mul(&u2, &b->x, &z12); + s1 = a->y; secp256k1_fe_normalize_weak(&s1); + secp256k1_fe_mul(&s2, &b->y, &z12); secp256k1_fe_mul(&s2, &s2, &a->z); + secp256k1_fe_negate(&h, &u1, 1); secp256k1_fe_add(&h, &u2); + secp256k1_fe_negate(&i, &s1, 1); secp256k1_fe_add(&i, &s2); + if (secp256k1_fe_normalizes_to_zero_var(&h)) { + if (secp256k1_fe_normalizes_to_zero_var(&i)) { + secp256k1_gej_double_var(r, a, rzr); + } else { + if (rzr != NULL) { + secp256k1_fe_set_int(rzr, 0); + } + r->infinity = 1; + } + return; + } + secp256k1_fe_sqr(&i2, &i); + secp256k1_fe_sqr(&h2, &h); + secp256k1_fe_mul(&h3, &h, &h2); + if (rzr != NULL) { + *rzr = h; + } + secp256k1_fe_mul(&r->z, &a->z, &h); + secp256k1_fe_mul(&t, &u1, &h2); + r->x = t; secp256k1_fe_mul_int(&r->x, 2); secp256k1_fe_add(&r->x, &h3); secp256k1_fe_negate(&r->x, &r->x, 3); secp256k1_fe_add(&r->x, &i2); + secp256k1_fe_negate(&r->y, &r->x, 5); secp256k1_fe_add(&r->y, &t); secp256k1_fe_mul(&r->y, &r->y, &i); + secp256k1_fe_mul(&h3, &h3, &s1); secp256k1_fe_negate(&h3, &h3, 1); + secp256k1_fe_add(&r->y, &h3); +} + +static void secp256k1_gej_add_zinv_var(secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_ge *b, const secp256k1_fe *bzinv) { + /* 9 mul, 3 sqr, 4 normalize, 12 mul_int/add/negate */ + secp256k1_fe az, z12, u1, u2, s1, s2, h, i, i2, h2, h3, t; + + if (b->infinity) { + *r = *a; + return; + } + if (a->infinity) { + secp256k1_fe bzinv2, bzinv3; + r->infinity = b->infinity; + secp256k1_fe_sqr(&bzinv2, bzinv); + secp256k1_fe_mul(&bzinv3, &bzinv2, bzinv); + secp256k1_fe_mul(&r->x, &b->x, &bzinv2); + secp256k1_fe_mul(&r->y, &b->y, &bzinv3); + secp256k1_fe_set_int(&r->z, 1); + return; + } + r->infinity = 0; + + /** We need to calculate (rx,ry,rz) = (ax,ay,az) + (bx,by,1/bzinv). Due to + * secp256k1's isomorphism we can multiply the Z coordinates on both sides + * by bzinv, and get: (rx,ry,rz*bzinv) = (ax,ay,az*bzinv) + (bx,by,1). + * This means that (rx,ry,rz) can be calculated as + * (ax,ay,az*bzinv) + (bx,by,1), when not applying the bzinv factor to rz. + * The variable az below holds the modified Z coordinate for a, which is used + * for the computation of rx and ry, but not for rz. + */ + secp256k1_fe_mul(&az, &a->z, bzinv); + + secp256k1_fe_sqr(&z12, &az); + u1 = a->x; secp256k1_fe_normalize_weak(&u1); + secp256k1_fe_mul(&u2, &b->x, &z12); + s1 = a->y; secp256k1_fe_normalize_weak(&s1); + secp256k1_fe_mul(&s2, &b->y, &z12); secp256k1_fe_mul(&s2, &s2, &az); + secp256k1_fe_negate(&h, &u1, 1); secp256k1_fe_add(&h, &u2); + secp256k1_fe_negate(&i, &s1, 1); secp256k1_fe_add(&i, &s2); + if (secp256k1_fe_normalizes_to_zero_var(&h)) { + if (secp256k1_fe_normalizes_to_zero_var(&i)) { + secp256k1_gej_double_var(r, a, NULL); + } else { + r->infinity = 1; + } + return; + } + secp256k1_fe_sqr(&i2, &i); + secp256k1_fe_sqr(&h2, &h); + secp256k1_fe_mul(&h3, &h, &h2); + r->z = a->z; secp256k1_fe_mul(&r->z, &r->z, &h); + secp256k1_fe_mul(&t, &u1, &h2); + r->x = t; secp256k1_fe_mul_int(&r->x, 2); secp256k1_fe_add(&r->x, &h3); secp256k1_fe_negate(&r->x, &r->x, 3); secp256k1_fe_add(&r->x, &i2); + secp256k1_fe_negate(&r->y, &r->x, 5); secp256k1_fe_add(&r->y, &t); secp256k1_fe_mul(&r->y, &r->y, &i); + secp256k1_fe_mul(&h3, &h3, &s1); secp256k1_fe_negate(&h3, &h3, 1); + secp256k1_fe_add(&r->y, &h3); +} + + +static void secp256k1_gej_add_ge(secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_ge *b) { + /* Operations: 7 mul, 5 sqr, 4 normalize, 21 mul_int/add/negate/cmov */ + static const secp256k1_fe fe_1 = SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 1); + secp256k1_fe zz, u1, u2, s1, s2, t, tt, m, n, q, rr; + secp256k1_fe m_alt, rr_alt; + int infinity, degenerate; + VERIFY_CHECK(!b->infinity); + VERIFY_CHECK(a->infinity == 0 || a->infinity == 1); + + /** In: + * Eric Brier and Marc Joye, Weierstrass Elliptic Curves and Side-Channel Attacks. + * In D. Naccache and P. Paillier, Eds., Public Key Cryptography, vol. 2274 of Lecture Notes in Computer Science, pages 335-345. Springer-Verlag, 2002. + * we find as solution for a unified addition/doubling formula: + * lambda = ((x1 + x2)^2 - x1 * x2 + a) / (y1 + y2), with a = 0 for secp256k1's curve equation. + * x3 = lambda^2 - (x1 + x2) + * 2*y3 = lambda * (x1 + x2 - 2 * x3) - (y1 + y2). + * + * Substituting x_i = Xi / Zi^2 and yi = Yi / Zi^3, for i=1,2,3, gives: + * U1 = X1*Z2^2, U2 = X2*Z1^2 + * S1 = Y1*Z2^3, S2 = Y2*Z1^3 + * Z = Z1*Z2 + * T = U1+U2 + * M = S1+S2 + * Q = T*M^2 + * R = T^2-U1*U2 + * X3 = 4*(R^2-Q) + * Y3 = 4*(R*(3*Q-2*R^2)-M^4) + * Z3 = 2*M*Z + * (Note that the paper uses xi = Xi / Zi and yi = Yi / Zi instead.) + * + * This formula has the benefit of being the same for both addition + * of distinct points and doubling. However, it breaks down in the + * case that either point is infinity, or that y1 = -y2. We handle + * these cases in the following ways: + * + * - If b is infinity we simply bail by means of a VERIFY_CHECK. + * + * - If a is infinity, we detect this, and at the end of the + * computation replace the result (which will be meaningless, + * but we compute to be constant-time) with b.x : b.y : 1. + * + * - If a = -b, we have y1 = -y2, which is a degenerate case. + * But here the answer is infinity, so we simply set the + * infinity flag of the result, overriding the computed values + * without even needing to cmov. + * + * - If y1 = -y2 but x1 != x2, which does occur thanks to certain + * properties of our curve (specifically, 1 has nontrivial cube + * roots in our field, and the curve equation has no x coefficient) + * then the answer is not infinity but also not given by the above + * equation. In this case, we cmov in place an alternate expression + * for lambda. Specifically (y1 - y2)/(x1 - x2). Where both these + * expressions for lambda are defined, they are equal, and can be + * obtained from each other by multiplication by (y1 + y2)/(y1 + y2) + * then substitution of x^3 + 7 for y^2 (using the curve equation). + * For all pairs of nonzero points (a, b) at least one is defined, + * so this covers everything. + */ + + secp256k1_fe_sqr(&zz, &a->z); /* z = Z1^2 */ + u1 = a->x; secp256k1_fe_normalize_weak(&u1); /* u1 = U1 = X1*Z2^2 (1) */ + secp256k1_fe_mul(&u2, &b->x, &zz); /* u2 = U2 = X2*Z1^2 (1) */ + s1 = a->y; secp256k1_fe_normalize_weak(&s1); /* s1 = S1 = Y1*Z2^3 (1) */ + secp256k1_fe_mul(&s2, &b->y, &zz); /* s2 = Y2*Z1^2 (1) */ + secp256k1_fe_mul(&s2, &s2, &a->z); /* s2 = S2 = Y2*Z1^3 (1) */ + t = u1; secp256k1_fe_add(&t, &u2); /* t = T = U1+U2 (2) */ + m = s1; secp256k1_fe_add(&m, &s2); /* m = M = S1+S2 (2) */ + secp256k1_fe_sqr(&rr, &t); /* rr = T^2 (1) */ + secp256k1_fe_negate(&m_alt, &u2, 1); /* Malt = -X2*Z1^2 */ + secp256k1_fe_mul(&tt, &u1, &m_alt); /* tt = -U1*U2 (2) */ + secp256k1_fe_add(&rr, &tt); /* rr = R = T^2-U1*U2 (3) */ + /** If lambda = R/M = 0/0 we have a problem (except in the "trivial" + * case that Z = z1z2 = 0, and this is special-cased later on). */ + degenerate = secp256k1_fe_normalizes_to_zero(&m) & + secp256k1_fe_normalizes_to_zero(&rr); + /* This only occurs when y1 == -y2 and x1^3 == x2^3, but x1 != x2. + * This means either x1 == beta*x2 or beta*x1 == x2, where beta is + * a nontrivial cube root of one. In either case, an alternate + * non-indeterminate expression for lambda is (y1 - y2)/(x1 - x2), + * so we set R/M equal to this. */ + rr_alt = s1; + secp256k1_fe_mul_int(&rr_alt, 2); /* rr = Y1*Z2^3 - Y2*Z1^3 (2) */ + secp256k1_fe_add(&m_alt, &u1); /* Malt = X1*Z2^2 - X2*Z1^2 */ + + secp256k1_fe_cmov(&rr_alt, &rr, !degenerate); + secp256k1_fe_cmov(&m_alt, &m, !degenerate); + /* Now Ralt / Malt = lambda and is guaranteed not to be 0/0. + * From here on out Ralt and Malt represent the numerator + * and denominator of lambda; R and M represent the explicit + * expressions x1^2 + x2^2 + x1x2 and y1 + y2. */ + secp256k1_fe_sqr(&n, &m_alt); /* n = Malt^2 (1) */ + secp256k1_fe_mul(&q, &n, &t); /* q = Q = T*Malt^2 (1) */ + /* These two lines use the observation that either M == Malt or M == 0, + * so M^3 * Malt is either Malt^4 (which is computed by squaring), or + * zero (which is "computed" by cmov). So the cost is one squaring + * versus two multiplications. */ + secp256k1_fe_sqr(&n, &n); + secp256k1_fe_cmov(&n, &m, degenerate); /* n = M^3 * Malt (2) */ + secp256k1_fe_sqr(&t, &rr_alt); /* t = Ralt^2 (1) */ + secp256k1_fe_mul(&r->z, &a->z, &m_alt); /* r->z = Malt*Z (1) */ + infinity = secp256k1_fe_normalizes_to_zero(&r->z) * (1 - a->infinity); + secp256k1_fe_mul_int(&r->z, 2); /* r->z = Z3 = 2*Malt*Z (2) */ + secp256k1_fe_negate(&q, &q, 1); /* q = -Q (2) */ + secp256k1_fe_add(&t, &q); /* t = Ralt^2-Q (3) */ + secp256k1_fe_normalize_weak(&t); + r->x = t; /* r->x = Ralt^2-Q (1) */ + secp256k1_fe_mul_int(&t, 2); /* t = 2*x3 (2) */ + secp256k1_fe_add(&t, &q); /* t = 2*x3 - Q: (4) */ + secp256k1_fe_mul(&t, &t, &rr_alt); /* t = Ralt*(2*x3 - Q) (1) */ + secp256k1_fe_add(&t, &n); /* t = Ralt*(2*x3 - Q) + M^3*Malt (3) */ + secp256k1_fe_negate(&r->y, &t, 3); /* r->y = Ralt*(Q - 2x3) - M^3*Malt (4) */ + secp256k1_fe_normalize_weak(&r->y); + secp256k1_fe_mul_int(&r->x, 4); /* r->x = X3 = 4*(Ralt^2-Q) */ + secp256k1_fe_mul_int(&r->y, 4); /* r->y = Y3 = 4*Ralt*(Q - 2x3) - 4*M^3*Malt (4) */ + + /** In case a->infinity == 1, replace r with (b->x, b->y, 1). */ + secp256k1_fe_cmov(&r->x, &b->x, a->infinity); + secp256k1_fe_cmov(&r->y, &b->y, a->infinity); + secp256k1_fe_cmov(&r->z, &fe_1, a->infinity); + r->infinity = infinity; +} + +static void secp256k1_gej_rescale(secp256k1_gej *r, const secp256k1_fe *s) { + /* Operations: 4 mul, 1 sqr */ + secp256k1_fe zz; + VERIFY_CHECK(!secp256k1_fe_is_zero(s)); + secp256k1_fe_sqr(&zz, s); + secp256k1_fe_mul(&r->x, &r->x, &zz); /* r->x *= s^2 */ + secp256k1_fe_mul(&r->y, &r->y, &zz); + secp256k1_fe_mul(&r->y, &r->y, s); /* r->y *= s^3 */ + secp256k1_fe_mul(&r->z, &r->z, s); /* r->z *= s */ +} + +static void secp256k1_ge_to_storage(secp256k1_ge_storage *r, const secp256k1_ge *a) { + secp256k1_fe x, y; + VERIFY_CHECK(!a->infinity); + x = a->x; + secp256k1_fe_normalize(&x); + y = a->y; + secp256k1_fe_normalize(&y); + secp256k1_fe_to_storage(&r->x, &x); + secp256k1_fe_to_storage(&r->y, &y); +} + +static void secp256k1_ge_from_storage(secp256k1_ge *r, const secp256k1_ge_storage *a) { + secp256k1_fe_from_storage(&r->x, &a->x); + secp256k1_fe_from_storage(&r->y, &a->y); + r->infinity = 0; +} + +static SECP256K1_INLINE void secp256k1_ge_storage_cmov(secp256k1_ge_storage *r, const secp256k1_ge_storage *a, int flag) { + secp256k1_fe_storage_cmov(&r->x, &a->x, flag); + secp256k1_fe_storage_cmov(&r->y, &a->y, flag); +} + +#ifdef USE_ENDOMORPHISM +static void secp256k1_ge_mul_lambda(secp256k1_ge *r, const secp256k1_ge *a) { + static const secp256k1_fe beta = SECP256K1_FE_CONST( + 0x7ae96a2bul, 0x657c0710ul, 0x6e64479eul, 0xac3434e9ul, + 0x9cf04975ul, 0x12f58995ul, 0xc1396c28ul, 0x719501eeul + ); + *r = *a; + secp256k1_fe_mul(&r->x, &r->x, &beta); +} +#endif + +static int secp256k1_gej_has_quad_y_var(const secp256k1_gej *a) { + secp256k1_fe yz; + + if (a->infinity) { + return 0; + } + + /* We rely on the fact that the Jacobi symbol of 1 / a->z^3 is the same as + * that of a->z. Thus a->y / a->z^3 is a quadratic residue iff a->y * a->z + is */ + secp256k1_fe_mul(&yz, &a->y, &a->z); + return secp256k1_fe_is_quad_var(&yz); +} + +#endif /* SECP256K1_GROUP_IMPL_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/hash.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/hash.h new file mode 100644 index 000000000..de26e4b89 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/hash.h @@ -0,0 +1,41 @@ +/********************************************************************** + * Copyright (c) 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_HASH_H +#define SECP256K1_HASH_H + +#include +#include + +typedef struct { + uint32_t s[8]; + uint32_t buf[16]; /* In big endian */ + size_t bytes; +} secp256k1_sha256; + +static void secp256k1_sha256_initialize(secp256k1_sha256 *hash); +static void secp256k1_sha256_write(secp256k1_sha256 *hash, const unsigned char *data, size_t size); +static void secp256k1_sha256_finalize(secp256k1_sha256 *hash, unsigned char *out32); + +typedef struct { + secp256k1_sha256 inner, outer; +} secp256k1_hmac_sha256; + +static void secp256k1_hmac_sha256_initialize(secp256k1_hmac_sha256 *hash, const unsigned char *key, size_t size); +static void secp256k1_hmac_sha256_write(secp256k1_hmac_sha256 *hash, const unsigned char *data, size_t size); +static void secp256k1_hmac_sha256_finalize(secp256k1_hmac_sha256 *hash, unsigned char *out32); + +typedef struct { + unsigned char v[32]; + unsigned char k[32]; + int retry; +} secp256k1_rfc6979_hmac_sha256; + +static void secp256k1_rfc6979_hmac_sha256_initialize(secp256k1_rfc6979_hmac_sha256 *rng, const unsigned char *key, size_t keylen); +static void secp256k1_rfc6979_hmac_sha256_generate(secp256k1_rfc6979_hmac_sha256 *rng, unsigned char *out, size_t outlen); +static void secp256k1_rfc6979_hmac_sha256_finalize(secp256k1_rfc6979_hmac_sha256 *rng); + +#endif /* SECP256K1_HASH_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/hash_impl.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/hash_impl.h new file mode 100644 index 000000000..5e015a51f --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/hash_impl.h @@ -0,0 +1,282 @@ +/********************************************************************** + * Copyright (c) 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_HASH_IMPL_H +#define SECP256K1_HASH_IMPL_H + +#include "hash.h" + +#include +#include +#include + +#define Ch(x,y,z) ((z) ^ ((x) & ((y) ^ (z)))) +#define Maj(x,y,z) (((x) & (y)) | ((z) & ((x) | (y)))) +#define Sigma0(x) (((x) >> 2 | (x) << 30) ^ ((x) >> 13 | (x) << 19) ^ ((x) >> 22 | (x) << 10)) +#define Sigma1(x) (((x) >> 6 | (x) << 26) ^ ((x) >> 11 | (x) << 21) ^ ((x) >> 25 | (x) << 7)) +#define sigma0(x) (((x) >> 7 | (x) << 25) ^ ((x) >> 18 | (x) << 14) ^ ((x) >> 3)) +#define sigma1(x) (((x) >> 17 | (x) << 15) ^ ((x) >> 19 | (x) << 13) ^ ((x) >> 10)) + +#define Round(a,b,c,d,e,f,g,h,k,w) do { \ + uint32_t t1 = (h) + Sigma1(e) + Ch((e), (f), (g)) + (k) + (w); \ + uint32_t t2 = Sigma0(a) + Maj((a), (b), (c)); \ + (d) += t1; \ + (h) = t1 + t2; \ +} while(0) + +#ifdef WORDS_BIGENDIAN +#define BE32(x) (x) +#else +#define BE32(p) ((((p) & 0xFF) << 24) | (((p) & 0xFF00) << 8) | (((p) & 0xFF0000) >> 8) | (((p) & 0xFF000000) >> 24)) +#endif + +static void secp256k1_sha256_initialize(secp256k1_sha256 *hash) { + hash->s[0] = 0x6a09e667ul; + hash->s[1] = 0xbb67ae85ul; + hash->s[2] = 0x3c6ef372ul; + hash->s[3] = 0xa54ff53aul; + hash->s[4] = 0x510e527ful; + hash->s[5] = 0x9b05688cul; + hash->s[6] = 0x1f83d9abul; + hash->s[7] = 0x5be0cd19ul; + hash->bytes = 0; +} + +/** Perform one SHA-256 transformation, processing 16 big endian 32-bit words. */ +static void secp256k1_sha256_transform(uint32_t* s, const uint32_t* chunk) { + uint32_t a = s[0], b = s[1], c = s[2], d = s[3], e = s[4], f = s[5], g = s[6], h = s[7]; + uint32_t w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15; + + Round(a, b, c, d, e, f, g, h, 0x428a2f98, w0 = BE32(chunk[0])); + Round(h, a, b, c, d, e, f, g, 0x71374491, w1 = BE32(chunk[1])); + Round(g, h, a, b, c, d, e, f, 0xb5c0fbcf, w2 = BE32(chunk[2])); + Round(f, g, h, a, b, c, d, e, 0xe9b5dba5, w3 = BE32(chunk[3])); + Round(e, f, g, h, a, b, c, d, 0x3956c25b, w4 = BE32(chunk[4])); + Round(d, e, f, g, h, a, b, c, 0x59f111f1, w5 = BE32(chunk[5])); + Round(c, d, e, f, g, h, a, b, 0x923f82a4, w6 = BE32(chunk[6])); + Round(b, c, d, e, f, g, h, a, 0xab1c5ed5, w7 = BE32(chunk[7])); + Round(a, b, c, d, e, f, g, h, 0xd807aa98, w8 = BE32(chunk[8])); + Round(h, a, b, c, d, e, f, g, 0x12835b01, w9 = BE32(chunk[9])); + Round(g, h, a, b, c, d, e, f, 0x243185be, w10 = BE32(chunk[10])); + Round(f, g, h, a, b, c, d, e, 0x550c7dc3, w11 = BE32(chunk[11])); + Round(e, f, g, h, a, b, c, d, 0x72be5d74, w12 = BE32(chunk[12])); + Round(d, e, f, g, h, a, b, c, 0x80deb1fe, w13 = BE32(chunk[13])); + Round(c, d, e, f, g, h, a, b, 0x9bdc06a7, w14 = BE32(chunk[14])); + Round(b, c, d, e, f, g, h, a, 0xc19bf174, w15 = BE32(chunk[15])); + + Round(a, b, c, d, e, f, g, h, 0xe49b69c1, w0 += sigma1(w14) + w9 + sigma0(w1)); + Round(h, a, b, c, d, e, f, g, 0xefbe4786, w1 += sigma1(w15) + w10 + sigma0(w2)); + Round(g, h, a, b, c, d, e, f, 0x0fc19dc6, w2 += sigma1(w0) + w11 + sigma0(w3)); + Round(f, g, h, a, b, c, d, e, 0x240ca1cc, w3 += sigma1(w1) + w12 + sigma0(w4)); + Round(e, f, g, h, a, b, c, d, 0x2de92c6f, w4 += sigma1(w2) + w13 + sigma0(w5)); + Round(d, e, f, g, h, a, b, c, 0x4a7484aa, w5 += sigma1(w3) + w14 + sigma0(w6)); + Round(c, d, e, f, g, h, a, b, 0x5cb0a9dc, w6 += sigma1(w4) + w15 + sigma0(w7)); + Round(b, c, d, e, f, g, h, a, 0x76f988da, w7 += sigma1(w5) + w0 + sigma0(w8)); + Round(a, b, c, d, e, f, g, h, 0x983e5152, w8 += sigma1(w6) + w1 + sigma0(w9)); + Round(h, a, b, c, d, e, f, g, 0xa831c66d, w9 += sigma1(w7) + w2 + sigma0(w10)); + Round(g, h, a, b, c, d, e, f, 0xb00327c8, w10 += sigma1(w8) + w3 + sigma0(w11)); + Round(f, g, h, a, b, c, d, e, 0xbf597fc7, w11 += sigma1(w9) + w4 + sigma0(w12)); + Round(e, f, g, h, a, b, c, d, 0xc6e00bf3, w12 += sigma1(w10) + w5 + sigma0(w13)); + Round(d, e, f, g, h, a, b, c, 0xd5a79147, w13 += sigma1(w11) + w6 + sigma0(w14)); + Round(c, d, e, f, g, h, a, b, 0x06ca6351, w14 += sigma1(w12) + w7 + sigma0(w15)); + Round(b, c, d, e, f, g, h, a, 0x14292967, w15 += sigma1(w13) + w8 + sigma0(w0)); + + Round(a, b, c, d, e, f, g, h, 0x27b70a85, w0 += sigma1(w14) + w9 + sigma0(w1)); + Round(h, a, b, c, d, e, f, g, 0x2e1b2138, w1 += sigma1(w15) + w10 + sigma0(w2)); + Round(g, h, a, b, c, d, e, f, 0x4d2c6dfc, w2 += sigma1(w0) + w11 + sigma0(w3)); + Round(f, g, h, a, b, c, d, e, 0x53380d13, w3 += sigma1(w1) + w12 + sigma0(w4)); + Round(e, f, g, h, a, b, c, d, 0x650a7354, w4 += sigma1(w2) + w13 + sigma0(w5)); + Round(d, e, f, g, h, a, b, c, 0x766a0abb, w5 += sigma1(w3) + w14 + sigma0(w6)); + Round(c, d, e, f, g, h, a, b, 0x81c2c92e, w6 += sigma1(w4) + w15 + sigma0(w7)); + Round(b, c, d, e, f, g, h, a, 0x92722c85, w7 += sigma1(w5) + w0 + sigma0(w8)); + Round(a, b, c, d, e, f, g, h, 0xa2bfe8a1, w8 += sigma1(w6) + w1 + sigma0(w9)); + Round(h, a, b, c, d, e, f, g, 0xa81a664b, w9 += sigma1(w7) + w2 + sigma0(w10)); + Round(g, h, a, b, c, d, e, f, 0xc24b8b70, w10 += sigma1(w8) + w3 + sigma0(w11)); + Round(f, g, h, a, b, c, d, e, 0xc76c51a3, w11 += sigma1(w9) + w4 + sigma0(w12)); + Round(e, f, g, h, a, b, c, d, 0xd192e819, w12 += sigma1(w10) + w5 + sigma0(w13)); + Round(d, e, f, g, h, a, b, c, 0xd6990624, w13 += sigma1(w11) + w6 + sigma0(w14)); + Round(c, d, e, f, g, h, a, b, 0xf40e3585, w14 += sigma1(w12) + w7 + sigma0(w15)); + Round(b, c, d, e, f, g, h, a, 0x106aa070, w15 += sigma1(w13) + w8 + sigma0(w0)); + + Round(a, b, c, d, e, f, g, h, 0x19a4c116, w0 += sigma1(w14) + w9 + sigma0(w1)); + Round(h, a, b, c, d, e, f, g, 0x1e376c08, w1 += sigma1(w15) + w10 + sigma0(w2)); + Round(g, h, a, b, c, d, e, f, 0x2748774c, w2 += sigma1(w0) + w11 + sigma0(w3)); + Round(f, g, h, a, b, c, d, e, 0x34b0bcb5, w3 += sigma1(w1) + w12 + sigma0(w4)); + Round(e, f, g, h, a, b, c, d, 0x391c0cb3, w4 += sigma1(w2) + w13 + sigma0(w5)); + Round(d, e, f, g, h, a, b, c, 0x4ed8aa4a, w5 += sigma1(w3) + w14 + sigma0(w6)); + Round(c, d, e, f, g, h, a, b, 0x5b9cca4f, w6 += sigma1(w4) + w15 + sigma0(w7)); + Round(b, c, d, e, f, g, h, a, 0x682e6ff3, w7 += sigma1(w5) + w0 + sigma0(w8)); + Round(a, b, c, d, e, f, g, h, 0x748f82ee, w8 += sigma1(w6) + w1 + sigma0(w9)); + Round(h, a, b, c, d, e, f, g, 0x78a5636f, w9 += sigma1(w7) + w2 + sigma0(w10)); + Round(g, h, a, b, c, d, e, f, 0x84c87814, w10 += sigma1(w8) + w3 + sigma0(w11)); + Round(f, g, h, a, b, c, d, e, 0x8cc70208, w11 += sigma1(w9) + w4 + sigma0(w12)); + Round(e, f, g, h, a, b, c, d, 0x90befffa, w12 += sigma1(w10) + w5 + sigma0(w13)); + Round(d, e, f, g, h, a, b, c, 0xa4506ceb, w13 += sigma1(w11) + w6 + sigma0(w14)); + Round(c, d, e, f, g, h, a, b, 0xbef9a3f7, w14 + sigma1(w12) + w7 + sigma0(w15)); + Round(b, c, d, e, f, g, h, a, 0xc67178f2, w15 + sigma1(w13) + w8 + sigma0(w0)); + + s[0] += a; + s[1] += b; + s[2] += c; + s[3] += d; + s[4] += e; + s[5] += f; + s[6] += g; + s[7] += h; +} + +static void secp256k1_sha256_write(secp256k1_sha256 *hash, const unsigned char *data, size_t len) { + size_t bufsize = hash->bytes & 0x3F; + hash->bytes += len; + while (bufsize + len >= 64) { + /* Fill the buffer, and process it. */ + size_t chunk_len = 64 - bufsize; + memcpy(((unsigned char*)hash->buf) + bufsize, data, chunk_len); + data += chunk_len; + len -= chunk_len; + secp256k1_sha256_transform(hash->s, hash->buf); + bufsize = 0; + } + if (len) { + /* Fill the buffer with what remains. */ + memcpy(((unsigned char*)hash->buf) + bufsize, data, len); + } +} + +static void secp256k1_sha256_finalize(secp256k1_sha256 *hash, unsigned char *out32) { + static const unsigned char pad[64] = {0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + uint32_t sizedesc[2]; + uint32_t out[8]; + int i = 0; + sizedesc[0] = BE32((uint32_t)hash->bytes >> 29); + sizedesc[1] = BE32((uint32_t)hash->bytes << 3); + secp256k1_sha256_write(hash, pad, 1 + ((119 - (hash->bytes % 64)) % 64)); + secp256k1_sha256_write(hash, (const unsigned char*)sizedesc, 8); + for (i = 0; i < 8; i++) { + out[i] = BE32(hash->s[i]); + hash->s[i] = 0; + } + memcpy(out32, (const unsigned char*)out, 32); +} + +static void secp256k1_hmac_sha256_initialize(secp256k1_hmac_sha256 *hash, const unsigned char *key, size_t keylen) { + size_t n; + unsigned char rkey[64]; + if (keylen <= sizeof(rkey)) { + memcpy(rkey, key, keylen); + memset(rkey + keylen, 0, sizeof(rkey) - keylen); + } else { + secp256k1_sha256 sha256; + secp256k1_sha256_initialize(&sha256); + secp256k1_sha256_write(&sha256, key, keylen); + secp256k1_sha256_finalize(&sha256, rkey); + memset(rkey + 32, 0, 32); + } + + secp256k1_sha256_initialize(&hash->outer); + for (n = 0; n < sizeof(rkey); n++) { + rkey[n] ^= 0x5c; + } + secp256k1_sha256_write(&hash->outer, rkey, sizeof(rkey)); + + secp256k1_sha256_initialize(&hash->inner); + for (n = 0; n < sizeof(rkey); n++) { + rkey[n] ^= 0x5c ^ 0x36; + } + secp256k1_sha256_write(&hash->inner, rkey, sizeof(rkey)); + memset(rkey, 0, sizeof(rkey)); +} + +static void secp256k1_hmac_sha256_write(secp256k1_hmac_sha256 *hash, const unsigned char *data, size_t size) { + secp256k1_sha256_write(&hash->inner, data, size); +} + +static void secp256k1_hmac_sha256_finalize(secp256k1_hmac_sha256 *hash, unsigned char *out32) { + unsigned char temp[32]; + secp256k1_sha256_finalize(&hash->inner, temp); + secp256k1_sha256_write(&hash->outer, temp, 32); + memset(temp, 0, 32); + secp256k1_sha256_finalize(&hash->outer, out32); +} + + +static void secp256k1_rfc6979_hmac_sha256_initialize(secp256k1_rfc6979_hmac_sha256 *rng, const unsigned char *key, size_t keylen) { + secp256k1_hmac_sha256 hmac; + static const unsigned char zero[1] = {0x00}; + static const unsigned char one[1] = {0x01}; + + memset(rng->v, 0x01, 32); /* RFC6979 3.2.b. */ + memset(rng->k, 0x00, 32); /* RFC6979 3.2.c. */ + + /* RFC6979 3.2.d. */ + secp256k1_hmac_sha256_initialize(&hmac, rng->k, 32); + secp256k1_hmac_sha256_write(&hmac, rng->v, 32); + secp256k1_hmac_sha256_write(&hmac, zero, 1); + secp256k1_hmac_sha256_write(&hmac, key, keylen); + secp256k1_hmac_sha256_finalize(&hmac, rng->k); + secp256k1_hmac_sha256_initialize(&hmac, rng->k, 32); + secp256k1_hmac_sha256_write(&hmac, rng->v, 32); + secp256k1_hmac_sha256_finalize(&hmac, rng->v); + + /* RFC6979 3.2.f. */ + secp256k1_hmac_sha256_initialize(&hmac, rng->k, 32); + secp256k1_hmac_sha256_write(&hmac, rng->v, 32); + secp256k1_hmac_sha256_write(&hmac, one, 1); + secp256k1_hmac_sha256_write(&hmac, key, keylen); + secp256k1_hmac_sha256_finalize(&hmac, rng->k); + secp256k1_hmac_sha256_initialize(&hmac, rng->k, 32); + secp256k1_hmac_sha256_write(&hmac, rng->v, 32); + secp256k1_hmac_sha256_finalize(&hmac, rng->v); + rng->retry = 0; +} + +static void secp256k1_rfc6979_hmac_sha256_generate(secp256k1_rfc6979_hmac_sha256 *rng, unsigned char *out, size_t outlen) { + /* RFC6979 3.2.h. */ + static const unsigned char zero[1] = {0x00}; + if (rng->retry) { + secp256k1_hmac_sha256 hmac; + secp256k1_hmac_sha256_initialize(&hmac, rng->k, 32); + secp256k1_hmac_sha256_write(&hmac, rng->v, 32); + secp256k1_hmac_sha256_write(&hmac, zero, 1); + secp256k1_hmac_sha256_finalize(&hmac, rng->k); + secp256k1_hmac_sha256_initialize(&hmac, rng->k, 32); + secp256k1_hmac_sha256_write(&hmac, rng->v, 32); + secp256k1_hmac_sha256_finalize(&hmac, rng->v); + } + + while (outlen > 0) { + secp256k1_hmac_sha256 hmac; + int now = (int)outlen; + secp256k1_hmac_sha256_initialize(&hmac, rng->k, 32); + secp256k1_hmac_sha256_write(&hmac, rng->v, 32); + secp256k1_hmac_sha256_finalize(&hmac, rng->v); + if (now > 32) { + now = 32; + } + memcpy(out, rng->v, now); + out += now; + outlen -= now; + } + + rng->retry = 1; +} + +static void secp256k1_rfc6979_hmac_sha256_finalize(secp256k1_rfc6979_hmac_sha256 *rng) { + memset(rng->k, 0, 32); + memset(rng->v, 0, 32); + rng->retry = 0; +} + +#undef BE32 +#undef Round +#undef sigma1 +#undef sigma0 +#undef Sigma1 +#undef Sigma0 +#undef Maj +#undef Ch + +#endif /* SECP256K1_HASH_IMPL_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/include/secp256k1.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/include/secp256k1.h new file mode 100644 index 000000000..ea2bc0155 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/include/secp256k1.h @@ -0,0 +1,767 @@ +#ifndef SECP256K1_H +#define SECP256K1_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/* These rules specify the order of arguments in API calls: + * + * 1. Context pointers go first, followed by output arguments, combined + * output/input arguments, and finally input-only arguments. + * 2. Array lengths always immediately the follow the argument whose length + * they describe, even if this violates rule 1. + * 3. Within the OUT/OUTIN/IN groups, pointers to data that is typically generated + * later go first. This means: signatures, public nonces, private nonces, + * messages, public keys, secret keys, tweaks. + * 4. Arguments that are not data pointers go last, from more complex to less + * complex: function pointers, algorithm names, messages, void pointers, + * counts, flags, booleans. + * 5. Opaque data pointers follow the function pointer they are to be passed to. + */ + +/** Opaque data structure that holds context information (precomputed tables etc.). + * + * The purpose of context structures is to cache large precomputed data tables + * that are expensive to construct, and also to maintain the randomization data + * for blinding. + * + * Do not create a new context object for each operation, as construction is + * far slower than all other API calls (~100 times slower than an ECDSA + * verification). + * + * A constructed context can safely be used from multiple threads + * simultaneously, but API call that take a non-const pointer to a context + * need exclusive access to it. In particular this is the case for + * secp256k1_context_destroy and secp256k1_context_randomize. + * + * Regarding randomization, either do it once at creation time (in which case + * you do not need any locking for the other calls), or use a read-write lock. + */ +typedef struct secp256k1_context_struct secp256k1_context; + +/** Opaque data structure that holds rewriteable "scratch space" + * + * The purpose of this structure is to replace dynamic memory allocations, + * because we target architectures where this may not be available. It is + * essentially a resizable (within specified parameters) block of bytes, + * which is initially created either by memory allocation or TODO as a pointer + * into some fixed rewritable space. + * + * Unlike the context object, this cannot safely be shared between threads + * without additional synchronization logic. + */ +typedef struct secp256k1_scratch_space_struct secp256k1_scratch_space; + +/** Opaque data structure that holds a parsed and valid public key. + * + * The exact representation of data inside is implementation defined and not + * guaranteed to be portable between different platforms or versions. It is + * however guaranteed to be 64 bytes in size, and can be safely copied/moved. + * If you need to convert to a format suitable for storage, transmission, or + * comparison, use secp256k1_ec_pubkey_serialize and secp256k1_ec_pubkey_parse. + */ +typedef struct { + unsigned char data[64]; +} secp256k1_pubkey; + +/** Opaque data structured that holds a parsed ECDSA signature. + * + * The exact representation of data inside is implementation defined and not + * guaranteed to be portable between different platforms or versions. It is + * however guaranteed to be 64 bytes in size, and can be safely copied/moved. + * If you need to convert to a format suitable for storage, transmission, or + * comparison, use the secp256k1_ecdsa_signature_serialize_* and + * secp256k1_ecdsa_signature_parse_* functions. + */ +typedef struct { + unsigned char data[64]; +} secp256k1_ecdsa_signature; + +/** A pointer to a function to deterministically generate a nonce. + * + * Returns: 1 if a nonce was successfully generated. 0 will cause signing to fail. + * Out: nonce32: pointer to a 32-byte array to be filled by the function. + * In: msg32: the 32-byte message hash being verified (will not be NULL) + * key32: pointer to a 32-byte secret key (will not be NULL) + * algo16: pointer to a 16-byte array describing the signature + * algorithm (will be NULL for ECDSA for compatibility). + * data: Arbitrary data pointer that is passed through. + * attempt: how many iterations we have tried to find a nonce. + * This will almost always be 0, but different attempt values + * are required to result in a different nonce. + * + * Except for test cases, this function should compute some cryptographic hash of + * the message, the algorithm, the key and the attempt. + */ +typedef int (*secp256k1_nonce_function)( + unsigned char *nonce32, + const unsigned char *msg32, + const unsigned char *key32, + const unsigned char *algo16, + void *data, + unsigned int attempt +); + +# if !defined(SECP256K1_GNUC_PREREQ) +# if defined(__GNUC__)&&defined(__GNUC_MINOR__) +# define SECP256K1_GNUC_PREREQ(_maj,_min) \ + ((__GNUC__<<16)+__GNUC_MINOR__>=((_maj)<<16)+(_min)) +# else +# define SECP256K1_GNUC_PREREQ(_maj,_min) 0 +# endif +# endif + +# if (!defined(__STDC_VERSION__) || (__STDC_VERSION__ < 199901L) ) +# if SECP256K1_GNUC_PREREQ(2,7) +# define SECP256K1_INLINE __inline__ +# elif (defined(_MSC_VER)) +# define SECP256K1_INLINE __inline +# else +# define SECP256K1_INLINE +# endif +# else +# define SECP256K1_INLINE inline +# endif + +#ifndef SECP256K1_API +# if defined(_WIN32) +# ifdef SECP256K1_BUILD +# define SECP256K1_API __declspec(dllexport) +# else +# define SECP256K1_API +# endif +# elif defined(__GNUC__) && defined(SECP256K1_BUILD) +# define SECP256K1_API __attribute__ ((visibility ("default"))) +# else +# define SECP256K1_API +# endif +#endif + +/**Warning attributes + * NONNULL is not used if SECP256K1_BUILD is set to avoid the compiler optimizing out + * some paranoid null checks. */ +# if defined(__GNUC__) && SECP256K1_GNUC_PREREQ(3, 4) +# define SECP256K1_WARN_UNUSED_RESULT __attribute__ ((__warn_unused_result__)) +# else +# define SECP256K1_WARN_UNUSED_RESULT +# endif +# if !defined(SECP256K1_BUILD) && defined(__GNUC__) && SECP256K1_GNUC_PREREQ(3, 4) +# define SECP256K1_ARG_NONNULL(_x) __attribute__ ((__nonnull__(_x))) +# else +# define SECP256K1_ARG_NONNULL(_x) +# endif + +/** All flags' lower 8 bits indicate what they're for. Do not use directly. */ +#define SECP256K1_FLAGS_TYPE_MASK ((1 << 8) - 1) +#define SECP256K1_FLAGS_TYPE_CONTEXT (1 << 0) +#define SECP256K1_FLAGS_TYPE_COMPRESSION (1 << 1) +/** The higher bits contain the actual data. Do not use directly. */ +#define SECP256K1_FLAGS_BIT_CONTEXT_VERIFY (1 << 8) +#define SECP256K1_FLAGS_BIT_CONTEXT_SIGN (1 << 9) +#define SECP256K1_FLAGS_BIT_COMPRESSION (1 << 8) + +/** Flags to pass to secp256k1_context_create. */ +#define SECP256K1_CONTEXT_VERIFY (SECP256K1_FLAGS_TYPE_CONTEXT | SECP256K1_FLAGS_BIT_CONTEXT_VERIFY) +#define SECP256K1_CONTEXT_SIGN (SECP256K1_FLAGS_TYPE_CONTEXT | SECP256K1_FLAGS_BIT_CONTEXT_SIGN) +#define SECP256K1_CONTEXT_NONE (SECP256K1_FLAGS_TYPE_CONTEXT) + +/** Flag to pass to secp256k1_ec_pubkey_serialize and secp256k1_ec_privkey_export. */ +#define SECP256K1_EC_COMPRESSED (SECP256K1_FLAGS_TYPE_COMPRESSION | SECP256K1_FLAGS_BIT_COMPRESSION) +#define SECP256K1_EC_UNCOMPRESSED (SECP256K1_FLAGS_TYPE_COMPRESSION) + +/** Prefix byte used to tag various encoded curvepoints for specific purposes */ +#define SECP256K1_TAG_PUBKEY_EVEN 0x02 +#define SECP256K1_TAG_PUBKEY_ODD 0x03 +#define SECP256K1_TAG_PUBKEY_UNCOMPRESSED 0x04 +#define SECP256K1_TAG_PUBKEY_HYBRID_EVEN 0x06 +#define SECP256K1_TAG_PUBKEY_HYBRID_ODD 0x07 + +/** Create a secp256k1 context object. + * + * Returns: a newly created context object. + * In: flags: which parts of the context to initialize. + * + * See also secp256k1_context_randomize. + */ +SECP256K1_API secp256k1_context* secp256k1_context_create( + unsigned int flags +) SECP256K1_WARN_UNUSED_RESULT; + +/** Copies a secp256k1 context object. + * + * Returns: a newly created context object. + * Args: ctx: an existing context to copy (cannot be NULL) + */ +SECP256K1_API secp256k1_context* secp256k1_context_clone( + const secp256k1_context* ctx +) SECP256K1_ARG_NONNULL(1) SECP256K1_WARN_UNUSED_RESULT; + +/** Destroy a secp256k1 context object. + * + * The context pointer may not be used afterwards. + * Args: ctx: an existing context to destroy (cannot be NULL) + */ +SECP256K1_API void secp256k1_context_destroy( + secp256k1_context* ctx +); + +/** Set a callback function to be called when an illegal argument is passed to + * an API call. It will only trigger for violations that are mentioned + * explicitly in the header. + * + * The philosophy is that these shouldn't be dealt with through a + * specific return value, as calling code should not have branches to deal with + * the case that this code itself is broken. + * + * On the other hand, during debug stage, one would want to be informed about + * such mistakes, and the default (crashing) may be inadvisable. + * When this callback is triggered, the API function called is guaranteed not + * to cause a crash, though its return value and output arguments are + * undefined. + * + * Args: ctx: an existing context object (cannot be NULL) + * In: fun: a pointer to a function to call when an illegal argument is + * passed to the API, taking a message and an opaque pointer + * (NULL restores a default handler that calls abort). + * data: the opaque pointer to pass to fun above. + */ +SECP256K1_API void secp256k1_context_set_illegal_callback( + secp256k1_context* ctx, + void (*fun)(const char* message, void* data), + const void* data +) SECP256K1_ARG_NONNULL(1); + +/** Set a callback function to be called when an internal consistency check + * fails. The default is crashing. + * + * This can only trigger in case of a hardware failure, miscompilation, + * memory corruption, serious bug in the library, or other error would can + * otherwise result in undefined behaviour. It will not trigger due to mere + * incorrect usage of the API (see secp256k1_context_set_illegal_callback + * for that). After this callback returns, anything may happen, including + * crashing. + * + * Args: ctx: an existing context object (cannot be NULL) + * In: fun: a pointer to a function to call when an internal error occurs, + * taking a message and an opaque pointer (NULL restores a default + * handler that calls abort). + * data: the opaque pointer to pass to fun above. + */ +SECP256K1_API void secp256k1_context_set_error_callback( + secp256k1_context* ctx, + void (*fun)(const char* message, void* data), + const void* data +) SECP256K1_ARG_NONNULL(1); + +/** Create a secp256k1 scratch space object. + * + * Returns: a newly created scratch space. + * Args: ctx: an existing context object (cannot be NULL) + * In: max_size: maximum amount of memory to allocate + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT secp256k1_scratch_space* secp256k1_scratch_space_create( + const secp256k1_context* ctx, + size_t max_size +) SECP256K1_ARG_NONNULL(1); + +/** Destroy a secp256k1 scratch space. + * + * The pointer may not be used afterwards. + * Args: scratch: space to destroy + */ +SECP256K1_API void secp256k1_scratch_space_destroy( + secp256k1_scratch_space* scratch +); + +/** Parse a variable-length public key into the pubkey object. + * + * Returns: 1 if the public key was fully valid. + * 0 if the public key could not be parsed or is invalid. + * Args: ctx: a secp256k1 context object. + * Out: pubkey: pointer to a pubkey object. If 1 is returned, it is set to a + * parsed version of input. If not, its value is undefined. + * In: input: pointer to a serialized public key + * inputlen: length of the array pointed to by input + * + * This function supports parsing compressed (33 bytes, header byte 0x02 or + * 0x03), uncompressed (65 bytes, header byte 0x04), or hybrid (65 bytes, header + * byte 0x06 or 0x07) format public keys. + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_parse( + const secp256k1_context* ctx, + secp256k1_pubkey* pubkey, + const unsigned char *input, + size_t inputlen +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Serialize a pubkey object into a serialized byte sequence. + * + * Returns: 1 always. + * Args: ctx: a secp256k1 context object. + * Out: output: a pointer to a 65-byte (if compressed==0) or 33-byte (if + * compressed==1) byte array to place the serialized key + * in. + * In/Out: outputlen: a pointer to an integer which is initially set to the + * size of output, and is overwritten with the written + * size. + * In: pubkey: a pointer to a secp256k1_pubkey containing an + * initialized public key. + * flags: SECP256K1_EC_COMPRESSED if serialization should be in + * compressed format, otherwise SECP256K1_EC_UNCOMPRESSED. + */ +SECP256K1_API int secp256k1_ec_pubkey_serialize( + const secp256k1_context* ctx, + unsigned char *output, + size_t *outputlen, + const secp256k1_pubkey* pubkey, + unsigned int flags +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + +/** Parse an ECDSA signature in compact (64 bytes) format. + * + * Returns: 1 when the signature could be parsed, 0 otherwise. + * Args: ctx: a secp256k1 context object + * Out: sig: a pointer to a signature object + * In: input64: a pointer to the 64-byte array to parse + * + * The signature must consist of a 32-byte big endian R value, followed by a + * 32-byte big endian S value. If R or S fall outside of [0..order-1], the + * encoding is invalid. R and S with value 0 are allowed in the encoding. + * + * After the call, sig will always be initialized. If parsing failed or R or + * S are zero, the resulting sig value is guaranteed to fail validation for any + * message and public key. + */ +SECP256K1_API int secp256k1_ecdsa_signature_parse_compact( + const secp256k1_context* ctx, + secp256k1_ecdsa_signature* sig, + const unsigned char *input64 +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Parse a DER ECDSA signature. + * + * Returns: 1 when the signature could be parsed, 0 otherwise. + * Args: ctx: a secp256k1 context object + * Out: sig: a pointer to a signature object + * In: input: a pointer to the signature to be parsed + * inputlen: the length of the array pointed to be input + * + * This function will accept any valid DER encoded signature, even if the + * encoded numbers are out of range. + * + * After the call, sig will always be initialized. If parsing failed or the + * encoded numbers are out of range, signature validation with it is + * guaranteed to fail for every message and public key. + */ +SECP256K1_API int secp256k1_ecdsa_signature_parse_der( + const secp256k1_context* ctx, + secp256k1_ecdsa_signature* sig, + const unsigned char *input, + size_t inputlen +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Serialize an ECDSA signature in DER format. + * + * Returns: 1 if enough space was available to serialize, 0 otherwise + * Args: ctx: a secp256k1 context object + * Out: output: a pointer to an array to store the DER serialization + * In/Out: outputlen: a pointer to a length integer. Initially, this integer + * should be set to the length of output. After the call + * it will be set to the length of the serialization (even + * if 0 was returned). + * In: sig: a pointer to an initialized signature object + */ +SECP256K1_API int secp256k1_ecdsa_signature_serialize_der( + const secp256k1_context* ctx, + unsigned char *output, + size_t *outputlen, + const secp256k1_ecdsa_signature* sig +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + +/** Serialize an ECDSA signature in compact (64 byte) format. + * + * Returns: 1 + * Args: ctx: a secp256k1 context object + * Out: output64: a pointer to a 64-byte array to store the compact serialization + * In: sig: a pointer to an initialized signature object + * + * See secp256k1_ecdsa_signature_parse_compact for details about the encoding. + */ +SECP256K1_API int secp256k1_ecdsa_signature_serialize_compact( + const secp256k1_context* ctx, + unsigned char *output64, + const secp256k1_ecdsa_signature* sig +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Verify an ECDSA signature. + * + * Returns: 1: correct signature + * 0: incorrect or unparseable signature + * Args: ctx: a secp256k1 context object, initialized for verification. + * In: sig: the signature being verified (cannot be NULL) + * msg32: the 32-byte message hash being verified (cannot be NULL) + * pubkey: pointer to an initialized public key to verify with (cannot be NULL) + * + * To avoid accepting malleable signatures, only ECDSA signatures in lower-S + * form are accepted. + * + * If you need to accept ECDSA signatures from sources that do not obey this + * rule, apply secp256k1_ecdsa_signature_normalize to the signature prior to + * validation, but be aware that doing so results in malleable signatures. + * + * For details, see the comments for that function. + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ecdsa_verify( + const secp256k1_context* ctx, + const secp256k1_ecdsa_signature *sig, + const unsigned char *msg32, + const secp256k1_pubkey *pubkey +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + +/** Convert a signature to a normalized lower-S form. + * + * Returns: 1 if sigin was not normalized, 0 if it already was. + * Args: ctx: a secp256k1 context object + * Out: sigout: a pointer to a signature to fill with the normalized form, + * or copy if the input was already normalized. (can be NULL if + * you're only interested in whether the input was already + * normalized). + * In: sigin: a pointer to a signature to check/normalize (cannot be NULL, + * can be identical to sigout) + * + * With ECDSA a third-party can forge a second distinct signature of the same + * message, given a single initial signature, but without knowing the key. This + * is done by negating the S value modulo the order of the curve, 'flipping' + * the sign of the random point R which is not included in the signature. + * + * Forgery of the same message isn't universally problematic, but in systems + * where message malleability or uniqueness of signatures is important this can + * cause issues. This forgery can be blocked by all verifiers forcing signers + * to use a normalized form. + * + * The lower-S form reduces the size of signatures slightly on average when + * variable length encodings (such as DER) are used and is cheap to verify, + * making it a good choice. Security of always using lower-S is assured because + * anyone can trivially modify a signature after the fact to enforce this + * property anyway. + * + * The lower S value is always between 0x1 and + * 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, + * inclusive. + * + * No other forms of ECDSA malleability are known and none seem likely, but + * there is no formal proof that ECDSA, even with this additional restriction, + * is free of other malleability. Commonly used serialization schemes will also + * accept various non-unique encodings, so care should be taken when this + * property is required for an application. + * + * The secp256k1_ecdsa_sign function will by default create signatures in the + * lower-S form, and secp256k1_ecdsa_verify will not accept others. In case + * signatures come from a system that cannot enforce this property, + * secp256k1_ecdsa_signature_normalize must be called before verification. + */ +SECP256K1_API int secp256k1_ecdsa_signature_normalize( + const secp256k1_context* ctx, + secp256k1_ecdsa_signature *sigout, + const secp256k1_ecdsa_signature *sigin +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(3); + +/** An implementation of RFC6979 (using HMAC-SHA256) as nonce generation function. + * If a data pointer is passed, it is assumed to be a pointer to 32 bytes of + * extra entropy. + */ +SECP256K1_API extern const secp256k1_nonce_function secp256k1_nonce_function_rfc6979; + +/** A default safe nonce generation function (currently equal to secp256k1_nonce_function_rfc6979). */ +SECP256K1_API extern const secp256k1_nonce_function secp256k1_nonce_function_default; + +/** Create an ECDSA signature. + * + * Returns: 1: signature created + * 0: the nonce generation function failed, or the private key was invalid. + * Args: ctx: pointer to a context object, initialized for signing (cannot be NULL) + * Out: sig: pointer to an array where the signature will be placed (cannot be NULL) + * In: msg32: the 32-byte message hash being signed (cannot be NULL) + * seckey: pointer to a 32-byte secret key (cannot be NULL) + * noncefp:pointer to a nonce generation function. If NULL, secp256k1_nonce_function_default is used + * ndata: pointer to arbitrary data used by the nonce generation function (can be NULL) + * + * The created signature is always in lower-S form. See + * secp256k1_ecdsa_signature_normalize for more details. + */ +SECP256K1_API int secp256k1_ecdsa_sign( + const secp256k1_context* ctx, + secp256k1_ecdsa_signature *sig, + const unsigned char *msg32, + const unsigned char *seckey, + secp256k1_nonce_function noncefp, + const void *ndata +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + +/** Verify an ECDSA secret key. + * + * Returns: 1: secret key is valid + * 0: secret key is invalid + * Args: ctx: pointer to a context object (cannot be NULL) + * In: seckey: pointer to a 32-byte secret key (cannot be NULL) + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_seckey_verify( + const secp256k1_context* ctx, + const unsigned char *seckey +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2); + +/** Compute the public key for a secret key. + * + * Returns: 1: secret was valid, public key stores + * 0: secret was invalid, try again + * Args: ctx: pointer to a context object, initialized for signing (cannot be NULL) + * Out: pubkey: pointer to the created public key (cannot be NULL) + * In: seckey: pointer to a 32-byte private key (cannot be NULL) + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_create( + const secp256k1_context* ctx, + secp256k1_pubkey *pubkey, + const unsigned char *seckey +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Negates a private key in place. + * + * Returns: 1 always + * Args: ctx: pointer to a context object + * In/Out: seckey: pointer to the 32-byte private key to be negated (cannot be NULL) + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_privkey_negate( + const secp256k1_context* ctx, + unsigned char *seckey +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2); + +/** Negates a public key in place. + * + * Returns: 1 always + * Args: ctx: pointer to a context object + * In/Out: pubkey: pointer to the public key to be negated (cannot be NULL) + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_negate( + const secp256k1_context* ctx, + secp256k1_pubkey *pubkey +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2); + +/** Tweak a private key by adding tweak to it. + * Returns: 0 if the tweak was out of range (chance of around 1 in 2^128 for + * uniformly random 32-byte arrays, or if the resulting private key + * would be invalid (only when the tweak is the complement of the + * private key). 1 otherwise. + * Args: ctx: pointer to a context object (cannot be NULL). + * In/Out: seckey: pointer to a 32-byte private key. + * In: tweak: pointer to a 32-byte tweak. + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_privkey_tweak_add( + const secp256k1_context* ctx, + unsigned char *seckey, + const unsigned char *tweak +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Tweak a public key by adding tweak times the generator to it. + * Returns: 0 if the tweak was out of range (chance of around 1 in 2^128 for + * uniformly random 32-byte arrays, or if the resulting public key + * would be invalid (only when the tweak is the complement of the + * corresponding private key). 1 otherwise. + * Args: ctx: pointer to a context object initialized for validation + * (cannot be NULL). + * In/Out: pubkey: pointer to a public key object. + * In: tweak: pointer to a 32-byte tweak. + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_tweak_add( + const secp256k1_context* ctx, + secp256k1_pubkey *pubkey, + const unsigned char *tweak +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Tweak a private key by multiplying it by a tweak. + * Returns: 0 if the tweak was out of range (chance of around 1 in 2^128 for + * uniformly random 32-byte arrays, or equal to zero. 1 otherwise. + * Args: ctx: pointer to a context object (cannot be NULL). + * In/Out: seckey: pointer to a 32-byte private key. + * In: tweak: pointer to a 32-byte tweak. + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_privkey_tweak_mul( + const secp256k1_context* ctx, + unsigned char *seckey, + const unsigned char *tweak +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Tweak a public key by multiplying it by a tweak value. + * Returns: 0 if the tweak was out of range (chance of around 1 in 2^128 for + * uniformly random 32-byte arrays, or equal to zero. 1 otherwise. + * Args: ctx: pointer to a context object initialized for validation + * (cannot be NULL). + * In/Out: pubkey: pointer to a public key obkect. + * In: tweak: pointer to a 32-byte tweak. + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_tweak_mul( + const secp256k1_context* ctx, + secp256k1_pubkey *pubkey, + const unsigned char *tweak +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Updates the context randomization to protect against side-channel leakage. + * Returns: 1: randomization successfully updated + * 0: error + * Args: ctx: pointer to a context object (cannot be NULL) + * In: seed32: pointer to a 32-byte random seed (NULL resets to initial state) + * + * While secp256k1 code is written to be constant-time no matter what secret + * values are, it's possible that a future compiler may output code which isn't, + * and also that the CPU may not emit the same radio frequencies or draw the same + * amount power for all values. + * + * This function provides a seed which is combined into the blinding value: that + * blinding value is added before each multiplication (and removed afterwards) so + * that it does not affect function results, but shields against attacks which + * rely on any input-dependent behaviour. + * + * You should call this after secp256k1_context_create or + * secp256k1_context_clone, and may call this repeatedly afterwards. + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_context_randomize( + secp256k1_context* ctx, + const unsigned char *seed32 +) SECP256K1_ARG_NONNULL(1); + +/** Add a number of public keys together. + * Returns: 1: the sum of the public keys is valid. + * 0: the sum of the public keys is not valid. + * Args: ctx: pointer to a context object + * Out: out: pointer to a public key object for placing the resulting public key + * (cannot be NULL) + * In: ins: pointer to array of pointers to public keys (cannot be NULL) + * n: the number of public keys to add together (must be at least 1) + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_combine( + const secp256k1_context* ctx, + secp256k1_pubkey *out, + 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. + * + * The exact representation of data inside is implementation defined and not + * guaranteed to be portable between different platforms or versions. It is + * however guaranteed to be 65 bytes in size, and can be safely copied/moved. + * If you need to convert to a format suitable for storage or transmission, use + * the secp256k1_ecdsa_signature_serialize_* and + * secp256k1_ecdsa_signature_parse_* functions. + * + * Furthermore, it is guaranteed that identical signatures (including their + * recoverability) will have identical representation, so they can be + * memcmp'ed. + */ + 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 + * Args: ctx: a secp256k1 context object + * Out: sig: a pointer to a signature object + * In: input64: a pointer to a 64-byte compact signature + * recid: the recovery id (0, 1, 2 or 3) + */ + SECP256K1_API int secp256k1_ecdsa_recoverable_signature_parse_compact( + const secp256k1_context* ctx, + secp256k1_ecdsa_recoverable_signature* sig, + 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 + * Out: sig: a pointer to a normal signature (cannot be NULL). + * In: sigin: a pointer to a recoverable signature (cannot be NULL). + */ + SECP256K1_API int secp256k1_ecdsa_recoverable_signature_convert( + const secp256k1_context* ctx, + 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 + * Args: ctx: a secp256k1 context object + * Out: output64: a pointer to a 64-byte array of the compact signature (cannot be NULL) + * recid: a pointer to an integer to hold the recovery id (can be NULL). + * In: sig: a pointer to an initialized signature object (cannot be NULL) + */ + SECP256K1_API int secp256k1_ecdsa_recoverable_signature_serialize_compact( + const secp256k1_context* ctx, + unsigned char *output64, + 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 + * 0: the nonce generation function failed, or the private key was invalid. + * Args: ctx: pointer to a context object, initialized for signing (cannot be NULL) + * Out: sig: pointer to an array where the signature will be placed (cannot be NULL) + * In: msg32: the 32-byte message hash being signed (cannot be NULL) + * seckey: pointer to a 32-byte secret key (cannot be NULL) + * noncefp:pointer to a nonce generation function. If NULL, secp256k1_nonce_function_default is used + * ndata: pointer to arbitrary data used by the nonce generation function (can be NULL) + */ + SECP256K1_API int secp256k1_ecdsa_sign_recoverable( + const secp256k1_context* ctx, + secp256k1_ecdsa_recoverable_signature *sig, + const unsigned char *msg32, + const unsigned char *seckey, + 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). + * 0: otherwise. + * Args: ctx: pointer to a context object, initialized for verification (cannot be NULL) + * Out: pubkey: pointer to the recovered public key (cannot be NULL) + * In: sig: pointer to initialized signature that supports pubkey recovery (cannot be NULL) + * msg32: the 32-byte message hash assumed to be signed (cannot be NULL) + */ + SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ecdsa_recover( + const secp256k1_context* ctx, + secp256k1_pubkey *pubkey, + const secp256k1_ecdsa_recoverable_signature *sig, + const unsigned char *msg32 + ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + /** Compute an EC Diffie-Hellman secret in constant time + * Returns: 1: exponentiation was successful + * 0: scalar was invalid (zero or overflow) + * Args: ctx: pointer to a context object (cannot be NULL) + * Out: result: a 32-byte array which will be populated by an ECDH + * secret computed from the point and scalar + * In: pubkey: a pointer to a secp256k1_pubkey containing an + * initialized public key + * privkey: a 32-byte scalar with which to multiply the point + */ + SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ecdh( + const secp256k1_context* ctx, + unsigned char *result, + 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 + +#endif /* SECP256K1_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/num.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/num.h new file mode 100644 index 000000000..7aadf7c67 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/num.h @@ -0,0 +1,72 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_NUM_H +#define SECP256K1_NUM_H + +#ifndef USE_NUM_NONE + +#include "secp256k1-config.h" + +#if defined(USE_NUM_GMP) +#include "num_gmp.h" +#else +#error "Please select num implementation" +#endif + +/** Copy a number. */ +static void secp256k1_num_copy(secp256k1_num *r, const secp256k1_num *a); + +/** Convert a number's absolute value to a binary big-endian string. + * There must be enough place. */ +static void secp256k1_num_get_bin(unsigned char *r, unsigned int rlen, const secp256k1_num *a); + +/** Set a number to the value of a binary big-endian string. */ +static void secp256k1_num_set_bin(secp256k1_num *r, const unsigned char *a, unsigned int alen); + +/** Compute a modular inverse. The input must be less than the modulus. */ +static void secp256k1_num_mod_inverse(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *m); + +/** Compute the jacobi symbol (a|b). b must be positive and odd. */ +static int secp256k1_num_jacobi(const secp256k1_num *a, const secp256k1_num *b); + +/** Compare the absolute value of two numbers. */ +static int secp256k1_num_cmp(const secp256k1_num *a, const secp256k1_num *b); + +/** Test whether two number are equal (including sign). */ +static int secp256k1_num_eq(const secp256k1_num *a, const secp256k1_num *b); + +/** Add two (signed) numbers. */ +static void secp256k1_num_add(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b); + +/** Subtract two (signed) numbers. */ +static void secp256k1_num_sub(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b); + +/** Multiply two (signed) numbers. */ +static void secp256k1_num_mul(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b); + +/** Replace a number by its remainder modulo m. M's sign is ignored. The result is a number between 0 and m-1, + even if r was negative. */ +static void secp256k1_num_mod(secp256k1_num *r, const secp256k1_num *m); + +/** Right-shift the passed number by bits bits. */ +static void secp256k1_num_shift(secp256k1_num *r, int bits); + +/** Check whether a number is zero. */ +static int secp256k1_num_is_zero(const secp256k1_num *a); + +/** Check whether a number is one. */ +static int secp256k1_num_is_one(const secp256k1_num *a); + +/** Check whether a number is strictly negative. */ +static int secp256k1_num_is_neg(const secp256k1_num *a); + +/** Change a number's sign. */ +static void secp256k1_num_negate(secp256k1_num *r); + +#endif + +#endif /* SECP256K1_NUM_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/num_gmp.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/num_gmp.h new file mode 100644 index 000000000..3619844bd --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/num_gmp.h @@ -0,0 +1,20 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_NUM_REPR_H +#define SECP256K1_NUM_REPR_H + +#include + +#define NUM_LIMBS ((256+GMP_NUMB_BITS-1)/GMP_NUMB_BITS) + +typedef struct { + mp_limb_t data[2*NUM_LIMBS]; + int neg; + int limbs; +} secp256k1_num; + +#endif /* SECP256K1_NUM_REPR_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/num_gmp_impl.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/num_gmp_impl.h new file mode 100644 index 000000000..0ae2a8ba0 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/num_gmp_impl.h @@ -0,0 +1,288 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_NUM_REPR_IMPL_H +#define SECP256K1_NUM_REPR_IMPL_H + +#include +#include +#include + +#include "util.h" +#include "num.h" + +#ifdef VERIFY +static void secp256k1_num_sanity(const secp256k1_num *a) { + VERIFY_CHECK(a->limbs == 1 || (a->limbs > 1 && a->data[a->limbs-1] != 0)); +} +#else +#define secp256k1_num_sanity(a) do { } while(0) +#endif + +static void secp256k1_num_copy(secp256k1_num *r, const secp256k1_num *a) { + *r = *a; +} + +static void secp256k1_num_get_bin(unsigned char *r, unsigned int rlen, const secp256k1_num *a) { + unsigned char tmp[65]; + int len = 0; + int shift = 0; + if (a->limbs>1 || a->data[0] != 0) { + len = mpn_get_str(tmp, 256, (mp_limb_t*)a->data, a->limbs); + } + while (shift < len && tmp[shift] == 0) shift++; + VERIFY_CHECK(len-shift <= (int)rlen); + memset(r, 0, rlen - len + shift); + if (len > shift) { + memcpy(r + rlen - len + shift, tmp + shift, len - shift); + } + memset(tmp, 0, sizeof(tmp)); +} + +static void secp256k1_num_set_bin(secp256k1_num *r, const unsigned char *a, unsigned int alen) { + int len; + VERIFY_CHECK(alen > 0); + VERIFY_CHECK(alen <= 64); + len = mpn_set_str(r->data, a, alen, 256); + if (len == 0) { + r->data[0] = 0; + len = 1; + } + VERIFY_CHECK(len <= NUM_LIMBS*2); + r->limbs = len; + r->neg = 0; + while (r->limbs > 1 && r->data[r->limbs-1]==0) { + r->limbs--; + } +} + +static void secp256k1_num_add_abs(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b) { + mp_limb_t c = mpn_add(r->data, a->data, a->limbs, b->data, b->limbs); + r->limbs = a->limbs; + if (c != 0) { + VERIFY_CHECK(r->limbs < 2*NUM_LIMBS); + r->data[r->limbs++] = c; + } +} + +static void secp256k1_num_sub_abs(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b) { + mp_limb_t c = mpn_sub(r->data, a->data, a->limbs, b->data, b->limbs); + (void)c; + VERIFY_CHECK(c == 0); + r->limbs = a->limbs; + while (r->limbs > 1 && r->data[r->limbs-1]==0) { + r->limbs--; + } +} + +static void secp256k1_num_mod(secp256k1_num *r, const secp256k1_num *m) { + secp256k1_num_sanity(r); + secp256k1_num_sanity(m); + + if (r->limbs >= m->limbs) { + mp_limb_t t[2*NUM_LIMBS]; + mpn_tdiv_qr(t, r->data, 0, r->data, r->limbs, m->data, m->limbs); + memset(t, 0, sizeof(t)); + r->limbs = m->limbs; + while (r->limbs > 1 && r->data[r->limbs-1]==0) { + r->limbs--; + } + } + + if (r->neg && (r->limbs > 1 || r->data[0] != 0)) { + secp256k1_num_sub_abs(r, m, r); + r->neg = 0; + } +} + +static void secp256k1_num_mod_inverse(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *m) { + int i; + mp_limb_t g[NUM_LIMBS+1]; + mp_limb_t u[NUM_LIMBS+1]; + mp_limb_t v[NUM_LIMBS+1]; + mp_size_t sn; + mp_size_t gn; + secp256k1_num_sanity(a); + secp256k1_num_sanity(m); + + /** mpn_gcdext computes: (G,S) = gcdext(U,V), where + * * G = gcd(U,V) + * * G = U*S + V*T + * * U has equal or more limbs than V, and V has no padding + * If we set U to be (a padded version of) a, and V = m: + * G = a*S + m*T + * G = a*S mod m + * Assuming G=1: + * S = 1/a mod m + */ + VERIFY_CHECK(m->limbs <= NUM_LIMBS); + VERIFY_CHECK(m->data[m->limbs-1] != 0); + for (i = 0; i < m->limbs; i++) { + u[i] = (i < a->limbs) ? a->data[i] : 0; + v[i] = m->data[i]; + } + sn = NUM_LIMBS+1; + gn = mpn_gcdext(g, r->data, &sn, u, m->limbs, v, m->limbs); + (void)gn; + VERIFY_CHECK(gn == 1); + VERIFY_CHECK(g[0] == 1); + r->neg = a->neg ^ m->neg; + if (sn < 0) { + mpn_sub(r->data, m->data, m->limbs, r->data, -sn); + r->limbs = m->limbs; + while (r->limbs > 1 && r->data[r->limbs-1]==0) { + r->limbs--; + } + } else { + r->limbs = sn; + } + memset(g, 0, sizeof(g)); + memset(u, 0, sizeof(u)); + memset(v, 0, sizeof(v)); +} + +static int secp256k1_num_jacobi(const secp256k1_num *a, const secp256k1_num *b) { + int ret; + mpz_t ga, gb; + secp256k1_num_sanity(a); + secp256k1_num_sanity(b); + VERIFY_CHECK(!b->neg && (b->limbs > 0) && (b->data[0] & 1)); + + mpz_inits(ga, gb, NULL); + + mpz_import(gb, b->limbs, -1, sizeof(mp_limb_t), 0, 0, b->data); + mpz_import(ga, a->limbs, -1, sizeof(mp_limb_t), 0, 0, a->data); + if (a->neg) { + mpz_neg(ga, ga); + } + + ret = mpz_jacobi(ga, gb); + + mpz_clears(ga, gb, NULL); + + return ret; +} + +static int secp256k1_num_is_one(const secp256k1_num *a) { + return (a->limbs == 1 && a->data[0] == 1); +} + +static int secp256k1_num_is_zero(const secp256k1_num *a) { + return (a->limbs == 1 && a->data[0] == 0); +} + +static int secp256k1_num_is_neg(const secp256k1_num *a) { + return (a->limbs > 1 || a->data[0] != 0) && a->neg; +} + +static int secp256k1_num_cmp(const secp256k1_num *a, const secp256k1_num *b) { + if (a->limbs > b->limbs) { + return 1; + } + if (a->limbs < b->limbs) { + return -1; + } + return mpn_cmp(a->data, b->data, a->limbs); +} + +static int secp256k1_num_eq(const secp256k1_num *a, const secp256k1_num *b) { + if (a->limbs > b->limbs) { + return 0; + } + if (a->limbs < b->limbs) { + return 0; + } + if ((a->neg && !secp256k1_num_is_zero(a)) != (b->neg && !secp256k1_num_is_zero(b))) { + return 0; + } + return mpn_cmp(a->data, b->data, a->limbs) == 0; +} + +static void secp256k1_num_subadd(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b, int bneg) { + if (!(b->neg ^ bneg ^ a->neg)) { /* a and b have the same sign */ + r->neg = a->neg; + if (a->limbs >= b->limbs) { + secp256k1_num_add_abs(r, a, b); + } else { + secp256k1_num_add_abs(r, b, a); + } + } else { + if (secp256k1_num_cmp(a, b) > 0) { + r->neg = a->neg; + secp256k1_num_sub_abs(r, a, b); + } else { + r->neg = b->neg ^ bneg; + secp256k1_num_sub_abs(r, b, a); + } + } +} + +static void secp256k1_num_add(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b) { + secp256k1_num_sanity(a); + secp256k1_num_sanity(b); + secp256k1_num_subadd(r, a, b, 0); +} + +static void secp256k1_num_sub(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b) { + secp256k1_num_sanity(a); + secp256k1_num_sanity(b); + secp256k1_num_subadd(r, a, b, 1); +} + +static void secp256k1_num_mul(secp256k1_num *r, const secp256k1_num *a, const secp256k1_num *b) { + mp_limb_t tmp[2*NUM_LIMBS+1]; + secp256k1_num_sanity(a); + secp256k1_num_sanity(b); + + VERIFY_CHECK(a->limbs + b->limbs <= 2*NUM_LIMBS+1); + if ((a->limbs==1 && a->data[0]==0) || (b->limbs==1 && b->data[0]==0)) { + r->limbs = 1; + r->neg = 0; + r->data[0] = 0; + return; + } + if (a->limbs >= b->limbs) { + mpn_mul(tmp, a->data, a->limbs, b->data, b->limbs); + } else { + mpn_mul(tmp, b->data, b->limbs, a->data, a->limbs); + } + r->limbs = a->limbs + b->limbs; + if (r->limbs > 1 && tmp[r->limbs - 1]==0) { + r->limbs--; + } + VERIFY_CHECK(r->limbs <= 2*NUM_LIMBS); + mpn_copyi(r->data, tmp, r->limbs); + r->neg = a->neg ^ b->neg; + memset(tmp, 0, sizeof(tmp)); +} + +static void secp256k1_num_shift(secp256k1_num *r, int bits) { + if (bits % GMP_NUMB_BITS) { + /* Shift within limbs. */ + mpn_rshift(r->data, r->data, r->limbs, bits % GMP_NUMB_BITS); + } + if (bits >= GMP_NUMB_BITS) { + int i; + /* Shift full limbs. */ + for (i = 0; i < r->limbs; i++) { + int index = i + (bits / GMP_NUMB_BITS); + if (index < r->limbs && index < 2*NUM_LIMBS) { + r->data[i] = r->data[index]; + } else { + r->data[i] = 0; + } + } + } + while (r->limbs>1 && r->data[r->limbs-1]==0) { + r->limbs--; + } +} + +static void secp256k1_num_negate(secp256k1_num *r) { + r->neg ^= 1; +} + +#endif /* SECP256K1_NUM_REPR_IMPL_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/num_impl.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/num_impl.h new file mode 100644 index 000000000..59dd6f7a1 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/num_impl.h @@ -0,0 +1,22 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_NUM_IMPL_H +#define SECP256K1_NUM_IMPL_H + +#include "secp256k1-config.h" + +#include "num.h" + +#if defined(USE_NUM_GMP) +#include "num_gmp_impl.h" +#elif defined(USE_NUM_NONE) +/* Nothing. */ +#else +#error "Please select num implementation" +#endif + +#endif /* SECP256K1_NUM_IMPL_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/recovery_impl.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/recovery_impl.h new file mode 100755 index 000000000..eb7051937 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/recovery_impl.h @@ -0,0 +1,193 @@ +/********************************************************************** + * Copyright (c) 2013-2015 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_MODULE_RECOVERY_MAIN_H +#define SECP256K1_MODULE_RECOVERY_MAIN_H + +#include "secp256k1.h" + +static void secp256k1_ecdsa_recoverable_signature_load(const secp256k1_context* ctx, secp256k1_scalar* r, secp256k1_scalar* s, int* recid, const secp256k1_ecdsa_recoverable_signature* sig) { + (void)ctx; + if (sizeof(secp256k1_scalar) == 32) { + /* When the secp256k1_scalar type is exactly 32 byte, use its + * representation inside secp256k1_ecdsa_signature, as conversion is very fast. + * Note that secp256k1_ecdsa_signature_save must use the same representation. */ + memcpy(r, &sig->data[0], 32); + memcpy(s, &sig->data[32], 32); + } else { + secp256k1_scalar_set_b32(r, &sig->data[0], NULL); + secp256k1_scalar_set_b32(s, &sig->data[32], NULL); + } + *recid = sig->data[64]; +} + +static void secp256k1_ecdsa_recoverable_signature_save(secp256k1_ecdsa_recoverable_signature* sig, const secp256k1_scalar* r, const secp256k1_scalar* s, int recid) { + if (sizeof(secp256k1_scalar) == 32) { + memcpy(&sig->data[0], r, 32); + memcpy(&sig->data[32], s, 32); + } else { + secp256k1_scalar_get_b32(&sig->data[0], r); + secp256k1_scalar_get_b32(&sig->data[32], s); + } + sig->data[64] = recid; +} + +int secp256k1_ecdsa_recoverable_signature_parse_compact(const secp256k1_context* ctx, secp256k1_ecdsa_recoverable_signature* sig, const unsigned char *input64, int recid) { + secp256k1_scalar r, s; + int ret = 1; + int overflow = 0; + + (void)ctx; + ARG_CHECK(sig != NULL); + ARG_CHECK(input64 != NULL); + ARG_CHECK(recid >= 0 && recid <= 3); + + secp256k1_scalar_set_b32(&r, &input64[0], &overflow); + ret &= !overflow; + secp256k1_scalar_set_b32(&s, &input64[32], &overflow); + ret &= !overflow; + if (ret) { + secp256k1_ecdsa_recoverable_signature_save(sig, &r, &s, recid); + } else { + memset(sig, 0, sizeof(*sig)); + } + return ret; +} + +int secp256k1_ecdsa_recoverable_signature_serialize_compact(const secp256k1_context* ctx, unsigned char *output64, int *recid, const secp256k1_ecdsa_recoverable_signature* sig) { + secp256k1_scalar r, s; + + (void)ctx; + ARG_CHECK(output64 != NULL); + ARG_CHECK(sig != NULL); + ARG_CHECK(recid != NULL); + + secp256k1_ecdsa_recoverable_signature_load(ctx, &r, &s, recid, sig); + secp256k1_scalar_get_b32(&output64[0], &r); + secp256k1_scalar_get_b32(&output64[32], &s); + return 1; +} + +int secp256k1_ecdsa_recoverable_signature_convert(const secp256k1_context* ctx, secp256k1_ecdsa_signature* sig, const secp256k1_ecdsa_recoverable_signature* sigin) { + secp256k1_scalar r, s; + int recid; + + (void)ctx; + ARG_CHECK(sig != NULL); + ARG_CHECK(sigin != NULL); + + secp256k1_ecdsa_recoverable_signature_load(ctx, &r, &s, &recid, sigin); + secp256k1_ecdsa_signature_save(sig, &r, &s); + return 1; +} + +static int secp256k1_ecdsa_sig_recover(const secp256k1_ecmult_context *ctx, const secp256k1_scalar *sigr, const secp256k1_scalar* sigs, secp256k1_ge *pubkey, const secp256k1_scalar *message, int recid) { + unsigned char brx[32]; + secp256k1_fe fx; + secp256k1_ge x; + secp256k1_gej xj; + secp256k1_scalar rn, u1, u2; + secp256k1_gej qj; + int r; + + if (secp256k1_scalar_is_zero(sigr) || secp256k1_scalar_is_zero(sigs)) { + return 0; + } + + secp256k1_scalar_get_b32(brx, sigr); + r = secp256k1_fe_set_b32(&fx, brx); + (void)r; + VERIFY_CHECK(r); /* brx comes from a scalar, so is less than the order; certainly less than p */ + if (recid & 2) { + if (secp256k1_fe_cmp_var(&fx, &secp256k1_ecdsa_const_p_minus_order) >= 0) { + return 0; + } + secp256k1_fe_add(&fx, &secp256k1_ecdsa_const_order_as_fe); + } + if (!secp256k1_ge_set_xo_var(&x, &fx, recid & 1)) { + return 0; + } + secp256k1_gej_set_ge(&xj, &x); + secp256k1_scalar_inverse_var(&rn, sigr); + secp256k1_scalar_mul(&u1, &rn, message); + secp256k1_scalar_negate(&u1, &u1); + secp256k1_scalar_mul(&u2, &rn, sigs); + secp256k1_ecmult(ctx, &qj, &xj, &u2, &u1); + secp256k1_ge_set_gej_var(pubkey, &qj); + return !secp256k1_gej_is_infinity(&qj); +} + +int secp256k1_ecdsa_sign_recoverable(const secp256k1_context* ctx, secp256k1_ecdsa_recoverable_signature *signature, const unsigned char *msg32, const unsigned char *seckey, secp256k1_nonce_function noncefp, const void* noncedata) { + secp256k1_scalar r, s; + secp256k1_scalar sec, non, msg; + int recid = 0; + int ret = 0; + int overflow = 0; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)); + ARG_CHECK(msg32 != NULL); + ARG_CHECK(signature != NULL); + ARG_CHECK(seckey != NULL); + if (noncefp == NULL) { + noncefp = secp256k1_nonce_function_default; + } + + secp256k1_scalar_set_b32(&sec, seckey, &overflow); + /* Fail if the secret key is invalid. */ + if (!overflow && !secp256k1_scalar_is_zero(&sec)) { + unsigned char nonce32[32]; + unsigned int count = 0; + secp256k1_scalar_set_b32(&msg, msg32, NULL); + while (1) { + ret = noncefp(nonce32, msg32, seckey, NULL, (void*)noncedata, count); + if (!ret) { + break; + } + secp256k1_scalar_set_b32(&non, nonce32, &overflow); + if (!secp256k1_scalar_is_zero(&non) && !overflow) { + if (secp256k1_ecdsa_sig_sign(&ctx->ecmult_gen_ctx, &r, &s, &sec, &msg, &non, &recid)) { + break; + } + } + count++; + } + memset(nonce32, 0, 32); + secp256k1_scalar_clear(&msg); + secp256k1_scalar_clear(&non); + secp256k1_scalar_clear(&sec); + } + if (ret) { + secp256k1_ecdsa_recoverable_signature_save(signature, &r, &s, recid); + } else { + memset(signature, 0, sizeof(*signature)); + } + return ret; +} + +int secp256k1_ecdsa_recover(const secp256k1_context* ctx, secp256k1_pubkey *pubkey, const secp256k1_ecdsa_recoverable_signature *signature, const unsigned char *msg32) { + secp256k1_ge q; + secp256k1_scalar r, s; + secp256k1_scalar m; + int recid; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_context_is_built(&ctx->ecmult_ctx)); + ARG_CHECK(msg32 != NULL); + ARG_CHECK(signature != NULL); + ARG_CHECK(pubkey != NULL); + + secp256k1_ecdsa_recoverable_signature_load(ctx, &r, &s, &recid, signature); + VERIFY_CHECK(recid >= 0 && recid < 4); /* should have been caught in parse_compact */ + secp256k1_scalar_set_b32(&m, msg32, NULL); + if (secp256k1_ecdsa_sig_recover(&ctx->ecmult_ctx, &r, &s, &q, &m, recid)) { + secp256k1_pubkey_save(pubkey, &q); + return 1; + } else { + memset(pubkey, 0, sizeof(*pubkey)); + return 0; + } +} + +#endif /* SECP256K1_MODULE_RECOVERY_MAIN_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar.h new file mode 100644 index 000000000..c909a43f6 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar.h @@ -0,0 +1,104 @@ +/********************************************************************** + * Copyright (c) 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_H +#define SECP256K1_SCALAR_H + +#include "num.h" + +#include "secp256k1-config.h" + +#if defined(EXHAUSTIVE_TEST_ORDER) +#include "scalar_low.h" +#elif defined(USE_SCALAR_4X64) +#include "scalar_4x64.h" +#elif defined(USE_SCALAR_8X32) +#include "scalar_8x32.h" +#else +#error "Please select scalar implementation" +#endif + +/** Clear a scalar to prevent the leak of sensitive data. */ +static void secp256k1_scalar_clear(secp256k1_scalar *r); + +/** Access bits from a scalar. All requested bits must belong to the same 32-bit limb. */ +static unsigned int secp256k1_scalar_get_bits(const secp256k1_scalar *a, unsigned int offset, unsigned int count); + +/** Access bits from a scalar. Not constant time. */ +static unsigned int secp256k1_scalar_get_bits_var(const secp256k1_scalar *a, unsigned int offset, unsigned int count); + +/** Set a scalar from a big endian byte array. */ +static void secp256k1_scalar_set_b32(secp256k1_scalar *r, const unsigned char *bin, int *overflow); + +/** Set a scalar to an unsigned integer. */ +static void secp256k1_scalar_set_int(secp256k1_scalar *r, unsigned int v); + +/** Convert a scalar to a byte array. */ +static void secp256k1_scalar_get_b32(unsigned char *bin, const secp256k1_scalar* a); + +/** Add two scalars together (modulo the group order). Returns whether it overflowed. */ +static int secp256k1_scalar_add(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b); + +/** Conditionally add a power of two to a scalar. The result is not allowed to overflow. */ +static void secp256k1_scalar_cadd_bit(secp256k1_scalar *r, unsigned int bit, int flag); + +/** Multiply two scalars (modulo the group order). */ +static void secp256k1_scalar_mul(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b); + +/** Shift a scalar right by some amount strictly between 0 and 16, returning + * the low bits that were shifted off */ +static int secp256k1_scalar_shr_int(secp256k1_scalar *r, int n); + +/** Compute the square of a scalar (modulo the group order). */ +static void secp256k1_scalar_sqr(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Compute the inverse of a scalar (modulo the group order). */ +static void secp256k1_scalar_inverse(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Compute the inverse of a scalar (modulo the group order), without constant-time guarantee. */ +static void secp256k1_scalar_inverse_var(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Compute the complement of a scalar (modulo the group order). */ +static void secp256k1_scalar_negate(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Check whether a scalar equals zero. */ +static int secp256k1_scalar_is_zero(const secp256k1_scalar *a); + +/** Check whether a scalar equals one. */ +static int secp256k1_scalar_is_one(const secp256k1_scalar *a); + +/** Check whether a scalar, considered as an nonnegative integer, is even. */ +static int secp256k1_scalar_is_even(const secp256k1_scalar *a); + +/** Check whether a scalar is higher than the group order divided by 2. */ +static int secp256k1_scalar_is_high(const secp256k1_scalar *a); + +/** Conditionally negate a number, in constant time. + * Returns -1 if the number was negated, 1 otherwise */ +static int secp256k1_scalar_cond_negate(secp256k1_scalar *a, int flag); + +#ifndef USE_NUM_NONE +/** Convert a scalar to a number. */ +static void secp256k1_scalar_get_num(secp256k1_num *r, const secp256k1_scalar *a); + +/** Get the order of the group as a number. */ +static void secp256k1_scalar_order_get_num(secp256k1_num *r); +#endif + +/** Compare two scalars. */ +static int secp256k1_scalar_eq(const secp256k1_scalar *a, const secp256k1_scalar *b); + +#ifdef USE_ENDOMORPHISM +/** Find r1 and r2 such that r1+r2*2^128 = a. */ +static void secp256k1_scalar_split_128(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a); +/** Find r1 and r2 such that r1+r2*lambda = a, and r1 and r2 are maximum 128 bits long (see secp256k1_gej_mul_lambda). */ +static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a); +#endif + +/** Multiply a and b (without taking the modulus!), divide by 2**shift, and round to the nearest integer. Shift must be at least 256. */ +static void secp256k1_scalar_mul_shift_var(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b, unsigned int shift); + +#endif /* SECP256K1_SCALAR_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_4x64.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_4x64.h new file mode 100644 index 000000000..19c7495d1 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_4x64.h @@ -0,0 +1,19 @@ +/********************************************************************** + * Copyright (c) 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_REPR_H +#define SECP256K1_SCALAR_REPR_H + +#include + +/** A scalar modulo the group order of the secp256k1 curve. */ +typedef struct { + uint64_t d[4]; +} secp256k1_scalar; + +#define SECP256K1_SCALAR_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{((uint64_t)(d1)) << 32 | (d0), ((uint64_t)(d3)) << 32 | (d2), ((uint64_t)(d5)) << 32 | (d4), ((uint64_t)(d7)) << 32 | (d6)}} + +#endif /* SECP256K1_SCALAR_REPR_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_4x64_impl.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_4x64_impl.h new file mode 100644 index 000000000..685bc99e6 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_4x64_impl.h @@ -0,0 +1,949 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_REPR_IMPL_H +#define SECP256K1_SCALAR_REPR_IMPL_H + +/* Limbs of the secp256k1 order. */ +#define SECP256K1_N_0 ((uint64_t)0xBFD25E8CD0364141ULL) +#define SECP256K1_N_1 ((uint64_t)0xBAAEDCE6AF48A03BULL) +#define SECP256K1_N_2 ((uint64_t)0xFFFFFFFFFFFFFFFEULL) +#define SECP256K1_N_3 ((uint64_t)0xFFFFFFFFFFFFFFFFULL) + +/* Limbs of 2^256 minus the secp256k1 order. */ +#define SECP256K1_N_C_0 (~SECP256K1_N_0 + 1) +#define SECP256K1_N_C_1 (~SECP256K1_N_1) +#define SECP256K1_N_C_2 (1) + +/* Limbs of half the secp256k1 order. */ +#define SECP256K1_N_H_0 ((uint64_t)0xDFE92F46681B20A0ULL) +#define SECP256K1_N_H_1 ((uint64_t)0x5D576E7357A4501DULL) +#define SECP256K1_N_H_2 ((uint64_t)0xFFFFFFFFFFFFFFFFULL) +#define SECP256K1_N_H_3 ((uint64_t)0x7FFFFFFFFFFFFFFFULL) + +SECP256K1_INLINE static void secp256k1_scalar_clear(secp256k1_scalar *r) { + r->d[0] = 0; + r->d[1] = 0; + r->d[2] = 0; + r->d[3] = 0; +} + +SECP256K1_INLINE static void secp256k1_scalar_set_int(secp256k1_scalar *r, unsigned int v) { + r->d[0] = v; + r->d[1] = 0; + r->d[2] = 0; + r->d[3] = 0; +} + +SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits(const secp256k1_scalar *a, unsigned int offset, unsigned int count) { + VERIFY_CHECK((offset + count - 1) >> 6 == offset >> 6); + return (uint)(a->d[offset >> 6] >> (offset & 0x3F)) & ((((uint64_t)1) << count) - 1); +} + +SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits_var(const secp256k1_scalar *a, unsigned int offset, unsigned int count) { + VERIFY_CHECK(count < 32); + VERIFY_CHECK(offset + count <= 256); + if ((offset + count - 1) >> 6 == offset >> 6) { + return secp256k1_scalar_get_bits(a, offset, count); + } else { + VERIFY_CHECK((offset >> 6) + 1 < 4); + return (uint)((a->d[offset >> 6] >> (offset & 0x3F)) | (a->d[(offset >> 6) + 1] << (64 - (offset & 0x3F)))) & ((((uint64_t)1) << count) - 1); + } +} + +SECP256K1_INLINE static int secp256k1_scalar_check_overflow(const secp256k1_scalar *a) { + int yes = 0; + int no = 0; + no |= (a->d[3] < SECP256K1_N_3); /* No need for a > check. */ + no |= (a->d[2] < SECP256K1_N_2); + yes |= (a->d[2] > SECP256K1_N_2) & ~no; + no |= (a->d[1] < SECP256K1_N_1); + yes |= (a->d[1] > SECP256K1_N_1) & ~no; + yes |= (a->d[0] >= SECP256K1_N_0) & ~no; + return yes; +} + +SECP256K1_INLINE static int secp256k1_scalar_reduce(secp256k1_scalar *r, unsigned int overflow) { + uint128_t t; + VERIFY_CHECK(overflow <= 1); + t = (uint128_t)r->d[0] + overflow * SECP256K1_N_C_0; + r->d[0] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)r->d[1] + overflow * SECP256K1_N_C_1; + r->d[1] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)r->d[2] + overflow * SECP256K1_N_C_2; + r->d[2] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint64_t)r->d[3]; + r->d[3] = t & 0xFFFFFFFFFFFFFFFFULL; + return overflow; +} + +static int secp256k1_scalar_add(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b) { + int overflow; + uint128_t t = (uint128_t)a->d[0] + b->d[0]; + r->d[0] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)a->d[1] + b->d[1]; + r->d[1] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)a->d[2] + b->d[2]; + r->d[2] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)a->d[3] + b->d[3]; + r->d[3] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + overflow = t + secp256k1_scalar_check_overflow(r); + VERIFY_CHECK(overflow == 0 || overflow == 1); + secp256k1_scalar_reduce(r, overflow); + return overflow; +} + +static void secp256k1_scalar_cadd_bit(secp256k1_scalar *r, unsigned int bit, int flag) { + uint128_t t; + VERIFY_CHECK(bit < 256); + bit += ((uint32_t) flag - 1) & 0x100; /* forcing (bit >> 6) > 3 makes this a noop */ + t = (uint128_t)r->d[0] + (((uint64_t)((bit >> 6) == 0)) << (bit & 0x3F)); + r->d[0] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)r->d[1] + (((uint64_t)((bit >> 6) == 1)) << (bit & 0x3F)); + r->d[1] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)r->d[2] + (((uint64_t)((bit >> 6) == 2)) << (bit & 0x3F)); + r->d[2] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)r->d[3] + (((uint64_t)((bit >> 6) == 3)) << (bit & 0x3F)); + r->d[3] = t & 0xFFFFFFFFFFFFFFFFULL; +#ifdef VERIFY + VERIFY_CHECK((t >> 64) == 0); + VERIFY_CHECK(secp256k1_scalar_check_overflow(r) == 0); +#endif +} + +static void secp256k1_scalar_set_b32(secp256k1_scalar *r, const unsigned char *b32, int *overflow) { + int over; + r->d[0] = (uint64_t)b32[31] | (uint64_t)b32[30] << 8 | (uint64_t)b32[29] << 16 | (uint64_t)b32[28] << 24 | (uint64_t)b32[27] << 32 | (uint64_t)b32[26] << 40 | (uint64_t)b32[25] << 48 | (uint64_t)b32[24] << 56; + r->d[1] = (uint64_t)b32[23] | (uint64_t)b32[22] << 8 | (uint64_t)b32[21] << 16 | (uint64_t)b32[20] << 24 | (uint64_t)b32[19] << 32 | (uint64_t)b32[18] << 40 | (uint64_t)b32[17] << 48 | (uint64_t)b32[16] << 56; + r->d[2] = (uint64_t)b32[15] | (uint64_t)b32[14] << 8 | (uint64_t)b32[13] << 16 | (uint64_t)b32[12] << 24 | (uint64_t)b32[11] << 32 | (uint64_t)b32[10] << 40 | (uint64_t)b32[9] << 48 | (uint64_t)b32[8] << 56; + r->d[3] = (uint64_t)b32[7] | (uint64_t)b32[6] << 8 | (uint64_t)b32[5] << 16 | (uint64_t)b32[4] << 24 | (uint64_t)b32[3] << 32 | (uint64_t)b32[2] << 40 | (uint64_t)b32[1] << 48 | (uint64_t)b32[0] << 56; + over = secp256k1_scalar_reduce(r, secp256k1_scalar_check_overflow(r)); + if (overflow) { + *overflow = over; + } +} + +static void secp256k1_scalar_get_b32(unsigned char *bin, const secp256k1_scalar* a) { + bin[0] = a->d[3] >> 56; bin[1] = a->d[3] >> 48; bin[2] = a->d[3] >> 40; bin[3] = a->d[3] >> 32; bin[4] = a->d[3] >> 24; bin[5] = a->d[3] >> 16; bin[6] = a->d[3] >> 8; bin[7] = a->d[3]; + bin[8] = a->d[2] >> 56; bin[9] = a->d[2] >> 48; bin[10] = a->d[2] >> 40; bin[11] = a->d[2] >> 32; bin[12] = a->d[2] >> 24; bin[13] = a->d[2] >> 16; bin[14] = a->d[2] >> 8; bin[15] = a->d[2]; + bin[16] = a->d[1] >> 56; bin[17] = a->d[1] >> 48; bin[18] = a->d[1] >> 40; bin[19] = a->d[1] >> 32; bin[20] = a->d[1] >> 24; bin[21] = a->d[1] >> 16; bin[22] = a->d[1] >> 8; bin[23] = a->d[1]; + bin[24] = a->d[0] >> 56; bin[25] = a->d[0] >> 48; bin[26] = a->d[0] >> 40; bin[27] = a->d[0] >> 32; bin[28] = a->d[0] >> 24; bin[29] = a->d[0] >> 16; bin[30] = a->d[0] >> 8; bin[31] = a->d[0]; +} + +SECP256K1_INLINE static int secp256k1_scalar_is_zero(const secp256k1_scalar *a) { + return (a->d[0] | a->d[1] | a->d[2] | a->d[3]) == 0; +} + +static void secp256k1_scalar_negate(secp256k1_scalar *r, const secp256k1_scalar *a) { + uint64_t nonzero = 0xFFFFFFFFFFFFFFFFULL * (secp256k1_scalar_is_zero(a) == 0); + uint128_t t = (uint128_t)(~a->d[0]) + SECP256K1_N_0 + 1; + r->d[0] = t & nonzero; t >>= 64; + t += (uint128_t)(~a->d[1]) + SECP256K1_N_1; + r->d[1] = t & nonzero; t >>= 64; + t += (uint128_t)(~a->d[2]) + SECP256K1_N_2; + r->d[2] = t & nonzero; t >>= 64; + t += (uint128_t)(~a->d[3]) + SECP256K1_N_3; + r->d[3] = t & nonzero; +} + +SECP256K1_INLINE static int secp256k1_scalar_is_one(const secp256k1_scalar *a) { + return ((a->d[0] ^ 1) | a->d[1] | a->d[2] | a->d[3]) == 0; +} + +static int secp256k1_scalar_is_high(const secp256k1_scalar *a) { + int yes = 0; + int no = 0; + no |= (a->d[3] < SECP256K1_N_H_3); + yes |= (a->d[3] > SECP256K1_N_H_3) & ~no; + no |= (a->d[2] < SECP256K1_N_H_2) & ~yes; /* No need for a > check. */ + no |= (a->d[1] < SECP256K1_N_H_1) & ~yes; + yes |= (a->d[1] > SECP256K1_N_H_1) & ~no; + yes |= (a->d[0] > SECP256K1_N_H_0) & ~no; + return yes; +} + +static int secp256k1_scalar_cond_negate(secp256k1_scalar *r, int flag) { + /* If we are flag = 0, mask = 00...00 and this is a no-op; + * if we are flag = 1, mask = 11...11 and this is identical to secp256k1_scalar_negate */ + uint64_t mask = !flag - 1; + uint64_t nonzero = (secp256k1_scalar_is_zero(r) != 0) - 1; + uint128_t t = (uint128_t)(r->d[0] ^ mask) + ((SECP256K1_N_0 + 1) & mask); + r->d[0] = t & nonzero; t >>= 64; + t += (uint128_t)(r->d[1] ^ mask) + (SECP256K1_N_1 & mask); + r->d[1] = t & nonzero; t >>= 64; + t += (uint128_t)(r->d[2] ^ mask) + (SECP256K1_N_2 & mask); + r->d[2] = t & nonzero; t >>= 64; + t += (uint128_t)(r->d[3] ^ mask) + (SECP256K1_N_3 & mask); + r->d[3] = t & nonzero; + return 2 * (mask == 0) - 1; +} + +/* Inspired by the macros in OpenSSL's crypto/bn/asm/x86_64-gcc.c. */ + +/** Add a*b to the number defined by (c0,c1,c2). c2 must never overflow. */ +#define muladd(a,b) { \ + uint64_t tl, th; \ + { \ + uint128_t t = (uint128_t)a * b; \ + th = t >> 64; /* at most 0xFFFFFFFFFFFFFFFE */ \ + tl = t; \ + } \ + c0 += tl; /* overflow is handled on the next line */ \ + th += (c0 < tl) ? 1 : 0; /* at most 0xFFFFFFFFFFFFFFFF */ \ + c1 += th; /* overflow is handled on the next line */ \ + c2 += (c1 < th) ? 1 : 0; /* never overflows by contract (verified in the next line) */ \ + VERIFY_CHECK((c1 >= th) || (c2 != 0)); \ +} + +/** Add a*b to the number defined by (c0,c1). c1 must never overflow. */ +#define muladd_fast(a,b) { \ + uint64_t tl, th; \ + { \ + uint128_t t = (uint128_t)a * b; \ + th = t >> 64; /* at most 0xFFFFFFFFFFFFFFFE */ \ + tl = t; \ + } \ + c0 += tl; /* overflow is handled on the next line */ \ + th += (c0 < tl) ? 1 : 0; /* at most 0xFFFFFFFFFFFFFFFF */ \ + c1 += th; /* never overflows by contract (verified in the next line) */ \ + VERIFY_CHECK(c1 >= th); \ +} + +/** Add 2*a*b to the number defined by (c0,c1,c2). c2 must never overflow. */ +#define muladd2(a,b) { \ + uint64_t tl, th, th2, tl2; \ + { \ + uint128_t t = (uint128_t)a * b; \ + th = t >> 64; /* at most 0xFFFFFFFFFFFFFFFE */ \ + tl = t; \ + } \ + th2 = th + th; /* at most 0xFFFFFFFFFFFFFFFE (in case th was 0x7FFFFFFFFFFFFFFF) */ \ + c2 += (th2 < th) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ + VERIFY_CHECK((th2 >= th) || (c2 != 0)); \ + tl2 = tl + tl; /* at most 0xFFFFFFFFFFFFFFFE (in case the lowest 63 bits of tl were 0x7FFFFFFFFFFFFFFF) */ \ + th2 += (tl2 < tl) ? 1 : 0; /* at most 0xFFFFFFFFFFFFFFFF */ \ + c0 += tl2; /* overflow is handled on the next line */ \ + th2 += (c0 < tl2) ? 1 : 0; /* second overflow is handled on the next line */ \ + c2 += (c0 < tl2) & (th2 == 0); /* never overflows by contract (verified the next line) */ \ + VERIFY_CHECK((c0 >= tl2) || (th2 != 0) || (c2 != 0)); \ + c1 += th2; /* overflow is handled on the next line */ \ + c2 += (c1 < th2) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ + VERIFY_CHECK((c1 >= th2) || (c2 != 0)); \ +} + +/** Add a to the number defined by (c0,c1,c2). c2 must never overflow. */ +#define sumadd(a) { \ + unsigned int over; \ + c0 += (a); /* overflow is handled on the next line */ \ + over = (c0 < (a)) ? 1 : 0; \ + c1 += over; /* overflow is handled on the next line */ \ + c2 += (c1 < over) ? 1 : 0; /* never overflows by contract */ \ +} + +/** Add a to the number defined by (c0,c1). c1 must never overflow, c2 must be zero. */ +#define sumadd_fast(a) { \ + c0 += (a); /* overflow is handled on the next line */ \ + c1 += (c0 < (a)) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ + VERIFY_CHECK((c1 != 0) | (c0 >= (a))); \ + VERIFY_CHECK(c2 == 0); \ +} + +/** Extract the lowest 64 bits of (c0,c1,c2) into n, and left shift the number 64 bits. */ +#define extract(n) { \ + (n) = c0; \ + c0 = c1; \ + c1 = c2; \ + c2 = 0; \ +} + +/** Extract the lowest 64 bits of (c0,c1,c2) into n, and left shift the number 64 bits. c2 is required to be zero. */ +#define extract_fast(n) { \ + (n) = c0; \ + c0 = c1; \ + c1 = 0; \ + VERIFY_CHECK(c2 == 0); \ +} + +static void secp256k1_scalar_reduce_512(secp256k1_scalar *r, const uint64_t *l) { +#ifdef USE_ASM_X86_64 + /* Reduce 512 bits into 385. */ + uint64_t m0, m1, m2, m3, m4, m5, m6; + uint64_t p0, p1, p2, p3, p4; + uint64_t c; + + __asm__ __volatile__( + /* Preload. */ + "movq 32(%%rsi), %%r11\n" + "movq 40(%%rsi), %%r12\n" + "movq 48(%%rsi), %%r13\n" + "movq 56(%%rsi), %%r14\n" + /* Initialize r8,r9,r10 */ + "movq 0(%%rsi), %%r8\n" + "xorq %%r9, %%r9\n" + "xorq %%r10, %%r10\n" + /* (r8,r9) += n0 * c0 */ + "movq %8, %%rax\n" + "mulq %%r11\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + /* extract m0 */ + "movq %%r8, %q0\n" + "xorq %%r8, %%r8\n" + /* (r9,r10) += l1 */ + "addq 8(%%rsi), %%r9\n" + "adcq $0, %%r10\n" + /* (r9,r10,r8) += n1 * c0 */ + "movq %8, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* (r9,r10,r8) += n0 * c1 */ + "movq %9, %%rax\n" + "mulq %%r11\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* extract m1 */ + "movq %%r9, %q1\n" + "xorq %%r9, %%r9\n" + /* (r10,r8,r9) += l2 */ + "addq 16(%%rsi), %%r10\n" + "adcq $0, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += n2 * c0 */ + "movq %8, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += n1 * c1 */ + "movq %9, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += n0 */ + "addq %%r11, %%r10\n" + "adcq $0, %%r8\n" + "adcq $0, %%r9\n" + /* extract m2 */ + "movq %%r10, %q2\n" + "xorq %%r10, %%r10\n" + /* (r8,r9,r10) += l3 */ + "addq 24(%%rsi), %%r8\n" + "adcq $0, %%r9\n" + "adcq $0, %%r10\n" + /* (r8,r9,r10) += n3 * c0 */ + "movq %8, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* (r8,r9,r10) += n2 * c1 */ + "movq %9, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* (r8,r9,r10) += n1 */ + "addq %%r12, %%r8\n" + "adcq $0, %%r9\n" + "adcq $0, %%r10\n" + /* extract m3 */ + "movq %%r8, %q3\n" + "xorq %%r8, %%r8\n" + /* (r9,r10,r8) += n3 * c1 */ + "movq %9, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* (r9,r10,r8) += n2 */ + "addq %%r13, %%r9\n" + "adcq $0, %%r10\n" + "adcq $0, %%r8\n" + /* extract m4 */ + "movq %%r9, %q4\n" + /* (r10,r8) += n3 */ + "addq %%r14, %%r10\n" + "adcq $0, %%r8\n" + /* extract m5 */ + "movq %%r10, %q5\n" + /* extract m6 */ + "movq %%r8, %q6\n" + : "=g"(m0), "=g"(m1), "=g"(m2), "=g"(m3), "=g"(m4), "=g"(m5), "=g"(m6) + : "S"(l), "n"(SECP256K1_N_C_0), "n"(SECP256K1_N_C_1) + : "rax", "rdx", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "cc"); + + /* Reduce 385 bits into 258. */ + __asm__ __volatile__( + /* Preload */ + "movq %q9, %%r11\n" + "movq %q10, %%r12\n" + "movq %q11, %%r13\n" + /* Initialize (r8,r9,r10) */ + "movq %q5, %%r8\n" + "xorq %%r9, %%r9\n" + "xorq %%r10, %%r10\n" + /* (r8,r9) += m4 * c0 */ + "movq %12, %%rax\n" + "mulq %%r11\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + /* extract p0 */ + "movq %%r8, %q0\n" + "xorq %%r8, %%r8\n" + /* (r9,r10) += m1 */ + "addq %q6, %%r9\n" + "adcq $0, %%r10\n" + /* (r9,r10,r8) += m5 * c0 */ + "movq %12, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* (r9,r10,r8) += m4 * c1 */ + "movq %13, %%rax\n" + "mulq %%r11\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* extract p1 */ + "movq %%r9, %q1\n" + "xorq %%r9, %%r9\n" + /* (r10,r8,r9) += m2 */ + "addq %q7, %%r10\n" + "adcq $0, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += m6 * c0 */ + "movq %12, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += m5 * c1 */ + "movq %13, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += m4 */ + "addq %%r11, %%r10\n" + "adcq $0, %%r8\n" + "adcq $0, %%r9\n" + /* extract p2 */ + "movq %%r10, %q2\n" + /* (r8,r9) += m3 */ + "addq %q8, %%r8\n" + "adcq $0, %%r9\n" + /* (r8,r9) += m6 * c1 */ + "movq %13, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + /* (r8,r9) += m5 */ + "addq %%r12, %%r8\n" + "adcq $0, %%r9\n" + /* extract p3 */ + "movq %%r8, %q3\n" + /* (r9) += m6 */ + "addq %%r13, %%r9\n" + /* extract p4 */ + "movq %%r9, %q4\n" + : "=&g"(p0), "=&g"(p1), "=&g"(p2), "=g"(p3), "=g"(p4) + : "g"(m0), "g"(m1), "g"(m2), "g"(m3), "g"(m4), "g"(m5), "g"(m6), "n"(SECP256K1_N_C_0), "n"(SECP256K1_N_C_1) + : "rax", "rdx", "r8", "r9", "r10", "r11", "r12", "r13", "cc"); + + /* Reduce 258 bits into 256. */ + __asm__ __volatile__( + /* Preload */ + "movq %q5, %%r10\n" + /* (rax,rdx) = p4 * c0 */ + "movq %7, %%rax\n" + "mulq %%r10\n" + /* (rax,rdx) += p0 */ + "addq %q1, %%rax\n" + "adcq $0, %%rdx\n" + /* extract r0 */ + "movq %%rax, 0(%q6)\n" + /* Move to (r8,r9) */ + "movq %%rdx, %%r8\n" + "xorq %%r9, %%r9\n" + /* (r8,r9) += p1 */ + "addq %q2, %%r8\n" + "adcq $0, %%r9\n" + /* (r8,r9) += p4 * c1 */ + "movq %8, %%rax\n" + "mulq %%r10\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + /* Extract r1 */ + "movq %%r8, 8(%q6)\n" + "xorq %%r8, %%r8\n" + /* (r9,r8) += p4 */ + "addq %%r10, %%r9\n" + "adcq $0, %%r8\n" + /* (r9,r8) += p2 */ + "addq %q3, %%r9\n" + "adcq $0, %%r8\n" + /* Extract r2 */ + "movq %%r9, 16(%q6)\n" + "xorq %%r9, %%r9\n" + /* (r8,r9) += p3 */ + "addq %q4, %%r8\n" + "adcq $0, %%r9\n" + /* Extract r3 */ + "movq %%r8, 24(%q6)\n" + /* Extract c */ + "movq %%r9, %q0\n" + : "=g"(c) + : "g"(p0), "g"(p1), "g"(p2), "g"(p3), "g"(p4), "D"(r), "n"(SECP256K1_N_C_0), "n"(SECP256K1_N_C_1) + : "rax", "rdx", "r8", "r9", "r10", "cc", "memory"); +#else + uint128_t c; + uint64_t c0, c1, c2; + uint64_t n0 = l[4], n1 = l[5], n2 = l[6], n3 = l[7]; + uint64_t m0, m1, m2, m3, m4, m5; + uint32_t m6; + uint64_t p0, p1, p2, p3; + uint32_t p4; + + /* Reduce 512 bits into 385. */ + /* m[0..6] = l[0..3] + n[0..3] * SECP256K1_N_C. */ + c0 = l[0]; c1 = 0; c2 = 0; + muladd_fast(n0, SECP256K1_N_C_0); + extract_fast(m0); + sumadd_fast(l[1]); + muladd(n1, SECP256K1_N_C_0); + muladd(n0, SECP256K1_N_C_1); + extract(m1); + sumadd(l[2]); + muladd(n2, SECP256K1_N_C_0); + muladd(n1, SECP256K1_N_C_1); + sumadd(n0); + extract(m2); + sumadd(l[3]); + muladd(n3, SECP256K1_N_C_0); + muladd(n2, SECP256K1_N_C_1); + sumadd(n1); + extract(m3); + muladd(n3, SECP256K1_N_C_1); + sumadd(n2); + extract(m4); + sumadd_fast(n3); + extract_fast(m5); + VERIFY_CHECK(c0 <= 1); + m6 = (uint32_t)c0; + + /* Reduce 385 bits into 258. */ + /* p[0..4] = m[0..3] + m[4..6] * SECP256K1_N_C. */ + c0 = m0; c1 = 0; c2 = 0; + muladd_fast(m4, SECP256K1_N_C_0); + extract_fast(p0); + sumadd_fast(m1); + muladd(m5, SECP256K1_N_C_0); + muladd(m4, SECP256K1_N_C_1); + extract(p1); + sumadd(m2); + muladd(m6, SECP256K1_N_C_0); + muladd(m5, SECP256K1_N_C_1); + sumadd(m4); + extract(p2); + sumadd_fast(m3); + muladd_fast(m6, SECP256K1_N_C_1); + sumadd_fast(m5); + extract_fast(p3); + p4 = (uint32_t)c0 + m6; + VERIFY_CHECK(p4 <= 2); + + /* Reduce 258 bits into 256. */ + /* r[0..3] = p[0..3] + p[4] * SECP256K1_N_C. */ + c = p0 + (uint128_t)SECP256K1_N_C_0 * p4; + r->d[0] = c & 0xFFFFFFFFFFFFFFFFULL; c >>= 64; + c += p1 + (uint128_t)SECP256K1_N_C_1 * p4; + r->d[1] = c & 0xFFFFFFFFFFFFFFFFULL; c >>= 64; + c += p2 + (uint128_t)p4; + r->d[2] = c & 0xFFFFFFFFFFFFFFFFULL; c >>= 64; + c += p3; + r->d[3] = c & 0xFFFFFFFFFFFFFFFFULL; c >>= 64; +#endif + + /* Final reduction of r. */ + secp256k1_scalar_reduce(r, c + secp256k1_scalar_check_overflow(r)); +} + +static void secp256k1_scalar_mul_512(uint64_t l[8], const secp256k1_scalar *a, const secp256k1_scalar *b) { +#ifdef USE_ASM_X86_64 + const uint64_t *pb = b->d; + __asm__ __volatile__( + /* Preload */ + "movq 0(%%rdi), %%r15\n" + "movq 8(%%rdi), %%rbx\n" + "movq 16(%%rdi), %%rcx\n" + "movq 0(%%rdx), %%r11\n" + "movq 8(%%rdx), %%r12\n" + "movq 16(%%rdx), %%r13\n" + "movq 24(%%rdx), %%r14\n" + /* (rax,rdx) = a0 * b0 */ + "movq %%r15, %%rax\n" + "mulq %%r11\n" + /* Extract l0 */ + "movq %%rax, 0(%%rsi)\n" + /* (r8,r9,r10) = (rdx) */ + "movq %%rdx, %%r8\n" + "xorq %%r9, %%r9\n" + "xorq %%r10, %%r10\n" + /* (r8,r9,r10) += a0 * b1 */ + "movq %%r15, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* (r8,r9,r10) += a1 * b0 */ + "movq %%rbx, %%rax\n" + "mulq %%r11\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* Extract l1 */ + "movq %%r8, 8(%%rsi)\n" + "xorq %%r8, %%r8\n" + /* (r9,r10,r8) += a0 * b2 */ + "movq %%r15, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* (r9,r10,r8) += a1 * b1 */ + "movq %%rbx, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* (r9,r10,r8) += a2 * b0 */ + "movq %%rcx, %%rax\n" + "mulq %%r11\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* Extract l2 */ + "movq %%r9, 16(%%rsi)\n" + "xorq %%r9, %%r9\n" + /* (r10,r8,r9) += a0 * b3 */ + "movq %%r15, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* Preload a3 */ + "movq 24(%%rdi), %%r15\n" + /* (r10,r8,r9) += a1 * b2 */ + "movq %%rbx, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += a2 * b1 */ + "movq %%rcx, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += a3 * b0 */ + "movq %%r15, %%rax\n" + "mulq %%r11\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* Extract l3 */ + "movq %%r10, 24(%%rsi)\n" + "xorq %%r10, %%r10\n" + /* (r8,r9,r10) += a1 * b3 */ + "movq %%rbx, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* (r8,r9,r10) += a2 * b2 */ + "movq %%rcx, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* (r8,r9,r10) += a3 * b1 */ + "movq %%r15, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* Extract l4 */ + "movq %%r8, 32(%%rsi)\n" + "xorq %%r8, %%r8\n" + /* (r9,r10,r8) += a2 * b3 */ + "movq %%rcx, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* (r9,r10,r8) += a3 * b2 */ + "movq %%r15, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* Extract l5 */ + "movq %%r9, 40(%%rsi)\n" + /* (r10,r8) += a3 * b3 */ + "movq %%r15, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + /* Extract l6 */ + "movq %%r10, 48(%%rsi)\n" + /* Extract l7 */ + "movq %%r8, 56(%%rsi)\n" + : "+d"(pb) + : "S"(l), "D"(a->d) + : "rax", "rbx", "rcx", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "cc", "memory"); +#else + /* 160 bit accumulator. */ + uint64_t c0 = 0, c1 = 0; + uint32_t c2 = 0; + + /* l[0..7] = a[0..3] * b[0..3]. */ + muladd_fast(a->d[0], b->d[0]); + extract_fast(l[0]); + muladd(a->d[0], b->d[1]); + muladd(a->d[1], b->d[0]); + extract(l[1]); + muladd(a->d[0], b->d[2]); + muladd(a->d[1], b->d[1]); + muladd(a->d[2], b->d[0]); + extract(l[2]); + muladd(a->d[0], b->d[3]); + muladd(a->d[1], b->d[2]); + muladd(a->d[2], b->d[1]); + muladd(a->d[3], b->d[0]); + extract(l[3]); + muladd(a->d[1], b->d[3]); + muladd(a->d[2], b->d[2]); + muladd(a->d[3], b->d[1]); + extract(l[4]); + muladd(a->d[2], b->d[3]); + muladd(a->d[3], b->d[2]); + extract(l[5]); + muladd_fast(a->d[3], b->d[3]); + extract_fast(l[6]); + VERIFY_CHECK(c1 == 0); + l[7] = c0; +#endif +} + +static void secp256k1_scalar_sqr_512(uint64_t l[8], const secp256k1_scalar *a) { +#ifdef USE_ASM_X86_64 + __asm__ __volatile__( + /* Preload */ + "movq 0(%%rdi), %%r11\n" + "movq 8(%%rdi), %%r12\n" + "movq 16(%%rdi), %%r13\n" + "movq 24(%%rdi), %%r14\n" + /* (rax,rdx) = a0 * a0 */ + "movq %%r11, %%rax\n" + "mulq %%r11\n" + /* Extract l0 */ + "movq %%rax, 0(%%rsi)\n" + /* (r8,r9,r10) = (rdx,0) */ + "movq %%rdx, %%r8\n" + "xorq %%r9, %%r9\n" + "xorq %%r10, %%r10\n" + /* (r8,r9,r10) += 2 * a0 * a1 */ + "movq %%r11, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* Extract l1 */ + "movq %%r8, 8(%%rsi)\n" + "xorq %%r8, %%r8\n" + /* (r9,r10,r8) += 2 * a0 * a2 */ + "movq %%r11, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* (r9,r10,r8) += a1 * a1 */ + "movq %%r12, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* Extract l2 */ + "movq %%r9, 16(%%rsi)\n" + "xorq %%r9, %%r9\n" + /* (r10,r8,r9) += 2 * a0 * a3 */ + "movq %%r11, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += 2 * a1 * a2 */ + "movq %%r12, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* Extract l3 */ + "movq %%r10, 24(%%rsi)\n" + "xorq %%r10, %%r10\n" + /* (r8,r9,r10) += 2 * a1 * a3 */ + "movq %%r12, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* (r8,r9,r10) += a2 * a2 */ + "movq %%r13, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* Extract l4 */ + "movq %%r8, 32(%%rsi)\n" + "xorq %%r8, %%r8\n" + /* (r9,r10,r8) += 2 * a2 * a3 */ + "movq %%r13, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* Extract l5 */ + "movq %%r9, 40(%%rsi)\n" + /* (r10,r8) += a3 * a3 */ + "movq %%r14, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + /* Extract l6 */ + "movq %%r10, 48(%%rsi)\n" + /* Extract l7 */ + "movq %%r8, 56(%%rsi)\n" + : + : "S"(l), "D"(a->d) + : "rax", "rdx", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "cc", "memory"); +#else + /* 160 bit accumulator. */ + uint64_t c0 = 0, c1 = 0; + uint32_t c2 = 0; + + /* l[0..7] = a[0..3] * b[0..3]. */ + muladd_fast(a->d[0], a->d[0]); + extract_fast(l[0]); + muladd2(a->d[0], a->d[1]); + extract(l[1]); + muladd2(a->d[0], a->d[2]); + muladd(a->d[1], a->d[1]); + extract(l[2]); + muladd2(a->d[0], a->d[3]); + muladd2(a->d[1], a->d[2]); + extract(l[3]); + muladd2(a->d[1], a->d[3]); + muladd(a->d[2], a->d[2]); + extract(l[4]); + muladd2(a->d[2], a->d[3]); + extract(l[5]); + muladd_fast(a->d[3], a->d[3]); + extract_fast(l[6]); + VERIFY_CHECK(c1 == 0); + l[7] = c0; +#endif +} + +#undef sumadd +#undef sumadd_fast +#undef muladd +#undef muladd_fast +#undef muladd2 +#undef extract +#undef extract_fast + +static void secp256k1_scalar_mul(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b) { + uint64_t l[8]; + secp256k1_scalar_mul_512(l, a, b); + secp256k1_scalar_reduce_512(r, l); +} + +static int secp256k1_scalar_shr_int(secp256k1_scalar *r, int n) { + int ret; + VERIFY_CHECK(n > 0); + VERIFY_CHECK(n < 16); + ret = r->d[0] & ((1 << n) - 1); + r->d[0] = (r->d[0] >> n) + (r->d[1] << (64 - n)); + r->d[1] = (r->d[1] >> n) + (r->d[2] << (64 - n)); + r->d[2] = (r->d[2] >> n) + (r->d[3] << (64 - n)); + r->d[3] = (r->d[3] >> n); + return ret; +} + +static void secp256k1_scalar_sqr(secp256k1_scalar *r, const secp256k1_scalar *a) { + uint64_t l[8]; + secp256k1_scalar_sqr_512(l, a); + secp256k1_scalar_reduce_512(r, l); +} + +#ifdef USE_ENDOMORPHISM +static void secp256k1_scalar_split_128(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { + r1->d[0] = a->d[0]; + r1->d[1] = a->d[1]; + r1->d[2] = 0; + r1->d[3] = 0; + r2->d[0] = a->d[2]; + r2->d[1] = a->d[3]; + r2->d[2] = 0; + r2->d[3] = 0; +} +#endif + +SECP256K1_INLINE static int secp256k1_scalar_eq(const secp256k1_scalar *a, const secp256k1_scalar *b) { + return ((a->d[0] ^ b->d[0]) | (a->d[1] ^ b->d[1]) | (a->d[2] ^ b->d[2]) | (a->d[3] ^ b->d[3])) == 0; +} + +SECP256K1_INLINE static void secp256k1_scalar_mul_shift_var(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b, unsigned int shift) { + uint64_t l[8]; + unsigned int shiftlimbs; + unsigned int shiftlow; + unsigned int shifthigh; + VERIFY_CHECK(shift >= 256); + secp256k1_scalar_mul_512(l, a, b); + shiftlimbs = shift >> 6; + shiftlow = shift & 0x3F; + shifthigh = 64 - shiftlow; + r->d[0] = shift < 512 ? (l[0 + shiftlimbs] >> shiftlow | (shift < 448 && shiftlow ? (l[1 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[1] = shift < 448 ? (l[1 + shiftlimbs] >> shiftlow | (shift < 384 && shiftlow ? (l[2 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[2] = shift < 384 ? (l[2 + shiftlimbs] >> shiftlow | (shift < 320 && shiftlow ? (l[3 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[3] = shift < 320 ? (l[3 + shiftlimbs] >> shiftlow) : 0; + secp256k1_scalar_cadd_bit(r, 0, (l[(shift - 1) >> 6] >> ((shift - 1) & 0x3f)) & 1); +} + +#endif /* SECP256K1_SCALAR_REPR_IMPL_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_8x32.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_8x32.h new file mode 100644 index 000000000..2c9a348e2 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_8x32.h @@ -0,0 +1,19 @@ +/********************************************************************** + * Copyright (c) 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_REPR_H +#define SECP256K1_SCALAR_REPR_H + +#include + +/** A scalar modulo the group order of the secp256k1 curve. */ +typedef struct { + uint32_t d[8]; +} secp256k1_scalar; + +#define SECP256K1_SCALAR_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{(d0), (d1), (d2), (d3), (d4), (d5), (d6), (d7)}} + +#endif /* SECP256K1_SCALAR_REPR_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_8x32_impl.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_8x32_impl.h new file mode 100644 index 000000000..b2c0581cf --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_8x32_impl.h @@ -0,0 +1,721 @@ +/********************************************************************** + * Copyright (c) 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_REPR_IMPL_H +#define SECP256K1_SCALAR_REPR_IMPL_H + +/* Limbs of the secp256k1 order. */ +#define SECP256K1_N_0 ((uint32_t)0xD0364141UL) +#define SECP256K1_N_1 ((uint32_t)0xBFD25E8CUL) +#define SECP256K1_N_2 ((uint32_t)0xAF48A03BUL) +#define SECP256K1_N_3 ((uint32_t)0xBAAEDCE6UL) +#define SECP256K1_N_4 ((uint32_t)0xFFFFFFFEUL) +#define SECP256K1_N_5 ((uint32_t)0xFFFFFFFFUL) +#define SECP256K1_N_6 ((uint32_t)0xFFFFFFFFUL) +#define SECP256K1_N_7 ((uint32_t)0xFFFFFFFFUL) + +/* Limbs of 2^256 minus the secp256k1 order. */ +#define SECP256K1_N_C_0 (~SECP256K1_N_0 + 1) +#define SECP256K1_N_C_1 (~SECP256K1_N_1) +#define SECP256K1_N_C_2 (~SECP256K1_N_2) +#define SECP256K1_N_C_3 (~SECP256K1_N_3) +#define SECP256K1_N_C_4 (1) + +/* Limbs of half the secp256k1 order. */ +#define SECP256K1_N_H_0 ((uint32_t)0x681B20A0UL) +#define SECP256K1_N_H_1 ((uint32_t)0xDFE92F46UL) +#define SECP256K1_N_H_2 ((uint32_t)0x57A4501DUL) +#define SECP256K1_N_H_3 ((uint32_t)0x5D576E73UL) +#define SECP256K1_N_H_4 ((uint32_t)0xFFFFFFFFUL) +#define SECP256K1_N_H_5 ((uint32_t)0xFFFFFFFFUL) +#define SECP256K1_N_H_6 ((uint32_t)0xFFFFFFFFUL) +#define SECP256K1_N_H_7 ((uint32_t)0x7FFFFFFFUL) + +SECP256K1_INLINE static void secp256k1_scalar_clear(secp256k1_scalar *r) { + r->d[0] = 0; + r->d[1] = 0; + r->d[2] = 0; + r->d[3] = 0; + r->d[4] = 0; + r->d[5] = 0; + r->d[6] = 0; + r->d[7] = 0; +} + +SECP256K1_INLINE static void secp256k1_scalar_set_int(secp256k1_scalar *r, unsigned int v) { + r->d[0] = v; + r->d[1] = 0; + r->d[2] = 0; + r->d[3] = 0; + r->d[4] = 0; + r->d[5] = 0; + r->d[6] = 0; + r->d[7] = 0; +} + +SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits(const secp256k1_scalar *a, unsigned int offset, unsigned int count) { + VERIFY_CHECK((offset + count - 1) >> 5 == offset >> 5); + return (a->d[offset >> 5] >> (offset & 0x1F)) & ((1 << count) - 1); +} + +SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits_var(const secp256k1_scalar *a, unsigned int offset, unsigned int count) { + VERIFY_CHECK(count < 32); + VERIFY_CHECK(offset + count <= 256); + if ((offset + count - 1) >> 5 == offset >> 5) { + return secp256k1_scalar_get_bits(a, offset, count); + } else { + VERIFY_CHECK((offset >> 5) + 1 < 8); + return ((a->d[offset >> 5] >> (offset & 0x1F)) | (a->d[(offset >> 5) + 1] << (32 - (offset & 0x1F)))) & ((((uint32_t)1) << count) - 1); + } +} + +SECP256K1_INLINE static int secp256k1_scalar_check_overflow(const secp256k1_scalar *a) { + int yes = 0; + int no = 0; + no |= (a->d[7] < SECP256K1_N_7); /* No need for a > check. */ + no |= (a->d[6] < SECP256K1_N_6); /* No need for a > check. */ + no |= (a->d[5] < SECP256K1_N_5); /* No need for a > check. */ + no |= (a->d[4] < SECP256K1_N_4); + yes |= (a->d[4] > SECP256K1_N_4) & ~no; + no |= (a->d[3] < SECP256K1_N_3) & ~yes; + yes |= (a->d[3] > SECP256K1_N_3) & ~no; + no |= (a->d[2] < SECP256K1_N_2) & ~yes; + yes |= (a->d[2] > SECP256K1_N_2) & ~no; + no |= (a->d[1] < SECP256K1_N_1) & ~yes; + yes |= (a->d[1] > SECP256K1_N_1) & ~no; + yes |= (a->d[0] >= SECP256K1_N_0) & ~no; + return yes; +} + +SECP256K1_INLINE static int secp256k1_scalar_reduce(secp256k1_scalar *r, uint32_t overflow) { + uint64_t t; + VERIFY_CHECK(overflow <= 1); + t = (uint64_t)r->d[0] + overflow * SECP256K1_N_C_0; + r->d[0] = t & 0xFFFFFFFFUL; t >>= 32; + t += (uint64_t)r->d[1] + overflow * SECP256K1_N_C_1; + r->d[1] = t & 0xFFFFFFFFUL; t >>= 32; + t += (uint64_t)r->d[2] + overflow * SECP256K1_N_C_2; + r->d[2] = t & 0xFFFFFFFFUL; t >>= 32; + t += (uint64_t)r->d[3] + overflow * SECP256K1_N_C_3; + r->d[3] = t & 0xFFFFFFFFUL; t >>= 32; + t += (uint64_t)r->d[4] + overflow * SECP256K1_N_C_4; + r->d[4] = t & 0xFFFFFFFFUL; t >>= 32; + t += (uint64_t)r->d[5]; + r->d[5] = t & 0xFFFFFFFFUL; t >>= 32; + t += (uint64_t)r->d[6]; + r->d[6] = t & 0xFFFFFFFFUL; t >>= 32; + t += (uint64_t)r->d[7]; + r->d[7] = t & 0xFFFFFFFFUL; + return overflow; +} + +static int secp256k1_scalar_add(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b) { + int overflow; + uint64_t t = (uint64_t)a->d[0] + b->d[0]; + r->d[0] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)a->d[1] + b->d[1]; + r->d[1] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)a->d[2] + b->d[2]; + r->d[2] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)a->d[3] + b->d[3]; + r->d[3] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)a->d[4] + b->d[4]; + r->d[4] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)a->d[5] + b->d[5]; + r->d[5] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)a->d[6] + b->d[6]; + r->d[6] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)a->d[7] + b->d[7]; + r->d[7] = t & 0xFFFFFFFFULL; t >>= 32; + overflow = (int)t + secp256k1_scalar_check_overflow(r); + VERIFY_CHECK(overflow == 0 || overflow == 1); + secp256k1_scalar_reduce(r, overflow); + return overflow; +} + +static void secp256k1_scalar_cadd_bit(secp256k1_scalar *r, unsigned int bit, int flag) { + uint64_t t; + VERIFY_CHECK(bit < 256); + bit += ((uint32_t) flag - 1) & 0x100; /* forcing (bit >> 5) > 7 makes this a noop */ + t = (uint64_t)r->d[0] + (((uint32_t)((bit >> 5) == 0)) << (bit & 0x1F)); + r->d[0] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)r->d[1] + (((uint32_t)((bit >> 5) == 1)) << (bit & 0x1F)); + r->d[1] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)r->d[2] + (((uint32_t)((bit >> 5) == 2)) << (bit & 0x1F)); + r->d[2] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)r->d[3] + (((uint32_t)((bit >> 5) == 3)) << (bit & 0x1F)); + r->d[3] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)r->d[4] + (((uint32_t)((bit >> 5) == 4)) << (bit & 0x1F)); + r->d[4] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)r->d[5] + (((uint32_t)((bit >> 5) == 5)) << (bit & 0x1F)); + r->d[5] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)r->d[6] + (((uint32_t)((bit >> 5) == 6)) << (bit & 0x1F)); + r->d[6] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)r->d[7] + (((uint32_t)((bit >> 5) == 7)) << (bit & 0x1F)); + r->d[7] = t & 0xFFFFFFFFULL; +#ifdef VERIFY + VERIFY_CHECK((t >> 32) == 0); + VERIFY_CHECK(secp256k1_scalar_check_overflow(r) == 0); +#endif +} + +static void secp256k1_scalar_set_b32(secp256k1_scalar *r, const unsigned char *b32, int *overflow) { + int over; + r->d[0] = (uint32_t)b32[31] | (uint32_t)b32[30] << 8 | (uint32_t)b32[29] << 16 | (uint32_t)b32[28] << 24; + r->d[1] = (uint32_t)b32[27] | (uint32_t)b32[26] << 8 | (uint32_t)b32[25] << 16 | (uint32_t)b32[24] << 24; + r->d[2] = (uint32_t)b32[23] | (uint32_t)b32[22] << 8 | (uint32_t)b32[21] << 16 | (uint32_t)b32[20] << 24; + r->d[3] = (uint32_t)b32[19] | (uint32_t)b32[18] << 8 | (uint32_t)b32[17] << 16 | (uint32_t)b32[16] << 24; + r->d[4] = (uint32_t)b32[15] | (uint32_t)b32[14] << 8 | (uint32_t)b32[13] << 16 | (uint32_t)b32[12] << 24; + r->d[5] = (uint32_t)b32[11] | (uint32_t)b32[10] << 8 | (uint32_t)b32[9] << 16 | (uint32_t)b32[8] << 24; + r->d[6] = (uint32_t)b32[7] | (uint32_t)b32[6] << 8 | (uint32_t)b32[5] << 16 | (uint32_t)b32[4] << 24; + r->d[7] = (uint32_t)b32[3] | (uint32_t)b32[2] << 8 | (uint32_t)b32[1] << 16 | (uint32_t)b32[0] << 24; + over = secp256k1_scalar_reduce(r, secp256k1_scalar_check_overflow(r)); + if (overflow) { + *overflow = over; + } +} + +static void secp256k1_scalar_get_b32(unsigned char *bin, const secp256k1_scalar* a) { + bin[0] = a->d[7] >> 24; bin[1] = a->d[7] >> 16; bin[2] = a->d[7] >> 8; bin[3] = a->d[7]; + bin[4] = a->d[6] >> 24; bin[5] = a->d[6] >> 16; bin[6] = a->d[6] >> 8; bin[7] = a->d[6]; + bin[8] = a->d[5] >> 24; bin[9] = a->d[5] >> 16; bin[10] = a->d[5] >> 8; bin[11] = a->d[5]; + bin[12] = a->d[4] >> 24; bin[13] = a->d[4] >> 16; bin[14] = a->d[4] >> 8; bin[15] = a->d[4]; + bin[16] = a->d[3] >> 24; bin[17] = a->d[3] >> 16; bin[18] = a->d[3] >> 8; bin[19] = a->d[3]; + bin[20] = a->d[2] >> 24; bin[21] = a->d[2] >> 16; bin[22] = a->d[2] >> 8; bin[23] = a->d[2]; + bin[24] = a->d[1] >> 24; bin[25] = a->d[1] >> 16; bin[26] = a->d[1] >> 8; bin[27] = a->d[1]; + bin[28] = a->d[0] >> 24; bin[29] = a->d[0] >> 16; bin[30] = a->d[0] >> 8; bin[31] = a->d[0]; +} + +SECP256K1_INLINE static int secp256k1_scalar_is_zero(const secp256k1_scalar *a) { + return (a->d[0] | a->d[1] | a->d[2] | a->d[3] | a->d[4] | a->d[5] | a->d[6] | a->d[7]) == 0; +} + +static void secp256k1_scalar_negate(secp256k1_scalar *r, const secp256k1_scalar *a) { + uint32_t nonzero = 0xFFFFFFFFUL * (secp256k1_scalar_is_zero(a) == 0); + uint64_t t = (uint64_t)(~a->d[0]) + SECP256K1_N_0 + 1; + r->d[0] = t & nonzero; t >>= 32; + t += (uint64_t)(~a->d[1]) + SECP256K1_N_1; + r->d[1] = t & nonzero; t >>= 32; + t += (uint64_t)(~a->d[2]) + SECP256K1_N_2; + r->d[2] = t & nonzero; t >>= 32; + t += (uint64_t)(~a->d[3]) + SECP256K1_N_3; + r->d[3] = t & nonzero; t >>= 32; + t += (uint64_t)(~a->d[4]) + SECP256K1_N_4; + r->d[4] = t & nonzero; t >>= 32; + t += (uint64_t)(~a->d[5]) + SECP256K1_N_5; + r->d[5] = t & nonzero; t >>= 32; + t += (uint64_t)(~a->d[6]) + SECP256K1_N_6; + r->d[6] = t & nonzero; t >>= 32; + t += (uint64_t)(~a->d[7]) + SECP256K1_N_7; + r->d[7] = t & nonzero; +} + +SECP256K1_INLINE static int secp256k1_scalar_is_one(const secp256k1_scalar *a) { + return ((a->d[0] ^ 1) | a->d[1] | a->d[2] | a->d[3] | a->d[4] | a->d[5] | a->d[6] | a->d[7]) == 0; +} + +static int secp256k1_scalar_is_high(const secp256k1_scalar *a) { + int yes = 0; + int no = 0; + no |= (a->d[7] < SECP256K1_N_H_7); + yes |= (a->d[7] > SECP256K1_N_H_7) & ~no; + no |= (a->d[6] < SECP256K1_N_H_6) & ~yes; /* No need for a > check. */ + no |= (a->d[5] < SECP256K1_N_H_5) & ~yes; /* No need for a > check. */ + no |= (a->d[4] < SECP256K1_N_H_4) & ~yes; /* No need for a > check. */ + no |= (a->d[3] < SECP256K1_N_H_3) & ~yes; + yes |= (a->d[3] > SECP256K1_N_H_3) & ~no; + no |= (a->d[2] < SECP256K1_N_H_2) & ~yes; + yes |= (a->d[2] > SECP256K1_N_H_2) & ~no; + no |= (a->d[1] < SECP256K1_N_H_1) & ~yes; + yes |= (a->d[1] > SECP256K1_N_H_1) & ~no; + yes |= (a->d[0] > SECP256K1_N_H_0) & ~no; + return yes; +} + +static int secp256k1_scalar_cond_negate(secp256k1_scalar *r, int flag) { + /* If we are flag = 0, mask = 00...00 and this is a no-op; + * if we are flag = 1, mask = 11...11 and this is identical to secp256k1_scalar_negate */ + uint32_t mask = !flag - 1; + uint32_t nonzero = 0xFFFFFFFFUL * (secp256k1_scalar_is_zero(r) == 0); + uint64_t t = (uint64_t)(r->d[0] ^ mask) + ((SECP256K1_N_0 + 1) & mask); + r->d[0] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[1] ^ mask) + (SECP256K1_N_1 & mask); + r->d[1] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[2] ^ mask) + (SECP256K1_N_2 & mask); + r->d[2] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[3] ^ mask) + (SECP256K1_N_3 & mask); + r->d[3] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[4] ^ mask) + (SECP256K1_N_4 & mask); + r->d[4] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[5] ^ mask) + (SECP256K1_N_5 & mask); + r->d[5] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[6] ^ mask) + (SECP256K1_N_6 & mask); + r->d[6] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[7] ^ mask) + (SECP256K1_N_7 & mask); + r->d[7] = t & nonzero; + return 2 * (mask == 0) - 1; +} + + +/* Inspired by the macros in OpenSSL's crypto/bn/asm/x86_64-gcc.c. */ + +/** Add a*b to the number defined by (c0,c1,c2). c2 must never overflow. */ +#define muladd(a,b) { \ + uint32_t tl, th; \ + { \ + uint64_t t = (uint64_t)a * b; \ + th = t >> 32; /* at most 0xFFFFFFFE */ \ + tl = t; \ + } \ + c0 += tl; /* overflow is handled on the next line */ \ + th += (c0 < tl) ? 1 : 0; /* at most 0xFFFFFFFF */ \ + c1 += th; /* overflow is handled on the next line */ \ + c2 += (c1 < th) ? 1 : 0; /* never overflows by contract (verified in the next line) */ \ + VERIFY_CHECK((c1 >= th) || (c2 != 0)); \ +} + +/** Add a*b to the number defined by (c0,c1). c1 must never overflow. */ +#define muladd_fast(a,b) { \ + uint32_t tl, th; \ + { \ + uint64_t t = (uint64_t)a * b; \ + th = t >> 32; /* at most 0xFFFFFFFE */ \ + tl = t; \ + } \ + c0 += tl; /* overflow is handled on the next line */ \ + th += (c0 < tl) ? 1 : 0; /* at most 0xFFFFFFFF */ \ + c1 += th; /* never overflows by contract (verified in the next line) */ \ + VERIFY_CHECK(c1 >= th); \ +} + +/** Add 2*a*b to the number defined by (c0,c1,c2). c2 must never overflow. */ +#define muladd2(a,b) { \ + uint32_t tl, th, th2, tl2; \ + { \ + uint64_t t = (uint64_t)a * b; \ + th = t >> 32; /* at most 0xFFFFFFFE */ \ + tl = t; \ + } \ + th2 = th + th; /* at most 0xFFFFFFFE (in case th was 0x7FFFFFFF) */ \ + c2 += (th2 < th) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ + VERIFY_CHECK((th2 >= th) || (c2 != 0)); \ + tl2 = tl + tl; /* at most 0xFFFFFFFE (in case the lowest 63 bits of tl were 0x7FFFFFFF) */ \ + th2 += (tl2 < tl) ? 1 : 0; /* at most 0xFFFFFFFF */ \ + c0 += tl2; /* overflow is handled on the next line */ \ + th2 += (c0 < tl2) ? 1 : 0; /* second overflow is handled on the next line */ \ + c2 += (c0 < tl2) & (th2 == 0); /* never overflows by contract (verified the next line) */ \ + VERIFY_CHECK((c0 >= tl2) || (th2 != 0) || (c2 != 0)); \ + c1 += th2; /* overflow is handled on the next line */ \ + c2 += (c1 < th2) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ + VERIFY_CHECK((c1 >= th2) || (c2 != 0)); \ +} + +/** Add a to the number defined by (c0,c1,c2). c2 must never overflow. */ +#define sumadd(a) { \ + unsigned int over; \ + c0 += (a); /* overflow is handled on the next line */ \ + over = (c0 < (a)) ? 1 : 0; \ + c1 += over; /* overflow is handled on the next line */ \ + c2 += (c1 < over) ? 1 : 0; /* never overflows by contract */ \ +} + +/** Add a to the number defined by (c0,c1). c1 must never overflow, c2 must be zero. */ +#define sumadd_fast(a) { \ + c0 += (a); /* overflow is handled on the next line */ \ + c1 += (c0 < (a)) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ + VERIFY_CHECK((c1 != 0) | (c0 >= (a))); \ + VERIFY_CHECK(c2 == 0); \ +} + +/** Extract the lowest 32 bits of (c0,c1,c2) into n, and left shift the number 32 bits. */ +#define extract(n) { \ + (n) = c0; \ + c0 = c1; \ + c1 = c2; \ + c2 = 0; \ +} + +/** Extract the lowest 32 bits of (c0,c1,c2) into n, and left shift the number 32 bits. c2 is required to be zero. */ +#define extract_fast(n) { \ + (n) = c0; \ + c0 = c1; \ + c1 = 0; \ + VERIFY_CHECK(c2 == 0); \ +} + +static void secp256k1_scalar_reduce_512(secp256k1_scalar *r, const uint32_t *l) { + uint64_t c; + uint32_t n0 = l[8], n1 = l[9], n2 = l[10], n3 = l[11], n4 = l[12], n5 = l[13], n6 = l[14], n7 = l[15]; + uint32_t m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12; + uint32_t p0, p1, p2, p3, p4, p5, p6, p7, p8; + + /* 96 bit accumulator. */ + uint32_t c0, c1, c2; + + /* Reduce 512 bits into 385. */ + /* m[0..12] = l[0..7] + n[0..7] * SECP256K1_N_C. */ + c0 = l[0]; c1 = 0; c2 = 0; + muladd_fast(n0, SECP256K1_N_C_0); + extract_fast(m0); + sumadd_fast(l[1]); + muladd(n1, SECP256K1_N_C_0); + muladd(n0, SECP256K1_N_C_1); + extract(m1); + sumadd(l[2]); + muladd(n2, SECP256K1_N_C_0); + muladd(n1, SECP256K1_N_C_1); + muladd(n0, SECP256K1_N_C_2); + extract(m2); + sumadd(l[3]); + muladd(n3, SECP256K1_N_C_0); + muladd(n2, SECP256K1_N_C_1); + muladd(n1, SECP256K1_N_C_2); + muladd(n0, SECP256K1_N_C_3); + extract(m3); + sumadd(l[4]); + muladd(n4, SECP256K1_N_C_0); + muladd(n3, SECP256K1_N_C_1); + muladd(n2, SECP256K1_N_C_2); + muladd(n1, SECP256K1_N_C_3); + sumadd(n0); + extract(m4); + sumadd(l[5]); + muladd(n5, SECP256K1_N_C_0); + muladd(n4, SECP256K1_N_C_1); + muladd(n3, SECP256K1_N_C_2); + muladd(n2, SECP256K1_N_C_3); + sumadd(n1); + extract(m5); + sumadd(l[6]); + muladd(n6, SECP256K1_N_C_0); + muladd(n5, SECP256K1_N_C_1); + muladd(n4, SECP256K1_N_C_2); + muladd(n3, SECP256K1_N_C_3); + sumadd(n2); + extract(m6); + sumadd(l[7]); + muladd(n7, SECP256K1_N_C_0); + muladd(n6, SECP256K1_N_C_1); + muladd(n5, SECP256K1_N_C_2); + muladd(n4, SECP256K1_N_C_3); + sumadd(n3); + extract(m7); + muladd(n7, SECP256K1_N_C_1); + muladd(n6, SECP256K1_N_C_2); + muladd(n5, SECP256K1_N_C_3); + sumadd(n4); + extract(m8); + muladd(n7, SECP256K1_N_C_2); + muladd(n6, SECP256K1_N_C_3); + sumadd(n5); + extract(m9); + muladd(n7, SECP256K1_N_C_3); + sumadd(n6); + extract(m10); + sumadd_fast(n7); + extract_fast(m11); + VERIFY_CHECK(c0 <= 1); + m12 = c0; + + /* Reduce 385 bits into 258. */ + /* p[0..8] = m[0..7] + m[8..12] * SECP256K1_N_C. */ + c0 = m0; c1 = 0; c2 = 0; + muladd_fast(m8, SECP256K1_N_C_0); + extract_fast(p0); + sumadd_fast(m1); + muladd(m9, SECP256K1_N_C_0); + muladd(m8, SECP256K1_N_C_1); + extract(p1); + sumadd(m2); + muladd(m10, SECP256K1_N_C_0); + muladd(m9, SECP256K1_N_C_1); + muladd(m8, SECP256K1_N_C_2); + extract(p2); + sumadd(m3); + muladd(m11, SECP256K1_N_C_0); + muladd(m10, SECP256K1_N_C_1); + muladd(m9, SECP256K1_N_C_2); + muladd(m8, SECP256K1_N_C_3); + extract(p3); + sumadd(m4); + muladd(m12, SECP256K1_N_C_0); + muladd(m11, SECP256K1_N_C_1); + muladd(m10, SECP256K1_N_C_2); + muladd(m9, SECP256K1_N_C_3); + sumadd(m8); + extract(p4); + sumadd(m5); + muladd(m12, SECP256K1_N_C_1); + muladd(m11, SECP256K1_N_C_2); + muladd(m10, SECP256K1_N_C_3); + sumadd(m9); + extract(p5); + sumadd(m6); + muladd(m12, SECP256K1_N_C_2); + muladd(m11, SECP256K1_N_C_3); + sumadd(m10); + extract(p6); + sumadd_fast(m7); + muladd_fast(m12, SECP256K1_N_C_3); + sumadd_fast(m11); + extract_fast(p7); + p8 = c0 + m12; + VERIFY_CHECK(p8 <= 2); + + /* Reduce 258 bits into 256. */ + /* r[0..7] = p[0..7] + p[8] * SECP256K1_N_C. */ + c = p0 + (uint64_t)SECP256K1_N_C_0 * p8; + r->d[0] = c & 0xFFFFFFFFUL; c >>= 32; + c += p1 + (uint64_t)SECP256K1_N_C_1 * p8; + r->d[1] = c & 0xFFFFFFFFUL; c >>= 32; + c += p2 + (uint64_t)SECP256K1_N_C_2 * p8; + r->d[2] = c & 0xFFFFFFFFUL; c >>= 32; + c += p3 + (uint64_t)SECP256K1_N_C_3 * p8; + r->d[3] = c & 0xFFFFFFFFUL; c >>= 32; + c += p4 + (uint64_t)p8; + r->d[4] = c & 0xFFFFFFFFUL; c >>= 32; + c += p5; + r->d[5] = c & 0xFFFFFFFFUL; c >>= 32; + c += p6; + r->d[6] = c & 0xFFFFFFFFUL; c >>= 32; + c += p7; + r->d[7] = c & 0xFFFFFFFFUL; c >>= 32; + + /* Final reduction of r. */ + secp256k1_scalar_reduce(r, c + secp256k1_scalar_check_overflow(r)); +} + +static void secp256k1_scalar_mul_512(uint32_t *l, const secp256k1_scalar *a, const secp256k1_scalar *b) { + /* 96 bit accumulator. */ + uint32_t c0 = 0, c1 = 0, c2 = 0; + + /* l[0..15] = a[0..7] * b[0..7]. */ + muladd_fast(a->d[0], b->d[0]); + extract_fast(l[0]); + muladd(a->d[0], b->d[1]); + muladd(a->d[1], b->d[0]); + extract(l[1]); + muladd(a->d[0], b->d[2]); + muladd(a->d[1], b->d[1]); + muladd(a->d[2], b->d[0]); + extract(l[2]); + muladd(a->d[0], b->d[3]); + muladd(a->d[1], b->d[2]); + muladd(a->d[2], b->d[1]); + muladd(a->d[3], b->d[0]); + extract(l[3]); + muladd(a->d[0], b->d[4]); + muladd(a->d[1], b->d[3]); + muladd(a->d[2], b->d[2]); + muladd(a->d[3], b->d[1]); + muladd(a->d[4], b->d[0]); + extract(l[4]); + muladd(a->d[0], b->d[5]); + muladd(a->d[1], b->d[4]); + muladd(a->d[2], b->d[3]); + muladd(a->d[3], b->d[2]); + muladd(a->d[4], b->d[1]); + muladd(a->d[5], b->d[0]); + extract(l[5]); + muladd(a->d[0], b->d[6]); + muladd(a->d[1], b->d[5]); + muladd(a->d[2], b->d[4]); + muladd(a->d[3], b->d[3]); + muladd(a->d[4], b->d[2]); + muladd(a->d[5], b->d[1]); + muladd(a->d[6], b->d[0]); + extract(l[6]); + muladd(a->d[0], b->d[7]); + muladd(a->d[1], b->d[6]); + muladd(a->d[2], b->d[5]); + muladd(a->d[3], b->d[4]); + muladd(a->d[4], b->d[3]); + muladd(a->d[5], b->d[2]); + muladd(a->d[6], b->d[1]); + muladd(a->d[7], b->d[0]); + extract(l[7]); + muladd(a->d[1], b->d[7]); + muladd(a->d[2], b->d[6]); + muladd(a->d[3], b->d[5]); + muladd(a->d[4], b->d[4]); + muladd(a->d[5], b->d[3]); + muladd(a->d[6], b->d[2]); + muladd(a->d[7], b->d[1]); + extract(l[8]); + muladd(a->d[2], b->d[7]); + muladd(a->d[3], b->d[6]); + muladd(a->d[4], b->d[5]); + muladd(a->d[5], b->d[4]); + muladd(a->d[6], b->d[3]); + muladd(a->d[7], b->d[2]); + extract(l[9]); + muladd(a->d[3], b->d[7]); + muladd(a->d[4], b->d[6]); + muladd(a->d[5], b->d[5]); + muladd(a->d[6], b->d[4]); + muladd(a->d[7], b->d[3]); + extract(l[10]); + muladd(a->d[4], b->d[7]); + muladd(a->d[5], b->d[6]); + muladd(a->d[6], b->d[5]); + muladd(a->d[7], b->d[4]); + extract(l[11]); + muladd(a->d[5], b->d[7]); + muladd(a->d[6], b->d[6]); + muladd(a->d[7], b->d[5]); + extract(l[12]); + muladd(a->d[6], b->d[7]); + muladd(a->d[7], b->d[6]); + extract(l[13]); + muladd_fast(a->d[7], b->d[7]); + extract_fast(l[14]); + VERIFY_CHECK(c1 == 0); + l[15] = c0; +} + +static void secp256k1_scalar_sqr_512(uint32_t *l, const secp256k1_scalar *a) { + /* 96 bit accumulator. */ + uint32_t c0 = 0, c1 = 0, c2 = 0; + + /* l[0..15] = a[0..7]^2. */ + muladd_fast(a->d[0], a->d[0]); + extract_fast(l[0]); + muladd2(a->d[0], a->d[1]); + extract(l[1]); + muladd2(a->d[0], a->d[2]); + muladd(a->d[1], a->d[1]); + extract(l[2]); + muladd2(a->d[0], a->d[3]); + muladd2(a->d[1], a->d[2]); + extract(l[3]); + muladd2(a->d[0], a->d[4]); + muladd2(a->d[1], a->d[3]); + muladd(a->d[2], a->d[2]); + extract(l[4]); + muladd2(a->d[0], a->d[5]); + muladd2(a->d[1], a->d[4]); + muladd2(a->d[2], a->d[3]); + extract(l[5]); + muladd2(a->d[0], a->d[6]); + muladd2(a->d[1], a->d[5]); + muladd2(a->d[2], a->d[4]); + muladd(a->d[3], a->d[3]); + extract(l[6]); + muladd2(a->d[0], a->d[7]); + muladd2(a->d[1], a->d[6]); + muladd2(a->d[2], a->d[5]); + muladd2(a->d[3], a->d[4]); + extract(l[7]); + muladd2(a->d[1], a->d[7]); + muladd2(a->d[2], a->d[6]); + muladd2(a->d[3], a->d[5]); + muladd(a->d[4], a->d[4]); + extract(l[8]); + muladd2(a->d[2], a->d[7]); + muladd2(a->d[3], a->d[6]); + muladd2(a->d[4], a->d[5]); + extract(l[9]); + muladd2(a->d[3], a->d[7]); + muladd2(a->d[4], a->d[6]); + muladd(a->d[5], a->d[5]); + extract(l[10]); + muladd2(a->d[4], a->d[7]); + muladd2(a->d[5], a->d[6]); + extract(l[11]); + muladd2(a->d[5], a->d[7]); + muladd(a->d[6], a->d[6]); + extract(l[12]); + muladd2(a->d[6], a->d[7]); + extract(l[13]); + muladd_fast(a->d[7], a->d[7]); + extract_fast(l[14]); + VERIFY_CHECK(c1 == 0); + l[15] = c0; +} + +#undef sumadd +#undef sumadd_fast +#undef muladd +#undef muladd_fast +#undef muladd2 +#undef extract +#undef extract_fast + +static void secp256k1_scalar_mul(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b) { + uint32_t l[16]; + secp256k1_scalar_mul_512(l, a, b); + secp256k1_scalar_reduce_512(r, l); +} + +static int secp256k1_scalar_shr_int(secp256k1_scalar *r, int n) { + int ret; + VERIFY_CHECK(n > 0); + VERIFY_CHECK(n < 16); + ret = r->d[0] & ((1 << n) - 1); + r->d[0] = (r->d[0] >> n) + (r->d[1] << (32 - n)); + r->d[1] = (r->d[1] >> n) + (r->d[2] << (32 - n)); + r->d[2] = (r->d[2] >> n) + (r->d[3] << (32 - n)); + r->d[3] = (r->d[3] >> n) + (r->d[4] << (32 - n)); + r->d[4] = (r->d[4] >> n) + (r->d[5] << (32 - n)); + r->d[5] = (r->d[5] >> n) + (r->d[6] << (32 - n)); + r->d[6] = (r->d[6] >> n) + (r->d[7] << (32 - n)); + r->d[7] = (r->d[7] >> n); + return ret; +} + +static void secp256k1_scalar_sqr(secp256k1_scalar *r, const secp256k1_scalar *a) { + uint32_t l[16]; + secp256k1_scalar_sqr_512(l, a); + secp256k1_scalar_reduce_512(r, l); +} + +#ifdef USE_ENDOMORPHISM +static void secp256k1_scalar_split_128(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { + r1->d[0] = a->d[0]; + r1->d[1] = a->d[1]; + r1->d[2] = a->d[2]; + r1->d[3] = a->d[3]; + r1->d[4] = 0; + r1->d[5] = 0; + r1->d[6] = 0; + r1->d[7] = 0; + r2->d[0] = a->d[4]; + r2->d[1] = a->d[5]; + r2->d[2] = a->d[6]; + r2->d[3] = a->d[7]; + r2->d[4] = 0; + r2->d[5] = 0; + r2->d[6] = 0; + r2->d[7] = 0; +} +#endif + +SECP256K1_INLINE static int secp256k1_scalar_eq(const secp256k1_scalar *a, const secp256k1_scalar *b) { + return ((a->d[0] ^ b->d[0]) | (a->d[1] ^ b->d[1]) | (a->d[2] ^ b->d[2]) | (a->d[3] ^ b->d[3]) | (a->d[4] ^ b->d[4]) | (a->d[5] ^ b->d[5]) | (a->d[6] ^ b->d[6]) | (a->d[7] ^ b->d[7])) == 0; +} + +SECP256K1_INLINE static void secp256k1_scalar_mul_shift_var(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b, unsigned int shift) { + uint32_t l[16]; + unsigned int shiftlimbs; + unsigned int shiftlow; + unsigned int shifthigh; + VERIFY_CHECK(shift >= 256); + secp256k1_scalar_mul_512(l, a, b); + shiftlimbs = shift >> 5; + shiftlow = shift & 0x1F; + shifthigh = 32 - shiftlow; + r->d[0] = shift < 512 ? (l[0 + shiftlimbs] >> shiftlow | (shift < 480 && shiftlow ? (l[1 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[1] = shift < 480 ? (l[1 + shiftlimbs] >> shiftlow | (shift < 448 && shiftlow ? (l[2 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[2] = shift < 448 ? (l[2 + shiftlimbs] >> shiftlow | (shift < 416 && shiftlow ? (l[3 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[3] = shift < 416 ? (l[3 + shiftlimbs] >> shiftlow | (shift < 384 && shiftlow ? (l[4 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[4] = shift < 384 ? (l[4 + shiftlimbs] >> shiftlow | (shift < 352 && shiftlow ? (l[5 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[5] = shift < 352 ? (l[5 + shiftlimbs] >> shiftlow | (shift < 320 && shiftlow ? (l[6 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[6] = shift < 320 ? (l[6 + shiftlimbs] >> shiftlow | (shift < 288 && shiftlow ? (l[7 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[7] = shift < 288 ? (l[7 + shiftlimbs] >> shiftlow) : 0; + secp256k1_scalar_cadd_bit(r, 0, (l[(shift - 1) >> 5] >> ((shift - 1) & 0x1f)) & 1); +} + +#endif /* SECP256K1_SCALAR_REPR_IMPL_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_impl.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_impl.h new file mode 100644 index 000000000..732d7c854 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_impl.h @@ -0,0 +1,331 @@ +/********************************************************************** + * Copyright (c) 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_IMPL_H +#define SECP256K1_SCALAR_IMPL_H + +#include "group.h" +#include "scalar.h" + +#include "secp256k1-config.h" + +#if defined(EXHAUSTIVE_TEST_ORDER) +#include "scalar_low_impl.h" +#elif defined(USE_SCALAR_4X64) +#include "scalar_4x64_impl.h" +#elif defined(USE_SCALAR_8X32) +#include "scalar_8x32_impl.h" +#else +#error "Please select scalar implementation" +#endif + +#ifndef USE_NUM_NONE +static void secp256k1_scalar_get_num(secp256k1_num *r, const secp256k1_scalar *a) { + unsigned char c[32]; + secp256k1_scalar_get_b32(c, a); + secp256k1_num_set_bin(r, c, 32); +} + +/** secp256k1 curve order, see secp256k1_ecdsa_const_order_as_fe in ecdsa_impl.h */ +static void secp256k1_scalar_order_get_num(secp256k1_num *r) { +#if defined(EXHAUSTIVE_TEST_ORDER) + static const unsigned char order[32] = { + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,EXHAUSTIVE_TEST_ORDER + }; +#else + static const unsigned char order[32] = { + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE, + 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B, + 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x41 + }; +#endif + secp256k1_num_set_bin(r, order, 32); +} +#endif + +static void secp256k1_scalar_inverse(secp256k1_scalar *r, const secp256k1_scalar *x) { +#if defined(EXHAUSTIVE_TEST_ORDER) + int i; + *r = 0; + for (i = 0; i < EXHAUSTIVE_TEST_ORDER; i++) + if ((i * *x) % EXHAUSTIVE_TEST_ORDER == 1) + *r = i; + /* If this VERIFY_CHECK triggers we were given a noninvertible scalar (and thus + * have a composite group order; fix it in exhaustive_tests.c). */ + VERIFY_CHECK(*r != 0); +} +#else + secp256k1_scalar *t; + int i; + /* First compute xN as x ^ (2^N - 1) for some values of N, + * and uM as x ^ M for some values of M. */ + secp256k1_scalar x2, x3, x6, x8, x14, x28, x56, x112, x126; + secp256k1_scalar u2, u5, u9, u11, u13; + + secp256k1_scalar_sqr(&u2, x); + secp256k1_scalar_mul(&x2, &u2, x); + secp256k1_scalar_mul(&u5, &u2, &x2); + secp256k1_scalar_mul(&x3, &u5, &u2); + secp256k1_scalar_mul(&u9, &x3, &u2); + secp256k1_scalar_mul(&u11, &u9, &u2); + secp256k1_scalar_mul(&u13, &u11, &u2); + + secp256k1_scalar_sqr(&x6, &u13); + secp256k1_scalar_sqr(&x6, &x6); + secp256k1_scalar_mul(&x6, &x6, &u11); + + secp256k1_scalar_sqr(&x8, &x6); + secp256k1_scalar_sqr(&x8, &x8); + secp256k1_scalar_mul(&x8, &x8, &x2); + + secp256k1_scalar_sqr(&x14, &x8); + for (i = 0; i < 5; i++) { + secp256k1_scalar_sqr(&x14, &x14); + } + secp256k1_scalar_mul(&x14, &x14, &x6); + + secp256k1_scalar_sqr(&x28, &x14); + for (i = 0; i < 13; i++) { + secp256k1_scalar_sqr(&x28, &x28); + } + secp256k1_scalar_mul(&x28, &x28, &x14); + + secp256k1_scalar_sqr(&x56, &x28); + for (i = 0; i < 27; i++) { + secp256k1_scalar_sqr(&x56, &x56); + } + secp256k1_scalar_mul(&x56, &x56, &x28); + + secp256k1_scalar_sqr(&x112, &x56); + for (i = 0; i < 55; i++) { + secp256k1_scalar_sqr(&x112, &x112); + } + secp256k1_scalar_mul(&x112, &x112, &x56); + + secp256k1_scalar_sqr(&x126, &x112); + for (i = 0; i < 13; i++) { + secp256k1_scalar_sqr(&x126, &x126); + } + secp256k1_scalar_mul(&x126, &x126, &x14); + + /* Then accumulate the final result (t starts at x126). */ + t = &x126; + for (i = 0; i < 3; i++) { + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u5); /* 101 */ + for (i = 0; i < 4; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &x3); /* 111 */ + for (i = 0; i < 4; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u5); /* 101 */ + for (i = 0; i < 5; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u11); /* 1011 */ + for (i = 0; i < 4; i++) { + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u11); /* 1011 */ + for (i = 0; i < 4; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &x3); /* 111 */ + for (i = 0; i < 5; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &x3); /* 111 */ + for (i = 0; i < 6; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u13); /* 1101 */ + for (i = 0; i < 4; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u5); /* 101 */ + for (i = 0; i < 3; i++) { + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &x3); /* 111 */ + for (i = 0; i < 5; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u9); /* 1001 */ + for (i = 0; i < 6; i++) { /* 000 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u5); /* 101 */ + for (i = 0; i < 10; i++) { /* 0000000 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &x3); /* 111 */ + for (i = 0; i < 4; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &x3); /* 111 */ + for (i = 0; i < 9; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &x8); /* 11111111 */ + for (i = 0; i < 5; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u9); /* 1001 */ + for (i = 0; i < 6; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u11); /* 1011 */ + for (i = 0; i < 4; i++) { + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u13); /* 1101 */ + for (i = 0; i < 5; i++) { + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &x2); /* 11 */ + for (i = 0; i < 6; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u13); /* 1101 */ + for (i = 0; i < 10; i++) { /* 000000 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u13); /* 1101 */ + for (i = 0; i < 4; i++) { + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, &u9); /* 1001 */ + for (i = 0; i < 6; i++) { /* 00000 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(t, t, x); /* 1 */ + for (i = 0; i < 8; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); + } + secp256k1_scalar_mul(r, t, &x6); /* 111111 */ +} + +SECP256K1_INLINE static int secp256k1_scalar_is_even(const secp256k1_scalar *a) { + return !(a->d[0] & 1); +} +#endif + +static void secp256k1_scalar_inverse_var(secp256k1_scalar *r, const secp256k1_scalar *x) { +#if defined(USE_SCALAR_INV_BUILTIN) + secp256k1_scalar_inverse(r, x); +#elif defined(USE_SCALAR_INV_NUM) + unsigned char b[32]; + secp256k1_num n, m; + secp256k1_scalar t = *x; + secp256k1_scalar_get_b32(b, &t); + secp256k1_num_set_bin(&n, b, 32); + secp256k1_scalar_order_get_num(&m); + secp256k1_num_mod_inverse(&n, &n, &m); + secp256k1_num_get_bin(b, 32, &n); + secp256k1_scalar_set_b32(r, b, NULL); + /* Verify that the inverse was computed correctly, without GMP code. */ + secp256k1_scalar_mul(&t, &t, r); + CHECK(secp256k1_scalar_is_one(&t)); +#else +#error "Please select scalar inverse implementation" +#endif +} + +#ifdef USE_ENDOMORPHISM +#if defined(EXHAUSTIVE_TEST_ORDER) +/** + * Find k1 and k2 given k, such that k1 + k2 * lambda == k mod n; unlike in the + * full case we don't bother making k1 and k2 be small, we just want them to be + * nontrivial to get full test coverage for the exhaustive tests. We therefore + * (arbitrarily) set k2 = k + 5 and k1 = k - k2 * lambda. + */ +static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { + *r2 = (*a + 5) % EXHAUSTIVE_TEST_ORDER; + *r1 = (*a + (EXHAUSTIVE_TEST_ORDER - *r2) * EXHAUSTIVE_TEST_LAMBDA) % EXHAUSTIVE_TEST_ORDER; +} +#else +/** + * The Secp256k1 curve has an endomorphism, where lambda * (x, y) = (beta * x, y), where + * lambda is {0x53,0x63,0xad,0x4c,0xc0,0x5c,0x30,0xe0,0xa5,0x26,0x1c,0x02,0x88,0x12,0x64,0x5a, + * 0x12,0x2e,0x22,0xea,0x20,0x81,0x66,0x78,0xdf,0x02,0x96,0x7c,0x1b,0x23,0xbd,0x72} + * + * "Guide to Elliptic Curve Cryptography" (Hankerson, Menezes, Vanstone) gives an algorithm + * (algorithm 3.74) to find k1 and k2 given k, such that k1 + k2 * lambda == k mod n, and k1 + * and k2 have a small size. + * It relies on constants a1, b1, a2, b2. These constants for the value of lambda above are: + * + * - a1 = {0x30,0x86,0xd2,0x21,0xa7,0xd4,0x6b,0xcd,0xe8,0x6c,0x90,0xe4,0x92,0x84,0xeb,0x15} + * - b1 = -{0xe4,0x43,0x7e,0xd6,0x01,0x0e,0x88,0x28,0x6f,0x54,0x7f,0xa9,0x0a,0xbf,0xe4,0xc3} + * - a2 = {0x01,0x14,0xca,0x50,0xf7,0xa8,0xe2,0xf3,0xf6,0x57,0xc1,0x10,0x8d,0x9d,0x44,0xcf,0xd8} + * - b2 = {0x30,0x86,0xd2,0x21,0xa7,0xd4,0x6b,0xcd,0xe8,0x6c,0x90,0xe4,0x92,0x84,0xeb,0x15} + * + * The algorithm then computes c1 = round(b1 * k / n) and c2 = round(b2 * k / n), and gives + * k1 = k - (c1*a1 + c2*a2) and k2 = -(c1*b1 + c2*b2). Instead, we use modular arithmetic, and + * compute k1 as k - k2 * lambda, avoiding the need for constants a1 and a2. + * + * g1, g2 are precomputed constants used to replace division with a rounded multiplication + * when decomposing the scalar for an endomorphism-based point multiplication. + * + * The possibility of using precomputed estimates is mentioned in "Guide to Elliptic Curve + * Cryptography" (Hankerson, Menezes, Vanstone) in section 3.5. + * + * The derivation is described in the paper "Efficient Software Implementation of Public-Key + * Cryptography on Sensor Networks Using the MSP430X Microcontroller" (Gouvea, Oliveira, Lopez), + * Section 4.3 (here we use a somewhat higher-precision estimate): + * d = a1*b2 - b1*a2 + * g1 = round((2^272)*b2/d) + * g2 = round((2^272)*b1/d) + * + * (Note that 'd' is also equal to the curve order here because [a1,b1] and [a2,b2] are found + * as outputs of the Extended Euclidean Algorithm on inputs 'order' and 'lambda'). + * + * The function below splits a in r1 and r2, such that r1 + lambda * r2 == a (mod order). + */ + +static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { + secp256k1_scalar c1, c2; + static const secp256k1_scalar minus_lambda = SECP256K1_SCALAR_CONST( + 0xAC9C52B3UL, 0x3FA3CF1FUL, 0x5AD9E3FDUL, 0x77ED9BA4UL, + 0xA880B9FCUL, 0x8EC739C2UL, 0xE0CFC810UL, 0xB51283CFUL + ); + static const secp256k1_scalar minus_b1 = SECP256K1_SCALAR_CONST( + 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x00000000UL, + 0xE4437ED6UL, 0x010E8828UL, 0x6F547FA9UL, 0x0ABFE4C3UL + ); + static const secp256k1_scalar minus_b2 = SECP256K1_SCALAR_CONST( + 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFEUL, + 0x8A280AC5UL, 0x0774346DUL, 0xD765CDA8UL, 0x3DB1562CUL + ); + static const secp256k1_scalar g1 = SECP256K1_SCALAR_CONST( + 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x00003086UL, + 0xD221A7D4UL, 0x6BCDE86CUL, 0x90E49284UL, 0xEB153DABUL + ); + static const secp256k1_scalar g2 = SECP256K1_SCALAR_CONST( + 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x0000E443UL, + 0x7ED6010EUL, 0x88286F54UL, 0x7FA90ABFUL, 0xE4C42212UL + ); + VERIFY_CHECK(r1 != a); + VERIFY_CHECK(r2 != a); + /* these _var calls are constant time since the shift amount is constant */ + secp256k1_scalar_mul_shift_var(&c1, a, &g1, 272); + secp256k1_scalar_mul_shift_var(&c2, a, &g2, 272); + secp256k1_scalar_mul(&c1, &c1, &minus_b1); + secp256k1_scalar_mul(&c2, &c2, &minus_b2); + secp256k1_scalar_add(r2, &c1, &c2); + secp256k1_scalar_mul(r1, r2, &minus_lambda); + secp256k1_scalar_add(r1, r1, a); +} +#endif +#endif + +#endif /* SECP256K1_SCALAR_IMPL_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_low.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_low.h new file mode 100644 index 000000000..5836febc5 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_low.h @@ -0,0 +1,15 @@ +/********************************************************************** + * Copyright (c) 2015 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_REPR_H +#define SECP256K1_SCALAR_REPR_H + +#include + +/** A scalar modulo the group order of the secp256k1 curve. */ +typedef uint32_t secp256k1_scalar; + +#endif /* SECP256K1_SCALAR_REPR_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_low_impl.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_low_impl.h new file mode 100644 index 000000000..c80e70c5a --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scalar_low_impl.h @@ -0,0 +1,114 @@ +/********************************************************************** + * Copyright (c) 2015 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_REPR_IMPL_H +#define SECP256K1_SCALAR_REPR_IMPL_H + +#include "scalar.h" + +#include + +SECP256K1_INLINE static int secp256k1_scalar_is_even(const secp256k1_scalar *a) { + return !(*a & 1); +} + +SECP256K1_INLINE static void secp256k1_scalar_clear(secp256k1_scalar *r) { *r = 0; } +SECP256K1_INLINE static void secp256k1_scalar_set_int(secp256k1_scalar *r, unsigned int v) { *r = v; } + +SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits(const secp256k1_scalar *a, unsigned int offset, unsigned int count) { + if (offset < 32) + return ((*a >> offset) & ((((uint32_t)1) << count) - 1)); + else + return 0; +} + +SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits_var(const secp256k1_scalar *a, unsigned int offset, unsigned int count) { + return secp256k1_scalar_get_bits(a, offset, count); +} + +SECP256K1_INLINE static int secp256k1_scalar_check_overflow(const secp256k1_scalar *a) { return *a >= EXHAUSTIVE_TEST_ORDER; } + +static int secp256k1_scalar_add(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b) { + *r = (*a + *b) % EXHAUSTIVE_TEST_ORDER; + return *r < *b; +} + +static void secp256k1_scalar_cadd_bit(secp256k1_scalar *r, unsigned int bit, int flag) { + if (flag && bit < 32) + *r += (1 << bit); +#ifdef VERIFY + VERIFY_CHECK(secp256k1_scalar_check_overflow(r) == 0); +#endif +} + +static void secp256k1_scalar_set_b32(secp256k1_scalar *r, const unsigned char *b32, int *overflow) { + const int base = 0x100 % EXHAUSTIVE_TEST_ORDER; + int i; + *r = 0; + for (i = 0; i < 32; i++) { + *r = ((*r * base) + b32[i]) % EXHAUSTIVE_TEST_ORDER; + } + /* just deny overflow, it basically always happens */ + if (overflow) *overflow = 0; +} + +static void secp256k1_scalar_get_b32(unsigned char *bin, const secp256k1_scalar* a) { + memset(bin, 0, 32); + bin[28] = *a >> 24; bin[29] = *a >> 16; bin[30] = *a >> 8; bin[31] = *a; +} + +SECP256K1_INLINE static int secp256k1_scalar_is_zero(const secp256k1_scalar *a) { + return *a == 0; +} + +static void secp256k1_scalar_negate(secp256k1_scalar *r, const secp256k1_scalar *a) { + if (*a == 0) { + *r = 0; + } else { + *r = EXHAUSTIVE_TEST_ORDER - *a; + } +} + +SECP256K1_INLINE static int secp256k1_scalar_is_one(const secp256k1_scalar *a) { + return *a == 1; +} + +static int secp256k1_scalar_is_high(const secp256k1_scalar *a) { + return *a > EXHAUSTIVE_TEST_ORDER / 2; +} + +static int secp256k1_scalar_cond_negate(secp256k1_scalar *r, int flag) { + if (flag) secp256k1_scalar_negate(r, r); + return flag ? -1 : 1; +} + +static void secp256k1_scalar_mul(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b) { + *r = (*a * *b) % EXHAUSTIVE_TEST_ORDER; +} + +static int secp256k1_scalar_shr_int(secp256k1_scalar *r, int n) { + int ret; + VERIFY_CHECK(n > 0); + VERIFY_CHECK(n < 16); + ret = *r & ((1 << n) - 1); + *r >>= n; + return ret; +} + +static void secp256k1_scalar_sqr(secp256k1_scalar *r, const secp256k1_scalar *a) { + *r = (*a * *a) % EXHAUSTIVE_TEST_ORDER; +} + +static void secp256k1_scalar_split_128(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { + *r1 = *a; + *r2 = 0; +} + +SECP256K1_INLINE static int secp256k1_scalar_eq(const secp256k1_scalar *a, const secp256k1_scalar *b) { + return *a == *b; +} + +#endif /* SECP256K1_SCALAR_REPR_IMPL_H */ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scratch.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scratch.h new file mode 100644 index 000000000..fef377af0 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scratch.h @@ -0,0 +1,39 @@ +/********************************************************************** + * Copyright (c) 2017 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef _SECP256K1_SCRATCH_ +#define _SECP256K1_SCRATCH_ + +#define SECP256K1_SCRATCH_MAX_FRAMES 5 + +/* The typedef is used internally; the struct name is used in the public API + * (where it is exposed as a different typedef) */ +typedef struct secp256k1_scratch_space_struct { + void *data[SECP256K1_SCRATCH_MAX_FRAMES]; + size_t offset[SECP256K1_SCRATCH_MAX_FRAMES]; + size_t frame_size[SECP256K1_SCRATCH_MAX_FRAMES]; + size_t frame; + size_t max_size; + const secp256k1_callback* error_callback; +} secp256k1_scratch; + +static secp256k1_scratch* secp256k1_scratch_create(const secp256k1_callback* error_callback, size_t max_size); + +static void secp256k1_scratch_destroy(secp256k1_scratch* scratch); + +/** Attempts to allocate a new stack frame with `n` available bytes. Returns 1 on success, 0 on failure */ +static int secp256k1_scratch_allocate_frame(secp256k1_scratch* scratch, size_t n, size_t objects); + +/** Deallocates a stack frame */ +static void secp256k1_scratch_deallocate_frame(secp256k1_scratch* scratch); + +/** Returns the maximum allocation the scratch space will allow */ +static size_t secp256k1_scratch_max_allocation(const secp256k1_scratch* scratch, size_t n_objects); + +/** Returns a pointer into the most recently allocated frame, or NULL if there is insufficient available space */ +static void *secp256k1_scratch_alloc(secp256k1_scratch* scratch, size_t n); + +#endif diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scratch_impl.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scratch_impl.h new file mode 100644 index 000000000..abed713b2 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/scratch_impl.h @@ -0,0 +1,86 @@ +/********************************************************************** + * Copyright (c) 2017 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef _SECP256K1_SCRATCH_IMPL_H_ +#define _SECP256K1_SCRATCH_IMPL_H_ + +#include "scratch.h" + +/* Using 16 bytes alignment because common architectures never have alignment + * requirements above 8 for any of the types we care about. In addition we + * leave some room because currently we don't care about a few bytes. + * TODO: Determine this at configure time. */ +#define ALIGNMENT 16 + +static secp256k1_scratch* secp256k1_scratch_create(const secp256k1_callback* error_callback, size_t max_size) { + secp256k1_scratch* ret = (secp256k1_scratch*)checked_malloc(error_callback, sizeof(*ret)); + if (ret != NULL) { + memset(ret, 0, sizeof(*ret)); + ret->max_size = max_size; + ret->error_callback = error_callback; + } + return ret; +} + +static void secp256k1_scratch_destroy(secp256k1_scratch* scratch) { + if (scratch != NULL) { + VERIFY_CHECK(scratch->frame == 0); + free(scratch); + } +} + +static size_t secp256k1_scratch_max_allocation(const secp256k1_scratch* scratch, size_t objects) { + size_t i = 0; + size_t allocated = 0; + for (i = 0; i < scratch->frame; i++) { + allocated += scratch->frame_size[i]; + } + if (scratch->max_size - allocated <= objects * ALIGNMENT) { + return 0; + } + return scratch->max_size - allocated - objects * ALIGNMENT; +} + +static int secp256k1_scratch_allocate_frame(secp256k1_scratch* scratch, size_t n, size_t objects) { + VERIFY_CHECK(scratch->frame < SECP256K1_SCRATCH_MAX_FRAMES); + + if (n <= secp256k1_scratch_max_allocation(scratch, objects)) { + n += objects * ALIGNMENT; + scratch->data[scratch->frame] = checked_malloc(scratch->error_callback, n); + if (scratch->data[scratch->frame] == NULL) { + return 0; + } + scratch->frame_size[scratch->frame] = n; + scratch->offset[scratch->frame] = 0; + scratch->frame++; + return 1; + } else { + return 0; + } +} + +static void secp256k1_scratch_deallocate_frame(secp256k1_scratch* scratch) { + VERIFY_CHECK(scratch->frame > 0); + scratch->frame -= 1; + free(scratch->data[scratch->frame]); +} + +static void *secp256k1_scratch_alloc(secp256k1_scratch* scratch, size_t size) { + void *ret; + size_t frame = scratch->frame - 1; + size = ((size + ALIGNMENT - 1) / ALIGNMENT) * ALIGNMENT; + + if (scratch->frame == 0 || size + scratch->offset[frame] > scratch->frame_size[frame]) { + return NULL; + } + ret = (void *) ((unsigned char *) scratch->data[frame] + scratch->offset[frame]); + memset(ret, 0, size); + scratch->offset[frame] += size; + + return ret; +} + +#endif diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/secp256k1-config.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/secp256k1-config.h new file mode 100644 index 000000000..e22848b5f --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/secp256k1-config.h @@ -0,0 +1,169 @@ +/* src/libsecp256k1-config.h. Generated from libsecp256k1-config.h.in by configure. */ +/* src/libsecp256k1-config.h.in. Generated from configure.ac by autoheader. */ + +#ifndef LIBSECP256K1_CONFIG_H + +#define LIBSECP256K1_CONFIG_H + +#undef USE_BASIC_CONFIG + +/* Define if building universal (internal helper macro) */ +/* #undef AC_APPLE_UNIVERSAL_BUILD */ + +/* Define this symbol to compile out all VERIFY code */ +/* #undef COVERAGE */ + +/* Define this symbol to enable the ECDH module */ +/* #undef ENABLE_MODULE_ECDH */ + +/* Define this symbol to enable the ECDSA pubkey recovery module */ +/* #undef ENABLE_MODULE_RECOVERY */ + +/* Define this symbol if OpenSSL EC functions are available */ +/* #undef ENABLE_OPENSSL_TESTS */ + +/* Define this symbol if __builtin_expect is available */ +#define HAVE_BUILTIN_EXPECT 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_DLFCN_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define this symbol if libcrypto is installed */ +/* #define HAVE_LIBCRYPTO 1 */ + +/* Define this symbol if libgmp is installed */ +/* #define HAVE_LIBGMP 1 */ + +/* Define to 1 if you have the header file. */ +#define HAVE_MEMORY_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UNISTD_H 1 + +/* Define to 1 if the system has the type `__int128'. */ +/* #define HAVE___INT128 1 */ + +/* Define to the sub-directory where libtool stores uninstalled libraries. */ +/* #define LT_OBJDIR ".libs/" */ + +/* Name of package */ +#define PACKAGE "libsecp256k1" + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "libsecp256k1" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "libsecp256k1 0.1" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "libsecp256k1" + +/* Define to the home page for this package. */ +#define PACKAGE_URL "" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "0.1" + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Define this symbol to enable x86_64 assembly optimizations */ +/* #define USE_ASM_X86_64 1 */ + +/* Define this symbol to use a statically generated ecmult table */ +#define USE_ECMULT_STATIC_PRECOMPUTATION 1 + +/* Define this symbol to use endomorphism optimization */ +/* #undef USE_ENDOMORPHISM */ + +/* Define this symbol if an external (non-inline) assembly implementation is + used */ +/* #undef USE_EXTERNAL_ASM */ + +/* Define this symbol to use the FIELD_10X26 implementation */ +/* #undef USE_FIELD_10X26 */ + +/* Define this symbol to use the FIELD_5X52 implementation */ +/* #define USE_FIELD_5X52 1 */ + +/* Define this symbol to use the native field inverse implementation */ +/* #undef USE_FIELD_INV_BUILTIN */ + +/* Define this symbol to use the num-based field inverse implementation */ +/* #define USE_FIELD_INV_NUM 1 */ + +/* Define this symbol to use the gmp implementation for num */ +/* #define USE_NUM_GMP 1 */ + +/* Define this symbol to use no num implementation */ +/* #undef USE_NUM_NONE */ + +/* Define this symbol to use the 4x64 scalar implementation */ +/* #define USE_SCALAR_4X64 1 */ + +/* Define this symbol to use the 8x32 scalar implementation */ +/* #undef USE_SCALAR_8X32 */ + +/* Define this symbol to use the native scalar inverse implementation */ +/* #undef USE_SCALAR_INV_BUILTIN */ + +/* Define this symbol to use the num-based scalar inverse implementation */ +/* #define USE_SCALAR_INV_NUM 1 */ + +/* Version number of package */ +#define VERSION "0.1" + +/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most + significant byte first (like Motorola and SPARC, unlike Intel). */ + +// #if defined AC_APPLE_UNIVERSAL_BUILD +// # if defined __BIG_ENDIAN__ +// # define WORDS_BIGENDIAN 1 +// # endif +// #else +// # ifndef WORDS_BIGENDIAN +// /* # undef WORDS_BIGENDIAN */ +// # endif +// #endif + +/* Extra configuration */ + +#define USE_NUM_NONE 1 +#define USE_FIELD_INV_BUILTIN 1 +#define USE_SCALAR_INV_BUILTIN 1 +#define ENABLE_MODULE_RECOVERY 1 + +#ifdef __LP64__ +#define HAVE___INT128 1 +#define USE_FIELD_5X52 1 +#define USE_SCALAR_4X64 1 +#else +#define USE_FIELD_10X26 1 +#define USE_SCALAR_8X32 1 +#endif + +#endif /*LIBSECP256K1_CONFIG_H*/ diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/secp256k1.c b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/secp256k1.c new file mode 100644 index 000000000..25fd50193 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/secp256k1.c @@ -0,0 +1,597 @@ +/********************************************************************** + * Copyright (c) 2013-2015 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#include "secp256k1.h" + +#include "util.h" +#include "num_impl.h" +#include "field_impl.h" +#include "scalar_impl.h" +#include "group_impl.h" +#include "ecmult_impl.h" +#include "ecmult_const_impl.h" +#include "ecmult_gen_impl.h" +#include "ecdsa_impl.h" +#include "eckey_impl.h" +#include "hash_impl.h" +#include "scratch_impl.h" + +#define ARG_CHECK(cond) do { \ + if (EXPECT(!(cond), 0)) { \ + secp256k1_callback_call(&ctx->illegal_callback, #cond); \ + return 0; \ + } \ +} while(0) + +static void default_illegal_callback_fn(const char* str, void* data) { + (void)data; + fprintf(stderr, "[libsecp256k1] illegal argument: %s\n", str); + abort(); +} + +static const secp256k1_callback default_illegal_callback = { + default_illegal_callback_fn, + NULL +}; + +static void default_error_callback_fn(const char* str, void* data) { + (void)data; + fprintf(stderr, "[libsecp256k1] internal consistency check failed: %s\n", str); + abort(); +} + +static const secp256k1_callback default_error_callback = { + default_error_callback_fn, + NULL +}; + + +struct secp256k1_context_struct { + secp256k1_ecmult_context ecmult_ctx; + secp256k1_ecmult_gen_context ecmult_gen_ctx; + secp256k1_callback illegal_callback; + secp256k1_callback error_callback; +}; + +secp256k1_context* secp256k1_context_create(unsigned int flags) { + secp256k1_context* ret = (secp256k1_context*)checked_malloc(&default_error_callback, sizeof(secp256k1_context)); + ret->illegal_callback = default_illegal_callback; + ret->error_callback = default_error_callback; + + if (EXPECT((flags & SECP256K1_FLAGS_TYPE_MASK) != SECP256K1_FLAGS_TYPE_CONTEXT, 0)) { + secp256k1_callback_call(&ret->illegal_callback, + "Invalid flags"); + free(ret); + return NULL; + } + + secp256k1_ecmult_context_init(&ret->ecmult_ctx); + secp256k1_ecmult_gen_context_init(&ret->ecmult_gen_ctx); + + if (flags & SECP256K1_FLAGS_BIT_CONTEXT_SIGN) { + secp256k1_ecmult_gen_context_build(&ret->ecmult_gen_ctx, &ret->error_callback); + } + if (flags & SECP256K1_FLAGS_BIT_CONTEXT_VERIFY) { + secp256k1_ecmult_context_build(&ret->ecmult_ctx, &ret->error_callback); + } + + return ret; +} + +secp256k1_context* secp256k1_context_clone(const secp256k1_context* ctx) { + secp256k1_context* ret = (secp256k1_context*)checked_malloc(&ctx->error_callback, sizeof(secp256k1_context)); + ret->illegal_callback = ctx->illegal_callback; + ret->error_callback = ctx->error_callback; + secp256k1_ecmult_context_clone(&ret->ecmult_ctx, &ctx->ecmult_ctx, &ctx->error_callback); + secp256k1_ecmult_gen_context_clone(&ret->ecmult_gen_ctx, &ctx->ecmult_gen_ctx, &ctx->error_callback); + return ret; +} + +void secp256k1_context_destroy(secp256k1_context* ctx) { + if (ctx != NULL) { + secp256k1_ecmult_context_clear(&ctx->ecmult_ctx); + secp256k1_ecmult_gen_context_clear(&ctx->ecmult_gen_ctx); + + free(ctx); + } +} + +void secp256k1_context_set_illegal_callback(secp256k1_context* ctx, void (*fun)(const char* message, void* data), const void* data) { + if (fun == NULL) { + fun = default_illegal_callback_fn; + } + ctx->illegal_callback.fn = fun; + ctx->illegal_callback.data = data; +} + +void secp256k1_context_set_error_callback(secp256k1_context* ctx, void (*fun)(const char* message, void* data), const void* data) { + if (fun == NULL) { + fun = default_error_callback_fn; + } + ctx->error_callback.fn = fun; + ctx->error_callback.data = data; +} + +secp256k1_scratch_space* secp256k1_scratch_space_create(const secp256k1_context* ctx, size_t max_size) { + VERIFY_CHECK(ctx != NULL); + return secp256k1_scratch_create(&ctx->error_callback, max_size); +} + +void secp256k1_scratch_space_destroy(secp256k1_scratch_space* scratch) { + secp256k1_scratch_destroy(scratch); +} + +static int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey) { + if (sizeof(secp256k1_ge_storage) == 64) { + /* When the secp256k1_ge_storage type is exactly 64 byte, use its + * representation inside secp256k1_pubkey, as conversion is very fast. + * Note that secp256k1_pubkey_save must use the same representation. */ + secp256k1_ge_storage s; + memcpy(&s, &pubkey->data[0], sizeof(s)); + secp256k1_ge_from_storage(ge, &s); + } else { + /* Otherwise, fall back to 32-byte big endian for X and Y. */ + secp256k1_fe x, y; + secp256k1_fe_set_b32(&x, pubkey->data); + secp256k1_fe_set_b32(&y, pubkey->data + 32); + secp256k1_ge_set_xy(ge, &x, &y); + } + ARG_CHECK(!secp256k1_fe_is_zero(&ge->x)); + return 1; +} + +static void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge) { + if (sizeof(secp256k1_ge_storage) == 64) { + secp256k1_ge_storage s; + secp256k1_ge_to_storage(&s, ge); + memcpy(&pubkey->data[0], &s, sizeof(s)); + } else { + VERIFY_CHECK(!secp256k1_ge_is_infinity(ge)); + secp256k1_fe_normalize_var(&ge->x); + secp256k1_fe_normalize_var(&ge->y); + secp256k1_fe_get_b32(pubkey->data, &ge->x); + secp256k1_fe_get_b32(pubkey->data + 32, &ge->y); + } +} + +int secp256k1_ec_pubkey_parse(const secp256k1_context* ctx, secp256k1_pubkey* pubkey, const unsigned char *input, size_t inputlen) { + secp256k1_ge Q; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(pubkey != NULL); + memset(pubkey, 0, sizeof(*pubkey)); + ARG_CHECK(input != NULL); + if (!secp256k1_eckey_pubkey_parse(&Q, input, inputlen)) { + return 0; + } + secp256k1_pubkey_save(pubkey, &Q); + secp256k1_ge_clear(&Q); + return 1; +} + +int secp256k1_ec_pubkey_serialize(const secp256k1_context* ctx, unsigned char *output, size_t *outputlen, const secp256k1_pubkey* pubkey, unsigned int flags) { + secp256k1_ge Q; + size_t len; + int ret = 0; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(outputlen != NULL); + ARG_CHECK(*outputlen >= ((flags & SECP256K1_FLAGS_BIT_COMPRESSION) ? 33 : 65)); + len = *outputlen; + *outputlen = 0; + ARG_CHECK(output != NULL); + memset(output, 0, len); + ARG_CHECK(pubkey != NULL); + ARG_CHECK((flags & SECP256K1_FLAGS_TYPE_MASK) == SECP256K1_FLAGS_TYPE_COMPRESSION); + if (secp256k1_pubkey_load(ctx, &Q, pubkey)) { + ret = secp256k1_eckey_pubkey_serialize(&Q, output, &len, flags & SECP256K1_FLAGS_BIT_COMPRESSION); + if (ret) { + *outputlen = len; + } + } + return ret; +} + +static void secp256k1_ecdsa_signature_load(const secp256k1_context* ctx, secp256k1_scalar* r, secp256k1_scalar* s, const secp256k1_ecdsa_signature* sig) { + (void)ctx; + if (sizeof(secp256k1_scalar) == 32) { + /* When the secp256k1_scalar type is exactly 32 byte, use its + * representation inside secp256k1_ecdsa_signature, as conversion is very fast. + * Note that secp256k1_ecdsa_signature_save must use the same representation. */ + memcpy(r, &sig->data[0], 32); + memcpy(s, &sig->data[32], 32); + } else { + secp256k1_scalar_set_b32(r, &sig->data[0], NULL); + secp256k1_scalar_set_b32(s, &sig->data[32], NULL); + } +} + +static void secp256k1_ecdsa_signature_save(secp256k1_ecdsa_signature* sig, const secp256k1_scalar* r, const secp256k1_scalar* s) { + if (sizeof(secp256k1_scalar) == 32) { + memcpy(&sig->data[0], r, 32); + memcpy(&sig->data[32], s, 32); + } else { + secp256k1_scalar_get_b32(&sig->data[0], r); + secp256k1_scalar_get_b32(&sig->data[32], s); + } +} + +int secp256k1_ecdsa_signature_parse_der(const secp256k1_context* ctx, secp256k1_ecdsa_signature* sig, const unsigned char *input, size_t inputlen) { + secp256k1_scalar r, s; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(sig != NULL); + ARG_CHECK(input != NULL); + + if (secp256k1_ecdsa_sig_parse(&r, &s, input, inputlen)) { + secp256k1_ecdsa_signature_save(sig, &r, &s); + return 1; + } else { + memset(sig, 0, sizeof(*sig)); + return 0; + } +} + +int secp256k1_ecdsa_signature_parse_compact(const secp256k1_context* ctx, secp256k1_ecdsa_signature* sig, const unsigned char *input64) { + secp256k1_scalar r, s; + int ret = 1; + int overflow = 0; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(sig != NULL); + ARG_CHECK(input64 != NULL); + + secp256k1_scalar_set_b32(&r, &input64[0], &overflow); + ret &= !overflow; + secp256k1_scalar_set_b32(&s, &input64[32], &overflow); + ret &= !overflow; + if (ret) { + secp256k1_ecdsa_signature_save(sig, &r, &s); + } else { + memset(sig, 0, sizeof(*sig)); + } + return ret; +} + +int secp256k1_ecdsa_signature_serialize_der(const secp256k1_context* ctx, unsigned char *output, size_t *outputlen, const secp256k1_ecdsa_signature* sig) { + secp256k1_scalar r, s; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(output != NULL); + ARG_CHECK(outputlen != NULL); + ARG_CHECK(sig != NULL); + + secp256k1_ecdsa_signature_load(ctx, &r, &s, sig); + return secp256k1_ecdsa_sig_serialize(output, outputlen, &r, &s); +} + +int secp256k1_ecdsa_signature_serialize_compact(const secp256k1_context* ctx, unsigned char *output64, const secp256k1_ecdsa_signature* sig) { + secp256k1_scalar r, s; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(output64 != NULL); + ARG_CHECK(sig != NULL); + + secp256k1_ecdsa_signature_load(ctx, &r, &s, sig); + secp256k1_scalar_get_b32(&output64[0], &r); + secp256k1_scalar_get_b32(&output64[32], &s); + return 1; +} + +int secp256k1_ecdsa_signature_normalize(const secp256k1_context* ctx, secp256k1_ecdsa_signature *sigout, const secp256k1_ecdsa_signature *sigin) { + secp256k1_scalar r, s; + int ret = 0; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(sigin != NULL); + + secp256k1_ecdsa_signature_load(ctx, &r, &s, sigin); + ret = secp256k1_scalar_is_high(&s); + if (sigout != NULL) { + if (ret) { + secp256k1_scalar_negate(&s, &s); + } + secp256k1_ecdsa_signature_save(sigout, &r, &s); + } + + return ret; +} + +int secp256k1_ecdsa_verify(const secp256k1_context* ctx, const secp256k1_ecdsa_signature *sig, const unsigned char *msg32, const secp256k1_pubkey *pubkey) { + secp256k1_ge q; + secp256k1_scalar r, s; + secp256k1_scalar m; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_context_is_built(&ctx->ecmult_ctx)); + ARG_CHECK(msg32 != NULL); + ARG_CHECK(sig != NULL); + ARG_CHECK(pubkey != NULL); + + secp256k1_scalar_set_b32(&m, msg32, NULL); + secp256k1_ecdsa_signature_load(ctx, &r, &s, sig); + return (!secp256k1_scalar_is_high(&s) && + secp256k1_pubkey_load(ctx, &q, pubkey) && + secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &r, &s, &q, &m)); +} + +static SECP256K1_INLINE void buffer_append(unsigned char *buf, unsigned int *offset, const void *data, unsigned int len) { + memcpy(buf + *offset, data, len); + *offset += len; +} + +static int nonce_function_rfc6979(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter) { + unsigned char keydata[112]; + unsigned int offset = 0; + secp256k1_rfc6979_hmac_sha256 rng; + unsigned int i; + /* We feed a byte array to the PRNG as input, consisting of: + * - the private key (32 bytes) and message (32 bytes), see RFC 6979 3.2d. + * - optionally 32 extra bytes of data, see RFC 6979 3.6 Additional Data. + * - optionally 16 extra bytes with the algorithm name. + * Because the arguments have distinct fixed lengths it is not possible for + * different argument mixtures to emulate each other and result in the same + * nonces. + */ + buffer_append(keydata, &offset, key32, 32); + buffer_append(keydata, &offset, msg32, 32); + if (data != NULL) { + buffer_append(keydata, &offset, data, 32); + } + if (algo16 != NULL) { + buffer_append(keydata, &offset, algo16, 16); + } + secp256k1_rfc6979_hmac_sha256_initialize(&rng, keydata, offset); + memset(keydata, 0, sizeof(keydata)); + for (i = 0; i <= counter; i++) { + secp256k1_rfc6979_hmac_sha256_generate(&rng, nonce32, 32); + } + secp256k1_rfc6979_hmac_sha256_finalize(&rng); + return 1; +} + +const secp256k1_nonce_function secp256k1_nonce_function_rfc6979 = nonce_function_rfc6979; +const secp256k1_nonce_function secp256k1_nonce_function_default = nonce_function_rfc6979; + +int secp256k1_ecdsa_sign(const secp256k1_context* ctx, secp256k1_ecdsa_signature *signature, const unsigned char *msg32, const unsigned char *seckey, secp256k1_nonce_function noncefp, const void* noncedata) { + secp256k1_scalar r, s; + secp256k1_scalar sec, non, msg; + int ret = 0; + int overflow = 0; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)); + ARG_CHECK(msg32 != NULL); + ARG_CHECK(signature != NULL); + ARG_CHECK(seckey != NULL); + if (noncefp == NULL) { + noncefp = secp256k1_nonce_function_default; + } + + secp256k1_scalar_set_b32(&sec, seckey, &overflow); + /* Fail if the secret key is invalid. */ + if (!overflow && !secp256k1_scalar_is_zero(&sec)) { + unsigned char nonce32[32]; + unsigned int count = 0; + secp256k1_scalar_set_b32(&msg, msg32, NULL); + while (1) { + ret = noncefp(nonce32, msg32, seckey, NULL, (void*)noncedata, count); + if (!ret) { + break; + } + secp256k1_scalar_set_b32(&non, nonce32, &overflow); + if (!overflow && !secp256k1_scalar_is_zero(&non)) { + if (secp256k1_ecdsa_sig_sign(&ctx->ecmult_gen_ctx, &r, &s, &sec, &msg, &non, NULL)) { + break; + } + } + count++; + } + memset(nonce32, 0, 32); + secp256k1_scalar_clear(&msg); + secp256k1_scalar_clear(&non); + secp256k1_scalar_clear(&sec); + } + if (ret) { + secp256k1_ecdsa_signature_save(signature, &r, &s); + } else { + memset(signature, 0, sizeof(*signature)); + } + return ret; +} + +int secp256k1_ec_seckey_verify(const secp256k1_context* ctx, const unsigned char *seckey) { + secp256k1_scalar sec; + int ret; + int overflow; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(seckey != NULL); + + secp256k1_scalar_set_b32(&sec, seckey, &overflow); + ret = !overflow && !secp256k1_scalar_is_zero(&sec); + secp256k1_scalar_clear(&sec); + return ret; +} + +int secp256k1_ec_pubkey_create(const secp256k1_context* ctx, secp256k1_pubkey *pubkey, const unsigned char *seckey) { + secp256k1_gej pj; + secp256k1_ge p; + secp256k1_scalar sec; + int overflow; + int ret = 0; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(pubkey != NULL); + memset(pubkey, 0, sizeof(*pubkey)); + ARG_CHECK(secp256k1_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)); + ARG_CHECK(seckey != NULL); + + secp256k1_scalar_set_b32(&sec, seckey, &overflow); + ret = (!overflow) & (!secp256k1_scalar_is_zero(&sec)); + if (ret) { + secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &pj, &sec); + secp256k1_ge_set_gej(&p, &pj); + secp256k1_pubkey_save(pubkey, &p); + } + secp256k1_scalar_clear(&sec); + return ret; +} + +int secp256k1_ec_privkey_negate(const secp256k1_context* ctx, unsigned char *seckey) { + secp256k1_scalar sec; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(seckey != NULL); + + secp256k1_scalar_set_b32(&sec, seckey, NULL); + secp256k1_scalar_negate(&sec, &sec); + secp256k1_scalar_get_b32(seckey, &sec); + + return 1; +} + +int secp256k1_ec_pubkey_negate(const secp256k1_context* ctx, secp256k1_pubkey *pubkey) { + int ret = 0; + secp256k1_ge p; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(pubkey != NULL); + + ret = secp256k1_pubkey_load(ctx, &p, pubkey); + memset(pubkey, 0, sizeof(*pubkey)); + if (ret) { + secp256k1_ge_neg(&p, &p); + secp256k1_pubkey_save(pubkey, &p); + } + return ret; +} + +int secp256k1_ec_privkey_tweak_add(const secp256k1_context* ctx, unsigned char *seckey, const unsigned char *tweak) { + secp256k1_scalar term; + secp256k1_scalar sec; + int ret = 0; + int overflow = 0; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(seckey != NULL); + ARG_CHECK(tweak != NULL); + + secp256k1_scalar_set_b32(&term, tweak, &overflow); + secp256k1_scalar_set_b32(&sec, seckey, NULL); + + ret = !overflow && secp256k1_eckey_privkey_tweak_add(&sec, &term); + memset(seckey, 0, 32); + if (ret) { + secp256k1_scalar_get_b32(seckey, &sec); + } + + secp256k1_scalar_clear(&sec); + secp256k1_scalar_clear(&term); + return ret; +} + +int secp256k1_ec_pubkey_tweak_add(const secp256k1_context* ctx, secp256k1_pubkey *pubkey, const unsigned char *tweak) { + secp256k1_ge p; + secp256k1_scalar term; + int ret = 0; + int overflow = 0; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_context_is_built(&ctx->ecmult_ctx)); + ARG_CHECK(pubkey != NULL); + ARG_CHECK(tweak != NULL); + + secp256k1_scalar_set_b32(&term, tweak, &overflow); + ret = !overflow && secp256k1_pubkey_load(ctx, &p, pubkey); + memset(pubkey, 0, sizeof(*pubkey)); + if (ret) { + if (secp256k1_eckey_pubkey_tweak_add(&ctx->ecmult_ctx, &p, &term)) { + secp256k1_pubkey_save(pubkey, &p); + } else { + ret = 0; + } + } + + return ret; +} + +int secp256k1_ec_privkey_tweak_mul(const secp256k1_context* ctx, unsigned char *seckey, const unsigned char *tweak) { + secp256k1_scalar factor; + secp256k1_scalar sec; + int ret = 0; + int overflow = 0; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(seckey != NULL); + ARG_CHECK(tweak != NULL); + + secp256k1_scalar_set_b32(&factor, tweak, &overflow); + secp256k1_scalar_set_b32(&sec, seckey, NULL); + ret = !overflow && secp256k1_eckey_privkey_tweak_mul(&sec, &factor); + memset(seckey, 0, 32); + if (ret) { + secp256k1_scalar_get_b32(seckey, &sec); + } + + secp256k1_scalar_clear(&sec); + secp256k1_scalar_clear(&factor); + return ret; +} + +int secp256k1_ec_pubkey_tweak_mul(const secp256k1_context* ctx, secp256k1_pubkey *pubkey, const unsigned char *tweak) { + secp256k1_ge p; + secp256k1_scalar factor; + int ret = 0; + int overflow = 0; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_context_is_built(&ctx->ecmult_ctx)); + ARG_CHECK(pubkey != NULL); + ARG_CHECK(tweak != NULL); + + secp256k1_scalar_set_b32(&factor, tweak, &overflow); + ret = !overflow && secp256k1_pubkey_load(ctx, &p, pubkey); + memset(pubkey, 0, sizeof(*pubkey)); + if (ret) { + if (secp256k1_eckey_pubkey_tweak_mul(&ctx->ecmult_ctx, &p, &factor)) { + secp256k1_pubkey_save(pubkey, &p); + } else { + ret = 0; + } + } + + return ret; +} + +int secp256k1_context_randomize(secp256k1_context* ctx, const unsigned char *seed32) { + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)); + secp256k1_ecmult_gen_blind(&ctx->ecmult_gen_ctx, seed32); + return 1; +} + +int secp256k1_ec_pubkey_combine(const secp256k1_context* ctx, secp256k1_pubkey *pubnonce, const secp256k1_pubkey * const *pubnonces, size_t n) { + size_t i; + secp256k1_gej Qj; + secp256k1_ge Q; + + ARG_CHECK(pubnonce != NULL); + memset(pubnonce, 0, sizeof(*pubnonce)); + ARG_CHECK(n >= 1); + ARG_CHECK(pubnonces != NULL); + + secp256k1_gej_set_infinity(&Qj); + + for (i = 0; i < n; i++) { + secp256k1_pubkey_load(ctx, &Q, pubnonces[i]); + secp256k1_gej_add_ge(&Qj, &Qj, &Q); + } + if (secp256k1_gej_is_infinity(&Qj)) { + return 0; + } + secp256k1_ge_set_gej(&Q, &Qj); + secp256k1_pubkey_save(pubnonce, &Q); + return 1; +} + +#ifdef ENABLE_MODULE_ECDH +# include "ecdh_impl.h" +#endif + +#ifdef ENABLE_MODULE_RECOVERY +# include "recovery_impl.h" +#endif diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/secp256k1_ec_mult_static_context.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/secp256k1_ec_mult_static_context.h new file mode 100644 index 000000000..61d937345 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/secp256k1_ec_mult_static_context.h @@ -0,0 +1,1160 @@ +#ifndef _SECP256K1_ECMULT_STATIC_CONTEXT_ +#define _SECP256K1_ECMULT_STATIC_CONTEXT_ +#include "group.h" +#define SC SECP256K1_GE_STORAGE_CONST +static const secp256k1_ge_storage secp256k1_ecmult_static_context[64][16] = { +{ + SC(983487347u, 1861041900u, 2599115456u, 565528146u, 1451326239u, 148794576u, 4224640328u, 3120843701u, 2076989736u, 3184115747u, 3754320824u, 2656004457u, 2876577688u, 2388659905u, 3527541004u, 1170708298u), + SC(3830281845u, 3284871255u, 1309883393u, 2806991612u, 1558611192u, 1249416977u, 1614773327u, 1353445208u, 633124399u, 4264439010u, 426432620u, 167800352u, 2355417627u, 2991792291u, 3042397084u, 505150283u), + SC(1792710820u, 2165839471u, 3876070801u, 3603801374u, 2437636273u, 1231643248u, 860890267u, 4002236272u, 3258245037u, 4085545079u, 2695347418u, 288209541u, 484302592u, 139267079u, 14621978u, 2750167787u), + SC(11094760u, 1663454715u, 3104893589u, 1290390142u, 1334245677u, 2671416785u, 3982578986u, 2050971459u, 2136209393u, 1792200847u, 367473428u, 114820199u, 1096121039u, 425028623u, 3983611854u, 923011107u), + SC(3063072592u, 3527226996u, 3276923831u, 3785926779u, 346414977u, 2234429237u, 547163845u, 1847763663u, 2978762519u, 623753375u, 2207114031u, 3006533282u, 3147176505u, 1421052999u, 4188545436u, 1210097867u), + SC(1763690305u, 2162645845u, 1202943473u, 469109438u, 1159538654u, 390308918u, 1603161004u, 2906790921u, 2394291613u, 4089459264u, 1827402608u, 2166723935u, 3207526147u, 1197293526u, 436375990u, 1773481373u), + SC(1882939156u, 2815960179u, 295089455u, 2929502411u, 2990911492u, 2056857815u, 3502518067u, 957616604u, 1591168682u, 1240626880u, 1298264859u, 1839469436u, 3185927997u, 2386526557u, 4025121105u, 260593756u), + SC(699984967u, 3527536033u, 3843799838u, 958940236u, 927446270u, 2095887205u, 733758855u, 793790581u, 2288595512u, 2237855935u, 4158071588u, 103726164u, 1804839263u, 2006149890u, 3944535719u, 3558448075u), + SC(1145702317u, 3893958345u, 851308226u, 566580932u, 1803510929u, 244954233u, 754894895u, 1321302288u, 772295727u, 4004336128u, 2009158070u, 4026087258u, 1899732245u, 1392930957u, 3019192545u, 149625039u), + SC(3772604811u, 577564124u, 4116730494u, 548732504u, 241159976u, 965811878u, 3286803623u, 3781136673u, 2690883927u, 863484863u, 463101630u, 2948469162u, 1712070245u, 3742601912u, 2535479384u, 1015456764u), + SC(2610513434u, 780361970u, 4072278968u, 3165566617u, 362677842u, 1775830058u, 4195110448u, 2813784845u, 1072168452u, 1018450691u, 1028609376u, 2101464438u, 2419500187u, 2190549840u, 1837865365u, 625038589u), + SC(1347265449u, 3654928411u, 3255194520u, 1322421425u, 3049188507u, 1827004342u, 3467202132u, 4261348427u, 3419671838u, 2239837129u, 3441474020u, 268041876u, 4157379961u, 971431753u, 2053887746u, 2038404815u), + SC(3723233964u, 515696298u, 2908946645u, 1626400003u, 2191461318u, 1201029625u, 186243574u, 1212380923u, 858781105u, 4236445790u, 1936144063u, 1009147468u, 2407567966u, 1865959325u, 1701035060u, 241151649u), + SC(3696430315u, 3089900654u, 1103438577u, 3528924465u, 1259662835u, 2438429227u, 1692672370u, 2989843137u, 1446894995u, 2239587625u, 2340544036u, 434491102u, 128239031u, 2734594294u, 2667284742u, 1865591178u), + SC(1980028431u, 1099813170u, 2013628738u, 4214038867u, 3231891435u, 3896266769u, 2756820145u, 1490749299u, 951981230u, 3655451652u, 1676645053u, 3593230746u, 3010864552u, 405419875u, 1336073872u, 1398624425u), + SC(3414779716u, 2008156201u, 4125277506u, 2287126283u, 2446053551u, 212726297u, 2794923956u, 3421277562u, 1460719994u, 552209919u, 2551004934u, 953727248u, 3096710400u, 3712627263u, 3614955842u, 557715603u) +}, +{ + SC(461660907u, 483260338u, 3090624303u, 3468817529u, 2869411999u, 3408320195u, 157674611u, 1298485121u, 103769941u, 3030878493u, 1440637991u, 4223892787u, 3840844824u, 2730509202u, 2748389383u, 214732837u), + SC(4143598594u, 459898515u, 2922648667u, 1209678535u, 1176716252u, 1612841999u, 2202917330u, 13015901u, 1575346251u, 891263272u, 3091905261u, 3543244385u, 3935435865u, 2372913859u, 1075649255u, 201888830u), + SC(3481295448u, 3640243220u, 2859715852u, 3846556079u, 1065182531u, 2330293896u, 2178091110u, 3893510868u, 4099261975u, 2577582684u, 4207143791u, 589834100u, 2090766670u, 4242818989u, 2413240316u, 1338191979u), + SC(1222367653u, 2295459885u, 1856816550u, 918616911u, 3733449540u, 288527426u, 308654335u, 175301747u, 2585816357u, 1572985110u, 3820086017u, 3400646033u, 3928615806u, 2543586180u, 1619974000u, 1257448912u), + SC(3467862907u, 681146163u, 2909728989u, 83906098u, 2626131995u, 3872919971u, 2290108548u, 1697087700u, 1793941143u, 3236443826u, 1940064764u, 1563989881u, 527371209u, 610869743u, 1604941439u, 3670721525u), + SC(2302729378u, 1391194029u, 1641771531u, 3876177737u, 1929557473u, 2752989331u, 2519109900u, 1131448856u, 3786463166u, 506905989u, 2345013855u, 2144715811u, 1583628159u, 291930150u, 3243470493u, 4130365181u), + SC(2855519179u, 3147287790u, 1536116015u, 1784764672u, 959281397u, 3099717666u, 86403980u, 3409201632u, 3921301684u, 2101228153u, 575924517u, 1382150904u, 641478876u, 3860064926u, 1937521554u, 2358132463u), + SC(972265053u, 3025511526u, 2467192450u, 4011934802u, 4015820825u, 3179306985u, 1744647725u, 423238442u, 2406064939u, 901607195u, 3316491016u, 4128592049u, 1397491632u, 439641584u, 90500461u, 2834580417u), + SC(1730532518u, 2821193463u, 2700804628u, 2416923244u, 3795632308u, 2799866320u, 3434703577u, 3883111373u, 1777933228u, 2963254493u, 3042948878u, 1746288680u, 2832145340u, 544625602u, 3633879343u, 2300858165u), + SC(62331695u, 2228442612u, 3527845246u, 2989876118u, 3995298903u, 3601545798u, 4170931516u, 445717530u, 1981201926u, 94264130u, 2668647577u, 953251412u, 3322279962u, 3837653687u, 3116466555u, 3369796531u), + SC(2739333573u, 3637259489u, 443756582u, 825678124u, 2455706402u, 2994548791u, 3653546249u, 2584145078u, 1245698352u, 89066746u, 1738138166u, 2916153640u, 1850062717u, 3472193431u, 2110631011u, 1214009088u), + SC(2386327178u, 3993497770u, 1051345891u, 4137183237u, 3078790224u, 3598213568u, 3344610192u, 1517270932u, 869515922u, 2057215060u, 2792454282u, 4228826509u, 3425305972u, 2708629086u, 880185559u, 1356729037u), + SC(2989561710u, 3550122639u, 1990591383u, 2036612756u, 3588709655u, 595888062u, 4189293408u, 1955008963u, 987876526u, 542093629u, 1953520395u, 2315684331u, 2929815182u, 3270759899u, 393611756u, 1677885197u), + SC(2331762734u, 371120497u, 1141333410u, 3466824114u, 4113916626u, 3698793791u, 2483365276u, 4265751258u, 3804325409u, 4085909553u, 3531838853u, 2629626707u, 625187055u, 3045263564u, 198131065u, 3993694760u), + SC(27419592u, 3267954699u, 2966738458u, 3143461717u, 3869766944u, 2163162934u, 1886283869u, 2052225367u, 958768216u, 2006727717u, 2069130137u, 1939449196u, 3015752138u, 258766841u, 3290132621u, 4163970366u), + SC(903383785u, 2983456345u, 4269392462u, 3731664159u, 1837248343u, 1888413004u, 652691803u, 897487558u, 3732206419u, 3625013640u, 1917594162u, 967935585u, 1804564817u, 883883125u, 2389854768u, 2347234078u) +}, +{ + SC(1793692126u, 406948681u, 23075151u, 2805328754u, 3264854407u, 427926777u, 2859563730u, 198037267u, 2129133850u, 1089701106u, 3842694445u, 2533380467u, 663211132u, 2312829798u, 807127373u, 38506815u), + SC(571890638u, 3882751380u, 1536180709u, 3437159763u, 3953528399u, 516828575u, 3769463872u, 1449076325u, 4270798907u, 3135758980u, 3520630973u, 1452980147u, 3957715387u, 3054428574u, 2391664223u, 2297670550u), + SC(2724204046u, 2456139736u, 265045669u, 1367810338u, 1722635060u, 1306450931u, 2894913322u, 3094293390u, 3490680992u, 2550020195u, 3028635086u, 4200216295u, 1066664286u, 4170330175u, 777827015u, 183484181u), + SC(947228665u, 1559209921u, 3080864826u, 3123295835u, 2934045313u, 1590990229u, 2766960143u, 3113606941u, 1136432319u, 3758046297u, 2054046144u, 1377389889u, 3244301201u, 127071274u, 1752358610u, 2783507663u), + SC(1460807831u, 3649051054u, 2799484569u, 1231562901u, 3377754600u, 3577118892u, 1234337315u, 380370215u, 3272388869u, 3656237932u, 2653126291u, 786263023u, 1028996455u, 4274234235u, 4225822550u, 10734444u), + SC(2071087047u, 1934036755u, 611830132u, 2015415885u, 1373497691u, 3709112893u, 3810392851u, 1519037663u, 779113716u, 2738053543u, 2754096050u, 2121500804u, 982626833u, 1064427872u, 1627071029u, 1799421889u), + SC(490669665u, 331510235u, 927653097u, 4010558541u, 1341899186u, 2739641489u, 1436050289u, 1379364712u, 441190387u, 3816107121u, 4151493979u, 3530159022u, 2848669857u, 2894763699u, 1938279708u, 3206735972u), + SC(1164630680u, 735028522u, 1426163473u, 1764145219u, 2188722839u, 2599797011u, 2331123230u, 996298865u, 2803113036u, 1732133918u, 4135374745u, 1403496102u, 61305906u, 1982207767u, 35608603u, 680731708u), + SC(3097030574u, 2239944926u, 3004506636u, 3698971324u, 438440050u, 806226289u, 3299217652u, 2137747676u, 2376642592u, 2372355096u, 1444993877u, 4198291752u, 3194432604u, 579432496u, 3143260503u, 58153128u), + SC(3073570790u, 2457870973u, 3254087300u, 132589961u, 3090464363u, 4031655485u, 3397735349u, 3738272915u, 2438408586u, 1610016484u, 3607490511u, 1979839295u, 1993157220u, 1628966973u, 2566520843u, 2415504793u), + SC(2516700697u, 2521039798u, 2777488721u, 3196543385u, 3593950703u, 2445108602u, 4227515375u, 3361503440u, 3741757104u, 1367007706u, 4282009789u, 2127358709u, 2970274265u, 108953332u, 1376097231u, 3612352600u), + SC(2841122028u, 289695603u, 908429972u, 1449591303u, 3496532142u, 430811028u, 1377898285u, 198605765u, 702014643u, 1582973696u, 1654127041u, 4145703462u, 294032334u, 4235431914u, 3438393459u, 865474483u), + SC(3545445168u, 3333415739u, 2928811023u, 1435493501u, 3112072977u, 3466119300u, 61597844u, 839813414u, 3787328278u, 1928915478u, 3046796186u, 549615137u, 3862451403u, 1325262296u, 3520760105u, 1333228419u), + SC(1325790793u, 3907821545u, 4134901119u, 1951705246u, 3223387882u, 561480379u, 1136389443u, 2963679361u, 3722857515u, 626885912u, 3665060294u, 2975869036u, 1378007717u, 1212143055u, 3672021732u, 2520983812u), + SC(436660944u, 1593040065u, 2835874356u, 3054866405u, 1746716106u, 2901130226u, 3275156703u, 889550475u, 1667636846u, 2171317649u, 477876339u, 169193861u, 3301423024u, 2923695575u, 1084572294u, 981889567u), + SC(3803276281u, 4055280968u, 3904809427u, 186227966u, 932166956u, 2399165660u, 3851784532u, 3001852135u, 813014380u, 4116676373u, 2706810629u, 527442580u, 120296772u, 3128162880u, 662936789u, 1729392771u) +}, +{ + SC(1686440452u, 1988561476u, 754604000u, 1313277943u, 3972816537u, 316394247u, 994407191u, 1904170630u, 2086644946u, 2443632379u, 2709748921u, 1003213045u, 3157743406u, 1758245536u, 3227689301u, 1181052876u), + SC(1258105424u, 4154135555u, 2219123623u, 3901620566u, 4152326230u, 2255006844u, 2043811343u, 3401743053u, 1077175625u, 4217078864u, 23446180u, 3296093630u, 2983403379u, 483875022u, 1821322007u, 933769937u), + SC(4094896192u, 2631249021u, 2047644402u, 1580854103u, 3103587285u, 3577080832u, 2726417365u, 309664155u, 1801899606u, 2578001137u, 150353312u, 1950478529u, 895600852u, 3405805048u, 2316670682u, 3067768105u), + SC(443311827u, 441757202u, 1505167796u, 3339695156u, 4080303377u, 2032258566u, 4249816510u, 3524388084u, 3057881006u, 1951550910u, 755229308u, 2331249069u, 1739558582u, 2222328965u, 511821487u, 2764767310u), + SC(989753134u, 2338266356u, 549068233u, 4113024610u, 2746193091u, 2634969710u, 3079940655u, 3384912157u, 143838693u, 4047635856u, 4286586687u, 149695182u, 1777393012u, 52209639u, 2932952119u, 3267437714u), + SC(682610480u, 2717190045u, 3874701500u, 2657184992u, 2055845501u, 1316949440u, 1867841182u, 3514766617u, 3083609836u, 2586162565u, 866399081u, 1085717952u, 3259379257u, 575055971u, 3866877694u, 451222497u), + SC(328731030u, 2942825188u, 1841689481u, 3492191519u, 967390237u, 99172838u, 3036642267u, 3931425637u, 933459735u, 3523655044u, 2662830483u, 2533317360u, 1151283556u, 1285468956u, 15891850u, 3194406721u), + SC(3082245252u, 2305218459u, 2853219703u, 1279555698u, 3695999195u, 2225441691u, 2702374346u, 2002979755u, 3394310641u, 1438568303u, 441738339u, 2319547123u, 745721770u, 3663132780u, 3613740038u, 3163545587u), + SC(3109530474u, 209548946u, 1705898345u, 1227555051u, 1300903197u, 521706788u, 1046889791u, 392785355u, 1195852439u, 1128202903u, 589172095u, 3844020294u, 989062243u, 3765536158u, 3601935109u, 563198009u), + SC(1408383323u, 2941773350u, 4185382573u, 3662857379u, 4172908289u, 4118722458u, 1935569844u, 1296819381u, 439467796u, 917888253u, 1573015538u, 2875181025u, 22626495u, 313409715u, 121133518u, 1579603291u), + SC(838355261u, 2323744266u, 929233883u, 1533162328u, 2939669145u, 1021427197u, 2448693967u, 1568998094u, 455286333u, 2516902543u, 1708158744u, 278073872u, 978123683u, 2512836694u, 3972232382u, 1433020779u), + SC(2010810703u, 4018381427u, 571706262u, 1692351234u, 4256546562u, 1231266051u, 268479287u, 2820752911u, 2261632188u, 845795375u, 3555293251u, 4247559674u, 3383569817u, 4149228066u, 180667610u, 1402241180u), + SC(3525485702u, 3451430050u, 2349871300u, 60510511u, 4165534527u, 3431222792u, 4244473672u, 526926602u, 763199050u, 672899723u, 1978849638u, 489006191u, 1575850086u, 1948428588u, 201110001u, 2038136322u), + SC(3829603224u, 567257667u, 2324557421u, 3080821304u, 1922441927u, 1741539649u, 2023385976u, 3349327437u, 1997432110u, 3734074051u, 1330703636u, 3180299184u, 1913578229u, 141656008u, 2692604045u, 1602929664u), + SC(29051889u, 27392875u, 2013870801u, 1608859787u, 4192290684u, 944038467u, 2706126772u, 4086572363u, 3654238115u, 631287070u, 4277765317u, 2361271762u, 4170133585u, 2022489410u, 2834765713u, 1378478404u), + SC(2835113470u, 3839837803u, 3596950757u, 2129670392u, 1881028173u, 4057879348u, 2459142230u, 3736551989u, 3032996358u, 1333513239u, 3006303259u, 3885122327u, 4228039994u, 134788219u, 3631677646u, 450886807u) +}, +{ + SC(2450731413u, 2768047193u, 2114778718u, 2363611449u, 3811833768u, 1142236074u, 836975073u, 719658637u, 89564040u, 2055034782u, 2279505737u, 2354364196u, 748992674u, 2341838369u, 3471590741u, 3103440079u), + SC(464369172u, 1784969737u, 2303680721u, 1699015058u, 1839678160u, 53342253u, 3929309179u, 3713202491u, 1764215120u, 2190365769u, 3137266333u, 3919018972u, 3446276485u, 1027535494u, 3649392538u, 1979045036u), + SC(3689697965u, 1535268856u, 4095087266u, 1879342666u, 1901613989u, 4062220771u, 1231692686u, 3479254943u, 517178359u, 3704348661u, 3200159500u, 592930780u, 3995209641u, 2367381241u, 1790597847u, 2276745810u), + SC(1563410665u, 2779883331u, 320555798u, 143478861u, 1984047202u, 2486036480u, 1819096593u, 876845470u, 4160262809u, 1685665332u, 1096211683u, 3396846267u, 1079209808u, 1622135728u, 2746449213u, 2258485533u), + SC(1981422448u, 2212169687u, 873443773u, 3576733408u, 3923794933u, 1875069523u, 3053667173u, 4292418240u, 2192702144u, 1027092432u, 278807989u, 2315740043u, 485097259u, 4099751129u, 1350843241u, 1137138810u), + SC(3929635582u, 2647315129u, 1255145681u, 2059161179u, 1939751218u, 2574940312u, 1013734441u, 3958841903u, 615021475u, 1092396560u, 1516857705u, 4167743313u, 744612233u, 1609870616u, 1905505775u, 2106400820u), + SC(1036005687u, 2272703162u, 2208830030u, 2182996589u, 441615709u, 3591433922u, 3586649797u, 164179585u, 3077875769u, 1792522157u, 2657252843u, 657567108u, 656390324u, 1816007391u, 3075467586u, 3873231707u), + SC(1236896749u, 2895887291u, 1978987518u, 822801819u, 516389325u, 1102535042u, 1787993035u, 3557481093u, 3231661433u, 991180576u, 3686912074u, 1297456949u, 3327185778u, 308709174u, 495078044u, 2969592590u), + SC(2019907021u, 744703189u, 2139199843u, 518542186u, 3124680574u, 142934434u, 551498542u, 3021773546u, 4091561632u, 1051317147u, 825719313u, 3707224763u, 335483791u, 4028731434u, 1335000639u, 4102709448u), + SC(1093818871u, 985937516u, 327542691u, 2046117782u, 1264752065u, 697293694u, 1615263505u, 1156460629u, 2812684388u, 1192736815u, 3019618111u, 4209127823u, 2556369187u, 2112950523u, 637809851u, 2176824541u), + SC(1687299893u, 3728297084u, 490922479u, 3634470646u, 250826345u, 3692215527u, 3273717576u, 965983458u, 2226919381u, 1460789800u, 2122435754u, 2519058236u, 1620196106u, 4066817802u, 1130044433u, 3889340415u), + SC(852530522u, 3312783835u, 1596416107u, 1741549460u, 2684468674u, 3424816114u, 2501858342u, 1775689041u, 2140910620u, 3593295971u, 3269455071u, 2386348485u, 3506744308u, 1454965514u, 1429132807u, 1936823584u), + SC(606602909u, 3019871883u, 3512048756u, 3287518999u, 3877975051u, 3914786486u, 3870177904u, 1340649290u, 520571284u, 3028797996u, 2616337132u, 1103844529u, 3133726039u, 1357152000u, 1508799653u, 31330228u), + SC(2817743510u, 2877820134u, 3034826170u, 1694674814u, 3472934533u, 2992700940u, 940570741u, 734740020u, 2101869811u, 3976806699u, 3986671415u, 556491401u, 2336314226u, 3375597171u, 2706276162u, 2068498899u), + SC(2875346415u, 3996130283u, 2530370154u, 2292821435u, 1717542531u, 4166402291u, 2045046397u, 210928306u, 1305773764u, 891667924u, 1720475570u, 2097400197u, 3748242244u, 1645769622u, 3986372109u, 4259524466u), + SC(258680563u, 3407077353u, 3701760456u, 1531445568u, 3746171918u, 2983392727u, 1490964851u, 3947644742u, 2779475335u, 3867487462u, 2573576052u, 3434694262u, 2755711440u, 3366989652u, 566303708u, 3091229946u) +}, +{ + SC(2925506593u, 3911544000u, 1647760999u, 3077282783u, 810174083u, 3532746750u, 1218244633u, 1800164995u, 3882366571u, 1552758454u, 417617232u, 3581187042u, 1107218813u, 308444727u, 2996521844u, 3546298006u), + SC(2766498247u, 1567718891u, 906631353u, 1539374134u, 2937267715u, 3075423755u, 466239025u, 348294756u, 2802746156u, 3822638356u, 2215866298u, 2676073175u, 2327206803u, 3701444736u, 533673746u, 1949565232u), + SC(779912645u, 2120746348u, 3775586707u, 1719694388u, 3225985094u, 1124933767u, 2466028289u, 3688916232u, 2352972448u, 3100332066u, 3699049642u, 105143046u, 3528587757u, 3202351686u, 3275195870u, 2542878955u), + SC(4208701680u, 3032319563u, 1934783333u, 1683344422u, 1898255641u, 1818484420u, 1090856325u, 4203146066u, 3166734039u, 1425051511u, 411614967u, 1272168350u, 905464202u, 2860309946u, 2899721999u, 4016531256u), + SC(1252276677u, 705548877u, 3321309972u, 2587486609u, 1841091772u, 1176108340u, 2483104333u, 1124739854u, 1417860124u, 2145011089u, 1095816787u, 561231448u, 3047186502u, 2188442748u, 782343512u, 2073487869u), + SC(773625401u, 1399854511u, 2112273744u, 3798562401u, 2328245221u, 4053035765u, 884849756u, 2543299151u, 3064173848u, 3322400978u, 2493736578u, 4109781307u, 3356431908u, 2033183790u, 3916558464u, 937192909u), + SC(1676839026u, 1837563838u, 681907940u, 1979087218u, 3861274680u, 1004821519u, 3526269549u, 3587326189u, 4130121750u, 5876755u, 277168273u, 3347389376u, 1295078502u, 3055055655u, 988901279u, 1750695367u), + SC(1466696987u, 793586382u, 3395028606u, 688541023u, 227515247u, 433349930u, 1151320534u, 2638968365u, 2730052118u, 2419949779u, 4184196159u, 3075595332u, 1762597117u, 3208522231u, 3793454426u, 2205574333u), + SC(2271935805u, 2221340650u, 4006866556u, 3892925071u, 3300102857u, 4023132062u, 1966820825u, 193229358u, 3829742367u, 3288127030u, 2999566231u, 1746318860u, 611198282u, 1740582489u, 586692015u, 272371975u), + SC(1512874083u, 1683202061u, 3100471136u, 875884760u, 2252521753u, 3056609126u, 2397470151u, 3238829627u, 398340158u, 1086173909u, 2650682699u, 3851040891u, 267796754u, 1063916466u, 134772391u, 616879617u), + SC(1190901836u, 3498895828u, 121518848u, 4122627266u, 4044339275u, 3929319666u, 3725675569u, 2249645810u, 1648430039u, 805152867u, 604009597u, 428134903u, 3660078748u, 1495738811u, 2912743026u, 3529964664u), + SC(1098872981u, 3803982233u, 1184687675u, 1724685244u, 1166128174u, 3324080552u, 2889006549u, 591614595u, 442372335u, 2188313994u, 392144341u, 559497602u, 2786744839u, 1080958720u, 963196350u, 4153188088u), + SC(2439538370u, 4080798018u, 3371249236u, 2272355420u, 3780648680u, 116755088u, 1743646150u, 3071185844u, 3348389643u, 3506488228u, 3592742183u, 3935997343u, 3470563636u, 4177761627u, 2879753187u, 203653531u), + SC(3278048310u, 2898758456u, 2355004932u, 2165371155u, 909690763u, 4208028121u, 3529336571u, 120122699u, 1468577489u, 2088039937u, 3804192119u, 4005659309u, 496708233u, 114985314u, 4186471387u, 1516837088u), + SC(1694326758u, 3482448156u, 2533790413u, 3535432659u, 1293417127u, 2007819995u, 3512854075u, 2476797465u, 936262398u, 4149678787u, 807292055u, 1683402105u, 3767740082u, 682769936u, 2956180563u, 2800734304u), + SC(804843744u, 1565609957u, 1986774659u, 4163563545u, 1192892219u, 2967653559u, 1407927717u, 134508609u, 2584983666u, 3798685912u, 1759632157u, 1938927553u, 3974685712u, 2763800386u, 3702401831u, 3969543832u) +}, +{ + SC(2016238746u, 3648008750u, 3741265531u, 1468285316u, 3314132186u, 3225615603u, 2260838904u, 650230459u, 666608997u, 1079817106u, 1685466519u, 3417306450u, 465799968u, 1454367507u, 1432699603u, 4060146438u), + SC(1761873323u, 2175765323u, 123320402u, 1086415744u, 3425420197u, 3163463272u, 2096010147u, 892174421u, 3834451486u, 191088153u, 650609666u, 1384830375u, 430440180u, 1275312435u, 936713210u, 3964237847u), + SC(3490530311u, 4154571850u, 1473147571u, 1874492814u, 3394183939u, 690761407u, 1765847887u, 4254640890u, 3957252213u, 852293459u, 403059579u, 1419995731u, 373422976u, 1691953324u, 1513498303u, 3782064719u), + SC(2587537765u, 1727580331u, 2067598687u, 2050934719u, 1018600463u, 825517190u, 281367288u, 396667874u, 2125440864u, 2142555808u, 3739024155u, 471264185u, 2298783646u, 926505635u, 485317745u, 4237064052u), + SC(4177694527u, 1331122857u, 2632274962u, 2272030823u, 2711200568u, 493910969u, 64158788u, 2976239616u, 2805230971u, 1856476899u, 706343172u, 883417303u, 3085501222u, 2167885061u, 2608970459u, 1305891290u), + SC(3887930902u, 1612140391u, 329833229u, 737708613u, 660227298u, 2588285981u, 3429746116u, 4247477263u, 2536670475u, 1091054728u, 1521783433u, 4262529359u, 3261855757u, 453613765u, 484850910u, 3619344637u), + SC(3635973664u, 4002263582u, 683484955u, 1188525929u, 3024525647u, 1588813480u, 3496033065u, 109022234u, 2342061519u, 1416918501u, 2207158673u, 948640868u, 637445219u, 508491813u, 3897434662u, 680054967u), + SC(1039851594u, 403130855u, 3868498597u, 1611578944u, 2942424644u, 2874427101u, 1261647069u, 261871566u, 2520758170u, 2840740989u, 3799279215u, 381717039u, 3582347301u, 2025353438u, 2948438214u, 2918501540u), + SC(81851588u, 3029358979u, 3777821133u, 2109529880u, 3684139703u, 3572137489u, 2624799u, 2076188243u, 53500651u, 2606703535u, 3206313372u, 346558880u, 465806762u, 434266486u, 1902707603u, 4080110534u), + SC(3612241613u, 1917140707u, 4136616607u, 4041104182u, 2193790431u, 801466537u, 3599423303u, 3561003895u, 1189069231u, 8494816u, 4244955339u, 451969883u, 3908494655u, 517115239u, 1812731691u, 777430858u), + SC(3522137911u, 2027939004u, 2210696271u, 3920541975u, 875695915u, 2825269477u, 687289812u, 4252564584u, 1824925315u, 507608234u, 2614820601u, 2462525050u, 3886866857u, 668083682u, 2768243607u, 3293579201u), + SC(1682273922u, 1330912967u, 3636074852u, 840196898u, 1025234484u, 1557176067u, 2837118766u, 3109038869u, 594323342u, 3200796742u, 1959017554u, 1440926582u, 3021668826u, 3738492638u, 446292405u, 2414347832u), + SC(4116164451u, 4091036540u, 474505628u, 1269644927u, 3643568118u, 1673027873u, 1438360759u, 4022285580u, 4024623082u, 1654730750u, 1581385912u, 3853471495u, 335076979u, 2185560806u, 2494598452u, 3520671279u), + SC(4099595861u, 2215053464u, 488918654u, 2772869965u, 2247823716u, 1588093320u, 1138185172u, 732569291u, 247618738u, 1702163570u, 1772683376u, 1056938600u, 1997535786u, 2064838561u, 3705150691u, 1453615480u), + SC(3809909081u, 1962152573u, 3909100601u, 1479514000u, 1615313752u, 3569344372u, 997113509u, 3043376485u, 3480943705u, 4021042580u, 2284195092u, 2749518560u, 3037939132u, 3554704413u, 185068622u, 683070990u), + SC(3163624176u, 326387389u, 438403431u, 1924575191u, 1706136937u, 2432230714u, 4175139676u, 713582699u, 175432919u, 505729353u, 375905517u, 3179239595u, 2233296987u, 472507277u, 1822318909u, 3059447908u) +}, +{ + SC(3955300819u, 2390314746u, 8780989u, 1526705205u, 4147934248u, 1494146575u, 1667625450u, 2277923659u, 406493586u, 957460913u, 3449491434u, 912766689u, 1387230361u, 2368913075u, 3538729245u, 2943257094u), + SC(2095358020u, 3831852940u, 1752942227u, 477088929u, 2503091779u, 898077u, 2215106688u, 1298885808u, 352224250u, 3952364758u, 3669616566u, 664714721u, 1826685582u, 1576488055u, 2121138397u, 1442223205u), + SC(1378268686u, 187975558u, 3210161726u, 870689300u, 1860632239u, 902013623u, 571573600u, 25414363u, 3412397724u, 3841538145u, 215707661u, 324367139u, 2323478150u, 3794355190u, 1128115053u, 2519022352u), + SC(566244395u, 2591175241u, 2926679038u, 2852174582u, 200192886u, 521908517u, 2098042185u, 3563798587u, 1529741033u, 1248315044u, 233787221u, 2706044694u, 2870731528u, 3970719810u, 4167465378u, 525407392u), + SC(2196340159u, 4056996284u, 1702457669u, 2086317410u, 3933566271u, 3751624213u, 4023204768u, 677196918u, 2137509058u, 4037704026u, 2299370032u, 1748548051u, 3326874481u, 1974512389u, 1751264060u, 266112293u), + SC(1812114662u, 524787647u, 285577300u, 3638318945u, 3389691808u, 585441476u, 145370930u, 1149989778u, 1314386440u, 3471672106u, 908522311u, 4171434326u, 329350743u, 2954206373u, 856961382u, 2008618089u), + SC(2318825510u, 3826102862u, 687747522u, 4263777564u, 2387018418u, 1135189382u, 1414060091u, 217356911u, 2998889592u, 698204196u, 801530770u, 3479982231u, 1117806357u, 154519605u, 960816747u, 3149429798u), + SC(3250819610u, 351683992u, 296382659u, 4149667465u, 2183346760u, 1485561783u, 2218034265u, 420633334u, 1869679065u, 1205517989u, 3666184780u, 1975151679u, 371905540u, 367504198u, 1917294142u, 2403996454u), + SC(3958230362u, 3773825115u, 783748416u, 1243337893u, 4032003144u, 3908441244u, 201600922u, 2000451013u, 728826842u, 3533421010u, 3229478766u, 278198864u, 3933272000u, 1331731276u, 3202405750u, 1474627286u), + SC(3181836998u, 2581633616u, 3993055681u, 4020956268u, 2094932060u, 3551878275u, 393027783u, 2154269634u, 2283536956u, 2260289773u, 832949759u, 2403309662u, 3488387345u, 1652392255u, 393935478u, 2309058441u), + SC(4141036972u, 1727820200u, 832481848u, 1055621047u, 1091666560u, 1393833209u, 3406509646u, 2428157250u, 2974564551u, 2286298667u, 3776410458u, 815994971u, 1241023789u, 775596275u, 1035618310u, 3934253771u), + SC(206932164u, 4239023187u, 2046365950u, 2616857124u, 4246776524u, 4059028269u, 129664965u, 907402684u, 3859465657u, 4204192080u, 91453633u, 301171900u, 385561248u, 2689085222u, 1614465584u, 3977451005u), + SC(3683171878u, 3148577689u, 4042394721u, 1085044656u, 682611813u, 2857177748u, 2417075323u, 2983755657u, 3777418770u, 2448398967u, 3909780770u, 4000218621u, 4227580585u, 2425908645u, 1704039191u, 3712924954u), + SC(290465694u, 3921687099u, 2971845338u, 1854613741u, 1583022754u, 371222458u, 1744154613u, 3918664956u, 1960343256u, 1291903121u, 4010470137u, 1525668440u, 4091170130u, 1370665614u, 3468958243u, 1262617601u), + SC(469638518u, 1129475898u, 3766065538u, 1777952666u, 2589258222u, 3182239596u, 2626554219u, 1853296675u, 2912212627u, 2518041806u, 2743002885u, 3765128027u, 851537937u, 2059010589u, 1827964742u, 3630398912u), + SC(2458599023u, 2699477701u, 2305781427u, 2536499567u, 2118412162u, 1356010449u, 1426052710u, 725853717u, 1358092245u, 4196538471u, 66159936u, 4076320019u, 3065284443u, 2664736186u, 1943959552u, 939016920u) +}, +{ + SC(3159079334u, 690659487u, 1550245019u, 1719420482u, 1795694879u, 2846363486u, 15987067u, 569538014u, 1561199762u, 967336684u, 3110376818u, 1863433225u, 3468533545u, 3644881587u, 369296717u, 3652676359u), + SC(3207794512u, 2847938045u, 2415472979u, 1444858769u, 666387488u, 1660608279u, 1038886882u, 10876848u, 2468284561u, 2494495733u, 2622688628u, 2362399325u, 2213804831u, 3448783854u, 3958704532u, 3639349832u), + SC(54374990u, 186360229u, 3420619566u, 1356363720u, 2768151763u, 3862789233u, 4270651882u, 2681019589u, 2332931746u, 928338209u, 3968478928u, 3908570621u, 923281930u, 2285715383u, 3620920276u, 130031468u), + SC(4009596626u, 493238747u, 1786722937u, 653638870u, 1636723425u, 1884625267u, 2113708566u, 1448416211u, 3613674959u, 239497564u, 404863679u, 1521570751u, 2819432609u, 623319225u, 3073321373u, 565867032u), + SC(1220575379u, 4235426741u, 1889734996u, 43054857u, 879216917u, 3299856237u, 2922851906u, 1054251029u, 693641076u, 1704223409u, 961665328u, 2828086835u, 2727513652u, 1580557310u, 4169876178u, 682569510u), + SC(1757813477u, 22814395u, 3549822650u, 2254547303u, 372100012u, 1555116803u, 2587184145u, 3995169383u, 2645743307u, 188252331u, 3723854483u, 2138484090u, 1895504984u, 3538655836u, 1183003060u, 1439034601u), + SC(2578441833u, 3136721732u, 380864696u, 817462912u, 2257087586u, 2256998015u, 93155068u, 930999672u, 2793712092u, 2223512111u, 3157527446u, 1098951014u, 3490358734u, 1362531303u, 2421324125u, 1961922428u), + SC(1049179776u, 2969815936u, 3869567708u, 2883407597u, 1876243265u, 3498929528u, 2248008570u, 1231166427u, 3544374122u, 2839689583u, 1991744998u, 2798946627u, 736844268u, 1293771673u, 153373649u, 1931110485u), + SC(3785289356u, 1913060964u, 169967200u, 3348219956u, 3732729076u, 987877186u, 3063387163u, 3310757163u, 3480818987u, 1991307039u, 2882756981u, 1215305494u, 855630497u, 1471153868u, 1338946323u, 398364632u), + SC(1356154057u, 3013675057u, 3810909135u, 1796458190u, 2691409967u, 3963509663u, 2487357466u, 2764459334u, 2828737787u, 378542508u, 427318427u, 2412936991u, 393927878u, 3384382899u, 1135834101u, 3447900619u), + SC(3813669196u, 1922867812u, 483725924u, 518662823u, 3954558327u, 1908218112u, 2258643690u, 2093138355u, 1162728847u, 205977116u, 821018600u, 1237824238u, 2980682686u, 1821003630u, 3221633606u, 2717269894u), + SC(1353035942u, 2442753208u, 348196860u, 2355246066u, 2218279077u, 2203055542u, 1964199656u, 1329637142u, 1824193111u, 3965017045u, 795175573u, 1029253807u, 3915633667u, 1084707851u, 1682462202u, 2090124205u), + SC(190807548u, 1133131805u, 249542006u, 2858611426u, 304500253u, 2183315108u, 4145782890u, 2998333644u, 962888949u, 974441750u, 1484862994u, 801464190u, 2311388331u, 114769498u, 4260362972u, 1017092877u), + SC(1311406963u, 465174990u, 1760870095u, 883652788u, 1015674641u, 840236175u, 3124632038u, 2756294642u, 178804852u, 3164952754u, 241649187u, 1040890173u, 82588907u, 1771630815u, 1058353446u, 2473824375u), + SC(943051847u, 4107933890u, 535438460u, 2683519853u, 3177219980u, 3711205196u, 3390138615u, 2920849102u, 3747455519u, 4138118615u, 400899690u, 4278329560u, 2602463649u, 808685972u, 136036034u, 1078020636u), + SC(2185570356u, 3896907774u, 3620938057u, 1790823508u, 720763411u, 2404776615u, 3257162972u, 1221107462u, 3223154083u, 2528715719u, 688766234u, 1813423773u, 2324112952u, 83241050u, 4119437520u, 552112812u) +}, +{ + SC(3370489298u, 1718569235u, 523721575u, 2176389434u, 218587365u, 2490878487u, 2288222859u, 812943600u, 2821517993u, 3626217235u, 1545838667u, 3155352961u, 741681736u, 669093936u, 2382929309u, 2620482966u), + SC(40739723u, 469402467u, 1810137291u, 109375068u, 1888845715u, 2140810583u, 1053250454u, 3220064762u, 2539857789u, 4089587896u, 1364971662u, 2996699084u, 3939034030u, 2020251221u, 1606532641u, 3453095239u), + SC(1376139558u, 886121026u, 3003069127u, 3500718919u, 4223467610u, 3212808910u, 126355621u, 2065481301u, 218954382u, 1236555811u, 2283280895u, 4256918831u, 1550185311u, 896721211u, 4286247506u, 2515527710u), + SC(2942433244u, 2364220023u, 3675668782u, 3695614763u, 4041312428u, 2311531471u, 543507321u, 1902188023u, 1380686629u, 2455468346u, 2346421766u, 2211296276u, 3675221499u, 3890242164u, 3592353914u, 323566438u), + SC(971323999u, 4115912859u, 3703400072u, 2662062035u, 2355087034u, 610373016u, 2293984834u, 2456129286u, 2927901115u, 1832014620u, 1168920846u, 552716242u, 3101454502u, 1707155244u, 3450287619u, 2546358284u), + SC(3062358608u, 1394539264u, 4158727824u, 1704721957u, 1117692646u, 4057908715u, 1958466020u, 2309578289u, 271836599u, 2617957229u, 202314495u, 2948978715u, 1423414031u, 4128837100u, 1937488702u, 3301405882u), + SC(1276638700u, 885904232u, 3686149920u, 3283641475u, 619290126u, 2510808612u, 1691008630u, 573145513u, 506979295u, 3062936948u, 2703005699u, 4056634904u, 3460956977u, 3783023797u, 1215556973u, 3726733337u), + SC(3145485089u, 2008513183u, 2407056102u, 633050174u, 2634406893u, 2883313710u, 1233018283u, 3273507959u, 174012667u, 2126243450u, 2258342097u, 2857351925u, 3446764464u, 1187986524u, 3004835628u, 3228122242u), + SC(991481464u, 1720231754u, 1918287975u, 2752686681u, 1174123782u, 4227334584u, 1634945718u, 1074218184u, 3572504705u, 1199611126u, 1378243227u, 2901862427u, 2145083550u, 1055786253u, 3960418624u, 587771424u), + SC(3060872990u, 789280525u, 184089463u, 1784976524u, 344050594u, 2949751745u, 3173202246u, 3813443247u, 1247337895u, 4000924548u, 76989753u, 2093985529u, 265772293u, 3310477933u, 717631968u, 1024610284u), + SC(3399834097u, 2964304651u, 3593395714u, 2850196125u, 2344305533u, 3920139836u, 937580696u, 1116439644u, 4147778799u, 544787491u, 2461636418u, 2647550544u, 1451408824u, 3266700679u, 829974548u, 2625074193u), + SC(645329496u, 2808202504u, 1366740717u, 2841442794u, 1298546911u, 2730798019u, 3834987045u, 3258634143u, 4257492959u, 2976079952u, 1735944512u, 988426767u, 2395072762u, 3103996991u, 730963792u, 4206896923u), + SC(3457675112u, 4140282966u, 1286302693u, 575230857u, 2270112110u, 3056424235u, 1835144711u, 421529065u, 2499621064u, 1907217915u, 1365357672u, 2875249236u, 1193490885u, 644367230u, 2115448516u, 2507997379u), + SC(70240820u, 3745431832u, 1098747160u, 82118642u, 2446590634u, 851446619u, 2715739022u, 2142293045u, 2689000746u, 4219383621u, 3140617705u, 1457579904u, 2541485894u, 3932513084u, 3406615220u, 2746135210u), + SC(2576508439u, 3244150028u, 2516535555u, 3986514000u, 2903382402u, 2225326585u, 1780804949u, 1164188435u, 1682143109u, 2949153515u, 1249412173u, 349674695u, 3467452794u, 1021028584u, 1194554595u, 1296132950u), + SC(1028084134u, 2577983628u, 184499631u, 1037888434u, 1676727662u, 1831883333u, 1276555462u, 4161670547u, 372201005u, 844715673u, 24290758u, 1268964661u, 297554992u, 4061435345u, 719976096u, 1670144314u) +}, +{ + SC(1239892635u, 3772349433u, 1058531752u, 1409211242u, 2847698653u, 2391143499u, 2637108329u, 3000217976u, 4288568828u, 658925470u, 2552628125u, 1468771377u, 3230644908u, 2692030796u, 7587087u, 1951830015u), + SC(488413080u, 1055864530u, 1967623060u, 3973308786u, 2745059783u, 477755698u, 544732176u, 3786002606u, 1569550024u, 2935491988u, 1047898991u, 1749060996u, 1828274710u, 2943223535u, 3716062834u, 1253889972u), + SC(1626917485u, 492893476u, 2371366539u, 3928996000u, 3710769983u, 1237244931u, 1562679102u, 2930576193u, 2085522193u, 2968039733u, 3202113740u, 4250144171u, 3666251088u, 2016963274u, 293320478u, 3775462481u), + SC(3337977767u, 1831658883u, 1096680294u, 2436280860u, 119870062u, 1444445305u, 1467566544u, 2038307180u, 661842797u, 2493843529u, 3851219498u, 3941720925u, 1848373617u, 4051739727u, 1120765529u, 1101800264u), + SC(929493756u, 2211014659u, 3851484027u, 3468182176u, 147674626u, 3850162187u, 1517171722u, 907705770u, 3997080856u, 3666272567u, 659948161u, 2282159142u, 429200635u, 2563204390u, 1422415938u, 1688129608u), + SC(551422730u, 1797390513u, 2828310972u, 97463725u, 131839682u, 3917501017u, 566617767u, 700714239u, 3061891811u, 856175415u, 1072683059u, 1754819408u, 3533865753u, 2568134802u, 4226648923u, 32646755u), + SC(3538971706u, 2916601269u, 2891999350u, 3825811373u, 2355258376u, 2876141009u, 3940019347u, 1309282440u, 2567828520u, 1367177503u, 2910098023u, 1986452448u, 1802584940u, 1360144734u, 2877029236u, 3033303547u), + SC(3313753312u, 261894832u, 3637017242u, 3699232915u, 3508549542u, 3960876382u, 582644479u, 3199091169u, 3644395252u, 2675904765u, 2072396219u, 4071523208u, 3976776729u, 1025403411u, 2178466200u, 1107450603u), + SC(2163612584u, 2845646977u, 4033161886u, 2723908899u, 1902990762u, 3375716497u, 2588626243u, 513179480u, 3101622846u, 1458272618u, 3875706546u, 3028150894u, 3612001457u, 2583302957u, 3385091312u, 3719047138u), + SC(1256280924u, 3685139058u, 1853414115u, 3160743702u, 3455476559u, 2505590918u, 2308735646u, 3742507036u, 4016470170u, 330769483u, 3470077232u, 3383715347u, 1440115354u, 2667395648u, 1883060415u, 3332144245u), + SC(558087170u, 3027059128u, 1986900497u, 1642930671u, 5966195u, 3083778816u, 3199769457u, 1248728791u, 2110460619u, 327014118u, 2524517189u, 1776442925u, 1472982408u, 3459887088u, 1029172283u, 2232815594u), + SC(1544258748u, 3397993939u, 2721410152u, 2948125157u, 3562231734u, 3011402493u, 3266317933u, 527195819u, 369665170u, 3216603774u, 1952585925u, 258420856u, 3339671680u, 3733846143u, 2326118329u, 2310291176u), + SC(4140585488u, 4198875250u, 3415599245u, 3398679011u, 4155727512u, 331520374u, 785987151u, 146809315u, 2929041163u, 1558279570u, 1346822944u, 4167931729u, 2800498595u, 2809390575u, 3295157947u, 4121566122u), + SC(3571413466u, 1596401972u, 140853088u, 3137527478u, 204556611u, 4111255020u, 3835120334u, 3048525996u, 399176328u, 3005771198u, 780994070u, 3747160103u, 3136546207u, 508755537u, 2521091931u, 1715747893u), + SC(1156063870u, 393984449u, 1521183961u, 3649564442u, 183535572u, 3139859119u, 445469714u, 2815871833u, 1268459010u, 355340626u, 2465929503u, 750513297u, 1590602217u, 3983872541u, 97286792u, 110438349u), + SC(2549125874u, 1976691716u, 2532749644u, 279085303u, 633988261u, 3513450026u, 1057503157u, 1110164955u, 317735960u, 3241215082u, 3855084900u, 4137511567u, 3550729054u, 819799870u, 1929320159u, 2825290282u) +}, +{ + SC(2585638847u, 1394876113u, 3750575776u, 4144761638u, 1991524028u, 3165938218u, 158354186u, 812072970u, 3814951634u, 2507408645u, 1163603486u, 3566585210u, 1424854671u, 3326584505u, 3332079056u, 1901915986u), + SC(1520752595u, 1952396314u, 3263601295u, 3458083478u, 3797830135u, 509407552u, 3232598095u, 1205382790u, 2667815610u, 2560349365u, 2472625295u, 2883979179u, 554514567u, 2376619906u, 638138357u, 2568018129u), + SC(2442202610u, 2091297602u, 25025777u, 3622813695u, 3869161931u, 614884494u, 984078136u, 3345125623u, 3918959025u, 227030161u, 3885929851u, 1281751413u, 1612359075u, 2958486463u, 2884267132u, 3619290927u), + SC(3048700207u, 2570072469u, 1076153001u, 3767270422u, 1408579070u, 2076435276u, 2224129615u, 1962182553u, 1823335118u, 1499162388u, 1563913085u, 2068011578u, 1991334162u, 1665201834u, 1756239294u, 648108494u), + SC(2337582449u, 1819429591u, 3833487099u, 3870804287u, 2300831739u, 2232929806u, 1869816966u, 4084965807u, 4220168543u, 1248736546u, 924637940u, 73528534u, 2319796252u, 3657850751u, 2794932350u, 4220430348u), + SC(3028904021u, 2992718647u, 2354594543u, 3084902105u, 3127673085u, 783373559u, 3896264500u, 3984439851u, 820119108u, 4253719169u, 2623678017u, 3039126654u, 2922756242u, 2436956481u, 442364253u, 918876081u), + SC(1539558451u, 2306960255u, 1095386938u, 770368485u, 2906552323u, 3075682102u, 3534951832u, 2083903147u, 1308495764u, 2261904633u, 2112467113u, 1044610889u, 3222649255u, 1736090274u, 1954974285u, 1361850096u), + SC(587984395u, 1588261189u, 4052666242u, 512106258u, 651085942u, 2768947530u, 1250487652u, 1245674804u, 857176247u, 3594046498u, 647658046u, 2882585491u, 259918032u, 3698728358u, 632752990u, 351374374u), + SC(2404749839u, 3296323382u, 805352255u, 3954906457u, 3558496371u, 2470613864u, 2024150378u, 3564550335u, 2499521206u, 2051669779u, 607498894u, 3748811695u, 1128400961u, 3072401950u, 3042994760u, 811721793u), + SC(3595493043u, 1889077187u, 1981480426u, 4189336058u, 2081249554u, 2321560592u, 971543366u, 358725627u, 3595364674u, 3986924883u, 2193763710u, 4189195361u, 3121216309u, 1140981210u, 3226790033u, 353586077u), + SC(2871195936u, 2843651834u, 635723881u, 287569049u, 2067429609u, 2943584978u, 644639896u, 1264563774u, 670309272u, 2690274713u, 246950668u, 933865226u, 4053660195u, 1381269871u, 462688690u, 5420925u), + SC(977313734u, 4104230969u, 3334283655u, 1580178205u, 1578158646u, 1460773045u, 1728595474u, 3957344726u, 553676110u, 966612385u, 1786516334u, 2979157051u, 921122693u, 911238485u, 3922067113u, 1046213221u), + SC(91424183u, 123813459u, 1667146297u, 3387121372u, 438965888u, 4260725592u, 154972710u, 3237027664u, 3006360433u, 2505005588u, 2902337724u, 2660287100u, 1901200613u, 2646189902u, 2780155597u, 49560303u), + SC(3586622617u, 925349590u, 415005474u, 1260234539u, 30249250u, 2179523979u, 3475887768u, 3019952034u, 3517624902u, 4230850494u, 3734868171u, 742624613u, 822822789u, 3974379285u, 3711572581u, 3366701706u), + SC(329275906u, 1905371123u, 4004795330u, 2339811253u, 353091905u, 548998992u, 3687895576u, 356859438u, 2494263562u, 926298666u, 3983230019u, 2882391620u, 2824170047u, 2247742371u, 1881005652u, 1386887463u), + SC(1046492158u, 2680429213u, 1614272999u, 4010933686u, 2479992689u, 595409283u, 765550354u, 2852655093u, 1983575334u, 3910696497u, 2308266592u, 3012641543u, 2582478313u, 14949228u, 60656360u, 1955264759u) +}, +{ + SC(1355623958u, 2575138117u, 2562403739u, 1638722303u, 1523970956u, 2189861089u, 3498071469u, 1919711232u, 231840827u, 3230371223u, 143629793u, 1497495034u, 1677900731u, 1608282251u, 3485501508u, 3944969019u), + SC(1317209868u, 3823870608u, 3335344652u, 3702793515u, 2425890570u, 1442662397u, 4007605978u, 2976935239u, 1444558882u, 3449074340u, 523287240u, 1767769527u, 1776192231u, 1111610095u, 4035220013u, 3434023407u), + SC(1286632782u, 1751340143u, 184421370u, 3989392405u, 1838859918u, 3681550977u, 707040060u, 2695037953u, 1828105102u, 812532736u, 1115387936u, 1381188966u, 1389542552u, 621856846u, 1135930465u, 831833090u), + SC(2741542793u, 3565635943u, 455105161u, 2389444906u, 2966273581u, 4048751601u, 2569017914u, 1796095397u, 1515760827u, 3870103158u, 2737365395u, 818096507u, 2179280538u, 1254083919u, 2114706477u, 1413209953u), + SC(2036431795u, 3313380793u, 2996275588u, 625273343u, 1627738147u, 2163909313u, 2645773664u, 3066825866u, 3862562238u, 3189614065u, 3074707667u, 1611214266u, 689055345u, 1845962762u, 3616153367u, 98214289u), + SC(1783057147u, 1095836105u, 952581152u, 665189523u, 4159236737u, 3621720388u, 2768968806u, 1541462219u, 1550070665u, 2946487171u, 3084327270u, 3528580128u, 3683323170u, 2326350340u, 681502936u, 611874814u), + SC(2075965546u, 3954443814u, 3457426695u, 3100575745u, 795895906u, 2051458923u, 4220432661u, 3191956430u, 2978441632u, 1935083482u, 1260223004u, 1989210512u, 708452144u, 1742032782u, 412060225u, 942058976u), + SC(1554952802u, 1148928548u, 435577880u, 1218016814u, 774531999u, 4171943086u, 2728379380u, 1755428421u, 3096769247u, 551470356u, 663936617u, 2259245103u, 3605128160u, 4254582248u, 2543346251u, 2641240630u), + SC(2834055303u, 3779347324u, 986655417u, 1060344853u, 1961336735u, 3444096071u, 3402507696u, 1296975131u, 4013745799u, 318316127u, 3012349080u, 1543913977u, 3581569730u, 3073345556u, 1048961320u, 3338742347u), + SC(1917475623u, 1573453706u, 3775608035u, 1560651154u, 3305702627u, 840251936u, 2021694407u, 1567223161u, 1217097878u, 4101089784u, 1480235880u, 823763473u, 1860062290u, 3212933927u, 305432786u, 2664137512u), + SC(488290329u, 2159084342u, 1977681447u, 3072933047u, 2133970307u, 2904163387u, 2929381044u, 2852811875u, 3486789427u, 3312981159u, 2897952520u, 3716688458u, 3312599340u, 2231560239u, 2736260178u, 2100166993u), + SC(2561748569u, 2171003952u, 3930314290u, 4171544961u, 4084487200u, 1829909478u, 4190664042u, 1205662930u, 1332053018u, 3102835265u, 2758716514u, 3094681405u, 890009818u, 1835725787u, 3657145276u, 2012429206u), + SC(1490727773u, 2663703693u, 1786667419u, 3911642156u, 1173781475u, 1032437218u, 949369190u, 3379245680u, 3855657643u, 102309733u, 3862169655u, 1953708469u, 2899532678u, 2185103023u, 2246792392u, 2140300644u), + SC(1105179994u, 3403119551u, 2151897995u, 2133026531u, 4095632628u, 1958582421u, 3756551819u, 1353448323u, 343568827u, 940163873u, 3647008605u, 2675342302u, 2020863909u, 3314608025u, 3678853306u, 2350764749u), + SC(3610890660u, 7527132u, 3948519712u, 999155044u, 1566318108u, 1592356541u, 1395933920u, 3725362820u, 1628394109u, 2361449910u, 3407340106u, 1370203307u, 1521539242u, 166450716u, 1562824595u, 815891091u), + SC(4169640806u, 3985781662u, 2412370154u, 452406588u, 105016225u, 176939651u, 3796204183u, 875428687u, 2497589429u, 82221910u, 4277856341u, 1375558239u, 286683641u, 3316069361u, 519521869u, 2295715438u) +}, +{ + SC(1272080061u, 1249052793u, 3406223580u, 3180222548u, 3305857569u, 3627944464u, 989639337u, 2790050407u, 2758101533u, 2203734512u, 1518825984u, 392742217u, 2425492197u, 2028188113u, 3750975833u, 2472872035u), + SC(23055961u, 3145183377u, 2430976923u, 2926141735u, 1297155725u, 3931229778u, 1820665319u, 2985180446u, 3042883880u, 2460902302u, 3663963302u, 4048537328u, 3995357361u, 2497655514u, 2584741032u, 1771542440u), + SC(3555045486u, 1984442910u, 1340694232u, 3778110580u, 1134128670u, 754930307u, 645413801u, 419876731u, 718672506u, 2655370853u, 650960778u, 1175245889u, 3468383881u, 2671574337u, 44753822u, 3359158981u), + SC(289419990u, 2387037467u, 2851881154u, 4063189789u, 1829943773u, 2629576813u, 942097665u, 562844855u, 2647906183u, 117874787u, 202211775u, 3519990636u, 3082138694u, 1836881245u, 583992800u, 2183831281u), + SC(2721107251u, 1807232970u, 3202569269u, 3708638735u, 3532027994u, 4114767065u, 2764680156u, 135914892u, 1473879964u, 2935607101u, 4201045944u, 3202280567u, 3793176244u, 41830505u, 969791663u, 1519485648u), + SC(1497249350u, 1416277963u, 4236912956u, 1827689230u, 1595876921u, 792380080u, 2973128767u, 43523726u, 365213078u, 1703541227u, 1608568996u, 2447861933u, 4236202627u, 2270952660u, 996772411u, 1327926083u), + SC(930257564u, 986864131u, 3788206015u, 4282936823u, 3575152799u, 1711906087u, 3523467955u, 1026809541u, 3754676659u, 126901401u, 34761162u, 674497989u, 546239979u, 3916171265u, 4169565745u, 1773808675u), + SC(1188611875u, 4038625723u, 846346399u, 3124471166u, 3540873247u, 133640400u, 3354116939u, 2182269853u, 3158440321u, 538434017u, 508437111u, 2461460484u, 1662547818u, 3578959375u, 209001526u, 3335522863u), + SC(4264155336u, 4248354463u, 3273048757u, 2876562537u, 4290560912u, 509206354u, 1722430555u, 1796475043u, 864985283u, 4161684480u, 1401260098u, 2472895218u, 2342429930u, 827590760u, 300446032u, 2313806596u), + SC(2581459341u, 3429172659u, 2024065972u, 4099664542u, 1148350145u, 3444652410u, 3577141975u, 2981349935u, 4203645620u, 3053918552u, 3258443245u, 1577847138u, 1635931506u, 873577721u, 2391948063u, 3880308298u), + SC(348781524u, 168814463u, 525438717u, 333282992u, 3413546488u, 563982782u, 3571937262u, 2168075485u, 2567967190u, 4135534212u, 2773230423u, 2560090101u, 4070935767u, 1086323696u, 2826348049u, 1398744384u), + SC(1019826995u, 663251023u, 3152709102u, 4103744231u, 1372971676u, 1214523997u, 1159949230u, 2703418845u, 786011241u, 2156179212u, 1156040729u, 3454726929u, 1928366760u, 4000343119u, 4288863167u, 3214674902u), + SC(2681260382u, 4128008241u, 2510236484u, 1511367526u, 1684226652u, 979685907u, 2954161581u, 3173181201u, 2348267479u, 1347783270u, 1149362033u, 739573388u, 2484197607u, 335176176u, 4239049161u, 739872951u), + SC(2990421330u, 2634202447u, 3179573376u, 2783566953u, 2521510477u, 3781882024u, 2239710944u, 2912891640u, 4089020966u, 4152247187u, 3694477470u, 1764138981u, 2507816564u, 3857045441u, 3960587447u, 1062920229u), + SC(2607237939u, 3082469982u, 2290705462u, 3066564076u, 3196897175u, 4248068159u, 2751492888u, 1096521131u, 1350638971u, 3209282660u, 3725272910u, 717966828u, 1468400702u, 1807609199u, 332456241u, 3283231722u), + SC(752680913u, 2889161941u, 555836002u, 2587892579u, 793746532u, 2681266768u, 719050347u, 3803221u, 1422540107u, 1615046554u, 1724888503u, 923959013u, 3231965435u, 2753642578u, 1839210672u, 3344430910u) +}, +{ + SC(35118683u, 172484830u, 3416100291u, 3700412376u, 540823883u, 3117923166u, 4211300427u, 2853939967u, 3346783680u, 988896867u, 2435731911u, 431849862u, 1744411117u, 2614624696u, 297543835u, 4045956333u), + SC(2040009399u, 3617093372u, 1922089948u, 419196583u, 488784755u, 779735420u, 2537006207u, 704283906u, 1092151363u, 2578829348u, 2820670194u, 2121866485u, 3135057501u, 2561548080u, 1838738028u, 3520705790u), + SC(2347233873u, 2021920507u, 3747005552u, 3302704092u, 1421533666u, 2091592699u, 3349570591u, 3813605549u, 115030445u, 3350012162u, 2428670067u, 3833734570u, 1834087037u, 3648785167u, 3795974654u, 230561124u), + SC(3166315679u, 1499753232u, 1332394568u, 512254231u, 3188709397u, 2787249743u, 4120940214u, 2887173650u, 3906489413u, 2295240998u, 2578634494u, 1588397589u, 1261609842u, 547227344u, 3285763119u, 2699176838u), + SC(2920964533u, 3740093834u, 2438698186u, 1924062654u, 745692322u, 2251363856u, 1198363872u, 1945834517u, 3791006786u, 4021475876u, 1202959856u, 137650558u, 3764418806u, 2028729507u, 3549185474u, 4085572018u), + SC(2715838951u, 1959655040u, 1103474341u, 961883214u, 3220165814u, 946461598u, 3310562057u, 3895921046u, 3423737504u, 3466676673u, 4053794032u, 4003999722u, 704282430u, 186242539u, 1929875533u, 2743489242u), + SC(3863164996u, 1689760206u, 3183192577u, 2929742795u, 2741898431u, 3788088914u, 2356234821u, 7039846u, 36640443u, 397902308u, 1207730645u, 450227359u, 3243815017u, 2084858847u, 1390053102u, 1800322698u), + SC(2899288970u, 284742850u, 4164169257u, 657423444u, 1943078242u, 2187671316u, 2338824812u, 1463135135u, 2886625321u, 272841068u, 3193451269u, 275059886u, 893727404u, 1588413844u, 3713690958u, 858582046u), + SC(220208151u, 2716463025u, 2076296789u, 1220608226u, 1158026410u, 3025895717u, 2670689841u, 80726308u, 1182245224u, 514737744u, 1549626516u, 2794996864u, 1140029757u, 2873715616u, 2877687374u, 2336796195u), + SC(1712499527u, 3009254442u, 159655935u, 3126441867u, 4265886590u, 3094626983u, 2035167860u, 2311303989u, 3444838362u, 2596170866u, 3801673179u, 1837914686u, 3231006463u, 1247923284u, 584065013u, 4147287941u), + SC(900839097u, 216650153u, 2150488455u, 1952211291u, 2276027011u, 3518121564u, 3433005808u, 477320989u, 4007917006u, 2860081630u, 3686269191u, 921073036u, 3922496269u, 1487331039u, 3974930220u, 2054391386u), + SC(3348685354u, 1508268709u, 1715972206u, 4188610176u, 2563479521u, 2178972493u, 3288192040u, 3754144178u, 1173914019u, 454089507u, 3398639886u, 574196980u, 135948897u, 105476021u, 2877469782u, 2140775314u), + SC(60661201u, 2505799644u, 1330476086u, 2641855913u, 3370908611u, 3545887069u, 2369313011u, 278373074u, 1677987717u, 2174519857u, 2497481396u, 1568231376u, 3671812134u, 1893623337u, 1526376990u, 3328774765u), + SC(2836826686u, 3566150450u, 1220364883u, 3711427451u, 3528155780u, 2723292785u, 3326692341u, 2222164977u, 1858144237u, 1869912598u, 665154087u, 1299959695u, 2415334423u, 2100885199u, 1677986979u, 848478053u), + SC(2293836559u, 1740853836u, 1031472293u, 3209927466u, 2722427870u, 1686533972u, 3134525842u, 43165427u, 4133377528u, 4179858803u, 3614537390u, 3380004165u, 2699323023u, 2351902646u, 3408173486u, 2494501357u), + SC(1820258417u, 3371479244u, 1743152481u, 953496909u, 4267482844u, 97428203u, 2755286865u, 830318058u, 1082737155u, 2096588114u, 869939293u, 1138867599u, 3414628151u, 3300388932u, 2755674787u, 886356844u) +}, +{ + SC(1981590337u, 957784565u, 3778147127u, 3909235993u, 1637480329u, 2280601867u, 1059949562u, 2968107974u, 4043469535u, 4159249472u, 895867525u, 402468881u, 3186079639u, 86430659u, 4027560590u, 4067278225u), + SC(174847206u, 2629171882u, 2333280466u, 3666750170u, 1365991192u, 1932613341u, 769674425u, 2870677148u, 3091982589u, 717533940u, 691292429u, 746447527u, 2346750954u, 2424023836u, 2489851473u, 1000862947u), + SC(1294470925u, 420276534u, 18534679u, 2910625938u, 3592407247u, 3676292946u, 91786365u, 2630448437u, 4060747756u, 3372072880u, 766751258u, 2899531047u, 631745164u, 3523898915u, 3168717447u, 2801541394u), + SC(4228902076u, 3340600279u, 3364406353u, 4167190351u, 39030410u, 2148305555u, 4106423272u, 4019775241u, 1048613489u, 896239533u, 2278643848u, 649090509u, 1858593869u, 1017004108u, 2725922618u, 2362479567u), + SC(3279186701u, 4095625861u, 3191586341u, 3252046177u, 4161721618u, 2329134038u, 751155705u, 2989611709u, 942304573u, 3648059604u, 2883823407u, 1492175829u, 54393633u, 3106238944u, 429976962u, 1435978615u), + SC(3849622377u, 2984399872u, 690474125u, 61954906u, 3671421106u, 3429544548u, 2830056933u, 4242121816u, 952897126u, 3854066003u, 462125754u, 3261473627u, 4248077119u, 2601130223u, 2596495819u, 1081964366u), + SC(3544595842u, 126020837u, 2577264196u, 3433073867u, 496013073u, 2132398305u, 2482253446u, 1347711182u, 3954364337u, 261394336u, 1107608476u, 3443266300u, 104305688u, 870955527u, 3446753045u, 646876293u), + SC(164137956u, 1354687087u, 347069906u, 2162313159u, 2097666782u, 2177194309u, 1083298213u, 1791764705u, 445921337u, 2034078155u, 2254058003u, 1297019339u, 2457505957u, 3923390662u, 3364713163u, 2092921u), + SC(2010686846u, 2180989257u, 2265174665u, 208481647u, 547071646u, 2570387552u, 227431381u, 3946252713u, 1802054573u, 2876468168u, 3435214380u, 619729504u, 96719536u, 601795828u, 1679578869u, 3266813859u), + SC(1689091897u, 2850488954u, 85895902u, 2363909390u, 557966933u, 189022184u, 4135255025u, 2090271113u, 2804992462u, 2897353835u, 3129164865u, 2671868525u, 1204434986u, 2421048110u, 1069687644u, 573230363u), + SC(1864118934u, 1742326766u, 130305247u, 3848358018u, 448383585u, 389136808u, 676464280u, 133776905u, 3973153497u, 15653017u, 4189644276u, 1910866015u, 4017185152u, 3100723612u, 137322886u, 3499754296u), + SC(2165760230u, 1978556390u, 4038887110u, 3280144759u, 2755863878u, 1292009146u, 4196675347u, 2883653205u, 2360229279u, 2940095236u, 4183119698u, 122598923u, 483221264u, 2336117478u, 1200036442u, 1470973u), + SC(22625049u, 2110942382u, 3865539390u, 3568657648u, 4280364838u, 467068956u, 1638706151u, 934686603u, 1016938107u, 1378881668u, 2052861738u, 969631954u, 3114829317u, 2704079673u, 4202235721u, 1896331078u), + SC(1272877817u, 322275610u, 2048255u, 3828419764u, 283292018u, 656555904u, 1730883898u, 407673382u, 3259565233u, 3319282763u, 829721223u, 1466466546u, 121051626u, 1142159685u, 3894622225u, 1384264827u), + SC(3763136398u, 3055118026u, 3433748869u, 930030556u, 2135841826u, 2075894041u, 2845381068u, 3086878324u, 257833966u, 160279206u, 524657374u, 1855318297u, 1760771791u, 1248968332u, 2414205221u, 2464430473u), + SC(3809273981u, 900900763u, 2895572448u, 3283497701u, 1349213062u, 580961411u, 3299214221u, 3628519825u, 3643683404u, 3319374656u, 3868217535u, 427844533u, 3841842588u, 2749654710u, 2681210929u, 1051800659u) +}, +{ + SC(1622151271u, 634353693u, 3884689189u, 1079019159u, 1060108012u, 22091029u, 115446660u, 534633082u, 1649201031u, 4042006969u, 137296836u, 1833810040u, 1562442638u, 3756418044u, 1181092791u, 160208619u), + SC(1041667920u, 3037209402u, 1477404634u, 1440610569u, 2797465015u, 2054982250u, 3391499235u, 3605494419u, 3639198696u, 1933432209u, 1915711520u, 2741088986u, 3869566747u, 1879175626u, 717801628u, 458685614u), + SC(2768417957u, 2138940313u, 1896672548u, 1414723957u, 827016389u, 745281061u, 1045174332u, 3577682097u, 2169383377u, 1730416479u, 712654956u, 3155052928u, 1776219501u, 3353461099u, 711436547u, 1497369655u), + SC(1896697766u, 3621973902u, 926548253u, 4069206549u, 2297004301u, 3251063401u, 993943014u, 1270589313u, 3281589988u, 588955836u, 2429665887u, 1734915238u, 3409902793u, 2578722241u, 654727507u, 3216225031u), + SC(2536890957u, 2554531636u, 2109372546u, 2649000077u, 358086224u, 3391808161u, 1211714614u, 2605265326u, 2606629887u, 206756474u, 1092207840u, 3362434504u, 3945886373u, 4232252600u, 2886868947u, 3532954370u), + SC(65718672u, 4071991225u, 2060698395u, 2198173427u, 3957878549u, 4022831630u, 3461473682u, 419893418u, 779469249u, 2019627177u, 2019172804u, 3609556656u, 2681069216u, 2978123659u, 1249817695u, 2366599297u), + SC(2811735153u, 3049657771u, 1390752797u, 1411409994u, 2127695318u, 3083850245u, 787626821u, 1929564189u, 855492837u, 4008216334u, 1809444437u, 2182869717u, 813270534u, 2247412174u, 1161082081u, 1381922858u), + SC(3920648469u, 503487540u, 2083562080u, 327383264u, 2785608988u, 867359286u, 1036950980u, 431152821u, 1419040671u, 2665230771u, 2455357484u, 351717207u, 3187759581u, 3348793239u, 2511298896u, 1213040259u), + SC(2396309679u, 670711827u, 2849604206u, 3201137057u, 818618388u, 2531623890u, 3805810347u, 1463443182u, 79508933u, 3480790940u, 3579218280u, 263259195u, 3368747551u, 3044188079u, 1352272344u, 3090026690u), + SC(337838342u, 789695791u, 185502398u, 1517725636u, 783544345u, 2877621235u, 2946546356u, 1215973672u, 1208860651u, 725001171u, 1289736233u, 3756237869u, 1654092362u, 364807179u, 4279861158u, 4016003402u), + SC(1113567525u, 3780565260u, 836674522u, 1827009520u, 756906197u, 2663480421u, 3902552087u, 3507352398u, 774509259u, 224530498u, 2361577079u, 3744385228u, 3961162378u, 2586454589u, 3040342450u, 332039963u), + SC(3041171145u, 1474749273u, 2282851768u, 649990155u, 2952549483u, 1360702019u, 1809905451u, 544396952u, 68636355u, 2878101257u, 1478326650u, 2199663643u, 320705780u, 628185476u, 2087425498u, 3828181698u), + SC(3988280964u, 459019854u, 4007245269u, 1946776277u, 125932076u, 3922945473u, 608655237u, 759981570u, 1458494773u, 3686363491u, 3746534866u, 3692063331u, 290340676u, 486223220u, 3313127929u, 2280570810u), + SC(233319658u, 3886064320u, 853251650u, 1236563554u, 538386922u, 1967845333u, 3003439052u, 2872751142u, 150287328u, 2176354561u, 3956114759u, 3858039u, 2003618785u, 4212993191u, 2956509701u, 3196752221u), + SC(2121593903u, 3906201458u, 1137774967u, 3978600103u, 780659717u, 3484790562u, 769856015u, 36405780u, 695767695u, 3397748350u, 3377872749u, 1577340836u, 783581424u, 3804923626u, 2896998870u, 1723843622u), + SC(2572703671u, 2154230449u, 1195305676u, 4208655231u, 922600921u, 448134411u, 986012643u, 2442352758u, 1662902878u, 1367546113u, 2863017129u, 59878996u, 2111442975u, 648834983u, 865532037u, 1000323350u) +}, +{ + SC(2802315204u, 2299944053u, 2128407100u, 3463617348u, 2448441666u, 1070000794u, 1884246751u, 210372176u, 4075251068u, 1818330260u, 3223083664u, 3496698459u, 3376508259u, 4156094473u, 3718580079u, 1962552466u), + SC(3866141502u, 1978128229u, 2646349807u, 2688968712u, 1012393569u, 2539553175u, 2230158790u, 2206981245u, 3747509223u, 1243575365u, 3510697084u, 4007723917u, 859148499u, 1713821117u, 199178654u, 2644187203u), + SC(1964672019u, 297703434u, 1518880848u, 3373273121u, 959853764u, 2251122694u, 723413077u, 800337307u, 648287930u, 2947400245u, 1113383775u, 3610122168u, 1829970570u, 2892296971u, 1554744636u, 494969279u), + SC(4031050415u, 1835549397u, 2490029791u, 1131956513u, 1204048760u, 1914510905u, 3436953651u, 3943499769u, 1759802551u, 3820069122u, 4025269834u, 2717988015u, 2671631612u, 1159803272u, 1951365142u, 4085381442u), + SC(606110736u, 4064038873u, 70240913u, 2494945854u, 3729188113u, 2063877878u, 3912150605u, 3215847250u, 2977890044u, 3389766053u, 356841724u, 356991784u, 2228722660u, 3145515298u, 2594559598u, 1158432841u), + SC(1794017518u, 25183950u, 1671020817u, 785574353u, 95301808u, 1715172822u, 2718673424u, 1470113919u, 1142251437u, 2499778479u, 4281783303u, 1325560741u, 2913926884u, 3804531669u, 3139007483u, 1406557472u), + SC(2970751291u, 2450850294u, 545967636u, 1959629374u, 3303894193u, 455065073u, 41447235u, 1831795469u, 3594460859u, 4077235761u, 722461030u, 598330044u, 192707446u, 509790368u, 1051867275u, 1446366645u), + SC(1959543921u, 1887295052u, 3154544834u, 487969766u, 2252004301u, 996805128u, 2018864848u, 597352487u, 1136669046u, 533675042u, 981364938u, 2653382923u, 1408807893u, 2742559841u, 1833041360u, 1912794731u), + SC(2721713526u, 3549551325u, 601974093u, 2790584575u, 3951999363u, 4215366345u, 2845142034u, 4218934731u, 1726020765u, 823952138u, 3809833u, 4233069287u, 1129914456u, 1399496316u, 1915356031u, 4169077603u), + SC(3926695685u, 1849292395u, 1522137139u, 1552827989u, 4109112844u, 2060253220u, 2853920191u, 801241282u, 3422535773u, 1693187125u, 2113050221u, 2708536698u, 2777027446u, 4174902187u, 1811957361u, 3772547370u), + SC(3930825929u, 747327770u, 2505687587u, 2880650279u, 583976081u, 3834434841u, 1957901663u, 82062519u, 1246607062u, 4096185443u, 1298601955u, 3551964017u, 2293924654u, 2316870880u, 1326950040u, 3135743003u), + SC(2476396705u, 2790106263u, 443544224u, 2802435205u, 819417773u, 177556618u, 4130535785u, 2505448107u, 2591437865u, 1610510350u, 3815578981u, 4114533339u, 2461835810u, 3856846001u, 1439644255u, 3343979676u), + SC(4065627430u, 2927818196u, 950831561u, 4171626868u, 1177734694u, 150634338u, 2487656862u, 796691698u, 2119716392u, 2975402883u, 833495592u, 2179672277u, 346833760u, 3054174076u, 3573945862u, 3318693908u), + SC(2752867821u, 4203551149u, 1685153083u, 1110714758u, 1962211454u, 2837810663u, 1792364454u, 4089022191u, 3967274249u, 192406218u, 3350506767u, 1577386058u, 1497165592u, 1817646171u, 1066733732u, 617241273u), + SC(307712584u, 3903562077u, 681601120u, 3047177738u, 2486055863u, 3842609448u, 3660507009u, 2553494609u, 3174736607u, 3482954246u, 1496988826u, 1025695462u, 3184242644u, 1095387068u, 949053977u, 2083266597u), + SC(3022399010u, 1538609936u, 2420072227u, 990220729u, 2914167049u, 3768364162u, 1346299210u, 1681335666u, 2574961060u, 4053930867u, 303191498u, 2606902764u, 726562386u, 2306023171u, 939416980u, 608183941u) +}, +{ + SC(1862109024u, 2933191225u, 198801920u, 104305860u, 4011109577u, 4122560610u, 1283427153u, 1072910968u, 1957473321u, 1766609671u, 2854361911u, 4075423370u, 2724854995u, 3336067759u, 2831739585u, 400030103u), + SC(3665137971u, 362515859u, 3613170351u, 1634568159u, 2407386812u, 2769867978u, 3661728638u, 966943982u, 2329232814u, 928287686u, 386060431u, 2380767940u, 993235698u, 994357638u, 4262826729u, 789587319u), + SC(700222805u, 4205189715u, 1681820282u, 2408317852u, 3145763515u, 149703318u, 2996102375u, 2778856747u, 1243021847u, 118692771u, 660320701u, 2037909966u, 3471407521u, 3539034550u, 2338530850u, 798101514u), + SC(202761792u, 3072251152u, 936980226u, 2112028598u, 55725596u, 545941282u, 2866544613u, 2541609642u, 2986914411u, 250525398u, 494419489u, 904338436u, 448237071u, 2519815520u, 3547503723u, 3479815920u), + SC(2591263445u, 2313710919u, 2225850186u, 2907469855u, 1923973028u, 2439332754u, 1359667863u, 1147453888u, 591668157u, 1802961428u, 2115337573u, 3814501239u, 1652114003u, 3286770823u, 2320492326u, 1627762005u), + SC(915583786u, 1541647557u, 857793588u, 1120457139u, 593298997u, 1235522530u, 3835902793u, 4029633796u, 2892088014u, 950803214u, 2067553664u, 3466102617u, 417988445u, 1721721291u, 2995105031u, 1833135847u), + SC(3713015457u, 984220366u, 1636921821u, 69668826u, 2853588756u, 3372417728u, 1514016965u, 3165630303u, 549067200u, 2237752955u, 3528219045u, 2819816242u, 2536477233u, 430232621u, 1219272797u, 2682238494u), + SC(4158909478u, 628504302u, 1961569314u, 3701318609u, 1298978065u, 2797817112u, 2778611026u, 2986972418u, 2728592083u, 1350107926u, 261737783u, 1726357156u, 2342206098u, 3937750792u, 3688276065u, 1598643893u), + SC(673033353u, 989709407u, 1304069795u, 4233856570u, 603282839u, 3834722266u, 3349356388u, 2690783748u, 318351191u, 3370905692u, 2347975280u, 2009518842u, 2234183321u, 2940030960u, 2623873751u, 1542240694u), + SC(2380479990u, 2443937714u, 165899369u, 1753008008u, 3688956092u, 2346743686u, 143829732u, 3830274100u, 446444093u, 1705814492u, 2316415254u, 1337109896u, 3093454689u, 1928322219u, 2296006624u, 2093435857u), + SC(4072133379u, 1665275533u, 1975626640u, 3338948757u, 3639875020u, 2527617364u, 2537708733u, 3825629008u, 3956434656u, 2047924528u, 2149850378u, 563001677u, 1364815414u, 2503665164u, 637530147u, 630327427u), + SC(2169035971u, 3667715128u, 133026623u, 1213164483u, 1858042667u, 1566345391u, 3257221880u, 1553218197u, 1494901497u, 2543246705u, 3407410762u, 149097838u, 2595763051u, 3921913476u, 3975713216u, 1013875562u), + SC(4285039888u, 3972750160u, 2508056116u, 3828502305u, 1554885499u, 2478771653u, 3465835374u, 2839338634u, 936668484u, 3860842840u, 1796057260u, 539213045u, 1979230663u, 2637220243u, 3822691920u, 124051918u), + SC(4008482152u, 442930842u, 3844390262u, 1477377511u, 2570068482u, 380269897u, 3550124210u, 1507268577u, 1690622835u, 1216029693u, 2876552462u, 1409060125u, 862828291u, 1145788484u, 2966975851u, 3091998876u), + SC(992351977u, 3038251247u, 1125019979u, 3468273479u, 2933515034u, 2848650947u, 3581678949u, 3449520008u, 3870604714u, 2854135121u, 1257402460u, 1206940695u, 2996845551u, 725641056u, 3899090423u, 600507448u), + SC(1594814264u, 3363681343u, 1687711901u, 1220822433u, 2890970125u, 4169329849u, 1095390946u, 3969022672u, 2174219653u, 1940964660u, 1237339498u, 2965031440u, 1016584643u, 2590104317u, 4235803743u, 3748725935u) +}, +{ + SC(770670183u, 2030489407u, 913827766u, 28354808u, 2556411291u, 589717159u, 413516142u, 20574376u, 1695189435u, 3750527782u, 3546610407u, 1435363367u, 2770958348u, 2608593137u, 3331479090u, 2086258508u), + SC(386282669u, 3729286075u, 814752142u, 1413230862u, 2616133966u, 2483044279u, 1602859126u, 1971292416u, 3070813417u, 3451205972u, 735409142u, 4007950155u, 2905395594u, 2869625175u, 3709680291u, 2952203732u), + SC(3404816958u, 563114856u, 2100979818u, 2101934521u, 2503989815u, 1063833326u, 1723163772u, 3130704072u, 2515274210u, 1396315966u, 393457735u, 2691705207u, 828877164u, 3349330754u, 122605524u, 2602269000u), + SC(3709941627u, 592327138u, 2051205206u, 810649302u, 871212350u, 1541388603u, 4163983787u, 2631105522u, 665062813u, 2612020092u, 3229205070u, 3819479307u, 3310127863u, 1843015221u, 2875318880u, 3723951791u), + SC(1567440489u, 946197176u, 1275093448u, 4236630568u, 3990268727u, 196525149u, 15396621u, 1859637416u, 3138749279u, 3859238173u, 3227404352u, 2720346799u, 3006927153u, 2147957966u, 397899810u, 870180302u), + SC(1039540230u, 838590221u, 2330450212u, 923346890u, 4067788704u, 3619481496u, 3864357516u, 1659963629u, 3299501842u, 1079788777u, 949881347u, 2502746723u, 3228809289u, 247884983u, 3118597092u, 302086001u), + SC(3566621623u, 1671359399u, 3923258138u, 1638982085u, 325268348u, 4006635798u, 1207442469u, 3002539627u, 4047574291u, 2011583803u, 1713508996u, 1060703309u, 4012225302u, 3776068377u, 2784459927u, 3025510009u), + SC(4215947449u, 1997878089u, 1026649407u, 646510252u, 850804277u, 1871694871u, 3390738440u, 3114862405u, 3567086852u, 195428920u, 1556755650u, 1851670178u, 2207687769u, 3388294264u, 4058594964u, 4248126948u), + SC(45480372u, 1361999478u, 2195192123u, 956464540u, 1294436548u, 3045580134u, 2390633033u, 757048237u, 1350268583u, 862465366u, 1780970485u, 3285033794u, 559081924u, 163710122u, 3170983363u, 2626972150u), + SC(90053239u, 741607095u, 3003181022u, 3546281037u, 1996206866u, 2019149839u, 2216417072u, 1170259974u, 4159879668u, 130215053u, 2605146665u, 3967236653u, 1930867601u, 2409157952u, 3775975830u, 1489883331u), + SC(40478381u, 3873592210u, 35609037u, 272986081u, 3051595606u, 504620408u, 1019656134u, 250693036u, 942133950u, 156032543u, 3738710122u, 1712961843u, 2888111563u, 1171258741u, 645705716u, 511104714u), + SC(239657447u, 2278853730u, 2391081998u, 746810345u, 3484552464u, 1369592268u, 2655434121u, 1213868536u, 2934523673u, 3058111393u, 4281279490u, 3966376385u, 1307651904u, 1645528218u, 3652190772u, 1126527756u), + SC(123809694u, 110218531u, 117547539u, 2035819815u, 3596140063u, 1382818318u, 3664758070u, 3019339789u, 2719299822u, 3892472009u, 2876096109u, 412140786u, 2578091481u, 2196346764u, 3068803053u, 1395690512u), + SC(880155357u, 791542602u, 112062960u, 2175792069u, 531560395u, 3155859615u, 1042526138u, 680268271u, 1355330482u, 2485441305u, 148200464u, 964096786u, 3215229166u, 2660485876u, 3076499838u, 353883041u), + SC(2388114644u, 1552848777u, 1649071283u, 2325568488u, 3165393822u, 2695611152u, 2713875122u, 898903657u, 2377088931u, 1138573339u, 3366910425u, 3238180215u, 676550680u, 1043832292u, 1583145576u, 3925456200u), + SC(3116588854u, 731097341u, 35427079u, 152855963u, 655343116u, 2522648040u, 3048497137u, 3838372571u, 777022751u, 2851975543u, 235569549u, 3020787559u, 727642795u, 120522014u, 2406411931u, 4235508200u) +}, +{ + SC(2533741935u, 4150033708u, 3133949860u, 2798619408u, 806119564u, 266064305u, 1385120185u, 1697466874u, 3309272849u, 2305765083u, 4237655511u, 751372374u, 3319766406u, 1139025033u, 1880631363u, 2216696728u), + SC(531691765u, 3457214584u, 2884896024u, 292273176u, 250051106u, 4144042126u, 176967583u, 4132839552u, 2406879878u, 872979134u, 3029052987u, 2283805120u, 2613859206u, 553294045u, 1245122721u, 3840523078u), + SC(1249934121u, 993078438u, 2897493833u, 1681305911u, 57100476u, 365202891u, 2111004277u, 4247410280u, 1628827737u, 3793711703u, 3364391257u, 3510640052u, 3346661510u, 885793286u, 3903378618u, 356572920u), + SC(680178688u, 1413780236u, 356581993u, 2539116542u, 3091268161u, 952393142u, 3601213640u, 3759147734u, 3201912600u, 2029303323u, 3233109971u, 3469579370u, 4191225303u, 2727922547u, 4241219026u, 1108397896u), + SC(581424072u, 2231376178u, 2556335427u, 507971440u, 4133814232u, 3831053002u, 2090051536u, 2682264467u, 1696017056u, 2590078109u, 3496563305u, 1242917226u, 2491190071u, 2058502209u, 3614091208u, 50680464u), + SC(1148224059u, 3153210519u, 1979896166u, 3699990000u, 2774705970u, 4177914488u, 1097495713u, 3943642621u, 28438271u, 1936652546u, 2951976972u, 917798112u, 3345031007u, 3414386063u, 2086388059u, 3336786964u), + SC(3207879285u, 3245056275u, 2753912038u, 3444068917u, 3619101580u, 301796681u, 469710494u, 37792426u, 2324375961u, 3765435021u, 2308122387u, 186365381u, 1748483921u, 2929955002u, 2507797221u, 1450081310u), + SC(2628113752u, 657975440u, 4188527535u, 3642824575u, 1167948061u, 570005820u, 1209373950u, 3114955026u, 2156903999u, 3426648275u, 258877187u, 4116394669u, 3424577769u, 1876755024u, 3610721045u, 137959590u), + SC(1295746957u, 2893879416u, 2731249393u, 43796623u, 1509060380u, 3580712054u, 2063633991u, 246915731u, 245935590u, 2758600953u, 1174591025u, 3759438209u, 874703696u, 3900497366u, 2032803558u, 741576512u), + SC(737124188u, 2899307081u, 1769647158u, 617077642u, 1659909664u, 278863054u, 4232490889u, 625515113u, 3013249184u, 3621100329u, 3078044036u, 1407642415u, 2069197169u, 551433765u, 2836890938u, 3978268035u), + SC(1956698332u, 1096426127u, 1006277939u, 3889489220u, 4030026180u, 3579514159u, 4250029335u, 2203857202u, 3553085216u, 3293255490u, 1237506477u, 1050435484u, 3944172449u, 3169627003u, 1477888937u, 2421667267u), + SC(867315816u, 669003983u, 4033294932u, 3994270030u, 1836283861u, 4220295811u, 3981502955u, 1254544883u, 2953929766u, 3399467612u, 2767815501u, 1837724890u, 359769422u, 525366934u, 2275330754u, 1596174485u), + SC(2757381304u, 618201396u, 1587888624u, 1754675322u, 309402992u, 1862772816u, 1766295424u, 776578164u, 3139660404u, 2518031939u, 4144540600u, 2162413735u, 2788510259u, 3413511116u, 1497090248u, 130610227u), + SC(4221771265u, 792248867u, 928054053u, 140258355u, 1340321712u, 917602285u, 1586319677u, 1429062327u, 3604542914u, 1952132240u, 3586261493u, 1380920077u, 1224870626u, 1321897505u, 3109874655u, 2938496454u), + SC(2321281375u, 3760646295u, 420407446u, 4154009512u, 2825227525u, 4188075686u, 2041350513u, 1285713851u, 1670924786u, 1104780793u, 3524777730u, 1315724274u, 2655303597u, 1675669649u, 3173211461u, 1286635196u), + SC(1138423224u, 1326909178u, 3451890502u, 3840823688u, 3093921534u, 4140902218u, 2007985143u, 2980979703u, 3539657192u, 1914000311u, 3861983402u, 1995841174u, 2739822780u, 4269529997u, 1752802206u, 3674790048u) +}, +{ + SC(1529327297u, 3326406825u, 3128910982u, 2593525414u, 42156971u, 3661621938u, 1244490461u, 1967679138u, 1025455708u, 720268318u, 2871990393u, 1117479541u, 1562094725u, 697888549u, 2324777980u, 3391621955u), + SC(1194208642u, 570517940u, 3796480395u, 3996975496u, 1891180536u, 2012913508u, 2586036803u, 2779419249u, 2424448764u, 654631266u, 3378681847u, 1794600320u, 850887774u, 2610529382u, 3440406071u, 442629809u), + SC(3922776395u, 1021134129u, 4161953411u, 3695042522u, 416696694u, 3141869998u, 2208946602u, 2248782897u, 3791212714u, 2183092330u, 2442693998u, 3821686193u, 359924765u, 1313892u, 732537261u, 3441185514u), + SC(3832647873u, 4126820624u, 1633739521u, 1776853127u, 1990846870u, 2931750872u, 723350088u, 2100866125u, 1353427778u, 3735236517u, 2936890827u, 1037652209u, 3538242522u, 1205440750u, 2681851721u, 3428134171u), + SC(3715940368u, 3100195993u, 139205042u, 933899119u, 508675941u, 2073279390u, 3838896736u, 762162827u, 2670162920u, 363468845u, 4142816880u, 2331633868u, 1859516459u, 2571514805u, 1415575689u, 3310370398u), + SC(1850103477u, 2861511197u, 2158258814u, 1914352173u, 4112609179u, 1613408074u, 2229142795u, 2743410061u, 386541358u, 4131835227u, 238820765u, 350328321u, 796595210u, 325800094u, 1477199872u, 130087432u), + SC(3503083399u, 2168288449u, 3773780757u, 707691176u, 2640783803u, 600372304u, 3521490788u, 1266639681u, 3049849833u, 3696342843u, 1559948576u, 3113774976u, 2979720549u, 3508429388u, 1393959701u, 716360542u), + SC(2281167118u, 2404489970u, 874916137u, 3296730075u, 4266077966u, 1052198560u, 3487426822u, 379036992u, 918125804u, 3064034925u, 3007906638u, 2843799763u, 13395259u, 1525101299u, 3917909303u, 323214095u), + SC(4272733253u, 1134926458u, 1071872991u, 1594198106u, 2743911342u, 1759781849u, 3909986783u, 357998405u, 4054491364u, 588230484u, 3248723140u, 4206364217u, 407716541u, 1660843258u, 3535395038u, 735131513u), + SC(3679104282u, 2103136756u, 3192389130u, 3635496721u, 3762160259u, 813057806u, 1922167568u, 196643685u, 1370854030u, 2657803320u, 3197001343u, 2838705898u, 1256322653u, 3731470140u, 1658864516u, 4241135314u), + SC(4138122573u, 1064712956u, 1914688217u, 3980579663u, 234064841u, 1340868250u, 2408246134u, 2334390091u, 3574856083u, 4185747404u, 2592066932u, 72932352u, 1132443153u, 3084950430u, 2850577555u, 531426487u), + SC(2552518597u, 1814188589u, 3771797408u, 1688271073u, 1392417060u, 1864411028u, 2178912172u, 2411760311u, 772279774u, 2791980611u, 2940533230u, 3149501999u, 370215731u, 2968115262u, 942881455u, 2310941126u), + SC(751991992u, 3546574605u, 2773077774u, 2498170045u, 3288367839u, 3030402134u, 1196921751u, 3823185297u, 3245569995u, 3802879953u, 493640893u, 3321821285u, 1141758187u, 3411864659u, 306737884u, 2761165281u), + SC(1865741334u, 706283811u, 2318095713u, 1419794148u, 2504644337u, 1922210484u, 263491957u, 3084520625u, 705689999u, 2554474009u, 3818190952u, 2133768662u, 3690402460u, 3381523320u, 831084441u, 1146769937u), + SC(831531101u, 3633896804u, 1996958159u, 636851001u, 4007892767u, 380666960u, 2826737942u, 4021398986u, 1411635481u, 515161969u, 4199924051u, 371116192u, 1868116156u, 397223417u, 972171737u, 2331326509u), + SC(974457928u, 3569708670u, 2643527780u, 699675161u, 2627045402u, 3565281489u, 1504374419u, 2979851122u, 688725044u, 4064400308u, 4156347928u, 4119156622u, 2098702491u, 2615488234u, 1090654007u, 3790938610u) +}, +{ + SC(1397828129u, 1248172308u, 2194412927u, 3657598991u, 2085616102u, 1202270518u, 3253032741u, 2632389423u, 1019922267u, 332153082u, 1521672215u, 2163564334u, 3102124007u, 582149809u, 329417494u, 188520915u), + SC(2484409087u, 165527253u, 332794704u, 523511269u, 3524328119u, 4077596669u, 3681267981u, 2969751460u, 3456338723u, 628364217u, 4089156990u, 1135761223u, 1241363911u, 2843043452u, 1927162020u, 1187988850u), + SC(3424784620u, 4001207648u, 1967060425u, 33527184u, 588161341u, 2216089406u, 1194534688u, 3972415390u, 3430941953u, 3671974564u, 355464831u, 2638417624u, 987848314u, 3854256447u, 2513703271u, 847178398u), + SC(944122325u, 1095537200u, 1611102749u, 3845108718u, 3985128242u, 1188491807u, 3783427529u, 722821803u, 2594736624u, 4038805042u, 2146959275u, 3199724336u, 3631416672u, 3989329185u, 1113423723u, 925573746u), + SC(536468163u, 2790961065u, 141113925u, 985919057u, 2438788330u, 374449238u, 2980068000u, 621714839u, 2454037345u, 2810385667u, 3189321079u, 794373297u, 4178743943u, 2630861151u, 1229894711u, 2665151675u), + SC(71889345u, 3684655732u, 3834974630u, 40555081u, 3804280840u, 423207811u, 1620826812u, 3717508581u, 1813258849u, 713714932u, 491517868u, 2389605511u, 767769458u, 2826892693u, 3923819122u, 3331321015u), + SC(3333750894u, 150650636u, 3555142699u, 1161199649u, 3068475424u, 1509735584u, 1033908609u, 3073273527u, 3313105177u, 3410735718u, 2770838598u, 2161939200u, 1654309303u, 1247727621u, 4123284974u, 3218452135u), + SC(4107359918u, 3667881557u, 4099213325u, 905728122u, 3167924799u, 3731720507u, 1537227227u, 659110227u, 2101733778u, 2731849932u, 1103266972u, 887588276u, 2413509058u, 3876926094u, 2675347623u, 834362982u), + SC(3178393694u, 2636806389u, 1832500758u, 186297941u, 3662837586u, 3282938029u, 1064394039u, 2117567716u, 95811670u, 1968831533u, 3070787872u, 2658254448u, 3676980228u, 3909574788u, 2135784404u, 3803100103u), + SC(2624310917u, 420491519u, 3322620679u, 3357048697u, 614451586u, 1196461215u, 41516451u, 3256616699u, 3715883496u, 2257787428u, 2455669147u, 880443853u, 2246776764u, 3074399406u, 278369115u, 1177356599u), + SC(439711555u, 2231299488u, 1079942678u, 677737570u, 563039018u, 2032266501u, 3704274118u, 1877323449u, 2386821791u, 2066266240u, 2520835526u, 1611863315u, 3800297318u, 2553770190u, 1751820038u, 2175904420u), + SC(3515911639u, 4055231138u, 2717511782u, 6831543u, 3016647759u, 2007513585u, 1217171617u, 3815960975u, 2720128636u, 364849140u, 4285658094u, 4211508323u, 127732138u, 997100418u, 3152669382u, 146802488u), + SC(3082714386u, 513166810u, 2182067081u, 798923178u, 921230382u, 1956178560u, 883901335u, 4290259857u, 2290170782u, 3274942148u, 2025203706u, 2950735447u, 3706997198u, 979032741u, 1714061744u, 1756952042u), + SC(1785121933u, 665679939u, 3927612276u, 926826810u, 456860581u, 4247102861u, 1802871345u, 3111467239u, 2947918463u, 4090223916u, 2765919892u, 3848356305u, 2236940933u, 2379663516u, 2033761836u, 170415812u), + SC(723418419u, 3083992977u, 2885930256u, 4084559514u, 3550295439u, 795067132u, 3902666387u, 98659646u, 3559229619u, 3518103022u, 3093345450u, 3504265473u, 3135355783u, 1746911831u, 3896748938u, 1982334610u), + SC(4151598450u, 129451956u, 3923175367u, 306344029u, 336516292u, 3560777935u, 2695409605u, 934056748u, 4131395595u, 112767211u, 3377236273u, 797539933u, 516899453u, 2089210576u, 1999558205u, 4107023428u) +}, +{ + SC(87353816u, 3198238907u, 1232123158u, 3291424375u, 3695263554u, 2608617182u, 3798070797u, 3966302680u, 3847946128u, 278442153u, 3929504461u, 3056452729u, 3658519828u, 643043450u, 684101279u, 121314490u), + SC(4041434108u, 1283940781u, 3208791522u, 2974918612u, 861706326u, 3183082284u, 508820598u, 682206875u, 1177134745u, 1065833400u, 1830916342u, 1348337823u, 1877305145u, 2647094535u, 2714586296u, 2450197741u), + SC(2726369020u, 1580548584u, 150986819u, 369792970u, 2983651480u, 3064179956u, 3511715342u, 1538695618u, 3829066845u, 578378703u, 2038030944u, 3732775932u, 1174552062u, 2377418012u, 375009203u, 1203897576u), + SC(3480144388u, 847968760u, 3831609064u, 2454845771u, 827762235u, 3561019074u, 3068061128u, 2125290281u, 500142325u, 2613926927u, 908976630u, 461018064u, 1790330457u, 2138554260u, 3099515250u, 2668195629u), + SC(1153226571u, 752634643u, 4102962367u, 2953166708u, 3172028384u, 1546019245u, 73810680u, 2123706323u, 2289283451u, 1736737040u, 4246735980u, 196740994u, 886758605u, 1893565373u, 3405498929u, 3744937024u), + SC(768993978u, 3888906052u, 3538251248u, 352204151u, 4022234611u, 1471705290u, 4243963811u, 2027117811u, 1763868778u, 1322271979u, 3608278288u, 3888498758u, 3465093513u, 3125049811u, 2129222282u, 295188310u), + SC(2552844131u, 1588346847u, 4175462227u, 3528353039u, 48525488u, 1810438463u, 342094266u, 3279671133u, 111165134u, 1329165912u, 4063411685u, 1911765579u, 2818934337u, 3808545183u, 3789526924u, 1948478023u), + SC(3331030119u, 905985030u, 3533623355u, 799989600u, 1593247216u, 4044824934u, 3057376453u, 1132187407u, 2788031862u, 3252641138u, 1745792893u, 1362467427u, 2194538589u, 4207162080u, 1731158987u, 3426969514u), + SC(282742454u, 1925220542u, 3537150606u, 1044967349u, 4104410814u, 3036747834u, 2170951116u, 4063975818u, 2876870249u, 40785387u, 3225638952u, 2818597718u, 1556539976u, 2301588618u, 2800555653u, 916700871u), + SC(607531008u, 2820787318u, 1270007122u, 63140951u, 2489460286u, 3749254552u, 3480926448u, 2300022433u, 3335552281u, 3577740253u, 4083676266u, 1879037356u, 3793973091u, 653990091u, 981292091u, 2669230849u), + SC(1168110979u, 889306226u, 331429321u, 3194220363u, 4271486769u, 2440942709u, 3008822642u, 561011853u, 2621371879u, 1149493671u, 1110535664u, 2670803472u, 394628735u, 4014155619u, 3742604108u, 1418371877u), + SC(1139004104u, 1152838795u, 3053437035u, 3533998804u, 965296070u, 2842987726u, 3847937142u, 3591812355u, 1659887171u, 3058851485u, 1843832825u, 2284970388u, 153709291u, 2147381595u, 1241923942u, 3246474482u), + SC(2372841964u, 95150550u, 785345036u, 3777509922u, 3777338585u, 1256811659u, 530593057u, 2218391448u, 163045439u, 4110451435u, 940149273u, 3289892018u, 1950559815u, 2046468986u, 785769535u, 229305669u), + SC(4222560409u, 1251917359u, 3419952330u, 3518946758u, 2125025139u, 840904710u, 2104865575u, 3206919775u, 407519472u, 2004634252u, 1712650404u, 3590313236u, 840286442u, 2628712493u, 3254945248u, 1148702071u), + SC(3313735124u, 1648160975u, 2356873919u, 1752134136u, 1812666743u, 1155388994u, 2048656880u, 513774477u, 495906662u, 2103152333u, 2943961999u, 735251223u, 2523783965u, 2210023145u, 1945848363u, 2437613245u), + SC(1086803487u, 4028294733u, 2247710942u, 1830793111u, 1634316303u, 2935377055u, 600165818u, 1578619540u, 2988076738u, 457218665u, 4176910460u, 454493682u, 1199052867u, 1940805269u, 347367761u, 1212452462u) +}, +{ + SC(3715433378u, 171840999u, 971741983u, 2238541363u, 3192426674u, 4094492328u, 467620204u, 194258737u, 3399274574u, 3279461044u, 1351137305u, 2503870624u, 193649547u, 2998335432u, 1712991547u, 2208648311u), + SC(2715750837u, 1950207216u, 2432412079u, 3161034889u, 3163700758u, 2527560734u, 1574123740u, 2830017576u, 1235654592u, 1173758764u, 3503805913u, 3353556737u, 1972267538u, 2593804497u, 4050894516u, 1536909338u), + SC(4252707359u, 3437282014u, 3776749445u, 203710275u, 463138159u, 2772620289u, 1182212975u, 1132575015u, 2008846240u, 1446588540u, 1178588185u, 2810502365u, 3189501211u, 3192046357u, 3703545124u, 2781338651u), + SC(127281203u, 3251296097u, 4229877600u, 1655402395u, 2971465573u, 744237737u, 3839563968u, 1414447733u, 2055975912u, 547297398u, 3544526703u, 1086573241u, 4145442250u, 370020177u, 2948813570u, 1970539713u), + SC(3163465607u, 792227545u, 605650287u, 3454430637u, 4436412u, 957261079u, 2917570432u, 3199157324u, 317922439u, 2607400867u, 3201779931u, 1812841573u, 973872378u, 3838606231u, 3221928943u, 461831659u), + SC(246719913u, 1498935408u, 1945961723u, 1327338499u, 2917210822u, 1660082997u, 597934446u, 1244971072u, 662537876u, 3851981101u, 2064803568u, 1228771649u, 4273868614u, 3144280868u, 3367923741u, 2660003700u), + SC(958115915u, 3015255252u, 3159655209u, 1681296573u, 2092702329u, 3275820278u, 1666603934u, 3861667140u, 2501203189u, 4234907638u, 1084271161u, 60369385u, 1104875606u, 3495688315u, 3738262066u, 4032927728u), + SC(1265262733u, 3131514218u, 237040963u, 4104455196u, 2691347880u, 3487609649u, 1785135800u, 1176579745u, 4089650722u, 3141152552u, 3206481300u, 1333364227u, 276607745u, 113027050u, 176916027u, 1602590030u), + SC(2774594376u, 3129694750u, 2287032514u, 2766750820u, 29083039u, 1069500497u, 840365222u, 3485333678u, 2555809577u, 3972967703u, 629036427u, 3011729266u, 1526288233u, 1119437732u, 917067812u, 194168105u), + SC(592881983u, 3318575349u, 4127058062u, 1732571107u, 3503756272u, 837953701u, 482225210u, 1269788935u, 1504556881u, 1896976655u, 165783184u, 328929494u, 4077662490u, 1253488686u, 3518656631u, 977900779u), + SC(4160682596u, 2908983358u, 1718640008u, 3588190607u, 1505225185u, 4179103009u, 1685793395u, 115536342u, 817223934u, 1402206707u, 3062750872u, 450873212u, 3409531894u, 2142975045u, 1392180850u, 3108320562u), + SC(1943394512u, 2513880371u, 1620134863u, 1529322591u, 4060169700u, 3770293993u, 1183592156u, 3047089385u, 1457468150u, 3671110754u, 1216162597u, 2044466392u, 888112901u, 3589252991u, 523705271u, 1679814981u), + SC(2715251449u, 70744868u, 3381212136u, 1205646623u, 2056792384u, 3523601635u, 3273403565u, 2609964048u, 1635414738u, 3927671477u, 2002719738u, 17329846u, 673666863u, 4128776449u, 1023303890u, 2113317599u), + SC(678583802u, 2909193903u, 1603800869u, 1698604501u, 292539447u, 3194048567u, 1222053939u, 4292027072u, 1744031112u, 463670025u, 1002183205u, 880963334u, 2427537891u, 2521706813u, 3815796576u, 836594698u), + SC(945238598u, 3719965767u, 2849528520u, 3282124488u, 1093917226u, 3479450861u, 2561471910u, 139299258u, 3917471374u, 1798050709u, 2851226278u, 2410252745u, 1571541746u, 2877491529u, 1276119582u, 4206041035u), + SC(3869162698u, 1114491339u, 1196187395u, 1533960773u, 3407411925u, 765004505u, 1831463563u, 3761422880u, 841664315u, 226257499u, 2314441323u, 2186776430u, 2801566686u, 2703073796u, 3780881787u, 1370189991u) +}, +{ + SC(3356584800u, 529363654u, 613773845u, 1186481398u, 3211505163u, 123165303u, 4059481794u, 1428486699u, 3074915494u, 3726640351u, 881339493u, 977699355u, 1396125459u, 3984731327u, 1086458841u, 3721516733u), + SC(3675076449u, 3333909775u, 1262445603u, 3668028655u, 433069981u, 3324184640u, 206500128u, 2656010471u, 782457265u, 4053687660u, 3895856132u, 315252919u, 2755213770u, 922519354u, 2055252100u, 2429801305u), + SC(2756940336u, 2847978751u, 1709353190u, 1195969566u, 1965491900u, 3974470294u, 4065860779u, 457378802u, 2625680435u, 4168918960u, 912437805u, 1940496017u, 2831564708u, 2681452721u, 2977785501u, 178951684u), + SC(2809970073u, 2149172818u, 128792792u, 4173216994u, 3752778392u, 3547909179u, 2139546257u, 363162335u, 1029632619u, 226065897u, 1871318430u, 3511308809u, 4293432909u, 733440206u, 3154916386u, 2246758263u), + SC(731502074u, 2752951666u, 3348551978u, 3130709972u, 1526861742u, 2511266125u, 4044638365u, 215744304u, 1267320586u, 1960868675u, 3421832152u, 2257930073u, 2620941002u, 851383950u, 547951559u, 1340068454u), + SC(2684856551u, 174120198u, 1829892583u, 1225976594u, 2442169561u, 2751359631u, 1396256832u, 4190566994u, 616089248u, 1633732935u, 1633964885u, 3929429044u, 842800539u, 676918864u, 1428572539u, 219449459u), + SC(133428457u, 620472331u, 1882141266u, 1679319159u, 679060192u, 3481716513u, 213482586u, 3423863792u, 4201383258u, 1319777873u, 927348830u, 208213775u, 4087467606u, 3653264448u, 3835415188u, 3916570843u), + SC(1895413499u, 3284443662u, 1774671761u, 36215094u, 1302729892u, 3712548907u, 689399756u, 809699792u, 1542256887u, 1010909539u, 1793915800u, 371041697u, 3719334021u, 1415418990u, 3304256413u, 1722896741u), + SC(4292037144u, 3413799593u, 431584770u, 554753321u, 1212891070u, 139387849u, 4633456u, 4145076332u, 2956733683u, 2226540590u, 257006677u, 3020881975u, 3400787219u, 587473979u, 260993303u, 3410840543u), + SC(4018910540u, 3254488333u, 2078930374u, 2245837925u, 2632570996u, 3139405325u, 1623001428u, 3612462970u, 2032232089u, 519993838u, 198517548u, 1752888302u, 2236384752u, 3428944014u, 3264747145u, 2955960571u), + SC(3519760330u, 3333709979u, 1048481536u, 1985059447u, 2643412116u, 3131942587u, 1137942580u, 1547604917u, 2831143240u, 2752062158u, 438973315u, 216212421u, 839130203u, 4170782680u, 1103599719u, 3606044489u), + SC(3979124118u, 943995448u, 2583700510u, 3458129573u, 1268799005u, 2693058918u, 2421470342u, 2310844252u, 4161944025u, 2910466020u, 1520150746u, 2594375360u, 1025693596u, 3356457299u, 1405172368u, 3357345029u), + SC(3608628529u, 1093067289u, 2172624909u, 336171229u, 1137437622u, 2177129887u, 3319848621u, 3625148145u, 940129946u, 3128586787u, 111536296u, 1792339610u, 2781599252u, 3659875306u, 872551800u, 2302213340u), + SC(1104919194u, 189973497u, 2565652941u, 2930155667u, 3463454839u, 2388313768u, 2445171637u, 16202936u, 1593006897u, 2191020511u, 2084184836u, 1467463398u, 2313657914u, 2691464051u, 4089268188u, 4294499481u), + SC(4188734592u, 3528391612u, 40836399u, 4036867171u, 4090825107u, 2939803682u, 140442162u, 2546416492u, 1084596508u, 3326586985u, 72576332u, 3780421002u, 3675044591u, 2008171921u, 3141075467u, 4288443118u), + SC(3852374110u, 4271371075u, 2076634991u, 3101716180u, 518739558u, 3284103928u, 1607286758u, 3505817896u, 42970787u, 1339303318u, 3280473330u, 1956150319u, 790791234u, 1449585627u, 3814185461u, 3901254732u) +}, +{ + SC(3892284764u, 2210224198u, 97085365u, 934022966u, 3120556498u, 264721182u, 4011343025u, 1936310374u, 2593930315u, 3833725723u, 4141640186u, 2218699022u, 3726005369u, 649732123u, 1594208266u, 3687592104u), + SC(2459115622u, 155132544u, 2344650987u, 2337329027u, 2478875455u, 1363777389u, 666384305u, 779524970u, 131624810u, 1099629813u, 755087667u, 1116544707u, 3462583113u, 1765615231u, 1221263451u, 345614861u), + SC(283432140u, 3102718597u, 937211953u, 3334135604u, 2242058317u, 3044145753u, 1441000856u, 2163904099u, 654999768u, 3976748269u, 4108102772u, 1209693616u, 3022484925u, 2592361118u, 3806239715u, 2457345174u), + SC(1983572202u, 34789206u, 3963513429u, 2661898079u, 3999779459u, 2657216026u, 2570146353u, 810465768u, 1310539449u, 3517224567u, 1830164911u, 2328664885u, 3323158486u, 200812613u, 1588943475u, 1631047872u), + SC(1996456687u, 665652044u, 360516388u, 3634015955u, 3932508085u, 3762889476u, 2869080596u, 2179691892u, 1880327422u, 3850327759u, 1653803674u, 236673399u, 2154944705u, 3229042401u, 2981554507u, 485288416u), + SC(264936494u, 3091907543u, 2050111855u, 2694936127u, 1954787063u, 722933256u, 3813405263u, 739130277u, 2256053561u, 3585156690u, 2029190911u, 3133350308u, 3458910883u, 3499638057u, 41852560u, 491183838u), + SC(2808085465u, 1288453772u, 2477084166u, 3837131567u, 1141955368u, 3112183866u, 1372456734u, 2203526963u, 2954171016u, 3969349716u, 2868857569u, 414601865u, 4013256181u, 468368341u, 1996835394u, 3658768313u), + SC(394302887u, 1097097404u, 3291468368u, 1194224926u, 1035172467u, 1541144594u, 3844885672u, 3479557309u, 3116596876u, 2815221788u, 2598284757u, 360029902u, 1618439794u, 2569763994u, 3258655905u, 2917038348u), + SC(2305403224u, 515881048u, 3401955316u, 2294640138u, 2523482065u, 2913659188u, 1840514079u, 1334322081u, 1545396585u, 4197671987u, 447162882u, 3846426473u, 2663235502u, 750784192u, 4164775689u, 2390294077u), + SC(2816642384u, 3952759529u, 3784236377u, 1797857230u, 1881467157u, 3886776601u, 754213935u, 2085935272u, 3814437883u, 3598631313u, 3014087408u, 1480756254u, 2838244491u, 132661795u, 909841870u, 675503551u), + SC(2053456581u, 627096201u, 3974668317u, 245144267u, 3845450294u, 1209560693u, 1003623636u, 3431474873u, 3952764341u, 3855863791u, 1357940588u, 3374805012u, 2942824193u, 2988435703u, 329942625u, 4139666589u), + SC(73006928u, 4068145413u, 2752900485u, 643186737u, 2386201439u, 296363448u, 2965535934u, 2202307569u, 1300692310u, 3766694667u, 2421404412u, 2295288621u, 1987219755u, 3682346025u, 885571108u, 1086202535u), + SC(3800801259u, 1729576293u, 2024334221u, 266315944u, 3877353536u, 2983817286u, 1164606138u, 2981999790u, 2626097845u, 3537364374u, 3559786635u, 2149380619u, 2137897542u, 2218263339u, 206251476u, 3754285811u), + SC(1009857555u, 1650586423u, 3853695002u, 1715580147u, 1146669099u, 1380681899u, 2219018152u, 1791877891u, 3247738482u, 1042579957u, 4035547117u, 2619207487u, 2408116465u, 3045899420u, 1771645449u, 1340019342u), + SC(2004305920u, 978372350u, 1705342765u, 503429310u, 3635208103u, 3659317811u, 3957481997u, 297103567u, 2521968324u, 599616959u, 1167498361u, 357125999u, 3158983160u, 3114128384u, 3086595483u, 2336612985u), + SC(4103187540u, 1182325894u, 97419735u, 1615223731u, 2031918136u, 2818146326u, 1038685355u, 1330155299u, 2657284062u, 4126074186u, 2871281156u, 2738191090u, 1922990674u, 2689532011u, 4040564095u, 99693623u) +}, +{ + SC(3639643416u, 3974502485u, 1527161781u, 180938703u, 2788643910u, 3418867931u, 2912046968u, 1776807950u, 1185488163u, 2433308651u, 3682797092u, 1938004308u, 753534320u, 795320477u, 3620835863u, 105275502u), + SC(2971894151u, 635573958u, 1662864280u, 3637757763u, 1966418418u, 2382544768u, 3521712538u, 4180511568u, 1216311665u, 1622710591u, 2836323703u, 1065095206u, 3046512769u, 2304432132u, 1370910091u, 3540050165u), + SC(3003078502u, 1266710982u, 63268125u, 3769826631u, 2161222028u, 1624738852u, 2999285769u, 2485757266u, 3350017650u, 1836975640u, 3947916645u, 3226839039u, 3416803572u, 2607406281u, 3224012241u, 1574498192u), + SC(2417128114u, 3148595382u, 316383238u, 491687931u, 3782721648u, 71265990u, 725842943u, 2574280796u, 2910592942u, 1266732336u, 3293910730u, 3812834954u, 758280869u, 2044998492u, 585388705u, 2220041893u), + SC(492257517u, 927280821u, 3326474467u, 3418658462u, 175063450u, 4228793954u, 2332128647u, 2793872080u, 3349562222u, 3060602442u, 1750735766u, 864506271u, 3021446456u, 1089650280u, 684313887u, 2273360774u), + SC(569437869u, 3392548160u, 448456633u, 786222873u, 1891470348u, 56622530u, 1988234620u, 1200550357u, 3540465428u, 1566012807u, 3682627310u, 3118219502u, 421481320u, 474517348u, 4276632114u, 3506654966u), + SC(200012878u, 1289466640u, 383837247u, 2978212823u, 641013196u, 1218428129u, 2429292619u, 1428313217u, 4155302101u, 1036892035u, 3775206351u, 778853475u, 3322870631u, 4195074838u, 3725481759u, 3550082329u), + SC(126839072u, 3914304851u, 1035784989u, 2867617428u, 1989254908u, 3724484330u, 1316610484u, 1040102649u, 1452719164u, 210631948u, 1224888518u, 1113840153u, 910511278u, 2297844676u, 797967535u, 283877762u), + SC(1244500121u, 2493482314u, 3779000024u, 2685901143u, 2759844693u, 2465008309u, 2989069530u, 1046572576u, 3374497605u, 2414541412u, 1726159904u, 3650454710u, 2872643374u, 1536622747u, 1381290537u, 3538573283u), + SC(1982773073u, 895953548u, 653968243u, 2944168854u, 1891156211u, 862699673u, 178384938u, 2122337777u, 3992617936u, 1827424625u, 1827918311u, 4247768891u, 2116109311u, 2389157370u, 3259962586u, 3018719650u), + SC(16401953u, 2306633926u, 2338480543u, 3225473112u, 3429377887u, 2444554167u, 3036218027u, 811186210u, 2350667613u, 3590742085u, 2594672781u, 575072326u, 272468093u, 997542396u, 3031146350u, 3776453205u), + SC(1784787552u, 1031272746u, 3302965053u, 805306745u, 3874552409u, 2790720051u, 483200429u, 1779723984u, 1097599486u, 1897611475u, 2456960784u, 1754250527u, 3808506348u, 3902842183u, 2596972722u, 2928554842u), + SC(2323692909u, 829274841u, 1103316386u, 1866432209u, 1938371795u, 4027514213u, 3989131198u, 2637747342u, 2193562562u, 1183535102u, 290853894u, 707762868u, 1909722738u, 2733745164u, 2354524179u, 94921256u), + SC(390966983u, 2005348047u, 1183001210u, 3460046175u, 1194344520u, 3385791048u, 306982602u, 876126480u, 3192052847u, 3055117485u, 1493712024u, 239443620u, 3677526258u, 3935077241u, 3195438491u, 2508943164u), + SC(3776157658u, 1760005001u, 3371368706u, 4151959572u, 4117952947u, 2782084300u, 3075220020u, 3130861900u, 3220322643u, 4251107806u, 2765944679u, 2454606920u, 3864173523u, 2241965276u, 1056706189u, 2253371852u), + SC(10455103u, 669421195u, 538798805u, 681593482u, 4243109638u, 2765550308u, 1560790187u, 2332940655u, 157674749u, 358872640u, 2549359913u, 811329072u, 318369228u, 2192271276u, 2616093049u, 3105543667u) +}, +{ + SC(3392929934u, 3483303263u, 1976307765u, 4193102460u, 1186037029u, 2559946979u, 3008510830u, 4008303279u, 2792795817u, 3991995u, 311426100u, 3736693519u, 1914150184u, 2000710916u, 1829538652u, 896726226u), + SC(1506989834u, 781231698u, 1423994091u, 932436763u, 2811140941u, 235158077u, 3312925598u, 1277169313u, 2161654787u, 95045550u, 2507009285u, 3400899479u, 1327874861u, 2641030305u, 845165129u, 3067306163u), + SC(81377829u, 4112377516u, 996390415u, 1466127523u, 1087938057u, 1370439327u, 2374941315u, 3221315808u, 35184362u, 4155013651u, 4157224703u, 3036174627u, 820839223u, 644204168u, 3814924360u, 2548030643u), + SC(1091124676u, 3446444543u, 108918031u, 285417020u, 1457053816u, 2518578419u, 3204558864u, 1447981867u, 3090612039u, 774503865u, 3344583272u, 2737274269u, 3562442510u, 1127429989u, 2804182977u, 1775681652u), + SC(2318905039u, 2047942274u, 566069924u, 123115342u, 2915025724u, 2614503051u, 611479778u, 1680640702u, 111791999u, 3565934367u, 3623017458u, 358904698u, 718271833u, 2594429479u, 2455462208u, 1049889789u), + SC(2072590390u, 2994175732u, 776612573u, 3305897523u, 938985307u, 4037860099u, 405398386u, 312125617u, 834030222u, 4269222652u, 3952042783u, 188369721u, 969558599u, 2241466312u, 1494637662u, 3640394545u), + SC(793329188u, 1680204464u, 4194525713u, 1397937237u, 2203558613u, 193170132u, 590149348u, 3837254789u, 2629901211u, 1547324833u, 4256276761u, 178627910u, 1204782838u, 3049171442u, 2847310157u, 1633221731u), + SC(1445130399u, 3305816299u, 706740166u, 1986021205u, 2637844550u, 1419078314u, 1678054887u, 2432697110u, 870544859u, 890225672u, 4294515721u, 4251895411u, 1276311012u, 1177847908u, 2958585231u, 4245816799u), + SC(4225912221u, 703507803u, 1922376483u, 3748563847u, 841832204u, 937238929u, 1762562329u, 2321245641u, 3396851205u, 4196168123u, 2898493537u, 4105193320u, 3913075709u, 3714213782u, 3736794417u, 1813506206u), + SC(473058800u, 1281200026u, 2096535567u, 1916392924u, 2499055699u, 1592813861u, 1665248526u, 1352252079u, 2539722497u, 3800235497u, 2456011531u, 2486813252u, 2969323588u, 2786889819u, 264256920u, 4162650714u), + SC(4093970658u, 1112717313u, 4105391438u, 692152127u, 3191447576u, 765356874u, 3774754898u, 3659714922u, 1417146611u, 4116649329u, 2382824064u, 4091923584u, 2943998996u, 2572469258u, 2350556732u, 4055180934u), + SC(4241530692u, 3958450744u, 2400383404u, 466315350u, 35062538u, 2419973666u, 1574066566u, 718969713u, 2103427683u, 1844215170u, 377438369u, 3472936858u, 4219642124u, 2727593550u, 2415179286u, 530554266u), + SC(1717990860u, 490767589u, 4104938990u, 1912533482u, 1727757083u, 4081637760u, 2971627803u, 4227474711u, 2482396781u, 1077462396u, 1040490667u, 188422725u, 1078987146u, 1905877850u, 3465315863u, 3779881072u), + SC(2343360099u, 2602377036u, 540592495u, 3215700530u, 2276091252u, 330543342u, 1521140429u, 3101043196u, 1353643940u, 4257187260u, 3766970644u, 3977679607u, 2139641066u, 2691703488u, 1191064988u, 3899819176u), + SC(4020334744u, 3662481612u, 4168714619u, 3391835711u, 3785299560u, 71469795u, 2493742903u, 3412561168u, 3292204549u, 1481564183u, 2157273751u, 477496008u, 931448839u, 2827709521u, 2133135454u, 3513095854u), + SC(1821292885u, 77067071u, 2713776553u, 2767520127u, 1059460035u, 985220275u, 2884538737u, 221640066u, 2657382407u, 232264137u, 3155923068u, 3788271780u, 2919723565u, 1308585734u, 3615447351u, 9588952u) +}, +{ + SC(2320406161u, 892569437u, 3092616448u, 1707673477u, 2810327980u, 4012118332u, 4142748730u, 3869507620u, 92116036u, 2366184953u, 1613655167u, 3287845172u, 3562699894u, 416962379u, 1296831910u, 1764080884u), + SC(220529260u, 249394787u, 707093586u, 3327680194u, 3905189366u, 612327964u, 3292761054u, 3030686883u, 1334491337u, 3207860077u, 3280619568u, 1041320647u, 2483468975u, 1479881667u, 3211575507u, 3039423798u), + SC(2075210586u, 859890386u, 3979249840u, 1571749934u, 1787834945u, 3779262932u, 3834468444u, 2848979155u, 3949299214u, 3265482052u, 521566179u, 4090178483u, 2634506734u, 537774764u, 1760986104u, 1885781444u), + SC(2157623553u, 1245488719u, 2108443037u, 4226304849u, 1701247415u, 4110744868u, 1746909616u, 3191493799u, 846028927u, 3826268145u, 3155840342u, 1303740777u, 3325552898u, 2580884535u, 3592783405u, 4209959030u), + SC(535271984u, 3867256577u, 2621667187u, 479852461u, 3031868718u, 681291605u, 3866870888u, 975222367u, 189285295u, 2489945122u, 4002580885u, 1631683077u, 2806354223u, 990581176u, 3013857114u, 805874285u), + SC(4221232460u, 3061114345u, 3434676469u, 1406782470u, 155821803u, 124504941u, 3888697140u, 2788501814u, 1026476732u, 2216503728u, 3089015914u, 2063998098u, 272392246u, 1587339314u, 677528523u, 2432699241u), + SC(3643892943u, 4282202220u, 2100563362u, 826776443u, 1365722925u, 2702305724u, 679208928u, 3149950187u, 1446692720u, 2990196076u, 3121167752u, 25041546u, 1204401671u, 3950457476u, 478874733u, 4191001246u), + SC(1002796340u, 395169719u, 3087599283u, 10336612u, 2123927609u, 504611529u, 4163730275u, 706425703u, 1588733263u, 4149509341u, 1952228143u, 3819719132u, 766367752u, 1435203845u, 1906598194u, 3492363785u), + SC(1774340829u, 3089482890u, 2870005976u, 919794943u, 2035504962u, 4034646005u, 3486869666u, 3458779364u, 2688966610u, 4246698276u, 241215855u, 1193302498u, 1307583268u, 129792487u, 301354381u, 2759318534u), + SC(1993945167u, 2379081822u, 2587040362u, 3154537819u, 1926143939u, 2749781524u, 935556830u, 4138641196u, 1781637476u, 2939621229u, 45782825u, 4247420511u, 1775642409u, 3169645376u, 1224651656u, 1411268824u), + SC(4099217380u, 332485632u, 702660355u, 2932600301u, 2644542769u, 1705216342u, 2043283695u, 2373746705u, 2092217219u, 1660104946u, 3159676245u, 3674605841u, 226100099u, 3987250021u, 2436672589u, 1083744721u), + SC(775618835u, 2173251804u, 4192653515u, 3582997173u, 3769245096u, 484007740u, 503088416u, 1360222738u, 586791868u, 3760447547u, 3490651251u, 3534666198u, 2531156474u, 1207301882u, 832959081u, 3020069982u), + SC(298341207u, 1349761730u, 1369831393u, 1101983922u, 2409775356u, 3892600618u, 3875266737u, 3482966490u, 4002034047u, 2018792567u, 1932407387u, 1184232926u, 3015567427u, 301694942u, 437132459u, 3636206614u), + SC(4090425889u, 2348669465u, 2575850637u, 3995997864u, 3040420324u, 1615191584u, 2490849366u, 2670494936u, 2841563080u, 3763919842u, 3580970157u, 3864708123u, 187158351u, 2199194387u, 4160227448u, 2176418944u), + SC(3040328915u, 1001466289u, 3676795030u, 2946692141u, 3593888463u, 2224708622u, 4148397123u, 4253879884u, 1993280384u, 1176406404u, 3148404923u, 4180061590u, 1786680964u, 4036906941u, 1164279397u, 3562714780u), + SC(1286200509u, 4232891464u, 1656861418u, 3412215448u, 1086562483u, 2512121988u, 2650588176u, 3097245464u, 3192968944u, 2220731064u, 3414522916u, 4204353060u, 3690514744u, 3688465060u, 2246470987u, 498255717u) +}, +{ + SC(1167035839u, 2632944828u, 1562396359u, 1120559767u, 244303722u, 181546963u, 2941229710u, 561240151u, 1460096143u, 346254175u, 110249239u, 1849542582u, 1293066381u, 147850597u, 3876457633u, 1458739232u), + SC(3571928080u, 2436259038u, 1291130511u, 4109706148u, 535321895u, 223400632u, 1981907545u, 281269666u, 3986674262u, 1137333737u, 1403128295u, 1607985509u, 1996916063u, 3564990547u, 3398899933u, 2822030993u), + SC(4187142002u, 2183119934u, 1635192887u, 2899344980u, 2532710469u, 3583070294u, 1537984623u, 296183513u, 2324170481u, 3475303187u, 3887648540u, 634736823u, 1254765115u, 3808584578u, 3772430219u, 561684376u), + SC(513372587u, 1759503751u, 4262413842u, 2894839952u, 1546497784u, 1634597484u, 3075497476u, 1112503488u, 1318854936u, 1645523550u, 1808408161u, 1471049890u, 1607196116u, 1989192912u, 3845591311u, 3230210229u), + SC(4281800629u, 256065360u, 161761292u, 2162610453u, 3289868207u, 803664088u, 1737988317u, 3468667062u, 1313091619u, 3871261661u, 4163576187u, 3519070773u, 663580583u, 2181685257u, 1282501745u, 373224564u), + SC(1305532007u, 4040631353u, 3016994284u, 364840424u, 312087064u, 2832713285u, 813363164u, 1634515727u, 2857968226u, 2482770921u, 2702964276u, 1457003903u, 4233117491u, 978467573u, 454990490u, 2451215822u), + SC(3309788844u, 1373644165u, 2568421202u, 4021050421u, 3214613315u, 3179866441u, 2282215282u, 4192353052u, 766132975u, 1427735093u, 3905164154u, 3510365574u, 3650419996u, 1208798186u, 2311177541u, 3425106727u), + SC(1485656607u, 1872571460u, 3807266779u, 3227427836u, 1367154025u, 2087101352u, 2787930808u, 1683647111u, 611621831u, 1033465938u, 1055561737u, 1718623444u, 3674681330u, 3643294293u, 3841507882u, 2950124804u), + SC(3583452191u, 43558840u, 2702416786u, 2831018419u, 4179535508u, 3293628424u, 3781032090u, 4272940814u, 1561835153u, 3434531879u, 2033417772u, 143682419u, 2206689113u, 2885101743u, 3330838914u, 3213033967u), + SC(1563269339u, 3268845808u, 481878529u, 1366255066u, 188999428u, 2024859095u, 3740130866u, 1902201859u, 3294724532u, 3498902869u, 2063801661u, 3851840419u, 1697955856u, 1216829830u, 2472036433u, 2158918739u), + SC(3706632627u, 1854832685u, 4075722340u, 3009760070u, 1947919686u, 1613829674u, 3359356634u, 160149010u, 3211678034u, 1403957074u, 2395316449u, 232911190u, 3595342115u, 593590477u, 4003146812u, 1042747586u), + SC(3566751331u, 1293366329u, 237055278u, 781035984u, 3490518265u, 471671502u, 3279573882u, 4088428685u, 3341570902u, 1660948465u, 2602036180u, 3189056267u, 1448251311u, 3378653995u, 367559448u, 1247557023u), + SC(332188181u, 124235367u, 2908363616u, 57405667u, 3860321591u, 2915594808u, 3193053797u, 3103490367u, 2893876952u, 791722516u, 2759950240u, 2647310599u, 1060814304u, 1104815755u, 3283917665u, 954167246u), + SC(3633439037u, 1737408037u, 3240746577u, 2032524778u, 210349431u, 1157873376u, 3552462955u, 3068823u, 2593869163u, 1645741574u, 2624282012u, 1595174943u, 3150496822u, 2635369792u, 3670346328u, 1317499755u), + SC(3066163224u, 734815666u, 3189326611u, 2603442644u, 551273493u, 3201260612u, 896218759u, 1203901890u, 3082479753u, 4206490018u, 1615910957u, 3112412856u, 3354260034u, 1776181406u, 227950091u, 2452682654u), + SC(2235295503u, 3336503999u, 656069002u, 1855251063u, 1400966644u, 100804460u, 3316705750u, 794158471u, 3220130150u, 1524496317u, 4024763824u, 915138624u, 1872936127u, 829155670u, 1406327784u, 3285915916u) +}, +{ + SC(3539989726u, 2664422354u, 3717852078u, 3493347675u, 431408204u, 2534904428u, 166307432u, 1071633271u, 2817060747u, 2307358268u, 3433391820u, 2071844151u, 219511979u, 303896099u, 3062367591u, 2892429963u), + SC(4169968731u, 2129799654u, 437437237u, 369342547u, 1225909990u, 105177072u, 378686654u, 1403688950u, 3897807924u, 3252342965u, 1215424641u, 560413328u, 1897408132u, 317929004u, 3828647679u, 1630564758u), + SC(2120346993u, 1574861569u, 4055542703u, 3156063114u, 2155135979u, 3395705935u, 3607950162u, 1649229112u, 1891339524u, 2871189526u, 475543260u, 4035849276u, 919486311u, 4103998043u, 2581732188u, 3337457769u), + SC(2650342494u, 2112594502u, 300482146u, 4214370423u, 3712572735u, 2394678491u, 944484075u, 2859174140u, 1298074617u, 4123981874u, 2931863188u, 4060402101u, 408241016u, 1141274074u, 2343754010u, 2412599648u), + SC(1561545950u, 3513590208u, 46110254u, 2131948246u, 1318148204u, 2154872738u, 1632214749u, 3758828119u, 3082206346u, 1424038120u, 2361241545u, 845137641u, 307971779u, 1724404993u, 861282060u, 1237934782u), + SC(2774909901u, 771645224u, 1285073837u, 2193431137u, 1992145786u, 1323638656u, 695741715u, 2225025760u, 1506694954u, 4281622541u, 648809495u, 1264275594u, 2179049970u, 2134563430u, 1143161913u, 1676304803u), + SC(146493114u, 1026262009u, 3602767471u, 2183478058u, 1903997235u, 4037497130u, 232766761u, 3333583275u, 4037065903u, 338762279u, 3658077565u, 3465013868u, 2987748329u, 1503145496u, 1553131083u, 2250198737u), + SC(2341715858u, 2700579248u, 3859696179u, 2395756825u, 1875611477u, 3083700335u, 3413235310u, 1368601544u, 2011324934u, 2489277894u, 3393073269u, 1479863073u, 1546719681u, 1270920228u, 832404816u, 4096637834u), + SC(3098090164u, 3937526885u, 3922595589u, 3117243593u, 3619511456u, 687964457u, 2049777986u, 2737216841u, 904576627u, 2497431372u, 3782524472u, 2176150332u, 3538905622u, 1249874595u, 386091287u, 597337724u), + SC(653517061u, 2613638042u, 3043803086u, 3430911227u, 3939946327u, 3394071887u, 1634025406u, 422896314u, 2056719107u, 2825344479u, 4064697313u, 3122017483u, 3752686726u, 3984230999u, 2989927946u, 36279219u), + SC(2977387875u, 1756856293u, 2305658602u, 3898809838u, 2022534013u, 3053356239u, 1719149320u, 1006974664u, 3980567886u, 911250528u, 3970581037u, 4208855094u, 2375475175u, 3461024498u, 4207299460u, 172606632u), + SC(2123341088u, 2610619360u, 3636249805u, 2405928311u, 194895330u, 4166746397u, 1666551241u, 3089845290u, 830253287u, 1769367456u, 492844122u, 2898915009u, 1465071417u, 1748645392u, 3136192983u, 3149049830u), + SC(182090295u, 2773063932u, 2875617227u, 2014878906u, 4034576690u, 3504190878u, 648632813u, 578906269u, 3395653562u, 3622802446u, 1642118462u, 1105217635u, 3484288771u, 4187487776u, 3066363798u, 3248936252u), + SC(154149828u, 3967951687u, 1435057545u, 77065166u, 3232269485u, 3912916706u, 592527655u, 4277917673u, 3417904405u, 3905839920u, 1437307359u, 2532079592u, 1386597940u, 4043192840u, 828125384u, 1712244674u), + SC(4144828863u, 1262971610u, 2738002832u, 3848745747u, 554156666u, 3660926287u, 1405749523u, 293551868u, 956195932u, 2061195588u, 3476646641u, 1003448777u, 4182963546u, 1462193925u, 2827901865u, 1370898532u), + SC(287054389u, 4206061741u, 3909899140u, 2957058664u, 2712205523u, 1231432323u, 1252507865u, 2198483068u, 3163354130u, 595880373u, 2050058791u, 535083586u, 4093274722u, 251534866u, 1425149793u, 2349787856u) +}, +{ + SC(3015000623u, 325176924u, 3212623969u, 1014540936u, 2686878702u, 3453922035u, 257234635u, 689320672u, 395365200u, 3425465866u, 3351439740u, 3293249321u, 2261203941u, 1504215424u, 2365812346u, 2486464854u), + SC(2802351214u, 1019547153u, 1581443183u, 2237644987u, 2316167912u, 1277137594u, 922833639u, 1775757119u, 2259030628u, 3320484395u, 3474839377u, 3039388985u, 3157017009u, 701728799u, 45087422u, 1375130067u), + SC(1408178651u, 332882372u, 2572930650u, 1429622838u, 3740348959u, 3769865143u, 1102404486u, 2395773863u, 2055053046u, 1642858333u, 434575788u, 1458579645u, 1077283311u, 3435370625u, 412513198u, 1108997u), + SC(166351317u, 1290556120u, 1492697218u, 3828755332u, 1787027698u, 2627329842u, 818520792u, 3844511768u, 1093689215u, 2840813230u, 4268955351u, 1793367442u, 1197897289u, 1467402002u, 558600125u, 4039642298u), + SC(2618143148u, 4195387407u, 3571081448u, 176847982u, 3021045559u, 2151239299u, 4216918791u, 349987936u, 1438071630u, 2148079477u, 510134808u, 1844452199u, 3473619148u, 3775643892u, 3701006526u, 2069649956u), + SC(2536827719u, 256373429u, 82685205u, 2031847695u, 1685669223u, 3749398630u, 3100433967u, 2559626296u, 2614261735u, 2095898325u, 2650411530u, 4139725354u, 2433652522u, 1465137472u, 3074463995u, 2942034210u), + SC(950856594u, 2511634642u, 447889167u, 3271534101u, 3998181635u, 850059409u, 1500318444u, 2845728509u, 2319192144u, 1285732158u, 3307511706u, 1860111207u, 106597122u, 1317987028u, 3909997475u, 2833499319u), + SC(197466102u, 106471666u, 3969627291u, 425148315u, 2088018812u, 3287551129u, 2083642145u, 386904296u, 2967132086u, 417456225u, 2418726206u, 2685222098u, 3920069151u, 388803267u, 1008714223u, 4223482981u), + SC(1730602173u, 1587573223u, 1136504786u, 801576255u, 1239639300u, 3897044404u, 2640640405u, 3098571739u, 2095045418u, 1782771792u, 2216047065u, 2006450887u, 1019963460u, 450135304u, 1704523436u, 4178916267u), + SC(3045516080u, 2837283309u, 3652809443u, 3617799274u, 2953845221u, 1870697859u, 1987277049u, 671334013u, 2347392220u, 1637733040u, 408564290u, 531095235u, 1714215546u, 2668823252u, 4291679007u, 1499030154u), + SC(1785804164u, 3771923969u, 1688952513u, 4078905240u, 4219818381u, 2140263698u, 3560443409u, 1027592498u, 981877075u, 1273450409u, 1808708945u, 366130160u, 1509712333u, 1419790056u, 3592515372u, 1023304152u), + SC(689558936u, 2052202277u, 1573780309u, 1046114431u, 1768897198u, 1193436549u, 613072153u, 961650488u, 3203433527u, 2587127126u, 2088764244u, 3898254742u, 1779313411u, 2448405043u, 2102013432u, 2635393468u), + SC(2025692259u, 905848568u, 1759010770u, 1792571870u, 4118995060u, 266283808u, 4139640706u, 3438115348u, 2780184652u, 3445643695u, 656585512u, 181166262u, 2272629776u, 370943424u, 1751557846u, 2309122167u), + SC(267180733u, 424783777u, 1080203254u, 2661909603u, 1424050736u, 3737445342u, 2397112235u, 1140319020u, 3540605726u, 1560404816u, 714090654u, 3305695922u, 4001926073u, 4235374954u, 2250613806u, 603974704u), + SC(244840167u, 1554020100u, 3702066775u, 2862773506u, 3785435454u, 3651035430u, 218349583u, 1404753202u, 3766478445u, 2586133471u, 1533117238u, 4149938439u, 2210912076u, 3594357012u, 575816505u, 525962129u), + SC(4146528898u, 2136081288u, 1410528199u, 2682243562u, 3659634297u, 3884779676u, 1276188622u, 3650143718u, 2534539131u, 69352587u, 4188728680u, 4144009400u, 528573366u, 1948891771u, 2778384350u, 3961787045u) +}, +{ + SC(771871546u, 3238832643u, 2874232693u, 1176661863u, 1772130049u, 1442937700u, 2722327092u, 1148976574u, 4122834849u, 744616687u, 1621674295u, 3475628518u, 2284524224u, 1048213347u, 4058663310u, 153122870u), + SC(2125145888u, 3034373129u, 148397811u, 141146887u, 2520820550u, 761993323u, 2298029094u, 2891332110u, 2829144983u, 2531560926u, 2167918181u, 3311166313u, 1986747894u, 2110826144u, 1833688282u, 2697250572u), + SC(3869871954u, 4004844136u, 2445592287u, 191554676u, 1824322074u, 1934754654u, 1806989779u, 631655906u, 1640478312u, 3779394326u, 3878618879u, 1897296401u, 116845712u, 1282189569u, 1638341398u, 253193742u), + SC(869049848u, 3185853214u, 1086566153u, 574813225u, 768296876u, 2336838903u, 1037196762u, 3581040974u, 1545806877u, 1185761684u, 533220394u, 2594450382u, 518321105u, 3416686830u, 2271268151u, 3918676320u), + SC(3856331543u, 2684505765u, 649861433u, 2052378851u, 4281491040u, 1056350427u, 1268888422u, 3791019043u, 2372988231u, 1754646015u, 3964172838u, 3080977165u, 1940074122u, 2762476976u, 3389041795u, 1131517310u), + SC(1630655860u, 1949945516u, 3883647184u, 3029959080u, 1311781856u, 408642488u, 2800393690u, 3410356207u, 115351401u, 3420630797u, 2709679468u, 2872316445u, 1790203899u, 1997501520u, 3278242062u, 551284298u), + SC(2323279372u, 1575922229u, 4047150033u, 1372010426u, 3148623809u, 2453870821u, 2339486538u, 2280451262u, 2466099576u, 2994948921u, 132102763u, 1776872552u, 3906687848u, 1416385780u, 2716658831u, 3839935313u), + SC(1482060017u, 4064599659u, 4201421603u, 1862488009u, 1206323034u, 1506270647u, 4148487892u, 2940354206u, 221477839u, 2184047858u, 1052602625u, 1800724448u, 2376949890u, 1248004043u, 4042069004u, 1001474649u), + SC(1973975072u, 2109156381u, 895285550u, 2806725496u, 4257596779u, 2294716595u, 2126073388u, 4029509053u, 2287557214u, 3863235224u, 910675328u, 3403565516u, 2460443864u, 4145068647u, 1675629270u, 2972605807u), + SC(3067953236u, 2487048107u, 1053067642u, 2406833819u, 1120120518u, 2019615106u, 2151977185u, 2444444329u, 3698388134u, 2675794597u, 2346696087u, 3691916163u, 416413840u, 2548582733u, 2519917531u, 3323365251u), + SC(4258867839u, 1450083676u, 3423817219u, 2338254228u, 956448310u, 2038800503u, 2270893323u, 23474499u, 4001071451u, 434241187u, 4225947271u, 3009484949u, 1212186223u, 3021170789u, 3408787844u, 4241328442u), + SC(544425045u, 2335106449u, 1970249987u, 676962447u, 2451092807u, 3397085111u, 644609608u, 622894566u, 3012162452u, 742316904u, 1183695331u, 1942632009u, 3993963459u, 2025380463u, 2934502595u, 2424729664u), + SC(489227787u, 2064607364u, 749046162u, 1223089239u, 4103152782u, 944881113u, 2156101348u, 2809656549u, 2750173639u, 2290439348u, 455194332u, 3662094961u, 2388553957u, 2373693996u, 3087294434u, 714908241u), + SC(844100070u, 1293873339u, 240400805u, 2741251793u, 4185619158u, 3756747900u, 2600026127u, 4095003808u, 2551250677u, 1982555415u, 1538344606u, 2598805396u, 1759235723u, 1251966u, 1750681115u, 626531732u), + SC(3996016258u, 3876613311u, 1191787057u, 3901742282u, 1577096572u, 270596184u, 3165567618u, 4061944625u, 3613068329u, 3912630805u, 2056061785u, 2568706449u, 2343664228u, 1807908509u, 1314728487u, 1028342757u), + SC(2729604648u, 2866824008u, 1921075953u, 959207538u, 460881358u, 1786258799u, 989199155u, 1140694999u, 3534517067u, 1671080238u, 1077292982u, 69981150u, 2456995550u, 2177711190u, 3355630373u, 505438766u) +}, +{ + SC(2470971363u, 1622646280u, 3521284388u, 611900249u, 53592433u, 1667691553u, 3986964859u, 3228144262u, 4160240678u, 1357358974u, 796266088u, 2135382104u, 2999113584u, 425466269u, 866665252u, 3795780335u), + SC(1943673032u, 163567132u, 2998325065u, 4151760187u, 4286963295u, 2037110896u, 4023804057u, 2843670454u, 4267379728u, 470850548u, 1360194572u, 542908383u, 117354082u, 3909600634u, 3301531838u, 585104523u), + SC(421763950u, 3621776882u, 1804759030u, 1922063749u, 28357531u, 2718763721u, 3528327041u, 2594458380u, 1745913977u, 1705774731u, 3785007083u, 1889010688u, 4275556992u, 2808027536u, 1706627542u, 967259307u), + SC(3761989171u, 2069950976u, 953323220u, 30139149u, 3360357391u, 466334029u, 1085748790u, 717259079u, 3822910993u, 1348849055u, 4159668773u, 3924702853u, 4257335520u, 1714446370u, 3394938265u, 2541598048u), + SC(2132231371u, 3951042779u, 332537683u, 2179456991u, 3112576172u, 2873883577u, 502046554u, 4014018248u, 4272356370u, 2124475345u, 3140973257u, 1234959848u, 3468807232u, 3812306463u, 2768101189u, 3493652974u), + SC(2983624056u, 158967077u, 546553405u, 3473936990u, 3742593866u, 3986716933u, 2905591308u, 285301696u, 2640868047u, 3062221467u, 70156428u, 150492378u, 3977001273u, 1087159682u, 1233481348u, 3391921638u), + SC(3432795737u, 4256529583u, 3151717298u, 4190687875u, 1563633254u, 158068428u, 685294219u, 733826550u, 2829744078u, 4225504275u, 2375584227u, 1429440840u, 2192098666u, 1015042413u, 840775854u, 41702830u), + SC(3231767315u, 1865273494u, 1093659663u, 1873962287u, 1664376931u, 1435837948u, 31100007u, 316783664u, 996300708u, 334486049u, 1648124912u, 3615910102u, 2480590997u, 2253624363u, 548978494u, 3975730498u), + SC(1923874249u, 3947343158u, 2264687656u, 1121555015u, 3593673308u, 289357572u, 3048054908u, 3707221766u, 2043411687u, 1708537123u, 3350208529u, 2939237811u, 2793137666u, 3370678100u, 1405378414u, 2235087472u), + SC(139882711u, 1304366355u, 1276034712u, 2139658031u, 2197726287u, 3663457902u, 2357615523u, 1611719773u, 2323318078u, 260257531u, 2850134214u, 3099029628u, 553263652u, 173876122u, 2118167747u, 1771928540u), + SC(566458485u, 3545725305u, 2257836680u, 2245189792u, 1605297549u, 245844769u, 2016071772u, 1896412522u, 821618527u, 1870442187u, 3958912319u, 4032980189u, 2069248247u, 4226059888u, 3345680132u, 1791157180u), + SC(4148097755u, 2486537082u, 4003164230u, 2318687306u, 2491702264u, 229564758u, 4126839602u, 211561653u, 3452304873u, 2572510204u, 1630441069u, 3167885411u, 4175966562u, 1295680948u, 161732432u, 107333173u), + SC(1923252062u, 311708286u, 1678166990u, 3717252154u, 3161198614u, 1069601573u, 4091259962u, 359278439u, 3768419820u, 2520693990u, 650972975u, 383288062u, 1217231824u, 2559091429u, 4278580592u, 2250271391u), + SC(510621576u, 1629846927u, 3397488683u, 961386517u, 653633283u, 1754007094u, 2769834941u, 2247122605u, 2701964981u, 3912616774u, 3406969249u, 63999109u, 3141040146u, 2619453260u, 1468121925u, 4171492447u), + SC(3961993547u, 1155134029u, 1496861029u, 1279080034u, 2846121209u, 3483514199u, 2468398271u, 505281559u, 3532558643u, 2311328115u, 2310583909u, 3085705085u, 2999958380u, 2683778623u, 32663880u, 1366954658u), + SC(3799286526u, 1580228485u, 2766986278u, 586308614u, 2894037718u, 587959438u, 1301020570u, 2323176208u, 3827747523u, 2955860540u, 455053544u, 124753776u, 703403555u, 1658788582u, 3867772588u, 3276199889u) +}, +{ + SC(2899222640u, 2858879423u, 4023946212u, 3203519621u, 2698675175u, 2895781552u, 3987224702u, 3120457323u, 2482773149u, 4275634169u, 1626305806u, 2497520450u, 1604357181u, 2396667630u, 133501825u, 425754851u), + SC(373198437u, 4218322088u, 1482670194u, 928038760u, 4272261342u, 1584479871u, 2503531505u, 354736840u, 303523947u, 2146627908u, 2295709985u, 233918502u, 3061152653u, 3878359811u, 3090216214u, 1263334344u), + SC(2076294749u, 898460940u, 2754527139u, 2099281956u, 3551675677u, 4195211229u, 3603181913u, 1984445192u, 1121699734u, 573102875u, 2187911072u, 656800898u, 1477748883u, 3685470532u, 3965328576u, 4253954499u), + SC(1876288412u, 2267864341u, 434083874u, 1779401913u, 2781669786u, 3073195348u, 669142308u, 3636028767u, 127310509u, 372075961u, 2537369503u, 2705808591u, 971889633u, 2718294671u, 1415139024u, 276903675u), + SC(3596445084u, 2918342013u, 1827011883u, 3900260359u, 1783558754u, 1921301616u, 3293933601u, 1111091218u, 3238604202u, 967515902u, 1208493040u, 1614341552u, 903992012u, 480937886u, 28823639u, 2379076161u), + SC(1968094521u, 1600813704u, 2958098796u, 909224758u, 1752381729u, 3115930502u, 3643078327u, 2863416031u, 2510423171u, 2162796973u, 1796627662u, 3678673773u, 239312629u, 2457874359u, 3809753210u, 2494718541u), + SC(1731463174u, 4265769542u, 194787641u, 1036371942u, 1745836602u, 660344840u, 1082796561u, 3963871960u, 4001246025u, 3118794916u, 3886266100u, 1928084049u, 3032262555u, 2306541818u, 3921311698u, 2426451176u), + SC(4018285402u, 658949239u, 1329629679u, 2738829796u, 776877685u, 1774949833u, 2797031752u, 3236392582u, 2542061420u, 1832249084u, 183211998u, 1840198657u, 1314474881u, 3361925365u, 3440999944u, 974653576u), + SC(1671164742u, 4271520021u, 1517391404u, 3289979834u, 1233503784u, 3050636514u, 3728319521u, 2919957525u, 3518724155u, 1272537958u, 3303667759u, 3864284110u, 234069183u, 1495943844u, 1989482539u, 3056780355u), + SC(1575547612u, 2187321001u, 2701011625u, 2761636008u, 1864623673u, 3995428494u, 1950725639u, 3749309698u, 2711714857u, 3743669273u, 3222519898u, 621366782u, 2554696188u, 176315043u, 1467854493u, 1806812435u), + SC(1182422499u, 3354985654u, 814715964u, 4226927046u, 3360200226u, 2503195953u, 1526762508u, 3747376732u, 1505823655u, 3718914053u, 2708056196u, 1868291203u, 1664951819u, 1982491563u, 751360443u, 1075645602u), + SC(101076600u, 386741863u, 2955045918u, 1653351871u, 1070602553u, 321875967u, 3200546966u, 2632915072u, 225765461u, 1759013254u, 4169466720u, 3880757831u, 1769634729u, 2642211393u, 4245887731u, 3909815727u), + SC(2379322656u, 1554830911u, 1971754317u, 1058862290u, 623917994u, 2775317172u, 3261049248u, 1667374591u, 3883068608u, 3752131736u, 2607464936u, 1251402973u, 4056909038u, 937468613u, 309280197u, 1804321090u), + SC(395093976u, 2154850233u, 624748058u, 3473623511u, 530005996u, 1656467301u, 451942772u, 3238178099u, 691726480u, 2563588439u, 3675387583u, 3294893253u, 1205949092u, 3844564019u, 114533547u, 4193437592u), + SC(1241354591u, 1121646490u, 1686974686u, 3373490541u, 1189649937u, 2948191343u, 2978671156u, 3827318062u, 3377194192u, 3805066092u, 3271994064u, 2484020181u, 549626522u, 1166583694u, 3299399570u, 764854172u), + SC(2808929206u, 427994673u, 2338143204u, 3942895356u, 2304289727u, 1468778908u, 1350679341u, 3972686632u, 2399853022u, 2097821409u, 3799931826u, 2500883276u, 1352425312u, 3372587055u, 596007302u, 2017539287u) +}, +{ + SC(172527491u, 737404283u, 1378219848u, 1967891125u, 3449182151u, 391223470u, 304889116u, 3996348146u, 1311927616u, 1686958697u, 766780722u, 1429807050u, 1546340567u, 1151984543u, 3172111324u, 2189332513u), + SC(3269764283u, 1288133244u, 1314904801u, 996741356u, 1884733412u, 1544206289u, 558284137u, 1518251699u, 1924323147u, 1635892959u, 1275016917u, 3776324356u, 1705865502u, 202621081u, 499067715u, 3311904259u), + SC(2660619816u, 3307703068u, 1451637465u, 3851776926u, 2364760323u, 1977782632u, 1515607226u, 1445106389u, 2327693248u, 2319920969u, 1115274896u, 1834441597u, 402374626u, 1205432354u, 1396686295u, 491780324u), + SC(1996097434u, 731516361u, 974312078u, 3421366629u, 3812294134u, 3978884039u, 3352635742u, 1797690428u, 13489496u, 1642706934u, 3128398168u, 106641350u, 4016459895u, 2470770670u, 115922099u, 2925890710u), + SC(2686884812u, 2748914055u, 1937433663u, 756783569u, 413219250u, 1566264233u, 3400883298u, 1726270584u, 1877719428u, 1988282262u, 4210071735u, 1623567192u, 186026227u, 1235988261u, 878101455u, 3591361377u), + SC(4053231115u, 4124107153u, 3534184341u, 1110486344u, 81952807u, 4125498697u, 1693462482u, 2990125452u, 3439709895u, 1055710168u, 4246237022u, 1943085528u, 719511299u, 700284484u, 1082914808u, 1529874921u), + SC(1481485493u, 1935423659u, 913226612u, 2395711383u, 1541429099u, 2771316424u, 3338417471u, 399999946u, 26796724u, 1562275554u, 2290450886u, 1574607684u, 2722372873u, 1229315759u, 1998792801u, 1299123352u), + SC(3949810665u, 1328858449u, 2680298883u, 4060684833u, 1165923991u, 2656262528u, 835037267u, 1633040358u, 3109606689u, 3612027263u, 1850965274u, 2501035455u, 1956880692u, 2989837601u, 2991272131u, 514909703u), + SC(3542886422u, 2995653583u, 3564619313u, 2091503271u, 1371789218u, 2765269616u, 3068810600u, 1666719265u, 2118314133u, 3335278251u, 3361418207u, 807286765u, 899334530u, 3994904643u, 2747385847u, 3528707340u), + SC(3132681349u, 3533155425u, 2330764867u, 3555018576u, 1500828005u, 1243623897u, 1071818853u, 2130356426u, 4099162373u, 1333917673u, 445413180u, 915835391u, 3998951530u, 3932499234u, 2014496944u, 1476384528u), + SC(2104877156u, 1430391164u, 3607724722u, 2456386351u, 3275987562u, 653382938u, 360082336u, 281545563u, 2556998173u, 802173963u, 1898654040u, 2873697709u, 3526274706u, 30023701u, 1532464389u, 335648001u), + SC(1216717657u, 3420164715u, 1026103527u, 2814363815u, 3399248527u, 2265457834u, 4230549954u, 3191596424u, 2096767009u, 197782440u, 661821193u, 3129199915u, 3603027595u, 571989255u, 3350141303u, 902722054u), + SC(86788496u, 2319129483u, 1051755765u, 871757145u, 3910221139u, 2373267495u, 991927221u, 3506242540u, 2918237538u, 555183593u, 3050652275u, 2550066259u, 1935622924u, 1141386013u, 1915989302u, 1193809339u), + SC(2961067645u, 912271025u, 3829956364u, 976054309u, 2426360429u, 3756714048u, 860863671u, 2976390123u, 651422564u, 3348472580u, 4062622529u, 3566918328u, 1262646615u, 526922344u, 336090107u, 3690353753u), + SC(1104160934u, 638409761u, 4090697585u, 3951520784u, 412890746u, 3037968225u, 623962484u, 1861465265u, 4172453316u, 2731726287u, 468253494u, 2636411583u, 2233875405u, 976659501u, 1885152597u, 441456529u), + SC(228814647u, 3127034711u, 536841111u, 970423620u, 335496573u, 1496573821u, 3839638808u, 2076574157u, 3960354230u, 1830746438u, 2136594363u, 1397484405u, 335074021u, 421124372u, 4043995000u, 1296743377u) +}, +{ + SC(2759056966u, 2773771898u, 915395955u, 378399267u, 1065424189u, 3786627878u, 2430240867u, 1910948145u, 1268823138u, 2460932406u, 2049702377u, 3729301642u, 2270156417u, 2935515669u, 1488232015u, 333167852u), + SC(3963231590u, 2717344665u, 3330507643u, 2069094492u, 1576271806u, 844971343u, 3725773593u, 3293220801u, 1933125411u, 1106657228u, 3650404527u, 3511000962u, 3309805512u, 23235466u, 884265026u, 3867812812u), + SC(2380535986u, 2007649740u, 291610222u, 4151143005u, 2330231880u, 3336494284u, 4079710776u, 3045731925u, 300175272u, 1753290057u, 2323446107u, 2448133203u, 1897525100u, 62520621u, 938748110u, 2483424933u), + SC(3941565796u, 4020457560u, 536627435u, 849338423u, 1622694903u, 2253013822u, 1890968103u, 2458058141u, 2431563444u, 3273994144u, 2920282564u, 2871620844u, 315460419u, 2331615405u, 105614140u, 3825521500u), + SC(1770365960u, 436268948u, 2889892729u, 3688514673u, 3952720709u, 1774783907u, 605504449u, 2947048934u, 38294098u, 846447109u, 2199988078u, 482652009u, 58745901u, 1043251865u, 1692020085u, 2977904741u), + SC(3749156389u, 3930496686u, 342096417u, 2961755248u, 1791611872u, 2622150301u, 1430397623u, 2049694734u, 1457522946u, 1307567328u, 1594457791u, 2920040322u, 2838823131u, 3221083429u, 2327375059u, 307491364u), + SC(439175999u, 704562179u, 1530705937u, 343762620u, 1895613568u, 82869187u, 23704978u, 3831637605u, 1611450850u, 923617677u, 3571146990u, 2520538539u, 2376639038u, 2377370369u, 3624250410u, 3615349574u), + SC(764309941u, 395778606u, 890380761u, 1156064327u, 244397938u, 560614464u, 4033284221u, 1090955901u, 3643294611u, 2912576497u, 772374999u, 2861631454u, 564730390u, 3124994653u, 646536012u, 3616789797u), + SC(3040822479u, 2767342245u, 2776280569u, 3485527708u, 3592541314u, 980436690u, 2153312390u, 215781809u, 2169043418u, 2501125521u, 3698439429u, 3999324854u, 2793459908u, 501030861u, 3583683133u, 3712651293u), + SC(4078810936u, 708788696u, 3557269243u, 3488736225u, 3893932756u, 4164798985u, 1241795187u, 3595203666u, 2393791384u, 3416169943u, 714289829u, 1522223608u, 2613922570u, 3640037692u, 3871460094u, 693107847u), + SC(2095442944u, 4280954881u, 166522183u, 982064125u, 4072843681u, 2413289870u, 966372633u, 3054322365u, 3306439070u, 657208192u, 175957468u, 411297739u, 771116169u, 1596617487u, 3454202820u, 2489020407u), + SC(1474971529u, 4158663721u, 2047384831u, 2598838221u, 256974012u, 2456523417u, 631366020u, 3323296862u, 3331748634u, 1360209248u, 3346726166u, 365777010u, 1290850614u, 2085594058u, 2979720197u, 2832663037u), + SC(1555709774u, 2326491405u, 2273744879u, 2585453209u, 2182701308u, 3405285511u, 2624534747u, 1273093088u, 862771016u, 2571185727u, 2627816705u, 753650915u, 1122934423u, 1670176575u, 3747348599u, 2369664950u), + SC(90900628u, 2102730721u, 781890942u, 2802660398u, 1018645876u, 4115262915u, 4149550831u, 3399458752u, 3886843346u, 2763694604u, 1310436099u, 1905281291u, 3814148817u, 4190880658u, 4069475791u, 3679310561u), + SC(2090876031u, 2877257381u, 2723690078u, 1430728835u, 1519931567u, 1820574481u, 3028789440u, 1269332520u, 487867652u, 423473929u, 386546855u, 57358783u, 1188070806u, 1428826466u, 1782333616u, 177182180u), + SC(1560550296u, 3093603077u, 293048812u, 568213435u, 3420818052u, 2217333393u, 3134601365u, 71485947u, 1184987600u, 3737951852u, 162939585u, 1604396734u, 102336303u, 398862141u, 820178097u, 490472018u) +}, +{ + SC(1198357412u, 890731121u, 697460724u, 351217501u, 1219769569u, 940317437u, 2678867462u, 4175440864u, 2131908090u, 1470497863u, 3243074932u, 494367929u, 1767796005u, 457609517u, 3543955443u, 4149669314u), + SC(3330984275u, 2556191310u, 3686726368u, 344917147u, 3386773283u, 2065247867u, 3908122913u, 3695674005u, 2012204991u, 2693522884u, 103992040u, 209624682u, 1376640025u, 3686868767u, 2902487256u, 913177313u), + SC(51667624u, 2920015049u, 3017253519u, 1071812123u, 2571723173u, 2160964558u, 1290623835u, 537361271u, 825729747u, 1392761590u, 1142623949u, 609149740u, 478665972u, 658807909u, 3553467330u, 1636424506u), + SC(3616504574u, 1808500084u, 668829693u, 946464586u, 1979729368u, 406956181u, 4175922839u, 412791377u, 2386664246u, 1192624407u, 2943858119u, 2548487829u, 1705793661u, 3457595727u, 202485393u, 1924721832u), + SC(2189382710u, 4186169698u, 1109472631u, 1983920883u, 3607145598u, 92147950u, 1402492489u, 429006982u, 2674194346u, 4283195956u, 1593180543u, 3760708566u, 643378372u, 4031840072u, 3394015175u, 1558737750u), + SC(1805700700u, 1754525187u, 1654624487u, 2216136944u, 68436239u, 2233918826u, 2968997668u, 4123197178u, 634669625u, 2517670383u, 3007433093u, 3522650191u, 696793327u, 1110232330u, 152147442u, 726198231u), + SC(742639492u, 3149716575u, 880320409u, 4630949u, 1505653181u, 1071542118u, 3069898832u, 2578767084u, 1314905164u, 2213468220u, 3680194608u, 2445142726u, 2802637025u, 3977804516u, 1184600151u, 419058566u), + SC(1336605659u, 403108152u, 2724587657u, 3679190711u, 2874389193u, 1647236788u, 3333657299u, 528273159u, 3515102004u, 947876802u, 3658623910u, 174276546u, 653934448u, 3828171172u, 1444811038u, 2933240663u), + SC(339431464u, 3233735983u, 2646677300u, 43177515u, 392637796u, 1436471495u, 1239428896u, 2348305406u, 2289915967u, 3084305790u, 3250948245u, 178888356u, 2146779246u, 4234024427u, 1032696742u, 3905672369u), + SC(961540617u, 2841143833u, 962675692u, 4171962245u, 2791421965u, 2368576296u, 3328980779u, 2916707843u, 1558316022u, 134331787u, 2460382133u, 1215270659u, 146717643u, 3198704598u, 2091590890u, 2460305557u), + SC(1042706599u, 2034894580u, 690504458u, 2345543782u, 4005260856u, 2432547988u, 112379796u, 3543073874u, 835904670u, 2590827554u, 918469413u, 3408148837u, 1789043194u, 1729294718u, 1834822488u, 2928788408u), + SC(3301658713u, 837504950u, 1727706187u, 1845900341u, 896114239u, 2352826711u, 3111232113u, 2017659422u, 2679415011u, 2370224692u, 3953323203u, 2250773775u, 1103871456u, 1933857783u, 3328123972u, 3307902309u), + SC(1767706194u, 3006067357u, 35851140u, 3240494485u, 2221989856u, 1899667734u, 6385932u, 2363969169u, 4105037265u, 1831329288u, 2027489194u, 884350865u, 1094001278u, 159320441u, 4110377537u, 68569781u), + SC(1525490260u, 665735034u, 2452169880u, 171203360u, 1236274187u, 676156893u, 1374080130u, 357190845u, 1839504596u, 1514713169u, 4060710869u, 1096636593u, 2588809028u, 3627704311u, 1809407212u, 476953361u), + SC(957000182u, 26105440u, 3440739633u, 2098069989u, 1584380370u, 2860012851u, 1732766592u, 212521659u, 3179187407u, 887560394u, 2490695882u, 2732057577u, 1018218231u, 3635922188u, 2062474881u, 2513446682u), + SC(1107263183u, 578424674u, 37103195u, 466969755u, 2523291988u, 291121216u, 3279675483u, 2003600853u, 4199013737u, 2715326244u, 4169142308u, 3686083459u, 3512922856u, 3093381668u, 1195683747u, 1393205701u) +}, +{ + SC(1331866444u, 3086683411u, 308412705u, 2554456370u, 2967351597u, 1733087234u, 827692265u, 2178921377u, 289799640u, 3318834771u, 2836568844u, 972864473u, 1500041772u, 4280362943u, 2447939655u, 904037199u), + SC(2575383612u, 3753748540u, 2811819999u, 1587868018u, 1038431720u, 790984055u, 3731301644u, 1846621966u, 951964491u, 415041564u, 2200992348u, 4272384400u, 296027191u, 4287888493u, 2854418940u, 3573682726u), + SC(1970740379u, 2607713160u, 3470587124u, 930264002u, 1173824281u, 122965335u, 3335069900u, 326806848u, 3632692886u, 129472919u, 3226625539u, 2728837633u, 416887061u, 1130551300u, 356705234u, 1369994655u), + SC(4223755401u, 2079062379u, 3389104769u, 4073338565u, 3689225172u, 440818499u, 856809827u, 381405275u, 127244068u, 376610605u, 2598268701u, 2534766433u, 2820385475u, 4294123141u, 330930335u, 318185845u), + SC(761419527u, 3536226585u, 2328998689u, 3591334816u, 1578134205u, 1103093801u, 3418753973u, 3588283844u, 1530820786u, 2684864777u, 924992522u, 3557568163u, 1869705595u, 3313643247u, 841618349u, 1632346896u), + SC(3475240082u, 1688964704u, 2950217939u, 2829510968u, 4218043142u, 1723444205u, 599182149u, 3585292920u, 1201476124u, 1461631424u, 3796636907u, 3015591958u, 325310290u, 4221903599u, 2685464188u, 843835594u), + SC(3270571096u, 3849271420u, 2838244847u, 4029431364u, 3703574760u, 3266810236u, 1964057057u, 1045028730u, 3535646880u, 4117469088u, 268273252u, 28527135u, 616206627u, 3498685014u, 1783632491u, 2430589238u), + SC(1270864764u, 2335784868u, 3187652054u, 3487500065u, 3514696661u, 4279511860u, 2691960889u, 1283768022u, 3239440117u, 3088430000u, 3270700109u, 2562105500u, 920167200u, 797042551u, 4008345612u, 1713652205u), + SC(1233553764u, 2449552413u, 3139739949u, 2886523083u, 3648218127u, 435238208u, 231513377u, 3598351734u, 1003225207u, 1550611030u, 4262337852u, 2819804714u, 3244463273u, 2073740987u, 855086785u, 975917304u), + SC(2715954175u, 3495328708u, 4029028922u, 3684471179u, 2815956881u, 3599669751u, 4163140273u, 33191313u, 2635890672u, 3683103094u, 1579697202u, 287936530u, 2496546027u, 832886459u, 1241267398u, 3564329642u), + SC(718666875u, 1628061148u, 3834972005u, 11037458u, 3790987439u, 2312775807u, 3375415349u, 3089087440u, 2679862136u, 918687461u, 3176925215u, 1435039099u, 1342114588u, 1906963252u, 3488735014u, 1611160706u), + SC(4216184459u, 1084561028u, 249927207u, 3584932419u, 1355984265u, 990857900u, 1870305536u, 582023708u, 1966962179u, 1733088207u, 1190083164u, 3785297292u, 1004947745u, 1784159416u, 1841702516u, 180335137u), + SC(4084089742u, 2441136551u, 426220168u, 1375299216u, 1841338030u, 1250354698u, 2728864721u, 2959990011u, 1071025467u, 1691914484u, 2858760972u, 1516700275u, 2771651049u, 607063247u, 4219381388u, 3373946171u), + SC(2146554811u, 2380633398u, 431356428u, 2501496525u, 4195490782u, 4281443977u, 1707183170u, 3515016439u, 43334925u, 2064458077u, 4149827026u, 2544422546u, 1259302114u, 1919625668u, 729425798u, 2757346641u), + SC(2475010648u, 501654469u, 1262984133u, 2284058265u, 3864896735u, 3216144340u, 3043718887u, 3290359029u, 2513504704u, 1583873907u, 787550022u, 889877880u, 4155285556u, 2519357244u, 1887123831u, 2544852082u), + SC(1329107374u, 3899397847u, 1931705980u, 3537599611u, 2074239136u, 1267070685u, 2447524924u, 3173107761u, 2842541385u, 924561908u, 2664553616u, 395476463u, 813764142u, 3107511895u, 179660379u, 2380654703u) +}, +{ + SC(286197159u, 1217476806u, 1373931377u, 3573925838u, 1757245025u, 108852419u, 959661087u, 2721509987u, 123823405u, 395119964u, 4128806145u, 3492638840u, 789641269u, 663309689u, 1335091190u, 3909761814u), + SC(2458775681u, 3448095605u, 3846079069u, 1243939168u, 2712179703u, 2514528696u, 1400411181u, 3792085496u, 528921884u, 1230512228u, 4062090867u, 931590129u, 3669288723u, 1764179131u, 2650488188u, 764612514u), + SC(3981461254u, 1881876860u, 3861653384u, 1419940889u, 3890280301u, 225359362u, 3772709602u, 2406778923u, 1744011295u, 836946168u, 1547583643u, 2969842237u, 3997288340u, 2150480638u, 3129156617u, 1325216902u), + SC(3592470591u, 3671101194u, 2792523734u, 2070472959u, 1473838345u, 785123121u, 2721504084u, 2212009910u, 4070989896u, 1696639999u, 2859248441u, 3104578877u, 2309769016u, 4267049236u, 2484173427u, 1626540609u), + SC(4267160019u, 2981312649u, 344263087u, 698599319u, 1002907346u, 93565259u, 286808078u, 1804582990u, 3599771325u, 2181306538u, 1961279765u, 187428107u, 223299791u, 4043449191u, 587626985u, 2106033479u), + SC(501761768u, 2386293097u, 1180388710u, 1812775472u, 918601490u, 3009070794u, 1574279477u, 1505824867u, 3643095372u, 3370828988u, 832869144u, 404837899u, 3152252263u, 3925885097u, 69867335u, 3741018586u), + SC(2051920526u, 1020215512u, 2058830843u, 1611771091u, 2552120098u, 75944844u, 1802229404u, 915313553u, 2313215016u, 1745739579u, 443475191u, 2998247588u, 3289885130u, 1289464560u, 2961919458u, 3798282256u), + SC(1496487624u, 2215532014u, 4148657376u, 3923080315u, 216179279u, 3856996518u, 2014567019u, 880786726u, 2125033974u, 58008256u, 4039109547u, 402585883u, 2182540617u, 437175766u, 1441865826u, 1665450276u), + SC(3078919323u, 1109978808u, 3102316446u, 4252174800u, 1046362670u, 3864571927u, 2260100326u, 3682270765u, 2139319322u, 1066628173u, 240059747u, 1164853046u, 1454716611u, 512654137u, 1544275853u, 2556727566u), + SC(580428655u, 115762757u, 1593355348u, 2740341778u, 1504897999u, 975028678u, 2401832824u, 4197869940u, 3667767462u, 644880229u, 691878327u, 369150353u, 4026243769u, 737605979u, 2791271214u, 2620684209u), + SC(624678531u, 4114750403u, 1274989179u, 1531504358u, 3520816024u, 2554021149u, 1865577096u, 1362433716u, 1638936249u, 3016959317u, 2526207810u, 3033412199u, 695904139u, 2060012285u, 3230414132u, 860289224u), + SC(3442642063u, 1520946900u, 218826564u, 968761561u, 4098434233u, 3360677602u, 2204368028u, 486310067u, 2601372374u, 1399175099u, 2183933043u, 806379489u, 2424203087u, 2668736829u, 1664637882u, 3005713727u), + SC(700899790u, 1066183324u, 3546718434u, 998702102u, 2557230354u, 2084117292u, 2934243163u, 1545771642u, 3688392810u, 3908656537u, 3447657276u, 840000010u, 2955752477u, 44371204u, 3799655472u, 3734995825u), + SC(3265506533u, 942399325u, 173917125u, 161041810u, 2297418901u, 849604788u, 2703870825u, 2810175425u, 3617296913u, 1432689375u, 3133875354u, 1118654553u, 2616257301u, 495686053u, 4127407123u, 1943733376u), + SC(2005668850u, 485568946u, 2260461782u, 2622034876u, 2693998905u, 2811925574u, 2831747304u, 3217266392u, 2520502878u, 1176196783u, 2567958416u, 1525744035u, 2841811417u, 1157609637u, 3871707993u, 2765099676u), + SC(207989197u, 368293876u, 3237374184u, 1394768686u, 1254103141u, 935691540u, 375090092u, 2481205522u, 2920254212u, 492683984u, 2055637221u, 4291235240u, 3889542314u, 2465899605u, 1694380507u, 757371549u) +}, +{ + SC(136266275u, 1782161742u, 3530966629u, 586004249u, 4076565170u, 3312577895u, 876489815u, 1337331291u, 888213221u, 1813863938u, 1374206604u, 2668794769u, 1377764865u, 784024905u, 1937217146u, 3627318859u), + SC(3161427495u, 2344678392u, 1808682441u, 2396619894u, 3034006140u, 1044331129u, 4102609084u, 1058091322u, 1515502621u, 1258860285u, 1406233340u, 127619173u, 3057107171u, 225762630u, 1651671815u, 4285298193u), + SC(630785468u, 1344100570u, 1929331818u, 828088181u, 2313124884u, 1302120759u, 3180735860u, 313275450u, 1008942268u, 2707820177u, 4248947940u, 1732478629u, 3645496831u, 611830707u, 1937638387u, 61731419u), + SC(1347537282u, 2857000226u, 227299159u, 1108544547u, 1181072563u, 1291715943u, 3752803919u, 2688390945u, 2484326219u, 1350060758u, 452823659u, 2363636452u, 2152205190u, 1812507720u, 607624535u, 2319475408u), + SC(3222638329u, 3875752446u, 758301165u, 51152840u, 2430504171u, 1189996379u, 44948392u, 232960619u, 3026371583u, 2974537914u, 3244781723u, 3702394182u, 2835938901u, 663347918u, 3320069474u, 3071978352u), + SC(1947047272u, 3022037725u, 949698504u, 1728470528u, 283847009u, 1458268020u, 360012619u, 1579646653u, 4005878207u, 1765381301u, 20903539u, 2558445559u, 757888638u, 2604781527u, 2240457927u, 3990518442u), + SC(4281545336u, 1208697934u, 2578865021u, 2456188396u, 1796646478u, 3757714293u, 2622755030u, 1606025966u, 30472258u, 3850691354u, 1208779266u, 405050222u, 3807844323u, 3748806955u, 358470323u, 4212845387u), + SC(2041619043u, 3711576883u, 835794591u, 2392116351u, 2862318436u, 689502669u, 2866163103u, 2052898811u, 576580608u, 1144506306u, 542475550u, 474572979u, 4137279429u, 2221684538u, 331268239u, 1556318477u), + SC(705880713u, 2092991958u, 815360595u, 3449491044u, 1305192012u, 2057063005u, 3299868133u, 1114733861u, 730760330u, 1129737257u, 4233249504u, 1217580888u, 452658791u, 2612091783u, 1764043106u, 1669202162u), + SC(3689992902u, 700129090u, 282055655u, 756126609u, 382876308u, 4262209576u, 2436932760u, 484247369u, 1415138625u, 2340918814u, 3058199817u, 4145497883u, 334812059u, 461523021u, 2221122791u, 2995497332u), + SC(706669295u, 3007808000u, 3728730665u, 3241577762u, 3126001367u, 292940936u, 1126531898u, 3913205978u, 304146054u, 2548053118u, 3490807704u, 3465095661u, 3938930443u, 804039554u, 297557674u, 1669808877u), + SC(2395818908u, 3199065200u, 4060875213u, 1731284266u, 1022607637u, 1154299144u, 3879751917u, 384430926u, 86892497u, 2036004815u, 2668116514u, 901861508u, 2277490553u, 1312485879u, 562264334u, 170374972u), + SC(2192479620u, 3046309306u, 143307916u, 3468295982u, 3110013374u, 699221760u, 273412494u, 3153322038u, 2886126025u, 1296005576u, 2326933823u, 3713038344u, 919578907u, 258326637u, 1991591857u, 604405680u), + SC(3283196708u, 902217854u, 1295144146u, 503984315u, 566424671u, 1755595238u, 2455519229u, 120267530u, 1004363245u, 1611271287u, 1013059281u, 3646183010u, 183890924u, 188417891u, 1612883046u, 2255154239u), + SC(1231171449u, 2524105034u, 653815517u, 585754026u, 3098352226u, 866901449u, 4223318963u, 1071806142u, 3239364285u, 4077877700u, 423690458u, 2222266564u, 4117269051u, 1893556406u, 3304547745u, 215164118u), + SC(3229321461u, 3443938850u, 803179772u, 3340311630u, 2749197592u, 565049216u, 1674980657u, 45735981u, 3858875409u, 2208179057u, 2167864606u, 3853383863u, 3320158569u, 901453102u, 2505912317u, 1486241881u) +}, +{ + SC(768143995u, 3015559849u, 803917440u, 4076216623u, 2181646206u, 1394504907u, 4103550766u, 2586780259u, 2146132903u, 2528467950u, 4288774330u, 4277434230u, 4233079764u, 751685015u, 1689565875u, 271910800u), + SC(2894970956u, 471567486u, 2880252031u, 2717262342u, 4077383193u, 1268797362u, 4257261832u, 2560701319u, 2691453933u, 1607372210u, 2771176414u, 58794458u, 4272438220u, 2521311077u, 642919262u, 3613569198u), + SC(549667688u, 1635817891u, 3597742712u, 2133548191u, 983618585u, 1077056145u, 1016537981u, 3024916594u, 3788763915u, 2354027825u, 234019788u, 1129974745u, 3836449602u, 132091652u, 2429034711u, 3714188356u), + SC(3752023309u, 1237246457u, 810507218u, 1575719630u, 2984629402u, 1312110059u, 1532351529u, 3778270553u, 500991970u, 3016414634u, 2451804626u, 3116044735u, 2749076428u, 609078974u, 343845623u, 1628221103u), + SC(1079050562u, 537097107u, 2113045556u, 1216978919u, 795109794u, 494396817u, 3615304214u, 3016596136u, 1485503229u, 2246940765u, 2872639209u, 812577075u, 3970992077u, 816616346u, 4279493103u, 2696304890u), + SC(302016674u, 1709668681u, 88411267u, 3337357281u, 3061995584u, 3396993199u, 1858891069u, 2509301562u, 3807375387u, 3567949934u, 3737724046u, 4137514111u, 1709156749u, 1400722499u, 3253197246u, 830289695u), + SC(86642997u, 2517748533u, 1802616926u, 3224858276u, 667521935u, 294768443u, 3699185630u, 2619978653u, 1654256627u, 789295435u, 4056501046u, 2298266369u, 3425028365u, 3740463800u, 2064449616u, 423401599u), + SC(587205175u, 208206623u, 1253389730u, 3674422134u, 284316357u, 2112208954u, 1196434050u, 302049830u, 985808817u, 4037289748u, 2191325460u, 4289570719u, 592322138u, 3671063901u, 886295122u, 2540475213u), + SC(2164961127u, 4048157441u, 2790139366u, 1435011700u, 4142835891u, 3320410016u, 2681849481u, 1047872443u, 2885564134u, 874029678u, 2048520878u, 2934385850u, 1097367713u, 1997417466u, 2045706034u, 898129538u), + SC(3451958921u, 95403444u, 4056502814u, 671939501u, 2069116441u, 3101129770u, 553516228u, 1712496197u, 2639919391u, 3157824758u, 2182076931u, 2920510603u, 91421090u, 3496854290u, 1333938225u, 2005754623u), + SC(469295760u, 426796598u, 3855795018u, 970866434u, 856973549u, 2439780350u, 2385957015u, 2589908140u, 3781058972u, 4109407963u, 32316753u, 3931244779u, 68560366u, 1699148814u, 843806029u, 3772908229u), + SC(3846833357u, 4119412096u, 438094070u, 2645426661u, 884548695u, 2876447138u, 80918210u, 2029354870u, 135282137u, 3030947473u, 2960763605u, 1898348122u, 4127316996u, 2240743006u, 2934791826u, 887094286u), + SC(1897883656u, 1406242187u, 2434671426u, 2734794757u, 2714201131u, 3046668149u, 257451999u, 3794951424u, 152449195u, 3454838096u, 2737741298u, 821046884u, 2554260361u, 962889686u, 1262263641u, 2203109889u), + SC(1985684731u, 222483668u, 2849949193u, 1221492625u, 2084499056u, 1235444595u, 2655267198u, 1020186662u, 1447071023u, 3629752849u, 651251319u, 2167418603u, 2268535831u, 2985934672u, 2652239173u, 3259021212u), + SC(3062826974u, 1796450254u, 1939504794u, 476729966u, 3521076442u, 3086668105u, 234121934u, 986487065u, 1570879569u, 2820662853u, 1206879400u, 4271520206u, 4242315964u, 2749978648u, 3007865079u, 4114755771u), + SC(3649818358u, 3409857055u, 1537210569u, 2398557069u, 3130583052u, 536941530u, 3880813719u, 1419070102u, 1164730147u, 2533104753u, 2046210979u, 2821557175u, 2327264610u, 1639358616u, 2001893732u, 1524105344u) +}, +{ + SC(294473811u, 4198428764u, 2165111046u, 977342291u, 950658751u, 1362860671u, 1381568815u, 4165654500u, 2742156443u, 3373802792u, 668387394u, 853861450u, 2637359866u, 2230427693u, 2824878545u, 103849618u), + SC(3462974251u, 3960356708u, 3970663027u, 1911703734u, 2602955995u, 2496279357u, 210580885u, 3874806640u, 2822070051u, 4063068709u, 2061277285u, 1429537360u, 2349584518u, 2910686068u, 3963567776u, 3972103816u), + SC(2016723458u, 2541590237u, 3532225472u, 3001659539u, 112442257u, 922189826u, 2246032020u, 3487464820u, 1658786807u, 2276379919u, 1596562072u, 457926499u, 2193005220u, 2575074329u, 529788645u, 1519231207u), + SC(1572936313u, 886315817u, 1530415140u, 2311860166u, 3941188424u, 45807153u, 2483174955u, 1469805839u, 3162970586u, 2454510043u, 2417743140u, 2783896043u, 4229304966u, 1351489836u, 284407686u, 4050060666u), + SC(1089549454u, 2684562245u, 1059803961u, 224950790u, 58262787u, 3033299806u, 927475933u, 1400133226u, 3082832878u, 1490904482u, 3040968407u, 593844137u, 1569781919u, 798746464u, 1083127814u, 1590280691u), + SC(1538536818u, 1828650047u, 3754703497u, 985555578u, 1002045074u, 767791702u, 915104522u, 465342914u, 1114045622u, 3426575950u, 1922317875u, 1070157234u, 3077282627u, 509171365u, 1607316331u, 668038565u), + SC(3323765415u, 1224391265u, 2469548057u, 3722781348u, 3031269370u, 4289586349u, 2226931390u, 957179955u, 2298143215u, 388542993u, 1780793152u, 2112973240u, 1502081645u, 1973971844u, 934878133u, 1618693887u), + SC(3954817210u, 3380652139u, 2572526672u, 1228436929u, 465848053u, 3939966705u, 2398020514u, 2900599831u, 2007674400u, 2727714272u, 2337519533u, 1681172994u, 4089802218u, 142069883u, 4261364192u, 2856729470u), + SC(4248537414u, 694781904u, 571619480u, 3221145068u, 2970038253u, 3370542615u, 2832314379u, 1807587465u, 1411648700u, 1964173012u, 121911610u, 1134463822u, 2574507072u, 885427058u, 3741638072u, 3097389771u), + SC(2158675312u, 116080836u, 3333803512u, 3797833536u, 984464391u, 4149942538u, 1145746749u, 1195624987u, 426540232u, 1021913877u, 3121679962u, 3390873776u, 3273678689u, 3851165262u, 4274383191u, 1915176720u), + SC(1158541955u, 1843489443u, 998849897u, 969171492u, 1791167915u, 2484857096u, 1119081920u, 1901041264u, 2534183757u, 1529097558u, 2956376281u, 1260291681u, 1159207651u, 3441978306u, 2518693280u, 4253362775u), + SC(1690661001u, 2213259738u, 3615956917u, 105152953u, 308358176u, 1328282355u, 1666389191u, 1019854259u, 2059193948u, 4244545599u, 1952864052u, 329670934u, 3592985517u, 571024701u, 1172799188u, 3135874872u), + SC(1184018396u, 889004172u, 1920099477u, 1964506637u, 189152569u, 1805931691u, 3250067608u, 3446883320u, 1471577127u, 2315956523u, 1588897116u, 2470229082u, 3602241877u, 554726955u, 1644067322u, 87402371u), + SC(1360270758u, 326216664u, 3362619326u, 1255989535u, 4140691901u, 856602972u, 2084629207u, 3858539838u, 78510889u, 2277092409u, 3136284616u, 1772786459u, 3229606238u, 94732571u, 2598206327u, 492226777u), + SC(1257123658u, 2873597433u, 3001150814u, 421725801u, 236310867u, 582305583u, 3367057659u, 2102668336u, 153914902u, 4226436363u, 290094468u, 690656835u, 1748591179u, 3668885459u, 165028339u, 2139821087u), + SC(2349582063u, 631395785u, 941018791u, 1503410647u, 181331585u, 2473834542u, 2528647747u, 3710284323u, 2364124560u, 3901998444u, 3224972026u, 605068436u, 546878913u, 356944705u, 3829683853u, 160452346u) +}, +{ + SC(1451965994u, 766802222u, 1324674662u, 350355960u, 2823290314u, 951779387u, 2914020724u, 508533147u, 1932833685u, 1640746212u, 1238908653u, 542788672u, 3642566481u, 2475403216u, 1859773861u, 3791645308u), + SC(216282074u, 1906267522u, 1852437064u, 1010678235u, 3729121535u, 4197231849u, 4150055440u, 1128246703u, 3264673345u, 1375783733u, 3415088931u, 34309836u, 2603881793u, 3106237815u, 2950890176u, 505684202u), + SC(3927516830u, 2488673756u, 327917152u, 614182630u, 2355346359u, 730432873u, 88446505u, 4240960753u, 4121410433u, 1398090547u, 2262743232u, 651724036u, 4138228417u, 3106475766u, 4179362424u, 750466827u), + SC(434692713u, 3111300976u, 3323560909u, 3413395188u, 601658363u, 2967722170u, 1070605430u, 74966422u, 813799229u, 4061279746u, 1996953298u, 1765274397u, 4035137864u, 2359104373u, 3535793255u, 618634298u), + SC(1231617791u, 3545122377u, 2628213180u, 2391855988u, 3734909337u, 2705206020u, 681643510u, 368801430u, 691450613u, 2224147576u, 951972679u, 2767063862u, 3676868191u, 158497152u, 2165075628u, 2832330233u), + SC(3529008459u, 1174295398u, 55914117u, 2816083797u, 205887723u, 1756010196u, 1648915894u, 1477354329u, 86311333u, 3889682737u, 1098085375u, 3464880379u, 1139759451u, 542536350u, 186494667u, 2442759451u), + SC(3094023174u, 1995851063u, 4191388160u, 1722723757u, 1329293492u, 727282912u, 2669776257u, 2772951118u, 1386276034u, 3089621174u, 2303649396u, 2292749559u, 1467806712u, 266878652u, 2651863592u, 1006978704u), + SC(2450691869u, 3012269556u, 3887712993u, 4048656504u, 2160727935u, 1940770088u, 174916584u, 3472792113u, 2648524840u, 990354037u, 1957678544u, 3888925732u, 1168435347u, 3720532709u, 3528212798u, 2624020545u), + SC(69863181u, 2459013627u, 4217968964u, 2735851825u, 1081344097u, 737361378u, 2157825722u, 2900791120u, 1412000158u, 1206005337u, 3067055303u, 230632577u, 601427243u, 2760861753u, 3679310020u, 2091861010u), + SC(2304197829u, 1531316041u, 2716383108u, 434697890u, 508817514u, 2929310544u, 3751532879u, 3785491984u, 2716598214u, 3666495867u, 3150261948u, 1306653078u, 2283636929u, 2492138954u, 1527136744u, 3312103429u), + SC(3387483809u, 1095455990u, 3248396980u, 3181117152u, 2258888938u, 2053848664u, 2160875912u, 553275695u, 1752757914u, 1504034431u, 1046528434u, 1855690339u, 2425857774u, 2142030048u, 237252438u, 3919745098u), + SC(3690358562u, 221287988u, 2268047572u, 3655202989u, 756646724u, 68846869u, 1965143185u, 513684595u, 404949341u, 3706987369u, 15990563u, 3409604325u, 658214808u, 2112012281u, 1742449680u, 1802932879u), + SC(2972942716u, 4184192946u, 4124576773u, 3089123761u, 1179063207u, 2093485395u, 512951348u, 59239037u, 3674464770u, 787225894u, 1288484371u, 1987692265u, 3767465580u, 4044585132u, 2916653148u, 2297816723u), + SC(3784876742u, 1057734114u, 4078669159u, 2003536621u, 3146165592u, 3800656487u, 297129408u, 4248472894u, 3906942491u, 4017607636u, 1285879766u, 3310681130u, 2653159866u, 2524355569u, 84128323u, 2374174391u), + SC(1598027967u, 344901367u, 413901309u, 2414916476u, 417612014u, 1371467558u, 1499802638u, 967537237u, 1571117481u, 1088564682u, 3141693657u, 833402800u, 723113978u, 882224086u, 3586817872u, 3592950853u), + SC(513582137u, 3376206006u, 3649593908u, 274710963u, 395026609u, 3340190413u, 1543782101u, 90195397u, 4157807658u, 412153222u, 558068169u, 2001737608u, 3474337160u, 1679447360u, 12885220u, 843004632u) +}, +{ + SC(2083716311u, 321936583u, 1157386229u, 758210093u, 3570268096u, 833886820u, 3681471481u, 4249803963u, 2130717687u, 3101800692u, 172642091u, 421697598u, 4220526099u, 1506535732u, 2318522651u, 2076732404u), + SC(3635330426u, 3675180635u, 4282523718u, 1750526474u, 1682343466u, 1292539119u, 2893227939u, 2897346987u, 1855384826u, 3916002889u, 4211021149u, 3439442996u, 241993264u, 1634586947u, 29890244u, 2635163863u), + SC(2111268073u, 1081371355u, 3873218083u, 4044562588u, 2141674529u, 2107952064u, 3689043955u, 3423481956u, 2548188353u, 2697516682u, 4235866514u, 2985306600u, 3687062917u, 2383095614u, 206503719u, 2548448480u), + SC(961167287u, 839569057u, 3482959339u, 4268254472u, 364097642u, 1343091094u, 3226753483u, 2159507482u, 3968394805u, 2518014496u, 3451298154u, 38127252u, 267735247u, 3484363065u, 957363479u, 1698662790u), + SC(2744437828u, 3863759709u, 3010153901u, 3500431594u, 2624982656u, 875272695u, 1378345519u, 1791692262u, 3726226549u, 2682325366u, 3925052276u, 389591343u, 3869112658u, 650251545u, 6263093u, 860194434u), + SC(309822299u, 841707800u, 2661553828u, 3383039256u, 238699224u, 1100968507u, 3534897900u, 4177846894u, 3463859410u, 1435499569u, 2006933774u, 3007046995u, 2819231184u, 288756524u, 1854189890u, 3858081977u), + SC(2088052675u, 3396090720u, 416722812u, 2597822221u, 1176386826u, 3290882216u, 1002529034u, 2156491632u, 4202546863u, 1988253003u, 164033721u, 941800849u, 1186836065u, 2298291750u, 1863561032u, 1437279190u), + SC(2858016010u, 775169843u, 2706497878u, 2821546952u, 2660836656u, 2077717717u, 3498848893u, 658545289u, 4048269927u, 418273988u, 1144587321u, 3094511386u, 4122354470u, 4225741678u, 603926280u, 979427875u), + SC(1933550557u, 635706492u, 1314164193u, 391588743u, 834468642u, 1475393570u, 467867971u, 1271027212u, 2540684860u, 3801872764u, 1235100171u, 2159823063u, 532708943u, 665828867u, 4215955726u, 3885758496u), + SC(3602864699u, 4002116109u, 644187852u, 1895585048u, 2776091504u, 72205071u, 554242761u, 4049640413u, 3149249833u, 688714164u, 687706448u, 3680924185u, 2274039047u, 303853541u, 2977107717u, 1196398757u), + SC(3014099531u, 1302405838u, 17960870u, 4110705157u, 3801652109u, 2085339416u, 223612049u, 2870889264u, 3353629397u, 3527061798u, 674241336u, 3525864585u, 2278818471u, 2069831593u, 2885891701u, 1329881521u), + SC(943450806u, 3704544104u, 3603194299u, 3757910007u, 502151885u, 765197432u, 4190577627u, 771063523u, 2436865367u, 678307964u, 1498061278u, 4120830837u, 3369466394u, 3399332765u, 1670894068u, 2891073104u), + SC(501595739u, 1876059299u, 4182005344u, 160804770u, 962098784u, 2636270989u, 1828906496u, 1316975808u, 4088133273u, 2943366134u, 216957582u, 1003216568u, 4242258589u, 3505873185u, 2810125978u, 3429220861u), + SC(2021386647u, 4046435053u, 1951135097u, 3941871277u, 2261999657u, 3808836272u, 2028063026u, 3659044589u, 3595750274u, 34514326u, 1889867282u, 1898224864u, 1659225476u, 3153868894u, 1647148554u, 1185039302u), + SC(4119269244u, 1304843028u, 2354051818u, 2031439365u, 533555049u, 1418960734u, 214120313u, 4187370667u, 4256529561u, 2635160409u, 1836564249u, 3828261559u, 3235640513u, 181194540u, 4018312346u, 680914749u), + SC(1914329770u, 3317667974u, 1413160514u, 2952053282u, 3332782151u, 3751637695u, 2146129829u, 167804454u, 2499496888u, 4213150810u, 223599992u, 2197202825u, 2869811316u, 2635473358u, 952082661u, 1532017334u) +}, +{ + SC(701959589u, 2450082966u, 3801334037u, 1119476651u, 3004037339u, 2895659371u, 1706080091u, 3016377454u, 2829429308u, 3274085782u, 3716849048u, 2275653490u, 4020356712u, 1066046591u, 4286629474u, 835127193u), + SC(897324213u, 739161909u, 1962309113u, 3449528554u, 2634765108u, 226285020u, 2832650161u, 324642926u, 2242711487u, 162722959u, 2264531309u, 2307017293u, 4006636248u, 1035416591u, 2557266093u, 3957962218u), + SC(1912896448u, 699621778u, 2975109255u, 1580597872u, 2818493758u, 515803157u, 1642586345u, 785148275u, 2098287545u, 1424779842u, 1039209855u, 4238164284u, 4173562747u, 3569896384u, 1089361492u, 1858690350u), + SC(2757340308u, 2538321018u, 2388474793u, 379482919u, 882562385u, 3129659692u, 4216198588u, 3565768337u, 1772023241u, 2931080253u, 3451485646u, 748689895u, 562737327u, 663797632u, 3315310934u, 2629536884u), + SC(242169331u, 1243063456u, 175561111u, 2950276224u, 3213816292u, 692329775u, 3181354285u, 3015261169u, 1744760252u, 3733849950u, 4219512025u, 693702734u, 2844842003u, 722286940u, 2391355922u, 3564773447u), + SC(2291286292u, 966238959u, 506903622u, 2122264528u, 1392182009u, 3447321781u, 3873294792u, 1373792940u, 991667700u, 2332723711u, 2764968211u, 2471301595u, 649629323u, 783169152u, 1459916213u, 3846736182u), + SC(2664330880u, 1149932862u, 1416201114u, 318583284u, 4140857901u, 1128356267u, 1095497693u, 1624736741u, 761312690u, 241788645u, 2036924781u, 1946525101u, 3225208750u, 4156033061u, 2590150721u, 3771407135u), + SC(2862143077u, 233168744u, 2659004990u, 155440145u, 3918377979u, 1360152661u, 627903232u, 1469886352u, 2876841580u, 3955906097u, 580277652u, 3039511497u, 1597126708u, 1404269416u, 42059925u, 2098341602u), + SC(812381463u, 3272442363u, 496180006u, 1236237424u, 2267310113u, 2237850197u, 1113026387u, 716498059u, 3503382440u, 328287114u, 1410789607u, 477863076u, 1362085890u, 3569642059u, 2006757845u, 675415451u), + SC(747557402u, 4212477852u, 3286869720u, 3708058361u, 3240421074u, 1188732842u, 916816078u, 2444327052u, 2111479336u, 1745064524u, 3637408011u, 3599633029u, 4230973048u, 1160089497u, 1136388910u, 4138160782u), + SC(1255139572u, 1856599651u, 1458352865u, 3271906169u, 3410637086u, 2119040671u, 1680850868u, 413922813u, 2782309328u, 3561735700u, 3723648708u, 609378416u, 268989415u, 3293584485u, 3271843364u, 1954072630u), + SC(4155626312u, 931793228u, 1049414704u, 1037617746u, 265265177u, 616902615u, 844384832u, 3477591939u, 3106685802u, 2357099686u, 1845236259u, 3355104451u, 3327830357u, 3100545339u, 1162051156u, 2646331847u), + SC(514329180u, 948073745u, 1774920952u, 105860125u, 2811186644u, 1695131452u, 940976033u, 2019732362u, 309099076u, 1607914408u, 4118428245u, 1337868060u, 3952860679u, 2578427283u, 265792106u, 295755030u), + SC(3882528435u, 2629929072u, 1617404150u, 1421619579u, 2309432083u, 724299897u, 2666040048u, 1096383838u, 1836447402u, 426930713u, 3934220119u, 3232225281u, 1000075862u, 3631628825u, 3529619355u, 1219322120u), + SC(3335633324u, 4194223138u, 3901817518u, 1335914529u, 3871871049u, 3709757137u, 3499113177u, 235348888u, 781652835u, 1102256292u, 3754223033u, 833068853u, 4178470716u, 1807198743u, 2733399861u, 3740356601u), + SC(228568838u, 3126580587u, 4000897922u, 1303869372u, 3850020302u, 1548458239u, 2356371812u, 3570971356u, 2544858219u, 4220062752u, 2062616152u, 953792592u, 764216612u, 2052428514u, 2314665964u, 2792116584u) +}, +{ + SC(2022030201u, 622422758u, 4099630680u, 255591669u, 2746707126u, 492890866u, 1170945474u, 626140794u, 2553916130u, 3034177025u, 437361978u, 3530139681u, 3716731527u, 788732176u, 2733886498u, 780490151u), + SC(4207089618u, 3411945447u, 1960753704u, 3552759657u, 1130668432u, 848791484u, 3810908171u, 353148861u, 3312275539u, 2963747704u, 2966813687u, 2483733320u, 2880725255u, 463405312u, 3340834122u, 1292390014u), + SC(2664721153u, 4108676217u, 2604619822u, 775242570u, 636236518u, 2873717047u, 1857718302u, 2091477716u, 1586310695u, 2528697445u, 2256487867u, 2787362203u, 2741360704u, 496928924u, 601271512u, 3586110309u), + SC(1791685197u, 4242641311u, 3369628733u, 2052809939u, 806398185u, 3412279529u, 1946210627u, 1398934260u, 3077042954u, 2276630414u, 814388665u, 1749609309u, 3367688729u, 1959714965u, 2411157301u, 2263996211u), + SC(439326213u, 4256425445u, 876987216u, 1314194194u, 3010100734u, 1576065730u, 598365157u, 3705087566u, 3427486218u, 1877721147u, 358249820u, 410263983u, 1386735339u, 573015435u, 3312164843u, 1274000474u), + SC(1340417963u, 1112802360u, 10328826u, 706586684u, 2526013892u, 4135069035u, 3566832565u, 2945858092u, 107866747u, 2114273476u, 1970904771u, 965191541u, 1793617219u, 1453495760u, 4269949644u, 41605060u), + SC(123137558u, 4245690796u, 820317976u, 1443287541u, 4203849632u, 2954045926u, 714382464u, 3076066234u, 1293485113u, 2554869888u, 1663243834u, 1823619723u, 3832632037u, 2772671780u, 1362964704u, 558960720u), + SC(104412626u, 1897841881u, 4081037590u, 3456756312u, 3025873323u, 2036419348u, 663042483u, 1254379139u, 1882881825u, 3296543036u, 153313200u, 916960321u, 2276001640u, 759388499u, 1134495268u, 1699779658u), + SC(4218137867u, 889442133u, 2322944798u, 2659784159u, 2592614267u, 3345396604u, 3647495000u, 2837331949u, 75759322u, 2350992064u, 2461684340u, 2333444962u, 60872001u, 106935728u, 2095087192u, 2026584532u), + SC(818402121u, 2851948581u, 2197490142u, 4158011576u, 1665124994u, 3116095068u, 4019154383u, 478938546u, 1455910301u, 1844755722u, 2818772446u, 2743310120u, 1907022363u, 1639658700u, 517605614u, 2705809838u), + SC(335193145u, 4147885949u, 3527556636u, 2575925391u, 2530836608u, 2938195122u, 3771589905u, 2663025172u, 4017017665u, 2146447634u, 3974365403u, 2994000421u, 3198356067u, 3382731724u, 2593683495u, 3554902256u), + SC(1108422413u, 1982378939u, 2047758090u, 246779179u, 2568353687u, 279750626u, 1730233650u, 784289836u, 2712478714u, 3614283837u, 1824826964u, 2514128237u, 3308726345u, 3623735281u, 887459898u, 3896777957u), + SC(3527405352u, 290146745u, 125808293u, 735109902u, 1788801307u, 3306408847u, 822599754u, 3798637803u, 1514985656u, 2967186195u, 716984495u, 3386310843u, 3156794500u, 1007814159u, 1629566196u, 4265651874u), + SC(1178327293u, 565847309u, 518944000u, 3901419432u, 941693255u, 4276272755u, 3595637504u, 1831384538u, 553054976u, 3799273120u, 516961220u, 3048859574u, 1887176404u, 3648800625u, 2905989893u, 2971331974u), + SC(561598562u, 3812086269u, 2571795641u, 1946669885u, 4094345694u, 1247304730u, 725275648u, 2382611624u, 3912910386u, 3657806663u, 2347179560u, 3311073478u, 3031523768u, 2672297551u, 829774364u, 4138790294u), + SC(3908534093u, 41076189u, 4026661177u, 1264946070u, 3582612650u, 3167460834u, 3305185564u, 1828271691u, 1883569901u, 567401887u, 2154847219u, 3599749472u, 834678216u, 1517326104u, 465030801u, 2253777505u) +}, +{ + SC(69398569u, 525452511u, 2938319650u, 1880483009u, 3967907249u, 2829806383u, 1621746321u, 1916983616u, 1370370736u, 248894365u, 3788903479u, 221658457u, 404383926u, 1308961733u, 2635279776u, 2619294254u), + SC(4116760418u, 3197079795u, 2972456007u, 1278881079u, 1399016013u, 267334468u, 3129907813u, 468505870u, 1237093446u, 3810554944u, 1980244001u, 1830827024u, 4255330344u, 3556724451u, 2936427778u, 3969278111u), + SC(3989128687u, 604159041u, 3302470711u, 1703086807u, 4153485525u, 2444501021u, 449535888u, 2817157702u, 3967126593u, 3774839729u, 4230523164u, 1130105305u, 2419296875u, 560268503u, 173246097u, 1794638932u), + SC(1735434103u, 3810847770u, 4216841726u, 1126260487u, 1019034952u, 4140633019u, 3223272164u, 440162565u, 3864068825u, 3275406276u, 2196958479u, 4212485308u, 539037402u, 431338309u, 4061221107u, 4289896057u), + SC(1802752446u, 2780168117u, 1133399256u, 2599868866u, 3158418134u, 2848371717u, 2893014484u, 1878597835u, 139427334u, 1841937895u, 2016179766u, 2330806831u, 3849381146u, 2224326221u, 2296824272u, 3983748073u), + SC(1520559143u, 1690628296u, 1614953069u, 1422707415u, 257987514u, 3063997315u, 2652769123u, 3445956897u, 843436720u, 4264023440u, 365609354u, 2250088148u, 2769492081u, 59746990u, 1275187671u, 1973406172u), + SC(2823162534u, 2631304853u, 2485683334u, 33106529u, 243176015u, 492943806u, 489814307u, 4023911334u, 4139752347u, 4133120235u, 2455727203u, 1293330101u, 1838339727u, 4219498628u, 2131345625u, 3646653738u), + SC(4198202713u, 3167956639u, 2765023077u, 3652537372u, 1708707687u, 2324231909u, 1009881825u, 1679047879u, 2515346176u, 794145218u, 554048969u, 3173445869u, 2193645289u, 1271864237u, 1006139617u, 1072905092u), + SC(4273823033u, 1749314885u, 4263358248u, 538495360u, 4104454924u, 1997598205u, 3080563305u, 3238994582u, 3099819109u, 3162260128u, 1706963773u, 405274298u, 1894479347u, 1596497438u, 1094591269u, 1522128209u), + SC(2640931764u, 1304425992u, 2939922746u, 3918107623u, 1248692482u, 1121191585u, 2062140937u, 1807331998u, 3643560968u, 3236720945u, 2667270358u, 411521120u, 3664086365u, 2334989504u, 2668098536u, 3236026237u), + SC(2404161740u, 567514400u, 3895963765u, 1201374790u, 674719322u, 2894222365u, 467511362u, 3395036514u, 1038550674u, 2948454520u, 1518702565u, 1362236790u, 157238862u, 3475771959u, 1415257606u, 2714484334u), + SC(1831986705u, 588754101u, 4075551797u, 2767613701u, 2944855428u, 1912813036u, 1398542170u, 3440695634u, 2367865816u, 842155635u, 2602621363u, 2143763320u, 4256143529u, 1826541687u, 1851134007u, 2997377819u), + SC(3699972731u, 227995919u, 3067674252u, 477404832u, 847958753u, 893077929u, 2153170373u, 3057114881u, 1197132301u, 3330088847u, 2465660906u, 549749504u, 722435391u, 4124201578u, 3419977887u, 636305133u), + SC(3346980455u, 338882355u, 1940861469u, 2106574528u, 4065634984u, 939438415u, 880899904u, 173329243u, 3962520186u, 3417951565u, 2532850810u, 1158609417u, 1846710650u, 305050726u, 600225342u, 3684765712u), + SC(1932816778u, 3409537322u, 2445361402u, 1740774412u, 3661005378u, 2854030637u, 1914937560u, 1558250179u, 3808763123u, 1298026979u, 2417248681u, 899022004u, 847010236u, 506303181u, 1296472514u, 648957572u), + SC(600303058u, 722185115u, 3110060002u, 3818809602u, 1551617161u, 4208042174u, 526230670u, 1957951010u, 3160030963u, 3295123990u, 3121214191u, 1337066151u, 2200271451u, 1066776105u, 1163805043u, 2606444927u) +}, +{ + SC(1137648243u, 3815904636u, 35128896u, 1498158156u, 2482392993u, 1978830034u, 1585381051u, 335710867u, 529205549u, 1286325760u, 863511412u, 283835652u, 936788847u, 101075250u, 116973165u, 2483395918u), + SC(2210369250u, 711585268u, 1961210974u, 1353321439u, 1215935705u, 1641330999u, 11213011u, 2020212318u, 695107713u, 3413272123u, 1378074688u, 2790029989u, 658491086u, 1881545465u, 3409839898u, 2042086316u), + SC(1723393102u, 3373492622u, 3599711002u, 3748987970u, 1143620470u, 2663282777u, 2229588531u, 2674289435u, 2963045423u, 2234232397u, 4178299567u, 2791622546u, 4001934471u, 757990509u, 2858420658u, 605204372u), + SC(4272330873u, 3840847353u, 659917277u, 1664684318u, 1563018625u, 821178295u, 3329580379u, 794312951u, 2169136998u, 1706378889u, 3017987093u, 1159314572u, 2524368718u, 2444830959u, 898030098u, 68613446u), + SC(3172236096u, 1547478676u, 3467968131u, 1603626860u, 1411948645u, 2916654969u, 2891471305u, 2110051838u, 1733578576u, 2788816800u, 1613389791u, 759324595u, 3991538909u, 4073480091u, 3323038139u, 2043658072u), + SC(3011536148u, 2207224783u, 101813390u, 4149858178u, 961260436u, 3760245299u, 2099300570u, 3143747485u, 3209436103u, 902146054u, 3598885374u, 597299239u, 1369786353u, 2099087354u, 1506359374u, 1017249349u), + SC(3137350455u, 1622014086u, 2828880803u, 599881832u, 2213606365u, 4248974065u, 675350384u, 1446749674u, 1254778294u, 1745968946u, 409433048u, 1103126998u, 2370471436u, 1143685003u, 3341252280u, 1003299547u), + SC(2019014241u, 1108099665u, 1035538349u, 2878848993u, 2585673617u, 1565675366u, 2261830657u, 117854892u, 1965053814u, 2351841804u, 4065720752u, 3747135308u, 959541091u, 1629950401u, 4236240320u, 189693687u), + SC(3443026785u, 3216851941u, 278623472u, 1568038608u, 1548544711u, 2243949731u, 3359141033u, 1425753427u, 2934907774u, 2301245979u, 2216178210u, 153063705u, 1690071616u, 791861830u, 1201756636u, 1249732113u), + SC(2497506925u, 3815453805u, 1308318422u, 1061717857u, 710358190u, 3797004413u, 1870767051u, 2099598345u, 845543228u, 2941187056u, 1083282999u, 1311194087u, 3227025541u, 423673289u, 2634724972u, 3297305091u), + SC(1394185841u, 1653557808u, 2313575976u, 1732811292u, 2133445032u, 171245194u, 3242484287u, 2667183179u, 1165233778u, 997752293u, 501180123u, 2529762237u, 429212016u, 1660866777u, 1766992150u, 2066419882u), + SC(945381459u, 1085161105u, 3490034658u, 983140246u, 425352282u, 2175943302u, 1166850024u, 3968884285u, 1417959566u, 3386676357u, 3168826489u, 2984241621u, 3305143707u, 246924146u, 4113453679u, 123892017u), + SC(1498291154u, 979168666u, 2565114847u, 3722708999u, 3116533535u, 2044826765u, 118913881u, 2684275795u, 30932180u, 3147559151u, 3769605849u, 2376328043u, 753602217u, 3789763983u, 1247346722u, 4123341034u), + SC(3203969599u, 2514533821u, 1007395325u, 2063305304u, 520326691u, 3823758018u, 3095693832u, 1864628246u, 2586004821u, 4190638257u, 2952735262u, 2977139992u, 1124651421u, 295756268u, 3428261546u, 3110485030u), + SC(1663042556u, 4114384947u, 1430450710u, 3825340149u, 1051862436u, 3194752601u, 3106848742u, 1383208530u, 3142397378u, 4065704146u, 1545077688u, 2297695627u, 3152458457u, 4134880529u, 2187655177u, 3419805764u), + SC(3081663242u, 3880428040u, 2670880433u, 1398290076u, 1232125961u, 3862005121u, 1297357575u, 3334998678u, 1135063881u, 1723120988u, 2716095891u, 1113861429u, 3955845594u, 88397004u, 1699846421u, 887623013u) +}, +{ + SC(2668669863u, 1518051232u, 591131964u, 3625564717u, 2443152079u, 2589878039u, 747840157u, 1417298109u, 2236109461u, 625624150u, 2276484522u, 3671203634u, 3004642785u, 2519941048u, 286358016u, 3502187361u), + SC(1979235571u, 2198968296u, 3104128030u, 1368659294u, 3672213117u, 1391937809u, 2759329883u, 1389958836u, 2420411428u, 890766213u, 2707043165u, 2738550562u, 3382941095u, 378763942u, 3093409509u, 2964936317u), + SC(738589056u, 2116353374u, 2279888429u, 1705963022u, 828292114u, 896734726u, 2179570630u, 199574728u, 977051187u, 779668316u, 2330529056u, 3992755888u, 1000402439u, 2191612089u, 357145081u, 1441305104u), + SC(3372185571u, 1990378702u, 1181109789u, 3007260699u, 2430812419u, 1342872134u, 2198044770u, 1122343273u, 492870646u, 795688582u, 3226537448u, 1245881435u, 1071312339u, 1997541910u, 3829149062u, 1964864598u), + SC(3005241683u, 2859584860u, 2297396821u, 999606499u, 3964655188u, 3075624064u, 1368424820u, 847579236u, 744318941u, 1201524211u, 1104903258u, 3771742070u, 4093550286u, 53333408u, 659192149u, 3026115299u), + SC(3415227510u, 2060701016u, 1724277801u, 2661091313u, 215175235u, 1719160017u, 2940192603u, 1942243742u, 2398510742u, 4053370504u, 720436957u, 3760614784u, 2014232625u, 4199009336u, 2658914393u, 246186938u), + SC(446126854u, 165933106u, 2141828870u, 892600041u, 4146883601u, 2127439849u, 3431174989u, 2697318886u, 754216027u, 2671089369u, 1463409379u, 2826265846u, 334206028u, 1562078629u, 62819702u, 350080249u), + SC(3607678201u, 1305808009u, 3724583207u, 482185919u, 703873206u, 1075587326u, 1772056430u, 1356871295u, 4212601732u, 3762698616u, 2707284202u, 752961239u, 3089561250u, 1634547883u, 2919906767u, 31529502u), + SC(299389109u, 1252069111u, 2304374236u, 1252642323u, 2415535563u, 271885157u, 592252779u, 1178960198u, 53568246u, 3149254195u, 2937703855u, 1474069228u, 1764301842u, 954790502u, 4245417136u, 3132108431u), + SC(2094400513u, 3190829985u, 2239253067u, 2918833540u, 4106202305u, 2502268912u, 1731261142u, 2453877410u, 1861934729u, 934615026u, 3785479199u, 3605446967u, 3582056355u, 3042887218u, 1961855879u, 496882544u), + SC(3179454680u, 881405516u, 158640787u, 2790186672u, 162147899u, 376983910u, 3379568747u, 1408037207u, 1411174731u, 535638557u, 1510230718u, 2856041085u, 1958999115u, 3678347246u, 2958940834u, 520309445u), + SC(1870118851u, 1980314816u, 3987573623u, 4117586697u, 396136405u, 3149345244u, 70002589u, 2314836548u, 1713919226u, 3789182954u, 2123295507u, 3015665476u, 4069315088u, 3980795614u, 2021907367u, 4155874670u), + SC(4078777812u, 3708497519u, 1529048728u, 3747007128u, 2780224299u, 2728976580u, 3953400499u, 550363476u, 3812495996u, 3116459113u, 2211909765u, 3967732138u, 315888386u, 4202077281u, 1437542127u, 2815522910u), + SC(3236576167u, 3189780679u, 2030714184u, 2121402515u, 772212369u, 2193424420u, 1417920098u, 2031545011u, 4110769775u, 697022136u, 1206489717u, 1691036150u, 88940849u, 535864250u, 547921653u, 2569798466u), + SC(598120112u, 3876471191u, 3533286352u, 3003233155u, 1039593763u, 2148663879u, 2659932582u, 279051507u, 988977723u, 3458445518u, 2950275676u, 4048574808u, 3093122873u, 831143981u, 214208408u, 3935649503u), + SC(2893621405u, 3242329790u, 1948255717u, 4083664057u, 3803596193u, 740414223u, 4293576836u, 3875047642u, 667197150u, 2081112783u, 2447275650u, 242164299u, 706345359u, 1928593492u, 1774391838u, 3660333945u) +}, +{ + SC(3009793609u, 3525092161u, 3245586135u, 574145899u, 4034974232u, 2828949446u, 3457574134u, 1546193476u, 3883480541u, 1976722737u, 3557056370u, 994794948u, 106991499u, 1626704265u, 3534503938u, 3271872260u), + SC(2939511082u, 3508735083u, 975571643u, 1775005849u, 4144127005u, 706007446u, 420750190u, 1296964164u, 3061654480u, 2268588398u, 258119220u, 1152421762u, 2183948554u, 3016917902u, 1186604447u, 3147111215u), + SC(405897674u, 923178082u, 1575208079u, 3088321769u, 2214762612u, 3893926734u, 3167279390u, 3951912989u, 2709000001u, 2390687969u, 3858727239u, 866338457u, 2045181240u, 3217044625u, 2328560686u, 1861539550u), + SC(1277015638u, 1098202702u, 1559301990u, 2587773702u, 236499920u, 458659357u, 2353007333u, 2611100088u, 3428309717u, 2008274629u, 3647015407u, 268886847u, 2626192792u, 3341061984u, 1515395072u, 3708589435u), + SC(4042661445u, 3420460388u, 402520550u, 3677541300u, 2230979515u, 1273170666u, 2514471146u, 827498216u, 1259202696u, 3072082970u, 475301020u, 2118811945u, 3612811582u, 1387362670u, 2779447975u, 2265478999u), + SC(2229583001u, 1885758268u, 2744744533u, 2751282929u, 3032060674u, 1949605811u, 1570835257u, 793354274u, 1683039266u, 449593771u, 109462780u, 1941150268u, 1808732776u, 139050949u, 2225765509u, 1246293964u), + SC(2802845617u, 3765730171u, 462111640u, 590276976u, 2549490668u, 1227143343u, 384473299u, 1872236586u, 2432932105u, 2621627369u, 29218585u, 3541815309u, 3762320683u, 3470760231u, 2011203130u, 2527437401u), + SC(796052351u, 4037990088u, 4017471553u, 1320960316u, 561010825u, 3728618461u, 3540350568u, 1334322515u, 2252671868u, 3217596003u, 3122272084u, 3124892250u, 146022162u, 3584383023u, 2911266650u, 2958817688u), + SC(161418820u, 3776882969u, 4050624816u, 1522984750u, 3239766493u, 3767349571u, 782872272u, 4177710199u, 1140123311u, 211837022u, 1955996644u, 402816745u, 3326870942u, 1443720320u, 1645866695u, 3832886909u), + SC(452931871u, 3201459109u, 3989748495u, 3779670060u, 3234605835u, 2462489907u, 3541849378u, 3952908948u, 2234764749u, 2534999097u, 1221823414u, 2220662906u, 2593424893u, 3688122472u, 2131104831u, 243658822u), + SC(1244527825u, 1331697159u, 1126644730u, 922926684u, 1475975786u, 704282514u, 1718439968u, 1878820141u, 2509443841u, 2182928123u, 1663057853u, 2828328506u, 1475048880u, 791101245u, 3209045799u, 807262644u), + SC(1506123994u, 75559732u, 2487617790u, 2776679170u, 2522687136u, 3704896305u, 945074946u, 2943008309u, 1088584510u, 2469322363u, 1078526500u, 2073262975u, 691596720u, 2702927487u, 380178128u, 704842212u), + SC(1460389583u, 4274587105u, 1447626425u, 3957246995u, 1621878179u, 1643627976u, 4030517934u, 1056559397u, 1438644008u, 32976965u, 2197709285u, 3567855255u, 2001746745u, 2603748421u, 3462117821u, 903804357u), + SC(3179129705u, 2297226467u, 1646197352u, 950157362u, 2929140164u, 4242027992u, 1652798968u, 4193267428u, 3343133888u, 2499845914u, 423061238u, 3494957413u, 3637365392u, 784231823u, 595573026u, 2713123590u), + SC(2810225213u, 3951319549u, 1905650326u, 3909017486u, 2335763951u, 3772810842u, 2983632261u, 489145948u, 4173940274u, 2703192453u, 2654763363u, 4064871590u, 1399005653u, 257836626u, 831912020u, 895345820u), + SC(4037755568u, 3145789767u, 2141184942u, 4120133888u, 346636610u, 3895536529u, 2259736314u, 1057113066u, 595225270u, 3051392771u, 2813693848u, 3877775276u, 1832280309u, 1138362004u, 3061980317u, 858203300u) +}, +{ + SC(941124125u, 1620226392u, 1431256941u, 3336438938u, 540497787u, 766040889u, 373284400u, 2979905322u, 177008709u, 2625544842u, 1096614388u, 1196846420u, 4186360501u, 3945210662u, 1143943919u, 3412870088u), + SC(2868459499u, 3255324438u, 807131982u, 2853200483u, 3487859623u, 3501857558u, 3107820062u, 2163227213u, 2115527726u, 2346720657u, 2251713340u, 3377131273u, 3223650794u, 3766790266u, 177525458u, 4167009497u), + SC(311132793u, 3961991670u, 3475828441u, 4275227465u, 4114440759u, 287999228u, 3329759386u, 2384037498u, 4228771259u, 844254234u, 256179964u, 1796107218u, 3127243322u, 1425447302u, 1385509204u, 1101567113u), + SC(2084416542u, 1837746358u, 3915669193u, 60671540u, 2731498203u, 842785439u, 103116859u, 3404407266u, 2713222963u, 3049100113u, 368142082u, 2923502225u, 3018451818u, 2169399182u, 3017634865u, 1845463402u), + SC(1620925474u, 3368534446u, 555437218u, 4144603563u, 1969376145u, 213474605u, 1856420595u, 3939242692u, 1705488978u, 252956811u, 1258322279u, 1776729832u, 3988114536u, 3572272198u, 1383845751u, 1398527932u), + SC(1762997475u, 799707654u, 1609033889u, 2324053368u, 2951656833u, 2545022095u, 1325992886u, 2638191889u, 737853621u, 891297811u, 1613139572u, 594983169u, 2686965496u, 4040759974u, 1496585540u, 294269531u), + SC(3866323582u, 3807637640u, 654389167u, 993860478u, 3985490230u, 874636344u, 2342980699u, 1928023737u, 1520117329u, 644165140u, 150615609u, 199275733u, 463804864u, 310744654u, 2057873049u, 1169977839u), + SC(239011286u, 715635161u, 1855226016u, 2750348850u, 4059485278u, 800137564u, 3998891997u, 4048007508u, 1194893107u, 3761772527u, 273800027u, 653240081u, 1187997500u, 310579555u, 786511222u, 3092283411u), + SC(3036944959u, 3482022954u, 3739636749u, 3919006909u, 4266819119u, 1212326408u, 103856594u, 597427799u, 1319114089u, 4260737761u, 1982976744u, 741084092u, 689793522u, 4260038527u, 1319231386u, 1661185367u), + SC(3846585080u, 1572901113u, 2683774833u, 3251385733u, 3753876990u, 849242549u, 4245340911u, 1064393430u, 3309340124u, 2842098330u, 2556268102u, 2033409485u, 757257328u, 2031055308u, 487255243u, 3197919149u), + SC(273355511u, 2413549351u, 710350577u, 1361281890u, 2485522754u, 1210096318u, 3839671116u, 3619357718u, 3954210633u, 312725146u, 3792397974u, 3833954588u, 1779821907u, 2701218449u, 2422680647u, 3829673069u), + SC(379167192u, 3494512635u, 855436470u, 2928216366u, 4239059924u, 4254878455u, 3617218283u, 739826290u, 3488721213u, 1288540569u, 2623691196u, 4237777587u, 1234356449u, 2367467024u, 185343202u, 2198868227u), + SC(333398980u, 1306721698u, 1267933489u, 3888643170u, 2305763143u, 1886386521u, 2247721544u, 1287414137u, 497238456u, 1934421131u, 1960709128u, 2688614248u, 3637710577u, 3756130276u, 1929365309u, 2796038772u), + SC(772805737u, 461244658u, 3551164236u, 4177074918u, 3920537361u, 4259237061u, 3625379235u, 3715444221u, 3444473673u, 2576271136u, 2750230085u, 2167864295u, 2571239709u, 3663560660u, 743894391u, 703945624u), + SC(2955504442u, 4192737708u, 2813336533u, 2037901957u, 1563142269u, 620241136u, 3249364868u, 1805455553u, 422364625u, 3061329310u, 3824436397u, 1640020182u, 2540832302u, 2063844885u, 2982901072u, 2809011473u), + SC(4188085081u, 1849071252u, 4251112483u, 1368274267u, 2811635355u, 3535120523u, 478922770u, 1090405967u, 2358353504u, 2249592823u, 2367480425u, 1158857070u, 1979230110u, 3661225756u, 2903524693u, 1830110173u) +}, +{ + SC(3638948794u, 3243385178u, 2365114888u, 1084927340u, 2097158816u, 336310452u, 231393062u, 580838002u, 3851653288u, 568877195u, 3846156888u, 2754011062u, 3396743120u, 2639744892u, 1431686029u, 1903473537u), + SC(3268926613u, 1818698216u, 1862252109u, 1578913474u, 4289804840u, 1885759995u, 2888888373u, 2636129891u, 2360477693u, 1672434489u, 4188472821u, 2046052045u, 437371108u, 3454488779u, 2151384078u, 1514762405u), + SC(3140765176u, 3623124217u, 3204258419u, 1994235030u, 4141313973u, 3067394014u, 3891883464u, 3387486245u, 3254639322u, 1970078634u, 2106725210u, 2833086525u, 1670513208u, 472865524u, 2121280699u, 2548725819u), + SC(309446023u, 3610145983u, 678094472u, 3223511337u, 4188624231u, 2675209562u, 619208065u, 1214683627u, 307823706u, 3407147709u, 2103429213u, 3636822787u, 2441204583u, 1675916090u, 1444359140u, 2979809856u), + SC(1982287011u, 2286805587u, 3436767742u, 3002584758u, 477850697u, 439716674u, 3863581947u, 2155905635u, 220608999u, 1402913678u, 2974580099u, 1207717136u, 3265452095u, 2174870701u, 464004734u, 3218951674u), + SC(2374025586u, 3926883961u, 3555874460u, 1238670328u, 856489843u, 4258163476u, 977941661u, 3889087192u, 2262660846u, 1677408901u, 2922467369u, 1043137100u, 4279650771u, 3357788771u, 1512036754u, 2539641395u), + SC(1142842756u, 272648505u, 914080820u, 4056304706u, 1529598235u, 1542384711u, 898735874u, 77881967u, 1035144846u, 702992091u, 2075420139u, 2454875215u, 1266516833u, 2974932401u, 3666315911u, 2262316403u), + SC(282628724u, 2966722803u, 3533567779u, 2474391608u, 1236598744u, 3094620093u, 2714845907u, 369896328u, 366951725u, 2971547133u, 2753808137u, 618960857u, 2006195012u, 551749950u, 1402811398u, 3808228405u), + SC(962649761u, 2486282608u, 1808066694u, 2361174774u, 234593415u, 400975056u, 83848885u, 1091105486u, 1020816894u, 1838575736u, 2668167699u, 73800319u, 2028242253u, 2121917721u, 1921251529u, 2828854963u), + SC(2717497535u, 366873177u, 336873963u, 978494261u, 2877822089u, 2054875183u, 2521644031u, 4057807064u, 3713415744u, 3955164880u, 2229410320u, 3755022307u, 3363858805u, 1398106956u, 800395520u, 1799982442u), + SC(399227430u, 164572050u, 2101616757u, 962629850u, 1654784623u, 3459989194u, 2240801569u, 1986371042u, 1911756881u, 2723553175u, 2964071573u, 3609789600u, 3185432638u, 2208423303u, 2967147750u, 4279453877u), + SC(282950688u, 2418348758u, 1686423600u, 1392917024u, 3343336708u, 976718153u, 671781049u, 4166009090u, 371505957u, 2474457927u, 1126253569u, 3355537407u, 4151375790u, 2105071839u, 941370857u, 331122028u), + SC(2127306191u, 1587304141u, 1137651997u, 1529991785u, 1356564935u, 726775332u, 1952136309u, 4003891353u, 61741949u, 780292838u, 1136081573u, 1836882786u, 528077243u, 30578492u, 465809744u, 2709331701u), + SC(4118645416u, 3394012023u, 348789448u, 3808052591u, 1284813572u, 265335400u, 545565522u, 929596026u, 744207086u, 3837069751u, 130735480u, 1107476780u, 910486599u, 2623115273u, 1478462314u, 2130033795u), + SC(1955617954u, 1897311939u, 3110934223u, 4221780767u, 1556888759u, 3849614629u, 306928433u, 3178221670u, 2099698284u, 308858727u, 2221495536u, 1221057715u, 974275765u, 2399830054u, 3285960273u, 1758193777u), + SC(1309372774u, 3725783295u, 3135972452u, 3122681380u, 3898315320u, 1245625291u, 3684458552u, 2498694383u, 145248803u, 3480764710u, 874108791u, 2482726617u, 434324108u, 1522025692u, 3554266182u, 2125028368u) +}, +{ + SC(4095464112u, 3774124339u, 1954448156u, 2941024780u, 584234335u, 483707475u, 286644251u, 3027719344u, 2257880535u, 651454587u, 3313147574u, 3910046631u, 3169039651u, 2576160449u, 696031594u, 3062648739u), + SC(3459141530u, 1009969738u, 35229281u, 2373814441u, 355537356u, 4228991558u, 213496956u, 1669603654u, 1552983955u, 3304370832u, 604896268u, 499179421u, 2737968344u, 807678026u, 3567168353u, 2353882345u), + SC(2454671851u, 2184874449u, 831795291u, 1169825676u, 1084590471u, 1942690394u, 2762211706u, 3042637679u, 2365319338u, 3552008694u, 348752618u, 993280940u, 1178602031u, 1559708076u, 3354759347u, 972286478u), + SC(2677560697u, 4247966509u, 151962163u, 3310844434u, 2986095882u, 3914030856u, 3436387520u, 860446559u, 4289606749u, 2343453766u, 3218454181u, 293342071u, 1238022655u, 3938175190u, 1394478132u, 4256084776u), + SC(3033685698u, 1795086146u, 719843849u, 255984080u, 2447365525u, 874035973u, 313642533u, 1163634918u, 2316564524u, 1195940716u, 1914843207u, 3907025376u, 23457264u, 1278433300u, 3111232984u, 668125878u), + SC(2135745017u, 2899432034u, 1819124473u, 2109840859u, 3124696519u, 2070710502u, 990727745u, 2752134271u, 1963223245u, 866344359u, 606159585u, 3867224292u, 3038840373u, 3295910586u, 2433460716u, 3384811471u), + SC(1744070416u, 383286836u, 3000319326u, 3310329765u, 4062980155u, 2749127191u, 1895582230u, 439084228u, 1884304792u, 326674045u, 377650590u, 3363592478u, 2947641322u, 1784390018u, 1332541121u, 4203919218u), + SC(472957101u, 1135650637u, 4212757570u, 185931877u, 2096733734u, 4238795506u, 481917546u, 1405180051u, 925427330u, 1923351053u, 2204480714u, 3944038373u, 372144582u, 3395978522u, 3795034464u, 1074487901u), + SC(227727393u, 2219043153u, 2909459085u, 3082645761u, 1970114976u, 3426610084u, 35253812u, 3123666967u, 4231900027u, 2888054525u, 2744804820u, 1500359618u, 191232240u, 3239664209u, 1569663960u, 1330983134u), + SC(996304063u, 2759713926u, 1022152104u, 4268512678u, 2870837640u, 3507597858u, 1252922637u, 3276898019u, 3824649934u, 1524401760u, 2559990337u, 1660220688u, 2350855385u, 609332995u, 2406016501u, 2406242521u), + SC(3333888266u, 3838886221u, 3016467419u, 3341790649u, 3667104212u, 783789160u, 1310400762u, 3633793516u, 4105695306u, 2973076533u, 455893547u, 2864660063u, 3696934279u, 2872882056u, 2264350097u, 539812697u), + SC(3263458726u, 2820785414u, 3760367911u, 628854049u, 1473785327u, 426717862u, 2025377226u, 3498407835u, 3577945153u, 1319190911u, 1062047947u, 3346460201u, 2590672215u, 2723591074u, 1487439866u, 4217021014u), + SC(2076058913u, 33130418u, 1949000294u, 3536165044u, 31327487u, 1891010986u, 2347335564u, 1669503944u, 3753248202u, 881959988u, 3846164684u, 3636142472u, 208517894u, 3407391141u, 3485893709u, 1074365179u), + SC(2175348532u, 3463201667u, 168136052u, 2889266255u, 4105885613u, 3068947090u, 2279310533u, 2649966235u, 828612565u, 2017635648u, 1260407590u, 1970316631u, 2447304459u, 2893112079u, 2425504835u, 1197046834u), + SC(2653983058u, 1419924288u, 2320709126u, 3640188854u, 2683911962u, 2643927342u, 3261193464u, 3929873787u, 2878724355u, 3436083049u, 3424148509u, 1311037973u, 3116391362u, 2037892948u, 454042580u, 970415398u), + SC(16199673u, 2464180001u, 89776423u, 672570852u, 2291071982u, 3899998968u, 4262439281u, 412856039u, 3677249728u, 1182323568u, 3472045521u, 3554674668u, 819725249u, 4078699211u, 2037243914u, 4166444096u) +}, +{ + SC(1740919499u, 3877396933u, 2326751436u, 2985697421u, 1447445291u, 2255966095u, 1611141497u, 1834170313u, 3589822942u, 2703601378u, 299681739u, 3037417379u, 4014970727u, 2126073701u, 3064037855u, 2610138122u), + SC(2959647136u, 3814991611u, 764778261u, 1677371416u, 497556143u, 1000564042u, 4065791500u, 1027030318u, 2636763418u, 2469599275u, 839050056u, 4115114412u, 3982189672u, 2204140838u, 1747652790u, 3786215179u), + SC(3812425833u, 3703652912u, 1980699604u, 1506061914u, 2330998846u, 3874717363u, 20614012u, 1484655664u, 2896690261u, 1196646483u, 159078055u, 1300317512u, 2570981831u, 1267318554u, 3037645632u, 3117135345u), + SC(2012483448u, 279997059u, 1908492604u, 1638405820u, 284407565u, 1607271004u, 1423855670u, 3949669604u, 1635878907u, 4045715556u, 3600475894u, 3387647818u, 3950223476u, 3109131487u, 2524676171u, 3329048150u), + SC(3505120665u, 1999377488u, 158974979u, 636438923u, 1767149410u, 2424026197u, 532320013u, 3350230775u, 3506414357u, 999737675u, 3415715721u, 797201045u, 3439137094u, 3636888232u, 1001867404u, 1070514934u), + SC(803341976u, 972240723u, 2174569332u, 4037031657u, 720363583u, 1532359940u, 222173943u, 3948724459u, 669414977u, 446802288u, 4195328223u, 2316597014u, 3039478974u, 1217500351u, 1058613984u, 3974805650u), + SC(2497689022u, 832535973u, 4012390289u, 3862385792u, 473134599u, 855172718u, 3160709443u, 2946049581u, 1340978834u, 1282260619u, 3672935594u, 1114896253u, 1194768191u, 2151967837u, 3557909289u, 83919397u), + SC(2685697085u, 4183307820u, 393931333u, 2425217781u, 2950365274u, 2300063381u, 3990090983u, 1961757942u, 3357278228u, 2993935030u, 779960569u, 3652282828u, 1743505267u, 3193034940u, 2134245237u, 4042181132u), + SC(2449311128u, 4037657778u, 318968012u, 1098807866u, 3241626396u, 745989749u, 4126255071u, 850508142u, 4075976689u, 357235455u, 2000916706u, 3900438139u, 2804084317u, 3036848582u, 604252796u, 2006800965u), + SC(101955641u, 2732365617u, 2730133770u, 3908553062u, 2872853047u, 264325893u, 2086018926u, 546076667u, 582367640u, 2242336949u, 2223649162u, 1521240572u, 178342991u, 3408523296u, 2216853754u, 1636770650u), + SC(1697876449u, 998213608u, 2367869150u, 3635535434u, 3029347602u, 2697162358u, 300760335u, 3790588806u, 3127970813u, 157171921u, 2766714052u, 3441353031u, 3760111386u, 1962222723u, 1338315915u, 1705537099u), + SC(2069540711u, 3174156395u, 3834082852u, 2243125169u, 1332693007u, 1773075089u, 820191370u, 262117783u, 184405617u, 469065021u, 1286610377u, 946922506u, 2233109630u, 2803987975u, 489850357u, 3341265389u), + SC(3152895344u, 3190413328u, 1371373852u, 2133030998u, 2097773989u, 3484604561u, 3233580762u, 2103971308u, 580626917u, 3723142348u, 1233964596u, 2884246809u, 1451113068u, 2274332609u, 834566918u, 4166322862u), + SC(474309298u, 31198476u, 474732582u, 1614612386u, 2339718649u, 702598622u, 2007092771u, 1563921691u, 3096928870u, 2036801390u, 3171632090u, 2666464957u, 2581592302u, 84487705u, 4066440296u, 250703600u), + SC(2850943751u, 3355276358u, 3608928556u, 645558581u, 1754003398u, 2401097307u, 4007141515u, 2306720640u, 2585847442u, 2486681168u, 916961025u, 2906286711u, 2183350629u, 3403456959u, 1234360906u, 608407455u), + SC(3919397u, 2910764499u, 1130649170u, 2504839137u, 475960727u, 4198145923u, 3575554927u, 727034596u, 3487299979u, 2134210036u, 1295494166u, 1094003986u, 3153584442u, 1125501956u, 1050325095u, 3018071122u) +}, +{ + SC(1456510740u, 215912204u, 253318863u, 2775298218u, 3073705928u, 3154352632u, 3237812190u, 434409115u, 3593346865u, 3020727994u, 1910411353u, 2325723409u, 1818165255u, 3742118891u, 4111316616u, 4010457359u), + SC(2413332453u, 1353953544u, 4051432026u, 303594340u, 1259813651u, 366336945u, 3380747343u, 2634392445u, 2066562619u, 120707135u, 1398541407u, 502464084u, 2984999938u, 3829298149u, 1120989122u, 3373752257u), + SC(1681071159u, 120984332u, 2029459879u, 1382039080u, 3634662556u, 54408822u, 48099449u, 1179080842u, 2669759950u, 3169946602u, 1520730683u, 3878549631u, 1666070500u, 1804495215u, 1101808889u, 1988315741u), + SC(1810699040u, 1982264875u, 1311915666u, 268159494u, 1265118580u, 1494821999u, 2740360551u, 3403457379u, 2370002476u, 3663200326u, 1969174367u, 2988878975u, 2261867571u, 1896957751u, 4228495601u, 268030737u), + SC(3788031612u, 1459331879u, 4195039120u, 148760443u, 2710036304u, 3803193725u, 2316636996u, 1290739855u, 2078515077u, 1158390637u, 187516666u, 1165781180u, 3871854912u, 2887741280u, 3432370474u, 3017515415u), + SC(2660400581u, 1115514969u, 819611304u, 2438542525u, 1149450061u, 641570348u, 4195260176u, 114239580u, 3415942550u, 2418164759u, 3596450733u, 4170880111u, 3742333800u, 707266970u, 294392938u, 1502400257u), + SC(4244209414u, 4144723933u, 1206802017u, 3395049043u, 1534528858u, 212213384u, 273948964u, 2465871688u, 98513287u, 526054552u, 101003852u, 2178852720u, 1739213138u, 2000068838u, 3443316390u, 2907641948u), + SC(4170329393u, 2397160575u, 698736458u, 1726629095u, 2059726015u, 608224441u, 940962377u, 3160021800u, 2474105021u, 1418624931u, 3220142189u, 3165061177u, 609263259u, 3526248509u, 2451110984u, 882122082u), + SC(1803413035u, 2626850042u, 3923382679u, 2501640460u, 887077755u, 2970691407u, 3982443858u, 546345352u, 545064661u, 1905866916u, 4137411501u, 4293519422u, 399697152u, 2101209662u, 4081268472u, 3745325674u), + SC(3913855272u, 3324082002u, 2401043817u, 1769760109u, 2460560183u, 875956117u, 1942607787u, 1641754800u, 1964565342u, 442388011u, 1687580604u, 293988342u, 3046598358u, 2835075967u, 920490836u, 349604594u), + SC(2643665013u, 1607952309u, 2279132309u, 992705865u, 1231530495u, 2682680275u, 2340070945u, 1036310446u, 2160469638u, 3849593659u, 569936175u, 133751759u, 1309000826u, 3681058360u, 1289881501u, 385711414u), + SC(1190130845u, 2798968177u, 277741425u, 3875973536u, 2502592372u, 251555512u, 1825737360u, 462006518u, 2334535950u, 3997809264u, 2012251623u, 3408888487u, 2549759312u, 3379458376u, 2301581275u, 4171117892u), + SC(1923456093u, 1653002750u, 3279649712u, 4281661052u, 1248011568u, 933375742u, 2109342469u, 751470571u, 2742486580u, 2572871261u, 3296809419u, 4075155428u, 3182626853u, 3435860599u, 3916597057u, 245531435u), + SC(514908612u, 2222061780u, 506774061u, 381342968u, 789366883u, 3683832850u, 9270407u, 528428861u, 590313143u, 483933274u, 1128871308u, 2791400346u, 3033966006u, 2397900561u, 174539653u, 2363998101u), + SC(3558289816u, 1015432688u, 3960686128u, 2087286003u, 446928557u, 4028273076u, 3055038539u, 885707705u, 942001648u, 3175434773u, 3929872598u, 2961036794u, 1122092143u, 2142675404u, 4054255588u, 1958229328u), + SC(2852327378u, 1383667573u, 3763466478u, 3195889922u, 2107642962u, 1739908882u, 157313327u, 492435243u, 4236498733u, 1510923342u, 3227437908u, 1896980749u, 154410481u, 2958311799u, 3270353062u, 1889012642u) +}, +{ + SC(822693957u, 1703644293u, 3960229340u, 2092754577u, 3495958557u, 4288710741u, 4092815138u, 1275224613u, 2592916775u, 472063207u, 2931222331u, 2597044591u, 1261640449u, 1272207288u, 2040245568u, 1417421068u), + SC(57865933u, 2591783175u, 1332940705u, 2361514832u, 2842982424u, 2581566511u, 1328343723u, 3898369656u, 2090549923u, 2179715082u, 2370481583u, 775215786u, 3850307123u, 2489521783u, 3999750482u, 1014134079u), + SC(2011629934u, 1914036612u, 3406392133u, 1425412057u, 1338374071u, 683386303u, 3190457777u, 428137206u, 1251032257u, 3672462899u, 2593185313u, 1953316437u, 2123216916u, 3258622817u, 3197533388u, 3442579011u), + SC(265734183u, 884987600u, 2786263189u, 3536027957u, 3885575220u, 1854265340u, 3853595664u, 1987453181u, 2744740518u, 512197390u, 114481815u, 96285071u, 3293497789u, 4015333892u, 4092376929u, 3025411574u), + SC(612519829u, 3198151239u, 3191059512u, 226844204u, 3503855660u, 764021515u, 3628841562u, 3951882416u, 3622158804u, 3603368155u, 2780109382u, 822859403u, 25907739u, 3882220368u, 3789068172u, 1684074913u), + SC(3520260226u, 1656105499u, 1676578448u, 838040958u, 3130046810u, 995588852u, 3233766730u, 2629592527u, 3096399775u, 1659682138u, 1365617549u, 2450677843u, 1725372848u, 2623357383u, 1402837393u, 1993344168u), + SC(2434333993u, 2901722469u, 518468307u, 3322336116u, 3303354477u, 2422295273u, 3584734361u, 1255342255u, 2224600785u, 3752112711u, 3720624102u, 3425652159u, 3563799906u, 957522630u, 501907560u, 3362627156u), + SC(3271809032u, 2402529419u, 3935184016u, 3639910664u, 659985988u, 2584831332u, 1091987512u, 224789177u, 2944016703u, 3591574599u, 1273021052u, 967556634u, 1019501719u, 1864898605u, 3453844870u, 4011599553u), + SC(1326048883u, 3477092042u, 1799777609u, 296885426u, 1109310872u, 255028335u, 163456938u, 2108662143u, 3501831646u, 225777648u, 4099069764u, 3428610561u, 4069711767u, 3876386370u, 1215899260u, 369937558u), + SC(3466874302u, 1921411468u, 3753149186u, 3739960133u, 1909238781u, 2219053499u, 4040572016u, 1651280893u, 754573870u, 383500798u, 2400558032u, 922698902u, 2125517085u, 2541623325u, 2827334144u, 2773618829u), + SC(2040368526u, 2190975469u, 1347589661u, 1684817146u, 2021572959u, 1656810013u, 330975936u, 994237514u, 2596719101u, 3800849855u, 600269956u, 1857741551u, 3033366103u, 1496147464u, 2628189942u, 4210116847u), + SC(3076719908u, 2490548320u, 377911263u, 2002478742u, 2549252529u, 839159951u, 230337140u, 3095221595u, 1528132928u, 2083899038u, 2503451113u, 272698731u, 2624407067u, 161482016u, 4135914440u, 2519252428u), + SC(2556876861u, 2107629748u, 2377697213u, 1433609947u, 3343742332u, 3505415093u, 2690575000u, 2017949066u, 4133794057u, 4184820210u, 2960078982u, 1333558937u, 3733636790u, 3960011078u, 945143131u, 3343864106u), + SC(1801254589u, 1449097227u, 181948563u, 1034221031u, 1779862110u, 3141289560u, 3383585093u, 2578193674u, 554670851u, 2530857925u, 4076682145u, 2827602863u, 4244507626u, 2938597885u, 3223414171u, 2204001183u), + SC(291814305u, 2937237569u, 1434020428u, 3585179044u, 3677832974u, 2016114805u, 3981784693u, 538800869u, 2673738915u, 999373833u, 1457987857u, 3180983013u, 501300267u, 4103517997u, 997980659u, 1113009463u), + SC(3993610129u, 1037741502u, 330412440u, 2749687355u, 1555232145u, 1196959672u, 530284980u, 340384986u, 2298150586u, 3185141181u, 26985524u, 2219307959u, 2447245692u, 1065988754u, 1248620406u, 2208024308u) +}, +{ + SC(3660855132u, 3816892380u, 3431508003u, 1440179111u, 768988979u, 3652895254u, 2084463131u, 3991218655u, 323118457u, 3675476946u, 2157306354u, 2684850253u, 1543808805u, 744627428u, 1091926767u, 3538062578u), + SC(2810298495u, 3411171710u, 4062828084u, 3003344135u, 3264709694u, 1048068132u, 3549102117u, 1927032841u, 3841604555u, 1360558064u, 2204714588u, 1197341693u, 3768005385u, 2899352192u, 2849083812u, 3793398404u), + SC(3631867959u, 3146872034u, 420513606u, 2446059169u, 2652499910u, 429155541u, 748397809u, 3543114527u, 235482177u, 894763888u, 1086818023u, 3285579564u, 1810274445u, 1142434275u, 140188668u, 4059040723u), + SC(2682453748u, 1595694625u, 17869409u, 4001607469u, 759206176u, 3336900820u, 3693692341u, 2473365492u, 2714988574u, 637563477u, 4105755464u, 3161387095u, 2814461644u, 4283494186u, 3858290792u, 1516784203u), + SC(4062605051u, 1956634460u, 3701616314u, 2342355265u, 1267526896u, 464674235u, 2247549950u, 3633206724u, 296547100u, 2905295542u, 4077085273u, 2746567644u, 1803616500u, 918536622u, 2709233803u, 2413530101u), + SC(1383097263u, 1316928613u, 759541292u, 3793001510u, 257497874u, 3658838865u, 3213596633u, 3650670599u, 63812226u, 1947202098u, 3651967368u, 2399936732u, 2521262969u, 322630211u, 4004516883u, 1422335688u), + SC(2852550033u, 3224936812u, 733055828u, 3325391168u, 1930707186u, 731324754u, 3498518219u, 4117056191u, 2179511600u, 2761523161u, 4282458808u, 3042559735u, 2438675720u, 2532100345u, 3706723018u, 4059342362u), + SC(2048163474u, 1848349034u, 3258863528u, 3644103333u, 1151231486u, 3308192205u, 2814277731u, 4197063636u, 3510455851u, 1315219655u, 2185965649u, 3799505477u, 4254363720u, 3128925961u, 1852465545u, 4138612075u), + SC(960983998u, 3301464188u, 2737893955u, 1522861436u, 4164105020u, 1184099683u, 64022400u, 2368856028u, 326418376u, 2065332946u, 2081529277u, 3466798514u, 208026276u, 417986090u, 3587033208u, 2294843214u), + SC(2712989146u, 349068332u, 3978782854u, 1513755929u, 4281030368u, 4041238337u, 1631550267u, 936378809u, 3831648862u, 1780262732u, 3189639539u, 328937247u, 722753719u, 3671027558u, 215485348u, 294998383u), + SC(170533035u, 3100330628u, 2519007245u, 2729143680u, 1780483799u, 1771308699u, 777046078u, 1252661309u, 944830935u, 3219243484u, 2959537667u, 145170296u, 892161275u, 1151850054u, 2176346749u, 598783080u), + SC(3596882604u, 51304713u, 1277701547u, 3288737023u, 2143659411u, 1229626338u, 2504854740u, 2518260221u, 2909459409u, 3820898741u, 1076396276u, 3330086214u, 2070741501u, 1675949151u, 4169029889u, 2072266145u), + SC(3395707749u, 1912264784u, 839246291u, 1812660322u, 2590197689u, 3115125394u, 280633483u, 1476186344u, 2182942190u, 4022517575u, 1314348304u, 2211853573u, 1730367526u, 3842875309u, 1411362967u, 749836026u), + SC(822183119u, 2084092802u, 2957672615u, 1548122281u, 2555590320u, 4127903458u, 704941703u, 3216796016u, 1310798669u, 1681974379u, 2704001393u, 836064664u, 2498528840u, 2878347924u, 3344415063u, 1714110968u), + SC(3763417450u, 1647484613u, 2916400914u, 1340277384u, 3671023234u, 2962715012u, 2086976330u, 2356641838u, 861453503u, 2497852292u, 3384683911u, 2044029625u, 3423593678u, 602612346u, 1947876325u, 1071593133u), + SC(502143537u, 3800930061u, 289630048u, 2019675509u, 690814111u, 1395759030u, 2095320716u, 1658529388u, 2140950369u, 4113871752u, 2130755443u, 1184235968u, 2624156111u, 1053548247u, 1666584094u, 3436241707u) +}, +{ + SC(2819478132u, 2629026829u, 2945562911u, 1854605392u, 41922071u, 2531530491u, 2316774439u, 3550381961u, 1180787169u, 3914439365u, 3786421842u, 3441223373u, 494782102u, 2858003292u, 1448968751u, 2940369046u), + SC(1228705098u, 2320747717u, 1742025124u, 3358828738u, 1857762103u, 2669617968u, 2684123743u, 2427291148u, 3948024171u, 3841263454u, 3817968782u, 3617000488u, 3457510946u, 3443415072u, 3976288418u, 291039859u), + SC(1118114309u, 1364783097u, 3986370035u, 1058514953u, 3723130907u, 2966082807u, 1592373613u, 4029958112u, 1261460522u, 159904028u, 385928252u, 2962822321u, 213058425u, 39305506u, 3400567258u, 2953928339u), + SC(4004285350u, 3275325131u, 2912133301u, 482119944u, 699333459u, 1353300830u, 498723416u, 2738735797u, 3773472794u, 1167510524u, 1995708610u, 1872986795u, 1771998886u, 460328822u, 2566240531u, 3665251184u), + SC(870908870u, 249845288u, 3674648542u, 3670939624u, 3213883826u, 2765218754u, 3292181727u, 1765634472u, 2846619223u, 156162860u, 2158300764u, 3792761756u, 4248292998u, 1588571137u, 1696144875u, 2915693433u), + SC(1257645965u, 743351844u, 3299328612u, 1606739395u, 2242479072u, 526126122u, 3132670209u, 2327012389u, 1257540758u, 1688790030u, 864103666u, 1782879705u, 2344074317u, 878043196u, 569218289u, 3875319913u), + SC(676712446u, 2310487862u, 3297058723u, 154140360u, 1534807165u, 2207878247u, 4002312458u, 1195155314u, 3973562995u, 203866583u, 1307033594u, 1808951889u, 3485439766u, 2123920858u, 3400721970u, 628518531u), + SC(453432196u, 3506137302u, 962794710u, 2800823697u, 944975983u, 445662356u, 620440622u, 225699982u, 1038708892u, 3484553780u, 4174808994u, 3862318255u, 1961625058u, 2183421173u, 2682639230u, 3890472885u), + SC(3472048934u, 1436162338u, 4281682055u, 1419885595u, 1926695253u, 861477946u, 2586543901u, 2286266784u, 2854911092u, 1779735787u, 2994125983u, 2248840912u, 677288518u, 3593153557u, 3383199489u, 2094768467u), + SC(971218259u, 3653638590u, 3374334294u, 479058129u, 1331477004u, 2497262229u, 892109896u, 3651901580u, 1455849852u, 2738531309u, 14202660u, 1968080740u, 1927308794u, 897128363u, 3654300057u, 1275380700u), + SC(684658124u, 660984744u, 2929312783u, 1473333980u, 1562502960u, 656352357u, 338449257u, 2159155320u, 2425193686u, 930413364u, 2001285554u, 307432757u, 2238003500u, 1858295105u, 481986971u, 1067622012u), + SC(943383548u, 127299943u, 2909652237u, 1257655712u, 4123282405u, 78394323u, 1736026340u, 2126927829u, 296638455u, 1861436609u, 641299684u, 636649068u, 3331138991u, 1014270261u, 257248847u, 1556179874u), + SC(2668740334u, 4261010365u, 3376970497u, 2258271000u, 3369826513u, 906131732u, 12531263u, 2501581679u, 861444520u, 2059219969u, 3536488433u, 3392343056u, 3231250347u, 3425501702u, 4204845226u, 3883035310u), + SC(875006280u, 3061145215u, 799684212u, 4150716124u, 1344915012u, 1442298502u, 887378800u, 2722425542u, 4141895498u, 4068116328u, 601774281u, 3538746538u, 1671758462u, 3066546971u, 1116345758u, 554718074u), + SC(1149406575u, 702696847u, 505403366u, 331269161u, 664926760u, 2151357672u, 2890104906u, 3156886545u, 1199701084u, 1614409973u, 4222014462u, 1336462493u, 3214687968u, 1279434993u, 2285235388u, 2975474024u), + SC(2419658919u, 481424988u, 2207220911u, 2736159805u, 4086711147u, 477511738u, 1428567116u, 3971000648u, 429362137u, 3495313342u, 3653961670u, 4170077754u, 2057308114u, 1445981917u, 97057494u, 3847612010u) +}, +{ + SC(3017729014u, 3423125690u, 1534829496u, 1346803271u, 888659105u, 1661894766u, 4165031912u, 697485157u, 3575889724u, 1795181757u, 1507549874u, 1480154979u, 3565672142u, 830054113u, 1507719534u, 3652903656u), + SC(4123340423u, 2168639254u, 3491407759u, 395600125u, 2056091205u, 1233197217u, 2716612715u, 3263564356u, 2257286689u, 2753339767u, 2228663460u, 3584404544u, 3972978154u, 3637886739u, 3854541466u, 1603898424u), + SC(641806023u, 3776877383u, 3574980110u, 2564901152u, 1378226343u, 738790225u, 4030459977u, 2255719927u, 295765315u, 60094770u, 422069111u, 439158593u, 3956842123u, 1242303994u, 150522972u, 3682386439u), + SC(2385589330u, 2076597417u, 605447848u, 3200763641u, 3106877254u, 3374069827u, 3828392492u, 1315607291u, 3211667999u, 305089333u, 179172787u, 3225149656u, 1080822644u, 3286534940u, 2231515542u, 2699760148u), + SC(3983719183u, 1208009460u, 767048521u, 326825213u, 1087716958u, 3599826498u, 3107818740u, 2785268698u, 1304576537u, 1847155836u, 3250405674u, 2694326935u, 2163030471u, 3253944705u, 1698753082u, 3845065767u), + SC(2823293375u, 2790862099u, 1207038844u, 3886043838u, 3567640686u, 3799791258u, 1638354726u, 1428653770u, 2075289233u, 1582582790u, 213364421u, 2858522524u, 2809903954u, 1742449197u, 324107072u, 1051562955u), + SC(2291926834u, 1805734123u, 3420689573u, 1003089617u, 476535216u, 1334543097u, 2045923069u, 2990972415u, 1822043289u, 2128934150u, 3541372378u, 1912558832u, 2295908612u, 1500502429u, 3539272060u, 2641558214u), + SC(3069594753u, 3051481608u, 2339450545u, 2054924228u, 4282917353u, 65440790u, 2134400604u, 3588265957u, 2569563771u, 741034486u, 740973978u, 93172292u, 1583303041u, 2980574219u, 2969067524u, 1088571815u), + SC(78721532u, 1566330912u, 1219109269u, 3229207312u, 2345730495u, 3209647323u, 2033975193u, 1009666575u, 2794060854u, 4218956981u, 3379703631u, 2400336569u, 100401885u, 3519721431u, 4007729122u, 3851183625u), + SC(2344993313u, 2454241381u, 3071516966u, 4207668067u, 250885582u, 1733938903u, 1658948056u, 2192440210u, 1717829063u, 849763004u, 2334162093u, 3715296533u, 1757279167u, 3270001477u, 2677428083u, 4197601814u), + SC(2911676146u, 4069956071u, 3299890629u, 3133371278u, 3551760603u, 558967408u, 205243474u, 237180706u, 4227661901u, 390685951u, 658498389u, 225847327u, 3028263358u, 3941067795u, 1850521034u, 1584413524u), + SC(304549398u, 3089811378u, 549382137u, 2353383127u, 2278640956u, 781853185u, 1734676013u, 3311472816u, 957105351u, 1291924767u, 2025324585u, 3897237789u, 80455313u, 302089802u, 3496158310u, 4000611245u), + SC(1221283087u, 3865703766u, 1551786763u, 3208862988u, 2964616465u, 1429406173u, 2847895093u, 3047143885u, 3187847794u, 3875229246u, 2044093786u, 2855772466u, 2252977997u, 1253496627u, 1824313803u, 3492626272u), + SC(1435191953u, 2954553263u, 3689501374u, 3761866706u, 3160683386u, 2172174457u, 4033800334u, 2293562561u, 500568896u, 2877151546u, 112648553u, 2760351679u, 1976713840u, 2960166087u, 1364536484u, 4127293522u), + SC(2942286091u, 3570696800u, 2680748212u, 879905933u, 371824626u, 2796545677u, 2544287558u, 1654320774u, 3724452395u, 1875952433u, 1755420330u, 700510406u, 2122483560u, 357724466u, 2579725929u, 4152935597u), + SC(732269412u, 3045632405u, 947036931u, 2403831527u, 2919479301u, 2947112020u, 1653738112u, 2316444303u, 3103978479u, 2856978461u, 308282125u, 1154683958u, 2086296447u, 1288456128u, 528614237u, 2945631134u) +}, +{ + SC(3751554592u, 1759634227u, 4138518211u, 3130599659u, 3881948336u, 669688286u, 3672211577u, 695226401u, 1226786139u, 1855160209u, 905875552u, 2831529665u, 1625185017u, 3130043300u, 3227522138u, 3659203373u), + SC(399372699u, 529779700u, 1206056828u, 1867177702u, 196488961u, 2148657353u, 2522788662u, 2308787051u, 1566407979u, 857878238u, 2852634973u, 2131204123u, 2812808340u, 3651465982u, 1947448513u, 3757182587u), + SC(3732610632u, 1025396308u, 60450219u, 3075208965u, 2460440177u, 301478800u, 2020185415u, 2910424285u, 1627945543u, 473410099u, 4114096970u, 2440686062u, 3031404169u, 2099206907u, 1232790956u, 2248800462u), + SC(2343232878u, 1198836246u, 1270188071u, 2305538045u, 1841160260u, 1049160535u, 2935147928u, 3818293360u, 2128394208u, 692132409u, 3183837651u, 981952986u, 3501941431u, 1239605342u, 1265208179u, 225920797u), + SC(1958540456u, 418545838u, 1645667403u, 4203505141u, 81660142u, 351421726u, 2877676470u, 871152679u, 2804776066u, 431108218u, 927442607u, 3782508732u, 318483929u, 4079394971u, 1143889788u, 4195920424u), + SC(2351179626u, 1598459225u, 3579449038u, 4292231882u, 2911534527u, 3174868713u, 2883217980u, 1046921244u, 3074833211u, 117299980u, 3425406982u, 2813303717u, 879305153u, 3439142119u, 1270010014u, 2633468950u), + SC(3394012837u, 1133386629u, 2931266329u, 2512080059u, 3268046571u, 585832644u, 1151303760u, 4164956195u, 1787214290u, 3523549326u, 4139598868u, 530139359u, 2107355242u, 1401770006u, 4264627539u, 3014221080u), + SC(1988836761u, 3474599222u, 2535855552u, 3118306895u, 1953046625u, 30632894u, 8987922u, 1482010220u, 1585584845u, 441041520u, 3045700482u, 362734762u, 3723600227u, 1056985402u, 2472480517u, 3558297033u), + SC(4137318322u, 915055827u, 1432589840u, 3550795442u, 1919127293u, 1256417138u, 946345068u, 1353195020u, 2948635882u, 3916808200u, 3223857138u, 2259986522u, 636089773u, 2116476405u, 266813303u, 3992924481u), + SC(1294364269u, 2282087282u, 719947200u, 1065389577u, 67185303u, 600695627u, 3423704882u, 507439949u, 1464333499u, 954935833u, 1949391476u, 2146234814u, 640934838u, 2477152026u, 3767255766u, 2397668523u), + SC(1825548026u, 2780595753u, 282065873u, 3347141416u, 3152283414u, 1656153711u, 1047376382u, 3616949007u, 464657631u, 3299783240u, 1162505878u, 3862534742u, 3899846651u, 3980167606u, 2513773976u, 1803555687u), + SC(734708953u, 181663675u, 2018505992u, 1055015000u, 2266993350u, 3679506170u, 1032089726u, 2239152753u, 3271229362u, 257492591u, 519168390u, 890304984u, 594386284u, 933877218u, 2646719799u, 439652468u), + SC(1253204385u, 2215899770u, 848155650u, 1305331452u, 1831981169u, 4101626048u, 253253616u, 718148001u, 3846087699u, 2362703617u, 564971301u, 878503956u, 2792594154u, 3831500219u, 630060686u, 2654848235u), + SC(2082956373u, 965635733u, 1172460454u, 3057130868u, 485386699u, 558270142u, 2819896785u, 247008390u, 1884023798u, 3291747866u, 1725636793u, 1552257124u, 171155452u, 894504521u, 3157754944u, 4135144713u), + SC(3013624247u, 3479051648u, 3976465681u, 139584997u, 690715168u, 2972053528u, 2543659091u, 81834710u, 261064551u, 1476481099u, 2550215537u, 1381589752u, 3557508349u, 3578290922u, 1272133161u, 3008228265u), + SC(3507369103u, 1077600519u, 1522596015u, 3088783267u, 2852999673u, 751358577u, 733140212u, 3467225217u, 100497019u, 50410977u, 68742811u, 3090618848u, 1603912616u, 2272476179u, 1767751118u, 3249696448u) +}, +{ + SC(2950670644u, 1870384244u, 3964091927u, 4110714448u, 298132763u, 3177974896u, 3260855649u, 1258311080u, 2976836646u, 3581267654u, 3094482836u, 80535005u, 2024129606u, 168620678u, 4254285674u, 2577025593u), + SC(1515179601u, 3578614970u, 3088354879u, 797813018u, 1355130048u, 1083957563u, 119796717u, 2021253602u, 1525138732u, 4127381203u, 3062851977u, 4142386071u, 1213064952u, 3609844670u, 1484215992u, 3431673114u), + SC(1401099367u, 3953214819u, 830584870u, 2207781603u, 918659453u, 4293181358u, 4072336467u, 4282551694u, 262435288u, 1941569548u, 147995405u, 1811389750u, 4118444114u, 1252574507u, 578798636u, 1074483177u), + SC(2872591360u, 1058667772u, 16799222u, 688522560u, 3475129040u, 3433794124u, 1076991040u, 1425059515u, 2939587530u, 236447274u, 3960100164u, 1298525395u, 2761371754u, 4025787449u, 2464666072u, 3981743594u), + SC(3976786453u, 1358319886u, 3905641993u, 1405765539u, 2585003073u, 3447572652u, 741448872u, 3444688769u, 971292808u, 1486657617u, 3079335839u, 862424956u, 248802634u, 1703726921u, 2982469234u, 2682500687u), + SC(4273605693u, 2467118193u, 3538801384u, 3862847335u, 1065478730u, 1602785515u, 1071410798u, 2624755760u, 2768741032u, 2700950902u, 558848464u, 3400938789u, 1410632048u, 2094050860u, 1686695852u, 2101955993u), + SC(4124709913u, 3191744141u, 3038636619u, 2944952304u, 2687117769u, 1502766822u, 14738299u, 223780235u, 32298390u, 1195949618u, 1154476371u, 1873391152u, 273358443u, 2362272244u, 509120994u, 606974408u), + SC(3937286725u, 1520668653u, 941545039u, 3056942351u, 574018151u, 2549472282u, 82289937u, 374652507u, 619831005u, 2134744303u, 1462663193u, 2963006112u, 3726585674u, 1797461239u, 1470634776u, 3441417480u), + SC(2845288945u, 3925574221u, 1989126288u, 3105801567u, 210047271u, 1545005898u, 2572648420u, 2278643173u, 2633053858u, 3288168184u, 3566345146u, 165026071u, 191806458u, 4116335861u, 1768316231u, 3169297484u), + SC(253765755u, 2509241970u, 1926513613u, 3735004917u, 4188741775u, 2806800711u, 281300019u, 3635185u, 3462483807u, 2277745510u, 1708651892u, 1413928970u, 56262931u, 531946794u, 2864634184u, 3118504241u), + SC(4194010611u, 4232988065u, 1802432341u, 3448133339u, 3732370320u, 253801846u, 2726367450u, 3905836819u, 1373544282u, 2066678017u, 3439519431u, 3381452691u, 2754663978u, 535580478u, 2512241599u, 2720083475u), + SC(3589933363u, 4047249230u, 2311777188u, 270484672u, 1108190662u, 2080251561u, 1724842405u, 4014518744u, 1593608472u, 2342434397u, 4205240553u, 2166622191u, 3528923u, 1996089122u, 4284726332u, 989608730u), + SC(2475269743u, 4230552139u, 3917936952u, 3098769598u, 3209444661u, 4188126675u, 3974782724u, 3639917274u, 2711234947u, 1439392508u, 1127433801u, 478802541u, 4223040451u, 2268034322u, 2452212595u, 3508939070u), + SC(2413851784u, 190519100u, 3576747926u, 2710481928u, 2148944938u, 3984096005u, 2427227598u, 1001464024u, 2191178977u, 1139441673u, 3841324161u, 308061908u, 3976150834u, 1467800561u, 3226772030u, 1743883019u), + SC(281260179u, 1415659644u, 915707047u, 1662956706u, 911938094u, 3456789397u, 2082200558u, 947098788u, 4036848108u, 2455542339u, 1466205449u, 4158358953u, 586549709u, 850657486u, 61343079u, 2292663847u), + SC(3487862268u, 4116082621u, 1969417576u, 1466595601u, 3136251120u, 3697533272u, 438943523u, 1041892750u, 1141661777u, 435333448u, 3031876514u, 2121342186u, 209290199u, 256519609u, 1400190683u, 4260080502u) +}, +{ + SC(1406628534u, 2978091511u, 343468499u, 973866526u, 757277528u, 1142388839u, 2945536141u, 3759469101u, 3001571847u, 2170606364u, 1017327004u, 3120716036u, 468321128u, 3656061918u, 2331571461u, 1930702552u), + SC(3117811324u, 4230396490u, 526101390u, 3589443580u, 12282838u, 3055128772u, 453582536u, 750425919u, 87216299u, 1999749165u, 2446098001u, 1907762611u, 183870981u, 3643605669u, 4232900175u, 2946539195u), + SC(3903405291u, 1034986659u, 2587588236u, 1880077572u, 1696686560u, 1243434386u, 3746745675u, 2212912696u, 2031851135u, 575946730u, 2663616094u, 2706019532u, 2635197066u, 1942621203u, 3760379195u, 4173271368u), + SC(2892050679u, 1105289247u, 1519565685u, 2426902952u, 65580444u, 3373395323u, 2112756687u, 3658806066u, 2548718870u, 3586646888u, 3350821933u, 1921239811u, 4061525916u, 3520594550u, 1872307168u, 3464547908u), + SC(2889143489u, 489507550u, 788811400u, 1800916293u, 3249681744u, 1400920516u, 3917828215u, 1093821500u, 1905385813u, 2931012984u, 1800788801u, 1697549042u, 3133274419u, 3606456099u, 2156683634u, 3205410986u), + SC(2814687995u, 4053305746u, 484530004u, 410862009u, 246830045u, 3164065541u, 3723774424u, 3388961612u, 3438413619u, 3662326637u, 2178649434u, 3555798301u, 164350275u, 2341607004u, 3896269562u, 1591806179u), + SC(3226183767u, 3881369008u, 700458770u, 376569395u, 2607908019u, 1353553198u, 2636334721u, 1140283021u, 2632309194u, 1710844790u, 3031461719u, 4081969123u, 3326745889u, 4034909949u, 3950856167u, 3153389256u), + SC(2184243175u, 2166726232u, 3921103433u, 872887260u, 623636347u, 95935618u, 2766774027u, 697875047u, 164043041u, 993154257u, 4114304816u, 3500729957u, 409872172u, 3504722710u, 2806324915u, 717798207u), + SC(1913401183u, 1684394893u, 957780895u, 2366199383u, 3846687839u, 2225031745u, 50628017u, 764720583u, 2251658783u, 1601491318u, 3836612294u, 3836982164u, 1834686310u, 4239983357u, 2677791106u, 718595268u), + SC(641418698u, 3008658673u, 1590313857u, 1025261614u, 1545641278u, 883067087u, 405447843u, 251932751u, 890679795u, 1380695500u, 4259157180u, 4219905082u, 665298826u, 4240175069u, 1720908833u, 2268480568u), + SC(1323007329u, 2757671761u, 531677728u, 1863777888u, 1512057206u, 2416428007u, 297355401u, 2843988168u, 3028483811u, 4269951770u, 844221740u, 1060678479u, 2913804270u, 3550002834u, 1490208797u, 2041637686u), + SC(4098631786u, 3088674341u, 2277647863u, 546429701u, 239595915u, 96051385u, 2043858235u, 356783975u, 3081379864u, 1495630942u, 1713035648u, 2797737429u, 4252005067u, 1174473008u, 182861961u, 1284115192u), + SC(1497340893u, 2990980382u, 435071738u, 25048206u, 1369038540u, 2388914024u, 3985375113u, 3187649864u, 1375850783u, 2762762203u, 3714513839u, 1546363407u, 2343675571u, 416152492u, 1797618344u, 3540898582u), + SC(2184924310u, 2347360549u, 640504537u, 1253044800u, 1440674061u, 1666425671u, 3827600864u, 2022304946u, 2918906490u, 263308814u, 3892002350u, 1942380643u, 1520343008u, 1245225248u, 3081248535u, 2098883649u), + SC(2377054091u, 3295547231u, 2240796492u, 1757295037u, 62158041u, 1809272299u, 4005194159u, 1592984938u, 366675588u, 3144502911u, 2973082795u, 4105706826u, 2851896979u, 3262002710u, 3082369242u, 634669574u), + SC(729159370u, 3948971047u, 1511320403u, 3061460707u, 3090283349u, 1868816562u, 3759558902u, 3868199437u, 2438888892u, 1660478281u, 2415784493u, 3546303863u, 3144683831u, 3066258755u, 2228021651u, 3294706852u) +} +}; +#undef SC +#endif diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/secp256k1_main.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/secp256k1_main.h new file mode 100644 index 000000000..ff54afffe --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/secp256k1_main.h @@ -0,0 +1,5 @@ +//! Project version number for secp256k1. +FOUNDATION_EXPORT double secp256k1VersionNumber; + +//! Project version string for secp256k1. +FOUNDATION_EXPORT const unsigned char secp256k1VersionString[]; diff --git a/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/util.h b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/util.h new file mode 100644 index 000000000..de2a002ba --- /dev/null +++ b/Example/myWeb3Wallet/Pods/secp256k1.c/secp256k1/util.h @@ -0,0 +1,119 @@ +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_UTIL_H +#define SECP256K1_UTIL_H + +#include "secp256k1-config.h" + +#include +#include +#include + +typedef struct { + void (*fn)(const char *text, void* data); + const void* data; +} secp256k1_callback; + +static SECP256K1_INLINE void secp256k1_callback_call(const secp256k1_callback * const cb, const char * const text) { + cb->fn(text, (void*)cb->data); +} + +#ifdef DETERMINISTIC +#define TEST_FAILURE(msg) do { \ + fprintf(stderr, "%s\n", msg); \ + abort(); \ +} while(0); +#else +#define TEST_FAILURE(msg) do { \ + fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, msg); \ + abort(); \ +} while(0) +#endif + +#ifdef HAVE_BUILTIN_EXPECT +#define EXPECT(x,c) __builtin_expect((x),(c)) +#else +#define EXPECT(x,c) (x) +#endif + +#ifdef DETERMINISTIC +#define CHECK(cond) do { \ + if (EXPECT(!(cond), 0)) { \ + TEST_FAILURE("test condition failed"); \ + } \ +} while(0) +#else +#define CHECK(cond) do { \ + if (EXPECT(!(cond), 0)) { \ + TEST_FAILURE("test condition failed: " #cond); \ + } \ +} while(0) +#endif + +/* Like assert(), but when VERIFY is defined, and side-effect safe. */ +#if defined(COVERAGE) +#define VERIFY_CHECK(check) +#define VERIFY_SETUP(stmt) +#elif defined(VERIFY) +#define VERIFY_CHECK CHECK +#define VERIFY_SETUP(stmt) do { stmt; } while(0) +#else +#define VERIFY_CHECK(cond) do { (void)(cond); } while(0) +#define VERIFY_SETUP(stmt) +#endif + +static SECP256K1_INLINE void *checked_malloc(const secp256k1_callback* cb, size_t size) { + void *ret = malloc(size); + if (ret == NULL) { + secp256k1_callback_call(cb, "Out of memory"); + } + return ret; +} + +static SECP256K1_INLINE void *checked_realloc(const secp256k1_callback* cb, void *ptr, size_t size) { + void *ret = realloc(ptr, size); + if (ret == NULL) { + secp256k1_callback_call(cb, "Out of memory"); + } + return ret; +} + +/* Macro for restrict, when available and not in a VERIFY build. */ +#if defined(SECP256K1_BUILD) && defined(VERIFY) +# define SECP256K1_RESTRICT +#else +# if (!defined(__STDC_VERSION__) || (__STDC_VERSION__ < 199901L) ) +# if SECP256K1_GNUC_PREREQ(3,0) +# define SECP256K1_RESTRICT __restrict__ +# elif (defined(_MSC_VER) && _MSC_VER >= 1400) +# define SECP256K1_RESTRICT __restrict +# else +# define SECP256K1_RESTRICT +# endif +# else +# define SECP256K1_RESTRICT restrict +# endif +#endif + +#if defined(_WIN32) +# define I64FORMAT "I64d" +# define I64uFORMAT "I64u" +#else +# define I64FORMAT "lld" +# define I64uFORMAT "llu" +#endif + +#if defined(HAVE___INT128) +# if defined(__GNUC__) +# define SECP256K1_GNUC_EXT __extension__ +# else +# define SECP256K1_GNUC_EXT +# endif +SECP256K1_GNUC_EXT typedef unsigned __int128 uint128_t; +#endif + +#endif /* SECP256K1_UTIL_H */ diff --git a/Example/myWeb3Wallet/Pods/web3swift/LICENSE.md b/Example/myWeb3Wallet/Pods/web3swift/LICENSE.md new file mode 100755 index 000000000..ed25277cc --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/LICENSE.md @@ -0,0 +1,203 @@ +Copyright (c) 2018 Aleksandr Vlasov, + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018 Aleksandr Vlasov + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Example/myWeb3Wallet/Pods/web3swift/README.md b/Example/myWeb3Wallet/Pods/web3swift/README.md new file mode 100755 index 000000000..ab4662ba1 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/README.md @@ -0,0 +1,426 @@ +# web3swift +**web3swift** is an iOS toolbelt for interaction with the Ethereum network. + +## [Join our discord](https://discord.gg/npZ6SuSS) if you need a support or want to contribute to web3swift development! + +![matter-github-swift](https://github.com/skywinder/web3swift/blob/develop/web3swift-logo.png) +[![Build Status](https://travis-ci.com/skywinder/web3swift.svg?branch=develop)](https://travis-ci.com/skywinder/web3swift) +[![Swift](https://img.shields.io/badge/Swift-5.4-orange.svg?style=flat)](https://developer.apple.com/swift/) +[![Platform](https://img.shields.io/cocoapods/p/web3swift.svg?style=flat)](http://cocoapods.org/pods/web3.swift.pod) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/web3.swift.pod.svg?style=flat)](http://cocoapods.org/pods/web3.swift.pod) +[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![License](https://img.shields.io/cocoapods/l/web3swift.svg?style=flat)](http://cocoapods.org/pods/web3.swift.pod) +[![support](https://brianmacdonald.github.io/Ethonate/svg/eth-support-blue.svg)](https://brianmacdonald.github.io/Ethonate/address#0xe22b8979739d724343bd002f9f432f5990879901) +[![Stackoverflow](https://img.shields.io/badge/stackoverflow-ask-blue.svg)](https://stackoverflow.com/questions/tagged/web3swift) + +--- + + + + + +- [Core features](#core-features) +- [Installation](#installation) + - [Example usage](#example-usage) + - [Send Ether](#send-ether) + - [Send ERC-20 Token](#send-erc-20-token) + - [Write Transaction and call smart contract method](#write-transaction-and-call-smart-contract-method) + - [Web3View example](#web3view-example) + - [Build from source](#build-from-source) + - [Requirements](#requirements) + - [Migration Guides](#migration-guides) +- [Documentation](#documentation) +- [Projects that are using web3swift](#projects-that-are-using-web3swift) +- [Support](#support) +- [Contribute](#contribute) + - [Future steps](#future-steps) +- [Credits](#credits) +- [Security Disclosure](#security-disclosure) +- [License](#license) + + + +## 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] 🔐 Local **keystore management** (`geth` compatible) +- [x] 🤖 Smart-contract **ABI parsing** +- [x] 🔓**ABI deconding** (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] ⛩ **Infura support**, patial Websockets API support +- [x] ⚒ **Parsing TxPool** content into native values (ethereum addresses and transactions) - easy to get pending transactions +- [x] 🖇 **Event loops** functionality +- [x] 📱Supports Web3View functionality (WKWebView with **injected "web3" provider**) +- [x] 🕵️‍♂️ Possibility to **add or remove "middleware" that intercepts**, modifies and even **cancel transaction** workflow on stages "before assembly", "after assembly"and "before submission" +- [x] ✅**Literally following the standards** (BIP, EIP, etc): + + - [x] **[BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) (HD Wallets), [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) (Seed phrases), [BIP44](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki) (Key generation prefixes)** +- [x] **[EIP-20](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md)** (Standart interface for tokens - ERC-20), **[EIP-67](https://github.com/ethereum/EIPs/issues/67)** (Standard URI scheme), **[EIP-155](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md)** (Replay attacks protection) + - [x] **And many others** *(For details about this EIP's look at [Documentation page](https://github.com/skywinder/web3swift/blob/master/Documentation/))*: EIP-681, EIP-721, EIP-165, EIP-777, EIP-820, EIP-888, EIP-1400, EIP-1410, EIP-1594, EIP-1643, EIP-1644, EIP-1633, EIP-721, EIP-1155, EIP-1376, ST-20 + +- [x] 🗜 **Batched requests** in concurrent mode +- [x] **RLP encoding** +- [x] Base58 encoding scheme +- [x] Formatting to and from Ethereum Units +- [x] Comprehensive Unit and Integration Test Coverage + +## Installation + +### CocoaPods + +[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: + +```bash +$ sudo gem install cocoapods +``` + +To integrate web3swift into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '9.0' + +target '' do + use_frameworks! + pod 'web3swift' +end + +``` + + +Then, run the following command: + +```bash +$ pod install +``` + +### Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. + +You can install Carthage with [Homebrew](https://brew.sh/) using the following command: + +```bash +$ brew update +$ brew install carthage +``` + +To integrate web3swift into your Xcode project using Carthage, specify it in your `Cartfile`. +Create an empty Cartfile with the touch command and open it: + +```bash +$ touch Cartfile +$ open -a Xcode Cartfile +``` + +Add the following line to the Cartfile and save it: + +```ogdl +github "skywinder/web3swift" "master" +``` + +Run `carthage update --no-use-binaries --platform iOS` to build the framework. By default, Carthage performs checkouts and creates a new directory 'Carthage' in the same location as your Cartfile. Open this directory, go to 'Build' directory, choose iOS or macOS directory, and use the selected directory framework in your Xcode project. + + + +### Swift Package +Open xcode setting and add this repo as a source + +### Example usage + +In the imports section: + +```swift +import web3swift +``` + +##### Send Ether + +```swift +let value: String = "1.0" // In Ether +let walletAddress = EthereumAddress(wallet.address)! // Your wallet address +let toAddress = EthereumAddress(toAddressString)! +let contract = web3.contract(Web3.Utils.coldWalletABI, at: toAddress, abiVersion: 2)! +let amount = Web3.Utils.parseToBigUInt(value, units: .eth) +var options = TransactionOptions.defaultOptions +options.value = amount +options.from = walletAddress +options.gasPrice = .automatic +options.gasLimit = .automatic +let tx = contract.write( +"fallback", +parameters: [AnyObject](), +extraData: Data(), +transactionOptions: options)! +``` + +##### Send ERC-20 Token + +```swift +let web3 = Web3.InfuraMainnetWeb3() +let value: String = "1.0" // In Tokens +let walletAddress = EthereumAddress(wallet.address)! // Your wallet address +let toAddress = EthereumAddress(toAddressString)! +let erc20ContractAddress = EthereumAddress(token.address)! +let contract = web3.contract(Web3.Utils.erc20ABI, at: erc20ContractAddress, abiVersion: 2)! +let amount = Web3.Utils.parseToBigUInt(value, units: .eth) +var options = TransactionOptions.defaultOptions +options.value = amount +options.from = walletAddress +options.gasPrice = .automatic +options.gasLimit = .automatic +let method = "transfer" +let tx = contract.write( + method, + parameters: [toAddress, amount] as [AnyObject], + extraData: Data(), + transactionOptions: options)! +``` + + +##### Get account balance +```swift +let web3 = Web3.InfuraMainnetWeb3() +let address = EthereumAddress("
")! +let balance = try web3.eth.getBalance(address: address) +let balanceString = Web3.Utils.formatToEthereumUnits(balance, toUnits: .eth, decimals: 3) +``` + +##### Write Transaction and call smart contract method + +```swift +let web3 = Web3.InfuraMainnetWeb3() +let value: String = "0.0" // Any amount of Ether you need to send +let walletAddress = EthereumAddress(wallet.address)! // Your wallet address +let contractMethod = "SOMECONTRACTMETHOD" // Contract method you want to write +let contractABI = "..." // Contract ABI +let contractAddress = EthereumAddress(contractAddressString)! +let abiVersion = 2 // Contract ABI version +let parameters: [AnyObject] = [...]() // Parameters for contract method +let extraData: Data = Data() // Extra data for contract method +let contract = web3.contract(contractABI, at: contractAddress, abiVersion: abiVersion)! +let amount = Web3.Utils.parseToBigUInt(value, units: .eth) +var options = TransactionOptions.defaultOptions +options.value = amount +options.from = walletAddress +options.gasPrice = .automatic +options.gasLimit = .automatic +let tx = contract.write( + contractMethod, + parameters: parameters, + extraData: extraData, + transactionOptions: options)! +``` + + +#### Write Transaction with your custom contract ABI +#### Requirement : Your custom contract ABI string +```Code + func contractTransactionMethod(){ + let yourCoin = self.yourbalance.text ?? "0.0" //Get token for sending + let userDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] //get user directory for keystore + if (FileManager.default.fileExists(atPath: userDir + "/keystore/key.json")) { + //Create Keystore + guard let manager = FilestoreWrapper.getKeystoreManager() else { + print("Manager not found ") + return + } + wethioKeystoreManager = manager + guard let urlStr = URL(string: "Your rpc url here") else { return } + guard let kManager = yourKeystoreManager else { return } + + //Create Web3Provider Instance with key manager + web3ProvideInstance = Web3HttpProvider(urlStr, keystoreManager: kManager) + guard let wProvier = self.web3ProvideInstance else {return} + self.web3Instance = Web3(provider: wProvier) //Set provide instance with web3 + guard let wInstance = self.web3Instance else {return} + self.receiverAddressString = self.walletAddressTF.text //get receiver address string + print("Receiver address is : ", self.receiverAddressString ?? " ") + self.etheriumAccountAddress = self.wethioKeystoreManager?.addresses.first?.address //get sender address in string + /* + convert address string into etherium addresss + */ + let senderEthAddress = EthereumAddress(self.etheriumAccountAddress ?? "") + //Run on backgrounnd tread + DispatchQueue.global(qos: .background).async { + do { + //Convert receiver address in to etherium address + let toaddress = EthereumAddress(self.receiverAddressString ?? "") + var options = Web3Options.defaultOptions() //Create web3 options + let amountDouble = BigInt((Double(yourCoin) ?? 0.1)*pow(10, 18)) //Convert amount into BIGINT + print("Total amount in double value : ", amountDouble) + var amount = BigUInt.init(amountDouble) //Convert amount in BIG UI Int + let estimateGasPrice = try wInstance.eth.getGasPrice() //estimate gas price + + guard let eGasReult = self.estimatedGasResult else { + print("Unable to find gas price") + return + } + let nonce = try wInstance.eth.getTransactionCount(address: senderEthAddress) //Get nonce or transaction count + print("Is the Transaction count", nonce) + let fee = estimateGasPrice * eGasReult + /* + adding + - sender address + - Gas Result + - Gas price + - amount + */ + var sendTransactionIntermediateOptions = Web3Options.defaultOptions() + sendTransactionIntermediateOptions.from = senderEthAddress + sendTransactionIntermediateOptions.gasLimit = eGasReult + sendTransactionIntermediateOptions.gasPrice = estimateGasPrice + var tokenTransactionIntermediate: TransactionIntermediate! //Create transaction intermediate + tokenTransactionIntermediate = try wInstance.contract("Your custom contract ABI string", at: contractAddress).method("transfer", args: toaddress, amount, options: sendTransactionIntermediateOptions) + let mainTransaction = try tokenTransactionIntermediate.send(options: sendTransactionIntermediateOptions, onBlock: "latest") + print(mainTransaction.hash, "is the hash of your transaction") + } + } + } + } + +``` + +### Web3View example + +You can see how to our demo project: **WKWebView with injected "web3" provider**: + +``` bash +git clone https://github.com/skywinder/web3swift.git +cd web3swift/Example/web3swiftBrowser +pod install +open ./web3swiftBrowser.xcworkspace +``` + +### Build from source + +### Default web3swift build + +1. Install carthage: +``` +brew install carthage +``` +2. Run carthage update: +``` +# Available platforms: `iOS, macOS` +carthage update --platform iOS --use-xcframeworks +``` +3. Build project in XCode: +`Command + B` + +### Build web3swift into .framework: +``` +carthage build --no-skip-current --platform iOS +``` + +### In case of build errors, please check this solition + +- Install dependencies via `./carthage-build.sh --platform iOS` (temp workaround, for of Carthage bug. [For details please look at](https://github.com/Carthage/Carthage/issues/3019#issuecomment-665136323) + +### Requirements + +- iOS 9.0+ / macOS 10.11+ +- Xcode 10.2+ +- Swift 5.0+ + +### Migration Guides + +- [web3swift 2.0 Migration Guide](https://github.com/matterinc/web3swift/blob/master/Documentation/web3swift%202.0%20Migration%20Guide.md) + +## Documentation + +For full documentation details and FAQ, please look at [Documentation](https://github.com/skywinder/web3swift/blob/master/Documentation/) + +*If you need to find or understand an API, check [Usage.md](https://github.com/skywinder/web3swift/blob/master/Documentation/Usage.md).* + + **FAQ moved [Documentation Page](https://github.com/skywinder/web3swift/blob/master/Documentation/)** + +Here are quick references for essential features: + +- [Preffered models](https://github.com/skywinder/web3swift/blob/master/Documentation/Usage.md#preffered-models) +- [Account Management (create, import, private keys managments, etc.)](https://github.com/skywinder/web3swift/blob/master/Documentation/Usage.md#account-management) +- [Ethereum Endpoints interaction (web3, balance, tx's operations, chain state)](https://github.com/skywinder/web3swift/blob/master/Documentation/Usage.md#ethereum-endpoints-interaction) +- [Websockets](https://github.com/skywinder/web3swift/blob/master/Documentation/Usage.md#websockets) +- [ENS](https://github.com/skywinder/web3swift/blob/master/Documentation/Usage.md#ens) + +## Projects that are using web3swift + +If you are using this library in your project, please [add a link](https://github.com/skywinder/web3swift/edit/develop/README.md) to this repo. + +* [MyEtherWallet/MEWconnect-iOS](https://github.com/MyEtherWallet/MEWconnect-iOS) +* [Peepeth iOS client](https://github.com/matterinc/PeepethClient) +* [Ethereum & ERC20Tokens Wallet](https://itunes.apple.com/us/app/ethereum-erc20tokens-wallet/id1386738877?ls=1&mt=8) +* [Pay-iOS](https://github.com/BANKEX/Pay-iOS) +* [GeoChain](https://github.com/awallish/GeoChain) +* [NewHorizonLabs/TRX-Wallet](https://github.com/NewHorizonLabs/TRX-Wallet) +* [SteadyAction/EtherWalletKit](https://github.com/SteadyAction/EtherWalletKit) +* [UP Wallet/loopr-ios](https://github.com/Loopring/loopr-ios) +* [MyENS Wallet](https://github.com/barrasso/enswallet) +* [LoanStar](https://github.com/barrasso/loan-star) +* [AlphaWallet](https://github.com/AlphaWallet/alpha-wallet-ios) +* [Follow_iOS](https://github.com/FollowInc/Follow_iOS) +* [Biomedical Data Sharing dApp - Geolocation](https://github.com/HD2i/Geolocation-iOS) +* [Alice Wallet](https://github.com/alicedapp/AliceX) +* [web3-react-native](https://github.com/cawfree/web3-react-native) +* [ProLabArt](https://prolabart.com) + + +* [YOUR APP CAN BE THERE (click me)](https://github.com/skywinder/web3swift/edit/develop/README.md) :wink: + +*Nothing makes developers happier than seeing someone else use our work and go wild with it.* + +## Support + +**[Join our discord](https://discord.gg/DZKFJFn3) if you need a support or want to contribute to web3swift development!** + +- If you **need help**, [open an issue](https://github.com/skywinder/web3swift/issues). +- If you'd like to **see web3swift best practices**, check [Projects that using web3swift](https://github.com/skywinder/web3swift#projects-that-using-web3swift). +- If you **found a bug**, [open an issue](https://github.com/skywinder/web3swift/issues). + + +## 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)!** + +- If you **have a feature request**, [open an issue](https://github.com/skywinder/web3swift/issues). + +If you **want to contribute**, [submit a pull request](https://github.com/skywinder/web3swift/pulls). + +#### Contribution +0. You are more than welcome to participate and get bounty by contributing! **Your contribution will be paid via [@gitcoin Grant program](https://gitcoin.co/grants/358/web3swift).** +1. Find or create an [issue](https://github.com/skywinder/web3swift/issues) +2. You can find open bounties in [Gitcoin Bounties](https://gitcoin.co/explorer?applicants=ALL&keywords=web3swift&order_by=-web3_created) list +2. Commita fix or a new feature in branch, push your changes +3. [Submit a pull request to **develop** branch](https://github.com/skywinder/web3swift/pulls) + +[@skywinder](https://github.com/skywinder) are charged with open-sourсe and do not require money for using web3swift library. +We want to continue to do everything we can to move the needle forward. + +- **Support us** via [@gitcoin Grant program](https://gitcoin.co/grants/358/web3swift) +- Ether wallet address: `0x6A3738c6299f45c31697aceA647D49EdCC9C28A4` + + + +- [x] Performance Improvements thanks to @**[xdozorx](https://github.com/xdozorx)** for [Update perfomance of import account](https://github.com/skywinder/web3swift/pull/336) +- [ ] **Modularity** with the basic Web3 subspec/SPM (the most basic functions like transaction signing and interacting with an http rpc server) and other modules with additional functionality +- [ ] [Complete Documentation](https://web3swift.github.io/web3swift) +- [ ] Convenient methods for namespaces + +## Credits + +- Alex Vlasov, [@shamatar](https://github.com/shamatar) - for the initial implementation +- Petr Korolev, [@skywinder](https://github.com/skywinder) - botstrap and continous support +- Anton Grigorev, [@baldyash](https://github.com/BaldyAsh) - core contributor, who use it and making a lot of ipmprovments +- Thanks to [web3swift's growing list of contributors](https://github.com/skywinder/web3swift/graphs/contributors). + +## Security Disclosure + +If you believe you have identified a security vulnerability with web3swift, you should report it as soon as possible via email to [web3swift@oxor.io](mailto:web3swift@oxor.io). Please do not post it to a public issue tracker. + +## License + +web3swift is available under the Apache License 2.0 license. See the [LICENSE](https://github.com/skywinder/web3swift/blob/master/LICENSE) for details. diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Browser/Bridge.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Browser/Bridge.swift new file mode 100644 index 000000000..b31db12bf --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Browser/Bridge.swift @@ -0,0 +1,250 @@ +// +// Bridge.swift +// JSBridge +// +// Created by SunJiangting on 2017/5/27. +// Copyright © 2017 Samaritan. All rights reserved. +// + +import WebKit + +/// Bridge for WKWebView and JavaScript +open class Bridge: NSObject { + + static let name: String = "pacific" + + fileprivate static let callbackEventName = "PacificDidReceiveNativeCallback" + fileprivate static let postEventName = "PacificDidReceiveNativeBroadcast" + + fileprivate enum MessageKey { + static let action = "action" + static let parameters = "parameters" + static let callback = "callback" + static let printable = "print" + } + + public struct JSError { + public let code: Int + public let description: String + + public init(code: Int, description: String) { + self.code = code + self.description = description + } + } + + /// Used to callback to webpage whether a message from webpage was handled successful or encountered an error. + /// + /// - success: The result of message was successful + /// + /// - failure: Unable to handle the message, notify js with error by **Object Error** { code: Int, description: String} + /// + public enum Results { + + case success([String: Any]?) + + case failure(JSError) + } + + /// Bridge Callback to webpage + /// - Parameter results: Value pass to webpage + public typealias Callback = (_ results: Results) -> Void + + /// Closure when js send message to native + /// - Parameter parameters: js parameters + /// - Parameter callback: callback func + public typealias Handler = (_ parameters: [String: Any]?, _ callback: @escaping Callback) -> Void + + public typealias DefaultHandler = (_ name: String, _ parameters: [String: Any]?, _ callback: @escaping Callback) -> Void + + private(set) var handlers = [String: Handler]() + + public var defaultHandler: DefaultHandler? + + fileprivate let configuration: WKWebViewConfiguration + fileprivate weak var webView: WKWebView? + + /// Print message body from webpage automatically. + public var printScriptMessageAutomatically = false + + deinit { + configuration.removeObserver(self, forKeyPath: #keyPath(WKWebViewConfiguration.userContentController)) + configuration.userContentController.removeScriptMessageHandler(forName: Bridge.name) + } + + fileprivate init(webView: WKWebView) { + self.webView = webView + self.configuration = webView.configuration + super.init() + configuration.addObserver(self, forKeyPath: #keyPath(WKWebViewConfiguration.userContentController), options: [.new, .old], context: nil) + configuration.userContentController.add(self, name: Bridge.name) + } + + /// Register to handle action + /// - Parameter handler: closure when handle message from webpage + /// - parameter action: name of action + /// + /// - SeeAlso: `Handler` + /// + /// ```javascript + /// // Post Event With Action Name + /// window.bridge.post('print', {message: 'Hello, world'}) + /// // Post Event With Callback + /// window.bridge.post('print', {message: 'Hello, world'}, (parameters, error) => { Handler Parameters Or Error}) + /// ``` + public func register(_ handler: @escaping Handler, for action: String) { + handlers[action] = handler + } + + /// Unregister an action + /// - Parameters action: name of action + public func unregister(for action: String) { + handlers[action] = nil + } + + /// send action to webpage + /// - Parameter action: action listened by js `window.bridge.on(**action**, handler)` + /// - Parameter parameters: parameters pass to js + /// + /// ```javascript + /// // listen native login action + /// window.bridge.on('login', (parameters)=> {console.log('User Did Login')}) + /// ``` + public func post(action: String, parameters: [String: Any]?) { + guard let webView = webView else { return } + webView.st_dispatchBridgeEvent(Bridge.postEventName, parameters: ["name": action], results: .success(parameters), completionHandler: nil) + } + + /// Evaluates the given JavaScript string. + /// - Parameter javaScriptString: The JavaScript string to evaluate. + /// - Parameter completion: A block to invoke when script evaluation completes or fails. + public func evaluate(_ javaScriptString: String, completion: ((Any?, Error?) -> Void)? = nil) { + guard let webView = webView else { return } + webView.evaluateJavaScript(javaScriptString, completionHandler: completion) + } + + open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { + if let obj = object as? WKWebViewConfiguration, let kp = keyPath, obj == configuration && kp == #keyPath(WKWebViewConfiguration.userContentController) { + if let change = change { + if let oldContentController = change[.oldKey] as? WKUserContentController { + oldContentController.removeScriptMessageHandler(forName: Bridge.name) + } + if let newContentController = change[.newKey] as? WKUserContentController { + newContentController.add(self, name: Bridge.name) + } + } + } + } +} + +extension Bridge: WKScriptMessageHandler { + + /*! @abstract Invoked when a script message is received from a webpage. + @param userContentController The user content controller invoking the + delegate method. + @param message The script message received. + */ + public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { + guard let body = message.body as? [String: Any], let name = body[MessageKey.action] as? String else { + return + } + if (body[MessageKey.printable] as? NSNumber)?.boolValue ?? printScriptMessageAutomatically { + print(body) + } + guard let handler = handlers[name] else { + guard let defaultHandler = self.defaultHandler else { + return + } + if let callbackID = (body[MessageKey.callback] as? NSNumber) { + defaultHandler(name, body[MessageKey.parameters] as? [String: Any]) { [weak self] (results) in + guard let strongSelf = self else { + return + } + // Do Nothing + guard let webView = strongSelf.webView else { return } + webView.st_dispatchBridgeEvent(Bridge.callbackEventName, parameters: ["id": callbackID], results: results, completionHandler: nil) + } + } else { + defaultHandler(name, body[MessageKey.parameters] as? [String: Any]) { (results) in + // Do Nothing + } + } + return + } + + if let callbackID = (body[MessageKey.callback] as? NSNumber) { + handler(body[MessageKey.parameters] as? [String: Any]) { [weak self] (results) in + guard let strongSelf = self else { + return + } + // Do Nothing + guard let webView = strongSelf.webView else { return } + webView.st_dispatchBridgeEvent(Bridge.callbackEventName, parameters: ["id": callbackID], results: results, completionHandler: nil) + } + } else { + handler(body[MessageKey.parameters] as? [String: Any]) { (results) in + // Do Nothing + } + } + } +} + +public extension WKWebView { + + private struct STPrivateStatic { + fileprivate static var bridgeKey = "STPrivateStatic.bridgeKey" + } + + /// Bridge for WKWebView and JavaScript. Initialize `lazy` + var bridge: Bridge { + if let bridge = objc_getAssociatedObject(self, &STPrivateStatic.bridgeKey) as? Bridge { + return bridge + } + let bridge = Bridge(webView: self) + objc_setAssociatedObject(self, &STPrivateStatic.bridgeKey, bridge, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + return bridge + } + + /// Remove Bridge And Reset, All the handlers will be removed + func removeBridge() { + if let bridge = objc_getAssociatedObject(self, &STPrivateStatic.bridgeKey) as? Bridge { + let userContentController = bridge.configuration.userContentController + userContentController.removeScriptMessageHandler(forName: Bridge.name) + } + objc_setAssociatedObject(self, &STPrivateStatic.bridgeKey, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } +} + +fileprivate extension WKWebView { + + func st_dispatchBridgeEvent(_ eventName: String, + parameters: [String: Any], + results: Bridge.Results, + completionHandler: ((Any?, Error?) -> Void)? = nil) { + + var eventDetail: [String: Any] = parameters + switch results { + case .failure(let error): + eventDetail["error"] = ["code": error.code, "description": error.description] + case .success(let callbackParameters): + eventDetail["parameters"] = callbackParameters ?? [:] + } + let eventBody: [String: Any] = ["detail": eventDetail] + let jsString: String + if + let _data = try? JSONSerialization.data(withJSONObject: eventBody, options: JSONSerialization.WritingOptions()), + let eventString = String(data: _data, encoding: .utf8) { + + jsString = "(function() { var event = new CustomEvent('\(eventName)', \(eventString)); document.dispatchEvent(event)}());" + } else { + // When JSON Not Serializable, Invoke with Default Parameters + switch results { + case .success(_): + jsString = "(function() { var event = new CustomEvent('\(eventName)', {'detail': {'parameters': {}}}); document.dispatchEvent(event)}());" + case .failure(let error): + jsString = "(function() { var event = new CustomEvent('\(eventName)', {'detail': {'error': {'code': \(error.code), 'description': '\(error.description)'}}}); document.dispatchEvent(event)}());" + } + } + evaluateJavaScript(jsString, completionHandler: completionHandler) + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Browser/BrowserViewController.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Browser/BrowserViewController.swift new file mode 100644 index 000000000..90ea08d13 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Browser/BrowserViewController.swift @@ -0,0 +1,128 @@ +// +// BrowserViewController.swift +// web3swift +// +// Created by Anton Grigorev on 16.03.2020. +// Copyright © 2020 Matter Labs. All rights reserved. +// + +import WebKit + +open class BrowserViewController: UIViewController { + + public enum Method: String { + case getAccounts + case signTransaction + case signMessage + case signPersonalMessage + case publishTransaction + case approveTransaction + } + + public lazy var webView: WKWebView = { + let websiteDataTypes = NSSet(array: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache]) + let date = NSDate(timeIntervalSince1970: 0) + + WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes as! Set, modifiedSince: date as Date, completionHandler:{ }) + let webView = WKWebView( + frame: .zero, + configuration: self.config + ) + webView.allowsBackForwardNavigationGestures = true + webView.scrollView.isScrollEnabled = true + webView.navigationDelegate = self + webView.configuration.preferences.setValue(true, forKey: "developerExtrasEnabled") + return webView + }() + + lazy var config: WKWebViewConfiguration = { + let config = WKWebViewConfiguration() + + var js = "" + + if let filepath = Bundle.main.path(forResource: "browser.min", ofType: "js") { + do { + js += try String(contentsOfFile: filepath) + NSLog("Loaded browser.js") + } catch { + NSLog("Failed to load web.js") + } + } else { + NSLog("web3.js not found in bundle") + } + let userScript = WKUserScript(source: js, injectionTime: .atDocumentStart, forMainFrameOnly: false) + config.userContentController.addUserScript(userScript) + return config + }() + + public func registerBridges(for web3: web3) { + self.webView.bridge.register({ (parameters, completion) in + let url = web3.provider.url.absoluteString + completion(.success(["rpcURL": url as Any])) + }, for: "getRPCurl") + + self.webView.bridge.register({ (parameters, completion) in + let allAccounts = web3.browserFunctions.getAccounts() + completion(.success(["accounts": allAccounts as Any])) + }, for: "eth_getAccounts") + + self.webView.bridge.register({ (parameters, completion) in + let coinbase = web3.browserFunctions.getCoinbase() + completion(.success(["coinbase": coinbase as Any])) + }, for: "eth_coinbase") + + self.webView.bridge.register({ (parameters, completion) in + if parameters == nil { + completion(.failure(Bridge.JSError(code: 0, description: "No parameters provided"))) + return + } + let payload = parameters!["payload"] as? [String:Any] + if payload == nil { + completion(.failure(Bridge.JSError(code: 0, description: "No parameters provided"))) + return + } + let personalMessage = payload!["data"] as? String + let account = payload!["from"] as? String + if personalMessage == nil || account == nil { + completion(.failure(Bridge.JSError(code: 0, description: "Not enough parameters provided"))) + return + } + let result = web3.browserFunctions.personalSign(personalMessage!, account: account!) + if result == nil { + completion(.failure(Bridge.JSError(code: 0, description: "Account or data is invalid"))) + return + } + completion(.success(["signedMessage": result as Any])) + }, for: "eth_sign") + + self.webView.bridge.register({ (parameters, completion) in + if parameters == nil { + completion(.failure(Bridge.JSError(code: 0, description: "No parameters provided"))) + return + } + let transaction = parameters!["transaction"] as? [String:Any] + if transaction == nil { + completion(.failure(Bridge.JSError(code: 0, description: "Not enough parameters provided"))) + return + } + let result = web3.browserFunctions.signTransaction(transaction!) + if result == nil { + completion(.failure(Bridge.JSError(code: 0, description: "Data is invalid"))) + return + } + completion(.success(["signedTransaction": result as Any])) + }, for: "eth_signTransaction") + } +} + +extension BrowserViewController: WKNavigationDelegate { + public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { + + } +} + +extension BrowserViewController: WKScriptMessageHandler { + public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { + NSLog("message \(message.body)") + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Browser/browser.js b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Browser/browser.js new file mode 100644 index 000000000..6f7d8ea26 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Browser/browser.js @@ -0,0 +1,68351 @@ +// Web3Swift.js +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// +(function(){function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0) { + window.web3.eth.defaultAccount = accs[0]; + } + })); + } + window.ethereum = engine; + } + }); + }()); + + //# 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")`, + * typically on application load. + * + * If called with no arguments, will return registration in + * following priority: + * + * For Node.js: + * + * 1. Previous registration + * 2. global.Promise if node.js version >= 0.12 + * 3. Auto detected promise based on first sucessful require of + * known promise libraries. Note this is a last resort, as the + * loaded library is non-deterministic. node.js >= 0.12 will + * always use global.Promise over this priority list. + * 4. Throws error. + * + * For Browser: + * + * 1. Previous registration + * 2. window.Promise + * 3. Throws error. + * + * Options: + * + * Promise: Desired Promise constructor + * global: Boolean - Should the registration be cached in a global variable to + * allow cross dependency/bundle registration? (default true) + */ + module.exports = function(root, loadImplementation){ + return function register(implementation, opts){ + implementation = implementation || null + opts = opts || {} + // global registration unless explicitly {global: false} in options (default true) + var registerGlobal = opts.global !== false; + + // load any previous global registration + if(registered === null && registerGlobal){ + registered = root[REGISTRATION_KEY] || null + } + + if(registered !== null + && implementation !== null + && registered.implementation !== implementation){ + // Throw error if attempting to redefine implementation + throw new Error('any-promise already defined as "'+registered.implementation+ + '". You can only register an implementation before the first '+ + ' call to require("any-promise") and an implementation cannot be changed') + } + + if(registered === null){ + // use provided implementation + if(implementation !== null && typeof opts.Promise !== 'undefined'){ + registered = { + Promise: opts.Promise, + implementation: implementation + } + } else { + // require implementation if implementation is specified but not provided + registered = loadImplementation(implementation) + } + + if(registerGlobal){ + // register preference globally in case multiple installations + root[REGISTRATION_KEY] = registered + } + } + + return registered + } + } + + },{}],4:[function(require,module,exports){ + "use strict"; + module.exports = require('./loader')(window, loadImplementation) + + /** + * Browser specific loadImplementation. Always uses `window.Promise` + * + * To register a custom implementation, must register with `Promise` option. + */ + function loadImplementation(){ + if(typeof window.Promise === 'undefined'){ + throw new Error("any-promise browser requires a polyfill or explicit registration"+ + " e.g: require('any-promise/register/bluebird')") + } + return { + Promise: window.Promise, + implementation: 'window.Promise' + } + } + + },{"./loader":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 { + named = require('vm').runInThisContext( + '(function ' + this.name + '(entity) {\n' + + ' this._initNamed(entity);\n' + + '})' + ); + } catch (e) { + named = function (entity) { + this._initNamed(entity); + }; + } + inherits(named, base); + 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 + if (!this.decoders.hasOwnProperty(enc)) + 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 + if (!this.encoders.hasOwnProperty(enc)) + 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; + this.value = value.map(function(item) { + if (!(item instanceof EncoderBuffer)) + item = new EncoderBuffer(item, reporter); + this.length += item.length; + return item; + }, this); + } else if (typeof value === 'number') { + if (!(0 <= value && value <= 0xff)) + return reporter.error('non-byte EncoderBuffer value'); + this.value = value; + this.length = 1; + } else if (typeof value === 'string') { + this.value = value; + this.length = Buffer.byteLength(value); + } else if (Buffer.isBuffer(value)) { + this.value = value; + this.length = value.length; + } else { + return reporter.error('Unsupported type: ' + typeof value); + } + } + 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); + offset += item.length; + }); + } else { + if (typeof this.value === 'number') + out[offset] = this.value; + else if (typeof this.value === 'string') + out.write(this.value, offset); + else if (Buffer.isBuffer(this.value)) + 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', + 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', + '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; + state.reverseArgs = null; + state.choice = null; + state.optional = false; + state.any = false; + state.obj = false; + state.use = null; + state.useDecoder = null; + state.key = null; + state['default'] = null; + state.explicit = null; + state.implicit = null; + state.contains = null; + + // Should create new instance on each method + if (!state.parent) { + state.children = []; + this._wrap(); + } + } + 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 = {}; + stateProps.forEach(function(prop) { + cstate[prop] = state[prop]; + }); + var res = new this.constructor(cstate.parent); + res._baseState = cstate; + return res; + }; + + Node.prototype._wrap = function wrap() { + var state = this._baseState; + methods.forEach(function(method) { + this[method] = function _wrappedMethod() { + var clone = new this.constructor(this); + state.children.push(clone); + return clone[method].apply(clone, arguments); + }; + }, 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; + }, this); + 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; + }, this); + } + if (args.length !== 0) { + assert(state.args === null); + state.args = args; + 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)) + key |= 0; + var value = arg[key]; + res[value] = key; + }); + return res; + }); + } + }; + + // + // 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; + if (state.explicit !== null) + tag = state.explicit; + else if (state.implicit !== null) + tag = state.implicit; + else if (state.tag !== null) + tag = state.tag; + + if (tag === null && !state.any) { + // Trial and Error + var save = input.save(); + try { + if (state.choice === null) + this._decodeGeneric(state.tag, input, options); + else + this._decodeChoice(input, options); + present = true; + } catch (e) { + present = false; + } + 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) { + var explicit = this._decodeTag(input, state.explicit); + if (input.isError(explicit)) + return explicit; + input = explicit; + } + + var start = input.offset; + + // Unwrap implicit and normal values + if (state.use === null && state.choice === null) { + if (state.any) + var save = input.save(); + var body = this._decodeTag( + input, + state.implicit !== null ? state.implicit : state.tag, + state.any + ); + 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; + else if (state.choice === null) + 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) { + // NOTE: We are ignoring errors here, to let parser continue with other + // parts of encoded data + 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); + result = this._getUse(state.contains, input._reporterState.obj) + ._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') + return this._decodeList(input, tag, state.args[0], options); + else if (/str$/.test(tag)) + return this._decodeStr(input, tag, options); + else if (tag === 'objid' && state.args) + return this._decodeObjid(input, state.args[0], state.args[1], options); + else if (tag === 'objid') + return this._decodeObjid(input, null, null, options); + else if (tag === 'gentime' || tag === 'utctime') + return this._decodeTime(input, tag, options); + else if (tag === 'null_') + return this._decodeNull(input, options); + else if (tag === 'bool') + return this._decodeBool(input, options); + else if (tag === 'objDesc') + 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); + } else { + 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); + assert(state.useDecoder._baseState.parent === null); + state.useDecoder = state.useDecoder._baseState.children[0]; + if (state.implicit !== state.useDecoder._baseState.implicit) { + state.useDecoder = state.useDecoder.clone(); + state.useDecoder._baseState.implicit = state.implicit; + } + 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]; + try { + var value = node._decode(input, options); + if (input.isError(value)) + return false; + + result = { type: key, value: value }; + match = true; + } catch (e) { + input.restore(save); + return false; + } + 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) + data = state['default'] + else + return; + } + + // Encode children first + var content = null; + var primitive = false; + if (state.any) { + // Anything that was given is translated to buffer + result = this._createEncoderBuffer(data); + } else if (state.choice) { + result = this._encodeChoice(data, reporter); + } else if (state.contains) { + content = this._getUse(state.contains, parent)._encode(data, reporter); + primitive = true; + } else if (state.children) { + 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; + }); + content = this._createEncoderBuffer(content); + } else { + if (state.tag === 'seqof' || state.tag === 'setof') { + // 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) { + result = this._getUse(state.use, parent)._encode(data, reporter); + } else { + content = this._encodePrimitive(state.tag, data); + 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()'); + } else { + if (state.use === null) + 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( + false, + data.type + ' not found in ' + + JSON.stringify(Object.keys(state.choice))); + } + 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) + return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); + else if (tag === 'objid') + return this._encodeObjid(data, null, null); + else if (tag === 'gentime' || tag === 'utctime') + return this._encodeTime(data, tag); + else if (tag === 'null_') + return this._encodeNull(); + else if (tag === 'int' || tag === 'enum') + return this._encodeInt(data, state.args && state.reverseArgs[0]); + else if (tag === 'bool') + return this._encodeBool(data); + else if (tag === 'objDesc') + return this._encodeStr(data, tag); + 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, + path: [], + options: options || {}, + errors: [] + }; + } + 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; + } else { + err = new ReporterError(state.path.map(function(elem) { + 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 + throw new Error(this.message); + } catch (e) { + this.stack = e.stack; + } + } + return this; + }; + + },{"inherits":180}],11:[function(require,module,exports){ + var constants = require('../constants'); + + exports.tagClass = { + 0: 'universal', + 1: 'application', + 2: 'context', + 3: 'private' + }; + exports.tagClassByName = constants._reverse(exports.tagClass); + + exports.tag = { + 0x00: 'end', + 0x01: 'bool', + 0x02: 'int', + 0x03: 'bitstr', + 0x04: 'octstr', + 0x05: 'null_', + 0x06: 'objid', + 0x07: 'objDesc', + 0x08: 'external', + 0x09: 'real', + 0x0a: 'enum', + 0x0b: 'embed', + 0x0c: 'utf8str', + 0x0d: 'relativeOid', + 0x10: 'seq', + 0x11: 'set', + 0x12: 'numstr', + 0x13: 'printstr', + 0x14: 't61str', + 0x15: 'videostr', + 0x16: 'ia5str', + 0x17: 'utctime', + 0x18: 'gentime', + 0x19: 'graphstr', + 0x1a: 'iso646str', + 0x1b: 'genstr', + 0x1c: 'unistr', + 0x1d: 'charstr', + 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( + buffer, + '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); + if (buffer.isError(tag)) + return tag; + 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 = []; + while (!buffer.isEmpty()) { + 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; + result.push(res); + } + return result; + }; + + DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { + if (tag === 'bitstr') { + var unused = buffer.readUInt8(); + if (buffer.isError(unused)) + return unused; + return { unused: unused, data: buffer.raw() }; + } else if (tag === 'bmpstr') { + 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)); + } + return str; + } else if (tag === 'numstr') { + var numstr = buffer.raw().toString('ascii'); + if (!this._isNumstr(numstr)) { + return buffer.error('Decoding of string type: ' + + 'numstr unsupported characters'); + } + return numstr; + } else if (tag === 'octstr') { + return buffer.raw(); + } else if (tag === 'objDesc') { + return buffer.raw(); + } else if (tag === 'printstr') { + var printstr = buffer.raw().toString('ascii'); + if (!this._isPrintstr(printstr)) { + return buffer.error('Decoding of string type: ' + + 'printstr unsupported characters'); + } + return printstr; + } else if (/str$/.test(tag)) { + return buffer.raw().toString(); + } else { + return buffer.error('Decoding of string type: ' + tag + ' unsupported'); + } + }; + + DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { + var result; + var identifiers = []; + var ident = 0; + while (!buffer.isEmpty()) { + var subident = buffer.readUInt8(); + ident <<= 7; + ident |= subident & 0x7f; + if ((subident & 0x80) === 0) { + identifiers.push(ident); + ident = 0; + } + } + 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) + tmp = values[result.join('.')]; + if (tmp !== undefined) + result = tmp; + } + + return result; + }; + + DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { + var str = buffer.raw().toString(); + if (tag === 'gentime') { + var year = str.slice(0, 4) | 0; + var mon = str.slice(4, 6) | 0; + var day = str.slice(6, 8) | 0; + var hour = str.slice(8, 10) | 0; + var min = str.slice(10, 12) | 0; + var sec = str.slice(12, 14) | 0; + } else if (tag === 'utctime') { + var year = str.slice(0, 2) | 0; + var mon = str.slice(2, 4) | 0; + var day = str.slice(4, 6) | 0; + var hour = str.slice(6, 8) | 0; + var min = str.slice(8, 10) | 0; + var sec = str.slice(10, 12) | 0; + if (year < 70) + year = 2000 + year; + else + year = 1900 + year; + } 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)) + return res; + 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; + tag = 0; + while ((oct & 0x80) === 0x80) { + oct = buf.readUInt8(fail); + if (buf.isError(oct)) + return oct; + + tag <<= 7; + tag |= oct & 0x7f; + } + } else { + tag &= 0x1f; + } + var tagStr = der.tag[tag]; + + return { + cls: cls, + primitive: primitive, + tag: tag, + 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; + var j = buf.readUInt8(fail); + if (buf.isError(j)) + 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; + for (var i = 0; i < lines.length; i++) { + var match = lines[i].match(re); + if (match === null) + continue; + + if (match[2] !== label) + continue; + + if (start === -1) { + if (match[1] !== 'BEGIN') + break; + start = i; + } else { + if (match[1] !== 'END') + break; + end = i; + break; + } + } + 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); + header[0] = encodedTag; + 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 ]); + } else if (tag === 'bmpstr') { + var buf = new Buffer(str.length * 2); + for (var i = 0; i < str.length; i++) { + buf.writeUInt16BE(str.charCodeAt(i), i * 2); + } + return this._createEncoderBuffer(buf); + } else if (tag === 'numstr') { + if (!this._isNumstr(str)) { + return this.reporter.error('Encoding of string type: numstr supports ' + + 'only digits and space'); + } + return this._createEncoderBuffer(str); + } else if (tag === 'printstr') { + if (!this._isPrintstr(str)) { + return this.reporter.error('Encoding of string type: printstr supports ' + + 'only latin upper and lower case letters, ' + + 'digits, space, apostrophe, left and rigth ' + + 'parenthesis, plus sign, comma, hyphen, ' + + 'dot, slash, colon, equal sign, ' + + 'question mark'); + } + return this._createEncoderBuffer(str); + } else if (/str$/.test(tag)) { + return this._createEncoderBuffer(str); + } else if (tag === 'objDesc') { + return this._createEncoderBuffer(str); + } else { + return this.reporter.error('Encoding of string type: ' + tag + + ' unsupported'); + } + }; + + DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { + if (typeof id === 'string') { + if (!values) + return this.reporter.error('string objid given, but no values map found'); + if (!values.hasOwnProperty(id)) + return this.reporter.error('objid not found in values map'); + id = values[id].split(/[\s\.]+/g); + for (var i = 0; i < id.length; i++) + id[i] |= 0; + } else if (Array.isArray(id)) { + id = id.slice(); + 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++) { + var ident = id[i]; + 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--) { + var ident = id[i]; + objid[offset--] = ident & 0x7f; + 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()), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else if (tag === 'utctime') { + str = [ + two(date.getFullYear() % 100), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } 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) + return this.reporter.error('String int or enum given, but no values map'); + if (!values.hasOwnProperty(num)) { + return this.reporter.error('Values map doesn\'t contain: ' + + JSON.stringify(num)); + } + num = values[num]; + } + + // Bignum, assume big endian + if (typeof num !== 'number' && !Buffer.isBuffer(num)) { + var numArray = num.toArray(); + if (!num.sign && numArray[0] & 0x80) { + numArray.unshift(0); + } + 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; + num >>= 8; + } + 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) + out.push(p.slice(i, i + 64)); + 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. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + function compare(a, b) { + if (a === b) { + return 0; + } + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + + if (x < y) { + return -1; + } + if (y < x) { + return 1; + } + return 0; + } + function isBuffer(b) { + if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { + return global.Buffer.isBuffer(b); + } + return !!(b != null && b._isBuffer); + } + + // based on node assert, original notice: + + // http://wiki.commonjs.org/wiki/Unit_Testing/1.0 + // + // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! + // + // Originally from narwhal.js (http://narwhaljs.org) + // Copyright (c) 2009 Thomas Robinson <280north.com> + // + // Permission is hereby granted, free of charge, to any person obtaining a copy + // of this software and associated documentation files (the 'Software'), to + // deal in the Software without restriction, including without limitation the + // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + // sell copies of the Software, and to permit persons to whom the Software is + // furnished to do so, subject to the following conditions: + // + // The above copyright notice and this permission notice shall be included in + // all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + var util = require('util/'); + var hasOwn = Object.prototype.hasOwnProperty; + var pSlice = Array.prototype.slice; + var functionsHaveNames = (function () { + return function foo() {}.name === 'foo'; + }()); + function pToString (obj) { + return Object.prototype.toString.call(obj); + } + function isView(arrbuf) { + if (isBuffer(arrbuf)) { + return false; + } + if (typeof global.ArrayBuffer !== 'function') { + return false; + } + if (typeof ArrayBuffer.isView === 'function') { + return ArrayBuffer.isView(arrbuf); + } + if (!arrbuf) { + return false; + } + if (arrbuf instanceof DataView) { + return true; + } + if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { + return true; + } + return false; + } + // 1. The assert module provides functions that throw + // AssertionError's when particular conditions are not met. The + // assert module must conform to the following interface. + + var assert = module.exports = ok; + + // 2. The AssertionError is defined in assert. + // new assert.AssertionError({ message: message, + // actual: actual, + // expected: expected }) + + var regex = /\s*function\s+([^\(\s]*)\s*/; + // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js + function getName(func) { + if (!util.isFunction(func)) { + return; + } + if (functionsHaveNames) { + return func.name; + } + var str = func.toString(); + var match = str.match(regex); + return match && match[1]; + } + assert.AssertionError = function AssertionError(options) { + this.name = 'AssertionError'; + this.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator; + if (options.message) { + this.message = options.message; + this.generatedMessage = false; + } else { + this.message = getMessage(this); + this.generatedMessage = true; + } + var stackStartFunction = options.stackStartFunction || fail; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, stackStartFunction); + } else { + // non v8 browsers so we can have a stacktrace + var err = new Error(); + if (err.stack) { + var out = err.stack; + + // try to strip useless frames + var fn_name = getName(stackStartFunction); + var idx = out.indexOf('\n' + fn_name); + if (idx >= 0) { + // once we have located the function frame + // we need to strip out everything before it (and its line) + var next_line = out.indexOf('\n', idx + 1); + out = out.substring(next_line + 1); + } + + this.stack = out; + } + } + }; + + // assert.AssertionError instanceof Error + util.inherits(assert.AssertionError, Error); + + function truncate(s, n) { + if (typeof s === 'string') { + return s.length < n ? s : s.slice(0, n); + } else { + return s; + } + } + function inspect(something) { + if (functionsHaveNames || !util.isFunction(something)) { + return util.inspect(something); + } + var rawname = getName(something); + var name = rawname ? ': ' + rawname : ''; + return '[Function' + name + ']'; + } + function getMessage(self) { + return truncate(inspect(self.actual), 128) + ' ' + + self.operator + ' ' + + truncate(inspect(self.expected), 128); + } + + // At present only the three keys mentioned above are used and + // understood by the spec. Implementations or sub modules can pass + // other keys to the AssertionError's constructor - they will be + // ignored. + + // 3. All of the following functions must throw an AssertionError + // when a corresponding condition is not met, with a message that + // may be undefined if not provided. All assertion methods provide + // both the actual and expected values to the assertion error for + // display purposes. + + function fail(actual, expected, message, operator, stackStartFunction) { + throw new assert.AssertionError({ + message: message, + actual: actual, + expected: expected, + operator: operator, + stackStartFunction: stackStartFunction + }); + } + + // EXTENSION! allows for well behaved errors defined elsewhere. + assert.fail = fail; + + // 4. Pure assertion tests whether a value is truthy, as determined + // by !!guard. + // assert.ok(guard, message_opt); + // This statement is equivalent to assert.equal(true, !!guard, + // message_opt);. To test strictly for the value true, use + // assert.strictEqual(true, guard, message_opt);. + + function ok(value, message) { + if (!value) fail(value, true, message, '==', assert.ok); + } + assert.ok = ok; + + // 5. The equality assertion tests shallow, coercive equality with + // ==. + // assert.equal(actual, expected, message_opt); + + assert.equal = function equal(actual, expected, message) { + if (actual != expected) fail(actual, expected, message, '==', assert.equal); + }; + + // 6. The non-equality assertion tests for whether two objects are not equal + // with != assert.notEqual(actual, expected, message_opt); + + assert.notEqual = function notEqual(actual, expected, message) { + if (actual == expected) { + fail(actual, expected, message, '!=', assert.notEqual); + } + }; + + // 7. The equivalence assertion tests a deep equality relation. + // assert.deepEqual(actual, expected, message_opt); + + assert.deepEqual = function deepEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'deepEqual', assert.deepEqual); + } + }; + + assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); + } + }; + + function _deepEqual(actual, expected, strict, memos) { + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; + } else if (isBuffer(actual) && isBuffer(expected)) { + return compare(actual, expected) === 0; + + // 7.2. If the expected value is a Date object, the actual value is + // equivalent if it is also a Date object that refers to the same time. + } else if (util.isDate(actual) && util.isDate(expected)) { + return actual.getTime() === expected.getTime(); + + // 7.3 If the expected value is a RegExp object, the actual value is + // equivalent if it is also a RegExp object with the same source and + // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). + } else if (util.isRegExp(actual) && util.isRegExp(expected)) { + return actual.source === expected.source && + actual.global === expected.global && + actual.multiline === expected.multiline && + actual.lastIndex === expected.lastIndex && + actual.ignoreCase === expected.ignoreCase; + + // 7.4. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if ((actual === null || typeof actual !== 'object') && + (expected === null || typeof expected !== 'object')) { + return strict ? actual === expected : actual == expected; + + // If both values are instances of typed arrays, wrap their underlying + // ArrayBuffers in a Buffer each to increase performance + // This optimization requires the arrays to have the same type as checked by + // Object.prototype.toString (aka pToString). Never perform binary + // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their + // bit patterns are not identical. + } else if (isView(actual) && isView(expected) && + pToString(actual) === pToString(expected) && + !(actual instanceof Float32Array || + actual instanceof Float64Array)) { + return compare(new Uint8Array(actual.buffer), + new Uint8Array(expected.buffer)) === 0; + + // 7.5 For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else if (isBuffer(actual) !== isBuffer(expected)) { + return false; + } else { + memos = memos || {actual: [], expected: []}; + + var actualIndex = memos.actual.indexOf(actual); + if (actualIndex !== -1) { + if (actualIndex === memos.expected.indexOf(expected)) { + return true; + } + } + + memos.actual.push(actual); + memos.expected.push(expected); + + return objEquiv(actual, expected, strict, memos); + } + } + + function isArguments(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; + } + + function objEquiv(a, b, strict, actualVisitedObjects) { + if (a === null || a === undefined || b === null || b === undefined) + return false; + // if one is a primitive, the other must be same + if (util.isPrimitive(a) || util.isPrimitive(b)) + return a === b; + if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) + return false; + var aIsArgs = isArguments(a); + var bIsArgs = isArguments(b); + if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) + return false; + if (aIsArgs) { + a = pSlice.call(a); + b = pSlice.call(b); + return _deepEqual(a, b, strict); + } + var ka = objectKeys(a); + var kb = objectKeys(b); + var key, i; + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length !== kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] !== kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) + return false; + } + return true; + } + + // 8. The non-equivalence assertion tests for any deep inequality. + // assert.notDeepEqual(actual, expected, message_opt); + + assert.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); + } + }; + + assert.notDeepStrictEqual = notDeepStrictEqual; + function notDeepStrictEqual(actual, expected, message) { + if (_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); + } + } + + + // 9. The strict equality assertion tests strict equality, as determined by ===. + // assert.strictEqual(actual, expected, message_opt); + + assert.strictEqual = function strictEqual(actual, expected, message) { + if (actual !== expected) { + fail(actual, expected, message, '===', assert.strictEqual); + } + }; + + // 10. The strict non-equality assertion tests for strict inequality, as + // determined by !==. assert.notStrictEqual(actual, expected, message_opt); + + assert.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (actual === expected) { + fail(actual, expected, message, '!==', assert.notStrictEqual); + } + }; + + function expectedException(actual, expected) { + if (!actual || !expected) { + return false; + } + + if (Object.prototype.toString.call(expected) == '[object RegExp]') { + return expected.test(actual); + } + + try { + if (actual instanceof expected) { + return true; + } + } catch (e) { + // Ignore. The instanceof check doesn't work for arrow functions. + } + + if (Error.isPrototypeOf(expected)) { + return false; + } + + return expected.call({}, actual) === true; + } + + function _tryBlock(block) { + var error; + try { + block(); + } catch (e) { + error = e; + } + return error; + } + + function _throws(shouldThrow, block, expected, message) { + var actual; + + if (typeof block !== 'function') { + throw new TypeError('"block" argument must be a function'); + } + + if (typeof expected === 'string') { + message = expected; + expected = null; + } + + actual = _tryBlock(block); + + message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + + (message ? ' ' + message : '.'); + + if (shouldThrow && !actual) { + fail(actual, expected, 'Missing expected exception' + message); + } + + var userProvidedMessage = typeof message === 'string'; + var isUnwantedException = !shouldThrow && util.isError(actual); + var isUnexpectedException = !shouldThrow && actual && !expected; + + if ((isUnwantedException && + userProvidedMessage && + expectedException(actual, expected)) || + isUnexpectedException) { + fail(actual, expected, 'Got unwanted exception' + message); + } + + if ((shouldThrow && actual && expected && + !expectedException(actual, expected)) || (!shouldThrow && actual)) { + throw actual; + } + } + + // 11. Expected to throw an error: + // assert.throws(block, Error_opt, message_opt); + + assert.throws = function(block, /*optional*/error, /*optional*/message) { + _throws(true, block, error, message); + }; + + // EXTENSION! This is annoying to write outside this module. + assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { + _throws(false, block, error, message); + }; + + assert.ifError = function(err) { if (err) throw err; }; + + var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + if (hasOwn.call(obj, key)) keys.push(key); + } + return keys; + }; + + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + },{"util/":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, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ + function asyncify(func) { + return (0, _initialParams2.default)(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if ((0, _isObject2.default)(result) && typeof result.then === 'function') { + result.then(function (value) { + invokeCallback(callback, null, value); + }, function (err) { + invokeCallback(callback, err.message ? err : new Error(err)); + }); + } else { + callback(null, result); + } + }); + } + + function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (e) { + (0, _setImmediate2.default)(rethrow, e); + } + } + + function rethrow(error) { + throw error; + } + module.exports = exports['default']; + },{"./internal/initialParams":31,"./internal/setImmediate":37,"lodash/isObject":225}],21:[function(require,module,exports){ + (function (process,global){ + (function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + 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); + var newArr = Array(newLen); + for(var idx = 0; idx < newLen; idx++) { + newArr[idx] = arrayLike[start + idx]; + } + return newArr; + } + + /** + * Creates a continuation function with some arguments already applied. + * + * Useful as a shorthand when combined with other control flow functions. Any + * arguments passed to the returned function are added to the arguments + * originally passed to apply. + * + * @name apply + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {Function} fn - The function you want to eventually apply all + * arguments to. Invokes with (arguments...). + * @param {...*} arguments... - Any number of arguments to automatically apply + * when the continuation is called. + * @returns {Function} the partially-applied function + * @example + * + * // using apply + * async.parallel([ + * async.apply(fs.writeFile, 'testfile1', 'test1'), + * async.apply(fs.writeFile, 'testfile2', 'test2') + * ]); + * + * + * // the same process without using apply + * async.parallel([ + * function(callback) { + * fs.writeFile('testfile1', 'test1', callback); + * }, + * function(callback) { + * fs.writeFile('testfile2', 'test2', callback); + * } + * ]); + * + * // It's possible to pass any number of additional arguments when calling the + * // continuation: + * + * node> var fn = async.apply(sys.puts, 'one'); + * node> fn('two', 'three'); + * one + * two + * three + */ + var apply = function(fn/*, ...args*/) { + var args = slice(arguments, 1); + return function(/*callArgs*/) { + var callArgs = slice(arguments); + return fn.apply(null, args.concat(callArgs)); + }; + }; + + var initialParams = function (fn) { + return function (/*...args, callback*/) { + var args = slice(arguments); + var callback = args.pop(); + 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) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + 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); + defer(function () { + fn.apply(null, args); + }); + }; + } + + var _defer; + + if (hasSetImmediate) { + _defer = setImmediate; + } else if (hasNextTick) { + _defer = process.nextTick; + } 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, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ + function asyncify(func) { + return initialParams(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (isObject(result) && typeof result.then === 'function') { + result.then(function(value) { + invokeCallback(callback, null, value); + }, function(err) { + invokeCallback(callback, err.message ? err : new Error(err)); + }); + } else { + callback(null, result); + } + }); + } + + function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (e) { + 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); + var go = initialParams(function(args, callback) { + var that = this; + return eachfn(fns, function (fn, cb) { + wrapAsync(fn).apply(that, args.concat(cb)); + }, callback); + }); + if (args.length) { + return go.apply(this, args); + } + else { + return go; + } + }; + } + + /** 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. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ + 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) { + value[symToStringTag$1] = tag; + } else { + delete value[symToStringTag$1]; + } + } + 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`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + 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. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? 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. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + 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. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + 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 + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + 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`. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Util + * @example + * + * _.times(2, _.noop); + * // => [undefined, undefined] + */ + function noop() { + // No operation performed. + } + + function once(fn) { + return function () { + if (fn === null) return; + var callFn = fn; + fn = null; + 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. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + 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". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return value != null && typeof value == 'object'; + } + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]'; + + /** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + 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. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); + }; + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray; + + /** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ + 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. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => 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. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER$1 : length; + return !!length && + (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]'; + var boolTag = '[object Boolean]'; + var dateTag = '[object Date]'; + var errorTag = '[object Error]'; + var funcTag$1 = '[object Function]'; + var mapTag = '[object Map]'; + var numberTag = '[object Number]'; + var objectTag = '[object Object]'; + var regexpTag = '[object RegExp]'; + var setTag = '[object Set]'; + var stringTag = '[object String]'; + var weakMapTag = '[object WeakMap]'; + + var arrayBufferTag = '[object ArrayBuffer]'; + var dataViewTag = '[object DataView]'; + var float32Tag = '[object Float32Array]'; + var float64Tag = '[object Float64Array]'; + var int8Tag = '[object Int8Array]'; + var int16Tag = '[object Int16Array]'; + var int32Tag = '[object Int32Array]'; + var uint8Tag = '[object Uint8Array]'; + 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] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = + typedArrayTags[mapTag] = typedArrayTags[numberTag] = + typedArrayTags[objectTag] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = false; + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + } + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + 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. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => 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`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + 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 && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; + } + + /** Used for built-in method references. */ + var objectProto$5 = Object.prototype; + + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + 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. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + 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. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty$3.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; + } + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } + + function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? {value: coll[i], key: i} : null; + } + } + + function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) + return null; + i++; + return {value: item.value, key: i}; + } + } + + function createObjectIterator(obj) { + var okeys = keys(obj); + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + 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."); + var callFn = fn; + fn = null; + callFn.apply(this, arguments); + }; + } + + function _eachOfLimit(limit) { + return function (obj, iteratee, callback) { + callback = once(callback || noop); + if (limit <= 0 || !obj) { + return callback(null); + } + var nextElem = iterator(obj); + var done = false; + var running = 0; + + function iterateeCallback(err, value) { + running -= 1; + if (err) { + done = true; + callback(err); + } + else if (value === breakLoop || (done && running <= 0)) { + done = true; + return callback(null); + } + else { + replenish(); + } + } + + function replenish () { + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + 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. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + */ + 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); + var index = 0, + completed = 0, + length = coll.length; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err) { + callback(err); + } else if ((++completed === length) || value === breakLoop) { + 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. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @example + * + * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; + * var configs = {}; + * + * async.forEachOf(obj, function (value, key, callback) { + * fs.readFile(__dirname + value, "utf8", function (err, data) { + * if (err) return callback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * }, function (err) { + * if (err) console.error(err.message); + * // configs is now a map of JSON data + * doSomethingWith(configs); + * }); + */ + var eachOf = function(coll, iteratee, callback) { + 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) { + results[index] = v; + callback(err); + }); + }, function (err) { + 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` + * and a callback for when it has finished processing. Each of these callback + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @example + * + * async.map(['file1','file2','file3'], fs.stat, function(err, results) { + * // results is now an array of stats for each file + * }); + */ + 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 + * argument, `fns`, then it will return a function which lets you pass in the + * arguments as if it were a single function call. If more arguments are + * provided, `callback` is required while `args` is still optional. + * + * @name applyEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s + * to all call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {Function} - If only the first argument, `fns`, is provided, it will + * return a function which lets you pass in the arguments as if it were a single + * function call. The signature is `(..args, callback)`. If invoked with any + * arguments, `callback` is required. + * @example + * + * async.applyEach([enableSearch, updateSchema], 'bucket', callback); + * + * // partial application example: + * async.each( + * buckets, + * async.applyEach([enableSearch, updateSchema]), + * callback + * ); + */ + 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. + * + * @name mapLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * 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. + * + * @name mapSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * 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. + * + * @name applyEachSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.applyEach]{@link module:ControlFlow.applyEach} + * @category Control Flow + * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s to all + * call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {Function} - If only the first argument is provided, it will return + * a function which lets you pass in the arguments as if it were a single + * function call. + */ + var applyEachSeries = applyEach$1(mapSeries); + + /** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEach(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; + } + + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + /** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + + /** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } + + /** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + 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; + } + } + return -1; + } + + /** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ + function baseIsNaN(value) { + return value !== value; + } + + /** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + return value === value + ? 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 + * being completed first, and each function is run as soon as its requirements + * are satisfied. + * + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence + * will stop. Further tasks will not execute (so any other functions depending + * on it will not run), and the main `callback` is immediately called with the + * error. + * + * {@link AsyncFunction}s also receive an object containing the results of functions which + * have completed so far as the first argument, if they have dependencies. If a + * task function has no dependencies, it will only be passed a callback. + * + * @name auto + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Object} tasks - An object. Each of its properties is either a + * function or an array of requirements, with the {@link AsyncFunction} itself the last item + * in the array. The object's key of a property serves as the name of the task + * defined by that property, i.e. can be used when specifying requirements for + * other tasks. The function receives one or two arguments: + * * a `results` object, containing the results of the previously executed + * functions, only passed if the task has any dependencies, + * * a `callback(err, result)` function, which must be called when finished, + * passing an `error` (which can be `null`) and the result of the function's + * execution. + * @param {number} [concurrency=Infinity] - An optional `integer` for + * determining the maximum number of tasks that can be run in parallel. By + * default, as many as possible. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback. Results are always returned; however, if an + * error occurs, no further `tasks` will be performed, and the results object + * will only contain partial results. Invoked with (err, results). + * @returns undefined + * @example + * + * async.auto({ + * // this function will just be passed a callback + * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'), + * showData: ['readData', function(results, cb) { + * // results.readData is the file's contents + * // ... + * }] + * }, callback); + * + * async.auto({ + * get_data: function(callback) { + * console.log('in get_data'); + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * console.log('in make_folder'); + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * console.log('in write_file', JSON.stringify(results)); + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * console.log('in email_link', JSON.stringify(results)); + * // once the file is written let's email a link to it... + * // results.write_file contains the filename returned by write_file. + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }, function(err, results) { + * console.log('err = ', err); + * console.log('results = ', results); + * }); + */ + var auto = function (tasks, concurrency, callback) { + if (typeof concurrency === 'function') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = once(callback || noop); + var keys$$1 = keys(tasks); + var numTasks = keys$$1.length; + if (!numTasks) { + return callback(null); + } + 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 + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } + + var dependencies = task.slice(0, task.length - 1); + var remainingDependencies = dependencies.length; + if (remainingDependencies === 0) { + enqueueTask(key, task); + readyToCheck.push(key); + return; + } + uncheckedDependencies[key] = remainingDependencies; + + arrayEach(dependencies, function (dependencyName) { + if (!tasks[dependencyName]) { + throw new Error('async.auto task `' + key + + '` has a non-existent dependency `' + + dependencyName + '` in ' + + dependencies.join(', ')); + } + addListener(dependencyName, function () { + remainingDependencies--; + if (remainingDependencies === 0) { + enqueueTask(key, task); + } + }); + }); + }); + + checkForDeadlocks(); + processQueue(); + + function enqueueTask(key, task) { + readyTasks.push(function () { + runTask(key, task); + }); + } + + function processQueue() { + if (readyTasks.length === 0 && runningTasks === 0) { + return callback(null, results); + } + while(readyTasks.length && runningTasks < concurrency) { + 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) { + fn(); + }); + processQueue(); + } + + + function runTask(key, task) { + if (hasError) return; + + var taskCallback = onlyOnce(function(err, result) { + runningTasks--; + if (arguments.length > 2) { + result = slice(arguments, 1); + } + if (err) { + var safeResults = {}; + baseForOwn(results, function(val, rkey) { + safeResults[rkey] = val; + }); + 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) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } + } + + function checkForDeadlocks() { + // Kahn's algorithm + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html + var currentTask; + var counter = 0; + while (readyToCheck.length) { + currentTask = readyToCheck.pop(); + counter++; + arrayEach(getDependents(currentTask), function (dependent) { + if (--uncheckedDependencies[dependent] === 0) { + readyToCheck.push(dependent); + } + }); + } + + 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) { + if (isArray(task) && baseIndexOf(task, taskName, 0) >= 0) { + result.push(key); + } + }); + return result; + } + }; + + /** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function arrayMap(array, iteratee) { + 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. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ + function isSymbol(value) { + 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. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ + function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap(value, baseToString) + ''; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + 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. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ + function castSlice(array, start, end) { + var length = array.length; + 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. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the last unmatched string symbol. + */ + 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. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the first unmatched string symbol. + */ + 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. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function asciiToArray(string) { + return string.split(''); + } + + /** Used to compose unicode character classes. */ + var rsAstralRange = '\\ud800-\\udfff'; + var rsComboMarksRange = '\\u0300-\\u036f'; + var reComboHalfMarksRange = '\\ufe20-\\ufe2f'; + 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. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ + function hasUnicode(string) { + return reHasUnicode.test(string); + } + + /** Used to compose unicode character classes. */ + var rsAstralRange$1 = '\\ud800-\\udfff'; + var rsComboMarksRange$1 = '\\u0300-\\u036f'; + var reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f'; + 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 + ']'; + var rsFitz = '\\ud83c[\\udffb-\\udfff]'; + var rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')'; + var rsNonAstral = '[^' + rsAstralRange$1 + ']'; + 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. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function unicodeToArray(string) { + return string.match(reUnicode) || []; + } + + /** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function stringToArray(string) { + return hasUnicode(string) + ? 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. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + 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`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to trim. + * @param {string} [chars=whitespace] The characters to trim. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the trimmed string. + * @example + * + * _.trim(' abc '); + * // => 'abc' + * + * _.trim('-_-abc-_-', '_-'); + * // => 'abc' + * + * _.map([' foo ', ' bar '], _.trim); + * // => ['foo', 'bar'] + */ + function trim(string, chars, guard) { + string = toString(string); + if (string && (guard || chars === undefined)) { + return string.replace(reTrim, ''); + } + if (!string || !(chars = baseToString(chars))) { + return string; + } + var strSymbols = stringToArray(string), + 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(' ', ''); + func = func ? func.split(FN_ARG_SPLIT) : []; + func = func.map(function (arg){ + return trim(arg.replace(FN_ARG, '')); + }); + 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 + * parameter, with the parameter names matching the names of the tasks it + * depends on. This can provide even more readable task graphs which can be + * easier to maintain. + * + * If a final callback is specified, the task results are similarly injected, + * specified as named parameters after the initial error parameter. + * + * The autoInject function is purely syntactic sugar and its semantics are + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. + * + * @name autoInject + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.auto]{@link module:ControlFlow.auto} + * @category Control Flow + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of + * the form 'func([dependencies...], callback). The object's key of a property + * serves as the name of the task defined by that property, i.e. can be used + * when specifying requirements for other tasks. + * * The `callback` parameter is a `callback(err, result)` which must be called + * when finished, passing an `error` (which can be `null`) and the result of + * the function's execution. The remaining parameters name other tasks on + * which the task is dependent, and the results from those tasks are the + * arguments of those parameters. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback, and a `results` object with any completed + * task results, similar to `auto`. + * @example + * + * // The example from `auto` can be rewritten as follows: + * async.autoInject({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: function(get_data, make_folder, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }, + * email_link: function(write_file, callback) { + * // once the file is written let's email a link to it... + * // write_file contains the filename returned by write_file. + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * } + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + * + * // If you are using a JS minifier that mangles parameter names, `autoInject` + * // will not work with plain functions, since the parameter names will be + * // collapsed to a single letter identifier. To work around this, you can + * // explicitly specify the names of the parameters your task function needs + * // in an array, similar to Angular.js dependency injection. + * + * // This still has an advantage over plain `auto`, since the results a task + * // depends on are still spread into arguments. + * async.autoInject({ + * //... + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(write_file, callback) { + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * }] + * //... + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + */ + 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 + newTasks[key] = taskFn; + } else { + params = parseParams(taskFn); + 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]; + }); + newArgs.push(taskCb); + 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 + // for queue support. + function DLL() { + 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; + if (node.next) node.next.prev = newNode; + else this.tail = newNode; + node.next = newNode; + this.length += 1; + }; + + DLL.prototype.insertBefore = function(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode; + else this.head = newNode; + 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; + for(var idx = 0; idx < this.length; idx++) { + arr[idx] = curr.data; + curr = curr.next; + } + return arr; + }; + + DLL.prototype.remove = function (testFn) { + var curr = this.head; + while(!!curr) { + var next = curr.next; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; + }; + + function queue(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } + 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') { + throw new Error('task callback must be a function'); + } + q.started = true; + if (!isArray(data)) { + data = [data]; + } + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + return setImmediate$1(function() { + 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() { + processingScheduled = false; + q.process(); + }); + } + } + + 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(), + concurrency: concurrency, + payload: payload, + saturated: noop, + unsaturated:noop, + buffer: concurrency / 4, + empty: noop, + drain: noop, + error: noop, + started: false, + paused: false, + push: function (data, callback) { + _insert(data, false, callback); + }, + kill: function () { + q.drain = noop; + q._tasks.empty(); + }, + unshift: function (data, callback) { + _insert(data, true, callback); + }, + remove: function (testFn) { + q._tasks.remove(testFn); + }, + process: function () { + // Avoid trying to start too many processing operations. This can occur + // when callbacks resolve synchronously (#1267). + if (isProcessing) { + return; + } + isProcessing = true; + while(!q.paused && numRunning < q.concurrency && q._tasks.length){ + var tasks = [], data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); + tasks.push(node); + 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); + } + isProcessing = false; + }, + length: function () { + return q._tasks.length; + }, + running: function () { + return numRunning; + }, + workersList: function () { + return workersList; + }, + idle: function() { + return q._tasks.length + numRunning === 0; + }, + pause: function () { + q.paused = true; + }, + resume: function () { + if (q.paused === false) { return; } + q.paused = false; + setImmediate$1(q.process); + } + }; + 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}. + * @typedef {Object} CargoObject + * @memberOf module:ControlFlow + * @property {Function} length - A function returning the number of items + * waiting to be processed. Invoke like `cargo.length()`. + * @property {number} payload - An `integer` for determining how many tasks + * should be process per round. This property can be changed after a `cargo` is + * created to alter the payload on-the-fly. + * @property {Function} push - Adds `task` to the `queue`. The callback is + * called once the `worker` has finished processing the task. Instead of a + * single task, an array of `tasks` can be submitted. The respective callback is + * used for every task in the list. Invoke like `cargo.push(task, [callback])`. + * @property {Function} saturated - A callback that is called when the + * `queue.length()` hits the concurrency and further tasks will be queued. + * @property {Function} empty - A callback that is called when the last item + * from the `queue` is given to a `worker`. + * @property {Function} drain - A callback that is called when the last item + * from the `queue` has returned from the `worker`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke like `cargo.idle()`. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke like `cargo.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke like `cargo.resume()`. + * @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 + * `worker` is in progress, the task is queued until it becomes available. Once + * the `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, cargo passes an array of tasks to a single worker, repeating + * when the worker is finished. + * + * @name cargo + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.CargoObject} A cargo object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargo and inner queue. + * @example + * + * // create a cargo object with payload 2 + * var cargo = async.cargo(function(tasks, callback) { + * for (var i=0; i true + */ + function identity(value) { + return value; + } + + function _createTester(check, getResult) { + return function(eachfn, arr, iteratee, cb) { + cb = cb || noop; + var testPassed = false; + var testResult; + eachfn(arr, function(value, _, callback) { + iteratee(value, function(err, result) { + if (err) { + callback(err); + } else if (check(result) && !testResult) { + testPassed = true; + testResult = getResult(true, value); + callback(null, breakLoop); + } else { + callback(); + } + }); + }, function(err) { + if (err) { + cb(err); + } else { + cb(null, testPassed ? testResult : getResult(false)); + } + }); + }; + } + + 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}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @example + * + * async.detect(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // result now equals the first file in the list that exists + * }); + */ + 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. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (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. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + */ + var detectSeries = doLimit(detectLimit, 1); + + function consoleFunc(name) { + return function (fn/*, ...args*/) { + var args = slice(arguments, 1); + args.push(function (err/*, ...args*/) { + var args = slice(arguments, 1); + if (typeof console === 'object') { + if (err) { + if (console.error) { + console.error(err); + } + } else if (console[name]) { + arrayEach(args, function (x) { + console[name](x); + }); + } + } + }); + 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. + * Only works in Node.js or in browsers that support `console.dir` and + * `console.error` (such as FF and Chrome). + * If multiple arguments are returned from the async function, + * `console.dir` is called on each argument in order. + * + * @name dir + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, {hello: name}); + * }, 1000); + * }; + * + * // in the node repl + * node> async.dir(hello, 'world'); + * {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. + * + * Also a version of [`doWhilst`]{@link module:ControlFlow.doWhilst} with asynchronous `test` function. + * @name doDuring + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.during]{@link module:ControlFlow.during} + * @category Control Flow + * @param {AsyncFunction} fn - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `fn`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `fn`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `fn` has stopped. `callback` + * will be passed an error if one occurred, otherwise `null`. + */ + function doDuring(fn, test, callback) { + 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. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {Function} test - synchronous truth test to perform after each + * execution of `iteratee`. Invoked with any non-error callback results of + * `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + */ + function doWhilst(iteratee, test, callback) { + callback = onlyOnce(callback || noop); + var _iteratee = wrapAsync(iteratee); + var next = function(err/*, ...args*/) { + if (err) return callback(err); + var args = slice(arguments, 1); + if (test.apply(this, args)) return _iteratee(next); + callback.apply(null, [null].concat(args)); + }; + _iteratee(next); + } + + /** + * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the + * argument ordering differs from `until`. + * + * @name doUntil + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} test - synchronous truth test to perform after each + * execution of `iteratee`. Invoked with any non-error callback results of + * `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + */ + function doUntil(iteratee, test, callback) { + doWhilst(iteratee, function() { + 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 + * passed to `test` or `fn`, the main callback is immediately called with the + * value of the error. + * + * @name during + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `fn`. Invoked with (callback). + * @param {AsyncFunction} fn - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `fn` has stopped. `callback` + * will be passed an error, if one occurred, otherwise `null`. + * @example + * + * var count = 0; + * + * async.during( + * function (callback) { + * return callback(null, count < 5); + * }, + * function (callback) { + * count++; + * setTimeout(callback, 1000); + * }, + * function (err) { + * // 5 seconds have passed + * } + * ); + */ + function during(test, fn, callback) { + 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 + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @example + * + * // assuming openFiles is an array of file names and saveFile is a function + * // to save the modified contents of that file: + * + * async.each(openFiles, saveFile, function(err){ + * // if any of the saves produced an error, err would equal that error + * }); + * + * // assuming openFiles is an array of file names + * async.each(openFiles, function(file, callback) { + * + * // Perform operation on file here. + * console.log('Processing file ' + file); + * + * if( file.length > 32 ) { + * console.log('This file name is too long'); + * callback('File name too long'); + * } else { + * // Do work to process file here + * console.log('File processed'); + * callback(); + * } + * }, function(err) { + * // if any of the file processing produced an error, err would equal that error + * if( err ) { + * // One of the iterations produced an error. + * // All processing will now stop. + * console.log('A file failed to process'); + * } else { + * console.log('All files have been processed successfully'); + * } + * }); + */ + 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. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + */ + 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. + * + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `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, + * no extra deferral is added. This is useful for preventing stack overflows + * (`RangeError: Maximum call stack size exceeded`) and generally keeping + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + * contained. ES2017 `async` functions are returned as-is -- they are immune + * to Zalgo's corrupting influences, as they always resolve on a later tick. + * + * @name ensureAsync + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - an async function, one that expects a node-style + * callback as its last argument. + * @returns {AsyncFunction} Returns a wrapped function with the exact same call + * signature as the function passed in. + * @example + * + * function sometimesAsync(arg, callback) { + * if (cache[arg]) { + * return callback(null, cache[arg]); // this would be synchronous!! + * } else { + * doSomeIO(arg, callback); // this IO would be asynchronous + * } + * } + * + * // this has a risk of stack overflows if many results are cached in a row + * async.mapSeries(args, sometimesAsync, done); + * + * // this will defer sometimesAsync's callback if necessary, + * // preventing stack overflows + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + */ + function ensureAsync(fn) { + if (isAsync(fn)) return fn; + return initialParams(function (args, callback) { + var sync = true; + args.push(function () { + var innerArgs = arguments; + if (sync) { + setImmediate$1(function () { + callback.apply(null, innerArgs); + }); + } else { + callback.apply(null, innerArgs); + } + }); + fn.apply(this, args); + 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. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @example + * + * async.every(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then every file exists + * }); + */ + 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. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * 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. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * 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. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + function filterArray(eachfn, arr, iteratee, callback) { + var truthValues = new Array(arr.length); + eachfn(arr, function (x, index, callback) { + iteratee(x, function (err, v) { + truthValues[index] = !!v; + callback(err); + }); + }, function (err) { + if (err) return callback(err); + var results = []; + for (var i = 0; i < arr.length; i++) { + if (truthValues[i]) results.push(arr[i]); + } + callback(null, results); + }); + } + + function filterGeneric(eachfn, coll, iteratee, callback) { + var results = []; + eachfn(coll, function (x, index, callback) { + iteratee(x, function (err, v) { + if (err) { + callback(err); + } else { + if (v) { + results.push({index: index, value: x}); + } + callback(); + } + }); + }, function (err) { + if (err) { + callback(err); + } else { + callback(null, arrayMap(results.sort(function (a, b) { + return a.index - b.index; + }), baseProperty('value'))); + } + }); + } + + 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 + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @example + * + * async.filter(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of the existing files + * }); + */ + var filter = doParallel(_filter); + + /** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `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. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `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. + * + * @name forever + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} fn - an async function to call repeatedly. + * Invoked with (next). + * @param {Function} [errback] - when `fn` passes an error to it's callback, + * this function will be called, and execution stops. Invoked with (err). + * @example + * + * async.forever( + * function(next) { + * // next is suitable for passing to things that need a callback(err [, whatever]); + * // it will result in this function being called again. + * }, + * function(err) { + * // if next is called with a value in its first parameter, it will appear + * // in here as 'err', and execution will stop. + * } + * ); + */ + 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. + * + * @name groupByLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + */ + var groupByLimit = function(coll, limit, iteratee, callback) { + callback = callback || noop; + var _iteratee = wrapAsync(iteratee); + mapLimit(coll, limit, function(val, callback) { + _iteratee(val, function(err, key) { + if (err) return callback(err); + return callback(null, {key: key, val: val}); + }); + }, function(err, mapResults) { + 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 { + result[key] = [val]; + } + } + } + + 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 + * correspond to the values passed to the `iteratee` callback. + * + * Note: Since this function applies the `iteratee` to each item in parallel, + * there is no guarantee that the `iteratee` functions will complete in order. + * However, the values for each key in the `result` will be in the same order as + * the original `coll`. For Objects, the values will roughly be in the order of + * the original Objects' keys (but this can vary across JavaScript engines). + * + * @name groupBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @example + * + * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) { + * db.findById(userId, function(err, user) { + * if (err) return callback(err); + * return callback(null, user.age); + * }); + * }, function(err, result) { + * // result is object containing the userIds grouped by age + * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']}; + * }); + */ + var groupBy = doLimit(groupByLimit, Infinity); + + /** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. + * + * @name groupBySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * 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 + * as FF and Chrome). If multiple arguments are returned from the async + * function, `console.log` is called on each argument in order. + * + * @name log + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, 'hello ' + name); + * }, 1000); + * }; + * + * // in the node repl + * node> async.log(hello, 'world'); + * '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. + * + * @name mapValuesLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + */ + function mapValuesLimit(obj, limit, iteratee, callback) { + callback = once(callback || noop); + var newObj = {}; + var _iteratee = wrapAsync(iteratee); + eachOfLimit(obj, limit, function(val, key, next) { + _iteratee(val, key, function (err, result) { + if (err) return next(err); + newObj[key] = result; + next(); + }); + }, function (err) { + callback(err, newObj); + }); + } + + /** + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. + * + * Produces a new Object by mapping each value of `obj` through the `iteratee` + * function. The `iteratee` is called each `value` and `key` from `obj` and a + * callback for when it has finished processing. Each of these callbacks takes + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` + * passes an error to its callback, the main `callback` (for the `mapValues` + * function) is immediately called with the error. + * + * Note, the order of the keys in the result is not guaranteed. The keys will + * be roughly in the order they complete, (but this is very engine-specific) + * + * @name mapValues + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @example + * + * async.mapValues({ + * f1: 'file1', + * f2: 'file2', + * f3: 'file3' + * }, function (file, key, callback) { + * fs.stat(file, callback); + * }, function(err, result) { + * // result is now a map of stats for each file, e.g. + * // { + * // f1: [stats for file1], + * // f2: [stats for file2], + * // f3: [stats for file3] + * // } + * }); + */ + + var mapValues = doLimit(mapValuesLimit, Infinity); + + /** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. + * + * @name mapValuesSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * 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 + * optional hash function can be used. + * + * If no hash function is specified, the first argument is used as a hash key, + * which may work reasonably if it is a string or a data type that converts to a + * distinct string. Note that objects and arrays will not behave reasonably. + * Neither will cases where the other arguments are significant. In such cases, + * specify your own hash function. + * + * The cache of results is exposed as the `memo` property of the function + * returned by `memoize`. + * + * @name memoize + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function to proxy and cache results from. + * @param {Function} hasher - An optional function for generating a custom hash + * for storing results. It has all the arguments applied to it apart from the + * callback, and must be synchronous. + * @returns {AsyncFunction} a memoized version of `fn` + * @example + * + * var slow_fn = function(name, callback) { + * // do something + * callback(null, result); + * }; + * var fn = async.memoize(slow_fn); + * + * // fn can now be used as if it were slow_fn + * fn('some name', function() { + * // callback + * }); + */ + function memoize(fn, hasher) { + var memo = Object.create(null); + var queues = Object.create(null); + hasher = hasher || identity; + var _fn = wrapAsync(fn); + var memoized = initialParams(function memoized(args, callback) { + var key = hasher.apply(null, args); + if (has(memo, key)) { + setImmediate$1(function() { + callback.apply(null, memo[key]); + }); + } else if (has(queues, key)) { + queues[key].push(callback); + } else { + queues[key] = [callback]; + _fn.apply(null, args.concat(function(/*args*/) { + var args = slice(arguments); + memo[key] = args; + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i].apply(null, args); + } + })); + } + }); + memoized.memo = memo; + 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 + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name nextTick + * @static + * @memberOf module:Utils + * @method + * @see [async.setImmediate]{@link module:Utils.setImmediate} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ + var _defer$1; + + if (hasNextTick) { + _defer$1 = process.nextTick; + } else if (hasSetImmediate) { + _defer$1 = setImmediate; + } 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) { + result = slice(arguments, 1); + } + results[key] = result; + callback(err); + }); + }, function (err) { + 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 + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * + * @example + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // optional callback + * function(err, results) { + * // the results array will equal ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equals to: {one: 1, two: 2} + * }); + */ + 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. + * + * @name parallelLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.parallel]{@link module:ControlFlow.parallel} + * @category Control Flow + * @param {Array|Iterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + */ + function parallelLimit$1(tasks, limit, callback) { + _parallel(_eachOfLimit(limit), tasks, callback); + } + + /** + * A queue of tasks for the worker function to complete. + * @typedef {Object} QueueObject + * @memberOf module:ControlFlow + * @property {Function} length - a function returning the number of items + * waiting to be processed. Invoke with `queue.length()`. + * @property {boolean} started - a boolean indicating whether or not any + * items have been pushed and processed by the queue. + * @property {Function} running - a function returning the number of items + * currently being processed. Invoke with `queue.running()`. + * @property {Function} workersList - a function returning the array of items + * currently being processed. Invoke with `queue.workersList()`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke with `queue.idle()`. + * @property {number} concurrency - an integer for determining how many `worker` + * functions should be run in parallel. This property can be changed after a + * `queue` is created to alter the concurrency on-the-fly. + * @property {Function} push - add a new task to the `queue`. Calls `callback` + * once the `worker` has finished processing the task. Instead of a single task, + * a `tasks` array can be submitted. The respective callback is used for every + * task in the list. Invoke with `queue.push(task, [callback])`, + * @property {Function} unshift - add a new task to the front of the `queue`. + * Invoke with `queue.unshift(task, [callback])`. + * @property {Function} remove - remove items from the queue that match a test + * function. The test function will be passed an object with a `data` property, + * and a `priority` property, if this is a + * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. + * Invoked with `queue.remove(testFn)`, where `testFn` is of the form + * `function ({data, priority}) {}` and returns a Boolean. + * @property {Function} saturated - a callback that is called when the number of + * running workers hits the `concurrency` limit, and further tasks will be + * queued. + * @property {Function} unsaturated - a callback that is called when the number + * of running workers is less than the `concurrency` & `buffer` limits, and + * further tasks will not be queued. + * @property {number} buffer - A minimum threshold buffer in order to say that + * the `queue` is `unsaturated`. + * @property {Function} empty - a callback that is called when the last item + * from the `queue` is given to a `worker`. + * @property {Function} drain - a callback that is called when the last item + * from the `queue` has returned from the `worker`. + * @property {Function} error - a callback that is called when a task errors. + * Has the signature `function(error, task)`. + * @property {boolean} paused - a boolean for determining whether the queue is + * in a paused state. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke with `queue.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke with `queue.resume()`. + * @property {Function} kill - a function that removes the `drain` callback and + * 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 + * `worker`s are in progress, the task is queued until one becomes available. + * Once a `worker` completes a `task`, that `task`'s callback is called. + * + * @name queue + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. Invoked with (task, callback). + * @param {number} [concurrency=1] - An `integer` for determining how many + * `worker` functions should be run in parallel. If omitted, the concurrency + * defaults to `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the queue. + * @example + * + * // create a queue object with concurrency 2 + * var q = async.queue(function(task, callback) { + * console.log('hello ' + task.name); + * callback(); + * }, 2); + * + * // assign a callback + * q.drain = function() { + * console.log('all items have been processed'); + * }; + * + * // add some items to the queue + * q.push({name: 'foo'}, function(err) { + * console.log('finished processing foo'); + * }); + * q.push({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + * + * // add some items to the queue (batch-wise) + * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { + * console.log('finished processing item'); + * }); + * + * // add some items to the front of the queue + * q.unshift({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + */ + var queue$1 = function (worker, concurrency) { + var _worker = wrapAsync(worker); + return queue(function (items, cb) { + _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. + * + * @name priorityQueue + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. + * Invoked with (task, callback). + * @param {number} concurrency - An `integer` for determining how many `worker` + * functions should be run in parallel. If omitted, the concurrency defaults to + * `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two + * differences between `queue` and `priorityQueue` objects: + * * `push(task, priority, [callback])` - `priority` should be a number. If an + * array of `tasks` is given, all tasks will be assigned the same priority. + * * The `unshift` method was removed. + */ + 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; + if (typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + if (!isArray(data)) { + data = [data]; + } + if (data.length === 0) { + // call drain immediately if there are no tasks + return setImmediate$1(function() { + 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 { + q._tasks.push(item); + } + } + 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 + * error to its callback, the main `callback` is immediately called. It's + * equivalent to `Promise.race()`. + * + * @name race + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} + * to run. Each function can complete with an optional `result` value. + * @param {Function} callback - A callback to run once any of the functions have + * completed. This function gets an error or result from the first function that + * completed. Invoked with (err, result). + * @returns undefined + * @example + * + * async.race([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // main callback + * function(err, result) { + * // the result will be equal to 'two' as it finishes earlier + * }); + */ + function race(tasks, callback) { + callback = once(callback || noop); + if (!isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); + if (!tasks.length) return callback(); + for (var i = 0, l = tasks.length; i < l; i++) { + wrapAsync(tasks[i])(callback); + } + } + + /** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee complete with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + */ + function reduceRight (array, memo, iteratee, callback) { + 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. + * + * The result object has either the property `error` or `value`. + * + * @name reflect + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function you want to wrap + * @returns {Function} - A function that always passes null to it's callback as + * the error. The second argument to the callback will be an `object` with + * either an `error` or a `value` property. + * @example + * + * async.parallel([ + * async.reflect(function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }), + * async.reflect(function(callback) { + * // do some more stuff but error ... + * callback('bad stuff happened'); + * }), + * async.reflect(function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * }) + * ], + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = 'bad stuff happened' + * // results[2].value = 'two' + * }); + */ + function reflect(fn) { + var _fn = wrapAsync(fn); + return initialParams(function reflectOn(args, reflectCallback) { + args.push(function callback(error, cbArg) { + if (error) { + reflectCallback(null, { error: error }); + } else { + var value; + if (arguments.length <= 2) { + value = cbArg; + } else { + value = slice(arguments, 1); + } + reflectCallback(null, { value: value }); + } + }); + + return _fn.apply(this, args); + }); + } + + /** + * A helper function that wraps an array or an object of functions with `reflect`. + * + * @name reflectAll + * @static + * @memberOf module:Utils + * @method + * @see [async.reflect]{@link module:Utils.reflect} + * @category Util + * @param {Array|Object|Iterable} tasks - The collection of + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. + * @returns {Array} Returns an array of async functions, each wrapped in + * `async.reflect` + * @example + * + * let tasks = [ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * // do some more stuff but error ... + * callback(new Error('bad stuff happened')); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = Error('bad stuff happened') + * // results[2].value = 'two' + * }); + * + * // an example using an object instead of an array + * let tasks = { + * one: function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * two: function(callback) { + * callback('two'); + * }, + * three: function(callback) { + * setTimeout(function() { + * callback(null, 'three'); + * }, 100); + * } + * }; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results.one.value = 'one' + * // results.two.error = 'two' + * // results.three.value = 'three' + * }); + */ + function reflectAll(tasks) { + var results; + if (isArray(tasks)) { + results = arrayMap(tasks, reflect); + } else { + results = {}; + baseForOwn(tasks, function(task, key) { + results[key] = reflect.call(this, task); + }); + } + return results; + } + + function reject$1(eachfn, arr, iteratee, callback) { + _filter(eachfn, arr, function(value, cb) { + iteratee(value, function(err, v) { + cb(err, !v); + }); + }, callback); + } + + /** + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. + * + * @name reject + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @example + * + * async.reject(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of missing files + * createFiles(results); + * }); + */ + var reject = doParallel(reject$1); + + /** + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a + * time. + * + * @name rejectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `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. + * + * @name rejectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + */ + var rejectSeries = doLimit(rejectLimit, 1); + + /** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new constant function. + * @example + * + * var objects = _.times(2, _.constant({ 'a': 1 })); + * + * console.log(objects); + * // => [{ 'a': 1 }, { 'a': 1 }] + * + * console.log(objects[0] === objects[1]); + * // => true + */ + function constant$1(value) { + return function() { + 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 + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ + 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; + } else { + throw new Error("Invalid arguments for async.retry"); + } + } + + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || noop; + task = opts; + } else { + 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) { + if (err && attempt++ < options.times && + (typeof options.errorFilter != 'function' || + options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt)); + } else { + callback.apply(null, arguments); + } + }); + } + + retryAttempt(); + } + + /** + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method + * wraps a task and makes it retryable, rather than immediately calling it + * with retries. + * + * @name retryable + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.retry]{@link module:ControlFlow.retry} + * @category Control Flow + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional + * options, exactly the same as from `retry` + * @param {AsyncFunction} task - the asynchronous function to wrap. + * This function will be passed any arguments passed to the returned wrapper. + * Invoked with (...args, callback). + * @returns {AsyncFunction} The wrapped function, which when invoked, will + * retry on an error, based on the parameters specified in `opts`. + * This function will accept the same parameters as `task`. + * @example + * + * async.auto({ + * dep1: async.retryable(3, getFromFlakyService), + * process: ["dep1", async.retryable(3, function (results, cb) { + * maybeProcessData(results.dep1, cb); + * })] + * }, callback); + */ + var retryable = function (opts, task) { + if (!task) { + task = opts; + opts = null; + } + var _task = wrapAsync(task); + return initialParams(function (args, callback) { + 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 + * error to its callback, no more functions are run, and `callback` is + * immediately called with the value of the error. Otherwise, `callback` + * receives an array of results when `tasks` have completed. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function, and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.series}. + * + * **Note** that while many implementations preserve the order of object + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) + * explicitly states that + * + * > The mechanics and order of enumerating the properties is not specified. + * + * So if you rely on the order in which your series of functions are executed, + * and want this to work on all platforms, consider using an array. + * + * @name series + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|Object} tasks - A collection containing + * [async functions]{@link AsyncFunction} to run in series. + * Each function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This function gets a results array (or object) + * containing all the result arguments passed to the `task` callbacks. Invoked + * with (err, result). + * @example + * async.series([ + * function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }, + * function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * } + * ], + * // optional callback + * function(err, results) { + * // results is now equal to ['one', 'two'] + * }); + * + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback){ + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equal to: {one: 1, two: 2} + * }); + */ + 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 + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @example + * + * async.some(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then at least one of the files exists + * }); + */ + 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. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * 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. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * 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`. + * + * @name sortBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a value to use as the sort criteria as + * its `result`. + * Invoked with (item, callback). + * @param {Function} callback - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is the items + * from the original `coll` sorted by the values returned by the `iteratee` + * calls. Invoked with (err, results). + * @example + * + * async.sortBy(['file1','file2','file3'], function(file, callback) { + * fs.stat(file, function(err, stats) { + * callback(err, stats.mtime); + * }); + * }, function(err, results) { + * // results is now the original array of files sorted by + * // modified date + * }); + * + * // By modifying the callback parameter the + * // sorting order can be influenced: + * + * // ascending order + * async.sortBy([1,9,3,5], function(x, callback) { + * callback(null, x); + * }, function(err,result) { + * // result callback + * }); + * + * // descending order + * async.sortBy([1,9,3,5], function(x, callback) { + * callback(null, x*-1); //<- x*-1 instead of x, turns the order around + * }, function(err,result) { + * // result callback + * }); + */ + function sortBy (coll, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + map(coll, function (x, callback) { + _iteratee(x, function (err, criteria) { + if (err) return callback(err); + callback(null, {value: x, criteria: criteria}); + }); + }, function (err, results) { + 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 + * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * + * @name timeout + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} asyncFn - The async function to limit in time. + * @param {number} milliseconds - The specified time limit. + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) + * to timeout Error for more information.. + * @returns {AsyncFunction} Returns a wrapped function that can be used with any + * of the control flow functions. + * Invoke this function with the same parameters as you would `asyncFunc`. + * @example + * + * function myFunction(foo, callback) { + * doAsyncTask(foo, function(err, data) { + * // handle errors + * if (err) return callback(err); + * + * // do some stuff ... + * + * // return processed data + * return callback(null, data); + * }); + * } + * + * var wrapped = async.timeout(myFunction, 1000); + * + * // call `wrapped` as you would `myFunction` + * wrapped({ bar: 'bar' }, function(err, data) { + * // if `myFunction` takes < 1000 ms to execute, `err` + * // and `data` will have their expected values + * + * // else `err` will be an Error with the code 'ETIMEDOUT' + * }); + */ + 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.'); + error.code = 'ETIMEDOUT'; + if (info) { + error.info = info; + } + 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. + * + * @private + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @param {number} step The value to increment or decrement by. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the range of numbers. + */ + function baseRange(start, end, step, fromRight) { + 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. + * + * @name timesLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} count - The number of times to run the function. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see [async.map]{@link module:Collections.map}. + */ + function timeLimit(count, limit, iteratee, callback) { + 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}. + * + * @name times + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.map]{@link module:Collections.map} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @example + * + * // Pretend this is some complicated async factory + * var createUser = function(id, callback) { + * callback(null, { + * id: 'user' + id + * }); + * }; + * + * // generate 5 users + * async.times(5, function(n, next) { + * createUser(n, function(err, user) { + * next(err, user); + * }); + * }, function(err, users) { + * // we should now have 5 users + * }); + */ + var times = doLimit(timeLimit, Infinity); + + /** + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * + * @name timesSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @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. + * The type of the accumulator defaults to the type of collection passed in. + * + * @name transform + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {*} [accumulator] - The initial state of the transform. If omitted, + * it will default to an empty Object or Array, depending on the type of `coll` + * @param {AsyncFunction} iteratee - A function applied to each item in the + * collection that potentially modifies the accumulator. + * Invoked with (accumulator, item, key, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the transformed accumulator. + * Invoked with (err, result). + * @example + * + * async.transform([1,2,3], function(acc, item, index, callback) { + * // pointless async: + * process.nextTick(function() { + * acc.push(item * 2) + * callback(null) + * }); + * }, function(err, result) { + * // result is now equal to [2, 4, 6] + * }); + * + * @example + * + * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { + * setImmediate(function () { + * obj[key] = val * 2; + * callback(); + * }) + * }, function (err, result) { + * // result is equal to {a: 2, b: 4, c: 6} + * }) + */ + function transform (coll, accumulator, iteratee, callback) { + if (arguments.length <= 3) { + callback = iteratee; + iteratee = accumulator; + accumulator = isArray(coll) ? [] : {}; + } + 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 + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @example + * async.tryEach([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ + function tryEach(tasks, callback) { + var error = null; + var result; + callback = callback || noop; + eachSeries(tasks, function(task, callback) { + wrapAsync(task)(function (err, res/*, ...args*/) { + if (arguments.length > 2) { + result = slice(arguments, 1); + } else { + result = res; + } + error = err; + callback(!err); + }); + }, function () { + callback(error, result); + }); + } + + /** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ + function unmemoize(fn) { + return function () { + return (fn.unmemoized || fn).apply(null, arguments); + }; + } + + /** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Function} test - synchronous truth test to perform before each + * execution of `iteratee`. Invoked with (). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns undefined + * @example + * + * var count = 0; + * async.whilst( + * function() { return count < 5; }, + * function(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ + function whilst(test, iteratee, callback) { + callback = onlyOnce(callback || noop); + var _iteratee = wrapAsync(iteratee); + if (!test()) return callback(null); + var next = function(err/*, ...args*/) { + if (err) return callback(err); + if (test()) return _iteratee(next); + var args = slice(arguments, 1); + callback.apply(null, [null].concat(args)); + }; + _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 + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {Function} test - synchronous truth test to perform before each + * execution of `iteratee`. Invoked with (). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + */ + function until(test, iteratee, callback) { + whilst(function() { + 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 + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns undefined + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ + var waterfall = function(tasks, callback) { + callback = once(callback || noop); + 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. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. + * + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static + */ + + /** + * Async is a utility module which provides straight-forward, powerful functions + * for working with asynchronous JavaScript. Although originally designed for + * use with [Node.js](http://nodejs.org) and installable via + * `npm install --save async`, it can also be used directly in the browser. + * @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, + applyEachSeries: applyEachSeries, + asyncify: asyncify, + auto: auto, + autoInject: autoInject, + cargo: cargo, + compose: compose, + concat: concat, + concatLimit: concatLimit, + concatSeries: concatSeries, + constant: constant, + detect: detect, + detectLimit: detectLimit, + detectSeries: detectSeries, + dir: dir, + doDuring: doDuring, + doUntil: doUntil, + doWhilst: doWhilst, + during: during, + each: eachLimit, + eachLimit: eachLimit$1, + eachOf: eachOf, + eachOfLimit: eachOfLimit, + eachOfSeries: eachOfSeries, + eachSeries: eachSeries, + ensureAsync: ensureAsync, + every: every, + everyLimit: everyLimit, + everySeries: everySeries, + filter: filter, + filterLimit: filterLimit, + filterSeries: filterSeries, + forever: forever, + groupBy: groupBy, + groupByLimit: groupByLimit, + groupBySeries: groupBySeries, + log: log, + map: map, + mapLimit: mapLimit, + mapSeries: mapSeries, + mapValues: mapValues, + mapValuesLimit: mapValuesLimit, + mapValuesSeries: mapValuesSeries, + memoize: memoize, + nextTick: nextTick, + parallel: parallelLimit, + parallelLimit: parallelLimit$1, + priorityQueue: priorityQueue, + queue: queue$1, + race: race, + reduce: reduce, + reduceRight: reduceRight, + reflect: reflect, + reflectAll: reflectAll, + reject: reject, + rejectLimit: rejectLimit, + rejectSeries: rejectSeries, + retry: retry, + retryable: retryable, + seq: seq, + series: series, + setImmediate: setImmediate$1, + some: some, + someLimit: someLimit, + someSeries: someSeries, + sortBy: sortBy, + timeout: timeout, + times: times, + timesLimit: timeLimit, + timesSeries: timesSeries, + transform: transform, + tryEach: tryEach, + unmemoize: unmemoize, + until: until, + waterfall: waterfall, + whilst: whilst, + + // aliases + all: every, + allLimit: everyLimit, + allSeries: everySeries, + any: some, + anyLimit: someLimit, + anySeries: someSeries, + find: detect, + findLimit: detectLimit, + findSeries: detectSeries, + forEach: eachLimit, + forEachSeries: eachSeries, + forEachLimit: eachLimit$1, + forEachOf: eachOf, + forEachOfSeries: eachOfSeries, + forEachOfLimit: eachOfLimit, + inject: reduce, + foldl: reduce, + foldr: reduceRight, + select: filter, + selectLimit: filterLimit, + selectSeries: filterSeries, + wrapSync: asyncify + }; + + exports['default'] = index; + exports.apply = apply; + exports.applyEach = applyEach; + exports.applyEachSeries = applyEachSeries; + exports.asyncify = asyncify; + exports.auto = auto; + exports.autoInject = autoInject; + exports.cargo = cargo; + exports.compose = compose; + exports.concat = concat; + exports.concatLimit = concatLimit; + exports.concatSeries = concatSeries; + exports.constant = constant; + exports.detect = detect; + exports.detectLimit = detectLimit; + exports.detectSeries = detectSeries; + exports.dir = dir; + exports.doDuring = doDuring; + exports.doUntil = doUntil; + exports.doWhilst = doWhilst; + exports.during = during; + exports.each = eachLimit; + exports.eachLimit = eachLimit$1; + exports.eachOf = eachOf; + exports.eachOfLimit = eachOfLimit; + exports.eachOfSeries = eachOfSeries; + exports.eachSeries = eachSeries; + exports.ensureAsync = ensureAsync; + exports.every = every; + exports.everyLimit = everyLimit; + exports.everySeries = everySeries; + exports.filter = filter; + exports.filterLimit = filterLimit; + exports.filterSeries = filterSeries; + exports.forever = forever; + exports.groupBy = groupBy; + exports.groupByLimit = groupByLimit; + exports.groupBySeries = groupBySeries; + exports.log = log; + exports.map = map; + exports.mapLimit = mapLimit; + exports.mapSeries = mapSeries; + exports.mapValues = mapValues; + exports.mapValuesLimit = mapValuesLimit; + exports.mapValuesSeries = mapValuesSeries; + exports.memoize = memoize; + exports.nextTick = nextTick; + exports.parallel = parallelLimit; + exports.parallelLimit = parallelLimit$1; + exports.priorityQueue = priorityQueue; + exports.queue = queue$1; + exports.race = race; + exports.reduce = reduce; + exports.reduceRight = reduceRight; + exports.reflect = reflect; + exports.reflectAll = reflectAll; + exports.reject = reject; + exports.rejectLimit = rejectLimit; + exports.rejectSeries = rejectSeries; + exports.retry = retry; + exports.retryable = retryable; + exports.seq = seq; + exports.series = series; + exports.setImmediate = setImmediate$1; + exports.some = some; + exports.someLimit = someLimit; + exports.someSeries = someSeries; + exports.sortBy = sortBy; + exports.timeout = timeout; + exports.times = times; + exports.timesLimit = timeLimit; + exports.timesSeries = timesSeries; + exports.transform = transform; + exports.tryEach = tryEach; + exports.unmemoize = unmemoize; + exports.until = until; + exports.waterfall = waterfall; + exports.whilst = whilst; + exports.all = every; + exports.allLimit = everyLimit; + exports.allSeries = everySeries; + exports.any = some; + exports.anyLimit = someLimit; + exports.anySeries = someSeries; + exports.find = detect; + exports.findLimit = detectLimit; + exports.findSeries = detectSeries; + exports.forEach = eachLimit; + exports.forEachSeries = eachSeries; + exports.forEachLimit = eachLimit$1; + exports.forEachOf = eachOf; + exports.forEachOfSeries = eachOfSeries; + exports.forEachOfLimit = eachOfLimit; + exports.inject = reduce; + exports.foldl = reduce; + exports.foldr = reduceRight; + exports.select = filter; + 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. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + */ + function eachLimit(coll, limit, iteratee, callback) { + (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); + } + module.exports = exports['default']; + },{"./internal/eachOfLimit":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); + var index = 0, + completed = 0, + length = coll.length; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err) { + callback(err); + } else if (++completed === length || value === _breakLoop2.default) { + 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. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @example + * + * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; + * var configs = {}; + * + * async.forEachOf(obj, function (value, key, callback) { + * fs.readFile(__dirname + value, "utf8", function (err, data) { + * if (err) return callback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * }, function (err) { + * if (err) console.error(err.message); + * // configs is now a map of JSON data + * doSomethingWith(configs); + * }); + */ + 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. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + */ + function eachOfLimit(coll, limit, iteratee, callback) { + (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); + } + 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. + * + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + */ + exports.default = (0, _doLimit2.default)(_eachLimit2.default, 1); + module.exports = exports['default']; + },{"./eachLimit":22,"./internal/doLimit":27}],26:[function(require,module,exports){ + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + // A temporary value used to identify if the loop should be broken. + // See #1064, #1293 + exports.default = {}; + module.exports = exports["default"]; + },{}],27:[function(require,module,exports){ + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = doLimit; + function doLimit(fn, limit) { + return function (iterable, iteratee, callback) { + return fn(iterable, limit, iteratee, callback); + }; + } + 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); + }; + } + 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); + if (limit <= 0 || !obj) { + return callback(null); + } + var nextElem = (0, _iterator2.default)(obj); + var done = false; + var running = 0; + + function iterateeCallback(err, value) { + running -= 1; + if (err) { + done = true; + callback(err); + } else if (value === _breakLoop2.default || done && running <= 0) { + done = true; + return callback(null); + } else { + replenish(); + } + } + + function replenish() { + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + 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); + var callback = args.pop(); + 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; + return function next() { + return ++i < len ? { value: coll[i], key: i } : null; + }; + } + + function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) return null; + i++; + return { value: item.value, key: i }; + }; + } + + function createObjectIterator(obj) { + var okeys = (0, _keys2.default)(obj); + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + 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) { + results[index] = v; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + module.exports = exports['default']; + },{"./wrapAsync":40,"lodash/noop":229}],34:[function(require,module,exports){ + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = once; + function once(fn) { + return function () { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, arguments); + }; + } + module.exports = exports["default"]; + },{}],35:[function(require,module,exports){ + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = onlyOnce; + function onlyOnce(fn) { + return function () { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; + callFn.apply(this, arguments); + }; + } + 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) { + result = (0, _slice2.default)(arguments, 1); + } + results[key] = result; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + module.exports = exports['default']; + },{"./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); + defer(function () { + fn.apply(null, args); + }); + }; + } + + var _defer; + + if (hasSetImmediate) { + _defer = setImmediate; + } else if (hasNextTick) { + _defer = process.nextTick; + } 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 + }); + exports.default = slice; + function slice(arrayLike, start) { + start = start | 0; + var newLen = Math.max(arrayLike.length - start, 0); + var newArr = Array(newLen); + for (var idx = 0; idx < newLen; idx++) { + newArr[idx] = arrayLike[start + idx]; + } + return newArr; + } + module.exports = exports["default"]; + },{}],39:[function(require,module,exports){ + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = _withoutIndex; + function _withoutIndex(iteratee) { + return function (value, index, callback) { + return iteratee(value, callback); + }; + } + 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` + * and a callback for when it has finished processing. Each of these callback + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @example + * + * async.map(['file1','file2','file3'], fs.stat, function(err, results) { + * // results is now an array of stats for each file + * }); + */ + exports.default = (0, _doParallel2.default)(_map2.default); + 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 + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * + * @example + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // optional callback + * function(err, results) { + * // the results array will equal ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equals to: {one: 1, two: 2} + * }); + */ + function parallelLimit(tasks, callback) { + (0, _parallel2.default)(_eachOf2.default, tasks, callback); + } + 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 + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ + 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; + } else { + throw new Error("Invalid arguments for async.retry"); + } + } + + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || _noop2.default; + task = opts; + } else { + 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) { + if (err && attempt++ < options.times && (typeof options.errorFilter != 'function' || options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt)); + } else { + callback.apply(null, arguments); + } + }); + } + + 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 + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns undefined + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ + },{"./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); + fn = args[0]; + vargs = args.slice(1, args.length - 1); + 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(); + } else { + this.backoffDelay_ = this.backoffStrategy_.next(); + this.timeoutID_ = setTimeout(this.handlers.backoff, this.backoffDelay_); + 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; + this.backoffStrategy_.reset(); + 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. + PENDING: 0, + // Call is in progress. + RUNNING: 1, + // Call completed successfully which means that either the wrapped function + // returned successfully or the maximal number of backoffs was reached. + COMPLETED: 2, + // 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) { + precond.checkState(this.isPending(), 'FunctionCall in progress.'); + 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 + // function call. + FunctionCall.prototype.retryIf = function(retryPredicate) { + precond.checkState(this.isPending(), 'FunctionCall in progress.'); + 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) { + this.numRetries_++; + } + var eventArgs = ['call'].concat(this.arguments_); + events.EventEmitter.prototype.emit.apply(this, eventArgs); + 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); + } else { + this.state_ = FunctionCall.State_.COMPLETED; + 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.', + options.factor); + this.factor_ = options.factor; + } + } + 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); + this.backoffDelay_ = 0; + 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: + // + // * `randomisationFactor`: The randomisation factor which must be between 0 + // and 1 where 1 equates to a randomization factor of 100% and 0 to no + // randomization. + // * `initialDelay`: The backoff initial delay in milliseconds. + // * `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() { + var backoffDelay = this.next_(); + var randomisationMultiple = 1 + Math.random() * this.randomisationFactor_; + 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 + // if there is only one, then the three characters before it represent 2 bytes + // 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 + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) + 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 = [] + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output.push(tripletToBase64(tmp)) + } + return output.join('') + } + + function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var 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] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3F] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3F] + 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. + * + * The DER format uses the most significant bit as a sign bit (& 0x80). + * If the significant bit is set AND the integer is positive, a 0x00 is prepended. + * + * Examples: + * + * 0 => 0x00 + * 1 => 0x01 + * -1 => 0xff + * 127 => 0x7f + * -127 => 0x81 + * 128 => 0x0080 + * -128 => 0x80 + * 255 => 0x00ff + * -255 => 0xff01 + * 16300 => 0x3fac + * -16300 => 0xc054 + * 62300 => 0x00f35c + * -62300 => 0xff0ca4 + */ + function encode (r, s) { + var lenR = r.length + var lenS = s.length + if (lenR === 0) throw new Error('R length is zero') + if (lenS === 0) throw new Error('S length is zero') + if (lenR > 33) throw new Error('R length is too long') + if (lenS > 33) throw new Error('S length is too long') + if (r[0] & 0x80) throw new Error('R value is negative') + if (s[0] & 0x80) throw new Error('S value is negative') + if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded') + if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded') + + var signature = Buffer.allocUnsafe(6 + lenR + lenS) + + // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] + signature[0] = 0x30 + signature[1] = signature.length - 2 + signature[2] = 0x02 + signature[3] = r.length + r.copy(signature, 4) + signature[4 + lenR] = 0x02 + signature[5 + lenR] = s.length + s.copy(signature, 6 + lenR) + + return signature + } + + module.exports = { + check: check, + decode: decode, + encode: encode + } + + },{"safe-buffer":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) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + Buffer = require('buffer').Buffer; + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + } + + if (base === 16) { + this._parseHex(number, start); + } else { + this._parseBase(number, base, start); + } + + if (number[0] === '-') { + this.negative = 1; + } + + this.strip(); + + if (endian !== 'le') return; + + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex (str, start, end) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r <<= 4; + + // 'a' - 'f' + if (c >= 49 && c <= 54) { + r |= c - 49 + 0xa; + + // 'A' - 'F' + } else if (c >= 17 && c <= 22) { + r |= c - 17 + 0xa; + + // '0' - '9' + } else { + r |= c & 0xf; + } + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + // Scan 24-bit chunks and add them to the number + var off = 0; + for (i = number.length - 6, j = 0; i >= start; i -= 6) { + w = parseHex(number, i, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + if (i + 6 !== start) { + w = parseHex(number, start, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + } + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + r.strip(); + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; + })(typeof module === 'undefined' || module, this); + + },{"buffer":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 + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + self.crypto.getRandomValues(arr); + return arr; + }; + } else if (self.msCrypto && self.msCrypto.getRandomValues) { + // IE + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + self.msCrypto.getRandomValues(arr); + return arr; + }; + + // Safari's WebWorkers do not have `crypto` + } else if (typeof window === 'object') { + // Old junk + Rand.prototype._rand = function() { + throw new Error('Not implemented yet'); + }; + } + } else { + // Node.js or Web worker with no crypto support + try { + var crypto = require('crypto'); + if (typeof crypto.randomBytes !== 'function') + throw new Error('Not supported'); + + Rand.prototype._rand = function _rand(n) { + return crypto.randomBytes(n); + }; + } catch (e) { + } + } + + },{"crypto":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++] + t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++] + t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++] + s0 = t0 + s1 = t1 + 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++] + t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++] + t0 = t0 >>> 0 + 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 () { + // Compute double table + var d = new Array(256) + for (var j = 0; j < 256; j++) { + if (j < 128) { + d[j] = j << 1 + } else { + 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 + for (var i = 0; i < 256; ++i) { + // Compute sbox + var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4) + 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 { + x = x2 ^ d[d[d[x8 ^ x2]]] + xi ^= d[d[xi]] + } + } + + return { + SBOX: SBOX, + INV_SBOX: INV_SBOX, + SUB_MIX: SUB_MIX, + 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 + AES.prototype.keySize = AES.keySize + AES.prototype._reset = function () { + var keyWords = this._key + 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 = + (G.SBOX[t >>> 24] << 24) | + (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 = + (G.SBOX[t >>> 24] << 24) | + (G.SBOX[(t >>> 16) & 0xff] << 16) | + (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 { + invKeySchedule[ik] = + G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^ + G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^ + G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^ + 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) + buf.writeUInt32BE(out[0], 0) + buf.writeUInt32BE(out[1], 4) + buf.writeUInt32BE(out[2], 8) + 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) + buf.writeUInt32BE(out[3], 4) + buf.writeUInt32BE(out[2], 8) + 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 + var Transform = require('cipher-base') + var inherits = require('inherits') + 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])]) + return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])]) + } + var ghash = new GHASH(ck) + var len = iv.length + var toPad = len % 16 + ghash.update(iv) + if (toPad) { + toPad = 16 - toPad + ghash.update(Buffer.alloc(toPad, 0)) + } + ghash.update(Buffer.alloc(8, 0)) + var ivBits = len * 8 + var tail = Buffer.alloc(8) + tail.writeUIntBE(ivBits, 0, 8) + ghash.update(tail) + self._finID = ghash.state + var out = Buffer.from(self._finID) + incr32(out) + return out + } + 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) + this._decrypt = decrypt + 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) + if (rump < 16) { + rump = Buffer.alloc(rump, 0) + this._ghash.update(rump) + } + } + + this._called = true + var out = this._mode.encrypt(this, chunk) + if (this._decrypt) { + this._ghash.update(chunk) + } else { + this._ghash.update(out) + } + 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 + var MODES = require('./modes') + var StreamCipher = require('./streamCipher') + var Transform = require('cipher-base') + 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) + this._prev = Buffer.from(iv) + this._mode = mode + this._autopadding = true + } + + inherits(Decipher, Transform) + + Decipher.prototype._update = function (data) { + this._cache.add(data) + var chunk + var thing + var out = [] + while ((chunk = this._cache.get(this._autopadding))) { + thing = this._mode.decrypt(this, chunk) + out.push(thing) + } + return Buffer.concat(out) + } + + Decipher.prototype._final = function () { + var chunk = this._cache.flush() + if (this._autopadding) { + return unpad(this._mode.decrypt(this, chunk)) + } else if (chunk) { + 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) { + if (this.cache.length > 16) { + out = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + return out + } + } else { + if (this.cache.length >= 16) { + out = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + 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 + while (++i < padded) { + if (last[(i + (16 - padded))] !== padded) { + throw new Error('unable to decrypt data') + } + } + 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') + var Buffer = require('safe-buffer').Buffer + var StreamCipher = require('./streamCipher') + var Transform = require('cipher-base') + 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) { + chunk = this._mode.encrypt(this, chunk) + 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) + this.cache = this.cache.slice(16) + return out + } + 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), + buf.readUInt32BE(4), + buf.readUInt32BE(8), + buf.readUInt32BE(12) + ] + } + + function fromArray (out) { + var buf = Buffer.allocUnsafe(16) + buf.writeUInt32BE(out[0] >>> 0, 0) + buf.writeUInt32BE(out[1] >>> 0, 4) + buf.writeUInt32BE(out[2] >>> 0, 8) + 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) { + var i = -1 + while (++i < block.length) { + this.state[i] ^= block[i] + } + this._multiply() + } + + GHASH.prototype._multiply = function () { + var Vi = toArray(this.h) + var Zi = [0, 0, 0, 0] + var j, xi, lsbVi + var i = -1 + while (++i < 128) { + xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0 + if (xi) { + // Z_i+1 = Z_i ^ V_i + Zi[0] ^= Vi[0] + Zi[1] ^= Vi[1] + 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) + } + } + this.state = fromArray(Zi) + } + + GHASH.prototype.update = function (buf) { + this.cache = Buffer.concat([this.cache, buf]) + var chunk + while (this.cache.length >= 16) { + chunk = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + 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 + var item + while (len--) { + item = iv.readUInt8(len) + if (item === 255) { + iv.writeUInt8(0, len) + } else { + item++ + iv.writeUInt8(item, len) + break + } + } + } + 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) + self._cache = self._cache.slice(len) + 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)]) + data = data.slice(len) + } else { + out = Buffer.concat([out, encryptStart(self, data, decrypt)]) + 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 + var len = 8 + var out = 0 + var bit, value + while (++i < len) { + pad = self._cipher.encryptBlock(self._prev) + bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0 + value = pad[0] ^ bit + out += ((value & 0x80) >> (i % 8)) + self._prev = shiftIn(self._prev, decrypt ? bit : value) + } + 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) + var start = self._cache.length + self._cache = Buffer.concat([ + self._cache, + Buffer.allocUnsafe(chunkNum * blockSize) + ]) + for (var i = 0; i < chunkNum; i++) { + var out = getBlock(self) + var offset = start + i * blockSize + self._cache.writeUInt32BE(out[0], offset + 0) + self._cache.writeUInt32BE(out[1], offset + 4) + self._cache.writeUInt32BE(out[2], offset + 8) + self._cache.writeUInt32BE(out[3], offset + 12) + } + var pad = self._cache.slice(0, chunk.length) + 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'), + CBC: require('./cbc'), + CFB: require('./cfb'), + CFB8: require('./cfb8'), + CFB1: require('./cfb1'), + OFB: require('./ofb'), + 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": { + "cipher": "AES", + "key": 128, + "iv": 0, + "mode": "ECB", + "type": "block" + }, + "aes-192-ecb": { + "cipher": "AES", + "key": 192, + "iv": 0, + "mode": "ECB", + "type": "block" + }, + "aes-256-ecb": { + "cipher": "AES", + "key": 256, + "iv": 0, + "mode": "ECB", + "type": "block" + }, + "aes-128-cbc": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes-192-cbc": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes-256-cbc": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes128": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes192": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes256": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes-128-cfb": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CFB", + "type": "stream" + }, + "aes-192-cfb": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CFB", + "type": "stream" + }, + "aes-256-cfb": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CFB", + "type": "stream" + }, + "aes-128-cfb8": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CFB8", + "type": "stream" + }, + "aes-192-cfb8": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CFB8", + "type": "stream" + }, + "aes-256-cfb8": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CFB8", + "type": "stream" + }, + "aes-128-cfb1": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CFB1", + "type": "stream" + }, + "aes-192-cfb1": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CFB1", + "type": "stream" + }, + "aes-256-cfb1": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CFB1", + "type": "stream" + }, + "aes-128-ofb": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "OFB", + "type": "stream" + }, + "aes-192-ofb": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "OFB", + "type": "stream" + }, + "aes-256-ofb": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "OFB", + "type": "stream" + }, + "aes-128-ctr": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CTR", + "type": "stream" + }, + "aes-192-ctr": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CTR", + "type": "stream" + }, + "aes-256-ctr": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CTR", + "type": "stream" + }, + "aes-128-gcm": { + "cipher": "AES", + "key": 128, + "iv": 12, + "mode": "GCM", + "type": "auth" + }, + "aes-192-gcm": { + "cipher": "AES", + "key": 192, + "iv": 12, + "mode": "GCM", + "type": "auth" + }, + "aes-256-gcm": { + "cipher": "AES", + "key": 256, + "iv": 12, + "mode": "GCM", + "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) + this._secCache = Buffer.allocUnsafe(0) + 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') + var DES = require('browserify-des') + var desModes = require('browserify-des/modes') + var aesModes = require('browserify-aes/modes') + function createCipher (suite, password) { + var keyLen, ivLen + suite = suite.toLowerCase() + if (aesModes[suite]) { + keyLen = aesModes[suite].key + ivLen = aesModes[suite].iv + } else if (desModes[suite]) { + keyLen = desModes[suite].key * 8 + ivLen = desModes[suite].iv + } else { + throw new TypeError('invalid suite type') + } + var keys = ebtk(password, false, keyLen, ivLen) + return createCipheriv(suite, keys.key, keys.iv) + } + function createDecipher (suite, password) { + var keyLen, ivLen + suite = suite.toLowerCase() + if (aesModes[suite]) { + keyLen = aesModes[suite].key + ivLen = aesModes[suite].iv + } else if (desModes[suite]) { + keyLen = desModes[suite].key * 8 + ivLen = desModes[suite].iv + } else { + throw new TypeError('invalid suite type') + } + 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]) { + return aes.createCipheriv(suite, key, iv) + } else if (desModes[suite]) { + return new DES({ + key: key, + iv: iv, + mode: suite + }) + } else { + throw new TypeError('invalid suite type') + } + } + function createDecipheriv (suite, key, iv) { + suite = suite.toLowerCase() + if (aesModes[suite]) { + return aes.createDecipheriv(suite, key, iv) + } else if (desModes[suite]) { + return new DES({ + key: key, + iv: iv, + mode: suite, + decrypt: true + }) + } else { + throw new TypeError('invalid suite type') + } + } + exports.createCipher = exports.Cipher = createCipher + exports.createCipheriv = exports.Cipheriv = createCipheriv + exports.createDecipher = exports.Decipher = createDecipher + exports.createDecipheriv = exports.Decipheriv = createDecipheriv + function getCiphers () { + 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, + 'des-ede-cbc': des.CBC.instantiate(des.EDE), + 'des-ede': des.EDE, + 'des-cbc': des.CBC.instantiate(des.DES), + 'des-ecb': des.DES + } + modes.des = modes['des-cbc'] + modes.des3 = modes['des-ede3-cbc'] + module.exports = DES + inherits(DES, CipherBase) + function DES (opts) { + CipherBase.call(this) + var modeName = opts.mode.toLowerCase() + var mode = modes[modeName] + var type + if (opts.decrypt) { + type = 'decrypt' + } else { + type = 'encrypt' + } + var key = opts.key + if (modeName === 'des-ede' || modeName === 'des-ede-cbc') { + key = Buffer.concat([key, key.slice(0, 8)]) + } + var iv = opts.iv + this._des = mode.create({ + key: key, + iv: iv, + type: type + }) + } + DES.prototype._update = function (data) { + return new Buffer(this._des.update(data)) + } + 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'] = { + key: 8, + iv: 0 + } + exports['des-cbc'] = exports.des = { + key: 8, + iv: 8 + } + exports['des-ede3-cbc'] = exports.des3 = { + key: 24, + iv: 8 + } + exports['des-ede3'] = { + key: 24, + iv: 0 + } + exports['des-ede-cbc'] = { + key: 16, + iv: 8 + } + exports['des-ede'] = { + key: 16, + iv: 0 + } + + },{}],76:[function(require,module,exports){ + (function (Buffer){ + var bn = require('bn.js'); + var randomBytes = require('randombytes'); + module.exports = crt; + function blind(priv) { + var r = getr(priv); + var blinder = r.toRed(bn.mont(priv.modulus)) + .redPow(new bn(priv.publicExponent)).fromRed(); + return { + blinder: blinder, + unblinder:r.invm(priv.modulus) + }; + } + function crt(msg, priv) { + var blinds = blind(priv); + var len = priv.modulus.byteLength(); + var mod = bn.mont(priv.modulus); + var blinded = new bn(msg).mul(blinds.blinder).umod(priv.modulus); + var c1 = blinded.toRed(bn.mont(priv.prime1)); + var c2 = blinded.toRed(bn.mont(priv.prime2)); + var qinv = priv.coefficient; + var p = priv.prime1; + var q = priv.prime2; + var m1 = c1.redPow(priv.exponent1); + var m2 = c2.redPow(priv.exponent2); + m1 = m1.fromRed(); + m2 = m2.fromRed(); + var h = m1.isub(m2).imul(qinv).umod(p); + h.imul(q); + m2.iadd(h); + return new Buffer(m2.imul(blinds.unblinder).umod(priv.modulus).toArray(false, len)); + } + crt.getr = getr; + function getr(priv) { + var len = priv.modulus.byteLength(); + var r = new bn(randomBytes(len)); + while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)) { + r = new bn(randomBytes(len)); + } + 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": { + "sign": "rsa", + "hash": "sha224", + "id": "302d300d06096086480165030402040500041c" + }, + "RSA-SHA224": { + "sign": "ecdsa/rsa", + "hash": "sha224", + "id": "302d300d06096086480165030402040500041c" + }, + "sha256WithRSAEncryption": { + "sign": "rsa", + "hash": "sha256", + "id": "3031300d060960864801650304020105000420" + }, + "RSA-SHA256": { + "sign": "ecdsa/rsa", + "hash": "sha256", + "id": "3031300d060960864801650304020105000420" + }, + "sha384WithRSAEncryption": { + "sign": "rsa", + "hash": "sha384", + "id": "3041300d060960864801650304020205000430" + }, + "RSA-SHA384": { + "sign": "ecdsa/rsa", + "hash": "sha384", + "id": "3041300d060960864801650304020205000430" + }, + "sha512WithRSAEncryption": { + "sign": "rsa", + "hash": "sha512", + "id": "3051300d060960864801650304020305000440" + }, + "RSA-SHA512": { + "sign": "ecdsa/rsa", + "hash": "sha512", + "id": "3051300d060960864801650304020305000440" + }, + "RSA-SHA1": { + "sign": "rsa", + "hash": "sha1", + "id": "3021300906052b0e03021a05000414" + }, + "ecdsa-with-SHA1": { + "sign": "ecdsa", + "hash": "sha1", + "id": "" + }, + "sha256": { + "sign": "ecdsa", + "hash": "sha256", + "id": "" + }, + "sha224": { + "sign": "ecdsa", + "hash": "sha224", + "id": "" + }, + "sha384": { + "sign": "ecdsa", + "hash": "sha384", + "id": "" + }, + "sha512": { + "sign": "ecdsa", + "hash": "sha512", + "id": "" + }, + "DSA-SHA": { + "sign": "dsa", + "hash": "sha1", + "id": "" + }, + "DSA-SHA1": { + "sign": "dsa", + "hash": "sha1", + "id": "" + }, + "DSA": { + "sign": "dsa", + "hash": "sha1", + "id": "" + }, + "DSA-WITH-SHA224": { + "sign": "dsa", + "hash": "sha224", + "id": "" + }, + "DSA-SHA224": { + "sign": "dsa", + "hash": "sha224", + "id": "" + }, + "DSA-WITH-SHA256": { + "sign": "dsa", + "hash": "sha256", + "id": "" + }, + "DSA-SHA256": { + "sign": "dsa", + "hash": "sha256", + "id": "" + }, + "DSA-WITH-SHA384": { + "sign": "dsa", + "hash": "sha384", + "id": "" + }, + "DSA-SHA384": { + "sign": "dsa", + "hash": "sha384", + "id": "" + }, + "DSA-WITH-SHA512": { + "sign": "dsa", + "hash": "sha512", + "id": "" + }, + "DSA-SHA512": { + "sign": "dsa", + "hash": "sha512", + "id": "" + }, + "DSA-RIPEMD160": { + "sign": "dsa", + "hash": "rmd160", + "id": "" + }, + "ripemd160WithRSA": { + "sign": "rsa", + "hash": "rmd160", + "id": "3021300906052b2403020105000414" + }, + "RSA-RIPEMD160": { + "sign": "rsa", + "hash": "rmd160", + "id": "3021300906052b2403020105000414" + }, + "md5WithRSAEncryption": { + "sign": "rsa", + "hash": "md5", + "id": "3020300c06082a864886f70d020505000410" + }, + "RSA-MD5": { + "sign": "rsa", + "hash": "md5", + "id": "3020300c06082a864886f70d020505000410" + } + } + + },{}],79:[function(require,module,exports){ + module.exports={ + "1.3.132.0.10": "secp256k1", + "1.3.132.0.33": "p224", + "1.2.840.10045.3.1.1": "p192", + "1.2.840.10045.3.1.7": "p256", + "1.3.132.0.34": "p384", + "1.3.132.0.35": "p521" + } + + },{}],80:[function(require,module,exports){ + (function (Buffer){ + var createHash = require('create-hash') + var stream = require('stream') + 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){ + // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js + var createHmac = require('create-hmac') + var crt = require('browserify-rsa') + var EC = require('elliptic').ec + 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) { + // rsa keys can be interpreted as ecdsa ones in openssl + if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type') + return ecSign(hash, priv) + } else if (priv.type === 'dsa') { + if (signType !== 'dsa') throw new Error('wrong private key type') + return dsaSign(hash, priv, hashType) + } else { + if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type') + } + hash = Buffer.concat([tag, hash]) + var len = priv.modulus.byteLength() + var pad = [ 0, 1 ] + while (hash.length + pad.length + 1 < len) pad.push(0xff) + 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 + var q = priv.params.q + var g = priv.params.g + var r = new BN(0) + var k + var H = bits2int(hash, q).mod(q) + var s = false + var kv = getKey(x, q, hash, algo) + while (s === false) { + k = makeKey(q, kv, algo) + r = makeR(g, k, p, q) + s = k.invm(q).imul(H.add(x.mul(r))).mod(q) + if (s.cmpn(0) === 0) { + s = false + r = new BN(0) + } + } + 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()) { + var zeros = new Buffer(q.byteLength() - x.length) + zeros.fill(0) + x = Buffer.concat([ zeros, x ]) + } + var hlen = hash.length + var hbits = bits2octets(hash, q) + var v = new Buffer(hlen) + v.fill(1) + var k = new Buffer(hlen) + k.fill(0) + k = createHmac(algo, k).update(v).update(new Buffer([ 0 ])).update(x).update(hbits).digest() + v = createHmac(algo, k).update(v).digest() + k = createHmac(algo, k).update(v).update(new Buffer([ 1 ])).update(x).update(hbits).digest() + 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) + var out = new Buffer(bits.toArray()) + if (out.length < q.byteLength()) { + var zeros = new Buffer(q.byteLength() - out.length) + zeros.fill(0) + out = Buffer.concat([ zeros, out ]) + } + 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){ + // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js + var BN = require('bn.js') + 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') { + // rsa keys can be interpreted as ecdsa ones in openssl + if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type') + return ecVerify(sig, hash, pub) + } else if (pub.type === 'dsa') { + if (signType !== 'dsa') throw new Error('wrong public key type') + return dsaVerify(sig, hash, pub) + } else { + if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type') + } + hash = Buffer.concat([tag, hash]) + var len = pub.modulus.byteLength() + var pad = [ 1 ] + var padNum = 0 + while (hash.length + pad.length + 2 < len) { + pad.push(0xff) + padNum++ + } + pad.push(0x00) + var i = -1 + while (++i < hash.length) { + pad.push(hash[i]) + } + 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 + var g = pub.data.g + var y = pub.data.pub_key + var unpacked = parseKeys.signature.decode(sig, 'der') + var s = unpacked.s + var r = unpacked.r + checkValue(s, q) + checkValue(r, q) + var montp = BN.mont(p) + var w = s.invm(q) + var v = g.toRed(montp) + .redPow(new BN(hash).mul(w).mod(q)) + .fromRed() + .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed()) + .mod(p) + .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){ + /*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + /* eslint-disable no-proto */ + + 'use strict' + + var base64 = require('base64-js') + var ieee754 = require('ieee754') + + exports.Buffer = Buffer + exports.SlowBuffer = SlowBuffer + exports.INSPECT_MAX_BYTES = 50 + + var K_MAX_LENGTH = 0x7fffffff + exports.kMaxLength = K_MAX_LENGTH + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ + Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + + if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) + } + + function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 + } catch (e) { + return false + } + } + + function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('Invalid typed array length') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length) + buf.__proto__ = Buffer.prototype + return buf + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) + } + + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true, + enumerable: false, + writable: false + }) + } + + Buffer.poolSize = 8192 // not used by this implementation + + function from (value, encodingOrOffset, length) { + if (typeof value === '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. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) + } + + // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: + // https://github.com/feross/buffer/pull/148 + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) + } + + function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) + } + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) + } + + function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"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) + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf + } + + function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is 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) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + buf.__proto__ = Buffer.prototype + return buf + } + + function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + var buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj) { + if (isArrayBufferView(obj) || 'length' in obj) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } + } + + 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.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 + } + + function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) + } + + Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true + } + + 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] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + } + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + } + + Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer + } + + function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (isArrayBufferView(string) || isArrayBuffer(string)) { + return string.byteLength + } + 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 (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } + } + Buffer.byteLength = byteLength + + function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } + } + + // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) + // to detect a Buffer instance. It's not possible to use `instanceof Buffer` + // reliably in a browserify context because there could be multiple different + // copies of the 'buffer' package in use. This method works even for Buffer + // instances that were created from another copy of the `buffer` package. + // See: https://github.com/feross/buffer/issues/154 + Buffer.prototype._isBuffer = true + + function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this + } + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this + } + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this + } + + Buffer.prototype.toString = function toString () { + var length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + } + + Buffer.prototype.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 + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + 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 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + } + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + } + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + } + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + } + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // 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 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } + } + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + } + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000 + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + newBuf.__proto__ = Buffer.prototype + return newBuf + } + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val + } + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val + } + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] + } + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) + } + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] + } + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + } + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + } + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val + } + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val + } + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + } + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val + } + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val + } + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + } + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + } + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) + } + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) + } + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) + } + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) + } + + function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 + } + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 + } + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 + } + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 + } + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 + } + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 + } + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 + } + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 + } + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + } + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + } + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + } + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + } + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('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) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } + + return len + } + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : new Buffer(val, encoding) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this + } + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray + } + + function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i + } + + // 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) { + return obj instanceof ArrayBuffer || + (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", + "101": "Switching Protocols", + "102": "Processing", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a teapot", + "421": "Misdirected Request", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Unordered Collection", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "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' + if (this.hashMode) { + this[hashMode] = this._finalOrDigest + } else { + this.final = this._finalOrDigest + } + if (this._final) { + this.__final = this._final + this._final = null + } + this._decoder = null + this._encoding = null + } + inherits(CipherBase, Transform) + + CipherBase.prototype.update = function (data, inputEnc, outputEnc) { + if (typeof data === 'string') { + data = Buffer.from(data, inputEnc) + } + + var outData = this._update(data) + if (this.hashMode) return this + + if (outputEnc) { + outData = this._toString(outData, outputEnc) + } + + return outData + } + + CipherBase.prototype.setAutoPadding = function () {} + CipherBase.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state') + } + + CipherBase.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state') + } + + CipherBase.prototype.setAAD = function () { + throw new Error('trying to set aad in unsupported state') + } + + CipherBase.prototype._transform = function (data, _, next) { + var err + try { + if (this.hashMode) { + this._update(data) + } else { + this.push(this._update(data)) + } + } catch (e) { + err = e + } finally { + next(err) + } + } + CipherBase.prototype._flush = function (done) { + var err + try { + this.push(this.__final()) + } catch (e) { + err = e + } + + done(err) + } + CipherBase.prototype._finalOrDigest = function (outputEnc) { + var outData = this.__final() || Buffer.alloc(0) + if (outputEnc) { + outData = this._toString(outData, outputEnc, true) + } + return outData + } + + CipherBase.prototype._toString = function (value, enc, fin) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc) + this._encoding = enc + } + + if (this._encoding !== enc) throw new Error('can\'t switch encodings') + + var out = this._decoder.write(value) + if (fin) { + out += this._decoder.end() + } + + return out + } + + module.exports = CipherBase + + },{"inherits":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; + } catch(_) { + // maybe a reference error because no `Map`. Give it a dummy value that no + // 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. + * + * This function supports circular references by default, but if you are certain + * there are no circular references in your object, you can save some CPU time + * by calling clone(obj, false). + * + * Caution: if `circular` is false and `parent` contains circular references, + * your program may enter an infinite loop and crash. + * + * @param `parent` - the object to be cloned + * @param `circular` - set to true if the object to be cloned may contain + * circular references. (optional - true by default) + * @param `depth` - set to a number if the object is only to be cloned to + * a particular depth. (optional - defaults to Infinity) + * @param `prototype` - sets the prototype to be used when cloning an object. + * (optional - defaults to parent prototype). + * @param `includeNonEnumerable` - set to true if the non-enumerable properties + * should be cloned as well. Non-enumerable properties on the prototype + * chain will be ignored. (optional - false by default) + */ + function clone(parent, circular, depth, prototype, includeNonEnumerable) { + if (typeof circular === 'object') { + depth = circular.depth; + prototype = circular.prototype; + includeNonEnumerable = circular.includeNonEnumerable; + circular = circular.circular; + } + // maintain two arrays for circular references, where corresponding parents + // 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)) { + child = new nativeSet(); + } else if (_instanceof(parent, nativePromise)) { + child = new nativePromise(function (resolve, reject) { + parent.then(function(value) { + resolve(_clone(value, depth - 1)); + }, function(err) { + reject(_clone(err, depth - 1)); + }); + }); + } else if (clone.__isArray(parent)) { + child = []; + } else if (clone.__isRegExp(parent)) { + child = new RegExp(parent.source, __getRegExpFlags(parent)); + if (parent.lastIndex) child.lastIndex = parent.lastIndex; + } else if (clone.__isDate(parent)) { + child = new Date(parent.getTime()); + } else if (useBuffer && Buffer.isBuffer(parent)) { + if (Buffer.allocUnsafe) { + // Node.js >= 4.5.0 + child = Buffer.allocUnsafe(parent.length); + } else { + // Older Node.js versions + child = new Buffer(parent.length); + } + parent.copy(child); + return child; + } else if (_instanceof(parent, Error)) { + child = Object.create(parent); + } else { + if (typeof prototype == 'undefined') { + proto = Object.getPrototypeOf(parent); + child = Object.create(proto); + } + else { + child = Object.create(prototype); + 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); + var valueChild = _clone(value, depth - 1); + child.set(keyChild, valueChild); + }); + } + if (_instanceof(parent, nativeSet)) { + parent.forEach(function(value) { + var entryChild = _clone(value, depth - 1); + 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++) { + // Don't need to worry about cloning a symbol because it is a primitive, + // like a number or string. + var symbol = symbols[i]; + var descriptor = Object.getOwnPropertyDescriptor(parent, symbol); + if (descriptor && !descriptor.enumerable && !includeNonEnumerable) { + continue; + } + child[symbol] = _clone(parent[symbol], depth - 1); + if (!descriptor.enumerable) { + Object.defineProperty(child, symbol, { + enumerable: false + }); + } + } + } + + if (includeNonEnumerable) { + var allPropertyNames = Object.getOwnPropertyNames(parent); + for (var i = 0; i < allPropertyNames.length; i++) { + var propertyName = allPropertyNames[i]; + var descriptor = Object.getOwnPropertyDescriptor(parent, propertyName); + if (descriptor && descriptor.enumerable) { + continue; + } + child[propertyName] = _clone(parent[propertyName], depth - 1); + Object.defineProperty(child, propertyName, { + enumerable: false + }); + } + } + + 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). + * + * USE WITH CAUTION! This may not behave as you wish if you do not know how this + * works. + */ + 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'; + if (re.ignoreCase) flags += 'i'; + if (re.multiline) flags += 'm'; + 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; + this.path = path || "/"; + this.secure = !!secure; + this.script = !!script; + return this; + } + return new CookieAccessInfo(domain, path, secure, script); + } + CookieAccessInfo.All = Object.freeze(Object.create(null)); + exports.CookieAccessInfo = CookieAccessInfo; + + function Cookie(cookiestr, request_domain, request_path) { + if (cookiestr instanceof Cookie) { + return cookiestr; + } + if (this instanceof Cookie) { + this.name = null; + this.value = null; + this.expiration_date = Infinity; + this.path = String(request_path || "/"); + this.explicit_path = false; + this.domain = request_domain || null; + this.explicit_domain = false; + this.secure = false; //how to define default? + this.noscript = false; //httponly + if (cookiestr) { + this.parse(cookiestr, request_domain, request_path); + } + return this; + } + 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) { + str.push("expires=" + (new Date(this.expiration_date)).toGMTString()); + } + if (this.domain) { + str.push("domain=" + this.domain); + } + if (this.path) { + str.push("path=" + this.path); + } + if (this.secure) { + str.push("secure"); + } + if (this.noscript) { + str.push("httponly"); + } + 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) { + var parts = str.split(";").filter(function (value) { + 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(); + value = pair[2]; + switch (key) { + case "httponly": + this.noscript = true; + break; + case "expires": + this.expiration_date = value ? + Number(Date.parse(value)) : + Infinity; + break; + case "path": + this.path = value ? + value.trim() : + ""; + this.explicit_path = true; + break; + case "domain": + this.domain = value ? + value.trim() : + ""; + this.explicit_domain = !!this.domain; + break; + case "secure": + this.secure = true; + 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; + } + if (this.noscript && access_info.script || + this.secure && !access_info.secure || + !this.collidesWith(access_info)) { + return false; + } + return true; + }; + + Cookie.prototype.collidesWith = function collidesWith(access_info) { + if ((this.path && !access_info.path) || (this.domain && !access_info.domain)) { + return false; + } + if (this.path && access_info.path.indexOf(this.path) !== 0) { + return false; + } + if (this.explicit_path && access_info.path.indexOf( this.path ) !== 0) { + return false; + } + var access_domain = access_info.domain && access_info.domain.replace(/^[\.]/,''); + var cookie_domain = this.domain && this.domain.replace(/^[\.]/,''); + if (cookie_domain === access_domain) { + return true; + } + if (cookie_domain) { + if (!this.explicit_domain) { + return false; // we already checked if the domains were exactly the same + } + var wildcard = access_domain.indexOf(cookie_domain); + if (wildcard === -1 || wildcard !== access_domain.length - cookie_domain.length) { + return false; + } + return true; + } + 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); + //Delete the cookie if the set is past the current time + remove = cookie.expiration_date <= Date.now(); + if (cookies[cookie.name] !== undefined) { + cookies_list = cookies[cookie.name]; + for (i = 0; i < cookies_list.length; i += 1) { + collidable_cookie = cookies_list[i]; + if (collidable_cookie.collidesWith(cookie)) { + if (remove) { + cookies_list.splice(i, 1); + if (cookies_list.length === 0) { + delete cookies[cookie.name]; + } + return false; + } + cookies_list[i] = cookie; + return cookie; + } + } + if (remove) { + return false; + } + cookies_list.push(cookie); + return cookie; + } + if (remove) { + return false; + } + cookies[cookie.name] = [cookie]; + return cookies[cookie.name]; + }; + //returns a cookie + this.getCookie = function getCookie(cookie_name, access_info) { + var cookie, i; + cookies_list = cookies[cookie_name]; + if (!cookies_list) { + return; + } + for (i = 0; i < cookies_list.length; i += 1) { + cookie = cookies_list[i]; + if (cookie.expiration_date <= Date.now()) { + if (cookies_list.length === 0) { + delete cookies[cookie.name]; + } + continue; + } + + if (cookie.matches(access_info)) { + return cookie; + } + } + }; + //returns a list of cookies + this.getCookies = function getCookies(access_info) { + var matches = [], cookie_name, cookie; + for (cookie_name in cookies) { + cookie = this.getCookie(cookie_name, access_info); + if (cookie) { + matches.push(cookie); + } + } + matches.toString = function toString() { + return matches.join(":"); + }; + matches.toValueString = function toValueString() { + return matches.map(function (c) { + return c.toValueString(); + }).join(';'); + }; + 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) ? + cookies : + cookies.split(cookie_str_splitter); + var successful = [], + i, + cookie; + cookies = cookies.map(function(item){ + return new Cookie(item, request_domain, request_path); + }); + for (i = 0; i < cookies.length; i += 1) { + cookie = cookies[i]; + if (this.setCookie(cookie, request_domain, request_path)) { + successful.push(cookie); + } + } + return successful; + }; + }()); + + },{}],89:[function(require,module,exports){ + (function (Buffer){ + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + + function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; + } + exports.isArray = isArray; + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + exports.isBoolean = isBoolean; + + function isNull(arg) { + return arg === null; + } + exports.isNull = isNull; + + function isNullOrUndefined(arg) { + return arg == null; + } + exports.isNullOrUndefined = isNullOrUndefined; + + function isNumber(arg) { + return typeof arg === 'number'; + } + exports.isNumber = isNumber; + + function isString(arg) { + return typeof arg === 'string'; + } + exports.isString = isString; + + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + exports.isSymbol = isSymbol; + + function isUndefined(arg) { + return arg === void 0; + } + exports.isUndefined = isUndefined; + + function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; + } + exports.isRegExp = isRegExp; + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + exports.isObject = isObject; + + function isDate(d) { + return objectToString(d) === '[object Date]'; + } + exports.isDate = isDate; + + function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); + } + exports.isError = isError; + + function isFunction(arg) { + return typeof arg === 'function'; + } + exports.isFunction = isFunction; + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + exports.isPrimitive = isPrimitive; + + exports.isBuffer = Buffer.isBuffer; + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) + },{"../../is-buffer/index.js":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', + byteLength: 32 + }, + secp224r1: { + name: 'p224', + byteLength: 28 + }, + prime256v1: { + name: 'p256', + byteLength: 32 + }, + prime192v1: { + name: 'p192', + byteLength: 24 + }, + ed25519: { + name: 'ed25519', + byteLength: 32 + }, + secp384r1: { + name: 'p384', + byteLength: 48 + }, + secp521r1: { + name: 'p521', + 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 ) { + this.curveType = { + name: curve + }; + } + 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)) { + other = new Buffer(other, inenc); + } + var otherPub = this.curve.keyFromPublic(other).getPublic(); + 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') { + if (key[key.length - 1] % 2) { + key[0] = 7; + } else { + key [0] = 6; + } + } + 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)) { + pub = new Buffer(pub, enc); + } + this.keys._importPublic(pub); + return this; + }; + + ECDH.prototype.setPrivateKey = function (priv, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(priv)) { + priv = new Buffer(priv, enc); + } + var _priv = new BN(priv); + _priv = _priv.toString(16); + this.keys._importPrivate(_priv); + return this; + }; + + function formatReturnValue(bn, enc, len) { + if (!Array.isArray(bn)) { + bn = bn.toArray(); + } + var buf = new Buffer(bn); + if (len && buf.length < len) { + var zeros = new Buffer(len - buf.length); + zeros.fill(0); + buf = Buffer.concat([zeros, buf]); + } + if (!enc) { + return buf; + } else { + return buf.toString(enc); + } + } + + }).call(this,require("buffer").Buffer) + },{"bn.js":53,"buffer":84,"elliptic":109}],91:[function(require,module,exports){ + (function (Buffer){ + 'use strict' + var inherits = require('inherits') + 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){ + 'use strict' + 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) + for (var i = 0; i < arr.length; i++) { + buf.writeInt32LE(arr[i], i << 2, true) + } + return buf + } + + }).call(this,require("buffer").Buffer) + },{"buffer":84}],93:[function(require,module,exports){ + 'use strict' + /* + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * 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 + */ + function core_md5 (x, len) { + /* 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) + b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330) + a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897) + d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426) + c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341) + b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983) + a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416) + d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417) + c = md5_ff(c, d, a, b, x[i + 10], 17, -42063) + b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162) + a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682) + 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) + b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302) + a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691) + d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083) + c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335) + b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848) + a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438) + d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690) + c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961) + b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501) + a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467) + 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) + b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556) + a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060) + d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353) + c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632) + b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640) + a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174) + d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222) + c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979) + b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189) + a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487) + 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) + b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055) + a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571) + d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606) + c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523) + b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799) + a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359) + d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744) + c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380) + b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649) + a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070) + 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. + */ + function safe_add (x, y) { + var lsw = (x & 0xFFFF) + (y & 0xFFFF) + 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') + var Legacy = require('./legacy') + var Base = require('cipher-base') + var Buffer = require('safe-buffer').Buffer + var md5 = require('create-hash/md5') + var RIPEMD160 = require('ripemd160') + + var sha = require('sha.js') + + var ZEROS = Buffer.alloc(128) + + function Hmac (alg, key) { + Base.call(this, 'digest') + if (typeof key === 'string') { + key = Buffer.from(key) + } + + var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 + + this._alg = alg + this._key = key + if (key.length > blocksize) { + var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) + key = hash.update(key).digest() + } else if (key.length < blocksize) { + key = Buffer.concat([key, ZEROS], blocksize) + } + + var ipad = this._ipad = Buffer.allocUnsafe(blocksize) + var opad = this._opad = Buffer.allocUnsafe(blocksize) + + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36 + opad[i] = key[i] ^ 0x5C + } + this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) + this._hash.update(ipad) + } + + inherits(Hmac, Base) + + Hmac.prototype._update = function (data) { + this._hash.update(data) + } + + Hmac.prototype._final = function () { + var h = this._hash.digest() + var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg) + return hash.update(this._opad).update(h).digest() + } + + module.exports = function createHmac (alg, key) { + alg = alg.toLowerCase() + if (alg === 'rmd160' || alg === 'ripemd160') { + return new Hmac('rmd160', key) + } + if (alg === 'md5') { + return new Legacy(md5, key) + } + return new Hmac(alg, key) + } + + },{"./legacy":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; } + F.prototype = root; + 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, + blob: 'FileReader' in self && 'Blob' in self && (function() { + try { + new Blob(); + return true + } catch(e) { + return false + } + })(), + formData: 'FormData' in self, + arrayBuffer: 'ArrayBuffer' in self + }; + + if (support.arrayBuffer) { + var viewClasses = [ + '[object Int8Array]', + '[object Uint8Array]', + '[object Uint8ClampedArray]', + '[object Int16Array]', + '[object Uint16Array]', + '[object Int32Array]', + '[object Uint32Array]', + '[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); + } + if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) { + throw new TypeError('Invalid character in header field name') + } + 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 = { + next: function() { + var value = items.shift(); + 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); + }, this); + } else if (Array.isArray(headers)) { + headers.forEach(function(header) { + this.append(header[0], header[1]); + }, this); + } else if (headers) { + Object.getOwnPropertyNames(headers).forEach(function(name) { + this.append(name, headers[name]); + }, 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)) { + callback.call(thisArg, this.map[name], name, this); + } + } + }; + + 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() { + resolve(reader.result); + }; + reader.onerror = function() { + reject(reader.error); + }; + }) + } + + 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) + } else { + var view = new Uint8Array(buf.byteLength); + view.set(new Uint8Array(buf)); + return view.buffer + } + } + + function Body() { + this.bodyUsed = false; + + this._initBody = function(body) { + this._bodyInit = body; + if (!body) { + this._bodyText = ''; + } else if (typeof body === 'string') { + this._bodyText = body; + } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { + this._bodyBlob = body; + } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { + this._bodyFormData = body; + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this._bodyText = body.toString(); + } else if (support.arrayBuffer && support.blob && isDataView(body)) { + this._bodyArrayBuffer = bufferClone(body.buffer); + // IE 10-11 can't handle a DataView body. + this._bodyInit = new Blob([this._bodyArrayBuffer]); + } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) { + this._bodyArrayBuffer = bufferClone(body); + } 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'); + } else if (this._bodyBlob && this._bodyBlob.type) { + this.headers.set('content-type', this._bodyBlob.type); + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); + } + } + }; + + 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) { + return Promise.resolve(new Blob([this._bodyArrayBuffer])) + } else if (this._bodyFormData) { + throw new Error('could not read FormData body as blob') + } else { + return Promise.resolve(new Blob([this._bodyText])) + } + }; + + this.arrayBuffer = function() { + if (this._bodyArrayBuffer) { + return consumed(this) || Promise.resolve(this._bodyArrayBuffer) + } else { + return this.blob().then(readBlobAsArrayBuffer) + } + }; + } + + this.text = function() { + var rejected = consumed(this); + if (rejected) { + return rejected + } + + if (this._bodyBlob) { + return readBlobAsText(this._bodyBlob) + } else if (this._bodyArrayBuffer) { + return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer)) + } else if (this._bodyFormData) { + throw new Error('could not read FormData body as text') + } else { + 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') + } + this.url = input.url; + this.credentials = input.credentials; + if (!options.headers) { + this.headers = new Headers(input.headers); + } + this.method = input.method; + this.mode = input.mode; + if (!body && input._bodyInit != null) { + body = input._bodyInit; + input.bodyUsed = true; + } + } else { + this.url = String(input); + } + + this.credentials = options.credentials || this.credentials || 'omit'; + if (options.headers || !this.headers) { + this.headers = new Headers(options.headers); + } + 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) { + if (bytes) { + var split = bytes.split('='); + var name = split.shift().replace(/\+/g, ' '); + var value = split.join('=').replace(/\+/g, ' '); + form.append(decodeURIComponent(name), decodeURIComponent(value)); + } + }); + 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 + // https://tools.ietf.org/html/rfc7230#section-3.2 + var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' '); + preProcessedHeaders.split(/\r?\n/).forEach(function(line) { + var parts = line.split(':'); + var key = parts.shift().trim(); + if (key) { + var value = parts.join(':').trim(); + headers.append(key, value); + } + }); + 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; + this.statusText = 'statusText' in options ? options.statusText : 'OK'; + this.headers = new Headers(options.headers); + this.url = options.url || ''; + this._initBody(bodyInit); + } + + Body.call(Response.prototype); + + Response.prototype.clone = function() { + return new Response(this._bodyInit, { + status: this.status, + statusText: this.statusText, + headers: new Headers(this.headers), + 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, + statusText: xhr.statusText, + headers: parseHeaders(xhr.getAllResponseHeaders() || '') + }; + options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL'); + 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); + }) + }; + self.fetch.polyfill = true; + })(typeof self !== 'undefined' ? self : this); + }).call(__root__, void(0)); + var fetch = __root__.fetch; + var Response = fetch.Response = __root__.Response; + var Request = fetch.Request = __root__.Request; + var Headers = fetch.Headers = __root__.Headers; + if (typeof module === 'object' && module.exports) { + module.exports = fetch; + // 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 + exports.createCipheriv = aes.createCipheriv + exports.Decipher = aes.Decipher + exports.createDecipher = aes.createDecipher + exports.Decipheriv = aes.Decipheriv + 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' + // ].forEach(function (name) { + // exports[name] = function () { + // throw new Error([ + // 'sorry, ' + name + ' is not implemented yet', + // 'we accept pull requests', + // 'https://github.com/crypto-browserify/crypto-browserify' + // ].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', + 'we accept pull requests', + 'https://github.com/crypto-browserify/crypto-browserify' + ].join('\n')) + } + + exports.constants = { + 'DH_CHECK_P_NOT_SAFE_PRIME': 2, + 'DH_CHECK_P_NOT_PRIME': 1, + 'DH_UNABLE_TO_CHECK_GENERATOR': 4, + 'DH_NOT_SUITABLE_GENERATOR': 8, + 'NPN_ENABLED': 1, + 'ALPN_ENABLED': 1, + 'RSA_PKCS1_PADDING': 1, + 'RSA_SSLV23_PADDING': 2, + 'RSA_NO_PADDING': 3, + 'RSA_PKCS1_OAEP_PADDING': 4, + 'RSA_X931_PADDING': 5, + 'RSA_PKCS1_PSS_PADDING': 6, + 'POINT_CONVERSION_COMPRESSED': 2, + '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 + return decodeURIComponent(components.join('')); + } catch (err) { + // Do nothing + } + + if (components.length === 1) { + return components; + } + + split = split || 1; + + // Split the array in 2 parts + var left = components.slice(0, split); + var right = components.slice(split); + + return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right)); + } + + function decode(input) { + try { + return decodeURIComponent(input); + } catch (err) { + var tokens = input.match(singleMatcher); + + for (var i = 1; i < tokens.length; i++) { + input = decodeComponents(tokens, i).join(''); + + tokens = input.match(singleMatcher); + } + + return input; + } + } + + function customDecodeURIComponent(input) { + // Keep track of all the replacements and prefill the map with the `BOM` + var replaceMap = { + '%FE%FF': '\uFFFD\uFFFD', + '%FF%FE': '\uFFFD\uFFFD' + }; + + var match = multiMatcher.exec(input); + while (match) { + try { + // Decode as big chunks as possible + replaceMap[match[0]] = decodeURIComponent(match[0]); + } catch (err) { + var result = decode(match[0]); + + if (result !== match[0]) { + replaceMap[match[0]] = result; + } + } + + match = multiMatcher.exec(input); + } + + // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else + replaceMap['%C2'] = '\uFFFD'; + + var entries = Object.keys(replaceMap); + + for (var i = 0; i < entries.length; i++) { + // Replace all decoded components + var key = entries[i]; + input = input.replace(new RegExp(key, 'g'), replaceMap[key]); + } + + return input; + } + + module.exports = function (encodedURI) { + if (typeof encodedURI !== 'string') { + throw new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`'); + } + + try { + encodedURI = encodedURI.replace(/\+/g, ' '); + + // Try the built in decoder first + return decodeURIComponent(encodedURI); + } catch (err) { + // Fallback to a more advanced decoder + return customDecodeURIComponent(encodedURI); + } + }; + + },{}],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]; + for (var i = 0; i < state.keys.length; i += 2) { + var shift = shiftTable[i >>> 1]; + kL = utils.r28shl(kL, shift); + kR = utils.r28shl(kR, shift); + 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 }), + DES.create({ type: 'decrypt', key: k2 }), + DES.create({ type: 'encrypt', key: k3 }) + ]; + } else { + this.ciphers = [ + DES.create({ type: 'decrypt', key: k3 }), + DES.create({ type: 'encrypt', key: k2 }), + DES.create({ type: 'decrypt', key: k1 }) + ]; + } + } + + 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) | + (bytes[2 + off] << 8) | + 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; + outL |= (inR >>> (j + i)) & 1; + } + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inL >>> (j + i)) & 1; + } + } + + for (var i = 6; i >= 0; i -= 2) { + for (var j = 1; j <= 25; j += 8) { + outR <<= 1; + outR |= (inR >>> (j + i)) & 1; + } + for (var j = 1; j <= 25; j += 8) { + outR <<= 1; + 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; + outL |= (inR >>> (j + i)) & 1; + outL <<= 1; + outL |= (inL >>> (j + i)) & 1; + } + } + for (var i = 4; i < 8; i++) { + for (var j = 24; j >= 0; j -= 8) { + outR <<= 1; + outR |= (inR >>> (j + i)) & 1; + outR <<= 1; + 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 + // 4, 12, 20, 28 + for (var i = 7; i >= 5; i--) { + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inR >> (j + i)) & 1; + } + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inL >> (j + i)) & 1; + } + } + for (var j = 0; j <= 24; j += 8) { + 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 + // 36, 44, 52, 60 + for (var i = 1; i <= 3; i++) { + for (var j = 0; j <= 24; j += 8) { + outR <<= 1; + outR |= (inR >> (j + i)) & 1; + } + for (var j = 0; j <= 24; j += 8) { + outR <<= 1; + outR |= (inL >> (j + i)) & 1; + } + } + for (var j = 0; j <= 24; j += 8) { + 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; + outL |= (inL >>> pc2table[i]) & 0x1; + } + for (var i = len; i < pc2table.length; i++) { + 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; + outL |= (r >>> i) & 0x3f; + } + for (var i = 11; i >= 3; i -= 4) { + outR |= (r >>> i) & 0x3f; + 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++) { + out <<= 1; + out |= (num >>> permuteTable[i]) & 0x1; + } + 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){ + var BN = require('bn.js'); + var MillerRabin = require('miller-rabin'); + var millerRabin = new MillerRabin(); + var TWENTYFOUR = new BN(24); + var ELEVEN = new BN(11); + var TEN = new BN(10); + var THREE = new BN(3); + var SEVEN = new BN(7); + var primes = require('./generatePrime'); + var randomBytes = require('randombytes'); + module.exports = DH; + + function setPublicKey(pub, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(pub)) { + pub = new Buffer(pub, enc); + } + this._pub = new BN(pub); + return this; + } + + function setPrivateKey(priv, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(priv)) { + priv = new Buffer(priv, enc); + } + this._priv = new BN(priv); + return this; + } + + var primeCache = {}; + function checkPrime(prime, generator) { + var gen = generator.toString('hex'); + var hex = [gen, prime.toString(16)].join('_'); + if (hex in primeCache) { + 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 + error += 8; + } else { + //we wouldn't be able to test the generator + // so +4 + error += 4; + } + primeCache[hex] = error; + return error; + } + if (!millerRabin.test(prime.shrn(1))) { + //not a safe prime + error += 2; + } + var rem; + switch (gen) { + case '02': + if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) { + // unsuidable generator + error += 8; + } + break; + case '05': + rem = prime.mod(TEN); + if (rem.cmp(THREE) && rem.cmp(SEVEN)) { + // prime mod 10 needs to equal 3 or 7 + error += 8; + } + break; + default: + error += 4; + } + primeCache[hex] = error; + return error; + } + + function DH(prime, generator, malleable) { + this.setGenerator(generator); + this.__prime = new BN(prime); + this._prime = BN.mont(this.__prime); + this._primeLen = prime.length; + this._pub = undefined; + this._priv = undefined; + this._primeCode = undefined; + if (malleable) { + this.setPublicKey = setPublicKey; + this.setPrivateKey = setPrivateKey; + } else { + this._primeCode = 8; + } + } + Object.defineProperty(DH.prototype, 'verifyError', { + enumerable: true, + get: function () { + if (typeof this._primeCode !== 'number') { + this._primeCode = checkPrime(this.__prime, this.__gen); + } + return this._primeCode; + } + }); + DH.prototype.generateKeys = function () { + if (!this._priv) { + this._priv = new BN(randomBytes(this._primeLen)); + } + 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); + var secret = other.redPow(this._priv).fromRed(); + var out = new Buffer(secret.toArray()); + var prime = this.getPrime(); + if (out.length < prime.length) { + var front = new Buffer(prime.length - out.length); + front.fill(0); + out = Buffer.concat([front, out]); + } + 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)) { + gen = new Buffer(gen, enc); + } + this.__gen = gen; + this._gen = new BN(gen); + return this; + }; + + function formatReturnValue(bn, enc) { + var buf = new Buffer(bn.toArray()); + if (!enc) { + return buf; + } else { + 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'); + module.exports = findPrime; + findPrime.simpleSieve = simpleSieve; + findPrime.fermatTest = fermatTest; + var BN = require('bn.js'); + var TWENTYFOUR = new BN(24); + var MillerRabin = require('miller-rabin'); + var millerRabin = new MillerRabin(); + var ONE = new BN(1); + var TWO = new BN(2); + var FIVE = new BN(5); + var SIXTEEN = new BN(16); + var EIGHT = new BN(8); + var TEN = new BN(10); + var THREE = new BN(3); + var SEVEN = new BN(7); + var ELEVEN = new BN(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; + for (var i = 1, k = 3; k < limit; k += 2) { + var sqrt = Math.ceil(Math.sqrt(k)); + 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) { + return true; + } else { + 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 + if (gen === 2 || gen === 5) { + return new BN([0x8c, 0x7b]); + } else { + return new BN([0x8c, 0x27]); + } + } + gen = new BN(gen); + + var num, n2; + + while (true) { + num = new BN(randomBytes(Math.ceil(bits / 8))); + while (num.bitLength() > bits) { + num.ishrn(1); + } + if (num.isEven()) { + num.iadd(ONE); + } + if (!num.testn(1)) { + num.iadd(TWO); + } + if (!gen.cmp(TWO)) { + while (num.mod(TWENTYFOUR).cmp(ELEVEN)) { + num.iadd(FOUR); + } + } else if (!gen.cmp(FIVE)) { + while (num.mod(TEN).cmp(THREE)) { + num.iadd(FOUR); + } + } + n2 = num.shrn(1); + if (simpleSieve(n2) && simpleSieve(num) && + fermatTest(n2) && fermatTest(num) && + millerRabin.test(n2) && millerRabin.test(num)) { + return num; + } + } + + } + + },{"bn.js":53,"miller-rabin":233,"randombytes":270}],108:[function(require,module,exports){ + module.exports={ + "modp1": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff" + }, + "modp2": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff" + }, + "modp5": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff" + }, + "modp14": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff" + }, + "modp15": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff" + }, + "modp16": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff" + }, + "modp17": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff" + }, + "modp18": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff" + } + } + },{}],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) { + this.redN = null; + } else { + this._maxwellTrick = true; + this.redN = this.n.toRed(this.red); + } + } + module.exports = BaseCurve; + + BaseCurve.prototype.point = function point() { + throw new Error('Not implemented'); + }; + + BaseCurve.prototype.validate = function validate() { + throw new Error('Not implemented'); + }; + + BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { + assert(p.precomputed); + var doubles = p._getDoubles(); + + var naf = getNAF(k, 1); + var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); + I /= 3; + + // Translate into more windowed form + var repr = []; + for (var j = 0; j < naf.length; j += doubles.step) { + var nafW = 0; + for (var k = j + doubles.step - 1; k >= j; k--) + nafW = (nafW << 1) + naf[k]; + repr.push(nafW); + } + + var a = this.jpoint(null, null, null); + var b = this.jpoint(null, null, null); + for (var i = I; i > 0; i--) { + for (var j = 0; j < repr.length; j++) { + var nafW = repr[j]; + if (nafW === i) + b = b.mixedAdd(doubles.points[j]); + else if (nafW === -i) + b = b.mixedAdd(doubles.points[j].neg()); + } + a = a.add(b); + } + return a.toP(); + }; + + BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { + var w = 4; + + // Precompute window + var nafPoints = p._getNAFPoints(w); + w = nafPoints.wnd; + var wnd = nafPoints.points; + + // Get NAF form + var naf = getNAF(k, w); + + // Add `this`*(N+1) for every w-NAF index + var acc = this.jpoint(null, null, null); + for (var i = naf.length - 1; i >= 0; i--) { + // Count zeroes + for (var k = 0; i >= 0 && naf[i] === 0; i--) + k++; + if (i >= 0) + k++; + acc = acc.dblp(k); + + if (i < 0) + break; + var z = naf[i]; + assert(z !== 0); + if (p.type === 'affine') { + // J +- P + if (z > 0) + acc = acc.mixedAdd(wnd[(z - 1) >> 1]); + else + acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); + } else { + // J +- J + if (z > 0) + acc = acc.add(wnd[(z - 1) >> 1]); + else + acc = acc.add(wnd[(-z - 1) >> 1].neg()); + } + } + return p.type === 'affine' ? acc.toP() : acc; + }; + + BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, + points, + coeffs, + len, + jacobianResult) { + var wndWidth = this._wnafT1; + var wnd = this._wnafT2; + var naf = this._wnafT3; + + // Fill all arrays + var max = 0; + for (var i = 0; i < len; i++) { + var p = points[i]; + var nafPoints = p._getNAFPoints(defW); + wndWidth[i] = nafPoints.wnd; + wnd[i] = nafPoints.points; + } + + // Comb small window NAFs + for (var i = len - 1; i >= 1; i -= 2) { + var a = i - 1; + var b = i; + if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { + naf[a] = getNAF(coeffs[a], wndWidth[a]); + naf[b] = getNAF(coeffs[b], wndWidth[b]); + max = Math.max(naf[a].length, max); + max = Math.max(naf[b].length, max); + continue; + } + + var comb = [ + points[a], /* 1 */ + null, /* 3 */ + null, /* 5 */ + points[b] /* 7 */ + ]; + + // Try to avoid Projective points, if possible + if (points[a].y.cmp(points[b].y) === 0) { + comb[1] = points[a].add(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].add(points[b].neg()); + } else { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } + + var index = [ + -3, /* -1 -1 */ + -1, /* -1 0 */ + -5, /* -1 1 */ + -7, /* 0 -1 */ + 0, /* 0 0 */ + 7, /* 0 1 */ + 5, /* 1 -1 */ + 1, /* 1 0 */ + 3 /* 1 1 */ + ]; + + var jsf = getJSF(coeffs[a], coeffs[b]); + max = Math.max(jsf[0].length, max); + naf[a] = new Array(max); + naf[b] = new Array(max); + for (var j = 0; j < max; j++) { + var ja = jsf[0][j] | 0; + var jb = jsf[1][j] | 0; + + naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; + naf[b][j] = 0; + wnd[a] = comb; + } + } + + var acc = this.jpoint(null, null, null); + var tmp = this._wnafT4; + for (var i = max; i >= 0; i--) { + var k = 0; + + while (i >= 0) { + var zero = true; + for (var j = 0; j < len; j++) { + tmp[j] = naf[j][i] | 0; + if (tmp[j] !== 0) + zero = false; + } + if (!zero) + break; + k++; + i--; + } + if (i >= 0) + k++; + acc = acc.dblp(k); + if (i < 0) + break; + + for (var j = 0; j < len; j++) { + var z = tmp[j]; + var p; + if (z === 0) + continue; + else if (z > 0) + p = wnd[j][(z - 1) >> 1]; + else if (z < 0) + p = wnd[j][(-z - 1) >> 1].neg(); + + if (p.type === 'affine') + acc = acc.mixedAdd(p); + else + acc = acc.add(p); + } + } + // Zeroify references + for (var i = 0; i < len; i++) + wnd[i] = null; + + if (jacobianResult) + return acc; + else + return acc.toP(); + }; + + function BasePoint(curve, type) { + this.curve = curve; + this.type = type; + this.precomputed = null; + } + BaseCurve.BasePoint = BasePoint; + + BasePoint.prototype.eq = function eq(/*other*/) { + throw new Error('Not implemented'); + }; + + BasePoint.prototype.validate = function validate() { + return this.curve.validate(this); + }; + + BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + bytes = utils.toArray(bytes, enc); + + var len = this.p.byteLength(); + + // uncompressed, hybrid-odd, hybrid-even + if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) && + bytes.length - 1 === 2 * len) { + if (bytes[0] === 0x06) + assert(bytes[bytes.length - 1] % 2 === 0); + else if (bytes[0] === 0x07) + assert(bytes[bytes.length - 1] % 2 === 1); + + var res = this.point(bytes.slice(1, 1 + len), + bytes.slice(1 + len, 1 + 2 * len)); + + return res; + } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && + bytes.length - 1 === len) { + return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03); + } + throw new Error('Unknown point format'); + }; + + BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { + return this.encode(enc, true); + }; + + BasePoint.prototype._encode = function _encode(compact) { + var len = this.curve.p.byteLength(); + var x = this.getX().toArray('be', len); + + if (compact) + return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); + + return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ; + }; + + BasePoint.prototype.encode = function encode(enc, compact) { + return utils.encode(this._encode(compact), enc); + }; + + BasePoint.prototype.precompute = function precompute(power) { + if (this.precomputed) + return this; + + var precomputed = { + doubles: null, + naf: null, + beta: null + }; + precomputed.naf = this._getNAFPoints(8); + precomputed.doubles = this._getDoubles(4, power); + precomputed.beta = this._getBeta(); + this.precomputed = precomputed; + + return this; + }; + + BasePoint.prototype._hasDoubles = function _hasDoubles(k) { + if (!this.precomputed) + return false; + + var doubles = this.precomputed.doubles; + if (!doubles) + return false; + + return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); + }; + + BasePoint.prototype._getDoubles = function _getDoubles(step, power) { + if (this.precomputed && this.precomputed.doubles) + return this.precomputed.doubles; + + var doubles = [ this ]; + var acc = this; + for (var i = 0; i < power; i += step) { + for (var j = 0; j < step; j++) + acc = acc.dbl(); + doubles.push(acc); + } + return { + step: step, + points: doubles + }; + }; + + BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { + if (this.precomputed && this.precomputed.naf) + return this.precomputed.naf; + + var res = [ this ]; + var max = (1 << wnd) - 1; + var dbl = max === 1 ? null : this.dbl(); + for (var i = 1; i < max; i++) + res[i] = res[i - 1].add(dbl); + return { + wnd: wnd, + points: res + }; + }; + + BasePoint.prototype._getBeta = function _getBeta() { + return null; + }; + + BasePoint.prototype.dblp = function dblp(k) { + var r = this; + for (var i = 0; i < k; i++) + r = r.dbl(); + return r; + }; + + },{"../../elliptic":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) { + this.x = this.curve.zero; + this.y = this.curve.one; + this.z = this.curve.one; + this.t = this.curve.zero; + this.zOne = true; + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + this.z = z ? new BN(z, 16) : this.curve.one; + this.t = t && new BN(t, 16); + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + if (this.t && !this.t.red) + this.t = this.t.toRed(this.curve.red); + this.zOne = this.z === this.curve.one; + + // Use extended coordinates + if (this.curve.extended && !this.t) { + this.t = this.x.redMul(this.y); + if (!this.zOne) + this.t = this.t.redMul(this.z.redInvm()); + } + } + } + inherits(Point, Base.BasePoint); + + EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); + }; + + EdwardsCurve.prototype.point = function point(x, y, z, t) { + return new Point(this, x, y, z, t); + }; + + Point.fromJSON = function fromJSON(curve, obj) { + return new Point(curve, obj[0], obj[1], obj[2]); + }; + + Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; + + Point.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.x.cmpn(0) === 0 && + this.y.cmp(this.z) === 0; + }; + + Point.prototype._extDbl = function _extDbl() { + // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html + // #doubling-dbl-2008-hwcd + // 4M + 4S + + // A = X1^2 + var a = this.x.redSqr(); + // B = Y1^2 + var b = this.y.redSqr(); + // C = 2 * Z1^2 + var c = this.z.redSqr(); + c = c.redIAdd(c); + // D = a * A + var d = this.curve._mulA(a); + // E = (X1 + Y1)^2 - A - B + var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); + // G = D + B + var g = d.redAdd(b); + // F = G - C + var f = g.redSub(c); + // H = D - B + var h = d.redSub(b); + // X3 = E * F + var nx = e.redMul(f); + // Y3 = G * H + var ny = g.redMul(h); + // T3 = E * H + var nt = e.redMul(h); + // Z3 = F * G + var nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); + }; + + Point.prototype._projDbl = function _projDbl() { + // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html + // #doubling-dbl-2008-bbjlp + // #doubling-dbl-2007-bl + // and others + // Generally 3M + 4S or 2M + 4S + + // B = (X1 + Y1)^2 + var b = this.x.redAdd(this.y).redSqr(); + // C = X1^2 + var c = this.x.redSqr(); + // D = Y1^2 + var d = this.y.redSqr(); + + var nx; + var ny; + var nz; + if (this.curve.twisted) { + // E = a * C + var e = this.curve._mulA(c); + // F = E + D + var f = e.redAdd(d); + if (this.zOne) { + // X3 = (B - C - D) * (F - 2) + nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); + // Y3 = F * (E - D) + ny = f.redMul(e.redSub(d)); + // Z3 = F^2 - 2 * F + nz = f.redSqr().redSub(f).redSub(f); + } else { + // H = Z1^2 + var h = this.z.redSqr(); + // J = F - 2 * H + var j = f.redSub(h).redISub(h); + // X3 = (B-C-D)*J + nx = b.redSub(c).redISub(d).redMul(j); + // Y3 = F * (E - D) + ny = f.redMul(e.redSub(d)); + // Z3 = F * J + nz = f.redMul(j); + } + } else { + // E = C + D + var e = c.redAdd(d); + // H = (c * Z1)^2 + var h = this.curve._mulC(this.c.redMul(this.z)).redSqr(); + // J = E - 2 * H + var j = e.redSub(h).redSub(h); + // X3 = c * (B - E) * J + nx = this.curve._mulC(b.redISub(e)).redMul(j); + // Y3 = c * E * (C - D) + ny = this.curve._mulC(e).redMul(c.redISub(d)); + // Z3 = E * J + nz = e.redMul(j); + } + return this.curve.point(nx, ny, nz); + }; + + Point.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + + // Double in extended coordinates + if (this.curve.extended) + return this._extDbl(); + else + return this._projDbl(); + }; + + Point.prototype._extAdd = function _extAdd(p) { + // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html + // #addition-add-2008-hwcd-3 + // 8M + + // A = (Y1 - X1) * (Y2 - X2) + var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); + // B = (Y1 + X1) * (Y2 + X2) + var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); + // C = T1 * k * T2 + var c = this.t.redMul(this.curve.dd).redMul(p.t); + // D = Z1 * 2 * Z2 + var d = this.z.redMul(p.z.redAdd(p.z)); + // E = B - A + var e = b.redSub(a); + // F = D - C + var f = d.redSub(c); + // G = D + C + var g = d.redAdd(c); + // H = B + A + var h = b.redAdd(a); + // X3 = E * F + var nx = e.redMul(f); + // Y3 = G * H + var ny = g.redMul(h); + // T3 = E * H + var nt = e.redMul(h); + // Z3 = F * G + var nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); + }; + + Point.prototype._projAdd = function _projAdd(p) { + // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html + // #addition-add-2008-bbjlp + // #addition-add-2007-bl + // 10M + 1S + + // A = Z1 * Z2 + var a = this.z.redMul(p.z); + // B = A^2 + var b = a.redSqr(); + // C = X1 * X2 + var c = this.x.redMul(p.x); + // D = Y1 * Y2 + var d = this.y.redMul(p.y); + // E = d * C * D + var e = this.curve.d.redMul(c).redMul(d); + // F = B - E + var f = b.redSub(e); + // G = B + E + var g = b.redAdd(e); + // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) + var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); + var nx = a.redMul(f).redMul(tmp); + var ny; + var nz; + if (this.curve.twisted) { + // Y3 = A * G * (D - a * C) + ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); + // Z3 = F * G + nz = f.redMul(g); + } else { + // Y3 = A * G * (D - C) + ny = a.redMul(g).redMul(d.redSub(c)); + // Z3 = c * F * G + nz = this.curve._mulC(f).redMul(g); + } + return this.curve.point(nx, ny, nz); + }; + + Point.prototype.add = function add(p) { + if (this.isInfinity()) + return p; + if (p.isInfinity()) + return this; + + if (this.curve.extended) + return this._extAdd(p); + else + return this._projAdd(p); + }; + + Point.prototype.mul = function mul(k) { + if (this._hasDoubles(k)) + return this.curve._fixedNafMul(this, k); + else + return this.curve._wnafMul(this, k); + }; + + Point.prototype.mulAdd = function mulAdd(k1, p, k2) { + return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); + }; + + Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) { + return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); + }; + + Point.prototype.normalize = function normalize() { + if (this.zOne) + return this; + + // Normalize coordinates + var zi = this.z.redInvm(); + this.x = this.x.redMul(zi); + this.y = this.y.redMul(zi); + if (this.t) + this.t = this.t.redMul(zi); + this.z = this.curve.one; + this.zOne = true; + return this; + }; + + Point.prototype.neg = function neg() { + return this.curve.point(this.x.redNeg(), + this.y, + this.z, + this.t && this.t.redNeg()); + }; + + Point.prototype.getX = function getX() { + this.normalize(); + return this.x.fromRed(); + }; + + Point.prototype.getY = function getY() { + this.normalize(); + return this.y.fromRed(); + }; + + Point.prototype.eq = function eq(other) { + return this === other || + this.getX().cmp(other.getX()) === 0 && + this.getY().cmp(other.getY()) === 0; + }; + + Point.prototype.eqXToP = function eqXToP(x) { + var rx = x.toRed(this.curve.red).redMul(this.z); + if (this.x.cmp(rx) === 0) + return true; + + var xc = x.clone(); + var t = this.curve.redN.redMul(this.z); + for (;;) { + xc.iadd(this.curve.n); + if (xc.cmp(this.curve.p) >= 0) + return false; + + rx.redIAdd(t); + if (this.x.cmp(rx) === 0) + return true; + } + 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(); + this.two = new BN(2).toRed(this.red); + this.a24 = this.i4.redMul(this.a.redAdd(this.two)); + } + inherits(MontCurve, Base); + module.exports = MontCurve; + + MontCurve.prototype.validate = function validate(point) { + var x = point.normalize().x; + var x2 = x.redSqr(); + var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); + var y = rhs.redSqrt(); + + return y.redSqr().cmp(rhs) === 0; + }; + + function Point(curve, x, z) { + Base.BasePoint.call(this, curve, 'projective'); + if (x === null && z === null) { + this.x = this.curve.one; + this.z = this.curve.zero; + } else { + this.x = new BN(x, 16); + this.z = new BN(z, 16); + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + } + } + inherits(Point, Base.BasePoint); + + MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + return this.point(utils.toArray(bytes, enc), 1); + }; + + MontCurve.prototype.point = function point(x, z) { + return new Point(this, x, z); + }; + + MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); + }; + + Point.prototype.precompute = function precompute() { + // No-op + }; + + Point.prototype._encode = function _encode() { + return this.getX().toArray('be', this.curve.p.byteLength()); + }; + + Point.fromJSON = function fromJSON(curve, obj) { + return new Point(curve, obj[0], obj[1] || curve.one); + }; + + Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; + + Point.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; + }; + + Point.prototype.dbl = function dbl() { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 + // 2M + 2S + 4A + + // A = X1 + Z1 + var a = this.x.redAdd(this.z); + // AA = A^2 + var aa = a.redSqr(); + // B = X1 - Z1 + var b = this.x.redSub(this.z); + // BB = B^2 + var bb = b.redSqr(); + // C = AA - BB + var c = aa.redSub(bb); + // X3 = AA * BB + var nx = aa.redMul(bb); + // Z3 = C * (BB + A24 * C) + var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); + return this.curve.point(nx, nz); + }; + + Point.prototype.add = function add() { + throw new Error('Not supported on Montgomery curve'); + }; + + Point.prototype.diffAdd = function diffAdd(p, diff) { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 + // 4M + 2S + 6A + + // A = X2 + Z2 + var a = this.x.redAdd(this.z); + // B = X2 - Z2 + var b = this.x.redSub(this.z); + // C = X3 + Z3 + var c = p.x.redAdd(p.z); + // D = X3 - Z3 + var d = p.x.redSub(p.z); + // DA = D * A + var da = d.redMul(a); + // CB = C * B + var cb = c.redMul(b); + // X5 = Z1 * (DA + CB)^2 + var nx = diff.z.redMul(da.redAdd(cb).redSqr()); + // Z5 = X1 * (DA - CB)^2 + var nz = diff.x.redMul(da.redISub(cb).redSqr()); + return this.curve.point(nx, nz); + }; + + Point.prototype.mul = function mul(k) { + var t = k.clone(); + var a = this; // (N / 2) * Q + Q + var b = this.curve.point(null, null); // (N / 2) * Q + var c = this; // Q + + for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) + bits.push(t.andln(1)); + + for (var i = bits.length - 1; i >= 0; i--) { + if (bits[i] === 0) { + // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q + a = a.diffAdd(b, c); + // N * Q = 2 * ((N / 2) * Q + Q)) + b = b.dbl(); + } else { + // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) + b = a.diffAdd(b, c); + // N * Q + Q = 2 * ((N / 2) * Q + Q) + a = a.dbl(); + } + } + return b; + }; + + Point.prototype.mulAdd = function mulAdd() { + throw new Error('Not supported on Montgomery curve'); + }; + + Point.prototype.jumlAdd = function jumlAdd() { + throw new Error('Not supported on Montgomery curve'); + }; + + Point.prototype.eq = function eq(other) { + return this.getX().cmp(other.getX()) === 0; + }; + + Point.prototype.normalize = function normalize() { + this.x = this.x.redMul(this.z.redInvm()); + this.z = this.curve.one; + return this; + }; + + Point.prototype.getX = function getX() { + // Normalize coordinates + this.normalize(); + + return this.x.fromRed(); + }; + + },{"../../elliptic":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); + this._endoWnafT2 = new Array(4); + } + inherits(ShortCurve, Base); + module.exports = ShortCurve; + + ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { + // No efficient endomorphism + if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) + return; + + // Compute beta and lambda, that lambda * P = (beta * Px; Py) + var beta; + var lambda; + if (conf.beta) { + beta = new BN(conf.beta, 16).toRed(this.red); + } else { + var betas = this._getEndoRoots(this.p); + // Choose the smallest beta + beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; + beta = beta.toRed(this.red); + } + if (conf.lambda) { + lambda = new BN(conf.lambda, 16); + } else { + // Choose the lambda that is matching selected beta + var lambdas = this._getEndoRoots(this.n); + if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { + lambda = lambdas[0]; + } else { + lambda = lambdas[1]; + assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); + } + } + + // Get basis vectors, used for balanced length-two representation + var basis; + if (conf.basis) { + basis = conf.basis.map(function(vec) { + return { + a: new BN(vec.a, 16), + b: new BN(vec.b, 16) + }; + }); + } else { + basis = this._getEndoBasis(lambda); + } + + return { + beta: beta, + lambda: lambda, + basis: basis + }; + }; + + ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { + // Find roots of for x^2 + x + 1 in F + // Root = (-1 +- Sqrt(-3)) / 2 + // + var red = num === this.p ? this.red : BN.mont(num); + var tinv = new BN(2).toRed(red).redInvm(); + var ntinv = tinv.redNeg(); + + var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv); + + var l1 = ntinv.redAdd(s).fromRed(); + var l2 = ntinv.redSub(s).fromRed(); + return [ l1, l2 ]; + }; + + ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { + // aprxSqrt >= sqrt(this.n) + var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); + + // 3.74 + // Run EGCD, until r(L + 1) < aprxSqrt + var u = lambda; + var v = this.n.clone(); + var x1 = new BN(1); + var y1 = new BN(0); + var x2 = new BN(0); + var y2 = new BN(1); + + // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) + var a0; + var b0; + // First vector + var a1; + var b1; + // Second vector + var a2; + var b2; + + var prevR; + var i = 0; + var r; + var x; + while (u.cmpn(0) !== 0) { + var q = v.div(u); + r = v.sub(q.mul(u)); + x = x2.sub(q.mul(x1)); + var y = y2.sub(q.mul(y1)); + + if (!a1 && r.cmp(aprxSqrt) < 0) { + a0 = prevR.neg(); + b0 = x1; + a1 = r.neg(); + b1 = x; + } else if (a1 && ++i === 2) { + break; + } + prevR = r; + + v = u; + u = r; + x2 = x1; + x1 = x; + y2 = y1; + y1 = y; + } + a2 = r.neg(); + b2 = x; + + var len1 = a1.sqr().add(b1.sqr()); + var len2 = a2.sqr().add(b2.sqr()); + if (len2.cmp(len1) >= 0) { + a2 = a0; + b2 = b0; + } + + // Normalize signs + if (a1.negative) { + a1 = a1.neg(); + b1 = b1.neg(); + } + if (a2.negative) { + a2 = a2.neg(); + b2 = b2.neg(); + } + + return [ + { a: a1, b: b1 }, + { a: a2, b: b2 } + ]; + }; + + ShortCurve.prototype._endoSplit = function _endoSplit(k) { + var basis = this.endo.basis; + var v1 = basis[0]; + var v2 = basis[1]; + + var c1 = v2.b.mul(k).divRound(this.n); + var c2 = v1.b.neg().mul(k).divRound(this.n); + + var p1 = c1.mul(v1.a); + var p2 = c2.mul(v2.a); + var q1 = c1.mul(v1.b); + var q2 = c2.mul(v2.b); + + // Calculate answer + var k1 = k.sub(p1).sub(p2); + var k2 = q1.add(q2).neg(); + return { k1: k1, k2: k2 }; + }; + + ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN(x, 16); + if (!x.red) + x = x.toRed(this.red); + + var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); + var y = y2.redSqrt(); + if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) + throw new Error('invalid point'); + + // XXX Is there any way to tell if the number is odd without converting it + // to non-red form? + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) + y = y.redNeg(); + + return this.point(x, y); + }; + + ShortCurve.prototype.validate = function validate(point) { + if (point.inf) + return true; + + var x = point.x; + var y = point.y; + + var ax = this.a.redMul(x); + var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); + return y.redSqr().redISub(rhs).cmpn(0) === 0; + }; + + ShortCurve.prototype._endoWnafMulAdd = + function _endoWnafMulAdd(points, coeffs, jacobianResult) { + var npoints = this._endoWnafT1; + var ncoeffs = this._endoWnafT2; + for (var i = 0; i < points.length; i++) { + var split = this._endoSplit(coeffs[i]); + var p = points[i]; + var beta = p._getBeta(); + + if (split.k1.negative) { + split.k1.ineg(); + p = p.neg(true); + } + if (split.k2.negative) { + split.k2.ineg(); + beta = beta.neg(true); + } + + npoints[i * 2] = p; + npoints[i * 2 + 1] = beta; + ncoeffs[i * 2] = split.k1; + ncoeffs[i * 2 + 1] = split.k2; + } + var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult); + + // Clean-up references to points and coefficients + for (var j = 0; j < i * 2; j++) { + npoints[j] = null; + ncoeffs[j] = null; + } + return res; + }; + + function Point(curve, x, y, isRed) { + Base.BasePoint.call(this, curve, 'affine'); + if (x === null && y === null) { + this.x = null; + this.y = null; + this.inf = true; + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + // Force redgomery representation when loading from JSON + if (isRed) { + this.x.forceRed(this.curve.red); + this.y.forceRed(this.curve.red); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + this.inf = false; + } + } + inherits(Point, Base.BasePoint); + + ShortCurve.prototype.point = function point(x, y, isRed) { + return new Point(this, x, y, isRed); + }; + + ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { + return Point.fromJSON(this, obj, red); + }; + + Point.prototype._getBeta = function _getBeta() { + if (!this.curve.endo) + return; + + var pre = this.precomputed; + if (pre && pre.beta) + return pre.beta; + + var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); + if (pre) { + var curve = this.curve; + var endoMul = function(p) { + return curve.point(p.x.redMul(curve.endo.beta), p.y); + }; + pre.beta = beta; + beta.precomputed = { + beta: null, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(endoMul) + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(endoMul) + } + }; + } + return beta; + }; + + Point.prototype.toJSON = function toJSON() { + if (!this.precomputed) + return [ this.x, this.y ]; + + return [ this.x, this.y, this.precomputed && { + doubles: this.precomputed.doubles && { + step: this.precomputed.doubles.step, + points: this.precomputed.doubles.points.slice(1) + }, + naf: this.precomputed.naf && { + wnd: this.precomputed.naf.wnd, + points: this.precomputed.naf.points.slice(1) + } + } ]; + }; + + Point.fromJSON = function fromJSON(curve, obj, red) { + if (typeof obj === 'string') + obj = JSON.parse(obj); + var res = curve.point(obj[0], obj[1], red); + if (!obj[2]) + return res; + + function obj2point(obj) { + return curve.point(obj[0], obj[1], red); + } + + var pre = obj[2]; + res.precomputed = { + beta: null, + doubles: pre.doubles && { + step: pre.doubles.step, + points: [ res ].concat(pre.doubles.points.map(obj2point)) + }, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: [ res ].concat(pre.naf.points.map(obj2point)) + } + }; + return res; + }; + + Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; + + Point.prototype.isInfinity = function isInfinity() { + return this.inf; + }; + + Point.prototype.add = function add(p) { + // O + P = P + if (this.inf) + return p; + + // P + O = P + if (p.inf) + return this; + + // P + P = 2P + if (this.eq(p)) + return this.dbl(); + + // P + (-P) = O + if (this.neg().eq(p)) + return this.curve.point(null, null); + + // P + Q = O + if (this.x.cmp(p.x) === 0) + return this.curve.point(null, null); + + var c = this.y.redSub(p.y); + if (c.cmpn(0) !== 0) + c = c.redMul(this.x.redSub(p.x).redInvm()); + var nx = c.redSqr().redISub(this.x).redISub(p.x); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); + }; + + Point.prototype.dbl = function dbl() { + if (this.inf) + return this; + + // 2P = O + var ys1 = this.y.redAdd(this.y); + if (ys1.cmpn(0) === 0) + return this.curve.point(null, null); + + var a = this.curve.a; + + var x2 = this.x.redSqr(); + var dyinv = ys1.redInvm(); + var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); + + var nx = c.redSqr().redISub(this.x.redAdd(this.x)); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); + }; + + Point.prototype.getX = function getX() { + return this.x.fromRed(); + }; + + Point.prototype.getY = function getY() { + return this.y.fromRed(); + }; + + Point.prototype.mul = function mul(k) { + k = new BN(k, 16); + + if (this._hasDoubles(k)) + return this.curve._fixedNafMul(this, k); + else if (this.curve.endo) + return this.curve._endoWnafMulAdd([ this ], [ k ]); + else + return this.curve._wnafMul(this, k); + }; + + Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { + var points = [ this, p2 ]; + var coeffs = [ k1, k2 ]; + if (this.curve.endo) + return this.curve._endoWnafMulAdd(points, coeffs); + else + return this.curve._wnafMulAdd(1, points, coeffs, 2); + }; + + Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) { + var points = [ this, p2 ]; + var coeffs = [ k1, k2 ]; + if (this.curve.endo) + return this.curve._endoWnafMulAdd(points, coeffs, true); + else + return this.curve._wnafMulAdd(1, points, coeffs, 2, true); + }; + + Point.prototype.eq = function eq(p) { + return this === p || + this.inf === p.inf && + (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); + }; + + Point.prototype.neg = function neg(_precompute) { + if (this.inf) + return this; + + var res = this.curve.point(this.x, this.y.redNeg()); + if (_precompute && this.precomputed) { + var pre = this.precomputed; + var negate = function(p) { + return p.neg(); + }; + res.precomputed = { + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(negate) + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(negate) + } + }; + } + return res; + }; + + Point.prototype.toJ = function toJ() { + if (this.inf) + return this.curve.jpoint(null, null, null); + + var res = this.curve.jpoint(this.x, this.y, this.curve.one); + return res; + }; + + function JPoint(curve, x, y, z) { + Base.BasePoint.call(this, curve, 'jacobian'); + if (x === null && y === null && z === null) { + this.x = this.curve.one; + this.y = this.curve.one; + this.z = new BN(0); + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + this.z = new BN(z, 16); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + + this.zOne = this.z === this.curve.one; + } + inherits(JPoint, Base.BasePoint); + + ShortCurve.prototype.jpoint = function jpoint(x, y, z) { + return new JPoint(this, x, y, z); + }; + + JPoint.prototype.toP = function toP() { + if (this.isInfinity()) + return this.curve.point(null, null); + + var zinv = this.z.redInvm(); + var zinv2 = zinv.redSqr(); + var ax = this.x.redMul(zinv2); + var ay = this.y.redMul(zinv2).redMul(zinv); + + return this.curve.point(ax, ay); + }; + + JPoint.prototype.neg = function neg() { + return this.curve.jpoint(this.x, this.y.redNeg(), this.z); + }; + + JPoint.prototype.add = function add(p) { + // O + P = P + if (this.isInfinity()) + return p; + + // P + O = P + if (p.isInfinity()) + return this; + + // 12M + 4S + 7A + var pz2 = p.z.redSqr(); + var z2 = this.z.redSqr(); + var u1 = this.x.redMul(pz2); + var u2 = p.x.redMul(z2); + var s1 = this.y.redMul(pz2.redMul(p.z)); + var s2 = p.y.redMul(z2.redMul(this.z)); + + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(p.z).redMul(h); + + return this.curve.jpoint(nx, ny, nz); + }; + + JPoint.prototype.mixedAdd = function mixedAdd(p) { + // O + P = P + if (this.isInfinity()) + return p.toJ(); + + // P + O = P + if (p.isInfinity()) + return this; + + // 8M + 3S + 7A + var z2 = this.z.redSqr(); + var u1 = this.x; + var u2 = p.x.redMul(z2); + var s1 = this.y; + var s2 = p.y.redMul(z2).redMul(this.z); + + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(h); + + return this.curve.jpoint(nx, ny, nz); + }; + + JPoint.prototype.dblp = function dblp(pow) { + if (pow === 0) + return this; + if (this.isInfinity()) + return this; + if (!pow) + return this.dbl(); + + if (this.curve.zeroA || this.curve.threeA) { + var r = this; + for (var i = 0; i < pow; i++) + r = r.dbl(); + return r; + } + + // 1M + 2S + 1A + N * (4S + 5M + 8A) + // N = 1 => 6M + 6S + 9A + var a = this.curve.a; + var tinv = this.curve.tinv; + + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + + // Reuse results + var jyd = jy.redAdd(jy); + for (var i = 0; i < pow; i++) { + var jx2 = jx.redSqr(); + var jyd2 = jyd.redSqr(); + var jyd4 = jyd2.redSqr(); + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + + var t1 = jx.redMul(jyd2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + var dny = c.redMul(t2); + dny = dny.redIAdd(dny).redISub(jyd4); + var nz = jyd.redMul(jz); + if (i + 1 < pow) + jz4 = jz4.redMul(jyd4); + + jx = nx; + jz = nz; + jyd = dny; + } + + return this.curve.jpoint(jx, jyd.redMul(tinv), jz); + }; + + JPoint.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + + if (this.curve.zeroA) + return this._zeroDbl(); + else if (this.curve.threeA) + return this._threeDbl(); + else + return this._dbl(); + }; + + JPoint.prototype._zeroDbl = function _zeroDbl() { + var nx; + var ny; + var nz; + // Z = 1 + if (this.zOne) { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html + // #doubling-mdbl-2007-bl + // 1M + 5S + 14A + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // S = 2 * ((X1 + YY)^2 - XX - YYYY) + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + // M = 3 * XX + a; a = 0 + var m = xx.redAdd(xx).redIAdd(xx); + // T = M ^ 2 - 2*S + var t = m.redSqr().redISub(s).redISub(s); + + // 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + + // X3 = T + nx = t; + // Y3 = M * (S - T) - 8 * YYYY + ny = m.redMul(s.redISub(t)).redISub(yyyy8); + // Z3 = 2*Y1 + nz = this.y.redAdd(this.y); + } else { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html + // #doubling-dbl-2009-l + // 2M + 5S + 13A + + // A = X1^2 + var a = this.x.redSqr(); + // B = Y1^2 + var b = this.y.redSqr(); + // C = B^2 + var c = b.redSqr(); + // D = 2 * ((X1 + B)^2 - A - C) + var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); + d = d.redIAdd(d); + // E = 3 * A + var e = a.redAdd(a).redIAdd(a); + // F = E^2 + var f = e.redSqr(); + + // 8 * C + var c8 = c.redIAdd(c); + c8 = c8.redIAdd(c8); + c8 = c8.redIAdd(c8); + + // X3 = F - 2 * D + nx = f.redISub(d).redISub(d); + // Y3 = E * (D - X3) - 8 * C + ny = e.redMul(d.redISub(nx)).redISub(c8); + // Z3 = 2 * Y1 * Z1 + nz = this.y.redMul(this.z); + nz = nz.redIAdd(nz); + } + + return this.curve.jpoint(nx, ny, nz); + }; + + JPoint.prototype._threeDbl = function _threeDbl() { + var nx; + var ny; + var nz; + // Z = 1 + if (this.zOne) { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html + // #doubling-mdbl-2007-bl + // 1M + 5S + 15A + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // S = 2 * ((X1 + YY)^2 - XX - YYYY) + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + // M = 3 * XX + a + var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); + // T = M^2 - 2 * S + var t = m.redSqr().redISub(s).redISub(s); + // X3 = T + nx = t; + // Y3 = M * (S - T) - 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + ny = m.redMul(s.redISub(t)).redISub(yyyy8); + // Z3 = 2 * Y1 + nz = this.y.redAdd(this.y); + } else { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b + // 3M + 5S + + // delta = Z1^2 + var delta = this.z.redSqr(); + // gamma = Y1^2 + var gamma = this.y.redSqr(); + // beta = X1 * gamma + var beta = this.x.redMul(gamma); + // alpha = 3 * (X1 - delta) * (X1 + delta) + var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); + alpha = alpha.redAdd(alpha).redIAdd(alpha); + // X3 = alpha^2 - 8 * beta + var beta4 = beta.redIAdd(beta); + beta4 = beta4.redIAdd(beta4); + var beta8 = beta4.redAdd(beta4); + nx = alpha.redSqr().redISub(beta8); + // Z3 = (Y1 + Z1)^2 - gamma - delta + nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); + // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 + var ggamma8 = gamma.redSqr(); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); + } + + return this.curve.jpoint(nx, ny, nz); + }; + + JPoint.prototype._dbl = function _dbl() { + var a = this.curve.a; + + // 4M + 6S + 10A + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + + var jx2 = jx.redSqr(); + var jy2 = jy.redSqr(); + + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + + var jxd4 = jx.redAdd(jx); + jxd4 = jxd4.redIAdd(jxd4); + var t1 = jxd4.redMul(jy2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + + var jyd8 = jy2.redSqr(); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + var ny = c.redMul(t2).redISub(jyd8); + var nz = jy.redAdd(jy).redMul(jz); + + return this.curve.jpoint(nx, ny, nz); + }; + + JPoint.prototype.trpl = function trpl() { + if (!this.curve.zeroA) + return this.dbl().add(this); + + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl + // 5M + 10S + ... + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // ZZ = Z1^2 + var zz = this.z.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // M = 3 * XX + a * ZZ2; a = 0 + var m = xx.redAdd(xx).redIAdd(xx); + // MM = M^2 + var mm = m.redSqr(); + // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM + var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + e = e.redIAdd(e); + e = e.redAdd(e).redIAdd(e); + e = e.redISub(mm); + // EE = E^2 + var ee = e.redSqr(); + // T = 16*YYYY + var t = yyyy.redIAdd(yyyy); + t = t.redIAdd(t); + t = t.redIAdd(t); + t = t.redIAdd(t); + // U = (M + E)^2 - MM - EE - T + var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); + // X3 = 4 * (X1 * EE - 4 * YY * U) + var yyu4 = yy.redMul(u); + yyu4 = yyu4.redIAdd(yyu4); + yyu4 = yyu4.redIAdd(yyu4); + var nx = this.x.redMul(ee).redISub(yyu4); + nx = nx.redIAdd(nx); + nx = nx.redIAdd(nx); + // Y3 = 8 * Y1 * (U * (T - U) - E * EE) + var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + // Z3 = (Z1 + E)^2 - ZZ - EE + var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); + + return this.curve.jpoint(nx, ny, nz); + }; + + JPoint.prototype.mul = function mul(k, kbase) { + k = new BN(k, kbase); + + return this.curve._wnafMul(this, k); + }; + + JPoint.prototype.eq = function eq(p) { + if (p.type === 'affine') + return this.eq(p.toJ()); + + if (this === p) + return true; + + // x1 * z2^2 == x2 * z1^2 + var z2 = this.z.redSqr(); + var pz2 = p.z.redSqr(); + if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) + return false; + + // y1 * z2^3 == y2 * z1^3 + var z3 = z2.redMul(this.z); + var pz3 = pz2.redMul(p.z); + return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; + }; + + JPoint.prototype.eqXToP = function eqXToP(x) { + var zs = this.z.redSqr(); + var rx = x.toRed(this.curve.red).redMul(zs); + if (this.x.cmp(rx) === 0) + return true; + + var xc = x.clone(); + var t = this.curve.redN.redMul(zs); + for (;;) { + xc.iadd(this.curve.n); + if (xc.cmp(this.curve.p) >= 0) + return false; + + rx.redIAdd(t); + if (this.x.cmp(rx) === 0) + return true; + } + return false; + }; + + JPoint.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; + }; + + JPoint.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; + }; + + },{"../../elliptic":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); + else if (options.type === 'edwards') + this.curve = new elliptic.curve.edwards(options); + else + this.curve = new elliptic.curve.mont(options); + this.g = this.curve.g; + this.n = this.curve.n; + this.hash = options.hash; + + assert(this.g.validate(), 'Invalid curve'); + assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); + } + curves.PresetCurve = PresetCurve; + + function defineCurve(name, options) { + Object.defineProperty(curves, name, { + configurable: true, + enumerable: true, + get: function() { + var curve = new PresetCurve(options); + Object.defineProperty(curves, name, { + configurable: true, + enumerable: true, + value: curve + }); + return curve; + } + }); + } + + defineCurve('p192', { + type: 'short', + prime: 'p192', + p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', + a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', + b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', + n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', + hash: hash.sha256, + gRed: false, + g: [ + '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', + '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811' + ] + }); + + defineCurve('p224', { + type: 'short', + prime: 'p224', + p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', + a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', + b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', + n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', + hash: hash.sha256, + gRed: false, + g: [ + 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', + 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34' + ] + }); + + defineCurve('p256', { + type: 'short', + prime: null, + p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', + a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', + b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', + n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', + hash: hash.sha256, + gRed: false, + g: [ + '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', + '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5' + ] + }); + + defineCurve('p384', { + type: 'short', + prime: null, + p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'fffffffe ffffffff 00000000 00000000 ffffffff', + a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'fffffffe ffffffff 00000000 00000000 fffffffc', + b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' + + '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef', + n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' + + 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973', + hash: hash.sha384, + gRed: false, + g: [ + 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' + + '5502f25d bf55296c 3a545e38 72760ab7', + '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' + + '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f' + ] + }); + + defineCurve('p521', { + type: 'short', + prime: null, + p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff', + a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff fffffffc', + b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' + + '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' + + '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00', + n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' + + 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409', + hash: hash.sha512, + gRed: false, + g: [ + '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' + + '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' + + 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', + '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' + + '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' + + '3fad0761 353c7086 a272c240 88be9476 9fd16650' + ] + }); + + defineCurve('curve25519', { + type: 'mont', + prime: 'p25519', + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: '76d06', + b: '1', + n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', + hash: hash.sha256, + gRed: false, + g: [ + '9' + ] + }); + + defineCurve('ed25519', { + type: 'edwards', + prime: 'p25519', + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: '-1', + c: '1', + // -121665 * (121666^(-1)) (mod P) + d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', + n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', + hash: hash.sha256, + gRed: false, + g: [ + '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', + + // 4/5 + '6666666666666666666666666666666666666666666666666666666666666658' + ] + }); + + var pre; + try { + pre = require('./precomputed/secp256k1'); + } catch (e) { + pre = undefined; + } + + defineCurve('secp256k1', { + type: 'short', + prime: 'k256', + p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', + a: '0', + b: '7', + n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', + h: '1', + hash: hash.sha256, + + // Precomputed endomorphism + beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', + lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', + basis: [ + { + a: '3086d221a7d46bcde86c90e49284eb15', + b: '-e4437ed6010e88286f547fa90abfe4c3' + }, + { + a: '114ca50f7a8e2f3f657c1108d9d44cfd8', + b: '3086d221a7d46bcde86c90e49284eb15' + } + ], + + gRed: false, + g: [ + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', + pre + ] + }); + + },{"../elliptic":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, + pers: options.pers, + persEnc: options.persEnc || 'utf8', + entropy: options.entropy || elliptic.rand(this.hash.hmacStrength), + entropyEnc: options.entropy && options.entropyEnc || 'utf8', + nonce: this.n.toArray() + }); + + var bytes = this.n.byteLength(); + var ns2 = this.n.sub(new BN(2)); + do { + var priv = new BN(drbg.generate(bytes)); + if (priv.cmp(ns2) > 0) + continue; + + priv.iaddn(1); + return this.keyFromPrivate(priv); + } while (true); + }; + + EC.prototype._truncateToN = function truncateToN(msg, truncOnly) { + var delta = msg.byteLength() * 8 - this.n.bitLength(); + if (delta > 0) + msg = msg.ushrn(delta); + if (!truncOnly && msg.cmp(this.n) >= 0) + return msg.sub(this.n); + else + return msg; + }; + + EC.prototype.sign = function sign(msg, key, enc, options) { + if (typeof enc === 'object') { + options = enc; + enc = null; + } + if (!options) + options = {}; + + key = this.keyFromPrivate(key, enc); + msg = this._truncateToN(new BN(msg, 16)); + + // Zero-extend key to provide enough entropy + var bytes = this.n.byteLength(); + var bkey = key.getPrivate().toArray('be', bytes); + + // Zero-extend nonce to have the same byte size as N + var nonce = msg.toArray('be', bytes); + + // Instantiate Hmac_DRBG + var drbg = new HmacDRBG({ + hash: this.hash, + entropy: bkey, + nonce: nonce, + pers: options.pers, + persEnc: options.persEnc || 'utf8' + }); + + // Number of bytes to generate + var ns1 = this.n.sub(new BN(1)); + + for (var iter = 0; true; iter++) { + var k = options.k ? + options.k(iter) : + new BN(drbg.generate(this.n.byteLength())); + k = this._truncateToN(k, true); + if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) + continue; + + var kp = this.g.mul(k); + if (kp.isInfinity()) + continue; + + var kpX = kp.getX(); + var r = kpX.umod(this.n); + if (r.cmpn(0) === 0) + continue; + + var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); + s = s.umod(this.n); + if (s.cmpn(0) === 0) + continue; + + var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | + (kpX.cmp(r) !== 0 ? 2 : 0); + + // Use complement of `s`, if it is > `n / 2` + if (options.canonical && s.cmp(this.nh) > 0) { + s = this.n.sub(s); + recoveryParam ^= 1; + } + + return new Signature({ r: r, s: s, recoveryParam: recoveryParam }); + } + }; + + EC.prototype.verify = function verify(msg, signature, key, enc) { + msg = this._truncateToN(new BN(msg, 16)); + key = this.keyFromPublic(key, enc); + signature = new Signature(signature, 'hex'); + + // Perform primitive values validation + var r = signature.r; + var s = signature.s; + if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) + return false; + if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) + return false; + + // Validate signature + var sinv = s.invm(this.n); + var u1 = sinv.mul(msg).umod(this.n); + var u2 = sinv.mul(r).umod(this.n); + + if (!this.curve._maxwellTrick) { + var p = this.g.mulAdd(u1, key.getPublic(), u2); + if (p.isInfinity()) + return false; + + return p.getX().umod(this.n).cmp(r) === 0; + } + + // NOTE: Greg Maxwell's trick, inspired by: + // https://git.io/vad3K + + var p = this.g.jmulAdd(u1, key.getPublic(), u2); + if (p.isInfinity()) + return false; + + // Compare `p.x` of Jacobian point with `r`, + // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the + // inverse of `p.z^2` + return p.eqXToP(r); + }; + + EC.prototype.recoverPubKey = function(msg, signature, j, enc) { + assert((3 & j) === j, 'The recovery param is more than two bits'); + signature = new Signature(signature, enc); + + var n = this.n; + var e = new BN(msg); + var r = signature.r; + var s = signature.s; + + // A set LSB signifies that the y-coordinate is odd + var isYOdd = j & 1; + var isSecondKey = j >> 1; + if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) + throw new Error('Unable to find sencond key candinate'); + + // 1.1. Let x = r + jn. + if (isSecondKey) + r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); + else + r = this.curve.pointFromX(r, isYOdd); + + var rInv = signature.r.invm(n); + var s1 = n.sub(e).mul(rInv).umod(n); + var s2 = s.mul(rInv).umod(n); + + // 1.6.1 Compute Q = r^-1 (sR - eG) + // Q = r^-1 (sR + -eG) + return this.g.mulAdd(s1, r, s2); + }; + + EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { + signature = new Signature(signature, enc); + if (signature.recoveryParam !== null) + return signature.recoveryParam; + + for (var i = 0; i < 4; i++) { + var Qprime; + try { + Qprime = this.recoverPubKey(e, signature, i); + } catch (e) { + continue; + } + + if (Qprime.eq(Q)) + return i; + } + throw new Error('Unable to find valid recovery factor'); + }; + + },{"../../elliptic":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); + if (options.pub) + this._importPublic(options.pub, options.pubEnc); + } + module.exports = KeyPair; + + KeyPair.fromPublic = function fromPublic(ec, pub, enc) { + if (pub instanceof KeyPair) + return pub; + + return new KeyPair(ec, { + pub: pub, + pubEnc: enc + }); + }; + + KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) { + if (priv instanceof KeyPair) + return priv; + + return new KeyPair(ec, { + priv: priv, + privEnc: enc + }); + }; + + KeyPair.prototype.validate = function validate() { + var pub = this.getPublic(); + + if (pub.isInfinity()) + return { result: false, reason: 'Invalid public key' }; + if (!pub.validate()) + return { result: false, reason: 'Public key is not a point' }; + if (!pub.mul(this.ec.curve.n).isInfinity()) + return { result: false, reason: 'Public key * N != O' }; + + return { result: true, reason: null }; + }; + + KeyPair.prototype.getPublic = function getPublic(compact, enc) { + // compact is optional argument + if (typeof compact === 'string') { + enc = compact; + compact = null; + } + + if (!this.pub) + this.pub = this.ec.g.mul(this.priv); + + if (!enc) + return this.pub; + + return this.pub.encode(enc, compact); + }; + + KeyPair.prototype.getPrivate = function getPrivate(enc) { + if (enc === 'hex') + return this.priv.toString(16, 2); + else + return this.priv; + }; + + KeyPair.prototype._importPrivate = function _importPrivate(key, enc) { + this.priv = new BN(key, enc || 16); + + // Ensure that the priv won't be bigger than n, otherwise we may fail + // in fixed multiplication method + this.priv = this.priv.umod(this.ec.curve.n); + }; + + KeyPair.prototype._importPublic = function _importPublic(key, enc) { + if (key.x || key.y) { + // Montgomery points only have an `x` coordinate. + // Weierstrass/Edwards points on the other hand have both `x` and + // `y` coordinates. + if (this.ec.curve.type === 'mont') { + assert(key.x, 'Need x coordinate'); + } else if (this.ec.curve.type === 'short' || + this.ec.curve.type === 'edwards') { + assert(key.x && key.y, 'Need both x and y coordinate'); + } + this.pub = this.ec.curve.point(key.x, key.y); + return; + } + this.pub = this.ec.curve.decodePoint(key, enc); + }; + + // ECDH + KeyPair.prototype.derive = function derive(pub) { + return pub.mul(this.priv).getX(); + }; + + // ECDSA + KeyPair.prototype.sign = function sign(msg, enc, options) { + return this.ec.sign(msg, this, enc, options); + }; + + KeyPair.prototype.verify = function verify(msg, signature) { + return this.ec.verify(msg, signature, this); + }; + + KeyPair.prototype.inspect = function inspect() { + return ''; + }; + + },{"../../elliptic":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); + if (options.recoveryParam === undefined) + this.recoveryParam = null; + else + this.recoveryParam = options.recoveryParam; + } + module.exports = Signature; + + function Position() { + this.place = 0; + } + + function getLength(buf, p) { + var initial = buf[p.place++]; + if (!(initial & 0x80)) { + return initial; + } + var octetLen = initial & 0xf; + var val = 0; + for (var i = 0, off = p.place; i < octetLen; i++, off++) { + val <<= 8; + val |= buf[off]; + } + p.place = off; + return val; + } + + function rmPadding(buf) { + var i = 0; + var len = buf.length - 1; + while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) { + i++; + } + if (i === 0) { + return buf; + } + return buf.slice(i); + } + + Signature.prototype._importDER = function _importDER(data, enc) { + data = utils.toArray(data, enc); + var p = new Position(); + if (data[p.place++] !== 0x30) { + return false; + } + var len = getLength(data, p); + if ((len + p.place) !== data.length) { + return false; + } + if (data[p.place++] !== 0x02) { + return false; + } + var rlen = getLength(data, p); + var r = data.slice(p.place, rlen + p.place); + p.place += rlen; + if (data[p.place++] !== 0x02) { + return false; + } + var slen = getLength(data, p); + if (data.length !== slen + p.place) { + return false; + } + var s = data.slice(p.place, slen + p.place); + if (r[0] === 0 && (r[1] & 0x80)) { + r = r.slice(1); + } + if (s[0] === 0 && (s[1] & 0x80)) { + s = s.slice(1); + } + + this.r = new BN(r); + this.s = new BN(s); + this.recoveryParam = null; + + return true; + }; + + function constructLength(arr, len) { + if (len < 0x80) { + arr.push(len); + return; + } + var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); + arr.push(octets | 0x80); + while (--octets) { + arr.push((len >>> (octets << 3)) & 0xff); + } + arr.push(len); + } + + Signature.prototype.toDER = function toDER(enc) { + var r = this.r.toArray(); + var s = this.s.toArray(); + + // Pad values + if (r[0] & 0x80) + r = [ 0 ].concat(r); + // Pad values + if (s[0] & 0x80) + s = [ 0 ].concat(s); + + r = rmPadding(r); + s = rmPadding(s); + + while (!s[0] && !(s[1] & 0x80)) { + s = s.slice(1); + } + var arr = [ 0x02 ]; + constructLength(arr, r.length); + arr = arr.concat(r); + arr.push(0x02); + constructLength(arr, s.length); + var backHalf = arr.concat(s); + var res = [ 0x30 ]; + constructLength(res, backHalf.length); + res = res.concat(backHalf); + return utils.encode(res, enc); + }; + + },{"../../elliptic":109,"bn.js":53}],119:[function(require,module,exports){ + 'use strict'; + + var hash = require('hash.js'); + var elliptic = require('../../elliptic'); + var utils = elliptic.utils; + var assert = utils.assert; + var parseBytes = utils.parseBytes; + var KeyPair = require('./key'); + var Signature = require('./signature'); + + function EDDSA(curve) { + assert(curve === 'ed25519', 'only tested with ed25519 so far'); + + if (!(this instanceof EDDSA)) + return new EDDSA(curve); + + var curve = elliptic.curves[curve].curve; + this.curve = curve; + this.g = curve.g; + this.g.precompute(curve.n.bitLength() + 1); + + this.pointClass = curve.point().constructor; + this.encodingLength = Math.ceil(curve.n.bitLength() / 8); + this.hash = hash.sha512; + } + + module.exports = EDDSA; + + /** + * @param {Array|String} message - message bytes + * @param {Array|String|KeyPair} secret - secret bytes or a keypair + * @returns {Signature} - signature + */ + EDDSA.prototype.sign = function sign(message, secret) { + message = parseBytes(message); + var key = this.keyFromSecret(secret); + var r = this.hashInt(key.messagePrefix(), message); + var R = this.g.mul(r); + var Rencoded = this.encodePoint(R); + var s_ = this.hashInt(Rencoded, key.pubBytes(), message) + .mul(key.priv()); + var S = r.add(s_).umod(this.curve.n); + return this.makeSignature({ R: R, S: S, Rencoded: Rencoded }); + }; + + /** + * @param {Array} message - message bytes + * @param {Array|String|Signature} sig - sig bytes + * @param {Array|String|Point|KeyPair} pub - public key + * @returns {Boolean} - true if public key matches sig of message + */ + EDDSA.prototype.verify = function verify(message, sig, pub) { + message = parseBytes(message); + sig = this.makeSignature(sig); + var key = this.keyFromPublic(pub); + var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message); + var SG = this.g.mul(sig.S()); + var RplusAh = sig.R().add(key.pub().mul(h)); + return RplusAh.eq(SG); + }; + + EDDSA.prototype.hashInt = function hashInt() { + var hash = this.hash(); + for (var i = 0; i < arguments.length; i++) + hash.update(arguments[i]); + return utils.intFromLE(hash.digest()).umod(this.curve.n); + }; + + EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { + return KeyPair.fromPublic(this, pub); + }; + + EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { + return KeyPair.fromSecret(this, secret); + }; + + EDDSA.prototype.makeSignature = function makeSignature(sig) { + if (sig instanceof Signature) + return sig; + return new Signature(this, sig); + }; + + /** + * * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2 + * + * EDDSA defines methods for encoding and decoding points and integers. These are + * helper convenience methods, that pass along to utility functions implied + * parameters. + * + */ + EDDSA.prototype.encodePoint = function encodePoint(point) { + var enc = point.getY().toArray('le', this.encodingLength); + enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0; + return enc; + }; + + EDDSA.prototype.decodePoint = function decodePoint(bytes) { + bytes = utils.parseBytes(bytes); + + var lastIx = bytes.length - 1; + var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); + var xIsOdd = (bytes[lastIx] & 0x80) !== 0; + + var y = utils.intFromLE(normed); + return this.curve.pointFromY(y, xIsOdd); + }; + + EDDSA.prototype.encodeInt = function encodeInt(num) { + return num.toArray('le', this.encodingLength); + }; + + EDDSA.prototype.decodeInt = function decodeInt(bytes) { + return utils.intFromLE(bytes); + }; + + EDDSA.prototype.isPoint = function isPoint(val) { + return val instanceof this.pointClass; + }; + + },{"../../elliptic":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 + * + * @param {Array} [params.secret] - secret seed bytes + * @param {Point} [params.pub] - public key point (aka `A` in eddsa terms) + * @param {Array} [params.pub] - public key point encoded as bytes + * + */ + function KeyPair(eddsa, params) { + this.eddsa = eddsa; + this._secret = parseBytes(params.secret); + if (eddsa.isPoint(params.pub)) + this._pub = params.pub; + else + this._pubBytes = parseBytes(params.pub); + } + + KeyPair.fromPublic = function fromPublic(eddsa, pub) { + if (pub instanceof KeyPair) + return pub; + return new KeyPair(eddsa, { pub: pub }); + }; + + KeyPair.fromSecret = function fromSecret(eddsa, secret) { + if (secret instanceof KeyPair) + return secret; + return new KeyPair(eddsa, { secret: secret }); + }; + + KeyPair.prototype.secret = function secret() { + return this._secret; + }; + + cachedProperty(KeyPair, 'pubBytes', function pubBytes() { + return this.eddsa.encodePoint(this.pub()); + }); + + cachedProperty(KeyPair, 'pub', function pub() { + if (this._pubBytes) + return this.eddsa.decodePoint(this._pubBytes); + return this.eddsa.g.mul(this.priv()); + }); + + cachedProperty(KeyPair, 'privBytes', function privBytes() { + var eddsa = this.eddsa; + var hash = this.hash(); + var lastIx = eddsa.encodingLength - 1; + + var a = hash.slice(0, eddsa.encodingLength); + a[0] &= 248; + a[lastIx] &= 127; + a[lastIx] |= 64; + + return a; + }); + + cachedProperty(KeyPair, 'priv', function priv() { + return this.eddsa.decodeInt(this.privBytes()); + }); + + cachedProperty(KeyPair, 'hash', function hash() { + return this.eddsa.hash().update(this.secret()).digest(); + }); + + cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() { + return this.hash().slice(this.eddsa.encodingLength); + }); + + KeyPair.prototype.sign = function sign(message) { + assert(this._secret, 'KeyPair can only verify'); + return this.eddsa.sign(message, this); + }; + + KeyPair.prototype.verify = function verify(message, sig) { + return this.eddsa.verify(message, sig, this); + }; + + KeyPair.prototype.getSecret = function getSecret(enc) { + assert(this._secret, 'KeyPair is public only'); + return utils.encode(this.secret(), enc); + }; + + KeyPair.prototype.getPublic = function getPublic(enc) { + return utils.encode(this.pubBytes(), enc); + }; + + module.exports = KeyPair; + + },{"../../elliptic":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 - + * @param {Array|Point} [sig.R] - R point as Point or bytes + * @param {Array|bn} [sig.S] - S scalar as bn or bytes + * @param {Array} [sig.Rencoded] - R point encoded + * @param {Array} [sig.Sencoded] - S scalar encoded + */ + function Signature(eddsa, sig) { + this.eddsa = eddsa; + + if (typeof sig !== 'object') + sig = parseBytes(sig); + + if (Array.isArray(sig)) { + sig = { + R: sig.slice(0, eddsa.encodingLength), + S: sig.slice(eddsa.encodingLength) + }; + } + + assert(sig.R && sig.S, 'Signature without R or S'); + + if (eddsa.isPoint(sig.R)) + this._R = sig.R; + if (sig.S instanceof BN) + this._S = sig.S; + + this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; + this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; + } + + cachedProperty(Signature, 'S', function S() { + return this.eddsa.decodeInt(this.Sencoded()); + }); + + cachedProperty(Signature, 'R', function R() { + return this.eddsa.decodePoint(this.Rencoded()); + }); + + cachedProperty(Signature, 'Rencoded', function Rencoded() { + return this.eddsa.encodePoint(this.R()); + }); + + cachedProperty(Signature, 'Sencoded', function Sencoded() { + return this.eddsa.encodeInt(this.S()); + }); + + Signature.prototype.toBytes = function toBytes() { + return this.Rencoded().concat(this.Sencoded()); + }; + + Signature.prototype.toHex = function toHex() { + return utils.encode(this.toBytes(), 'hex').toUpperCase(); + }; + + module.exports = Signature; + + },{"../../elliptic":109,"bn.js":53}],122:[function(require,module,exports){ + module.exports = { + doubles: { + step: 4, + points: [ + [ + 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', + 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821' + ], + [ + '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', + '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf' + ], + [ + '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', + 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695' + ], + [ + '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', + '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9' + ], + [ + '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', + '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36' + ], + [ + '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', + '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f' + ], + [ + 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', + '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999' + ], + [ + '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', + 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09' + ], + [ + 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', + '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d' + ], + [ + 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', + 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088' + ], + [ + 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', + '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d' + ], + [ + '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', + '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8' + ], + [ + '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', + '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a' + ], + [ + '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', + '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453' + ], + [ + '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', + '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160' + ], + [ + '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', + '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0' + ], + [ + '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', + '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6' + ], + [ + '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', + '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589' + ], + [ + '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', + 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17' + ], + [ + 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', + '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda' + ], + [ + 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', + '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd' + ], + [ + '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', + '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2' + ], + [ + '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', + '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6' + ], + [ + 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', + '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f' + ], + [ + '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', + 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01' + ], + [ + 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', + '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3' + ], + [ + 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', + 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f' + ], + [ + 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', + '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7' + ], + [ + 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', + 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78' + ], + [ + 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', + '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1' + ], + [ + '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', + 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150' + ], + [ + '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', + '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82' + ], + [ + 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', + '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc' + ], + [ + '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', + 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b' + ], + [ + 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', + '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51' + ], + [ + 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', + '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45' + ], + [ + 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', + 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120' + ], + [ + '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', + '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84' + ], + [ + '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', + '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d' + ], + [ + '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', + 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d' + ], + [ + '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', + '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8' + ], + [ + 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', + '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8' + ], + [ + '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', + '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac' + ], + [ + '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', + 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f' + ], + [ + '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', + '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962' + ], + [ + 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', + '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907' + ], + [ + '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', + 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec' + ], + [ + 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', + 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d' + ], + [ + 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', + '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414' + ], + [ + '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', + 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd' + ], + [ + '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', + 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0' + ], + [ + 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', + '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811' + ], + [ + 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', + '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1' + ], + [ + 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', + '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c' + ], + [ + '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', + 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73' + ], + [ + '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', + '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd' + ], + [ + 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', + 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405' + ], + [ + '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', + 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589' + ], + [ + '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', + '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e' + ], + [ + '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', + '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27' + ], + [ + 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', + 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1' + ], + [ + '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', + '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482' + ], + [ + '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', + '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945' + ], + [ + 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', + '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573' + ], + [ + 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', + 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82' + ] + ] + }, + naf: { + wnd: 7, + points: [ + [ + 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', + '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672' + ], + [ + '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', + 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6' + ], + [ + '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', + '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da' + ], + [ + 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', + 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37' + ], + [ + '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', + 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b' + ], + [ + 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', + 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81' + ], + [ + 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', + '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58' + ], + [ + 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', + '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77' + ], + [ + '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', + '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a' + ], + [ + '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', + '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c' + ], + [ + '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', + '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67' + ], + [ + '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', + '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402' + ], + [ + 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', + 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55' + ], + [ + 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', + '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482' + ], + [ + '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', + 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82' + ], + [ + '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', + 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396' + ], + [ + '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', + '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49' + ], + [ + '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', + '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf' + ], + [ + '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', + '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a' + ], + [ + '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', + 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7' + ], + [ + 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', + 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933' + ], + [ + '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', + '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a' + ], + [ + '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', + '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6' + ], + [ + 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', + 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37' + ], + [ + '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', + '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e' + ], + [ + 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', + 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6' + ], + [ + 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', + 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476' + ], + [ + '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', + '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40' + ], + [ + '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', + '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61' + ], + [ + '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', + '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683' + ], + [ + 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', + '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5' + ], + [ + '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', + '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b' + ], + [ + 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', + '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417' + ], + [ + '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', + 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868' + ], + [ + '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', + 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a' + ], + [ + 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', + 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6' + ], + [ + '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', + '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996' + ], + [ + '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', + 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e' + ], + [ + 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', + 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d' + ], + [ + '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', + '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2' + ], + [ + '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', + 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e' + ], + [ + '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', + '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437' + ], + [ + '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', + 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311' + ], + [ + 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', + '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4' + ], + [ + '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', + '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575' + ], + [ + '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', + 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d' + ], + [ + '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', + 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d' + ], + [ + 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', + 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629' + ], + [ + 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', + 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06' + ], + [ + '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', + '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374' + ], + [ + '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', + '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee' + ], + [ + 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', + '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1' + ], + [ + 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', + 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b' + ], + [ + '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', + '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661' + ], + [ + '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', + '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6' + ], + [ + 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', + '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e' + ], + [ + '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', + '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d' + ], + [ + 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', + 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc' + ], + [ + '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', + 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4' + ], + [ + '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', + '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c' + ], + [ + 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', + '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b' + ], + [ + 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', + '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913' + ], + [ + '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', + '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154' + ], + [ + '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', + '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865' + ], + [ + '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', + 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc' + ], + [ + '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', + 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224' + ], + [ + '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', + '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e' + ], + [ + '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', + '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6' + ], + [ + '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', + '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511' + ], + [ + '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', + 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b' + ], + [ + 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', + 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2' + ], + [ + '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', + 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c' + ], + [ + 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', + '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3' + ], + [ + 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', + '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d' + ], + [ + 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', + '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700' + ], + [ + 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', + '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4' + ], + [ + '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', + 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196' + ], + [ + '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', + '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4' + ], + [ + '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', + 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257' + ], + [ + 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', + 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13' + ], + [ + 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', + '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096' + ], + [ + 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', + 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38' + ], + [ + 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', + '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f' + ], + [ + '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', + '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448' + ], + [ + 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', + '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a' + ], + [ + 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', + '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4' + ], + [ + '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', + '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437' + ], + [ + '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', + 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7' + ], + [ + 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', + '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d' + ], + [ + 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', + '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a' + ], + [ + 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', + '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54' + ], + [ + '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', + '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77' + ], + [ + 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', + 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517' + ], + [ + '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', + 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10' + ], + [ + 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', + 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125' + ], + [ + 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', + '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e' + ], + [ + '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', + 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1' + ], + [ + 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', + '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2' + ], + [ + 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', + '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423' + ], + [ + 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', + '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8' + ], + [ + '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', + 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758' + ], + [ + '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', + 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375' + ], + [ + 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', + '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d' + ], + [ + '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', + 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec' + ], + [ + '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', + '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0' + ], + [ + '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', + 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c' + ], + [ + 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', + 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4' + ], + [ + '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', + 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f' + ], + [ + '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', + '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649' + ], + [ + '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', + 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826' + ], + [ + '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', + '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5' + ], + [ + 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', + 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87' + ], + [ + '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', + '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b' + ], + [ + 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', + '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc' + ], + [ + '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', + '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c' + ], + [ + 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', + 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f' + ], + [ + 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', + '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a' + ], + [ + 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', + 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46' + ], + [ + '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', + 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f' + ], + [ + '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', + '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03' + ], + [ + '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', + 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08' + ], + [ + '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', + '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8' + ], + [ + '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', + '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373' + ], + [ + '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', + 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3' + ], + [ + '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', + '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8' + ], + [ + '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', + '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1' + ], + [ + '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', + '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9' + ] + ] + } + }; + + },{}],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 = []; + var ws = 1 << (w + 1); + var k = num.clone(); + while (k.cmpn(1) >= 0) { + var z; + if (k.isOdd()) { + var mod = k.andln(ws - 1); + if (mod > (ws >> 1) - 1) + z = (ws >> 1) - mod; + else + z = mod; + k.isubn(z); + } else { + z = 0; + } + naf.push(z); + + // Optimization, shift by word if possible + var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1; + for (var i = 1; i < shift; i++) + naf.push(0); + k.iushrn(shift); + } + + return naf; + } + utils.getNAF = getNAF; + + // Represent k1, k2 in a Joint Sparse Form + function getJSF(k1, k2) { + var jsf = [ + [], + [] + ]; + + k1 = k1.clone(); + k2 = k2.clone(); + var d1 = 0; + var d2 = 0; + while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { + + // First phase + var m14 = (k1.andln(3) + d1) & 3; + var m24 = (k2.andln(3) + d2) & 3; + if (m14 === 3) + m14 = -1; + if (m24 === 3) + m24 = -1; + var u1; + if ((m14 & 1) === 0) { + u1 = 0; + } else { + var m8 = (k1.andln(7) + d1) & 7; + if ((m8 === 3 || m8 === 5) && m24 === 2) + u1 = -m14; + else + u1 = m14; + } + jsf[0].push(u1); + + var u2; + if ((m24 & 1) === 0) { + u2 = 0; + } else { + var m8 = (k2.andln(7) + d2) & 7; + if ((m8 === 3 || m8 === 5) && m14 === 2) + u2 = -m24; + else + u2 = m24; + } + jsf[1].push(u2); + + // Second phase + if (2 * d1 === u1 + 1) + d1 = 1 - d1; + if (2 * d2 === u2 + 1) + d2 = 1 - d2; + k1.iushrn(1); + k2.iushrn(1); + } + + return jsf; + } + utils.getJSF = getJSF; + + function cachedProperty(obj, name, computer) { + var key = '_' + name; + obj.prototype[name] = function cachedProperty() { + return this[key] !== undefined ? this[key] : + this[key] = computer.call(this); + }; + } + utils.cachedProperty = cachedProperty; + + function parseBytes(bytes) { + return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : + bytes; + } + utils.parseBytes = parseBytes; + + function intFromLE(bytes) { + return new BN(bytes, 'hex', 'le'); + } + utils.intFromLE = intFromLE; + + + },{"bn.js":53,"minimalistic-assert":234,"minimalistic-crypto-utils":235}],124:[function(require,module,exports){ + module.exports={ + "_from": "elliptic@^6.0.0", + "_id": "elliptic@6.4.0", + "_inBundle": false, + "_integrity": "sha1-ysmvh2LIWDYYcAPI3+GT5eLq5d8=", + "_location": "/elliptic", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "elliptic@^6.0.0", + "name": "elliptic", + "escapedName": "elliptic", + "rawSpec": "^6.0.0", + "saveSpec": null, + "fetchSpec": "^6.0.0" + }, + "_requiredBy": [ + "/browserify-sign", + "/create-ecdh" + ], + "_resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.4.0.tgz", + "_shasum": "cac9af8762c85836187003c8dfe193e5e2eae5df", + "_spec": "elliptic@^6.0.0", + "_where": "/Users/alexvlasov/Blockchain/web3swift_jsproxy/node_modules/browserify-sign", + "author": { + "name": "Fedor Indutny", + "email": "fedor@indutny.com" + }, + "bugs": { + "url": "https://github.com/indutny/elliptic/issues" + }, + "bundleDependencies": false, + "dependencies": { + "bn.js": "^4.4.0", + "brorand": "^1.0.1", + "hash.js": "^1.0.0", + "hmac-drbg": "^1.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0", + "minimalistic-crypto-utils": "^1.0.0" + }, + "deprecated": false, + "description": "EC cryptography", + "devDependencies": { + "brfs": "^1.4.3", + "coveralls": "^2.11.3", + "grunt": "^0.4.5", + "grunt-browserify": "^5.0.0", + "grunt-cli": "^1.2.0", + "grunt-contrib-connect": "^1.0.0", + "grunt-contrib-copy": "^1.0.0", + "grunt-contrib-uglify": "^1.0.1", + "grunt-mocha-istanbul": "^3.0.1", + "grunt-saucelabs": "^8.6.2", + "istanbul": "^0.4.2", + "jscs": "^2.9.0", + "jshint": "^2.6.0", + "mocha": "^2.1.0" + }, + "files": [ + "lib" + ], + "homepage": "https://github.com/indutny/elliptic", + "keywords": [ + "EC", + "Elliptic", + "curve", + "Cryptography" + ], + "license": "MIT", + "main": "lib/elliptic.js", + "name": "elliptic", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/indutny/elliptic.git" + }, + "scripts": { + "jscs": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js", + "jshint": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js", + "lint": "npm run jscs && npm run jshint", + "test": "npm run lint && npm run unit", + "unit": "istanbul test _mocha --reporter=spec test/index.js", + "version": "grunt dist && git add dist/" + }, + "version": "6.4.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') { + stripped = stripped.substr(1) + } + return `0x${stripped}` + } + + },{"ethjs-util":155}],126:[function(require,module,exports){ + // const EthQuery = require('ethjs-query') + const EthQuery = require('eth-query') + const EventEmitter = require('events') + const pify = require('pify') + const hexUtils = require('./hexUtils') + 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.') + this._provider = opts.provider + this._query = new EthQuery(opts.provider) + // config + this._pollingInterval = opts.pollingInterval || 4 * sec + this._syncingTimeout = opts.syncingTimeout || 1 * min + // state + this._trackingBlock = null + this._trackingBlockTimestamp = null + this._currentBlock = null + this._isRunning = false + // bind methods for cleaner syntax later + 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 + // wait for "sync" event + await new Promise(resolve => this.once('latest', resolve)) + // return newly set current block + return this._currentBlock + } + + async start (opts = {}) { + // abort if already started + if (this._isRunning) return + this._isRunning = true + // if this._currentBlock + if (opts.fromBlock) { + // use specified start point + await this._setTrackingBlock(await this._fetchBlockByNumber(opts.fromBlock)) + } else { + // or query for latest + await this._setTrackingBlock(await this._fetchLatestBlock()) + } + if (this._provider.on) { + await this._initSubscription() + } else { + this._performSync() + .catch((err) => { + if (err) console.error(err) + }) + } + } + + 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 + const previous = this._trackingBlockTimestamp + const now = Date.now() + // check for desynchronization (computer sleep or no internet) + if (previous && (now - previous) > this._syncingTimeout) { + this._trackingBlockTimestamp = null + await this._warpToLatest() + } else { + this._trackingBlock = newBlock + this._trackingBlockTimestamp = now + this.emit('block', newBlock) + } + } + + async _setCurrentBlock (newBlock) { + if (this._currentBlock && (this._currentBlock.hash === newBlock.hash)) return + const oldBlock = this._currentBlock + this._currentBlock = newBlock + 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 + await this._setTrackingBlock(newBlock) + // ask for next block + this._performSync() + } else { + // set tracking block as current block + await this._setCurrentBlock(trackingBlock) + // 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")) { + // set tracking block as current block + await this._setCurrentBlock(trackingBlock) + // setup poll for next block + this._pollForNextBlock() + } else { + 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(), + method: 'eth_subscribe', + params: [ + '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(), + method: 'eth_unsubscribe', + params: [ + 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 + // ├─ gasUsed: 0x6384 + // ├─ hash: 0xf60903687b1559b9c80f2d935b4c4f468ad95c3076928c432ec34f2ef3d4eec9 + // ├─ logsBloom: 0x00000000000000000000000000000000000000000000000000000000000020000000000000000000000000040000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000 + // ├─ miner: 0x01711853335f857442ef6f349b2467c531731318 + // ├─ mixHash: 0xf0d9bec999600eec92e8e4da8fc1182e357468c9ed2f849aa17e0e900412b352 + // ├─ nonce: 0xd556d5a5504198e4 + // ├─ number: 0x72ac8 + // ├─ parentHash: 0xf5239c3ce1085194521435a5052494c02bbb1002b019684dcf368490ea6208e5 + // ├─ receiptsRoot: 0x78c6f8236094b392bcc43b47b0dc1ce93ecd2875bfb5e4e4c3431e5af698ff99 + // ├─ sha3Uncles: 0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347 + // ├─ size: 0x2ad + // ├─ stateRoot: 0x0554f145c481df2fa02ecd2da17071672740c3aa948c896f1465e6772f741ac6 + // ├─ timestamp: 0x58955844 + // ├─ totalDifficulty: 0x751d0dfa03c1 + // ├─ transactions + // │ └─ 0 + // │ ├─ blockHash: 0xf60903687b1559b9c80f2d935b4c4f468ad95c3076928c432ec34f2ef3d4eec9 + // │ ├─ blockNumber: 0x72ac8 + // │ ├─ from: 0x201354729f8d0f8b64e9a0c353c672c6a66b3857 + // │ ├─ gas: 0x15f90 + // │ ├─ gasPrice: 0x4a817c800 + // │ ├─ hash: 0xd5a15d7c2449150db4f74f42a6ca0702150a24c46c5b406a7e1b3e44908ef44d + // │ ├─ input: 0xe1fa8e849bc10d87fb03c6b0603b05a3e29043c7e0b7c927119576a4bec457e96c7d7cde + // │ ├─ nonce: 0x323e + // │ ├─ to: 0xd10e3be2bc8f959bc8c41cf65f60de721cf89adf + // │ ├─ transactionIndex: 0x0 + // │ ├─ value: 0x0 + // │ ├─ v: 0x29 + // │ ├─ r: 0xf35f8ab241e6bb3ccaffd21b268dbfc7fcb5df1c1fb83ee5306207e4a1a3e954 + // │ └─ 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){ + /** + * [js-sha3]{@link https://github.com/emn178/js-sha3} + * + * @version 0.5.7 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2015-2016 + * @license MIT + */ + /*jslint bitwise: true */ + (function () { + 'use strict'; + + var root = typeof window === 'object' ? window : {}; + var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node; + if (NODE_JS) { + root = global; + } + var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && typeof module === 'object' && module.exports; + var HEX_CHARS = '0123456789abcdef'.split(''); + var SHAKE_PADDING = [31, 7936, 2031616, 520093696]; + var KECCAK_PADDING = [1, 256, 65536, 16777216]; + var PADDING = [6, 1536, 393216, 100663296]; + var SHIFT = [0, 8, 16, 24]; + var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, + 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, + 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, + 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, + 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]; + var BITS = [224, 256, 384, 512]; + var SHAKE_BITS = [128, 256]; + var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array']; + + var createOutputMethod = function (bits, padding, outputType) { + return function (message) { + return new Keccak(bits, padding, bits).update(message)[outputType](); + }; + }; + + var createShakeOutputMethod = function (bits, padding, outputType) { + return function (message, outputBits) { + return new Keccak(bits, padding, outputBits).update(message)[outputType](); + }; + }; + + var createMethod = function (bits, padding) { + var method = createOutputMethod(bits, padding, 'hex'); + method.create = function () { + return new Keccak(bits, padding, bits); + }; + method.update = function (message) { + return method.create().update(message); + }; + for (var i = 0; i < OUTPUT_TYPES.length; ++i) { + var type = OUTPUT_TYPES[i]; + method[type] = createOutputMethod(bits, padding, type); + } + return method; + }; + + var createShakeMethod = function (bits, padding) { + var method = createShakeOutputMethod(bits, padding, 'hex'); + method.create = function (outputBits) { + return new Keccak(bits, padding, outputBits); + }; + method.update = function (message, outputBits) { + return method.create(outputBits).update(message); + }; + for (var i = 0; i < OUTPUT_TYPES.length; ++i) { + var type = OUTPUT_TYPES[i]; + method[type] = createShakeOutputMethod(bits, padding, type); + } + return method; + }; + + var algorithms = [ + {name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod}, + {name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod}, + {name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod} + ]; + + var methods = {}, methodNames = []; + + for (var i = 0; i < algorithms.length; ++i) { + var algorithm = algorithms[i]; + var bits = algorithm.bits; + for (var j = 0; j < bits.length; ++j) { + var methodName = algorithm.name +'_' + bits[j]; + methodNames.push(methodName); + methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding); + } + } + + function Keccak(bits, padding, outputBits) { + this.blocks = []; + this.s = []; + this.padding = padding; + this.outputBits = outputBits; + this.reset = true; + this.block = 0; + this.start = 0; + this.blockCount = (1600 - (bits << 1)) >> 5; + this.byteCount = this.blockCount << 2; + this.outputBlocks = outputBits >> 5; + this.extraBytes = (outputBits & 31) >> 3; + + for (var i = 0; i < 50; ++i) { + this.s[i] = 0; + } + } + + Keccak.prototype.update = function (message) { + var notString = typeof message !== 'string'; + if (notString && message.constructor === ArrayBuffer) { + message = new Uint8Array(message); + } + var length = message.length, blocks = this.blocks, byteCount = this.byteCount, + blockCount = this.blockCount, index = 0, s = this.s, i, code; + + while (index < length) { + if (this.reset) { + this.reset = false; + blocks[0] = this.block; + for (i = 1; i < blockCount + 1; ++i) { + blocks[i] = 0; + } + } + if (notString) { + for (i = this.start; index < length && i < byteCount; ++index) { + blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; + } + } else { + for (i = this.start; index < length && i < byteCount; ++index) { + code = message.charCodeAt(index); + if (code < 0x80) { + blocks[i >> 2] |= code << SHIFT[i++ & 3]; + } else if (code < 0x800) { + blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } else if (code < 0xd800 || code >= 0xe000) { + blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } else { + code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); + blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } + } + } + this.lastByteIndex = i; + if (i >= byteCount) { + this.start = i - byteCount; + this.block = blocks[blockCount]; + for (i = 0; i < blockCount; ++i) { + s[i] ^= blocks[i]; + } + f(s); + this.reset = true; + } else { + this.start = i; + } + } + return this; + }; + + Keccak.prototype.finalize = function () { + var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s; + blocks[i >> 2] |= this.padding[i & 3]; + if (this.lastByteIndex === this.byteCount) { + blocks[0] = blocks[blockCount]; + for (i = 1; i < blockCount + 1; ++i) { + blocks[i] = 0; + } + } + blocks[blockCount - 1] |= 0x80000000; + for (i = 0; i < blockCount; ++i) { + s[i] ^= blocks[i]; + } + f(s); + }; + + Keccak.prototype.toString = Keccak.prototype.hex = function () { + this.finalize(); + + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, + extraBytes = this.extraBytes, i = 0, j = 0; + var hex = '', block; + while (j < outputBlocks) { + for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { + block = s[i]; + hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] + + HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] + + HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] + + HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F]; + } + if (j % blockCount === 0) { + f(s); + i = 0; + } + } + if (extraBytes) { + block = s[i]; + if (extraBytes > 0) { + hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F]; + } + if (extraBytes > 1) { + hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F]; + } + if (extraBytes > 2) { + hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F]; + } + } + return hex; + }; + + Keccak.prototype.arrayBuffer = function () { + this.finalize(); + + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, + extraBytes = this.extraBytes, i = 0, j = 0; + var bytes = this.outputBits >> 3; + var buffer; + if (extraBytes) { + buffer = new ArrayBuffer((outputBlocks + 1) << 2); + } else { + buffer = new ArrayBuffer(bytes); + } + var array = new Uint32Array(buffer); + while (j < outputBlocks) { + for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { + array[j] = s[i]; + } + if (j % blockCount === 0) { + f(s); + } + } + if (extraBytes) { + array[i] = s[i]; + buffer = buffer.slice(0, bytes); + } + return buffer; + }; + + Keccak.prototype.buffer = Keccak.prototype.arrayBuffer; + + Keccak.prototype.digest = Keccak.prototype.array = function () { + this.finalize(); + + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, + extraBytes = this.extraBytes, i = 0, j = 0; + var array = [], offset, block; + while (j < outputBlocks) { + for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { + offset = j << 2; + block = s[i]; + array[offset] = block & 0xFF; + array[offset + 1] = (block >> 8) & 0xFF; + array[offset + 2] = (block >> 16) & 0xFF; + array[offset + 3] = (block >> 24) & 0xFF; + } + if (j % blockCount === 0) { + f(s); + } + } + if (extraBytes) { + offset = j << 2; + block = s[i]; + if (extraBytes > 0) { + array[offset] = block & 0xFF; + } + if (extraBytes > 1) { + array[offset + 1] = (block >> 8) & 0xFF; + } + if (extraBytes > 2) { + array[offset + 2] = (block >> 16) & 0xFF; + } + } + return array; + }; + + var f = function (s) { + var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, + b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, + b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, + b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49; + for (n = 0; n < 48; n += 2) { + c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]; + c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]; + c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]; + c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]; + c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]; + c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]; + c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]; + c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]; + c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]; + c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]; + + h = c8 ^ ((c2 << 1) | (c3 >>> 31)); + l = c9 ^ ((c3 << 1) | (c2 >>> 31)); + s[0] ^= h; + s[1] ^= l; + s[10] ^= h; + s[11] ^= l; + s[20] ^= h; + s[21] ^= l; + s[30] ^= h; + s[31] ^= l; + s[40] ^= h; + s[41] ^= l; + h = c0 ^ ((c4 << 1) | (c5 >>> 31)); + l = c1 ^ ((c5 << 1) | (c4 >>> 31)); + s[2] ^= h; + s[3] ^= l; + s[12] ^= h; + s[13] ^= l; + s[22] ^= h; + s[23] ^= l; + s[32] ^= h; + s[33] ^= l; + s[42] ^= h; + s[43] ^= l; + h = c2 ^ ((c6 << 1) | (c7 >>> 31)); + l = c3 ^ ((c7 << 1) | (c6 >>> 31)); + s[4] ^= h; + s[5] ^= l; + s[14] ^= h; + s[15] ^= l; + s[24] ^= h; + s[25] ^= l; + s[34] ^= h; + s[35] ^= l; + s[44] ^= h; + s[45] ^= l; + h = c4 ^ ((c8 << 1) | (c9 >>> 31)); + l = c5 ^ ((c9 << 1) | (c8 >>> 31)); + s[6] ^= h; + s[7] ^= l; + s[16] ^= h; + s[17] ^= l; + s[26] ^= h; + s[27] ^= l; + s[36] ^= h; + s[37] ^= l; + s[46] ^= h; + s[47] ^= l; + h = c6 ^ ((c0 << 1) | (c1 >>> 31)); + l = c7 ^ ((c1 << 1) | (c0 >>> 31)); + s[8] ^= h; + s[9] ^= l; + s[18] ^= h; + s[19] ^= l; + s[28] ^= h; + s[29] ^= l; + s[38] ^= h; + s[39] ^= l; + s[48] ^= h; + s[49] ^= l; + + b0 = s[0]; + b1 = s[1]; + b32 = (s[11] << 4) | (s[10] >>> 28); + b33 = (s[10] << 4) | (s[11] >>> 28); + b14 = (s[20] << 3) | (s[21] >>> 29); + b15 = (s[21] << 3) | (s[20] >>> 29); + b46 = (s[31] << 9) | (s[30] >>> 23); + b47 = (s[30] << 9) | (s[31] >>> 23); + b28 = (s[40] << 18) | (s[41] >>> 14); + b29 = (s[41] << 18) | (s[40] >>> 14); + b20 = (s[2] << 1) | (s[3] >>> 31); + b21 = (s[3] << 1) | (s[2] >>> 31); + b2 = (s[13] << 12) | (s[12] >>> 20); + b3 = (s[12] << 12) | (s[13] >>> 20); + b34 = (s[22] << 10) | (s[23] >>> 22); + b35 = (s[23] << 10) | (s[22] >>> 22); + b16 = (s[33] << 13) | (s[32] >>> 19); + b17 = (s[32] << 13) | (s[33] >>> 19); + b48 = (s[42] << 2) | (s[43] >>> 30); + b49 = (s[43] << 2) | (s[42] >>> 30); + b40 = (s[5] << 30) | (s[4] >>> 2); + b41 = (s[4] << 30) | (s[5] >>> 2); + b22 = (s[14] << 6) | (s[15] >>> 26); + b23 = (s[15] << 6) | (s[14] >>> 26); + b4 = (s[25] << 11) | (s[24] >>> 21); + b5 = (s[24] << 11) | (s[25] >>> 21); + b36 = (s[34] << 15) | (s[35] >>> 17); + b37 = (s[35] << 15) | (s[34] >>> 17); + b18 = (s[45] << 29) | (s[44] >>> 3); + b19 = (s[44] << 29) | (s[45] >>> 3); + b10 = (s[6] << 28) | (s[7] >>> 4); + b11 = (s[7] << 28) | (s[6] >>> 4); + b42 = (s[17] << 23) | (s[16] >>> 9); + b43 = (s[16] << 23) | (s[17] >>> 9); + b24 = (s[26] << 25) | (s[27] >>> 7); + b25 = (s[27] << 25) | (s[26] >>> 7); + b6 = (s[36] << 21) | (s[37] >>> 11); + b7 = (s[37] << 21) | (s[36] >>> 11); + b38 = (s[47] << 24) | (s[46] >>> 8); + b39 = (s[46] << 24) | (s[47] >>> 8); + b30 = (s[8] << 27) | (s[9] >>> 5); + b31 = (s[9] << 27) | (s[8] >>> 5); + b12 = (s[18] << 20) | (s[19] >>> 12); + b13 = (s[19] << 20) | (s[18] >>> 12); + b44 = (s[29] << 7) | (s[28] >>> 25); + b45 = (s[28] << 7) | (s[29] >>> 25); + b26 = (s[38] << 8) | (s[39] >>> 24); + b27 = (s[39] << 8) | (s[38] >>> 24); + b8 = (s[48] << 14) | (s[49] >>> 18); + b9 = (s[49] << 14) | (s[48] >>> 18); + + s[0] = b0 ^ (~b2 & b4); + s[1] = b1 ^ (~b3 & b5); + s[10] = b10 ^ (~b12 & b14); + s[11] = b11 ^ (~b13 & b15); + s[20] = b20 ^ (~b22 & b24); + s[21] = b21 ^ (~b23 & b25); + s[30] = b30 ^ (~b32 & b34); + s[31] = b31 ^ (~b33 & b35); + s[40] = b40 ^ (~b42 & b44); + s[41] = b41 ^ (~b43 & b45); + s[2] = b2 ^ (~b4 & b6); + s[3] = b3 ^ (~b5 & b7); + s[12] = b12 ^ (~b14 & b16); + s[13] = b13 ^ (~b15 & b17); + s[22] = b22 ^ (~b24 & b26); + s[23] = b23 ^ (~b25 & b27); + s[32] = b32 ^ (~b34 & b36); + s[33] = b33 ^ (~b35 & b37); + s[42] = b42 ^ (~b44 & b46); + s[43] = b43 ^ (~b45 & b47); + s[4] = b4 ^ (~b6 & b8); + s[5] = b5 ^ (~b7 & b9); + s[14] = b14 ^ (~b16 & b18); + s[15] = b15 ^ (~b17 & b19); + s[24] = b24 ^ (~b26 & b28); + s[25] = b25 ^ (~b27 & b29); + s[34] = b34 ^ (~b36 & b38); + s[35] = b35 ^ (~b37 & b39); + s[44] = b44 ^ (~b46 & b48); + s[45] = b45 ^ (~b47 & b49); + s[6] = b6 ^ (~b8 & b0); + s[7] = b7 ^ (~b9 & b1); + s[16] = b16 ^ (~b18 & b10); + s[17] = b17 ^ (~b19 & b11); + s[26] = b26 ^ (~b28 & b20); + s[27] = b27 ^ (~b29 & b21); + s[36] = b36 ^ (~b38 & b30); + s[37] = b37 ^ (~b39 & b31); + s[46] = b46 ^ (~b48 & b40); + s[47] = b47 ^ (~b49 & b41); + s[8] = b8 ^ (~b0 & b2); + s[9] = b9 ^ (~b1 & b3); + s[18] = b18 ^ (~b10 & b12); + s[19] = b19 ^ (~b11 & b13); + s[28] = b28 ^ (~b20 & b22); + s[29] = b29 ^ (~b21 & b23); + s[38] = b38 ^ (~b30 & b32); + s[39] = b39 ^ (~b31 & b33); + s[48] = b48 ^ (~b40 & b42); + s[49] = b49 ^ (~b41 & b43); + + s[0] ^= RC[n]; + s[1] ^= RC[n + 1]; + } + }; + + if (COMMON_JS) { + module.exports = methods; + } else { + for (var i = 0; i < methodNames.length; ++i) { + root[methodNames[i]] = methods[methodNames[i]]; + } + } + })(); + + }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + },{"_process":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 + 'Gateway timeout', + 'ETIMEDOUT', + 'ECONNRESET', + // ignore server sent html error pages + // 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++) { + try { + // attempt request + await performFetch(network, req, res) + // request was succesful + break + } catch (err) { + // an error was caught while performing the request + // if not retriable, resolve with the encountered error + if (!isRetriableError(err)) { + // abort with error + throw err + } + // if no more attempts remaining, throw an error + const remainingAttempts = maxAttempts - attempt + if (!remainingAttempts) { + const errMsg = `InfuraProvider - cannot complete request. All retries exhausted.\nOriginal Error:\n${err.toString()}\n\n` + const retriesExhaustedErr = new Error(errMsg) + throw retriesExhaustedErr + } + // otherwise, ignore error and retry again after timeout + await timeout(1000) + } + } + // 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) + const rawData = await response.text() + // handle errors + if (!response.ok) { + 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) + if (isPostMethod) { + fetchParams.method = 'POST' + fetchParams.headers = { + 'Accept': 'application/json', + 'Content-Type': 'application/json' + }, + fetchParams.body = JSON.stringify(cleanReq) + } else { + fetchParams.method = 'GET' + 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 { + id: req.id, + jsonrpc: req.jsonrpc, + method: req.method, + 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 = []; + for (var i = 0; i < num; ++i) { + a.push(fn(i)); + }return a; + }; + + var replicate = function replicate(num, val) { + return generate(num, function () { + return val; + }); + }; + + var concat = function concat(a, b) { + return a.concat(b); + }; + + var flatten = function flatten(a) { + var r = []; + for (var j = 0, J = a.length; j < J; ++j) { + for (var i = 0, I = a[j].length; i < I; ++i) { + r.push(a[j][i]); + } + }return r; + }; + + var chunksOf = function chunksOf(n, a) { + var b = []; + for (var i = 0, l = a.length; i < l; i += n) { + b.push(a.slice(i, i + n)); + }return b; + }; + + module.exports = { + generate: generate, + replicate: replicate, + concat: concat, + flatten: flatten, + chunksOf: chunksOf + }; + },{}],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."; + var hex = "0x"; + for (var i = 0; i < bytes; ++i) { + hex += ("00" + rnd[i].toString(16)).slice(-2); + }return hex; + }; + + var length = function length(a) { + return (a.length - 2) / 2; + }; + + var flatten = function flatten(a) { + return "0x" + a.reduce(function (r, s) { + return r + s.slice(2); + }, ""); + }; + + var slice = function slice(i, j, bs) { + return "0x" + bs.slice(i * 2 + 2, j * 2 + 2); + }; + + var reverse = function reverse(hex) { + var rev = "0x"; + for (var i = 0, l = length(hex); i < l; ++i) { + rev += hex.slice((l - i) * 2, (l - i + 1) * 2); + } + return rev; + }; + + var pad = function pad(l, hex) { + return hex.length === l * 2 + 2 ? hex : pad(l, "0x" + "0" + hex.slice(2)); + }; + + var padRight = function padRight(l, hex) { + return hex.length === l * 2 + 2 ? hex : padRight(l, hex + "0"); + }; + + var toArray = function toArray(hex) { + var arr = []; + for (var i = 2, l = hex.length; i < l; i += 2) { + arr.push(parseInt(hex.slice(i, i + 2), 16)); + }return arr; + }; + + var fromArray = function fromArray(arr) { + var hex = "0x"; + for (var i = 0, l = arr.length; i < l; ++i) { + var b = arr[i]; + hex += (b < 16 ? "0" : "") + b.toString(16); + } + return hex; + }; + + var toUint8Array = function toUint8Array(hex) { + return new Uint8Array(toArray(hex)); + }; + + var fromUint8Array = function fromUint8Array(arr) { + return fromArray([].slice.call(arr, 0)); + }; + + var fromNumber = function fromNumber(num) { + var hex = num.toString(16); + return hex.length % 2 === 0 ? "0x" + hex : "0x0" + hex; + }; + + var toNumber = function toNumber(hex) { + return parseInt(hex.slice(2), 16); + }; + + var concat = function concat(a, b) { + return a.concat(b.slice(2)); + }; + + var fromNat = function fromNat(bn) { + return bn === "0x0" ? "0x" : bn.length % 2 === 0 ? bn : "0x0" + bn.slice(2); + }; + + var toNat = function toNat(bn) { + return bn[2] === "0" ? "0x" + bn.slice(3) : bn; + }; + + var fromAscii = function fromAscii(ascii) { + var hex = "0x"; + for (var i = 0; i < ascii.length; ++i) { + hex += ("00" + ascii.charCodeAt(i).toString(16)).slice(-2); + }return hex; + }; + + var toAscii = function toAscii(hex) { + var ascii = ""; + for (var i = 2; i < hex.length; i += 2) { + ascii += String.fromCharCode(parseInt(hex.slice(i, i + 2), 16)); + }return ascii; + }; + + // From https://gist.github.com/pascaldekloe/62546103a1576803dade9269ccf76330 + var fromString = function fromString(s) { + var makeByte = function makeByte(uint8) { + var b = uint8.toString(16); + return b.length < 2 ? "0" + b : b; + }; + var bytes = "0x"; + for (var ci = 0; ci != s.length; ci++) { + var c = s.charCodeAt(ci); + if (c < 128) { + bytes += makeByte(c); + continue; + } + if (c < 2048) { + bytes += makeByte(c >> 6 | 192); + } else { + if (c > 0xd7ff && c < 0xdc00) { + if (++ci == s.length) return null; + var c2 = s.charCodeAt(ci); + if (c2 < 0xdc00 || c2 > 0xdfff) return null; + c = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff); + bytes += makeByte(c >> 18 | 240); + bytes += makeByte(c >> 12 & 63 | 128); + } else { + // c <= 0xffff + bytes += makeByte(c >> 12 | 224); + } + bytes += makeByte(c >> 6 & 63 | 128); + } + bytes += makeByte(c & 63 | 128); + } + return bytes; + }; + + var toString = function toString(bytes) { + var s = ''; + var i = 0; + var l = length(bytes); + while (i < l) { + var c = at(bytes, i++); + if (c > 127) { + if (c > 191 && c < 224) { + if (i >= l) return null; + c = (c & 31) << 6 | at(bytes, i) & 63; + } else if (c > 223 && c < 240) { + if (i + 1 >= l) return null; + c = (c & 15) << 12 | (at(bytes, i) & 63) << 6 | at(bytes, ++i) & 63; + } else if (c > 239 && c < 248) { + if (i + 2 >= l) return null; + c = (c & 7) << 18 | (at(bytes, i) & 63) << 12 | (at(bytes, ++i) & 63) << 6 | at(bytes, ++i) & 63; + } else return null; + ++i; + } + if (c <= 0xffff) s += String.fromCharCode(c);else if (c <= 0x10ffff) { + c -= 0x10000; + s += String.fromCharCode(c >> 10 | 0xd800); + s += String.fromCharCode(c & 0x3FF | 0xdc00); + } else return null; + } + return s; + }; + + module.exports = { + random: random, + length: length, + concat: concat, + flatten: flatten, + slice: slice, + reverse: reverse, + pad: pad, + padRight: padRight, + fromAscii: fromAscii, + toAscii: toAscii, + fromString: fromString, + toString: toString, + fromNumber: fromNumber, + toNumber: toNumber, + fromNat: fromNat, + toNat: toNat, + fromArray: fromArray, + toArray: toArray, + fromUint8Array: fromUint8Array, + toUint8Array: toUint8Array + }; + },{"./array.js":132}],134:[function(require,module,exports){ + // This was ported from https://github.com/emn178/js-sha3, with some minor + // modifications and pruning. It is licensed under MIT: + // + // Copyright 2015-2016 Chen, Yi-Cyuan + // + // Permission is hereby granted, free of charge, to any person obtaining + // a copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to + // permit persons to whom the Software is furnished to do so, subject to + // the following conditions: + // + // The above copyright notice and this permission notice shall be + // included in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + var HEX_CHARS = '0123456789abcdef'.split(''); + var KECCAK_PADDING = [1, 256, 65536, 16777216]; + var SHIFT = [0, 8, 16, 24]; + var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]; + + var Keccak = function Keccak(bits) { + return { + blocks: [], + reset: true, + block: 0, + start: 0, + blockCount: 1600 - (bits << 1) >> 5, + outputBlocks: bits >> 5, + s: function (s) { + return [].concat(s, s, s, s, s); + }([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) + }; + }; + + var update = function update(state, message) { + var length = message.length, + blocks = state.blocks, + byteCount = state.blockCount << 2, + blockCount = state.blockCount, + outputBlocks = state.outputBlocks, + s = state.s, + index = 0, + i, + code; + + // update + while (index < length) { + if (state.reset) { + state.reset = false; + blocks[0] = state.block; + for (i = 1; i < blockCount + 1; ++i) { + blocks[i] = 0; + } + } + if (typeof message !== "string") { + for (i = state.start; index < length && i < byteCount; ++index) { + blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; + } + } else { + for (i = state.start; index < length && i < byteCount; ++index) { + code = message.charCodeAt(index); + if (code < 0x80) { + blocks[i >> 2] |= code << SHIFT[i++ & 3]; + } else if (code < 0x800) { + blocks[i >> 2] |= (0xc0 | code >> 6) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3]; + } else if (code < 0xd800 || code >= 0xe000) { + blocks[i >> 2] |= (0xe0 | code >> 12) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | code >> 6 & 0x3f) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3]; + } else { + code = 0x10000 + ((code & 0x3ff) << 10 | message.charCodeAt(++index) & 0x3ff); + blocks[i >> 2] |= (0xf0 | code >> 18) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | code >> 12 & 0x3f) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | code >> 6 & 0x3f) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3]; + } + } + } + state.lastByteIndex = i; + if (i >= byteCount) { + state.start = i - byteCount; + state.block = blocks[blockCount]; + for (i = 0; i < blockCount; ++i) { + s[i] ^= blocks[i]; + } + f(s); + state.reset = true; + } else { + state.start = i; + } + } + + // finalize + i = state.lastByteIndex; + blocks[i >> 2] |= KECCAK_PADDING[i & 3]; + if (state.lastByteIndex === byteCount) { + blocks[0] = blocks[blockCount]; + for (i = 1; i < blockCount + 1; ++i) { + blocks[i] = 0; + } + } + blocks[blockCount - 1] |= 0x80000000; + for (i = 0; i < blockCount; ++i) { + s[i] ^= blocks[i]; + } + f(s); + + // toString + var hex = '', + i = 0, + j = 0, + block; + while (j < outputBlocks) { + for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) { + block = s[i]; + hex += HEX_CHARS[block >> 4 & 0x0F] + HEX_CHARS[block & 0x0F] + HEX_CHARS[block >> 12 & 0x0F] + HEX_CHARS[block >> 8 & 0x0F] + HEX_CHARS[block >> 20 & 0x0F] + HEX_CHARS[block >> 16 & 0x0F] + HEX_CHARS[block >> 28 & 0x0F] + HEX_CHARS[block >> 24 & 0x0F]; + } + if (j % blockCount === 0) { + f(s); + i = 0; + } + } + return "0x" + hex; + }; + + var f = function f(s) { + var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49; + + for (n = 0; n < 48; n += 2) { + c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]; + c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]; + c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]; + c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]; + c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]; + c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]; + c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]; + c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]; + c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]; + c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]; + + h = c8 ^ (c2 << 1 | c3 >>> 31); + l = c9 ^ (c3 << 1 | c2 >>> 31); + s[0] ^= h; + s[1] ^= l; + s[10] ^= h; + s[11] ^= l; + s[20] ^= h; + s[21] ^= l; + s[30] ^= h; + s[31] ^= l; + s[40] ^= h; + s[41] ^= l; + h = c0 ^ (c4 << 1 | c5 >>> 31); + l = c1 ^ (c5 << 1 | c4 >>> 31); + s[2] ^= h; + s[3] ^= l; + s[12] ^= h; + s[13] ^= l; + s[22] ^= h; + s[23] ^= l; + s[32] ^= h; + s[33] ^= l; + s[42] ^= h; + s[43] ^= l; + h = c2 ^ (c6 << 1 | c7 >>> 31); + l = c3 ^ (c7 << 1 | c6 >>> 31); + s[4] ^= h; + s[5] ^= l; + s[14] ^= h; + s[15] ^= l; + s[24] ^= h; + s[25] ^= l; + s[34] ^= h; + s[35] ^= l; + s[44] ^= h; + s[45] ^= l; + h = c4 ^ (c8 << 1 | c9 >>> 31); + l = c5 ^ (c9 << 1 | c8 >>> 31); + s[6] ^= h; + s[7] ^= l; + s[16] ^= h; + s[17] ^= l; + s[26] ^= h; + s[27] ^= l; + s[36] ^= h; + s[37] ^= l; + s[46] ^= h; + s[47] ^= l; + h = c6 ^ (c0 << 1 | c1 >>> 31); + l = c7 ^ (c1 << 1 | c0 >>> 31); + s[8] ^= h; + s[9] ^= l; + s[18] ^= h; + s[19] ^= l; + s[28] ^= h; + s[29] ^= l; + s[38] ^= h; + s[39] ^= l; + s[48] ^= h; + s[49] ^= l; + + b0 = s[0]; + b1 = s[1]; + b32 = s[11] << 4 | s[10] >>> 28; + b33 = s[10] << 4 | s[11] >>> 28; + b14 = s[20] << 3 | s[21] >>> 29; + b15 = s[21] << 3 | s[20] >>> 29; + b46 = s[31] << 9 | s[30] >>> 23; + b47 = s[30] << 9 | s[31] >>> 23; + b28 = s[40] << 18 | s[41] >>> 14; + b29 = s[41] << 18 | s[40] >>> 14; + b20 = s[2] << 1 | s[3] >>> 31; + b21 = s[3] << 1 | s[2] >>> 31; + b2 = s[13] << 12 | s[12] >>> 20; + b3 = s[12] << 12 | s[13] >>> 20; + b34 = s[22] << 10 | s[23] >>> 22; + b35 = s[23] << 10 | s[22] >>> 22; + b16 = s[33] << 13 | s[32] >>> 19; + b17 = s[32] << 13 | s[33] >>> 19; + b48 = s[42] << 2 | s[43] >>> 30; + b49 = s[43] << 2 | s[42] >>> 30; + b40 = s[5] << 30 | s[4] >>> 2; + b41 = s[4] << 30 | s[5] >>> 2; + b22 = s[14] << 6 | s[15] >>> 26; + b23 = s[15] << 6 | s[14] >>> 26; + b4 = s[25] << 11 | s[24] >>> 21; + b5 = s[24] << 11 | s[25] >>> 21; + b36 = s[34] << 15 | s[35] >>> 17; + b37 = s[35] << 15 | s[34] >>> 17; + b18 = s[45] << 29 | s[44] >>> 3; + b19 = s[44] << 29 | s[45] >>> 3; + b10 = s[6] << 28 | s[7] >>> 4; + b11 = s[7] << 28 | s[6] >>> 4; + b42 = s[17] << 23 | s[16] >>> 9; + b43 = s[16] << 23 | s[17] >>> 9; + b24 = s[26] << 25 | s[27] >>> 7; + b25 = s[27] << 25 | s[26] >>> 7; + b6 = s[36] << 21 | s[37] >>> 11; + b7 = s[37] << 21 | s[36] >>> 11; + b38 = s[47] << 24 | s[46] >>> 8; + b39 = s[46] << 24 | s[47] >>> 8; + b30 = s[8] << 27 | s[9] >>> 5; + b31 = s[9] << 27 | s[8] >>> 5; + b12 = s[18] << 20 | s[19] >>> 12; + b13 = s[19] << 20 | s[18] >>> 12; + b44 = s[29] << 7 | s[28] >>> 25; + b45 = s[28] << 7 | s[29] >>> 25; + b26 = s[38] << 8 | s[39] >>> 24; + b27 = s[39] << 8 | s[38] >>> 24; + b8 = s[48] << 14 | s[49] >>> 18; + b9 = s[49] << 14 | s[48] >>> 18; + + s[0] = b0 ^ ~b2 & b4; + s[1] = b1 ^ ~b3 & b5; + s[10] = b10 ^ ~b12 & b14; + s[11] = b11 ^ ~b13 & b15; + s[20] = b20 ^ ~b22 & b24; + s[21] = b21 ^ ~b23 & b25; + s[30] = b30 ^ ~b32 & b34; + s[31] = b31 ^ ~b33 & b35; + s[40] = b40 ^ ~b42 & b44; + s[41] = b41 ^ ~b43 & b45; + s[2] = b2 ^ ~b4 & b6; + s[3] = b3 ^ ~b5 & b7; + s[12] = b12 ^ ~b14 & b16; + s[13] = b13 ^ ~b15 & b17; + s[22] = b22 ^ ~b24 & b26; + s[23] = b23 ^ ~b25 & b27; + s[32] = b32 ^ ~b34 & b36; + s[33] = b33 ^ ~b35 & b37; + s[42] = b42 ^ ~b44 & b46; + s[43] = b43 ^ ~b45 & b47; + s[4] = b4 ^ ~b6 & b8; + s[5] = b5 ^ ~b7 & b9; + s[14] = b14 ^ ~b16 & b18; + s[15] = b15 ^ ~b17 & b19; + s[24] = b24 ^ ~b26 & b28; + s[25] = b25 ^ ~b27 & b29; + s[34] = b34 ^ ~b36 & b38; + s[35] = b35 ^ ~b37 & b39; + s[44] = b44 ^ ~b46 & b48; + s[45] = b45 ^ ~b47 & b49; + s[6] = b6 ^ ~b8 & b0; + s[7] = b7 ^ ~b9 & b1; + s[16] = b16 ^ ~b18 & b10; + s[17] = b17 ^ ~b19 & b11; + s[26] = b26 ^ ~b28 & b20; + s[27] = b27 ^ ~b29 & b21; + s[36] = b36 ^ ~b38 & b30; + s[37] = b37 ^ ~b39 & b31; + s[46] = b46 ^ ~b48 & b40; + s[47] = b47 ^ ~b49 & b41; + s[8] = b8 ^ ~b0 & b2; + s[9] = b9 ^ ~b1 & b3; + s[18] = b18 ^ ~b10 & b12; + s[19] = b19 ^ ~b11 & b13; + s[28] = b28 ^ ~b20 & b22; + s[29] = b29 ^ ~b21 & b23; + s[38] = b38 ^ ~b30 & b32; + s[39] = b39 ^ ~b31 & b33; + s[48] = b48 ^ ~b40 & b42; + s[49] = b49 ^ ~b41 & b43; + + s[0] ^= RC[n]; + s[1] ^= RC[n + 1]; + } + }; + + var keccak = function keccak(bits) { + return function (str) { + var msg; + if (str.slice(0, 2) === "0x") { + msg = []; + for (var i = 2, l = str.length; i < l; i += 2) { + msg.push(parseInt(str.slice(i, i + 2), 16)); + } + } else { + msg = str; + } + return update(Keccak(bits, bits), msg); + }; + }; + + module.exports = { + keccak256: keccak(256), + keccak512: keccak(512), + keccak256s: keccak(256), + keccak512s: keccak(512) + }; + },{}],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') + EthQuery.prototype.getTransactionCount = generateFnWithDefaultBlockFor(2, 'eth_getTransactionCount') + EthQuery.prototype.getStorageAt = generateFnWithDefaultBlockFor(3, 'eth_getStorageAt') + EthQuery.prototype.call = generateFnWithDefaultBlockFor(2, 'eth_call') + // standard + EthQuery.prototype.protocolVersion = generateFnFor('eth_protocolVersion') + EthQuery.prototype.syncing = generateFnFor('eth_syncing') + EthQuery.prototype.coinbase = generateFnFor('eth_coinbase') + EthQuery.prototype.mining = generateFnFor('eth_mining') + EthQuery.prototype.hashrate = generateFnFor('eth_hashrate') + EthQuery.prototype.gasPrice = generateFnFor('eth_gasPrice') + EthQuery.prototype.accounts = generateFnFor('eth_accounts') + EthQuery.prototype.blockNumber = generateFnFor('eth_blockNumber') + EthQuery.prototype.getBlockTransactionCountByHash = generateFnFor('eth_getBlockTransactionCountByHash') + EthQuery.prototype.getBlockTransactionCountByNumber = generateFnFor('eth_getBlockTransactionCountByNumber') + EthQuery.prototype.getUncleCountByBlockHash = generateFnFor('eth_getUncleCountByBlockHash') + EthQuery.prototype.getUncleCountByBlockNumber = generateFnFor('eth_getUncleCountByBlockNumber') + EthQuery.prototype.sign = generateFnFor('eth_sign') + EthQuery.prototype.sendTransaction = generateFnFor('eth_sendTransaction') + EthQuery.prototype.sendRawTransaction = generateFnFor('eth_sendRawTransaction') + EthQuery.prototype.estimateGas = generateFnFor('eth_estimateGas') + EthQuery.prototype.getBlockByHash = generateFnFor('eth_getBlockByHash') + EthQuery.prototype.getBlockByNumber = generateFnFor('eth_getBlockByNumber') + EthQuery.prototype.getTransactionByHash = generateFnFor('eth_getTransactionByHash') + EthQuery.prototype.getTransactionByBlockHashAndIndex = generateFnFor('eth_getTransactionByBlockHashAndIndex') + EthQuery.prototype.getTransactionByBlockNumberAndIndex = generateFnFor('eth_getTransactionByBlockNumberAndIndex') + EthQuery.prototype.getTransactionReceipt = generateFnFor('eth_getTransactionReceipt') + EthQuery.prototype.getUncleByBlockHashAndIndex = generateFnFor('eth_getUncleByBlockHashAndIndex') + EthQuery.prototype.getUncleByBlockNumberAndIndex = generateFnFor('eth_getUncleByBlockNumberAndIndex') + EthQuery.prototype.getCompilers = generateFnFor('eth_getCompilers') + EthQuery.prototype.compileLLL = generateFnFor('eth_compileLLL') + EthQuery.prototype.compileSolidity = generateFnFor('eth_compileSolidity') + EthQuery.prototype.compileSerpent = generateFnFor('eth_compileSerpent') + EthQuery.prototype.newFilter = generateFnFor('eth_newFilter') + EthQuery.prototype.newBlockFilter = generateFnFor('eth_newBlockFilter') + EthQuery.prototype.newPendingTransactionFilter = generateFnFor('eth_newPendingTransactionFilter') + EthQuery.prototype.uninstallFilter = generateFnFor('eth_uninstallFilter') + EthQuery.prototype.getFilterChanges = generateFnFor('eth_getFilterChanges') + EthQuery.prototype.getFilterLogs = generateFnFor('eth_getFilterLogs') + EthQuery.prototype.getLogs = generateFnFor('eth_getLogs') + 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){ + if (!err && response.error) err = new Error('EthQuery - RPC Error - '+response.error.message) + if (err) return cb(err) + cb(null, response.result) + }) + } + + // util + + function generateFnFor(methodName){ + return function(){ + const self = this + var args = [].slice.call(arguments) + var cb = args.pop() + self.sendAsync({ + method: methodName, + params: args, + }, cb) + } + } + + function generateFnWithDefaultBlockFor(argCount, methodName){ + return function(){ + const self = this + var args = [].slice.call(arguments) + var cb = args.pop() + // set optional default block param + if (args.length < argCount) args.push('latest') + self.sendAsync({ + method: methodName, + params: args, + }, cb) + } + } + + function createPayload(data){ + return extend({ + // defaults + id: createRandomId(), + jsonrpc: '2.0', + params: [], + // 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) + const vSig = ethUtil.bufferToInt(v) + const rStr = padWithZeroes(ethUtil.toUnsigned(rSig).toString('hex'), 64) + const sStr = padWithZeroes(ethUtil.toUnsigned(sSig).toString('hex'), 64) + 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) + var sig = ethUtil.ecsign(msgHash, privateKey) + 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 + */ + 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 + }) + const types = typedData.map(function (e) { return e.type }) + const schema = typedData.map(function (e) { + if (!e.name) throw error + return e.type + ' ' + e.name + }) + + return ethAbi.soliditySHA3( + ['bytes32', 'bytes32'], + [ + ethAbi.soliditySHA3(new Array(typedData.length).fill('string'), schema), + ethAbi.soliditySHA3(types, data) + ] + ) + } + + 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) { + myString = '0' + myString + } + return myString + } + + },{"ethereumjs-abi":138,"ethereumjs-util":141}],137:[function(require,module,exports){ + module.exports={ + "genesisGasLimit": { + "v": 5000, + "d": "Gas limit of the Genesis block." + }, + "genesisDifficulty": { + "v": 17179869184, + "d": "Difficulty of the Genesis block." + }, + "genesisNonce": { + "v": "0x0000000000000042", + "d": "the geneis nonce" + }, + "genesisExtraData": { + "v": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa", + "d": "extra data " + }, + "genesisHash": { + "v": "0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3", + "d": "genesis hash" + }, + "genesisStateRoot": { + "v": "0xd7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544", + "d": "the genesis state root" + }, + "minGasLimit": { + "v": 5000, + "d": "Minimum the gas limit may ever be." + }, + "gasLimitBoundDivisor": { + "v": 1024, + "d": "The bound divisor of the gas limit, used in update calculations." + }, + "minimumDifficulty": { + "v": 131072, + "d": "The minimum that the difficulty may ever be." + }, + "difficultyBoundDivisor": { + "v": 2048, + "d": "The bound divisor of the difficulty, used in the update calculations." + }, + "durationLimit": { + "v": 13, + "d": "The decision boundary on the blocktime duration used to determine whether difficulty should go up or not." + }, + "maximumExtraDataSize": { + "v": 32, + "d": "Maximum size extra data may be after Genesis." + }, + "epochDuration": { + "v": 30000, + "d": "Duration between proof-of-work epochs." + }, + "stackLimit": { + "v": 1024, + "d": "Maximum size of VM stack allowed." + }, + "callCreateDepth": { + "v": 1024, + "d": "Maximum depth of call/create stack." + }, + + "tierStepGas": { + "v": [0, 2, 3, 5, 8, 10, 20], + "d": "Once per operation, for a selection of them." + }, + "expGas": { + "v": 10, + "d": "Once per EXP instuction." + }, + "expByteGas": { + "v": 10, + "d": "Times ceil(log256(exponent)) for the EXP instruction." + }, + + "sha3Gas": { + "v": 30, + "d": "Once per SHA3 operation." + }, + "sha3WordGas": { + "v": 6, + "d": "Once per word of the SHA3 operation's data." + }, + "sloadGas": { + "v": 50, + "d": "Once per SLOAD operation." + }, + "sstoreSetGas": { + "v": 20000, + "d": "Once per SSTORE operation if the zeroness changes from zero." + }, + "sstoreResetGas": { + "v": 5000, + "d": "Once per SSTORE operation if the zeroness does not change from zero." + }, + "sstoreRefundGas": { + "v": 15000, + "d": "Once per SSTORE operation if the zeroness changes to zero." + }, + "jumpdestGas": { + "v": 1, + "d": "Refunded gas, once per SSTORE operation if the zeroness changes to zero." + }, + + "logGas": { + "v": 375, + "d": "Per LOG* operation." + }, + "logDataGas": { + "v": 8, + "d": "Per byte in a LOG* operation's data." + }, + "logTopicGas": { + "v": 375, + "d": "Multiplied by the * of the LOG*, per LOG transaction. e.g. LOG0 incurs 0 * c_txLogTopicGas, LOG4 incurs 4 * c_txLogTopicGas." + }, + + "createGas": { + "v": 32000, + "d": "Once per CREATE operation & contract-creation transaction." + }, + + "callGas": { + "v": 40, + "d": "Once per CALL operation & message call transaction." + }, + "callStipend": { + "v": 2300, + "d": "Free gas given at beginning of call." + }, + "callValueTransferGas": { + "v": 9000, + "d": "Paid for CALL when the value transfor is non-zero." + }, + "callNewAccountGas": { + "v": 25000, + "d": "Paid for CALL when the destination address didn't exist prior." + }, + + "suicideRefundGas": { + "v": 24000, + "d": "Refunded following a suicide operation." + }, + + "memoryGas": { + "v": 3, + "d": "Times the address of the (highest referenced byte in memory + 1). NOTE: referencing happens on read, write and in instructions such as RETURN and CALL." + }, + "quadCoeffDiv": { + "v": 512, + "d": "Divisor for the quadratic particle of the memory cost equation." + }, + + "createDataGas": { + "v": 200, + "d": "" + }, + "txGas": { + "v": 21000, + "d": "Per transaction. NOTE: Not payable on data of calls between transactions." + }, + "txCreation": { + "v": 32000, + "d": "the cost of creating a contract via tx" + }, + "txDataZeroGas": { + "v": 4, + "d": "Per byte of data attached to a transaction that equals zero. NOTE: Not payable on data of calls between transactions." + }, + "txDataNonZeroGas": { + "v": 68, + "d": "Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions." + }, + + "copyGas": { + "v": 3, + "d": "Multiplied by the number of 32-byte words that are copied (round up) for any *COPY operation and added." + }, + + "ecrecoverGas": { + "v": 3000, + "d": "" + }, + "sha256Gas": { + "v": 60, + "d": "" + }, + "sha256WordGas": { + "v": 12, + "d": "" + }, + "ripemd160Gas": { + "v": 600, + "d": "" + }, + "ripemd160WordGas": { + "v": 120, + "d": "" + }, + "identityGas": { + "v": 15, + "d": "" + }, + "identityWordGas": { + "v": 3, + "d": "" + }, + "minerReward": { + "v": "5000000000000000000", + "d": "the amount a miner get rewarded for mining a block" + }, + "ommerReward": { + "v": "625000000000000000", + "d": "The amount of wei a miner of an uncle block gets for being inculded in the blockchain" + }, + "niblingReward": { + "v": "156250000000000000", + "d": "the amount a miner gets for inculding a uncle" + }, + "homeSteadForkNumber": { + "v": 1150000, + "d": "the block that the Homestead fork started at" + }, + "homesteadRepriceForkNumber": { + "v": 2463000, + "d": "the block that the Homestead Reprice (EIP150) fork started at" + }, + "timebombPeriod": { + "v": 100000, + "d": "Exponential difficulty timebomb period" + }, + "freeBlockPeriod": { + "v": 2 + } + } + + },{}],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) { + if (name.startsWith('int[')) { + return 'int256' + name.slice(3) + } else if (name === 'int') { + return 'int256' + } else if (name.startsWith('uint[')) { + return 'uint256' + name.slice(4) + } else if (name === 'uint') { + return 'uint256' + } else if (name.startsWith('fixed[')) { + return 'fixed128x128' + name.slice(5) + } else if (name === 'fixed') { + return 'fixed128x128' + } else if (name.startsWith('ufixed[')) { + return 'ufixed128x128' + name.slice(6) + } else if (name === 'ufixed') { + return 'ufixed128x128' + } + 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(/(.*)\[(.*?)\]$/) + if (tmp) { + return tmp[2] === '' ? 'dynamic' : parseInt(tmp[2], 10) + } + return null + } + + function parseNumber (arg) { + var type = typeof arg + if (type === 'string') { + if (utils.isHexPrefixed(arg)) { + return new BN(utils.stripHexPrefix(arg), 16) + } else { + return new BN(arg, 10) + } + } else if (type === 'number') { + return new BN(arg) + } else if (arg.toArray) { + // assume this is a BN for the moment, replace with BN.isBN soon + return arg + } else { + throw new Error('Argument is not a number') + } + } + + // someMethod(bytes,uint) + // someMethod(bytes,uint):(boolean) + function parseSignature (sig) { + var tmp = /^(\w+)\((.+)\)$/.exec(sig) + 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], + args: args[1].split(','), + retargs: args[2].split(',') + } + } else { + return { + method: tmp[1], + args: tmp[2].split(',') + } + } + } + + // 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') { + return encodeSingle('uint8', arg ? 1 : 0) + } else if (type === 'string') { + return encodeSingle('bytes', new Buffer(arg, 'utf8')) + } else if (isArray(type)) { + // this part handles fixed-length ([2]) and variable length ([]) arrays + // NOTE: we catch here all calls to arrays, that simplifies the rest + if (typeof arg.length === 'undefined') { + throw new Error('Not an array?') + } + size = parseTypeArray(type) + if (size !== 'dynamic' && size !== 0 && arg.length > size) { + throw new Error('Elements exceed array size: ' + size) + } + ret = [] + type = type.slice(0, type.lastIndexOf('[')) + if (typeof arg === 'string') { + arg = JSON.parse(arg) + } + for (i in arg) { + ret.push(encodeSingle(type, arg[i])) + } + if (size === 'dynamic') { + var length = encodeSingle('uint256', arg.length) + ret.unshift(length) + } + 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 + function decodeSingle (parsedType, data, offset) { + if (typeof parsedType === 'string') { + 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') { + return decodeSingle(parsedType.rawType, data, offset).toString() === new BN(1).toString() + } else if (parsedType.name === 'string') { + var bytes = decodeSingle(parsedType.rawType, data, offset) + return new Buffer(bytes, 'utf8').toString() + } else if (parsedType.isArray) { + // this part handles fixed-length arrays ([2]) and variable length ([]) arrays + // 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() + offset = offset + 32 + } + for (i = 0; i < size; i++) { + var decoded = decodeSingle(parsedType.subArray, data, offset) + ret.push(decoded) + offset += parsedType.subArray.memoryUsage + } + return ret + } else if (parsedType.name === 'bytes') { + offset = decodeSingle('uint256', data, offset).toNumber() + size = decodeSingle('uint256', data, offset).toNumber() + return data.slice(offset + 32, offset + 32 + size) + } else if (parsedType.name.startsWith('bytes')) { + return data.slice(offset, offset + parsedType.size) + } else if (parsedType.name.startsWith('uint')) { + num = new BN(data.slice(offset, offset + 32), 16, 'be') + if (num.bitLength() > parsedType.size) { + throw new Error('Decoded int exceeds width: ' + parsedType.size + ' vs ' + num.bitLength()) + } + return num + } else if (parsedType.name.startsWith('int')) { + num = new BN(data.slice(offset, offset + 32), 16, 'be').fromTwos(256) + 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])) + num = decodeSingle('uint256', data, offset) + if (!num.mod(size).isZero()) { + throw new Error('Decimals not supported yet') + } + return num.div(size) + } else if (parsedType.name.startsWith('fixed')) { + size = new BN(2).pow(new BN(parsedType.size[1])) + num = decodeSingle('int256', data, offset) + if (!num.mod(size).isZero()) { + throw new Error('Decimals not supported yet') + } + return num.div(size) + } + 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) { + var size + var ret + if (isArray(type)) { + size = parseTypeArray(type) + var subArray = type.slice(0, type.lastIndexOf('[')) + subArray = parseType(subArray) + ret = { + isArray: true, + name: type, + size: size, + memoryUsage: size === 'dynamic' ? 32 : subArray.memoryUsage * size, + subArray: subArray + } + return ret + } else { + var rawType + switch (type) { + case 'address': + rawType = 'uint160' + break + case 'bool': + rawType = 'uint8' + break + case 'string': + rawType = 'bytes' + break + } + ret = { + rawType: rawType, + 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) + } + if ((type.startsWith('uint') || type.startsWith('int')) && (ret.size % 8 || ret.size < 8 || ret.size > 256)) { + throw new Error('Invalid int/uint width: ' + ret.size) + } + 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 { + headLength += 32 + } + } else { + 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)) + data.push(cur) + headLength += cur.length + } else { + output.push(cur) + } + } + + return Buffer.concat(output.concat(data)) + } + + ABI.rawDecode = function (types, data) { + var ret = [] + data = new Buffer(data) + var offset = 0 + for (var i = 0; i < types.length; i++) { + var type = elementaryName(types[i]) + var parsed = parseType(type, data, offset) + var decoded = decodeSingle(parsed, data, offset) + offset += parsed.memoryUsage + ret.push(decoded) + } + 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') + } else { + 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) { + return stringify(type, item) + }).join(', ') + } 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') { + ret.push(new Buffer(value, 'utf8')) + } else if (type === 'bool') { + ret.push(new Buffer(value ? '01' : '00', 'hex')) + } else if (type === 'address') { + ret.push(utils.setLengthLeft(value, 20)) + } else if (type.startsWith('bytes')) { + size = parseTypeN(type) + 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 = [] + for (var i = 0; i < sig.length; i++) { + var type = sig[i] + if (type === 's') { + ret.push('bytes') + } else if (type === 'b') { + var tmp = 'bytes' + var j = i + 1 + while ((j < sig.length) && isNumeric(sig[j])) { + tmp += sig[j] - '0' + j++ + } + i = j - 1 + ret.push(tmp) + } else if (type === 'i') { + ret.push('int256') + } else if (type === 'a') { + ret.push('int256[]') + } else { + throw new Error('Unsupported or invalid type: ' + type) + } + } + return ret + } + + ABI.toSerpent = function (types) { + var ret = [] + for (var i = 0; i < types.length; i++) { + var type = types[i] + if (type === 'bytes') { + ret.push('s') + } else if (type.startsWith('bytes')) { + ret.push('b' + parseTypeN(type)) + } else if (type === 'int256') { + ret.push('i') + } else if (type === 'int256[]') { + ret.push('a') + } else { + throw new Error('Unsupported or invalid type: ' + type) + } + } + 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. + * + * @example + * var rawTx = { + * nonce: '00', + * gasPrice: '09184e72a000', + * gasLimit: '2710', + * to: '0000000000000000000000000000000000000000', + * value: '00', + * data: '7f7465737432000000000000000000000000000000000000000000000000000000600057', + * v: '1c', + * r: '5e1d3a76fbf824220eafc8c79ad578ad2b67d01b0c2425eb1f1347e8f50882ab', + * s: '5bd428537f05f9830e93792f90ea6a3e2d1ee84952dd96edbae9f658f831ab13' + * }; + * var tx = new Transaction(rawTx); + * + * @class + * @param {Buffer | Array | Object} data a transaction can be initiailized with either a buffer containing the RLP serialized transaction or an array of buffers relating to each of the tx Properties, listed in order below in the exmple. + * + * Or lastly an Object containing the Properties of the transaction like in the Usage example. + * + * For Object and Arrays each of the elements can either be a Buffer, a hex-prefixed (0x) String , Number, or an object with a toBuffer method such as Bignum + * + * @property {Buffer} raw The raw rlp encoded transaction + * @param {Buffer} data.nonce nonce number + * @param {Buffer} data.gasLimit transaction gas limit + * @param {Buffer} data.gasPrice transaction gas price + * @param {Buffer} data.to to the to address + * @param {Buffer} data.value the amount of ether sent + * @param {Buffer} data.data this will contain the data of the message or the init of a contract + * @param {Buffer} data.v EC signature parameter + * @param {Buffer} data.r EC signature parameter + * @param {Buffer} data.s EC recovery ID + * @param {Number} data.chainId EIP 155 chainId - mainnet: 1, ropsten: 3 + * */ + + var Transaction = function () { + function Transaction(data) { + _classCallCheck(this, Transaction); + + data = data || {}; + // Define Properties + var fields = [{ + name: 'nonce', + length: 32, + allowLess: true, + default: new Buffer([]) + }, { + name: 'gasPrice', + length: 32, + allowLess: true, + default: new Buffer([]) + }, { + name: 'gasLimit', + alias: 'gas', + length: 32, + allowLess: true, + default: new Buffer([]) + }, { + name: 'to', + allowZero: true, + length: 20, + default: new Buffer([]) + }, { + name: 'value', + length: 32, + allowLess: true, + default: new Buffer([]) + }, { + name: 'data', + alias: 'input', + allowZero: true, + default: new Buffer([]) + }, { + name: 'v', + allowZero: true, + default: new Buffer([0x1c]) + }, { + name: 'r', + length: 32, + allowZero: true, + allowLess: true, + default: new Buffer([]) + }, { + name: 's', + length: 32, + allowZero: true, + allowLess: true, + default: new Buffer([]) + }]; + + /** + * Returns the rlp encoding of the transaction + * @method serialize + * @return {Buffer} + * @memberof Transaction + * @name serialize + */ + // attached serialize + ethUtil.defineProperties(this, fields, data); + + /** + * @property {Buffer} from (read only) sender address of this transaction, mathematically derived from other parameters. + * @name from + * @memberof Transaction + */ + Object.defineProperty(this, 'from', { + enumerable: true, + configurable: true, + get: this.getSenderAddress.bind(this) + }); + + // calculate chainId from signature + var sigV = ethUtil.bufferToInt(this.v); + var chainId = Math.floor((sigV - 35) / 2); + if (chainId < 0) chainId = 0; + + // set chainId + this._chainId = chainId || data.chainId || 0; + this._homestead = true; + } + + /** + * If the tx's `to` is to the creation address + * @return {Boolean} + */ + + + Transaction.prototype.toCreationAddress = function toCreationAddress() { + return this.to.toString('hex') === ''; + }; + + /** + * Computes a sha3-256 hash of the serialized tx + * @param {Boolean} [includeSignature=true] whether or not to inculde the signature + * @return {Buffer} + */ + + + Transaction.prototype.hash = function hash(includeSignature) { + if (includeSignature === undefined) includeSignature = true; + + // EIP155 spec: + // when computing the hash of a transaction for purposes of signing or recovering, + // instead of hashing only the first six elements (ie. nonce, gasprice, startgas, to, value, data), + // hash nine elements, with v replaced by CHAIN_ID, r = 0 and s = 0 + + var items = void 0; + if (includeSignature) { + items = this.raw; + } else { + if (this._chainId > 0) { + var raw = this.raw.slice(); + this.v = this._chainId; + this.r = 0; + this.s = 0; + items = this.raw; + this.raw = raw; + } else { + items = this.raw.slice(0, 6); + } + } + + // create hash + return ethUtil.rlphash(items); + }; + + /** + * returns the public key of the sender + * @return {Buffer} + */ + + + Transaction.prototype.getChainId = function getChainId() { + return this._chainId; + }; + + /** + * returns the sender's address + * @return {Buffer} + */ + + + Transaction.prototype.getSenderAddress = function getSenderAddress() { + if (this._from) { + return this._from; + } + var pubkey = this.getSenderPublicKey(); + this._from = ethUtil.publicToAddress(pubkey); + return this._from; + }; + + /** + * returns the public key of the sender + * @return {Buffer} + */ + + + Transaction.prototype.getSenderPublicKey = function getSenderPublicKey() { + if (!this._senderPubKey || !this._senderPubKey.length) { + if (!this.verifySignature()) throw new Error('Invalid Signature'); + } + return this._senderPubKey; + }; + + /** + * Determines if the signature is valid + * @return {Boolean} + */ + + + Transaction.prototype.verifySignature = function verifySignature() { + var msgHash = this.hash(false); + // All transaction signatures whose s-value is greater than secp256k1n/2 are considered invalid. + if (this._homestead && new BN(this.s).cmp(N_DIV_2) === 1) { + return false; + } + + try { + var v = ethUtil.bufferToInt(this.v); + if (this._chainId > 0) { + v -= this._chainId * 2 + 8; + } + this._senderPubKey = ethUtil.ecrecover(msgHash, v, this.r, this.s); + } catch (e) { + return false; + } + + return !!this._senderPubKey; + }; + + /** + * sign a transaction with a given a private key + * @param {Buffer} privateKey + */ + + + Transaction.prototype.sign = function sign(privateKey) { + var msgHash = this.hash(false); + var sig = ethUtil.ecsign(msgHash, privateKey); + if (this._chainId > 0) { + sig.v += this._chainId * 2 + 8; + } + Object.assign(this, sig); + }; + + /** + * The amount of gas paid for the data in this tx + * @return {BN} + */ + + + Transaction.prototype.getDataFee = function getDataFee() { + var data = this.raw[5]; + var cost = new BN(0); + for (var i = 0; i < data.length; i++) { + data[i] === 0 ? cost.iaddn(fees.txDataZeroGas.v) : cost.iaddn(fees.txDataNonZeroGas.v); + } + return cost; + }; + + /** + * the minimum amount of gas the tx must have (DataFee + TxFee + Creation Fee) + * @return {BN} + */ + + + Transaction.prototype.getBaseFee = function getBaseFee() { + var fee = this.getDataFee().iaddn(fees.txGas.v); + if (this._homestead && this.toCreationAddress()) { + fee.iaddn(fees.txCreation.v); + } + return fee; + }; + + /** + * the up front amount that an account must have for this transaction to be valid + * @return {BN} + */ + + + Transaction.prototype.getUpfrontCost = function getUpfrontCost() { + return new BN(this.gasLimit).imul(new BN(this.gasPrice)).iadd(new BN(this.value)); + }; + + /** + * validates the signature and checks to see if it has enough gas + * @param {Boolean} [stringError=false] whether to return a string with a dscription of why the validation failed or return a Bloolean + * @return {Boolean|String} + */ + + + Transaction.prototype.validate = function validate(stringError) { + var errors = []; + if (!this.verifySignature()) { + errors.push('Invalid Signature'); + } + + if (this.getBaseFee().cmp(new BN(this.gasLimit)) > 0) { + errors.push(['gas limit is too low. Need at least ' + this.getBaseFee()]); + } + + if (stringError === undefined || stringError === false) { + return errors.length === 0; + } else { + return errors.join(' '); + } + }; + + return Transaction; + }(); + + module.exports = Transaction; + }).call(this,require("buffer").Buffer) + },{"buffer":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'); + var rlp = require('rlp'); + var BN = require('bn.js'); + var createHash = require('create-hash'); + var Buffer = require('safe-buffer').Buffer; + Object.assign(exports, require('ethjs-util')); + + /** + * the max integer that this VM can handle (a ```BN```) + * @var {BN} MAX_INTEGER + */ + exports.MAX_INTEGER = new BN('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16); + + /** + * 2^256 (a ```BN```) + * @var {BN} TWO_POW256 + */ + exports.TWO_POW256 = new BN('10000000000000000000000000000000000000000000000000000000000000000', 16); + + /** + * Keccak-256 hash of null (a ```String```) + * @var {String} KECCAK256_NULL_S + */ + exports.KECCAK256_NULL_S = 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'; + exports.SHA3_NULL_S = exports.KECCAK256_NULL_S; + + /** + * Keccak-256 hash of null (a ```Buffer```) + * @var {Buffer} KECCAK256_NULL + */ + exports.KECCAK256_NULL = Buffer.from(exports.KECCAK256_NULL_S, 'hex'); + exports.SHA3_NULL = exports.KECCAK256_NULL; + + /** + * Keccak-256 of an RLP of an empty array (a ```String```) + * @var {String} KECCAK256_RLP_ARRAY_S + */ + exports.KECCAK256_RLP_ARRAY_S = '1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347'; + exports.SHA3_RLP_ARRAY_S = exports.KECCAK256_RLP_ARRAY_S; + + /** + * Keccak-256 of an RLP of an empty array (a ```Buffer```) + * @var {Buffer} KECCAK256_RLP_ARRAY + */ + exports.KECCAK256_RLP_ARRAY = Buffer.from(exports.KECCAK256_RLP_ARRAY_S, 'hex'); + exports.SHA3_RLP_ARRAY = exports.KECCAK256_RLP_ARRAY; + + /** + * Keccak-256 hash of the RLP of null (a ```String```) + * @var {String} KECCAK256_RLP_S + */ + exports.KECCAK256_RLP_S = '56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421'; + exports.SHA3_RLP_S = exports.KECCAK256_RLP_S; + + /** + * Keccak-256 hash of the RLP of null (a ```Buffer```) + * @var {Buffer} KECCAK256_RLP + */ + exports.KECCAK256_RLP = Buffer.from(exports.KECCAK256_RLP_S, 'hex'); + exports.SHA3_RLP = exports.KECCAK256_RLP; + + /** + * [`BN`](https://github.com/indutny/bn.js) + * @var {Function} + */ + exports.BN = BN; + + /** + * [`rlp`](https://github.com/ethereumjs/rlp) + * @var {Function} + */ + exports.rlp = rlp; + + /** + * [`secp256k1`](https://github.com/cryptocoinjs/secp256k1-node/) + * @var {Object} + */ + exports.secp256k1 = secp256k1; + + /** + * Returns a buffer filled with 0s + * @method zeros + * @param {Number} bytes the number of bytes the buffer should be + * @return {Buffer} + */ + exports.zeros = function (bytes) { + return Buffer.allocUnsafe(bytes).fill(0); + }; + + /** + * Returns a zero address + * @method zeroAddress + * @return {String} + */ + exports.zeroAddress = function () { + var addressLength = 20; + var zeroAddress = exports.zeros(addressLength); + return exports.bufferToHex(zeroAddress); + }; + + /** + * Left Pads an `Array` or `Buffer` with leading zeros till it has `length` bytes. + * Or it truncates the beginning if it exceeds. + * @method lsetLength + * @param {Buffer|Array} msg the value to pad + * @param {Number} length the number of bytes the output should be + * @param {Boolean} [right=false] whether to start padding form the left or right + * @return {Buffer|Array} + */ + exports.setLengthLeft = exports.setLength = function (msg, length, right) { + var buf = exports.zeros(length); + msg = exports.toBuffer(msg); + if (right) { + if (msg.length < length) { + msg.copy(buf); + return buf; + } + return msg.slice(0, length); + } else { + if (msg.length < length) { + msg.copy(buf, length - msg.length); + return buf; + } + return msg.slice(-length); + } + }; + + /** + * Right Pads an `Array` or `Buffer` with leading zeros till it has `length` bytes. + * Or it truncates the beginning if it exceeds. + * @param {Buffer|Array} msg the value to pad + * @param {Number} length the number of bytes the output should be + * @return {Buffer|Array} + */ + exports.setLengthRight = function (msg, length) { + return exports.setLength(msg, length, true); + }; + + /** + * Trims leading zeros from a `Buffer` or an `Array` + * @param {Buffer|Array|String} a + * @return {Buffer|Array|String} + */ + exports.unpad = exports.stripZeros = function (a) { + a = exports.stripHexPrefix(a); + var first = a[0]; + while (a.length > 0 && first.toString() === '0') { + a = a.slice(1); + first = a[0]; + } + return a; + }; + /** + * Attempts to turn a value into a `Buffer`. As input it supports `Buffer`, `String`, `Number`, null/undefined, `BN` and other objects with a `toArray()` method. + * @param {*} v the value + */ + exports.toBuffer = function (v) { + if (!Buffer.isBuffer(v)) { + if (Array.isArray(v)) { + v = Buffer.from(v); + } else if (typeof v === 'string') { + if (exports.isHexString(v)) { + v = Buffer.from(exports.padToEven(exports.stripHexPrefix(v)), 'hex'); + } else { + v = Buffer.from(v); + } + } else if (typeof v === 'number') { + v = exports.intToBuffer(v); + } else if (v === null || v === undefined) { + v = Buffer.allocUnsafe(0); + } else if (BN.isBN(v)) { + v = v.toArrayLike(Buffer); + } else if (v.toArray) { + // converts a BN to a Buffer + v = Buffer.from(v.toArray()); + } else { + throw new Error('invalid type'); + } + } + return v; + }; + + /** + * Converts a `Buffer` to a `Number` + * @param {Buffer} buf + * @return {Number} + * @throws If the input number exceeds 53 bits. + */ + exports.bufferToInt = function (buf) { + return new BN(exports.toBuffer(buf)).toNumber(); + }; + + /** + * Converts a `Buffer` into a hex `String` + * @param {Buffer} buf + * @return {String} + */ + exports.bufferToHex = function (buf) { + buf = exports.toBuffer(buf); + return '0x' + buf.toString('hex'); + }; + + /** + * Interprets a `Buffer` as a signed integer and returns a `BN`. Assumes 256-bit numbers. + * @param {Buffer} num + * @return {BN} + */ + exports.fromSigned = function (num) { + return new BN(num).fromTwos(256); + }; + + /** + * Converts a `BN` to an unsigned integer and returns it as a `Buffer`. Assumes 256-bit numbers. + * @param {BN} num + * @return {Buffer} + */ + exports.toUnsigned = function (num) { + return Buffer.from(num.toTwos(256).toArray()); + }; + + /** + * Creates Keccak hash of the input + * @param {Buffer|Array|String|Number} a the input data + * @param {Number} [bits=256] the Keccak width + * @return {Buffer} + */ + exports.keccak = function (a, bits) { + a = exports.toBuffer(a); + if (!bits) bits = 256; + + return createKeccakHash('keccak' + bits).update(a).digest(); + }; + + /** + * Creates Keccak-256 hash of the input, alias for keccak(a, 256) + * @param {Buffer|Array|String|Number} a the input data + * @return {Buffer} + */ + exports.keccak256 = function (a) { + return exports.keccak(a); + }; + + /** + * Creates SHA-3 (Keccak) hash of the input [OBSOLETE] + * @param {Buffer|Array|String|Number} a the input data + * @param {Number} [bits=256] the SHA-3 width + * @return {Buffer} + */ + exports.sha3 = exports.keccak; + + /** + * Creates SHA256 hash of the input + * @param {Buffer|Array|String|Number} a the input data + * @return {Buffer} + */ + exports.sha256 = function (a) { + a = exports.toBuffer(a); + return createHash('sha256').update(a).digest(); + }; + + /** + * Creates RIPEMD160 hash of the input + * @param {Buffer|Array|String|Number} a the input data + * @param {Boolean} padded whether it should be padded to 256 bits or not + * @return {Buffer} + */ + exports.ripemd160 = function (a, padded) { + a = exports.toBuffer(a); + var hash = createHash('rmd160').update(a).digest(); + if (padded === true) { + return exports.setLength(hash, 32); + } else { + return hash; + } + }; + + /** + * Creates SHA-3 hash of the RLP encoded version of the input + * @param {Buffer|Array|String|Number} a the input data + * @return {Buffer} + */ + exports.rlphash = function (a) { + return exports.keccak(rlp.encode(a)); + }; + + /** + * Checks if the private key satisfies the rules of the curve secp256k1. + * @param {Buffer} privateKey + * @return {Boolean} + */ + exports.isValidPrivate = function (privateKey) { + return secp256k1.privateKeyVerify(privateKey); + }; + + /** + * Checks if the public key satisfies the rules of the curve secp256k1 + * and the requirements of Ethereum. + * @param {Buffer} publicKey The two points of an uncompressed key, unless sanitize is enabled + * @param {Boolean} [sanitize=false] Accept public keys in other formats + * @return {Boolean} + */ + exports.isValidPublic = function (publicKey, sanitize) { + if (publicKey.length === 64) { + // Convert to SEC1 for secp256k1 + return secp256k1.publicKeyVerify(Buffer.concat([Buffer.from([4]), publicKey])); + } + + if (!sanitize) { + return false; + } + + return secp256k1.publicKeyVerify(publicKey); + }; + + /** + * Returns the ethereum address of a given public key. + * Accepts "Ethereum public keys" and SEC1 encoded keys. + * @param {Buffer} pubKey The two points of an uncompressed key, unless sanitize is enabled + * @param {Boolean} [sanitize=false] Accept public keys in other formats + * @return {Buffer} + */ + exports.pubToAddress = exports.publicToAddress = function (pubKey, sanitize) { + pubKey = exports.toBuffer(pubKey); + if (sanitize && pubKey.length !== 64) { + pubKey = secp256k1.publicKeyConvert(pubKey, false).slice(1); + } + assert(pubKey.length === 64); + // Only take the lower 160bits of the hash + return exports.keccak(pubKey).slice(-20); + }; + + /** + * Returns the ethereum public key of a given private key + * @param {Buffer} privateKey A private key must be 256 bits wide + * @return {Buffer} + */ + var privateToPublic = exports.privateToPublic = function (privateKey) { + privateKey = exports.toBuffer(privateKey); + // skip the type flag and use the X, Y points + return secp256k1.publicKeyCreate(privateKey, false).slice(1); + }; + + /** + * Converts a public key to the Ethereum format. + * @param {Buffer} publicKey + * @return {Buffer} + */ + exports.importPublic = function (publicKey) { + publicKey = exports.toBuffer(publicKey); + if (publicKey.length !== 64) { + publicKey = secp256k1.publicKeyConvert(publicKey, false).slice(1); + } + return publicKey; + }; + + /** + * ECDSA sign + * @param {Buffer} msgHash + * @param {Buffer} privateKey + * @return {Object} + */ + exports.ecsign = function (msgHash, privateKey) { + var sig = secp256k1.sign(msgHash, privateKey); + + var ret = {}; + ret.r = sig.signature.slice(0, 32); + ret.s = sig.signature.slice(32, 64); + ret.v = sig.recovery + 27; + return ret; + }; + + /** + * Returns the keccak-256 hash of `message`, prefixed with the header used by the `eth_sign` RPC call. + * The output of this function can be fed into `ecsign` to produce the same signature as the `eth_sign` + * call for a given `message`, or fed to `ecrecover` along with a signature to recover the public key + * used to produce the signature. + * @param message + * @returns {Buffer} hash + */ + exports.hashPersonalMessage = function (message) { + var prefix = exports.toBuffer('\x19Ethereum Signed Message:\n' + message.length.toString()); + return exports.keccak(Buffer.concat([prefix, message])); + }; + + /** + * ECDSA public key recovery from signature + * @param {Buffer} msgHash + * @param {Number} v + * @param {Buffer} r + * @param {Buffer} s + * @return {Buffer} publicKey + */ + exports.ecrecover = function (msgHash, v, r, s) { + var signature = Buffer.concat([exports.setLength(r, 32), exports.setLength(s, 32)], 64); + var recovery = v - 27; + if (recovery !== 0 && recovery !== 1) { + throw new Error('Invalid signature v value'); + } + var senderPubKey = secp256k1.recover(msgHash, signature, recovery); + return secp256k1.publicKeyConvert(senderPubKey, false).slice(1); + }; + + /** + * Convert signature parameters into the format of `eth_sign` RPC method + * @param {Number} v + * @param {Buffer} r + * @param {Buffer} s + * @return {String} sig + */ + exports.toRpcSig = function (v, r, s) { + // NOTE: with potential introduction of chainId this might need to be updated + if (v !== 27 && v !== 28) { + throw new Error('Invalid recovery id'); + } + + // geth (and the RPC eth_sign method) uses the 65 byte format used by Bitcoin + // FIXME: this might change in the future - https://github.com/ethereum/go-ethereum/issues/2053 + return exports.bufferToHex(Buffer.concat([exports.setLengthLeft(r, 32), exports.setLengthLeft(s, 32), exports.toBuffer(v - 27)])); + }; + + /** + * Convert signature format of the `eth_sign` RPC method to signature parameters + * NOTE: all because of a bug in geth: https://github.com/ethereum/go-ethereum/issues/2053 + * @param {String} sig + * @return {Object} + */ + exports.fromRpcSig = function (sig) { + sig = exports.toBuffer(sig); + + // NOTE: with potential introduction of chainId this might need to be updated + if (sig.length !== 65) { + throw new Error('Invalid signature length'); + } + + var v = sig[64]; + // support both versions of `eth_sign` responses + if (v < 27) { + v += 27; + } + + return { + v: v, + r: sig.slice(0, 32), + s: sig.slice(32, 64) + }; + }; + + /** + * Returns the ethereum address of a given private key + * @param {Buffer} privateKey A private key must be 256 bits wide + * @return {Buffer} + */ + exports.privateToAddress = function (privateKey) { + return exports.publicToAddress(privateToPublic(privateKey)); + }; + + /** + * Checks if the address is a valid. Accepts checksummed addresses too + * @param {String} address + * @return {Boolean} + */ + exports.isValidAddress = function (address) { + return (/^0x[0-9a-fA-F]{40}$/.test(address) + ); + }; + + /** + * Checks if a given address is a zero address + * @method isZeroAddress + * @param {String} address + * @return {Boolean} + */ + exports.isZeroAddress = function (address) { + var zeroAddress = exports.zeroAddress(); + return zeroAddress === exports.addHexPrefix(address); + }; + + /** + * Returns a checksummed address + * @param {String} address + * @return {String} + */ + exports.toChecksumAddress = function (address) { + address = exports.stripHexPrefix(address).toLowerCase(); + var hash = exports.keccak(address).toString('hex'); + var ret = '0x'; + + for (var i = 0; i < address.length; i++) { + if (parseInt(hash[i], 16) >= 8) { + ret += address[i].toUpperCase(); + } else { + ret += address[i]; + } + } + + return ret; + }; + + /** + * Checks if the address is a valid checksummed address + * @param {Buffer} address + * @return {Boolean} + */ + exports.isValidChecksumAddress = function (address) { + return exports.isValidAddress(address) && exports.toChecksumAddress(address) === address; + }; + + /** + * Generates an address of a newly created contract + * @param {Buffer} from the address which is creating this new address + * @param {Buffer} nonce the nonce of the from account + * @return {Buffer} + */ + exports.generateAddress = function (from, nonce) { + from = exports.toBuffer(from); + nonce = new BN(nonce); + + if (nonce.isZero()) { + // in RLP we want to encode null in the case of zero nonce + // read the RLP documentation for an answer if you dare + nonce = null; + } else { + nonce = Buffer.from(nonce.toArray()); + } + + // Only take the lower 160bits of the hash + return exports.rlphash([from, nonce]).slice(-20); + }; + + /** + * Returns true if the supplied address belongs to a precompiled account (Byzantium) + * @param {Buffer|String} address + * @return {Boolean} + */ + exports.isPrecompiled = function (address) { + var a = exports.unpad(address); + return a.length === 1 && a[0] >= 1 && a[0] <= 8; + }; + + /** + * Adds "0x" to a given `String` if it does not already start with "0x" + * @param {String} str + * @return {String} + */ + exports.addHexPrefix = function (str) { + if (typeof str !== 'string') { + return str; + } + + return exports.isHexPrefixed(str) ? str : '0x' + str; + }; + + /** + * Validate ECDSA signature + * @method isValidSignature + * @param {Buffer} v + * @param {Buffer} r + * @param {Buffer} s + * @param {Boolean} [homestead=true] + * @return {Boolean} + */ + + exports.isValidSignature = function (v, r, s, homestead) { + var SECP256K1_N_DIV_2 = new BN('7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0', 16); + var SECP256K1_N = new BN('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 16); + + if (r.length !== 32 || s.length !== 32) { + return false; + } + + if (v !== 27 && v !== 28) { + return false; + } + + r = new BN(r); + s = new BN(s); + + if (r.isZero() || r.gt(SECP256K1_N) || s.isZero() || s.gt(SECP256K1_N)) { + return false; + } + + if (homestead === false && new BN(s).cmp(SECP256K1_N_DIV_2) === 1) { + return false; + } + + return true; + }; + + /** + * Converts a `Buffer` or `Array` to JSON + * @param {Buffer|Array} ba + * @return {Array|String|null} + */ + exports.baToJSON = function (ba) { + if (Buffer.isBuffer(ba)) { + return '0x' + ba.toString('hex'); + } else if (ba instanceof Array) { + var array = []; + for (var i = 0; i < ba.length; i++) { + array.push(exports.baToJSON(ba[i])); + } + return array; + } + }; + + /** + * Defines properties on a `Object`. It make the assumption that underlying data is binary. + * @param {Object} self the `Object` to define properties on + * @param {Array} fields an array fields to define. Fields can contain: + * * `name` - the name of the properties + * * `length` - the number of bytes the field can have + * * `allowLess` - if the field can be less than the length + * * `allowEmpty` + * @param {*} data data to be validated against the definitions + */ + exports.defineProperties = function (self, fields, data) { + self.raw = []; + self._fields = []; + + // attach the `toJSON` + self.toJSON = function (label) { + if (label) { + var obj = {}; + self._fields.forEach(function (field) { + obj[field] = '0x' + self[field].toString('hex'); + }); + return obj; + } + return exports.baToJSON(this.raw); + }; + + self.serialize = function serialize() { + return rlp.encode(self.raw); + }; + + fields.forEach(function (field, i) { + self._fields.push(field.name); + function getter() { + return self.raw[i]; + } + function setter(v) { + v = exports.toBuffer(v); + + if (v.toString('hex') === '00' && !field.allowZero) { + v = Buffer.allocUnsafe(0); + } + + if (field.allowLess && field.length) { + v = exports.stripZeros(v); + assert(field.length >= v.length, 'The field ' + field.name + ' must not have more ' + field.length + ' bytes'); + } else if (!(field.allowZero && v.length === 0) && field.length) { + assert(field.length === v.length, 'The field ' + field.name + ' must have byte length of ' + field.length); + } + + self.raw[i] = v; + } + + Object.defineProperty(self, field.name, { + enumerable: true, + configurable: true, + get: getter, + set: setter + }); + + if (field.default) { + self[field.name] = field.default; + } + + // attach alias + if (field.alias) { + Object.defineProperty(self, field.alias, { + enumerable: false, + configurable: true, + set: setter, + get: getter + }); + } + }); + + // if the constuctor is passed data + if (data) { + if (typeof data === 'string') { + data = Buffer.from(exports.stripHexPrefix(data), 'hex'); + } + + if (Buffer.isBuffer(data)) { + data = rlp.decode(data); + } + + if (Array.isArray(data)) { + if (data.length > self._fields.length) { + throw new Error('wrong number of fields in data'); + } + + // make sure all the items are buffers + data.forEach(function (d, i) { + self[self._fields[i]] = exports.toBuffer(d); + }); + } else if ((typeof data === 'undefined' ? 'undefined' : _typeof(data)) === 'object') { + var keys = Object.keys(data); + fields.forEach(function (field) { + if (keys.indexOf(field.name) !== -1) self[field.name] = data[field.name]; + if (keys.indexOf(field.alias) !== -1) self[field.alias] = data[field.alias]; + }); + } else { + throw new Error('invalid data'); + } + } + }; + },{"assert":19,"bn.js":53,"create-hash":91,"ethjs-util":155,"keccak":195,"rlp":289,"safe-buffer":290,"secp256k1":295}],142:[function(require,module,exports){ + arguments[4][128][0].apply(exports,arguments) + },{"_process":257,"dup":128}],143:[function(require,module,exports){ + 'use strict'; + var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + // See: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI + var address_1 = require("./address"); + var bignumber_1 = require("./bignumber"); + var bytes_1 = require("./bytes"); + var utf8_1 = require("./utf8"); + var properties_1 = require("./properties"); + var errors = __importStar(require("./errors")); + var paramTypeBytes = new RegExp(/^bytes([0-9]*)$/); + var paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/); + var paramTypeArray = new RegExp(/^(.*)\[([0-9]*)\]$/); + exports.defaultCoerceFunc = function (type, value) { + var match = type.match(paramTypeNumber); + if (match && parseInt(match[2]) <= 48) { + return value.toNumber(); + } + return value; + }; + /////////////////////////////////// + // Parsing for Solidity Signatures + var regexParen = new RegExp("^([^)(]*)\\((.*)\\)([^)(]*)$"); + var regexIdentifier = new RegExp("^[A-Za-z_][A-Za-z0-9_]*$"); + function verifyType(type) { + // These need to be transformed to their full description + if (type.match(/^uint($|[^1-9])/)) { + type = 'uint256' + type.substring(4); + } + else if (type.match(/^int($|[^1-9])/)) { + type = 'int256' + type.substring(3); + } + return type; + } + function parseParam(param, allowIndexed) { + function throwError(i) { + throw new Error('unexpected character "' + param[i] + '" at position ' + i + ' in "' + param + '"'); + } + var parent = { type: '', name: '', state: { allowType: true } }; + var node = parent; + for (var i = 0; i < param.length; i++) { + var c = param[i]; + switch (c) { + case '(': + if (!node.state.allowParams) { + throwError(i); + } + node.state.allowType = false; + node.type = verifyType(node.type); + node.components = [{ type: '', name: '', parent: node, state: { allowType: true } }]; + node = node.components[0]; + break; + case ')': + delete node.state; + if (allowIndexed && node.name === 'indexed') { + node.indexed = true; + node.name = ''; + } + node.type = verifyType(node.type); + var child = node; + node = node.parent; + if (!node) { + throwError(i); + } + delete child.parent; + node.state.allowParams = false; + node.state.allowName = true; + node.state.allowArray = true; + break; + case ',': + delete node.state; + if (allowIndexed && node.name === 'indexed') { + node.indexed = true; + node.name = ''; + } + node.type = verifyType(node.type); + var sibling = { type: '', name: '', parent: node.parent, state: { allowType: true } }; + node.parent.components.push(sibling); + delete node.parent; + node = sibling; + break; + // Hit a space... + case ' ': + // If reading type, the type is done and may read a param or name + if (node.state.allowType) { + if (node.type !== '') { + node.type = verifyType(node.type); + delete node.state.allowType; + node.state.allowName = true; + node.state.allowParams = true; + } + } + // If reading name, the name is done + if (node.state.allowName) { + if (node.name !== '') { + if (allowIndexed && node.name === 'indexed') { + node.indexed = true; + node.name = ''; + } + else { + node.state.allowName = false; + } + } + } + break; + case '[': + if (!node.state.allowArray) { + throwError(i); + } + node.type += c; + node.state.allowArray = false; + node.state.allowName = false; + node.state.readArray = true; + break; + case ']': + if (!node.state.readArray) { + throwError(i); + } + node.type += c; + node.state.readArray = false; + node.state.allowArray = true; + node.state.allowName = true; + break; + default: + if (node.state.allowType) { + node.type += c; + node.state.allowParams = true; + node.state.allowArray = true; + } + else if (node.state.allowName) { + node.name += c; + delete node.state.allowArray; + } + else if (node.state.readArray) { + node.type += c; + } + else { + throwError(i); + } + } + } + if (node.parent) { + throw new Error("unexpected eof"); + } + delete parent.state; + if (allowIndexed && node.name === 'indexed') { + node.indexed = true; + node.name = ''; + } + parent.type = verifyType(parent.type); + return parent; + } + // @TODO: Better return type + function parseSignatureEvent(fragment) { + var abi = { + anonymous: false, + inputs: [], + name: '', + type: 'event' + }; + var match = fragment.match(regexParen); + if (!match) { + throw new Error('invalid event: ' + fragment); + } + abi.name = match[1].trim(); + splitNesting(match[2]).forEach(function (param) { + param = parseParam(param, true); + param.indexed = !!param.indexed; + abi.inputs.push(param); + }); + match[3].split(' ').forEach(function (modifier) { + switch (modifier) { + case 'anonymous': + abi.anonymous = true; + break; + case '': + break; + default: + console.log('unknown modifier: ' + modifier); + } + }); + if (abi.name && !abi.name.match(regexIdentifier)) { + throw new Error('invalid identifier: "' + abi.name + '"'); + } + return abi; + } + function parseSignatureFunction(fragment) { + var abi = { + constant: false, + inputs: [], + name: '', + outputs: [], + payable: false, + stateMutability: null, + type: 'function' + }; + var comps = fragment.split(' returns '); + var left = comps[0].match(regexParen); + if (!left) { + throw new Error('invalid signature'); + } + abi.name = left[1].trim(); + if (!abi.name.match(regexIdentifier)) { + throw new Error('invalid identifier: "' + left[1] + '"'); + } + splitNesting(left[2]).forEach(function (param) { + abi.inputs.push(parseParam(param)); + }); + left[3].split(' ').forEach(function (modifier) { + switch (modifier) { + case 'constant': + abi.constant = true; + break; + case 'payable': + abi.payable = true; + break; + case 'pure': + abi.constant = true; + abi.stateMutability = 'pure'; + break; + case 'view': + abi.constant = true; + abi.stateMutability = 'view'; + break; + case '': + break; + default: + console.log('unknown modifier: ' + modifier); + } + }); + // We have outputs + if (comps.length > 1) { + var right = comps[1].match(regexParen); + if (right[1].trim() != '' || right[3].trim() != '') { + throw new Error('unexpected tokens'); + } + splitNesting(right[2]).forEach(function (param) { + abi.outputs.push(parseParam(param)); + }); + } + return abi; + } + function parseParamType(type) { + return parseParam(type, true); + } + exports.parseParamType = parseParamType; + // @TODO: Allow a second boolean to expose names + function formatParamType(paramType) { + return getParamCoder(exports.defaultCoerceFunc, paramType).type; + } + exports.formatParamType = formatParamType; + // @TODO: Allow a second boolean to expose names and modifiers + function formatSignature(fragment) { + return fragment.name + '(' + fragment.inputs.map(function (i) { return formatParamType(i); }).join(',') + ')'; + } + exports.formatSignature = formatSignature; + function parseSignature(fragment) { + if (typeof (fragment) === 'string') { + // Make sure the "returns" is surrounded by a space and all whitespace is exactly one space + fragment = fragment.replace(/\(/g, ' (').replace(/\)/g, ') ').replace(/\s+/g, ' '); + fragment = fragment.trim(); + if (fragment.substring(0, 6) === 'event ') { + return parseSignatureEvent(fragment.substring(6).trim()); + } + else { + if (fragment.substring(0, 9) === 'function ') { + fragment = fragment.substring(9); + } + return parseSignatureFunction(fragment.trim()); + } + } + throw new Error('unknown signature'); + } + exports.parseSignature = parseSignature; + var Coder = /** @class */ (function () { + function Coder(coerceFunc, name, type, localName, dynamic) { + this.coerceFunc = coerceFunc; + this.name = name; + this.type = type; + this.localName = localName; + this.dynamic = dynamic; + } + return Coder; + }()); + // Clones the functionality of an existing Coder, but without a localName + var CoderAnonymous = /** @class */ (function (_super) { + __extends(CoderAnonymous, _super); + function CoderAnonymous(coder) { + var _this = _super.call(this, coder.coerceFunc, coder.name, coder.type, undefined, coder.dynamic) || this; + properties_1.defineReadOnly(_this, 'coder', coder); + return _this; + } + CoderAnonymous.prototype.encode = function (value) { return this.coder.encode(value); }; + CoderAnonymous.prototype.decode = function (data, offset) { return this.coder.decode(data, offset); }; + return CoderAnonymous; + }(Coder)); + var CoderNull = /** @class */ (function (_super) { + __extends(CoderNull, _super); + function CoderNull(coerceFunc, localName) { + return _super.call(this, coerceFunc, 'null', '', localName, false) || this; + } + CoderNull.prototype.encode = function (value) { + return bytes_1.arrayify([]); + }; + CoderNull.prototype.decode = function (data, offset) { + if (offset > data.length) { + throw new Error('invalid null'); + } + return { + consumed: 0, + value: this.coerceFunc('null', undefined) + }; + }; + return CoderNull; + }(Coder)); + var CoderNumber = /** @class */ (function (_super) { + __extends(CoderNumber, _super); + function CoderNumber(coerceFunc, size, signed, localName) { + var _this = this; + var name = ((signed ? 'int' : 'uint') + (size * 8)); + _this = _super.call(this, coerceFunc, name, name, localName, false) || this; + _this.size = size; + _this.signed = signed; + return _this; + } + CoderNumber.prototype.encode = function (value) { + try { + var v = bignumber_1.bigNumberify(value); + v = v.toTwos(this.size * 8).maskn(this.size * 8); + //value = value.toTwos(size * 8).maskn(size * 8); + if (this.signed) { + v = v.fromTwos(this.size * 8).toTwos(256); + } + return bytes_1.padZeros(bytes_1.arrayify(v), 32); + } + catch (error) { + errors.throwError('invalid number value', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: this.name, + value: value + }); + } + return null; + }; + CoderNumber.prototype.decode = function (data, offset) { + if (data.length < offset + 32) { + errors.throwError('insufficient data for ' + this.name + ' type', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: this.name, + value: bytes_1.hexlify(data.slice(offset, offset + 32)) + }); + } + var junkLength = 32 - this.size; + var value = bignumber_1.bigNumberify(data.slice(offset + junkLength, offset + 32)); + if (this.signed) { + value = value.fromTwos(this.size * 8); + } + else { + value = value.maskn(this.size * 8); + } + return { + consumed: 32, + value: this.coerceFunc(this.name, value), + }; + }; + return CoderNumber; + }(Coder)); + var uint256Coder = new CoderNumber(function (type, value) { return value; }, 32, false, 'none'); + var CoderBoolean = /** @class */ (function (_super) { + __extends(CoderBoolean, _super); + function CoderBoolean(coerceFunc, localName) { + return _super.call(this, coerceFunc, 'bool', 'bool', localName, false) || this; + } + CoderBoolean.prototype.encode = function (value) { + return uint256Coder.encode(!!value ? 1 : 0); + }; + CoderBoolean.prototype.decode = function (data, offset) { + try { + var result = uint256Coder.decode(data, offset); + } + catch (error) { + if (error.reason === 'insufficient data for uint256 type') { + errors.throwError('insufficient data for boolean type', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: 'boolean', + value: error.value + }); + } + throw error; + } + return { + consumed: result.consumed, + value: this.coerceFunc('bool', !result.value.isZero()) + }; + }; + return CoderBoolean; + }(Coder)); + var CoderFixedBytes = /** @class */ (function (_super) { + __extends(CoderFixedBytes, _super); + function CoderFixedBytes(coerceFunc, length, localName) { + var _this = this; + var name = ('bytes' + length); + _this = _super.call(this, coerceFunc, name, name, localName, false) || this; + _this.length = length; + return _this; + } + CoderFixedBytes.prototype.encode = function (value) { + var result = new Uint8Array(32); + try { + var data = bytes_1.arrayify(value); + if (data.length > 32) { + throw new Error(); + } + result.set(data); + } + catch (error) { + errors.throwError('invalid ' + this.name + ' value', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: this.name, + value: (error.value || value) + }); + } + return result; + }; + CoderFixedBytes.prototype.decode = function (data, offset) { + if (data.length < offset + 32) { + errors.throwError('insufficient data for ' + name + ' type', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: this.name, + value: bytes_1.hexlify(data.slice(offset, offset + 32)) + }); + } + return { + consumed: 32, + value: this.coerceFunc(this.name, bytes_1.hexlify(data.slice(offset, offset + this.length))) + }; + }; + return CoderFixedBytes; + }(Coder)); + var CoderAddress = /** @class */ (function (_super) { + __extends(CoderAddress, _super); + function CoderAddress(coerceFunc, localName) { + return _super.call(this, coerceFunc, 'address', 'address', localName, false) || this; + } + CoderAddress.prototype.encode = function (value) { + var result = new Uint8Array(32); + try { + result.set(bytes_1.arrayify(address_1.getAddress(value)), 12); + } + catch (error) { + errors.throwError('invalid address', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: 'address', + value: value + }); + } + return result; + }; + CoderAddress.prototype.decode = function (data, offset) { + if (data.length < offset + 32) { + errors.throwError('insufficuent data for address type', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: 'address', + value: bytes_1.hexlify(data.slice(offset, offset + 32)) + }); + } + return { + consumed: 32, + value: this.coerceFunc('address', address_1.getAddress(bytes_1.hexlify(data.slice(offset + 12, offset + 32)))) + }; + }; + return CoderAddress; + }(Coder)); + function _encodeDynamicBytes(value) { + var dataLength = 32 * Math.ceil(value.length / 32); + var padding = new Uint8Array(dataLength - value.length); + return bytes_1.concat([ + uint256Coder.encode(value.length), + value, + padding + ]); + } + function _decodeDynamicBytes(data, offset, localName) { + if (data.length < offset + 32) { + errors.throwError('insufficient data for dynamicBytes length', errors.INVALID_ARGUMENT, { + arg: localName, + coderType: 'dynamicBytes', + value: bytes_1.hexlify(data.slice(offset, offset + 32)) + }); + } + var length = uint256Coder.decode(data, offset).value; + try { + length = length.toNumber(); + } + catch (error) { + errors.throwError('dynamic bytes count too large', errors.INVALID_ARGUMENT, { + arg: localName, + coderType: 'dynamicBytes', + value: length.toString() + }); + } + if (data.length < offset + 32 + length) { + errors.throwError('insufficient data for dynamicBytes type', errors.INVALID_ARGUMENT, { + arg: localName, + coderType: 'dynamicBytes', + value: bytes_1.hexlify(data.slice(offset, offset + 32 + length)) + }); + } + return { + consumed: 32 + 32 * Math.ceil(length / 32), + value: data.slice(offset + 32, offset + 32 + length), + }; + } + var CoderDynamicBytes = /** @class */ (function (_super) { + __extends(CoderDynamicBytes, _super); + function CoderDynamicBytes(coerceFunc, localName) { + return _super.call(this, coerceFunc, 'bytes', 'bytes', localName, true) || this; + } + CoderDynamicBytes.prototype.encode = function (value) { + try { + return _encodeDynamicBytes(bytes_1.arrayify(value)); + } + catch (error) { + errors.throwError('invalid bytes value', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: 'bytes', + value: error.value + }); + } + return null; + }; + CoderDynamicBytes.prototype.decode = function (data, offset) { + var result = _decodeDynamicBytes(data, offset, this.localName); + result.value = this.coerceFunc('bytes', bytes_1.hexlify(result.value)); + return result; + }; + return CoderDynamicBytes; + }(Coder)); + var CoderString = /** @class */ (function (_super) { + __extends(CoderString, _super); + function CoderString(coerceFunc, localName) { + return _super.call(this, coerceFunc, 'string', 'string', localName, true) || this; + } + CoderString.prototype.encode = function (value) { + if (typeof (value) !== 'string') { + errors.throwError('invalid string value', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: 'string', + value: value + }); + } + return _encodeDynamicBytes(utf8_1.toUtf8Bytes(value)); + }; + CoderString.prototype.decode = function (data, offset) { + var result = _decodeDynamicBytes(data, offset, this.localName); + result.value = this.coerceFunc('string', utf8_1.toUtf8String(result.value)); + return result; + }; + return CoderString; + }(Coder)); + function alignSize(size) { + return 32 * Math.ceil(size / 32); + } + function pack(coders, values) { + if (Array.isArray(values)) { + // do nothing + } + else if (values && typeof (values) === 'object') { + var arrayValues = []; + coders.forEach(function (coder) { + arrayValues.push(values[coder.localName]); + }); + values = arrayValues; + } + else { + errors.throwError('invalid tuple value', errors.INVALID_ARGUMENT, { + coderType: 'tuple', + value: values + }); + } + if (coders.length !== values.length) { + errors.throwError('types/value length mismatch', errors.INVALID_ARGUMENT, { + coderType: 'tuple', + value: values + }); + } + var parts = []; + coders.forEach(function (coder, index) { + parts.push({ dynamic: coder.dynamic, value: coder.encode(values[index]) }); + }); + var staticSize = 0, dynamicSize = 0; + parts.forEach(function (part) { + if (part.dynamic) { + staticSize += 32; + dynamicSize += alignSize(part.value.length); + } + else { + staticSize += alignSize(part.value.length); + } + }); + var offset = 0, dynamicOffset = staticSize; + var data = new Uint8Array(staticSize + dynamicSize); + parts.forEach(function (part) { + if (part.dynamic) { + //uint256Coder.encode(dynamicOffset).copy(data, offset); + data.set(uint256Coder.encode(dynamicOffset), offset); + offset += 32; + //part.value.copy(data, dynamicOffset); @TODO + data.set(part.value, dynamicOffset); + dynamicOffset += alignSize(part.value.length); + } + else { + //part.value.copy(data, offset); @TODO + data.set(part.value, offset); + offset += alignSize(part.value.length); + } + }); + return data; + } + function unpack(coders, data, offset) { + var baseOffset = offset; + var consumed = 0; + var value = []; + coders.forEach(function (coder) { + if (coder.dynamic) { + var dynamicOffset = uint256Coder.decode(data, offset); + var result = coder.decode(data, baseOffset + dynamicOffset.value.toNumber()); + // The dynamic part is leap-frogged somewhere else; doesn't count towards size + result.consumed = dynamicOffset.consumed; + } + else { + var result = coder.decode(data, offset); + } + if (result.value != undefined) { + value.push(result.value); + } + offset += result.consumed; + consumed += result.consumed; + }); + coders.forEach(function (coder, index) { + var name = coder.localName; + if (!name) { + return; + } + if (name === 'length') { + name = '_length'; + } + if (value[name] != null) { + return; + } + value[name] = value[index]; + }); + return { + value: value, + consumed: consumed + }; + } + var CoderArray = /** @class */ (function (_super) { + __extends(CoderArray, _super); + function CoderArray(coerceFunc, coder, length, localName) { + var _this = this; + var type = (coder.type + '[' + (length >= 0 ? length : '') + ']'); + var dynamic = (length === -1 || coder.dynamic); + _this = _super.call(this, coerceFunc, 'array', type, localName, dynamic) || this; + _this.coder = coder; + _this.length = length; + return _this; + } + CoderArray.prototype.encode = function (value) { + if (!Array.isArray(value)) { + errors.throwError('expected array value', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: 'array', + value: value + }); + } + var count = this.length; + var result = new Uint8Array(0); + if (count === -1) { + count = value.length; + result = uint256Coder.encode(count); + } + errors.checkArgumentCount(count, value.length, 'in coder array' + (this.localName ? (" " + this.localName) : "")); + var coders = []; + for (var i = 0; i < value.length; i++) { + coders.push(this.coder); + } + return bytes_1.concat([result, pack(coders, value)]); + }; + CoderArray.prototype.decode = function (data, offset) { + // @TODO: + //if (data.length < offset + length * 32) { throw new Error('invalid array'); } + var consumed = 0; + var count = this.length; + if (count === -1) { + try { + var decodedLength = uint256Coder.decode(data, offset); + } + catch (error) { + errors.throwError('insufficient data for dynamic array length', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: 'array', + value: error.value + }); + } + try { + count = decodedLength.value.toNumber(); + } + catch (error) { + errors.throwError('array count too large', errors.INVALID_ARGUMENT, { + arg: this.localName, + coderType: 'array', + value: decodedLength.value.toString() + }); + } + consumed += decodedLength.consumed; + offset += decodedLength.consumed; + } + var coders = []; + for (var i = 0; i < count; i++) { + coders.push(new CoderAnonymous(this.coder)); + } + var result = unpack(coders, data, offset); + result.consumed += consumed; + result.value = this.coerceFunc(this.type, result.value); + return result; + }; + return CoderArray; + }(Coder)); + var CoderTuple = /** @class */ (function (_super) { + __extends(CoderTuple, _super); + function CoderTuple(coerceFunc, coders, localName) { + var _this = this; + var dynamic = false; + var types = []; + coders.forEach(function (coder) { + if (coder.dynamic) { + dynamic = true; + } + types.push(coder.type); + }); + var type = ('tuple(' + types.join(',') + ')'); + _this = _super.call(this, coerceFunc, 'tuple', type, localName, dynamic) || this; + _this.coders = coders; + return _this; + } + CoderTuple.prototype.encode = function (value) { + return pack(this.coders, value); + }; + CoderTuple.prototype.decode = function (data, offset) { + var result = unpack(this.coders, data, offset); + result.value = this.coerceFunc(this.type, result.value); + return result; + }; + return CoderTuple; + }(Coder)); + /* + function getTypes(coders) { + var type = coderTuple(coders).type; + return type.substring(6, type.length - 1); + } + */ + function splitNesting(value) { + var result = []; + var accum = ''; + var depth = 0; + for (var offset = 0; offset < value.length; offset++) { + var c = value[offset]; + if (c === ',' && depth === 0) { + result.push(accum); + accum = ''; + } + else { + accum += c; + if (c === '(') { + depth++; + } + else if (c === ')') { + depth--; + if (depth === -1) { + throw new Error('unbalanced parenthsis'); + } + } + } + } + result.push(accum); + return result; + } + // @TODO: Is there a way to return "class"? + var paramTypeSimple = { + address: CoderAddress, + bool: CoderBoolean, + string: CoderString, + bytes: CoderDynamicBytes, + }; + function getTupleParamCoder(coerceFunc, components, localName) { + if (!components) { + components = []; + } + var coders = []; + components.forEach(function (component) { + coders.push(getParamCoder(coerceFunc, component)); + }); + return new CoderTuple(coerceFunc, coders, localName); + } + function getParamCoder(coerceFunc, param) { + var coder = paramTypeSimple[param.type]; + if (coder) { + return new coder(coerceFunc, param.name); + } + var match = param.type.match(paramTypeNumber); + if (match) { + var size = parseInt(match[2] || "256"); + if (size === 0 || size > 256 || (size % 8) !== 0) { + errors.throwError('invalid ' + match[1] + ' bit length', errors.INVALID_ARGUMENT, { + arg: 'param', + value: param + }); + } + return new CoderNumber(coerceFunc, size / 8, (match[1] === 'int'), param.name); + } + var match = param.type.match(paramTypeBytes); + if (match) { + var size = parseInt(match[1]); + if (size === 0 || size > 32) { + errors.throwError('invalid bytes length', errors.INVALID_ARGUMENT, { + arg: 'param', + value: param + }); + } + return new CoderFixedBytes(coerceFunc, size, param.name); + } + var match = param.type.match(paramTypeArray); + if (match) { + var size = parseInt(match[2] || "-1"); + param = properties_1.jsonCopy(param); + param.type = match[1]; + return new CoderArray(coerceFunc, getParamCoder(coerceFunc, param), size, param.name); + } + if (param.type.substring(0, 5) === 'tuple') { + return getTupleParamCoder(coerceFunc, param.components, param.name); + } + if (param.type === '') { + return new CoderNull(coerceFunc, param.name); + } + errors.throwError('invalid type', errors.INVALID_ARGUMENT, { + arg: 'type', + value: param.type + }); + return null; + } + var AbiCoder = /** @class */ (function () { + function AbiCoder(coerceFunc) { + errors.checkNew(this, AbiCoder); + if (!coerceFunc) { + coerceFunc = exports.defaultCoerceFunc; + } + properties_1.defineReadOnly(this, 'coerceFunc', coerceFunc); + } + AbiCoder.prototype.encode = function (types, values) { + if (types.length !== values.length) { + errors.throwError('types/values length mismatch', errors.INVALID_ARGUMENT, { + count: { types: types.length, values: values.length }, + value: { types: types, values: values } + }); + } + var coders = []; + types.forEach(function (type) { + // Convert types to type objects + // - "uint foo" => { type: "uint", name: "foo" } + // - "tuple(uint, uint)" => { type: "tuple", components: [ { type: "uint" }, { type: "uint" }, ] } + var typeObject = null; + if (typeof (type) === 'string') { + typeObject = parseParam(type); + } + else { + typeObject = type; + } + coders.push(getParamCoder(this.coerceFunc, typeObject)); + }, this); + return bytes_1.hexlify(new CoderTuple(this.coerceFunc, coders, '_').encode(values)); + }; + AbiCoder.prototype.decode = function (types, data) { + var coders = []; + types.forEach(function (type) { + // See encode for details + var typeObject = null; + if (typeof (type) === 'string') { + typeObject = parseParam(type); + } + else { + typeObject = properties_1.jsonCopy(type); + } + coders.push(getParamCoder(this.coerceFunc, typeObject)); + }, this); + return new CoderTuple(this.coerceFunc, coders, '_').decode(bytes_1.arrayify(data), 0).value; + }; + return AbiCoder; + }()); + exports.AbiCoder = AbiCoder; + exports.defaultAbiCoder = new AbiCoder(); + + },{"./address":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) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + // We use this for base 36 maths + var bn_js_1 = __importDefault(require("bn.js")); + var bytes_1 = require("./bytes"); + var keccak256_1 = require("./keccak256"); + var rlp_1 = require("./rlp"); + var errors = require("./errors"); + function getChecksumAddress(address) { + if (typeof (address) !== 'string' || !address.match(/^0x[0-9A-Fa-f]{40}$/)) { + errors.throwError('invalid address', errors.INVALID_ARGUMENT, { arg: 'address', value: address }); + } + address = address.toLowerCase(); + var chars = address.substring(2).split(''); + var hashed = new Uint8Array(40); + for (var i_1 = 0; i_1 < 40; i_1++) { + hashed[i_1] = chars[i_1].charCodeAt(0); + } + hashed = bytes_1.arrayify(keccak256_1.keccak256(hashed)); + for (var i = 0; i < 40; i += 2) { + if ((hashed[i >> 1] >> 4) >= 8) { + chars[i] = chars[i].toUpperCase(); + } + if ((hashed[i >> 1] & 0x0f) >= 8) { + chars[i + 1] = chars[i + 1].toUpperCase(); + } + } + return '0x' + chars.join(''); + } + // Shims for environments that are missing some required constants and functions + var MAX_SAFE_INTEGER = 0x1fffffffffffff; + function log10(x) { + if (Math.log10) { + return Math.log10(x); + } + return Math.log(x) / Math.LN10; + } + // See: https://en.wikipedia.org/wiki/International_Bank_Account_Number + // Create lookup table + var ibanLookup = {}; + for (var i = 0; i < 10; i++) { + ibanLookup[String(i)] = String(i); + } + for (var i = 0; i < 26; i++) { + ibanLookup[String.fromCharCode(65 + i)] = String(10 + i); + } + // How many decimal digits can we process? (for 64-bit float, this is 15) + var safeDigits = Math.floor(log10(MAX_SAFE_INTEGER)); + function ibanChecksum(address) { + address = address.toUpperCase(); + address = address.substring(4) + address.substring(0, 2) + '00'; + var expanded = ''; + address.split('').forEach(function (c) { + expanded += ibanLookup[c]; + }); + // Javascript can handle integers safely up to 15 (decimal) digits + while (expanded.length >= safeDigits) { + var block = expanded.substring(0, safeDigits); + expanded = parseInt(block, 10) % 97 + expanded.substring(block.length); + } + var checksum = String(98 - (parseInt(expanded, 10) % 97)); + while (checksum.length < 2) { + checksum = '0' + checksum; + } + return checksum; + } + ; + function getAddress(address) { + var result = null; + if (typeof (address) !== 'string') { + errors.throwError('invalid address', errors.INVALID_ARGUMENT, { arg: 'address', value: address }); + } + if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) { + // Missing the 0x prefix + if (address.substring(0, 2) !== '0x') { + address = '0x' + address; + } + result = getChecksumAddress(address); + // It is a checksummed address with a bad checksum + if (address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) && result !== address) { + errors.throwError('bad address checksum', errors.INVALID_ARGUMENT, { arg: 'address', value: address }); + } + // Maybe ICAP? (we only support direct mode) + } + else if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) { + // It is an ICAP address with a bad checksum + if (address.substring(2, 4) !== ibanChecksum(address)) { + errors.throwError('bad icap checksum', errors.INVALID_ARGUMENT, { arg: 'address', value: address }); + } + result = (new bn_js_1.default.BN(address.substring(4), 36)).toString(16); + while (result.length < 40) { + result = '0' + result; + } + result = getChecksumAddress('0x' + result); + } + else { + errors.throwError('invalid address', errors.INVALID_ARGUMENT, { arg: 'address', value: address }); + } + return result; + } + exports.getAddress = getAddress; + function getIcapAddress(address) { + var base36 = (new bn_js_1.default.BN(getAddress(address).substring(2), 16)).toString(36).toUpperCase(); + while (base36.length < 30) { + base36 = '0' + base36; + } + return 'XE' + ibanChecksum('XE00' + base36) + base36; + } + exports.getIcapAddress = getIcapAddress; + // http://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed + function getContractAddress(transaction) { + if (!transaction.from) { + throw new Error('missing from address'); + } + var nonce = transaction.nonce; + return getAddress('0x' + keccak256_1.keccak256(rlp_1.encode([ + getAddress(transaction.from), + bytes_1.stripZeros(bytes_1.hexlify(nonce)) + ])).substring(26)); + } + exports.getContractAddress = getContractAddress; + + },{"./bytes":146,"./errors":147,"./keccak256":148,"./rlp":150,"bn.js":53}],145:[function(require,module,exports){ + 'use strict'; + var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + /** + * BigNumber + * + * A wrapper around the BN.js object. We use the BN.js library + * because it is used by elliptic, so it is required regardles. + * + */ + var bn_js_1 = __importDefault(require("bn.js")); + var bytes_1 = require("./bytes"); + var properties_1 = require("./properties"); + var types_1 = require("./types"); + var errors = __importStar(require("./errors")); + var BN_1 = new bn_js_1.default.BN(-1); + function toHex(bn) { + var value = bn.toString(16); + if (value[0] === '-') { + if ((value.length % 2) === 0) { + return '-0x0' + value.substring(1); + } + return "-0x" + value.substring(1); + } + if ((value.length % 2) === 1) { + return '0x0' + value; + } + return '0x' + value; + } + function toBN(value) { + return bigNumberify(value)._bn; + } + function toBigNumber(bn) { + return new BigNumber(toHex(bn)); + } + var BigNumber = /** @class */ (function (_super) { + __extends(BigNumber, _super); + function BigNumber(value) { + var _this = _super.call(this) || this; + errors.checkNew(_this, BigNumber); + if (typeof (value) === 'string') { + if (bytes_1.isHexString(value)) { + if (value == '0x') { + value = '0x0'; + } + properties_1.defineReadOnly(_this, '_hex', value); + } + else if (value[0] === '-' && bytes_1.isHexString(value.substring(1))) { + properties_1.defineReadOnly(_this, '_hex', value); + } + else if (value.match(/^-?[0-9]*$/)) { + if (value == '') { + value = '0'; + } + properties_1.defineReadOnly(_this, '_hex', toHex(new bn_js_1.default.BN(value))); + } + else { + errors.throwError('invalid BigNumber string value', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); + } + } + else if (typeof (value) === 'number') { + if (parseInt(String(value)) !== value) { + errors.throwError('underflow', errors.NUMERIC_FAULT, { operation: 'setValue', fault: 'underflow', value: value, outputValue: parseInt(String(value)) }); + } + try { + properties_1.defineReadOnly(_this, '_hex', toHex(new bn_js_1.default.BN(value))); + } + catch (error) { + errors.throwError('overflow', errors.NUMERIC_FAULT, { operation: 'setValue', fault: 'overflow', details: error.message }); + } + } + else if (value instanceof BigNumber) { + properties_1.defineReadOnly(_this, '_hex', value._hex); + } + else if (value.toHexString) { + properties_1.defineReadOnly(_this, '_hex', toHex(toBN(value.toHexString()))); + } + else if (bytes_1.isArrayish(value)) { + properties_1.defineReadOnly(_this, '_hex', toHex(new bn_js_1.default.BN(bytes_1.hexlify(value).substring(2), 16))); + } + else { + errors.throwError('invalid BigNumber value', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); + } + return _this; + } + Object.defineProperty(BigNumber.prototype, "_bn", { + get: function () { + if (this._hex[0] === '-') { + return (new bn_js_1.default.BN(this._hex.substring(3), 16)).mul(BN_1); + } + return new bn_js_1.default.BN(this._hex.substring(2), 16); + }, + enumerable: true, + configurable: true + }); + BigNumber.prototype.fromTwos = function (value) { + return toBigNumber(this._bn.fromTwos(value)); + }; + BigNumber.prototype.toTwos = function (value) { + return toBigNumber(this._bn.toTwos(value)); + }; + BigNumber.prototype.add = function (other) { + return toBigNumber(this._bn.add(toBN(other))); + }; + BigNumber.prototype.sub = function (other) { + return toBigNumber(this._bn.sub(toBN(other))); + }; + BigNumber.prototype.div = function (other) { + var o = bigNumberify(other); + if (o.isZero()) { + errors.throwError('division by zero', errors.NUMERIC_FAULT, { operation: 'divide', fault: 'division by zero' }); + } + return toBigNumber(this._bn.div(toBN(other))); + }; + BigNumber.prototype.mul = function (other) { + return toBigNumber(this._bn.mul(toBN(other))); + }; + BigNumber.prototype.mod = function (other) { + return toBigNumber(this._bn.mod(toBN(other))); + }; + BigNumber.prototype.pow = function (other) { + return toBigNumber(this._bn.pow(toBN(other))); + }; + BigNumber.prototype.maskn = function (value) { + return toBigNumber(this._bn.maskn(value)); + }; + BigNumber.prototype.eq = function (other) { + return this._bn.eq(toBN(other)); + }; + BigNumber.prototype.lt = function (other) { + return this._bn.lt(toBN(other)); + }; + BigNumber.prototype.lte = function (other) { + return this._bn.lte(toBN(other)); + }; + BigNumber.prototype.gt = function (other) { + return this._bn.gt(toBN(other)); + }; + BigNumber.prototype.gte = function (other) { + return this._bn.gte(toBN(other)); + }; + BigNumber.prototype.isZero = function () { + return this._bn.isZero(); + }; + BigNumber.prototype.toNumber = function () { + try { + return this._bn.toNumber(); + } + catch (error) { + errors.throwError('overflow', errors.NUMERIC_FAULT, { operation: 'setValue', fault: 'overflow', details: error.message }); + } + return null; + }; + BigNumber.prototype.toString = function () { + return this._bn.toString(10); + }; + BigNumber.prototype.toHexString = function () { + return this._hex; + }; + return BigNumber; + }(types_1.BigNumber)); + function bigNumberify(value) { + if (value instanceof BigNumber) { + return value; + } + return new BigNumber(value); + } + exports.bigNumberify = bigNumberify; + exports.ConstantNegativeOne = bigNumberify(-1); + exports.ConstantZero = bigNumberify(0); + exports.ConstantOne = bigNumberify(1); + exports.ConstantTwo = bigNumberify(2); + exports.ConstantWeiPerEther = bigNumberify('1000000000000000000'); + + },{"./bytes":146,"./errors":147,"./properties":149,"./types":151,"bn.js":53}],146:[function(require,module,exports){ + "use strict"; + /** + * Conversion Utilities + * + */ + Object.defineProperty(exports, "__esModule", { value: true }); + var errors = require("./errors"); + exports.AddressZero = '0x0000000000000000000000000000000000000000'; + exports.HashZero = '0x0000000000000000000000000000000000000000000000000000000000000000'; + function isBigNumber(value) { + return !!value._bn; + } + function addSlice(array) { + if (array.slice) { + return array; + } + array.slice = function () { + var args = Array.prototype.slice.call(arguments); + return new Uint8Array(Array.prototype.slice.apply(array, args)); + }; + return array; + } + function isArrayish(value) { + if (!value || parseInt(String(value.length)) != value.length || typeof (value) === 'string') { + return false; + } + for (var i = 0; i < value.length; i++) { + var v = value[i]; + if (v < 0 || v >= 256 || parseInt(String(v)) != v) { + return false; + } + } + return true; + } + exports.isArrayish = isArrayish; + function arrayify(value) { + if (value == null) { + errors.throwError('cannot convert null value to array', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); + } + if (isBigNumber(value)) { + value = value.toHexString(); + } + if (typeof (value) === 'string') { + var match = value.match(/^(0x)?[0-9a-fA-F]*$/); + if (!match) { + errors.throwError('invalid hexidecimal string', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); + } + if (match[1] !== '0x') { + errors.throwError('hex string must have 0x prefix', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); + } + value = value.substring(2); + if (value.length % 2) { + value = '0' + value; + } + var result = []; + for (var i = 0; i < value.length; i += 2) { + result.push(parseInt(value.substr(i, 2), 16)); + } + return addSlice(new Uint8Array(result)); + } + else if (typeof (value) === 'string') { + } + if (isArrayish(value)) { + return addSlice(new Uint8Array(value)); + } + errors.throwError('invalid arrayify value', null, { arg: 'value', value: value, type: typeof (value) }); + return null; + } + exports.arrayify = arrayify; + function concat(objects) { + var arrays = []; + var length = 0; + for (var i = 0; i < objects.length; i++) { + var object = arrayify(objects[i]); + arrays.push(object); + length += object.length; + } + var result = new Uint8Array(length); + var offset = 0; + for (var i = 0; i < arrays.length; i++) { + result.set(arrays[i], offset); + offset += arrays[i].length; + } + return addSlice(result); + } + exports.concat = concat; + function stripZeros(value) { + var result = arrayify(value); + if (result.length === 0) { + return result; + } + // Find the first non-zero entry + var start = 0; + while (result[start] === 0) { + start++; + } + // If we started with zeros, strip them + if (start) { + result = result.slice(start); + } + return result; + } + exports.stripZeros = stripZeros; + function padZeros(value, length) { + value = arrayify(value); + if (length < value.length) { + throw new Error('cannot pad'); + } + var result = new Uint8Array(length); + result.set(value, length - value.length); + return addSlice(result); + } + exports.padZeros = padZeros; + function isHexString(value, length) { + if (typeof (value) !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) { + return false; + } + if (length && value.length !== 2 + 2 * length) { + return false; + } + return true; + } + exports.isHexString = isHexString; + var HexCharacters = '0123456789abcdef'; + function hexlify(value) { + if (isBigNumber(value)) { + return value.toHexString(); + } + if (typeof (value) === 'number') { + if (value < 0) { + errors.throwError('cannot hexlify negative value', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); + } + var hex = ''; + while (value) { + hex = HexCharacters[value & 0x0f] + hex; + value = Math.floor(value / 16); + } + if (hex.length) { + if (hex.length % 2) { + hex = '0' + hex; + } + return '0x' + hex; + } + return '0x00'; + } + if (typeof (value) === 'string') { + var match = value.match(/^(0x)?[0-9a-fA-F]*$/); + if (!match) { + errors.throwError('invalid hexidecimal string', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); + } + if (match[1] !== '0x') { + errors.throwError('hex string must have 0x prefix', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); + } + if (value.length % 2) { + value = '0x0' + value.substring(2); + } + return value; + } + if (isArrayish(value)) { + var result = []; + for (var i = 0; i < value.length; i++) { + var v = value[i]; + result.push(HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f]); + } + return '0x' + result.join(''); + } + errors.throwError('invalid hexlify value', null, { arg: 'value', value: value }); + return 'never'; + } + exports.hexlify = hexlify; + function hexDataLength(data) { + if (!isHexString(data) || (data.length % 2) !== 0) { + return null; + } + return (data.length - 2) / 2; + } + exports.hexDataLength = hexDataLength; + function hexDataSlice(data, offset, length) { + if (!isHexString(data)) { + errors.throwError('invalid hex data', errors.INVALID_ARGUMENT, { arg: 'value', value: data }); + } + if ((data.length % 2) !== 0) { + errors.throwError('hex data length must be even', errors.INVALID_ARGUMENT, { arg: 'value', value: data }); + } + offset = 2 + 2 * offset; + if (length != null) { + return '0x' + data.substring(offset, offset + 2 * length); + } + return '0x' + data.substring(offset); + } + exports.hexDataSlice = hexDataSlice; + function hexStripZeros(value) { + if (!isHexString(value)) { + errors.throwError('invalid hex string', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); + } + while (value.length > 3 && value.substring(0, 3) === '0x0') { + value = '0x' + value.substring(3); + } + return value; + } + exports.hexStripZeros = hexStripZeros; + function hexZeroPad(value, length) { + if (!isHexString(value)) { + errors.throwError('invalid hex string', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); + } + while (value.length < 2 * length + 2) { + value = '0x0' + value.substring(2); + } + return value; + } + exports.hexZeroPad = hexZeroPad; + function isSignature(value) { + return (value && value.r != null && value.s != null); + } + function splitSignature(signature) { + var v = 0; + var r = '0x', s = '0x'; + if (isSignature(signature)) { + if (signature.v == null && signature.recoveryParam == null) { + errors.throwError('at least on of recoveryParam or v must be specified', errors.INVALID_ARGUMENT, { argument: 'signature', value: signature }); + } + r = hexZeroPad(signature.r, 32); + s = hexZeroPad(signature.s, 32); + v = signature.v; + if (typeof (v) === 'string') { + v = parseInt(v, 16); + } + var recoveryParam = signature.recoveryParam; + if (recoveryParam == null && signature.v != null) { + recoveryParam = 1 - (v % 2); + } + v = 27 + recoveryParam; + } + else { + var bytes = arrayify(signature); + if (bytes.length !== 65) { + throw new Error('invalid signature'); + } + r = hexlify(bytes.slice(0, 32)); + s = hexlify(bytes.slice(32, 64)); + v = bytes[64]; + if (v !== 27 && v !== 28) { + v = 27 + (v % 2); + } + } + return { + r: r, + s: s, + recoveryParam: (v - 27), + v: v + }; + } + exports.splitSignature = splitSignature; + function joinSignature(signature) { + signature = splitSignature(signature); + return hexlify(concat([ + signature.r, + signature.s, + (signature.recoveryParam ? '0x1c' : '0x1b') + ])); + } + exports.joinSignature = joinSignature; + + },{"./errors":147}],147:[function(require,module,exports){ + 'use strict'; + Object.defineProperty(exports, "__esModule", { value: true }); + // Unknown Error + exports.UNKNOWN_ERROR = 'UNKNOWN_ERROR'; + // Not implemented + exports.NOT_IMPLEMENTED = 'NOT_IMPLEMENTED'; + // Missing new operator to an object + // - name: The name of the class + exports.MISSING_NEW = 'MISSING_NEW'; + // Call exception + // - transaction: the transaction + // - address?: the contract address + // - args?: The arguments passed into the function + // - method?: The Solidity method signature + // - errorSignature?: The EIP848 error signature + // - errorArgs?: The EIP848 error parameters + // - reason: The reason (only for EIP848 "Error(string)") + exports.CALL_EXCEPTION = 'CALL_EXCEPTION'; + // Response from a server was invalid + // - response: The body of the response + //'BAD_RESPONSE', + // Invalid argument (e.g. value is incompatible with type) to a function: + // - arg: The argument name that was invalid + // - value: The value of the argument + exports.INVALID_ARGUMENT = 'INVALID_ARGUMENT'; + // Missing argument to a function: + // - count: The number of arguments received + // - expectedCount: The number of arguments expected + exports.MISSING_ARGUMENT = 'MISSING_ARGUMENT'; + // Too many arguments + // - count: The number of arguments received + // - expectedCount: The number of arguments expected + exports.UNEXPECTED_ARGUMENT = 'UNEXPECTED_ARGUMENT'; + // Numeric Fault + // - operation: the operation being executed + // - fault: the reason this faulted + exports.NUMERIC_FAULT = 'NUMERIC_FAULT'; + // Unsupported operation + // - operation + exports.UNSUPPORTED_OPERATION = 'UNSUPPORTED_OPERATION'; + var _permanentCensorErrors = false; + var _censorErrors = false; + // @TODO: Enum + function throwError(message, code, params) { + if (_censorErrors) { + throw new Error('unknown error'); + } + if (!code) { + code = exports.UNKNOWN_ERROR; + } + if (!params) { + params = {}; + } + var messageDetails = []; + Object.keys(params).forEach(function (key) { + try { + messageDetails.push(key + '=' + JSON.stringify(params[key])); + } + catch (error) { + messageDetails.push(key + '=' + JSON.stringify(params[key].toString())); + } + }); + var reason = message; + if (messageDetails.length) { + message += ' (' + messageDetails.join(', ') + ')'; + } + // @TODO: Any?? + var error = new Error(message); + error.reason = reason; + error.code = code; + Object.keys(params).forEach(function (key) { + error[key] = params[key]; + }); + throw error; + } + exports.throwError = throwError; + function checkNew(self, kind) { + if (!(self instanceof kind)) { + throwError('missing new', exports.MISSING_NEW, { name: kind.name }); + } + } + exports.checkNew = checkNew; + function checkArgumentCount(count, expectedCount, suffix) { + if (!suffix) { + suffix = ''; + } + if (count < expectedCount) { + throwError('missing argument' + suffix, exports.MISSING_ARGUMENT, { count: count, expectedCount: expectedCount }); + } + if (count > expectedCount) { + throwError('too many arguments' + suffix, exports.UNEXPECTED_ARGUMENT, { count: count, expectedCount: expectedCount }); + } + } + exports.checkArgumentCount = checkArgumentCount; + function setCensorship(censorship, permanent) { + if (_permanentCensorErrors) { + throwError('error censorship permanent', exports.UNSUPPORTED_OPERATION, { operation: 'setCersorship' }); + } + _censorErrors = !!censorship; + _permanentCensorErrors = !!permanent; + } + exports.setCensorship = setCensorship; + + },{}],148:[function(require,module,exports){ + 'use strict'; + Object.defineProperty(exports, "__esModule", { value: true }); + var sha3 = require("js-sha3"); + var bytes_1 = require("./bytes"); + function keccak256(data) { + return '0x' + sha3.keccak_256(bytes_1.arrayify(data)); + } + exports.keccak256 = keccak256; + + },{"./bytes":146,"js-sha3":142}],149:[function(require,module,exports){ + 'use strict'; + Object.defineProperty(exports, "__esModule", { value: true }); + function defineReadOnly(object, name, value) { + Object.defineProperty(object, name, { + enumerable: true, + value: value, + writable: false, + }); + } + exports.defineReadOnly = defineReadOnly; + function defineFrozen(object, name, value) { + var frozen = JSON.stringify(value); + Object.defineProperty(object, name, { + enumerable: true, + get: function () { return JSON.parse(frozen); } + }); + } + exports.defineFrozen = defineFrozen; + function resolveProperties(object) { + var result = {}; + var promises = []; + Object.keys(object).forEach(function (key) { + var value = object[key]; + if (value instanceof Promise) { + promises.push(value.then(function (value) { + result[key] = value; + return null; + })); + } + else { + result[key] = value; + } + }); + return Promise.all(promises).then(function () { + return result; + }); + } + exports.resolveProperties = resolveProperties; + function shallowCopy(object) { + var result = {}; + for (var key in object) { + result[key] = object[key]; + } + return result; + } + exports.shallowCopy = shallowCopy; + function jsonCopy(object) { + return JSON.parse(JSON.stringify(object)); + } + exports.jsonCopy = jsonCopy; + + },{}],150:[function(require,module,exports){ + "use strict"; + //See: https://github.com/ethereum/wiki/wiki/RLP + Object.defineProperty(exports, "__esModule", { value: true }); + var bytes_1 = require("./bytes"); + function arrayifyInteger(value) { + var result = []; + while (value) { + result.unshift(value & 0xff); + value >>= 8; + } + return result; + } + function unarrayifyInteger(data, offset, length) { + var result = 0; + for (var i = 0; i < length; i++) { + result = (result * 256) + data[offset + i]; + } + return result; + } + function _encode(object) { + if (Array.isArray(object)) { + var payload = []; + object.forEach(function (child) { + payload = payload.concat(_encode(child)); + }); + if (payload.length <= 55) { + payload.unshift(0xc0 + payload.length); + return payload; + } + var length = arrayifyInteger(payload.length); + length.unshift(0xf7 + length.length); + return length.concat(payload); + } + var data = Array.prototype.slice.call(bytes_1.arrayify(object)); + if (data.length === 1 && data[0] <= 0x7f) { + return data; + } + else if (data.length <= 55) { + data.unshift(0x80 + data.length); + return data; + } + var length = arrayifyInteger(data.length); + length.unshift(0xb7 + length.length); + return length.concat(data); + } + function encode(object) { + return bytes_1.hexlify(_encode(object)); + } + exports.encode = encode; + function _decodeChildren(data, offset, childOffset, length) { + var result = []; + while (childOffset < offset + 1 + length) { + var decoded = _decode(data, childOffset); + result.push(decoded.result); + childOffset += decoded.consumed; + if (childOffset > offset + 1 + length) { + throw new Error('invalid rlp'); + } + } + return { consumed: (1 + length), result: result }; + } + // returns { consumed: number, result: Object } + function _decode(data, offset) { + if (data.length === 0) { + throw new Error('invalid rlp data'); + } + // Array with extra length prefix + if (data[offset] >= 0xf8) { + var lengthLength = data[offset] - 0xf7; + if (offset + 1 + lengthLength > data.length) { + throw new Error('too short'); + } + var length = unarrayifyInteger(data, offset + 1, lengthLength); + if (offset + 1 + lengthLength + length > data.length) { + throw new Error('to short'); + } + return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length); + } + else if (data[offset] >= 0xc0) { + var length = data[offset] - 0xc0; + if (offset + 1 + length > data.length) { + throw new Error('invalid rlp data'); + } + return _decodeChildren(data, offset, offset + 1, length); + } + else if (data[offset] >= 0xb8) { + var lengthLength = data[offset] - 0xb7; + if (offset + 1 + lengthLength > data.length) { + throw new Error('invalid rlp data'); + } + var length = unarrayifyInteger(data, offset + 1, lengthLength); + if (offset + 1 + lengthLength + length > data.length) { + throw new Error('invalid rlp data'); + } + var result = bytes_1.hexlify(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length)); + return { consumed: (1 + lengthLength + length), result: result }; + } + else if (data[offset] >= 0x80) { + var length = data[offset] - 0x80; + if (offset + 1 + length > data.length) { + throw new Error('invlaid rlp data'); + } + var result = bytes_1.hexlify(data.slice(offset + 1, offset + 1 + length)); + return { consumed: (1 + length), result: result }; + } + return { consumed: 1, result: bytes_1.hexlify(data[offset]) }; + } + function decode(data) { + var bytes = bytes_1.arrayify(data); + var decoded = _decode(bytes, 0); + if (decoded.consumed !== bytes.length) { + throw new Error('invalid rlp data'); + } + return decoded.result; + } + exports.decode = decode; + + },{"./bytes":146}],151:[function(require,module,exports){ + "use strict"; + /////////////////////////////// + // Bytes + Object.defineProperty(exports, "__esModule", { value: true }); + /////////////////////////////// + // BigNumber + var BigNumber = /** @class */ (function () { + function BigNumber() { + } + return BigNumber; + }()); + exports.BigNumber = BigNumber; + ; + ; + ; + /////////////////////////////// + // Interface + var Indexed = /** @class */ (function () { + function Indexed() { + } + return Indexed; + }()); + exports.Indexed = Indexed; + /** + * Provider + * + * Note: We use an abstract class so we can use instanceof to determine if an + * object is a Provider. + */ + var MinimalProvider = /** @class */ (function () { + function MinimalProvider() { + } + return MinimalProvider; + }()); + exports.MinimalProvider = MinimalProvider; + /** + * Signer + * + * Note: We use an abstract class so we can use instanceof to determine if an + * object is a Signer. + */ + var Signer = /** @class */ (function () { + function Signer() { + } + return Signer; + }()); + exports.Signer = Signer; + /////////////////////////////// + // HDNode + var HDNode = /** @class */ (function () { + function HDNode() { + } + return HDNode; + }()); + exports.HDNode = HDNode; + + },{}],152:[function(require,module,exports){ + 'use strict'; + Object.defineProperty(exports, "__esModule", { value: true }); + var bytes_1 = require("./bytes"); + var UnicodeNormalizationForm; + (function (UnicodeNormalizationForm) { + UnicodeNormalizationForm["current"] = ""; + UnicodeNormalizationForm["NFC"] = "NFC"; + UnicodeNormalizationForm["NFD"] = "NFD"; + UnicodeNormalizationForm["NFKC"] = "NFKC"; + UnicodeNormalizationForm["NFKD"] = "NFKD"; + })(UnicodeNormalizationForm = exports.UnicodeNormalizationForm || (exports.UnicodeNormalizationForm = {})); + ; + // http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array + function toUtf8Bytes(str, form) { + if (form === void 0) { form = UnicodeNormalizationForm.current; } + if (form != UnicodeNormalizationForm.current) { + str = str.normalize(form); + } + var result = []; + var offset = 0; + for (var i = 0; i < str.length; i++) { + var c = str.charCodeAt(i); + if (c < 128) { + result[offset++] = c; + } + else if (c < 2048) { + result[offset++] = (c >> 6) | 192; + result[offset++] = (c & 63) | 128; + } + else if (((c & 0xFC00) == 0xD800) && (i + 1) < str.length && ((str.charCodeAt(i + 1) & 0xFC00) == 0xDC00)) { + // Surrogate Pair + c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF); + result[offset++] = (c >> 18) | 240; + result[offset++] = ((c >> 12) & 63) | 128; + result[offset++] = ((c >> 6) & 63) | 128; + result[offset++] = (c & 63) | 128; + } + else { + result[offset++] = (c >> 12) | 224; + result[offset++] = ((c >> 6) & 63) | 128; + result[offset++] = (c & 63) | 128; + } + } + return bytes_1.arrayify(result); + } + exports.toUtf8Bytes = toUtf8Bytes; + ; + // http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499 + function toUtf8String(bytes) { + bytes = bytes_1.arrayify(bytes); + var result = ''; + var i = 0; + // Invalid bytes are ignored + while (i < bytes.length) { + var c = bytes[i++]; + if (c >> 7 == 0) { + // 0xxx xxxx + result += String.fromCharCode(c); + continue; + } + // Invalid starting byte + if (c >> 6 == 0x02) { + continue; + } + // Multibyte; how many bytes left for thus character? + var extraLength = null; + if (c >> 5 == 0x06) { + extraLength = 1; + } + else if (c >> 4 == 0x0e) { + extraLength = 2; + } + else if (c >> 3 == 0x1e) { + extraLength = 3; + } + else if (c >> 2 == 0x3e) { + extraLength = 4; + } + else if (c >> 1 == 0x7e) { + extraLength = 5; + } + else { + continue; + } + // Do we have enough bytes in our data? + if (i + extraLength > bytes.length) { + // If there is an invalid unprocessed byte, try to continue + for (; i < bytes.length; i++) { + if (bytes[i] >> 6 != 0x02) { + break; + } + } + if (i != bytes.length) + continue; + // All leftover bytes are valid. + return result; + } + // Remove the UTF-8 prefix from the char (res) + var res = c & ((1 << (8 - extraLength - 1)) - 1); + var count; + for (count = 0; count < extraLength; count++) { + var nextChar = bytes[i++]; + // Is the char valid multibyte part? + if (nextChar >> 6 != 0x02) { + break; + } + ; + res = (res << 6) | (nextChar & 0x3f); + } + if (count != extraLength) { + i--; + continue; + } + if (res <= 0xffff) { + result += String.fromCharCode(res); + continue; + } + res -= 0x10000; + result += String.fromCharCode(((res >> 10) & 0x3ff) + 0xd800, (res & 0x3ff) + 0xdc00); + } + return result; + } + exports.toUtf8String = toUtf8String; + + },{"./bytes":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 + 'wei': '1', // eslint-disable-line + 'kwei': '1000', // eslint-disable-line + 'Kwei': '1000', // eslint-disable-line + 'babbage': '1000', // eslint-disable-line + 'femtoether': '1000', // eslint-disable-line + 'mwei': '1000000', // eslint-disable-line + 'Mwei': '1000000', // eslint-disable-line + 'lovelace': '1000000', // eslint-disable-line + 'picoether': '1000000', // eslint-disable-line + 'gwei': '1000000000', // eslint-disable-line + 'Gwei': '1000000000', // eslint-disable-line + 'shannon': '1000000000', // eslint-disable-line + 'nanoether': '1000000000', // eslint-disable-line + 'nano': '1000000000', // eslint-disable-line + 'szabo': '1000000000000', // eslint-disable-line + 'microether': '1000000000000', // eslint-disable-line + 'micro': '1000000000000', // eslint-disable-line + 'finney': '1000000000000000', // eslint-disable-line + 'milliether': '1000000000000000', // eslint-disable-line + 'milli': '1000000000000000', // eslint-disable-line + 'ether': '1000000000000000000', // eslint-disable-line + 'kether': '1000000000000000000000', // eslint-disable-line + 'grand': '1000000000000000000000', // eslint-disable-line + 'mether': '1000000000000000000000000', // eslint-disable-line + 'gether': '1000000000000000000000000000', // eslint-disable-line + 'tether': '1000000000000000000000000000000' }; + + /** + * Returns value of unit in Wei + * + * @method getValueOfUnit + * @param {String} unit the unit to convert to, default ether + * @returns {BigNumber} value of the unit (in Wei) + * @throws error if the unit is not correct:w + */ + function getValueOfUnit(unitInput) { + var unit = unitInput ? unitInput.toLowerCase() : 'ether'; + var unitValue = unitMap[unit]; // eslint-disable-line + + if (typeof unitValue !== 'string') { + throw new Error('[ethjs-unit] the unit provided ' + unitInput + ' doesn\'t exists, please use the one of the following units ' + JSON.stringify(unitMap, null, 2)); + } + + return new BN(unitValue, 10); + } + + function numberToString(arg) { + if (typeof arg === 'string') { + if (!arg.match(/^-?[0-9.]+$/)) { + throw new Error('while converting number to string, invalid number value \'' + arg + '\', should be a number matching (^-?[0-9.]+).'); + } + return arg; + } else if (typeof arg === 'number') { + return String(arg); + } else if (typeof arg === 'object' && arg.toString && (arg.toTwos || arg.dividedToIntegerBy)) { + if (arg.toPrecision) { + return String(arg.toPrecision()); + } else { + // eslint-disable-line + return arg.toString(10); + } + } + throw new Error('while converting number to string, invalid number value \'' + arg + '\' type ' + typeof arg + '.'); + } + + function fromWei(weiInput, unit, optionsInput) { + var wei = numberToBN(weiInput); // eslint-disable-line + var negative = wei.lt(zero); // eslint-disable-line + var base = getValueOfUnit(unit); + var baseLength = unitMap[unit].length - 1 || 1; + var options = optionsInput || {}; + + if (negative) { + wei = wei.mul(negative1); + } + + var fraction = wei.mod(base).toString(10); // eslint-disable-line + + while (fraction.length < baseLength) { + fraction = '0' + fraction; + } + + if (!options.pad) { + fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1]; + } + + var whole = wei.div(base).toString(10); // eslint-disable-line + + if (options.commify) { + whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ','); + } + + var value = '' + whole + (fraction == '0' ? '' : '.' + fraction); // eslint-disable-line + + if (negative) { + value = '-' + value; + } + + return value; + } + + function toWei(etherInput, unit) { + var ether = numberToString(etherInput); // eslint-disable-line + var base = getValueOfUnit(unit); + var baseLength = unitMap[unit].length - 1 || 1; + + // Is it negative? + var negative = ether.substring(0, 1) === '-'; // eslint-disable-line + if (negative) { + ether = ether.substring(1); + } + + if (ether === '.') { + throw new Error('[ethjs-unit] while converting number ' + etherInput + ' to wei, invalid value'); + } + + // Split it into a whole and fractional part + var comps = ether.split('.'); // eslint-disable-line + if (comps.length > 2) { + throw new Error('[ethjs-unit] while converting number ' + etherInput + ' to wei, too many decimal points'); + } + + var whole = comps[0], + fraction = comps[1]; // eslint-disable-line + + if (!whole) { + whole = '0'; + } + if (!fraction) { + fraction = '0'; + } + if (fraction.length > baseLength) { + throw new Error('[ethjs-unit] while converting number ' + etherInput + ' to wei, too many decimal places'); + } + + while (fraction.length < baseLength) { + fraction += '0'; + } + + whole = new BN(whole); + fraction = new BN(fraction); + var wei = whole.mul(base).add(fraction); // eslint-disable-line + + if (negative) { + wei = wei.mul(negative1); + } + + return new BN(wei.toString(10), 10); + } + + module.exports = { + unitMap: unitMap, + numberToString: numberToString, + getValueOfUnit: getValueOfUnit, + fromWei: fromWei, + toWei: toWei + }; + },{"bn.js":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) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + + // BN + + function BN (number, base, endian) { + if (BN.isBN(number)) { + return number; + } + + this.negative = 0; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (number !== null) { + if (base === 'le' || base === 'be') { + endian = base; + base = 10; + } + + this._init(number || 0, base || 10, endian || 'be'); + } + } + if (typeof module === 'object') { + module.exports = BN; + } else { + exports.BN = BN; + } + + BN.BN = BN; + BN.wordSize = 26; + + var Buffer; + try { + Buffer = require('buf' + 'fer').Buffer; + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); + }; + + BN.max = function max (left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + + BN.min = function min (left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + + BN.prototype._init = function init (number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } + + if (typeof number === 'object') { + return this._initArray(number, base, endian); + } + + if (base === 'hex') { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; + } + + if (base === 16) { + this._parseHex(number, start); + } else { + this._parseBase(number, base, start); + } + + if (number[0] === '-') { + this.negative = 1; + } + + this.strip(); + + if (endian !== 'le') return; + + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initNumber = function _initNumber (number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; + } + + if (endian !== 'le') return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); + }; + + BN.prototype._initArray = function _initArray (number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; + } + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + var off = 0; + if (endian === 'be') { + for (i = number.length - 1, j = 0; i >= 0; i -= 3) { + w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } else if (endian === 'le') { + for (i = 0, j = 0; i < number.length; i += 3) { + w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + } + return this.strip(); + }; + + function parseHex (str, start, end) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r <<= 4; + + // 'a' - 'f' + if (c >= 49 && c <= 54) { + r |= c - 49 + 0xa; + + // 'A' - 'F' + } else if (c >= 17 && c <= 22) { + r |= c - 17 + 0xa; + + // '0' - '9' + } else { + r |= c & 0xf; + } + } + return r; + } + + BN.prototype._parseHex = function _parseHex (number, start) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + this.words[i] = 0; + } + + var j, w; + // Scan 24-bit chunks and add them to the number + var off = 0; + for (i = number.length - 6, j = 0; i >= start; i -= 6) { + w = parseHex(number, i, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } + } + if (i + 6 !== start) { + w = parseHex(number, start, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + } + this.strip(); + }; + + function parseBase (str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } + } + return r; + } + + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; + } + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + + for (i = 0; i < mod; i++) { + pow *= base; + } + + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + }; + + BN.prototype.copy = function copy (dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) { + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; + + BN.prototype._expand = function _expand (size) { + while (this.length < size) { + this.words[this.length++] = 0; + } + return this; + }; + + // Remove leading `0` from `this` + BN.prototype.strip = function strip () { + while (this.length > 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; + + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; + + /* + + var zeros = []; + var groupSizes = []; + var groupBases = []; + + var s = ''; + var i = -1; + while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; + } + groupSizes[0] = 0; + groupSizes[1] = 0; + groupBases[0] = 0; + groupBases[1] = 0; + var base = 2 - 1; + while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; + } + + */ + + var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' + ]; + + var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 + ]; + + var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 + ]; + + BN.prototype.toString = function toString (base, padding) { + base = base || 10; + padding = padding | 0 || 1; + + var out; + if (base === 16 || base === 'hex') { + out = ''; + var off = 0; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + out = ''; + var c = this.clone(); + c.negative = 0; + while (!c.isZero()) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } + } + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; + } + + assert(false, 'Base should be between 2 and 36'); + }; + + BN.prototype.toNumber = function toNumber () { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 0x4000000; + } else if (this.length === 3 && this.words[2] === 0x01) { + // NOTE: at this stage it is known that the top bit is set + ret += 0x10000000000000 + (this.words[1] * 0x4000000); + } else if (this.length > 2) { + assert(false, 'Number can only safely store up to 53 bits'); + } + return (this.negative !== 0) ? -ret : ret; + }; + + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; + + BN.prototype.toBuffer = function toBuffer (endian, length) { + assert(typeof Buffer !== 'undefined'); + return this.toArrayLike(Buffer, endian, length); + }; + + BN.prototype.toArray = function toArray (endian, length) { + return this.toArrayLike(Array, endian, length); + }; + + BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, 'byte array longer than desired length'); + assert(reqLength > 0, 'Requested array length <= 0'); + + this.strip(); + var littleEndian = endian === 'le'; + var res = new ArrayType(reqLength); + + var b, i; + var q = this.clone(); + if (!littleEndian) { + // Assume big-endian + for (i = 0; i < reqLength - byteLength; i++) { + res[i] = 0; + } + + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[reqLength - i - 1] = b; + } + } else { + for (i = 0; !q.isZero(); i++) { + b = q.andln(0xff); + q.iushrn(8); + + res[i] = b; + } + + for (; i < reqLength; i++) { + res[i] = 0; + } + } + + return res; + }; + + if (Math.clz32) { + BN.prototype._countBits = function _countBits (w) { + return 32 - Math.clz32(w); + }; + } else { + BN.prototype._countBits = function _countBits (w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; + } + + BN.prototype._zeroBits = function _zeroBits (w) { + // Short-cut + if (w === 0) return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) { + r++; + } + return r; + }; + + // Return number of used bits in a BN + BN.prototype.bitLength = function bitLength () { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + + function toBitArray (num) { + var w = new Array(num.bitLength()); + + for (var bit = 0; bit < w.length; bit++) { + var off = (bit / 26) | 0; + var wbit = bit % 26; + + w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + } + + return w; + } + + // Number of trailing zero bits + BN.prototype.zeroBits = function zeroBits () { + if (this.isZero()) return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + + BN.prototype.byteLength = function byteLength () { + return Math.ceil(this.bitLength() / 8); + }; + + BN.prototype.toTwos = function toTwos (width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + + BN.prototype.fromTwos = function fromTwos (width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + + BN.prototype.isNeg = function isNeg () { + return this.negative !== 0; + }; + + // Return negative clone of `this` + BN.prototype.neg = function neg () { + return this.clone().ineg(); + }; + + BN.prototype.ineg = function ineg () { + if (!this.isZero()) { + this.negative ^= 1; + } + + return this; + }; + + // Or `num` with `this` in-place + BN.prototype.iuor = function iuor (num) { + while (this.length < num.length) { + this.words[this.length++] = 0; + } + + for (var i = 0; i < num.length; i++) { + this.words[i] = this.words[i] | num.words[i]; + } + + return this.strip(); + }; + + BN.prototype.ior = function ior (num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + + // Or `num` with `this` + BN.prototype.or = function or (num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + + BN.prototype.uor = function uor (num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + + // And `num` with `this` in-place + BN.prototype.iuand = function iuand (num) { + // b = min-length(num, this) + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = this.words[i] & num.words[i]; + } + + this.length = b.length; + + return this.strip(); + }; + + BN.prototype.iand = function iand (num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + + // And `num` with `this` + BN.prototype.and = function and (num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + + BN.prototype.uand = function uand (num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + + // Xor `num` with `this` in-place + BN.prototype.iuxor = function iuxor (num) { + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + for (var i = 0; i < b.length; i++) { + this.words[i] = a.words[i] ^ b.words[i]; + } + + if (this !== a) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = a.length; + + return this.strip(); + }; + + BN.prototype.ixor = function ixor (num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + + // Xor `num` with `this` + BN.prototype.xor = function xor (num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + + BN.prototype.uxor = function uxor (num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + + // Not ``this`` with ``width`` bitwidth + BN.prototype.inotn = function inotn (width) { + assert(typeof width === 'number' && width >= 0); + + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + + // Extend the buffer with leading zeroes + this._expand(bytesNeeded); + + if (bitsLeft > 0) { + bytesNeeded--; + } + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; + } + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); + } + + // And remove leading zeroes + return this.strip(); + }; + + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; + + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + + return this.strip(); + }; + + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; + + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + return this; + }; + + // Add `num` to `this` + BN.prototype.add = function add (num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + + if (this.length > num.length) return this.clone().iadd(num); + + return num.clone().iadd(this); + }; + + // Subtract `num` from `this` in-place + BN.prototype.isub = function isub (num) { + // this - (-num) = this + num + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + + // a > b + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) { + for (; i < a.length; i++) { + this.words[i] = a.words[i]; + } + } + + this.length = Math.max(this.length, i); + + if (a !== this) { + this.negative = 1; + } + + return this.strip(); + }; + + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; + + function smallMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + var len = (self.length + num.length) | 0; + out.length = len; + len = (len - 1) | 0; + + // Peel one iteration (compiler can't do it, because of code complexity) + var a = self.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; + + for (var k = 1; k < len; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = (k - j) | 0; + a = self.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += (r / 0x4000000) | 0; + rword = r & 0x3ffffff; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + + return out.strip(); + } + + // TODO(indutny): it may be reasonable to omit it for users who don't need + // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit + // multiplication (like elliptic secp256k1). + var comb10MulTo = function comb10MulTo (self, num, out) { + var a = self.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 0x1fff; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 0x1fff; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 0x1fff; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 0x1fff; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 0x1fff; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 0x1fff; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 0x1fff; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 0x1fff; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 0x1fff; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 0x1fff; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 0x1fff; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 0x1fff; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 0x1fff; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 0x1fff; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 0x1fff; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 0x1fff; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 0x1fff; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 0x1fff; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 0x1fff; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 0x1fff; + var bh9 = b9 >>> 13; + + out.negative = self.negative ^ num.negative; + out.length = 19; + /* k = 0 */ + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + w18 &= 0x3ffffff; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = self.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + + return out.strip(); + } + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); + } + + BN.prototype.mulTo = function mulTo (num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + + return res; + }; + + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion + + function FFTM (x, y) { + this.x = x; + this.y = y; + } + + FFTM.prototype.makeRBT = function makeRBT (N) { + var t = new Array(N); + var l = BN.prototype._countBits(N) - 1; + for (var i = 0; i < N; i++) { + t[i] = this.revBin(i, l, N); + } + + return t; + }; + + // Returns binary-reversed representation of `x` + FFTM.prototype.revBin = function revBin (x, l, N) { + if (x === 0 || x === N - 1) return x; + + var rb = 0; + for (var i = 0; i < l; i++) { + rb |= (x & 1) << (l - i - 1); + x >>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < N; i++) { + rtws[i] = rws[rbt[i]]; + itws[i] = iws[rbt[i]]; + } + }; + + FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { + this.permute(rbt, rws, iws, rtws, itws, N); + + for (var s = 1; s < N; s <<= 1) { + var l = s << 1; + + var rtwdf = Math.cos(2 * Math.PI / l); + var itwdf = Math.sin(2 * Math.PI / l); + + for (var p = 0; p < N; p += l) { + var rtwdf_ = rtwdf; + var itwdf_ = itwdf; + + for (var j = 0; j < s; j++) { + var re = rtws[p + j]; + var ie = itws[p + j]; + + var ro = rtws[p + j + s]; + var io = itws[p + j + s]; + + var rx = rtwdf_ * ro - itwdf_ * io; + + io = rtwdf_ * io + itwdf_ * ro; + ro = rx; + + rtws[p + j] = re + ro; + itws[p + j] = ie + io; + + rtws[p + j + s] = re - ro; + itws[p + j + s] = ie - io; + + /* jshint maxdepth : false */ + if (j !== l) { + rx = rtwdf * rtwdf_ - itwdf * itwdf_; + + itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; + rtwdf_ = rx; + } + } + } + } + }; + + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { + var N = Math.max(m, n) | 1; + var odd = N & 1; + var i = 0; + for (N = N / 2 | 0; N; N = N >>> 1) { + i++; + } + + return 1 << i + 1 + odd; + }; + + FFTM.prototype.conjugate = function conjugate (rws, iws, N) { + if (N <= 1) return; + + for (var i = 0; i < N / 2; i++) { + var t = rws[i]; + + rws[i] = rws[N - i - 1]; + rws[N - i - 1] = t; + + t = iws[i]; + + iws[i] = -iws[N - i - 1]; + iws[N - i - 1] = -t; + } + }; + + FFTM.prototype.normalize13b = function normalize13b (ws, N) { + var carry = 0; + for (var i = 0; i < N / 2; i++) { + var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + + Math.round(ws[2 * i] / N) + + carry; + + ws[i] = w & 0x3ffffff; + + if (w < 0x4000000) { + carry = 0; + } else { + carry = w / 0x4000000 | 0; + } + } + + return ws; + }; + + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); + + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } + + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } + + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; + + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } + + return ph; + }; + + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); + + var rbt = this.makeRBT(N); + + var _ = this.stub(N); + + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); + + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); + + var rmws = out.words; + rmws.length = N; + + this.convert13b(x.words, x.length, rws, N); + this.convert13b(y.words, y.length, nrws, N); + + this.transform(rws, _, rwst, iwst, N, rbt); + this.transform(nrws, _, nrwst, niwst, N, rbt); + + for (var i = 0; i < N; i++) { + var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; + iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; + rwst[i] = rx; + } + + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); + + out.negative = x.negative ^ y.negative; + out.length = x.length + y.length; + return out.strip(); + }; + + // Multiply `this` by `num` + BN.prototype.mul = function mul (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + + // Multiply employing FFT + BN.prototype.mulf = function mulf (num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + + // In-place Multiplication + BN.prototype.imul = function imul (num) { + return this.clone().mulTo(num, this); + }; + + BN.prototype.imuln = function imuln (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = (this.words[i] | 0) * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } + + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + + return this; + }; + + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; + + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; + + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; + + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(1); + + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; + } + + if (++i < w.length) { + for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { + if (w[i] === 0) continue; + + res = res.mul(q); + } + } + + return res; + }; + + // Shift-left in-place + BN.prototype.iushln = function iushln (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + var i; + + if (r !== 0) { + var carry = 0; + + for (i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = ((this.words[i] | 0) - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + + if (carry) { + this.words[i] = carry; + this.length++; + } + } + + if (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; + } + + for (i = 0; i < s; i++) { + this.words[i] = 0; + } + + this.length += s; + } + + return this.strip(); + }; + + BN.prototype.ishln = function ishln (bits) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushln(bits); + }; + + // Shift-right in-place + // NOTE: `hint` is a lowest bit before trailing zeroes + // NOTE: if `extended` is present - it will be filled with destroyed bits + BN.prototype.iushrn = function iushrn (bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) { + h = (hint - (hint % 26)) / 26; + } else { + h = 0; + } + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) { + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (i = 0; i < this.length; i++) { + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i] | 0; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + return this.strip(); + }; + + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; + + BN.prototype.ushln = function ushln (bits) { + return this.clone().iushln(bits); + }; + + // Shift-right + BN.prototype.shrn = function shrn (bits) { + return this.clone().ishrn(bits); + }; + + BN.prototype.ushrn = function ushrn (bits) { + return this.clone().iushrn(bits); + }; + + // Test if n bit is set + BN.prototype.testn = function testn (bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) return false; + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); + }; + + // Return only lowers bits of number (in-place) + BN.prototype.imaskn = function imaskn (bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(this.negative === 0, 'imaskn works only with positive numbers'); + + if (this.length <= s) { + return this; + } + + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); + }; + + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; + + // Add plain number `num` to `this` + BN.prototype.iaddn = function iaddn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.isubn(-num); + + // Possible sign change + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) < num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + + // Add without checks + return this._iaddn(num); + }; + + BN.prototype._iaddn = function _iaddn (num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + + return this; + }; + + // Subtract plain number `num` from `this` + BN.prototype.isubn = function isubn (num) { + assert(typeof num === 'number'); + assert(num < 0x4000000); + if (num < 0) return this.iaddn(-num); + + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } + } + + return this.strip(); + }; + + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; + + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; + + BN.prototype.iabs = function iabs () { + this.negative = 0; + + return this; + }; + + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; + + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; + + this._expand(len); + + var w; + var carry = 0; + for (i = 0; i < num.length; i++) { + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } + + if (carry === 0) return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (i = 0; i < this.length; i++) { + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.negative = 1; + + return this.strip(); + }; + + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) { + q.words[i] = 0; + } + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.negative !== 0) { + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q.strip(); + } + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) { + a.iushrn(shift); + } + + return { + div: q || null, + mod: a + }; + }; + + // NOTE: 1) `mode` can be set to `mod` to request mod only, + // to `div` to request div only, or be absent to + // request both div & mod + // 2) `positive` is true if unsigned mod is requested + BN.prototype.divmod = function divmod (num, mode, positive) { + assert(!num.isZero()); + + if (this.isZero()) { + return { + div: new BN(0), + mod: new BN(0) + }; + } + + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + + return { + div: div, + mod: mod + }; + } + + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + + if (mode !== 'mod') { + div = res.div.neg(); + } + + return { + div: div, + mod: res.mod + }; + } + + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + + return { + div: res.div, + mod: mod + }; + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; + } + + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); + }; + + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; + + // Find `this` % `num` + BN.prototype.mod = function mod (num) { + return this.divmod(num, 'mod', false).mod; + }; + + BN.prototype.umod = function umod (num) { + return this.divmod(num, 'mod', true).mod; + }; + + // Find Round(`this` / `num`) + BN.prototype.divRound = function divRound (num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.isZero()) return dm.div; + + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; + } + + return acc; + }; + + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = (this.words[i] | 0) + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); + }; + + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; + + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var x = this; + var y = p.clone(); + + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.iushrn(1); + y.iushrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (!x.isZero()) { + for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while (i-- > 0) { + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + + A.iushrn(1); + B.iushrn(1); + } + } + + for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while (j-- > 0) { + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + + C.iushrn(1); + D.iushrn(1); + } + } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + + // This is reduced incarnation of the binary EEA + // above, designated to invert members of the + // _prime_ fields F(p) at a maximal speed + BN.prototype._invmp = function _invmp (p) { + assert(p.negative === 0); + assert(!p.isZero()); + + var a = this; + var b = p.clone(); + + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while (i-- > 0) { + if (x1.isOdd()) { + x1.iadd(delta); + } + + x1.iushrn(1); + } + } + + for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while (j-- > 0) { + if (x2.isOdd()) { + x2.iadd(delta); + } + + x2.iushrn(1); + } + } + + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + + if (res.cmpn(0) < 0) { + res.iadd(p); + } + + return res; + }; + + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } + + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.iushln(shift); + }; + + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; + + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; + + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; + + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; + + // Increment at the bit position in-line + BN.prototype.bincn = function bincn (bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + + BN.prototype.isZero = function isZero () { + return this.length === 1 && this.words[0] === 0; + }; + + BN.prototype.cmpn = function cmpn (num) { + var negative = num < 0; + + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + + assert(num <= 0x3ffffff, 'Number is too big'); + + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Compare two numbers and return: + // 1 - if `this` > `num` + // 0 - if `this` == `num` + // -1 - if `this` < `num` + BN.prototype.cmp = function cmp (num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + + // Unsigned comparison + BN.prototype.ucmp = function ucmp (num) { + // At this point both numbers have the same sign + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i] | 0; + var b = num.words[i] | 0; + + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + + BN.prototype.gtn = function gtn (num) { + return this.cmpn(num) === 1; + }; + + BN.prototype.gt = function gt (num) { + return this.cmp(num) === 1; + }; + + BN.prototype.gten = function gten (num) { + return this.cmpn(num) >= 0; + }; + + BN.prototype.gte = function gte (num) { + return this.cmp(num) >= 0; + }; + + BN.prototype.ltn = function ltn (num) { + return this.cmpn(num) === -1; + }; + + BN.prototype.lt = function lt (num) { + return this.cmp(num) === -1; + }; + + BN.prototype.lten = function lten (num) { + return this.cmpn(num) <= 0; + }; + + BN.prototype.lte = function lte (num) { + return this.cmp(num) <= 0; + }; + + BN.prototype.eqn = function eqn (num) { + return this.cmpn(num) === 0; + }; + + BN.prototype.eq = function eq (num) { + return this.cmp(num) === 0; + }; + + // + // A reduce context, could be using montgomery or something better, depending + // on the `m` itself. + // + BN.red = function red (num) { + return new Red(num); + }; + + BN.prototype.toRed = function toRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(this.negative === 0, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); + }; + + BN.prototype.fromRed = function fromRed () { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); + }; + + BN.prototype._forceRed = function _forceRed (ctx) { + this.red = ctx; + return this; + }; + + BN.prototype.forceRed = function forceRed (ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); + }; + + BN.prototype.redAdd = function redAdd (num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); + }; + + BN.prototype.redIAdd = function redIAdd (num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); + }; + + BN.prototype.redSub = function redSub (num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); + }; + + BN.prototype.redISub = function redISub (num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); + }; + + BN.prototype.redShl = function redShl (num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); + }; + + BN.prototype.redMul = function redMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + + BN.prototype.redIMul = function redIMul (num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + + BN.prototype.redSqr = function redSqr () { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); + }; + + BN.prototype.redISqr = function redISqr () { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); + }; + + // Square root over p + BN.prototype.redSqrt = function redSqrt () { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); + }; + + BN.prototype.redInvm = function redInvm () { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); + }; + + // Return negative clone of `this` % `red modulo` + BN.prototype.redNeg = function redNeg () { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); + }; + + BN.prototype.redPow = function redPow (num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); + }; + + // Prime numbers with efficient reduction + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + + // Pseudo-Mersenne prime + function MPrime (name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).iushln(this.n).isub(this.p); + + this.tmp = this._tmp(); + } + + MPrime.prototype._tmp = function _tmp () { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + + MPrime.prototype.ireduce = function ireduce (num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + r.strip(); + } + + return r; + }; + + MPrime.prototype.split = function split (input, out) { + input.iushrn(this.n, 0, out); + }; + + MPrime.prototype.imulK = function imulK (num) { + return num.imul(this.k); + }; + + function K256 () { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + } + inherits(K256, MPrime); + + K256.prototype.split = function split (input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) { + output.words[i] = input.words[i]; + } + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (i = 10; i < input.length; i++) { + var next = input.words[i] | 0; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + + K256.prototype.imulK = function imulK (num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i] | 0; + lo += w * 0x3d1; + num.words[i] = lo & 0x3ffffff; + lo = w * 0x40 + ((lo / 0x4000000) | 0); + } + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + + function P224 () { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + } + inherits(P224, MPrime); + + function P192 () { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + } + inherits(P192, MPrime); + + function P25519 () { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + } + inherits(P25519, MPrime); + + P25519.prototype.imulK = function imulK (num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = (num.words[i] | 0) * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + + // Exported mostly for testing purposes, use plain name instead + BN._prime = function prime (name) { + // Cached version of prime + if (primes[name]) return primes[name]; + + var prime; + if (name === 'k256') { + prime = new K256(); + } else if (name === 'p224') { + prime = new P224(); + } else if (name === 'p192') { + prime = new P192(); + } else if (name === 'p25519') { + prime = new P25519(); + } else { + throw new Error('Unknown prime ' + name); + } + primes[name] = prime; + + return prime; + }; + + // + // Base reduction engine + // + function Red (m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), 'modulus must be greater than 1'); + this.m = m; + this.prime = null; + } + } + + Red.prototype._verify1 = function _verify1 (a) { + assert(a.negative === 0, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); + }; + + Red.prototype._verify2 = function _verify2 (a, b) { + assert((a.negative | b.negative) === 0, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); + }; + + Red.prototype.imod = function imod (a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + return a.umod(this.m)._forceRed(this); + }; + + Red.prototype.neg = function neg (a) { + if (a.isZero()) { + return a.clone(); + } + + return this.m.sub(a)._forceRed(this); + }; + + Red.prototype.add = function add (a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.iadd = function iadd (a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + + Red.prototype.sub = function sub (a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + + Red.prototype.isub = function isub (a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + + Red.prototype.shl = function shl (a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + + Red.prototype.imul = function imul (a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + + Red.prototype.mul = function mul (a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + + Red.prototype.isqr = function isqr (a) { + return this.imul(a, a.clone()); + }; + + Red.prototype.sqr = function sqr (a) { + return this.mul(a, a); + }; + + Red.prototype.sqrt = function sqrt (a) { + if (a.isZero()) return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).iushrn(2); + return this.pow(a, pow); + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (!q.isZero() && q.andln(1) === 0) { + s++; + q.iushrn(1); + } + assert(!q.isZero()); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + + while (this.pow(z, lpow).cmp(nOne) !== 0) { + z.redIAdd(nOne); + } + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) { + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN(1).iushln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + + return r; + }; + + Red.prototype.invm = function invm (a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + + Red.prototype.pow = function pow (a, num) { + if (num.isZero()) return new BN(1); + if (num.cmpn(1) === 0) return a.clone(); + + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN(1).toRed(this); + wnd[1] = a; + for (var i = 2; i < wnd.length; i++) { + wnd[i] = this.mul(wnd[i - 1], a); + } + + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + + for (i = num.length - 1; i >= 0; i--) { + var word = num.words[i]; + for (var j = start - 1; j >= 0; j--) { + var bit = (word >> j) & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + + return res; + }; + + Red.prototype.convertTo = function convertTo (num) { + var r = num.umod(this.m); + + return r === num ? r.clone() : r; + }; + + Red.prototype.convertFrom = function convertFrom (num) { + var res = num.clone(); + res.red = null; + return res; + }; + + // + // Montgomery method engine + // + + BN.mont = function mont (num) { + return new Mont(num); + }; + + function Mont (m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - (this.shift % 26); + } + + this.r = new BN(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + + Mont.prototype.convertTo = function convertTo (num) { + return this.imod(num.ushln(this.shift)); + }; + + Mont.prototype.convertFrom = function convertFrom (num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + + Mont.prototype.imul = function imul (a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.mul = function mul (a, b) { + if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + + return res._forceRed(this); + }; + + Mont.prototype.invm = function invm (a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; + })(typeof module === 'undefined' || module, this); + + },{}],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 + * @return {String} output + */ + function padToEven(value) { + var a = value; // eslint-disable-line + + if (typeof a !== 'string') { + throw new Error('[ethjs-util] while padding to even, value must be string, is currently ' + typeof a + ', while padToEven.'); + } + + if (a.length % 2) { + a = '0' + a; + } + + return a; + } + + /** + * Converts a `Number` into a hex `String` + * @param {Number} i + * @return {String} + */ + function intToHex(i) { + var hex = i.toString(16); // eslint-disable-line + + return '0x' + hex; + } + + /** + * Converts an `Number` to a `Buffer` + * @param {Number} i + * @return {Buffer} + */ + function intToBuffer(i) { + var hex = intToHex(i); + + return new Buffer(padToEven(hex.slice(2)), 'hex'); + } + + /** + * Get the binary size of a string + * @param {String} str + * @return {Number} + */ + function getBinarySize(str) { + if (typeof str !== 'string') { + throw new Error('[ethjs-util] while getting binary size, method getBinarySize requires input \'str\' to be type String, got \'' + typeof str + '\'.'); + } + + return Buffer.byteLength(str, 'utf8'); + } + + /** + * Returns TRUE if the first specified array contains all elements + * from the second one. FALSE otherwise. + * + * @param {array} superset + * @param {array} subset + * + * @returns {boolean} + */ + function arrayContainsArray(superset, subset, some) { + if (Array.isArray(superset) !== true) { + throw new Error('[ethjs-util] method arrayContainsArray requires input \'superset\' to be an array got type \'' + typeof superset + '\''); + } + if (Array.isArray(subset) !== true) { + throw new Error('[ethjs-util] method arrayContainsArray requires input \'subset\' to be an array got type \'' + typeof subset + '\''); + } + + return subset[Boolean(some) && 'some' || 'every'](function (value) { + return superset.indexOf(value) >= 0; + }); + } + + /** + * Should be called to get utf8 from it's hex representation + * + * @method toUtf8 + * @param {String} string in hex + * @returns {String} ascii string representation of hex value + */ + function toUtf8(hex) { + var bufferValue = new Buffer(padToEven(stripHexPrefix(hex).replace(/^0+|0+$/g, '')), 'hex'); + + return bufferValue.toString('utf8'); + } + + /** + * Should be called to get ascii from it's hex representation + * + * @method toAscii + * @param {String} string in hex + * @returns {String} ascii string representation of hex value + */ + function toAscii(hex) { + var str = ''; // eslint-disable-line + var i = 0, + l = hex.length; // eslint-disable-line + + if (hex.substring(0, 2) === '0x') { + i = 2; + } + + for (; i < l; i += 2) { + var code = parseInt(hex.substr(i, 2), 16); + str += String.fromCharCode(code); + } + + return str; + } + + /** + * Should be called to get hex representation (prefixed by 0x) of utf8 string + * + * @method fromUtf8 + * @param {String} string + * @param {Number} optional padding + * @returns {String} hex representation of input string + */ + function fromUtf8(stringValue) { + var str = new Buffer(stringValue, 'utf8'); + + return '0x' + padToEven(str.toString('hex')).replace(/^0+|0+$/g, ''); + } + + /** + * Should be called to get hex representation (prefixed by 0x) of ascii string + * + * @method fromAscii + * @param {String} string + * @param {Number} optional padding + * @returns {String} hex representation of input string + */ + function fromAscii(stringValue) { + var hex = ''; // eslint-disable-line + for (var i = 0; i < stringValue.length; i++) { + // eslint-disable-line + var code = stringValue.charCodeAt(i); + var n = code.toString(16); + hex += n.length < 2 ? '0' + n : n; + } + + return '0x' + hex; + } + + /** + * getKeys([{a: 1, b: 2}, {a: 3, b: 4}], 'a') => [1, 3] + * + * @method getKeys get specific key from inner object array of objects + * @param {String} params + * @param {String} key + * @param {Boolean} allowEmpty + * @returns {Array} output just a simple array of output keys + */ + function getKeys(params, key, allowEmpty) { + if (!Array.isArray(params)) { + throw new Error('[ethjs-util] method getKeys expecting type Array as \'params\' input, got \'' + typeof params + '\''); + } + if (typeof key !== 'string') { + throw new Error('[ethjs-util] method getKeys expecting type String for input \'key\' got \'' + typeof key + '\'.'); + } + + var result = []; // eslint-disable-line + + for (var i = 0; i < params.length; i++) { + // eslint-disable-line + var value = params[i][key]; // eslint-disable-line + if (allowEmpty && !value) { + value = ''; + } else if (typeof value !== 'string') { + throw new Error('invalid abi'); + } + result.push(value); + } + + return result; + } + + /** + * Is the string a hex string. + * + * @method check if string is hex string of specific length + * @param {String} value + * @param {Number} length + * @returns {Boolean} output the string is a hex string + */ + function isHexString(value, length) { + if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) { + return false; + } + + if (length && value.length !== 2 + 2 * length) { + return false; + } + + return true; + } + + module.exports = { + arrayContainsArray: arrayContainsArray, + intToBuffer: intToBuffer, + getBinarySize: getBinarySize, + isHexPrefixed: isHexPrefixed, + stripHexPrefix: stripHexPrefix, + padToEven: padToEven, + intToHex: intToHex, + fromAscii: fromAscii, + fromUtf8: fromUtf8, + toAscii: toAscii, + toUtf8: toUtf8, + getKeys: getKeys, + isHexString: isHexString + }; + }).call(this,require("buffer").Buffer) + },{"buffer":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 + // `~` to make sure that the built-in object properties are not overridden or + // used as an attack vector. + // We also assume that `Object.create(null)` is available when the event name + // is an ES6 Symbol. + // + var prefix = typeof Object.create !== 'function' ? '~' : false; + + /** + * Representation of a single EventEmitter function. + * + * @param {Function} fn Event handler to be called. + * @param {Mixed} context Context for function execution. + * @param {Boolean} once Only emit once + * @api private + */ + function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; + } + + /** + * Minimal EventEmitter interface that is molded against the Node.js + * EventEmitter interface. + * + * @constructor + * @api public + */ + function EventEmitter() { /* Nothing to set */ } + + /** + * Holds the assigned EventEmitters by name. + * + * @type {Object} + * @private + */ + EventEmitter.prototype._events = undefined; + + /** + * Return a list of assigned event listeners. + * + * @param {String} event The events that should be listed. + * @param {Boolean} exists We only need to know if there are listeners. + * @returns {Array|Boolean} + * @api public + */ + 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. + * + * @param {String} event The name of the event. + * @returns {Boolean} Indication if we've emitted an event. + * @api public + */ + 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; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + 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; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + default: + 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. + * + * @param {String} event Name of the event. + * @param {Functon} fn Callback function. + * @param {Mixed} context The context of the function. + * @api public + */ + 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 { + if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [ + this._events[evt], listener + ]; + } + + return this; + }; + + /** + * Add an EventListener that's only called once. + * + * @param {String} event Name of the event. + * @param {Function} fn Callback function. + * @param {Mixed} context The context of the function. + * @api public + */ + 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 { + if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [ + this._events[evt], listener + ]; + } + + return this; + }; + + /** + * Remove event listeners. + * + * @param {String} event The event we want to remove. + * @param {Function} fn The listener that we need to find. + * @param {Mixed} context Only remove listeners matching this context. + * @param {Boolean} once Only remove once listeners. + * @api public + */ + 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 ( + listeners.fn !== fn + || (once && !listeners.once) + || (context && listeners.context !== context) + ) { + events.push(listeners); + } + } else { + for (var i = 0, length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn + || (once && !listeners[i].once) + || (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) { + this._events[evt] = events.length === 1 ? events[0] : events; + } else { + delete this._events[evt]; + } + + return this; + }; + + /** + * Remove all listeners or only the listeners for the specified event. + * + * @param {String} event The event want to remove all listeners for. + * @api public + */ + 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. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 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) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + 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 || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + } + } + + handler = this._events[type]; + + if (isUndefined(handler)) + return false; + + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); + } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + 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; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + 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)) { + m = this._maxListeners; + } 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 ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } + + 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 || + (list[i].listener && list[i].listener === listener)) { + position = i; + 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) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } + + listeners = this._events[type]; + + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + 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]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + 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) + return evlistener.length; + } + 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') + if (salt) { + 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) + tmp.copy(iv, ivStart, used, used + length) + 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)) { + if (receiver == null) { + iterator(array[i], i, array); + } else { + iterator.call(receiver, array[i], i, array); + } + } + } + }; + + var forEachString = function forEachString(string, iterator, receiver) { + for (var i = 0, len = string.length; i < len; i++) { + // no such thing as a sparse string. + if (receiver == null) { + iterator(string.charAt(i), i, string); + } else { + iterator.call(receiver, string.charAt(i), i, string); + } + } + }; + + var forEachObject = function forEachObject(object, iterator, receiver) { + for (var k in object) { + if (hasOwnProperty.call(object, k)) { + if (receiver == null) { + iterator(object[k], k, object); + } else { + iterator.call(receiver, object[k], k, object); + } + } + } + }; + + var forEach = function forEach(list, iterator, thisArg) { + if (!isCallable(iterator)) { + throw new TypeError('iterator must be a function'); + } + + var receiver; + if (arguments.length >= 3) { + receiver = thisArg; + } + + if (toStr.call(list) === '[object Array]') { + forEachArray(list, iterator, receiver); + } else if (typeof list === 'string') { + forEachString(list, iterator, receiver); + } else { + forEachObject(list, iterator, receiver); + } + }; + + module.exports = forEach; + + },{"is-callable":182}],160:[function(require,module,exports){ + (function (global){ + var win; + + if (typeof window !== "undefined") { + win = window; + } else if (typeof global !== "undefined") { + win = global; + } else if (typeof self !== "undefined"){ + win = self; + } else { + win = {}; + } + + module.exports = win; + + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + },{}],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 { + if (encoding !== 'buffer') chunk = new Buffer(chunk, encoding) + this.update(chunk) + } catch (err) { + error = err + } + + callback(error) + } + + HashBase.prototype._flush = function (callback) { + var error = null + try { + this.push(this._digest()) + } catch (err) { + error = err + } + + callback(error) + } + + HashBase.prototype.update = function (data, encoding) { + 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 + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] + this._update() + this._blockOffset = 0 + } + while (offset < data.length) block[this._blockOffset++] = data[offset++] + + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry + carry = (this._length[j] / 0x0100000000) | 0 + if (carry > 0) this._length[j] -= 0x0100000000 * carry + } + + return this + } + + HashBase.prototype._update = function (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; + hash.sha224 = hash.sha.sha224; + 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; + this.blockSize = this.constructor.blockSize; + this.outSize = this.constructor.outSize; + this.hmacStrength = this.constructor.hmacStrength; + this.padLength = this.constructor.padLength / 8; + this.endian = 'big'; + + this._delta8 = this.blockSize / 8; + this._delta32 = this.blockSize / 32; + } + exports.BlockHash = BlockHash; + + BlockHash.prototype.update = function update(msg, enc) { + // Convert message to array, pad it, and join into 32bit blocks + msg = utils.toArray(msg, enc); + if (!this.pending) + this.pending = msg; + else + this.pending = this.pending.concat(msg); + this.pendingTotal += msg.length; + + // Enough data, try updating + if (this.pending.length >= this._delta8) { + msg = this.pending; + + // Process pending data in blocks + var r = msg.length % this._delta8; + this.pending = msg.slice(msg.length - r, msg.length); + if (this.pending.length === 0) + this.pending = null; + + msg = utils.join32(msg, 0, msg.length - r, this.endian); + for (var i = 0; i < msg.length; i += this._delta32) + this._update(msg, i, i + this._delta32); + } + + return this; + }; + + BlockHash.prototype.digest = function digest(enc) { + this.update(this._pad()); + assert(this.pending === null); + + return this._digest(enc); + }; + + BlockHash.prototype._pad = function pad() { + var len = this.pendingTotal; + var bytes = this._delta8; + var k = bytes - ((len + this.padLength) % bytes); + var res = new Array(k + this.padLength); + res[0] = 0x80; + for (var i = 1; i < k; i++) + res[i] = 0; + + // Append length + len <<= 3; + if (this.endian === 'big') { + for (var t = 8; t < this.padLength; t++) + res[i++] = 0; + + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = (len >>> 24) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = len & 0xff; + } else { + res[i++] = len & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 24) & 0xff; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + + for (t = 8; t < this.padLength; t++) + res[i++] = 0; + } + + return res; + }; + + },{"./utils":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); + this.Hash = hash; + this.blockSize = hash.blockSize / 8; + this.outSize = hash.outSize / 8; + this.inner = null; + this.outer = null; + + this._init(utils.toArray(key, enc)); + } + module.exports = Hmac; + + Hmac.prototype._init = function init(key) { + // Shorten key, if needed + if (key.length > this.blockSize) + key = new this.Hash().update(key).digest(); + assert(key.length <= this.blockSize); + + // Add padding to key + for (var i = key.length; i < this.blockSize; i++) + key.push(0); + + for (i = 0; i < key.length; i++) + key[i] ^= 0x36; + this.inner = new this.Hash().update(key); + + // 0x36 ^ 0x5c = 0x6a + for (i = 0; i < key.length; i++) + key[i] ^= 0x6a; + this.outer = new this.Hash().update(key); + }; + + Hmac.prototype.update = function update(msg, enc) { + this.inner.update(msg, enc); + return this; + }; + + Hmac.prototype.digest = function digest(enc) { + this.outer.update(this.inner.digest()); + return this.outer.digest(enc); + }; + + },{"./utils":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]; + var C = this.h[2]; + var D = this.h[3]; + var E = this.h[4]; + var Ah = A; + var Bh = B; + var Ch = C; + var Dh = D; + var Eh = E; + for (var j = 0; j < 80; j++) { + var T = sum32( + rotl32( + sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), + s[j]), + E); + A = E; + E = D; + D = rotl32(C, 10); + C = B; + B = T; + T = sum32( + rotl32( + sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), + sh[j]), + Eh); + Ah = Eh; + Eh = Dh; + Dh = rotl32(Ch, 10); + Ch = Bh; + Bh = T; + } + T = sum32_3(this.h[1], C, Dh); + this.h[1] = sum32_3(this.h[2], D, Eh); + this.h[2] = sum32_3(this.h[3], E, Ah); + this.h[3] = sum32_3(this.h[4], A, Bh); + this.h[4] = sum32_3(this.h[0], B, Ch); + this.h[0] = T; + }; + + RIPEMD160.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'little'); + else + return utils.split32(this.h, 'little'); + }; + + function f(j, x, y, z) { + if (j <= 15) + return x ^ y ^ z; + else if (j <= 31) + return (x & y) | ((~x) & z); + else if (j <= 47) + return (x | (~y)) ^ z; + else if (j <= 63) + return (x & z) | (y & (~z)); + else + return x ^ (y | (~z)); + } + + function K(j) { + if (j <= 15) + return 0x00000000; + else if (j <= 31) + return 0x5a827999; + else if (j <= 47) + return 0x6ed9eba1; + else if (j <= 63) + return 0x8f1bbcdc; + else + return 0xa953fd4e; + } + + function Kh(j) { + if (j <= 15) + return 0x50a28be6; + else if (j <= 31) + return 0x5c4dd124; + else if (j <= 47) + return 0x6d703ef3; + else if (j <= 63) + return 0x7a6d76e9; + else + return 0x00000000; + } + + var r = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 + ]; + + var rh = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 + ]; + + var s = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 + ]; + + var sh = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 + ]; + + },{"./common":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]); + e = d; + d = c; + c = rotl32(b, 30); + b = a; + a = t; + } + + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); + }; + + SHA1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); + }; + + },{"../common":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, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; + } + utils.inherits(SHA224, SHA256); + module.exports = SHA224; + + SHA224.blockSize = 512; + SHA224.outSize = 224; + SHA224.hmacStrength = 192; + SHA224.padLength = 64; + + SHA224.prototype._digest = function digest(enc) { + // Just truncate output + if (enc === 'hex') + return utils.toHex32(this.h.slice(0, 7), 'big'); + else + return utils.split32(this.h.slice(0, 7), 'big'); + }; + + + },{"../utils":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; + var ch32 = shaCommon.ch32; + var maj32 = shaCommon.maj32; + var s0_256 = shaCommon.s0_256; + var s1_256 = shaCommon.s1_256; + var g0_256 = shaCommon.g0_256; + var g1_256 = shaCommon.g1_256; + + var BlockHash = common.BlockHash; + + var sha256_K = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, + 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, + 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, + 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, + 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, + 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 + ]; + + function SHA256() { + if (!(this instanceof SHA256)) + return new SHA256(); + + BlockHash.call(this); + this.h = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + ]; + this.k = sha256_K; + this.W = new Array(64); + } + utils.inherits(SHA256, BlockHash); + module.exports = SHA256; + + SHA256.blockSize = 512; + SHA256.outSize = 256; + SHA256.hmacStrength = 192; + SHA256.padLength = 64; + + SHA256.prototype._update = function _update(msg, start) { + var W = this.W; + + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + for (; i < W.length; i++) + W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); + + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + var f = this.h[5]; + var g = this.h[6]; + var h = this.h[7]; + + assert(this.k.length === W.length); + for (i = 0; i < W.length; i++) { + var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]); + var T2 = sum32(s0_256(a), maj32(a, b, c)); + h = g; + g = f; + f = e; + e = sum32(d, T1); + d = c; + c = b; + b = a; + a = sum32(T1, T2); + } + + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); + this.h[5] = sum32(this.h[5], f); + this.h[6] = sum32(this.h[6], g); + this.h[7] = sum32(this.h[7], h); + }; + + SHA256.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); + }; + + },{"../common":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, + 0x629a292a, 0x367cd507, + 0x9159015a, 0x3070dd17, + 0x152fecd8, 0xf70e5939, + 0x67332667, 0xffc00b31, + 0x8eb44a87, 0x68581511, + 0xdb0c2e0d, 0x64f98fa7, + 0x47b5481d, 0xbefa4fa4 ]; + } + utils.inherits(SHA384, SHA512); + module.exports = SHA384; + + SHA384.blockSize = 1024; + SHA384.outSize = 384; + SHA384.hmacStrength = 192; + SHA384.padLength = 128; + + SHA384.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h.slice(0, 12), 'big'); + else + return utils.split32(this.h.slice(0, 12), 'big'); + }; + + },{"../utils":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; + var shr64_lo = utils.shr64_lo; + var sum64 = utils.sum64; + var sum64_hi = utils.sum64_hi; + var sum64_lo = utils.sum64_lo; + var sum64_4_hi = utils.sum64_4_hi; + var sum64_4_lo = utils.sum64_4_lo; + var sum64_5_hi = utils.sum64_5_hi; + var sum64_5_lo = utils.sum64_5_lo; + + var BlockHash = common.BlockHash; + + var sha512_K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 + ]; + + function SHA512() { + if (!(this instanceof SHA512)) + return new SHA512(); + + BlockHash.call(this); + this.h = [ + 0x6a09e667, 0xf3bcc908, + 0xbb67ae85, 0x84caa73b, + 0x3c6ef372, 0xfe94f82b, + 0xa54ff53a, 0x5f1d36f1, + 0x510e527f, 0xade682d1, + 0x9b05688c, 0x2b3e6c1f, + 0x1f83d9ab, 0xfb41bd6b, + 0x5be0cd19, 0x137e2179 ]; + this.k = sha512_K; + this.W = new Array(160); + } + utils.inherits(SHA512, BlockHash); + module.exports = SHA512; + + SHA512.blockSize = 1024; + SHA512.outSize = 512; + SHA512.hmacStrength = 192; + SHA512.padLength = 128; + + SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { + var W = this.W; + + // 32 x 32bit words + for (var i = 0; i < 32; i++) + W[i] = msg[start + i]; + for (; i < W.length; i += 2) { + var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2 + var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); + var c1_hi = W[i - 14]; // i - 7 + var c1_lo = W[i - 13]; + var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 + var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); + var c3_hi = W[i - 32]; // i - 16 + var c3_lo = W[i - 31]; + + W[i] = sum64_4_hi( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo); + W[i + 1] = sum64_4_lo( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo); + } + }; + + SHA512.prototype._update = function _update(msg, start) { + this._prepareBlock(msg, start); + + var W = this.W; + + var ah = this.h[0]; + var al = this.h[1]; + var bh = this.h[2]; + var bl = this.h[3]; + var ch = this.h[4]; + var cl = this.h[5]; + var dh = this.h[6]; + var dl = this.h[7]; + var eh = this.h[8]; + var el = this.h[9]; + var fh = this.h[10]; + var fl = this.h[11]; + var gh = this.h[12]; + var gl = this.h[13]; + var hh = this.h[14]; + var hl = this.h[15]; + + assert(this.k.length === W.length); + for (var i = 0; i < W.length; i += 2) { + var c0_hi = hh; + var c0_lo = hl; + var c1_hi = s1_512_hi(eh, el); + var c1_lo = s1_512_lo(eh, el); + var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl); + var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); + var c3_hi = this.k[i]; + var c3_lo = this.k[i + 1]; + var c4_hi = W[i]; + var c4_lo = W[i + 1]; + + var T1_hi = sum64_5_hi( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo, + c4_hi, c4_lo); + var T1_lo = sum64_5_lo( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo, + c4_hi, c4_lo); + + c0_hi = s0_512_hi(ah, al); + c0_lo = s0_512_lo(ah, al); + c1_hi = maj64_hi(ah, al, bh, bl, ch, cl); + c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); + + var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo); + var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo); + + hh = gh; + hl = gl; + + gh = fh; + gl = fl; + + fh = eh; + fl = el; + + eh = sum64_hi(dh, dl, T1_hi, T1_lo); + el = sum64_lo(dl, dl, T1_hi, T1_lo); + + dh = ch; + dl = cl; + + ch = bh; + cl = bl; + + bh = ah; + bl = al; + + ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); + al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); + } + + sum64(this.h, 0, ah, al); + sum64(this.h, 2, bh, bl); + sum64(this.h, 4, ch, cl); + sum64(this.h, 6, dh, dl); + sum64(this.h, 8, eh, el); + sum64(this.h, 10, fh, fl); + sum64(this.h, 12, gh, gl); + sum64(this.h, 14, hh, hl); + }; + + SHA512.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); + }; + + function ch64_hi(xh, xl, yh, yl, zh) { + var r = (xh & yh) ^ ((~xh) & zh); + if (r < 0) + r += 0x100000000; + return r; + } + + function ch64_lo(xh, xl, yh, yl, zh, zl) { + var r = (xl & yl) ^ ((~xl) & zl); + if (r < 0) + r += 0x100000000; + return r; + } + + function maj64_hi(xh, xl, yh, yl, zh) { + var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); + if (r < 0) + r += 0x100000000; + return r; + } + + function maj64_lo(xh, xl, yh, yl, zh, zl) { + var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); + if (r < 0) + r += 0x100000000; + return r; + } + + function s0_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 28); + var c1_hi = rotr64_hi(xl, xh, 2); // 34 + var c2_hi = rotr64_hi(xl, xh, 7); // 39 + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; + } + + function s0_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 28); + var c1_lo = rotr64_lo(xl, xh, 2); // 34 + var c2_lo = rotr64_lo(xl, xh, 7); // 39 + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; + } + + function s1_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 14); + var c1_hi = rotr64_hi(xh, xl, 18); + var c2_hi = rotr64_hi(xl, xh, 9); // 41 + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; + } + + function s1_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 14); + var c1_lo = rotr64_lo(xh, xl, 18); + var c2_lo = rotr64_lo(xl, xh, 9); // 41 + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; + } + + function g0_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 1); + var c1_hi = rotr64_hi(xh, xl, 8); + var c2_hi = shr64_hi(xh, xl, 7); + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; + } + + function g0_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 1); + var c1_lo = rotr64_lo(xh, xl, 8); + var c2_lo = shr64_lo(xh, xl, 7); + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; + } + + function g1_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 19); + var c1_hi = rotr64_hi(xl, xh, 29); // 61 + var c2_hi = shr64_hi(xh, xl, 6); + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; + } + + function g1_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 19); + var c1_lo = rotr64_lo(xl, xh, 29); // 61 + var c2_lo = shr64_lo(xh, xl, 6); + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; + } + + },{"../common":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); + if (s === 1 || s === 3) + return p32(x, y, z); + if (s === 2) + return maj32(x, y, z); + } + exports.ft_1 = ft_1; + + function ch32(x, y, z) { + return (x & y) ^ ((~x) & z); + } + exports.ch32 = ch32; + + function maj32(x, y, z) { + return (x & y) ^ (x & z) ^ (y & z); + } + exports.maj32 = maj32; + + function p32(x, y, z) { + return x ^ y ^ z; + } + exports.p32 = p32; + + function s0_256(x) { + return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); + } + exports.s0_256 = s0_256; + + function s1_256(x) { + return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); + } + exports.s1_256 = s1_256; + + function g0_256(x) { + return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); + } + exports.g0_256 = g0_256; + + function g1_256(x) { + return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); + } + exports.g1_256 = g1_256; + + },{"../utils":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(); + if (!msg) + return []; + var res = []; + if (typeof msg === 'string') { + if (!enc) { + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + var hi = c >> 8; + var lo = c & 0xff; + if (hi) + res.push(hi, lo); + else + res.push(lo); + } + } else if (enc === 'hex') { + msg = msg.replace(/[^a-z0-9]+/ig, ''); + if (msg.length % 2 !== 0) + msg = '0' + msg; + for (i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } + } else { + for (i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + } + return res; + } + exports.toArray = toArray; + + function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; + } + exports.toHex = toHex; + + function htonl(w) { + var res = (w >>> 24) | + ((w >>> 8) & 0xff00) | + ((w << 8) & 0xff0000) | + ((w & 0xff) << 24); + return res >>> 0; + } + exports.htonl = htonl; + + function toHex32(msg, endian) { + var res = ''; + for (var i = 0; i < msg.length; i++) { + var w = msg[i]; + if (endian === 'little') + w = htonl(w); + res += zero8(w.toString(16)); + } + return res; + } + exports.toHex32 = toHex32; + + function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; + } + exports.zero2 = zero2; + + function zero8(word) { + if (word.length === 7) + return '0' + word; + else if (word.length === 6) + return '00' + word; + else if (word.length === 5) + return '000' + word; + else if (word.length === 4) + return '0000' + word; + else if (word.length === 3) + return '00000' + word; + else if (word.length === 2) + return '000000' + word; + else if (word.length === 1) + return '0000000' + word; + else + return word; + } + exports.zero8 = zero8; + + function join32(msg, start, end, endian) { + var len = end - start; + assert(len % 4 === 0); + var res = new Array(len / 4); + for (var i = 0, k = start; i < res.length; i++, k += 4) { + var w; + if (endian === 'big') + w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; + else + w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; + res[i] = w >>> 0; + } + return res; + } + exports.join32 = join32; + + function split32(msg, endian) { + var res = new Array(msg.length * 4); + for (var i = 0, k = 0; i < msg.length; i++, k += 4) { + var m = msg[i]; + if (endian === 'big') { + res[k] = m >>> 24; + res[k + 1] = (m >>> 16) & 0xff; + res[k + 2] = (m >>> 8) & 0xff; + res[k + 3] = m & 0xff; + } else { + res[k + 3] = m >>> 24; + res[k + 2] = (m >>> 16) & 0xff; + res[k + 1] = (m >>> 8) & 0xff; + res[k] = m & 0xff; + } + } + return res; + } + exports.split32 = split32; + + function rotr32(w, b) { + return (w >>> b) | (w << (32 - b)); + } + exports.rotr32 = rotr32; + + function rotl32(w, b) { + return (w << b) | (w >>> (32 - b)); + } + exports.rotl32 = rotl32; + + function sum32(a, b) { + return (a + b) >>> 0; + } + exports.sum32 = sum32; + + function sum32_3(a, b, c) { + return (a + b + c) >>> 0; + } + exports.sum32_3 = sum32_3; + + function sum32_4(a, b, c, d) { + return (a + b + c + d) >>> 0; + } + exports.sum32_4 = sum32_4; + + function sum32_5(a, b, c, d, e) { + return (a + b + c + d + e) >>> 0; + } + exports.sum32_5 = sum32_5; + + function sum64(buf, pos, ah, al) { + var bh = buf[pos]; + var bl = buf[pos + 1]; + + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + buf[pos] = hi >>> 0; + buf[pos + 1] = lo; + } + exports.sum64 = sum64; + + function sum64_hi(ah, al, bh, bl) { + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + return hi >>> 0; + } + exports.sum64_hi = sum64_hi; + + function sum64_lo(ah, al, bh, bl) { + var lo = al + bl; + return lo >>> 0; + } + exports.sum64_lo = sum64_lo; + + function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { + var carry = 0; + var lo = al; + lo = (lo + bl) >>> 0; + carry += lo < al ? 1 : 0; + lo = (lo + cl) >>> 0; + carry += lo < cl ? 1 : 0; + lo = (lo + dl) >>> 0; + carry += lo < dl ? 1 : 0; + + var hi = ah + bh + ch + dh + carry; + return hi >>> 0; + } + exports.sum64_4_hi = sum64_4_hi; + + function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { + var lo = al + bl + cl + dl; + return lo >>> 0; + } + exports.sum64_4_lo = sum64_4_lo; + + function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var carry = 0; + var lo = al; + lo = (lo + bl) >>> 0; + carry += lo < al ? 1 : 0; + lo = (lo + cl) >>> 0; + carry += lo < cl ? 1 : 0; + lo = (lo + dl) >>> 0; + carry += lo < dl ? 1 : 0; + lo = (lo + el) >>> 0; + carry += lo < el ? 1 : 0; + + var hi = ah + bh + ch + dh + eh + carry; + return hi >>> 0; + } + exports.sum64_5_hi = sum64_5_hi; + + function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var lo = al + bl + cl + dl + el; + + return lo >>> 0; + } + exports.sum64_5_lo = sum64_5_lo; + + function rotr64_hi(ah, al, num) { + var r = (al << (32 - num)) | (ah >>> num); + return r >>> 0; + } + exports.rotr64_hi = rotr64_hi; + + function rotr64_lo(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; + } + exports.rotr64_lo = rotr64_lo; + + function shr64_hi(ah, al, num) { + return ah >>> num; + } + exports.shr64_hi = shr64_hi; + + function shr64_lo(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; + } + exports.shr64_lo = shr64_lo; + + },{"inherits":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'); + assert(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + this._init(entropy, nonce, pers); + } + module.exports = HmacDRBG; + + HmacDRBG.prototype._init = function init(entropy, nonce, pers) { + var seed = entropy.concat(nonce).concat(pers); + + this.K = new Array(this.outLen / 8); + this.V = new Array(this.outLen / 8); + for (var i = 0; i < this.V.length; i++) { + this.K[i] = 0x00; + this.V[i] = 0x01; + } + + this._update(seed); + this._reseed = 1; + this.reseedInterval = 0x1000000000000; // 2^48 + }; + + HmacDRBG.prototype._hmac = function hmac() { + return new hash.hmac(this.hash, this.K); + }; + + HmacDRBG.prototype._update = function update(seed) { + var kmac = this._hmac() + .update(this.V) + .update([ 0x00 ]); + if (seed) + kmac = kmac.update(seed); + this.K = kmac.digest(); + this.V = this._hmac().update(this.V).digest(); + if (!seed) + return; + + this.K = this._hmac() + .update(this.V) + .update([ 0x01 ]) + .update(seed) + .digest(); + this.V = this._hmac().update(this.V).digest(); + }; + + HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { + // Optional entropy enc + if (typeof entropyEnc !== 'string') { + addEnc = add; + add = entropyEnc; + entropyEnc = null; + } + + entropy = utils.toArray(entropy, entropyEnc); + add = utils.toArray(add, addEnc); + + assert(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + + this._update(entropy.concat(add || [])); + this._reseed = 1; + }; + + HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { + if (this._reseed > this.reseedInterval) + throw new Error('Reseed is required'); + + // Optional encoding + if (typeof enc !== 'string') { + addEnc = add; + add = enc; + enc = null; + } + + // Optional additional data + if (add) { + add = utils.toArray(add, addEnc || 'hex'); + this._update(add); + } + + var temp = []; + while (temp.length < len) { + this.V = this._hmac().update(this.V).digest(); + temp = temp.concat(this.V); + } + + var res = temp.slice(0, len); + this._update(add); + this._reseed++; + return utils.encode(res, enc); + }; + + },{"hash.js":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) + } + if (!params.protocol) { + params.protocol = 'https:' + } + if (params.protocol !== 'https:') { + throw new Error('Protocol "' + params.protocol + '" not supported. Expected "https:"') + } + 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) { + define([], function () { return factory(); }); + } else if (typeof exports === 'object') { + module.exports = factory(); + } else { + root.uts46_map = factory(); + } + }(this, function () { + var blocks = [ + new Uint32Array([2157250,2157314,2157378,2157442,2157506,2157570,2157634,0,2157698,2157762,2157826,2157890,2157954,0,2158018,0]), + new Uint32Array([2179041,6291456,2179073,6291456,2179105,6291456,2179137,6291456,2179169,6291456,2179201,6291456,2179233,6291456,2179265,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,14680064,14680064,14680064,14680064,14680064]), + new Uint32Array([0,2113729,2197345,2197377,2113825,2197409,2197441,2113921,2197473,2114017,2197505,2197537,2197569,2197601,2197633,2197665]), + new Uint32Array([6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,23068672,23068672,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,0,23068672,23068672,23068672,0,0,0,0,23068672]), + new Uint32Array([14680064,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,14680064,14680064]), + new Uint32Array([2196001,2196033,2196065,2196097,2196129,2196161,2196193,2196225,2196257,2196289,2196321,2196353,2196385,2196417,2196449,2196481]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,6291456,0,0,0,0,0]), + new Uint32Array([2097281,2105921,2097729,2106081,0,2097601,2162337,2106017,2133281,2097505,2105889,2097185,2097697,2135777,2097633,2097441]), + new Uint32Array([2177025,6291456,2177057,6291456,2177089,6291456,2177121,6291456,2177153,6291456,2177185,6291456,2177217,6291456,2177249,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,0,6291456,6291456,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456]), + new Uint32Array([0,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,6291456]), + new Uint32Array([2134435,2134531,2134627,2134723,2134723,2134819,2134819,2134915,2134915,2135011,2105987,2135107,2135203,2135299,2131587,2135395]), + new Uint32Array([0,0,0,0,0,0,0,6291456,2168673,2169249,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2147906,2147970,2148034,2148098,2148162,2148226,2148290,2148354,2147906,2147970,2148034,2148098,2148162,2148226,2148290,2148354]), + new Uint32Array([2125219,2125315,2152834,2152898,2125411,2152962,2153026,2125506,2125507,2125603,2153090,2153154,2153218,2153282,2153346,2105348]), + new Uint32Array([2203393,6291456,2203425,6291456,2203457,6291456,2203489,6291456,6291456,6291456,6291456,2203521,6291456,2181281,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,23068672,6291456,2145538,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,6291456]), + new Uint32Array([2139426,2160834,2160898,2160962,2134242,2161026,2161090,2161154,2161218,2161282,2161346,2161410,2138658,2161474,2161538,2134722]), + new Uint32Array([2119939,2124930,2125026,2106658,2125218,2128962,2129058,2129154,2129250,2129346,2129442,2108866,2108770,2150466,2150530,2150594]), + new Uint32Array([2201601,6291456,2201633,6291456,2201665,6291456,2201697,6291456,2201729,6291456,2201761,6291456,2201793,6291456,2201825,6291456]), + new Uint32Array([2193537,2193569,2193601,2193633,2193665,2193697,2193729,2193761,2193793,2193825,2193857,2193889,2193921,2193953,2193985,2194017]), + new Uint32Array([6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([0,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2190561,6291456,2190593,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2190625,6291456,2190657,6291456,23068672]), + new Uint32Array([2215905,2215937,2215969,2216001,2216033,2216065,2216097,2216129,2216161,2216193,2216225,2216257,2105441,2216289,2216321,2216353]), + new Uint32Array([23068672,18884130,23068672,23068672,23068672,6291456,23068672,23068672,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672]), + new Uint32Array([23068672,23068672,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,6291456,23068672,23068672,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2191233,2191265,2191297,2191329,2191361,2191393,2191425,2117377,2191457,2191489,2191521,2191553,2191585,2191617,2191649,2117953]), + new Uint32Array([2132227,2132323,2132419,2132419,2132515,2132515,2132611,2132707,2132707,2132803,2132899,2132899,2132995,2132995,2133091,2133187]), + new Uint32Array([0,0,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,6291456,0,0]), + new Uint32Array([2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,10609889,10610785,10609921,10610817,2222241]), + new Uint32Array([6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,0,0]), + new Uint32Array([2219969,2157121,2157441,2157505,2157889,2157953,2220001,2158465,2158529,10575617,2156994,2157058,2129923,2130019,2157122,2157186]), + new Uint32Array([6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0]), + new Uint32Array([2185249,6291456,2185281,6291456,2185313,6291456,2185345,6291456,2185377,6291456,2185409,6291456,2185441,6291456,2185473,6291456]), + new Uint32Array([0,0,0,0,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,0,23068672,23068672,0,0,23068672,23068672,23068672,6291456,0]), + new Uint32Array([2183361,6291456,2183393,6291456,2183425,6291456,2183457,6291456,2183489,6291456,2183521,6291456,2183553,6291456,2183585,6291456]), + new Uint32Array([2192161,2192193,2192225,2192257,2192289,2192321,2192353,2192385,2192417,2192449,2192481,2192513,2192545,2192577,2192609,2192641]), + new Uint32Array([2212001,2212033,2212065,2212097,2212129,2212161,2212193,2212225,2212257,2212289,2212321,2212353,2212385,2212417,2212449,2207265]), + new Uint32Array([2249825,2249857,2249889,2249921,2249954,2250018,2250082,2250145,2250177,2250209,2250241,2250274,2250337,2250370,2250433,2250465]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2147905,2147969,2148033,2148097,2148161,2148225,2148289,2148353]), + new Uint32Array([10485857,6291456,2197217,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,23068672,23068672]), + new Uint32Array([0,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456]), + new Uint32Array([2180353,2180385,2144033,2180417,2180449,2180481,2180513,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,10610209,10610465,10610241,10610753,10609857]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,0,0]), + new Uint32Array([2223842,2223906,2223970,2224034,2224098,2224162,2224226,2224290,2224354,2224418,2224482,2224546,2224610,2224674,2224738,2224802]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,6291456,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456]), + new Uint32Array([23068672,23068672,23068672,18923650,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,18923714,23068672,23068672]), + new Uint32Array([2126179,2125538,2126275,2126371,2126467,2125634,2126563,2105603,2105604,2125346,2126659,2126755,2126851,2098179,2098181,2098182]), + new Uint32Array([2227426,2227490,2227554,2227618,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2192353,2240642,2240642,2240705,2240737,2240737,2240769,2240802,2240866,2240929,2240961,2240993,2241025,2241057,2241089,2241121]), + new Uint32Array([6291456,2170881,2170913,2170945,6291456,2170977,6291456,2171009,2171041,6291456,6291456,6291456,2171073,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2132226,2132514,2163586,2132610,2160386,2133090,2133186,2160450,2160514,2160578,2133570,2106178,2160642,2133858,2160706,2160770]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,10532162,10532226,10532290,10532354,10532418,10532482,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,23068672]), + new Uint32Array([2098209,2108353,2108193,2108481,2170241,2111713,2105473,2105569,2105601,2112289,2112481,2098305,2108321,0,0,0]), + new Uint32Array([2209121,2209153,2209185,2209217,2209249,2209281,2209313,2209345,2209377,2209409,2209441,2209473,2207265,2209505,2209537,2209569]), + new Uint32Array([2189025,6291456,2189057,6291456,2189089,6291456,2189121,6291456,2189153,6291456,2189185,6291456,2189217,6291456,2189249,6291456]), + new Uint32Array([2173825,2153473,2173857,2173889,2173921,2173953,2173985,2173761,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233057]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2165764,2140004]), + new Uint32Array([2215105,6291456,2215137,6291456,6291456,2215169,2215201,6291456,6291456,6291456,2215233,2215265,2215297,2215329,2215361,2215393]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,6291456,6291456,6291456,23068672,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([10505091,10505187,10505283,10505379,10505475,10505571,10505667,10505763,10505859,10505955,10506051,10506147,10506243,10506339,10506435,10506531]), + new Uint32Array([2229730,2229794,2229858,2229922,2229986,2230050,2230114,2230178,2230242,2230306,2230370,2230434,2230498,2230562,2230626,2230690]), + new Uint32Array([2105505,2098241,2108353,2108417,2105825,0,2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177]), + new Uint32Array([6291456,6291456,6291456,6291456,10502115,10502178,10502211,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([0,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456]), + new Uint32Array([2190305,6291456,2190337,6291456,2190369,6291456,2190401,6291456,2190433,6291456,2190465,6291456,2190497,6291456,2190529,6291456]), + new Uint32Array([2173793,2173985,2174017,6291456,2173761,2173697,6291456,2174689,6291456,2174017,2174721,6291456,6291456,2174753,2174785,2174817]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2099521,2099105,2120705,2098369,2120801,2103361,2097985,2098433,2121377,2121473,2099169,2099873,2098401,2099393,2152609,2100033]), + new Uint32Array([2132898,2163842,2163906,2133282,2132034,2131938,2137410,2132802,2132706,2164866,2133282,2160578,2165186,2165186,6291456,6291456]), + new Uint32Array([10500003,10500099,10500195,10500291,10500387,10500483,10500579,10500675,10500771,10500867,10500963,10501059,10501155,10501251,10501347,10501443]), + new Uint32Array([2163458,2130978,2131074,2131266,2131362,2163522,2160130,2132066,2131010,2131106,2106018,2131618,2131298,2132034,2131938,2137410]), + new Uint32Array([2212961,2116993,2212993,2213025,2213057,2213089,2213121,2213153,2213185,2213217,2213249,2209633,2213281,2213313,2213345,2213377]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456]), + new Uint32Array([2113729,2113825,2113921,2114017,2114113,2114209,2114305,2114401,2114497,2114593,2114689,2114785,2114881,2114977,2115073,2115169]), + new Uint32Array([2238177,2238209,2238241,2238273,2238305,2238337,2238337,2217537,2238369,2238401,2238433,2238465,2215649,2238497,2238529,2238561]), + new Uint32Array([2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905]), + new Uint32Array([6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,0,0]), + new Uint32Array([6291456,0,6291456,2145026,0,6291456,2145090,0,6291456,6291456,0,0,23068672,0,23068672,23068672]), + new Uint32Array([2099233,2122017,2200673,2098113,2121537,2103201,2200705,2104033,2121857,2121953,2122401,2099649,2099969,2123009,2100129,2100289]), + new Uint32Array([6291456,23068672,6291456,0,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,23068672,23068672,0,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0]), + new Uint32Array([2187681,2187713,2187745,2187777,2187809,2187841,2187873,2187905,2187937,2187969,2188001,2188033,2188065,2188097,2188129,2188161]), + new Uint32Array([0,10554498,10554562,10554626,10554690,10554754,10554818,10554882,10554946,10555010,10555074,6291456,6291456,0,0,0]), + new Uint32Array([2235170,2235234,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0]), + new Uint32Array([2181153,6291456,2188897,6291456,6291456,2188929,6291456,6291456,6291456,6291456,6291456,6291456,2111905,2100865,2188961,2188993]), + new Uint32Array([2100833,2100897,0,0,2101569,2101697,2101825,2101953,2102081,2102209,10575617,2187041,10502177,10489601,10489697,2112289]), + new Uint32Array([6291456,2172833,6291456,2172865,2172897,2172929,2172961,6291456,2172993,6291456,2173025,6291456,2173057,6291456,2173089,6291456]), + new Uint32Array([6291456,0,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,0,0,23068672,6291456,23068672,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,2190721]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,23068672,6291456,6291456]), + new Uint32Array([2184993,6291456,2185025,6291456,2185057,6291456,2185089,6291456,2185121,6291456,2185153,6291456,2185185,6291456,2185217,6291456]), + new Uint32Array([2115265,2115361,2115457,2115553,2115649,2115745,2115841,2115937,2116033,2116129,2116225,2116321,2150658,2150722,2200225,6291456]), + new Uint32Array([2168321,6291456,2168353,6291456,2168385,6291456,2168417,6291456,2168449,6291456,2168481,6291456,2168513,6291456,2168545,6291456]), + new Uint32Array([23068672,23068672,23068672,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,0,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456,0,6291456,0,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,2186625,0,0,6291456,6291456,2186657,2186689,2186721,2173505,0,10496067,10496163,10496259]), + new Uint32Array([2178785,6291456,2178817,6291456,2178849,6291456,2178881,6291456,2178913,6291456,2178945,6291456,2178977,6291456,2179009,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0]), + new Uint32Array([2097152,0,0,0,2097152,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456]), + new Uint32Array([6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([0,0,2197857,2197889,2197921,2197953,2197985,2198017,0,0,2198049,2198081,2198113,2198145,2198177,2198209]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2098209,2167297,2111137,6291456]), + new Uint32Array([2171393,6291456,2171425,6291456,2171457,6291456,2171489,6291456,2171521,6291456,2171553,6291456,2171585,6291456,2171617,6291456]), + new Uint32Array([2206753,2206785,2195457,2206817,2206849,2206881,2206913,2197153,2197153,2206945,2117857,2206977,2207009,2207041,2207073,2207105]), + new Uint32Array([0,0,0,0,0,0,0,23068672,0,0,0,0,2144834,2144898,0,2144962]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,23068672]), + new Uint32Array([2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,0,2105505,2098241]), + new Uint32Array([6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,2202049,6291456,2202081,6291456,2202113,6291456,2202145,6291456,2202177,6291456,2202209,6291456,2202241,6291456]), + new Uint32Array([10501155,10501251,10501347,10501443,10501539,10501635,10501731,10501827,10501923,10502019,2141731,2105505,2098177,2155586,2166530,0]), + new Uint32Array([2102081,2102209,2100833,2100737,2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209,2100833,2100737,2098337,2101441]), + new Uint32Array([2146882,2146946,2147010,2147074,2147138,2147202,2147266,2147330,2146882,2146946,2147010,2147074,2147138,2147202,2147266,2147330]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0]), + new Uint32Array([10502307,10502403,10502499,10502595,10502691,10502787,10502883,10502979,10503075,10503171,10503267,10503363,10503459,10503555,10503651,10503747]), + new Uint32Array([2179937,2179969,2180001,2180033,2156545,2180065,2156577,2180097,2180129,2180161,2180193,2180225,2180257,2180289,2156737,2180321]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,0,0,0,6291456,0,0,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0]), + new Uint32Array([2227682,2227746,2227810,2227874,2227938,2228002,2228066,2228130,2228194,2228258,2228322,2228386,2228450,2228514,2228578,2228642]), + new Uint32Array([2105601,2169121,2108193,2170049,2181025,2181057,2112481,2108321,2108289,2181089,2170497,2100865,2181121,2173601,2173633,2173665]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2180641,6291456,6291456,6291456]), + new Uint32Array([0,6291456,6291456,6291456,0,6291456,0,6291456,0,0,6291456,6291456,0,6291456,6291456,6291456]), + new Uint32Array([2178273,6291456,2178305,6291456,2178337,6291456,2178369,6291456,2178401,6291456,2178433,6291456,2178465,6291456,2178497,6291456]), + new Uint32Array([6291456,6291456,23068672,23068672,23068672,6291456,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,14680064,14680064,14680064,14680064,14680064,14680064]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456]), + new Uint32Array([2237377,2237409,2236225,2237441,2237473,2217441,2215521,2215553,2217473,2237505,2237537,2209697,2237569,2215585,2237601,2237633]), + new Uint32Array([2221985,2165601,2165601,2165665,2165665,2222017,2222017,2165729,2165729,2158913,2158913,2158913,2158913,2097281,2097281,2105921]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2149634,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2176897,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,2176929,6291456,2176961,6291456,2176993,6291456]), + new Uint32Array([2172641,6291456,2172673,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2172705,2172737,6291456,2172769,2172801,6291456]), + new Uint32Array([2099173,2104196,2121667,2099395,2121763,2152258,2152322,2098946,2152386,2121859,2121955,2099333,2122051,2104324,2099493,2122147]), + new Uint32Array([6291456,6291456,6291456,2145794,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,2145858,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,0,0,6291456,0]), + new Uint32Array([0,2105921,2097729,0,2097377,0,0,2106017,0,2097505,2105889,2097185,2097697,2135777,2097633,2097441]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2239074,2239138,2239201,2239233,2239265,2239297,2239329,2239361,0,2239393,2239425,2239425,2239458,2239521,2239553,2209569]), + new Uint32Array([14680064,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,6291456,23068672]), + new Uint32Array([2108321,2108289,2113153,2098209,2180897,2180929,2180961,2111137,2098241,2108353,2170241,2170273,2180993,2105825,6291456,2105473]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2146114,6291456,6291456,6291456,0,0,0]), + new Uint32Array([2105921,2105921,2105921,2222049,2222049,2130977,2130977,2130977,2130977,2160065,2160065,2160065,2160065,2097729,2097729,2097729]), + new Uint32Array([2218145,2214785,2207937,2218177,2218209,2192993,2210113,2212769,2218241,2218273,2216129,2218305,2216161,2218337,2218369,2218401]), + new Uint32Array([0,0,0,2156546,2156610,2156674,2156738,2156802,0,0,0,0,0,2156866,23068672,2156930]), + new Uint32Array([23068672,23068672,23068672,0,0,0,0,23068672,23068672,0,0,23068672,23068672,23068672,0,0]), + new Uint32Array([2213409,2213441,2213473,2213505,2213537,2213569,2213601,2213633,2213665,2195681,2213697,2213729,2213761,2213793,2213825,2213857]), + new Uint32Array([2100033,2099233,2122017,2200673,2098113,2121537,2103201,2200705,2104033,2121857,2121953,2122401,2099649,2099969,2123009,2100129]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2201857,6291456,2201889,6291456,2201921,6291456,2201953,6291456,2201985,6291456,2202017,6291456,2176193,2176257,23068672,23068672]), + new Uint32Array([6291456,6291456,23068672,23068672,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2188193,2188225,2188257,2188289,2188321,2188353,2188385,2188417,2188449,2188481,2188513,2188545,2188577,2188609,2188641,0]), + new Uint32Array([10554529,2221089,0,10502113,10562017,10537921,10538049,2221121,2221153,0,0,0,0,0,0,0]), + new Uint32Array([2213889,2213921,2213953,2213985,2214017,2214049,2214081,2194177,2214113,2214145,2214177,2214209,2214241,2214273,2214305,2214337]), + new Uint32Array([2166978,2167042,2099169,0,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2180545,6291456,6291456,6291456]), + new Uint32Array([10518915,10519011,10519107,10519203,2162242,2162306,2159554,2162370,2159362,2159618,2105922,2162434,2159746,2162498,2159810,2159874]), + new Uint32Array([2161730,2161794,2135586,2161858,2161922,2137186,2131810,2160290,2135170,2161986,2137954,2162050,2162114,2162178,10518723,10518819]), + new Uint32Array([10506627,10506723,10506819,10506915,10507011,10507107,10507203,10507299,10507395,10507491,10507587,10507683,10507779,10507875,10507971,10508067]), + new Uint32Array([6291456,23068672,23068672,23068672,0,23068672,23068672,0,0,0,0,0,23068672,23068672,23068672,23068672]), + new Uint32Array([23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0]), + new Uint32Array([2175873,2175905,2175937,2175969,2176001,2176033,2176065,2176097,2176129,2176161,2176193,2176225,2176257,2176289,2176321,2176353]), + new Uint32Array([2140006,2140198,2140390,2140582,2140774,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,23068672,23068672,23068672]), + new Uint32Array([2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241]), + new Uint32Array([0,23068672,0,0,0,0,0,0,0,2145154,2145218,2145282,6291456,0,2145346,0]), + new Uint32Array([0,0,0,0,10531458,10495395,2148545,2143201,2173473,2148865,2173505,0,2173537,0,2173569,2149121]), + new Uint32Array([10537282,10495683,2148738,2148802,2148866,0,6291456,2148930,2186593,2173473,2148737,2148865,2148802,10495779,10495875,10495971]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2215425,2215457,2215489,2215521,2215553,2215585,2215617,2215649,2215681,2215713,2215745,2215777,2192033,2215809,2215841,2215873]), + new Uint32Array([2242049,2242081,2242113,2242145,2242177,2242209,2242241,2242273,2215937,2242305,2242338,2242401,2242433,2242465,2242497,2216001]), + new Uint32Array([10554529,2221089,0,0,10562017,10502113,10538049,10537921,2221185,10489601,10489697,10609889,10609921,2141729,2141793,10610273]), + new Uint32Array([2141923,2142019,2142115,2142211,2142307,2142403,2142499,2142595,2142691,0,0,0,0,0,0,0]), + new Uint32Array([0,2221185,2221217,10609857,10609857,10489601,10489697,10609889,10609921,2141729,2141793,2221345,2221377,2221409,2221441,2187105]), + new Uint32Array([6291456,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,18923970,23068672,23068672,23068672,0,6291456,6291456]), + new Uint32Array([2183105,6291456,2183137,6291456,2183169,6291456,2183201,6291456,2183233,6291456,2183265,6291456,2183297,6291456,2183329,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0]), + new Uint32Array([23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456]), + new Uint32Array([2134434,2134818,2097666,2097186,2097474,2097698,2105986,2131586,2132450,2131874,2131778,2135970,2135778,2161602,2136162,2161666]), + new Uint32Array([2236865,2236897,2236930,2236993,2237025,2235681,2237058,2237121,2237153,2237185,2237217,2217281,2237250,2191233,2237313,2237345]), + new Uint32Array([2190049,6291456,2190081,6291456,2190113,6291456,2190145,6291456,2190177,6291456,2190209,6291456,2190241,6291456,2190273,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2101922,2102050,2102178,2102306,10498755,10498851,10498947,10499043,10499139,10499235,10499331,10499427,10499523,10489604,10489732,10489860]), + new Uint32Array([2166914,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0]), + new Uint32Array([2181601,2170561,2181633,2181665,2170753,2181697,2172897,2170881,2181729,2170913,2172929,2113441,2181761,2181793,2171009,2173761]), + new Uint32Array([0,2105921,2097729,2106081,0,2097601,2162337,2106017,2133281,2097505,0,2097185,2097697,2135777,2097633,2097441]), + new Uint32Array([6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,0,0,0,0]), + new Uint32Array([2248001,2248033,2248066,2248130,2248193,2248226,2248289,2248322,2248385,2248417,2216673,2248450,2248514,2248577,2248610,2248673]), + new Uint32Array([6291456,6291456,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,0,0,0]), + new Uint32Array([2169729,6291456,2169761,6291456,2169793,6291456,2169825,6291456,2169857,2169889,6291456,2169921,6291456,2143329,6291456,2098305]), + new Uint32Array([2162178,2163202,2163266,2135170,2136226,2161986,2137954,2159426,2159490,2163330,2159554,2163394,2159682,2139522,2136450,2159746]), + new Uint32Array([2173953,2173985,0,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2174209,2174241,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,4271169,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2174273]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,6291456,0,0,0,0,0,0,0,6291456,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,2190785,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2189793,6291456,2189825,6291456,2189857,6291456,2189889,6291456,2189921,6291456,2189953,6291456,2189985,6291456,2190017,6291456]), + new Uint32Array([2105601,2112289,2108193,2112481,2112577,0,2098305,2108321,2108289,2100865,2113153,2108481,2113345,0,2098209,2111137]), + new Uint32Array([2172129,6291456,2172161,6291456,2172193,6291456,2172225,6291456,2172257,6291456,2172289,6291456,2172321,6291456,2172353,6291456]), + new Uint32Array([2214753,6291456,2214785,6291456,6291456,2214817,2214849,2214881,2214913,2214945,2214977,2215009,2215041,2215073,2194401,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,6291456,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([0,0,0,0,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([10610305,10610337,10575617,2221761,10610401,10610433,10502177,0,10610465,10610497,10610529,10610561,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,23068672,0,0,0,0,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2187105,2187137,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2199393,2199425,2199457,2199489,2199521,2199553,2199585,2199617,2199649,2199681,2199713,2199745,2199777,2199809,2199841,0]), + new Uint32Array([2217249,2217281,2217313,2217345,2217377,2217409,2217441,2217473,2215617,2217505,2217537,2217569,2214753,2217601,2217633,2217665]), + new Uint32Array([2170273,2170305,6291456,2170337,2170369,6291456,2170401,2170433,2170465,6291456,6291456,6291456,2170497,2170529,6291456,2170561]), + new Uint32Array([2188673,6291456,2188705,2188737,2188769,6291456,6291456,2188801,6291456,2188833,6291456,2188865,6291456,2180929,2181505,2180897]), + new Uint32Array([10489988,10490116,10490244,10490372,10490500,10490628,10490756,10490884,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2147393,2147457,2147521,2147585,2147649,2147713,2147777,2147841]), + new Uint32Array([23068672,23068672,0,23068672,23068672,0,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0]), + new Uint32Array([2241153,2241185,2241217,2215809,2241250,2241313,2241345,2241377,2217921,2241377,2241409,2215873,2241441,2241473,2241505,2241537]), + new Uint32Array([23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2220417,2220417,2220449,2220449,2220481,2220481,2220513,2220513,2220545,2220545,2220577,2220577,2220609,2220609,2220641,2220641]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,2144002,0,6291456,6291456,0,0,6291456,6291456,6291456]), + new Uint32Array([2167105,2167137,2167169,2167201,2167233,2167265,2167297,2167329,2167361,2167393,2167425,2167457,2167489,2167521,2167553,2167585]), + new Uint32Array([10575521,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193]), + new Uint32Array([2234146,2234210,2234274,2234338,2234402,2234466,2234530,2234594,2234658,2234722,2234786,2234850,2234914,2234978,2235042,2235106]), + new Uint32Array([0,0,0,0,0,0,0,2180577,0,0,0,0,0,2180609,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,0,0,6291456,6291456]), + new Uint32Array([2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481]), + new Uint32Array([23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2242529,2242561,2242593,2242625,2242657,2242689,2242721,2242753,2207937,2218177,2242785,2242817,2242849,2242882,2242945,2242977]), + new Uint32Array([2118049,2105345,2118241,2105441,2118433,2118529,2118625,2118721,2118817,2200257,2200289,2191809,2200321,2200353,2200385,2200417]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0]), + new Uint32Array([2185505,6291456,2185537,6291456,2185569,6291456,2185601,6291456,2185633,6291456,2185665,6291456,2185697,6291456,2185729,6291456]), + new Uint32Array([2231970,2232034,2232098,2232162,2232226,2232290,2232354,2232418,2232482,2232546,2232610,2232674,2232738,2232802,2232866,2232930]), + new Uint32Array([2218625,2246402,2246466,2246530,2246594,2246657,2246689,2246689,2218657,2219681,2246721,2246753,2246785,2246818,2246881,2208481]), + new Uint32Array([2197025,2197057,2197089,2197121,2197153,2197185,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2219137,2216961,2219169,2219201,2219233,2219265,2219297,2217025,2215041,2219329,2217057,2219361,2217089,2219393,2197153,2219426]), + new Uint32Array([23068672,23068672,23068672,0,0,0,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,0,0]), + new Uint32Array([2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713]), + new Uint32Array([2243522,2243585,2243617,2243649,2243681,2210113,2243713,2243746,2243810,2243874,2243937,2243970,2244033,2244065,2244097,2244129]), + new Uint32Array([2178017,6291456,2178049,6291456,2178081,6291456,2178113,6291456,2178145,6291456,2178177,6291456,2178209,6291456,2178241,6291456]), + new Uint32Array([10553858,2165314,10518722,6291456,10518818,0,10518914,2130690,10519010,2130786,10519106,2130882,10519202,2165378,10554050,2165506]), + new Uint32Array([0,0,2135491,2135587,2135683,2135779,2135875,2135971,2135971,2136067,2136163,2136259,2136355,2136355,2136451,2136547]), + new Uint32Array([23068672,23068672,23068672,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456]), + new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2220033,2220033,2220065,2220065,2220065,2220065,2220097,2220097,2220097,2220097,2220129,2220129,2220129,2220129,2220161,2220161]), + new Uint32Array([6291456,6291456,6291456,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,23068672,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2100897,2100898,2100899,2150018,2100865,2100866,2100867,2100868,2150082,2108481,2109858,2109859,2105569,2105505,2098241,2105601]), + new Uint32Array([2097217,2097505,2097505,2097505,2097505,2165570,2165570,2165634,2165634,2165698,2165698,2097858,2097858,0,0,2097152]), + new Uint32Array([23068672,6291456,23068672,23068672,23068672,6291456,6291456,23068672,23068672,6291456,6291456,6291456,6291456,6291456,23068672,23068672]), + new Uint32Array([23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0]), + new Uint32Array([10503843,10503939,10504035,10504131,10504227,10504323,10504419,10504515,10504611,10504707,10504803,10504899,10504995,10491140,10491268,0]), + new Uint32Array([2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889,2173921,2173953,2173985,2173761,2174017,2174049]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2134145,2097153,2134241,2105953,2132705,2130977,2160065,2131297,2162049,2133089,2160577,2133857,2235297,2220769,2235329,2235361]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2222401,2222433,2222465,10531394,2222497,2222529,2222561,0,2222593,2222625,2222657,2222689,2222721,2222753,2222785,0]), + new Uint32Array([2184481,6291456,2184513,6291456,2184545,6291456,2184577,6291456,2184609,6291456,2184641,6291456,2184673,6291456,2184705,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,23068672,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,23068672,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2105570,2156034,2126947,2156098,2153666,2127043,2127139,2156162,0,2127235,2156226,2156290,2156354,2156418,2127331,2127427]), + new Uint32Array([2215905,2207041,2153185,2241569,2241601,2241633,2241665,2241697,2241730,2241793,2241825,2241857,2241889,2241921,2241954,2242017]), + new Uint32Array([2203777,6291456,2203809,6291456,2203841,6291456,2203873,6291456,2203905,6291456,2173121,2180993,2181249,2203937,2181313,0]), + new Uint32Array([2168577,6291456,2168609,6291456,2168641,6291456,2168673,6291456,2168705,6291456,2168737,6291456,2168769,6291456,2168801,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,23068672,23068672,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,0,23068672,23068672,23068672,0,0]), + new Uint32Array([2210113,2195521,2210145,2210177,2210209,2210241,2210273,2210305,2210337,2210369,2210401,2210433,2210465,2210497,2210529,2210561]), + new Uint32Array([6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0]), + new Uint32Array([2228706,2228770,2228834,2228898,2228962,2229026,2229090,2229154,2229218,2229282,2229346,2229410,2229474,2229538,2229602,2229666]), + new Uint32Array([23068672,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,0,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,18874368,18874368,18874368,0,0]), + new Uint32Array([2133089,2133281,2133281,2133281,2133281,2160577,2160577,2160577,2160577,2097441,2097441,2097441,2097441,2133857,2133857,2133857]), + new Uint32Array([6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2173825,2153473,2173857,2173889,2173921,2173953,2173985,2174017,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233089]), + new Uint32Array([2178529,6291456,2178561,6291456,2178593,6291456,2178625,6291456,2178657,6291456,2178689,6291456,2178721,6291456,2178753,6291456]), + new Uint32Array([2221025,2221025,2221057,2221057,2159329,2159329,2159329,2159329,2097217,2097217,2158914,2158914,2158978,2158978,2159042,2159042]), + new Uint32Array([2208161,2208193,2208225,2208257,2194433,2208289,2208321,2208353,2208385,2208417,2208449,2208481,2208513,2208545,2208577,2208609]), + new Uint32Array([2169217,6291456,2169249,6291456,2169281,6291456,2169313,6291456,2169345,6291456,2169377,6291456,2169409,6291456,2169441,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456]), + new Uint32Array([2133187,2133283,2133283,2133379,2133475,2133571,2133667,2133667,2133763,2133859,2133955,2134051,2134147,2134147,2134243,2134339]), + new Uint32Array([2197697,2114113,2114209,2197729,2197761,2114305,2197793,2114401,2114497,2197825,2114593,2114689,2114785,2114881,2114977,0]), + new Uint32Array([2193089,2193121,2193153,2193185,2117665,2117569,2193217,2193249,2193281,2193313,2193345,2193377,2193409,2193441,2193473,2193505]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0]), + new Uint32Array([6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2184225,6291456,2184257,6291456,2184289,6291456,2184321,6291456,2184353,6291456,2184385,6291456,2184417,6291456,2184449,6291456]), + new Uint32Array([2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2100833,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2098657,2098049,2200737,2123489,2123681,2200769,2098625,2100321,2098145,2100449,2098017,2098753,2200801,2200833,2200865,0]), + new Uint32Array([23068672,23068672,23068672,0,0,0,0,0,0,0,0,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0]), + new Uint32Array([2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,0,2098241,2108353,2108417,2105825,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2181153,2105505,2181185,2167617,2180993]), + new Uint32Array([2160002,2160066,2160130,2160194,2160258,2132066,2131010,2131106,2106018,2131618,2160322,2131298,2132034,2131938,2137410,2132226]), + new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,6291456]), + new Uint32Array([2183617,6291456,2183649,6291456,2183681,6291456,2183713,6291456,2183745,6291456,2183777,6291456,2183809,6291456,2183841,6291456]), + new Uint32Array([0,6291456,6291456,0,6291456,0,0,6291456,6291456,0,6291456,0,0,6291456,0,0]), + new Uint32Array([2250977,2251009,2251041,2251073,2195009,2251106,2251169,2251201,2251233,2251265,2251297,2251330,2251394,2251457,2251489,2251521]), + new Uint32Array([2205729,2205761,2205793,2205825,2205857,2205889,2205921,2205953,2205985,2206017,2206049,2206081,2206113,2206145,2206177,2206209]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2143170,2168993,6291456,2169025,6291456,2169057,6291456,2169089,6291456,2143234,2169121,6291456,2169153,6291456,2169185,6291456]), + new Uint32Array([23068672,23068672,2190689,6291456,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2248706,2248769,2248801,2248833,2248865,2248897,2248929,2248962,2249026,2249090,2249154,2240705,2249217,2249249,2249281,2249313]), + new Uint32Array([10485857,6291456,6291456,6291456,6291456,6291456,6291456,6291456,10495394,6291456,2098209,6291456,6291456,2097152,6291456,10531394]), + new Uint32Array([0,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,0]), + new Uint32Array([14680064,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2173985,2173953,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889]), + new Uint32Array([6291456,2186977,6291456,6291456,6291456,6291456,6291456,10537858,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2209601,2209633,2209665,2209697,2209729,2209761,2209793,2209825,2209857,2209889,2209921,2209953,2209985,2210017,2210049,2210081]), + new Uint32Array([10501539,10501635,10501731,10501827,10501923,10502019,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905]), + new Uint32Array([2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889,2173921,2173953,2173985,2174017,2174017,2174049]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,0,0]), + new Uint32Array([6291456,6291456,23068672,23068672,23068672,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2194561,2194593,2194625,2119777,2119873,2194657,2194689,2194721,2194753,2194785,2194817,2194849,2194881,2194913,2194945,2194977]), + new Uint32Array([2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569]), + new Uint32Array([2222818,2222882,2222946,2223010,2223074,2223138,2223202,2223266,2223330,2223394,2223458,2223522,2223586,2223650,2223714,2223778]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672]), + new Uint32Array([0,2179553,2179585,2179617,2179649,2144001,2179681,2179713,2179745,2179777,2179809,2156705,2179841,2156833,2179873,2179905]), + new Uint32Array([6291456,23068672,6291456,2145602,23068672,23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,6291456,0,0]), + new Uint32Array([2196513,2196545,2196577,2196609,2196641,2196673,2196705,2196737,2196769,2196801,2196833,2196865,2196897,2196929,2196961,2196993]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2177281,6291456,2177313,6291456,2177345,6291456,2177377,6291456,2177409,6291456,2177441,6291456,2177473,6291456,2177505,6291456]), + new Uint32Array([2187137,2221473,2221505,2221537,2221569,6291456,6291456,10610209,10610241,10537986,10537986,10537986,10537986,10609857,10609857,10609857]), + new Uint32Array([2243009,2243041,2216033,2243074,2243137,2243169,2243201,2219617,2243233,2243265,2243297,2243329,2243362,2243425,2243457,2243489]), + new Uint32Array([10485857,10485857,10485857,10485857,10485857,10485857,10485857,10485857,10485857,10485857,10485857,2097152,4194304,4194304,0,0]), + new Uint32Array([2143042,6291456,2143106,2143106,2168833,6291456,2168865,6291456,6291456,2168897,6291456,2168929,6291456,2168961,6291456,2143170]), + new Uint32Array([6291456,6291456,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2204193,2204225,2204257,2204289,2204321,2204353,2204385,2204417,2204449,2204481,2204513,2204545,2204577,2204609,2204641,2204673]), + new Uint32Array([2202753,6291456,2202785,6291456,2202817,6291456,2202849,6291456,2202881,6291456,2202913,6291456,2202945,6291456,2202977,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177,2098305,2108321]), + new Uint32Array([2147394,2147458,2147522,2147586,2147650,2147714,2147778,2147842,2147394,2147458,2147522,2147586,2147650,2147714,2147778,2147842]), + new Uint32Array([2253313,2253346,2253409,2253441,2253473,2253505,2253537,2253569,2253601,2253634,2219393,2253697,2253729,2253761,2253793,2253825]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,6291456,6291456]), + new Uint32Array([2162562,2162626,2131362,2162690,2159938,2160002,2162754,2162818,2160130,2162882,2160194,2160258,2160834,2160898,2161026,2161090]), + new Uint32Array([2175361,2175393,2175425,2175457,2175489,2175521,2175553,2175585,2175617,2175649,2175681,2175713,2175745,2175777,2175809,2175841]), + new Uint32Array([2253858,2253921,2253954,2254018,2254082,2196737,2254145,2196865,2254177,2254209,2254241,2254273,2197025,2254306,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2202113,2204129,2188705,2204161]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,0,6291456,6291456,6291456,6291456,0,0]), + new Uint32Array([2173985,2174017,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233089,2173697,2173761,2173793,2174113,2173985,2173953]), + new Uint32Array([2101569,2101697,2101825,2101953,2102081,2102209,2100833,2100737,2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209]), + new Uint32Array([2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241,0,2108417,0,2111713,2100897,2111905]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0]), + new Uint32Array([2175425,2175489,2175809,2175905,2175937,2175937,2176193,2176417,2180865,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,2143298,2143298,2143298,2143362,2143362,2143362,2143426,2143426,2143426,2171105,6291456,2171137]), + new Uint32Array([2120162,2120258,2151618,2151682,2151746,2151810,2151874,2151938,2152002,2120035,2120131,2120227,2152066,2120323,2152130,2120419]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2195361,2142433,2236065,2236097,2236129,2236161,2118241,2117473,2236193,2236225,2236257,2236289,0,0,0,0]), + new Uint32Array([2189281,6291456,2189313,6291456,2189345,6291456,2189377,6291456,2189409,6291456,2189441,6291456,2189473,6291456,2189505,6291456]), + new Uint32Array([6291456,6291456,2145922,6291456,6291456,6291456,6291456,2145986,6291456,6291456,6291456,6291456,2146050,6291456,6291456,6291456]), + new Uint32Array([2100833,2100737,2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209,10502113,10562017,10610401,10502177,10610433,10538049]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,2186401,0,2186433,0,2186465,0,2186497]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,23068672,23068672,23068672]), + new Uint32Array([0,0,2198241,2198273,2198305,2198337,2198369,2198401,0,0,2198433,2198465,2198497,0,0,0]), + new Uint32Array([6291456,0,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,0,6291456,0,23068672,23068672,23068672,23068672,23068672,23068672,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,0,0,23068672,6291456,23068672,23068672]), + new Uint32Array([0,2105921,2097729,0,2097377,0,0,2106017,2133281,2097505,2105889,0,2097697,2135777,2097633,2097441]), + new Uint32Array([2197889,2197921,2197953,2197985,2198017,2198049,2198081,2198113,2198145,2198177,2198209,2198241,2198273,2198305,2198337,2198369]), + new Uint32Array([2132514,2132610,2160386,2133090,2133186,2160450,2160514,2133282,2160578,2133570,2106178,2160642,2133858,2160706,2160770,2134146]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,23068672,0,0,0,0,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,23068672,23068672,6291456,23068672,23068672,6291456,23068672,0,0,0,0,0,0,0,0]), + new Uint32Array([2184737,6291456,2184769,6291456,2184801,6291456,2184833,6291456,2184865,6291456,2184897,6291456,2184929,6291456,2184961,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,0,6291456,6291456,6291456,6291456,0,6291456]), + new Uint32Array([6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,6291456,23068672,23068672,23068672,6291456,23068672,23068672,23068672,23068672,23068672,0,0]), + new Uint32Array([6291456,6291456,6291456,2186753,6291456,6291456,6291456,6291456,2186785,2186817,2186849,2173569,2186881,10496355,10495395,10575521]), + new Uint32Array([0,0,2097729,0,0,0,0,2106017,0,2097505,0,2097185,0,2135777,2097633,2097441]), + new Uint32Array([2189537,6291456,2189569,6291456,2189601,6291456,2189633,6291456,2189665,6291456,2189697,6291456,2189729,6291456,2189761,6291456]), + new Uint32Array([2202497,6291456,2202529,6291456,2202561,6291456,2202593,6291456,2202625,6291456,2202657,6291456,2202689,6291456,2202721,6291456]), + new Uint32Array([2245217,2218369,2245249,2245282,2245345,2245377,2245410,2245474,2245537,2245569,2245601,2245633,2245665,2245665,2245697,2245729]), + new Uint32Array([6291456,0,23068672,23068672,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,0,0,0,0,0,0,23068672,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,6291456,23068672,6291456,23068672,6291456,6291456,6291456,6291456,23068672,23068672]), + new Uint32Array([0,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2097281,2105921,2097729,2106081,2097377,2097601,2162337,2106017,2133281,2097505,0,2097185,2097697,2135777,2097633,2097441]), + new Uint32Array([2176641,6291456,2176673,6291456,2176705,6291456,2176737,6291456,2176769,6291456,2176801,6291456,2176833,6291456,2176865,6291456]), + new Uint32Array([2174145,2174177,2149057,2233089,2173697,2173761,2173793,2174113,2173985,2173953,2174369,2174369,0,0,2100833,2100737]), + new Uint32Array([2116513,2190817,2190849,2190881,2190913,2190945,2116609,2190977,2191009,2191041,2191073,2117185,2191105,2191137,2191169,2191201]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,6291456,6291456,6291456]), + new Uint32Array([0,0,0,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456]), + new Uint32Array([2167617,2167649,2167681,2167713,2167745,2167777,2167809,6291456,2167841,2167873,2167905,2167937,2167969,2168001,2168033,4240130]), + new Uint32Array([2165122,2163970,2164034,2164098,2164162,2164226,2164290,2164354,2164418,2164482,2164546,2133122,2134562,2132162,2132834,2136866]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,2186209,2186241,2186273,2186305,2186337,2186369,0,0]), + new Uint32Array([2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,14680064,14680064,14680064,14680064,14680064]), + new Uint32Array([0,0,23068672,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456]), + new Uint32Array([0,10537921,10610689,10610273,10610497,10610529,10610305,10610721,10489601,10489697,10610337,10575617,10554529,2221761,2197217,10496577]), + new Uint32Array([2105473,2105569,2105601,2112289,0,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441]), + new Uint32Array([2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481]), + new Uint32Array([2125346,2153410,2153474,2127394,2153538,2153602,2153666,2153730,2105507,2105476,2153794,2153858,2153922,2153986,2154050,2105794]), + new Uint32Array([2200449,2119681,2200481,2153313,2199873,2199905,2199937,2200513,2200545,2200577,2200609,2119105,2119201,2119297,2119393,2119489]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2175777,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2222273,2197217,2221473,2221505,2221089,2222305,2200865,2099681,2104481,2222337,2099905,2120737,2222369,2103713,2100225,2098785]), + new Uint32Array([2201377,6291456,2201409,6291456,2201441,6291456,2201473,6291456,2201505,6291456,2201537,6291456,2201569,6291456,6291456,23068672]), + new Uint32Array([2174081,2174113,2174145,2174177,2149057,2233057,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793]), + new Uint32Array([2200897,6291456,2200929,6291456,2200961,6291456,2200993,6291456,2201025,6291456,2180865,6291456,2201057,6291456,2201089,6291456]), + new Uint32Array([0,0,0,0,0,23068672,23068672,0,6291456,6291456,6291456,0,0,0,0,0]), + new Uint32Array([2161154,2161410,2138658,2161474,2161538,2097666,2097186,2097474,2162946,2132450,2163010,2163074,2136162,2163138,2161666,2161730]), + new Uint32Array([2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889,2173921,2173953]), + new Uint32Array([0,0,0,0,0,0,23068672,23068672,0,0,0,0,2145410,2145474,0,6291456]), + new Uint32Array([2244161,2216065,2212769,2244193,2244225,2244257,2244290,2244353,2244385,2244417,2244449,2218273,2244481,2244514,2244577,2244609]), + new Uint32Array([2125730,2125699,2125795,2125891,2125987,2154114,2154178,2154242,2154306,2154370,2154434,2154498,2126082,2126178,2126274,2126083]), + new Uint32Array([2237665,2237697,2237697,2237697,2237730,2237793,2237825,2237857,2237890,2237953,2237985,2238017,2238049,2238081,2238113,2238145]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2150146,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,0,23068672,23068672,0,0,23068672,23068672,23068672,0,0]), + new Uint32Array([2214369,2238593,2238625,2238657,2238689,2238721,2238753,2238785,2238817,2238850,2238913,2238945,2238977,2235457,2239009,2239041]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0]), + new Uint32Array([2252066,2252130,2252193,2252225,2252257,2252290,2252353,2252385,2252417,2252449,2252481,2252513,2252545,2252578,2252641,2252673]), + new Uint32Array([2197697,2114113,2114209,2197729,2197761,2114305,2197793,2114401,2114497,2197825,2114593,2114689,2114785,2114881,2114977,2197857]), + new Uint32Array([2224866,2224930,2224994,2225058,2225122,2225186,2225250,2225314,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2219490,2219554,2219617,2219649,2219681,2219714,2219778,2219842,2219905,2219937,0,0,0,0,0,0]), + new Uint32Array([6291456,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456]), + new Uint32Array([2113345,2113441,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289]), + new Uint32Array([2174081,2174113,2174145,2174177,2149057,2233089,2173697,2173761,2173793,2174113,2173985,2173953,2148481,2173601,2173633,2173665]), + new Uint32Array([2220161,2220161,2220193,2220193,2220193,2220193,2220225,2220225,2220225,2220225,2220257,2220257,2220257,2220257,2220289,2220289]), + new Uint32Array([2192673,2192705,2192737,2192769,2192801,2192833,2192865,2118049,2192897,2117473,2117761,2192929,2192961,2192993,2193025,2193057]), + new Uint32Array([2179297,6291456,2179329,6291456,2179361,6291456,2179393,6291456,2179425,6291456,2179457,6291456,2179489,6291456,2179521,6291456]), + new Uint32Array([6291456,6291456,6291456,23068672,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2235745,2235777,2193633,2235809,2235841,2235873,2235905,2235937,2235969,2116513,2116705,2236001,2200513,2199905,2200545,2236033]), + new Uint32Array([2113153,2108481,2113345,2113441,2232993,2233025,0,0,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761]), + new Uint32Array([2170593,6291456,2170625,6291456,2170657,6291456,2170689,2170721,6291456,2170753,6291456,6291456,2170785,6291456,2170817,2170849]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2166786,2166850,0,0,0,0]), + new Uint32Array([23068672,6291456,0,0,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456]), + new Uint32Array([2100833,2100737,2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209,10575617,2187041,10502177,10489601,10489697,0]), + new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2134562,2132162,2132834,2136866,2136482,2164610,2164674,2164738,2164802,2132802,2132706,2164866,2132898,2164930,2164994,2165058]), + new Uint32Array([6291456,6291456,2098337,2101441,10531458,2153473,6291456,6291456,10531522,2100737,2108193,6291456,2106499,2106595,2106691,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2233122,2233186,2233250,2233314,2233378,2233442,2233506,2233570,2233634,2233698,2233762,2233826,2233890,2233954,2234018,2234082]), + new Uint32Array([23068672,6291456,23068672,23068672,23068672,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2205217,2205249,2205281,2205313,2205345,2205377,2205409,2205441,2205473,2205505,2205537,2205569,2205601,2205633,2205665,2205697]), + new Uint32Array([6291456,0,6291456,0,0,0,6291456,6291456,6291456,6291456,0,0,23068672,6291456,23068672,23068672]), + new Uint32Array([2173601,2173761,2174081,2173569,2174241,2174113,2173953,6291456,2174305,6291456,2174337,6291456,2174369,6291456,2174401,6291456]), + new Uint32Array([6291456,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456]), + new Uint32Array([2152450,2152514,2099653,2104452,2099813,2122243,2099973,2152578,2122339,2122435,2122531,2122627,2122723,2104580,2122819,2152642]), + new Uint32Array([2236385,2236417,2236449,2236482,2236545,2215425,2236577,2236609,2236641,2236673,2215457,2236705,2236737,2236770,2215489,2236833]), + new Uint32Array([2163394,2159746,2163458,2131362,2163522,2160130,2163778,2132226,2163842,2132898,2163906,2161410,2138658,2097666,2136162,2163650]), + new Uint32Array([2218721,2246913,2246946,2216385,2247010,2247074,2215009,2247137,2247169,2216481,2247201,2247233,2247266,2247330,2247330,0]), + new Uint32Array([2129730,2129762,2129858,2129731,2129827,2156482,2156482,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,0,0,0,0,0,6291456,0,0]), + new Uint32Array([2203969,2204001,2181377,2204033,2204065,6291456,2204097,6291456,0,0,0,0,0,0,0,0]), + new Uint32Array([2169473,6291456,2169505,6291456,2169537,6291456,2169569,6291456,2169601,6291456,2169633,6291456,2169665,6291456,2169697,6291456]), + new Uint32Array([2141542,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2220801,2220801,2220801,2220801,2220833,2220833,2220865,2220865,2220865,2220865,2220897,2220897,2220897,2220897,2139873,2139873]), + new Uint32Array([0,0,0,0,0,23068672,23068672,0,0,0,0,0,0,0,6291456,0]), + new Uint32Array([2214849,2218433,2218465,2218497,2218529,2218561,2214881,2218593,2218625,2218657,2218689,2218721,2218753,2216545,2218785,2218817]), + new Uint32Array([23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0,0,0,0,6291456]), + new Uint32Array([2136482,2164610,2164674,2164738,2164802,2132802,2132706,2164866,2132898,2164930,2164994,2165058,2165122,2132802,2132706,2164866]), + new Uint32Array([2207649,2207681,2207713,2207745,2207777,2207809,2207841,2207873,2207905,2207937,2207969,2208001,2208033,2208065,2208097,2208129]), + new Uint32Array([2123683,2105092,2152706,2123779,2105220,2152770,2100453,2098755,2123906,2124002,2124098,2124194,2124290,2124386,2124482,2124578]), + new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,6291456,0,0,0,0,0,0,0,10485857]), + new Uint32Array([6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([10508163,10508259,10508355,10508451,2200129,2200161,2192737,2200193,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2203553,6291456,2203585,6291456,6291456,6291456,2203617,6291456,2203649,6291456,2203681,6291456,2203713,6291456,2203745,6291456]), + new Uint32Array([18884449,18884065,23068672,18884417,18884034,18921185,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,18874368]), + new Uint32Array([2247393,2247426,2247489,2247521,2247553,2247586,2247649,2247681,2247713,2247745,2247777,2247810,2247873,2247905,2247937,2247969]), + new Uint32Array([6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,23068672]), + new Uint32Array([2134145,2097153,2134241,0,2132705,2130977,2160065,2131297,0,2133089,2160577,2133857,2235297,0,2235329,0]), + new Uint32Array([2182593,6291456,2182625,6291456,2182657,6291456,2182689,6291456,2182721,6291456,2182753,6291456,2182785,6291456,2182817,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2102402,2102403,6291456,2110050]), + new Uint32Array([2149890,2108323,2149954,6291456,2113441,6291456,2149057,6291456,2113441,6291456,2105473,2167265,2111137,2105505,6291456,2108353]), + new Uint32Array([2219105,2219137,2195233,2251554,2251617,2251649,2251681,2251713,2251746,2251810,2251873,2251905,2251937,2251970,2252033,2219169]), + new Uint32Array([2203009,6291456,2203041,6291456,2203073,6291456,2203105,6291456,2203137,6291456,2203169,6291456,2203201,6291456,2203233,6291456]), + new Uint32Array([2128195,2128291,2128387,2128483,2128579,2128675,2128771,2128867,2128963,2129059,2129155,2129251,2129347,2129443,2129539,2129635]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2140964,2141156,2140966,2141158,2141350]), + new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2225378,2225442,2225506,2225570,2225634,2225698,2225762,2225826,2225890,2225954,2226018,2226082,2226146,2226210,2226274,2226338]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241,2108353,2108417]), + new Uint32Array([2108353,2108417,0,2105601,2108193,2157121,2157313,2157377,2157441,2100897,6291456,2108419,2173953,2173633,2173633,2173953]), + new Uint32Array([2111713,2173121,2111905,2098177,2173153,2173185,2173217,2113153,2113345,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,2190753]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,2197249,6291456,2117377,2197281,2197313,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,0,0,0,0,0,0,23068672,0,0,0,0,0,6291456,6291456,6291456]), + new Uint32Array([2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209,2100833,2100737,2098337,2101441,2101569,2101697,2101825,2101953]), + new Uint32Array([23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0]), + new Uint32Array([0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,23068672,23068672,23068672]), + new Uint32Array([2173281,6291456,2173313,6291456,2173345,6291456,2173377,6291456,0,0,10532546,6291456,6291456,6291456,10562017,2173441]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,0,0]), + new Uint32Array([23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2159426,2159490,2159554,2159362,2159618,2159682,2139522,2136450,2159746,2159810,2159874,2130978,2131074,2131266,2131362,2159938]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2203233,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2203265,6291456,2203297,6291456,2203329,2203361,6291456]), + new Uint32Array([6291456,6291456,2148418,2148482,2148546,0,6291456,2148610,2186529,2186561,2148417,2148545,2148482,10495778,2143969,10495778]), + new Uint32Array([2134146,2139426,2160962,2134242,2161218,2161282,2161346,2161410,2138658,2134722,2134434,2134818,2097666,2097346,2097698,2105986]), + new Uint32Array([2198881,2198913,2198945,2198977,2199009,2199041,2199073,2199105,2199137,2199169,2199201,2199233,2199265,2199297,2199329,2199361]), + new Uint32Array([0,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456]), + new Uint32Array([10610561,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193]), + new Uint32Array([2183873,6291456,2183905,6291456,2183937,6291456,2183969,6291456,2184001,6291456,2184033,6291456,2184065,6291456,2184097,6291456]), + new Uint32Array([2244642,2244706,2244769,2244801,2218305,2244833,2244865,2244897,2244929,2244961,2244993,2245026,2245089,2245122,2245185,0]), + new Uint32Array([6291456,6291456,2116513,2116609,2116705,2116801,2199873,2199905,2199937,2199969,2190913,2200001,2200033,2200065,2200097,2191009]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,2180673,2180705,2180737,2180769,2180801,2180833,0,0]), + new Uint32Array([2098081,2099521,2099105,2120705,2098369,2120801,2103361,2097985,2098433,2121377,2121473,2099169,2099873,2098401,2099393,2152609]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2150402]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,2145666,2145730,6291456,6291456]), + new Uint32Array([2173921,2173953,2173985,2173761,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233057,2148481,2173601,2173633,2173665]), + new Uint32Array([2187073,6291456,6291456,6291456,6291456,2098241,2098241,2108353,2100897,2111905,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2102404,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,2100612,6291456,6291456,6291456,6291456,6291456,6291456,6291456,10485857]), + new Uint32Array([2149057,2233057,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889]), + new Uint32Array([2217697,2217729,2217761,2217793,2217825,2217857,2217889,2217921,2217953,2215873,2217985,2215905,2218017,2218049,2218081,2218113]), + new Uint32Array([2211233,2218849,2216673,2218881,2218913,2218945,2218977,2219009,2216833,2219041,2215137,2219073,2216865,2209505,2219105,2216897]), + new Uint32Array([2240097,2240129,2240161,2240193,2240225,2240257,2240289,2240321,2240353,2240386,2240449,2240481,2240513,2240545,2207905,2240578]), + new Uint32Array([6291456,6291456,2202273,6291456,2202305,6291456,2202337,6291456,2202369,6291456,2202401,6291456,2202433,6291456,2202465,6291456]), + new Uint32Array([0,23068672,23068672,18923394,23068672,18923458,18923522,18884099,18923586,18884195,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2201121,6291456,2201153,6291456,2201185,6291456,2201217,6291456,2201249,6291456,2201281,6291456,2201313,6291456,2201345,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456]), + new Uint32Array([2211041,2211073,2211105,2211137,2211169,2211201,2211233,2211265,2211297,2211329,2211361,2211393,2211425,2211457,2211489,2211521]), + new Uint32Array([2181825,6291456,2181857,6291456,2181889,6291456,2181921,6291456,2181953,6291456,2181985,6291456,2182017,6291456,2182049,6291456]), + new Uint32Array([2162337,2097633,2097633,2097633,2097633,2132705,2132705,2132705,2132705,2097153,2097153,2097153,2097153,2133089,2133089,2133089]), + new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,2148545,6291456,2173473,6291456,2148865,6291456,2173505,6291456,2173537,6291456,2173569,6291456,2149121,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,0,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0]), + new Uint32Array([2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889,2173921,2173953,2173985,2174017,2174017,2174049,2174081,2174113]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2207137,2207169,2207201,2207233,2207265,2207297,2207329,2207361,2207393,2207425,2207457,2207489,2207521,2207553,2207585,2207617]), + new Uint32Array([6291456,6291456,23068672,23068672,23068672,6291456,6291456,0,23068672,23068672,0,0,0,0,0,0]), + new Uint32Array([2198401,2198433,2198465,2198497,0,2198529,2198561,2198593,2198625,2198657,2198689,2198721,2198753,2198785,2198817,2198849]), + new Uint32Array([2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177]), + new Uint32Array([23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,0,0]), + new Uint32Array([2216385,2118721,2216417,2216449,2216481,2216513,2216545,2211233,2216577,2216609,2216641,2216673,2216705,2216737,2216737,2216769]), + new Uint32Array([2216801,2216833,2216865,2216897,2216929,2216961,2216993,2215169,2217025,2217057,2217089,2217121,2217154,2217217,0,0]), + new Uint32Array([2210593,2191809,2210625,2210657,2210689,2210721,2210753,2210785,2210817,2210849,2191297,2210881,2210913,2210945,2210977,2211009]), + new Uint32Array([0,0,2105825,0,0,2111905,2105473,0,0,2112289,2108193,2112481,2112577,0,2098305,2108321]), + new Uint32Array([0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([0,2097153,2134241,0,2132705,0,0,2131297,0,2133089,0,2133857,0,2220769,0,2235361]), + new Uint32Array([14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,6291456,6291456,14680064]), + new Uint32Array([23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0]), + new Uint32Array([2171873,6291456,2171905,6291456,2171937,6291456,2171969,6291456,2172001,6291456,2172033,6291456,2172065,6291456,2172097,6291456]), + new Uint32Array([2220929,2220929,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2133857,2134145,2134145,2134145,2134145,2134241,2134241,2134241,2134241,2105889,2105889,2105889,2105889,2097185,2097185,2097185]), + new Uint32Array([2173697,2173761,2173793,2174113,2173985,2173953,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793]), + new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,0,10499619,10499715,10499811,10499907]), + new Uint32Array([0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,0,0,0,0,0,0,0,0,0,0,0,0,0,0,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,0,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,0,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,23068672,23068672]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,2144322,2144386,2144450,2144514,2144578,2144642,2144706,2144770]), + new Uint32Array([23068672,23068672,23068672,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456]), + new Uint32Array([2113153,2108481,2113345,2113441,2098209,2111137,0,2098241,2108353,2108417,2105825,0,0,2111905,2105473,2105569]), + new Uint32Array([2236321,2236353,0,0,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2152194,2121283,2103684,2103812,2097986,2098533,2097990,2098693,2098595,2098853,2099013,2103940,2121379,2121475,2121571,2104068]), + new Uint32Array([2206241,2206273,2206305,2206337,2206369,2206401,2206433,2206465,2206497,2206529,2206561,2206593,2206625,2206657,2206689,2206721]), + new Uint32Array([6291456,6291456,6291456,6291456,16777216,16777216,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,23068672,23068672,10538818,10538882,6291456,6291456,2150338]), + new Uint32Array([6291456,6291456,6291456,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2214369,2214401,2214433,2214465,2214497,2214529,2214561,2214593,2194977,2214625,2195073,2214657,2214689,2214721,6291456,6291456]), + new Uint32Array([2097152,2097152,2097152,2097152,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2182081,6291456,2182113,6291456,2182145,6291456,2182177,6291456,2182209,6291456,2182241,6291456,2182273,6291456,2182305,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2146881,2146945,2147009,2147073,2147137,2147201,2147265,2147329]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,23068672,23068672]), + new Uint32Array([0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2122915,2123011,2123107,2104708,2123203,2123299,2123395,2100133,2104836,2100290,2100293,2104962,2104964,2098052,2123491,2123587]), + new Uint32Array([23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456]), + new Uint32Array([6291456,2171169,6291456,2171201,6291456,2171233,6291456,2171265,6291456,2171297,6291456,2171329,6291456,6291456,2171361,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([0,0,2148994,2149058,2149122,0,6291456,2149186,2186945,2173537,2148993,2149121,2149058,10531458,10496066,0]), + new Uint32Array([2195009,2195041,2195073,2195105,2195137,2195169,2195201,2195233,2195265,2195297,2195329,2195361,2195393,2195425,2195457,2195489]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,0,0,6291456,6291456]), + new Uint32Array([2182849,6291456,2182881,6291456,2182913,6291456,2182945,6291456,2182977,6291456,2183009,6291456,2183041,6291456,2183073,6291456]), + new Uint32Array([2211553,2210081,2211585,2211617,2211649,2211681,2211713,2211745,2211777,2211809,2209569,2211841,2211873,2211905,2211937,2211969]), + new Uint32Array([2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2166594,2127298,2166658,2142978,2141827,2166722]), + new Uint32Array([2173985,2173761,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233057,2148481,2173601,2173633,2173665,2173697,2173729]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,2185761,2185793,2185825,2185857,2185889,2185921,0,0]), + new Uint32Array([6291456,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889,2173921]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,6291456]), + new Uint32Array([0,0,0,2220961,2220961,2220961,2220961,2144193,2144193,2159201,2159201,2159265,2159265,2144194,2220993,2220993]), + new Uint32Array([2192641,2235393,2235425,2152257,2116609,2235457,2235489,2200065,2235521,2235553,2235585,2212449,2235617,2235649,2235681,2235713]), + new Uint32Array([2194049,2194081,2194113,2194145,2194177,2194209,2194241,2194273,2194305,2194337,2194369,2194401,2194433,2194465,2194497,2194529]), + new Uint32Array([2196673,2208641,2208673,2208705,2208737,2208769,2208801,2208833,2208865,2208897,2208929,2208961,2208993,2209025,2209057,2209089]), + new Uint32Array([2191681,2191713,2191745,2191777,2153281,2191809,2191841,2191873,2191905,2191937,2191969,2192001,2192033,2192065,2192097,2192129]), + new Uint32Array([2230946,2231010,2231074,2231138,2231202,2231266,2231330,2231394,2231458,2231522,2231586,2231650,2231714,2231778,2231842,2231906]), + new Uint32Array([14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2185953,2185985,2186017,2186049,2186081,2186113,2186145,2186177]), + new Uint32Array([2139811,2139907,2097284,2105860,2105988,2106116,2106244,2097444,2097604,2097155,10485778,10486344,2106372,6291456,0,0]), + new Uint32Array([2110051,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([0,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2172385,6291456,2172417,6291456,2172449,6291456,2172481,6291456,2172513,6291456,2172545,6291456,2172577,6291456,2172609,6291456]), + new Uint32Array([0,0,23068672,23068672,6291456,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2249345,2249377,2249409,2249441,2249473,2249505,2249537,2249570,2210209,2249633,2249665,2249697,2249729,2249761,2249793,2216769]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,6291456,6291456,6291456,6291456]), + new Uint32Array([2187169,2187201,2187233,2187265,2187297,2187329,2187361,2187393,2187425,2187457,2187489,2187521,2187553,2187585,2187617,2187649]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([0,0,0,6291456,6291456,0,0,0,6291456,6291456,6291456,0,0,0,6291456,6291456]), + new Uint32Array([2182337,6291456,2182369,6291456,2182401,6291456,2182433,6291456,2182465,6291456,2182497,6291456,2182529,6291456,2182561,6291456]), + new Uint32Array([2138179,2138275,2138371,2138467,2134243,2134435,2138563,2138659,2138755,2138851,2138947,2139043,2138947,2138755,2139139,2139235]), + new Uint32Array([23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0]), + new Uint32Array([0,0,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2250498,2250562,2250625,2250657,2208321,2250689,2250721,2250753,2250785,2250817,2250849,2218945,2250881,2250913,2250945,0]), + new Uint32Array([2170369,2105569,2098305,2108481,2173249,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456]), + new Uint32Array([2100897,2111905,2105473,2105569,2105601,0,2108193,0,0,0,2098305,2108321,2108289,2100865,2113153,2108481]), + new Uint32Array([2100897,2100897,2105569,2105569,6291456,2112289,2149826,6291456,6291456,2112481,2112577,2098177,2098177,2098177,6291456,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,6291456,6291456,6291456]), + new Uint32Array([6291456,2169953,2169985,6291456,2170017,6291456,2170049,2170081,6291456,2170113,2170145,2170177,6291456,6291456,2170209,2170241]), + new Uint32Array([6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2220641,2220641,2220673,2220673,2220673,2220673,2220705,2220705,2220705,2220705,2220737,2220737,2220737,2220737,2220769,2220769]), + new Uint32Array([2127650,2127746,2127842,2127938,2128034,2128130,2128226,2128322,2128418,2127523,2127619,2127715,2127811,2127907,2128003,2128099]), + new Uint32Array([2143969,2173793,2173825,2153473,2173857,2173889,2173921,2173953,2173985,2173761,2174017,2174049,2174081,2174113,2174145,2174177]), + new Uint32Array([0,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([2204705,2204737,2204769,2204801,2204833,2204865,2204897,2204929,2204961,2204993,2205025,2205057,2205089,2205121,2205153,2205185]), + new Uint32Array([2176385,6291456,2176417,6291456,2176449,6291456,2176481,6291456,2176513,6291456,2176545,6291456,2176577,6291456,2176609,6291456]), + new Uint32Array([2195521,2195553,2195585,2195617,2195649,2195681,2117857,2195713,2195745,2195777,2195809,2195841,2195873,2195905,2195937,2195969]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456]), + new Uint32Array([2173921,2173953,2173985,2174017,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233089,2173697,2173761,2173793,2174113]), + new Uint32Array([2131586,2132450,2135970,2135778,2161602,2136162,2163650,2161794,2135586,2163714,2137186,2131810,2160290,2135170,2097506,2159554]), + new Uint32Array([2134145,2097153,2134241,2105953,2132705,2130977,2160065,2131297,2162049,2133089,2160577,2133857,0,0,0,0]), + new Uint32Array([2116513,2116609,2116705,2116801,2116897,2116993,2117089,2117185,2117281,2117377,2117473,2117569,2117665,2117761,2117857,2117953]), + new Uint32Array([2100737,2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209,2100802,2101154,2101282,2101410,2101538,2101666,2101794]), + new Uint32Array([2100289,2098657,2098049,2200737,2123489,2123681,2200769,2098625,2100321,2098145,2100449,2098017,2098753,2098977,2150241,2150305]), + new Uint32Array([6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,2109955,6291456,6291456,0,0,0,0]), + new Uint32Array([18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,0,6291456,0,0]), + new Uint32Array([2130979,2131075,2131075,2131171,2131267,2131363,2131459,2131555,2131651,2131651,2131747,2131843,2131939,2132035,2132131,2132227]), + new Uint32Array([0,2177793,6291456,2177825,6291456,2177857,6291456,2177889,6291456,2177921,6291456,2177953,6291456,2177985,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]), + new Uint32Array([6291456,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2113345,0,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289]), + new Uint32Array([2136643,2136739,2136835,2136931,2137027,2137123,2137219,2137315,2137411,2137507,2137603,2137699,2137795,2137891,2137987,2138083]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0]), + new Uint32Array([2174433,6291456,2174465,6291456,2174497,6291456,2174529,6291456,2174561,6291456,2174593,6291456,2174625,6291456,2174657,6291456]), + new Uint32Array([0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441]), + new Uint32Array([10496547,10496643,2105505,2149698,6291456,10496739,10496835,2170273,6291456,2149762,2105825,2111713,2111713,2111713,2111713,2168673]), + new Uint32Array([6291456,2143490,2143490,2143490,2171649,6291456,2171681,2171713,2171745,6291456,2171777,6291456,2171809,6291456,2171841,6291456]), + new Uint32Array([2159106,2159106,2159170,2159170,2159234,2159234,2159298,2159298,2159298,2159362,2159362,2159362,2106401,2106401,2106401,2106401]), + new Uint32Array([2105601,2112289,2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137]), + new Uint32Array([2108417,2181217,2181249,2181281,2170433,2170401,2181313,2181345,2181377,2181409,2181441,2181473,2181505,2181537,2170529,2181569]), + new Uint32Array([2218433,2245761,2245793,2245825,2245857,2245890,2245953,2245986,2209665,2246050,2246113,2246146,2246210,2246274,2246337,2246369]), + new Uint32Array([2230754,2230818,2230882,0,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([6291456,0,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2184129,6291456,2184161,6291456,2184193,6291456,6291456,6291456,6291456,6291456,2146818,2183361,6291456,6291456,2142978,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2135170,2097506,2130691,2130787,2130883,2163970,2164034,2164098,2164162,2164226,2164290,2164354,2164418,2164482,2164546,2133122]), + new Uint32Array([2108515,2108611,2100740,2108707,2108803,2108899,2108995,2109091,2109187,2109283,2109379,2109475,2109571,2109667,2109763,2100738]), + new Uint32Array([2102788,2102916,2103044,2120515,2103172,2120611,2120707,2098373,2103300,2120803,2120899,2120995,2103428,2103556,2121091,2121187]), + new Uint32Array([2158082,2158146,0,2158210,2158274,0,2158338,2158402,2158466,2129922,2158530,2158594,2158658,2158722,2158786,2158850]), + new Uint32Array([10499619,10499715,10499811,10499907,10500003,10500099,10500195,10500291,10500387,10500483,10500579,10500675,10500771,10500867,10500963,10501059]), + new Uint32Array([2239585,2239618,2239681,2239713,0,2191969,2239745,2239777,2192033,2239809,2239841,2239874,2239937,2239970,2240033,2240065]), + new Uint32Array([2252705,2252738,2252801,2252833,2252865,2252897,2252930,2252994,2253057,2253089,2253121,2253154,2253217,2253250,2219361,2219361]), + new Uint32Array([2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,10538050,10538114,10538178,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([2226402,2226466,2226530,2226594,2226658,2226722,2226786,2226850,2226914,2226978,2227042,2227106,2227170,2227234,2227298,2227362]), + new Uint32Array([23068672,6291456,6291456,6291456,6291456,2144066,2144130,2144194,2144258,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,6291456,23068672,23068672]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0]), + new Uint32Array([2124674,2124770,2123875,2123971,2124067,2124163,2124259,2124355,2124451,2124547,2124643,2124739,2124835,2124931,2125027,2125123]), + new Uint32Array([2168065,6291456,2168097,6291456,2168129,6291456,2168161,6291456,2168193,6291456,2168225,6291456,2168257,6291456,2168289,6291456]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0]), + new Uint32Array([23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,2100610,2100611,6291456,2107842,2107843,6291456,6291456,6291456,6291456,10537922,6291456,10537986,6291456]), + new Uint32Array([2174849,2174881,2174913,2174945,2174977,2175009,2175041,2175073,2175105,2175137,2175169,2175201,2175233,2175265,2175297,2175329]), + new Uint32Array([2154562,2154626,2154690,2154754,2141858,2154818,2154882,2127298,2154946,2127298,2155010,2155074,2155138,2155202,2155266,2155202]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,23068672,0]), + new Uint32Array([2200641,2150786,2150850,2150914,2150978,2151042,2106562,2151106,2150562,2151170,2151234,2151298,2151362,2151426,2151490,2151554]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0,6291456,6291456]), + new Uint32Array([2220289,2220289,2220321,2220321,2220321,2220321,2220353,2220353,2220353,2220353,2220385,2220385,2220385,2220385,2220417,2220417]), + new Uint32Array([2155330,2155394,0,2155458,2155522,2155586,2105732,0,2155650,2155714,2155778,2125314,2155842,2155906,2126274,2155970]), + new Uint32Array([23068672,23068672,23068672,23068672,23068672,6291456,6291456,23068672,23068672,6291456,23068672,23068672,23068672,23068672,6291456,6291456]), + new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0]), + new Uint32Array([2097729,2106017,2106017,2106017,2106017,2131297,2131297,2131297,2131297,2106081,2106081,2162049,2162049,2105953,2105953,2162337]), + new Uint32Array([2097185,2097697,2097697,2097697,2097697,2135777,2135777,2135777,2135777,2097377,2097377,2097377,2097377,2097601,2097601,2097217]), + new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,23068672]), + new Uint32Array([2139331,2139427,2139523,2139043,2133571,2132611,2139619,2139715,0,0,0,0,0,0,0,0]), + new Uint32Array([2174113,2174145,2100897,2098177,2108289,2100865,2173601,2173633,2173985,2174113,2174145,6291456,6291456,6291456,6291456,6291456]), + new Uint32Array([6291456,6291456,23068672,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456]), + new Uint32Array([23068672,23068672,18923778,23068672,23068672,23068672,23068672,18923842,23068672,23068672,23068672,23068672,18923906,23068672,23068672,23068672]), + new Uint32Array([2134145,2097153,2134241,0,2132705,2130977,2160065,2131297,0,2133089,0,2133857,0,0,0,0]), + new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2177537,6291456,2177569,6291456,2177601,6291456,2177633,6291456,2177665,6291456,2177697,6291456,2177729,6291456,2177761,6291456]), + new Uint32Array([2212481,2212513,2212545,2212577,2197121,2212609,2212641,2212673,2212705,2212737,2212769,2212801,2212833,2212865,2212897,2212929]), + new Uint32Array([6291456,6291456,23068672,23068672,23068672,6291456,6291456,0,0,0,0,0,0,0,0,0]), + new Uint32Array([2098241,2108353,2170209,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,6291456,2108193,2172417,2112481,2098177]), + new Uint32Array([6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456]), + ]; + var blockIdxes = new Uint16Array([616,616,565,147,161,411,330,2,131,131,328,454,241,408,86,86,696,113,285,350,325,301,473,214,639,232,447,64,369,598,124,672,567,223,621,154,107,86,86,86,86,86,86,505,86,68,634,86,218,218,218,218,486,218,218,513,188,608,216,86,217,463,668,85,700,360,184,86,86,86,647,402,153,10,346,718,662,260,145,298,117,1,443,342,138,54,563,86,240,572,218,70,387,86,118,460,641,602,86,86,306,218,86,692,86,86,86,86,86,162,707,86,458,26,86,218,638,86,86,86,86,86,65,449,86,86,306,183,86,58,391,667,86,157,131,131,131,131,86,433,131,406,31,218,247,86,86,693,218,581,351,86,438,295,69,462,45,126,173,650,14,295,69,97,168,187,641,78,523,390,69,108,287,664,173,219,83,295,69,108,431,426,173,694,412,115,628,52,257,398,641,118,501,121,69,579,151,423,173,620,464,121,69,382,151,476,173,27,53,121,86,594,578,226,173,86,632,130,86,96,228,268,641,622,563,86,86,21,148,650,131,131,321,43,144,343,381,531,131,131,178,20,86,399,156,375,164,541,30,60,715,198,92,118,131,131,86,86,306,407,86,280,457,196,488,358,131,131,244,86,86,143,86,86,86,86,86,667,563,86,86,86,86,86,86,86,86,86,86,86,86,86,336,363,86,86,336,86,86,380,678,67,86,86,86,678,86,86,86,512,86,307,86,708,86,86,86,86,86,528,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,563,307,86,86,86,86,86,104,450,337,86,720,86,32,450,397,86,86,86,587,218,558,708,708,293,708,86,86,86,86,86,694,205,86,8,86,86,86,86,549,86,667,697,697,679,86,458,460,86,86,650,86,708,543,86,86,86,245,86,86,86,140,218,127,708,708,458,197,131,131,131,131,500,86,86,483,251,86,306,510,515,86,722,86,86,86,65,201,86,86,483,580,470,86,86,86,368,131,131,131,694,114,110,555,86,86,123,721,163,142,713,418,86,317,675,209,218,218,218,371,545,592,629,490,603,199,46,320,525,680,310,279,388,111,42,252,593,607,235,617,410,377,50,548,135,356,17,520,189,116,392,600,349,332,482,699,690,535,119,106,451,71,152,667,131,218,218,265,671,637,492,504,533,683,269,269,658,86,86,86,86,86,86,86,86,86,491,619,86,86,6,86,86,86,86,86,86,86,86,86,86,86,229,86,86,86,86,86,86,86,86,86,86,86,86,667,86,86,171,131,118,131,656,206,234,571,89,334,670,246,311,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,534,86,86,86,86,86,86,82,86,86,86,86,86,430,86,86,86,86,86,86,86,86,86,599,86,324,86,470,69,640,264,131,626,101,174,86,86,667,233,105,73,374,394,221,204,84,28,326,86,86,471,86,86,86,109,573,86,171,200,200,200,200,218,218,86,86,86,86,460,131,131,131,86,506,86,86,86,86,86,220,404,34,614,47,442,305,25,612,338,601,648,7,344,255,131,131,51,86,312,507,563,86,86,86,86,588,86,86,86,86,86,530,511,86,458,3,435,384,556,522,230,527,86,118,86,86,717,86,137,273,79,181,484,23,93,112,655,249,417,703,370,87,98,313,684,585,155,465,596,481,695,18,416,428,61,701,706,282,643,495,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,549,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,549,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,307,86,86,86,171,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,650,131,422,542,420,263,24,172,86,86,86,86,86,566,86,86,132,540,395,353,494,519,19,485,284,472,131,131,131,16,714,86,211,708,86,86,86,694,698,86,86,483,704,708,218,272,86,86,120,86,159,478,86,307,247,86,86,663,597,459,627,667,86,86,277,455,39,302,86,250,86,86,86,271,99,452,306,281,329,400,200,86,86,362,549,352,646,461,323,586,86,86,4,708,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,717,86,518,86,86,650,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,125,554,480,300,613,72,333,288,561,544,604,48,719,91,169,176,590,224,76,191,29,559,560,231,537,166,477,538,256,437,131,131,469,167,40,0,685,266,441,705,239,642,475,568,640,610,299,673,517,318,385,22,202,180,179,359,424,215,90,66,521,653,467,682,453,409,479,88,131,661,35,303,15,262,666,630,712,131,131,618,659,175,218,195,347,193,227,261,150,165,709,546,294,569,710,270,413,376,524,55,242,38,419,529,170,657,3,304,122,379,278,131,651,86,67,576,458,458,131,131,86,86,86,86,86,86,86,118,309,86,86,547,86,86,86,86,667,650,664,131,131,86,86,56,131,131,131,131,131,131,131,131,86,307,86,86,86,664,238,650,86,86,717,86,118,86,86,315,86,59,86,86,574,549,131,131,340,57,436,86,86,86,86,86,86,458,708,499,691,62,86,650,86,86,694,86,86,86,319,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,171,86,549,694,131,131,131,131,131,131,131,131,131,77,86,86,139,86,502,86,86,86,667,595,131,131,131,86,12,86,13,86,609,131,131,131,131,86,86,86,625,86,669,86,86,182,129,86,5,694,104,86,86,86,86,131,131,86,86,386,171,86,86,86,345,86,324,86,589,86,213,36,131,131,131,131,131,86,86,86,86,104,131,131,131,141,290,80,677,86,86,86,267,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,667,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,515,86,86,33,136,669,86,711,515,86,86,550,640,86,104,708,515,86,159,372,717,86,86,444,515,86,86,663,37,86,563,460,86,390,624,702,131,131,131,131,389,59,708,86,86,341,208,708,635,295,69,108,431,508,100,190,131,131,131,131,131,131,131,131,86,86,86,649,516,660,131,131,86,86,86,218,631,708,131,131,131,131,131,131,131,131,131,131,86,86,341,575,238,514,131,131,86,86,86,218,291,708,307,131,86,86,306,367,708,131,131,131,86,378,697,86,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,615,253,86,86,86,292,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,104,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,69,86,341,553,549,86,307,86,86,645,275,455,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,708,131,131,131,131,131,131,86,86,86,86,86,86,667,460,86,86,86,86,86,86,86,86,86,86,86,86,717,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,667,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,171,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,104,86,667,459,131,131,131,131,131,131,86,458,225,86,86,86,516,549,11,390,405,86,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,460,44,218,197,711,515,131,131,131,131,664,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,307,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,308,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,640,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,118,307,104,286,591,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,549,86,86,681,86,86,75,185,314,582,86,358,496,474,86,104,131,86,86,86,86,146,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,171,86,640,131,131,131,131,131,131,131,131,246,503,689,339,674,81,258,415,439,128,562,366,414,246,503,689,583,222,557,316,636,665,186,355,95,670,246,503,689,339,674,557,258,415,439,186,355,95,670,246,503,689,446,644,536,652,331,532,335,440,274,421,297,570,74,425,364,425,606,552,403,509,134,365,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,218,218,218,498,218,218,577,627,551,497,572,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,553,354,236,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,296,455,131,131,456,243,103,86,41,459,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,9,276,158,716,393,564,383,489,401,654,210,654,131,131,131,640,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,650,86,86,86,86,86,86,717,667,563,563,563,86,549,102,686,133,246,605,86,448,86,86,207,307,131,131,131,641,86,177,611,445,373,194,584,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,308,307,171,86,86,86,86,86,86,86,717,86,86,86,86,86,460,131,131,650,86,86,86,694,708,86,86,694,86,458,131,131,131,131,131,131,667,694,289,650,667,131,131,86,640,131,131,664,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,171,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,460,86,86,86,86,86,86,86,86,86,86,86,86,86,458,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,640,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,466,203,149,429,94,432,160,687,539,63,237,283,192,248,348,259,427,526,396,676,254,468,487,212,327,623,49,633,322,493,434,688,357,361,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131]); + var mappingStr = "صلى الله عليه وسلمجل جلالهキロメートルrad∕s2エスクードキログラムキロワットグラムトンクルゼイロサンチームパーセントピアストルファラッドブッシェルヘクタールマンションミリバールレントゲン′′′′1⁄10viii(10)(11)(12)(13)(14)(15)(16)(17)(18)(19)(20)∫∫∫∫(오전)(오후)アパートアルファアンペアイニングエーカーカラットカロリーキュリーギルダークローネサイクルシリングバーレルフィートポイントマイクロミクロンメガトンリットルルーブル株式会社kcalm∕s2c∕kgاكبرمحمدصلعمرسولریال1⁄41⁄23⁄4 ̈́ྲཱྀླཱྀ ̈͂ ̓̀ ̓́ ̓͂ ̔̀ ̔́ ̔͂ ̈̀‵‵‵a/ca/sc/oc/utelfax1⁄71⁄91⁄32⁄31⁄52⁄53⁄54⁄51⁄65⁄61⁄83⁄85⁄87⁄8xii0⁄3∮∮∮(1)(2)(3)(4)(5)(6)(7)(8)(9)(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)(q)(r)(s)(t)(u)(v)(w)(x)(y)(z)::====(ᄀ)(ᄂ)(ᄃ)(ᄅ)(ᄆ)(ᄇ)(ᄉ)(ᄋ)(ᄌ)(ᄎ)(ᄏ)(ᄐ)(ᄑ)(ᄒ)(가)(나)(다)(라)(마)(바)(사)(아)(자)(차)(카)(타)(파)(하)(주)(一)(二)(三)(四)(五)(六)(七)(八)(九)(十)(月)(火)(水)(木)(金)(土)(日)(株)(有)(社)(名)(特)(財)(祝)(労)(代)(呼)(学)(監)(企)(資)(協)(祭)(休)(自)(至)pte10月11月12月ergltdアールインチウォンオンスオームカイリガロンガンマギニーケースコルナコーポセンチダースノットハイツパーツピクルフランペニヒヘルツペンスページベータボルトポンドホールホーンマイルマッハマルクヤードヤールユアンルピー10点11点12点13点14点15点16点17点18点19点20点21点22点23点24点hpabardm2dm3khzmhzghzthzmm2cm2km2mm3cm3km3kpampagpalogmilmolppmv∕ma∕m10日11日12日13日14日15日16日17日18日19日20日21日22日23日24日25日26日27日28日29日30日31日galffifflשּׁשּׂ ٌّ ٍّ َّ ُّ ِّ ّٰـَّـُّـِّتجمتحجتحمتخمتمجتمحتمخجمححميحمىسحجسجحسجىسمحسمجسممصححصممشحمشجيشمخشممضحىضخمطمحطممطميعجمعممعمىغممغميغمىفخمقمحقمملحملحيلحىلججلخملمحمحجمحيمجحمجممخممجخهمجهممنحمنحىنجمنجىنمينمىيممبخيتجيتجىتخيتخىتميتمىجميجحىجمىسخىصحيشحيضحيلجيلمييحييجييميمميقمينحيعميكمينجحمخيلجمكممجحيحجيمجيفميبحيسخينجيصلےقلے𝅘𝅥𝅮𝅘𝅥𝅯𝅘𝅥𝅰𝅘𝅥𝅱𝅘𝅥𝅲𝆹𝅥𝅮𝆺𝅥𝅮𝆹𝅥𝅯𝆺𝅥𝅯〔s〕ppv〔本〕〔三〕〔二〕〔安〕〔点〕〔打〕〔盗〕〔勝〕〔敗〕 ̄ ́ ̧ssi̇ijl·ʼndžljnjdz ̆ ̇ ̊ ̨ ̃ ̋ ιեւاٴوٴۇٴيٴक़ख़ग़ज़ड़ढ़फ़य़ড়ঢ়য়ਲ਼ਸ਼ਖ਼ਗ਼ਜ਼ਫ਼ଡ଼ଢ଼ําໍາຫນຫມགྷཌྷདྷབྷཛྷཀྵཱཱིུྲྀླྀྒྷྜྷྡྷྦྷྫྷྐྵaʾἀιἁιἂιἃιἄιἅιἆιἇιἠιἡιἢιἣιἤιἥιἦιἧιὠιὡιὢιὣιὤιὥιὦιὧιὰιαιάιᾶι ͂ὴιηιήιῆιὼιωιώιῶι ̳!! ̅???!!?rs°c°fnosmtmivix⫝̸ ゙ ゚よりコト333435참고주의363738394042444546474849503月4月5月6月7月8月9月hgevギガデシドルナノピコビルペソホンリラレムdaauovpciu平成昭和大正明治naμakakbmbgbpfnfμfμgmgμlmldlklfmnmμmpsnsμsmsnvμvkvpwnwμwmwkwkωmωbqcccddbgyhainkkktlnlxphprsrsvwbstմնմեմիվնմխיִײַשׁשׂאַאָאּבּגּדּהּוּזּטּיּךּכּלּמּנּסּףּפּצּקּרּתּוֹבֿכֿפֿאלئائەئوئۇئۆئۈئېئىئجئحئمئيبجبمبىبيتىتيثجثمثىثيخحضجضمطحظمغجفجفحفىفيقحقىقيكاكجكحكخكلكىكينخنىنيهجهىهييىذٰرٰىٰئرئزئنبزبنترتزتنثرثزثنمانرنزننيريزئخئهبهتهصخنههٰثهسهشهطىطيعىعيغىغيسىسيشىشيصىصيضىضيشخشرسرصرضراً ًـًـّ ْـْلآلألإ𝅗𝅥0,1,2,3,4,5,6,7,8,9,wzhvsdwcmcmddjほかココàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþāăąćĉċčďđēĕėęěĝğġģĥħĩīĭįĵķĺļľłńņňŋōŏőœŕŗřśŝşšţťŧũūŭůűųŵŷÿźżɓƃƅɔƈɖɗƌǝəɛƒɠɣɩɨƙɯɲɵơƣƥʀƨʃƭʈưʊʋƴƶʒƹƽǎǐǒǔǖǘǚǜǟǡǣǥǧǩǫǭǯǵƕƿǹǻǽǿȁȃȅȇȉȋȍȏȑȓȕȗșțȝȟƞȣȥȧȩȫȭȯȱȳⱥȼƚⱦɂƀʉʌɇɉɋɍɏɦɹɻʁʕͱͳʹͷ;ϳέίόύβγδεζθκλνξοπρστυφχψϊϋϗϙϛϝϟϡϣϥϧϩϫϭϯϸϻͻͼͽѐёђѓєѕіїјљњћќѝўџабвгдежзийклмнопрстуфхцчшщъыьэюяѡѣѥѧѩѫѭѯѱѳѵѷѹѻѽѿҁҋҍҏґғҕҗҙқҝҟҡңҥҧҩҫҭүұҳҵҷҹһҽҿӂӄӆӈӊӌӎӑӓӕӗәӛӝӟӡӣӥӧөӫӭӯӱӳӵӷӹӻӽӿԁԃԅԇԉԋԍԏԑԓԕԗԙԛԝԟԡԣԥԧԩԫԭԯաբգդզէըթժլծկհձղճյշոչպջռստրցփքօֆ་ⴧⴭნᏰᏱᏲᏳᏴᏵꙋɐɑᴂɜᴖᴗᴝᴥɒɕɟɡɥɪᵻʝɭᶅʟɱɰɳɴɸʂƫᴜʐʑḁḃḅḇḉḋḍḏḑḓḕḗḙḛḝḟḡḣḥḧḩḫḭḯḱḳḵḷḹḻḽḿṁṃṅṇṉṋṍṏṑṓṕṗṙṛṝṟṡṣṥṧṩṫṭṯṱṳṵṷṹṻṽṿẁẃẅẇẉẋẍẏẑẓẕạảấầẩẫậắằẳẵặẹẻẽếềểễệỉịọỏốồổỗộớờởỡợụủứừửữựỳỵỷỹỻỽỿἐἑἒἓἔἕἰἱἲἳἴἵἶἷὀὁὂὃὄὅὑὓὕὗᾰᾱὲΐῐῑὶΰῠῡὺῥ`ὸ‐+−∑〈〉ⰰⰱⰲⰳⰴⰵⰶⰷⰸⰹⰺⰻⰼⰽⰾⰿⱀⱁⱂⱃⱄⱅⱆⱇⱈⱉⱊⱋⱌⱍⱎⱏⱐⱑⱒⱓⱔⱕⱖⱗⱘⱙⱚⱛⱜⱝⱞⱡɫᵽɽⱨⱪⱬⱳⱶȿɀⲁⲃⲅⲇⲉⲋⲍⲏⲑⲓⲕⲗⲙⲛⲝⲟⲡⲣⲥⲧⲩⲫⲭⲯⲱⲳⲵⲷⲹⲻⲽⲿⳁⳃⳅⳇⳉⳋⳍⳏⳑⳓⳕⳗⳙⳛⳝⳟⳡⳣⳬⳮⳳⵡ母龟丨丶丿乙亅亠人儿入冂冖冫几凵刀力勹匕匚匸卜卩厂厶又口囗士夂夊夕女子宀寸小尢尸屮山巛工己巾干幺广廴廾弋弓彐彡彳心戈戶手支攴文斗斤方无曰欠止歹殳毋比毛氏气爪父爻爿片牙牛犬玄玉瓜瓦甘生用田疋疒癶白皮皿目矛矢石示禸禾穴立竹米糸缶网羊羽老而耒耳聿肉臣臼舌舛舟艮色艸虍虫血行衣襾見角言谷豆豕豸貝赤走足身車辛辰辵邑酉釆里長門阜隶隹雨靑非面革韋韭音頁風飛食首香馬骨高髟鬥鬯鬲鬼魚鳥鹵鹿麥麻黃黍黑黹黽鼎鼓鼠鼻齊齒龍龜龠.〒卄卅ᄁᆪᆬᆭᄄᆰᆱᆲᆳᆴᆵᄚᄈᄡᄊ짜ᅢᅣᅤᅥᅦᅧᅨᅩᅪᅫᅬᅭᅮᅯᅰᅱᅲᅳᅴᅵᄔᄕᇇᇈᇌᇎᇓᇗᇙᄜᇝᇟᄝᄞᄠᄢᄣᄧᄩᄫᄬᄭᄮᄯᄲᄶᅀᅇᅌᇱᇲᅗᅘᅙᆄᆅᆈᆑᆒᆔᆞᆡ上中下甲丙丁天地問幼箏우秘男適優印注項写左右医宗夜テヌモヨヰヱヲꙁꙃꙅꙇꙉꙍꙏꙑꙓꙕꙗꙙꙛꙝꙟꙡꙣꙥꙧꙩꙫꙭꚁꚃꚅꚇꚉꚋꚍꚏꚑꚓꚕꚗꚙꚛꜣꜥꜧꜩꜫꜭꜯꜳꜵꜷꜹꜻꜽꜿꝁꝃꝅꝇꝉꝋꝍꝏꝑꝓꝕꝗꝙꝛꝝꝟꝡꝣꝥꝧꝩꝫꝭꝯꝺꝼᵹꝿꞁꞃꞅꞇꞌꞑꞓꞗꞙꞛꞝꞟꞡꞣꞥꞧꞩɬʞʇꭓꞵꞷꬷꭒᎠᎡᎢᎣᎤᎥᎦᎧᎨᎩᎪᎫᎬᎭᎮᎯᎰᎱᎲᎳᎴᎵᎶᎷᎸᎹᎺᎻᎼᎽᎾᎿᏀᏁᏂᏃᏄᏅᏆᏇᏈᏉᏊᏋᏌᏍᏎᏏᏐᏑᏒᏓᏔᏕᏖᏗᏘᏙᏚᏛᏜᏝᏞᏟᏠᏡᏢᏣᏤᏥᏦᏧᏨᏩᏪᏫᏬᏭᏮᏯ豈更賈滑串句契喇奈懶癩羅蘿螺裸邏樂洛烙珞落酪駱亂卵欄爛蘭鸞嵐濫藍襤拉臘蠟廊朗浪狼郎來冷勞擄櫓爐盧蘆虜路露魯鷺碌祿綠菉錄論壟弄籠聾牢磊賂雷壘屢樓淚漏累縷陋勒肋凜凌稜綾菱陵讀拏諾丹寧怒率異北磻便復不泌數索參塞省葉說殺沈拾若掠略亮兩凉梁糧良諒量勵呂廬旅濾礪閭驪麗黎曆歷轢年憐戀撚漣煉璉秊練聯輦蓮連鍊列劣咽烈裂廉念捻殮簾獵令囹嶺怜玲瑩羚聆鈴零靈領例禮醴隸惡了僚寮尿料燎療蓼遼暈阮劉杻柳流溜琉留硫紐類戮陸倫崙淪輪律慄栗隆利吏履易李梨泥理痢罹裏裡離匿溺吝燐璘藺隣鱗麟林淋臨笠粒狀炙識什茶刺切度拓糖宅洞暴輻降廓兀嗀塚晴凞猪益礼神祥福靖精蘒諸逸都飯飼館鶴郞隷侮僧免勉勤卑喝嘆器塀墨層悔慨憎懲敏既暑梅海渚漢煮爫琢碑祉祈祐祖禍禎穀突節縉繁署者臭艹著褐視謁謹賓贈辶難響頻恵𤋮舘並况全侀充冀勇勺啕喙嗢墳奄奔婢嬨廒廙彩徭惘慎愈慠戴揄搜摒敖望杖滛滋瀞瞧爵犯瑱甆画瘝瘟盛直睊着磌窱类絛缾荒華蝹襁覆調請諭變輸遲醙鉶陼韛頋鬒𢡊𢡄𣏕㮝䀘䀹𥉉𥳐𧻓齃龎עםٱٻپڀٺٿٹڤڦڄڃچڇڍڌڎڈژڑکگڳڱںڻۀہھۓڭۋۅۉ、〖〗—–_{}【】《》「」『』[]#&*-<>\\$%@ءؤة\"'^|~⦅⦆・ゥャ¢£¬¦¥₩│←↑→↓■○𐐨𐐩𐐪𐐫𐐬𐐭𐐮𐐯𐐰𐐱𐐲𐐳𐐴𐐵𐐶𐐷𐐸𐐹𐐺𐐻𐐼𐐽𐐾𐐿𐑀𐑁𐑂𐑃𐑄𐑅𐑆𐑇𐑈𐑉𐑊𐑋𐑌𐑍𐑎𐑏𐓘𐓙𐓚𐓛𐓜𐓝𐓞𐓟𐓠𐓡𐓢𐓣𐓤𐓥𐓦𐓧𐓨𐓩𐓪𐓫𐓬𐓭𐓮𐓯𐓰𐓱𐓲𐓳𐓴𐓵𐓶𐓷𐓸𐓹𐓺𐓻𐳀𐳁𐳂𐳃𐳄𐳅𐳆𐳇𐳈𐳉𐳊𐳋𐳌𐳍𐳎𐳏𐳐𐳑𐳒𐳓𐳔𐳕𐳖𐳗𐳘𐳙𐳚𐳛𐳜𐳝𐳞𐳟𐳠𐳡𐳢𐳣𐳤𐳥𐳦𐳧𐳨𐳩𐳪𐳫𐳬𐳭𐳮𐳯𐳰𐳱𐳲𑣀𑣁𑣂𑣃𑣄𑣅𑣆𑣇𑣈𑣉𑣊𑣋𑣌𑣍𑣎𑣏𑣐𑣑𑣒𑣓𑣔𑣕𑣖𑣗𑣘𑣙𑣚𑣛𑣜𑣝𑣞𑣟ıȷ∇∂𞤢𞤣𞤤𞤥𞤦𞤧𞤨𞤩𞤪𞤫𞤬𞤭𞤮𞤯𞤰𞤱𞤲𞤳𞤴𞤵𞤶𞤷𞤸𞤹𞤺𞤻𞤼𞤽𞤾𞤿𞥀𞥁𞥂𞥃ٮڡٯ字双多解交映無前後再新初終販声吹演投捕遊指禁空合満申割営配得可丽丸乁𠄢你侻倂偺備像㒞𠘺兔兤具𠔜㒹內𠕋冗冤仌冬𩇟刃㓟刻剆剷㔕包匆卉博即卽卿𠨬灰及叟𠭣叫叱吆咞吸呈周咢哶唐啓啣善喫喳嗂圖圗噑噴壮城埴堍型堲報墬𡓤売壷夆夢奢𡚨𡛪姬娛娧姘婦㛮嬈嬾𡧈寃寘寳𡬘寿将㞁屠峀岍𡷤嵃𡷦嵮嵫嵼巡巢㠯巽帨帽幩㡢𢆃㡼庰庳庶𪎒𢌱舁弢㣇𣊸𦇚形彫㣣徚忍志忹悁㤺㤜𢛔惇慈慌慺憲憤憯懞戛扝抱拔捐𢬌挽拼捨掃揤𢯱搢揅掩㨮摩摾撝摷㩬敬𣀊旣書晉㬙㬈㫤冒冕最暜肭䏙朡杞杓𣏃㭉柺枅桒𣑭梎栟椔楂榣槪檨𣚣櫛㰘次𣢧歔㱎歲殟殻𣪍𡴋𣫺汎𣲼沿泍汧洖派浩浸涅𣴞洴港湮㴳滇𣻑淹潮𣽞𣾎濆瀹瀛㶖灊災灷炭𠔥煅𤉣熜爨牐𤘈犀犕𤜵𤠔獺王㺬玥㺸瑇瑜璅瓊㼛甤𤰶甾𤲒𢆟瘐𤾡𤾸𥁄㿼䀈𥃳𥃲𥄙𥄳眞真瞋䁆䂖𥐝硎䃣𥘦𥚚𥛅秫䄯穊穏𥥼𥪧䈂𥮫篆築䈧𥲀糒䊠糨糣紀𥾆絣䌁緇縂繅䌴𦈨𦉇䍙𦋙罺𦌾羕翺𦓚𦔣聠𦖨聰𣍟䏕育脃䐋脾媵𦞧𦞵𣎓𣎜舄辞䑫芑芋芝劳花芳芽苦𦬼茝荣莭茣莽菧荓菊菌菜𦰶𦵫𦳕䔫蓱蓳蔖𧏊蕤𦼬䕝䕡𦾱𧃒䕫虐虧虩蚩蚈蜎蛢蜨蝫螆蟡蠁䗹衠𧙧裗裞䘵裺㒻𧢮𧥦䚾䛇誠𧲨貫賁贛起𧼯𠠄跋趼跰𠣞軔𨗒𨗭邔郱鄑𨜮鄛鈸鋗鋘鉼鏹鐕𨯺開䦕閷𨵷䧦雃嶲霣𩅅𩈚䩮䩶韠𩐊䪲𩒖頩𩖶飢䬳餩馧駂駾䯎𩬰鱀鳽䳎䳭鵧𪃎䳸𪄅𪈎𪊑䵖黾鼅鼏鼖𪘀"; + + function mapChar(codePoint) { + if (codePoint >= 0x30000) { + // High planes are special cased. + if (codePoint >= 0xE0100 && codePoint <= 0xE01EF) + return 18874368; + return 0; + } + return blocks[blockIdxes[codePoint >> 4]][codePoint & 15]; + } + + return { + mapStr: mappingStr, + mapChar: mapChar + }; + })); + + },{}],177:[function(require,module,exports){ + (function(root, factory) { + /* istanbul ignore next */ + if (typeof define === 'function' && define.amd) { + define(['punycode', './idna-map'], function(punycode, idna_map) { + return factory(punycode, idna_map); + }); + } + else if (typeof exports === 'object') { + module.exports = factory(require('punycode'), require('./idna-map')); + } + else { + root.uts46 = factory(root.punycode, root.idna_map); + } + }(this, function(punycode, idna_map) { + + function mapLabel(label, useStd3ASCII, transitional) { + var mapped = []; + var chars = punycode.ucs2.decode(label); + for (var i = 0; i < chars.length; i++) { + var cp = chars[i]; + var ch = punycode.ucs2.encode([chars[i]]); + var composite = idna_map.mapChar(cp); + var flags = (composite >> 23); + var kind = (composite >> 21) & 3; + var index = (composite >> 5) & 0xffff; + var length = composite & 0x1f; + var value = idna_map.mapStr.substr(index, length); + if (kind === 0 || (useStd3ASCII && (flags & 1))) { + throw new Error("Illegal char " + ch); + } + else if (kind === 1) { + mapped.push(value); + } + else if (kind === 2) { + mapped.push(transitional ? value : ch); + } + /* istanbul ignore next */ + else if (kind === 3) { + mapped.push(ch); + } + } + + var newLabel = mapped.join("").normalize("NFC"); + return newLabel; + } + + function process(domain, transitional, useStd3ASCII) { + /* istanbul ignore if */ + if (useStd3ASCII === undefined) + useStd3ASCII = false; + var mappedIDNA = mapLabel(domain, useStd3ASCII, transitional); + + // Step 3. Break + var labels = mappedIDNA.split("."); + + // Step 4. Convert/Validate + labels = labels.map(function(label) { + if (label.startsWith("xn--")) { + label = punycode.decode(label.substring(4)); + validateLabel(label, useStd3ASCII, false); + } + else { + validateLabel(label, useStd3ASCII, transitional); + } + return label; + }); + + return labels.join("."); + } + + function validateLabel(label, useStd3ASCII, transitional) { + // 2. The label must not contain a U+002D HYPHEN-MINUS character in both the + // third position and fourth positions. + if (label[2] === '-' && label[3] === '-') + throw new Error("Failed to validate " + label); + + // 3. The label must neither begin nor end with a U+002D HYPHEN-MINUS + // character. + if (label.startsWith('-') || label.endsWith('-')) + throw new Error("Failed to validate " + label); + + // 4. The label must not contain a U+002E ( . ) FULL STOP. + // this should nerver happen as label is chunked internally by this character + /* istanbul ignore if */ + if (label.includes('.')) + throw new Error("Failed to validate " + label); + + if (mapLabel(label, useStd3ASCII, transitional) !== label) + throw new Error("Failed to validate " + label); + + // 5. The label must not begin with a combining mark, that is: + // General_Category=Mark. + var ch = label.codePointAt(0); + if (idna_map.mapChar(ch) & (0x2 << 23)) + throw new Error("Label contains illegal character: " + ch); + } + + function toAscii(domain, options) { + if (options === undefined) + options = {}; + var transitional = 'transitional' in options ? options.transitional : true; + var useStd3ASCII = 'useStd3ASCII' in options ? options.useStd3ASCII : false; + var verifyDnsLength = 'verifyDnsLength' in options ? options.verifyDnsLength : false; + var labels = process(domain, transitional, useStd3ASCII).split('.'); + var asciiLabels = labels.map(punycode.toASCII); + var asciiString = asciiLabels.join('.'); + var i; + if (verifyDnsLength) { + if (asciiString.length < 1 || asciiString.length > 253) { + throw new Error("DNS name has wrong length: " + asciiString); + } + for (i = 0; i < asciiLabels.length; i++) {//for .. of replacement + var label = asciiLabels[i]; + if (label.length < 1 || label.length > 63) + throw new Error("DNS label has wrong length: " + label); + } + } + return asciiString; + } + + function toUnicode(domain, options) { + if (options === undefined) + options = {}; + var useStd3ASCII = 'useStd3ASCII' in options ? options.useStd3ASCII : false; + return process(domain, false, useStd3ASCII); + } + + return { + toUnicode: toUnicode, + toAscii: toAscii, + }; + })); + + },{"./idna-map":176,"punycode":265}],178:[function(require,module,exports){ + exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 + } + + },{}],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) { + if (arr[i] === obj) return i; + } + return -1; + }; + },{}],180:[function(require,module,exports){ + if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } + + },{}],181:[function(require,module,exports){ + /*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ + + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + module.exports = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) + } + + function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) + } + + },{}],182:[function(require,module,exports){ + 'use strict'; + + var fnToStr = Function.prototype.toString; + + var constructorRegex = /^\s*class\b/; + var isES6ClassFn = function isES6ClassFunction(value) { + try { + var fnStr = fnToStr.call(value); + return constructorRegex.test(fnStr); + } catch (e) { + return false; // not a function + } + }; + + var tryFunctionObject = function tryFunctionToStr(value) { + try { + if (isES6ClassFn(value)) { return false; } + fnToStr.call(value); + return true; + } catch (e) { + return false; + } + }; + var toStr = Object.prototype.toString; + 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; } + if (typeof value === 'function' && !value.prototype) { return true; } + if (hasToStringTag) { return tryFunctionObject(value); } + if (isES6ClassFn(value)) { return false; } + 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]' || + (typeof fn === 'function' && string !== '[object RegExp]') || + (typeof window !== 'undefined' && + // IE8 and below + (fn === window.setTimeout || + fn === window.alert || + fn === window.confirm || + fn === window.prompt)) + }; + + },{}],185:[function(require,module,exports){ + /** + * Returns a `Boolean` on whether or not the a `String` starts with '0x' + * @param {String} str the string input value + * @return {Boolean} a boolean if it is or is not hex prefixed + * @throws if the str input is not a string + */ + module.exports = function isHexPrefixed(str) { + if (typeof str !== 'string') { + throw new Error("[is-hex-prefixed] value must be type 'string', is currently type " + (typeof str) + ", while checking isHexPrefixed."); + } + + return str.slice(0, 2) === '0x'; + } + + },{}],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 () { + var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + nextDonePromise = getNextDoneCallback(); + _context.next = 3; + return nextDonePromise; + + case 3: + return _context.abrupt('return', undefined); + + case 4: + case 'end': + return _context.stop(); + } + } + }, _callee, this); + })); + + return function getNextPromise() { + return _ref.apply(this, arguments); + }; + }(); + + var nextDonePromise = null; + var finishedPromise = asyncMiddleware(req, res, getNextPromise); + promiseToCallback(finishedPromise)(function (err) { + // async middleware ended + if (nextDonePromise) { + // next handler was called - complete nextHandler + promiseToCallback(nextDonePromise)(function (nextErr, nextHandlerSignalDone) { + // nextErr is only present if something went really wrong + // if an error is thrown after `await next()` it appears as `err` and not `nextErr` + if (nextErr) { + console.error(nextErr); + return end(nextErr); + } + nextHandlerSignalDone(err); + }); + } else { + // next handler was not called - complete middleware + end(err); + } + }); + + function getNextDoneCallback() { + return new Promise(function (resolve) { + next(function (cb) { + return resolve(cb); + }); + }); + } + }; + } + + },{"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) { + this._middleware.push(middleware); + } + }, { + key: 'handle', + value: function handle(req, cb) { + // batch request support + if (Array.isArray(req)) { + async.map(req, this._handle.bind(this), cb); + } else { + this._handle(req, cb); + } + } + + // + // Private + // + + }, { + key: '_handle', + value: function _handle(_req, cb) { + // shallow clone request object + var req = Object.assign({}, _req); + // create response obj + var res = { + id: req.id, + jsonrpc: req.jsonrpc + // process all middleware + };this._runMiddleware(req, res, function (err) { + // return response + cb(err, res); + }); + } + }, { + 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); + var message = 'JsonRpcEngine - response has no error or result for request:\n' + requestBody; + return cb(new Error(message)); + } + if (!isComplete) { + var _requestBody = JSON.stringify(req, null, 2); + var _message = 'JsonRpcEngine - nothing ended request:\n' + _requestBody; + return cb(new Error(_message)); + } + // 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) { + // for climbing back up the stack + 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); + cb(); + } + function end(err) { + if (err) return cb(err); + // mark as completed + isComplete = true; + cb(); + } + } + + // returns, indicating whether or not it ended + function completeRequest(err) { + if (err) { + // prepare error message + res.error = { + code: err.code || -32603, + message: err.stack + // return error-first and res with err + };return onDone(err, res); + } + var returnHandlers = allReturnHandlers.filter(Boolean).reverse(); + onDone(null, { isComplete: isComplete, returnHandlers: returnHandlers }); + } + } + + // climbs the stack calling return handlers + + }, { + key: '_runReturnHandlersUp', + value: function _runReturnHandlersUp(returnHandlers, cb) { + async.eachSeries(returnHandlers, function (handler, next) { + return handler(next); + }, 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 + escapee = { + '"': '"', + '\\': '\\', + '/': '/', + b: '\b', + f: '\f', + n: '\n', + r: '\r', + t: '\t' + }, + text, + + error = function (m) { + // Call error when something is wrong. + throw { + name: 'SyntaxError', + message: m, + at: at, + 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('-'); + } + while (ch >= '0' && ch <= '9') { + string += ch; + next(); + } + if (ch === '.') { + string += '.'; + while (next() && ch >= '0' && ch <= '9') { + string += ch; + } + } + if (ch === 'e' || ch === 'E') { + string += ch; + next(); + if (ch === '-' || ch === '+') { + string += ch; + next(); + } + while (ch >= '0' && ch <= '9') { + string += ch; + next(); + } + } + number = +string; + if (!isFinite(number)) { + error("Bad number"); + } else { + 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()) { + if (ch === '"') { + next(); + return string; + } else if (ch === '\\') { + next(); + if (ch === 'u') { + uffff = 0; + for (i = 0; i < 4; i += 1) { + hex = parseInt(next(), 16); + if (!isFinite(hex)) { + break; + } + uffff = uffff * 16 + hex; + } + string += String.fromCharCode(uffff); + } else if (typeof escapee[ch] === 'string') { + string += escapee[ch]; + } else { + break; + } + } else { + string += ch; + } + } + } + error("Bad string"); + }, + + white = function () { + + // Skip whitespace. + + while (ch && ch <= ' ') { + next(); + } + }, + + word = function () { + + // true, false, or null. + + switch (ch) { + case 't': + next('t'); + next('r'); + next('u'); + next('e'); + return true; + case 'f': + next('f'); + next('a'); + next('l'); + next('s'); + next('e'); + return false; + case 'n': + next('n'); + next('u'); + next('l'); + next('l'); + return null; + } + error("Unexpected '" + ch + "'"); + }, + + value, // Place holder for the value function. + + array = function () { + + // Parse an array value. + + var array = []; + + if (ch === '[') { + next('['); + white(); + if (ch === ']') { + next(']'); + return array; // empty array + } + while (ch) { + array.push(value()); + white(); + if (ch === ']') { + next(']'); + return array; + } + next(','); + white(); + } + } + error("Bad array"); + }, + + object = function () { + + // Parse an object value. + + var key, + object = {}; + + if (ch === '{') { + next('{'); + white(); + if (ch === '}') { + next('}'); + return object; // empty object + } + while (ch) { + key = string(); + white(); + next(':'); + if (Object.hasOwnProperty.call(object, key)) { + error('Duplicate key "' + key + '"'); + } + object[key] = value(); + white(); + if (ch === '}') { + next('}'); + return object; + } + next(','); + white(); + } + } + 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 '{': + return object(); + case '[': + return array(); + case '"': + return string(); + case '-': + return number(); + default: + 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 = ' '; + result = value(); + white(); + 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') { + for (k in value) { + if (Object.prototype.hasOwnProperty.call(value, k)) { + v = walk(value, k); + if (v !== undefined) { + value[k] = v; + } else { + delete value[k]; + } + } + } + } + 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, + gap, + indent, + meta = { // table of character substitutions + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + '"' : '\\"', + '\\': '\\\\' + }, + 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]; + return typeof c === 'string' ? c : + '\\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. + k, // The member key. + v, // The member value. + length, + 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 ? + '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : + '[' + partial.join(',') + ']'; + gap = mind; + return v; + } + + // If the replacer is an array, use it to select the members to be + // stringified. + if (rep && typeof rep === 'object') { + length = rep.length; + for (i = 0; i < length; i += 1) { + k = rep[i]; + if (typeof k === 'string') { + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } + else { + // Otherwise, iterate through all of the keys in the object. + for (k in value) { + if (Object.prototype.hasOwnProperty.call(value, k)) { + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } + + // 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(',') + '}'; + gap = mind; + 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') { + for (i = 0; i < space; i += 1) { + indent += ' '; + } + } + // If the space parameter is a string, it will be used as the indent string. + 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; + if (replacer && typeof replacer !== 'function' + && (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) { + case 'keccak224': return new Keccak(1152, 448, null, 224, options) + case 'keccak256': return new Keccak(1088, 512, null, 256, options) + case 'keccak384': return new Keccak(832, 768, null, 384, options) + case 'keccak512': return new Keccak(576, 1024, null, 512, options) + + case 'sha3-224': return new Keccak(1152, 448, 0x06, 224, options) + case 'sha3-256': return new Keccak(1088, 512, 0x06, 256, options) + case 'sha3-384': return new Keccak(832, 768, 0x06, 384, options) + case 'sha3-512': return new Keccak(576, 1024, 0x06, 512, options) + + case 'shake128': return new Shake(1344, 256, 0x1f, options) + case 'shake256': return new Shake(1088, 512, 0x1f, options) + + default: throw new Error('Invald algorithm: ' + algorithm) + } + } + } + + },{"./keccak":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 { + this.update(chunk, encoding) + } catch (err) { + error = err + } + + callback(error) + } + + Keccak.prototype._flush = function (callback) { + var error = null + try { + this.push(this.digest()) + } catch (err) { + error = err + } + + callback(error) + } + + Keccak.prototype.update = function (data, encoding) { + if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer') + if (this._finalized) throw new Error('Digest already called') + if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) + + this._state.absorb(data) + + return this + } + + Keccak.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true + + if (this._delimitedSuffix) this._state.absorbLastFewBits(this._delimitedSuffix) + var digest = this._state.squeeze(this._hashBitLength / 8) + if (encoding !== undefined) digest = digest.toString(encoding) + + this._resetState() + + return digest + } + + // remove result from memory + Keccak.prototype._resetState = function () { + this._state.initialize(this._rate, this._capacity) + return this + } + + // because sometimes we need hash right now and little later + Keccak.prototype._clone = function () { + var clone = new Keccak(this._rate, this._capacity, this._delimitedSuffix, this._hashBitLength, this._options) + this._state.copy(clone._state) + clone._finalized = this._finalized + + return clone + } + + return Keccak + } + + },{"inherits":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 { + this.update(chunk, encoding) + } catch (err) { + error = err + } + + callback(error) + } + + Shake.prototype._flush = function () {} + + Shake.prototype._read = function (size) { + this.push(this.squeeze(size)) + } + + Shake.prototype.update = function (data, encoding) { + if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer') + if (this._finalized) throw new Error('Squeeze already called') + if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) + + this._state.absorb(data) + + return this + } + + Shake.prototype.squeeze = function (dataByteLength, encoding) { + if (!this._finalized) { + this._finalized = true + this._state.absorbLastFewBits(this._delimitedSuffix) + } + + var data = this._state.squeeze(dataByteLength) + if (encoding !== undefined) data = data.toString(encoding) + + return data + } + + Shake.prototype._resetState = function () { + this._state.initialize(this._rate, this._capacity) + return this + } + + Shake.prototype._clone = function () { + var clone = new Shake(this._rate, this._capacity, this._delimitedSuffix, this._options) + this._state.copy(clone._state) + clone._finalized = this._finalized + + return clone + } + + return Shake + } + + },{"inherits":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 + var lo0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40] + var hi0 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41] + var lo1 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42] + var hi1 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43] + var lo2 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44] + var hi2 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45] + var lo3 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46] + var hi3 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47] + var lo4 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48] + var hi4 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49] + + var lo = lo4 ^ (lo1 << 1 | hi1 >>> 31) + var hi = hi4 ^ (hi1 << 1 | lo1 >>> 31) + var t1slo0 = s[0] ^ lo + var t1shi0 = s[1] ^ hi + var t1slo5 = s[10] ^ lo + var t1shi5 = s[11] ^ hi + var t1slo10 = s[20] ^ lo + var t1shi10 = s[21] ^ hi + var t1slo15 = s[30] ^ lo + var t1shi15 = s[31] ^ hi + var t1slo20 = s[40] ^ lo + var t1shi20 = s[41] ^ hi + lo = lo0 ^ (lo2 << 1 | hi2 >>> 31) + hi = hi0 ^ (hi2 << 1 | lo2 >>> 31) + var t1slo1 = s[2] ^ lo + var t1shi1 = s[3] ^ hi + var t1slo6 = s[12] ^ lo + var t1shi6 = s[13] ^ hi + var t1slo11 = s[22] ^ lo + var t1shi11 = s[23] ^ hi + var t1slo16 = s[32] ^ lo + var t1shi16 = s[33] ^ hi + var t1slo21 = s[42] ^ lo + var t1shi21 = s[43] ^ hi + lo = lo1 ^ (lo3 << 1 | hi3 >>> 31) + hi = hi1 ^ (hi3 << 1 | lo3 >>> 31) + var t1slo2 = s[4] ^ lo + var t1shi2 = s[5] ^ hi + var t1slo7 = s[14] ^ lo + var t1shi7 = s[15] ^ hi + var t1slo12 = s[24] ^ lo + var t1shi12 = s[25] ^ hi + var t1slo17 = s[34] ^ lo + var t1shi17 = s[35] ^ hi + var t1slo22 = s[44] ^ lo + var t1shi22 = s[45] ^ hi + lo = lo2 ^ (lo4 << 1 | hi4 >>> 31) + hi = hi2 ^ (hi4 << 1 | lo4 >>> 31) + var t1slo3 = s[6] ^ lo + var t1shi3 = s[7] ^ hi + var t1slo8 = s[16] ^ lo + var t1shi8 = s[17] ^ hi + var t1slo13 = s[26] ^ lo + var t1shi13 = s[27] ^ hi + var t1slo18 = s[36] ^ lo + var t1shi18 = s[37] ^ hi + var t1slo23 = s[46] ^ lo + var t1shi23 = s[47] ^ hi + lo = lo3 ^ (lo0 << 1 | hi0 >>> 31) + hi = hi3 ^ (hi0 << 1 | lo0 >>> 31) + var t1slo4 = s[8] ^ lo + var t1shi4 = s[9] ^ hi + var t1slo9 = s[18] ^ lo + var t1shi9 = s[19] ^ hi + var t1slo14 = s[28] ^ lo + var t1shi14 = s[29] ^ hi + var t1slo19 = s[38] ^ lo + var t1shi19 = s[39] ^ hi + var t1slo24 = s[48] ^ lo + var t1shi24 = s[49] ^ hi + + // rho & pi + var t2slo0 = t1slo0 + var t2shi0 = t1shi0 + var t2slo16 = (t1shi5 << 4 | t1slo5 >>> 28) + var t2shi16 = (t1slo5 << 4 | t1shi5 >>> 28) + var t2slo7 = (t1slo10 << 3 | t1shi10 >>> 29) + var t2shi7 = (t1shi10 << 3 | t1slo10 >>> 29) + var t2slo23 = (t1shi15 << 9 | t1slo15 >>> 23) + var t2shi23 = (t1slo15 << 9 | t1shi15 >>> 23) + var t2slo14 = (t1slo20 << 18 | t1shi20 >>> 14) + var t2shi14 = (t1shi20 << 18 | t1slo20 >>> 14) + var t2slo10 = (t1slo1 << 1 | t1shi1 >>> 31) + var t2shi10 = (t1shi1 << 1 | t1slo1 >>> 31) + var t2slo1 = (t1shi6 << 12 | t1slo6 >>> 20) + var t2shi1 = (t1slo6 << 12 | t1shi6 >>> 20) + var t2slo17 = (t1slo11 << 10 | t1shi11 >>> 22) + var t2shi17 = (t1shi11 << 10 | t1slo11 >>> 22) + var t2slo8 = (t1shi16 << 13 | t1slo16 >>> 19) + var t2shi8 = (t1slo16 << 13 | t1shi16 >>> 19) + var t2slo24 = (t1slo21 << 2 | t1shi21 >>> 30) + var t2shi24 = (t1shi21 << 2 | t1slo21 >>> 30) + var t2slo20 = (t1shi2 << 30 | t1slo2 >>> 2) + var t2shi20 = (t1slo2 << 30 | t1shi2 >>> 2) + var t2slo11 = (t1slo7 << 6 | t1shi7 >>> 26) + var t2shi11 = (t1shi7 << 6 | t1slo7 >>> 26) + var t2slo2 = (t1shi12 << 11 | t1slo12 >>> 21) + var t2shi2 = (t1slo12 << 11 | t1shi12 >>> 21) + var t2slo18 = (t1slo17 << 15 | t1shi17 >>> 17) + var t2shi18 = (t1shi17 << 15 | t1slo17 >>> 17) + var t2slo9 = (t1shi22 << 29 | t1slo22 >>> 3) + var t2shi9 = (t1slo22 << 29 | t1shi22 >>> 3) + var t2slo5 = (t1slo3 << 28 | t1shi3 >>> 4) + var t2shi5 = (t1shi3 << 28 | t1slo3 >>> 4) + var t2slo21 = (t1shi8 << 23 | t1slo8 >>> 9) + var t2shi21 = (t1slo8 << 23 | t1shi8 >>> 9) + var t2slo12 = (t1slo13 << 25 | t1shi13 >>> 7) + var t2shi12 = (t1shi13 << 25 | t1slo13 >>> 7) + var t2slo3 = (t1slo18 << 21 | t1shi18 >>> 11) + var t2shi3 = (t1shi18 << 21 | t1slo18 >>> 11) + var t2slo19 = (t1shi23 << 24 | t1slo23 >>> 8) + var t2shi19 = (t1slo23 << 24 | t1shi23 >>> 8) + var t2slo15 = (t1slo4 << 27 | t1shi4 >>> 5) + var t2shi15 = (t1shi4 << 27 | t1slo4 >>> 5) + var t2slo6 = (t1slo9 << 20 | t1shi9 >>> 12) + var t2shi6 = (t1shi9 << 20 | t1slo9 >>> 12) + var t2slo22 = (t1shi14 << 7 | t1slo14 >>> 25) + var t2shi22 = (t1slo14 << 7 | t1shi14 >>> 25) + var t2slo13 = (t1slo19 << 8 | t1shi19 >>> 24) + var t2shi13 = (t1shi19 << 8 | t1slo19 >>> 24) + var t2slo4 = (t1slo24 << 14 | t1shi24 >>> 18) + var t2shi4 = (t1shi24 << 14 | t1slo24 >>> 18) + + // chi + s[0] = t2slo0 ^ (~t2slo1 & t2slo2) + s[1] = t2shi0 ^ (~t2shi1 & t2shi2) + s[10] = t2slo5 ^ (~t2slo6 & t2slo7) + s[11] = t2shi5 ^ (~t2shi6 & t2shi7) + s[20] = t2slo10 ^ (~t2slo11 & t2slo12) + s[21] = t2shi10 ^ (~t2shi11 & t2shi12) + s[30] = t2slo15 ^ (~t2slo16 & t2slo17) + s[31] = t2shi15 ^ (~t2shi16 & t2shi17) + s[40] = t2slo20 ^ (~t2slo21 & t2slo22) + s[41] = t2shi20 ^ (~t2shi21 & t2shi22) + s[2] = t2slo1 ^ (~t2slo2 & t2slo3) + s[3] = t2shi1 ^ (~t2shi2 & t2shi3) + s[12] = t2slo6 ^ (~t2slo7 & t2slo8) + s[13] = t2shi6 ^ (~t2shi7 & t2shi8) + s[22] = t2slo11 ^ (~t2slo12 & t2slo13) + s[23] = t2shi11 ^ (~t2shi12 & t2shi13) + s[32] = t2slo16 ^ (~t2slo17 & t2slo18) + s[33] = t2shi16 ^ (~t2shi17 & t2shi18) + s[42] = t2slo21 ^ (~t2slo22 & t2slo23) + s[43] = t2shi21 ^ (~t2shi22 & t2shi23) + s[4] = t2slo2 ^ (~t2slo3 & t2slo4) + s[5] = t2shi2 ^ (~t2shi3 & t2shi4) + s[14] = t2slo7 ^ (~t2slo8 & t2slo9) + s[15] = t2shi7 ^ (~t2shi8 & t2shi9) + s[24] = t2slo12 ^ (~t2slo13 & t2slo14) + s[25] = t2shi12 ^ (~t2shi13 & t2shi14) + s[34] = t2slo17 ^ (~t2slo18 & t2slo19) + s[35] = t2shi17 ^ (~t2shi18 & t2shi19) + s[44] = t2slo22 ^ (~t2slo23 & t2slo24) + s[45] = t2shi22 ^ (~t2shi23 & t2shi24) + s[6] = t2slo3 ^ (~t2slo4 & t2slo0) + s[7] = t2shi3 ^ (~t2shi4 & t2shi0) + s[16] = t2slo8 ^ (~t2slo9 & t2slo5) + s[17] = t2shi8 ^ (~t2shi9 & t2shi5) + s[26] = t2slo13 ^ (~t2slo14 & t2slo10) + s[27] = t2shi13 ^ (~t2shi14 & t2shi10) + s[36] = t2slo18 ^ (~t2slo19 & t2slo15) + s[37] = t2shi18 ^ (~t2shi19 & t2shi15) + s[46] = t2slo23 ^ (~t2slo24 & t2slo20) + s[47] = t2shi23 ^ (~t2shi24 & t2shi20) + s[8] = t2slo4 ^ (~t2slo0 & t2slo1) + s[9] = t2shi4 ^ (~t2shi0 & t2shi1) + s[18] = t2slo9 ^ (~t2slo5 & t2slo6) + s[19] = t2shi9 ^ (~t2shi5 & t2shi6) + s[28] = t2slo14 ^ (~t2slo10 & t2slo11) + s[29] = t2shi14 ^ (~t2shi10 & t2shi11) + s[38] = t2slo19 ^ (~t2slo15 & t2slo16) + s[39] = t2shi19 ^ (~t2shi15 & t2shi16) + s[48] = t2slo24 ^ (~t2slo20 & t2slo21) + s[49] = t2shi24 ^ (~t2shi20 & t2shi21) + + // iota + s[0] ^= P1600_ROUND_CONSTANTS[round * 2] + s[1] ^= P1600_ROUND_CONSTANTS[round * 2 + 1] + } + } + + },{}],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 = [ + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0 + ] + + this.blockSize = null + this.count = 0 + this.squeezing = false + } + + Keccak.prototype.initialize = function (rate, capacity) { + for (var i = 0; i < 50; ++i) this.state[i] = 0 + this.blockSize = rate / 8 + this.count = 0 + this.squeezing = false + } + + Keccak.prototype.absorb = function (data) { + for (var i = 0; i < data.length; ++i) { + this.state[~~(this.count / 4)] ^= data[i] << (8 * (this.count % 4)) + this.count += 1 + if (this.count === this.blockSize) { + keccakState.p1600(this.state) + this.count = 0 + } + } + } + + Keccak.prototype.absorbLastFewBits = function (bits) { + this.state[~~(this.count / 4)] ^= bits << (8 * (this.count % 4)) + if ((bits & 0x80) !== 0 && this.count === (this.blockSize - 1)) keccakState.p1600(this.state) + this.state[~~((this.blockSize - 1) / 4)] ^= 0x80 << (8 * ((this.blockSize - 1) % 4)) + keccakState.p1600(this.state) + this.count = 0 + this.squeezing = true + } + + Keccak.prototype.squeeze = function (length) { + if (!this.squeezing) this.absorbLastFewBits(0x01) + + var output = Buffer.alloc(length) + for (var i = 0; i < length; ++i) { + output[i] = (this.state[~~(this.count / 4)] >>> (8 * (this.count % 4))) & 0xff + this.count += 1 + if (this.count === this.blockSize) { + keccakState.p1600(this.state) + this.count = 0 + } + } + + return output + } + + Keccak.prototype.copy = function (dest) { + for (var i = 0; i < 50; ++i) dest.state[i] = this.state[i] + dest.blockSize = this.blockSize + dest.count = this.count + dest.squeezing = this.squeezing + } + + module.exports = Keccak + + },{"./keccak-state-unroll":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'), + isArray = require('./isArray'), + 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`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + 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 && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + 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. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? 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`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + 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]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + weakMapTag = '[object WeakMap]'; + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag] = + typedArrayTags[objectTag] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = false; + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + 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. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; + } + + module.exports = baseKeys; + + },{"./_isPrototype":212,"./_nativeKeys":213}],207:[function(require,module,exports){ + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + 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. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + 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. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ + 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) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + 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. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (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. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + 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`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + 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. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + 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`. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new constant function. + * @example + * + * var objects = _.times(2, _.constant({ 'a': 1 })); + * + * console.log(objects); + * // => [{ 'a': 1 }, { 'a': 1 }] + * + * console.log(objects[0] === objects[1]); + * // => true + */ + function constant(value) { + return function() { + 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. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + 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. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => 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 + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + 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. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => 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. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + 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. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + 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 + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + 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` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + 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. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => 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`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + 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`. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Util + * @example + * + * _.times(2, _.noop); + * // => [undefined, undefined] + */ + function noop() { + // No operation performed. + } + + module.exports = noop; + + },{}],230:[function(require,module,exports){ + /** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ + 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) + b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22) + a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7) + d = fnF(d, a, b, c, M[5], 0x4787c62a, 12) + c = fnF(c, d, a, b, M[6], 0xa8304613, 17) + b = fnF(b, c, d, a, M[7], 0xfd469501, 22) + a = fnF(a, b, c, d, M[8], 0x698098d8, 7) + d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12) + c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17) + b = fnF(b, c, d, a, M[11], 0x895cd7be, 22) + a = fnF(a, b, c, d, M[12], 0x6b901122, 7) + d = fnF(d, a, b, c, M[13], 0xfd987193, 12) + c = fnF(c, d, a, b, M[14], 0xa679438e, 17) + b = fnF(b, c, d, a, M[15], 0x49b40821, 22) + + a = fnG(a, b, c, d, M[1], 0xf61e2562, 5) + d = fnG(d, a, b, c, M[6], 0xc040b340, 9) + c = fnG(c, d, a, b, M[11], 0x265e5a51, 14) + b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20) + a = fnG(a, b, c, d, M[5], 0xd62f105d, 5) + d = fnG(d, a, b, c, M[10], 0x02441453, 9) + c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14) + b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20) + a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5) + d = fnG(d, a, b, c, M[14], 0xc33707d6, 9) + c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14) + b = fnG(b, c, d, a, M[8], 0x455a14ed, 20) + a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5) + d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9) + c = fnG(c, d, a, b, M[7], 0x676f02d9, 14) + b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20) + + a = fnH(a, b, c, d, M[5], 0xfffa3942, 4) + d = fnH(d, a, b, c, M[8], 0x8771f681, 11) + c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16) + b = fnH(b, c, d, a, M[14], 0xfde5380c, 23) + a = fnH(a, b, c, d, M[1], 0xa4beea44, 4) + d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11) + c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16) + b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23) + a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4) + d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11) + c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16) + b = fnH(b, c, d, a, M[6], 0x04881d05, 23) + a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4) + d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11) + c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16) + b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23) + + a = fnI(a, b, c, d, M[0], 0xf4292244, 6) + d = fnI(d, a, b, c, M[7], 0x432aff97, 10) + c = fnI(c, d, a, b, M[14], 0xab9423a7, 15) + b = fnI(b, c, d, a, M[5], 0xfc93a039, 21) + a = fnI(a, b, c, d, M[12], 0x655b59c3, 6) + d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10) + c = fnI(c, d, a, b, M[10], 0xffeff47d, 15) + b = fnI(b, c, d, a, M[1], 0x85845dd1, 21) + a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6) + d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10) + c = fnI(c, d, a, b, M[6], 0xa3014314, 15) + b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21) + a = fnI(a, b, c, d, M[4], 0xf7537e82, 6) + d = fnI(d, a, b, c, M[11], 0xbd3af235, 10) + c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15) + b = fnI(b, c, d, a, M[9], 0xeb86d391, 21) + + this._a = (this._a + a) | 0 + this._b = (this._b + b) | 0 + this._c = (this._c + c) | 0 + this._d = (this._d + d) | 0 + } + + MD5.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80 + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64) + this._update() + this._blockOffset = 0 + } + + this._block.fill(0, this._blockOffset, 56) + this._block.writeUInt32LE(this._length[0], 56) + this._block.writeUInt32LE(this._length[1], 60) + this._update() + + // produce result + var buffer = new Buffer(16) + buffer.writeInt32LE(this._a, 0) + buffer.writeInt32LE(this._b, 4) + buffer.writeInt32LE(this._c, 8) + buffer.writeInt32LE(this._d, 12) + return buffer + } + + function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) + } + + function fnF (a, b, c, d, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 + } + + function fnG (a, b, c, d, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 + } + + function fnH (a, b, c, d, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 + } + + function fnI (a, b, c, d, m, k, s) { + return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 + } + + module.exports = MD5 + + }).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 { + this.update(chunk, encoding) + } catch (err) { + error = err + } + + callback(error) + } + + HashBase.prototype._flush = function (callback) { + var error = null + try { + this.push(this.digest()) + } catch (err) { + error = err + } + + callback(error) + } + + HashBase.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data') + if (this._finalized) throw new Error('Digest already called') + if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) + + // consume data + var block = this._block + var offset = 0 + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] + this._update() + this._blockOffset = 0 + } + while (offset < data.length) block[this._blockOffset++] = data[offset++] + + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry + carry = (this._length[j] / 0x0100000000) | 0 + if (carry > 0) this._length[j] -= 0x0100000000 * carry + } + + return this + } + + HashBase.prototype._update = function () { + throw new Error('_update is not implemented') + } + + HashBase.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true + + var digest = this._digest() + if (encoding !== undefined) digest = digest.toString(encoding) + + // reset state + this._block.fill(0) + this._blockOffset = 0 + for (var i = 0; i < 4; ++i) this._length[i] = 0 + + return digest + } + + HashBase.prototype._digest = function () { + throw new Error('_digest is not implemented') + } + + module.exports = HashBase + + },{"inherits":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(); + if (!msg) + return []; + var res = []; + if (typeof msg !== 'string') { + for (var i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + return res; + } + if (enc === 'hex') { + msg = msg.replace(/[^a-z0-9]+/ig, ''); + if (msg.length % 2 !== 0) + msg = '0' + msg; + for (var i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } else { + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + var hi = c >> 8; + var lo = c & 0xff; + if (hi) + res.push(hi, lo); + else + res.push(lo); + } + } + return res; + } + utils.toArray = toArray; + + function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; + } + utils.zero2 = zero2; + + function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; + } + utils.toHex = toHex; + + utils.encode = function encode(arr, enc) { + if (enc === 'hex') + return toHex(arr); + else + return arr; + }; + + },{}],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 + * @return {Object} `output` BN object of the number + * @throws if the argument is not an array, object that isn't a bignumber, not a string number or number + */ + module.exports = function numberToBN(arg) { + if (typeof arg === 'string' || typeof arg === 'number') { + var multiplier = new BN(1); // eslint-disable-line + var formattedString = String(arg).toLowerCase().trim(); + var isHexPrefixed = formattedString.substr(0, 2) === '0x' || formattedString.substr(0, 3) === '-0x'; + var stringArg = stripHexPrefix(formattedString); // eslint-disable-line + if (stringArg.substr(0, 1) === '-') { + stringArg = stripHexPrefix(stringArg.slice(1)); + 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); + } + } else if (typeof arg === 'object' && arg.toString && (!arg.pop && !arg.push)) { + if (arg.toString(10).match(/^-?[0-9]+$/) && (arg.mul || arg.dividedToIntegerBy)) { + 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++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + '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++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + 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 + PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + */ + + /** + * 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"); + * // 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) + + 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; + + 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)]; + } + + return varArgs(function(startParams){ + + return foldR(next, startParams, fnsList)[0]; + }); + }); + + /** + * A more optimised version of compose that takes exactly two functions + * @param f1 + * @param f2 + */ + function compose2(f1, f2){ + return function(){ + 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 + * 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]) + * + * @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 + * 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 + * 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; + + + if( numberOfFixedArguments == 0 ) { + // 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 + + // 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); + + return function(){ + + for (var i = 0; i < numberOfFixedArguments; i++) { + argsHolder[i] = arguments[i]; + } + + argsHolder[numberOfFixedArguments] = + slice.call(arguments, numberOfFixedArguments); + + 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){ + return function(a, b){ + 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 + */ + function functor(val){ + return function(){ + return val; + } + } + + /** + * 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'), + 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 + * is not an object. + */ + function hasAllProperties(fieldList, o) { + + return (o instanceof Object) + && + 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 + performance and this slows oboe-mark down by + ~25%. Under theoretical future JS engines that freeze more + efficiently (possibly even use immutability to + 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 + * + * asList([a,b,c]) + * + * is equivalent to: + * + * cons(a, cons(b, cons(c, emptyList))) + **/ + function arrayAsList(inputArray){ + + return reverseList( + inputArray.reduce( + flip(cons), + emptyList + ) + ); + } + + /** + * A varargs version of arrayAsList. Works a bit like list + * in LISP. + * + * 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 + */ + 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 + */ + function foldR(fn, startValue, 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 + */ + function foldR1(fn, 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 + */ + function without(list, test, removedFn) { + + return withoutInner(list, removedFn || noop); + + function withoutInner(subList, removedFn) { + 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 + */ + function all(fn, 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 + * it doesn't return anything. Hence, this is only really useful if the + * functions being called have side-effects. + */ + function applyEach(fnList, args) { + + if( fnList ) { + head(fnList).apply(null, args); + + applyEach(tail(fnList), args); + } + } + + /** + * Reverse the order of a 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 + 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 + */ + + function clarinet(eventBus) { + "use strict"; + + 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 + , OPEN_OBJECT = _n++ // { + , CLOSE_OBJECT = _n++ // } + , OPEN_ARRAY = _n++ // [ + , CLOSE_ARRAY = _n++ // ] + , STRING = _n++ // "" + , OPEN_KEY = _n++ // , "a" + , CLOSE_KEY = _n++ // : + , TRUE = _n++ // r + , TRUE2 = _n++ // u + , TRUE3 = _n++ // e + , FALSE = _n++ // a + , FALSE2 = _n++ // l + , FALSE3 = _n++ // s + , FALSE4 = _n++ // e + , NULL = _n++ // u + , NULL2 = _n++ // l + , NULL3 = _n++ // l + , NUMBER_DECIMAL_POINT = _n++ // . + , NUMBER_DIGIT = _n // [0-9] + + // setup initial parser values + , bufferCheckPosition = MAX_BUFFER_LENGTH + , latestError + , c + , p + , textNode = undefined + , numberNode = "" + , slashed = false + , closed = false + , state = BEGIN + , stack = [] + , unicodeS = null + , unicodeI = 0 + , depth = 0 + , position = 0 + , 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); + } + if (numberNode.length > MAX_BUFFER_LENGTH) { + 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 + valid json, ie if not all arrays, objects and Strings closed properly */ + 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]; + + 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; + if(state === OPEN_KEY) stack.push(CLOSE_KEY); + else { + if(c === '}') { + emitValueOpen({}); + emitValueClose(); + state = stack.pop() || VALUE; + continue; + } else stack.push(CLOSE_OBJECT); + } + if(c === '"') + state = STRING; + 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 + emitValueOpen({}); + emitSaxKey(textNode); + textNode = undefined; + } + depth++; + } else { + if (textNode !== undefined) { + emitSaxKey(textNode); + textNode = undefined; + } + } + state = VALUE; + } else if (c==='}') { + if (textNode !== undefined) { + emitValueOpen(textNode); + emitValueClose(); + textNode = undefined; + } + emitValueClose(); + depth--; + state = stack.pop() || VALUE; + } else if(c===',') { + if(state === CLOSE_OBJECT) + stack.push(CLOSE_OBJECT); + if (textNode !== undefined) { + emitValueOpen(textNode); + emitValueClose(); + textNode = undefined; + } + state = OPEN_KEY; + } 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++; + state = VALUE; + if(c === ']') { + emitValueClose(); + depth--; + state = stack.pop() || VALUE; + continue; + } else { + stack.push(CLOSE_ARRAY); + } + } + if(c === '"') state = STRING; + else if(c === '{') state = OPEN_OBJECT; + else if(c === '[') state = OPEN_ARRAY; + else if(c === 't') state = TRUE; + else if(c === 'f') state = FALSE; + else if(c === 'n') state = NULL; + else if(c === '-') { // keep and continue + numberNode += c; + } else if(c==='0') { + numberNode += c; + state = NUMBER_DIGIT; + } else if('123456789'.indexOf(c) !== -1) { + numberNode += c; + state = NUMBER_DIGIT; + } else + return emitError("Bad value"); + continue; + + case CLOSE_ARRAY: + if(c===',') { + stack.push(CLOSE_ARRAY); + if (textNode !== undefined) { + emitValueOpen(textNode); + emitValueClose(); + textNode = undefined; + } + state = VALUE; + } else if (c===']') { + if (textNode !== undefined) { + emitValueOpen(textNode); + emitValueClose(); + textNode = undefined; + } + emitValueClose(); + depth--; + state = stack.pop() || VALUE; + } else if (whitespace(c)) + continue; + 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; + c = chunk.charAt(i++); + if (unicodeI === 4) { + // TODO this might be slow? well, probably not used too often anyway + textNode += String.fromCharCode(parseInt(unicodeS, 16)); + unicodeI = 0; + starti = i-1; + } else { + unicodeI++; + } + // we can just break here: no stuff we skipped that still has to be sliced out or so + if (!c) break STRING_BIGLOOP; + } + if (c === '"' && !slashed) { + state = stack.pop() || VALUE; + textNode += chunk.substring(starti, i-1); + break; + } + if (c === '\\' && !slashed) { + slashed = true; + textNode += chunk.substring(starti, i-1); + c = chunk.charAt(i++); + if (!c) break; + } + if (slashed) { + slashed = false; + if (c === 'n') { textNode += '\n'; } + else if (c === 'r') { textNode += '\r'; } + else if (c === 't') { textNode += '\t'; } + else if (c === 'f') { textNode += '\f'; } + else if (c === 'b') { textNode += '\b'; } + else if (c === 'u') { + // \uxxxx. meh! + unicodeI = 1; + unicodeS = ''; + } else { + textNode += c; + } + c = chunk.charAt(i++); + starti = i-1; + if (!c) break; + else continue; + } + + stringTokenPattern.lastIndex = i; + var reResult = stringTokenPattern.exec(chunk); + if (!reResult) { + i = chunk.length+1; + textNode += chunk.substring(starti, i-1); + break; + } + i = reResult.index+1; + c = chunk.charAt(reResult.index); + if (!c) { + textNode += chunk.substring(starti, i-1); + break; + } + } + 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') { + emitValueOpen(true); + emitValueClose(); + state = stack.pop() || VALUE; + } 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') { + emitValueOpen(false); + emitValueClose(); + state = stack.pop() || VALUE; + } 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 + return emitError('Invalid null started with nul'+ c); + continue; + + case NUMBER_DECIMAL_POINT: + if(c==='.') { + numberNode += c; + state = NUMBER_DIGIT; + } else + return emitError('Leading zero not followed by .'); + continue; + + case NUMBER_DIGIT: + if('0123456789'.indexOf(c) !== -1) numberNode += c; + else if (c==='.') { + if(numberNode.indexOf('.')!==-1) + return emitError('Invalid number has two dots'); + numberNode += c; + } else if (c==='e' || c==='E') { + if(numberNode.indexOf('e')!==-1 || + numberNode.indexOf('E')!==-1 ) + return emitError('Invalid number has two exponential'); + numberNode += c; + } else if (c==="+" || c==="-") { + if(!(p==='e' || p==='E')) + return emitError('Invalid symbol in number'); + numberNode += c; + } else { + if (numberNode) { + emitValueOpen(parseFloat(numberNode)); + emitValueClose(); + numberNode = ""; + } + i--; // go back one + state = stack.pop() || VALUE; + } + continue; + + default: + return emitError("Unknown state: " + state); + } + } + if (position >= bufferCheckPosition) + 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: + * http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders-method + * This method parses that string into a user-friendly key/value pair object. + */ + 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)] + = 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 + * origin of the url that we want to ajax in + */ + function isCrossOrigin(pageLocation, ajaxHost) { + + /* + * NB: defaultPort only knows http and https. + * Returns undefined otherwise. + */ + 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 + // if such is given + // + // 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 + * event whenever a new part of the response is available. + * + * 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 + * but for tests a stub can be provided instead. + * @param {String} method one of 'GET' 'POST' 'PUT' 'PATCH' 'DELETE' + * @param {String} url the url to make a request to + * @param {String|Null} data some content to be sent with the request. + * Only valid if method is POST or PUT. + * @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 + oboeBus( ABORTING ).on( function(){ + + // 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 + 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 + // the next readyState if it fails + try{ + stillToSendStartEvent && oboeBus( HTTP_START ).emit( + xhr.status, + parseResponseHeaders(xhr.getAllResponseHeaders()) ); + 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 + // progress event for each part of the response + handleProgress(); + + oboeBus(STREAM_END).emit(); + } else { + + emitFail( errorReport( + 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. + 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 + * 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 + * 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 + componentRegexes.unshift(/^/); + + return regexDescriptor( + RegExp( + componentRegexes.map(attr('source')).join('') + ) + ); + }) + + , possiblyCapturing = /(\$?)/ + , namedNode = /([\w-_]+|\*)/ + , namePlaceholder = /()/ + , nodeInArrayNotation = /\["([^"]+)"\]/ + , numberedNodeInArrayNotation = /\[(\d+|\*)\]/ + , fieldList = /{([\w ]*?)}/ + , optionalFieldList = /(?:{([\w ]*?)})?/ + + + // foo or * + , jsonPathNamedNodeInObjectNotation = jsonPathClause( + possiblyCapturing, + namedNode, + optionalFieldList + ) + + // ["foo"] + , jsonPathNamedNodeInArrayNotation = jsonPathClause( + possiblyCapturing, + nodeInArrayNotation, + optionalFieldList + ) + + // [2] or [*] + , jsonPathNumberedNodeInArrayNotation = jsonPathClause( + possiblyCapturing, + numberedNodeInArrayNotation, + optionalFieldList + ) + + // {a b c} + , jsonPathPureDuckTyping = jsonPathClause( + possiblyCapturing, + namePlaceholder, + fieldList + ) + + // .. + , jsonPathDoubleDot = jsonPathClause(/\.\./) + + // . + , jsonPathDot = jsonPathClause(/\./) + + // ! + , jsonPathBang = jsonPathClause( + possiblyCapturing, + /!/ + ) + + // nada! + , emptyString = jsonPathClause(/$/) + + ; + + + /* We export only a single function. When called, this function injects + into another function the descriptors from above. + */ + return function (fn){ + return fn( + lazyUnion( + jsonPathNamedNodeInObjectNotation + , jsonPathNamedNodeInArrayNotation + , jsonPathNumberedNodeInArrayNotation + , jsonPathPureDuckTyping + ) + , jsonPathDoubleDot + , jsonPathDot + , jsonPathBang + , 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 + * 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. + **/ + var ROOT_PATH = {}; + + + /** + * 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 + numbers. */ + + var parentNode = nodeOf( head( possiblyInconsistentAscent)); + + return isOfType( Array, parentNode) + ? + keyFound( possiblyInconsistentAscent, + len(parentNode), + newDeepestNode + ) + : + // nothing needed, return unchanged + possiblyInconsistentAscent + ; + } + + function nodeOpened( ascent, newDeepestNode ) { + + if( !ascent ) { + // we discovered the root node, + emitRootOpened( newDeepestNode); + + return keyFound( ascent, ROOT_PATH, newDeepestNode); + } + + // we discovered a non-root node + + var arrayConsistentAscent = arrayIndicesAreKeys( ascent, newDeepestNode), + ancestorBranches = tail( arrayConsistentAscent), + previouslyUnmappedName = keyOf( head( arrayConsistentAscent)); + + appendBuiltContent( + ancestorBranches, + 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 + * 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 + * 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: + appendBuiltContent( ascent, 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: + 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 + * 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 + * arguments and no variables are reassigned. + */ + // the call to jsonPathSyntax injects the token syntaxes that are needed + // inside the compiler + 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] + */ + function nameClause(previousExpr, detection ) { + + var name = detection[NAME_INDEX], + + 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 + + var hasAllrequiredFields = partialComplete( + hasAllProperties, + arrayAsList(fieldListStr.split(/\W+/)) + ), + + isMatch = compose2( + hasAllrequiredFields, + headNode + ); + + return lazyIntersection(isMatch, previousExpr); + } + + /** + * Expression for $, returns the evaluator function + */ + function capture( previousExpr, 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 + + 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. + * + * 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 + is at the start of the jsonPath. + 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 + 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 + 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) + ); + + } + + /** + * 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 + is at the start of the jsonPath. + 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; + } + + 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. + terminalCaseWhenArrivingAtRoot = rootExpr(), + terminalCaseWhenPreviousExpressionIsSatisfied = previousExpr, + recursiveCase = skip1(function(ascent) { + return cases(ascent); + }), + + cases = lazyUnion( + terminalCaseWhenArrivingAtRoot + , terminalCaseWhenPreviousExpressionIsSatisfied + , recursiveCase + ); + + return cases; + } + + /** + * Generate an evaluator for ! - matches only the root element of the json + * 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 + * 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 + * 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 + // this as a special case + + return foldR( + function( parserGeneratedSoFar, expr ){ + + return expr(parserGeneratedSoFar, detection); + }, + 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 + * 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, + detected + ), + + remainingUnparsedJsonPath = jsonPath.substr(len(detected[0])); + + return onSuccess(remainingUnparsedJsonPath, compiledParser); + } + } + + /** + * Partially completes generateClauseReaderIfTokenFound above. + */ + function clauseMatcher(tokenDetector, exprs) { + + return partialComplete( + generateClauseReaderIfTokenFound, + tokenDetector, + exprs + ); + } + + /** + * 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, + 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 + // expressions when this token is found + , clauseMatcher(dotSyntax , list() ) + + , clauseMatcher(bangSyntax , list( capture, + rootExpr)) + + , clauseMatcher(emptySyntax , list( statementExpr)) + + , function (jsonPath) { + throw Error('"' + jsonPath + '" could not be tokenised') + } + ); + + + /** + * 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 + * any remaining jsonPath to be compiled. + */ + function returnFoundParser(_remainingJsonPath, compiledParser){ + return compiledParser + } + + /** + * Recursively compile a JSONPath expression. + * + * 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, + 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 + * the parser that we have found so far. + */ + var onFind = uncompiledJsonPath + ? compileJsonPathToFunction + : returnFoundParser; + + 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 + return compileJsonPathToFunction(jsonPath, always); + + } catch( e ) { + throw Error( 'Could not compile "' + jsonPath + + '" because ' + e.message + ); + } + } + + }); + + /** + * 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 + * the name of the events managed by this singleEventPubSub + * @param {singleEventPubSub} [newListener] + * place to notify of new listeners + * @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 + * can be iterated more quickly when we are emitting + */ + var listenerTupleList, + listenerList; + + function hasId(id){ + return function(tuple) { + return tuple.id == id; + }; + } + + return { + + /** + * @param {Function} listener + * @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 () { + applyEach( listenerList, arguments ); + }, + + un: function( listenerId ) { + + 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)); + } + }; + } + /** + * 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 + * 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'); + + function newSingle(eventName) { + return singles[eventName] = singleEventPubSub( + eventName, + newListener, + removeListener + ); + } + + /** pubSub instances are functions */ + 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 + // 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 - + 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 + * 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 + 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 + listAsArray(tail(map(keyOf,descent))), // path + 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 + * oboeBus('node:!') + * + * + * + * @param {Function} predicateEvent + * either oboeBus(NODE_CLOSED) or oboeBus(NODE_OPENED). + * @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: + 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. + */ + if (maybeMatchingMapping !== false) { + + emitMatchingNode( + emitMatch, + nodeOf(maybeMatchingMapping), + ascent + ); + } + }, fullEventName); + + oboeBus('removeListener').on( function(removedEventName){ + + // 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) ) { + + addUnderlyingListener( + fullEventName, + predicateEvent, + jsonPathCompiler( match[2] ) + ); + } + } + }) + + } + + /** + * The instance API is the thing that is returned when oboe() is called. + * it allows: + * + * - listeners for various events to be added and removed + * - 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 + * fired instead) + * + * The callback is used as the listener id so that it can later be + * removed using .un(callback) + */ + function addProtectedCallback(eventName, callback) { + 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 + */ + function protectedCallback( callback ) { + return function() { + try{ + return callback.apply(oboeApi, arguments); + }catch(e) { + setTimeout(function() { + throw e; + }); + } + } + } + + /** + * Return the fully qualified event for when a pattern matches + * either a node or a path + * + * @param type {String} either 'node' or 'path' + */ + 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 { + emitNodeSwap(returnValueFromCallback); + } + } + } + } + + 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 + */ + return oboeApi = { + on : addListener, + 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(), + httpMethodName, + contentSource, + body, + headers, + withCredentials + ); + } + + clarinet(oboeBus); + + ascentManager(oboeBus, incrementalContentBuilder(oboeBus)); + + 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: + // oboe( readableStream ) + return applyDefaults( + wire, + arg1 // url + ); + + } else { + + // method signature is: + // oboe({method:m, url:u, body:b, headers:{...}}) + + return applyDefaults( + wire, + arg1.url, + arg1.method, + arg1.body, + arg1.headers, + arg1.withCredentials, + arg1.cached + ); + + } + } else { + // 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') { + module.exports = oboe; + } else { + window.oboe = oboe; + } + })((function(){ + // Access to the window object throws an exception in HTML5 web workers so + // point it to "self" if it runs in a web worker + try { + return window; + } catch (e) { + 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", + "2.16.840.1.101.3.4.1.3": "aes-128-ofb", + "2.16.840.1.101.3.4.1.4": "aes-128-cfb", + "2.16.840.1.101.3.4.1.21": "aes-192-ecb", + "2.16.840.1.101.3.4.1.22": "aes-192-cbc", + "2.16.840.1.101.3.4.1.23": "aes-192-ofb", + "2.16.840.1.101.3.4.1.24": "aes-192-cfb", + "2.16.840.1.101.3.4.1.41": "aes-256-ecb", + "2.16.840.1.101.3.4.1.42": "aes-256-cbc", + "2.16.840.1.101.3.4.1.43": "aes-256-ofb", + "2.16.840.1.101.3.4.1.44": "aes-256-cfb" + } + },{}],242:[function(require,module,exports){ + // 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(), + this.key('modulus').int(), + this.key('publicExponent').int(), + this.key('privateExponent').int(), + this.key('prime1').int(), + this.key('prime2').int(), + this.key('exponent1').int(), + this.key('exponent2').int(), + this.key('coefficient').int() + ) + }) + exports.RSAPrivateKey = RSAPrivateKey + + var RSAPublicKey = asn1.define('RSAPublicKey', function () { + this.seq().obj( + this.key('modulus').int(), + this.key('publicExponent').int() + ) + }) + exports.RSAPublicKey = RSAPublicKey + + var PublicKey = asn1.define('SubjectPublicKeyInfo', function () { + this.seq().obj( + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPublicKey').bitstr() + ) + }) + exports.PublicKey = PublicKey + + var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () { + this.seq().obj( + this.key('algorithm').objid(), + this.key('none').null_().optional(), + this.key('curve').objid().optional(), + this.key('params').seq().obj( + this.key('p').int(), + this.key('q').int(), + this.key('g').int() + ).optional() + ) + }) + + var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () { + this.seq().obj( + this.key('version').int(), + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPrivateKey').octstr() + ) + }) + exports.PrivateKey = PrivateKeyInfo + var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () { + this.seq().obj( + this.key('algorithm').seq().obj( + this.key('id').objid(), + this.key('decrypt').seq().obj( + this.key('kde').seq().obj( + this.key('id').objid(), + this.key('kdeparams').seq().obj( + this.key('salt').octstr(), + this.key('iters').int() + ) + ), + this.key('cipher').seq().obj( + this.key('algo').objid(), + this.key('iv').octstr() + ) + ) + ), + this.key('subjectPrivateKey').octstr() + ) + }) + + exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo + + var DSAPrivateKey = asn1.define('DSAPrivateKey', function () { + this.seq().obj( + this.key('version').int(), + this.key('p').int(), + this.key('q').int(), + this.key('g').int(), + this.key('pub_key').int(), + this.key('priv_key').int() + ) + }) + exports.DSAPrivateKey = DSAPrivateKey + + exports.DSAparam = asn1.define('DSAparam', function () { + this.int() + }) + + var ECPrivateKey = asn1.define('ECPrivateKey', function () { + this.seq().obj( + this.key('version').int(), + this.key('privateKey').octstr(), + this.key('parameters').optional().explicit(0).use(ECParameters), + this.key('publicKey').optional().explicit(1).bitstr() + ) + }) + 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(), + this.key('critical').bool().def(false), + this.key('extnValue').octstr() + ) + }) + + var TBSCertificate = asn.define('TBSCertificate', function () { + this.seq().obj( + this.key('version').explicit(0).int(), + this.key('serialNumber').int(), + this.key('signature').use(AlgorithmIdentifier), + this.key('issuer').use(Name), + this.key('validity').use(Validity), + this.key('subject').use(Name), + this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo), + this.key('issuerUniqueID').implicit(1).bitstr().optional(), + this.key('subjectUniqueID').implicit(2).bitstr().optional(), + this.key('extensions').explicit(3).seqof(Extension).optional() + ) + }) + + var X509Certificate = asn.define('X509Certificate', function () { + this.seq().obj( + this.key('tbsCertificate').use(TBSCertificate), + this.key('signatureAlgorithm').use(AlgorithmIdentifier), + this.key('signatureValue').bitstr() + ) + }) + + module.exports = X509Certificate + + },{"asn1.js":5}],244:[function(require,module,exports){ + (function (Buffer){ + // adapted from https://github.com/apatil/pemstrip + var findProc = /Proc-Type: 4,ENCRYPTED\n\r?DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)\n\r?\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?/m + var startRegex = /^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----\n/m + var fullRegex = /^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?-----END \1-----$/m + var evp = require('evp_bytestokey') + var ciphers = require('browserify-aes') + module.exports = function (okey, password) { + var key = okey.toString() + var match = key.match(findProc) + var decrypted + if (!match) { + var match2 = key.match(fullRegex) + decrypted = new Buffer(match2[2].replace(/\r?\n/g, ''), 'base64') + } else { + var suite = 'aes' + match[1] + var iv = new Buffer(match[2], 'hex') + var cipherText = new Buffer(match[3].replace(/\r?\n/g, ''), 'base64') + var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key + var out = [] + var cipher = ciphers.createDecipheriv(suite, cipherKey, iv) + out.push(cipher.update(cipherText)) + out.push(cipher.final()) + decrypted = Buffer.concat(out) + } + var tag = key.match(startRegex)[1] + return { + tag: tag, + data: decrypted + } + } + + }).call(this,require("buffer").Buffer) + },{"browserify-aes":58,"buffer":84,"evp_bytestokey":158}],245:[function(require,module,exports){ + (function (Buffer){ + var asn1 = require('./asn1') + var aesid = require('./aesid.json') + var fixProc = require('./fixProc') + var ciphers = require('browserify-aes') + var compat = require('pbkdf2') + module.exports = parseKeys + + function parseKeys (buffer) { + var password + if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) { + password = buffer.passphrase + buffer = buffer.key + } + if (typeof buffer === 'string') { + buffer = new Buffer(buffer) + } + + var stripped = fixProc(buffer, password) + + var type = stripped.tag + var data = stripped.data + var subtype, ndata + switch (type) { + case 'CERTIFICATE': + ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo + // falls through + case 'PUBLIC KEY': + if (!ndata) { + ndata = asn1.PublicKey.decode(data, 'der') + } + subtype = ndata.algorithm.algorithm.join('.') + switch (subtype) { + case '1.2.840.113549.1.1.1': + return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der') + case '1.2.840.10045.2.1': + ndata.subjectPrivateKey = ndata.subjectPublicKey + return { + type: 'ec', + data: ndata + } + case '1.2.840.10040.4.1': + ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der') + return { + type: 'dsa', + data: ndata.algorithm.params + } + default: throw new Error('unknown key id ' + subtype) + } + throw new Error('unknown key type ' + type) + case 'ENCRYPTED PRIVATE KEY': + data = asn1.EncryptedPrivateKey.decode(data, 'der') + data = decrypt(data, password) + // falls through + case 'PRIVATE KEY': + ndata = asn1.PrivateKey.decode(data, 'der') + subtype = ndata.algorithm.algorithm.join('.') + switch (subtype) { + case '1.2.840.113549.1.1.1': + return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der') + case '1.2.840.10045.2.1': + return { + curve: ndata.algorithm.curve, + privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey + } + case '1.2.840.10040.4.1': + ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der') + return { + type: 'dsa', + params: ndata.algorithm.params + } + default: throw new Error('unknown key id ' + subtype) + } + throw new Error('unknown key type ' + type) + case 'RSA PUBLIC KEY': + return asn1.RSAPublicKey.decode(data, 'der') + case 'RSA PRIVATE KEY': + return asn1.RSAPrivateKey.decode(data, 'der') + case 'DSA PRIVATE KEY': + return { + type: 'dsa', + params: asn1.DSAPrivateKey.decode(data, 'der') + } + case 'EC PRIVATE KEY': + data = asn1.ECPrivateKey.decode(data, 'der') + return { + curve: data.parameters.value, + privateKey: data.privateKey + } + default: throw new Error('unknown key type ' + type) + } + } + parseKeys.signature = asn1.signature + function decrypt (data, password) { + var salt = data.algorithm.decrypt.kde.kdeparams.salt + var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10) + var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')] + var iv = data.algorithm.decrypt.cipher.iv + var cipherText = data.subjectPrivateKey + var keylen = parseInt(algo.split('-')[1], 10) / 8 + var key = compat.pbkdf2Sync(password, salt, iters, keylen) + var cipher = ciphers.createDecipheriv(algo, key, iv) + var out = [] + out.push(cipher.update(cipherText)) + 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') + , forEach = require('for-each') + , 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])) { + result[key].push(value) + } else { + result[key] = [ result[key], value ] + } + } + ) + + 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 = { + 'sha': 'SHA-1', + 'sha-1': 'SHA-1', + 'sha1': 'SHA-1', + 'sha256': 'SHA-256', + 'sha-256': 'SHA-256', + 'sha384': 'SHA-384', + 'sha-384': 'SHA-384', + 'sha-512': 'SHA-512', + 'sha512': 'SHA-512' + } + var checks = [] + function checkNative (algo) { + if (global.process && !global.process.browser) { + return Promise.resolve(false) + } + if (!subtle || !subtle.importKey || !subtle.deriveBits) { + return Promise.resolve(false) + } + if (checks[algo] !== undefined) { + return checks[algo] + } + ZERO_BUF = ZERO_BUF || Buffer.alloc(8) + var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo) + .then(function () { + return true + }).catch(function () { + return false + }) + checks[algo] = prom + return prom + } + function browserPbkdf2 (password, salt, iterations, length, algo) { + return subtle.importKey( + 'raw', password, {name: 'PBKDF2'}, false, ['deriveBits'] + ).then(function (key) { + return subtle.deriveBits({ + name: 'PBKDF2', + salt: salt, + iterations: iterations, + hash: { + name: algo + } + }, key, length << 3) + }).then(function (res) { + return Buffer.from(res) + }) + } + function resolvePromise (promise, callback) { + promise.then(function (out) { + process.nextTick(function () { + callback(null, out) + }) + }, function (e) { + process.nextTick(function () { + callback(e) + }) + }) + } + 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') { + return process.nextTick(function () { + var out + try { + out = sync(password, salt, iterations, keylen, digest) + } catch (e) { + return callback(e) + } + callback(null, out) + }) + } + resolvePromise(checkNative(algo).then(function (resp) { + if (resp) { + return browserPbkdf2(password, salt, iterations, keylen, algo) + } else { + return sync(password, salt, iterations, keylen, digest) + } + }), 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){ + var defaultEncoding + /* istanbul ignore next */ + if (process.browser) { + 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 + module.exports = function (iterations, keylen) { + 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 + var ZEROS = Buffer.alloc(128) + var sizes = { + md5: 16, + sha1: 20, + sha224: 28, + sha256: 32, + sha384: 48, + sha512: 64, + 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 + this.ipad2 = ipad + this.opad = opad + this.alg = alg + this.blocksize = blocksize + 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)); + var error = new ExceptionConstructor(message); + 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) { + var s = typeof value; + if (s == 'object') { + if (!value) { + return 'null'; + } else if (value instanceof Array) { + return 'array'; + } + } + 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) { + module.exports = { nextTick: nextTick }; + } else { + module.exports = process + } + + function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } + } + + + }).call(this,require('_process')) + },{"_process":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'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + (function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } + } ()) + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + + process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + }; + + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + process.title = 'browser'; + process.browser = true; + process.env = {}; + process.argv = []; + process.version = ''; // empty string to avoid regexp issues + process.versions = {}; + + function noop() {} + + process.on = noop; + process.addListener = noop; + process.once = noop; + process.off = noop; + process.removeListener = noop; + process.removeAllListeners = noop; + process.emit = noop; + process.prependListener = noop; + process.prependOnceListener = noop; + + process.listeners = function (name) { return [] } + + process.binding = function (name) { + throw new Error('process.binding is not supported'); + }; + + process.cwd = function () { return '/' }; + process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); + }; + process.umask = function() { return 0; }; + + },{}],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); + }, function (err) { + setImmediate(cb, err); + }); + }; + }; + + },{"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); + }; + },{"./privateDecrypt":261,"./publicEncrypt":262}],260:[function(require,module,exports){ + (function (Buffer){ + var createHash = require('create-hash'); + module.exports = function (seed, len) { + var t = new Buffer(''); + var i = 0, c; + while (t.length < len) { + c = i2ops(i++); + t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()]); + } + return t.slice(0, len); + }; + + function i2ops(c) { + var out = new Buffer(4); + out.writeUInt32BE(c,0); + return out; + } + }).call(this,require("buffer").Buffer) + },{"buffer":84,"create-hash":91}],261:[function(require,module,exports){ + (function (Buffer){ + var parseKeys = require('parse-asn1'); + var mgf = require('./mgf'); + var xor = require('./xor'); + var bn = require('bn.js'); + var crt = require('browserify-rsa'); + var createHash = require('create-hash'); + var withPublic = require('./withPublic'); + module.exports = function privateDecrypt(private_key, enc, reverse) { + var padding; + if (private_key.padding) { + padding = private_key.padding; + } else if (reverse) { + padding = 1; + } else { + padding = 4; + } + + var key = parseKeys(private_key); + var k = key.modulus.byteLength(); + if (enc.length > k || new bn(enc).cmp(key.modulus) >= 0) { + throw new Error('decryption error'); + } + var msg; + if (reverse) { + msg = withPublic(new bn(enc), key); + } else { + msg = crt(enc, key); + } + var zBuffer = new Buffer(k - msg.length); + zBuffer.fill(0); + msg = Buffer.concat([zBuffer, msg], k); + if (padding === 4) { + return oaep(key, msg); + } else if (padding === 1) { + return pkcs1(key, msg, reverse); + } else if (padding === 3) { + return msg; + } else { + throw new Error('unknown padding'); + } + }; + + function oaep(key, msg){ + var n = key.modulus; + var k = key.modulus.byteLength(); + var mLen = msg.length; + var iHash = createHash('sha1').update(new Buffer('')).digest(); + var hLen = iHash.length; + var hLen2 = 2 * hLen; + if (msg[0] !== 0) { + throw new Error('decryption error'); + } + var maskedSeed = msg.slice(1, hLen + 1); + var maskedDb = msg.slice(hLen + 1); + var seed = xor(maskedSeed, mgf(maskedDb, hLen)); + var db = xor(maskedDb, mgf(seed, k - hLen - 1)); + if (compare(iHash, db.slice(0, hLen))) { + throw new Error('decryption error'); + } + var i = hLen; + while (db[i] === 0) { + i++; + } + if (db[i++] !== 1) { + throw new Error('decryption error'); + } + return db.slice(i); + } + + function pkcs1(key, msg, reverse){ + var p1 = msg.slice(0, 2); + var i = 2; + var status = 0; + while (msg[i++] !== 0) { + if (i >= msg.length) { + status++; + break; + } + } + 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++; + } + if (ps.length < 8) { + status++; + } + if (status) { + throw new Error('decryption error'); + } + return msg.slice(i); + } + function compare(a, b){ + a = new Buffer(a); + b = new Buffer(b); + var dif = 0; + var len = a.length; + if (a.length !== b.length) { + dif++; + len = Math.min(a.length, b.length); + } + var i = -1; + while (++i < len) { + dif += (a[i] ^ b[i]); + } + return dif; + } + }).call(this,require("buffer").Buffer) + },{"./mgf":260,"./withPublic":263,"./xor":264,"bn.js":53,"browserify-rsa":76,"buffer":84,"create-hash":91,"parse-asn1":245}],262:[function(require,module,exports){ + (function (Buffer){ + var parseKeys = require('parse-asn1'); + var randomBytes = require('randombytes'); + var createHash = require('create-hash'); + var mgf = require('./mgf'); + var xor = require('./xor'); + 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) { + padding = public_key.padding; + } else if (reverse) { + padding = 1; + } else { + padding = 4; + } + var key = parseKeys(public_key); + var paddedMsg; + if (padding === 4) { + paddedMsg = oaep(key, msg); + } else if (padding === 1) { + paddedMsg = pkcs1(key, msg, reverse); + } else if (padding === 3) { + paddedMsg = new bn(msg); + if (paddedMsg.cmp(key.modulus) >= 0) { + throw new Error('data too long for modulus'); + } + } else { + throw new Error('unknown padding'); + } + if (reverse) { + return crt(paddedMsg, key); + } else { + return withPublic(paddedMsg, key); + } + }; + + function oaep(key, msg){ + var k = key.modulus.byteLength(); + var mLen = msg.length; + var iHash = createHash('sha1').update(new Buffer('')).digest(); + var hLen = iHash.length; + var hLen2 = 2 * hLen; + if (mLen > k - hLen2 - 2) { + throw new Error('message too long'); + } + var ps = new Buffer(k - mLen - hLen2 - 2); + ps.fill(0); + var dblen = k - hLen - 1; + var seed = randomBytes(hLen); + var maskedDb = xor(Buffer.concat([iHash, ps, new Buffer([1]), msg], dblen), mgf(seed, dblen)); + var maskedSeed = xor(seed, mgf(maskedDb, hLen)); + return new bn(Buffer.concat([new Buffer([0]), maskedSeed, maskedDb], k)); + } + function pkcs1(key, msg, reverse){ + var mLen = msg.length; + var k = key.modulus.byteLength(); + if (mLen > k - 11) { + throw new Error('message too long'); + } + var ps; + if (reverse) { + ps = new Buffer(k - mLen - 3); + ps.fill(0xff); + } else { + ps = nonZero(k - mLen - 3); + } + return new bn(Buffer.concat([new Buffer([0, reverse?1:2]), ps, new Buffer([0]), msg], k)); + } + function nonZero(len, crypto) { + var out = new Buffer(len); + var i = 0; + var cache = randomBytes(len*2); + var cur = 0; + var num; + while (i < len) { + if (cur === cache.length) { + cache = randomBytes(len*2); + cur = 0; + } + num = cache[cur++]; + if (num) { + out[i++] = num; + } + } + return out; + } + }).call(this,require("buffer").Buffer) + },{"./mgf":260,"./withPublic":263,"./xor":264,"bn.js":53,"browserify-rsa":76,"buffer":84,"create-hash":91,"parse-asn1":245,"randombytes":270}],263:[function(require,module,exports){ + (function (Buffer){ + var bn = require('bn.js'); + function withPublic(paddedMsg, key) { + return new Buffer(paddedMsg + .toRed(bn.mont(key.modulus)) + .redPow(new bn(key.publicExponent)) + .fromRed() + .toArray()); + } + + module.exports = withPublic; + }).call(this,require("buffer").Buffer) + },{"bn.js":53,"buffer":84}],264:[function(require,module,exports){ + module.exports = function xor(a, b) { + var len = a.length; + var i = -1; + while (++i < len) { + a[i] ^= b[i]; + } + return a + }; + },{}],265:[function(require,module,exports){ + (function (global){ + /*! https://mths.be/punycode v1.4.1 by @mathias */ + ;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + + }(this)); + + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + },{}],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': + return function (key, value, index) { + return value === null ? [ + encode(key, opts), + '[', + index, + ']' + ].join('') : [ + encode(key, opts), + '[', + encode(index, opts), + ']=', + encode(value, opts) + ].join(''); + }; + + case 'bracket': + return function (key, value) { + return value === null ? encode(key, opts) : [ + encode(key, opts), + '[]=', + encode(value, opts) + ].join(''); + }; + + default: + return function (key, value) { + return value === null ? encode(key, opts) : [ + encode(key, opts), + '=', + encode(value, opts) + ].join(''); + }; + } + } + + 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; + } else if (accumulator[key] === undefined) { + 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(); + } else if (typeof input === 'object') { + return keysSorter(Object.keys(input)).sort(function (a, b) { + return Number(a) - Number(b); + }).map(function (key) { + return input[key]; + }); + } + + return input; + } + + function extract(str) { + var queryStart = str.indexOf('?'); + if (queryStart === -1) { + return ''; + } + 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)) { + // Sort object keys, not values + result[key] = keysSorter(val); + } 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. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 'use strict'; + + // 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); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + 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. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 'use strict'; + + var 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; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + 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 = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; + } + + var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + 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') + } + var safeBuffer = require('safe-buffer') + var randombytes = require('randombytes') + var Buffer = safeBuffer.Buffer + var kBufferMaxLength = safeBuffer.kMaxLength + var crypto = global.crypto || global.msCrypto + var kMaxUint32 = Math.pow(2, 32) - 1 + function assertOffset (offset, length) { + 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') + } + } + if ((crypto && crypto.getRandomValues) || !process.browser) { + exports.randomFill = randomFill + exports.randomFillSync = randomFillSync + } else { + exports.randomFill = oldBrowser + exports.randomFillSync = oldBrowser + } + function randomFill (buf, offset, size, cb) { + 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 + size = buf.length + } else if (typeof size === 'function') { + cb = size + size = buf.length - offset + } else if (typeof cb !== 'function') { + throw new TypeError('"cb" argument must be a function') + } + assertOffset(offset, buf.length) + assertSize(size, offset, buf.length) + return actualFill(buf, offset, size, cb) + } + + function actualFill (buf, offset, size, cb) { + if (process.browser) { + var ourBuf = buf.buffer + var uint = new Uint8Array(ourBuf, offset, size) + crypto.getRandomValues(uint) + if (cb) { + process.nextTick(function () { + cb(null, buf) + }) + return + } + return buf + } + if (cb) { + randombytes(size, function (err, bytes) { + if (err) { + return cb(err) + } + bytes.copy(buf, offset) + cb(null, buf) + }) + return + } + var bytes = randombytes(size) + bytes.copy(buf, offset) + return buf + } + function randomFillSync (buf, offset, size) { + if (typeof offset === 'undefined') { + offset = 0 + } + 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; + },{}],273:[function(require,module,exports){ + module.exports = require('crypto'); + },{"crypto":272}],274:[function(require,module,exports){ + 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.')); + } else { + 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) { + callback(null, '0x'+ result.toString('hex')); + } else { + callback(error); + } + }) + } 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 { + throw error; + } + } + } + }; + + + 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. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + // a duplex stream is just a stream that is both readable and writable. + // Since JS doesn't have multiple prototypal inheritance, this class + // prototypally inherits from Readable, and then parasitically from + // Writable. + + 'use strict'; + + /**/ + + var processNextTick = require('process-nextick-args').nextTick; + /**/ + + /**/ + var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; + }; + /**/ + + module.exports = Duplex; + + /**/ + var util = require('core-util-is'); + util.inherits = require('inherits'); + /**/ + + var Readable = require('./_stream_readable'); + var Writable = require('./_stream_writable'); + + util.inherits(Duplex, Readable); + + 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) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } + }); + + Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); + + processNextTick(cb, err); + }; + + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + },{"./_stream_readable":278,"./_stream_writable":280,"core-util-is":89,"inherits":180,"process-nextick-args":256}],277:[function(require,module,exports){ + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + // a passthrough stream. + // basically just the most minimal sort of Transform stream. + // Every written chunk gets output as-is. + + 'use strict'; + + module.exports = PassThrough; + + var Transform = require('./_stream_transform'); + + /**/ + var util = require('core-util-is'); + util.inherits = require('inherits'); + /**/ + + util.inherits(PassThrough, Transform); + + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); + } + + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + },{"./_stream_transform":279,"core-util-is":89,"inherits":180}],278:[function(require,module,exports){ + (function (process,global){ + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 'use strict'; + + /**/ + + var 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) { + return Buffer.from(chunk); + } + function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; + } + + /**/ + + /**/ + var util = require('core-util-is'); + util.inherits = require('inherits'); + /**/ + + /**/ + var debugUtil = require('util'); + var debug = void 0; + if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); + } else { + debug = function () {}; + } + /**/ + + var BufferList = require('./internal/streams/BufferList'); + var destroyImpl = require('./internal/streams/destroy'); + var StringDecoder; + + util.inherits(Readable, Stream); + + var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + } + + function ReadableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var readableHwm = options.readableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + + function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); + } + + Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } + }); + + Readable.prototype.destroy = destroyImpl.destroy; + Readable.prototype._undestroy = destroyImpl.undestroy; + Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); + }; + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); + }; + + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); + }; + + function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + } + } + + return needMoreData(state); + } + + function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); + } + + function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; + } + + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; + + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; + }; + + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) 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 + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + processNextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; + } + + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); + }; + + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; + } + + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, unpipeInfo); + }return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this, unpipeInfo); + + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + processNextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + 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) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; + }; + + // exposed for testing purposes only. + Readable._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; + } + + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } + + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + processNextTick(endReadableNT, state, stream); + } + } + + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } + + function 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; + } + return -1; + } + }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + },{"./_stream_duplex":276,"./internal/streams/BufferList":281,"./internal/streams/destroy":282,"./internal/streams/stream":283,"_process":257,"core-util-is":89,"events":157,"inherits":180,"isarray":186,"process-nextick-args":256,"safe-buffer":290,"string_decoder/":317,"util":55}],279:[function(require,module,exports){ + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. + + 'use strict'; + + module.exports = Transform; + + var Duplex = require('./_stream_duplex'); + + /**/ + var util = require('core-util-is'); + util.inherits = require('inherits'); + /**/ + + util.inherits(Transform, Duplex); + + function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) { + return this.emit('error', new Error('write callback called multiple times')); + } + + ts.writechunk = null; + ts.writecb = null; + + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + + cb(er); + + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } + } + + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); + } + + function prefinish() { + var _this = this; + + if (typeof this._flush === 'function') { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } + } + + Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); + }; + + Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + Transform.prototype._destroy = function (err, cb) { + var _this2 = this; + + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this2.emit('close'); + }); + }; + + function done(stream, er, data) { + if (er) return stream.emit('error', er); + + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); + + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); + } + },{"./_stream_duplex":276,"core-util-is":89,"inherits":180}],280:[function(require,module,exports){ + (function (process,global){ + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + // 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; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } + + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; + } + /* */ + + /**/ + var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : 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) { + return Buffer.from(chunk); + } + function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; + } + + /**/ + + var destroyImpl = require('./internal/streams/destroy'); + + util.inherits(Writable, Stream); + + function nop() {} + + function WritableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var writableHwm = options.writableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + + (function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} + })(); + + // Test _writableState for inheritance to account for Duplex streams, + // whose prototype chain only points to Readable. + var realHasInstance; + if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + + return object && object._writableState instanceof WritableState; + } + }); + } else { + realHasInstance = function (object) { + return object instanceof this; + }; + } + + function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + + if (typeof options.final === 'function') this._final = options.final; + } + + Stream.call(this); + } + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; + + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + 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) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + processNextTick(cb, er); + valid = false; + } + return valid; + } + + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + + return ret; + }; + + Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; + }; + + Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; + } + + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + processNextTick(cb, er); + // this can emit finish, and it will always happen + // after error + processNextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } + + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); + }; + + Writable.prototype._writev = null; + + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); + }; + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + stream.emit('error', err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); + } + function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function') { + state.pendingcb++; + state.finalCalled = true; + processNextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + } + } + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) processNextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } + + function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = corkReq; + } else { + state.corkedRequestsFree = corkReq; + } + } + + Object.defineProperty(Writable.prototype, 'destroyed', { + get: function () { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } + }); + + Writable.prototype.destroy = destroyImpl.destroy; + Writable.prototype._undestroy = destroyImpl.undestroy; + Writable.prototype._destroy = function (err, cb) { + this.end(); + cb(err); + }; + }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + },{"./_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; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + return BufferList; + }(); + + if (util && util.inspect && util.inspect.custom) { + module.exports.prototype[util.inspect.custom] = function () { + var obj = util.inspect({ length: this.length }); + return this.constructor.name + ' ' + obj; + }; + } + },{"safe-buffer":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); + } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { + processNextTick(emitErrorNT, this, err); + } + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + processNextTick(emitErrorNT, _this, err); + if (_this._writableState) { + _this._writableState.errorEmitted = true; + } + } else if (cb) { + cb(err); + } + }); + + return this; + } + + function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } + } + + function emitErrorNT(self, err) { + self.emit('error', err); + } + + module.exports = { + destroy: destroy, + undestroy: undestroy + }; + },{"process-nextick-args":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; + exports.Readable = exports; + exports.Writable = require('./lib/_stream_writable.js'); + exports.Duplex = require('./lib/_stream_duplex.js'); + exports.Transform = require('./lib/_stream_transform.js'); + exports.PassThrough = require('./lib/_stream_passthrough.js'); + + },{"./lib/_stream_duplex.js":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 + this._c = 0x98badcfe + 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 + al = fn1(al, bl, cl, dl, el, m[0], 0x00000000, 11); cl = rotl(cl, 10) + el = fn1(el, al, bl, cl, dl, m[1], 0x00000000, 14); bl = rotl(bl, 10) + dl = fn1(dl, el, al, bl, cl, m[2], 0x00000000, 15); al = rotl(al, 10) + cl = fn1(cl, dl, el, al, bl, m[3], 0x00000000, 12); el = rotl(el, 10) + bl = fn1(bl, cl, dl, el, al, m[4], 0x00000000, 5); dl = rotl(dl, 10) + al = fn1(al, bl, cl, dl, el, m[5], 0x00000000, 8); cl = rotl(cl, 10) + el = fn1(el, al, bl, cl, dl, m[6], 0x00000000, 7); bl = rotl(bl, 10) + dl = fn1(dl, el, al, bl, cl, m[7], 0x00000000, 9); al = rotl(al, 10) + cl = fn1(cl, dl, el, al, bl, m[8], 0x00000000, 11); el = rotl(el, 10) + bl = fn1(bl, cl, dl, el, al, m[9], 0x00000000, 13); dl = rotl(dl, 10) + al = fn1(al, bl, cl, dl, el, m[10], 0x00000000, 14); cl = rotl(cl, 10) + el = fn1(el, al, bl, cl, dl, m[11], 0x00000000, 15); bl = rotl(bl, 10) + dl = fn1(dl, el, al, bl, cl, m[12], 0x00000000, 6); al = rotl(al, 10) + 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 + el = fn2(el, al, bl, cl, dl, m[7], 0x5a827999, 7); bl = rotl(bl, 10) + dl = fn2(dl, el, al, bl, cl, m[4], 0x5a827999, 6); al = rotl(al, 10) + cl = fn2(cl, dl, el, al, bl, m[13], 0x5a827999, 8); el = rotl(el, 10) + bl = fn2(bl, cl, dl, el, al, m[1], 0x5a827999, 13); dl = rotl(dl, 10) + al = fn2(al, bl, cl, dl, el, m[10], 0x5a827999, 11); cl = rotl(cl, 10) + el = fn2(el, al, bl, cl, dl, m[6], 0x5a827999, 9); bl = rotl(bl, 10) + dl = fn2(dl, el, al, bl, cl, m[15], 0x5a827999, 7); al = rotl(al, 10) + cl = fn2(cl, dl, el, al, bl, m[3], 0x5a827999, 15); el = rotl(el, 10) + bl = fn2(bl, cl, dl, el, al, m[12], 0x5a827999, 7); dl = rotl(dl, 10) + al = fn2(al, bl, cl, dl, el, m[0], 0x5a827999, 12); cl = rotl(cl, 10) + el = fn2(el, al, bl, cl, dl, m[9], 0x5a827999, 15); bl = rotl(bl, 10) + dl = fn2(dl, el, al, bl, cl, m[5], 0x5a827999, 9); al = rotl(al, 10) + cl = fn2(cl, dl, el, al, bl, m[2], 0x5a827999, 11); el = rotl(el, 10) + 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 + dl = fn3(dl, el, al, bl, cl, m[3], 0x6ed9eba1, 11); al = rotl(al, 10) + cl = fn3(cl, dl, el, al, bl, m[10], 0x6ed9eba1, 13); el = rotl(el, 10) + bl = fn3(bl, cl, dl, el, al, m[14], 0x6ed9eba1, 6); dl = rotl(dl, 10) + al = fn3(al, bl, cl, dl, el, m[4], 0x6ed9eba1, 7); cl = rotl(cl, 10) + el = fn3(el, al, bl, cl, dl, m[9], 0x6ed9eba1, 14); bl = rotl(bl, 10) + dl = fn3(dl, el, al, bl, cl, m[15], 0x6ed9eba1, 9); al = rotl(al, 10) + cl = fn3(cl, dl, el, al, bl, m[8], 0x6ed9eba1, 13); el = rotl(el, 10) + bl = fn3(bl, cl, dl, el, al, m[1], 0x6ed9eba1, 15); dl = rotl(dl, 10) + al = fn3(al, bl, cl, dl, el, m[2], 0x6ed9eba1, 14); cl = rotl(cl, 10) + el = fn3(el, al, bl, cl, dl, m[7], 0x6ed9eba1, 8); bl = rotl(bl, 10) + dl = fn3(dl, el, al, bl, cl, m[0], 0x6ed9eba1, 13); al = rotl(al, 10) + cl = fn3(cl, dl, el, al, bl, m[6], 0x6ed9eba1, 6); el = rotl(el, 10) + bl = fn3(bl, cl, dl, el, al, m[13], 0x6ed9eba1, 5); dl = rotl(dl, 10) + 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 + cl = fn4(cl, dl, el, al, bl, m[1], 0x8f1bbcdc, 11); el = rotl(el, 10) + bl = fn4(bl, cl, dl, el, al, m[9], 0x8f1bbcdc, 12); dl = rotl(dl, 10) + al = fn4(al, bl, cl, dl, el, m[11], 0x8f1bbcdc, 14); cl = rotl(cl, 10) + el = fn4(el, al, bl, cl, dl, m[10], 0x8f1bbcdc, 15); bl = rotl(bl, 10) + dl = fn4(dl, el, al, bl, cl, m[0], 0x8f1bbcdc, 14); al = rotl(al, 10) + cl = fn4(cl, dl, el, al, bl, m[8], 0x8f1bbcdc, 15); el = rotl(el, 10) + bl = fn4(bl, cl, dl, el, al, m[12], 0x8f1bbcdc, 9); dl = rotl(dl, 10) + al = fn4(al, bl, cl, dl, el, m[4], 0x8f1bbcdc, 8); cl = rotl(cl, 10) + el = fn4(el, al, bl, cl, dl, m[13], 0x8f1bbcdc, 9); bl = rotl(bl, 10) + dl = fn4(dl, el, al, bl, cl, m[3], 0x8f1bbcdc, 14); al = rotl(al, 10) + cl = fn4(cl, dl, el, al, bl, m[7], 0x8f1bbcdc, 5); el = rotl(el, 10) + bl = fn4(bl, cl, dl, el, al, m[15], 0x8f1bbcdc, 6); dl = rotl(dl, 10) + al = fn4(al, bl, cl, dl, el, m[14], 0x8f1bbcdc, 8); cl = rotl(cl, 10) + 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 + bl = fn5(bl, cl, dl, el, al, m[4], 0xa953fd4e, 9); dl = rotl(dl, 10) + al = fn5(al, bl, cl, dl, el, m[0], 0xa953fd4e, 15); cl = rotl(cl, 10) + el = fn5(el, al, bl, cl, dl, m[5], 0xa953fd4e, 5); bl = rotl(bl, 10) + dl = fn5(dl, el, al, bl, cl, m[9], 0xa953fd4e, 11); al = rotl(al, 10) + cl = fn5(cl, dl, el, al, bl, m[7], 0xa953fd4e, 6); el = rotl(el, 10) + bl = fn5(bl, cl, dl, el, al, m[12], 0xa953fd4e, 8); dl = rotl(dl, 10) + al = fn5(al, bl, cl, dl, el, m[2], 0xa953fd4e, 13); cl = rotl(cl, 10) + el = fn5(el, al, bl, cl, dl, m[10], 0xa953fd4e, 12); bl = rotl(bl, 10) + dl = fn5(dl, el, al, bl, cl, m[14], 0xa953fd4e, 5); al = rotl(al, 10) + cl = fn5(cl, dl, el, al, bl, m[1], 0xa953fd4e, 12); el = rotl(el, 10) + bl = fn5(bl, cl, dl, el, al, m[3], 0xa953fd4e, 13); dl = rotl(dl, 10) + al = fn5(al, bl, cl, dl, el, m[8], 0xa953fd4e, 14); cl = rotl(cl, 10) + el = fn5(el, al, bl, cl, dl, m[11], 0xa953fd4e, 11); bl = rotl(bl, 10) + 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 + ar = fn5(ar, br, cr, dr, er, m[5], 0x50a28be6, 8); cr = rotl(cr, 10) + er = fn5(er, ar, br, cr, dr, m[14], 0x50a28be6, 9); br = rotl(br, 10) + dr = fn5(dr, er, ar, br, cr, m[7], 0x50a28be6, 9); ar = rotl(ar, 10) + cr = fn5(cr, dr, er, ar, br, m[0], 0x50a28be6, 11); er = rotl(er, 10) + br = fn5(br, cr, dr, er, ar, m[9], 0x50a28be6, 13); dr = rotl(dr, 10) + ar = fn5(ar, br, cr, dr, er, m[2], 0x50a28be6, 15); cr = rotl(cr, 10) + er = fn5(er, ar, br, cr, dr, m[11], 0x50a28be6, 15); br = rotl(br, 10) + dr = fn5(dr, er, ar, br, cr, m[4], 0x50a28be6, 5); ar = rotl(ar, 10) + cr = fn5(cr, dr, er, ar, br, m[13], 0x50a28be6, 7); er = rotl(er, 10) + br = fn5(br, cr, dr, er, ar, m[6], 0x50a28be6, 7); dr = rotl(dr, 10) + ar = fn5(ar, br, cr, dr, er, m[15], 0x50a28be6, 8); cr = rotl(cr, 10) + er = fn5(er, ar, br, cr, dr, m[8], 0x50a28be6, 11); br = rotl(br, 10) + dr = fn5(dr, er, ar, br, cr, m[1], 0x50a28be6, 14); ar = rotl(ar, 10) + 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 + er = fn4(er, ar, br, cr, dr, m[6], 0x5c4dd124, 9); br = rotl(br, 10) + dr = fn4(dr, er, ar, br, cr, m[11], 0x5c4dd124, 13); ar = rotl(ar, 10) + cr = fn4(cr, dr, er, ar, br, m[3], 0x5c4dd124, 15); er = rotl(er, 10) + br = fn4(br, cr, dr, er, ar, m[7], 0x5c4dd124, 7); dr = rotl(dr, 10) + ar = fn4(ar, br, cr, dr, er, m[0], 0x5c4dd124, 12); cr = rotl(cr, 10) + er = fn4(er, ar, br, cr, dr, m[13], 0x5c4dd124, 8); br = rotl(br, 10) + dr = fn4(dr, er, ar, br, cr, m[5], 0x5c4dd124, 9); ar = rotl(ar, 10) + cr = fn4(cr, dr, er, ar, br, m[10], 0x5c4dd124, 11); er = rotl(er, 10) + br = fn4(br, cr, dr, er, ar, m[14], 0x5c4dd124, 7); dr = rotl(dr, 10) + ar = fn4(ar, br, cr, dr, er, m[15], 0x5c4dd124, 7); cr = rotl(cr, 10) + er = fn4(er, ar, br, cr, dr, m[8], 0x5c4dd124, 12); br = rotl(br, 10) + dr = fn4(dr, er, ar, br, cr, m[12], 0x5c4dd124, 7); ar = rotl(ar, 10) + cr = fn4(cr, dr, er, ar, br, m[4], 0x5c4dd124, 6); er = rotl(er, 10) + 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 + dr = fn3(dr, er, ar, br, cr, m[15], 0x6d703ef3, 9); ar = rotl(ar, 10) + cr = fn3(cr, dr, er, ar, br, m[5], 0x6d703ef3, 7); er = rotl(er, 10) + br = fn3(br, cr, dr, er, ar, m[1], 0x6d703ef3, 15); dr = rotl(dr, 10) + ar = fn3(ar, br, cr, dr, er, m[3], 0x6d703ef3, 11); cr = rotl(cr, 10) + er = fn3(er, ar, br, cr, dr, m[7], 0x6d703ef3, 8); br = rotl(br, 10) + dr = fn3(dr, er, ar, br, cr, m[14], 0x6d703ef3, 6); ar = rotl(ar, 10) + cr = fn3(cr, dr, er, ar, br, m[6], 0x6d703ef3, 6); er = rotl(er, 10) + br = fn3(br, cr, dr, er, ar, m[9], 0x6d703ef3, 14); dr = rotl(dr, 10) + ar = fn3(ar, br, cr, dr, er, m[11], 0x6d703ef3, 12); cr = rotl(cr, 10) + er = fn3(er, ar, br, cr, dr, m[8], 0x6d703ef3, 13); br = rotl(br, 10) + dr = fn3(dr, er, ar, br, cr, m[12], 0x6d703ef3, 5); ar = rotl(ar, 10) + cr = fn3(cr, dr, er, ar, br, m[2], 0x6d703ef3, 14); er = rotl(er, 10) + br = fn3(br, cr, dr, er, ar, m[10], 0x6d703ef3, 13); dr = rotl(dr, 10) + 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 + cr = fn2(cr, dr, er, ar, br, m[8], 0x7a6d76e9, 15); er = rotl(er, 10) + br = fn2(br, cr, dr, er, ar, m[6], 0x7a6d76e9, 5); dr = rotl(dr, 10) + ar = fn2(ar, br, cr, dr, er, m[4], 0x7a6d76e9, 8); cr = rotl(cr, 10) + er = fn2(er, ar, br, cr, dr, m[1], 0x7a6d76e9, 11); br = rotl(br, 10) + dr = fn2(dr, er, ar, br, cr, m[3], 0x7a6d76e9, 14); ar = rotl(ar, 10) + cr = fn2(cr, dr, er, ar, br, m[11], 0x7a6d76e9, 14); er = rotl(er, 10) + br = fn2(br, cr, dr, er, ar, m[15], 0x7a6d76e9, 6); dr = rotl(dr, 10) + ar = fn2(ar, br, cr, dr, er, m[0], 0x7a6d76e9, 14); cr = rotl(cr, 10) + er = fn2(er, ar, br, cr, dr, m[5], 0x7a6d76e9, 6); br = rotl(br, 10) + dr = fn2(dr, er, ar, br, cr, m[12], 0x7a6d76e9, 9); ar = rotl(ar, 10) + cr = fn2(cr, dr, er, ar, br, m[2], 0x7a6d76e9, 12); er = rotl(er, 10) + br = fn2(br, cr, dr, er, ar, m[13], 0x7a6d76e9, 9); dr = rotl(dr, 10) + ar = fn2(ar, br, cr, dr, er, m[9], 0x7a6d76e9, 12); cr = rotl(cr, 10) + 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 + br = fn1(br, cr, dr, er, ar, m[12], 0x00000000, 8); dr = rotl(dr, 10) + ar = fn1(ar, br, cr, dr, er, m[15], 0x00000000, 5); cr = rotl(cr, 10) + er = fn1(er, ar, br, cr, dr, m[10], 0x00000000, 12); br = rotl(br, 10) + dr = fn1(dr, er, ar, br, cr, m[4], 0x00000000, 9); ar = rotl(ar, 10) + cr = fn1(cr, dr, er, ar, br, m[1], 0x00000000, 12); er = rotl(er, 10) + br = fn1(br, cr, dr, er, ar, m[5], 0x00000000, 5); dr = rotl(dr, 10) + ar = fn1(ar, br, cr, dr, er, m[8], 0x00000000, 14); cr = rotl(cr, 10) + er = fn1(er, ar, br, cr, dr, m[7], 0x00000000, 6); br = rotl(br, 10) + dr = fn1(dr, er, ar, br, cr, m[6], 0x00000000, 8); ar = rotl(ar, 10) + cr = fn1(cr, dr, er, ar, br, m[2], 0x00000000, 13); er = rotl(er, 10) + br = fn1(br, cr, dr, er, ar, m[13], 0x00000000, 6); dr = rotl(dr, 10) + ar = fn1(ar, br, cr, dr, er, m[14], 0x00000000, 5); cr = rotl(cr, 10) + er = fn1(er, ar, br, cr, dr, m[0], 0x00000000, 15); br = rotl(br, 10) + 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 + this._c = (this._d + el + ar) | 0 + this._d = (this._e + al + br) | 0 + this._e = (this._a + bl + cr) | 0 + this._a = t + } + + RIPEMD160.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80 + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64) + this._update() + this._blockOffset = 0 + } + + this._block.fill(0, this._blockOffset, 56) + this._block.writeUInt32LE(this._length[0], 56) + this._block.writeUInt32LE(this._length[1], 60) + this._update() + + // produce result + var buffer = new Buffer(20) + buffer.writeInt32LE(this._a, 0) + buffer.writeInt32LE(this._b, 4) + buffer.writeInt32LE(this._c, 8) + buffer.writeInt32LE(this._d, 12) + buffer.writeInt32LE(this._e, 16) + return buffer + } + + function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) + } + + function fn1 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 + } + + function fn2 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 + } + + function fn3 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 + } + + function fn4 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 + } + + function fn5 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 + } + + module.exports = RIPEMD160 + + }).call(this,require("buffer").Buffer) + },{"buffer":84,"hash-base":161,"inherits":180}],289:[function(require,module,exports){ + const assert = require('assert') + const Buffer = require('safe-buffer').Buffer + /** + * RLP Encoding based on: https://github.com/ethereum/wiki/wiki/%5BEnglish%5D-RLP + * This function takes in a data, convert it to buffer if not, and a length for recursion + * + * @param {Buffer,String,Integer,Array} data - will be converted to buffer + * @returns {Buffer} - returns buffer of encoded data + **/ + exports.encode = function (input) { + if (input instanceof Array) { + var output = [] + for (var i = 0; i < input.length; i++) { + output.push(exports.encode(input[i])) + } + var buf = Buffer.concat(output) + return Buffer.concat([encodeLength(buf.length, 192), buf]) + } else { + input = toBuffer(input) + if (input.length === 1 && input[0] < 128) { + return input + } else { + return Buffer.concat([encodeLength(input.length, 128), input]) + } + } + } + + function safeParseInt (v, base) { + if (v.slice(0, 2) === '00') { + throw (new Error('invalid RLP: extra zeros')) + } + + return parseInt(v, base) + } + + function encodeLength (len, offset) { + if (len < 56) { + return Buffer.from([len + offset]) + } else { + var hexLength = intToHex(len) + var lLength = hexLength.length / 2 + var firstByte = intToHex(offset + 55 + lLength) + return Buffer.from(firstByte + hexLength, 'hex') + } + } + + /** + * 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 + * @returns {Array} - returns decode Array of Buffers containg the original message + **/ + exports.decode = function (input, stream) { + 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) { + return input.length + } else if (firstByte <= 0xb7) { + return firstByte - 0x7f + } else if (firstByte <= 0xbf) { + return firstByte - 0xb6 + } else if (firstByte <= 0xf7) { + // a list between 0-55 bytes long + return firstByte - 0xbf + } else { + // a list over 55 bytes long + var llength = firstByte - 0xf6 + var length = safeParseInt(input.slice(1, llength).toString('hex'), 16) + 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 { + data: input.slice(0, 1), + remainder: input.slice(1) + } + } else if (firstByte <= 0xb7) { + // string is 0-55 bytes long. A single byte with value 0x80 plus the length of the string followed by the string + // The range of the first byte is [0x80, 0xb7] + length = firstByte - 0x7f + + // set 0x80 null to 0 + if (firstByte === 0x80) { + data = Buffer.from([]) + } else { + data = input.slice(1, length) + } + + if (length === 2 && data[0] < 0x80) { + throw new Error('invalid rlp encoding: byte must be less 0x80') + } + + return { + data: data, + remainder: input.slice(length) + } + } else if (firstByte <= 0xbf) { + llength = firstByte - 0xb6 + length = safeParseInt(input.slice(1, llength).toString('hex'), 16) + data = input.slice(llength, length + llength) + if (data.length < length) { + throw (new Error('invalid RLP')) + } + + return { + data: data, + remainder: input.slice(length + llength) + } + } else if (firstByte <= 0xf7) { + // a list between 0-55 bytes long + length = firstByte - 0xbf + innerRemainder = input.slice(1, length) + while (innerRemainder.length) { + d = _decode(innerRemainder) + decoded.push(d.data) + innerRemainder = d.remainder + } + + return { + data: decoded, + remainder: input.slice(length) + } + } else { + // a list over 55 bytes long + llength = firstByte - 0xf6 + length = safeParseInt(input.slice(1, llength).toString('hex'), 16) + var totalLength = llength + length + if (totalLength > input.length) { + throw new Error('invalid rlp: total length is larger than the data') + } + + innerRemainder = input.slice(llength, totalLength) + if (innerRemainder.length === 0) { + throw new Error('invalid rlp, List has a invalid length') + } + + while (innerRemainder.length) { + d = _decode(innerRemainder) + decoded.push(d.data) + innerRemainder = d.remainder + } + return { + data: decoded, + remainder: input.slice(totalLength) + } + } + } + + function isHexPrefixed (str) { + return str.slice(0, 2) === '0x' + } + + // Removes 0x from a given String + function stripHexPrefix (str) { + if (typeof str !== 'string') { + return str + } + return isHexPrefixed(str) ? str.slice(2) : str + } + + 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') { + if (isHexPrefixed(v)) { + v = Buffer.from(padToEven(stripHexPrefix(v)), 'hex') + } else { + v = Buffer.from(v) + } + } else if (typeof v === 'number') { + if (!v) { + v = Buffer.from([]) + } else { + v = intToBuffer(v) + } + } else if (v === null || v === undefined) { + v = Buffer.from([]) + } else if (v.toArray) { + // converts a BN to a Buffer + v = Buffer.from(v.toArray()) + } else { + throw new Error('invalid type') + } + } + 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) { + dst[key] = src[key] + } + } + if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer + } else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer + } + + function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) + } + + // Copy static methods from Buffer + copyProps(Buffer, SafeBuffer) + + SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) + } + + SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf + } + + SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) + } + + SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) + } + + },{"buffer":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; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + // Note: The comments on the `throw` lines are intentional, they show + // up in Node's output if this results in an unhandled exception. + throw er; // Unhandled 'error' event + } + // At least give some kind of context to the user + var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); + 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); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + // edited: using safeApply + safeApply(listeners[i], this, args); + } + + return true; + } + + function safeApply(handler, context, args) { + try { + ReflectApply(handler, context, args) + } catch (err) { + // throw error after timeout so as not to interupt the stack + setTimeout(() => { + throw err + }) + } + } + + 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. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 'use strict'; + + var 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 + } else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target) + .concat(Object.getOwnPropertySymbols(target)); + }; + } else { + ReflectOwnKeys = function ReflectOwnKeys(target) { + 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() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); + } + 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) { + if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); + } + 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; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + // Note: The comments on the `throw` lines are intentional, they show + // up in Node's output if this results in an unhandled exception. + throw er; // Unhandled 'error' event + } + // At least give some kind of context to the user + var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); + 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 { + var len = handler.length; + var listeners = arrayClone(handler, len); + 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); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener !== 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; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + // If we've already got an array, just append. + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + + // Check for listener leak + m = $getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + // No error code for this since it is a Warning + // eslint-disable-next-line no-restricted-syntax + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + String(type) + ' listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + 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]); + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + 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); + wrapped.listener = listener; + 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); + } + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } + 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); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + + if (list.length === 1) + events[type] = list[0]; + + if (events.removeListener !== 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) { + this._events = Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== undefined) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = Object.create(null); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners !== undefined) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + + return this; + }; + + function _listeners(target, type, unwrap) { + var events = target._events; + + if (events === 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); + } else { + 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) { + ret[i] = arr[i].listener || arr[i]; + } + 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({ + current: currentOp, + total: totalOps, + percent: (currentOp / totalOps) * 100.0 + }) + } + } + } + + 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 + B32[i] |= (B[i * 4 + 2] & 0xff) << 16 + 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) + x[12] ^= R(x[ 8] + x[ 4], 13) + x[ 0] ^= R(x[12] + x[ 8], 18) + x[ 9] ^= R(x[ 5] + x[ 1], 7) + x[13] ^= R(x[ 9] + x[ 5], 9) + x[ 1] ^= R(x[13] + x[ 9], 13) + x[ 5] ^= R(x[ 1] + x[13], 18) + x[14] ^= R(x[10] + x[ 6], 7) + x[ 2] ^= R(x[14] + x[10], 9) + x[ 6] ^= R(x[ 2] + x[14], 13) + x[10] ^= R(x[ 6] + x[ 2], 18) + x[ 3] ^= R(x[15] + x[11], 7) + x[ 7] ^= R(x[ 3] + x[15], 9) + x[11] ^= R(x[ 7] + x[ 3], 13) + x[15] ^= R(x[11] + x[ 7], 18) + x[ 1] ^= R(x[ 0] + x[ 3], 7) + x[ 2] ^= R(x[ 1] + x[ 0], 9) + x[ 3] ^= R(x[ 2] + x[ 1], 13) + x[ 0] ^= R(x[ 3] + x[ 2], 18) + x[ 6] ^= R(x[ 5] + x[ 4], 7) + x[ 7] ^= R(x[ 6] + x[ 5], 9) + x[ 4] ^= R(x[ 7] + x[ 6], 13) + x[ 5] ^= R(x[ 4] + x[ 7], 18) + x[11] ^= R(x[10] + x[ 9], 7) + x[ 8] ^= R(x[11] + x[10], 9) + x[ 9] ^= R(x[ 8] + x[11], 13) + x[10] ^= R(x[ 9] + x[ 8], 18) + x[12] ^= R(x[15] + x[14], 7) + x[13] ^= R(x[12] + x[15], 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) + B[bi + 1] = (B32[i] >> 8 & 0xff) + B[bi + 2] = (B32[i] >> 16 & 0xff) + B[bi + 3] = (B32[i] >> 24 & 0xff) + // 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++) { + D[Di + i] ^= S[Si + i] + } + } + } + + function arraycopy (src, srcPos, dest, destPos, length) { + if (Buffer.isBuffer(src) && Buffer.isBuffer(dest)) { + src.copy(dest, destPos, srcPos, srcPos + length) + } else { + while (length--) { + dest[destPos++] = src[srcPos++] + } + } + } + + 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, + // private key + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // middle + 0xa0, 0x81, 0x85, 0x30, 0x81, 0x82, 0x02, 0x01, 0x01, 0x30, 0x2c, 0x06, 0x07, 0x2a, 0x86, 0x48, + 0xcE, 0x3d, 0x01, 0x01, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xfE, 0xff, 0xff, 0xfc, 0x2f, 0x30, 0x06, 0x04, 0x01, 0x00, 0x04, 0x01, 0x07, 0x04, + 0x21, 0x02, 0x79, 0xbE, 0x66, 0x7E, 0xf9, 0xdc, 0xbb, 0xac, 0x55, 0xa0, 0x62, 0x95, 0xcE, 0x87, + 0x0b, 0x07, 0x02, 0x9b, 0xfc, 0xdb, 0x2d, 0xcE, 0x28, 0xd9, 0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8, + 0x17, 0x98, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xfE, 0xba, 0xaE, 0xdc, 0xE6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5E, + 0x8c, 0xd0, 0x36, 0x41, 0x41, 0x02, 0x01, 0x01, 0xa1, 0x24, 0x03, 0x22, 0x00, + // public key + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00 + ]) + + var EC_PRIVKEY_EXPORT_DER_UNCOMPRESSED = Buffer.from([ + // begin + 0x30, 0x82, 0x01, 0x13, 0x02, 0x01, 0x01, 0x04, 0x20, + // private key + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // middle + 0xa0, 0x81, 0xa5, 0x30, 0x81, 0xa2, 0x02, 0x01, 0x01, 0x30, 0x2c, 0x06, 0x07, 0x2a, 0x86, 0x48, + 0xcE, 0x3d, 0x01, 0x01, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xfE, 0xff, 0xff, 0xfc, 0x2f, 0x30, 0x06, 0x04, 0x01, 0x00, 0x04, 0x01, 0x07, 0x04, + 0x41, 0x04, 0x79, 0xbE, 0x66, 0x7E, 0xf9, 0xdc, 0xbb, 0xac, 0x55, 0xa0, 0x62, 0x95, 0xcE, 0x87, + 0x0b, 0x07, 0x02, 0x9b, 0xfc, 0xdb, 0x2d, 0xcE, 0x28, 0xd9, 0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8, + 0x17, 0x98, 0x48, 0x3a, 0xda, 0x77, 0x26, 0xa3, 0xc4, 0x65, 0x5d, 0xa4, 0xfb, 0xfc, 0x0E, 0x11, + 0x08, 0xa8, 0xfd, 0x17, 0xb4, 0x48, 0xa6, 0x85, 0x54, 0x19, 0x9c, 0x47, 0xd0, 0x8f, 0xfb, 0x10, + 0xd4, 0xb8, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xfE, 0xba, 0xaE, 0xdc, 0xE6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5E, + 0x8c, 0xd0, 0x36, 0x41, 0x41, 0x02, 0x01, 0x01, 0xa1, 0x44, 0x03, 0x42, 0x00, + // public key + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00 + ]) + + exports.privateKeyExport = function (privateKey, publicKey, compressed) { + var result = Buffer.from(compressed ? EC_PRIVKEY_EXPORT_DER_COMPRESSED : EC_PRIVKEY_EXPORT_DER_UNCOMPRESSED) + privateKey.copy(result, compressed ? 8 : 9) + publicKey.copy(result, compressed ? 181 : 214) + return result + } + + exports.privateKeyImport = function (privateKey) { + var length = privateKey.length + + // sequence header + var index = 0 + if (length < index + 1 || privateKey[index] !== 0x30) return + index += 1 + + // sequence length constructor + if (length < index + 1 || !(privateKey[index] & 0x80)) return + + var lenb = privateKey[index] & 0x7f + index += 1 + if (lenb < 1 || lenb > 2) return + if (length < index + lenb) return + + // sequence length + var len = privateKey[index + lenb - 1] | (lenb > 1 ? privateKey[index + lenb - 2] << 8 : 0) + index += lenb + if (length < index + len) return + + // sequence element 0: version number (=1) + if (length < index + 3 || + privateKey[index] !== 0x02 || + privateKey[index + 1] !== 0x01 || + privateKey[index + 2] !== 0x01) { + return + } + index += 3 + + // sequence element 1: octet string, up to 32 bytes + if (length < index + 2 || + privateKey[index] !== 0x04 || + privateKey[index + 1] > 0x20 || + length < index + 2 + privateKey[index + 1]) { + return + } + + return privateKey.slice(index + 2, index + 2 + privateKey[index + 1]) + } + + exports.signatureExport = function (sigObj) { + var r = Buffer.concat([Buffer.from([0]), sigObj.r]) + for (var lenR = 33, posR = 0; lenR > 1 && r[posR] === 0x00 && !(r[posR + 1] & 0x80); --lenR, ++posR); + + var s = Buffer.concat([Buffer.from([0]), sigObj.s]) + for (var lenS = 33, posS = 0; lenS > 1 && s[posS] === 0x00 && !(s[posS + 1] & 0x80); --lenS, ++posS); + + return bip66.encode(r.slice(posR), s.slice(posS)) + } + + exports.signatureImport = function (sig) { + var r = Buffer.alloc(32, 0) + var s = Buffer.alloc(32, 0) + + try { + var sigObj = bip66.decode(sig) + if (sigObj.r.length === 33 && sigObj.r[0] === 0x00) sigObj.r = sigObj.r.slice(1) + if (sigObj.r.length > 32) throw new Error('R length is too long') + if (sigObj.s.length === 33 && sigObj.s[0] === 0x00) sigObj.s = sigObj.s.slice(1) + if (sigObj.s.length > 32) throw new Error('S length is too long') + } catch (err) { + return + } + + sigObj.r.copy(r, 32 - sigObj.r.length) + sigObj.s.copy(s, 32 - sigObj.s.length) + + return { r: r, s: s } + } + + exports.signatureImportLax = function (sig) { + var r = Buffer.alloc(32, 0) + var s = Buffer.alloc(32, 0) + + var length = sig.length + var index = 0 + + // sequence tag byte + if (sig[index++] !== 0x30) return + + // sequence length byte + var lenbyte = sig[index++] + if (lenbyte & 0x80) { + index += lenbyte - 0x80 + if (index > length) return + } + + // sequence tag byte for r + if (sig[index++] !== 0x02) return + + // length for r + var rlen = sig[index++] + if (rlen & 0x80) { + lenbyte = rlen - 0x80 + if (index + lenbyte > length) return + for (; lenbyte > 0 && sig[index] === 0x00; index += 1, lenbyte -= 1); + for (rlen = 0; lenbyte > 0; index += 1, lenbyte -= 1) rlen = (rlen << 8) + sig[index] + } + if (rlen > length - index) return + var rindex = index + index += rlen + + // sequence tag byte for s + if (sig[index++] !== 0x02) return + + // length for s + var slen = sig[index++] + if (slen & 0x80) { + lenbyte = slen - 0x80 + if (index + lenbyte > length) return + for (; lenbyte > 0 && sig[index] === 0x00; index += 1, lenbyte -= 1); + for (slen = 0; lenbyte > 0; index += 1, lenbyte -= 1) slen = (slen << 8) + sig[index] + } + if (slen > length - index) return + var sindex = index + index += slen + + // ignore leading zeros in r + for (; rlen > 0 && sig[rindex] === 0x00; rlen -= 1, rindex += 1); + // copy r value + if (rlen > 32) return + var rvalue = sig.slice(rindex, rindex + rlen) + rvalue.copy(r, 32 - rvalue.length) + + // ignore leading zeros in s + for (; slen > 0 && sig[sindex] === 0x00; slen -= 1, sindex += 1); + // copy s value + if (slen > 32) return + var svalue = sig.slice(sindex, sindex + slen) + svalue.copy(s, 32 - svalue.length) + + return { r: r, s: s } + } + + },{"bip66":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) { + case 0x02: + case 0x03: + if (publicKey.length !== 33) return null + return loadCompressedPublicKey(first, publicKey.slice(1, 33)) + case 0x04: + case 0x06: + case 0x07: + if (publicKey.length !== 65) return null + return loadUncompressedPublicKey(first, publicKey.slice(1, 33), publicKey.slice(33, 65)) + default: + return null + } + } + + exports.privateKeyVerify = function (privateKey) { + var bn = new BN(privateKey) + return bn.cmp(ecparams.n) < 0 && !bn.isZero() + } + + exports.privateKeyExport = function (privateKey, compressed) { + var d = new BN(privateKey) + if (d.cmp(ecparams.n) >= 0 || d.isZero()) throw new Error(messages.EC_PRIVATE_KEY_EXPORT_DER_FAIL) + + return Buffer.from(ec.keyFromPrivate(privateKey).getPublic(compressed, true)) + } + + exports.privateKeyNegate = function (privateKey) { + var bn = new BN(privateKey) + return bn.isZero() ? Buffer.alloc(32) : ecparams.n.sub(bn).umod(ecparams.n).toArrayLike(Buffer, 'be', 32) + } + + exports.privateKeyModInverse = function (privateKey) { + var bn = new BN(privateKey) + if (bn.cmp(ecparams.n) >= 0 || bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_RANGE_INVALID) + + return bn.invm(ecparams.n).toArrayLike(Buffer, 'be', 32) + } + + exports.privateKeyTweakAdd = function (privateKey, tweak) { + var bn = new BN(tweak) + if (bn.cmp(ecparams.n) >= 0) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_ADD_FAIL) + + bn.iadd(new BN(privateKey)) + if (bn.cmp(ecparams.n) >= 0) bn.isub(ecparams.n) + if (bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_ADD_FAIL) + + return bn.toArrayLike(Buffer, 'be', 32) + } + + exports.privateKeyTweakMul = function (privateKey, tweak) { + var bn = new BN(tweak) + if (bn.cmp(ecparams.n) >= 0 || bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_MUL_FAIL) + + bn.imul(new BN(privateKey)) + if (bn.cmp(ecparams.n)) bn = bn.umod(ecparams.n) + + return bn.toArrayLike(Buffer, 'be', 32) + } + + exports.publicKeyCreate = function (privateKey, compressed) { + var d = new BN(privateKey) + if (d.cmp(ecparams.n) >= 0 || d.isZero()) throw new Error(messages.EC_PUBLIC_KEY_CREATE_FAIL) + + return Buffer.from(ec.keyFromPrivate(privateKey).getPublic(compressed, true)) + } + + exports.publicKeyConvert = function (publicKey, compressed) { + var pair = loadPublicKey(publicKey) + if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) + + return Buffer.from(pair.getPublic(compressed, true)) + } + + exports.publicKeyVerify = function (publicKey) { + return loadPublicKey(publicKey) !== null + } + + exports.publicKeyTweakAdd = function (publicKey, tweak, compressed) { + var pair = loadPublicKey(publicKey) + if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) + + tweak = new BN(tweak) + if (tweak.cmp(ecparams.n) >= 0) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_ADD_FAIL) + + 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([ + result.r.toArrayLike(Buffer, 'be', 32), + result.s.toArrayLike(Buffer, 'be', 32) + ]), + recovery: result.recoveryParam + } + } + + exports.verify = function (message, signature, publicKey) { + var sigObj = {r: signature.slice(0, 32), s: signature.slice(32, 64)} + + var sigr = new BN(sigObj.r) + var sigs = new BN(sigObj.s) + if (sigr.cmp(ecparams.n) >= 0 || sigs.cmp(ecparams.n) >= 0) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL) + if (sigs.cmp(ec.nh) === 1 || sigr.isZero() || sigs.isZero()) return false + + var pair = loadPublicKey(publicKey) + if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) + + return ec.verify(message, sigObj, {x: pair.pub.x, y: pair.pub.y}) + } + + exports.recover = function (message, signature, recovery, compressed) { + var sigObj = {r: signature.slice(0, 32), s: signature.slice(32, 64)} + + var sigr = new BN(sigObj.r) + var sigs = new BN(sigObj.s) + if (sigr.cmp(ecparams.n) >= 0 || sigs.cmp(ecparams.n) >= 0) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL) + + try { + if (sigr.isZero() || sigs.isZero()) throw new Error() + + var point = ec.recoverPubKey(message, sigObj, recovery) + return Buffer.from(point.encode(true, compressed)) + } catch (err) { + throw new Error(messages.ECDSA_RECOVER_FAIL) + } + } + + exports.ecdh = function (publicKey, privateKey) { + var shared = exports.ecdhUnsafe(publicKey, privateKey, true) + return createHash('sha256').update(shared).digest() + } + + exports.ecdhUnsafe = function (publicKey, privateKey, compressed) { + var pair = loadPublicKey(publicKey) + if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) + + var scalar = new BN(privateKey) + if (scalar.cmp(ecparams.n) >= 0 || scalar.isZero()) throw new Error(messages.ECDH_FAIL) + + return Buffer.from(pair.pub.mul(scalar).encode(true, compressed)) + } + + },{"../messages.json":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) + for (var i = 0; i < publicKeys.length; ++i) { + assert.isBuffer(publicKeys[i], messages.EC_PUBLIC_KEY_TYPE_INVALID) + assert.isBufferLength2(publicKeys[i], 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) + } + + compressed = initCompressedValue(compressed, true) + + return secp256k1.publicKeyCombine(publicKeys, compressed) + }, + + signatureNormalize: function (signature) { + assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) + assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) + + return secp256k1.signatureNormalize(signature) + }, + + signatureExport: function (signature) { + assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) + assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) + + var sigObj = secp256k1.signatureExport(signature) + return der.signatureExport(sigObj) + }, + + signatureImport: function (sig) { + assert.isBuffer(sig, messages.ECDSA_SIGNATURE_TYPE_INVALID) + assert.isLengthGTZero(sig, messages.ECDSA_SIGNATURE_LENGTH_INVALID) + + var sigObj = der.signatureImport(sig) + if (sigObj) return secp256k1.signatureImport(sigObj) + + throw new Error(messages.ECDSA_SIGNATURE_PARSE_DER_FAIL) + }, + + signatureImportLax: function (sig) { + assert.isBuffer(sig, messages.ECDSA_SIGNATURE_TYPE_INVALID) + assert.isLengthGTZero(sig, messages.ECDSA_SIGNATURE_LENGTH_INVALID) + + var sigObj = der.signatureImportLax(sig) + if (sigObj) return secp256k1.signatureImport(sigObj) + + throw new Error(messages.ECDSA_SIGNATURE_PARSE_DER_FAIL) + }, + + sign: function (message, privateKey, options) { + assert.isBuffer(message, messages.MSG32_TYPE_INVALID) + assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID) + + assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) + assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) + + var data = null + var noncefn = null + if (options !== undefined) { + assert.isObject(options, messages.OPTIONS_TYPE_INVALID) + + if (options.data !== undefined) { + assert.isBuffer(options.data, messages.OPTIONS_DATA_TYPE_INVALID) + assert.isBufferLength(options.data, 32, messages.OPTIONS_DATA_LENGTH_INVALID) + data = options.data + } + + if (options.noncefn !== undefined) { + assert.isFunction(options.noncefn, messages.OPTIONS_NONCEFN_TYPE_INVALID) + noncefn = options.noncefn + } + } + + return secp256k1.sign(message, privateKey, noncefn, data) + }, + + verify: function (message, signature, publicKey) { + assert.isBuffer(message, messages.MSG32_TYPE_INVALID) + assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID) + + assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) + assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) + + assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) + assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) + + return secp256k1.verify(message, signature, publicKey) + }, + + recover: function (message, signature, recovery, compressed) { + assert.isBuffer(message, messages.MSG32_TYPE_INVALID) + assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID) + + assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) + assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) + + assert.isNumber(recovery, messages.RECOVERY_ID_TYPE_INVALID) + assert.isNumberInInterval(recovery, -1, 4, messages.RECOVERY_ID_VALUE_INVALID) + + compressed = initCompressedValue(compressed, true) + + return secp256k1.recover(message, signature, recovery, compressed) + }, + + ecdh: function (publicKey, privateKey) { + assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) + assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) + + assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) + assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) + + return secp256k1.ecdh(publicKey, privateKey) + }, + + ecdhUnsafe: function (publicKey, privateKey, compressed) { + assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) + assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) + + assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) + assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) + + compressed = initCompressedValue(compressed, true) + + return secp256k1.ecdhUnsafe(publicKey, privateKey, compressed) + } + } + } + + },{"./assert":296,"./der":297,"./messages.json":300}],300:[function(require,module,exports){ + module.exports={ + "COMPRESSED_TYPE_INVALID": "compressed should be a boolean", + "EC_PRIVATE_KEY_TYPE_INVALID": "private key should be a Buffer", + "EC_PRIVATE_KEY_LENGTH_INVALID": "private key length is invalid", + "EC_PRIVATE_KEY_RANGE_INVALID": "private key range is invalid", + "EC_PRIVATE_KEY_TWEAK_ADD_FAIL": "tweak out of range or resulting private key is invalid", + "EC_PRIVATE_KEY_TWEAK_MUL_FAIL": "tweak out of range", + "EC_PRIVATE_KEY_EXPORT_DER_FAIL": "couldn't export to DER format", + "EC_PRIVATE_KEY_IMPORT_DER_FAIL": "couldn't import from DER format", + "EC_PUBLIC_KEYS_TYPE_INVALID": "public keys should be an Array", + "EC_PUBLIC_KEYS_LENGTH_INVALID": "public keys Array should have at least 1 element", + "EC_PUBLIC_KEY_TYPE_INVALID": "public key should be a Buffer", + "EC_PUBLIC_KEY_LENGTH_INVALID": "public key length is invalid", + "EC_PUBLIC_KEY_PARSE_FAIL": "the public key could not be parsed or is invalid", + "EC_PUBLIC_KEY_CREATE_FAIL": "private was invalid, try again", + "EC_PUBLIC_KEY_TWEAK_ADD_FAIL": "tweak out of range or resulting public key is invalid", + "EC_PUBLIC_KEY_TWEAK_MUL_FAIL": "tweak out of range", + "EC_PUBLIC_KEY_COMBINE_FAIL": "the sum of the public keys is not valid", + "ECDH_FAIL": "scalar was invalid (zero or overflow)", + "ECDSA_SIGNATURE_TYPE_INVALID": "signature should be a Buffer", + "ECDSA_SIGNATURE_LENGTH_INVALID": "signature length is invalid", + "ECDSA_SIGNATURE_PARSE_FAIL": "couldn't parse signature", + "ECDSA_SIGNATURE_PARSE_DER_FAIL": "couldn't parse DER signature", + "ECDSA_SIGNATURE_SERIALIZE_DER_FAIL": "couldn't serialize signature to DER format", + "ECDSA_SIGN_FAIL": "nonce generation function failed or private key is invalid", + "ECDSA_RECOVER_FAIL": "couldn't recover public key from signature", + "MSG32_TYPE_INVALID": "message should be a Buffer", + "MSG32_LENGTH_INVALID": "message length is invalid", + "OPTIONS_TYPE_INVALID": "options should be an Object", + "OPTIONS_DATA_TYPE_INVALID": "options.data should be a Buffer", + "OPTIONS_DATA_LENGTH_INVALID": "options.data length is invalid", + "OPTIONS_NONCEFN_TYPE_INVALID": "options.noncefn should be a Function", + "RECOVERY_ID_TYPE_INVALID": "recovery should be a Number", + "RECOVERY_ID_VALUE_INVALID": "recovery should have value between -1 and 4", + "TWEAK_TYPE_INVALID": "tweak should be a Buffer", + "TWEAK_LENGTH_INVALID": "tweak length is invalid" + } + + },{}],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++; + semaphore.firstHere = true; + var isFirst = 1; + } else { + 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--; + semaphore.firstHere = false; + } + 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; + } else if (typeof define === 'function' && define.amd) { + // amd export + define(function () { + return semaphore; + }); + } else { + // browser global + global.semaphore = semaphore; + } + }(this)); + + }).call(this,require('_process')) + },{"_process":257}],302:[function(require,module,exports){ + 'use strict'; + module.exports = typeof setImmediate === 'function' ? setImmediate : + function setImmediate() { + var args = [].slice.apply(arguments); + 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) + this._finalSize = finalSize + this._blockSize = blockSize + this._len = 0 + } + + Hash.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8' + data = Buffer.from(data, enc) + } + + var block = this._block + var blockSize = this._blockSize + var length = data.length + var accum = this._len + + for (var offset = 0; offset < length;) { + var assigned = accum % blockSize + var remainder = Math.min(length - offset, blockSize - assigned) + + for (var i = 0; i < remainder; i++) { + block[assigned + i] = data[offset + i] + } + + accum += remainder + offset += remainder + + if ((accum % blockSize) === 0) { + this._update(block) + } + } + + this._len += length + return this + } + + Hash.prototype.digest = function (enc) { + var rem = this._len % this._blockSize + + this._block[rem] = 0x80 + + // zero (rem + 1) trailing bits, where (rem + 1) is the smallest + // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize + this._block.fill(0, rem + 1) + + if (rem >= this._finalSize) { + this._update(this._block) + this._block.fill(0) + } + + var bits = this._len * 8 + + // uint32 + if (bits <= 0xffffffff) { + this._block.writeUInt32BE(bits, this._blockSize - 4) + + // uint64 + } else { + var lowBits = (bits & 0xffffffff) >>> 0 + var highBits = (bits - lowBits) / 0x100000000 + + this._block.writeUInt32BE(highBits, this._blockSize - 8) + this._block.writeUInt32BE(lowBits, this._blockSize - 4) + } + + this._update(this._block) + var hash = this._hash() + + return enc ? hash.toString(enc) : hash + } + + Hash.prototype._update = function () { + throw new Error('_update must be implemented by subclass') + } + + module.exports = Hash + + },{"safe-buffer":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 + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ + + var inherits = require('inherits') + var Hash = require('./hash') + var Buffer = require('safe-buffer').Buffer + + var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ] + + var W = new Array(80) + + function Sha () { + this.init() + this._w = W + + Hash.call(this, 64, 56) + } + + inherits(Sha, Hash) + + Sha.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + + return this + } + + function rotl5 (num) { + return (num << 5) | (num >>> 27) + } + + function rotl30 (num) { + return (num << 30) | (num >>> 2) + } + + function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d + } + + Sha.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16] + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + + e = d + d = c + c = rotl30(b) + b = a + a = t + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 + } + + Sha.prototype._hash = function () { + var H = Buffer.allocUnsafe(20) + + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) + + return H + } + + module.exports = Sha + + },{"./hash":303,"inherits":180,"safe-buffer":290}],306:[function(require,module,exports){ + /* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ + + var inherits = require('inherits') + var Hash = require('./hash') + var Buffer = require('safe-buffer').Buffer + + var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 + ] + + var W = new Array(80) + + function Sha1 () { + this.init() + this._w = W + + Hash.call(this, 64, 56) + } + + inherits(Sha1, Hash) + + Sha1.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + + return this + } + + function rotl1 (num) { + return (num << 1) | (num >>> 31) + } + + function rotl5 (num) { + return (num << 5) | (num >>> 27) + } + + function rotl30 (num) { + return (num << 30) | (num >>> 2) + } + + function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d + } + + Sha1.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]) + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + + e = d + d = c + c = rotl30(b) + b = a + a = t + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 + } + + Sha1.prototype._hash = function () { + var H = Buffer.allocUnsafe(20) + + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) + + return H + } + + module.exports = Sha1 + + },{"./hash":303,"inherits":180,"safe-buffer":290}],307:[function(require,module,exports){ + /** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + + var inherits = require('inherits') + var Sha256 = require('./sha256') + var Hash = require('./hash') + var Buffer = require('safe-buffer').Buffer + + var W = new Array(64) + + function Sha224 () { + this.init() + + this._w = W // new Array(64) + + Hash.call(this, 64, 56) + } + + inherits(Sha224, Sha256) + + Sha224.prototype.init = function () { + this._a = 0xc1059ed8 + this._b = 0x367cd507 + this._c = 0x3070dd17 + this._d = 0xf70e5939 + this._e = 0xffc00b31 + this._f = 0x68581511 + this._g = 0x64f98fa7 + this._h = 0xbefa4fa4 + + return this + } + + Sha224.prototype._hash = function () { + var H = Buffer.allocUnsafe(28) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + + return H + } + + module.exports = Sha224 + + },{"./hash":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 + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + + var inherits = require('inherits') + var Hash = require('./hash') + var Buffer = require('safe-buffer').Buffer + + var K = [ + 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, + 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, + 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, + 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, + 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, + 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, + 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, + 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, + 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, + 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, + 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, + 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, + 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, + 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, + 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, + 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 + ] + + var W = new Array(64) + + function Sha256 () { + this.init() + + this._w = W // new Array(64) + + Hash.call(this, 64, 56) + } + + inherits(Sha256, Hash) + + Sha256.prototype.init = function () { + this._a = 0x6a09e667 + this._b = 0xbb67ae85 + this._c = 0x3c6ef372 + this._d = 0xa54ff53a + this._e = 0x510e527f + this._f = 0x9b05688c + this._g = 0x1f83d9ab + this._h = 0x5be0cd19 + + return this + } + + function ch (x, y, z) { + return z ^ (x & (y ^ z)) + } + + function maj (x, y, z) { + return (x & y) | (z & (x | y)) + } + + function sigma0 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) + } + + function sigma1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) + } + + function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) + } + + function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) + } + + Sha256.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + var f = this._f | 0 + var g = this._g | 0 + var h = this._h | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 + + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 + var T2 = (sigma0(a) + maj(a, b, c)) | 0 + + h = g + g = f + f = e + e = (d + T1) | 0 + d = c + c = b + b = a + a = (T1 + T2) | 0 + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 + this._f = (f + this._f) | 0 + this._g = (g + this._g) | 0 + this._h = (h + this._h) | 0 + } + + Sha256.prototype._hash = function () { + var H = Buffer.allocUnsafe(32) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + H.writeInt32BE(this._h, 28) + + return H + } + + module.exports = Sha256 + + },{"./hash":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 + this._ch = 0x9159015a + this._dh = 0x152fecd8 + this._eh = 0x67332667 + this._fh = 0x8eb44a87 + this._gh = 0xdb0c2e0d + this._hh = 0x47b5481d + + this._al = 0xc1059ed8 + this._bl = 0x367cd507 + this._cl = 0x3070dd17 + this._dl = 0xf70e5939 + this._el = 0xffc00b31 + this._fl = 0x68581511 + this._gl = 0x64f98fa7 + this._hl = 0xbefa4fa4 + + return this + } + + Sha384.prototype._hash = function () { + var H = Buffer.allocUnsafe(48) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + + return H + } + + module.exports = Sha384 + + },{"./hash":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, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 + ] + + var W = new Array(160) + + function Sha512 () { + this.init() + this._w = W + + Hash.call(this, 128, 112) + } + + inherits(Sha512, Hash) + + Sha512.prototype.init = function () { + this._ah = 0x6a09e667 + this._bh = 0xbb67ae85 + this._ch = 0x3c6ef372 + this._dh = 0xa54ff53a + this._eh = 0x510e527f + this._fh = 0x9b05688c + this._gh = 0x1f83d9ab + this._hh = 0x5be0cd19 + + this._al = 0xf3bcc908 + this._bl = 0x84caa73b + this._cl = 0xfe94f82b + this._dl = 0x5f1d36f1 + this._el = 0xade682d1 + this._fl = 0x2b3e6c1f + this._gl = 0xfb41bd6b + this._hl = 0x137e2179 + + return this + } + + function Ch (x, y, z) { + return z ^ (x & (y ^ z)) + } + + function maj (x, y, z) { + return (x & y) | (z & (x | y)) + } + + function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) + } + + function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) + } + + function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) + } + + function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) + } + + function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) + } + + function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) + } + + function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 + } + + Sha512.prototype._update = function (M) { + var W = this._w + + var ah = this._ah | 0 + var bh = this._bh | 0 + var ch = this._ch | 0 + var dh = this._dh | 0 + var eh = this._eh | 0 + var fh = this._fh | 0 + var gh = this._gh | 0 + var hh = this._hh | 0 + + var al = this._al | 0 + var bl = this._bl | 0 + var cl = this._cl | 0 + var dl = this._dl | 0 + var el = this._el | 0 + var fl = this._fl | 0 + var gl = this._gl | 0 + var hl = this._hl | 0 + + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4) + W[i + 1] = M.readInt32BE(i * 4 + 4) + } + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2] + var xl = W[i - 15 * 2 + 1] + var gamma0 = Gamma0(xh, xl) + var gamma0l = Gamma0l(xl, xh) + + xh = W[i - 2 * 2] + xl = W[i - 2 * 2 + 1] + var gamma1 = Gamma1(xh, xl) + var gamma1l = Gamma1l(xl, xh) + + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2] + var Wi7l = W[i - 7 * 2 + 1] + + var Wi16h = W[i - 16 * 2] + var Wi16l = W[i - 16 * 2 + 1] + + var Wil = (gamma0l + Wi7l) | 0 + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 + Wil = (Wil + gamma1l) | 0 + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 + Wil = (Wil + Wi16l) | 0 + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 + + W[i] = Wih + W[i + 1] = Wil + } + + for (var j = 0; j < 160; j += 2) { + Wih = W[j] + Wil = W[j + 1] + + var majh = maj(ah, bh, ch) + var majl = maj(al, bl, cl) + + var sigma0h = sigma0(ah, al) + var sigma0l = sigma0(al, ah) + var sigma1h = sigma1(eh, el) + var sigma1l = sigma1(el, eh) + + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K[j] + var Kil = K[j + 1] + + var chh = Ch(eh, fh, gh) + var chl = Ch(el, fl, gl) + + var t1l = (hl + sigma1l) | 0 + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 + t1l = (t1l + chl) | 0 + t1h = (t1h + chh + getCarry(t1l, chl)) | 0 + t1l = (t1l + Kil) | 0 + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 + t1l = (t1l + Wil) | 0 + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 + + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0 + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 + + hh = gh + hl = gl + gh = fh + gl = fl + fh = eh + fl = el + el = (dl + t1l) | 0 + eh = (dh + t1h + getCarry(el, dl)) | 0 + dh = ch + dl = cl + ch = bh + cl = bl + bh = ah + bl = al + al = (t1l + t2l) | 0 + ah = (t1h + t2h + getCarry(al, t1l)) | 0 + } + + this._al = (this._al + al) | 0 + this._bl = (this._bl + bl) | 0 + this._cl = (this._cl + cl) | 0 + this._dl = (this._dl + dl) | 0 + this._el = (this._el + el) | 0 + this._fl = (this._fl + fl) | 0 + this._gl = (this._gl + gl) | 0 + this._hl = (this._hl + hl) | 0 + + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 + } + + Sha512.prototype._hash = function () { + var H = Buffer.allocUnsafe(64) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + writeInt64BE(this._gh, this._gl, 48) + writeInt64BE(this._hh, this._hl, 56) + + return H + } + + module.exports = Sha512 + + },{"./hash":303,"inherits":180,"safe-buffer":290}],311:[function(require,module,exports){ + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + module.exports = Stream; + + var EE = require('events').EventEmitter; + var inherits = require('inherits'); + + inherits(Stream, EE); + Stream.Readable = require('readable-stream/readable.js'); + Stream.Writable = require('readable-stream/writable.js'); + Stream.Duplex = require('readable-stream/duplex.js'); + Stream.Transform = require('readable-stream/transform.js'); + Stream.PassThrough = require('readable-stream/passthrough.js'); + + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; + + + + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. + + function Stream() { + EE.call(this); + } + + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; + + },{"events":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') + var IncomingMessage = require('./lib/response') + 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', + 'COPY', + 'DELETE', + 'GET', + 'HEAD', + 'LOCK', + 'M-SEARCH', + 'MERGE', + 'MKACTIVITY', + 'MKCOL', + 'MOVE', + 'NOTIFY', + 'OPTIONS', + 'PATCH', + 'POST', + 'PROPFIND', + 'PROPPATCH', + 'PURGE', + 'PUT', + 'REPORT', + 'SEARCH', + 'SUBSCRIBE', + 'TRACE', + 'UNLOCK', + 'UNSUBSCRIBE' + ] + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + },{"./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. + var xhr + 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 + // cross domain), use the page location. Otherwise use example.com + // Note: this doesn't actually make an http request. + try { + xhr.open('GET', global.XDomainRequest ? '/' : 'https://example.com') + } catch(e) { + xhr = null + } + } else { + // Service workers don't have XHR + xhr = null + } + return xhr + } + + function checkTypeSupport (type) { + var xhr = getXHR() + if (!xhr) return false + try { + xhr.responseType = type + return xhr.responseType === type + } 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){ + var capability = require('./capability') + var inherits = require('inherits') + 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' + } else if (capability.mozchunkedarraybuffer) { + return 'moz-chunked-arraybuffer' + } else if (capability.msstream) { + return 'ms-stream' + } else if (capability.arraybuffer && preferBinary) { + return 'arraybuffer' + } else if (capability.vbArray && preferBinary) { + return 'text:vbarray' + } else { + return 'text' + } + } + + var ClientRequest = module.exports = function (opts) { + var self = this + stream.Writable.call(self) + + self._opts = opts + self._body = [] + self._headers = {} + if (opts.auth) + self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64')) + 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)) { + // If the use of XHR should be preferred. Not typically needed. + useFetch = false + preferBinary = true + } else if (opts.mode === 'prefer-streaming') { + // If streaming is a high priority but binary compatibility and + // the accuracy of the 'content-type' header aren't + preferBinary = false + } else if (opts.mode === 'allow-wrong-content-type') { + // If streaming is more important than preserving the 'content-type' header + preferBinary = !capability.overrideMimeType + } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') { + // Use binary if text streaming may corrupt data or the content-type header, or for speed + preferBinary = true + } else { + 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() + // This check is not necessary, but it prevents warnings from browsers about setting unsafe + // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but + // 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') { + if (capability.arraybuffer) { + body = toArrayBuffer(Buffer.concat(self._body)) + } else if (capability.blobConstructor) { + body = new global.Blob(self._body.map(function (buffer) { + return toArrayBuffer(buffer) + }), { + type: (headersObj['content-type'] || {}).value || '' + }) + } else { + // get utf8 string + body = Buffer.concat(self._body).toString() + } + } + + // create flattened list of headers + var headersList = [] + Object.keys(headersObj).forEach(function (keyName) { + var name = headersObj[keyName].name + var value = headersObj[keyName].value + if (Array.isArray(value)) { + value.forEach(function (v) { + headersList.push([name, v]) + }) + } else { + 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') + if (self._fetchAbortController) + self._fetchAbortController.abort() + }, opts.requestTimeout) + } + } + + global.fetch(self._opts.url, { + method: self._opts.method, + headers: headersList, + body: body || undefined, + mode: 'cors', + credentials: opts.withCredentials ? 'include' : 'same-origin', + signal: signal + }).then(function (response) { + self._fetchResponse = response + self._connect() + }, function (reason) { + self.emit('error', reason) + }) + } else { + var xhr = self._xhr = new global.XMLHttpRequest() + try { + xhr.open(self._opts.method, self._opts.url, true) + } catch (err) { + process.nextTick(function () { + self.emit('error', err) + }) + 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) { + case rStates.LOADING: + case rStates.DONE: + self._onXHRProgress() + break + } + } + // Necessary for streaming in Firefox, since xhr.response is ONLY defined + // in onprogress, not in onreadystatechange with xhr.readyState = 3 + if (self._mode === 'moz-chunked-arraybuffer') { + xhr.onprogress = function () { + self._onXHRProgress() + } + } + + xhr.onerror = function () { + if (self._destroyed) + return + self.emit('error', new Error('XHR error')) + } + + try { + xhr.send(body) + } catch (err) { + process.nextTick(function () { + self.emit('error', err) + }) + return + } + } + } + + /** + * Checks if xhr.status is readable and non-zero, indicating no error. + * Even though the spec says it should be available in readyState 3, + * accessing it throws an exception in IE8 + */ + function statusValid (xhr) { + try { + var status = xhr.status + return (status !== null && status !== 0) + } catch (e) { + 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 + if (self._response) + self._response._destroyed = true + if (self._xhr) + self._xhr.abort() + 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', + 'accept-encoding', + 'access-control-request-headers', + 'access-control-request-method', + 'connection', + 'content-length', + 'cookie', + 'cookie2', + 'date', + 'dnt', + 'expect', + 'host', + 'keep-alive', + 'origin', + 'referer', + 'te', + 'trailer', + 'transfer-encoding', + 'upgrade', + '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, + HEADERS_RECEIVED: 2, + 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 + process.nextTick(function () { + 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) { + return new Promise(function (resolve, reject) { + if (self._destroyed) { + return + } else if(self.push(new Buffer(chunk))) { + resolve() + } else { + self._resumeFetch = resolve + } + }) + }, + close: function () { + if (!self._destroyed) + self.push(null) + }, + abort: function (err) { + if (!self._destroyed) + self.emit('error', err) + } + }) + + try { + response.body.pipeTo(writable) + return + } catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this + } + // fallback for when writableStream or pipeTo aren't available + var reader = response.body.getReader() + function read () { + reader.read().then(function (result) { + if (self._destroyed) + return + if (result.done) { + self.push(null) + return + } + self.push(new Buffer(result.value)) + read() + }).catch(function(err) { + if (!self._destroyed) + self.emit('error', err) + }) + } + read() + } else { + self._xhr = xhr + self._pos = 0 + + self.url = xhr.responseURL + self.statusCode = xhr.status + self.statusMessage = xhr.statusText + var headers = xhr.getAllResponseHeaders().split(/\r?\n/) + headers.forEach(function (header) { + var matches = header.match(/^([^:]+):\s*(.*)/) + if (matches) { + var key = matches[1].toLowerCase() + if (key === 'set-cookie') { + if (self.headers[key] === undefined) { + self.headers[key] = [] + } + self.headers[key].push(matches[2]) + } else if (self.headers[key] !== undefined) { + self.headers[key] += ', ' + matches[2] + } else { + self.headers[key] = matches[2] + } + self.rawHeaders.push(matches[1], matches[2]) + } + }) + + self._charset = 'x-user-defined' + if (!capability.overrideMimeType) { + var mimeType = self.rawHeaders['mime-type'] + if (mimeType) { + var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/) + if (charsetMatch) { + self._charset = charsetMatch[1].toLowerCase() + } + } + if (!self._charset) + self._charset = 'utf-8' // best guess + } + } + } + + 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 + if (xhr.readyState !== rStates.DONE) + break + try { + // This fails in IE8 + response = new global.VBArray(xhr.responseBody).toArray() + } catch (e) {} + if (response !== null) { + self.push(new Buffer(response)) + break + } + // 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 + } catch (e) { + self._mode = 'text:vbarray' + break + } + if (response.length > self._pos) { + var newData = response.substr(self._pos) + if (self._charset === 'x-user-defined') { + 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) + } + self._pos = response.length + } + break + case 'arraybuffer': + if (xhr.readyState !== rStates.DONE || !xhr.response) + break + response = xhr.response + self.push(new Buffer(new Uint8Array(response))) + break + case 'moz-chunked-arraybuffer': // take whole + response = xhr.response + if (xhr.readyState !== rStates.LOADING || !response) + break + self.push(new Buffer(new Uint8Array(response))) + break + case 'ms-stream': + response = xhr.response + if (xhr.readyState !== rStates.LOADING) + break + var reader = new global.MSStreamReader() + reader.onprogress = function () { + if (reader.result.byteLength > self._pos) { + self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos)))) + self._pos = reader.result.byteLength + } + } + reader.onload = function () { + self.push(null) + } + // reader.onerror = ??? // TODO: this + 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'; + module.exports = function (str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { + 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()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } + }; + + function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } + }; + + // Do not cache `Buffer.isEncoding` when checking encoding names as some + // modules monkey-patch it to support additional encodings + function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. + exports.StringDecoder = StringDecoder; + function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); + } + + StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; + }; + + StringDecoder.prototype.end = utf8End; + + // Returns only complete characters in a Buffer + StringDecoder.prototype.text = utf8Text; + + // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer + StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; + }; + + // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a + // continuation byte. + 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. + function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; + } + + // Validates as many continuation bytes for a multi-byte UTF-8 character as + // needed or are available. If we see a non-continuation byte where we expect + // one, we "replace" the validated continuation bytes we've seen so far with + // UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding + // behavior. The continuation byte check is included three times in the case + // where all of the continuation bytes for a character exist in the same buffer. + // It is also done this way as a slight performance increase instead of using a + // loop. + function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'.repeat(p); + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'.repeat(p + 1); + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'.repeat(p + 2); + } + } + } + } + + // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. + function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; + } + + // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a + // partial character, the character's bytes are buffered until the required + // number of bytes are available. + function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); + } + + // For UTF-8, a replacement character for each buffered byte of a (partial) + // character needs to be added to the output. + function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + 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 + // decode the last character properly. + function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); + } + + // For UTF-16LE we do not explicitly append special replacement characters if we + // end on a partial character, we simply let v8 handle that. + function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; + } + + function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); + } + + function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; + } + + // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) + function simpleWrite(buf) { + return buf.toString(this.encoding); + } + + function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; + } + },{"safe-buffer":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 + * @return {String|Optional} a string by pass if necessary + */ + module.exports = function stripHexPrefix(str) { + if (typeof str !== 'string') { + return str; + } + + return isHexPrefixed(str) ? str.slice(2) : str; + } + + },{"is-hex-prefixed":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 }; + var path = { join: unavailable, slice: unavailable }; + var child_process = { spawn: unavailable }; + var mimetype = { lookup: unavailable }; + var defaultArchives = {}; + var downloadUrl = null; + var request = require("xhr-request-promise"); + var bytes = require("eth-lib/lib/bytes"); + var hash = require("./swarm-hash.js"); + var pick = require("./pick.js"); + var swarm = require("./swarm"); + + module.exports = swarm({ + fsp: fsp, + files: files, + os: os, + path: path, + child_process: child_process, + defaultArchives: defaultArchives, + mimetype: mimetype, + request: request, + downloadUrl: downloadUrl, + bytes: bytes, + hash: hash, + pick: pick + }); + },{"./pick.js":320,"./swarm":322,"./swarm-hash.js":321,"eth-lib/lib/bytes":133,"xhr-request-promise":411}],320:[function(require,module,exports){ + var picker = function picker(type) { + return function () { + return new Promise(function (resolve, reject) { + var fileLoader = function fileLoader(e) { + var directory = {}; + var totalFiles = e.target.files.length; + var loadedFiles = 0; + [].map.call(e.target.files, function (file) { + var reader = new FileReader(); + reader.onload = function (e) { + var data = new Uint8Array(e.target.result); + if (type === "directory") { + var path = file.webkitRelativePath; + directory[path.slice(path.indexOf("/") + 1)] = { + type: "text/plain", + data: data + }; + if (++loadedFiles === totalFiles) resolve(directory); + } else if (type === "file") { + var _path = file.webkitRelativePath; + resolve({ "type": mimetype.lookup(_path), "data": data }); + } else { + resolve(data); + } + }; + reader.readAsArrayBuffer(file); + }); + }; + + var fileInput = void 0; + if (type === "directory") { + fileInput = document.createElement("input"); + fileInput.addEventListener("change", fileLoader); + fileInput.type = "file"; + fileInput.webkitdirectory = true; + fileInput.mozdirectory = true; + fileInput.msdirectory = true; + fileInput.odirectory = true; + fileInput.directory = true; + } else { + fileInput = document.createElement("input"); + 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"), + directory: picker("directory") + }; + },{}],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") { + data = Bytes.fromString(data); + } 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 + // slightly better long-term solution would be to split this file into two, + // separating the functions that are used on Node.js from the functions that + // are used only on the browser. + module.exports = function (_ref) { + var fsp = _ref.fsp, + files = _ref.files, + os = _ref.os, + path = _ref.path, + child_process = _ref.child_process, + mimetype = _ref.mimetype, + defaultArchives = _ref.defaultArchives, + request = _ref.request, + downloadUrl = _ref.downloadUrl, + 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) { + return function (val) { + return function (map) { + return map[key] = val, map; + }; + }; + }; + + // String -> JSON -> Map String JSON + // Merges an array of keys and an array of vals into an object. + var toMap = function toMap(keys) { + return function (vals) { + var map = {}; + for (var i = 0, l = keys.length; i < l; ++i) { + map[keys[i]] = vals[i]; + }return map; + }; + }; + + // ∀ a . Map String a -> Map String a -> Map String a + // Merges two maps into one. + var merge = function merge(a) { + return function (b) { + var map = {}; + for (var key in a) { + map[key] = a[key]; + }for (var _key in b) { + map[_key] = b[_key]; + }return map; + }; + }; + + // ∀ a . [a] -> [a] -> Bool + var equals = function equals(a) { + return function (b) { + if (a.length !== b.length) { + return false; + } else { + for (var i = 0, l = a.length; i < a; ++i) { + if (a[i] !== b[i]) return false; + } + } + 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) { + return function (hash) { + return request(rawUrl(swarmUrl)(hash), { responseType: "arraybuffer" }).then(function (arrayBuffer) { + var uint8Array = new Uint8Array(arrayBuffer); + var error404 = [52, 48, 52, 32, 112, 97, 103, 101, 32, 110, 111, 116, 32, 102, 111, 117, 110, 100, 10]; + if (equals(uint8Array)(error404)) throw "Error 404."; + return uint8Array; + }); + }; + }; + + // 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. + var downloadEntries = function downloadEntries(swarmUrl) { + return function (hash) { + var search = function search(hash) { + return function (path) { + return function (routes) { + // Formats an entry to the Swarm.js type. + var format = function format(entry) { + return { + 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 + var downloadEntry = function downloadEntry(entry) { + if (entry.path === undefined) { + return Promise.resolve(); + } else { + 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; + }).then(function (entries) { + return Promise.all(entries.map(downloadEntry)); + }).then(function () { + return routes; + }); + }; + }; + }; + + return search(hash)("")({}); + }; + }; + + // String -> String -> Promise (Map String String) + // Same as `downloadEntries`, but returns only hashes (no types). + var downloadRoutes = function downloadRoutes(swarmUrl) { + return function (hash) { + return downloadEntries(swarmUrl)(hash).then(function (entries) { + return toMap(Object.keys(entries))(Object.keys(entries).map(function (route) { + return entries[route].hash; + })); + }); + }; + }; + + // String -> String -> Promise (Map String File) + // Gets the entire directory tree in a Swarm address. + // Returns a promise mapping paths to file contents. + var downloadDirectory = function downloadDirectory(swarmUrl) { + return function (hash) { + return downloadEntries(swarmUrl)(hash).then(function (entries) { + var paths = Object.keys(entries); + var hashs = paths.map(function (path) { + return entries[path].hash; + }); + var types = paths.map(function (path) { + return entries[path].type; + }); + var datas = hashs.map(downloadData(swarmUrl)); + var files = function files(datas) { + return datas.map(function (data, i) { + return { type: types[i], data: data }; + }); + }; + return Promise.all(datas).then(function (datas) { + return toMap(paths)(files(datas)); + }); + }); + }; + }; + + // String -> String -> String -> Promise String + // Gets the raw contents of a Swarm hash address. + // Returns a promise with the downloaded file path. + var downloadDataToDisk = function downloadDataToDisk(swarmUrl) { + return function (hash) { + return function (filePath) { + return files.download(rawUrl(swarmUrl)(hash))(filePath); + }; + }; + }; + + // String -> String -> String -> Promise (Map String String) + // Gets the entire directory tree in a Swarm address. + // Returns a promise mapping paths to file contents. + var downloadDirectoryToDisk = function downloadDirectoryToDisk(swarmUrl) { + return function (hash) { + return function (dirPath) { + return downloadRoutes(swarmUrl)(hash).then(function (routingTable) { + var downloads = []; + for (var route in routingTable) { + if (route.length > 0) { + var filePath = path.join(dirPath, route); + downloads.push(downloadDataToDisk(swarmUrl)(routingTable[route])(filePath)); + }; + }; + return Promise.all(downloads).then(function () { + return dirPath; + }); + }); + }; + }; + }; + + // String -> Uint8Array -> Promise String + // Uploads raw data to Swarm. + // Returns a promise with the uploaded hash. + var uploadData = function uploadData(swarmUrl) { + return function (data) { + return request(swarmUrl + "/bzzr:/", { + body: typeof data === "string" ? fromString(data) : data, + 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. + // FIXME: for some reasons Swarm-Gateways is sometimes returning + // error 404 (bad request), so we retry up to 3 times. Why? + var uploadToManifest = function uploadToManifest(swarmUrl) { + return function (hash) { + return function (route) { + return function (file) { + var attempt = function attempt(n) { + var slashRoute = route[0] === "/" ? route : "/" + route; + var url = swarmUrl + "/bzz:/" + hash + slashRoute; + var opt = { + method: "PUT", + headers: { "Content-Type": file.type }, + body: file.data }; + return request(url, opt).then(function (response) { + if (response.indexOf("error") !== -1) { + throw response; + } + return response; + }).catch(function (e) { + return n > 0 && attempt(n - 1); + }); + }; + return attempt(3); + }; + }; + }; + }; + + // 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) { + return fsp.readFile(filePath).then(function (data) { + return uploadFile(swarmUrl)({ type: mimetype.lookup(filePath), data: data }); + }); + }; + }; + + // String -> Map String File -> Promise String + // Uploads a directory to Swarm. The directory is + // represented as a map of routes and files. + // A default path is encoded by having a "" route. + var uploadDirectory = function uploadDirectory(swarmUrl) { + return function (directory) { + return uploadData(swarmUrl)("{}").then(function (hash) { + var uploadRoute = function uploadRoute(route) { + return function (hash) { + return uploadToManifest(swarmUrl)(hash)(route)(directory[route]); + }; + }; + var uploadToHash = function uploadToHash(hash, route) { + return hash.then(uploadRoute(route)); + }; + return Object.keys(directory).reduce(uploadToHash, Promise.resolve(hash)); + }); + }; + }; + + // 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) { + return function (dirPath) { + return files.directoryTree(dirPath).then(function (fullPaths) { + return Promise.all(fullPaths.map(function (path) { + return fsp.readFile(path); + })).then(function (datas) { + var paths = fullPaths.map(function (path) { + return path.slice(dirPath.length); + }); + var types = fullPaths.map(function (path) { + return mimetype.lookup(path) || "text/plain"; + }); + return toMap(paths)(datas.map(function (data, i) { + return { type: types[i], data: data }; + })); + }); + }).then(function (directory) { + return merge(defaultPath ? { "": directory[defaultPath] } : {})(directory); + }).then(uploadDirectory(swarmUrl)); + }; + }; + }; + + // String -> UploadInfo -> Promise String + // Simplified multi-type upload which calls the correct + // one based on the type of the argument given. + var _upload = function _upload(swarmUrl) { + return function (arg) { + // 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) { + case "data": + return uploadDataFromDisk(swarmUrl)(arg.path); + case "file": + return uploadFileFromDisk(swarmUrl)(arg.path); + 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 + // directory or a file. + var _download = function _download(swarmUrl) { + return function (hash) { + return function (path) { + return isDirectory(swarmUrl)(hash).then(function (isDir) { + if (isDir) { + return path ? downloadDirectoryToDisk(swarmUrl)(hash)(path) : downloadDirectory(swarmUrl)(hash); + } else { + return path ? downloadDataToDisk(swarmUrl)(hash)(path) : downloadData(swarmUrl)(hash); + } + }); + }; + }; + }; + + // 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. + // If it was already there to begin with, skips the download. + var downloadBinary = function downloadBinary(path, archives) { + var system = os.platform().replace("win32", "windows") + "-" + (os.arch() === "x64" ? "amd64" : "386"); + var archive = (archives || defaultArchives)[system]; + var archiveUrl = downloadUrl + archive.archive + ".tar.gz"; + var archiveMD5 = archive.archiveMD5; + var binaryMD5 = archive.binaryMD5; + return files.safeDownloadArchived(archiveUrl)(archiveMD5)(binaryMD5)(path); + }; + + // type SwarmSetup = { + // account : String, + // password : String, + // dataDir : String, + // binPath : String, + // ensApi : String, + // onDownloadProgress : Number ~> (), + // archives : [{ + // archive: String, + // binaryMD5: String, + // 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; + }; + }; + var account = swarmSetup.account, + password = swarmSetup.password, + 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 () { + state = STARTING; + swarmProcess.stdin.write(password + '\n'); + }, 500); + } else if (hasString(LISTENING_HOOK)(data)) { + state = LISTENING; + clearTimeout(timeout); + 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); + }; + var error = function error() { + return reject(new Error("Couldn't start swarm process.")); + }; + var timeout = setTimeout(error, 20000); + }); + }; + + // Process ~> Promise () + // Stops the Swarm process. + var stopProcess = function stopProcess(process) { + return new Promise(function (resolve, reject) { + process.stderr.removeAllListeners('data'); + process.stdout.removeAllListeners('data'); + process.stdin.removeAllListeners('error'); + 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 + // downloads the Swarm binaries to the dataDir (if not there), checksums, + // starts the Swarm process and calls the callback function with an API + // object using the local node. That callback must return a promise which + // will resolve when it is done using the API, so that this function can + // close the Swarm process properly. Returns a promise that resolves when the + // user is done with the API and the Swarm process is closed. + // TODO: check if Swarm process is already running (improve `isAvailable`) + var local = function local(swarmSetup) { + return function (useAPI) { + return _isAvailable("http://localhost:8500").then(function (isAvailable) { + return isAvailable ? useAPI(at("http://localhost:8500")).then(function () {}) : downloadBinary(swarmSetup.binPath, swarmSetup.archives).onData(function (data) { + return (swarmSetup.onProgress || function () {})(data.length); + }).then(function () { + return startProcess(swarmSetup); + }).then(function (process) { + return useAPI(at("http://localhost:8500")).then(function () { + return process; + }); + }).then(stopProcess); + }); + }; + }; + + // String ~> Promise Bool + // Returns true if Swarm is available on `url`. + // Perfoms a test upload to determine that. + // TODO: improve this? + var _isAvailable = function _isAvailable(swarmUrl) { + var testFile = "test"; + var testHash = "c9a99c7d326dcc6316f32fe2625b311f6dc49a175e6877681ded93137d3569e7"; + return uploadData(swarmUrl)(testFile).then(function (hash) { + return hash === testHash; + }).catch(function () { + 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. + // TODO: improve this? + var isDirectory = function isDirectory(swarmUrl) { + return function (hash) { + return downloadData(swarmUrl)(hash).then(function (data) { + try { + return !!JSON.parse(toString(data)).entries; + } catch (e) { + return false; + } + }); + }; + }; + + // 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) { + var p; + // Hardcoded because efficiency (`arguments` is very slow). + if (typeof a !== "undefined") p = f(a); + if (typeof b !== "undefined") p = f(b); + if (typeof c !== "undefined") p = f(c); + if (typeof d !== "undefined") p = f(d); + if (typeof e !== "undefined") p = f(e); + 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) { + return { + download: function download(hash, path) { + return _download(swarmUrl)(hash)(path); + }, + downloadData: uncurry(downloadData(swarmUrl)), + downloadDataToDisk: uncurry(downloadDataToDisk(swarmUrl)), + downloadDirectory: uncurry(downloadDirectory(swarmUrl)), + downloadDirectoryToDisk: uncurry(downloadDirectoryToDisk(swarmUrl)), + downloadEntries: uncurry(downloadEntries(swarmUrl)), + downloadRoutes: uncurry(downloadRoutes(swarmUrl)), + isAvailable: function isAvailable() { + return _isAvailable(swarmUrl); + }, + upload: function upload(arg) { + return _upload(swarmUrl)(arg); + }, + uploadData: uncurry(uploadData(swarmUrl)), + uploadFile: uncurry(uploadFile(swarmUrl)), + uploadFileFromDisk: uncurry(uploadFile(swarmUrl)), + uploadDataFromDisk: uncurry(uploadDataFromDisk(swarmUrl)), + uploadDirectory: uncurry(uploadDirectory(swarmUrl)), + uploadDirectoryFromDisk: uncurry(uploadDirectoryFromDisk(swarmUrl)), + uploadToManifest: uncurry(uploadToManifest(swarmUrl)), + pick: pick, + hash: hash, + fromString: fromString, + toString: toString + }; + }; + + return { + at: at, + local: local, + download: _download, + downloadBinary: downloadBinary, + downloadData: downloadData, + downloadDataToDisk: downloadDataToDisk, + downloadDirectory: downloadDirectory, + downloadDirectoryToDisk: downloadDirectoryToDisk, + downloadEntries: downloadEntries, + downloadRoutes: downloadRoutes, + isAvailable: _isAvailable, + startProcess: startProcess, + stopProcess: stopProcess, + upload: _upload, + uploadData: uploadData, + uploadDataFromDisk: uploadDataFromDisk, + uploadFile: uploadFile, + uploadFileFromDisk: uploadFileFromDisk, + uploadDirectory: uploadDirectory, + uploadDirectoryFromDisk: uploadDirectoryFromDisk, + uploadToManifest: uploadToManifest, + pick: pick, + hash: hash, + fromString: fromString, + 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) { + // If the buffer isn't a subarray, return the underlying ArrayBuffer + if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) { + return buf.buffer + } else if (typeof buf.buffer.slice === 'function') { + // Otherwise we need to get a proper copy + 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) + var arrayCopy = new Uint8Array(buf.length) + var len = buf.length + for (var i = 0; i < len; i++) { + arrayCopy[i] = buf[i] + } + return arrayCopy.buffer + } else { + 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 + nativeIsArray = Array.isArray, + 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. + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = _; + } + exports._ = _; + } 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. + var optimizeCb = function(func, context, argCount) { + if (context === void 0) return func; + switch (argCount == null ? 3 : argCount) { + case 1: return function(value) { + return func.call(context, value); + }; + case 2: return function(value, other) { + return func.call(context, value, other); + }; + case 3: return function(value, index, collection) { + return func.call(context, value, index, collection); + }; + case 4: return function(accumulator, value, index, collection) { + return func.call(context, accumulator, value, index, collection); + }; + } + return function() { + 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. + var cb = function(value, context, argCount) { + if (value == null) return _.identity; + if (_.isFunction(value)) return optimizeCb(value, context, argCount); + if (_.isObject(value)) return _.matcher(value); + return _.property(value); + }; + _.iteratee = function(value, context) { + return cb(value, context, Infinity); + }; + + // An internal function for creating assigner functions. + var createAssigner = function(keysFunc, undefinedOnly) { + return function(obj) { + var length = arguments.length; + if (length < 2 || obj == null) return obj; + for (var index = 1; index < length; index++) { + var source = arguments[index], + keys = keysFunc(source), + l = keys.length; + for (var i = 0; i < l; i++) { + var key = keys[i]; + if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key]; + } + } + return obj; + }; + }; + + // An internal function for creating a new object that inherits from another. + var baseCreate = function(prototype) { + if (!_.isObject(prototype)) return {}; + if (nativeCreate) return nativeCreate(prototype); + Ctor.prototype = prototype; + var result = new Ctor; + 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 + // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094 + var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; + var getLength = property('length'); + var isArrayLike = function(collection) { + 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. + _.each = _.forEach = function(obj, iteratee, context) { + iteratee = optimizeCb(iteratee, context); + var i, length; + if (isArrayLike(obj)) { + for (i = 0, length = obj.length; i < length; i++) { + iteratee(obj[i], i, obj); + } + } else { + var keys = _.keys(obj); + for (i = 0, length = keys.length; i < length; i++) { + iteratee(obj[keys[i]], keys[i], obj); + } + } + return obj; + }; + + // Return the results of applying the iteratee to each element. + _.map = _.collect = function(obj, iteratee, context) { + iteratee = cb(iteratee, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length, + results = Array(length); + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + results[index] = iteratee(obj[currentKey], currentKey, obj); + } + return results; + }; + + // Create a reducing function iterating left or right. + function createReduce(dir) { + // Optimized iterator function as using arguments.length + // in the main function will deoptimize the, see #1991. + function iterator(obj, iteratee, memo, keys, index, length) { + for (; index >= 0 && index < length; index += dir) { + var currentKey = keys ? keys[index] : index; + memo = iteratee(memo, obj[currentKey], currentKey, obj); + } + return memo; + } + + return function(obj, iteratee, memo, context) { + iteratee = optimizeCb(iteratee, context, 4); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length, + index = dir > 0 ? 0 : length - 1; + // Determine the initial value if none is provided. + if (arguments.length < 3) { + memo = obj[keys ? keys[index] : index]; + index += dir; + } + 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; + if (isArrayLike(obj)) { + key = _.findIndex(obj, predicate, context); + } else { + key = _.findKey(obj, predicate, context); + } + 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) { + var results = []; + predicate = cb(predicate, context); + _.each(obj, function(value, index, list) { + if (predicate(value, index, list)) results.push(value); + }); + 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) { + predicate = cb(predicate, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length; + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + if (!predicate(obj[currentKey], currentKey, obj)) return false; + } + return true; + }; + + // Determine if at least one element in the object matches a truth test. + // Aliased as `any`. + _.some = _.any = function(obj, predicate, context) { + predicate = cb(predicate, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length; + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + if (predicate(obj[currentKey], currentKey, obj)) return true; + } + 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) { + if (!isArrayLike(obj)) obj = _.values(obj); + 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); + var isFunc = _.isFunction(method); + return _.map(obj, function(value) { + var func = isFunc ? method : value[method]; + 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, + value, computed; + if (iteratee == null && obj != null) { + obj = isArrayLike(obj) ? obj : _.values(obj); + for (var i = 0, length = obj.length; i < length; i++) { + value = obj[i]; + if (value > result) { + result = value; + } + } + } else { + iteratee = cb(iteratee, context); + _.each(obj, function(value, index, list) { + computed = iteratee(value, index, list); + if (computed > lastComputed || computed === -Infinity && result === -Infinity) { + result = value; + lastComputed = computed; + } + }); + } + return result; + }; + + // Return the minimum element (or element-based computation). + _.min = function(obj, iteratee, context) { + var result = Infinity, lastComputed = Infinity, + value, computed; + if (iteratee == null && obj != null) { + obj = isArrayLike(obj) ? obj : _.values(obj); + for (var i = 0, length = obj.length; i < length; i++) { + value = obj[i]; + if (value < result) { + result = value; + } + } + } else { + iteratee = cb(iteratee, context); + _.each(obj, function(value, index, list) { + computed = iteratee(value, index, list); + if (computed < lastComputed || computed === Infinity && result === Infinity) { + result = value; + lastComputed = computed; + } + }); + } + 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) { + var set = isArrayLike(obj) ? obj : _.values(obj); + var length = set.length; + var shuffled = Array(length); + for (var index = 0, rand; index < length; index++) { + rand = _.random(0, index); + if (rand !== index) shuffled[index] = shuffled[rand]; + shuffled[rand] = set[index]; + } + 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`. + _.sample = function(obj, n, guard) { + if (n == null || guard) { + if (!isArrayLike(obj)) obj = _.values(obj); + return obj[_.random(obj.length - 1)]; + } + 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); + return _.pluck(_.map(obj, function(value, index, list) { + return { + value: value, + index: index, + criteria: iteratee(value, index, list) + }; + }).sort(function(left, right) { + var a = left.criteria; + var b = right.criteria; + if (a !== b) { + if (a > b || a === void 0) return 1; + if (a < b || b === void 0) return -1; + } + return left.index - right.index; + }), 'value'); + }; + + // An internal function used for aggregate "group by" operations. + var group = function(behavior) { + return function(obj, iteratee, context) { + var result = {}; + iteratee = cb(iteratee, context); + _.each(obj, function(value, index) { + var key = iteratee(value, index, obj); + behavior(result, value, key); + }); + 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 []; + if (_.isArray(obj)) return slice.call(obj); + 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) { + predicate = cb(predicate, context); + var pass = [], fail = []; + _.each(obj, function(value, key, obj) { + (predicate(value, key, obj) ? pass : fail).push(value); + }); + 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`. + _.first = _.head = _.take = function(array, n, guard) { + if (array == null) return void 0; + 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) { + if (array == null) return void 0; + 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; + for (var i = startIndex || 0, length = getLength(input); i < length; i++) { + var value = input[i]; + if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) { + //flatten current level of array or arguments object + if (!shallow) value = flatten(value, shallow, strict); + var j = 0, len = value.length; + output.length += len; + while (j < len) { + output[idx++] = value[j++]; + } + } else if (!strict) { + output[idx++] = value; + } + } + 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`. + _.uniq = _.unique = function(array, isSorted, iteratee, context) { + if (!_.isBoolean(isSorted)) { + context = iteratee; + iteratee = isSorted; + isSorted = false; + } + if (iteratee != null) iteratee = cb(iteratee, context); + var result = []; + var seen = []; + for (var i = 0, length = getLength(array); i < length; i++) { + var value = array[i], + computed = iteratee ? iteratee(value, i, array) : value; + if (isSorted) { + if (!i || seen !== computed) result.push(value); + seen = computed; + } else if (iteratee) { + if (!_.contains(seen, computed)) { + seen.push(computed); + result.push(value); + } + } else if (!_.contains(result, value)) { + result.push(value); + } + } + 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) { + var result = []; + var argsLength = arguments.length; + for (var i = 0, length = getLength(array); i < length; i++) { + var item = array[i]; + if (_.contains(result, item)) continue; + for (var j = 1; j < argsLength; j++) { + if (!_.contains(arguments[j], item)) break; + } + if (j === argsLength) result.push(item); + } + 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) { + var rest = flatten(arguments, true, true, 1); + return _.filter(array, function(value){ + 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. + _.object = function(list, values) { + var result = {}; + for (var i = 0, length = getLength(list); i < length; i++) { + if (values) { + result[list[i]] = values[i]; + } else { + result[list[i][0]] = list[i][1]; + } + } + return result; + }; + + // Generator function to create the findIndex and findLastIndex functions + function createPredicateIndexFinder(dir) { + return function(array, predicate, context) { + predicate = cb(predicate, context); + var length = getLength(array); + var index = dir > 0 ? 0 : length - 1; + for (; index >= 0 && index < length; index += dir) { + if (predicate(array[index], index, array)) return index; + } + 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) { + iteratee = cb(iteratee, context, 1); + var value = iteratee(obj); + var low = 0, high = getLength(array); + while (low < high) { + var mid = Math.floor((low + high) / 2); + if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; + } + return low; + }; + + // Generator function to create the indexOf and lastIndexOf functions + function createIndexFinder(dir, predicateFind, sortedIndex) { + return function(array, item, idx) { + var i = 0, length = getLength(array); + if (typeof idx == 'number') { + if (dir > 0) { + i = idx >= 0 ? idx : Math.max(idx + length, i); + } else { + length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; + } + } else if (sortedIndex && idx && length) { + idx = sortedIndex(array, item); + return array[idx] === item ? idx : -1; + } + if (item !== item) { + idx = predicateFind(slice.call(array, i, length), _.isNaN); + return idx >= 0 ? idx + i : -1; + } + for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) { + if (array[idx] === item) return idx; + } + 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). + _.range = function(start, stop, step) { + if (stop == null) { + stop = start || 0; + 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) { + if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args); + var self = baseCreate(sourceFunc.prototype); + var result = sourceFunc.apply(self, args); + 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. + _.bind = function(func, context) { + if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); + if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); + var args = slice.call(arguments, 2); + var bound = function() { + return executeBound(func, bound, context, this, args.concat(slice.call(arguments))); + }; + 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. + _.partial = function(func) { + var boundArgs = slice.call(arguments, 1); + var bound = function() { + var position = 0, length = boundArgs.length; + var args = Array(length); + for (var i = 0; i < length; i++) { + args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i]; + } + while (position < arguments.length) args.push(arguments[position++]); + return executeBound(func, bound, this, this, args); + }; + 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. + _.bindAll = function(obj) { + var i, length = arguments.length, key; + if (length <= 1) throw new Error('bindAll must be passed function names'); + for (i = 1; i < length; i++) { + key = arguments[i]; + obj[key] = _.bind(obj[key], obj); + } + return obj; + }; + + // Memoize an expensive function by storing its results. + _.memoize = function(func, hasher) { + var memoize = function(key) { + var cache = memoize.cache; + var address = '' + (hasher ? hasher.apply(this, arguments) : key); + if (!_.has(cache, address)) cache[address] = func.apply(this, arguments); + return cache[address]; + }; + 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) { + var args = slice.call(arguments, 2); + return setTimeout(function(){ + 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; + // but if you'd like to disable the execution on the leading edge, pass + // `{leading: false}`. To disable execution on the trailing edge, ditto. + _.throttle = function(func, wait, options) { + var context, args, result; + var timeout = null; + var previous = 0; + if (!options) options = {}; + var later = function() { + previous = options.leading === false ? 0 : _.now(); + timeout = null; + result = func.apply(context, args); + if (!timeout) context = args = null; + }; + return function() { + var now = _.now(); + if (!previous && options.leading === false) previous = now; + var remaining = wait - (now - previous); + context = this; + args = arguments; + if (remaining <= 0 || remaining > wait) { + if (timeout) { + clearTimeout(timeout); + timeout = null; + } + previous = now; + result = func.apply(context, args); + if (!timeout) context = args = null; + } else if (!timeout && options.trailing !== false) { + timeout = setTimeout(later, remaining); + } + 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 { + timeout = null; + if (!immediate) { + result = func.apply(context, args); + if (!timeout) context = args = null; + } + } + }; + + return function() { + context = this; + args = arguments; + timestamp = _.now(); + var callNow = immediate && !timeout; + if (!timeout) timeout = setTimeout(later, wait); + if (callNow) { + 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() { + var args = arguments; + var start = args.length - 1; + return function() { + var i = start; + var result = args[start].apply(this, arguments); + while (i--) result = args[i].call(this, result); + return result; + }; + }; + + // Returns a function that will only be executed on and after the Nth call. + _.after = function(times, func) { + return function() { + if (--times < 1) { + return func.apply(this, arguments); + } + }; + }; + + // Returns a function that will only be executed up to (but not including) the Nth call. + _.before = function(times, func) { + var memo; + return function() { + if (--times > 0) { + memo = func.apply(this, arguments); + } + if (times <= 1) func = null; + 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)) { + keys.push(prop); + } + } + } + + // Retrieve the names of an object's own properties. + // Delegates to **ECMAScript 5**'s native `Object.keys` + _.keys = function(obj) { + if (!_.isObject(obj)) return []; + if (nativeKeys) return nativeKeys(obj); + var keys = []; + for (var key in obj) if (_.has(obj, key)) keys.push(key); + // Ahem, IE < 9. + if (hasEnumBug) collectNonEnumProps(obj, keys); + return keys; + }; + + // Retrieve all the property names of an object. + _.allKeys = function(obj) { + if (!_.isObject(obj)) return []; + var keys = []; + for (var key in obj) keys.push(key); + // Ahem, IE < 9. + if (hasEnumBug) collectNonEnumProps(obj, keys); + return keys; + }; + + // Retrieve the values of an object's properties. + _.values = function(obj) { + var keys = _.keys(obj); + var length = keys.length; + var values = Array(length); + for (var i = 0; i < length; i++) { + values[i] = obj[keys[i]]; + } + 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) { + iteratee = cb(iteratee, context); + var keys = _.keys(obj), + length = keys.length, + results = {}, + currentKey; + for (var index = 0; index < length; index++) { + currentKey = keys[index]; + results[currentKey] = iteratee(obj[currentKey], currentKey, obj); + } + return results; + }; + + // Convert an object into a list of `[key, value]` pairs. + _.pairs = function(obj) { + var keys = _.keys(obj); + var length = keys.length; + var pairs = Array(length); + for (var i = 0; i < length; i++) { + pairs[i] = [keys[i], obj[keys[i]]]; + } + return pairs; + }; + + // Invert the keys and values of an object. The values must be serializable. + _.invert = function(obj) { + var result = {}; + var keys = _.keys(obj); + for (var i = 0, length = keys.length; i < length; i++) { + result[obj[keys[i]]] = keys[i]; + } + return result; + }; + + // Return a sorted list of the function names available on the object. + // Aliased as `methods` + _.functions = _.methods = function(obj) { + var names = []; + for (var key in obj) { + if (_.isFunction(obj[key])) names.push(key); + } + 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); + var keys = _.keys(obj), key; + for (var i = 0, length = keys.length; i < length; i++) { + key = keys[i]; + 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; + if (obj == null) return result; + if (_.isFunction(oiteratee)) { + keys = _.allKeys(obj); + iteratee = optimizeCb(oiteratee, context); + } else { + keys = flatten(arguments, false, false, 1); + iteratee = function(value, key, obj) { return key in obj; }; + obj = Object(obj); + } + for (var i = 0, length = keys.length; i < length; i++) { + var key = keys[i]; + var value = obj[key]; + if (iteratee(value, key, obj)) result[key] = value; + } + return result; + }; + + // Return a copy of the object without the blacklisted properties. + _.omit = function(obj, iteratee, context) { + if (_.isFunction(iteratee)) { + iteratee = _.negate(iteratee); + } else { + var keys = _.map(flatten(arguments, false, false, 1), String); + iteratee = function(value, key) { + return !_.contains(keys, key); + }; + } + 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. + _.create = function(prototype, props) { + var result = baseCreate(prototype); + 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. + _.tap = function(obj, interceptor) { + 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; + if (object == null) return !length; + var obj = Object(object); + for (var i = 0; i < length; i++) { + var key = keys[i]; + if (attrs[key] !== obj[key] || !(key in obj)) return false; + } + 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. + // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). + if (a === b) return a !== 0 || 1 / a === 1 / b; + // A strict comparison is necessary because `null == undefined`. + if (a == null || b == null) return a === b; + // Unwrap any wrapped objects. + if (a instanceof _) a = a._wrapped; + if (b instanceof _) b = b._wrapped; + // Compare `[[Class]]` names. + var className = toString.call(a); + if (className !== toString.call(b)) return false; + switch (className) { + // Strings, numbers, regular expressions, dates, and booleans are compared by value. + case '[object RegExp]': + // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') + case '[object String]': + // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is + // equivalent to `new String("5")`. + return '' + a === '' + b; + case '[object Number]': + // `NaN`s are equivalent, but non-reflexive. + // Object(NaN) is equivalent to NaN + if (+a !== +a) return +b !== +b; + // An `egal` comparison is performed for other numeric values. + return +a === 0 ? 1 / +a === 1 / b : +a === +b; + case '[object Date]': + case '[object Boolean]': + // Coerce dates and booleans to numeric primitive values. Dates are compared by their + // millisecond representations. Note that invalid dates with millisecond representations + // 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; + if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor && + _.isFunction(bCtor) && bCtor instanceof bCtor) + && ('constructor' in a && 'constructor' in b)) { + return false; + } + } + // 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 || []; + bStack = bStack || []; + var length = aStack.length; + while (length--) { + // Linear search. Performance is inversely proportional to the number of + // 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. + length = a.length; + if (length !== b.length) return false; + // Deep compare the contents, ignoring non-numeric properties. + while (length--) { + if (!eq(a[length], b[length], aStack, bStack)) return false; + } + } else { + // Deep compare objects. + var keys = _.keys(a), key; + length = keys.length; + // Ensure that both objects contain the same number of properties before comparing deep equality. + if (_.keys(b).length !== length) return false; + while (length--) { + // Deep compare each member + key = keys[length]; + if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false; + } + } + // Remove the first object from the stack of traversed objects. + aStack.pop(); + 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) { + if (obj == null) return true; + 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)) { + _.isArguments = function(obj) { + 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') { + _.isFunction = function(obj) { + 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) { + attrs = _.extendOwn({}, attrs); + return function(obj) { + return _.isMatch(obj, attrs); + }; + }; + + // Run a function **n** times. + _.times = function(n, iteratee, context) { + var accum = Array(Math.max(0, n)); + iteratee = optimizeCb(iteratee, context, 1); + 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) { + max = min; + min = 0; + } + 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 = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', + '`': '`' + }; + var unescapeMap = _.invert(escapeMap); + + // Functions for escaping and unescaping strings to/from HTML interpolation. + var createEscaper = function(map) { + var escaper = function(match) { + return map[match]; + }; + // Regexes for identifying a key that needs to be escaped + var source = '(?:' + _.keys(map).join('|') + ')'; + var testRegexp = RegExp(source); + var replaceRegexp = RegExp(source, 'g'); + return function(string) { + string = string == null ? '' : '' + string; + return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; + }; + }; + _.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) { + var value = object == null ? void 0 : object[property]; + if (value === void 0) { + value = fallback; + } + 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; + _.uniqueId = function(prefix) { + 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 = { + evaluate : /<%([\s\S]+?)%>/g, + 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 = { + "'": "'", + '\\': '\\', + '\r': 'r', + '\n': 'n', + '\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. + // NB: `oldSettings` only exists for backwards compatibility. + _.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) { + source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; + } 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) { + var func = _[name] = obj[name]; + _.prototype[name] = function() { + var args = [this._wrapped]; + push.apply(args, arguments); + return result(this, func.apply(_, args)); + }; + }); + }; + + // 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]; + _.prototype[name] = function() { + var obj = this._wrapped; + method.apply(obj, arguments); + if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; + return result(this, obj); + }; + }); + + // Add all accessor Array functions to the wrapper. + _.each(['concat', 'join', 'slice'], function(name) { + var method = ArrayProto[name]; + _.prototype[name] = function() { + 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 + // as a named module because, like jQuery, it is a base library that is + // popular enough to be bundled in a third party lib, but not be part of + // an AMD load request. Those cases could generate an error when an + // anonymous define() is called outside of a loader request. + if (typeof define === 'function' && define.amd) { + define('underscore', [], function() { + return _; + }); + } + }.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)) { + // e.g. http://foo.com -> http://foo.com/ + start = start + '/' + } + var match = url.match(/(\#.*)$/) + url = start + query + if (match) { // add hash back in + url = url + match[0] + } + } + return url + } + + },{}],327:[function(require,module,exports){ + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 'use strict'; + + var 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; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + 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. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + '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 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + 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); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + 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 + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // 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++) { + var hec = rest.indexOf(hostEndingChars[i]); + 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; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // 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) { + auth = rest.slice(0, atSign); + 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++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // 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(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + 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 + // have non-ASCII characters, i.e. it doesn't matter if + // 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) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // 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. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + 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. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); + } + + Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + 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) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + 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 || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } 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 + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + 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 + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + 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. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + 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. + var last = srcPath.slice(-1)[0]; + 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; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + 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 ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + 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 : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + }; + + Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + 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'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + 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 = []; + var counter = 0; + var length = string.length; + var value; + var extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + // Taken from https://mths.be/punycode + function ucs2encode(array) { + var length = array.length; + var index = -1; + var value; + var output = ''; + while (++index < length) { + value = array[index]; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + } + return output; + } + + function checkScalarValue(codePoint) { + if (codePoint >= 0xD800 && codePoint <= 0xDFFF) { + throw Error( + 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() + + ' is not a scalar value' + ); + } + } + /*--------------------------------------------------------------------------*/ + + function createByte(codePoint, shift) { + return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80); + } + + function encodeCodePoint(codePoint) { + if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence + return stringFromCharCode(codePoint); + } + var symbol = ''; + if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence + symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0); + } + else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence + checkScalarValue(codePoint); + symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0); + symbol += createByte(codePoint, 6); + } + else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence + symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0); + symbol += createByte(codePoint, 12); + symbol += createByte(codePoint, 6); + } + symbol += stringFromCharCode((codePoint & 0x3F) | 0x80); + return symbol; + } + + function utf8encode(string) { + var codePoints = ucs2decode(string); + var length = codePoints.length; + var index = -1; + var codePoint; + var byteString = ''; + while (++index < length) { + codePoint = codePoints[index]; + byteString += encodeCodePoint(codePoint); + } + 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(); + codePoint = ((byte1 & 0x1F) << 6) | byte2; + if (codePoint >= 0x80) { + return codePoint; + } else { + throw Error('Invalid continuation byte'); + } + } + + // 3-byte sequence (may include unpaired surrogates) + if ((byte1 & 0xF0) == 0xE0) { + byte2 = readContinuationByte(); + byte3 = readContinuationByte(); + codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3; + if (codePoint >= 0x0800) { + checkScalarValue(codePoint); + return codePoint; + } else { + throw Error('Invalid continuation byte'); + } + } + + // 4-byte sequence + if ((byte1 & 0xF8) == 0xF0) { + byte2 = readContinuationByte(); + byte3 = readContinuationByte(); + byte4 = readContinuationByte(); + codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) | + (byte3 << 0x06) | byte4; + if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) { + return codePoint; + } + } + + throw Error('Invalid UTF-8 detected'); + } + + var byteArray; + var byteCount; + var byteIndex; + function utf8decode(byteString) { + byteArray = ucs2decode(byteString); + byteCount = byteArray.length; + byteIndex = 0; + var codePoints = []; + var tmp; + while ((tmp = decodeSymbol()) !== false) { + codePoints.push(tmp); + } + 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 ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define(function() { + return utf8; + }); + } else if (freeExports && !freeExports.nodeType) { + if (freeModule) { // in Node.js or RingoJS v0.8.0+ + freeModule.exports = utf8; + } else { // in Narwhal or RingoJS v0.7.0- + var object = {}; + var hasOwnProperty = object.hasOwnProperty; + for (var key in utf8) { + hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]); + } + } + } 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. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + + function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + } + + /** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + + function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; + } + + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + },{}],331:[function(require,module,exports){ + arguments[4][180][0].apply(exports,arguments) + },{"dup":180}],332:[function(require,module,exports){ + module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; + } + },{}],333:[function(require,module,exports){ + (function (process,global){ + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var formatRegExp = /%[sdj%]/g; + exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + }; + + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + }; + + + var debugs = {}; + var debugEnviron; + exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + }; + + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + exports.inspect = inspect; + + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + exports.isArray = isArray; + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + exports.isBoolean = isBoolean; + + function isNull(arg) { + return arg === null; + } + exports.isNull = isNull; + + function isNullOrUndefined(arg) { + return arg == null; + } + exports.isNullOrUndefined = isNullOrUndefined; + + function isNumber(arg) { + return typeof arg === 'number'; + } + exports.isNumber = isNumber; + + function isString(arg) { + return typeof arg === 'string'; + } + exports.isString = isString; + + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + exports.isSymbol = isSymbol; + + function isUndefined(arg) { + return arg === void 0; + } + exports.isUndefined = isUndefined; + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + exports.isRegExp = isRegExp; + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + exports.isObject = isObject; + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + exports.isDate = isDate; + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + exports.isError = isError; + + function isFunction(arg) { + return typeof arg === 'function'; + } + exports.isFunction = isFunction; + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + exports.isPrimitive = isPrimitive; + + exports.isBuffer = require('./support/isBuffer'); + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); + }; + + + /** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ + exports.inherits = require('inherits'); + + exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + }; + + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + },{"./support/isBuffer":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 { + var res = []; + for (var key in obj) res.push(key) + 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({}, '_', {}); + return function(obj, name, value) { + Object.defineProperty(obj, name, { + writable: true, + enumerable: false, + configurable: true, + value: value + }) + }; + } catch(e) { + return function(obj, name, value) { + obj[name] = value; + }; + } + }()); + + 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]; + }); + forEach(globals, function (key) { + if (context[key]) { + 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` + // that was only introduced after the eval. + if (key in context || indexOf(winKeys, key) === -1) { + 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') { + forEach(Object_keys(context), function (key) { + copy[key] = context[key]; + }); + } + 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 . + */ + /** + * @file index.js + * @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; + if(typeof ethereumProvider !== 'undefined' && ethereumProvider.bzz) { + Bzz.givenProvider = ethereumProvider.bzz; + } + /* jshint ignore:end */ + + Bzz.prototype.setProvider = function(provider) { + // is ethereum provider + if(_.isObject(provider) && _.isString(provider.bzz)) { + provider = provider.bzz; + // is no string, set default + } + // 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 . + */ + /** + * @file errors.js + * @author Fabian Vogelsteller + * @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); + return new Error('Returned error: ' + message); + }, + InvalidNumberOfParams: function (got, expected, method) { + return new Error('Invalid number of parameters for "'+ method +'". Got '+ got +' expected '+ expected +'!'); + }, + InvalidConnection: function (host){ + return new Error('CONNECTION ERROR: Couldn\'t connect to node '+ host +'.'); + }, + InvalidProvider: function () { + return new Error('Provider not set or invalid'); + }, + InvalidResponse: function (result){ + var message = !!result && !!result.error && !!result.error.message ? result.error.message : 'Invalid JSON RPC response: ' + JSON.stringify(result); + return new Error(message); + }, + ConnectionTimeout: function (ms){ + 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 . + */ + /** + * @file formatters.js + * @author Fabian Vogelsteller + * @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 + * + * @method outputBigNumberFormatter + * @param {String|Number|BigNumber} number + * @returns {BigNumber} object + */ + 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; + } + if (blockNumber === 'genesis' || blockNumber === 'earliest') { + return '0x0'; + } + return inputBlockNumberFormatter(blockNumber); + }; + + var inputBlockNumberFormatter = function (blockNumber) { + if (blockNumber === undefined) { + return undefined; + } else if (isPredefinedBlockNumber(blockNumber)) { + return blockNumber; + } + return (utils.isHexStrict(blockNumber)) ? ((_.isString(blockNumber)) ? blockNumber.toLowerCase() : blockNumber) : utils.numberToHex(blockNumber); + }; + + /** + * Formats the input of a transaction and converts all values to HEX + * + * @method _txInputFormatter + * @param {Object} transaction options + * @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 + * + * @method inputCallFormatter + * @param {Object} transaction options + * @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 + * + * @method inputTransactionFormatter + * @param {Object} options + * @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 + * + * @method inputSignFormatter + * @param {String} data + * @returns {String} + */ + var inputSignFormatter = function (data) { + return (utils.isHexStrict(data)) ? data : utils.utf8ToHex(data); + }; + + /** + * Formats the output of a transaction to its proper values + * + * @method outputTransactionFormatter + * @param {Object} tx + * @returns {Object} + */ + var outputTransactionFormatter = function (tx){ + if(tx.blockNumber !== null) + tx.blockNumber = utils.hexToNumber(tx.blockNumber); + if(tx.transactionIndex !== null) + tx.transactionIndex = utils.hexToNumber(tx.transactionIndex); + tx.nonce = utils.hexToNumber(tx.nonce); + 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 + * + * @method outputTransactionReceiptFormatter + * @param {Object} receipt + * @returns {Object} + */ + var outputTransactionReceiptFormatter = function (receipt){ + 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 + * + * @method outputBlockFormatter + * @param {Object} block + * @returns {Object} + */ + var outputBlockFormatter = function(block) { + + // transform to number + block.gasLimit = utils.hexToNumber(block.gasLimit); + block.gasUsed = utils.hexToNumber(block.gasUsed); + block.size = utils.hexToNumber(block.size); + 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 + * + * @method inputLogFormatter + * @param {Object} log object + * @returns {Object} log + */ + 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 + * + * @method outputLogFormatter + * @param {Object} log object + * @returns {Object} log + */ + var outputLogFormatter = function(log) { + + // generate a custom log id + if(typeof log.blockHash === 'string' && + typeof log.transactionHash === 'string' && + typeof log.logIndex === 'string') { + var shaId = utils.sha3(log.blockHash.replace('0x','') + log.transactionHash.replace('0x','') + log.logIndex.replace('0x','')); + log.id = 'log_'+ shaId.replace('0x','').substr(0,8); + } 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 + * + * @method inputPostFormatter + * @param {Object} transaction object + * @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 + * + * @method outputPostFormatter + * @param {Object} + * @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 = []; + } + 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()) { + return iban.toAddress().toLowerCase(); + } else if (utils.isAddress(address)) { + return '0x' + address.toLowerCase().replace('0x',''); + } + 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); + if (result.knownStates) { + result.knownStates = utils.hexToNumber(result.knownStates); + result.pulledStates = utils.hexToNumber(result.pulledStates); + } + + return result; + }; + + module.exports = { + inputDefaultBlockNumberFormatter: inputDefaultBlockNumberFormatter, + inputBlockNumberFormatter: inputBlockNumberFormatter, + inputCallFormatter: inputCallFormatter, + inputTransactionFormatter: inputTransactionFormatter, + inputAddressFormatter: inputAddressFormatter, + inputPostFormatter: inputPostFormatter, + inputLogFormatter: inputLogFormatter, + inputSignFormatter: inputSignFormatter, + outputBigNumberFormatter: outputBigNumberFormatter, + outputTransactionFormatter: outputTransactionFormatter, + outputTransactionReceiptFormatter: outputTransactionReceiptFormatter, + outputBlockFormatter: outputBlockFormatter, + outputLogFormatter: outputLogFormatter, + 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 . + */ + /** + * @file index.js + * @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 . + */ + /** + * @file index.js + * @author Fabian Vogelsteller + * @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; + this.inputFormatter = options.inputFormatter; + 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; + var name = this.name.split('.'); + if (name.length > 1) { + obj[name[0]] = obj[name[0]] || {}; + obj[name[0]][name[1]] = func; + } else { + obj[name[0]] = func; + } + }; + + /** + * Should be used to determine name of the jsonrpc method based on arguments + * + * @method getCall + * @param {Array} arguments + * @return {String} name of jsonrpc method + */ + 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 + * + * @method extractCallback + * @param {Array} arguments + * @return {Function|Null} callback, if exists + */ + Method.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 + * + * @method validateArgs + * @param {Array} arguments + * @throws {Error} if it is not + */ + Method.prototype.validateArgs = function (args) { + if (args.length !== this.params) { + throw errors.InvalidNumberOfParams(args.length, this.params, this.name); + } + }; + + /** + * Should be called to format input args of method + * + * @method formatInput + * @param {Array} + * @return {Array} + */ + 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 + * + * @method formatOutput + * @param {Object} + * @return {Object} + */ + Method.prototype.formatOutput = function (result) { + var _this = this; + + if(_.isArray(result)) { + return result.map(function(res){ + return _this.outputFormatter && res ? _this.outputFormatter(res) : res; + }); + } else { + return this.outputFormatter && result ? this.outputFormatter(result) : result; + } + }; + + /** + * Should create payload from given input args + * + * @method toPayload + * @param {Array} args + * @return {Object} + */ + Method.prototype.toPayload = function (args) { + var call = this.getCall(args); + 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, + canUnsubscribe = true, + timeoutCount = 0, + confirmationCount = 0, + intervalId = null, + receiptJSON = '', + gasProvided = (_.isObject(payload.params[0]) && payload.params[0].gas) ? payload.params[0].gas : null, + isContractDeployment = _.isObject(payload.params[0]) && + payload.params[0].data && + payload.params[0].from && + !payload.params[0].to; + + // add custom send Methods + var _ethereumCalls = [ + new Method({ + name: 'getTransactionReceipt', + call: 'eth_getTransactionReceipt', + params: 1, + inputFormatter: [null], + outputFormatter: formatters.outputTransactionReceiptFormatter + }), + new Method({ + name: 'getCode', + call: 'eth_getCode', + params: 2, + inputFormatter: [formatters.inputAddressFormatter, formatters.inputDefaultBlockNumberFormatter] + }), + new Subscriptions({ + name: 'subscribe', + type: 'eth', + subscriptions: { + 'newBlockHeaders': { + subscriptionName: 'newHeads', // replace subscription with this name + params: 0, + outputFormatter: formatters.outputBlockFormatter + } + } + }) + ]; + // attach methods to this._ethereumCall + var _ethereumCall = {}; + _.each(_ethereumCalls, function (mthd) { + 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) { + // create fake unsubscribe + if (!sub) { + sub = { + unsubscribe: function () { + clearInterval(intervalId); + } + }; + } + // if we have a valid receipt we don't need to send a request + return (existingReceipt ? promiEvent.resolve(existingReceipt) : _ethereumCall.getTransactionReceipt(result)) + // catch error from requesting receipt + .catch(function (err) { + sub.unsubscribe(); + promiseResolved = true; + utils._fireError({message: 'Failed to check for transaction receipt:', data: err}, defer.eventEmitter, defer.reject); + }) + // if CONFIRMATION listener exists check for confirmations, by setting canUnsubscribe = false + .then(function(receipt) { + 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') { + utils._fireError(new Error("Transaction has been reverted by the EVM:\n" + receiptJSON), + defer.eventEmitter, defer.reject); + } else { + utils._fireError( + new Error("Transaction ran out of gas. Please provide more gas:\n" + receiptJSON), + 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 + if (timeoutCount - 1 >= POLLINGTIMEOUT) { + sub.unsubscribe(); + promiseResolved = true; + utils._fireError(new Error('Transaction was not mined within' + POLLINGTIMEOUT + ' seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!'), defer.eventEmitter, defer.reject); + } + } else { + if (timeoutCount - 1 >= TIMEOUTBLOCK) { + sub.unsubscribe(); + promiseResolved = true; + utils._fireError(new Error('Transaction was not mined within 50 blocks, please make sure your transaction was properly sent. Be aware that it might still be mined!'), defer.eventEmitter, defer.reject); + } + } + }); + + + } 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 + if (_.isFunction(this.requestManager.provider.on)) { + _ethereumCall.subscribe('newBlockHeaders', checkConfirmation.bind(null, existingReceipt, false)); + } else { + 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) { + if (receipt && receipt.blockHash) { + if (defer.eventEmitter.listeners('confirmation').length > 0) { + // We must keep on watching for new Blocks, if a confirmation listener is present + startWatching(receipt); + } + checkConfirmation(receipt, false); + + } else if (!promiseResolved) { + startWatching(); + } + }) + .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 { + result = method.formatOutput(result); + } catch(e) { + err = e; + } + + if (result instanceof Error) { + err = result; + } + + if (!err) { + if (payload.callback) { + payload.callback(null, result); + } + } else { + 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 + * + * @method request + * @return {Object} jsonrpc request + */ + Method.prototype.request = function () { + var payload = this.toPayload(Array.prototype.slice.call(arguments)); + 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 . + */ + /** + * @file index.js + * @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 + * + * @method eventifiedPromise + */ + var PromiEvent = function PromiEvent(justPromise) { + var resolve, reject, + eventEmitter = new Promise(function() { + resolve = arguments[0]; + reject = arguments[1]; + }); + + if(justPromise) { + return { + resolve: resolve, + reject: reject, + eventEmitter: eventEmitter + }; + } + + // get eventEmitter + var emitter = new EventEmitter(); + + // add eventEmitter to the promise + eventEmitter._events = emitter._events; + eventEmitter.emit = emitter.emit; + eventEmitter.on = emitter.on; + eventEmitter.once = emitter.once; + eventEmitter.off = emitter.off; + eventEmitter.listeners = emitter.listeners; + 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 . + */ + /** + * @file batch.js + * @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 + * + * @method add + * @param {Object} jsonrpc requet object + */ + Batch.prototype.add = function (request) { + this.requests.push(request); + }; + + /** + * Should be called to execute batch request + * + * @method execute + */ + Batch.prototype.execute = function () { + var requests = this.requests; + this.requestManager.sendBatch(requests, function (err, results) { + results = results || []; + requests.map(function (request, index) { + return results[index] || {}; + }).forEach(function (result, index) { + if (requests[index].callback) { + 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) { + requests[index].callback(err); + } + } + }); + }); + }; + + 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 . + */ + /** + * @file givenProvider.js + * @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 . + */ + /** + * @file index.js + * @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 + * Default poll timeout is 1 second + * Singleton + */ + 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 + * + * @method setProvider + * @param {Object} p + */ + 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); + } + }); + // TODO add error, end, timeout, connect?? + // this.provider.on('error', function requestManagerNotification(result){ + // Object.keys(_this.subscriptions).forEach(function(id){ + // if(_this.subscriptions[id].callback) + // _this.subscriptions[id].callback(err); + // }); + // } + } + }; + + + /** + * Should be used to asynchronously send request + * + * @method sendAsync + * @param {Object} data + * @param {Function} callback + */ + 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 + * + * @method sendBatch + * @param {Array} batch data + * @param {Function} callback + */ + RequestManager.prototype.sendBatch = function (data, callback) { + 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 + * + * @method addSubscription + * @param {String} id the subscription id + * @param {String} name the subscription name + * @param {String} type the subscription namespace (eth, personal, etc) + * @param {Function} callback the callback to call for incoming notifications + */ + RequestManager.prototype.addSubscription = function (id, name, type, callback) { + if(this.provider.on) { + this.subscriptions[id] = { + callback: callback, + type: type, + name: name + }; + + } else { + throw new Error('The provider doesn\'t support subscriptions: '+ this.provider.constructor.name); + } + }; + + /** + * Waits for notifications + * + * @method removeSubscription + * @param {String} id the subscription id + * @param {Function} callback fired once the subscription is removed + */ + 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 + * + * @method reset + */ + 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 . + */ + /** @file jsonrpc.js + * @authors: + * Fabian Vogelsteller + * Marek Kotewicz + * 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 + * + * @method toPayload + * @param {Function} method of jsonrpc call, required + * @param {Array} params, an array of method params, optional + * @returns {Object} valid jsonrpc payload object + */ + Jsonrpc.toPayload = function (method, params) { + 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, + method: method, + params: params || [] + }; + }; + + /** + * Should be called to check if jsonrpc response is valid + * + * @method isValidResponse + * @param {Object} + * @returns {Boolean} true if response is valid, otherwise false + */ + Jsonrpc.isValidResponse = function (response) { + return Array.isArray(response) ? response.every(validateSingleMessage) : validateSingleMessage(response); + + function validateSingleMessage(message){ + return !!message && + !message.error && + message.jsonrpc === '2.0' && + (typeof message.id === 'number' || typeof message.id === 'string') && + message.result !== undefined; // only undefined is not valid json object + } + }; + + /** + * Should be called to create batch payload object + * + * @method toBatchPayload + * @param {Array} messages, an array of objects with method (required) and params (optional) fields + * @returns {Array} batch payload + */ + Jsonrpc.toBatchPayload = function (messages) { + return messages.map(function (message) { + 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 . + */ + /** + * @file index.js + * @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('.'); + if (name.length > 1) { + obj[name[0]] = obj[name[0]] || {}; + obj[name[0]][name[1]] = func; + } else { + 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 . + */ + /** + * @file subscription.js + * @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 + * + * @method extractCallback + * @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 + * + * @method validateArgs + * @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 + * + * @method formatInput + * @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 + * + * @method formatOutput + * @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 + * + * @method toPayload + * @param {Array} args + * @return {Object} + */ + 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 + * + * @method unsubscribe + * @return {Object} + */ + Subscription.prototype.unsubscribe = function(callback) { + this.options.requestManager.removeSubscription(this.id, callback); + this.id = null; + this.removeAllListeners(); + clearInterval(this._reconnectIntervalId); + }; + + /** + * Subscribes and watches for changes + * + * @method subscribe + * @param {String} subscription the subscription + * @param {Object} options the options object with address topics and fromBlock + * @return {Object} + */ + Subscription.prototype.subscribe = function() { + 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); + this.callback(err2, null, this); + 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 + this.options.requestManager.send({ + method: 'eth_getLogs', + params: [payload.params[1]] + }, function (err, logs) { + if(!err) { + logs.forEach(function(log){ + var output = _this._formatOutput(log); + _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 () { + // TODO check if that makes sense! + if (_this.options.requestManager.provider.reconnect) { + _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); + } + }); + } else { + _this.callback(err, null, _this); + _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 . + */ + /** + * @file extend.js + * @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]) { + pckg[extension.property] = {}; + } + extendedObject = pckg[extension.property]; + } 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 . + */ + /** + * @file index.js + * @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 () { + return pkg._provider; + }, + set: function (value) { + return pkg.setProvider(value); + }, + 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) { + pkg._requestManager.setProvider(provider, net); + pkg._provider = pkg._requestManager.provider; + return true; + }; + } + + // attach batch request creation + pkg.BatchRequest = requestManager.BatchManager.bind(null, pkg._requestManager); + + // attach extend function + pkg.extend = extend(pkg); + }, + addProviders: function (pkg) { + pkg.givenProvider = requestManager.Manager.givenProvider; + 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 . + */ + /** + * @file index.js + * @author Marek Kotewicz + * @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')) { + return value.toString(); + } + 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. + * + * @method encodeFunctionSignature + * @param {String|Object} functionName + * @return {String} encoded function name + */ + ABICoder.prototype.encodeFunctionSignature = function (functionName) { + 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. + * + * @method encodeEventSignature + * @param {String|Object} functionName + * @return {String} encoded function name + */ + ABICoder.prototype.encodeEventSignature = function (functionName) { + if (_.isObject(functionName)) { + functionName = utils._jsonInterfaceMethodToString(functionName); + } + + return utils.sha3(functionName); + }; + + /** + * Should be used to encode plain param + * + * @method encodeParameter + * @param {String} type + * @param {Object} param + * @return {String} encoded plain param + */ + ABICoder.prototype.encodeParameter = function (type, param) { + return this.encodeParameters([type], [param]); + }; + + /** + * Should be used to encode list of params + * + * @method encodeParameters + * @param {Array} types + * @param {Array} params + * @return {String} encoded list of params + */ + ABICoder.prototype.encodeParameters = function (types, params) { + return ethersAbiCoder.encode(this.mapTypes(types), params); + }; + + /** + * Map types if simplified format is used + * + * @method mapTypes + * @param {Array} types + * @return {Array} + */ + ABICoder.prototype.mapTypes = function (types) { + var self = this; + var mappedTypes = []; + types.forEach(function (type) { + if (self.isSimplifiedStructFormat(type)) { + var structName = Object.keys(type)[0]; + mappedTypes.push( + Object.assign( + self.mapStructNameAndType(structName), + { + components: self.mapStructToCoderFormat(type[structName]) + } + ) + ); + + return; + } + + mappedTypes.push(type); + }); + + return mappedTypes; + }; + + /** + * Check if type is simplified struct format + * + * @method isSimplifiedStructFormat + * @param {string | Object} type + * @returns {boolean} + */ + 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 + * + * @method mapStructNameAndType + * @param {string} structName + * @return {{type: string, name: *}} + */ + 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 + * + * @method mapStructToCoderFormat + * @param {Object} struct + * @return {Array} + */ + ABICoder.prototype.mapStructToCoderFormat = function (struct) { + var self = this; + var components = []; + Object.keys(struct).forEach(function (key) { + if (typeof struct[key] === 'object') { + components.push( + Object.assign( + self.mapStructNameAndType(key), + { + components: self.mapStructToCoderFormat(struct[key]) + } + ) + ); + + return; + } + + components.push({ + name: key, + type: struct[key] + }); + }); + + return components; + }; + + /** + * Encodes a function call from its json interface and parameters. + * + * @method encodeFunctionCall + * @param {Array} jsonInterface + * @param {Array} params + * @return {String} The encoded ABI for this function call + */ + 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 + * + * @method decodeParameter + * @param {String} type + * @param {String} bytes + * @return {Object} plain param + */ + ABICoder.prototype.decodeParameter = function (type, bytes) { + return this.decodeParameters([type], bytes)[0]; + }; + + /** + * Should be used to decode list of params + * + * @method decodeParameter + * @param {Array} outputs + * @param {String} bytes + * @return {Array} array of plain params + */ + ABICoder.prototype.decodeParameters = function (outputs, bytes) { + 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. + * + * @method decodeLog + * @param {Object} inputs + * @param {String} data + * @param {Array} topics + * @return {Array} array of plain params + */ + 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) { + return input.type.indexOf(staticType) !== -1; + })) ? _this.decodeParameter(input.type, topics[topicCount]) : topics[topicCount]; + topicCount++; + } else { + 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"; + for (var i = 0; i < 40; i++) { + 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); + var publicKey = "0x" + ecKey.getPublic(false, 'hex').slice(2); + var publicHash = keccak256(publicKey); + var address = toChecksum("0x" + publicHash.slice(-40)); + return { + address: address, + 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) }; + var ecPublicKey = secp256k1.recoverPubKey(new Buffer(hash.slice(2), "hex"), vrs, vrs.v < 2 ? vrs.v : 1 - vrs.v % 2); // because odd vals mean v=0... sadly that means v=0 means v=1... I hate that + var publicKey = "0x" + ecPublicKey.encode("hex", false).slice(2); + var publicHash = keccak256(publicKey); + var address = toChecksum("0x" + publicHash.slice(-40)); + return address; + }; + + module.exports = { + create: create, + toChecksum: toChecksum, + fromPrivate: fromPrivate, + sign: sign, + makeSigner: makeSigner, + recover: recover, + encodeSignature: encodeSignature, + decodeSignature: decodeSignature + }; + }).call(this,require("buffer").Buffer) + },{"./bytes":352,"./hash":353,"./nat":354,"./rlp":355,"buffer":84,"elliptic":109}],351:[function(require,module,exports){ + arguments[4][132][0].apply(exports,arguments) + },{"dup":132}],352:[function(require,module,exports){ + arguments[4][133][0].apply(exports,arguments) + },{"./array.js":351,"dup":133}],353:[function(require,module,exports){ + arguments[4][134][0].apply(exports,arguments) + },{"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, + toNumber: toNumber, + fromNumber: fromNumber, + toEther: toEther, + fromEther: fromEther, + toUint256: toUint256, + add: add, + mul: mul, + div: div, + sub: sub + }; + },{"./bytes":352,"bn.js":53}],355:[function(require,module,exports){ + // The RLP format + // Serialization and deserialization for the BytesTree type, under the following grammar: + // | First byte | Meaning | + // | ---------- | -------------------------------------------------------------------------- | + // | 0 to 127 | HEX(leaf) | + // | 128 to 183 | HEX(length_of_leaf + 128) + HEX(leaf) | + // | 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); + var pre = hex.length != 2 || hex >= "80" ? length(hex.length / 2, 128) : ""; + return pre + hex; + } else { + var _hex = tree.map(dataTree).join(""); + var _pre = length(_hex.length / 2, 192); + 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 = []; + while (i < lim) { + 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 + var _rnds8 = new Uint8Array(16); + rng = function whatwgRNG() { + crypto.getRandomValues(_rnds8); + return _rnds8; + }; + } + + if (!rng) { + // Math.random()-based (RNG) + // + // If all else fails, use Math.random(). It's fast, but is of unspecified + // quality. + var _rnds = new Array(16); + rng = function() { + for (var i = 0, r; i < 16; i++) { + 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 = {}; + for (var i = 0; i < 256; i++) { + _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; + return bth[buf[i++]] + bth[buf[i++]] + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + + 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 . + */ + /** + * @file accounts.js + * @author Fabian Vogelsteller + * @date 2017 + */ + + "use strict"; + + var _ = require("underscore"); + var core = require('web3-core'); + var Method = require('web3-core-method'); + var Promise = require('any-promise'); + var Account = require("eth-lib/lib/account"); + var Hash = require("eth-lib/lib/hash"); + var RLP = require("eth-lib/lib/rlp"); + var Nat = require("eth-lib/lib/nat"); + var Bytes = require("eth-lib/lib/bytes"); + var cryp = (typeof global === 'undefined') ? require('crypto-browserify') : require('crypto'); + var scryptsy = require('scrypt.js'); + 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', + call: 'net_version', + params: 0, + outputFormatter: utils.hexToNumber + }), + new Method({ + name: 'getGasPrice', + call: 'eth_gasPrice', + params: 0 + }), + new Method({ + name: 'getTransactionCount', + call: 'eth_getTransactionCount', + params: 2, + inputFormatter: [function (address) { + if (utils.isAddress(address)) { + return address; + } else { + throw new Error('Address '+ address +' is not a valid address to get the "transactionCount".'); + } + }, function () { return 'latest'; }] + }) + ]; + // attach methods to this._ethereumCall + this._ethereumCall = {}; + _.each(_ethereumCall, function (method) { + 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); + }; + 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), + Bytes.fromNat(transaction.gas), + transaction.to.toLowerCase(), + Bytes.fromNat(transaction.value), + transaction.data, + 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, + v: trimLeadingZero(values[6]), + r: trimLeadingZero(values[7]), + 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, + isNot(tx.gasPrice) ? _this._ethereumCall.getGasPrice() : tx.gasPrice, + isNot(tx.nonce) ? _this._ethereumCall.getTransactionCount(_this.privateKeyToAccount(privateKey).address) : tx.nonce + ]).then(function (args) { + if (isNot(args[0]) || isNot(args[1]) || isNot(args[2])) { + throw new Error('One of the values "chainId", "gasPrice", or "nonce" couldn\'t be fetched: '+ JSON.stringify(args)); + } + 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); + var signature = Account.encodeSignature(values.slice(6,9)); + var recovery = Bytes.toNumber(values[6]); + var extraData = recovery < 35 ? [] : [Bytes.fromNumber((recovery - 35) >> 1), "0x", "0x"]; + var signingData = values.slice(0,6).concat(extraData); + var signingDataHex = RLP.encode(signingData); + 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); + var preamble = "\x19Ethereum Signed Message:\n" + message.length; + var preambleBuffer = Buffer.from(preamble); + 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); + var vrs = Account.decodeSignature(signature); + return { + message: data, + messageHash: hash, + v: vrs[0], + r: vrs[1], + s: vrs[2], + 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'; + derivedKey = cryp.pbkdf2Sync(new Buffer(password), salt, kdfparams.c, kdfparams.dklen, 'sha256'); + } else if (kdf === 'scrypt') { + // FIXME: support progress reporting callback + kdfparams.n = options.n || 8192; // 2048 4096 8192 16384 + kdfparams.r = options.r || 8; + kdfparams.p = options.p || 1; + derivedKey = scryptsy(new Buffer(password), salt, kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen); + } 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) }), + address: account.address.toLowerCase().replace('0x',''), + crypto: { + ciphertext: ciphertext.toString('hex'), + cipherparams: { + iv: iv.toString('hex') + }, + cipher: options.cipher || 'aes-128-ctr', + kdf: kdf, + kdfparams: kdfparams, + mac: mac.toString('hex') + } + }; + }; + + + // 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)) { + return this._findSafeIndex(pointer + 1); + } else { + 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; + delete this[account.address]; + // address lowercase + this[account.address.toLowerCase()].privateKey = null; + delete this[account.address.toLowerCase()]; + // 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 . + */ + /** + * @file contract.js + * + * To initialize a contract use: + * + * var Contract = require('web3-eth-contract'); + * Contract.setProvider('ws://localhost:8546'); + * var contract = new Contract(abi, address, ...); + * + * @author Fabian Vogelsteller + * @date 2017 + */ + + + "use strict"; + + + var _ = require('underscore'); + var core = require('web3-core'); + var Method = require('web3-core-method'); + var utils = require('web3-utils'); + var Subscription = require('web3-core-subscriptions').subscription; + var formatters = require('web3-core-helpers').formatters; + 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 + * + * @method Contract + * @constructor + * @param {Array} jsonInterface + * @param {String} address + * @param {Object} options + */ + 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){ + if(value) { + _this._address = utils.toChecksumAddress(formatters.inputAddressFormatter(value)); + } + }, + get: function(){ + return _this._address; + }, + 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); + func = _this._createTxObject.bind({ + method: method, + parent: _this + }); + + + // add method only if not one already exists + if(!_this.methods[method.name]) { + _this.methods[method.name] = func; + } else { + var cascadeFunc = _this._createTxObject.bind({ + method: method, + parent: _this, + nextMethod: _this.methods[method.name] + }); + _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(){ + return _this._jsonInterface; + }, + 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; + }, + set: function (val) { + if(val) { + defaultAccount = utils.toChecksumAddress(formatters.inputAddressFormatter(val)); + } + + return val; + }, + enumerable: true + }); + Object.defineProperty(this, 'defaultBlock', { + get: function () { + return defaultBlock; + }, + 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 + * + * @method _getCallback + * @param {Array} args + * @return {Function} the callback + */ + Contract.prototype._getCallback = function getCallback(args) { + if (args && _.isFunction(args[args.length - 1])) { + return args.pop(); // modify the args array! + } + }; + + /** + * Checks that no listener with name "newListener" or "removeListener" is added. + * + * @method _checkListener + * @param {String} type + * @param {String} event + * @return {Object} the contract instance + */ + Contract.prototype._checkListener = function(type, event){ + if(event === type) { + throw new Error('The event "'+ type +'" is a reserved event name, you can\'t use it.'); + } + }; + + + /** + * Use default values, if options are not available + * + * @method _getOrSetDefaultOptions + * @param {Object} options the options gived by the user + * @return {Object} the options with gaps filled by defaults + */ + 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 + * + * @method _encodeEventABI + * @param {Object} event + * @param {Object} options + * @return {Object} everything combined together and encoded + */ + Contract.prototype._encodeEventABI = function (event, options) { + 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) { + return i.indexed === true; + }).map(function (i) { + var value = filter[i.name]; + 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); + }); + } + 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 + * + * @method _decodeEventABI + * @param {Object} data + * @return {Object} result object with decoded indexed && not indexed params + */ + 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, + topics: result.topics + }; + 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. + * + * @method _encodeMethodABI + * @param {Mixed} args the arguments to encode + * @param {String} the encoded ABI + */ + 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; + } + return _.isArray(json.inputs) ? json.inputs : []; + }).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 + * + * @method _decodeMethodReturn + * @param {Array} outputs + * @param {String} returnValues + * @return {Object} decoded output return values + */ + Contract.prototype._decodeMethodReturn = function (outputs, returnValues) { + 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 { + delete result.__length__; + return result; + } + }; + + + /** + * Deploys a contract and fire events based on its state: transactionHash, receipt + * + * All event listeners will be removed, once the last possible event is fired ("error", or "receipt") + * + * @method deploy + * @param {Object} options + * @param {Function} callback + * @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 + * + * @method _generateEventOptions + * @param {Object} event + * @param {Object} options + * @param {Function} callback + * @return {Object} the event options object + */ + 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', + jsonInterface: this.options.jsonInterface + } : 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. + * + * @method clone + * @return {Object} the event subscription + */ + 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. + * + * @method once + * @param {String} event + * @param {Object} options + * @param {Function} callback + * @return {Object} the event subscription + */ + 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(); + if(_.isFunction(callback)){ + callback(err, res, sub); + } + }); + + return undefined; + }; + + /** + * Adds event listeners and creates a subscription. + * + * @method _on + * @param {String} event + * @param {Object} options + * @param {Function} callback + * @return {Object} the event subscription + */ + 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: { + params: 1, + inputFormatter: [formatters.inputLogFormatter], + outputFormatter: this._decodeEventABI.bind(subOptions.event), + // DUBLICATE, also in web3-eth + subscriptionHandler: function (output) { + if(output.removed) { + this.emit('changed', output); + } else { + this.emit('data', output); + } + + if (_.isFunction(this.callback)) { + this.callback(null, output, this); + } + } + }, + type: 'eth', + requestManager: this._requestManager + }); + subscription.subscribe('logs', subOptions.params, subOptions.callback || function () {}); + + return subscription; + }; + + /** + * Get past events from contracts + * + * @method getPastEvents + * @param {String} event + * @param {Object} options + * @param {Function} callback + * @return {Object} the promievent + */ + Contract.prototype.getPastEvents = function(){ + var subOptions = this._generateEventOptions.apply(this, arguments); + + var getPastLogs = new Method({ + name: 'getPastLogs', + call: 'eth_getLogs', + params: 1, + inputFormatter: [formatters.inputLogFormatter], + outputFormatter: this._decodeEventABI.bind(subOptions.event) + }); + 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 + * + * @method _createTxObject + * @returns {Object} an object with functions to call the methods + */ + 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 + * + * @method _processExecuteArguments + * @param {Array} args + * @param {Promise} defer + */ + 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 + * + * @method _executeMethod + * @param {String} type the type this execute function should execute + * @param {Boolean} makeRequest if true, it simply returns the request parameters, rather than executing it + */ + Contract.prototype._executeMethod = function _executeMethod(){ + var _this = this, + 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'; + payload.format = this._parent._decodeMethodReturn.bind(null, this._method.outputs); + } else { + payload.method = 'eth_sendTransaction'; + } + + return payload; + + } else { + + switch (args.type) { + case 'estimate': + + var estimateGas = (new Method({ + name: 'estimateGas', + call: 'eth_estimateGas', + params: 1, + inputFormatter: [formatters.inputCallFormatter], + outputFormatter: utils.hexToNumber, + requestManager: _this._parent._requestManager, + accounts: ethAccounts, // is eth.accounts (necessary for wallet signing) + 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', + params: 2, + inputFormatter: [formatters.inputCallFormatter, formatters.inputDefaultBlockNumberFormatter], + // add output formatter for decoding + outputFormatter: function (result) { + return _this._parent._decodeMethodReturn(_this._method.outputs, result); + }, + requestManager: _this._parent._requestManager, + accounts: ethAccounts, // is eth.accounts (necessary for wallet signing) + 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({ + name: 'ALLEVENTS', + jsonInterface: _this._parent.options.jsonInterface + }, log); + }); + + // make log names keys + receipt.events = {}; + var count = 0; + events.forEach(function (ev) { + if (ev.event) { + // if > 1 of the same event, don't overwrite any existing events + if (receipt.events[ev.event]) { + if (Array.isArray(receipt.events[ ev.event ])) { + receipt.events[ ev.event ].push(ev); + } else { + receipt.events[ev.event] = [receipt.events[ev.event], ev]; + } + } else { + receipt.events[ ev.event ] = ev; + } + } else { + receipt.events[count] = ev; + count++; + } + }); + + delete receipt.logs; + } + return receipt; + }, + contractDeployFormatter: function (receipt) { + var newContract = _this._parent.clone(); + newContract.options.address = receipt.contractAddress; + return newContract; + } + }; + + var sendTransaction = (new Method({ + name: 'sendTransaction', + call: 'eth_sendTransaction', + params: 1, + inputFormatter: [formatters.inputTransactionFormatter], + requestManager: _this._parent._requestManager, + accounts: _this.constructor._ethAccounts || _this._ethAccounts, // is eth.accounts (necessary for wallet signing) + defaultAccount: _this._parent.defaultAccount, + 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. + 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 . + */ + /** + * @file ENS.js + * + * @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 + * + * @method ENS + * @param {Object} eth + * @constructor + */ + 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} + */ + ENS.prototype.resolver = function (name) { + return this.registry.resolver(name); + }; + + /** + * Returns the address record associated with a name. + * + * @method getAddress + * @param {string} name + * @param {function} callback + * @return {eventifiedPromise} + */ + ENS.prototype.getAddress = function (name, callback) { + return this.resolverMethodHandler.method(name, 'addr', []).call(callback); + }; + + /** + * Sets a new address + * + * @method setAddress + * @param {string} name + * @param {string} address + * @param {Object} sendOptions + * @param {function} callback + * @returns {eventifiedPromise} + */ + ENS.prototype.setAddress = function (name, address, sendOptions, callback) { + return this.resolverMethodHandler.method(name, 'setAddr', [address]).send(sendOptions, callback); + }; + + /** + * Returns the public key + * + * @method getPubkey + * @param {string} name + * @param {function} callback + * @returns {eventifiedPromise} + */ + ENS.prototype.getPubkey = function (name, callback) { + return this.resolverMethodHandler.method(name, 'pubkey', [], callback).call(callback); + }; + + /** + * Set the new public key + * + * @method setPubkey + * @param {string} name + * @param {string} x + * @param {string} y + * @param {Object} sendOptions + * @param {function} callback + * @returns {eventifiedPromise} + */ + ENS.prototype.setPubkey = function (name, x, y, sendOptions, callback) { + return this.resolverMethodHandler.method(name, 'setPubkey', [x, y]).send(sendOptions, callback); + }; + + /** + * Returns the content + * + * @method getContent + * @param {string} name + * @param {function} callback + * @returns {eventifiedPromise} + */ + ENS.prototype.getContent = function (name, callback) { + return this.resolverMethodHandler.method(name, 'content', []).call(callback); + }; + + /** + * Set the content + * + * @method setContent + * @param {string} name + * @param {string} hash + * @param {function} callback + * @param {Object} sendOptions + * @returns {eventifiedPromise} + */ + ENS.prototype.setContent = function (name, hash, sendOptions, callback) { + return this.resolverMethodHandler.method(name, 'setContent', [hash]).send(sendOptions, callback); + }; + + /** + * Get the multihash + * + * @method getMultihash + * @param {string} name + * @param {function} callback + * @returns {eventifiedPromise} + */ + ENS.prototype.getMultihash = function (name, callback) { + return this.resolverMethodHandler.method(name, 'multihash', []).call(callback); + }; + + /** + * Set the multihash + * + * @method setMultihash + * @param {string} name + * @param {string} hash + * @param {Object} sendOptions + * @param {function} callback + * @returns {eventifiedPromise} + */ + 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. + * + * @returns {Promise} + */ + ENS.prototype.checkNetwork = function () { + var self = this; + return self.eth.getBlock('latest').then(function (block) { + var headAge = new Date() / 1000 - block.timestamp; + if (headAge > 3600) { + throw new Error("Network not synced; last block was " + headAge + " seconds ago"); + } + return self.eth.net.getNetworkType(); + }).then(function (networkType) { + var addr = config.addresses[networkType]; + 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", + ropsten: "0x112234455c3a32fd11230c42e7bccd4a84e02010", + rinkeby: "0xe7410170f87102df0055eb195163a03b7f2bff4a" + }, + }; + + module.exports = config; + + },{}],362:[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 . + */ + /** + * @file Registry.js + * + * @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. + * + * @method Registry + * @param {Ens} ens + * @constructor + */ + function Registry(ens) { + var self = this; + this.ens = ens; + 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. + * + * @method owner + * @param {string} name + * @param {function} callback + * @return {Promise} + */ + 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. + * + * @method resolver + * @param {string} name + * @return {Promise} + */ + 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) { + var contract = new Contract(RESOLVER_ABI, address); + contract.setProvider(self.ens.eth.currentProvider); + 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. + 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 . + */ + /** + * @file index.js + * + * @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. + 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 . + */ + /** + * @file ResolverMethodHandler.js + * + * @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 + */ + function ResolverMethodHandler(registry) { + this.registry = registry; + } + + /** + * Executes an resolver method and returns an eventifiedPromise + * + * @param {string} ensName + * @param {string} methodName + * @param {array} methodArguments + * @param {function} callback + * @returns {Object} + */ + ResolverMethodHandler.prototype.method = function (ensName, methodName, methodArguments, callback) { + return { + call: this.call.bind({ + ensName: ensName, + methodName: methodName, + methodArguments: methodArguments, + callback: callback, + parent: this + }), + send: this.send.bind({ + ensName: ensName, + methodName: methodName, + methodArguments: methodArguments, + callback: callback, + parent: this + }) + }; + }; + + /** + * Executes call + * + * @returns {eventifiedPromise} + */ + ResolverMethodHandler.prototype.call = function (callback) { + 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 + * + * @param {Object} sendOptions + * @param {function} callback + * @returns {eventifiedPromise} + */ + ResolverMethodHandler.prototype.send = function (sendOptions, callback) { + 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 + * + * @param {eventifiedPromise} promiEvent + * @param {function} method + * @param {array} preparedArguments + * @param {function} callback + * @returns {eventifiedPromise} + */ + ResolverMethodHandler.prototype.handleCall = function (promiEvent, method, preparedArguments, callback) { + 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 + * + * @param {eventifiedPromise} promiEvent + * @param {function} method + * @param {array} preparedArguments + * @param {Object} sendOptions + * @param {function} callback + * @returns {eventifiedPromise} + */ + ResolverMethodHandler.prototype.handleSend = function (promiEvent, method, preparedArguments, sendOptions, callback) { + method.apply(this, preparedArguments).send(sendOptions) + .on('transactionHash', function (hash) { + promiEvent.eventEmitter.emit('transactionHash', hash); + }) + .on('confirmation', function (confirmationNumber, receipt) { + promiEvent.eventEmitter.emit('confirmation', confirmationNumber, receipt); + }) + .on('receipt', function (receipt) { + promiEvent.eventEmitter.emit('receipt', receipt); + promiEvent.resolve(receipt); + + if (_.isFunction(callback)) { + callback(receipt); + } + }) + .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 + * + * @param {string} name + * @param {array} methodArguments + * @returns {array} + */ + 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, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "resolver", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "owner", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "label", + "type": "bytes32" + }, + { + "name": "owner", + "type": "address" + } + ], + "name": "setSubnodeOwner", + "outputs": [], + "payable": false, + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "ttl", + "type": "uint64" + } + ], + "name": "setTTL", + "outputs": [], + "payable": false, + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "ttl", + "outputs": [ + { + "name": "", + "type": "uint64" + } + ], + "payable": false, + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "resolver", + "type": "address" + } + ], + "name": "setResolver", + "outputs": [], + "payable": false, + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "owner", + "type": "address" + } + ], + "name": "setOwner", + "outputs": [], + "payable": false, + "type": "function" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "owner", + "type": "address" + } + ], + "name": "Transfer", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": true, + "name": "label", + "type": "bytes32" + }, + { + "indexed": false, + "name": "owner", + "type": "address" + } + ], + "name": "NewOwner", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "resolver", + "type": "address" + } + ], + "name": "NewResolver", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "ttl", + "type": "uint64" + } + ], + "name": "NewTTL", + "type": "event" + } + ]; + + module.exports = REGISTRY; + + },{}],366:[function(require,module,exports){ + "use strict"; + + var RESOLVER = [ + { + "constant": true, + "inputs": [ + { + "name": "interfaceID", + "type": "bytes4" + } + ], + "name": "supportsInterface", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "contentTypes", + "type": "uint256" + } + ], + "name": "ABI", + "outputs": [ + { + "name": "contentType", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + } + ], + "payable": false, + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "hash", + "type": "bytes" + } + ], + "name": "setMultihash", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "multihash", + "outputs": [ + { + "name": "", + "type": "bytes" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "x", + "type": "bytes32" + }, + { + "name": "y", + "type": "bytes32" + } + ], + "name": "setPubkey", + "outputs": [], + "payable": false, + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "content", + "outputs": [ + { + "name": "ret", + "type": "bytes32" + } + ], + "payable": false, + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "addr", + "outputs": [ + { + "name": "ret", + "type": "address" + } + ], + "payable": false, + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "contentType", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + } + ], + "name": "setABI", + "outputs": [], + "payable": false, + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "name", + "outputs": [ + { + "name": "ret", + "type": "string" + } + ], + "payable": false, + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "name", + "type": "string" + } + ], + "name": "setName", + "outputs": [], + "payable": false, + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "hash", + "type": "bytes32" + } + ], + "name": "setContent", + "outputs": [], + "payable": false, + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "pubkey", + "outputs": [ + { + "name": "x", + "type": "bytes32" + }, + { + "name": "y", + "type": "bytes32" + } + ], + "payable": false, + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "addr", + "type": "address" + } + ], + "name": "setAddr", + "outputs": [], + "payable": false, + "type": "function" + }, + { + "inputs": [ + { + "name": "ensAddr", + "type": "address" + } + ], + "payable": false, + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "a", + "type": "address" + } + ], + "name": "AddrChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "hash", + "type": "bytes32" + } + ], + "name": "ContentChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "name", + "type": "string" + } + ], + "name": "NameChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": true, + "name": "contentType", + "type": "uint256" + } + ], + "name": "ABIChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "x", + "type": "bytes32" + }, + { + "indexed": false, + "name": "y", + "type": "bytes32" + } + ], + "name": "PubkeyChanged", + "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 . + */ + /** + * @file iban.js + * + * Details: https://github.com/ethereum/wiki/wiki/ICAP:-Inter-exchange-Client-Address-Protocol + * + * @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) { + result = '0' + result; + } + 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. + * + * @method iso13616Prepare + * @param {String} iban the IBAN + * @returns {String} the prepared IBAN + */ + 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){ + // A = 10, B = 11, ... Z = 35 + return code - A + 10; + } else { + return n; + } + }).join(''); + }; + + /** + * Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064. + * + * @method mod9710 + * @param {String} iban + * @returns {Number} + */ + 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 + * + * @param {String} iban + */ + var Iban = function Iban(iban) { + this._iban = iban; + }; + + /** + * This method should be used to create an ethereum address from a direct iban address + * + * @method toAddress + * @param {String} iban address + * @return {String} the ethereum address + */ + 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 + * + * @method toIban + * @param {String} address + * @return {String} the IBAN address + */ + Iban.toIban = function (address) { + return Iban.fromAddress(address).toString(); + }; + + /** + * This method should be used to create iban object from an ethereum address + * + * @method fromAddress + * @param {String} address + * @return {Iban} the IBAN object + */ + Iban.fromAddress = function (address) { + 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". + * This method implements the preferred algorithm described in http://en.wikipedia.org/wiki/International_Bank_Account_Number#Generating_IBAN_check_digits + * + * @method fromBban + * @param {String} bban the BBAN to convert to IBAN + * @returns {Iban} the IBAN object + */ + 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 + * + * @method createIndirect + * @param {Object} options, required options are "institution" and "identifier" + * @return {Iban} the IBAN object + */ + 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 + * + * @method isValid + * @param {String} iban string + * @return {Boolean} true if it is valid IBAN + */ + Iban.isValid = function (iban) { + var i = new Iban(iban); + return i.isValid(); + }; + + /** + * Should be called to check if iban is correct + * + * @method isValid + * @returns {Boolean} true if it is, otherwise false + */ + Iban.prototype.isValid = function () { + 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 + * + * @method isDirect + * @returns {Boolean} true if it is, otherwise false + */ + Iban.prototype.isDirect = function () { + return this._iban.length === 34 || this._iban.length === 35; + }; + + /** + * Should be called to check if iban number if indirect + * + * @method isIndirect + * @returns {Boolean} true if it is, otherwise false + */ + 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) + * + * @method checksum + * @returns {String} checksum + */ + Iban.prototype.checksum = function () { + return this._iban.substr(2, 2); + }; + + /** + * Should be called to get institution identifier + * eg. XREG + * + * @method institution + * @returns {String} institution identifier + */ + Iban.prototype.institution = function () { + return this.isIndirect() ? this._iban.substr(7, 4) : ''; + }; + + /** + * Should be called to get client identifier within institution + * eg. GAVOFYORK + * + * @method client + * @returns {String} client identifier + */ + Iban.prototype.client = function () { + return this.isIndirect() ? this._iban.substr(11) : ''; + }; + + /** + * Should be called to get client direct address + * + * @method toAddress + * @returns {String} ethereum address + */ + Iban.prototype.toAddress = function () { + if (this.isDirect()) { + var base36 = this._iban.substr(4); + 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 . + */ + /** + * @file index.js + * @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; + }, + set: function (val) { + if(val) { + defaultAccount = utils.toChecksumAddress(formatters.inputAddressFormatter(val)); + } + + // update defaultBlock + methods.forEach(function(method) { + method.defaultAccount = defaultAccount; + }); + + return val; + }, + enumerable: true + }); + Object.defineProperty(this, 'defaultBlock', { + get: function () { + return defaultBlock; + }, + set: function (val) { + defaultBlock = val; + + // update defaultBlock + methods.forEach(function(method) { + method.defaultBlock = defaultBlock; + }); + + return val; + }, + enumerable: true + }); + + + var methods = [ + new Method({ + name: 'getAccounts', + call: 'personal_listAccounts', + params: 0, + outputFormatter: utils.toChecksumAddress + }), + new Method({ + name: 'newAccount', + call: 'personal_newAccount', + params: 1, + inputFormatter: [null], + outputFormatter: utils.toChecksumAddress + }), + new Method({ + name: 'unlockAccount', + call: 'personal_unlockAccount', + params: 3, + inputFormatter: [formatters.inputAddressFormatter, null, null] + }), + new Method({ + name: 'lockAccount', + call: 'personal_lockAccount', + params: 1, + inputFormatter: [formatters.inputAddressFormatter] + }), + new Method({ + name: 'importRawKey', + call: 'personal_importRawKey', + params: 2 + }), + new Method({ + name: 'sendTransaction', + call: 'personal_sendTransaction', + params: 2, + inputFormatter: [formatters.inputTransactionFormatter, null] + }), + new Method({ + name: 'signTransaction', + call: 'personal_signTransaction', + params: 2, + inputFormatter: [formatters.inputTransactionFormatter, null] + }), + new Method({ + name: 'sign', + call: 'personal_sign', + params: 3, + inputFormatter: [formatters.inputSignFormatter, formatters.inputAddressFormatter, null] + }), + new Method({ + name: 'ecRecover', + call: 'personal_ecRecover', + params: 2, + inputFormatter: [formatters.inputSignFormatter, null] + }) + ]; + methods.forEach(function(method) { + method.attachToObject(_this); + method.setRequestManager(_this._requestManager); + method.defaultBlock = _this.defaultBlock; + 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 . + */ + /** + * @file getNetworkType.js + * @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'; + } + if (genesis.hash === '0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303' && + id === 2) { + returnValue = 'morden'; + } + if (genesis.hash === '0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d' && + id === 3) { + returnValue = 'ropsten'; + } + if (genesis.hash === '0x6341fd3daf94b748c72ced5a5b26028f2474f5f00d824504e4fa37a75767e177' && + id === 4) { + returnValue = 'rinkeby'; + } + if (genesis.hash === '0xa3c565fc15c7478862d50ccd6561e3c06b24cc509bf388941c25ea985ce32cb9' && + id === 42) { + returnValue = 'kovan'; + } + + if (_.isFunction(callback)) { + callback(null, returnValue); + } + + return returnValue; + }) + .catch(function (err) { + if (_.isFunction(callback)) { + callback(err); + } else { + throw err; + } + }); + }; + + 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 . + */ + /** + * @file index.js + * @author Fabian Vogelsteller + * @date 2017 + */ + + "use strict"; + + var _ = require('underscore'); + var core = require('web3-core'); + var helpers = require('web3-core-helpers'); + var Subscriptions = require('web3-core-subscriptions').subscriptions; + 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 () { + setProvider.apply(_this, arguments); + _this.net.setProvider.apply(_this, arguments); + _this.personal.setProvider.apply(_this, arguments); + _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; + }, + set: function (val) { + 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 + }); + Object.defineProperty(this, 'defaultBlock', { + get: function () { + return defaultBlock; + }, + set: function (val) { + defaultBlock = val; + // 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 + // web3-eth would subsequently change the provider for _all_ contract + // instances! + 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 + // the contract instances + var _this = this; + var setProvider = self.setProvider; + self.setProvider = function() { + setProvider.apply(self, arguments); + 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', + call: 'web3_clientVersion' + }), + new Method({ + name: 'getProtocolVersion', + call: 'eth_protocolVersion', + params: 0 + }), + new Method({ + name: 'getCoinbase', + call: 'eth_coinbase', + params: 0 + }), + new Method({ + name: 'isMining', + call: 'eth_mining', + params: 0 + }), + new Method({ + name: 'getHashrate', + call: 'eth_hashrate', + params: 0, + outputFormatter: utils.hexToNumber + }), + new Method({ + name: 'isSyncing', + call: 'eth_syncing', + params: 0, + outputFormatter: formatter.outputSyncingFormatter + }), + new Method({ + name: 'getGasPrice', + call: 'eth_gasPrice', + params: 0, + outputFormatter: formatter.outputBigNumberFormatter + }), + new Method({ + name: 'getAccounts', + call: 'eth_accounts', + params: 0, + outputFormatter: utils.toChecksumAddress + }), + new Method({ + name: 'getBlockNumber', + call: 'eth_blockNumber', + params: 0, + outputFormatter: utils.hexToNumber + }), + new Method({ + name: 'getBalance', + call: 'eth_getBalance', + params: 2, + inputFormatter: [formatter.inputAddressFormatter, formatter.inputDefaultBlockNumberFormatter], + outputFormatter: formatter.outputBigNumberFormatter + }), + new Method({ + name: 'getStorageAt', + call: 'eth_getStorageAt', + params: 3, + inputFormatter: [formatter.inputAddressFormatter, utils.numberToHex, formatter.inputDefaultBlockNumberFormatter] + }), + new Method({ + name: 'getCode', + call: 'eth_getCode', + params: 2, + inputFormatter: [formatter.inputAddressFormatter, formatter.inputDefaultBlockNumberFormatter] + }), + new Method({ + name: 'getBlock', + call: blockCall, + params: 2, + inputFormatter: [formatter.inputBlockNumberFormatter, function (val) { return !!val; }], + outputFormatter: formatter.outputBlockFormatter + }), + new Method({ + name: 'getUncle', + call: uncleCall, + params: 2, + inputFormatter: [formatter.inputBlockNumberFormatter, utils.numberToHex], + outputFormatter: formatter.outputBlockFormatter, + + }), + new Method({ + name: 'getBlockTransactionCount', + call: getBlockTransactionCountCall, + params: 1, + inputFormatter: [formatter.inputBlockNumberFormatter], + outputFormatter: utils.hexToNumber + }), + new Method({ + name: 'getBlockUncleCount', + call: uncleCountCall, + params: 1, + inputFormatter: [formatter.inputBlockNumberFormatter], + outputFormatter: utils.hexToNumber + }), + new Method({ + name: 'getTransaction', + call: 'eth_getTransactionByHash', + params: 1, + inputFormatter: [null], + outputFormatter: formatter.outputTransactionFormatter + }), + new Method({ + name: 'getTransactionFromBlock', + call: transactionFromBlockCall, + params: 2, + inputFormatter: [formatter.inputBlockNumberFormatter, utils.numberToHex], + outputFormatter: formatter.outputTransactionFormatter + }), + new Method({ + name: 'getTransactionReceipt', + call: 'eth_getTransactionReceipt', + params: 1, + inputFormatter: [null], + outputFormatter: formatter.outputTransactionReceiptFormatter + }), + new Method({ + name: 'getTransactionCount', + call: 'eth_getTransactionCount', + params: 2, + inputFormatter: [formatter.inputAddressFormatter, formatter.inputDefaultBlockNumberFormatter], + outputFormatter: utils.hexToNumber + }), + new Method({ + name: 'sendSignedTransaction', + call: 'eth_sendRawTransaction', + params: 1, + inputFormatter: [null] + }), + new Method({ + name: 'signTransaction', + call: 'eth_signTransaction', + params: 1, + inputFormatter: [formatter.inputTransactionFormatter] + }), + new Method({ + name: 'sendTransaction', + call: 'eth_sendTransaction', + params: 1, + inputFormatter: [formatter.inputTransactionFormatter] + }), + new Method({ + name: 'sign', + call: 'eth_sign', + params: 2, + inputFormatter: [formatter.inputSignFormatter, formatter.inputAddressFormatter], + transformPayload: function (payload) { + payload.params.reverse(); + return payload; + } + }), + new Method({ + name: 'call', + call: 'eth_call', + params: 2, + inputFormatter: [formatter.inputCallFormatter, formatter.inputDefaultBlockNumberFormatter] + }), + new Method({ + name: 'estimateGas', + call: 'eth_estimateGas', + params: 1, + inputFormatter: [formatter.inputCallFormatter], + outputFormatter: utils.hexToNumber + }), + new Method({ + name: 'submitWork', + call: 'eth_submitWork', + params: 3 + }), + new Method({ + name: 'getWork', + call: 'eth_getWork', + params: 0 + }), + new Method({ + name: 'getPastLogs', + call: 'eth_getLogs', + params: 1, + inputFormatter: [formatter.inputLogFormatter], + outputFormatter: formatter.outputLogFormatter + }), + + // subscriptions + new Subscriptions({ + name: 'subscribe', + type: 'eth', + subscriptions: { + 'newBlockHeaders': { + // TODO rename on RPC side? + subscriptionName: 'newHeads', // replace subscription with this name + params: 0, + outputFormatter: formatter.outputBlockFormatter + }, + 'pendingTransactions': { + subscriptionName: 'newPendingTransactions', // replace subscription with this name + params: 0 + }, + 'logs': { + params: 1, + inputFormatter: [formatter.inputLogFormatter], + outputFormatter: formatter.outputLogFormatter, + // DUBLICATE, also in web3-eth-contract + subscriptionHandler: function (output) { + if(output.removed) { + this.emit('changed', output); + } else { + this.emit('data', output); + } + + if (_.isFunction(this.callback)) { + this.callback(null, output, this); + } + } + }, + 'syncing': { + params: 0, + 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); + } + } + }, 500); + } + } + } + } + }) + ]; + + 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 . + */ + /** + * @file index.js + * @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', + call: 'net_version', + params: 0, + outputFormatter: utils.hexToNumber + }), + new Method({ + name: 'isListening', + call: 'net_listening', + params: 0 + }), + new Method({ + name: 'getPeerCount', + call: 'net_peerCount', + params: 0, + outputFormatter: utils.hexToNumber + }) + ].forEach(function(method) { + 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 + const ethUtil = require('ethereumjs-util') + const EthBlockTracker = require('eth-block-tracker') + const map = require('async/map') + const eachSeries = require('async/eachSeries') + const Stoplight = require('./util/stoplight.js') + 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 + self._blockTracker = opts.blockTracker || new EthBlockTracker({ + 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 + self._blockTracker.once('block', () => { + self._ready.go() + }) + // local state + 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) + } else { + // 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) { + end(new Error('Request for method "' + payload.method + '" not handled by any subprovider. Please check your subprovider configuration to ensure this method is handled.')) + } else { + try { + var provider = self._providers[currentProvider] + provider.handleRequest(payload, next, end) + } catch (e) { + end(e) + } + } + } + + function end(_error, _result) { + error = _error + result = _result + + eachSeries(stack, function(fn, callback) { + + if (fn) { + fn(error, result, callback) + } else { + callback() + } + }, 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, + code: -32000 + } + // respond with both error formats + finished(error, resultObj) + } else { + finished(null, resultObj) + } + }) + } + } + + // + // 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), + hash: ethUtil.toBuffer(jsonBlock.hash), + parentHash: ethUtil.toBuffer(jsonBlock.parentHash), + nonce: ethUtil.toBuffer(jsonBlock.nonce), + mixHash: ethUtil.toBuffer(jsonBlock.mixHash), + sha3Uncles: ethUtil.toBuffer(jsonBlock.sha3Uncles), + logsBloom: ethUtil.toBuffer(jsonBlock.logsBloom), + transactionsRoot: ethUtil.toBuffer(jsonBlock.transactionsRoot), + stateRoot: ethUtil.toBuffer(jsonBlock.stateRoot), + receiptsRoot: ethUtil.toBuffer(jsonBlock.receiptRoot || jsonBlock.receiptsRoot), + miner: ethUtil.toBuffer(jsonBlock.miner), + difficulty: ethUtil.toBuffer(jsonBlock.difficulty), + totalDifficulty: ethUtil.toBuffer(jsonBlock.totalDifficulty), + size: ethUtil.toBuffer(jsonBlock.size), + extraData: ethUtil.toBuffer(jsonBlock.extraData), + gasLimit: ethUtil.toBuffer(jsonBlock.gasLimit), + gasUsed: ethUtil.toBuffer(jsonBlock.gasUsed), + timestamp: ethUtil.toBuffer(jsonBlock.timestamp), + 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 }; + var space = opts.space || ''; + 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) { + var aobj = { key: a, value: node[a] }; + var bobj = { key: b, value: node[b] }; + return f(aobj, bobj); + }; + }; + })(opts.cmp); + + var seen = []; + return (function stringify (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; + } + if (typeof node !== 'object' || node === null) { + return json.stringify(node); + } + if (isArray(node)) { + var out = []; + for (var i = 0; i < node.length; i++) { + var item = stringify(node, i, node[i], level+1) || json.stringify(null); + out.push(indent + space + item); + } + return '[' + out.join(',') + indent + ']'; + } + else { + if (seen.indexOf(node) !== -1) { + if (cycles) return json.stringify('__cycle__'); + 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; + ; + out.push(indent + space + keyValue); + } + seen.splice(seen.indexOf(node), 1); + return '{' + out.join(',') + indent + '}'; + } + })({ '': 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 = []; + for (var key in obj) { + if (has.call(obj, key)) keys.push(key); + } + return keys; + }; + + },{"jsonify":192}],375:[function(require,module,exports){ + module.exports={ + "_from": "web3-provider-engine@14.1.0", + "_id": "web3-provider-engine@14.1.0", + "_inBundle": false, + "_integrity": "sha512-vGZtqhSUzGTiMGhJXNnB/aRDlrPZLhLnBZ2NPArkZtr8XSrwg9m08tw4+PuWg5za0TJuoE/vuPQc501HddZZWw==", + "_location": "/web3-provider-engine", + "_phantomChildren": { + "jsonify": "0.0.0" + }, + "_requested": { + "type": "version", + "registry": true, + "raw": "web3-provider-engine@14.1.0", + "name": "web3-provider-engine", + "escapedName": "web3-provider-engine", + "rawSpec": "14.1.0", + "saveSpec": null, + "fetchSpec": "14.1.0" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/web3-provider-engine/-/web3-provider-engine-14.1.0.tgz", + "_shasum": "91590020f8b8c1b65846321310cbfdb039090fc6", + "_spec": "web3-provider-engine@14.1.0", + "_where": "/Users/alexvlasov/Blockchain/web3swift/web3swiftJSProxy", + "author": "", + "browser": { + "request": false, + "ws": false + }, + "bugs": { + "url": "https://github.com/MetaMask/provider-engine/issues" + }, + "bundleDependencies": false, + "dependencies": { + "async": "^2.5.0", + "backoff": "^2.5.0", + "clone": "^2.0.0", + "cross-fetch": "^2.1.0", + "eth-block-tracker": "^3.0.0", + "eth-json-rpc-infura": "^3.1.0", + "eth-sig-util": "^1.4.2", + "ethereumjs-block": "^1.2.2", + "ethereumjs-tx": "^1.2.0", + "ethereumjs-util": "^5.1.5", + "ethereumjs-vm": "^2.3.4", + "json-rpc-error": "^2.0.0", + "json-stable-stringify": "^1.0.1", + "promise-to-callback": "^1.0.0", + "readable-stream": "^2.2.9", + "request": "^2.85.0", + "semaphore": "^1.0.3", + "ws": "^5.1.1", + "xhr": "^2.2.0", + "xtend": "^4.0.1" + }, + "deprecated": false, + "description": "[![Greenkeeper badge](https://badges.greenkeeper.io/MetaMask/provider-engine.svg)](https://greenkeeper.io/)", + "devDependencies": { + "babel-cli": "^6.26.0", + "babel-preset-es2015": "^6.24.1", + "babel-preset-stage-0": "^6.24.1", + "browserify": "^16.1.1", + "ethjs": "^0.3.6", + "tape": "^4.4.0" + }, + "homepage": "https://github.com/MetaMask/provider-engine#readme", + "license": "MIT", + "main": "index.js", + "name": "web3-provider-engine", + "repository": { + "type": "git", + "url": "git+https://github.com/MetaMask/provider-engine.git" + }, + "scripts": { + "build": "babel zero.js index.js -d dist/es5 && babel subproviders -d dist/es5/subproviders && babel util -d dist/es5/util", + "bundle": "mkdir -p ./dist && npm run bundle-engine && npm run bundle-zero", + "bundle-engine": "browserify -s ProviderEngine -e index.js -t [ babelify --presets [ es2015 ] ] > dist/ProviderEngine.js", + "bundle-zero": "browserify -s ZeroClientProvider -e zero.js -t [ babelify --presets [ es2015 ] ] > dist/ZeroClientProvider.js", + "prepublish": "npm run build && npm run bundle", + "test": "node test/index.js" + }, + "version": "14.1.0" + } + + },{}],376:[function(require,module,exports){ + const inherits = require('util').inherits + const ethUtil = require('ethereumjs-util') + const BN = ethUtil.BN + const clone = require('clone') + 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 || {} + // set initialization blocker + self._ready = new Stoplight() + self.strategies = { + perma: new ConditionalPermaCacheStrategy({ + eth_getTransactionByHash: containsBlockhash, + eth_getTransactionReceipt: containsBlockhash, + }), + block: new BlockCacheStrategy(self), + fork: new BlockCacheStrategy(self), + } + } + + // setup a block listener on 'setEngine' + BlockCacheProvider.prototype.setEngine = function(engine) { + const self = this + self.engine = engine + // unblock initialization after first block + engine.once('block', function(block) { + self.currentBlock = block + self._ready.go() + // from now on, empty old cache every block + engine.on('block', clearOldCache) + }) + + function clearOldCache(newBlock) { + var previousBlock = self.currentBlock + self.currentBlock = newBlock + if (!previousBlock) return + self.strategies.block.cacheRollOff(previousBlock) + 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') { + requestedBlockNumber = ethUtil.bufferToHex(self.currentBlock.number) + } else { + // 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. + next(function(err, result, cb) { + // err is already handled by engine + if (err) return cb() + strategy.cacheResult(payload, result, requestedBlockNumber, cb) + }) + }) + } + + // + // Cache Strategies + // + + function PermaCacheStrategy() { + var self = this + self.cache = {} + // clear cache every ten minutes + var timeout = setInterval(function(){ + self.cache = {} + }, 10 * 60 * 1e3) + // 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, + // send it back down to the client (where it will be recached.) + var cacheIsEarlyEnough = compareHex(requestedBlockNumber, cached.blockNumber) >= 0 + if (cacheIsEarlyEnough) { + var clonedValue = clone(cached.result) + return hit(null, clonedValue) + } else { + return miss() + } + } + + PermaCacheStrategy.prototype.cacheResult = function(payload, result, requestedBlockNumber, callback) { + var identifier = cacheUtils.cacheIdentifierForPayload(payload) + + if (result) { + var clonedValue = clone(result) + this.cache[identifier] = { + blockNumber: requestedBlockNumber, + 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) + } else { + callback() + } + } else { + // Cache all requests that don't have a conditional + 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] + // create new cache if necesary + if (!blockCache) { + const newCache = {} + this.cache[blockNumber] = newCache + blockCache = newCache + } + 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) + var identifier = cacheUtils.cacheIdentifierForPayload(payload) + blockCache[identifier] = result + } + 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 + const previousHex = ethUtil.bufferToHex(previousBlock.number) + const oldBlockNumber = Number.parseInt(previousHex, 16) + // clear old caches + Object.keys(self.cache) + .map(Number) + .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 || {} + var responses = extend({ + web3_clientVersion: 'ProviderEngine/v'+version+'/javascript', + net_listening: true, + eth_hashrate: '0x00', + eth_mining: false, + }, 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 + const retry = require('async/retry') + const waterfall = require('async/waterfall') + const asyncify = require('async/asyncify') + const JsonRpcError = require('json-rpc-error') + 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', + 'ETIMEDOUT', + // ignore server sent html error pages + // 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: { + 'Accept': 'application/json', + 'Content-Type': 'application/json' + }, + body: JSON.stringify(newPayload) + } + + if (self.originHttpHeaderKey && originDomain) { + reqParams.headers[self.originHttpHeaderKey] = originDomain + } + + retry({ + times: 5, + interval: 1000, + errorFilter: isErrorRetriable, + }, + (cb) => self._submitRequest(reqParams, cb), + (err, result) => { + // ends on retriable error + if (err && isErrorRetriable(err)) { + const errMsg = `FetchSubprovider - cannot complete request. All retries exhausted.\nOriginal Error:\n${err.toString()}\n\n` + const retriesExhaustedErr = new Error(errMsg) + return end(retriesExhaustedErr) + } + // otherwise continue normally + 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, + // buffer body + (cb) => promiseToCallback(res.text())(cb), + // parse body + 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) { + return cb(new JsonRpcError.InternalError(body)) + } + // check for rpc error + if (body.error) return cb(new JsonRpcError.InternalError(body.error)) + // return successful result + cb(null, body.result) + } + }) + } + + 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 + const ethUtil = require('ethereumjs-util') + 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 + // eth_newFilter + // eth_getFilterChanges + // eth_uninstallFilter + // eth_getFilterLogs + + inherits(FilterSubprovider, Subprovider) + + function FilterSubprovider(opts) { + opts = opts || {} + const self = this + self.filterIndex = 0 + self.filters = {} + self.filterDestroyHandlers = {} + self.asyncBlockHandlers = {} + self.asyncPendingBlockHandlers = {} + self._ready = new Stoplight() + self._ready.setMaxListeners(opts.maxFilters || 25) + 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 + self.engine.on('block', function(block){ + // pause processing + self._ready.stop() + // update filters + var updaters = valuesFor(self.asyncBlockHandlers) + .map(function(fn){ return fn.bind(null, block) }) + async.parallel(updaters, function(err){ + if (err) console.error(err) + // unpause processing + self._ready.go() + }) + }) + }) + + } + + 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){ + self._logsForBlock(block, function(err, logs){ + if (err) return cb(err) + newLogHandler(logs) + 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){ + self._txHashesForBlock(block, function(err, txs){ + if (err) return cb(err) + newTxHandler(txs) + 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) + if (!filter) return cb(null, []) + var results = filter.getChanges() + 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) + if (!filter) return cb(null, []) + if (filter.type === 'log') { + self.emitPayload({ + method: 'eth_getLogs', + params: [{ + fromBlock: filter.fromBlock, + toBlock: filter.toBlock, + address: filter.address, + topics: filter.topics, + }], + }, function(err, res){ + if (err) return cb(err) + cb(null, res.result) + }) + } else { + var results = [] + 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 + if (self.checkForPendingBlocksActive) return + var activePendingTxFilters = !!Object.keys(self.asyncPendingBlockHandlers).length + if (activePendingTxFilters) { + self.checkForPendingBlocksActive = true + self.emitPayload({ + method: 'eth_getBlockByNumber', + params: ['pending', true], + }, function(err, res){ + if (err) { + self.checkForPendingBlocksActive = false + console.error(err) + return + } + self.onNewPendingBlock(res.result, function(err){ + if (err) console.error(err) + self.checkForPendingBlocksActive = false + setTimeout(self.checkForPendingBlocks.bind(self), self.pendingBlockTimeout) + }) + }) + } + } + + FilterSubprovider.prototype.onNewPendingBlock = function(block, cb){ + const self = this + // update filters + var updaters = valuesFor(self.asyncPendingBlockHandlers) + .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) + self.emitPayload({ + method: 'eth_getLogs', + params: [{ + fromBlock: blockNumber, + toBlock: blockNumber, + }], + }, function(err, response){ + if (err) return cb(err) + if (response.error) return cb(response.error) + cb(null, response.result) + }) + + } + + FilterSubprovider.prototype._txHashesForBlock = function(block, cb) { + const self = this + var txs = block.transactions + // short circuit if empty + if (txs.length === 0) return cb(null, []) + // txs are already hashes + if ('string' === typeof txs[0]) { + cb(null, txs) + // txs are obj, need to map to hashes + } else { + var results = txs.map((tx) => tx.hash) + cb(null, results) + } + } + + // + // BlockFilter + // + + inherits(BlockFilter, EventEmitter) + + function BlockFilter(opts) { + // console.log('BlockFilter - new') + const self = this + EventEmitter.apply(self) + self.type = 'block' + self.engine = opts.engine + self.blockNumber = opts.blockNumber + self.updates = [] + } + + BlockFilter.prototype.update = function(block){ + // console.log('BlockFilter - update') + const self = this + var blockHash = bufferToHex(block.hash) + 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 + EventEmitter.apply(self) + self.type = 'log' + self.fromBlock = (opts.fromBlock !== undefined) ? opts.fromBlock : 'latest' + self.toBlock = (opts.toBlock !== undefined) ? opts.toBlock : 'latest' + var expectedAddress = opts.address && (Array.isArray(opts.address) ? opts.address : [opts.address]); + self.address = expectedAddress && expectedAddress.map(normalizeHex); + self.topics = opts.topics || [] + 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] + // topics can be null, representing a wild card for that position + // console.log('LogFilter - validateLog - topics', log.topics) + // console.log('LogFilter - validateLog - against topics', self.topics) + var topicsMatch = self.topics.reduce(function(previousMatched, topicPattern, index){ + // abort in progress + if (!previousMatched) return false + // wild card + if (!topicPattern) return true + // pattern is longer than actual topics + var logTopic = log.topics[index] + if (!logTopic) return false + // check each possible matching topic + var subtopicsToMatch = Array.isArray(topicPattern) ? topicPattern : [topicPattern] + var topicDoesMatch = subtopicsToMatch.filter(function(subTopic) { + return logTopic.toLowerCase() === subTopic.toLowerCase() + }).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 + // validate filter match + var validLogs = [] + logs.forEach(function(log) { + var validated = self.validateLog(log) + if (!validated) return + // add to results + validLogs.push(log) + self.updates.push(log) + self.allResults.push(log) + }) + if (validLogs.length > 0) { + 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 + EventEmitter.apply(self) + self.type = 'pendingTx' + 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 + var validTxs = [] + txs.forEach(function (tx) { + // validate filter match + var validated = self.validateUnique(tx) + if (!validated) return + // add to results + validTxs.push(tx) + self.updates.push(tx) + self.allResults.push(tx) + }) + if (validTxs.length > 0) { + 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') { + stripped = stripped.substr(1) + } + 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] + // async function + if ('function' === typeof staticResponse) { + staticResponse(payload, next, end) + // static response - null is valid response + } else if (staticResponse !== undefined) { + // return result asynchronously + setTimeout(() => end(null, staticResponse)) + // no prepared response - skip + } else { + next() + } + } + + },{"./subprovider.js":387,"util":333}],381:[function(require,module,exports){ + /* + * Emulate 'eth_accounts' / 'eth_sendTransaction' using 'eth_sendRawTransaction' + * + * The two callbacks a user needs to implement are: + * - 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 + const ethUtil = require('ethereumjs-util') + const sigUtil = require('eth-sig-util') + const extend = require('xtend') + const Semaphore = require('semaphore') + 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 + // eth_sendTransaction + // eth_sign + // eth_signTypedData + // personal_sign + // personal_ecRecover + // parity_postTransaction + // parity_checkRequest + // parity_defaultAccount + + // + // Tx Signature Flow + // + // handleRequest: eth_sendTransaction + // validateTransaction (basic validity check) + // validateSender (checks that sender is in accounts) + // processTransaction (sign tx and submit to network) + // approveTransaction (UI approval hook) + // checkApproval + // finalizeAndSubmitTx (tx signing) + // nonceLock.take (bottle neck to ensure atomic nonce) + // fillInTxExtras (set fallback gasPrice, nonce, etc) + // 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 + if (opts.processTransaction) self.processTransaction = opts.processTransaction + if (opts.processMessage) self.processMessage = opts.processMessage + if (opts.processPersonalMessage) self.processPersonalMessage = opts.processPersonalMessage + if (opts.processTypedMessage) self.processTypedMessage = opts.processTypedMessage + // approval hooks + self.approveTransaction = opts.approveTransaction || self.autoApprove + self.approveMessage = opts.approveMessage || self.autoApprove + self.approvePersonalMessage = opts.approvePersonalMessage || self.autoApprove + self.approveTypedMessage = opts.approveTypedMessage || self.autoApprove + // actually perform the signature + if (opts.signTransaction) self.signTransaction = opts.signTransaction || mustProvideInConstructor('signTransaction') + if (opts.signMessage) self.signMessage = opts.signMessage || mustProvideInConstructor('signMessage') + if (opts.signPersonalMessage) self.signPersonalMessage = opts.signPersonalMessage || mustProvideInConstructor('signPersonalMessage') + if (opts.signTypedMessage) self.signTypedMessage = opts.signTypedMessage || mustProvideInConstructor('signTypedMessage') + if (opts.recoverPersonalSignature) self.recoverPersonalSignature = opts.recoverPersonalSignature + // 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){ + if (err) return end(err) + let result = accounts[0] || null + end(null, result) + }) + return + + case 'eth_accounts': + // process normally + self.getAccounts(function(err, accounts){ + if (err) return end(err) + end(null, accounts) + }) + return + + case 'eth_sendTransaction': + txParams = payload.params[0] + waterfall([ + (cb) => self.validateTransaction(txParams, cb), + (cb) => self.processTransaction(txParams, cb), + ], end) + return + + case 'eth_signTransaction': + txParams = payload.params[0] + waterfall([ + (cb) => self.validateTransaction(txParams, cb), + (cb) => self.processSignTransaction(txParams, cb), + ], end) + return + + case 'eth_sign': + // process normally + address = payload.params[0] + message = payload.params[1] + // non-standard "extraParams" to be appended to our "msgParams" obj + // good place for metadata + extraParams = payload.params[2] || {} + msgParams = extend(extraParams, { + from: address, + data: message, + }) + waterfall([ + (cb) => self.validateMessage(msgParams, cb), + (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 + // when it is clearly identifiable. + // + // That means when the first param is definitely an address, + // and the second param is definitely not, but is hex. + if (resemblesData(second) && resemblesAddress(first)) { + let warning = `The eth_personalSign method requires params ordered ` + warning += `[message, address]. This was previously handled incorrectly, ` + 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] || {} + msgParams = extend(extraParams, { + from: address, + data: message, + }) + waterfall([ + (cb) => self.validatePersonalMessage(msgParams, cb), + (cb) => self.processPersonalMessage(msgParams, cb), + ], end) + return + + case 'personal_ecRecover': + message = payload.params[0] + let signature = payload.params[1] + // non-standard "extraParams" to be appended to our "msgParams" obj + // good place for metadata + extraParams = payload.params[2] || {} + msgParams = extend(extraParams, { + sig: signature, + data: message, + }) + self.recoverPersonalSignature(msgParams, end) + return + + case 'eth_signTypedData': + // process normally + message = payload.params[0] + address = payload.params[1] + extraParams = payload.params[2] || {} + msgParams = extend(extraParams, { + from: address, + data: message, + }) + waterfall([ + (cb) => self.validateTypedMessage(msgParams, cb), + (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) + const account = accounts[0] || null + 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([ + (cb) => self.approveTransaction(txParams, cb), + (didApprove, cb) => self.checkApproval('transaction', didApprove, cb), + (cb) => self.finalizeAndSubmitTx(txParams, cb), + ], cb) + } + + + HookedWalletSubprovider.prototype.processSignTransaction = function(txParams, cb) { + const self = this + waterfall([ + (cb) => self.approveTransaction(txParams, cb), + (didApprove, cb) => self.checkApproval('transaction', didApprove, cb), + (cb) => self.finalizeTx(txParams, cb), + ], cb) + } + + HookedWalletSubprovider.prototype.processMessage = function(msgParams, cb) { + const self = this + waterfall([ + (cb) => self.approveMessage(msgParams, cb), + (didApprove, cb) => self.checkApproval('message', didApprove, cb), + (cb) => self.signMessage(msgParams, cb), + ], cb) + } + + HookedWalletSubprovider.prototype.processPersonalMessage = function(msgParams, cb) { + const self = this + waterfall([ + (cb) => self.approvePersonalMessage(msgParams, cb), + (didApprove, cb) => self.checkApproval('message', didApprove, cb), + (cb) => self.signPersonalMessage(msgParams, cb), + ], cb) + } + + HookedWalletSubprovider.prototype.processTypedMessage = function(msgParams, cb) { + const self = this + waterfall([ + (cb) => self.approveTypedMessage(msgParams, cb), + (didApprove, cb) => self.checkApproval('message', didApprove, cb), + (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], + }, function(error, res){ + if (error) { + self._parityRequests[reqId] = { error } + return + } + 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], + }, function(error, res){ + if (error) { + self._parityRequests[reqId] = { error } + return + } + 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 + // tx not handled yet + if (!result) return cb(null, null) + // tx was rejected (or other error) + if (result.error) return cb(result.error) + // tx sent + cb(null, result) + } + + // + // signature and recovery + // + + HookedWalletSubprovider.prototype.recoverPersonalSignature = function(msgParams, cb) { + let senderHex + try { + senderHex = sigUtil.recoverPersonalSignature(msgParams) + } catch (err) { + return cb(err) + } + cb(null, senderHex) + } + + // + // validation + // + + HookedWalletSubprovider.prototype.validateTransaction = function(txParams, cb){ + const self = this + // shortcut: undefined sender is invalid + if (txParams.from === undefined) return cb(new Error(`Undefined address - from address required to sign transaction.`)) + self.validateSender(txParams.from, function(err, senderIsValid){ + if (err) return cb(err) + if (!senderIsValid) return cb(new Error(`Unknown address - unable to sign transaction for this address: "${txParams.from}"`)) + 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.`)) + self.validateSender(msgParams.from, function(err, senderIsValid){ + if (err) return cb(err) + if (!senderIsValid) return cb(new Error(`Unknown address - unable to sign message for this address: "${msgParams.from}"`)) + 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.`)) + if (msgParams.data === undefined) return cb(new Error(`Undefined message - message required to sign personal message.`)) + if (!isValidHex(msgParams.data)) return cb(new Error(`HookedWalletSubprovider - validateMessage - message was not encoded as hex.`)) + self.validateSender(msgParams.from, function(err, senderIsValid){ + if (err) return cb(err) + if (!senderIsValid) return cb(new Error(`Unknown address - unable to sign message for this address: "${msgParams.from}"`)) + 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.`)) + this.validateSender(msgParams.from, function(err, senderIsValid){ + if (err) return cb(err) + if (!senderIsValid) return cb(new Error(`Unknown address - unable to sign message for this address: "${msgParams.from}"`)) + cb() + }) + } + + HookedWalletSubprovider.prototype.validateSender = function(senderAddress, cb){ + const self = this + // shortcut: undefined sender is invalid + if (!senderAddress) return cb(null, false) + self.getAccounts(function(err, accounts){ + if (err) return cb(err) + const senderIsValid = (accounts.map(toLowerCase).indexOf(senderAddress.toLowerCase()) !== -1) + 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 + // so we can atomically consume a nonce + self.nonceLock.take(function(){ + waterfall([ + self.fillInTxExtras.bind(self, txParams), + self.signTransaction.bind(self), + self.publishTransaction.bind(self), + ], function(err, txHash){ + self.nonceLock.leave() + if (err) return cb(err) + cb(null, txHash) + }) + }) + } + + HookedWalletSubprovider.prototype.finalizeTx = function(txParams, cb) { + const self = this + // can only allow one tx to pass through this flow at a time + // so we can atomically consume a nonce + self.nonceLock.take(function(){ + waterfall([ + self.fillInTxExtras.bind(self, txParams), + self.signTransaction.bind(self), + ], function(err, signedTx){ + self.nonceLock.leave() + if (err) return cb(err) + cb(null, {raw: signedTx, tx: txParams}) + }) + }) + } + + HookedWalletSubprovider.prototype.publishTransaction = function(rawTx, cb) { + const self = this + self.emitPayload({ + method: 'eth_sendRawTransaction', + params: [rawTx], + }, function(err, res){ + if (err) return cb(err) + 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 { + from: txParams.from, + to: txParams.to, + value: txParams.value, + data: txParams.data, + gas: txParams.gas, + gasPrice: txParams.gasPrice, + 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) { + const fixed = ethUtil.addHexPrefix(string) + const isValidAddress = ethUtil.isValidAddress(fixed) + return !isValidAddress && isValidHex(string) + } + + function isValidHex(data) { + const isString = typeof data === 'string' + if (!isString) return false + const isHexPrefixed = data.slice(0,2) === '0x' + if (!isHexPrefixed) return false + const nonPrefixed = data.slice(2) + 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 + const Transaction = require('ethereumjs-tx') + 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() + var cachedResult = self.nonceCache[address] + // only handle requests against the 'pending' blockTag + if (blockTag === 'pending') { + // has a result + if (cachedResult) { + end(null, cachedResult) + // fallthrough then populate cache + } else { + next(function(err, result, cb){ + if (err) return cb() + if (self.nonceCache[address] === undefined) { + self.nonceCache[address] = result + } + cb() + }) + } + } else { + next() + } + return + + case 'eth_sendRawTransaction': + // allow the request to continue normally + next(function(err, result, cb){ + // only update local nonce if tx was submitted correctly + if (err) return cb() + // parse raw tx + var rawTx = payload.params[0] + var stripped = ethUtil.stripHexPrefix(rawTx) + var rawData = new Buffer(ethUtil.stripHexPrefix(rawTx), 'hex') + var tx = new Transaction(new Buffer(ethUtil.stripHexPrefix(rawTx), 'hex')) + // extract address + var address = '0x'+tx.getSenderAddress().toString('hex').toLowerCase() + // extract nonce and increment + var nonce = ethUtil.bufferToInt(tx.nonce) + nonce++ + // hexify and normalize + var hexNonce = nonce.toString(16) + if (hexNonce.length%2) hexNonce = '0'+hexNonce + hexNonce = '0x'+hexNonce + // dont update our record on the nonce until the submit was successful + // update cache + self.nonceCache[address] = hexNonce + 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) + if (response.error) return end(new Error(response.error.message)) + 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', + 'to', + 'value', + 'data', + 'gas', + 'gasPrice', + 'nonce', + 'fromBlock', + 'toBlock', + 'address', + 'topics', + ] + + function cloneTxParams(txParams){ + var sanitized = permitted.reduce(function(copy, permitted) { + if (permitted in txParams) { + if (Array.isArray(txParams[permitted])) { + copy[permitted] = txParams[permitted] + .map(function(item) { + return sanitize(item) + }) + } else { + copy[permitted] = sanitize(txParams[permitted]) + } + } + return copy + }, {}) + + return sanitized + } + + function sanitize(value) { + switch (value) { + case 'latest': + return value + case 'pending': + return value + case 'earliest': + return value + default: + if (typeof value === 'string') { + return ethUtil.addHexPrefix(value.toLowerCase()) + } else { + return value + } + } + } + + },{"./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 + engine.on('block', function(block) { + 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) + } + },{"../util/create-payload.js":391}],388:[function(require,module,exports){ + const EventEmitter = require('events').EventEmitter + const FilterSubprovider = require('./filters.js') + 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': + createSubscriptionFilter = self.newPendingTransactionFilter.bind(self) + break + case 'newHeads': + createSubscriptionFilter = self.newBlockFilter.bind(self) + break + case 'syncing': + default: + 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() + }) + if (subscriptionType === 'newPendingTransactions') { + self.checkForPendingBlocks() + } + cb(null, hexId) + }) + } + + SubscriptionSubprovider.prototype.eth_unsubscribe = function(payload, cb) { + const self = this + let hexId = payload.params[0] + const id = Number.parseInt(hexId, 16) + if (!self.subscriptions[id]) { + cb(new Error(`Subscription ID ${hexId} not found.`)) + } else { + let subscriptionType = self.subscriptions[id] + self.uninstallFilter(hexId, function (err, result) { + delete self.subscriptions[id] + cb(err, result) + }) + } + } + + + 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, { + jsonrpc: "2.0", + method: "eth_subscription", + params: { + subscription: hexId, + result: result, + }, + }) + } + + SubscriptionSubprovider.prototype._notificationResultFromBlock = function(block) { + return { + hash: utils.bufferToHex(block.hash), + parentHash: utils.bufferToHex(block.parentHash), + sha3Uncles: utils.bufferToHex(block.sha3Uncles), + miner: utils.bufferToHex(block.miner), + stateRoot: utils.bufferToHex(block.stateRoot), + transactionsRoot: utils.bufferToHex(block.transactionsRoot), + receiptsRoot: utils.bufferToHex(block.receiptsRoot), + logsBloom: utils.bufferToHex(block.logsBloom), + difficulty: from.intToQuantityHex(utils.bufferToInt(block.difficulty)), + number: from.intToQuantityHex(utils.bufferToInt(block.number)), + gasLimit: from.intToQuantityHex(utils.bufferToInt(block.gasLimit)), + gasUsed: from.intToQuantityHex(utils.bufferToInt(block.gasUsed)), + nonce: block.nonce ? utils.bufferToHex(block.nonce): null, + mixHash: utils.bufferToHex(block.mixHash), + timestamp: from.intToQuantityHex(utils.bufferToInt(block.timestamp)), + extraData: utils.bufferToHex(block.extraData) + } + } + + SubscriptionSubprovider.prototype.handleRequest = function(payload, next, end) { + switch(payload.method){ + case 'eth_subscribe': + this.eth_subscribe(payload, end) + break + case 'eth_unsubscribe': + this.eth_unsubscribe(payload, end) + break + default: + 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') + const EventEmitter = require('events') + const inherits = require('util').inherits + 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({ + randomisationFactor: 0.2, + maxDelay: 5000 + }) + }, + _connectTime: { + value: null, + writable: true + }, + _log: { + value: debug + ? (...args) => console.info.apply(console, ['[WSProvider]', ...args]) + : () => { } + }, + _origin: { + value: origin + }, + _pendingRequests: { + value: new Map() + }, + _socket: { + value: null, + writable: true + }, + _unhandledRequests: { + value: [] + }, + _url: { + 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}) + this._socket.addEventListener('close', this._handleSocketClose) + this._socket.addEventListener('message', this._handleSocketMessage) + 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 + id: getRandomId(), + jsonrpc: '2.0', + params: [], + // 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', + params: [txParams] + }), function(err, res){ + if (err) { + // handle simple value transfer case + if (err.message === 'no contract code at given address') { + return cb(null, '0xcf08') + } else { + return cb(err) + } + } + cb(null, res.result) + }) + } + },{"./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) + // 3 random digits + var extraPart = Math.floor(Math.random()*Math.pow(10, extraDigits)) + // 16 digits + return datePart+extraPart + } + },{}],394:[function(require,module,exports){ + const stringify = require('json-stable-stringify') + + module.exports = { + cacheIdentifierForPayload: cacheIdentifierForPayload, + canCache: canCache, + blockTagForPayload: blockTagForPayload, + paramsWithoutBlockTag: paramsWithoutBlockTag, + 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 + case 'eth_getStorageAt': + return 2 + // blockTag is second param + case 'eth_getBalance': + case 'eth_getCode': + case 'eth_getTransactionCount': + case 'eth_call': + case 'eth_estimateGas': + return 1 + // blockTag is first param + case 'eth_getBlockByNumber': + return 0 + // there is no blockTag + default: + return undefined + } + } + + function cacheTypeForPayload(payload) { + switch (payload.method) { + // cache permanently + case 'web3_clientVersion': + case 'web3_sha3': + case 'eth_protocolVersion': + case 'eth_getBlockTransactionCountByHash': + case 'eth_getUncleCountByBlockHash': + case 'eth_getCode': + case 'eth_getBlockByHash': + case 'eth_getTransactionByHash': + case 'eth_getTransactionByBlockHashAndIndex': + case 'eth_getTransactionReceipt': + case 'eth_getUncleByBlockHashAndIndex': + case 'eth_getCompilers': + case 'eth_compileLLL': + case 'eth_compileSolidity': + case 'eth_compileSerpent': + case 'shh_version': + return 'perma' + + // cache until fork + case 'eth_getBlockByNumber': + case 'eth_getBlockTransactionCountByNumber': + case 'eth_getUncleCountByBlockNumber': + case 'eth_getTransactionByBlockNumberAndIndex': + case 'eth_getUncleByBlockNumberAndIndex': + return 'fork' + + // cache for block + case 'eth_gasPrice': + case 'eth_blockNumber': + case 'eth_getBalance': + case 'eth_getStorageAt': + case 'eth_getTransactionCount': + case 'eth_call': + case 'eth_estimateGas': + case 'eth_getFilterLogs': + case 'eth_getLogs': + case 'net_peerCount': + return 'block' + + // never cache + case 'net_version': + case 'net_peerCount': + case 'net_listening': + case 'eth_syncing': + case 'eth_sign': + case 'eth_coinbase': + case 'eth_mining': + case 'eth_hashrate': + case 'eth_accounts': + case 'eth_sendTransaction': + case 'eth_sendRawTransaction': + case 'eth_newFilter': + case 'eth_newBlockFilter': + case 'eth_newPendingTransactionFilter': + case 'eth_uninstallFilter': + case 'eth_getFilterChanges': + case 'eth_getWork': + case 'eth_submitWork': + case 'eth_submitHashrate': + case 'db_putString': + case 'db_getString': + case 'db_putHex': + case 'db_getHex': + case 'shh_post': + case 'shh_newIdentity': + case 'shh_hasIdentity': + case 'shh_newGroup': + case 'shh_addToGroup': + case 'shh_newFilter': + case 'shh_uninstallFilter': + case 'shh_getFilterChanges': + case 'shh_getMessages': + 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') + if (nHex[0] === '0') { + nHex = nHex.substring(1) + } + return ethUtil.addHexPrefix(nHex) + } + + function quantityHexToInt(prefixedQuantityHex) { + assert(typeof prefixedQuantityHex === 'string', 'arg to quantityHexToInt must be a string') + var quantityHex = ethUtil.stripHexPrefix(prefixedQuantityHex) + var isEven = quantityHex.length % 2 === 0 + if (!isEven) { + quantityHex = '0' + quantityHex + } + 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) { + self.once('unlock', fn) + } else { + setTimeout(fn) + } + } + },{"events":157,"util":333}],397:[function(require,module,exports){ + const ProviderEngine = require('./index.js') + const DefaultFixture = require('./subproviders/default-fixture.js') + const NonceTrackerSubprovider = require('./subproviders/nonce-tracker.js') + const CacheSubprovider = require('./subproviders/cache.js') + const FilterSubprovider = require('./subproviders/filters.js') + const SubscriptionSubprovider = require('./subproviders/subscriptions') + const InflightCacheSubprovider = require('./subproviders/inflight-cache') + const HookedWalletSubprovider = require('./subproviders/hooked-wallet.js') + const SanitizingSubprovider = require('./subproviders/sanitizer.js') + 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') { + const filterSubprovider = new FilterSubprovider() + engine.addProvider(filterSubprovider) + // otherwise, polyfill both subscriptions and filters + } else { + const filterAndSubsSubprovider = new SubscriptionSubprovider() + // forward subscription events through provider + filterAndSubsSubprovider.on('data', (err, notification) => { + engine.emit('data', err, notification) + }) + engine.addProvider(filterAndSubsSubprovider) + } + + // inflight cache + const inflightCache = new InflightCacheSubprovider() + engine.addProvider(inflightCache) + + // id mgmt + const idmgmtSubprovider = new HookedWalletSubprovider({ + // accounts + getAccounts: opts.getAccounts, + // transactions + processTransaction: opts.processTransaction, + approveTransaction: opts.approveTransaction, + signTransaction: opts.signTransaction, + publishTransaction: opts.publishTransaction, + // messages + // old eth_sign + processMessage: opts.processMessage, + approveMessage: opts.approveMessage, + signMessage: opts.signMessage, + // new personal_sign + processPersonalMessage: opts.processPersonalMessage, + processTypedMessage: opts.processTypedMessage, + approvePersonalMessage: opts.approvePersonalMessage, + approveTypedMessage: opts.approveTypedMessage, + signPersonalMessage: opts.signPersonalMessage, + signTypedMessage: opts.signTypedMessage, + personalRecoverSigner: opts.personalRecoverSigner, + }) + engine.addProvider(idmgmtSubprovider) + + // data source + const dataSubprovider = opts.dataSubprovider || createDataSubprovider(connectionType, opts) + // for websockets, forward subscription events through provider + if (connectionType === 'ws') { + dataSubprovider.on('data', (err, notification) => { + engine.emit('data', err, notification) + }) + } + 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() + } + if (connectionType === 'http') { + return new FetchSubprovider({ rpcUrl, debug }) + } + 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': + case 'https': + return 'http' + case 'ws': + case 'wss': + return 'ws' + default: + 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 . + */ + /** @file httpprovider.js + * @authors: + * Marek Kotewicz + * Marian Oancea + * 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 + */ + var HttpProvider = function HttpProvider(host, options) { + options = options || {}; + this.host = host || 'http://localhost:8545'; + if (this.host.substring(0,5) === "https"){ + this.httpsAgent = new https.Agent({ keepAlive: true }); + }else{ + this.httpAgent = new http.Agent({ keepAlive: true }); + } + this.timeout = options.timeout || 0; + 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 + * + * @method send + * @param {Object} payload + * @param {Function} callback triggered on end with (err, result) + */ + 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) { + this.connected = false; + 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 . + */ + /** @file index.js + * @authors: + * 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){ + if(_this.responseCallbacks[load.id]) + id = load.id; + }); + } 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) + .done(callback); + } else { + this.connection.on('data', function(data){ + _this._parseResponse(data.toString()).forEach(callback); + }); + } + }; + + /** + 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,'}|--|{') // }{ + .replace(/\}\][\n\r]?\[\{/g,'}]|--|[{') // }][{ + .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() { + for(var key in this.responseCallbacks) { + if(this.responseCallbacks.hasOwnProperty(key)){ + this.responseCallbacks[key](errors.InvalidConnection('on IPC')); + delete this.responseCallbacks[key]; + } + } + }; + + /** + 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){ + if(cb === callback) + _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' + */ + IpcProvider.prototype.removeAllListeners = function (type) { + switch(type){ + 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 . + */ + /** @file WebsocketProvider.js + * @authors: + * 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; + if (typeof window !== 'undefined' && typeof window.WebSocket !== 'undefined') { + Ws = function(url, protocols) { + return new window.WebSocket(url, protocols); + }; + _btoa = btoa; + parseURL = function(url) { + return new URL(url); + }; + } else { + Ws = require('websocket').w3cwebsocket; + _btoa = function(str) { + return Buffer(str).toString('base64'); + }; + var url = require('url'); + if (url.URL) { + // Use the new Node 6+ API for parsing URLs that supports username/password + var newURL = url.URL; + parseURL = function(url) { + return new newURL(url); + }; + } + else { + // Web3 supports Node.js 5, so fall back to the legacy URL API if necessary + parseURL = require('url').parse; + } + } + // 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 + var parsedURL = parseURL(url); + var headers = options.headers || {}; + var protocol = options.protocol || undefined; + 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){ + if(_this.responseCallbacks[load.id]) + id = load.id; + }); + } 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); + delete _this.responseCallbacks[id]; + } + }); + }; + + // make property `connected` which will return the current connection status + Object.defineProperty(this, 'connected', { + get: function () { + return this.connection && this.connection.readyState === this.connection.OPEN; + }, + 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,'}|--|{') // }{ + .replace(/\}\][\n\r]?\[\{/g,'}]|--|[{') // }][{ + .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 () { + if (_this.responseCallbacks[id]) { + _this.responseCallbacks[id](errors.ConnectionTimeout(_this._customTimeout)); + delete _this.responseCallbacks[id]; + } + }, this._customTimeout); + } + }; + + /** + Timeout all requests when the end/error event is fired + + @method _timeout + */ + WebsocketProvider.prototype._timeout = function() { + for(var key in this.responseCallbacks) { + if(this.responseCallbacks.hasOwnProperty(key)){ + this.responseCallbacks[key](errors.InvalidConnection('on WS')); + delete this.responseCallbacks[key]; + } + } + }; + + + 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}); + if (this.connection.readyState !== this.connection.OPEN) { + console.error('connection not open on send()'); + if (typeof this.connection.onerror === 'function') { + this.connection.onerror(new Error('connection not open')); + } else { + console.error('no error callback'); + } + 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){ + if(cb === callback) + _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' + */ + WebsocketProvider.prototype.removeAllListeners = function (type) { + switch(type){ + 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 . + */ + /** + * @file index.js + * @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', + type: 'shh', + subscriptions: { + 'messages': { + params: 1 + // inputFormatter: [formatters.inputPostFormatter], + // outputFormatter: formatters.outputPostFormatter + } + } + }), + + new Method({ + name: 'getVersion', + call: 'shh_version', + params: 0 + }), + new Method({ + name: 'getInfo', + call: 'shh_info', + params: 0 + }), + new Method({ + name: 'setMaxMessageSize', + call: 'shh_setMaxMessageSize', + params: 1 + }), + new Method({ + name: 'setMinPoW', + call: 'shh_setMinPoW', + params: 1 + }), + new Method({ + name: 'markTrustedPeer', + call: 'shh_markTrustedPeer', + params: 1 + }), + new Method({ + name: 'newKeyPair', + call: 'shh_newKeyPair', + params: 0 + }), + new Method({ + name: 'addPrivateKey', + call: 'shh_addPrivateKey', + params: 1 + }), + new Method({ + name: 'deleteKeyPair', + call: 'shh_deleteKeyPair', + params: 1 + }), + new Method({ + name: 'hasKeyPair', + call: 'shh_hasKeyPair', + params: 1 + }), + new Method({ + name: 'getPublicKey', + call: 'shh_getPublicKey', + params: 1 + }), + new Method({ + name: 'getPrivateKey', + call: 'shh_getPrivateKey', + params: 1 + }), + new Method({ + name: 'newSymKey', + call: 'shh_newSymKey', + params: 0 + }), + new Method({ + name: 'addSymKey', + call: 'shh_addSymKey', + params: 1 + }), + new Method({ + name: 'generateSymKeyFromPassword', + call: 'shh_generateSymKeyFromPassword', + params: 1 + }), + new Method({ + name: 'hasSymKey', + call: 'shh_hasSymKey', + params: 1 + }), + new Method({ + name: 'getSymKey', + call: 'shh_getSymKey', + params: 1 + }), + new Method({ + name: 'deleteSymKey', + call: 'shh_deleteSymKey', + params: 1 + }), + + new Method({ + name: 'newMessageFilter', + call: 'shh_newMessageFilter', + params: 1 + }), + new Method({ + name: 'getFilterMessages', + call: 'shh_getFilterMessages', + params: 1 + }), + new Method({ + name: 'deleteMessageFilter', + call: 'shh_deleteMessageFilter', + params: 1 + }), + + new Method({ + name: 'post', + call: 'shh_post', + params: 1, + inputFormatter: [null] + }), + + new Method({ + name: 'unsubscribe', + call: 'shh_unsubscribe', + params: 1 + }) + ].forEach(function(method) { + method.attachToObject(_this); + 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 . + */ + /** + * @file utils.js + * @author Marek Kotewicz + * @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 + * + * @method _fireError + * @param {Object} error a string, a error, or an object with {message, data} + * @param {Object} emitter + * @param {Function} reject + * @param {Function} callback + * @return {Object} the emitter + */ + 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); + } + if (_.isFunction(reject)) { + // suppress uncatched error if an error listener is present + // OR suppress uncatched error if an callback listener is present + if (emitter && + (_.isFunction(emitter.listeners) && + emitter.listeners('error').length) || _.isFunction(callback)) { + emitter.catch(function(){}); + } + // reject later, to be able to return emitter + setTimeout(function () { + reject(error); + }, 1); + } + + if(emitter && _.isFunction(emitter.emit)) { + // emit later, to be able to return emitter + setTimeout(function () { + emitter.emit('error', error); + emitter.removeAllListeners(); + }, 1); + } + + return emitter; + }; + + /** + * Should be used to create full function/event name from json abi + * + * @method _jsonInterfaceMethodToString + * @param {Object} json + * @return {String} full function/event name + */ + var _jsonInterfaceMethodToString = function (json) { + 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 + * + * @method _flattenTypes + * @param {bool} includeTuple + * @param {Object} puts + * @return {Array} parameters as strings + */ + var _flattenTypes = function(includeTuple, puts) + { + // 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') { + throw new Error('components found but type is not tuple; report on GitHub'); + } + var suffix = ''; + var arrayBracket = param.type.indexOf('['); + if (arrayBracket >= 0) { suffix = param.type.substring(arrayBracket); } + var result = _flattenTypes(includeTuple, param.components); + // console.log("result should have things: " + result) + if(_.isArray(result) && includeTuple) { + // console.log("include tuple word, and its an array. joining...: " + result.types) + types.push('tuple(' + result.join(',') + ')' + suffix); + } + else if(!includeTuple) { + // console.log("don't include tuple, but its an array. joining...: " + result) + types.push('(' + result.join(',') + ')' + suffix); + } + else { + // console.log("its a single type within a tuple: " + result.types) + types.push('(' + result + ')'); + } + } else { + // console.log("its a type and not directly in a tuple: " + param.type) + types.push(param.type); + } + }); + + return types; + }; + + + /** + * Should be called to get ascii from it's hex representation + * + * @method hexToAscii + * @param {String} hex + * @returns {String} ascii string representation of hex value + */ + 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') { + 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 ascii string + * + * @method asciiToHex + * @param {String} str + * @returns {String} hex representation of input string + */ + var asciiToHex = function(str) { + if(!str) + return "0x00"; + var hex = ""; + for(var i = 0; i < str.length; i++) { + var code = str.charCodeAt(i); + var n = code.toString(16); + hex += n.length < 2 ? '0' + n : n; + } + + return "0x" + hex; + }; + + + + /** + * Returns value of unit in Wei + * + * @method getUnitValue + * @param {String} unit the unit to convert to, default ether + * @returns {BN} value of the unit (in Wei) + * @throws error if the unit is not correct:w + */ + var getUnitValue = function (unit) { + unit = unit ? unit.toLowerCase() : 'ether'; + if (!ethjsUnit.unitMap[unit]) { + throw new Error('This unit "'+ unit +'" doesn\'t exist, please use the one of the following units' + JSON.stringify(ethjsUnit.unitMap, null, 2)); + } + return unit; + }; + + /** + * Takes a number of wei and converts it to any other ether unit. + * + * Possible units are: + * SI Short SI Full Effigy Other + * - kwei femtoether babbage + * - mwei picoether lovelace + * - gwei nanoether shannon nano + * - -- microether szabo micro + * - -- milliether finney milli + * - ether -- -- + * - kether -- grand + * - mether + * - gether + * - tether + * + * @method fromWei + * @param {Number|String} number can be a number, number string or a HEX of a decimal + * @param {String} unit the unit to convert to, default ether + * @return {String|Object} When given a BN object it returns one as well, otherwise a number + */ + 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. + * + * Possible units are: + * SI Short SI Full Effigy Other + * - kwei femtoether babbage + * - mwei picoether lovelace + * - gwei nanoether shannon nano + * - -- microether szabo micro + * - -- microether szabo micro + * - -- milliether finney milli + * - ether -- -- + * - kether -- grand + * - mether + * - gether + * - tether + * + * @method toWei + * @param {Number|String|BN} number can be a number, number string or a HEX of a decimal + * @param {String} unit the unit to convert from, default ether + * @return {String|Object} When given a BN object it returns one as well, otherwise a number + */ + 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 + * + * @method toChecksumAddress + * @param {String} address the given HEX address + * @return {String} + */ + 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) { + checksumAddress += address[i].toUpperCase(); + } else { + checksumAddress += address[i]; + } + } + return checksumAddress; + }; + + + + module.exports = { + _fireError: _fireError, + _jsonInterfaceMethodToString: _jsonInterfaceMethodToString, + _flattenTypes: _flattenTypes, + // extractDisplayName: extractDisplayName, + // extractTypeName: extractTypeName, + randomHex: randomHex, + _: _, + BN: utils.BN, + isBN: utils.isBN, + isBigNumber: utils.isBigNumber, + isHex: utils.isHex, + isHexStrict: utils.isHexStrict, + sha3: utils.sha3, + keccak256: utils.sha3, + soliditySha3: soliditySha3, + isAddress: utils.isAddress, + checkAddressChecksum: utils.checkAddressChecksum, + 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 . + */ + /** + * @file soliditySha3.js + * @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') { + return 'int256'; + } else if (name.startsWith('uint[')) { + return 'uint256' + name.slice(4); + } else if (name === 'uint') { + return 'uint256'; + } else if (name.startsWith('fixed[')) { + return 'fixed128x128' + name.slice(5); + } else if (name === 'fixed') { + return 'fixed128x128'; + } else if (name.startsWith('ufixed[')) { + return 'ufixed128x128' + name.slice(6); + } else if (name === 'ufixed') { + return 'ufixed128x128'; + } + 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') { + if (utils.isHexStrict(arg)) { + return new BN(arg.replace(/0x/i,''), 16); + } else { + return new BN(arg, 10); + } + } else if (type === 'number') { + return new BN(arg); + } else if (utils.isBigNumber(arg)) { + return new BN(arg.toString(10)); + } else if (utils.isBN(arg)) { + return arg; + } else { + 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); + } else if (type === 'bool') { + return value ? '01' : '00'; + } else if (type.startsWith('address')) { + if(arraySize) { + size = 64; + } 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); + if(arraySize && value.length !== arraySize) { + throw new Error(type +' is not matching the given array '+ JSON.stringify(value)); + } else { + arraySize = value.length; + } + } + + + if (_.isArray(value)) { + hexArg = value.map(function (val) { + return _solidityPack(type, val, arraySize).toString('hex').replace('0x',''); + }); + return hexArg.join(''); + } else { + hexArg = _solidityPack(type, value, arraySize); + return hexArg.toString('hex').replace('0x',''); + } + + }; + + /** + * Hashes solidity values to a sha3 hash using keccak 256 + * + * @method soliditySha3 + * @return {Object} the sha3 + */ + 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 . + */ + /** + * @file utils.js + * @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 + * + * @method isBN + * @param {Object} object + * @return {Boolean} + */ + var isBN = function (object) { + return object instanceof BN || + (object && object.constructor && object.constructor.name === 'BN'); + }; + + /** + * Returns true if object is BigNumber, otherwise false + * + * @method isBigNumber + * @param {Object} object + * @return {Boolean} + */ + var isBigNumber = function (object) { + return object && object.constructor && object.constructor.name === 'BigNumber'; + }; + + /** + * Takes an input and transforms it into an BN + * + * @method toBN + * @param {Number|String|BN} number, string, HEX string or BN + * @return {BN} BN + */ + var toBN = function(number){ + try { + return numberToBN.apply(null, arguments); + } catch(e) { + throw new Error(e + ' Given value: "'+ number +'"'); + } + }; + + + /** + * Takes and input transforms it into BN and if it is negative value, into two's complement + * + * @method toTwosComplement + * @param {Number|String|BN} number + * @return {String} + */ + var toTwosComplement = function (number) { + return '0x'+ toBN(number).toTwos(256).toString(16, 64); + }; + + /** + * Checks if the given string is an address + * + * @method isAddress + * @param {String} address the given HEX address + * @return {Boolean} + */ + var isAddress = function (address) { + // check if it has the basic requirements of an address + if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) { + return false; + // If it's ALL lowercase or ALL upppercase + } else if (/^(0x|0X)?[0-9a-f]{40}$/.test(address) || /^(0x|0X)?[0-9A-F]{40}$/.test(address)) { + return true; + // Otherwise check each case + } else { + return checkAddressChecksum(address); + } + }; + + + + /** + * Checks if the given string is a checksummed address + * + * @method checkAddressChecksum + * @param {String} address the given HEX address + * @return {Boolean} + */ + var checkAddressChecksum = function (address) { + // 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])) { + return false; + } + } + return true; + }; + + /** + * Should be called to pad string to expected length + * + * @method leftPad + * @param {String} string to be padded + * @param {Number} chars that result string should have + * @param {String} sign, by default 0 + * @returns {String} right aligned string + */ + 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 + * + * @method rightPad + * @param {String} string to be padded + * @param {Number} chars that result string should have + * @param {String} sign, by default 0 + * @returns {String} right aligned string + */ + 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 + * + * @method utf8ToHex + * @param {String} str + * @returns {String} hex representation of input string + */ + 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) { + var n = code.toString(16); + hex += n.length < 2 ? '0' + n : n; + // } + } + + return "0x" + hex; + }; + + /** + * Should be called to get utf8 from it's hex representation + * + * @method hexToUtf8 + * @param {String} hex + * @returns {String} ascii string representation of hex value + */ + 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 + * + * @method hexToNumber + * @param {String|Number|BN} value + * @return {String} + */ + var hexToNumber = function (value) { + if (!value) { + return value; + } + + return toBN(value).toNumber(); + }; + + /** + * Converts value to it's decimal representation in string + * + * @method hexToNumberString + * @param {String|Number|BN} value + * @return {String} + */ + var hexToNumberString = function (value) { + if (!value) return value; + + return toBN(value).toString(10); + }; + + + /** + * Converts value to it's hex representation + * + * @method numberToHex + * @param {String|Number|BN} value + * @return {String} + */ + var numberToHex = function (value) { + 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 + * + * Note: Implementation from crypto-js + * + * @method bytesToHex + * @param {Array} bytes + * @return {String} the hex string + */ + var bytesToHex = function(bytes) { + for (var hex = [], i = 0; i < bytes.length; i++) { + /* jshint ignore:start */ + hex.push((bytes[i] >>> 4).toString(16)); + hex.push((bytes[i] & 0xF).toString(16)); + /* jshint ignore:end */ + } + return '0x'+ hex.join(""); + }; + + /** + * Convert a hex string to a byte array + * + * Note: Implementation from crypto-js + * + * @method hexToBytes + * @param {string} hex + * @return {Array} the byte array + */ + 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. + * + * And even stringifys objects before. + * + * @method toHex + * @param {String|Number|BN|Object} value + * @param {Boolean} returnType + * @return {String} + */ + 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) { + return returnType ? 'int256' : numberToHex(value); + } else if(value.indexOf('0x') === 0 || value.indexOf('0X') === 0) { + return returnType ? 'bytes' : value; + } else if (!isFinite(value)) { + return returnType ? 'string' : utf8ToHex(value); + } + } + + return returnType ? (value < 0 ? 'int256' : 'uint256') : numberToHex(value); + }; + + + /** + * Check if string is HEX, requires a 0x in front + * + * @method isHexStrict + * @param {String} hex to be checked + * @returns {Boolean} + */ + var isHexStrict = function (hex) { + return ((_.isString(hex) || _.isNumber(hex)) && /^(-)?0x[0-9a-f]*$/i.test(hex)); + }; + + /** + * Check if string is HEX + * + * @method isHex + * @param {String} hex to be checked + * @returns {Boolean} + */ + 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. + * + * TODO UNDOCUMENTED + * + * @method isBloom + * @param {String} hex encoded bloom filter + * @return {Boolean} + */ + var isBloom = function (bloom) { + if (!/^(0x)?[0-9a-f]{512}$/i.test(bloom)) { + return false; + } else if (/^(0x)?[0-9a-f]{512}$/.test(bloom) || /^(0x)?[0-9A-F]{512}$/.test(bloom)) { + return true; + } + return false; + }; + + /** + * Returns true if given string is a valid log topic. + * + * TODO UNDOCUMENTED + * + * @method isTopic + * @param {String} hex encoded topic + * @return {Boolean} + */ + var isTopic = function (topic) { + if (!/^(0x)?[0-9a-f]{64}$/i.test(topic)) { + return false; + } else if (/^(0x)?[0-9a-f]{64}$/.test(topic) || /^(0x)?[0-9A-F]{64}$/.test(topic)) { + return true; + } + return false; + }; + + + /** + * Hashes values to a sha3 hash using keccak 256 + * + * To hash a HEX string the hex must have 0x in front. + * + * @method sha3 + * @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 { + return returnValue; + } + }; + // expose the under the hood keccak256 + sha3._Hash = Hash; + + + module.exports = { + BN: BN, + isBN: isBN, + isBigNumber: isBigNumber, + toBN: toBN, + isAddress: isAddress, + isBloom: isBloom, // TODO UNDOCUMENTED + isTopic: isTopic, // TODO UNDOCUMENTED + checkAddressChecksum: checkAddressChecksum, + utf8ToHex: utf8ToHex, + hexToUtf8: hexToUtf8, + hexToNumber: hexToNumber, + hexToNumberString: hexToNumberString, + numberToHex: numberToHex, + toHex: toHex, + hexToBytes: hexToBytes, + bytesToHex: bytesToHex, + isHex: isHex, + isHexStrict: isHexStrict, + leftPad: leftPad, + rightPad: rightPad, + 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", + "_id": "web3@1.0.0-beta.36", + "_inBundle": false, + "_integrity": "sha512-fZDunw1V0AQS27r5pUN3eOVP7u8YAvyo6vOapdgVRolAu5LgaweP7jncYyLINqIX9ZgWdS5A090bt+ymgaYHsw==", + "_location": "/web3", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "web3@1.0.0-beta.36", + "name": "web3", + "escapedName": "web3", + "rawSpec": "1.0.0-beta.36", + "saveSpec": null, + "fetchSpec": "1.0.0-beta.36" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/web3/-/web3-1.0.0-beta.36.tgz", + "_shasum": "2954da9e431124c88396025510d840ba731c8373", + "_spec": "web3@1.0.0-beta.36", + "_where": "/Users/alexvlasov/Blockchain/web3swift/web3swiftJSProxy", + "author": { + "name": "ethereum.org" + }, + "authors": [ + { + "name": "Fabian Vogelsteller", + "email": "fabian@ethereum.org", + "homepage": "http://frozeman.de" + }, + { + "name": "Marek Kotewicz", + "email": "marek@parity.io", + "url": "https://github.com/debris" + }, + { + "name": "Marian Oancea", + "url": "https://github.com/cubedro" + }, + { + "name": "Gav Wood", + "email": "g@parity.io", + "homepage": "http://gavwood.com" + }, + { + "name": "Jeffery Wilcke", + "email": "jeffrey.wilcke@ethereum.org", + "url": "https://github.com/obscuren" + } + ], + "bugs": { + "url": "https://github.com/ethereum/web3.js/issues" + }, + "bundleDependencies": false, + "dependencies": { + "web3-bzz": "1.0.0-beta.36", + "web3-core": "1.0.0-beta.36", + "web3-eth": "1.0.0-beta.36", + "web3-eth-personal": "1.0.0-beta.36", + "web3-net": "1.0.0-beta.36", + "web3-shh": "1.0.0-beta.36", + "web3-utils": "1.0.0-beta.36" + }, + "deprecated": false, + "description": "Ethereum JavaScript API", + "keywords": [ + "Ethereum", + "JavaScript", + "API" + ], + "license": "LGPL-3.0", + "main": "src/index.js", + "name": "web3", + "namespace": "ethereum", + "repository": { + "type": "git", + "url": "https://github.com/ethereum/web3.js/tree/master/packages/web3" + }, + "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 . + */ + /** + * @file index.js + * @authors: + * Fabian Vogelsteller + * Gav Wood + * Jeffrey Wilcke + * Marek Kotewicz + * Marian Oancea + * @date 2017 + */ + + "use strict"; + + + var version = require('../package.json').version; + var core = require('web3-core'); + var Eth = require('web3-eth'); + var Net = require('web3-net'); + var Personal = require('web3-eth-personal'); + 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 = { + Eth: Eth, + Net: Net, + Personal: Personal, + 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 + * instance of W3CWebSocket via 'new W3CWebSocket()'. + * + * ECMAScript 5: http://bclary.com/2004/11/07/#a-13.2.2 + */ + return native_instance; + } + if (NativeWebSocket) { + ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'].forEach(function(prop) { + Object.defineProperty(W3CWebSocket, prop, { + get: function() { return NativeWebSocket[prop]; } + }); + }); + } + + /** + * Module exports. + */ + module.exports = { + '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", + "_id": "websocket@1.0.26", + "_inBundle": false, + "_integrity": "", + "_location": "/websocket", + "_phantomChildren": {}, + "_requested": { + "type": "git", + "raw": "websocket@git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible", + "name": "websocket", + "escapedName": "websocket", + "rawSpec": "git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible", + "saveSpec": "git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible", + "fetchSpec": "git://github.com/frozeman/WebSocket-Node.git", + "gitCommittish": "browserifyCompatible" + }, + "_requiredBy": [ + "/web3-providers-ws" + ], + "_resolved": "git://github.com/frozeman/WebSocket-Node.git#6c72925e3f8aaaea8dc8450f97627e85263999f2", + "_spec": "websocket@git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible", + "_where": "/Users/alexvlasov/Blockchain/web3swift/web3swiftJSProxy/node_modules/web3-providers-ws", + "author": { + "name": "Brian McKelvey", + "email": "brian@worlize.com", + "url": "https://www.worlize.com/" + }, + "browser": "lib/browser.js", + "bugs": { + "url": "https://github.com/theturtle32/WebSocket-Node/issues" + }, + "bundleDependencies": false, + "config": { + "verbose": false + }, + "contributors": [ + { + "name": "Iñaki Baz Castillo", + "email": "ibc@aliax.net", + "url": "http://dev.sipdoc.net" + } + ], + "dependencies": { + "debug": "^2.2.0", + "nan": "^2.3.3", + "typedarray-to-buffer": "^3.1.2", + "yaeti": "^0.0.6" + }, + "deprecated": false, + "description": "Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.", + "devDependencies": { + "buffer-equal": "^1.0.0", + "faucet": "^0.0.1", + "gulp": "git+https://github.com/gulpjs/gulp.git#4.0", + "gulp-jshint": "^2.0.4", + "jshint": "^2.0.0", + "jshint-stylish": "^2.2.1", + "tape": "^4.0.1" + }, + "directories": { + "lib": "./lib" + }, + "engines": { + "node": ">=0.10.0" + }, + "homepage": "https://github.com/theturtle32/WebSocket-Node", + "keywords": [ + "websocket", + "websockets", + "socket", + "networking", + "comet", + "push", + "RFC-6455", + "realtime", + "server", + "client" + ], + "license": "Apache-2.0", + "main": "index", + "name": "websocket", + "repository": { + "type": "git", + "url": "git+https://github.com/theturtle32/WebSocket-Node.git" + }, + "scripts": { + "gulp": "gulp", + "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", + "test": "faucet test/unit" + }, + "version": "1.0.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) { + if (err) reject(err); + else resolve(data); + }); + }); + }; + + },{"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') { + throw new TypeError('must specify a URL') + } + if (typeof opt === 'function') { + cb = opt + opt = {} + } + 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 + if (query) { + if (typeof query !== 'string') { + query = queryString.stringify(query) + } + 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) { + var lower = key.toLowerCase() + if (!headers[key] && !headers[lower]) { + headers[key] = value + } + } + + },{}],414:[function(require,module,exports){ + module.exports = getResponse + function getResponse (opt, resp) { + if (!resp) return null + return { + statusCode: resp.statusCode, + headers: resp.headers, + method: opt.method, + url: opt.url, + // the XHR object in browser, http response in Node + 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 { + var text = resp.rawRequest.responseText + body = JSON.parse(text) + } catch (e) { + 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 () { + var ret = onabort.apply(req, Array.prototype.slice.call(arguments)) + cb(new Error('XHR Aborted')) + 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) + options.method = method.toUpperCase() + 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") { + params = {uri:uri} + } + } 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){ + called = true + 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)){ + evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") ) + } + evt.statusCode = 0 + return callback(evt, failureResponse) + } + + // will load the data & process the response in a special response object + function loadFunc() { + if (aborted) return + var status + clearTimeout(timeoutTimer) + if(options.useXDR && xhr.status===undefined) { + //IE8 CORS GET successful response doesn't have a status field, but body is fine + status = 200 + } else { + status = (xhr.status === 1223 ? 204 : xhr.status) + } + var response = failureResponse + var err = null + + if (status !== 0){ + response = { + body: getBody(), + statusCode: status, + method: method, + headers: {}, + url: uri, + rawRequest: xhr + } + if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE + response.headers = parseHeaders(xhr.getAllResponseHeaders()) + } + } else { + err = new Error("Internal XMLHttpRequest Error") + } + return callback(err, response, response.body) + } + + var xhr = options.xhr || null + + if (!xhr) { + if (options.cors || options.useXDR) { + xhr = new createXHR.XDomainRequest() + }else{ + xhr = new createXHR.XMLHttpRequest() + } + } + + var key + var aborted + var uri = xhr.url = options.uri || options.url + var method = xhr.method = options.method || "GET" + var body = options.body || options.data + var headers = xhr.headers = options.headers || {} + var sync = !!options.sync + var isJson = false + var timeoutTimer + var failureResponse = { + body: undefined, + headers: {}, + statusCode: 0, + method: method, + 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 + if (method !== "GET" && method !== "HEAD") { + headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user + body = JSON.stringify(options.json === true ? body : options.json) + } + } + + xhr.onreadystatechange = readystatechange + xhr.onload = loadFunc + xhr.onerror = errorFunc + // IE9 must have onprogress be set to a unique function. + xhr.onprogress = function () { + // IE must die + } + xhr.onabort = function(){ + aborted = true; + } + xhr.ontimeout = errorFunc + xhr.open(method, uri, !sync, options.username, options.password) + //has to be after open + if(!sync) { + xhr.withCredentials = !!options.withCredentials + } + // Cannot set timeout with sync request + // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly + // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent + if (!sync && options.timeout > 0 ) { + timeoutTimer = setTimeout(function(){ + if (aborted) return + aborted = true//IE9 may still call readystatechange + xhr.abort("timeout") + var e = new Error("XMLHttpRequest timeout") + e.code = "ETIMEDOUT" + errorFunc(e) + }, options.timeout ) + } + + if (xhr.setRequestHeader) { + for(key in headers){ + if(headers.hasOwnProperty(key)){ + xhr.setRequestHeader(key, headers[key]) + } + } + } 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. + try { + if (xhr.responseType === "document") { + return xhr.responseXML + } + var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror" + if (xhr.responseType === "" && !firefoxBugTakenEffect) { + 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 () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + var SecurityError = /** @class */ (function (_super) { + __extends(SecurityError, _super); + function SecurityError() { + return _super !== null && _super.apply(this, arguments) || this; + } + return SecurityError; + }(Error)); + exports.SecurityError = SecurityError; + var InvalidStateError = /** @class */ (function (_super) { + __extends(InvalidStateError, _super); + function InvalidStateError() { + return _super !== null && _super.apply(this, arguments) || this; + } + return InvalidStateError; + }(Error)); + exports.InvalidStateError = InvalidStateError; + var NetworkError = /** @class */ (function (_super) { + __extends(NetworkError, _super); + function NetworkError() { + return _super !== null && _super.apply(this, arguments) || this; + } + return NetworkError; + }(Error)); + exports.NetworkError = NetworkError; + var SyntaxError = /** @class */ (function (_super) { + __extends(SyntaxError, _super); + function SyntaxError() { + return _super !== null && _super.apply(this, arguments) || this; + } + return SyntaxError; + }(Error)); + exports.SyntaxError = SyntaxError; + + },{}],418:[function(require,module,exports){ + "use strict"; + function __export(m) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; + } + Object.defineProperty(exports, "__esModule", { value: true }); + __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 }); + var ProgressEvent = /** @class */ (function () { + function ProgressEvent(type) { + this.type = type; + this.bubbles = false; + this.cancelable = false; + this.loaded = 0; + this.lengthComputable = false; + this.total = 0; + } + return ProgressEvent; + }()); + exports.ProgressEvent = ProgressEvent; + + },{}],420:[function(require,module,exports){ + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var XMLHttpRequestEventTarget = /** @class */ (function () { + function XMLHttpRequestEventTarget() { + this.listeners = {}; + } + XMLHttpRequestEventTarget.prototype.addEventListener = function (eventType, listener) { + eventType = eventType.toLowerCase(); + this.listeners[eventType] = this.listeners[eventType] || []; + this.listeners[eventType].push(listener.handleEvent || listener); + }; + XMLHttpRequestEventTarget.prototype.removeEventListener = function (eventType, listener) { + eventType = eventType.toLowerCase(); + if (!this.listeners[eventType]) { + return; + } + var index = this.listeners[eventType].indexOf(listener.handleEvent || listener); + if (index < 0) { + return; + } + this.listeners[eventType].splice(index, 1); + }; + XMLHttpRequestEventTarget.prototype.dispatchEvent = function (event) { + var eventType = event.type.toLowerCase(); + event.target = this; // TODO: set event.currentTarget? + if (this.listeners[eventType]) { + for (var _i = 0, _a = this.listeners[eventType]; _i < _a.length; _i++) { + var listener_1 = _a[_i]; + listener_1.call(this, event); + } + } + var listener = this["on" + eventType]; + if (listener) { + listener.call(this, event); + } + return true; + }; + return XMLHttpRequestEventTarget; + }()); + exports.XMLHttpRequestEventTarget = XMLHttpRequestEventTarget; + + },{}],421:[function(require,module,exports){ + (function (Buffer){ + "use strict"; + var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + var xml_http_request_event_target_1 = require("./xml-http-request-event-target"); + var XMLHttpRequestUpload = /** @class */ (function (_super) { + __extends(XMLHttpRequestUpload, _super); + function XMLHttpRequestUpload() { + var _this = _super.call(this) || this; + _this._contentType = null; + _this._body = null; + _this._reset(); + return _this; + } + XMLHttpRequestUpload.prototype._reset = function () { + this._contentType = null; + this._body = null; + }; + XMLHttpRequestUpload.prototype._setData = function (data) { + if (data == null) { + return; + } + if (typeof data === 'string') { + if (data.length !== 0) { + this._contentType = 'text/plain;charset=UTF-8'; + } + this._body = new Buffer(data, 'utf-8'); + } + else if (Buffer.isBuffer(data)) { + this._body = data; + } + else if (data instanceof ArrayBuffer) { + var body = new Buffer(data.byteLength); + var view = new Uint8Array(data); + for (var i = 0; i < data.byteLength; i++) { + body[i] = view[i]; + } + this._body = body; + } + else if (data.buffer && data.buffer instanceof ArrayBuffer) { + var body = new Buffer(data.byteLength); + var offset = data.byteOffset; + var view = new Uint8Array(data.buffer); + for (var i = 0; i < data.byteLength; i++) { + body[i] = view[i + offset]; + } + this._body = body; + } + else { + throw new Error("Unsupported send() data " + data); + } + }; + XMLHttpRequestUpload.prototype._finalizeHeaders = function (headers, loweredHeaders) { + if (this._contentType && !loweredHeaders['content-type']) { + headers['Content-Type'] = this._contentType; + } + if (this._body) { + headers['Content-Length'] = this._body.length.toString(); + } + }; + XMLHttpRequestUpload.prototype._startUpload = function (request) { + if (this._body) { + request.write(this._body); + } + request.end(); + }; + 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){ + "use strict"; + var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + var http = require("http"); + var https = require("https"); + var os = require("os"); + var url = require("url"); + var progress_event_1 = require("./progress-event"); + var errors_1 = require("./errors"); + var xml_http_request_event_target_1 = require("./xml-http-request-event-target"); + var xml_http_request_upload_1 = require("./xml-http-request-upload"); + var Cookie = require("cookiejar"); + var XMLHttpRequest = /** @class */ (function (_super) { + __extends(XMLHttpRequest, _super); + function XMLHttpRequest(options) { + if (options === void 0) { options = {}; } + var _this = _super.call(this) || this; + _this.UNSENT = XMLHttpRequest.UNSENT; + _this.OPENED = XMLHttpRequest.OPENED; + _this.HEADERS_RECEIVED = XMLHttpRequest.HEADERS_RECEIVED; + _this.LOADING = XMLHttpRequest.LOADING; + _this.DONE = XMLHttpRequest.DONE; + _this.onreadystatechange = null; + _this.readyState = XMLHttpRequest.UNSENT; + _this.response = null; + _this.responseText = ''; + _this.responseType = ''; + _this.status = 0; // TODO: UNSENT? + _this.statusText = ''; + _this.timeout = 0; + _this.upload = new xml_http_request_upload_1.XMLHttpRequestUpload(); + _this.responseUrl = ''; + _this.withCredentials = false; + _this._method = null; + _this._url = null; + _this._sync = false; + _this._headers = {}; + _this._loweredHeaders = {}; + _this._mimeOverride = null; // TODO: is type right? + _this._request = null; + _this._response = null; + _this._responseParts = null; + _this._responseHeaders = null; + _this._aborting = null; // TODO: type? + _this._error = null; // TODO: type? + _this._loadedBytes = 0; + _this._totalBytes = 0; + _this._lengthComputable = false; + _this._restrictedMethods = { CONNECT: true, TRACE: true, TRACK: true }; + _this._restrictedHeaders = { + 'accept-charset': true, + 'accept-encoding': true, + 'access-control-request-headers': true, + 'access-control-request-method': true, + connection: true, + 'content-length': true, + cookie: true, + cookie2: true, + date: true, + dnt: true, + expect: true, + host: true, + 'keep-alive': true, + origin: true, + referer: true, + te: true, + trailer: true, + 'transfer-encoding': true, + upgrade: true, + 'user-agent': true, + via: true + }; + _this._privateHeaders = { 'set-cookie': true, 'set-cookie2': true }; + _this._userAgent = "Mozilla/5.0 (" + os.type() + " " + os.arch() + ") node.js/" + process.versions.node + " v8/" + process.versions.v8; + _this._anonymous = options.anon || false; + return _this; + } + XMLHttpRequest.prototype.open = function (method, url, async, user, password) { + if (async === void 0) { async = true; } + method = method.toUpperCase(); + if (this._restrictedMethods[method]) { + throw new XMLHttpRequest.SecurityError("HTTP method " + method + " is not allowed in XHR"); + } + ; + var xhrUrl = this._parseUrl(url, user, password); + if (this.readyState === XMLHttpRequest.HEADERS_RECEIVED || this.readyState === XMLHttpRequest.LOADING) { + // TODO(pwnall): terminate abort(), terminate send() + } + this._method = method; + this._url = xhrUrl; + this._sync = !async; + this._headers = {}; + this._loweredHeaders = {}; + this._mimeOverride = null; + this._setReadyState(XMLHttpRequest.OPENED); + this._request = null; + this._response = null; + this.status = 0; + this.statusText = ''; + this._responseParts = []; + this._responseHeaders = null; + this._loadedBytes = 0; + this._totalBytes = 0; + this._lengthComputable = false; + }; + XMLHttpRequest.prototype.setRequestHeader = function (name, value) { + if (this.readyState !== XMLHttpRequest.OPENED) { + throw new XMLHttpRequest.InvalidStateError('XHR readyState must be OPENED'); + } + var loweredName = name.toLowerCase(); + if (this._restrictedHeaders[loweredName] || /^sec-/.test(loweredName) || /^proxy-/.test(loweredName)) { + console.warn("Refused to set unsafe header \"" + name + "\""); + return; + } + value = value.toString(); + if (this._loweredHeaders[loweredName] != null) { + name = this._loweredHeaders[loweredName]; + this._headers[name] = this._headers[name] + ", " + value; + } + else { + this._loweredHeaders[loweredName] = name; + this._headers[name] = value; + } + }; + XMLHttpRequest.prototype.send = function (data) { + if (this.readyState !== XMLHttpRequest.OPENED) { + throw new XMLHttpRequest.InvalidStateError('XHR readyState must be OPENED'); + } + if (this._request) { + throw new XMLHttpRequest.InvalidStateError('send() already called'); + } + switch (this._url.protocol) { + case 'file:': + return this._sendFile(data); + case 'http:': + case 'https:': + return this._sendHttp(data); + default: + throw new XMLHttpRequest.NetworkError("Unsupported protocol " + this._url.protocol); + } + }; + XMLHttpRequest.prototype.abort = function () { + if (this._request == null) { + return; + } + this._request.abort(); + this._setError(); + this._dispatchProgress('abort'); + this._dispatchProgress('loadend'); + }; + XMLHttpRequest.prototype.getResponseHeader = function (name) { + if (this._responseHeaders == null || name == null) { + return null; + } + var loweredName = name.toLowerCase(); + return this._responseHeaders.hasOwnProperty(loweredName) + ? this._responseHeaders[name.toLowerCase()] + : null; + }; + XMLHttpRequest.prototype.getAllResponseHeaders = function () { + var _this = this; + if (this._responseHeaders == null) { + return ''; + } + return Object.keys(this._responseHeaders).map(function (key) { return key + ": " + _this._responseHeaders[key]; }).join('\r\n'); + }; + XMLHttpRequest.prototype.overrideMimeType = function (mimeType) { + if (this.readyState === XMLHttpRequest.LOADING || this.readyState === XMLHttpRequest.DONE) { + throw new XMLHttpRequest.InvalidStateError('overrideMimeType() not allowed in LOADING or DONE'); + } + this._mimeOverride = mimeType.toLowerCase(); + }; + XMLHttpRequest.prototype.nodejsSet = function (options) { + this.nodejsHttpAgent = options.httpAgent || this.nodejsHttpAgent; + this.nodejsHttpsAgent = options.httpsAgent || this.nodejsHttpsAgent; + if (options.hasOwnProperty('baseUrl')) { + if (options.baseUrl != null) { + var parsedUrl = url.parse(options.baseUrl, false, true); + if (!parsedUrl.protocol) { + throw new XMLHttpRequest.SyntaxError("baseUrl must be an absolute URL"); + } + } + this.nodejsBaseUrl = options.baseUrl; + } + }; + XMLHttpRequest.nodejsSet = function (options) { + XMLHttpRequest.prototype.nodejsSet(options); + }; + XMLHttpRequest.prototype._setReadyState = function (readyState) { + this.readyState = readyState; + this.dispatchEvent(new progress_event_1.ProgressEvent('readystatechange')); + }; + XMLHttpRequest.prototype._sendFile = function (data) { + // TODO + throw new Error('Protocol file: not implemented'); + }; + XMLHttpRequest.prototype._sendHttp = function (data) { + if (this._sync) { + throw new Error('Synchronous XHR processing not implemented'); + } + if (data && (this._method === 'GET' || this._method === 'HEAD')) { + console.warn("Discarding entity body for " + this._method + " requests"); + data = null; + } + else { + data = data || ''; + } + this.upload._setData(data); + this._finalizeHeaders(); + this._sendHxxpRequest(); + }; + XMLHttpRequest.prototype._sendHxxpRequest = function () { + var _this = this; + if (this.withCredentials) { + var cookie = XMLHttpRequest.cookieJar + .getCookies(Cookie.CookieAccessInfo(this._url.hostname, this._url.pathname, this._url.protocol === 'https:')).toValueString(); + this._headers.cookie = this._headers.cookie2 = cookie; + } + var _a = this._url.protocol === 'http:' ? [http, this.nodejsHttpAgent] : [https, this.nodejsHttpsAgent], hxxp = _a[0], agent = _a[1]; + var requestMethod = hxxp.request.bind(hxxp); + var request = requestMethod({ + hostname: this._url.hostname, + port: +this._url.port, + path: this._url.path, + auth: this._url.auth, + method: this._method, + headers: this._headers, + agent: agent + }); + this._request = request; + if (this.timeout) { + request.setTimeout(this.timeout, function () { return _this._onHttpTimeout(request); }); + } + request.on('response', function (response) { return _this._onHttpResponse(request, response); }); + request.on('error', function (error) { return _this._onHttpRequestError(request, error); }); + this.upload._startUpload(request); + if (this._request === request) { + this._dispatchProgress('loadstart'); + } + }; + XMLHttpRequest.prototype._finalizeHeaders = function () { + this._headers = __assign({}, this._headers, { Connection: 'keep-alive', Host: this._url.host, 'User-Agent': this._userAgent }, this._anonymous ? { Referer: 'about:blank' } : {}); + this.upload._finalizeHeaders(this._headers, this._loweredHeaders); + }; + XMLHttpRequest.prototype._onHttpResponse = function (request, response) { + var _this = this; + if (this._request !== request) { + return; + } + if (this.withCredentials && (response.headers['set-cookie'] || response.headers['set-cookie2'])) { + XMLHttpRequest.cookieJar + .setCookies(response.headers['set-cookie'] || response.headers['set-cookie2']); + } + if ([301, 302, 303, 307, 308].indexOf(response.statusCode) >= 0) { + this._url = this._parseUrl(response.headers.location); + this._method = 'GET'; + if (this._loweredHeaders['content-type']) { + delete this._headers[this._loweredHeaders['content-type']]; + delete this._loweredHeaders['content-type']; + } + if (this._headers['Content-Type'] != null) { + delete this._headers['Content-Type']; + } + delete this._headers['Content-Length']; + this.upload._reset(); + this._finalizeHeaders(); + this._sendHxxpRequest(); + return; + } + this._response = response; + this._response.on('data', function (data) { return _this._onHttpResponseData(response, data); }); + this._response.on('end', function () { return _this._onHttpResponseEnd(response); }); + this._response.on('close', function () { return _this._onHttpResponseClose(response); }); + this.responseUrl = this._url.href.split('#')[0]; + this.status = response.statusCode; + this.statusText = http.STATUS_CODES[this.status]; + this._parseResponseHeaders(response); + var lengthString = this._responseHeaders['content-length'] || ''; + this._totalBytes = +lengthString; + this._lengthComputable = !!lengthString; + this._setReadyState(XMLHttpRequest.HEADERS_RECEIVED); + }; + XMLHttpRequest.prototype._onHttpResponseData = function (response, data) { + if (this._response !== response) { + return; + } + this._responseParts.push(new Buffer(data)); + this._loadedBytes += data.length; + if (this.readyState !== XMLHttpRequest.LOADING) { + this._setReadyState(XMLHttpRequest.LOADING); + } + this._dispatchProgress('progress'); + }; + XMLHttpRequest.prototype._onHttpResponseEnd = function (response) { + if (this._response !== response) { + return; + } + this._parseResponse(); + this._request = null; + this._response = null; + this._setReadyState(XMLHttpRequest.DONE); + this._dispatchProgress('load'); + this._dispatchProgress('loadend'); + }; + XMLHttpRequest.prototype._onHttpResponseClose = function (response) { + if (this._response !== response) { + return; + } + var request = this._request; + this._setError(); + request.abort(); + this._setReadyState(XMLHttpRequest.DONE); + this._dispatchProgress('error'); + this._dispatchProgress('loadend'); + }; + XMLHttpRequest.prototype._onHttpTimeout = function (request) { + if (this._request !== request) { + return; + } + this._setError(); + request.abort(); + this._setReadyState(XMLHttpRequest.DONE); + this._dispatchProgress('timeout'); + this._dispatchProgress('loadend'); + }; + XMLHttpRequest.prototype._onHttpRequestError = function (request, error) { + if (this._request !== request) { + return; + } + this._setError(); + request.abort(); + this._setReadyState(XMLHttpRequest.DONE); + this._dispatchProgress('error'); + this._dispatchProgress('loadend'); + }; + XMLHttpRequest.prototype._dispatchProgress = function (eventType) { + var event = new XMLHttpRequest.ProgressEvent(eventType); + event.lengthComputable = this._lengthComputable; + event.loaded = this._loadedBytes; + event.total = this._totalBytes; + this.dispatchEvent(event); + }; + XMLHttpRequest.prototype._setError = function () { + this._request = null; + this._response = null; + this._responseHeaders = null; + this._responseParts = null; + }; + XMLHttpRequest.prototype._parseUrl = function (urlString, user, password) { + var absoluteUrl = this.nodejsBaseUrl == null ? urlString : url.resolve(this.nodejsBaseUrl, urlString); + var xhrUrl = url.parse(absoluteUrl, false, true); + xhrUrl.hash = null; + var _a = (xhrUrl.auth || '').split(':'), xhrUser = _a[0], xhrPassword = _a[1]; + if (xhrUser || xhrPassword || user || password) { + xhrUrl.auth = (user || xhrUser || '') + ":" + (password || xhrPassword || ''); + } + return xhrUrl; + }; + XMLHttpRequest.prototype._parseResponseHeaders = function (response) { + this._responseHeaders = {}; + for (var name_1 in response.headers) { + var loweredName = name_1.toLowerCase(); + if (this._privateHeaders[loweredName]) { + continue; + } + this._responseHeaders[loweredName] = response.headers[name_1]; + } + if (this._mimeOverride != null) { + this._responseHeaders['content-type'] = this._mimeOverride; + } + }; + XMLHttpRequest.prototype._parseResponse = function () { + var buffer = Buffer.concat(this._responseParts); + this._responseParts = null; + switch (this.responseType) { + case 'json': + this.responseText = null; + try { + this.response = JSON.parse(buffer.toString('utf-8')); + } + catch (_a) { + this.response = null; + } + return; + case 'buffer': + this.responseText = null; + this.response = buffer; + return; + case 'arraybuffer': + this.responseText = null; + var arrayBuffer = new ArrayBuffer(buffer.length); + var view = new Uint8Array(arrayBuffer); + for (var i = 0; i < buffer.length; i++) { + view[i] = buffer[i]; + } + this.response = arrayBuffer; + return; + case 'text': + default: + try { + this.responseText = buffer.toString(this._parseResponseEncoding()); + } + catch (_b) { + this.responseText = buffer.toString('binary'); + } + this.response = this.responseText; + } + }; + XMLHttpRequest.prototype._parseResponseEncoding = function () { + return /;\s*charset=(.*)$/.exec(this._responseHeaders['content-type'] || '')[1] || 'utf-8'; + }; + XMLHttpRequest.ProgressEvent = progress_event_1.ProgressEvent; + XMLHttpRequest.InvalidStateError = errors_1.InvalidStateError; + XMLHttpRequest.NetworkError = errors_1.NetworkError; + XMLHttpRequest.SecurityError = errors_1.SecurityError; + XMLHttpRequest.SyntaxError = errors_1.SyntaxError; + XMLHttpRequest.XMLHttpRequestUpload = xml_http_request_upload_1.XMLHttpRequestUpload; + XMLHttpRequest.UNSENT = 0; + XMLHttpRequest.OPENED = 1; + XMLHttpRequest.HEADERS_RECEIVED = 2; + XMLHttpRequest.LOADING = 3; + XMLHttpRequest.DONE = 4; + XMLHttpRequest.cookieJar = Cookie.CookieJar(); + return XMLHttpRequest; + }(xml_http_request_event_target_1.XMLHttpRequestEventTarget)); + exports.XMLHttpRequest = XMLHttpRequest; + 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() { + if (window.isIOS) { + return; + } + window.isIOS = function() { + return navigator && navigator.userAgent && (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)); + }; + }()); + (function() { + if (window.bridge) { + return; + } + window.bridge = function() { + var callbacks = [], + callbackID = 0, + registerHandlers = []; + document.addEventListener('PacificDidReceiveNativeCallback', function(e) { + if (e.detail) { + var detail = e.detail; + var id = isNaN(parseInt(detail.id)) ? -1 : parseInt(detail.id); + if (id != -1) { + callbacks[id] && callbacks[id](detail.parameters, detail.error); + delete callbacks[id]; + } + } + }, false); + document.addEventListener('PacificDidReceiveNativeBroadcast', function(e) { + if (e.detail) { + var detail = e.detail; + var name = detail.name; + if (name !== undefined && registerHandlers[name]) { + var namedListeners = registerHandlers[name]; + if (namedListeners instanceof Array) { + var parameters = detail.parameters; + namedListeners.forEach(function(handler) { + handler(parameters); + }); + } + } + } + }, false); + return { + 'post': function(action, parameters, callback, print) { + var id = callbackID++; + callbacks[id] = callback; + if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.pacific) { + window.webkit.messageHandlers.pacific.postMessage({ + 'action': action, + 'parameters': parameters, + 'callback': id, + 'print': print || 0 + }); + } + }, + 'on': function(name, callback) { + var namedListeners = registerHandlers[name]; + if (!namedListeners) { + registerHandlers[name] = namedListeners = []; + } + namedListeners.push(callback); + return function() { + namedListeners[indexOf(namedListeners, callback)] = null; + }; + }, + 'off': function(name) { + delete registerHandlers[name]; + } + }; + }(); + }()); + + //# sourceURL=/Users/alexvlasov/Blockchain/web3swift/web3swiftJSProxy/wk.bridge.js + },{}]},{},[1]); + \ No newline at end of file diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Browser/browser.min.js b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Browser/browser.min.js new file mode 100644 index 000000000..f838d4a4b --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Browser/browser.min.js @@ -0,0 +1,2 @@ +!function(){return function e(t,r,n){function i(a,s){if(!r[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(o)return o(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var f=r[a]={exports:{}};t[a][0].call(f.exports,function(e){var r=t[a][1][e];return i(r||e)},f,f.exports,e,t,r,n)}return r[a].exports}for(var o="function"==typeof require&&require,a=0;a0&&(window.web3.eth.defaultAccount=t[0])})}window.ethereum=s}}},console.log("JS bridging rpc url access"),"undefined"!=typeof window&&window.bridge?window.bridge.post("getRPCurl",{},function(e,r){r&&t(r.description,null),t(null,e.rpcURL)}):(console.log("No bridge to native code is found"),t(!0,null))}()},{"./wk.bridge":424,web3:407,"web3-provider-engine/zero.js":397}],2:[function(e,t,r){t.exports=e("./register")().Promise},{"./register":4}],3:[function(e,t,r){"use strict";var n=null;t.exports=function(e,t){return function(r,i){r=r||null;var o=!1!==(i=i||{}).global;if(null===n&&o&&(n=e["@@any-promise/REGISTRATION"]||null),null!==n&&null!==r&&n.implementation!==r)throw new Error('any-promise already defined as "'+n.implementation+'". You can only register an implementation before the first call to require("any-promise") and an implementation cannot be changed');return null===n&&(n=null!==r&&void 0!==i.Promise?{Promise:i.Promise,implementation:r}:t(r),o&&(e["@@any-promise/REGISTRATION"]=n)),n}}},{}],4:[function(e,t,r){"use strict";t.exports=e("./loader")(window,function(){if(void 0===window.Promise)throw new Error("any-promise browser requires a polyfill or explicit registration e.g: require('any-promise/register/bluebird')");return{Promise:window.Promise,implementation:"window.Promise"}})},{"./loader":3}],5:[function(e,t,r){var n=r;n.bignum=e("bn.js"),n.define=e("./asn1/api").define,n.base=e("./asn1/base"),n.constants=e("./asn1/constants"),n.decoders=e("./asn1/decoders"),n.encoders=e("./asn1/encoders")},{"./asn1/api":6,"./asn1/base":8,"./asn1/constants":12,"./asn1/decoders":14,"./asn1/encoders":17,"bn.js":53}],6:[function(e,t,r){var n=e("../asn1"),i=e("inherits");function o(e,t){this.name=e,this.body=t,this.decoders={},this.encoders={}}r.define=function(e,t){return new o(e,t)},o.prototype._createNamed=function(t){var r;try{r=e("vm").runInThisContext("(function "+this.name+"(entity) {\n this._initNamed(entity);\n})")}catch(e){r=function(e){this._initNamed(e)}}return i(r,t),r.prototype._initNamed=function(e){t.call(this,e)},new r(this)},o.prototype._getDecoder=function(e){return e=e||"der",this.decoders.hasOwnProperty(e)||(this.decoders[e]=this._createNamed(n.decoders[e])),this.decoders[e]},o.prototype.decode=function(e,t,r){return this._getDecoder(t).decode(e,r)},o.prototype._getEncoder=function(e){return e=e||"der",this.encoders.hasOwnProperty(e)||(this.encoders[e]=this._createNamed(n.encoders[e])),this.encoders[e]},o.prototype.encode=function(e,t,r){return this._getEncoder(t).encode(e,r)}},{"../asn1":5,inherits:180,vm:334}],7:[function(e,t,r){var n=e("inherits"),i=e("../base").Reporter,o=e("buffer").Buffer;function a(e,t){i.call(this,t),o.isBuffer(e)?(this.base=e,this.offset=0,this.length=e.length):this.error("Input not Buffer")}function s(e,t){if(Array.isArray(e))this.length=0,this.value=e.map(function(e){return e instanceof s||(e=new s(e,t)),this.length+=e.length,e},this);else if("number"==typeof e){if(!(0<=e&&e<=255))return t.error("non-byte EncoderBuffer value");this.value=e,this.length=1}else if("string"==typeof e)this.value=e,this.length=o.byteLength(e);else{if(!o.isBuffer(e))return t.error("Unsupported type: "+typeof e);this.value=e,this.length=e.length}}n(a,i),r.DecoderBuffer=a,a.prototype.save=function(){return{offset:this.offset,reporter:i.prototype.save.call(this)}},a.prototype.restore=function(e){var t=new a(this.base);return t.offset=e.offset,t.length=this.offset,this.offset=e.offset,i.prototype.restore.call(this,e.reporter),t},a.prototype.isEmpty=function(){return this.offset===this.length},a.prototype.readUInt8=function(e){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(e||"DecoderBuffer overrun")},a.prototype.skip=function(e,t){if(!(this.offset+e<=this.length))return this.error(t||"DecoderBuffer overrun");var r=new a(this.base);return r._reporterState=this._reporterState,r.offset=this.offset,r.length=this.offset+e,this.offset+=e,r},a.prototype.raw=function(e){return this.base.slice(e?e.offset:this.offset,this.length)},r.EncoderBuffer=s,s.prototype.join=function(e,t){return e||(e=new o(this.length)),t||(t=0),0===this.length?e:(Array.isArray(this.value)?this.value.forEach(function(r){r.join(e,t),t+=r.length}):("number"==typeof this.value?e[t]=this.value:"string"==typeof this.value?e.write(this.value,t):o.isBuffer(this.value)&&this.value.copy(e,t),t+=this.length),e)}},{"../base":8,buffer:84,inherits:180}],8:[function(e,t,r){var n=r;n.Reporter=e("./reporter").Reporter,n.DecoderBuffer=e("./buffer").DecoderBuffer,n.EncoderBuffer=e("./buffer").EncoderBuffer,n.Node=e("./node")},{"./buffer":7,"./node":9,"./reporter":10}],9:[function(e,t,r){var n=e("../base").Reporter,i=e("../base").EncoderBuffer,o=e("../base").DecoderBuffer,a=e("minimalistic-assert"),s=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],u=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(s);function c(e,t){var r={};this._baseState=r,r.enc=e,r.parent=t||null,r.children=null,r.tag=null,r.args=null,r.reverseArgs=null,r.choice=null,r.optional=!1,r.any=!1,r.obj=!1,r.use=null,r.useDecoder=null,r.key=null,r.default=null,r.explicit=null,r.implicit=null,r.contains=null,r.parent||(r.children=[],this._wrap())}t.exports=c;var f=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];c.prototype.clone=function(){var e=this._baseState,t={};f.forEach(function(r){t[r]=e[r]});var r=new this.constructor(t.parent);return r._baseState=t,r},c.prototype._wrap=function(){var e=this._baseState;u.forEach(function(t){this[t]=function(){var r=new this.constructor(this);return e.children.push(r),r[t].apply(r,arguments)}},this)},c.prototype._init=function(e){var t=this._baseState;a(null===t.parent),e.call(this),t.children=t.children.filter(function(e){return e._baseState.parent===this},this),a.equal(t.children.length,1,"Root node can have only one child")},c.prototype._useArgs=function(e){var t=this._baseState,r=e.filter(function(e){return e instanceof this.constructor},this);e=e.filter(function(e){return!(e instanceof this.constructor)},this),0!==r.length&&(a(null===t.children),t.children=r,r.forEach(function(e){e._baseState.parent=this},this)),0!==e.length&&(a(null===t.args),t.args=e,t.reverseArgs=e.map(function(e){if("object"!=typeof e||e.constructor!==Object)return e;var t={};return Object.keys(e).forEach(function(r){r==(0|r)&&(r|=0);var n=e[r];t[n]=r}),t}))},["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"].forEach(function(e){c.prototype[e]=function(){var t=this._baseState;throw new Error(e+" not implemented for encoding: "+t.enc)}}),s.forEach(function(e){c.prototype[e]=function(){var t=this._baseState,r=Array.prototype.slice.call(arguments);return a(null===t.tag),t.tag=e,this._useArgs(r),this}}),c.prototype.use=function(e){a(e);var t=this._baseState;return a(null===t.use),t.use=e,this},c.prototype.optional=function(){return this._baseState.optional=!0,this},c.prototype.def=function(e){var t=this._baseState;return a(null===t.default),t.default=e,t.optional=!0,this},c.prototype.explicit=function(e){var t=this._baseState;return a(null===t.explicit&&null===t.implicit),t.explicit=e,this},c.prototype.implicit=function(e){var t=this._baseState;return a(null===t.explicit&&null===t.implicit),t.implicit=e,this},c.prototype.obj=function(){var e=this._baseState,t=Array.prototype.slice.call(arguments);return e.obj=!0,0!==t.length&&this._useArgs(t),this},c.prototype.key=function(e){var t=this._baseState;return a(null===t.key),t.key=e,this},c.prototype.any=function(){return this._baseState.any=!0,this},c.prototype.choice=function(e){var t=this._baseState;return a(null===t.choice),t.choice=e,this._useArgs(Object.keys(e).map(function(t){return e[t]})),this},c.prototype.contains=function(e){var t=this._baseState;return a(null===t.use),t.contains=e,this},c.prototype._decode=function(e,t){var r=this._baseState;if(null===r.parent)return e.wrapResult(r.children[0]._decode(e,t));var n,i=r.default,a=!0,s=null;if(null!==r.key&&(s=e.enterKey(r.key)),r.optional){var u=null;if(null!==r.explicit?u=r.explicit:null!==r.implicit?u=r.implicit:null!==r.tag&&(u=r.tag),null!==u||r.any){if(a=this._peekTag(e,u,r.any),e.isError(a))return a}else{var c=e.save();try{null===r.choice?this._decodeGeneric(r.tag,e,t):this._decodeChoice(e,t),a=!0}catch(e){a=!1}e.restore(c)}}if(r.obj&&a&&(n=e.enterObject()),a){if(null!==r.explicit){var f=this._decodeTag(e,r.explicit);if(e.isError(f))return f;e=f}var h=e.offset;if(null===r.use&&null===r.choice){if(r.any)c=e.save();var l=this._decodeTag(e,null!==r.implicit?r.implicit:r.tag,r.any);if(e.isError(l))return l;r.any?i=e.raw(c):e=l}if(t&&t.track&&null!==r.tag&&t.track(e.path(),h,e.length,"tagged"),t&&t.track&&null!==r.tag&&t.track(e.path(),e.offset,e.length,"content"),i=r.any?i:null===r.choice?this._decodeGeneric(r.tag,e,t):this._decodeChoice(e,t),e.isError(i))return i;if(r.any||null!==r.choice||null===r.children||r.children.forEach(function(r){r._decode(e,t)}),r.contains&&("octstr"===r.tag||"bitstr"===r.tag)){var d=new o(i);i=this._getUse(r.contains,e._reporterState.obj)._decode(d,t)}}return r.obj&&a&&(i=e.leaveObject(n)),null===r.key||null===i&&!0!==a?null!==s&&e.exitKey(s):e.leaveKey(s,r.key,i),i},c.prototype._decodeGeneric=function(e,t,r){var n=this._baseState;return"seq"===e||"set"===e?null:"seqof"===e||"setof"===e?this._decodeList(t,e,n.args[0],r):/str$/.test(e)?this._decodeStr(t,e,r):"objid"===e&&n.args?this._decodeObjid(t,n.args[0],n.args[1],r):"objid"===e?this._decodeObjid(t,null,null,r):"gentime"===e||"utctime"===e?this._decodeTime(t,e,r):"null_"===e?this._decodeNull(t,r):"bool"===e?this._decodeBool(t,r):"objDesc"===e?this._decodeStr(t,e,r):"int"===e||"enum"===e?this._decodeInt(t,n.args&&n.args[0],r):null!==n.use?this._getUse(n.use,t._reporterState.obj)._decode(t,r):t.error("unknown tag: "+e)},c.prototype._getUse=function(e,t){var r=this._baseState;return r.useDecoder=this._use(e,t),a(null===r.useDecoder._baseState.parent),r.useDecoder=r.useDecoder._baseState.children[0],r.implicit!==r.useDecoder._baseState.implicit&&(r.useDecoder=r.useDecoder.clone(),r.useDecoder._baseState.implicit=r.implicit),r.useDecoder},c.prototype._decodeChoice=function(e,t){var r=this._baseState,n=null,i=!1;return Object.keys(r.choice).some(function(o){var a=e.save(),s=r.choice[o];try{var u=s._decode(e,t);if(e.isError(u))return!1;n={type:o,value:u},i=!0}catch(t){return e.restore(a),!1}return!0},this),i?n:e.error("Choice not matched")},c.prototype._createEncoderBuffer=function(e){return new i(e,this.reporter)},c.prototype._encode=function(e,t,r){var n=this._baseState;if(null===n.default||n.default!==e){var i=this._encodeValue(e,t,r);if(void 0!==i&&!this._skipDefault(i,t,r))return i}},c.prototype._encodeValue=function(e,t,r){var i=this._baseState;if(null===i.parent)return i.children[0]._encode(e,t||new n);var o=null;if(this.reporter=t,i.optional&&void 0===e){if(null===i.default)return;e=i.default}var a=null,s=!1;if(i.any)o=this._createEncoderBuffer(e);else if(i.choice)o=this._encodeChoice(e,t);else if(i.contains)a=this._getUse(i.contains,r)._encode(e,t),s=!0;else if(i.children)a=i.children.map(function(r){if("null_"===r._baseState.tag)return r._encode(null,t,e);if(null===r._baseState.key)return t.error("Child should have a key");var n=t.enterKey(r._baseState.key);if("object"!=typeof e)return t.error("Child expected, but input is not object");var i=r._encode(e[r._baseState.key],t,e);return t.leaveKey(n),i},this).filter(function(e){return e}),a=this._createEncoderBuffer(a);else if("seqof"===i.tag||"setof"===i.tag){if(!i.args||1!==i.args.length)return t.error("Too many args for : "+i.tag);if(!Array.isArray(e))return t.error("seqof/setof, but data is not Array");var u=this.clone();u._baseState.implicit=null,a=this._createEncoderBuffer(e.map(function(r){var n=this._baseState;return this._getUse(n.args[0],e)._encode(r,t)},u))}else null!==i.use?o=this._getUse(i.use,r)._encode(e,t):(a=this._encodePrimitive(i.tag,e),s=!0);if(!i.any&&null===i.choice){var c=null!==i.implicit?i.implicit:i.tag,f=null===i.implicit?"universal":"context";null===c?null===i.use&&t.error("Tag could be omitted only for .use()"):null===i.use&&(o=this._encodeComposite(c,s,f,a))}return null!==i.explicit&&(o=this._encodeComposite(i.explicit,!1,"context",o)),o},c.prototype._encodeChoice=function(e,t){var r=this._baseState,n=r.choice[e.type];return n||a(!1,e.type+" not found in "+JSON.stringify(Object.keys(r.choice))),n._encode(e.value,t)},c.prototype._encodePrimitive=function(e,t){var r=this._baseState;if(/str$/.test(e))return this._encodeStr(t,e);if("objid"===e&&r.args)return this._encodeObjid(t,r.reverseArgs[0],r.args[1]);if("objid"===e)return this._encodeObjid(t,null,null);if("gentime"===e||"utctime"===e)return this._encodeTime(t,e);if("null_"===e)return this._encodeNull();if("int"===e||"enum"===e)return this._encodeInt(t,r.args&&r.reverseArgs[0]);if("bool"===e)return this._encodeBool(t);if("objDesc"===e)return this._encodeStr(t,e);throw new Error("Unsupported tag: "+e)},c.prototype._isNumstr=function(e){return/^[0-9 ]*$/.test(e)},c.prototype._isPrintstr=function(e){return/^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(e)}},{"../base":8,"minimalistic-assert":234}],10:[function(e,t,r){var n=e("inherits");function i(e){this._reporterState={obj:null,path:[],options:e||{},errors:[]}}function o(e,t){this.path=e,this.rethrow(t)}r.Reporter=i,i.prototype.isError=function(e){return e instanceof o},i.prototype.save=function(){var e=this._reporterState;return{obj:e.obj,pathLen:e.path.length}},i.prototype.restore=function(e){var t=this._reporterState;t.obj=e.obj,t.path=t.path.slice(0,e.pathLen)},i.prototype.enterKey=function(e){return this._reporterState.path.push(e)},i.prototype.exitKey=function(e){var t=this._reporterState;t.path=t.path.slice(0,e-1)},i.prototype.leaveKey=function(e,t,r){var n=this._reporterState;this.exitKey(e),null!==n.obj&&(n.obj[t]=r)},i.prototype.path=function(){return this._reporterState.path.join("/")},i.prototype.enterObject=function(){var e=this._reporterState,t=e.obj;return e.obj={},t},i.prototype.leaveObject=function(e){var t=this._reporterState,r=t.obj;return t.obj=e,r},i.prototype.error=function(e){var t,r=this._reporterState,n=e instanceof o;if(t=n?e:new o(r.path.map(function(e){return"["+JSON.stringify(e)+"]"}).join(""),e.message||e,e.stack),!r.options.partial)throw t;return n||r.errors.push(t),t},i.prototype.wrapResult=function(e){var t=this._reporterState;return t.options.partial?{result:this.isError(e)?null:e,errors:t.errors}:e},n(o,Error),o.prototype.rethrow=function(e){if(this.message=e+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,o),!this.stack)try{throw new Error(this.message)}catch(e){this.stack=e.stack}return this}},{inherits:180}],11:[function(e,t,r){var n=e("../constants");r.tagClass={0:"universal",1:"application",2:"context",3:"private"},r.tagClassByName=n._reverse(r.tagClass),r.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},r.tagByName=n._reverse(r.tag)},{"../constants":12}],12:[function(e,t,r){var n=r;n._reverse=function(e){var t={};return Object.keys(e).forEach(function(r){(0|r)==r&&(r|=0);var n=e[r];t[n]=r}),t},n.der=e("./der")},{"./der":11}],13:[function(e,t,r){var n=e("inherits"),i=e("../../asn1"),o=i.base,a=i.bignum,s=i.constants.der;function u(e){this.enc="der",this.name=e.name,this.entity=e,this.tree=new c,this.tree._init(e.body)}function c(e){o.Node.call(this,"der",e)}function f(e,t){var r=e.readUInt8(t);if(e.isError(r))return r;var n=s.tagClass[r>>6],i=0==(32&r);if(31==(31&r)){var o=r;for(r=0;128==(128&o);){if(o=e.readUInt8(t),e.isError(o))return o;r<<=7,r|=127&o}}else r&=31;return{cls:n,primitive:i,tag:r,tagStr:s.tag[r]}}function h(e,t,r){var n=e.readUInt8(r);if(e.isError(n))return n;if(!t&&128===n)return null;if(0==(128&n))return n;var i=127&n;if(i>4)return e.error("length octect is too long");n=0;for(var o=0;o=31)return n.error("Multi-octet tag encoding unsupported");t||(i|=32);return i|=s.tagClassByName[r||"universal"]<<6}(e,t,r,this.reporter);if(n.length<128)return(o=new i(2))[0]=a,o[1]=n.length,this._createEncoderBuffer([o,n]);for(var u=1,c=n.length;c>=256;c>>=8)u++;(o=new i(2+u))[0]=a,o[1]=128|u;c=1+u;for(var f=n.length;f>0;c--,f>>=8)o[c]=255&f;return this._createEncoderBuffer([o,n])},c.prototype._encodeStr=function(e,t){if("bitstr"===t)return this._createEncoderBuffer([0|e.unused,e.data]);if("bmpstr"===t){for(var r=new i(2*e.length),n=0;n=40)return this.reporter.error("Second objid identifier OOB");e.splice(0,2,40*e[0]+e[1])}var o=0;for(n=0;n=128;a>>=7)o++}var s=new i(o),u=s.length-1;for(n=e.length-1;n>=0;n--){a=e[n];for(s[u--]=127&a;(a>>=7)>0;)s[u--]=128|127&a}return this._createEncoderBuffer(s)},c.prototype._encodeTime=function(e,t){var r,n=new Date(e);return"gentime"===t?r=[f(n.getFullYear()),f(n.getUTCMonth()+1),f(n.getUTCDate()),f(n.getUTCHours()),f(n.getUTCMinutes()),f(n.getUTCSeconds()),"Z"].join(""):"utctime"===t?r=[f(n.getFullYear()%100),f(n.getUTCMonth()+1),f(n.getUTCDate()),f(n.getUTCHours()),f(n.getUTCMinutes()),f(n.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+t+" time is not supported yet"),this._encodeStr(r,"octstr")},c.prototype._encodeNull=function(){return this._createEncoderBuffer("")},c.prototype._encodeInt=function(e,t){if("string"==typeof e){if(!t)return this.reporter.error("String int or enum given, but no values map");if(!t.hasOwnProperty(e))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(e));e=t[e]}if("number"!=typeof e&&!i.isBuffer(e)){var r=e.toArray();!e.sign&&128&r[0]&&r.unshift(0),e=new i(r)}if(i.isBuffer(e)){var n=e.length;0===e.length&&n++;var o=new i(n);return e.copy(o),0===e.length&&(o[0]=0),this._createEncoderBuffer(o)}if(e<128)return this._createEncoderBuffer(e);if(e<256)return this._createEncoderBuffer([0,e]);n=1;for(var a=e;a>=256;a>>=8)n++;for(a=(o=new Array(n)).length-1;a>=0;a--)o[a]=255&e,e>>=8;return 128&o[0]&&o.unshift(0),this._createEncoderBuffer(new i(o))},c.prototype._encodeBool=function(e){return this._createEncoderBuffer(e?255:0)},c.prototype._use=function(e,t){return"function"==typeof e&&(e=e(t)),e._getEncoder("der").tree},c.prototype._skipDefault=function(e,t,r){var n,i=this._baseState;if(null===i.default)return!1;var o=e.join();if(void 0===i.defaultBuffer&&(i.defaultBuffer=this._encodeValue(i.default,t,r).join()),o.length!==i.defaultBuffer.length)return!1;for(n=0;n=0;c--)if(f[c]!==h[c])return!1;for(c=f.length-1;c>=0;c--)if(u=f[c],!v(e[u],t[u],r,n))return!1;return!0}(e,t,r,a))}return r?e===t:e==t}function g(e){return"[object Arguments]"==Object.prototype.toString.call(e)}function w(e,t){if(!e||!t)return!1;if("[object RegExp]"==Object.prototype.toString.call(t))return t.test(e);try{if(e instanceof t)return!0}catch(e){}return!Error.isPrototypeOf(t)&&!0===t.call({},e)}function _(e,t,r,n){var i;if("function"!=typeof t)throw new TypeError('"block" argument must be a function');"string"==typeof r&&(n=r,r=null),i=function(e){var t;try{e()}catch(e){t=e}return t}(t),n=(r&&r.name?" ("+r.name+").":".")+(n?" "+n:"."),e&&!i&&y(i,r,"Missing expected exception"+n);var a="string"==typeof n,s=!e&&i&&!r;if((!e&&o.isError(i)&&a&&w(i,r)||s)&&y(i,r,"Got unwanted exception"+n),e&&i&&r&&!w(i,r)||!e&&i)throw i}h.AssertionError=function(e){var t;this.name="AssertionError",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,e.message?(this.message=e.message,this.generatedMessage=!1):(this.message=p(b((t=this).actual),128)+" "+t.operator+" "+p(b(t.expected),128),this.generatedMessage=!0);var r=e.stackStartFunction||y;if(Error.captureStackTrace)Error.captureStackTrace(this,r);else{var n=new Error;if(n.stack){var i=n.stack,o=d(r),a=i.indexOf("\n"+o);if(a>=0){var s=i.indexOf("\n",a+1);i=i.substring(s+1)}this.stack=i}}},o.inherits(h.AssertionError,Error),h.fail=y,h.ok=m,h.equal=function(e,t,r){e!=t&&y(e,t,r,"==",h.equal)},h.notEqual=function(e,t,r){e==t&&y(e,t,r,"!=",h.notEqual)},h.deepEqual=function(e,t,r){v(e,t,!1)||y(e,t,r,"deepEqual",h.deepEqual)},h.deepStrictEqual=function(e,t,r){v(e,t,!0)||y(e,t,r,"deepStrictEqual",h.deepStrictEqual)},h.notDeepEqual=function(e,t,r){v(e,t,!1)&&y(e,t,r,"notDeepEqual",h.notDeepEqual)},h.notDeepStrictEqual=function e(t,r,n){v(t,r,!0)&&y(t,r,n,"notDeepStrictEqual",e)},h.strictEqual=function(e,t,r){e!==t&&y(e,t,r,"===",h.strictEqual)},h.notStrictEqual=function(e,t,r){e===t&&y(e,t,r,"!==",h.notStrictEqual)},h.throws=function(e,t,r){_(!0,e,t,r)},h.doesNotThrow=function(e,t,r){_(!1,e,t,r)},h.ifError=function(e){if(e)throw e};var A=Object.keys||function(e){var t=[];for(var r in e)a.call(e,r)&&t.push(r);return t}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"util/":333}],20:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(function(t,r){var i;try{i=e.apply(this,t)}catch(e){return r(e)}(0,n.default)(i)&&"function"==typeof i.then?i.then(function(e){s(r,null,e)},function(e){s(r,e.message?e:new Error(e))}):r(null,i)})};var n=a(e("lodash/isObject")),i=a(e("./internal/initialParams")),o=a(e("./internal/setImmediate"));function a(e){return e&&e.__esModule?e:{default:e}}function s(e,t,r){try{e(t,r)}catch(e){(0,o.default)(u,e)}}function u(e){throw e}t.exports=r.default},{"./internal/initialParams":31,"./internal/setImmediate":37,"lodash/isObject":225}],21:[function(e,t,r){(function(e,n){!function(e,n){"object"==typeof r&&void 0!==t?n(r):"function"==typeof define&&define.amd?define(["exports"],n):n(e.async=e.async||{})}(this,function(r){"use strict";function i(e,t){t|=0;for(var r=Math.max(e.length-t,0),n=Array(r),i=0;i-1&&e%1==0&&e<=L}function D(e){return null!=e&&O(e.length)&&!function(e){if(!s(e))return!1;var t=B(e);return t==C||t==N||t==P||t==R}(e)}var F={};function q(){}function H(e){return function(){if(null!==e){var t=e;e=null,t.apply(this,arguments)}}}var z="function"==typeof Symbol&&Symbol.iterator,K=function(e){return z&&e[z]&&e[z]()};function V(e){return null!=e&&"object"==typeof e}var G="[object Arguments]";function W(e){return V(e)&&B(e)==G}var Y=Object.prototype,X=Y.hasOwnProperty,Z=Y.propertyIsEnumerable,J=W(function(){return arguments}())?W:function(e){return V(e)&&X.call(e,"callee")&&!Z.call(e,"callee")},$=Array.isArray;var Q="object"==typeof r&&r&&!r.nodeType&&r,ee=Q&&"object"==typeof t&&t&&!t.nodeType&&t,te=ee&&ee.exports===Q?A.Buffer:void 0,re=(te?te.isBuffer:void 0)||function(){return!1},ne=9007199254740991,ie=/^(?:0|[1-9]\d*)$/;function oe(e,t){return!!(t=null==t?ne:t)&&("number"==typeof e||ie.test(e))&&e>-1&&e%1==0&&e2&&(n=i(arguments,1)),t){var c={};Fe(o,function(e,t){c[t]=e}),c[e]=n,s=!0,u=Object.create(null),r(t,c)}else o[e]=n,Le(u[e]||[],function(e){e()}),d()});a++;var c=v(t[t.length-1]);t.length>1?c(o,n):c(n)}(e,t)})}function d(){if(0===c.length&&0===a)return r(null,o);for(;c.length&&a=0&&r.push(n)}),r}Fe(e,function(t,r){if(!$(t))return l(r,[t]),void f.push(r);var n=t.slice(0,t.length-1),i=n.length;if(0===i)return l(r,t),void f.push(r);h[r]=i,Le(n,function(o){if(!e[o])throw new Error("async.auto task `"+r+"` has a non-existent dependency `"+o+"` in "+n.join(", "));!function(e,t){var r=u[e];r||(r=u[e]=[]);r.push(t)}(o,function(){0===--i&&l(r,t)})})}),function(){var e,t=0;for(;f.length;)e=f.pop(),t++,Le(p(e),function(e){0==--h[e]&&f.push(e)});if(t!==n)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}(),d()};function Ke(e,t){for(var r=-1,n=null==e?0:e.length,i=Array(n);++r=n?e:function(e,t,r){var n=-1,i=e.length;t<0&&(t=-t>i?0:i+t),(r=r>i?i:r)<0&&(r+=i),i=t>r?0:r-t>>>0,t>>>=0;for(var o=Array(i);++n-1;);return r}(i,o),function(e,t){for(var r=e.length;r--&&He(t,e[r],0)>-1;);return r}(i,o)+1).join("")}var ht=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,lt=/,/,dt=/(=.+)?(\s*)$/,pt=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;function bt(e,t){var r={};Fe(e,function(e,t){var n,i,o=m(e),a=!o&&1===e.length||o&&0===e.length;if($(e))n=e.slice(0,-1),e=e[e.length-1],r[t]=n.concat(n.length>0?s:e);else if(a)r[t]=e;else{if(n=i=(i=(i=(i=(i=e).toString().replace(pt,"")).match(ht)[2].replace(" ",""))?i.split(lt):[]).map(function(e){return ft(e.replace(dt,""))}),0===e.length&&!o&&0===n.length)throw new Error("autoInject task functions require explicit parameters.");o||n.pop(),r[t]=n.concat(s)}function s(t,r){var i=Ke(n,function(e){return t[e]});i.push(r),v(e).apply(null,i)}}),ze(r,t)}function yt(){this.head=this.tail=null,this.length=0}function mt(e,t){e.length=1,e.head=e.tail=t}function vt(e,t,r){if(null==t)t=1;else if(0===t)throw new Error("Concurrency must not be zero");var n=v(e),i=0,o=[],a=!1;function s(e,t,r){if(null!=r&&"function"!=typeof r)throw new Error("task callback must be a function");if(f.started=!0,$(e)||(e=[e]),0===e.length&&f.idle())return l(function(){f.drain()});for(var n=0,i=e.length;n0&&o.splice(s,1),a.callback.apply(a,arguments),null!=t&&f.error(t,a.data)}i<=f.concurrency-f.buffer&&f.unsaturated(),f.idle()&&f.drain(),f.process()}}var c=!1,f={_tasks:new yt,concurrency:t,payload:r,saturated:q,unsaturated:q,buffer:t/4,empty:q,drain:q,error:q,started:!1,paused:!1,push:function(e,t){s(e,!1,t)},kill:function(){f.drain=q,f._tasks.empty()},unshift:function(e,t){s(e,!0,t)},remove:function(e){f._tasks.remove(e)},process:function(){if(!c){for(c=!0;!f.paused&&i2&&(o=i(arguments,1)),n[t]=o,r(e)})},function(e){r(e,n)})}function br(e,t){pr(Ie,e,t)}function yr(e,t,r){pr(Ee(t),e,r)}var mr=function(e,t){var r=v(e);return vt(function(e,t){r(e[0],t)},t,1)},vr=function(e,t){var r=mr(e,t);return r.push=function(e,t,n){if(null==n&&(n=q),"function"!=typeof n)throw new Error("task callback must be a function");if(r.started=!0,$(e)||(e=[e]),0===e.length)return l(function(){r.drain()});t=t||0;for(var i=r._tasks.head;i&&t>=i.priority;)i=i.next;for(var o=0,a=e.length;on?1:0}je(e,function(e,t){n(e,function(r,n){if(r)return t(r);t(null,{value:e,criteria:n})})},function(e,t){if(e)return r(e);r(null,Ke(t.sort(i),Zt("value")))})}function Nr(e,t,r){var n=v(e);return a(function(i,o){var a,s=!1;i.push(function(){s||(o.apply(null,arguments),clearTimeout(a))}),a=setTimeout(function(){var t=e.name||"anonymous",n=new Error('Callback function "'+t+'" timed out.');n.code="ETIMEDOUT",r&&(n.info=r),s=!0,o(n)},t),n.apply(null,i)})}var Rr=Math.ceil,Lr=Math.max;function Or(e,t,r,n){var i=v(r);Ce(function(e,t,r,n){for(var i=-1,o=Lr(Rr((t-e)/(r||1)),0),a=Array(o);o--;)a[n?o:++i]=e,e+=r;return a}(0,e,1),t,i,n)}var Dr=ke(Or,1/0),Fr=ke(Or,1);function qr(e,t,r,n){arguments.length<=3&&(n=r,r=t,t=$(e)?[]:{}),n=H(n||q);var i=v(r);Ie(e,function(e,r,n){i(t,e,r,n)},function(e){n(e,t)})}function Hr(e,t){var r,n=null;t=t||q,Kt(e,function(e,t){v(e)(function(e,o){r=arguments.length>2?i(arguments,1):o,n=e,t(!e)})},function(){t(n,r)})}function zr(e){return function(){return(e.unmemoized||e).apply(null,arguments)}}function Kr(e,t,r){r=Ae(r||q);var n=v(t);if(!e())return r(null);var o=function(t){if(t)return r(t);if(e())return n(o);var a=i(arguments,1);r.apply(null,[null].concat(a))};n(o)}function Vr(e,t,r){Kr(function(){return!e.apply(this,arguments)},t,r)}var Gr=function(e,t){if(t=H(t||q),!$(e))return t(new Error("First argument to waterfall must be an array of functions"));if(!e.length)return t();var r=0;function n(t){var n=v(e[r++]);t.push(Ae(o)),n.apply(null,t)}function o(o){if(o||r===e.length)return t.apply(null,arguments);n(i(arguments,1))}n([])},Wr={apply:o,applyEach:Be,applyEachSeries:Re,asyncify:d,auto:ze,autoInject:bt,cargo:gt,compose:Et,concat:St,concatLimit:kt,concatSeries:Mt,constant:It,detect:Bt,detectLimit:Pt,detectSeries:Ct,dir:Rt,doDuring:Lt,doUntil:Dt,doWhilst:Ot,during:Ft,each:Ht,eachLimit:zt,eachOf:Ie,eachOfLimit:xe,eachOfSeries:wt,eachSeries:Kt,ensureAsync:Vt,every:Wt,everyLimit:Yt,everySeries:Xt,filter:er,filterLimit:tr,filterSeries:rr,forever:nr,groupBy:or,groupByLimit:ir,groupBySeries:ar,log:sr,map:je,mapLimit:Ce,mapSeries:Ne,mapValues:cr,mapValuesLimit:ur,mapValuesSeries:fr,memoize:lr,nextTick:dr,parallel:br,parallelLimit:yr,priorityQueue:vr,queue:mr,race:gr,reduce:_t,reduceRight:wr,reflect:_r,reflectAll:Ar,reject:xr,rejectLimit:kr,rejectSeries:Sr,retry:Ir,retryable:Tr,seq:At,series:Ur,setImmediate:l,some:jr,someLimit:Br,someSeries:Pr,sortBy:Cr,timeout:Nr,times:Dr,timesLimit:Or,timesSeries:Fr,transform:qr,tryEach:Hr,unmemoize:zr,until:Vr,waterfall:Gr,whilst:Kr,all:Wt,allLimit:Yt,allSeries:Xt,any:jr,anyLimit:Br,anySeries:Pr,find:Bt,findLimit:Pt,findSeries:Ct,forEach:Ht,forEachSeries:Kt,forEachLimit:zt,forEachOf:Ie,forEachOfSeries:wt,forEachOfLimit:xe,inject:_t,foldl:_t,foldr:wr,select:er,selectLimit:tr,selectSeries:rr,wrapSync:d};r.default=Wr,r.apply=o,r.applyEach=Be,r.applyEachSeries=Re,r.asyncify=d,r.auto=ze,r.autoInject=bt,r.cargo=gt,r.compose=Et,r.concat=St,r.concatLimit=kt,r.concatSeries=Mt,r.constant=It,r.detect=Bt,r.detectLimit=Pt,r.detectSeries=Ct,r.dir=Rt,r.doDuring=Lt,r.doUntil=Dt,r.doWhilst=Ot,r.during=Ft,r.each=Ht,r.eachLimit=zt,r.eachOf=Ie,r.eachOfLimit=xe,r.eachOfSeries=wt,r.eachSeries=Kt,r.ensureAsync=Vt,r.every=Wt,r.everyLimit=Yt,r.everySeries=Xt,r.filter=er,r.filterLimit=tr,r.filterSeries=rr,r.forever=nr,r.groupBy=or,r.groupByLimit=ir,r.groupBySeries=ar,r.log=sr,r.map=je,r.mapLimit=Ce,r.mapSeries=Ne,r.mapValues=cr,r.mapValuesLimit=ur,r.mapValuesSeries=fr,r.memoize=lr,r.nextTick=dr,r.parallel=br,r.parallelLimit=yr,r.priorityQueue=vr,r.queue=mr,r.race=gr,r.reduce=_t,r.reduceRight=wr,r.reflect=_r,r.reflectAll=Ar,r.reject=xr,r.rejectLimit=kr,r.rejectSeries=Sr,r.retry=Ir,r.retryable=Tr,r.seq=At,r.series=Ur,r.setImmediate=l,r.some=jr,r.someLimit=Br,r.someSeries=Pr,r.sortBy=Cr,r.timeout=Nr,r.times=Dr,r.timesLimit=Or,r.timesSeries=Fr,r.transform=qr,r.tryEach=Hr,r.unmemoize=zr,r.until=Vr,r.waterfall=Gr,r.whilst=Kr,r.all=Wt,r.allLimit=Yt,r.allSeries=Xt,r.any=jr,r.anyLimit=Br,r.anySeries=Pr,r.find=Bt,r.findLimit=Pt,r.findSeries=Ct,r.forEach=Ht,r.forEachSeries=Kt,r.forEachLimit=zt,r.forEachOf=Ie,r.forEachOfSeries=wt,r.forEachOfLimit=xe,r.inject=_t,r.foldl=_t,r.foldr=wr,r.select=er,r.selectLimit=tr,r.selectSeries=rr,r.wrapSync=d,Object.defineProperty(r,"__esModule",{value:!0})})}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:257}],22:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t,r,a){(0,n.default)(t)(e,(0,i.default)((0,o.default)(r)),a)};var n=a(e("./internal/eachOfLimit")),i=a(e("./internal/withoutIndex")),o=a(e("./internal/wrapAsync"));function a(e){return e&&e.__esModule?e:{default:e}}t.exports=r.default},{"./internal/eachOfLimit":29,"./internal/withoutIndex":39,"./internal/wrapAsync":40}],23:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t,r){((0,n.default)(e)?l:d)(e,(0,f.default)(t),r)};var n=h(e("lodash/isArrayLike")),i=h(e("./internal/breakLoop")),o=h(e("./eachOfLimit")),a=h(e("./internal/doLimit")),s=h(e("lodash/noop")),u=h(e("./internal/once")),c=h(e("./internal/onlyOnce")),f=h(e("./internal/wrapAsync"));function h(e){return e&&e.__esModule?e:{default:e}}function l(e,t,r){r=(0,u.default)(r||s.default);var n=0,o=0,a=e.length;function f(e,t){e?r(e):++o!==a&&t!==i.default||r(null)}for(0===a&&r(null);n2&&(n=(0,o.default)(arguments,1)),s[t]=n,r(e)})},function(e){r(e,s)})};var n=s(e("lodash/noop")),i=s(e("lodash/isArrayLike")),o=s(e("./slice")),a=s(e("./wrapAsync"));function s(e){return e&&e.__esModule?e:{default:e}}t.exports=r.default},{"./slice":38,"./wrapAsync":40,"lodash/isArrayLike":221,"lodash/noop":229}],37:[function(e,t,r){(function(t){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.hasNextTick=r.hasSetImmediate=void 0,r.fallback=c,r.wrap=f;var n,i=e("./slice"),o=(n=i)&&n.__esModule?n:{default:n};var a,s=r.hasSetImmediate="function"==typeof setImmediate&&setImmediate,u=r.hasNextTick="object"==typeof t&&"function"==typeof t.nextTick;function c(e){setTimeout(e,0)}function f(e){return function(t){var r=(0,o.default)(arguments,1);e(function(){t.apply(null,r)})}}a=s?setImmediate:u?t.nextTick:c,r.default=f(a)}).call(this,e("_process"))},{"./slice":38,_process:257}],38:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){t|=0;for(var r=Math.max(e.length-t,0),n=Array(r),i=0;i0,"Expected a maximum number of retry greater than 0 but got %s.",e),this.maxNumberOfRetry_=e},o.prototype.backoff=function(e){i.checkState(-1===this.timeoutID_,"Backoff in progress."),this.backoffNumber_===this.maxNumberOfRetry_?(this.emit("fail",e),this.reset()):(this.backoffDelay_=this.backoffStrategy_.next(),this.timeoutID_=setTimeout(this.handlers.backoff,this.backoffDelay_),this.emit("backoff",this.backoffNumber_,this.backoffDelay_,e))},o.prototype.onBackoff_=function(){this.timeoutID_=-1,this.emit("ready",this.backoffNumber_,this.backoffDelay_),this.backoffNumber_++},o.prototype.reset=function(){this.backoffNumber_=0,this.backoffStrategy_.reset(),clearTimeout(this.timeoutID_),this.timeoutID_=-1},t.exports=o},{events:157,precond:253,util:333}],47:[function(e,t,r){var n=e("events"),i=e("precond"),o=e("util"),a=e("./backoff"),s=e("./strategy/fibonacci");function u(e,t,r){n.EventEmitter.call(this),i.checkIsFunction(e,"Expected fn to be a function."),i.checkIsArray(t,"Expected args to be an array."),i.checkIsFunction(r,"Expected callback to be a function."),this.function_=e,this.arguments_=t,this.callback_=r,this.lastResult_=[],this.numRetries_=0,this.backoff_=null,this.strategy_=null,this.failAfter_=-1,this.retryPredicate_=u.DEFAULT_RETRY_PREDICATE_,this.state_=u.State_.PENDING}o.inherits(u,n.EventEmitter),u.State_={PENDING:0,RUNNING:1,COMPLETED:2,ABORTED:3},u.DEFAULT_RETRY_PREDICATE_=function(e){return!0},u.prototype.isPending=function(){return this.state_==u.State_.PENDING},u.prototype.isRunning=function(){return this.state_==u.State_.RUNNING},u.prototype.isCompleted=function(){return this.state_==u.State_.COMPLETED},u.prototype.isAborted=function(){return this.state_==u.State_.ABORTED},u.prototype.setStrategy=function(e){return i.checkState(this.isPending(),"FunctionCall in progress."),this.strategy_=e,this},u.prototype.retryIf=function(e){return i.checkState(this.isPending(),"FunctionCall in progress."),this.retryPredicate_=e,this},u.prototype.getLastResult=function(){return this.lastResult_.concat()},u.prototype.getNumRetries=function(){return this.numRetries_},u.prototype.failAfter=function(e){return i.checkState(this.isPending(),"FunctionCall in progress."),this.failAfter_=e,this},u.prototype.abort=function(){this.isCompleted()||this.isAborted()||(this.isRunning()&&this.backoff_.reset(),this.state_=u.State_.ABORTED,this.lastResult_=[new Error("Backoff aborted.")],this.emit("abort"),this.doCallback_())},u.prototype.start=function(e){i.checkState(!this.isAborted(),"FunctionCall is aborted."),i.checkState(this.isPending(),"FunctionCall already started.");var t=this.strategy_||new s;this.backoff_=e?e(t):new a(t),this.backoff_.on("ready",this.doCall_.bind(this,!0)),this.backoff_.on("fail",this.doCallback_.bind(this)),this.backoff_.on("backoff",this.handleBackoff_.bind(this)),this.failAfter_>0&&this.backoff_.failAfter(this.failAfter_),this.state_=u.State_.RUNNING,this.doCall_(!1)},u.prototype.doCall_=function(e){e&&this.numRetries_++;var t=["call"].concat(this.arguments_);n.EventEmitter.prototype.emit.apply(this,t);var r=this.handleFunctionCallback_.bind(this);this.function_.apply(null,this.arguments_.concat(r))},u.prototype.doCallback_=function(){this.callback_.apply(null,this.lastResult_)},u.prototype.handleFunctionCallback_=function(){if(!this.isAborted()){var e=Array.prototype.slice.call(arguments);this.lastResult_=e,n.EventEmitter.prototype.emit.apply(this,["callback"].concat(e));var t=e[0];t&&this.retryPredicate_(t)?this.backoff_.backoff(t):(this.state_=u.State_.COMPLETED,this.doCallback_())}},u.prototype.handleBackoff_=function(e,t,r){this.emit("backoff",e,t,r)},t.exports=u},{"./backoff":46,"./strategy/fibonacci":49,events:157,precond:253,util:333}],48:[function(e,t,r){var n=e("util"),i=e("precond"),o=e("./strategy");function a(e){o.call(this,e),this.backoffDelay_=0,this.nextBackoffDelay_=this.getInitialDelay(),this.factor_=a.DEFAULT_FACTOR,e&&void 0!==e.factor&&(i.checkArgument(e.factor>1,"Exponential factor should be greater than 1 but got %s.",e.factor),this.factor_=e.factor)}n.inherits(a,o),a.DEFAULT_FACTOR=2,a.prototype.next_=function(){return this.backoffDelay_=Math.min(this.nextBackoffDelay_,this.getMaxDelay()),this.nextBackoffDelay_=this.backoffDelay_*this.factor_,this.backoffDelay_},a.prototype.reset_=function(){this.backoffDelay_=0,this.nextBackoffDelay_=this.getInitialDelay()},t.exports=a},{"./strategy":50,precond:253,util:333}],49:[function(e,t,r){var n=e("util"),i=e("./strategy");function o(e){i.call(this,e),this.backoffDelay_=0,this.nextBackoffDelay_=this.getInitialDelay()}n.inherits(o,i),o.prototype.next_=function(){var e=Math.min(this.nextBackoffDelay_,this.getMaxDelay());return this.nextBackoffDelay_+=this.backoffDelay_,this.backoffDelay_=e,e},o.prototype.reset_=function(){this.nextBackoffDelay_=this.getInitialDelay(),this.backoffDelay_=0},t.exports=o},{"./strategy":50,util:333}],50:[function(e,t,r){e("events"),e("util");function n(e){return null!=e}function i(e){if(n((e=e||{}).initialDelay)&&e.initialDelay<1)throw new Error("The initial timeout must be greater than 0.");if(n(e.maxDelay)&&e.maxDelay<1)throw new Error("The maximal timeout must be greater than 0.");if(this.initialDelay_=e.initialDelay||100,this.maxDelay_=e.maxDelay||1e4,this.maxDelay_<=this.initialDelay_)throw new Error("The maximal backoff delay must be greater than the initial backoff delay.");if(n(e.randomisationFactor)&&(e.randomisationFactor<0||e.randomisationFactor>1))throw new Error("The randomisation factor must be between 0 and 1.");this.randomisationFactor_=e.randomisationFactor||0}i.prototype.getMaxDelay=function(){return this.maxDelay_},i.prototype.getInitialDelay=function(){return this.initialDelay_},i.prototype.next=function(){var e=this.next_(),t=1+Math.random()*this.randomisationFactor_;return Math.round(e*t)},i.prototype.next_=function(){throw new Error("BackoffStrategy.next_() unimplemented.")},i.prototype.reset=function(){this.reset_()},i.prototype.reset_=function(){throw new Error("BackoffStrategy.reset_() unimplemented.")},t.exports=i},{events:157,util:333}],51:[function(e,t,r){"use strict";r.byteLength=function(e){return 3*e.length/4-c(e)},r.toByteArray=function(e){var t,r,n,a,s,u=e.length;a=c(e),s=new o(3*u/4-a),r=a>0?u-4:u;var f=0;for(t=0;t>16&255,s[f++]=n>>8&255,s[f++]=255&n;2===a?(n=i[e.charCodeAt(t)]<<2|i[e.charCodeAt(t+1)]>>4,s[f++]=255&n):1===a&&(n=i[e.charCodeAt(t)]<<10|i[e.charCodeAt(t+1)]<<4|i[e.charCodeAt(t+2)]>>2,s[f++]=n>>8&255,s[f++]=255&n);return s},r.fromByteArray=function(e){for(var t,r=e.length,i=r%3,o="",a=[],s=0,u=r-i;su?u:s+16383));1===i?(t=e[r-1],o+=n[t>>2],o+=n[t<<4&63],o+="=="):2===i&&(t=(e[r-2]<<8)+e[r-1],o+=n[t>>10],o+=n[t>>4&63],o+=n[t<<2&63],o+="=");return a.push(o),a.join("")};for(var n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,u=a.length;s0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===e[t-2]?2:"="===e[t-1]?1:0}function f(e,t,r){for(var i,o,a=[],s=t;s>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return a.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},{}],52:[function(e,t,r){var n=e("safe-buffer").Buffer;t.exports={check:function(e){if(e.length<8)return!1;if(e.length>72)return!1;if(48!==e[0])return!1;if(e[1]!==e.length-2)return!1;if(2!==e[2])return!1;var t=e[3];if(0===t)return!1;if(5+t>=e.length)return!1;if(2!==e[4+t])return!1;var r=e[5+t];return!(0===r||6+t+r!==e.length||128&e[4]||t>1&&0===e[4]&&!(128&e[5])||128&e[t+6]||r>1&&0===e[t+6]&&!(128&e[t+7]))},decode:function(e){if(e.length<8)throw new Error("DER sequence length is too short");if(e.length>72)throw new Error("DER sequence length is too long");if(48!==e[0])throw new Error("Expected DER sequence");if(e[1]!==e.length-2)throw new Error("DER sequence length is invalid");if(2!==e[2])throw new Error("Expected DER integer");var t=e[3];if(0===t)throw new Error("R length is zero");if(5+t>=e.length)throw new Error("R length is too long");if(2!==e[4+t])throw new Error("Expected DER integer (2)");var r=e[5+t];if(0===r)throw new Error("S length is zero");if(6+t+r!==e.length)throw new Error("S length is invalid");if(128&e[4])throw new Error("R value is negative");if(t>1&&0===e[4]&&!(128&e[5]))throw new Error("R value excessively padded");if(128&e[t+6])throw new Error("S value is negative");if(r>1&&0===e[t+6]&&!(128&e[t+7]))throw new Error("S value excessively padded");return{r:e.slice(4,4+t),s:e.slice(6+t)}},encode:function(e,t){var r=e.length,i=t.length;if(0===r)throw new Error("R length is zero");if(0===i)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(i>33)throw new Error("S length is too long");if(128&e[0])throw new Error("R value is negative");if(128&t[0])throw new Error("S value is negative");if(r>1&&0===e[0]&&!(128&e[1]))throw new Error("R value excessively padded");if(i>1&&0===t[0]&&!(128&t[1]))throw new Error("S value excessively padded");var o=n.allocUnsafe(6+r+i);return o[0]=48,o[1]=o.length-2,o[2]=2,o[3]=e.length,e.copy(o,4),o[4+r]=2,o[5+r]=t.length,t.copy(o,6+r),o}}},{"safe-buffer":290}],53:[function(e,t,r){!function(t,r){"use strict";function n(e,t){if(!e)throw new Error(t||"Assertion failed")}function i(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}function o(e,t,r){if(o.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(r=t,t=10),this._init(e||0,t||10,r||"be"))}var a;"object"==typeof t?t.exports=o:r.BN=o,o.BN=o,o.wordSize=26;try{a=e("buffer").Buffer}catch(e){}function s(e,t,r){for(var n=0,i=Math.min(e.length,r),o=t;o=49&&a<=54?a-49+10:a>=17&&a<=22?a-17+10:15&a}return n}function u(e,t,r,n){for(var i=0,o=Math.min(e.length,r),a=t;a=49?s-49+10:s>=17?s-17+10:s}return i}o.isBN=function(e){return e instanceof o||null!==e&&"object"==typeof e&&e.constructor.wordSize===o.wordSize&&Array.isArray(e.words)},o.max=function(e,t){return e.cmp(t)>0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&i++,16===t?this._parseHex(e,i):this._parseBase(e,t,i),"-"===e[0]&&(this.negative=1),this.strip(),"le"===r&&this._initArray(this.toArray(),t,r)},o.prototype._initNumber=function(e,t,r){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(n(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===r&&this._initArray(this.toArray(),t,r)},o.prototype._initArray=function(e,t,r){if(n("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3)a=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[o]|=a<>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);else if("le"===r)for(i=0,o=0;i>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);return this.strip()},o.prototype._parseHex=function(e,t){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var r=0;r=t;r-=6)i=s(e,r,r+6),this.words[n]|=i<>>26-o&4194303,(o+=24)>=26&&(o-=26,n++);r+6!==t&&(i=s(e,t,r+6),this.words[n]|=i<>>26-o&4194303),this.strip()},o.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=t)n++;n--,i=i/t|0;for(var o=e.length-r,a=o%n,s=Math.min(o,o-a)+r,c=0,f=r;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},o.prototype.inspect=function(){return(this.red?""};var c=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],f=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],h=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(e,t,r){r.negative=t.negative^e.negative;var n=e.length+t.length|0;r.length=n,n=n-1|0;var i=0|e.words[0],o=0|t.words[0],a=i*o,s=67108863&a,u=a/67108864|0;r.words[0]=s;for(var c=1;c>>26,h=67108863&u,l=Math.min(c,t.length-1),d=Math.max(0,c-e.length+1);d<=l;d++){var p=c-d|0;f+=(a=(i=0|e.words[p])*(o=0|t.words[d])+h)/67108864|0,h=67108863&a}r.words[c]=0|h,u=0|f}return 0!==u?r.words[c]=0|u:r.length--,r.strip()}o.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var i=0,o=0,a=0;a>>24-i&16777215)||a!==this.length-1?c[6-u.length]+u+r:u+r,(i+=2)>=26&&(i-=26,a--)}for(0!==o&&(r=o.toString(16)+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var l=f[e],d=h[e];r="";var p=this.clone();for(p.negative=0;!p.isZero();){var b=p.modn(d).toString(e);r=(p=p.idivn(d)).isZero()?b+r:c[l-b.length]+b+r}for(this.isZero()&&(r="0"+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16)},o.prototype.toBuffer=function(e,t){return n(void 0!==a),this.toArrayLike(a,e,t)},o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},o.prototype.toArrayLike=function(e,t,r){var i=this.byteLength(),o=r||Math.max(1,i);n(i<=o,"byte array longer than desired length"),n(o>0,"Requested array length <= 0"),this.strip();var a,s,u="le"===t,c=new e(o),f=this.clone();if(u){for(s=0;!f.isZero();s++)a=f.andln(255),f.iushrn(8),c[s]=a;for(;s=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;re.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,r;this.length>e.length?(t=this,r=e):(t=e,r=this);for(var n=0;ne.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-r),this.strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,i=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<e.length?(r=this,n=e):(r=e,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;oe.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var r,n,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=e):(r=e,n=this);for(var o=0,a=0;a>26,this.words[a]=67108863&t;for(;0!==o&&a>26,this.words[a]=67108863&t;if(0===o&&a>>13,d=0|a[1],p=8191&d,b=d>>>13,y=0|a[2],m=8191&y,v=y>>>13,g=0|a[3],w=8191&g,_=g>>>13,A=0|a[4],E=8191&A,x=A>>>13,k=0|a[5],S=8191&k,M=k>>>13,I=0|a[6],T=8191&I,U=I>>>13,j=0|a[7],B=8191&j,P=j>>>13,C=0|a[8],N=8191&C,R=C>>>13,L=0|a[9],O=8191&L,D=L>>>13,F=0|s[0],q=8191&F,H=F>>>13,z=0|s[1],K=8191&z,V=z>>>13,G=0|s[2],W=8191&G,Y=G>>>13,X=0|s[3],Z=8191&X,J=X>>>13,$=0|s[4],Q=8191&$,ee=$>>>13,te=0|s[5],re=8191&te,ne=te>>>13,ie=0|s[6],oe=8191&ie,ae=ie>>>13,se=0|s[7],ue=8191&se,ce=se>>>13,fe=0|s[8],he=8191&fe,le=fe>>>13,de=0|s[9],pe=8191&de,be=de>>>13;r.negative=e.negative^t.negative,r.length=19;var ye=(c+(n=Math.imul(h,q))|0)+((8191&(i=(i=Math.imul(h,H))+Math.imul(l,q)|0))<<13)|0;c=((o=Math.imul(l,H))+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,n=Math.imul(p,q),i=(i=Math.imul(p,H))+Math.imul(b,q)|0,o=Math.imul(b,H);var me=(c+(n=n+Math.imul(h,K)|0)|0)+((8191&(i=(i=i+Math.imul(h,V)|0)+Math.imul(l,K)|0))<<13)|0;c=((o=o+Math.imul(l,V)|0)+(i>>>13)|0)+(me>>>26)|0,me&=67108863,n=Math.imul(m,q),i=(i=Math.imul(m,H))+Math.imul(v,q)|0,o=Math.imul(v,H),n=n+Math.imul(p,K)|0,i=(i=i+Math.imul(p,V)|0)+Math.imul(b,K)|0,o=o+Math.imul(b,V)|0;var ve=(c+(n=n+Math.imul(h,W)|0)|0)+((8191&(i=(i=i+Math.imul(h,Y)|0)+Math.imul(l,W)|0))<<13)|0;c=((o=o+Math.imul(l,Y)|0)+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,n=Math.imul(w,q),i=(i=Math.imul(w,H))+Math.imul(_,q)|0,o=Math.imul(_,H),n=n+Math.imul(m,K)|0,i=(i=i+Math.imul(m,V)|0)+Math.imul(v,K)|0,o=o+Math.imul(v,V)|0,n=n+Math.imul(p,W)|0,i=(i=i+Math.imul(p,Y)|0)+Math.imul(b,W)|0,o=o+Math.imul(b,Y)|0;var ge=(c+(n=n+Math.imul(h,Z)|0)|0)+((8191&(i=(i=i+Math.imul(h,J)|0)+Math.imul(l,Z)|0))<<13)|0;c=((o=o+Math.imul(l,J)|0)+(i>>>13)|0)+(ge>>>26)|0,ge&=67108863,n=Math.imul(E,q),i=(i=Math.imul(E,H))+Math.imul(x,q)|0,o=Math.imul(x,H),n=n+Math.imul(w,K)|0,i=(i=i+Math.imul(w,V)|0)+Math.imul(_,K)|0,o=o+Math.imul(_,V)|0,n=n+Math.imul(m,W)|0,i=(i=i+Math.imul(m,Y)|0)+Math.imul(v,W)|0,o=o+Math.imul(v,Y)|0,n=n+Math.imul(p,Z)|0,i=(i=i+Math.imul(p,J)|0)+Math.imul(b,Z)|0,o=o+Math.imul(b,J)|0;var we=(c+(n=n+Math.imul(h,Q)|0)|0)+((8191&(i=(i=i+Math.imul(h,ee)|0)+Math.imul(l,Q)|0))<<13)|0;c=((o=o+Math.imul(l,ee)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,n=Math.imul(S,q),i=(i=Math.imul(S,H))+Math.imul(M,q)|0,o=Math.imul(M,H),n=n+Math.imul(E,K)|0,i=(i=i+Math.imul(E,V)|0)+Math.imul(x,K)|0,o=o+Math.imul(x,V)|0,n=n+Math.imul(w,W)|0,i=(i=i+Math.imul(w,Y)|0)+Math.imul(_,W)|0,o=o+Math.imul(_,Y)|0,n=n+Math.imul(m,Z)|0,i=(i=i+Math.imul(m,J)|0)+Math.imul(v,Z)|0,o=o+Math.imul(v,J)|0,n=n+Math.imul(p,Q)|0,i=(i=i+Math.imul(p,ee)|0)+Math.imul(b,Q)|0,o=o+Math.imul(b,ee)|0;var _e=(c+(n=n+Math.imul(h,re)|0)|0)+((8191&(i=(i=i+Math.imul(h,ne)|0)+Math.imul(l,re)|0))<<13)|0;c=((o=o+Math.imul(l,ne)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,n=Math.imul(T,q),i=(i=Math.imul(T,H))+Math.imul(U,q)|0,o=Math.imul(U,H),n=n+Math.imul(S,K)|0,i=(i=i+Math.imul(S,V)|0)+Math.imul(M,K)|0,o=o+Math.imul(M,V)|0,n=n+Math.imul(E,W)|0,i=(i=i+Math.imul(E,Y)|0)+Math.imul(x,W)|0,o=o+Math.imul(x,Y)|0,n=n+Math.imul(w,Z)|0,i=(i=i+Math.imul(w,J)|0)+Math.imul(_,Z)|0,o=o+Math.imul(_,J)|0,n=n+Math.imul(m,Q)|0,i=(i=i+Math.imul(m,ee)|0)+Math.imul(v,Q)|0,o=o+Math.imul(v,ee)|0,n=n+Math.imul(p,re)|0,i=(i=i+Math.imul(p,ne)|0)+Math.imul(b,re)|0,o=o+Math.imul(b,ne)|0;var Ae=(c+(n=n+Math.imul(h,oe)|0)|0)+((8191&(i=(i=i+Math.imul(h,ae)|0)+Math.imul(l,oe)|0))<<13)|0;c=((o=o+Math.imul(l,ae)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,n=Math.imul(B,q),i=(i=Math.imul(B,H))+Math.imul(P,q)|0,o=Math.imul(P,H),n=n+Math.imul(T,K)|0,i=(i=i+Math.imul(T,V)|0)+Math.imul(U,K)|0,o=o+Math.imul(U,V)|0,n=n+Math.imul(S,W)|0,i=(i=i+Math.imul(S,Y)|0)+Math.imul(M,W)|0,o=o+Math.imul(M,Y)|0,n=n+Math.imul(E,Z)|0,i=(i=i+Math.imul(E,J)|0)+Math.imul(x,Z)|0,o=o+Math.imul(x,J)|0,n=n+Math.imul(w,Q)|0,i=(i=i+Math.imul(w,ee)|0)+Math.imul(_,Q)|0,o=o+Math.imul(_,ee)|0,n=n+Math.imul(m,re)|0,i=(i=i+Math.imul(m,ne)|0)+Math.imul(v,re)|0,o=o+Math.imul(v,ne)|0,n=n+Math.imul(p,oe)|0,i=(i=i+Math.imul(p,ae)|0)+Math.imul(b,oe)|0,o=o+Math.imul(b,ae)|0;var Ee=(c+(n=n+Math.imul(h,ue)|0)|0)+((8191&(i=(i=i+Math.imul(h,ce)|0)+Math.imul(l,ue)|0))<<13)|0;c=((o=o+Math.imul(l,ce)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,n=Math.imul(N,q),i=(i=Math.imul(N,H))+Math.imul(R,q)|0,o=Math.imul(R,H),n=n+Math.imul(B,K)|0,i=(i=i+Math.imul(B,V)|0)+Math.imul(P,K)|0,o=o+Math.imul(P,V)|0,n=n+Math.imul(T,W)|0,i=(i=i+Math.imul(T,Y)|0)+Math.imul(U,W)|0,o=o+Math.imul(U,Y)|0,n=n+Math.imul(S,Z)|0,i=(i=i+Math.imul(S,J)|0)+Math.imul(M,Z)|0,o=o+Math.imul(M,J)|0,n=n+Math.imul(E,Q)|0,i=(i=i+Math.imul(E,ee)|0)+Math.imul(x,Q)|0,o=o+Math.imul(x,ee)|0,n=n+Math.imul(w,re)|0,i=(i=i+Math.imul(w,ne)|0)+Math.imul(_,re)|0,o=o+Math.imul(_,ne)|0,n=n+Math.imul(m,oe)|0,i=(i=i+Math.imul(m,ae)|0)+Math.imul(v,oe)|0,o=o+Math.imul(v,ae)|0,n=n+Math.imul(p,ue)|0,i=(i=i+Math.imul(p,ce)|0)+Math.imul(b,ue)|0,o=o+Math.imul(b,ce)|0;var xe=(c+(n=n+Math.imul(h,he)|0)|0)+((8191&(i=(i=i+Math.imul(h,le)|0)+Math.imul(l,he)|0))<<13)|0;c=((o=o+Math.imul(l,le)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,n=Math.imul(O,q),i=(i=Math.imul(O,H))+Math.imul(D,q)|0,o=Math.imul(D,H),n=n+Math.imul(N,K)|0,i=(i=i+Math.imul(N,V)|0)+Math.imul(R,K)|0,o=o+Math.imul(R,V)|0,n=n+Math.imul(B,W)|0,i=(i=i+Math.imul(B,Y)|0)+Math.imul(P,W)|0,o=o+Math.imul(P,Y)|0,n=n+Math.imul(T,Z)|0,i=(i=i+Math.imul(T,J)|0)+Math.imul(U,Z)|0,o=o+Math.imul(U,J)|0,n=n+Math.imul(S,Q)|0,i=(i=i+Math.imul(S,ee)|0)+Math.imul(M,Q)|0,o=o+Math.imul(M,ee)|0,n=n+Math.imul(E,re)|0,i=(i=i+Math.imul(E,ne)|0)+Math.imul(x,re)|0,o=o+Math.imul(x,ne)|0,n=n+Math.imul(w,oe)|0,i=(i=i+Math.imul(w,ae)|0)+Math.imul(_,oe)|0,o=o+Math.imul(_,ae)|0,n=n+Math.imul(m,ue)|0,i=(i=i+Math.imul(m,ce)|0)+Math.imul(v,ue)|0,o=o+Math.imul(v,ce)|0,n=n+Math.imul(p,he)|0,i=(i=i+Math.imul(p,le)|0)+Math.imul(b,he)|0,o=o+Math.imul(b,le)|0;var ke=(c+(n=n+Math.imul(h,pe)|0)|0)+((8191&(i=(i=i+Math.imul(h,be)|0)+Math.imul(l,pe)|0))<<13)|0;c=((o=o+Math.imul(l,be)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,n=Math.imul(O,K),i=(i=Math.imul(O,V))+Math.imul(D,K)|0,o=Math.imul(D,V),n=n+Math.imul(N,W)|0,i=(i=i+Math.imul(N,Y)|0)+Math.imul(R,W)|0,o=o+Math.imul(R,Y)|0,n=n+Math.imul(B,Z)|0,i=(i=i+Math.imul(B,J)|0)+Math.imul(P,Z)|0,o=o+Math.imul(P,J)|0,n=n+Math.imul(T,Q)|0,i=(i=i+Math.imul(T,ee)|0)+Math.imul(U,Q)|0,o=o+Math.imul(U,ee)|0,n=n+Math.imul(S,re)|0,i=(i=i+Math.imul(S,ne)|0)+Math.imul(M,re)|0,o=o+Math.imul(M,ne)|0,n=n+Math.imul(E,oe)|0,i=(i=i+Math.imul(E,ae)|0)+Math.imul(x,oe)|0,o=o+Math.imul(x,ae)|0,n=n+Math.imul(w,ue)|0,i=(i=i+Math.imul(w,ce)|0)+Math.imul(_,ue)|0,o=o+Math.imul(_,ce)|0,n=n+Math.imul(m,he)|0,i=(i=i+Math.imul(m,le)|0)+Math.imul(v,he)|0,o=o+Math.imul(v,le)|0;var Se=(c+(n=n+Math.imul(p,pe)|0)|0)+((8191&(i=(i=i+Math.imul(p,be)|0)+Math.imul(b,pe)|0))<<13)|0;c=((o=o+Math.imul(b,be)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,n=Math.imul(O,W),i=(i=Math.imul(O,Y))+Math.imul(D,W)|0,o=Math.imul(D,Y),n=n+Math.imul(N,Z)|0,i=(i=i+Math.imul(N,J)|0)+Math.imul(R,Z)|0,o=o+Math.imul(R,J)|0,n=n+Math.imul(B,Q)|0,i=(i=i+Math.imul(B,ee)|0)+Math.imul(P,Q)|0,o=o+Math.imul(P,ee)|0,n=n+Math.imul(T,re)|0,i=(i=i+Math.imul(T,ne)|0)+Math.imul(U,re)|0,o=o+Math.imul(U,ne)|0,n=n+Math.imul(S,oe)|0,i=(i=i+Math.imul(S,ae)|0)+Math.imul(M,oe)|0,o=o+Math.imul(M,ae)|0,n=n+Math.imul(E,ue)|0,i=(i=i+Math.imul(E,ce)|0)+Math.imul(x,ue)|0,o=o+Math.imul(x,ce)|0,n=n+Math.imul(w,he)|0,i=(i=i+Math.imul(w,le)|0)+Math.imul(_,he)|0,o=o+Math.imul(_,le)|0;var Me=(c+(n=n+Math.imul(m,pe)|0)|0)+((8191&(i=(i=i+Math.imul(m,be)|0)+Math.imul(v,pe)|0))<<13)|0;c=((o=o+Math.imul(v,be)|0)+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863,n=Math.imul(O,Z),i=(i=Math.imul(O,J))+Math.imul(D,Z)|0,o=Math.imul(D,J),n=n+Math.imul(N,Q)|0,i=(i=i+Math.imul(N,ee)|0)+Math.imul(R,Q)|0,o=o+Math.imul(R,ee)|0,n=n+Math.imul(B,re)|0,i=(i=i+Math.imul(B,ne)|0)+Math.imul(P,re)|0,o=o+Math.imul(P,ne)|0,n=n+Math.imul(T,oe)|0,i=(i=i+Math.imul(T,ae)|0)+Math.imul(U,oe)|0,o=o+Math.imul(U,ae)|0,n=n+Math.imul(S,ue)|0,i=(i=i+Math.imul(S,ce)|0)+Math.imul(M,ue)|0,o=o+Math.imul(M,ce)|0,n=n+Math.imul(E,he)|0,i=(i=i+Math.imul(E,le)|0)+Math.imul(x,he)|0,o=o+Math.imul(x,le)|0;var Ie=(c+(n=n+Math.imul(w,pe)|0)|0)+((8191&(i=(i=i+Math.imul(w,be)|0)+Math.imul(_,pe)|0))<<13)|0;c=((o=o+Math.imul(_,be)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,n=Math.imul(O,Q),i=(i=Math.imul(O,ee))+Math.imul(D,Q)|0,o=Math.imul(D,ee),n=n+Math.imul(N,re)|0,i=(i=i+Math.imul(N,ne)|0)+Math.imul(R,re)|0,o=o+Math.imul(R,ne)|0,n=n+Math.imul(B,oe)|0,i=(i=i+Math.imul(B,ae)|0)+Math.imul(P,oe)|0,o=o+Math.imul(P,ae)|0,n=n+Math.imul(T,ue)|0,i=(i=i+Math.imul(T,ce)|0)+Math.imul(U,ue)|0,o=o+Math.imul(U,ce)|0,n=n+Math.imul(S,he)|0,i=(i=i+Math.imul(S,le)|0)+Math.imul(M,he)|0,o=o+Math.imul(M,le)|0;var Te=(c+(n=n+Math.imul(E,pe)|0)|0)+((8191&(i=(i=i+Math.imul(E,be)|0)+Math.imul(x,pe)|0))<<13)|0;c=((o=o+Math.imul(x,be)|0)+(i>>>13)|0)+(Te>>>26)|0,Te&=67108863,n=Math.imul(O,re),i=(i=Math.imul(O,ne))+Math.imul(D,re)|0,o=Math.imul(D,ne),n=n+Math.imul(N,oe)|0,i=(i=i+Math.imul(N,ae)|0)+Math.imul(R,oe)|0,o=o+Math.imul(R,ae)|0,n=n+Math.imul(B,ue)|0,i=(i=i+Math.imul(B,ce)|0)+Math.imul(P,ue)|0,o=o+Math.imul(P,ce)|0,n=n+Math.imul(T,he)|0,i=(i=i+Math.imul(T,le)|0)+Math.imul(U,he)|0,o=o+Math.imul(U,le)|0;var Ue=(c+(n=n+Math.imul(S,pe)|0)|0)+((8191&(i=(i=i+Math.imul(S,be)|0)+Math.imul(M,pe)|0))<<13)|0;c=((o=o+Math.imul(M,be)|0)+(i>>>13)|0)+(Ue>>>26)|0,Ue&=67108863,n=Math.imul(O,oe),i=(i=Math.imul(O,ae))+Math.imul(D,oe)|0,o=Math.imul(D,ae),n=n+Math.imul(N,ue)|0,i=(i=i+Math.imul(N,ce)|0)+Math.imul(R,ue)|0,o=o+Math.imul(R,ce)|0,n=n+Math.imul(B,he)|0,i=(i=i+Math.imul(B,le)|0)+Math.imul(P,he)|0,o=o+Math.imul(P,le)|0;var je=(c+(n=n+Math.imul(T,pe)|0)|0)+((8191&(i=(i=i+Math.imul(T,be)|0)+Math.imul(U,pe)|0))<<13)|0;c=((o=o+Math.imul(U,be)|0)+(i>>>13)|0)+(je>>>26)|0,je&=67108863,n=Math.imul(O,ue),i=(i=Math.imul(O,ce))+Math.imul(D,ue)|0,o=Math.imul(D,ce),n=n+Math.imul(N,he)|0,i=(i=i+Math.imul(N,le)|0)+Math.imul(R,he)|0,o=o+Math.imul(R,le)|0;var Be=(c+(n=n+Math.imul(B,pe)|0)|0)+((8191&(i=(i=i+Math.imul(B,be)|0)+Math.imul(P,pe)|0))<<13)|0;c=((o=o+Math.imul(P,be)|0)+(i>>>13)|0)+(Be>>>26)|0,Be&=67108863,n=Math.imul(O,he),i=(i=Math.imul(O,le))+Math.imul(D,he)|0,o=Math.imul(D,le);var Pe=(c+(n=n+Math.imul(N,pe)|0)|0)+((8191&(i=(i=i+Math.imul(N,be)|0)+Math.imul(R,pe)|0))<<13)|0;c=((o=o+Math.imul(R,be)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863;var Ce=(c+(n=Math.imul(O,pe))|0)+((8191&(i=(i=Math.imul(O,be))+Math.imul(D,pe)|0))<<13)|0;return c=((o=Math.imul(D,be))+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,u[0]=ye,u[1]=me,u[2]=ve,u[3]=ge,u[4]=we,u[5]=_e,u[6]=Ae,u[7]=Ee,u[8]=xe,u[9]=ke,u[10]=Se,u[11]=Me,u[12]=Ie,u[13]=Te,u[14]=Ue,u[15]=je,u[16]=Be,u[17]=Pe,u[18]=Ce,0!==c&&(u[19]=c,r.length++),r};function p(e,t,r){return(new b).mulp(e,t,r)}function b(e,t){this.x=e,this.y=t}Math.imul||(d=l),o.prototype.mulTo=function(e,t){var r=this.length+e.length;return 10===this.length&&10===e.length?d(this,e,t):r<63?l(this,e,t):r<1024?function(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,a&=67108863}r.words[o]=s,n=a,a=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,e,t):p(this,e,t)},b.prototype.makeRBT=function(e){for(var t=new Array(e),r=o.prototype._countBits(e)-1,n=0;n>=1;return n},b.prototype.permute=function(e,t,r,n,i,o){for(var a=0;a>>=1)i++;return 1<>>=13,r[2*a+1]=8191&o,o>>>=13;for(a=2*t;a>=26,t+=i/67108864|0,t+=o>>>26,this.words[r]=67108863&o}return 0!==t&&(this.words[r]=t,this.length++),this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),r=0;r>>i}return t}(e);if(0===t.length)return new o(1);for(var r=this,n=0;n=0);var t,r=e%26,i=(e-r)/26,o=67108863>>>26-r<<26-r;if(0!==r){var a=0;for(t=0;t>>26-r}a&&(this.words[t]=a,this.length++)}if(0!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t=0),i=t?(t-t%26)/26:0;var o=e%26,a=Math.min((e-o)/26,this.length),s=67108863^67108863>>>o<a)for(this.length-=a,c=0;c=0&&(0!==f||c>=i);c--){var h=0|this.words[c];this.words[c]=f<<26-o|h>>>o,f=h&s}return u&&0!==f&&(u.words[u.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},o.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,i=1<=0);var t=e%26,r=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var i=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(u/67108864|0),this.words[i+r]=67108863&o}for(;i>26,this.words[i+r]=67108863&o;if(0===s)return this.strip();for(n(-1===s),s=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},o.prototype._wordDiv=function(e,t){var r=(this.length,e.length),n=this.clone(),i=e,a=0|i.words[i.length-1];0!==(r=26-this._countBits(a))&&(i=i.ushln(r),n.iushln(r),a=0|i.words[i.length-1]);var s,u=n.length-i.length;if("mod"!==t){(s=new o(null)).length=u+1,s.words=new Array(s.length);for(var c=0;c=0;h--){var l=67108864*(0|n.words[i.length+h])+(0|n.words[i.length+h-1]);for(l=Math.min(l/a|0,67108863),n._ishlnsubmul(i,l,h);0!==n.negative;)l--,n.negative=0,n._ishlnsubmul(i,1,h),n.isZero()||(n.negative^=1);s&&(s.words[h]=l)}return s&&s.strip(),n.strip(),"div"!==t&&0!==r&&n.iushrn(r),{div:s||null,mod:n}},o.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(s=this.neg().divmod(e,t),"mod"!==t&&(i=s.div.neg()),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.iadd(e)),{div:i,mod:a}):0===this.negative&&0!==e.negative?(s=this.divmod(e.neg(),t),"mod"!==t&&(i=s.div.neg()),{div:i,mod:s.mod}):0!=(this.negative&e.negative)?(s=this.neg().divmod(e.neg(),t),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.isub(e)),{div:s.div,mod:a}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modn(e.words[0]))}:this._wordDiv(e,t);var i,a,s},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=0!==t.div.negative?t.mod.isub(e):t.mod,n=e.ushrn(1),i=e.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modn=function(e){n(e<=67108863);for(var t=(1<<26)%e,r=0,i=this.length-1;i>=0;i--)r=(t*r+(0|this.words[i]))%e;return r},o.prototype.idivn=function(e){n(e<=67108863);for(var t=0,r=this.length-1;r>=0;r--){var i=(0|this.words[r])+67108864*t;this.words[r]=i/e|0,t=i%e}return this.strip()},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new o(1),a=new o(0),s=new o(0),u=new o(1),c=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++c;for(var f=r.clone(),h=t.clone();!t.isZero();){for(var l=0,d=1;0==(t.words[0]&d)&&l<26;++l,d<<=1);if(l>0)for(t.iushrn(l);l-- >0;)(i.isOdd()||a.isOdd())&&(i.iadd(f),a.isub(h)),i.iushrn(1),a.iushrn(1);for(var p=0,b=1;0==(r.words[0]&b)&&p<26;++p,b<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(s.isOdd()||u.isOdd())&&(s.iadd(f),u.isub(h)),s.iushrn(1),u.iushrn(1);t.cmp(r)>=0?(t.isub(r),i.isub(s),a.isub(u)):(r.isub(t),s.isub(i),u.isub(a))}return{a:s,b:u,gcd:r.iushln(c)}},o.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,a=new o(1),s=new o(0),u=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var c=0,f=1;0==(t.words[0]&f)&&c<26;++c,f<<=1);if(c>0)for(t.iushrn(c);c-- >0;)a.isOdd()&&a.iadd(u),a.iushrn(1);for(var h=0,l=1;0==(r.words[0]&l)&&h<26;++h,l<<=1);if(h>0)for(r.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(u),s.iushrn(1);t.cmp(r)>=0?(t.isub(r),a.isub(s)):(r.isub(t),s.isub(a))}return(i=0===t.cmpn(1)?a:s).cmpn(0)<0&&i.iadd(e),i},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var n=0;t.isEven()&&r.isEven();n++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=t.cmp(r);if(i<0){var o=t;t=r,r=o}else if(0===i||0===r.cmpn(1))break;t.isub(r)}return r.iushln(n)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return 0==(1&this.words[0])},o.prototype.isOdd=function(){return 1==(1&this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,i=1<>>26,s&=67108863,this.words[a]=s}return 0!==o&&(this.words[a]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this.strip(),this.length>1)t=1;else{r&&(e=-e),n(e<=67108863,"Number is too big");var i=0|this.words[0];t=i===e?0:ie.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|e.words[r];if(n!==i){ni&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new A(e)},o.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var y={k256:null,p224:null,p192:null,p25519:null};function m(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function v(){m.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function g(){m.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function w(){m.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function _(){m.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function A(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function E(e){A.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(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)}m.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},m.prototype.ireduce=function(e){var t,r=e;do{this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(t>this.n);var n=t0?r.isub(this.p):r.strip(),r},m.prototype.split=function(e,t){e.iushrn(this.n,0,t)},m.prototype.imulK=function(e){return e.imul(this.k)},i(v,m),v.prototype.split=function(e,t){for(var r=Math.min(e.length,9),n=0;n>>22,i=o}i>>>=22,e.words[n-10]=i,0===i&&e.length>10?e.length-=10:e.length-=9},v.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r>>=26,e.words[r]=i,t=n}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(y[e])return y[e];var t;if("k256"===e)t=new v;else if("p224"===e)t=new g;else if("p192"===e)t=new w;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new _}return y[e]=t,t},A.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},A.prototype._verify2=function(e,t){n(0==(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},A.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},A.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},A.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},A.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},A.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},A.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},A.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},A.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},A.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},A.prototype.isqr=function(e){return this.imul(e,e.clone())},A.prototype.sqr=function(e){return this.mul(e,e)},A.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var r=this.m.add(new o(1)).iushrn(2);return this.pow(e,r)}for(var i=this.m.subn(1),a=0;!i.isZero()&&0===i.andln(1);)a++,i.iushrn(1);n(!i.isZero());var s=new o(1).toRed(this),u=s.redNeg(),c=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new o(2*f*f).toRed(this);0!==this.pow(f,c).cmp(u);)f.redIAdd(u);for(var h=this.pow(f,i),l=this.pow(e,i.addn(1).iushrn(1)),d=this.pow(e,i),p=a;0!==d.cmp(s);){for(var b=d,y=0;0!==b.cmp(s);y++)b=b.redSqr();n(y=0;n--){for(var c=t.words[n],f=u-1;f>=0;f--){var h=c>>f&1;i!==r[0]&&(i=this.sqr(i)),0!==h||0!==a?(a<<=1,a|=h,(4===++s||0===n&&0===f)&&(i=this.mul(i,r[a]),s=0,a=0)):s=0}u=26}return i},A.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},A.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new E(e)},i(E,A),E.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},E.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},E.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},E.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var r=e.mul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},E.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===t||t,this)},{buffer:55}],54:[function(e,t,r){var n;function i(e){this.rand=e}if(t.exports=function(e){return n||(n=new i(null)),n.generate(e)},t.exports.Rand=i,i.prototype.generate=function(e){return this._rand(e)},i.prototype._rand=function(e){if(this.rand.getBytes)return this.rand.getBytes(e);for(var t=new Uint8Array(e),r=0;r>>24]^f[p>>>16&255]^h[b>>>8&255]^l[255&y]^t[m++],a=c[p>>>24]^f[b>>>16&255]^h[y>>>8&255]^l[255&d]^t[m++],s=c[b>>>24]^f[y>>>16&255]^h[d>>>8&255]^l[255&p]^t[m++],u=c[y>>>24]^f[d>>>16&255]^h[p>>>8&255]^l[255&b]^t[m++],d=o,p=a,b=s,y=u;return o=(n[d>>>24]<<24|n[p>>>16&255]<<16|n[b>>>8&255]<<8|n[255&y])^t[m++],a=(n[p>>>24]<<24|n[b>>>16&255]<<16|n[y>>>8&255]<<8|n[255&d])^t[m++],s=(n[b>>>24]<<24|n[y>>>16&255]<<16|n[d>>>8&255]<<8|n[255&p])^t[m++],u=(n[y>>>24]<<24|n[d>>>16&255]<<16|n[p>>>8&255]<<8|n[255&b])^t[m++],[o>>>=0,a>>>=0,s>>>=0,u>>>=0]}var s=[0,1,2,4,8,16,32,64,128,27,54],u=function(){for(var e=new Array(256),t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;for(var r=[],n=[],i=[[],[],[],[]],o=[[],[],[],[]],a=0,s=0,u=0;u<256;++u){var c=s^s<<1^s<<2^s<<3^s<<4;c=c>>>8^255&c^99,r[a]=c,n[c]=a;var f=e[a],h=e[f],l=e[h],d=257*e[c]^16843008*c;i[0][a]=d<<24|d>>>8,i[1][a]=d<<16|d>>>16,i[2][a]=d<<8|d>>>24,i[3][a]=d,d=16843009*l^65537*h^257*f^16843008*a,o[0][c]=d<<24|d>>>8,o[1][c]=d<<16|d>>>16,o[2][c]=d<<8|d>>>24,o[3][c]=d,0===a?a=s=1:(a=f^e[e[e[l^f]]],s^=e[e[s]])}return{SBOX:r,INV_SBOX:n,SUB_MIX:i,INV_SUB_MIX:o}}();function c(e){this._key=i(e),this._reset()}c.blockSize=16,c.keySize=32,c.prototype.blockSize=c.blockSize,c.prototype.keySize=c.keySize,c.prototype._reset=function(){for(var e=this._key,t=e.length,r=t+6,n=4*(r+1),i=[],o=0;o>>24,a=u.SBOX[a>>>24]<<24|u.SBOX[a>>>16&255]<<16|u.SBOX[a>>>8&255]<<8|u.SBOX[255&a],a^=s[o/t|0]<<24):t>6&&o%t==4&&(a=u.SBOX[a>>>24]<<24|u.SBOX[a>>>16&255]<<16|u.SBOX[a>>>8&255]<<8|u.SBOX[255&a]),i[o]=i[o-t]^a}for(var c=[],f=0;f>>24]]^u.INV_SUB_MIX[1][u.SBOX[l>>>16&255]]^u.INV_SUB_MIX[2][u.SBOX[l>>>8&255]]^u.INV_SUB_MIX[3][u.SBOX[255&l]]}this._nRounds=r,this._keySchedule=i,this._invKeySchedule=c},c.prototype.encryptBlockRaw=function(e){return a(e=i(e),this._keySchedule,u.SUB_MIX,u.SBOX,this._nRounds)},c.prototype.encryptBlock=function(e){var t=this.encryptBlockRaw(e),r=n.allocUnsafe(16);return r.writeUInt32BE(t[0],0),r.writeUInt32BE(t[1],4),r.writeUInt32BE(t[2],8),r.writeUInt32BE(t[3],12),r},c.prototype.decryptBlock=function(e){var t=(e=i(e))[1];e[1]=e[3],e[3]=t;var r=a(e,this._invKeySchedule,u.INV_SUB_MIX,u.INV_SBOX,this._nRounds),o=n.allocUnsafe(16);return o.writeUInt32BE(r[0],0),o.writeUInt32BE(r[3],4),o.writeUInt32BE(r[2],8),o.writeUInt32BE(r[1],12),o},c.prototype.scrub=function(){o(this._keySchedule),o(this._invKeySchedule),o(this._key)},t.exports.AES=c},{"safe-buffer":290}],57:[function(e,t,r){var n=e("./aes"),i=e("safe-buffer").Buffer,o=e("cipher-base"),a=e("inherits"),s=e("./ghash"),u=e("buffer-xor"),c=e("./incr32");function f(e,t,r,a){o.call(this);var u=i.alloc(4,0);this._cipher=new n.AES(t);var f=this._cipher.encryptBlock(u);this._ghash=new s(f),r=function(e,t,r){if(12===t.length)return e._finID=i.concat([t,i.from([0,0,0,1])]),i.concat([t,i.from([0,0,0,2])]);var n=new s(r),o=t.length,a=o%16;n.update(t),a&&(a=16-a,n.update(i.alloc(a,0))),n.update(i.alloc(8,0));var u=8*o,f=i.alloc(8);f.writeUIntBE(u,0,8),n.update(f),e._finID=n.state;var h=i.from(e._finID);return c(h),h}(this,r,f),this._prev=i.from(r),this._cache=i.allocUnsafe(0),this._secCache=i.allocUnsafe(0),this._decrypt=a,this._alen=0,this._len=0,this._mode=e,this._authTag=null,this._called=!1}a(f,o),f.prototype._update=function(e){if(!this._called&&this._alen){var t=16-this._alen%16;t<16&&(t=i.alloc(t,0),this._ghash.update(t))}this._called=!0;var r=this._mode.encrypt(this,e);return this._decrypt?this._ghash.update(e):this._ghash.update(r),this._len+=e.length,r},f.prototype._final=function(){if(this._decrypt&&!this._authTag)throw new Error("Unsupported state or unable to authenticate data");var e=u(this._ghash.final(8*this._alen,8*this._len),this._cipher.encryptBlock(this._finID));if(this._decrypt&&function(e,t){var r=0;e.length!==t.length&&r++;for(var n=Math.min(e.length,t.length),i=0;i16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t}else if(this.cache.length>=16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t;return null},h.prototype.flush=function(){if(this.cache.length)return this.cache},r.createDecipher=function(e,t){var r=o[e.toLowerCase()];if(!r)throw new TypeError("invalid suite type");var n=c(t,!1,r.key,r.iv);return l(e,n.key,n.iv)},r.createDecipheriv=l},{"./aes":56,"./authCipher":57,"./modes":69,"./streamCipher":72,"cipher-base":86,evp_bytestokey:158,inherits:180,"safe-buffer":290}],60:[function(e,t,r){var n=e("./modes"),i=e("./authCipher"),o=e("safe-buffer").Buffer,a=e("./streamCipher"),s=e("cipher-base"),u=e("./aes"),c=e("evp_bytestokey");function f(e,t,r){s.call(this),this._cache=new l,this._cipher=new u.AES(t),this._prev=o.from(r),this._mode=e,this._autopadding=!0}e("inherits")(f,s),f.prototype._update=function(e){var t,r;this._cache.add(e);for(var n=[];t=this._cache.get();)r=this._mode.encrypt(this,t),n.push(r);return o.concat(n)};var h=o.alloc(16,16);function l(){this.cache=o.allocUnsafe(0)}function d(e,t,r){var s=n[e.toLowerCase()];if(!s)throw new TypeError("invalid suite type");if("string"==typeof t&&(t=o.from(t)),t.length!==s.key/8)throw new TypeError("invalid key length "+t.length);if("string"==typeof r&&(r=o.from(r)),"GCM"!==s.mode&&r.length!==s.iv)throw new TypeError("invalid iv length "+r.length);return"stream"===s.type?new a(s.module,t,r):"auth"===s.type?new i(s.module,t,r):new f(s.module,t,r)}f.prototype._final=function(){var e=this._cache.flush();if(this._autopadding)return e=this._mode.encrypt(this,e),this._cipher.scrub(),e;if(!e.equals(h))throw this._cipher.scrub(),new Error("data not multiple of block length")},f.prototype.setAutoPadding=function(e){return this._autopadding=!!e,this},l.prototype.add=function(e){this.cache=o.concat([this.cache,e])},l.prototype.get=function(){if(this.cache.length>15){var e=this.cache.slice(0,16);return this.cache=this.cache.slice(16),e}return null},l.prototype.flush=function(){for(var e=16-this.cache.length,t=o.allocUnsafe(e),r=-1;++r>>0,0),t.writeUInt32BE(e[1]>>>0,4),t.writeUInt32BE(e[2]>>>0,8),t.writeUInt32BE(e[3]>>>0,12),t}function a(e){this.h=e,this.state=n.alloc(16,0),this.cache=n.allocUnsafe(0)}a.prototype.ghash=function(e){for(var t=-1;++t0;t--)n[t]=n[t]>>>1|(1&n[t-1])<<31;n[0]=n[0]>>>1,r&&(n[0]=n[0]^225<<24)}this.state=o(i)},a.prototype.update=function(e){var t;for(this.cache=n.concat([this.cache,e]);this.cache.length>=16;)t=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(t)},a.prototype.final=function(e,t){return this.cache.length&&this.ghash(n.concat([this.cache,i],16)),this.ghash(o([0,e,0,t])),this.state},t.exports=a},{"safe-buffer":290}],62:[function(e,t,r){t.exports=function(e){for(var t,r=e.length;r--;){if(255!==(t=e.readUInt8(r))){t++,e.writeUInt8(t,r);break}e.writeUInt8(0,r)}}},{}],63:[function(e,t,r){var n=e("buffer-xor");r.encrypt=function(e,t){var r=n(t,e._prev);return e._prev=e._cipher.encryptBlock(r),e._prev},r.decrypt=function(e,t){var r=e._prev;e._prev=t;var i=e._cipher.decryptBlock(t);return n(i,r)}},{"buffer-xor":83}],64:[function(e,t,r){var n=e("safe-buffer").Buffer,i=e("buffer-xor");function o(e,t,r){var o=t.length,a=i(t,e._cache);return e._cache=e._cache.slice(o),e._prev=n.concat([e._prev,r?t:a]),a}r.encrypt=function(e,t,r){for(var i,a=n.allocUnsafe(0);t.length;){if(0===e._cache.length&&(e._cache=e._cipher.encryptBlock(e._prev),e._prev=n.allocUnsafe(0)),!(e._cache.length<=t.length)){a=n.concat([a,o(e,t,r)]);break}i=e._cache.length,a=n.concat([a,o(e,t.slice(0,i),r)]),t=t.slice(i)}return a}},{"buffer-xor":83,"safe-buffer":290}],65:[function(e,t,r){var n=e("safe-buffer").Buffer;function i(e,t,r){for(var n,i,a=-1,s=0;++a<8;)n=t&1<<7-a?128:0,s+=(128&(i=e._cipher.encryptBlock(e._prev)[0]^n))>>a%8,e._prev=o(e._prev,r?n:i);return s}function o(e,t){var r=e.length,i=-1,o=n.allocUnsafe(e.length);for(e=n.concat([e,n.from([t])]);++i>7;return o}r.encrypt=function(e,t,r){for(var o=t.length,a=n.allocUnsafe(o),s=-1;++s=0||!r.umod(e.prime1)||!r.umod(e.prime2);)r=new n(i(t));return r}t.exports=o,o.getr=a}).call(this,e("buffer").Buffer)},{"bn.js":53,buffer:84,randombytes:270}],77:[function(e,t,r){t.exports=e("./browser/algorithms.json")},{"./browser/algorithms.json":78}],78:[function(e,t,r){t.exports={sha224WithRSAEncryption:{sign:"rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},"RSA-SHA224":{sign:"ecdsa/rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},sha256WithRSAEncryption:{sign:"rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},"RSA-SHA256":{sign:"ecdsa/rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},sha384WithRSAEncryption:{sign:"rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},"RSA-SHA384":{sign:"ecdsa/rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},sha512WithRSAEncryption:{sign:"rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA512":{sign:"ecdsa/rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA1":{sign:"rsa",hash:"sha1",id:"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{sign:"ecdsa",hash:"sha1",id:""},sha256:{sign:"ecdsa",hash:"sha256",id:""},sha224:{sign:"ecdsa",hash:"sha224",id:""},sha384:{sign:"ecdsa",hash:"sha384",id:""},sha512:{sign:"ecdsa",hash:"sha512",id:""},"DSA-SHA":{sign:"dsa",hash:"sha1",id:""},"DSA-SHA1":{sign:"dsa",hash:"sha1",id:""},DSA:{sign:"dsa",hash:"sha1",id:""},"DSA-WITH-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-WITH-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-WITH-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-WITH-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-RIPEMD160":{sign:"dsa",hash:"rmd160",id:""},ripemd160WithRSA:{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},"RSA-RIPEMD160":{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},md5WithRSAEncryption:{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"},"RSA-MD5":{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"}}},{}],79:[function(e,t,r){t.exports={"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"}},{}],80:[function(e,t,r){(function(r){var n=e("create-hash"),i=e("stream"),o=e("inherits"),a=e("./sign"),s=e("./verify"),u=e("./algorithms.json");function c(e){i.Writable.call(this);var t=u[e];if(!t)throw new Error("Unknown message digest");this._hashType=t.hash,this._hash=n(t.hash),this._tag=t.id,this._signType=t.sign}function f(e){i.Writable.call(this);var t=u[e];if(!t)throw new Error("Unknown message digest");this._hash=n(t.hash),this._tag=t.id,this._signType=t.sign}function h(e){return new c(e)}function l(e){return new f(e)}Object.keys(u).forEach(function(e){u[e].id=new r(u[e].id,"hex"),u[e.toLowerCase()]=u[e]}),o(c,i.Writable),c.prototype._write=function(e,t,r){this._hash.update(e),r()},c.prototype.update=function(e,t){return"string"==typeof e&&(e=new r(e,t)),this._hash.update(e),this},c.prototype.sign=function(e,t){this.end();var r=this._hash.digest(),n=a(r,e,this._hashType,this._signType,this._tag);return t?n.toString(t):n},o(f,i.Writable),f.prototype._write=function(e,t,r){this._hash.update(e),r()},f.prototype.update=function(e,t){return"string"==typeof e&&(e=new r(e,t)),this._hash.update(e),this},f.prototype.verify=function(e,t,n){"string"==typeof t&&(t=new r(t,n)),this.end();var i=this._hash.digest();return s(t,i,e,this._signType,this._tag)},t.exports={Sign:h,Verify:l,createSign:h,createVerify:l}}).call(this,e("buffer").Buffer)},{"./algorithms.json":78,"./sign":81,"./verify":82,buffer:84,"create-hash":91,inherits:180,stream:311}],81:[function(e,t,r){(function(r){var n=e("create-hmac"),i=e("browserify-rsa"),o=e("elliptic").ec,a=e("bn.js"),s=e("parse-asn1"),u=e("./curves.json");function c(e,t,i,o){if((e=new r(e.toArray())).length0&&r.ishrn(n),r}function h(e,t,i){var o,a;do{for(o=new r(0);8*o.length=t)throw new Error("invalid sig")}t.exports=function(e,t,u,c,f){var h=o(u);if("ec"===h.type){if("ecdsa"!==c&&"ecdsa/rsa"!==c)throw new Error("wrong public key type");return function(e,t,r){var n=a[r.data.algorithm.curve.join(".")];if(!n)throw new Error("unknown curve "+r.data.algorithm.curve.join("."));var o=new i(n),s=r.data.subjectPrivateKey.data;return o.verify(t,e,s)}(e,t,h)}if("dsa"===h.type){if("dsa"!==c)throw new Error("wrong public key type");return function(e,t,r){var i=r.data.p,a=r.data.q,u=r.data.g,c=r.data.pub_key,f=o.signature.decode(e,"der"),h=f.s,l=f.r;s(h,a),s(l,a);var d=n.mont(i),p=h.invm(a);return 0===u.toRed(d).redPow(new n(t).mul(p).mod(a)).fromRed().mul(c.toRed(d).redPow(l.mul(p).mod(a)).fromRed()).mod(i).mod(a).cmp(l)}(e,t,h)}if("rsa"!==c&&"ecdsa/rsa"!==c)throw new Error("wrong public key type");t=r.concat([f,t]);for(var l=h.modulus.byteLength(),d=[1],p=0;t.length+d.length+2o)throw new RangeError("Invalid typed array length");var t=new Uint8Array(e);return t.__proto__=s.prototype,t}function s(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return f(e)}return u(e,t,r)}function u(e,t,r){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return F(e)?function(e,t,r){if(t<0||e.byteLength=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function d(e,t){if(s.isBuffer(e))return e.length;if(q(e)||F(e))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return L(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return O(e).length;default:if(n)return L(e).length;t=(""+t).toLowerCase(),n=!0}}function p(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function b(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),H(r=+r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=s.from(t,n)),s.isBuffer(t))return 0===t.length?-1:y(e,t,r,n,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):y(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function y(e,t,r,n,i){var o,a=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,r/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(i){var f=-1;for(o=r;os&&(r=s-u),o=r;o>=0;o--){for(var h=!0,l=0;li&&(n=i):n=i;var o=t.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var a=0;a>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function E(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function x(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i239?4:c>223?3:c>191?2:1;if(i+h<=r)switch(h){case 1:c<128&&(f=c);break;case 2:128==(192&(o=e[i+1]))&&(u=(31&c)<<6|63&o)>127&&(f=u);break;case 3:o=e[i+1],a=e[i+2],128==(192&o)&&128==(192&a)&&(u=(15&c)<<12|(63&o)<<6|63&a)>2047&&(u<55296||u>57343)&&(f=u);break;case 4:o=e[i+1],a=e[i+2],s=e[i+3],128==(192&o)&&128==(192&a)&&128==(192&s)&&(u=(15&c)<<18|(63&o)<<12|(63&a)<<6|63&s)>65535&&u<1114112&&(f=u)}null===f?(f=65533,h=1):f>65535&&(f-=65536,n.push(f>>>10&1023|55296),f=56320|1023&f),n.push(f),i+=h}return function(e){var t=e.length;if(t<=k)return String.fromCharCode.apply(String,e);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return I(this,t,r);case"utf8":case"utf-8":return x(this,t,r);case"ascii":return S(this,t,r);case"latin1":case"binary":return M(this,t,r);case"base64":return E(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}.apply(this,arguments)},s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.prototype.inspect=function(){var e="",t=r.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},s.prototype.compare=function(e,t,r,n,i){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;for(var o=(i>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0),u=Math.min(o,a),c=this.slice(n,i),f=e.slice(t,r),h=0;h>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return m(this,e,t,r);case"utf8":case"utf-8":return v(this,e,t,r);case"ascii":return g(this,e,t,r);case"latin1":case"binary":return w(this,e,t,r);case"base64":return _(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var k=4096;function S(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;in)&&(r=n);for(var i="",o=t;or)throw new RangeError("Trying to access beyond buffer length")}function j(e,t,r,n,i,o){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function B(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function P(e,t,r,n,o){return t=+t,r>>>=0,o||B(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function C(e,t,r,n,o){return t=+t,r>>>=0,o||B(e,0,r,8),i.write(e,t,r,n,52,8),r+8}s.prototype.slice=function(e,t){var r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||U(e,t,this.length);for(var n=this[e],i=1,o=0;++o>>=0,t>>>=0,r||U(e,t,this.length);for(var n=this[e+--t],i=1;t>0&&(i*=256);)n+=this[e+--t]*i;return n},s.prototype.readUInt8=function(e,t){return e>>>=0,t||U(e,1,this.length),this[e]},s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||U(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||U(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||U(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||U(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);for(var n=this[e],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*t)),n},s.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);for(var n=t,i=1,o=this[e+--n];n>0&&(i*=256);)o+=this[e+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*t)),o},s.prototype.readInt8=function(e,t){return e>>>=0,t||U(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||U(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt16BE=function(e,t){e>>>=0,t||U(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||U(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||U(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readFloatLE=function(e,t){return e>>>=0,t||U(e,4,this.length),i.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||U(e,4,this.length),i.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||U(e,8,this.length),i.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||U(e,8,this.length),i.read(this,e,!1,52,8)},s.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t>>>=0,r>>>=0,n)||j(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[t]=255&e;++o>>=0,r>>>=0,n)||j(this,e,t,r,Math.pow(2,8*r)-1,0);var i=r-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r},s.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);j(this,e,t,r,i-1,-i)}var o=0,a=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+r},s.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);j(this,e,t,r,i-1,-i)}var o=r-1,a=1,s=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a>>0)-s&255;return t+r},s.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeFloatLE=function(e,t,r){return P(this,e,t,!0,r)},s.prototype.writeFloatBE=function(e,t,r){return P(this,e,t,!1,r)},s.prototype.writeDoubleLE=function(e,t,r){return C(this,e,t,!0,r)},s.prototype.writeDoubleBE=function(e,t,r){return C(this,e,t,!1,r)},s.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--i)e[i+t]=this[i+r];else if(o<1e3)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function O(e){return n.toByteArray(function(e){if((e=e.trim().replace(N,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function D(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function F(e){return e instanceof ArrayBuffer||null!=e&&null!=e.constructor&&"ArrayBuffer"===e.constructor.name&&"number"==typeof e.byteLength}function q(e){return"function"==typeof ArrayBuffer.isView&&ArrayBuffer.isView(e)}function H(e){return e!=e}},{"base64-js":51,ieee754:178}],85:[function(e,t,r){t.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}},{}],86:[function(e,t,r){var n=e("safe-buffer").Buffer,i=e("stream").Transform,o=e("string_decoder").StringDecoder;function a(e){i.call(this),this.hashMode="string"==typeof e,this.hashMode?this[e]=this._finalOrDigest:this.final=this._finalOrDigest,this._final&&(this.__final=this._final,this._final=null),this._decoder=null,this._encoding=null}e("inherits")(a,i),a.prototype.update=function(e,t,r){"string"==typeof e&&(e=n.from(e,t));var i=this._update(e);return this.hashMode?this:(r&&(i=this._toString(i,r)),i)},a.prototype.setAutoPadding=function(){},a.prototype.getAuthTag=function(){throw new Error("trying to get auth tag in unsupported state")},a.prototype.setAuthTag=function(){throw new Error("trying to set auth tag in unsupported state")},a.prototype.setAAD=function(){throw new Error("trying to set aad in unsupported state")},a.prototype._transform=function(e,t,r){var n;try{this.hashMode?this._update(e):this.push(this._update(e))}catch(e){n=e}finally{r(n)}},a.prototype._flush=function(e){var t;try{this.push(this.__final())}catch(e){t=e}e(t)},a.prototype._finalOrDigest=function(e){var t=this.__final()||n.alloc(0);return e&&(t=this._toString(t,e,!0)),t},a.prototype._toString=function(e,t,r){if(this._decoder||(this._decoder=new o(t),this._encoding=t),this._encoding!==t)throw new Error("can't switch encodings");var n=this._decoder.write(e);return r&&(n+=this._decoder.end()),n},t.exports=a},{inherits:180,"safe-buffer":290,stream:311,string_decoder:317}],87:[function(e,t,r){(function(e){var r=function(){"use strict";function t(e,t){return null!=t&&e instanceof t}var r,n,i;try{r=Map}catch(e){r=function(){}}try{n=Set}catch(e){n=function(){}}try{i=Promise}catch(e){i=function(){}}function o(a,u,c,f,h){"object"==typeof u&&(c=u.depth,f=u.prototype,h=u.includeNonEnumerable,u=u.circular);var l=[],d=[],p=void 0!==e;return void 0===u&&(u=!0),void 0===c&&(c=1/0),function a(c,b){if(null===c)return null;if(0===b)return c;var y,m;if("object"!=typeof c)return c;if(t(c,r))y=new r;else if(t(c,n))y=new n;else if(t(c,i))y=new i(function(e,t){c.then(function(t){e(a(t,b-1))},function(e){t(a(e,b-1))})});else if(o.__isArray(c))y=[];else if(o.__isRegExp(c))y=new RegExp(c.source,s(c)),c.lastIndex&&(y.lastIndex=c.lastIndex);else if(o.__isDate(c))y=new Date(c.getTime());else{if(p&&e.isBuffer(c))return y=e.allocUnsafe?e.allocUnsafe(c.length):new e(c.length),c.copy(y),y;t(c,Error)?y=Object.create(c):void 0===f?(m=Object.getPrototypeOf(c),y=Object.create(m)):(y=Object.create(f),m=f)}if(u){var v=l.indexOf(c);if(-1!=v)return d[v];l.push(c),d.push(y)}for(var g in t(c,r)&&c.forEach(function(e,t){var r=a(t,b-1),n=a(e,b-1);y.set(r,n)}),t(c,n)&&c.forEach(function(e){var t=a(e,b-1);y.add(t)}),c){var w;m&&(w=Object.getOwnPropertyDescriptor(m,g)),w&&null==w.set||(y[g]=a(c[g],b-1))}if(Object.getOwnPropertySymbols){var _=Object.getOwnPropertySymbols(c);for(g=0;g<_.length;g++){var A=_[g];(!(x=Object.getOwnPropertyDescriptor(c,A))||x.enumerable||h)&&(y[A]=a(c[A],b-1),x.enumerable||Object.defineProperty(y,A,{enumerable:!1}))}}if(h){var E=Object.getOwnPropertyNames(c);for(g=0;g>>2),a=0,s=0;a>5]|=128<>>9<<4)]=t;for(var r=1732584193,n=-271733879,i=-1732584194,o=271733878,h=0;h>>32-s,r);var a,s}function a(e,t,r,n,i,a,s){return o(t&r|~t&n,e,t,i,a,s)}function s(e,t,r,n,i,a,s){return o(t&n|r&~n,e,t,i,a,s)}function u(e,t,r,n,i,a,s){return o(t^r^n,e,t,i,a,s)}function c(e,t,r,n,i,a,s){return o(r^(t|~n),e,t,i,a,s)}function f(e,t){var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}t.exports=function(e){return n(e,i)}},{"./make-hash":92}],94:[function(e,t,r){"use strict";var n=e("inherits"),i=e("./legacy"),o=e("cipher-base"),a=e("safe-buffer").Buffer,s=e("create-hash/md5"),u=e("ripemd160"),c=e("sha.js"),f=a.alloc(128);function h(e,t){o.call(this,"digest"),"string"==typeof t&&(t=a.from(t));var r="sha512"===e||"sha384"===e?128:64;(this._alg=e,this._key=t,t.length>r)?t=("rmd160"===e?new u:c(e)).update(t).digest():t.lengths?t=e(t):t.length-1};f.prototype.append=function(e,t){e=s(e),t=u(t);var r=this.map[e];this.map[e]=r?r+","+t:t},f.prototype.delete=function(e){delete this.map[s(e)]},f.prototype.get=function(e){return e=s(e),this.has(e)?this.map[e]:null},f.prototype.has=function(e){return this.map.hasOwnProperty(s(e))},f.prototype.set=function(e,t){this.map[s(e)]=u(t)},f.prototype.forEach=function(e,t){for(var r in this.map)this.map.hasOwnProperty(r)&&e.call(t,this.map[r],r,this)},f.prototype.keys=function(){var e=[];return this.forEach(function(t,r){e.push(r)}),c(e)},f.prototype.values=function(){var e=[];return this.forEach(function(t){e.push(t)}),c(e)},f.prototype.entries=function(){var e=[];return this.forEach(function(t,r){e.push([r,t])}),c(e)},t.iterable&&(f.prototype[Symbol.iterator]=f.prototype.entries);var o=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];y.prototype.clone=function(){return new y(this,{body:this._bodyInit})},b.call(y.prototype),b.call(v.prototype),v.prototype.clone=function(){return new v(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new f(this.headers),url:this.url})},v.error=function(){var e=new v(null,{status:0,statusText:""});return e.type="error",e};var a=[301,302,303,307,308];v.redirect=function(e,t){if(-1===a.indexOf(t))throw new RangeError("Invalid status code");return new v(null,{status:t,headers:{location:e}})},e.Headers=f,e.Request=y,e.Response=v,e.fetch=function(e,r){return new Promise(function(n,i){var o=new y(e,r),a=new XMLHttpRequest;a.onload=function(){var e,t,r={status:a.status,statusText:a.statusText,headers:(e=a.getAllResponseHeaders()||"",t=new f,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach(function(e){var r=e.split(":"),n=r.shift().trim();if(n){var i=r.join(":").trim();t.append(n,i)}}),t)};r.url="responseURL"in a?a.responseURL:r.headers.get("X-Request-URL");var i="response"in a?a.response:a.responseText;n(new v(i,r))},a.onerror=function(){i(new TypeError("Network request failed"))},a.ontimeout=function(){i(new TypeError("Network request failed"))},a.open(o.method,o.url,!0),"include"===o.credentials?a.withCredentials=!0:"omit"===o.credentials&&(a.withCredentials=!1),"responseType"in a&&t.blob&&(a.responseType="blob"),o.headers.forEach(function(e,t){a.setRequestHeader(t,e)}),a.send(void 0===o._bodyInit?null:o._bodyInit)})},e.fetch.polyfill=!0}function s(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function u(e){return"string"!=typeof e&&(e=String(e)),e}function c(e){var r={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return t.iterable&&(r[Symbol.iterator]=function(){return r}),r}function f(e){this.map={},e instanceof f?e.forEach(function(e,t){this.append(t,e)},this):Array.isArray(e)?e.forEach(function(e){this.append(e[0],e[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}function h(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function l(e){return new Promise(function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}})}function d(e){var t=new FileReader,r=l(t);return t.readAsArrayBuffer(e),r}function p(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function b(){return this.bodyUsed=!1,this._initBody=function(e){if(this._bodyInit=e,e)if("string"==typeof e)this._bodyText=e;else if(t.blob&&Blob.prototype.isPrototypeOf(e))this._bodyBlob=e;else if(t.formData&&FormData.prototype.isPrototypeOf(e))this._bodyFormData=e;else if(t.searchParams&&URLSearchParams.prototype.isPrototypeOf(e))this._bodyText=e.toString();else if(t.arrayBuffer&&t.blob&&n(e))this._bodyArrayBuffer=p(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer]);else{if(!t.arrayBuffer||!ArrayBuffer.prototype.isPrototypeOf(e)&&!i(e))throw new Error("unsupported BodyInit type");this._bodyArrayBuffer=p(e)}else this._bodyText="";this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):t.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},t.blob&&(this.blob=function(){var e=h(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?h(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(d)}),this.text=function(){var e,t,r,n=h(this);if(n)return n;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,r=l(t),t.readAsText(e),r;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),r=new Array(t.length),n=0;n-1?n:r),this.mode=t.mode||this.mode||null,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&i)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(i)}function m(e){var t=new FormData;return e.trim().split("&").forEach(function(e){if(e){var r=e.split("="),n=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");t.append(decodeURIComponent(n),decodeURIComponent(i))}}),t}function v(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new f(t.headers),this.url=t.url||"",this._initBody(e)}}(void 0!==e?e:this)}).call(n,void 0);var i=n.fetch;i.Response=n.Response,i.Request=n.Request,i.Headers=n.Headers;"object"==typeof t&&t.exports&&(t.exports=i,t.exports.default=i)},{}],97:[function(e,t,r){"use strict";r.randomBytes=r.rng=r.pseudoRandomBytes=r.prng=e("randombytes"),r.createHash=r.Hash=e("create-hash"),r.createHmac=r.Hmac=e("create-hmac");var n=e("browserify-sign/algos"),i=Object.keys(n),o=["sha1","sha224","sha256","sha384","sha512","md5","rmd160"].concat(i);r.getHashes=function(){return o};var a=e("pbkdf2");r.pbkdf2=a.pbkdf2,r.pbkdf2Sync=a.pbkdf2Sync;var s=e("browserify-cipher");r.Cipher=s.Cipher,r.createCipher=s.createCipher,r.Cipheriv=s.Cipheriv,r.createCipheriv=s.createCipheriv,r.Decipher=s.Decipher,r.createDecipher=s.createDecipher,r.Decipheriv=s.Decipheriv,r.createDecipheriv=s.createDecipheriv,r.getCiphers=s.getCiphers,r.listCiphers=s.listCiphers;var u=e("diffie-hellman");r.DiffieHellmanGroup=u.DiffieHellmanGroup,r.createDiffieHellmanGroup=u.createDiffieHellmanGroup,r.getDiffieHellman=u.getDiffieHellman,r.createDiffieHellman=u.createDiffieHellman,r.DiffieHellman=u.DiffieHellman;var c=e("browserify-sign");r.createSign=c.createSign,r.Sign=c.Sign,r.createVerify=c.createVerify,r.Verify=c.Verify,r.createECDH=e("create-ecdh");var f=e("public-encrypt");r.publicEncrypt=f.publicEncrypt,r.privateEncrypt=f.privateEncrypt,r.publicDecrypt=f.publicDecrypt,r.privateDecrypt=f.privateDecrypt;var h=e("randomfill");r.randomFill=h.randomFill,r.randomFillSync=h.randomFillSync,r.createCredentials=function(){throw new Error(["sorry, createCredentials is not implemented yet","we accept pull requests","https://github.com/crypto-browserify/crypto-browserify"].join("\n"))},r.constants={DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,NPN_ENABLED:1,ALPN_ENABLED:1,RSA_PKCS1_PADDING:1,RSA_SSLV23_PADDING:2,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,POINT_CONVERSION_COMPRESSED:2,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(e,t,r){"use strict";var n=new RegExp("%[a-f0-9]{2}","gi"),i=new RegExp("(%[a-f0-9]{2})+","gi");function o(e,t){try{return decodeURIComponent(e.join(""))}catch(e){}if(1===e.length)return e;t=t||1;var r=e.slice(0,t),n=e.slice(t);return Array.prototype.concat.call([],o(r),o(n))}function a(e){try{return decodeURIComponent(e)}catch(i){for(var t=e.match(n),r=1;r0;n--)t+=this._buffer(e,t),r+=this._flushBuffer(i,r);return t+=this._buffer(e,t),i},i.prototype.final=function(e){var t,r;return e&&(t=this.update(e)),r="encrypt"===this.type?this._finalEncrypt():this._finalDecrypt(),t?t.concat(r):r},i.prototype._pad=function(e,t){if(0===t)return!1;for(;t>>1];r=a.r28shl(r,s),i=a.r28shl(i,s),a.pc2(r,i,e.keys,o)}},u.prototype._update=function(e,t,r,n){var i=this._desState,o=a.readUInt32BE(e,t),s=a.readUInt32BE(e,t+4);a.ip(o,s,i.tmp,0),o=i.tmp[0],s=i.tmp[1],"encrypt"===this.type?this._encrypt(i,o,s,i.tmp,0):this._decrypt(i,o,s,i.tmp,0),o=i.tmp[0],s=i.tmp[1],a.writeUInt32BE(r,o,n),a.writeUInt32BE(r,s,n+4)},u.prototype._pad=function(e,t){for(var r=e.length-t,n=t;n>>0,o=l}a.rip(s,o,n,i)},u.prototype._decrypt=function(e,t,r,n,i){for(var o=r,s=t,u=e.keys.length-2;u>=0;u-=2){var c=e.keys[u],f=e.keys[u+1];a.expand(o,e.tmp,0),c^=e.tmp[0],f^=e.tmp[1];var h=a.substitute(c,f),l=o;o=(s^a.permute(h))>>>0,s=l}a.rip(o,s,n,i)}},{"../des":99,inherits:180,"minimalistic-assert":234}],103:[function(e,t,r){"use strict";var n=e("minimalistic-assert"),i=e("inherits"),o=e("../des"),a=o.Cipher,s=o.DES;function u(e){a.call(this,e);var t=new function(e,t){n.equal(t.length,24,"Invalid key length");var r=t.slice(0,8),i=t.slice(8,16),o=t.slice(16,24);this.ciphers="encrypt"===e?[s.create({type:"encrypt",key:r}),s.create({type:"decrypt",key:i}),s.create({type:"encrypt",key:o})]:[s.create({type:"decrypt",key:o}),s.create({type:"encrypt",key:i}),s.create({type:"decrypt",key:r})]}(this.type,this.options.key);this._edeState=t}i(u,a),t.exports=u,u.create=function(e){return new u(e)},u.prototype._update=function(e,t,r,n){var i=this._edeState;i.ciphers[0]._update(e,t,r,n),i.ciphers[1]._update(r,n,r,n),i.ciphers[2]._update(r,n,r,n)},u.prototype._pad=s.prototype._pad,u.prototype._unpad=s.prototype._unpad},{"../des":99,inherits:180,"minimalistic-assert":234}],104:[function(e,t,r){"use strict";r.readUInt32BE=function(e,t){return(e[0+t]<<24|e[1+t]<<16|e[2+t]<<8|e[3+t])>>>0},r.writeUInt32BE=function(e,t,r){e[0+r]=t>>>24,e[1+r]=t>>>16&255,e[2+r]=t>>>8&255,e[3+r]=255&t},r.ip=function(e,t,r,n){for(var i=0,o=0,a=6;a>=0;a-=2){for(var s=0;s<=24;s+=8)i<<=1,i|=t>>>s+a&1;for(s=0;s<=24;s+=8)i<<=1,i|=e>>>s+a&1}for(a=6;a>=0;a-=2){for(s=1;s<=25;s+=8)o<<=1,o|=t>>>s+a&1;for(s=1;s<=25;s+=8)o<<=1,o|=e>>>s+a&1}r[n+0]=i>>>0,r[n+1]=o>>>0},r.rip=function(e,t,r,n){for(var i=0,o=0,a=0;a<4;a++)for(var s=24;s>=0;s-=8)i<<=1,i|=t>>>s+a&1,i<<=1,i|=e>>>s+a&1;for(a=4;a<8;a++)for(s=24;s>=0;s-=8)o<<=1,o|=t>>>s+a&1,o<<=1,o|=e>>>s+a&1;r[n+0]=i>>>0,r[n+1]=o>>>0},r.pc1=function(e,t,r,n){for(var i=0,o=0,a=7;a>=5;a--){for(var s=0;s<=24;s+=8)i<<=1,i|=t>>s+a&1;for(s=0;s<=24;s+=8)i<<=1,i|=e>>s+a&1}for(s=0;s<=24;s+=8)i<<=1,i|=t>>s+a&1;for(a=1;a<=3;a++){for(s=0;s<=24;s+=8)o<<=1,o|=t>>s+a&1;for(s=0;s<=24;s+=8)o<<=1,o|=e>>s+a&1}for(s=0;s<=24;s+=8)o<<=1,o|=e>>s+a&1;r[n+0]=i>>>0,r[n+1]=o>>>0},r.r28shl=function(e,t){return e<>>28-t};var n=[14,11,17,4,27,23,25,0,13,22,7,18,5,9,16,24,2,20,12,21,1,8,15,26,15,4,25,19,9,1,26,16,5,11,23,8,12,7,17,0,22,3,10,14,6,20,27,24];r.pc2=function(e,t,r,i){for(var o=0,a=0,s=n.length>>>1,u=0;u>>n[u]&1;for(u=s;u>>n[u]&1;r[i+0]=o>>>0,r[i+1]=a>>>0},r.expand=function(e,t,r){var n=0,i=0;n=(1&e)<<5|e>>>27;for(var o=23;o>=15;o-=4)n<<=6,n|=e>>>o&63;for(o=11;o>=3;o-=4)i|=e>>>o&63,i<<=6;i|=(31&e)<<1|e>>>31,t[r+0]=n>>>0,t[r+1]=i>>>0};var i=[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];r.substitute=function(e,t){for(var r=0,n=0;n<4;n++){r<<=4,r|=i[64*n+(e>>>18-6*n&63)]}for(n=0;n<4;n++){r<<=4,r|=i[256+64*n+(t>>>18-6*n&63)]}return r>>>0};var o=[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];r.permute=function(e){for(var t=0,r=0;r>>o[r]&1;return t>>>0},r.padSplit=function(e,t,r){for(var n=e.toString(2);n.lengthe;)r.ishrn(1);if(r.isEven()&&r.iadd(s),r.testn(1)||r.iadd(u),t.cmp(u)){if(!t.cmp(c))for(;r.mod(f).cmp(h);)r.iadd(d)}else for(;r.mod(o).cmp(l);)r.iadd(d);if(y(p=r.shrn(1))&&y(r)&&m(p)&&m(r)&&a.test(p)&&a.test(r))return r}}},{"bn.js":53,"miller-rabin":233,randombytes:270}],108:[function(e,t,r){t.exports={modp1:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},modp2:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},modp5:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},modp14:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},modp15:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},modp16:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},modp17:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},modp18:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"}}},{}],109:[function(e,t,r){"use strict";var n=r;n.version=e("../package.json").version,n.utils=e("./elliptic/utils"),n.rand=e("brorand"),n.curve=e("./elliptic/curve"),n.curves=e("./elliptic/curves"),n.ec=e("./elliptic/ec"),n.eddsa=e("./elliptic/eddsa")},{"../package.json":124,"./elliptic/curve":112,"./elliptic/curves":115,"./elliptic/ec":116,"./elliptic/eddsa":119,"./elliptic/utils":123,brorand:54}],110:[function(e,t,r){"use strict";var n=e("bn.js"),i=e("../../elliptic").utils,o=i.getNAF,a=i.getJSF,s=i.assert;function u(e,t){this.type=e,this.p=new n(t.p,16),this.red=t.prime?n.red(t.prime):n.mont(this.p),this.zero=new n(0).toRed(this.red),this.one=new n(1).toRed(this.red),this.two=new n(2).toRed(this.red),this.n=t.n&&new n(t.n,16),this.g=t.g&&this.pointFromJSON(t.g,t.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4);var r=this.n&&this.p.div(this.n);!r||r.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}function c(e,t){this.curve=e,this.type=t,this.precomputed=null}t.exports=u,u.prototype.point=function(){throw new Error("Not implemented")},u.prototype.validate=function(){throw new Error("Not implemented")},u.prototype._fixedNafMul=function(e,t){s(e.precomputed);var r=e._getDoubles(),n=o(t,1),i=(1<=u;t--)c=(c<<1)+n[t];a.push(c)}for(var f=this.jpoint(null,null,null),h=this.jpoint(null,null,null),l=i;l>0;l--){for(u=0;u=0;c--){for(t=0;c>=0&&0===a[c];c--)t++;if(c>=0&&t++,u=u.dblp(t),c<0)break;var f=a[c];s(0!==f),u="affine"===e.type?f>0?u.mixedAdd(i[f-1>>1]):u.mixedAdd(i[-f-1>>1].neg()):f>0?u.add(i[f-1>>1]):u.add(i[-f-1>>1].neg())}return"affine"===e.type?u.toP():u},u.prototype._wnafMulAdd=function(e,t,r,n,i){for(var s=this._wnafT1,u=this._wnafT2,c=this._wnafT3,f=0,h=0;h=1;h-=2){var d=h-1,p=h;if(1===s[d]&&1===s[p]){var b=[t[d],null,null,t[p]];0===t[d].y.cmp(t[p].y)?(b[1]=t[d].add(t[p]),b[2]=t[d].toJ().mixedAdd(t[p].neg())):0===t[d].y.cmp(t[p].y.redNeg())?(b[1]=t[d].toJ().mixedAdd(t[p]),b[2]=t[d].add(t[p].neg())):(b[1]=t[d].toJ().mixedAdd(t[p]),b[2]=t[d].toJ().mixedAdd(t[p].neg()));var y=[-3,-1,-5,-7,0,7,5,1,3],m=a(r[d],r[p]);f=Math.max(m[0].length,f),c[d]=new Array(f),c[p]=new Array(f);for(var v=0;v=0;h--){for(var E=0;h>=0;){var x=!0;for(v=0;v=0&&E++,_=_.dblp(E),h<0)break;for(v=0;v0?k=u[v][S-1>>1]:S<0&&(k=u[v][-S-1>>1].neg()),_="affine"===k.type?_.mixedAdd(k):_.add(k))}}for(h=0;h=Math.ceil((e.bitLength()+1)/t.step)},c.prototype._getDoubles=function(e,t){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i":""},f.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&0===this.y.cmp(this.z)},f.prototype._extDbl=function(){var e=this.x.redSqr(),t=this.y.redSqr(),r=this.z.redSqr();r=r.redIAdd(r);var n=this.curve._mulA(e),i=this.x.redAdd(this.y).redSqr().redISub(e).redISub(t),o=n.redAdd(t),a=o.redSub(r),s=n.redSub(t),u=i.redMul(a),c=o.redMul(s),f=i.redMul(s),h=a.redMul(o);return this.curve.point(u,c,h,f)},f.prototype._projDbl=function(){var e,t,r,n=this.x.redAdd(this.y).redSqr(),i=this.x.redSqr(),o=this.y.redSqr();if(this.curve.twisted){var a=(c=this.curve._mulA(i)).redAdd(o);if(this.zOne)e=n.redSub(i).redSub(o).redMul(a.redSub(this.curve.two)),t=a.redMul(c.redSub(o)),r=a.redSqr().redSub(a).redSub(a);else{var s=this.z.redSqr(),u=a.redSub(s).redISub(s);e=n.redSub(i).redISub(o).redMul(u),t=a.redMul(c.redSub(o)),r=a.redMul(u)}}else{var c=i.redAdd(o);s=this.curve._mulC(this.c.redMul(this.z)).redSqr(),u=c.redSub(s).redSub(s);e=this.curve._mulC(n.redISub(c)).redMul(u),t=this.curve._mulC(c).redMul(i.redISub(o)),r=c.redMul(u)}return this.curve.point(e,t,r)},f.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},f.prototype._extAdd=function(e){var t=this.y.redSub(this.x).redMul(e.y.redSub(e.x)),r=this.y.redAdd(this.x).redMul(e.y.redAdd(e.x)),n=this.t.redMul(this.curve.dd).redMul(e.t),i=this.z.redMul(e.z.redAdd(e.z)),o=r.redSub(t),a=i.redSub(n),s=i.redAdd(n),u=r.redAdd(t),c=o.redMul(a),f=s.redMul(u),h=o.redMul(u),l=a.redMul(s);return this.curve.point(c,f,l,h)},f.prototype._projAdd=function(e){var t,r,n=this.z.redMul(e.z),i=n.redSqr(),o=this.x.redMul(e.x),a=this.y.redMul(e.y),s=this.curve.d.redMul(o).redMul(a),u=i.redSub(s),c=i.redAdd(s),f=this.x.redAdd(this.y).redMul(e.x.redAdd(e.y)).redISub(o).redISub(a),h=n.redMul(u).redMul(f);return this.curve.twisted?(t=n.redMul(c).redMul(a.redSub(this.curve._mulA(o))),r=u.redMul(c)):(t=n.redMul(c).redMul(a.redSub(o)),r=this.curve._mulC(u).redMul(c)),this.curve.point(h,t,r)},f.prototype.add=function(e){return this.isInfinity()?e:e.isInfinity()?this:this.curve.extended?this._extAdd(e):this._projAdd(e)},f.prototype.mul=function(e){return this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve._wnafMul(this,e)},f.prototype.mulAdd=function(e,t,r){return this.curve._wnafMulAdd(1,[this,t],[e,r],2,!1)},f.prototype.jmulAdd=function(e,t,r){return this.curve._wnafMulAdd(1,[this,t],[e,r],2,!0)},f.prototype.normalize=function(){if(this.zOne)return this;var e=this.z.redInvm();return this.x=this.x.redMul(e),this.y=this.y.redMul(e),this.t&&(this.t=this.t.redMul(e)),this.z=this.curve.one,this.zOne=!0,this},f.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},f.prototype.getX=function(){return this.normalize(),this.x.fromRed()},f.prototype.getY=function(){return this.normalize(),this.y.fromRed()},f.prototype.eq=function(e){return this===e||0===this.getX().cmp(e.getX())&&0===this.getY().cmp(e.getY())},f.prototype.eqXToP=function(e){var t=e.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(t))return!0;for(var r=e.clone(),n=this.curve.redN.redMul(this.z);;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(t.redIAdd(n),0===this.x.cmp(t))return!0}return!1},f.prototype.toP=f.prototype.normalize,f.prototype.mixedAdd=f.prototype.add},{"../../elliptic":109,"../curve":112,"bn.js":53,inherits:180}],112:[function(e,t,r){"use strict";var n=r;n.base=e("./base"),n.short=e("./short"),n.mont=e("./mont"),n.edwards=e("./edwards")},{"./base":110,"./edwards":111,"./mont":113,"./short":114}],113:[function(e,t,r){"use strict";var n=e("../curve"),i=e("bn.js"),o=e("inherits"),a=n.base,s=e("../../elliptic").utils;function u(e){a.call(this,"mont",e),this.a=new i(e.a,16).toRed(this.red),this.b=new i(e.b,16).toRed(this.red),this.i4=new i(4).toRed(this.red).redInvm(),this.two=new i(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}function c(e,t,r){a.BasePoint.call(this,e,"projective"),null===t&&null===r?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new i(t,16),this.z=new i(r,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}o(u,a),t.exports=u,u.prototype.validate=function(e){var t=e.normalize().x,r=t.redSqr(),n=r.redMul(t).redAdd(r.redMul(this.a)).redAdd(t);return 0===n.redSqrt().redSqr().cmp(n)},o(c,a.BasePoint),u.prototype.decodePoint=function(e,t){return this.point(s.toArray(e,t),1)},u.prototype.point=function(e,t){return new c(this,e,t)},u.prototype.pointFromJSON=function(e){return c.fromJSON(this,e)},c.prototype.precompute=function(){},c.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},c.fromJSON=function(e,t){return new c(e,t[0],t[1]||e.one)},c.prototype.inspect=function(){return this.isInfinity()?"":""},c.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},c.prototype.dbl=function(){var e=this.x.redAdd(this.z).redSqr(),t=this.x.redSub(this.z).redSqr(),r=e.redSub(t),n=e.redMul(t),i=r.redMul(t.redAdd(this.curve.a24.redMul(r)));return this.curve.point(n,i)},c.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.diffAdd=function(e,t){var r=this.x.redAdd(this.z),n=this.x.redSub(this.z),i=e.x.redAdd(e.z),o=e.x.redSub(e.z).redMul(r),a=i.redMul(n),s=t.z.redMul(o.redAdd(a).redSqr()),u=t.x.redMul(o.redISub(a).redSqr());return this.curve.point(s,u)},c.prototype.mul=function(e){for(var t=e.clone(),r=this,n=this.curve.point(null,null),i=[];0!==t.cmpn(0);t.iushrn(1))i.push(t.andln(1));for(var o=i.length-1;o>=0;o--)0===i[o]?(r=r.diffAdd(n,this),n=n.dbl()):(n=r.diffAdd(n,this),r=r.dbl());return n},c.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.eq=function(e){return 0===this.getX().cmp(e.getX())},c.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},c.prototype.getX=function(){return this.normalize(),this.x.fromRed()}},{"../../elliptic":109,"../curve":112,"bn.js":53,inherits:180}],114:[function(e,t,r){"use strict";var n=e("../curve"),i=e("../../elliptic"),o=e("bn.js"),a=e("inherits"),s=n.base,u=i.utils.assert;function c(e){s.call(this,"short",e),this.a=new o(e.a,16).toRed(this.red),this.b=new o(e.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=0===this.a.fromRed().cmpn(0),this.threeA=0===this.a.fromRed().sub(this.p).cmpn(-3),this.endo=this._getEndomorphism(e),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}function f(e,t,r,n){s.BasePoint.call(this,e,"affine"),null===t&&null===r?(this.x=null,this.y=null,this.inf=!0):(this.x=new o(t,16),this.y=new o(r,16),n&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}function h(e,t,r,n){s.BasePoint.call(this,e,"jacobian"),null===t&&null===r&&null===n?(this.x=this.curve.one,this.y=this.curve.one,this.z=new o(0)):(this.x=new o(t,16),this.y=new o(r,16),this.z=new o(n,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}a(c,s),t.exports=c,c.prototype._getEndomorphism=function(e){if(this.zeroA&&this.g&&this.n&&1===this.p.modn(3)){var t,r;if(e.beta)t=new o(e.beta,16).toRed(this.red);else{var n=this._getEndoRoots(this.p);t=(t=n[0].cmp(n[1])<0?n[0]:n[1]).toRed(this.red)}if(e.lambda)r=new o(e.lambda,16);else{var i=this._getEndoRoots(this.n);0===this.g.mul(i[0]).x.cmp(this.g.x.redMul(t))?r=i[0]:(r=i[1],u(0===this.g.mul(r).x.cmp(this.g.x.redMul(t))))}return{beta:t,lambda:r,basis:e.basis?e.basis.map(function(e){return{a:new o(e.a,16),b:new o(e.b,16)}}):this._getEndoBasis(r)}}},c.prototype._getEndoRoots=function(e){var t=e===this.p?this.red:o.mont(e),r=new o(2).toRed(t).redInvm(),n=r.redNeg(),i=new o(3).toRed(t).redNeg().redSqrt().redMul(r);return[n.redAdd(i).fromRed(),n.redSub(i).fromRed()]},c.prototype._getEndoBasis=function(e){for(var t,r,n,i,a,s,u,c,f,h=this.n.ushrn(Math.floor(this.n.bitLength()/2)),l=e,d=this.n.clone(),p=new o(1),b=new o(0),y=new o(0),m=new o(1),v=0;0!==l.cmpn(0);){var g=d.div(l);c=d.sub(g.mul(l)),f=y.sub(g.mul(p));var w=m.sub(g.mul(b));if(!n&&c.cmp(h)<0)t=u.neg(),r=p,n=c.neg(),i=f;else if(n&&2==++v)break;u=c,d=l,l=c,y=p,p=f,m=b,b=w}a=c.neg(),s=f;var _=n.sqr().add(i.sqr());return a.sqr().add(s.sqr()).cmp(_)>=0&&(a=t,s=r),n.negative&&(n=n.neg(),i=i.neg()),a.negative&&(a=a.neg(),s=s.neg()),[{a:n,b:i},{a:a,b:s}]},c.prototype._endoSplit=function(e){var t=this.endo.basis,r=t[0],n=t[1],i=n.b.mul(e).divRound(this.n),o=r.b.neg().mul(e).divRound(this.n),a=i.mul(r.a),s=o.mul(n.a),u=i.mul(r.b),c=o.mul(n.b);return{k1:e.sub(a).sub(s),k2:u.add(c).neg()}},c.prototype.pointFromX=function(e,t){(e=new o(e,16)).red||(e=e.toRed(this.red));var r=e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(0!==n.redSqr().redSub(r).cmp(this.zero))throw new Error("invalid point");var i=n.fromRed().isOdd();return(t&&!i||!t&&i)&&(n=n.redNeg()),this.point(e,n)},c.prototype.validate=function(e){if(e.inf)return!0;var t=e.x,r=e.y,n=this.a.redMul(t),i=t.redSqr().redMul(t).redIAdd(n).redIAdd(this.b);return 0===r.redSqr().redISub(i).cmpn(0)},c.prototype._endoWnafMulAdd=function(e,t,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,o=0;o":""},f.prototype.isInfinity=function(){return this.inf},f.prototype.add=function(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return this.curve.point(null,null);if(0===this.x.cmp(e.x))return this.curve.point(null,null);var t=this.y.redSub(e.y);0!==t.cmpn(0)&&(t=t.redMul(this.x.redSub(e.x).redInvm()));var r=t.redSqr().redISub(this.x).redISub(e.x),n=t.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},f.prototype.dbl=function(){if(this.inf)return this;var e=this.y.redAdd(this.y);if(0===e.cmpn(0))return this.curve.point(null,null);var t=this.curve.a,r=this.x.redSqr(),n=e.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(t).redMul(n),o=i.redSqr().redISub(this.x.redAdd(this.x)),a=i.redMul(this.x.redSub(o)).redISub(this.y);return this.curve.point(o,a)},f.prototype.getX=function(){return this.x.fromRed()},f.prototype.getY=function(){return this.y.fromRed()},f.prototype.mul=function(e){return e=new o(e,16),this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve.endo?this.curve._endoWnafMulAdd([this],[e]):this.curve._wnafMul(this,e)},f.prototype.mulAdd=function(e,t,r){var n=[this,t],i=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},f.prototype.jmulAdd=function(e,t,r){var n=[this,t],i=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},f.prototype.eq=function(e){return this===e||this.inf===e.inf&&(this.inf||0===this.x.cmp(e.x)&&0===this.y.cmp(e.y))},f.prototype.neg=function(e){if(this.inf)return this;var t=this.curve.point(this.x,this.y.redNeg());if(e&&this.precomputed){var r=this.precomputed,n=function(e){return e.neg()};t.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return t},f.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},a(h,s.BasePoint),c.prototype.jpoint=function(e,t,r){return new h(this,e,t,r)},h.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var e=this.z.redInvm(),t=e.redSqr(),r=this.x.redMul(t),n=this.y.redMul(t).redMul(e);return this.curve.point(r,n)},h.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},h.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(t),i=e.x.redMul(r),o=this.y.redMul(t.redMul(e.z)),a=e.y.redMul(r.redMul(this.z)),s=n.redSub(i),u=o.redSub(a);if(0===s.cmpn(0))return 0!==u.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var c=s.redSqr(),f=c.redMul(s),h=n.redMul(c),l=u.redSqr().redIAdd(f).redISub(h).redISub(h),d=u.redMul(h.redISub(l)).redISub(o.redMul(f)),p=this.z.redMul(e.z).redMul(s);return this.curve.jpoint(l,d,p)},h.prototype.mixedAdd=function(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;var t=this.z.redSqr(),r=this.x,n=e.x.redMul(t),i=this.y,o=e.y.redMul(t).redMul(this.z),a=r.redSub(n),s=i.redSub(o);if(0===a.cmpn(0))return 0!==s.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var u=a.redSqr(),c=u.redMul(a),f=r.redMul(u),h=s.redSqr().redIAdd(c).redISub(f).redISub(f),l=s.redMul(f.redISub(h)).redISub(i.redMul(c)),d=this.z.redMul(a);return this.curve.jpoint(h,l,d)},h.prototype.dblp=function(e){if(0===e)return this;if(this.isInfinity())return this;if(!e)return this.dbl();if(this.curve.zeroA||this.curve.threeA){for(var t=this,r=0;r=0)return!1;if(r.redIAdd(i),0===this.x.cmp(r))return!0}return!1},h.prototype.inspect=function(){return this.isInfinity()?"":""},h.prototype.isInfinity=function(){return 0===this.z.cmpn(0)}},{"../../elliptic":109,"../curve":112,"bn.js":53,inherits:180}],115:[function(e,t,r){"use strict";var n,i=r,o=e("hash.js"),a=e("../elliptic"),s=a.utils.assert;function u(e){"short"===e.type?this.curve=new a.curve.short(e):"edwards"===e.type?this.curve=new a.curve.edwards(e):this.curve=new a.curve.mont(e),this.g=this.curve.g,this.n=this.curve.n,this.hash=e.hash,s(this.g.validate(),"Invalid curve"),s(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}function c(e,t){Object.defineProperty(i,e,{configurable:!0,enumerable:!0,get:function(){var r=new u(t);return Object.defineProperty(i,e,{configurable:!0,enumerable:!0,value:r}),r}})}i.PresetCurve=u,c("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:o.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),c("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:o.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),c("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:o.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),c("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:o.sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),c("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:o.sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),c("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:o.sha256,gRed:!1,g:["9"]}),c("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:o.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});try{n=e("./precomputed/secp256k1")}catch(e){n=void 0}c("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:o.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",n]})},{"../elliptic":109,"./precomputed/secp256k1":122,"hash.js":162}],116:[function(e,t,r){"use strict";var n=e("bn.js"),i=e("hmac-drbg"),o=e("../../elliptic"),a=o.utils.assert,s=e("./key"),u=e("./signature");function c(e){if(!(this instanceof c))return new c(e);"string"==typeof e&&(a(o.curves.hasOwnProperty(e),"Unknown curve "+e),e=o.curves[e]),e instanceof o.curves.PresetCurve&&(e={curve:e}),this.curve=e.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=e.curve.g,this.g.precompute(e.curve.n.bitLength()+1),this.hash=e.hash||e.curve.hash}t.exports=c,c.prototype.keyPair=function(e){return new s(this,e)},c.prototype.keyFromPrivate=function(e,t){return s.fromPrivate(this,e,t)},c.prototype.keyFromPublic=function(e,t){return s.fromPublic(this,e,t)},c.prototype.genKeyPair=function(e){e||(e={});for(var t=new i({hash:this.hash,pers:e.pers,persEnc:e.persEnc||"utf8",entropy:e.entropy||o.rand(this.hash.hmacStrength),entropyEnc:e.entropy&&e.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),a=this.n.sub(new n(2));;){var s=new n(t.generate(r));if(!(s.cmp(a)>0))return s.iaddn(1),this.keyFromPrivate(s)}},c.prototype._truncateToN=function(e,t){var r=8*e.byteLength()-this.n.bitLength();return r>0&&(e=e.ushrn(r)),!t&&e.cmp(this.n)>=0?e.sub(this.n):e},c.prototype.sign=function(e,t,r,o){"object"==typeof r&&(o=r,r=null),o||(o={}),t=this.keyFromPrivate(t,r),e=this._truncateToN(new n(e,16));for(var a=this.n.byteLength(),s=t.getPrivate().toArray("be",a),c=e.toArray("be",a),f=new i({hash:this.hash,entropy:s,nonce:c,pers:o.pers,persEnc:o.persEnc||"utf8"}),h=this.n.sub(new n(1)),l=0;;l++){var d=o.k?o.k(l):new n(f.generate(this.n.byteLength()));if(!((d=this._truncateToN(d,!0)).cmpn(1)<=0||d.cmp(h)>=0)){var p=this.g.mul(d);if(!p.isInfinity()){var b=p.getX(),y=b.umod(this.n);if(0!==y.cmpn(0)){var m=d.invm(this.n).mul(y.mul(t.getPrivate()).iadd(e));if(0!==(m=m.umod(this.n)).cmpn(0)){var v=(p.getY().isOdd()?1:0)|(0!==b.cmp(y)?2:0);return o.canonical&&m.cmp(this.nh)>0&&(m=this.n.sub(m),v^=1),new u({r:y,s:m,recoveryParam:v})}}}}}},c.prototype.verify=function(e,t,r,i){e=this._truncateToN(new n(e,16)),r=this.keyFromPublic(r,i);var o=(t=new u(t,"hex")).r,a=t.s;if(o.cmpn(1)<0||o.cmp(this.n)>=0)return!1;if(a.cmpn(1)<0||a.cmp(this.n)>=0)return!1;var s,c=a.invm(this.n),f=c.mul(e).umod(this.n),h=c.mul(o).umod(this.n);return this.curve._maxwellTrick?!(s=this.g.jmulAdd(f,r.getPublic(),h)).isInfinity()&&s.eqXToP(o):!(s=this.g.mulAdd(f,r.getPublic(),h)).isInfinity()&&0===s.getX().umod(this.n).cmp(o)},c.prototype.recoverPubKey=function(e,t,r,i){a((3&r)===r,"The recovery param is more than two bits"),t=new u(t,i);var o=this.n,s=new n(e),c=t.r,f=t.s,h=1&r,l=r>>1;if(c.cmp(this.curve.p.umod(this.curve.n))>=0&&l)throw new Error("Unable to find sencond key candinate");c=l?this.curve.pointFromX(c.add(this.curve.n),h):this.curve.pointFromX(c,h);var d=t.r.invm(o),p=o.sub(s).mul(d).umod(o),b=f.mul(d).umod(o);return this.g.mulAdd(p,c,b)},c.prototype.getKeyRecoveryParam=function(e,t,r,n){if(null!==(t=new u(t,n)).recoveryParam)return t.recoveryParam;for(var i=0;i<4;i++){var o;try{o=this.recoverPubKey(e,t,i)}catch(e){continue}if(o.eq(r))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(e,t,r){"use strict";var n=e("bn.js"),i=e("../../elliptic").utils.assert;function o(e,t){this.ec=e,this.priv=null,this.pub=null,t.priv&&this._importPrivate(t.priv,t.privEnc),t.pub&&this._importPublic(t.pub,t.pubEnc)}t.exports=o,o.fromPublic=function(e,t,r){return t instanceof o?t:new o(e,{pub:t,pubEnc:r})},o.fromPrivate=function(e,t,r){return t instanceof o?t:new o(e,{priv:t,privEnc:r})},o.prototype.validate=function(){var e=this.getPublic();return e.isInfinity()?{result:!1,reason:"Invalid public key"}:e.validate()?e.mul(this.ec.curve.n).isInfinity()?{result:!0,reason:null}:{result:!1,reason:"Public key * N != O"}:{result:!1,reason:"Public key is not a point"}},o.prototype.getPublic=function(e,t){return"string"==typeof e&&(t=e,e=null),this.pub||(this.pub=this.ec.g.mul(this.priv)),t?this.pub.encode(t,e):this.pub},o.prototype.getPrivate=function(e){return"hex"===e?this.priv.toString(16,2):this.priv},o.prototype._importPrivate=function(e,t){this.priv=new n(e,t||16),this.priv=this.priv.umod(this.ec.curve.n)},o.prototype._importPublic=function(e,t){if(e.x||e.y)return"mont"===this.ec.curve.type?i(e.x,"Need x coordinate"):"short"!==this.ec.curve.type&&"edwards"!==this.ec.curve.type||i(e.x&&e.y,"Need both x and y coordinate"),void(this.pub=this.ec.curve.point(e.x,e.y));this.pub=this.ec.curve.decodePoint(e,t)},o.prototype.derive=function(e){return e.mul(this.priv).getX()},o.prototype.sign=function(e,t,r){return this.ec.sign(e,this,t,r)},o.prototype.verify=function(e,t){return this.ec.verify(e,t,this)},o.prototype.inspect=function(){return""}},{"../../elliptic":109,"bn.js":53}],118:[function(e,t,r){"use strict";var n=e("bn.js"),i=e("../../elliptic").utils,o=i.assert;function a(e,t){if(e instanceof a)return e;this._importDER(e,t)||(o(e.r&&e.s,"Signature without r or s"),this.r=new n(e.r,16),this.s=new n(e.s,16),void 0===e.recoveryParam?this.recoveryParam=null:this.recoveryParam=e.recoveryParam)}function s(e,t){var r=e[t.place++];if(!(128&r))return r;for(var n=15&r,i=0,o=0,a=t.place;o>>3);for(e.push(128|r);--r;)e.push(t>>>(r<<3)&255);e.push(t)}}t.exports=a,a.prototype._importDER=function(e,t){e=i.toArray(e,t);var r=new function(){this.place=0};if(48!==e[r.place++])return!1;if(s(e,r)+r.place!==e.length)return!1;if(2!==e[r.place++])return!1;var o=s(e,r),a=e.slice(r.place,o+r.place);if(r.place+=o,2!==e[r.place++])return!1;var u=s(e,r);if(e.length!==u+r.place)return!1;var c=e.slice(r.place,u+r.place);return 0===a[0]&&128&a[1]&&(a=a.slice(1)),0===c[0]&&128&c[1]&&(c=c.slice(1)),this.r=new n(a),this.s=new n(c),this.recoveryParam=null,!0},a.prototype.toDER=function(e){var t=this.r.toArray(),r=this.s.toArray();for(128&t[0]&&(t=[0].concat(t)),128&r[0]&&(r=[0].concat(r)),t=u(t),r=u(r);!(r[0]||128&r[1]);)r=r.slice(1);var n=[2];c(n,t.length),(n=n.concat(t)).push(2),c(n,r.length);var o=n.concat(r),a=[48];return c(a,o.length),a=a.concat(o),i.encode(a,e)}},{"../../elliptic":109,"bn.js":53}],119:[function(e,t,r){"use strict";var n=e("hash.js"),i=e("../../elliptic"),o=i.utils,a=o.assert,s=o.parseBytes,u=e("./key"),c=e("./signature");function f(e){if(a("ed25519"===e,"only tested with ed25519 so far"),!(this instanceof f))return new f(e);e=i.curves[e].curve;this.curve=e,this.g=e.g,this.g.precompute(e.n.bitLength()+1),this.pointClass=e.point().constructor,this.encodingLength=Math.ceil(e.n.bitLength()/8),this.hash=n.sha512}t.exports=f,f.prototype.sign=function(e,t){e=s(e);var r=this.keyFromSecret(t),n=this.hashInt(r.messagePrefix(),e),i=this.g.mul(n),o=this.encodePoint(i),a=this.hashInt(o,r.pubBytes(),e).mul(r.priv()),u=n.add(a).umod(this.curve.n);return this.makeSignature({R:i,S:u,Rencoded:o})},f.prototype.verify=function(e,t,r){e=s(e),t=this.makeSignature(t);var n=this.keyFromPublic(r),i=this.hashInt(t.Rencoded(),n.pubBytes(),e),o=this.g.mul(t.S());return t.R().add(n.pub().mul(i)).eq(o)},f.prototype.hashInt=function(){for(var e=this.hash(),t=0;t=0;){var o;if(i.isOdd()){var a=i.andln(n-1);o=a>(n>>1)-1?(n>>1)-a:a,i.isubn(o)}else o=0;r.push(o);for(var s=0!==i.cmpn(0)&&0===i.andln(n-1)?t+1:1,u=1;u0||t.cmpn(-i)>0;){var o,a,s,u=e.andln(3)+n&3,c=t.andln(3)+i&3;3===u&&(u=-1),3===c&&(c=-1),o=0==(1&u)?0:3!=(s=e.andln(7)+n&7)&&5!==s||2!==c?u:-u,r[0].push(o),a=0==(1&c)?0:3!=(s=t.andln(7)+i&7)&&5!==s||2!==u?c:-c,r[1].push(a),2*n===o+1&&(n=1-n),2*i===a+1&&(i=1-i),e.iushrn(1),t.iushrn(1)}return r},n.cachedProperty=function(e,t,r){var n="_"+t;e.prototype[t]=function(){return void 0!==this[n]?this[n]:this[n]=r.call(this)}},n.parseBytes=function(e){return"string"==typeof e?n.toArray(e,"hex"):e},n.intFromLE=function(e){return new i(e,"hex","le")}},{"bn.js":53,"minimalistic-assert":234,"minimalistic-crypto-utils":235}],124:[function(e,t,r){t.exports={_from:"elliptic@^6.0.0",_id:"elliptic@6.4.0",_inBundle:!1,_integrity:"sha1-ysmvh2LIWDYYcAPI3+GT5eLq5d8=",_location:"/elliptic",_phantomChildren:{},_requested:{type:"range",registry:!0,raw:"elliptic@^6.0.0",name:"elliptic",escapedName:"elliptic",rawSpec:"^6.0.0",saveSpec:null,fetchSpec:"^6.0.0"},_requiredBy:["/browserify-sign","/create-ecdh"],_resolved:"https://registry.npmjs.org/elliptic/-/elliptic-6.4.0.tgz",_shasum:"cac9af8762c85836187003c8dfe193e5e2eae5df",_spec:"elliptic@^6.0.0",_where:"/Users/alexvlasov/Blockchain/web3swift_jsproxy/node_modules/browserify-sign",author:{name:"Fedor Indutny",email:"fedor@indutny.com"},bugs:{url:"https://github.com/indutny/elliptic/issues"},bundleDependencies:!1,dependencies:{"bn.js":"^4.4.0",brorand:"^1.0.1","hash.js":"^1.0.0","hmac-drbg":"^1.0.0",inherits:"^2.0.1","minimalistic-assert":"^1.0.0","minimalistic-crypto-utils":"^1.0.0"},deprecated:!1,description:"EC cryptography",devDependencies:{brfs:"^1.4.3",coveralls:"^2.11.3",grunt:"^0.4.5","grunt-browserify":"^5.0.0","grunt-cli":"^1.2.0","grunt-contrib-connect":"^1.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^1.0.1","grunt-mocha-istanbul":"^3.0.1","grunt-saucelabs":"^8.6.2",istanbul:"^0.4.2",jscs:"^2.9.0",jshint:"^2.6.0",mocha:"^2.1.0"},files:["lib"],homepage:"https://github.com/indutny/elliptic",keywords:["EC","Elliptic","curve","Cryptography"],license:"MIT",main:"lib/elliptic.js",name:"elliptic",repository:{type:"git",url:"git+ssh://git@github.com/indutny/elliptic.git"},scripts:{jscs:"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",jshint:"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",lint:"npm run jscs && npm run jshint",test:"npm run lint && npm run unit",unit:"istanbul test _mocha --reporter=spec test/index.js",version:"grunt dist && git add dist/"},version:"6.4.0"}},{}],125:[function(e,t,r){"use strict";const n=e("ethjs-util");function i(e){let t=n.stripHexPrefix(e);for(;"0"===t[0];)t=t.substr(1);return`0x${t}`}t.exports={incrementHexNumber:function(e){return i(n.intToHex(parseInt(e,16)+1))},formatHex:i}},{"ethjs-util":155}],126:[function(e,t,r){const n=e("eth-query"),i=e("events"),o=e("pify"),a=e("./hexUtils"),s=a.incrementHexNumber,u=1e3,c=60*u;t.exports=class extends i{constructor(e={}){if(super(),!e.provider)throw new Error("RpcBlockTracker - no provider specified.");this._provider=e.provider,this._query=new n(e.provider),this._pollingInterval=e.pollingInterval||4*u,this._syncingTimeout=e.syncingTimeout||1*c,this._trackingBlock=null,this._trackingBlockTimestamp=null,this._currentBlock=null,this._isRunning=!1,this._performSync=this._performSync.bind(this),this._handleNewBlockNotification=this._handleNewBlockNotification.bind(this)}getTrackingBlock(){return this._trackingBlock}getCurrentBlock(){return this._currentBlock}async awaitCurrentBlock(){return this._currentBlock?this._currentBlock:(await new Promise(e=>this.once("latest",e)),this._currentBlock)}async start(e={}){this._isRunning||(this._isRunning=!0,e.fromBlock?await this._setTrackingBlock(await this._fetchBlockByNumber(e.fromBlock)):await this._setTrackingBlock(await this._fetchLatestBlock()),this._provider.on?await this._initSubscription():this._performSync().catch(e=>{e&&console.error(e)}))}async stop(){this._isRunning=!1,this._provider.on&&await this._removeSubscription()}async _setTrackingBlock(e){if(this._trackingBlock&&this._trackingBlock.hash===e.hash)return;const t=this._trackingBlockTimestamp,r=Date.now();t&&r-t>this._syncingTimeout?(this._trackingBlockTimestamp=null,await this._warpToLatest()):(this._trackingBlock=e,this._trackingBlockTimestamp=r,this.emit("block",e))}async _setCurrentBlock(e){if(this._currentBlock&&this._currentBlock.hash===e.hash)return;const t=this._currentBlock;this._currentBlock=e,this.emit("latest",e),this.emit("sync",{newBlock:e,oldBlock:t})}async _warpToLatest(){await this._setTrackingBlock(await this._fetchLatestBlock())}async _pollForNextBlock(){setTimeout(()=>this._performSync(),this._pollingInterval)}async _performSync(){if(!this._isRunning)return;const e=this.getTrackingBlock();if(!e)throw new Error("RpcBlockTracker - tracking block is missing");const t=s(e.number);try{const r=await this._fetchBlockByNumber(t);r?(await this._setTrackingBlock(r),this._performSync()):(await this._setCurrentBlock(e),this._pollForNextBlock())}catch(t){t.message.includes("index out of range")||t.message.includes("Couldn't find block by reference")?(await this._setCurrentBlock(e),this._pollForNextBlock()):(console.error(t),this._pollForNextBlock())}}async _handleNewBlockNotification(e,t){t.id==this._subscriptionId&&(e&&(this.emit("error",e),await this._removeSubscription()),await this._setTrackingBlock(await this._fetchBlockByNumber(t.result.number)))}async _initSubscription(){this._provider.on("data",this._handleNewBlockNotification);let e=await o(this._provider.sendAsync||this._provider.send)({jsonrpc:"2.0",id:(new Date).getTime(),method:"eth_subscribe",params:["newHeads"]});this._subscriptionId=e.result}async _removeSubscription(){if(!this._subscriptionId)throw new Error("Not subscribed.");this._provider.removeListener("data",this._handleNewBlockNotification),await o(this._provider.sendAsync||this._provider.send)({jsonrpc:"2.0",id:(new Date).getTime(),method:"eth_unsubscribe",params:[this._subscriptionId]}),delete this._subscriptionId}_fetchLatestBlock(){return o(this._query.getBlockByNumber).call(this._query,"latest",!0)}_fetchBlockByNumber(e){const t=a.formatHex(e);return o(this._query.getBlockByNumber).call(this._query,t,!0)}}},{"./hexUtils":125,"eth-query":135,events:157,pify:252}],127:[function(e,t,r){(function(t){var n=e("js-sha3").keccak_256,i=e("idna-uts46-hx");function o(e){return e?i.toUnicode(e,{useStd3ASCII:!0,transitional:!1}):e}r.hash=function(e){for(var r="",i=0;i<32;i++)r+="00";if(name=o(e),name){var a=name.split(".");for(i=a.length-1;i>=0;i--){var s=n(a[i]);r=n(new t(r+s,"hex"))}}return"0x"+r},r.normalize=o}).call(this,e("buffer").Buffer)},{buffer:84,"idna-uts46-hx":177,"js-sha3":128}],128:[function(e,t,r){(function(e,r){!function(){"use strict";var n="object"==typeof window?window:{};!n.JS_SHA3_NO_NODE_JS&&"object"==typeof e&&e.versions&&e.versions.node&&(n=r);for(var i=!n.JS_SHA3_NO_COMMON_JS&&"object"==typeof t&&t.exports,o="0123456789abcdef".split(""),a=[0,8,16,24],s=[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],u=[224,256,384,512],c=["hex","buffer","arrayBuffer","array"],f=function(e,t,r){return function(n){return new _(e,t,e).update(n)[r]()}},h=function(e,t,r){return function(n,i){return new _(e,t,i).update(n)[r]()}},l=function(e,t){var r=f(e,t,"hex");r.create=function(){return new _(e,t,e)},r.update=function(e){return r.create().update(e)};for(var n=0;n>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var n=0;n<50;++n)this.s[n]=0}_.prototype.update=function(e){var t="string"!=typeof e;t&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e));for(var r,n,i=e.length,o=this.blocks,s=this.byteCount,u=this.blockCount,c=0,f=this.s;c>2]|=e[c]<>2]|=n<>2]|=(192|n>>6)<>2]|=(128|63&n)<=57344?(o[r>>2]|=(224|n>>12)<>2]|=(128|n>>6&63)<>2]|=(128|63&n)<>2]|=(240|n>>18)<>2]|=(128|n>>12&63)<>2]|=(128|n>>6&63)<>2]|=(128|63&n)<=s){for(this.start=r-s,this.block=o[u],r=0;r>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t>4&15]+o[15&e]+o[e>>12&15]+o[e>>8&15]+o[e>>20&15]+o[e>>16&15]+o[e>>28&15]+o[e>>24&15];s%t==0&&(A(r),a=0)}return i&&(e=r[a],i>0&&(u+=o[e>>4&15]+o[15&e]),i>1&&(u+=o[e>>12&15]+o[e>>8&15]),i>2&&(u+=o[e>>20&15]+o[e>>16&15])),u},_.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,i=this.extraBytes,o=0,a=0,s=this.outputBits>>3;e=i?new ArrayBuffer(n+1<<2):new ArrayBuffer(s);for(var u=new Uint32Array(e);a>8&255,u[e+2]=t>>16&255,u[e+3]=t>>24&255;s%r==0&&A(n)}return o&&(e=s<<2,t=n[a],o>0&&(u[e]=255&t),o>1&&(u[e+1]=t>>8&255),o>2&&(u[e+2]=t>>16&255)),u};var A=function(e){var t,r,n,i,o,a,u,c,f,h,l,d,p,b,y,m,v,g,w,_,A,E,x,k,S,M,I,T,U,j,B,P,C,N,R,L,O,D,F,q,H,z,K,V,G,W,Y,X,Z,J,$,Q,ee,te,re,ne,ie,oe,ae,se,ue,ce,fe;for(n=0;n<48;n+=2)i=e[0]^e[10]^e[20]^e[30]^e[40],o=e[1]^e[11]^e[21]^e[31]^e[41],a=e[2]^e[12]^e[22]^e[32]^e[42],u=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],f=e[5]^e[15]^e[25]^e[35]^e[45],h=e[6]^e[16]^e[26]^e[36]^e[46],l=e[7]^e[17]^e[27]^e[37]^e[47],t=(d=e[8]^e[18]^e[28]^e[38]^e[48])^(a<<1|u>>>31),r=(p=e[9]^e[19]^e[29]^e[39]^e[49])^(u<<1|a>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=i^(c<<1|f>>>31),r=o^(f<<1|c>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=a^(h<<1|l>>>31),r=u^(l<<1|h>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=c^(d<<1|p>>>31),r=f^(p<<1|d>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=h^(i<<1|o>>>31),r=l^(o<<1|i>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,b=e[0],y=e[1],W=e[11]<<4|e[10]>>>28,Y=e[10]<<4|e[11]>>>28,T=e[20]<<3|e[21]>>>29,U=e[21]<<3|e[20]>>>29,se=e[31]<<9|e[30]>>>23,ue=e[30]<<9|e[31]>>>23,z=e[40]<<18|e[41]>>>14,K=e[41]<<18|e[40]>>>14,N=e[2]<<1|e[3]>>>31,R=e[3]<<1|e[2]>>>31,m=e[13]<<12|e[12]>>>20,v=e[12]<<12|e[13]>>>20,X=e[22]<<10|e[23]>>>22,Z=e[23]<<10|e[22]>>>22,j=e[33]<<13|e[32]>>>19,B=e[32]<<13|e[33]>>>19,ce=e[42]<<2|e[43]>>>30,fe=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,L=e[14]<<6|e[15]>>>26,O=e[15]<<6|e[14]>>>26,g=e[25]<<11|e[24]>>>21,w=e[24]<<11|e[25]>>>21,J=e[34]<<15|e[35]>>>17,$=e[35]<<15|e[34]>>>17,P=e[45]<<29|e[44]>>>3,C=e[44]<<29|e[45]>>>3,k=e[6]<<28|e[7]>>>4,S=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,ie=e[16]<<23|e[17]>>>9,D=e[26]<<25|e[27]>>>7,F=e[27]<<25|e[26]>>>7,_=e[36]<<21|e[37]>>>11,A=e[37]<<21|e[36]>>>11,Q=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,V=e[8]<<27|e[9]>>>5,G=e[9]<<27|e[8]>>>5,M=e[18]<<20|e[19]>>>12,I=e[19]<<20|e[18]>>>12,oe=e[29]<<7|e[28]>>>25,ae=e[28]<<7|e[29]>>>25,q=e[38]<<8|e[39]>>>24,H=e[39]<<8|e[38]>>>24,E=e[48]<<14|e[49]>>>18,x=e[49]<<14|e[48]>>>18,e[0]=b^~m&g,e[1]=y^~v&w,e[10]=k^~M&T,e[11]=S^~I&U,e[20]=N^~L&D,e[21]=R^~O&F,e[30]=V^~W&X,e[31]=G^~Y&Z,e[40]=te^~ne&oe,e[41]=re^~ie&ae,e[2]=m^~g&_,e[3]=v^~w&A,e[12]=M^~T&j,e[13]=I^~U&B,e[22]=L^~D&q,e[23]=O^~F&H,e[32]=W^~X&J,e[33]=Y^~Z&$,e[42]=ne^~oe&se,e[43]=ie^~ae&ue,e[4]=g^~_&E,e[5]=w^~A&x,e[14]=T^~j&P,e[15]=U^~B&C,e[24]=D^~q&z,e[25]=F^~H&K,e[34]=X^~J&Q,e[35]=Z^~$&ee,e[44]=oe^~se&ce,e[45]=ae^~ue&fe,e[6]=_^~E&b,e[7]=A^~x&y,e[16]=j^~P&k,e[17]=B^~C&S,e[26]=q^~z&N,e[27]=H^~K&R,e[36]=J^~Q&V,e[37]=$^~ee&G,e[46]=se^~ce&te,e[47]=ue^~fe&re,e[8]=E^~b&m,e[9]=x^~y&v,e[18]=P^~k&M,e[19]=C^~S&I,e[28]=z^~N&L,e[29]=K^~R&O,e[38]=Q^~V&W,e[39]=ee^~G&Y,e[48]=ce^~te&ne,e[49]=fe^~re&ie,e[0]^=s[n],e[1]^=s[n+1]};if(i)t.exports=p;else for(y=0;y{setTimeout(t,e)})}function c(e){const t=e.toString();return s.some(e=>t.includes(e))}async function f(e,t,r){const{fetchUrl:n,fetchParams:a}=h({network:e,req:t}),s=await o(n,a),u=await s.text();if(!s.ok)switch(s.status){case 405:throw new i.MethodNotFound;case 418:throw l("Request is being rate limited.");case 503:case 504:throw function(){let e="Gateway timeout. The request took too long to process. ";return e+="This can happen when querying logs over too wide a block range.",l("Gateway timeout. The request took too long to process. This can happen when querying logs over too wide a block range.")}();default:throw l(u)}if("eth_getBlockByNumber"===t.method&&"Not Found"===u)return void(r.result=null);const c=JSON.parse(u);r.result=c.result,r.error=c.error}function h({network:e,req:t}){const r=function(e){return{id:e.id,jsonrpc:e.jsonrpc,method:e.method,params:e.params}}(t),{method:n,params:i}=r,o={};let s=`https://api.infura.io/v1/jsonrpc/${e}`;if(a.includes(n))o.method="POST",o.headers={Accept:"application/json","Content-Type":"application/json"},o.body=JSON.stringify(r);else{o.method="GET",s+=`/${n}?params=${encodeURIComponent(JSON.stringify(i))}`}return{fetchUrl:s,fetchParams:o}}function l(e){const t=new Error(e);return new i.InternalError(t)}t.exports=function(e={}){const t=e.network||"mainnet",r=e.maxAttempts||5;if(!r)throw new Error(`Invalid value for 'maxAttempts': "${r}" (${typeof r})`);return n(async(e,n,i)=>{for(let i=1;i<=r;i++)try{await f(t,e,n);break}catch(e){if(!c(e))throw e;const t=r-i;if(!t){const t=`InfuraProvider - cannot complete request. All retries exhausted.\nOriginal Error:\n${e.toString()}\n\n`,r=new Error(t);throw r}await u(1e3)}})},t.exports.fetchConfigFromReq=h},{"cross-fetch":96,"json-rpc-engine/src/createAsyncMiddleware":187,"json-rpc-error":189}],131:[function(e,t,r){t.exports=function(e){return{sendAsync:e.handle.bind(e)}}},{}],132:[function(e,t,r){var n=function(e,t){for(var r=[],n=0;n>6|192);else{if(i>55295&&i<56320){if(++n==e.length)return null;var o=e.charCodeAt(n);if(o<56320||o>57343)return null;r+=t((i=65536+((1023&i)<<10)+(1023&o))>>18|240),r+=t(i>>12&63|128)}else r+=t(i>>12|224);r+=t(i>>6&63|128)}r+=t(63&i|128)}}return r},toString:function(e){for(var t="",r=0,o=i(e);r127){if(a>191&&a<224){if(r>=o)return null;a=(31&a)<<6|63&n(e,r)}else if(a>223&&a<240){if(r+1>=o)return null;a=(15&a)<<12|(63&n(e,r))<<6|63&n(e,++r)}else{if(!(a>239&&a<248))return null;if(r+2>=o)return null;a=(7&a)<<18|(63&n(e,r))<<12|(63&n(e,++r))<<6|63&n(e,++r)}++r}if(a<=65535)t+=String.fromCharCode(a);else{if(!(a<=1114111))return null;a-=65536,t+=String.fromCharCode(a>>10|55296),t+=String.fromCharCode(1023&a|56320)}}return t},fromNumber:function(e){var t=e.toString(16);return t.length%2==0?"0x"+t:"0x0"+t},toNumber:function(e){return parseInt(e.slice(2),16)},fromNat:function(e){return"0x0"===e?"0x":e.length%2==0?e:"0x0"+e.slice(2)},toNat:function(e){return"0"===e[2]?"0x"+e.slice(3):e},fromArray:a,toArray:o,fromUint8Array:function(e){return a([].slice.call(e,0))},toUint8Array:function(e){return new Uint8Array(o(e))}}},{"./array.js":132}],134:[function(e,t,r){var n="0123456789abcdef".split(""),i=[1,256,65536,16777216],o=[0,8,16,24],a=[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],s=function(e){var t,r,n,i,o,s,u,c,f,h,l,d,p,b,y,m,v,g,w,_,A,E,x,k,S,M,I,T,U,j,B,P,C,N,R,L,O,D,F,q,H,z,K,V,G,W,Y,X,Z,J,$,Q,ee,te,re,ne,ie,oe,ae,se,ue,ce,fe;for(n=0;n<48;n+=2)i=e[0]^e[10]^e[20]^e[30]^e[40],o=e[1]^e[11]^e[21]^e[31]^e[41],s=e[2]^e[12]^e[22]^e[32]^e[42],u=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],f=e[5]^e[15]^e[25]^e[35]^e[45],h=e[6]^e[16]^e[26]^e[36]^e[46],l=e[7]^e[17]^e[27]^e[37]^e[47],t=(d=e[8]^e[18]^e[28]^e[38]^e[48])^(s<<1|u>>>31),r=(p=e[9]^e[19]^e[29]^e[39]^e[49])^(u<<1|s>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=i^(c<<1|f>>>31),r=o^(f<<1|c>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=s^(h<<1|l>>>31),r=u^(l<<1|h>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=c^(d<<1|p>>>31),r=f^(p<<1|d>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=h^(i<<1|o>>>31),r=l^(o<<1|i>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,b=e[0],y=e[1],W=e[11]<<4|e[10]>>>28,Y=e[10]<<4|e[11]>>>28,T=e[20]<<3|e[21]>>>29,U=e[21]<<3|e[20]>>>29,se=e[31]<<9|e[30]>>>23,ue=e[30]<<9|e[31]>>>23,z=e[40]<<18|e[41]>>>14,K=e[41]<<18|e[40]>>>14,N=e[2]<<1|e[3]>>>31,R=e[3]<<1|e[2]>>>31,m=e[13]<<12|e[12]>>>20,v=e[12]<<12|e[13]>>>20,X=e[22]<<10|e[23]>>>22,Z=e[23]<<10|e[22]>>>22,j=e[33]<<13|e[32]>>>19,B=e[32]<<13|e[33]>>>19,ce=e[42]<<2|e[43]>>>30,fe=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,L=e[14]<<6|e[15]>>>26,O=e[15]<<6|e[14]>>>26,g=e[25]<<11|e[24]>>>21,w=e[24]<<11|e[25]>>>21,J=e[34]<<15|e[35]>>>17,$=e[35]<<15|e[34]>>>17,P=e[45]<<29|e[44]>>>3,C=e[44]<<29|e[45]>>>3,k=e[6]<<28|e[7]>>>4,S=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,ie=e[16]<<23|e[17]>>>9,D=e[26]<<25|e[27]>>>7,F=e[27]<<25|e[26]>>>7,_=e[36]<<21|e[37]>>>11,A=e[37]<<21|e[36]>>>11,Q=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,V=e[8]<<27|e[9]>>>5,G=e[9]<<27|e[8]>>>5,M=e[18]<<20|e[19]>>>12,I=e[19]<<20|e[18]>>>12,oe=e[29]<<7|e[28]>>>25,ae=e[28]<<7|e[29]>>>25,q=e[38]<<8|e[39]>>>24,H=e[39]<<8|e[38]>>>24,E=e[48]<<14|e[49]>>>18,x=e[49]<<14|e[48]>>>18,e[0]=b^~m&g,e[1]=y^~v&w,e[10]=k^~M&T,e[11]=S^~I&U,e[20]=N^~L&D,e[21]=R^~O&F,e[30]=V^~W&X,e[31]=G^~Y&Z,e[40]=te^~ne&oe,e[41]=re^~ie&ae,e[2]=m^~g&_,e[3]=v^~w&A,e[12]=M^~T&j,e[13]=I^~U&B,e[22]=L^~D&q,e[23]=O^~F&H,e[32]=W^~X&J,e[33]=Y^~Z&$,e[42]=ne^~oe&se,e[43]=ie^~ae&ue,e[4]=g^~_&E,e[5]=w^~A&x,e[14]=T^~j&P,e[15]=U^~B&C,e[24]=D^~q&z,e[25]=F^~H&K,e[34]=X^~J&Q,e[35]=Z^~$&ee,e[44]=oe^~se&ce,e[45]=ae^~ue&fe,e[6]=_^~E&b,e[7]=A^~x&y,e[16]=j^~P&k,e[17]=B^~C&S,e[26]=q^~z&N,e[27]=H^~K&R,e[36]=J^~Q&V,e[37]=$^~ee&G,e[46]=se^~ce&te,e[47]=ue^~fe&re,e[8]=E^~b&m,e[9]=x^~y&v,e[18]=P^~k&M,e[19]=C^~S&I,e[28]=z^~N&L,e[29]=K^~R&O,e[38]=Q^~V&W,e[39]=ee^~G&Y,e[48]=ce^~te&ne,e[49]=fe^~re&ie,e[0]^=a[n],e[1]^=a[n+1]},u=function(e){return function(t){var r;if("0x"===t.slice(0,2)){r=[];for(var a=2,u=t.length;a>2]|=t[d]<>2]|=r<>2]|=(192|r>>6)<>2]|=(128|63&r)<=57344?(u[y>>2]|=(224|r>>12)<>2]|=(128|r>>6&63)<>2]|=(128|63&r)<>2]|=(240|r>>18)<>2]|=(128|r>>12&63)<>2]|=(128|r>>6&63)<>2]|=(128|63&r)<=c){for(e.start=y-c,e.block=u[f],y=0;y>2]|=i[3&y],e.lastByteIndex===c)for(u[0]=u[f],y=1;y>4&15]+n[15&p]+n[p>>12&15]+n[p>>8&15]+n[p>>20&15]+n[p>>16&15]+n[p>>28&15]+n[p>>24&15];m%f==0&&(s(l),y=0)}return"0x"+b}(function(e){return{blocks:[],reset:!0,block:0,start:0,blockCount:1600-(e<<1)>>5,outputBlocks:e>>5,s:(t=[0,0,0,0,0,0,0,0,0,0],[].concat(t,t,t,t,t))};var t}(e),r)}};t.exports={keccak256:u(256),keccak512:u(512),keccak256s:u(256),keccak512s:u(512)}},{}],135:[function(e,t,r){const n=e("xtend"),i=e("json-rpc-random-id")();function o(e){this.currentProvider=e}function a(e){return function(){var t=[].slice.call(arguments),r=t.pop();this.sendAsync({method:e,params:t},r)}}function s(e,t){return function(){var r=[].slice.call(arguments),n=r.pop();r.lengtho)throw new Error("Elements exceed array size: "+o);for(d in h=[],e=e.slice(0,e.lastIndexOf("[")),"string"==typeof t&&(t=JSON.parse(t)),t)h.push(l(e,t[d]));if("dynamic"===o){var p=l("uint256",t.length);h.unshift(p)}return r.concat(h)}if("bytes"===e)return t=new r(t),h=r.concat([l("uint256",t.length),t]),t.length%32!=0&&(h=r.concat([h,n.zeros(32-t.length%32)])),h;if(e.startsWith("bytes")){if((o=s(e))<1||o>32)throw new Error("Invalid bytes width: "+o);return n.setLengthRight(t,32)}if(e.startsWith("uint")){if((o=s(e))%8||o<8||o>256)throw new Error("Invalid uint width: "+o);if((a=f(t)).bitLength()>o)throw new Error("Supplied uint exceeds width: "+o+" vs "+a.bitLength());if(a<0)throw new Error("Supplied uint is negative");return a.toArrayLike(r,"be",32)}if(e.startsWith("int")){if((o=s(e))%8||o<8||o>256)throw new Error("Invalid int width: "+o);if((a=f(t)).bitLength()>o)throw new Error("Supplied int exceeds width: "+o+" vs "+a.bitLength());return a.toTwos(256).toArrayLike(r,"be",32)}if(e.startsWith("ufixed")){if(o=u(e),(a=f(t))<0)throw new Error("Supplied ufixed is negative");return l("uint256",a.mul(new i(2).pow(new i(o[1]))))}if(e.startsWith("fixed"))return o=u(e),l("int256",f(t).mul(new i(2).pow(new i(o[1]))));throw new Error("Unsupported or invalid type: "+e)}function d(e,t,n){var o,a,s,u;if("string"==typeof e&&(e=p(e)),"address"===e.name)return d(e.rawType,t,n).toArrayLike(r,"be",20).toString("hex");if("bool"===e.name)return d(e.rawType,t,n).toString()===new i(1).toString();if("string"===e.name){var c=d(e.rawType,t,n);return new r(c,"utf8").toString()}if(e.isArray){for(s=[],o=e.size,"dynamic"===e.size&&(o=d("uint256",t,n=d("uint256",t,n).toNumber()).toNumber(),n+=32),u=0;ue.size)throw new Error("Decoded int exceeds width: "+e.size+" vs "+a.bitLength());return a}if(e.name.startsWith("int")){if((a=new i(t.slice(n,n+32),16,"be").fromTwos(256)).bitLength()>e.size)throw new Error("Decoded uint exceeds width: "+e.size+" vs "+a.bitLength());return a}if(e.name.startsWith("ufixed")){if(o=new i(2).pow(new i(e.size[1])),!(a=d("uint256",t,n)).mod(o).isZero())throw new Error("Decimals not supported yet");return a.div(o)}if(e.name.startsWith("fixed")){if(o=new i(2).pow(new i(e.size[1])),!(a=d("int256",t,n)).mod(o).isZero())throw new Error("Decimals not supported yet");return a.div(o)}throw new Error("Unsupported or invalid type: "+e.name)}function p(e){var t,r,n;if(y(e)){t=c(e);var i=e.slice(0,e.lastIndexOf("["));return i=p(i),r={isArray:!0,name:e,size:t,memoryUsage:"dynamic"===t?32:i.memoryUsage*t,subArray:i}}switch(e){case"address":n="uint160";break;case"bool":n="uint8";break;case"string":n="bytes"}if(r={rawType:n,name:e,memoryUsage:32},e.startsWith("bytes")&&"bytes"!==e||e.startsWith("uint")||e.startsWith("int")?r.size=s(e):(e.startsWith("ufixed")||e.startsWith("fixed"))&&(r.size=u(e)),e.startsWith("bytes")&&"bytes"!==e&&(r.size<1||r.size>32))throw new Error("Invalid bytes width: "+r.size);if((e.startsWith("uint")||e.startsWith("int"))&&(r.size%8||r.size<8||r.size>256))throw new Error("Invalid int/uint width: "+r.size);return r}function b(e){return"string"===e||"bytes"===e||"dynamic"===c(e)}function y(e){return e.lastIndexOf("]")===e.length-1}function m(e,t){return e.startsWith("address")||e.startsWith("bytes")?"0x"+t.toString("hex"):t.toString()}o.eventID=function(e,t){var i=e+"("+t.map(a).join(",")+")";return n.sha3(new r(i))},o.methodID=function(e,t){return o.eventID(e,t).slice(0,4)},o.rawEncode=function(e,t){var n=[],i=[],o=0;e.forEach(function(e){if(y(e)){var t=c(e);o+="dynamic"!==t?32*t:32}else o+=32});for(var s=0;s32)throw new Error("Invalid bytes width: "+i);u.push(n.setLengthRight(l,i))}else if(h.startsWith("uint")){if((i=s(h))%8||i<8||i>256)throw new Error("Invalid uint width: "+i);if((o=f(l)).bitLength()>i)throw new Error("Supplied uint exceeds width: "+i+" vs "+o.bitLength());u.push(o.toArrayLike(r,"be",i/8))}else{if(!h.startsWith("int"))throw new Error("Unsupported or invalid type: "+h);if((i=s(h))%8||i<8||i>256)throw new Error("Invalid int width: "+i);if((o=f(l)).bitLength()>i)throw new Error("Supplied int exceeds width: "+i+" vs "+o.bitLength());u.push(o.toTwos(i).toArrayLike(r,"be",i/8))}}return r.concat(u)},o.soliditySHA3=function(e,t){return n.sha3(o.solidityPack(e,t))},o.soliditySHA256=function(e,t){return n.sha256(o.solidityPack(e,t))},o.solidityRIPEMD160=function(e,t){return n.ripemd160(o.solidityPack(e,t),!0)},o.fromSerpent=function(e){for(var t,r=[],n=0;n="0"&&t<="9");)o+=e[a]-"0",a++;n=a-1,r.push(o)}else if("i"===i)r.push("int256");else{if("a"!==i)throw new Error("Unsupported or invalid type: "+i);r.push("int256[]")}}return r},o.toSerpent=function(e){for(var t=[],r=0;r0){var r=this.raw.slice();this.v=this._chainId,this.r=0,this.s=0,t=this.raw,this.raw=r}else t=this.raw.slice(0,6);return n.rlphash(t)},e.prototype.getChainId=function(){return this._chainId},e.prototype.getSenderAddress=function(){if(this._from)return this._from;var e=this.getSenderPublicKey();return this._from=n.publicToAddress(e),this._from},e.prototype.getSenderPublicKey=function(){if(!(this._senderPubKey&&this._senderPubKey.length||this.verifySignature()))throw new Error("Invalid Signature");return this._senderPubKey},e.prototype.verifySignature=function(){var e=this.hash(!1);if(this._homestead&&1===new o(this.s).cmp(a))return!1;try{var t=n.bufferToInt(this.v);this._chainId>0&&(t-=2*this._chainId+8),this._senderPubKey=n.ecrecover(e,t,this.r,this.s)}catch(e){return!1}return!!this._senderPubKey},e.prototype.sign=function(e){var t=this.hash(!1),r=n.ecsign(t,e);this._chainId>0&&(r.v+=2*this._chainId+8),Object.assign(this,r)},e.prototype.getDataFee=function(){for(var e=this.raw[5],t=new o(0),r=0;r0&&t.push(["gas limit is too low. Need at least "+this.getBaseFee()]),void 0===e||!1===e?0===t.length:t.join(" ")},e}();t.exports=s}).call(this,e("buffer").Buffer)},{buffer:84,"ethereum-common/params.json":137,"ethereumjs-util":141}],141:[function(e,t,r){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=e("keccak"),o=e("secp256k1"),a=e("assert"),s=e("rlp"),u=e("bn.js"),c=e("create-hash"),f=e("safe-buffer").Buffer;Object.assign(r,e("ethjs-util")),r.MAX_INTEGER=new u("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",16),r.TWO_POW256=new u("10000000000000000000000000000000000000000000000000000000000000000",16),r.KECCAK256_NULL_S="c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470",r.SHA3_NULL_S=r.KECCAK256_NULL_S,r.KECCAK256_NULL=f.from(r.KECCAK256_NULL_S,"hex"),r.SHA3_NULL=r.KECCAK256_NULL,r.KECCAK256_RLP_ARRAY_S="1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",r.SHA3_RLP_ARRAY_S=r.KECCAK256_RLP_ARRAY_S,r.KECCAK256_RLP_ARRAY=f.from(r.KECCAK256_RLP_ARRAY_S,"hex"),r.SHA3_RLP_ARRAY=r.KECCAK256_RLP_ARRAY,r.KECCAK256_RLP_S="56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",r.SHA3_RLP_S=r.KECCAK256_RLP_S,r.KECCAK256_RLP=f.from(r.KECCAK256_RLP_S,"hex"),r.SHA3_RLP=r.KECCAK256_RLP,r.BN=u,r.rlp=s,r.secp256k1=o,r.zeros=function(e){return f.allocUnsafe(e).fill(0)},r.zeroAddress=function(){var e=r.zeros(20);return r.bufferToHex(e)},r.setLengthLeft=r.setLength=function(e,t,n){var i=r.zeros(t);return e=r.toBuffer(e),n?e.length0&&"0"===t.toString();)t=(e=e.slice(1))[0];return e},r.toBuffer=function(e){if(!f.isBuffer(e))if(Array.isArray(e))e=f.from(e);else if("string"==typeof e)e=r.isHexString(e)?f.from(r.padToEven(r.stripHexPrefix(e)),"hex"):f.from(e);else if("number"==typeof e)e=r.intToBuffer(e);else if(null==e)e=f.allocUnsafe(0);else if(u.isBN(e))e=e.toArrayLike(f);else{if(!e.toArray)throw new Error("invalid type");e=f.from(e.toArray())}return e},r.bufferToInt=function(e){return new u(r.toBuffer(e)).toNumber()},r.bufferToHex=function(e){return"0x"+(e=r.toBuffer(e)).toString("hex")},r.fromSigned=function(e){return new u(e).fromTwos(256)},r.toUnsigned=function(e){return f.from(e.toTwos(256).toArray())},r.keccak=function(e,t){return e=r.toBuffer(e),t||(t=256),i("keccak"+t).update(e).digest()},r.keccak256=function(e){return r.keccak(e)},r.sha3=r.keccak,r.sha256=function(e){return e=r.toBuffer(e),c("sha256").update(e).digest()},r.ripemd160=function(e,t){e=r.toBuffer(e);var n=c("rmd160").update(e).digest();return!0===t?r.setLength(n,32):n},r.rlphash=function(e){return r.keccak(s.encode(e))},r.isValidPrivate=function(e){return o.privateKeyVerify(e)},r.isValidPublic=function(e,t){return 64===e.length?o.publicKeyVerify(f.concat([f.from([4]),e])):!!t&&o.publicKeyVerify(e)},r.pubToAddress=r.publicToAddress=function(e,t){return e=r.toBuffer(e),t&&64!==e.length&&(e=o.publicKeyConvert(e,!1).slice(1)),a(64===e.length),r.keccak(e).slice(-20)};var h=r.privateToPublic=function(e){return e=r.toBuffer(e),o.publicKeyCreate(e,!1).slice(1)};r.importPublic=function(e){return 64!==(e=r.toBuffer(e)).length&&(e=o.publicKeyConvert(e,!1).slice(1)),e},r.ecsign=function(e,t){var r=o.sign(e,t),n={};return n.r=r.signature.slice(0,32),n.s=r.signature.slice(32,64),n.v=r.recovery+27,n},r.hashPersonalMessage=function(e){var t=r.toBuffer("Ethereum Signed Message:\n"+e.length.toString());return r.keccak(f.concat([t,e]))},r.ecrecover=function(e,t,n,i){var a=f.concat([r.setLength(n,32),r.setLength(i,32)],64),s=t-27;if(0!==s&&1!==s)throw new Error("Invalid signature v value");var u=o.recover(e,a,s);return o.publicKeyConvert(u,!1).slice(1)},r.toRpcSig=function(e,t,n){if(27!==e&&28!==e)throw new Error("Invalid recovery id");return r.bufferToHex(f.concat([r.setLengthLeft(t,32),r.setLengthLeft(n,32),r.toBuffer(e-27)]))},r.fromRpcSig=function(e){if(65!==(e=r.toBuffer(e)).length)throw new Error("Invalid signature length");var t=e[64];return t<27&&(t+=27),{v:t,r:e.slice(0,32),s:e.slice(32,64)}},r.privateToAddress=function(e){return r.publicToAddress(h(e))},r.isValidAddress=function(e){return/^0x[0-9a-fA-F]{40}$/.test(e)},r.isZeroAddress=function(e){return r.zeroAddress()===r.addHexPrefix(e)},r.toChecksumAddress=function(e){e=r.stripHexPrefix(e).toLowerCase();for(var t=r.keccak(e).toString("hex"),n="0x",i=0;i=8?n+=e[i].toUpperCase():n+=e[i];return n},r.isValidChecksumAddress=function(e){return r.isValidAddress(e)&&r.toChecksumAddress(e)===e},r.generateAddress=function(e,t){return e=r.toBuffer(e),t=(t=new u(t)).isZero()?null:f.from(t.toArray()),r.rlphash([e,t]).slice(-20)},r.isPrecompiled=function(e){var t=r.unpad(e);return 1===t.length&&t[0]>=1&&t[0]<=8},r.addHexPrefix=function(e){return"string"!=typeof e?e:r.isHexPrefixed(e)?e:"0x"+e},r.isValidSignature=function(e,t,r,n){var i=new u("7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0",16),o=new u("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",16);return 32===t.length&&32===r.length&&((27===e||28===e)&&(t=new u(t),r=new u(r),!(t.isZero()||t.gt(o)||r.isZero()||r.gt(o))&&(!1!==n||1!==new u(r).cmp(i))))},r.baToJSON=function(e){if(f.isBuffer(e))return"0x"+e.toString("hex");if(e instanceof Array){for(var t=[],n=0;n=i.length,"The field "+t.name+" must not have more "+t.length+" bytes")):t.allowZero&&0===i.length||!t.length||a(t.length===i.length,"The field "+t.name+" must have byte length of "+t.length),e.raw[n]=i}e._fields.push(t.name),Object.defineProperty(e,t.name,{enumerable:!0,configurable:!0,get:i,set:o}),t.default&&(e[t.name]=t.default),t.alias&&Object.defineProperty(e,t.alias,{enumerable:!1,configurable:!0,set:o,get:i})}),i)if("string"==typeof i&&(i=f.from(r.stripHexPrefix(i),"hex")),f.isBuffer(i)&&(i=s.decode(i)),Array.isArray(i)){if(i.length>e._fields.length)throw new Error("wrong number of fields in data");i.forEach(function(t,n){e[e._fields[n]]=r.toBuffer(t)})}else{if("object"!==(void 0===i?"undefined":n(i)))throw new Error("invalid data");var o=Object.keys(i);t.forEach(function(t){-1!==o.indexOf(t.name)&&(e[t.name]=i[t.name]),-1!==o.indexOf(t.alias)&&(e[t.alias]=i[t.alias])})}}},{assert:19,"bn.js":53,"create-hash":91,"ethjs-util":155,keccak:195,rlp:289,"safe-buffer":290,secp256k1:295}],142:[function(e,t,r){arguments[4][128][0].apply(r,arguments)},{_process:257,dup:128}],143:[function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t};Object.defineProperty(r,"__esModule",{value:!0});var a=e("./address"),s=e("./bignumber"),u=e("./bytes"),c=e("./utf8"),f=e("./properties"),h=o(e("./errors")),l=new RegExp(/^bytes([0-9]*)$/),d=new RegExp(/^(u?int)([0-9]*)$/),p=new RegExp(/^(.*)\[([0-9]*)\]$/);r.defaultCoerceFunc=function(e,t){var r=e.match(d);return r&&parseInt(r[2])<=48?t.toNumber():t};var b=new RegExp("^([^)(]*)\\((.*)\\)([^)(]*)$"),y=new RegExp("^[A-Za-z_][A-Za-z0-9_]*$");function m(e){return e.match(/^uint($|[^1-9])/)?e="uint256"+e.substring(4):e.match(/^int($|[^1-9])/)&&(e="int256"+e.substring(3)),e}function v(e,t){function r(t){throw new Error('unexpected character "'+e[t]+'" at position '+t+' in "'+e+'"')}for(var n={type:"",name:"",state:{allowType:!0}},i=n,o=0;o1){var i=r[1].match(b);if(""!=i[1].trim()||""!=i[3].trim())throw new Error("unexpected tokens");L(i[2]).forEach(function(e){t.outputs.push(v(e))})}return t}(e.trim()));throw new Error("unknown signature")};var w=function(){return function(e,t,r,n,i){this.coerceFunc=e,this.name=t,this.type=r,this.localName=n,this.dynamic=i}}(),_=function(e){function t(t){var r=e.call(this,t.coerceFunc,t.name,t.type,void 0,t.dynamic)||this;return f.defineReadOnly(r,"coder",t),r}return i(t,e),t.prototype.encode=function(e){return this.coder.encode(e)},t.prototype.decode=function(e,t){return this.coder.decode(e,t)},t}(w),A=function(e){function t(t,r){return e.call(this,t,"null","",r,!1)||this}return i(t,e),t.prototype.encode=function(e){return u.arrayify([])},t.prototype.decode=function(e,t){if(t>e.length)throw new Error("invalid null");return{consumed:0,value:this.coerceFunc("null",void 0)}},t}(w),E=function(e){function t(t,r,n,i){var o=this,a=(n?"int":"uint")+8*r;return(o=e.call(this,t,a,a,i,!1)||this).size=r,o.signed=n,o}return i(t,e),t.prototype.encode=function(e){try{var t=s.bigNumberify(e);return t=t.toTwos(8*this.size).maskn(8*this.size),this.signed&&(t=t.fromTwos(8*this.size).toTwos(256)),u.padZeros(u.arrayify(t),32)}catch(t){h.throwError("invalid number value",h.INVALID_ARGUMENT,{arg:this.localName,coderType:this.name,value:e})}return null},t.prototype.decode=function(e,t){e.length32)throw new Error;t.set(r)}catch(t){h.throwError("invalid "+this.name+" value",h.INVALID_ARGUMENT,{arg:this.localName,coderType:this.name,value:t.value||e})}return t},t.prototype.decode=function(e,t){return e.length=0?n:"")+"]",s=-1===n||r.dynamic;return(o=e.call(this,t,"array",a,i,s)||this).coder=r,o.length=n,o}return i(t,e),t.prototype.encode=function(e){Array.isArray(e)||h.throwError("expected array value",h.INVALID_ARGUMENT,{arg:this.localName,coderType:"array",value:e});var t=this.length,r=new Uint8Array(0);-1===t&&(t=e.length,r=x.encode(t)),h.checkArgumentCount(t,e.length,"in coder array"+(this.localName?" "+this.localName:""));for(var n=[],i=0;i256||i%8!=0)&&h.throwError("invalid "+r[1]+" bit length",h.INVALID_ARGUMENT,{arg:"param",value:t}),new E(e,i/8,"int"===r[1],t.name);if(r=t.type.match(l))return(0===(i=parseInt(r[1]))||i>32)&&h.throwError("invalid bytes length",h.INVALID_ARGUMENT,{arg:"param",value:t}),new S(e,i,t.name);if(r=t.type.match(p)){var i=parseInt(r[2]||"-1");return(t=f.jsonCopy(t)).type=r[1],new N(e,D(e,t),i,t.name)}return"tuple"===t.type.substring(0,5)?function(e,t,r){t||(t=[]);var n=[];return t.forEach(function(t){n.push(D(e,t))}),new R(e,n,r)}(e,t.components,t.name):""===t.type?new A(e,t.name):(h.throwError("invalid type",h.INVALID_ARGUMENT,{arg:"type",value:t.type}),null)}var F=function(){function e(t){h.checkNew(this,e),t||(t=r.defaultCoerceFunc),f.defineReadOnly(this,"coerceFunc",t)}return e.prototype.encode=function(e,t){e.length!==t.length&&h.throwError("types/values length mismatch",h.INVALID_ARGUMENT,{count:{types:e.length,values:t.length},value:{types:e,values:t}});var r=[];return e.forEach(function(e){var t=null;t="string"==typeof e?v(e):e,r.push(D(this.coerceFunc,t))},this),u.hexlify(new R(this.coerceFunc,r,"_").encode(t))},e.prototype.decode=function(e,t){var r=[];return e.forEach(function(e){var t=null;t="string"==typeof e?v(e):f.jsonCopy(e),r.push(D(this.coerceFunc,t))},this),new R(this.coerceFunc,r,"_").decode(u.arrayify(t),0).value},e}();r.AbiCoder=F,r.defaultAbiCoder=new F},{"./address":144,"./bignumber":145,"./bytes":146,"./errors":147,"./properties":149,"./utf8":152}],144:[function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0});var i=n(e("bn.js")),o=e("./bytes"),a=e("./keccak256"),s=e("./rlp"),u=e("./errors");function c(e){"string"==typeof e&&e.match(/^0x[0-9A-Fa-f]{40}$/)||u.throwError("invalid address",u.INVALID_ARGUMENT,{arg:"address",value:e});for(var t=(e=e.toLowerCase()).substring(2).split(""),r=new Uint8Array(40),n=0;n<40;n++)r[n]=t[n].charCodeAt(0);r=o.arrayify(a.keccak256(r));for(var i=0;i<40;i+=2)r[i>>1]>>4>=8&&(t[i]=t[i].toUpperCase()),(15&r[i>>1])>=8&&(t[i+1]=t[i+1].toUpperCase());return"0x"+t.join("")}for(var f={},h=0;h<10;h++)f[String(h)]=String(h);for(h=0;h<26;h++)f[String.fromCharCode(65+h)]=String(10+h);var l,d=Math.floor((l=9007199254740991,Math.log10?Math.log10(l):Math.log(l)/Math.LN10));function p(e){e=(e=e.toUpperCase()).substring(4)+e.substring(0,2)+"00";var t="";for(e.split("").forEach(function(e){t+=f[e]});t.length>=d;){var r=t.substring(0,d);t=parseInt(r,10)%97+t.substring(r.length)}for(var n=String(98-parseInt(t,10)%97);n.length<2;)n="0"+n;return n}function b(e){var t=null;if("string"!=typeof e&&u.throwError("invalid address",u.INVALID_ARGUMENT,{arg:"address",value:e}),e.match(/^(0x)?[0-9a-fA-F]{40}$/))"0x"!==e.substring(0,2)&&(e="0x"+e),t=c(e),e.match(/([A-F].*[a-f])|([a-f].*[A-F])/)&&t!==e&&u.throwError("bad address checksum",u.INVALID_ARGUMENT,{arg:"address",value:e});else if(e.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){for(e.substring(2,4)!==p(e)&&u.throwError("bad icap checksum",u.INVALID_ARGUMENT,{arg:"address",value:e}),t=new i.default.BN(e.substring(4),36).toString(16);t.length<40;)t="0"+t;t=c("0x"+t)}else u.throwError("invalid address",u.INVALID_ARGUMENT,{arg:"address",value:e});return t}r.getAddress=b,r.getIcapAddress=function(e){for(var t=new i.default.BN(b(e).substring(2),16).toString(36).toUpperCase();t.length<30;)t="0"+t;return"XE"+p("XE00"+t)+t},r.getContractAddress=function(e){if(!e.from)throw new Error("missing from address");var t=e.nonce;return b("0x"+a.keccak256(s.encode([b(e.from),o.stripZeros(o.hexlify(t))])).substring(26))}},{"./bytes":146,"./errors":147,"./keccak256":148,"./rlp":150,"bn.js":53}],145:[function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t};Object.defineProperty(r,"__esModule",{value:!0});var s=o(e("bn.js")),u=e("./bytes"),c=e("./properties"),f=e("./types"),h=a(e("./errors")),l=new s.default.BN(-1);function d(e){var t=e.toString(16);return"-"===t[0]?t.length%2==0?"-0x0"+t.substring(1):"-0x"+t.substring(1):t.length%2==1?"0x0"+t:"0x"+t}function p(e){return m(e)._bn}function b(e){return new y(d(e))}var y=function(e){function t(r){var n=e.call(this)||this;if(h.checkNew(n,t),"string"==typeof r)u.isHexString(r)?("0x"==r&&(r="0x0"),c.defineReadOnly(n,"_hex",r)):"-"===r[0]&&u.isHexString(r.substring(1))?c.defineReadOnly(n,"_hex",r):r.match(/^-?[0-9]*$/)?(""==r&&(r="0"),c.defineReadOnly(n,"_hex",d(new s.default.BN(r)))):h.throwError("invalid BigNumber string value",h.INVALID_ARGUMENT,{arg:"value",value:r});else if("number"==typeof r){parseInt(String(r))!==r&&h.throwError("underflow",h.NUMERIC_FAULT,{operation:"setValue",fault:"underflow",value:r,outputValue:parseInt(String(r))});try{c.defineReadOnly(n,"_hex",d(new s.default.BN(r)))}catch(e){h.throwError("overflow",h.NUMERIC_FAULT,{operation:"setValue",fault:"overflow",details:e.message})}}else r instanceof t?c.defineReadOnly(n,"_hex",r._hex):r.toHexString?c.defineReadOnly(n,"_hex",d(p(r.toHexString()))):u.isArrayish(r)?c.defineReadOnly(n,"_hex",d(new s.default.BN(u.hexlify(r).substring(2),16))):h.throwError("invalid BigNumber value",h.INVALID_ARGUMENT,{arg:"value",value:r});return n}return i(t,e),Object.defineProperty(t.prototype,"_bn",{get:function(){return"-"===this._hex[0]?new s.default.BN(this._hex.substring(3),16).mul(l):new s.default.BN(this._hex.substring(2),16)},enumerable:!0,configurable:!0}),t.prototype.fromTwos=function(e){return b(this._bn.fromTwos(e))},t.prototype.toTwos=function(e){return b(this._bn.toTwos(e))},t.prototype.add=function(e){return b(this._bn.add(p(e)))},t.prototype.sub=function(e){return b(this._bn.sub(p(e)))},t.prototype.div=function(e){return m(e).isZero()&&h.throwError("division by zero",h.NUMERIC_FAULT,{operation:"divide",fault:"division by zero"}),b(this._bn.div(p(e)))},t.prototype.mul=function(e){return b(this._bn.mul(p(e)))},t.prototype.mod=function(e){return b(this._bn.mod(p(e)))},t.prototype.pow=function(e){return b(this._bn.pow(p(e)))},t.prototype.maskn=function(e){return b(this._bn.maskn(e))},t.prototype.eq=function(e){return this._bn.eq(p(e))},t.prototype.lt=function(e){return this._bn.lt(p(e))},t.prototype.lte=function(e){return this._bn.lte(p(e))},t.prototype.gt=function(e){return this._bn.gt(p(e))},t.prototype.gte=function(e){return this._bn.gte(p(e))},t.prototype.isZero=function(){return this._bn.isZero()},t.prototype.toNumber=function(){try{return this._bn.toNumber()}catch(e){h.throwError("overflow",h.NUMERIC_FAULT,{operation:"setValue",fault:"overflow",details:e.message})}return null},t.prototype.toString=function(){return this._bn.toString(10)},t.prototype.toHexString=function(){return this._hex},t}(f.BigNumber);function m(e){return e instanceof y?e:new y(e)}r.bigNumberify=m,r.ConstantNegativeOne=m(-1),r.ConstantZero=m(0),r.ConstantOne=m(1),r.ConstantTwo=m(2),r.ConstantWeiPerEther=m("1000000000000000000")},{"./bytes":146,"./errors":147,"./properties":149,"./types":151,"bn.js":53}],146:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("./errors");function i(e){return!!e._bn}function o(e){return e.slice?e:(e.slice=function(){var t=Array.prototype.slice.call(arguments);return new Uint8Array(Array.prototype.slice.apply(e,t))},e)}function a(e){if(!e||parseInt(String(e.length))!=e.length||"string"==typeof e)return!1;for(var t=0;t=256||parseInt(String(r))!=r)return!1}return!0}function s(e){if(null==e&&n.throwError("cannot convert null value to array",n.INVALID_ARGUMENT,{arg:"value",value:e}),i(e)&&(e=e.toHexString()),"string"==typeof e){var t=e.match(/^(0x)?[0-9a-fA-F]*$/);t||n.throwError("invalid hexidecimal string",n.INVALID_ARGUMENT,{arg:"value",value:e}),"0x"!==t[1]&&n.throwError("hex string must have 0x prefix",n.INVALID_ARGUMENT,{arg:"value",value:e}),(e=e.substring(2)).length%2&&(e="0"+e);for(var r=[],s=0;s>4]+f[15&u])}return"0x"+o.join("")}return n.throwError("invalid hexlify value",null,{arg:"value",value:e}),"never"}function l(e,t){for(c(e)||n.throwError("invalid hex string",n.INVALID_ARGUMENT,{arg:"value",value:e});e.length<2*t+2;)e="0x0"+e.substring(2);return e}function d(e){var t,r=0,i="0x",o="0x";if((t=e)&&null!=t.r&&null!=t.s){null==e.v&&null==e.recoveryParam&&n.throwError("at least on of recoveryParam or v must be specified",n.INVALID_ARGUMENT,{argument:"signature",value:e}),i=l(e.r,32),o=l(e.s,32),"string"==typeof(r=e.v)&&(r=parseInt(r,16));var a=e.recoveryParam;null==a&&null!=e.v&&(a=1-r%2),r=27+a}else{var u=s(e);if(65!==u.length)throw new Error("invalid signature");i=h(u.slice(0,32)),o=h(u.slice(32,64)),27!==(r=u[64])&&28!==r&&(r=27+r%2)}return{r:i,s:o,recoveryParam:r-27,v:r}}r.hexlify=h,r.hexDataLength=function(e){return c(e)&&e.length%2==0?(e.length-2)/2:null},r.hexDataSlice=function(e,t,r){return c(e)||n.throwError("invalid hex data",n.INVALID_ARGUMENT,{arg:"value",value:e}),e.length%2!=0&&n.throwError("hex data length must be even",n.INVALID_ARGUMENT,{arg:"value",value:e}),t=2+2*t,null!=r?"0x"+e.substring(t,t+2*r):"0x"+e.substring(t)},r.hexStripZeros=function(e){for(c(e)||n.throwError("invalid hex string",n.INVALID_ARGUMENT,{arg:"value",value:e});e.length>3&&"0x0"===e.substring(0,3);)e="0x"+e.substring(3);return e},r.hexZeroPad=l,r.splitSignature=d,r.joinSignature=function(e){return h(u([(e=d(e)).r,e.s,e.recoveryParam?"0x1c":"0x1b"]))}},{"./errors":147}],147:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.UNKNOWN_ERROR="UNKNOWN_ERROR",r.NOT_IMPLEMENTED="NOT_IMPLEMENTED",r.MISSING_NEW="MISSING_NEW",r.CALL_EXCEPTION="CALL_EXCEPTION",r.INVALID_ARGUMENT="INVALID_ARGUMENT",r.MISSING_ARGUMENT="MISSING_ARGUMENT",r.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",r.NUMERIC_FAULT="NUMERIC_FAULT",r.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION";var n=!1,i=!1;function o(e,t,n){if(i)throw new Error("unknown error");t||(t=r.UNKNOWN_ERROR),n||(n={});var o=[];Object.keys(n).forEach(function(e){try{o.push(e+"="+JSON.stringify(n[e]))}catch(t){o.push(e+"="+JSON.stringify(n[e].toString()))}});var a=e;o.length&&(e+=" ("+o.join(", ")+")");var s=new Error(e);throw s.reason=a,s.code=t,Object.keys(n).forEach(function(e){s[e]=n[e]}),s}r.throwError=o,r.checkNew=function(e,t){e instanceof t||o("missing new",r.MISSING_NEW,{name:t.name})},r.checkArgumentCount=function(e,t,n){n||(n=""),et&&o("too many arguments"+n,r.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})},r.setCensorship=function(e,t){n&&o("error censorship permanent",r.UNSUPPORTED_OPERATION,{operation:"setCersorship"}),i=!!e,n=!!t}},{}],148:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("js-sha3"),i=e("./bytes");r.keccak256=function(e){return"0x"+n.keccak_256(i.arrayify(e))}},{"./bytes":146,"js-sha3":142}],149:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.defineReadOnly=function(e,t,r){Object.defineProperty(e,t,{enumerable:!0,value:r,writable:!1})},r.defineFrozen=function(e,t,r){var n=JSON.stringify(r);Object.defineProperty(e,t,{enumerable:!0,get:function(){return JSON.parse(n)}})},r.resolveProperties=function(e){var t={},r=[];return Object.keys(e).forEach(function(n){var i=e[n];i instanceof Promise?r.push(i.then(function(e){return t[n]=e,null})):t[n]=i}),Promise.all(r).then(function(){return t})},r.shallowCopy=function(e){var t={};for(var r in e)t[r]=e[r];return t},r.jsonCopy=function(e){return JSON.parse(JSON.stringify(e))}},{}],150:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("./bytes");function i(e){for(var t=[];e;)t.unshift(255&e),e>>=8;return t}function o(e,t,r){for(var n=0,i=0;it+1+n)throw new Error("invalid rlp")}return{consumed:1+n,result:i}}function s(e,t){if(0===e.length)throw new Error("invalid rlp data");if(e[t]>=248){if(t+1+(r=e[t]-247)>e.length)throw new Error("too short");if(t+1+r+(i=o(e,t+1,r))>e.length)throw new Error("to short");return a(e,t,t+1+r,r+i)}if(e[t]>=192){if(t+1+(i=e[t]-192)>e.length)throw new Error("invalid rlp data");return a(e,t,t+1,i)}if(e[t]>=184){var r;if(t+1+(r=e[t]-183)>e.length)throw new Error("invalid rlp data");if(t+1+r+(i=o(e,t+1,r))>e.length)throw new Error("invalid rlp data");return{consumed:1+r+i,result:n.hexlify(e.slice(t+1+r,t+1+r+i))}}if(e[t]>=128){var i;if(t+1+(i=e[t]-128)>e.length)throw new Error("invlaid rlp data");return{consumed:1+i,result:n.hexlify(e.slice(t+1,t+1+i))}}return{consumed:1,result:n.hexlify(e[t])}}r.encode=function(e){return n.hexlify(function e(t){if(Array.isArray(t)){var r=[];return t.forEach(function(t){r=r.concat(e(t))}),r.length<=55?(r.unshift(192+r.length),r):((o=i(r.length)).unshift(247+o.length),o.concat(r))}var o,a=Array.prototype.slice.call(n.arrayify(t));return 1===a.length&&a[0]<=127?a:a.length<=55?(a.unshift(128+a.length),a):((o=i(a.length)).unshift(183+o.length),o.concat(a))}(e))},r.decode=function(e){var t=n.arrayify(e),r=s(t,0);if(r.consumed!==t.length)throw new Error("invalid rlp data");return r.result}},{"./bytes":146}],151:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=function(){return function(){}}();r.BigNumber=n;var i=function(){return function(){}}();r.Indexed=i;var o=function(){return function(){}}();r.MinimalProvider=o;var a=function(){return function(){}}();r.Signer=a;var s=function(){return function(){}}();r.HDNode=s},{}],152:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n,i=e("./bytes");!function(e){e.current="",e.NFC="NFC",e.NFD="NFD",e.NFKC="NFKC",e.NFKD="NFKD"}(n=r.UnicodeNormalizationForm||(r.UnicodeNormalizationForm={})),r.toUtf8Bytes=function(e,t){void 0===t&&(t=n.current),t!=n.current&&(e=e.normalize(t));for(var r=[],o=0,a=0;a>6|192,r[o++]=63&s|128):55296==(64512&s)&&a+1>18|240,r[o++]=s>>12&63|128,r[o++]=s>>6&63|128,r[o++]=63&s|128):(r[o++]=s>>12|224,r[o++]=s>>6&63|128,r[o++]=63&s|128)}return i.arrayify(r)},r.toUtf8String=function(e){e=i.arrayify(e);for(var t="",r=0;r>7!=0){if(n>>6!=2){var o=null;if(n>>5==6)o=1;else if(n>>4==14)o=2;else if(n>>3==30)o=3;else if(n>>2==62)o=4;else{if(n>>1!=126)continue;o=5}if(r+o>e.length){for(;r>6==2;r++);if(r!=e.length)continue;return t}var a,s=n&(1<<8-o-1)-1;for(a=0;a>6!=2)break;s=s<<6|63&u}a==o?s<=65535?t+=String.fromCharCode(s):(s-=65536,t+=String.fromCharCode(55296+(s>>10&1023),56320+(1023&s))):r--}}else t+=String.fromCharCode(n)}return t}},{"./bytes":146}],153:[function(e,t,r){"use strict";var n=e("bn.js"),i=e("number-to-bn"),o=new n(0),a=new n(-1),s={noether:"0",wei:"1",kwei:"1000",Kwei:"1000",babbage:"1000",femtoether:"1000",mwei:"1000000",Mwei:"1000000",lovelace:"1000000",picoether:"1000000",gwei:"1000000000",Gwei:"1000000000",shannon:"1000000000",nanoether:"1000000000",nano:"1000000000",szabo:"1000000000000",microether:"1000000000000",micro:"1000000000000",finney:"1000000000000000",milliether:"1000000000000000",milli:"1000000000000000",ether:"1000000000000000000",kether:"1000000000000000000000",grand:"1000000000000000000000",mether:"1000000000000000000000000",gether:"1000000000000000000000000000",tether:"1000000000000000000000000000000"};function u(e){var t=e?e.toLowerCase():"ether",r=s[t];if("string"!=typeof r)throw new Error("[ethjs-unit] the unit provided "+e+" doesn't exists, please use the one of the following units "+JSON.stringify(s,null,2));return new n(r,10)}function c(e){if("string"==typeof e){if(!e.match(/^-?[0-9.]+$/))throw new Error("while converting number to string, invalid number value '"+e+"', should be a number matching (^-?[0-9.]+).");return e}if("number"==typeof e)return String(e);if("object"==typeof e&&e.toString&&(e.toTwos||e.dividedToIntegerBy))return e.toPrecision?String(e.toPrecision()):e.toString(10);throw new Error("while converting number to string, invalid number value '"+e+"' type "+typeof e+".")}t.exports={unitMap:s,numberToString:c,getValueOfUnit:u,fromWei:function(e,t,r){var n=i(e),c=n.lt(o),f=u(t),h=s[t].length-1||1,l=r||{};c&&(n=n.mul(a));for(var d=n.mod(f).toString(10);d.length2)throw new Error("[ethjs-unit] while converting number "+e+" to wei, too many decimal points");var l=h[0],d=h[1];if(l||(l="0"),d||(d="0"),d.length>o)throw new Error("[ethjs-unit] while converting number "+e+" to wei, too many decimal places");for(;d.length=49&&a<=54?a-49+10:a>=17&&a<=22?a-17+10:15&a}return n}function u(e,t,r,n){for(var i=0,o=Math.min(e.length,r),a=t;a=49?s-49+10:s>=17?s-17+10:s}return i}o.isBN=function(e){return e instanceof o||null!==e&&"object"==typeof e&&e.constructor.wordSize===o.wordSize&&Array.isArray(e.words)},o.max=function(e,t){return e.cmp(t)>0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&i++,16===t?this._parseHex(e,i):this._parseBase(e,t,i),"-"===e[0]&&(this.negative=1),this.strip(),"le"===r&&this._initArray(this.toArray(),t,r)},o.prototype._initNumber=function(e,t,r){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(n(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===r&&this._initArray(this.toArray(),t,r)},o.prototype._initArray=function(e,t,r){if(n("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3)a=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[o]|=a<>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);else if("le"===r)for(i=0,o=0;i>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);return this.strip()},o.prototype._parseHex=function(e,t){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var r=0;r=t;r-=6)i=s(e,r,r+6),this.words[n]|=i<>>26-o&4194303,(o+=24)>=26&&(o-=26,n++);r+6!==t&&(i=s(e,t,r+6),this.words[n]|=i<>>26-o&4194303),this.strip()},o.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=t)n++;n--,i=i/t|0;for(var o=e.length-r,a=o%n,s=Math.min(o,o-a)+r,c=0,f=r;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},o.prototype.inspect=function(){return(this.red?""};var c=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],f=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],h=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(e,t,r){r.negative=t.negative^e.negative;var n=e.length+t.length|0;r.length=n,n=n-1|0;var i=0|e.words[0],o=0|t.words[0],a=i*o,s=67108863&a,u=a/67108864|0;r.words[0]=s;for(var c=1;c>>26,h=67108863&u,l=Math.min(c,t.length-1),d=Math.max(0,c-e.length+1);d<=l;d++){var p=c-d|0;f+=(a=(i=0|e.words[p])*(o=0|t.words[d])+h)/67108864|0,h=67108863&a}r.words[c]=0|h,u=0|f}return 0!==u?r.words[c]=0|u:r.length--,r.strip()}o.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var i=0,o=0,a=0;a>>24-i&16777215)||a!==this.length-1?c[6-u.length]+u+r:u+r,(i+=2)>=26&&(i-=26,a--)}for(0!==o&&(r=o.toString(16)+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var l=f[e],d=h[e];r="";var p=this.clone();for(p.negative=0;!p.isZero();){var b=p.modn(d).toString(e);r=(p=p.idivn(d)).isZero()?b+r:c[l-b.length]+b+r}for(this.isZero()&&(r="0"+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16)},o.prototype.toBuffer=function(e,t){return n(void 0!==a),this.toArrayLike(a,e,t)},o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},o.prototype.toArrayLike=function(e,t,r){var i=this.byteLength(),o=r||Math.max(1,i);n(i<=o,"byte array longer than desired length"),n(o>0,"Requested array length <= 0"),this.strip();var a,s,u="le"===t,c=new e(o),f=this.clone();if(u){for(s=0;!f.isZero();s++)a=f.andln(255),f.iushrn(8),c[s]=a;for(;s=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;re.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,r;this.length>e.length?(t=this,r=e):(t=e,r=this);for(var n=0;ne.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-r),this.strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,i=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<e.length?(r=this,n=e):(r=e,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;oe.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var r,n,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=e):(r=e,n=this);for(var o=0,a=0;a>26,this.words[a]=67108863&t;for(;0!==o&&a>26,this.words[a]=67108863&t;if(0===o&&a>>13,d=0|a[1],p=8191&d,b=d>>>13,y=0|a[2],m=8191&y,v=y>>>13,g=0|a[3],w=8191&g,_=g>>>13,A=0|a[4],E=8191&A,x=A>>>13,k=0|a[5],S=8191&k,M=k>>>13,I=0|a[6],T=8191&I,U=I>>>13,j=0|a[7],B=8191&j,P=j>>>13,C=0|a[8],N=8191&C,R=C>>>13,L=0|a[9],O=8191&L,D=L>>>13,F=0|s[0],q=8191&F,H=F>>>13,z=0|s[1],K=8191&z,V=z>>>13,G=0|s[2],W=8191&G,Y=G>>>13,X=0|s[3],Z=8191&X,J=X>>>13,$=0|s[4],Q=8191&$,ee=$>>>13,te=0|s[5],re=8191&te,ne=te>>>13,ie=0|s[6],oe=8191&ie,ae=ie>>>13,se=0|s[7],ue=8191&se,ce=se>>>13,fe=0|s[8],he=8191&fe,le=fe>>>13,de=0|s[9],pe=8191&de,be=de>>>13;r.negative=e.negative^t.negative,r.length=19;var ye=(c+(n=Math.imul(h,q))|0)+((8191&(i=(i=Math.imul(h,H))+Math.imul(l,q)|0))<<13)|0;c=((o=Math.imul(l,H))+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,n=Math.imul(p,q),i=(i=Math.imul(p,H))+Math.imul(b,q)|0,o=Math.imul(b,H);var me=(c+(n=n+Math.imul(h,K)|0)|0)+((8191&(i=(i=i+Math.imul(h,V)|0)+Math.imul(l,K)|0))<<13)|0;c=((o=o+Math.imul(l,V)|0)+(i>>>13)|0)+(me>>>26)|0,me&=67108863,n=Math.imul(m,q),i=(i=Math.imul(m,H))+Math.imul(v,q)|0,o=Math.imul(v,H),n=n+Math.imul(p,K)|0,i=(i=i+Math.imul(p,V)|0)+Math.imul(b,K)|0,o=o+Math.imul(b,V)|0;var ve=(c+(n=n+Math.imul(h,W)|0)|0)+((8191&(i=(i=i+Math.imul(h,Y)|0)+Math.imul(l,W)|0))<<13)|0;c=((o=o+Math.imul(l,Y)|0)+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,n=Math.imul(w,q),i=(i=Math.imul(w,H))+Math.imul(_,q)|0,o=Math.imul(_,H),n=n+Math.imul(m,K)|0,i=(i=i+Math.imul(m,V)|0)+Math.imul(v,K)|0,o=o+Math.imul(v,V)|0,n=n+Math.imul(p,W)|0,i=(i=i+Math.imul(p,Y)|0)+Math.imul(b,W)|0,o=o+Math.imul(b,Y)|0;var ge=(c+(n=n+Math.imul(h,Z)|0)|0)+((8191&(i=(i=i+Math.imul(h,J)|0)+Math.imul(l,Z)|0))<<13)|0;c=((o=o+Math.imul(l,J)|0)+(i>>>13)|0)+(ge>>>26)|0,ge&=67108863,n=Math.imul(E,q),i=(i=Math.imul(E,H))+Math.imul(x,q)|0,o=Math.imul(x,H),n=n+Math.imul(w,K)|0,i=(i=i+Math.imul(w,V)|0)+Math.imul(_,K)|0,o=o+Math.imul(_,V)|0,n=n+Math.imul(m,W)|0,i=(i=i+Math.imul(m,Y)|0)+Math.imul(v,W)|0,o=o+Math.imul(v,Y)|0,n=n+Math.imul(p,Z)|0,i=(i=i+Math.imul(p,J)|0)+Math.imul(b,Z)|0,o=o+Math.imul(b,J)|0;var we=(c+(n=n+Math.imul(h,Q)|0)|0)+((8191&(i=(i=i+Math.imul(h,ee)|0)+Math.imul(l,Q)|0))<<13)|0;c=((o=o+Math.imul(l,ee)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,n=Math.imul(S,q),i=(i=Math.imul(S,H))+Math.imul(M,q)|0,o=Math.imul(M,H),n=n+Math.imul(E,K)|0,i=(i=i+Math.imul(E,V)|0)+Math.imul(x,K)|0,o=o+Math.imul(x,V)|0,n=n+Math.imul(w,W)|0,i=(i=i+Math.imul(w,Y)|0)+Math.imul(_,W)|0,o=o+Math.imul(_,Y)|0,n=n+Math.imul(m,Z)|0,i=(i=i+Math.imul(m,J)|0)+Math.imul(v,Z)|0,o=o+Math.imul(v,J)|0,n=n+Math.imul(p,Q)|0,i=(i=i+Math.imul(p,ee)|0)+Math.imul(b,Q)|0,o=o+Math.imul(b,ee)|0;var _e=(c+(n=n+Math.imul(h,re)|0)|0)+((8191&(i=(i=i+Math.imul(h,ne)|0)+Math.imul(l,re)|0))<<13)|0;c=((o=o+Math.imul(l,ne)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,n=Math.imul(T,q),i=(i=Math.imul(T,H))+Math.imul(U,q)|0,o=Math.imul(U,H),n=n+Math.imul(S,K)|0,i=(i=i+Math.imul(S,V)|0)+Math.imul(M,K)|0,o=o+Math.imul(M,V)|0,n=n+Math.imul(E,W)|0,i=(i=i+Math.imul(E,Y)|0)+Math.imul(x,W)|0,o=o+Math.imul(x,Y)|0,n=n+Math.imul(w,Z)|0,i=(i=i+Math.imul(w,J)|0)+Math.imul(_,Z)|0,o=o+Math.imul(_,J)|0,n=n+Math.imul(m,Q)|0,i=(i=i+Math.imul(m,ee)|0)+Math.imul(v,Q)|0,o=o+Math.imul(v,ee)|0,n=n+Math.imul(p,re)|0,i=(i=i+Math.imul(p,ne)|0)+Math.imul(b,re)|0,o=o+Math.imul(b,ne)|0;var Ae=(c+(n=n+Math.imul(h,oe)|0)|0)+((8191&(i=(i=i+Math.imul(h,ae)|0)+Math.imul(l,oe)|0))<<13)|0;c=((o=o+Math.imul(l,ae)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,n=Math.imul(B,q),i=(i=Math.imul(B,H))+Math.imul(P,q)|0,o=Math.imul(P,H),n=n+Math.imul(T,K)|0,i=(i=i+Math.imul(T,V)|0)+Math.imul(U,K)|0,o=o+Math.imul(U,V)|0,n=n+Math.imul(S,W)|0,i=(i=i+Math.imul(S,Y)|0)+Math.imul(M,W)|0,o=o+Math.imul(M,Y)|0,n=n+Math.imul(E,Z)|0,i=(i=i+Math.imul(E,J)|0)+Math.imul(x,Z)|0,o=o+Math.imul(x,J)|0,n=n+Math.imul(w,Q)|0,i=(i=i+Math.imul(w,ee)|0)+Math.imul(_,Q)|0,o=o+Math.imul(_,ee)|0,n=n+Math.imul(m,re)|0,i=(i=i+Math.imul(m,ne)|0)+Math.imul(v,re)|0,o=o+Math.imul(v,ne)|0,n=n+Math.imul(p,oe)|0,i=(i=i+Math.imul(p,ae)|0)+Math.imul(b,oe)|0,o=o+Math.imul(b,ae)|0;var Ee=(c+(n=n+Math.imul(h,ue)|0)|0)+((8191&(i=(i=i+Math.imul(h,ce)|0)+Math.imul(l,ue)|0))<<13)|0;c=((o=o+Math.imul(l,ce)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,n=Math.imul(N,q),i=(i=Math.imul(N,H))+Math.imul(R,q)|0,o=Math.imul(R,H),n=n+Math.imul(B,K)|0,i=(i=i+Math.imul(B,V)|0)+Math.imul(P,K)|0,o=o+Math.imul(P,V)|0,n=n+Math.imul(T,W)|0,i=(i=i+Math.imul(T,Y)|0)+Math.imul(U,W)|0,o=o+Math.imul(U,Y)|0,n=n+Math.imul(S,Z)|0,i=(i=i+Math.imul(S,J)|0)+Math.imul(M,Z)|0,o=o+Math.imul(M,J)|0,n=n+Math.imul(E,Q)|0,i=(i=i+Math.imul(E,ee)|0)+Math.imul(x,Q)|0,o=o+Math.imul(x,ee)|0,n=n+Math.imul(w,re)|0,i=(i=i+Math.imul(w,ne)|0)+Math.imul(_,re)|0,o=o+Math.imul(_,ne)|0,n=n+Math.imul(m,oe)|0,i=(i=i+Math.imul(m,ae)|0)+Math.imul(v,oe)|0,o=o+Math.imul(v,ae)|0,n=n+Math.imul(p,ue)|0,i=(i=i+Math.imul(p,ce)|0)+Math.imul(b,ue)|0,o=o+Math.imul(b,ce)|0;var xe=(c+(n=n+Math.imul(h,he)|0)|0)+((8191&(i=(i=i+Math.imul(h,le)|0)+Math.imul(l,he)|0))<<13)|0;c=((o=o+Math.imul(l,le)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,n=Math.imul(O,q),i=(i=Math.imul(O,H))+Math.imul(D,q)|0,o=Math.imul(D,H),n=n+Math.imul(N,K)|0,i=(i=i+Math.imul(N,V)|0)+Math.imul(R,K)|0,o=o+Math.imul(R,V)|0,n=n+Math.imul(B,W)|0,i=(i=i+Math.imul(B,Y)|0)+Math.imul(P,W)|0,o=o+Math.imul(P,Y)|0,n=n+Math.imul(T,Z)|0,i=(i=i+Math.imul(T,J)|0)+Math.imul(U,Z)|0,o=o+Math.imul(U,J)|0,n=n+Math.imul(S,Q)|0,i=(i=i+Math.imul(S,ee)|0)+Math.imul(M,Q)|0,o=o+Math.imul(M,ee)|0,n=n+Math.imul(E,re)|0,i=(i=i+Math.imul(E,ne)|0)+Math.imul(x,re)|0,o=o+Math.imul(x,ne)|0,n=n+Math.imul(w,oe)|0,i=(i=i+Math.imul(w,ae)|0)+Math.imul(_,oe)|0,o=o+Math.imul(_,ae)|0,n=n+Math.imul(m,ue)|0,i=(i=i+Math.imul(m,ce)|0)+Math.imul(v,ue)|0,o=o+Math.imul(v,ce)|0,n=n+Math.imul(p,he)|0,i=(i=i+Math.imul(p,le)|0)+Math.imul(b,he)|0,o=o+Math.imul(b,le)|0;var ke=(c+(n=n+Math.imul(h,pe)|0)|0)+((8191&(i=(i=i+Math.imul(h,be)|0)+Math.imul(l,pe)|0))<<13)|0;c=((o=o+Math.imul(l,be)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,n=Math.imul(O,K),i=(i=Math.imul(O,V))+Math.imul(D,K)|0,o=Math.imul(D,V),n=n+Math.imul(N,W)|0,i=(i=i+Math.imul(N,Y)|0)+Math.imul(R,W)|0,o=o+Math.imul(R,Y)|0,n=n+Math.imul(B,Z)|0,i=(i=i+Math.imul(B,J)|0)+Math.imul(P,Z)|0,o=o+Math.imul(P,J)|0,n=n+Math.imul(T,Q)|0,i=(i=i+Math.imul(T,ee)|0)+Math.imul(U,Q)|0,o=o+Math.imul(U,ee)|0,n=n+Math.imul(S,re)|0,i=(i=i+Math.imul(S,ne)|0)+Math.imul(M,re)|0,o=o+Math.imul(M,ne)|0,n=n+Math.imul(E,oe)|0,i=(i=i+Math.imul(E,ae)|0)+Math.imul(x,oe)|0,o=o+Math.imul(x,ae)|0,n=n+Math.imul(w,ue)|0,i=(i=i+Math.imul(w,ce)|0)+Math.imul(_,ue)|0,o=o+Math.imul(_,ce)|0,n=n+Math.imul(m,he)|0,i=(i=i+Math.imul(m,le)|0)+Math.imul(v,he)|0,o=o+Math.imul(v,le)|0;var Se=(c+(n=n+Math.imul(p,pe)|0)|0)+((8191&(i=(i=i+Math.imul(p,be)|0)+Math.imul(b,pe)|0))<<13)|0;c=((o=o+Math.imul(b,be)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,n=Math.imul(O,W),i=(i=Math.imul(O,Y))+Math.imul(D,W)|0,o=Math.imul(D,Y),n=n+Math.imul(N,Z)|0,i=(i=i+Math.imul(N,J)|0)+Math.imul(R,Z)|0,o=o+Math.imul(R,J)|0,n=n+Math.imul(B,Q)|0,i=(i=i+Math.imul(B,ee)|0)+Math.imul(P,Q)|0,o=o+Math.imul(P,ee)|0,n=n+Math.imul(T,re)|0,i=(i=i+Math.imul(T,ne)|0)+Math.imul(U,re)|0,o=o+Math.imul(U,ne)|0,n=n+Math.imul(S,oe)|0,i=(i=i+Math.imul(S,ae)|0)+Math.imul(M,oe)|0,o=o+Math.imul(M,ae)|0,n=n+Math.imul(E,ue)|0,i=(i=i+Math.imul(E,ce)|0)+Math.imul(x,ue)|0,o=o+Math.imul(x,ce)|0,n=n+Math.imul(w,he)|0,i=(i=i+Math.imul(w,le)|0)+Math.imul(_,he)|0,o=o+Math.imul(_,le)|0;var Me=(c+(n=n+Math.imul(m,pe)|0)|0)+((8191&(i=(i=i+Math.imul(m,be)|0)+Math.imul(v,pe)|0))<<13)|0;c=((o=o+Math.imul(v,be)|0)+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863,n=Math.imul(O,Z),i=(i=Math.imul(O,J))+Math.imul(D,Z)|0,o=Math.imul(D,J),n=n+Math.imul(N,Q)|0,i=(i=i+Math.imul(N,ee)|0)+Math.imul(R,Q)|0,o=o+Math.imul(R,ee)|0,n=n+Math.imul(B,re)|0,i=(i=i+Math.imul(B,ne)|0)+Math.imul(P,re)|0,o=o+Math.imul(P,ne)|0,n=n+Math.imul(T,oe)|0,i=(i=i+Math.imul(T,ae)|0)+Math.imul(U,oe)|0,o=o+Math.imul(U,ae)|0,n=n+Math.imul(S,ue)|0,i=(i=i+Math.imul(S,ce)|0)+Math.imul(M,ue)|0,o=o+Math.imul(M,ce)|0,n=n+Math.imul(E,he)|0,i=(i=i+Math.imul(E,le)|0)+Math.imul(x,he)|0,o=o+Math.imul(x,le)|0;var Ie=(c+(n=n+Math.imul(w,pe)|0)|0)+((8191&(i=(i=i+Math.imul(w,be)|0)+Math.imul(_,pe)|0))<<13)|0;c=((o=o+Math.imul(_,be)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,n=Math.imul(O,Q),i=(i=Math.imul(O,ee))+Math.imul(D,Q)|0,o=Math.imul(D,ee),n=n+Math.imul(N,re)|0,i=(i=i+Math.imul(N,ne)|0)+Math.imul(R,re)|0,o=o+Math.imul(R,ne)|0,n=n+Math.imul(B,oe)|0,i=(i=i+Math.imul(B,ae)|0)+Math.imul(P,oe)|0,o=o+Math.imul(P,ae)|0,n=n+Math.imul(T,ue)|0,i=(i=i+Math.imul(T,ce)|0)+Math.imul(U,ue)|0,o=o+Math.imul(U,ce)|0,n=n+Math.imul(S,he)|0,i=(i=i+Math.imul(S,le)|0)+Math.imul(M,he)|0,o=o+Math.imul(M,le)|0;var Te=(c+(n=n+Math.imul(E,pe)|0)|0)+((8191&(i=(i=i+Math.imul(E,be)|0)+Math.imul(x,pe)|0))<<13)|0;c=((o=o+Math.imul(x,be)|0)+(i>>>13)|0)+(Te>>>26)|0,Te&=67108863,n=Math.imul(O,re),i=(i=Math.imul(O,ne))+Math.imul(D,re)|0,o=Math.imul(D,ne),n=n+Math.imul(N,oe)|0,i=(i=i+Math.imul(N,ae)|0)+Math.imul(R,oe)|0,o=o+Math.imul(R,ae)|0,n=n+Math.imul(B,ue)|0,i=(i=i+Math.imul(B,ce)|0)+Math.imul(P,ue)|0,o=o+Math.imul(P,ce)|0,n=n+Math.imul(T,he)|0,i=(i=i+Math.imul(T,le)|0)+Math.imul(U,he)|0,o=o+Math.imul(U,le)|0;var Ue=(c+(n=n+Math.imul(S,pe)|0)|0)+((8191&(i=(i=i+Math.imul(S,be)|0)+Math.imul(M,pe)|0))<<13)|0;c=((o=o+Math.imul(M,be)|0)+(i>>>13)|0)+(Ue>>>26)|0,Ue&=67108863,n=Math.imul(O,oe),i=(i=Math.imul(O,ae))+Math.imul(D,oe)|0,o=Math.imul(D,ae),n=n+Math.imul(N,ue)|0,i=(i=i+Math.imul(N,ce)|0)+Math.imul(R,ue)|0,o=o+Math.imul(R,ce)|0,n=n+Math.imul(B,he)|0,i=(i=i+Math.imul(B,le)|0)+Math.imul(P,he)|0,o=o+Math.imul(P,le)|0;var je=(c+(n=n+Math.imul(T,pe)|0)|0)+((8191&(i=(i=i+Math.imul(T,be)|0)+Math.imul(U,pe)|0))<<13)|0;c=((o=o+Math.imul(U,be)|0)+(i>>>13)|0)+(je>>>26)|0,je&=67108863,n=Math.imul(O,ue),i=(i=Math.imul(O,ce))+Math.imul(D,ue)|0,o=Math.imul(D,ce),n=n+Math.imul(N,he)|0,i=(i=i+Math.imul(N,le)|0)+Math.imul(R,he)|0,o=o+Math.imul(R,le)|0;var Be=(c+(n=n+Math.imul(B,pe)|0)|0)+((8191&(i=(i=i+Math.imul(B,be)|0)+Math.imul(P,pe)|0))<<13)|0;c=((o=o+Math.imul(P,be)|0)+(i>>>13)|0)+(Be>>>26)|0,Be&=67108863,n=Math.imul(O,he),i=(i=Math.imul(O,le))+Math.imul(D,he)|0,o=Math.imul(D,le);var Pe=(c+(n=n+Math.imul(N,pe)|0)|0)+((8191&(i=(i=i+Math.imul(N,be)|0)+Math.imul(R,pe)|0))<<13)|0;c=((o=o+Math.imul(R,be)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863;var Ce=(c+(n=Math.imul(O,pe))|0)+((8191&(i=(i=Math.imul(O,be))+Math.imul(D,pe)|0))<<13)|0;return c=((o=Math.imul(D,be))+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,u[0]=ye,u[1]=me,u[2]=ve,u[3]=ge,u[4]=we,u[5]=_e,u[6]=Ae,u[7]=Ee,u[8]=xe,u[9]=ke,u[10]=Se,u[11]=Me,u[12]=Ie,u[13]=Te,u[14]=Ue,u[15]=je,u[16]=Be,u[17]=Pe,u[18]=Ce,0!==c&&(u[19]=c,r.length++),r};function p(e,t,r){return(new b).mulp(e,t,r)}function b(e,t){this.x=e,this.y=t}Math.imul||(d=l),o.prototype.mulTo=function(e,t){var r=this.length+e.length;return 10===this.length&&10===e.length?d(this,e,t):r<63?l(this,e,t):r<1024?function(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,a&=67108863}r.words[o]=s,n=a,a=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,e,t):p(this,e,t)},b.prototype.makeRBT=function(e){for(var t=new Array(e),r=o.prototype._countBits(e)-1,n=0;n>=1;return n},b.prototype.permute=function(e,t,r,n,i,o){for(var a=0;a>>=1)i++;return 1<>>=13,r[2*a+1]=8191&o,o>>>=13;for(a=2*t;a>=26,t+=i/67108864|0,t+=o>>>26,this.words[r]=67108863&o}return 0!==t&&(this.words[r]=t,this.length++),this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),r=0;r>>i}return t}(e);if(0===t.length)return new o(1);for(var r=this,n=0;n=0);var t,r=e%26,i=(e-r)/26,o=67108863>>>26-r<<26-r;if(0!==r){var a=0;for(t=0;t>>26-r}a&&(this.words[t]=a,this.length++)}if(0!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t=0),i=t?(t-t%26)/26:0;var o=e%26,a=Math.min((e-o)/26,this.length),s=67108863^67108863>>>o<a)for(this.length-=a,c=0;c=0&&(0!==f||c>=i);c--){var h=0|this.words[c];this.words[c]=f<<26-o|h>>>o,f=h&s}return u&&0!==f&&(u.words[u.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},o.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,i=1<=0);var t=e%26,r=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var i=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(u/67108864|0),this.words[i+r]=67108863&o}for(;i>26,this.words[i+r]=67108863&o;if(0===s)return this.strip();for(n(-1===s),s=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},o.prototype._wordDiv=function(e,t){var r=(this.length,e.length),n=this.clone(),i=e,a=0|i.words[i.length-1];0!==(r=26-this._countBits(a))&&(i=i.ushln(r),n.iushln(r),a=0|i.words[i.length-1]);var s,u=n.length-i.length;if("mod"!==t){(s=new o(null)).length=u+1,s.words=new Array(s.length);for(var c=0;c=0;h--){var l=67108864*(0|n.words[i.length+h])+(0|n.words[i.length+h-1]);for(l=Math.min(l/a|0,67108863),n._ishlnsubmul(i,l,h);0!==n.negative;)l--,n.negative=0,n._ishlnsubmul(i,1,h),n.isZero()||(n.negative^=1);s&&(s.words[h]=l)}return s&&s.strip(),n.strip(),"div"!==t&&0!==r&&n.iushrn(r),{div:s||null,mod:n}},o.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(s=this.neg().divmod(e,t),"mod"!==t&&(i=s.div.neg()),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.iadd(e)),{div:i,mod:a}):0===this.negative&&0!==e.negative?(s=this.divmod(e.neg(),t),"mod"!==t&&(i=s.div.neg()),{div:i,mod:s.mod}):0!=(this.negative&e.negative)?(s=this.neg().divmod(e.neg(),t),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.isub(e)),{div:s.div,mod:a}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modn(e.words[0]))}:this._wordDiv(e,t);var i,a,s},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=0!==t.div.negative?t.mod.isub(e):t.mod,n=e.ushrn(1),i=e.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modn=function(e){n(e<=67108863);for(var t=(1<<26)%e,r=0,i=this.length-1;i>=0;i--)r=(t*r+(0|this.words[i]))%e;return r},o.prototype.idivn=function(e){n(e<=67108863);for(var t=0,r=this.length-1;r>=0;r--){var i=(0|this.words[r])+67108864*t;this.words[r]=i/e|0,t=i%e}return this.strip()},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new o(1),a=new o(0),s=new o(0),u=new o(1),c=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++c;for(var f=r.clone(),h=t.clone();!t.isZero();){for(var l=0,d=1;0==(t.words[0]&d)&&l<26;++l,d<<=1);if(l>0)for(t.iushrn(l);l-- >0;)(i.isOdd()||a.isOdd())&&(i.iadd(f),a.isub(h)),i.iushrn(1),a.iushrn(1);for(var p=0,b=1;0==(r.words[0]&b)&&p<26;++p,b<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(s.isOdd()||u.isOdd())&&(s.iadd(f),u.isub(h)),s.iushrn(1),u.iushrn(1);t.cmp(r)>=0?(t.isub(r),i.isub(s),a.isub(u)):(r.isub(t),s.isub(i),u.isub(a))}return{a:s,b:u,gcd:r.iushln(c)}},o.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,a=new o(1),s=new o(0),u=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var c=0,f=1;0==(t.words[0]&f)&&c<26;++c,f<<=1);if(c>0)for(t.iushrn(c);c-- >0;)a.isOdd()&&a.iadd(u),a.iushrn(1);for(var h=0,l=1;0==(r.words[0]&l)&&h<26;++h,l<<=1);if(h>0)for(r.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(u),s.iushrn(1);t.cmp(r)>=0?(t.isub(r),a.isub(s)):(r.isub(t),s.isub(a))}return(i=0===t.cmpn(1)?a:s).cmpn(0)<0&&i.iadd(e),i},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var n=0;t.isEven()&&r.isEven();n++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=t.cmp(r);if(i<0){var o=t;t=r,r=o}else if(0===i||0===r.cmpn(1))break;t.isub(r)}return r.iushln(n)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return 0==(1&this.words[0])},o.prototype.isOdd=function(){return 1==(1&this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,i=1<>>26,s&=67108863,this.words[a]=s}return 0!==o&&(this.words[a]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this.strip(),this.length>1)t=1;else{r&&(e=-e),n(e<=67108863,"Number is too big");var i=0|this.words[0];t=i===e?0:ie.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|e.words[r];if(n!==i){ni&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new A(e)},o.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var y={k256:null,p224:null,p192:null,p25519:null};function m(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function v(){m.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function g(){m.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function w(){m.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function _(){m.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function A(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function E(e){A.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(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)}m.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},m.prototype.ireduce=function(e){var t,r=e;do{this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(t>this.n);var n=t0?r.isub(this.p):r.strip(),r},m.prototype.split=function(e,t){e.iushrn(this.n,0,t)},m.prototype.imulK=function(e){return e.imul(this.k)},i(v,m),v.prototype.split=function(e,t){for(var r=Math.min(e.length,9),n=0;n>>22,i=o}i>>>=22,e.words[n-10]=i,0===i&&e.length>10?e.length-=10:e.length-=9},v.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r>>=26,e.words[r]=i,t=n}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(y[e])return y[e];var t;if("k256"===e)t=new v;else if("p224"===e)t=new g;else if("p192"===e)t=new w;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new _}return y[e]=t,t},A.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},A.prototype._verify2=function(e,t){n(0==(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},A.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},A.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},A.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},A.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},A.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},A.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},A.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},A.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},A.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},A.prototype.isqr=function(e){return this.imul(e,e.clone())},A.prototype.sqr=function(e){return this.mul(e,e)},A.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var r=this.m.add(new o(1)).iushrn(2);return this.pow(e,r)}for(var i=this.m.subn(1),a=0;!i.isZero()&&0===i.andln(1);)a++,i.iushrn(1);n(!i.isZero());var s=new o(1).toRed(this),u=s.redNeg(),c=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new o(2*f*f).toRed(this);0!==this.pow(f,c).cmp(u);)f.redIAdd(u);for(var h=this.pow(f,i),l=this.pow(e,i.addn(1).iushrn(1)),d=this.pow(e,i),p=a;0!==d.cmp(s);){for(var b=d,y=0;0!==b.cmp(s);y++)b=b.redSqr();n(y=0;n--){for(var c=t.words[n],f=u-1;f>=0;f--){var h=c>>f&1;i!==r[0]&&(i=this.sqr(i)),0!==h||0!==a?(a<<=1,a|=h,(4===++s||0===n&&0===f)&&(i=this.mul(i,r[a]),s=0,a=0)):s=0}u=26}return i},A.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},A.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new E(e)},i(E,A),E.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},E.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},E.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},E.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var r=e.mul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},E.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===t||t,this)},{}],155:[function(e,t,r){(function(r){"use strict";var n=e("is-hex-prefixed"),i=e("strip-hex-prefix");function o(e){var t=e;if("string"!=typeof t)throw new Error("[ethjs-util] while padding to even, value must be string, is currently "+typeof t+", while padToEven.");return t.length%2&&(t="0"+t),t}function a(e){return"0x"+e.toString(16)}t.exports={arrayContainsArray:function(e,t,r){if(!0!==Array.isArray(e))throw new Error("[ethjs-util] method arrayContainsArray requires input 'superset' to be an array got type '"+typeof e+"'");if(!0!==Array.isArray(t))throw new Error("[ethjs-util] method arrayContainsArray requires input 'subset' to be an array got type '"+typeof t+"'");return t[Boolean(r)?"some":"every"](function(t){return e.indexOf(t)>=0})},intToBuffer:function(e){var t=a(e);return new r(o(t.slice(2)),"hex")},getBinarySize:function(e){if("string"!=typeof e)throw new Error("[ethjs-util] while getting binary size, method getBinarySize requires input 'str' to be type String, got '"+typeof e+"'.");return r.byteLength(e,"utf8")},isHexPrefixed:n,stripHexPrefix:i,padToEven:o,intToHex:a,fromAscii:function(e){for(var t="",r=0;r0&&this._events[e].length>r&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(e,t){if(!i(t))throw TypeError("listener must be a function");var r=!1;function n(){this.removeListener(e,n),r||(r=!0,t.apply(this,arguments))}return n.listener=t,this.on(e,n),this},n.prototype.removeListener=function(e,t){var r,n,a,s;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(a=(r=this._events[e]).length,n=-1,r===t||i(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(o(r)){for(s=a;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){n=s;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},n.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(i(r=this._events[e]))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},n.prototype.listeners=function(e){return this._events&&this._events[e]?i(this._events[e])?[this._events[e]]:this._events[e].slice():[]},n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;if(t)return t.length}return 0},n.listenerCount=function(e,t){return e.listenerCount(t)}},{}],158:[function(e,t,r){var n=e("safe-buffer").Buffer,i=e("md5.js");t.exports=function(e,t,r,o){if(n.isBuffer(e)||(e=n.from(e,"binary")),t&&(n.isBuffer(t)||(t=n.from(t,"binary")),8!==t.length))throw new RangeError("salt should be Buffer with 8 byte length");for(var a=r/8,s=n.alloc(a),u=n.alloc(o||0),c=n.alloc(0);a>0||o>0;){var f=new i;f.update(c),f.update(e),t&&f.update(t),c=f.digest();var h=0;if(a>0){var l=s.length-a;h=Math.min(a,c.length),c.copy(s,l,0,h),a-=h}if(h0){var d=u.length-o,p=Math.min(o,c.length-h);c.copy(u,d,h,h+p),o-=p}}return c.fill(0),{key:s,iv:u}}},{"md5.js":231,"safe-buffer":290}],159:[function(e,t,r){"use strict";var n=e("is-callable"),i=Object.prototype.toString,o=Object.prototype.hasOwnProperty;t.exports=function(e,t,r){if(!n(t))throw new TypeError("iterator must be a function");var a;arguments.length>=3&&(a=r),"[object Array]"===i.call(e)?function(e,t,r){for(var n=0,i=e.length;n=this._blockSize;){for(var o=this._blockOffset;o0;++a)this._length[a]+=s,(s=this._length[a]/4294967296|0)>0&&(this._length[a]-=4294967296*s);return this},i.prototype._update=function(e){throw new Error("_update is not implemented")},i.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();return void 0!==e&&(t=t.toString(e)),t},i.prototype._digest=function(){throw new Error("_digest is not implemented")},t.exports=i}).call(this,e("buffer").Buffer)},{buffer:84,inherits:180,stream:311}],162:[function(e,t,r){var n=r;n.utils=e("./hash/utils"),n.common=e("./hash/common"),n.sha=e("./hash/sha"),n.ripemd=e("./hash/ripemd"),n.hmac=e("./hash/hmac"),n.sha1=n.sha.sha1,n.sha256=n.sha.sha256,n.sha224=n.sha.sha224,n.sha384=n.sha.sha384,n.sha512=n.sha.sha512,n.ripemd160=n.ripemd.ripemd160},{"./hash/common":163,"./hash/hmac":164,"./hash/ripemd":165,"./hash/sha":166,"./hash/utils":173}],163:[function(e,t,r){"use strict";var n=e("./utils"),i=e("minimalistic-assert");function o(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}r.BlockHash=o,o.prototype.update=function(e,t){if(e=n.toArray(e,t),this.pending?this.pending=this.pending.concat(e):this.pending=e,this.pendingTotal+=e.length,this.pending.length>=this._delta8){var r=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-r,e.length),0===this.pending.length&&(this.pending=null),e=n.join32(e,0,e.length-r,this.endian);for(var i=0;i>>24&255,n[i++]=e>>>16&255,n[i++]=e>>>8&255,n[i++]=255&e}else for(n[i++]=255&e,n[i++]=e>>>8&255,n[i++]=e>>>16&255,n[i++]=e>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,o=8;othis.blockSize&&(e=(new this.Hash).update(e).digest()),i(e.length<=this.blockSize);for(var t=e.length;t>>3},r.g1_256=function(e){return n(e,17)^n(e,19)^e>>>10}},{"../utils":173}],173:[function(e,t,r){"use strict";var n=e("minimalistic-assert"),i=e("inherits");function o(e){return(e>>>24|e>>>8&65280|e<<8&16711680|(255&e)<<24)>>>0}function a(e){return 1===e.length?"0"+e:e}function s(e){return 7===e.length?"0"+e:6===e.length?"00"+e:5===e.length?"000"+e:4===e.length?"0000"+e:3===e.length?"00000"+e:2===e.length?"000000"+e:1===e.length?"0000000"+e:e}r.inherits=i,r.toArray=function(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var r=[];if("string"==typeof e)if(t){if("hex"===t)for((e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e),n=0;n>8,a=255&i;o?r.push(o,a):r.push(a)}else for(n=0;n>>0}return a},r.split32=function(e,t){for(var r=new Array(4*e.length),n=0,i=0;n>>24,r[i+1]=o>>>16&255,r[i+2]=o>>>8&255,r[i+3]=255&o):(r[i+3]=o>>>24,r[i+2]=o>>>16&255,r[i+1]=o>>>8&255,r[i]=255&o)}return r},r.rotr32=function(e,t){return e>>>t|e<<32-t},r.rotl32=function(e,t){return e<>>32-t},r.sum32=function(e,t){return e+t>>>0},r.sum32_3=function(e,t,r){return e+t+r>>>0},r.sum32_4=function(e,t,r,n){return e+t+r+n>>>0},r.sum32_5=function(e,t,r,n,i){return e+t+r+n+i>>>0},r.sum64=function(e,t,r,n){var i=e[t],o=n+e[t+1]>>>0,a=(o>>0,e[t+1]=o},r.sum64_hi=function(e,t,r,n){return(t+n>>>0>>0},r.sum64_lo=function(e,t,r,n){return t+n>>>0},r.sum64_4_hi=function(e,t,r,n,i,o,a,s){var u=0,c=t;return u+=(c=c+n>>>0)>>0)>>0)>>0},r.sum64_4_lo=function(e,t,r,n,i,o,a,s){return t+n+o+s>>>0},r.sum64_5_hi=function(e,t,r,n,i,o,a,s,u,c){var f=0,h=t;return f+=(h=h+n>>>0)>>0)>>0)>>0)>>0},r.sum64_5_lo=function(e,t,r,n,i,o,a,s,u,c){return t+n+o+s+c>>>0},r.rotr64_hi=function(e,t,r){return(t<<32-r|e>>>r)>>>0},r.rotr64_lo=function(e,t,r){return(e<<32-r|t>>>r)>>>0},r.shr64_hi=function(e,t,r){return e>>>r},r.shr64_lo=function(e,t,r){return(e<<32-r|t>>>r)>>>0}},{inherits:180,"minimalistic-assert":234}],174:[function(e,t,r){"use strict";var n=e("hash.js"),i=e("minimalistic-crypto-utils"),o=e("minimalistic-assert");function a(e){if(!(this instanceof a))return new a(e);this.hash=e.hash,this.predResist=!!e.predResist,this.outLen=this.hash.outSize,this.minEntropy=e.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var t=i.toArray(e.entropy,e.entropyEnc||"hex"),r=i.toArray(e.nonce,e.nonceEnc||"hex"),n=i.toArray(e.pers,e.persEnc||"hex");o(t.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(t,r,n)}t.exports=a,a.prototype._init=function(e,t,r){var n=e.concat(t).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(e.concat(r||[])),this._reseed=1},a.prototype.generate=function(e,t,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof t&&(n=r,r=t,t=null),r&&(r=i.toArray(r,n||"hex"),this._update(r));for(var o=[];o.length\\$%@ءؤة\"'^|~⦅⦆・ゥャ¢£¬¦¥₩│←↑→↓■○𐐨𐐩𐐪𐐫𐐬𐐭𐐮𐐯𐐰𐐱𐐲𐐳𐐴𐐵𐐶𐐷𐐸𐐹𐐺𐐻𐐼𐐽𐐾𐐿𐑀𐑁𐑂𐑃𐑄𐑅𐑆𐑇𐑈𐑉𐑊𐑋𐑌𐑍𐑎𐑏𐓘𐓙𐓚𐓛𐓜𐓝𐓞𐓟𐓠𐓡𐓢𐓣𐓤𐓥𐓦𐓧𐓨𐓩𐓪𐓫𐓬𐓭𐓮𐓯𐓰𐓱𐓲𐓳𐓴𐓵𐓶𐓷𐓸𐓹𐓺𐓻𐳀𐳁𐳂𐳃𐳄𐳅𐳆𐳇𐳈𐳉𐳊𐳋𐳌𐳍𐳎𐳏𐳐𐳑𐳒𐳓𐳔𐳕𐳖𐳗𐳘𐳙𐳚𐳛𐳜𐳝𐳞𐳟𐳠𐳡𐳢𐳣𐳤𐳥𐳦𐳧𐳨𐳩𐳪𐳫𐳬𐳭𐳮𐳯𐳰𐳱𐳲𑣀𑣁𑣂𑣃𑣄𑣅𑣆𑣇𑣈𑣉𑣊𑣋𑣌𑣍𑣎𑣏𑣐𑣑𑣒𑣓𑣔𑣕𑣖𑣗𑣘𑣙𑣚𑣛𑣜𑣝𑣞𑣟ıȷ∇∂𞤢𞤣𞤤𞤥𞤦𞤧𞤨𞤩𞤪𞤫𞤬𞤭𞤮𞤯𞤰𞤱𞤲𞤳𞤴𞤵𞤶𞤷𞤸𞤹𞤺𞤻𞤼𞤽𞤾𞤿𞥀𞥁𞥂𞥃ٮڡٯ字双多解交映無前後再新初終販声吹演投捕遊指禁空合満申割営配得可丽丸乁𠄢你侻倂偺備像㒞𠘺兔兤具𠔜㒹內𠕋冗冤仌冬𩇟刃㓟刻剆剷㔕包匆卉博即卽卿𠨬灰及叟𠭣叫叱吆咞吸呈周咢哶唐啓啣善喫喳嗂圖圗噑噴壮城埴堍型堲報墬𡓤売壷夆夢奢𡚨𡛪姬娛娧姘婦㛮嬈嬾𡧈寃寘寳𡬘寿将㞁屠峀岍𡷤嵃𡷦嵮嵫嵼巡巢㠯巽帨帽幩㡢𢆃㡼庰庳庶𪎒𢌱舁弢㣇𣊸𦇚形彫㣣徚忍志忹悁㤺㤜𢛔惇慈慌慺憲憤憯懞戛扝抱拔捐𢬌挽拼捨掃揤𢯱搢揅掩㨮摩摾撝摷㩬敬𣀊旣書晉㬙㬈㫤冒冕最暜肭䏙朡杞杓𣏃㭉柺枅桒𣑭梎栟椔楂榣槪檨𣚣櫛㰘次𣢧歔㱎歲殟殻𣪍𡴋𣫺汎𣲼沿泍汧洖派浩浸涅𣴞洴港湮㴳滇𣻑淹潮𣽞𣾎濆瀹瀛㶖灊災灷炭𠔥煅𤉣熜爨牐𤘈犀犕𤜵𤠔獺王㺬玥㺸瑇瑜璅瓊㼛甤𤰶甾𤲒𢆟瘐𤾡𤾸𥁄㿼䀈𥃳𥃲𥄙𥄳眞真瞋䁆䂖𥐝硎䃣𥘦𥚚𥛅秫䄯穊穏𥥼𥪧䈂𥮫篆築䈧𥲀糒䊠糨糣紀𥾆絣䌁緇縂繅䌴𦈨𦉇䍙𦋙罺𦌾羕翺𦓚𦔣聠𦖨聰𣍟䏕育脃䐋脾媵𦞧𦞵𣎓𣎜舄辞䑫芑芋芝劳花芳芽苦𦬼茝荣莭茣莽菧荓菊菌菜𦰶𦵫𦳕䔫蓱蓳蔖𧏊蕤𦼬䕝䕡𦾱𧃒䕫虐虧虩蚩蚈蜎蛢蜨蝫螆蟡蠁䗹衠𧙧裗裞䘵裺㒻𧢮𧥦䚾䛇誠𧲨貫賁贛起𧼯𠠄跋趼跰𠣞軔𨗒𨗭邔郱鄑𨜮鄛鈸鋗鋘鉼鏹鐕𨯺開䦕閷𨵷䧦雃嶲霣𩅅𩈚䩮䩶韠𩐊䪲𩒖頩𩖶飢䬳餩馧駂駾䯎𩬰鱀鳽䳎䳭鵧𪃎䳸𪄅𪈎𪊑䵖黾鼅鼏鼖𪘀",mapChar:function(r){return r>=196608?r>=917760&&r<=917999?18874368:0:e[t[r>>4]][15&r]}}},"function"==typeof define&&define.amd?define([],function(){return i()}):"object"==typeof r?t.exports=i():n.uts46_map=i()},{}],177:[function(e,t,r){var n,i;n=this,i=function(e,t){function r(r,n,i){for(var o=[],a=e.ucs2.decode(r),s=0;s>23,l=f>>21&3,d=f>>5&65535,p=31&f,b=t.mapStr.substr(d,p);if(0===l||n&&1&h)throw new Error("Illegal char "+c);1===l?o.push(b):2===l?o.push(i?b:c):3===l&&o.push(c)}return o.join("").normalize("NFC")}function n(t,n,o){void 0===o&&(o=!1);var a=r(t,o,n).split(".");return(a=a.map(function(t){return t.startsWith("xn--")?i(t=e.decode(t.substring(4)),o,!1):i(t,o,n),t})).join(".")}function i(e,n,i){if("-"===e[2]&&"-"===e[3])throw new Error("Failed to validate "+e);if(e.startsWith("-")||e.endsWith("-"))throw new Error("Failed to validate "+e);if(e.includes("."))throw new Error("Failed to validate "+e);if(r(e,n,i)!==e)throw new Error("Failed to validate "+e);var o=e.codePointAt(0);if(t.mapChar(o)&2<<23)throw new Error("Label contains illegal character: "+o)}return{toUnicode:function(e,t){return void 0===t&&(t={}),n(e,!1,"useStd3ASCII"in t&&t.useStd3ASCII)},toAscii:function(t,r){void 0===r&&(r={});var i,o=!("transitional"in r)||r.transitional,a="useStd3ASCII"in r&&r.useStd3ASCII,s="verifyDnsLength"in r&&r.verifyDnsLength,u=n(t,o,a).split(".").map(e.toASCII),c=u.join(".");if(s){if(c.length<1||c.length>253)throw new Error("DNS name has wrong length: "+c);for(i=0;i63)throw new Error("DNS label has wrong length: "+f)}}return c}}},"function"==typeof define&&define.amd?define(["punycode","./idna-map"],function(e,t){return i(e,t)}):"object"==typeof r?t.exports=i(e("punycode"),e("./idna-map")):n.uts46=i(n.punycode,n.idna_map)},{"./idna-map":176,punycode:265}],178:[function(e,t,r){r.read=function(e,t,r,n,i){var o,a,s=8*i-n-1,u=(1<>1,f=-7,h=r?i-1:0,l=r?-1:1,d=e[t+h];for(h+=l,o=d&(1<<-f)-1,d>>=-f,f+=s;f>0;o=256*o+e[t+h],h+=l,f-=8);for(a=o&(1<<-f)-1,o>>=-f,f+=n;f>0;a=256*a+e[t+h],h+=l,f-=8);if(0===o)o=1-c;else{if(o===u)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,n),o-=c}return(d?-1:1)*a*Math.pow(2,o-n)},r.write=function(e,t,r,n,i,o){var a,s,u,c=8*o-i-1,f=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:o-1,p=n?1:-1,b=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=f):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+h>=1?l/u:l*Math.pow(2,1-h))*u>=2&&(a++,u/=2),a+h>=f?(s=0,a=f):a+h>=1?(s=(t*u-1)*Math.pow(2,i),a+=h):(s=t*Math.pow(2,h-1)*Math.pow(2,i),a=0));i>=8;e[r+d]=255&s,d+=p,s/=256,i-=8);for(a=a<0;e[r+d]=255&a,d+=p,a/=256,c-=8);e[r+d-p]|=128*b}},{}],179:[function(e,t,r){var n=[].indexOf;t.exports=function(e,t){if(n)return e.indexOf(t);for(var r=0;r-32e3)throw new Error("Invalid error code");if(!(this instanceof f))return new f(e);i.call(this,"Server error",e)};n(f,i),i.ParseError=o,i.InvalidRequest=a,i.MethodNotFound=s,i.InvalidParams=u,i.InternalError=c,i.ServerError=f,t.exports=i},{inherits:180}],191:[function(e,t,r){t.exports=function(e){var t=(e=e||{}).max||Number.MAX_SAFE_INTEGER,r=void 0!==e.start?e.start:Math.floor(Math.random()*t);return function(){return r%=t,r++}}},{}],192:[function(e,t,r){r.parse=e("./lib/parse"),r.stringify=e("./lib/stringify")},{"./lib/parse":193,"./lib/stringify":194}],193:[function(e,t,r){var n,i,o,a,s={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"},u=function(e){throw{name:"SyntaxError",message:e,at:n,text:o}},c=function(e){return e&&e!==i&&u("Expected '"+e+"' instead of '"+i+"'"),i=o.charAt(n),n+=1,i},f=function(){var e,t="";for("-"===i&&(t="-",c("-"));i>="0"&&i<="9";)t+=i,c();if("."===i)for(t+=".";c()&&i>="0"&&i<="9";)t+=i;if("e"===i||"E"===i)for(t+=i,c(),"-"!==i&&"+"!==i||(t+=i,c());i>="0"&&i<="9";)t+=i,c();if(e=+t,isFinite(e))return e;u("Bad number")},h=function(){var e,t,r,n="";if('"'===i)for(;c();){if('"'===i)return c(),n;if("\\"===i)if(c(),"u"===i){for(r=0,t=0;t<4&&(e=parseInt(c(),16),isFinite(e));t+=1)r=16*r+e;n+=String.fromCharCode(r)}else{if("string"!=typeof s[i])break;n+=s[i]}else n+=i}u("Bad string")},l=function(){for(;i&&i<=" ";)c()};a=function(){switch(l(),i){case"{":return function(){var e,t={};if("{"===i){if(c("{"),l(),"}"===i)return c("}"),t;for(;i;){if(e=h(),l(),c(":"),Object.hasOwnProperty.call(t,e)&&u('Duplicate key "'+e+'"'),t[e]=a(),l(),"}"===i)return c("}"),t;c(","),l()}}u("Bad object")}();case"[":return function(){var e=[];if("["===i){if(c("["),l(),"]"===i)return c("]"),e;for(;i;){if(e.push(a()),l(),"]"===i)return c("]"),e;c(","),l()}}u("Bad array")}();case'"':return h();case"-":return f();default:return i>="0"&&i<="9"?f():function(){switch(i){case"t":return c("t"),c("r"),c("u"),c("e"),!0;case"f":return c("f"),c("a"),c("l"),c("s"),c("e"),!1;case"n":return c("n"),c("u"),c("l"),c("l"),null}u("Unexpected '"+i+"'")}()}},t.exports=function(e,t){var r;return o=e,n=0,i=" ",r=a(),l(),i&&u("Syntax error"),"function"==typeof t?function e(r,n){var i,o,a=r[n];if(a&&"object"==typeof a)for(i in a)Object.prototype.hasOwnProperty.call(a,i)&&(void 0!==(o=e(a,i))?a[i]=o:delete a[i]);return t.call(r,n,a)}({"":r},""):r}},{}],194:[function(e,t,r){var n,i,o,a=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,s={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};function u(e){return a.lastIndex=0,a.test(e)?'"'+e.replace(a,function(e){var t=s[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}t.exports=function(e,t,r){var a;if(n="",i="","number"==typeof r)for(a=0;a>>31),p=l^(a<<1|o>>>31),b=e[0]^d,y=e[1]^p,m=e[10]^d,v=e[11]^p,g=e[20]^d,w=e[21]^p,_=e[30]^d,A=e[31]^p,E=e[40]^d,x=e[41]^p;d=r^(s<<1|u>>>31),p=i^(u<<1|s>>>31);var k=e[2]^d,S=e[3]^p,M=e[12]^d,I=e[13]^p,T=e[22]^d,U=e[23]^p,j=e[32]^d,B=e[33]^p,P=e[42]^d,C=e[43]^p;d=o^(c<<1|f>>>31),p=a^(f<<1|c>>>31);var N=e[4]^d,R=e[5]^p,L=e[14]^d,O=e[15]^p,D=e[24]^d,F=e[25]^p,q=e[34]^d,H=e[35]^p,z=e[44]^d,K=e[45]^p;d=s^(h<<1|l>>>31),p=u^(l<<1|h>>>31);var V=e[6]^d,G=e[7]^p,W=e[16]^d,Y=e[17]^p,X=e[26]^d,Z=e[27]^p,J=e[36]^d,$=e[37]^p,Q=e[46]^d,ee=e[47]^p;d=c^(r<<1|i>>>31),p=f^(i<<1|r>>>31);var te=e[8]^d,re=e[9]^p,ne=e[18]^d,ie=e[19]^p,oe=e[28]^d,ae=e[29]^p,se=e[38]^d,ue=e[39]^p,ce=e[48]^d,fe=e[49]^p,he=b,le=y,de=v<<4|m>>>28,pe=m<<4|v>>>28,be=g<<3|w>>>29,ye=w<<3|g>>>29,me=A<<9|_>>>23,ve=_<<9|A>>>23,ge=E<<18|x>>>14,we=x<<18|E>>>14,_e=k<<1|S>>>31,Ae=S<<1|k>>>31,Ee=I<<12|M>>>20,xe=M<<12|I>>>20,ke=T<<10|U>>>22,Se=U<<10|T>>>22,Me=B<<13|j>>>19,Ie=j<<13|B>>>19,Te=P<<2|C>>>30,Ue=C<<2|P>>>30,je=R<<30|N>>>2,Be=N<<30|R>>>2,Pe=L<<6|O>>>26,Ce=O<<6|L>>>26,Ne=F<<11|D>>>21,Re=D<<11|F>>>21,Le=q<<15|H>>>17,Oe=H<<15|q>>>17,De=K<<29|z>>>3,Fe=z<<29|K>>>3,qe=V<<28|G>>>4,He=G<<28|V>>>4,ze=Y<<23|W>>>9,Ke=W<<23|Y>>>9,Ve=X<<25|Z>>>7,Ge=Z<<25|X>>>7,We=J<<21|$>>>11,Ye=$<<21|J>>>11,Xe=ee<<24|Q>>>8,Ze=Q<<24|ee>>>8,Je=te<<27|re>>>5,$e=re<<27|te>>>5,Qe=ne<<20|ie>>>12,et=ie<<20|ne>>>12,tt=ae<<7|oe>>>25,rt=oe<<7|ae>>>25,nt=se<<8|ue>>>24,it=ue<<8|se>>>24,ot=ce<<14|fe>>>18,at=fe<<14|ce>>>18;e[0]=he^~Ee&Ne,e[1]=le^~xe&Re,e[10]=qe^~Qe&be,e[11]=He^~et&ye,e[20]=_e^~Pe&Ve,e[21]=Ae^~Ce&Ge,e[30]=Je^~de&ke,e[31]=$e^~pe&Se,e[40]=je^~ze&tt,e[41]=Be^~Ke&rt,e[2]=Ee^~Ne&We,e[3]=xe^~Re&Ye,e[12]=Qe^~be&Me,e[13]=et^~ye&Ie,e[22]=Pe^~Ve&nt,e[23]=Ce^~Ge&it,e[32]=de^~ke&Le,e[33]=pe^~Se&Oe,e[42]=ze^~tt&me,e[43]=Ke^~rt&ve,e[4]=Ne^~We&ot,e[5]=Re^~Ye&at,e[14]=be^~Me&De,e[15]=ye^~Ie&Fe,e[24]=Ve^~nt&ge,e[25]=Ge^~it&we,e[34]=ke^~Le&Xe,e[35]=Se^~Oe&Ze,e[44]=tt^~me&Te,e[45]=rt^~ve&Ue,e[6]=We^~ot&he,e[7]=Ye^~at&le,e[16]=Me^~De&qe,e[17]=Ie^~Fe&He,e[26]=nt^~ge&_e,e[27]=it^~we&Ae,e[36]=Le^~Xe&Je,e[37]=Oe^~Ze&$e,e[46]=me^~Te&je,e[47]=ve^~Ue&Be,e[8]=ot^~he&Ee,e[9]=at^~le&xe,e[18]=De^~qe&Qe,e[19]=Fe^~He&et,e[28]=ge^~_e&Pe,e[29]=we^~Ae&Ce,e[38]=Xe^~Je&de,e[39]=Ze^~$e&pe,e[48]=Te^~je&ze,e[49]=Ue^~Be&Ke,e[0]^=n[2*t],e[1]^=n[2*t+1]}}},{}],200:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("./keccak-state-unroll");function o(){this.state=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.blockSize=null,this.count=0,this.squeezing=!1}o.prototype.initialize=function(e,t){for(var r=0;r<50;++r)this.state[r]=0;this.blockSize=e/8,this.count=0,this.squeezing=!1},o.prototype.absorb=function(e){for(var t=0;t>>this.count%4*8&255,this.count+=1,this.count===this.blockSize&&(i.p1600(this.state),this.count=0);return t},o.prototype.copy=function(e){for(var t=0;t<50;++t)e.state[t]=this.state[t];e.blockSize=this.blockSize,e.count=this.count,e.squeezing=this.squeezing},t.exports=o},{"./keccak-state-unroll":199,"safe-buffer":290}],201:[function(e,t,r){var n=e("./_root").Symbol;t.exports=n},{"./_root":217}],202:[function(e,t,r){var n=e("./_baseTimes"),i=e("./isArguments"),o=e("./isArray"),a=e("./isBuffer"),s=e("./_isIndex"),u=e("./isTypedArray"),c=Object.prototype.hasOwnProperty;t.exports=function(e,t){var r=o(e),f=!r&&i(e),h=!r&&!f&&a(e),l=!r&&!f&&!h&&u(e),d=r||f||h||l,p=d?n(e.length,String):[],b=p.length;for(var y in e)!t&&!c.call(e,y)||d&&("length"==y||h&&("offset"==y||"parent"==y)||l&&("buffer"==y||"byteLength"==y||"byteOffset"==y)||s(y,b))||p.push(y);return p}},{"./_baseTimes":207,"./_isIndex":211,"./isArguments":219,"./isArray":220,"./isBuffer":222,"./isTypedArray":227}],203:[function(e,t,r){var n=e("./_Symbol"),i=e("./_getRawTag"),o=e("./_objectToString"),a="[object Null]",s="[object Undefined]",u=n?n.toStringTag:void 0;t.exports=function(e){return null==e?void 0===e?s:a:u&&u in Object(e)?i(e):o(e)}},{"./_Symbol":201,"./_getRawTag":210,"./_objectToString":215}],204:[function(e,t,r){var n=e("./_baseGetTag"),i=e("./isObjectLike"),o="[object Arguments]";t.exports=function(e){return i(e)&&n(e)==o}},{"./_baseGetTag":203,"./isObjectLike":226}],205:[function(e,t,r){var n=e("./_baseGetTag"),i=e("./isLength"),o=e("./isObjectLike"),a={};a["[object Float32Array]"]=a["[object Float64Array]"]=a["[object Int8Array]"]=a["[object Int16Array]"]=a["[object Int32Array]"]=a["[object Uint8Array]"]=a["[object Uint8ClampedArray]"]=a["[object Uint16Array]"]=a["[object Uint32Array]"]=!0,a["[object Arguments]"]=a["[object Array]"]=a["[object ArrayBuffer]"]=a["[object Boolean]"]=a["[object DataView]"]=a["[object Date]"]=a["[object Error]"]=a["[object Function]"]=a["[object Map]"]=a["[object Number]"]=a["[object Object]"]=a["[object RegExp]"]=a["[object Set]"]=a["[object String]"]=a["[object WeakMap]"]=!1,t.exports=function(e){return o(e)&&i(e.length)&&!!a[n(e)]}},{"./_baseGetTag":203,"./isLength":224,"./isObjectLike":226}],206:[function(e,t,r){var n=e("./_isPrototype"),i=e("./_nativeKeys"),o=Object.prototype.hasOwnProperty;t.exports=function(e){if(!n(e))return i(e);var t=[];for(var r in Object(e))o.call(e,r)&&"constructor"!=r&&t.push(r);return t}},{"./_isPrototype":212,"./_nativeKeys":213}],207:[function(e,t,r){t.exports=function(e,t){for(var r=-1,n=Array(e);++r-1&&e%1==0&&e-1&&e%1==0&&e<=n}},{}],225:[function(e,t,r){t.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}},{}],226:[function(e,t,r){t.exports=function(e){return null!=e&&"object"==typeof e}},{}],227:[function(e,t,r){var n=e("./_baseIsTypedArray"),i=e("./_baseUnary"),o=e("./_nodeUtil"),a=o&&o.isTypedArray,s=a?i(a):n;t.exports=s},{"./_baseIsTypedArray":205,"./_baseUnary":208,"./_nodeUtil":214}],228:[function(e,t,r){var n=e("./_arrayLikeKeys"),i=e("./_baseKeys"),o=e("./isArrayLike");t.exports=function(e){return o(e)?n(e):i(e)}},{"./_arrayLikeKeys":202,"./_baseKeys":206,"./isArrayLike":221}],229:[function(e,t,r){t.exports=function(){}},{}],230:[function(e,t,r){t.exports=function(){return!1}},{}],231:[function(e,t,r){(function(r){"use strict";var n=e("inherits"),i=e("hash-base"),o=new Array(16);function a(){i.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}function s(e,t){return e<>>32-t}function u(e,t,r,n,i,o,a){return s(e+(t&r|~t&n)+i+o|0,a)+t|0}function c(e,t,r,n,i,o,a){return s(e+(t&n|r&~n)+i+o|0,a)+t|0}function f(e,t,r,n,i,o,a){return s(e+(t^r^n)+i+o|0,a)+t|0}function h(e,t,r,n,i,o,a){return s(e+(r^(t|~n))+i+o|0,a)+t|0}n(a,i),a.prototype._update=function(){for(var e=o,t=0;t<16;++t)e[t]=this._block.readInt32LE(4*t);var r=this._a,n=this._b,i=this._c,a=this._d;n=h(n=h(n=h(n=h(n=f(n=f(n=f(n=f(n=c(n=c(n=c(n=c(n=u(n=u(n=u(n=u(n,i=u(i,a=u(a,r=u(r,n,i,a,e[0],3614090360,7),n,i,e[1],3905402710,12),r,n,e[2],606105819,17),a,r,e[3],3250441966,22),i=u(i,a=u(a,r=u(r,n,i,a,e[4],4118548399,7),n,i,e[5],1200080426,12),r,n,e[6],2821735955,17),a,r,e[7],4249261313,22),i=u(i,a=u(a,r=u(r,n,i,a,e[8],1770035416,7),n,i,e[9],2336552879,12),r,n,e[10],4294925233,17),a,r,e[11],2304563134,22),i=u(i,a=u(a,r=u(r,n,i,a,e[12],1804603682,7),n,i,e[13],4254626195,12),r,n,e[14],2792965006,17),a,r,e[15],1236535329,22),i=c(i,a=c(a,r=c(r,n,i,a,e[1],4129170786,5),n,i,e[6],3225465664,9),r,n,e[11],643717713,14),a,r,e[0],3921069994,20),i=c(i,a=c(a,r=c(r,n,i,a,e[5],3593408605,5),n,i,e[10],38016083,9),r,n,e[15],3634488961,14),a,r,e[4],3889429448,20),i=c(i,a=c(a,r=c(r,n,i,a,e[9],568446438,5),n,i,e[14],3275163606,9),r,n,e[3],4107603335,14),a,r,e[8],1163531501,20),i=c(i,a=c(a,r=c(r,n,i,a,e[13],2850285829,5),n,i,e[2],4243563512,9),r,n,e[7],1735328473,14),a,r,e[12],2368359562,20),i=f(i,a=f(a,r=f(r,n,i,a,e[5],4294588738,4),n,i,e[8],2272392833,11),r,n,e[11],1839030562,16),a,r,e[14],4259657740,23),i=f(i,a=f(a,r=f(r,n,i,a,e[1],2763975236,4),n,i,e[4],1272893353,11),r,n,e[7],4139469664,16),a,r,e[10],3200236656,23),i=f(i,a=f(a,r=f(r,n,i,a,e[13],681279174,4),n,i,e[0],3936430074,11),r,n,e[3],3572445317,16),a,r,e[6],76029189,23),i=f(i,a=f(a,r=f(r,n,i,a,e[9],3654602809,4),n,i,e[12],3873151461,11),r,n,e[15],530742520,16),a,r,e[2],3299628645,23),i=h(i,a=h(a,r=h(r,n,i,a,e[0],4096336452,6),n,i,e[7],1126891415,10),r,n,e[14],2878612391,15),a,r,e[5],4237533241,21),i=h(i,a=h(a,r=h(r,n,i,a,e[12],1700485571,6),n,i,e[3],2399980690,10),r,n,e[10],4293915773,15),a,r,e[1],2240044497,21),i=h(i,a=h(a,r=h(r,n,i,a,e[8],1873313359,6),n,i,e[15],4264355552,10),r,n,e[6],2734768916,15),a,r,e[13],1309151649,21),i=h(i,a=h(a,r=h(r,n,i,a,e[4],4149444226,6),n,i,e[11],3174756917,10),r,n,e[2],718787259,15),a,r,e[9],3951481745,21),this._a=this._a+r|0,this._b=this._b+n|0,this._c=this._c+i|0,this._d=this._d+a|0},a.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=new r(16);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e},t.exports=a}).call(this,e("buffer").Buffer)},{buffer:84,"hash-base":232,inherits:180}],232:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("stream").Transform;function o(e){i.call(this),this._block=n.allocUnsafe(e),this._blockSize=e,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}e("inherits")(o,i),o.prototype._transform=function(e,t,r){var n=null;try{this.update(e,t)}catch(e){n=e}r(n)},o.prototype._flush=function(e){var t=null;try{this.push(this.digest())}catch(e){t=e}e(t)},o.prototype.update=function(e,t){if(function(e,t){if(!n.isBuffer(e)&&"string"!=typeof e)throw new TypeError(t+" must be a string or a buffer")}(e,"Data"),this._finalized)throw new Error("Digest already called");n.isBuffer(e)||(e=n.from(e,t));for(var r=this._block,i=0;this._blockOffset+e.length-i>=this._blockSize;){for(var o=this._blockOffset;o0;++a)this._length[a]+=s,(s=this._length[a]/4294967296|0)>0&&(this._length[a]-=4294967296*s);return this},o.prototype._update=function(){throw new Error("_update is not implemented")},o.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();void 0!==e&&(t=t.toString(e)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return t},o.prototype._digest=function(){throw new Error("_digest is not implemented")},t.exports=o},{inherits:180,"safe-buffer":290,stream:311}],233:[function(e,t,r){var n=e("bn.js"),i=e("brorand");function o(e){this.rand=e||new i.Rand}t.exports=o,o.create=function(e){return new o(e)},o.prototype._randbelow=function(e){var t=e.bitLength(),r=Math.ceil(t/8);do{var i=new n(this.rand.generate(r))}while(i.cmp(e)>=0);return i},o.prototype._randrange=function(e,t){var r=t.sub(e);return e.add(this._randbelow(r))},o.prototype.test=function(e,t,r){var i=e.bitLength(),o=n.mont(e),a=new n(1).toRed(o);t||(t=Math.max(1,i/48|0));for(var s=e.subn(1),u=0;!s.testn(u);u++);for(var c=e.shrn(u),f=s.toRed(o);t>0;t--){var h=this._randrange(new n(2),s);r&&r(h);var l=h.toRed(o).redPow(c);if(0!==l.cmp(a)&&0!==l.cmp(f)){for(var d=1;d0;t--){var f=this._randrange(new n(2),a),h=e.gcd(f);if(0!==h.cmpn(1))return h;var l=f.toRed(i).redPow(u);if(0!==l.cmp(o)&&0!==l.cmp(c)){for(var d=1;d>8,a=255&i;o?r.push(o,a):r.push(a)}return r},n.zero2=i,n.toHex=o,n.encode=function(e,t){return"hex"===t?o(e):e}},{}],236:[function(e,t,r){arguments[4][154][0].apply(r,arguments)},{dup:154}],237:[function(e,t,r){var n=e("bn.js"),i=e("strip-hex-prefix");t.exports=function(e){if("string"==typeof e||"number"==typeof e){var t=new n(1),r=String(e).toLowerCase().trim(),o="0x"===r.substr(0,2)||"-0x"===r.substr(0,3),a=i(r);if("-"===a.substr(0,1)&&(a=i(a.slice(1)),t=new n(-1,10)),!(a=""===a?"0":a).match(/^-?[0-9]+$/)&&a.match(/^[0-9A-Fa-f]+$/)||a.match(/^[a-fA-F]+$/)||!0===o&&a.match(/^[0-9A-Fa-f]+$/))return new n(a,16).mul(t);if((a.match(/^-?[0-9]+$/)||""===a)&&!1===o)return new n(a,10).mul(t)}else if("object"==typeof e&&e.toString&&!e.pop&&!e.push&&e.toString(10).match(/^-?[0-9]+$/)&&(e.mul||e.dividedToIntegerBy))return new n(e.toString(10),10);throw new Error("[number-to-bn] while converting number "+JSON.stringify(e)+" 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(e,t,r){"use strict";var n=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable;t.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},r=0;r<10;r++)t["_"+String.fromCharCode(r)]=r;if("0123456789"!==Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(""))return!1;var n={};return"abcdefghijklmnopqrst".split("").forEach(function(e){n[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},n)).join("")}catch(e){return!1}}()?Object.assign:function(e,t){for(var r,a,s=function(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}(e),u=1;u0;)if(q+=r,r=e.charAt(o++),4===H?(N+=String.fromCharCode(parseInt(q,16)),H=0,c=o-1):H++,!r)break e;if('"'===r&&!L){D=F.pop()||p,N+=e.substring(c,o-1);break}if(!("\\"!==r||L||(L=!0,N+=e.substring(c,o-1),r=e.charAt(o++))))break;if(L){if(L=!1,"n"===r?N+="\n":"r"===r?N+="\r":"t"===r?N+="\t":"f"===r?N+="\f":"b"===r?N+="\b":"u"===r?(H=1,q=""):N+=r,r=e.charAt(o++),c=o-1,r)continue;break}h.lastIndex=o;var l=h.exec(e);if(!l){o=e.length+1,N+=e.substring(c,o-1);break}if(o=l.index+1,!(r=e.charAt(l.index))){N+=e.substring(c,o-1);break}}continue;case A:if(!r)continue;if("r"!==r)return W("Invalid true started with t"+r);D=E;continue;case E:if(!r)continue;if("u"!==r)return W("Invalid true started with tr"+r);D=x;continue;case x:if(!r)continue;if("e"!==r)return W("Invalid true started with tru"+r);a(!0),u(),D=F.pop()||p;continue;case k:if(!r)continue;if("a"!==r)return W("Invalid false started with f"+r);D=S;continue;case S:if(!r)continue;if("l"!==r)return W("Invalid false started with fa"+r);D=M;continue;case M:if(!r)continue;if("s"!==r)return W("Invalid false started with fal"+r);D=I;continue;case I:if(!r)continue;if("e"!==r)return W("Invalid false started with fals"+r);a(!1),u(),D=F.pop()||p;continue;case T:if(!r)continue;if("u"!==r)return W("Invalid null started with n"+r);D=U;continue;case U:if(!r)continue;if("l"!==r)return W("Invalid null started with nu"+r);D=j;continue;case j:if(!r)continue;if("l"!==r)return W("Invalid null started with nul"+r);a(null),u(),D=F.pop()||p;continue;case B:if("."!==r)return W("Leading zero not followed by .");R+=r,D=P;continue;case P:if(-1!=="0123456789".indexOf(r))R+=r;else if("."===r){if(-1!==R.indexOf("."))return W("Invalid number has two dots");R+=r}else if("e"===r||"E"===r){if(-1!==R.indexOf("e")||-1!==R.indexOf("E"))return W("Invalid number has two exponential");R+=r}else if("+"===r||"-"===r){if("e"!==n&&"E"!==n)return W("Invalid symbol in number");R+=r}else R&&(a(parseFloat(R)),u(),R=""),o--,D=F.pop()||p;continue;default:return W("Unknown state: "+D)}K>=C&&(X=0,N!==s&&N.length>f&&(W("Max buffer length exceeded: textNode"),X=Math.max(X,N.length)),R.length>f&&(W("Max buffer length exceeded: numberNode"),X=Math.max(X,R.length)),C=f-X+K);var X}),e(ce).on(function(){if(D==d)return a({}),u(),void(O=!0);D===p&&0===z||W("Unexpected end");N!==s&&(a(N),u(),N=s);O=!0})}var C,N,R,L,O,D,F,q,H,z,K,V=(C=d(function(e){return e.unshift(/^/),(t=RegExp(e.map(f("source")).join(""))).exec.bind(t);var t}),L=C(N=/(\$?)/,/([\w-_]+|\*)/,R=/(?:{([\w ]*?)})?/),O=C(N,/\["([^"]+)"\]/,R),D=C(N,/\[(\d+|\*)\]/,R),F=C(N,/()/,/{([\w ]*?)}/),q=C(/\.\./),H=C(/\./),z=C(N,/!/),K=C(/$/),function(e){return e(h(L,O,D,F),q,H,z,K)});function G(e,t){return{key:e,node:t}}var W=f("key"),Y=f("node"),X={};function Z(e){var t=e(ee).emit,r=e(te).emit,n=e(ae).emit,o=e(oe).emit;function a(e,t,r){Y(x(e))[t]=r}function s(e,r,n){e&&a(e,r,n);var i=A(G(r,n),e);return t(i),i}var u={};return u[le]=function(e,t){if(!e)return n(t),s(e,X,t);var r=function(e,t){var r=Y(x(e));return m(i,r)?s(e,v(r),t):e}(e,t),o=k(r),u=W(x(r));return a(o,u,t),A(G(u,t),o)},u[de]=function(e){return r(e),k(e)||o(Y(x(e)))},u[he]=s,u}var J=V(function(e,t,r,n,i){var a=1,s=2,f=3,l=c(W,x),d=c(Y,x);function b(e,t){return!!t[a]?p(e,x):e}function m(e){if(e==y)return y;return p(function(e){return l(e)!=X},c(e,k))}function g(){return function(e){return l(e)==X}}function w(e,t,r,n,i){var o=e(r);if(o){var a=function(e,t,r){return U(function(e,t){return t(e,r)},t,e)}(t,n,o);return i(r.substr(v(o[0])),a)}}function A(e,t){return u(w,e,t)}var E=h(A(e,M(b,function(e,t){var r=t[f];return r?p(c(u(_,S(r.split(/\W+/))),d),e):e},function(e,t){var r=t[s];return p(r&&"*"!=r?function(e){return l(e)==r}:y,e)},m)),A(t,M(function(e){if(e==y)return y;var t=g(),r=e,n=m(function(e){return i(e)}),i=h(t,r,n);return i})),A(r,M()),A(n,M(b,g)),A(i,M(function(e){return function(t){var r=e(t);return!0===r?x(t):r}})),function(e){throw o('"'+e+'" could not be tokenised')});function I(e,t){return t}function T(e,t){return E(e,t,e?T:I)}return function(e){try{return T(e,y)}catch(t){throw o('Could not compile "'+e+'" because '+t.message)}}});function $(e,t,r){var n,i;function o(e){return function(t){return t.id==e}}return{on:function(r,o){var a={listener:r,id:o||r};return t&&t.emit(e,r,a.id),n=A(a,n),i=A(r,i),this},emit:function(){!function e(t,r){t&&(x(t).apply(null,r),e(k(t),r))}(i,arguments)},un:function(t){var a;n=j(n,o(t),function(e){a=e}),a&&(i=j(i,function(e){return e==a.listener}),r&&r.emit(e,a.listener,a.id))},listeners:function(){return i},hasListener:function(e){return w(function e(t,r){return r&&(t(x(r))?x(r):e(t,k(r)))}(e?o(e):y,n))}}}var Q=1,ee=Q++,te=Q++,re=Q++,ne=Q++,ie="fail",oe=Q++,ae=Q++,se="start",ue="data",ce="end",fe=Q++,he=Q++,le=Q++,de=Q++;function pe(e,t,r){try{var n=a.parse(t)}catch(e){}return{statusCode:e,body:t,jsonBody:n,thrown:r}}function be(e,t){var r={node:e(te),path:e(ee)};function n(t,r,n){var i=e(t).emit;r.on(function(e){var t=n(e);!1!==t&&function(e,t,r){var n=B(r);e(t,I(k(T(W,n))),I(T(Y,n)))}(i,Y(t),e)},t),e("removeListener").on(function(n){n==t&&(e(n).listeners()||r.un(t))})}e("newListener").on(function(e){var i=/(node|path):(.*)/.exec(e);if(i){var o=r[i[1]];o.hasListener(e)||n(e,o,t(i[2]))}})}function ye(e,t){var r,n=/^(node|path):./,i=e(oe),o=e(ne).emit,a=e(re).emit,s=d(function(t,i){if(r[t])l(i,r[t]);else{var o=e(t),a=i[0];n.test(t)?c(o,a):o.on(a)}return r});function c(e,t,n){n=n||t;var i=f(t);return e.on(function(){var t=!1;r.forget=function(){t=!0},l(arguments,i),delete r.forget,t&&e.un(n)},n),r}function f(e){return function(){try{return e.apply(r,arguments)}catch(e){setTimeout(function(){throw e})}}}function h(t,r,n){var i;i="node"==t?function(e){return function(){var t=e.apply(this,arguments);w(t)&&(t==ge.drop?o():a(t))}}(n):n,c(function(t,r){return e(t+":"+r)}(t,r),i,n)}function p(e,t,n){return g(t)?h(e,t,n):function(e,t){for(var r in t)h(e,r,t[r])}(e,t),r}return e(ae).on(function(e){var t;r.root=(t=e,function(){return t})}),e(se).on(function(e,t){r.header=function(e){return e?t[e]:t}}),r={on:s,addListener:s,removeListener:function(t,n,o){if("done"==t)i.un(n);else if("node"==t||"path"==t)e.un(t+":"+n,o);else{var a=n;e(t).un(a)}return r},emit:e.emit,node:u(p,"node"),path:u(p,"path"),done:u(c,i),start:u(function(t,n){return e(t).on(f(n),n),r},se),fail:e(ie).on,abort:e(fe).emit,header:b,root:b,source:t}}function me(t,r,n,i,o){var a=function(){var e={},t=n("newListener"),r=n("removeListener");function n(n){return e[n]=$(n,t,r)}function i(t){return e[t]||n(t)}return["emit","on","un"].forEach(function(e){i[e]=d(function(t,r){l(r,i(t)[e])})}),i}();return r&&function(t,r,n,i,o,a,c){"use strict";var f=t(ue).emit,h=t(ie).emit,l=0,d=!0;function p(){var e=r.responseText,t=e.substr(l);t&&f(t),l=v(e)}t(fe).on(function(){r.onreadystatechange=null,r.abort()}),"onprogress"in r&&(r.onprogress=p),r.onreadystatechange=function(){function e(){try{d&&t(se).emit(r.status,(e=r.getAllResponseHeaders(),n={},e&&e.split("\r\n").forEach(function(e){var t=e.indexOf(": ");n[e.substring(0,t)]=e.substring(t+2)}),n)),d=!1}catch(e){}var e,n}switch(r.readyState){case 2:case 3:return e();case 4:e(),2==String(r.status)[0]?(p(),t(ce).emit()):h(pe(r.status,r.responseText))}};try{for(var b in r.open(n,i,!0),a)r.setRequestHeader(b,a[b]);(function(e,t){function r(t){return t.port||{"http:":80,"https:":443}[t.protocol||e.protocol]}return!!(t.protocol&&t.protocol!=e.protocol||t.host&&t.host!=e.host||t.host&&r(t)!=r(e))})(e.location,function(e){var t=/(\w+:)?(?:\/\/)([\w.-]+)?(?::(\d+))?\/?/.exec(e)||[];return{protocol:t[1]||"",host:t[2]||"",port:t[3]||""}}(i))||r.setRequestHeader("X-Requested-With","XMLHttpRequest"),r.withCredentials=c,r.send(o)}catch(t){e.setTimeout(u(h,pe(s,s,t)),0)}}(a,new XMLHttpRequest,t,r,n,i,o),P(a),function(e,t){"use strict";var r,n={};function i(e){return function(t){r=e(r,t)}}for(var o in t)e(o).on(i(t[o]),n);e(re).on(function(e){var t=x(r),n=W(t),i=k(r);i&&(Y(x(i))[n]=e)}),e(ne).on(function(){var e=x(r),t=W(e),n=k(r);n&&delete Y(x(n))[t]}),e(fe).on(function(){for(var r in t)e(r).un(n)})}(a,Z(a)),be(a,J),ye(a,r)}function ve(e,t,r,n,i,o,s){return i=i?a.parse(a.stringify(i)):{},n?g(n)||(n=a.stringify(n),i["Content-Type"]=i["Content-Type"]||"application/json"):n=null,e(r||"GET",function(e,t){return!1===t&&(-1==e.indexOf("?")?e+="?":e+="&",e+="_="+(new Date).getTime()),e}(t,s),n,i,o||!1)}function ge(e){var t=M("resume","pause","pipe"),r=u(_,t);return e?r(e)||g(e)?ve(me,e):ve(me,e.url,e.method,e.body,e.headers,e.withCredentials,e.cached):me()}ge.drop=function(){return ge.drop},"function"==typeof define&&define.amd?define("oboe",[],function(){return ge}):"object"==typeof r?t.exports=ge:e.oboe=ge}(function(){try{return window}catch(e){return self}}(),Object,Array,Error,JSON)},{}],240:[function(e,t,r){r.endianness=function(){return"LE"},r.hostname=function(){return"undefined"!=typeof location?location.hostname:""},r.loadavg=function(){return[]},r.uptime=function(){return 0},r.freemem=function(){return Number.MAX_VALUE},r.totalmem=function(){return Number.MAX_VALUE},r.cpus=function(){return[]},r.type=function(){return"Browser"},r.release=function(){return"undefined"!=typeof navigator?navigator.appVersion:""},r.networkInterfaces=r.getNetworkInterfaces=function(){return{}},r.arch=function(){return"javascript"},r.platform=function(){return"browser"},r.tmpdir=r.tmpDir=function(){return"/tmp"},r.EOL="\n",r.homedir=function(){return"/"}},{}],241:[function(e,t,r){t.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","2.16.840.1.101.3.4.1.3":"aes-128-ofb","2.16.840.1.101.3.4.1.4":"aes-128-cfb","2.16.840.1.101.3.4.1.21":"aes-192-ecb","2.16.840.1.101.3.4.1.22":"aes-192-cbc","2.16.840.1.101.3.4.1.23":"aes-192-ofb","2.16.840.1.101.3.4.1.24":"aes-192-cfb","2.16.840.1.101.3.4.1.41":"aes-256-ecb","2.16.840.1.101.3.4.1.42":"aes-256-cbc","2.16.840.1.101.3.4.1.43":"aes-256-ofb","2.16.840.1.101.3.4.1.44":"aes-256-cfb"}},{}],242:[function(e,t,r){"use strict";var n=e("asn1.js");r.certificate=e("./certificate");var i=n.define("RSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("modulus").int(),this.key("publicExponent").int(),this.key("privateExponent").int(),this.key("prime1").int(),this.key("prime2").int(),this.key("exponent1").int(),this.key("exponent2").int(),this.key("coefficient").int())});r.RSAPrivateKey=i;var o=n.define("RSAPublicKey",function(){this.seq().obj(this.key("modulus").int(),this.key("publicExponent").int())});r.RSAPublicKey=o;var a=n.define("SubjectPublicKeyInfo",function(){this.seq().obj(this.key("algorithm").use(s),this.key("subjectPublicKey").bitstr())});r.PublicKey=a;var s=n.define("AlgorithmIdentifier",function(){this.seq().obj(this.key("algorithm").objid(),this.key("none").null_().optional(),this.key("curve").objid().optional(),this.key("params").seq().obj(this.key("p").int(),this.key("q").int(),this.key("g").int()).optional())}),u=n.define("PrivateKeyInfo",function(){this.seq().obj(this.key("version").int(),this.key("algorithm").use(s),this.key("subjectPrivateKey").octstr())});r.PrivateKey=u;var c=n.define("EncryptedPrivateKeyInfo",function(){this.seq().obj(this.key("algorithm").seq().obj(this.key("id").objid(),this.key("decrypt").seq().obj(this.key("kde").seq().obj(this.key("id").objid(),this.key("kdeparams").seq().obj(this.key("salt").octstr(),this.key("iters").int())),this.key("cipher").seq().obj(this.key("algo").objid(),this.key("iv").octstr()))),this.key("subjectPrivateKey").octstr())});r.EncryptedPrivateKey=c;var f=n.define("DSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("p").int(),this.key("q").int(),this.key("g").int(),this.key("pub_key").int(),this.key("priv_key").int())});r.DSAPrivateKey=f,r.DSAparam=n.define("DSAparam",function(){this.int()});var h=n.define("ECPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").optional().explicit(0).use(l),this.key("publicKey").optional().explicit(1).bitstr())});r.ECPrivateKey=h;var l=n.define("ECParameters",function(){this.choice({namedCurve:this.objid()})});r.signature=n.define("signature",function(){this.seq().obj(this.key("r").int(),this.key("s").int())})},{"./certificate":243,"asn1.js":5}],243:[function(e,t,r){"use strict";var n=e("asn1.js"),i=n.define("Time",function(){this.choice({utcTime:this.utctime(),generalTime:this.gentime()})}),o=n.define("AttributeTypeValue",function(){this.seq().obj(this.key("type").objid(),this.key("value").any())}),a=n.define("AlgorithmIdentifier",function(){this.seq().obj(this.key("algorithm").objid(),this.key("parameters").optional())}),s=n.define("SubjectPublicKeyInfo",function(){this.seq().obj(this.key("algorithm").use(a),this.key("subjectPublicKey").bitstr())}),u=n.define("RelativeDistinguishedName",function(){this.setof(o)}),c=n.define("RDNSequence",function(){this.seqof(u)}),f=n.define("Name",function(){this.choice({rdnSequence:this.use(c)})}),h=n.define("Validity",function(){this.seq().obj(this.key("notBefore").use(i),this.key("notAfter").use(i))}),l=n.define("Extension",function(){this.seq().obj(this.key("extnID").objid(),this.key("critical").bool().def(!1),this.key("extnValue").octstr())}),d=n.define("TBSCertificate",function(){this.seq().obj(this.key("version").explicit(0).int(),this.key("serialNumber").int(),this.key("signature").use(a),this.key("issuer").use(f),this.key("validity").use(h),this.key("subject").use(f),this.key("subjectPublicKeyInfo").use(s),this.key("issuerUniqueID").implicit(1).bitstr().optional(),this.key("subjectUniqueID").implicit(2).bitstr().optional(),this.key("extensions").explicit(3).seqof(l).optional())}),p=n.define("X509Certificate",function(){this.seq().obj(this.key("tbsCertificate").use(d),this.key("signatureAlgorithm").use(a),this.key("signatureValue").bitstr())});t.exports=p},{"asn1.js":5}],244:[function(e,t,r){(function(r){var n=/Proc-Type: 4,ENCRYPTED\n\r?DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)\n\r?\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?/m,i=/^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----\n/m,o=/^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?-----END \1-----$/m,a=e("evp_bytestokey"),s=e("browserify-aes");t.exports=function(e,t){var u,c=e.toString(),f=c.match(n);if(f){var h="aes"+f[1],l=new r(f[2],"hex"),d=new r(f[3].replace(/\r?\n/g,""),"base64"),p=a(t,l.slice(0,8),parseInt(f[1],10)).key,b=[],y=s.createDecipheriv(h,p,l);b.push(y.update(d)),b.push(y.final()),u=r.concat(b)}else{var m=c.match(o);u=new r(m[2].replace(/\r?\n/g,""),"base64")}return{tag:c.match(i)[1],data:u}}}).call(this,e("buffer").Buffer)},{"browserify-aes":58,buffer:84,evp_bytestokey:158}],245:[function(e,t,r){(function(r){var n=e("./asn1"),i=e("./aesid.json"),o=e("./fixProc"),a=e("browserify-aes"),s=e("pbkdf2");function u(e){var t;"object"!=typeof e||r.isBuffer(e)||(t=e.passphrase,e=e.key),"string"==typeof e&&(e=new r(e));var u,c,f=o(e,t),h=f.tag,l=f.data;switch(h){case"CERTIFICATE":c=n.certificate.decode(l,"der").tbsCertificate.subjectPublicKeyInfo;case"PUBLIC KEY":switch(c||(c=n.PublicKey.decode(l,"der")),u=c.algorithm.algorithm.join(".")){case"1.2.840.113549.1.1.1":return n.RSAPublicKey.decode(c.subjectPublicKey.data,"der");case"1.2.840.10045.2.1":return c.subjectPrivateKey=c.subjectPublicKey,{type:"ec",data:c};case"1.2.840.10040.4.1":return c.algorithm.params.pub_key=n.DSAparam.decode(c.subjectPublicKey.data,"der"),{type:"dsa",data:c.algorithm.params};default:throw new Error("unknown key id "+u)}throw new Error("unknown key type "+h);case"ENCRYPTED PRIVATE KEY":l=function(e,t){var n=e.algorithm.decrypt.kde.kdeparams.salt,o=parseInt(e.algorithm.decrypt.kde.kdeparams.iters.toString(),10),u=i[e.algorithm.decrypt.cipher.algo.join(".")],c=e.algorithm.decrypt.cipher.iv,f=e.subjectPrivateKey,h=parseInt(u.split("-")[1],10)/8,l=s.pbkdf2Sync(t,n,o,h),d=a.createDecipheriv(u,l,c),p=[];return p.push(d.update(f)),p.push(d.final()),r.concat(p)}(l=n.EncryptedPrivateKey.decode(l,"der"),t);case"PRIVATE KEY":switch(u=(c=n.PrivateKey.decode(l,"der")).algorithm.algorithm.join(".")){case"1.2.840.113549.1.1.1":return n.RSAPrivateKey.decode(c.subjectPrivateKey,"der");case"1.2.840.10045.2.1":return{curve:c.algorithm.curve,privateKey:n.ECPrivateKey.decode(c.subjectPrivateKey,"der").privateKey};case"1.2.840.10040.4.1":return c.algorithm.params.priv_key=n.DSAparam.decode(c.subjectPrivateKey,"der"),{type:"dsa",params:c.algorithm.params};default:throw new Error("unknown key id "+u)}throw new Error("unknown key type "+h);case"RSA PUBLIC KEY":return n.RSAPublicKey.decode(l,"der");case"RSA PRIVATE KEY":return n.RSAPrivateKey.decode(l,"der");case"DSA PRIVATE KEY":return{type:"dsa",params:n.DSAPrivateKey.decode(l,"der")};case"EC PRIVATE KEY":return{curve:(l=n.ECPrivateKey.decode(l,"der")).parameters.value,privateKey:l.privateKey};default:throw new Error("unknown key type "+h)}}t.exports=u,u.signature=n.signature}).call(this,e("buffer").Buffer)},{"./aesid.json":241,"./asn1":242,"./fixProc":244,"browserify-aes":58,buffer:84,pbkdf2:247}],246:[function(e,t,r){var n=e("trim"),i=e("for-each");t.exports=function(e){if(!e)return{};var t={};return i(n(e).split("\n"),function(e){var r,i=e.indexOf(":"),o=n(e.slice(0,i)).toLowerCase(),a=n(e.slice(i+1));void 0===t[o]?t[o]=a:(r=t[o],"[object Array]"===Object.prototype.toString.call(r)?t[o].push(a):t[o]=[t[o],a])}),t}},{"for-each":159,trim:324}],247:[function(e,t,r){r.pbkdf2=e("./lib/async"),r.pbkdf2Sync=e("./lib/sync")},{"./lib/async":248,"./lib/sync":251}],248:[function(e,t,r){(function(r,n){var i,o=e("./precondition"),a=e("./default-encoding"),s=e("./sync"),u=e("safe-buffer").Buffer,c=n.crypto&&n.crypto.subtle,f={sha:"SHA-1","sha-1":"SHA-1",sha1:"SHA-1",sha256:"SHA-256","sha-256":"SHA-256",sha384:"SHA-384","sha-384":"SHA-384","sha-512":"SHA-512",sha512:"SHA-512"},h=[];function l(e,t,r,n,i){return c.importKey("raw",e,{name:"PBKDF2"},!1,["deriveBits"]).then(function(e){return c.deriveBits({name:"PBKDF2",salt:t,iterations:r,hash:{name:i}},e,n<<3)}).then(function(e){return u.from(e)})}t.exports=function(e,t,d,p,b,y){if(u.isBuffer(e)||(e=u.from(e,a)),u.isBuffer(t)||(t=u.from(t,a)),o(d,p),"function"==typeof b&&(y=b,b=void 0),"function"!=typeof y)throw new Error("No callback provided to pbkdf2");var m=f[(b=b||"sha1").toLowerCase()];if(!m||"function"!=typeof n.Promise)return r.nextTick(function(){var r;try{r=s(e,t,d,p,b)}catch(e){return y(e)}y(null,r)});!function(e,t){e.then(function(e){r.nextTick(function(){t(null,e)})},function(e){r.nextTick(function(){t(e)})})}(function(e){if(n.process&&!n.process.browser)return Promise.resolve(!1);if(!c||!c.importKey||!c.deriveBits)return Promise.resolve(!1);if(void 0!==h[e])return h[e];var t=l(i=i||u.alloc(8),i,10,128,e).then(function(){return!0}).catch(function(){return!1});return h[e]=t,t}(m).then(function(r){return r?l(e,t,d,p,m):s(e,t,d,p,b)}),y)}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./default-encoding":249,"./precondition":250,"./sync":251,_process:257,"safe-buffer":290}],249:[function(e,t,r){(function(e){var r;e.browser?r="utf-8":r=parseInt(e.version.split(".")[0].slice(1),10)>=6?"utf-8":"binary";t.exports=r}).call(this,e("_process"))},{_process:257}],250:[function(e,t,r){var n=Math.pow(2,30)-1;t.exports=function(e,t){if("number"!=typeof e)throw new TypeError("Iterations not a number");if(e<0)throw new TypeError("Bad iterations");if("number"!=typeof t)throw new TypeError("Key length not a number");if(t<0||t>n||t!=t)throw new TypeError("Bad key length")}},{}],251:[function(e,t,r){var n=e("create-hash/md5"),i=e("ripemd160"),o=e("sha.js"),a=e("./precondition"),s=e("./default-encoding"),u=e("safe-buffer").Buffer,c=u.alloc(128),f={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,rmd160:20,ripemd160:20};function h(e,t,r){var a=function(e){return"rmd160"===e||"ripemd160"===e?i:"md5"===e?n:function(t){return o(e).update(t).digest()}}(e),s="sha512"===e||"sha384"===e?128:64;t.length>s?t=a(t):t.length1)for(var r=1;rp||new a(t).cmp(d.modulus)>=0)throw new Error("decryption error");l=f?c(new a(t),d):s(t,d);var b=new r(p-l.length);if(b.fill(0),l=r.concat([b,l],p),4===h)return function(e,t){e.modulus;var n=e.modulus.byteLength(),a=(t.length,u("sha1").update(new r("")).digest()),s=a.length;if(0!==t[0])throw new Error("decryption error");var c=t.slice(1,s+1),f=t.slice(s+1),h=o(c,i(f,s)),l=o(f,i(h,n-s-1));if(function(e,t){e=new r(e),t=new r(t);var n=0,i=e.length;e.length!==t.length&&(n++,i=Math.min(e.length,t.length));var o=-1;for(;++o=t.length){o++;break}var a=t.slice(2,i-1);t.slice(i-1,i);("0002"!==n.toString("hex")&&!r||"0001"!==n.toString("hex")&&r)&&o++;a.length<8&&o++;if(o)throw new Error("decryption error");return t.slice(i)}(0,l,f);if(3===h)return l;throw new Error("unknown padding")}}).call(this,e("buffer").Buffer)},{"./mgf":260,"./withPublic":263,"./xor":264,"bn.js":53,"browserify-rsa":76,buffer:84,"create-hash":91,"parse-asn1":245}],262:[function(e,t,r){(function(r){var n=e("parse-asn1"),i=e("randombytes"),o=e("create-hash"),a=e("./mgf"),s=e("./xor"),u=e("bn.js"),c=e("./withPublic"),f=e("browserify-rsa");t.exports=function(e,t,h){var l;l=e.padding?e.padding:h?1:4;var d,p=n(e);if(4===l)d=function(e,t){var n=e.modulus.byteLength(),c=t.length,f=o("sha1").update(new r("")).digest(),h=f.length,l=2*h;if(c>n-l-2)throw new Error("message too long");var d=new r(n-c-l-2);d.fill(0);var p=n-h-1,b=i(h),y=s(r.concat([f,d,new r([1]),t],p),a(b,p)),m=s(b,a(y,h));return new u(r.concat([new r([0]),m,y],n))}(p,t);else if(1===l)d=function(e,t,n){var o,a=t.length,s=e.modulus.byteLength();if(a>s-11)throw new Error("message too long");n?(o=new r(s-a-3)).fill(255):o=function(e,t){var n,o=new r(e),a=0,s=i(2*e),u=0;for(;a=0)throw new Error("data too long for modulus")}return h?f(d,p):c(d,p)}}).call(this,e("buffer").Buffer)},{"./mgf":260,"./withPublic":263,"./xor":264,"bn.js":53,"browserify-rsa":76,buffer:84,"create-hash":91,"parse-asn1":245,randombytes:270}],263:[function(e,t,r){(function(r){var n=e("bn.js");t.exports=function(e,t){return new r(e.toRed(n.mont(t.modulus)).redPow(new n(t.publicExponent)).fromRed().toArray())}}).call(this,e("buffer").Buffer)},{"bn.js":53,buffer:84}],264:[function(e,t,r){t.exports=function(e,t){for(var r=e.length,n=-1;++n= 0x80 (not a basic code point)","invalid-input":"Invalid input"},A=f-h,E=Math.floor,x=String.fromCharCode;function k(e){throw new RangeError(_[e])}function S(e,t){for(var r=e.length,n=[];r--;)n[r]=t(e[r]);return n}function M(e,t){var r=e.split("@"),n="";return r.length>1&&(n=r[0]+"@",e=r[1]),n+S((e=e.replace(w,".")).split("."),t).join(".")}function I(e){for(var t,r,n=[],i=0,o=e.length;i=55296&&t<=56319&&i65535&&(t+=x((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=x(e)}).join("")}function U(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function j(e,t,r){var n=0;for(e=r?E(e/p):e>>1,e+=E(e/t);e>A*l>>1;n+=f)e=E(e/A);return E(n+(A+1)*e/(e+d))}function B(e){var t,r,n,i,o,a,s,u,d,p,v,g=[],w=e.length,_=0,A=y,x=b;for((r=e.lastIndexOf(m))<0&&(r=0),n=0;n=128&&k("not-basic"),g.push(e.charCodeAt(n));for(i=r>0?r+1:0;i=w&&k("invalid-input"),((u=(v=e.charCodeAt(i++))-48<10?v-22:v-65<26?v-65:v-97<26?v-97:f)>=f||u>E((c-_)/a))&&k("overflow"),_+=u*a,!(u<(d=s<=x?h:s>=x+l?l:s-x));s+=f)a>E(c/(p=f-d))&&k("overflow"),a*=p;x=j(_-o,t=g.length+1,0==o),E(_/t)>c-A&&k("overflow"),A+=E(_/t),_%=t,g.splice(_++,0,A)}return T(g)}function P(e){var t,r,n,i,o,a,s,u,d,p,v,g,w,_,A,S=[];for(g=(e=I(e)).length,t=y,r=0,o=b,a=0;a=t&&vE((c-r)/(w=n+1))&&k("overflow"),r+=(s-t)*w,t=s,a=0;ac&&k("overflow"),v==t){for(u=r,d=f;!(u<(p=d<=o?h:d>=o+l?l:d-o));d+=f)A=u-p,_=f-p,S.push(x(U(p+A%_,0))),u=E(A/_);S.push(x(U(u,0))),o=j(r,w,n==i),r=0,++n}++r,++t}return S.join("")}if(s={version:"1.4.1",ucs2:{decode:I,encode:T},decode:B,encode:P,toASCII:function(e){return M(e,function(e){return g.test(e)?"xn--"+P(e):e})},toUnicode:function(e){return M(e,function(e){return v.test(e)?B(e.slice(4).toLowerCase()):e})}},"function"==typeof define&&"object"==typeof define.amd&&define.amd)define("punycode",function(){return s});else if(i&&o)if(t.exports==i)o.exports=s;else for(u in s)s.hasOwnProperty(u)&&(i[u]=s[u]);else n.punycode=s}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],266:[function(e,t,r){"use strict";var n=e("strict-uri-encode"),i=e("object-assign"),o=e("decode-uri-component");function a(e,t){return t.encode?t.strict?n(e):encodeURIComponent(e):e}function s(e){var t=e.indexOf("?");return-1===t?"":e.slice(t+1)}function u(e,t){var r=function(e){var t;switch(e.arrayFormat){case"index":return function(e,r,n){t=/\[(\d*)\]$/.exec(e),e=e.replace(/\[\d*\]$/,""),t?(void 0===n[e]&&(n[e]={}),n[e][t[1]]=r):n[e]=r};case"bracket":return function(e,r,n){t=/(\[\])$/.exec(e),e=e.replace(/\[\]$/,""),t?void 0!==n[e]?n[e]=[].concat(n[e],r):n[e]=[r]:n[e]=r};default:return function(e,t,r){void 0!==r[e]?r[e]=[].concat(r[e],t):r[e]=t}}}(t=i({arrayFormat:"none"},t)),n=Object.create(null);return"string"!=typeof e?n:(e=e.trim().replace(/^[?#&]/,""))?(e.split("&").forEach(function(e){var t=e.replace(/\+/g," ").split("="),i=t.shift(),a=t.length>0?t.join("="):void 0;a=void 0===a?null:o(a),r(o(i),a,n)}),Object.keys(n).sort().reduce(function(e,t){var r=n[t];return Boolean(r)&&"object"==typeof r&&!Array.isArray(r)?e[t]=function e(t){return Array.isArray(t)?t.sort():"object"==typeof t?e(Object.keys(t)).sort(function(e,t){return Number(e)-Number(t)}).map(function(e){return t[e]}):t}(r):e[t]=r,e},Object.create(null))):n}r.extract=s,r.parse=u,r.stringify=function(e,t){!1===(t=i({encode:!0,strict:!0,arrayFormat:"none"},t)).sort&&(t.sort=function(){});var r=function(e){switch(e.arrayFormat){case"index":return function(t,r,n){return null===r?[a(t,e),"[",n,"]"].join(""):[a(t,e),"[",a(n,e),"]=",a(r,e)].join("")};case"bracket":return function(t,r){return null===r?a(t,e):[a(t,e),"[]=",a(r,e)].join("")};default:return function(t,r){return null===r?a(t,e):[a(t,e),"=",a(r,e)].join("")}}}(t);return e?Object.keys(e).sort(t.sort).map(function(n){var i=e[n];if(void 0===i)return"";if(null===i)return a(n,t);if(Array.isArray(i)){var o=[];return i.slice().forEach(function(e){void 0!==e&&o.push(r(n,e,o.length))}),o.join("&")}return a(n,t)+"="+a(i,t)}).filter(function(e){return e.length>0}).join("&"):""},r.parseUrl=function(e,t){return{url:e.split("?")[0]||"",query:u(s(e),t)}}},{"decode-uri-component":98,"object-assign":238,"strict-uri-encode":316}],267:[function(e,t,r){"use strict";function n(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.exports=function(e,t,r,o){t=t||"&",r=r||"=";var a={};if("string"!=typeof e||0===e.length)return a;var s=/\+/g;e=e.split(t);var u=1e3;o&&"number"==typeof o.maxKeys&&(u=o.maxKeys);var c=e.length;u>0&&c>u&&(c=u);for(var f=0;f=0?(h=b.substr(0,y),l=b.substr(y+1)):(h=b,l=""),d=decodeURIComponent(h),p=decodeURIComponent(l),n(a,d)?i(a[d])?a[d].push(p):a[d]=[a[d],p]:a[d]=p}return a};var i=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],268:[function(e,t,r){"use strict";var n=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,r,s){return t=t||"&",r=r||"=",null===e&&(e=void 0),"object"==typeof e?o(a(e),function(a){var s=encodeURIComponent(n(a))+r;return i(e[a])?o(e[a],function(e){return s+encodeURIComponent(n(e))}).join(t):s+encodeURIComponent(n(e[a]))}).join(t):s?encodeURIComponent(n(s))+r+encodeURIComponent(n(e)):""};var i=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function o(e,t){if(e.map)return e.map(t);for(var r=[],n=0;n65536)throw new Error("requested too many random bytes");var a=new n.Uint8Array(e);e>0&&o.getRandomValues(a);var s=i.from(a.buffer);if("function"==typeof t)return r.nextTick(function(){t(null,s)});return s}:t.exports=function(){throw new Error("Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11")}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:257,"safe-buffer":290}],271:[function(e,t,r){(function(t,n){"use strict";function i(){throw new Error("secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11")}var o=e("safe-buffer"),a=e("randombytes"),s=o.Buffer,u=o.kMaxLength,c=n.crypto||n.msCrypto,f=Math.pow(2,32)-1;function h(e,t){if("number"!=typeof e||e!=e)throw new TypeError("offset must be a number");if(e>f||e<0)throw new TypeError("offset must be a uint32");if(e>u||e>t)throw new RangeError("offset out of range")}function l(e,t,r){if("number"!=typeof e||e!=e)throw new TypeError("size must be a number");if(e>f||e<0)throw new TypeError("size must be a uint32");if(e+t>r||e>u)throw new RangeError("buffer too small")}function d(e,r,n,i){if(t.browser){var o=e.buffer,s=new Uint8Array(o,r,n);return c.getRandomValues(s),i?void t.nextTick(function(){i(null,e)}):e}if(!i)return a(n).copy(e,r),e;a(n,function(t,n){if(t)return i(t);n.copy(e,r),i(null,e)})}c&&c.getRandomValues||!t.browser?(r.randomFill=function(e,t,r,i){if(!(s.isBuffer(e)||e instanceof n.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');if("function"==typeof t)i=t,t=0,r=e.length;else if("function"==typeof r)i=r,r=e.length-t;else if("function"!=typeof i)throw new TypeError('"cb" argument must be a function');return h(t,e.length),l(r,t,e.length),d(e,t,r,i)},r.randomFillSync=function(e,t,r){void 0===t&&(t=0);if(!(s.isBuffer(e)||e instanceof n.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');h(t,e.length),void 0===r&&(r=e.length-t);return l(r,t,e.length),d(e,t,r)}):(r.randomFill=i,r.randomFillSync=i)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:257,randombytes:270,"safe-buffer":290}],272:[function(e,t,r){t.exports=window.crypto},{}],273:[function(e,t,r){t.exports=e("crypto")},{crypto:272}],274:[function(e,t,r){t.exports=function(t,r){var n=e("./crypto.js"),i="function"==typeof r;if(t>65536){if(!i)throw new Error("Requested too many random bytes.");r(new Error("Requested too many random bytes."))}if(void 0!==n&&n.randomBytes){if(!i)return"0x"+n.randomBytes(t).toString("hex");n.randomBytes(t,function(e,t){e?r(u):r(null,"0x"+t.toString("hex"))})}else{var o;if(void 0!==n?o=n:"undefined"!=typeof msCrypto&&(o=msCrypto),o&&o.getRandomValues){var a=o.getRandomValues(new Uint8Array(t)),s="0x"+Array.from(a).map(function(e){return e.toString(16)}).join("");if(!i)return s;r(null,s)}else{var u=new Error('No "crypto" object available. This Browser doesn\'t support generating secure random bytes.');if(!i)throw u;r(u)}}}},{"./crypto.js":273}],275:[function(e,t,r){t.exports=e("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":276}],276:[function(e,t,r){"use strict";var n=e("process-nextick-args").nextTick,i=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};t.exports=h;var o=e("core-util-is");o.inherits=e("inherits");var a=e("./_stream_readable"),s=e("./_stream_writable");o.inherits(h,a);for(var u=i(s.prototype),c=0;c0?("string"==typeof t||a.objectMode||Object.getPrototypeOf(t)===c.prototype||(t=function(e){return c.from(e)}(t)),n?a.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):_(e,a,t,!0):a.ended?e.emit("error",new Error("stream.push() after EOF")):(a.reading=!1,a.decoder&&!r?(t=a.decoder.write(t),a.objectMode||0!==t.length?_(e,a,t,!1):S(e,a)):_(e,a,t,!1))):n||(a.reading=!1));return function(e){return!e.ended&&(e.needReadable||e.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=A?e=A:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function x(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(d("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?i(k,e):k(e))}function k(e){d("emit readable"),e.emit("readable"),U(e)}function S(e,t){t.readingMore||(t.readingMore=!0,i(M,e,t))}function M(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):r=function(e,t,r){var n;eo.length?o.length:e;if(a===o.length?i+=o:i+=o.slice(0,e),0===(e-=a)){a===o.length?(++n,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=o.slice(a));break}++n}return t.length-=n,i}(e,t):function(e,t){var r=c.allocUnsafe(e),n=t.head,i=1;n.data.copy(r),e-=n.data.length;for(;n=n.next;){var o=n.data,a=e>o.length?o.length:e;if(o.copy(r,r.length-e,0,a),0===(e-=a)){a===o.length?(++i,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(a));break}++i}return t.length-=i,r}(e,t);return n}(e,t.buffer,t.decoder),r);var r}function B(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,i(P,t,e))}function P(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function C(e,t){for(var r=0,n=e.length;r=t.highWaterMark||t.ended))return d("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?B(this):x(this),null;if(0===(e=E(e,t))&&t.ended)return 0===t.length&&B(this),null;var n,i=t.needReadable;return d("need readable",i),(0===t.length||t.length-e0?j(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&B(this)),null!==n&&this.emit("data",n),n},g.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},g.prototype.pipe=function(e,t){var n=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,d("pipe count=%d opts=%j",o.pipesCount,t);var u=(!t||!1!==t.end)&&e!==r.stdout&&e!==r.stderr?f:g;function c(t,r){d("onunpipe"),t===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,d("cleanup"),e.removeListener("close",m),e.removeListener("finish",v),e.removeListener("drain",h),e.removeListener("error",y),e.removeListener("unpipe",c),n.removeListener("end",f),n.removeListener("end",g),n.removeListener("data",b),l=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||h())}function f(){d("onend"),e.end()}o.endEmitted?i(u):n.once("end",u),e.on("unpipe",c);var h=function(e){return function(){var t=e._readableState;d("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&s(e,"data")&&(t.flowing=!0,U(e))}}(n);e.on("drain",h);var l=!1;var p=!1;function b(t){d("ondata"),p=!1,!1!==e.write(t)||p||((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==C(o.pipes,e))&&!l&&(d("false write response, pause",n._readableState.awaitDrain),n._readableState.awaitDrain++,p=!0),n.pause())}function y(t){d("onerror",t),g(),e.removeListener("error",y),0===s(e,"error")&&e.emit("error",t)}function m(){e.removeListener("finish",v),g()}function v(){d("onfinish"),e.removeListener("close",m),g()}function g(){d("unpipe"),n.unpipe(e)}return n.on("data",b),function(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?a(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}(e,"error",y),e.once("close",m),e.once("finish",v),e.emit("pipe",n),o.flowing||(d("pipe resume"),n.resume()),e},g.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r),this);if(!e){var n=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o-1?setImmediate:i;m.WritableState=y;var u=e("core-util-is");u.inherits=e("inherits");var c={deprecate:e("util-deprecate")},f=e("./internal/streams/stream"),h=e("safe-buffer").Buffer,l=n.Uint8Array||function(){};var d,p=e("./internal/streams/destroy");function b(){}function y(t,r){a=a||e("./_stream_duplex"),t=t||{};var n=r instanceof a;this.objectMode=!!t.objectMode,n&&(this.objectMode=this.objectMode||!!t.writableObjectMode);var u=t.highWaterMark,c=t.writableHighWaterMark,f=this.objectMode?16:16384;this.highWaterMark=u||0===u?u:n&&(c||0===c)?c:f,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var h=!1===t.decodeStrings;this.decodeStrings=!h,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var r=e._writableState,n=r.sync,o=r.writecb;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(r),t)!function(e,t,r,n,o){--t.pendingcb,r?(i(o,n),i(E,e,t),e._writableState.errorEmitted=!0,e.emit("error",n)):(o(n),e._writableState.errorEmitted=!0,e.emit("error",n),E(e,t))}(e,r,n,t,o);else{var a=_(r);a||r.corked||r.bufferProcessing||!r.bufferedRequest||w(e,r),n?s(g,e,r,a,o):g(e,r,a,o)}}(r,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new o(this)}function m(t){if(a=a||e("./_stream_duplex"),!(d.call(m,this)||this instanceof a))return new m(t);this._writableState=new y(t,this),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),f.call(this)}function v(e,t,r,n,i,o,a){t.writelen=n,t.writecb=a,t.writing=!0,t.sync=!0,r?e._writev(i,t.onwrite):e._write(i,o,t.onwrite),t.sync=!1}function g(e,t,r,n){r||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,n(),E(e,t)}function w(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var n=t.bufferedRequestCount,i=new Array(n),a=t.corkedRequestsFree;a.entry=r;for(var s=0,u=!0;r;)i[s]=r,r.isBuf||(u=!1),r=r.next,s+=1;i.allBuffers=u,v(e,t,!0,t.length,i,"",a.finish),t.pendingcb++,t.lastBufferedRequest=null,a.next?(t.corkedRequestsFree=a.next,a.next=null):t.corkedRequestsFree=new o(t),t.bufferedRequestCount=0}else{for(;r;){var c=r.chunk,f=r.encoding,h=r.callback;if(v(e,t,!1,t.objectMode?1:c.length,c,f,h),r=r.next,t.bufferedRequestCount--,t.writing)break}null===r&&(t.lastBufferedRequest=null)}t.bufferedRequest=r,t.bufferProcessing=!1}function _(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function A(e,t){e._final(function(r){t.pendingcb--,r&&e.emit("error",r),t.prefinished=!0,e.emit("prefinish"),E(e,t)})}function E(e,t){var r=_(t);return r&&(!function(e,t){t.prefinished||t.finalCalled||("function"==typeof e._final?(t.pendingcb++,t.finalCalled=!0,i(A,e,t)):(t.prefinished=!0,e.emit("prefinish")))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"))),r}u.inherits(m,f),y.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(y.prototype,"buffer",{get:c.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(d=Function.prototype[Symbol.hasInstance],Object.defineProperty(m,Symbol.hasInstance,{value:function(e){return!!d.call(this,e)||this===m&&(e&&e._writableState instanceof y)}})):d=function(e){return e instanceof this},m.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},m.prototype.write=function(e,t,r){var n,o=this._writableState,a=!1,s=!o.objectMode&&(n=e,h.isBuffer(n)||n instanceof l);return s&&!h.isBuffer(e)&&(e=function(e){return h.from(e)}(e)),"function"==typeof t&&(r=t,t=null),s?t="buffer":t||(t=o.defaultEncoding),"function"!=typeof r&&(r=b),o.ended?function(e,t){var r=new Error("write after end");e.emit("error",r),i(t,r)}(this,r):(s||function(e,t,r,n){var o=!0,a=!1;return null===r?a=new TypeError("May not write null values to stream"):"string"==typeof r||void 0===r||t.objectMode||(a=new TypeError("Invalid non-string/buffer chunk")),a&&(e.emit("error",a),i(n,a),o=!1),o}(this,o,e,r))&&(o.pendingcb++,a=function(e,t,r,n,i,o){if(!r){var a=function(e,t,r){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=h.from(t,r));return t}(t,n,i);n!==a&&(r=!0,i="buffer",n=a)}var s=t.objectMode?1:n.length;t.length+=s;var u=t.length-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},m.prototype._write=function(e,t,r){r(new Error("_write() is not implemented"))},m.prototype._writev=null,m.prototype.end=function(e,t,r){var n=this._writableState;"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||function(e,t,r){t.ending=!0,E(e,t),r&&(t.finished?i(r):e.once("finish",r));t.ended=!0,e.writable=!1}(this,n,r)},Object.defineProperty(m.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),m.prototype.destroy=p.destroy,m.prototype._undestroy=p.undestroy,m.prototype._destroy=function(e,t){this.end(),t(e)}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?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(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("util");t.exports=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.head=null,this.tail=null,this.length=0}return e.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},e.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},e.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r},e.prototype.concat=function(e){if(0===this.length)return n.alloc(0);if(1===this.length)return this.head.data;for(var t,r,i,o=n.allocUnsafe(e>>>0),a=this.head,s=0;a;)t=a.data,r=o,i=s,t.copy(r,i),s+=a.data.length,a=a.next;return o},e}(),i&&i.inspect&&i.inspect.custom&&(t.exports.prototype[i.inspect.custom]=function(){var e=i.inspect({length:this.length});return this.constructor.name+" "+e})},{"safe-buffer":290,util:55}],282:[function(e,t,r){"use strict";var n=e("process-nextick-args").nextTick;function i(e,t){e.emit("error",t)}t.exports={destroy:function(e,t){var r=this,o=this._readableState&&this._readableState.destroyed,a=this._writableState&&this._writableState.destroyed;return o||a?(t?t(e):!e||this._writableState&&this._writableState.errorEmitted||n(i,this,e),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!t&&e?(n(i,r,e),r._writableState&&(r._writableState.errorEmitted=!0)):t&&t(e)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}}},{"process-nextick-args":256}],283:[function(e,t,r){t.exports=e("events").EventEmitter},{events:157}],284:[function(e,t,r){t.exports=e("./readable").PassThrough},{"./readable":285}],285:[function(e,t,r){(r=t.exports=e("./lib/_stream_readable.js")).Stream=r,r.Readable=r,r.Writable=e("./lib/_stream_writable.js"),r.Duplex=e("./lib/_stream_duplex.js"),r.Transform=e("./lib/_stream_transform.js"),r.PassThrough=e("./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(e,t,r){t.exports=e("./readable").Transform},{"./readable":285}],287:[function(e,t,r){t.exports=e("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":280}],288:[function(e,t,r){(function(r){"use strict";var n=e("inherits"),i=e("hash-base");function o(){i.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function a(e,t){return e<>>32-t}function s(e,t,r,n,i,o,s,u){return a(e+(t^r^n)+o+s|0,u)+i|0}function u(e,t,r,n,i,o,s,u){return a(e+(t&r|~t&n)+o+s|0,u)+i|0}function c(e,t,r,n,i,o,s,u){return a(e+((t|~r)^n)+o+s|0,u)+i|0}function f(e,t,r,n,i,o,s,u){return a(e+(t&n|r&~n)+o+s|0,u)+i|0}function h(e,t,r,n,i,o,s,u){return a(e+(t^(r|~n))+o+s|0,u)+i|0}n(o,i),o.prototype._update=function(){for(var e=new Array(16),t=0;t<16;++t)e[t]=this._block.readInt32LE(4*t);var r=this._a,n=this._b,i=this._c,o=this._d,l=this._e;l=s(l,r=s(r,n,i,o,l,e[0],0,11),n,i=a(i,10),o,e[1],0,14),n=s(n=a(n,10),i=s(i,o=s(o,l,r,n,i,e[2],0,15),l,r=a(r,10),n,e[3],0,12),o,l=a(l,10),r,e[4],0,5),o=s(o=a(o,10),l=s(l,r=s(r,n,i,o,l,e[5],0,8),n,i=a(i,10),o,e[6],0,7),r,n=a(n,10),i,e[7],0,9),r=s(r=a(r,10),n=s(n,i=s(i,o,l,r,n,e[8],0,11),o,l=a(l,10),r,e[9],0,13),i,o=a(o,10),l,e[10],0,14),i=s(i=a(i,10),o=s(o,l=s(l,r,n,i,o,e[11],0,15),r,n=a(n,10),i,e[12],0,6),l,r=a(r,10),n,e[13],0,7),l=u(l=a(l,10),r=s(r,n=s(n,i,o,l,r,e[14],0,9),i,o=a(o,10),l,e[15],0,8),n,i=a(i,10),o,e[7],1518500249,7),n=u(n=a(n,10),i=u(i,o=u(o,l,r,n,i,e[4],1518500249,6),l,r=a(r,10),n,e[13],1518500249,8),o,l=a(l,10),r,e[1],1518500249,13),o=u(o=a(o,10),l=u(l,r=u(r,n,i,o,l,e[10],1518500249,11),n,i=a(i,10),o,e[6],1518500249,9),r,n=a(n,10),i,e[15],1518500249,7),r=u(r=a(r,10),n=u(n,i=u(i,o,l,r,n,e[3],1518500249,15),o,l=a(l,10),r,e[12],1518500249,7),i,o=a(o,10),l,e[0],1518500249,12),i=u(i=a(i,10),o=u(o,l=u(l,r,n,i,o,e[9],1518500249,15),r,n=a(n,10),i,e[5],1518500249,9),l,r=a(r,10),n,e[2],1518500249,11),l=u(l=a(l,10),r=u(r,n=u(n,i,o,l,r,e[14],1518500249,7),i,o=a(o,10),l,e[11],1518500249,13),n,i=a(i,10),o,e[8],1518500249,12),n=c(n=a(n,10),i=c(i,o=c(o,l,r,n,i,e[3],1859775393,11),l,r=a(r,10),n,e[10],1859775393,13),o,l=a(l,10),r,e[14],1859775393,6),o=c(o=a(o,10),l=c(l,r=c(r,n,i,o,l,e[4],1859775393,7),n,i=a(i,10),o,e[9],1859775393,14),r,n=a(n,10),i,e[15],1859775393,9),r=c(r=a(r,10),n=c(n,i=c(i,o,l,r,n,e[8],1859775393,13),o,l=a(l,10),r,e[1],1859775393,15),i,o=a(o,10),l,e[2],1859775393,14),i=c(i=a(i,10),o=c(o,l=c(l,r,n,i,o,e[7],1859775393,8),r,n=a(n,10),i,e[0],1859775393,13),l,r=a(r,10),n,e[6],1859775393,6),l=c(l=a(l,10),r=c(r,n=c(n,i,o,l,r,e[13],1859775393,5),i,o=a(o,10),l,e[11],1859775393,12),n,i=a(i,10),o,e[5],1859775393,7),n=f(n=a(n,10),i=f(i,o=c(o,l,r,n,i,e[12],1859775393,5),l,r=a(r,10),n,e[1],2400959708,11),o,l=a(l,10),r,e[9],2400959708,12),o=f(o=a(o,10),l=f(l,r=f(r,n,i,o,l,e[11],2400959708,14),n,i=a(i,10),o,e[10],2400959708,15),r,n=a(n,10),i,e[0],2400959708,14),r=f(r=a(r,10),n=f(n,i=f(i,o,l,r,n,e[8],2400959708,15),o,l=a(l,10),r,e[12],2400959708,9),i,o=a(o,10),l,e[4],2400959708,8),i=f(i=a(i,10),o=f(o,l=f(l,r,n,i,o,e[13],2400959708,9),r,n=a(n,10),i,e[3],2400959708,14),l,r=a(r,10),n,e[7],2400959708,5),l=f(l=a(l,10),r=f(r,n=f(n,i,o,l,r,e[15],2400959708,6),i,o=a(o,10),l,e[14],2400959708,8),n,i=a(i,10),o,e[5],2400959708,6),n=h(n=a(n,10),i=f(i,o=f(o,l,r,n,i,e[6],2400959708,5),l,r=a(r,10),n,e[2],2400959708,12),o,l=a(l,10),r,e[4],2840853838,9),o=h(o=a(o,10),l=h(l,r=h(r,n,i,o,l,e[0],2840853838,15),n,i=a(i,10),o,e[5],2840853838,5),r,n=a(n,10),i,e[9],2840853838,11),r=h(r=a(r,10),n=h(n,i=h(i,o,l,r,n,e[7],2840853838,6),o,l=a(l,10),r,e[12],2840853838,8),i,o=a(o,10),l,e[2],2840853838,13),i=h(i=a(i,10),o=h(o,l=h(l,r,n,i,o,e[10],2840853838,12),r,n=a(n,10),i,e[14],2840853838,5),l,r=a(r,10),n,e[1],2840853838,12),l=h(l=a(l,10),r=h(r,n=h(n,i,o,l,r,e[3],2840853838,13),i,o=a(o,10),l,e[8],2840853838,14),n,i=a(i,10),o,e[11],2840853838,11),n=h(n=a(n,10),i=h(i,o=h(o,l,r,n,i,e[6],2840853838,8),l,r=a(r,10),n,e[15],2840853838,5),o,l=a(l,10),r,e[13],2840853838,6),o=a(o,10);var d=this._a,p=this._b,b=this._c,y=this._d,m=this._e;m=h(m,d=h(d,p,b,y,m,e[5],1352829926,8),p,b=a(b,10),y,e[14],1352829926,9),p=h(p=a(p,10),b=h(b,y=h(y,m,d,p,b,e[7],1352829926,9),m,d=a(d,10),p,e[0],1352829926,11),y,m=a(m,10),d,e[9],1352829926,13),y=h(y=a(y,10),m=h(m,d=h(d,p,b,y,m,e[2],1352829926,15),p,b=a(b,10),y,e[11],1352829926,15),d,p=a(p,10),b,e[4],1352829926,5),d=h(d=a(d,10),p=h(p,b=h(b,y,m,d,p,e[13],1352829926,7),y,m=a(m,10),d,e[6],1352829926,7),b,y=a(y,10),m,e[15],1352829926,8),b=h(b=a(b,10),y=h(y,m=h(m,d,p,b,y,e[8],1352829926,11),d,p=a(p,10),b,e[1],1352829926,14),m,d=a(d,10),p,e[10],1352829926,14),m=f(m=a(m,10),d=h(d,p=h(p,b,y,m,d,e[3],1352829926,12),b,y=a(y,10),m,e[12],1352829926,6),p,b=a(b,10),y,e[6],1548603684,9),p=f(p=a(p,10),b=f(b,y=f(y,m,d,p,b,e[11],1548603684,13),m,d=a(d,10),p,e[3],1548603684,15),y,m=a(m,10),d,e[7],1548603684,7),y=f(y=a(y,10),m=f(m,d=f(d,p,b,y,m,e[0],1548603684,12),p,b=a(b,10),y,e[13],1548603684,8),d,p=a(p,10),b,e[5],1548603684,9),d=f(d=a(d,10),p=f(p,b=f(b,y,m,d,p,e[10],1548603684,11),y,m=a(m,10),d,e[14],1548603684,7),b,y=a(y,10),m,e[15],1548603684,7),b=f(b=a(b,10),y=f(y,m=f(m,d,p,b,y,e[8],1548603684,12),d,p=a(p,10),b,e[12],1548603684,7),m,d=a(d,10),p,e[4],1548603684,6),m=f(m=a(m,10),d=f(d,p=f(p,b,y,m,d,e[9],1548603684,15),b,y=a(y,10),m,e[1],1548603684,13),p,b=a(b,10),y,e[2],1548603684,11),p=c(p=a(p,10),b=c(b,y=c(y,m,d,p,b,e[15],1836072691,9),m,d=a(d,10),p,e[5],1836072691,7),y,m=a(m,10),d,e[1],1836072691,15),y=c(y=a(y,10),m=c(m,d=c(d,p,b,y,m,e[3],1836072691,11),p,b=a(b,10),y,e[7],1836072691,8),d,p=a(p,10),b,e[14],1836072691,6),d=c(d=a(d,10),p=c(p,b=c(b,y,m,d,p,e[6],1836072691,6),y,m=a(m,10),d,e[9],1836072691,14),b,y=a(y,10),m,e[11],1836072691,12),b=c(b=a(b,10),y=c(y,m=c(m,d,p,b,y,e[8],1836072691,13),d,p=a(p,10),b,e[12],1836072691,5),m,d=a(d,10),p,e[2],1836072691,14),m=c(m=a(m,10),d=c(d,p=c(p,b,y,m,d,e[10],1836072691,13),b,y=a(y,10),m,e[0],1836072691,13),p,b=a(b,10),y,e[4],1836072691,7),p=u(p=a(p,10),b=u(b,y=c(y,m,d,p,b,e[13],1836072691,5),m,d=a(d,10),p,e[8],2053994217,15),y,m=a(m,10),d,e[6],2053994217,5),y=u(y=a(y,10),m=u(m,d=u(d,p,b,y,m,e[4],2053994217,8),p,b=a(b,10),y,e[1],2053994217,11),d,p=a(p,10),b,e[3],2053994217,14),d=u(d=a(d,10),p=u(p,b=u(b,y,m,d,p,e[11],2053994217,14),y,m=a(m,10),d,e[15],2053994217,6),b,y=a(y,10),m,e[0],2053994217,14),b=u(b=a(b,10),y=u(y,m=u(m,d,p,b,y,e[5],2053994217,6),d,p=a(p,10),b,e[12],2053994217,9),m,d=a(d,10),p,e[2],2053994217,12),m=u(m=a(m,10),d=u(d,p=u(p,b,y,m,d,e[13],2053994217,9),b,y=a(y,10),m,e[9],2053994217,12),p,b=a(b,10),y,e[7],2053994217,5),p=s(p=a(p,10),b=u(b,y=u(y,m,d,p,b,e[10],2053994217,15),m,d=a(d,10),p,e[14],2053994217,8),y,m=a(m,10),d,e[12],0,8),y=s(y=a(y,10),m=s(m,d=s(d,p,b,y,m,e[15],0,5),p,b=a(b,10),y,e[10],0,12),d,p=a(p,10),b,e[4],0,9),d=s(d=a(d,10),p=s(p,b=s(b,y,m,d,p,e[1],0,12),y,m=a(m,10),d,e[5],0,5),b,y=a(y,10),m,e[8],0,14),b=s(b=a(b,10),y=s(y,m=s(m,d,p,b,y,e[7],0,6),d,p=a(p,10),b,e[6],0,8),m,d=a(d,10),p,e[2],0,13),m=s(m=a(m,10),d=s(d,p=s(p,b,y,m,d,e[13],0,6),b,y=a(y,10),m,e[14],0,5),p,b=a(b,10),y,e[0],0,15),p=s(p=a(p,10),b=s(b,y=s(y,m,d,p,b,e[3],0,13),m,d=a(d,10),p,e[9],0,11),y,m=a(m,10),d,e[11],0,11),y=a(y,10);var v=this._b+i+y|0;this._b=this._c+o+m|0,this._c=this._d+l+d|0,this._d=this._e+r+p|0,this._e=this._a+n+b|0,this._a=v},o.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=new r(20);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e.writeInt32LE(this._e,16),e},t.exports=o}).call(this,e("buffer").Buffer)},{buffer:84,"hash-base":161,inherits:180}],289:[function(e,t,r){const n=e("assert"),i=e("safe-buffer").Buffer;function o(e,t){if("00"===e.slice(0,2))throw new Error("invalid RLP: extra zeros");return parseInt(e,t)}function a(e,t){if(e<56)return i.from([e+t]);var r=u(e),n=u(t+55+r.length/2);return i.from(n+r,"hex")}function s(e){return"0x"===e.slice(0,2)}function u(e){var t=e.toString(16);return t.length%2&&(t="0"+t),t}function c(e){if(!i.isBuffer(e))if("string"==typeof e)e=s(e)?i.from(((r="string"!=typeof(n=e)?n:s(n)?n.slice(2):n).length%2&&(r="0"+r),r),"hex"):i.from(e);else if("number"==typeof e)e?(t=u(e),e=i.from(t,"hex")):e=i.from([]);else if(null==e)e=i.from([]);else{if(!e.toArray)throw new Error("invalid type");e=i.from(e.toArray())}var t,r,n;return e}r.encode=function(e){if(e instanceof Array){for(var t=[],n=0;nt.length)throw new Error("invalid rlp: total length is larger than the data");if(0===(s=t.slice(n,h)).length)throw new Error("invalid rlp, List has a invalid length");for(;s.length;)u=e(s),c.push(u.data),s=u.remainder;return{data:c,remainder:t.slice(h)}}(e=c(e));return t?r:(n.equal(r.remainder.length,0,"invalid remainder"),r.data)},r.getLength=function(e){if(!e||0===e.length)return i.from([]);var t=(e=c(e))[0];if(t<=127)return e.length;if(t<=183)return t-127;if(t<=191)return t-182;if(t<=247)return t-191;var r=t-246;return r+o(e.slice(1,r).toString("hex"),16)}},{assert:19,"safe-buffer":290}],290:[function(e,t,r){var n=e("buffer"),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function a(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=n:(o(n,r),r.Buffer=a),o(i,a),a.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},a.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},{buffer:84}],291:[function(e,t,r){const n=e("util"),i=e("events/");var o="object"==typeof Reflect?Reflect:null,a=o&&"function"==typeof o.apply?o.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};function s(){i.call(this)}function u(e,t,r){try{a(e,t,r)}catch(e){setTimeout(()=>{throw e})}}t.exports=s,n.inherits(s,i),s.prototype.emit=function(e){for(var t=[],r=1;r0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var s=i[e];if(void 0===s)return!1;if("function"==typeof s)u(s,this,t);else{var c=s.length,f=function(e,t){for(var r=new Array(t),n=0;n0&&a.length>i&&!a.warned){a.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=a.length,s=u,console&&console.warn&&console.warn(s)}return e}function h(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=function(){for(var e=[],t=0;t0&&(a=t[0]),a instanceof Error)throw a;var s=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw s.context=a,s}var u=i[e];if(void 0===u)return!1;if("function"==typeof u)o(u,this,t);else{var c=u.length,f=p(u,c);for(r=0;r=0;o--)if(r[o]===t||r[o].listener===t){a=r[o].listener,i=o;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1=0;n--)this.removeListener(e,t[n]);return this},s.prototype.listeners=function(e){return l(this,e,!0)},s.prototype.rawListeners=function(e){return l(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):d.call(e,t)},s.prototype.listenerCount=d,s.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]}},{}],293:[function(e,t,r){t.exports=e("scryptsy")},{scryptsy:294}],294:[function(e,t,r){(function(r){var n=e("pbkdf2").pbkdf2Sync,i=2147483647;function o(e,t,n,i,o){if(r.isBuffer(e)&&r.isBuffer(n))e.copy(n,i,t,t+o);else for(;o--;)n[i++]=e[t++]}t.exports=function(e,t,a,s,u,c,f){if(0===a||0!=(a&a-1))throw Error("N must be > 0 and a power of 2");if(a>i/128/s)throw Error("Parameter N is too large");if(s>i/128/u)throw Error("Parameter r is too large");var h,l=new r(256*s),d=new r(128*s*a),p=new Int32Array(16),b=new Int32Array(16),y=new r(64),m=n(e,t,1,128*u*s,"sha256");if(f){var v=u*a*2,g=0;h=function(){++g%1e3==0&&f({current:g,total:v,percent:g/v*100})}}for(var w=0;w>>32-t}function x(e){var t;for(t=0;t<16;t++)p[t]=(255&e[4*t+0])<<0,p[t]|=(255&e[4*t+1])<<8,p[t]|=(255&e[4*t+2])<<16,p[t]|=(255&e[4*t+3])<<24;for(o(p,0,b,0,16),t=8;t>0;t-=2)b[4]^=E(b[0]+b[12],7),b[8]^=E(b[4]+b[0],9),b[12]^=E(b[8]+b[4],13),b[0]^=E(b[12]+b[8],18),b[9]^=E(b[5]+b[1],7),b[13]^=E(b[9]+b[5],9),b[1]^=E(b[13]+b[9],13),b[5]^=E(b[1]+b[13],18),b[14]^=E(b[10]+b[6],7),b[2]^=E(b[14]+b[10],9),b[6]^=E(b[2]+b[14],13),b[10]^=E(b[6]+b[2],18),b[3]^=E(b[15]+b[11],7),b[7]^=E(b[3]+b[15],9),b[11]^=E(b[7]+b[3],13),b[15]^=E(b[11]+b[7],18),b[1]^=E(b[0]+b[3],7),b[2]^=E(b[1]+b[0],9),b[3]^=E(b[2]+b[1],13),b[0]^=E(b[3]+b[2],18),b[6]^=E(b[5]+b[4],7),b[7]^=E(b[6]+b[5],9),b[4]^=E(b[7]+b[6],13),b[5]^=E(b[4]+b[7],18),b[11]^=E(b[10]+b[9],7),b[8]^=E(b[11]+b[10],9),b[9]^=E(b[8]+b[11],13),b[10]^=E(b[9]+b[8],18),b[12]^=E(b[15]+b[14],7),b[13]^=E(b[12]+b[15],9),b[14]^=E(b[13]+b[12],13),b[15]^=E(b[14]+b[13],18);for(t=0;t<16;++t)p[t]=b[t]+p[t];for(t=0;t<16;t++){var r=4*t;e[r+0]=p[t]>>0&255,e[r+1]=p[t]>>8&255,e[r+2]=p[t]>>16&255,e[r+3]=p[t]>>24&255}}function k(e,t,r,n,i){for(var o=0;o=r)throw RangeError(n)}}).call(this,{isBuffer:e("../../is-buffer/index.js")})},{"../../is-buffer/index.js":181}],297:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("bip66"),o=n.from([48,129,211,2,1,1,4,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,160,129,133,48,129,130,2,1,1,48,44,6,7,42,134,72,206,61,1,1,2,33,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,255,255,252,47,48,6,4,1,0,4,1,7,4,33,2,121,190,102,126,249,220,187,172,85,160,98,149,206,135,11,7,2,155,252,219,45,206,40,217,89,242,129,91,22,248,23,152,2,33,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,186,174,220,230,175,72,160,59,191,210,94,140,208,54,65,65,2,1,1,161,36,3,34,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),a=n.from([48,130,1,19,2,1,1,4,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,160,129,165,48,129,162,2,1,1,48,44,6,7,42,134,72,206,61,1,1,2,33,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,255,255,252,47,48,6,4,1,0,4,1,7,4,65,4,121,190,102,126,249,220,187,172,85,160,98,149,206,135,11,7,2,155,252,219,45,206,40,217,89,242,129,91,22,248,23,152,72,58,218,119,38,163,196,101,93,164,251,252,14,17,8,168,253,23,180,72,166,133,84,25,156,71,208,143,251,16,212,184,2,33,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,186,174,220,230,175,72,160,59,191,210,94,140,208,54,65,65,2,1,1,161,68,3,66,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);r.privateKeyExport=function(e,t,r){var i=n.from(r?o:a);return e.copy(i,r?8:9),t.copy(i,r?181:214),i},r.privateKeyImport=function(e){var t=e.length,r=0;if(!(t2||t1?e[r+n-2]<<8:0);if(!(t<(r+=n)+i||t32||t1&&0===t[o]&&!(128&t[o+1]);--r,++o);for(var a=n.concat([n.from([0]),e.s]),s=33,u=0;s>1&&0===a[u]&&!(128&a[u+1]);--s,++u);return i.encode(t.slice(o),a.slice(u))},r.signatureImport=function(e){var t=n.alloc(32,0),r=n.alloc(32,0);try{var o=i.decode(e);if(33===o.r.length&&0===o.r[0]&&(o.r=o.r.slice(1)),o.r.length>32)throw new Error("R length is too long");if(33===o.s.length&&0===o.s[0]&&(o.s=o.s.slice(1)),o.s.length>32)throw new Error("S length is too long")}catch(e){return}return o.r.copy(t,32-o.r.length),o.s.copy(r,32-o.s.length),{r:t,s:r}},r.signatureImportLax=function(e){var t=n.alloc(32,0),r=n.alloc(32,0),i=e.length,o=0;if(48===e[o++]){var a=e[o++];if(!(128&a&&(o+=a-128)>i)&&2===e[o++]){var s=e[o++];if(128&s){if(o+(a=s-128)>i)return;for(;a>0&&0===e[o];o+=1,a-=1);for(s=0;a>0;o+=1,a-=1)s=(s<<8)+e[o]}if(!(s>i-o)){var u=o;if(o+=s,2===e[o++]){var c=e[o++];if(128&c){if(o+(a=c-128)>i)return;for(;a>0&&0===e[o];o+=1,a-=1);for(c=0;a>0;o+=1,a-=1)c=(c<<8)+e[o]}if(!(c>i-o)){var f=o;for(o+=c;s>0&&0===e[u];s-=1,u+=1);if(!(s>32)){var h=e.slice(u,u+s);for(h.copy(t,32-h.length);c>0&&0===e[f];c-=1,f+=1);if(!(c>32)){var l=e.slice(f,f+c);return l.copy(r,32-l.length),{r:t,s:r}}}}}}}}}},{bip66:52,"safe-buffer":290}],298:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("create-hash"),o=e("bn.js"),a=e("elliptic").ec,s=e("../messages.json"),u=new a("secp256k1"),c=u.curve;function f(e){var t=e[0];switch(t){case 2:case 3:return 33!==e.length?null:function(e,t){var r=new o(t);if(r.cmp(c.p)>=0)return null;var n=(r=r.toRed(c.red)).redSqr().redIMul(r).redIAdd(c.b).redSqrt();return 3===e!==n.isOdd()&&(n=n.redNeg()),u.keyPair({pub:{x:r,y:n}})}(t,e.slice(1,33));case 4:case 6:case 7:return 65!==e.length?null:function(e,t,r){var n=new o(t),i=new o(r);if(n.cmp(c.p)>=0||i.cmp(c.p)>=0)return null;if(n=n.toRed(c.red),i=i.toRed(c.red),(6===e||7===e)&&i.isOdd()!==(7===e))return null;var a=n.redSqr().redIMul(n);return i.redSqr().redISub(a.redIAdd(c.b)).isZero()?u.keyPair({pub:{x:n,y:i}}):null}(t,e.slice(1,33),e.slice(33,65));default:return null}}r.privateKeyVerify=function(e){var t=new o(e);return t.cmp(c.n)<0&&!t.isZero()},r.privateKeyExport=function(e,t){var r=new o(e);if(r.cmp(c.n)>=0||r.isZero())throw new Error(s.EC_PRIVATE_KEY_EXPORT_DER_FAIL);return n.from(u.keyFromPrivate(e).getPublic(t,!0))},r.privateKeyNegate=function(e){var t=new o(e);return t.isZero()?n.alloc(32):c.n.sub(t).umod(c.n).toArrayLike(n,"be",32)},r.privateKeyModInverse=function(e){var t=new o(e);if(t.cmp(c.n)>=0||t.isZero())throw new Error(s.EC_PRIVATE_KEY_RANGE_INVALID);return t.invm(c.n).toArrayLike(n,"be",32)},r.privateKeyTweakAdd=function(e,t){var r=new o(t);if(r.cmp(c.n)>=0)throw new Error(s.EC_PRIVATE_KEY_TWEAK_ADD_FAIL);if(r.iadd(new o(e)),r.cmp(c.n)>=0&&r.isub(c.n),r.isZero())throw new Error(s.EC_PRIVATE_KEY_TWEAK_ADD_FAIL);return r.toArrayLike(n,"be",32)},r.privateKeyTweakMul=function(e,t){var r=new o(t);if(r.cmp(c.n)>=0||r.isZero())throw new Error(s.EC_PRIVATE_KEY_TWEAK_MUL_FAIL);return r.imul(new o(e)),r.cmp(c.n)&&(r=r.umod(c.n)),r.toArrayLike(n,"be",32)},r.publicKeyCreate=function(e,t){var r=new o(e);if(r.cmp(c.n)>=0||r.isZero())throw new Error(s.EC_PUBLIC_KEY_CREATE_FAIL);return n.from(u.keyFromPrivate(e).getPublic(t,!0))},r.publicKeyConvert=function(e,t){var r=f(e);if(null===r)throw new Error(s.EC_PUBLIC_KEY_PARSE_FAIL);return n.from(r.getPublic(t,!0))},r.publicKeyVerify=function(e){return null!==f(e)},r.publicKeyTweakAdd=function(e,t,r){var i=f(e);if(null===i)throw new Error(s.EC_PUBLIC_KEY_PARSE_FAIL);if((t=new o(t)).cmp(c.n)>=0)throw new Error(s.EC_PUBLIC_KEY_TWEAK_ADD_FAIL);return n.from(c.g.mul(t).add(i.pub).encode(!0,r))},r.publicKeyTweakMul=function(e,t,r){var i=f(e);if(null===i)throw new Error(s.EC_PUBLIC_KEY_PARSE_FAIL);if((t=new o(t)).cmp(c.n)>=0||t.isZero())throw new Error(s.EC_PUBLIC_KEY_TWEAK_MUL_FAIL);return n.from(i.pub.mul(t).encode(!0,r))},r.publicKeyCombine=function(e,t){for(var r=new Array(e.length),i=0;i=0||r.cmp(c.n)>=0)throw new Error(s.ECDSA_SIGNATURE_PARSE_FAIL);var i=n.from(e);return 1===r.cmp(u.nh)&&c.n.sub(r).toArrayLike(n,"be",32).copy(i,32),i},r.signatureExport=function(e){var t=e.slice(0,32),r=e.slice(32,64);if(new o(t).cmp(c.n)>=0||new o(r).cmp(c.n)>=0)throw new Error(s.ECDSA_SIGNATURE_PARSE_FAIL);return{r:t,s:r}},r.signatureImport=function(e){var t=new o(e.r);t.cmp(c.n)>=0&&(t=new o(0));var r=new o(e.s);return r.cmp(c.n)>=0&&(r=new o(0)),n.concat([t.toArrayLike(n,"be",32),r.toArrayLike(n,"be",32)])},r.sign=function(e,t,r,i){if("function"==typeof r){var a=r;r=function(r){var u=a(e,t,null,i,r);if(!n.isBuffer(u)||32!==u.length)throw new Error(s.ECDSA_SIGN_FAIL);return new o(u)}}var f=new o(t);if(f.cmp(c.n)>=0||f.isZero())throw new Error(s.ECDSA_SIGN_FAIL);var h=u.sign(e,t,{canonical:!0,k:r,pers:i});return{signature:n.concat([h.r.toArrayLike(n,"be",32),h.s.toArrayLike(n,"be",32)]),recovery:h.recoveryParam}},r.verify=function(e,t,r){var n={r:t.slice(0,32),s:t.slice(32,64)},i=new o(n.r),a=new o(n.s);if(i.cmp(c.n)>=0||a.cmp(c.n)>=0)throw new Error(s.ECDSA_SIGNATURE_PARSE_FAIL);if(1===a.cmp(u.nh)||i.isZero()||a.isZero())return!1;var h=f(r);if(null===h)throw new Error(s.EC_PUBLIC_KEY_PARSE_FAIL);return u.verify(e,n,{x:h.pub.x,y:h.pub.y})},r.recover=function(e,t,r,i){var a={r:t.slice(0,32),s:t.slice(32,64)},f=new o(a.r),h=new o(a.s);if(f.cmp(c.n)>=0||h.cmp(c.n)>=0)throw new Error(s.ECDSA_SIGNATURE_PARSE_FAIL);try{if(f.isZero()||h.isZero())throw new Error;var l=u.recoverPubKey(e,a,r);return n.from(l.encode(!0,i))}catch(e){throw new Error(s.ECDSA_RECOVER_FAIL)}},r.ecdh=function(e,t){var n=r.ecdhUnsafe(e,t,!0);return i("sha256").update(n).digest()},r.ecdhUnsafe=function(e,t,r){var i=f(e);if(null===i)throw new Error(s.EC_PUBLIC_KEY_PARSE_FAIL);var a=new o(t);if(a.cmp(c.n)>=0||a.isZero())throw new Error(s.ECDH_FAIL);return n.from(i.pub.mul(a).encode(!0,r))}},{"../messages.json":300,"bn.js":53,"create-hash":91,elliptic:109,"safe-buffer":290}],299:[function(e,t,r){"use strict";var n=e("./assert"),i=e("./der"),o=e("./messages.json");function a(e,t){return void 0===e?t:(n.isBoolean(e,o.COMPRESSED_TYPE_INVALID),e)}t.exports=function(e){return{privateKeyVerify:function(t){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),32===t.length&&e.privateKeyVerify(t)},privateKeyExport:function(t,r){n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),r=a(r,!0);var s=e.privateKeyExport(t,r);return i.privateKeyExport(t,s,r)},privateKeyImport:function(t){if(n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),(t=i.privateKeyImport(t))&&32===t.length&&e.privateKeyVerify(t))return t;throw new Error(o.EC_PRIVATE_KEY_IMPORT_DER_FAIL)},privateKeyNegate:function(t){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),e.privateKeyNegate(t)},privateKeyModInverse:function(t){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),e.privateKeyModInverse(t)},privateKeyTweakAdd:function(t,r){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),n.isBuffer(r,o.TWEAK_TYPE_INVALID),n.isBufferLength(r,32,o.TWEAK_LENGTH_INVALID),e.privateKeyTweakAdd(t,r)},privateKeyTweakMul:function(t,r){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),n.isBuffer(r,o.TWEAK_TYPE_INVALID),n.isBufferLength(r,32,o.TWEAK_LENGTH_INVALID),e.privateKeyTweakMul(t,r)},publicKeyCreate:function(t,r){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),r=a(r,!0),e.publicKeyCreate(t,r)},publicKeyConvert:function(t,r){return n.isBuffer(t,o.EC_PUBLIC_KEY_TYPE_INVALID),n.isBufferLength2(t,33,65,o.EC_PUBLIC_KEY_LENGTH_INVALID),r=a(r,!0),e.publicKeyConvert(t,r)},publicKeyVerify:function(t){return n.isBuffer(t,o.EC_PUBLIC_KEY_TYPE_INVALID),e.publicKeyVerify(t)},publicKeyTweakAdd:function(t,r,i){return n.isBuffer(t,o.EC_PUBLIC_KEY_TYPE_INVALID),n.isBufferLength2(t,33,65,o.EC_PUBLIC_KEY_LENGTH_INVALID),n.isBuffer(r,o.TWEAK_TYPE_INVALID),n.isBufferLength(r,32,o.TWEAK_LENGTH_INVALID),i=a(i,!0),e.publicKeyTweakAdd(t,r,i)},publicKeyTweakMul:function(t,r,i){return n.isBuffer(t,o.EC_PUBLIC_KEY_TYPE_INVALID),n.isBufferLength2(t,33,65,o.EC_PUBLIC_KEY_LENGTH_INVALID),n.isBuffer(r,o.TWEAK_TYPE_INVALID),n.isBufferLength(r,32,o.TWEAK_LENGTH_INVALID),i=a(i,!0),e.publicKeyTweakMul(t,r,i)},publicKeyCombine:function(t,r){n.isArray(t,o.EC_PUBLIC_KEYS_TYPE_INVALID),n.isLengthGTZero(t,o.EC_PUBLIC_KEYS_LENGTH_INVALID);for(var i=0;i=2&&("function"==typeof arguments[1]?r.task=arguments[1]:r.n=arguments[1]);var n=r.task;if(r.task=function(){n(t.leave)},t.current+r.n-e>t.capacity)return 1===e&&(t.current--,t.firstHere=!1),t.queue.push(r);t.current+=r.n-e,r.task(t.leave),1===e&&(t.firstHere=!1)},leave:function(e){if(e=e||1,t.current-=e,t.queue.length){var r=t.queue[0];r.n+t.current>t.capacity||(t.queue.shift(),t.current+=r.n,i(r.task))}else if(t.current<0)throw new Error("leave called too many times.")},available:function(e){return e=e||1,t.current+e<=t.capacity}};return t}void 0!==e&&e&&"function"==typeof e.nextTick&&(i=e.nextTick),"object"==typeof r?t.exports=o:"function"==typeof define&&define.amd?define(function(){return o}):n.semaphore=o}(this)}).call(this,e("_process"))},{_process:257}],302:[function(e,t,r){"use strict";t.exports="function"==typeof setImmediate?setImmediate:function(){var e=[].slice.apply(arguments);e.splice(1,0,0),setTimeout.apply(null,e)}},{}],303:[function(e,t,r){var n=e("safe-buffer").Buffer;function i(e,t){this._block=n.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}i.prototype.update=function(e,t){"string"==typeof e&&(t=t||"utf8",e=n.from(e,t));for(var r=this._block,i=this._blockSize,o=e.length,a=this._len,s=0;s=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var o=this._hash();return e?o.toString(e):o},i.prototype._update=function(){throw new Error("_update must be implemented by subclass")},t.exports=i},{"safe-buffer":290}],304:[function(e,t,r){(r=t.exports=function(e){e=e.toLowerCase();var t=r[e];if(!t)throw new Error(e+" is not supported (we accept pull requests)");return new t}).sha=e("./sha"),r.sha1=e("./sha1"),r.sha224=e("./sha224"),r.sha256=e("./sha256"),r.sha384=e("./sha384"),r.sha512=e("./sha512")},{"./sha":305,"./sha1":306,"./sha224":307,"./sha256":308,"./sha384":309,"./sha512":310}],305:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1518500249,1859775393,-1894007588,-899497514],s=new Array(80);function u(){this.init(),this._w=s,i.call(this,64,56)}function c(e){return e<<30|e>>>2}function f(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}n(u,i),u.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,h=0;h<16;++h)r[h]=e.readInt32BE(4*h);for(;h<80;++h)r[h]=r[h-3]^r[h-8]^r[h-14]^r[h-16];for(var l=0;l<80;++l){var d=~~(l/20),p=0|((t=n)<<5|t>>>27)+f(d,i,o,s)+u+r[l]+a[d];u=s,s=o,o=c(i),i=n,n=p}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},u.prototype._hash=function(){var e=o.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},t.exports=u},{"./hash":303,inherits:180,"safe-buffer":290}],306:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1518500249,1859775393,-1894007588,-899497514],s=new Array(80);function u(){this.init(),this._w=s,i.call(this,64,56)}function c(e){return e<<5|e>>>27}function f(e){return e<<30|e>>>2}function h(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}n(u,i),u.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,l=0;l<16;++l)r[l]=e.readInt32BE(4*l);for(;l<80;++l)r[l]=(t=r[l-3]^r[l-8]^r[l-14]^r[l-16])<<1|t>>>31;for(var d=0;d<80;++d){var p=~~(d/20),b=c(n)+h(p,i,o,s)+u+r[d]+a[p]|0;u=s,s=o,o=f(i),i=n,n=b}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},u.prototype._hash=function(){var e=o.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},t.exports=u},{"./hash":303,inherits:180,"safe-buffer":290}],307:[function(e,t,r){var n=e("inherits"),i=e("./sha256"),o=e("./hash"),a=e("safe-buffer").Buffer,s=new Array(64);function u(){this.init(),this._w=s,o.call(this,64,56)}n(u,i),u.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},u.prototype._hash=function(){var e=a.allocUnsafe(28);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e},t.exports=u},{"./hash":303,"./sha256":308,inherits:180,"safe-buffer":290}],308:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],s=new Array(64);function u(){this.init(),this._w=s,i.call(this,64,56)}function c(e,t,r){return r^e&(t^r)}function f(e,t,r){return e&t|r&(e|t)}function h(e){return(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function l(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function d(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}n(u,i),u.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,p=0|this._f,b=0|this._g,y=0|this._h,m=0;m<16;++m)r[m]=e.readInt32BE(4*m);for(;m<64;++m)r[m]=0|(((t=r[m-2])>>>17|t<<15)^(t>>>19|t<<13)^t>>>10)+r[m-7]+d(r[m-15])+r[m-16];for(var v=0;v<64;++v){var g=y+l(u)+c(u,p,b)+a[v]+r[v]|0,w=h(n)+f(n,i,o)|0;y=b,b=p,p=u,u=s+g|0,s=o,o=i,i=n,n=g+w|0}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0,this._f=p+this._f|0,this._g=b+this._g|0,this._h=y+this._h|0},u.prototype._hash=function(){var e=o.allocUnsafe(32);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e.writeInt32BE(this._h,28),e},t.exports=u},{"./hash":303,inherits:180,"safe-buffer":290}],309:[function(e,t,r){var n=e("inherits"),i=e("./sha512"),o=e("./hash"),a=e("safe-buffer").Buffer,s=new Array(160);function u(){this.init(),this._w=s,o.call(this,128,112)}n(u,i),u.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},u.prototype._hash=function(){var e=a.allocUnsafe(48);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e},t.exports=u},{"./hash":303,"./sha512":310,inherits:180,"safe-buffer":290}],310:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],s=new Array(160);function u(){this.init(),this._w=s,i.call(this,128,112)}function c(e,t,r){return r^e&(t^r)}function f(e,t,r){return e&t|r&(e|t)}function h(e,t){return(e>>>28|t<<4)^(t>>>2|e<<30)^(t>>>7|e<<25)}function l(e,t){return(e>>>14|t<<18)^(e>>>18|t<<14)^(t>>>9|e<<23)}function d(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^e>>>7}function p(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^(e>>>7|t<<25)}function b(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^e>>>6}function y(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^(e>>>6|t<<26)}function m(e,t){return e>>>0>>0?1:0}n(u,i),u.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},u.prototype._update=function(e){for(var t=this._w,r=0|this._ah,n=0|this._bh,i=0|this._ch,o=0|this._dh,s=0|this._eh,u=0|this._fh,v=0|this._gh,g=0|this._hh,w=0|this._al,_=0|this._bl,A=0|this._cl,E=0|this._dl,x=0|this._el,k=0|this._fl,S=0|this._gl,M=0|this._hl,I=0;I<32;I+=2)t[I]=e.readInt32BE(4*I),t[I+1]=e.readInt32BE(4*I+4);for(;I<160;I+=2){var T=t[I-30],U=t[I-30+1],j=d(T,U),B=p(U,T),P=b(T=t[I-4],U=t[I-4+1]),C=y(U,T),N=t[I-14],R=t[I-14+1],L=t[I-32],O=t[I-32+1],D=B+R|0,F=j+N+m(D,B)|0;F=(F=F+P+m(D=D+C|0,C)|0)+L+m(D=D+O|0,O)|0,t[I]=F,t[I+1]=D}for(var q=0;q<160;q+=2){F=t[q],D=t[q+1];var H=f(r,n,i),z=f(w,_,A),K=h(r,w),V=h(w,r),G=l(s,x),W=l(x,s),Y=a[q],X=a[q+1],Z=c(s,u,v),J=c(x,k,S),$=M+W|0,Q=g+G+m($,M)|0;Q=(Q=(Q=Q+Z+m($=$+J|0,J)|0)+Y+m($=$+X|0,X)|0)+F+m($=$+D|0,D)|0;var ee=V+z|0,te=K+H+m(ee,V)|0;g=v,M=S,v=u,S=k,u=s,k=x,s=o+Q+m(x=E+$|0,E)|0,o=i,E=A,i=n,A=_,n=r,_=w,r=Q+te+m(w=$+ee|0,$)|0}this._al=this._al+w|0,this._bl=this._bl+_|0,this._cl=this._cl+A|0,this._dl=this._dl+E|0,this._el=this._el+x|0,this._fl=this._fl+k|0,this._gl=this._gl+S|0,this._hl=this._hl+M|0,this._ah=this._ah+r+m(this._al,w)|0,this._bh=this._bh+n+m(this._bl,_)|0,this._ch=this._ch+i+m(this._cl,A)|0,this._dh=this._dh+o+m(this._dl,E)|0,this._eh=this._eh+s+m(this._el,x)|0,this._fh=this._fh+u+m(this._fl,k)|0,this._gh=this._gh+v+m(this._gl,S)|0,this._hh=this._hh+g+m(this._hl,M)|0},u.prototype._hash=function(){var e=o.allocUnsafe(64);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e},t.exports=u},{"./hash":303,inherits:180,"safe-buffer":290}],311:[function(e,t,r){t.exports=i;var n=e("events").EventEmitter;function i(){n.call(this)}e("inherits")(i,n),i.Readable=e("readable-stream/readable.js"),i.Writable=e("readable-stream/writable.js"),i.Duplex=e("readable-stream/duplex.js"),i.Transform=e("readable-stream/transform.js"),i.PassThrough=e("readable-stream/passthrough.js"),i.Stream=i,i.prototype.pipe=function(e,t){var r=this;function i(t){e.writable&&!1===e.write(t)&&r.pause&&r.pause()}function o(){r.readable&&r.resume&&r.resume()}r.on("data",i),e.on("drain",o),e._isStdio||t&&!1===t.end||(r.on("end",s),r.on("close",u));var a=!1;function s(){a||(a=!0,e.end())}function u(){a||(a=!0,"function"==typeof e.destroy&&e.destroy())}function c(e){if(f(),0===n.listenerCount(this,"error"))throw e}function f(){r.removeListener("data",i),e.removeListener("drain",o),r.removeListener("end",s),r.removeListener("close",u),r.removeListener("error",c),e.removeListener("error",c),r.removeListener("end",f),r.removeListener("close",f),e.removeListener("close",f)}return r.on("error",c),e.on("error",c),r.on("end",f),r.on("close",f),e.on("close",f),e.emit("pipe",r),e}},{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(e,t,r){(function(t){var n=e("./lib/request"),i=e("./lib/response"),o=e("xtend"),a=e("builtin-status-codes"),s=e("url"),u=r;u.request=function(e,r){e="string"==typeof e?s.parse(e):o(e);var i=-1===t.location.protocol.search(/^https?:$/)?"http:":"",a=e.protocol||i,u=e.hostname||e.host,c=e.port,f=e.path||"/";u&&-1!==u.indexOf(":")&&(u="["+u+"]"),e.url=(u?a+"//"+u:"")+(c?":"+c:"")+f,e.method=(e.method||"GET").toUpperCase(),e.headers=e.headers||{};var h=new n(e);return r&&h.on("response",r),h},u.get=function(e,t){var r=u.request(e,t);return r.end(),r},u.ClientRequest=n,u.IncomingMessage=i,u.Agent=function(){},u.Agent.defaultMaxSockets=4,u.STATUS_CODES=a,u.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./lib/request":314,"./lib/response":315,"builtin-status-codes":85,url:327,xtend:423}],313:[function(e,t,r){(function(e){r.fetch=s(e.fetch)&&s(e.ReadableStream),r.writableStream=s(e.WritableStream),r.abortController=s(e.AbortController),r.blobConstructor=!1;try{new Blob([new ArrayBuffer(1)]),r.blobConstructor=!0}catch(e){}var t;function n(){if(void 0!==t)return t;if(e.XMLHttpRequest){t=new e.XMLHttpRequest;try{t.open("GET",e.XDomainRequest?"/":"https://example.com")}catch(e){t=null}}else t=null;return t}function i(e){var t=n();if(!t)return!1;try{return t.responseType=e,t.responseType===e}catch(e){}return!1}var o=void 0!==e.ArrayBuffer,a=o&&s(e.ArrayBuffer.prototype.slice);function s(e){return"function"==typeof e}r.arraybuffer=r.fetch||o&&i("arraybuffer"),r.msstream=!r.fetch&&a&&i("ms-stream"),r.mozchunkedarraybuffer=!r.fetch&&o&&i("moz-chunked-arraybuffer"),r.overrideMimeType=r.fetch||!!n()&&s(n().overrideMimeType),r.vbArray=s(e.VBArray),t=null}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],314:[function(e,t,r){(function(r,n,i){var o=e("./capability"),a=e("inherits"),s=e("./response"),u=e("readable-stream"),c=e("to-arraybuffer"),f=s.IncomingMessage,h=s.readyStates;var l=t.exports=function(e){var t,r=this;u.Writable.call(r),r._opts=e,r._body=[],r._headers={},e.auth&&r.setHeader("Authorization","Basic "+new i(e.auth).toString("base64")),Object.keys(e.headers).forEach(function(t){r.setHeader(t,e.headers[t])});var n=!0;if("disable-fetch"===e.mode||"requestTimeout"in e&&!o.abortController)n=!1,t=!0;else if("prefer-streaming"===e.mode)t=!1;else if("allow-wrong-content-type"===e.mode)t=!o.overrideMimeType;else{if(e.mode&&"default"!==e.mode&&"prefer-fast"!==e.mode)throw new Error("Invalid value for opts.mode");t=!0}r._mode=function(e,t){return o.fetch&&t?"fetch":o.mozchunkedarraybuffer?"moz-chunked-arraybuffer":o.msstream?"ms-stream":o.arraybuffer&&e?"arraybuffer":o.vbArray&&e?"text:vbarray":"text"}(t,n),r.on("finish",function(){r._onFinish()})};a(l,u.Writable),l.prototype.setHeader=function(e,t){var r=e.toLowerCase();-1===d.indexOf(r)&&(this._headers[r]={name:e,value:t})},l.prototype.getHeader=function(e){var t=this._headers[e.toLowerCase()];return t?t.value:null},l.prototype.removeHeader=function(e){delete this._headers[e.toLowerCase()]},l.prototype._onFinish=function(){var e=this;if(!e._destroyed){var t=e._opts,a=e._headers,s=null;"GET"!==t.method&&"HEAD"!==t.method&&(s=o.arraybuffer?c(i.concat(e._body)):o.blobConstructor?new n.Blob(e._body.map(function(e){return c(e)}),{type:(a["content-type"]||{}).value||""}):i.concat(e._body).toString());var u=[];if(Object.keys(a).forEach(function(e){var t=a[e].name,r=a[e].value;Array.isArray(r)?r.forEach(function(e){u.push([t,e])}):u.push([t,r])}),"fetch"===e._mode){var f=null;if(o.abortController){var l=new AbortController;f=l.signal,e._fetchAbortController=l,"requestTimeout"in t&&0!==t.requestTimeout&&n.setTimeout(function(){e.emit("requestTimeout"),e._fetchAbortController&&e._fetchAbortController.abort()},t.requestTimeout)}n.fetch(e._opts.url,{method:e._opts.method,headers:u,body:s||void 0,mode:"cors",credentials:t.withCredentials?"include":"same-origin",signal:f}).then(function(t){e._fetchResponse=t,e._connect()},function(t){e.emit("error",t)})}else{var d=e._xhr=new n.XMLHttpRequest;try{d.open(e._opts.method,e._opts.url,!0)}catch(t){return void r.nextTick(function(){e.emit("error",t)})}"responseType"in d&&(d.responseType=e._mode.split(":")[0]),"withCredentials"in d&&(d.withCredentials=!!t.withCredentials),"text"===e._mode&&"overrideMimeType"in d&&d.overrideMimeType("text/plain; charset=x-user-defined"),"requestTimeout"in t&&(d.timeout=t.requestTimeout,d.ontimeout=function(){e.emit("requestTimeout")}),u.forEach(function(e){d.setRequestHeader(e[0],e[1])}),e._response=null,d.onreadystatechange=function(){switch(d.readyState){case h.LOADING:case h.DONE:e._onXHRProgress()}},"moz-chunked-arraybuffer"===e._mode&&(d.onprogress=function(){e._onXHRProgress()}),d.onerror=function(){e._destroyed||e.emit("error",new Error("XHR error"))};try{d.send(s)}catch(t){return void r.nextTick(function(){e.emit("error",t)})}}}},l.prototype._onXHRProgress=function(){(function(e){try{var t=e.status;return null!==t&&0!==t}catch(e){return!1}})(this._xhr)&&!this._destroyed&&(this._response||this._connect(),this._response._onXHRProgress())},l.prototype._connect=function(){var e=this;e._destroyed||(e._response=new f(e._xhr,e._fetchResponse,e._mode),e._response.on("error",function(t){e.emit("error",t)}),e.emit("response",e._response))},l.prototype._write=function(e,t,r){this._body.push(e),r()},l.prototype.abort=l.prototype.destroy=function(){this._destroyed=!0,this._response&&(this._response._destroyed=!0),this._xhr?this._xhr.abort():this._fetchAbortController&&this._fetchAbortController.abort()},l.prototype.end=function(e,t,r){"function"==typeof e&&(r=e,e=void 0),u.Writable.prototype.end.call(this,e,t,r)},l.prototype.flushHeaders=function(){},l.prototype.setTimeout=function(){},l.prototype.setNoDelay=function(){},l.prototype.setSocketKeepAlive=function(){};var d=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","user-agent","via"]}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"./capability":313,"./response":315,_process:257,buffer:84,inherits:180,"readable-stream":285,"to-arraybuffer":323}],315:[function(e,t,r){(function(t,n,i){var o=e("./capability"),a=e("inherits"),s=e("readable-stream"),u=r.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},c=r.IncomingMessage=function(e,r,n){var a=this;if(s.Readable.call(a),a._mode=n,a.headers={},a.rawHeaders=[],a.trailers={},a.rawTrailers=[],a.on("end",function(){t.nextTick(function(){a.emit("close")})}),"fetch"===n){if(a._fetchResponse=r,a.url=r.url,a.statusCode=r.status,a.statusMessage=r.statusText,r.headers.forEach(function(e,t){a.headers[t.toLowerCase()]=e,a.rawHeaders.push(t,e)}),o.writableStream){var u=new WritableStream({write:function(e){return new Promise(function(t,r){a._destroyed||(a.push(new i(e))?t():a._resumeFetch=t)})},close:function(){a._destroyed||a.push(null)},abort:function(e){a._destroyed||a.emit("error",e)}});try{return void r.body.pipeTo(u)}catch(e){}}var c=r.body.getReader();!function e(){c.read().then(function(t){a._destroyed||(t.done?a.push(null):(a.push(new i(t.value)),e()))}).catch(function(e){a._destroyed||a.emit("error",e)})}()}else{if(a._xhr=e,a._pos=0,a.url=e.responseURL,a.statusCode=e.status,a.statusMessage=e.statusText,e.getAllResponseHeaders().split(/\r?\n/).forEach(function(e){var t=e.match(/^([^:]+):\s*(.*)/);if(t){var r=t[1].toLowerCase();"set-cookie"===r?(void 0===a.headers[r]&&(a.headers[r]=[]),a.headers[r].push(t[2])):void 0!==a.headers[r]?a.headers[r]+=", "+t[2]:a.headers[r]=t[2],a.rawHeaders.push(t[1],t[2])}}),a._charset="x-user-defined",!o.overrideMimeType){var f=a.rawHeaders["mime-type"];if(f){var h=f.match(/;\s*charset=([^;])(;|$)/);h&&(a._charset=h[1].toLowerCase())}a._charset||(a._charset="utf-8")}}};a(c,s.Readable),c.prototype._read=function(){var e=this._resumeFetch;e&&(this._resumeFetch=null,e())},c.prototype._onXHRProgress=function(){var e=this,t=e._xhr,r=null;switch(e._mode){case"text:vbarray":if(t.readyState!==u.DONE)break;try{r=new n.VBArray(t.responseBody).toArray()}catch(e){}if(null!==r){e.push(new i(r));break}case"text":try{r=t.responseText}catch(t){e._mode="text:vbarray";break}if(r.length>e._pos){var o=r.substr(e._pos);if("x-user-defined"===e._charset){for(var a=new i(o.length),s=0;se._pos&&(e.push(new i(new Uint8Array(c.result.slice(e._pos)))),e._pos=c.result.byteLength)},c.onload=function(){e.push(null)},c.readAsArrayBuffer(r)}e._xhr.readyState===u.DONE&&"ms-stream"!==e._mode&&e.push(null)}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"./capability":313,_process:257,buffer:84,inherits:180,"readable-stream":285}],316:[function(e,t,r){"use strict";t.exports=function(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}},{}],317:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=n.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function o(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(n.isEncoding===i||!i(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=u,this.end=c,t=4;break;case"utf8":this.fillLast=s,t=4;break;case"base64":this.text=f,this.end=h,t=3;break;default:return this.write=l,void(this.end=d)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(t)}function a(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:-1}function s(e){var t=this.lastTotal-this.lastNeed,r=function(e,t,r){if(128!=(192&t[0]))return e.lastNeed=0,"�".repeat(r);if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�".repeat(r+1);if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�".repeat(r+2)}}(this,e,t);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function u(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function c(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function f(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function h(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function l(e){return e.toString(this.encoding)}function d(e){return e&&e.length?this.write(e):""}r.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0)return i>0&&(e.lastNeed=i-1),i;if(--n=0)return i>0&&(e.lastNeed=i-2),i;if(--n=0)return i>0&&(2===i?i=0:e.lastNeed=i-3),i;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)},o.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},{"safe-buffer":290}],318:[function(e,t,r){var n=e("is-hex-prefixed");t.exports=function(e){return"string"!=typeof e?e:n(e)?e.slice(2):e}},{"is-hex-prefixed":185}],319:[function(e,t,r){var n=function(){throw"This swarm.js function isn't available on the browser."},i={readFile:n},o={download:n,safeDownloadArchived:n,directoryTree:n},a={platform:n,arch:n},s={join:n,slice:n},u={spawn:n},c={lookup:n},f=e("xhr-request-promise"),h=e("eth-lib/lib/bytes"),l=e("./swarm-hash.js"),d=e("./pick.js"),p=e("./swarm");t.exports=p({fsp:i,files:o,os:a,path:s,child_process:u,defaultArchives:{},mimetype:c,request:f,downloadUrl:null,bytes:h,hash:l,pick:d})},{"./pick.js":320,"./swarm":322,"./swarm-hash.js":321,"eth-lib/lib/bytes":133,"xhr-request-promise":411}],320:[function(e,t,r){var n=function(e){return function(){return new Promise(function(t,r){var n=function(r){var n={},i=r.target.files.length,o=0;[].map.call(r.target.files,function(r){var a=new FileReader;a.onload=function(a){var s=new Uint8Array(a.target.result);if("directory"===e){var u=r.webkitRelativePath;n[u.slice(u.indexOf("/")+1)]={type:"text/plain",data:s},++o===i&&t(n)}else if("file"===e){var c=r.webkitRelativePath;t({type:mimetype.lookup(c),data:s})}else t(s)},a.readAsArrayBuffer(r)})},i=void 0;"directory"===e?((i=document.createElement("input")).addEventListener("change",n),i.type="file",i.webkitdirectory=!0,i.mozdirectory=!0,i.msdirectory=!0,i.odirectory=!0,i.directory=!0):((i=document.createElement("input")).addEventListener("change",n),i.type="file");var o=document.createEvent("MouseEvents");o.initEvent("click",!0,!1),i.dispatchEvent(o)})}};t.exports={data:n("data"),file:n("file"),directory:n("directory")}},{}],321:[function(e,t,r){var n=e("eth-lib/lib/hash").keccak256,i=e("eth-lib/lib/bytes"),o=function(e,t){var r=i.reverse(i.pad(6,i.fromNumber(e))),o=i.flatten([r,"0x0000",t]);return n(o).slice(2)};t.exports=function e(t){"string"==typeof t&&"0x"!==t.slice(0,2)?t=i.fromString(t):"string"!=typeof t&&void 0!==t.length&&(t=i.fromUint8Array(t));var r=i.length(t);if(r<=4096)return o(r,t);for(var n=4096;128*n0){var a=i.join(r,o);n.push(g(e)(t[o])(a))}return Promise.all(n).then(function(){return r})})}}},_=function(e){return function(t){return u(e+"/bzzr:/",{body:"string"==typeof t?L(t):t,method:"POST"})}},A=function(e){return function(t){return function(r){return function(n){return function i(o){var a="/"===r[0]?r:"/"+r,s=e+"/bzz:/"+t+a,c={method:"PUT",headers:{"Content-Type":n.type},body:n.data};return u(s,c).then(function(e){if(-1!==e.indexOf("error"))throw e;return e}).catch(function(e){return o>0&&i(o-1)})}(3)}}}},E=function(e){return function(t){return k(e)({"":t})}},x=function(e){return function(r){return t.readFile(r).then(function(t){return E(e)({type:a.lookup(r),data:t})})}},k=function(e){return function(t){return _(e)("{}").then(function(r){return Object.keys(t).reduce(function(r,n){return r.then(function(r){return function(n){return A(e)(n)(r)(t[r])}}(n))},Promise.resolve(r))})}},S=function(e){return function(r){return t.readFile(r).then(_(e))}},M=function(e){return function(n){return function(i){return r.directoryTree(i).then(function(e){return Promise.all(e.map(function(e){return t.readFile(e)})).then(function(t){var r=e.map(function(e){return e.slice(i.length)}),n=e.map(function(e){return a.lookup(e)||"text/plain"});return d(r)(t.map(function(e,t){return{type:n[t],data:e}}))})}).then(function(e){return(t=n?{"":e[n]}:{},function(e){var r={};for(var n in t)r[n]=t[n];for(var i in e)r[i]=e[i];return r})(e);var t}).then(k(e))}}},I=function(e){return function(t){if("data"===t.pick)return l.data().then(_(e));if("file"===t.pick)return l.file().then(E(e));if("directory"===t.pick)return l.directory().then(k(e));if(t.path)switch(t.kind){case"data":return S(e)(t.path);case"file":return x(e)(t.path);case"directory":return M(e)(t.defaultFile)(t.path)}else{if(t.length||"string"==typeof t)return _(e)(t);if(t instanceof Object)return k(e)(t)}return Promise.reject(new Error("Bad arguments"))}},T=function(e){return function(t){return function(r){return C(e)(t).then(function(n){return n?r?w(e)(t)(r):v(e)(t):r?g(e)(t)(r):b(e)(t)})}}},U=function(e,t){var i=n.platform().replace("win32","windows")+"-"+("x64"===n.arch()?"amd64":"386"),o=(t||s)[i],a=c+o.archive+".tar.gz",u=o.archiveMD5,f=o.binaryMD5;return r.safeDownloadArchived(a)(u)(f)(e)},j=function(e){return new Promise(function(t,r){var n=o.spawn,i=function(e){return function(t){return-1!==(""+t).indexOf(e)}},a=e.account,s=e.password,u=e.dataDir,c=e.ensApi,f=e.privateKey,h=0,l=n(e.binPath,["--bzzaccount",a||f,"--datadir",u,"--ens-api",c]),d=function(e){0===h&&i("Passphrase")(e)?setTimeout(function(){h=1,l.stdin.write(s+"\n")},500):i("Swarm http proxy started")(e)&&(h=2,clearTimeout(p),t(l))};l.stdout.on("data",d),l.stderr.on("data",d);var p=setTimeout(function(){return r(new Error("Couldn't start swarm process."))},2e4)})},B=function(e){return new Promise(function(t,r){e.stderr.removeAllListeners("data"),e.stdout.removeAllListeners("data"),e.stdin.removeAllListeners("error"),e.removeAllListeners("error"),e.removeAllListeners("exit"),e.kill("SIGINT");var n=setTimeout(function(){return e.kill("SIGKILL")},8e3);e.once("close",function(){clearTimeout(n),t()})})},P=function(e){return _(e)("test").then(function(e){return"c9a99c7d326dcc6316f32fe2625b311f6dc49a175e6877681ded93137d3569e7"===e}).catch(function(){return!1})},C=function(e){return function(t){return b(e)(t).then(function(e){try{return!!JSON.parse(R(e)).entries}catch(e){return!1}})}},N=function(e){return function(t,r,n,i,o){var a;return void 0!==t&&(a=e(t)),void 0!==r&&(a=e(r)),void 0!==n&&(a=e(n)),void 0!==i&&(a=e(i)),void 0!==o&&(a=e(o)),a}},R=function(e){return f.toString(f.fromUint8Array(e))},L=function(e){return f.toUint8Array(f.fromString(e))},O=function(e){return{download:function(t,r){return T(e)(t)(r)},downloadData:N(b(e)),downloadDataToDisk:N(g(e)),downloadDirectory:N(v(e)),downloadDirectoryToDisk:N(w(e)),downloadEntries:N(y(e)),downloadRoutes:N(m(e)),isAvailable:function(){return P(e)},upload:function(t){return I(e)(t)},uploadData:N(_(e)),uploadFile:N(E(e)),uploadFileFromDisk:N(E(e)),uploadDataFromDisk:N(S(e)),uploadDirectory:N(k(e)),uploadDirectoryFromDisk:N(M(e)),uploadToManifest:N(A(e)),pick:l,hash:h,fromString:L,toString:R}};return{at:O,local:function(e){return function(t){return P("http://localhost:8500").then(function(r){return r?t(O("http://localhost:8500")).then(function(){}):U(e.binPath,e.archives).onData(function(t){return(e.onProgress||function(){})(t.length)}).then(function(){return j(e)}).then(function(e){return t(O("http://localhost:8500")).then(function(){return e})}).then(B)})}},download:T,downloadBinary:U,downloadData:b,downloadDataToDisk:g,downloadDirectory:v,downloadDirectoryToDisk:w,downloadEntries:y,downloadRoutes:m,isAvailable:P,startProcess:j,stopProcess:B,upload:I,uploadData:_,uploadDataFromDisk:S,uploadFile:E,uploadFileFromDisk:x,uploadDirectory:k,uploadDirectoryFromDisk:M,uploadToManifest:A,pick:l,hash:h,fromString:L,toString:R}}},{}],323:[function(e,t,r){var n=e("buffer").Buffer;t.exports=function(e){if(e instanceof Uint8Array){if(0===e.byteOffset&&e.byteLength===e.buffer.byteLength)return e.buffer;if("function"==typeof e.buffer.slice)return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}if(n.isBuffer(e)){for(var t=new Uint8Array(e.length),r=e.length,i=0;i=0&&t<=A};function k(e){return function(t,r,n,i){r=m(r,i,4);var o=!x(t)&&y.keys(t),a=(o||t).length,s=e>0?0:a-1;return arguments.length<3&&(n=t[o?o[s]:s],s+=e),function(t,r,n,i,o,a){for(;o>=0&&o=0},y.invoke=function(e,t){var r=u.call(arguments,2),n=y.isFunction(t);return y.map(e,function(e){var i=n?t:e[t];return null==i?i:i.apply(e,r)})},y.pluck=function(e,t){return y.map(e,y.property(t))},y.where=function(e,t){return y.filter(e,y.matcher(t))},y.findWhere=function(e,t){return y.find(e,y.matcher(t))},y.max=function(e,t,r){var n,i,o=-1/0,a=-1/0;if(null==t&&null!=e)for(var s=0,u=(e=x(e)?e:y.values(e)).length;so&&(o=n);else t=v(t,r),y.each(e,function(e,r,n){((i=t(e,r,n))>a||i===-1/0&&o===-1/0)&&(o=e,a=i)});return o},y.min=function(e,t,r){var n,i,o=1/0,a=1/0;if(null==t&&null!=e)for(var s=0,u=(e=x(e)?e:y.values(e)).length;sn||void 0===r)return 1;if(r0?0:i-1;o>=0&&o0?a=o>=0?o:Math.max(o+s,a):s=o>=0?Math.min(o+1,s):o+s+1;else if(r&&o&&s)return n[o=r(n,i)]===i?o:-1;if(i!=i)return(o=t(u.call(n,a,s),y.isNaN))>=0?o+a:-1;for(o=e>0?a:s-1;o>=0&&ot?(a&&(clearTimeout(a),a=null),s=c,o=e.apply(n,i),a||(n=i=null)):a||!1===r.trailing||(a=setTimeout(u,f)),o}},y.debounce=function(e,t,r){var n,i,o,a,s,u=function(){var c=y.now()-a;c=0?n=setTimeout(u,t-c):(n=null,r||(s=e.apply(o,i),n||(o=i=null)))};return function(){o=this,i=arguments,a=y.now();var c=r&&!n;return n||(n=setTimeout(u,t)),c&&(s=e.apply(o,i),o=i=null),s}},y.wrap=function(e,t){return y.partial(t,e)},y.negate=function(e){return function(){return!e.apply(this,arguments)}},y.compose=function(){var e=arguments,t=e.length-1;return function(){for(var r=t,n=e[t].apply(this,arguments);r--;)n=e[r].call(this,n);return n}},y.after=function(e,t){return function(){if(--e<1)return t.apply(this,arguments)}},y.before=function(e,t){var r;return function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=null),r}},y.once=y.partial(y.before,2);var j=!{toString:null}.propertyIsEnumerable("toString"),B=["valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"];function P(e,t){var r=B.length,n=e.constructor,i=y.isFunction(n)&&n.prototype||o,a="constructor";for(y.has(e,a)&&!y.contains(t,a)&&t.push(a);r--;)(a=B[r])in e&&e[a]!==i[a]&&!y.contains(t,a)&&t.push(a)}y.keys=function(e){if(!y.isObject(e))return[];if(l)return l(e);var t=[];for(var r in e)y.has(e,r)&&t.push(r);return j&&P(e,t),t},y.allKeys=function(e){if(!y.isObject(e))return[];var t=[];for(var r in e)t.push(r);return j&&P(e,t),t},y.values=function(e){for(var t=y.keys(e),r=t.length,n=Array(r),i=0;i":">",'"':""","'":"'","`":"`"},R=y.invert(N),L=function(e){var t=function(t){return e[t]},r="(?:"+y.keys(e).join("|")+")",n=RegExp(r),i=RegExp(r,"g");return function(e){return e=null==e?"":""+e,n.test(e)?e.replace(i,t):e}};y.escape=L(N),y.unescape=L(R),y.result=function(e,t,r){var n=null==e?void 0:e[t];return void 0===n&&(n=r),y.isFunction(n)?n.call(e):n};var O=0;y.uniqueId=function(e){var t=++O+"";return e?e+t:t},y.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var D=/(.)^/,F={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},q=/\\|'|\r|\n|\u2028|\u2029/g,H=function(e){return"\\"+F[e]};y.template=function(e,t,r){!t&&r&&(t=r),t=y.defaults({},t,y.templateSettings);var n=RegExp([(t.escape||D).source,(t.interpolate||D).source,(t.evaluate||D).source].join("|")+"|$","g"),i=0,o="__p+='";e.replace(n,function(t,r,n,a,s){return o+=e.slice(i,s).replace(q,H),i=s+t.length,r?o+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'":n?o+="'+\n((__t=("+n+"))==null?'':__t)+\n'":a&&(o+="';\n"+a+"\n__p+='"),t}),o+="';\n",t.variable||(o="with(obj||{}){\n"+o+"}\n"),o="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+o+"return __p;\n";try{var a=new Function(t.variable||"obj","_",o)}catch(e){throw e.source=o,e}var s=function(e){return a.call(this,e,y)},u=t.variable||"obj";return s.source="function("+u+"){\n"+o+"}",s},y.chain=function(e){var t=y(e);return t._chain=!0,t};var z=function(e,t){return e._chain?y(t).chain():t};y.mixin=function(e){y.each(y.functions(e),function(t){var r=y[t]=e[t];y.prototype[t]=function(){var e=[this._wrapped];return s.apply(e,arguments),z(this,r.apply(y,e))}})},y.mixin(y),y.each(["pop","push","reverse","shift","sort","splice","unshift"],function(e){var t=i[e];y.prototype[e]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!==e&&"splice"!==e||0!==r.length||delete r[0],z(this,r)}}),y.each(["concat","join","slice"],function(e){var t=i[e];y.prototype[e]=function(){return z(this,t.apply(this._wrapped,arguments))}}),y.prototype.value=function(){return this._wrapped},y.prototype.valueOf=y.prototype.toJSON=y.prototype.value,y.prototype.toString=function(){return""+this._wrapped},"function"==typeof define&&define.amd&&define("underscore",[],function(){return y})}).call(this)},{}],326:[function(e,t,r){t.exports=function(e,t){if(t){t=(t=t.trim().replace(/^(\?|#|&)/,""))?"?"+t:t;var r=e.split(/[\?\#]/),n=r[0];t&&/\:\/\/[^\/]*$/.test(n)&&(n+="/");var i=e.match(/(\#.*)$/);e=n+t,i&&(e+=i[0])}return e}},{}],327:[function(e,t,r){"use strict";var n=e("punycode"),i=e("./util");function o(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}r.parse=g,r.resolve=function(e,t){return g(e,!1,!0).resolve(t)},r.resolveObject=function(e,t){return e?g(e,!1,!0).resolveObject(t):t},r.format=function(e){i.isString(e)&&(e=g(e));return e instanceof o?e.format():o.prototype.format.call(e)},r.Url=o;var a=/^([a-z0-9.+-]+:)/i,s=/:[0-9]*$/,u=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,c=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),f=["'"].concat(c),h=["%","/","?",";","#"].concat(f),l=["/","?","#"],d=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,b={javascript:!0,"javascript:":!0},y={javascript:!0,"javascript:":!0},m={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},v=e("querystring");function g(e,t,r){if(e&&i.isObject(e)&&e instanceof o)return e;var n=new o;return n.parse(e,t,r),n}o.prototype.parse=function(e,t,r){if(!i.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var o=e.indexOf("?"),s=-1!==o&&o127?P+="x":P+=B[C];if(!P.match(d)){var R=U.slice(0,M),L=U.slice(M+1),O=B.match(p);O&&(R.push(O[1]),L.unshift(O[2])),L.length&&(g="/"+L.join(".")+g),this.hostname=R.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),T||(this.hostname=n.toASCII(this.hostname));var D=this.port?":"+this.port:"",F=this.hostname||"";this.host=F+D,this.href+=this.host,T&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==g[0]&&(g="/"+g))}if(!b[A])for(M=0,j=f.length;M0)&&r.host.split("@"))&&(r.auth=T.shift(),r.host=r.hostname=T.shift());return r.search=e.search,r.query=e.query,i.isNull(r.pathname)&&i.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!E.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var k=E.slice(-1)[0],S=(r.host||e.host||E.length>1)&&("."===k||".."===k)||""===k,M=0,I=E.length;I>=0;I--)"."===(k=E[I])?E.splice(I,1):".."===k?(E.splice(I,1),M++):M&&(E.splice(I,1),M--);if(!_&&!A)for(;M--;M)E.unshift("..");!_||""===E[0]||E[0]&&"/"===E[0].charAt(0)||E.unshift(""),S&&"/"!==E.join("/").substr(-1)&&E.push("");var T,U=""===E[0]||E[0]&&"/"===E[0].charAt(0);x&&(r.hostname=r.host=U?"":E.length?E.shift():"",(T=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@"))&&(r.auth=T.shift(),r.host=r.hostname=T.shift()));return(_=_||r.host&&E.length)&&!U&&E.unshift(""),E.length?r.pathname=E.join("/"):(r.pathname=null,r.path=null),i.isNull(r.pathname)&&i.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=e.auth||r.auth,r.slashes=r.slashes||e.slashes,r.href=r.format(),r},o.prototype.parseHost=function(){var e=this.host,t=s.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{"./util":328,punycode:265,querystring:269}],328:[function(e,t,r){"use strict";t.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},{}],329:[function(e,t,r){(function(e){!function(n){var i="object"==typeof r&&r,o="object"==typeof t&&t&&t.exports==i&&t,a="object"==typeof e&&e;a.global!==a&&a.window!==a||(n=a);var s,u,c,f=String.fromCharCode;function h(e){for(var t,r,n=[],i=0,o=e.length;i=55296&&t<=56319&&i=55296&&e<=57343)throw Error("Lone surrogate U+"+e.toString(16).toUpperCase()+" is not a scalar value")}function d(e,t){return f(e>>t&63|128)}function p(e){if(0==(4294967168&e))return f(e);var t="";return 0==(4294965248&e)?t=f(e>>6&31|192):0==(4294901760&e)?(l(e),t=f(e>>12&15|224),t+=d(e,6)):0==(4292870144&e)&&(t=f(e>>18&7|240),t+=d(e,12),t+=d(e,6)),t+=f(63&e|128)}function b(){if(c>=u)throw Error("Invalid byte index");var e=255&s[c];if(c++,128==(192&e))return 63&e;throw Error("Invalid continuation byte")}function y(){var e,t;if(c>u)throw Error("Invalid byte index");if(c==u)return!1;if(e=255&s[c],c++,0==(128&e))return e;if(192==(224&e)){if((t=(31&e)<<6|b())>=128)return t;throw Error("Invalid continuation byte")}if(224==(240&e)){if((t=(15&e)<<12|b()<<6|b())>=2048)return l(t),t;throw Error("Invalid continuation byte")}if(240==(248&e)&&(t=(15&e)<<18|b()<<12|b()<<6|b())>=65536&&t<=1114111)return t;throw Error("Invalid UTF-8 detected")}var m={version:"2.0.0",encode:function(e){for(var t=h(e),r=t.length,n=-1,i="";++n65535&&(i+=f((t-=65536)>>>10&1023|55296),t=56320|1023&t),i+=f(t);return i}(r)}};if("function"==typeof define&&"object"==typeof define.amd&&define.amd)define(function(){return m});else if(i&&!i.nodeType)if(o)o.exports=m;else{var v={}.hasOwnProperty;for(var g in m)v.call(m,g)&&(i[g]=m[g])}else n.utf8=m}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],330:[function(e,t,r){(function(e){function r(t){try{if(!e.localStorage)return!1}catch(e){return!1}var r=e.localStorage[t];return null!=r&&"true"===String(r).toLowerCase()}t.exports=function(e,t){if(r("noDeprecation"))return e;var n=!1;return function(){if(!n){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],331:[function(e,t,r){arguments[4][180][0].apply(r,arguments)},{dup:180}],332:[function(e,t,r){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],333:[function(e,t,r){(function(t,n){var i=/%[sdj%]/g;r.format=function(e){if(!m(e)){for(var t=[],r=0;r=o)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(e){return"[Circular]"}default:return e}}),u=n[r];r=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),p(t)?n.showHidden=t:t&&r._extend(n,t),v(n.showHidden)&&(n.showHidden=!1),v(n.depth)&&(n.depth=2),v(n.colors)&&(n.colors=!1),v(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=u),f(n,e,n.depth)}function u(e,t){var r=s.styles[t];return r?"["+s.colors[r][0]+"m"+e+"["+s.colors[r][1]+"m":e}function c(e,t){return e}function f(e,t,n){if(e.customInspect&&t&&E(t.inspect)&&t.inspect!==r.inspect&&(!t.constructor||t.constructor.prototype!==t)){var i=t.inspect(n,e);return m(i)||(i=f(e,i,n)),i}var o=function(e,t){if(v(t))return e.stylize("undefined","undefined");if(m(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(y(t))return e.stylize(""+t,"number");if(p(t))return e.stylize(""+t,"boolean");if(b(t))return e.stylize("null","null")}(e,t);if(o)return o;var a=Object.keys(t),s=function(e){var t={};return e.forEach(function(e,r){t[e]=!0}),t}(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(t)),A(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return h(t);if(0===a.length){if(E(t)){var u=t.name?": "+t.name:"";return e.stylize("[Function"+u+"]","special")}if(g(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(_(t))return e.stylize(Date.prototype.toString.call(t),"date");if(A(t))return h(t)}var c,w="",x=!1,k=["{","}"];(d(t)&&(x=!0,k=["[","]"]),E(t))&&(w=" [Function"+(t.name?": "+t.name:"")+"]");return g(t)&&(w=" "+RegExp.prototype.toString.call(t)),_(t)&&(w=" "+Date.prototype.toUTCString.call(t)),A(t)&&(w=" "+h(t)),0!==a.length||x&&0!=t.length?n<0?g(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),c=x?function(e,t,r,n,i){for(var o=[],a=0,s=t.length;a=0&&0,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60)return r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1];return r[0]+t+" "+e.join(", ")+" "+r[1]}(c,w,k)):k[0]+w+k[1]}function h(e){return"["+Error.prototype.toString.call(e)+"]"}function l(e,t,r,n,i,o){var a,s,u;if((u=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]}).get?s=u.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):u.set&&(s=e.stylize("[Setter]","special")),M(n,i)||(a="["+i+"]"),s||(e.seen.indexOf(u.value)<0?(s=b(r)?f(e,u.value,null):f(e,u.value,r-1)).indexOf("\n")>-1&&(s=o?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n")):s=e.stylize("[Circular]","special")),v(a)){if(o&&i.match(/^\d+$/))return s;(a=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function d(e){return Array.isArray(e)}function p(e){return"boolean"==typeof e}function b(e){return null===e}function y(e){return"number"==typeof e}function m(e){return"string"==typeof e}function v(e){return void 0===e}function g(e){return w(e)&&"[object RegExp]"===x(e)}function w(e){return"object"==typeof e&&null!==e}function _(e){return w(e)&&"[object Date]"===x(e)}function A(e){return w(e)&&("[object Error]"===x(e)||e instanceof Error)}function E(e){return"function"==typeof e}function x(e){return Object.prototype.toString.call(e)}function k(e){return e<10?"0"+e.toString(10):e.toString(10)}r.debuglog=function(e){if(v(o)&&(o=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!a[e])if(new RegExp("\\b"+e+"\\b","i").test(o)){var n=t.pid;a[e]=function(){var t=r.format.apply(r,arguments);console.error("%s %d: %s",e,n,t)}}else a[e]=function(){};return a[e]},r.inspect=s,s.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},s.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},r.isArray=d,r.isBoolean=p,r.isNull=b,r.isNullOrUndefined=function(e){return null==e},r.isNumber=y,r.isString=m,r.isSymbol=function(e){return"symbol"==typeof e},r.isUndefined=v,r.isRegExp=g,r.isObject=w,r.isDate=_,r.isError=A,r.isFunction=E,r.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},r.isBuffer=e("./support/isBuffer");var S=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function M(e,t){return Object.prototype.hasOwnProperty.call(e,t)}r.log=function(){var e,t;console.log("%s - %s",(e=new Date,t=[k(e.getHours()),k(e.getMinutes()),k(e.getSeconds())].join(":"),[e.getDate(),S[e.getMonth()],t].join(" ")),r.format.apply(r,arguments))},r.inherits=e("inherits"),r._extend=function(e,t){if(!t||!w(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":332,_process:257,inherits:331}],334:[function(require,module,exports){var indexOf=require("indexof"),Object_keys=function(e){if(Object.keys)return Object.keys(e);var t=[];for(var r in e)t.push(r);return t},forEach=function(e,t){if(e.forEach)return e.forEach(t);for(var r=0;r1?(e[r[0]]=e[r[0]]||{},e[r[0]][r[1]]=t):e[r[0]]=t},c.prototype.getCall=function(e){return n.isFunction(this.call)?this.call(e):this.call},c.prototype.extractCallback=function(e){if(n.isFunction(e[e.length-1]))return e.pop()},c.prototype.validateArgs=function(e){if(e.length!==this.params)throw i.InvalidNumberOfParams(e.length,this.params,this.name)},c.prototype.formatInput=function(e){var t=this;return this.inputFormatter?this.inputFormatter.map(function(r,n){return r?r.call(t,e[n]):e[n]}):e},c.prototype.formatOutput=function(e){var t=this;return n.isArray(e)?e.map(function(e){return t.outputFormatter&&e?t.outputFormatter(e):e}):this.outputFormatter&&e?this.outputFormatter(e):e},c.prototype.toPayload=function(e){var t=this.getCall(e),r=this.extractCallback(e),n=this.formatInput(e);this.validateArgs(n);var i={method:t,params:n,callback:r};return this.transformPayload&&(i=this.transformPayload(i)),i},c.prototype._confirmTransaction=function(e,t,r){var i=this,f=!1,h=!0,l=0,d=0,p=null,b="",y=n.isObject(r.params[0])&&r.params[0].gas?r.params[0].gas:null,m=n.isObject(r.params[0])&&r.params[0].data&&r.params[0].from&&!r.params[0].to,v=[new c({name:"getTransactionReceipt",call:"eth_getTransactionReceipt",params:1,inputFormatter:[null],outputFormatter:o.outputTransactionReceiptFormatter}),new c({name:"getCode",call:"eth_getCode",params:2,inputFormatter:[o.inputAddressFormatter,o.inputDefaultBlockNumberFormatter]}),new u({name:"subscribe",type:"eth",subscriptions:{newBlockHeaders:{subscriptionName:"newHeads",params:0,outputFormatter:o.outputBlockFormatter}}})],g={};n.each(v,function(e){e.attachToObject(g),e.requestManager=i.requestManager});var w=function(r,n,o,u,c){if(!o)return c||(c={unsubscribe:function(){clearInterval(p)}}),(r?s.resolve(r):g.getTransactionReceipt(t)).catch(function(t){c.unsubscribe(),f=!0,a._fireError({message:"Failed to check for transaction receipt:",data:t},e.eventEmitter,e.reject)}).then(function(t){if(!t||!t.blockHash)throw new Error("Receipt missing or blockHash null");return i.extraFormatters&&i.extraFormatters.receiptFormatter&&(t=i.extraFormatters.receiptFormatter(t)),e.eventEmitter.listeners("confirmation").length>0&&(void 0!==r&&0===d||e.eventEmitter.emit("confirmation",d,t),h=!1,25===++d&&(c.unsubscribe(),e.eventEmitter.removeAllListeners())),t}).then(function(t){if(m&&!f){if(!t.contractAddress)return h&&(c.unsubscribe(),f=!0),void a._fireError(new Error("The transaction receipt didn't contain a contract address."),e.eventEmitter,e.reject);g.getCode(t.contractAddress,function(r,n){n&&(n.length>2?(e.eventEmitter.emit("receipt",t),i.extraFormatters&&i.extraFormatters.contractDeployFormatter?e.resolve(i.extraFormatters.contractDeployFormatter(t)):e.resolve(t),h&&e.eventEmitter.removeAllListeners()):a._fireError(new Error("The contract code couldn't be stored, please check your gas limit."),e.eventEmitter,e.reject),h&&c.unsubscribe(),f=!0)})}return t}).then(function(t){m||f||(t.outOfGas||y&&y===t.gasUsed||!0!==t.status&&"0x1"!==t.status&&void 0!==t.status?(b=JSON.stringify(t,null,2),!1===t.status||"0x0"===t.status?a._fireError(new Error("Transaction has been reverted by the EVM:\n"+b),e.eventEmitter,e.reject):a._fireError(new Error("Transaction ran out of gas. Please provide more gas:\n"+b),e.eventEmitter,e.reject)):(e.eventEmitter.emit("receipt",t),e.resolve(t),h&&e.eventEmitter.removeAllListeners()),h&&c.unsubscribe(),f=!0)}).catch(function(){l++,n?l-1>=750&&(c.unsubscribe(),f=!0,a._fireError(new Error("Transaction was not mined within750 seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!"),e.eventEmitter,e.reject)):l-1>=50&&(c.unsubscribe(),f=!0,a._fireError(new Error("Transaction was not mined within 50 blocks, please make sure your transaction was properly sent. Be aware that it might still be mined!"),e.eventEmitter,e.reject))});c.unsubscribe(),f=!0,a._fireError({message:"Failed to subscribe to new newBlockHeaders to confirm the transaction receipts.",data:o},e.eventEmitter,e.reject)},_=function(e){n.isFunction(this.requestManager.provider.on)?g.subscribe("newBlockHeaders",w.bind(null,e,!1)):p=setInterval(w.bind(null,e,!0),1e3)}.bind(this);g.getTransactionReceipt(t).then(function(t){t&&t.blockHash?(e.eventEmitter.listeners("confirmation").length>0&&_(t),w(t,!1)):f||_()}).catch(function(){f||_()})};var f=function(e,t){return n.isNumber(e)?t.wallet[e]:n.isObject(e)&&e.address&&e.privateKey?e:t.wallet[e.toLowerCase()]};c.prototype.buildCall=function(){var e=this,t="eth_sendTransaction"===e.call||"eth_sendRawTransaction"===e.call,r=function(){var r=s(!t),i=e.toPayload(Array.prototype.slice.call(arguments)),o=function(n,o){try{o=e.formatOutput(o)}catch(e){n=e}if(o instanceof Error&&(n=o),n)return n.error&&(n=n.error),a._fireError(n,r.eventEmitter,r.reject,i.callback);i.callback&&i.callback(null,o),t?(r.eventEmitter.emit("transactionHash",o),e._confirmTransaction(r,o,i)):n||r.resolve(o)},u=function(t){var r=n.extend({},i,{method:"eth_sendRawTransaction",params:[t.rawTransaction]});e.requestManager.send(r,o)},h=function(e,t){var i;if(t&&t.accounts&&t.accounts.wallet&&t.accounts.wallet.length)if("eth_sendTransaction"===e.method){var a=e.params[0];if((i=f(n.isObject(a)?a.from:null,t.accounts))&&i.privateKey)return t.accounts.signTransaction(n.omit(a,"from"),i.privateKey).then(u)}else if("eth_sign"===e.method){var s=e.params[1];if((i=f(e.params[0],t.accounts))&&i.privateKey){var c=t.accounts.sign(s,i.privateKey);return e.callback&&e.callback(null,c.signature),void r.resolve(c.signature)}}return t.requestManager.send(e,o)};t&&n.isObject(i.params[0])&&void 0===i.params[0].gasPrice?new c({name:"getGasPrice",call:"eth_gasPrice",params:0}).createFunction(e.requestManager)(function(t,r){r&&(i.params[0].gasPrice=r),h(i,e)}):h(i,e);return r.eventEmitter};return r.method=e,r.request=this.request.bind(this),r},c.prototype.request=function(){var e=this.toPayload(Array.prototype.slice.call(arguments));return e.format=this.formatOutput.bind(this),e},t.exports=c},{underscore:325,"web3-core-helpers":338,"web3-core-promievent":340,"web3-core-subscriptions":345,"web3-utils":403}],340:[function(e,t,r){"use strict";var n=e("eventemitter3"),i=e("any-promise"),o=function(e){var t,r,o=new i(function(){t=arguments[0],r=arguments[1]});if(e)return{resolve:t,reject:r,eventEmitter:o};var a=new n;return o._events=a._events,o.emit=a.emit,o.on=a.on,o.once=a.once,o.off=a.off,o.listeners=a.listeners,o.addListener=a.addListener,o.removeListener=a.removeListener,o.removeAllListeners=a.removeAllListeners,{resolve:t,reject:r,eventEmitter:o}};o.resolve=function(e){var t=o(!0);return t.resolve(e),t.eventEmitter},t.exports=o},{"any-promise":2,eventemitter3:156}],341:[function(e,t,r){"use strict";var n=e("./jsonrpc"),i=e("web3-core-helpers").errors,o=function(e){this.requestManager=e,this.requests=[]};o.prototype.add=function(e){this.requests.push(e)},o.prototype.execute=function(){var e=this.requests;this.requestManager.sendBatch(e,function(t,r){r=r||[],e.map(function(e,t){return r[t]||{}}).forEach(function(t,r){if(e[r].callback){if(t&&t.error)return e[r].callback(i.ErrorResponse(t));if(!n.isValidResponse(t))return e[r].callback(i.InvalidResponse(t));try{e[r].callback(null,e[r].format?e[r].format(t.result):t.result)}catch(t){e[r].callback(t)}}})})},t.exports=o},{"./jsonrpc":344,"web3-core-helpers":338}],342:[function(e,t,r){"use strict";var n=null,i=window;void 0!==i.ethereumProvider?n=i.ethereumProvider:void 0!==i.web3&&i.web3.currentProvider&&(i.web3.currentProvider.sendAsync&&(i.web3.currentProvider.send=i.web3.currentProvider.sendAsync,delete i.web3.currentProvider.sendAsync),!i.web3.currentProvider.on&&i.web3.currentProvider.connection&&"ipcProviderWrapper"===i.web3.currentProvider.connection.constructor.name&&(i.web3.currentProvider.on=function(e,t){if("function"!=typeof t)throw new Error("The second parameter callback must be a function.");switch(e){case"data":this.connection.on("data",function(e){var r="";e=e.toString();try{r=JSON.parse(e)}catch(r){return t(new Error("Couldn't parse response data"+e))}r.id||-1===r.method.indexOf("_subscription")||t(null,r)});break;default:this.connection.on(e,t)}}),n=i.web3.currentProvider),t.exports=n},{}],343:[function(e,t,r){"use strict";var n=e("underscore"),i=e("web3-core-helpers").errors,o=e("./jsonrpc.js"),a=e("./batch.js"),s=e("./givenProvider.js"),u=function e(t){this.provider=null,this.providers=e.providers,this.setProvider(t),this.subscriptions={}};u.givenProvider=s,u.providers={WebsocketProvider:e("web3-providers-ws"),HttpProvider:e("web3-providers-http"),IpcProvider:e("web3-providers-ipc")},u.prototype.setProvider=function(e,t){var r=this;if(e&&"string"==typeof e&&this.providers)if(/^http(s)?:\/\//i.test(e))e=new this.providers.HttpProvider(e);else if(/^ws(s)?:\/\//i.test(e))e=new this.providers.WebsocketProvider(e);else if(e&&"object"==typeof t&&"function"==typeof t.connect)e=new this.providers.IpcProvider(e,t);else if(e)throw new Error("Can't autodetect provider for \""+e+'"');this.provider&&this.provider.connected&&this.clearSubscriptions(),this.provider=e||null,this.provider&&this.provider.on&&this.provider.on("data",function(e,t){(e=e||t).method&&r.subscriptions[e.params.subscription]&&r.subscriptions[e.params.subscription].callback&&r.subscriptions[e.params.subscription].callback(null,e.params.result)})},u.prototype.send=function(e,t){if(t=t||function(){},!this.provider)return t(i.InvalidProvider());var r=o.toPayload(e.method,e.params);this.provider[this.provider.sendAsync?"sendAsync":"send"](r,function(e,n){return n&&n.id&&r.id!==n.id?t(new Error('Wrong response id "'+n.id+'" (expected: "'+r.id+'") in '+JSON.stringify(r))):e?t(e):n&&n.error?t(i.ErrorResponse(n)):o.isValidResponse(n)?void t(null,n.result):t(i.InvalidResponse(n))})},u.prototype.sendBatch=function(e,t){if(!this.provider)return t(i.InvalidProvider());var r=o.toBatchPayload(e);this.provider[this.provider.sendAsync?"sendAsync":"send"](r,function(e,r){return e?t(e):n.isArray(r)?void t(null,r):t(i.InvalidResponse(r))})},u.prototype.addSubscription=function(e,t,r,n){if(!this.provider.on)throw new Error("The provider doesn't support subscriptions: "+this.provider.constructor.name);this.subscriptions[e]={callback:n,type:r,name:t}},u.prototype.removeSubscription=function(e,t){this.subscriptions[e]&&(this.send({method:this.subscriptions[e].type+"_unsubscribe",params:[e]},t),delete this.subscriptions[e])},u.prototype.clearSubscriptions=function(e){var t=this;Object.keys(this.subscriptions).forEach(function(r){e&&"syncing"===t.subscriptions[r].name||t.removeSubscription(r)}),this.provider.reset&&this.provider.reset()},t.exports={Manager:u,BatchManager:a}},{"./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(e,t,r){"use strict";var n={messageId:0,toPayload:function(e,t){if(!e)throw new Error('JSONRPC method should be specified for params: "'+JSON.stringify(t)+'"!');return n.messageId++,{jsonrpc:"2.0",id:n.messageId,method:e,params:t||[]}},isValidResponse:function(e){return Array.isArray(e)?e.every(t):t(e);function t(e){return!(!e||e.error||"2.0"!==e.jsonrpc||"number"!=typeof e.id&&"string"!=typeof e.id||void 0===e.result)}},toBatchPayload:function(e){return e.map(function(e){return n.toPayload(e.method,e.params)})}};t.exports=n},{}],345:[function(e,t,r){"use strict";var n=e("./subscription.js"),i=function(e){this.name=e.name,this.type=e.type,this.subscriptions=e.subscriptions||{},this.requestManager=null};i.prototype.setRequestManager=function(e){this.requestManager=e},i.prototype.attachToObject=function(e){var t=this.buildCall(),r=this.name.split(".");r.length>1?(e[r[0]]=e[r[0]]||{},e[r[0]][r[1]]=t):e[r[0]]=t},i.prototype.buildCall=function(){var e=this;return function(){e.subscriptions[arguments[0]]||console.warn("Subscription "+JSON.stringify(arguments[0])+" doesn't exist. Subscribing anyway.");var t=new n({subscription:e.subscriptions[arguments[0]],requestManager:e.requestManager,type:e.type});return t.subscribe.apply(t,arguments)}},t.exports={subscriptions:i,subscription:n}},{"./subscription.js":346}],346:[function(e,t,r){"use strict";var n=e("underscore"),i=e("web3-core-helpers").errors,o=e("eventemitter3");function a(e){o.call(this),this.id=null,this.callback=n.identity,this.arguments=null,this._reconnectIntervalId=null,this.options={subscription:e.subscription,type:e.type,requestManager:e.requestManager}}a.prototype=Object.create(o.prototype),a.prototype.constructor=a,a.prototype._extractCallback=function(e){if(n.isFunction(e[e.length-1]))return e.pop()},a.prototype._validateArgs=function(e){var t=this.options.subscription;if(t||(t={}),t.params||(t.params=0),e.length!==t.params)throw i.InvalidNumberOfParams(e.length,t.params+1,e[0])},a.prototype._formatInput=function(e){var t=this.options.subscription;return t&&t.inputFormatter?t.inputFormatter.map(function(t,r){return t?t(e[r]):e[r]}):e},a.prototype._formatOutput=function(e){var t=this.options.subscription;return t&&t.outputFormatter&&e?t.outputFormatter(e):e},a.prototype._toPayload=function(e){var t=[];if(this.callback=this._extractCallback(e)||n.identity,this.subscriptionMethod||(this.subscriptionMethod=e.shift(),this.options.subscription.subscriptionName&&(this.subscriptionMethod=this.options.subscription.subscriptionName)),this.arguments||(this.arguments=this._formatInput(e),this._validateArgs(this.arguments),e=[]),t.push(this.subscriptionMethod),t=t.concat(this.arguments),e.length)throw new Error("Only a callback is allowed as parameter on an already instantiated subscription.");return{method:this.options.type+"_subscribe",params:t}},a.prototype.unsubscribe=function(e){this.options.requestManager.removeSubscription(this.id,e),this.id=null,this.removeAllListeners(),clearInterval(this._reconnectIntervalId)},a.prototype.subscribe=function(){var e=this,t=Array.prototype.slice.call(arguments),r=this._toPayload(t);if(!r)return this;if(!this.options.requestManager.provider){var i=new Error("No provider set.");return this.callback(i,null,this),this.emit("error",i),this}if(!this.options.requestManager.provider.on){var o=new Error("The current provider doesn't support subscriptions: "+this.options.requestManager.provider.constructor.name);return this.callback(o,null,this),this.emit("error",o),this}return this.id&&this.unsubscribe(),this.options.params=r.params[1],"logs"===r.params[0]&&n.isObject(r.params[1])&&r.params[1].hasOwnProperty("fromBlock")&&isFinite(r.params[1].fromBlock)&&this.options.requestManager.send({method:"eth_getLogs",params:[r.params[1]]},function(t,r){t?(e.callback(t,null,e),e.emit("error",t)):r.forEach(function(t){var r=e._formatOutput(t);e.callback(null,r,e),e.emit("data",r)})}),"object"==typeof r.params[1]&&delete r.params[1].fromBlock,this.options.requestManager.send(r,function(t,i){!t&&i?(e.id=i,e.options.requestManager.addSubscription(e.id,r.params[0],e.options.type,function(t,r){t?(e.options.requestManager.removeSubscription(e.id),e.options.requestManager.provider.once&&(e._reconnectIntervalId=setInterval(function(){e.options.requestManager.provider.reconnect&&e.options.requestManager.provider.reconnect()},500),e.options.requestManager.provider.once("connect",function(){clearInterval(e._reconnectIntervalId),e.subscribe(e.callback)})),e.emit("error",t),e.callback(t,null,e)):(n.isArray(r)||(r=[r]),r.forEach(function(t){var r=e._formatOutput(t);if(n.isFunction(e.options.subscription.subscriptionHandler))return e.options.subscription.subscriptionHandler.call(e,r);e.emit("data",r),e.callback(null,r,e)}))})):(e.callback(t,null,e),e.emit("error",t))}),this},t.exports=a},{eventemitter3:156,underscore:325,"web3-core-helpers":338}],347:[function(e,t,r){"use strict";var n=e("web3-core-helpers").formatters,i=e("web3-core-method"),o=e("web3-utils");t.exports=function(e){var t=function(t){var r;return t.property?(e[t.property]||(e[t.property]={}),r=e[t.property]):r=e,t.methods&&t.methods.forEach(function(t){t instanceof i||(t=new i(t)),t.attachToObject(r),t.setRequestManager(e._requestManager)}),e};return t.formatters=n,t.utils=o,t.Method=i,t}},{"web3-core-helpers":338,"web3-core-method":339,"web3-utils":403}],348:[function(e,t,r){"use strict";var n=e("web3-core-requestmanager"),i=e("./extend.js");t.exports={packageInit:function(e,t){if(t=Array.prototype.slice.call(t),!e)throw new Error('You need to instantiate using the "new" keyword.');Object.defineProperty(e,"currentProvider",{get:function(){return e._provider},set:function(t){return e.setProvider(t)},enumerable:!0,configurable:!0}),t[0]&&t[0]._requestManager?e._requestManager=new n.Manager(t[0].currentProvider):(e._requestManager=new n.Manager,e._requestManager.setProvider(t[0],t[1])),e.givenProvider=n.Manager.givenProvider,e.providers=n.Manager.providers,e._provider=e._requestManager.provider,e.setProvider||(e.setProvider=function(t,r){return e._requestManager.setProvider(t,r),e._provider=e._requestManager.provider,!0}),e.BatchRequest=n.BatchManager.bind(null,e._requestManager),e.extend=i(e)},addProviders:function(e){e.givenProvider=n.Manager.givenProvider,e.providers=n.Manager.providers}}},{"./extend.js":347,"web3-core-requestmanager":343}],349:[function(e,t,r){var n=e("underscore"),i=e("web3-utils"),o=new(0,e("ethers/utils/abi-coder").AbiCoder)(function(e,t){return!e.match(/^u?int/)||n.isArray(t)||n.isObject(t)&&"BN"===t.constructor.name?t:t.toString()});function a(){}var s=function(){};s.prototype.encodeFunctionSignature=function(e){return n.isObject(e)&&(e=i._jsonInterfaceMethodToString(e)),i.sha3(e).slice(0,10)},s.prototype.encodeEventSignature=function(e){return n.isObject(e)&&(e=i._jsonInterfaceMethodToString(e)),i.sha3(e)},s.prototype.encodeParameter=function(e,t){return this.encodeParameters([e],[t])},s.prototype.encodeParameters=function(e,t){return o.encode(this.mapTypes(e),t)},s.prototype.mapTypes=function(e){var t=this,r=[];return e.forEach(function(e){if(t.isSimplifiedStructFormat(e)){var n=Object.keys(e)[0];r.push(Object.assign(t.mapStructNameAndType(n),{components:t.mapStructToCoderFormat(e[n])}))}else r.push(e)}),r},s.prototype.isSimplifiedStructFormat=function(e){return"object"==typeof e&&void 0===e.components&&void 0===e.name},s.prototype.mapStructNameAndType=function(e){var t="tuple";return e.indexOf("[]")>-1&&(t="tuple[]",e=e.slice(0,-2)),{type:t,name:e}},s.prototype.mapStructToCoderFormat=function(e){var t=this,r=[];return Object.keys(e).forEach(function(n){"object"!=typeof e[n]?r.push({name:n,type:e[n]}):r.push(Object.assign(t.mapStructNameAndType(n),{components:t.mapStructToCoderFormat(e[n])}))}),r},s.prototype.encodeFunctionCall=function(e,t){return this.encodeFunctionSignature(e)+this.encodeParameters(e.inputs,t).replace("0x","")},s.prototype.decodeParameter=function(e,t){return this.decodeParameters([e],t)[0]},s.prototype.decodeParameters=function(e,t){if(!t||"0x"===t||"0X"===t)throw new Error("Returned values aren't valid, did it run Out of Gas?");var r=o.decode(this.mapTypes(e),"0x"+t.replace(/0x/i,"")),i=new a;return i.__length__=0,e.forEach(function(e,t){var o=r[i.__length__];o="0x"===o?null:o,i[t]=o,n.isObject(e)&&e.name&&(i[e.name]=o),i.__length__++}),i},s.prototype.decodeLog=function(e,t,r){var i=this;r=n.isArray(r)?r:[r],t=t||"";var o=[],s=[],u=0;e.forEach(function(e,t){e.indexed?(s[t]=["bool","int","uint","address","fixed","ufixed"].find(function(t){return-1!==e.type.indexOf(t)})?i.decodeParameter(e.type,r[u]):r[u],u++):o[t]=e});var c=t,f=c?this.decodeParameters(o,c):[],h=new a;return h.__length__=0,e.forEach(function(e,t){h[t]="string"===e.type?"":null,void 0!==f[t]&&(h[t]=f[t]),void 0!==s[t]&&(h[t]=s[t]),e.name&&(h[e.name]=h[t]),h.__length__++}),h};var u=new s;t.exports=u},{"ethers/utils/abi-coder":143,underscore:325,"web3-utils":403}],350:[function(e,t,r){(function(r){var n=function(){return function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var r=[],n=!0,i=!1,o=void 0;try{for(var a,s=e[Symbol.iterator]();!(n=(a=s.next()).done)&&(r.push(a.value),!t||r.length!==t);n=!0);}catch(e){i=!0,o=e}finally{try{!n&&s.return&&s.return()}finally{if(i)throw o}}return r}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),i=e("./bytes"),o=e("./nat"),a=e("elliptic"),s=(e("./rlp"),new a.ec("secp256k1")),u=e("./hash"),c=u.keccak256,f=u.keccak256s,h=function(e){for(var t=f(e.slice(2)),r="0x",n=0;n<40;n++)r+=parseInt(t[n+2],16)>7?e[n+2].toUpperCase():e[n+2];return r},l=function(e){var t=new r(e.slice(2),"hex"),n="0x"+s.keyFromPrivate(t).getPublic(!1,"hex").slice(2),i=c(n);return{address:h("0x"+i.slice(-40)),privateKey:e}},d=function(e){var t=n(e,3),r=t[0],o=i.pad(32,t[1]),a=i.pad(32,t[2]);return i.flatten([o,a,r])},p=function(e){return[i.slice(64,i.length(e),e),i.slice(0,32,e),i.slice(32,64,e)]},b=function(e){return function(t,n){var a=s.keyFromPrivate(new r(n.slice(2),"hex")).sign(new r(t.slice(2),"hex"),{canonical:!0});return d([o.fromString(i.fromNumber(e+a.recoveryParam)),i.pad(32,i.fromNat("0x"+a.r.toString(16))),i.pad(32,i.fromNat("0x"+a.s.toString(16)))])}},y=b(27);t.exports={create:function(e){var t=c(i.concat(i.random(32),e||i.random(32))),r=i.concat(i.concat(i.random(32),t),i.random(32)),n=c(r);return l(n)},toChecksum:h,fromPrivate:l,sign:y,makeSigner:b,recover:function(e,t){var n=p(t),o={v:i.toNumber(n[0]),r:n[1].slice(2),s:n[2].slice(2)},a="0x"+s.recoverPubKey(new r(e.slice(2),"hex"),o,o.v<2?o.v:1-o.v%2).encode("hex",!1).slice(2),u=c(a);return h("0x"+u.slice(-40))},encodeSignature:d,decodeSignature:p}}).call(this,e("buffer").Buffer)},{"./bytes":352,"./hash":353,"./nat":354,"./rlp":355,buffer:84,elliptic:109}],351:[function(e,t,r){arguments[4][132][0].apply(r,arguments)},{dup:132}],352:[function(e,t,r){arguments[4][133][0].apply(r,arguments)},{"./array.js":351,dup:133}],353:[function(e,t,r){arguments[4][134][0].apply(r,arguments)},{dup:134}],354:[function(e,t,r){var n=e("bn.js"),i=e("./bytes"),o=function(e){return new n(e.slice(2),16)},a=function(e){var t="0x"+("0x"===e.slice(0,2)?new n(e.slice(2),16):new n(e,10)).toString("hex");return"0x0"===t?"0x":t},s=function(e){return"string"==typeof e?/^0x/.test(e)?e:"0x"+e:"0x"+new n(e).toString("hex")},u=function(e){return o(e).toNumber()},c=function(e){return function(t,r){return"0x"+o(t)[e](o(r)).toString("hex")}},f=c("add"),h=c("mul"),l=c("div"),d=c("sub");t.exports={toString:function(e){return o(e).toString(10)},fromString:a,toNumber:u,fromNumber:s,toEther:function(e){return u(l(e,a("10000000000")))/1e8},fromEther:function(e){return h(s(Math.floor(1e8*e)),a("10000000000"))},toUint256:function(e){return i.pad(32,e)},add:f,mul:h,div:l,sub:d}},{"./bytes":352,"bn.js":53}],355:[function(e,t,r){t.exports={encode:function(e){var t=function(e){return(t=e.toString(16)).length%2==0?t:"0"+t;var t},r=function(e,r){return e<56?t(r+e):t(r+t(e).length/2+55)+t(e)};return"0x"+function e(t){if("string"==typeof t){var n=t.slice(2);return(2!=n.length||n>="80"?r(n.length/2,128):"")+n}var i=t.map(e).join("");return r(i.length/2,192)+i}(e)},decode:function(e){var t=2,r=function(){if(t>=e.length)throw"";var r=e.slice(t,t+2);return r<"80"?(t+=2,"0x"+r):r<"c0"?i():o()},n=function(){var r=parseInt(e.slice(t,t+=2),16)%64;return r<56?r:parseInt(e.slice(t,t+=2*(r-55)),16)},i=function(){var r=n();return"0x"+e.slice(t,t+=2*r)},o=function(){for(var e=2*n()+t,i=[];t>>((3&t)<<3)&255;return i}}t.exports=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],357:[function(e,t,r){for(var n=e("./rng"),i=[],o={},a=0;a<256;a++)i[a]=(a+256).toString(16).substr(1),o[i[a]]=a;function s(e,t){var r=t||0,n=i;return n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]}var u=n(),c=[1|u[0],u[1],u[2],u[3],u[4],u[5]],f=16383&(u[6]<<8|u[7]),h=0,l=0;function d(e,t,r){var i=t&&r||0;"string"==typeof e&&(t="binary"==e?new Array(16):null,e=null);var o=(e=e||{}).random||(e.rng||n)();if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,t)for(var a=0;a<16;a++)t[i+a]=o[a];return t||s(o)}var p=d;p.v1=function(e,t,r){var n=t&&r||0,i=t||[],o=void 0!==(e=e||{}).clockseq?e.clockseq:f,a=void 0!==e.msecs?e.msecs:(new Date).getTime(),u=void 0!==e.nsecs?e.nsecs:l+1,d=a-h+(u-l)/1e4;if(d<0&&void 0===e.clockseq&&(o=o+1&16383),(d<0||a>h)&&void 0===e.nsecs&&(u=0),u>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");h=a,l=u,f=o;var p=(1e4*(268435455&(a+=122192928e5))+u)%4294967296;i[n++]=p>>>24&255,i[n++]=p>>>16&255,i[n++]=p>>>8&255,i[n++]=255&p;var b=a/4294967296*1e4&268435455;i[n++]=b>>>8&255,i[n++]=255&b,i[n++]=b>>>24&15|16,i[n++]=b>>>16&255,i[n++]=o>>>8|128,i[n++]=255&o;for(var y=e.node||c,m=0;m<6;m++)i[n+m]=y[m];return t||s(i)},p.v4=d,p.parse=function(e,t,r){var n=t&&r||0,i=0;for(t=t||[],e.toLowerCase().replace(/[0-9a-f]{2}/g,function(e){i<16&&(t[n+i++]=o[e])});i<16;)t[n+i++]=0;return t},p.unparse=s,t.exports=p},{"./rng":356}],358:[function(e,t,r){(function(r,n){"use strict";var i=e("underscore"),o=e("web3-core"),a=e("web3-core-method"),s=e("any-promise"),u=e("eth-lib/lib/account"),c=e("eth-lib/lib/hash"),f=e("eth-lib/lib/rlp"),h=e("eth-lib/lib/nat"),l=e("eth-lib/lib/bytes"),d=e(void 0===r?"crypto-browserify":"crypto"),p=e("scrypt.js"),b=e("uuid"),y=e("web3-utils"),m=e("web3-core-helpers"),v=function(e){return i.isUndefined(e)||i.isNull(e)},g=function(e){for(;e&&e.startsWith("0x0");)e="0x"+e.slice(3);return e},w=function(e){return e.length%2==1&&(e=e.replace("0x","0x0")),e},_=function(){var e=this;o.packageInit(this,arguments),delete this.BatchRequest,delete this.extend;var t=[new a({name:"getId",call:"net_version",params:0,outputFormatter:y.hexToNumber}),new a({name:"getGasPrice",call:"eth_gasPrice",params:0}),new a({name:"getTransactionCount",call:"eth_getTransactionCount",params:2,inputFormatter:[function(e){if(y.isAddress(e))return e;throw new Error("Address "+e+' is not a valid address to get the "transactionCount".')},function(){return"latest"}]})];this._ethereumCall={},i.each(t,function(t){t.attachToObject(e._ethereumCall),t.setRequestManager(e._requestManager)}),this.wallet=new A(this)};function A(e){this._accounts=e,this.length=0,this.defaultKeyName="web3js_wallet"}_.prototype._addAccountFunctions=function(e){var t=this;return e.signTransaction=function(r,n){return t.signTransaction(r,e.privateKey,n)},e.sign=function(r){return t.sign(r,e.privateKey)},e.encrypt=function(r,n){return t.encrypt(e.privateKey,r,n)},e},_.prototype.create=function(e){return this._addAccountFunctions(u.create(e||y.randomHex(32)))},_.prototype.privateKeyToAccount=function(e){return this._addAccountFunctions(u.fromPrivate(e))},_.prototype.signTransaction=function(e,t,r){var n,o=!1;if(r=r||function(){},!e)return o=new Error("No transaction object given!"),r(o),s.reject(o);function a(e){if(e.gas||e.gasLimit||(o=new Error('"gas" is missing')),(e.nonce<0||e.gas<0||e.gasPrice<0||e.chainId<0)&&(o=new Error("Gas, gasPrice, nonce or chainId is lower than 0")),o)return r(o),s.reject(o);try{var i=e=m.formatters.inputCallFormatter(e);i.to=e.to||"0x",i.data=e.data||"0x",i.value=e.value||"0x",i.chainId=y.numberToHex(e.chainId);var a=f.encode([l.fromNat(i.nonce),l.fromNat(i.gasPrice),l.fromNat(i.gas),i.to.toLowerCase(),l.fromNat(i.value),i.data,l.fromNat(i.chainId||"0x1"),"0x","0x"]),d=c.keccak256(a),p=u.makeSigner(2*h.toNumber(i.chainId||"0x1")+35)(c.keccak256(a),t),b=f.decode(a).slice(0,6).concat(u.decodeSignature(p));b[6]=w(g(b[6])),b[7]=w(g(b[7])),b[8]=w(g(b[8]));var v=f.encode(b),_=f.decode(v);n={messageHash:d,v:g(_[6]),r:g(_[7]),s:g(_[8]),rawTransaction:v}}catch(e){return r(e),s.reject(e)}return r(null,n),n}return void 0!==e.nonce&&void 0!==e.chainId&&void 0!==e.gasPrice?s.resolve(a(e)):s.all([v(e.chainId)?this._ethereumCall.getId():e.chainId,v(e.gasPrice)?this._ethereumCall.getGasPrice():e.gasPrice,v(e.nonce)?this._ethereumCall.getTransactionCount(this.privateKeyToAccount(t).address):e.nonce]).then(function(t){if(v(t[0])||v(t[1])||v(t[2]))throw new Error('One of the values "chainId", "gasPrice", or "nonce" couldn\'t be fetched: '+JSON.stringify(t));return a(i.extend(e,{chainId:t[0],gasPrice:t[1],nonce:t[2]}))})},_.prototype.recoverTransaction=function(e){var t=f.decode(e),r=u.encodeSignature(t.slice(6,9)),n=l.toNumber(t[6]),i=n<35?[]:[l.fromNumber(n-35>>1),"0x","0x"],o=t.slice(0,6).concat(i),a=f.encode(o);return u.recover(c.keccak256(a),r)},_.prototype.hashMessage=function(e){var t=y.isHexStrict(e)?y.hexToBytes(e):e,r=n.from(t),i="Ethereum Signed Message:\n"+t.length,o=n.from(i),a=n.concat([o,r]);return c.keccak256s(a)},_.prototype.sign=function(e,t){var r=this.hashMessage(e),n=u.sign(r,t),i=u.decodeSignature(n);return{message:e,messageHash:r,v:i[0],r:i[1],s:i[2],signature:n}},_.prototype.recover=function(e,t,r){var n=[].slice.apply(arguments);return i.isObject(e)?this.recover(e.messageHash,u.encodeSignature([e.v,e.r,e.s]),!0):(r||(e=this.hashMessage(e)),n.length>=4?(r=n.slice(-1)[0],r=!!i.isBoolean(r)&&!!r,this.recover(e,u.encodeSignature(n.slice(1,4)),r)):u.recover(e,t))},_.prototype.decrypt=function(e,t,r){if(!i.isString(t))throw new Error("No password given.");var o,a,s=i.isObject(e)?e:JSON.parse(r?e.toLowerCase():e);if(3!==s.version)throw new Error("Not a valid V3 wallet");if("scrypt"===s.crypto.kdf)a=s.crypto.kdfparams,o=p(new n(t),new n(a.salt,"hex"),a.n,a.r,a.p,a.dklen);else{if("pbkdf2"!==s.crypto.kdf)throw new Error("Unsupported key derivation scheme");if("hmac-sha256"!==(a=s.crypto.kdfparams).prf)throw new Error("Unsupported parameters to PBKDF2");o=d.pbkdf2Sync(new n(t),new n(a.salt,"hex"),a.c,a.dklen,"sha256")}var u=new n(s.crypto.ciphertext,"hex");if(y.sha3(n.concat([o.slice(16,32),u])).replace("0x","")!==s.crypto.mac)throw new Error("Key derivation failed - possibly wrong password");var c=d.createDecipheriv(s.crypto.cipher,o.slice(0,16),new n(s.crypto.cipherparams.iv,"hex")),f="0x"+n.concat([c.update(u),c.final()]).toString("hex");return this.privateKeyToAccount(f)},_.prototype.encrypt=function(e,t,r){var i,o=this.privateKeyToAccount(e),a=(r=r||{}).salt||d.randomBytes(32),s=r.iv||d.randomBytes(16),u=r.kdf||"scrypt",c={dklen:r.dklen||32,salt:a.toString("hex")};if("pbkdf2"===u)c.c=r.c||262144,c.prf="hmac-sha256",i=d.pbkdf2Sync(new n(t),a,c.c,c.dklen,"sha256");else{if("scrypt"!==u)throw new Error("Unsupported kdf");c.n=r.n||8192,c.r=r.r||8,c.p=r.p||1,i=p(new n(t),a,c.n,c.r,c.p,c.dklen)}var f=d.createCipheriv(r.cipher||"aes-128-ctr",i.slice(0,16),s);if(!f)throw new Error("Unsupported cipher");var h=n.concat([f.update(new n(o.privateKey.replace("0x",""),"hex")),f.final()]),l=y.sha3(n.concat([i.slice(16,32),new n(h,"hex")])).replace("0x","");return{version:3,id:b.v4({random:r.uuid||d.randomBytes(16)}),address:o.address.toLowerCase().replace("0x",""),crypto:{ciphertext:h.toString("hex"),cipherparams:{iv:s.toString("hex")},cipher:r.cipher||"aes-128-ctr",kdf:u,kdfparams:c,mac:l.toString("hex")}}},A.prototype._findSafeIndex=function(e){return e=e||0,i.has(this,e)?this._findSafeIndex(e+1):e},A.prototype._currentIndexes=function(){return Object.keys(this).map(function(e){return parseInt(e)}).filter(function(e){return e<9e20})},A.prototype.create=function(e,t){for(var r=0;r=2?t.slice(2):t;var r=h.decodeParameters(e,t);return 1===r.__length__?r[0]:(delete r.__length__,r)},l.prototype.deploy=function(e,t){if((e=e||{}).arguments=e.arguments||[],!(e=this._getOrSetDefaultOptions(e)).data)return a._fireError(new Error('No "data" specified in neither the given options, nor the default options.'),null,null,t);var r=n.find(this.options.jsonInterface,function(e){return"constructor"===e.type})||{};return r.signature="constructor",this._createTxObject.apply({method:r,parent:this,deployData:e.data,_ethAccounts:this.constructor._ethAccounts},e.arguments)},l.prototype._generateEventOptions=function(){var e=Array.prototype.slice.call(arguments),t=this._getCallback(e),r=n.isObject(e[e.length-1])?e.pop():{},i=n.isString(e[0])?e[0]:"allevents";if(!(i="allevents"===i.toLowerCase()?{name:"ALLEVENTS",jsonInterface:this.options.jsonInterface}:this.options.jsonInterface.find(function(e){return"event"===e.type&&(e.name===i||e.signature==="0x"+i.replace("0x",""))})))throw new Error('Event "'+i.name+"\" doesn't exist in this contract.");if(!a.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(i,r),event:i,callback:t}},l.prototype.clone=function(){return new this.constructor(this.options.jsonInterface,this.options.address,this.options)},l.prototype.once=function(e,t,r){var i=Array.prototype.slice.call(arguments);if(!(r=this._getCallback(i)))throw new Error("Once requires a callback as the second parameter.");t&&delete t.fromBlock,this._on(e,t,function(e,t,i){i.unsubscribe(),n.isFunction(r)&&r(e,t,i)})},l.prototype._on=function(){var e=this._generateEventOptions.apply(this,arguments);this._checkListener("newListener",e.event.name,e.callback),this._checkListener("removeListener",e.event.name,e.callback);var t=new s({subscription:{params:1,inputFormatter:[u.inputLogFormatter],outputFormatter:this._decodeEventABI.bind(e.event),subscriptionHandler:function(e){e.removed?this.emit("changed",e):this.emit("data",e),n.isFunction(this.callback)&&this.callback(null,e,this)}},type:"eth",requestManager:this._requestManager});return t.subscribe("logs",e.params,e.callback||function(){}),t},l.prototype.getPastEvents=function(){var e=this._generateEventOptions.apply(this,arguments),t=new o({name:"getPastLogs",call:"eth_getLogs",params:1,inputFormatter:[u.inputLogFormatter],outputFormatter:this._decodeEventABI.bind(e.event)});t.setRequestManager(this._requestManager);var r=t.buildCall();return t=null,r(e.params,e.callback)},l.prototype._createTxObject=function(){var e=Array.prototype.slice.call(arguments),t={};if("function"===this.method.type&&(t.call=this.parent._executeMethod.bind(t,"call"),t.call.request=this.parent._executeMethod.bind(t,"call",!0)),t.send=this.parent._executeMethod.bind(t,"send"),t.send.request=this.parent._executeMethod.bind(t,"send",!0),t.encodeABI=this.parent._encodeMethodABI.bind(t),t.estimateGas=this.parent._executeMethod.bind(t,"estimate"),e&&this.method.inputs&&e.length!==this.method.inputs.length){if(this.nextMethod)return this.nextMethod.apply(null,e);throw c.InvalidNumberOfParams(e.length,this.method.inputs.length,this.method.name)}return t.arguments=e||[],t._method=this.method,t._parent=this.parent,t._ethAccounts=this.parent.constructor._ethAccounts||this._ethAccounts,this.deployData&&(t._deployData=this.deployData),t},l.prototype._processExecuteArguments=function(e,t){var r={};if(r.type=e.shift(),r.callback=this._parent._getCallback(e),"call"===r.type&&!0!==e[e.length-1]&&(n.isString(e[e.length-1])||isFinite(e[e.length-1]))&&(r.defaultBlock=e.pop()),r.options=n.isObject(e[e.length-1])?e.pop():{},r.generateRequest=!0===e[e.length-1]&&e.pop(),r.options=this._parent._getOrSetDefaultOptions(r.options),r.options.data=this.encodeABI(),!this._deployData&&!a.isAddress(this._parent.options.address))throw new Error("This contract object doesn't have address set yet, please set an address first.");return this._deployData||(r.options.to=this._parent.options.address),r.options.data?r:a._fireError(new Error("Couldn't find a matching contract method, or the number of parameters is wrong."),t.eventEmitter,t.reject,r.callback)},l.prototype._executeMethod=function(){var e=this,t=this._parent._processExecuteArguments.call(this,Array.prototype.slice.call(arguments),r),r=f("send"!==t.type),i=e.constructor._ethAccounts||e._ethAccounts;if(t.generateRequest){var s={params:[u.inputCallFormatter.call(this._parent,t.options)],callback:t.callback};return"call"===t.type?(s.params.push(u.inputDefaultBlockNumberFormatter.call(this._parent,t.defaultBlock)),s.method="eth_call",s.format=this._parent._decodeMethodReturn.bind(null,this._method.outputs)):s.method="eth_sendTransaction",s}switch(t.type){case"estimate":return new o({name:"estimateGas",call:"eth_estimateGas",params:1,inputFormatter:[u.inputCallFormatter],outputFormatter:a.hexToNumber,requestManager:e._parent._requestManager,accounts:i,defaultAccount:e._parent.defaultAccount,defaultBlock:e._parent.defaultBlock}).createFunction()(t.options,t.callback);case"call":return new o({name:"call",call:"eth_call",params:2,inputFormatter:[u.inputCallFormatter,u.inputDefaultBlockNumberFormatter],outputFormatter:function(t){return e._parent._decodeMethodReturn(e._method.outputs,t)},requestManager:e._parent._requestManager,accounts:i,defaultAccount:e._parent.defaultAccount,defaultBlock:e._parent.defaultBlock}).createFunction()(t.options,t.defaultBlock,t.callback);case"send":if(!a.isAddress(t.options.from))return a._fireError(new Error('No "from" address specified in neither the given options, nor the default options.'),r.eventEmitter,r.reject,t.callback);if(n.isBoolean(this._method.payable)&&!this._method.payable&&t.options.value&&t.options.value>0)return a._fireError(new Error("Can not send value to non-payable contract method or constructor"),r.eventEmitter,r.reject,t.callback);var c={receiptFormatter:function(t){if(n.isArray(t.logs)){var r=n.map(t.logs,function(t){return e._parent._decodeEventABI.call({name:"ALLEVENTS",jsonInterface:e._parent.options.jsonInterface},t)});t.events={};var i=0;r.forEach(function(e){e.event?t.events[e.event]?Array.isArray(t.events[e.event])?t.events[e.event].push(e):t.events[e.event]=[t.events[e.event],e]:t.events[e.event]=e:(t.events[i]=e,i++)}),delete t.logs}return t},contractDeployFormatter:function(t){var r=e._parent.clone();return r.options.address=t.contractAddress,r}};return new o({name:"sendTransaction",call:"eth_sendTransaction",params:1,inputFormatter:[u.inputTransactionFormatter],requestManager:e._parent._requestManager,accounts:e.constructor._ethAccounts||e._ethAccounts,defaultAccount:e._parent.defaultAccount,defaultBlock:e._parent.defaultBlock,extraFormatters:c}).createFunction()(t.options,t.callback)}},t.exports=l},{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(e,t,r){"use strict";var n=e("./config"),i=e("./contracts/Registry"),o=e("./lib/ResolverMethodHandler");function a(e){this.eth=e}Object.defineProperty(a.prototype,"registry",{get:function(){return new i(this)},enumerable:!0}),Object.defineProperty(a.prototype,"resolverMethodHandler",{get:function(){return new o(this.registry)},enumerable:!0}),a.prototype.resolver=function(e){return this.registry.resolver(e)},a.prototype.getAddress=function(e,t){return this.resolverMethodHandler.method(e,"addr",[]).call(t)},a.prototype.setAddress=function(e,t,r,n){return this.resolverMethodHandler.method(e,"setAddr",[t]).send(r,n)},a.prototype.getPubkey=function(e,t){return this.resolverMethodHandler.method(e,"pubkey",[],t).call(t)},a.prototype.setPubkey=function(e,t,r,n,i){return this.resolverMethodHandler.method(e,"setPubkey",[t,r]).send(n,i)},a.prototype.getContent=function(e,t){return this.resolverMethodHandler.method(e,"content",[]).call(t)},a.prototype.setContent=function(e,t,r,n){return this.resolverMethodHandler.method(e,"setContent",[t]).send(r,n)},a.prototype.getMultihash=function(e,t){return this.resolverMethodHandler.method(e,"multihash",[]).call(t)},a.prototype.setMultihash=function(e,t,r,n){return this.resolverMethodHandler.method(e,"multihash",[t]).send(r,n)},a.prototype.checkNetwork=function(){var e=this;return e.eth.getBlock("latest").then(function(t){var r=new Date/1e3-t.timestamp;if(r>3600)throw new Error("Network not synced; last block was "+r+" seconds ago");return e.eth.net.getNetworkType()}).then(function(e){var t=n.addresses[e];if(void 0===t)throw new Error("ENS is not supported on network "+e);return t})},t.exports=a},{"./config":361,"./contracts/Registry":362,"./lib/ResolverMethodHandler":364}],361:[function(e,t,r){"use strict";t.exports={addresses:{main:"0x314159265dD8dbb310642f98f50C066173C1259b",ropsten:"0x112234455c3a32fd11230c42e7bccd4a84e02010",rinkeby:"0xe7410170f87102df0055eb195163a03b7f2bff4a"}}},{}],362:[function(e,t,r){"use strict";var n=e("underscore"),i=e("web3-eth-contract"),o=e("eth-ens-namehash"),a=e("web3-core-promievent"),s=e("../ressources/ABI/Registry"),u=e("../ressources/ABI/Resolver");function c(e){var t=this;this.ens=e,this.contract=e.checkNetwork().then(function(e){var r=new i(s,e);return r.setProvider(t.ens.eth.currentProvider),r})}c.prototype.owner=function(e,t){var r=new a(!0);return this.contract.then(function(i){i.methods.owner(o.hash(e)).call().then(function(e){r.resolve(e),n.isFunction(t)&&t(e)}).catch(function(e){r.reject(e),n.isFunction(t)&&t(e)})}),r.eventEmitter},c.prototype.resolver=function(e){var t=this;return this.contract.then(function(t){return t.methods.resolver(o.hash(e)).call()}).then(function(e){var r=new i(u,e);return r.setProvider(t.ens.eth.currentProvider),r})},t.exports=c},{"../ressources/ABI/Registry":365,"../ressources/ABI/Resolver":366,"eth-ens-namehash":127,underscore:325,"web3-core-promievent":340,"web3-eth-contract":359}],363:[function(e,t,r){"use strict";var n=e("./ENS");t.exports=n},{"./ENS":360}],364:[function(e,t,r){"use strict";var n=e("web3-core-promievent"),i=e("eth-ens-namehash"),o=e("underscore");function a(e){this.registry=e}a.prototype.method=function(e,t,r,n){return{call:this.call.bind({ensName:e,methodName:t,methodArguments:r,callback:n,parent:this}),send:this.send.bind({ensName:e,methodName:t,methodArguments:r,callback:n,parent:this})}},a.prototype.call=function(e){var t=this,r=new n,i=this.parent.prepareArguments(this.ensName,this.methodArguments);return this.parent.registry.resolver(this.ensName).then(function(n){t.parent.handleCall(r,n.methods[t.methodName],i,e)}).catch(function(e){r.reject(e)}),r.eventEmitter},a.prototype.send=function(e,t){var r=this,i=new n,o=this.parent.prepareArguments(this.ensName,this.methodArguments);return this.parent.registry.resolver(this.ensName).then(function(n){r.parent.handleSend(i,n.methods[r.methodName],o,e,t)}).catch(function(e){i.reject(e)}),i.eventEmitter},a.prototype.handleCall=function(e,t,r,n){return t.apply(this,r).call().then(function(t){e.resolve(t),o.isFunction(n)&&n(t)}).catch(function(t){e.reject(t),o.isFunction(n)&&n(t)}),e},a.prototype.handleSend=function(e,t,r,n,i){return t.apply(this,r).send(n).on("transactionHash",function(t){e.eventEmitter.emit("transactionHash",t)}).on("confirmation",function(t,r){e.eventEmitter.emit("confirmation",t,r)}).on("receipt",function(t){e.eventEmitter.emit("receipt",t),e.resolve(t),o.isFunction(i)&&i(t)}).on("error",function(t){e.eventEmitter.emit("error",t),e.reject(t),o.isFunction(i)&&i(t)}),e},a.prototype.prepareArguments=function(e,t){var r=i.hash(e);return t.length>0?(t.unshift(r),t):[r]},t.exports=a},{"eth-ens-namehash":127,underscore:325,"web3-core-promievent":340}],365:[function(e,t,r){"use strict";t.exports=[{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"resolver",outputs:[{name:"",type:"address"}],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"owner",outputs:[{name:"",type:"address"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"label",type:"bytes32"},{name:"owner",type:"address"}],name:"setSubnodeOwner",outputs:[],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"ttl",type:"uint64"}],name:"setTTL",outputs:[],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"ttl",outputs:[{name:"",type:"uint64"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"resolver",type:"address"}],name:"setResolver",outputs:[],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"owner",type:"address"}],name:"setOwner",outputs:[],payable:!1,type:"function"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"owner",type:"address"}],name:"Transfer",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!0,name:"label",type:"bytes32"},{indexed:!1,name:"owner",type:"address"}],name:"NewOwner",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"resolver",type:"address"}],name:"NewResolver",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"ttl",type:"uint64"}],name:"NewTTL",type:"event"}]},{}],366:[function(e,t,r){"use strict";t.exports=[{constant:!0,inputs:[{name:"interfaceID",type:"bytes4"}],name:"supportsInterface",outputs:[{name:"",type:"bool"}],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"},{name:"contentTypes",type:"uint256"}],name:"ABI",outputs:[{name:"contentType",type:"uint256"},{name:"data",type:"bytes"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"hash",type:"bytes"}],name:"setMultihash",outputs:[],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"multihash",outputs:[{name:"",type:"bytes"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"x",type:"bytes32"},{name:"y",type:"bytes32"}],name:"setPubkey",outputs:[],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"content",outputs:[{name:"ret",type:"bytes32"}],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"addr",outputs:[{name:"ret",type:"address"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"contentType",type:"uint256"},{name:"data",type:"bytes"}],name:"setABI",outputs:[],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"name",outputs:[{name:"ret",type:"string"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"name",type:"string"}],name:"setName",outputs:[],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"hash",type:"bytes32"}],name:"setContent",outputs:[],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"pubkey",outputs:[{name:"x",type:"bytes32"},{name:"y",type:"bytes32"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"addr",type:"address"}],name:"setAddr",outputs:[],payable:!1,type:"function"},{inputs:[{name:"ensAddr",type:"address"}],payable:!1,type:"constructor"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"a",type:"address"}],name:"AddrChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"hash",type:"bytes32"}],name:"ContentChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"name",type:"string"}],name:"NameChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!0,name:"contentType",type:"uint256"}],name:"ABIChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"x",type:"bytes32"},{indexed:!1,name:"y",type:"bytes32"}],name:"PubkeyChanged",type:"event"}]},{}],367:[function(e,t,r){arguments[4][154][0].apply(r,arguments)},{dup:154}],368:[function(e,t,r){"use strict";var n=e("web3-utils"),i=e("bn.js"),o=function(e){var t="A".charCodeAt(0),r="Z".charCodeAt(0);return(e=(e=e.toUpperCase()).substr(4)+e.substr(0,4)).split("").map(function(e){var n=e.charCodeAt(0);return n>=t&&n<=r?n-t+10:e}).join("")},a=function(e){for(var t,r=e;r.length>2;)t=r.slice(0,9),r=parseInt(t,10)%97+r.slice(t.length);return parseInt(r,10)%97},s=function(e){this._iban=e};s.toAddress=function(e){if(!(e=new s(e)).isDirect())throw new Error("IBAN is indirect and can't be converted");return e.toAddress()},s.toIban=function(e){return s.fromAddress(e).toString()},s.fromAddress=function(e){if(!n.isAddress(e))throw new Error("Provided address is not a valid address: "+e);e=e.replace("0x","").replace("0X","");var t=function(e,t){for(var r=e;r.length<2*t;)r="0"+r;return r}(new i(e,16).toString(36),15);return s.fromBban(t.toUpperCase())},s.fromBban=function(e){var t=("0"+(98-a(o("XE00"+e)))).slice(-2);return new s("XE"+t+e)},s.createIndirect=function(e){return s.fromBban("ETH"+e.institution+e.identifier)},s.isValid=function(e){return new s(e).isValid()},s.prototype.isValid=function(){return/^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$/.test(this._iban)&&1===a(o(this._iban))},s.prototype.isDirect=function(){return 34===this._iban.length||35===this._iban.length},s.prototype.isIndirect=function(){return 20===this._iban.length},s.prototype.checksum=function(){return this._iban.substr(2,2)},s.prototype.institution=function(){return this.isIndirect()?this._iban.substr(7,4):""},s.prototype.client=function(){return this.isIndirect()?this._iban.substr(11):""},s.prototype.toAddress=function(){if(this.isDirect()){var e=this._iban.substr(4),t=new i(e,36);return n.toChecksumAddress(t.toString(16,20))}return""},s.prototype.toString=function(){return this._iban},t.exports=s},{"bn.js":367,"web3-utils":403}],369:[function(e,t,r){"use strict";var n=e("web3-core"),i=e("web3-core-method"),o=e("web3-utils"),a=e("web3-net"),s=e("web3-core-helpers").formatters,u=function(){var e=this;n.packageInit(this,arguments),this.net=new a(this.currentProvider);var t=null,r="latest";Object.defineProperty(this,"defaultAccount",{get:function(){return t},set:function(e){return e&&(t=o.toChecksumAddress(s.inputAddressFormatter(e))),u.forEach(function(e){e.defaultAccount=t}),e},enumerable:!0}),Object.defineProperty(this,"defaultBlock",{get:function(){return r},set:function(e){return r=e,u.forEach(function(e){e.defaultBlock=r}),e},enumerable:!0});var u=[new i({name:"getAccounts",call:"personal_listAccounts",params:0,outputFormatter:o.toChecksumAddress}),new i({name:"newAccount",call:"personal_newAccount",params:1,inputFormatter:[null],outputFormatter:o.toChecksumAddress}),new i({name:"unlockAccount",call:"personal_unlockAccount",params:3,inputFormatter:[s.inputAddressFormatter,null,null]}),new i({name:"lockAccount",call:"personal_lockAccount",params:1,inputFormatter:[s.inputAddressFormatter]}),new i({name:"importRawKey",call:"personal_importRawKey",params:2}),new i({name:"sendTransaction",call:"personal_sendTransaction",params:2,inputFormatter:[s.inputTransactionFormatter,null]}),new i({name:"signTransaction",call:"personal_signTransaction",params:2,inputFormatter:[s.inputTransactionFormatter,null]}),new i({name:"sign",call:"personal_sign",params:3,inputFormatter:[s.inputSignFormatter,s.inputAddressFormatter,null]}),new i({name:"ecRecover",call:"personal_ecRecover",params:2,inputFormatter:[s.inputSignFormatter,null]})];u.forEach(function(t){t.attachToObject(e),t.setRequestManager(e._requestManager),t.defaultBlock=e.defaultBlock,t.defaultAccount=e.defaultAccount})};n.addProviders(u),t.exports=u},{"web3-core":348,"web3-core-helpers":338,"web3-core-method":339,"web3-net":372,"web3-utils":403}],370:[function(e,t,r){"use strict";var n=e("underscore");t.exports=function(e){var t,r=this;return this.net.getId().then(function(e){return t=e,r.getBlock(0)}).then(function(r){var i="private";return"0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3"===r.hash&&1===t&&(i="main"),"0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303"===r.hash&&2===t&&(i="morden"),"0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d"===r.hash&&3===t&&(i="ropsten"),"0x6341fd3daf94b748c72ced5a5b26028f2474f5f00d824504e4fa37a75767e177"===r.hash&&4===t&&(i="rinkeby"),"0xa3c565fc15c7478862d50ccd6561e3c06b24cc509bf388941c25ea985ce32cb9"===r.hash&&42===t&&(i="kovan"),n.isFunction(e)&&e(null,i),i}).catch(function(t){if(!n.isFunction(e))throw t;e(t)})}},{underscore:325}],371:[function(e,t,r){"use strict";var n=e("underscore"),i=e("web3-core"),o=e("web3-core-helpers"),a=e("web3-core-subscriptions").subscriptions,s=e("web3-core-method"),u=e("web3-utils"),c=e("web3-net"),f=e("web3-eth-ens"),h=e("web3-eth-personal"),l=e("web3-eth-contract"),d=e("web3-eth-iban"),p=e("web3-eth-accounts"),b=e("web3-eth-abi"),y=e("./getNetworkType.js"),m=o.formatters,v=function(e){return n.isString(e[0])&&0===e[0].indexOf("0x")?"eth_getBlockByHash":"eth_getBlockByNumber"},g=function(e){return n.isString(e[0])&&0===e[0].indexOf("0x")?"eth_getTransactionByBlockHashAndIndex":"eth_getTransactionByBlockNumberAndIndex"},w=function(e){return n.isString(e[0])&&0===e[0].indexOf("0x")?"eth_getUncleByBlockHashAndIndex":"eth_getUncleByBlockNumberAndIndex"},_=function(e){return n.isString(e[0])&&0===e[0].indexOf("0x")?"eth_getBlockTransactionCountByHash":"eth_getBlockTransactionCountByNumber"},A=function(e){return n.isString(e[0])&&0===e[0].indexOf("0x")?"eth_getUncleCountByBlockHash":"eth_getUncleCountByBlockNumber"},E=function(){var e=this;i.packageInit(this,arguments);var t=this.setProvider;this.setProvider=function(){t.apply(e,arguments),e.net.setProvider.apply(e,arguments),e.personal.setProvider.apply(e,arguments),e.accounts.setProvider.apply(e,arguments),e.Contract.setProvider(e.currentProvider,e.accounts)};var r=null,o="latest";Object.defineProperty(this,"defaultAccount",{get:function(){return r},set:function(t){return t&&(r=u.toChecksumAddress(m.inputAddressFormatter(t))),e.Contract.defaultAccount=r,e.personal.defaultAccount=r,k.forEach(function(e){e.defaultAccount=r}),t},enumerable:!0}),Object.defineProperty(this,"defaultBlock",{get:function(){return o},set:function(t){return o=t,e.Contract.defaultBlock=o,e.personal.defaultBlock=o,k.forEach(function(e){e.defaultBlock=o}),t},enumerable:!0}),this.clearSubscriptions=e._requestManager.clearSubscriptions,this.net=new c(this.currentProvider),this.net.getNetworkType=y.bind(this),this.accounts=new p(this.currentProvider),this.personal=new h(this.currentProvider),this.personal.defaultAccount=this.defaultAccount;var E=this,x=function(){l.apply(this,arguments);var e=this,t=E.setProvider;E.setProvider=function(){t.apply(E,arguments),i.packageInit(e,[E.currentProvider])}};x.setProvider=function(){l.setProvider.apply(this,arguments)},(x.prototype=Object.create(l.prototype)).constructor=x,this.Contract=x,this.Contract.defaultAccount=this.defaultAccount,this.Contract.defaultBlock=this.defaultBlock,this.Contract.setProvider(this.currentProvider,this.accounts),this.Iban=d,this.abi=b,this.ens=new f(this);var k=[new s({name:"getNodeInfo",call:"web3_clientVersion"}),new s({name:"getProtocolVersion",call:"eth_protocolVersion",params:0}),new s({name:"getCoinbase",call:"eth_coinbase",params:0}),new s({name:"isMining",call:"eth_mining",params:0}),new s({name:"getHashrate",call:"eth_hashrate",params:0,outputFormatter:u.hexToNumber}),new s({name:"isSyncing",call:"eth_syncing",params:0,outputFormatter:m.outputSyncingFormatter}),new s({name:"getGasPrice",call:"eth_gasPrice",params:0,outputFormatter:m.outputBigNumberFormatter}),new s({name:"getAccounts",call:"eth_accounts",params:0,outputFormatter:u.toChecksumAddress}),new s({name:"getBlockNumber",call:"eth_blockNumber",params:0,outputFormatter:u.hexToNumber}),new s({name:"getBalance",call:"eth_getBalance",params:2,inputFormatter:[m.inputAddressFormatter,m.inputDefaultBlockNumberFormatter],outputFormatter:m.outputBigNumberFormatter}),new s({name:"getStorageAt",call:"eth_getStorageAt",params:3,inputFormatter:[m.inputAddressFormatter,u.numberToHex,m.inputDefaultBlockNumberFormatter]}),new s({name:"getCode",call:"eth_getCode",params:2,inputFormatter:[m.inputAddressFormatter,m.inputDefaultBlockNumberFormatter]}),new s({name:"getBlock",call:v,params:2,inputFormatter:[m.inputBlockNumberFormatter,function(e){return!!e}],outputFormatter:m.outputBlockFormatter}),new s({name:"getUncle",call:w,params:2,inputFormatter:[m.inputBlockNumberFormatter,u.numberToHex],outputFormatter:m.outputBlockFormatter}),new s({name:"getBlockTransactionCount",call:_,params:1,inputFormatter:[m.inputBlockNumberFormatter],outputFormatter:u.hexToNumber}),new s({name:"getBlockUncleCount",call:A,params:1,inputFormatter:[m.inputBlockNumberFormatter],outputFormatter:u.hexToNumber}),new s({name:"getTransaction",call:"eth_getTransactionByHash",params:1,inputFormatter:[null],outputFormatter:m.outputTransactionFormatter}),new s({name:"getTransactionFromBlock",call:g,params:2,inputFormatter:[m.inputBlockNumberFormatter,u.numberToHex],outputFormatter:m.outputTransactionFormatter}),new s({name:"getTransactionReceipt",call:"eth_getTransactionReceipt",params:1,inputFormatter:[null],outputFormatter:m.outputTransactionReceiptFormatter}),new s({name:"getTransactionCount",call:"eth_getTransactionCount",params:2,inputFormatter:[m.inputAddressFormatter,m.inputDefaultBlockNumberFormatter],outputFormatter:u.hexToNumber}),new s({name:"sendSignedTransaction",call:"eth_sendRawTransaction",params:1,inputFormatter:[null]}),new s({name:"signTransaction",call:"eth_signTransaction",params:1,inputFormatter:[m.inputTransactionFormatter]}),new s({name:"sendTransaction",call:"eth_sendTransaction",params:1,inputFormatter:[m.inputTransactionFormatter]}),new s({name:"sign",call:"eth_sign",params:2,inputFormatter:[m.inputSignFormatter,m.inputAddressFormatter],transformPayload:function(e){return e.params.reverse(),e}}),new s({name:"call",call:"eth_call",params:2,inputFormatter:[m.inputCallFormatter,m.inputDefaultBlockNumberFormatter]}),new s({name:"estimateGas",call:"eth_estimateGas",params:1,inputFormatter:[m.inputCallFormatter],outputFormatter:u.hexToNumber}),new s({name:"submitWork",call:"eth_submitWork",params:3}),new s({name:"getWork",call:"eth_getWork",params:0}),new s({name:"getPastLogs",call:"eth_getLogs",params:1,inputFormatter:[m.inputLogFormatter],outputFormatter:m.outputLogFormatter}),new a({name:"subscribe",type:"eth",subscriptions:{newBlockHeaders:{subscriptionName:"newHeads",params:0,outputFormatter:m.outputBlockFormatter},pendingTransactions:{subscriptionName:"newPendingTransactions",params:0},logs:{params:1,inputFormatter:[m.inputLogFormatter],outputFormatter:m.outputLogFormatter,subscriptionHandler:function(e){e.removed?this.emit("changed",e):this.emit("data",e),n.isFunction(this.callback)&&this.callback(null,e,this)}},syncing:{params:0,outputFormatter:m.outputSyncingFormatter,subscriptionHandler:function(e){var t=this;!0!==this._isSyncing?(this._isSyncing=!0,this.emit("changed",t._isSyncing),n.isFunction(this.callback)&&this.callback(null,t._isSyncing,this),setTimeout(function(){t.emit("data",e),n.isFunction(t.callback)&&t.callback(null,e,t)},0)):(this.emit("data",e),n.isFunction(t.callback)&&this.callback(null,e,this),clearTimeout(this._isSyncingTimeout),this._isSyncingTimeout=setTimeout(function(){e.currentBlock>e.highestBlock-200&&(t._isSyncing=!1,t.emit("changed",t._isSyncing),n.isFunction(t.callback)&&t.callback(null,t._isSyncing,t))},500))}}}})];k.forEach(function(t){t.attachToObject(e),t.setRequestManager(e._requestManager,e.accounts),t.defaultBlock=e.defaultBlock,t.defaultAccount=e.defaultAccount})};i.addProviders(E),t.exports=E},{"./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(e,t,r){"use strict";var n=e("web3-core"),i=e("web3-core-method"),o=e("web3-utils"),a=function(){var e=this;n.packageInit(this,arguments),[new i({name:"getId",call:"net_version",params:0,outputFormatter:o.hexToNumber}),new i({name:"isListening",call:"net_listening",params:0}),new i({name:"getPeerCount",call:"net_peerCount",params:0,outputFormatter:o.hexToNumber})].forEach(function(t){t.attachToObject(e),t.setRequestManager(e._requestManager)})};n.addProviders(a),t.exports=a},{"web3-core":348,"web3-core-method":339,"web3-utils":403}],373:[function(e,t,r){const n=e("events").EventEmitter,i=e("util").inherits,o=e("ethereumjs-util"),a=e("eth-block-tracker"),s=e("async/map"),u=e("async/eachSeries"),c=e("./util/stoplight.js");e("./util/rpc-cache-utils.js"),e("./util/create-payload.js");function f(e){const t=this;n.call(t),t.setMaxListeners(30),e=e||{};const r={sendAsync:t._handleAsync.bind(t)},i=e.blockTrackerProvider||r;t._blockTracker=e.blockTracker||new a({provider:i,pollingInterval:e.pollingInterval||4e3}),t._blockTracker.on("block",e=>{const r=function(e){return{number:o.toBuffer(e.number),hash:o.toBuffer(e.hash),parentHash:o.toBuffer(e.parentHash),nonce:o.toBuffer(e.nonce),mixHash:o.toBuffer(e.mixHash),sha3Uncles:o.toBuffer(e.sha3Uncles),logsBloom:o.toBuffer(e.logsBloom),transactionsRoot:o.toBuffer(e.transactionsRoot),stateRoot:o.toBuffer(e.stateRoot),receiptsRoot:o.toBuffer(e.receiptRoot||e.receiptsRoot),miner:o.toBuffer(e.miner),difficulty:o.toBuffer(e.difficulty),totalDifficulty:o.toBuffer(e.totalDifficulty),size:o.toBuffer(e.size),extraData:o.toBuffer(e.extraData),gasLimit:o.toBuffer(e.gasLimit),gasUsed:o.toBuffer(e.gasUsed),timestamp:o.toBuffer(e.timestamp),transactions:e.transactions}}(e);t._setCurrentBlock(r)}),t._blockTracker.on("block",t.emit.bind(t,"rawBlock")),t._blockTracker.on("sync",t.emit.bind(t,"sync")),t._blockTracker.on("latest",t.emit.bind(t,"latest")),t._ready=new c,t._blockTracker.once("block",()=>{t._ready.go()}),t.currentBlock=null,t._providers=[]}t.exports=f,i(f,n),f.prototype.start=function(e=function(){}){this._blockTracker.start().then(e).catch(e)},f.prototype.stop=function(){this._blockTracker.stop()},f.prototype.addProvider=function(e){this._providers.push(e),e.setEngine(this)},f.prototype.send=function(e){throw new Error("Web3ProviderEngine does not support synchronous requests.")},f.prototype.sendAsync=function(e,t){const r=this;r._ready.await(function(){Array.isArray(e)?s(e,r._handleAsync.bind(r),t):r._handleAsync(e,t)})},f.prototype._handleAsync=function(e,t){var r=this,n=-1,i=null,o=null,a=[];function s(r,n){o=r,i=n,u(a,function(e,t){e?e(o,i,t):t()},function(){var r={id:e.id,jsonrpc:e.jsonrpc,result:i};null!=o?(r.error={message:o.stack||o.message||o,code:-32e3},t(o,r)):t(null,r)})}!function t(i){n+=1;a.unshift(i);if(n>=r._providers.length)s(new Error('Request for method "'+e.method+'" not handled by any subprovider. Please check your subprovider configuration to ensure this method is handled.'));else try{var o=r._providers[n];o.handleRequest(e,t,s)}catch(e){s(e)}}()},f.prototype._setCurrentBlock=function(e){this.currentBlock=e,this.emit("block",e)}},{"./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(e,t,r){var n="undefined"!=typeof JSON?JSON:e("jsonify");t.exports=function(e,t){t||(t={}),"function"==typeof t&&(t={cmp:t});var r=t.space||"";"number"==typeof r&&(r=Array(r+1).join(" "));var a,s="boolean"==typeof t.cycles&&t.cycles,u=t.replacer||function(e,t){return t},c=t.cmp&&(a=t.cmp,function(e){return function(t,r){var n={key:t,value:e[t]},i={key:r,value:e[r]};return a(n,i)}}),f=[];return function e(t,a,h,l){var d=r?"\n"+new Array(l+1).join(r):"",p=r?": ":":";if(h&&h.toJSON&&"function"==typeof h.toJSON&&(h=h.toJSON()),void 0!==(h=u.call(t,a,h))){if("object"!=typeof h||null===h)return n.stringify(h);if(i(h)){for(var b=[],y=0;y dist/ProviderEngine.js","bundle-zero":"browserify -s ZeroClientProvider -e zero.js -t [ babelify --presets [ es2015 ] ] > dist/ZeroClientProvider.js",prepublish:"npm run build && npm run bundle",test:"node test/index.js"},version:"14.1.0"}},{}],376:[function(e,t,r){const n=e("util").inherits,i=e("ethereumjs-util"),o=i.BN,a=e("clone"),s=e("../util/rpc-cache-utils.js"),u=e("../util/stoplight.js"),c=e("./subprovider.js");function f(e){e=e||{},this._ready=new u,this.strategies={perma:new l({eth_getTransactionByHash:p,eth_getTransactionReceipt:p}),block:new d(this),fork:new d(this)}}function h(){var e=this;e.cache={};var t=setInterval(function(){e.cache={}},6e5);t.unref&&t.unref()}function l(e){this.strategy=new h,this.conditionals=e}function d(){this.cache={}}function p(e){if(!e)return!1;if(!e.blockHash)return!1;var t;return(t=e.blockHash,new o(i.toBuffer(t))).gt(new o(0))}t.exports=f,n(f,c),f.prototype.setEngine=function(e){const t=this;function r(e){var r=t.currentBlock;t.currentBlock=e,r&&(t.strategies.block.cacheRollOff(r),t.strategies.fork.cacheRollOff(r))}t.engine=e,e.once("block",function(n){t.currentBlock=n,t._ready.go(),e.on("block",r)})},f.prototype.handleRequest=function(e,t,r){const n=this;return e.skipCache?t():"eth_getBlockByNumber"===e.method&&"latest"===e.params[0]?t():void n._ready.await(function(){n._handleRequest(e,t,r)})},f.prototype._handleRequest=function(e,t,r){const n=this;var o=s.cacheTypeForPayload(e),a=this.strategies[o];if(!a)return t();if(!a.canCache(e))return t();var u,c=s.blockTagForPayload(e);c||(c="latest"),u="earliest"===c?"0x00":"latest"===c?i.bufferToHex(n.currentBlock.number):c,a.hitCheck(e,u,r,function(){t(function(t,r,n){if(t)return n();a.cacheResult(e,r,u,n)})})},h.prototype.hitCheck=function(e,t,r,n){var i,o,u,c,f=s.cacheIdentifierForPayload(e),h=this.cache[f];return h&&(i=t,o=h.blockNumber,u=parseInt(i,16),c=parseInt(o,16),(u===c?0:u>c?1:-1)>=0)?r(null,a(h.result)):n()},h.prototype.cacheResult=function(e,t,r,n){var i=s.cacheIdentifierForPayload(e);if(t){var o=a(t);this.cache[i]={blockNumber:r,result:o}}n()},h.prototype.canCache=function(e){return s.canCache(e)},l.prototype.hitCheck=function(e,t,r,n){return this.strategy.hitCheck(e,t,r,n)},l.prototype.cacheResult=function(e,t,r,n){var i=this.conditionals[e.method];i?i(t)?this.strategy.cacheResult(e,t,r,n):n():this.strategy.cacheResult(e,t,r,n)},l.prototype.canCache=function(e){return this.strategy.canCache(e)},d.prototype.getBlockCacheForPayload=function(e,t){const r=Number.parseInt(t,16);let n=this.cache[r];if(!n){const e={};this.cache[r]=e,n=e}return n},d.prototype.hitCheck=function(e,t,r,n){var i=this.getBlockCacheForPayload(e,t);if(!i)return n();var o=i[s.cacheIdentifierForPayload(e)];return o?r(null,o):n()},d.prototype.cacheResult=function(e,t,r,n){t&&(this.getBlockCacheForPayload(e,r)[s.cacheIdentifierForPayload(e)]=t);n()},d.prototype.canCache=function(e){return!!s.canCache(e)&&"pending"!==s.blockTagForPayload(e)},d.prototype.cacheRollOff=function(e){const t=this,r=i.bufferToHex(e.number),n=Number.parseInt(r,16);Object.keys(t.cache).map(Number).filter(e=>e<=n).forEach(e=>delete t.cache[e])}},{"../util/rpc-cache-utils.js":394,"../util/stoplight.js":396,"./subprovider.js":387,clone:87,"ethereumjs-util":141,util:333}],377:[function(e,t,r){const n=e("util").inherits,i=e("xtend"),o=e("./fixture.js"),a=e("../package.json").version;function s(e){var t=i({web3_clientVersion:"ProviderEngine/v"+a+"/javascript",net_listening:!0,eth_hashrate:"0x00",eth_mining:!1},e=e||{});o.call(this,t)}t.exports=s,n(s,o)},{"../package.json":375,"./fixture.js":380,util:333,xtend:423}],378:[function(e,t,r){const n=e("cross-fetch"),i=e("util").inherits,o=e("async/retry"),a=e("async/waterfall"),s=e("async/asyncify"),u=e("json-rpc-error"),c=e("promise-to-callback"),f=e("../util/create-payload.js"),h=e("./subprovider.js"),l=["Gateway timeout","ETIMEDOUT","SyntaxError"];function d(e){this.rpcUrl=e.rpcUrl,this.originHttpHeaderKey=e.originHttpHeaderKey}function p(e){const t=e.toString();return l.some(e=>t.includes(e))}t.exports=d,i(d,h),d.prototype.handleRequest=function(e,t,r){const n=this,i=e.origin,a=f(e);delete a.origin;const s={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(a)};n.originHttpHeaderKey&&i&&(s.headers[n.originHttpHeaderKey]=i),o({times:5,interval:1e3,errorFilter:p},e=>n._submitRequest(s,e),(e,t)=>{if(e&&p(e)){const t=`FetchSubprovider - cannot complete request. All retries exhausted.\nOriginal Error:\n${e.toString()}\n\n`,n=new Error(t);return r(n)}return r(e,t)})},d.prototype._submitRequest=function(e,t){const r=this.rpcUrl;c(n(r,e))((e,r)=>{if(e)return t(e);a([function(e){switch(r.status){case 405:return e(new u.MethodNotFound);case 418:return e(function(){const e=new Error("Request is being rate limited.");return new u.InternalError(e)}());case 503:case 504:return e(function(){let e="Gateway timeout. The request took too long to process. ";const t=new Error(e+="This can happen when querying logs over too wide a block range.");return new u.InternalError(t)}());default:return e()}},e=>c(r.text())(e),s(e=>JSON.parse(e)),function(e,t){if(200!==r.status)return t(new u.InternalError(e));if(e.error)return t(new u.InternalError(e.error));t(null,e.result)}],t)})}},{"../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(e,t,r){const n=e("async"),i=e("util").inherits,o=e("ethereumjs-util"),a=e("./subprovider.js"),s=e("../util/stoplight.js"),u=e("events").EventEmitter;function c(e){e=e||{};const t=this;t.filterIndex=0,t.filters={},t.filterDestroyHandlers={},t.asyncBlockHandlers={},t.asyncPendingBlockHandlers={},t._ready=new s,t._ready.setMaxListeners(e.maxFilters||25),t._ready.go(),t.pendingBlockTimeout=e.pendingBlockTimeout||4e3,t.checkForPendingBlocksActive=!1,setTimeout(function(){t.engine.on("block",function(e){t._ready.stop();var r=v(t.asyncBlockHandlers).map(function(t){return t.bind(null,e)});n.parallel(r,function(e){e&&console.error(e),t._ready.go()})})})}function f(e){u.apply(this),this.type="block",this.engine=e.engine,this.blockNumber=e.blockNumber,this.updates=[]}function h(e){u.apply(this),this.type="log",this.fromBlock=void 0!==e.fromBlock?e.fromBlock:"latest",this.toBlock=void 0!==e.toBlock?e.toBlock:"latest";var t=e.address&&(Array.isArray(e.address)?e.address:[e.address]);this.address=t&&t.map(d),this.topics=e.topics||[],this.updates=[],this.allResults=[]}function l(){u.apply(this),this.type="pendingTx",this.updates=[],this.allResults=[]}function d(e){return"0x"===e.slice(0,2)?e:"0x"+e}function p(e){return o.intToHex(e)}function b(e){return Number(e)}function y(e){return function(e){let t=o.stripHexPrefix(e);for(;"0"===t[0];)t=t.substr(1);return`0x${t}`}(e.toString("hex"))}function m(e){return e&&-1===["earliest","latest","pending"].indexOf(e)}function v(e){return Object.keys(e).map(function(t){return e[t]})}t.exports=c,i(c,a),c.prototype.handleRequest=function(e,t,r){const n=this;switch(e.method){case"eth_newBlockFilter":return void n.newBlockFilter(r);case"eth_newPendingTransactionFilter":return n.newPendingTransactionFilter(r),void n.checkForPendingBlocks();case"eth_newFilter":return void n.newLogFilter(e.params[0],r);case"eth_getFilterChanges":return void n._ready.await(function(){n.getFilterChanges(e.params[0],r)});case"eth_getFilterLogs":return void n._ready.await(function(){n.getFilterLogs(e.params[0],r)});case"eth_uninstallFilter":return void n._ready.await(function(){n.uninstallFilter(e.params[0],r)});default:return void t()}},c.prototype.newBlockFilter=function(e){const t=this;t._getBlockNumber(function(r,n){if(r)return e(r);var i=new f({blockNumber:n}),o=i.update.bind(i);t.engine.on("block",o);t.filterIndex++,t.filters[t.filterIndex]=i,t.filterDestroyHandlers[t.filterIndex]=function(){t.engine.removeListener("block",o)};var a=p(t.filterIndex);e(null,a)})},c.prototype.newLogFilter=function(e,t){const r=this;r._getBlockNumber(function(n,i){if(n)return t(n);var o=new h(e),a=o.update.bind(o);r.filterIndex++,r.asyncBlockHandlers[r.filterIndex]=function(e,t){r._logsForBlock(e,function(e,r){if(e)return t(e);a(r),t()})},r.filters[r.filterIndex]=o;var s=p(r.filterIndex);t(null,s)})},c.prototype.newPendingTransactionFilter=function(e){const t=this;var r=new l,n=r.update.bind(r);t.filterIndex++,t.asyncPendingBlockHandlers[t.filterIndex]=function(e,r){t._txHashesForBlock(e,function(e,t){if(e)return r(e);n(t),r()})},t.filters[t.filterIndex]=r,e(null,p(t.filterIndex))},c.prototype.getFilterChanges=function(e,t){var r=Number.parseInt(e,16),n=this.filters[r];if(n||console.warn("FilterSubprovider - no filter with that id:",e),!n)return t(null,[]);var i=n.getChanges();n.clearChanges(),t(null,i)},c.prototype.getFilterLogs=function(e,t){const r=this;var n=Number.parseInt(e,16),i=r.filters[n];if(i||console.warn("FilterSubprovider - no filter with that id:",e),!i)return t(null,[]);if("log"===i.type)r.emitPayload({method:"eth_getLogs",params:[{fromBlock:i.fromBlock,toBlock:i.toBlock,address:i.address,topics:i.topics}]},function(e,r){if(e)return t(e);t(null,r.result)});else{t(null,[])}},c.prototype.uninstallFilter=function(e,t){var r=Number.parseInt(e,16);if(this.filters[r]){this.filters[r].removeAllListeners();var n=this.filterDestroyHandlers[r];delete this.filters[r],delete this.asyncBlockHandlers[r],delete this.asyncPendingBlockHandlers[r],delete this.filterDestroyHandlers[r],n&&n(),t(null,!0)}else t(null,!1)},c.prototype.checkForPendingBlocks=function(){const e=this;e.checkForPendingBlocksActive||!!Object.keys(e.asyncPendingBlockHandlers).length&&(e.checkForPendingBlocksActive=!0,e.emitPayload({method:"eth_getBlockByNumber",params:["pending",!0]},function(t,r){if(t)return e.checkForPendingBlocksActive=!1,void console.error(t);e.onNewPendingBlock(r.result,function(t){t&&console.error(t),e.checkForPendingBlocksActive=!1,setTimeout(e.checkForPendingBlocks.bind(e),e.pendingBlockTimeout)})}))},c.prototype.onNewPendingBlock=function(e,t){var r=v(this.asyncPendingBlockHandlers).map(function(t){return t.bind(null,e)});n.parallel(r,t)},c.prototype._getBlockNumber=function(e){e(null,y(this.engine.currentBlock.number))},c.prototype._logsForBlock=function(e,t){var r=y(e.number);this.emitPayload({method:"eth_getLogs",params:[{fromBlock:r,toBlock:r}]},function(e,r){return e?t(e):r.error?t(r.error):void t(null,r.result)})},c.prototype._txHashesForBlock=function(e,t){var r=e.transactions;if(0===r.length)return t(null,[]);"string"==typeof r[0]?t(null,r):t(null,r.map(e=>e.hash))},i(f,u),f.prototype.update=function(e){var t="0x"+e.hash.toString("hex");this.updates.push(t),this.emit("data",e)},f.prototype.getChanges=function(){return this.updates},f.prototype.clearChanges=function(){this.updates=[]},i(h,u),h.prototype.validateLog=function(e){return!(m(this.fromBlock)&&b(this.fromBlock)>=b(e.blockNumber))&&(!(m(this.toBlock)&&b(this.toBlock)<=b(e.blockNumber))&&(!(this.address&&!this.address.map(e=>e.toLowerCase()).includes(e.address.toLowerCase()))&&this.topics.reduce(function(t,r,n){if(!t)return!1;if(!r)return!0;var i=e.topics[n];return!!i&&(Array.isArray(r)?r:[r]).filter(function(e){return i.toLowerCase()===e.toLowerCase()}).length>0},!0)))},h.prototype.update=function(e){const t=this;var r=[];e.forEach(function(e){t.validateLog(e)&&(r.push(e),t.updates.push(e),t.allResults.push(e))}),r.length>0&&t.emit("data",r)},h.prototype.getChanges=function(){return this.updates},h.prototype.getAllResults=function(){return this.allResults},h.prototype.clearChanges=function(){this.updates=[]},i(l,u),l.prototype.validateUnique=function(e){return-1===this.allResults.indexOf(e)},l.prototype.update=function(e){const t=this;var r=[];e.forEach(function(e){t.validateUnique(e)&&(r.push(e),t.updates.push(e),t.allResults.push(e))}),r.length>0&&t.emit("data",r)},l.prototype.getChanges=function(){return this.updates},l.prototype.getAllResults=function(){return this.allResults},l.prototype.clearChanges=function(){this.updates=[]}},{"../util/stoplight.js":396,"./subprovider.js":387,async:21,"ethereumjs-util":141,events:157,util:333}],380:[function(e,t,r){const n=e("util").inherits,i=e("./subprovider.js");function o(e){e=e||{},this.staticResponses=e}t.exports=o,n(o,i),o.prototype.handleRequest=function(e,t,r){var n=this.staticResponses[e.method];"function"==typeof n?n(e,t,r):void 0!==n?setTimeout(()=>r(null,n)):t()}},{"./subprovider.js":387,util:333}],381:[function(e,t,r){const n=e("async/waterfall"),i=e("async/parallel"),o=e("util").inherits,a=e("ethereumjs-util"),s=e("eth-sig-util"),u=e("xtend"),c=e("semaphore"),f=e("./subprovider.js"),h=e("../util/estimate-gas.js"),l=/^[0-9A-Fa-f]+$/g;function d(e){this.nonceLock=c(1),e.getAccounts&&(this.getAccounts=e.getAccounts),e.processTransaction&&(this.processTransaction=e.processTransaction),e.processMessage&&(this.processMessage=e.processMessage),e.processPersonalMessage&&(this.processPersonalMessage=e.processPersonalMessage),e.processTypedMessage&&(this.processTypedMessage=e.processTypedMessage),this.approveTransaction=e.approveTransaction||this.autoApprove,this.approveMessage=e.approveMessage||this.autoApprove,this.approvePersonalMessage=e.approvePersonalMessage||this.autoApprove,this.approveTypedMessage=e.approveTypedMessage||this.autoApprove,e.signTransaction&&(this.signTransaction=e.signTransaction||y("signTransaction")),e.signMessage&&(this.signMessage=e.signMessage||y("signMessage")),e.signPersonalMessage&&(this.signPersonalMessage=e.signPersonalMessage||y("signPersonalMessage")),e.signTypedMessage&&(this.signTypedMessage=e.signTypedMessage||y("signTypedMessage")),e.recoverPersonalSignature&&(this.recoverPersonalSignature=e.recoverPersonalSignature),e.publishTransaction&&(this.publishTransaction=e.publishTransaction)}function p(e){return e.toLowerCase()}function b(e){return"string"==typeof e&&("0x"===e.slice(0,2)&&e.slice(2).match(l))}function y(e){return function(t,r){r(new Error('ProviderEngine - HookedWalletSubprovider - Must provide "'+e+'" fn in constructor options'))}}t.exports=d,o(d,f),d.prototype.handleRequest=function(e,t,r){const i=this;let o,s,c,f,h;switch(i._parityRequests={},i._parityRequestCount=0,e.method){case"eth_coinbase":return void i.getAccounts(function(e,t){if(e)return r(e);let n=t[0]||null;r(null,n)});case"eth_accounts":return void i.getAccounts(function(e,t){if(e)return r(e);r(null,t)});case"eth_sendTransaction":return o=e.params[0],void n([e=>i.validateTransaction(o,e),e=>i.processTransaction(o,e)],r);case"eth_signTransaction":return o=e.params[0],void n([e=>i.validateTransaction(o,e),e=>i.processSignTransaction(o,e)],r);case"eth_sign":return h=e.params[0],f=e.params[1],c=e.params[2]||{},s=u(c,{from:h,data:f}),void n([e=>i.validateMessage(s,e),e=>i.processMessage(s,e)],r);case"personal_sign":const l=e.params[0];if(function(e){const t=a.addHexPrefix(e);return!a.isValidAddress(t)&&b(e)}(e.params[1])&&function(e){const t=a.addHexPrefix(e);return a.isValidAddress(t)}(l)){let t="The eth_personalSign method requires params ordered ";t+="[message, address]. This was previously handled incorrectly, ",t+="and has been corrected automatically. ",t+="Please switch this param order for smooth behavior in the future.",console.warn(t),h=e.params[0],f=e.params[1]}else f=e.params[0],h=e.params[1];return c=e.params[2]||{},s=u(c,{from:h,data:f}),void n([e=>i.validatePersonalMessage(s,e),e=>i.processPersonalMessage(s,e)],r);case"personal_ecRecover":f=e.params[0];let d=e.params[1];return c=e.params[2]||{},s=u(c,{sig:d,data:f}),void i.recoverPersonalSignature(s,r);case"eth_signTypedData":return f=e.params[0],h=e.params[1],c=e.params[2]||{},s=u(c,{from:h,data:f}),void n([e=>i.validateTypedMessage(s,e),e=>i.processTypedMessage(s,e)],r);case"parity_postTransaction":return o=e.params[0],void i.parityPostTransaction(o,r);case"parity_postSign":return h=e.params[0],f=e.params[1],void i.parityPostSign(h,f,r);case"parity_checkRequest":const p=e.params[0];return void i.parityCheckRequest(p,r);case"parity_defaultAccount":return void i.getAccounts(function(e,t){if(e)return r(e);const n=t[0]||null;r(null,n)});default:return void t()}},d.prototype.getAccounts=function(e){e(null,[])},d.prototype.processTransaction=function(e,t){const r=this;n([t=>r.approveTransaction(e,t),(e,t)=>r.checkApproval("transaction",e,t),t=>r.finalizeAndSubmitTx(e,t)],t)},d.prototype.processSignTransaction=function(e,t){const r=this;n([t=>r.approveTransaction(e,t),(e,t)=>r.checkApproval("transaction",e,t),t=>r.finalizeTx(e,t)],t)},d.prototype.processMessage=function(e,t){const r=this;n([t=>r.approveMessage(e,t),(e,t)=>r.checkApproval("message",e,t),t=>r.signMessage(e,t)],t)},d.prototype.processPersonalMessage=function(e,t){const r=this;n([t=>r.approvePersonalMessage(e,t),(e,t)=>r.checkApproval("message",e,t),t=>r.signPersonalMessage(e,t)],t)},d.prototype.processTypedMessage=function(e,t){const r=this;n([t=>r.approveTypedMessage(e,t),(e,t)=>r.checkApproval("message",e,t),t=>r.signTypedMessage(e,t)],t)},d.prototype.autoApprove=function(e,t){t(null,!0)},d.prototype.checkApproval=function(e,t,r){r(t?null:new Error("User denied "+e+" signature."))},d.prototype.parityPostTransaction=function(e,t){const r=this,n=`0x${r._parityRequestCount.toString(16)}`;r._parityRequestCount++,r.emitPayload({method:"eth_sendTransaction",params:[e]},function(e,t){if(e)return void(r._parityRequests[n]={error:e});const i=t.result;r._parityRequests[n]=i}),t(null,n)},d.prototype.parityPostSign=function(e,t,r){const n=this,i=`0x${n._parityRequestCount.toString(16)}`;n._parityRequestCount++,n.emitPayload({method:"eth_sign",params:[e,t]},function(e,t){if(e)return void(n._parityRequests[i]={error:e});const r=t.result;n._parityRequests[i]=r}),r(null,i)},d.prototype.parityCheckRequest=function(e,t){const r=this._parityRequests[e]||null;return r?r.error?t(r.error):void t(null,r):t(null,null)},d.prototype.recoverPersonalSignature=function(e,t){let r;try{r=s.recoverPersonalSignature(e)}catch(e){return t(e)}t(null,r)},d.prototype.validateTransaction=function(e,t){if(void 0===e.from)return t(new Error("Undefined address - from address required to sign transaction."));this.validateSender(e.from,function(r,n){return r?t(r):n?void t():t(new Error(`Unknown address - unable to sign transaction for this address: "${e.from}"`))})},d.prototype.validateMessage=function(e,t){if(void 0===e.from)return t(new Error("Undefined address - from address required to sign message."));this.validateSender(e.from,function(r,n){return r?t(r):n?void t():t(new Error(`Unknown address - unable to sign message for this address: "${e.from}"`))})},d.prototype.validatePersonalMessage=function(e,t){return void 0===e.from?t(new Error("Undefined address - from address required to sign personal message.")):void 0===e.data?t(new Error("Undefined message - message required to sign personal message.")):b(e.data)?void this.validateSender(e.from,function(r,n){return r?t(r):n?void t():t(new Error(`Unknown address - unable to sign message for this address: "${e.from}"`))}):t(new Error("HookedWalletSubprovider - validateMessage - message was not encoded as hex."))},d.prototype.validateTypedMessage=function(e,t){return void 0===e.from?t(new Error("Undefined address - from address required to sign typed data.")):void 0===e.data?t(new Error("Undefined data - message required to sign typed data.")):void this.validateSender(e.from,function(r,n){return r?t(r):n?void t():t(new Error(`Unknown address - unable to sign message for this address: "${e.from}"`))})},d.prototype.validateSender=function(e,t){if(!e)return t(null,!1);this.getAccounts(function(r,n){if(r)return t(r);const i=-1!==n.map(p).indexOf(e.toLowerCase());t(null,i)})},d.prototype.finalizeAndSubmitTx=function(e,t){const r=this;r.nonceLock.take(function(){n([r.fillInTxExtras.bind(r,e),r.signTransaction.bind(r),r.publishTransaction.bind(r)],function(e,n){if(r.nonceLock.leave(),e)return t(e);t(null,n)})})},d.prototype.finalizeTx=function(e,t){const r=this;r.nonceLock.take(function(){n([r.fillInTxExtras.bind(r,e),r.signTransaction.bind(r)],function(n,i){if(r.nonceLock.leave(),n)return t(n);t(null,{raw:i,tx:e})})})},d.prototype.publishTransaction=function(e,t){this.emitPayload({method:"eth_sendRawTransaction",params:[e]},function(e,r){if(e)return t(e);t(null,r.result)})},d.prototype.fillInTxExtras=function(e,t){const r=this,n=e.from,o={};void 0===e.gasPrice&&(o.gasPrice=r.emitPayload.bind(r,{method:"eth_gasPrice",params:[]})),void 0===e.nonce&&(o.nonce=r.emitPayload.bind(r,{method:"eth_getTransactionCount",params:[n,"pending"]})),void 0===e.gas&&(o.gas=h.bind(null,r.engine,function(e){return{from:e.from,to:e.to,value:e.value,data:e.data,gas:e.gas,gasPrice:e.gasPrice,nonce:e.nonce}}(e))),i(o,function(r,n){if(r)return t(r);const i={};n.gasPrice&&(i.gasPrice=n.gasPrice.result),n.nonce&&(i.nonce=n.nonce.result),n.gas&&(i.gas=n.gas),t(null,u(e,i))})}},{"../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(e,t,r){const n=e("../util/rpc-cache-utils.js").cacheIdentifierForPayload,i=e("./subprovider.js");t.exports=class extends i{constructor(e){super(),this.inflightRequests={}}addEngine(e){this.engine=e}handleRequest(e,t,r){const i=n(e,{includeBlockRef:!0});if(!i)return t();let o=this.inflightRequests[i];o?o.push(r):(o=[],this.inflightRequests[i]=o,t((e,t,r)=>{delete this.inflightRequests[i],o.forEach(r=>r(e,t)),r(e,t)}))}}},{"../util/rpc-cache-utils.js":394,"./subprovider.js":387}],383:[function(e,t,r){const n=e("eth-json-rpc-infura/src/createProvider"),i=e("./provider.js");t.exports=class extends i{constructor(e={}){super(n(e))}}},{"./provider.js":385,"eth-json-rpc-infura/src/createProvider":129}],384:[function(e,t,r){(function(r){const n=e("util").inherits,i=e("ethereumjs-tx"),o=e("ethereumjs-util"),a=e("./subprovider.js"),s=e("../util/rpc-cache-utils").blockTagForPayload;function u(e){this.nonceCache={}}t.exports=u,n(u,a),u.prototype.handleRequest=function(e,t,n){const a=this;switch(e.method){case"eth_getTransactionCount":var u=s(e),c=e.params[0].toLowerCase(),f=a.nonceCache[c];return void("pending"===u?f?n(null,f):t(function(e,t,r){if(e)return r();void 0===a.nonceCache[c]&&(a.nonceCache[c]=t),r()}):t());case"eth_sendRawTransaction":return void t(function(t,n,s){if(t)return s();var u=e.params[0],c=(o.stripHexPrefix(u),new r(o.stripHexPrefix(u),"hex"),new i(new r(o.stripHexPrefix(u),"hex"))),f="0x"+c.getSenderAddress().toString("hex").toLowerCase(),h=o.bufferToInt(c.nonce),l=(++h).toString(16);l.length%2&&(l="0"+l),l="0x"+l,a.nonceCache[f]=l,s()});default:return void t()}}}).call(this,e("buffer").Buffer)},{"../util/rpc-cache-utils":394,"./subprovider.js":387,buffer:84,"ethereumjs-tx":140,"ethereumjs-util":141,util:333}],385:[function(e,t,r){const n=e("util").inherits,i=e("./subprovider.js");function o(e){if(!e)throw new Error("ProviderSubprovider - no provider specified");if(!e.sendAsync)throw new Error("ProviderSubprovider - specified provider does not have a sendAsync method");this.provider=e}t.exports=o,n(o,i),o.prototype.handleRequest=function(e,t,r){this.provider.sendAsync(e,function(e,t){return e?r(e):t.error?r(new Error(t.error.message)):void r(null,t.result)})}},{"./subprovider.js":387,util:333}],386:[function(e,t,r){const n=e("util").inherits,i=e("./subprovider.js"),o=(e("xtend"),e("ethereumjs-util"));function a(e){}t.exports=a,n(a,i),a.prototype.handleRequest=function(e,t,r){var n=e.params[0];if("object"==typeof n&&!Array.isArray(n)){var i=function(e){return s.reduce(function(t,r){return r in e&&(Array.isArray(e[r])?t[r]=e[r].map(function(e){return u(e)}):t[r]=u(e[r])),t},{})}(n);e.params[0]=i}t()};var s=["from","to","value","data","gas","gasPrice","nonce","fromBlock","toBlock","address","topics"];function u(e){switch(e){case"latest":case"pending":case"earliest":return e;default:return"string"==typeof e?o.addHexPrefix(e.toLowerCase()):e}}},{"./subprovider.js":387,"ethereumjs-util":141,util:333,xtend:423}],387:[function(e,t,r){const n=e("../util/create-payload.js");function i(){}t.exports=i,i.prototype.setEngine=function(e){const t=this;t.engine=e,e.on("block",function(e){t.currentBlock=e})},i.prototype.handleRequest=function(e,t,r){throw new Error("Subproviders should override `handleRequest`.")},i.prototype.emitPayload=function(e,t){this.engine.sendAsync(n(e),t)}},{"../util/create-payload.js":391}],388:[function(e,t,r){const n=e("events").EventEmitter,i=e("./filters.js"),o=e("../util/rpc-hex-encoding.js"),a=e("util").inherits,s=e("ethereumjs-util");function u(e){e=e||{},n.apply(this,Array.prototype.slice.call(arguments)),i.apply(this,[e]),this.subscriptions={}}a(u,i),Object.assign(u.prototype,n.prototype),u.prototype.constructor=u,u.prototype.eth_subscribe=function(e,t){const r=this;let n=()=>{},i=e.params[0];switch(i){case"logs":let o=e.params[1];n=r.newLogFilter.bind(r,o);break;case"newPendingTransactions":n=r.newPendingTransactionFilter.bind(r);break;case"newHeads":n=r.newBlockFilter.bind(r);break;case"syncing":default:return void t(new Error("unsupported subscription type"))}n(function(e,n){if(e)return t(e);const o=Number.parseInt(n,16);r.subscriptions[o]=i,r.filters[o].on("data",function(e){Array.isArray(e)||(e=[e]);var t=r._notificationHandler.bind(r,n,i);e.forEach(t),r.filters[o].clearChanges()}),"newPendingTransactions"===i&&r.checkForPendingBlocks(),t(null,n)})},u.prototype.eth_unsubscribe=function(e,t){const r=this;let n=e.params[0];const i=Number.parseInt(n,16);if(r.subscriptions[i]){r.subscriptions[i];r.uninstallFilter(n,function(e,n){delete r.subscriptions[i],t(e,n)})}else t(new Error(`Subscription ID ${n} not found.`))},u.prototype._notificationHandler=function(e,t,r){const n=this;"newHeads"===t&&(r=n._notificationResultFromBlock(r)),n.emit("data",null,{jsonrpc:"2.0",method:"eth_subscription",params:{subscription:e,result:r}})},u.prototype._notificationResultFromBlock=function(e){return{hash:s.bufferToHex(e.hash),parentHash:s.bufferToHex(e.parentHash),sha3Uncles:s.bufferToHex(e.sha3Uncles),miner:s.bufferToHex(e.miner),stateRoot:s.bufferToHex(e.stateRoot),transactionsRoot:s.bufferToHex(e.transactionsRoot),receiptsRoot:s.bufferToHex(e.receiptsRoot),logsBloom:s.bufferToHex(e.logsBloom),difficulty:o.intToQuantityHex(s.bufferToInt(e.difficulty)),number:o.intToQuantityHex(s.bufferToInt(e.number)),gasLimit:o.intToQuantityHex(s.bufferToInt(e.gasLimit)),gasUsed:o.intToQuantityHex(s.bufferToInt(e.gasUsed)),nonce:e.nonce?s.bufferToHex(e.nonce):null,mixHash:s.bufferToHex(e.mixHash),timestamp:o.intToQuantityHex(s.bufferToInt(e.timestamp)),extraData:s.bufferToHex(e.extraData)}},u.prototype.handleRequest=function(e,t,r){switch(e.method){case"eth_subscribe":this.eth_subscribe(e,r);break;case"eth_unsubscribe":this.eth_unsubscribe(e,r);break;default:i.prototype.handleRequest.apply(this,Array.prototype.slice.call(arguments))}},t.exports=u},{"../util/rpc-hex-encoding.js":395,"./filters.js":379,"ethereumjs-util":141,events:157,util:333}],389:[function(e,t,r){(function(r){const n=e("backoff"),i=e("events"),o=(e("util").inherits,r.WebSocket||e("ws")),a=e("./subprovider"),s=e("../util/create-payload");class u extends a{constructor({rpcUrl:e,debug:t,origin:r}){super(),i.call(this),Object.defineProperties(this,{_backoff:{value:n.exponential({randomisationFactor:.2,maxDelay:5e3})},_connectTime:{value:null,writable:!0},_log:{value:t?(...e)=>console.info.apply(console,["[WSProvider]",...e]):()=>{}},_origin:{value:r},_pendingRequests:{value:new Map},_socket:{value:null,writable:!0},_unhandledRequests:{value:[]},_url:{value:e}}),this._handleSocketClose=this._handleSocketClose.bind(this),this._handleSocketMessage=this._handleSocketMessage.bind(this),this._handleSocketOpen=this._handleSocketOpen.bind(this),this._backoff.on("ready",()=>{this._openSocket()}),this._openSocket()}handleRequest(e,t,r){if(!this._socket||this._socket.readyState!==o.OPEN)return this._unhandledRequests.push(Array.from(arguments)),void this._log("Socket not open. Request queued.");this._pendingRequests.set(e.id,[e,r]);const n=s(e);delete n.origin,this._socket.send(JSON.stringify(n)),this._log(`Sent: ${n.method} #${n.id}`)}_handleSocketClose({reason:e,code:t}){this._log(`Socket closed, code ${t} (${e||"no reason"})`),this._connectTime&&Date.now()-this._connectTime>5e3&&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(e){let t;try{t=JSON.parse(e.data)}catch(e){return void this._log("Received a message that is not valid JSON:",t)}if(void 0===t.id)return this.emit("data",null,t);if(!this._pendingRequests.has(t.id))return;const[r,n]=this._pendingRequests.get(t.id);if(this._pendingRequests.delete(t.id),this._log(`Received: ${r.method} #${t.id}`),t.error)return n(new Error(t.error.message));n(null,t.result)}_handleSocketOpen(){this._log("Socket open."),this._connectTime=Date.now(),this._pendingRequests.forEach(([e,t])=>{this._unhandledRequests.push([e,null,t])}),this._pendingRequests.clear(),this._unhandledRequests.splice(0,this._unhandledRequests.length).forEach(e=>{this.handleRequest.apply(this,e)})}_openSocket(){this._log("Opening socket..."),this._socket=new o(this._url,null,{origin:this._origin}),this._socket.addEventListener("close",this._handleSocketClose),this._socket.addEventListener("message",this._handleSocketMessage),this._socket.addEventListener("open",this._handleSocketOpen)}}Object.assign(u.prototype,i.prototype),t.exports=u}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../util/create-payload":391,"./subprovider":387,backoff:45,events:157,util:333,ws:55}],390:[function(e,t,r){t.exports=function(e,t){if(!e)throw t||"Assertion failed"}},{}],391:[function(e,t,r){const n=e("./random-id.js"),i=e("xtend");t.exports=function(e){return i({id:n(),jsonrpc:"2.0",params:[]},e)}},{"./random-id.js":393,xtend:423}],392:[function(e,t,r){const n=e("./create-payload.js");t.exports=function(e,t,r){e.sendAsync(n({method:"eth_estimateGas",params:[t]}),function(e,t){if(e)return"no contract code at given address"===e.message?r(null,"0xcf08"):r(e);r(null,t.result)})}},{"./create-payload.js":391}],393:[function(e,t,r){const n=3;t.exports=function(){var e=(new Date).getTime()*Math.pow(10,n),t=Math.floor(Math.random()*Math.pow(10,n));return e+t}},{}],394:[function(e,t,r){const n=e("json-stable-stringify");function i(e){return"never"!==s(e)}function o(e){var t=a(e);return t>=e.params.length?e.params:"eth_getBlockByNumber"===e.method?e.params.slice(1):e.params.slice(0,t)}function a(e){switch(e.method){case"eth_getStorageAt":return 2;case"eth_getBalance":case"eth_getCode":case"eth_getTransactionCount":case"eth_call":case"eth_estimateGas":return 1;case"eth_getBlockByNumber":return 0;default:return}}function s(e){switch(e.method){case"web3_clientVersion":case"web3_sha3":case"eth_protocolVersion":case"eth_getBlockTransactionCountByHash":case"eth_getUncleCountByBlockHash":case"eth_getCode":case"eth_getBlockByHash":case"eth_getTransactionByHash":case"eth_getTransactionByBlockHashAndIndex":case"eth_getTransactionReceipt":case"eth_getUncleByBlockHashAndIndex":case"eth_getCompilers":case"eth_compileLLL":case"eth_compileSolidity":case"eth_compileSerpent":case"shh_version":return"perma";case"eth_getBlockByNumber":case"eth_getBlockTransactionCountByNumber":case"eth_getUncleCountByBlockNumber":case"eth_getTransactionByBlockNumberAndIndex":case"eth_getUncleByBlockNumberAndIndex":return"fork";case"eth_gasPrice":case"eth_blockNumber":case"eth_getBalance":case"eth_getStorageAt":case"eth_getTransactionCount":case"eth_call":case"eth_estimateGas":case"eth_getFilterLogs":case"eth_getLogs":case"net_peerCount":return"block";case"net_version":case"net_peerCount":case"net_listening":case"eth_syncing":case"eth_sign":case"eth_coinbase":case"eth_mining":case"eth_hashrate":case"eth_accounts":case"eth_sendTransaction":case"eth_sendRawTransaction":case"eth_newFilter":case"eth_newBlockFilter":case"eth_newPendingTransactionFilter":case"eth_uninstallFilter":case"eth_getFilterChanges":case"eth_getWork":case"eth_submitWork":case"eth_submitHashrate":case"db_putString":case"db_getString":case"db_putHex":case"db_getHex":case"shh_post":case"shh_newIdentity":case"shh_hasIdentity":case"shh_newGroup":case"shh_addToGroup":case"shh_newFilter":case"shh_uninstallFilter":case"shh_getFilterChanges":case"shh_getMessages":return"never"}}t.exports={cacheIdentifierForPayload:function(e,t={}){if(!i(e))return null;const{includeBlockRef:r}=t,a=r?e.params:o(e);return e.method+":"+n(a)},canCache:i,blockTagForPayload:function(e){var t=a(e);if(t>=e.params.length)return null;return e.params[t]},paramsWithoutBlockTag:o,blockTagParamIndex:a,cacheTypeForPayload:s}},{"json-stable-stringify":374}],395:[function(e,t,r){(function(r){const n=e("ethereumjs-util"),i=e("./assert.js");t.exports={intToQuantityHex:function(e){i("number"==typeof e&&e===Math.floor(e),"intToQuantityHex arg must be an integer");var t=n.toBuffer(e).toString("hex");"0"===t[0]&&(t=t.substring(1));return n.addHexPrefix(t)},quantityHexToInt:function(e){i("string"==typeof e,"arg to quantityHexToInt must be a string");var t=n.stripHexPrefix(e);t.length%2!=0&&(t="0"+t);var o=new r(t,"hex");return n.bufferToInt(o)}}}).call(this,e("buffer").Buffer)},{"./assert.js":390,buffer:84,"ethereumjs-util":141}],396:[function(e,t,r){const n=e("events").EventEmitter,i=e("util").inherits;function o(){n.call(this),this.isLocked=!0}t.exports=o,i(o,n),o.prototype.go=function(){this.isLocked=!1,this.emit("unlock")},o.prototype.stop=function(){this.isLocked=!0,this.emit("lock")},o.prototype.await=function(e){const t=this;t.isLocked?t.once("unlock",e):setTimeout(e)}},{events:157,util:333}],397:[function(e,t,r){const n=e("./index.js"),i=e("./subproviders/default-fixture.js"),o=e("./subproviders/nonce-tracker.js"),a=e("./subproviders/cache.js"),s=e("./subproviders/filters.js"),u=e("./subproviders/subscriptions"),c=e("./subproviders/inflight-cache"),f=e("./subproviders/hooked-wallet.js"),h=e("./subproviders/sanitizer.js"),l=e("./subproviders/infura.js"),d=e("./subproviders/fetch.js"),p=e("./subproviders/websocket.js");t.exports=function(e={}){const t=function({rpcUrl:e}){if(!e)return;switch(e.split(":")[0].toLowerCase()){case"http":case"https":return"http";case"ws":case"wss":return"ws";default:throw new Error(`ProviderEngine - unrecognized protocol in "${e}"`)}}(e),r=new n(e.engineParams),b=new i(e.static);r.addProvider(b),r.addProvider(new o);const y=new h;r.addProvider(y);const m=new a;if(r.addProvider(m),"ws"===t){const e=new s;r.addProvider(e)}else{const e=new u;e.on("data",(e,t)=>{r.emit("data",e,t)}),r.addProvider(e)}const v=new c;r.addProvider(v);const g=new f({getAccounts:e.getAccounts,processTransaction:e.processTransaction,approveTransaction:e.approveTransaction,signTransaction:e.signTransaction,publishTransaction:e.publishTransaction,processMessage:e.processMessage,approveMessage:e.approveMessage,signMessage:e.signMessage,processPersonalMessage:e.processPersonalMessage,processTypedMessage:e.processTypedMessage,approvePersonalMessage:e.approvePersonalMessage,approveTypedMessage:e.approveTypedMessage,signPersonalMessage:e.signPersonalMessage,signTypedMessage:e.signTypedMessage,personalRecoverSigner:e.personalRecoverSigner});r.addProvider(g);const w=e.dataSubprovider||function(e,t){const{rpcUrl:r,debug:n}=t;if(!e)return new l;if("http"===e)return new d({rpcUrl:r,debug:n});if("ws"===e)return new p({rpcUrl:r,debug:n});throw new Error(`ProviderEngine - unrecognized connectionType "${e}"`)}(t,e);"ws"===t&&w.on("data",(e,t)=>{r.emit("data",e,t)});r.addProvider(w),e.stopped||r.start();return r}},{"./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(e,t,r){var n=e("web3-core-helpers").errors,i=e("xhr2-cookies").XMLHttpRequest,o=e("http"),a=e("https"),s=function(e,t){t=t||{},this.host=e||"http://localhost:8545","https"===this.host.substring(0,5)?this.httpsAgent=new a.Agent({keepAlive:!0}):this.httpAgent=new o.Agent({keepAlive:!0}),this.timeout=t.timeout||0,this.headers=t.headers,this.connected=!1};s.prototype._prepareRequest=function(){var e=new i;return e.nodejsSet({httpsAgent:this.httpsAgent,httpAgent:this.httpAgent}),e.open("POST",this.host,!0),e.setRequestHeader("Content-Type","application/json"),e.timeout=this.timeout&&1!==this.timeout?this.timeout:0,e.withCredentials=!0,this.headers&&this.headers.forEach(function(t){e.setRequestHeader(t.name,t.value)}),e},s.prototype.send=function(e,t){var r=this,i=this._prepareRequest();i.onreadystatechange=function(){if(4===i.readyState&&1!==i.timeout){var e=i.responseText,o=null;try{e=JSON.parse(e)}catch(e){o=n.InvalidResponse(i.responseText)}r.connected=!0,t(o,e)}},i.ontimeout=function(){r.connected=!1,t(n.ConnectionTimeout(this.timeout))};try{i.send(JSON.stringify(e))}catch(e){this.connected=!1,t(n.InvalidConnection(this.host))}},s.prototype.disconnect=function(){},t.exports=s},{http:312,https:175,"web3-core-helpers":338,"xhr2-cookies":418}],399:[function(e,t,r){"use strict";var n=e("underscore"),i=e("web3-core-helpers").errors,o=e("oboe"),a=function(e,t){var r=this;this.responseCallbacks={},this.notificationCallbacks=[],this.path=e,this.connected=!1,this.connection=t.connect({path:this.path}),this.addDefaultEvents();var i=function(e){var t=null;n.isArray(e)?e.forEach(function(e){r.responseCallbacks[e.id]&&(t=e.id)}):t=e.id,t||-1===e.method.indexOf("_subscription")?r.responseCallbacks[t]&&(r.responseCallbacks[t](null,e),delete r.responseCallbacks[t]):r.notificationCallbacks.forEach(function(t){n.isFunction(t)&&t(e)})};"Socket"===t.constructor.name?o(this.connection).done(i):this.connection.on("data",function(e){r._parseResponse(e.toString()).forEach(i)})};a.prototype.addDefaultEvents=function(){var e=this;this.connection.on("connect",function(){e.connected=!0}),this.connection.on("close",function(){e.connected=!1}),this.connection.on("error",function(){e._timeout()}),this.connection.on("end",function(){e._timeout()}),this.connection.on("timeout",function(){e._timeout()})},a.prototype._parseResponse=function(e){var t=this,r=[];return e.replace(/\}[\n\r]?\{/g,"}|--|{").replace(/\}\][\n\r]?\[\{/g,"}]|--|[{").replace(/\}[\n\r]?\[\{/g,"}|--|[{").replace(/\}\][\n\r]?\{/g,"}]|--|{").split("|--|").forEach(function(e){t.lastChunk&&(e=t.lastChunk+e);var n=null;try{n=JSON.parse(e)}catch(r){return t.lastChunk=e,clearTimeout(t.lastChunkTimeout),void(t.lastChunkTimeout=setTimeout(function(){throw t._timeout(),i.InvalidResponse(e)},15e3))}clearTimeout(t.lastChunkTimeout),t.lastChunk=null,n&&r.push(n)}),r},a.prototype._addResponseCallback=function(e,t){var r=e.id||e[0].id,n=e.method||e[0].method;this.responseCallbacks[r]=t,this.responseCallbacks[r].method=n},a.prototype._timeout=function(){for(var e in this.responseCallbacks)this.responseCallbacks.hasOwnProperty(e)&&(this.responseCallbacks[e](i.InvalidConnection("on IPC")),delete this.responseCallbacks[e])},a.prototype.reconnect=function(){this.connection.connect({path:this.path})},a.prototype.send=function(e,t){this.connection.writable||this.connection.connect({path:this.path}),this.connection.write(JSON.stringify(e)),this._addResponseCallback(e,t)},a.prototype.on=function(e,t){if("function"!=typeof t)throw new Error("The second parameter callback must be a function.");switch(e){case"data":this.notificationCallbacks.push(t);break;default:this.connection.on(e,t)}},a.prototype.once=function(e,t){if("function"!=typeof t)throw new Error("The second parameter callback must be a function.");this.connection.once(e,t)},a.prototype.removeListener=function(e,t){var r=this;switch(e){case"data":this.notificationCallbacks.forEach(function(e,n){e===t&&r.notificationCallbacks.splice(n,1)});break;default:this.connection.removeListener(e,t)}},a.prototype.removeAllListeners=function(e){switch(e){case"data":this.notificationCallbacks=[];break;default:this.connection.removeAllListeners(e)}},a.prototype.reset=function(){this._timeout(),this.notificationCallbacks=[],this.connection.removeAllListeners("error"),this.connection.removeAllListeners("end"),this.connection.removeAllListeners("timeout"),this.addDefaultEvents()},t.exports=a},{oboe:239,underscore:325,"web3-core-helpers":338}],400:[function(e,t,r){(function(r){"use strict";var n=e("underscore"),i=e("web3-core-helpers").errors,o=null,a=null,s=null;if("undefined"!=typeof window&&void 0!==window.WebSocket)o=function(e,t){return new window.WebSocket(e,t)},a=btoa,s=function(e){return new URL(e)};else{o=e("websocket").w3cwebsocket,a=function(e){return r(e).toString("base64")};var u=e("url");if(u.URL){var c=u.URL;s=function(e){return new c(e)}}else s=e("url").parse}var f=function(e,t){var r=this;this.responseCallbacks={},this.notificationCallbacks=[],t=t||{},this._customTimeout=t.timeout;var i=s(e),u=t.headers||{},c=t.protocol||void 0;i.username&&i.password&&(u.authorization="Basic "+a(i.username+":"+i.password));var f=t.clientConfig||void 0;i.auth&&(u.authorization="Basic "+a(i.auth)),this.connection=new o(e,c,void 0,u,void 0,f),this.addDefaultEvents(),this.connection.onmessage=function(e){var t="string"==typeof e.data?e.data:"";r._parseResponse(t).forEach(function(e){var t=null;n.isArray(e)?e.forEach(function(e){r.responseCallbacks[e.id]&&(t=e.id)}):t=e.id,!t&&e&&e.method&&-1!==e.method.indexOf("_subscription")?r.notificationCallbacks.forEach(function(t){n.isFunction(t)&&t(e)}):r.responseCallbacks[t]&&(r.responseCallbacks[t](null,e),delete r.responseCallbacks[t])})},Object.defineProperty(this,"connected",{get:function(){return this.connection&&this.connection.readyState===this.connection.OPEN},enumerable:!0})};f.prototype.addDefaultEvents=function(){var e=this;this.connection.onerror=function(){e._timeout()},this.connection.onclose=function(){e._timeout(),e.reset()}},f.prototype._parseResponse=function(e){var t=this,r=[];return e.replace(/\}[\n\r]?\{/g,"}|--|{").replace(/\}\][\n\r]?\[\{/g,"}]|--|[{").replace(/\}[\n\r]?\[\{/g,"}|--|[{").replace(/\}\][\n\r]?\{/g,"}]|--|{").split("|--|").forEach(function(e){t.lastChunk&&(e=t.lastChunk+e);var n=null;try{n=JSON.parse(e)}catch(r){return t.lastChunk=e,clearTimeout(t.lastChunkTimeout),void(t.lastChunkTimeout=setTimeout(function(){throw t._timeout(),i.InvalidResponse(e)},15e3))}clearTimeout(t.lastChunkTimeout),t.lastChunk=null,n&&r.push(n)}),r},f.prototype._addResponseCallback=function(e,t){var r=e.id||e[0].id,n=e.method||e[0].method;this.responseCallbacks[r]=t,this.responseCallbacks[r].method=n;var o=this;this._customTimeout&&setTimeout(function(){o.responseCallbacks[r]&&(o.responseCallbacks[r](i.ConnectionTimeout(o._customTimeout)),delete o.responseCallbacks[r])},this._customTimeout)},f.prototype._timeout=function(){for(var e in this.responseCallbacks)this.responseCallbacks.hasOwnProperty(e)&&(this.responseCallbacks[e](i.InvalidConnection("on WS")),delete this.responseCallbacks[e])},f.prototype.send=function(e,t){var r=this;if(this.connection.readyState!==this.connection.CONNECTING){if(this.connection.readyState!==this.connection.OPEN)return console.error("connection not open on send()"),"function"==typeof this.connection.onerror?this.connection.onerror(new Error("connection not open")):console.error("no error callback"),void t(new Error("connection not open"));this.connection.send(JSON.stringify(e)),this._addResponseCallback(e,t)}else setTimeout(function(){r.send(e,t)},10)},f.prototype.on=function(e,t){if("function"!=typeof t)throw new Error("The second parameter callback must be a function.");switch(e){case"data":this.notificationCallbacks.push(t);break;case"connect":this.connection.onopen=t;break;case"end":this.connection.onclose=t;break;case"error":this.connection.onerror=t}},f.prototype.removeListener=function(e,t){var r=this;switch(e){case"data":this.notificationCallbacks.forEach(function(e,n){e===t&&r.notificationCallbacks.splice(n,1)})}},f.prototype.removeAllListeners=function(e){switch(e){case"data":this.notificationCallbacks=[];break;case"connect":this.connection.onopen=null;break;case"end":this.connection.onclose=null;break;case"error":this.connection.onerror=null}},f.prototype.reset=function(){this._timeout(),this.notificationCallbacks=[],this.addDefaultEvents()},f.prototype.disconnect=function(){this.connection&&this.connection.close()},t.exports=f}).call(this,e("buffer").Buffer)},{buffer:84,underscore:325,url:327,"web3-core-helpers":338,websocket:408}],401:[function(e,t,r){"use strict";var n=e("web3-core"),i=e("web3-core-subscriptions").subscriptions,o=e("web3-core-method"),a=e("web3-net"),s=function(){var e=this;n.packageInit(this,arguments);var t=this.setProvider;this.setProvider=function(){t.apply(e,arguments),e.net.setProvider.apply(e,arguments)},this.clearSubscriptions=e._requestManager.clearSubscriptions,this.net=new a(this.currentProvider),[new i({name:"subscribe",type:"shh",subscriptions:{messages:{params:1}}}),new o({name:"getVersion",call:"shh_version",params:0}),new o({name:"getInfo",call:"shh_info",params:0}),new o({name:"setMaxMessageSize",call:"shh_setMaxMessageSize",params:1}),new o({name:"setMinPoW",call:"shh_setMinPoW",params:1}),new o({name:"markTrustedPeer",call:"shh_markTrustedPeer",params:1}),new o({name:"newKeyPair",call:"shh_newKeyPair",params:0}),new o({name:"addPrivateKey",call:"shh_addPrivateKey",params:1}),new o({name:"deleteKeyPair",call:"shh_deleteKeyPair",params:1}),new o({name:"hasKeyPair",call:"shh_hasKeyPair",params:1}),new o({name:"getPublicKey",call:"shh_getPublicKey",params:1}),new o({name:"getPrivateKey",call:"shh_getPrivateKey",params:1}),new o({name:"newSymKey",call:"shh_newSymKey",params:0}),new o({name:"addSymKey",call:"shh_addSymKey",params:1}),new o({name:"generateSymKeyFromPassword",call:"shh_generateSymKeyFromPassword",params:1}),new o({name:"hasSymKey",call:"shh_hasSymKey",params:1}),new o({name:"getSymKey",call:"shh_getSymKey",params:1}),new o({name:"deleteSymKey",call:"shh_deleteSymKey",params:1}),new o({name:"newMessageFilter",call:"shh_newMessageFilter",params:1}),new o({name:"getFilterMessages",call:"shh_getFilterMessages",params:1}),new o({name:"deleteMessageFilter",call:"shh_deleteMessageFilter",params:1}),new o({name:"post",call:"shh_post",params:1,inputFormatter:[null]}),new o({name:"unsubscribe",call:"shh_unsubscribe",params:1})].forEach(function(t){t.attachToObject(e),t.setRequestManager(e._requestManager)})};n.addProviders(s),t.exports=s},{"web3-core":348,"web3-core-method":339,"web3-core-subscriptions":345,"web3-net":372}],402:[function(e,t,r){arguments[4][154][0].apply(r,arguments)},{dup:154}],403:[function(e,t,r){var n=e("underscore"),i=e("ethjs-unit"),o=e("./utils.js"),a=e("./soliditySha3.js"),s=e("randomhex"),u=function(e,t){var r=[];return t.forEach(function(t){if("object"==typeof t.components){if("tuple"!==t.type.substring(0,5))throw new Error("components found but type is not tuple; report on GitHub");var i="",o=t.type.indexOf("[");o>=0&&(i=t.type.substring(o));var a=u(e,t.components);n.isArray(a)&&e?r.push("tuple("+a.join(",")+")"+i):e?r.push("("+a+")"):r.push("("+a.join(",")+")"+i)}else r.push(t.type)}),r},c=function(e){if(!o.isHexStrict(e))throw new Error("The parameter must be a valid HEX string.");var t="",r=0,n=e.length;for("0x"===e.substring(0,2)&&(r=2);r7?r+=e[n].toUpperCase():r+=e[n];return r},toHex:o.toHex,toBN:o.toBN,bytesToHex:o.bytesToHex,hexToBytes:o.hexToBytes,hexToNumberString:o.hexToNumberString,hexToNumber:o.hexToNumber,toDecimal:o.hexToNumber,numberToHex:o.numberToHex,fromDecimal:o.numberToHex,hexToUtf8:o.hexToUtf8,hexToString:o.hexToUtf8,toUtf8:o.hexToUtf8,utf8ToHex:o.utf8ToHex,stringToHex:o.utf8ToHex,fromUtf8:o.utf8ToHex,hexToAscii:c,toAscii:c,asciiToHex:f,fromAscii:f,unitMap:i.unitMap,toWei:function(e,t){if(t=h(t),!o.isBN(e)&&!n.isString(e))throw new Error("Please pass numbers as strings or BigNumber objects to avoid precision errors.");return o.isBN(e)?i.toWei(e,t):i.toWei(e,t).toString(10)},fromWei:function(e,t){if(t=h(t),!o.isBN(e)&&!n.isString(e))throw new Error("Please pass numbers as strings or BigNumber objects to avoid precision errors.");return o.isBN(e)?i.fromWei(e,t):i.fromWei(e,t).toString(10)},padLeft:o.leftPad,leftPad:o.leftPad,padRight:o.rightPad,rightPad:o.rightPad,toTwosComplement:o.toTwosComplement}},{"./soliditySha3.js":404,"./utils.js":405,"ethjs-unit":153,randomhex:274,underscore:325}],404:[function(e,t,r){var n=e("underscore"),i=e("bn.js"),o=e("./utils.js"),a=function(e){var t=typeof e;if("string"===t)return o.isHexStrict(e)?new i(e.replace(/0x/i,""),16):new i(e,10);if("number"===t)return new i(e);if(o.isBigNumber(e))return new i(e.toString(10));if(o.isBN(e))return e;throw new Error(e+" is not a number")},s=function(e,t,r){var n,s,u;if("bytes"===(e=(u=e).startsWith("int[")?"int256"+u.slice(3):"int"===u?"int256":u.startsWith("uint[")?"uint256"+u.slice(4):"uint"===u?"uint256":u.startsWith("fixed[")?"fixed128x128"+u.slice(5):"fixed"===u?"fixed128x128":u.startsWith("ufixed[")?"ufixed128x128"+u.slice(6):"ufixed"===u?"ufixed128x128":u)){if(t.replace(/^0x/i,"").length%2!=0)throw new Error("Invalid bytes characters "+t.length);return t}if("string"===e)return o.utf8ToHex(t);if("bool"===e)return t?"01":"00";if(e.startsWith("address")){if(n=r?64:40,!o.isAddress(t))throw new Error(t+" is not a valid address, or the checksum is invalid.");return o.leftPad(t.toLowerCase(),n)}if(n=function(e){var t=/^\D+(\d+).*$/.exec(e);return t?parseInt(t[1],10):null}(e),e.startsWith("bytes")){if(!n)throw new Error("bytes[] not yet supported in solidity");if(r&&(n=32),n<1||n>32||n256)throw new Error("Invalid uint"+n+" size");if((s=a(t)).bitLength()>n)throw new Error("Supplied uint exceeds width: "+n+" vs "+s.bitLength());if(s.lt(new i(0)))throw new Error("Supplied uint "+s.toString()+" is negative");return n?o.leftPad(s.toString("hex"),n/8*2):s}if(e.startsWith("int")){if(n%8||n<8||n>256)throw new Error("Invalid int"+n+" size");if((s=a(t)).bitLength()>n)throw new Error("Supplied int exceeds width: "+n+" vs "+s.bitLength());return s.lt(new i(0))?s.toTwos(n).toString("hex"):n?o.leftPad(s.toString("hex"),n/8*2):s}throw new Error("Unsupported or invalid type: "+e)},u=function(e){if(n.isArray(e))throw new Error("Autodetection of array types is not supported.");var t,r,a="";if(n.isObject(e)&&(e.hasOwnProperty("v")||e.hasOwnProperty("t")||e.hasOwnProperty("value")||e.hasOwnProperty("type"))?(t=e.hasOwnProperty("t")?e.t:e.type,a=e.hasOwnProperty("v")?e.v:e.value):(t=o.toHex(e,!0),a=o.toHex(e),t.startsWith("int")||t.startsWith("uint")||(t="bytes")),!t.startsWith("int")&&!t.startsWith("uint")||"string"!=typeof a||/^(-)?0x/i.test(a)||(a=new i(a)),n.isArray(a)){if((r=function(e){var t=/^\D+\d*\[(\d+)\]$/.exec(e);return t?parseInt(t[1],10):null}(t))&&a.length!==r)throw new Error(t+" is not matching the given array "+JSON.stringify(a));r=a.length}return n.isArray(a)?a.map(function(e){return s(t,e,r).toString("hex").replace("0x","")}).join(""):s(t,a,r).toString("hex").replace("0x","")};t.exports=function(){var e=Array.prototype.slice.call(arguments),t=n.map(e,u);return o.sha3("0x"+t.join(""))}},{"./utils.js":405,"bn.js":402,underscore:325}],405:[function(e,t,r){var n=e("underscore"),i=e("bn.js"),o=e("number-to-bn"),a=e("utf8"),s=e("eth-lib/lib/hash"),u=function(e){return e instanceof i||e&&e.constructor&&"BN"===e.constructor.name},c=function(e){return e&&e.constructor&&"BigNumber"===e.constructor.name},f=function(e){try{return o.apply(null,arguments)}catch(t){throw new Error(t+' Given value: "'+e+'"')}},h=function(e){return!!/^(0x)?[0-9a-f]{40}$/i.test(e)&&(!(!/^(0x|0X)?[0-9a-f]{40}$/.test(e)&&!/^(0x|0X)?[0-9A-F]{40}$/.test(e))||l(e))},l=function(e){e=e.replace(/^0x/i,"");for(var t=m(e.toLowerCase()).replace(/^0x/i,""),r=0;r<40;r++)if(parseInt(t[r],16)>7&&e[r].toUpperCase()!==e[r]||parseInt(t[r],16)<=7&&e[r].toLowerCase()!==e[r])return!1;return!0},d=function(e){var t="";e=(e=(e=(e=(e=a.encode(e)).replace(/^(?:\u0000)*/,"")).split("").reverse().join("")).replace(/^(?:\u0000)*/,"")).split("").reverse().join("");for(var r=0;r>>4).toString(16)),t.push((15&e[r]).toString(16));return"0x"+t.join("")},isHex:function(e){return(n.isString(e)||n.isNumber(e))&&/^(-0x|0x)?[0-9a-f]*$/i.test(e)},isHexStrict:y,leftPad:function(e,t,r){var n=/^0x/i.test(e)||"number"==typeof e,i=t-(e=e.toString(16).replace(/^0x/i,"")).length+1>=0?t-e.length+1:0;return(n?"0x":"")+new Array(i).join(r||"0")+e},rightPad:function(e,t,r){var n=/^0x/i.test(e)||"number"==typeof e,i=t-(e=e.toString(16).replace(/^0x/i,"")).length+1>=0?t-e.length+1:0;return(n?"0x":"")+e+new Array(i).join(r||"0")},toTwosComplement:function(e){return"0x"+f(e).toTwos(256).toString(16,64)},sha3:m}},{"bn.js":402,"eth-lib/lib/hash":134,"number-to-bn":237,underscore:325,utf8:329}],406:[function(e,t,r){t.exports={_from:"web3@1.0.0-beta.36",_id:"web3@1.0.0-beta.36",_inBundle:!1,_integrity:"sha512-fZDunw1V0AQS27r5pUN3eOVP7u8YAvyo6vOapdgVRolAu5LgaweP7jncYyLINqIX9ZgWdS5A090bt+ymgaYHsw==",_location:"/web3",_phantomChildren:{},_requested:{type:"version",registry:!0,raw:"web3@1.0.0-beta.36",name:"web3",escapedName:"web3",rawSpec:"1.0.0-beta.36",saveSpec:null,fetchSpec:"1.0.0-beta.36"},_requiredBy:["#USER","/"],_resolved:"https://registry.npmjs.org/web3/-/web3-1.0.0-beta.36.tgz",_shasum:"2954da9e431124c88396025510d840ba731c8373",_spec:"web3@1.0.0-beta.36",_where:"/Users/alexvlasov/Blockchain/web3swift/web3swiftJSProxy",author:{name:"ethereum.org"},authors:[{name:"Fabian Vogelsteller",email:"fabian@ethereum.org",homepage:"http://frozeman.de"},{name:"Marek Kotewicz",email:"marek@parity.io",url:"https://github.com/debris"},{name:"Marian Oancea",url:"https://github.com/cubedro"},{name:"Gav Wood",email:"g@parity.io",homepage:"http://gavwood.com"},{name:"Jeffery Wilcke",email:"jeffrey.wilcke@ethereum.org",url:"https://github.com/obscuren"}],bugs:{url:"https://github.com/ethereum/web3.js/issues"},bundleDependencies:!1,dependencies:{"web3-bzz":"1.0.0-beta.36","web3-core":"1.0.0-beta.36","web3-eth":"1.0.0-beta.36","web3-eth-personal":"1.0.0-beta.36","web3-net":"1.0.0-beta.36","web3-shh":"1.0.0-beta.36","web3-utils":"1.0.0-beta.36"},deprecated:!1,description:"Ethereum JavaScript API",keywords:["Ethereum","JavaScript","API"],license:"LGPL-3.0",main:"src/index.js",name:"web3",namespace:"ethereum",repository:{type:"git",url:"https://github.com/ethereum/web3.js/tree/master/packages/web3"},version:"1.0.0-beta.36"}},{}],407:[function(e,t,r){"use strict";var n=e("../package.json").version,i=e("web3-core"),o=e("web3-eth"),a=e("web3-net"),s=e("web3-eth-personal"),u=e("web3-shh"),c=e("web3-bzz"),f=e("web3-utils"),h=function(){var e=this;i.packageInit(this,arguments),this.version=n,this.utils=f,this.eth=new o(this),this.shh=new u(this),this.bzz=new c(this);var t=this.setProvider;this.setProvider=function(r,n){return t.apply(e,arguments),this.eth.setProvider(r,n),this.shh.setProvider(r,n),this.bzz.setProvider(r),!0}};h.version=n,h.utils=f,h.modules={Eth:o,Net:a,Personal:s,Shh:u,Bzz:c},i.addProviders(h),t.exports=h},{"../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(e,t,r){var n=function(){return this||{}}(),i=n.WebSocket||n.MozWebSocket,o=e("./version");function a(e,t){return t?new i(e,t):new i(e)}i&&["CONNECTING","OPEN","CLOSING","CLOSED"].forEach(function(e){Object.defineProperty(a,e,{get:function(){return i[e]}})}),t.exports={w3cwebsocket:i?a:null,version:o}},{"./version":409}],409:[function(e,t,r){t.exports=e("../package.json").version},{"../package.json":410}],410:[function(e,t,r){t.exports={_from:"git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible",_id:"websocket@1.0.26",_inBundle:!1,_integrity:"",_location:"/websocket",_phantomChildren:{},_requested:{type:"git",raw:"websocket@git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible",name:"websocket",escapedName:"websocket",rawSpec:"git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible",saveSpec:"git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible",fetchSpec:"git://github.com/frozeman/WebSocket-Node.git",gitCommittish:"browserifyCompatible"},_requiredBy:["/web3-providers-ws"],_resolved:"git://github.com/frozeman/WebSocket-Node.git#6c72925e3f8aaaea8dc8450f97627e85263999f2",_spec:"websocket@git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible",_where:"/Users/alexvlasov/Blockchain/web3swift/web3swiftJSProxy/node_modules/web3-providers-ws",author:{name:"Brian McKelvey",email:"brian@worlize.com",url:"https://www.worlize.com/"},browser:"lib/browser.js",bugs:{url:"https://github.com/theturtle32/WebSocket-Node/issues"},bundleDependencies:!1,config:{verbose:!1},contributors:[{name:"Iñaki Baz Castillo",email:"ibc@aliax.net",url:"http://dev.sipdoc.net"}],dependencies:{debug:"^2.2.0",nan:"^2.3.3","typedarray-to-buffer":"^3.1.2",yaeti:"^0.0.6"},deprecated:!1,description:"Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.",devDependencies:{"buffer-equal":"^1.0.0",faucet:"^0.0.1",gulp:"git+https://github.com/gulpjs/gulp.git#4.0","gulp-jshint":"^2.0.4",jshint:"^2.0.0","jshint-stylish":"^2.2.1",tape:"^4.0.1"},directories:{lib:"./lib"},engines:{node:">=0.10.0"},homepage:"https://github.com/theturtle32/WebSocket-Node",keywords:["websocket","websockets","socket","networking","comet","push","RFC-6455","realtime","server","client"],license:"Apache-2.0",main:"index",name:"websocket",repository:{type:"git",url:"git+https://github.com/theturtle32/WebSocket-Node.git"},scripts:{gulp:"gulp",install:"(node-gyp rebuild 2> builderror.log) || (exit 0)",test:"faucet test/unit"},version:"1.0.26"}},{}],411:[function(e,t,r){var n=e("xhr-request");t.exports=function(e,t){return new Promise(function(r,i){n(e,t,function(e,t){e?i(e):r(t)})})}},{"xhr-request":412}],412:[function(e,t,r){var n=e("query-string"),i=e("url-set-query"),o=e("object-assign"),a=e("./lib/ensure-header.js"),s=e("./lib/request.js"),u="application/json",c=function(){};t.exports=function(e,t,r){if(!e||"string"!=typeof e)throw new TypeError("must specify a URL");"function"==typeof t&&(r=t,t={});if(r&&"function"!=typeof r)throw new TypeError("expected cb to be undefined or a function");r=r||c;var f=(t=t||{}).json?"json":"text",h=(t=o({responseType:f},t)).headers||{},l=(t.method||"GET").toUpperCase(),d=t.query;d&&("string"!=typeof d&&(d=n.stringify(d)),e=i(e,d));"json"===t.responseType&&a(h,"Accept",u);t.json&&"GET"!==l&&"HEAD"!==l&&(a(h,"Content-Type",u),t.body=JSON.stringify(t.body));return t.method=l,t.url=e,t.headers=h,delete t.query,delete t.json,s(t,r)}},{"./lib/ensure-header.js":413,"./lib/request.js":415,"object-assign":238,"query-string":266,"url-set-query":326}],413:[function(e,t,r){t.exports=function(e,t,r){var n=t.toLowerCase();e[t]||e[n]||(e[t]=r)}},{}],414:[function(e,t,r){t.exports=function(e,t){return t?{statusCode:t.statusCode,headers:t.headers,method:e.method,url:e.url,rawRequest:t.rawRequest?t.rawRequest:t}:null}},{}],415:[function(e,t,r){var n=e("xhr"),i=e("./normalize-response"),o=function(){};t.exports=function(e,t){delete e.uri;var r=!1;"json"===e.responseType&&(e.responseType="text",r=!0);var a=n(e,function(n,a,s){if(r&&!n)try{var u=a.rawRequest.responseText;s=JSON.parse(u)}catch(e){n=e}a=i(e,a),t(n,n?null:s,a),t=o}),s=a.onabort;return a.onabort=function(){var e=s.apply(a,Array.prototype.slice.call(arguments));return t(new Error("XHR Aborted")),t=o,e},a}},{"./normalize-response":414,xhr:416}],416:[function(e,t,r){"use strict";var n=e("global/window"),i=e("is-function"),o=e("parse-headers"),a=e("xtend");function s(e,t,r){var n=e;return i(t)?(r=t,"string"==typeof e&&(n={uri:e})):n=a(t,{uri:e}),n.callback=r,n}function u(e,t,r){return c(t=s(e,t,r))}function c(e){if(void 0===e.callback)throw new Error("callback argument missing");var t=!1,r=function(r,n,i){t||(t=!0,e.callback(r,n,i))};function n(e){return clearTimeout(f),e instanceof Error||(e=new Error(""+(e||"Unknown XMLHttpRequest Error"))),e.statusCode=0,r(e,m)}function i(){if(!s){var t;clearTimeout(f),t=e.useXDR&&void 0===c.status?200:1223===c.status?204:c.status;var n=m,i=null;return 0!==t?(n={body:function(){var e=void 0;if(e=c.response?c.response:c.responseText||function(e){try{if("document"===e.responseType)return e.responseXML;var t=e.responseXML&&"parsererror"===e.responseXML.documentElement.nodeName;if(""===e.responseType&&!t)return e.responseXML}catch(e){}return null}(c),y)try{e=JSON.parse(e)}catch(e){}return e}(),statusCode:t,method:l,headers:{},url:h,rawRequest:c},c.getAllResponseHeaders&&(n.headers=o(c.getAllResponseHeaders()))):i=new Error("Internal XMLHttpRequest Error"),r(i,n,n.body)}}var a,s,c=e.xhr||null;c||(c=e.cors||e.useXDR?new u.XDomainRequest:new u.XMLHttpRequest);var f,h=c.url=e.uri||e.url,l=c.method=e.method||"GET",d=e.body||e.data,p=c.headers=e.headers||{},b=!!e.sync,y=!1,m={body:void 0,headers:{},statusCode:0,method:l,url:h,rawRequest:c};if("json"in e&&!1!==e.json&&(y=!0,p.accept||p.Accept||(p.Accept="application/json"),"GET"!==l&&"HEAD"!==l&&(p["content-type"]||p["Content-Type"]||(p["Content-Type"]="application/json"),d=JSON.stringify(!0===e.json?d:e.json))),c.onreadystatechange=function(){4===c.readyState&&setTimeout(i,0)},c.onload=i,c.onerror=n,c.onprogress=function(){},c.onabort=function(){s=!0},c.ontimeout=n,c.open(l,h,!b,e.username,e.password),b||(c.withCredentials=!!e.withCredentials),!b&&e.timeout>0&&(f=setTimeout(function(){if(!s){s=!0,c.abort("timeout");var e=new Error("XMLHttpRequest timeout");e.code="ETIMEDOUT",n(e)}},e.timeout)),c.setRequestHeader)for(a in p)p.hasOwnProperty(a)&&c.setRequestHeader(a,p[a]);else if(e.headers&&!function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0}(e.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in e&&(c.responseType=e.responseType),"beforeSend"in e&&"function"==typeof e.beforeSend&&e.beforeSend(c),c.send(d||null),c}t.exports=u,t.exports.default=u,u.XMLHttpRequest=n.XMLHttpRequest||function(){},u.XDomainRequest="withCredentials"in new u.XMLHttpRequest?u.XMLHttpRequest:n.XDomainRequest,function(e,t){for(var r=0;r=0)return this._url=this._parseUrl(t.headers.location),this._method="GET",this._loweredHeaders["content-type"]&&(delete this._headers[this._loweredHeaders["content-type"]],delete this._loweredHeaders["content-type"]),null!=this._headers["Content-Type"]&&delete this._headers["Content-Type"],delete this._headers["Content-Length"],this.upload._reset(),this._finalizeHeaders(),void this._sendHxxpRequest();this._response=t,this._response.on("data",function(e){return n._onHttpResponseData(t,e)}),this._response.on("end",function(){return n._onHttpResponseEnd(t)}),this._response.on("close",function(){return n._onHttpResponseClose(t)}),this.responseUrl=this._url.href.split("#")[0],this.status=t.statusCode,this.statusText=s.STATUS_CODES[this.status],this._parseResponseHeaders(t);var i=this._responseHeaders["content-length"]||"";this._totalBytes=+i,this._lengthComputable=!!i,this._setReadyState(r.HEADERS_RECEIVED)}},r.prototype._onHttpResponseData=function(e,t){this._response===e&&(this._responseParts.push(new n(t)),this._loadedBytes+=t.length,this.readyState!==r.LOADING&&this._setReadyState(r.LOADING),this._dispatchProgress("progress"))},r.prototype._onHttpResponseEnd=function(e){this._response===e&&(this._parseResponse(),this._request=null,this._response=null,this._setReadyState(r.DONE),this._dispatchProgress("load"),this._dispatchProgress("loadend"))},r.prototype._onHttpResponseClose=function(e){if(this._response===e){var t=this._request;this._setError(),t.abort(),this._setReadyState(r.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}},r.prototype._onHttpTimeout=function(e){this._request===e&&(this._setError(),e.abort(),this._setReadyState(r.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend"))},r.prototype._onHttpRequestError=function(e,t){this._request===e&&(this._setError(),e.abort(),this._setReadyState(r.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend"))},r.prototype._dispatchProgress=function(e){var t=new r.ProgressEvent(e);t.lengthComputable=this._lengthComputable,t.loaded=this._loadedBytes,t.total=this._totalBytes,this.dispatchEvent(t)},r.prototype._setError=function(){this._request=null,this._response=null,this._responseHeaders=null,this._responseParts=null},r.prototype._parseUrl=function(e,t,r){var n=null==this.nodejsBaseUrl?e:f.resolve(this.nodejsBaseUrl,e),i=f.parse(n,!1,!0);i.hash=null;var o=(i.auth||"").split(":"),a=o[0],s=o[1];return(a||s||t||r)&&(i.auth=(t||a||"")+":"+(r||s||"")),i},r.prototype._parseResponseHeaders=function(e){for(var t in this._responseHeaders={},e.headers){var r=t.toLowerCase();this._privateHeaders[r]||(this._responseHeaders[r]=e.headers[t])}null!=this._mimeOverride&&(this._responseHeaders["content-type"]=this._mimeOverride)},r.prototype._parseResponse=function(){var e=n.concat(this._responseParts);switch(this._responseParts=null,this.responseType){case"json":this.responseText=null;try{this.response=JSON.parse(e.toString("utf-8"))}catch(e){this.response=null}return;case"buffer":return this.responseText=null,void(this.response=e);case"arraybuffer":this.responseText=null;for(var t=new ArrayBuffer(e.length),r=new Uint8Array(t),i=0;i0&&(window.web3.eth.defaultAccount=t[0])})}window.ethereum=s}}},console.log("JS bridging rpc url access"),"undefined"!=typeof window&&window.bridge?window.bridge.post("getRPCurl",{},function(e,r){r&&t(r.description,null),t(null,e.rpcURL)}):(console.log("No bridge to native code is found"),t(!0,null))}()},{"./wk.bridge":424,web3:407,"web3-provider-engine/zero.js":397}],2:[function(e,t,r){t.exports=e("./register")().Promise},{"./register":4}],3:[function(e,t,r){"use strict";var n=null;t.exports=function(e,t){return function(r,i){r=r||null;var o=!1!==(i=i||{}).global;if(null===n&&o&&(n=e["@@any-promise/REGISTRATION"]||null),null!==n&&null!==r&&n.implementation!==r)throw new Error('any-promise already defined as "'+n.implementation+'". You can only register an implementation before the first call to require("any-promise") and an implementation cannot be changed');return null===n&&(n=null!==r&&void 0!==i.Promise?{Promise:i.Promise,implementation:r}:t(r),o&&(e["@@any-promise/REGISTRATION"]=n)),n}}},{}],4:[function(e,t,r){"use strict";t.exports=e("./loader")(window,function(){if(void 0===window.Promise)throw new Error("any-promise browser requires a polyfill or explicit registration e.g: require('any-promise/register/bluebird')");return{Promise:window.Promise,implementation:"window.Promise"}})},{"./loader":3}],5:[function(e,t,r){var n=r;n.bignum=e("bn.js"),n.define=e("./asn1/api").define,n.base=e("./asn1/base"),n.constants=e("./asn1/constants"),n.decoders=e("./asn1/decoders"),n.encoders=e("./asn1/encoders")},{"./asn1/api":6,"./asn1/base":8,"./asn1/constants":12,"./asn1/decoders":14,"./asn1/encoders":17,"bn.js":53}],6:[function(e,t,r){var n=e("../asn1"),i=e("inherits");function o(e,t){this.name=e,this.body=t,this.decoders={},this.encoders={}}r.define=function(e,t){return new o(e,t)},o.prototype._createNamed=function(t){var r;try{r=e("vm").runInThisContext("(function "+this.name+"(entity) {\n this._initNamed(entity);\n})")}catch(e){r=function(e){this._initNamed(e)}}return i(r,t),r.prototype._initNamed=function(e){t.call(this,e)},new r(this)},o.prototype._getDecoder=function(e){return e=e||"der",this.decoders.hasOwnProperty(e)||(this.decoders[e]=this._createNamed(n.decoders[e])),this.decoders[e]},o.prototype.decode=function(e,t,r){return this._getDecoder(t).decode(e,r)},o.prototype._getEncoder=function(e){return e=e||"der",this.encoders.hasOwnProperty(e)||(this.encoders[e]=this._createNamed(n.encoders[e])),this.encoders[e]},o.prototype.encode=function(e,t,r){return this._getEncoder(t).encode(e,r)}},{"../asn1":5,inherits:180,vm:334}],7:[function(e,t,r){var n=e("inherits"),i=e("../base").Reporter,o=e("buffer").Buffer;function a(e,t){i.call(this,t),o.isBuffer(e)?(this.base=e,this.offset=0,this.length=e.length):this.error("Input not Buffer")}function s(e,t){if(Array.isArray(e))this.length=0,this.value=e.map(function(e){return e instanceof s||(e=new s(e,t)),this.length+=e.length,e},this);else if("number"==typeof e){if(!(0<=e&&e<=255))return t.error("non-byte EncoderBuffer value");this.value=e,this.length=1}else if("string"==typeof e)this.value=e,this.length=o.byteLength(e);else{if(!o.isBuffer(e))return t.error("Unsupported type: "+typeof e);this.value=e,this.length=e.length}}n(a,i),r.DecoderBuffer=a,a.prototype.save=function(){return{offset:this.offset,reporter:i.prototype.save.call(this)}},a.prototype.restore=function(e){var t=new a(this.base);return t.offset=e.offset,t.length=this.offset,this.offset=e.offset,i.prototype.restore.call(this,e.reporter),t},a.prototype.isEmpty=function(){return this.offset===this.length},a.prototype.readUInt8=function(e){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(e||"DecoderBuffer overrun")},a.prototype.skip=function(e,t){if(!(this.offset+e<=this.length))return this.error(t||"DecoderBuffer overrun");var r=new a(this.base);return r._reporterState=this._reporterState,r.offset=this.offset,r.length=this.offset+e,this.offset+=e,r},a.prototype.raw=function(e){return this.base.slice(e?e.offset:this.offset,this.length)},r.EncoderBuffer=s,s.prototype.join=function(e,t){return e||(e=new o(this.length)),t||(t=0),0===this.length?e:(Array.isArray(this.value)?this.value.forEach(function(r){r.join(e,t),t+=r.length}):("number"==typeof this.value?e[t]=this.value:"string"==typeof this.value?e.write(this.value,t):o.isBuffer(this.value)&&this.value.copy(e,t),t+=this.length),e)}},{"../base":8,buffer:84,inherits:180}],8:[function(e,t,r){var n=r;n.Reporter=e("./reporter").Reporter,n.DecoderBuffer=e("./buffer").DecoderBuffer,n.EncoderBuffer=e("./buffer").EncoderBuffer,n.Node=e("./node")},{"./buffer":7,"./node":9,"./reporter":10}],9:[function(e,t,r){var n=e("../base").Reporter,i=e("../base").EncoderBuffer,o=e("../base").DecoderBuffer,a=e("minimalistic-assert"),s=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],u=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(s);function c(e,t){var r={};this._baseState=r,r.enc=e,r.parent=t||null,r.children=null,r.tag=null,r.args=null,r.reverseArgs=null,r.choice=null,r.optional=!1,r.any=!1,r.obj=!1,r.use=null,r.useDecoder=null,r.key=null,r.default=null,r.explicit=null,r.implicit=null,r.contains=null,r.parent||(r.children=[],this._wrap())}t.exports=c;var f=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];c.prototype.clone=function(){var e=this._baseState,t={};f.forEach(function(r){t[r]=e[r]});var r=new this.constructor(t.parent);return r._baseState=t,r},c.prototype._wrap=function(){var e=this._baseState;u.forEach(function(t){this[t]=function(){var r=new this.constructor(this);return e.children.push(r),r[t].apply(r,arguments)}},this)},c.prototype._init=function(e){var t=this._baseState;a(null===t.parent),e.call(this),t.children=t.children.filter(function(e){return e._baseState.parent===this},this),a.equal(t.children.length,1,"Root node can have only one child")},c.prototype._useArgs=function(e){var t=this._baseState,r=e.filter(function(e){return e instanceof this.constructor},this);e=e.filter(function(e){return!(e instanceof this.constructor)},this),0!==r.length&&(a(null===t.children),t.children=r,r.forEach(function(e){e._baseState.parent=this},this)),0!==e.length&&(a(null===t.args),t.args=e,t.reverseArgs=e.map(function(e){if("object"!=typeof e||e.constructor!==Object)return e;var t={};return Object.keys(e).forEach(function(r){r==(0|r)&&(r|=0);var n=e[r];t[n]=r}),t}))},["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"].forEach(function(e){c.prototype[e]=function(){var t=this._baseState;throw new Error(e+" not implemented for encoding: "+t.enc)}}),s.forEach(function(e){c.prototype[e]=function(){var t=this._baseState,r=Array.prototype.slice.call(arguments);return a(null===t.tag),t.tag=e,this._useArgs(r),this}}),c.prototype.use=function(e){a(e);var t=this._baseState;return a(null===t.use),t.use=e,this},c.prototype.optional=function(){return this._baseState.optional=!0,this},c.prototype.def=function(e){var t=this._baseState;return a(null===t.default),t.default=e,t.optional=!0,this},c.prototype.explicit=function(e){var t=this._baseState;return a(null===t.explicit&&null===t.implicit),t.explicit=e,this},c.prototype.implicit=function(e){var t=this._baseState;return a(null===t.explicit&&null===t.implicit),t.implicit=e,this},c.prototype.obj=function(){var e=this._baseState,t=Array.prototype.slice.call(arguments);return e.obj=!0,0!==t.length&&this._useArgs(t),this},c.prototype.key=function(e){var t=this._baseState;return a(null===t.key),t.key=e,this},c.prototype.any=function(){return this._baseState.any=!0,this},c.prototype.choice=function(e){var t=this._baseState;return a(null===t.choice),t.choice=e,this._useArgs(Object.keys(e).map(function(t){return e[t]})),this},c.prototype.contains=function(e){var t=this._baseState;return a(null===t.use),t.contains=e,this},c.prototype._decode=function(e,t){var r=this._baseState;if(null===r.parent)return e.wrapResult(r.children[0]._decode(e,t));var n,i=r.default,a=!0,s=null;if(null!==r.key&&(s=e.enterKey(r.key)),r.optional){var u=null;if(null!==r.explicit?u=r.explicit:null!==r.implicit?u=r.implicit:null!==r.tag&&(u=r.tag),null!==u||r.any){if(a=this._peekTag(e,u,r.any),e.isError(a))return a}else{var c=e.save();try{null===r.choice?this._decodeGeneric(r.tag,e,t):this._decodeChoice(e,t),a=!0}catch(e){a=!1}e.restore(c)}}if(r.obj&&a&&(n=e.enterObject()),a){if(null!==r.explicit){var f=this._decodeTag(e,r.explicit);if(e.isError(f))return f;e=f}var h=e.offset;if(null===r.use&&null===r.choice){if(r.any)c=e.save();var l=this._decodeTag(e,null!==r.implicit?r.implicit:r.tag,r.any);if(e.isError(l))return l;r.any?i=e.raw(c):e=l}if(t&&t.track&&null!==r.tag&&t.track(e.path(),h,e.length,"tagged"),t&&t.track&&null!==r.tag&&t.track(e.path(),e.offset,e.length,"content"),i=r.any?i:null===r.choice?this._decodeGeneric(r.tag,e,t):this._decodeChoice(e,t),e.isError(i))return i;if(r.any||null!==r.choice||null===r.children||r.children.forEach(function(r){r._decode(e,t)}),r.contains&&("octstr"===r.tag||"bitstr"===r.tag)){var d=new o(i);i=this._getUse(r.contains,e._reporterState.obj)._decode(d,t)}}return r.obj&&a&&(i=e.leaveObject(n)),null===r.key||null===i&&!0!==a?null!==s&&e.exitKey(s):e.leaveKey(s,r.key,i),i},c.prototype._decodeGeneric=function(e,t,r){var n=this._baseState;return"seq"===e||"set"===e?null:"seqof"===e||"setof"===e?this._decodeList(t,e,n.args[0],r):/str$/.test(e)?this._decodeStr(t,e,r):"objid"===e&&n.args?this._decodeObjid(t,n.args[0],n.args[1],r):"objid"===e?this._decodeObjid(t,null,null,r):"gentime"===e||"utctime"===e?this._decodeTime(t,e,r):"null_"===e?this._decodeNull(t,r):"bool"===e?this._decodeBool(t,r):"objDesc"===e?this._decodeStr(t,e,r):"int"===e||"enum"===e?this._decodeInt(t,n.args&&n.args[0],r):null!==n.use?this._getUse(n.use,t._reporterState.obj)._decode(t,r):t.error("unknown tag: "+e)},c.prototype._getUse=function(e,t){var r=this._baseState;return r.useDecoder=this._use(e,t),a(null===r.useDecoder._baseState.parent),r.useDecoder=r.useDecoder._baseState.children[0],r.implicit!==r.useDecoder._baseState.implicit&&(r.useDecoder=r.useDecoder.clone(),r.useDecoder._baseState.implicit=r.implicit),r.useDecoder},c.prototype._decodeChoice=function(e,t){var r=this._baseState,n=null,i=!1;return Object.keys(r.choice).some(function(o){var a=e.save(),s=r.choice[o];try{var u=s._decode(e,t);if(e.isError(u))return!1;n={type:o,value:u},i=!0}catch(t){return e.restore(a),!1}return!0},this),i?n:e.error("Choice not matched")},c.prototype._createEncoderBuffer=function(e){return new i(e,this.reporter)},c.prototype._encode=function(e,t,r){var n=this._baseState;if(null===n.default||n.default!==e){var i=this._encodeValue(e,t,r);if(void 0!==i&&!this._skipDefault(i,t,r))return i}},c.prototype._encodeValue=function(e,t,r){var i=this._baseState;if(null===i.parent)return i.children[0]._encode(e,t||new n);var o=null;if(this.reporter=t,i.optional&&void 0===e){if(null===i.default)return;e=i.default}var a=null,s=!1;if(i.any)o=this._createEncoderBuffer(e);else if(i.choice)o=this._encodeChoice(e,t);else if(i.contains)a=this._getUse(i.contains,r)._encode(e,t),s=!0;else if(i.children)a=i.children.map(function(r){if("null_"===r._baseState.tag)return r._encode(null,t,e);if(null===r._baseState.key)return t.error("Child should have a key");var n=t.enterKey(r._baseState.key);if("object"!=typeof e)return t.error("Child expected, but input is not object");var i=r._encode(e[r._baseState.key],t,e);return t.leaveKey(n),i},this).filter(function(e){return e}),a=this._createEncoderBuffer(a);else if("seqof"===i.tag||"setof"===i.tag){if(!i.args||1!==i.args.length)return t.error("Too many args for : "+i.tag);if(!Array.isArray(e))return t.error("seqof/setof, but data is not Array");var u=this.clone();u._baseState.implicit=null,a=this._createEncoderBuffer(e.map(function(r){var n=this._baseState;return this._getUse(n.args[0],e)._encode(r,t)},u))}else null!==i.use?o=this._getUse(i.use,r)._encode(e,t):(a=this._encodePrimitive(i.tag,e),s=!0);if(!i.any&&null===i.choice){var c=null!==i.implicit?i.implicit:i.tag,f=null===i.implicit?"universal":"context";null===c?null===i.use&&t.error("Tag could be omitted only for .use()"):null===i.use&&(o=this._encodeComposite(c,s,f,a))}return null!==i.explicit&&(o=this._encodeComposite(i.explicit,!1,"context",o)),o},c.prototype._encodeChoice=function(e,t){var r=this._baseState,n=r.choice[e.type];return n||a(!1,e.type+" not found in "+JSON.stringify(Object.keys(r.choice))),n._encode(e.value,t)},c.prototype._encodePrimitive=function(e,t){var r=this._baseState;if(/str$/.test(e))return this._encodeStr(t,e);if("objid"===e&&r.args)return this._encodeObjid(t,r.reverseArgs[0],r.args[1]);if("objid"===e)return this._encodeObjid(t,null,null);if("gentime"===e||"utctime"===e)return this._encodeTime(t,e);if("null_"===e)return this._encodeNull();if("int"===e||"enum"===e)return this._encodeInt(t,r.args&&r.reverseArgs[0]);if("bool"===e)return this._encodeBool(t);if("objDesc"===e)return this._encodeStr(t,e);throw new Error("Unsupported tag: "+e)},c.prototype._isNumstr=function(e){return/^[0-9 ]*$/.test(e)},c.prototype._isPrintstr=function(e){return/^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(e)}},{"../base":8,"minimalistic-assert":234}],10:[function(e,t,r){var n=e("inherits");function i(e){this._reporterState={obj:null,path:[],options:e||{},errors:[]}}function o(e,t){this.path=e,this.rethrow(t)}r.Reporter=i,i.prototype.isError=function(e){return e instanceof o},i.prototype.save=function(){var e=this._reporterState;return{obj:e.obj,pathLen:e.path.length}},i.prototype.restore=function(e){var t=this._reporterState;t.obj=e.obj,t.path=t.path.slice(0,e.pathLen)},i.prototype.enterKey=function(e){return this._reporterState.path.push(e)},i.prototype.exitKey=function(e){var t=this._reporterState;t.path=t.path.slice(0,e-1)},i.prototype.leaveKey=function(e,t,r){var n=this._reporterState;this.exitKey(e),null!==n.obj&&(n.obj[t]=r)},i.prototype.path=function(){return this._reporterState.path.join("/")},i.prototype.enterObject=function(){var e=this._reporterState,t=e.obj;return e.obj={},t},i.prototype.leaveObject=function(e){var t=this._reporterState,r=t.obj;return t.obj=e,r},i.prototype.error=function(e){var t,r=this._reporterState,n=e instanceof o;if(t=n?e:new o(r.path.map(function(e){return"["+JSON.stringify(e)+"]"}).join(""),e.message||e,e.stack),!r.options.partial)throw t;return n||r.errors.push(t),t},i.prototype.wrapResult=function(e){var t=this._reporterState;return t.options.partial?{result:this.isError(e)?null:e,errors:t.errors}:e},n(o,Error),o.prototype.rethrow=function(e){if(this.message=e+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,o),!this.stack)try{throw new Error(this.message)}catch(e){this.stack=e.stack}return this}},{inherits:180}],11:[function(e,t,r){var n=e("../constants");r.tagClass={0:"universal",1:"application",2:"context",3:"private"},r.tagClassByName=n._reverse(r.tagClass),r.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},r.tagByName=n._reverse(r.tag)},{"../constants":12}],12:[function(e,t,r){var n=r;n._reverse=function(e){var t={};return Object.keys(e).forEach(function(r){(0|r)==r&&(r|=0);var n=e[r];t[n]=r}),t},n.der=e("./der")},{"./der":11}],13:[function(e,t,r){var n=e("inherits"),i=e("../../asn1"),o=i.base,a=i.bignum,s=i.constants.der;function u(e){this.enc="der",this.name=e.name,this.entity=e,this.tree=new c,this.tree._init(e.body)}function c(e){o.Node.call(this,"der",e)}function f(e,t){var r=e.readUInt8(t);if(e.isError(r))return r;var n=s.tagClass[r>>6],i=0==(32&r);if(31==(31&r)){var o=r;for(r=0;128==(128&o);){if(o=e.readUInt8(t),e.isError(o))return o;r<<=7,r|=127&o}}else r&=31;return{cls:n,primitive:i,tag:r,tagStr:s.tag[r]}}function h(e,t,r){var n=e.readUInt8(r);if(e.isError(n))return n;if(!t&&128===n)return null;if(0==(128&n))return n;var i=127&n;if(i>4)return e.error("length octect is too long");n=0;for(var o=0;o=31)return n.error("Multi-octet tag encoding unsupported");t||(i|=32);return i|=s.tagClassByName[r||"universal"]<<6}(e,t,r,this.reporter);if(n.length<128)return(o=new i(2))[0]=a,o[1]=n.length,this._createEncoderBuffer([o,n]);for(var u=1,c=n.length;c>=256;c>>=8)u++;(o=new i(2+u))[0]=a,o[1]=128|u;c=1+u;for(var f=n.length;f>0;c--,f>>=8)o[c]=255&f;return this._createEncoderBuffer([o,n])},c.prototype._encodeStr=function(e,t){if("bitstr"===t)return this._createEncoderBuffer([0|e.unused,e.data]);if("bmpstr"===t){for(var r=new i(2*e.length),n=0;n=40)return this.reporter.error("Second objid identifier OOB");e.splice(0,2,40*e[0]+e[1])}var o=0;for(n=0;n=128;a>>=7)o++}var s=new i(o),u=s.length-1;for(n=e.length-1;n>=0;n--){a=e[n];for(s[u--]=127&a;(a>>=7)>0;)s[u--]=128|127&a}return this._createEncoderBuffer(s)},c.prototype._encodeTime=function(e,t){var r,n=new Date(e);return"gentime"===t?r=[f(n.getFullYear()),f(n.getUTCMonth()+1),f(n.getUTCDate()),f(n.getUTCHours()),f(n.getUTCMinutes()),f(n.getUTCSeconds()),"Z"].join(""):"utctime"===t?r=[f(n.getFullYear()%100),f(n.getUTCMonth()+1),f(n.getUTCDate()),f(n.getUTCHours()),f(n.getUTCMinutes()),f(n.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+t+" time is not supported yet"),this._encodeStr(r,"octstr")},c.prototype._encodeNull=function(){return this._createEncoderBuffer("")},c.prototype._encodeInt=function(e,t){if("string"==typeof e){if(!t)return this.reporter.error("String int or enum given, but no values map");if(!t.hasOwnProperty(e))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(e));e=t[e]}if("number"!=typeof e&&!i.isBuffer(e)){var r=e.toArray();!e.sign&&128&r[0]&&r.unshift(0),e=new i(r)}if(i.isBuffer(e)){var n=e.length;0===e.length&&n++;var o=new i(n);return e.copy(o),0===e.length&&(o[0]=0),this._createEncoderBuffer(o)}if(e<128)return this._createEncoderBuffer(e);if(e<256)return this._createEncoderBuffer([0,e]);n=1;for(var a=e;a>=256;a>>=8)n++;for(a=(o=new Array(n)).length-1;a>=0;a--)o[a]=255&e,e>>=8;return 128&o[0]&&o.unshift(0),this._createEncoderBuffer(new i(o))},c.prototype._encodeBool=function(e){return this._createEncoderBuffer(e?255:0)},c.prototype._use=function(e,t){return"function"==typeof e&&(e=e(t)),e._getEncoder("der").tree},c.prototype._skipDefault=function(e,t,r){var n,i=this._baseState;if(null===i.default)return!1;var o=e.join();if(void 0===i.defaultBuffer&&(i.defaultBuffer=this._encodeValue(i.default,t,r).join()),o.length!==i.defaultBuffer.length)return!1;for(n=0;n=0;c--)if(f[c]!==h[c])return!1;for(c=f.length-1;c>=0;c--)if(u=f[c],!v(e[u],t[u],r,n))return!1;return!0}(e,t,r,a))}return r?e===t:e==t}function g(e){return"[object Arguments]"==Object.prototype.toString.call(e)}function w(e,t){if(!e||!t)return!1;if("[object RegExp]"==Object.prototype.toString.call(t))return t.test(e);try{if(e instanceof t)return!0}catch(e){}return!Error.isPrototypeOf(t)&&!0===t.call({},e)}function _(e,t,r,n){var i;if("function"!=typeof t)throw new TypeError('"block" argument must be a function');"string"==typeof r&&(n=r,r=null),i=function(e){var t;try{e()}catch(e){t=e}return t}(t),n=(r&&r.name?" ("+r.name+").":".")+(n?" "+n:"."),e&&!i&&y(i,r,"Missing expected exception"+n);var a="string"==typeof n,s=!e&&i&&!r;if((!e&&o.isError(i)&&a&&w(i,r)||s)&&y(i,r,"Got unwanted exception"+n),e&&i&&r&&!w(i,r)||!e&&i)throw i}h.AssertionError=function(e){var t;this.name="AssertionError",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,e.message?(this.message=e.message,this.generatedMessage=!1):(this.message=p(b((t=this).actual),128)+" "+t.operator+" "+p(b(t.expected),128),this.generatedMessage=!0);var r=e.stackStartFunction||y;if(Error.captureStackTrace)Error.captureStackTrace(this,r);else{var n=new Error;if(n.stack){var i=n.stack,o=d(r),a=i.indexOf("\n"+o);if(a>=0){var s=i.indexOf("\n",a+1);i=i.substring(s+1)}this.stack=i}}},o.inherits(h.AssertionError,Error),h.fail=y,h.ok=m,h.equal=function(e,t,r){e!=t&&y(e,t,r,"==",h.equal)},h.notEqual=function(e,t,r){e==t&&y(e,t,r,"!=",h.notEqual)},h.deepEqual=function(e,t,r){v(e,t,!1)||y(e,t,r,"deepEqual",h.deepEqual)},h.deepStrictEqual=function(e,t,r){v(e,t,!0)||y(e,t,r,"deepStrictEqual",h.deepStrictEqual)},h.notDeepEqual=function(e,t,r){v(e,t,!1)&&y(e,t,r,"notDeepEqual",h.notDeepEqual)},h.notDeepStrictEqual=function e(t,r,n){v(t,r,!0)&&y(t,r,n,"notDeepStrictEqual",e)},h.strictEqual=function(e,t,r){e!==t&&y(e,t,r,"===",h.strictEqual)},h.notStrictEqual=function(e,t,r){e===t&&y(e,t,r,"!==",h.notStrictEqual)},h.throws=function(e,t,r){_(!0,e,t,r)},h.doesNotThrow=function(e,t,r){_(!1,e,t,r)},h.ifError=function(e){if(e)throw e};var A=Object.keys||function(e){var t=[];for(var r in e)a.call(e,r)&&t.push(r);return t}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"util/":333}],20:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(0,i.default)(function(t,r){var i;try{i=e.apply(this,t)}catch(e){return r(e)}(0,n.default)(i)&&"function"==typeof i.then?i.then(function(e){s(r,null,e)},function(e){s(r,e.message?e:new Error(e))}):r(null,i)})};var n=a(e("lodash/isObject")),i=a(e("./internal/initialParams")),o=a(e("./internal/setImmediate"));function a(e){return e&&e.__esModule?e:{default:e}}function s(e,t,r){try{e(t,r)}catch(e){(0,o.default)(u,e)}}function u(e){throw e}t.exports=r.default},{"./internal/initialParams":31,"./internal/setImmediate":37,"lodash/isObject":225}],21:[function(e,t,r){(function(e,n){!function(e,n){"object"==typeof r&&void 0!==t?n(r):"function"==typeof define&&define.amd?define(["exports"],n):n(e.async=e.async||{})}(this,function(r){"use strict";function i(e,t){t|=0;for(var r=Math.max(e.length-t,0),n=Array(r),i=0;i-1&&e%1==0&&e<=L}function D(e){return null!=e&&O(e.length)&&!function(e){if(!s(e))return!1;var t=B(e);return t==C||t==N||t==P||t==R}(e)}var F={};function q(){}function H(e){return function(){if(null!==e){var t=e;e=null,t.apply(this,arguments)}}}var z="function"==typeof Symbol&&Symbol.iterator,K=function(e){return z&&e[z]&&e[z]()};function V(e){return null!=e&&"object"==typeof e}var G="[object Arguments]";function W(e){return V(e)&&B(e)==G}var Y=Object.prototype,X=Y.hasOwnProperty,Z=Y.propertyIsEnumerable,J=W(function(){return arguments}())?W:function(e){return V(e)&&X.call(e,"callee")&&!Z.call(e,"callee")},$=Array.isArray;var Q="object"==typeof r&&r&&!r.nodeType&&r,ee=Q&&"object"==typeof t&&t&&!t.nodeType&&t,te=ee&&ee.exports===Q?A.Buffer:void 0,re=(te?te.isBuffer:void 0)||function(){return!1},ne=9007199254740991,ie=/^(?:0|[1-9]\d*)$/;function oe(e,t){return!!(t=null==t?ne:t)&&("number"==typeof e||ie.test(e))&&e>-1&&e%1==0&&e2&&(n=i(arguments,1)),t){var c={};Fe(o,function(e,t){c[t]=e}),c[e]=n,s=!0,u=Object.create(null),r(t,c)}else o[e]=n,Le(u[e]||[],function(e){e()}),d()});a++;var c=v(t[t.length-1]);t.length>1?c(o,n):c(n)}(e,t)})}function d(){if(0===c.length&&0===a)return r(null,o);for(;c.length&&a=0&&r.push(n)}),r}Fe(e,function(t,r){if(!$(t))return l(r,[t]),void f.push(r);var n=t.slice(0,t.length-1),i=n.length;if(0===i)return l(r,t),void f.push(r);h[r]=i,Le(n,function(o){if(!e[o])throw new Error("async.auto task `"+r+"` has a non-existent dependency `"+o+"` in "+n.join(", "));!function(e,t){var r=u[e];r||(r=u[e]=[]);r.push(t)}(o,function(){0===--i&&l(r,t)})})}),function(){var e,t=0;for(;f.length;)e=f.pop(),t++,Le(p(e),function(e){0==--h[e]&&f.push(e)});if(t!==n)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}(),d()};function Ke(e,t){for(var r=-1,n=null==e?0:e.length,i=Array(n);++r=n?e:function(e,t,r){var n=-1,i=e.length;t<0&&(t=-t>i?0:i+t),(r=r>i?i:r)<0&&(r+=i),i=t>r?0:r-t>>>0,t>>>=0;for(var o=Array(i);++n-1;);return r}(i,o),function(e,t){for(var r=e.length;r--&&He(t,e[r],0)>-1;);return r}(i,o)+1).join("")}var ht=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,lt=/,/,dt=/(=.+)?(\s*)$/,pt=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;function bt(e,t){var r={};Fe(e,function(e,t){var n,i,o=m(e),a=!o&&1===e.length||o&&0===e.length;if($(e))n=e.slice(0,-1),e=e[e.length-1],r[t]=n.concat(n.length>0?s:e);else if(a)r[t]=e;else{if(n=i=(i=(i=(i=(i=e).toString().replace(pt,"")).match(ht)[2].replace(" ",""))?i.split(lt):[]).map(function(e){return ft(e.replace(dt,""))}),0===e.length&&!o&&0===n.length)throw new Error("autoInject task functions require explicit parameters.");o||n.pop(),r[t]=n.concat(s)}function s(t,r){var i=Ke(n,function(e){return t[e]});i.push(r),v(e).apply(null,i)}}),ze(r,t)}function yt(){this.head=this.tail=null,this.length=0}function mt(e,t){e.length=1,e.head=e.tail=t}function vt(e,t,r){if(null==t)t=1;else if(0===t)throw new Error("Concurrency must not be zero");var n=v(e),i=0,o=[],a=!1;function s(e,t,r){if(null!=r&&"function"!=typeof r)throw new Error("task callback must be a function");if(f.started=!0,$(e)||(e=[e]),0===e.length&&f.idle())return l(function(){f.drain()});for(var n=0,i=e.length;n0&&o.splice(s,1),a.callback.apply(a,arguments),null!=t&&f.error(t,a.data)}i<=f.concurrency-f.buffer&&f.unsaturated(),f.idle()&&f.drain(),f.process()}}var c=!1,f={_tasks:new yt,concurrency:t,payload:r,saturated:q,unsaturated:q,buffer:t/4,empty:q,drain:q,error:q,started:!1,paused:!1,push:function(e,t){s(e,!1,t)},kill:function(){f.drain=q,f._tasks.empty()},unshift:function(e,t){s(e,!0,t)},remove:function(e){f._tasks.remove(e)},process:function(){if(!c){for(c=!0;!f.paused&&i2&&(o=i(arguments,1)),n[t]=o,r(e)})},function(e){r(e,n)})}function br(e,t){pr(Ie,e,t)}function yr(e,t,r){pr(Ee(t),e,r)}var mr=function(e,t){var r=v(e);return vt(function(e,t){r(e[0],t)},t,1)},vr=function(e,t){var r=mr(e,t);return r.push=function(e,t,n){if(null==n&&(n=q),"function"!=typeof n)throw new Error("task callback must be a function");if(r.started=!0,$(e)||(e=[e]),0===e.length)return l(function(){r.drain()});t=t||0;for(var i=r._tasks.head;i&&t>=i.priority;)i=i.next;for(var o=0,a=e.length;on?1:0}je(e,function(e,t){n(e,function(r,n){if(r)return t(r);t(null,{value:e,criteria:n})})},function(e,t){if(e)return r(e);r(null,Ke(t.sort(i),Zt("value")))})}function Nr(e,t,r){var n=v(e);return a(function(i,o){var a,s=!1;i.push(function(){s||(o.apply(null,arguments),clearTimeout(a))}),a=setTimeout(function(){var t=e.name||"anonymous",n=new Error('Callback function "'+t+'" timed out.');n.code="ETIMEDOUT",r&&(n.info=r),s=!0,o(n)},t),n.apply(null,i)})}var Rr=Math.ceil,Lr=Math.max;function Or(e,t,r,n){var i=v(r);Ce(function(e,t,r,n){for(var i=-1,o=Lr(Rr((t-e)/(r||1)),0),a=Array(o);o--;)a[n?o:++i]=e,e+=r;return a}(0,e,1),t,i,n)}var Dr=ke(Or,1/0),Fr=ke(Or,1);function qr(e,t,r,n){arguments.length<=3&&(n=r,r=t,t=$(e)?[]:{}),n=H(n||q);var i=v(r);Ie(e,function(e,r,n){i(t,e,r,n)},function(e){n(e,t)})}function Hr(e,t){var r,n=null;t=t||q,Kt(e,function(e,t){v(e)(function(e,o){r=arguments.length>2?i(arguments,1):o,n=e,t(!e)})},function(){t(n,r)})}function zr(e){return function(){return(e.unmemoized||e).apply(null,arguments)}}function Kr(e,t,r){r=Ae(r||q);var n=v(t);if(!e())return r(null);var o=function(t){if(t)return r(t);if(e())return n(o);var a=i(arguments,1);r.apply(null,[null].concat(a))};n(o)}function Vr(e,t,r){Kr(function(){return!e.apply(this,arguments)},t,r)}var Gr=function(e,t){if(t=H(t||q),!$(e))return t(new Error("First argument to waterfall must be an array of functions"));if(!e.length)return t();var r=0;function n(t){var n=v(e[r++]);t.push(Ae(o)),n.apply(null,t)}function o(o){if(o||r===e.length)return t.apply(null,arguments);n(i(arguments,1))}n([])},Wr={apply:o,applyEach:Be,applyEachSeries:Re,asyncify:d,auto:ze,autoInject:bt,cargo:gt,compose:Et,concat:St,concatLimit:kt,concatSeries:Mt,constant:It,detect:Bt,detectLimit:Pt,detectSeries:Ct,dir:Rt,doDuring:Lt,doUntil:Dt,doWhilst:Ot,during:Ft,each:Ht,eachLimit:zt,eachOf:Ie,eachOfLimit:xe,eachOfSeries:wt,eachSeries:Kt,ensureAsync:Vt,every:Wt,everyLimit:Yt,everySeries:Xt,filter:er,filterLimit:tr,filterSeries:rr,forever:nr,groupBy:or,groupByLimit:ir,groupBySeries:ar,log:sr,map:je,mapLimit:Ce,mapSeries:Ne,mapValues:cr,mapValuesLimit:ur,mapValuesSeries:fr,memoize:lr,nextTick:dr,parallel:br,parallelLimit:yr,priorityQueue:vr,queue:mr,race:gr,reduce:_t,reduceRight:wr,reflect:_r,reflectAll:Ar,reject:xr,rejectLimit:kr,rejectSeries:Sr,retry:Ir,retryable:Tr,seq:At,series:Ur,setImmediate:l,some:jr,someLimit:Br,someSeries:Pr,sortBy:Cr,timeout:Nr,times:Dr,timesLimit:Or,timesSeries:Fr,transform:qr,tryEach:Hr,unmemoize:zr,until:Vr,waterfall:Gr,whilst:Kr,all:Wt,allLimit:Yt,allSeries:Xt,any:jr,anyLimit:Br,anySeries:Pr,find:Bt,findLimit:Pt,findSeries:Ct,forEach:Ht,forEachSeries:Kt,forEachLimit:zt,forEachOf:Ie,forEachOfSeries:wt,forEachOfLimit:xe,inject:_t,foldl:_t,foldr:wr,select:er,selectLimit:tr,selectSeries:rr,wrapSync:d};r.default=Wr,r.apply=o,r.applyEach=Be,r.applyEachSeries=Re,r.asyncify=d,r.auto=ze,r.autoInject=bt,r.cargo=gt,r.compose=Et,r.concat=St,r.concatLimit=kt,r.concatSeries=Mt,r.constant=It,r.detect=Bt,r.detectLimit=Pt,r.detectSeries=Ct,r.dir=Rt,r.doDuring=Lt,r.doUntil=Dt,r.doWhilst=Ot,r.during=Ft,r.each=Ht,r.eachLimit=zt,r.eachOf=Ie,r.eachOfLimit=xe,r.eachOfSeries=wt,r.eachSeries=Kt,r.ensureAsync=Vt,r.every=Wt,r.everyLimit=Yt,r.everySeries=Xt,r.filter=er,r.filterLimit=tr,r.filterSeries=rr,r.forever=nr,r.groupBy=or,r.groupByLimit=ir,r.groupBySeries=ar,r.log=sr,r.map=je,r.mapLimit=Ce,r.mapSeries=Ne,r.mapValues=cr,r.mapValuesLimit=ur,r.mapValuesSeries=fr,r.memoize=lr,r.nextTick=dr,r.parallel=br,r.parallelLimit=yr,r.priorityQueue=vr,r.queue=mr,r.race=gr,r.reduce=_t,r.reduceRight=wr,r.reflect=_r,r.reflectAll=Ar,r.reject=xr,r.rejectLimit=kr,r.rejectSeries=Sr,r.retry=Ir,r.retryable=Tr,r.seq=At,r.series=Ur,r.setImmediate=l,r.some=jr,r.someLimit=Br,r.someSeries=Pr,r.sortBy=Cr,r.timeout=Nr,r.times=Dr,r.timesLimit=Or,r.timesSeries=Fr,r.transform=qr,r.tryEach=Hr,r.unmemoize=zr,r.until=Vr,r.waterfall=Gr,r.whilst=Kr,r.all=Wt,r.allLimit=Yt,r.allSeries=Xt,r.any=jr,r.anyLimit=Br,r.anySeries=Pr,r.find=Bt,r.findLimit=Pt,r.findSeries=Ct,r.forEach=Ht,r.forEachSeries=Kt,r.forEachLimit=zt,r.forEachOf=Ie,r.forEachOfSeries=wt,r.forEachOfLimit=xe,r.inject=_t,r.foldl=_t,r.foldr=wr,r.select=er,r.selectLimit=tr,r.selectSeries=rr,r.wrapSync=d,Object.defineProperty(r,"__esModule",{value:!0})})}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:257}],22:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t,r,a){(0,n.default)(t)(e,(0,i.default)((0,o.default)(r)),a)};var n=a(e("./internal/eachOfLimit")),i=a(e("./internal/withoutIndex")),o=a(e("./internal/wrapAsync"));function a(e){return e&&e.__esModule?e:{default:e}}t.exports=r.default},{"./internal/eachOfLimit":29,"./internal/withoutIndex":39,"./internal/wrapAsync":40}],23:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t,r){((0,n.default)(e)?l:d)(e,(0,f.default)(t),r)};var n=h(e("lodash/isArrayLike")),i=h(e("./internal/breakLoop")),o=h(e("./eachOfLimit")),a=h(e("./internal/doLimit")),s=h(e("lodash/noop")),u=h(e("./internal/once")),c=h(e("./internal/onlyOnce")),f=h(e("./internal/wrapAsync"));function h(e){return e&&e.__esModule?e:{default:e}}function l(e,t,r){r=(0,u.default)(r||s.default);var n=0,o=0,a=e.length;function f(e,t){e?r(e):++o!==a&&t!==i.default||r(null)}for(0===a&&r(null);n2&&(n=(0,o.default)(arguments,1)),s[t]=n,r(e)})},function(e){r(e,s)})};var n=s(e("lodash/noop")),i=s(e("lodash/isArrayLike")),o=s(e("./slice")),a=s(e("./wrapAsync"));function s(e){return e&&e.__esModule?e:{default:e}}t.exports=r.default},{"./slice":38,"./wrapAsync":40,"lodash/isArrayLike":221,"lodash/noop":229}],37:[function(e,t,r){(function(t){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.hasNextTick=r.hasSetImmediate=void 0,r.fallback=c,r.wrap=f;var n,i=e("./slice"),o=(n=i)&&n.__esModule?n:{default:n};var a,s=r.hasSetImmediate="function"==typeof setImmediate&&setImmediate,u=r.hasNextTick="object"==typeof t&&"function"==typeof t.nextTick;function c(e){setTimeout(e,0)}function f(e){return function(t){var r=(0,o.default)(arguments,1);e(function(){t.apply(null,r)})}}a=s?setImmediate:u?t.nextTick:c,r.default=f(a)}).call(this,e("_process"))},{"./slice":38,_process:257}],38:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){t|=0;for(var r=Math.max(e.length-t,0),n=Array(r),i=0;i0,"Expected a maximum number of retry greater than 0 but got %s.",e),this.maxNumberOfRetry_=e},o.prototype.backoff=function(e){i.checkState(-1===this.timeoutID_,"Backoff in progress."),this.backoffNumber_===this.maxNumberOfRetry_?(this.emit("fail",e),this.reset()):(this.backoffDelay_=this.backoffStrategy_.next(),this.timeoutID_=setTimeout(this.handlers.backoff,this.backoffDelay_),this.emit("backoff",this.backoffNumber_,this.backoffDelay_,e))},o.prototype.onBackoff_=function(){this.timeoutID_=-1,this.emit("ready",this.backoffNumber_,this.backoffDelay_),this.backoffNumber_++},o.prototype.reset=function(){this.backoffNumber_=0,this.backoffStrategy_.reset(),clearTimeout(this.timeoutID_),this.timeoutID_=-1},t.exports=o},{events:157,precond:253,util:333}],47:[function(e,t,r){var n=e("events"),i=e("precond"),o=e("util"),a=e("./backoff"),s=e("./strategy/fibonacci");function u(e,t,r){n.EventEmitter.call(this),i.checkIsFunction(e,"Expected fn to be a function."),i.checkIsArray(t,"Expected args to be an array."),i.checkIsFunction(r,"Expected callback to be a function."),this.function_=e,this.arguments_=t,this.callback_=r,this.lastResult_=[],this.numRetries_=0,this.backoff_=null,this.strategy_=null,this.failAfter_=-1,this.retryPredicate_=u.DEFAULT_RETRY_PREDICATE_,this.state_=u.State_.PENDING}o.inherits(u,n.EventEmitter),u.State_={PENDING:0,RUNNING:1,COMPLETED:2,ABORTED:3},u.DEFAULT_RETRY_PREDICATE_=function(e){return!0},u.prototype.isPending=function(){return this.state_==u.State_.PENDING},u.prototype.isRunning=function(){return this.state_==u.State_.RUNNING},u.prototype.isCompleted=function(){return this.state_==u.State_.COMPLETED},u.prototype.isAborted=function(){return this.state_==u.State_.ABORTED},u.prototype.setStrategy=function(e){return i.checkState(this.isPending(),"FunctionCall in progress."),this.strategy_=e,this},u.prototype.retryIf=function(e){return i.checkState(this.isPending(),"FunctionCall in progress."),this.retryPredicate_=e,this},u.prototype.getLastResult=function(){return this.lastResult_.concat()},u.prototype.getNumRetries=function(){return this.numRetries_},u.prototype.failAfter=function(e){return i.checkState(this.isPending(),"FunctionCall in progress."),this.failAfter_=e,this},u.prototype.abort=function(){this.isCompleted()||this.isAborted()||(this.isRunning()&&this.backoff_.reset(),this.state_=u.State_.ABORTED,this.lastResult_=[new Error("Backoff aborted.")],this.emit("abort"),this.doCallback_())},u.prototype.start=function(e){i.checkState(!this.isAborted(),"FunctionCall is aborted."),i.checkState(this.isPending(),"FunctionCall already started.");var t=this.strategy_||new s;this.backoff_=e?e(t):new a(t),this.backoff_.on("ready",this.doCall_.bind(this,!0)),this.backoff_.on("fail",this.doCallback_.bind(this)),this.backoff_.on("backoff",this.handleBackoff_.bind(this)),this.failAfter_>0&&this.backoff_.failAfter(this.failAfter_),this.state_=u.State_.RUNNING,this.doCall_(!1)},u.prototype.doCall_=function(e){e&&this.numRetries_++;var t=["call"].concat(this.arguments_);n.EventEmitter.prototype.emit.apply(this,t);var r=this.handleFunctionCallback_.bind(this);this.function_.apply(null,this.arguments_.concat(r))},u.prototype.doCallback_=function(){this.callback_.apply(null,this.lastResult_)},u.prototype.handleFunctionCallback_=function(){if(!this.isAborted()){var e=Array.prototype.slice.call(arguments);this.lastResult_=e,n.EventEmitter.prototype.emit.apply(this,["callback"].concat(e));var t=e[0];t&&this.retryPredicate_(t)?this.backoff_.backoff(t):(this.state_=u.State_.COMPLETED,this.doCallback_())}},u.prototype.handleBackoff_=function(e,t,r){this.emit("backoff",e,t,r)},t.exports=u},{"./backoff":46,"./strategy/fibonacci":49,events:157,precond:253,util:333}],48:[function(e,t,r){var n=e("util"),i=e("precond"),o=e("./strategy");function a(e){o.call(this,e),this.backoffDelay_=0,this.nextBackoffDelay_=this.getInitialDelay(),this.factor_=a.DEFAULT_FACTOR,e&&void 0!==e.factor&&(i.checkArgument(e.factor>1,"Exponential factor should be greater than 1 but got %s.",e.factor),this.factor_=e.factor)}n.inherits(a,o),a.DEFAULT_FACTOR=2,a.prototype.next_=function(){return this.backoffDelay_=Math.min(this.nextBackoffDelay_,this.getMaxDelay()),this.nextBackoffDelay_=this.backoffDelay_*this.factor_,this.backoffDelay_},a.prototype.reset_=function(){this.backoffDelay_=0,this.nextBackoffDelay_=this.getInitialDelay()},t.exports=a},{"./strategy":50,precond:253,util:333}],49:[function(e,t,r){var n=e("util"),i=e("./strategy");function o(e){i.call(this,e),this.backoffDelay_=0,this.nextBackoffDelay_=this.getInitialDelay()}n.inherits(o,i),o.prototype.next_=function(){var e=Math.min(this.nextBackoffDelay_,this.getMaxDelay());return this.nextBackoffDelay_+=this.backoffDelay_,this.backoffDelay_=e,e},o.prototype.reset_=function(){this.nextBackoffDelay_=this.getInitialDelay(),this.backoffDelay_=0},t.exports=o},{"./strategy":50,util:333}],50:[function(e,t,r){e("events"),e("util");function n(e){return null!=e}function i(e){if(n((e=e||{}).initialDelay)&&e.initialDelay<1)throw new Error("The initial timeout must be greater than 0.");if(n(e.maxDelay)&&e.maxDelay<1)throw new Error("The maximal timeout must be greater than 0.");if(this.initialDelay_=e.initialDelay||100,this.maxDelay_=e.maxDelay||1e4,this.maxDelay_<=this.initialDelay_)throw new Error("The maximal backoff delay must be greater than the initial backoff delay.");if(n(e.randomisationFactor)&&(e.randomisationFactor<0||e.randomisationFactor>1))throw new Error("The randomisation factor must be between 0 and 1.");this.randomisationFactor_=e.randomisationFactor||0}i.prototype.getMaxDelay=function(){return this.maxDelay_},i.prototype.getInitialDelay=function(){return this.initialDelay_},i.prototype.next=function(){var e=this.next_(),t=1+Math.random()*this.randomisationFactor_;return Math.round(e*t)},i.prototype.next_=function(){throw new Error("BackoffStrategy.next_() unimplemented.")},i.prototype.reset=function(){this.reset_()},i.prototype.reset_=function(){throw new Error("BackoffStrategy.reset_() unimplemented.")},t.exports=i},{events:157,util:333}],51:[function(e,t,r){"use strict";r.byteLength=function(e){return 3*e.length/4-c(e)},r.toByteArray=function(e){var t,r,n,a,s,u=e.length;a=c(e),s=new o(3*u/4-a),r=a>0?u-4:u;var f=0;for(t=0;t>16&255,s[f++]=n>>8&255,s[f++]=255&n;2===a?(n=i[e.charCodeAt(t)]<<2|i[e.charCodeAt(t+1)]>>4,s[f++]=255&n):1===a&&(n=i[e.charCodeAt(t)]<<10|i[e.charCodeAt(t+1)]<<4|i[e.charCodeAt(t+2)]>>2,s[f++]=n>>8&255,s[f++]=255&n);return s},r.fromByteArray=function(e){for(var t,r=e.length,i=r%3,o="",a=[],s=0,u=r-i;su?u:s+16383));1===i?(t=e[r-1],o+=n[t>>2],o+=n[t<<4&63],o+="=="):2===i&&(t=(e[r-2]<<8)+e[r-1],o+=n[t>>10],o+=n[t>>4&63],o+=n[t<<2&63],o+="=");return a.push(o),a.join("")};for(var n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,u=a.length;s0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===e[t-2]?2:"="===e[t-1]?1:0}function f(e,t,r){for(var i,o,a=[],s=t;s>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return a.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},{}],52:[function(e,t,r){var n=e("safe-buffer").Buffer;t.exports={check:function(e){if(e.length<8)return!1;if(e.length>72)return!1;if(48!==e[0])return!1;if(e[1]!==e.length-2)return!1;if(2!==e[2])return!1;var t=e[3];if(0===t)return!1;if(5+t>=e.length)return!1;if(2!==e[4+t])return!1;var r=e[5+t];return!(0===r||6+t+r!==e.length||128&e[4]||t>1&&0===e[4]&&!(128&e[5])||128&e[t+6]||r>1&&0===e[t+6]&&!(128&e[t+7]))},decode:function(e){if(e.length<8)throw new Error("DER sequence length is too short");if(e.length>72)throw new Error("DER sequence length is too long");if(48!==e[0])throw new Error("Expected DER sequence");if(e[1]!==e.length-2)throw new Error("DER sequence length is invalid");if(2!==e[2])throw new Error("Expected DER integer");var t=e[3];if(0===t)throw new Error("R length is zero");if(5+t>=e.length)throw new Error("R length is too long");if(2!==e[4+t])throw new Error("Expected DER integer (2)");var r=e[5+t];if(0===r)throw new Error("S length is zero");if(6+t+r!==e.length)throw new Error("S length is invalid");if(128&e[4])throw new Error("R value is negative");if(t>1&&0===e[4]&&!(128&e[5]))throw new Error("R value excessively padded");if(128&e[t+6])throw new Error("S value is negative");if(r>1&&0===e[t+6]&&!(128&e[t+7]))throw new Error("S value excessively padded");return{r:e.slice(4,4+t),s:e.slice(6+t)}},encode:function(e,t){var r=e.length,i=t.length;if(0===r)throw new Error("R length is zero");if(0===i)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(i>33)throw new Error("S length is too long");if(128&e[0])throw new Error("R value is negative");if(128&t[0])throw new Error("S value is negative");if(r>1&&0===e[0]&&!(128&e[1]))throw new Error("R value excessively padded");if(i>1&&0===t[0]&&!(128&t[1]))throw new Error("S value excessively padded");var o=n.allocUnsafe(6+r+i);return o[0]=48,o[1]=o.length-2,o[2]=2,o[3]=e.length,e.copy(o,4),o[4+r]=2,o[5+r]=t.length,t.copy(o,6+r),o}}},{"safe-buffer":290}],53:[function(e,t,r){!function(t,r){"use strict";function n(e,t){if(!e)throw new Error(t||"Assertion failed")}function i(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}function o(e,t,r){if(o.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(r=t,t=10),this._init(e||0,t||10,r||"be"))}var a;"object"==typeof t?t.exports=o:r.BN=o,o.BN=o,o.wordSize=26;try{a=e("buffer").Buffer}catch(e){}function s(e,t,r){for(var n=0,i=Math.min(e.length,r),o=t;o=49&&a<=54?a-49+10:a>=17&&a<=22?a-17+10:15&a}return n}function u(e,t,r,n){for(var i=0,o=Math.min(e.length,r),a=t;a=49?s-49+10:s>=17?s-17+10:s}return i}o.isBN=function(e){return e instanceof o||null!==e&&"object"==typeof e&&e.constructor.wordSize===o.wordSize&&Array.isArray(e.words)},o.max=function(e,t){return e.cmp(t)>0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&i++,16===t?this._parseHex(e,i):this._parseBase(e,t,i),"-"===e[0]&&(this.negative=1),this.strip(),"le"===r&&this._initArray(this.toArray(),t,r)},o.prototype._initNumber=function(e,t,r){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(n(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===r&&this._initArray(this.toArray(),t,r)},o.prototype._initArray=function(e,t,r){if(n("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3)a=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[o]|=a<>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);else if("le"===r)for(i=0,o=0;i>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);return this.strip()},o.prototype._parseHex=function(e,t){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var r=0;r=t;r-=6)i=s(e,r,r+6),this.words[n]|=i<>>26-o&4194303,(o+=24)>=26&&(o-=26,n++);r+6!==t&&(i=s(e,t,r+6),this.words[n]|=i<>>26-o&4194303),this.strip()},o.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=t)n++;n--,i=i/t|0;for(var o=e.length-r,a=o%n,s=Math.min(o,o-a)+r,c=0,f=r;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},o.prototype.inspect=function(){return(this.red?""};var c=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],f=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],h=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(e,t,r){r.negative=t.negative^e.negative;var n=e.length+t.length|0;r.length=n,n=n-1|0;var i=0|e.words[0],o=0|t.words[0],a=i*o,s=67108863&a,u=a/67108864|0;r.words[0]=s;for(var c=1;c>>26,h=67108863&u,l=Math.min(c,t.length-1),d=Math.max(0,c-e.length+1);d<=l;d++){var p=c-d|0;f+=(a=(i=0|e.words[p])*(o=0|t.words[d])+h)/67108864|0,h=67108863&a}r.words[c]=0|h,u=0|f}return 0!==u?r.words[c]=0|u:r.length--,r.strip()}o.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var i=0,o=0,a=0;a>>24-i&16777215)||a!==this.length-1?c[6-u.length]+u+r:u+r,(i+=2)>=26&&(i-=26,a--)}for(0!==o&&(r=o.toString(16)+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var l=f[e],d=h[e];r="";var p=this.clone();for(p.negative=0;!p.isZero();){var b=p.modn(d).toString(e);r=(p=p.idivn(d)).isZero()?b+r:c[l-b.length]+b+r}for(this.isZero()&&(r="0"+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16)},o.prototype.toBuffer=function(e,t){return n(void 0!==a),this.toArrayLike(a,e,t)},o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},o.prototype.toArrayLike=function(e,t,r){var i=this.byteLength(),o=r||Math.max(1,i);n(i<=o,"byte array longer than desired length"),n(o>0,"Requested array length <= 0"),this.strip();var a,s,u="le"===t,c=new e(o),f=this.clone();if(u){for(s=0;!f.isZero();s++)a=f.andln(255),f.iushrn(8),c[s]=a;for(;s=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;re.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,r;this.length>e.length?(t=this,r=e):(t=e,r=this);for(var n=0;ne.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-r),this.strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,i=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<e.length?(r=this,n=e):(r=e,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;oe.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var r,n,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=e):(r=e,n=this);for(var o=0,a=0;a>26,this.words[a]=67108863&t;for(;0!==o&&a>26,this.words[a]=67108863&t;if(0===o&&a>>13,d=0|a[1],p=8191&d,b=d>>>13,y=0|a[2],m=8191&y,v=y>>>13,g=0|a[3],w=8191&g,_=g>>>13,A=0|a[4],E=8191&A,x=A>>>13,k=0|a[5],S=8191&k,M=k>>>13,I=0|a[6],T=8191&I,U=I>>>13,j=0|a[7],B=8191&j,P=j>>>13,C=0|a[8],N=8191&C,R=C>>>13,L=0|a[9],O=8191&L,D=L>>>13,F=0|s[0],q=8191&F,H=F>>>13,z=0|s[1],K=8191&z,V=z>>>13,G=0|s[2],W=8191&G,Y=G>>>13,X=0|s[3],Z=8191&X,J=X>>>13,$=0|s[4],Q=8191&$,ee=$>>>13,te=0|s[5],re=8191&te,ne=te>>>13,ie=0|s[6],oe=8191&ie,ae=ie>>>13,se=0|s[7],ue=8191&se,ce=se>>>13,fe=0|s[8],he=8191&fe,le=fe>>>13,de=0|s[9],pe=8191&de,be=de>>>13;r.negative=e.negative^t.negative,r.length=19;var ye=(c+(n=Math.imul(h,q))|0)+((8191&(i=(i=Math.imul(h,H))+Math.imul(l,q)|0))<<13)|0;c=((o=Math.imul(l,H))+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,n=Math.imul(p,q),i=(i=Math.imul(p,H))+Math.imul(b,q)|0,o=Math.imul(b,H);var me=(c+(n=n+Math.imul(h,K)|0)|0)+((8191&(i=(i=i+Math.imul(h,V)|0)+Math.imul(l,K)|0))<<13)|0;c=((o=o+Math.imul(l,V)|0)+(i>>>13)|0)+(me>>>26)|0,me&=67108863,n=Math.imul(m,q),i=(i=Math.imul(m,H))+Math.imul(v,q)|0,o=Math.imul(v,H),n=n+Math.imul(p,K)|0,i=(i=i+Math.imul(p,V)|0)+Math.imul(b,K)|0,o=o+Math.imul(b,V)|0;var ve=(c+(n=n+Math.imul(h,W)|0)|0)+((8191&(i=(i=i+Math.imul(h,Y)|0)+Math.imul(l,W)|0))<<13)|0;c=((o=o+Math.imul(l,Y)|0)+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,n=Math.imul(w,q),i=(i=Math.imul(w,H))+Math.imul(_,q)|0,o=Math.imul(_,H),n=n+Math.imul(m,K)|0,i=(i=i+Math.imul(m,V)|0)+Math.imul(v,K)|0,o=o+Math.imul(v,V)|0,n=n+Math.imul(p,W)|0,i=(i=i+Math.imul(p,Y)|0)+Math.imul(b,W)|0,o=o+Math.imul(b,Y)|0;var ge=(c+(n=n+Math.imul(h,Z)|0)|0)+((8191&(i=(i=i+Math.imul(h,J)|0)+Math.imul(l,Z)|0))<<13)|0;c=((o=o+Math.imul(l,J)|0)+(i>>>13)|0)+(ge>>>26)|0,ge&=67108863,n=Math.imul(E,q),i=(i=Math.imul(E,H))+Math.imul(x,q)|0,o=Math.imul(x,H),n=n+Math.imul(w,K)|0,i=(i=i+Math.imul(w,V)|0)+Math.imul(_,K)|0,o=o+Math.imul(_,V)|0,n=n+Math.imul(m,W)|0,i=(i=i+Math.imul(m,Y)|0)+Math.imul(v,W)|0,o=o+Math.imul(v,Y)|0,n=n+Math.imul(p,Z)|0,i=(i=i+Math.imul(p,J)|0)+Math.imul(b,Z)|0,o=o+Math.imul(b,J)|0;var we=(c+(n=n+Math.imul(h,Q)|0)|0)+((8191&(i=(i=i+Math.imul(h,ee)|0)+Math.imul(l,Q)|0))<<13)|0;c=((o=o+Math.imul(l,ee)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,n=Math.imul(S,q),i=(i=Math.imul(S,H))+Math.imul(M,q)|0,o=Math.imul(M,H),n=n+Math.imul(E,K)|0,i=(i=i+Math.imul(E,V)|0)+Math.imul(x,K)|0,o=o+Math.imul(x,V)|0,n=n+Math.imul(w,W)|0,i=(i=i+Math.imul(w,Y)|0)+Math.imul(_,W)|0,o=o+Math.imul(_,Y)|0,n=n+Math.imul(m,Z)|0,i=(i=i+Math.imul(m,J)|0)+Math.imul(v,Z)|0,o=o+Math.imul(v,J)|0,n=n+Math.imul(p,Q)|0,i=(i=i+Math.imul(p,ee)|0)+Math.imul(b,Q)|0,o=o+Math.imul(b,ee)|0;var _e=(c+(n=n+Math.imul(h,re)|0)|0)+((8191&(i=(i=i+Math.imul(h,ne)|0)+Math.imul(l,re)|0))<<13)|0;c=((o=o+Math.imul(l,ne)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,n=Math.imul(T,q),i=(i=Math.imul(T,H))+Math.imul(U,q)|0,o=Math.imul(U,H),n=n+Math.imul(S,K)|0,i=(i=i+Math.imul(S,V)|0)+Math.imul(M,K)|0,o=o+Math.imul(M,V)|0,n=n+Math.imul(E,W)|0,i=(i=i+Math.imul(E,Y)|0)+Math.imul(x,W)|0,o=o+Math.imul(x,Y)|0,n=n+Math.imul(w,Z)|0,i=(i=i+Math.imul(w,J)|0)+Math.imul(_,Z)|0,o=o+Math.imul(_,J)|0,n=n+Math.imul(m,Q)|0,i=(i=i+Math.imul(m,ee)|0)+Math.imul(v,Q)|0,o=o+Math.imul(v,ee)|0,n=n+Math.imul(p,re)|0,i=(i=i+Math.imul(p,ne)|0)+Math.imul(b,re)|0,o=o+Math.imul(b,ne)|0;var Ae=(c+(n=n+Math.imul(h,oe)|0)|0)+((8191&(i=(i=i+Math.imul(h,ae)|0)+Math.imul(l,oe)|0))<<13)|0;c=((o=o+Math.imul(l,ae)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,n=Math.imul(B,q),i=(i=Math.imul(B,H))+Math.imul(P,q)|0,o=Math.imul(P,H),n=n+Math.imul(T,K)|0,i=(i=i+Math.imul(T,V)|0)+Math.imul(U,K)|0,o=o+Math.imul(U,V)|0,n=n+Math.imul(S,W)|0,i=(i=i+Math.imul(S,Y)|0)+Math.imul(M,W)|0,o=o+Math.imul(M,Y)|0,n=n+Math.imul(E,Z)|0,i=(i=i+Math.imul(E,J)|0)+Math.imul(x,Z)|0,o=o+Math.imul(x,J)|0,n=n+Math.imul(w,Q)|0,i=(i=i+Math.imul(w,ee)|0)+Math.imul(_,Q)|0,o=o+Math.imul(_,ee)|0,n=n+Math.imul(m,re)|0,i=(i=i+Math.imul(m,ne)|0)+Math.imul(v,re)|0,o=o+Math.imul(v,ne)|0,n=n+Math.imul(p,oe)|0,i=(i=i+Math.imul(p,ae)|0)+Math.imul(b,oe)|0,o=o+Math.imul(b,ae)|0;var Ee=(c+(n=n+Math.imul(h,ue)|0)|0)+((8191&(i=(i=i+Math.imul(h,ce)|0)+Math.imul(l,ue)|0))<<13)|0;c=((o=o+Math.imul(l,ce)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,n=Math.imul(N,q),i=(i=Math.imul(N,H))+Math.imul(R,q)|0,o=Math.imul(R,H),n=n+Math.imul(B,K)|0,i=(i=i+Math.imul(B,V)|0)+Math.imul(P,K)|0,o=o+Math.imul(P,V)|0,n=n+Math.imul(T,W)|0,i=(i=i+Math.imul(T,Y)|0)+Math.imul(U,W)|0,o=o+Math.imul(U,Y)|0,n=n+Math.imul(S,Z)|0,i=(i=i+Math.imul(S,J)|0)+Math.imul(M,Z)|0,o=o+Math.imul(M,J)|0,n=n+Math.imul(E,Q)|0,i=(i=i+Math.imul(E,ee)|0)+Math.imul(x,Q)|0,o=o+Math.imul(x,ee)|0,n=n+Math.imul(w,re)|0,i=(i=i+Math.imul(w,ne)|0)+Math.imul(_,re)|0,o=o+Math.imul(_,ne)|0,n=n+Math.imul(m,oe)|0,i=(i=i+Math.imul(m,ae)|0)+Math.imul(v,oe)|0,o=o+Math.imul(v,ae)|0,n=n+Math.imul(p,ue)|0,i=(i=i+Math.imul(p,ce)|0)+Math.imul(b,ue)|0,o=o+Math.imul(b,ce)|0;var xe=(c+(n=n+Math.imul(h,he)|0)|0)+((8191&(i=(i=i+Math.imul(h,le)|0)+Math.imul(l,he)|0))<<13)|0;c=((o=o+Math.imul(l,le)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,n=Math.imul(O,q),i=(i=Math.imul(O,H))+Math.imul(D,q)|0,o=Math.imul(D,H),n=n+Math.imul(N,K)|0,i=(i=i+Math.imul(N,V)|0)+Math.imul(R,K)|0,o=o+Math.imul(R,V)|0,n=n+Math.imul(B,W)|0,i=(i=i+Math.imul(B,Y)|0)+Math.imul(P,W)|0,o=o+Math.imul(P,Y)|0,n=n+Math.imul(T,Z)|0,i=(i=i+Math.imul(T,J)|0)+Math.imul(U,Z)|0,o=o+Math.imul(U,J)|0,n=n+Math.imul(S,Q)|0,i=(i=i+Math.imul(S,ee)|0)+Math.imul(M,Q)|0,o=o+Math.imul(M,ee)|0,n=n+Math.imul(E,re)|0,i=(i=i+Math.imul(E,ne)|0)+Math.imul(x,re)|0,o=o+Math.imul(x,ne)|0,n=n+Math.imul(w,oe)|0,i=(i=i+Math.imul(w,ae)|0)+Math.imul(_,oe)|0,o=o+Math.imul(_,ae)|0,n=n+Math.imul(m,ue)|0,i=(i=i+Math.imul(m,ce)|0)+Math.imul(v,ue)|0,o=o+Math.imul(v,ce)|0,n=n+Math.imul(p,he)|0,i=(i=i+Math.imul(p,le)|0)+Math.imul(b,he)|0,o=o+Math.imul(b,le)|0;var ke=(c+(n=n+Math.imul(h,pe)|0)|0)+((8191&(i=(i=i+Math.imul(h,be)|0)+Math.imul(l,pe)|0))<<13)|0;c=((o=o+Math.imul(l,be)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,n=Math.imul(O,K),i=(i=Math.imul(O,V))+Math.imul(D,K)|0,o=Math.imul(D,V),n=n+Math.imul(N,W)|0,i=(i=i+Math.imul(N,Y)|0)+Math.imul(R,W)|0,o=o+Math.imul(R,Y)|0,n=n+Math.imul(B,Z)|0,i=(i=i+Math.imul(B,J)|0)+Math.imul(P,Z)|0,o=o+Math.imul(P,J)|0,n=n+Math.imul(T,Q)|0,i=(i=i+Math.imul(T,ee)|0)+Math.imul(U,Q)|0,o=o+Math.imul(U,ee)|0,n=n+Math.imul(S,re)|0,i=(i=i+Math.imul(S,ne)|0)+Math.imul(M,re)|0,o=o+Math.imul(M,ne)|0,n=n+Math.imul(E,oe)|0,i=(i=i+Math.imul(E,ae)|0)+Math.imul(x,oe)|0,o=o+Math.imul(x,ae)|0,n=n+Math.imul(w,ue)|0,i=(i=i+Math.imul(w,ce)|0)+Math.imul(_,ue)|0,o=o+Math.imul(_,ce)|0,n=n+Math.imul(m,he)|0,i=(i=i+Math.imul(m,le)|0)+Math.imul(v,he)|0,o=o+Math.imul(v,le)|0;var Se=(c+(n=n+Math.imul(p,pe)|0)|0)+((8191&(i=(i=i+Math.imul(p,be)|0)+Math.imul(b,pe)|0))<<13)|0;c=((o=o+Math.imul(b,be)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,n=Math.imul(O,W),i=(i=Math.imul(O,Y))+Math.imul(D,W)|0,o=Math.imul(D,Y),n=n+Math.imul(N,Z)|0,i=(i=i+Math.imul(N,J)|0)+Math.imul(R,Z)|0,o=o+Math.imul(R,J)|0,n=n+Math.imul(B,Q)|0,i=(i=i+Math.imul(B,ee)|0)+Math.imul(P,Q)|0,o=o+Math.imul(P,ee)|0,n=n+Math.imul(T,re)|0,i=(i=i+Math.imul(T,ne)|0)+Math.imul(U,re)|0,o=o+Math.imul(U,ne)|0,n=n+Math.imul(S,oe)|0,i=(i=i+Math.imul(S,ae)|0)+Math.imul(M,oe)|0,o=o+Math.imul(M,ae)|0,n=n+Math.imul(E,ue)|0,i=(i=i+Math.imul(E,ce)|0)+Math.imul(x,ue)|0,o=o+Math.imul(x,ce)|0,n=n+Math.imul(w,he)|0,i=(i=i+Math.imul(w,le)|0)+Math.imul(_,he)|0,o=o+Math.imul(_,le)|0;var Me=(c+(n=n+Math.imul(m,pe)|0)|0)+((8191&(i=(i=i+Math.imul(m,be)|0)+Math.imul(v,pe)|0))<<13)|0;c=((o=o+Math.imul(v,be)|0)+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863,n=Math.imul(O,Z),i=(i=Math.imul(O,J))+Math.imul(D,Z)|0,o=Math.imul(D,J),n=n+Math.imul(N,Q)|0,i=(i=i+Math.imul(N,ee)|0)+Math.imul(R,Q)|0,o=o+Math.imul(R,ee)|0,n=n+Math.imul(B,re)|0,i=(i=i+Math.imul(B,ne)|0)+Math.imul(P,re)|0,o=o+Math.imul(P,ne)|0,n=n+Math.imul(T,oe)|0,i=(i=i+Math.imul(T,ae)|0)+Math.imul(U,oe)|0,o=o+Math.imul(U,ae)|0,n=n+Math.imul(S,ue)|0,i=(i=i+Math.imul(S,ce)|0)+Math.imul(M,ue)|0,o=o+Math.imul(M,ce)|0,n=n+Math.imul(E,he)|0,i=(i=i+Math.imul(E,le)|0)+Math.imul(x,he)|0,o=o+Math.imul(x,le)|0;var Ie=(c+(n=n+Math.imul(w,pe)|0)|0)+((8191&(i=(i=i+Math.imul(w,be)|0)+Math.imul(_,pe)|0))<<13)|0;c=((o=o+Math.imul(_,be)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,n=Math.imul(O,Q),i=(i=Math.imul(O,ee))+Math.imul(D,Q)|0,o=Math.imul(D,ee),n=n+Math.imul(N,re)|0,i=(i=i+Math.imul(N,ne)|0)+Math.imul(R,re)|0,o=o+Math.imul(R,ne)|0,n=n+Math.imul(B,oe)|0,i=(i=i+Math.imul(B,ae)|0)+Math.imul(P,oe)|0,o=o+Math.imul(P,ae)|0,n=n+Math.imul(T,ue)|0,i=(i=i+Math.imul(T,ce)|0)+Math.imul(U,ue)|0,o=o+Math.imul(U,ce)|0,n=n+Math.imul(S,he)|0,i=(i=i+Math.imul(S,le)|0)+Math.imul(M,he)|0,o=o+Math.imul(M,le)|0;var Te=(c+(n=n+Math.imul(E,pe)|0)|0)+((8191&(i=(i=i+Math.imul(E,be)|0)+Math.imul(x,pe)|0))<<13)|0;c=((o=o+Math.imul(x,be)|0)+(i>>>13)|0)+(Te>>>26)|0,Te&=67108863,n=Math.imul(O,re),i=(i=Math.imul(O,ne))+Math.imul(D,re)|0,o=Math.imul(D,ne),n=n+Math.imul(N,oe)|0,i=(i=i+Math.imul(N,ae)|0)+Math.imul(R,oe)|0,o=o+Math.imul(R,ae)|0,n=n+Math.imul(B,ue)|0,i=(i=i+Math.imul(B,ce)|0)+Math.imul(P,ue)|0,o=o+Math.imul(P,ce)|0,n=n+Math.imul(T,he)|0,i=(i=i+Math.imul(T,le)|0)+Math.imul(U,he)|0,o=o+Math.imul(U,le)|0;var Ue=(c+(n=n+Math.imul(S,pe)|0)|0)+((8191&(i=(i=i+Math.imul(S,be)|0)+Math.imul(M,pe)|0))<<13)|0;c=((o=o+Math.imul(M,be)|0)+(i>>>13)|0)+(Ue>>>26)|0,Ue&=67108863,n=Math.imul(O,oe),i=(i=Math.imul(O,ae))+Math.imul(D,oe)|0,o=Math.imul(D,ae),n=n+Math.imul(N,ue)|0,i=(i=i+Math.imul(N,ce)|0)+Math.imul(R,ue)|0,o=o+Math.imul(R,ce)|0,n=n+Math.imul(B,he)|0,i=(i=i+Math.imul(B,le)|0)+Math.imul(P,he)|0,o=o+Math.imul(P,le)|0;var je=(c+(n=n+Math.imul(T,pe)|0)|0)+((8191&(i=(i=i+Math.imul(T,be)|0)+Math.imul(U,pe)|0))<<13)|0;c=((o=o+Math.imul(U,be)|0)+(i>>>13)|0)+(je>>>26)|0,je&=67108863,n=Math.imul(O,ue),i=(i=Math.imul(O,ce))+Math.imul(D,ue)|0,o=Math.imul(D,ce),n=n+Math.imul(N,he)|0,i=(i=i+Math.imul(N,le)|0)+Math.imul(R,he)|0,o=o+Math.imul(R,le)|0;var Be=(c+(n=n+Math.imul(B,pe)|0)|0)+((8191&(i=(i=i+Math.imul(B,be)|0)+Math.imul(P,pe)|0))<<13)|0;c=((o=o+Math.imul(P,be)|0)+(i>>>13)|0)+(Be>>>26)|0,Be&=67108863,n=Math.imul(O,he),i=(i=Math.imul(O,le))+Math.imul(D,he)|0,o=Math.imul(D,le);var Pe=(c+(n=n+Math.imul(N,pe)|0)|0)+((8191&(i=(i=i+Math.imul(N,be)|0)+Math.imul(R,pe)|0))<<13)|0;c=((o=o+Math.imul(R,be)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863;var Ce=(c+(n=Math.imul(O,pe))|0)+((8191&(i=(i=Math.imul(O,be))+Math.imul(D,pe)|0))<<13)|0;return c=((o=Math.imul(D,be))+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,u[0]=ye,u[1]=me,u[2]=ve,u[3]=ge,u[4]=we,u[5]=_e,u[6]=Ae,u[7]=Ee,u[8]=xe,u[9]=ke,u[10]=Se,u[11]=Me,u[12]=Ie,u[13]=Te,u[14]=Ue,u[15]=je,u[16]=Be,u[17]=Pe,u[18]=Ce,0!==c&&(u[19]=c,r.length++),r};function p(e,t,r){return(new b).mulp(e,t,r)}function b(e,t){this.x=e,this.y=t}Math.imul||(d=l),o.prototype.mulTo=function(e,t){var r=this.length+e.length;return 10===this.length&&10===e.length?d(this,e,t):r<63?l(this,e,t):r<1024?function(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,a&=67108863}r.words[o]=s,n=a,a=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,e,t):p(this,e,t)},b.prototype.makeRBT=function(e){for(var t=new Array(e),r=o.prototype._countBits(e)-1,n=0;n>=1;return n},b.prototype.permute=function(e,t,r,n,i,o){for(var a=0;a>>=1)i++;return 1<>>=13,r[2*a+1]=8191&o,o>>>=13;for(a=2*t;a>=26,t+=i/67108864|0,t+=o>>>26,this.words[r]=67108863&o}return 0!==t&&(this.words[r]=t,this.length++),this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),r=0;r>>i}return t}(e);if(0===t.length)return new o(1);for(var r=this,n=0;n=0);var t,r=e%26,i=(e-r)/26,o=67108863>>>26-r<<26-r;if(0!==r){var a=0;for(t=0;t>>26-r}a&&(this.words[t]=a,this.length++)}if(0!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t=0),i=t?(t-t%26)/26:0;var o=e%26,a=Math.min((e-o)/26,this.length),s=67108863^67108863>>>o<a)for(this.length-=a,c=0;c=0&&(0!==f||c>=i);c--){var h=0|this.words[c];this.words[c]=f<<26-o|h>>>o,f=h&s}return u&&0!==f&&(u.words[u.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},o.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,i=1<=0);var t=e%26,r=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var i=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(u/67108864|0),this.words[i+r]=67108863&o}for(;i>26,this.words[i+r]=67108863&o;if(0===s)return this.strip();for(n(-1===s),s=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},o.prototype._wordDiv=function(e,t){var r=(this.length,e.length),n=this.clone(),i=e,a=0|i.words[i.length-1];0!==(r=26-this._countBits(a))&&(i=i.ushln(r),n.iushln(r),a=0|i.words[i.length-1]);var s,u=n.length-i.length;if("mod"!==t){(s=new o(null)).length=u+1,s.words=new Array(s.length);for(var c=0;c=0;h--){var l=67108864*(0|n.words[i.length+h])+(0|n.words[i.length+h-1]);for(l=Math.min(l/a|0,67108863),n._ishlnsubmul(i,l,h);0!==n.negative;)l--,n.negative=0,n._ishlnsubmul(i,1,h),n.isZero()||(n.negative^=1);s&&(s.words[h]=l)}return s&&s.strip(),n.strip(),"div"!==t&&0!==r&&n.iushrn(r),{div:s||null,mod:n}},o.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(s=this.neg().divmod(e,t),"mod"!==t&&(i=s.div.neg()),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.iadd(e)),{div:i,mod:a}):0===this.negative&&0!==e.negative?(s=this.divmod(e.neg(),t),"mod"!==t&&(i=s.div.neg()),{div:i,mod:s.mod}):0!=(this.negative&e.negative)?(s=this.neg().divmod(e.neg(),t),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.isub(e)),{div:s.div,mod:a}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modn(e.words[0]))}:this._wordDiv(e,t);var i,a,s},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=0!==t.div.negative?t.mod.isub(e):t.mod,n=e.ushrn(1),i=e.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modn=function(e){n(e<=67108863);for(var t=(1<<26)%e,r=0,i=this.length-1;i>=0;i--)r=(t*r+(0|this.words[i]))%e;return r},o.prototype.idivn=function(e){n(e<=67108863);for(var t=0,r=this.length-1;r>=0;r--){var i=(0|this.words[r])+67108864*t;this.words[r]=i/e|0,t=i%e}return this.strip()},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new o(1),a=new o(0),s=new o(0),u=new o(1),c=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++c;for(var f=r.clone(),h=t.clone();!t.isZero();){for(var l=0,d=1;0==(t.words[0]&d)&&l<26;++l,d<<=1);if(l>0)for(t.iushrn(l);l-- >0;)(i.isOdd()||a.isOdd())&&(i.iadd(f),a.isub(h)),i.iushrn(1),a.iushrn(1);for(var p=0,b=1;0==(r.words[0]&b)&&p<26;++p,b<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(s.isOdd()||u.isOdd())&&(s.iadd(f),u.isub(h)),s.iushrn(1),u.iushrn(1);t.cmp(r)>=0?(t.isub(r),i.isub(s),a.isub(u)):(r.isub(t),s.isub(i),u.isub(a))}return{a:s,b:u,gcd:r.iushln(c)}},o.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,a=new o(1),s=new o(0),u=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var c=0,f=1;0==(t.words[0]&f)&&c<26;++c,f<<=1);if(c>0)for(t.iushrn(c);c-- >0;)a.isOdd()&&a.iadd(u),a.iushrn(1);for(var h=0,l=1;0==(r.words[0]&l)&&h<26;++h,l<<=1);if(h>0)for(r.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(u),s.iushrn(1);t.cmp(r)>=0?(t.isub(r),a.isub(s)):(r.isub(t),s.isub(a))}return(i=0===t.cmpn(1)?a:s).cmpn(0)<0&&i.iadd(e),i},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var n=0;t.isEven()&&r.isEven();n++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=t.cmp(r);if(i<0){var o=t;t=r,r=o}else if(0===i||0===r.cmpn(1))break;t.isub(r)}return r.iushln(n)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return 0==(1&this.words[0])},o.prototype.isOdd=function(){return 1==(1&this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,i=1<>>26,s&=67108863,this.words[a]=s}return 0!==o&&(this.words[a]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this.strip(),this.length>1)t=1;else{r&&(e=-e),n(e<=67108863,"Number is too big");var i=0|this.words[0];t=i===e?0:ie.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|e.words[r];if(n!==i){ni&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new A(e)},o.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var y={k256:null,p224:null,p192:null,p25519:null};function m(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function v(){m.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function g(){m.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function w(){m.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function _(){m.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function A(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function E(e){A.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(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)}m.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},m.prototype.ireduce=function(e){var t,r=e;do{this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(t>this.n);var n=t0?r.isub(this.p):r.strip(),r},m.prototype.split=function(e,t){e.iushrn(this.n,0,t)},m.prototype.imulK=function(e){return e.imul(this.k)},i(v,m),v.prototype.split=function(e,t){for(var r=Math.min(e.length,9),n=0;n>>22,i=o}i>>>=22,e.words[n-10]=i,0===i&&e.length>10?e.length-=10:e.length-=9},v.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r>>=26,e.words[r]=i,t=n}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(y[e])return y[e];var t;if("k256"===e)t=new v;else if("p224"===e)t=new g;else if("p192"===e)t=new w;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new _}return y[e]=t,t},A.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},A.prototype._verify2=function(e,t){n(0==(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},A.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},A.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},A.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},A.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},A.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},A.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},A.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},A.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},A.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},A.prototype.isqr=function(e){return this.imul(e,e.clone())},A.prototype.sqr=function(e){return this.mul(e,e)},A.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var r=this.m.add(new o(1)).iushrn(2);return this.pow(e,r)}for(var i=this.m.subn(1),a=0;!i.isZero()&&0===i.andln(1);)a++,i.iushrn(1);n(!i.isZero());var s=new o(1).toRed(this),u=s.redNeg(),c=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new o(2*f*f).toRed(this);0!==this.pow(f,c).cmp(u);)f.redIAdd(u);for(var h=this.pow(f,i),l=this.pow(e,i.addn(1).iushrn(1)),d=this.pow(e,i),p=a;0!==d.cmp(s);){for(var b=d,y=0;0!==b.cmp(s);y++)b=b.redSqr();n(y=0;n--){for(var c=t.words[n],f=u-1;f>=0;f--){var h=c>>f&1;i!==r[0]&&(i=this.sqr(i)),0!==h||0!==a?(a<<=1,a|=h,(4===++s||0===n&&0===f)&&(i=this.mul(i,r[a]),s=0,a=0)):s=0}u=26}return i},A.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},A.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new E(e)},i(E,A),E.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},E.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},E.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},E.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var r=e.mul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},E.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===t||t,this)},{buffer:55}],54:[function(e,t,r){var n;function i(e){this.rand=e}if(t.exports=function(e){return n||(n=new i(null)),n.generate(e)},t.exports.Rand=i,i.prototype.generate=function(e){return this._rand(e)},i.prototype._rand=function(e){if(this.rand.getBytes)return this.rand.getBytes(e);for(var t=new Uint8Array(e),r=0;r>>24]^f[p>>>16&255]^h[b>>>8&255]^l[255&y]^t[m++],a=c[p>>>24]^f[b>>>16&255]^h[y>>>8&255]^l[255&d]^t[m++],s=c[b>>>24]^f[y>>>16&255]^h[d>>>8&255]^l[255&p]^t[m++],u=c[y>>>24]^f[d>>>16&255]^h[p>>>8&255]^l[255&b]^t[m++],d=o,p=a,b=s,y=u;return o=(n[d>>>24]<<24|n[p>>>16&255]<<16|n[b>>>8&255]<<8|n[255&y])^t[m++],a=(n[p>>>24]<<24|n[b>>>16&255]<<16|n[y>>>8&255]<<8|n[255&d])^t[m++],s=(n[b>>>24]<<24|n[y>>>16&255]<<16|n[d>>>8&255]<<8|n[255&p])^t[m++],u=(n[y>>>24]<<24|n[d>>>16&255]<<16|n[p>>>8&255]<<8|n[255&b])^t[m++],[o>>>=0,a>>>=0,s>>>=0,u>>>=0]}var s=[0,1,2,4,8,16,32,64,128,27,54],u=function(){for(var e=new Array(256),t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;for(var r=[],n=[],i=[[],[],[],[]],o=[[],[],[],[]],a=0,s=0,u=0;u<256;++u){var c=s^s<<1^s<<2^s<<3^s<<4;c=c>>>8^255&c^99,r[a]=c,n[c]=a;var f=e[a],h=e[f],l=e[h],d=257*e[c]^16843008*c;i[0][a]=d<<24|d>>>8,i[1][a]=d<<16|d>>>16,i[2][a]=d<<8|d>>>24,i[3][a]=d,d=16843009*l^65537*h^257*f^16843008*a,o[0][c]=d<<24|d>>>8,o[1][c]=d<<16|d>>>16,o[2][c]=d<<8|d>>>24,o[3][c]=d,0===a?a=s=1:(a=f^e[e[e[l^f]]],s^=e[e[s]])}return{SBOX:r,INV_SBOX:n,SUB_MIX:i,INV_SUB_MIX:o}}();function c(e){this._key=i(e),this._reset()}c.blockSize=16,c.keySize=32,c.prototype.blockSize=c.blockSize,c.prototype.keySize=c.keySize,c.prototype._reset=function(){for(var e=this._key,t=e.length,r=t+6,n=4*(r+1),i=[],o=0;o>>24,a=u.SBOX[a>>>24]<<24|u.SBOX[a>>>16&255]<<16|u.SBOX[a>>>8&255]<<8|u.SBOX[255&a],a^=s[o/t|0]<<24):t>6&&o%t==4&&(a=u.SBOX[a>>>24]<<24|u.SBOX[a>>>16&255]<<16|u.SBOX[a>>>8&255]<<8|u.SBOX[255&a]),i[o]=i[o-t]^a}for(var c=[],f=0;f>>24]]^u.INV_SUB_MIX[1][u.SBOX[l>>>16&255]]^u.INV_SUB_MIX[2][u.SBOX[l>>>8&255]]^u.INV_SUB_MIX[3][u.SBOX[255&l]]}this._nRounds=r,this._keySchedule=i,this._invKeySchedule=c},c.prototype.encryptBlockRaw=function(e){return a(e=i(e),this._keySchedule,u.SUB_MIX,u.SBOX,this._nRounds)},c.prototype.encryptBlock=function(e){var t=this.encryptBlockRaw(e),r=n.allocUnsafe(16);return r.writeUInt32BE(t[0],0),r.writeUInt32BE(t[1],4),r.writeUInt32BE(t[2],8),r.writeUInt32BE(t[3],12),r},c.prototype.decryptBlock=function(e){var t=(e=i(e))[1];e[1]=e[3],e[3]=t;var r=a(e,this._invKeySchedule,u.INV_SUB_MIX,u.INV_SBOX,this._nRounds),o=n.allocUnsafe(16);return o.writeUInt32BE(r[0],0),o.writeUInt32BE(r[3],4),o.writeUInt32BE(r[2],8),o.writeUInt32BE(r[1],12),o},c.prototype.scrub=function(){o(this._keySchedule),o(this._invKeySchedule),o(this._key)},t.exports.AES=c},{"safe-buffer":290}],57:[function(e,t,r){var n=e("./aes"),i=e("safe-buffer").Buffer,o=e("cipher-base"),a=e("inherits"),s=e("./ghash"),u=e("buffer-xor"),c=e("./incr32");function f(e,t,r,a){o.call(this);var u=i.alloc(4,0);this._cipher=new n.AES(t);var f=this._cipher.encryptBlock(u);this._ghash=new s(f),r=function(e,t,r){if(12===t.length)return e._finID=i.concat([t,i.from([0,0,0,1])]),i.concat([t,i.from([0,0,0,2])]);var n=new s(r),o=t.length,a=o%16;n.update(t),a&&(a=16-a,n.update(i.alloc(a,0))),n.update(i.alloc(8,0));var u=8*o,f=i.alloc(8);f.writeUIntBE(u,0,8),n.update(f),e._finID=n.state;var h=i.from(e._finID);return c(h),h}(this,r,f),this._prev=i.from(r),this._cache=i.allocUnsafe(0),this._secCache=i.allocUnsafe(0),this._decrypt=a,this._alen=0,this._len=0,this._mode=e,this._authTag=null,this._called=!1}a(f,o),f.prototype._update=function(e){if(!this._called&&this._alen){var t=16-this._alen%16;t<16&&(t=i.alloc(t,0),this._ghash.update(t))}this._called=!0;var r=this._mode.encrypt(this,e);return this._decrypt?this._ghash.update(e):this._ghash.update(r),this._len+=e.length,r},f.prototype._final=function(){if(this._decrypt&&!this._authTag)throw new Error("Unsupported state or unable to authenticate data");var e=u(this._ghash.final(8*this._alen,8*this._len),this._cipher.encryptBlock(this._finID));if(this._decrypt&&function(e,t){var r=0;e.length!==t.length&&r++;for(var n=Math.min(e.length,t.length),i=0;i16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t}else if(this.cache.length>=16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t;return null},h.prototype.flush=function(){if(this.cache.length)return this.cache},r.createDecipher=function(e,t){var r=o[e.toLowerCase()];if(!r)throw new TypeError("invalid suite type");var n=c(t,!1,r.key,r.iv);return l(e,n.key,n.iv)},r.createDecipheriv=l},{"./aes":56,"./authCipher":57,"./modes":69,"./streamCipher":72,"cipher-base":86,evp_bytestokey:158,inherits:180,"safe-buffer":290}],60:[function(e,t,r){var n=e("./modes"),i=e("./authCipher"),o=e("safe-buffer").Buffer,a=e("./streamCipher"),s=e("cipher-base"),u=e("./aes"),c=e("evp_bytestokey");function f(e,t,r){s.call(this),this._cache=new l,this._cipher=new u.AES(t),this._prev=o.from(r),this._mode=e,this._autopadding=!0}e("inherits")(f,s),f.prototype._update=function(e){var t,r;this._cache.add(e);for(var n=[];t=this._cache.get();)r=this._mode.encrypt(this,t),n.push(r);return o.concat(n)};var h=o.alloc(16,16);function l(){this.cache=o.allocUnsafe(0)}function d(e,t,r){var s=n[e.toLowerCase()];if(!s)throw new TypeError("invalid suite type");if("string"==typeof t&&(t=o.from(t)),t.length!==s.key/8)throw new TypeError("invalid key length "+t.length);if("string"==typeof r&&(r=o.from(r)),"GCM"!==s.mode&&r.length!==s.iv)throw new TypeError("invalid iv length "+r.length);return"stream"===s.type?new a(s.module,t,r):"auth"===s.type?new i(s.module,t,r):new f(s.module,t,r)}f.prototype._final=function(){var e=this._cache.flush();if(this._autopadding)return e=this._mode.encrypt(this,e),this._cipher.scrub(),e;if(!e.equals(h))throw this._cipher.scrub(),new Error("data not multiple of block length")},f.prototype.setAutoPadding=function(e){return this._autopadding=!!e,this},l.prototype.add=function(e){this.cache=o.concat([this.cache,e])},l.prototype.get=function(){if(this.cache.length>15){var e=this.cache.slice(0,16);return this.cache=this.cache.slice(16),e}return null},l.prototype.flush=function(){for(var e=16-this.cache.length,t=o.allocUnsafe(e),r=-1;++r>>0,0),t.writeUInt32BE(e[1]>>>0,4),t.writeUInt32BE(e[2]>>>0,8),t.writeUInt32BE(e[3]>>>0,12),t}function a(e){this.h=e,this.state=n.alloc(16,0),this.cache=n.allocUnsafe(0)}a.prototype.ghash=function(e){for(var t=-1;++t0;t--)n[t]=n[t]>>>1|(1&n[t-1])<<31;n[0]=n[0]>>>1,r&&(n[0]=n[0]^225<<24)}this.state=o(i)},a.prototype.update=function(e){var t;for(this.cache=n.concat([this.cache,e]);this.cache.length>=16;)t=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(t)},a.prototype.final=function(e,t){return this.cache.length&&this.ghash(n.concat([this.cache,i],16)),this.ghash(o([0,e,0,t])),this.state},t.exports=a},{"safe-buffer":290}],62:[function(e,t,r){t.exports=function(e){for(var t,r=e.length;r--;){if(255!==(t=e.readUInt8(r))){t++,e.writeUInt8(t,r);break}e.writeUInt8(0,r)}}},{}],63:[function(e,t,r){var n=e("buffer-xor");r.encrypt=function(e,t){var r=n(t,e._prev);return e._prev=e._cipher.encryptBlock(r),e._prev},r.decrypt=function(e,t){var r=e._prev;e._prev=t;var i=e._cipher.decryptBlock(t);return n(i,r)}},{"buffer-xor":83}],64:[function(e,t,r){var n=e("safe-buffer").Buffer,i=e("buffer-xor");function o(e,t,r){var o=t.length,a=i(t,e._cache);return e._cache=e._cache.slice(o),e._prev=n.concat([e._prev,r?t:a]),a}r.encrypt=function(e,t,r){for(var i,a=n.allocUnsafe(0);t.length;){if(0===e._cache.length&&(e._cache=e._cipher.encryptBlock(e._prev),e._prev=n.allocUnsafe(0)),!(e._cache.length<=t.length)){a=n.concat([a,o(e,t,r)]);break}i=e._cache.length,a=n.concat([a,o(e,t.slice(0,i),r)]),t=t.slice(i)}return a}},{"buffer-xor":83,"safe-buffer":290}],65:[function(e,t,r){var n=e("safe-buffer").Buffer;function i(e,t,r){for(var n,i,a=-1,s=0;++a<8;)n=t&1<<7-a?128:0,s+=(128&(i=e._cipher.encryptBlock(e._prev)[0]^n))>>a%8,e._prev=o(e._prev,r?n:i);return s}function o(e,t){var r=e.length,i=-1,o=n.allocUnsafe(e.length);for(e=n.concat([e,n.from([t])]);++i>7;return o}r.encrypt=function(e,t,r){for(var o=t.length,a=n.allocUnsafe(o),s=-1;++s=0||!r.umod(e.prime1)||!r.umod(e.prime2);)r=new n(i(t));return r}t.exports=o,o.getr=a}).call(this,e("buffer").Buffer)},{"bn.js":53,buffer:84,randombytes:270}],77:[function(e,t,r){t.exports=e("./browser/algorithms.json")},{"./browser/algorithms.json":78}],78:[function(e,t,r){t.exports={sha224WithRSAEncryption:{sign:"rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},"RSA-SHA224":{sign:"ecdsa/rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},sha256WithRSAEncryption:{sign:"rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},"RSA-SHA256":{sign:"ecdsa/rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},sha384WithRSAEncryption:{sign:"rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},"RSA-SHA384":{sign:"ecdsa/rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},sha512WithRSAEncryption:{sign:"rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA512":{sign:"ecdsa/rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA1":{sign:"rsa",hash:"sha1",id:"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{sign:"ecdsa",hash:"sha1",id:""},sha256:{sign:"ecdsa",hash:"sha256",id:""},sha224:{sign:"ecdsa",hash:"sha224",id:""},sha384:{sign:"ecdsa",hash:"sha384",id:""},sha512:{sign:"ecdsa",hash:"sha512",id:""},"DSA-SHA":{sign:"dsa",hash:"sha1",id:""},"DSA-SHA1":{sign:"dsa",hash:"sha1",id:""},DSA:{sign:"dsa",hash:"sha1",id:""},"DSA-WITH-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-WITH-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-WITH-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-WITH-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-RIPEMD160":{sign:"dsa",hash:"rmd160",id:""},ripemd160WithRSA:{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},"RSA-RIPEMD160":{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},md5WithRSAEncryption:{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"},"RSA-MD5":{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"}}},{}],79:[function(e,t,r){t.exports={"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"}},{}],80:[function(e,t,r){(function(r){var n=e("create-hash"),i=e("stream"),o=e("inherits"),a=e("./sign"),s=e("./verify"),u=e("./algorithms.json");function c(e){i.Writable.call(this);var t=u[e];if(!t)throw new Error("Unknown message digest");this._hashType=t.hash,this._hash=n(t.hash),this._tag=t.id,this._signType=t.sign}function f(e){i.Writable.call(this);var t=u[e];if(!t)throw new Error("Unknown message digest");this._hash=n(t.hash),this._tag=t.id,this._signType=t.sign}function h(e){return new c(e)}function l(e){return new f(e)}Object.keys(u).forEach(function(e){u[e].id=new r(u[e].id,"hex"),u[e.toLowerCase()]=u[e]}),o(c,i.Writable),c.prototype._write=function(e,t,r){this._hash.update(e),r()},c.prototype.update=function(e,t){return"string"==typeof e&&(e=new r(e,t)),this._hash.update(e),this},c.prototype.sign=function(e,t){this.end();var r=this._hash.digest(),n=a(r,e,this._hashType,this._signType,this._tag);return t?n.toString(t):n},o(f,i.Writable),f.prototype._write=function(e,t,r){this._hash.update(e),r()},f.prototype.update=function(e,t){return"string"==typeof e&&(e=new r(e,t)),this._hash.update(e),this},f.prototype.verify=function(e,t,n){"string"==typeof t&&(t=new r(t,n)),this.end();var i=this._hash.digest();return s(t,i,e,this._signType,this._tag)},t.exports={Sign:h,Verify:l,createSign:h,createVerify:l}}).call(this,e("buffer").Buffer)},{"./algorithms.json":78,"./sign":81,"./verify":82,buffer:84,"create-hash":91,inherits:180,stream:311}],81:[function(e,t,r){(function(r){var n=e("create-hmac"),i=e("browserify-rsa"),o=e("elliptic").ec,a=e("bn.js"),s=e("parse-asn1"),u=e("./curves.json");function c(e,t,i,o){if((e=new r(e.toArray())).length0&&r.ishrn(n),r}function h(e,t,i){var o,a;do{for(o=new r(0);8*o.length=t)throw new Error("invalid sig")}t.exports=function(e,t,u,c,f){var h=o(u);if("ec"===h.type){if("ecdsa"!==c&&"ecdsa/rsa"!==c)throw new Error("wrong public key type");return function(e,t,r){var n=a[r.data.algorithm.curve.join(".")];if(!n)throw new Error("unknown curve "+r.data.algorithm.curve.join("."));var o=new i(n),s=r.data.subjectPrivateKey.data;return o.verify(t,e,s)}(e,t,h)}if("dsa"===h.type){if("dsa"!==c)throw new Error("wrong public key type");return function(e,t,r){var i=r.data.p,a=r.data.q,u=r.data.g,c=r.data.pub_key,f=o.signature.decode(e,"der"),h=f.s,l=f.r;s(h,a),s(l,a);var d=n.mont(i),p=h.invm(a);return 0===u.toRed(d).redPow(new n(t).mul(p).mod(a)).fromRed().mul(c.toRed(d).redPow(l.mul(p).mod(a)).fromRed()).mod(i).mod(a).cmp(l)}(e,t,h)}if("rsa"!==c&&"ecdsa/rsa"!==c)throw new Error("wrong public key type");t=r.concat([f,t]);for(var l=h.modulus.byteLength(),d=[1],p=0;t.length+d.length+2o)throw new RangeError("Invalid typed array length");var t=new Uint8Array(e);return t.__proto__=s.prototype,t}function s(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return f(e)}return u(e,t,r)}function u(e,t,r){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return F(e)?function(e,t,r){if(t<0||e.byteLength=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function d(e,t){if(s.isBuffer(e))return e.length;if(q(e)||F(e))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return L(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return O(e).length;default:if(n)return L(e).length;t=(""+t).toLowerCase(),n=!0}}function p(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function b(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),H(r=+r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=s.from(t,n)),s.isBuffer(t))return 0===t.length?-1:y(e,t,r,n,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):y(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function y(e,t,r,n,i){var o,a=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,r/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(i){var f=-1;for(o=r;os&&(r=s-u),o=r;o>=0;o--){for(var h=!0,l=0;li&&(n=i):n=i;var o=t.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var a=0;a>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function E(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function x(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i239?4:c>223?3:c>191?2:1;if(i+h<=r)switch(h){case 1:c<128&&(f=c);break;case 2:128==(192&(o=e[i+1]))&&(u=(31&c)<<6|63&o)>127&&(f=u);break;case 3:o=e[i+1],a=e[i+2],128==(192&o)&&128==(192&a)&&(u=(15&c)<<12|(63&o)<<6|63&a)>2047&&(u<55296||u>57343)&&(f=u);break;case 4:o=e[i+1],a=e[i+2],s=e[i+3],128==(192&o)&&128==(192&a)&&128==(192&s)&&(u=(15&c)<<18|(63&o)<<12|(63&a)<<6|63&s)>65535&&u<1114112&&(f=u)}null===f?(f=65533,h=1):f>65535&&(f-=65536,n.push(f>>>10&1023|55296),f=56320|1023&f),n.push(f),i+=h}return function(e){var t=e.length;if(t<=k)return String.fromCharCode.apply(String,e);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return I(this,t,r);case"utf8":case"utf-8":return x(this,t,r);case"ascii":return S(this,t,r);case"latin1":case"binary":return M(this,t,r);case"base64":return E(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}.apply(this,arguments)},s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.prototype.inspect=function(){var e="",t=r.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},s.prototype.compare=function(e,t,r,n,i){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;for(var o=(i>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0),u=Math.min(o,a),c=this.slice(n,i),f=e.slice(t,r),h=0;h>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return m(this,e,t,r);case"utf8":case"utf-8":return v(this,e,t,r);case"ascii":return g(this,e,t,r);case"latin1":case"binary":return w(this,e,t,r);case"base64":return _(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var k=4096;function S(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;in)&&(r=n);for(var i="",o=t;or)throw new RangeError("Trying to access beyond buffer length")}function j(e,t,r,n,i,o){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function B(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function P(e,t,r,n,o){return t=+t,r>>>=0,o||B(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function C(e,t,r,n,o){return t=+t,r>>>=0,o||B(e,0,r,8),i.write(e,t,r,n,52,8),r+8}s.prototype.slice=function(e,t){var r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||U(e,t,this.length);for(var n=this[e],i=1,o=0;++o>>=0,t>>>=0,r||U(e,t,this.length);for(var n=this[e+--t],i=1;t>0&&(i*=256);)n+=this[e+--t]*i;return n},s.prototype.readUInt8=function(e,t){return e>>>=0,t||U(e,1,this.length),this[e]},s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||U(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||U(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||U(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||U(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);for(var n=this[e],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*t)),n},s.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||U(e,t,this.length);for(var n=t,i=1,o=this[e+--n];n>0&&(i*=256);)o+=this[e+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*t)),o},s.prototype.readInt8=function(e,t){return e>>>=0,t||U(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||U(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt16BE=function(e,t){e>>>=0,t||U(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||U(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||U(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readFloatLE=function(e,t){return e>>>=0,t||U(e,4,this.length),i.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||U(e,4,this.length),i.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||U(e,8,this.length),i.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||U(e,8,this.length),i.read(this,e,!1,52,8)},s.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t>>>=0,r>>>=0,n)||j(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[t]=255&e;++o>>=0,r>>>=0,n)||j(this,e,t,r,Math.pow(2,8*r)-1,0);var i=r-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r},s.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);j(this,e,t,r,i-1,-i)}var o=0,a=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+r},s.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);j(this,e,t,r,i-1,-i)}var o=r-1,a=1,s=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a>>0)-s&255;return t+r},s.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeFloatLE=function(e,t,r){return P(this,e,t,!0,r)},s.prototype.writeFloatBE=function(e,t,r){return P(this,e,t,!1,r)},s.prototype.writeDoubleLE=function(e,t,r){return C(this,e,t,!0,r)},s.prototype.writeDoubleBE=function(e,t,r){return C(this,e,t,!1,r)},s.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--i)e[i+t]=this[i+r];else if(o<1e3)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function O(e){return n.toByteArray(function(e){if((e=e.trim().replace(N,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function D(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function F(e){return e instanceof ArrayBuffer||null!=e&&null!=e.constructor&&"ArrayBuffer"===e.constructor.name&&"number"==typeof e.byteLength}function q(e){return"function"==typeof ArrayBuffer.isView&&ArrayBuffer.isView(e)}function H(e){return e!=e}},{"base64-js":51,ieee754:178}],85:[function(e,t,r){t.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}},{}],86:[function(e,t,r){var n=e("safe-buffer").Buffer,i=e("stream").Transform,o=e("string_decoder").StringDecoder;function a(e){i.call(this),this.hashMode="string"==typeof e,this.hashMode?this[e]=this._finalOrDigest:this.final=this._finalOrDigest,this._final&&(this.__final=this._final,this._final=null),this._decoder=null,this._encoding=null}e("inherits")(a,i),a.prototype.update=function(e,t,r){"string"==typeof e&&(e=n.from(e,t));var i=this._update(e);return this.hashMode?this:(r&&(i=this._toString(i,r)),i)},a.prototype.setAutoPadding=function(){},a.prototype.getAuthTag=function(){throw new Error("trying to get auth tag in unsupported state")},a.prototype.setAuthTag=function(){throw new Error("trying to set auth tag in unsupported state")},a.prototype.setAAD=function(){throw new Error("trying to set aad in unsupported state")},a.prototype._transform=function(e,t,r){var n;try{this.hashMode?this._update(e):this.push(this._update(e))}catch(e){n=e}finally{r(n)}},a.prototype._flush=function(e){var t;try{this.push(this.__final())}catch(e){t=e}e(t)},a.prototype._finalOrDigest=function(e){var t=this.__final()||n.alloc(0);return e&&(t=this._toString(t,e,!0)),t},a.prototype._toString=function(e,t,r){if(this._decoder||(this._decoder=new o(t),this._encoding=t),this._encoding!==t)throw new Error("can't switch encodings");var n=this._decoder.write(e);return r&&(n+=this._decoder.end()),n},t.exports=a},{inherits:180,"safe-buffer":290,stream:311,string_decoder:317}],87:[function(e,t,r){(function(e){var r=function(){"use strict";function t(e,t){return null!=t&&e instanceof t}var r,n,i;try{r=Map}catch(e){r=function(){}}try{n=Set}catch(e){n=function(){}}try{i=Promise}catch(e){i=function(){}}function o(a,u,c,f,h){"object"==typeof u&&(c=u.depth,f=u.prototype,h=u.includeNonEnumerable,u=u.circular);var l=[],d=[],p=void 0!==e;return void 0===u&&(u=!0),void 0===c&&(c=1/0),function a(c,b){if(null===c)return null;if(0===b)return c;var y,m;if("object"!=typeof c)return c;if(t(c,r))y=new r;else if(t(c,n))y=new n;else if(t(c,i))y=new i(function(e,t){c.then(function(t){e(a(t,b-1))},function(e){t(a(e,b-1))})});else if(o.__isArray(c))y=[];else if(o.__isRegExp(c))y=new RegExp(c.source,s(c)),c.lastIndex&&(y.lastIndex=c.lastIndex);else if(o.__isDate(c))y=new Date(c.getTime());else{if(p&&e.isBuffer(c))return y=e.allocUnsafe?e.allocUnsafe(c.length):new e(c.length),c.copy(y),y;t(c,Error)?y=Object.create(c):void 0===f?(m=Object.getPrototypeOf(c),y=Object.create(m)):(y=Object.create(f),m=f)}if(u){var v=l.indexOf(c);if(-1!=v)return d[v];l.push(c),d.push(y)}for(var g in t(c,r)&&c.forEach(function(e,t){var r=a(t,b-1),n=a(e,b-1);y.set(r,n)}),t(c,n)&&c.forEach(function(e){var t=a(e,b-1);y.add(t)}),c){var w;m&&(w=Object.getOwnPropertyDescriptor(m,g)),w&&null==w.set||(y[g]=a(c[g],b-1))}if(Object.getOwnPropertySymbols){var _=Object.getOwnPropertySymbols(c);for(g=0;g<_.length;g++){var A=_[g];(!(x=Object.getOwnPropertyDescriptor(c,A))||x.enumerable||h)&&(y[A]=a(c[A],b-1),x.enumerable||Object.defineProperty(y,A,{enumerable:!1}))}}if(h){var E=Object.getOwnPropertyNames(c);for(g=0;g>>2),a=0,s=0;a>5]|=128<>>9<<4)]=t;for(var r=1732584193,n=-271733879,i=-1732584194,o=271733878,h=0;h>>32-s,r);var a,s}function a(e,t,r,n,i,a,s){return o(t&r|~t&n,e,t,i,a,s)}function s(e,t,r,n,i,a,s){return o(t&n|r&~n,e,t,i,a,s)}function u(e,t,r,n,i,a,s){return o(t^r^n,e,t,i,a,s)}function c(e,t,r,n,i,a,s){return o(r^(t|~n),e,t,i,a,s)}function f(e,t){var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}t.exports=function(e){return n(e,i)}},{"./make-hash":92}],94:[function(e,t,r){"use strict";var n=e("inherits"),i=e("./legacy"),o=e("cipher-base"),a=e("safe-buffer").Buffer,s=e("create-hash/md5"),u=e("ripemd160"),c=e("sha.js"),f=a.alloc(128);function h(e,t){o.call(this,"digest"),"string"==typeof t&&(t=a.from(t));var r="sha512"===e||"sha384"===e?128:64;(this._alg=e,this._key=t,t.length>r)?t=("rmd160"===e?new u:c(e)).update(t).digest():t.lengths?t=e(t):t.length-1};f.prototype.append=function(e,t){e=s(e),t=u(t);var r=this.map[e];this.map[e]=r?r+","+t:t},f.prototype.delete=function(e){delete this.map[s(e)]},f.prototype.get=function(e){return e=s(e),this.has(e)?this.map[e]:null},f.prototype.has=function(e){return this.map.hasOwnProperty(s(e))},f.prototype.set=function(e,t){this.map[s(e)]=u(t)},f.prototype.forEach=function(e,t){for(var r in this.map)this.map.hasOwnProperty(r)&&e.call(t,this.map[r],r,this)},f.prototype.keys=function(){var e=[];return this.forEach(function(t,r){e.push(r)}),c(e)},f.prototype.values=function(){var e=[];return this.forEach(function(t){e.push(t)}),c(e)},f.prototype.entries=function(){var e=[];return this.forEach(function(t,r){e.push([r,t])}),c(e)},t.iterable&&(f.prototype[Symbol.iterator]=f.prototype.entries);var o=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];y.prototype.clone=function(){return new y(this,{body:this._bodyInit})},b.call(y.prototype),b.call(v.prototype),v.prototype.clone=function(){return new v(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new f(this.headers),url:this.url})},v.error=function(){var e=new v(null,{status:0,statusText:""});return e.type="error",e};var a=[301,302,303,307,308];v.redirect=function(e,t){if(-1===a.indexOf(t))throw new RangeError("Invalid status code");return new v(null,{status:t,headers:{location:e}})},e.Headers=f,e.Request=y,e.Response=v,e.fetch=function(e,r){return new Promise(function(n,i){var o=new y(e,r),a=new XMLHttpRequest;a.onload=function(){var e,t,r={status:a.status,statusText:a.statusText,headers:(e=a.getAllResponseHeaders()||"",t=new f,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach(function(e){var r=e.split(":"),n=r.shift().trim();if(n){var i=r.join(":").trim();t.append(n,i)}}),t)};r.url="responseURL"in a?a.responseURL:r.headers.get("X-Request-URL");var i="response"in a?a.response:a.responseText;n(new v(i,r))},a.onerror=function(){i(new TypeError("Network request failed"))},a.ontimeout=function(){i(new TypeError("Network request failed"))},a.open(o.method,o.url,!0),"include"===o.credentials?a.withCredentials=!0:"omit"===o.credentials&&(a.withCredentials=!1),"responseType"in a&&t.blob&&(a.responseType="blob"),o.headers.forEach(function(e,t){a.setRequestHeader(t,e)}),a.send(void 0===o._bodyInit?null:o._bodyInit)})},e.fetch.polyfill=!0}function s(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function u(e){return"string"!=typeof e&&(e=String(e)),e}function c(e){var r={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return t.iterable&&(r[Symbol.iterator]=function(){return r}),r}function f(e){this.map={},e instanceof f?e.forEach(function(e,t){this.append(t,e)},this):Array.isArray(e)?e.forEach(function(e){this.append(e[0],e[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}function h(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function l(e){return new Promise(function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}})}function d(e){var t=new FileReader,r=l(t);return t.readAsArrayBuffer(e),r}function p(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function b(){return this.bodyUsed=!1,this._initBody=function(e){if(this._bodyInit=e,e)if("string"==typeof e)this._bodyText=e;else if(t.blob&&Blob.prototype.isPrototypeOf(e))this._bodyBlob=e;else if(t.formData&&FormData.prototype.isPrototypeOf(e))this._bodyFormData=e;else if(t.searchParams&&URLSearchParams.prototype.isPrototypeOf(e))this._bodyText=e.toString();else if(t.arrayBuffer&&t.blob&&n(e))this._bodyArrayBuffer=p(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer]);else{if(!t.arrayBuffer||!ArrayBuffer.prototype.isPrototypeOf(e)&&!i(e))throw new Error("unsupported BodyInit type");this._bodyArrayBuffer=p(e)}else this._bodyText="";this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):t.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},t.blob&&(this.blob=function(){var e=h(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?h(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(d)}),this.text=function(){var e,t,r,n=h(this);if(n)return n;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,r=l(t),t.readAsText(e),r;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),r=new Array(t.length),n=0;n-1?n:r),this.mode=t.mode||this.mode||null,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&i)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(i)}function m(e){var t=new FormData;return e.trim().split("&").forEach(function(e){if(e){var r=e.split("="),n=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");t.append(decodeURIComponent(n),decodeURIComponent(i))}}),t}function v(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new f(t.headers),this.url=t.url||"",this._initBody(e)}}(void 0!==e?e:this)}).call(n,void 0);var i=n.fetch;i.Response=n.Response,i.Request=n.Request,i.Headers=n.Headers;"object"==typeof t&&t.exports&&(t.exports=i,t.exports.default=i)},{}],97:[function(e,t,r){"use strict";r.randomBytes=r.rng=r.pseudoRandomBytes=r.prng=e("randombytes"),r.createHash=r.Hash=e("create-hash"),r.createHmac=r.Hmac=e("create-hmac");var n=e("browserify-sign/algos"),i=Object.keys(n),o=["sha1","sha224","sha256","sha384","sha512","md5","rmd160"].concat(i);r.getHashes=function(){return o};var a=e("pbkdf2");r.pbkdf2=a.pbkdf2,r.pbkdf2Sync=a.pbkdf2Sync;var s=e("browserify-cipher");r.Cipher=s.Cipher,r.createCipher=s.createCipher,r.Cipheriv=s.Cipheriv,r.createCipheriv=s.createCipheriv,r.Decipher=s.Decipher,r.createDecipher=s.createDecipher,r.Decipheriv=s.Decipheriv,r.createDecipheriv=s.createDecipheriv,r.getCiphers=s.getCiphers,r.listCiphers=s.listCiphers;var u=e("diffie-hellman");r.DiffieHellmanGroup=u.DiffieHellmanGroup,r.createDiffieHellmanGroup=u.createDiffieHellmanGroup,r.getDiffieHellman=u.getDiffieHellman,r.createDiffieHellman=u.createDiffieHellman,r.DiffieHellman=u.DiffieHellman;var c=e("browserify-sign");r.createSign=c.createSign,r.Sign=c.Sign,r.createVerify=c.createVerify,r.Verify=c.Verify,r.createECDH=e("create-ecdh");var f=e("public-encrypt");r.publicEncrypt=f.publicEncrypt,r.privateEncrypt=f.privateEncrypt,r.publicDecrypt=f.publicDecrypt,r.privateDecrypt=f.privateDecrypt;var h=e("randomfill");r.randomFill=h.randomFill,r.randomFillSync=h.randomFillSync,r.createCredentials=function(){throw new Error(["sorry, createCredentials is not implemented yet","we accept pull requests","https://github.com/crypto-browserify/crypto-browserify"].join("\n"))},r.constants={DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,NPN_ENABLED:1,ALPN_ENABLED:1,RSA_PKCS1_PADDING:1,RSA_SSLV23_PADDING:2,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,POINT_CONVERSION_COMPRESSED:2,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(e,t,r){"use strict";var n=new RegExp("%[a-f0-9]{2}","gi"),i=new RegExp("(%[a-f0-9]{2})+","gi");function o(e,t){try{return decodeURIComponent(e.join(""))}catch(e){}if(1===e.length)return e;t=t||1;var r=e.slice(0,t),n=e.slice(t);return Array.prototype.concat.call([],o(r),o(n))}function a(e){try{return decodeURIComponent(e)}catch(i){for(var t=e.match(n),r=1;r0;n--)t+=this._buffer(e,t),r+=this._flushBuffer(i,r);return t+=this._buffer(e,t),i},i.prototype.final=function(e){var t,r;return e&&(t=this.update(e)),r="encrypt"===this.type?this._finalEncrypt():this._finalDecrypt(),t?t.concat(r):r},i.prototype._pad=function(e,t){if(0===t)return!1;for(;t>>1];r=a.r28shl(r,s),i=a.r28shl(i,s),a.pc2(r,i,e.keys,o)}},u.prototype._update=function(e,t,r,n){var i=this._desState,o=a.readUInt32BE(e,t),s=a.readUInt32BE(e,t+4);a.ip(o,s,i.tmp,0),o=i.tmp[0],s=i.tmp[1],"encrypt"===this.type?this._encrypt(i,o,s,i.tmp,0):this._decrypt(i,o,s,i.tmp,0),o=i.tmp[0],s=i.tmp[1],a.writeUInt32BE(r,o,n),a.writeUInt32BE(r,s,n+4)},u.prototype._pad=function(e,t){for(var r=e.length-t,n=t;n>>0,o=l}a.rip(s,o,n,i)},u.prototype._decrypt=function(e,t,r,n,i){for(var o=r,s=t,u=e.keys.length-2;u>=0;u-=2){var c=e.keys[u],f=e.keys[u+1];a.expand(o,e.tmp,0),c^=e.tmp[0],f^=e.tmp[1];var h=a.substitute(c,f),l=o;o=(s^a.permute(h))>>>0,s=l}a.rip(o,s,n,i)}},{"../des":99,inherits:180,"minimalistic-assert":234}],103:[function(e,t,r){"use strict";var n=e("minimalistic-assert"),i=e("inherits"),o=e("../des"),a=o.Cipher,s=o.DES;function u(e){a.call(this,e);var t=new function(e,t){n.equal(t.length,24,"Invalid key length");var r=t.slice(0,8),i=t.slice(8,16),o=t.slice(16,24);this.ciphers="encrypt"===e?[s.create({type:"encrypt",key:r}),s.create({type:"decrypt",key:i}),s.create({type:"encrypt",key:o})]:[s.create({type:"decrypt",key:o}),s.create({type:"encrypt",key:i}),s.create({type:"decrypt",key:r})]}(this.type,this.options.key);this._edeState=t}i(u,a),t.exports=u,u.create=function(e){return new u(e)},u.prototype._update=function(e,t,r,n){var i=this._edeState;i.ciphers[0]._update(e,t,r,n),i.ciphers[1]._update(r,n,r,n),i.ciphers[2]._update(r,n,r,n)},u.prototype._pad=s.prototype._pad,u.prototype._unpad=s.prototype._unpad},{"../des":99,inherits:180,"minimalistic-assert":234}],104:[function(e,t,r){"use strict";r.readUInt32BE=function(e,t){return(e[0+t]<<24|e[1+t]<<16|e[2+t]<<8|e[3+t])>>>0},r.writeUInt32BE=function(e,t,r){e[0+r]=t>>>24,e[1+r]=t>>>16&255,e[2+r]=t>>>8&255,e[3+r]=255&t},r.ip=function(e,t,r,n){for(var i=0,o=0,a=6;a>=0;a-=2){for(var s=0;s<=24;s+=8)i<<=1,i|=t>>>s+a&1;for(s=0;s<=24;s+=8)i<<=1,i|=e>>>s+a&1}for(a=6;a>=0;a-=2){for(s=1;s<=25;s+=8)o<<=1,o|=t>>>s+a&1;for(s=1;s<=25;s+=8)o<<=1,o|=e>>>s+a&1}r[n+0]=i>>>0,r[n+1]=o>>>0},r.rip=function(e,t,r,n){for(var i=0,o=0,a=0;a<4;a++)for(var s=24;s>=0;s-=8)i<<=1,i|=t>>>s+a&1,i<<=1,i|=e>>>s+a&1;for(a=4;a<8;a++)for(s=24;s>=0;s-=8)o<<=1,o|=t>>>s+a&1,o<<=1,o|=e>>>s+a&1;r[n+0]=i>>>0,r[n+1]=o>>>0},r.pc1=function(e,t,r,n){for(var i=0,o=0,a=7;a>=5;a--){for(var s=0;s<=24;s+=8)i<<=1,i|=t>>s+a&1;for(s=0;s<=24;s+=8)i<<=1,i|=e>>s+a&1}for(s=0;s<=24;s+=8)i<<=1,i|=t>>s+a&1;for(a=1;a<=3;a++){for(s=0;s<=24;s+=8)o<<=1,o|=t>>s+a&1;for(s=0;s<=24;s+=8)o<<=1,o|=e>>s+a&1}for(s=0;s<=24;s+=8)o<<=1,o|=e>>s+a&1;r[n+0]=i>>>0,r[n+1]=o>>>0},r.r28shl=function(e,t){return e<>>28-t};var n=[14,11,17,4,27,23,25,0,13,22,7,18,5,9,16,24,2,20,12,21,1,8,15,26,15,4,25,19,9,1,26,16,5,11,23,8,12,7,17,0,22,3,10,14,6,20,27,24];r.pc2=function(e,t,r,i){for(var o=0,a=0,s=n.length>>>1,u=0;u>>n[u]&1;for(u=s;u>>n[u]&1;r[i+0]=o>>>0,r[i+1]=a>>>0},r.expand=function(e,t,r){var n=0,i=0;n=(1&e)<<5|e>>>27;for(var o=23;o>=15;o-=4)n<<=6,n|=e>>>o&63;for(o=11;o>=3;o-=4)i|=e>>>o&63,i<<=6;i|=(31&e)<<1|e>>>31,t[r+0]=n>>>0,t[r+1]=i>>>0};var i=[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];r.substitute=function(e,t){for(var r=0,n=0;n<4;n++){r<<=4,r|=i[64*n+(e>>>18-6*n&63)]}for(n=0;n<4;n++){r<<=4,r|=i[256+64*n+(t>>>18-6*n&63)]}return r>>>0};var o=[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];r.permute=function(e){for(var t=0,r=0;r>>o[r]&1;return t>>>0},r.padSplit=function(e,t,r){for(var n=e.toString(2);n.lengthe;)r.ishrn(1);if(r.isEven()&&r.iadd(s),r.testn(1)||r.iadd(u),t.cmp(u)){if(!t.cmp(c))for(;r.mod(f).cmp(h);)r.iadd(d)}else for(;r.mod(o).cmp(l);)r.iadd(d);if(y(p=r.shrn(1))&&y(r)&&m(p)&&m(r)&&a.test(p)&&a.test(r))return r}}},{"bn.js":53,"miller-rabin":233,randombytes:270}],108:[function(e,t,r){t.exports={modp1:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},modp2:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},modp5:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},modp14:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},modp15:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},modp16:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},modp17:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},modp18:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"}}},{}],109:[function(e,t,r){"use strict";var n=r;n.version=e("../package.json").version,n.utils=e("./elliptic/utils"),n.rand=e("brorand"),n.curve=e("./elliptic/curve"),n.curves=e("./elliptic/curves"),n.ec=e("./elliptic/ec"),n.eddsa=e("./elliptic/eddsa")},{"../package.json":124,"./elliptic/curve":112,"./elliptic/curves":115,"./elliptic/ec":116,"./elliptic/eddsa":119,"./elliptic/utils":123,brorand:54}],110:[function(e,t,r){"use strict";var n=e("bn.js"),i=e("../../elliptic").utils,o=i.getNAF,a=i.getJSF,s=i.assert;function u(e,t){this.type=e,this.p=new n(t.p,16),this.red=t.prime?n.red(t.prime):n.mont(this.p),this.zero=new n(0).toRed(this.red),this.one=new n(1).toRed(this.red),this.two=new n(2).toRed(this.red),this.n=t.n&&new n(t.n,16),this.g=t.g&&this.pointFromJSON(t.g,t.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4);var r=this.n&&this.p.div(this.n);!r||r.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}function c(e,t){this.curve=e,this.type=t,this.precomputed=null}t.exports=u,u.prototype.point=function(){throw new Error("Not implemented")},u.prototype.validate=function(){throw new Error("Not implemented")},u.prototype._fixedNafMul=function(e,t){s(e.precomputed);var r=e._getDoubles(),n=o(t,1),i=(1<=u;t--)c=(c<<1)+n[t];a.push(c)}for(var f=this.jpoint(null,null,null),h=this.jpoint(null,null,null),l=i;l>0;l--){for(u=0;u=0;c--){for(t=0;c>=0&&0===a[c];c--)t++;if(c>=0&&t++,u=u.dblp(t),c<0)break;var f=a[c];s(0!==f),u="affine"===e.type?f>0?u.mixedAdd(i[f-1>>1]):u.mixedAdd(i[-f-1>>1].neg()):f>0?u.add(i[f-1>>1]):u.add(i[-f-1>>1].neg())}return"affine"===e.type?u.toP():u},u.prototype._wnafMulAdd=function(e,t,r,n,i){for(var s=this._wnafT1,u=this._wnafT2,c=this._wnafT3,f=0,h=0;h=1;h-=2){var d=h-1,p=h;if(1===s[d]&&1===s[p]){var b=[t[d],null,null,t[p]];0===t[d].y.cmp(t[p].y)?(b[1]=t[d].add(t[p]),b[2]=t[d].toJ().mixedAdd(t[p].neg())):0===t[d].y.cmp(t[p].y.redNeg())?(b[1]=t[d].toJ().mixedAdd(t[p]),b[2]=t[d].add(t[p].neg())):(b[1]=t[d].toJ().mixedAdd(t[p]),b[2]=t[d].toJ().mixedAdd(t[p].neg()));var y=[-3,-1,-5,-7,0,7,5,1,3],m=a(r[d],r[p]);f=Math.max(m[0].length,f),c[d]=new Array(f),c[p]=new Array(f);for(var v=0;v=0;h--){for(var E=0;h>=0;){var x=!0;for(v=0;v=0&&E++,_=_.dblp(E),h<0)break;for(v=0;v0?k=u[v][S-1>>1]:S<0&&(k=u[v][-S-1>>1].neg()),_="affine"===k.type?_.mixedAdd(k):_.add(k))}}for(h=0;h=Math.ceil((e.bitLength()+1)/t.step)},c.prototype._getDoubles=function(e,t){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i":""},f.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&0===this.y.cmp(this.z)},f.prototype._extDbl=function(){var e=this.x.redSqr(),t=this.y.redSqr(),r=this.z.redSqr();r=r.redIAdd(r);var n=this.curve._mulA(e),i=this.x.redAdd(this.y).redSqr().redISub(e).redISub(t),o=n.redAdd(t),a=o.redSub(r),s=n.redSub(t),u=i.redMul(a),c=o.redMul(s),f=i.redMul(s),h=a.redMul(o);return this.curve.point(u,c,h,f)},f.prototype._projDbl=function(){var e,t,r,n=this.x.redAdd(this.y).redSqr(),i=this.x.redSqr(),o=this.y.redSqr();if(this.curve.twisted){var a=(c=this.curve._mulA(i)).redAdd(o);if(this.zOne)e=n.redSub(i).redSub(o).redMul(a.redSub(this.curve.two)),t=a.redMul(c.redSub(o)),r=a.redSqr().redSub(a).redSub(a);else{var s=this.z.redSqr(),u=a.redSub(s).redISub(s);e=n.redSub(i).redISub(o).redMul(u),t=a.redMul(c.redSub(o)),r=a.redMul(u)}}else{var c=i.redAdd(o);s=this.curve._mulC(this.c.redMul(this.z)).redSqr(),u=c.redSub(s).redSub(s);e=this.curve._mulC(n.redISub(c)).redMul(u),t=this.curve._mulC(c).redMul(i.redISub(o)),r=c.redMul(u)}return this.curve.point(e,t,r)},f.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},f.prototype._extAdd=function(e){var t=this.y.redSub(this.x).redMul(e.y.redSub(e.x)),r=this.y.redAdd(this.x).redMul(e.y.redAdd(e.x)),n=this.t.redMul(this.curve.dd).redMul(e.t),i=this.z.redMul(e.z.redAdd(e.z)),o=r.redSub(t),a=i.redSub(n),s=i.redAdd(n),u=r.redAdd(t),c=o.redMul(a),f=s.redMul(u),h=o.redMul(u),l=a.redMul(s);return this.curve.point(c,f,l,h)},f.prototype._projAdd=function(e){var t,r,n=this.z.redMul(e.z),i=n.redSqr(),o=this.x.redMul(e.x),a=this.y.redMul(e.y),s=this.curve.d.redMul(o).redMul(a),u=i.redSub(s),c=i.redAdd(s),f=this.x.redAdd(this.y).redMul(e.x.redAdd(e.y)).redISub(o).redISub(a),h=n.redMul(u).redMul(f);return this.curve.twisted?(t=n.redMul(c).redMul(a.redSub(this.curve._mulA(o))),r=u.redMul(c)):(t=n.redMul(c).redMul(a.redSub(o)),r=this.curve._mulC(u).redMul(c)),this.curve.point(h,t,r)},f.prototype.add=function(e){return this.isInfinity()?e:e.isInfinity()?this:this.curve.extended?this._extAdd(e):this._projAdd(e)},f.prototype.mul=function(e){return this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve._wnafMul(this,e)},f.prototype.mulAdd=function(e,t,r){return this.curve._wnafMulAdd(1,[this,t],[e,r],2,!1)},f.prototype.jmulAdd=function(e,t,r){return this.curve._wnafMulAdd(1,[this,t],[e,r],2,!0)},f.prototype.normalize=function(){if(this.zOne)return this;var e=this.z.redInvm();return this.x=this.x.redMul(e),this.y=this.y.redMul(e),this.t&&(this.t=this.t.redMul(e)),this.z=this.curve.one,this.zOne=!0,this},f.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},f.prototype.getX=function(){return this.normalize(),this.x.fromRed()},f.prototype.getY=function(){return this.normalize(),this.y.fromRed()},f.prototype.eq=function(e){return this===e||0===this.getX().cmp(e.getX())&&0===this.getY().cmp(e.getY())},f.prototype.eqXToP=function(e){var t=e.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(t))return!0;for(var r=e.clone(),n=this.curve.redN.redMul(this.z);;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(t.redIAdd(n),0===this.x.cmp(t))return!0}return!1},f.prototype.toP=f.prototype.normalize,f.prototype.mixedAdd=f.prototype.add},{"../../elliptic":109,"../curve":112,"bn.js":53,inherits:180}],112:[function(e,t,r){"use strict";var n=r;n.base=e("./base"),n.short=e("./short"),n.mont=e("./mont"),n.edwards=e("./edwards")},{"./base":110,"./edwards":111,"./mont":113,"./short":114}],113:[function(e,t,r){"use strict";var n=e("../curve"),i=e("bn.js"),o=e("inherits"),a=n.base,s=e("../../elliptic").utils;function u(e){a.call(this,"mont",e),this.a=new i(e.a,16).toRed(this.red),this.b=new i(e.b,16).toRed(this.red),this.i4=new i(4).toRed(this.red).redInvm(),this.two=new i(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}function c(e,t,r){a.BasePoint.call(this,e,"projective"),null===t&&null===r?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new i(t,16),this.z=new i(r,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}o(u,a),t.exports=u,u.prototype.validate=function(e){var t=e.normalize().x,r=t.redSqr(),n=r.redMul(t).redAdd(r.redMul(this.a)).redAdd(t);return 0===n.redSqrt().redSqr().cmp(n)},o(c,a.BasePoint),u.prototype.decodePoint=function(e,t){return this.point(s.toArray(e,t),1)},u.prototype.point=function(e,t){return new c(this,e,t)},u.prototype.pointFromJSON=function(e){return c.fromJSON(this,e)},c.prototype.precompute=function(){},c.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},c.fromJSON=function(e,t){return new c(e,t[0],t[1]||e.one)},c.prototype.inspect=function(){return this.isInfinity()?"":""},c.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},c.prototype.dbl=function(){var e=this.x.redAdd(this.z).redSqr(),t=this.x.redSub(this.z).redSqr(),r=e.redSub(t),n=e.redMul(t),i=r.redMul(t.redAdd(this.curve.a24.redMul(r)));return this.curve.point(n,i)},c.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.diffAdd=function(e,t){var r=this.x.redAdd(this.z),n=this.x.redSub(this.z),i=e.x.redAdd(e.z),o=e.x.redSub(e.z).redMul(r),a=i.redMul(n),s=t.z.redMul(o.redAdd(a).redSqr()),u=t.x.redMul(o.redISub(a).redSqr());return this.curve.point(s,u)},c.prototype.mul=function(e){for(var t=e.clone(),r=this,n=this.curve.point(null,null),i=[];0!==t.cmpn(0);t.iushrn(1))i.push(t.andln(1));for(var o=i.length-1;o>=0;o--)0===i[o]?(r=r.diffAdd(n,this),n=n.dbl()):(n=r.diffAdd(n,this),r=r.dbl());return n},c.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.eq=function(e){return 0===this.getX().cmp(e.getX())},c.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},c.prototype.getX=function(){return this.normalize(),this.x.fromRed()}},{"../../elliptic":109,"../curve":112,"bn.js":53,inherits:180}],114:[function(e,t,r){"use strict";var n=e("../curve"),i=e("../../elliptic"),o=e("bn.js"),a=e("inherits"),s=n.base,u=i.utils.assert;function c(e){s.call(this,"short",e),this.a=new o(e.a,16).toRed(this.red),this.b=new o(e.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=0===this.a.fromRed().cmpn(0),this.threeA=0===this.a.fromRed().sub(this.p).cmpn(-3),this.endo=this._getEndomorphism(e),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}function f(e,t,r,n){s.BasePoint.call(this,e,"affine"),null===t&&null===r?(this.x=null,this.y=null,this.inf=!0):(this.x=new o(t,16),this.y=new o(r,16),n&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}function h(e,t,r,n){s.BasePoint.call(this,e,"jacobian"),null===t&&null===r&&null===n?(this.x=this.curve.one,this.y=this.curve.one,this.z=new o(0)):(this.x=new o(t,16),this.y=new o(r,16),this.z=new o(n,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}a(c,s),t.exports=c,c.prototype._getEndomorphism=function(e){if(this.zeroA&&this.g&&this.n&&1===this.p.modn(3)){var t,r;if(e.beta)t=new o(e.beta,16).toRed(this.red);else{var n=this._getEndoRoots(this.p);t=(t=n[0].cmp(n[1])<0?n[0]:n[1]).toRed(this.red)}if(e.lambda)r=new o(e.lambda,16);else{var i=this._getEndoRoots(this.n);0===this.g.mul(i[0]).x.cmp(this.g.x.redMul(t))?r=i[0]:(r=i[1],u(0===this.g.mul(r).x.cmp(this.g.x.redMul(t))))}return{beta:t,lambda:r,basis:e.basis?e.basis.map(function(e){return{a:new o(e.a,16),b:new o(e.b,16)}}):this._getEndoBasis(r)}}},c.prototype._getEndoRoots=function(e){var t=e===this.p?this.red:o.mont(e),r=new o(2).toRed(t).redInvm(),n=r.redNeg(),i=new o(3).toRed(t).redNeg().redSqrt().redMul(r);return[n.redAdd(i).fromRed(),n.redSub(i).fromRed()]},c.prototype._getEndoBasis=function(e){for(var t,r,n,i,a,s,u,c,f,h=this.n.ushrn(Math.floor(this.n.bitLength()/2)),l=e,d=this.n.clone(),p=new o(1),b=new o(0),y=new o(0),m=new o(1),v=0;0!==l.cmpn(0);){var g=d.div(l);c=d.sub(g.mul(l)),f=y.sub(g.mul(p));var w=m.sub(g.mul(b));if(!n&&c.cmp(h)<0)t=u.neg(),r=p,n=c.neg(),i=f;else if(n&&2==++v)break;u=c,d=l,l=c,y=p,p=f,m=b,b=w}a=c.neg(),s=f;var _=n.sqr().add(i.sqr());return a.sqr().add(s.sqr()).cmp(_)>=0&&(a=t,s=r),n.negative&&(n=n.neg(),i=i.neg()),a.negative&&(a=a.neg(),s=s.neg()),[{a:n,b:i},{a:a,b:s}]},c.prototype._endoSplit=function(e){var t=this.endo.basis,r=t[0],n=t[1],i=n.b.mul(e).divRound(this.n),o=r.b.neg().mul(e).divRound(this.n),a=i.mul(r.a),s=o.mul(n.a),u=i.mul(r.b),c=o.mul(n.b);return{k1:e.sub(a).sub(s),k2:u.add(c).neg()}},c.prototype.pointFromX=function(e,t){(e=new o(e,16)).red||(e=e.toRed(this.red));var r=e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(0!==n.redSqr().redSub(r).cmp(this.zero))throw new Error("invalid point");var i=n.fromRed().isOdd();return(t&&!i||!t&&i)&&(n=n.redNeg()),this.point(e,n)},c.prototype.validate=function(e){if(e.inf)return!0;var t=e.x,r=e.y,n=this.a.redMul(t),i=t.redSqr().redMul(t).redIAdd(n).redIAdd(this.b);return 0===r.redSqr().redISub(i).cmpn(0)},c.prototype._endoWnafMulAdd=function(e,t,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,o=0;o":""},f.prototype.isInfinity=function(){return this.inf},f.prototype.add=function(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return this.curve.point(null,null);if(0===this.x.cmp(e.x))return this.curve.point(null,null);var t=this.y.redSub(e.y);0!==t.cmpn(0)&&(t=t.redMul(this.x.redSub(e.x).redInvm()));var r=t.redSqr().redISub(this.x).redISub(e.x),n=t.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},f.prototype.dbl=function(){if(this.inf)return this;var e=this.y.redAdd(this.y);if(0===e.cmpn(0))return this.curve.point(null,null);var t=this.curve.a,r=this.x.redSqr(),n=e.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(t).redMul(n),o=i.redSqr().redISub(this.x.redAdd(this.x)),a=i.redMul(this.x.redSub(o)).redISub(this.y);return this.curve.point(o,a)},f.prototype.getX=function(){return this.x.fromRed()},f.prototype.getY=function(){return this.y.fromRed()},f.prototype.mul=function(e){return e=new o(e,16),this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve.endo?this.curve._endoWnafMulAdd([this],[e]):this.curve._wnafMul(this,e)},f.prototype.mulAdd=function(e,t,r){var n=[this,t],i=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},f.prototype.jmulAdd=function(e,t,r){var n=[this,t],i=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},f.prototype.eq=function(e){return this===e||this.inf===e.inf&&(this.inf||0===this.x.cmp(e.x)&&0===this.y.cmp(e.y))},f.prototype.neg=function(e){if(this.inf)return this;var t=this.curve.point(this.x,this.y.redNeg());if(e&&this.precomputed){var r=this.precomputed,n=function(e){return e.neg()};t.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return t},f.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},a(h,s.BasePoint),c.prototype.jpoint=function(e,t,r){return new h(this,e,t,r)},h.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var e=this.z.redInvm(),t=e.redSqr(),r=this.x.redMul(t),n=this.y.redMul(t).redMul(e);return this.curve.point(r,n)},h.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},h.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(t),i=e.x.redMul(r),o=this.y.redMul(t.redMul(e.z)),a=e.y.redMul(r.redMul(this.z)),s=n.redSub(i),u=o.redSub(a);if(0===s.cmpn(0))return 0!==u.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var c=s.redSqr(),f=c.redMul(s),h=n.redMul(c),l=u.redSqr().redIAdd(f).redISub(h).redISub(h),d=u.redMul(h.redISub(l)).redISub(o.redMul(f)),p=this.z.redMul(e.z).redMul(s);return this.curve.jpoint(l,d,p)},h.prototype.mixedAdd=function(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;var t=this.z.redSqr(),r=this.x,n=e.x.redMul(t),i=this.y,o=e.y.redMul(t).redMul(this.z),a=r.redSub(n),s=i.redSub(o);if(0===a.cmpn(0))return 0!==s.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var u=a.redSqr(),c=u.redMul(a),f=r.redMul(u),h=s.redSqr().redIAdd(c).redISub(f).redISub(f),l=s.redMul(f.redISub(h)).redISub(i.redMul(c)),d=this.z.redMul(a);return this.curve.jpoint(h,l,d)},h.prototype.dblp=function(e){if(0===e)return this;if(this.isInfinity())return this;if(!e)return this.dbl();if(this.curve.zeroA||this.curve.threeA){for(var t=this,r=0;r=0)return!1;if(r.redIAdd(i),0===this.x.cmp(r))return!0}return!1},h.prototype.inspect=function(){return this.isInfinity()?"":""},h.prototype.isInfinity=function(){return 0===this.z.cmpn(0)}},{"../../elliptic":109,"../curve":112,"bn.js":53,inherits:180}],115:[function(e,t,r){"use strict";var n,i=r,o=e("hash.js"),a=e("../elliptic"),s=a.utils.assert;function u(e){"short"===e.type?this.curve=new a.curve.short(e):"edwards"===e.type?this.curve=new a.curve.edwards(e):this.curve=new a.curve.mont(e),this.g=this.curve.g,this.n=this.curve.n,this.hash=e.hash,s(this.g.validate(),"Invalid curve"),s(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}function c(e,t){Object.defineProperty(i,e,{configurable:!0,enumerable:!0,get:function(){var r=new u(t);return Object.defineProperty(i,e,{configurable:!0,enumerable:!0,value:r}),r}})}i.PresetCurve=u,c("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:o.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),c("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:o.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),c("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:o.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),c("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:o.sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),c("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:o.sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),c("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:o.sha256,gRed:!1,g:["9"]}),c("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:o.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});try{n=e("./precomputed/secp256k1")}catch(e){n=void 0}c("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:o.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",n]})},{"../elliptic":109,"./precomputed/secp256k1":122,"hash.js":162}],116:[function(e,t,r){"use strict";var n=e("bn.js"),i=e("hmac-drbg"),o=e("../../elliptic"),a=o.utils.assert,s=e("./key"),u=e("./signature");function c(e){if(!(this instanceof c))return new c(e);"string"==typeof e&&(a(o.curves.hasOwnProperty(e),"Unknown curve "+e),e=o.curves[e]),e instanceof o.curves.PresetCurve&&(e={curve:e}),this.curve=e.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=e.curve.g,this.g.precompute(e.curve.n.bitLength()+1),this.hash=e.hash||e.curve.hash}t.exports=c,c.prototype.keyPair=function(e){return new s(this,e)},c.prototype.keyFromPrivate=function(e,t){return s.fromPrivate(this,e,t)},c.prototype.keyFromPublic=function(e,t){return s.fromPublic(this,e,t)},c.prototype.genKeyPair=function(e){e||(e={});for(var t=new i({hash:this.hash,pers:e.pers,persEnc:e.persEnc||"utf8",entropy:e.entropy||o.rand(this.hash.hmacStrength),entropyEnc:e.entropy&&e.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),a=this.n.sub(new n(2));;){var s=new n(t.generate(r));if(!(s.cmp(a)>0))return s.iaddn(1),this.keyFromPrivate(s)}},c.prototype._truncateToN=function(e,t){var r=8*e.byteLength()-this.n.bitLength();return r>0&&(e=e.ushrn(r)),!t&&e.cmp(this.n)>=0?e.sub(this.n):e},c.prototype.sign=function(e,t,r,o){"object"==typeof r&&(o=r,r=null),o||(o={}),t=this.keyFromPrivate(t,r),e=this._truncateToN(new n(e,16));for(var a=this.n.byteLength(),s=t.getPrivate().toArray("be",a),c=e.toArray("be",a),f=new i({hash:this.hash,entropy:s,nonce:c,pers:o.pers,persEnc:o.persEnc||"utf8"}),h=this.n.sub(new n(1)),l=0;;l++){var d=o.k?o.k(l):new n(f.generate(this.n.byteLength()));if(!((d=this._truncateToN(d,!0)).cmpn(1)<=0||d.cmp(h)>=0)){var p=this.g.mul(d);if(!p.isInfinity()){var b=p.getX(),y=b.umod(this.n);if(0!==y.cmpn(0)){var m=d.invm(this.n).mul(y.mul(t.getPrivate()).iadd(e));if(0!==(m=m.umod(this.n)).cmpn(0)){var v=(p.getY().isOdd()?1:0)|(0!==b.cmp(y)?2:0);return o.canonical&&m.cmp(this.nh)>0&&(m=this.n.sub(m),v^=1),new u({r:y,s:m,recoveryParam:v})}}}}}},c.prototype.verify=function(e,t,r,i){e=this._truncateToN(new n(e,16)),r=this.keyFromPublic(r,i);var o=(t=new u(t,"hex")).r,a=t.s;if(o.cmpn(1)<0||o.cmp(this.n)>=0)return!1;if(a.cmpn(1)<0||a.cmp(this.n)>=0)return!1;var s,c=a.invm(this.n),f=c.mul(e).umod(this.n),h=c.mul(o).umod(this.n);return this.curve._maxwellTrick?!(s=this.g.jmulAdd(f,r.getPublic(),h)).isInfinity()&&s.eqXToP(o):!(s=this.g.mulAdd(f,r.getPublic(),h)).isInfinity()&&0===s.getX().umod(this.n).cmp(o)},c.prototype.recoverPubKey=function(e,t,r,i){a((3&r)===r,"The recovery param is more than two bits"),t=new u(t,i);var o=this.n,s=new n(e),c=t.r,f=t.s,h=1&r,l=r>>1;if(c.cmp(this.curve.p.umod(this.curve.n))>=0&&l)throw new Error("Unable to find sencond key candinate");c=l?this.curve.pointFromX(c.add(this.curve.n),h):this.curve.pointFromX(c,h);var d=t.r.invm(o),p=o.sub(s).mul(d).umod(o),b=f.mul(d).umod(o);return this.g.mulAdd(p,c,b)},c.prototype.getKeyRecoveryParam=function(e,t,r,n){if(null!==(t=new u(t,n)).recoveryParam)return t.recoveryParam;for(var i=0;i<4;i++){var o;try{o=this.recoverPubKey(e,t,i)}catch(e){continue}if(o.eq(r))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(e,t,r){"use strict";var n=e("bn.js"),i=e("../../elliptic").utils.assert;function o(e,t){this.ec=e,this.priv=null,this.pub=null,t.priv&&this._importPrivate(t.priv,t.privEnc),t.pub&&this._importPublic(t.pub,t.pubEnc)}t.exports=o,o.fromPublic=function(e,t,r){return t instanceof o?t:new o(e,{pub:t,pubEnc:r})},o.fromPrivate=function(e,t,r){return t instanceof o?t:new o(e,{priv:t,privEnc:r})},o.prototype.validate=function(){var e=this.getPublic();return e.isInfinity()?{result:!1,reason:"Invalid public key"}:e.validate()?e.mul(this.ec.curve.n).isInfinity()?{result:!0,reason:null}:{result:!1,reason:"Public key * N != O"}:{result:!1,reason:"Public key is not a point"}},o.prototype.getPublic=function(e,t){return"string"==typeof e&&(t=e,e=null),this.pub||(this.pub=this.ec.g.mul(this.priv)),t?this.pub.encode(t,e):this.pub},o.prototype.getPrivate=function(e){return"hex"===e?this.priv.toString(16,2):this.priv},o.prototype._importPrivate=function(e,t){this.priv=new n(e,t||16),this.priv=this.priv.umod(this.ec.curve.n)},o.prototype._importPublic=function(e,t){if(e.x||e.y)return"mont"===this.ec.curve.type?i(e.x,"Need x coordinate"):"short"!==this.ec.curve.type&&"edwards"!==this.ec.curve.type||i(e.x&&e.y,"Need both x and y coordinate"),void(this.pub=this.ec.curve.point(e.x,e.y));this.pub=this.ec.curve.decodePoint(e,t)},o.prototype.derive=function(e){return e.mul(this.priv).getX()},o.prototype.sign=function(e,t,r){return this.ec.sign(e,this,t,r)},o.prototype.verify=function(e,t){return this.ec.verify(e,t,this)},o.prototype.inspect=function(){return""}},{"../../elliptic":109,"bn.js":53}],118:[function(e,t,r){"use strict";var n=e("bn.js"),i=e("../../elliptic").utils,o=i.assert;function a(e,t){if(e instanceof a)return e;this._importDER(e,t)||(o(e.r&&e.s,"Signature without r or s"),this.r=new n(e.r,16),this.s=new n(e.s,16),void 0===e.recoveryParam?this.recoveryParam=null:this.recoveryParam=e.recoveryParam)}function s(e,t){var r=e[t.place++];if(!(128&r))return r;for(var n=15&r,i=0,o=0,a=t.place;o>>3);for(e.push(128|r);--r;)e.push(t>>>(r<<3)&255);e.push(t)}}t.exports=a,a.prototype._importDER=function(e,t){e=i.toArray(e,t);var r=new function(){this.place=0};if(48!==e[r.place++])return!1;if(s(e,r)+r.place!==e.length)return!1;if(2!==e[r.place++])return!1;var o=s(e,r),a=e.slice(r.place,o+r.place);if(r.place+=o,2!==e[r.place++])return!1;var u=s(e,r);if(e.length!==u+r.place)return!1;var c=e.slice(r.place,u+r.place);return 0===a[0]&&128&a[1]&&(a=a.slice(1)),0===c[0]&&128&c[1]&&(c=c.slice(1)),this.r=new n(a),this.s=new n(c),this.recoveryParam=null,!0},a.prototype.toDER=function(e){var t=this.r.toArray(),r=this.s.toArray();for(128&t[0]&&(t=[0].concat(t)),128&r[0]&&(r=[0].concat(r)),t=u(t),r=u(r);!(r[0]||128&r[1]);)r=r.slice(1);var n=[2];c(n,t.length),(n=n.concat(t)).push(2),c(n,r.length);var o=n.concat(r),a=[48];return c(a,o.length),a=a.concat(o),i.encode(a,e)}},{"../../elliptic":109,"bn.js":53}],119:[function(e,t,r){"use strict";var n=e("hash.js"),i=e("../../elliptic"),o=i.utils,a=o.assert,s=o.parseBytes,u=e("./key"),c=e("./signature");function f(e){if(a("ed25519"===e,"only tested with ed25519 so far"),!(this instanceof f))return new f(e);e=i.curves[e].curve;this.curve=e,this.g=e.g,this.g.precompute(e.n.bitLength()+1),this.pointClass=e.point().constructor,this.encodingLength=Math.ceil(e.n.bitLength()/8),this.hash=n.sha512}t.exports=f,f.prototype.sign=function(e,t){e=s(e);var r=this.keyFromSecret(t),n=this.hashInt(r.messagePrefix(),e),i=this.g.mul(n),o=this.encodePoint(i),a=this.hashInt(o,r.pubBytes(),e).mul(r.priv()),u=n.add(a).umod(this.curve.n);return this.makeSignature({R:i,S:u,Rencoded:o})},f.prototype.verify=function(e,t,r){e=s(e),t=this.makeSignature(t);var n=this.keyFromPublic(r),i=this.hashInt(t.Rencoded(),n.pubBytes(),e),o=this.g.mul(t.S());return t.R().add(n.pub().mul(i)).eq(o)},f.prototype.hashInt=function(){for(var e=this.hash(),t=0;t=0;){var o;if(i.isOdd()){var a=i.andln(n-1);o=a>(n>>1)-1?(n>>1)-a:a,i.isubn(o)}else o=0;r.push(o);for(var s=0!==i.cmpn(0)&&0===i.andln(n-1)?t+1:1,u=1;u0||t.cmpn(-i)>0;){var o,a,s,u=e.andln(3)+n&3,c=t.andln(3)+i&3;3===u&&(u=-1),3===c&&(c=-1),o=0==(1&u)?0:3!=(s=e.andln(7)+n&7)&&5!==s||2!==c?u:-u,r[0].push(o),a=0==(1&c)?0:3!=(s=t.andln(7)+i&7)&&5!==s||2!==u?c:-c,r[1].push(a),2*n===o+1&&(n=1-n),2*i===a+1&&(i=1-i),e.iushrn(1),t.iushrn(1)}return r},n.cachedProperty=function(e,t,r){var n="_"+t;e.prototype[t]=function(){return void 0!==this[n]?this[n]:this[n]=r.call(this)}},n.parseBytes=function(e){return"string"==typeof e?n.toArray(e,"hex"):e},n.intFromLE=function(e){return new i(e,"hex","le")}},{"bn.js":53,"minimalistic-assert":234,"minimalistic-crypto-utils":235}],124:[function(e,t,r){t.exports={_from:"elliptic@^6.0.0",_id:"elliptic@6.4.0",_inBundle:!1,_integrity:"sha1-ysmvh2LIWDYYcAPI3+GT5eLq5d8=",_location:"/elliptic",_phantomChildren:{},_requested:{type:"range",registry:!0,raw:"elliptic@^6.0.0",name:"elliptic",escapedName:"elliptic",rawSpec:"^6.0.0",saveSpec:null,fetchSpec:"^6.0.0"},_requiredBy:["/browserify-sign","/create-ecdh"],_resolved:"https://registry.npmjs.org/elliptic/-/elliptic-6.4.0.tgz",_shasum:"cac9af8762c85836187003c8dfe193e5e2eae5df",_spec:"elliptic@^6.0.0",_where:"/Users/alexvlasov/Blockchain/web3swift_jsproxy/node_modules/browserify-sign",author:{name:"Fedor Indutny",email:"fedor@indutny.com"},bugs:{url:"https://github.com/indutny/elliptic/issues"},bundleDependencies:!1,dependencies:{"bn.js":"^4.4.0",brorand:"^1.0.1","hash.js":"^1.0.0","hmac-drbg":"^1.0.0",inherits:"^2.0.1","minimalistic-assert":"^1.0.0","minimalistic-crypto-utils":"^1.0.0"},deprecated:!1,description:"EC cryptography",devDependencies:{brfs:"^1.4.3",coveralls:"^2.11.3",grunt:"^0.4.5","grunt-browserify":"^5.0.0","grunt-cli":"^1.2.0","grunt-contrib-connect":"^1.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^1.0.1","grunt-mocha-istanbul":"^3.0.1","grunt-saucelabs":"^8.6.2",istanbul:"^0.4.2",jscs:"^2.9.0",jshint:"^2.6.0",mocha:"^2.1.0"},files:["lib"],homepage:"https://github.com/indutny/elliptic",keywords:["EC","Elliptic","curve","Cryptography"],license:"MIT",main:"lib/elliptic.js",name:"elliptic",repository:{type:"git",url:"git+ssh://git@github.com/indutny/elliptic.git"},scripts:{jscs:"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",jshint:"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",lint:"npm run jscs && npm run jshint",test:"npm run lint && npm run unit",unit:"istanbul test _mocha --reporter=spec test/index.js",version:"grunt dist && git add dist/"},version:"6.4.0"}},{}],125:[function(e,t,r){"use strict";const n=e("ethjs-util");function i(e){let t=n.stripHexPrefix(e);for(;"0"===t[0];)t=t.substr(1);return`0x${t}`}t.exports={incrementHexNumber:function(e){return i(n.intToHex(parseInt(e,16)+1))},formatHex:i}},{"ethjs-util":155}],126:[function(e,t,r){const n=e("eth-query"),i=e("events"),o=e("pify"),a=e("./hexUtils"),s=a.incrementHexNumber,u=1e3,c=60*u;t.exports=class extends i{constructor(e={}){if(super(),!e.provider)throw new Error("RpcBlockTracker - no provider specified.");this._provider=e.provider,this._query=new n(e.provider),this._pollingInterval=e.pollingInterval||4*u,this._syncingTimeout=e.syncingTimeout||1*c,this._trackingBlock=null,this._trackingBlockTimestamp=null,this._currentBlock=null,this._isRunning=!1,this._performSync=this._performSync.bind(this),this._handleNewBlockNotification=this._handleNewBlockNotification.bind(this)}getTrackingBlock(){return this._trackingBlock}getCurrentBlock(){return this._currentBlock}async awaitCurrentBlock(){return this._currentBlock?this._currentBlock:(await new Promise(e=>this.once("latest",e)),this._currentBlock)}async start(e={}){this._isRunning||(this._isRunning=!0,e.fromBlock?await this._setTrackingBlock(await this._fetchBlockByNumber(e.fromBlock)):await this._setTrackingBlock(await this._fetchLatestBlock()),this._provider.on?await this._initSubscription():this._performSync().catch(e=>{e&&console.error(e)}))}async stop(){this._isRunning=!1,this._provider.on&&await this._removeSubscription()}async _setTrackingBlock(e){if(this._trackingBlock&&this._trackingBlock.hash===e.hash)return;const t=this._trackingBlockTimestamp,r=Date.now();t&&r-t>this._syncingTimeout?(this._trackingBlockTimestamp=null,await this._warpToLatest()):(this._trackingBlock=e,this._trackingBlockTimestamp=r,this.emit("block",e))}async _setCurrentBlock(e){if(this._currentBlock&&this._currentBlock.hash===e.hash)return;const t=this._currentBlock;this._currentBlock=e,this.emit("latest",e),this.emit("sync",{newBlock:e,oldBlock:t})}async _warpToLatest(){await this._setTrackingBlock(await this._fetchLatestBlock())}async _pollForNextBlock(){setTimeout(()=>this._performSync(),this._pollingInterval)}async _performSync(){if(!this._isRunning)return;const e=this.getTrackingBlock();if(!e)throw new Error("RpcBlockTracker - tracking block is missing");const t=s(e.number);try{const r=await this._fetchBlockByNumber(t);r?(await this._setTrackingBlock(r),this._performSync()):(await this._setCurrentBlock(e),this._pollForNextBlock())}catch(t){t.message.includes("index out of range")||t.message.includes("Couldn't find block by reference")?(await this._setCurrentBlock(e),this._pollForNextBlock()):(console.error(t),this._pollForNextBlock())}}async _handleNewBlockNotification(e,t){t.id==this._subscriptionId&&(e&&(this.emit("error",e),await this._removeSubscription()),await this._setTrackingBlock(await this._fetchBlockByNumber(t.result.number)))}async _initSubscription(){this._provider.on("data",this._handleNewBlockNotification);let e=await o(this._provider.sendAsync||this._provider.send)({jsonrpc:"2.0",id:(new Date).getTime(),method:"eth_subscribe",params:["newHeads"]});this._subscriptionId=e.result}async _removeSubscription(){if(!this._subscriptionId)throw new Error("Not subscribed.");this._provider.removeListener("data",this._handleNewBlockNotification),await o(this._provider.sendAsync||this._provider.send)({jsonrpc:"2.0",id:(new Date).getTime(),method:"eth_unsubscribe",params:[this._subscriptionId]}),delete this._subscriptionId}_fetchLatestBlock(){return o(this._query.getBlockByNumber).call(this._query,"latest",!0)}_fetchBlockByNumber(e){const t=a.formatHex(e);return o(this._query.getBlockByNumber).call(this._query,t,!0)}}},{"./hexUtils":125,"eth-query":135,events:157,pify:252}],127:[function(e,t,r){(function(t){var n=e("js-sha3").keccak_256,i=e("idna-uts46-hx");function o(e){return e?i.toUnicode(e,{useStd3ASCII:!0,transitional:!1}):e}r.hash=function(e){for(var r="",i=0;i<32;i++)r+="00";if(name=o(e),name){var a=name.split(".");for(i=a.length-1;i>=0;i--){var s=n(a[i]);r=n(new t(r+s,"hex"))}}return"0x"+r},r.normalize=o}).call(this,e("buffer").Buffer)},{buffer:84,"idna-uts46-hx":177,"js-sha3":128}],128:[function(e,t,r){(function(e,r){!function(){"use strict";var n="object"==typeof window?window:{};!n.JS_SHA3_NO_NODE_JS&&"object"==typeof e&&e.versions&&e.versions.node&&(n=r);for(var i=!n.JS_SHA3_NO_COMMON_JS&&"object"==typeof t&&t.exports,o="0123456789abcdef".split(""),a=[0,8,16,24],s=[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],u=[224,256,384,512],c=["hex","buffer","arrayBuffer","array"],f=function(e,t,r){return function(n){return new _(e,t,e).update(n)[r]()}},h=function(e,t,r){return function(n,i){return new _(e,t,i).update(n)[r]()}},l=function(e,t){var r=f(e,t,"hex");r.create=function(){return new _(e,t,e)},r.update=function(e){return r.create().update(e)};for(var n=0;n>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var n=0;n<50;++n)this.s[n]=0}_.prototype.update=function(e){var t="string"!=typeof e;t&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e));for(var r,n,i=e.length,o=this.blocks,s=this.byteCount,u=this.blockCount,c=0,f=this.s;c>2]|=e[c]<>2]|=n<>2]|=(192|n>>6)<>2]|=(128|63&n)<=57344?(o[r>>2]|=(224|n>>12)<>2]|=(128|n>>6&63)<>2]|=(128|63&n)<>2]|=(240|n>>18)<>2]|=(128|n>>12&63)<>2]|=(128|n>>6&63)<>2]|=(128|63&n)<=s){for(this.start=r-s,this.block=o[u],r=0;r>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t>4&15]+o[15&e]+o[e>>12&15]+o[e>>8&15]+o[e>>20&15]+o[e>>16&15]+o[e>>28&15]+o[e>>24&15];s%t==0&&(A(r),a=0)}return i&&(e=r[a],i>0&&(u+=o[e>>4&15]+o[15&e]),i>1&&(u+=o[e>>12&15]+o[e>>8&15]),i>2&&(u+=o[e>>20&15]+o[e>>16&15])),u},_.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,i=this.extraBytes,o=0,a=0,s=this.outputBits>>3;e=i?new ArrayBuffer(n+1<<2):new ArrayBuffer(s);for(var u=new Uint32Array(e);a>8&255,u[e+2]=t>>16&255,u[e+3]=t>>24&255;s%r==0&&A(n)}return o&&(e=s<<2,t=n[a],o>0&&(u[e]=255&t),o>1&&(u[e+1]=t>>8&255),o>2&&(u[e+2]=t>>16&255)),u};var A=function(e){var t,r,n,i,o,a,u,c,f,h,l,d,p,b,y,m,v,g,w,_,A,E,x,k,S,M,I,T,U,j,B,P,C,N,R,L,O,D,F,q,H,z,K,V,G,W,Y,X,Z,J,$,Q,ee,te,re,ne,ie,oe,ae,se,ue,ce,fe;for(n=0;n<48;n+=2)i=e[0]^e[10]^e[20]^e[30]^e[40],o=e[1]^e[11]^e[21]^e[31]^e[41],a=e[2]^e[12]^e[22]^e[32]^e[42],u=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],f=e[5]^e[15]^e[25]^e[35]^e[45],h=e[6]^e[16]^e[26]^e[36]^e[46],l=e[7]^e[17]^e[27]^e[37]^e[47],t=(d=e[8]^e[18]^e[28]^e[38]^e[48])^(a<<1|u>>>31),r=(p=e[9]^e[19]^e[29]^e[39]^e[49])^(u<<1|a>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=i^(c<<1|f>>>31),r=o^(f<<1|c>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=a^(h<<1|l>>>31),r=u^(l<<1|h>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=c^(d<<1|p>>>31),r=f^(p<<1|d>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=h^(i<<1|o>>>31),r=l^(o<<1|i>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,b=e[0],y=e[1],W=e[11]<<4|e[10]>>>28,Y=e[10]<<4|e[11]>>>28,T=e[20]<<3|e[21]>>>29,U=e[21]<<3|e[20]>>>29,se=e[31]<<9|e[30]>>>23,ue=e[30]<<9|e[31]>>>23,z=e[40]<<18|e[41]>>>14,K=e[41]<<18|e[40]>>>14,N=e[2]<<1|e[3]>>>31,R=e[3]<<1|e[2]>>>31,m=e[13]<<12|e[12]>>>20,v=e[12]<<12|e[13]>>>20,X=e[22]<<10|e[23]>>>22,Z=e[23]<<10|e[22]>>>22,j=e[33]<<13|e[32]>>>19,B=e[32]<<13|e[33]>>>19,ce=e[42]<<2|e[43]>>>30,fe=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,L=e[14]<<6|e[15]>>>26,O=e[15]<<6|e[14]>>>26,g=e[25]<<11|e[24]>>>21,w=e[24]<<11|e[25]>>>21,J=e[34]<<15|e[35]>>>17,$=e[35]<<15|e[34]>>>17,P=e[45]<<29|e[44]>>>3,C=e[44]<<29|e[45]>>>3,k=e[6]<<28|e[7]>>>4,S=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,ie=e[16]<<23|e[17]>>>9,D=e[26]<<25|e[27]>>>7,F=e[27]<<25|e[26]>>>7,_=e[36]<<21|e[37]>>>11,A=e[37]<<21|e[36]>>>11,Q=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,V=e[8]<<27|e[9]>>>5,G=e[9]<<27|e[8]>>>5,M=e[18]<<20|e[19]>>>12,I=e[19]<<20|e[18]>>>12,oe=e[29]<<7|e[28]>>>25,ae=e[28]<<7|e[29]>>>25,q=e[38]<<8|e[39]>>>24,H=e[39]<<8|e[38]>>>24,E=e[48]<<14|e[49]>>>18,x=e[49]<<14|e[48]>>>18,e[0]=b^~m&g,e[1]=y^~v&w,e[10]=k^~M&T,e[11]=S^~I&U,e[20]=N^~L&D,e[21]=R^~O&F,e[30]=V^~W&X,e[31]=G^~Y&Z,e[40]=te^~ne&oe,e[41]=re^~ie&ae,e[2]=m^~g&_,e[3]=v^~w&A,e[12]=M^~T&j,e[13]=I^~U&B,e[22]=L^~D&q,e[23]=O^~F&H,e[32]=W^~X&J,e[33]=Y^~Z&$,e[42]=ne^~oe&se,e[43]=ie^~ae&ue,e[4]=g^~_&E,e[5]=w^~A&x,e[14]=T^~j&P,e[15]=U^~B&C,e[24]=D^~q&z,e[25]=F^~H&K,e[34]=X^~J&Q,e[35]=Z^~$&ee,e[44]=oe^~se&ce,e[45]=ae^~ue&fe,e[6]=_^~E&b,e[7]=A^~x&y,e[16]=j^~P&k,e[17]=B^~C&S,e[26]=q^~z&N,e[27]=H^~K&R,e[36]=J^~Q&V,e[37]=$^~ee&G,e[46]=se^~ce&te,e[47]=ue^~fe&re,e[8]=E^~b&m,e[9]=x^~y&v,e[18]=P^~k&M,e[19]=C^~S&I,e[28]=z^~N&L,e[29]=K^~R&O,e[38]=Q^~V&W,e[39]=ee^~G&Y,e[48]=ce^~te&ne,e[49]=fe^~re&ie,e[0]^=s[n],e[1]^=s[n+1]};if(i)t.exports=p;else for(y=0;y{setTimeout(t,e)})}function c(e){const t=e.toString();return s.some(e=>t.includes(e))}async function f(e,t,r){const{fetchUrl:n,fetchParams:a}=h({network:e,req:t}),s=await o(n,a),u=await s.text();if(!s.ok)switch(s.status){case 405:throw new i.MethodNotFound;case 418:throw l("Request is being rate limited.");case 503:case 504:throw function(){let e="Gateway timeout. The request took too long to process. ";return e+="This can happen when querying logs over too wide a block range.",l("Gateway timeout. The request took too long to process. This can happen when querying logs over too wide a block range.")}();default:throw l(u)}if("eth_getBlockByNumber"===t.method&&"Not Found"===u)return void(r.result=null);const c=JSON.parse(u);r.result=c.result,r.error=c.error}function h({network:e,req:t}){const r=function(e){return{id:e.id,jsonrpc:e.jsonrpc,method:e.method,params:e.params}}(t),{method:n,params:i}=r,o={};let s=`https://api.infura.io/v1/jsonrpc/${e}`;if(a.includes(n))o.method="POST",o.headers={Accept:"application/json","Content-Type":"application/json"},o.body=JSON.stringify(r);else{o.method="GET",s+=`/${n}?params=${encodeURIComponent(JSON.stringify(i))}`}return{fetchUrl:s,fetchParams:o}}function l(e){const t=new Error(e);return new i.InternalError(t)}t.exports=function(e={}){const t=e.network||"mainnet",r=e.maxAttempts||5;if(!r)throw new Error(`Invalid value for 'maxAttempts': "${r}" (${typeof r})`);return n(async(e,n,i)=>{for(let i=1;i<=r;i++)try{await f(t,e,n);break}catch(e){if(!c(e))throw e;const t=r-i;if(!t){const t=`InfuraProvider - cannot complete request. All retries exhausted.\nOriginal Error:\n${e.toString()}\n\n`,r=new Error(t);throw r}await u(1e3)}})},t.exports.fetchConfigFromReq=h},{"cross-fetch":96,"json-rpc-engine/src/createAsyncMiddleware":187,"json-rpc-error":189}],131:[function(e,t,r){t.exports=function(e){return{sendAsync:e.handle.bind(e)}}},{}],132:[function(e,t,r){var n=function(e,t){for(var r=[],n=0;n>6|192);else{if(i>55295&&i<56320){if(++n==e.length)return null;var o=e.charCodeAt(n);if(o<56320||o>57343)return null;r+=t((i=65536+((1023&i)<<10)+(1023&o))>>18|240),r+=t(i>>12&63|128)}else r+=t(i>>12|224);r+=t(i>>6&63|128)}r+=t(63&i|128)}}return r},toString:function(e){for(var t="",r=0,o=i(e);r127){if(a>191&&a<224){if(r>=o)return null;a=(31&a)<<6|63&n(e,r)}else if(a>223&&a<240){if(r+1>=o)return null;a=(15&a)<<12|(63&n(e,r))<<6|63&n(e,++r)}else{if(!(a>239&&a<248))return null;if(r+2>=o)return null;a=(7&a)<<18|(63&n(e,r))<<12|(63&n(e,++r))<<6|63&n(e,++r)}++r}if(a<=65535)t+=String.fromCharCode(a);else{if(!(a<=1114111))return null;a-=65536,t+=String.fromCharCode(a>>10|55296),t+=String.fromCharCode(1023&a|56320)}}return t},fromNumber:function(e){var t=e.toString(16);return t.length%2==0?"0x"+t:"0x0"+t},toNumber:function(e){return parseInt(e.slice(2),16)},fromNat:function(e){return"0x0"===e?"0x":e.length%2==0?e:"0x0"+e.slice(2)},toNat:function(e){return"0"===e[2]?"0x"+e.slice(3):e},fromArray:a,toArray:o,fromUint8Array:function(e){return a([].slice.call(e,0))},toUint8Array:function(e){return new Uint8Array(o(e))}}},{"./array.js":132}],134:[function(e,t,r){var n="0123456789abcdef".split(""),i=[1,256,65536,16777216],o=[0,8,16,24],a=[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],s=function(e){var t,r,n,i,o,s,u,c,f,h,l,d,p,b,y,m,v,g,w,_,A,E,x,k,S,M,I,T,U,j,B,P,C,N,R,L,O,D,F,q,H,z,K,V,G,W,Y,X,Z,J,$,Q,ee,te,re,ne,ie,oe,ae,se,ue,ce,fe;for(n=0;n<48;n+=2)i=e[0]^e[10]^e[20]^e[30]^e[40],o=e[1]^e[11]^e[21]^e[31]^e[41],s=e[2]^e[12]^e[22]^e[32]^e[42],u=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],f=e[5]^e[15]^e[25]^e[35]^e[45],h=e[6]^e[16]^e[26]^e[36]^e[46],l=e[7]^e[17]^e[27]^e[37]^e[47],t=(d=e[8]^e[18]^e[28]^e[38]^e[48])^(s<<1|u>>>31),r=(p=e[9]^e[19]^e[29]^e[39]^e[49])^(u<<1|s>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=i^(c<<1|f>>>31),r=o^(f<<1|c>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=s^(h<<1|l>>>31),r=u^(l<<1|h>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=c^(d<<1|p>>>31),r=f^(p<<1|d>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=h^(i<<1|o>>>31),r=l^(o<<1|i>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,b=e[0],y=e[1],W=e[11]<<4|e[10]>>>28,Y=e[10]<<4|e[11]>>>28,T=e[20]<<3|e[21]>>>29,U=e[21]<<3|e[20]>>>29,se=e[31]<<9|e[30]>>>23,ue=e[30]<<9|e[31]>>>23,z=e[40]<<18|e[41]>>>14,K=e[41]<<18|e[40]>>>14,N=e[2]<<1|e[3]>>>31,R=e[3]<<1|e[2]>>>31,m=e[13]<<12|e[12]>>>20,v=e[12]<<12|e[13]>>>20,X=e[22]<<10|e[23]>>>22,Z=e[23]<<10|e[22]>>>22,j=e[33]<<13|e[32]>>>19,B=e[32]<<13|e[33]>>>19,ce=e[42]<<2|e[43]>>>30,fe=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,L=e[14]<<6|e[15]>>>26,O=e[15]<<6|e[14]>>>26,g=e[25]<<11|e[24]>>>21,w=e[24]<<11|e[25]>>>21,J=e[34]<<15|e[35]>>>17,$=e[35]<<15|e[34]>>>17,P=e[45]<<29|e[44]>>>3,C=e[44]<<29|e[45]>>>3,k=e[6]<<28|e[7]>>>4,S=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,ie=e[16]<<23|e[17]>>>9,D=e[26]<<25|e[27]>>>7,F=e[27]<<25|e[26]>>>7,_=e[36]<<21|e[37]>>>11,A=e[37]<<21|e[36]>>>11,Q=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,V=e[8]<<27|e[9]>>>5,G=e[9]<<27|e[8]>>>5,M=e[18]<<20|e[19]>>>12,I=e[19]<<20|e[18]>>>12,oe=e[29]<<7|e[28]>>>25,ae=e[28]<<7|e[29]>>>25,q=e[38]<<8|e[39]>>>24,H=e[39]<<8|e[38]>>>24,E=e[48]<<14|e[49]>>>18,x=e[49]<<14|e[48]>>>18,e[0]=b^~m&g,e[1]=y^~v&w,e[10]=k^~M&T,e[11]=S^~I&U,e[20]=N^~L&D,e[21]=R^~O&F,e[30]=V^~W&X,e[31]=G^~Y&Z,e[40]=te^~ne&oe,e[41]=re^~ie&ae,e[2]=m^~g&_,e[3]=v^~w&A,e[12]=M^~T&j,e[13]=I^~U&B,e[22]=L^~D&q,e[23]=O^~F&H,e[32]=W^~X&J,e[33]=Y^~Z&$,e[42]=ne^~oe&se,e[43]=ie^~ae&ue,e[4]=g^~_&E,e[5]=w^~A&x,e[14]=T^~j&P,e[15]=U^~B&C,e[24]=D^~q&z,e[25]=F^~H&K,e[34]=X^~J&Q,e[35]=Z^~$&ee,e[44]=oe^~se&ce,e[45]=ae^~ue&fe,e[6]=_^~E&b,e[7]=A^~x&y,e[16]=j^~P&k,e[17]=B^~C&S,e[26]=q^~z&N,e[27]=H^~K&R,e[36]=J^~Q&V,e[37]=$^~ee&G,e[46]=se^~ce&te,e[47]=ue^~fe&re,e[8]=E^~b&m,e[9]=x^~y&v,e[18]=P^~k&M,e[19]=C^~S&I,e[28]=z^~N&L,e[29]=K^~R&O,e[38]=Q^~V&W,e[39]=ee^~G&Y,e[48]=ce^~te&ne,e[49]=fe^~re&ie,e[0]^=a[n],e[1]^=a[n+1]},u=function(e){return function(t){var r;if("0x"===t.slice(0,2)){r=[];for(var a=2,u=t.length;a>2]|=t[d]<>2]|=r<>2]|=(192|r>>6)<>2]|=(128|63&r)<=57344?(u[y>>2]|=(224|r>>12)<>2]|=(128|r>>6&63)<>2]|=(128|63&r)<>2]|=(240|r>>18)<>2]|=(128|r>>12&63)<>2]|=(128|r>>6&63)<>2]|=(128|63&r)<=c){for(e.start=y-c,e.block=u[f],y=0;y>2]|=i[3&y],e.lastByteIndex===c)for(u[0]=u[f],y=1;y>4&15]+n[15&p]+n[p>>12&15]+n[p>>8&15]+n[p>>20&15]+n[p>>16&15]+n[p>>28&15]+n[p>>24&15];m%f==0&&(s(l),y=0)}return"0x"+b}(function(e){return{blocks:[],reset:!0,block:0,start:0,blockCount:1600-(e<<1)>>5,outputBlocks:e>>5,s:(t=[0,0,0,0,0,0,0,0,0,0],[].concat(t,t,t,t,t))};var t}(e),r)}};t.exports={keccak256:u(256),keccak512:u(512),keccak256s:u(256),keccak512s:u(512)}},{}],135:[function(e,t,r){const n=e("xtend"),i=e("json-rpc-random-id")();function o(e){this.currentProvider=e}function a(e){return function(){var t=[].slice.call(arguments),r=t.pop();this.sendAsync({method:e,params:t},r)}}function s(e,t){return function(){var r=[].slice.call(arguments),n=r.pop();r.lengtho)throw new Error("Elements exceed array size: "+o);for(d in h=[],e=e.slice(0,e.lastIndexOf("[")),"string"==typeof t&&(t=JSON.parse(t)),t)h.push(l(e,t[d]));if("dynamic"===o){var p=l("uint256",t.length);h.unshift(p)}return r.concat(h)}if("bytes"===e)return t=new r(t),h=r.concat([l("uint256",t.length),t]),t.length%32!=0&&(h=r.concat([h,n.zeros(32-t.length%32)])),h;if(e.startsWith("bytes")){if((o=s(e))<1||o>32)throw new Error("Invalid bytes width: "+o);return n.setLengthRight(t,32)}if(e.startsWith("uint")){if((o=s(e))%8||o<8||o>256)throw new Error("Invalid uint width: "+o);if((a=f(t)).bitLength()>o)throw new Error("Supplied uint exceeds width: "+o+" vs "+a.bitLength());if(a<0)throw new Error("Supplied uint is negative");return a.toArrayLike(r,"be",32)}if(e.startsWith("int")){if((o=s(e))%8||o<8||o>256)throw new Error("Invalid int width: "+o);if((a=f(t)).bitLength()>o)throw new Error("Supplied int exceeds width: "+o+" vs "+a.bitLength());return a.toTwos(256).toArrayLike(r,"be",32)}if(e.startsWith("ufixed")){if(o=u(e),(a=f(t))<0)throw new Error("Supplied ufixed is negative");return l("uint256",a.mul(new i(2).pow(new i(o[1]))))}if(e.startsWith("fixed"))return o=u(e),l("int256",f(t).mul(new i(2).pow(new i(o[1]))));throw new Error("Unsupported or invalid type: "+e)}function d(e,t,n){var o,a,s,u;if("string"==typeof e&&(e=p(e)),"address"===e.name)return d(e.rawType,t,n).toArrayLike(r,"be",20).toString("hex");if("bool"===e.name)return d(e.rawType,t,n).toString()===new i(1).toString();if("string"===e.name){var c=d(e.rawType,t,n);return new r(c,"utf8").toString()}if(e.isArray){for(s=[],o=e.size,"dynamic"===e.size&&(o=d("uint256",t,n=d("uint256",t,n).toNumber()).toNumber(),n+=32),u=0;ue.size)throw new Error("Decoded int exceeds width: "+e.size+" vs "+a.bitLength());return a}if(e.name.startsWith("int")){if((a=new i(t.slice(n,n+32),16,"be").fromTwos(256)).bitLength()>e.size)throw new Error("Decoded uint exceeds width: "+e.size+" vs "+a.bitLength());return a}if(e.name.startsWith("ufixed")){if(o=new i(2).pow(new i(e.size[1])),!(a=d("uint256",t,n)).mod(o).isZero())throw new Error("Decimals not supported yet");return a.div(o)}if(e.name.startsWith("fixed")){if(o=new i(2).pow(new i(e.size[1])),!(a=d("int256",t,n)).mod(o).isZero())throw new Error("Decimals not supported yet");return a.div(o)}throw new Error("Unsupported or invalid type: "+e.name)}function p(e){var t,r,n;if(y(e)){t=c(e);var i=e.slice(0,e.lastIndexOf("["));return i=p(i),r={isArray:!0,name:e,size:t,memoryUsage:"dynamic"===t?32:i.memoryUsage*t,subArray:i}}switch(e){case"address":n="uint160";break;case"bool":n="uint8";break;case"string":n="bytes"}if(r={rawType:n,name:e,memoryUsage:32},e.startsWith("bytes")&&"bytes"!==e||e.startsWith("uint")||e.startsWith("int")?r.size=s(e):(e.startsWith("ufixed")||e.startsWith("fixed"))&&(r.size=u(e)),e.startsWith("bytes")&&"bytes"!==e&&(r.size<1||r.size>32))throw new Error("Invalid bytes width: "+r.size);if((e.startsWith("uint")||e.startsWith("int"))&&(r.size%8||r.size<8||r.size>256))throw new Error("Invalid int/uint width: "+r.size);return r}function b(e){return"string"===e||"bytes"===e||"dynamic"===c(e)}function y(e){return e.lastIndexOf("]")===e.length-1}function m(e,t){return e.startsWith("address")||e.startsWith("bytes")?"0x"+t.toString("hex"):t.toString()}o.eventID=function(e,t){var i=e+"("+t.map(a).join(",")+")";return n.sha3(new r(i))},o.methodID=function(e,t){return o.eventID(e,t).slice(0,4)},o.rawEncode=function(e,t){var n=[],i=[],o=0;e.forEach(function(e){if(y(e)){var t=c(e);o+="dynamic"!==t?32*t:32}else o+=32});for(var s=0;s32)throw new Error("Invalid bytes width: "+i);u.push(n.setLengthRight(l,i))}else if(h.startsWith("uint")){if((i=s(h))%8||i<8||i>256)throw new Error("Invalid uint width: "+i);if((o=f(l)).bitLength()>i)throw new Error("Supplied uint exceeds width: "+i+" vs "+o.bitLength());u.push(o.toArrayLike(r,"be",i/8))}else{if(!h.startsWith("int"))throw new Error("Unsupported or invalid type: "+h);if((i=s(h))%8||i<8||i>256)throw new Error("Invalid int width: "+i);if((o=f(l)).bitLength()>i)throw new Error("Supplied int exceeds width: "+i+" vs "+o.bitLength());u.push(o.toTwos(i).toArrayLike(r,"be",i/8))}}return r.concat(u)},o.soliditySHA3=function(e,t){return n.sha3(o.solidityPack(e,t))},o.soliditySHA256=function(e,t){return n.sha256(o.solidityPack(e,t))},o.solidityRIPEMD160=function(e,t){return n.ripemd160(o.solidityPack(e,t),!0)},o.fromSerpent=function(e){for(var t,r=[],n=0;n="0"&&t<="9");)o+=e[a]-"0",a++;n=a-1,r.push(o)}else if("i"===i)r.push("int256");else{if("a"!==i)throw new Error("Unsupported or invalid type: "+i);r.push("int256[]")}}return r},o.toSerpent=function(e){for(var t=[],r=0;r0){var r=this.raw.slice();this.v=this._chainId,this.r=0,this.s=0,t=this.raw,this.raw=r}else t=this.raw.slice(0,6);return n.rlphash(t)},e.prototype.getChainId=function(){return this._chainId},e.prototype.getSenderAddress=function(){if(this._from)return this._from;var e=this.getSenderPublicKey();return this._from=n.publicToAddress(e),this._from},e.prototype.getSenderPublicKey=function(){if(!(this._senderPubKey&&this._senderPubKey.length||this.verifySignature()))throw new Error("Invalid Signature");return this._senderPubKey},e.prototype.verifySignature=function(){var e=this.hash(!1);if(this._homestead&&1===new o(this.s).cmp(a))return!1;try{var t=n.bufferToInt(this.v);this._chainId>0&&(t-=2*this._chainId+8),this._senderPubKey=n.ecrecover(e,t,this.r,this.s)}catch(e){return!1}return!!this._senderPubKey},e.prototype.sign=function(e){var t=this.hash(!1),r=n.ecsign(t,e);this._chainId>0&&(r.v+=2*this._chainId+8),Object.assign(this,r)},e.prototype.getDataFee=function(){for(var e=this.raw[5],t=new o(0),r=0;r0&&t.push(["gas limit is too low. Need at least "+this.getBaseFee()]),void 0===e||!1===e?0===t.length:t.join(" ")},e}();t.exports=s}).call(this,e("buffer").Buffer)},{buffer:84,"ethereum-common/params.json":137,"ethereumjs-util":141}],141:[function(e,t,r){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=e("keccak"),o=e("secp256k1"),a=e("assert"),s=e("rlp"),u=e("bn.js"),c=e("create-hash"),f=e("safe-buffer").Buffer;Object.assign(r,e("ethjs-util")),r.MAX_INTEGER=new u("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",16),r.TWO_POW256=new u("10000000000000000000000000000000000000000000000000000000000000000",16),r.KECCAK256_NULL_S="c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470",r.SHA3_NULL_S=r.KECCAK256_NULL_S,r.KECCAK256_NULL=f.from(r.KECCAK256_NULL_S,"hex"),r.SHA3_NULL=r.KECCAK256_NULL,r.KECCAK256_RLP_ARRAY_S="1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",r.SHA3_RLP_ARRAY_S=r.KECCAK256_RLP_ARRAY_S,r.KECCAK256_RLP_ARRAY=f.from(r.KECCAK256_RLP_ARRAY_S,"hex"),r.SHA3_RLP_ARRAY=r.KECCAK256_RLP_ARRAY,r.KECCAK256_RLP_S="56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",r.SHA3_RLP_S=r.KECCAK256_RLP_S,r.KECCAK256_RLP=f.from(r.KECCAK256_RLP_S,"hex"),r.SHA3_RLP=r.KECCAK256_RLP,r.BN=u,r.rlp=s,r.secp256k1=o,r.zeros=function(e){return f.allocUnsafe(e).fill(0)},r.zeroAddress=function(){var e=r.zeros(20);return r.bufferToHex(e)},r.setLengthLeft=r.setLength=function(e,t,n){var i=r.zeros(t);return e=r.toBuffer(e),n?e.length0&&"0"===t.toString();)t=(e=e.slice(1))[0];return e},r.toBuffer=function(e){if(!f.isBuffer(e))if(Array.isArray(e))e=f.from(e);else if("string"==typeof e)e=r.isHexString(e)?f.from(r.padToEven(r.stripHexPrefix(e)),"hex"):f.from(e);else if("number"==typeof e)e=r.intToBuffer(e);else if(null==e)e=f.allocUnsafe(0);else if(u.isBN(e))e=e.toArrayLike(f);else{if(!e.toArray)throw new Error("invalid type");e=f.from(e.toArray())}return e},r.bufferToInt=function(e){return new u(r.toBuffer(e)).toNumber()},r.bufferToHex=function(e){return"0x"+(e=r.toBuffer(e)).toString("hex")},r.fromSigned=function(e){return new u(e).fromTwos(256)},r.toUnsigned=function(e){return f.from(e.toTwos(256).toArray())},r.keccak=function(e,t){return e=r.toBuffer(e),t||(t=256),i("keccak"+t).update(e).digest()},r.keccak256=function(e){return r.keccak(e)},r.sha3=r.keccak,r.sha256=function(e){return e=r.toBuffer(e),c("sha256").update(e).digest()},r.ripemd160=function(e,t){e=r.toBuffer(e);var n=c("rmd160").update(e).digest();return!0===t?r.setLength(n,32):n},r.rlphash=function(e){return r.keccak(s.encode(e))},r.isValidPrivate=function(e){return o.privateKeyVerify(e)},r.isValidPublic=function(e,t){return 64===e.length?o.publicKeyVerify(f.concat([f.from([4]),e])):!!t&&o.publicKeyVerify(e)},r.pubToAddress=r.publicToAddress=function(e,t){return e=r.toBuffer(e),t&&64!==e.length&&(e=o.publicKeyConvert(e,!1).slice(1)),a(64===e.length),r.keccak(e).slice(-20)};var h=r.privateToPublic=function(e){return e=r.toBuffer(e),o.publicKeyCreate(e,!1).slice(1)};r.importPublic=function(e){return 64!==(e=r.toBuffer(e)).length&&(e=o.publicKeyConvert(e,!1).slice(1)),e},r.ecsign=function(e,t){var r=o.sign(e,t),n={};return n.r=r.signature.slice(0,32),n.s=r.signature.slice(32,64),n.v=r.recovery+27,n},r.hashPersonalMessage=function(e){var t=r.toBuffer("Ethereum Signed Message:\n"+e.length.toString());return r.keccak(f.concat([t,e]))},r.ecrecover=function(e,t,n,i){var a=f.concat([r.setLength(n,32),r.setLength(i,32)],64),s=t-27;if(0!==s&&1!==s)throw new Error("Invalid signature v value");var u=o.recover(e,a,s);return o.publicKeyConvert(u,!1).slice(1)},r.toRpcSig=function(e,t,n){if(27!==e&&28!==e)throw new Error("Invalid recovery id");return r.bufferToHex(f.concat([r.setLengthLeft(t,32),r.setLengthLeft(n,32),r.toBuffer(e-27)]))},r.fromRpcSig=function(e){if(65!==(e=r.toBuffer(e)).length)throw new Error("Invalid signature length");var t=e[64];return t<27&&(t+=27),{v:t,r:e.slice(0,32),s:e.slice(32,64)}},r.privateToAddress=function(e){return r.publicToAddress(h(e))},r.isValidAddress=function(e){return/^0x[0-9a-fA-F]{40}$/.test(e)},r.isZeroAddress=function(e){return r.zeroAddress()===r.addHexPrefix(e)},r.toChecksumAddress=function(e){e=r.stripHexPrefix(e).toLowerCase();for(var t=r.keccak(e).toString("hex"),n="0x",i=0;i=8?n+=e[i].toUpperCase():n+=e[i];return n},r.isValidChecksumAddress=function(e){return r.isValidAddress(e)&&r.toChecksumAddress(e)===e},r.generateAddress=function(e,t){return e=r.toBuffer(e),t=(t=new u(t)).isZero()?null:f.from(t.toArray()),r.rlphash([e,t]).slice(-20)},r.isPrecompiled=function(e){var t=r.unpad(e);return 1===t.length&&t[0]>=1&&t[0]<=8},r.addHexPrefix=function(e){return"string"!=typeof e?e:r.isHexPrefixed(e)?e:"0x"+e},r.isValidSignature=function(e,t,r,n){var i=new u("7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0",16),o=new u("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",16);return 32===t.length&&32===r.length&&((27===e||28===e)&&(t=new u(t),r=new u(r),!(t.isZero()||t.gt(o)||r.isZero()||r.gt(o))&&(!1!==n||1!==new u(r).cmp(i))))},r.baToJSON=function(e){if(f.isBuffer(e))return"0x"+e.toString("hex");if(e instanceof Array){for(var t=[],n=0;n=i.length,"The field "+t.name+" must not have more "+t.length+" bytes")):t.allowZero&&0===i.length||!t.length||a(t.length===i.length,"The field "+t.name+" must have byte length of "+t.length),e.raw[n]=i}e._fields.push(t.name),Object.defineProperty(e,t.name,{enumerable:!0,configurable:!0,get:i,set:o}),t.default&&(e[t.name]=t.default),t.alias&&Object.defineProperty(e,t.alias,{enumerable:!1,configurable:!0,set:o,get:i})}),i)if("string"==typeof i&&(i=f.from(r.stripHexPrefix(i),"hex")),f.isBuffer(i)&&(i=s.decode(i)),Array.isArray(i)){if(i.length>e._fields.length)throw new Error("wrong number of fields in data");i.forEach(function(t,n){e[e._fields[n]]=r.toBuffer(t)})}else{if("object"!==(void 0===i?"undefined":n(i)))throw new Error("invalid data");var o=Object.keys(i);t.forEach(function(t){-1!==o.indexOf(t.name)&&(e[t.name]=i[t.name]),-1!==o.indexOf(t.alias)&&(e[t.alias]=i[t.alias])})}}},{assert:19,"bn.js":53,"create-hash":91,"ethjs-util":155,keccak:195,rlp:289,"safe-buffer":290,secp256k1:295}],142:[function(e,t,r){arguments[4][128][0].apply(r,arguments)},{_process:257,dup:128}],143:[function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t};Object.defineProperty(r,"__esModule",{value:!0});var a=e("./address"),s=e("./bignumber"),u=e("./bytes"),c=e("./utf8"),f=e("./properties"),h=o(e("./errors")),l=new RegExp(/^bytes([0-9]*)$/),d=new RegExp(/^(u?int)([0-9]*)$/),p=new RegExp(/^(.*)\[([0-9]*)\]$/);r.defaultCoerceFunc=function(e,t){var r=e.match(d);return r&&parseInt(r[2])<=48?t.toNumber():t};var b=new RegExp("^([^)(]*)\\((.*)\\)([^)(]*)$"),y=new RegExp("^[A-Za-z_][A-Za-z0-9_]*$");function m(e){return e.match(/^uint($|[^1-9])/)?e="uint256"+e.substring(4):e.match(/^int($|[^1-9])/)&&(e="int256"+e.substring(3)),e}function v(e,t){function r(t){throw new Error('unexpected character "'+e[t]+'" at position '+t+' in "'+e+'"')}for(var n={type:"",name:"",state:{allowType:!0}},i=n,o=0;o1){var i=r[1].match(b);if(""!=i[1].trim()||""!=i[3].trim())throw new Error("unexpected tokens");L(i[2]).forEach(function(e){t.outputs.push(v(e))})}return t}(e.trim()));throw new Error("unknown signature")};var w=function(){return function(e,t,r,n,i){this.coerceFunc=e,this.name=t,this.type=r,this.localName=n,this.dynamic=i}}(),_=function(e){function t(t){var r=e.call(this,t.coerceFunc,t.name,t.type,void 0,t.dynamic)||this;return f.defineReadOnly(r,"coder",t),r}return i(t,e),t.prototype.encode=function(e){return this.coder.encode(e)},t.prototype.decode=function(e,t){return this.coder.decode(e,t)},t}(w),A=function(e){function t(t,r){return e.call(this,t,"null","",r,!1)||this}return i(t,e),t.prototype.encode=function(e){return u.arrayify([])},t.prototype.decode=function(e,t){if(t>e.length)throw new Error("invalid null");return{consumed:0,value:this.coerceFunc("null",void 0)}},t}(w),E=function(e){function t(t,r,n,i){var o=this,a=(n?"int":"uint")+8*r;return(o=e.call(this,t,a,a,i,!1)||this).size=r,o.signed=n,o}return i(t,e),t.prototype.encode=function(e){try{var t=s.bigNumberify(e);return t=t.toTwos(8*this.size).maskn(8*this.size),this.signed&&(t=t.fromTwos(8*this.size).toTwos(256)),u.padZeros(u.arrayify(t),32)}catch(t){h.throwError("invalid number value",h.INVALID_ARGUMENT,{arg:this.localName,coderType:this.name,value:e})}return null},t.prototype.decode=function(e,t){e.length32)throw new Error;t.set(r)}catch(t){h.throwError("invalid "+this.name+" value",h.INVALID_ARGUMENT,{arg:this.localName,coderType:this.name,value:t.value||e})}return t},t.prototype.decode=function(e,t){return e.length=0?n:"")+"]",s=-1===n||r.dynamic;return(o=e.call(this,t,"array",a,i,s)||this).coder=r,o.length=n,o}return i(t,e),t.prototype.encode=function(e){Array.isArray(e)||h.throwError("expected array value",h.INVALID_ARGUMENT,{arg:this.localName,coderType:"array",value:e});var t=this.length,r=new Uint8Array(0);-1===t&&(t=e.length,r=x.encode(t)),h.checkArgumentCount(t,e.length,"in coder array"+(this.localName?" "+this.localName:""));for(var n=[],i=0;i256||i%8!=0)&&h.throwError("invalid "+r[1]+" bit length",h.INVALID_ARGUMENT,{arg:"param",value:t}),new E(e,i/8,"int"===r[1],t.name);if(r=t.type.match(l))return(0===(i=parseInt(r[1]))||i>32)&&h.throwError("invalid bytes length",h.INVALID_ARGUMENT,{arg:"param",value:t}),new S(e,i,t.name);if(r=t.type.match(p)){var i=parseInt(r[2]||"-1");return(t=f.jsonCopy(t)).type=r[1],new N(e,D(e,t),i,t.name)}return"tuple"===t.type.substring(0,5)?function(e,t,r){t||(t=[]);var n=[];return t.forEach(function(t){n.push(D(e,t))}),new R(e,n,r)}(e,t.components,t.name):""===t.type?new A(e,t.name):(h.throwError("invalid type",h.INVALID_ARGUMENT,{arg:"type",value:t.type}),null)}var F=function(){function e(t){h.checkNew(this,e),t||(t=r.defaultCoerceFunc),f.defineReadOnly(this,"coerceFunc",t)}return e.prototype.encode=function(e,t){e.length!==t.length&&h.throwError("types/values length mismatch",h.INVALID_ARGUMENT,{count:{types:e.length,values:t.length},value:{types:e,values:t}});var r=[];return e.forEach(function(e){var t=null;t="string"==typeof e?v(e):e,r.push(D(this.coerceFunc,t))},this),u.hexlify(new R(this.coerceFunc,r,"_").encode(t))},e.prototype.decode=function(e,t){var r=[];return e.forEach(function(e){var t=null;t="string"==typeof e?v(e):f.jsonCopy(e),r.push(D(this.coerceFunc,t))},this),new R(this.coerceFunc,r,"_").decode(u.arrayify(t),0).value},e}();r.AbiCoder=F,r.defaultAbiCoder=new F},{"./address":144,"./bignumber":145,"./bytes":146,"./errors":147,"./properties":149,"./utf8":152}],144:[function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0});var i=n(e("bn.js")),o=e("./bytes"),a=e("./keccak256"),s=e("./rlp"),u=e("./errors");function c(e){"string"==typeof e&&e.match(/^0x[0-9A-Fa-f]{40}$/)||u.throwError("invalid address",u.INVALID_ARGUMENT,{arg:"address",value:e});for(var t=(e=e.toLowerCase()).substring(2).split(""),r=new Uint8Array(40),n=0;n<40;n++)r[n]=t[n].charCodeAt(0);r=o.arrayify(a.keccak256(r));for(var i=0;i<40;i+=2)r[i>>1]>>4>=8&&(t[i]=t[i].toUpperCase()),(15&r[i>>1])>=8&&(t[i+1]=t[i+1].toUpperCase());return"0x"+t.join("")}for(var f={},h=0;h<10;h++)f[String(h)]=String(h);for(h=0;h<26;h++)f[String.fromCharCode(65+h)]=String(10+h);var l,d=Math.floor((l=9007199254740991,Math.log10?Math.log10(l):Math.log(l)/Math.LN10));function p(e){e=(e=e.toUpperCase()).substring(4)+e.substring(0,2)+"00";var t="";for(e.split("").forEach(function(e){t+=f[e]});t.length>=d;){var r=t.substring(0,d);t=parseInt(r,10)%97+t.substring(r.length)}for(var n=String(98-parseInt(t,10)%97);n.length<2;)n="0"+n;return n}function b(e){var t=null;if("string"!=typeof e&&u.throwError("invalid address",u.INVALID_ARGUMENT,{arg:"address",value:e}),e.match(/^(0x)?[0-9a-fA-F]{40}$/))"0x"!==e.substring(0,2)&&(e="0x"+e),t=c(e),e.match(/([A-F].*[a-f])|([a-f].*[A-F])/)&&t!==e&&u.throwError("bad address checksum",u.INVALID_ARGUMENT,{arg:"address",value:e});else if(e.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){for(e.substring(2,4)!==p(e)&&u.throwError("bad icap checksum",u.INVALID_ARGUMENT,{arg:"address",value:e}),t=new i.default.BN(e.substring(4),36).toString(16);t.length<40;)t="0"+t;t=c("0x"+t)}else u.throwError("invalid address",u.INVALID_ARGUMENT,{arg:"address",value:e});return t}r.getAddress=b,r.getIcapAddress=function(e){for(var t=new i.default.BN(b(e).substring(2),16).toString(36).toUpperCase();t.length<30;)t="0"+t;return"XE"+p("XE00"+t)+t},r.getContractAddress=function(e){if(!e.from)throw new Error("missing from address");var t=e.nonce;return b("0x"+a.keccak256(s.encode([b(e.from),o.stripZeros(o.hexlify(t))])).substring(26))}},{"./bytes":146,"./errors":147,"./keccak256":148,"./rlp":150,"bn.js":53}],145:[function(e,t,r){"use strict";var n,i=this&&this.__extends||(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])},function(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t};Object.defineProperty(r,"__esModule",{value:!0});var s=o(e("bn.js")),u=e("./bytes"),c=e("./properties"),f=e("./types"),h=a(e("./errors")),l=new s.default.BN(-1);function d(e){var t=e.toString(16);return"-"===t[0]?t.length%2==0?"-0x0"+t.substring(1):"-0x"+t.substring(1):t.length%2==1?"0x0"+t:"0x"+t}function p(e){return m(e)._bn}function b(e){return new y(d(e))}var y=function(e){function t(r){var n=e.call(this)||this;if(h.checkNew(n,t),"string"==typeof r)u.isHexString(r)?("0x"==r&&(r="0x0"),c.defineReadOnly(n,"_hex",r)):"-"===r[0]&&u.isHexString(r.substring(1))?c.defineReadOnly(n,"_hex",r):r.match(/^-?[0-9]*$/)?(""==r&&(r="0"),c.defineReadOnly(n,"_hex",d(new s.default.BN(r)))):h.throwError("invalid BigNumber string value",h.INVALID_ARGUMENT,{arg:"value",value:r});else if("number"==typeof r){parseInt(String(r))!==r&&h.throwError("underflow",h.NUMERIC_FAULT,{operation:"setValue",fault:"underflow",value:r,outputValue:parseInt(String(r))});try{c.defineReadOnly(n,"_hex",d(new s.default.BN(r)))}catch(e){h.throwError("overflow",h.NUMERIC_FAULT,{operation:"setValue",fault:"overflow",details:e.message})}}else r instanceof t?c.defineReadOnly(n,"_hex",r._hex):r.toHexString?c.defineReadOnly(n,"_hex",d(p(r.toHexString()))):u.isArrayish(r)?c.defineReadOnly(n,"_hex",d(new s.default.BN(u.hexlify(r).substring(2),16))):h.throwError("invalid BigNumber value",h.INVALID_ARGUMENT,{arg:"value",value:r});return n}return i(t,e),Object.defineProperty(t.prototype,"_bn",{get:function(){return"-"===this._hex[0]?new s.default.BN(this._hex.substring(3),16).mul(l):new s.default.BN(this._hex.substring(2),16)},enumerable:!0,configurable:!0}),t.prototype.fromTwos=function(e){return b(this._bn.fromTwos(e))},t.prototype.toTwos=function(e){return b(this._bn.toTwos(e))},t.prototype.add=function(e){return b(this._bn.add(p(e)))},t.prototype.sub=function(e){return b(this._bn.sub(p(e)))},t.prototype.div=function(e){return m(e).isZero()&&h.throwError("division by zero",h.NUMERIC_FAULT,{operation:"divide",fault:"division by zero"}),b(this._bn.div(p(e)))},t.prototype.mul=function(e){return b(this._bn.mul(p(e)))},t.prototype.mod=function(e){return b(this._bn.mod(p(e)))},t.prototype.pow=function(e){return b(this._bn.pow(p(e)))},t.prototype.maskn=function(e){return b(this._bn.maskn(e))},t.prototype.eq=function(e){return this._bn.eq(p(e))},t.prototype.lt=function(e){return this._bn.lt(p(e))},t.prototype.lte=function(e){return this._bn.lte(p(e))},t.prototype.gt=function(e){return this._bn.gt(p(e))},t.prototype.gte=function(e){return this._bn.gte(p(e))},t.prototype.isZero=function(){return this._bn.isZero()},t.prototype.toNumber=function(){try{return this._bn.toNumber()}catch(e){h.throwError("overflow",h.NUMERIC_FAULT,{operation:"setValue",fault:"overflow",details:e.message})}return null},t.prototype.toString=function(){return this._bn.toString(10)},t.prototype.toHexString=function(){return this._hex},t}(f.BigNumber);function m(e){return e instanceof y?e:new y(e)}r.bigNumberify=m,r.ConstantNegativeOne=m(-1),r.ConstantZero=m(0),r.ConstantOne=m(1),r.ConstantTwo=m(2),r.ConstantWeiPerEther=m("1000000000000000000")},{"./bytes":146,"./errors":147,"./properties":149,"./types":151,"bn.js":53}],146:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("./errors");function i(e){return!!e._bn}function o(e){return e.slice?e:(e.slice=function(){var t=Array.prototype.slice.call(arguments);return new Uint8Array(Array.prototype.slice.apply(e,t))},e)}function a(e){if(!e||parseInt(String(e.length))!=e.length||"string"==typeof e)return!1;for(var t=0;t=256||parseInt(String(r))!=r)return!1}return!0}function s(e){if(null==e&&n.throwError("cannot convert null value to array",n.INVALID_ARGUMENT,{arg:"value",value:e}),i(e)&&(e=e.toHexString()),"string"==typeof e){var t=e.match(/^(0x)?[0-9a-fA-F]*$/);t||n.throwError("invalid hexidecimal string",n.INVALID_ARGUMENT,{arg:"value",value:e}),"0x"!==t[1]&&n.throwError("hex string must have 0x prefix",n.INVALID_ARGUMENT,{arg:"value",value:e}),(e=e.substring(2)).length%2&&(e="0"+e);for(var r=[],s=0;s>4]+f[15&u])}return"0x"+o.join("")}return n.throwError("invalid hexlify value",null,{arg:"value",value:e}),"never"}function l(e,t){for(c(e)||n.throwError("invalid hex string",n.INVALID_ARGUMENT,{arg:"value",value:e});e.length<2*t+2;)e="0x0"+e.substring(2);return e}function d(e){var t,r=0,i="0x",o="0x";if((t=e)&&null!=t.r&&null!=t.s){null==e.v&&null==e.recoveryParam&&n.throwError("at least on of recoveryParam or v must be specified",n.INVALID_ARGUMENT,{argument:"signature",value:e}),i=l(e.r,32),o=l(e.s,32),"string"==typeof(r=e.v)&&(r=parseInt(r,16));var a=e.recoveryParam;null==a&&null!=e.v&&(a=1-r%2),r=27+a}else{var u=s(e);if(65!==u.length)throw new Error("invalid signature");i=h(u.slice(0,32)),o=h(u.slice(32,64)),27!==(r=u[64])&&28!==r&&(r=27+r%2)}return{r:i,s:o,recoveryParam:r-27,v:r}}r.hexlify=h,r.hexDataLength=function(e){return c(e)&&e.length%2==0?(e.length-2)/2:null},r.hexDataSlice=function(e,t,r){return c(e)||n.throwError("invalid hex data",n.INVALID_ARGUMENT,{arg:"value",value:e}),e.length%2!=0&&n.throwError("hex data length must be even",n.INVALID_ARGUMENT,{arg:"value",value:e}),t=2+2*t,null!=r?"0x"+e.substring(t,t+2*r):"0x"+e.substring(t)},r.hexStripZeros=function(e){for(c(e)||n.throwError("invalid hex string",n.INVALID_ARGUMENT,{arg:"value",value:e});e.length>3&&"0x0"===e.substring(0,3);)e="0x"+e.substring(3);return e},r.hexZeroPad=l,r.splitSignature=d,r.joinSignature=function(e){return h(u([(e=d(e)).r,e.s,e.recoveryParam?"0x1c":"0x1b"]))}},{"./errors":147}],147:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.UNKNOWN_ERROR="UNKNOWN_ERROR",r.NOT_IMPLEMENTED="NOT_IMPLEMENTED",r.MISSING_NEW="MISSING_NEW",r.CALL_EXCEPTION="CALL_EXCEPTION",r.INVALID_ARGUMENT="INVALID_ARGUMENT",r.MISSING_ARGUMENT="MISSING_ARGUMENT",r.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",r.NUMERIC_FAULT="NUMERIC_FAULT",r.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION";var n=!1,i=!1;function o(e,t,n){if(i)throw new Error("unknown error");t||(t=r.UNKNOWN_ERROR),n||(n={});var o=[];Object.keys(n).forEach(function(e){try{o.push(e+"="+JSON.stringify(n[e]))}catch(t){o.push(e+"="+JSON.stringify(n[e].toString()))}});var a=e;o.length&&(e+=" ("+o.join(", ")+")");var s=new Error(e);throw s.reason=a,s.code=t,Object.keys(n).forEach(function(e){s[e]=n[e]}),s}r.throwError=o,r.checkNew=function(e,t){e instanceof t||o("missing new",r.MISSING_NEW,{name:t.name})},r.checkArgumentCount=function(e,t,n){n||(n=""),et&&o("too many arguments"+n,r.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})},r.setCensorship=function(e,t){n&&o("error censorship permanent",r.UNSUPPORTED_OPERATION,{operation:"setCersorship"}),i=!!e,n=!!t}},{}],148:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("js-sha3"),i=e("./bytes");r.keccak256=function(e){return"0x"+n.keccak_256(i.arrayify(e))}},{"./bytes":146,"js-sha3":142}],149:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.defineReadOnly=function(e,t,r){Object.defineProperty(e,t,{enumerable:!0,value:r,writable:!1})},r.defineFrozen=function(e,t,r){var n=JSON.stringify(r);Object.defineProperty(e,t,{enumerable:!0,get:function(){return JSON.parse(n)}})},r.resolveProperties=function(e){var t={},r=[];return Object.keys(e).forEach(function(n){var i=e[n];i instanceof Promise?r.push(i.then(function(e){return t[n]=e,null})):t[n]=i}),Promise.all(r).then(function(){return t})},r.shallowCopy=function(e){var t={};for(var r in e)t[r]=e[r];return t},r.jsonCopy=function(e){return JSON.parse(JSON.stringify(e))}},{}],150:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=e("./bytes");function i(e){for(var t=[];e;)t.unshift(255&e),e>>=8;return t}function o(e,t,r){for(var n=0,i=0;it+1+n)throw new Error("invalid rlp")}return{consumed:1+n,result:i}}function s(e,t){if(0===e.length)throw new Error("invalid rlp data");if(e[t]>=248){if(t+1+(r=e[t]-247)>e.length)throw new Error("too short");if(t+1+r+(i=o(e,t+1,r))>e.length)throw new Error("to short");return a(e,t,t+1+r,r+i)}if(e[t]>=192){if(t+1+(i=e[t]-192)>e.length)throw new Error("invalid rlp data");return a(e,t,t+1,i)}if(e[t]>=184){var r;if(t+1+(r=e[t]-183)>e.length)throw new Error("invalid rlp data");if(t+1+r+(i=o(e,t+1,r))>e.length)throw new Error("invalid rlp data");return{consumed:1+r+i,result:n.hexlify(e.slice(t+1+r,t+1+r+i))}}if(e[t]>=128){var i;if(t+1+(i=e[t]-128)>e.length)throw new Error("invlaid rlp data");return{consumed:1+i,result:n.hexlify(e.slice(t+1,t+1+i))}}return{consumed:1,result:n.hexlify(e[t])}}r.encode=function(e){return n.hexlify(function e(t){if(Array.isArray(t)){var r=[];return t.forEach(function(t){r=r.concat(e(t))}),r.length<=55?(r.unshift(192+r.length),r):((o=i(r.length)).unshift(247+o.length),o.concat(r))}var o,a=Array.prototype.slice.call(n.arrayify(t));return 1===a.length&&a[0]<=127?a:a.length<=55?(a.unshift(128+a.length),a):((o=i(a.length)).unshift(183+o.length),o.concat(a))}(e))},r.decode=function(e){var t=n.arrayify(e),r=s(t,0);if(r.consumed!==t.length)throw new Error("invalid rlp data");return r.result}},{"./bytes":146}],151:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=function(){return function(){}}();r.BigNumber=n;var i=function(){return function(){}}();r.Indexed=i;var o=function(){return function(){}}();r.MinimalProvider=o;var a=function(){return function(){}}();r.Signer=a;var s=function(){return function(){}}();r.HDNode=s},{}],152:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n,i=e("./bytes");!function(e){e.current="",e.NFC="NFC",e.NFD="NFD",e.NFKC="NFKC",e.NFKD="NFKD"}(n=r.UnicodeNormalizationForm||(r.UnicodeNormalizationForm={})),r.toUtf8Bytes=function(e,t){void 0===t&&(t=n.current),t!=n.current&&(e=e.normalize(t));for(var r=[],o=0,a=0;a>6|192,r[o++]=63&s|128):55296==(64512&s)&&a+1>18|240,r[o++]=s>>12&63|128,r[o++]=s>>6&63|128,r[o++]=63&s|128):(r[o++]=s>>12|224,r[o++]=s>>6&63|128,r[o++]=63&s|128)}return i.arrayify(r)},r.toUtf8String=function(e){e=i.arrayify(e);for(var t="",r=0;r>7!=0){if(n>>6!=2){var o=null;if(n>>5==6)o=1;else if(n>>4==14)o=2;else if(n>>3==30)o=3;else if(n>>2==62)o=4;else{if(n>>1!=126)continue;o=5}if(r+o>e.length){for(;r>6==2;r++);if(r!=e.length)continue;return t}var a,s=n&(1<<8-o-1)-1;for(a=0;a>6!=2)break;s=s<<6|63&u}a==o?s<=65535?t+=String.fromCharCode(s):(s-=65536,t+=String.fromCharCode(55296+(s>>10&1023),56320+(1023&s))):r--}}else t+=String.fromCharCode(n)}return t}},{"./bytes":146}],153:[function(e,t,r){"use strict";var n=e("bn.js"),i=e("number-to-bn"),o=new n(0),a=new n(-1),s={noether:"0",wei:"1",kwei:"1000",Kwei:"1000",babbage:"1000",femtoether:"1000",mwei:"1000000",Mwei:"1000000",lovelace:"1000000",picoether:"1000000",gwei:"1000000000",Gwei:"1000000000",shannon:"1000000000",nanoether:"1000000000",nano:"1000000000",szabo:"1000000000000",microether:"1000000000000",micro:"1000000000000",finney:"1000000000000000",milliether:"1000000000000000",milli:"1000000000000000",ether:"1000000000000000000",kether:"1000000000000000000000",grand:"1000000000000000000000",mether:"1000000000000000000000000",gether:"1000000000000000000000000000",tether:"1000000000000000000000000000000"};function u(e){var t=e?e.toLowerCase():"ether",r=s[t];if("string"!=typeof r)throw new Error("[ethjs-unit] the unit provided "+e+" doesn't exists, please use the one of the following units "+JSON.stringify(s,null,2));return new n(r,10)}function c(e){if("string"==typeof e){if(!e.match(/^-?[0-9.]+$/))throw new Error("while converting number to string, invalid number value '"+e+"', should be a number matching (^-?[0-9.]+).");return e}if("number"==typeof e)return String(e);if("object"==typeof e&&e.toString&&(e.toTwos||e.dividedToIntegerBy))return e.toPrecision?String(e.toPrecision()):e.toString(10);throw new Error("while converting number to string, invalid number value '"+e+"' type "+typeof e+".")}t.exports={unitMap:s,numberToString:c,getValueOfUnit:u,fromWei:function(e,t,r){var n=i(e),c=n.lt(o),f=u(t),h=s[t].length-1||1,l=r||{};c&&(n=n.mul(a));for(var d=n.mod(f).toString(10);d.length2)throw new Error("[ethjs-unit] while converting number "+e+" to wei, too many decimal points");var l=h[0],d=h[1];if(l||(l="0"),d||(d="0"),d.length>o)throw new Error("[ethjs-unit] while converting number "+e+" to wei, too many decimal places");for(;d.length=49&&a<=54?a-49+10:a>=17&&a<=22?a-17+10:15&a}return n}function u(e,t,r,n){for(var i=0,o=Math.min(e.length,r),a=t;a=49?s-49+10:s>=17?s-17+10:s}return i}o.isBN=function(e){return e instanceof o||null!==e&&"object"==typeof e&&e.constructor.wordSize===o.wordSize&&Array.isArray(e.words)},o.max=function(e,t){return e.cmp(t)>0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&i++,16===t?this._parseHex(e,i):this._parseBase(e,t,i),"-"===e[0]&&(this.negative=1),this.strip(),"le"===r&&this._initArray(this.toArray(),t,r)},o.prototype._initNumber=function(e,t,r){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(n(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===r&&this._initArray(this.toArray(),t,r)},o.prototype._initArray=function(e,t,r){if(n("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3)a=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[o]|=a<>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);else if("le"===r)for(i=0,o=0;i>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);return this.strip()},o.prototype._parseHex=function(e,t){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var r=0;r=t;r-=6)i=s(e,r,r+6),this.words[n]|=i<>>26-o&4194303,(o+=24)>=26&&(o-=26,n++);r+6!==t&&(i=s(e,t,r+6),this.words[n]|=i<>>26-o&4194303),this.strip()},o.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=t)n++;n--,i=i/t|0;for(var o=e.length-r,a=o%n,s=Math.min(o,o-a)+r,c=0,f=r;f1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},o.prototype.inspect=function(){return(this.red?""};var c=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],f=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],h=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(e,t,r){r.negative=t.negative^e.negative;var n=e.length+t.length|0;r.length=n,n=n-1|0;var i=0|e.words[0],o=0|t.words[0],a=i*o,s=67108863&a,u=a/67108864|0;r.words[0]=s;for(var c=1;c>>26,h=67108863&u,l=Math.min(c,t.length-1),d=Math.max(0,c-e.length+1);d<=l;d++){var p=c-d|0;f+=(a=(i=0|e.words[p])*(o=0|t.words[d])+h)/67108864|0,h=67108863&a}r.words[c]=0|h,u=0|f}return 0!==u?r.words[c]=0|u:r.length--,r.strip()}o.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var i=0,o=0,a=0;a>>24-i&16777215)||a!==this.length-1?c[6-u.length]+u+r:u+r,(i+=2)>=26&&(i-=26,a--)}for(0!==o&&(r=o.toString(16)+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var l=f[e],d=h[e];r="";var p=this.clone();for(p.negative=0;!p.isZero();){var b=p.modn(d).toString(e);r=(p=p.idivn(d)).isZero()?b+r:c[l-b.length]+b+r}for(this.isZero()&&(r="0"+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16)},o.prototype.toBuffer=function(e,t){return n(void 0!==a),this.toArrayLike(a,e,t)},o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},o.prototype.toArrayLike=function(e,t,r){var i=this.byteLength(),o=r||Math.max(1,i);n(i<=o,"byte array longer than desired length"),n(o>0,"Requested array length <= 0"),this.strip();var a,s,u="le"===t,c=new e(o),f=this.clone();if(u){for(s=0;!f.isZero();s++)a=f.andln(255),f.iushrn(8),c[s]=a;for(;s=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;re.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,r;this.length>e.length?(t=this,r=e):(t=e,r=this);for(var n=0;ne.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-r),this.strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,i=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<e.length?(r=this,n=e):(r=e,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;oe.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var r,n,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=e):(r=e,n=this);for(var o=0,a=0;a>26,this.words[a]=67108863&t;for(;0!==o&&a>26,this.words[a]=67108863&t;if(0===o&&a>>13,d=0|a[1],p=8191&d,b=d>>>13,y=0|a[2],m=8191&y,v=y>>>13,g=0|a[3],w=8191&g,_=g>>>13,A=0|a[4],E=8191&A,x=A>>>13,k=0|a[5],S=8191&k,M=k>>>13,I=0|a[6],T=8191&I,U=I>>>13,j=0|a[7],B=8191&j,P=j>>>13,C=0|a[8],N=8191&C,R=C>>>13,L=0|a[9],O=8191&L,D=L>>>13,F=0|s[0],q=8191&F,H=F>>>13,z=0|s[1],K=8191&z,V=z>>>13,G=0|s[2],W=8191&G,Y=G>>>13,X=0|s[3],Z=8191&X,J=X>>>13,$=0|s[4],Q=8191&$,ee=$>>>13,te=0|s[5],re=8191&te,ne=te>>>13,ie=0|s[6],oe=8191&ie,ae=ie>>>13,se=0|s[7],ue=8191&se,ce=se>>>13,fe=0|s[8],he=8191&fe,le=fe>>>13,de=0|s[9],pe=8191&de,be=de>>>13;r.negative=e.negative^t.negative,r.length=19;var ye=(c+(n=Math.imul(h,q))|0)+((8191&(i=(i=Math.imul(h,H))+Math.imul(l,q)|0))<<13)|0;c=((o=Math.imul(l,H))+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,n=Math.imul(p,q),i=(i=Math.imul(p,H))+Math.imul(b,q)|0,o=Math.imul(b,H);var me=(c+(n=n+Math.imul(h,K)|0)|0)+((8191&(i=(i=i+Math.imul(h,V)|0)+Math.imul(l,K)|0))<<13)|0;c=((o=o+Math.imul(l,V)|0)+(i>>>13)|0)+(me>>>26)|0,me&=67108863,n=Math.imul(m,q),i=(i=Math.imul(m,H))+Math.imul(v,q)|0,o=Math.imul(v,H),n=n+Math.imul(p,K)|0,i=(i=i+Math.imul(p,V)|0)+Math.imul(b,K)|0,o=o+Math.imul(b,V)|0;var ve=(c+(n=n+Math.imul(h,W)|0)|0)+((8191&(i=(i=i+Math.imul(h,Y)|0)+Math.imul(l,W)|0))<<13)|0;c=((o=o+Math.imul(l,Y)|0)+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,n=Math.imul(w,q),i=(i=Math.imul(w,H))+Math.imul(_,q)|0,o=Math.imul(_,H),n=n+Math.imul(m,K)|0,i=(i=i+Math.imul(m,V)|0)+Math.imul(v,K)|0,o=o+Math.imul(v,V)|0,n=n+Math.imul(p,W)|0,i=(i=i+Math.imul(p,Y)|0)+Math.imul(b,W)|0,o=o+Math.imul(b,Y)|0;var ge=(c+(n=n+Math.imul(h,Z)|0)|0)+((8191&(i=(i=i+Math.imul(h,J)|0)+Math.imul(l,Z)|0))<<13)|0;c=((o=o+Math.imul(l,J)|0)+(i>>>13)|0)+(ge>>>26)|0,ge&=67108863,n=Math.imul(E,q),i=(i=Math.imul(E,H))+Math.imul(x,q)|0,o=Math.imul(x,H),n=n+Math.imul(w,K)|0,i=(i=i+Math.imul(w,V)|0)+Math.imul(_,K)|0,o=o+Math.imul(_,V)|0,n=n+Math.imul(m,W)|0,i=(i=i+Math.imul(m,Y)|0)+Math.imul(v,W)|0,o=o+Math.imul(v,Y)|0,n=n+Math.imul(p,Z)|0,i=(i=i+Math.imul(p,J)|0)+Math.imul(b,Z)|0,o=o+Math.imul(b,J)|0;var we=(c+(n=n+Math.imul(h,Q)|0)|0)+((8191&(i=(i=i+Math.imul(h,ee)|0)+Math.imul(l,Q)|0))<<13)|0;c=((o=o+Math.imul(l,ee)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,n=Math.imul(S,q),i=(i=Math.imul(S,H))+Math.imul(M,q)|0,o=Math.imul(M,H),n=n+Math.imul(E,K)|0,i=(i=i+Math.imul(E,V)|0)+Math.imul(x,K)|0,o=o+Math.imul(x,V)|0,n=n+Math.imul(w,W)|0,i=(i=i+Math.imul(w,Y)|0)+Math.imul(_,W)|0,o=o+Math.imul(_,Y)|0,n=n+Math.imul(m,Z)|0,i=(i=i+Math.imul(m,J)|0)+Math.imul(v,Z)|0,o=o+Math.imul(v,J)|0,n=n+Math.imul(p,Q)|0,i=(i=i+Math.imul(p,ee)|0)+Math.imul(b,Q)|0,o=o+Math.imul(b,ee)|0;var _e=(c+(n=n+Math.imul(h,re)|0)|0)+((8191&(i=(i=i+Math.imul(h,ne)|0)+Math.imul(l,re)|0))<<13)|0;c=((o=o+Math.imul(l,ne)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,n=Math.imul(T,q),i=(i=Math.imul(T,H))+Math.imul(U,q)|0,o=Math.imul(U,H),n=n+Math.imul(S,K)|0,i=(i=i+Math.imul(S,V)|0)+Math.imul(M,K)|0,o=o+Math.imul(M,V)|0,n=n+Math.imul(E,W)|0,i=(i=i+Math.imul(E,Y)|0)+Math.imul(x,W)|0,o=o+Math.imul(x,Y)|0,n=n+Math.imul(w,Z)|0,i=(i=i+Math.imul(w,J)|0)+Math.imul(_,Z)|0,o=o+Math.imul(_,J)|0,n=n+Math.imul(m,Q)|0,i=(i=i+Math.imul(m,ee)|0)+Math.imul(v,Q)|0,o=o+Math.imul(v,ee)|0,n=n+Math.imul(p,re)|0,i=(i=i+Math.imul(p,ne)|0)+Math.imul(b,re)|0,o=o+Math.imul(b,ne)|0;var Ae=(c+(n=n+Math.imul(h,oe)|0)|0)+((8191&(i=(i=i+Math.imul(h,ae)|0)+Math.imul(l,oe)|0))<<13)|0;c=((o=o+Math.imul(l,ae)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,n=Math.imul(B,q),i=(i=Math.imul(B,H))+Math.imul(P,q)|0,o=Math.imul(P,H),n=n+Math.imul(T,K)|0,i=(i=i+Math.imul(T,V)|0)+Math.imul(U,K)|0,o=o+Math.imul(U,V)|0,n=n+Math.imul(S,W)|0,i=(i=i+Math.imul(S,Y)|0)+Math.imul(M,W)|0,o=o+Math.imul(M,Y)|0,n=n+Math.imul(E,Z)|0,i=(i=i+Math.imul(E,J)|0)+Math.imul(x,Z)|0,o=o+Math.imul(x,J)|0,n=n+Math.imul(w,Q)|0,i=(i=i+Math.imul(w,ee)|0)+Math.imul(_,Q)|0,o=o+Math.imul(_,ee)|0,n=n+Math.imul(m,re)|0,i=(i=i+Math.imul(m,ne)|0)+Math.imul(v,re)|0,o=o+Math.imul(v,ne)|0,n=n+Math.imul(p,oe)|0,i=(i=i+Math.imul(p,ae)|0)+Math.imul(b,oe)|0,o=o+Math.imul(b,ae)|0;var Ee=(c+(n=n+Math.imul(h,ue)|0)|0)+((8191&(i=(i=i+Math.imul(h,ce)|0)+Math.imul(l,ue)|0))<<13)|0;c=((o=o+Math.imul(l,ce)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,n=Math.imul(N,q),i=(i=Math.imul(N,H))+Math.imul(R,q)|0,o=Math.imul(R,H),n=n+Math.imul(B,K)|0,i=(i=i+Math.imul(B,V)|0)+Math.imul(P,K)|0,o=o+Math.imul(P,V)|0,n=n+Math.imul(T,W)|0,i=(i=i+Math.imul(T,Y)|0)+Math.imul(U,W)|0,o=o+Math.imul(U,Y)|0,n=n+Math.imul(S,Z)|0,i=(i=i+Math.imul(S,J)|0)+Math.imul(M,Z)|0,o=o+Math.imul(M,J)|0,n=n+Math.imul(E,Q)|0,i=(i=i+Math.imul(E,ee)|0)+Math.imul(x,Q)|0,o=o+Math.imul(x,ee)|0,n=n+Math.imul(w,re)|0,i=(i=i+Math.imul(w,ne)|0)+Math.imul(_,re)|0,o=o+Math.imul(_,ne)|0,n=n+Math.imul(m,oe)|0,i=(i=i+Math.imul(m,ae)|0)+Math.imul(v,oe)|0,o=o+Math.imul(v,ae)|0,n=n+Math.imul(p,ue)|0,i=(i=i+Math.imul(p,ce)|0)+Math.imul(b,ue)|0,o=o+Math.imul(b,ce)|0;var xe=(c+(n=n+Math.imul(h,he)|0)|0)+((8191&(i=(i=i+Math.imul(h,le)|0)+Math.imul(l,he)|0))<<13)|0;c=((o=o+Math.imul(l,le)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,n=Math.imul(O,q),i=(i=Math.imul(O,H))+Math.imul(D,q)|0,o=Math.imul(D,H),n=n+Math.imul(N,K)|0,i=(i=i+Math.imul(N,V)|0)+Math.imul(R,K)|0,o=o+Math.imul(R,V)|0,n=n+Math.imul(B,W)|0,i=(i=i+Math.imul(B,Y)|0)+Math.imul(P,W)|0,o=o+Math.imul(P,Y)|0,n=n+Math.imul(T,Z)|0,i=(i=i+Math.imul(T,J)|0)+Math.imul(U,Z)|0,o=o+Math.imul(U,J)|0,n=n+Math.imul(S,Q)|0,i=(i=i+Math.imul(S,ee)|0)+Math.imul(M,Q)|0,o=o+Math.imul(M,ee)|0,n=n+Math.imul(E,re)|0,i=(i=i+Math.imul(E,ne)|0)+Math.imul(x,re)|0,o=o+Math.imul(x,ne)|0,n=n+Math.imul(w,oe)|0,i=(i=i+Math.imul(w,ae)|0)+Math.imul(_,oe)|0,o=o+Math.imul(_,ae)|0,n=n+Math.imul(m,ue)|0,i=(i=i+Math.imul(m,ce)|0)+Math.imul(v,ue)|0,o=o+Math.imul(v,ce)|0,n=n+Math.imul(p,he)|0,i=(i=i+Math.imul(p,le)|0)+Math.imul(b,he)|0,o=o+Math.imul(b,le)|0;var ke=(c+(n=n+Math.imul(h,pe)|0)|0)+((8191&(i=(i=i+Math.imul(h,be)|0)+Math.imul(l,pe)|0))<<13)|0;c=((o=o+Math.imul(l,be)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,n=Math.imul(O,K),i=(i=Math.imul(O,V))+Math.imul(D,K)|0,o=Math.imul(D,V),n=n+Math.imul(N,W)|0,i=(i=i+Math.imul(N,Y)|0)+Math.imul(R,W)|0,o=o+Math.imul(R,Y)|0,n=n+Math.imul(B,Z)|0,i=(i=i+Math.imul(B,J)|0)+Math.imul(P,Z)|0,o=o+Math.imul(P,J)|0,n=n+Math.imul(T,Q)|0,i=(i=i+Math.imul(T,ee)|0)+Math.imul(U,Q)|0,o=o+Math.imul(U,ee)|0,n=n+Math.imul(S,re)|0,i=(i=i+Math.imul(S,ne)|0)+Math.imul(M,re)|0,o=o+Math.imul(M,ne)|0,n=n+Math.imul(E,oe)|0,i=(i=i+Math.imul(E,ae)|0)+Math.imul(x,oe)|0,o=o+Math.imul(x,ae)|0,n=n+Math.imul(w,ue)|0,i=(i=i+Math.imul(w,ce)|0)+Math.imul(_,ue)|0,o=o+Math.imul(_,ce)|0,n=n+Math.imul(m,he)|0,i=(i=i+Math.imul(m,le)|0)+Math.imul(v,he)|0,o=o+Math.imul(v,le)|0;var Se=(c+(n=n+Math.imul(p,pe)|0)|0)+((8191&(i=(i=i+Math.imul(p,be)|0)+Math.imul(b,pe)|0))<<13)|0;c=((o=o+Math.imul(b,be)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,n=Math.imul(O,W),i=(i=Math.imul(O,Y))+Math.imul(D,W)|0,o=Math.imul(D,Y),n=n+Math.imul(N,Z)|0,i=(i=i+Math.imul(N,J)|0)+Math.imul(R,Z)|0,o=o+Math.imul(R,J)|0,n=n+Math.imul(B,Q)|0,i=(i=i+Math.imul(B,ee)|0)+Math.imul(P,Q)|0,o=o+Math.imul(P,ee)|0,n=n+Math.imul(T,re)|0,i=(i=i+Math.imul(T,ne)|0)+Math.imul(U,re)|0,o=o+Math.imul(U,ne)|0,n=n+Math.imul(S,oe)|0,i=(i=i+Math.imul(S,ae)|0)+Math.imul(M,oe)|0,o=o+Math.imul(M,ae)|0,n=n+Math.imul(E,ue)|0,i=(i=i+Math.imul(E,ce)|0)+Math.imul(x,ue)|0,o=o+Math.imul(x,ce)|0,n=n+Math.imul(w,he)|0,i=(i=i+Math.imul(w,le)|0)+Math.imul(_,he)|0,o=o+Math.imul(_,le)|0;var Me=(c+(n=n+Math.imul(m,pe)|0)|0)+((8191&(i=(i=i+Math.imul(m,be)|0)+Math.imul(v,pe)|0))<<13)|0;c=((o=o+Math.imul(v,be)|0)+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863,n=Math.imul(O,Z),i=(i=Math.imul(O,J))+Math.imul(D,Z)|0,o=Math.imul(D,J),n=n+Math.imul(N,Q)|0,i=(i=i+Math.imul(N,ee)|0)+Math.imul(R,Q)|0,o=o+Math.imul(R,ee)|0,n=n+Math.imul(B,re)|0,i=(i=i+Math.imul(B,ne)|0)+Math.imul(P,re)|0,o=o+Math.imul(P,ne)|0,n=n+Math.imul(T,oe)|0,i=(i=i+Math.imul(T,ae)|0)+Math.imul(U,oe)|0,o=o+Math.imul(U,ae)|0,n=n+Math.imul(S,ue)|0,i=(i=i+Math.imul(S,ce)|0)+Math.imul(M,ue)|0,o=o+Math.imul(M,ce)|0,n=n+Math.imul(E,he)|0,i=(i=i+Math.imul(E,le)|0)+Math.imul(x,he)|0,o=o+Math.imul(x,le)|0;var Ie=(c+(n=n+Math.imul(w,pe)|0)|0)+((8191&(i=(i=i+Math.imul(w,be)|0)+Math.imul(_,pe)|0))<<13)|0;c=((o=o+Math.imul(_,be)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,n=Math.imul(O,Q),i=(i=Math.imul(O,ee))+Math.imul(D,Q)|0,o=Math.imul(D,ee),n=n+Math.imul(N,re)|0,i=(i=i+Math.imul(N,ne)|0)+Math.imul(R,re)|0,o=o+Math.imul(R,ne)|0,n=n+Math.imul(B,oe)|0,i=(i=i+Math.imul(B,ae)|0)+Math.imul(P,oe)|0,o=o+Math.imul(P,ae)|0,n=n+Math.imul(T,ue)|0,i=(i=i+Math.imul(T,ce)|0)+Math.imul(U,ue)|0,o=o+Math.imul(U,ce)|0,n=n+Math.imul(S,he)|0,i=(i=i+Math.imul(S,le)|0)+Math.imul(M,he)|0,o=o+Math.imul(M,le)|0;var Te=(c+(n=n+Math.imul(E,pe)|0)|0)+((8191&(i=(i=i+Math.imul(E,be)|0)+Math.imul(x,pe)|0))<<13)|0;c=((o=o+Math.imul(x,be)|0)+(i>>>13)|0)+(Te>>>26)|0,Te&=67108863,n=Math.imul(O,re),i=(i=Math.imul(O,ne))+Math.imul(D,re)|0,o=Math.imul(D,ne),n=n+Math.imul(N,oe)|0,i=(i=i+Math.imul(N,ae)|0)+Math.imul(R,oe)|0,o=o+Math.imul(R,ae)|0,n=n+Math.imul(B,ue)|0,i=(i=i+Math.imul(B,ce)|0)+Math.imul(P,ue)|0,o=o+Math.imul(P,ce)|0,n=n+Math.imul(T,he)|0,i=(i=i+Math.imul(T,le)|0)+Math.imul(U,he)|0,o=o+Math.imul(U,le)|0;var Ue=(c+(n=n+Math.imul(S,pe)|0)|0)+((8191&(i=(i=i+Math.imul(S,be)|0)+Math.imul(M,pe)|0))<<13)|0;c=((o=o+Math.imul(M,be)|0)+(i>>>13)|0)+(Ue>>>26)|0,Ue&=67108863,n=Math.imul(O,oe),i=(i=Math.imul(O,ae))+Math.imul(D,oe)|0,o=Math.imul(D,ae),n=n+Math.imul(N,ue)|0,i=(i=i+Math.imul(N,ce)|0)+Math.imul(R,ue)|0,o=o+Math.imul(R,ce)|0,n=n+Math.imul(B,he)|0,i=(i=i+Math.imul(B,le)|0)+Math.imul(P,he)|0,o=o+Math.imul(P,le)|0;var je=(c+(n=n+Math.imul(T,pe)|0)|0)+((8191&(i=(i=i+Math.imul(T,be)|0)+Math.imul(U,pe)|0))<<13)|0;c=((o=o+Math.imul(U,be)|0)+(i>>>13)|0)+(je>>>26)|0,je&=67108863,n=Math.imul(O,ue),i=(i=Math.imul(O,ce))+Math.imul(D,ue)|0,o=Math.imul(D,ce),n=n+Math.imul(N,he)|0,i=(i=i+Math.imul(N,le)|0)+Math.imul(R,he)|0,o=o+Math.imul(R,le)|0;var Be=(c+(n=n+Math.imul(B,pe)|0)|0)+((8191&(i=(i=i+Math.imul(B,be)|0)+Math.imul(P,pe)|0))<<13)|0;c=((o=o+Math.imul(P,be)|0)+(i>>>13)|0)+(Be>>>26)|0,Be&=67108863,n=Math.imul(O,he),i=(i=Math.imul(O,le))+Math.imul(D,he)|0,o=Math.imul(D,le);var Pe=(c+(n=n+Math.imul(N,pe)|0)|0)+((8191&(i=(i=i+Math.imul(N,be)|0)+Math.imul(R,pe)|0))<<13)|0;c=((o=o+Math.imul(R,be)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863;var Ce=(c+(n=Math.imul(O,pe))|0)+((8191&(i=(i=Math.imul(O,be))+Math.imul(D,pe)|0))<<13)|0;return c=((o=Math.imul(D,be))+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,u[0]=ye,u[1]=me,u[2]=ve,u[3]=ge,u[4]=we,u[5]=_e,u[6]=Ae,u[7]=Ee,u[8]=xe,u[9]=ke,u[10]=Se,u[11]=Me,u[12]=Ie,u[13]=Te,u[14]=Ue,u[15]=je,u[16]=Be,u[17]=Pe,u[18]=Ce,0!==c&&(u[19]=c,r.length++),r};function p(e,t,r){return(new b).mulp(e,t,r)}function b(e,t){this.x=e,this.y=t}Math.imul||(d=l),o.prototype.mulTo=function(e,t){var r=this.length+e.length;return 10===this.length&&10===e.length?d(this,e,t):r<63?l(this,e,t):r<1024?function(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,a&=67108863}r.words[o]=s,n=a,a=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,e,t):p(this,e,t)},b.prototype.makeRBT=function(e){for(var t=new Array(e),r=o.prototype._countBits(e)-1,n=0;n>=1;return n},b.prototype.permute=function(e,t,r,n,i,o){for(var a=0;a>>=1)i++;return 1<>>=13,r[2*a+1]=8191&o,o>>>=13;for(a=2*t;a>=26,t+=i/67108864|0,t+=o>>>26,this.words[r]=67108863&o}return 0!==t&&(this.words[r]=t,this.length++),this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),r=0;r>>i}return t}(e);if(0===t.length)return new o(1);for(var r=this,n=0;n=0);var t,r=e%26,i=(e-r)/26,o=67108863>>>26-r<<26-r;if(0!==r){var a=0;for(t=0;t>>26-r}a&&(this.words[t]=a,this.length++)}if(0!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t=0),i=t?(t-t%26)/26:0;var o=e%26,a=Math.min((e-o)/26,this.length),s=67108863^67108863>>>o<a)for(this.length-=a,c=0;c=0&&(0!==f||c>=i);c--){var h=0|this.words[c];this.words[c]=f<<26-o|h>>>o,f=h&s}return u&&0!==f&&(u.words[u.length++]=f),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},o.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,i=1<=0);var t=e%26,r=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var i=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(u/67108864|0),this.words[i+r]=67108863&o}for(;i>26,this.words[i+r]=67108863&o;if(0===s)return this.strip();for(n(-1===s),s=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},o.prototype._wordDiv=function(e,t){var r=(this.length,e.length),n=this.clone(),i=e,a=0|i.words[i.length-1];0!==(r=26-this._countBits(a))&&(i=i.ushln(r),n.iushln(r),a=0|i.words[i.length-1]);var s,u=n.length-i.length;if("mod"!==t){(s=new o(null)).length=u+1,s.words=new Array(s.length);for(var c=0;c=0;h--){var l=67108864*(0|n.words[i.length+h])+(0|n.words[i.length+h-1]);for(l=Math.min(l/a|0,67108863),n._ishlnsubmul(i,l,h);0!==n.negative;)l--,n.negative=0,n._ishlnsubmul(i,1,h),n.isZero()||(n.negative^=1);s&&(s.words[h]=l)}return s&&s.strip(),n.strip(),"div"!==t&&0!==r&&n.iushrn(r),{div:s||null,mod:n}},o.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(s=this.neg().divmod(e,t),"mod"!==t&&(i=s.div.neg()),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.iadd(e)),{div:i,mod:a}):0===this.negative&&0!==e.negative?(s=this.divmod(e.neg(),t),"mod"!==t&&(i=s.div.neg()),{div:i,mod:s.mod}):0!=(this.negative&e.negative)?(s=this.neg().divmod(e.neg(),t),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.isub(e)),{div:s.div,mod:a}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modn(e.words[0]))}:this._wordDiv(e,t);var i,a,s},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=0!==t.div.negative?t.mod.isub(e):t.mod,n=e.ushrn(1),i=e.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modn=function(e){n(e<=67108863);for(var t=(1<<26)%e,r=0,i=this.length-1;i>=0;i--)r=(t*r+(0|this.words[i]))%e;return r},o.prototype.idivn=function(e){n(e<=67108863);for(var t=0,r=this.length-1;r>=0;r--){var i=(0|this.words[r])+67108864*t;this.words[r]=i/e|0,t=i%e}return this.strip()},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new o(1),a=new o(0),s=new o(0),u=new o(1),c=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++c;for(var f=r.clone(),h=t.clone();!t.isZero();){for(var l=0,d=1;0==(t.words[0]&d)&&l<26;++l,d<<=1);if(l>0)for(t.iushrn(l);l-- >0;)(i.isOdd()||a.isOdd())&&(i.iadd(f),a.isub(h)),i.iushrn(1),a.iushrn(1);for(var p=0,b=1;0==(r.words[0]&b)&&p<26;++p,b<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(s.isOdd()||u.isOdd())&&(s.iadd(f),u.isub(h)),s.iushrn(1),u.iushrn(1);t.cmp(r)>=0?(t.isub(r),i.isub(s),a.isub(u)):(r.isub(t),s.isub(i),u.isub(a))}return{a:s,b:u,gcd:r.iushln(c)}},o.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,a=new o(1),s=new o(0),u=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var c=0,f=1;0==(t.words[0]&f)&&c<26;++c,f<<=1);if(c>0)for(t.iushrn(c);c-- >0;)a.isOdd()&&a.iadd(u),a.iushrn(1);for(var h=0,l=1;0==(r.words[0]&l)&&h<26;++h,l<<=1);if(h>0)for(r.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(u),s.iushrn(1);t.cmp(r)>=0?(t.isub(r),a.isub(s)):(r.isub(t),s.isub(a))}return(i=0===t.cmpn(1)?a:s).cmpn(0)<0&&i.iadd(e),i},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var n=0;t.isEven()&&r.isEven();n++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=t.cmp(r);if(i<0){var o=t;t=r,r=o}else if(0===i||0===r.cmpn(1))break;t.isub(r)}return r.iushln(n)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return 0==(1&this.words[0])},o.prototype.isOdd=function(){return 1==(1&this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,i=1<>>26,s&=67108863,this.words[a]=s}return 0!==o&&(this.words[a]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this.strip(),this.length>1)t=1;else{r&&(e=-e),n(e<=67108863,"Number is too big");var i=0|this.words[0];t=i===e?0:ie.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|e.words[r];if(n!==i){ni&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new A(e)},o.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var y={k256:null,p224:null,p192:null,p25519:null};function m(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function v(){m.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function g(){m.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function w(){m.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function _(){m.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function A(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function E(e){A.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(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)}m.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},m.prototype.ireduce=function(e){var t,r=e;do{this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(t>this.n);var n=t0?r.isub(this.p):r.strip(),r},m.prototype.split=function(e,t){e.iushrn(this.n,0,t)},m.prototype.imulK=function(e){return e.imul(this.k)},i(v,m),v.prototype.split=function(e,t){for(var r=Math.min(e.length,9),n=0;n>>22,i=o}i>>>=22,e.words[n-10]=i,0===i&&e.length>10?e.length-=10:e.length-=9},v.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r>>=26,e.words[r]=i,t=n}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(y[e])return y[e];var t;if("k256"===e)t=new v;else if("p224"===e)t=new g;else if("p192"===e)t=new w;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new _}return y[e]=t,t},A.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},A.prototype._verify2=function(e,t){n(0==(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},A.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},A.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},A.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},A.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},A.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},A.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},A.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},A.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},A.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},A.prototype.isqr=function(e){return this.imul(e,e.clone())},A.prototype.sqr=function(e){return this.mul(e,e)},A.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var r=this.m.add(new o(1)).iushrn(2);return this.pow(e,r)}for(var i=this.m.subn(1),a=0;!i.isZero()&&0===i.andln(1);)a++,i.iushrn(1);n(!i.isZero());var s=new o(1).toRed(this),u=s.redNeg(),c=this.m.subn(1).iushrn(1),f=this.m.bitLength();for(f=new o(2*f*f).toRed(this);0!==this.pow(f,c).cmp(u);)f.redIAdd(u);for(var h=this.pow(f,i),l=this.pow(e,i.addn(1).iushrn(1)),d=this.pow(e,i),p=a;0!==d.cmp(s);){for(var b=d,y=0;0!==b.cmp(s);y++)b=b.redSqr();n(y=0;n--){for(var c=t.words[n],f=u-1;f>=0;f--){var h=c>>f&1;i!==r[0]&&(i=this.sqr(i)),0!==h||0!==a?(a<<=1,a|=h,(4===++s||0===n&&0===f)&&(i=this.mul(i,r[a]),s=0,a=0)):s=0}u=26}return i},A.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},A.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new E(e)},i(E,A),E.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},E.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},E.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},E.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var r=e.mul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},E.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===t||t,this)},{}],155:[function(e,t,r){(function(r){"use strict";var n=e("is-hex-prefixed"),i=e("strip-hex-prefix");function o(e){var t=e;if("string"!=typeof t)throw new Error("[ethjs-util] while padding to even, value must be string, is currently "+typeof t+", while padToEven.");return t.length%2&&(t="0"+t),t}function a(e){return"0x"+e.toString(16)}t.exports={arrayContainsArray:function(e,t,r){if(!0!==Array.isArray(e))throw new Error("[ethjs-util] method arrayContainsArray requires input 'superset' to be an array got type '"+typeof e+"'");if(!0!==Array.isArray(t))throw new Error("[ethjs-util] method arrayContainsArray requires input 'subset' to be an array got type '"+typeof t+"'");return t[Boolean(r)?"some":"every"](function(t){return e.indexOf(t)>=0})},intToBuffer:function(e){var t=a(e);return new r(o(t.slice(2)),"hex")},getBinarySize:function(e){if("string"!=typeof e)throw new Error("[ethjs-util] while getting binary size, method getBinarySize requires input 'str' to be type String, got '"+typeof e+"'.");return r.byteLength(e,"utf8")},isHexPrefixed:n,stripHexPrefix:i,padToEven:o,intToHex:a,fromAscii:function(e){for(var t="",r=0;r0&&this._events[e].length>r&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(e,t){if(!i(t))throw TypeError("listener must be a function");var r=!1;function n(){this.removeListener(e,n),r||(r=!0,t.apply(this,arguments))}return n.listener=t,this.on(e,n),this},n.prototype.removeListener=function(e,t){var r,n,a,s;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(a=(r=this._events[e]).length,n=-1,r===t||i(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(o(r)){for(s=a;s-- >0;)if(r[s]===t||r[s].listener&&r[s].listener===t){n=s;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},n.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(i(r=this._events[e]))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},n.prototype.listeners=function(e){return this._events&&this._events[e]?i(this._events[e])?[this._events[e]]:this._events[e].slice():[]},n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;if(t)return t.length}return 0},n.listenerCount=function(e,t){return e.listenerCount(t)}},{}],158:[function(e,t,r){var n=e("safe-buffer").Buffer,i=e("md5.js");t.exports=function(e,t,r,o){if(n.isBuffer(e)||(e=n.from(e,"binary")),t&&(n.isBuffer(t)||(t=n.from(t,"binary")),8!==t.length))throw new RangeError("salt should be Buffer with 8 byte length");for(var a=r/8,s=n.alloc(a),u=n.alloc(o||0),c=n.alloc(0);a>0||o>0;){var f=new i;f.update(c),f.update(e),t&&f.update(t),c=f.digest();var h=0;if(a>0){var l=s.length-a;h=Math.min(a,c.length),c.copy(s,l,0,h),a-=h}if(h0){var d=u.length-o,p=Math.min(o,c.length-h);c.copy(u,d,h,h+p),o-=p}}return c.fill(0),{key:s,iv:u}}},{"md5.js":231,"safe-buffer":290}],159:[function(e,t,r){"use strict";var n=e("is-callable"),i=Object.prototype.toString,o=Object.prototype.hasOwnProperty;t.exports=function(e,t,r){if(!n(t))throw new TypeError("iterator must be a function");var a;arguments.length>=3&&(a=r),"[object Array]"===i.call(e)?function(e,t,r){for(var n=0,i=e.length;n=this._blockSize;){for(var o=this._blockOffset;o0;++a)this._length[a]+=s,(s=this._length[a]/4294967296|0)>0&&(this._length[a]-=4294967296*s);return this},i.prototype._update=function(e){throw new Error("_update is not implemented")},i.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();return void 0!==e&&(t=t.toString(e)),t},i.prototype._digest=function(){throw new Error("_digest is not implemented")},t.exports=i}).call(this,e("buffer").Buffer)},{buffer:84,inherits:180,stream:311}],162:[function(e,t,r){var n=r;n.utils=e("./hash/utils"),n.common=e("./hash/common"),n.sha=e("./hash/sha"),n.ripemd=e("./hash/ripemd"),n.hmac=e("./hash/hmac"),n.sha1=n.sha.sha1,n.sha256=n.sha.sha256,n.sha224=n.sha.sha224,n.sha384=n.sha.sha384,n.sha512=n.sha.sha512,n.ripemd160=n.ripemd.ripemd160},{"./hash/common":163,"./hash/hmac":164,"./hash/ripemd":165,"./hash/sha":166,"./hash/utils":173}],163:[function(e,t,r){"use strict";var n=e("./utils"),i=e("minimalistic-assert");function o(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}r.BlockHash=o,o.prototype.update=function(e,t){if(e=n.toArray(e,t),this.pending?this.pending=this.pending.concat(e):this.pending=e,this.pendingTotal+=e.length,this.pending.length>=this._delta8){var r=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-r,e.length),0===this.pending.length&&(this.pending=null),e=n.join32(e,0,e.length-r,this.endian);for(var i=0;i>>24&255,n[i++]=e>>>16&255,n[i++]=e>>>8&255,n[i++]=255&e}else for(n[i++]=255&e,n[i++]=e>>>8&255,n[i++]=e>>>16&255,n[i++]=e>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,o=8;othis.blockSize&&(e=(new this.Hash).update(e).digest()),i(e.length<=this.blockSize);for(var t=e.length;t>>3},r.g1_256=function(e){return n(e,17)^n(e,19)^e>>>10}},{"../utils":173}],173:[function(e,t,r){"use strict";var n=e("minimalistic-assert"),i=e("inherits");function o(e){return(e>>>24|e>>>8&65280|e<<8&16711680|(255&e)<<24)>>>0}function a(e){return 1===e.length?"0"+e:e}function s(e){return 7===e.length?"0"+e:6===e.length?"00"+e:5===e.length?"000"+e:4===e.length?"0000"+e:3===e.length?"00000"+e:2===e.length?"000000"+e:1===e.length?"0000000"+e:e}r.inherits=i,r.toArray=function(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var r=[];if("string"==typeof e)if(t){if("hex"===t)for((e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e),n=0;n>8,a=255&i;o?r.push(o,a):r.push(a)}else for(n=0;n>>0}return a},r.split32=function(e,t){for(var r=new Array(4*e.length),n=0,i=0;n>>24,r[i+1]=o>>>16&255,r[i+2]=o>>>8&255,r[i+3]=255&o):(r[i+3]=o>>>24,r[i+2]=o>>>16&255,r[i+1]=o>>>8&255,r[i]=255&o)}return r},r.rotr32=function(e,t){return e>>>t|e<<32-t},r.rotl32=function(e,t){return e<>>32-t},r.sum32=function(e,t){return e+t>>>0},r.sum32_3=function(e,t,r){return e+t+r>>>0},r.sum32_4=function(e,t,r,n){return e+t+r+n>>>0},r.sum32_5=function(e,t,r,n,i){return e+t+r+n+i>>>0},r.sum64=function(e,t,r,n){var i=e[t],o=n+e[t+1]>>>0,a=(o>>0,e[t+1]=o},r.sum64_hi=function(e,t,r,n){return(t+n>>>0>>0},r.sum64_lo=function(e,t,r,n){return t+n>>>0},r.sum64_4_hi=function(e,t,r,n,i,o,a,s){var u=0,c=t;return u+=(c=c+n>>>0)>>0)>>0)>>0},r.sum64_4_lo=function(e,t,r,n,i,o,a,s){return t+n+o+s>>>0},r.sum64_5_hi=function(e,t,r,n,i,o,a,s,u,c){var f=0,h=t;return f+=(h=h+n>>>0)>>0)>>0)>>0)>>0},r.sum64_5_lo=function(e,t,r,n,i,o,a,s,u,c){return t+n+o+s+c>>>0},r.rotr64_hi=function(e,t,r){return(t<<32-r|e>>>r)>>>0},r.rotr64_lo=function(e,t,r){return(e<<32-r|t>>>r)>>>0},r.shr64_hi=function(e,t,r){return e>>>r},r.shr64_lo=function(e,t,r){return(e<<32-r|t>>>r)>>>0}},{inherits:180,"minimalistic-assert":234}],174:[function(e,t,r){"use strict";var n=e("hash.js"),i=e("minimalistic-crypto-utils"),o=e("minimalistic-assert");function a(e){if(!(this instanceof a))return new a(e);this.hash=e.hash,this.predResist=!!e.predResist,this.outLen=this.hash.outSize,this.minEntropy=e.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var t=i.toArray(e.entropy,e.entropyEnc||"hex"),r=i.toArray(e.nonce,e.nonceEnc||"hex"),n=i.toArray(e.pers,e.persEnc||"hex");o(t.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(t,r,n)}t.exports=a,a.prototype._init=function(e,t,r){var n=e.concat(t).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(e.concat(r||[])),this._reseed=1},a.prototype.generate=function(e,t,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof t&&(n=r,r=t,t=null),r&&(r=i.toArray(r,n||"hex"),this._update(r));for(var o=[];o.length\\$%@ءؤة\"'^|~⦅⦆・ゥャ¢£¬¦¥₩│←↑→↓■○𐐨𐐩𐐪𐐫𐐬𐐭𐐮𐐯𐐰𐐱𐐲𐐳𐐴𐐵𐐶𐐷𐐸𐐹𐐺𐐻𐐼𐐽𐐾𐐿𐑀𐑁𐑂𐑃𐑄𐑅𐑆𐑇𐑈𐑉𐑊𐑋𐑌𐑍𐑎𐑏𐓘𐓙𐓚𐓛𐓜𐓝𐓞𐓟𐓠𐓡𐓢𐓣𐓤𐓥𐓦𐓧𐓨𐓩𐓪𐓫𐓬𐓭𐓮𐓯𐓰𐓱𐓲𐓳𐓴𐓵𐓶𐓷𐓸𐓹𐓺𐓻𐳀𐳁𐳂𐳃𐳄𐳅𐳆𐳇𐳈𐳉𐳊𐳋𐳌𐳍𐳎𐳏𐳐𐳑𐳒𐳓𐳔𐳕𐳖𐳗𐳘𐳙𐳚𐳛𐳜𐳝𐳞𐳟𐳠𐳡𐳢𐳣𐳤𐳥𐳦𐳧𐳨𐳩𐳪𐳫𐳬𐳭𐳮𐳯𐳰𐳱𐳲𑣀𑣁𑣂𑣃𑣄𑣅𑣆𑣇𑣈𑣉𑣊𑣋𑣌𑣍𑣎𑣏𑣐𑣑𑣒𑣓𑣔𑣕𑣖𑣗𑣘𑣙𑣚𑣛𑣜𑣝𑣞𑣟ıȷ∇∂𞤢𞤣𞤤𞤥𞤦𞤧𞤨𞤩𞤪𞤫𞤬𞤭𞤮𞤯𞤰𞤱𞤲𞤳𞤴𞤵𞤶𞤷𞤸𞤹𞤺𞤻𞤼𞤽𞤾𞤿𞥀𞥁𞥂𞥃ٮڡٯ字双多解交映無前後再新初終販声吹演投捕遊指禁空合満申割営配得可丽丸乁𠄢你侻倂偺備像㒞𠘺兔兤具𠔜㒹內𠕋冗冤仌冬𩇟刃㓟刻剆剷㔕包匆卉博即卽卿𠨬灰及叟𠭣叫叱吆咞吸呈周咢哶唐啓啣善喫喳嗂圖圗噑噴壮城埴堍型堲報墬𡓤売壷夆夢奢𡚨𡛪姬娛娧姘婦㛮嬈嬾𡧈寃寘寳𡬘寿将㞁屠峀岍𡷤嵃𡷦嵮嵫嵼巡巢㠯巽帨帽幩㡢𢆃㡼庰庳庶𪎒𢌱舁弢㣇𣊸𦇚形彫㣣徚忍志忹悁㤺㤜𢛔惇慈慌慺憲憤憯懞戛扝抱拔捐𢬌挽拼捨掃揤𢯱搢揅掩㨮摩摾撝摷㩬敬𣀊旣書晉㬙㬈㫤冒冕最暜肭䏙朡杞杓𣏃㭉柺枅桒𣑭梎栟椔楂榣槪檨𣚣櫛㰘次𣢧歔㱎歲殟殻𣪍𡴋𣫺汎𣲼沿泍汧洖派浩浸涅𣴞洴港湮㴳滇𣻑淹潮𣽞𣾎濆瀹瀛㶖灊災灷炭𠔥煅𤉣熜爨牐𤘈犀犕𤜵𤠔獺王㺬玥㺸瑇瑜璅瓊㼛甤𤰶甾𤲒𢆟瘐𤾡𤾸𥁄㿼䀈𥃳𥃲𥄙𥄳眞真瞋䁆䂖𥐝硎䃣𥘦𥚚𥛅秫䄯穊穏𥥼𥪧䈂𥮫篆築䈧𥲀糒䊠糨糣紀𥾆絣䌁緇縂繅䌴𦈨𦉇䍙𦋙罺𦌾羕翺𦓚𦔣聠𦖨聰𣍟䏕育脃䐋脾媵𦞧𦞵𣎓𣎜舄辞䑫芑芋芝劳花芳芽苦𦬼茝荣莭茣莽菧荓菊菌菜𦰶𦵫𦳕䔫蓱蓳蔖𧏊蕤𦼬䕝䕡𦾱𧃒䕫虐虧虩蚩蚈蜎蛢蜨蝫螆蟡蠁䗹衠𧙧裗裞䘵裺㒻𧢮𧥦䚾䛇誠𧲨貫賁贛起𧼯𠠄跋趼跰𠣞軔𨗒𨗭邔郱鄑𨜮鄛鈸鋗鋘鉼鏹鐕𨯺開䦕閷𨵷䧦雃嶲霣𩅅𩈚䩮䩶韠𩐊䪲𩒖頩𩖶飢䬳餩馧駂駾䯎𩬰鱀鳽䳎䳭鵧𪃎䳸𪄅𪈎𪊑䵖黾鼅鼏鼖𪘀",mapChar:function(r){return r>=196608?r>=917760&&r<=917999?18874368:0:e[t[r>>4]][15&r]}}},"function"==typeof define&&define.amd?define([],function(){return i()}):"object"==typeof r?t.exports=i():n.uts46_map=i()},{}],177:[function(e,t,r){var n,i;n=this,i=function(e,t){function r(r,n,i){for(var o=[],a=e.ucs2.decode(r),s=0;s>23,l=f>>21&3,d=f>>5&65535,p=31&f,b=t.mapStr.substr(d,p);if(0===l||n&&1&h)throw new Error("Illegal char "+c);1===l?o.push(b):2===l?o.push(i?b:c):3===l&&o.push(c)}return o.join("").normalize("NFC")}function n(t,n,o){void 0===o&&(o=!1);var a=r(t,o,n).split(".");return(a=a.map(function(t){return t.startsWith("xn--")?i(t=e.decode(t.substring(4)),o,!1):i(t,o,n),t})).join(".")}function i(e,n,i){if("-"===e[2]&&"-"===e[3])throw new Error("Failed to validate "+e);if(e.startsWith("-")||e.endsWith("-"))throw new Error("Failed to validate "+e);if(e.includes("."))throw new Error("Failed to validate "+e);if(r(e,n,i)!==e)throw new Error("Failed to validate "+e);var o=e.codePointAt(0);if(t.mapChar(o)&2<<23)throw new Error("Label contains illegal character: "+o)}return{toUnicode:function(e,t){return void 0===t&&(t={}),n(e,!1,"useStd3ASCII"in t&&t.useStd3ASCII)},toAscii:function(t,r){void 0===r&&(r={});var i,o=!("transitional"in r)||r.transitional,a="useStd3ASCII"in r&&r.useStd3ASCII,s="verifyDnsLength"in r&&r.verifyDnsLength,u=n(t,o,a).split(".").map(e.toASCII),c=u.join(".");if(s){if(c.length<1||c.length>253)throw new Error("DNS name has wrong length: "+c);for(i=0;i63)throw new Error("DNS label has wrong length: "+f)}}return c}}},"function"==typeof define&&define.amd?define(["punycode","./idna-map"],function(e,t){return i(e,t)}):"object"==typeof r?t.exports=i(e("punycode"),e("./idna-map")):n.uts46=i(n.punycode,n.idna_map)},{"./idna-map":176,punycode:265}],178:[function(e,t,r){r.read=function(e,t,r,n,i){var o,a,s=8*i-n-1,u=(1<>1,f=-7,h=r?i-1:0,l=r?-1:1,d=e[t+h];for(h+=l,o=d&(1<<-f)-1,d>>=-f,f+=s;f>0;o=256*o+e[t+h],h+=l,f-=8);for(a=o&(1<<-f)-1,o>>=-f,f+=n;f>0;a=256*a+e[t+h],h+=l,f-=8);if(0===o)o=1-c;else{if(o===u)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,n),o-=c}return(d?-1:1)*a*Math.pow(2,o-n)},r.write=function(e,t,r,n,i,o){var a,s,u,c=8*o-i-1,f=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:o-1,p=n?1:-1,b=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=f):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+h>=1?l/u:l*Math.pow(2,1-h))*u>=2&&(a++,u/=2),a+h>=f?(s=0,a=f):a+h>=1?(s=(t*u-1)*Math.pow(2,i),a+=h):(s=t*Math.pow(2,h-1)*Math.pow(2,i),a=0));i>=8;e[r+d]=255&s,d+=p,s/=256,i-=8);for(a=a<0;e[r+d]=255&a,d+=p,a/=256,c-=8);e[r+d-p]|=128*b}},{}],179:[function(e,t,r){var n=[].indexOf;t.exports=function(e,t){if(n)return e.indexOf(t);for(var r=0;r-32e3)throw new Error("Invalid error code");if(!(this instanceof f))return new f(e);i.call(this,"Server error",e)};n(f,i),i.ParseError=o,i.InvalidRequest=a,i.MethodNotFound=s,i.InvalidParams=u,i.InternalError=c,i.ServerError=f,t.exports=i},{inherits:180}],191:[function(e,t,r){t.exports=function(e){var t=(e=e||{}).max||Number.MAX_SAFE_INTEGER,r=void 0!==e.start?e.start:Math.floor(Math.random()*t);return function(){return r%=t,r++}}},{}],192:[function(e,t,r){r.parse=e("./lib/parse"),r.stringify=e("./lib/stringify")},{"./lib/parse":193,"./lib/stringify":194}],193:[function(e,t,r){var n,i,o,a,s={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"},u=function(e){throw{name:"SyntaxError",message:e,at:n,text:o}},c=function(e){return e&&e!==i&&u("Expected '"+e+"' instead of '"+i+"'"),i=o.charAt(n),n+=1,i},f=function(){var e,t="";for("-"===i&&(t="-",c("-"));i>="0"&&i<="9";)t+=i,c();if("."===i)for(t+=".";c()&&i>="0"&&i<="9";)t+=i;if("e"===i||"E"===i)for(t+=i,c(),"-"!==i&&"+"!==i||(t+=i,c());i>="0"&&i<="9";)t+=i,c();if(e=+t,isFinite(e))return e;u("Bad number")},h=function(){var e,t,r,n="";if('"'===i)for(;c();){if('"'===i)return c(),n;if("\\"===i)if(c(),"u"===i){for(r=0,t=0;t<4&&(e=parseInt(c(),16),isFinite(e));t+=1)r=16*r+e;n+=String.fromCharCode(r)}else{if("string"!=typeof s[i])break;n+=s[i]}else n+=i}u("Bad string")},l=function(){for(;i&&i<=" ";)c()};a=function(){switch(l(),i){case"{":return function(){var e,t={};if("{"===i){if(c("{"),l(),"}"===i)return c("}"),t;for(;i;){if(e=h(),l(),c(":"),Object.hasOwnProperty.call(t,e)&&u('Duplicate key "'+e+'"'),t[e]=a(),l(),"}"===i)return c("}"),t;c(","),l()}}u("Bad object")}();case"[":return function(){var e=[];if("["===i){if(c("["),l(),"]"===i)return c("]"),e;for(;i;){if(e.push(a()),l(),"]"===i)return c("]"),e;c(","),l()}}u("Bad array")}();case'"':return h();case"-":return f();default:return i>="0"&&i<="9"?f():function(){switch(i){case"t":return c("t"),c("r"),c("u"),c("e"),!0;case"f":return c("f"),c("a"),c("l"),c("s"),c("e"),!1;case"n":return c("n"),c("u"),c("l"),c("l"),null}u("Unexpected '"+i+"'")}()}},t.exports=function(e,t){var r;return o=e,n=0,i=" ",r=a(),l(),i&&u("Syntax error"),"function"==typeof t?function e(r,n){var i,o,a=r[n];if(a&&"object"==typeof a)for(i in a)Object.prototype.hasOwnProperty.call(a,i)&&(void 0!==(o=e(a,i))?a[i]=o:delete a[i]);return t.call(r,n,a)}({"":r},""):r}},{}],194:[function(e,t,r){var n,i,o,a=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,s={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};function u(e){return a.lastIndex=0,a.test(e)?'"'+e.replace(a,function(e){var t=s[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}t.exports=function(e,t,r){var a;if(n="",i="","number"==typeof r)for(a=0;a>>31),p=l^(a<<1|o>>>31),b=e[0]^d,y=e[1]^p,m=e[10]^d,v=e[11]^p,g=e[20]^d,w=e[21]^p,_=e[30]^d,A=e[31]^p,E=e[40]^d,x=e[41]^p;d=r^(s<<1|u>>>31),p=i^(u<<1|s>>>31);var k=e[2]^d,S=e[3]^p,M=e[12]^d,I=e[13]^p,T=e[22]^d,U=e[23]^p,j=e[32]^d,B=e[33]^p,P=e[42]^d,C=e[43]^p;d=o^(c<<1|f>>>31),p=a^(f<<1|c>>>31);var N=e[4]^d,R=e[5]^p,L=e[14]^d,O=e[15]^p,D=e[24]^d,F=e[25]^p,q=e[34]^d,H=e[35]^p,z=e[44]^d,K=e[45]^p;d=s^(h<<1|l>>>31),p=u^(l<<1|h>>>31);var V=e[6]^d,G=e[7]^p,W=e[16]^d,Y=e[17]^p,X=e[26]^d,Z=e[27]^p,J=e[36]^d,$=e[37]^p,Q=e[46]^d,ee=e[47]^p;d=c^(r<<1|i>>>31),p=f^(i<<1|r>>>31);var te=e[8]^d,re=e[9]^p,ne=e[18]^d,ie=e[19]^p,oe=e[28]^d,ae=e[29]^p,se=e[38]^d,ue=e[39]^p,ce=e[48]^d,fe=e[49]^p,he=b,le=y,de=v<<4|m>>>28,pe=m<<4|v>>>28,be=g<<3|w>>>29,ye=w<<3|g>>>29,me=A<<9|_>>>23,ve=_<<9|A>>>23,ge=E<<18|x>>>14,we=x<<18|E>>>14,_e=k<<1|S>>>31,Ae=S<<1|k>>>31,Ee=I<<12|M>>>20,xe=M<<12|I>>>20,ke=T<<10|U>>>22,Se=U<<10|T>>>22,Me=B<<13|j>>>19,Ie=j<<13|B>>>19,Te=P<<2|C>>>30,Ue=C<<2|P>>>30,je=R<<30|N>>>2,Be=N<<30|R>>>2,Pe=L<<6|O>>>26,Ce=O<<6|L>>>26,Ne=F<<11|D>>>21,Re=D<<11|F>>>21,Le=q<<15|H>>>17,Oe=H<<15|q>>>17,De=K<<29|z>>>3,Fe=z<<29|K>>>3,qe=V<<28|G>>>4,He=G<<28|V>>>4,ze=Y<<23|W>>>9,Ke=W<<23|Y>>>9,Ve=X<<25|Z>>>7,Ge=Z<<25|X>>>7,We=J<<21|$>>>11,Ye=$<<21|J>>>11,Xe=ee<<24|Q>>>8,Ze=Q<<24|ee>>>8,Je=te<<27|re>>>5,$e=re<<27|te>>>5,Qe=ne<<20|ie>>>12,et=ie<<20|ne>>>12,tt=ae<<7|oe>>>25,rt=oe<<7|ae>>>25,nt=se<<8|ue>>>24,it=ue<<8|se>>>24,ot=ce<<14|fe>>>18,at=fe<<14|ce>>>18;e[0]=he^~Ee&Ne,e[1]=le^~xe&Re,e[10]=qe^~Qe&be,e[11]=He^~et&ye,e[20]=_e^~Pe&Ve,e[21]=Ae^~Ce&Ge,e[30]=Je^~de&ke,e[31]=$e^~pe&Se,e[40]=je^~ze&tt,e[41]=Be^~Ke&rt,e[2]=Ee^~Ne&We,e[3]=xe^~Re&Ye,e[12]=Qe^~be&Me,e[13]=et^~ye&Ie,e[22]=Pe^~Ve&nt,e[23]=Ce^~Ge&it,e[32]=de^~ke&Le,e[33]=pe^~Se&Oe,e[42]=ze^~tt&me,e[43]=Ke^~rt&ve,e[4]=Ne^~We&ot,e[5]=Re^~Ye&at,e[14]=be^~Me&De,e[15]=ye^~Ie&Fe,e[24]=Ve^~nt&ge,e[25]=Ge^~it&we,e[34]=ke^~Le&Xe,e[35]=Se^~Oe&Ze,e[44]=tt^~me&Te,e[45]=rt^~ve&Ue,e[6]=We^~ot&he,e[7]=Ye^~at&le,e[16]=Me^~De&qe,e[17]=Ie^~Fe&He,e[26]=nt^~ge&_e,e[27]=it^~we&Ae,e[36]=Le^~Xe&Je,e[37]=Oe^~Ze&$e,e[46]=me^~Te&je,e[47]=ve^~Ue&Be,e[8]=ot^~he&Ee,e[9]=at^~le&xe,e[18]=De^~qe&Qe,e[19]=Fe^~He&et,e[28]=ge^~_e&Pe,e[29]=we^~Ae&Ce,e[38]=Xe^~Je&de,e[39]=Ze^~$e&pe,e[48]=Te^~je&ze,e[49]=Ue^~Be&Ke,e[0]^=n[2*t],e[1]^=n[2*t+1]}}},{}],200:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("./keccak-state-unroll");function o(){this.state=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.blockSize=null,this.count=0,this.squeezing=!1}o.prototype.initialize=function(e,t){for(var r=0;r<50;++r)this.state[r]=0;this.blockSize=e/8,this.count=0,this.squeezing=!1},o.prototype.absorb=function(e){for(var t=0;t>>this.count%4*8&255,this.count+=1,this.count===this.blockSize&&(i.p1600(this.state),this.count=0);return t},o.prototype.copy=function(e){for(var t=0;t<50;++t)e.state[t]=this.state[t];e.blockSize=this.blockSize,e.count=this.count,e.squeezing=this.squeezing},t.exports=o},{"./keccak-state-unroll":199,"safe-buffer":290}],201:[function(e,t,r){var n=e("./_root").Symbol;t.exports=n},{"./_root":217}],202:[function(e,t,r){var n=e("./_baseTimes"),i=e("./isArguments"),o=e("./isArray"),a=e("./isBuffer"),s=e("./_isIndex"),u=e("./isTypedArray"),c=Object.prototype.hasOwnProperty;t.exports=function(e,t){var r=o(e),f=!r&&i(e),h=!r&&!f&&a(e),l=!r&&!f&&!h&&u(e),d=r||f||h||l,p=d?n(e.length,String):[],b=p.length;for(var y in e)!t&&!c.call(e,y)||d&&("length"==y||h&&("offset"==y||"parent"==y)||l&&("buffer"==y||"byteLength"==y||"byteOffset"==y)||s(y,b))||p.push(y);return p}},{"./_baseTimes":207,"./_isIndex":211,"./isArguments":219,"./isArray":220,"./isBuffer":222,"./isTypedArray":227}],203:[function(e,t,r){var n=e("./_Symbol"),i=e("./_getRawTag"),o=e("./_objectToString"),a="[object Null]",s="[object Undefined]",u=n?n.toStringTag:void 0;t.exports=function(e){return null==e?void 0===e?s:a:u&&u in Object(e)?i(e):o(e)}},{"./_Symbol":201,"./_getRawTag":210,"./_objectToString":215}],204:[function(e,t,r){var n=e("./_baseGetTag"),i=e("./isObjectLike"),o="[object Arguments]";t.exports=function(e){return i(e)&&n(e)==o}},{"./_baseGetTag":203,"./isObjectLike":226}],205:[function(e,t,r){var n=e("./_baseGetTag"),i=e("./isLength"),o=e("./isObjectLike"),a={};a["[object Float32Array]"]=a["[object Float64Array]"]=a["[object Int8Array]"]=a["[object Int16Array]"]=a["[object Int32Array]"]=a["[object Uint8Array]"]=a["[object Uint8ClampedArray]"]=a["[object Uint16Array]"]=a["[object Uint32Array]"]=!0,a["[object Arguments]"]=a["[object Array]"]=a["[object ArrayBuffer]"]=a["[object Boolean]"]=a["[object DataView]"]=a["[object Date]"]=a["[object Error]"]=a["[object Function]"]=a["[object Map]"]=a["[object Number]"]=a["[object Object]"]=a["[object RegExp]"]=a["[object Set]"]=a["[object String]"]=a["[object WeakMap]"]=!1,t.exports=function(e){return o(e)&&i(e.length)&&!!a[n(e)]}},{"./_baseGetTag":203,"./isLength":224,"./isObjectLike":226}],206:[function(e,t,r){var n=e("./_isPrototype"),i=e("./_nativeKeys"),o=Object.prototype.hasOwnProperty;t.exports=function(e){if(!n(e))return i(e);var t=[];for(var r in Object(e))o.call(e,r)&&"constructor"!=r&&t.push(r);return t}},{"./_isPrototype":212,"./_nativeKeys":213}],207:[function(e,t,r){t.exports=function(e,t){for(var r=-1,n=Array(e);++r-1&&e%1==0&&e-1&&e%1==0&&e<=n}},{}],225:[function(e,t,r){t.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}},{}],226:[function(e,t,r){t.exports=function(e){return null!=e&&"object"==typeof e}},{}],227:[function(e,t,r){var n=e("./_baseIsTypedArray"),i=e("./_baseUnary"),o=e("./_nodeUtil"),a=o&&o.isTypedArray,s=a?i(a):n;t.exports=s},{"./_baseIsTypedArray":205,"./_baseUnary":208,"./_nodeUtil":214}],228:[function(e,t,r){var n=e("./_arrayLikeKeys"),i=e("./_baseKeys"),o=e("./isArrayLike");t.exports=function(e){return o(e)?n(e):i(e)}},{"./_arrayLikeKeys":202,"./_baseKeys":206,"./isArrayLike":221}],229:[function(e,t,r){t.exports=function(){}},{}],230:[function(e,t,r){t.exports=function(){return!1}},{}],231:[function(e,t,r){(function(r){"use strict";var n=e("inherits"),i=e("hash-base"),o=new Array(16);function a(){i.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}function s(e,t){return e<>>32-t}function u(e,t,r,n,i,o,a){return s(e+(t&r|~t&n)+i+o|0,a)+t|0}function c(e,t,r,n,i,o,a){return s(e+(t&n|r&~n)+i+o|0,a)+t|0}function f(e,t,r,n,i,o,a){return s(e+(t^r^n)+i+o|0,a)+t|0}function h(e,t,r,n,i,o,a){return s(e+(r^(t|~n))+i+o|0,a)+t|0}n(a,i),a.prototype._update=function(){for(var e=o,t=0;t<16;++t)e[t]=this._block.readInt32LE(4*t);var r=this._a,n=this._b,i=this._c,a=this._d;n=h(n=h(n=h(n=h(n=f(n=f(n=f(n=f(n=c(n=c(n=c(n=c(n=u(n=u(n=u(n=u(n,i=u(i,a=u(a,r=u(r,n,i,a,e[0],3614090360,7),n,i,e[1],3905402710,12),r,n,e[2],606105819,17),a,r,e[3],3250441966,22),i=u(i,a=u(a,r=u(r,n,i,a,e[4],4118548399,7),n,i,e[5],1200080426,12),r,n,e[6],2821735955,17),a,r,e[7],4249261313,22),i=u(i,a=u(a,r=u(r,n,i,a,e[8],1770035416,7),n,i,e[9],2336552879,12),r,n,e[10],4294925233,17),a,r,e[11],2304563134,22),i=u(i,a=u(a,r=u(r,n,i,a,e[12],1804603682,7),n,i,e[13],4254626195,12),r,n,e[14],2792965006,17),a,r,e[15],1236535329,22),i=c(i,a=c(a,r=c(r,n,i,a,e[1],4129170786,5),n,i,e[6],3225465664,9),r,n,e[11],643717713,14),a,r,e[0],3921069994,20),i=c(i,a=c(a,r=c(r,n,i,a,e[5],3593408605,5),n,i,e[10],38016083,9),r,n,e[15],3634488961,14),a,r,e[4],3889429448,20),i=c(i,a=c(a,r=c(r,n,i,a,e[9],568446438,5),n,i,e[14],3275163606,9),r,n,e[3],4107603335,14),a,r,e[8],1163531501,20),i=c(i,a=c(a,r=c(r,n,i,a,e[13],2850285829,5),n,i,e[2],4243563512,9),r,n,e[7],1735328473,14),a,r,e[12],2368359562,20),i=f(i,a=f(a,r=f(r,n,i,a,e[5],4294588738,4),n,i,e[8],2272392833,11),r,n,e[11],1839030562,16),a,r,e[14],4259657740,23),i=f(i,a=f(a,r=f(r,n,i,a,e[1],2763975236,4),n,i,e[4],1272893353,11),r,n,e[7],4139469664,16),a,r,e[10],3200236656,23),i=f(i,a=f(a,r=f(r,n,i,a,e[13],681279174,4),n,i,e[0],3936430074,11),r,n,e[3],3572445317,16),a,r,e[6],76029189,23),i=f(i,a=f(a,r=f(r,n,i,a,e[9],3654602809,4),n,i,e[12],3873151461,11),r,n,e[15],530742520,16),a,r,e[2],3299628645,23),i=h(i,a=h(a,r=h(r,n,i,a,e[0],4096336452,6),n,i,e[7],1126891415,10),r,n,e[14],2878612391,15),a,r,e[5],4237533241,21),i=h(i,a=h(a,r=h(r,n,i,a,e[12],1700485571,6),n,i,e[3],2399980690,10),r,n,e[10],4293915773,15),a,r,e[1],2240044497,21),i=h(i,a=h(a,r=h(r,n,i,a,e[8],1873313359,6),n,i,e[15],4264355552,10),r,n,e[6],2734768916,15),a,r,e[13],1309151649,21),i=h(i,a=h(a,r=h(r,n,i,a,e[4],4149444226,6),n,i,e[11],3174756917,10),r,n,e[2],718787259,15),a,r,e[9],3951481745,21),this._a=this._a+r|0,this._b=this._b+n|0,this._c=this._c+i|0,this._d=this._d+a|0},a.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=new r(16);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e},t.exports=a}).call(this,e("buffer").Buffer)},{buffer:84,"hash-base":232,inherits:180}],232:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("stream").Transform;function o(e){i.call(this),this._block=n.allocUnsafe(e),this._blockSize=e,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}e("inherits")(o,i),o.prototype._transform=function(e,t,r){var n=null;try{this.update(e,t)}catch(e){n=e}r(n)},o.prototype._flush=function(e){var t=null;try{this.push(this.digest())}catch(e){t=e}e(t)},o.prototype.update=function(e,t){if(function(e,t){if(!n.isBuffer(e)&&"string"!=typeof e)throw new TypeError(t+" must be a string or a buffer")}(e,"Data"),this._finalized)throw new Error("Digest already called");n.isBuffer(e)||(e=n.from(e,t));for(var r=this._block,i=0;this._blockOffset+e.length-i>=this._blockSize;){for(var o=this._blockOffset;o0;++a)this._length[a]+=s,(s=this._length[a]/4294967296|0)>0&&(this._length[a]-=4294967296*s);return this},o.prototype._update=function(){throw new Error("_update is not implemented")},o.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();void 0!==e&&(t=t.toString(e)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return t},o.prototype._digest=function(){throw new Error("_digest is not implemented")},t.exports=o},{inherits:180,"safe-buffer":290,stream:311}],233:[function(e,t,r){var n=e("bn.js"),i=e("brorand");function o(e){this.rand=e||new i.Rand}t.exports=o,o.create=function(e){return new o(e)},o.prototype._randbelow=function(e){var t=e.bitLength(),r=Math.ceil(t/8);do{var i=new n(this.rand.generate(r))}while(i.cmp(e)>=0);return i},o.prototype._randrange=function(e,t){var r=t.sub(e);return e.add(this._randbelow(r))},o.prototype.test=function(e,t,r){var i=e.bitLength(),o=n.mont(e),a=new n(1).toRed(o);t||(t=Math.max(1,i/48|0));for(var s=e.subn(1),u=0;!s.testn(u);u++);for(var c=e.shrn(u),f=s.toRed(o);t>0;t--){var h=this._randrange(new n(2),s);r&&r(h);var l=h.toRed(o).redPow(c);if(0!==l.cmp(a)&&0!==l.cmp(f)){for(var d=1;d0;t--){var f=this._randrange(new n(2),a),h=e.gcd(f);if(0!==h.cmpn(1))return h;var l=f.toRed(i).redPow(u);if(0!==l.cmp(o)&&0!==l.cmp(c)){for(var d=1;d>8,a=255&i;o?r.push(o,a):r.push(a)}return r},n.zero2=i,n.toHex=o,n.encode=function(e,t){return"hex"===t?o(e):e}},{}],236:[function(e,t,r){arguments[4][154][0].apply(r,arguments)},{dup:154}],237:[function(e,t,r){var n=e("bn.js"),i=e("strip-hex-prefix");t.exports=function(e){if("string"==typeof e||"number"==typeof e){var t=new n(1),r=String(e).toLowerCase().trim(),o="0x"===r.substr(0,2)||"-0x"===r.substr(0,3),a=i(r);if("-"===a.substr(0,1)&&(a=i(a.slice(1)),t=new n(-1,10)),!(a=""===a?"0":a).match(/^-?[0-9]+$/)&&a.match(/^[0-9A-Fa-f]+$/)||a.match(/^[a-fA-F]+$/)||!0===o&&a.match(/^[0-9A-Fa-f]+$/))return new n(a,16).mul(t);if((a.match(/^-?[0-9]+$/)||""===a)&&!1===o)return new n(a,10).mul(t)}else if("object"==typeof e&&e.toString&&!e.pop&&!e.push&&e.toString(10).match(/^-?[0-9]+$/)&&(e.mul||e.dividedToIntegerBy))return new n(e.toString(10),10);throw new Error("[number-to-bn] while converting number "+JSON.stringify(e)+" 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(e,t,r){"use strict";var n=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable;t.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},r=0;r<10;r++)t["_"+String.fromCharCode(r)]=r;if("0123456789"!==Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(""))return!1;var n={};return"abcdefghijklmnopqrst".split("").forEach(function(e){n[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},n)).join("")}catch(e){return!1}}()?Object.assign:function(e,t){for(var r,a,s=function(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}(e),u=1;u0;)if(q+=r,r=e.charAt(o++),4===H?(N+=String.fromCharCode(parseInt(q,16)),H=0,c=o-1):H++,!r)break e;if('"'===r&&!L){D=F.pop()||p,N+=e.substring(c,o-1);break}if(!("\\"!==r||L||(L=!0,N+=e.substring(c,o-1),r=e.charAt(o++))))break;if(L){if(L=!1,"n"===r?N+="\n":"r"===r?N+="\r":"t"===r?N+="\t":"f"===r?N+="\f":"b"===r?N+="\b":"u"===r?(H=1,q=""):N+=r,r=e.charAt(o++),c=o-1,r)continue;break}h.lastIndex=o;var l=h.exec(e);if(!l){o=e.length+1,N+=e.substring(c,o-1);break}if(o=l.index+1,!(r=e.charAt(l.index))){N+=e.substring(c,o-1);break}}continue;case A:if(!r)continue;if("r"!==r)return W("Invalid true started with t"+r);D=E;continue;case E:if(!r)continue;if("u"!==r)return W("Invalid true started with tr"+r);D=x;continue;case x:if(!r)continue;if("e"!==r)return W("Invalid true started with tru"+r);a(!0),u(),D=F.pop()||p;continue;case k:if(!r)continue;if("a"!==r)return W("Invalid false started with f"+r);D=S;continue;case S:if(!r)continue;if("l"!==r)return W("Invalid false started with fa"+r);D=M;continue;case M:if(!r)continue;if("s"!==r)return W("Invalid false started with fal"+r);D=I;continue;case I:if(!r)continue;if("e"!==r)return W("Invalid false started with fals"+r);a(!1),u(),D=F.pop()||p;continue;case T:if(!r)continue;if("u"!==r)return W("Invalid null started with n"+r);D=U;continue;case U:if(!r)continue;if("l"!==r)return W("Invalid null started with nu"+r);D=j;continue;case j:if(!r)continue;if("l"!==r)return W("Invalid null started with nul"+r);a(null),u(),D=F.pop()||p;continue;case B:if("."!==r)return W("Leading zero not followed by .");R+=r,D=P;continue;case P:if(-1!=="0123456789".indexOf(r))R+=r;else if("."===r){if(-1!==R.indexOf("."))return W("Invalid number has two dots");R+=r}else if("e"===r||"E"===r){if(-1!==R.indexOf("e")||-1!==R.indexOf("E"))return W("Invalid number has two exponential");R+=r}else if("+"===r||"-"===r){if("e"!==n&&"E"!==n)return W("Invalid symbol in number");R+=r}else R&&(a(parseFloat(R)),u(),R=""),o--,D=F.pop()||p;continue;default:return W("Unknown state: "+D)}K>=C&&(X=0,N!==s&&N.length>f&&(W("Max buffer length exceeded: textNode"),X=Math.max(X,N.length)),R.length>f&&(W("Max buffer length exceeded: numberNode"),X=Math.max(X,R.length)),C=f-X+K);var X}),e(ce).on(function(){if(D==d)return a({}),u(),void(O=!0);D===p&&0===z||W("Unexpected end");N!==s&&(a(N),u(),N=s);O=!0})}var C,N,R,L,O,D,F,q,H,z,K,V=(C=d(function(e){return e.unshift(/^/),(t=RegExp(e.map(f("source")).join(""))).exec.bind(t);var t}),L=C(N=/(\$?)/,/([\w-_]+|\*)/,R=/(?:{([\w ]*?)})?/),O=C(N,/\["([^"]+)"\]/,R),D=C(N,/\[(\d+|\*)\]/,R),F=C(N,/()/,/{([\w ]*?)}/),q=C(/\.\./),H=C(/\./),z=C(N,/!/),K=C(/$/),function(e){return e(h(L,O,D,F),q,H,z,K)});function G(e,t){return{key:e,node:t}}var W=f("key"),Y=f("node"),X={};function Z(e){var t=e(ee).emit,r=e(te).emit,n=e(ae).emit,o=e(oe).emit;function a(e,t,r){Y(x(e))[t]=r}function s(e,r,n){e&&a(e,r,n);var i=A(G(r,n),e);return t(i),i}var u={};return u[le]=function(e,t){if(!e)return n(t),s(e,X,t);var r=function(e,t){var r=Y(x(e));return m(i,r)?s(e,v(r),t):e}(e,t),o=k(r),u=W(x(r));return a(o,u,t),A(G(u,t),o)},u[de]=function(e){return r(e),k(e)||o(Y(x(e)))},u[he]=s,u}var J=V(function(e,t,r,n,i){var a=1,s=2,f=3,l=c(W,x),d=c(Y,x);function b(e,t){return!!t[a]?p(e,x):e}function m(e){if(e==y)return y;return p(function(e){return l(e)!=X},c(e,k))}function g(){return function(e){return l(e)==X}}function w(e,t,r,n,i){var o=e(r);if(o){var a=function(e,t,r){return U(function(e,t){return t(e,r)},t,e)}(t,n,o);return i(r.substr(v(o[0])),a)}}function A(e,t){return u(w,e,t)}var E=h(A(e,M(b,function(e,t){var r=t[f];return r?p(c(u(_,S(r.split(/\W+/))),d),e):e},function(e,t){var r=t[s];return p(r&&"*"!=r?function(e){return l(e)==r}:y,e)},m)),A(t,M(function(e){if(e==y)return y;var t=g(),r=e,n=m(function(e){return i(e)}),i=h(t,r,n);return i})),A(r,M()),A(n,M(b,g)),A(i,M(function(e){return function(t){var r=e(t);return!0===r?x(t):r}})),function(e){throw o('"'+e+'" could not be tokenised')});function I(e,t){return t}function T(e,t){return E(e,t,e?T:I)}return function(e){try{return T(e,y)}catch(t){throw o('Could not compile "'+e+'" because '+t.message)}}});function $(e,t,r){var n,i;function o(e){return function(t){return t.id==e}}return{on:function(r,o){var a={listener:r,id:o||r};return t&&t.emit(e,r,a.id),n=A(a,n),i=A(r,i),this},emit:function(){!function e(t,r){t&&(x(t).apply(null,r),e(k(t),r))}(i,arguments)},un:function(t){var a;n=j(n,o(t),function(e){a=e}),a&&(i=j(i,function(e){return e==a.listener}),r&&r.emit(e,a.listener,a.id))},listeners:function(){return i},hasListener:function(e){return w(function e(t,r){return r&&(t(x(r))?x(r):e(t,k(r)))}(e?o(e):y,n))}}}var Q=1,ee=Q++,te=Q++,re=Q++,ne=Q++,ie="fail",oe=Q++,ae=Q++,se="start",ue="data",ce="end",fe=Q++,he=Q++,le=Q++,de=Q++;function pe(e,t,r){try{var n=a.parse(t)}catch(e){}return{statusCode:e,body:t,jsonBody:n,thrown:r}}function be(e,t){var r={node:e(te),path:e(ee)};function n(t,r,n){var i=e(t).emit;r.on(function(e){var t=n(e);!1!==t&&function(e,t,r){var n=B(r);e(t,I(k(T(W,n))),I(T(Y,n)))}(i,Y(t),e)},t),e("removeListener").on(function(n){n==t&&(e(n).listeners()||r.un(t))})}e("newListener").on(function(e){var i=/(node|path):(.*)/.exec(e);if(i){var o=r[i[1]];o.hasListener(e)||n(e,o,t(i[2]))}})}function ye(e,t){var r,n=/^(node|path):./,i=e(oe),o=e(ne).emit,a=e(re).emit,s=d(function(t,i){if(r[t])l(i,r[t]);else{var o=e(t),a=i[0];n.test(t)?c(o,a):o.on(a)}return r});function c(e,t,n){n=n||t;var i=f(t);return e.on(function(){var t=!1;r.forget=function(){t=!0},l(arguments,i),delete r.forget,t&&e.un(n)},n),r}function f(e){return function(){try{return e.apply(r,arguments)}catch(e){setTimeout(function(){throw e})}}}function h(t,r,n){var i;i="node"==t?function(e){return function(){var t=e.apply(this,arguments);w(t)&&(t==ge.drop?o():a(t))}}(n):n,c(function(t,r){return e(t+":"+r)}(t,r),i,n)}function p(e,t,n){return g(t)?h(e,t,n):function(e,t){for(var r in t)h(e,r,t[r])}(e,t),r}return e(ae).on(function(e){var t;r.root=(t=e,function(){return t})}),e(se).on(function(e,t){r.header=function(e){return e?t[e]:t}}),r={on:s,addListener:s,removeListener:function(t,n,o){if("done"==t)i.un(n);else if("node"==t||"path"==t)e.un(t+":"+n,o);else{var a=n;e(t).un(a)}return r},emit:e.emit,node:u(p,"node"),path:u(p,"path"),done:u(c,i),start:u(function(t,n){return e(t).on(f(n),n),r},se),fail:e(ie).on,abort:e(fe).emit,header:b,root:b,source:t}}function me(t,r,n,i,o){var a=function(){var e={},t=n("newListener"),r=n("removeListener");function n(n){return e[n]=$(n,t,r)}function i(t){return e[t]||n(t)}return["emit","on","un"].forEach(function(e){i[e]=d(function(t,r){l(r,i(t)[e])})}),i}();return r&&function(t,r,n,i,o,a,c){"use strict";var f=t(ue).emit,h=t(ie).emit,l=0,d=!0;function p(){var e=r.responseText,t=e.substr(l);t&&f(t),l=v(e)}t(fe).on(function(){r.onreadystatechange=null,r.abort()}),"onprogress"in r&&(r.onprogress=p),r.onreadystatechange=function(){function e(){try{d&&t(se).emit(r.status,(e=r.getAllResponseHeaders(),n={},e&&e.split("\r\n").forEach(function(e){var t=e.indexOf(": ");n[e.substring(0,t)]=e.substring(t+2)}),n)),d=!1}catch(e){}var e,n}switch(r.readyState){case 2:case 3:return e();case 4:e(),2==String(r.status)[0]?(p(),t(ce).emit()):h(pe(r.status,r.responseText))}};try{for(var b in r.open(n,i,!0),a)r.setRequestHeader(b,a[b]);(function(e,t){function r(t){return t.port||{"http:":80,"https:":443}[t.protocol||e.protocol]}return!!(t.protocol&&t.protocol!=e.protocol||t.host&&t.host!=e.host||t.host&&r(t)!=r(e))})(e.location,function(e){var t=/(\w+:)?(?:\/\/)([\w.-]+)?(?::(\d+))?\/?/.exec(e)||[];return{protocol:t[1]||"",host:t[2]||"",port:t[3]||""}}(i))||r.setRequestHeader("X-Requested-With","XMLHttpRequest"),r.withCredentials=c,r.send(o)}catch(t){e.setTimeout(u(h,pe(s,s,t)),0)}}(a,new XMLHttpRequest,t,r,n,i,o),P(a),function(e,t){"use strict";var r,n={};function i(e){return function(t){r=e(r,t)}}for(var o in t)e(o).on(i(t[o]),n);e(re).on(function(e){var t=x(r),n=W(t),i=k(r);i&&(Y(x(i))[n]=e)}),e(ne).on(function(){var e=x(r),t=W(e),n=k(r);n&&delete Y(x(n))[t]}),e(fe).on(function(){for(var r in t)e(r).un(n)})}(a,Z(a)),be(a,J),ye(a,r)}function ve(e,t,r,n,i,o,s){return i=i?a.parse(a.stringify(i)):{},n?g(n)||(n=a.stringify(n),i["Content-Type"]=i["Content-Type"]||"application/json"):n=null,e(r||"GET",function(e,t){return!1===t&&(-1==e.indexOf("?")?e+="?":e+="&",e+="_="+(new Date).getTime()),e}(t,s),n,i,o||!1)}function ge(e){var t=M("resume","pause","pipe"),r=u(_,t);return e?r(e)||g(e)?ve(me,e):ve(me,e.url,e.method,e.body,e.headers,e.withCredentials,e.cached):me()}ge.drop=function(){return ge.drop},"function"==typeof define&&define.amd?define("oboe",[],function(){return ge}):"object"==typeof r?t.exports=ge:e.oboe=ge}(function(){try{return window}catch(e){return self}}(),Object,Array,Error,JSON)},{}],240:[function(e,t,r){r.endianness=function(){return"LE"},r.hostname=function(){return"undefined"!=typeof location?location.hostname:""},r.loadavg=function(){return[]},r.uptime=function(){return 0},r.freemem=function(){return Number.MAX_VALUE},r.totalmem=function(){return Number.MAX_VALUE},r.cpus=function(){return[]},r.type=function(){return"Browser"},r.release=function(){return"undefined"!=typeof navigator?navigator.appVersion:""},r.networkInterfaces=r.getNetworkInterfaces=function(){return{}},r.arch=function(){return"javascript"},r.platform=function(){return"browser"},r.tmpdir=r.tmpDir=function(){return"/tmp"},r.EOL="\n",r.homedir=function(){return"/"}},{}],241:[function(e,t,r){t.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","2.16.840.1.101.3.4.1.3":"aes-128-ofb","2.16.840.1.101.3.4.1.4":"aes-128-cfb","2.16.840.1.101.3.4.1.21":"aes-192-ecb","2.16.840.1.101.3.4.1.22":"aes-192-cbc","2.16.840.1.101.3.4.1.23":"aes-192-ofb","2.16.840.1.101.3.4.1.24":"aes-192-cfb","2.16.840.1.101.3.4.1.41":"aes-256-ecb","2.16.840.1.101.3.4.1.42":"aes-256-cbc","2.16.840.1.101.3.4.1.43":"aes-256-ofb","2.16.840.1.101.3.4.1.44":"aes-256-cfb"}},{}],242:[function(e,t,r){"use strict";var n=e("asn1.js");r.certificate=e("./certificate");var i=n.define("RSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("modulus").int(),this.key("publicExponent").int(),this.key("privateExponent").int(),this.key("prime1").int(),this.key("prime2").int(),this.key("exponent1").int(),this.key("exponent2").int(),this.key("coefficient").int())});r.RSAPrivateKey=i;var o=n.define("RSAPublicKey",function(){this.seq().obj(this.key("modulus").int(),this.key("publicExponent").int())});r.RSAPublicKey=o;var a=n.define("SubjectPublicKeyInfo",function(){this.seq().obj(this.key("algorithm").use(s),this.key("subjectPublicKey").bitstr())});r.PublicKey=a;var s=n.define("AlgorithmIdentifier",function(){this.seq().obj(this.key("algorithm").objid(),this.key("none").null_().optional(),this.key("curve").objid().optional(),this.key("params").seq().obj(this.key("p").int(),this.key("q").int(),this.key("g").int()).optional())}),u=n.define("PrivateKeyInfo",function(){this.seq().obj(this.key("version").int(),this.key("algorithm").use(s),this.key("subjectPrivateKey").octstr())});r.PrivateKey=u;var c=n.define("EncryptedPrivateKeyInfo",function(){this.seq().obj(this.key("algorithm").seq().obj(this.key("id").objid(),this.key("decrypt").seq().obj(this.key("kde").seq().obj(this.key("id").objid(),this.key("kdeparams").seq().obj(this.key("salt").octstr(),this.key("iters").int())),this.key("cipher").seq().obj(this.key("algo").objid(),this.key("iv").octstr()))),this.key("subjectPrivateKey").octstr())});r.EncryptedPrivateKey=c;var f=n.define("DSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("p").int(),this.key("q").int(),this.key("g").int(),this.key("pub_key").int(),this.key("priv_key").int())});r.DSAPrivateKey=f,r.DSAparam=n.define("DSAparam",function(){this.int()});var h=n.define("ECPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").optional().explicit(0).use(l),this.key("publicKey").optional().explicit(1).bitstr())});r.ECPrivateKey=h;var l=n.define("ECParameters",function(){this.choice({namedCurve:this.objid()})});r.signature=n.define("signature",function(){this.seq().obj(this.key("r").int(),this.key("s").int())})},{"./certificate":243,"asn1.js":5}],243:[function(e,t,r){"use strict";var n=e("asn1.js"),i=n.define("Time",function(){this.choice({utcTime:this.utctime(),generalTime:this.gentime()})}),o=n.define("AttributeTypeValue",function(){this.seq().obj(this.key("type").objid(),this.key("value").any())}),a=n.define("AlgorithmIdentifier",function(){this.seq().obj(this.key("algorithm").objid(),this.key("parameters").optional())}),s=n.define("SubjectPublicKeyInfo",function(){this.seq().obj(this.key("algorithm").use(a),this.key("subjectPublicKey").bitstr())}),u=n.define("RelativeDistinguishedName",function(){this.setof(o)}),c=n.define("RDNSequence",function(){this.seqof(u)}),f=n.define("Name",function(){this.choice({rdnSequence:this.use(c)})}),h=n.define("Validity",function(){this.seq().obj(this.key("notBefore").use(i),this.key("notAfter").use(i))}),l=n.define("Extension",function(){this.seq().obj(this.key("extnID").objid(),this.key("critical").bool().def(!1),this.key("extnValue").octstr())}),d=n.define("TBSCertificate",function(){this.seq().obj(this.key("version").explicit(0).int(),this.key("serialNumber").int(),this.key("signature").use(a),this.key("issuer").use(f),this.key("validity").use(h),this.key("subject").use(f),this.key("subjectPublicKeyInfo").use(s),this.key("issuerUniqueID").implicit(1).bitstr().optional(),this.key("subjectUniqueID").implicit(2).bitstr().optional(),this.key("extensions").explicit(3).seqof(l).optional())}),p=n.define("X509Certificate",function(){this.seq().obj(this.key("tbsCertificate").use(d),this.key("signatureAlgorithm").use(a),this.key("signatureValue").bitstr())});t.exports=p},{"asn1.js":5}],244:[function(e,t,r){(function(r){var n=/Proc-Type: 4,ENCRYPTED\n\r?DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)\n\r?\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?/m,i=/^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----\n/m,o=/^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?-----END \1-----$/m,a=e("evp_bytestokey"),s=e("browserify-aes");t.exports=function(e,t){var u,c=e.toString(),f=c.match(n);if(f){var h="aes"+f[1],l=new r(f[2],"hex"),d=new r(f[3].replace(/\r?\n/g,""),"base64"),p=a(t,l.slice(0,8),parseInt(f[1],10)).key,b=[],y=s.createDecipheriv(h,p,l);b.push(y.update(d)),b.push(y.final()),u=r.concat(b)}else{var m=c.match(o);u=new r(m[2].replace(/\r?\n/g,""),"base64")}return{tag:c.match(i)[1],data:u}}}).call(this,e("buffer").Buffer)},{"browserify-aes":58,buffer:84,evp_bytestokey:158}],245:[function(e,t,r){(function(r){var n=e("./asn1"),i=e("./aesid.json"),o=e("./fixProc"),a=e("browserify-aes"),s=e("pbkdf2");function u(e){var t;"object"!=typeof e||r.isBuffer(e)||(t=e.passphrase,e=e.key),"string"==typeof e&&(e=new r(e));var u,c,f=o(e,t),h=f.tag,l=f.data;switch(h){case"CERTIFICATE":c=n.certificate.decode(l,"der").tbsCertificate.subjectPublicKeyInfo;case"PUBLIC KEY":switch(c||(c=n.PublicKey.decode(l,"der")),u=c.algorithm.algorithm.join(".")){case"1.2.840.113549.1.1.1":return n.RSAPublicKey.decode(c.subjectPublicKey.data,"der");case"1.2.840.10045.2.1":return c.subjectPrivateKey=c.subjectPublicKey,{type:"ec",data:c};case"1.2.840.10040.4.1":return c.algorithm.params.pub_key=n.DSAparam.decode(c.subjectPublicKey.data,"der"),{type:"dsa",data:c.algorithm.params};default:throw new Error("unknown key id "+u)}throw new Error("unknown key type "+h);case"ENCRYPTED PRIVATE KEY":l=function(e,t){var n=e.algorithm.decrypt.kde.kdeparams.salt,o=parseInt(e.algorithm.decrypt.kde.kdeparams.iters.toString(),10),u=i[e.algorithm.decrypt.cipher.algo.join(".")],c=e.algorithm.decrypt.cipher.iv,f=e.subjectPrivateKey,h=parseInt(u.split("-")[1],10)/8,l=s.pbkdf2Sync(t,n,o,h),d=a.createDecipheriv(u,l,c),p=[];return p.push(d.update(f)),p.push(d.final()),r.concat(p)}(l=n.EncryptedPrivateKey.decode(l,"der"),t);case"PRIVATE KEY":switch(u=(c=n.PrivateKey.decode(l,"der")).algorithm.algorithm.join(".")){case"1.2.840.113549.1.1.1":return n.RSAPrivateKey.decode(c.subjectPrivateKey,"der");case"1.2.840.10045.2.1":return{curve:c.algorithm.curve,privateKey:n.ECPrivateKey.decode(c.subjectPrivateKey,"der").privateKey};case"1.2.840.10040.4.1":return c.algorithm.params.priv_key=n.DSAparam.decode(c.subjectPrivateKey,"der"),{type:"dsa",params:c.algorithm.params};default:throw new Error("unknown key id "+u)}throw new Error("unknown key type "+h);case"RSA PUBLIC KEY":return n.RSAPublicKey.decode(l,"der");case"RSA PRIVATE KEY":return n.RSAPrivateKey.decode(l,"der");case"DSA PRIVATE KEY":return{type:"dsa",params:n.DSAPrivateKey.decode(l,"der")};case"EC PRIVATE KEY":return{curve:(l=n.ECPrivateKey.decode(l,"der")).parameters.value,privateKey:l.privateKey};default:throw new Error("unknown key type "+h)}}t.exports=u,u.signature=n.signature}).call(this,e("buffer").Buffer)},{"./aesid.json":241,"./asn1":242,"./fixProc":244,"browserify-aes":58,buffer:84,pbkdf2:247}],246:[function(e,t,r){var n=e("trim"),i=e("for-each");t.exports=function(e){if(!e)return{};var t={};return i(n(e).split("\n"),function(e){var r,i=e.indexOf(":"),o=n(e.slice(0,i)).toLowerCase(),a=n(e.slice(i+1));void 0===t[o]?t[o]=a:(r=t[o],"[object Array]"===Object.prototype.toString.call(r)?t[o].push(a):t[o]=[t[o],a])}),t}},{"for-each":159,trim:324}],247:[function(e,t,r){r.pbkdf2=e("./lib/async"),r.pbkdf2Sync=e("./lib/sync")},{"./lib/async":248,"./lib/sync":251}],248:[function(e,t,r){(function(r,n){var i,o=e("./precondition"),a=e("./default-encoding"),s=e("./sync"),u=e("safe-buffer").Buffer,c=n.crypto&&n.crypto.subtle,f={sha:"SHA-1","sha-1":"SHA-1",sha1:"SHA-1",sha256:"SHA-256","sha-256":"SHA-256",sha384:"SHA-384","sha-384":"SHA-384","sha-512":"SHA-512",sha512:"SHA-512"},h=[];function l(e,t,r,n,i){return c.importKey("raw",e,{name:"PBKDF2"},!1,["deriveBits"]).then(function(e){return c.deriveBits({name:"PBKDF2",salt:t,iterations:r,hash:{name:i}},e,n<<3)}).then(function(e){return u.from(e)})}t.exports=function(e,t,d,p,b,y){if(u.isBuffer(e)||(e=u.from(e,a)),u.isBuffer(t)||(t=u.from(t,a)),o(d,p),"function"==typeof b&&(y=b,b=void 0),"function"!=typeof y)throw new Error("No callback provided to pbkdf2");var m=f[(b=b||"sha1").toLowerCase()];if(!m||"function"!=typeof n.Promise)return r.nextTick(function(){var r;try{r=s(e,t,d,p,b)}catch(e){return y(e)}y(null,r)});!function(e,t){e.then(function(e){r.nextTick(function(){t(null,e)})},function(e){r.nextTick(function(){t(e)})})}(function(e){if(n.process&&!n.process.browser)return Promise.resolve(!1);if(!c||!c.importKey||!c.deriveBits)return Promise.resolve(!1);if(void 0!==h[e])return h[e];var t=l(i=i||u.alloc(8),i,10,128,e).then(function(){return!0}).catch(function(){return!1});return h[e]=t,t}(m).then(function(r){return r?l(e,t,d,p,m):s(e,t,d,p,b)}),y)}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./default-encoding":249,"./precondition":250,"./sync":251,_process:257,"safe-buffer":290}],249:[function(e,t,r){(function(e){var r;e.browser?r="utf-8":r=parseInt(e.version.split(".")[0].slice(1),10)>=6?"utf-8":"binary";t.exports=r}).call(this,e("_process"))},{_process:257}],250:[function(e,t,r){var n=Math.pow(2,30)-1;t.exports=function(e,t){if("number"!=typeof e)throw new TypeError("Iterations not a number");if(e<0)throw new TypeError("Bad iterations");if("number"!=typeof t)throw new TypeError("Key length not a number");if(t<0||t>n||t!=t)throw new TypeError("Bad key length")}},{}],251:[function(e,t,r){var n=e("create-hash/md5"),i=e("ripemd160"),o=e("sha.js"),a=e("./precondition"),s=e("./default-encoding"),u=e("safe-buffer").Buffer,c=u.alloc(128),f={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,rmd160:20,ripemd160:20};function h(e,t,r){var a=function(e){return"rmd160"===e||"ripemd160"===e?i:"md5"===e?n:function(t){return o(e).update(t).digest()}}(e),s="sha512"===e||"sha384"===e?128:64;t.length>s?t=a(t):t.length1)for(var r=1;rp||new a(t).cmp(d.modulus)>=0)throw new Error("decryption error");l=f?c(new a(t),d):s(t,d);var b=new r(p-l.length);if(b.fill(0),l=r.concat([b,l],p),4===h)return function(e,t){e.modulus;var n=e.modulus.byteLength(),a=(t.length,u("sha1").update(new r("")).digest()),s=a.length;if(0!==t[0])throw new Error("decryption error");var c=t.slice(1,s+1),f=t.slice(s+1),h=o(c,i(f,s)),l=o(f,i(h,n-s-1));if(function(e,t){e=new r(e),t=new r(t);var n=0,i=e.length;e.length!==t.length&&(n++,i=Math.min(e.length,t.length));var o=-1;for(;++o=t.length){o++;break}var a=t.slice(2,i-1);t.slice(i-1,i);("0002"!==n.toString("hex")&&!r||"0001"!==n.toString("hex")&&r)&&o++;a.length<8&&o++;if(o)throw new Error("decryption error");return t.slice(i)}(0,l,f);if(3===h)return l;throw new Error("unknown padding")}}).call(this,e("buffer").Buffer)},{"./mgf":260,"./withPublic":263,"./xor":264,"bn.js":53,"browserify-rsa":76,buffer:84,"create-hash":91,"parse-asn1":245}],262:[function(e,t,r){(function(r){var n=e("parse-asn1"),i=e("randombytes"),o=e("create-hash"),a=e("./mgf"),s=e("./xor"),u=e("bn.js"),c=e("./withPublic"),f=e("browserify-rsa");t.exports=function(e,t,h){var l;l=e.padding?e.padding:h?1:4;var d,p=n(e);if(4===l)d=function(e,t){var n=e.modulus.byteLength(),c=t.length,f=o("sha1").update(new r("")).digest(),h=f.length,l=2*h;if(c>n-l-2)throw new Error("message too long");var d=new r(n-c-l-2);d.fill(0);var p=n-h-1,b=i(h),y=s(r.concat([f,d,new r([1]),t],p),a(b,p)),m=s(b,a(y,h));return new u(r.concat([new r([0]),m,y],n))}(p,t);else if(1===l)d=function(e,t,n){var o,a=t.length,s=e.modulus.byteLength();if(a>s-11)throw new Error("message too long");n?(o=new r(s-a-3)).fill(255):o=function(e,t){var n,o=new r(e),a=0,s=i(2*e),u=0;for(;a=0)throw new Error("data too long for modulus")}return h?f(d,p):c(d,p)}}).call(this,e("buffer").Buffer)},{"./mgf":260,"./withPublic":263,"./xor":264,"bn.js":53,"browserify-rsa":76,buffer:84,"create-hash":91,"parse-asn1":245,randombytes:270}],263:[function(e,t,r){(function(r){var n=e("bn.js");t.exports=function(e,t){return new r(e.toRed(n.mont(t.modulus)).redPow(new n(t.publicExponent)).fromRed().toArray())}}).call(this,e("buffer").Buffer)},{"bn.js":53,buffer:84}],264:[function(e,t,r){t.exports=function(e,t){for(var r=e.length,n=-1;++n= 0x80 (not a basic code point)","invalid-input":"Invalid input"},A=f-h,E=Math.floor,x=String.fromCharCode;function k(e){throw new RangeError(_[e])}function S(e,t){for(var r=e.length,n=[];r--;)n[r]=t(e[r]);return n}function M(e,t){var r=e.split("@"),n="";return r.length>1&&(n=r[0]+"@",e=r[1]),n+S((e=e.replace(w,".")).split("."),t).join(".")}function I(e){for(var t,r,n=[],i=0,o=e.length;i=55296&&t<=56319&&i65535&&(t+=x((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=x(e)}).join("")}function U(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function j(e,t,r){var n=0;for(e=r?E(e/p):e>>1,e+=E(e/t);e>A*l>>1;n+=f)e=E(e/A);return E(n+(A+1)*e/(e+d))}function B(e){var t,r,n,i,o,a,s,u,d,p,v,g=[],w=e.length,_=0,A=y,x=b;for((r=e.lastIndexOf(m))<0&&(r=0),n=0;n=128&&k("not-basic"),g.push(e.charCodeAt(n));for(i=r>0?r+1:0;i=w&&k("invalid-input"),((u=(v=e.charCodeAt(i++))-48<10?v-22:v-65<26?v-65:v-97<26?v-97:f)>=f||u>E((c-_)/a))&&k("overflow"),_+=u*a,!(u<(d=s<=x?h:s>=x+l?l:s-x));s+=f)a>E(c/(p=f-d))&&k("overflow"),a*=p;x=j(_-o,t=g.length+1,0==o),E(_/t)>c-A&&k("overflow"),A+=E(_/t),_%=t,g.splice(_++,0,A)}return T(g)}function P(e){var t,r,n,i,o,a,s,u,d,p,v,g,w,_,A,S=[];for(g=(e=I(e)).length,t=y,r=0,o=b,a=0;a=t&&vE((c-r)/(w=n+1))&&k("overflow"),r+=(s-t)*w,t=s,a=0;ac&&k("overflow"),v==t){for(u=r,d=f;!(u<(p=d<=o?h:d>=o+l?l:d-o));d+=f)A=u-p,_=f-p,S.push(x(U(p+A%_,0))),u=E(A/_);S.push(x(U(u,0))),o=j(r,w,n==i),r=0,++n}++r,++t}return S.join("")}if(s={version:"1.4.1",ucs2:{decode:I,encode:T},decode:B,encode:P,toASCII:function(e){return M(e,function(e){return g.test(e)?"xn--"+P(e):e})},toUnicode:function(e){return M(e,function(e){return v.test(e)?B(e.slice(4).toLowerCase()):e})}},"function"==typeof define&&"object"==typeof define.amd&&define.amd)define("punycode",function(){return s});else if(i&&o)if(t.exports==i)o.exports=s;else for(u in s)s.hasOwnProperty(u)&&(i[u]=s[u]);else n.punycode=s}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],266:[function(e,t,r){"use strict";var n=e("strict-uri-encode"),i=e("object-assign"),o=e("decode-uri-component");function a(e,t){return t.encode?t.strict?n(e):encodeURIComponent(e):e}function s(e){var t=e.indexOf("?");return-1===t?"":e.slice(t+1)}function u(e,t){var r=function(e){var t;switch(e.arrayFormat){case"index":return function(e,r,n){t=/\[(\d*)\]$/.exec(e),e=e.replace(/\[\d*\]$/,""),t?(void 0===n[e]&&(n[e]={}),n[e][t[1]]=r):n[e]=r};case"bracket":return function(e,r,n){t=/(\[\])$/.exec(e),e=e.replace(/\[\]$/,""),t?void 0!==n[e]?n[e]=[].concat(n[e],r):n[e]=[r]:n[e]=r};default:return function(e,t,r){void 0!==r[e]?r[e]=[].concat(r[e],t):r[e]=t}}}(t=i({arrayFormat:"none"},t)),n=Object.create(null);return"string"!=typeof e?n:(e=e.trim().replace(/^[?#&]/,""))?(e.split("&").forEach(function(e){var t=e.replace(/\+/g," ").split("="),i=t.shift(),a=t.length>0?t.join("="):void 0;a=void 0===a?null:o(a),r(o(i),a,n)}),Object.keys(n).sort().reduce(function(e,t){var r=n[t];return Boolean(r)&&"object"==typeof r&&!Array.isArray(r)?e[t]=function e(t){return Array.isArray(t)?t.sort():"object"==typeof t?e(Object.keys(t)).sort(function(e,t){return Number(e)-Number(t)}).map(function(e){return t[e]}):t}(r):e[t]=r,e},Object.create(null))):n}r.extract=s,r.parse=u,r.stringify=function(e,t){!1===(t=i({encode:!0,strict:!0,arrayFormat:"none"},t)).sort&&(t.sort=function(){});var r=function(e){switch(e.arrayFormat){case"index":return function(t,r,n){return null===r?[a(t,e),"[",n,"]"].join(""):[a(t,e),"[",a(n,e),"]=",a(r,e)].join("")};case"bracket":return function(t,r){return null===r?a(t,e):[a(t,e),"[]=",a(r,e)].join("")};default:return function(t,r){return null===r?a(t,e):[a(t,e),"=",a(r,e)].join("")}}}(t);return e?Object.keys(e).sort(t.sort).map(function(n){var i=e[n];if(void 0===i)return"";if(null===i)return a(n,t);if(Array.isArray(i)){var o=[];return i.slice().forEach(function(e){void 0!==e&&o.push(r(n,e,o.length))}),o.join("&")}return a(n,t)+"="+a(i,t)}).filter(function(e){return e.length>0}).join("&"):""},r.parseUrl=function(e,t){return{url:e.split("?")[0]||"",query:u(s(e),t)}}},{"decode-uri-component":98,"object-assign":238,"strict-uri-encode":316}],267:[function(e,t,r){"use strict";function n(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.exports=function(e,t,r,o){t=t||"&",r=r||"=";var a={};if("string"!=typeof e||0===e.length)return a;var s=/\+/g;e=e.split(t);var u=1e3;o&&"number"==typeof o.maxKeys&&(u=o.maxKeys);var c=e.length;u>0&&c>u&&(c=u);for(var f=0;f=0?(h=b.substr(0,y),l=b.substr(y+1)):(h=b,l=""),d=decodeURIComponent(h),p=decodeURIComponent(l),n(a,d)?i(a[d])?a[d].push(p):a[d]=[a[d],p]:a[d]=p}return a};var i=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],268:[function(e,t,r){"use strict";var n=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,r,s){return t=t||"&",r=r||"=",null===e&&(e=void 0),"object"==typeof e?o(a(e),function(a){var s=encodeURIComponent(n(a))+r;return i(e[a])?o(e[a],function(e){return s+encodeURIComponent(n(e))}).join(t):s+encodeURIComponent(n(e[a]))}).join(t):s?encodeURIComponent(n(s))+r+encodeURIComponent(n(e)):""};var i=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function o(e,t){if(e.map)return e.map(t);for(var r=[],n=0;n65536)throw new Error("requested too many random bytes");var a=new n.Uint8Array(e);e>0&&o.getRandomValues(a);var s=i.from(a.buffer);if("function"==typeof t)return r.nextTick(function(){t(null,s)});return s}:t.exports=function(){throw new Error("Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11")}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:257,"safe-buffer":290}],271:[function(e,t,r){(function(t,n){"use strict";function i(){throw new Error("secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11")}var o=e("safe-buffer"),a=e("randombytes"),s=o.Buffer,u=o.kMaxLength,c=n.crypto||n.msCrypto,f=Math.pow(2,32)-1;function h(e,t){if("number"!=typeof e||e!=e)throw new TypeError("offset must be a number");if(e>f||e<0)throw new TypeError("offset must be a uint32");if(e>u||e>t)throw new RangeError("offset out of range")}function l(e,t,r){if("number"!=typeof e||e!=e)throw new TypeError("size must be a number");if(e>f||e<0)throw new TypeError("size must be a uint32");if(e+t>r||e>u)throw new RangeError("buffer too small")}function d(e,r,n,i){if(t.browser){var o=e.buffer,s=new Uint8Array(o,r,n);return c.getRandomValues(s),i?void t.nextTick(function(){i(null,e)}):e}if(!i)return a(n).copy(e,r),e;a(n,function(t,n){if(t)return i(t);n.copy(e,r),i(null,e)})}c&&c.getRandomValues||!t.browser?(r.randomFill=function(e,t,r,i){if(!(s.isBuffer(e)||e instanceof n.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');if("function"==typeof t)i=t,t=0,r=e.length;else if("function"==typeof r)i=r,r=e.length-t;else if("function"!=typeof i)throw new TypeError('"cb" argument must be a function');return h(t,e.length),l(r,t,e.length),d(e,t,r,i)},r.randomFillSync=function(e,t,r){void 0===t&&(t=0);if(!(s.isBuffer(e)||e instanceof n.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');h(t,e.length),void 0===r&&(r=e.length-t);return l(r,t,e.length),d(e,t,r)}):(r.randomFill=i,r.randomFillSync=i)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:257,randombytes:270,"safe-buffer":290}],272:[function(e,t,r){t.exports=window.crypto},{}],273:[function(e,t,r){t.exports=e("crypto")},{crypto:272}],274:[function(e,t,r){t.exports=function(t,r){var n=e("./crypto.js"),i="function"==typeof r;if(t>65536){if(!i)throw new Error("Requested too many random bytes.");r(new Error("Requested too many random bytes."))}if(void 0!==n&&n.randomBytes){if(!i)return"0x"+n.randomBytes(t).toString("hex");n.randomBytes(t,function(e,t){e?r(u):r(null,"0x"+t.toString("hex"))})}else{var o;if(void 0!==n?o=n:"undefined"!=typeof msCrypto&&(o=msCrypto),o&&o.getRandomValues){var a=o.getRandomValues(new Uint8Array(t)),s="0x"+Array.from(a).map(function(e){return e.toString(16)}).join("");if(!i)return s;r(null,s)}else{var u=new Error('No "crypto" object available. This Browser doesn\'t support generating secure random bytes.');if(!i)throw u;r(u)}}}},{"./crypto.js":273}],275:[function(e,t,r){t.exports=e("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":276}],276:[function(e,t,r){"use strict";var n=e("process-nextick-args").nextTick,i=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};t.exports=h;var o=e("core-util-is");o.inherits=e("inherits");var a=e("./_stream_readable"),s=e("./_stream_writable");o.inherits(h,a);for(var u=i(s.prototype),c=0;c0?("string"==typeof t||a.objectMode||Object.getPrototypeOf(t)===c.prototype||(t=function(e){return c.from(e)}(t)),n?a.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):_(e,a,t,!0):a.ended?e.emit("error",new Error("stream.push() after EOF")):(a.reading=!1,a.decoder&&!r?(t=a.decoder.write(t),a.objectMode||0!==t.length?_(e,a,t,!1):S(e,a)):_(e,a,t,!1))):n||(a.reading=!1));return function(e){return!e.ended&&(e.needReadable||e.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=A?e=A:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function x(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(d("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?i(k,e):k(e))}function k(e){d("emit readable"),e.emit("readable"),U(e)}function S(e,t){t.readingMore||(t.readingMore=!0,i(M,e,t))}function M(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):r=function(e,t,r){var n;eo.length?o.length:e;if(a===o.length?i+=o:i+=o.slice(0,e),0===(e-=a)){a===o.length?(++n,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=o.slice(a));break}++n}return t.length-=n,i}(e,t):function(e,t){var r=c.allocUnsafe(e),n=t.head,i=1;n.data.copy(r),e-=n.data.length;for(;n=n.next;){var o=n.data,a=e>o.length?o.length:e;if(o.copy(r,r.length-e,0,a),0===(e-=a)){a===o.length?(++i,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(a));break}++i}return t.length-=i,r}(e,t);return n}(e,t.buffer,t.decoder),r);var r}function B(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,i(P,t,e))}function P(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function C(e,t){for(var r=0,n=e.length;r=t.highWaterMark||t.ended))return d("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?B(this):x(this),null;if(0===(e=E(e,t))&&t.ended)return 0===t.length&&B(this),null;var n,i=t.needReadable;return d("need readable",i),(0===t.length||t.length-e0?j(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&B(this)),null!==n&&this.emit("data",n),n},g.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},g.prototype.pipe=function(e,t){var n=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,d("pipe count=%d opts=%j",o.pipesCount,t);var u=(!t||!1!==t.end)&&e!==r.stdout&&e!==r.stderr?f:g;function c(t,r){d("onunpipe"),t===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,d("cleanup"),e.removeListener("close",m),e.removeListener("finish",v),e.removeListener("drain",h),e.removeListener("error",y),e.removeListener("unpipe",c),n.removeListener("end",f),n.removeListener("end",g),n.removeListener("data",b),l=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||h())}function f(){d("onend"),e.end()}o.endEmitted?i(u):n.once("end",u),e.on("unpipe",c);var h=function(e){return function(){var t=e._readableState;d("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&s(e,"data")&&(t.flowing=!0,U(e))}}(n);e.on("drain",h);var l=!1;var p=!1;function b(t){d("ondata"),p=!1,!1!==e.write(t)||p||((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==C(o.pipes,e))&&!l&&(d("false write response, pause",n._readableState.awaitDrain),n._readableState.awaitDrain++,p=!0),n.pause())}function y(t){d("onerror",t),g(),e.removeListener("error",y),0===s(e,"error")&&e.emit("error",t)}function m(){e.removeListener("finish",v),g()}function v(){d("onfinish"),e.removeListener("close",m),g()}function g(){d("unpipe"),n.unpipe(e)}return n.on("data",b),function(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?a(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}(e,"error",y),e.once("close",m),e.once("finish",v),e.emit("pipe",n),o.flowing||(d("pipe resume"),n.resume()),e},g.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r),this);if(!e){var n=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o-1?setImmediate:i;m.WritableState=y;var u=e("core-util-is");u.inherits=e("inherits");var c={deprecate:e("util-deprecate")},f=e("./internal/streams/stream"),h=e("safe-buffer").Buffer,l=n.Uint8Array||function(){};var d,p=e("./internal/streams/destroy");function b(){}function y(t,r){a=a||e("./_stream_duplex"),t=t||{};var n=r instanceof a;this.objectMode=!!t.objectMode,n&&(this.objectMode=this.objectMode||!!t.writableObjectMode);var u=t.highWaterMark,c=t.writableHighWaterMark,f=this.objectMode?16:16384;this.highWaterMark=u||0===u?u:n&&(c||0===c)?c:f,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var h=!1===t.decodeStrings;this.decodeStrings=!h,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var r=e._writableState,n=r.sync,o=r.writecb;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(r),t)!function(e,t,r,n,o){--t.pendingcb,r?(i(o,n),i(E,e,t),e._writableState.errorEmitted=!0,e.emit("error",n)):(o(n),e._writableState.errorEmitted=!0,e.emit("error",n),E(e,t))}(e,r,n,t,o);else{var a=_(r);a||r.corked||r.bufferProcessing||!r.bufferedRequest||w(e,r),n?s(g,e,r,a,o):g(e,r,a,o)}}(r,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new o(this)}function m(t){if(a=a||e("./_stream_duplex"),!(d.call(m,this)||this instanceof a))return new m(t);this._writableState=new y(t,this),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),f.call(this)}function v(e,t,r,n,i,o,a){t.writelen=n,t.writecb=a,t.writing=!0,t.sync=!0,r?e._writev(i,t.onwrite):e._write(i,o,t.onwrite),t.sync=!1}function g(e,t,r,n){r||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,n(),E(e,t)}function w(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var n=t.bufferedRequestCount,i=new Array(n),a=t.corkedRequestsFree;a.entry=r;for(var s=0,u=!0;r;)i[s]=r,r.isBuf||(u=!1),r=r.next,s+=1;i.allBuffers=u,v(e,t,!0,t.length,i,"",a.finish),t.pendingcb++,t.lastBufferedRequest=null,a.next?(t.corkedRequestsFree=a.next,a.next=null):t.corkedRequestsFree=new o(t),t.bufferedRequestCount=0}else{for(;r;){var c=r.chunk,f=r.encoding,h=r.callback;if(v(e,t,!1,t.objectMode?1:c.length,c,f,h),r=r.next,t.bufferedRequestCount--,t.writing)break}null===r&&(t.lastBufferedRequest=null)}t.bufferedRequest=r,t.bufferProcessing=!1}function _(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function A(e,t){e._final(function(r){t.pendingcb--,r&&e.emit("error",r),t.prefinished=!0,e.emit("prefinish"),E(e,t)})}function E(e,t){var r=_(t);return r&&(!function(e,t){t.prefinished||t.finalCalled||("function"==typeof e._final?(t.pendingcb++,t.finalCalled=!0,i(A,e,t)):(t.prefinished=!0,e.emit("prefinish")))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"))),r}u.inherits(m,f),y.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(y.prototype,"buffer",{get:c.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(d=Function.prototype[Symbol.hasInstance],Object.defineProperty(m,Symbol.hasInstance,{value:function(e){return!!d.call(this,e)||this===m&&(e&&e._writableState instanceof y)}})):d=function(e){return e instanceof this},m.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},m.prototype.write=function(e,t,r){var n,o=this._writableState,a=!1,s=!o.objectMode&&(n=e,h.isBuffer(n)||n instanceof l);return s&&!h.isBuffer(e)&&(e=function(e){return h.from(e)}(e)),"function"==typeof t&&(r=t,t=null),s?t="buffer":t||(t=o.defaultEncoding),"function"!=typeof r&&(r=b),o.ended?function(e,t){var r=new Error("write after end");e.emit("error",r),i(t,r)}(this,r):(s||function(e,t,r,n){var o=!0,a=!1;return null===r?a=new TypeError("May not write null values to stream"):"string"==typeof r||void 0===r||t.objectMode||(a=new TypeError("Invalid non-string/buffer chunk")),a&&(e.emit("error",a),i(n,a),o=!1),o}(this,o,e,r))&&(o.pendingcb++,a=function(e,t,r,n,i,o){if(!r){var a=function(e,t,r){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=h.from(t,r));return t}(t,n,i);n!==a&&(r=!0,i="buffer",n=a)}var s=t.objectMode?1:n.length;t.length+=s;var u=t.length-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},m.prototype._write=function(e,t,r){r(new Error("_write() is not implemented"))},m.prototype._writev=null,m.prototype.end=function(e,t,r){var n=this._writableState;"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||function(e,t,r){t.ending=!0,E(e,t),r&&(t.finished?i(r):e.once("finish",r));t.ended=!0,e.writable=!1}(this,n,r)},Object.defineProperty(m.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),m.prototype.destroy=p.destroy,m.prototype._undestroy=p.undestroy,m.prototype._destroy=function(e,t){this.end(),t(e)}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?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(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("util");t.exports=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.head=null,this.tail=null,this.length=0}return e.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},e.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},e.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r},e.prototype.concat=function(e){if(0===this.length)return n.alloc(0);if(1===this.length)return this.head.data;for(var t,r,i,o=n.allocUnsafe(e>>>0),a=this.head,s=0;a;)t=a.data,r=o,i=s,t.copy(r,i),s+=a.data.length,a=a.next;return o},e}(),i&&i.inspect&&i.inspect.custom&&(t.exports.prototype[i.inspect.custom]=function(){var e=i.inspect({length:this.length});return this.constructor.name+" "+e})},{"safe-buffer":290,util:55}],282:[function(e,t,r){"use strict";var n=e("process-nextick-args").nextTick;function i(e,t){e.emit("error",t)}t.exports={destroy:function(e,t){var r=this,o=this._readableState&&this._readableState.destroyed,a=this._writableState&&this._writableState.destroyed;return o||a?(t?t(e):!e||this._writableState&&this._writableState.errorEmitted||n(i,this,e),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!t&&e?(n(i,r,e),r._writableState&&(r._writableState.errorEmitted=!0)):t&&t(e)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}}},{"process-nextick-args":256}],283:[function(e,t,r){t.exports=e("events").EventEmitter},{events:157}],284:[function(e,t,r){t.exports=e("./readable").PassThrough},{"./readable":285}],285:[function(e,t,r){(r=t.exports=e("./lib/_stream_readable.js")).Stream=r,r.Readable=r,r.Writable=e("./lib/_stream_writable.js"),r.Duplex=e("./lib/_stream_duplex.js"),r.Transform=e("./lib/_stream_transform.js"),r.PassThrough=e("./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(e,t,r){t.exports=e("./readable").Transform},{"./readable":285}],287:[function(e,t,r){t.exports=e("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":280}],288:[function(e,t,r){(function(r){"use strict";var n=e("inherits"),i=e("hash-base");function o(){i.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function a(e,t){return e<>>32-t}function s(e,t,r,n,i,o,s,u){return a(e+(t^r^n)+o+s|0,u)+i|0}function u(e,t,r,n,i,o,s,u){return a(e+(t&r|~t&n)+o+s|0,u)+i|0}function c(e,t,r,n,i,o,s,u){return a(e+((t|~r)^n)+o+s|0,u)+i|0}function f(e,t,r,n,i,o,s,u){return a(e+(t&n|r&~n)+o+s|0,u)+i|0}function h(e,t,r,n,i,o,s,u){return a(e+(t^(r|~n))+o+s|0,u)+i|0}n(o,i),o.prototype._update=function(){for(var e=new Array(16),t=0;t<16;++t)e[t]=this._block.readInt32LE(4*t);var r=this._a,n=this._b,i=this._c,o=this._d,l=this._e;l=s(l,r=s(r,n,i,o,l,e[0],0,11),n,i=a(i,10),o,e[1],0,14),n=s(n=a(n,10),i=s(i,o=s(o,l,r,n,i,e[2],0,15),l,r=a(r,10),n,e[3],0,12),o,l=a(l,10),r,e[4],0,5),o=s(o=a(o,10),l=s(l,r=s(r,n,i,o,l,e[5],0,8),n,i=a(i,10),o,e[6],0,7),r,n=a(n,10),i,e[7],0,9),r=s(r=a(r,10),n=s(n,i=s(i,o,l,r,n,e[8],0,11),o,l=a(l,10),r,e[9],0,13),i,o=a(o,10),l,e[10],0,14),i=s(i=a(i,10),o=s(o,l=s(l,r,n,i,o,e[11],0,15),r,n=a(n,10),i,e[12],0,6),l,r=a(r,10),n,e[13],0,7),l=u(l=a(l,10),r=s(r,n=s(n,i,o,l,r,e[14],0,9),i,o=a(o,10),l,e[15],0,8),n,i=a(i,10),o,e[7],1518500249,7),n=u(n=a(n,10),i=u(i,o=u(o,l,r,n,i,e[4],1518500249,6),l,r=a(r,10),n,e[13],1518500249,8),o,l=a(l,10),r,e[1],1518500249,13),o=u(o=a(o,10),l=u(l,r=u(r,n,i,o,l,e[10],1518500249,11),n,i=a(i,10),o,e[6],1518500249,9),r,n=a(n,10),i,e[15],1518500249,7),r=u(r=a(r,10),n=u(n,i=u(i,o,l,r,n,e[3],1518500249,15),o,l=a(l,10),r,e[12],1518500249,7),i,o=a(o,10),l,e[0],1518500249,12),i=u(i=a(i,10),o=u(o,l=u(l,r,n,i,o,e[9],1518500249,15),r,n=a(n,10),i,e[5],1518500249,9),l,r=a(r,10),n,e[2],1518500249,11),l=u(l=a(l,10),r=u(r,n=u(n,i,o,l,r,e[14],1518500249,7),i,o=a(o,10),l,e[11],1518500249,13),n,i=a(i,10),o,e[8],1518500249,12),n=c(n=a(n,10),i=c(i,o=c(o,l,r,n,i,e[3],1859775393,11),l,r=a(r,10),n,e[10],1859775393,13),o,l=a(l,10),r,e[14],1859775393,6),o=c(o=a(o,10),l=c(l,r=c(r,n,i,o,l,e[4],1859775393,7),n,i=a(i,10),o,e[9],1859775393,14),r,n=a(n,10),i,e[15],1859775393,9),r=c(r=a(r,10),n=c(n,i=c(i,o,l,r,n,e[8],1859775393,13),o,l=a(l,10),r,e[1],1859775393,15),i,o=a(o,10),l,e[2],1859775393,14),i=c(i=a(i,10),o=c(o,l=c(l,r,n,i,o,e[7],1859775393,8),r,n=a(n,10),i,e[0],1859775393,13),l,r=a(r,10),n,e[6],1859775393,6),l=c(l=a(l,10),r=c(r,n=c(n,i,o,l,r,e[13],1859775393,5),i,o=a(o,10),l,e[11],1859775393,12),n,i=a(i,10),o,e[5],1859775393,7),n=f(n=a(n,10),i=f(i,o=c(o,l,r,n,i,e[12],1859775393,5),l,r=a(r,10),n,e[1],2400959708,11),o,l=a(l,10),r,e[9],2400959708,12),o=f(o=a(o,10),l=f(l,r=f(r,n,i,o,l,e[11],2400959708,14),n,i=a(i,10),o,e[10],2400959708,15),r,n=a(n,10),i,e[0],2400959708,14),r=f(r=a(r,10),n=f(n,i=f(i,o,l,r,n,e[8],2400959708,15),o,l=a(l,10),r,e[12],2400959708,9),i,o=a(o,10),l,e[4],2400959708,8),i=f(i=a(i,10),o=f(o,l=f(l,r,n,i,o,e[13],2400959708,9),r,n=a(n,10),i,e[3],2400959708,14),l,r=a(r,10),n,e[7],2400959708,5),l=f(l=a(l,10),r=f(r,n=f(n,i,o,l,r,e[15],2400959708,6),i,o=a(o,10),l,e[14],2400959708,8),n,i=a(i,10),o,e[5],2400959708,6),n=h(n=a(n,10),i=f(i,o=f(o,l,r,n,i,e[6],2400959708,5),l,r=a(r,10),n,e[2],2400959708,12),o,l=a(l,10),r,e[4],2840853838,9),o=h(o=a(o,10),l=h(l,r=h(r,n,i,o,l,e[0],2840853838,15),n,i=a(i,10),o,e[5],2840853838,5),r,n=a(n,10),i,e[9],2840853838,11),r=h(r=a(r,10),n=h(n,i=h(i,o,l,r,n,e[7],2840853838,6),o,l=a(l,10),r,e[12],2840853838,8),i,o=a(o,10),l,e[2],2840853838,13),i=h(i=a(i,10),o=h(o,l=h(l,r,n,i,o,e[10],2840853838,12),r,n=a(n,10),i,e[14],2840853838,5),l,r=a(r,10),n,e[1],2840853838,12),l=h(l=a(l,10),r=h(r,n=h(n,i,o,l,r,e[3],2840853838,13),i,o=a(o,10),l,e[8],2840853838,14),n,i=a(i,10),o,e[11],2840853838,11),n=h(n=a(n,10),i=h(i,o=h(o,l,r,n,i,e[6],2840853838,8),l,r=a(r,10),n,e[15],2840853838,5),o,l=a(l,10),r,e[13],2840853838,6),o=a(o,10);var d=this._a,p=this._b,b=this._c,y=this._d,m=this._e;m=h(m,d=h(d,p,b,y,m,e[5],1352829926,8),p,b=a(b,10),y,e[14],1352829926,9),p=h(p=a(p,10),b=h(b,y=h(y,m,d,p,b,e[7],1352829926,9),m,d=a(d,10),p,e[0],1352829926,11),y,m=a(m,10),d,e[9],1352829926,13),y=h(y=a(y,10),m=h(m,d=h(d,p,b,y,m,e[2],1352829926,15),p,b=a(b,10),y,e[11],1352829926,15),d,p=a(p,10),b,e[4],1352829926,5),d=h(d=a(d,10),p=h(p,b=h(b,y,m,d,p,e[13],1352829926,7),y,m=a(m,10),d,e[6],1352829926,7),b,y=a(y,10),m,e[15],1352829926,8),b=h(b=a(b,10),y=h(y,m=h(m,d,p,b,y,e[8],1352829926,11),d,p=a(p,10),b,e[1],1352829926,14),m,d=a(d,10),p,e[10],1352829926,14),m=f(m=a(m,10),d=h(d,p=h(p,b,y,m,d,e[3],1352829926,12),b,y=a(y,10),m,e[12],1352829926,6),p,b=a(b,10),y,e[6],1548603684,9),p=f(p=a(p,10),b=f(b,y=f(y,m,d,p,b,e[11],1548603684,13),m,d=a(d,10),p,e[3],1548603684,15),y,m=a(m,10),d,e[7],1548603684,7),y=f(y=a(y,10),m=f(m,d=f(d,p,b,y,m,e[0],1548603684,12),p,b=a(b,10),y,e[13],1548603684,8),d,p=a(p,10),b,e[5],1548603684,9),d=f(d=a(d,10),p=f(p,b=f(b,y,m,d,p,e[10],1548603684,11),y,m=a(m,10),d,e[14],1548603684,7),b,y=a(y,10),m,e[15],1548603684,7),b=f(b=a(b,10),y=f(y,m=f(m,d,p,b,y,e[8],1548603684,12),d,p=a(p,10),b,e[12],1548603684,7),m,d=a(d,10),p,e[4],1548603684,6),m=f(m=a(m,10),d=f(d,p=f(p,b,y,m,d,e[9],1548603684,15),b,y=a(y,10),m,e[1],1548603684,13),p,b=a(b,10),y,e[2],1548603684,11),p=c(p=a(p,10),b=c(b,y=c(y,m,d,p,b,e[15],1836072691,9),m,d=a(d,10),p,e[5],1836072691,7),y,m=a(m,10),d,e[1],1836072691,15),y=c(y=a(y,10),m=c(m,d=c(d,p,b,y,m,e[3],1836072691,11),p,b=a(b,10),y,e[7],1836072691,8),d,p=a(p,10),b,e[14],1836072691,6),d=c(d=a(d,10),p=c(p,b=c(b,y,m,d,p,e[6],1836072691,6),y,m=a(m,10),d,e[9],1836072691,14),b,y=a(y,10),m,e[11],1836072691,12),b=c(b=a(b,10),y=c(y,m=c(m,d,p,b,y,e[8],1836072691,13),d,p=a(p,10),b,e[12],1836072691,5),m,d=a(d,10),p,e[2],1836072691,14),m=c(m=a(m,10),d=c(d,p=c(p,b,y,m,d,e[10],1836072691,13),b,y=a(y,10),m,e[0],1836072691,13),p,b=a(b,10),y,e[4],1836072691,7),p=u(p=a(p,10),b=u(b,y=c(y,m,d,p,b,e[13],1836072691,5),m,d=a(d,10),p,e[8],2053994217,15),y,m=a(m,10),d,e[6],2053994217,5),y=u(y=a(y,10),m=u(m,d=u(d,p,b,y,m,e[4],2053994217,8),p,b=a(b,10),y,e[1],2053994217,11),d,p=a(p,10),b,e[3],2053994217,14),d=u(d=a(d,10),p=u(p,b=u(b,y,m,d,p,e[11],2053994217,14),y,m=a(m,10),d,e[15],2053994217,6),b,y=a(y,10),m,e[0],2053994217,14),b=u(b=a(b,10),y=u(y,m=u(m,d,p,b,y,e[5],2053994217,6),d,p=a(p,10),b,e[12],2053994217,9),m,d=a(d,10),p,e[2],2053994217,12),m=u(m=a(m,10),d=u(d,p=u(p,b,y,m,d,e[13],2053994217,9),b,y=a(y,10),m,e[9],2053994217,12),p,b=a(b,10),y,e[7],2053994217,5),p=s(p=a(p,10),b=u(b,y=u(y,m,d,p,b,e[10],2053994217,15),m,d=a(d,10),p,e[14],2053994217,8),y,m=a(m,10),d,e[12],0,8),y=s(y=a(y,10),m=s(m,d=s(d,p,b,y,m,e[15],0,5),p,b=a(b,10),y,e[10],0,12),d,p=a(p,10),b,e[4],0,9),d=s(d=a(d,10),p=s(p,b=s(b,y,m,d,p,e[1],0,12),y,m=a(m,10),d,e[5],0,5),b,y=a(y,10),m,e[8],0,14),b=s(b=a(b,10),y=s(y,m=s(m,d,p,b,y,e[7],0,6),d,p=a(p,10),b,e[6],0,8),m,d=a(d,10),p,e[2],0,13),m=s(m=a(m,10),d=s(d,p=s(p,b,y,m,d,e[13],0,6),b,y=a(y,10),m,e[14],0,5),p,b=a(b,10),y,e[0],0,15),p=s(p=a(p,10),b=s(b,y=s(y,m,d,p,b,e[3],0,13),m,d=a(d,10),p,e[9],0,11),y,m=a(m,10),d,e[11],0,11),y=a(y,10);var v=this._b+i+y|0;this._b=this._c+o+m|0,this._c=this._d+l+d|0,this._d=this._e+r+p|0,this._e=this._a+n+b|0,this._a=v},o.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=new r(20);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e.writeInt32LE(this._e,16),e},t.exports=o}).call(this,e("buffer").Buffer)},{buffer:84,"hash-base":161,inherits:180}],289:[function(e,t,r){const n=e("assert"),i=e("safe-buffer").Buffer;function o(e,t){if("00"===e.slice(0,2))throw new Error("invalid RLP: extra zeros");return parseInt(e,t)}function a(e,t){if(e<56)return i.from([e+t]);var r=u(e),n=u(t+55+r.length/2);return i.from(n+r,"hex")}function s(e){return"0x"===e.slice(0,2)}function u(e){var t=e.toString(16);return t.length%2&&(t="0"+t),t}function c(e){if(!i.isBuffer(e))if("string"==typeof e)e=s(e)?i.from(((r="string"!=typeof(n=e)?n:s(n)?n.slice(2):n).length%2&&(r="0"+r),r),"hex"):i.from(e);else if("number"==typeof e)e?(t=u(e),e=i.from(t,"hex")):e=i.from([]);else if(null==e)e=i.from([]);else{if(!e.toArray)throw new Error("invalid type");e=i.from(e.toArray())}var t,r,n;return e}r.encode=function(e){if(e instanceof Array){for(var t=[],n=0;nt.length)throw new Error("invalid rlp: total length is larger than the data");if(0===(s=t.slice(n,h)).length)throw new Error("invalid rlp, List has a invalid length");for(;s.length;)u=e(s),c.push(u.data),s=u.remainder;return{data:c,remainder:t.slice(h)}}(e=c(e));return t?r:(n.equal(r.remainder.length,0,"invalid remainder"),r.data)},r.getLength=function(e){if(!e||0===e.length)return i.from([]);var t=(e=c(e))[0];if(t<=127)return e.length;if(t<=183)return t-127;if(t<=191)return t-182;if(t<=247)return t-191;var r=t-246;return r+o(e.slice(1,r).toString("hex"),16)}},{assert:19,"safe-buffer":290}],290:[function(e,t,r){var n=e("buffer"),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function a(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=n:(o(n,r),r.Buffer=a),o(i,a),a.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},a.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},{buffer:84}],291:[function(e,t,r){const n=e("util"),i=e("events/");var o="object"==typeof Reflect?Reflect:null,a=o&&"function"==typeof o.apply?o.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};function s(){i.call(this)}function u(e,t,r){try{a(e,t,r)}catch(e){setTimeout(()=>{throw e})}}t.exports=s,n.inherits(s,i),s.prototype.emit=function(e){for(var t=[],r=1;r0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var s=i[e];if(void 0===s)return!1;if("function"==typeof s)u(s,this,t);else{var c=s.length,f=function(e,t){for(var r=new Array(t),n=0;n0&&a.length>i&&!a.warned){a.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=a.length,s=u,console&&console.warn&&console.warn(s)}return e}function h(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=function(){for(var e=[],t=0;t0&&(a=t[0]),a instanceof Error)throw a;var s=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw s.context=a,s}var u=i[e];if(void 0===u)return!1;if("function"==typeof u)o(u,this,t);else{var c=u.length,f=p(u,c);for(r=0;r=0;o--)if(r[o]===t||r[o].listener===t){a=r[o].listener,i=o;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1=0;n--)this.removeListener(e,t[n]);return this},s.prototype.listeners=function(e){return l(this,e,!0)},s.prototype.rawListeners=function(e){return l(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):d.call(e,t)},s.prototype.listenerCount=d,s.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]}},{}],293:[function(e,t,r){t.exports=e("scryptsy")},{scryptsy:294}],294:[function(e,t,r){(function(r){var n=e("pbkdf2").pbkdf2Sync,i=2147483647;function o(e,t,n,i,o){if(r.isBuffer(e)&&r.isBuffer(n))e.copy(n,i,t,t+o);else for(;o--;)n[i++]=e[t++]}t.exports=function(e,t,a,s,u,c,f){if(0===a||0!=(a&a-1))throw Error("N must be > 0 and a power of 2");if(a>i/128/s)throw Error("Parameter N is too large");if(s>i/128/u)throw Error("Parameter r is too large");var h,l=new r(256*s),d=new r(128*s*a),p=new Int32Array(16),b=new Int32Array(16),y=new r(64),m=n(e,t,1,128*u*s,"sha256");if(f){var v=u*a*2,g=0;h=function(){++g%1e3==0&&f({current:g,total:v,percent:g/v*100})}}for(var w=0;w>>32-t}function x(e){var t;for(t=0;t<16;t++)p[t]=(255&e[4*t+0])<<0,p[t]|=(255&e[4*t+1])<<8,p[t]|=(255&e[4*t+2])<<16,p[t]|=(255&e[4*t+3])<<24;for(o(p,0,b,0,16),t=8;t>0;t-=2)b[4]^=E(b[0]+b[12],7),b[8]^=E(b[4]+b[0],9),b[12]^=E(b[8]+b[4],13),b[0]^=E(b[12]+b[8],18),b[9]^=E(b[5]+b[1],7),b[13]^=E(b[9]+b[5],9),b[1]^=E(b[13]+b[9],13),b[5]^=E(b[1]+b[13],18),b[14]^=E(b[10]+b[6],7),b[2]^=E(b[14]+b[10],9),b[6]^=E(b[2]+b[14],13),b[10]^=E(b[6]+b[2],18),b[3]^=E(b[15]+b[11],7),b[7]^=E(b[3]+b[15],9),b[11]^=E(b[7]+b[3],13),b[15]^=E(b[11]+b[7],18),b[1]^=E(b[0]+b[3],7),b[2]^=E(b[1]+b[0],9),b[3]^=E(b[2]+b[1],13),b[0]^=E(b[3]+b[2],18),b[6]^=E(b[5]+b[4],7),b[7]^=E(b[6]+b[5],9),b[4]^=E(b[7]+b[6],13),b[5]^=E(b[4]+b[7],18),b[11]^=E(b[10]+b[9],7),b[8]^=E(b[11]+b[10],9),b[9]^=E(b[8]+b[11],13),b[10]^=E(b[9]+b[8],18),b[12]^=E(b[15]+b[14],7),b[13]^=E(b[12]+b[15],9),b[14]^=E(b[13]+b[12],13),b[15]^=E(b[14]+b[13],18);for(t=0;t<16;++t)p[t]=b[t]+p[t];for(t=0;t<16;t++){var r=4*t;e[r+0]=p[t]>>0&255,e[r+1]=p[t]>>8&255,e[r+2]=p[t]>>16&255,e[r+3]=p[t]>>24&255}}function k(e,t,r,n,i){for(var o=0;o=r)throw RangeError(n)}}).call(this,{isBuffer:e("../../is-buffer/index.js")})},{"../../is-buffer/index.js":181}],297:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("bip66"),o=n.from([48,129,211,2,1,1,4,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,160,129,133,48,129,130,2,1,1,48,44,6,7,42,134,72,206,61,1,1,2,33,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,255,255,252,47,48,6,4,1,0,4,1,7,4,33,2,121,190,102,126,249,220,187,172,85,160,98,149,206,135,11,7,2,155,252,219,45,206,40,217,89,242,129,91,22,248,23,152,2,33,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,186,174,220,230,175,72,160,59,191,210,94,140,208,54,65,65,2,1,1,161,36,3,34,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),a=n.from([48,130,1,19,2,1,1,4,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,160,129,165,48,129,162,2,1,1,48,44,6,7,42,134,72,206,61,1,1,2,33,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,255,255,252,47,48,6,4,1,0,4,1,7,4,65,4,121,190,102,126,249,220,187,172,85,160,98,149,206,135,11,7,2,155,252,219,45,206,40,217,89,242,129,91,22,248,23,152,72,58,218,119,38,163,196,101,93,164,251,252,14,17,8,168,253,23,180,72,166,133,84,25,156,71,208,143,251,16,212,184,2,33,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,186,174,220,230,175,72,160,59,191,210,94,140,208,54,65,65,2,1,1,161,68,3,66,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);r.privateKeyExport=function(e,t,r){var i=n.from(r?o:a);return e.copy(i,r?8:9),t.copy(i,r?181:214),i},r.privateKeyImport=function(e){var t=e.length,r=0;if(!(t2||t1?e[r+n-2]<<8:0);if(!(t<(r+=n)+i||t32||t1&&0===t[o]&&!(128&t[o+1]);--r,++o);for(var a=n.concat([n.from([0]),e.s]),s=33,u=0;s>1&&0===a[u]&&!(128&a[u+1]);--s,++u);return i.encode(t.slice(o),a.slice(u))},r.signatureImport=function(e){var t=n.alloc(32,0),r=n.alloc(32,0);try{var o=i.decode(e);if(33===o.r.length&&0===o.r[0]&&(o.r=o.r.slice(1)),o.r.length>32)throw new Error("R length is too long");if(33===o.s.length&&0===o.s[0]&&(o.s=o.s.slice(1)),o.s.length>32)throw new Error("S length is too long")}catch(e){return}return o.r.copy(t,32-o.r.length),o.s.copy(r,32-o.s.length),{r:t,s:r}},r.signatureImportLax=function(e){var t=n.alloc(32,0),r=n.alloc(32,0),i=e.length,o=0;if(48===e[o++]){var a=e[o++];if(!(128&a&&(o+=a-128)>i)&&2===e[o++]){var s=e[o++];if(128&s){if(o+(a=s-128)>i)return;for(;a>0&&0===e[o];o+=1,a-=1);for(s=0;a>0;o+=1,a-=1)s=(s<<8)+e[o]}if(!(s>i-o)){var u=o;if(o+=s,2===e[o++]){var c=e[o++];if(128&c){if(o+(a=c-128)>i)return;for(;a>0&&0===e[o];o+=1,a-=1);for(c=0;a>0;o+=1,a-=1)c=(c<<8)+e[o]}if(!(c>i-o)){var f=o;for(o+=c;s>0&&0===e[u];s-=1,u+=1);if(!(s>32)){var h=e.slice(u,u+s);for(h.copy(t,32-h.length);c>0&&0===e[f];c-=1,f+=1);if(!(c>32)){var l=e.slice(f,f+c);return l.copy(r,32-l.length),{r:t,s:r}}}}}}}}}},{bip66:52,"safe-buffer":290}],298:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("create-hash"),o=e("bn.js"),a=e("elliptic").ec,s=e("../messages.json"),u=new a("secp256k1"),c=u.curve;function f(e){var t=e[0];switch(t){case 2:case 3:return 33!==e.length?null:function(e,t){var r=new o(t);if(r.cmp(c.p)>=0)return null;var n=(r=r.toRed(c.red)).redSqr().redIMul(r).redIAdd(c.b).redSqrt();return 3===e!==n.isOdd()&&(n=n.redNeg()),u.keyPair({pub:{x:r,y:n}})}(t,e.slice(1,33));case 4:case 6:case 7:return 65!==e.length?null:function(e,t,r){var n=new o(t),i=new o(r);if(n.cmp(c.p)>=0||i.cmp(c.p)>=0)return null;if(n=n.toRed(c.red),i=i.toRed(c.red),(6===e||7===e)&&i.isOdd()!==(7===e))return null;var a=n.redSqr().redIMul(n);return i.redSqr().redISub(a.redIAdd(c.b)).isZero()?u.keyPair({pub:{x:n,y:i}}):null}(t,e.slice(1,33),e.slice(33,65));default:return null}}r.privateKeyVerify=function(e){var t=new o(e);return t.cmp(c.n)<0&&!t.isZero()},r.privateKeyExport=function(e,t){var r=new o(e);if(r.cmp(c.n)>=0||r.isZero())throw new Error(s.EC_PRIVATE_KEY_EXPORT_DER_FAIL);return n.from(u.keyFromPrivate(e).getPublic(t,!0))},r.privateKeyNegate=function(e){var t=new o(e);return t.isZero()?n.alloc(32):c.n.sub(t).umod(c.n).toArrayLike(n,"be",32)},r.privateKeyModInverse=function(e){var t=new o(e);if(t.cmp(c.n)>=0||t.isZero())throw new Error(s.EC_PRIVATE_KEY_RANGE_INVALID);return t.invm(c.n).toArrayLike(n,"be",32)},r.privateKeyTweakAdd=function(e,t){var r=new o(t);if(r.cmp(c.n)>=0)throw new Error(s.EC_PRIVATE_KEY_TWEAK_ADD_FAIL);if(r.iadd(new o(e)),r.cmp(c.n)>=0&&r.isub(c.n),r.isZero())throw new Error(s.EC_PRIVATE_KEY_TWEAK_ADD_FAIL);return r.toArrayLike(n,"be",32)},r.privateKeyTweakMul=function(e,t){var r=new o(t);if(r.cmp(c.n)>=0||r.isZero())throw new Error(s.EC_PRIVATE_KEY_TWEAK_MUL_FAIL);return r.imul(new o(e)),r.cmp(c.n)&&(r=r.umod(c.n)),r.toArrayLike(n,"be",32)},r.publicKeyCreate=function(e,t){var r=new o(e);if(r.cmp(c.n)>=0||r.isZero())throw new Error(s.EC_PUBLIC_KEY_CREATE_FAIL);return n.from(u.keyFromPrivate(e).getPublic(t,!0))},r.publicKeyConvert=function(e,t){var r=f(e);if(null===r)throw new Error(s.EC_PUBLIC_KEY_PARSE_FAIL);return n.from(r.getPublic(t,!0))},r.publicKeyVerify=function(e){return null!==f(e)},r.publicKeyTweakAdd=function(e,t,r){var i=f(e);if(null===i)throw new Error(s.EC_PUBLIC_KEY_PARSE_FAIL);if((t=new o(t)).cmp(c.n)>=0)throw new Error(s.EC_PUBLIC_KEY_TWEAK_ADD_FAIL);return n.from(c.g.mul(t).add(i.pub).encode(!0,r))},r.publicKeyTweakMul=function(e,t,r){var i=f(e);if(null===i)throw new Error(s.EC_PUBLIC_KEY_PARSE_FAIL);if((t=new o(t)).cmp(c.n)>=0||t.isZero())throw new Error(s.EC_PUBLIC_KEY_TWEAK_MUL_FAIL);return n.from(i.pub.mul(t).encode(!0,r))},r.publicKeyCombine=function(e,t){for(var r=new Array(e.length),i=0;i=0||r.cmp(c.n)>=0)throw new Error(s.ECDSA_SIGNATURE_PARSE_FAIL);var i=n.from(e);return 1===r.cmp(u.nh)&&c.n.sub(r).toArrayLike(n,"be",32).copy(i,32),i},r.signatureExport=function(e){var t=e.slice(0,32),r=e.slice(32,64);if(new o(t).cmp(c.n)>=0||new o(r).cmp(c.n)>=0)throw new Error(s.ECDSA_SIGNATURE_PARSE_FAIL);return{r:t,s:r}},r.signatureImport=function(e){var t=new o(e.r);t.cmp(c.n)>=0&&(t=new o(0));var r=new o(e.s);return r.cmp(c.n)>=0&&(r=new o(0)),n.concat([t.toArrayLike(n,"be",32),r.toArrayLike(n,"be",32)])},r.sign=function(e,t,r,i){if("function"==typeof r){var a=r;r=function(r){var u=a(e,t,null,i,r);if(!n.isBuffer(u)||32!==u.length)throw new Error(s.ECDSA_SIGN_FAIL);return new o(u)}}var f=new o(t);if(f.cmp(c.n)>=0||f.isZero())throw new Error(s.ECDSA_SIGN_FAIL);var h=u.sign(e,t,{canonical:!0,k:r,pers:i});return{signature:n.concat([h.r.toArrayLike(n,"be",32),h.s.toArrayLike(n,"be",32)]),recovery:h.recoveryParam}},r.verify=function(e,t,r){var n={r:t.slice(0,32),s:t.slice(32,64)},i=new o(n.r),a=new o(n.s);if(i.cmp(c.n)>=0||a.cmp(c.n)>=0)throw new Error(s.ECDSA_SIGNATURE_PARSE_FAIL);if(1===a.cmp(u.nh)||i.isZero()||a.isZero())return!1;var h=f(r);if(null===h)throw new Error(s.EC_PUBLIC_KEY_PARSE_FAIL);return u.verify(e,n,{x:h.pub.x,y:h.pub.y})},r.recover=function(e,t,r,i){var a={r:t.slice(0,32),s:t.slice(32,64)},f=new o(a.r),h=new o(a.s);if(f.cmp(c.n)>=0||h.cmp(c.n)>=0)throw new Error(s.ECDSA_SIGNATURE_PARSE_FAIL);try{if(f.isZero()||h.isZero())throw new Error;var l=u.recoverPubKey(e,a,r);return n.from(l.encode(!0,i))}catch(e){throw new Error(s.ECDSA_RECOVER_FAIL)}},r.ecdh=function(e,t){var n=r.ecdhUnsafe(e,t,!0);return i("sha256").update(n).digest()},r.ecdhUnsafe=function(e,t,r){var i=f(e);if(null===i)throw new Error(s.EC_PUBLIC_KEY_PARSE_FAIL);var a=new o(t);if(a.cmp(c.n)>=0||a.isZero())throw new Error(s.ECDH_FAIL);return n.from(i.pub.mul(a).encode(!0,r))}},{"../messages.json":300,"bn.js":53,"create-hash":91,elliptic:109,"safe-buffer":290}],299:[function(e,t,r){"use strict";var n=e("./assert"),i=e("./der"),o=e("./messages.json");function a(e,t){return void 0===e?t:(n.isBoolean(e,o.COMPRESSED_TYPE_INVALID),e)}t.exports=function(e){return{privateKeyVerify:function(t){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),32===t.length&&e.privateKeyVerify(t)},privateKeyExport:function(t,r){n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),r=a(r,!0);var s=e.privateKeyExport(t,r);return i.privateKeyExport(t,s,r)},privateKeyImport:function(t){if(n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),(t=i.privateKeyImport(t))&&32===t.length&&e.privateKeyVerify(t))return t;throw new Error(o.EC_PRIVATE_KEY_IMPORT_DER_FAIL)},privateKeyNegate:function(t){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),e.privateKeyNegate(t)},privateKeyModInverse:function(t){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),e.privateKeyModInverse(t)},privateKeyTweakAdd:function(t,r){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),n.isBuffer(r,o.TWEAK_TYPE_INVALID),n.isBufferLength(r,32,o.TWEAK_LENGTH_INVALID),e.privateKeyTweakAdd(t,r)},privateKeyTweakMul:function(t,r){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),n.isBuffer(r,o.TWEAK_TYPE_INVALID),n.isBufferLength(r,32,o.TWEAK_LENGTH_INVALID),e.privateKeyTweakMul(t,r)},publicKeyCreate:function(t,r){return n.isBuffer(t,o.EC_PRIVATE_KEY_TYPE_INVALID),n.isBufferLength(t,32,o.EC_PRIVATE_KEY_LENGTH_INVALID),r=a(r,!0),e.publicKeyCreate(t,r)},publicKeyConvert:function(t,r){return n.isBuffer(t,o.EC_PUBLIC_KEY_TYPE_INVALID),n.isBufferLength2(t,33,65,o.EC_PUBLIC_KEY_LENGTH_INVALID),r=a(r,!0),e.publicKeyConvert(t,r)},publicKeyVerify:function(t){return n.isBuffer(t,o.EC_PUBLIC_KEY_TYPE_INVALID),e.publicKeyVerify(t)},publicKeyTweakAdd:function(t,r,i){return n.isBuffer(t,o.EC_PUBLIC_KEY_TYPE_INVALID),n.isBufferLength2(t,33,65,o.EC_PUBLIC_KEY_LENGTH_INVALID),n.isBuffer(r,o.TWEAK_TYPE_INVALID),n.isBufferLength(r,32,o.TWEAK_LENGTH_INVALID),i=a(i,!0),e.publicKeyTweakAdd(t,r,i)},publicKeyTweakMul:function(t,r,i){return n.isBuffer(t,o.EC_PUBLIC_KEY_TYPE_INVALID),n.isBufferLength2(t,33,65,o.EC_PUBLIC_KEY_LENGTH_INVALID),n.isBuffer(r,o.TWEAK_TYPE_INVALID),n.isBufferLength(r,32,o.TWEAK_LENGTH_INVALID),i=a(i,!0),e.publicKeyTweakMul(t,r,i)},publicKeyCombine:function(t,r){n.isArray(t,o.EC_PUBLIC_KEYS_TYPE_INVALID),n.isLengthGTZero(t,o.EC_PUBLIC_KEYS_LENGTH_INVALID);for(var i=0;i=2&&("function"==typeof arguments[1]?r.task=arguments[1]:r.n=arguments[1]);var n=r.task;if(r.task=function(){n(t.leave)},t.current+r.n-e>t.capacity)return 1===e&&(t.current--,t.firstHere=!1),t.queue.push(r);t.current+=r.n-e,r.task(t.leave),1===e&&(t.firstHere=!1)},leave:function(e){if(e=e||1,t.current-=e,t.queue.length){var r=t.queue[0];r.n+t.current>t.capacity||(t.queue.shift(),t.current+=r.n,i(r.task))}else if(t.current<0)throw new Error("leave called too many times.")},available:function(e){return e=e||1,t.current+e<=t.capacity}};return t}void 0!==e&&e&&"function"==typeof e.nextTick&&(i=e.nextTick),"object"==typeof r?t.exports=o:"function"==typeof define&&define.amd?define(function(){return o}):n.semaphore=o}(this)}).call(this,e("_process"))},{_process:257}],302:[function(e,t,r){"use strict";t.exports="function"==typeof setImmediate?setImmediate:function(){var e=[].slice.apply(arguments);e.splice(1,0,0),setTimeout.apply(null,e)}},{}],303:[function(e,t,r){var n=e("safe-buffer").Buffer;function i(e,t){this._block=n.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}i.prototype.update=function(e,t){"string"==typeof e&&(t=t||"utf8",e=n.from(e,t));for(var r=this._block,i=this._blockSize,o=e.length,a=this._len,s=0;s=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var o=this._hash();return e?o.toString(e):o},i.prototype._update=function(){throw new Error("_update must be implemented by subclass")},t.exports=i},{"safe-buffer":290}],304:[function(e,t,r){(r=t.exports=function(e){e=e.toLowerCase();var t=r[e];if(!t)throw new Error(e+" is not supported (we accept pull requests)");return new t}).sha=e("./sha"),r.sha1=e("./sha1"),r.sha224=e("./sha224"),r.sha256=e("./sha256"),r.sha384=e("./sha384"),r.sha512=e("./sha512")},{"./sha":305,"./sha1":306,"./sha224":307,"./sha256":308,"./sha384":309,"./sha512":310}],305:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1518500249,1859775393,-1894007588,-899497514],s=new Array(80);function u(){this.init(),this._w=s,i.call(this,64,56)}function c(e){return e<<30|e>>>2}function f(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}n(u,i),u.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,h=0;h<16;++h)r[h]=e.readInt32BE(4*h);for(;h<80;++h)r[h]=r[h-3]^r[h-8]^r[h-14]^r[h-16];for(var l=0;l<80;++l){var d=~~(l/20),p=0|((t=n)<<5|t>>>27)+f(d,i,o,s)+u+r[l]+a[d];u=s,s=o,o=c(i),i=n,n=p}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},u.prototype._hash=function(){var e=o.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},t.exports=u},{"./hash":303,inherits:180,"safe-buffer":290}],306:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1518500249,1859775393,-1894007588,-899497514],s=new Array(80);function u(){this.init(),this._w=s,i.call(this,64,56)}function c(e){return e<<5|e>>>27}function f(e){return e<<30|e>>>2}function h(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}n(u,i),u.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,l=0;l<16;++l)r[l]=e.readInt32BE(4*l);for(;l<80;++l)r[l]=(t=r[l-3]^r[l-8]^r[l-14]^r[l-16])<<1|t>>>31;for(var d=0;d<80;++d){var p=~~(d/20),b=c(n)+h(p,i,o,s)+u+r[d]+a[p]|0;u=s,s=o,o=f(i),i=n,n=b}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0},u.prototype._hash=function(){var e=o.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},t.exports=u},{"./hash":303,inherits:180,"safe-buffer":290}],307:[function(e,t,r){var n=e("inherits"),i=e("./sha256"),o=e("./hash"),a=e("safe-buffer").Buffer,s=new Array(64);function u(){this.init(),this._w=s,o.call(this,64,56)}n(u,i),u.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},u.prototype._hash=function(){var e=a.allocUnsafe(28);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e},t.exports=u},{"./hash":303,"./sha256":308,inherits:180,"safe-buffer":290}],308:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],s=new Array(64);function u(){this.init(),this._w=s,i.call(this,64,56)}function c(e,t,r){return r^e&(t^r)}function f(e,t,r){return e&t|r&(e|t)}function h(e){return(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function l(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function d(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}n(u,i),u.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},u.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,u=0|this._e,p=0|this._f,b=0|this._g,y=0|this._h,m=0;m<16;++m)r[m]=e.readInt32BE(4*m);for(;m<64;++m)r[m]=0|(((t=r[m-2])>>>17|t<<15)^(t>>>19|t<<13)^t>>>10)+r[m-7]+d(r[m-15])+r[m-16];for(var v=0;v<64;++v){var g=y+l(u)+c(u,p,b)+a[v]+r[v]|0,w=h(n)+f(n,i,o)|0;y=b,b=p,p=u,u=s+g|0,s=o,o=i,i=n,n=g+w|0}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=u+this._e|0,this._f=p+this._f|0,this._g=b+this._g|0,this._h=y+this._h|0},u.prototype._hash=function(){var e=o.allocUnsafe(32);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e.writeInt32BE(this._h,28),e},t.exports=u},{"./hash":303,inherits:180,"safe-buffer":290}],309:[function(e,t,r){var n=e("inherits"),i=e("./sha512"),o=e("./hash"),a=e("safe-buffer").Buffer,s=new Array(160);function u(){this.init(),this._w=s,o.call(this,128,112)}n(u,i),u.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},u.prototype._hash=function(){var e=a.allocUnsafe(48);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e},t.exports=u},{"./hash":303,"./sha512":310,inherits:180,"safe-buffer":290}],310:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],s=new Array(160);function u(){this.init(),this._w=s,i.call(this,128,112)}function c(e,t,r){return r^e&(t^r)}function f(e,t,r){return e&t|r&(e|t)}function h(e,t){return(e>>>28|t<<4)^(t>>>2|e<<30)^(t>>>7|e<<25)}function l(e,t){return(e>>>14|t<<18)^(e>>>18|t<<14)^(t>>>9|e<<23)}function d(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^e>>>7}function p(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^(e>>>7|t<<25)}function b(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^e>>>6}function y(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^(e>>>6|t<<26)}function m(e,t){return e>>>0>>0?1:0}n(u,i),u.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},u.prototype._update=function(e){for(var t=this._w,r=0|this._ah,n=0|this._bh,i=0|this._ch,o=0|this._dh,s=0|this._eh,u=0|this._fh,v=0|this._gh,g=0|this._hh,w=0|this._al,_=0|this._bl,A=0|this._cl,E=0|this._dl,x=0|this._el,k=0|this._fl,S=0|this._gl,M=0|this._hl,I=0;I<32;I+=2)t[I]=e.readInt32BE(4*I),t[I+1]=e.readInt32BE(4*I+4);for(;I<160;I+=2){var T=t[I-30],U=t[I-30+1],j=d(T,U),B=p(U,T),P=b(T=t[I-4],U=t[I-4+1]),C=y(U,T),N=t[I-14],R=t[I-14+1],L=t[I-32],O=t[I-32+1],D=B+R|0,F=j+N+m(D,B)|0;F=(F=F+P+m(D=D+C|0,C)|0)+L+m(D=D+O|0,O)|0,t[I]=F,t[I+1]=D}for(var q=0;q<160;q+=2){F=t[q],D=t[q+1];var H=f(r,n,i),z=f(w,_,A),K=h(r,w),V=h(w,r),G=l(s,x),W=l(x,s),Y=a[q],X=a[q+1],Z=c(s,u,v),J=c(x,k,S),$=M+W|0,Q=g+G+m($,M)|0;Q=(Q=(Q=Q+Z+m($=$+J|0,J)|0)+Y+m($=$+X|0,X)|0)+F+m($=$+D|0,D)|0;var ee=V+z|0,te=K+H+m(ee,V)|0;g=v,M=S,v=u,S=k,u=s,k=x,s=o+Q+m(x=E+$|0,E)|0,o=i,E=A,i=n,A=_,n=r,_=w,r=Q+te+m(w=$+ee|0,$)|0}this._al=this._al+w|0,this._bl=this._bl+_|0,this._cl=this._cl+A|0,this._dl=this._dl+E|0,this._el=this._el+x|0,this._fl=this._fl+k|0,this._gl=this._gl+S|0,this._hl=this._hl+M|0,this._ah=this._ah+r+m(this._al,w)|0,this._bh=this._bh+n+m(this._bl,_)|0,this._ch=this._ch+i+m(this._cl,A)|0,this._dh=this._dh+o+m(this._dl,E)|0,this._eh=this._eh+s+m(this._el,x)|0,this._fh=this._fh+u+m(this._fl,k)|0,this._gh=this._gh+v+m(this._gl,S)|0,this._hh=this._hh+g+m(this._hl,M)|0},u.prototype._hash=function(){var e=o.allocUnsafe(64);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e},t.exports=u},{"./hash":303,inherits:180,"safe-buffer":290}],311:[function(e,t,r){t.exports=i;var n=e("events").EventEmitter;function i(){n.call(this)}e("inherits")(i,n),i.Readable=e("readable-stream/readable.js"),i.Writable=e("readable-stream/writable.js"),i.Duplex=e("readable-stream/duplex.js"),i.Transform=e("readable-stream/transform.js"),i.PassThrough=e("readable-stream/passthrough.js"),i.Stream=i,i.prototype.pipe=function(e,t){var r=this;function i(t){e.writable&&!1===e.write(t)&&r.pause&&r.pause()}function o(){r.readable&&r.resume&&r.resume()}r.on("data",i),e.on("drain",o),e._isStdio||t&&!1===t.end||(r.on("end",s),r.on("close",u));var a=!1;function s(){a||(a=!0,e.end())}function u(){a||(a=!0,"function"==typeof e.destroy&&e.destroy())}function c(e){if(f(),0===n.listenerCount(this,"error"))throw e}function f(){r.removeListener("data",i),e.removeListener("drain",o),r.removeListener("end",s),r.removeListener("close",u),r.removeListener("error",c),e.removeListener("error",c),r.removeListener("end",f),r.removeListener("close",f),e.removeListener("close",f)}return r.on("error",c),e.on("error",c),r.on("end",f),r.on("close",f),e.on("close",f),e.emit("pipe",r),e}},{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(e,t,r){(function(t){var n=e("./lib/request"),i=e("./lib/response"),o=e("xtend"),a=e("builtin-status-codes"),s=e("url"),u=r;u.request=function(e,r){e="string"==typeof e?s.parse(e):o(e);var i=-1===t.location.protocol.search(/^https?:$/)?"http:":"",a=e.protocol||i,u=e.hostname||e.host,c=e.port,f=e.path||"/";u&&-1!==u.indexOf(":")&&(u="["+u+"]"),e.url=(u?a+"//"+u:"")+(c?":"+c:"")+f,e.method=(e.method||"GET").toUpperCase(),e.headers=e.headers||{};var h=new n(e);return r&&h.on("response",r),h},u.get=function(e,t){var r=u.request(e,t);return r.end(),r},u.ClientRequest=n,u.IncomingMessage=i,u.Agent=function(){},u.Agent.defaultMaxSockets=4,u.STATUS_CODES=a,u.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./lib/request":314,"./lib/response":315,"builtin-status-codes":85,url:327,xtend:423}],313:[function(e,t,r){(function(e){r.fetch=s(e.fetch)&&s(e.ReadableStream),r.writableStream=s(e.WritableStream),r.abortController=s(e.AbortController),r.blobConstructor=!1;try{new Blob([new ArrayBuffer(1)]),r.blobConstructor=!0}catch(e){}var t;function n(){if(void 0!==t)return t;if(e.XMLHttpRequest){t=new e.XMLHttpRequest;try{t.open("GET",e.XDomainRequest?"/":"https://example.com")}catch(e){t=null}}else t=null;return t}function i(e){var t=n();if(!t)return!1;try{return t.responseType=e,t.responseType===e}catch(e){}return!1}var o=void 0!==e.ArrayBuffer,a=o&&s(e.ArrayBuffer.prototype.slice);function s(e){return"function"==typeof e}r.arraybuffer=r.fetch||o&&i("arraybuffer"),r.msstream=!r.fetch&&a&&i("ms-stream"),r.mozchunkedarraybuffer=!r.fetch&&o&&i("moz-chunked-arraybuffer"),r.overrideMimeType=r.fetch||!!n()&&s(n().overrideMimeType),r.vbArray=s(e.VBArray),t=null}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],314:[function(e,t,r){(function(r,n,i){var o=e("./capability"),a=e("inherits"),s=e("./response"),u=e("readable-stream"),c=e("to-arraybuffer"),f=s.IncomingMessage,h=s.readyStates;var l=t.exports=function(e){var t,r=this;u.Writable.call(r),r._opts=e,r._body=[],r._headers={},e.auth&&r.setHeader("Authorization","Basic "+new i(e.auth).toString("base64")),Object.keys(e.headers).forEach(function(t){r.setHeader(t,e.headers[t])});var n=!0;if("disable-fetch"===e.mode||"requestTimeout"in e&&!o.abortController)n=!1,t=!0;else if("prefer-streaming"===e.mode)t=!1;else if("allow-wrong-content-type"===e.mode)t=!o.overrideMimeType;else{if(e.mode&&"default"!==e.mode&&"prefer-fast"!==e.mode)throw new Error("Invalid value for opts.mode");t=!0}r._mode=function(e,t){return o.fetch&&t?"fetch":o.mozchunkedarraybuffer?"moz-chunked-arraybuffer":o.msstream?"ms-stream":o.arraybuffer&&e?"arraybuffer":o.vbArray&&e?"text:vbarray":"text"}(t,n),r.on("finish",function(){r._onFinish()})};a(l,u.Writable),l.prototype.setHeader=function(e,t){var r=e.toLowerCase();-1===d.indexOf(r)&&(this._headers[r]={name:e,value:t})},l.prototype.getHeader=function(e){var t=this._headers[e.toLowerCase()];return t?t.value:null},l.prototype.removeHeader=function(e){delete this._headers[e.toLowerCase()]},l.prototype._onFinish=function(){var e=this;if(!e._destroyed){var t=e._opts,a=e._headers,s=null;"GET"!==t.method&&"HEAD"!==t.method&&(s=o.arraybuffer?c(i.concat(e._body)):o.blobConstructor?new n.Blob(e._body.map(function(e){return c(e)}),{type:(a["content-type"]||{}).value||""}):i.concat(e._body).toString());var u=[];if(Object.keys(a).forEach(function(e){var t=a[e].name,r=a[e].value;Array.isArray(r)?r.forEach(function(e){u.push([t,e])}):u.push([t,r])}),"fetch"===e._mode){var f=null;if(o.abortController){var l=new AbortController;f=l.signal,e._fetchAbortController=l,"requestTimeout"in t&&0!==t.requestTimeout&&n.setTimeout(function(){e.emit("requestTimeout"),e._fetchAbortController&&e._fetchAbortController.abort()},t.requestTimeout)}n.fetch(e._opts.url,{method:e._opts.method,headers:u,body:s||void 0,mode:"cors",credentials:t.withCredentials?"include":"same-origin",signal:f}).then(function(t){e._fetchResponse=t,e._connect()},function(t){e.emit("error",t)})}else{var d=e._xhr=new n.XMLHttpRequest;try{d.open(e._opts.method,e._opts.url,!0)}catch(t){return void r.nextTick(function(){e.emit("error",t)})}"responseType"in d&&(d.responseType=e._mode.split(":")[0]),"withCredentials"in d&&(d.withCredentials=!!t.withCredentials),"text"===e._mode&&"overrideMimeType"in d&&d.overrideMimeType("text/plain; charset=x-user-defined"),"requestTimeout"in t&&(d.timeout=t.requestTimeout,d.ontimeout=function(){e.emit("requestTimeout")}),u.forEach(function(e){d.setRequestHeader(e[0],e[1])}),e._response=null,d.onreadystatechange=function(){switch(d.readyState){case h.LOADING:case h.DONE:e._onXHRProgress()}},"moz-chunked-arraybuffer"===e._mode&&(d.onprogress=function(){e._onXHRProgress()}),d.onerror=function(){e._destroyed||e.emit("error",new Error("XHR error"))};try{d.send(s)}catch(t){return void r.nextTick(function(){e.emit("error",t)})}}}},l.prototype._onXHRProgress=function(){(function(e){try{var t=e.status;return null!==t&&0!==t}catch(e){return!1}})(this._xhr)&&!this._destroyed&&(this._response||this._connect(),this._response._onXHRProgress())},l.prototype._connect=function(){var e=this;e._destroyed||(e._response=new f(e._xhr,e._fetchResponse,e._mode),e._response.on("error",function(t){e.emit("error",t)}),e.emit("response",e._response))},l.prototype._write=function(e,t,r){this._body.push(e),r()},l.prototype.abort=l.prototype.destroy=function(){this._destroyed=!0,this._response&&(this._response._destroyed=!0),this._xhr?this._xhr.abort():this._fetchAbortController&&this._fetchAbortController.abort()},l.prototype.end=function(e,t,r){"function"==typeof e&&(r=e,e=void 0),u.Writable.prototype.end.call(this,e,t,r)},l.prototype.flushHeaders=function(){},l.prototype.setTimeout=function(){},l.prototype.setNoDelay=function(){},l.prototype.setSocketKeepAlive=function(){};var d=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","user-agent","via"]}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"./capability":313,"./response":315,_process:257,buffer:84,inherits:180,"readable-stream":285,"to-arraybuffer":323}],315:[function(e,t,r){(function(t,n,i){var o=e("./capability"),a=e("inherits"),s=e("readable-stream"),u=r.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},c=r.IncomingMessage=function(e,r,n){var a=this;if(s.Readable.call(a),a._mode=n,a.headers={},a.rawHeaders=[],a.trailers={},a.rawTrailers=[],a.on("end",function(){t.nextTick(function(){a.emit("close")})}),"fetch"===n){if(a._fetchResponse=r,a.url=r.url,a.statusCode=r.status,a.statusMessage=r.statusText,r.headers.forEach(function(e,t){a.headers[t.toLowerCase()]=e,a.rawHeaders.push(t,e)}),o.writableStream){var u=new WritableStream({write:function(e){return new Promise(function(t,r){a._destroyed||(a.push(new i(e))?t():a._resumeFetch=t)})},close:function(){a._destroyed||a.push(null)},abort:function(e){a._destroyed||a.emit("error",e)}});try{return void r.body.pipeTo(u)}catch(e){}}var c=r.body.getReader();!function e(){c.read().then(function(t){a._destroyed||(t.done?a.push(null):(a.push(new i(t.value)),e()))}).catch(function(e){a._destroyed||a.emit("error",e)})}()}else{if(a._xhr=e,a._pos=0,a.url=e.responseURL,a.statusCode=e.status,a.statusMessage=e.statusText,e.getAllResponseHeaders().split(/\r?\n/).forEach(function(e){var t=e.match(/^([^:]+):\s*(.*)/);if(t){var r=t[1].toLowerCase();"set-cookie"===r?(void 0===a.headers[r]&&(a.headers[r]=[]),a.headers[r].push(t[2])):void 0!==a.headers[r]?a.headers[r]+=", "+t[2]:a.headers[r]=t[2],a.rawHeaders.push(t[1],t[2])}}),a._charset="x-user-defined",!o.overrideMimeType){var f=a.rawHeaders["mime-type"];if(f){var h=f.match(/;\s*charset=([^;])(;|$)/);h&&(a._charset=h[1].toLowerCase())}a._charset||(a._charset="utf-8")}}};a(c,s.Readable),c.prototype._read=function(){var e=this._resumeFetch;e&&(this._resumeFetch=null,e())},c.prototype._onXHRProgress=function(){var e=this,t=e._xhr,r=null;switch(e._mode){case"text:vbarray":if(t.readyState!==u.DONE)break;try{r=new n.VBArray(t.responseBody).toArray()}catch(e){}if(null!==r){e.push(new i(r));break}case"text":try{r=t.responseText}catch(t){e._mode="text:vbarray";break}if(r.length>e._pos){var o=r.substr(e._pos);if("x-user-defined"===e._charset){for(var a=new i(o.length),s=0;se._pos&&(e.push(new i(new Uint8Array(c.result.slice(e._pos)))),e._pos=c.result.byteLength)},c.onload=function(){e.push(null)},c.readAsArrayBuffer(r)}e._xhr.readyState===u.DONE&&"ms-stream"!==e._mode&&e.push(null)}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"./capability":313,_process:257,buffer:84,inherits:180,"readable-stream":285}],316:[function(e,t,r){"use strict";t.exports=function(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}},{}],317:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=n.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function o(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(n.isEncoding===i||!i(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=u,this.end=c,t=4;break;case"utf8":this.fillLast=s,t=4;break;case"base64":this.text=f,this.end=h,t=3;break;default:return this.write=l,void(this.end=d)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(t)}function a(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:-1}function s(e){var t=this.lastTotal-this.lastNeed,r=function(e,t,r){if(128!=(192&t[0]))return e.lastNeed=0,"�".repeat(r);if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�".repeat(r+1);if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�".repeat(r+2)}}(this,e,t);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function u(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function c(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function f(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function h(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function l(e){return e.toString(this.encoding)}function d(e){return e&&e.length?this.write(e):""}r.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0)return i>0&&(e.lastNeed=i-1),i;if(--n=0)return i>0&&(e.lastNeed=i-2),i;if(--n=0)return i>0&&(2===i?i=0:e.lastNeed=i-3),i;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)},o.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},{"safe-buffer":290}],318:[function(e,t,r){var n=e("is-hex-prefixed");t.exports=function(e){return"string"!=typeof e?e:n(e)?e.slice(2):e}},{"is-hex-prefixed":185}],319:[function(e,t,r){var n=function(){throw"This swarm.js function isn't available on the browser."},i={readFile:n},o={download:n,safeDownloadArchived:n,directoryTree:n},a={platform:n,arch:n},s={join:n,slice:n},u={spawn:n},c={lookup:n},f=e("xhr-request-promise"),h=e("eth-lib/lib/bytes"),l=e("./swarm-hash.js"),d=e("./pick.js"),p=e("./swarm");t.exports=p({fsp:i,files:o,os:a,path:s,child_process:u,defaultArchives:{},mimetype:c,request:f,downloadUrl:null,bytes:h,hash:l,pick:d})},{"./pick.js":320,"./swarm":322,"./swarm-hash.js":321,"eth-lib/lib/bytes":133,"xhr-request-promise":411}],320:[function(e,t,r){var n=function(e){return function(){return new Promise(function(t,r){var n=function(r){var n={},i=r.target.files.length,o=0;[].map.call(r.target.files,function(r){var a=new FileReader;a.onload=function(a){var s=new Uint8Array(a.target.result);if("directory"===e){var u=r.webkitRelativePath;n[u.slice(u.indexOf("/")+1)]={type:"text/plain",data:s},++o===i&&t(n)}else if("file"===e){var c=r.webkitRelativePath;t({type:mimetype.lookup(c),data:s})}else t(s)},a.readAsArrayBuffer(r)})},i=void 0;"directory"===e?((i=document.createElement("input")).addEventListener("change",n),i.type="file",i.webkitdirectory=!0,i.mozdirectory=!0,i.msdirectory=!0,i.odirectory=!0,i.directory=!0):((i=document.createElement("input")).addEventListener("change",n),i.type="file");var o=document.createEvent("MouseEvents");o.initEvent("click",!0,!1),i.dispatchEvent(o)})}};t.exports={data:n("data"),file:n("file"),directory:n("directory")}},{}],321:[function(e,t,r){var n=e("eth-lib/lib/hash").keccak256,i=e("eth-lib/lib/bytes"),o=function(e,t){var r=i.reverse(i.pad(6,i.fromNumber(e))),o=i.flatten([r,"0x0000",t]);return n(o).slice(2)};t.exports=function e(t){"string"==typeof t&&"0x"!==t.slice(0,2)?t=i.fromString(t):"string"!=typeof t&&void 0!==t.length&&(t=i.fromUint8Array(t));var r=i.length(t);if(r<=4096)return o(r,t);for(var n=4096;128*n0){var a=i.join(r,o);n.push(g(e)(t[o])(a))}return Promise.all(n).then(function(){return r})})}}},_=function(e){return function(t){return u(e+"/bzzr:/",{body:"string"==typeof t?L(t):t,method:"POST"})}},A=function(e){return function(t){return function(r){return function(n){return function i(o){var a="/"===r[0]?r:"/"+r,s=e+"/bzz:/"+t+a,c={method:"PUT",headers:{"Content-Type":n.type},body:n.data};return u(s,c).then(function(e){if(-1!==e.indexOf("error"))throw e;return e}).catch(function(e){return o>0&&i(o-1)})}(3)}}}},E=function(e){return function(t){return k(e)({"":t})}},x=function(e){return function(r){return t.readFile(r).then(function(t){return E(e)({type:a.lookup(r),data:t})})}},k=function(e){return function(t){return _(e)("{}").then(function(r){return Object.keys(t).reduce(function(r,n){return r.then(function(r){return function(n){return A(e)(n)(r)(t[r])}}(n))},Promise.resolve(r))})}},S=function(e){return function(r){return t.readFile(r).then(_(e))}},M=function(e){return function(n){return function(i){return r.directoryTree(i).then(function(e){return Promise.all(e.map(function(e){return t.readFile(e)})).then(function(t){var r=e.map(function(e){return e.slice(i.length)}),n=e.map(function(e){return a.lookup(e)||"text/plain"});return d(r)(t.map(function(e,t){return{type:n[t],data:e}}))})}).then(function(e){return(t=n?{"":e[n]}:{},function(e){var r={};for(var n in t)r[n]=t[n];for(var i in e)r[i]=e[i];return r})(e);var t}).then(k(e))}}},I=function(e){return function(t){if("data"===t.pick)return l.data().then(_(e));if("file"===t.pick)return l.file().then(E(e));if("directory"===t.pick)return l.directory().then(k(e));if(t.path)switch(t.kind){case"data":return S(e)(t.path);case"file":return x(e)(t.path);case"directory":return M(e)(t.defaultFile)(t.path)}else{if(t.length||"string"==typeof t)return _(e)(t);if(t instanceof Object)return k(e)(t)}return Promise.reject(new Error("Bad arguments"))}},T=function(e){return function(t){return function(r){return C(e)(t).then(function(n){return n?r?w(e)(t)(r):v(e)(t):r?g(e)(t)(r):b(e)(t)})}}},U=function(e,t){var i=n.platform().replace("win32","windows")+"-"+("x64"===n.arch()?"amd64":"386"),o=(t||s)[i],a=c+o.archive+".tar.gz",u=o.archiveMD5,f=o.binaryMD5;return r.safeDownloadArchived(a)(u)(f)(e)},j=function(e){return new Promise(function(t,r){var n=o.spawn,i=function(e){return function(t){return-1!==(""+t).indexOf(e)}},a=e.account,s=e.password,u=e.dataDir,c=e.ensApi,f=e.privateKey,h=0,l=n(e.binPath,["--bzzaccount",a||f,"--datadir",u,"--ens-api",c]),d=function(e){0===h&&i("Passphrase")(e)?setTimeout(function(){h=1,l.stdin.write(s+"\n")},500):i("Swarm http proxy started")(e)&&(h=2,clearTimeout(p),t(l))};l.stdout.on("data",d),l.stderr.on("data",d);var p=setTimeout(function(){return r(new Error("Couldn't start swarm process."))},2e4)})},B=function(e){return new Promise(function(t,r){e.stderr.removeAllListeners("data"),e.stdout.removeAllListeners("data"),e.stdin.removeAllListeners("error"),e.removeAllListeners("error"),e.removeAllListeners("exit"),e.kill("SIGINT");var n=setTimeout(function(){return e.kill("SIGKILL")},8e3);e.once("close",function(){clearTimeout(n),t()})})},P=function(e){return _(e)("test").then(function(e){return"c9a99c7d326dcc6316f32fe2625b311f6dc49a175e6877681ded93137d3569e7"===e}).catch(function(){return!1})},C=function(e){return function(t){return b(e)(t).then(function(e){try{return!!JSON.parse(R(e)).entries}catch(e){return!1}})}},N=function(e){return function(t,r,n,i,o){var a;return void 0!==t&&(a=e(t)),void 0!==r&&(a=e(r)),void 0!==n&&(a=e(n)),void 0!==i&&(a=e(i)),void 0!==o&&(a=e(o)),a}},R=function(e){return f.toString(f.fromUint8Array(e))},L=function(e){return f.toUint8Array(f.fromString(e))},O=function(e){return{download:function(t,r){return T(e)(t)(r)},downloadData:N(b(e)),downloadDataToDisk:N(g(e)),downloadDirectory:N(v(e)),downloadDirectoryToDisk:N(w(e)),downloadEntries:N(y(e)),downloadRoutes:N(m(e)),isAvailable:function(){return P(e)},upload:function(t){return I(e)(t)},uploadData:N(_(e)),uploadFile:N(E(e)),uploadFileFromDisk:N(E(e)),uploadDataFromDisk:N(S(e)),uploadDirectory:N(k(e)),uploadDirectoryFromDisk:N(M(e)),uploadToManifest:N(A(e)),pick:l,hash:h,fromString:L,toString:R}};return{at:O,local:function(e){return function(t){return P("http://localhost:8500").then(function(r){return r?t(O("http://localhost:8500")).then(function(){}):U(e.binPath,e.archives).onData(function(t){return(e.onProgress||function(){})(t.length)}).then(function(){return j(e)}).then(function(e){return t(O("http://localhost:8500")).then(function(){return e})}).then(B)})}},download:T,downloadBinary:U,downloadData:b,downloadDataToDisk:g,downloadDirectory:v,downloadDirectoryToDisk:w,downloadEntries:y,downloadRoutes:m,isAvailable:P,startProcess:j,stopProcess:B,upload:I,uploadData:_,uploadDataFromDisk:S,uploadFile:E,uploadFileFromDisk:x,uploadDirectory:k,uploadDirectoryFromDisk:M,uploadToManifest:A,pick:l,hash:h,fromString:L,toString:R}}},{}],323:[function(e,t,r){var n=e("buffer").Buffer;t.exports=function(e){if(e instanceof Uint8Array){if(0===e.byteOffset&&e.byteLength===e.buffer.byteLength)return e.buffer;if("function"==typeof e.buffer.slice)return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}if(n.isBuffer(e)){for(var t=new Uint8Array(e.length),r=e.length,i=0;i=0&&t<=A};function k(e){return function(t,r,n,i){r=m(r,i,4);var o=!x(t)&&y.keys(t),a=(o||t).length,s=e>0?0:a-1;return arguments.length<3&&(n=t[o?o[s]:s],s+=e),function(t,r,n,i,o,a){for(;o>=0&&o=0},y.invoke=function(e,t){var r=u.call(arguments,2),n=y.isFunction(t);return y.map(e,function(e){var i=n?t:e[t];return null==i?i:i.apply(e,r)})},y.pluck=function(e,t){return y.map(e,y.property(t))},y.where=function(e,t){return y.filter(e,y.matcher(t))},y.findWhere=function(e,t){return y.find(e,y.matcher(t))},y.max=function(e,t,r){var n,i,o=-1/0,a=-1/0;if(null==t&&null!=e)for(var s=0,u=(e=x(e)?e:y.values(e)).length;so&&(o=n);else t=v(t,r),y.each(e,function(e,r,n){((i=t(e,r,n))>a||i===-1/0&&o===-1/0)&&(o=e,a=i)});return o},y.min=function(e,t,r){var n,i,o=1/0,a=1/0;if(null==t&&null!=e)for(var s=0,u=(e=x(e)?e:y.values(e)).length;sn||void 0===r)return 1;if(r0?0:i-1;o>=0&&o0?a=o>=0?o:Math.max(o+s,a):s=o>=0?Math.min(o+1,s):o+s+1;else if(r&&o&&s)return n[o=r(n,i)]===i?o:-1;if(i!=i)return(o=t(u.call(n,a,s),y.isNaN))>=0?o+a:-1;for(o=e>0?a:s-1;o>=0&&ot?(a&&(clearTimeout(a),a=null),s=c,o=e.apply(n,i),a||(n=i=null)):a||!1===r.trailing||(a=setTimeout(u,f)),o}},y.debounce=function(e,t,r){var n,i,o,a,s,u=function(){var c=y.now()-a;c=0?n=setTimeout(u,t-c):(n=null,r||(s=e.apply(o,i),n||(o=i=null)))};return function(){o=this,i=arguments,a=y.now();var c=r&&!n;return n||(n=setTimeout(u,t)),c&&(s=e.apply(o,i),o=i=null),s}},y.wrap=function(e,t){return y.partial(t,e)},y.negate=function(e){return function(){return!e.apply(this,arguments)}},y.compose=function(){var e=arguments,t=e.length-1;return function(){for(var r=t,n=e[t].apply(this,arguments);r--;)n=e[r].call(this,n);return n}},y.after=function(e,t){return function(){if(--e<1)return t.apply(this,arguments)}},y.before=function(e,t){var r;return function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=null),r}},y.once=y.partial(y.before,2);var j=!{toString:null}.propertyIsEnumerable("toString"),B=["valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"];function P(e,t){var r=B.length,n=e.constructor,i=y.isFunction(n)&&n.prototype||o,a="constructor";for(y.has(e,a)&&!y.contains(t,a)&&t.push(a);r--;)(a=B[r])in e&&e[a]!==i[a]&&!y.contains(t,a)&&t.push(a)}y.keys=function(e){if(!y.isObject(e))return[];if(l)return l(e);var t=[];for(var r in e)y.has(e,r)&&t.push(r);return j&&P(e,t),t},y.allKeys=function(e){if(!y.isObject(e))return[];var t=[];for(var r in e)t.push(r);return j&&P(e,t),t},y.values=function(e){for(var t=y.keys(e),r=t.length,n=Array(r),i=0;i":">",'"':""","'":"'","`":"`"},R=y.invert(N),L=function(e){var t=function(t){return e[t]},r="(?:"+y.keys(e).join("|")+")",n=RegExp(r),i=RegExp(r,"g");return function(e){return e=null==e?"":""+e,n.test(e)?e.replace(i,t):e}};y.escape=L(N),y.unescape=L(R),y.result=function(e,t,r){var n=null==e?void 0:e[t];return void 0===n&&(n=r),y.isFunction(n)?n.call(e):n};var O=0;y.uniqueId=function(e){var t=++O+"";return e?e+t:t},y.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var D=/(.)^/,F={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},q=/\\|'|\r|\n|\u2028|\u2029/g,H=function(e){return"\\"+F[e]};y.template=function(e,t,r){!t&&r&&(t=r),t=y.defaults({},t,y.templateSettings);var n=RegExp([(t.escape||D).source,(t.interpolate||D).source,(t.evaluate||D).source].join("|")+"|$","g"),i=0,o="__p+='";e.replace(n,function(t,r,n,a,s){return o+=e.slice(i,s).replace(q,H),i=s+t.length,r?o+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'":n?o+="'+\n((__t=("+n+"))==null?'':__t)+\n'":a&&(o+="';\n"+a+"\n__p+='"),t}),o+="';\n",t.variable||(o="with(obj||{}){\n"+o+"}\n"),o="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+o+"return __p;\n";try{var a=new Function(t.variable||"obj","_",o)}catch(e){throw e.source=o,e}var s=function(e){return a.call(this,e,y)},u=t.variable||"obj";return s.source="function("+u+"){\n"+o+"}",s},y.chain=function(e){var t=y(e);return t._chain=!0,t};var z=function(e,t){return e._chain?y(t).chain():t};y.mixin=function(e){y.each(y.functions(e),function(t){var r=y[t]=e[t];y.prototype[t]=function(){var e=[this._wrapped];return s.apply(e,arguments),z(this,r.apply(y,e))}})},y.mixin(y),y.each(["pop","push","reverse","shift","sort","splice","unshift"],function(e){var t=i[e];y.prototype[e]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!==e&&"splice"!==e||0!==r.length||delete r[0],z(this,r)}}),y.each(["concat","join","slice"],function(e){var t=i[e];y.prototype[e]=function(){return z(this,t.apply(this._wrapped,arguments))}}),y.prototype.value=function(){return this._wrapped},y.prototype.valueOf=y.prototype.toJSON=y.prototype.value,y.prototype.toString=function(){return""+this._wrapped},"function"==typeof define&&define.amd&&define("underscore",[],function(){return y})}).call(this)},{}],326:[function(e,t,r){t.exports=function(e,t){if(t){t=(t=t.trim().replace(/^(\?|#|&)/,""))?"?"+t:t;var r=e.split(/[\?\#]/),n=r[0];t&&/\:\/\/[^\/]*$/.test(n)&&(n+="/");var i=e.match(/(\#.*)$/);e=n+t,i&&(e+=i[0])}return e}},{}],327:[function(e,t,r){"use strict";var n=e("punycode"),i=e("./util");function o(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}r.parse=g,r.resolve=function(e,t){return g(e,!1,!0).resolve(t)},r.resolveObject=function(e,t){return e?g(e,!1,!0).resolveObject(t):t},r.format=function(e){i.isString(e)&&(e=g(e));return e instanceof o?e.format():o.prototype.format.call(e)},r.Url=o;var a=/^([a-z0-9.+-]+:)/i,s=/:[0-9]*$/,u=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,c=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),f=["'"].concat(c),h=["%","/","?",";","#"].concat(f),l=["/","?","#"],d=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,b={javascript:!0,"javascript:":!0},y={javascript:!0,"javascript:":!0},m={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},v=e("querystring");function g(e,t,r){if(e&&i.isObject(e)&&e instanceof o)return e;var n=new o;return n.parse(e,t,r),n}o.prototype.parse=function(e,t,r){if(!i.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var o=e.indexOf("?"),s=-1!==o&&o127?P+="x":P+=B[C];if(!P.match(d)){var R=U.slice(0,M),L=U.slice(M+1),O=B.match(p);O&&(R.push(O[1]),L.unshift(O[2])),L.length&&(g="/"+L.join(".")+g),this.hostname=R.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),T||(this.hostname=n.toASCII(this.hostname));var D=this.port?":"+this.port:"",F=this.hostname||"";this.host=F+D,this.href+=this.host,T&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==g[0]&&(g="/"+g))}if(!b[A])for(M=0,j=f.length;M0)&&r.host.split("@"))&&(r.auth=T.shift(),r.host=r.hostname=T.shift());return r.search=e.search,r.query=e.query,i.isNull(r.pathname)&&i.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!E.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var k=E.slice(-1)[0],S=(r.host||e.host||E.length>1)&&("."===k||".."===k)||""===k,M=0,I=E.length;I>=0;I--)"."===(k=E[I])?E.splice(I,1):".."===k?(E.splice(I,1),M++):M&&(E.splice(I,1),M--);if(!_&&!A)for(;M--;M)E.unshift("..");!_||""===E[0]||E[0]&&"/"===E[0].charAt(0)||E.unshift(""),S&&"/"!==E.join("/").substr(-1)&&E.push("");var T,U=""===E[0]||E[0]&&"/"===E[0].charAt(0);x&&(r.hostname=r.host=U?"":E.length?E.shift():"",(T=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@"))&&(r.auth=T.shift(),r.host=r.hostname=T.shift()));return(_=_||r.host&&E.length)&&!U&&E.unshift(""),E.length?r.pathname=E.join("/"):(r.pathname=null,r.path=null),i.isNull(r.pathname)&&i.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=e.auth||r.auth,r.slashes=r.slashes||e.slashes,r.href=r.format(),r},o.prototype.parseHost=function(){var e=this.host,t=s.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{"./util":328,punycode:265,querystring:269}],328:[function(e,t,r){"use strict";t.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},{}],329:[function(e,t,r){(function(e){!function(n){var i="object"==typeof r&&r,o="object"==typeof t&&t&&t.exports==i&&t,a="object"==typeof e&&e;a.global!==a&&a.window!==a||(n=a);var s,u,c,f=String.fromCharCode;function h(e){for(var t,r,n=[],i=0,o=e.length;i=55296&&t<=56319&&i=55296&&e<=57343)throw Error("Lone surrogate U+"+e.toString(16).toUpperCase()+" is not a scalar value")}function d(e,t){return f(e>>t&63|128)}function p(e){if(0==(4294967168&e))return f(e);var t="";return 0==(4294965248&e)?t=f(e>>6&31|192):0==(4294901760&e)?(l(e),t=f(e>>12&15|224),t+=d(e,6)):0==(4292870144&e)&&(t=f(e>>18&7|240),t+=d(e,12),t+=d(e,6)),t+=f(63&e|128)}function b(){if(c>=u)throw Error("Invalid byte index");var e=255&s[c];if(c++,128==(192&e))return 63&e;throw Error("Invalid continuation byte")}function y(){var e,t;if(c>u)throw Error("Invalid byte index");if(c==u)return!1;if(e=255&s[c],c++,0==(128&e))return e;if(192==(224&e)){if((t=(31&e)<<6|b())>=128)return t;throw Error("Invalid continuation byte")}if(224==(240&e)){if((t=(15&e)<<12|b()<<6|b())>=2048)return l(t),t;throw Error("Invalid continuation byte")}if(240==(248&e)&&(t=(15&e)<<18|b()<<12|b()<<6|b())>=65536&&t<=1114111)return t;throw Error("Invalid UTF-8 detected")}var m={version:"2.0.0",encode:function(e){for(var t=h(e),r=t.length,n=-1,i="";++n65535&&(i+=f((t-=65536)>>>10&1023|55296),t=56320|1023&t),i+=f(t);return i}(r)}};if("function"==typeof define&&"object"==typeof define.amd&&define.amd)define(function(){return m});else if(i&&!i.nodeType)if(o)o.exports=m;else{var v={}.hasOwnProperty;for(var g in m)v.call(m,g)&&(i[g]=m[g])}else n.utf8=m}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],330:[function(e,t,r){(function(e){function r(t){try{if(!e.localStorage)return!1}catch(e){return!1}var r=e.localStorage[t];return null!=r&&"true"===String(r).toLowerCase()}t.exports=function(e,t){if(r("noDeprecation"))return e;var n=!1;return function(){if(!n){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],331:[function(e,t,r){arguments[4][180][0].apply(r,arguments)},{dup:180}],332:[function(e,t,r){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],333:[function(e,t,r){(function(t,n){var i=/%[sdj%]/g;r.format=function(e){if(!m(e)){for(var t=[],r=0;r=o)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(e){return"[Circular]"}default:return e}}),u=n[r];r=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),p(t)?n.showHidden=t:t&&r._extend(n,t),v(n.showHidden)&&(n.showHidden=!1),v(n.depth)&&(n.depth=2),v(n.colors)&&(n.colors=!1),v(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=u),f(n,e,n.depth)}function u(e,t){var r=s.styles[t];return r?"["+s.colors[r][0]+"m"+e+"["+s.colors[r][1]+"m":e}function c(e,t){return e}function f(e,t,n){if(e.customInspect&&t&&E(t.inspect)&&t.inspect!==r.inspect&&(!t.constructor||t.constructor.prototype!==t)){var i=t.inspect(n,e);return m(i)||(i=f(e,i,n)),i}var o=function(e,t){if(v(t))return e.stylize("undefined","undefined");if(m(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(y(t))return e.stylize(""+t,"number");if(p(t))return e.stylize(""+t,"boolean");if(b(t))return e.stylize("null","null")}(e,t);if(o)return o;var a=Object.keys(t),s=function(e){var t={};return e.forEach(function(e,r){t[e]=!0}),t}(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(t)),A(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return h(t);if(0===a.length){if(E(t)){var u=t.name?": "+t.name:"";return e.stylize("[Function"+u+"]","special")}if(g(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(_(t))return e.stylize(Date.prototype.toString.call(t),"date");if(A(t))return h(t)}var c,w="",x=!1,k=["{","}"];(d(t)&&(x=!0,k=["[","]"]),E(t))&&(w=" [Function"+(t.name?": "+t.name:"")+"]");return g(t)&&(w=" "+RegExp.prototype.toString.call(t)),_(t)&&(w=" "+Date.prototype.toUTCString.call(t)),A(t)&&(w=" "+h(t)),0!==a.length||x&&0!=t.length?n<0?g(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),c=x?function(e,t,r,n,i){for(var o=[],a=0,s=t.length;a=0&&0,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60)return r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1];return r[0]+t+" "+e.join(", ")+" "+r[1]}(c,w,k)):k[0]+w+k[1]}function h(e){return"["+Error.prototype.toString.call(e)+"]"}function l(e,t,r,n,i,o){var a,s,u;if((u=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]}).get?s=u.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):u.set&&(s=e.stylize("[Setter]","special")),M(n,i)||(a="["+i+"]"),s||(e.seen.indexOf(u.value)<0?(s=b(r)?f(e,u.value,null):f(e,u.value,r-1)).indexOf("\n")>-1&&(s=o?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n")):s=e.stylize("[Circular]","special")),v(a)){if(o&&i.match(/^\d+$/))return s;(a=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function d(e){return Array.isArray(e)}function p(e){return"boolean"==typeof e}function b(e){return null===e}function y(e){return"number"==typeof e}function m(e){return"string"==typeof e}function v(e){return void 0===e}function g(e){return w(e)&&"[object RegExp]"===x(e)}function w(e){return"object"==typeof e&&null!==e}function _(e){return w(e)&&"[object Date]"===x(e)}function A(e){return w(e)&&("[object Error]"===x(e)||e instanceof Error)}function E(e){return"function"==typeof e}function x(e){return Object.prototype.toString.call(e)}function k(e){return e<10?"0"+e.toString(10):e.toString(10)}r.debuglog=function(e){if(v(o)&&(o=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!a[e])if(new RegExp("\\b"+e+"\\b","i").test(o)){var n=t.pid;a[e]=function(){var t=r.format.apply(r,arguments);console.error("%s %d: %s",e,n,t)}}else a[e]=function(){};return a[e]},r.inspect=s,s.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},s.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},r.isArray=d,r.isBoolean=p,r.isNull=b,r.isNullOrUndefined=function(e){return null==e},r.isNumber=y,r.isString=m,r.isSymbol=function(e){return"symbol"==typeof e},r.isUndefined=v,r.isRegExp=g,r.isObject=w,r.isDate=_,r.isError=A,r.isFunction=E,r.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},r.isBuffer=e("./support/isBuffer");var S=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function M(e,t){return Object.prototype.hasOwnProperty.call(e,t)}r.log=function(){var e,t;console.log("%s - %s",(e=new Date,t=[k(e.getHours()),k(e.getMinutes()),k(e.getSeconds())].join(":"),[e.getDate(),S[e.getMonth()],t].join(" ")),r.format.apply(r,arguments))},r.inherits=e("inherits"),r._extend=function(e,t){if(!t||!w(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":332,_process:257,inherits:331}],334:[function(require,module,exports){var indexOf=require("indexof"),Object_keys=function(e){if(Object.keys)return Object.keys(e);var t=[];for(var r in e)t.push(r);return t},forEach=function(e,t){if(e.forEach)return e.forEach(t);for(var r=0;r1?(e[r[0]]=e[r[0]]||{},e[r[0]][r[1]]=t):e[r[0]]=t},c.prototype.getCall=function(e){return n.isFunction(this.call)?this.call(e):this.call},c.prototype.extractCallback=function(e){if(n.isFunction(e[e.length-1]))return e.pop()},c.prototype.validateArgs=function(e){if(e.length!==this.params)throw i.InvalidNumberOfParams(e.length,this.params,this.name)},c.prototype.formatInput=function(e){var t=this;return this.inputFormatter?this.inputFormatter.map(function(r,n){return r?r.call(t,e[n]):e[n]}):e},c.prototype.formatOutput=function(e){var t=this;return n.isArray(e)?e.map(function(e){return t.outputFormatter&&e?t.outputFormatter(e):e}):this.outputFormatter&&e?this.outputFormatter(e):e},c.prototype.toPayload=function(e){var t=this.getCall(e),r=this.extractCallback(e),n=this.formatInput(e);this.validateArgs(n);var i={method:t,params:n,callback:r};return this.transformPayload&&(i=this.transformPayload(i)),i},c.prototype._confirmTransaction=function(e,t,r){var i=this,f=!1,h=!0,l=0,d=0,p=null,b="",y=n.isObject(r.params[0])&&r.params[0].gas?r.params[0].gas:null,m=n.isObject(r.params[0])&&r.params[0].data&&r.params[0].from&&!r.params[0].to,v=[new c({name:"getTransactionReceipt",call:"eth_getTransactionReceipt",params:1,inputFormatter:[null],outputFormatter:o.outputTransactionReceiptFormatter}),new c({name:"getCode",call:"eth_getCode",params:2,inputFormatter:[o.inputAddressFormatter,o.inputDefaultBlockNumberFormatter]}),new u({name:"subscribe",type:"eth",subscriptions:{newBlockHeaders:{subscriptionName:"newHeads",params:0,outputFormatter:o.outputBlockFormatter}}})],g={};n.each(v,function(e){e.attachToObject(g),e.requestManager=i.requestManager});var w=function(r,n,o,u,c){if(!o)return c||(c={unsubscribe:function(){clearInterval(p)}}),(r?s.resolve(r):g.getTransactionReceipt(t)).catch(function(t){c.unsubscribe(),f=!0,a._fireError({message:"Failed to check for transaction receipt:",data:t},e.eventEmitter,e.reject)}).then(function(t){if(!t||!t.blockHash)throw new Error("Receipt missing or blockHash null");return i.extraFormatters&&i.extraFormatters.receiptFormatter&&(t=i.extraFormatters.receiptFormatter(t)),e.eventEmitter.listeners("confirmation").length>0&&(void 0!==r&&0===d||e.eventEmitter.emit("confirmation",d,t),h=!1,25===++d&&(c.unsubscribe(),e.eventEmitter.removeAllListeners())),t}).then(function(t){if(m&&!f){if(!t.contractAddress)return h&&(c.unsubscribe(),f=!0),void a._fireError(new Error("The transaction receipt didn't contain a contract address."),e.eventEmitter,e.reject);g.getCode(t.contractAddress,function(r,n){n&&(n.length>2?(e.eventEmitter.emit("receipt",t),i.extraFormatters&&i.extraFormatters.contractDeployFormatter?e.resolve(i.extraFormatters.contractDeployFormatter(t)):e.resolve(t),h&&e.eventEmitter.removeAllListeners()):a._fireError(new Error("The contract code couldn't be stored, please check your gas limit."),e.eventEmitter,e.reject),h&&c.unsubscribe(),f=!0)})}return t}).then(function(t){m||f||(t.outOfGas||y&&y===t.gasUsed||!0!==t.status&&"0x1"!==t.status&&void 0!==t.status?(b=JSON.stringify(t,null,2),!1===t.status||"0x0"===t.status?a._fireError(new Error("Transaction has been reverted by the EVM:\n"+b),e.eventEmitter,e.reject):a._fireError(new Error("Transaction ran out of gas. Please provide more gas:\n"+b),e.eventEmitter,e.reject)):(e.eventEmitter.emit("receipt",t),e.resolve(t),h&&e.eventEmitter.removeAllListeners()),h&&c.unsubscribe(),f=!0)}).catch(function(){l++,n?l-1>=750&&(c.unsubscribe(),f=!0,a._fireError(new Error("Transaction was not mined within750 seconds, please make sure your transaction was properly sent. Be aware that it might still be mined!"),e.eventEmitter,e.reject)):l-1>=50&&(c.unsubscribe(),f=!0,a._fireError(new Error("Transaction was not mined within 50 blocks, please make sure your transaction was properly sent. Be aware that it might still be mined!"),e.eventEmitter,e.reject))});c.unsubscribe(),f=!0,a._fireError({message:"Failed to subscribe to new newBlockHeaders to confirm the transaction receipts.",data:o},e.eventEmitter,e.reject)},_=function(e){n.isFunction(this.requestManager.provider.on)?g.subscribe("newBlockHeaders",w.bind(null,e,!1)):p=setInterval(w.bind(null,e,!0),1e3)}.bind(this);g.getTransactionReceipt(t).then(function(t){t&&t.blockHash?(e.eventEmitter.listeners("confirmation").length>0&&_(t),w(t,!1)):f||_()}).catch(function(){f||_()})};var f=function(e,t){return n.isNumber(e)?t.wallet[e]:n.isObject(e)&&e.address&&e.privateKey?e:t.wallet[e.toLowerCase()]};c.prototype.buildCall=function(){var e=this,t="eth_sendTransaction"===e.call||"eth_sendRawTransaction"===e.call,r=function(){var r=s(!t),i=e.toPayload(Array.prototype.slice.call(arguments)),o=function(n,o){try{o=e.formatOutput(o)}catch(e){n=e}if(o instanceof Error&&(n=o),n)return n.error&&(n=n.error),a._fireError(n,r.eventEmitter,r.reject,i.callback);i.callback&&i.callback(null,o),t?(r.eventEmitter.emit("transactionHash",o),e._confirmTransaction(r,o,i)):n||r.resolve(o)},u=function(t){var r=n.extend({},i,{method:"eth_sendRawTransaction",params:[t.rawTransaction]});e.requestManager.send(r,o)},h=function(e,t){var i;if(t&&t.accounts&&t.accounts.wallet&&t.accounts.wallet.length)if("eth_sendTransaction"===e.method){var a=e.params[0];if((i=f(n.isObject(a)?a.from:null,t.accounts))&&i.privateKey)return t.accounts.signTransaction(n.omit(a,"from"),i.privateKey).then(u)}else if("eth_sign"===e.method){var s=e.params[1];if((i=f(e.params[0],t.accounts))&&i.privateKey){var c=t.accounts.sign(s,i.privateKey);return e.callback&&e.callback(null,c.signature),void r.resolve(c.signature)}}return t.requestManager.send(e,o)};t&&n.isObject(i.params[0])&&void 0===i.params[0].gasPrice?new c({name:"getGasPrice",call:"eth_gasPrice",params:0}).createFunction(e.requestManager)(function(t,r){r&&(i.params[0].gasPrice=r),h(i,e)}):h(i,e);return r.eventEmitter};return r.method=e,r.request=this.request.bind(this),r},c.prototype.request=function(){var e=this.toPayload(Array.prototype.slice.call(arguments));return e.format=this.formatOutput.bind(this),e},t.exports=c},{underscore:325,"web3-core-helpers":338,"web3-core-promievent":340,"web3-core-subscriptions":345,"web3-utils":403}],340:[function(e,t,r){"use strict";var n=e("eventemitter3"),i=e("any-promise"),o=function(e){var t,r,o=new i(function(){t=arguments[0],r=arguments[1]});if(e)return{resolve:t,reject:r,eventEmitter:o};var a=new n;return o._events=a._events,o.emit=a.emit,o.on=a.on,o.once=a.once,o.off=a.off,o.listeners=a.listeners,o.addListener=a.addListener,o.removeListener=a.removeListener,o.removeAllListeners=a.removeAllListeners,{resolve:t,reject:r,eventEmitter:o}};o.resolve=function(e){var t=o(!0);return t.resolve(e),t.eventEmitter},t.exports=o},{"any-promise":2,eventemitter3:156}],341:[function(e,t,r){"use strict";var n=e("./jsonrpc"),i=e("web3-core-helpers").errors,o=function(e){this.requestManager=e,this.requests=[]};o.prototype.add=function(e){this.requests.push(e)},o.prototype.execute=function(){var e=this.requests;this.requestManager.sendBatch(e,function(t,r){r=r||[],e.map(function(e,t){return r[t]||{}}).forEach(function(t,r){if(e[r].callback){if(t&&t.error)return e[r].callback(i.ErrorResponse(t));if(!n.isValidResponse(t))return e[r].callback(i.InvalidResponse(t));try{e[r].callback(null,e[r].format?e[r].format(t.result):t.result)}catch(t){e[r].callback(t)}}})})},t.exports=o},{"./jsonrpc":344,"web3-core-helpers":338}],342:[function(e,t,r){"use strict";var n=null,i=window;void 0!==i.ethereumProvider?n=i.ethereumProvider:void 0!==i.web3&&i.web3.currentProvider&&(i.web3.currentProvider.sendAsync&&(i.web3.currentProvider.send=i.web3.currentProvider.sendAsync,delete i.web3.currentProvider.sendAsync),!i.web3.currentProvider.on&&i.web3.currentProvider.connection&&"ipcProviderWrapper"===i.web3.currentProvider.connection.constructor.name&&(i.web3.currentProvider.on=function(e,t){if("function"!=typeof t)throw new Error("The second parameter callback must be a function.");switch(e){case"data":this.connection.on("data",function(e){var r="";e=e.toString();try{r=JSON.parse(e)}catch(r){return t(new Error("Couldn't parse response data"+e))}r.id||-1===r.method.indexOf("_subscription")||t(null,r)});break;default:this.connection.on(e,t)}}),n=i.web3.currentProvider),t.exports=n},{}],343:[function(e,t,r){"use strict";var n=e("underscore"),i=e("web3-core-helpers").errors,o=e("./jsonrpc.js"),a=e("./batch.js"),s=e("./givenProvider.js"),u=function e(t){this.provider=null,this.providers=e.providers,this.setProvider(t),this.subscriptions={}};u.givenProvider=s,u.providers={WebsocketProvider:e("web3-providers-ws"),HttpProvider:e("web3-providers-http"),IpcProvider:e("web3-providers-ipc")},u.prototype.setProvider=function(e,t){var r=this;if(e&&"string"==typeof e&&this.providers)if(/^http(s)?:\/\//i.test(e))e=new this.providers.HttpProvider(e);else if(/^ws(s)?:\/\//i.test(e))e=new this.providers.WebsocketProvider(e);else if(e&&"object"==typeof t&&"function"==typeof t.connect)e=new this.providers.IpcProvider(e,t);else if(e)throw new Error("Can't autodetect provider for \""+e+'"');this.provider&&this.provider.connected&&this.clearSubscriptions(),this.provider=e||null,this.provider&&this.provider.on&&this.provider.on("data",function(e,t){(e=e||t).method&&r.subscriptions[e.params.subscription]&&r.subscriptions[e.params.subscription].callback&&r.subscriptions[e.params.subscription].callback(null,e.params.result)})},u.prototype.send=function(e,t){if(t=t||function(){},!this.provider)return t(i.InvalidProvider());var r=o.toPayload(e.method,e.params);this.provider[this.provider.sendAsync?"sendAsync":"send"](r,function(e,n){return n&&n.id&&r.id!==n.id?t(new Error('Wrong response id "'+n.id+'" (expected: "'+r.id+'") in '+JSON.stringify(r))):e?t(e):n&&n.error?t(i.ErrorResponse(n)):o.isValidResponse(n)?void t(null,n.result):t(i.InvalidResponse(n))})},u.prototype.sendBatch=function(e,t){if(!this.provider)return t(i.InvalidProvider());var r=o.toBatchPayload(e);this.provider[this.provider.sendAsync?"sendAsync":"send"](r,function(e,r){return e?t(e):n.isArray(r)?void t(null,r):t(i.InvalidResponse(r))})},u.prototype.addSubscription=function(e,t,r,n){if(!this.provider.on)throw new Error("The provider doesn't support subscriptions: "+this.provider.constructor.name);this.subscriptions[e]={callback:n,type:r,name:t}},u.prototype.removeSubscription=function(e,t){this.subscriptions[e]&&(this.send({method:this.subscriptions[e].type+"_unsubscribe",params:[e]},t),delete this.subscriptions[e])},u.prototype.clearSubscriptions=function(e){var t=this;Object.keys(this.subscriptions).forEach(function(r){e&&"syncing"===t.subscriptions[r].name||t.removeSubscription(r)}),this.provider.reset&&this.provider.reset()},t.exports={Manager:u,BatchManager:a}},{"./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(e,t,r){"use strict";var n={messageId:0,toPayload:function(e,t){if(!e)throw new Error('JSONRPC method should be specified for params: "'+JSON.stringify(t)+'"!');return n.messageId++,{jsonrpc:"2.0",id:n.messageId,method:e,params:t||[]}},isValidResponse:function(e){return Array.isArray(e)?e.every(t):t(e);function t(e){return!(!e||e.error||"2.0"!==e.jsonrpc||"number"!=typeof e.id&&"string"!=typeof e.id||void 0===e.result)}},toBatchPayload:function(e){return e.map(function(e){return n.toPayload(e.method,e.params)})}};t.exports=n},{}],345:[function(e,t,r){"use strict";var n=e("./subscription.js"),i=function(e){this.name=e.name,this.type=e.type,this.subscriptions=e.subscriptions||{},this.requestManager=null};i.prototype.setRequestManager=function(e){this.requestManager=e},i.prototype.attachToObject=function(e){var t=this.buildCall(),r=this.name.split(".");r.length>1?(e[r[0]]=e[r[0]]||{},e[r[0]][r[1]]=t):e[r[0]]=t},i.prototype.buildCall=function(){var e=this;return function(){e.subscriptions[arguments[0]]||console.warn("Subscription "+JSON.stringify(arguments[0])+" doesn't exist. Subscribing anyway.");var t=new n({subscription:e.subscriptions[arguments[0]],requestManager:e.requestManager,type:e.type});return t.subscribe.apply(t,arguments)}},t.exports={subscriptions:i,subscription:n}},{"./subscription.js":346}],346:[function(e,t,r){"use strict";var n=e("underscore"),i=e("web3-core-helpers").errors,o=e("eventemitter3");function a(e){o.call(this),this.id=null,this.callback=n.identity,this.arguments=null,this._reconnectIntervalId=null,this.options={subscription:e.subscription,type:e.type,requestManager:e.requestManager}}a.prototype=Object.create(o.prototype),a.prototype.constructor=a,a.prototype._extractCallback=function(e){if(n.isFunction(e[e.length-1]))return e.pop()},a.prototype._validateArgs=function(e){var t=this.options.subscription;if(t||(t={}),t.params||(t.params=0),e.length!==t.params)throw i.InvalidNumberOfParams(e.length,t.params+1,e[0])},a.prototype._formatInput=function(e){var t=this.options.subscription;return t&&t.inputFormatter?t.inputFormatter.map(function(t,r){return t?t(e[r]):e[r]}):e},a.prototype._formatOutput=function(e){var t=this.options.subscription;return t&&t.outputFormatter&&e?t.outputFormatter(e):e},a.prototype._toPayload=function(e){var t=[];if(this.callback=this._extractCallback(e)||n.identity,this.subscriptionMethod||(this.subscriptionMethod=e.shift(),this.options.subscription.subscriptionName&&(this.subscriptionMethod=this.options.subscription.subscriptionName)),this.arguments||(this.arguments=this._formatInput(e),this._validateArgs(this.arguments),e=[]),t.push(this.subscriptionMethod),t=t.concat(this.arguments),e.length)throw new Error("Only a callback is allowed as parameter on an already instantiated subscription.");return{method:this.options.type+"_subscribe",params:t}},a.prototype.unsubscribe=function(e){this.options.requestManager.removeSubscription(this.id,e),this.id=null,this.removeAllListeners(),clearInterval(this._reconnectIntervalId)},a.prototype.subscribe=function(){var e=this,t=Array.prototype.slice.call(arguments),r=this._toPayload(t);if(!r)return this;if(!this.options.requestManager.provider){var i=new Error("No provider set.");return this.callback(i,null,this),this.emit("error",i),this}if(!this.options.requestManager.provider.on){var o=new Error("The current provider doesn't support subscriptions: "+this.options.requestManager.provider.constructor.name);return this.callback(o,null,this),this.emit("error",o),this}return this.id&&this.unsubscribe(),this.options.params=r.params[1],"logs"===r.params[0]&&n.isObject(r.params[1])&&r.params[1].hasOwnProperty("fromBlock")&&isFinite(r.params[1].fromBlock)&&this.options.requestManager.send({method:"eth_getLogs",params:[r.params[1]]},function(t,r){t?(e.callback(t,null,e),e.emit("error",t)):r.forEach(function(t){var r=e._formatOutput(t);e.callback(null,r,e),e.emit("data",r)})}),"object"==typeof r.params[1]&&delete r.params[1].fromBlock,this.options.requestManager.send(r,function(t,i){!t&&i?(e.id=i,e.options.requestManager.addSubscription(e.id,r.params[0],e.options.type,function(t,r){t?(e.options.requestManager.removeSubscription(e.id),e.options.requestManager.provider.once&&(e._reconnectIntervalId=setInterval(function(){e.options.requestManager.provider.reconnect&&e.options.requestManager.provider.reconnect()},500),e.options.requestManager.provider.once("connect",function(){clearInterval(e._reconnectIntervalId),e.subscribe(e.callback)})),e.emit("error",t),e.callback(t,null,e)):(n.isArray(r)||(r=[r]),r.forEach(function(t){var r=e._formatOutput(t);if(n.isFunction(e.options.subscription.subscriptionHandler))return e.options.subscription.subscriptionHandler.call(e,r);e.emit("data",r),e.callback(null,r,e)}))})):(e.callback(t,null,e),e.emit("error",t))}),this},t.exports=a},{eventemitter3:156,underscore:325,"web3-core-helpers":338}],347:[function(e,t,r){"use strict";var n=e("web3-core-helpers").formatters,i=e("web3-core-method"),o=e("web3-utils");t.exports=function(e){var t=function(t){var r;return t.property?(e[t.property]||(e[t.property]={}),r=e[t.property]):r=e,t.methods&&t.methods.forEach(function(t){t instanceof i||(t=new i(t)),t.attachToObject(r),t.setRequestManager(e._requestManager)}),e};return t.formatters=n,t.utils=o,t.Method=i,t}},{"web3-core-helpers":338,"web3-core-method":339,"web3-utils":403}],348:[function(e,t,r){"use strict";var n=e("web3-core-requestmanager"),i=e("./extend.js");t.exports={packageInit:function(e,t){if(t=Array.prototype.slice.call(t),!e)throw new Error('You need to instantiate using the "new" keyword.');Object.defineProperty(e,"currentProvider",{get:function(){return e._provider},set:function(t){return e.setProvider(t)},enumerable:!0,configurable:!0}),t[0]&&t[0]._requestManager?e._requestManager=new n.Manager(t[0].currentProvider):(e._requestManager=new n.Manager,e._requestManager.setProvider(t[0],t[1])),e.givenProvider=n.Manager.givenProvider,e.providers=n.Manager.providers,e._provider=e._requestManager.provider,e.setProvider||(e.setProvider=function(t,r){return e._requestManager.setProvider(t,r),e._provider=e._requestManager.provider,!0}),e.BatchRequest=n.BatchManager.bind(null,e._requestManager),e.extend=i(e)},addProviders:function(e){e.givenProvider=n.Manager.givenProvider,e.providers=n.Manager.providers}}},{"./extend.js":347,"web3-core-requestmanager":343}],349:[function(e,t,r){var n=e("underscore"),i=e("web3-utils"),o=new(0,e("ethers/utils/abi-coder").AbiCoder)(function(e,t){return!e.match(/^u?int/)||n.isArray(t)||n.isObject(t)&&"BN"===t.constructor.name?t:t.toString()});function a(){}var s=function(){};s.prototype.encodeFunctionSignature=function(e){return n.isObject(e)&&(e=i._jsonInterfaceMethodToString(e)),i.sha3(e).slice(0,10)},s.prototype.encodeEventSignature=function(e){return n.isObject(e)&&(e=i._jsonInterfaceMethodToString(e)),i.sha3(e)},s.prototype.encodeParameter=function(e,t){return this.encodeParameters([e],[t])},s.prototype.encodeParameters=function(e,t){return o.encode(this.mapTypes(e),t)},s.prototype.mapTypes=function(e){var t=this,r=[];return e.forEach(function(e){if(t.isSimplifiedStructFormat(e)){var n=Object.keys(e)[0];r.push(Object.assign(t.mapStructNameAndType(n),{components:t.mapStructToCoderFormat(e[n])}))}else r.push(e)}),r},s.prototype.isSimplifiedStructFormat=function(e){return"object"==typeof e&&void 0===e.components&&void 0===e.name},s.prototype.mapStructNameAndType=function(e){var t="tuple";return e.indexOf("[]")>-1&&(t="tuple[]",e=e.slice(0,-2)),{type:t,name:e}},s.prototype.mapStructToCoderFormat=function(e){var t=this,r=[];return Object.keys(e).forEach(function(n){"object"!=typeof e[n]?r.push({name:n,type:e[n]}):r.push(Object.assign(t.mapStructNameAndType(n),{components:t.mapStructToCoderFormat(e[n])}))}),r},s.prototype.encodeFunctionCall=function(e,t){return this.encodeFunctionSignature(e)+this.encodeParameters(e.inputs,t).replace("0x","")},s.prototype.decodeParameter=function(e,t){return this.decodeParameters([e],t)[0]},s.prototype.decodeParameters=function(e,t){if(!t||"0x"===t||"0X"===t)throw new Error("Returned values aren't valid, did it run Out of Gas?");var r=o.decode(this.mapTypes(e),"0x"+t.replace(/0x/i,"")),i=new a;return i.__length__=0,e.forEach(function(e,t){var o=r[i.__length__];o="0x"===o?null:o,i[t]=o,n.isObject(e)&&e.name&&(i[e.name]=o),i.__length__++}),i},s.prototype.decodeLog=function(e,t,r){var i=this;r=n.isArray(r)?r:[r],t=t||"";var o=[],s=[],u=0;e.forEach(function(e,t){e.indexed?(s[t]=["bool","int","uint","address","fixed","ufixed"].find(function(t){return-1!==e.type.indexOf(t)})?i.decodeParameter(e.type,r[u]):r[u],u++):o[t]=e});var c=t,f=c?this.decodeParameters(o,c):[],h=new a;return h.__length__=0,e.forEach(function(e,t){h[t]="string"===e.type?"":null,void 0!==f[t]&&(h[t]=f[t]),void 0!==s[t]&&(h[t]=s[t]),e.name&&(h[e.name]=h[t]),h.__length__++}),h};var u=new s;t.exports=u},{"ethers/utils/abi-coder":143,underscore:325,"web3-utils":403}],350:[function(e,t,r){(function(r){var n=function(){return function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var r=[],n=!0,i=!1,o=void 0;try{for(var a,s=e[Symbol.iterator]();!(n=(a=s.next()).done)&&(r.push(a.value),!t||r.length!==t);n=!0);}catch(e){i=!0,o=e}finally{try{!n&&s.return&&s.return()}finally{if(i)throw o}}return r}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),i=e("./bytes"),o=e("./nat"),a=e("elliptic"),s=(e("./rlp"),new a.ec("secp256k1")),u=e("./hash"),c=u.keccak256,f=u.keccak256s,h=function(e){for(var t=f(e.slice(2)),r="0x",n=0;n<40;n++)r+=parseInt(t[n+2],16)>7?e[n+2].toUpperCase():e[n+2];return r},l=function(e){var t=new r(e.slice(2),"hex"),n="0x"+s.keyFromPrivate(t).getPublic(!1,"hex").slice(2),i=c(n);return{address:h("0x"+i.slice(-40)),privateKey:e}},d=function(e){var t=n(e,3),r=t[0],o=i.pad(32,t[1]),a=i.pad(32,t[2]);return i.flatten([o,a,r])},p=function(e){return[i.slice(64,i.length(e),e),i.slice(0,32,e),i.slice(32,64,e)]},b=function(e){return function(t,n){var a=s.keyFromPrivate(new r(n.slice(2),"hex")).sign(new r(t.slice(2),"hex"),{canonical:!0});return d([o.fromString(i.fromNumber(e+a.recoveryParam)),i.pad(32,i.fromNat("0x"+a.r.toString(16))),i.pad(32,i.fromNat("0x"+a.s.toString(16)))])}},y=b(27);t.exports={create:function(e){var t=c(i.concat(i.random(32),e||i.random(32))),r=i.concat(i.concat(i.random(32),t),i.random(32)),n=c(r);return l(n)},toChecksum:h,fromPrivate:l,sign:y,makeSigner:b,recover:function(e,t){var n=p(t),o={v:i.toNumber(n[0]),r:n[1].slice(2),s:n[2].slice(2)},a="0x"+s.recoverPubKey(new r(e.slice(2),"hex"),o,o.v<2?o.v:1-o.v%2).encode("hex",!1).slice(2),u=c(a);return h("0x"+u.slice(-40))},encodeSignature:d,decodeSignature:p}}).call(this,e("buffer").Buffer)},{"./bytes":352,"./hash":353,"./nat":354,"./rlp":355,buffer:84,elliptic:109}],351:[function(e,t,r){arguments[4][132][0].apply(r,arguments)},{dup:132}],352:[function(e,t,r){arguments[4][133][0].apply(r,arguments)},{"./array.js":351,dup:133}],353:[function(e,t,r){arguments[4][134][0].apply(r,arguments)},{dup:134}],354:[function(e,t,r){var n=e("bn.js"),i=e("./bytes"),o=function(e){return new n(e.slice(2),16)},a=function(e){var t="0x"+("0x"===e.slice(0,2)?new n(e.slice(2),16):new n(e,10)).toString("hex");return"0x0"===t?"0x":t},s=function(e){return"string"==typeof e?/^0x/.test(e)?e:"0x"+e:"0x"+new n(e).toString("hex")},u=function(e){return o(e).toNumber()},c=function(e){return function(t,r){return"0x"+o(t)[e](o(r)).toString("hex")}},f=c("add"),h=c("mul"),l=c("div"),d=c("sub");t.exports={toString:function(e){return o(e).toString(10)},fromString:a,toNumber:u,fromNumber:s,toEther:function(e){return u(l(e,a("10000000000")))/1e8},fromEther:function(e){return h(s(Math.floor(1e8*e)),a("10000000000"))},toUint256:function(e){return i.pad(32,e)},add:f,mul:h,div:l,sub:d}},{"./bytes":352,"bn.js":53}],355:[function(e,t,r){t.exports={encode:function(e){var t=function(e){return(t=e.toString(16)).length%2==0?t:"0"+t;var t},r=function(e,r){return e<56?t(r+e):t(r+t(e).length/2+55)+t(e)};return"0x"+function e(t){if("string"==typeof t){var n=t.slice(2);return(2!=n.length||n>="80"?r(n.length/2,128):"")+n}var i=t.map(e).join("");return r(i.length/2,192)+i}(e)},decode:function(e){var t=2,r=function(){if(t>=e.length)throw"";var r=e.slice(t,t+2);return r<"80"?(t+=2,"0x"+r):r<"c0"?i():o()},n=function(){var r=parseInt(e.slice(t,t+=2),16)%64;return r<56?r:parseInt(e.slice(t,t+=2*(r-55)),16)},i=function(){var r=n();return"0x"+e.slice(t,t+=2*r)},o=function(){for(var e=2*n()+t,i=[];t>>((3&t)<<3)&255;return i}}t.exports=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],357:[function(e,t,r){for(var n=e("./rng"),i=[],o={},a=0;a<256;a++)i[a]=(a+256).toString(16).substr(1),o[i[a]]=a;function s(e,t){var r=t||0,n=i;return n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+"-"+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]+n[e[r++]]}var u=n(),c=[1|u[0],u[1],u[2],u[3],u[4],u[5]],f=16383&(u[6]<<8|u[7]),h=0,l=0;function d(e,t,r){var i=t&&r||0;"string"==typeof e&&(t="binary"==e?new Array(16):null,e=null);var o=(e=e||{}).random||(e.rng||n)();if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,t)for(var a=0;a<16;a++)t[i+a]=o[a];return t||s(o)}var p=d;p.v1=function(e,t,r){var n=t&&r||0,i=t||[],o=void 0!==(e=e||{}).clockseq?e.clockseq:f,a=void 0!==e.msecs?e.msecs:(new Date).getTime(),u=void 0!==e.nsecs?e.nsecs:l+1,d=a-h+(u-l)/1e4;if(d<0&&void 0===e.clockseq&&(o=o+1&16383),(d<0||a>h)&&void 0===e.nsecs&&(u=0),u>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");h=a,l=u,f=o;var p=(1e4*(268435455&(a+=122192928e5))+u)%4294967296;i[n++]=p>>>24&255,i[n++]=p>>>16&255,i[n++]=p>>>8&255,i[n++]=255&p;var b=a/4294967296*1e4&268435455;i[n++]=b>>>8&255,i[n++]=255&b,i[n++]=b>>>24&15|16,i[n++]=b>>>16&255,i[n++]=o>>>8|128,i[n++]=255&o;for(var y=e.node||c,m=0;m<6;m++)i[n+m]=y[m];return t||s(i)},p.v4=d,p.parse=function(e,t,r){var n=t&&r||0,i=0;for(t=t||[],e.toLowerCase().replace(/[0-9a-f]{2}/g,function(e){i<16&&(t[n+i++]=o[e])});i<16;)t[n+i++]=0;return t},p.unparse=s,t.exports=p},{"./rng":356}],358:[function(e,t,r){(function(r,n){"use strict";var i=e("underscore"),o=e("web3-core"),a=e("web3-core-method"),s=e("any-promise"),u=e("eth-lib/lib/account"),c=e("eth-lib/lib/hash"),f=e("eth-lib/lib/rlp"),h=e("eth-lib/lib/nat"),l=e("eth-lib/lib/bytes"),d=e(void 0===r?"crypto-browserify":"crypto"),p=e("scrypt.js"),b=e("uuid"),y=e("web3-utils"),m=e("web3-core-helpers"),v=function(e){return i.isUndefined(e)||i.isNull(e)},g=function(e){for(;e&&e.startsWith("0x0");)e="0x"+e.slice(3);return e},w=function(e){return e.length%2==1&&(e=e.replace("0x","0x0")),e},_=function(){var e=this;o.packageInit(this,arguments),delete this.BatchRequest,delete this.extend;var t=[new a({name:"getId",call:"net_version",params:0,outputFormatter:y.hexToNumber}),new a({name:"getGasPrice",call:"eth_gasPrice",params:0}),new a({name:"getTransactionCount",call:"eth_getTransactionCount",params:2,inputFormatter:[function(e){if(y.isAddress(e))return e;throw new Error("Address "+e+' is not a valid address to get the "transactionCount".')},function(){return"latest"}]})];this._ethereumCall={},i.each(t,function(t){t.attachToObject(e._ethereumCall),t.setRequestManager(e._requestManager)}),this.wallet=new A(this)};function A(e){this._accounts=e,this.length=0,this.defaultKeyName="web3js_wallet"}_.prototype._addAccountFunctions=function(e){var t=this;return e.signTransaction=function(r,n){return t.signTransaction(r,e.privateKey,n)},e.sign=function(r){return t.sign(r,e.privateKey)},e.encrypt=function(r,n){return t.encrypt(e.privateKey,r,n)},e},_.prototype.create=function(e){return this._addAccountFunctions(u.create(e||y.randomHex(32)))},_.prototype.privateKeyToAccount=function(e){return this._addAccountFunctions(u.fromPrivate(e))},_.prototype.signTransaction=function(e,t,r){var n,o=!1;if(r=r||function(){},!e)return o=new Error("No transaction object given!"),r(o),s.reject(o);function a(e){if(e.gas||e.gasLimit||(o=new Error('"gas" is missing')),(e.nonce<0||e.gas<0||e.gasPrice<0||e.chainId<0)&&(o=new Error("Gas, gasPrice, nonce or chainId is lower than 0")),o)return r(o),s.reject(o);try{var i=e=m.formatters.inputCallFormatter(e);i.to=e.to||"0x",i.data=e.data||"0x",i.value=e.value||"0x",i.chainId=y.numberToHex(e.chainId);var a=f.encode([l.fromNat(i.nonce),l.fromNat(i.gasPrice),l.fromNat(i.gas),i.to.toLowerCase(),l.fromNat(i.value),i.data,l.fromNat(i.chainId||"0x1"),"0x","0x"]),d=c.keccak256(a),p=u.makeSigner(2*h.toNumber(i.chainId||"0x1")+35)(c.keccak256(a),t),b=f.decode(a).slice(0,6).concat(u.decodeSignature(p));b[6]=w(g(b[6])),b[7]=w(g(b[7])),b[8]=w(g(b[8]));var v=f.encode(b),_=f.decode(v);n={messageHash:d,v:g(_[6]),r:g(_[7]),s:g(_[8]),rawTransaction:v}}catch(e){return r(e),s.reject(e)}return r(null,n),n}return void 0!==e.nonce&&void 0!==e.chainId&&void 0!==e.gasPrice?s.resolve(a(e)):s.all([v(e.chainId)?this._ethereumCall.getId():e.chainId,v(e.gasPrice)?this._ethereumCall.getGasPrice():e.gasPrice,v(e.nonce)?this._ethereumCall.getTransactionCount(this.privateKeyToAccount(t).address):e.nonce]).then(function(t){if(v(t[0])||v(t[1])||v(t[2]))throw new Error('One of the values "chainId", "gasPrice", or "nonce" couldn\'t be fetched: '+JSON.stringify(t));return a(i.extend(e,{chainId:t[0],gasPrice:t[1],nonce:t[2]}))})},_.prototype.recoverTransaction=function(e){var t=f.decode(e),r=u.encodeSignature(t.slice(6,9)),n=l.toNumber(t[6]),i=n<35?[]:[l.fromNumber(n-35>>1),"0x","0x"],o=t.slice(0,6).concat(i),a=f.encode(o);return u.recover(c.keccak256(a),r)},_.prototype.hashMessage=function(e){var t=y.isHexStrict(e)?y.hexToBytes(e):e,r=n.from(t),i="Ethereum Signed Message:\n"+t.length,o=n.from(i),a=n.concat([o,r]);return c.keccak256s(a)},_.prototype.sign=function(e,t){var r=this.hashMessage(e),n=u.sign(r,t),i=u.decodeSignature(n);return{message:e,messageHash:r,v:i[0],r:i[1],s:i[2],signature:n}},_.prototype.recover=function(e,t,r){var n=[].slice.apply(arguments);return i.isObject(e)?this.recover(e.messageHash,u.encodeSignature([e.v,e.r,e.s]),!0):(r||(e=this.hashMessage(e)),n.length>=4?(r=n.slice(-1)[0],r=!!i.isBoolean(r)&&!!r,this.recover(e,u.encodeSignature(n.slice(1,4)),r)):u.recover(e,t))},_.prototype.decrypt=function(e,t,r){if(!i.isString(t))throw new Error("No password given.");var o,a,s=i.isObject(e)?e:JSON.parse(r?e.toLowerCase():e);if(3!==s.version)throw new Error("Not a valid V3 wallet");if("scrypt"===s.crypto.kdf)a=s.crypto.kdfparams,o=p(new n(t),new n(a.salt,"hex"),a.n,a.r,a.p,a.dklen);else{if("pbkdf2"!==s.crypto.kdf)throw new Error("Unsupported key derivation scheme");if("hmac-sha256"!==(a=s.crypto.kdfparams).prf)throw new Error("Unsupported parameters to PBKDF2");o=d.pbkdf2Sync(new n(t),new n(a.salt,"hex"),a.c,a.dklen,"sha256")}var u=new n(s.crypto.ciphertext,"hex");if(y.sha3(n.concat([o.slice(16,32),u])).replace("0x","")!==s.crypto.mac)throw new Error("Key derivation failed - possibly wrong password");var c=d.createDecipheriv(s.crypto.cipher,o.slice(0,16),new n(s.crypto.cipherparams.iv,"hex")),f="0x"+n.concat([c.update(u),c.final()]).toString("hex");return this.privateKeyToAccount(f)},_.prototype.encrypt=function(e,t,r){var i,o=this.privateKeyToAccount(e),a=(r=r||{}).salt||d.randomBytes(32),s=r.iv||d.randomBytes(16),u=r.kdf||"scrypt",c={dklen:r.dklen||32,salt:a.toString("hex")};if("pbkdf2"===u)c.c=r.c||262144,c.prf="hmac-sha256",i=d.pbkdf2Sync(new n(t),a,c.c,c.dklen,"sha256");else{if("scrypt"!==u)throw new Error("Unsupported kdf");c.n=r.n||8192,c.r=r.r||8,c.p=r.p||1,i=p(new n(t),a,c.n,c.r,c.p,c.dklen)}var f=d.createCipheriv(r.cipher||"aes-128-ctr",i.slice(0,16),s);if(!f)throw new Error("Unsupported cipher");var h=n.concat([f.update(new n(o.privateKey.replace("0x",""),"hex")),f.final()]),l=y.sha3(n.concat([i.slice(16,32),new n(h,"hex")])).replace("0x","");return{version:3,id:b.v4({random:r.uuid||d.randomBytes(16)}),address:o.address.toLowerCase().replace("0x",""),crypto:{ciphertext:h.toString("hex"),cipherparams:{iv:s.toString("hex")},cipher:r.cipher||"aes-128-ctr",kdf:u,kdfparams:c,mac:l.toString("hex")}}},A.prototype._findSafeIndex=function(e){return e=e||0,i.has(this,e)?this._findSafeIndex(e+1):e},A.prototype._currentIndexes=function(){return Object.keys(this).map(function(e){return parseInt(e)}).filter(function(e){return e<9e20})},A.prototype.create=function(e,t){for(var r=0;r=2?t.slice(2):t;var r=h.decodeParameters(e,t);return 1===r.__length__?r[0]:(delete r.__length__,r)},l.prototype.deploy=function(e,t){if((e=e||{}).arguments=e.arguments||[],!(e=this._getOrSetDefaultOptions(e)).data)return a._fireError(new Error('No "data" specified in neither the given options, nor the default options.'),null,null,t);var r=n.find(this.options.jsonInterface,function(e){return"constructor"===e.type})||{};return r.signature="constructor",this._createTxObject.apply({method:r,parent:this,deployData:e.data,_ethAccounts:this.constructor._ethAccounts},e.arguments)},l.prototype._generateEventOptions=function(){var e=Array.prototype.slice.call(arguments),t=this._getCallback(e),r=n.isObject(e[e.length-1])?e.pop():{},i=n.isString(e[0])?e[0]:"allevents";if(!(i="allevents"===i.toLowerCase()?{name:"ALLEVENTS",jsonInterface:this.options.jsonInterface}:this.options.jsonInterface.find(function(e){return"event"===e.type&&(e.name===i||e.signature==="0x"+i.replace("0x",""))})))throw new Error('Event "'+i.name+"\" doesn't exist in this contract.");if(!a.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(i,r),event:i,callback:t}},l.prototype.clone=function(){return new this.constructor(this.options.jsonInterface,this.options.address,this.options)},l.prototype.once=function(e,t,r){var i=Array.prototype.slice.call(arguments);if(!(r=this._getCallback(i)))throw new Error("Once requires a callback as the second parameter.");t&&delete t.fromBlock,this._on(e,t,function(e,t,i){i.unsubscribe(),n.isFunction(r)&&r(e,t,i)})},l.prototype._on=function(){var e=this._generateEventOptions.apply(this,arguments);this._checkListener("newListener",e.event.name,e.callback),this._checkListener("removeListener",e.event.name,e.callback);var t=new s({subscription:{params:1,inputFormatter:[u.inputLogFormatter],outputFormatter:this._decodeEventABI.bind(e.event),subscriptionHandler:function(e){e.removed?this.emit("changed",e):this.emit("data",e),n.isFunction(this.callback)&&this.callback(null,e,this)}},type:"eth",requestManager:this._requestManager});return t.subscribe("logs",e.params,e.callback||function(){}),t},l.prototype.getPastEvents=function(){var e=this._generateEventOptions.apply(this,arguments),t=new o({name:"getPastLogs",call:"eth_getLogs",params:1,inputFormatter:[u.inputLogFormatter],outputFormatter:this._decodeEventABI.bind(e.event)});t.setRequestManager(this._requestManager);var r=t.buildCall();return t=null,r(e.params,e.callback)},l.prototype._createTxObject=function(){var e=Array.prototype.slice.call(arguments),t={};if("function"===this.method.type&&(t.call=this.parent._executeMethod.bind(t,"call"),t.call.request=this.parent._executeMethod.bind(t,"call",!0)),t.send=this.parent._executeMethod.bind(t,"send"),t.send.request=this.parent._executeMethod.bind(t,"send",!0),t.encodeABI=this.parent._encodeMethodABI.bind(t),t.estimateGas=this.parent._executeMethod.bind(t,"estimate"),e&&this.method.inputs&&e.length!==this.method.inputs.length){if(this.nextMethod)return this.nextMethod.apply(null,e);throw c.InvalidNumberOfParams(e.length,this.method.inputs.length,this.method.name)}return t.arguments=e||[],t._method=this.method,t._parent=this.parent,t._ethAccounts=this.parent.constructor._ethAccounts||this._ethAccounts,this.deployData&&(t._deployData=this.deployData),t},l.prototype._processExecuteArguments=function(e,t){var r={};if(r.type=e.shift(),r.callback=this._parent._getCallback(e),"call"===r.type&&!0!==e[e.length-1]&&(n.isString(e[e.length-1])||isFinite(e[e.length-1]))&&(r.defaultBlock=e.pop()),r.options=n.isObject(e[e.length-1])?e.pop():{},r.generateRequest=!0===e[e.length-1]&&e.pop(),r.options=this._parent._getOrSetDefaultOptions(r.options),r.options.data=this.encodeABI(),!this._deployData&&!a.isAddress(this._parent.options.address))throw new Error("This contract object doesn't have address set yet, please set an address first.");return this._deployData||(r.options.to=this._parent.options.address),r.options.data?r:a._fireError(new Error("Couldn't find a matching contract method, or the number of parameters is wrong."),t.eventEmitter,t.reject,r.callback)},l.prototype._executeMethod=function(){var e=this,t=this._parent._processExecuteArguments.call(this,Array.prototype.slice.call(arguments),r),r=f("send"!==t.type),i=e.constructor._ethAccounts||e._ethAccounts;if(t.generateRequest){var s={params:[u.inputCallFormatter.call(this._parent,t.options)],callback:t.callback};return"call"===t.type?(s.params.push(u.inputDefaultBlockNumberFormatter.call(this._parent,t.defaultBlock)),s.method="eth_call",s.format=this._parent._decodeMethodReturn.bind(null,this._method.outputs)):s.method="eth_sendTransaction",s}switch(t.type){case"estimate":return new o({name:"estimateGas",call:"eth_estimateGas",params:1,inputFormatter:[u.inputCallFormatter],outputFormatter:a.hexToNumber,requestManager:e._parent._requestManager,accounts:i,defaultAccount:e._parent.defaultAccount,defaultBlock:e._parent.defaultBlock}).createFunction()(t.options,t.callback);case"call":return new o({name:"call",call:"eth_call",params:2,inputFormatter:[u.inputCallFormatter,u.inputDefaultBlockNumberFormatter],outputFormatter:function(t){return e._parent._decodeMethodReturn(e._method.outputs,t)},requestManager:e._parent._requestManager,accounts:i,defaultAccount:e._parent.defaultAccount,defaultBlock:e._parent.defaultBlock}).createFunction()(t.options,t.defaultBlock,t.callback);case"send":if(!a.isAddress(t.options.from))return a._fireError(new Error('No "from" address specified in neither the given options, nor the default options.'),r.eventEmitter,r.reject,t.callback);if(n.isBoolean(this._method.payable)&&!this._method.payable&&t.options.value&&t.options.value>0)return a._fireError(new Error("Can not send value to non-payable contract method or constructor"),r.eventEmitter,r.reject,t.callback);var c={receiptFormatter:function(t){if(n.isArray(t.logs)){var r=n.map(t.logs,function(t){return e._parent._decodeEventABI.call({name:"ALLEVENTS",jsonInterface:e._parent.options.jsonInterface},t)});t.events={};var i=0;r.forEach(function(e){e.event?t.events[e.event]?Array.isArray(t.events[e.event])?t.events[e.event].push(e):t.events[e.event]=[t.events[e.event],e]:t.events[e.event]=e:(t.events[i]=e,i++)}),delete t.logs}return t},contractDeployFormatter:function(t){var r=e._parent.clone();return r.options.address=t.contractAddress,r}};return new o({name:"sendTransaction",call:"eth_sendTransaction",params:1,inputFormatter:[u.inputTransactionFormatter],requestManager:e._parent._requestManager,accounts:e.constructor._ethAccounts||e._ethAccounts,defaultAccount:e._parent.defaultAccount,defaultBlock:e._parent.defaultBlock,extraFormatters:c}).createFunction()(t.options,t.callback)}},t.exports=l},{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(e,t,r){"use strict";var n=e("./config"),i=e("./contracts/Registry"),o=e("./lib/ResolverMethodHandler");function a(e){this.eth=e}Object.defineProperty(a.prototype,"registry",{get:function(){return new i(this)},enumerable:!0}),Object.defineProperty(a.prototype,"resolverMethodHandler",{get:function(){return new o(this.registry)},enumerable:!0}),a.prototype.resolver=function(e){return this.registry.resolver(e)},a.prototype.getAddress=function(e,t){return this.resolverMethodHandler.method(e,"addr",[]).call(t)},a.prototype.setAddress=function(e,t,r,n){return this.resolverMethodHandler.method(e,"setAddr",[t]).send(r,n)},a.prototype.getPubkey=function(e,t){return this.resolverMethodHandler.method(e,"pubkey",[],t).call(t)},a.prototype.setPubkey=function(e,t,r,n,i){return this.resolverMethodHandler.method(e,"setPubkey",[t,r]).send(n,i)},a.prototype.getContent=function(e,t){return this.resolverMethodHandler.method(e,"content",[]).call(t)},a.prototype.setContent=function(e,t,r,n){return this.resolverMethodHandler.method(e,"setContent",[t]).send(r,n)},a.prototype.getMultihash=function(e,t){return this.resolverMethodHandler.method(e,"multihash",[]).call(t)},a.prototype.setMultihash=function(e,t,r,n){return this.resolverMethodHandler.method(e,"multihash",[t]).send(r,n)},a.prototype.checkNetwork=function(){var e=this;return e.eth.getBlock("latest").then(function(t){var r=new Date/1e3-t.timestamp;if(r>3600)throw new Error("Network not synced; last block was "+r+" seconds ago");return e.eth.net.getNetworkType()}).then(function(e){var t=n.addresses[e];if(void 0===t)throw new Error("ENS is not supported on network "+e);return t})},t.exports=a},{"./config":361,"./contracts/Registry":362,"./lib/ResolverMethodHandler":364}],361:[function(e,t,r){"use strict";t.exports={addresses:{main:"0x314159265dD8dbb310642f98f50C066173C1259b",ropsten:"0x112234455c3a32fd11230c42e7bccd4a84e02010",rinkeby:"0xe7410170f87102df0055eb195163a03b7f2bff4a"}}},{}],362:[function(e,t,r){"use strict";var n=e("underscore"),i=e("web3-eth-contract"),o=e("eth-ens-namehash"),a=e("web3-core-promievent"),s=e("../ressources/ABI/Registry"),u=e("../ressources/ABI/Resolver");function c(e){var t=this;this.ens=e,this.contract=e.checkNetwork().then(function(e){var r=new i(s,e);return r.setProvider(t.ens.eth.currentProvider),r})}c.prototype.owner=function(e,t){var r=new a(!0);return this.contract.then(function(i){i.methods.owner(o.hash(e)).call().then(function(e){r.resolve(e),n.isFunction(t)&&t(e)}).catch(function(e){r.reject(e),n.isFunction(t)&&t(e)})}),r.eventEmitter},c.prototype.resolver=function(e){var t=this;return this.contract.then(function(t){return t.methods.resolver(o.hash(e)).call()}).then(function(e){var r=new i(u,e);return r.setProvider(t.ens.eth.currentProvider),r})},t.exports=c},{"../ressources/ABI/Registry":365,"../ressources/ABI/Resolver":366,"eth-ens-namehash":127,underscore:325,"web3-core-promievent":340,"web3-eth-contract":359}],363:[function(e,t,r){"use strict";var n=e("./ENS");t.exports=n},{"./ENS":360}],364:[function(e,t,r){"use strict";var n=e("web3-core-promievent"),i=e("eth-ens-namehash"),o=e("underscore");function a(e){this.registry=e}a.prototype.method=function(e,t,r,n){return{call:this.call.bind({ensName:e,methodName:t,methodArguments:r,callback:n,parent:this}),send:this.send.bind({ensName:e,methodName:t,methodArguments:r,callback:n,parent:this})}},a.prototype.call=function(e){var t=this,r=new n,i=this.parent.prepareArguments(this.ensName,this.methodArguments);return this.parent.registry.resolver(this.ensName).then(function(n){t.parent.handleCall(r,n.methods[t.methodName],i,e)}).catch(function(e){r.reject(e)}),r.eventEmitter},a.prototype.send=function(e,t){var r=this,i=new n,o=this.parent.prepareArguments(this.ensName,this.methodArguments);return this.parent.registry.resolver(this.ensName).then(function(n){r.parent.handleSend(i,n.methods[r.methodName],o,e,t)}).catch(function(e){i.reject(e)}),i.eventEmitter},a.prototype.handleCall=function(e,t,r,n){return t.apply(this,r).call().then(function(t){e.resolve(t),o.isFunction(n)&&n(t)}).catch(function(t){e.reject(t),o.isFunction(n)&&n(t)}),e},a.prototype.handleSend=function(e,t,r,n,i){return t.apply(this,r).send(n).on("transactionHash",function(t){e.eventEmitter.emit("transactionHash",t)}).on("confirmation",function(t,r){e.eventEmitter.emit("confirmation",t,r)}).on("receipt",function(t){e.eventEmitter.emit("receipt",t),e.resolve(t),o.isFunction(i)&&i(t)}).on("error",function(t){e.eventEmitter.emit("error",t),e.reject(t),o.isFunction(i)&&i(t)}),e},a.prototype.prepareArguments=function(e,t){var r=i.hash(e);return t.length>0?(t.unshift(r),t):[r]},t.exports=a},{"eth-ens-namehash":127,underscore:325,"web3-core-promievent":340}],365:[function(e,t,r){"use strict";t.exports=[{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"resolver",outputs:[{name:"",type:"address"}],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"owner",outputs:[{name:"",type:"address"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"label",type:"bytes32"},{name:"owner",type:"address"}],name:"setSubnodeOwner",outputs:[],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"ttl",type:"uint64"}],name:"setTTL",outputs:[],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"ttl",outputs:[{name:"",type:"uint64"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"resolver",type:"address"}],name:"setResolver",outputs:[],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"owner",type:"address"}],name:"setOwner",outputs:[],payable:!1,type:"function"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"owner",type:"address"}],name:"Transfer",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!0,name:"label",type:"bytes32"},{indexed:!1,name:"owner",type:"address"}],name:"NewOwner",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"resolver",type:"address"}],name:"NewResolver",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"ttl",type:"uint64"}],name:"NewTTL",type:"event"}]},{}],366:[function(e,t,r){"use strict";t.exports=[{constant:!0,inputs:[{name:"interfaceID",type:"bytes4"}],name:"supportsInterface",outputs:[{name:"",type:"bool"}],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"},{name:"contentTypes",type:"uint256"}],name:"ABI",outputs:[{name:"contentType",type:"uint256"},{name:"data",type:"bytes"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"hash",type:"bytes"}],name:"setMultihash",outputs:[],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"multihash",outputs:[{name:"",type:"bytes"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"x",type:"bytes32"},{name:"y",type:"bytes32"}],name:"setPubkey",outputs:[],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"content",outputs:[{name:"ret",type:"bytes32"}],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"addr",outputs:[{name:"ret",type:"address"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"contentType",type:"uint256"},{name:"data",type:"bytes"}],name:"setABI",outputs:[],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"name",outputs:[{name:"ret",type:"string"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"name",type:"string"}],name:"setName",outputs:[],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"hash",type:"bytes32"}],name:"setContent",outputs:[],payable:!1,type:"function"},{constant:!0,inputs:[{name:"node",type:"bytes32"}],name:"pubkey",outputs:[{name:"x",type:"bytes32"},{name:"y",type:"bytes32"}],payable:!1,type:"function"},{constant:!1,inputs:[{name:"node",type:"bytes32"},{name:"addr",type:"address"}],name:"setAddr",outputs:[],payable:!1,type:"function"},{inputs:[{name:"ensAddr",type:"address"}],payable:!1,type:"constructor"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"a",type:"address"}],name:"AddrChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"hash",type:"bytes32"}],name:"ContentChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"name",type:"string"}],name:"NameChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!0,name:"contentType",type:"uint256"}],name:"ABIChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"node",type:"bytes32"},{indexed:!1,name:"x",type:"bytes32"},{indexed:!1,name:"y",type:"bytes32"}],name:"PubkeyChanged",type:"event"}]},{}],367:[function(e,t,r){arguments[4][154][0].apply(r,arguments)},{dup:154}],368:[function(e,t,r){"use strict";var n=e("web3-utils"),i=e("bn.js"),o=function(e){var t="A".charCodeAt(0),r="Z".charCodeAt(0);return(e=(e=e.toUpperCase()).substr(4)+e.substr(0,4)).split("").map(function(e){var n=e.charCodeAt(0);return n>=t&&n<=r?n-t+10:e}).join("")},a=function(e){for(var t,r=e;r.length>2;)t=r.slice(0,9),r=parseInt(t,10)%97+r.slice(t.length);return parseInt(r,10)%97},s=function(e){this._iban=e};s.toAddress=function(e){if(!(e=new s(e)).isDirect())throw new Error("IBAN is indirect and can't be converted");return e.toAddress()},s.toIban=function(e){return s.fromAddress(e).toString()},s.fromAddress=function(e){if(!n.isAddress(e))throw new Error("Provided address is not a valid address: "+e);e=e.replace("0x","").replace("0X","");var t=function(e,t){for(var r=e;r.length<2*t;)r="0"+r;return r}(new i(e,16).toString(36),15);return s.fromBban(t.toUpperCase())},s.fromBban=function(e){var t=("0"+(98-a(o("XE00"+e)))).slice(-2);return new s("XE"+t+e)},s.createIndirect=function(e){return s.fromBban("ETH"+e.institution+e.identifier)},s.isValid=function(e){return new s(e).isValid()},s.prototype.isValid=function(){return/^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$/.test(this._iban)&&1===a(o(this._iban))},s.prototype.isDirect=function(){return 34===this._iban.length||35===this._iban.length},s.prototype.isIndirect=function(){return 20===this._iban.length},s.prototype.checksum=function(){return this._iban.substr(2,2)},s.prototype.institution=function(){return this.isIndirect()?this._iban.substr(7,4):""},s.prototype.client=function(){return this.isIndirect()?this._iban.substr(11):""},s.prototype.toAddress=function(){if(this.isDirect()){var e=this._iban.substr(4),t=new i(e,36);return n.toChecksumAddress(t.toString(16,20))}return""},s.prototype.toString=function(){return this._iban},t.exports=s},{"bn.js":367,"web3-utils":403}],369:[function(e,t,r){"use strict";var n=e("web3-core"),i=e("web3-core-method"),o=e("web3-utils"),a=e("web3-net"),s=e("web3-core-helpers").formatters,u=function(){var e=this;n.packageInit(this,arguments),this.net=new a(this.currentProvider);var t=null,r="latest";Object.defineProperty(this,"defaultAccount",{get:function(){return t},set:function(e){return e&&(t=o.toChecksumAddress(s.inputAddressFormatter(e))),u.forEach(function(e){e.defaultAccount=t}),e},enumerable:!0}),Object.defineProperty(this,"defaultBlock",{get:function(){return r},set:function(e){return r=e,u.forEach(function(e){e.defaultBlock=r}),e},enumerable:!0});var u=[new i({name:"getAccounts",call:"personal_listAccounts",params:0,outputFormatter:o.toChecksumAddress}),new i({name:"newAccount",call:"personal_newAccount",params:1,inputFormatter:[null],outputFormatter:o.toChecksumAddress}),new i({name:"unlockAccount",call:"personal_unlockAccount",params:3,inputFormatter:[s.inputAddressFormatter,null,null]}),new i({name:"lockAccount",call:"personal_lockAccount",params:1,inputFormatter:[s.inputAddressFormatter]}),new i({name:"importRawKey",call:"personal_importRawKey",params:2}),new i({name:"sendTransaction",call:"personal_sendTransaction",params:2,inputFormatter:[s.inputTransactionFormatter,null]}),new i({name:"signTransaction",call:"personal_signTransaction",params:2,inputFormatter:[s.inputTransactionFormatter,null]}),new i({name:"sign",call:"personal_sign",params:3,inputFormatter:[s.inputSignFormatter,s.inputAddressFormatter,null]}),new i({name:"ecRecover",call:"personal_ecRecover",params:2,inputFormatter:[s.inputSignFormatter,null]})];u.forEach(function(t){t.attachToObject(e),t.setRequestManager(e._requestManager),t.defaultBlock=e.defaultBlock,t.defaultAccount=e.defaultAccount})};n.addProviders(u),t.exports=u},{"web3-core":348,"web3-core-helpers":338,"web3-core-method":339,"web3-net":372,"web3-utils":403}],370:[function(e,t,r){"use strict";var n=e("underscore");t.exports=function(e){var t,r=this;return this.net.getId().then(function(e){return t=e,r.getBlock(0)}).then(function(r){var i="private";return"0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3"===r.hash&&1===t&&(i="main"),"0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303"===r.hash&&2===t&&(i="morden"),"0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d"===r.hash&&3===t&&(i="ropsten"),"0x6341fd3daf94b748c72ced5a5b26028f2474f5f00d824504e4fa37a75767e177"===r.hash&&4===t&&(i="rinkeby"),"0xa3c565fc15c7478862d50ccd6561e3c06b24cc509bf388941c25ea985ce32cb9"===r.hash&&42===t&&(i="kovan"),n.isFunction(e)&&e(null,i),i}).catch(function(t){if(!n.isFunction(e))throw t;e(t)})}},{underscore:325}],371:[function(e,t,r){"use strict";var n=e("underscore"),i=e("web3-core"),o=e("web3-core-helpers"),a=e("web3-core-subscriptions").subscriptions,s=e("web3-core-method"),u=e("web3-utils"),c=e("web3-net"),f=e("web3-eth-ens"),h=e("web3-eth-personal"),l=e("web3-eth-contract"),d=e("web3-eth-iban"),p=e("web3-eth-accounts"),b=e("web3-eth-abi"),y=e("./getNetworkType.js"),m=o.formatters,v=function(e){return n.isString(e[0])&&0===e[0].indexOf("0x")?"eth_getBlockByHash":"eth_getBlockByNumber"},g=function(e){return n.isString(e[0])&&0===e[0].indexOf("0x")?"eth_getTransactionByBlockHashAndIndex":"eth_getTransactionByBlockNumberAndIndex"},w=function(e){return n.isString(e[0])&&0===e[0].indexOf("0x")?"eth_getUncleByBlockHashAndIndex":"eth_getUncleByBlockNumberAndIndex"},_=function(e){return n.isString(e[0])&&0===e[0].indexOf("0x")?"eth_getBlockTransactionCountByHash":"eth_getBlockTransactionCountByNumber"},A=function(e){return n.isString(e[0])&&0===e[0].indexOf("0x")?"eth_getUncleCountByBlockHash":"eth_getUncleCountByBlockNumber"},E=function(){var e=this;i.packageInit(this,arguments);var t=this.setProvider;this.setProvider=function(){t.apply(e,arguments),e.net.setProvider.apply(e,arguments),e.personal.setProvider.apply(e,arguments),e.accounts.setProvider.apply(e,arguments),e.Contract.setProvider(e.currentProvider,e.accounts)};var r=null,o="latest";Object.defineProperty(this,"defaultAccount",{get:function(){return r},set:function(t){return t&&(r=u.toChecksumAddress(m.inputAddressFormatter(t))),e.Contract.defaultAccount=r,e.personal.defaultAccount=r,k.forEach(function(e){e.defaultAccount=r}),t},enumerable:!0}),Object.defineProperty(this,"defaultBlock",{get:function(){return o},set:function(t){return o=t,e.Contract.defaultBlock=o,e.personal.defaultBlock=o,k.forEach(function(e){e.defaultBlock=o}),t},enumerable:!0}),this.clearSubscriptions=e._requestManager.clearSubscriptions,this.net=new c(this.currentProvider),this.net.getNetworkType=y.bind(this),this.accounts=new p(this.currentProvider),this.personal=new h(this.currentProvider),this.personal.defaultAccount=this.defaultAccount;var E=this,x=function(){l.apply(this,arguments);var e=this,t=E.setProvider;E.setProvider=function(){t.apply(E,arguments),i.packageInit(e,[E.currentProvider])}};x.setProvider=function(){l.setProvider.apply(this,arguments)},(x.prototype=Object.create(l.prototype)).constructor=x,this.Contract=x,this.Contract.defaultAccount=this.defaultAccount,this.Contract.defaultBlock=this.defaultBlock,this.Contract.setProvider(this.currentProvider,this.accounts),this.Iban=d,this.abi=b,this.ens=new f(this);var k=[new s({name:"getNodeInfo",call:"web3_clientVersion"}),new s({name:"getProtocolVersion",call:"eth_protocolVersion",params:0}),new s({name:"getCoinbase",call:"eth_coinbase",params:0}),new s({name:"isMining",call:"eth_mining",params:0}),new s({name:"getHashrate",call:"eth_hashrate",params:0,outputFormatter:u.hexToNumber}),new s({name:"isSyncing",call:"eth_syncing",params:0,outputFormatter:m.outputSyncingFormatter}),new s({name:"getGasPrice",call:"eth_gasPrice",params:0,outputFormatter:m.outputBigNumberFormatter}),new s({name:"getAccounts",call:"eth_accounts",params:0,outputFormatter:u.toChecksumAddress}),new s({name:"getBlockNumber",call:"eth_blockNumber",params:0,outputFormatter:u.hexToNumber}),new s({name:"getBalance",call:"eth_getBalance",params:2,inputFormatter:[m.inputAddressFormatter,m.inputDefaultBlockNumberFormatter],outputFormatter:m.outputBigNumberFormatter}),new s({name:"getStorageAt",call:"eth_getStorageAt",params:3,inputFormatter:[m.inputAddressFormatter,u.numberToHex,m.inputDefaultBlockNumberFormatter]}),new s({name:"getCode",call:"eth_getCode",params:2,inputFormatter:[m.inputAddressFormatter,m.inputDefaultBlockNumberFormatter]}),new s({name:"getBlock",call:v,params:2,inputFormatter:[m.inputBlockNumberFormatter,function(e){return!!e}],outputFormatter:m.outputBlockFormatter}),new s({name:"getUncle",call:w,params:2,inputFormatter:[m.inputBlockNumberFormatter,u.numberToHex],outputFormatter:m.outputBlockFormatter}),new s({name:"getBlockTransactionCount",call:_,params:1,inputFormatter:[m.inputBlockNumberFormatter],outputFormatter:u.hexToNumber}),new s({name:"getBlockUncleCount",call:A,params:1,inputFormatter:[m.inputBlockNumberFormatter],outputFormatter:u.hexToNumber}),new s({name:"getTransaction",call:"eth_getTransactionByHash",params:1,inputFormatter:[null],outputFormatter:m.outputTransactionFormatter}),new s({name:"getTransactionFromBlock",call:g,params:2,inputFormatter:[m.inputBlockNumberFormatter,u.numberToHex],outputFormatter:m.outputTransactionFormatter}),new s({name:"getTransactionReceipt",call:"eth_getTransactionReceipt",params:1,inputFormatter:[null],outputFormatter:m.outputTransactionReceiptFormatter}),new s({name:"getTransactionCount",call:"eth_getTransactionCount",params:2,inputFormatter:[m.inputAddressFormatter,m.inputDefaultBlockNumberFormatter],outputFormatter:u.hexToNumber}),new s({name:"sendSignedTransaction",call:"eth_sendRawTransaction",params:1,inputFormatter:[null]}),new s({name:"signTransaction",call:"eth_signTransaction",params:1,inputFormatter:[m.inputTransactionFormatter]}),new s({name:"sendTransaction",call:"eth_sendTransaction",params:1,inputFormatter:[m.inputTransactionFormatter]}),new s({name:"sign",call:"eth_sign",params:2,inputFormatter:[m.inputSignFormatter,m.inputAddressFormatter],transformPayload:function(e){return e.params.reverse(),e}}),new s({name:"call",call:"eth_call",params:2,inputFormatter:[m.inputCallFormatter,m.inputDefaultBlockNumberFormatter]}),new s({name:"estimateGas",call:"eth_estimateGas",params:1,inputFormatter:[m.inputCallFormatter],outputFormatter:u.hexToNumber}),new s({name:"submitWork",call:"eth_submitWork",params:3}),new s({name:"getWork",call:"eth_getWork",params:0}),new s({name:"getPastLogs",call:"eth_getLogs",params:1,inputFormatter:[m.inputLogFormatter],outputFormatter:m.outputLogFormatter}),new a({name:"subscribe",type:"eth",subscriptions:{newBlockHeaders:{subscriptionName:"newHeads",params:0,outputFormatter:m.outputBlockFormatter},pendingTransactions:{subscriptionName:"newPendingTransactions",params:0},logs:{params:1,inputFormatter:[m.inputLogFormatter],outputFormatter:m.outputLogFormatter,subscriptionHandler:function(e){e.removed?this.emit("changed",e):this.emit("data",e),n.isFunction(this.callback)&&this.callback(null,e,this)}},syncing:{params:0,outputFormatter:m.outputSyncingFormatter,subscriptionHandler:function(e){var t=this;!0!==this._isSyncing?(this._isSyncing=!0,this.emit("changed",t._isSyncing),n.isFunction(this.callback)&&this.callback(null,t._isSyncing,this),setTimeout(function(){t.emit("data",e),n.isFunction(t.callback)&&t.callback(null,e,t)},0)):(this.emit("data",e),n.isFunction(t.callback)&&this.callback(null,e,this),clearTimeout(this._isSyncingTimeout),this._isSyncingTimeout=setTimeout(function(){e.currentBlock>e.highestBlock-200&&(t._isSyncing=!1,t.emit("changed",t._isSyncing),n.isFunction(t.callback)&&t.callback(null,t._isSyncing,t))},500))}}}})];k.forEach(function(t){t.attachToObject(e),t.setRequestManager(e._requestManager,e.accounts),t.defaultBlock=e.defaultBlock,t.defaultAccount=e.defaultAccount})};i.addProviders(E),t.exports=E},{"./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(e,t,r){"use strict";var n=e("web3-core"),i=e("web3-core-method"),o=e("web3-utils"),a=function(){var e=this;n.packageInit(this,arguments),[new i({name:"getId",call:"net_version",params:0,outputFormatter:o.hexToNumber}),new i({name:"isListening",call:"net_listening",params:0}),new i({name:"getPeerCount",call:"net_peerCount",params:0,outputFormatter:o.hexToNumber})].forEach(function(t){t.attachToObject(e),t.setRequestManager(e._requestManager)})};n.addProviders(a),t.exports=a},{"web3-core":348,"web3-core-method":339,"web3-utils":403}],373:[function(e,t,r){const n=e("events").EventEmitter,i=e("util").inherits,o=e("ethereumjs-util"),a=e("eth-block-tracker"),s=e("async/map"),u=e("async/eachSeries"),c=e("./util/stoplight.js");e("./util/rpc-cache-utils.js"),e("./util/create-payload.js");function f(e){const t=this;n.call(t),t.setMaxListeners(30),e=e||{};const r={sendAsync:t._handleAsync.bind(t)},i=e.blockTrackerProvider||r;t._blockTracker=e.blockTracker||new a({provider:i,pollingInterval:e.pollingInterval||4e3}),t._blockTracker.on("block",e=>{const r=function(e){return{number:o.toBuffer(e.number),hash:o.toBuffer(e.hash),parentHash:o.toBuffer(e.parentHash),nonce:o.toBuffer(e.nonce),mixHash:o.toBuffer(e.mixHash),sha3Uncles:o.toBuffer(e.sha3Uncles),logsBloom:o.toBuffer(e.logsBloom),transactionsRoot:o.toBuffer(e.transactionsRoot),stateRoot:o.toBuffer(e.stateRoot),receiptsRoot:o.toBuffer(e.receiptRoot||e.receiptsRoot),miner:o.toBuffer(e.miner),difficulty:o.toBuffer(e.difficulty),totalDifficulty:o.toBuffer(e.totalDifficulty),size:o.toBuffer(e.size),extraData:o.toBuffer(e.extraData),gasLimit:o.toBuffer(e.gasLimit),gasUsed:o.toBuffer(e.gasUsed),timestamp:o.toBuffer(e.timestamp),transactions:e.transactions}}(e);t._setCurrentBlock(r)}),t._blockTracker.on("block",t.emit.bind(t,"rawBlock")),t._blockTracker.on("sync",t.emit.bind(t,"sync")),t._blockTracker.on("latest",t.emit.bind(t,"latest")),t._ready=new c,t._blockTracker.once("block",()=>{t._ready.go()}),t.currentBlock=null,t._providers=[]}t.exports=f,i(f,n),f.prototype.start=function(e=function(){}){this._blockTracker.start().then(e).catch(e)},f.prototype.stop=function(){this._blockTracker.stop()},f.prototype.addProvider=function(e){this._providers.push(e),e.setEngine(this)},f.prototype.send=function(e){throw new Error("Web3ProviderEngine does not support synchronous requests.")},f.prototype.sendAsync=function(e,t){const r=this;r._ready.await(function(){Array.isArray(e)?s(e,r._handleAsync.bind(r),t):r._handleAsync(e,t)})},f.prototype._handleAsync=function(e,t){var r=this,n=-1,i=null,o=null,a=[];function s(r,n){o=r,i=n,u(a,function(e,t){e?e(o,i,t):t()},function(){var r={id:e.id,jsonrpc:e.jsonrpc,result:i};null!=o?(r.error={message:o.stack||o.message||o,code:-32e3},t(o,r)):t(null,r)})}!function t(i){n+=1;a.unshift(i);if(n>=r._providers.length)s(new Error('Request for method "'+e.method+'" not handled by any subprovider. Please check your subprovider configuration to ensure this method is handled.'));else try{var o=r._providers[n];o.handleRequest(e,t,s)}catch(e){s(e)}}()},f.prototype._setCurrentBlock=function(e){this.currentBlock=e,this.emit("block",e)}},{"./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(e,t,r){var n="undefined"!=typeof JSON?JSON:e("jsonify");t.exports=function(e,t){t||(t={}),"function"==typeof t&&(t={cmp:t});var r=t.space||"";"number"==typeof r&&(r=Array(r+1).join(" "));var a,s="boolean"==typeof t.cycles&&t.cycles,u=t.replacer||function(e,t){return t},c=t.cmp&&(a=t.cmp,function(e){return function(t,r){var n={key:t,value:e[t]},i={key:r,value:e[r]};return a(n,i)}}),f=[];return function e(t,a,h,l){var d=r?"\n"+new Array(l+1).join(r):"",p=r?": ":":";if(h&&h.toJSON&&"function"==typeof h.toJSON&&(h=h.toJSON()),void 0!==(h=u.call(t,a,h))){if("object"!=typeof h||null===h)return n.stringify(h);if(i(h)){for(var b=[],y=0;y dist/ProviderEngine.js","bundle-zero":"browserify -s ZeroClientProvider -e zero.js -t [ babelify --presets [ es2015 ] ] > dist/ZeroClientProvider.js",prepublish:"npm run build && npm run bundle",test:"node test/index.js"},version:"14.1.0"}},{}],376:[function(e,t,r){const n=e("util").inherits,i=e("ethereumjs-util"),o=i.BN,a=e("clone"),s=e("../util/rpc-cache-utils.js"),u=e("../util/stoplight.js"),c=e("./subprovider.js");function f(e){e=e||{},this._ready=new u,this.strategies={perma:new l({eth_getTransactionByHash:p,eth_getTransactionReceipt:p}),block:new d(this),fork:new d(this)}}function h(){var e=this;e.cache={};var t=setInterval(function(){e.cache={}},6e5);t.unref&&t.unref()}function l(e){this.strategy=new h,this.conditionals=e}function d(){this.cache={}}function p(e){if(!e)return!1;if(!e.blockHash)return!1;var t;return(t=e.blockHash,new o(i.toBuffer(t))).gt(new o(0))}t.exports=f,n(f,c),f.prototype.setEngine=function(e){const t=this;function r(e){var r=t.currentBlock;t.currentBlock=e,r&&(t.strategies.block.cacheRollOff(r),t.strategies.fork.cacheRollOff(r))}t.engine=e,e.once("block",function(n){t.currentBlock=n,t._ready.go(),e.on("block",r)})},f.prototype.handleRequest=function(e,t,r){const n=this;return e.skipCache?t():"eth_getBlockByNumber"===e.method&&"latest"===e.params[0]?t():void n._ready.await(function(){n._handleRequest(e,t,r)})},f.prototype._handleRequest=function(e,t,r){const n=this;var o=s.cacheTypeForPayload(e),a=this.strategies[o];if(!a)return t();if(!a.canCache(e))return t();var u,c=s.blockTagForPayload(e);c||(c="latest"),u="earliest"===c?"0x00":"latest"===c?i.bufferToHex(n.currentBlock.number):c,a.hitCheck(e,u,r,function(){t(function(t,r,n){if(t)return n();a.cacheResult(e,r,u,n)})})},h.prototype.hitCheck=function(e,t,r,n){var i,o,u,c,f=s.cacheIdentifierForPayload(e),h=this.cache[f];return h&&(i=t,o=h.blockNumber,u=parseInt(i,16),c=parseInt(o,16),(u===c?0:u>c?1:-1)>=0)?r(null,a(h.result)):n()},h.prototype.cacheResult=function(e,t,r,n){var i=s.cacheIdentifierForPayload(e);if(t){var o=a(t);this.cache[i]={blockNumber:r,result:o}}n()},h.prototype.canCache=function(e){return s.canCache(e)},l.prototype.hitCheck=function(e,t,r,n){return this.strategy.hitCheck(e,t,r,n)},l.prototype.cacheResult=function(e,t,r,n){var i=this.conditionals[e.method];i?i(t)?this.strategy.cacheResult(e,t,r,n):n():this.strategy.cacheResult(e,t,r,n)},l.prototype.canCache=function(e){return this.strategy.canCache(e)},d.prototype.getBlockCacheForPayload=function(e,t){const r=Number.parseInt(t,16);let n=this.cache[r];if(!n){const e={};this.cache[r]=e,n=e}return n},d.prototype.hitCheck=function(e,t,r,n){var i=this.getBlockCacheForPayload(e,t);if(!i)return n();var o=i[s.cacheIdentifierForPayload(e)];return o?r(null,o):n()},d.prototype.cacheResult=function(e,t,r,n){t&&(this.getBlockCacheForPayload(e,r)[s.cacheIdentifierForPayload(e)]=t);n()},d.prototype.canCache=function(e){return!!s.canCache(e)&&"pending"!==s.blockTagForPayload(e)},d.prototype.cacheRollOff=function(e){const t=this,r=i.bufferToHex(e.number),n=Number.parseInt(r,16);Object.keys(t.cache).map(Number).filter(e=>e<=n).forEach(e=>delete t.cache[e])}},{"../util/rpc-cache-utils.js":394,"../util/stoplight.js":396,"./subprovider.js":387,clone:87,"ethereumjs-util":141,util:333}],377:[function(e,t,r){const n=e("util").inherits,i=e("xtend"),o=e("./fixture.js"),a=e("../package.json").version;function s(e){var t=i({web3_clientVersion:"ProviderEngine/v"+a+"/javascript",net_listening:!0,eth_hashrate:"0x00",eth_mining:!1},e=e||{});o.call(this,t)}t.exports=s,n(s,o)},{"../package.json":375,"./fixture.js":380,util:333,xtend:423}],378:[function(e,t,r){const n=e("cross-fetch"),i=e("util").inherits,o=e("async/retry"),a=e("async/waterfall"),s=e("async/asyncify"),u=e("json-rpc-error"),c=e("promise-to-callback"),f=e("../util/create-payload.js"),h=e("./subprovider.js"),l=["Gateway timeout","ETIMEDOUT","SyntaxError"];function d(e){this.rpcUrl=e.rpcUrl,this.originHttpHeaderKey=e.originHttpHeaderKey}function p(e){const t=e.toString();return l.some(e=>t.includes(e))}t.exports=d,i(d,h),d.prototype.handleRequest=function(e,t,r){const n=this,i=e.origin,a=f(e);delete a.origin;const s={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(a)};n.originHttpHeaderKey&&i&&(s.headers[n.originHttpHeaderKey]=i),o({times:5,interval:1e3,errorFilter:p},e=>n._submitRequest(s,e),(e,t)=>{if(e&&p(e)){const t=`FetchSubprovider - cannot complete request. All retries exhausted.\nOriginal Error:\n${e.toString()}\n\n`,n=new Error(t);return r(n)}return r(e,t)})},d.prototype._submitRequest=function(e,t){const r=this.rpcUrl;c(n(r,e))((e,r)=>{if(e)return t(e);a([function(e){switch(r.status){case 405:return e(new u.MethodNotFound);case 418:return e(function(){const e=new Error("Request is being rate limited.");return new u.InternalError(e)}());case 503:case 504:return e(function(){let e="Gateway timeout. The request took too long to process. ";const t=new Error(e+="This can happen when querying logs over too wide a block range.");return new u.InternalError(t)}());default:return e()}},e=>c(r.text())(e),s(e=>JSON.parse(e)),function(e,t){if(200!==r.status)return t(new u.InternalError(e));if(e.error)return t(new u.InternalError(e.error));t(null,e.result)}],t)})}},{"../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(e,t,r){const n=e("async"),i=e("util").inherits,o=e("ethereumjs-util"),a=e("./subprovider.js"),s=e("../util/stoplight.js"),u=e("events").EventEmitter;function c(e){e=e||{};const t=this;t.filterIndex=0,t.filters={},t.filterDestroyHandlers={},t.asyncBlockHandlers={},t.asyncPendingBlockHandlers={},t._ready=new s,t._ready.setMaxListeners(e.maxFilters||25),t._ready.go(),t.pendingBlockTimeout=e.pendingBlockTimeout||4e3,t.checkForPendingBlocksActive=!1,setTimeout(function(){t.engine.on("block",function(e){t._ready.stop();var r=v(t.asyncBlockHandlers).map(function(t){return t.bind(null,e)});n.parallel(r,function(e){e&&console.error(e),t._ready.go()})})})}function f(e){u.apply(this),this.type="block",this.engine=e.engine,this.blockNumber=e.blockNumber,this.updates=[]}function h(e){u.apply(this),this.type="log",this.fromBlock=void 0!==e.fromBlock?e.fromBlock:"latest",this.toBlock=void 0!==e.toBlock?e.toBlock:"latest";var t=e.address&&(Array.isArray(e.address)?e.address:[e.address]);this.address=t&&t.map(d),this.topics=e.topics||[],this.updates=[],this.allResults=[]}function l(){u.apply(this),this.type="pendingTx",this.updates=[],this.allResults=[]}function d(e){return"0x"===e.slice(0,2)?e:"0x"+e}function p(e){return o.intToHex(e)}function b(e){return Number(e)}function y(e){return function(e){let t=o.stripHexPrefix(e);for(;"0"===t[0];)t=t.substr(1);return`0x${t}`}(e.toString("hex"))}function m(e){return e&&-1===["earliest","latest","pending"].indexOf(e)}function v(e){return Object.keys(e).map(function(t){return e[t]})}t.exports=c,i(c,a),c.prototype.handleRequest=function(e,t,r){const n=this;switch(e.method){case"eth_newBlockFilter":return void n.newBlockFilter(r);case"eth_newPendingTransactionFilter":return n.newPendingTransactionFilter(r),void n.checkForPendingBlocks();case"eth_newFilter":return void n.newLogFilter(e.params[0],r);case"eth_getFilterChanges":return void n._ready.await(function(){n.getFilterChanges(e.params[0],r)});case"eth_getFilterLogs":return void n._ready.await(function(){n.getFilterLogs(e.params[0],r)});case"eth_uninstallFilter":return void n._ready.await(function(){n.uninstallFilter(e.params[0],r)});default:return void t()}},c.prototype.newBlockFilter=function(e){const t=this;t._getBlockNumber(function(r,n){if(r)return e(r);var i=new f({blockNumber:n}),o=i.update.bind(i);t.engine.on("block",o);t.filterIndex++,t.filters[t.filterIndex]=i,t.filterDestroyHandlers[t.filterIndex]=function(){t.engine.removeListener("block",o)};var a=p(t.filterIndex);e(null,a)})},c.prototype.newLogFilter=function(e,t){const r=this;r._getBlockNumber(function(n,i){if(n)return t(n);var o=new h(e),a=o.update.bind(o);r.filterIndex++,r.asyncBlockHandlers[r.filterIndex]=function(e,t){r._logsForBlock(e,function(e,r){if(e)return t(e);a(r),t()})},r.filters[r.filterIndex]=o;var s=p(r.filterIndex);t(null,s)})},c.prototype.newPendingTransactionFilter=function(e){const t=this;var r=new l,n=r.update.bind(r);t.filterIndex++,t.asyncPendingBlockHandlers[t.filterIndex]=function(e,r){t._txHashesForBlock(e,function(e,t){if(e)return r(e);n(t),r()})},t.filters[t.filterIndex]=r,e(null,p(t.filterIndex))},c.prototype.getFilterChanges=function(e,t){var r=Number.parseInt(e,16),n=this.filters[r];if(n||console.warn("FilterSubprovider - no filter with that id:",e),!n)return t(null,[]);var i=n.getChanges();n.clearChanges(),t(null,i)},c.prototype.getFilterLogs=function(e,t){const r=this;var n=Number.parseInt(e,16),i=r.filters[n];if(i||console.warn("FilterSubprovider - no filter with that id:",e),!i)return t(null,[]);if("log"===i.type)r.emitPayload({method:"eth_getLogs",params:[{fromBlock:i.fromBlock,toBlock:i.toBlock,address:i.address,topics:i.topics}]},function(e,r){if(e)return t(e);t(null,r.result)});else{t(null,[])}},c.prototype.uninstallFilter=function(e,t){var r=Number.parseInt(e,16);if(this.filters[r]){this.filters[r].removeAllListeners();var n=this.filterDestroyHandlers[r];delete this.filters[r],delete this.asyncBlockHandlers[r],delete this.asyncPendingBlockHandlers[r],delete this.filterDestroyHandlers[r],n&&n(),t(null,!0)}else t(null,!1)},c.prototype.checkForPendingBlocks=function(){const e=this;e.checkForPendingBlocksActive||!!Object.keys(e.asyncPendingBlockHandlers).length&&(e.checkForPendingBlocksActive=!0,e.emitPayload({method:"eth_getBlockByNumber",params:["pending",!0]},function(t,r){if(t)return e.checkForPendingBlocksActive=!1,void console.error(t);e.onNewPendingBlock(r.result,function(t){t&&console.error(t),e.checkForPendingBlocksActive=!1,setTimeout(e.checkForPendingBlocks.bind(e),e.pendingBlockTimeout)})}))},c.prototype.onNewPendingBlock=function(e,t){var r=v(this.asyncPendingBlockHandlers).map(function(t){return t.bind(null,e)});n.parallel(r,t)},c.prototype._getBlockNumber=function(e){e(null,y(this.engine.currentBlock.number))},c.prototype._logsForBlock=function(e,t){var r=y(e.number);this.emitPayload({method:"eth_getLogs",params:[{fromBlock:r,toBlock:r}]},function(e,r){return e?t(e):r.error?t(r.error):void t(null,r.result)})},c.prototype._txHashesForBlock=function(e,t){var r=e.transactions;if(0===r.length)return t(null,[]);"string"==typeof r[0]?t(null,r):t(null,r.map(e=>e.hash))},i(f,u),f.prototype.update=function(e){var t="0x"+e.hash.toString("hex");this.updates.push(t),this.emit("data",e)},f.prototype.getChanges=function(){return this.updates},f.prototype.clearChanges=function(){this.updates=[]},i(h,u),h.prototype.validateLog=function(e){return!(m(this.fromBlock)&&b(this.fromBlock)>=b(e.blockNumber))&&(!(m(this.toBlock)&&b(this.toBlock)<=b(e.blockNumber))&&(!(this.address&&!this.address.map(e=>e.toLowerCase()).includes(e.address.toLowerCase()))&&this.topics.reduce(function(t,r,n){if(!t)return!1;if(!r)return!0;var i=e.topics[n];return!!i&&(Array.isArray(r)?r:[r]).filter(function(e){return i.toLowerCase()===e.toLowerCase()}).length>0},!0)))},h.prototype.update=function(e){const t=this;var r=[];e.forEach(function(e){t.validateLog(e)&&(r.push(e),t.updates.push(e),t.allResults.push(e))}),r.length>0&&t.emit("data",r)},h.prototype.getChanges=function(){return this.updates},h.prototype.getAllResults=function(){return this.allResults},h.prototype.clearChanges=function(){this.updates=[]},i(l,u),l.prototype.validateUnique=function(e){return-1===this.allResults.indexOf(e)},l.prototype.update=function(e){const t=this;var r=[];e.forEach(function(e){t.validateUnique(e)&&(r.push(e),t.updates.push(e),t.allResults.push(e))}),r.length>0&&t.emit("data",r)},l.prototype.getChanges=function(){return this.updates},l.prototype.getAllResults=function(){return this.allResults},l.prototype.clearChanges=function(){this.updates=[]}},{"../util/stoplight.js":396,"./subprovider.js":387,async:21,"ethereumjs-util":141,events:157,util:333}],380:[function(e,t,r){const n=e("util").inherits,i=e("./subprovider.js");function o(e){e=e||{},this.staticResponses=e}t.exports=o,n(o,i),o.prototype.handleRequest=function(e,t,r){var n=this.staticResponses[e.method];"function"==typeof n?n(e,t,r):void 0!==n?setTimeout(()=>r(null,n)):t()}},{"./subprovider.js":387,util:333}],381:[function(e,t,r){const n=e("async/waterfall"),i=e("async/parallel"),o=e("util").inherits,a=e("ethereumjs-util"),s=e("eth-sig-util"),u=e("xtend"),c=e("semaphore"),f=e("./subprovider.js"),h=e("../util/estimate-gas.js"),l=/^[0-9A-Fa-f]+$/g;function d(e){this.nonceLock=c(1),e.getAccounts&&(this.getAccounts=e.getAccounts),e.processTransaction&&(this.processTransaction=e.processTransaction),e.processMessage&&(this.processMessage=e.processMessage),e.processPersonalMessage&&(this.processPersonalMessage=e.processPersonalMessage),e.processTypedMessage&&(this.processTypedMessage=e.processTypedMessage),this.approveTransaction=e.approveTransaction||this.autoApprove,this.approveMessage=e.approveMessage||this.autoApprove,this.approvePersonalMessage=e.approvePersonalMessage||this.autoApprove,this.approveTypedMessage=e.approveTypedMessage||this.autoApprove,e.signTransaction&&(this.signTransaction=e.signTransaction||y("signTransaction")),e.signMessage&&(this.signMessage=e.signMessage||y("signMessage")),e.signPersonalMessage&&(this.signPersonalMessage=e.signPersonalMessage||y("signPersonalMessage")),e.signTypedMessage&&(this.signTypedMessage=e.signTypedMessage||y("signTypedMessage")),e.recoverPersonalSignature&&(this.recoverPersonalSignature=e.recoverPersonalSignature),e.publishTransaction&&(this.publishTransaction=e.publishTransaction)}function p(e){return e.toLowerCase()}function b(e){return"string"==typeof e&&("0x"===e.slice(0,2)&&e.slice(2).match(l))}function y(e){return function(t,r){r(new Error('ProviderEngine - HookedWalletSubprovider - Must provide "'+e+'" fn in constructor options'))}}t.exports=d,o(d,f),d.prototype.handleRequest=function(e,t,r){const i=this;let o,s,c,f,h;switch(i._parityRequests={},i._parityRequestCount=0,e.method){case"eth_coinbase":return void i.getAccounts(function(e,t){if(e)return r(e);let n=t[0]||null;r(null,n)});case"eth_accounts":return void i.getAccounts(function(e,t){if(e)return r(e);r(null,t)});case"eth_sendTransaction":return o=e.params[0],void n([e=>i.validateTransaction(o,e),e=>i.processTransaction(o,e)],r);case"eth_signTransaction":return o=e.params[0],void n([e=>i.validateTransaction(o,e),e=>i.processSignTransaction(o,e)],r);case"eth_sign":return h=e.params[0],f=e.params[1],c=e.params[2]||{},s=u(c,{from:h,data:f}),void n([e=>i.validateMessage(s,e),e=>i.processMessage(s,e)],r);case"personal_sign":const l=e.params[0];if(function(e){const t=a.addHexPrefix(e);return!a.isValidAddress(t)&&b(e)}(e.params[1])&&function(e){const t=a.addHexPrefix(e);return a.isValidAddress(t)}(l)){let t="The eth_personalSign method requires params ordered ";t+="[message, address]. This was previously handled incorrectly, ",t+="and has been corrected automatically. ",t+="Please switch this param order for smooth behavior in the future.",console.warn(t),h=e.params[0],f=e.params[1]}else f=e.params[0],h=e.params[1];return c=e.params[2]||{},s=u(c,{from:h,data:f}),void n([e=>i.validatePersonalMessage(s,e),e=>i.processPersonalMessage(s,e)],r);case"personal_ecRecover":f=e.params[0];let d=e.params[1];return c=e.params[2]||{},s=u(c,{sig:d,data:f}),void i.recoverPersonalSignature(s,r);case"eth_signTypedData":return f=e.params[0],h=e.params[1],c=e.params[2]||{},s=u(c,{from:h,data:f}),void n([e=>i.validateTypedMessage(s,e),e=>i.processTypedMessage(s,e)],r);case"parity_postTransaction":return o=e.params[0],void i.parityPostTransaction(o,r);case"parity_postSign":return h=e.params[0],f=e.params[1],void i.parityPostSign(h,f,r);case"parity_checkRequest":const p=e.params[0];return void i.parityCheckRequest(p,r);case"parity_defaultAccount":return void i.getAccounts(function(e,t){if(e)return r(e);const n=t[0]||null;r(null,n)});default:return void t()}},d.prototype.getAccounts=function(e){e(null,[])},d.prototype.processTransaction=function(e,t){const r=this;n([t=>r.approveTransaction(e,t),(e,t)=>r.checkApproval("transaction",e,t),t=>r.finalizeAndSubmitTx(e,t)],t)},d.prototype.processSignTransaction=function(e,t){const r=this;n([t=>r.approveTransaction(e,t),(e,t)=>r.checkApproval("transaction",e,t),t=>r.finalizeTx(e,t)],t)},d.prototype.processMessage=function(e,t){const r=this;n([t=>r.approveMessage(e,t),(e,t)=>r.checkApproval("message",e,t),t=>r.signMessage(e,t)],t)},d.prototype.processPersonalMessage=function(e,t){const r=this;n([t=>r.approvePersonalMessage(e,t),(e,t)=>r.checkApproval("message",e,t),t=>r.signPersonalMessage(e,t)],t)},d.prototype.processTypedMessage=function(e,t){const r=this;n([t=>r.approveTypedMessage(e,t),(e,t)=>r.checkApproval("message",e,t),t=>r.signTypedMessage(e,t)],t)},d.prototype.autoApprove=function(e,t){t(null,!0)},d.prototype.checkApproval=function(e,t,r){r(t?null:new Error("User denied "+e+" signature."))},d.prototype.parityPostTransaction=function(e,t){const r=this,n=`0x${r._parityRequestCount.toString(16)}`;r._parityRequestCount++,r.emitPayload({method:"eth_sendTransaction",params:[e]},function(e,t){if(e)return void(r._parityRequests[n]={error:e});const i=t.result;r._parityRequests[n]=i}),t(null,n)},d.prototype.parityPostSign=function(e,t,r){const n=this,i=`0x${n._parityRequestCount.toString(16)}`;n._parityRequestCount++,n.emitPayload({method:"eth_sign",params:[e,t]},function(e,t){if(e)return void(n._parityRequests[i]={error:e});const r=t.result;n._parityRequests[i]=r}),r(null,i)},d.prototype.parityCheckRequest=function(e,t){const r=this._parityRequests[e]||null;return r?r.error?t(r.error):void t(null,r):t(null,null)},d.prototype.recoverPersonalSignature=function(e,t){let r;try{r=s.recoverPersonalSignature(e)}catch(e){return t(e)}t(null,r)},d.prototype.validateTransaction=function(e,t){if(void 0===e.from)return t(new Error("Undefined address - from address required to sign transaction."));this.validateSender(e.from,function(r,n){return r?t(r):n?void t():t(new Error(`Unknown address - unable to sign transaction for this address: "${e.from}"`))})},d.prototype.validateMessage=function(e,t){if(void 0===e.from)return t(new Error("Undefined address - from address required to sign message."));this.validateSender(e.from,function(r,n){return r?t(r):n?void t():t(new Error(`Unknown address - unable to sign message for this address: "${e.from}"`))})},d.prototype.validatePersonalMessage=function(e,t){return void 0===e.from?t(new Error("Undefined address - from address required to sign personal message.")):void 0===e.data?t(new Error("Undefined message - message required to sign personal message.")):b(e.data)?void this.validateSender(e.from,function(r,n){return r?t(r):n?void t():t(new Error(`Unknown address - unable to sign message for this address: "${e.from}"`))}):t(new Error("HookedWalletSubprovider - validateMessage - message was not encoded as hex."))},d.prototype.validateTypedMessage=function(e,t){return void 0===e.from?t(new Error("Undefined address - from address required to sign typed data.")):void 0===e.data?t(new Error("Undefined data - message required to sign typed data.")):void this.validateSender(e.from,function(r,n){return r?t(r):n?void t():t(new Error(`Unknown address - unable to sign message for this address: "${e.from}"`))})},d.prototype.validateSender=function(e,t){if(!e)return t(null,!1);this.getAccounts(function(r,n){if(r)return t(r);const i=-1!==n.map(p).indexOf(e.toLowerCase());t(null,i)})},d.prototype.finalizeAndSubmitTx=function(e,t){const r=this;r.nonceLock.take(function(){n([r.fillInTxExtras.bind(r,e),r.signTransaction.bind(r),r.publishTransaction.bind(r)],function(e,n){if(r.nonceLock.leave(),e)return t(e);t(null,n)})})},d.prototype.finalizeTx=function(e,t){const r=this;r.nonceLock.take(function(){n([r.fillInTxExtras.bind(r,e),r.signTransaction.bind(r)],function(n,i){if(r.nonceLock.leave(),n)return t(n);t(null,{raw:i,tx:e})})})},d.prototype.publishTransaction=function(e,t){this.emitPayload({method:"eth_sendRawTransaction",params:[e]},function(e,r){if(e)return t(e);t(null,r.result)})},d.prototype.fillInTxExtras=function(e,t){const r=this,n=e.from,o={};void 0===e.gasPrice&&(o.gasPrice=r.emitPayload.bind(r,{method:"eth_gasPrice",params:[]})),void 0===e.nonce&&(o.nonce=r.emitPayload.bind(r,{method:"eth_getTransactionCount",params:[n,"pending"]})),void 0===e.gas&&(o.gas=h.bind(null,r.engine,function(e){return{from:e.from,to:e.to,value:e.value,data:e.data,gas:e.gas,gasPrice:e.gasPrice,nonce:e.nonce}}(e))),i(o,function(r,n){if(r)return t(r);const i={};n.gasPrice&&(i.gasPrice=n.gasPrice.result),n.nonce&&(i.nonce=n.nonce.result),n.gas&&(i.gas=n.gas),t(null,u(e,i))})}},{"../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(e,t,r){const n=e("../util/rpc-cache-utils.js").cacheIdentifierForPayload,i=e("./subprovider.js");t.exports=class extends i{constructor(e){super(),this.inflightRequests={}}addEngine(e){this.engine=e}handleRequest(e,t,r){const i=n(e,{includeBlockRef:!0});if(!i)return t();let o=this.inflightRequests[i];o?o.push(r):(o=[],this.inflightRequests[i]=o,t((e,t,r)=>{delete this.inflightRequests[i],o.forEach(r=>r(e,t)),r(e,t)}))}}},{"../util/rpc-cache-utils.js":394,"./subprovider.js":387}],383:[function(e,t,r){const n=e("eth-json-rpc-infura/src/createProvider"),i=e("./provider.js");t.exports=class extends i{constructor(e={}){super(n(e))}}},{"./provider.js":385,"eth-json-rpc-infura/src/createProvider":129}],384:[function(e,t,r){(function(r){const n=e("util").inherits,i=e("ethereumjs-tx"),o=e("ethereumjs-util"),a=e("./subprovider.js"),s=e("../util/rpc-cache-utils").blockTagForPayload;function u(e){this.nonceCache={}}t.exports=u,n(u,a),u.prototype.handleRequest=function(e,t,n){const a=this;switch(e.method){case"eth_getTransactionCount":var u=s(e),c=e.params[0].toLowerCase(),f=a.nonceCache[c];return void("pending"===u?f?n(null,f):t(function(e,t,r){if(e)return r();void 0===a.nonceCache[c]&&(a.nonceCache[c]=t),r()}):t());case"eth_sendRawTransaction":return void t(function(t,n,s){if(t)return s();var u=e.params[0],c=(o.stripHexPrefix(u),new r(o.stripHexPrefix(u),"hex"),new i(new r(o.stripHexPrefix(u),"hex"))),f="0x"+c.getSenderAddress().toString("hex").toLowerCase(),h=o.bufferToInt(c.nonce),l=(++h).toString(16);l.length%2&&(l="0"+l),l="0x"+l,a.nonceCache[f]=l,s()});default:return void t()}}}).call(this,e("buffer").Buffer)},{"../util/rpc-cache-utils":394,"./subprovider.js":387,buffer:84,"ethereumjs-tx":140,"ethereumjs-util":141,util:333}],385:[function(e,t,r){const n=e("util").inherits,i=e("./subprovider.js");function o(e){if(!e)throw new Error("ProviderSubprovider - no provider specified");if(!e.sendAsync)throw new Error("ProviderSubprovider - specified provider does not have a sendAsync method");this.provider=e}t.exports=o,n(o,i),o.prototype.handleRequest=function(e,t,r){this.provider.sendAsync(e,function(e,t){return e?r(e):t.error?r(new Error(t.error.message)):void r(null,t.result)})}},{"./subprovider.js":387,util:333}],386:[function(e,t,r){const n=e("util").inherits,i=e("./subprovider.js"),o=(e("xtend"),e("ethereumjs-util"));function a(e){}t.exports=a,n(a,i),a.prototype.handleRequest=function(e,t,r){var n=e.params[0];if("object"==typeof n&&!Array.isArray(n)){var i=function(e){return s.reduce(function(t,r){return r in e&&(Array.isArray(e[r])?t[r]=e[r].map(function(e){return u(e)}):t[r]=u(e[r])),t},{})}(n);e.params[0]=i}t()};var s=["from","to","value","data","gas","gasPrice","nonce","fromBlock","toBlock","address","topics"];function u(e){switch(e){case"latest":case"pending":case"earliest":return e;default:return"string"==typeof e?o.addHexPrefix(e.toLowerCase()):e}}},{"./subprovider.js":387,"ethereumjs-util":141,util:333,xtend:423}],387:[function(e,t,r){const n=e("../util/create-payload.js");function i(){}t.exports=i,i.prototype.setEngine=function(e){const t=this;t.engine=e,e.on("block",function(e){t.currentBlock=e})},i.prototype.handleRequest=function(e,t,r){throw new Error("Subproviders should override `handleRequest`.")},i.prototype.emitPayload=function(e,t){this.engine.sendAsync(n(e),t)}},{"../util/create-payload.js":391}],388:[function(e,t,r){const n=e("events").EventEmitter,i=e("./filters.js"),o=e("../util/rpc-hex-encoding.js"),a=e("util").inherits,s=e("ethereumjs-util");function u(e){e=e||{},n.apply(this,Array.prototype.slice.call(arguments)),i.apply(this,[e]),this.subscriptions={}}a(u,i),Object.assign(u.prototype,n.prototype),u.prototype.constructor=u,u.prototype.eth_subscribe=function(e,t){const r=this;let n=()=>{},i=e.params[0];switch(i){case"logs":let o=e.params[1];n=r.newLogFilter.bind(r,o);break;case"newPendingTransactions":n=r.newPendingTransactionFilter.bind(r);break;case"newHeads":n=r.newBlockFilter.bind(r);break;case"syncing":default:return void t(new Error("unsupported subscription type"))}n(function(e,n){if(e)return t(e);const o=Number.parseInt(n,16);r.subscriptions[o]=i,r.filters[o].on("data",function(e){Array.isArray(e)||(e=[e]);var t=r._notificationHandler.bind(r,n,i);e.forEach(t),r.filters[o].clearChanges()}),"newPendingTransactions"===i&&r.checkForPendingBlocks(),t(null,n)})},u.prototype.eth_unsubscribe=function(e,t){const r=this;let n=e.params[0];const i=Number.parseInt(n,16);if(r.subscriptions[i]){r.subscriptions[i];r.uninstallFilter(n,function(e,n){delete r.subscriptions[i],t(e,n)})}else t(new Error(`Subscription ID ${n} not found.`))},u.prototype._notificationHandler=function(e,t,r){const n=this;"newHeads"===t&&(r=n._notificationResultFromBlock(r)),n.emit("data",null,{jsonrpc:"2.0",method:"eth_subscription",params:{subscription:e,result:r}})},u.prototype._notificationResultFromBlock=function(e){return{hash:s.bufferToHex(e.hash),parentHash:s.bufferToHex(e.parentHash),sha3Uncles:s.bufferToHex(e.sha3Uncles),miner:s.bufferToHex(e.miner),stateRoot:s.bufferToHex(e.stateRoot),transactionsRoot:s.bufferToHex(e.transactionsRoot),receiptsRoot:s.bufferToHex(e.receiptsRoot),logsBloom:s.bufferToHex(e.logsBloom),difficulty:o.intToQuantityHex(s.bufferToInt(e.difficulty)),number:o.intToQuantityHex(s.bufferToInt(e.number)),gasLimit:o.intToQuantityHex(s.bufferToInt(e.gasLimit)),gasUsed:o.intToQuantityHex(s.bufferToInt(e.gasUsed)),nonce:e.nonce?s.bufferToHex(e.nonce):null,mixHash:s.bufferToHex(e.mixHash),timestamp:o.intToQuantityHex(s.bufferToInt(e.timestamp)),extraData:s.bufferToHex(e.extraData)}},u.prototype.handleRequest=function(e,t,r){switch(e.method){case"eth_subscribe":this.eth_subscribe(e,r);break;case"eth_unsubscribe":this.eth_unsubscribe(e,r);break;default:i.prototype.handleRequest.apply(this,Array.prototype.slice.call(arguments))}},t.exports=u},{"../util/rpc-hex-encoding.js":395,"./filters.js":379,"ethereumjs-util":141,events:157,util:333}],389:[function(e,t,r){(function(r){const n=e("backoff"),i=e("events"),o=(e("util").inherits,r.WebSocket||e("ws")),a=e("./subprovider"),s=e("../util/create-payload");class u extends a{constructor({rpcUrl:e,debug:t,origin:r}){super(),i.call(this),Object.defineProperties(this,{_backoff:{value:n.exponential({randomisationFactor:.2,maxDelay:5e3})},_connectTime:{value:null,writable:!0},_log:{value:t?(...e)=>console.info.apply(console,["[WSProvider]",...e]):()=>{}},_origin:{value:r},_pendingRequests:{value:new Map},_socket:{value:null,writable:!0},_unhandledRequests:{value:[]},_url:{value:e}}),this._handleSocketClose=this._handleSocketClose.bind(this),this._handleSocketMessage=this._handleSocketMessage.bind(this),this._handleSocketOpen=this._handleSocketOpen.bind(this),this._backoff.on("ready",()=>{this._openSocket()}),this._openSocket()}handleRequest(e,t,r){if(!this._socket||this._socket.readyState!==o.OPEN)return this._unhandledRequests.push(Array.from(arguments)),void this._log("Socket not open. Request queued.");this._pendingRequests.set(e.id,[e,r]);const n=s(e);delete n.origin,this._socket.send(JSON.stringify(n)),this._log(`Sent: ${n.method} #${n.id}`)}_handleSocketClose({reason:e,code:t}){this._log(`Socket closed, code ${t} (${e||"no reason"})`),this._connectTime&&Date.now()-this._connectTime>5e3&&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(e){let t;try{t=JSON.parse(e.data)}catch(e){return void this._log("Received a message that is not valid JSON:",t)}if(void 0===t.id)return this.emit("data",null,t);if(!this._pendingRequests.has(t.id))return;const[r,n]=this._pendingRequests.get(t.id);if(this._pendingRequests.delete(t.id),this._log(`Received: ${r.method} #${t.id}`),t.error)return n(new Error(t.error.message));n(null,t.result)}_handleSocketOpen(){this._log("Socket open."),this._connectTime=Date.now(),this._pendingRequests.forEach(([e,t])=>{this._unhandledRequests.push([e,null,t])}),this._pendingRequests.clear(),this._unhandledRequests.splice(0,this._unhandledRequests.length).forEach(e=>{this.handleRequest.apply(this,e)})}_openSocket(){this._log("Opening socket..."),this._socket=new o(this._url,null,{origin:this._origin}),this._socket.addEventListener("close",this._handleSocketClose),this._socket.addEventListener("message",this._handleSocketMessage),this._socket.addEventListener("open",this._handleSocketOpen)}}Object.assign(u.prototype,i.prototype),t.exports=u}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../util/create-payload":391,"./subprovider":387,backoff:45,events:157,util:333,ws:55}],390:[function(e,t,r){t.exports=function(e,t){if(!e)throw t||"Assertion failed"}},{}],391:[function(e,t,r){const n=e("./random-id.js"),i=e("xtend");t.exports=function(e){return i({id:n(),jsonrpc:"2.0",params:[]},e)}},{"./random-id.js":393,xtend:423}],392:[function(e,t,r){const n=e("./create-payload.js");t.exports=function(e,t,r){e.sendAsync(n({method:"eth_estimateGas",params:[t]}),function(e,t){if(e)return"no contract code at given address"===e.message?r(null,"0xcf08"):r(e);r(null,t.result)})}},{"./create-payload.js":391}],393:[function(e,t,r){const n=3;t.exports=function(){var e=(new Date).getTime()*Math.pow(10,n),t=Math.floor(Math.random()*Math.pow(10,n));return e+t}},{}],394:[function(e,t,r){const n=e("json-stable-stringify");function i(e){return"never"!==s(e)}function o(e){var t=a(e);return t>=e.params.length?e.params:"eth_getBlockByNumber"===e.method?e.params.slice(1):e.params.slice(0,t)}function a(e){switch(e.method){case"eth_getStorageAt":return 2;case"eth_getBalance":case"eth_getCode":case"eth_getTransactionCount":case"eth_call":case"eth_estimateGas":return 1;case"eth_getBlockByNumber":return 0;default:return}}function s(e){switch(e.method){case"web3_clientVersion":case"web3_sha3":case"eth_protocolVersion":case"eth_getBlockTransactionCountByHash":case"eth_getUncleCountByBlockHash":case"eth_getCode":case"eth_getBlockByHash":case"eth_getTransactionByHash":case"eth_getTransactionByBlockHashAndIndex":case"eth_getTransactionReceipt":case"eth_getUncleByBlockHashAndIndex":case"eth_getCompilers":case"eth_compileLLL":case"eth_compileSolidity":case"eth_compileSerpent":case"shh_version":return"perma";case"eth_getBlockByNumber":case"eth_getBlockTransactionCountByNumber":case"eth_getUncleCountByBlockNumber":case"eth_getTransactionByBlockNumberAndIndex":case"eth_getUncleByBlockNumberAndIndex":return"fork";case"eth_gasPrice":case"eth_blockNumber":case"eth_getBalance":case"eth_getStorageAt":case"eth_getTransactionCount":case"eth_call":case"eth_estimateGas":case"eth_getFilterLogs":case"eth_getLogs":case"net_peerCount":return"block";case"net_version":case"net_peerCount":case"net_listening":case"eth_syncing":case"eth_sign":case"eth_coinbase":case"eth_mining":case"eth_hashrate":case"eth_accounts":case"eth_sendTransaction":case"eth_sendRawTransaction":case"eth_newFilter":case"eth_newBlockFilter":case"eth_newPendingTransactionFilter":case"eth_uninstallFilter":case"eth_getFilterChanges":case"eth_getWork":case"eth_submitWork":case"eth_submitHashrate":case"db_putString":case"db_getString":case"db_putHex":case"db_getHex":case"shh_post":case"shh_newIdentity":case"shh_hasIdentity":case"shh_newGroup":case"shh_addToGroup":case"shh_newFilter":case"shh_uninstallFilter":case"shh_getFilterChanges":case"shh_getMessages":return"never"}}t.exports={cacheIdentifierForPayload:function(e,t={}){if(!i(e))return null;const{includeBlockRef:r}=t,a=r?e.params:o(e);return e.method+":"+n(a)},canCache:i,blockTagForPayload:function(e){var t=a(e);if(t>=e.params.length)return null;return e.params[t]},paramsWithoutBlockTag:o,blockTagParamIndex:a,cacheTypeForPayload:s}},{"json-stable-stringify":374}],395:[function(e,t,r){(function(r){const n=e("ethereumjs-util"),i=e("./assert.js");t.exports={intToQuantityHex:function(e){i("number"==typeof e&&e===Math.floor(e),"intToQuantityHex arg must be an integer");var t=n.toBuffer(e).toString("hex");"0"===t[0]&&(t=t.substring(1));return n.addHexPrefix(t)},quantityHexToInt:function(e){i("string"==typeof e,"arg to quantityHexToInt must be a string");var t=n.stripHexPrefix(e);t.length%2!=0&&(t="0"+t);var o=new r(t,"hex");return n.bufferToInt(o)}}}).call(this,e("buffer").Buffer)},{"./assert.js":390,buffer:84,"ethereumjs-util":141}],396:[function(e,t,r){const n=e("events").EventEmitter,i=e("util").inherits;function o(){n.call(this),this.isLocked=!0}t.exports=o,i(o,n),o.prototype.go=function(){this.isLocked=!1,this.emit("unlock")},o.prototype.stop=function(){this.isLocked=!0,this.emit("lock")},o.prototype.await=function(e){const t=this;t.isLocked?t.once("unlock",e):setTimeout(e)}},{events:157,util:333}],397:[function(e,t,r){const n=e("./index.js"),i=e("./subproviders/default-fixture.js"),o=e("./subproviders/nonce-tracker.js"),a=e("./subproviders/cache.js"),s=e("./subproviders/filters.js"),u=e("./subproviders/subscriptions"),c=e("./subproviders/inflight-cache"),f=e("./subproviders/hooked-wallet.js"),h=e("./subproviders/sanitizer.js"),l=e("./subproviders/infura.js"),d=e("./subproviders/fetch.js"),p=e("./subproviders/websocket.js");t.exports=function(e={}){const t=function({rpcUrl:e}){if(!e)return;switch(e.split(":")[0].toLowerCase()){case"http":case"https":return"http";case"ws":case"wss":return"ws";default:throw new Error(`ProviderEngine - unrecognized protocol in "${e}"`)}}(e),r=new n(e.engineParams),b=new i(e.static);r.addProvider(b),r.addProvider(new o);const y=new h;r.addProvider(y);const m=new a;if(r.addProvider(m),"ws"===t){const e=new s;r.addProvider(e)}else{const e=new u;e.on("data",(e,t)=>{r.emit("data",e,t)}),r.addProvider(e)}const v=new c;r.addProvider(v);const g=new f({getAccounts:e.getAccounts,processTransaction:e.processTransaction,approveTransaction:e.approveTransaction,signTransaction:e.signTransaction,publishTransaction:e.publishTransaction,processMessage:e.processMessage,approveMessage:e.approveMessage,signMessage:e.signMessage,processPersonalMessage:e.processPersonalMessage,processTypedMessage:e.processTypedMessage,approvePersonalMessage:e.approvePersonalMessage,approveTypedMessage:e.approveTypedMessage,signPersonalMessage:e.signPersonalMessage,signTypedMessage:e.signTypedMessage,personalRecoverSigner:e.personalRecoverSigner});r.addProvider(g);const w=e.dataSubprovider||function(e,t){const{rpcUrl:r,debug:n}=t;if(!e)return new l;if("http"===e)return new d({rpcUrl:r,debug:n});if("ws"===e)return new p({rpcUrl:r,debug:n});throw new Error(`ProviderEngine - unrecognized connectionType "${e}"`)}(t,e);"ws"===t&&w.on("data",(e,t)=>{r.emit("data",e,t)});r.addProvider(w),e.stopped||r.start();return r}},{"./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(e,t,r){var n=e("web3-core-helpers").errors,i=e("xhr2-cookies").XMLHttpRequest,o=e("http"),a=e("https"),s=function(e,t){t=t||{},this.host=e||"http://localhost:8545","https"===this.host.substring(0,5)?this.httpsAgent=new a.Agent({keepAlive:!0}):this.httpAgent=new o.Agent({keepAlive:!0}),this.timeout=t.timeout||0,this.headers=t.headers,this.connected=!1};s.prototype._prepareRequest=function(){var e=new i;return e.nodejsSet({httpsAgent:this.httpsAgent,httpAgent:this.httpAgent}),e.open("POST",this.host,!0),e.setRequestHeader("Content-Type","application/json"),e.timeout=this.timeout&&1!==this.timeout?this.timeout:0,e.withCredentials=!0,this.headers&&this.headers.forEach(function(t){e.setRequestHeader(t.name,t.value)}),e},s.prototype.send=function(e,t){var r=this,i=this._prepareRequest();i.onreadystatechange=function(){if(4===i.readyState&&1!==i.timeout){var e=i.responseText,o=null;try{e=JSON.parse(e)}catch(e){o=n.InvalidResponse(i.responseText)}r.connected=!0,t(o,e)}},i.ontimeout=function(){r.connected=!1,t(n.ConnectionTimeout(this.timeout))};try{i.send(JSON.stringify(e))}catch(e){this.connected=!1,t(n.InvalidConnection(this.host))}},s.prototype.disconnect=function(){},t.exports=s},{http:312,https:175,"web3-core-helpers":338,"xhr2-cookies":418}],399:[function(e,t,r){"use strict";var n=e("underscore"),i=e("web3-core-helpers").errors,o=e("oboe"),a=function(e,t){var r=this;this.responseCallbacks={},this.notificationCallbacks=[],this.path=e,this.connected=!1,this.connection=t.connect({path:this.path}),this.addDefaultEvents();var i=function(e){var t=null;n.isArray(e)?e.forEach(function(e){r.responseCallbacks[e.id]&&(t=e.id)}):t=e.id,t||-1===e.method.indexOf("_subscription")?r.responseCallbacks[t]&&(r.responseCallbacks[t](null,e),delete r.responseCallbacks[t]):r.notificationCallbacks.forEach(function(t){n.isFunction(t)&&t(e)})};"Socket"===t.constructor.name?o(this.connection).done(i):this.connection.on("data",function(e){r._parseResponse(e.toString()).forEach(i)})};a.prototype.addDefaultEvents=function(){var e=this;this.connection.on("connect",function(){e.connected=!0}),this.connection.on("close",function(){e.connected=!1}),this.connection.on("error",function(){e._timeout()}),this.connection.on("end",function(){e._timeout()}),this.connection.on("timeout",function(){e._timeout()})},a.prototype._parseResponse=function(e){var t=this,r=[];return e.replace(/\}[\n\r]?\{/g,"}|--|{").replace(/\}\][\n\r]?\[\{/g,"}]|--|[{").replace(/\}[\n\r]?\[\{/g,"}|--|[{").replace(/\}\][\n\r]?\{/g,"}]|--|{").split("|--|").forEach(function(e){t.lastChunk&&(e=t.lastChunk+e);var n=null;try{n=JSON.parse(e)}catch(r){return t.lastChunk=e,clearTimeout(t.lastChunkTimeout),void(t.lastChunkTimeout=setTimeout(function(){throw t._timeout(),i.InvalidResponse(e)},15e3))}clearTimeout(t.lastChunkTimeout),t.lastChunk=null,n&&r.push(n)}),r},a.prototype._addResponseCallback=function(e,t){var r=e.id||e[0].id,n=e.method||e[0].method;this.responseCallbacks[r]=t,this.responseCallbacks[r].method=n},a.prototype._timeout=function(){for(var e in this.responseCallbacks)this.responseCallbacks.hasOwnProperty(e)&&(this.responseCallbacks[e](i.InvalidConnection("on IPC")),delete this.responseCallbacks[e])},a.prototype.reconnect=function(){this.connection.connect({path:this.path})},a.prototype.send=function(e,t){this.connection.writable||this.connection.connect({path:this.path}),this.connection.write(JSON.stringify(e)),this._addResponseCallback(e,t)},a.prototype.on=function(e,t){if("function"!=typeof t)throw new Error("The second parameter callback must be a function.");switch(e){case"data":this.notificationCallbacks.push(t);break;default:this.connection.on(e,t)}},a.prototype.once=function(e,t){if("function"!=typeof t)throw new Error("The second parameter callback must be a function.");this.connection.once(e,t)},a.prototype.removeListener=function(e,t){var r=this;switch(e){case"data":this.notificationCallbacks.forEach(function(e,n){e===t&&r.notificationCallbacks.splice(n,1)});break;default:this.connection.removeListener(e,t)}},a.prototype.removeAllListeners=function(e){switch(e){case"data":this.notificationCallbacks=[];break;default:this.connection.removeAllListeners(e)}},a.prototype.reset=function(){this._timeout(),this.notificationCallbacks=[],this.connection.removeAllListeners("error"),this.connection.removeAllListeners("end"),this.connection.removeAllListeners("timeout"),this.addDefaultEvents()},t.exports=a},{oboe:239,underscore:325,"web3-core-helpers":338}],400:[function(e,t,r){(function(r){"use strict";var n=e("underscore"),i=e("web3-core-helpers").errors,o=null,a=null,s=null;if("undefined"!=typeof window&&void 0!==window.WebSocket)o=function(e,t){return new window.WebSocket(e,t)},a=btoa,s=function(e){return new URL(e)};else{o=e("websocket").w3cwebsocket,a=function(e){return r(e).toString("base64")};var u=e("url");if(u.URL){var c=u.URL;s=function(e){return new c(e)}}else s=e("url").parse}var f=function(e,t){var r=this;this.responseCallbacks={},this.notificationCallbacks=[],t=t||{},this._customTimeout=t.timeout;var i=s(e),u=t.headers||{},c=t.protocol||void 0;i.username&&i.password&&(u.authorization="Basic "+a(i.username+":"+i.password));var f=t.clientConfig||void 0;i.auth&&(u.authorization="Basic "+a(i.auth)),this.connection=new o(e,c,void 0,u,void 0,f),this.addDefaultEvents(),this.connection.onmessage=function(e){var t="string"==typeof e.data?e.data:"";r._parseResponse(t).forEach(function(e){var t=null;n.isArray(e)?e.forEach(function(e){r.responseCallbacks[e.id]&&(t=e.id)}):t=e.id,!t&&e&&e.method&&-1!==e.method.indexOf("_subscription")?r.notificationCallbacks.forEach(function(t){n.isFunction(t)&&t(e)}):r.responseCallbacks[t]&&(r.responseCallbacks[t](null,e),delete r.responseCallbacks[t])})},Object.defineProperty(this,"connected",{get:function(){return this.connection&&this.connection.readyState===this.connection.OPEN},enumerable:!0})};f.prototype.addDefaultEvents=function(){var e=this;this.connection.onerror=function(){e._timeout()},this.connection.onclose=function(){e._timeout(),e.reset()}},f.prototype._parseResponse=function(e){var t=this,r=[];return e.replace(/\}[\n\r]?\{/g,"}|--|{").replace(/\}\][\n\r]?\[\{/g,"}]|--|[{").replace(/\}[\n\r]?\[\{/g,"}|--|[{").replace(/\}\][\n\r]?\{/g,"}]|--|{").split("|--|").forEach(function(e){t.lastChunk&&(e=t.lastChunk+e);var n=null;try{n=JSON.parse(e)}catch(r){return t.lastChunk=e,clearTimeout(t.lastChunkTimeout),void(t.lastChunkTimeout=setTimeout(function(){throw t._timeout(),i.InvalidResponse(e)},15e3))}clearTimeout(t.lastChunkTimeout),t.lastChunk=null,n&&r.push(n)}),r},f.prototype._addResponseCallback=function(e,t){var r=e.id||e[0].id,n=e.method||e[0].method;this.responseCallbacks[r]=t,this.responseCallbacks[r].method=n;var o=this;this._customTimeout&&setTimeout(function(){o.responseCallbacks[r]&&(o.responseCallbacks[r](i.ConnectionTimeout(o._customTimeout)),delete o.responseCallbacks[r])},this._customTimeout)},f.prototype._timeout=function(){for(var e in this.responseCallbacks)this.responseCallbacks.hasOwnProperty(e)&&(this.responseCallbacks[e](i.InvalidConnection("on WS")),delete this.responseCallbacks[e])},f.prototype.send=function(e,t){var r=this;if(this.connection.readyState!==this.connection.CONNECTING){if(this.connection.readyState!==this.connection.OPEN)return console.error("connection not open on send()"),"function"==typeof this.connection.onerror?this.connection.onerror(new Error("connection not open")):console.error("no error callback"),void t(new Error("connection not open"));this.connection.send(JSON.stringify(e)),this._addResponseCallback(e,t)}else setTimeout(function(){r.send(e,t)},10)},f.prototype.on=function(e,t){if("function"!=typeof t)throw new Error("The second parameter callback must be a function.");switch(e){case"data":this.notificationCallbacks.push(t);break;case"connect":this.connection.onopen=t;break;case"end":this.connection.onclose=t;break;case"error":this.connection.onerror=t}},f.prototype.removeListener=function(e,t){var r=this;switch(e){case"data":this.notificationCallbacks.forEach(function(e,n){e===t&&r.notificationCallbacks.splice(n,1)})}},f.prototype.removeAllListeners=function(e){switch(e){case"data":this.notificationCallbacks=[];break;case"connect":this.connection.onopen=null;break;case"end":this.connection.onclose=null;break;case"error":this.connection.onerror=null}},f.prototype.reset=function(){this._timeout(),this.notificationCallbacks=[],this.addDefaultEvents()},f.prototype.disconnect=function(){this.connection&&this.connection.close()},t.exports=f}).call(this,e("buffer").Buffer)},{buffer:84,underscore:325,url:327,"web3-core-helpers":338,websocket:408}],401:[function(e,t,r){"use strict";var n=e("web3-core"),i=e("web3-core-subscriptions").subscriptions,o=e("web3-core-method"),a=e("web3-net"),s=function(){var e=this;n.packageInit(this,arguments);var t=this.setProvider;this.setProvider=function(){t.apply(e,arguments),e.net.setProvider.apply(e,arguments)},this.clearSubscriptions=e._requestManager.clearSubscriptions,this.net=new a(this.currentProvider),[new i({name:"subscribe",type:"shh",subscriptions:{messages:{params:1}}}),new o({name:"getVersion",call:"shh_version",params:0}),new o({name:"getInfo",call:"shh_info",params:0}),new o({name:"setMaxMessageSize",call:"shh_setMaxMessageSize",params:1}),new o({name:"setMinPoW",call:"shh_setMinPoW",params:1}),new o({name:"markTrustedPeer",call:"shh_markTrustedPeer",params:1}),new o({name:"newKeyPair",call:"shh_newKeyPair",params:0}),new o({name:"addPrivateKey",call:"shh_addPrivateKey",params:1}),new o({name:"deleteKeyPair",call:"shh_deleteKeyPair",params:1}),new o({name:"hasKeyPair",call:"shh_hasKeyPair",params:1}),new o({name:"getPublicKey",call:"shh_getPublicKey",params:1}),new o({name:"getPrivateKey",call:"shh_getPrivateKey",params:1}),new o({name:"newSymKey",call:"shh_newSymKey",params:0}),new o({name:"addSymKey",call:"shh_addSymKey",params:1}),new o({name:"generateSymKeyFromPassword",call:"shh_generateSymKeyFromPassword",params:1}),new o({name:"hasSymKey",call:"shh_hasSymKey",params:1}),new o({name:"getSymKey",call:"shh_getSymKey",params:1}),new o({name:"deleteSymKey",call:"shh_deleteSymKey",params:1}),new o({name:"newMessageFilter",call:"shh_newMessageFilter",params:1}),new o({name:"getFilterMessages",call:"shh_getFilterMessages",params:1}),new o({name:"deleteMessageFilter",call:"shh_deleteMessageFilter",params:1}),new o({name:"post",call:"shh_post",params:1,inputFormatter:[null]}),new o({name:"unsubscribe",call:"shh_unsubscribe",params:1})].forEach(function(t){t.attachToObject(e),t.setRequestManager(e._requestManager)})};n.addProviders(s),t.exports=s},{"web3-core":348,"web3-core-method":339,"web3-core-subscriptions":345,"web3-net":372}],402:[function(e,t,r){arguments[4][154][0].apply(r,arguments)},{dup:154}],403:[function(e,t,r){var n=e("underscore"),i=e("ethjs-unit"),o=e("./utils.js"),a=e("./soliditySha3.js"),s=e("randomhex"),u=function(e,t){var r=[];return t.forEach(function(t){if("object"==typeof t.components){if("tuple"!==t.type.substring(0,5))throw new Error("components found but type is not tuple; report on GitHub");var i="",o=t.type.indexOf("[");o>=0&&(i=t.type.substring(o));var a=u(e,t.components);n.isArray(a)&&e?r.push("tuple("+a.join(",")+")"+i):e?r.push("("+a+")"):r.push("("+a.join(",")+")"+i)}else r.push(t.type)}),r},c=function(e){if(!o.isHexStrict(e))throw new Error("The parameter must be a valid HEX string.");var t="",r=0,n=e.length;for("0x"===e.substring(0,2)&&(r=2);r7?r+=e[n].toUpperCase():r+=e[n];return r},toHex:o.toHex,toBN:o.toBN,bytesToHex:o.bytesToHex,hexToBytes:o.hexToBytes,hexToNumberString:o.hexToNumberString,hexToNumber:o.hexToNumber,toDecimal:o.hexToNumber,numberToHex:o.numberToHex,fromDecimal:o.numberToHex,hexToUtf8:o.hexToUtf8,hexToString:o.hexToUtf8,toUtf8:o.hexToUtf8,utf8ToHex:o.utf8ToHex,stringToHex:o.utf8ToHex,fromUtf8:o.utf8ToHex,hexToAscii:c,toAscii:c,asciiToHex:f,fromAscii:f,unitMap:i.unitMap,toWei:function(e,t){if(t=h(t),!o.isBN(e)&&!n.isString(e))throw new Error("Please pass numbers as strings or BigNumber objects to avoid precision errors.");return o.isBN(e)?i.toWei(e,t):i.toWei(e,t).toString(10)},fromWei:function(e,t){if(t=h(t),!o.isBN(e)&&!n.isString(e))throw new Error("Please pass numbers as strings or BigNumber objects to avoid precision errors.");return o.isBN(e)?i.fromWei(e,t):i.fromWei(e,t).toString(10)},padLeft:o.leftPad,leftPad:o.leftPad,padRight:o.rightPad,rightPad:o.rightPad,toTwosComplement:o.toTwosComplement}},{"./soliditySha3.js":404,"./utils.js":405,"ethjs-unit":153,randomhex:274,underscore:325}],404:[function(e,t,r){var n=e("underscore"),i=e("bn.js"),o=e("./utils.js"),a=function(e){var t=typeof e;if("string"===t)return o.isHexStrict(e)?new i(e.replace(/0x/i,""),16):new i(e,10);if("number"===t)return new i(e);if(o.isBigNumber(e))return new i(e.toString(10));if(o.isBN(e))return e;throw new Error(e+" is not a number")},s=function(e,t,r){var n,s,u;if("bytes"===(e=(u=e).startsWith("int[")?"int256"+u.slice(3):"int"===u?"int256":u.startsWith("uint[")?"uint256"+u.slice(4):"uint"===u?"uint256":u.startsWith("fixed[")?"fixed128x128"+u.slice(5):"fixed"===u?"fixed128x128":u.startsWith("ufixed[")?"ufixed128x128"+u.slice(6):"ufixed"===u?"ufixed128x128":u)){if(t.replace(/^0x/i,"").length%2!=0)throw new Error("Invalid bytes characters "+t.length);return t}if("string"===e)return o.utf8ToHex(t);if("bool"===e)return t?"01":"00";if(e.startsWith("address")){if(n=r?64:40,!o.isAddress(t))throw new Error(t+" is not a valid address, or the checksum is invalid.");return o.leftPad(t.toLowerCase(),n)}if(n=function(e){var t=/^\D+(\d+).*$/.exec(e);return t?parseInt(t[1],10):null}(e),e.startsWith("bytes")){if(!n)throw new Error("bytes[] not yet supported in solidity");if(r&&(n=32),n<1||n>32||n256)throw new Error("Invalid uint"+n+" size");if((s=a(t)).bitLength()>n)throw new Error("Supplied uint exceeds width: "+n+" vs "+s.bitLength());if(s.lt(new i(0)))throw new Error("Supplied uint "+s.toString()+" is negative");return n?o.leftPad(s.toString("hex"),n/8*2):s}if(e.startsWith("int")){if(n%8||n<8||n>256)throw new Error("Invalid int"+n+" size");if((s=a(t)).bitLength()>n)throw new Error("Supplied int exceeds width: "+n+" vs "+s.bitLength());return s.lt(new i(0))?s.toTwos(n).toString("hex"):n?o.leftPad(s.toString("hex"),n/8*2):s}throw new Error("Unsupported or invalid type: "+e)},u=function(e){if(n.isArray(e))throw new Error("Autodetection of array types is not supported.");var t,r,a="";if(n.isObject(e)&&(e.hasOwnProperty("v")||e.hasOwnProperty("t")||e.hasOwnProperty("value")||e.hasOwnProperty("type"))?(t=e.hasOwnProperty("t")?e.t:e.type,a=e.hasOwnProperty("v")?e.v:e.value):(t=o.toHex(e,!0),a=o.toHex(e),t.startsWith("int")||t.startsWith("uint")||(t="bytes")),!t.startsWith("int")&&!t.startsWith("uint")||"string"!=typeof a||/^(-)?0x/i.test(a)||(a=new i(a)),n.isArray(a)){if((r=function(e){var t=/^\D+\d*\[(\d+)\]$/.exec(e);return t?parseInt(t[1],10):null}(t))&&a.length!==r)throw new Error(t+" is not matching the given array "+JSON.stringify(a));r=a.length}return n.isArray(a)?a.map(function(e){return s(t,e,r).toString("hex").replace("0x","")}).join(""):s(t,a,r).toString("hex").replace("0x","")};t.exports=function(){var e=Array.prototype.slice.call(arguments),t=n.map(e,u);return o.sha3("0x"+t.join(""))}},{"./utils.js":405,"bn.js":402,underscore:325}],405:[function(e,t,r){var n=e("underscore"),i=e("bn.js"),o=e("number-to-bn"),a=e("utf8"),s=e("eth-lib/lib/hash"),u=function(e){return e instanceof i||e&&e.constructor&&"BN"===e.constructor.name},c=function(e){return e&&e.constructor&&"BigNumber"===e.constructor.name},f=function(e){try{return o.apply(null,arguments)}catch(t){throw new Error(t+' Given value: "'+e+'"')}},h=function(e){return!!/^(0x)?[0-9a-f]{40}$/i.test(e)&&(!(!/^(0x|0X)?[0-9a-f]{40}$/.test(e)&&!/^(0x|0X)?[0-9A-F]{40}$/.test(e))||l(e))},l=function(e){e=e.replace(/^0x/i,"");for(var t=m(e.toLowerCase()).replace(/^0x/i,""),r=0;r<40;r++)if(parseInt(t[r],16)>7&&e[r].toUpperCase()!==e[r]||parseInt(t[r],16)<=7&&e[r].toLowerCase()!==e[r])return!1;return!0},d=function(e){var t="";e=(e=(e=(e=(e=a.encode(e)).replace(/^(?:\u0000)*/,"")).split("").reverse().join("")).replace(/^(?:\u0000)*/,"")).split("").reverse().join("");for(var r=0;r>>4).toString(16)),t.push((15&e[r]).toString(16));return"0x"+t.join("")},isHex:function(e){return(n.isString(e)||n.isNumber(e))&&/^(-0x|0x)?[0-9a-f]*$/i.test(e)},isHexStrict:y,leftPad:function(e,t,r){var n=/^0x/i.test(e)||"number"==typeof e,i=t-(e=e.toString(16).replace(/^0x/i,"")).length+1>=0?t-e.length+1:0;return(n?"0x":"")+new Array(i).join(r||"0")+e},rightPad:function(e,t,r){var n=/^0x/i.test(e)||"number"==typeof e,i=t-(e=e.toString(16).replace(/^0x/i,"")).length+1>=0?t-e.length+1:0;return(n?"0x":"")+e+new Array(i).join(r||"0")},toTwosComplement:function(e){return"0x"+f(e).toTwos(256).toString(16,64)},sha3:m}},{"bn.js":402,"eth-lib/lib/hash":134,"number-to-bn":237,underscore:325,utf8:329}],406:[function(e,t,r){t.exports={_from:"web3@1.0.0-beta.36",_id:"web3@1.0.0-beta.36",_inBundle:!1,_integrity:"sha512-fZDunw1V0AQS27r5pUN3eOVP7u8YAvyo6vOapdgVRolAu5LgaweP7jncYyLINqIX9ZgWdS5A090bt+ymgaYHsw==",_location:"/web3",_phantomChildren:{},_requested:{type:"version",registry:!0,raw:"web3@1.0.0-beta.36",name:"web3",escapedName:"web3",rawSpec:"1.0.0-beta.36",saveSpec:null,fetchSpec:"1.0.0-beta.36"},_requiredBy:["#USER","/"],_resolved:"https://registry.npmjs.org/web3/-/web3-1.0.0-beta.36.tgz",_shasum:"2954da9e431124c88396025510d840ba731c8373",_spec:"web3@1.0.0-beta.36",_where:"/Users/alexvlasov/Blockchain/web3swift/web3swiftJSProxy",author:{name:"ethereum.org"},authors:[{name:"Fabian Vogelsteller",email:"fabian@ethereum.org",homepage:"http://frozeman.de"},{name:"Marek Kotewicz",email:"marek@parity.io",url:"https://github.com/debris"},{name:"Marian Oancea",url:"https://github.com/cubedro"},{name:"Gav Wood",email:"g@parity.io",homepage:"http://gavwood.com"},{name:"Jeffery Wilcke",email:"jeffrey.wilcke@ethereum.org",url:"https://github.com/obscuren"}],bugs:{url:"https://github.com/ethereum/web3.js/issues"},bundleDependencies:!1,dependencies:{"web3-bzz":"1.0.0-beta.36","web3-core":"1.0.0-beta.36","web3-eth":"1.0.0-beta.36","web3-eth-personal":"1.0.0-beta.36","web3-net":"1.0.0-beta.36","web3-shh":"1.0.0-beta.36","web3-utils":"1.0.0-beta.36"},deprecated:!1,description:"Ethereum JavaScript API",keywords:["Ethereum","JavaScript","API"],license:"LGPL-3.0",main:"src/index.js",name:"web3",namespace:"ethereum",repository:{type:"git",url:"https://github.com/ethereum/web3.js/tree/master/packages/web3"},version:"1.0.0-beta.36"}},{}],407:[function(e,t,r){"use strict";var n=e("../package.json").version,i=e("web3-core"),o=e("web3-eth"),a=e("web3-net"),s=e("web3-eth-personal"),u=e("web3-shh"),c=e("web3-bzz"),f=e("web3-utils"),h=function(){var e=this;i.packageInit(this,arguments),this.version=n,this.utils=f,this.eth=new o(this),this.shh=new u(this),this.bzz=new c(this);var t=this.setProvider;this.setProvider=function(r,n){return t.apply(e,arguments),this.eth.setProvider(r,n),this.shh.setProvider(r,n),this.bzz.setProvider(r),!0}};h.version=n,h.utils=f,h.modules={Eth:o,Net:a,Personal:s,Shh:u,Bzz:c},i.addProviders(h),t.exports=h},{"../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(e,t,r){var n=function(){return this||{}}(),i=n.WebSocket||n.MozWebSocket,o=e("./version");function a(e,t){return t?new i(e,t):new i(e)}i&&["CONNECTING","OPEN","CLOSING","CLOSED"].forEach(function(e){Object.defineProperty(a,e,{get:function(){return i[e]}})}),t.exports={w3cwebsocket:i?a:null,version:o}},{"./version":409}],409:[function(e,t,r){t.exports=e("../package.json").version},{"../package.json":410}],410:[function(e,t,r){t.exports={_from:"git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible",_id:"websocket@1.0.26",_inBundle:!1,_integrity:"",_location:"/websocket",_phantomChildren:{},_requested:{type:"git",raw:"websocket@git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible",name:"websocket",escapedName:"websocket",rawSpec:"git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible",saveSpec:"git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible",fetchSpec:"git://github.com/frozeman/WebSocket-Node.git",gitCommittish:"browserifyCompatible"},_requiredBy:["/web3-providers-ws"],_resolved:"git://github.com/frozeman/WebSocket-Node.git#6c72925e3f8aaaea8dc8450f97627e85263999f2",_spec:"websocket@git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible",_where:"/Users/alexvlasov/Blockchain/web3swift/web3swiftJSProxy/node_modules/web3-providers-ws",author:{name:"Brian McKelvey",email:"brian@worlize.com",url:"https://www.worlize.com/"},browser:"lib/browser.js",bugs:{url:"https://github.com/theturtle32/WebSocket-Node/issues"},bundleDependencies:!1,config:{verbose:!1},contributors:[{name:"Iñaki Baz Castillo",email:"ibc@aliax.net",url:"http://dev.sipdoc.net"}],dependencies:{debug:"^2.2.0",nan:"^2.3.3","typedarray-to-buffer":"^3.1.2",yaeti:"^0.0.6"},deprecated:!1,description:"Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.",devDependencies:{"buffer-equal":"^1.0.0",faucet:"^0.0.1",gulp:"git+https://github.com/gulpjs/gulp.git#4.0","gulp-jshint":"^2.0.4",jshint:"^2.0.0","jshint-stylish":"^2.2.1",tape:"^4.0.1"},directories:{lib:"./lib"},engines:{node:">=0.10.0"},homepage:"https://github.com/theturtle32/WebSocket-Node",keywords:["websocket","websockets","socket","networking","comet","push","RFC-6455","realtime","server","client"],license:"Apache-2.0",main:"index",name:"websocket",repository:{type:"git",url:"git+https://github.com/theturtle32/WebSocket-Node.git"},scripts:{gulp:"gulp",install:"(node-gyp rebuild 2> builderror.log) || (exit 0)",test:"faucet test/unit"},version:"1.0.26"}},{}],411:[function(e,t,r){var n=e("xhr-request");t.exports=function(e,t){return new Promise(function(r,i){n(e,t,function(e,t){e?i(e):r(t)})})}},{"xhr-request":412}],412:[function(e,t,r){var n=e("query-string"),i=e("url-set-query"),o=e("object-assign"),a=e("./lib/ensure-header.js"),s=e("./lib/request.js"),u="application/json",c=function(){};t.exports=function(e,t,r){if(!e||"string"!=typeof e)throw new TypeError("must specify a URL");"function"==typeof t&&(r=t,t={});if(r&&"function"!=typeof r)throw new TypeError("expected cb to be undefined or a function");r=r||c;var f=(t=t||{}).json?"json":"text",h=(t=o({responseType:f},t)).headers||{},l=(t.method||"GET").toUpperCase(),d=t.query;d&&("string"!=typeof d&&(d=n.stringify(d)),e=i(e,d));"json"===t.responseType&&a(h,"Accept",u);t.json&&"GET"!==l&&"HEAD"!==l&&(a(h,"Content-Type",u),t.body=JSON.stringify(t.body));return t.method=l,t.url=e,t.headers=h,delete t.query,delete t.json,s(t,r)}},{"./lib/ensure-header.js":413,"./lib/request.js":415,"object-assign":238,"query-string":266,"url-set-query":326}],413:[function(e,t,r){t.exports=function(e,t,r){var n=t.toLowerCase();e[t]||e[n]||(e[t]=r)}},{}],414:[function(e,t,r){t.exports=function(e,t){return t?{statusCode:t.statusCode,headers:t.headers,method:e.method,url:e.url,rawRequest:t.rawRequest?t.rawRequest:t}:null}},{}],415:[function(e,t,r){var n=e("xhr"),i=e("./normalize-response"),o=function(){};t.exports=function(e,t){delete e.uri;var r=!1;"json"===e.responseType&&(e.responseType="text",r=!0);var a=n(e,function(n,a,s){if(r&&!n)try{var u=a.rawRequest.responseText;s=JSON.parse(u)}catch(e){n=e}a=i(e,a),t(n,n?null:s,a),t=o}),s=a.onabort;return a.onabort=function(){var e=s.apply(a,Array.prototype.slice.call(arguments));return t(new Error("XHR Aborted")),t=o,e},a}},{"./normalize-response":414,xhr:416}],416:[function(e,t,r){"use strict";var n=e("global/window"),i=e("is-function"),o=e("parse-headers"),a=e("xtend");function s(e,t,r){var n=e;return i(t)?(r=t,"string"==typeof e&&(n={uri:e})):n=a(t,{uri:e}),n.callback=r,n}function u(e,t,r){return c(t=s(e,t,r))}function c(e){if(void 0===e.callback)throw new Error("callback argument missing");var t=!1,r=function(r,n,i){t||(t=!0,e.callback(r,n,i))};function n(e){return clearTimeout(f),e instanceof Error||(e=new Error(""+(e||"Unknown XMLHttpRequest Error"))),e.statusCode=0,r(e,m)}function i(){if(!s){var t;clearTimeout(f),t=e.useXDR&&void 0===c.status?200:1223===c.status?204:c.status;var n=m,i=null;return 0!==t?(n={body:function(){var e=void 0;if(e=c.response?c.response:c.responseText||function(e){try{if("document"===e.responseType)return e.responseXML;var t=e.responseXML&&"parsererror"===e.responseXML.documentElement.nodeName;if(""===e.responseType&&!t)return e.responseXML}catch(e){}return null}(c),y)try{e=JSON.parse(e)}catch(e){}return e}(),statusCode:t,method:l,headers:{},url:h,rawRequest:c},c.getAllResponseHeaders&&(n.headers=o(c.getAllResponseHeaders()))):i=new Error("Internal XMLHttpRequest Error"),r(i,n,n.body)}}var a,s,c=e.xhr||null;c||(c=e.cors||e.useXDR?new u.XDomainRequest:new u.XMLHttpRequest);var f,h=c.url=e.uri||e.url,l=c.method=e.method||"GET",d=e.body||e.data,p=c.headers=e.headers||{},b=!!e.sync,y=!1,m={body:void 0,headers:{},statusCode:0,method:l,url:h,rawRequest:c};if("json"in e&&!1!==e.json&&(y=!0,p.accept||p.Accept||(p.Accept="application/json"),"GET"!==l&&"HEAD"!==l&&(p["content-type"]||p["Content-Type"]||(p["Content-Type"]="application/json"),d=JSON.stringify(!0===e.json?d:e.json))),c.onreadystatechange=function(){4===c.readyState&&setTimeout(i,0)},c.onload=i,c.onerror=n,c.onprogress=function(){},c.onabort=function(){s=!0},c.ontimeout=n,c.open(l,h,!b,e.username,e.password),b||(c.withCredentials=!!e.withCredentials),!b&&e.timeout>0&&(f=setTimeout(function(){if(!s){s=!0,c.abort("timeout");var e=new Error("XMLHttpRequest timeout");e.code="ETIMEDOUT",n(e)}},e.timeout)),c.setRequestHeader)for(a in p)p.hasOwnProperty(a)&&c.setRequestHeader(a,p[a]);else if(e.headers&&!function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0}(e.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in e&&(c.responseType=e.responseType),"beforeSend"in e&&"function"==typeof e.beforeSend&&e.beforeSend(c),c.send(d||null),c}t.exports=u,t.exports.default=u,u.XMLHttpRequest=n.XMLHttpRequest||function(){},u.XDomainRequest="withCredentials"in new u.XMLHttpRequest?u.XMLHttpRequest:n.XDomainRequest,function(e,t){for(var r=0;r=0)return this._url=this._parseUrl(t.headers.location),this._method="GET",this._loweredHeaders["content-type"]&&(delete this._headers[this._loweredHeaders["content-type"]],delete this._loweredHeaders["content-type"]),null!=this._headers["Content-Type"]&&delete this._headers["Content-Type"],delete this._headers["Content-Length"],this.upload._reset(),this._finalizeHeaders(),void this._sendHxxpRequest();this._response=t,this._response.on("data",function(e){return n._onHttpResponseData(t,e)}),this._response.on("end",function(){return n._onHttpResponseEnd(t)}),this._response.on("close",function(){return n._onHttpResponseClose(t)}),this.responseUrl=this._url.href.split("#")[0],this.status=t.statusCode,this.statusText=s.STATUS_CODES[this.status],this._parseResponseHeaders(t);var i=this._responseHeaders["content-length"]||"";this._totalBytes=+i,this._lengthComputable=!!i,this._setReadyState(r.HEADERS_RECEIVED)}},r.prototype._onHttpResponseData=function(e,t){this._response===e&&(this._responseParts.push(new n(t)),this._loadedBytes+=t.length,this.readyState!==r.LOADING&&this._setReadyState(r.LOADING),this._dispatchProgress("progress"))},r.prototype._onHttpResponseEnd=function(e){this._response===e&&(this._parseResponse(),this._request=null,this._response=null,this._setReadyState(r.DONE),this._dispatchProgress("load"),this._dispatchProgress("loadend"))},r.prototype._onHttpResponseClose=function(e){if(this._response===e){var t=this._request;this._setError(),t.abort(),this._setReadyState(r.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend")}},r.prototype._onHttpTimeout=function(e){this._request===e&&(this._setError(),e.abort(),this._setReadyState(r.DONE),this._dispatchProgress("timeout"),this._dispatchProgress("loadend"))},r.prototype._onHttpRequestError=function(e,t){this._request===e&&(this._setError(),e.abort(),this._setReadyState(r.DONE),this._dispatchProgress("error"),this._dispatchProgress("loadend"))},r.prototype._dispatchProgress=function(e){var t=new r.ProgressEvent(e);t.lengthComputable=this._lengthComputable,t.loaded=this._loadedBytes,t.total=this._totalBytes,this.dispatchEvent(t)},r.prototype._setError=function(){this._request=null,this._response=null,this._responseHeaders=null,this._responseParts=null},r.prototype._parseUrl=function(e,t,r){var n=null==this.nodejsBaseUrl?e:f.resolve(this.nodejsBaseUrl,e),i=f.parse(n,!1,!0);i.hash=null;var o=(i.auth||"").split(":"),a=o[0],s=o[1];return(a||s||t||r)&&(i.auth=(t||a||"")+":"+(r||s||"")),i},r.prototype._parseResponseHeaders=function(e){for(var t in this._responseHeaders={},e.headers){var r=t.toLowerCase();this._privateHeaders[r]||(this._responseHeaders[r]=e.headers[t])}null!=this._mimeOverride&&(this._responseHeaders["content-type"]=this._mimeOverride)},r.prototype._parseResponse=function(){var e=n.concat(this._responseParts);switch(this._responseParts=null,this.responseType){case"json":this.responseText=null;try{this.response=JSON.parse(e.toString("utf-8"))}catch(e){this.response=null}return;case"buffer":return this.responseText=null,void(this.response=e);case"arraybuffer":this.responseText=null;for(var t=new ArrayBuffer(e.length),r=new Uint8Array(t),i=0;i{ <# print parameters, error #> }); */ +/* var unregisterHandler = window.bridge.on('userDidLogin', (parameters) => { <# receive notify from native #> } ); Call unregisterHandler() when cancel a listen. */ diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Contract/ComparisonExtensions.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Contract/ComparisonExtensions.swift new file mode 100755 index 000000000..33f525ff6 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Contract/ComparisonExtensions.swift @@ -0,0 +1,95 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +extension BigUInt: EventFilterComparable { + public func isEqualTo(_ other: AnyObject) -> Bool { + switch other { + case let oth as BigUInt: + return self == oth + case let oth as BigInt: + return self.magnitude == oth.magnitude && self.signum() == oth.signum() + default: + return false + } + } +} + +extension BigInt: EventFilterComparable { + public func isEqualTo(_ other: AnyObject) -> Bool { + switch other { + case let oth as BigInt: + return self == oth + case let oth as BigUInt: + return self.magnitude == oth.magnitude && self.signum() == oth.signum() + default: + return false + } + } +} + +extension String: EventFilterComparable { + public func isEqualTo(_ other: AnyObject) -> Bool { + switch other { + case let oth as String: + guard let data = self.data(using: .utf8) else {return false} + guard let otherData = oth.data(using: .utf8) else {return false} + let hash = data.sha3(.keccak256) + let otherHash = otherData.sha3(.keccak256) + return hash == otherHash + case let oth as Data: + guard let data = self.data(using: .utf8) else {return false} + let hash = data.sha3(.keccak256) + let otherHash = oth.sha3(.keccak256) + return hash == otherHash + default: + return false + } + } +} + +extension Data: EventFilterComparable { + public func isEqualTo(_ other: AnyObject) -> Bool { + switch other { + case let oth as String: + guard let data = Data.fromHex(oth) else {return false} + if self == data { + return true + } + let hash = data.sha3(.keccak256) + return self == hash + case let oth as Data: + if self == oth { + return true + } + let hash = oth.sha3(.keccak256) + return self == hash + default: + return false + } + } +} + +extension EthereumAddress: EventFilterComparable { + public func isEqualTo(_ other: AnyObject) -> Bool { + switch other { + case let oth as String: + let addr = EthereumAddress(oth) + return self == addr + case let oth as Data: + let addr = EthereumAddress(oth) + return self == addr + case let oth as EthereumAddress: + return self == oth + default: + return false + } + } +} + diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Contract/ContractProtocol.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Contract/ContractProtocol.swift new file mode 100755 index 000000000..60a31251d --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Contract/ContractProtocol.swift @@ -0,0 +1,109 @@ +// +// ContractProtocol.swift +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +public protocol ContractProtocol { + var address: EthereumAddress? {get set} + var transactionOptions: TransactionOptions? {get set} + var allMethods: [String] {get} + var allEvents: [String] {get} + func deploy(bytecode:Data, parameters: [AnyObject], extraData: Data) -> EthereumTransaction? + func method(_ method:String, parameters: [AnyObject], extraData: Data) -> EthereumTransaction? + init?(_ abiString: String, at: EthereumAddress?) + func decodeReturnData(_ method:String, data: Data) -> [String:Any]? + func decodeInputData(_ method:String, data: Data) -> [String:Any]? + func decodeInputData(_ data: Data) -> [String:Any]? + func parseEvent(_ eventLog: EventLog) -> (eventName:String?, eventData:[String:Any]?) + func testBloomForEventPrecence(eventName: String, bloom: EthereumBloomFilter) -> Bool? +} + +public protocol EventFilterComparable { + func isEqualTo(_ other: AnyObject) -> Bool +} + +public protocol EventFilterEncodable { + func eventFilterEncoded() -> String? +} + +public protocol EventFilterable: EventFilterComparable, EventFilterEncodable { + +} + +extension BigUInt: EventFilterable { +} +extension BigInt: EventFilterable { +} +extension Data: EventFilterable { +} +extension String: EventFilterable { +} +extension EthereumAddress: EventFilterable { +} + + +public struct EventFilter { + public enum Block { + case latest + case pending + case blockNumber(UInt64) + + var encoded: String { + switch self { + case .latest: + return "latest" + case .pending: + return "pending" + case .blockNumber(let number): + return String(number, radix: 16).addHexPrefix() + } + } + } + + public init() { + + } + + public init(fromBlock: Block?, toBlock: Block?, + addresses: [EthereumAddress]? = nil, + parameterFilters: [[EventFilterable]?]? = nil) { + self.fromBlock = fromBlock + self.toBlock = toBlock + self.addresses = addresses + self.parameterFilters = parameterFilters + } + + public var fromBlock: Block? + public var toBlock: Block? + public var addresses: [EthereumAddress]? + public var parameterFilters: [[EventFilterable]?]? + + public func rpcPreEncode() -> EventFilterParameters { + var encoding = EventFilterParameters() + if self.fromBlock != nil { + encoding.fromBlock = self.fromBlock!.encoded + } + if self.toBlock != nil { + encoding.toBlock = self.toBlock!.encoded + } + if self.addresses != nil { + if self.addresses!.count == 1 { + encoding.address = [self.addresses![0].address] + } else { + var encodedAddresses = [String?]() + for addr in self.addresses! { + encodedAddresses.append(addr.address) + } + encoding.address = encodedAddresses + } + } + return encoding + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Contract/EthereumContract.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Contract/EthereumContract.swift new file mode 100755 index 000000000..203c51519 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Contract/EthereumContract.swift @@ -0,0 +1,297 @@ +// +// Created by Alexander Vlasov. +// Copyright © 2018 Alexander Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress +//import EthereumABI + +public struct EthereumContract:ContractProtocol { + public var transactionOptions: TransactionOptions? = TransactionOptions.defaultOptions + public var address: EthereumAddress? = nil + + var _abi: [ABI.Element] + + public var allEvents: [String] { + return events.keys.compactMap({ (s) -> String in + return s + }) + } + + public var allMethods: [String] { + return methods.keys.compactMap({ (s) -> String in + return s + }) + } + + public struct EventFilter { + public var parameterName: String + public var parameterValues: [AnyObject] + } + + public var methods: [String: ABI.Element] { + var toReturn = [String: ABI.Element]() + for m in self._abi { + switch m { + case .function(let function): + guard let name = function.name else {continue} + toReturn[name] = m + default: + continue + } + } + return toReturn + } + + public var constructor: ABI.Element? { + var toReturn : ABI.Element? = nil + for m in self._abi { + if toReturn != nil { + break + } + switch m { + case .constructor(_): + toReturn = m + break + default: + continue + } + } + if toReturn == nil { + let defaultConstructor = ABI.Element.constructor(ABI.Element.Constructor(inputs: [], constant: false, payable: false)) + return defaultConstructor + } + return toReturn + } + + public var events: [String: ABI.Element.Event] { + var toReturn = [String: ABI.Element.Event]() + for m in self._abi { + switch m { + case .event(let event): + let name = event.name + toReturn[name] = event + default: + continue + } + } + return toReturn + } + + public init?(_ abiString: String, at: EthereumAddress? = nil) { + do { + let jsonData = abiString.data(using: .utf8) + let abi = try JSONDecoder().decode([ABI.Record].self, from: jsonData!) + let abiNative = try abi.map({ (record) -> ABI.Element in + return try record.parse() + }) + _abi = abiNative + if at != nil { + self.address = at + } + } + catch{ + return nil + } + } + + public init(abi: [ABI.Element]) { + _abi = abi + } + + public init(abi: [ABI.Element], at: EthereumAddress) { + _abi = abi + address = at + } + +// public func deploy(bytecode:Data, parameters: [AnyObject] = [AnyObject](), extraData: Data = Data(), options: Web3Options?) -> EthereumTransaction? { +// let to:EthereumAddress = EthereumAddress.contractDeploymentAddress() +// let mergedOptions = Web3Options.merge(self.options, with: options) +// var gasLimit:BigUInt +// if let gasInOptions = mergedOptions?.gasLimit { +// gasLimit = gasInOptions +// } else { +// return nil +// } +// +// var gasPrice:BigUInt +// if let gasPriceInOptions = mergedOptions?.gasPrice { +// gasPrice = gasPriceInOptions +// } else { +// return nil +// } +// +// var value:BigUInt +// if let valueInOptions = mergedOptions?.value { +// value = valueInOptions +// } else { +// value = BigUInt(0) +// } +// guard let constructor = self.constructor else {return nil} +// guard let encodedData = constructor.encodeParameters(parameters) else {return nil} +// var fullData = bytecode +// if encodedData != Data() { +// fullData.append(encodedData) +// } else if extraData != Data() { +// fullData.append(extraData) +// } +// let transaction = EthereumTransaction(gasPrice: gasPrice, gasLimit: gasLimit, to: to, value: value, data: fullData) +// return transaction +// } + + public func deploy(bytecode:Data, parameters: [AnyObject] = [AnyObject](), extraData: Data = Data()) -> EthereumTransaction? { + let to:EthereumAddress = EthereumAddress.contractDeploymentAddress() + guard let constructor = self.constructor else {return nil} + guard let encodedData = constructor.encodeParameters(parameters) else {return nil} + var fullData = bytecode + if encodedData != Data() { + fullData.append(encodedData) + } else if extraData != Data() { + fullData.append(extraData) + } + let transaction = EthereumTransaction(gasPrice: BigUInt(0), gasLimit: BigUInt(0), to: to, value: BigUInt(0), data: fullData) + return transaction + } + +// public func method(_ method:String = "fallback", parameters: [AnyObject] = [AnyObject](), extraData: Data = Data(), options: Web3Options?) -> EthereumTransaction? { +// var to:EthereumAddress +// let mergedOptions = Web3Options.merge(self.options, with: options) +// if (self.address != nil) { +// to = self.address! +// } else if let toFound = mergedOptions?.to, toFound.isValid { +// to = toFound +// } else { +// return nil +// } +// +// var gasLimit:BigUInt +// if let gasInOptions = mergedOptions?.gasLimit { +// gasLimit = gasInOptions +// } else { +// return nil +// } +// +// var gasPrice:BigUInt +// if let gasPriceInOptions = mergedOptions?.gasPrice { +// gasPrice = gasPriceInOptions +// } else { +// return nil +// } +// +// var value:BigUInt +// if let valueInOptions = mergedOptions?.value { +// value = valueInOptions +// } else { +// value = BigUInt(0) +// } +// +// if (method == "fallback") { +// let transaction = EthereumTransaction(gasPrice: gasPrice, gasLimit: gasLimit, to: to, value: value, data: extraData) +// return transaction +// } +// let foundMethod = self.methods.filter { (key, value) -> Bool in +// return key == method +// } +// guard foundMethod.count == 1 else {return nil} +// let abiMethod = foundMethod[method] +// guard let encodedData = abiMethod?.encodeParameters(parameters) else {return nil} +// let transaction = EthereumTransaction(gasPrice: gasPrice, gasLimit: gasLimit, to: to, value: value, data: encodedData) +// return transaction +// } + + public func method(_ method:String = "fallback", parameters: [AnyObject] = [AnyObject](), extraData: Data = Data()) -> EthereumTransaction? { + guard let to = self.address else {return nil} + + if (method == "fallback") { + let transaction = EthereumTransaction(gasPrice: BigUInt(0), gasLimit: BigUInt(0), to: to, value: BigUInt(0), data: extraData) + return transaction + } + let foundMethod = self.methods.filter { (key, value) -> Bool in + return key == method + } + guard foundMethod.count == 1 else {return nil} + let abiMethod = foundMethod[method] + guard let encodedData = abiMethod?.encodeParameters(parameters) else {return nil} + let transaction = EthereumTransaction(gasPrice: BigUInt(0), gasLimit: BigUInt(0), to: to, value: BigUInt(0), data: encodedData) + return transaction + } + + public func parseEvent(_ eventLog: EventLog) -> (eventName:String?, eventData:[String:Any]?) { + for (eName, ev) in self.events { + if (!ev.anonymous) { + if eventLog.topics[0] != ev.topic { + continue + } + else { + let logTopics = eventLog.topics + let logData = eventLog.data + let parsed = ev.decodeReturnedLogs(eventLogTopics: logTopics, eventLogData: logData) + if parsed != nil { + return (eName, parsed!) + } + } + } else { + let logTopics = eventLog.topics + let logData = eventLog.data + let parsed = ev.decodeReturnedLogs(eventLogTopics: logTopics, eventLogData: logData) + if parsed != nil { + return (eName, parsed!) + } + } + } + return (nil, nil) + } + + public func testBloomForEventPrecence(eventName: String, bloom: EthereumBloomFilter) -> Bool? { + guard let event = events[eventName] else {return nil} + if event.anonymous { + return true + } + let eventOfSuchTypeIsPresent = bloom.test(topic: event.topic) + return eventOfSuchTypeIsPresent + } + + public func decodeReturnData(_ method:String, data: Data) -> [String:Any]? { + if method == "fallback" { + return [String:Any]() + } + guard let function = methods[method] else {return nil} + guard case .function(_) = function else {return nil} + return function.decodeReturnData(data) + } + + public func decodeInputData(_ method: String, data: Data) -> [String : Any]? { + if method == "fallback" { + return nil + } + guard let function = methods[method] else {return nil} + switch function { + case .function(_): + return function.decodeInputData(data) + case .constructor(_): + return function.decodeInputData(data) + default: + return nil + } + } + + public func decodeInputData(_ data: Data) -> [String:Any]? { + guard data.count % 32 == 4 else {return nil} + let methodSignature = data[0..<4] + let foundFunction = self._abi.filter { (m) -> Bool in + switch m { + case .function(let function): + return function.methodEncoding == methodSignature + default: + return false + } + } + guard foundFunction.count == 1 else { + return nil + } + let function = foundFunction[0] + return function.decodeInputData(Data(data[4 ..< data.count])) + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Contract/EthereumFilterEncodingExtensions.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Contract/EthereumFilterEncodingExtensions.swift new file mode 100755 index 000000000..d590a87d9 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Contract/EthereumFilterEncodingExtensions.swift @@ -0,0 +1,44 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +extension BigUInt: EventFilterEncodable { + public func eventFilterEncoded() -> String? { + return self.abiEncode(bits: 256)?.toHexString().addHexPrefix() + } +} + +extension BigInt: EventFilterEncodable { + public func eventFilterEncoded() -> String? { + return self.abiEncode(bits: 256)?.toHexString().addHexPrefix() + } +} + +extension Data: EventFilterEncodable { + public func eventFilterEncoded() -> String? { + guard let padded = self.setLengthLeft(32) else {return nil} + return padded.toHexString().addHexPrefix() + } +} + +extension EthereumAddress: EventFilterEncodable { + public func eventFilterEncoded() -> String? { + guard let padded = self.addressData.setLengthLeft(32) else {return nil} + return padded.toHexString().addHexPrefix() + } +} + +extension String: EventFilterEncodable { + public func eventFilterEncoded() -> String? { + guard let data = self.data(using: .utf8) else {return nil} + return data.sha3(.keccak256).toHexString().addHexPrefix() + } +} + + diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Contract/EventFiltering.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Contract/EventFiltering.swift new file mode 100755 index 000000000..b170285c7 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Contract/EventFiltering.swift @@ -0,0 +1,170 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +//import EthereumABI +//import EthereumAddress + +internal func filterLogs(decodedLogs: [EventParserResultProtocol], eventFilter: EventFilter) -> [EventParserResultProtocol] { + let filteredLogs = decodedLogs.filter { (result) -> Bool in + if eventFilter.addresses == nil { + return true + } else { + if eventFilter.addresses!.contains(result.contractAddress) { + return true + } else { + return false + } + } + }.filter { (result) -> Bool in + if eventFilter.parameterFilters == nil { + return true + } else { + let keys = result.decodedResult.keys.filter({ (key) -> Bool in + if let _ = UInt64(key) { + return true + } + return false + }) + if keys.count < eventFilter.parameterFilters!.count { + return false + } + for i in 0 ..< eventFilter.parameterFilters!.count { + let allowedValues = eventFilter.parameterFilters![i] + let actualValue = result.decodedResult["\(i)"] + if actualValue == nil { + return false + } + if allowedValues == nil { + continue + } + var inAllowed = false + for value in allowedValues! { + if value.isEqualTo(actualValue! as AnyObject) { + inAllowed = true + break + } + } + if !inAllowed { + return false + } + } + return true + } + } + return filteredLogs +} + +internal func encodeTopicToGetLogs(contract: EthereumContract, eventName: String?, filter: EventFilter) -> EventFilterParameters? { + var eventTopic: Data? = nil + var event: ABI.Element.Event? = nil + if eventName != nil { + guard let ev = contract.events[eventName!] else {return nil} + event = ev + eventTopic = ev.topic + } + var topics = [[String?]?]() + if eventTopic != nil { + topics.append([eventTopic!.toHexString().addHexPrefix()]) + } else { + topics.append(nil as [String?]?) + } + if filter.parameterFilters != nil { + if event == nil {return nil} + var lastNonemptyFilter = -1 + for i in 0 ..< filter.parameterFilters!.count { + let filterValue = filter.parameterFilters![i] + if filterValue != nil { + lastNonemptyFilter = i + } + } + if lastNonemptyFilter >= 0 { + guard lastNonemptyFilter <= event!.inputs.count else {return nil} + for i in 0 ... lastNonemptyFilter { + let filterValues = filter.parameterFilters![i] + if filterValues != nil { + var isFound = false + var targetIndexedPosition = i + for j in 0 ..< event!.inputs.count{ + if event!.inputs[j].indexed { + if targetIndexedPosition == 0 { + isFound = true + break + } + targetIndexedPosition -= 1 + } + } + + if !isFound {return nil} + } + if filterValues == nil { + topics.append(nil as [String?]?) + continue + } + var encodings = [String]() + for val in filterValues! { + guard let enc = val.eventFilterEncoded() else {return nil} + encodings.append(enc) + } + topics.append(encodings) + } + } + } + var preEncoding = filter.rpcPreEncode() + preEncoding.topics = topics + return preEncoding +} + +internal func parseReceiptForLogs(receipt: TransactionReceipt, contract: ContractProtocol, eventName: String, filter: EventFilter?) -> [EventParserResultProtocol]? { + guard let bloom = receipt.logsBloom else {return nil} + if contract.address != nil { + let addressPresent = bloom.test(topic: contract.address!.addressData) + if (addressPresent != true) { + return [EventParserResultProtocol]() + } + } + if filter != nil, let filterAddresses = filter?.addresses { + var oneIsPresent = false + for addr in filterAddresses { + let addressPresent = bloom.test(topic: addr.addressData) + if (addressPresent == true) { + oneIsPresent = true + break + } + } + if (oneIsPresent != true) { + return [EventParserResultProtocol]() + } + } + guard let eventOfSuchTypeIsPresent = contract.testBloomForEventPrecence(eventName: eventName, bloom: bloom) else {return nil} + if (!eventOfSuchTypeIsPresent) { + return [EventParserResultProtocol]() + } + var allLogs = receipt.logs + if (contract.address != nil) { + allLogs = receipt.logs.filter({ (log) -> Bool in + log.address == contract.address + }) + } + let decodedLogs = allLogs.compactMap({ (log) -> EventParserResultProtocol? in + let (n, d) = contract.parseEvent(log) + guard let evName = n, let evData = d else {return nil} + var result = EventParserResult(eventName: evName, transactionReceipt: receipt, contractAddress: log.address, decodedResult: evData) + result.eventLog = log + return result + }).filter { (res:EventParserResultProtocol?) -> Bool in + return res != nil && res?.eventName == eventName + } + var allResults = [EventParserResultProtocol]() + if (filter != nil) { + let eventFilter = filter! + let filteredLogs = filterLogs(decodedLogs: decodedLogs, eventFilter: eventFilter) + allResults = filteredLogs + } else { + allResults = decodedLogs + } + return allResults +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Array+Extension.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Array+Extension.swift new file mode 100755 index 000000000..3fc7e80f2 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Array+Extension.swift @@ -0,0 +1,16 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +extension Array { + public func split(intoChunksOf chunkSize: Int) -> [[Element]] { + return stride(from: 0, to: self.count, by: chunkSize).map { + let endIndex = ($0.advanced(by: chunkSize) > self.count) ? self.count - $0 : chunkSize + return Array(self[$0..<$0.advanced(by: endIndex)]) + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Base58.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Base58.swift new file mode 100755 index 000000000..397b389cd --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Base58.swift @@ -0,0 +1,170 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +struct Base58 { + static let base58Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + + // Encode + static func base58FromBytes(_ bytes: [UInt8]) -> String { + var bytes = bytes + var zerosCount = 0 + var length = 0 + + for b in bytes { + if b != 0 { break } + zerosCount += 1 + } + + bytes.removeFirst(zerosCount) + + let size = bytes.count * 138 / 100 + 1 + + var base58: [UInt8] = Array(repeating: 0, count: size) + for b in bytes { + var carry = Int(b) + var i = 0 + + for j in 0...base58.count-1 where carry != 0 || i < length { + carry += 256 * Int(base58[base58.count - j - 1]) + base58[base58.count - j - 1] = UInt8(carry % 58) + carry /= 58 + i += 1 + } + + assert(carry == 0) + + length = i + } + + // skip leading zeros + var zerosToRemove = 0 + var str = "" + for b in base58 { + if b != 0 { break } + zerosToRemove += 1 + } + base58.removeFirst(zerosToRemove) + + while 0 < zerosCount { + str = "\(str)1" + zerosCount -= 1 + } + + for b in base58 { + //str = "\(str)\(base58Alphabet[String.Index(encodedOffset: Int(b))])" + str = "\(str)\(base58Alphabet[String.Index(utf16Offset: Int(b), in: base58Alphabet)])" + } + + return str + } + + // Decode + static func bytesFromBase58(_ base58: String) -> [UInt8] { + // remove leading and trailing whitespaces + let string = base58.trimmingCharacters(in: CharacterSet.whitespaces) + + guard !string.isEmpty else { return [] } + + var zerosCount = 0 + var length = 0 + for c in string { + if c != "1" { break } + zerosCount += 1 + } + + let size = string.lengthOfBytes(using: String.Encoding.utf8) * 733 / 1000 + 1 - zerosCount + var base58: [UInt8] = Array(repeating: 0, count: size) + for c in string where c != " " { + // search for base58 character + guard let base58Index = base58Alphabet.index(of: c) else { return [] } + +// var carry = base58Index.encodedOffset + var carry = base58Index.utf16Offset(in: base58Alphabet) + var i = 0 + for j in 0...base58.count where carry != 0 || i < length { + carry += 58 * Int(base58[base58.count - j - 1]) + base58[base58.count - j - 1] = UInt8(carry % 256) + carry /= 256 + i += 1 + } + + assert(carry == 0) + length = i + } + + // skip leading zeros + var zerosToRemove = 0 + + for b in base58 { + if b != 0 { break } + zerosToRemove += 1 + } + base58.removeFirst(zerosToRemove) + + var result: [UInt8] = Array(repeating: 0, count: zerosCount) + for b in base58 { + result.append(b) + } + return result + } +} + + + +extension Array where Element == UInt8 { + public var base58EncodedString: String { + guard !self.isEmpty else { return "" } + return Base58.base58FromBytes(self) + } + + public var base58CheckEncodedString: String { + var bytes = self + let checksum = [UInt8](bytes.sha256().sha256()[0..<4]) + + bytes.append(contentsOf: checksum) + + return Base58.base58FromBytes(bytes) + } +} + +extension String { + public var base58EncodedString: String { + return [UInt8](utf8).base58EncodedString + } + + public var base58DecodedData: Data? { + let bytes = Base58.bytesFromBase58(self) + return Data(bytes) + } + + public var base58CheckDecodedData: Data? { + guard let bytes = self.base58CheckDecodedBytes else { return nil } + return Data(bytes) + } + + public var base58CheckDecodedBytes: [UInt8]? { + var bytes = Base58.bytesFromBase58(self) + guard 4 <= bytes.count else { return nil } + + let checksum = [UInt8](bytes[bytes.count-4..(_ value: T) -> [UInt8] { + var value = value + return withUnsafeBytes(of: &value) { Array($0) } +} + +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} + return Data(result) +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Data+Extension.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Data+Extension.swift new file mode 100755 index 000000000..fb2d4aeb4 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Data+Extension.swift @@ -0,0 +1,142 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +public extension Data { + + init(fromArray values: [T]) { + var values = values + self.init(buffer: UnsafeBufferPointer(start: &values, count: values.count)) + } + + func toArray(type: T.Type) throws -> [T] { + return try self.withUnsafeBytes { (body: UnsafeRawBufferPointer) in + if let bodyAddress = body.baseAddress, body.count > 0 { + let pointer = bodyAddress.assumingMemoryBound(to: T.self) + return [T](UnsafeBufferPointer(start: pointer, count: self.count/MemoryLayout.stride)) + } else { + throw Web3Error.dataError + } + } + } + + // func toArray(type: T.Type) throws -> [T] { + // return try self.withUnsafeBytes { (body: UnsafeRawBufferPointer) in + // if let bodyAddress = body.baseAddress, body.count > 0 { + // let pointer = bodyAddress.assumingMemoryBound(to: T.self) + // return [T](UnsafeBufferPointer(start: pointer, count: self.count/MemoryLayout.stride)) + // } else { + // throw Web3Error.dataError + // } + // } + // } + + func constantTimeComparisonTo(_ other:Data?) -> Bool { + guard let rhs = other else {return false} + guard self.count == rhs.count else {return false} + var difference = UInt8(0x00) + for i in 0.. Data? { + for _ in 0...1024 { + var data = Data(repeating: 0, count: length) + let result = data.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) -> Int32? in + if let bodyAddress = body.baseAddress, body.count > 0 { + let pointer = bodyAddress.assumingMemoryBound(to: UInt8.self) + return SecRandomCopyBytes(kSecRandomDefault, 32, pointer) + } else { + return nil + } + } + if let notNilResult = result, notNilResult == errSecSuccess { + return data + } + } + return nil + } + + // static func randomBytes(length: Int) -> Data? { + // for _ in 0...1024 { + // var data = Data(repeating: 0, count: length) + // let result = data.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) -> Int32? in + // if let bodyAddress = body.baseAddress, body.count > 0 { + // let pointer = bodyAddress.assumingMemoryBound(to: UInt8.self) + // return SecRandomCopyBytes(kSecRandomDefault, 32, pointer) + // } else { + // return nil + // } + // } + // if let notNilResult = result, notNilResult == errSecSuccess { + // return data + // } + // } + // return nil + // } + + static func fromHex(_ hex: String) -> Data? { + let string = hex.lowercased().stripHexPrefix() + let array = Array(hex: string) + if (array.count == 0) { + if (hex == "0x" || hex == "") { + return Data() + } else { + return nil + } + } + return Data(array) + } + + 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} + 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} + let pointee = padded.withUnsafeBytes { (body: UnsafeRawBufferPointer) in + body.baseAddress?.assumingMemoryBound(to: UInt64.self).pointee + } + guard let ptee = pointee else {return nil} + var uintRepresentation = UInt64(bigEndian: ptee) + uintRepresentation = uintRepresentation << (startingBit % 8) + uintRepresentation = uintRepresentation >> UInt64(64 - length) + return uintRepresentation + } + + // 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} + // 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} + // let pointee = padded.withUnsafeBytes { (body: UnsafeRawBufferPointer) in + // body.baseAddress?.assumingMemoryBound(to: UInt64.self).pointee + // } + // guard let ptee = pointee else {return nil} + // var uintRepresentation = UInt64(bigEndian: ptee) + // uintRepresentation = uintRepresentation << (startingBit % 8) + // uintRepresentation = uintRepresentation >> UInt64(64 - length) + // return uintRepresentation + // } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Decodable+Extensions.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Decodable+Extensions.swift new file mode 100644 index 000000000..59f82fb0a --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Decodable+Extensions.swift @@ -0,0 +1,146 @@ +// +// DecodingContainer+AnyCollection.swift +// AnyDecodable +// +// Created by levantAJ on 1/18/19. +// Copyright © 2019 levantAJ. All rights reserved. +// +import Foundation + +struct AnyCodingKey: CodingKey { + var stringValue: String + var intValue: Int? + + init?(stringValue: String) { + self.stringValue = stringValue + } + + init?(intValue: Int) { + self.intValue = intValue + self.stringValue = String(intValue) + } +} + +extension KeyedDecodingContainer { + /// Decodes a value of the given type for the given key. + /// + /// - parameter type: The type of value to decode. + /// - parameter key: The key that the decoded value is associated with. + /// - returns: A value of the requested type, if present for the given key + /// and convertible to the requested type. + /// - throws: `DecodingError.typeMismatch` if the encountered encoded value + /// is not convertible to the requested type. + /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry + /// for the given key. + /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for + /// the given key. + public func decode(_ type: [Any].Type, forKey key: KeyedDecodingContainer.Key) throws -> [Any] { + var values = try nestedUnkeyedContainer(forKey: key) + return try values.decode(type) + } + + /// Decodes a value of the given type for the given key. + /// + /// - parameter type: The type of value to decode. + /// - parameter key: The key that the decoded value is associated with. + /// - returns: A value of the requested type, if present for the given key + /// and convertible to the requested type. + /// - throws: `DecodingError.typeMismatch` if the encountered encoded value + /// is not convertible to the requested type. + /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry + /// for the given key. + /// - throws: `DecodingError.valueNotFound` if `self` has a null entry for + /// the given key. + public func decode(_ type: [String: Any].Type, forKey key: KeyedDecodingContainer.Key) throws -> [String: Any] { + let values = try nestedContainer(keyedBy: AnyCodingKey.self, forKey: key) + return try values.decode(type) + } + + /// Decodes a value of the given type for the given key, if present. + /// + /// This method returns `nil` if the container does not have a value + /// associated with `key`, or if the value is null. The difference between + /// these states can be distinguished with a `contains(_:)` call. + /// + /// - parameter type: The type of value to decode. + /// - parameter key: The key that the decoded value is associated with. + /// - returns: A decoded value of the requested type, or `nil` if the + /// `Decoder` does not have an entry associated with the given key, or if + /// the value is a null value. + /// - throws: `DecodingError.typeMismatch` if the encountered encoded value + /// is not convertible to the requested type. + public func decodeIfPresent(_ type: [Any].Type, forKey key: KeyedDecodingContainer.Key) throws -> [Any]? { + guard contains(key), + try decodeNil(forKey: key) == false else { return nil } + return try decode(type, forKey: key) + } + + /// Decodes a value of the given type for the given key, if present. + /// + /// This method returns `nil` if the container does not have a value + /// associated with `key`, or if the value is null. The difference between + /// these states can be distinguished with a `contains(_:)` call. + /// + /// - parameter type: The type of value to decode. + /// - parameter key: The key that the decoded value is associated with. + /// - returns: A decoded value of the requested type, or `nil` if the + /// `Decoder` does not have an entry associated with the given key, or if + /// the value is a null value. + /// - throws: `DecodingError.typeMismatch` if the encountered encoded value + /// is not convertible to the requested type. + public func decodeIfPresent(_ type: [String: Any].Type, forKey key: KeyedDecodingContainer.Key) throws -> [String: Any]? { + guard contains(key), + try decodeNil(forKey: key) == false else { return nil } + return try decode(type, forKey: key) + } +} + +private extension KeyedDecodingContainer { + func decode(_ type: [String: Any].Type) throws -> [String: Any] { + var dictionary: [String: Any] = [:] + for key in allKeys { + if try decodeNil(forKey: key) { + dictionary[key.stringValue] = NSNull() + } else if let bool = try? decode(Bool.self, forKey: key) { + dictionary[key.stringValue] = bool + } else if let string = try? decode(String.self, forKey: key) { + dictionary[key.stringValue] = string + } else if let int = try? decode(Int.self, forKey: key) { + dictionary[key.stringValue] = int + } else if let double = try? decode(Double.self, forKey: key) { + dictionary[key.stringValue] = double + } else if let dict = try? decode([String: Any].self, forKey: key) { + dictionary[key.stringValue] = dict + } else if let array = try? decode([Any].self, forKey: key) { + dictionary[key.stringValue] = array + } + } + return dictionary + } +} + +private extension UnkeyedDecodingContainer { + mutating func decode(_ type: [Any].Type) throws -> [Any] { + var elements: [Any] = [] + while !isAtEnd { + if try decodeNil() { + elements.append(NSNull()) + } else if let int = try? decode(Int.self) { + elements.append(int) + } else if let bool = try? decode(Bool.self) { + elements.append(bool) + } else if let double = try? decode(Double.self) { + elements.append(double) + } else if let string = try? decode(String.self) { + elements.append(string) + } else if let values = try? nestedContainer(keyedBy: AnyCodingKey.self), + let element = try? values.decode([String: Any].self) { + elements.append(element) + } else if var values = try? nestedUnkeyedContainer(), + let element = try? values.decode([Any].self) { + elements.append(element) + } + } + return elements + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Dictionary+Extension.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Dictionary+Extension.swift new file mode 100755 index 000000000..ee1a68133 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Dictionary+Extension.swift @@ -0,0 +1,18 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +extension Dictionary where Key == String, Value: Equatable { + func keyForValue(value : Value) -> String? { + for key in self.keys { + if self[key] == value { + return key + } + } + return nil + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Encodable+Extensions.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Encodable+Extensions.swift new file mode 100644 index 000000000..84bad03eb --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/Encodable+Extensions.swift @@ -0,0 +1,130 @@ +// +// EncodingContainer+AnyCollection.swift +// AnyDecodable +// +// Created by ShopBack on 1/19/19. +// Copyright © 2019 levantAJ. All rights reserved. +// +import Foundation + +extension KeyedEncodingContainer { + /// Encodes the given value for the given key. + /// + /// - parameter value: The value to encode. + /// - parameter key: The key to associate the value with. + /// - throws: `EncodingError.invalidValue` if the given value is invalid in + /// the current context for this format. + public mutating func encode(_ value: [String: Any], forKey key: KeyedEncodingContainer.Key) throws { + var container = nestedContainer(keyedBy: AnyCodingKey.self, forKey: key) + try container.encode(value) + } + + /// Encodes the given value for the given key. + /// + /// - parameter value: The value to encode. + /// - parameter key: The key to associate the value with. + /// - throws: `EncodingError.invalidValue` if the given value is invalid in + /// the current context for this format. + public mutating func encode(_ value: [Any], forKey key: KeyedEncodingContainer.Key) throws { + var container = nestedUnkeyedContainer(forKey: key) + try container.encode(value) + } + + /// Encodes the given value for the given key if it is not `nil`. + /// + /// - parameter value: The value to encode. + /// - parameter key: The key to associate the value with. + /// - throws: `EncodingError.invalidValue` if the given value is invalid in + /// the current context for this format. + public mutating func encodeIfPresent(_ value: [String: Any]?, forKey key: KeyedEncodingContainer.Key) throws { + if let value = value { + var container = nestedContainer(keyedBy: AnyCodingKey.self, forKey: key) + try container.encode(value) + } else { + try encodeNil(forKey: key) + } + } + + /// Encodes the given value for the given key if it is not `nil`. + /// + /// - parameter value: The value to encode. + /// - parameter key: The key to associate the value with. + /// - throws: `EncodingError.invalidValue` if the given value is invalid in + /// the current context for this format. + public mutating func encodeIfPresent(_ value: [Any]?, forKey key: KeyedEncodingContainer.Key) throws { + if let value = value { + var container = nestedUnkeyedContainer(forKey: key) + try container.encode(value) + } else { + try encodeNil(forKey: key) + } + } +} + +private extension KeyedEncodingContainer where K == AnyCodingKey { + mutating func encode(_ value: [String: Any]) throws { + for (k, v) in value { + let key = AnyCodingKey(stringValue: k)! + switch v { + case is NSNull: + try encodeNil(forKey: key) + case let string as String: + try encode(string, forKey: key) + case let int as Int: + try encode(int, forKey: key) + case let bool as Bool: + try encode(bool, forKey: key) + case let double as Double: + try encode(double, forKey: key) + case let dict as [String: Any]: + try encode(dict, forKey: key) + case let array as [Any]: + try encode(array, forKey: key) + default: + debugPrint("⚠️ Unsuported type!", v) + continue + } + } + } +} + +private extension UnkeyedEncodingContainer { + /// Encodes the given value. + /// + /// - parameter value: The value to encode. + /// - throws: `EncodingError.invalidValue` if the given value is invalid in + /// the current context for this format. + mutating func encode(_ value: [Any]) throws { + for v in value { + switch v { + case is NSNull: + try encodeNil() + case let string as String: + try encode(string) + case let int as Int: + try encode(int) + case let bool as Bool: + try encode(bool) + case let double as Double: + try encode(double) + case let dict as [String: Any]: + try encode(dict) + case let array as [Any]: + var values = nestedUnkeyedContainer() + try values.encode(array) + default: + debugPrint("⚠️ Unsuported type!", v) + } + } + } + + /// Encodes the given value. + /// + /// - parameter value: The value to encode. + /// - throws: `EncodingError.invalidValue` if the given value is invalid in + /// the current context for this format. + mutating func encode(_ value: [String: Any]) throws { + var container = self.nestedContainer(keyedBy: AnyCodingKey.self) + try container.encode(value) + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/NSRegularExpressionExtension.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/NSRegularExpressionExtension.swift new file mode 100755 index 000000000..1b511a627 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/NSRegularExpressionExtension.swift @@ -0,0 +1,83 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + + +import Foundation + + +extension NSRegularExpression { + typealias GroupNamesSearchResult = (NSTextCheckingResult, NSTextCheckingResult, Int) + + private func textCheckingResultsOfNamedCaptureGroups() -> [String:GroupNamesSearchResult] { + var groupnames = [String:GroupNamesSearchResult]() + + guard let greg = try? NSRegularExpression(pattern: "^\\(\\?<([\\w\\a_-]*)>$", options: NSRegularExpression.Options.dotMatchesLineSeparators) else { + // This never happens but the alternative is to make this method throwing + return groupnames + } + guard let reg = try? NSRegularExpression(pattern: "\\(.*?>", options: NSRegularExpression.Options.dotMatchesLineSeparators) else { + // This never happens but the alternative is to make this method throwing + return groupnames + } + let m = reg.matches(in: self.pattern, options: NSRegularExpression.MatchingOptions.withTransparentBounds, range: NSRange(location: 0, length: self.pattern.utf16.count)) + for (n,g) in m.enumerated() { + let r = self.pattern.range(from: g.range(at: 0)) + let gstring = String(self.pattern[r!]) + let gmatch = greg.matches(in: gstring, options: NSRegularExpression.MatchingOptions.anchored, range: NSRange(location: 0, length: gstring.utf16.count)) + if gmatch.count > 0{ + let r2 = gstring.range(from: gmatch[0].range(at: 1))! + groupnames[String(gstring[r2])] = (g, gmatch[0],n) + } + + } + return groupnames + } + + func indexOfNamedCaptureGroups() throws -> [String:Int] { + var groupnames = [String:Int]() + for (name,(_,_,n)) in self.textCheckingResultsOfNamedCaptureGroups() { + groupnames[name] = n + 1 + } + return groupnames + } + + func rangesOfNamedCaptureGroups(match:NSTextCheckingResult) throws -> [String:Range] { + var ranges = [String:Range]() + for (name,(_,_,n)) in self.textCheckingResultsOfNamedCaptureGroups() { + ranges[name] = Range(match.range(at: n+1)) + } + return ranges + } + + private func nameForIndex(_ index: Int, from: [String:GroupNamesSearchResult]) -> String? { + for (name,(_,_,n)) in from { + if (n + 1) == index { + return name + } + } + return nil + } + + func captureGroups(string: String, options: NSRegularExpression.MatchingOptions = []) -> [String:String] { + return captureGroups(string: string, options: options, range: NSRange(location: 0, length: string.utf16.count)) + } + + func captureGroups(string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> [String:String] { + var dict = [String:String]() + let matchResult = matches(in: string, options: options, range: range) + let names = self.textCheckingResultsOfNamedCaptureGroups() + for (_,m) in matchResult.enumerated() { + for i in (0.. Data? { + let existingLength = UInt64(self.count) + if (existingLength == toBytes) { + return Data(self) + } else if (existingLength > toBytes) { + return nil + } + var data:Data + if (isNegative) { + data = Data(repeating: UInt8(255), count: Int(toBytes - existingLength)) + } else { + data = Data(repeating: UInt8(0), count: Int(toBytes - existingLength)) + } + data.append(self) + return data + } + + func setLengthRight(_ toBytes: UInt64, isNegative:Bool = false ) -> Data? { + let existingLength = UInt64(self.count) + if (existingLength == toBytes) { + return Data(self) + } else if (existingLength > toBytes) { + return nil + } + var data:Data = Data() + data.append(self) + if (isNegative) { + data.append(Data(repeating: UInt8(255), count: Int(toBytes - existingLength))) + } else { + data.append(Data(repeating: UInt8(0), count:Int(toBytes - existingLength))) + } + return data + } +} + +extension BigInt { + func toTwosComplement() -> Data { + if (self.sign == BigInt.Sign.plus) { + return self.magnitude.serialize() + } else { + let serializedLength = self.magnitude.serialize().count + let MAX = BigUInt(1) << (serializedLength*8) + let twoComplement = MAX - self.magnitude + return twoComplement.serialize() + } + } +} + +extension BigUInt { + func abiEncode(bits: UInt64) -> Data? { + let data = self.serialize() + let paddedLength = UInt64(ceil((Double(bits)/8.0))) + let padded = data.setLengthLeft(paddedLength) + return padded + } +} + +extension BigInt { + func abiEncode(bits: UInt64) -> Data? { + let isNegative = self < (BigInt(0)) + let data = self.toTwosComplement() + let paddedLength = UInt64(ceil((Double(bits)/8.0))) + let padded = data.setLengthLeft(paddedLength, isNegative: isNegative) + return padded + } +} + +extension BigInt { + static func fromTwosComplement(data: Data) -> BigInt { + let isPositive = ((data[0] & 128) >> 7) == 0 + if (isPositive) { + let magnitude = BigUInt(data) + return BigInt(magnitude) + } else { + let MAX = (BigUInt(1) << (data.count*8)) + let magnitude = MAX - BigUInt(data) + let bigint = BigInt(0) - BigInt(magnitude) + return bigint + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/RIPEMD160+StackOveflow.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/RIPEMD160+StackOveflow.swift new file mode 100755 index 000000000..df4cfb3c7 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/RIPEMD160+StackOveflow.swift @@ -0,0 +1,534 @@ +// +// RIPEMD160_SO.swift +// web3swift +// +// Created by Alexander Vlasov on 10.01.2018. +// + +//From https://stackoverflow.com/questions/43091858/swift-hash-a-string-using-hash-hmac-with-ripemd160/43191938 + +import Foundation + +public struct RIPEMD160 { + + private var MDbuf: (UInt32, UInt32, UInt32, UInt32, UInt32) + private var buffer: Data + private var count: Int64 // Total # of bytes processed. + + public init() { + MDbuf = (0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0) + buffer = Data() + count = 0 + } + + private mutating func compress(_ X: UnsafePointer) { + + // *** Helper functions (originally macros in rmd160.h) *** + + /* ROL(x, n) cyclically rotates x over n bits to the left */ + /* x must be of an unsigned 32 bits type and 0 <= n < 32. */ + func ROL(_ x: UInt32, _ n: UInt32) -> UInt32 { + return (x << n) | ( x >> (32 - n)) + } + + /* the five basic functions F(), G() and H() */ + + func F(_ x: UInt32, _ y: UInt32, _ z: UInt32) -> UInt32 { + return x ^ y ^ z + } + + func G(_ x: UInt32, _ y: UInt32, _ z: UInt32) -> UInt32 { + return (x & y) | (~x & z) + } + + func H(_ x: UInt32, _ y: UInt32, _ z: UInt32) -> UInt32 { + return (x | ~y) ^ z + } + + func I(_ x: UInt32, _ y: UInt32, _ z: UInt32) -> UInt32 { + return (x & z) | (y & ~z) + } + + func J(_ x: UInt32, _ y: UInt32, _ z: UInt32) -> UInt32 { + return x ^ (y | ~z) + } + + /* the ten basic operations FF() through III() */ + + func FF(_ a: inout UInt32, _ b: UInt32, _ c: inout UInt32, _ d: UInt32, _ e: UInt32, _ x: UInt32, _ s: UInt32) { + a = a &+ F(b, c, d) &+ x + a = ROL(a, s) &+ e + c = ROL(c, 10) + } + + func GG(_ a: inout UInt32, _ b: UInt32, _ c: inout UInt32, _ d: UInt32, _ e: UInt32, _ x: UInt32, _ s: UInt32) { + a = a &+ G(b, c, d) &+ x &+ 0x5a827999 + a = ROL(a, s) &+ e + c = ROL(c, 10) + } + + func HH(_ a: inout UInt32, _ b: UInt32, _ c: inout UInt32, _ d: UInt32, _ e: UInt32, _ x: UInt32, _ s: UInt32) { + a = a &+ H(b, c, d) &+ x &+ 0x6ed9eba1 + a = ROL(a, s) &+ e + c = ROL(c, 10) + } + + func II(_ a: inout UInt32, _ b: UInt32, _ c: inout UInt32, _ d: UInt32, _ e: UInt32, _ x: UInt32, _ s: UInt32) { + a = a &+ I(b, c, d) &+ x &+ 0x8f1bbcdc + a = ROL(a, s) &+ e + c = ROL(c, 10) + } + + func JJ(_ a: inout UInt32, _ b: UInt32, _ c: inout UInt32, _ d: UInt32, _ e: UInt32, _ x: UInt32, _ s: UInt32) { + a = a &+ J(b, c, d) &+ x &+ 0xa953fd4e + a = ROL(a, s) &+ e + c = ROL(c, 10) + } + + func FFF(_ a: inout UInt32, _ b: UInt32, _ c: inout UInt32, _ d: UInt32, _ e: UInt32, _ x: UInt32, _ s: UInt32) { + a = a &+ F(b, c, d) &+ x + a = ROL(a, s) &+ e + c = ROL(c, 10) + } + + func GGG(_ a: inout UInt32, _ b: UInt32, _ c: inout UInt32, _ d: UInt32, _ e: UInt32, _ x: UInt32, _ s: UInt32) { + a = a &+ G(b, c, d) &+ x &+ 0x7a6d76e9 + a = ROL(a, s) &+ e + c = ROL(c, 10) + } + + func HHH(_ a: inout UInt32, _ b: UInt32, _ c: inout UInt32, _ d: UInt32, _ e: UInt32, _ x: UInt32, _ s: UInt32) { + a = a &+ H(b, c, d) &+ x &+ 0x6d703ef3 + a = ROL(a, s) &+ e + c = ROL(c, 10) + } + + func III(_ a: inout UInt32, _ b: UInt32, _ c: inout UInt32, _ d: UInt32, _ e: UInt32, _ x: UInt32, _ s: UInt32) { + a = a &+ I(b, c, d) &+ x &+ 0x5c4dd124 + a = ROL(a, s) &+ e + c = ROL(c, 10) + } + + func JJJ(_ a: inout UInt32, _ b: UInt32, _ c: inout UInt32, _ d: UInt32, _ e: UInt32, _ x: UInt32, _ s: UInt32) { + a = a &+ J(b, c, d) &+ x &+ 0x50a28be6 + a = ROL(a, s) &+ e + c = ROL(c, 10) + } + + // *** The function starts here *** + + var (aa, bb, cc, dd, ee) = MDbuf + var (aaa, bbb, ccc, ddd, eee) = MDbuf + + /* round 1 */ + FF(&aa, bb, &cc, dd, ee, X[ 0], 11) + FF(&ee, aa, &bb, cc, dd, X[ 1], 14) + FF(&dd, ee, &aa, bb, cc, X[ 2], 15) + FF(&cc, dd, &ee, aa, bb, X[ 3], 12) + FF(&bb, cc, &dd, ee, aa, X[ 4], 5) + FF(&aa, bb, &cc, dd, ee, X[ 5], 8) + FF(&ee, aa, &bb, cc, dd, X[ 6], 7) + FF(&dd, ee, &aa, bb, cc, X[ 7], 9) + FF(&cc, dd, &ee, aa, bb, X[ 8], 11) + FF(&bb, cc, &dd, ee, aa, X[ 9], 13) + FF(&aa, bb, &cc, dd, ee, X[10], 14) + FF(&ee, aa, &bb, cc, dd, X[11], 15) + FF(&dd, ee, &aa, bb, cc, X[12], 6) + FF(&cc, dd, &ee, aa, bb, X[13], 7) + FF(&bb, cc, &dd, ee, aa, X[14], 9) + FF(&aa, bb, &cc, dd, ee, X[15], 8) + + /* round 2 */ + GG(&ee, aa, &bb, cc, dd, X[ 7], 7) + GG(&dd, ee, &aa, bb, cc, X[ 4], 6) + GG(&cc, dd, &ee, aa, bb, X[13], 8) + GG(&bb, cc, &dd, ee, aa, X[ 1], 13) + GG(&aa, bb, &cc, dd, ee, X[10], 11) + GG(&ee, aa, &bb, cc, dd, X[ 6], 9) + GG(&dd, ee, &aa, bb, cc, X[15], 7) + GG(&cc, dd, &ee, aa, bb, X[ 3], 15) + GG(&bb, cc, &dd, ee, aa, X[12], 7) + GG(&aa, bb, &cc, dd, ee, X[ 0], 12) + GG(&ee, aa, &bb, cc, dd, X[ 9], 15) + GG(&dd, ee, &aa, bb, cc, X[ 5], 9) + GG(&cc, dd, &ee, aa, bb, X[ 2], 11) + GG(&bb, cc, &dd, ee, aa, X[14], 7) + GG(&aa, bb, &cc, dd, ee, X[11], 13) + GG(&ee, aa, &bb, cc, dd, X[ 8], 12) + + /* round 3 */ + HH(&dd, ee, &aa, bb, cc, X[ 3], 11) + HH(&cc, dd, &ee, aa, bb, X[10], 13) + HH(&bb, cc, &dd, ee, aa, X[14], 6) + HH(&aa, bb, &cc, dd, ee, X[ 4], 7) + HH(&ee, aa, &bb, cc, dd, X[ 9], 14) + HH(&dd, ee, &aa, bb, cc, X[15], 9) + HH(&cc, dd, &ee, aa, bb, X[ 8], 13) + HH(&bb, cc, &dd, ee, aa, X[ 1], 15) + HH(&aa, bb, &cc, dd, ee, X[ 2], 14) + HH(&ee, aa, &bb, cc, dd, X[ 7], 8) + HH(&dd, ee, &aa, bb, cc, X[ 0], 13) + HH(&cc, dd, &ee, aa, bb, X[ 6], 6) + HH(&bb, cc, &dd, ee, aa, X[13], 5) + HH(&aa, bb, &cc, dd, ee, X[11], 12) + HH(&ee, aa, &bb, cc, dd, X[ 5], 7) + HH(&dd, ee, &aa, bb, cc, X[12], 5) + + /* round 4 */ + II(&cc, dd, &ee, aa, bb, X[ 1], 11) + II(&bb, cc, &dd, ee, aa, X[ 9], 12) + II(&aa, bb, &cc, dd, ee, X[11], 14) + II(&ee, aa, &bb, cc, dd, X[10], 15) + II(&dd, ee, &aa, bb, cc, X[ 0], 14) + II(&cc, dd, &ee, aa, bb, X[ 8], 15) + II(&bb, cc, &dd, ee, aa, X[12], 9) + II(&aa, bb, &cc, dd, ee, X[ 4], 8) + II(&ee, aa, &bb, cc, dd, X[13], 9) + II(&dd, ee, &aa, bb, cc, X[ 3], 14) + II(&cc, dd, &ee, aa, bb, X[ 7], 5) + II(&bb, cc, &dd, ee, aa, X[15], 6) + II(&aa, bb, &cc, dd, ee, X[14], 8) + II(&ee, aa, &bb, cc, dd, X[ 5], 6) + II(&dd, ee, &aa, bb, cc, X[ 6], 5) + II(&cc, dd, &ee, aa, bb, X[ 2], 12) + + /* round 5 */ + JJ(&bb, cc, &dd, ee, aa, X[ 4], 9) + JJ(&aa, bb, &cc, dd, ee, X[ 0], 15) + JJ(&ee, aa, &bb, cc, dd, X[ 5], 5) + JJ(&dd, ee, &aa, bb, cc, X[ 9], 11) + JJ(&cc, dd, &ee, aa, bb, X[ 7], 6) + JJ(&bb, cc, &dd, ee, aa, X[12], 8) + JJ(&aa, bb, &cc, dd, ee, X[ 2], 13) + JJ(&ee, aa, &bb, cc, dd, X[10], 12) + JJ(&dd, ee, &aa, bb, cc, X[14], 5) + JJ(&cc, dd, &ee, aa, bb, X[ 1], 12) + JJ(&bb, cc, &dd, ee, aa, X[ 3], 13) + JJ(&aa, bb, &cc, dd, ee, X[ 8], 14) + JJ(&ee, aa, &bb, cc, dd, X[11], 11) + JJ(&dd, ee, &aa, bb, cc, X[ 6], 8) + JJ(&cc, dd, &ee, aa, bb, X[15], 5) + JJ(&bb, cc, &dd, ee, aa, X[13], 6) + + /* parallel round 1 */ + JJJ(&aaa, bbb, &ccc, ddd, eee, X[ 5], 8) + JJJ(&eee, aaa, &bbb, ccc, ddd, X[14], 9) + JJJ(&ddd, eee, &aaa, bbb, ccc, X[ 7], 9) + JJJ(&ccc, ddd, &eee, aaa, bbb, X[ 0], 11) + JJJ(&bbb, ccc, &ddd, eee, aaa, X[ 9], 13) + JJJ(&aaa, bbb, &ccc, ddd, eee, X[ 2], 15) + JJJ(&eee, aaa, &bbb, ccc, ddd, X[11], 15) + JJJ(&ddd, eee, &aaa, bbb, ccc, X[ 4], 5) + JJJ(&ccc, ddd, &eee, aaa, bbb, X[13], 7) + JJJ(&bbb, ccc, &ddd, eee, aaa, X[ 6], 7) + JJJ(&aaa, bbb, &ccc, ddd, eee, X[15], 8) + JJJ(&eee, aaa, &bbb, ccc, ddd, X[ 8], 11) + JJJ(&ddd, eee, &aaa, bbb, ccc, X[ 1], 14) + JJJ(&ccc, ddd, &eee, aaa, bbb, X[10], 14) + JJJ(&bbb, ccc, &ddd, eee, aaa, X[ 3], 12) + JJJ(&aaa, bbb, &ccc, ddd, eee, X[12], 6) + + /* parallel round 2 */ + III(&eee, aaa, &bbb, ccc, ddd, X[ 6], 9) + III(&ddd, eee, &aaa, bbb, ccc, X[11], 13) + III(&ccc, ddd, &eee, aaa, bbb, X[ 3], 15) + III(&bbb, ccc, &ddd, eee, aaa, X[ 7], 7) + III(&aaa, bbb, &ccc, ddd, eee, X[ 0], 12) + III(&eee, aaa, &bbb, ccc, ddd, X[13], 8) + III(&ddd, eee, &aaa, bbb, ccc, X[ 5], 9) + III(&ccc, ddd, &eee, aaa, bbb, X[10], 11) + III(&bbb, ccc, &ddd, eee, aaa, X[14], 7) + III(&aaa, bbb, &ccc, ddd, eee, X[15], 7) + III(&eee, aaa, &bbb, ccc, ddd, X[ 8], 12) + III(&ddd, eee, &aaa, bbb, ccc, X[12], 7) + III(&ccc, ddd, &eee, aaa, bbb, X[ 4], 6) + III(&bbb, ccc, &ddd, eee, aaa, X[ 9], 15) + III(&aaa, bbb, &ccc, ddd, eee, X[ 1], 13) + III(&eee, aaa, &bbb, ccc, ddd, X[ 2], 11) + + /* parallel round 3 */ + HHH(&ddd, eee, &aaa, bbb, ccc, X[15], 9) + HHH(&ccc, ddd, &eee, aaa, bbb, X[ 5], 7) + HHH(&bbb, ccc, &ddd, eee, aaa, X[ 1], 15) + HHH(&aaa, bbb, &ccc, ddd, eee, X[ 3], 11) + HHH(&eee, aaa, &bbb, ccc, ddd, X[ 7], 8) + HHH(&ddd, eee, &aaa, bbb, ccc, X[14], 6) + HHH(&ccc, ddd, &eee, aaa, bbb, X[ 6], 6) + HHH(&bbb, ccc, &ddd, eee, aaa, X[ 9], 14) + HHH(&aaa, bbb, &ccc, ddd, eee, X[11], 12) + HHH(&eee, aaa, &bbb, ccc, ddd, X[ 8], 13) + HHH(&ddd, eee, &aaa, bbb, ccc, X[12], 5) + HHH(&ccc, ddd, &eee, aaa, bbb, X[ 2], 14) + HHH(&bbb, ccc, &ddd, eee, aaa, X[10], 13) + HHH(&aaa, bbb, &ccc, ddd, eee, X[ 0], 13) + HHH(&eee, aaa, &bbb, ccc, ddd, X[ 4], 7) + HHH(&ddd, eee, &aaa, bbb, ccc, X[13], 5) + + /* parallel round 4 */ + GGG(&ccc, ddd, &eee, aaa, bbb, X[ 8], 15) + GGG(&bbb, ccc, &ddd, eee, aaa, X[ 6], 5) + GGG(&aaa, bbb, &ccc, ddd, eee, X[ 4], 8) + GGG(&eee, aaa, &bbb, ccc, ddd, X[ 1], 11) + GGG(&ddd, eee, &aaa, bbb, ccc, X[ 3], 14) + GGG(&ccc, ddd, &eee, aaa, bbb, X[11], 14) + GGG(&bbb, ccc, &ddd, eee, aaa, X[15], 6) + GGG(&aaa, bbb, &ccc, ddd, eee, X[ 0], 14) + GGG(&eee, aaa, &bbb, ccc, ddd, X[ 5], 6) + GGG(&ddd, eee, &aaa, bbb, ccc, X[12], 9) + GGG(&ccc, ddd, &eee, aaa, bbb, X[ 2], 12) + GGG(&bbb, ccc, &ddd, eee, aaa, X[13], 9) + GGG(&aaa, bbb, &ccc, ddd, eee, X[ 9], 12) + GGG(&eee, aaa, &bbb, ccc, ddd, X[ 7], 5) + GGG(&ddd, eee, &aaa, bbb, ccc, X[10], 15) + GGG(&ccc, ddd, &eee, aaa, bbb, X[14], 8) + + /* parallel round 5 */ + FFF(&bbb, ccc, &ddd, eee, aaa, X[12] , 8) + FFF(&aaa, bbb, &ccc, ddd, eee, X[15] , 5) + FFF(&eee, aaa, &bbb, ccc, ddd, X[10] , 12) + FFF(&ddd, eee, &aaa, bbb, ccc, X[ 4] , 9) + FFF(&ccc, ddd, &eee, aaa, bbb, X[ 1] , 12) + FFF(&bbb, ccc, &ddd, eee, aaa, X[ 5] , 5) + FFF(&aaa, bbb, &ccc, ddd, eee, X[ 8] , 14) + FFF(&eee, aaa, &bbb, ccc, ddd, X[ 7] , 6) + FFF(&ddd, eee, &aaa, bbb, ccc, X[ 6] , 8) + FFF(&ccc, ddd, &eee, aaa, bbb, X[ 2] , 13) + FFF(&bbb, ccc, &ddd, eee, aaa, X[13] , 6) + FFF(&aaa, bbb, &ccc, ddd, eee, X[14] , 5) + FFF(&eee, aaa, &bbb, ccc, ddd, X[ 0] , 15) + FFF(&ddd, eee, &aaa, bbb, ccc, X[ 3] , 13) + FFF(&ccc, ddd, &eee, aaa, bbb, X[ 9] , 11) + FFF(&bbb, ccc, &ddd, eee, aaa, X[11] , 11) + + /* combine results */ + MDbuf = (MDbuf.1 &+ cc &+ ddd, + MDbuf.2 &+ dd &+ eee, + MDbuf.3 &+ ee &+ aaa, + MDbuf.4 &+ aa &+ bbb, + MDbuf.0 &+ bb &+ ccc) + } + + public mutating func update(data: Data) throws { + try data.withUnsafeBytes { (body: UnsafeRawBufferPointer) in + if let bodyAddress = body.baseAddress, body.count > 0 { + var ptr = bodyAddress.assumingMemoryBound(to: UInt8.self) + var length = data.count + var X = [UInt32](repeating: 0, count: 16) + + // Process remaining bytes from last call: + if buffer.count > 0 && buffer.count + length >= 64 { + let amount = 64 - buffer.count + buffer.append(ptr, count: amount) + try buffer.withUnsafeBytes { (body: UnsafeRawBufferPointer) in + if let bodyAddress = body.baseAddress, body.count > 0 { + let pointer = bodyAddress.assumingMemoryBound(to: Void.self) + _ = memcpy(&X, pointer, 64) + } else { + throw Web3Error.dataError + } + } + compress(X) + ptr += amount + length -= amount + } + // Process 64 byte chunks: + while length >= 64 { + memcpy(&X, ptr, 64) + compress(X) + ptr += 64 + length -= 64 + } + // Save remaining unprocessed bytes: + buffer = Data(bytes: ptr, count: length) + } else { + throw Web3Error.dataError + } + } + count += Int64(data.count) + } + + public mutating func finalize() throws -> Data { + var X = [UInt32](repeating: 0, count: 16) + /* append the bit m_n == 1 */ + buffer.append(0x80) + try buffer.withUnsafeBytes { (body: UnsafeRawBufferPointer) in + if let bodyAddress = body.baseAddress, body.count > 0 { + let pointer = bodyAddress.assumingMemoryBound(to: Void.self) + _ = memcpy(&X, pointer, buffer.count) + } else { + throw Web3Error.dataError + } + } + + if (count & 63) > 55 { + /* length goes to next block */ + compress(X) + X = [UInt32](repeating: 0, count: 16) + } + + /* append length in bits */ + let lswlen = UInt32(truncatingIfNeeded: count) + let mswlen = UInt32(UInt64(count) >> 32) + X[14] = lswlen << 3 + X[15] = (lswlen >> 29) | (mswlen << 3) + compress(X) + + var data = Data(count: 20) + try data.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) in + if let bodyAddress = body.baseAddress, body.count > 0 { + let pointer = bodyAddress.assumingMemoryBound(to: UInt32.self) + pointer[0] = MDbuf.0 + pointer[1] = MDbuf.1 + pointer[2] = MDbuf.2 + pointer[3] = MDbuf.3 + pointer[4] = MDbuf.4 + } else { + throw Web3Error.dataError + } + } + + buffer = Data() + + return data + } + + // public mutating func update(data: Data) throws { + // try data.withUnsafeBytes { (body: UnsafeRawBufferPointer) in + // + // if let bodyAddress = body.baseAddress, body.count > 0 { + // var ptr = bodyAddress.assumingMemoryBound(to: UInt8.self) + // var length = data.count + // var X = [UInt32](repeating: 0, count: 16) + // + // // Process remaining bytes from last call: + // if buffer.count > 0 && buffer.count + length >= 64 { + // let amount = 64 - buffer.count + // buffer.append(ptr, count: amount) + // try buffer.withUnsafeBytes { (body: UnsafeRawBufferPointer) in + // if let bodyAddress = body.baseAddress, body.count > 0 { + // let pointer = bodyAddress.assumingMemoryBound(to: Void.self) + // _ = memcpy(&X, pointer, 64) + // } else { + // throw Web3Error.dataError + // } + // } + // compress(X) + // ptr += amount + // length -= amount + // } + // // Process 64 byte chunks: + // while length >= 64 { + // memcpy(&X, ptr, 64) + // compress(X) + // ptr += 64 + // length -= 64 + // } + // // Save remaining unprocessed bytes: + // buffer = Data(bytes: ptr, count: length) + // } else { + // throw Web3Error.dataError + // } + // + // } + // count += Int64(data.count) + // } + // + // public mutating func finalize() throws -> Data { + // var X = [UInt32](repeating: 0, count: 16) + // /* append the bit m_n == 1 */ + // buffer.append(0x80) + // try buffer.withUnsafeBytes { (body: UnsafeRawBufferPointer) in + // if let bodyAddress = body.baseAddress, body.count > 0 { + // let pointer = bodyAddress.assumingMemoryBound(to: Void.self) + // _ = memcpy(&X, pointer, buffer.count) + // } else { + // throw Web3Error.dataError + // } + // } + // + // if (count & 63) > 55 { + // /* length goes to next block */ + // compress(X) + // X = [UInt32](repeating: 0, count: 16) + // } + // + // /* append length in bits */ + // let lswlen = UInt32(truncatingIfNeeded: count) + // let mswlen = UInt32(UInt64(count) >> 32) + // X[14] = lswlen << 3 + // X[15] = (lswlen >> 29) | (mswlen << 3) + // compress(X) + // + // var data = Data(count: 20) + // try data.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) in + // if let bodyAddress = body.baseAddress, body.count > 0 { + // let pointer = bodyAddress.assumingMemoryBound(to: UInt32.self) + // pointer[0] = MDbuf.0 + // pointer[1] = MDbuf.1 + // pointer[2] = MDbuf.2 + // pointer[3] = MDbuf.3 + // pointer[4] = MDbuf.4 + // } else { + // throw Web3Error.dataError + // } + // } + // + // buffer = Data() + // + // return data + // } +} + +public extension RIPEMD160 { + + static func hash(message: Data) throws -> Data { + var md = RIPEMD160() + try md.update(data: message) + return try md.finalize() + // return try md.finalize() + } + + static func hash(message: String) throws -> Data { + return try RIPEMD160.hash(message: message.data(using: .utf8)!) + // return try RIPEMD160.hash(message: message.data(using: .utf8)!) + } +} + +public extension RIPEMD160 { + + static func hmac(key: Data, message: Data) throws -> Data { + + var key = key + key.count = 64 // Truncate to 64 bytes or fill-up with zeros. + + // let outerKeyPad = Data(bytes: key.map { $0 ^ 0x5c }) + // let innerKeyPad = Data(bytes: key.map { $0 ^ 0x36 }) + let outerKeyPad = Data(key.map { $0 ^ 0x5c }) + let innerKeyPad = Data(key.map { $0 ^ 0x36 }) + + var innerMd = RIPEMD160() + try innerMd.update(data: innerKeyPad) + try innerMd.update(data: message) + // try innerMd.update(data: innerKeyPad) + // try innerMd.update(data: message) + + var outerMd = RIPEMD160() + try outerMd.update(data: outerKeyPad) + try outerMd.update(data: innerMd.finalize()) + // try outerMd.update(data: outerKeyPad) + // try outerMd.update(data: innerMd.finalize()) + + return try outerMd.finalize() + // return try outerMd.finalize() + } + + static func hmac(key: Data, message: String) throws -> Data { + return try RIPEMD160.hmac(key: key, message: message.data(using: .utf8)!) + // return try RIPEMD160.hmac(key: key, message: message.data(using: .utf8)!) + } + + static func hmac(key: String, message: String) throws -> Data { + return try RIPEMD160.hmac(key: key.data(using: .utf8)!, message: message) + // return try RIPEMD160.hmac(key: key.data(using: .utf8)!, message: message) + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/SECP256k1.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/SECP256k1.swift new file mode 100755 index 000000000..800a44765 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Convenience/SECP256k1.swift @@ -0,0 +1,385 @@ +// +// secp256k1.swift +// secp256k1_swift +// +// Created by Alexander Vlasov on 30.05.2018. +// Copyright © 2018 Alexander Vlasov. All rights reserved. +// + +import Foundation +import secp256k1 + +public struct SECP256K1 { + public struct UnmarshaledSignature{ + public var v: UInt8 = 0 + public var r = Data(repeating: 0, count: 32) + public var s = Data(repeating: 0, count: 32) + + public init(v: UInt8, r: Data, s: Data) { + self.v = v + self.r = r + self.s = s + } + } +} + +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 !SECP256K1.verifyPrivateKey(privateKey: privateKey) { + return (nil, nil) + } + for _ in 0...1024 { + guard var recoverableSignature = SECP256K1.recoverableSign(hash: hash, privateKey: privateKey, useExtraEntropy: useExtraEntropy) else { + continue + } + guard let truePublicKey = SECP256K1.privateKeyToPublicKey(privateKey: privateKey) else {continue} + guard let recoveredPublicKey = SECP256K1.recoverPublicKey(hash: hash, recoverableSignature: &recoverableSignature) else {continue} + if !SECP256K1.constantTimeComparison(Data(toByteArray(truePublicKey.data)), Data(toByteArray(recoveredPublicKey.data))) { + continue + } + guard let serializedSignature = SECP256K1.serializeSignature(recoverableSignature: &recoverableSignature) else {continue} + let rawSignature = Data(toByteArray(recoverableSignature)) + return (serializedSignature, rawSignature) + } + return (nil, nil) + } + + 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} + return serializedKey + } + + public static func combineSerializedPublicKeys(keys: [Data], outputCompressed: Bool = false) -> Data? { + let numToCombine = keys.count + guard numToCombine >= 1 else { return nil} + var storage = ContiguousArray() + let arrayOfPointers = UnsafeMutablePointer< UnsafePointer? >.allocate(capacity: numToCombine) + defer { + arrayOfPointers.deinitialize(count: numToCombine) + arrayOfPointers.deallocate() + } + for i in 0 ..< numToCombine { + let key = keys[i] + guard let pubkey = SECP256K1.parsePublicKey(serializedKey: key) else {return nil} + storage.append(pubkey) + } + for i in 0 ..< numToCombine { + withUnsafePointer(to: &storage[i]) { (ptr) -> Void in + arrayOfPointers.advanced(by: i).pointee = ptr + } + } + 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) + return res + } + if result == 0 { + return nil + } + let serializedKey = SECP256K1.serializePublicKey(publicKey: &publicKey, compressed: outputCompressed) + return serializedKey + } + + + internal static func recoverPublicKey(hash: Data, recoverableSignature: inout secp256k1_ecdsa_recoverable_signature) -> secp256k1_pubkey? { + guard hash.count == 32 else {return nil} + var publicKey: secp256k1_pubkey = secp256k1_pubkey() + 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 res + }) + }) + } else { + return nil + } + }) + guard let res = result, res != 0 else { + return nil + } + return publicKey + } + + internal static func privateKeyToPublicKey(privateKey: Data) -> secp256k1_pubkey? { + 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!, UnsafeMutablePointer(&publicKey), privateKeyPointer) + return res + } else { + return nil + } + } + guard let res = result, res != 0 else { + return nil + } + return publicKey + } + + public static func serializePublicKey(publicKey: inout secp256k1_pubkey, compressed: Bool = false) -> Data? { + 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 res + }) + }) + } else { + return nil + } + } + guard let res = result, res != 0 else { + return nil + } + return Data(serializedPubkey) + } + + internal static func parsePublicKey(serializedKey: Data) -> secp256k1_pubkey? { + guard serializedKey.count == 33 || serializedKey.count == 65 else { + return nil + } + let keyLen: Int = Int(serializedKey.count) + var publicKey = secp256k1_pubkey() + 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!, UnsafeMutablePointer(&publicKey), serializedKeyPointer, keyLen) + return res + } else { + return nil + } + } + guard let res = result, res != 0 else { + return nil + } + return publicKey + } + + public static func parseSignature(signature: Data) -> secp256k1_ecdsa_recoverable_signature? { + guard 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]) + if v >= 27 && v <= 30 { + v -= 27 + } else if v >= 31 && v <= 34 { + v -= 31 + } else if v >= 35 && v <= 38 { + v -= 35 + } + 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 res + }) + } else { + return nil + } + } + guard let res = result, res != 0 else { + return nil + } + return recoverableSignature + } + + internal static func serializeSignature(recoverableSignature: inout secp256k1_ecdsa_recoverable_signature) -> Data? { + 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) + return res + }) + } + } else { + return nil + } + } + guard let res = result, res != 0 else { + return nil + } + if (v == 0 || v == 27 || v == 31 || v == 35) { + serializedSignature.append(0x1b) + } else if (v == 1 || v == 28 || v == 32 || v == 36) { + serializedSignature.append(0x1c) + } else { + return nil + } + return Data(serializedSignature) + } + + internal static func recoverableSign(hash: Data, privateKey: Data, useExtraEntropy: Bool = false) -> secp256k1_ecdsa_recoverable_signature? { + if (hash.count != 32 || privateKey.count != 32) { + return nil + } + if !SECP256K1.verifyPrivateKey(privateKey: privateKey) { + return nil + } + var recoverableSignature: secp256k1_ecdsa_recoverable_signature = secp256k1_ecdsa_recoverable_signature(); + 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 + if let privateKeyRPointer = privateKeyRBPointer.baseAddress, privateKeyRBPointer.count > 0 { + let privateKeyPointer = privateKeyRPointer.assumingMemoryBound(to: UInt8.self) + 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 res + }) + } else { + return nil + } + }) + } else { + return nil + } + }) + } else { + return nil + } + } + guard let res = result, res != 0 else { + print("Failed to sign!") + return nil + } + return recoverableSignature + } + + 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} + return serializedKey + } + + + public static func verifyPrivateKey(privateKey: Data) -> Bool { + if (privateKey.count != 32) {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) + return res + } else { + return nil + } + } + guard let res = result, res == 1 else { + return false + } + return true + } + + public static func generatePrivateKey() -> Data? { + for _ in 0...1024 { + guard let keyData = SECP256K1.randomBytes(length: 32) else { + continue + } + guard SECP256K1.verifyPrivateKey(privateKey: keyData) else { + continue + } + return keyData + } + return nil + } + + public static func unmarshalSignature(signatureData:Data) -> UnmarshaledSignature? { + if (signatureData.count != 65) {return nil} + let v = signatureData[64] + let r = Data(signatureData[0..<32]) + let s = Data(signatureData[32..<64]) + return UnmarshaledSignature(v: v, r: r, s: s) + } + + public static func marshalSignature(v: UInt8, r: [UInt8], s: [UInt8]) -> Data? { + guard r.count == 32, s.count == 32 else {return nil} + var completeSignature = Data(r) + completeSignature.append(Data(s)) + completeSignature.append(Data([v])) + return completeSignature + } + + public static func marshalSignature(v: Data, r: Data, s: Data) -> Data? { + guard r.count == 32, s.count == 32 else {return nil} + var completeSignature = Data(r) + completeSignature.append(s) + completeSignature.append(v) + return completeSignature + } + + internal static func randomBytes(length: Int) -> Data? { + for _ in 0...1024 { + var data = Data(repeating: 0, count: length) + let result = data.withUnsafeMutableBytes { (mutableRBBytes) -> Int32? in + if let mutableRBytes = mutableRBBytes.baseAddress, mutableRBBytes.count > 0 { + let mutableBytes = mutableRBytes.assumingMemoryBound(to: UInt8.self) + return SecRandomCopyBytes(kSecRandomDefault, 32, mutableBytes) + } else { + return nil + } + } + if let res = result, res == errSecSuccess { + return data + } else { + continue + } + } + return nil + } + + internal static func toByteArray(_ value: T) -> [UInt8] { + var value = value + return withUnsafeBytes(of: &value) { Array($0) } + } + + internal static func fromByteArray(_ value: [UInt8], _: T.Type) -> T { + return value.withUnsafeBytes { + $0.baseAddress!.load(as: T.self) + } + } + + internal static func constantTimeComparison(_ lhs: Data, _ rhs:Data) -> Bool { + guard lhs.count == rhs.count else {return false} + var difference = UInt8(0x00) + for i in 0.. { + return startIndex.. Index? { + guard let range = range(of: String(char)) else { + return nil + } + return range.lowerBound + } + + func split(intoChunksOf chunkSize: Int) -> [String] { + var output = [String]() + let splittedString = self + .map { $0 } + .split(intoChunksOf: chunkSize) + splittedString.forEach { + output.append($0.map { String($0) }.joined(separator: "")) + } + return output + } + + subscript (bounds: CountableClosedRange) -> String { + let start = index(self.startIndex, offsetBy: bounds.lowerBound) + let end = index(self.startIndex, offsetBy: bounds.upperBound) + return String(self[start...end]) + } + + subscript (bounds: CountableRange) -> String { + let start = index(self.startIndex, offsetBy: bounds.lowerBound) + let end = index(self.startIndex, offsetBy: bounds.upperBound) + return String(self[start..) -> String { + let start = index(self.startIndex, offsetBy: bounds.lowerBound) + let end = self.endIndex + return String(self[start.. String { + let stringLength = self.count + if stringLength < toLength { + return String(repeatElement(character, count: toLength - stringLength)) + self + } else { + return String(self.suffix(toLength)) + } + } + + func interpretAsBinaryData() -> Data? { + let padded = self.padding(toLength: ((self.count + 7) / 8) * 8, withPad: "0", startingAt: 0) + let byteArray = padded.split(intoChunksOf: 8).map { UInt8(strtoul($0, nil, 2)) } + return Data(byteArray) + } + + func hasHexPrefix() -> Bool { + return self.hasPrefix("0x") + } + + func stripHexPrefix() -> String { + if self.hasPrefix("0x") { + let indexStart = self.index(self.startIndex, offsetBy: 2) + return String(self[indexStart...]) + } + return self + } + + func addHexPrefix() -> String { + if !self.hasPrefix("0x") { + return "0x" + self + } + return self + } + + func stripLeadingZeroes() -> String? { + let hex = self.addHexPrefix() + guard let matcher = try? NSRegularExpression(pattern: "^(?0x)0*(?[0-9a-fA-F]*)$", options: NSRegularExpression.Options.dotMatchesLineSeparators) else {return nil} + let match = matcher.captureGroups(string: hex, options: NSRegularExpression.MatchingOptions.anchored) + guard let prefix = match["prefix"] else {return nil} + guard let end = match["end"] else {return nil} + if (end != "") { + return prefix + end + } + return "0x0" + } + + func matchingStrings(regex: String) -> [[String]] { + guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] } + let nsString = self as NSString + let results = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length)) + return results.map { result in + (0.. Range? { + guard + let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex), + let to16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location + nsRange.length, limitedBy: utf16.endIndex), + let from = from16.samePosition(in: self), + let to = to16.samePosition(in: self) + else { return nil } + return from ..< to + } + + var asciiValue: Int { + get { + let s = self.unicodeScalars + return Int(s[s.startIndex].value) + } + } +} + +extension Character { + var asciiValue: Int { + get { + let s = String(self).unicodeScalars + return Int(s[s.startIndex].value) + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABI.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABI.swift new file mode 100755 index 000000000..d139fd3b0 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABI.swift @@ -0,0 +1,28 @@ +// +// Created by Alex Vlasov on 25/10/2018. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +public struct ABI { + +} + +protocol ABIElementPropertiesProtocol { + var isStatic: Bool {get} + var isArray: Bool {get} + var isTuple: Bool {get} + var arraySize: ABI.Element.ArraySize {get} + var subtype: ABI.Element.ParameterType? {get} + var memoryUsage: UInt64 {get} + var emptyValue: Any {get} +} + +protocol ABIEncoding { + var abiRepresentation: String {get} +} + +protocol ABIValidation { + var isValid: Bool {get} +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABIDecoding.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABIDecoding.swift new file mode 100755 index 000000000..eae5c332b --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABIDecoding.swift @@ -0,0 +1,286 @@ +// +// Created by Alex Vlasov on 25/10/2018. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt + +public struct ABIDecoder { + +} + +extension ABIDecoder { + public static func decode(types: [ABI.Element.InOut], data: Data) -> [AnyObject]? { + let params = types.compactMap { (el) -> ABI.Element.ParameterType in + return el.type + } + return decode(types: params, data: data) + } + + public static func decode(types: [ABI.Element.ParameterType], data: Data) -> [AnyObject]? { + // print("Full data: \n" + data.toHexString()) + var toReturn = [AnyObject]() + var consumed: UInt64 = 0 + for i in 0 ..< types.count { + let (v, c) = decodeSignleType(type: types[i], data: data, pointer: consumed) + guard let valueUnwrapped = v, let consumedUnwrapped = c else {return nil} + toReturn.append(valueUnwrapped) + consumed = consumed + consumedUnwrapped + } + guard toReturn.count == types.count else {return nil} + return toReturn + } + + public static func decodeSignleType(type: ABI.Element.ParameterType, data: Data, pointer: UInt64 = 0) -> (value: AnyObject?, bytesConsumed: UInt64?) { + let (elData, nextPtr) = followTheData(type: type, data: data, pointer: pointer) + guard let elementItself = elData, let nextElementPointer = nextPtr else { + return (nil, nil) + } + switch type { + case .uint(let bits): + // print("Uint256 element itself: \n" + elementItself.toHexString()) + guard elementItself.count >= 32 else {break} + let mod = BigUInt(1) << bits + let dataSlice = elementItself[0 ..< 32] + let v = BigUInt(dataSlice) % mod + // print("Uint256 element is: \n" + String(v)) + return (v as AnyObject, type.memoryUsage) + case .int(let bits): + // print("Int256 element itself: \n" + elementItself.toHexString()) + guard elementItself.count >= 32 else {break} + let mod = BigInt(1) << bits + let dataSlice = elementItself[0 ..< 32] + let v = BigInt.fromTwosComplement(data: dataSlice) % mod + // print("Int256 element is: \n" + String(v)) + return (v as AnyObject, type.memoryUsage) + case .address: + // print("Address element itself: \n" + elementItself.toHexString()) + guard elementItself.count >= 32 else {break} + let dataSlice = elementItself[12 ..< 32] + let address = EthereumAddress(dataSlice) + // print("Address element is: \n" + String(address.address)) + return (address as AnyObject, type.memoryUsage) + case .bool: + // print("Bool element itself: \n" + elementItself.toHexString()) + guard elementItself.count >= 32 else {break} + let dataSlice = elementItself[0 ..< 32] + let v = BigUInt(dataSlice) + // print("Address element is: \n" + String(v)) + if v == BigUInt(36) || + v == BigUInt(32) || + v == BigUInt(28) || + v == BigUInt(1) { + return (true as AnyObject, type.memoryUsage) + } else if v == BigUInt(35) || + v == BigUInt(31) || + v == BigUInt(27) || + v == BigUInt(0) { + return (false as AnyObject, type.memoryUsage) + } + case .bytes(let length): + // print("Bytes32 element itself: \n" + elementItself.toHexString()) + guard elementItself.count >= 32 else {break} + let dataSlice = elementItself[0 ..< length] + // print("Bytes32 element is: \n" + String(dataSlice.toHexString())) + return (dataSlice as AnyObject, type.memoryUsage) + case .string: + // print("String element itself: \n" + elementItself.toHexString()) + guard elementItself.count >= 32 else {break} + var dataSlice = elementItself[0 ..< 32] + let length = UInt64(BigUInt(dataSlice)) + guard elementItself.count >= 32+length else {break} + dataSlice = elementItself[32 ..< 32 + length] + guard let string = String(data: dataSlice, encoding: .utf8) else {break} + // print("String element is: \n" + String(string)) + return (string as AnyObject, type.memoryUsage) + case .dynamicBytes: + // print("Bytes element itself: \n" + elementItself.toHexString()) + guard elementItself.count >= 32 else {break} + var dataSlice = elementItself[0 ..< 32] + let length = UInt64(BigUInt(dataSlice)) + guard elementItself.count >= 32+length else {break} + dataSlice = elementItself[32 ..< 32 + length] + // print("Bytes element is: \n" + String(dataSlice.toHexString())) + return (dataSlice as AnyObject, type.memoryUsage) + case .array(type: let subType, length: let length): + switch type.arraySize { + case .dynamicSize: + // print("Dynamic array element itself: \n" + elementItself.toHexString()) + if subType.isStatic { + // uint[] like, expect length and elements + guard elementItself.count >= 32 else {break} + var dataSlice = elementItself[0 ..< 32] + let length = UInt64(BigUInt(dataSlice)) + guard elementItself.count >= 32 + subType.memoryUsage*length else {break} + dataSlice = elementItself[32 ..< 32 + subType.memoryUsage*length] + var subpointer: UInt64 = 32; + var toReturn = [AnyObject]() + for _ in 0 ..< length { + let (v, c) = decodeSignleType(type: subType, data: elementItself, pointer: subpointer) + guard let valueUnwrapped = v, let consumedUnwrapped = c else {break} + toReturn.append(valueUnwrapped) + subpointer = subpointer + consumedUnwrapped + } + return (toReturn as AnyObject, type.memoryUsage) + } else { + // in principle is true for tuple[], so will work for string[] too + guard elementItself.count >= 32 else {break} + var dataSlice = elementItself[0 ..< 32] + let length = UInt64(BigUInt(dataSlice)) + guard elementItself.count >= 32 else {break} + dataSlice = Data(elementItself[32 ..< elementItself.count]) + var subpointer: UInt64 = 0; + var toReturn = [AnyObject]() + // print("Dynamic array sub element itself: \n" + dataSlice.toHexString()) + for _ in 0 ..< length { + let (v, c) = decodeSignleType(type: subType, data: dataSlice, pointer: subpointer) + guard let valueUnwrapped = v, let consumedUnwrapped = c else {break} + toReturn.append(valueUnwrapped) + subpointer = subpointer + consumedUnwrapped + } + return (toReturn as AnyObject, nextElementPointer) + } + case .staticSize(let staticLength): + // print("Static array element itself: \n" + elementItself.toHexString()) + guard length == staticLength else {break} + var toReturn = [AnyObject]() + var consumed:UInt64 = 0 + for _ in 0 ..< length { + let (v, c) = decodeSignleType(type: subType, data: elementItself, pointer: consumed) + guard let valueUnwrapped = v, let consumedUnwrapped = c else {return (nil, nil)} + toReturn.append(valueUnwrapped) + consumed = consumed + consumedUnwrapped + } + if subType.isStatic { + return (toReturn as AnyObject, consumed) + } else { + return (toReturn as AnyObject, nextElementPointer) + } + case .notArray: + break + } + case .tuple(types: let subTypes): + // print("Tuple element itself: \n" + elementItself.toHexString()) + var toReturn = [AnyObject]() + var consumed:UInt64 = 0 + for i in 0 ..< subTypes.count { + let (v, c) = decodeSignleType(type: subTypes[i], data: elementItself, pointer: consumed) + guard let valueUnwrapped = v, let consumedUnwrapped = c else {return (nil, nil)} + toReturn.append(valueUnwrapped) + consumed = consumed + consumedUnwrapped + } + // print("Tuple element is: \n" + String(describing: toReturn)) + if type.isStatic { + return (toReturn as AnyObject, consumed) + } else { + return (toReturn as AnyObject, nextElementPointer) + } + case .function: + // print("Function element itself: \n" + elementItself.toHexString()) + guard elementItself.count >= 32 else {break} + let dataSlice = elementItself[8 ..< 32] + // print("Function element is: \n" + String(dataSlice.toHexString())) + return (dataSlice as AnyObject, type.memoryUsage) + } + return (nil, nil) + } + + fileprivate static func followTheData(type: ABI.Element.ParameterType, data: Data, pointer: UInt64 = 0) -> (elementEncoding: Data?, nextElementPointer: UInt64?) { + // print("Follow the data: \n" + data.toHexString()) + // print("At pointer: \n" + String(pointer)) + if type.isStatic { + guard data.count >= pointer + type.memoryUsage else {return (nil, nil)} + let elementItself = data[pointer ..< pointer + type.memoryUsage] + let nextElement = pointer + type.memoryUsage + // print("Got element itself: \n" + elementItself.toHexString()) + // print("Next element pointer: \n" + String(nextElement)) + return (Data(elementItself), nextElement) + } else { + guard data.count >= pointer + type.memoryUsage else {return (nil, nil)} + let dataSlice = data[pointer ..< pointer + type.memoryUsage] + let bn = BigUInt(dataSlice) + if bn > UINT64_MAX || bn >= data.count { + // there are ERC20 contracts that use bytes32 intead of string. Let's be optimistic and return some data + if case .string = type { + let nextElement = pointer + type.memoryUsage + let preambula = BigUInt(32).abiEncode(bits: 256)! + return (preambula + Data(dataSlice), nextElement) + } else if case .dynamicBytes = type { + let nextElement = pointer + type.memoryUsage + let preambula = BigUInt(32).abiEncode(bits: 256)! + return (preambula + Data(dataSlice), nextElement) + } + return (nil, nil) + } + let elementPointer = UInt64(bn) + let elementItself = data[elementPointer ..< UInt64(data.count)] + let nextElement = pointer + type.memoryUsage + // print("Got element itself: \n" + elementItself.toHexString()) + // print("Next element pointer: \n" + String(nextElement)) + return (Data(elementItself), nextElement) + } + } + + public static func decodeLog(event: ABI.Element.Event, eventLogTopics: [Data], eventLogData: Data) -> [String:Any]? { + if event.topic != eventLogTopics[0] && !event.anonymous { + return nil + } + var eventContent = [String: Any]() + eventContent["name"]=event.name + let logs = eventLogTopics + let dataForProcessing = eventLogData + let indexedInputs = event.inputs.filter { (inp) -> Bool in + return inp.indexed + } + if (logs.count == 1 && indexedInputs.count > 0) { + return nil + } + let nonIndexedInputs = event.inputs.filter { (inp) -> Bool in + return !inp.indexed + } + let nonIndexedTypes = nonIndexedInputs.compactMap { (inp) -> ABI.Element.ParameterType in + return inp.type + } + guard logs.count == indexedInputs.count + 1 else {return nil} + var indexedValues = [AnyObject]() + 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.decodeSignleType(type: .bytes(length: 32), data: data) + guard let valueUnwrapped = v else {return nil} + indexedValues.append(valueUnwrapped) + } else { + let (v, _) = ABIDecoder.decodeSignleType(type: input.type, data: data) + 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} + var indexedInputCounter = 0 + var nonIndexedInputCounter = 0 + for i in 0 ..< event.inputs.count { + let el = event.inputs[i] + if el.indexed { + let name = "\(i)" + let value = indexedValues[indexedInputCounter] + eventContent[name] = value + if el.name != "" { + eventContent[el.name] = value + } + indexedInputCounter = indexedInputCounter + 1 + } else { + let name = "\(i)" + let value = nonIndexedValues[nonIndexedInputCounter] + eventContent[name] = value + if el.name != "" { + eventContent[el.name] = value + } + nonIndexedInputCounter = nonIndexedInputCounter + 1 + } + } + return eventContent + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABIElements.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABIElements.swift new file mode 100755 index 000000000..7f76012f6 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABIElements.swift @@ -0,0 +1,286 @@ +// +// Created by Alex Vlasov on 25/10/2018. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt + +public extension ABI { + // JSON Decoding + struct Input: Decodable { + public var name: String? + public var type: String + public var indexed: Bool? + public var components: [Input]? + } + + struct Output: Decodable { + public var name: String? + public var type: String + public var components: [Output]? + } + + struct Record: Decodable { + public var name: String? + public var type: String? + public var payable: Bool? + public var constant: Bool? + public var stateMutability: String? + public var inputs: [ABI.Input]? + public var outputs: [ABI.Output]? + public var anonymous: Bool? + } + + enum Element { + public enum ArraySize { //bytes for convenience + case staticSize(UInt64) + case dynamicSize + case notArray + } + + case function(Function) + case constructor(Constructor) + case fallback(Fallback) + case event(Event) + + public enum StateMutability { + case payable + case mutating + case view + case pure + + var isConstant: Bool { + switch self { + case .payable: + return false + case .mutating: + return false + default: + return true + } + } + + var isPayable: Bool { + switch self { + case .payable: + return true + default: + return false + } + } + } + + public struct InOut { + public let name: String + public let type: ParameterType + + public init(name: String, type: ParameterType) { + self.name = name + self.type = type + } + } + + public struct Function { + public let name: String? + public let inputs: [InOut] + public let outputs: [InOut] + public let stateMutability: StateMutability? = nil + public let constant: Bool + public let payable: Bool + + public init(name: String?, inputs: [InOut], outputs: [InOut], constant: Bool, payable: Bool) { + self.name = name + self.inputs = inputs + self.outputs = outputs + self.constant = constant + self.payable = payable + } + } + + public struct Constructor { + public let inputs: [InOut] + public let constant: Bool + public let payable: Bool + public init(inputs: [InOut], constant: Bool, payable: Bool) { + self.inputs = inputs + self.constant = constant + self.payable = payable + } + } + + public struct Fallback { + public let constant: Bool + public let payable: Bool + + public init(constant: Bool, payable: Bool) { + self.constant = constant + self.payable = payable + } + } + + public struct Event { + public let name: String + public let inputs: [Input] + public let anonymous: Bool + + public init(name: String, inputs: [Input], anonymous: Bool) { + self.name = name + self.inputs = inputs + self.anonymous = anonymous + } + + public struct Input { + public let name: String + public let type: ParameterType + public let indexed: Bool + + public init(name: String, type: ParameterType, indexed: Bool) { + self.name = name + self.type = type + self.indexed = indexed + } + } + } + } +} + +extension ABI.Element { + public func encodeParameters(_ parameters: [AnyObject]) -> Data? { + switch self { + case .constructor(let constructor): + guard parameters.count == constructor.inputs.count else {return nil} + guard let data = ABIEncoder.encode(types: constructor.inputs, values: parameters) else {return nil} + return data + case .event(_): + return nil + case .fallback(_): + return nil + case .function(let function): + guard parameters.count == function.inputs.count else {return nil} + let signature = function.methodEncoding + guard let data = ABIEncoder.encode(types: function.inputs, values: parameters) else {return nil} + return signature + data + } + } +} + +extension ABI.Element { + public func decodeReturnData(_ data: Data) -> [String:Any]? { + switch self { + case .constructor(_): + return nil + case .event(_): + return nil + case .fallback(_): + return nil + case .function(let function): + if (data.count == 0 && function.outputs.count == 1) { + let name = "0" + let value = function.outputs[0].type.emptyValue + var returnArray = [String:Any]() + returnArray[name] = value + if function.outputs[0].name != "" { + returnArray[function.outputs[0].name] = value + } + return returnArray + } + + guard function.outputs.count*32 <= data.count else {return nil} + var returnArray = [String:Any]() + var i = 0; + guard let values = ABIDecoder.decode(types: function.outputs, data: data) else {return nil} + for output in function.outputs { + let name = "\(i)" + returnArray[name] = values[i] + if output.name != "" { + returnArray[output.name] = values[i] + } + i = i + 1 + } + return returnArray + } + } + + public func decodeInputData(_ rawData: Data) -> [String: Any]? { + var data = rawData + var sig: Data? = nil + switch rawData.count % 32 { + case 0: + break + case 4: + sig = rawData[0 ..< 4] + data = Data(rawData[4 ..< rawData.count]) + default: + return nil + } + switch self { + case .constructor(let function): + if (data.count == 0 && function.inputs.count == 1) { + let name = "0" + let value = function.inputs[0].type.emptyValue + var returnArray = [String:Any]() + returnArray[name] = value + if function.inputs[0].name != "" { + returnArray[function.inputs[0].name] = value + } + return returnArray + } + + guard function.inputs.count*32 <= data.count else {return nil} + var returnArray = [String:Any]() + var i = 0; + guard let values = ABIDecoder.decode(types: function.inputs, data: data) else {return nil} + for input in function.inputs { + let name = "\(i)" + returnArray[name] = values[i] + if input.name != "" { + returnArray[input.name] = values[i] + } + i = i + 1 + } + return returnArray + case .event(_): + return nil + case .fallback(_): + return nil + case .function(let function): + if sig != nil && sig != function.methodEncoding { + return nil + } + if (data.count == 0 && function.inputs.count == 1) { + let name = "0" + let value = function.inputs[0].type.emptyValue + var returnArray = [String:Any]() + returnArray[name] = value + if function.inputs[0].name != "" { + returnArray[function.inputs[0].name] = value + } + return returnArray + } + + guard function.inputs.count*32 <= data.count else {return nil} + var returnArray = [String:Any]() + var i = 0; + guard let values = ABIDecoder.decode(types: function.inputs, data: data) else {return nil} + for input in function.inputs { + let name = "\(i)" + returnArray[name] = values[i] + if input.name != "" { + returnArray[input.name] = values[i] + } + i = i + 1 + } + return returnArray + } + } +} + +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} + return eventContent + } +} + + diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABIEncoding.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABIEncoding.swift new file mode 100755 index 000000000..16c358f91 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABIEncoding.swift @@ -0,0 +1,388 @@ +// +// Created by Alex Vlasov on 25/10/2018. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt + +public struct ABIEncoder { + +} + +extension ABIEncoder { + public static func convertToBigUInt(_ value: AnyObject) -> BigUInt? { + switch value { + case let v as BigUInt: + return v + case let v as BigInt: + switch v.sign { + case .minus: + return nil + case .plus: + return v.magnitude + } + case let v as String: + let base10 = BigUInt(v, radix: 10) + if base10 != nil { + return base10! + } + let base16 = BigUInt(v.stripHexPrefix(), radix: 16) + if base16 != nil { + return base16! + } + break + case let v as UInt: + return BigUInt(v) + case let v as UInt8: + return BigUInt(v) + case let v as UInt16: + return BigUInt(v) + case let v as UInt32: + return BigUInt(v) + case let v as UInt64: + return BigUInt(v) + case let v as Int: + return BigUInt(v) + case let v as Int8: + return BigUInt(v) + case let v as Int16: + return BigUInt(v) + case let v as Int32: + return BigUInt(v) + case let v as Int64: + return BigUInt(v) + default: + return nil + } + return nil + } + + public static func convertToBigInt(_ value: AnyObject) -> BigInt? { + switch value { + case let v as BigUInt: + return BigInt(v) + case let v as BigInt: + return v + case let v as String: + let base10 = BigInt(v, radix: 10) + if base10 != nil { + return base10 + } + let base16 = BigInt(v.stripHexPrefix(), radix: 16) + if base16 != nil { + return base16 + } + break + case let v as UInt: + return BigInt(v) + case let v as UInt8: + return BigInt(v) + case let v as UInt16: + return BigInt(v) + case let v as UInt32: + return BigInt(v) + case let v as UInt64: + return BigInt(v) + case let v as Int: + return BigInt(v) + case let v as Int8: + return BigInt(v) + case let v as Int16: + return BigInt(v) + case let v as Int32: + return BigInt(v) + case let v as Int64: + return BigInt(v) + default: + return nil + } + return nil + } + + public static func convertToData(_ value: AnyObject) -> Data? { + switch value { + case let d as Data: + return d + case let d as String: + if d.hasHexPrefix() { + let hex = Data.fromHex(d) + if hex != nil { + return hex + } + } + let str = d.data(using: .utf8) + if str != nil { + return str + } + case let d as [UInt8]: + return Data(d) + case let d as EthereumAddress: + return d.addressData + case let d as [IntegerLiteralType]: + var bytesArray = [UInt8]() + for el in d { + guard el >= 0, el <= 255 else {return nil} + bytesArray.append(UInt8(el)) + } + return Data(bytesArray) + default: + return nil + } + return nil + } + + + public static func encode(types: [ABI.Element.InOut], values: [AnyObject]) -> Data? { + guard types.count == values.count else {return nil} + let params = types.compactMap { (el) -> ABI.Element.ParameterType in + return el.type + } + return encode(types: params, values: values) + } + + public static func encode(types: [ABI.Element.ParameterType], values: [AnyObject]) -> Data? { + 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} + if types[i].isStatic { + heads.append(encoding) + tails.append(Data()) + } else { + heads.append(Data(repeating: 0x0, count: 32)) + tails.append(encoding) + } + } + var headsConcatenated = Data() + for h in heads { + headsConcatenated.append(h) + } + var tailsPointer = BigUInt(headsConcatenated.count) + headsConcatenated = Data() + var tailsConcatenated = Data() + for i in 0 ..< types.count { + let head = heads[i] + let tail = tails[i] + if !types[i].isStatic { + guard let newHead = tailsPointer.abiEncode(bits: 256) else {return nil} + headsConcatenated.append(newHead) + tailsConcatenated.append(tail) + tailsPointer = tailsPointer + BigUInt(tail.count) + } else { + headsConcatenated.append(head) + tailsConcatenated.append(tail) + } + } + return headsConcatenated + tailsConcatenated + } + + public static func encodeSingleType(type: ABI.Element.ParameterType, value: AnyObject) -> Data? { + switch type { + case .uint(_): + if let biguint = convertToBigUInt(value) { + return biguint.abiEncode(bits: 256) + } + if let bigint = convertToBigInt(value) { + return bigint.abiEncode(bits: 256) + } + case .int(_): + if let biguint = convertToBigUInt(value) { + return biguint.abiEncode(bits: 256) + } + if let bigint = convertToBigInt(value) { + return bigint.abiEncode(bits: 256) + } + case .address: + if let string = value as? String { + guard let address = EthereumAddress(string) else {return nil} + let data = address.addressData + return data.setLengthLeft(32) + } else if let address = value as? EthereumAddress { + guard address.isValid else {break} + let data = address.addressData + return data.setLengthLeft(32) + } else if let data = value as? Data { + return data.setLengthLeft(32) + } + case .bool: + if let bool = value as? Bool { + if (bool) { + return BigUInt(1).abiEncode(bits: 256) + } else { + return BigUInt(0).abiEncode(bits: 256) + } + } + case .bytes(let length): + guard let data = convertToData(value) else {break} + if data.count > length {break} + return data.setLengthRight(32) + case .string: + if let string = value as? String { + var dataGuess: Data? + if string.hasHexPrefix() { + dataGuess = Data.fromHex(string.lowercased().stripHexPrefix()) + } + else { + dataGuess = string.data(using: .utf8) + } + guard let data = dataGuess else {break} + let minLength = ((data.count + 31) / 32)*32 + guard let paddedData = data.setLengthRight(UInt64(minLength)) else {break} + let length = BigUInt(data.count) + guard let head = length.abiEncode(bits: 256) else {break} + let total = head+paddedData + return total + } + case .dynamicBytes: + guard let data = convertToData(value) else {break} + let minLength = ((data.count + 31) / 32)*32 + guard let paddedData = data.setLengthRight(UInt64(minLength)) else {break} + let length = BigUInt(data.count) + guard let head = length.abiEncode(bits: 256) else {break} + let total = head+paddedData + return total + case .array(type: let subType, length: let length): + switch type.arraySize { + case .dynamicSize: + guard length == 0 else {break} + guard let val = value as? [AnyObject] else {break} + guard let lengthEncoding = BigUInt(val.count).abiEncode(bits: 256) else {break} + if subType.isStatic { + // work in a previous context + var toReturn = Data() + for i in 0 ..< val.count { + let enc = encodeSingleType(type: subType, value: val[i]) + guard let encoding = enc else {break} + toReturn.append(encoding) + } + let total = lengthEncoding + toReturn + // print("Dynamic array of static types encoding :\n" + String(total.toHexString())) + return total + } else { + // create new context + var tails = [Data]() + var heads = [Data]() + for i in 0 ..< val.count { + let enc = encodeSingleType(type: subType, value: val[i]) + guard let encoding = enc else {return nil} + heads.append(Data(repeating: 0x0, count: 32)) + tails.append(encoding) + } + var headsConcatenated = Data() + for h in heads { + headsConcatenated.append(h) + } + var tailsPointer = BigUInt(headsConcatenated.count) + headsConcatenated = Data() + var tailsConcatenated = Data() + for i in 0 ..< val.count { + let head = heads[i] + let tail = tails[i] + if tail != Data() { + guard let newHead = tailsPointer.abiEncode(bits: 256) else {return nil} + headsConcatenated.append(newHead) + tailsConcatenated.append(tail) + tailsPointer = tailsPointer + BigUInt(tail.count) + } else { + headsConcatenated.append(head) + tailsConcatenated.append(tail) + } + } + let total = lengthEncoding + headsConcatenated + tailsConcatenated + // print("Dynamic array of dynamic types encoding :\n" + String(total.toHexString())) + return total + } + case .staticSize(let staticLength): + guard staticLength != 0 else {break} + guard let val = value as? [AnyObject] else {break} + guard staticLength == val.count else {break} + if subType.isStatic { + // work in a previous context + var toReturn = Data() + for i in 0 ..< val.count { + let enc = encodeSingleType(type: subType, value: val[i]) + guard let encoding = enc else {break} + toReturn.append(encoding) + } + // print("Static array of static types encoding :\n" + String(toReturn.toHexString())) + let total = toReturn + return total + } else { + // create new context + var tails = [Data]() + var heads = [Data]() + for i in 0 ..< val.count { + let enc = encodeSingleType(type: subType, value: val[i]) + guard let encoding = enc else {return nil} + heads.append(Data(repeating: 0x0, count: 32)) + tails.append(encoding) + } + var headsConcatenated = Data() + for h in heads { + headsConcatenated.append(h) + } + var tailsPointer = BigUInt(headsConcatenated.count) + headsConcatenated = Data() + var tailsConcatenated = Data() + for i in 0 ..< val.count { + let tail = tails[i] + guard let newHead = tailsPointer.abiEncode(bits: 256) else {return nil} + headsConcatenated.append(newHead) + tailsConcatenated.append(tail) + tailsPointer = tailsPointer + BigUInt(tail.count) + } + let total = headsConcatenated + tailsConcatenated + // print("Static array of dynamic types encoding :\n" + String(total.toHexString())) + return total + } + case .notArray: + break + } + case .tuple(types: let subTypes): + var tails = [Data]() + var heads = [Data]() + guard let val = value as? [AnyObject] else {break} + for i in 0 ..< subTypes.count { + let enc = encodeSingleType(type: subTypes[i], value: val[i]) + guard let encoding = enc else {return nil} + if subTypes[i].isStatic { + heads.append(encoding) + tails.append(Data()) + } else { + heads.append(Data(repeating: 0x0, count: 32)) + tails.append(encoding) + } + } + var headsConcatenated = Data() + for h in heads { + headsConcatenated.append(h) + } + var tailsPointer = BigUInt(headsConcatenated.count) + headsConcatenated = Data() + var tailsConcatenated = Data() + for i in 0 ..< subTypes.count { + let head = heads[i] + let tail = tails[i] + if !subTypes[i].isStatic { + guard let newHead = tailsPointer.abiEncode(bits: 256) else {return nil} + headsConcatenated.append(newHead) + tailsConcatenated.append(tail) + tailsPointer = tailsPointer + BigUInt(tail.count) + } else { + headsConcatenated.append(head) + tailsConcatenated.append(tail) + } + } + let total = headsConcatenated + tailsConcatenated + return total + case .function: + if let data = value as? Data { + return data.setLengthLeft(32) + } + } + return nil + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABIParameterTypes.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABIParameterTypes.swift new file mode 100755 index 000000000..0bbd8038b --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABIParameterTypes.swift @@ -0,0 +1,250 @@ +// +// Created by Alex Vlasov on 25/10/2018. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt + +extension ABI.Element { + + /// Specifies the type that parameters in a contract have. + public enum ParameterType: ABIElementPropertiesProtocol { + case uint(bits: UInt64) + case int(bits: UInt64) + case address + case function + case bool + case bytes(length: UInt64) + indirect case array(type: ParameterType, length: UInt64) + case dynamicBytes + case string + indirect case tuple(types: [ParameterType]) + + var isStatic: Bool { + switch self { + case .string: + return false + case .dynamicBytes: + return false + case .array(type: let type, length: let length): + if (length == 0) { + return false + } + if (!type.isStatic) { + return false + } + return true + case .tuple(types: let types): + for t in types { + if (!t.isStatic) { + return false + } + } + return true + case .bytes(length: _): + return true + default: + return true + } + } + + var isArray: Bool { + switch self { + case .array(type: _, length: _): + return true + default: + return false + } + } + + var isTuple: Bool { + switch self { + case .tuple(_): + return true + default: + return false + } + } + + var subtype: ABI.Element.ParameterType? { + switch self { + case .array(type: let type, length: _): + return type + default: + return nil + } + } + + var memoryUsage: UInt64 { + switch self { + case .array(_, length: let length): + if length == 0 { + return 32 + } + if self.isStatic { + return 32*length + } + return 32 + case .tuple(types: let types): + if !self.isStatic { + return 32 + } + var sum: UInt64 = 0; + for t in types { + sum = sum + t.memoryUsage + } + return sum + default: + return 32 + } + } + + var emptyValue: Any { + switch self { + case .uint(bits: _): + return BigUInt(0) + case .int(bits: _): + return BigUInt(0) + case .address: + return EthereumAddress("0x0000000000000000000000000000000000000000")! + case .function: + return Data(repeating: 0x00, count: 24) + case .bool: + return false + case .bytes(length: let length): + return Data(repeating: 0x00, count: Int(length)) + case .array(type: let type, length: let length): + let emptyValueOfType = type.emptyValue + return Array.init(repeating: emptyValueOfType, count: Int(length)) + case .dynamicBytes: + return Data() + case .string: + return "" + case .tuple(types: _): + return [Any]() + } + } + + var arraySize: ABI.Element.ArraySize { + switch self { + case .array(type: _, length: let length): + if (length == 0) { + return ArraySize.dynamicSize + } + return ArraySize.staticSize(length) + default: + return ArraySize.notArray + } + } + } + + +} + +extension ABI.Element.ParameterType: Equatable { + public static func ==(lhs: ABI.Element.ParameterType, rhs: ABI.Element.ParameterType) -> Bool { + switch (lhs, rhs) { + case let (.uint(length1), .uint(length2)): + return length1 == length2 + case let (.int(length1), .int(length2)): + return length1 == length2 + case (.address, .address): + return true + case (.bool, .bool): + return true + case let (.bytes(length1), .bytes(length2)): + return length1 == length2 + case (.function, .function): + return true + case let (.array(type1, length1), .array(type2, length2)): + return type1 == type2 && length1 == length2 + case (.dynamicBytes, .dynamicBytes): + return true + case (.string, .string): + return true + default: + return false + } + } +} + +extension ABI.Element.Function { + public var signature: String { + return "\(name ?? "")(\(inputs.map { $0.type.abiRepresentation }.joined(separator: ",")))" + } + + public var methodString: String { + return String(signature.sha3(.keccak256).prefix(8)) + } + + public var methodEncoding: Data { + return signature.data(using: .ascii)!.sha3(.keccak256)[0...3] + } +} + +// MARK: - Event topic +extension ABI.Element.Event { + public var signature: String { + return "\(name)(\(inputs.map { $0.type.abiRepresentation }.joined(separator: ",")))" + } + + public var topic: Data { + return signature.data(using: .ascii)!.sha3(.keccak256) + } +} + + +extension ABI.Element.ParameterType: ABIEncoding { + public var abiRepresentation: String { + switch self { + case .uint(let bits): + return "uint\(bits)" + case .int(let bits): + return "int\(bits)" + case .address: + return "address" + case .bool: + return "bool" + case .bytes(let length): + return "bytes\(length)" + case .dynamicBytes: + return "bytes" + case .function: + return "function" + case .array(type: let type, length: let length): + if (length == 0) { + return "\(type.abiRepresentation)[]" + } + return "\(type.abiRepresentation)[\(length)]" + case .tuple(types: let types): + let typesRepresentation = types.map({return $0.abiRepresentation}) + let typesJoined = typesRepresentation.joined(separator: ",") + return "tuple(\(typesJoined))" + case .string: + return "string" + } + } +} + +extension ABI.Element.ParameterType: ABIValidation { + public var isValid: Bool { + switch self { + case .uint(let bits), .int(let bits): + return bits > 0 && bits <= 256 && bits % 8 == 0 + case .bytes(let length): + return length > 0 && length <= 32 + case .array(type: let type, _): + return type.isValid + case .tuple(types: let types): + for t in types { + if (!t.isValid) { + return false + } + } + return true + default: + return true + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABIParsing.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABIParsing.swift new file mode 100755 index 000000000..bc989ed7a --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABIParsing.swift @@ -0,0 +1,186 @@ +// +// Created by Alex Vlasov on 25/10/2018. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +extension ABI { + + public enum ParsingError: Swift.Error { + case invalidJsonFile + case elementTypeInvalid + case elementNameInvalid + case functionInputInvalid + case functionOutputInvalid + case eventInputInvalid + case parameterTypeInvalid + case parameterTypeNotFound + case abiInvalid + } + + enum TypeParsingExpressions { + static var typeEatingRegex = "^((u?int|bytes)([1-9][0-9]*)|(address|bool|string|tuple|bytes)|(\\[([1-9][0-9]*)\\]))" + static var arrayEatingRegex = "^(\\[([1-9][0-9]*)?\\])?.*$" + } + + + fileprivate enum ElementType: String { + case function + case constructor + case fallback + case event + } + +} + +extension ABI.Record { + public func parse() throws -> ABI.Element { + let typeString = self.type != nil ? self.type! : "function" + guard let type = ABI.ElementType(rawValue: typeString) else { + throw ABI.ParsingError.elementTypeInvalid + } + return try parseToElement(from: self, type: type) + } +} + +fileprivate func parseToElement(from abiRecord: ABI.Record, type: ABI.ElementType) throws -> ABI.Element { + switch type { + case .function: + let function = try parseFunction(abiRecord: abiRecord) + return ABI.Element.function(function) + case .constructor: + let constructor = try parseConstructor(abiRecord: abiRecord) + return ABI.Element.constructor(constructor) + case .fallback: + let fallback = try parseFallback(abiRecord: abiRecord) + return ABI.Element.fallback(fallback) + case .event: + let event = try parseEvent(abiRecord: abiRecord) + return ABI.Element.event(event) + } + +} + +fileprivate func parseFunction(abiRecord:ABI.Record) throws -> ABI.Element.Function { + let inputs = try abiRecord.inputs?.map({ (input:ABI.Input) throws -> ABI.Element.InOut in + let nativeInput = try input.parse() + return nativeInput + }) + let abiInputs = inputs != nil ? inputs! : [ABI.Element.InOut]() + let outputs = try abiRecord.outputs?.map({ (output:ABI.Output) throws -> ABI.Element.InOut in + let nativeOutput = try output.parse() + return nativeOutput + }) + let abiOutputs = outputs != nil ? outputs! : [ABI.Element.InOut]() + let name = abiRecord.name != nil ? abiRecord.name! : "" + let payable = abiRecord.stateMutability != nil ? + (abiRecord.stateMutability == "payable" || abiRecord.payable ?? false) : false + let constant = (abiRecord.constant == true || abiRecord.stateMutability == "view" || abiRecord.stateMutability == "pure") + let functionElement = ABI.Element.Function(name: name, inputs: abiInputs, outputs: abiOutputs, constant: constant, payable: payable) + return functionElement +} + +fileprivate func parseFallback(abiRecord:ABI.Record) throws -> ABI.Element.Fallback { + let payable = (abiRecord.stateMutability == "payable" || abiRecord.payable == true) + var constant = abiRecord.constant == true + if (abiRecord.stateMutability == "view" || abiRecord.stateMutability == "pure") { + constant = true + } + let functionElement = ABI.Element.Fallback(constant: constant, payable: payable) + return functionElement +} + +fileprivate func parseConstructor(abiRecord:ABI.Record) throws -> ABI.Element.Constructor { + let inputs = try abiRecord.inputs?.map({ (input:ABI.Input) throws -> ABI.Element.InOut in + let nativeInput = try input.parse() + return nativeInput + }) + let abiInputs = inputs != nil ? inputs! : [ABI.Element.InOut]() + var payable = false + if (abiRecord.payable != nil) { + payable = abiRecord.payable! + } + if (abiRecord.stateMutability == "payable") { + payable = true + } + let constant = false + let functionElement = ABI.Element.Constructor(inputs: abiInputs, constant: constant, payable: payable) + return functionElement +} + +fileprivate func parseEvent(abiRecord:ABI.Record) throws -> ABI.Element.Event { + let inputs = try abiRecord.inputs?.map({ (input:ABI.Input) throws -> ABI.Element.Event.Input in + let nativeInput = try input.parseForEvent() + return nativeInput + }) + let abiInputs = inputs != nil ? inputs! : [ABI.Element.Event.Input]() + let name = abiRecord.name != nil ? abiRecord.name! : "" + let anonymous = abiRecord.anonymous != nil ? abiRecord.anonymous! : false + let functionElement = ABI.Element.Event(name: name, inputs: abiInputs, anonymous: anonymous) + return functionElement +} + +extension ABI.Input { + func parse() throws -> ABI.Element.InOut { + let name = self.name != nil ? self.name! : "" + let parameterType = try ABITypeParser.parseTypeString(self.type) + if case .tuple(types: _) = parameterType { + let components = try self.components?.compactMap({ (inp: ABI.Input) throws -> ABI.Element.ParameterType in + let input = try inp.parse() + return input.type + }) + let type = ABI.Element.ParameterType.tuple(types: components!) + let nativeInput = ABI.Element.InOut(name: name, type: type) + return nativeInput + } + else { + let nativeInput = ABI.Element.InOut(name: name, type: parameterType) + return nativeInput + } + } + + func parseForEvent() throws -> ABI.Element.Event.Input{ + let name = self.name != nil ? self.name! : "" + let parameterType = try ABITypeParser.parseTypeString(self.type) + let indexed = self.indexed == true + return ABI.Element.Event.Input(name:name, type: parameterType, indexed: indexed) + } +} + +extension ABI.Output { + func parse() throws -> ABI.Element.InOut { + let name = self.name != nil ? self.name! : "" + let parameterType = try ABITypeParser.parseTypeString(self.type) + switch parameterType { + case .tuple(types: _): + let components = try self.components?.compactMap({ (inp: ABI.Output) throws -> ABI.Element.ParameterType in + let input = try inp.parse() + return input.type + }) + let type = ABI.Element.ParameterType.tuple(types: components!) + let nativeInput = ABI.Element.InOut(name: name, type: type) + return nativeInput + case .array(type: let subtype, length: let length): + switch subtype { + case .tuple(types: _): + let components = try self.components?.compactMap({ (inp: ABI.Output) throws -> ABI.Element.ParameterType in + let input = try inp.parse() + return input.type + }) + let nestedSubtype = ABI.Element.ParameterType.tuple(types: components!) + let properType = ABI.Element.ParameterType.array(type: nestedSubtype, length: length) + let nativeInput = ABI.Element.InOut(name: name, type: properType) + return nativeInput + default: + let nativeInput = ABI.Element.InOut(name: name, type: parameterType) + return nativeInput + } + default: + let nativeInput = ABI.Element.InOut(name: name, type: parameterType) + return nativeInput + } + } +} + + diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABITypeParser.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABITypeParser.swift new file mode 100755 index 000000000..274712471 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumABI/ABITypeParser.swift @@ -0,0 +1,110 @@ +// +// Created by Alex Vlasov on 25/10/2018. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +public struct ABITypeParser { + + private enum BaseParameterType: String { + case address + case uint + case int + case bool + case function + case bytes + case string + case tuple + } + + static func baseTypeMatch(from string: String, length: UInt64 = 0) -> ABI.Element.ParameterType? { + switch BaseParameterType(rawValue: string) { + case .address?: + return .address + case .uint?: + return .uint(bits: length == 0 ? 256: length) + case .int?: + return .int(bits: length == 0 ? 256: length) + case .bool?: + return .bool + case .function?: + return .function + case .bytes?: + if length == 0 { + return .dynamicBytes + } + return .bytes(length: length) + case .string?: + return .string + case .tuple?: + return .tuple(types: [ABI.Element.ParameterType]()) + default: + return nil + } + } + + public static func parseTypeString(_ string:String) throws -> ABI.Element.ParameterType { + let (type, tail) = recursiveParseType(string) + guard let t = type, tail == nil else {throw ABI.ParsingError.elementTypeInvalid} + return t + } + + static func recursiveParseType(_ string: String) -> (type: ABI.Element.ParameterType?, tail: String?) { + let matcher = try! NSRegularExpression(pattern: ABI.TypeParsingExpressions.typeEatingRegex, options: NSRegularExpression.Options.dotMatchesLineSeparators) + let match = matcher.matches(in: string, options: NSRegularExpression.MatchingOptions.anchored, range: string.fullNSRange) + guard match.count == 1 else { + return (nil, nil) + } + var tail: String = "" + var type: ABI.Element.ParameterType? + guard match[0].numberOfRanges >= 1 else {return (nil, nil)} + guard let baseTypeRange = Range(match[0].range(at: 1), in: string) else {return (nil, nil)} + let baseTypeString = String(string[baseTypeRange]) + if match[0].numberOfRanges >= 2, let exactTypeRange = Range(match[0].range(at: 2), in: string) { + let typeString = String(string[exactTypeRange]) + if match[0].numberOfRanges >= 3, let lengthRange = Range(match[0].range(at: 3), in: string) { + let lengthString = String(string[lengthRange]) + guard let typeLength = UInt64(lengthString) else {return (nil, nil)} + guard let baseType = baseTypeMatch(from: typeString, length: typeLength) else {return (nil, nil)} + type = baseType + } else { + guard let baseType = baseTypeMatch(from: typeString, length: 0) else {return (nil, nil)} + type = baseType + } + } else { + guard let baseType = baseTypeMatch(from: baseTypeString, length: 0) else {return (nil, nil)} + type = baseType + } + tail = string.replacingCharacters(in: string.range(of: baseTypeString)!, with: "") + if (tail == "") { + return (type, nil) + } + return recursiveParseArray(baseType: type!, string: tail) + } + + static func recursiveParseArray(baseType: ABI.Element.ParameterType, string: String) -> (type: ABI.Element.ParameterType?, tail: String?) { + let matcher = try! NSRegularExpression(pattern: ABI.TypeParsingExpressions.arrayEatingRegex, options: NSRegularExpression.Options.dotMatchesLineSeparators) + let match = matcher.matches(in: string, options: NSRegularExpression.MatchingOptions.anchored, range: string.fullNSRange) + guard match.count == 1 else {return (nil, nil)} + var tail: String = "" + var type: ABI.Element.ParameterType? + guard match[0].numberOfRanges >= 1 else {return (nil, nil)} + guard let baseArrayRange = Range(match[0].range(at: 1), in: string) else {return (nil, nil)} + let baseArrayString = String(string[baseArrayRange]) + if match[0].numberOfRanges >= 2, let exactArrayRange = Range(match[0].range(at: 2), in: string) { + let lengthString = String(string[exactArrayRange]) + guard let arrayLength = UInt64(lengthString) else {return (nil, nil)} + let baseType = ABI.Element.ParameterType.array(type: baseType, length: arrayLength) + type = baseType + } else { + let baseType = ABI.Element.ParameterType.array(type: baseType, length: 0) + type = baseType + } + tail = string.replacingCharacters(in: string.range(of: baseArrayString)!, with: "") + if (tail == "") { + return (type, nil) + } + return recursiveParseArray(baseType: type!, string: tail) + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumAddress/EthereumAddress.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumAddress/EthereumAddress.swift new file mode 100755 index 000000000..da47d982c --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumAddress/EthereumAddress.swift @@ -0,0 +1,136 @@ +// +// EthereumAddress.swift +// EthereumAddress +// +// Created by Alex Vlasov on 25/10/2018. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import CryptoSwift + +public struct EthereumAddress: Equatable { + public enum AddressType { + case normal + case contractDeployment + } + + public var isValid: Bool { + get { + switch self.type { + case .normal: + return (self.addressData.count == 20) + case .contractDeployment: + return true + } + + } + } + var _address: String + public var type: AddressType = .normal + public static func ==(lhs: EthereumAddress, rhs: EthereumAddress) -> Bool { + return lhs.addressData == rhs.addressData && lhs.type == rhs.type + // return lhs.address.lowercased() == rhs.address.lowercased() && lhs.type == rhs.type + } + + public var addressData: Data { + get { + switch self.type { + case .normal: + guard let dataArray = Data.fromHex(_address) else {return Data()} + return dataArray + // guard let d = dataArray.setLengthLeft(20) else { return Data()} + // return d + case .contractDeployment: + return Data() + } + } + } + public var address:String { + switch self.type { + case .normal: + return EthereumAddress.toChecksumAddress(_address)! + case .contractDeployment: + return "0x" + } + } + + 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} + var ret = "0x" + + for (i,char) in address.enumerated() { + let startIdx = hash.index(hash.startIndex, offsetBy: i) + let endIdx = hash.index(hash.startIndex, offsetBy: i+1) + let hashChar = String(hash[startIdx..= 8) { + ret += c.uppercased() + } else { + ret += c + } + } + return ret + } + + 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} + if !addressString.hasHexPrefix() { + return nil + } + if (!ignoreChecksum) { + // check for checksum + if data.toHexString() == addressString.stripHexPrefix() { + self._address = data.toHexString().addHexPrefix() + self.type = .normal + return + } else if data.toHexString().uppercased() == addressString.stripHexPrefix() { + self._address = data.toHexString().addHexPrefix() + self.type = .normal + return + } else { + let checksummedAddress = EthereumAddress.toChecksumAddress(data.toHexString().addHexPrefix()) + guard checksummedAddress == addressString else {return nil} + self._address = data.toHexString().addHexPrefix() + self.type = .normal + return + } + } else { + self._address = data.toHexString().addHexPrefix() + self.type = .normal + return + } + case .contractDeployment: + self._address = "0x" + self.type = .contractDeployment + } + } + + public init?(_ addressData:Data, type: AddressType = .normal) { + guard addressData.count == 20 else {return nil} + self._address = addressData.toHexString().addHexPrefix() + self.type = type + } + + public static func contractDeploymentAddress() -> EthereumAddress { + return EthereumAddress("0x", type: .contractDeployment)! + } + + // public static func fromIBAN(_ iban: String) -> EthereumAddress { + // + // } + +} + +extension EthereumAddress: Hashable { + +} + + + + diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumAddress/Extensions.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumAddress/Extensions.swift new file mode 100755 index 000000000..f82edee10 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/EthereumAddress/Extensions.swift @@ -0,0 +1,60 @@ +// +// Extensions.swift +// EthereumAddress +// +// Created by Alex Vlasov on 25/10/2018. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +extension Array where Element == UInt8 { + init(hex: String) { + self.init() + self.reserveCapacity(hex.unicodeScalars.lazy.underestimatedCount) + var buffer: UInt8? + var skip = hex.hasPrefix("0x") ? 2 : 0 + for char in hex.unicodeScalars.lazy { + guard skip == 0 else { + skip -= 1 + continue + } + guard char.value >= 48 && char.value <= 102 else { + removeAll() + return + } + let v: UInt8 + let c: UInt8 = UInt8(char.value) + switch c { + case let c where c <= 57: + v = c - 48 + case let c where c >= 65 && c <= 70: + v = c - 55 + case let c where c >= 97: + v = c - 87 + default: + removeAll() + return + } + if let b = buffer { + append(b << 4 | v) + buffer = nil + } else { + buffer = v + } + } + if let b = buffer { + append(b) + } + } + + func toHexString() -> String { + return `lazy`.reduce("") { + var s = String($1, radix: 16) + if s.count == 1 { + s = "0" + s + } + return $0 + s + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/HookedFunctions/Web3+BrowserFunctions.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/HookedFunctions/Web3+BrowserFunctions.swift new file mode 100755 index 000000000..ed1576a3b --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/HookedFunctions/Web3+BrowserFunctions.swift @@ -0,0 +1,209 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import secp256k1_swift +//import EthereumAddress + +extension web3.BrowserFunctions { + + public func getAccounts() -> [String]? { + do { + let accounts = try self.web3.eth.getAccounts() + return accounts.compactMap({$0.address}) + } catch { + return [String]() + } + } + + public func getCoinbase() -> String? { + guard let addresses = self.getAccounts() else {return nil} + guard addresses.count > 0 else {return nil} + return addresses[0] + } + + public func personalSign(_ personalMessage: String, account: String, password: String = "web3swift") -> String? { + return self.sign(personalMessage, account: account, password: password) + } + + public func sign(_ personalMessage: String, account: String, password: String = "web3swift") -> String? { + 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 = "web3swift") -> 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} + return signature.toHexString().addHexPrefix() + } + catch{ + print(error) + return nil + } + } + + 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} + return self.personalECRecover(data, signature:sig) + } + + public func personalECRecover(_ personalMessage: Data, signature: Data) -> String? { + 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 = Web3.Utils.hashPersonalMessage(personalMessage) else {return nil} + guard let publicKey = SECP256K1.recoverPublicKey(hash: hash, signature: signatureData) else {return nil} + return Web3.Utils.publicToAddressString(publicKey) + } + + + public func sendTransaction(_ transactionJSON: [String: Any], password: String = "web3swift") -> [String:Any]? { + guard let transaction = EthereumTransaction.fromJSON(transactionJSON) else {return nil} + guard let options = TransactionOptions.fromJSON(transactionJSON) else {return nil} + var transactionOptions = TransactionOptions() + transactionOptions.from = options.from + transactionOptions.to = options.to + transactionOptions.value = options.value != nil ? options.value! : BigUInt(0) + transactionOptions.gasLimit = options.gasLimit != nil ? options.gasLimit! : .automatic + transactionOptions.gasPrice = options.gasPrice != nil ? options.gasPrice! : .automatic + return self.sendTransaction(transaction, transactionOptions: transactionOptions, password: password) + } + + public func sendTransaction(_ transaction: EthereumTransaction, transactionOptions: TransactionOptions, password: String = "web3swift") -> [String:Any]? { + do { + let result = try self.web3.eth.sendTransaction(transaction, transactionOptions: transactionOptions, password: password) + return ["txhash": result.hash] + } catch { + return nil + } + } + + public func estimateGas(_ transactionJSON: [String: Any]) -> BigUInt? { + guard let transaction = EthereumTransaction.fromJSON(transactionJSON) else {return nil} + guard let options = TransactionOptions.fromJSON(transactionJSON) else {return nil} + var transactionOptions = TransactionOptions() + transactionOptions.from = options.from + transactionOptions.to = options.to + transactionOptions.value = options.value != nil ? options.value! : BigUInt(0) + transactionOptions.gasLimit = .automatic + transactionOptions.gasPrice = options.gasPrice != nil ? options.gasPrice! : .automatic + return self.estimateGas(transaction, transactionOptions: transactionOptions) + } + + public func estimateGas(_ transaction: EthereumTransaction, transactionOptions: TransactionOptions) -> BigUInt? { + do { + let result = try self.web3.eth.estimateGas(transaction, transactionOptions: transactionOptions) + return result + } catch { + return nil + } + } + + public func prepareTxForApproval(_ transactionJSON: [String: Any]) -> (transaction: EthereumTransaction?, options: TransactionOptions?) { + guard let transaction = EthereumTransaction.fromJSON(transactionJSON) else {return (nil, nil)} + guard let options = TransactionOptions.fromJSON(transactionJSON) else {return (nil, nil)} + do { + return try self.prepareTxForApproval(transaction, options: options) + } catch { + return (nil, nil) + } + } + + public func prepareTxForApproval(_ trans: EthereumTransaction, options opts: TransactionOptions) throws -> (transaction: EthereumTransaction?, options: TransactionOptions?) { + do { + var transaction = trans + var options = opts + guard let _ = options.from else {return (nil, nil)} + let gasPrice = try self.web3.eth.getGasPrice() + transaction.gasPrice = gasPrice + options.gasPrice = .manual(gasPrice) + guard let gasEstimate = self.estimateGas(transaction, transactionOptions: options) else {return (nil, nil)} + transaction.gasLimit = gasEstimate + options.gasLimit = .limited(gasEstimate) + print(transaction) + return (transaction, options) + } catch { + return (nil, nil) + } + } + + public func signTransaction(_ transactionJSON: [String: Any], password: String = "web3swift") -> String? { + guard let transaction = EthereumTransaction.fromJSON(transactionJSON) else {return nil} + guard let options = TransactionOptions.fromJSON(transactionJSON) else {return nil} + var transactionOptions = TransactionOptions() + transactionOptions.from = options.from + transactionOptions.to = options.to + transactionOptions.value = options.value != nil ? options.value! : BigUInt(0) + transactionOptions.gasLimit = options.gasLimit != nil ? options.gasLimit! : .automatic + transactionOptions.gasPrice = options.gasPrice != nil ? options.gasPrice! : .automatic + if let nonceString = transactionJSON["nonce"] as? String, let nonce = BigUInt(nonceString.stripHexPrefix(), radix: 16) { + transactionOptions.nonce = .manual(nonce) + } else { + transactionOptions.nonce = .pending + } + return self.signTransaction(transaction, transactionOptions: transactionOptions, password: password) + } + + public func signTransaction(_ trans: EthereumTransaction, transactionOptions: TransactionOptions, password: String = "web3swift") -> String? { + do { + var transaction = trans + guard let from = transactionOptions.from else {return nil} + guard let keystoreManager = self.web3.provider.attachedKeystoreManager else {return nil} + guard let gasPricePolicy = transactionOptions.gasPrice else {return nil} + guard let gasLimitPolicy = transactionOptions.gasLimit else {return nil} + guard let noncePolicy = transactionOptions.nonce else {return nil} + switch gasPricePolicy { + case .manual(let gasPrice): + transaction.gasPrice = gasPrice + default: + let gasPrice = try self.web3.eth.getGasPrice() + transaction.gasPrice = gasPrice + } + + switch gasLimitPolicy { + case .manual(let gasLimit): + transaction.gasLimit = gasLimit + default: + let gasLimit = try self.web3.eth.estimateGas(transaction, transactionOptions: transactionOptions) + transaction.gasLimit = gasLimit + } + + switch noncePolicy { + case .manual(let nonce): + transaction.nonce = nonce + default: + let nonce = try self.web3.eth.getTransactionCount(address: from, onBlock: "pending") + transaction.nonce = nonce + } + + if (self.web3.provider.network != nil) { + transaction.chainID = self.web3.provider.network?.chainID + } + + 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(forSignature: false, chainID: nil)?.toHexString().addHexPrefix() + return signedData + } + catch { + return nil + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/HookedFunctions/Web3+Wallet.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/HookedFunctions/Web3+Wallet.swift new file mode 100755 index 000000000..c7b0e8c44 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/HookedFunctions/Web3+Wallet.swift @@ -0,0 +1,73 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +extension web3.Web3Wallet { + + public func getAccounts() throws -> [EthereumAddress] { + guard let keystoreManager = self.web3.provider.attachedKeystoreManager else { + throw Web3Error.walletError + } + guard let ethAddresses = keystoreManager.addresses else { + throw Web3Error.walletError + } + return ethAddresses + } + + public func getCoinbase() throws -> EthereumAddress { + let addresses = try self.getAccounts() + guard addresses.count > 0 else { + throw Web3Error.walletError + } + return addresses[0] + } + + public func signTX(transaction:inout EthereumTransaction, account: EthereumAddress, password: String = "web3swift") throws -> Bool { + do { + guard let keystoreManager = self.web3.provider.attachedKeystoreManager else { + throw Web3Error.walletError + } + try Web3Signer.signTX(transaction: &transaction, keystore: keystoreManager, account: account, password: password) + return true + } catch { + if error is AbstractKeystoreError { + throw Web3Error.keystoreError(err: error as! AbstractKeystoreError) + } + throw Web3Error.generalError(err: error) + } + } + + public func signPersonalMessage(_ personalMessage: String, account: EthereumAddress, password: String = "web3swift") throws -> Data { + guard let data = Data.fromHex(personalMessage) else + { + throw Web3Error.dataError + } + return try self.signPersonalMessage(data, account: account, password: password) + } + + public func signPersonalMessage(_ personalMessage: Data, account: EthereumAddress, password: String = "web3swift") throws -> Data { + do { + guard let keystoreManager = self.web3.provider.attachedKeystoreManager else + { + throw Web3Error.walletError + } + guard let data = try Web3Signer.signPersonalMessage(personalMessage, keystore: keystoreManager, account: account, password: password) else { + throw Web3Error.walletError + } + return data + } + catch{ + if error is AbstractKeystoreError { + throw Web3Error.keystoreError(err: error as! AbstractKeystoreError) + } + throw Web3Error.generalError(err: error) + } + } + +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/AbstractKeystore.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/AbstractKeystore.swift new file mode 100755 index 000000000..ec736d005 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/AbstractKeystore.swift @@ -0,0 +1,24 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +//import EthereumAddress + +public protocol AbstractKeystore { + var addresses: [EthereumAddress]? { get } + var isHDKeystore: Bool { get } + func UNSAFE_getPrivateKeyData(password: String, account: EthereumAddress) throws -> Data +} + +public enum AbstractKeystoreError: Error { + case noEntropyError + case keyDerivationError + case aesError + case invalidAccountError + case invalidPasswordError + case encryptionError(String) +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32HDNode.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32HDNode.swift new file mode 100755 index 000000000..267b7f024 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32HDNode.swift @@ -0,0 +1,302 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import CryptoSwift +//import secp256k1_swift + +extension UInt32 { + public func serialize32() -> Data { + let uint32 = UInt32(self) + var bigEndian = uint32.bigEndian + let count = MemoryLayout.size + let bytePtr = withUnsafePointer(to: &bigEndian) { + $0.withMemoryRebound(to: UInt8.self, capacity: count) { + UnsafeBufferPointer(start: $0, count: count) + } + } + let byteArray = Array(bytePtr) + return Data(byteArray) + } +} + +public class HDNode { + public struct HDversion{ + public var privatePrefix: Data = Data.fromHex("0x0488ADE4")! + public var publicPrefix: Data = Data.fromHex("0x0488B21E")! + public init() { + + } + } + public var path: String? = "m" + public var privateKey: Data? = nil + public var publicKey: Data + public var chaincode: Data + public var depth: UInt8 + 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) + } + } + public var index: UInt32 { + get { + if self.isHardened { + return self.childNumber - (UInt32(1) << 31) + } else { + return self.childNumber + } + } + } + public var hasPrivate:Bool { + get { + return privateKey != nil + } + } + + init() { + publicKey = Data() + chaincode = Data() + depth = UInt8(0) + } + + public convenience init?(_ serializedString: String) { + let data = Data(Base58.bytesFromBase58(serializedString)) + self.init(data) + } + + public init?(_ data: Data) { + guard data.count == 82 else {return nil} + let header = data[0..<4] + var serializePrivate = false + if header == HDNode.HDversion().privatePrefix { + serializePrivate = true + } + depth = data[4..<5].bytes[0] + parentFingerprint = data[5..<9] + let cNum = data[9..<13].bytes + childNumber = UnsafePointer(cNum).withMemoryRebound(to: UInt32.self, capacity: 1) { + $0.pointee + } + chaincode = data[13..<45] + if serializePrivate { + privateKey = data[46..<78] + guard let pubKey = Web3.Utils.privateToPublic(privateKey!, compressed: true) else {return nil} + if pubKey[0] != 0x02 && pubKey[0] != 0x03 {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} + } + + public init?(seed: Data) { + guard seed.count >= 16 else {return nil} + let hmacKey = "Bitcoin seed".data(using: .ascii)! + let hmac:Authenticator = HMAC(key: hmacKey.bytes, variant: HMAC.Variant.sha512) + guard let entropy = try? hmac.authenticate(seed.bytes) else {return nil} + guard 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} + publicKey = pubKeyCandidate + privateKey = privKeyCandidate + depth = 0x00 + childNumber = UInt32(0) + } + + private static var curveOrder = BigUInt("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", radix: 16)! + 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" + public static var defaultPathMetamaskPrefix: String = "m/44'/60'/0'/0" + public static var hardenedIndexPrefix: UInt32 = (UInt32(1) << 31) +} + +extension 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:Array + 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: .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: .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:Array // 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: .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 = pubKeyCandidate + 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 + } + } + + public func derive (path: String, derivePrivateKey: Bool = true) -> HDNode? { + let components = path.components(separatedBy: "/") + var currentNode:HDNode = self + var firstComponent = 0 + if path.hasPrefix("m") { + firstComponent = 1 + } + for component in components[firstComponent ..< components.count] { + var hardened = false + 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} + currentNode = newNode + } + return currentNode + } + + 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 + } + + public func serialize(serializePublic: Bool = true, version: HDversion = HDversion()) -> Data? { + var data = Data() + if (!serializePublic && !self.hasPrivate) {return nil} + if serializePublic { + data.append(version.publicPrefix) + } else { + 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: [0x00]) + data.append(self.privateKey!) + } + let hashedData = data.sha256().sha256() + let checksum = hashedData[0..<4] + data.append(checksum) + return data + } + +} + diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32Keystore.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32Keystore.swift new file mode 100755 index 000000000..3e3a60da4 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32Keystore.swift @@ -0,0 +1,401 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import CryptoSwift +import Foundation + +//import EthereumAddress + +public class BIP32Keystore: AbstractKeystore { + + + // Protocol + public var isHDKeystore: Bool = true + + public var keystoreParams: KeystoreParamsBIP32? + public var paths: [String: EthereumAddress] = [String: EthereumAddress]() + + public var rootPrefix: String + + public var addresses: [EthereumAddress]? { + get { + if self.paths.count == 0 { + return nil + } + var allAccounts = [EthereumAddress]() + for (_, address) in paths { + allAccounts.append(address) + } + return allAccounts + } + } + + public func UNSAFE_getPrivateKeyData(password: String, account: EthereumAddress) throws -> Data { + if let key = self.paths.keyForValue(value: account) { + guard let decryptedRootNode = try? self.getPrefixNodeData(password) else { + throw AbstractKeystoreError.encryptionError("Failed to decrypt a keystore") + } + guard let rootNode = HDNode(decryptedRootNode) else { + throw AbstractKeystoreError.encryptionError("Failed to deserialize a root node") + } + guard rootNode.depth == (self.rootPrefix.components(separatedBy: "/").count - 1) else { + throw AbstractKeystoreError.encryptionError("Derivation depth mismatch") + } +// guard rootNode.depth == HDNode.defaultPathPrefix.components(separatedBy: "/").count - 1 else {throw AbstractKeystoreError.encryptionError("Derivation depth mismatch")} + guard let index = UInt32(key.components(separatedBy: "/").last!) else { + throw AbstractKeystoreError.encryptionError("Derivation depth mismatch") + } + guard let keyNode = rootNode.derive(index: index, derivePrivateKey: true) else { + throw AbstractKeystoreError.encryptionError("Derivation failed") + } + guard let privateKey = keyNode.privateKey else { + throw AbstractKeystoreError.invalidAccountError + } + return privateKey + } + throw AbstractKeystoreError.invalidAccountError + } + + // -------------- + + + public convenience init?(_ jsonString: String) { + let lowercaseJSON = jsonString.lowercased() + guard let jsonData = lowercaseJSON.data(using: .utf8) else { + return nil + } + self.init(jsonData) + } + + public init?(_ jsonData: Data) { + guard var keystorePars = try? JSONDecoder().decode(KeystoreParamsBIP32.self, from: jsonData) else { + return nil + } + if (keystorePars.version != 3) { + return nil + } + if (keystorePars.crypto.version != nil && keystorePars.crypto.version != "1") { + return nil + } + if (!keystorePars.isHDWallet) { + return nil + } + for (p, ad) in keystorePars.pathToAddress { + paths[p] = EthereumAddress(ad) + } + if keystorePars.rootPath == nil { + keystorePars.rootPath = HDNode.defaultPathPrefix + } + keystoreParams = keystorePars + rootPrefix = keystoreParams!.rootPath! + } + + public convenience init?(mnemonics: String, password: String = "web3swift", mnemonicsPassword: String = "", language: BIP39Language = BIP39Language.english, prefixPath: String = HDNode.defaultPathMetamaskPrefix, aesMode: String = "aes-128-cbc") throws { + guard var seed = BIP39.seedFromMmemonics(mnemonics, password: mnemonicsPassword, language: language) else { + throw AbstractKeystoreError.noEntropyError + } + defer{ + Data.zero(&seed) + } + try self.init(seed: seed, password: password, prefixPath: prefixPath, aesMode: aesMode) + } + + public init?(seed: Data, password: String = "web3swift", prefixPath: String = HDNode.defaultPathMetamaskPrefix, aesMode: String = "aes-128-cbc") throws { + 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 { + throw AbstractKeystoreError.keyDerivationError + } + try encryptDataToStorage(password, data: serializedRootNode, aesMode: aesMode) + } + + public func createNewChildAccount(password: String = "web3swift") throws { + guard let decryptedRootNode = try? self.getPrefixNodeData(password) else { + throw AbstractKeystoreError.encryptionError("Failed to decrypt a keystore") + } + guard let rootNode = HDNode(decryptedRootNode) else { + throw AbstractKeystoreError.encryptionError("Failed to deserialize a root node") + } + let prefixPath = self.rootPrefix + guard rootNode.depth == prefixPath.components(separatedBy: "/").count - 1 else { + throw AbstractKeystoreError.encryptionError("Derivation depth mismatch") + } + try createNewAccount(parentNode: rootNode, password: password) + guard let serializedRootNode = rootNode.serialize(serializePublic: false) else { + throw AbstractKeystoreError.keyDerivationError + } + try encryptDataToStorage(password, data: serializedRootNode, aesMode: self.keystoreParams!.crypto.cipher) + } + + func createNewAccount(parentNode: HDNode, password: String = "web3swift") throws { + var newIndex = UInt32(0) + for (p, _) in paths { + guard let idx = UInt32(p.components(separatedBy: "/").last!) else { + continue + } + if idx >= newIndex { + newIndex = idx + 1 + } + } + guard let newNode = parentNode.derive(index: newIndex, derivePrivateKey: true, hardened: false) else { + throw AbstractKeystoreError.keyDerivationError + } + guard let newAddress = Web3.Utils.publicToAddress(newNode.publicKey) else { + throw AbstractKeystoreError.keyDerivationError + } + let prefixPath = self.rootPrefix + var newPath: String + if newNode.isHardened { + newPath = prefixPath + "/" + String(newNode.index % HDNode.hardenedIndexPrefix) + "'" + } else { + newPath = prefixPath + "/" + String(newNode.index) + } + paths[newPath] = newAddress + } + + public func createNewCustomChildAccount(password: String = "web3swift", path: String) throws {guard let decryptedRootNode = try? self.getPrefixNodeData(password) else { + throw AbstractKeystoreError.encryptionError("Failed to decrypt a keystore") + } + guard let rootNode = HDNode(decryptedRootNode) else { + throw AbstractKeystoreError.encryptionError("Failed to deserialize a root node") + } + let prefixPath = self.rootPrefix + var pathAppendix: String? = nil + if path.hasPrefix(prefixPath) { + let upperIndex = (path.range(of: prefixPath)?.upperBound)! + if upperIndex < path.endIndex + { + pathAppendix = String(path[path.index(after: upperIndex)]) + } else + { + throw AbstractKeystoreError.encryptionError("out of bounds") + } + + guard pathAppendix != nil else { + throw AbstractKeystoreError.encryptionError("Derivation depth mismatch") + } + if pathAppendix!.hasPrefix("/") { + pathAppendix = pathAppendix?.trimmingCharacters(in: CharacterSet.init(charactersIn: "/")) + } + } else { + if path.hasPrefix("/") { + pathAppendix = path.trimmingCharacters(in: CharacterSet.init(charactersIn: "/")) + } + } + guard pathAppendix != nil else { + throw AbstractKeystoreError.encryptionError("Derivation depth mismatch") + } + guard rootNode.depth == prefixPath.components(separatedBy: "/").count - 1 else { + throw AbstractKeystoreError.encryptionError("Derivation depth mismatch") + } + guard let newNode = rootNode.derive(path: pathAppendix!, derivePrivateKey: true) else { + throw AbstractKeystoreError.keyDerivationError + } + guard let newAddress = Web3.Utils.publicToAddress(newNode.publicKey) else { + throw AbstractKeystoreError.keyDerivationError + } + var newPath: String + if newNode.isHardened { + newPath = prefixPath + "/" + pathAppendix!.trimmingCharacters(in: CharacterSet.init(charactersIn: "'")) + "'" + } else { + newPath = prefixPath + "/" + pathAppendix! + } + paths[newPath] = newAddress + guard let serializedRootNode = rootNode.serialize(serializePublic: false) else { + throw AbstractKeystoreError.keyDerivationError + } + try encryptDataToStorage(password, data: serializedRootNode, aesMode: self.keystoreParams!.crypto.cipher) + } + + fileprivate func encryptDataToStorage(_ password: String, data: Data?, dkLen: Int = 32, N: Int = 4096, R: Int = 6, P: Int = 1, aesMode: String = "aes-128-cbc") throws { + if (data == nil) { + throw AbstractKeystoreError.encryptionError("Encryption without key data") + } + if (data!.count != 82) { + throw AbstractKeystoreError.encryptionError("Invalid expected data length") + } + let saltLen = 32; + guard let saltData = Data.randomBytes(length: saltLen) else { + throw AbstractKeystoreError.noEntropyError + } + guard let derivedKey = scrypt(password: password, salt: saltData, length: dkLen, N: N, R: R, P: P) else { + throw AbstractKeystoreError.keyDerivationError + } + let last16bytes = derivedKey[(derivedKey.count - 16)...(derivedKey.count - 1)] + let encryptionKey = derivedKey[0...15] + guard let IV = Data.randomBytes(length: 16) else { + throw AbstractKeystoreError.noEntropyError + } + var aesCipher: AES? + switch aesMode { + case "aes-128-cbc": + aesCipher = try? AES(key: encryptionKey.bytes, blockMode: CBC(iv: IV.bytes), padding: .pkcs7) + case "aes-128-ctr": + aesCipher = try? AES(key: encryptionKey.bytes, blockMode: CTR(iv: IV.bytes), padding: .pkcs7) + default: + aesCipher = nil + } + if aesCipher == nil { + throw AbstractKeystoreError.aesError + } + guard let encryptedKey = try aesCipher?.encrypt(data!.bytes) else { + throw AbstractKeystoreError.aesError + } +// let encryptedKeyData = Data(bytes:encryptedKey) Data(encryptedKey) + let encryptedKeyData = Data(encryptedKey) + var dataForMAC = Data() + dataForMAC.append(last16bytes) + dataForMAC.append(encryptedKeyData) + let mac = dataForMAC.sha3(.keccak256) + let kdfparams = KdfParamsV3(salt: saltData.toHexString(), dklen: dkLen, n: N, p: P, r: R, c: nil, prf: nil) + let cipherparams = CipherParamsV3(iv: IV.toHexString()) + let crypto = CryptoParamsV3(ciphertext: encryptedKeyData.toHexString(), cipher: aesMode, cipherparams: cipherparams, kdf: "scrypt", kdfparams: kdfparams, mac: mac.toHexString(), version: nil) + var pathToAddress = [String: String]() + for (path, address) in paths { + pathToAddress[path] = address.address + } + var keystorePars = KeystoreParamsBIP32(crypto: crypto, id: UUID().uuidString.lowercased(), version: 3) + keystorePars.pathToAddress = pathToAddress + keystorePars.rootPath = self.rootPrefix + keystoreParams = keystorePars + } + + public func regenerate(oldPassword: String, newPassword: String, dkLen: Int = 32, N: Int = 4096, R: Int = 6, P: Int = 1) throws { + var keyData = try self.getPrefixNodeData(oldPassword) + if keyData == nil { + throw AbstractKeystoreError.encryptionError("Failed to decrypt a keystore") + } + defer { + Data.zero(&keyData!) + } + try self.encryptDataToStorage(newPassword, data: keyData!, aesMode: self.keystoreParams!.crypto.cipher) + } + + fileprivate func getPrefixNodeData(_ password: String) throws -> Data? { + guard let keystorePars = keystoreParams else { + return nil + } + guard let saltData = Data.fromHex(keystorePars.crypto.kdfparams.salt) else { + return nil + } + let derivedLen = keystorePars.crypto.kdfparams.dklen + var passwordDerivedKey: Data? + switch keystorePars.crypto.kdf { + case "scrypt": + guard let N = keystorePars.crypto.kdfparams.n else { + return nil + } + guard let P = keystorePars.crypto.kdfparams.p else { + return nil + } + guard let R = keystorePars.crypto.kdfparams.r else { + return nil + } + passwordDerivedKey = scrypt(password: password, salt: saltData, length: derivedLen, N: N, R: R, P: P) + case "pbkdf2": + guard let algo = keystorePars.crypto.kdfparams.prf else { + return nil + } + var hashVariant: HMAC.Variant?; + switch algo { + case "hmac-sha256": + hashVariant = HMAC.Variant.sha256 + case "hmac-sha384": + hashVariant = HMAC.Variant.sha384 + case "hmac-sha512": + hashVariant = HMAC.Variant.sha512 + default: + hashVariant = nil + } + guard (hashVariant != nil) else { + return nil + } + guard let c = keystorePars.crypto.kdfparams.c else { + return nil + } + guard let passData = password.data(using: .utf8) else { + return nil + } + guard let derivedArray = try? PKCS5.PBKDF2(password: passData.bytes, salt: saltData.bytes, iterations: c, keyLength: derivedLen, variant: hashVariant!).calculate() else { + return nil + } +// passwordDerivedKey = Data(bytes:derivedArray) + passwordDerivedKey = Data(derivedArray) + default: + return nil + } + guard let derivedKey = passwordDerivedKey else { + return nil + } + var dataForMAC = Data() + let derivedKeyLast16bytes = derivedKey[(derivedKey.count - 16)...(derivedKey.count - 1)] + dataForMAC.append(derivedKeyLast16bytes) + guard let cipherText = Data.fromHex(keystorePars.crypto.ciphertext) else { + return nil + } + guard (cipherText.count.isMultiple(of: 32)) else { + return nil + } + dataForMAC.append(cipherText) + let mac = dataForMAC.sha3(.keccak256) + guard let calculatedMac = Data.fromHex(keystorePars.crypto.mac), mac.constantTimeComparisonTo(calculatedMac) else { + return nil + } + let cipher = keystorePars.crypto.cipher + let decryptionKey = derivedKey[0...15] + guard let IV = Data.fromHex(keystorePars.crypto.cipherparams.iv) else { + return nil + } + var decryptedPK: Array? + switch cipher { + case "aes-128-ctr": + guard let aesCipher = try? AES(key: decryptionKey.bytes, blockMode: CTR(iv: IV.bytes), padding: .pkcs7) else { + return nil + } + decryptedPK = try aesCipher.decrypt(cipherText.bytes) + case "aes-128-cbc": + guard let aesCipher = try? AES(key: decryptionKey.bytes, blockMode: CBC(iv: IV.bytes), padding: .pkcs7) else { + return nil + } + decryptedPK = try? aesCipher.decrypt(cipherText.bytes) + default: + return nil + } + guard decryptedPK != nil else { + return nil + } + guard decryptedPK?.count == 82 else { + return nil + } +// return Data(bytes:decryptedPK!) + return Data(decryptedPK!) + } + + public func serialize() throws -> Data? { + guard let params = self.keystoreParams else { + return nil + } + let data = try JSONEncoder().encode(params) + return data + } + + public func serializeRootNodeToString(password: String = "web3swift") throws -> String { + guard let decryptedRootNode = try? self.getPrefixNodeData(password) else { + throw AbstractKeystoreError.encryptionError("Failed to decrypt a keystore") + } + guard let rootNode = HDNode(decryptedRootNode) else { + throw AbstractKeystoreError.encryptionError("Failed to deserialize a root node") + } + guard let string = rootNode.serializeToString(serializePublic: false) else { + throw AbstractKeystoreError.encryptionError("Failed to deserialize a root node") + } + return string + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP39+WordLists.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP39+WordLists.swift new file mode 100755 index 000000000..79b68efcb --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP39+WordLists.swift @@ -0,0 +1,35 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + + +extension BIP39Language { + var englishWords: [String] { + return "abandon ability able about above absent absorb abstract absurd abuse access accident account accuse achieve acid acoustic acquire across act action actor actress actual adapt add addict address adjust admit adult advance advice aerobic affair afford afraid again age agent agree ahead aim air airport aisle alarm album alcohol alert alien all alley allow almost alone alpha already also alter always amateur amazing among amount amused analyst anchor ancient anger angle angry animal ankle announce annual another answer antenna antique anxiety any apart apology appear apple approve april arch arctic area arena argue arm armed armor army around arrange arrest arrive arrow art artefact artist artwork ask aspect assault asset assist assume asthma athlete atom attack attend attitude attract auction audit august aunt author auto autumn average avocado avoid awake aware away awesome awful awkward axis baby bachelor bacon badge bag balance balcony ball bamboo banana banner bar barely bargain barrel base basic basket battle beach bean beauty because become beef before begin behave behind believe below belt bench benefit best betray better between beyond bicycle bid bike bind biology bird birth bitter black blade blame blanket blast bleak bless blind blood blossom blouse blue blur blush board boat body boil bomb bone bonus book boost border boring borrow boss bottom bounce box boy bracket brain brand brass brave bread breeze brick bridge brief bright bring brisk broccoli broken bronze broom brother brown brush bubble buddy budget buffalo build bulb bulk bullet bundle bunker burden burger burst bus business busy butter buyer buzz cabbage cabin cable cactus cage cake call calm camera camp can canal cancel candy cannon canoe canvas canyon capable capital captain car carbon card cargo carpet carry cart case cash casino castle casual cat catalog catch category cattle caught cause caution cave ceiling celery cement census century cereal certain chair chalk champion change chaos chapter charge chase chat cheap check cheese chef cherry chest chicken chief child chimney choice choose chronic chuckle chunk churn cigar cinnamon circle citizen city civil claim clap clarify claw clay clean clerk clever click client cliff climb clinic clip clock clog close cloth cloud clown club clump cluster clutch coach coast coconut code coffee coil coin collect color column combine come comfort comic common company concert conduct confirm congress connect consider control convince cook cool copper copy coral core corn correct cost cotton couch country couple course cousin cover coyote crack cradle craft cram crane crash crater crawl crazy cream credit creek crew cricket crime crisp critic crop cross crouch crowd crucial cruel cruise crumble crunch crush cry crystal cube culture cup cupboard curious current curtain curve cushion custom cute cycle dad damage damp dance danger daring dash daughter dawn day deal debate debris decade december decide decline decorate decrease deer defense define defy degree delay deliver demand demise denial dentist deny depart depend deposit depth deputy derive describe desert design desk despair destroy detail detect develop device devote diagram dial diamond diary dice diesel diet differ digital dignity dilemma dinner dinosaur direct dirt disagree discover disease dish dismiss disorder display distance divert divide divorce dizzy doctor document dog doll dolphin domain donate donkey donor door dose double dove draft dragon drama drastic draw dream dress drift drill drink drip drive drop drum dry duck dumb dune during dust dutch duty dwarf dynamic eager eagle early earn earth easily east easy echo ecology economy edge edit educate effort egg eight either elbow elder electric elegant element elephant elevator elite else embark embody embrace emerge emotion employ empower empty enable enact end endless endorse enemy energy enforce engage engine enhance enjoy enlist enough enrich enroll ensure enter entire entry envelope episode equal equip era erase erode erosion error erupt escape essay essence estate eternal ethics evidence evil evoke evolve exact example excess exchange excite exclude excuse execute exercise exhaust exhibit exile exist exit exotic expand expect expire explain expose express extend extra eye eyebrow fabric face faculty fade faint faith fall false fame family famous fan fancy fantasy farm fashion fat fatal father fatigue fault favorite feature february federal fee feed feel female fence festival fetch fever few fiber fiction field figure file film filter final find fine finger finish fire firm first fiscal fish fit fitness fix flag flame flash flat flavor flee flight flip float flock floor flower fluid flush fly foam focus fog foil fold follow food foot force forest forget fork fortune forum forward fossil foster found fox fragile frame frequent fresh friend fringe frog front frost frown frozen fruit fuel fun funny furnace fury future gadget gain galaxy gallery game gap garage garbage garden garlic garment gas gasp gate gather gauge gaze general genius genre gentle genuine gesture ghost giant gift giggle ginger giraffe girl give glad glance glare glass glide glimpse globe gloom glory glove glow glue goat goddess gold good goose gorilla gospel gossip govern gown grab grace grain grant grape grass gravity great green grid grief grit grocery group grow grunt guard guess guide guilt guitar gun gym habit hair half hammer hamster hand happy harbor hard harsh harvest hat have hawk hazard head health heart heavy hedgehog height hello helmet help hen hero hidden high hill hint hip hire history hobby hockey hold hole holiday hollow home honey hood hope horn horror horse hospital host hotel hour hover hub huge human humble humor hundred hungry hunt hurdle hurry hurt husband hybrid ice icon idea identify idle ignore ill illegal illness image imitate immense immune impact impose improve impulse inch include income increase index indicate indoor industry infant inflict inform inhale inherit initial inject injury inmate inner innocent input inquiry insane insect inside inspire install intact interest into invest invite involve iron island isolate issue item ivory jacket jaguar jar jazz jealous jeans jelly jewel job join joke journey joy judge juice jump jungle junior junk just kangaroo keen keep ketchup key kick kid kidney kind kingdom kiss kit kitchen kite kitten kiwi knee knife knock know lab label labor ladder lady lake lamp language laptop large later latin laugh laundry lava law lawn lawsuit layer lazy leader leaf learn leave lecture left leg legal legend leisure lemon lend length lens leopard lesson letter level liar liberty library license life lift light like limb limit link lion liquid list little live lizard load loan lobster local lock logic lonely long loop lottery loud lounge love loyal lucky luggage lumber lunar lunch luxury lyrics machine mad magic magnet maid mail main major make mammal man manage mandate mango mansion manual maple marble march margin marine market marriage mask mass master match material math matrix matter maximum maze meadow mean measure meat mechanic medal media melody melt member memory mention menu mercy merge merit merry mesh message metal method middle midnight milk million mimic mind minimum minor minute miracle mirror misery miss mistake mix mixed mixture mobile model modify mom moment monitor monkey monster month moon moral more morning mosquito mother motion motor mountain mouse move movie much muffin mule multiply muscle museum mushroom music must mutual myself mystery myth naive name napkin narrow nasty nation nature near neck need negative neglect neither nephew nerve nest net network neutral never news next nice night noble noise nominee noodle normal north nose notable note nothing notice novel now nuclear number nurse nut oak obey object oblige obscure observe obtain obvious occur ocean october odor off offer office often oil okay old olive olympic omit once one onion online only open opera opinion oppose option orange orbit orchard order ordinary organ orient original orphan ostrich other outdoor outer output outside oval oven over own owner oxygen oyster ozone pact paddle page pair palace palm panda panel panic panther paper parade parent park parrot party pass patch path patient patrol pattern pause pave payment peace peanut pear peasant pelican pen penalty pencil people pepper perfect permit person pet phone photo phrase physical piano picnic picture piece pig pigeon pill pilot pink pioneer pipe pistol pitch pizza place planet plastic plate play please pledge pluck plug plunge poem poet point polar pole police pond pony pool popular portion position possible post potato pottery poverty powder power practice praise predict prefer prepare present pretty prevent price pride primary print priority prison private prize problem process produce profit program project promote proof property prosper protect proud provide public pudding pull pulp pulse pumpkin punch pupil puppy purchase purity purpose purse push put puzzle pyramid quality quantum quarter question quick quit quiz quote rabbit raccoon race rack radar radio rail rain raise rally ramp ranch random range rapid rare rate rather raven raw razor ready real reason rebel rebuild recall receive recipe record recycle reduce reflect reform refuse region regret regular reject relax release relief rely remain remember remind remove render renew rent reopen repair repeat replace report require rescue resemble resist resource response result retire retreat return reunion reveal review reward rhythm rib ribbon rice rich ride ridge rifle right rigid ring riot ripple risk ritual rival river road roast robot robust rocket romance roof rookie room rose rotate rough round route royal rubber rude rug rule run runway rural sad saddle sadness safe sail salad salmon salon salt salute same sample sand satisfy satoshi sauce sausage save say scale scan scare scatter scene scheme school science scissors scorpion scout scrap screen script scrub sea search season seat second secret section security seed seek segment select sell seminar senior sense sentence series service session settle setup seven shadow shaft shallow share shed shell sheriff shield shift shine ship shiver shock shoe shoot shop short shoulder shove shrimp shrug shuffle shy sibling sick side siege sight sign silent silk silly silver similar simple since sing siren sister situate six size skate sketch ski skill skin skirt skull slab slam sleep slender slice slide slight slim slogan slot slow slush small smart smile smoke smooth snack snake snap sniff snow soap soccer social sock soda soft solar soldier solid solution solve someone song soon sorry sort soul sound soup source south space spare spatial spawn speak special speed spell spend sphere spice spider spike spin spirit split spoil sponsor spoon sport spot spray spread spring spy square squeeze squirrel stable stadium staff stage stairs stamp stand start state stay steak steel stem step stereo stick still sting stock stomach stone stool story stove strategy street strike strong struggle student stuff stumble style subject submit subway success such sudden suffer sugar suggest suit summer sun sunny sunset super supply supreme sure surface surge surprise surround survey suspect sustain swallow swamp swap swarm swear sweet swift swim swing switch sword symbol symptom syrup system table tackle tag tail talent talk tank tape target task taste tattoo taxi teach team tell ten tenant tennis tent term test text thank that theme then theory there they thing this thought three thrive throw thumb thunder ticket tide tiger tilt timber time tiny tip tired tissue title toast tobacco today toddler toe together toilet token tomato tomorrow tone tongue tonight tool tooth top topic topple torch tornado tortoise toss total tourist toward tower town toy track trade traffic tragic train transfer trap trash travel tray treat tree trend trial tribe trick trigger trim trip trophy trouble truck true truly trumpet trust truth try tube tuition tumble tuna tunnel turkey turn turtle twelve twenty twice twin twist two type typical ugly umbrella unable unaware uncle uncover under undo unfair unfold unhappy uniform unique unit universe unknown unlock until unusual unveil update upgrade uphold upon upper upset urban urge usage use used useful useless usual utility vacant vacuum vague valid valley valve van vanish vapor various vast vault vehicle velvet vendor venture venue verb verify version very vessel veteran viable vibrant vicious victory video view village vintage violin virtual virus visa visit visual vital vivid vocal voice void volcano volume vote voyage wage wagon wait walk wall walnut want warfare warm warrior wash wasp waste water wave way wealth weapon wear weasel weather web wedding weekend weird welcome west wet whale what wheat wheel when where whip whisper wide width wife wild will win window wine wing wink winner winter wire wisdom wise wish witness wolf woman wonder wood wool word work world worry worth wrap wreck wrestle wrist write wrong yard year yellow you young youth zebra zero zone zoo".components(separatedBy: " ") + } + var simplifiedchineseWords: [String] { + return "的 一 是 在 不 了 有 和 人 这 中 大 为 上 个 国 我 以 要 他 时 来 用 们 生 到 作 地 于 出 就 分 对 成 会 可 主 发 年 动 同 工 也 能 下 过 子 说 产 种 面 而 方 后 多 定 行 学 法 所 民 得 经 十 三 之 进 着 等 部 度 家 电 力 里 如 水 化 高 自 二 理 起 小 物 现 实 加 量 都 两 体 制 机 当 使 点 从 业 本 去 把 性 好 应 开 它 合 还 因 由 其 些 然 前 外 天 政 四 日 那 社 义 事 平 形 相 全 表 间 样 与 关 各 重 新 线 内 数 正 心 反 你 明 看 原 又 么 利 比 或 但 质 气 第 向 道 命 此 变 条 只 没 结 解 问 意 建 月 公 无 系 军 很 情 者 最 立 代 想 已 通 并 提 直 题 党 程 展 五 果 料 象 员 革 位 入 常 文 总 次 品 式 活 设 及 管 特 件 长 求 老 头 基 资 边 流 路 级 少 图 山 统 接 知 较 将 组 见 计 别 她 手 角 期 根 论 运 农 指 几 九 区 强 放 决 西 被 干 做 必 战 先 回 则 任 取 据 处 队 南 给 色 光 门 即 保 治 北 造 百 规 热 领 七 海 口 东 导 器 压 志 世 金 增 争 济 阶 油 思 术 极 交 受 联 什 认 六 共 权 收 证 改 清 美 再 采 转 更 单 风 切 打 白 教 速 花 带 安 场 身 车 例 真 务 具 万 每 目 至 达 走 积 示 议 声 报 斗 完 类 八 离 华 名 确 才 科 张 信 马 节 话 米 整 空 元 况 今 集 温 传 土 许 步 群 广 石 记 需 段 研 界 拉 林 律 叫 且 究 观 越 织 装 影 算 低 持 音 众 书 布 复 容 儿 须 际 商 非 验 连 断 深 难 近 矿 千 周 委 素 技 备 半 办 青 省 列 习 响 约 支 般 史 感 劳 便 团 往 酸 历 市 克 何 除 消 构 府 称 太 准 精 值 号 率 族 维 划 选 标 写 存 候 毛 亲 快 效 斯 院 查 江 型 眼 王 按 格 养 易 置 派 层 片 始 却 专 状 育 厂 京 识 适 属 圆 包 火 住 调 满 县 局 照 参 红 细 引 听 该 铁 价 严 首 底 液 官 德 随 病 苏 失 尔 死 讲 配 女 黄 推 显 谈 罪 神 艺 呢 席 含 企 望 密 批 营 项 防 举 球 英 氧 势 告 李 台 落 木 帮 轮 破 亚 师 围 注 远 字 材 排 供 河 态 封 另 施 减 树 溶 怎 止 案 言 士 均 武 固 叶 鱼 波 视 仅 费 紧 爱 左 章 早 朝 害 续 轻 服 试 食 充 兵 源 判 护 司 足 某 练 差 致 板 田 降 黑 犯 负 击 范 继 兴 似 余 坚 曲 输 修 故 城 夫 够 送 笔 船 占 右 财 吃 富 春 职 觉 汉 画 功 巴 跟 虽 杂 飞 检 吸 助 升 阳 互 初 创 抗 考 投 坏 策 古 径 换 未 跑 留 钢 曾 端 责 站 简 述 钱 副 尽 帝 射 草 冲 承 独 令 限 阿 宣 环 双 请 超 微 让 控 州 良 轴 找 否 纪 益 依 优 顶 础 载 倒 房 突 坐 粉 敌 略 客 袁 冷 胜 绝 析 块 剂 测 丝 协 诉 念 陈 仍 罗 盐 友 洋 错 苦 夜 刑 移 频 逐 靠 混 母 短 皮 终 聚 汽 村 云 哪 既 距 卫 停 烈 央 察 烧 迅 境 若 印 洲 刻 括 激 孔 搞 甚 室 待 核 校 散 侵 吧 甲 游 久 菜 味 旧 模 湖 货 损 预 阻 毫 普 稳 乙 妈 植 息 扩 银 语 挥 酒 守 拿 序 纸 医 缺 雨 吗 针 刘 啊 急 唱 误 训 愿 审 附 获 茶 鲜 粮 斤 孩 脱 硫 肥 善 龙 演 父 渐 血 欢 械 掌 歌 沙 刚 攻 谓 盾 讨 晚 粒 乱 燃 矛 乎 杀 药 宁 鲁 贵 钟 煤 读 班 伯 香 介 迫 句 丰 培 握 兰 担 弦 蛋 沉 假 穿 执 答 乐 谁 顺 烟 缩 征 脸 喜 松 脚 困 异 免 背 星 福 买 染 井 概 慢 怕 磁 倍 祖 皇 促 静 补 评 翻 肉 践 尼 衣 宽 扬 棉 希 伤 操 垂 秋 宜 氢 套 督 振 架 亮 末 宪 庆 编 牛 触 映 雷 销 诗 座 居 抓 裂 胞 呼 娘 景 威 绿 晶 厚 盟 衡 鸡 孙 延 危 胶 屋 乡 临 陆 顾 掉 呀 灯 岁 措 束 耐 剧 玉 赵 跳 哥 季 课 凯 胡 额 款 绍 卷 齐 伟 蒸 殖 永 宗 苗 川 炉 岩 弱 零 杨 奏 沿 露 杆 探 滑 镇 饭 浓 航 怀 赶 库 夺 伊 灵 税 途 灭 赛 归 召 鼓 播 盘 裁 险 康 唯 录 菌 纯 借 糖 盖 横 符 私 努 堂 域 枪 润 幅 哈 竟 熟 虫 泽 脑 壤 碳 欧 遍 侧 寨 敢 彻 虑 斜 薄 庭 纳 弹 饲 伸 折 麦 湿 暗 荷 瓦 塞 床 筑 恶 户 访 塔 奇 透 梁 刀 旋 迹 卡 氯 遇 份 毒 泥 退 洗 摆 灰 彩 卖 耗 夏 择 忙 铜 献 硬 予 繁 圈 雪 函 亦 抽 篇 阵 阴 丁 尺 追 堆 雄 迎 泛 爸 楼 避 谋 吨 野 猪 旗 累 偏 典 馆 索 秦 脂 潮 爷 豆 忽 托 惊 塑 遗 愈 朱 替 纤 粗 倾 尚 痛 楚 谢 奋 购 磨 君 池 旁 碎 骨 监 捕 弟 暴 割 贯 殊 释 词 亡 壁 顿 宝 午 尘 闻 揭 炮 残 冬 桥 妇 警 综 招 吴 付 浮 遭 徐 您 摇 谷 赞 箱 隔 订 男 吹 园 纷 唐 败 宋 玻 巨 耕 坦 荣 闭 湾 键 凡 驻 锅 救 恩 剥 凝 碱 齿 截 炼 麻 纺 禁 废 盛 版 缓 净 睛 昌 婚 涉 筒 嘴 插 岸 朗 庄 街 藏 姑 贸 腐 奴 啦 惯 乘 伙 恢 匀 纱 扎 辩 耳 彪 臣 亿 璃 抵 脉 秀 萨 俄 网 舞 店 喷 纵 寸 汗 挂 洪 贺 闪 柬 爆 烯 津 稻 墙 软 勇 像 滚 厘 蒙 芳 肯 坡 柱 荡 腿 仪 旅 尾 轧 冰 贡 登 黎 削 钻 勒 逃 障 氨 郭 峰 币 港 伏 轨 亩 毕 擦 莫 刺 浪 秘 援 株 健 售 股 岛 甘 泡 睡 童 铸 汤 阀 休 汇 舍 牧 绕 炸 哲 磷 绩 朋 淡 尖 启 陷 柴 呈 徒 颜 泪 稍 忘 泵 蓝 拖 洞 授 镜 辛 壮 锋 贫 虚 弯 摩 泰 幼 廷 尊 窗 纲 弄 隶 疑 氏 宫 姐 震 瑞 怪 尤 琴 循 描 膜 违 夹 腰 缘 珠 穷 森 枝 竹 沟 催 绳 忆 邦 剩 幸 浆 栏 拥 牙 贮 礼 滤 钠 纹 罢 拍 咱 喊 袖 埃 勤 罚 焦 潜 伍 墨 欲 缝 姓 刊 饱 仿 奖 铝 鬼 丽 跨 默 挖 链 扫 喝 袋 炭 污 幕 诸 弧 励 梅 奶 洁 灾 舟 鉴 苯 讼 抱 毁 懂 寒 智 埔 寄 届 跃 渡 挑 丹 艰 贝 碰 拔 爹 戴 码 梦 芽 熔 赤 渔 哭 敬 颗 奔 铅 仲 虎 稀 妹 乏 珍 申 桌 遵 允 隆 螺 仓 魏 锐 晓 氮 兼 隐 碍 赫 拨 忠 肃 缸 牵 抢 博 巧 壳 兄 杜 讯 诚 碧 祥 柯 页 巡 矩 悲 灌 龄 伦 票 寻 桂 铺 圣 恐 恰 郑 趣 抬 荒 腾 贴 柔 滴 猛 阔 辆 妻 填 撤 储 签 闹 扰 紫 砂 递 戏 吊 陶 伐 喂 疗 瓶 婆 抚 臂 摸 忍 虾 蜡 邻 胸 巩 挤 偶 弃 槽 劲 乳 邓 吉 仁 烂 砖 租 乌 舰 伴 瓜 浅 丙 暂 燥 橡 柳 迷 暖 牌 秧 胆 详 簧 踏 瓷 谱 呆 宾 糊 洛 辉 愤 竞 隙 怒 粘 乃 绪 肩 籍 敏 涂 熙 皆 侦 悬 掘 享 纠 醒 狂 锁 淀 恨 牲 霸 爬 赏 逆 玩 陵 祝 秒 浙 貌 役 彼 悉 鸭 趋 凤 晨 畜 辈 秩 卵 署 梯 炎 滩 棋 驱 筛 峡 冒 啥 寿 译 浸 泉 帽 迟 硅 疆 贷 漏 稿 冠 嫩 胁 芯 牢 叛 蚀 奥 鸣 岭 羊 凭 串 塘 绘 酵 融 盆 锡 庙 筹 冻 辅 摄 袭 筋 拒 僚 旱 钾 鸟 漆 沈 眉 疏 添 棒 穗 硝 韩 逼 扭 侨 凉 挺 碗 栽 炒 杯 患 馏 劝 豪 辽 勃 鸿 旦 吏 拜 狗 埋 辊 掩 饮 搬 骂 辞 勾 扣 估 蒋 绒 雾 丈 朵 姆 拟 宇 辑 陕 雕 偿 蓄 崇 剪 倡 厅 咬 驶 薯 刷 斥 番 赋 奉 佛 浇 漫 曼 扇 钙 桃 扶 仔 返 俗 亏 腔 鞋 棱 覆 框 悄 叔 撞 骗 勘 旺 沸 孤 吐 孟 渠 屈 疾 妙 惜 仰 狠 胀 谐 抛 霉 桑 岗 嘛 衰 盗 渗 脏 赖 涌 甜 曹 阅 肌 哩 厉 烃 纬 毅 昨 伪 症 煮 叹 钉 搭 茎 笼 酷 偷 弓 锥 恒 杰 坑 鼻 翼 纶 叙 狱 逮 罐 络 棚 抑 膨 蔬 寺 骤 穆 冶 枯 册 尸 凸 绅 坯 牺 焰 轰 欣 晋 瘦 御 锭 锦 丧 旬 锻 垄 搜 扑 邀 亭 酯 迈 舒 脆 酶 闲 忧 酚 顽 羽 涨 卸 仗 陪 辟 惩 杭 姚 肚 捉 飘 漂 昆 欺 吾 郎 烷 汁 呵 饰 萧 雅 邮 迁 燕 撒 姻 赴 宴 烦 债 帐 斑 铃 旨 醇 董 饼 雏 姿 拌 傅 腹 妥 揉 贤 拆 歪 葡 胺 丢 浩 徽 昂 垫 挡 览 贪 慰 缴 汪 慌 冯 诺 姜 谊 凶 劣 诬 耀 昏 躺 盈 骑 乔 溪 丛 卢 抹 闷 咨 刮 驾 缆 悟 摘 铒 掷 颇 幻 柄 惠 惨 佳 仇 腊 窝 涤 剑 瞧 堡 泼 葱 罩 霍 捞 胎 苍 滨 俩 捅 湘 砍 霞 邵 萄 疯 淮 遂 熊 粪 烘 宿 档 戈 驳 嫂 裕 徙 箭 捐 肠 撑 晒 辨 殿 莲 摊 搅 酱 屏 疫 哀 蔡 堵 沫 皱 畅 叠 阁 莱 敲 辖 钩 痕 坝 巷 饿 祸 丘 玄 溜 曰 逻 彭 尝 卿 妨 艇 吞 韦 怨 矮 歇".components(separatedBy: " ") + } + var traditionalchineseWords: [String] { + return "的 一 是 在 不 了 有 和 人 這 中 大 為 上 個 國 我 以 要 他 時 來 用 們 生 到 作 地 於 出 就 分 對 成 會 可 主 發 年 動 同 工 也 能 下 過 子 說 產 種 面 而 方 後 多 定 行 學 法 所 民 得 經 十 三 之 進 著 等 部 度 家 電 力 裡 如 水 化 高 自 二 理 起 小 物 現 實 加 量 都 兩 體 制 機 當 使 點 從 業 本 去 把 性 好 應 開 它 合 還 因 由 其 些 然 前 外 天 政 四 日 那 社 義 事 平 形 相 全 表 間 樣 與 關 各 重 新 線 內 數 正 心 反 你 明 看 原 又 麼 利 比 或 但 質 氣 第 向 道 命 此 變 條 只 沒 結 解 問 意 建 月 公 無 系 軍 很 情 者 最 立 代 想 已 通 並 提 直 題 黨 程 展 五 果 料 象 員 革 位 入 常 文 總 次 品 式 活 設 及 管 特 件 長 求 老 頭 基 資 邊 流 路 級 少 圖 山 統 接 知 較 將 組 見 計 別 她 手 角 期 根 論 運 農 指 幾 九 區 強 放 決 西 被 幹 做 必 戰 先 回 則 任 取 據 處 隊 南 給 色 光 門 即 保 治 北 造 百 規 熱 領 七 海 口 東 導 器 壓 志 世 金 增 爭 濟 階 油 思 術 極 交 受 聯 什 認 六 共 權 收 證 改 清 美 再 採 轉 更 單 風 切 打 白 教 速 花 帶 安 場 身 車 例 真 務 具 萬 每 目 至 達 走 積 示 議 聲 報 鬥 完 類 八 離 華 名 確 才 科 張 信 馬 節 話 米 整 空 元 況 今 集 溫 傳 土 許 步 群 廣 石 記 需 段 研 界 拉 林 律 叫 且 究 觀 越 織 裝 影 算 低 持 音 眾 書 布 复 容 兒 須 際 商 非 驗 連 斷 深 難 近 礦 千 週 委 素 技 備 半 辦 青 省 列 習 響 約 支 般 史 感 勞 便 團 往 酸 歷 市 克 何 除 消 構 府 稱 太 準 精 值 號 率 族 維 劃 選 標 寫 存 候 毛 親 快 效 斯 院 查 江 型 眼 王 按 格 養 易 置 派 層 片 始 卻 專 狀 育 廠 京 識 適 屬 圓 包 火 住 調 滿 縣 局 照 參 紅 細 引 聽 該 鐵 價 嚴 首 底 液 官 德 隨 病 蘇 失 爾 死 講 配 女 黃 推 顯 談 罪 神 藝 呢 席 含 企 望 密 批 營 項 防 舉 球 英 氧 勢 告 李 台 落 木 幫 輪 破 亞 師 圍 注 遠 字 材 排 供 河 態 封 另 施 減 樹 溶 怎 止 案 言 士 均 武 固 葉 魚 波 視 僅 費 緊 愛 左 章 早 朝 害 續 輕 服 試 食 充 兵 源 判 護 司 足 某 練 差 致 板 田 降 黑 犯 負 擊 范 繼 興 似 餘 堅 曲 輸 修 故 城 夫 夠 送 筆 船 佔 右 財 吃 富 春 職 覺 漢 畫 功 巴 跟 雖 雜 飛 檢 吸 助 昇 陽 互 初 創 抗 考 投 壞 策 古 徑 換 未 跑 留 鋼 曾 端 責 站 簡 述 錢 副 盡 帝 射 草 衝 承 獨 令 限 阿 宣 環 雙 請 超 微 讓 控 州 良 軸 找 否 紀 益 依 優 頂 礎 載 倒 房 突 坐 粉 敵 略 客 袁 冷 勝 絕 析 塊 劑 測 絲 協 訴 念 陳 仍 羅 鹽 友 洋 錯 苦 夜 刑 移 頻 逐 靠 混 母 短 皮 終 聚 汽 村 雲 哪 既 距 衛 停 烈 央 察 燒 迅 境 若 印 洲 刻 括 激 孔 搞 甚 室 待 核 校 散 侵 吧 甲 遊 久 菜 味 舊 模 湖 貨 損 預 阻 毫 普 穩 乙 媽 植 息 擴 銀 語 揮 酒 守 拿 序 紙 醫 缺 雨 嗎 針 劉 啊 急 唱 誤 訓 願 審 附 獲 茶 鮮 糧 斤 孩 脫 硫 肥 善 龍 演 父 漸 血 歡 械 掌 歌 沙 剛 攻 謂 盾 討 晚 粒 亂 燃 矛 乎 殺 藥 寧 魯 貴 鐘 煤 讀 班 伯 香 介 迫 句 豐 培 握 蘭 擔 弦 蛋 沉 假 穿 執 答 樂 誰 順 煙 縮 徵 臉 喜 松 腳 困 異 免 背 星 福 買 染 井 概 慢 怕 磁 倍 祖 皇 促 靜 補 評 翻 肉 踐 尼 衣 寬 揚 棉 希 傷 操 垂 秋 宜 氫 套 督 振 架 亮 末 憲 慶 編 牛 觸 映 雷 銷 詩 座 居 抓 裂 胞 呼 娘 景 威 綠 晶 厚 盟 衡 雞 孫 延 危 膠 屋 鄉 臨 陸 顧 掉 呀 燈 歲 措 束 耐 劇 玉 趙 跳 哥 季 課 凱 胡 額 款 紹 卷 齊 偉 蒸 殖 永 宗 苗 川 爐 岩 弱 零 楊 奏 沿 露 桿 探 滑 鎮 飯 濃 航 懷 趕 庫 奪 伊 靈 稅 途 滅 賽 歸 召 鼓 播 盤 裁 險 康 唯 錄 菌 純 借 糖 蓋 橫 符 私 努 堂 域 槍 潤 幅 哈 竟 熟 蟲 澤 腦 壤 碳 歐 遍 側 寨 敢 徹 慮 斜 薄 庭 納 彈 飼 伸 折 麥 濕 暗 荷 瓦 塞 床 築 惡 戶 訪 塔 奇 透 梁 刀 旋 跡 卡 氯 遇 份 毒 泥 退 洗 擺 灰 彩 賣 耗 夏 擇 忙 銅 獻 硬 予 繁 圈 雪 函 亦 抽 篇 陣 陰 丁 尺 追 堆 雄 迎 泛 爸 樓 避 謀 噸 野 豬 旗 累 偏 典 館 索 秦 脂 潮 爺 豆 忽 托 驚 塑 遺 愈 朱 替 纖 粗 傾 尚 痛 楚 謝 奮 購 磨 君 池 旁 碎 骨 監 捕 弟 暴 割 貫 殊 釋 詞 亡 壁 頓 寶 午 塵 聞 揭 炮 殘 冬 橋 婦 警 綜 招 吳 付 浮 遭 徐 您 搖 谷 贊 箱 隔 訂 男 吹 園 紛 唐 敗 宋 玻 巨 耕 坦 榮 閉 灣 鍵 凡 駐 鍋 救 恩 剝 凝 鹼 齒 截 煉 麻 紡 禁 廢 盛 版 緩 淨 睛 昌 婚 涉 筒 嘴 插 岸 朗 莊 街 藏 姑 貿 腐 奴 啦 慣 乘 夥 恢 勻 紗 扎 辯 耳 彪 臣 億 璃 抵 脈 秀 薩 俄 網 舞 店 噴 縱 寸 汗 掛 洪 賀 閃 柬 爆 烯 津 稻 牆 軟 勇 像 滾 厘 蒙 芳 肯 坡 柱 盪 腿 儀 旅 尾 軋 冰 貢 登 黎 削 鑽 勒 逃 障 氨 郭 峰 幣 港 伏 軌 畝 畢 擦 莫 刺 浪 秘 援 株 健 售 股 島 甘 泡 睡 童 鑄 湯 閥 休 匯 舍 牧 繞 炸 哲 磷 績 朋 淡 尖 啟 陷 柴 呈 徒 顏 淚 稍 忘 泵 藍 拖 洞 授 鏡 辛 壯 鋒 貧 虛 彎 摩 泰 幼 廷 尊 窗 綱 弄 隸 疑 氏 宮 姐 震 瑞 怪 尤 琴 循 描 膜 違 夾 腰 緣 珠 窮 森 枝 竹 溝 催 繩 憶 邦 剩 幸 漿 欄 擁 牙 貯 禮 濾 鈉 紋 罷 拍 咱 喊 袖 埃 勤 罰 焦 潛 伍 墨 欲 縫 姓 刊 飽 仿 獎 鋁 鬼 麗 跨 默 挖 鏈 掃 喝 袋 炭 污 幕 諸 弧 勵 梅 奶 潔 災 舟 鑑 苯 訟 抱 毀 懂 寒 智 埔 寄 屆 躍 渡 挑 丹 艱 貝 碰 拔 爹 戴 碼 夢 芽 熔 赤 漁 哭 敬 顆 奔 鉛 仲 虎 稀 妹 乏 珍 申 桌 遵 允 隆 螺 倉 魏 銳 曉 氮 兼 隱 礙 赫 撥 忠 肅 缸 牽 搶 博 巧 殼 兄 杜 訊 誠 碧 祥 柯 頁 巡 矩 悲 灌 齡 倫 票 尋 桂 鋪 聖 恐 恰 鄭 趣 抬 荒 騰 貼 柔 滴 猛 闊 輛 妻 填 撤 儲 簽 鬧 擾 紫 砂 遞 戲 吊 陶 伐 餵 療 瓶 婆 撫 臂 摸 忍 蝦 蠟 鄰 胸 鞏 擠 偶 棄 槽 勁 乳 鄧 吉 仁 爛 磚 租 烏 艦 伴 瓜 淺 丙 暫 燥 橡 柳 迷 暖 牌 秧 膽 詳 簧 踏 瓷 譜 呆 賓 糊 洛 輝 憤 競 隙 怒 粘 乃 緒 肩 籍 敏 塗 熙 皆 偵 懸 掘 享 糾 醒 狂 鎖 淀 恨 牲 霸 爬 賞 逆 玩 陵 祝 秒 浙 貌 役 彼 悉 鴨 趨 鳳 晨 畜 輩 秩 卵 署 梯 炎 灘 棋 驅 篩 峽 冒 啥 壽 譯 浸 泉 帽 遲 矽 疆 貸 漏 稿 冠 嫩 脅 芯 牢 叛 蝕 奧 鳴 嶺 羊 憑 串 塘 繪 酵 融 盆 錫 廟 籌 凍 輔 攝 襲 筋 拒 僚 旱 鉀 鳥 漆 沈 眉 疏 添 棒 穗 硝 韓 逼 扭 僑 涼 挺 碗 栽 炒 杯 患 餾 勸 豪 遼 勃 鴻 旦 吏 拜 狗 埋 輥 掩 飲 搬 罵 辭 勾 扣 估 蔣 絨 霧 丈 朵 姆 擬 宇 輯 陝 雕 償 蓄 崇 剪 倡 廳 咬 駛 薯 刷 斥 番 賦 奉 佛 澆 漫 曼 扇 鈣 桃 扶 仔 返 俗 虧 腔 鞋 棱 覆 框 悄 叔 撞 騙 勘 旺 沸 孤 吐 孟 渠 屈 疾 妙 惜 仰 狠 脹 諧 拋 黴 桑 崗 嘛 衰 盜 滲 臟 賴 湧 甜 曹 閱 肌 哩 厲 烴 緯 毅 昨 偽 症 煮 嘆 釘 搭 莖 籠 酷 偷 弓 錐 恆 傑 坑 鼻 翼 綸 敘 獄 逮 罐 絡 棚 抑 膨 蔬 寺 驟 穆 冶 枯 冊 屍 凸 紳 坯 犧 焰 轟 欣 晉 瘦 禦 錠 錦 喪 旬 鍛 壟 搜 撲 邀 亭 酯 邁 舒 脆 酶 閒 憂 酚 頑 羽 漲 卸 仗 陪 闢 懲 杭 姚 肚 捉 飄 漂 昆 欺 吾 郎 烷 汁 呵 飾 蕭 雅 郵 遷 燕 撒 姻 赴 宴 煩 債 帳 斑 鈴 旨 醇 董 餅 雛 姿 拌 傅 腹 妥 揉 賢 拆 歪 葡 胺 丟 浩 徽 昂 墊 擋 覽 貪 慰 繳 汪 慌 馮 諾 姜 誼 兇 劣 誣 耀 昏 躺 盈 騎 喬 溪 叢 盧 抹 悶 諮 刮 駕 纜 悟 摘 鉺 擲 頗 幻 柄 惠 慘 佳 仇 臘 窩 滌 劍 瞧 堡 潑 蔥 罩 霍 撈 胎 蒼 濱 倆 捅 湘 砍 霞 邵 萄 瘋 淮 遂 熊 糞 烘 宿 檔 戈 駁 嫂 裕 徙 箭 捐 腸 撐 曬 辨 殿 蓮 攤 攪 醬 屏 疫 哀 蔡 堵 沫 皺 暢 疊 閣 萊 敲 轄 鉤 痕 壩 巷 餓 禍 丘 玄 溜 曰 邏 彭 嘗 卿 妨 艇 吞 韋 怨 矮 歇".components(separatedBy: " ") + } + var japaneseWords: [String] { + return "あいこくしん あいさつ あいだ あおぞら あかちゃん あきる あけがた あける あこがれる あさい あさひ あしあと あじわう あずかる あずき あそぶ あたえる あたためる あたりまえ あたる あつい あつかう あっしゅく あつまり あつめる あてな あてはまる あひる あぶら あぶる あふれる あまい あまど あまやかす あまり あみもの あめりか あやまる あゆむ あらいぐま あらし あらすじ あらためる あらゆる あらわす ありがとう あわせる あわてる あんい あんがい あんこ あんぜん あんてい あんない あんまり いいだす いおん いがい いがく いきおい いきなり いきもの いきる いくじ いくぶん いけばな いけん いこう いこく いこつ いさましい いさん いしき いじゅう いじょう いじわる いずみ いずれ いせい いせえび いせかい いせき いぜん いそうろう いそがしい いだい いだく いたずら いたみ いたりあ いちおう いちじ いちど いちば いちぶ いちりゅう いつか いっしゅん いっせい いっそう いったん いっち いってい いっぽう いてざ いてん いどう いとこ いない いなか いねむり いのち いのる いはつ いばる いはん いびき いひん いふく いへん いほう いみん いもうと いもたれ いもり いやがる いやす いよかん いよく いらい いらすと いりぐち いりょう いれい いれもの いれる いろえんぴつ いわい いわう いわかん いわば いわゆる いんげんまめ いんさつ いんしょう いんよう うえき うえる うおざ うがい うかぶ うかべる うきわ うくらいな うくれれ うけたまわる うけつけ うけとる うけもつ うける うごかす うごく うこん うさぎ うしなう うしろがみ うすい うすぎ うすぐらい うすめる うせつ うちあわせ うちがわ うちき うちゅう うっかり うつくしい うったえる うつる うどん うなぎ うなじ うなずく うなる うねる うのう うぶげ うぶごえ うまれる うめる うもう うやまう うよく うらがえす うらぐち うらない うりあげ うりきれ うるさい うれしい うれゆき うれる うろこ うわき うわさ うんこう うんちん うんてん うんどう えいえん えいが えいきょう えいご えいせい えいぶん えいよう えいわ えおり えがお えがく えきたい えくせる えしゃく えすて えつらん えのぐ えほうまき えほん えまき えもじ えもの えらい えらぶ えりあ えんえん えんかい えんぎ えんげき えんしゅう えんぜつ えんそく えんちょう えんとつ おいかける おいこす おいしい おいつく おうえん おうさま おうじ おうせつ おうたい おうふく おうべい おうよう おえる おおい おおう おおどおり おおや おおよそ おかえり おかず おがむ おかわり おぎなう おきる おくさま おくじょう おくりがな おくる おくれる おこす おこなう おこる おさえる おさない おさめる おしいれ おしえる おじぎ おじさん おしゃれ おそらく おそわる おたがい おたく おだやか おちつく おっと おつり おでかけ おとしもの おとなしい おどり おどろかす おばさん おまいり おめでとう おもいで おもう おもたい おもちゃ おやつ おやゆび およぼす おらんだ おろす おんがく おんけい おんしゃ おんせん おんだん おんちゅう おんどけい かあつ かいが がいき がいけん がいこう かいさつ かいしゃ かいすいよく かいぜん かいぞうど かいつう かいてん かいとう かいふく がいへき かいほう かいよう がいらい かいわ かえる かおり かかえる かがく かがし かがみ かくご かくとく かざる がぞう かたい かたち がちょう がっきゅう がっこう がっさん がっしょう かなざわし かのう がはく かぶか かほう かほご かまう かまぼこ かめれおん かゆい かようび からい かるい かろう かわく かわら がんか かんけい かんこう かんしゃ かんそう かんたん かんち がんばる きあい きあつ きいろ ぎいん きうい きうん きえる きおう きおく きおち きおん きかい きかく きかんしゃ ききて きくばり きくらげ きけんせい きこう きこえる きこく きさい きさく きさま きさらぎ ぎじかがく ぎしき ぎじたいけん ぎじにってい ぎじゅつしゃ きすう きせい きせき きせつ きそう きぞく きぞん きたえる きちょう きつえん ぎっちり きつつき きつね きてい きどう きどく きない きなが きなこ きぬごし きねん きのう きのした きはく きびしい きひん きふく きぶん きぼう きほん きまる きみつ きむずかしい きめる きもだめし きもち きもの きゃく きやく ぎゅうにく きよう きょうりゅう きらい きらく きりん きれい きれつ きろく ぎろん きわめる ぎんいろ きんかくじ きんじょ きんようび ぐあい くいず くうかん くうき くうぐん くうこう ぐうせい くうそう ぐうたら くうふく くうぼ くかん くきょう くげん ぐこう くさい くさき くさばな くさる くしゃみ くしょう くすのき くすりゆび くせげ くせん ぐたいてき くださる くたびれる くちこみ くちさき くつした ぐっすり くつろぐ くとうてん くどく くなん くねくね くのう くふう くみあわせ くみたてる くめる くやくしょ くらす くらべる くるま くれる くろう くわしい ぐんかん ぐんしょく ぐんたい ぐんて けあな けいかく けいけん けいこ けいさつ げいじゅつ けいたい げいのうじん けいれき けいろ けおとす けおりもの げきか げきげん げきだん げきちん げきとつ げきは げきやく げこう げこくじょう げざい けさき げざん けしき けしごむ けしょう げすと けたば けちゃっぷ けちらす けつあつ けつい けつえき けっこん けつじょ けっせき けってい けつまつ げつようび げつれい けつろん げどく けとばす けとる けなげ けなす けなみ けぬき げねつ けねん けはい げひん けぶかい げぼく けまり けみかる けむし けむり けもの けらい けろけろ けわしい けんい けんえつ けんお けんか げんき けんげん けんこう けんさく けんしゅう けんすう げんそう けんちく けんてい けんとう けんない けんにん げんぶつ けんま けんみん けんめい けんらん けんり こあくま こいぬ こいびと ごうい こうえん こうおん こうかん ごうきゅう ごうけい こうこう こうさい こうじ こうすい ごうせい こうそく こうたい こうちゃ こうつう こうてい こうどう こうない こうはい ごうほう ごうまん こうもく こうりつ こえる こおり ごかい ごがつ ごかん こくご こくさい こくとう こくない こくはく こぐま こけい こける ここのか こころ こさめ こしつ こすう こせい こせき こぜん こそだて こたい こたえる こたつ こちょう こっか こつこつ こつばん こつぶ こてい こてん ことがら ことし ことば ことり こなごな こねこね このまま このみ このよ ごはん こひつじ こふう こふん こぼれる ごまあぶら こまかい ごますり こまつな こまる こむぎこ こもじ こもち こもの こもん こやく こやま こゆう こゆび こよい こよう こりる これくしょん ころっけ こわもて こわれる こんいん こんかい こんき こんしゅう こんすい こんだて こんとん こんなん こんびに こんぽん こんまけ こんや こんれい こんわく ざいえき さいかい さいきん ざいげん ざいこ さいしょ さいせい ざいたく ざいちゅう さいてき ざいりょう さうな さかいし さがす さかな さかみち さがる さぎょう さくし さくひん さくら さこく さこつ さずかる ざせき さたん さつえい ざつおん ざっか ざつがく さっきょく ざっし さつじん ざっそう さつたば さつまいも さてい さといも さとう さとおや さとし さとる さのう さばく さびしい さべつ さほう さほど さます さみしい さみだれ さむけ さめる さやえんどう さゆう さよう さよく さらだ ざるそば さわやか さわる さんいん さんか さんきゃく さんこう さんさい ざんしょ さんすう さんせい さんそ さんち さんま さんみ さんらん しあい しあげ しあさって しあわせ しいく しいん しうち しえい しおけ しかい しかく じかん しごと しすう じだい したうけ したぎ したて したみ しちょう しちりん しっかり しつじ しつもん してい してき してつ じてん じどう しなぎれ しなもの しなん しねま しねん しのぐ しのぶ しはい しばかり しはつ しはらい しはん しひょう しふく じぶん しへい しほう しほん しまう しまる しみん しむける じむしょ しめい しめる しもん しゃいん しゃうん しゃおん じゃがいも しやくしょ しゃくほう しゃけん しゃこ しゃざい しゃしん しゃせん しゃそう しゃたい しゃちょう しゃっきん じゃま しゃりん しゃれい じゆう じゅうしょ しゅくはく じゅしん しゅっせき しゅみ しゅらば じゅんばん しょうかい しょくたく しょっけん しょどう しょもつ しらせる しらべる しんか しんこう じんじゃ しんせいじ しんちく しんりん すあげ すあし すあな ずあん すいえい すいか すいとう ずいぶん すいようび すうがく すうじつ すうせん すおどり すきま すくう すくない すける すごい すこし ずさん すずしい すすむ すすめる すっかり ずっしり ずっと すてき すてる すねる すのこ すはだ すばらしい ずひょう ずぶぬれ すぶり すふれ すべて すべる ずほう すぼん すまい すめし すもう すやき すらすら するめ すれちがう すろっと すわる すんぜん すんぽう せあぶら せいかつ せいげん せいじ せいよう せおう せかいかん せきにん せきむ せきゆ せきらんうん せけん せこう せすじ せたい せたけ せっかく せっきゃく ぜっく せっけん せっこつ せっさたくま せつぞく せつだん せつでん せっぱん せつび せつぶん せつめい せつりつ せなか せのび せはば せびろ せぼね せまい せまる せめる せもたれ せりふ ぜんあく せんい せんえい せんか せんきょ せんく せんげん ぜんご せんさい せんしゅ せんすい せんせい せんぞ せんたく せんちょう せんてい せんとう せんぬき せんねん せんぱい ぜんぶ ぜんぽう せんむ せんめんじょ せんもん せんやく せんゆう せんよう ぜんら ぜんりゃく せんれい せんろ そあく そいとげる そいね そうがんきょう そうき そうご そうしん そうだん そうなん そうび そうめん そうり そえもの そえん そがい そげき そこう そこそこ そざい そしな そせい そせん そそぐ そだてる そつう そつえん そっかん そつぎょう そっけつ そっこう そっせん そっと そとがわ そとづら そなえる そなた そふぼ そぼく そぼろ そまつ そまる そむく そむりえ そめる そもそも そよかぜ そらまめ そろう そんかい そんけい そんざい そんしつ そんぞく そんちょう ぞんび ぞんぶん そんみん たあい たいいん たいうん たいえき たいおう だいがく たいき たいぐう たいけん たいこ たいざい だいじょうぶ だいすき たいせつ たいそう だいたい たいちょう たいてい だいどころ たいない たいねつ たいのう たいはん だいひょう たいふう たいへん たいほ たいまつばな たいみんぐ たいむ たいめん たいやき たいよう たいら たいりょく たいる たいわん たうえ たえる たおす たおる たおれる たかい たかね たきび たくさん たこく たこやき たさい たしざん だじゃれ たすける たずさわる たそがれ たたかう たたく ただしい たたみ たちばな だっかい だっきゃく だっこ だっしゅつ だったい たてる たとえる たなばた たにん たぬき たのしみ たはつ たぶん たべる たぼう たまご たまる だむる ためいき ためす ためる たもつ たやすい たよる たらす たりきほんがん たりょう たりる たると たれる たれんと たろっと たわむれる だんあつ たんい たんおん たんか たんき たんけん たんご たんさん たんじょうび だんせい たんそく たんたい だんち たんてい たんとう だんな たんにん だんねつ たんのう たんぴん だんぼう たんまつ たんめい だんれつ だんろ だんわ ちあい ちあん ちいき ちいさい ちえん ちかい ちから ちきゅう ちきん ちけいず ちけん ちこく ちさい ちしき ちしりょう ちせい ちそう ちたい ちたん ちちおや ちつじょ ちてき ちてん ちぬき ちぬり ちのう ちひょう ちへいせん ちほう ちまた ちみつ ちみどろ ちめいど ちゃんこなべ ちゅうい ちゆりょく ちょうし ちょさくけん ちらし ちらみ ちりがみ ちりょう ちるど ちわわ ちんたい ちんもく ついか ついたち つうか つうじょう つうはん つうわ つかう つかれる つくね つくる つけね つける つごう つたえる つづく つつじ つつむ つとめる つながる つなみ つねづね つのる つぶす つまらない つまる つみき つめたい つもり つもる つよい つるぼ つるみく つわもの つわり てあし てあて てあみ ていおん ていか ていき ていけい ていこく ていさつ ていし ていせい ていたい ていど ていねい ていひょう ていへん ていぼう てうち ておくれ てきとう てくび でこぼこ てさぎょう てさげ てすり てそう てちがい てちょう てつがく てつづき でっぱ てつぼう てつや でぬかえ てぬき てぬぐい てのひら てはい てぶくろ てふだ てほどき てほん てまえ てまきずし てみじか てみやげ てらす てれび てわけ てわたし でんあつ てんいん てんかい てんき てんぐ てんけん てんごく てんさい てんし てんすう でんち てんてき てんとう てんない てんぷら てんぼうだい てんめつ てんらんかい でんりょく でんわ どあい といれ どうかん とうきゅう どうぐ とうし とうむぎ とおい とおか とおく とおす とおる とかい とかす ときおり ときどき とくい とくしゅう とくてん とくに とくべつ とけい とける とこや とさか としょかん とそう とたん とちゅう とっきゅう とっくん とつぜん とつにゅう とどける ととのえる とない となえる となり とのさま とばす どぶがわ とほう とまる とめる ともだち ともる どようび とらえる とんかつ どんぶり ないかく ないこう ないしょ ないす ないせん ないそう なおす ながい なくす なげる なこうど なさけ なたでここ なっとう なつやすみ ななおし なにごと なにもの なにわ なのか なふだ なまいき なまえ なまみ なみだ なめらか なめる なやむ ならう ならび ならぶ なれる なわとび なわばり にあう にいがた にうけ におい にかい にがて にきび にくしみ にくまん にげる にさんかたんそ にしき にせもの にちじょう にちようび にっか にっき にっけい にっこう にっさん にっしょく にっすう にっせき にってい になう にほん にまめ にもつ にやり にゅういん にりんしゃ にわとり にんい にんか にんき にんげん にんしき にんずう にんそう にんたい にんち にんてい にんにく にんぷ にんまり にんむ にんめい にんよう ぬいくぎ ぬかす ぬぐいとる ぬぐう ぬくもり ぬすむ ぬまえび ぬめり ぬらす ぬんちゃく ねあげ ねいき ねいる ねいろ ねぐせ ねくたい ねくら ねこぜ ねこむ ねさげ ねすごす ねそべる ねだん ねつい ねっしん ねつぞう ねったいぎょ ねぶそく ねふだ ねぼう ねほりはほり ねまき ねまわし ねみみ ねむい ねむたい ねもと ねらう ねわざ ねんいり ねんおし ねんかん ねんきん ねんぐ ねんざ ねんし ねんちゃく ねんど ねんぴ ねんぶつ ねんまつ ねんりょう ねんれい のいず のおづま のがす のきなみ のこぎり のこす のこる のせる のぞく のぞむ のたまう のちほど のっく のばす のはら のべる のぼる のみもの のやま のらいぬ のらねこ のりもの のりゆき のれん のんき ばあい はあく ばあさん ばいか ばいく はいけん はいご はいしん はいすい はいせん はいそう はいち ばいばい はいれつ はえる はおる はかい ばかり はかる はくしゅ はけん はこぶ はさみ はさん はしご ばしょ はしる はせる ぱそこん はそん はたん はちみつ はつおん はっかく はづき はっきり はっくつ はっけん はっこう はっさん はっしん はったつ はっちゅう はってん はっぴょう はっぽう はなす はなび はにかむ はぶらし はみがき はむかう はめつ はやい はやし はらう はろうぃん はわい はんい はんえい はんおん はんかく はんきょう ばんぐみ はんこ はんしゃ はんすう はんだん ぱんち ぱんつ はんてい はんとし はんのう はんぱ はんぶん はんぺん はんぼうき はんめい はんらん はんろん ひいき ひうん ひえる ひかく ひかり ひかる ひかん ひくい ひけつ ひこうき ひこく ひさい ひさしぶり ひさん びじゅつかん ひしょ ひそか ひそむ ひたむき ひだり ひたる ひつぎ ひっこし ひっし ひつじゅひん ひっす ひつぜん ぴったり ぴっちり ひつよう ひてい ひとごみ ひなまつり ひなん ひねる ひはん ひびく ひひょう ひほう ひまわり ひまん ひみつ ひめい ひめじし ひやけ ひやす ひよう びょうき ひらがな ひらく ひりつ ひりょう ひるま ひるやすみ ひれい ひろい ひろう ひろき ひろゆき ひんかく ひんけつ ひんこん ひんしゅ ひんそう ぴんち ひんぱん びんぼう ふあん ふいうち ふうけい ふうせん ぷうたろう ふうとう ふうふ ふえる ふおん ふかい ふきん ふくざつ ふくぶくろ ふこう ふさい ふしぎ ふじみ ふすま ふせい ふせぐ ふそく ぶたにく ふたん ふちょう ふつう ふつか ふっかつ ふっき ふっこく ぶどう ふとる ふとん ふのう ふはい ふひょう ふへん ふまん ふみん ふめつ ふめん ふよう ふりこ ふりる ふるい ふんいき ぶんがく ぶんぐ ふんしつ ぶんせき ふんそう ぶんぽう へいあん へいおん へいがい へいき へいげん へいこう へいさ へいしゃ へいせつ へいそ へいたく へいてん へいねつ へいわ へきが へこむ べにいろ べにしょうが へらす へんかん べんきょう べんごし へんさい へんたい べんり ほあん ほいく ぼうぎょ ほうこく ほうそう ほうほう ほうもん ほうりつ ほえる ほおん ほかん ほきょう ぼきん ほくろ ほけつ ほけん ほこう ほこる ほしい ほしつ ほしゅ ほしょう ほせい ほそい ほそく ほたて ほたる ぽちぶくろ ほっきょく ほっさ ほったん ほとんど ほめる ほんい ほんき ほんけ ほんしつ ほんやく まいにち まかい まかせる まがる まける まこと まさつ まじめ ますく まぜる まつり まとめ まなぶ まぬけ まねく まほう まもる まゆげ まよう まろやか まわす まわり まわる まんが まんきつ まんぞく まんなか みいら みうち みえる みがく みかた みかん みけん みこん みじかい みすい みすえる みせる みっか みつかる みつける みてい みとめる みなと みなみかさい みねらる みのう みのがす みほん みもと みやげ みらい みりょく みわく みんか みんぞく むいか むえき むえん むかい むかう むかえ むかし むぎちゃ むける むげん むさぼる むしあつい むしば むじゅん むしろ むすう むすこ むすぶ むすめ むせる むせん むちゅう むなしい むのう むやみ むよう むらさき むりょう むろん めいあん めいうん めいえん めいかく めいきょく めいさい めいし めいそう めいぶつ めいれい めいわく めぐまれる めざす めした めずらしい めだつ めまい めやす めんきょ めんせき めんどう もうしあげる もうどうけん もえる もくし もくてき もくようび もちろん もどる もらう もんく もんだい やおや やける やさい やさしい やすい やすたろう やすみ やせる やそう やたい やちん やっと やっぱり やぶる やめる ややこしい やよい やわらかい ゆうき ゆうびんきょく ゆうべ ゆうめい ゆけつ ゆしゅつ ゆせん ゆそう ゆたか ゆちゃく ゆでる ゆにゅう ゆびわ ゆらい ゆれる ようい ようか ようきゅう ようじ ようす ようちえん よかぜ よかん よきん よくせい よくぼう よけい よごれる よさん よしゅう よそう よそく よっか よてい よどがわく よねつ よやく よゆう よろこぶ よろしい らいう らくがき らくご らくさつ らくだ らしんばん らせん らぞく らたい らっか られつ りえき りかい りきさく りきせつ りくぐん りくつ りけん りこう りせい りそう りそく りてん りねん りゆう りゅうがく りよう りょうり りょかん りょくちゃ りょこう りりく りれき りろん りんご るいけい るいさい るいじ るいせき るすばん るりがわら れいかん れいぎ れいせい れいぞうこ れいとう れいぼう れきし れきだい れんあい れんけい れんこん れんさい れんしゅう れんぞく れんらく ろうか ろうご ろうじん ろうそく ろくが ろこつ ろじうら ろしゅつ ろせん ろてん ろめん ろれつ ろんぎ ろんぱ ろんぶん ろんり わかす わかめ わかやま わかれる わしつ わじまし わすれもの わらう われる".components(separatedBy: " ") + } + var koreanWords: [String] { + return "가격 가끔 가난 가능 가득 가르침 가뭄 가방 가상 가슴 가운데 가을 가이드 가입 가장 가정 가족 가죽 각오 각자 간격 간부 간섭 간장 간접 간판 갈등 갈비 갈색 갈증 감각 감기 감소 감수성 감자 감정 갑자기 강남 강당 강도 강력히 강변 강북 강사 강수량 강아지 강원도 강의 강제 강조 같이 개구리 개나리 개방 개별 개선 개성 개인 객관적 거실 거액 거울 거짓 거품 걱정 건강 건물 건설 건조 건축 걸음 검사 검토 게시판 게임 겨울 견해 결과 결국 결론 결석 결승 결심 결정 결혼 경계 경고 경기 경력 경복궁 경비 경상도 경영 경우 경쟁 경제 경주 경찰 경치 경향 경험 계곡 계단 계란 계산 계속 계약 계절 계층 계획 고객 고구려 고궁 고급 고등학생 고무신 고민 고양이 고장 고전 고집 고춧가루 고통 고향 곡식 골목 골짜기 골프 공간 공개 공격 공군 공급 공기 공동 공무원 공부 공사 공식 공업 공연 공원 공장 공짜 공책 공통 공포 공항 공휴일 과목 과일 과장 과정 과학 관객 관계 관광 관념 관람 관련 관리 관습 관심 관점 관찰 광경 광고 광장 광주 괴로움 굉장히 교과서 교문 교복 교실 교양 교육 교장 교직 교통 교환 교훈 구경 구름 구멍 구별 구분 구석 구성 구속 구역 구입 구청 구체적 국가 국기 국내 국립 국물 국민 국수 국어 국왕 국적 국제 국회 군대 군사 군인 궁극적 권리 권위 권투 귀국 귀신 규정 규칙 균형 그날 그냥 그늘 그러나 그룹 그릇 그림 그제서야 그토록 극복 극히 근거 근교 근래 근로 근무 근본 근원 근육 근처 글씨 글자 금강산 금고 금년 금메달 금액 금연 금요일 금지 긍정적 기간 기관 기념 기능 기독교 기둥 기록 기름 기법 기본 기분 기쁨 기숙사 기술 기억 기업 기온 기운 기원 기적 기준 기침 기혼 기획 긴급 긴장 길이 김밥 김치 김포공항 깍두기 깜빡 깨달음 깨소금 껍질 꼭대기 꽃잎 나들이 나란히 나머지 나물 나침반 나흘 낙엽 난방 날개 날씨 날짜 남녀 남대문 남매 남산 남자 남편 남학생 낭비 낱말 내년 내용 내일 냄비 냄새 냇물 냉동 냉면 냉방 냉장고 넥타이 넷째 노동 노란색 노력 노인 녹음 녹차 녹화 논리 논문 논쟁 놀이 농구 농담 농민 농부 농업 농장 농촌 높이 눈동자 눈물 눈썹 뉴욕 느낌 늑대 능동적 능력 다방 다양성 다음 다이어트 다행 단계 단골 단독 단맛 단순 단어 단위 단점 단체 단추 단편 단풍 달걀 달러 달력 달리 닭고기 담당 담배 담요 담임 답변 답장 당근 당분간 당연히 당장 대규모 대낮 대단히 대답 대도시 대략 대량 대륙 대문 대부분 대신 대응 대장 대전 대접 대중 대책 대출 대충 대통령 대학 대한민국 대합실 대형 덩어리 데이트 도대체 도덕 도둑 도망 도서관 도심 도움 도입 도자기 도저히 도전 도중 도착 독감 독립 독서 독일 독창적 동화책 뒷모습 뒷산 딸아이 마누라 마늘 마당 마라톤 마련 마무리 마사지 마약 마요네즈 마을 마음 마이크 마중 마지막 마찬가지 마찰 마흔 막걸리 막내 막상 만남 만두 만세 만약 만일 만점 만족 만화 많이 말기 말씀 말투 맘대로 망원경 매년 매달 매력 매번 매스컴 매일 매장 맥주 먹이 먼저 먼지 멀리 메일 며느리 며칠 면담 멸치 명단 명령 명예 명의 명절 명칭 명함 모금 모니터 모델 모든 모범 모습 모양 모임 모조리 모집 모퉁이 목걸이 목록 목사 목소리 목숨 목적 목표 몰래 몸매 몸무게 몸살 몸속 몸짓 몸통 몹시 무관심 무궁화 무더위 무덤 무릎 무슨 무엇 무역 무용 무조건 무지개 무척 문구 문득 문법 문서 문제 문학 문화 물가 물건 물결 물고기 물론 물리학 물음 물질 물체 미국 미디어 미사일 미술 미역 미용실 미움 미인 미팅 미혼 민간 민족 민주 믿음 밀가루 밀리미터 밑바닥 바가지 바구니 바나나 바늘 바닥 바닷가 바람 바이러스 바탕 박물관 박사 박수 반대 반드시 반말 반발 반성 반응 반장 반죽 반지 반찬 받침 발가락 발걸음 발견 발달 발레 발목 발바닥 발생 발음 발자국 발전 발톱 발표 밤하늘 밥그릇 밥맛 밥상 밥솥 방금 방면 방문 방바닥 방법 방송 방식 방안 방울 방지 방학 방해 방향 배경 배꼽 배달 배드민턴 백두산 백색 백성 백인 백제 백화점 버릇 버섯 버튼 번개 번역 번지 번호 벌금 벌레 벌써 범위 범인 범죄 법률 법원 법적 법칙 베이징 벨트 변경 변동 변명 변신 변호사 변화 별도 별명 별일 병실 병아리 병원 보관 보너스 보라색 보람 보름 보상 보안 보자기 보장 보전 보존 보통 보편적 보험 복도 복사 복숭아 복습 볶음 본격적 본래 본부 본사 본성 본인 본질 볼펜 봉사 봉지 봉투 부근 부끄러움 부담 부동산 부문 부분 부산 부상 부엌 부인 부작용 부장 부정 부족 부지런히 부친 부탁 부품 부회장 북부 북한 분노 분량 분리 분명 분석 분야 분위기 분필 분홍색 불고기 불과 불교 불꽃 불만 불법 불빛 불안 불이익 불행 브랜드 비극 비난 비닐 비둘기 비디오 비로소 비만 비명 비밀 비바람 비빔밥 비상 비용 비율 비중 비타민 비판 빌딩 빗물 빗방울 빗줄기 빛깔 빨간색 빨래 빨리 사건 사계절 사나이 사냥 사람 사랑 사립 사모님 사물 사방 사상 사생활 사설 사슴 사실 사업 사용 사월 사장 사전 사진 사촌 사춘기 사탕 사투리 사흘 산길 산부인과 산업 산책 살림 살인 살짝 삼계탕 삼국 삼십 삼월 삼촌 상관 상금 상대 상류 상반기 상상 상식 상업 상인 상자 상점 상처 상추 상태 상표 상품 상황 새벽 색깔 색연필 생각 생명 생물 생방송 생산 생선 생신 생일 생활 서랍 서른 서명 서민 서비스 서양 서울 서적 서점 서쪽 서클 석사 석유 선거 선물 선배 선생 선수 선원 선장 선전 선택 선풍기 설거지 설날 설렁탕 설명 설문 설사 설악산 설치 설탕 섭씨 성공 성당 성명 성별 성인 성장 성적 성질 성함 세금 세미나 세상 세월 세종대왕 세탁 센터 센티미터 셋째 소규모 소극적 소금 소나기 소년 소득 소망 소문 소설 소속 소아과 소용 소원 소음 소중히 소지품 소질 소풍 소형 속담 속도 속옷 손가락 손길 손녀 손님 손등 손목 손뼉 손실 손질 손톱 손해 솔직히 솜씨 송아지 송이 송편 쇠고기 쇼핑 수건 수년 수단 수돗물 수동적 수면 수명 수박 수상 수석 수술 수시로 수업 수염 수영 수입 수준 수집 수출 수컷 수필 수학 수험생 수화기 숙녀 숙소 숙제 순간 순서 순수 순식간 순위 숟가락 술병 술집 숫자 스님 스물 스스로 스승 스웨터 스위치 스케이트 스튜디오 스트레스 스포츠 슬쩍 슬픔 습관 습기 승객 승리 승부 승용차 승진 시각 시간 시골 시금치 시나리오 시댁 시리즈 시멘트 시민 시부모 시선 시설 시스템 시아버지 시어머니 시월 시인 시일 시작 시장 시절 시점 시중 시즌 시집 시청 시합 시험 식구 식기 식당 식량 식료품 식물 식빵 식사 식생활 식초 식탁 식품 신고 신규 신념 신문 신발 신비 신사 신세 신용 신제품 신청 신체 신화 실감 실내 실력 실례 실망 실수 실습 실시 실장 실정 실질적 실천 실체 실컷 실태 실패 실험 실현 심리 심부름 심사 심장 심정 심판 쌍둥이 씨름 씨앗 아가씨 아나운서 아드님 아들 아쉬움 아스팔트 아시아 아울러 아저씨 아줌마 아직 아침 아파트 아프리카 아픔 아홉 아흔 악기 악몽 악수 안개 안경 안과 안내 안녕 안동 안방 안부 안주 알루미늄 알코올 암시 암컷 압력 앞날 앞문 애인 애정 액수 앨범 야간 야단 야옹 약간 약국 약속 약수 약점 약품 약혼녀 양념 양력 양말 양배추 양주 양파 어둠 어려움 어른 어젯밤 어쨌든 어쩌다가 어쩐지 언니 언덕 언론 언어 얼굴 얼른 얼음 얼핏 엄마 업무 업종 업체 엉덩이 엉망 엉터리 엊그제 에너지 에어컨 엔진 여건 여고생 여관 여군 여권 여대생 여덟 여동생 여든 여론 여름 여섯 여성 여왕 여인 여전히 여직원 여학생 여행 역사 역시 역할 연결 연구 연극 연기 연락 연설 연세 연속 연습 연애 연예인 연인 연장 연주 연출 연필 연합 연휴 열기 열매 열쇠 열심히 열정 열차 열흘 염려 엽서 영국 영남 영상 영양 영역 영웅 영원히 영하 영향 영혼 영화 옆구리 옆방 옆집 예감 예금 예방 예산 예상 예선 예술 예습 예식장 예약 예전 예절 예정 예컨대 옛날 오늘 오락 오랫동안 오렌지 오로지 오른발 오븐 오십 오염 오월 오전 오직 오징어 오페라 오피스텔 오히려 옥상 옥수수 온갖 온라인 온몸 온종일 온통 올가을 올림픽 올해 옷차림 와이셔츠 와인 완성 완전 왕비 왕자 왜냐하면 왠지 외갓집 외국 외로움 외삼촌 외출 외침 외할머니 왼발 왼손 왼쪽 요금 요일 요즘 요청 용기 용서 용어 우산 우선 우승 우연히 우정 우체국 우편 운동 운명 운반 운전 운행 울산 울음 움직임 웃어른 웃음 워낙 원고 원래 원서 원숭이 원인 원장 원피스 월급 월드컵 월세 월요일 웨이터 위반 위법 위성 위원 위험 위협 윗사람 유난히 유럽 유명 유물 유산 유적 유치원 유학 유행 유형 육군 육상 육십 육체 은행 음력 음료 음반 음성 음식 음악 음주 의견 의논 의문 의복 의식 의심 의외로 의욕 의원 의학 이것 이곳 이념 이놈 이달 이대로 이동 이렇게 이력서 이론적 이름 이민 이발소 이별 이불 이빨 이상 이성 이슬 이야기 이용 이웃 이월 이윽고 이익 이전 이중 이튿날 이틀 이혼 인간 인격 인공 인구 인근 인기 인도 인류 인물 인생 인쇄 인연 인원 인재 인종 인천 인체 인터넷 인하 인형 일곱 일기 일단 일대 일등 일반 일본 일부 일상 일생 일손 일요일 일월 일정 일종 일주일 일찍 일체 일치 일행 일회용 임금 임무 입대 입력 입맛 입사 입술 입시 입원 입장 입학 자가용 자격 자극 자동 자랑 자부심 자식 자신 자연 자원 자율 자전거 자정 자존심 자판 작가 작년 작성 작업 작용 작은딸 작품 잔디 잔뜩 잔치 잘못 잠깐 잠수함 잠시 잠옷 잠자리 잡지 장관 장군 장기간 장래 장례 장르 장마 장면 장모 장미 장비 장사 장소 장식 장애인 장인 장점 장차 장학금 재능 재빨리 재산 재생 재작년 재정 재채기 재판 재학 재활용 저것 저고리 저곳 저녁 저런 저렇게 저번 저울 저절로 저축 적극 적당히 적성 적용 적응 전개 전공 전기 전달 전라도 전망 전문 전반 전부 전세 전시 전용 전자 전쟁 전주 전철 전체 전통 전혀 전후 절대 절망 절반 절약 절차 점검 점수 점심 점원 점점 점차 접근 접시 접촉 젓가락 정거장 정도 정류장 정리 정말 정면 정문 정반대 정보 정부 정비 정상 정성 정오 정원 정장 정지 정치 정확히 제공 제과점 제대로 제목 제발 제법 제삿날 제안 제일 제작 제주도 제출 제품 제한 조각 조건 조금 조깅 조명 조미료 조상 조선 조용히 조절 조정 조직 존댓말 존재 졸업 졸음 종교 종로 종류 종소리 종업원 종종 종합 좌석 죄인 주관적 주름 주말 주머니 주먹 주문 주민 주방 주변 주식 주인 주일 주장 주전자 주택 준비 줄거리 줄기 줄무늬 중간 중계방송 중국 중년 중단 중독 중반 중부 중세 중소기업 중순 중앙 중요 중학교 즉석 즉시 즐거움 증가 증거 증권 증상 증세 지각 지갑 지경 지극히 지금 지급 지능 지름길 지리산 지방 지붕 지식 지역 지우개 지원 지적 지점 지진 지출 직선 직업 직원 직장 진급 진동 진로 진료 진리 진짜 진찰 진출 진통 진행 질문 질병 질서 짐작 집단 집안 집중 짜증 찌꺼기 차남 차라리 차량 차림 차별 차선 차츰 착각 찬물 찬성 참가 참기름 참새 참석 참여 참외 참조 찻잔 창가 창고 창구 창문 창밖 창작 창조 채널 채점 책가방 책방 책상 책임 챔피언 처벌 처음 천국 천둥 천장 천재 천천히 철도 철저히 철학 첫날 첫째 청년 청바지 청소 청춘 체계 체력 체온 체육 체중 체험 초등학생 초반 초밥 초상화 초순 초여름 초원 초저녁 초점 초청 초콜릿 촛불 총각 총리 총장 촬영 최근 최상 최선 최신 최악 최종 추석 추억 추진 추천 추측 축구 축소 축제 축하 출근 출발 출산 출신 출연 출입 출장 출판 충격 충고 충돌 충분히 충청도 취업 취직 취향 치약 친구 친척 칠십 칠월 칠판 침대 침묵 침실 칫솔 칭찬 카메라 카운터 칼국수 캐릭터 캠퍼스 캠페인 커튼 컨디션 컬러 컴퓨터 코끼리 코미디 콘서트 콜라 콤플렉스 콩나물 쾌감 쿠데타 크림 큰길 큰딸 큰소리 큰아들 큰어머니 큰일 큰절 클래식 클럽 킬로 타입 타자기 탁구 탁자 탄생 태권도 태양 태풍 택시 탤런트 터널 터미널 테니스 테스트 테이블 텔레비전 토론 토마토 토요일 통계 통과 통로 통신 통역 통일 통장 통제 통증 통합 통화 퇴근 퇴원 퇴직금 튀김 트럭 특급 특별 특성 특수 특징 특히 튼튼히 티셔츠 파란색 파일 파출소 판결 판단 판매 판사 팔십 팔월 팝송 패션 팩스 팩시밀리 팬티 퍼센트 페인트 편견 편의 편지 편히 평가 평균 평생 평소 평양 평일 평화 포스터 포인트 포장 포함 표면 표정 표준 표현 품목 품질 풍경 풍속 풍습 프랑스 프린터 플라스틱 피곤 피망 피아노 필름 필수 필요 필자 필통 핑계 하느님 하늘 하드웨어 하룻밤 하반기 하숙집 하순 하여튼 하지만 하천 하품 하필 학과 학교 학급 학기 학년 학력 학번 학부모 학비 학생 학술 학습 학용품 학원 학위 학자 학점 한계 한글 한꺼번에 한낮 한눈 한동안 한때 한라산 한마디 한문 한번 한복 한식 한여름 한쪽 할머니 할아버지 할인 함께 함부로 합격 합리적 항공 항구 항상 항의 해결 해군 해답 해당 해물 해석 해설 해수욕장 해안 핵심 핸드백 햄버거 햇볕 햇살 행동 행복 행사 행운 행위 향기 향상 향수 허락 허용 헬기 현관 현금 현대 현상 현실 현장 현재 현지 혈액 협력 형부 형사 형수 형식 형제 형태 형편 혜택 호기심 호남 호랑이 호박 호텔 호흡 혹시 홀로 홈페이지 홍보 홍수 홍차 화면 화분 화살 화요일 화장 화학 확보 확인 확장 확정 환갑 환경 환영 환율 환자 활기 활동 활발히 활용 활짝 회견 회관 회복 회색 회원 회장 회전 횟수 횡단보도 효율적 후반 후춧가루 훈련 훨씬 휴식 휴일 흉내 흐름 흑백 흑인 흔적 흔히 흥미 흥분 희곡 희망 희생 흰색 힘껏".components(separatedBy: " ") + } + var frenchWords: [String] { + return "abaisser abandon abdiquer abeille abolir aborder aboutir aboyer abrasif abreuver abriter abroger abrupt absence absolu absurde abusif abyssal académie acajou acarien accabler accepter acclamer accolade accroche accuser acerbe achat acheter aciduler acier acompte acquérir acronyme acteur actif actuel adepte adéquat adhésif adjectif adjuger admettre admirer adopter adorer adoucir adresse adroit adulte adverbe aérer aéronef affaire affecter affiche affreux affubler agacer agencer agile agiter agrafer agréable agrume aider aiguille ailier aimable aisance ajouter ajuster alarmer alchimie alerte algèbre algue aliéner aliment alléger alliage allouer allumer alourdir alpaga altesse alvéole amateur ambigu ambre aménager amertume amidon amiral amorcer amour amovible amphibie ampleur amusant analyse anaphore anarchie anatomie ancien anéantir angle angoisse anguleux animal annexer annonce annuel anodin anomalie anonyme anormal antenne antidote anxieux apaiser apéritif aplanir apologie appareil appeler apporter appuyer aquarium aqueduc arbitre arbuste ardeur ardoise argent arlequin armature armement armoire armure arpenter arracher arriver arroser arsenic artériel article aspect asphalte aspirer assaut asservir assiette associer assurer asticot astre astuce atelier atome atrium atroce attaque attentif attirer attraper aubaine auberge audace audible augurer aurore automne autruche avaler avancer avarice avenir averse aveugle aviateur avide avion aviser avoine avouer avril axial axiome badge bafouer bagage baguette baignade balancer balcon baleine balisage bambin bancaire bandage banlieue bannière banquier barbier baril baron barque barrage bassin bastion bataille bateau batterie baudrier bavarder belette bélier belote bénéfice berceau berger berline bermuda besace besogne bétail beurre biberon bicycle bidule bijou bilan bilingue billard binaire biologie biopsie biotype biscuit bison bistouri bitume bizarre blafard blague blanchir blessant blinder blond bloquer blouson bobard bobine boire boiser bolide bonbon bondir bonheur bonifier bonus bordure borne botte boucle boueux bougie boulon bouquin bourse boussole boutique boxeur branche brasier brave brebis brèche breuvage bricoler brigade brillant brioche brique brochure broder bronzer brousse broyeur brume brusque brutal bruyant buffle buisson bulletin bureau burin bustier butiner butoir buvable buvette cabanon cabine cachette cadeau cadre caféine caillou caisson calculer calepin calibre calmer calomnie calvaire camarade caméra camion campagne canal caneton canon cantine canular capable caporal caprice capsule capter capuche carabine carbone caresser caribou carnage carotte carreau carton cascade casier casque cassure causer caution cavalier caverne caviar cédille ceinture céleste cellule cendrier censurer central cercle cérébral cerise cerner cerveau cesser chagrin chaise chaleur chambre chance chapitre charbon chasseur chaton chausson chavirer chemise chenille chéquier chercher cheval chien chiffre chignon chimère chiot chlorure chocolat choisir chose chouette chrome chute cigare cigogne cimenter cinéma cintrer circuler cirer cirque citerne citoyen citron civil clairon clameur claquer classe clavier client cligner climat clivage cloche clonage cloporte cobalt cobra cocasse cocotier coder codifier coffre cogner cohésion coiffer coincer colère colibri colline colmater colonel combat comédie commande compact concert conduire confier congeler connoter consonne contact convexe copain copie corail corbeau cordage corniche corpus correct cortège cosmique costume coton coude coupure courage couteau couvrir coyote crabe crainte cravate crayon créature créditer crémeux creuser crevette cribler crier cristal critère croire croquer crotale crucial cruel crypter cubique cueillir cuillère cuisine cuivre culminer cultiver cumuler cupide curatif curseur cyanure cycle cylindre cynique daigner damier danger danseur dauphin débattre débiter déborder débrider débutant décaler décembre déchirer décider déclarer décorer décrire décupler dédale déductif déesse défensif défiler défrayer dégager dégivrer déglutir dégrafer déjeuner délice déloger demander demeurer démolir dénicher dénouer dentelle dénuder départ dépenser déphaser déplacer déposer déranger dérober désastre descente désert désigner désobéir dessiner destrier détacher détester détourer détresse devancer devenir deviner devoir diable dialogue diamant dicter différer digérer digital digne diluer dimanche diminuer dioxyde directif diriger discuter disposer dissiper distance divertir diviser docile docteur dogme doigt domaine domicile dompter donateur donjon donner dopamine dortoir dorure dosage doseur dossier dotation douanier double douceur douter doyen dragon draper dresser dribbler droiture duperie duplexe durable durcir dynastie éblouir écarter écharpe échelle éclairer éclipse éclore écluse école économie écorce écouter écraser écrémer écrivain écrou écume écureuil édifier éduquer effacer effectif effigie effort effrayer effusion égaliser égarer éjecter élaborer élargir électron élégant éléphant élève éligible élitisme éloge élucider éluder emballer embellir embryon émeraude émission emmener émotion émouvoir empereur employer emporter emprise émulsion encadrer enchère enclave encoche endiguer endosser endroit enduire énergie enfance enfermer enfouir engager engin englober énigme enjamber enjeu enlever ennemi ennuyeux enrichir enrobage enseigne entasser entendre entier entourer entraver énumérer envahir enviable envoyer enzyme éolien épaissir épargne épatant épaule épicerie épidémie épier épilogue épine épisode épitaphe époque épreuve éprouver épuisant équerre équipe ériger érosion erreur éruption escalier espadon espèce espiègle espoir esprit esquiver essayer essence essieu essorer estime estomac estrade étagère étaler étanche étatique éteindre étendoir éternel éthanol éthique ethnie étirer étoffer étoile étonnant étourdir étrange étroit étude euphorie évaluer évasion éventail évidence éviter évolutif évoquer exact exagérer exaucer exceller excitant exclusif excuse exécuter exemple exercer exhaler exhorter exigence exiler exister exotique expédier explorer exposer exprimer exquis extensif extraire exulter fable fabuleux facette facile facture faiblir falaise fameux famille farceur farfelu farine farouche fasciner fatal fatigue faucon fautif faveur favori fébrile féconder fédérer félin femme fémur fendoir féodal fermer féroce ferveur festival feuille feutre février fiasco ficeler fictif fidèle figure filature filetage filière filleul filmer filou filtrer financer finir fiole firme fissure fixer flairer flamme flasque flatteur fléau flèche fleur flexion flocon flore fluctuer fluide fluvial folie fonderie fongible fontaine forcer forgeron formuler fortune fossile foudre fougère fouiller foulure fourmi fragile fraise franchir frapper frayeur frégate freiner frelon frémir frénésie frère friable friction frisson frivole froid fromage frontal frotter fruit fugitif fuite fureur furieux furtif fusion futur gagner galaxie galerie gambader garantir gardien garnir garrigue gazelle gazon géant gélatine gélule gendarme général génie genou gentil géologie géomètre géranium germe gestuel geyser gibier gicler girafe givre glace glaive glisser globe gloire glorieux golfeur gomme gonfler gorge gorille goudron gouffre goulot goupille gourmand goutte graduel graffiti graine grand grappin gratuit gravir grenat griffure griller grimper grogner gronder grotte groupe gruger grutier gruyère guépard guerrier guide guimauve guitare gustatif gymnaste gyrostat habitude hachoir halte hameau hangar hanneton haricot harmonie harpon hasard hélium hématome herbe hérisson hermine héron hésiter heureux hiberner hibou hilarant histoire hiver homard hommage homogène honneur honorer honteux horde horizon horloge hormone horrible houleux housse hublot huileux humain humble humide humour hurler hydromel hygiène hymne hypnose idylle ignorer iguane illicite illusion image imbiber imiter immense immobile immuable impact impérial implorer imposer imprimer imputer incarner incendie incident incliner incolore indexer indice inductif inédit ineptie inexact infini infliger informer infusion ingérer inhaler inhiber injecter injure innocent inoculer inonder inscrire insecte insigne insolite inspirer instinct insulter intact intense intime intrigue intuitif inutile invasion inventer inviter invoquer ironique irradier irréel irriter isoler ivoire ivresse jaguar jaillir jambe janvier jardin jauger jaune javelot jetable jeton jeudi jeunesse joindre joncher jongler joueur jouissif journal jovial joyau joyeux jubiler jugement junior jupon juriste justice juteux juvénile kayak kimono kiosque label labial labourer lacérer lactose lagune laine laisser laitier lambeau lamelle lampe lanceur langage lanterne lapin largeur larme laurier lavabo lavoir lecture légal léger légume lessive lettre levier lexique lézard liasse libérer libre licence licorne liège lièvre ligature ligoter ligue limer limite limonade limpide linéaire lingot lionceau liquide lisière lister lithium litige littoral livreur logique lointain loisir lombric loterie louer lourd loutre louve loyal lubie lucide lucratif lueur lugubre luisant lumière lunaire lundi luron lutter luxueux machine magasin magenta magique maigre maillon maintien mairie maison majorer malaxer maléfice malheur malice mallette mammouth mandater maniable manquant manteau manuel marathon marbre marchand mardi maritime marqueur marron marteler mascotte massif matériel matière matraque maudire maussade mauve maximal méchant méconnu médaille médecin méditer méduse meilleur mélange mélodie membre mémoire menacer mener menhir mensonge mentor mercredi mérite merle messager mesure métal météore méthode métier meuble miauler microbe miette mignon migrer milieu million mimique mince minéral minimal minorer minute miracle miroiter missile mixte mobile moderne moelleux mondial moniteur monnaie monotone monstre montagne monument moqueur morceau morsure mortier moteur motif mouche moufle moulin mousson mouton mouvant multiple munition muraille murène murmure muscle muséum musicien mutation muter mutuel myriade myrtille mystère mythique nageur nappe narquois narrer natation nation nature naufrage nautique navire nébuleux nectar néfaste négation négliger négocier neige nerveux nettoyer neurone neutron neveu niche nickel nitrate niveau noble nocif nocturne noirceur noisette nomade nombreux nommer normatif notable notifier notoire nourrir nouveau novateur novembre novice nuage nuancer nuire nuisible numéro nuptial nuque nutritif obéir objectif obliger obscur observer obstacle obtenir obturer occasion occuper océan octobre octroyer octupler oculaire odeur odorant offenser officier offrir ogive oiseau oisillon olfactif olivier ombrage omettre onctueux onduler onéreux onirique opale opaque opérer opinion opportun opprimer opter optique orageux orange orbite ordonner oreille organe orgueil orifice ornement orque ortie osciller osmose ossature otarie ouragan ourson outil outrager ouvrage ovation oxyde oxygène ozone paisible palace palmarès palourde palper panache panda pangolin paniquer panneau panorama pantalon papaye papier papoter papyrus paradoxe parcelle paresse parfumer parler parole parrain parsemer partager parure parvenir passion pastèque paternel patience patron pavillon pavoiser payer paysage peigne peintre pelage pélican pelle pelouse peluche pendule pénétrer pénible pensif pénurie pépite péplum perdrix perforer période permuter perplexe persil perte peser pétale petit pétrir peuple pharaon phobie phoque photon phrase physique piano pictural pièce pierre pieuvre pilote pinceau pipette piquer pirogue piscine piston pivoter pixel pizza placard plafond plaisir planer plaque plastron plateau pleurer plexus pliage plomb plonger pluie plumage pochette poésie poète pointe poirier poisson poivre polaire policier pollen polygone pommade pompier ponctuel pondérer poney portique position posséder posture potager poteau potion pouce poulain poumon pourpre poussin pouvoir prairie pratique précieux prédire préfixe prélude prénom présence prétexte prévoir primitif prince prison priver problème procéder prodige profond progrès proie projeter prologue promener propre prospère protéger prouesse proverbe prudence pruneau psychose public puceron puiser pulpe pulsar punaise punitif pupitre purifier puzzle pyramide quasar querelle question quiétude quitter quotient racine raconter radieux ragondin raideur raisin ralentir rallonge ramasser rapide rasage ratisser ravager ravin rayonner réactif réagir réaliser réanimer recevoir réciter réclamer récolter recruter reculer recycler rédiger redouter refaire réflexe réformer refrain refuge régalien région réglage régulier réitérer rejeter rejouer relatif relever relief remarque remède remise remonter remplir remuer renard renfort renifler renoncer rentrer renvoi replier reporter reprise reptile requin réserve résineux résoudre respect rester résultat rétablir retenir réticule retomber retracer réunion réussir revanche revivre révolte révulsif richesse rideau rieur rigide rigoler rincer riposter risible risque rituel rival rivière rocheux romance rompre ronce rondin roseau rosier rotatif rotor rotule rouge rouille rouleau routine royaume ruban rubis ruche ruelle rugueux ruiner ruisseau ruser rustique rythme sabler saboter sabre sacoche safari sagesse saisir salade salive salon saluer samedi sanction sanglier sarcasme sardine saturer saugrenu saumon sauter sauvage savant savonner scalpel scandale scélérat scénario sceptre schéma science scinder score scrutin sculpter séance sécable sécher secouer sécréter sédatif séduire seigneur séjour sélectif semaine sembler semence séminal sénateur sensible sentence séparer séquence serein sergent sérieux serrure sérum service sésame sévir sevrage sextuple sidéral siècle siéger siffler sigle signal silence silicium simple sincère sinistre siphon sirop sismique situer skier social socle sodium soigneux soldat soleil solitude soluble sombre sommeil somnoler sonde songeur sonnette sonore sorcier sortir sosie sottise soucieux soudure souffle soulever soupape source soutirer souvenir spacieux spatial spécial sphère spiral stable station sternum stimulus stipuler strict studieux stupeur styliste sublime substrat subtil subvenir succès sucre suffixe suggérer suiveur sulfate superbe supplier surface suricate surmener surprise sursaut survie suspect syllabe symbole symétrie synapse syntaxe système tabac tablier tactile tailler talent talisman talonner tambour tamiser tangible tapis taquiner tarder tarif tartine tasse tatami tatouage taupe taureau taxer témoin temporel tenaille tendre teneur tenir tension terminer terne terrible tétine texte thème théorie thérapie thorax tibia tiède timide tirelire tiroir tissu titane titre tituber toboggan tolérant tomate tonique tonneau toponyme torche tordre tornade torpille torrent torse tortue totem toucher tournage tousser toxine traction trafic tragique trahir train trancher travail trèfle tremper trésor treuil triage tribunal tricoter trilogie triomphe tripler triturer trivial trombone tronc tropical troupeau tuile tulipe tumulte tunnel turbine tuteur tutoyer tuyau tympan typhon typique tyran ubuesque ultime ultrason unanime unifier union unique unitaire univers uranium urbain urticant usage usine usuel usure utile utopie vacarme vaccin vagabond vague vaillant vaincre vaisseau valable valise vallon valve vampire vanille vapeur varier vaseux vassal vaste vecteur vedette végétal véhicule veinard véloce vendredi vénérer venger venimeux ventouse verdure vérin vernir verrou verser vertu veston vétéran vétuste vexant vexer viaduc viande victoire vidange vidéo vignette vigueur vilain village vinaigre violon vipère virement virtuose virus visage viseur vision visqueux visuel vital vitesse viticole vitrine vivace vivipare vocation voguer voile voisin voiture volaille volcan voltiger volume vorace vortex voter vouloir voyage voyelle wagon xénon yacht zèbre zénith zeste zoologie".components(separatedBy: " ") + } + var italianWords: [String] { + return "abaco abbaglio abbinato abete abisso abolire abrasivo abrogato accadere accenno accusato acetone achille acido acqua acre acrilico acrobata acuto adagio addebito addome adeguato aderire adipe adottare adulare affabile affetto affisso affranto aforisma afoso africano agave agente agevole aggancio agire agitare agonismo agricolo agrumeto aguzzo alabarda alato albatro alberato albo albume alce alcolico alettone alfa algebra aliante alibi alimento allagato allegro allievo allodola allusivo almeno alogeno alpaca alpestre altalena alterno alticcio altrove alunno alveolo alzare amalgama amanita amarena ambito ambrato ameba america ametista amico ammasso ammenda ammirare ammonito amore ampio ampliare amuleto anacardo anagrafe analista anarchia anatra anca ancella ancora andare andrea anello angelo angolare angusto anima annegare annidato anno annuncio anonimo anticipo anzi apatico apertura apode apparire appetito appoggio approdo appunto aprile arabica arachide aragosta araldica arancio aratura arazzo arbitro archivio ardito arenile argento argine arguto aria armonia arnese arredato arringa arrosto arsenico arso artefice arzillo asciutto ascolto asepsi asettico asfalto asino asola aspirato aspro assaggio asse assoluto assurdo asta astenuto astice astratto atavico ateismo atomico atono attesa attivare attorno attrito attuale ausilio austria autista autonomo autunno avanzato avere avvenire avviso avvolgere azione azoto azzimo azzurro babele baccano bacino baco badessa badilata bagnato baita balcone baldo balena ballata balzano bambino bandire baraonda barbaro barca baritono barlume barocco basilico basso batosta battuto baule bava bavosa becco beffa belgio belva benda benevole benigno benzina bere berlina beta bibita bici bidone bifido biga bilancia bimbo binocolo biologo bipede bipolare birbante birra biscotto bisesto bisnonno bisonte bisturi bizzarro blando blatta bollito bonifico bordo bosco botanico bottino bozzolo braccio bradipo brama branca bravura bretella brevetto brezza briglia brillante brindare broccolo brodo bronzina brullo bruno bubbone buca budino buffone buio bulbo buono burlone burrasca bussola busta cadetto caduco calamaro calcolo calesse calibro calmo caloria cambusa camerata camicia cammino camola campale canapa candela cane canino canotto cantina capace capello capitolo capogiro cappero capra capsula carapace carcassa cardo carisma carovana carretto cartolina casaccio cascata caserma caso cassone castello casuale catasta catena catrame cauto cavillo cedibile cedrata cefalo celebre cellulare cena cenone centesimo ceramica cercare certo cerume cervello cesoia cespo ceto chela chiaro chicca chiedere chimera china chirurgo chitarra ciao ciclismo cifrare cigno cilindro ciottolo circa cirrosi citrico cittadino ciuffo civetta civile classico clinica cloro cocco codardo codice coerente cognome collare colmato colore colposo coltivato colza coma cometa commando comodo computer comune conciso condurre conferma congelare coniuge connesso conoscere consumo continuo convegno coperto copione coppia copricapo corazza cordata coricato cornice corolla corpo corredo corsia cortese cosmico costante cottura covato cratere cravatta creato credere cremoso crescita creta criceto crinale crisi critico croce cronaca crostata cruciale crusca cucire cuculo cugino cullato cupola curatore cursore curvo cuscino custode dado daino dalmata damerino daniela dannoso danzare datato davanti davvero debutto decennio deciso declino decollo decreto dedicato definito deforme degno delegare delfino delirio delta demenza denotato dentro deposito derapata derivare deroga descritto deserto desiderio desumere detersivo devoto diametro dicembre diedro difeso diffuso digerire digitale diluvio dinamico dinnanzi dipinto diploma dipolo diradare dire dirotto dirupo disagio discreto disfare disgelo disposto distanza disumano dito divano divelto dividere divorato doblone docente doganale dogma dolce domato domenica dominare dondolo dono dormire dote dottore dovuto dozzina drago druido dubbio dubitare ducale duna duomo duplice duraturo ebano eccesso ecco eclissi economia edera edicola edile editoria educare egemonia egli egoismo egregio elaborato elargire elegante elencato eletto elevare elfico elica elmo elsa eluso emanato emblema emesso emiro emotivo emozione empirico emulo endemico enduro energia enfasi enoteca entrare enzima epatite epilogo episodio epocale eppure equatore erario erba erboso erede eremita erigere ermetico eroe erosivo errante esagono esame esanime esaudire esca esempio esercito esibito esigente esistere esito esofago esortato esoso espanso espresso essenza esso esteso estimare estonia estroso esultare etilico etnico etrusco etto euclideo europa evaso evidenza evitato evoluto evviva fabbrica faccenda fachiro falco famiglia fanale fanfara fango fantasma fare farfalla farinoso farmaco fascia fastoso fasullo faticare fato favoloso febbre fecola fede fegato felpa feltro femmina fendere fenomeno fermento ferro fertile fessura festivo fetta feudo fiaba fiducia fifa figurato filo finanza finestra finire fiore fiscale fisico fiume flacone flamenco flebo flemma florido fluente fluoro fobico focaccia focoso foderato foglio folata folclore folgore fondente fonetico fonia fontana forbito forchetta foresta formica fornaio foro fortezza forzare fosfato fosso fracasso frana frassino fratello freccetta frenata fresco frigo frollino fronde frugale frutta fucilata fucsia fuggente fulmine fulvo fumante fumetto fumoso fune funzione fuoco furbo furgone furore fuso futile gabbiano gaffe galateo gallina galoppo gambero gamma garanzia garbo garofano garzone gasdotto gasolio gastrico gatto gaudio gazebo gazzella geco gelatina gelso gemello gemmato gene genitore gennaio genotipo gergo ghepardo ghiaccio ghisa giallo gilda ginepro giocare gioiello giorno giove girato girone gittata giudizio giurato giusto globulo glutine gnomo gobba golf gomito gommone gonfio gonna governo gracile grado grafico grammo grande grattare gravoso grazia greca gregge grifone grigio grinza grotta gruppo guadagno guaio guanto guardare gufo guidare ibernato icona identico idillio idolo idra idrico idrogeno igiene ignaro ignorato ilare illeso illogico illudere imballo imbevuto imbocco imbuto immane immerso immolato impacco impeto impiego importo impronta inalare inarcare inattivo incanto incendio inchino incisivo incluso incontro incrocio incubo indagine india indole inedito infatti infilare inflitto ingaggio ingegno inglese ingordo ingrosso innesco inodore inoltrare inondato insano insetto insieme insonnia insulina intasato intero intonaco intuito inumidire invalido invece invito iperbole ipnotico ipotesi ippica iride irlanda ironico irrigato irrorare isolato isotopo isterico istituto istrice italia iterare labbro labirinto lacca lacerato lacrima lacuna laddove lago lampo lancetta lanterna lardoso larga laringe lastra latenza latino lattuga lavagna lavoro legale leggero lembo lentezza lenza leone lepre lesivo lessato lesto letterale leva levigato libero lido lievito lilla limatura limitare limpido lineare lingua liquido lira lirica lisca lite litigio livrea locanda lode logica lombare londra longevo loquace lorenzo loto lotteria luce lucidato lumaca luminoso lungo lupo luppolo lusinga lusso lutto macabro macchina macero macinato madama magico maglia magnete magro maiolica malafede malgrado malinteso malsano malto malumore mana mancia mandorla mangiare manifesto mannaro manovra mansarda mantide manubrio mappa maratona marcire maretta marmo marsupio maschera massaia mastino materasso matricola mattone maturo mazurca meandro meccanico mecenate medesimo meditare mega melassa melis melodia meninge meno mensola mercurio merenda merlo meschino mese messere mestolo metallo metodo mettere miagolare mica micelio michele microbo midollo miele migliore milano milite mimosa minerale mini minore mirino mirtillo miscela missiva misto misurare mitezza mitigare mitra mittente mnemonico modello modifica modulo mogano mogio mole molosso monastero monco mondina monetario monile monotono monsone montato monviso mora mordere morsicato mostro motivato motosega motto movenza movimento mozzo mucca mucosa muffa mughetto mugnaio mulatto mulinello multiplo mummia munto muovere murale musa muscolo musica mutevole muto nababbo nafta nanometro narciso narice narrato nascere nastrare naturale nautica naviglio nebulosa necrosi negativo negozio nemmeno neofita neretto nervo nessuno nettuno neutrale neve nevrotico nicchia ninfa nitido nobile nocivo nodo nome nomina nordico normale norvegese nostrano notare notizia notturno novella nucleo nulla numero nuovo nutrire nuvola nuziale oasi obbedire obbligo obelisco oblio obolo obsoleto occasione occhio occidente occorrere occultare ocra oculato odierno odorare offerta offrire offuscato oggetto oggi ognuno olandese olfatto oliato oliva ologramma oltre omaggio ombelico ombra omega omissione ondoso onere onice onnivoro onorevole onta operato opinione opposto oracolo orafo ordine orecchino orefice orfano organico origine orizzonte orma ormeggio ornativo orologio orrendo orribile ortensia ortica orzata orzo osare oscurare osmosi ospedale ospite ossa ossidare ostacolo oste otite otre ottagono ottimo ottobre ovale ovest ovino oviparo ovocito ovunque ovviare ozio pacchetto pace pacifico padella padrone paese paga pagina palazzina palesare pallido palo palude pandoro pannello paolo paonazzo paprica parabola parcella parere pargolo pari parlato parola partire parvenza parziale passivo pasticca patacca patologia pattume pavone peccato pedalare pedonale peggio peloso penare pendice penisola pennuto penombra pensare pentola pepe pepita perbene percorso perdonato perforare pergamena periodo permesso perno perplesso persuaso pertugio pervaso pesatore pesista peso pestifero petalo pettine petulante pezzo piacere pianta piattino piccino picozza piega pietra piffero pigiama pigolio pigro pila pilifero pillola pilota pimpante pineta pinna pinolo pioggia piombo piramide piretico pirite pirolisi pitone pizzico placebo planare plasma platano plenario pochezza poderoso podismo poesia poggiare polenta poligono pollice polmonite polpetta polso poltrona polvere pomice pomodoro ponte popoloso porfido poroso porpora porre portata posa positivo possesso postulato potassio potere pranzo prassi pratica precluso predica prefisso pregiato prelievo premere prenotare preparato presenza pretesto prevalso prima principe privato problema procura produrre profumo progetto prolunga promessa pronome proposta proroga proteso prova prudente prugna prurito psiche pubblico pudica pugilato pugno pulce pulito pulsante puntare pupazzo pupilla puro quadro qualcosa quasi querela quota raccolto raddoppio radicale radunato raffica ragazzo ragione ragno ramarro ramingo ramo randagio rantolare rapato rapina rappreso rasatura raschiato rasente rassegna rastrello rata ravveduto reale recepire recinto recluta recondito recupero reddito redimere regalato registro regola regresso relazione remare remoto renna replica reprimere reputare resa residente responso restauro rete retina retorica rettifica revocato riassunto ribadire ribelle ribrezzo ricarica ricco ricevere riciclato ricordo ricreduto ridicolo ridurre rifasare riflesso riforma rifugio rigare rigettato righello rilassato rilevato rimanere rimbalzo rimedio rimorchio rinascita rincaro rinforzo rinnovo rinomato rinsavito rintocco rinuncia rinvenire riparato ripetuto ripieno riportare ripresa ripulire risata rischio riserva risibile riso rispetto ristoro risultato risvolto ritardo ritegno ritmico ritrovo riunione riva riverso rivincita rivolto rizoma roba robotico robusto roccia roco rodaggio rodere roditore rogito rollio romantico rompere ronzio rosolare rospo rotante rotondo rotula rovescio rubizzo rubrica ruga rullino rumine rumoroso ruolo rupe russare rustico sabato sabbiare sabotato sagoma salasso saldatura salgemma salivare salmone salone saltare saluto salvo sapere sapido saporito saraceno sarcasmo sarto sassoso satellite satira satollo saturno savana savio saziato sbadiglio sbalzo sbancato sbarra sbattere sbavare sbendare sbirciare sbloccato sbocciato sbrinare sbruffone sbuffare scabroso scadenza scala scambiare scandalo scapola scarso scatenare scavato scelto scenico scettro scheda schiena sciarpa scienza scindere scippo sciroppo scivolo sclerare scodella scolpito scomparto sconforto scoprire scorta scossone scozzese scriba scrollare scrutinio scuderia scultore scuola scuro scusare sdebitare sdoganare seccatura secondo sedano seggiola segnalato segregato seguito selciato selettivo sella selvaggio semaforo sembrare seme seminato sempre senso sentire sepolto sequenza serata serbato sereno serio serpente serraglio servire sestina setola settimana sfacelo sfaldare sfamato sfarzoso sfaticato sfera sfida sfilato sfinge sfocato sfoderare sfogo sfoltire sforzato sfratto sfruttato sfuggito sfumare sfuso sgabello sgarbato sgonfiare sgorbio sgrassato sguardo sibilo siccome sierra sigla signore silenzio sillaba simbolo simpatico simulato sinfonia singolo sinistro sino sintesi sinusoide sipario sisma sistole situato slitta slogatura sloveno smarrito smemorato smentito smeraldo smilzo smontare smottato smussato snellire snervato snodo sobbalzo sobrio soccorso sociale sodale soffitto sogno soldato solenne solido sollazzo solo solubile solvente somatico somma sonda sonetto sonnifero sopire soppeso sopra sorgere sorpasso sorriso sorso sorteggio sorvolato sospiro sosta sottile spada spalla spargere spatola spavento spazzola specie spedire spegnere spelatura speranza spessore spettrale spezzato spia spigoloso spillato spinoso spirale splendido sportivo sposo spranga sprecare spronato spruzzo spuntino squillo sradicare srotolato stabile stacco staffa stagnare stampato stantio starnuto stasera statuto stelo steppa sterzo stiletto stima stirpe stivale stizzoso stonato storico strappo stregato stridulo strozzare strutto stuccare stufo stupendo subentro succoso sudore suggerito sugo sultano suonare superbo supporto surgelato surrogato sussurro sutura svagare svedese sveglio svelare svenuto svezia sviluppo svista svizzera svolta svuotare tabacco tabulato tacciare taciturno tale talismano tampone tannino tara tardivo targato tariffa tarpare tartaruga tasto tattico taverna tavolata tazza teca tecnico telefono temerario tempo temuto tendone tenero tensione tentacolo teorema terme terrazzo terzetto tesi tesserato testato tetro tettoia tifare tigella timbro tinto tipico tipografo tiraggio tiro titanio titolo titubante tizio tizzone toccare tollerare tolto tombola tomo tonfo tonsilla topazio topologia toppa torba tornare torrone tortora toscano tossire tostatura totano trabocco trachea trafila tragedia tralcio tramonto transito trapano trarre trasloco trattato trave treccia tremolio trespolo tributo tricheco trifoglio trillo trincea trio tristezza triturato trivella tromba trono troppo trottola trovare truccato tubatura tuffato tulipano tumulto tunisia turbare turchino tuta tutela ubicato uccello uccisore udire uditivo uffa ufficio uguale ulisse ultimato umano umile umorismo uncinetto ungere ungherese unicorno unificato unisono unitario unte uovo upupa uragano urgenza urlo usanza usato uscito usignolo usuraio utensile utilizzo utopia vacante vaccinato vagabondo vagliato valanga valgo valico valletta valoroso valutare valvola vampata vangare vanitoso vano vantaggio vanvera vapore varano varcato variante vasca vedetta vedova veduto vegetale veicolo velcro velina velluto veloce venato vendemmia vento verace verbale vergogna verifica vero verruca verticale vescica vessillo vestale veterano vetrina vetusto viandante vibrante vicenda vichingo vicinanza vidimare vigilia vigneto vigore vile villano vimini vincitore viola vipera virgola virologo virulento viscoso visione vispo vissuto visura vita vitello vittima vivanda vivido viziare voce voga volatile volere volpe voragine vulcano zampogna zanna zappato zattera zavorra zefiro zelante zelo zenzero zerbino zibetto zinco zircone zitto zolla zotico zucchero zufolo zulu zuppa".components(separatedBy: " ") + } + var spanishWords: [String] { + return "ábaco abdomen abeja abierto abogado abono aborto abrazo abrir abuelo abuso acabar academia acceso acción aceite acelga acento aceptar ácido aclarar acné acoger acoso activo acto actriz actuar acudir acuerdo acusar adicto admitir adoptar adorno aduana adulto aéreo afectar afición afinar afirmar ágil agitar agonía agosto agotar agregar agrio agua agudo águila aguja ahogo ahorro aire aislar ajedrez ajeno ajuste alacrán alambre alarma alba álbum alcalde aldea alegre alejar alerta aleta alfiler alga algodón aliado aliento alivio alma almeja almíbar altar alteza altivo alto altura alumno alzar amable amante amapola amargo amasar ámbar ámbito ameno amigo amistad amor amparo amplio ancho anciano ancla andar andén anemia ángulo anillo ánimo anís anotar antena antiguo antojo anual anular anuncio añadir añejo año apagar aparato apetito apio aplicar apodo aporte apoyo aprender aprobar apuesta apuro arado araña arar árbitro árbol arbusto archivo arco arder ardilla arduo área árido aries armonía arnés aroma arpa arpón arreglo arroz arruga arte artista asa asado asalto ascenso asegurar aseo asesor asiento asilo asistir asno asombro áspero astilla astro astuto asumir asunto atajo ataque atar atento ateo ático atleta átomo atraer atroz atún audaz audio auge aula aumento ausente autor aval avance avaro ave avellana avena avestruz avión aviso ayer ayuda ayuno azafrán azar azote azúcar azufre azul baba babor bache bahía baile bajar balanza balcón balde bambú banco banda baño barba barco barniz barro báscula bastón basura batalla batería batir batuta baúl bazar bebé bebida bello besar beso bestia bicho bien bingo blanco bloque blusa boa bobina bobo boca bocina boda bodega boina bola bolero bolsa bomba bondad bonito bono bonsái borde borrar bosque bote botín bóveda bozal bravo brazo brecha breve brillo brinco brisa broca broma bronce brote bruja brusco bruto buceo bucle bueno buey bufanda bufón búho buitre bulto burbuja burla burro buscar butaca buzón caballo cabeza cabina cabra cacao cadáver cadena caer café caída caimán caja cajón cal calamar calcio caldo calidad calle calma calor calvo cama cambio camello camino campo cáncer candil canela canguro canica canto caña cañón caoba caos capaz capitán capote captar capucha cara carbón cárcel careta carga cariño carne carpeta carro carta casa casco casero caspa castor catorce catre caudal causa cazo cebolla ceder cedro celda célebre celoso célula cemento ceniza centro cerca cerdo cereza cero cerrar certeza césped cetro chacal chaleco champú chancla chapa charla chico chiste chivo choque choza chuleta chupar ciclón ciego cielo cien cierto cifra cigarro cima cinco cine cinta ciprés circo ciruela cisne cita ciudad clamor clan claro clase clave cliente clima clínica cobre cocción cochino cocina coco código codo cofre coger cohete cojín cojo cola colcha colegio colgar colina collar colmo columna combate comer comida cómodo compra conde conejo conga conocer consejo contar copa copia corazón corbata corcho cordón corona correr coser cosmos costa cráneo cráter crear crecer creído crema cría crimen cripta crisis cromo crónica croqueta crudo cruz cuadro cuarto cuatro cubo cubrir cuchara cuello cuento cuerda cuesta cueva cuidar culebra culpa culto cumbre cumplir cuna cuneta cuota cupón cúpula curar curioso curso curva cutis dama danza dar dardo dátil deber débil década decir dedo defensa definir dejar delfín delgado delito demora denso dental deporte derecho derrota desayuno deseo desfile desnudo destino desvío detalle detener deuda día diablo diadema diamante diana diario dibujo dictar diente dieta diez difícil digno dilema diluir dinero directo dirigir disco diseño disfraz diva divino doble doce dolor domingo don donar dorado dormir dorso dos dosis dragón droga ducha duda duelo dueño dulce dúo duque durar dureza duro ébano ebrio echar eco ecuador edad edición edificio editor educar efecto eficaz eje ejemplo elefante elegir elemento elevar elipse élite elixir elogio eludir embudo emitir emoción empate empeño empleo empresa enano encargo enchufe encía enemigo enero enfado enfermo engaño enigma enlace enorme enredo ensayo enseñar entero entrar envase envío época equipo erizo escala escena escolar escribir escudo esencia esfera esfuerzo espada espejo espía esposa espuma esquí estar este estilo estufa etapa eterno ética etnia evadir evaluar evento evitar exacto examen exceso excusa exento exigir exilio existir éxito experto explicar exponer extremo fábrica fábula fachada fácil factor faena faja falda fallo falso faltar fama familia famoso faraón farmacia farol farsa fase fatiga fauna favor fax febrero fecha feliz feo feria feroz fértil fervor festín fiable fianza fiar fibra ficción ficha fideo fiebre fiel fiera fiesta figura fijar fijo fila filete filial filtro fin finca fingir finito firma flaco flauta flecha flor flota fluir flujo flúor fobia foca fogata fogón folio folleto fondo forma forro fortuna forzar fosa foto fracaso frágil franja frase fraude freír freno fresa frío frito fruta fuego fuente fuerza fuga fumar función funda furgón furia fusil fútbol futuro gacela gafas gaita gajo gala galería gallo gamba ganar gancho ganga ganso garaje garza gasolina gastar gato gavilán gemelo gemir gen género genio gente geranio gerente germen gesto gigante gimnasio girar giro glaciar globo gloria gol golfo goloso golpe goma gordo gorila gorra gota goteo gozar grada gráfico grano grasa gratis grave grieta grillo gripe gris grito grosor grúa grueso grumo grupo guante guapo guardia guerra guía guiño guion guiso guitarra gusano gustar haber hábil hablar hacer hacha hada hallar hamaca harina haz hazaña hebilla hebra hecho helado helio hembra herir hermano héroe hervir hielo hierro hígado higiene hijo himno historia hocico hogar hoguera hoja hombre hongo honor honra hora hormiga horno hostil hoyo hueco huelga huerta hueso huevo huida huir humano húmedo humilde humo hundir huracán hurto icono ideal idioma ídolo iglesia iglú igual ilegal ilusión imagen imán imitar impar imperio imponer impulso incapaz índice inerte infiel informe ingenio inicio inmenso inmune innato insecto instante interés íntimo intuir inútil invierno ira iris ironía isla islote jabalí jabón jamón jarabe jardín jarra jaula jazmín jefe jeringa jinete jornada joroba joven joya juerga jueves juez jugador jugo juguete juicio junco jungla junio juntar júpiter jurar justo juvenil juzgar kilo koala labio lacio lacra lado ladrón lagarto lágrima laguna laico lamer lámina lámpara lana lancha langosta lanza lápiz largo larva lástima lata látex latir laurel lavar lazo leal lección leche lector leer legión legumbre lejano lengua lento leña león leopardo lesión letal letra leve leyenda libertad libro licor líder lidiar lienzo liga ligero lima límite limón limpio lince lindo línea lingote lino linterna líquido liso lista litera litio litro llaga llama llanto llave llegar llenar llevar llorar llover lluvia lobo loción loco locura lógica logro lombriz lomo lonja lote lucha lucir lugar lujo luna lunes lupa lustro luto luz maceta macho madera madre maduro maestro mafia magia mago maíz maldad maleta malla malo mamá mambo mamut manco mando manejar manga maniquí manjar mano manso manta mañana mapa máquina mar marco marea marfil margen marido mármol marrón martes marzo masa máscara masivo matar materia matiz matriz máximo mayor mazorca mecha medalla medio médula mejilla mejor melena melón memoria menor mensaje mente menú mercado merengue mérito mes mesón meta meter método metro mezcla miedo miel miembro miga mil milagro militar millón mimo mina minero mínimo minuto miope mirar misa miseria misil mismo mitad mito mochila moción moda modelo moho mojar molde moler molino momento momia monarca moneda monja monto moño morada morder moreno morir morro morsa mortal mosca mostrar motivo mover móvil mozo mucho mudar mueble muela muerte muestra mugre mujer mula muleta multa mundo muñeca mural muro músculo museo musgo música muslo nácar nación nadar naipe naranja nariz narrar nasal natal nativo natural náusea naval nave navidad necio néctar negar negocio negro neón nervio neto neutro nevar nevera nicho nido niebla nieto niñez niño nítido nivel nobleza noche nómina noria norma norte nota noticia novato novela novio nube nuca núcleo nudillo nudo nuera nueve nuez nulo número nutria oasis obeso obispo objeto obra obrero observar obtener obvio oca ocaso océano ochenta ocho ocio ocre octavo octubre oculto ocupar ocurrir odiar odio odisea oeste ofensa oferta oficio ofrecer ogro oído oír ojo ola oleada olfato olivo olla olmo olor olvido ombligo onda onza opaco opción ópera opinar oponer optar óptica opuesto oración orador oral órbita orca orden oreja órgano orgía orgullo oriente origen orilla oro orquesta oruga osadía oscuro osezno oso ostra otoño otro oveja óvulo óxido oxígeno oyente ozono pacto padre paella página pago país pájaro palabra palco paleta pálido palma paloma palpar pan panal pánico pantera pañuelo papá papel papilla paquete parar parcela pared parir paro párpado parque párrafo parte pasar paseo pasión paso pasta pata patio patria pausa pauta pavo payaso peatón pecado pecera pecho pedal pedir pegar peine pelar peldaño pelea peligro pellejo pelo peluca pena pensar peñón peón peor pepino pequeño pera percha perder pereza perfil perico perla permiso perro persona pesa pesca pésimo pestaña pétalo petróleo pez pezuña picar pichón pie piedra pierna pieza pijama pilar piloto pimienta pino pintor pinza piña piojo pipa pirata pisar piscina piso pista pitón pizca placa plan plata playa plaza pleito pleno plomo pluma plural pobre poco poder podio poema poesía poeta polen policía pollo polvo pomada pomelo pomo pompa poner porción portal posada poseer posible poste potencia potro pozo prado precoz pregunta premio prensa preso previo primo príncipe prisión privar proa probar proceso producto proeza profesor programa prole promesa pronto propio próximo prueba público puchero pudor pueblo puerta puesto pulga pulir pulmón pulpo pulso puma punto puñal puño pupa pupila puré quedar queja quemar querer queso quieto química quince quitar rábano rabia rabo ración radical raíz rama rampa rancho rango rapaz rápido rapto rasgo raspa rato rayo raza razón reacción realidad rebaño rebote recaer receta rechazo recoger recreo recto recurso red redondo reducir reflejo reforma refrán refugio regalo regir regla regreso rehén reino reír reja relato relevo relieve relleno reloj remar remedio remo rencor rendir renta reparto repetir reposo reptil res rescate resina respeto resto resumen retiro retorno retrato reunir revés revista rey rezar rico riego rienda riesgo rifa rígido rigor rincón riñón río riqueza risa ritmo rito rizo roble roce rociar rodar rodeo rodilla roer rojizo rojo romero romper ron ronco ronda ropa ropero rosa rosca rostro rotar rubí rubor rudo rueda rugir ruido ruina ruleta rulo rumbo rumor ruptura ruta rutina sábado saber sabio sable sacar sagaz sagrado sala saldo salero salir salmón salón salsa salto salud salvar samba sanción sandía sanear sangre sanidad sano santo sapo saque sardina sartén sastre satán sauna saxofón sección seco secreto secta sed seguir seis sello selva semana semilla senda sensor señal señor separar sepia sequía ser serie sermón servir sesenta sesión seta setenta severo sexo sexto sidra siesta siete siglo signo sílaba silbar silencio silla símbolo simio sirena sistema sitio situar sobre socio sodio sol solapa soldado soledad sólido soltar solución sombra sondeo sonido sonoro sonrisa sopa soplar soporte sordo sorpresa sorteo sostén sótano suave subir suceso sudor suegra suelo sueño suerte sufrir sujeto sultán sumar superar suplir suponer supremo sur surco sureño surgir susto sutil tabaco tabique tabla tabú taco tacto tajo talar talco talento talla talón tamaño tambor tango tanque tapa tapete tapia tapón taquilla tarde tarea tarifa tarjeta tarot tarro tarta tatuaje tauro taza tazón teatro techo tecla técnica tejado tejer tejido tela teléfono tema temor templo tenaz tender tener tenis tenso teoría terapia terco término ternura terror tesis tesoro testigo tetera texto tez tibio tiburón tiempo tienda tierra tieso tigre tijera tilde timbre tímido timo tinta tío típico tipo tira tirón titán títere título tiza toalla tobillo tocar tocino todo toga toldo tomar tono tonto topar tope toque tórax torero tormenta torneo toro torpedo torre torso tortuga tos tosco toser tóxico trabajo tractor traer tráfico trago traje tramo trance trato trauma trazar trébol tregua treinta tren trepar tres tribu trigo tripa triste triunfo trofeo trompa tronco tropa trote trozo truco trueno trufa tubería tubo tuerto tumba tumor túnel túnica turbina turismo turno tutor ubicar úlcera umbral unidad unir universo uno untar uña urbano urbe urgente urna usar usuario útil utopía uva vaca vacío vacuna vagar vago vaina vajilla vale válido valle valor válvula vampiro vara variar varón vaso vecino vector vehículo veinte vejez vela velero veloz vena vencer venda veneno vengar venir venta venus ver verano verbo verde vereda verja verso verter vía viaje vibrar vicio víctima vida vídeo vidrio viejo viernes vigor vil villa vinagre vino viñedo violín viral virgo virtud visor víspera vista vitamina viudo vivaz vivero vivir vivo volcán volumen volver voraz votar voto voz vuelo vulgar yacer yate yegua yema yerno yeso yodo yoga yogur zafiro zanja zapato zarza zona zorro zumo zurdo".components(separatedBy: " ") + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP39.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP39.swift new file mode 100755 index 000000000..fdf0bea5f --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP39.swift @@ -0,0 +1,165 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import CryptoSwift + +public enum BIP39Language { + case english + case chinese_simplified + case chinese_traditional + case japanese + case korean + case french + case italian + case spanish + public var words: [String] { + switch self { + case .english: + return englishWords + case .chinese_simplified: + return simplifiedchineseWords + case .chinese_traditional: + return traditionalchineseWords + case .japanese: + return japaneseWords + case .korean: + return koreanWords + case.french: + return frenchWords + case .italian: + return italianWords + case .spanish: + return spanishWords + } + } + public var separator: String { + switch self { + case .japanese: + return "\u{3000}" + default: + return " " + } + } + + init?(language: String) { + switch language { + case "english": + self = .english + case "chinese_simplified": + self = .chinese_simplified + case "chinese_traditional": + self = .chinese_traditional + case "japanese": + self = .japanese + case "korean": + self = .korean + case "french": + self = .french + case "italian": + self = .italian + case "spanish": + self = .spanish + default: + return nil + } + } +} + +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} + let checksum = entropy.sha256() + let checksumBits = entropy.count*8/32 + var fullEntropy = Data() + fullEntropy.append(entropy) + 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} + let index = Int(bits) + guard language.words.count > index else {return nil} + let word = language.words[index] + wordList.append(word) + } + let separator = language.separator + return wordList.joined(separator: separator) + } + + /** + Initializes a new mnemonics set with the provided bitsOfEntropy. + + - Parameters: + - bitsOfEntropy: 128 - 12 words, 192 - 18 words , 256 - 24 words in output. + - language: words language, default english + + - Returns: random 12-24 words, that represent new Mnemonic phrase. + */ + + /// Initializes a new mnemonics set with the provided bitsOfEntropy. + /// - Parameters: + /// - bitsOfEntropy: 128 - 12 words, 192 - 18 words , 256 - 24 words in output. + /// - language: words language, default english + 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 let entropy = Data.randomBytes(length: bitsOfEntropy/8) else {throw AbstractKeystoreError.noEntropyError} + return BIP39.generateMnemonicsFromEntropy(entropy: entropy, language: + language) + + } + + static public func mnemonicsToEntropy(_ mnemonics: String, language: BIP39Language = BIP39Language.english) -> Data? { + let wordList = mnemonics.components(separatedBy: " ") + guard wordList.count >= 12 && wordList.count.isMultiple(of: 4) else {return nil} + var bitString = "" + for word in wordList { +// let idx = language.words.index(of: word) + let idx = language.words.firstIndex(of: word) + if (idx == nil) { + return nil + } + let idxAsInt = language.words.startIndex.distance(to: idx!) + let stringForm = String(UInt16(idxAsInt), radix: 2).leftPadding(toLength: 11, withPad: "0") + bitString.append(stringForm) + } + let stringCount = bitString.count + if !stringCount.isMultiple(of: 33) { + return nil + } + let entropyBits = bitString[0 ..< (bitString.count - bitString.count/33)] + let checksumBits = bitString[(bitString.count - bitString.count/33) ..< bitString.count] + guard let entropy = entropyBits.interpretAsBinaryData() else { + return nil + } + let checksum = String(entropy.sha256().bitsInRange(0, checksumBits.count)!, radix: 2).leftPadding(toLength: checksumBits.count, withPad: "0") + if checksum != checksumBits { + return nil + } + return entropy + } + + static public func seedFromMmemonics(_ mnemonics: String, password: String = "", language: BIP39Language = BIP39Language.english) -> Data? { + let valid = BIP39.mnemonicsToEntropy(mnemonics, language: language) != nil + if (!valid) { + 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.sha512).calculate() else {return nil} +// let seed = Data(bytes:seedArray) + let seed = Data(seedArray) + return seed + } + + static public func seedFromEntropy(_ entropy: Data, password: String = "", language: BIP39Language = BIP39Language.english) -> Data? { + guard let mnemonics = BIP39.generateMnemonicsFromEntropy(entropy: entropy, language: language) else { + return nil + } + return BIP39.seedFromMmemonics(mnemonics, password: password, language: language) + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/EthereumKeystoreV3.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/EthereumKeystoreV3.swift new file mode 100755 index 000000000..775268a74 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/EthereumKeystoreV3.swift @@ -0,0 +1,261 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import CryptoSwift +import Foundation + +public class EthereumKeystoreV3: AbstractKeystore { + // Protocol + public var isHDKeystore: Bool = false + private var address: EthereumAddress? + public var keystoreParams: KeystoreParamsV3? + + + public var addresses: [EthereumAddress]? { + get { + if self.address != nil { + return [self.address!] + } + return nil + } + } + + public func UNSAFE_getPrivateKeyData(password: String, account: EthereumAddress) throws -> Data { + if self.addresses?.count == 1 && account == self.addresses?.last { + guard let privateKey = try? self.getKeyData(password) else { + throw AbstractKeystoreError.invalidPasswordError + } + return privateKey + } + throw AbstractKeystoreError.invalidAccountError + } + + // Class + + public func getAddress() -> EthereumAddress? { + return self.address + } + + // -------------- + + public convenience init?(_ jsonString: String) { + let lowercaseJSON = jsonString.lowercased() + guard let jsonData = lowercaseJSON.data(using: .utf8) else { + return nil + } + self.init(jsonData) + } + + public convenience init?(_ jsonData: Data) { + guard let keystoreParams = try? JSONDecoder().decode(KeystoreParamsV3.self, from: jsonData) else { + return nil + } + self.init(keystoreParams) + } + + public init?(_ keystoreParams: KeystoreParamsV3) { + if (keystoreParams.version != 3) { + return nil + } + if (keystoreParams.crypto.version != nil && keystoreParams.crypto.version != "1") { + return nil + } + self.keystoreParams = keystoreParams + if keystoreParams.address != nil { + self.address = EthereumAddress(keystoreParams.address!.addHexPrefix()) + } else { + return nil + } + } + + public init?(password: String = "web3swift", aesMode: String = "aes-128-cbc") throws { + guard var newPrivateKey = SECP256K1.generatePrivateKey() else { + return nil + } + defer { + Data.zero(&newPrivateKey) + } + try encryptDataToStorage(password, keyData: newPrivateKey, aesMode: aesMode) + } + + public init?(privateKey: Data, password: String = "web3swift", aesMode: String = "aes-128-cbc") throws { + guard privateKey.count == 32 else { + return nil + } + guard SECP256K1.verifyPrivateKey(privateKey: privateKey) else { + return nil + } + try encryptDataToStorage(password, keyData: privateKey, aesMode: aesMode) + } + + fileprivate func encryptDataToStorage(_ password: String, keyData: Data?, dkLen: Int = 32, N: Int = 4096, R: Int = 6, P: Int = 1, aesMode: String = "aes-128-cbc") throws { + if (keyData == nil) { + throw AbstractKeystoreError.encryptionError("Encryption without key data") + } + let saltLen = 32; + guard let saltData = Data.randomBytes(length: saltLen) else { + throw AbstractKeystoreError.noEntropyError + } + guard let derivedKey = scrypt(password: password, salt: saltData, length: dkLen, N: N, R: R, P: P) else { + throw AbstractKeystoreError.keyDerivationError + } + let last16bytes = Data(derivedKey[(derivedKey.count - 16)...(derivedKey.count - 1)]) + let encryptionKey = Data(derivedKey[0...15]) + guard let IV = Data.randomBytes(length: 16) else { + throw AbstractKeystoreError.noEntropyError + } + var aesCipher: AES? + switch aesMode { + case "aes-128-cbc": + aesCipher = try? AES(key: encryptionKey.bytes, blockMode: CBC(iv: IV.bytes), padding: .noPadding) + case "aes-128-ctr": + aesCipher = try? AES(key: encryptionKey.bytes, blockMode: CTR(iv: IV.bytes), padding: .noPadding) + default: + aesCipher = nil + } + if aesCipher == nil { + throw AbstractKeystoreError.aesError + } + guard let encryptedKey = try aesCipher?.encrypt(keyData!.bytes) else { + throw AbstractKeystoreError.aesError + } +// let encryptedKeyData = Data(bytes:encryptedKey) + let encryptedKeyData = Data(encryptedKey) + var dataForMAC = Data() + dataForMAC.append(last16bytes) + dataForMAC.append(encryptedKeyData) + let mac = dataForMAC.sha3(.keccak256) + let kdfparams = KdfParamsV3(salt: saltData.toHexString(), dklen: dkLen, n: N, p: P, r: R, c: nil, prf: nil) + let cipherparams = CipherParamsV3(iv: IV.toHexString()) + let crypto = CryptoParamsV3(ciphertext: encryptedKeyData.toHexString(), cipher: aesMode, cipherparams: cipherparams, kdf: "scrypt", kdfparams: kdfparams, mac: mac.toHexString(), version: nil) + guard let pubKey = Web3.Utils.privateToPublic(keyData!) else { + throw AbstractKeystoreError.keyDerivationError + } + guard let addr = Web3.Utils.publicToAddress(pubKey) else { + throw AbstractKeystoreError.keyDerivationError + } + self.address = addr + let keystoreparams = KeystoreParamsV3(address: addr.address.lowercased(), crypto: crypto, id: UUID().uuidString.lowercased(), version: 3) + self.keystoreParams = keystoreparams + } + + public func regenerate(oldPassword: String, newPassword: String, dkLen: Int = 32, N: Int = 4096, R: Int = 6, P: Int = 1) throws { + var keyData = try self.getKeyData(oldPassword) + if keyData == nil { + throw AbstractKeystoreError.encryptionError("Failed to decrypt a keystore") + } + defer { + Data.zero(&keyData!) + } + try self.encryptDataToStorage(newPassword, keyData: keyData!, aesMode: self.keystoreParams!.crypto.cipher) + } + + fileprivate func getKeyData(_ password: String) throws -> Data? { + guard let keystoreParams = self.keystoreParams else { + return nil + } + guard let saltData = Data.fromHex(keystoreParams.crypto.kdfparams.salt) else { + return nil + } + let derivedLen = keystoreParams.crypto.kdfparams.dklen + var passwordDerivedKey: Data? + switch keystoreParams.crypto.kdf { + case "scrypt": + guard let N = keystoreParams.crypto.kdfparams.n else { + return nil + } + guard let P = keystoreParams.crypto.kdfparams.p else { + return nil + } + guard let R = keystoreParams.crypto.kdfparams.r else { + return nil + } + passwordDerivedKey = scrypt(password: password, salt: saltData, length: derivedLen, N: N, R: R, P: P) + case "pbkdf2": + guard let algo = keystoreParams.crypto.kdfparams.prf else { + return nil + } + var hashVariant: HMAC.Variant?; + switch algo { + case "hmac-sha256": + hashVariant = HMAC.Variant.sha256 + case "hmac-sha384": + hashVariant = HMAC.Variant.sha384 + case "hmac-sha512": + hashVariant = HMAC.Variant.sha512 + default: + hashVariant = nil + } + guard hashVariant != nil else { + return nil + } + guard let c = keystoreParams.crypto.kdfparams.c else { + return nil + } + guard let passData = password.data(using: .utf8) else { + return nil + } + guard let derivedArray = try? PKCS5.PBKDF2(password: passData.bytes, salt: saltData.bytes, iterations: c, keyLength: derivedLen, variant: hashVariant!).calculate() else { + return nil + } +// passwordDerivedKey = Data(bytes:derivedArray) + passwordDerivedKey = Data(derivedArray) + default: + return nil + } + guard let derivedKey = passwordDerivedKey else { + return nil + } + var dataForMAC = Data() + let derivedKeyLast16bytes = Data(derivedKey[(derivedKey.count - 16)...(derivedKey.count - 1)]) + dataForMAC.append(derivedKeyLast16bytes) + guard let cipherText = Data.fromHex(keystoreParams.crypto.ciphertext) else { + return nil + } + if (cipherText.count != 32) { + return nil + } + dataForMAC.append(cipherText) + let mac = dataForMAC.sha3(.keccak256) + guard let calculatedMac = Data.fromHex(keystoreParams.crypto.mac), mac.constantTimeComparisonTo(calculatedMac) else { + return nil + } + let cipher = keystoreParams.crypto.cipher + let decryptionKey = derivedKey[0...15] + guard let IV = Data.fromHex(keystoreParams.crypto.cipherparams.iv) else { + return nil + } + var decryptedPK: Array? + switch cipher { + case "aes-128-ctr": + guard let aesCipher = try? AES(key: decryptionKey.bytes, blockMode: CTR(iv: IV.bytes), padding: .noPadding) else { + return nil + } + decryptedPK = try aesCipher.decrypt(cipherText.bytes) + case "aes-128-cbc": + guard let aesCipher = try? AES(key: decryptionKey.bytes, blockMode: CBC(iv: IV.bytes), padding: .noPadding) else { + return nil + } + decryptedPK = try? aesCipher.decrypt(cipherText.bytes) + default: + return nil + } + guard decryptedPK != nil else { + return nil + } +// return Data(bytes:decryptedPK!) + return Data(decryptedPK!) + } + + public func serialize() throws -> Data? { + guard let params = self.keystoreParams else { + return nil + } + let data = try JSONEncoder().encode(params) + return data + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/IBAN.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/IBAN.swift new file mode 100755 index 000000000..500f9560a --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/IBAN.swift @@ -0,0 +1,138 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +public struct ICAP { + public var asset: String + public var institution: String + public var client: String +} + +public struct IBAN { + public var iban: String + + public var isDirect: Bool { + return self.iban.count == 34 || self.iban.count == 35 + } + + public var isIndirect: Bool { + return self.iban.count == 20 + } + + public var checksum: String { + return self.iban[2..<4]; + } + + public var asset: String { + if (self.isIndirect) { + return self.iban[4..<7] + } else { + return "" + } + } + + public var institution : String { + if (self.isIndirect) { + return self.iban[7..<11] + } else { + return "" + } + } + + public var client : String { + if self.isIndirect { + return self.iban[11...] + } else { + return "" + } + } + + + public func toEthereumAddress() -> EthereumAddress? { + if self.isDirect { + let base36 = self.iban[4...]; + guard let asBigNumber = BigUInt(base36, radix: 36) else {return nil} + let addressString = String(asBigNumber, radix: 16).leftPadding(toLength: 40, withPad: "0") + return EthereumAddress(addressString.addHexPrefix()) + } else { + return nil + } + } + + internal static func decodeToInts(_ iban: String) -> String { +// let codePointForA = "A".asciiValue +// let codePointForZ = "Z".asciiValue + + let uppercasedIBAN = iban.replacingOccurrences(of: " ", with: "").uppercased() + let begining = String(uppercasedIBAN[0..<4]) + let end = String(uppercasedIBAN[4...]) + let IBAN = end + begining + var arrayOfInts = [Int]() + for ch in IBAN { + guard let dataPoint = String(ch).data(using: .ascii) else {return ""} + guard dataPoint.count == 1 else {return ""} + let code = Int(dataPoint[0]) + if code >= 65 && code <= 90 { + arrayOfInts.append(code - 65 + 10) + } else { + arrayOfInts.append(code - 48) + } + } + let joinedString = arrayOfInts.map({ (intCh) -> String in + return String(intCh) + }).joined() + return joinedString + } + + internal static func calculateChecksumMod97(_ preparedString: String) -> Int { + var m = 0 + for digit in preparedString.split(intoChunksOf: 1) { + m = m * 10 + m = m + Int(digit)! + m = m % 97 + } + return m + } + + public static func isValidIBANaddress(_ iban: String, noValidityCheck: Bool = false) -> Bool { + let regex = "^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$" + let matcher = try! NSRegularExpression(pattern: regex, options: NSRegularExpression.Options.dotMatchesLineSeparators) + let match = matcher.matches(in: iban, options: NSRegularExpression.MatchingOptions.anchored, range: iban.fullNSRange) + guard match.count == 1 else { + return false + } + if (iban.hasPrefix("XE") && !noValidityCheck) { + let remainder = calculateChecksumMod97(decodeToInts(iban)) + return remainder == 1 + } else { + return true + } + } + + public init?(_ ibanString: String) { + let matched = ibanString.replacingOccurrences(of: " ", with: "").uppercased() + 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} + let base36EncodedString = String(bigNumber, radix: 36); + 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)); + let checkDigits = "0" + String(98 - remainder) + let twoDigits = checkDigits[checkDigits.count-2.. Data { + guard let keystore = self.walletForAddress(account) else {throw AbstractKeystoreError.invalidAccountError} + return try keystore.UNSAFE_getPrivateKeyData(password: password, account: account) + } + + public static var allManagers = [KeystoreManager]() + public static var defaultManager: KeystoreManager? { + if KeystoreManager.allManagers.count == 0 { + return nil + } + return KeystoreManager.allManagers[0] + } + + public static func managerForPath(_ path: String, scanForHDwallets: Bool = false, suffix: String? = nil) -> KeystoreManager? { + guard let manager = try? KeystoreManager(path, scanForHDwallets: scanForHDwallets, suffix: suffix) else { + return nil + } + return manager + } + + public var path: String + + public func walletForAddress(_ address: EthereumAddress) -> AbstractKeystore? { + for keystore in _keystores { + guard let key = keystore.addresses?.first else { + continue + } + if key == address && key.isValid { + return keystore as AbstractKeystore? + } + } + for keystore in _bip32keystores { + guard let allAddresses = keystore.addresses else { + continue + } + for addr in allAddresses { + if addr == address && addr.isValid { + return keystore as AbstractKeystore? + } + } + } + for keystore in _plainKeystores { + guard let key = keystore.addresses?.first else { + continue + } + if key == address && key.isValid { + return keystore as AbstractKeystore? + } + } + return nil + } + + var _keystores: [EthereumKeystoreV3] = [EthereumKeystoreV3]() + var _bip32keystores: [BIP32Keystore] = [BIP32Keystore]() + var _plainKeystores: [PlainKeystore] = [PlainKeystore]() + + public var keystores: [EthereumKeystoreV3] { + get { + return self._keystores + } + } + + public var bip32keystores: [BIP32Keystore] { + get { + return self._bip32keystores + } + } + + public var plainKeystores: [PlainKeystore] { + get { + return self._plainKeystores + } + } + + public init(_ keystores: [EthereumKeystoreV3]) { + self.isHDKeystore = false + self._keystores = keystores + self.path = "" + } + + public init(_ keystores: [BIP32Keystore]) { + self.isHDKeystore = true + self._bip32keystores = keystores + self.path = "bip32" + } + + public init(_ keystores: [PlainKeystore]) { + self.isHDKeystore = false + self._plainKeystores = keystores + self.path = "plain" + } + + private init?(_ path: String, scanForHDwallets: Bool = false, suffix: String? = nil) throws { + if (scanForHDwallets) { + self.isHDKeystore = true + } + self.path = path + let fileManager = FileManager.default + var isDir: ObjCBool = false + var exists = fileManager.fileExists(atPath: path, isDirectory: &isDir) + if (!exists && !isDir.boolValue) { + try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil) + exists = fileManager.fileExists(atPath: path, isDirectory: &isDir) + } + if (!isDir.boolValue) { + return nil + } + let allFiles = try fileManager.contentsOfDirectory(atPath: path) + if (suffix != nil) { + for file in allFiles where file.hasSuffix(suffix!) { + var filePath = path + if (!path.hasSuffix("/")) { + filePath = path + "/" + } + filePath = filePath + file + guard let content = fileManager.contents(atPath: filePath) else { + continue + } + if (!scanForHDwallets) { + guard let keystore = EthereumKeystoreV3(content) else { + continue + } + _keystores.append(keystore) + } else { + guard let bipkeystore = BIP32Keystore(content) else { + continue + } + _bip32keystores.append(bipkeystore) + } + } + } else { + for file in allFiles { + var filePath = path + if (!path.hasSuffix("/")) { + filePath = path + "/" + } + filePath = filePath + file + guard let content = fileManager.contents(atPath: filePath) else { + continue + } + if (!scanForHDwallets) { + guard let keystore = EthereumKeystoreV3(content) else { + continue + } + _keystores.append(keystore) + } else { + guard let bipkeystore = BIP32Keystore(content) else { + continue + } + _bip32keystores.append(bipkeystore) + } + } + } + + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/KeystoreParams.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/KeystoreParams.swift new file mode 100644 index 000000000..4fd97d10a --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/KeystoreParams.swift @@ -0,0 +1,79 @@ +// +// Created by Petr Korolev on 26.10.2020. +// + +import Foundation + + +public struct KdfParamsV3: Decodable, Encodable { + var salt: String + var dklen: Int + var n: Int? + var p: Int? + var r: Int? + var c: Int? + var prf: String? +} + +public struct CipherParamsV3: Decodable, Encodable { + var iv: String +} + +public struct CryptoParamsV3: Decodable, Encodable { + var ciphertext: String + var cipher: String + var cipherparams: CipherParamsV3 + var kdf: String + var kdfparams: KdfParamsV3 + var mac: String + var version: String? +} + + +public protocol AbstractKeystoreParams: Codable { + var crypto: CryptoParamsV3 { get } + var id: String? { get } + var version: Int { get } + var isHDWallet: Bool { get } + +} + + +public struct KeystoreParamsBIP32: AbstractKeystoreParams { + public var crypto: CryptoParamsV3 + public var id: String? + public var version: Int + public var isHDWallet: Bool + + var pathToAddress: [String: String] + var rootPath: String? + + public init(crypto cr: CryptoParamsV3, id i: String, version ver: Int = 32, rootPath: String? = nil) { + self.crypto = cr + self.id = i + self.version = ver + pathToAddress = [String: String]() + self.rootPath = rootPath + self.isHDWallet = true + } + +} + + +public struct KeystoreParamsV3: AbstractKeystoreParams { + public var crypto: CryptoParamsV3 + public var id: String? + public var version: Int + public var isHDWallet: Bool + + var address: String? + + public init(address ad: String?, crypto cr: CryptoParamsV3, id i: String, version ver: Int) { + address = ad + self.crypto = cr + self.id = i + self.version = ver + self.isHDWallet = false + } + +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/PlainKeystore.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/PlainKeystore.swift new file mode 100755 index 000000000..3937911ec --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/KeystoreManager/PlainKeystore.swift @@ -0,0 +1,37 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +//import secp256k1_swift + +//import EthereumAddress + +public class PlainKeystore: AbstractKeystore { + + public var isHDKeystore: Bool = false + + private var privateKey: Data + + public var addresses: [EthereumAddress]? + + public func UNSAFE_getPrivateKeyData(password: String = "", account: EthereumAddress) throws -> Data { + return self.privateKey + } + + public convenience init?(privateKey: String) { + 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 = Web3.Utils.privateToPublic(privateKey, compressed: false) else {return nil} + guard let address = Web3.Utils.publicToAddress(publicKey) else {return nil} + self.addresses = [address] + self.privateKey = privateKey + } + +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Batching.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Batching.swift new file mode 100755 index 000000000..0d2184580 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Batching.swift @@ -0,0 +1,139 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import PromiseKit + +public class JSONRPCrequestDispatcher { + public var MAX_WAIT_TIME: TimeInterval = 0.1 + public var policy: DispatchPolicy + public var queue: DispatchQueue + + private var provider: Web3Provider + private var lockQueue: DispatchQueue + private var batches: [Batch] = [Batch]() + + public init(provider: Web3Provider, queue: DispatchQueue, policy: DispatchPolicy) { + self.provider = provider + self.queue = queue + self.policy = policy + self.lockQueue = DispatchQueue.init(label: "batchingQueue") // serial simplest queue +// DispatchQueue(label: "batchingQueue", qos: .userInitiated) + self.batches.append(Batch(provider: self.provider, capacity: 32, queue: self.queue, lockQueue: self.lockQueue)) + } + + internal final class Batch { + var capacity: Int + var promisesDict: [UInt64: (promise: Promise, resolver: Resolver)] = [UInt64: (promise: Promise, resolver: Resolver)]() + var requests: [JSONRPCrequest] = [JSONRPCrequest]() + var pendingTrigger: Guarantee? + var provider: Web3Provider + var queue: DispatchQueue + var lockQueue : DispatchQueue + var triggered : Bool = false + func add(_ request: JSONRPCrequest, maxWaitTime: TimeInterval) throws -> Promise { + if self.triggered { + throw Web3Error.nodeError(desc: "Batch is already in flight") + } + let requestID = request.id + let promiseToReturn = Promise.pending() + self.lockQueue.async { + if self.promisesDict[requestID] != nil { + promiseToReturn.resolver.reject(Web3Error.processingError(desc: "Request ID collision")) + } + self.promisesDict[requestID] = promiseToReturn + self.requests.append(request) + if self.pendingTrigger == nil { + self.pendingTrigger = after(seconds: maxWaitTime).done(on: self.queue) { + self.trigger() + } + } + if self.requests.count == self.capacity { + self.trigger() + } + } + return promiseToReturn.promise + } + + func trigger() { + self.lockQueue.async { + if self.triggered { + return + } + self.triggered = true + let requestsBatch = JSONRPCrequestBatch(requests: self.requests) + _ = self.provider.sendAsync(requestsBatch, queue: self.queue).done(on: self.queue){batch in + for response in batch.responses { + if self.promisesDict[UInt64(response.id)] == nil { + for k in self.promisesDict.keys { + self.promisesDict[k]?.resolver.reject(Web3Error.nodeError(desc: "Unknown request id")) + } + return + } + } + for response in batch.responses { + let promise = self.promisesDict[UInt64(response.id)]! + promise.resolver.fulfill(response) + } + }.catch(on:self.queue) {err in + for k in self.promisesDict.keys { + self.promisesDict[k]?.resolver.reject(err) + } + } + } + } + + init (provider: Web3Provider, capacity: Int, queue: DispatchQueue, lockQueue: DispatchQueue) { + self.provider = provider + self.capacity = capacity + self.queue = queue + self.lockQueue = lockQueue + } + } + + func getBatch() throws -> Batch { + guard case .Batch(let batchLength) = self.policy else { + throw Web3Error.inputError(desc: "Trying to batch a request when policy is not to batch") + } + let currentBatch = self.batches.last! + if currentBatch.requests.count.isMultiple(of: batchLength) || currentBatch.triggered { + let newBatch = Batch(provider: self.provider, capacity: Int(batchLength), queue: self.queue, lockQueue: self.lockQueue) + self.batches.append(newBatch) + return newBatch + } + return currentBatch + } + + public enum DispatchPolicy { + case Batch(Int) + case NoBatching + } + + func addToQueue(request: JSONRPCrequest) -> Promise { + switch self.policy { + case .NoBatching: + return self.provider.sendAsync(request, queue: self.queue) + case .Batch(_): + let promise = Promise { + seal in + self.lockQueue.async { + do { + let batch = try self.getBatch() + let internalPromise = try batch.add(request, maxWaitTime: self.MAX_WAIT_TIME) + internalPromise.done(on: self.queue) {resp in + seal.fulfill(resp) + }.catch(on: self.queue){err in + seal.reject(err) + } + } catch { + seal.reject(error) + } + } + } + return promise + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+HttpProvider.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+HttpProvider.swift new file mode 100755 index 000000000..94b1b5a50 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+HttpProvider.swift @@ -0,0 +1,109 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import PromiseKit + +extension Web3HttpProvider { + + static func post(_ request: JSONRPCrequest, providerURL: URL, queue: DispatchQueue = .main, session: URLSession) -> Promise { + let rp = Promise.pending() + var task: URLSessionTask? = nil + queue.async { + do { + let encoder = JSONEncoder() + let requestData = try encoder.encode(request) + var urlRequest = URLRequest(url: providerURL, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData) + urlRequest.httpMethod = "POST" + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + urlRequest.setValue("application/json", forHTTPHeaderField: "Accept") + urlRequest.httpBody = requestData +// let debugValue = try JSONSerialization.jsonObject(with: requestData, options: JSONSerialization.ReadingOptions(rawValue: 0)) +// print(debugValue) +// let debugString = String(data: requestData, encoding: .utf8) +// print(debugString) + task = session.dataTask(with: urlRequest){ (data, response, error) in + guard error == nil else { + rp.resolver.reject(error!) + return + } + guard data != nil else { + rp.resolver.reject(Web3Error.nodeError(desc: "Node response is empty")) + return + } + rp.resolver.fulfill(data!) + } + task?.resume() + } catch { + rp.resolver.reject(error) + } + } + return rp.promise.ensure(on: queue) { + task = nil + }.map(on: queue){ (data: Data) throws -> JSONRPCresponse in + let parsedResponse = try JSONDecoder().decode(JSONRPCresponse.self, from: data) + if parsedResponse.error != nil { + throw Web3Error.nodeError(desc: "Received an error message from node\n" + String(describing: parsedResponse.error!)) + } + return parsedResponse + } + } + + static func post(_ request: JSONRPCrequestBatch, providerURL: URL, queue: DispatchQueue = .main, session: URLSession) -> Promise { + let rp = Promise.pending() + var task: URLSessionTask? = nil + queue.async { + do { + let encoder = JSONEncoder() + let requestData = try encoder.encode(request) + var urlRequest = URLRequest(url: providerURL, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData) + urlRequest.httpMethod = "POST" + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + urlRequest.setValue("application/json", forHTTPHeaderField: "Accept") + urlRequest.httpBody = requestData +// let debugValue = try JSONSerialization.jsonObject(with: requestData, options: JSONSerialization.ReadingOptions(rawValue: 0)) +// print(debugValue) +// let debugString = String(data: requestData, encoding: .utf8) +// print(debugString) + task = session.dataTask(with: urlRequest){ (data, response, error) in + guard error == nil else { + rp.resolver.reject(error!) + return + } + guard data != nil, data!.count != 0 else { + rp.resolver.reject(Web3Error.nodeError(desc: "Node response is empty")) + return + } + rp.resolver.fulfill(data!) + } + task?.resume() + } catch { + rp.resolver.reject(error) + } + } + return rp.promise.ensure(on: queue) { + task = nil + }.map(on: queue){ (data: Data) throws -> JSONRPCresponseBatch in +// let debugValue = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)) +// print(debugValue) + let parsedResponse = try JSONDecoder().decode(JSONRPCresponseBatch.self, from: data) + return parsedResponse + } + } + + public func sendAsync(_ request: JSONRPCrequest, queue: DispatchQueue = .main) -> Promise { + if request.method == nil { + return Promise(error: Web3Error.nodeError(desc: "RPC method is nill")) + } + + return Web3HttpProvider.post(request, providerURL: self.url, queue: queue, session: self.session) + } + + public func sendAsync(_ requests: JSONRPCrequestBatch, queue: DispatchQueue = .main) -> Promise { + return Web3HttpProvider.post(requests, providerURL: self.url, queue: queue, session: self.session) + } +} + diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Contract+GetIndexedEvents.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Contract+GetIndexedEvents.swift new file mode 100755 index 000000000..66391e1fe --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Contract+GetIndexedEvents.swift @@ -0,0 +1,11 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + + +// placeholder + + + diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+Call.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+Call.swift new file mode 100755 index 000000000..ee206b341 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+Call.swift @@ -0,0 +1,36 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import PromiseKit + +extension web3.Eth { + + public func callPromise(_ transaction: EthereumTransaction, transactionOptions: TransactionOptions?) -> Promise{ + let queue = web3.requestDispatcher.queue + do { + guard let request = EthereumTransaction.createRequest(method: .call, transaction: transaction, transactionOptions: transactionOptions) else { + throw Web3Error.processingError(desc: "Transaction is invalid") + } + let rp = web3.dispatch(request) + return rp.map(on: queue ) { response in + guard let value: Data = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } catch { + let returnPromise = Promise.pending() + queue.async { + returnPromise.resolver.reject(error) + } + return returnPromise.promise + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+EstimateGas.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+EstimateGas.swift new file mode 100755 index 000000000..946ef0ecc --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+EstimateGas.swift @@ -0,0 +1,53 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit + +extension web3.Eth { + + public func estimateGasPromise(_ transaction: EthereumTransaction, transactionOptions: TransactionOptions?) -> Promise{ + let queue = web3.requestDispatcher.queue + do { + guard let request = EthereumTransaction.createRequest(method: .estimateGas, transaction: transaction, transactionOptions: transactionOptions) else { + throw Web3Error.processingError(desc: "Transaction is invalid") + } + let rp = web3.dispatch(request) + return rp.map(on: queue ) { response in + guard let value: BigUInt = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + + if let policy = transactionOptions?.gasLimit { + switch policy { + case .automatic: + return value + case .limited(let limitValue): + return limitValue < value ? limitValue: value + case .manual(let exactValue): + return exactValue + case .withMargin: + // MARK: - update value according margin + return value + } + } else { + return value + } + } + } catch { + let returnPromise = Promise.pending() + queue.async { + returnPromise.resolver.reject(error) + } + return returnPromise.promise + } + } +} + diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetAccounts.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetAccounts.swift new file mode 100755 index 000000000..f8ccd0cd1 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetAccounts.swift @@ -0,0 +1,39 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +//import EthereumAddress + +extension web3.Eth { + public func getAccountsPromise() -> Promise<[EthereumAddress]> { + let queue = web3.requestDispatcher.queue + if (self.web3.provider.attachedKeystoreManager != nil) { + let promise = Promise<[EthereumAddress]>.pending() + queue.async { + do { + let allAccounts = try self.web3.wallet.getAccounts() + promise.resolver.fulfill(allAccounts) + } catch { + promise.resolver.reject(error) + } + } + return promise.promise + } + let request = JSONRPCRequestFabric.prepareRequest(.getAccounts, parameters: []) + let rp = web3.dispatch(request) + return rp.map(on: queue ) { response in + guard let value: [EthereumAddress] = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBalance.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBalance.swift new file mode 100755 index 000000000..5bdb60305 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBalance.swift @@ -0,0 +1,31 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import PromiseKit +import BigInt +//import EthereumAddress + +extension web3.Eth { + public func getBalancePromise(address: EthereumAddress, onBlock: String = "latest") -> Promise { + let addr = address.address + return getBalancePromise(address: addr, onBlock: onBlock) + } + public func getBalancePromise(address: String, onBlock: String = "latest") -> Promise { + let request = JSONRPCRequestFabric.prepareRequest(.getBalance, parameters: [address.lowercased(), onBlock]) + let rp = web3.dispatch(request) + let queue = web3.requestDispatcher.queue + return rp.map(on: queue ) { response in + guard let value: BigUInt = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByHash.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByHash.swift new file mode 100755 index 000000000..90710d4fb --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByHash.swift @@ -0,0 +1,31 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit + +extension web3.Eth { + public func getBlockByHashPromise(_ hash: Data, fullTransactions: Bool = false) -> Promise { + let hashString = hash.toHexString().addHexPrefix() + return getBlockByHashPromise(hashString, fullTransactions: fullTransactions) + } + + public func getBlockByHashPromise(_ hash: String, fullTransactions: Bool = false) -> Promise { + let request = JSONRPCRequestFabric.prepareRequest(.getBlockByHash, parameters: [hash, fullTransactions]) + let rp = web3.dispatch(request) + let queue = web3.requestDispatcher.queue + return rp.map(on: queue ) { response in + guard let value: Block = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByNumber.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByNumber.swift new file mode 100755 index 000000000..ac92584e5 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByNumber.swift @@ -0,0 +1,36 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit + +extension web3.Eth { + public func getBlockByNumberPromise(_ number: UInt64, fullTransactions: Bool = false) -> Promise { + let block = String(number, radix: 16).addHexPrefix() + return getBlockByNumberPromise(block, fullTransactions: fullTransactions) + } + + public func getBlockByNumberPromise(_ number: BigUInt, fullTransactions: Bool = false) -> Promise { + let block = String(number, radix: 16).addHexPrefix() + return getBlockByNumberPromise(block, fullTransactions: fullTransactions) + } + + public func getBlockByNumberPromise(_ number: String, fullTransactions: Bool = false) -> Promise { + let request = JSONRPCRequestFabric.prepareRequest(.getBlockByNumber, parameters: [number, fullTransactions]) + let rp = web3.dispatch(request) + let queue = web3.requestDispatcher.queue + return rp.map(on: queue ) { response in + guard let value: Block = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockNumber.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockNumber.swift new file mode 100755 index 000000000..e8bc2676d --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockNumber.swift @@ -0,0 +1,26 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit + +extension web3.Eth { + public func getBlockNumberPromise() -> Promise { + let request = JSONRPCRequestFabric.prepareRequest(.blockNumber, parameters: []) + let rp = web3.dispatch(request) + let queue = web3.requestDispatcher.queue + return rp.map(on: queue ) { response in + guard let value: BigUInt = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetGasPrice.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetGasPrice.swift new file mode 100755 index 000000000..fbda2ace7 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetGasPrice.swift @@ -0,0 +1,26 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit + +extension web3.Eth { + public func getGasPricePromise() -> Promise { + let request = JSONRPCRequestFabric.prepareRequest(.gasPrice, parameters: []) + let rp = web3.dispatch(request) + let queue = web3.requestDispatcher.queue + return rp.map(on: queue ) { response in + guard let value: BigUInt = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionCount.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionCount.swift new file mode 100755 index 000000000..cbd1f4708 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionCount.swift @@ -0,0 +1,32 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +//import EthereumAddress + +extension web3.Eth { + public func getTransactionCountPromise(address: EthereumAddress, onBlock: String = "latest") -> Promise { + let addr = address.address + return getTransactionCountPromise(address: addr, onBlock: onBlock) + } + + public func getTransactionCountPromise(address: String, onBlock: String = "latest") -> Promise { + let request = JSONRPCRequestFabric.prepareRequest(.getTransactionCount, parameters: [address.lowercased(), onBlock]) + let rp = web3.dispatch(request) + let queue = web3.requestDispatcher.queue + return rp.map(on: queue ) { response in + guard let value: BigUInt = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionDetails.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionDetails.swift new file mode 100755 index 000000000..522f04307 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionDetails.swift @@ -0,0 +1,31 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit + +extension web3.Eth { + public func getTransactionDetailsPromise(_ txhash: Data) -> Promise { + let hashString = txhash.toHexString().addHexPrefix() + return self.getTransactionDetailsPromise(hashString) + } + + public func getTransactionDetailsPromise(_ txhash: String) -> Promise { + let request = JSONRPCRequestFabric.prepareRequest(.getTransactionByHash, parameters: [txhash]) + let rp = web3.dispatch(request) + let queue = web3.requestDispatcher.queue + return rp.map(on: queue ) { response in + guard let value: TransactionDetails = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionReceipt.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionReceipt.swift new file mode 100755 index 000000000..517a007ee --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionReceipt.swift @@ -0,0 +1,31 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit + +extension web3.Eth { + public func getTransactionReceiptPromise(_ txhash: Data) -> Promise { + let hashString = txhash.toHexString().addHexPrefix() + return self.getTransactionReceiptPromise(hashString) + } + + public func getTransactionReceiptPromise(_ txhash: String) -> Promise { + let request = JSONRPCRequestFabric.prepareRequest(.getTransactionReceipt, parameters: [txhash]) + let rp = web3.dispatch(request) + let queue = web3.requestDispatcher.queue + return rp.map(on: queue ) { response in + guard let value: TransactionReceipt = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+SendRawTransaction.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+SendRawTransaction.swift new file mode 100755 index 000000000..7aa3b83a6 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+SendRawTransaction.swift @@ -0,0 +1,51 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import PromiseKit + +extension web3.Eth { + public func sendRawTransactionPromise(_ transaction: Data) -> Promise { + guard let deserializedTX = EthereumTransaction.fromRaw(transaction) else { + let promise = Promise.pending() + promise.resolver.reject(Web3Error.processingError(desc: "Serialized TX is invalid")) + return promise.promise + } + return sendRawTransactionPromise(deserializedTX) + } + + public func sendRawTransactionPromise(_ transaction: EthereumTransaction) -> Promise{ +// print(transaction) + let queue = web3.requestDispatcher.queue + do { + guard let request = EthereumTransaction.createRawTransaction(transaction: transaction) else { + throw Web3Error.processingError(desc: "Transaction is invalid") + } + let rp = web3.dispatch(request) + return rp.map(on: queue ) { response in + guard let value: String = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + let result = TransactionSendingResult(transaction: transaction, hash: value) + for hook in self.web3.postSubmissionHooks { + hook.queue.async { + hook.function(result) + } + } + return result + } + } catch { + let returnPromise = Promise.pending() + queue.async { + returnPromise.resolver.reject(error) + } + return returnPromise.promise + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+SendTransaction.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+SendTransaction.swift new file mode 100755 index 000000000..7fe53fd98 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+SendTransaction.swift @@ -0,0 +1,79 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit + +extension web3.Eth { + + public func sendTransactionPromise(_ transaction: EthereumTransaction, transactionOptions: TransactionOptions? = nil, password:String = "web3swift") -> Promise { +// print(transaction) + var assembledTransaction : EthereumTransaction = transaction // .mergedWithOptions(transactionOptions) + let queue = web3.requestDispatcher.queue + do { + var mergedOptions = self.web3.transactionOptions.merge(transactionOptions) + + var forAssemblyPipeline : (EthereumTransaction, TransactionOptions) = (assembledTransaction, mergedOptions) + + for hook in self.web3.preSubmissionHooks { + let prom : Promise = Promise {seal in + hook.queue.async { + let hookResult = hook.function(forAssemblyPipeline) + if hookResult.2 { + forAssemblyPipeline = (hookResult.0, hookResult.1) + } + seal.fulfill(hookResult.2) + } + } + let shouldContinue = try prom.wait() + if !shouldContinue { + throw Web3Error.processingError(desc: "Transaction is canceled by middleware") + } + } + + assembledTransaction = forAssemblyPipeline.0 + mergedOptions = forAssemblyPipeline.1 + + if self.web3.provider.attachedKeystoreManager == nil { + guard let request = EthereumTransaction.createRequest(method: .sendTransaction, transaction: assembledTransaction, transactionOptions: mergedOptions) else + { + throw Web3Error.processingError(desc: "Failed to create a request to send transaction") + } + return self.web3.dispatch(request).map(on: queue) {response in + guard let value: String = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + let result = TransactionSendingResult(transaction: assembledTransaction, hash: value) + for hook in self.web3.postSubmissionHooks { + hook.queue.async { + hook.function(result) + } + } + return result + } + } + guard let from = mergedOptions.from else { + throw Web3Error.inputError(desc: "No 'from' field provided") + } + do { + try Web3Signer.signTX(transaction: &assembledTransaction, keystore: self.web3.provider.attachedKeystoreManager!, account: from, password: password) + } catch { + throw Web3Error.inputError(desc: "Failed to locally sign a transaction") + } + return self.web3.eth.sendRawTransactionPromise(assembledTransaction) + } catch { + let returnPromise = Promise.pending() + queue.async { + returnPromise.resolver.reject(error) + } + return returnPromise.promise + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+CreateAccount.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+CreateAccount.swift new file mode 100755 index 000000000..e5e83d556 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+CreateAccount.swift @@ -0,0 +1,37 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +//import EthereumAddress + +extension web3.Personal { + public func createAccountPromise(password:String = "web3swift") -> Promise { + let queue = web3.requestDispatcher.queue + do { + if self.web3.provider.attachedKeystoreManager == nil { + let request = JSONRPCRequestFabric.prepareRequest(.createAccount, parameters: [password]) + return self.web3.dispatch(request).map(on: queue) {response in + guard let value: EthereumAddress = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } + throw Web3Error.inputError(desc: "Creating account in a local keystore with this method is not supported") + } catch { + let returnPromise = Promise.pending() + queue.async { + returnPromise.resolver.reject(error) + } + return returnPromise.promise + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+Sign.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+Sign.swift new file mode 100755 index 000000000..bf71b10c1 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+Sign.swift @@ -0,0 +1,44 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +//import EthereumAddress + +extension web3.Personal { + + public func signPersonalMessagePromise(message: Data, from: EthereumAddress, password:String = "web3swift") -> Promise { + let queue = web3.requestDispatcher.queue + do { + if self.web3.provider.attachedKeystoreManager == nil { + let hexData = message.toHexString().addHexPrefix() + let request = JSONRPCRequestFabric.prepareRequest(.personalSign, parameters: [from.address.lowercased(), hexData]) + return self.web3.dispatch(request).map(on: queue) {response in + guard let value: Data = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } + guard let signature = try Web3Signer.signPersonalMessage(message, keystore: self.web3.provider.attachedKeystoreManager!, account: from, password: password) else { throw Web3Error.inputError(desc: "Failed to locally sign a message") } + let returnPromise = Promise.pending() + queue.async { + returnPromise.resolver.fulfill(signature) + } + return returnPromise.promise + } catch { + let returnPromise = Promise.pending() + queue.async { + returnPromise.resolver.reject(error) + } + return returnPromise.promise + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+UnlockAccount.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+UnlockAccount.swift new file mode 100755 index 000000000..62512f6d4 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+UnlockAccount.swift @@ -0,0 +1,43 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +//import EthereumAddress + +extension web3.Personal { + public func unlockAccountPromise(account: EthereumAddress, password:String = "web3swift", seconds: UInt64 = 300) -> Promise { + let addr = account.address + return unlockAccountPromise(account: addr, password: password, seconds: seconds) + } + + + public func unlockAccountPromise(account: String, password:String = "web3swift", seconds: UInt64 = 300) -> Promise { + let queue = web3.requestDispatcher.queue + do { + if self.web3.provider.attachedKeystoreManager == nil { + let request = JSONRPCRequestFabric.prepareRequest(.unlockAccount, parameters: [account.lowercased(), password, seconds]) + return self.web3.dispatch(request).map(on: queue) {response in + guard let value: Bool = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } + throw Web3Error.inputError(desc: "Can not unlock a local keystore") + } catch { + let returnPromise = Promise.pending() + queue.async { + returnPromise.resolver.reject(error) + } + return returnPromise.promise + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+TxPool.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+TxPool.swift new file mode 100755 index 000000000..996fae706 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+TxPool.swift @@ -0,0 +1,56 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit + +extension web3.TxPool { + public func getInspectPromise() -> Promise<[String:[String:[String:String]]]> { + let request = JSONRPCRequestFabric.prepareRequest(.getTxPoolInspect, parameters: []) + let rp = web3.dispatch(request) + let queue = web3.requestDispatcher.queue + return rp.map(on: queue ) { response in + guard let value: [String:[String:[String:String]]] = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } + + public func getStatusPromise() -> Promise { + let request = JSONRPCRequestFabric.prepareRequest(.getTxPoolStatus, parameters: []) + let rp = web3.dispatch(request) + let queue = web3.requestDispatcher.queue + return rp.map(on: queue ) { response in + guard let value: TxPoolStatus = response.result as? TxPoolStatus else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } + + public func getContentPromise() -> Promise { + let request = JSONRPCRequestFabric.prepareRequest(.getTxPoolContent, parameters: []) + let rp = web3.dispatch(request) + let queue = web3.requestDispatcher.queue + return rp.map(on: queue ) { response in + guard let value: TxPoolContent = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Invalid value from Ethereum node") + } + return value + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/SwiftRLP/RLP.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/SwiftRLP/RLP.swift new file mode 100755 index 000000000..e9f904ad6 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/SwiftRLP/RLP.swift @@ -0,0 +1,320 @@ +// +// RLP.swift +// SwiftRLP +// +// Created by Alex Vlasov on 04/10/2018. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt + +//protocol ArrayType {} +//extension Array : ArrayType {} +public struct RLP { + enum Error: Swift.Error { + case encodingError + case decodingError + } + + static var length56 = BigUInt(UInt(56)) + static var lengthMax = (BigUInt(UInt(1)) << 256) + + internal static func encode(_ element: AnyObject) -> Data? { + if let string = element as? String { + return encode(string) + + } else if let data = element as? Data { + return encode(data) + } + else if let biguint = element as? BigUInt { + return encode(biguint) + } + return nil; + } + + internal static func encode(_ string: String) -> Data? { + if let hexData = Data.fromHex(string) { + return encode(hexData) + } + 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} + let uint = UInt(number) + return encode(uint) + } + + internal static func encode(_ number: UInt) -> Data? { + let biguint = BigUInt(number) + return encode(biguint) + } + + internal static func encode(_ number: BigUInt) -> Data? { + let encoded = number.serialize() + return encode(encoded) + } + + internal static func encode(_ data: Data) -> Data? { + if (data.count == 1 && data.bytes[0] < UInt8(0x80)) { + return data + } else { + guard let length = encodeLength(data.count, offset: UInt8(0x80)) else {return nil} + var encoded = Data() + encoded.append(length) + encoded.append(data) + return encoded + } + } + + internal static func encodeLength(_ length: Int, offset: UInt8) -> Data? { + if (length < 0) { + return nil; + } + let bigintLength = BigUInt(UInt(length)) + return encodeLength(bigintLength, offset: offset) + } + + 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} + 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} + let lengthPrefix = prefix + offset + UInt8(55) + var encoded = Data([lengthPrefix]) + encoded.append(encodedLength) + return encoded + } + return nil + } + + internal static func lengthToBinary(_ length: BigUInt) -> UInt8? { + if (length == 0) { + return UInt8(0) + } + let divisor = BigUInt(256) + var encoded = Data() + guard let prefix = lengthToBinary(length/divisor) else {return nil} + let suffix = length % divisor + + var prefixData = Data([prefix]) + if (prefix == UInt8(0)) { + prefixData = Data() + } + let suffixData = suffix.serialize() + + encoded.append(prefixData) + encoded.append(suffixData) + guard encoded.count == 1 else {return nil} + return encoded.bytes[0] + } + + public static func encode(_ elements: Array) -> Data? { + var encodedData = Data() + for e in elements { + if let encoded = encode(e) { + encodedData.append(encoded) + } else { + guard let asArray = e as? Array 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} + if (encodedLength != Data()) { + encodedLength.append(encodedData) + } + return encodedLength + } + + public static func decode(_ raw: String) -> RLPItem? { + guard let rawData = Data.fromHex(raw) else {return nil} + return decode(rawData) + } + + public static func decode(_ raw: Data) -> RLPItem? { + if raw.count == 0 { + return RLPItem.noItem + } + var outputArray = [RLPItem]() + 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} + switch type { + case .empty: + break + case .data: + 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} + switch inside.content { + case .data(_): + return nil + default: + outputArray.append(inside) + } + } + guard let tail = try? slice(data: bytesToParse, start: offset + dataLength) else {return nil} + bytesToParse = tail + } + return RLPItem.init(content: .list(outputArray, 0, Data(raw))) + } + + public struct RLPItem { + + enum UnderlyingType { + case empty + case data + case list + } + + public enum RLPContent { + case noItem + case data(Data) + indirect case list([RLPItem], Int, Data) + } + + public var content: RLPContent + + public var isData: Bool { + switch self.content { + case .noItem: + return false + case .data(_): + return true + case .list(_, _, _): + return false + } + } + + public var isList: Bool { + switch self.content { + case .noItem: + return false + case .data(_): + return false + case .list(_,_,_): + return true + } + } + public var count: Int? { + switch self.content { + case .noItem: + return nil + case .data(_): + return nil + case .list(let list, _, _): + return list.count + } + } + // public var hasNext: Bool { + // switch self.content { + // case .noItem: + // return false + // case .data(_): + // return false + // case .list(let list, let counter, _): + // return list.count > counter + // } + // } + + public subscript(index: Int) -> RLPItem? { + get { + // guard self.hasNext else {return nil} + guard case .list(let list, _, _) = self.content else {return nil} + let item = list[index] + return item + } + } + + public var data: Data? { + return self.getData() + } + + public func getData() -> Data? { + if self.isList { + guard case .list(_, _, let rawContent) = self.content else {return nil} + return rawContent + } + guard case .data(let data) = self.content else {return nil} + return data + } + + public static var noItem: RLPItem { + return RLPItem.init(content: .noItem) + } + } + + internal static func decodeLength(_ input: Data) -> (offset: BigUInt?, length: BigUInt?, type: RLPItem.UnderlyingType?) { + do { + let length = BigUInt(input.count) + if (length == BigUInt(0)) { + return (0, 0, .empty) + } + let prefixByte = input[0] + if prefixByte <= 0x7f { + return (BigUInt(0), BigUInt(1), .data) + }else if prefixByte <= 0xb7 && length > BigUInt(prefixByte - 0x80) { + let dataLength = BigUInt(prefixByte - 0x80) + return (BigUInt(1), dataLength, .data) + } else if try prefixByte <= 0xbf && length > BigUInt(prefixByte - 0xb7) && length > BigUInt(prefixByte - 0xb7) + toBigUInt(slice(data: input, offset: BigUInt(1), length: BigUInt(prefixByte - 0xb7))) { + let lengthOfLength = BigUInt(prefixByte - 0xb7) + let dataLength = try toBigUInt(slice(data: input, offset: BigUInt(1), length: BigUInt(prefixByte - 0xb7))) + return (1 + lengthOfLength, dataLength, .data) + } else if prefixByte <= 0xf7 && length > BigUInt(prefixByte - 0xc0) { + let listLen = BigUInt(prefixByte - 0xc0) + return (1, listLen, .list) + } else if try prefixByte <= 0xff && length > BigUInt(prefixByte - 0xf7) && length > BigUInt(prefixByte - 0xf7) + toBigUInt(slice(data: input, offset: BigUInt(1), length: BigUInt(prefixByte - 0xf7))) { + let lengthOfListLength = BigUInt(prefixByte - 0xf7) + let listLength = try toBigUInt(slice(data: input, offset: BigUInt(1), length: BigUInt(prefixByte - 0xf7))) + return (1 + lengthOfListLength, listLength, .list) + } else { + return (nil, nil, nil) + } + } catch { + return (nil, nil, nil) + } + } + + internal static func slice(data: Data, offset: BigUInt, length: BigUInt) throws -> Data { + if BigUInt(data.count) < offset + length {throw Error.encodingError} + let slice = data[UInt64(offset) ..< UInt64(offset + length)] + return Data(slice) + } + + internal static func slice(data: Data, start: BigUInt) throws -> Data { + if BigUInt(data.count) < start {throw Error.encodingError} + let slice = data[UInt64(start) ..< UInt64(data.count)] + return Data(slice) + } + + internal static func toBigUInt(_ raw: Data) throws -> BigUInt { + if raw.count == 0 { + throw Error.encodingError + } else if raw.count == 1 { + return BigUInt.init(raw) + } else { + let slice = raw[0 ..< raw.count - 1] + return try BigUInt(raw[raw.count-1]) + toBigUInt(slice)*256 + } + } +} + +fileprivate extension Data { + + var bytes: Array { + return Array(self) + } +} + diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1155/Web3+ERC1155.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1155/Web3+ERC1155.swift new file mode 100644 index 000000000..2daebddbe --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1155/Web3+ERC1155.swift @@ -0,0 +1,147 @@ +// +// Web3+ERC1155.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 20/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +//import EthereumAddress + +//Multi Token Standard +protocol IERC1155: IERC165 { + + func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, id: BigUInt, value: BigUInt, data: [UInt8]) throws -> WriteTransaction + + func safeBatchTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, ids: [BigUInt], values: [BigUInt], data: [UInt8]) throws -> WriteTransaction + + func balanceOf(account: EthereumAddress, id: BigUInt) throws -> BigUInt + + func setApprovalForAll(from: EthereumAddress, operator user: EthereumAddress, approved: Bool, scope: Data) throws -> WriteTransaction + + func isApprovedForAll(owner: EthereumAddress, operator user: EthereumAddress, scope: Data) throws -> Bool +} + +protocol IERC1155Metadata { + func uri(id: BigUInt) throws -> String + func name(id: BigUInt) throws -> String +} + +public class ERC1155: IERC1155 { + + private var _tokenId: BigUInt? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc1155ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var tokenId: BigUInt { + self.readProperties() + if self._tokenId != nil { + return self._tokenId! + } + return 0 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + + guard let tokenIdPromise = contract.read("id", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [tokenIdPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let tokenIdResult) = resolvedPromises[0] else {return} + guard let tokenId = tokenIdResult["0"] as? BigUInt else {return} + self._tokenId = tokenId + + self._hasReadProperties = true + }.wait() + } + + func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, id: BigUInt, value: BigUInt, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("safeTransferFrom", parameters: [originalOwner, to, id, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func safeBatchTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, ids: [BigUInt], values: [BigUInt], data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("safeBatchTransferFrom", parameters: [originalOwner, to, ids, values, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func balanceOf(account: EthereumAddress, id: BigUInt) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account, id] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + + func setApprovalForAll(from: EthereumAddress, operator user: EthereumAddress, approved: Bool, scope: Data) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("setApprovalForAll", parameters: [user, approved, scope] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func isApprovedForAll(owner: EthereumAddress, operator user: EthereumAddress, scope: Data) throws -> Bool { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.callOnBlock = .latest + let result = try contract.read("isApprovedForAll", parameters: [owner, user, scope] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + + func supportsInterface(interfaceID: String) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + transactionOptions.gasLimit = .manual(30000) + let result = try contract.read("supportsInterface", parameters: [interfaceID] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1376/Web3+ERC1376.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1376/Web3+ERC1376.swift new file mode 100644 index 000000000..7e1c6b943 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1376/Web3+ERC1376.swift @@ -0,0 +1,502 @@ +// +// Web3+ERC1376.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 20/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress +import PromiseKit + +public enum IERC1376DelegateMode: UInt { + case PublicMsgSender = 0 + case PublicTxOrigin = 1 + case PrivateMsgSender = 2 + case PrivateTxOrigin = 3 +} + +public struct DirectDebitInfo { + let amount: BigUInt + let startTime: BigUInt + let interval: BigUInt +} + +public struct DirectDebit { + let info: DirectDebitInfo + let epoch: BigUInt +} + +extension DirectDebit: Hashable { +} + +extension DirectDebitInfo: Hashable { +} + +//Service-Friendly Token Standard +protocol IERC1376: IERC20 { + func approve(from: EthereumAddress, spender: EthereumAddress, expectedValue: String, newValue: String) throws -> WriteTransaction + func increaseAllowance(from: EthereumAddress, spender: EthereumAddress, value: String) throws -> WriteTransaction + func decreaseAllowance(from: EthereumAddress, spender: EthereumAddress, value: String, strict: Bool) throws -> WriteTransaction + func setERC20ApproveChecking(from: EthereumAddress, approveChecking: Bool) throws -> WriteTransaction + + func spendableAllowance(owner: EthereumAddress, spender: EthereumAddress) throws -> BigUInt + func transfer(from: EthereumAddress, data: String) throws -> WriteTransaction + func transferAndCall(from: EthereumAddress, to: EthereumAddress, value: String, data: [UInt8]) throws -> WriteTransaction + + func nonceOf(owner: EthereumAddress) throws -> BigUInt + func increaseNonce(from: EthereumAddress) throws -> WriteTransaction + func delegateTransferAndCall(from: EthereumAddress, + nonce: BigUInt, + fee: BigUInt, + gasAmount: BigUInt, + to: EthereumAddress, + value: String, + data: [UInt8], + mode: IERC1376DelegateMode, + v: UInt8, + r: Data, + s: Data) throws -> WriteTransaction + + func directDebit(debtor: EthereumAddress, receiver: EthereumAddress) throws -> DirectDebit + func setupDirectDebit(from: EthereumAddress, receiver: EthereumAddress, info: DirectDebitInfo) throws -> WriteTransaction + func terminateDirectDebit(from: EthereumAddress, receiver: EthereumAddress) throws -> WriteTransaction + func withdrawDirectDebit(from: EthereumAddress, debtor: EthereumAddress) throws -> WriteTransaction + func withdrawDirectDebit(from: EthereumAddress, debtors: [EthereumAddress], strict: Bool) throws -> WriteTransaction +} + +public class ERC1376: IERC1376 { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc1376ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 255 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("allowance", parameters: [originalOwner, delegate] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(newAmount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("setAllowance", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func approve(from: EthereumAddress, spender: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + + func approve(from: EthereumAddress, spender: EthereumAddress, expectedValue: String, newValue: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 eValue = Web3.Utils.parseToBigUInt(expectedValue, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + guard let nValue = Web3.Utils.parseToBigUInt(newValue, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, eValue, nValue] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func increaseAllowance(from: EthereumAddress, spender: EthereumAddress, value: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 amount = Web3.Utils.parseToBigUInt(value, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("increaseAllowance", parameters: [spender, amount] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func decreaseAllowance(from: EthereumAddress, spender: EthereumAddress, value: String, strict: Bool) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 amount = Web3.Utils.parseToBigUInt(value, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("decreaseAllowance", parameters: [spender, amount, strict] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func setERC20ApproveChecking(from: EthereumAddress, approveChecking: Bool) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("setERC20ApproveChecking", parameters: [approveChecking] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func spendableAllowance(owner: EthereumAddress, spender: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("spendableAllowance", parameters: [owner, spender] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + + func transfer(from: EthereumAddress, data: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(data, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func transferAndCall(from: EthereumAddress, to: EthereumAddress, value: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 amount = Web3.Utils.parseToBigUInt(value, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transferAndCall", parameters: [to, amount, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func nonceOf(owner: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("nonceOf", parameters: [owner] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + + func increaseNonce(from: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + let tx = contract.write("increaseNonce", parameters: [] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func delegateTransferAndCall(from: EthereumAddress, nonce: BigUInt, fee: BigUInt, gasAmount: BigUInt, to: EthereumAddress, value: String, data: [UInt8], mode: IERC1376DelegateMode, v: UInt8, r: Data, s: Data) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 amount = Web3.Utils.parseToBigUInt(value, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let modeValue = mode.rawValue + + let tx = contract.write("delegateTransferAndCall", parameters: [nonce, fee, gasAmount, to, amount, data, modeValue, v, r, s] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func directDebit(debtor: EthereumAddress, receiver: EthereumAddress) throws -> DirectDebit { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("directDebit", parameters: [debtor, receiver] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + guard let res = result["0"] as? DirectDebit else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + return res + } + + func setupDirectDebit(from: EthereumAddress, receiver: EthereumAddress, info: DirectDebitInfo) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("setupDirectDebit", parameters: [receiver, info] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func terminateDirectDebit(from: EthereumAddress, receiver: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("terminateDirectDebit", parameters: [receiver] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func withdrawDirectDebit(from: EthereumAddress, debtor: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("withdrawDirectDebit", parameters: [debtor] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func withdrawDirectDebit(from: EthereumAddress, debtors: [EthereumAddress], strict: Bool) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("withdrawDirectDebit", parameters: [debtors, strict] as [AnyObject], transactionOptions: basicOptions)! + return tx + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1400/Web3+ERC1400.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1400/Web3+ERC1400.swift new file mode 100644 index 000000000..8db216c47 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1400/Web3+ERC1400.swift @@ -0,0 +1,931 @@ +// +// Web3+ERC1400.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 14/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// +import Foundation +import BigInt +//import EthereumAddress +import PromiseKit + +//Security Token Standard +protocol IERC1400: IERC20 { + + // Document Management + func getDocument(name: Data) throws -> (String, Data) + func setDocument(from: EthereumAddress, name: Data, uri: String, documentHash: Data) throws -> WriteTransaction + + // Token Information + func balanceOfByPartition(partition: Data, tokenHolder: EthereumAddress) throws -> BigUInt + func partitionsOf(tokenHolder: EthereumAddress) throws -> [Data] + + // Transfers + func transferWithData(from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + func transferFromWithData(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + + // Partition Token Transfers + func transferByPartition(partition: Data, from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + func operatorTransferByPartition(partition: Data, from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction + + // Controller Operation + func isControllable() throws -> Bool + func controllerTransfer(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction + func controllerRedeem(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction + + // Operator Management + func authorizeOperator(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction + func revokeOperator(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction + func authorizeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) throws -> WriteTransaction + func revokeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) throws -> WriteTransaction + + // Operator Information + func isOperator(operator user: EthereumAddress, tokenHolder: EthereumAddress) throws -> Bool + func isOperatorForPartition(partition: Data, operator user: EthereumAddress, tokenHolder: EthereumAddress) throws -> Bool + + // Token Issuance + func isIssuable() throws -> Bool + func issue(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + func issueByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + + // Token Redemption + func redeem(from: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + func redeemFrom(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + func redeemByPartition(from: EthereumAddress, partition: Data, amount: String, data: [UInt8]) throws -> WriteTransaction + func operatorRedeemByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, operatorData: [UInt8]) throws -> WriteTransaction + + // Transfer Validity + func canTransfer(to: EthereumAddress, amount: String, data: [UInt8]) throws -> ([UInt8], Data) + func canTransferFrom(originalOwner: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) throws -> ([UInt8], Data) + func canTransferByPartition(originalOwner: EthereumAddress, to: EthereumAddress, partition: Data, amount: String, data: [UInt8]) throws -> ([UInt8], Data, Data) +} + +// This namespace contains functions to work with ERC1400 tokens. +// variables are lazyly evaluated or global token information (name, ticker, total supply) +// can be imperatively read and saved +public class ERC1400: IERC1400 { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc1400ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 255 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("allowance", parameters: [originalOwner, delegate] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(newAmount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("setAllowance", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + //ERC1400 methods + public func getDocument(name: Data) throws -> (String, Data) { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("getDocument", parameters: [name] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("setDocument", parameters: [name, uri, documentHash] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func balanceOfByPartition(partition: Data, tokenHolder: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOfByPartition", parameters: [partition, tokenHolder] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> [Data] { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("partitionsOf", parameters: [tokenHolder] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferWithData", parameters: [to, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFromWithData(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFromWithData", parameters: [originalOwner, to, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferByPartition(partition: Data, from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferByPartition", parameters: [partition, to, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func operatorTransferByPartition(partition: Data, from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("operatorTransferByPartition", parameters: [partition, originalOwner, to, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func isControllable() throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("isControllable", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("controllerTransfer", parameters: [originalOwner, to, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func controllerRedeem(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("controllerRedeem", parameters: [tokenHolder, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func authorizeOperator(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("authorizeOperator", parameters: [user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func revokeOperator(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("revokeOperator", parameters: [user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func authorizeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("authorizeOperatorByPartition", parameters: [partition, user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func revokeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("revokeOperatorByPartition", parameters: [partition, user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func isOperator(operator user: EthereumAddress, tokenHolder: EthereumAddress) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("isOperator", parameters: [user, tokenHolder] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("isOperatorForPartition", parameters: [partition, user, tokenHolder] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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() throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("isIssuable", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("issue", parameters: [tokenHolder, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func issueByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("issueByPartition", parameters: [partition, tokenHolder, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func redeem(from: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("redeem", parameters: [value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func redeemFrom(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("redeemFrom", parameters: [tokenHolder, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func redeemByPartition(from: EthereumAddress, partition: Data, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("redeemByPartition", parameters: [partition, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func operatorRedeemByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("operatorRedeemByPartition", parameters: [partition, tokenHolder, value, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func canTransfer(to: EthereumAddress, amount: String, data: [UInt8]) throws -> ([UInt8], Data) { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: transactionOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let result = try contract.read("canTransfer", parameters: [to, value, data] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> ([UInt8], Data) { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: transactionOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let result = try contract.read("canTransfer", parameters: [originalOwner, to, value, data] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> ([UInt8], Data, Data) { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: transactionOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let result = try contract.read("canTransfer", parameters: [originalOwner, to, partition, value, data] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } +} + +extension ERC1400: IERC777 { + public func canImplementInterfaceForAddress(interfaceHash: Data, addr: EthereumAddress) throws -> Data { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("canImplementInterfaceForAddress", parameters: [interfaceHash, addr] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> EthereumAddress { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("getInterfaceImplementer", parameters: [addr, interfaceHash] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("setInterfaceImplementer", parameters: [addr, interfaceHash, implementer] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setManager(from: EthereumAddress, addr: EthereumAddress, newManager: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("setManager", parameters: [addr, newManager] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func interfaceHash(interfaceName: String) throws -> Data { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("interfaceHash", parameters: [interfaceName] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("updateERC165Cache", parameters: [contract, interfaceId] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func supportsInterface(interfaceID: String) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + transactionOptions.gasLimit = .manual(30000) + let result = try contract.read("supportsInterface", parameters: [interfaceID] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("granularity", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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() throws -> [EthereumAddress] { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("defaultOperators", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + let tx = contract.write("authorizeOperator", parameters: [user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func revoke(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + let tx = contract.write("revokeOperator", parameters: [user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func isOperatorFor(operator user: EthereumAddress, tokenHolder: EthereumAddress) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("isOperatorFor", parameters: [user, tokenHolder] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("send", parameters: [to, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func operatorSend(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("operatorSend", parameters: [originalOwner, to, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func burn(from: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("burn", parameters: [value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func operatorBurn(from: EthereumAddress, amount: String, originalOwner: EthereumAddress, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("burn", parameters: [originalOwner, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1410/Web3+ERC1410.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1410/Web3+ERC1410.swift new file mode 100644 index 000000000..836dcdf69 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1410/Web3+ERC1410.swift @@ -0,0 +1,664 @@ +// +// Web3+ERC1410.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 19/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress +import PromiseKit + +//Partially Fungible Token Standard +protocol IERC1410: IERC20 { + + // Token Information + func getBalance(account: EthereumAddress) throws -> BigUInt + func balanceOfByPartition(partition: Data, tokenHolder: EthereumAddress) throws -> BigUInt + func partitionsOf(tokenHolder: EthereumAddress) throws -> [Data] + func totalSupply() throws -> BigUInt + + // Token Transfers + func transferByPartition(partition: Data, from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + func operatorTransferByPartition(partition: Data, from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction + func canTransferByPartition(originalOwner: EthereumAddress, to: EthereumAddress, partition: Data, amount: String, data: [UInt8]) throws -> ([UInt8], Data, Data) + + // Operator Information + func isOperator(operator user: EthereumAddress, tokenHolder: EthereumAddress) throws -> Bool + func isOperatorForPartition(partition: Data, operator user: EthereumAddress, tokenHolder: EthereumAddress) throws -> Bool + + // Operator Management + func authorizeOperator(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction + func revokeOperator(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction + func authorizeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) throws -> WriteTransaction + func revokeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) throws -> WriteTransaction + + // Issuance / Redemption + func issueByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + func redeemByPartition(from: EthereumAddress, partition: Data, amount: String, data: [UInt8]) throws -> WriteTransaction + func operatorRedeemByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, operatorData: [UInt8]) throws -> WriteTransaction + +} + +public class ERC1410: IERC1410 { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + private var _totalSupply: BigUInt? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc1410ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 255 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("allowance", parameters: [originalOwner, delegate] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(newAmount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("setAllowance", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + //ERC1410 methods + public func balanceOfByPartition(partition: Data, tokenHolder: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOfByPartition", parameters: [partition, tokenHolder] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> [Data] { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("partitionsOf", parameters: [tokenHolder] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferByPartition", parameters: [partition, to, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func operatorTransferByPartition(partition: Data, from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("operatorTransferByPartition", parameters: [partition, originalOwner, to, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func canTransferByPartition(originalOwner: EthereumAddress, to: EthereumAddress, partition: Data, amount: String, data: [UInt8]) throws -> ([UInt8], Data, Data) { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: transactionOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let result = try contract.read("canTransfer", parameters: [originalOwner, to, partition, value, data] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("isOperator", parameters: [user, tokenHolder] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("isOperatorForPartition", parameters: [partition, user, tokenHolder] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("authorizeOperator", parameters: [user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func revokeOperator(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("revokeOperator", parameters: [user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func authorizeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("authorizeOperatorByPartition", parameters: [partition, user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func revokeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("revokeOperatorByPartition", parameters: [partition, user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func issueByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("issueByPartition", parameters: [partition, tokenHolder, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func redeemByPartition(from: EthereumAddress, partition: Data, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("redeemByPartition", parameters: [partition, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func operatorRedeemByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("operatorRedeemByPartition", parameters: [partition, tokenHolder, value, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } +} + +extension ERC1410: IERC777 { + public func canImplementInterfaceForAddress(interfaceHash: Data, addr: EthereumAddress) throws -> Data { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("canImplementInterfaceForAddress", parameters: [interfaceHash, addr] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> EthereumAddress { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("getInterfaceImplementer", parameters: [addr, interfaceHash] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + + let tx = contract.write("setInterfaceImplementer", parameters: [addr, interfaceHash, implementer] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setManager(from: EthereumAddress, addr: EthereumAddress, newManager: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + + let tx = contract.write("setManager", parameters: [addr, newManager] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func interfaceHash(interfaceName: String) throws -> Data { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("interfaceHash", parameters: [interfaceName] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + + let tx = contract.write("updateERC165Cache", parameters: [contract, interfaceId] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func supportsInterface(interfaceID: String) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + transactionOptions.gasLimit = .manual(30000) + let result = try contract.read("supportsInterface", parameters: [interfaceID] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.callOnBlock = .latest + + let tx = contract.write("authorizeOperator", parameters: [user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func revoke(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.callOnBlock = .latest + + let tx = contract.write("revokeOperator", parameters: [user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func isOperatorFor(operator user: EthereumAddress, tokenHolder: EthereumAddress) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("isOperatorFor", parameters: [user, tokenHolder] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("send", parameters: [to, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func operatorSend(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("operatorSend", parameters: [originalOwner, to, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func burn(from: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("burn", parameters: [value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func operatorBurn(from: EthereumAddress, amount: String, originalOwner: EthereumAddress, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("burn", parameters: [originalOwner, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func getGranularity() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("granularity", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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() throws -> [EthereumAddress] { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("defaultOperators", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1594/Web3+ERC1594.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1594/Web3+ERC1594.swift new file mode 100644 index 000000000..7e8b94616 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1594/Web3+ERC1594.swift @@ -0,0 +1,409 @@ +// +// Web3+ERC1594.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 19/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress +import PromiseKit + +//Core Security Token Standard +protocol IERC1594: IERC20 { + + // Transfers + func transferWithData(from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + func transferFromWithData(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + + // Token Issuance + func isIssuable() throws -> Bool + func issue(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + + // Token Redemption + func redeem(from: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + func redeemFrom(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + + // Transfer Validity + func canTransfer(to: EthereumAddress, amount: String, data: [UInt8]) throws -> ([UInt8], Data) + func canTransferFrom(originalOwner: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) throws -> ([UInt8], Data) + +} + +public class ERC1594: IERC1594 { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc1594ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 255 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("allowance", parameters: [originalOwner, delegate] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(newAmount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("setAllowance", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + //ERC1594 + public func transferWithData(from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferWithData", parameters: [to, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFromWithData(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFromWithData", parameters: [originalOwner, to, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func isIssuable() throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("isIssuable", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("issue", parameters: [tokenHolder, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func redeem(from: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("redeem", parameters: [value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func redeemFrom(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("redeemFrom", parameters: [tokenHolder, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func canTransfer(to: EthereumAddress, amount: String, data: [UInt8]) throws -> ([UInt8], Data) { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: transactionOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let result = try contract.read("canTransfer", parameters: [to, value, data] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> ([UInt8], Data) { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: transactionOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let result = try contract.read("canTransfer", parameters: [originalOwner, to, value, data] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } +} + + diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1633/Web3+ERC1633.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1633/Web3+ERC1633.swift new file mode 100644 index 000000000..13ccdaf48 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1633/Web3+ERC1633.swift @@ -0,0 +1,254 @@ +// +// Web3+ERC1634.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 20/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress +import PromiseKit + +///Re-Fungible Token Standard (RFT) +protocol IERC1633: IERC20, IERC165 { + + func parentToken() throws -> EthereumAddress + func parentTokenId() throws -> BigUInt + +} + +public class ERC1633: IERC1633 { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc1633ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 255 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("allowance", parameters: [originalOwner, delegate] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(newAmount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("setAllowance", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func parentToken() throws -> EthereumAddress { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("parentToken", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("parentTokenId", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + transactionOptions.gasLimit = .manual(30000) + let result = try contract.read("supportsInterface", parameters: [interfaceID] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1643/Web3+ERC1643.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1643/Web3+ERC1643.swift new file mode 100644 index 000000000..e18bbead8 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1643/Web3+ERC1643.swift @@ -0,0 +1,267 @@ +// +// Web3+ERC1643.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 19/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress +import PromiseKit + +//Document Management Standard +protocol IERC1643: IERC20 { + + // Document Management + func getDocument(name: Data) throws -> (String, Data) + func setDocument(from: EthereumAddress, name: Data, uri: String, documentHash: Data) throws -> WriteTransaction + func removeDocument(from: EthereumAddress, name: Data) throws -> WriteTransaction + func getAllDocuments() throws -> [Data] + +} + +public class ERC1643: IERC1643 { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc1643ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 255 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("allowance", parameters: [originalOwner, delegate] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(newAmount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("setAllowance", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + //ERC1643 methods + public func getDocument(name: Data) throws -> (String, Data) { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("getDocument", parameters: [name] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("setDocument", parameters: [name, uri, documentHash] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func removeDocument(from: EthereumAddress, name: Data) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("removeDocument", parameters: [name] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func getAllDocuments() throws -> [Data] { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("getAllDocuments", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1644/Web3+ERC1644.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1644/Web3+ERC1644.swift new file mode 100644 index 000000000..fffbe6609 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC1644/Web3+ERC1644.swift @@ -0,0 +1,283 @@ +// +// Web3+ERC1644.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 19/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress +import PromiseKit + +//Controller Token Operation Standard +protocol IERC1644: IERC20 { + + // Controller Operation + func isControllable() throws -> Bool + func controllerTransfer(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction + func controllerRedeem(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction + +} + +public class ERC1644: IERC1644 { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc1644ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 255 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("allowance", parameters: [originalOwner, delegate] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(newAmount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("setAllowance", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + //ERC1644 + public func isControllable() throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("isControllable", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("controllerTransfer", parameters: [originalOwner, to, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func controllerRedeem(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("controllerRedeem", parameters: [tokenHolder, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC165/Web3+ERC165.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC165/Web3+ERC165.swift new file mode 100644 index 000000000..5abd3e955 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC165/Web3+ERC165.swift @@ -0,0 +1,16 @@ +// +// Web3+ERC165.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 15/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// + +import Foundation + +//Standard Interface Detection +protocol IERC165 { + + func supportsInterface(interfaceID: String) throws -> Bool + +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC20/Web3+ERC20.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC20/Web3+ERC20.swift new file mode 100644 index 000000000..f3000f57b --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC20/Web3+ERC20.swift @@ -0,0 +1,228 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress +import PromiseKit + +//Token Standard +protocol IERC20 { + func getBalance(account: EthereumAddress) throws -> BigUInt + func getAllowance(originalOwner: EthereumAddress, delegate: EthereumAddress) throws -> BigUInt + func transfer(from: EthereumAddress, to: EthereumAddress, amount: String) throws -> WriteTransaction + func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction + func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction + func approve(from: EthereumAddress, spender: EthereumAddress, amount: String) throws -> WriteTransaction + func totalSupply() throws -> BigUInt +} + +// This namespace contains functions to work with ERC20 tokens. +// variables are lazyly evaluated or global token information (name, ticker, total supply) +// can be imperatively read and saved +public class ERC20: IERC20 { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(Web3.Utils.erc20ABI, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 255 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("allowance", parameters: [originalOwner, delegate] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(newAmount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("setAllowance", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func approve(from: EthereumAddress, spender: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC721/Web3+ERC721.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC721/Web3+ERC721.swift new file mode 100644 index 000000000..08dba2cd5 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC721/Web3+ERC721.swift @@ -0,0 +1,280 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +//import EthereumAddress + +//Non-Fungible Token Standard +protocol IERC721: IERC165 { + + func getBalance(account: EthereumAddress) throws -> BigUInt + + func getOwner(tokenId: BigUInt) throws -> EthereumAddress + + func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction + + func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction + + func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt, data: [UInt8]) throws -> WriteTransaction + + func transfer(from: EthereumAddress, to: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction + + func approve(from: EthereumAddress, approved: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction + + func setApprovalForAll(from: EthereumAddress, operator user: EthereumAddress, approved: Bool) throws -> WriteTransaction + + func getApproved(tokenId: BigUInt) throws -> EthereumAddress + + func isApprovedForAll(owner: EthereumAddress, operator user: EthereumAddress) throws -> Bool +} + +protocol IERC721Metadata { + + func name() throws -> String + + func symbol() throws -> String + + func tokenURI(tokenId: BigUInt) throws -> String + +} + +protocol IERC721Enumerable { + + func totalSupply() throws -> BigUInt + + func tokenByIndex(index: BigUInt) throws -> BigUInt + + func tokenOfOwnerByIndex(owner: EthereumAddress, index: BigUInt) throws -> BigUInt +} + +// This namespace contains functions to work with ERC721 tokens. +// can be imperatively read and saved +public class ERC721: IERC721 { + + private var _tokenId: BigUInt? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(Web3.Utils.erc721ABI, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.transactionOptions = mergedOptions + } + + public var tokenId: BigUInt { + self.readProperties() + if self._tokenId != nil { + return self._tokenId! + } + return 0 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + + guard let tokenIdPromise = contract.read("tokenId", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [tokenIdPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let tokenIdResult) = resolvedPromises[0] else {return} + guard let tokenId = tokenIdResult["0"] as? BigUInt else {return} + self._tokenId = tokenId + + self._hasReadProperties = true + }.wait() + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 getOwner(tokenId: BigUInt) throws -> EthereumAddress { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("ownerOf", parameters: [tokenId] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 getApproved(tokenId: BigUInt) throws -> EthereumAddress { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("getApproved", parameters: [tokenId] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 transfer(from: EthereumAddress, to: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("transfer", parameters: [to, tokenId] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, tokenId] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("safeTransferFrom", parameters: [originalOwner, to, tokenId] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("safeTransferFrom", parameters: [originalOwner, to, tokenId, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func approve(from: EthereumAddress, approved: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("approve", parameters: [approved, tokenId] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setApprovalForAll(from: EthereumAddress, operator user: EthereumAddress, approved: Bool) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("setApprovalForAll", parameters: [user, approved] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func isApprovedForAll(owner: EthereumAddress, operator user: EthereumAddress) throws -> Bool { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.callOnBlock = .latest + let result = try contract.read("isApprovedForAll", parameters: [owner, user] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + transactionOptions.gasLimit = .manual(30000) + let result = try contract.read("supportsInterface", parameters: [interfaceID] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + +} + +extension ERC721: IERC721Enumerable { + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 tokenByIndex(index: BigUInt) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("tokenByIndex", parameters: [index] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 tokenOfOwnerByIndex(owner: EthereumAddress, index: BigUInt) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("tokenOfOwnerByIndex", parameters: [owner, index] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + +} + +extension ERC721: IERC721Metadata { + + public func name() throws -> String { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("name", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + guard let res = result["0"] as? String else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + return res + } + + public func symbol() throws -> String { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("symbol", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + guard let res = result["0"] as? String else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + return res + } + + public func tokenURI(tokenId: BigUInt) throws -> String { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("tokenId", parameters: [tokenId] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + guard let res = result["0"] as? String else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + return res + } + +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC721x/Web3+ERC721x.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC721x/Web3+ERC721x.swift new file mode 100644 index 000000000..94e9f5713 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC721x/Web3+ERC721x.swift @@ -0,0 +1,332 @@ +// +// Web3+ERC721x.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 20/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +//import EthereumAddress + +///A Smarter Token for the Future of Crypto Collectibles +///ERC721x is an extension of ERC721 that adds support for multi-fungible tokens and batch transfers, while being fully backward-compatible. + +protocol IERC721x: IERC721, IERC721Metadata, IERC721Enumerable { + func implementsERC721X() throws -> Bool + func getOwner(tokenId: BigUInt) throws -> EthereumAddress + func getBalance(account: EthereumAddress) throws -> BigUInt + func getBalance(account: EthereumAddress, tokenId: BigUInt) throws -> BigUInt + + func tokensOwned(account: EthereumAddress) throws -> ([BigUInt], [BigUInt]) + + func transfer(from: EthereumAddress, to: EthereumAddress, tokenId: BigUInt, quantity: BigUInt) throws -> WriteTransaction + func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt, quantity: BigUInt) throws -> WriteTransaction + + // Fungible Safe Transfer From + func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt, amount: BigUInt) throws -> WriteTransaction + func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt, amount: BigUInt, data: [UInt8]) throws -> WriteTransaction + + // Batch Safe Transfer From + func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenIds: [BigUInt], amounts: [BigUInt], data: [UInt8]) throws -> WriteTransaction + + func name() throws -> String + func symbol() throws -> String +} + +public class ERC721x: IERC721x { + + private var _tokenId: BigUInt? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc721xABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var tokenId: BigUInt { + self.readProperties() + if self._tokenId != nil { + return self._tokenId! + } + return 0 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + + guard let tokenIdPromise = contract.read("tokenId", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [tokenIdPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let tokenIdResult) = resolvedPromises[0] else {return} + guard let tokenId = tokenIdResult["0"] as? BigUInt else {return} + self._tokenId = tokenId + + self._hasReadProperties = true + }.wait() + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 getOwner(tokenId: BigUInt) throws -> EthereumAddress { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("ownerOf", parameters: [tokenId] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 getApproved(tokenId: BigUInt) throws -> EthereumAddress { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("getApproved", parameters: [tokenId] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 transfer(from: EthereumAddress, to: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("transfer", parameters: [to, tokenId] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, tokenId] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("safeTransferFrom", parameters: [originalOwner, to, tokenId] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("safeTransferFrom", parameters: [originalOwner, to, tokenId, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func approve(from: EthereumAddress, approved: EthereumAddress, tokenId: BigUInt) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("approve", parameters: [approved, tokenId] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setApprovalForAll(from: EthereumAddress, operator user: EthereumAddress, approved: Bool) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("setApprovalForAll", parameters: [user, approved] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func isApprovedForAll(owner: EthereumAddress, operator user: EthereumAddress) throws -> Bool { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.callOnBlock = .latest + let result = try contract.read("isApprovedForAll", parameters: [owner, user] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + transactionOptions.gasLimit = .manual(30000) + let result = try contract.read("supportsInterface", parameters: [interfaceID] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 tokenByIndex(index: BigUInt) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("tokenByIndex", parameters: [index] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 tokenOfOwnerByIndex(owner: EthereumAddress, index: BigUInt) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("tokenOfOwnerByIndex", parameters: [owner, index] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 name() throws -> String { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("name", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + guard let res = result["0"] as? String else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + return res + } + + public func symbol() throws -> String { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("symbol", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + guard let res = result["0"] as? String else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + return res + } + + public func tokenURI(tokenId: BigUInt) throws -> String { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("tokenId", parameters: [tokenId] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + guard let res = result["0"] as? String else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + return res + } + + func implementsERC721X() throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("implementsERC721X", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + + func getBalance(account: EthereumAddress, tokenId: BigUInt) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account, tokenId] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + + func tokensOwned(account: EthereumAddress) throws -> ([BigUInt], [BigUInt]) { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("tokensOwned", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + guard let res = result["0"] as? ([BigUInt], [BigUInt]) else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + return res + } + + func transfer(from: EthereumAddress, to: EthereumAddress, tokenId: BigUInt, quantity: BigUInt) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("transfer", parameters: [to, tokenId, quantity] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt, quantity: BigUInt) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, tokenId, quantity] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt, amount: BigUInt) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("safeTransferFrom", parameters: [originalOwner, to, tokenId, amount] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenId: BigUInt, amount: BigUInt, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("safeTransferFrom", parameters: [originalOwner, to, tokenId, amount, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func safeTransferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, tokenIds: [BigUInt], amounts: [BigUInt], data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("safeTransferFrom", parameters: [originalOwner, to, tokenIds, amounts, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC777/Web3+ERC777.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC777/Web3+ERC777.swift new file mode 100644 index 000000000..775ff9c15 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC777/Web3+ERC777.swift @@ -0,0 +1,445 @@ +// +// Web3+ERC777.swift +// web3swift +// +// Created by Anton Grigorev on 07/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// +import Foundation +import BigInt +import PromiseKit +//import EthereumAddress + +//A New Advanced Token Standard +protocol IERC777: IERC20, IERC820 { + func getDefaultOperators() throws -> [EthereumAddress] + func getGranularity() throws -> BigUInt + func getBalance(account: EthereumAddress) throws -> BigUInt + func getAllowance(originalOwner: EthereumAddress, delegate: EthereumAddress) throws -> BigUInt + func transfer(from: EthereumAddress, to: EthereumAddress, amount: String) throws -> WriteTransaction + func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction + func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction + func authorize(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction + func revoke(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction + func isOperatorFor(operator user: EthereumAddress, tokenHolder: EthereumAddress) throws -> Bool + func send(from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + func operatorSend(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction + func burn(from: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction + func operatorBurn(from: EthereumAddress, amount: String, originalOwner: EthereumAddress, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction +} + +// This namespace contains functions to work with ERC777 tokens. +// can be imperatively read and saved +public class ERC777: IERC777 { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc777ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + /// Must be 18! + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 18 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + public func getGranularity() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("granularity", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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() throws -> [EthereumAddress] { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("defaultOperators", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("allowance", parameters: [originalOwner, delegate] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(newAmount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("setAllowance", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + + /// ERC777 methods + public func authorize(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + let tx = contract.write("authorizeOperator", parameters: [user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func revoke(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + let tx = contract.write("revokeOperator", parameters: [user] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func isOperatorFor(operator user: EthereumAddress, tokenHolder: EthereumAddress) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("isOperatorFor", parameters: [user, tokenHolder] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("send", parameters: [to, value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func operatorSend(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("operatorSend", parameters: [originalOwner, to, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func burn(from: EthereumAddress, amount: String, data: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("burn", parameters: [value, data] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func operatorBurn(from: EthereumAddress, amount: String, originalOwner: EthereumAddress, data: [UInt8], operatorData: [UInt8]) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("burn", parameters: [originalOwner, value, data, operatorData] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func canImplementInterfaceForAddress(interfaceHash: Data, addr: EthereumAddress) throws -> Data { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("canImplementInterfaceForAddress", parameters: [interfaceHash, addr] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> EthereumAddress { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("getInterfaceImplementer", parameters: [addr, interfaceHash] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("setInterfaceImplementer", parameters: [addr, interfaceHash, implementer] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setManager(from: EthereumAddress, addr: EthereumAddress, newManager: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("setManager", parameters: [addr, newManager] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func interfaceHash(interfaceName: String) throws -> Data { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("interfaceHash", parameters: [interfaceName] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + + let tx = contract.write("updateERC165Cache", parameters: [contract, interfaceId] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func approve(from: EthereumAddress, spender: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func supportsInterface(interfaceID: String) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + transactionOptions.gasLimit = .manual(30000) + let result = try contract.read("supportsInterface", parameters: [interfaceID] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC820/Web3+ERC820.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC820/Web3+ERC820.swift new file mode 100644 index 000000000..4e805e9a2 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC820/Web3+ERC820.swift @@ -0,0 +1,20 @@ +// +// Web3+ERC820.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 15/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// + +import Foundation +//import EthereumAddress + +//Pseudo-introspection using a registry contract +protocol IERC820: IERC165 { + func canImplementInterfaceForAddress(interfaceHash: Data, addr: EthereumAddress) throws -> Data + func getInterfaceImplementer(addr: EthereumAddress, interfaceHash: Data) throws -> EthereumAddress + func setInterfaceImplementer(from: EthereumAddress, addr: EthereumAddress, interfaceHash: Data, implementer: EthereumAddress) throws -> WriteTransaction + func setManager(from: EthereumAddress, addr: EthereumAddress, newManager: EthereumAddress) throws -> WriteTransaction + func interfaceHash(interfaceName: String) throws -> Data + func updateERC165Cache(from: EthereumAddress, contract: EthereumAddress, interfaceId: [UInt8]) throws -> WriteTransaction +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC888/Web3+ERC888.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC888/Web3+ERC888.swift new file mode 100644 index 000000000..ce98f9b7c --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ERC888/Web3+ERC888.swift @@ -0,0 +1,138 @@ +// +// Web3+ERC888.swift +// web3swift-iOS +// +// Created by Anton Grigorev on 15/12/2018. +// Copyright © 2018 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress +import PromiseKit + +//MultiDimensional Token Standard +protocol IERC888 { + func getBalance(account: EthereumAddress) throws -> BigUInt + func transfer(from: EthereumAddress, to: EthereumAddress, amount: String) throws -> WriteTransaction +} + +public class ERC888: IERC888 { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc888ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 255 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + +} + diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ST20/Web3+ST20.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ST20/Web3+ST20.swift new file mode 100644 index 000000000..cc6b77344 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ST20/Web3+ST20.swift @@ -0,0 +1,314 @@ +// +// Web3+ST20.swift +// web3swift +// +// Created by Anton on 05/03/2019. +// Copyright © 2019 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +//import EthereumAddress + +//NPolymath Token Standard +protocol IST20: IERC20 { + // off-chain hash + func tokenDetails() throws -> [UInt32] + + //transfer, transferFrom must respect the result of verifyTransfer + func verifyTransfer(from: EthereumAddress, originalOwner: EthereumAddress, to: EthereumAddress, amount: String) throws -> WriteTransaction + + //used to create tokens + func mint(from: EthereumAddress, investor: EthereumAddress, amount: String) throws -> WriteTransaction + + //Burn function used to burn the securityToken + func burn(from: EthereumAddress, amount: String) throws -> WriteTransaction +} + +// This namespace contains functions to work with ST-20 tokens. +// can be imperatively read and saved +public class ST20: IST20 { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.st20ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + /// Must be 18! + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 18 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + func tokenDetails() throws -> [UInt32] { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("tokenDetails", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("verifyTransfer", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func mint(from: EthereumAddress, investor: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("mint", parameters: [investor, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func burn(from: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("burn", parameters: [value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("allowance", parameters: [originalOwner, delegate] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(newAmount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("setAllowance", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func approve(from: EthereumAddress, spender: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } + +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ST20/Web3+SecurityToken.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ST20/Web3+SecurityToken.swift new file mode 100644 index 000000000..2412616d4 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Tokens/ST20/Web3+SecurityToken.swift @@ -0,0 +1,473 @@ +// +// Web3+SecurityToken.swift +// web3swift +// +// Created by Anton on 05/03/2019. +// Copyright © 2019 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +//import EthereumAddress + +//The Ownable contract has an owner address, and provides basic authorization control functions, this simplifies the implementation of "user permissions". +protocol IOwnable { + //Allows the current owner to relinquish control of the contract. + func renounceOwnership(from: EthereumAddress) throws -> WriteTransaction + + //Allows the current owner to transfer control of the contract to a newOwner. + func transferOwnership(from: EthereumAddress, newOwner: EthereumAddress) throws -> WriteTransaction +} + +//Security token interface +protocol ISecurityToken: IST20, IOwnable { + // Value of current checkpoint + func currentCheckpointId() throws -> BigUInt + + func getGranularity() throws -> BigUInt + + // Total number of non-zero token holders + func investorCount() throws -> BigUInt + + // List of token holders + func investors() throws -> [EthereumAddress] + + // Permissions this to a Permission module, which has a key of 1 + // If no Permission return false - note that IModule withPerm will allow ST owner all permissions anyway + // this allows individual modules to override this logic if needed (to not allow ST owner all permissions) + func checkPermission(delegate: EthereumAddress, module: EthereumAddress, perm: [UInt32]) throws -> Bool + + //returns module list for a module type + //params: + //- moduleType is which type of module we are trying to remove + //- moduleIndex is the index of the module within the chosen type + func getModule(moduleType: UInt8, moduleIndex: UInt8) throws -> ([UInt32], EthereumAddress) + + //returns module list for a module name - will return first match + //params: + //- moduleType is which type of module we are trying to remove + //- name is the name of the module within the chosen type + func getModuleByName(moduleType: UInt8, name: [UInt32]) throws -> ([UInt32], EthereumAddress) + + //Queries totalSupply as of a defined checkpoint + func totalSupplyAt(checkpointId: BigUInt) throws -> BigUInt + + //Queries balances as of a defined checkpoint + func balanceOfAt(investor: EthereumAddress, checkpointId: BigUInt) throws -> BigUInt + + //Creates a checkpoint that can be used to query historical balances / totalSuppy + func createCheckpoint(from: EthereumAddress) throws -> WriteTransaction + + //gets length of investors array + func getInvestorsLength() throws -> BigUInt +} + +public class SecurityToken: ISecurityToken { + + private var _name: String? = nil + private var _symbol: String? = nil + private var _decimals: UInt8? = nil + + private var _hasReadProperties: Bool = false + + public var transactionOptions: TransactionOptions + public var web3: web3 + public var provider: Web3Provider + public var address: EthereumAddress + public var abi: String + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public init(web3: web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.st20ABI) { + self.web3 = web3 + self.provider = provider + self.address = address + var mergedOptions = web3.transactionOptions + mergedOptions.to = address + self.abi = abi + self.transactionOptions = mergedOptions + } + + public var name: String { + self.readProperties() + if self._name != nil { + return self._name! + } + return "" + } + + public var symbol: String { + self.readProperties() + if self._symbol != nil { + return self._symbol! + } + return "" + } + + /// Must be 18! + public var decimals: UInt8 { + self.readProperties() + if self._decimals != nil { + return self._decimals! + } + return 18 + } + + public func readProperties() { + if self._hasReadProperties { + return + } + let contract = self.contract + guard contract.contract.address != nil else {return} + var transactionOptions = TransactionOptions.defaultOptions + transactionOptions.callOnBlock = .latest + guard let namePromise = contract.read("name", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let symbolPromise = contract.read("symbol", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + guard let decimalPromise = contract.read("decimals", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: transactionOptions)?.callPromise() else {return} + + let allPromises = [namePromise, symbolPromise, decimalPromise] + let queue = self.web3.requestDispatcher.queue + when(resolved: allPromises).map(on: queue) { (resolvedPromises) -> Void in + guard case .fulfilled(let nameResult) = resolvedPromises[0] else {return} + guard let name = nameResult["0"] as? String else {return} + self._name = name + + guard case .fulfilled(let symbolResult) = resolvedPromises[1] else {return} + guard let symbol = symbolResult["0"] as? String else {return} + self._symbol = symbol + + guard case .fulfilled(let decimalsResult) = resolvedPromises[2] else {return} + guard let decimals = decimalsResult["0"] as? BigUInt else {return} + self._decimals = UInt8(decimals) + + self._hasReadProperties = true + }.wait() + } + + func tokenDetails() throws -> [UInt32] { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("tokenDetails", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("verifyTransfer", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + func mint(from: EthereumAddress, investor: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("mint", parameters: [investor, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func burn(from: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("burn", parameters: [value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func getBalance(account: EthereumAddress) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOf", parameters: [account] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("allowance", parameters: [originalOwner, delegate] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + let tx = contract.write("transfer", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("transferFrom", parameters: [originalOwner, to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(newAmount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("setAllowance", parameters: [to, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func approve(from: EthereumAddress, spender: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + 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 = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func totalSupply() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupply", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 renounceOwnership(from: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + let tx = contract.write("renounceOwnership", parameters: [AnyObject](), transactionOptions: basicOptions)! + return tx + } + + public func transferOwnership(from: EthereumAddress, newOwner: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + let tx = contract.write("transferOwnership", parameters: [newOwner] as [AnyObject], transactionOptions: basicOptions)! + return tx + } + + public func currentCheckpointId() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("currentCheckpointId", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 getGranularity() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("granularity", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 investorCount() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("investorCount", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 investors() throws -> [EthereumAddress] { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("investors", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 checkPermission(delegate: EthereumAddress, module: EthereumAddress, perm: [UInt32]) throws -> Bool { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("checkPermission", parameters: [delegate, module, perm] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 getModule(moduleType: UInt8, moduleIndex: UInt8) throws -> ([UInt32], EthereumAddress) { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("getModule", parameters: [moduleType, moduleIndex] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + guard let moduleList = result["0"] as? [UInt32] else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + guard let moduleAddress = result["1"] as? EthereumAddress else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + return (moduleList, moduleAddress) + } + + public func getModuleByName(moduleType: UInt8, name: [UInt32]) throws -> ([UInt32], EthereumAddress) { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("getModuleByName", parameters: [moduleType, name] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + guard let moduleList = result["0"] as? [UInt32] else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + guard let moduleAddress = result["1"] as? EthereumAddress else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + return (moduleList, moduleAddress) + } + + public func totalSupplyAt(checkpointId: BigUInt) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("totalSupplyAt", parameters: [checkpointId] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 balanceOfAt(investor: EthereumAddress, checkpointId: BigUInt) throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("balanceOfAt", parameters: [investor, checkpointId] as [AnyObject], extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 createCheckpoint(from: EthereumAddress) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.to = self.address + basicOptions.callOnBlock = .latest + + let tx = contract.write("createCheckpoint", parameters: [AnyObject](), transactionOptions: basicOptions)! + return tx + } + + public func getInvestorsLength() throws -> BigUInt { + let contract = self.contract + var transactionOptions = TransactionOptions() + transactionOptions.callOnBlock = .latest + let result = try contract.read("getInvestorsLength", parameters: [AnyObject](), extraData: Data(), transactionOptions: self.transactionOptions)!.call(transactionOptions: transactionOptions) + 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 + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Transaction/BloomFilter.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Transaction/BloomFilter.swift new file mode 100755 index 000000000..4daded407 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Transaction/BloomFilter.swift @@ -0,0 +1,110 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import CryptoSwift +//import EthereumAddress + +public struct EthereumBloomFilter{ + public var bytes = Data(repeatElement(UInt8(0), count: 256)) + public init?(_ biguint: BigUInt) { + guard let data = biguint.serialize().setLengthLeft(256) else {return nil} + bytes = data + } + public init() {} + public init(_ data: Data) { + let padding = Data(repeatElement(UInt8(0), count: 256 - data.count)) + bytes = padding + data + } + public func asBigUInt() -> BigUInt { + return BigUInt(self.bytes) + } +} + +extension EthereumBloomFilter { + + static func bloom9(_ biguint: BigUInt) -> BigUInt { + return EthereumBloomFilter.bloom9(biguint.serialize()) + } + + static func bloom9(_ data: Data) -> BigUInt { + let b = data.sha3(.keccak256) + var r = BigUInt(0) + let mask = BigUInt(2047) + for i in stride(from: 0, to: 6, by: 2) { + var t = BigUInt(1) + let num = (BigUInt(b[i+1]) + (BigUInt(b[i]) << 8)) & mask +// b = num.serialize().setLengthLeft(8)! + t = t << num + r = r | t + } + return r + } + + static func logsToBloom(_ logs: [EventLog]) -> BigUInt { + var bin = BigUInt(0) + for log in logs { + bin = bin | bloom9(log.address.addressData) + for topic in log.topics { + bin = bin | bloom9(topic) + } + } + return bin + } + + public static func createBloom(_ receipts: [TransactionReceipt]) -> EthereumBloomFilter? { + var bin = BigUInt(0) + for receipt in receipts { + bin = bin | EthereumBloomFilter.logsToBloom(receipt.logs) + } + return EthereumBloomFilter(bin) + } + + public func test(topic: Data) -> Bool { + let bin = self.asBigUInt() + let comparison = EthereumBloomFilter.bloom9(topic) + return bin & comparison == comparison + } + + public func test(topic: BigUInt) -> Bool { + return self.test(topic: topic.serialize()) + } + + public static func bloomLookup(_ bloom: EthereumBloomFilter, topic:Data) -> Bool { + let bin = bloom.asBigUInt() + let comparison = bloom9(topic) + return bin & comparison == comparison + } + + public static func bloomLookup(_ bloom: EthereumBloomFilter, topic:BigUInt) -> Bool { + return EthereumBloomFilter.bloomLookup(bloom, topic: topic.serialize()) + } + + public mutating func add(_ biguint: BigUInt) { + var bin = BigUInt(self.bytes) + bin = bin | EthereumBloomFilter.bloom9(biguint) + setBytes(bin.serialize()) + } + + public mutating func add(_ data: Data) { + var bin = BigUInt(self.bytes) + bin = bin | EthereumBloomFilter.bloom9(data) + setBytes(bin.serialize()) + } + + public func lookup (_ topic: Data) -> Bool { + return EthereumBloomFilter.bloomLookup(self, topic: topic) + } + + mutating func setBytes(_ data: Data) { + if (self.bytes.count < data.count) { + fatalError("bloom bytes are too big") + } + self.bytes = self.bytes[0 ..< data.count] + data + } + +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Transaction/EthereumTransaction.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Transaction/EthereumTransaction.swift new file mode 100755 index 000000000..d799d3ab7 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Transaction/EthereumTransaction.swift @@ -0,0 +1,403 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import SwiftRLP +//import secp256k1_swift +//import EthereumAddress + +public struct EthereumTransaction: CustomStringConvertible { + public var nonce: BigUInt + public var gasPrice: BigUInt = BigUInt(0) + public var gasLimit: BigUInt = BigUInt(0) + // The destination address of the message, left undefined for a contract-creation transaction. + public var to: EthereumAddress + // (optional) The value transferred for the transaction in wei, also the endowment if it’s a contract-creation transaction. + // TODO - split EthereumTransaction to two classes: with optional and required value property, depends on type of transaction + public var value: BigUInt? + public var data: Data + public var v: BigUInt = BigUInt(1) + public var r: BigUInt = BigUInt(0) + public var s: BigUInt = BigUInt(0) + var chainID: BigUInt? = nil + + public var inferedChainID: BigUInt? { + get{ + if (self.r == BigUInt(0) && self.s == BigUInt(0)) { + return self.v + } else if (self.v == BigUInt(27) || self.v == BigUInt(28)) { + return nil + } else { + return ((self.v - BigUInt(1)) / BigUInt(2)) - BigUInt(17) + } + } + } + + public var intrinsicChainID: BigUInt? { + get{ + return self.chainID + } + } + + public mutating func UNSAFE_setChainID(_ chainID: BigUInt?) { + self.chainID = chainID + } + + public var hash: Data? { + var encoded: Data + let inferedChainID = self.inferedChainID + if inferedChainID != nil { + guard let enc = self.self.encode(forSignature: false, chainID: inferedChainID) else {return nil} + encoded = enc + } else { + guard let enc = self.self.encode(forSignature: false, chainID: self.chainID) else {return nil} + encoded = enc + } + let hash = encoded.sha3(.keccak256) + return hash + } + + public init(gasPrice: BigUInt, gasLimit: BigUInt, to: EthereumAddress, value: BigUInt, data: Data) { + self.nonce = BigUInt(0) + self.gasPrice = gasPrice + self.gasLimit = gasLimit + self.value = value + self.data = data + self.to = to + } + + + public init (nonce: BigUInt, gasPrice: BigUInt, gasLimit: BigUInt, to: EthereumAddress, value: BigUInt, data: Data, v: BigUInt, r: BigUInt, s: BigUInt) { + self.nonce = nonce + self.gasPrice = gasPrice + self.gasLimit = gasLimit + self.to = to + self.value = value + self.data = data + self.v = v + self.r = r + self.s = s + } + + public var description: String { + get { + var toReturn = "" + toReturn = toReturn + "Transaction" + "\n" + toReturn = toReturn + "Nonce: " + String(self.nonce) + "\n" + toReturn = toReturn + "Gas price: " + String(self.gasPrice) + "\n" + toReturn = toReturn + "Gas limit: " + String(describing: self.gasLimit) + "\n" + toReturn = toReturn + "To: " + self.to.address + "\n" + toReturn = toReturn + "Value: " + String(self.value ?? "nil") + "\n" + toReturn = toReturn + "Data: " + self.data.toHexString().addHexPrefix().lowercased() + "\n" + toReturn = toReturn + "v: " + String(self.v) + "\n" + toReturn = toReturn + "r: " + String(self.r) + "\n" + toReturn = toReturn + "s: " + String(self.s) + "\n" + toReturn = toReturn + "Intrinsic chainID: " + String(describing:self.chainID) + "\n" + toReturn = toReturn + "Infered chainID: " + String(describing:self.inferedChainID) + "\n" + toReturn = toReturn + "sender: " + String(describing: self.sender?.address) + "\n" + toReturn = toReturn + "hash: " + String(describing: self.hash?.toHexString().addHexPrefix()) + "\n" + return toReturn + } + + } + public var sender: EthereumAddress? { + get { + guard let publicKey = self.recoverPublicKey() else {return nil} + return Web3.Utils.publicToAddress(publicKey) + } + } + + public func recoverPublicKey() -> Data? { + if (self.r == BigUInt(0) && self.s == BigUInt(0)) { + return nil + } + var normalizedV:BigUInt = BigUInt(27) + let inferedChainID = self.inferedChainID + var d = BigUInt(0) + if self.v >= 35 && self.v <= 38 { + d = BigUInt(35) + } else if self.v >= 31 && self.v <= 34 { + d = BigUInt(31) + } else if self.v >= 27 && self.v <= 30 { + d = BigUInt(27) + } + if (self.chainID != nil && self.chainID != BigUInt(0)) { + normalizedV = self.v - d - self.chainID! - self.chainID! + } else if (inferedChainID != nil) { + normalizedV = self.v - d - inferedChainID! - inferedChainID! + } else { + normalizedV = self.v - d + } + guard let vData = normalizedV.serialize().setLengthLeft(1) else {return nil} + guard let rData = r.serialize().setLengthLeft(32) else {return nil} + guard let sData = s.serialize().setLengthLeft(32) else {return nil} + guard let signatureData = SECP256K1.marshalSignature(v: vData, r: rData, s: sData) else {return nil} + var hash: Data + if inferedChainID != nil { + guard let h = self.hashForSignature(chainID: inferedChainID) else {return nil} + hash = h + } else { + guard let h = self.hashForSignature(chainID: self.chainID) else {return nil} + hash = h + } + guard let publicKey = SECP256K1.recoverPublicKey(hash: hash, signature: signatureData) else {return nil} + return publicKey + } + + public var txhash: String? { + get{ + guard self.sender != nil else {return nil} + guard let hash = self.hash else {return nil} + let txid = hash.toHexString().addHexPrefix().lowercased() + return txid + } + } + + public var txid: String? { + get { + return self.txhash + } + } + + public func encode(forSignature:Bool = false, chainID: BigUInt? = nil) -> Data? { + if (forSignature) { + if chainID != nil { + let fields = [self.nonce, self.gasPrice, self.gasLimit, self.to.addressData, self.value!, self.data, chainID!, BigUInt(0), BigUInt(0)] as [AnyObject] + return RLP.encode(fields) + } + else if self.chainID != nil { + let fields = [self.nonce, self.gasPrice, self.gasLimit, self.to.addressData, self.value!, self.data, self.chainID!, BigUInt(0), BigUInt(0)] as [AnyObject] + return RLP.encode(fields) + } else { + let fields = [self.nonce, self.gasPrice, self.gasLimit, self.to.addressData, self.value!, self.data] as [AnyObject] + return RLP.encode(fields) + } + } else { + let fields = [self.nonce, self.gasPrice, self.gasLimit, self.to.addressData, self.value!, self.data, self.v, self.r, self.s] as [AnyObject] + return RLP.encode(fields) + } + } + + public func encodeAsDictionary(from: EthereumAddress? = nil) -> TransactionParameters? { + var toString: String? = nil + switch self.to.type { + case .normal: + toString = self.to.address.lowercased() + case .contractDeployment: + break + } + var params = TransactionParameters(from: from?.address.lowercased(), + to: toString) + let gasEncoding = self.gasLimit.abiEncode(bits: 256) + params.gas = gasEncoding?.toHexString().addHexPrefix().stripLeadingZeroes() + let gasPriceEncoding = self.gasPrice.abiEncode(bits: 256) + params.gasPrice = gasPriceEncoding?.toHexString().addHexPrefix().stripLeadingZeroes() + let valueEncoding = self.value?.abiEncode(bits: 256) + params.value = valueEncoding?.toHexString().addHexPrefix().stripLeadingZeroes() + if (self.data != Data()) { + params.data = self.data.toHexString().addHexPrefix() + } else { + params.data = "0x" + } + return params + } + + public func hashForSignature(chainID: BigUInt? = nil) -> Data? { + guard let encoded = self.encode(forSignature: true, chainID: chainID) else {return nil} + let hash = encoded.sha3(.keccak256) + return hash + } + + public static func fromRaw(_ raw: Data) -> EthereumTransaction? { + guard let totalItem = RLP.decode(raw) else {return nil} + guard let rlpItem = totalItem[0] else {return nil} + switch rlpItem.count { + case 9?: + guard let nonceData = rlpItem[0]!.data else {return nil} + let nonce = BigUInt(nonceData) + guard let gasPriceData = rlpItem[1]!.data else {return nil} + let gasPrice = BigUInt(gasPriceData) + guard let gasLimitData = rlpItem[2]!.data else {return nil} + let gasLimit = BigUInt(gasLimitData) + var to:EthereumAddress + switch rlpItem[3]!.content { + case .noItem: + to = EthereumAddress.contractDeploymentAddress() + case .data(let addressData): + if addressData.count == 0 { + to = EthereumAddress.contractDeploymentAddress() + } else if addressData.count == 20 { + guard let addr = EthereumAddress(addressData) else {return nil} + to = addr + } else { + return nil + } + case .list(_, _, _): + return nil + } + guard let valueData = rlpItem[4]!.data else {return nil} + let value = BigUInt(valueData) + guard let transactionData = rlpItem[5]!.data else {return nil} + guard let vData = rlpItem[6]!.data else {return nil} + let v = BigUInt(vData) + guard let rData = rlpItem[7]!.data else {return nil} + let r = BigUInt(rData) + guard let sData = rlpItem[8]!.data else {return nil} + let s = BigUInt(sData) + return EthereumTransaction.init(nonce: nonce, gasPrice: gasPrice, gasLimit: gasLimit, to: to, value: value, data: transactionData, v: v, r: r, s: s) + case 6?: + return nil + default: + return nil + } + } + + static func createRequest(method: JSONRPCmethod, transaction: EthereumTransaction, transactionOptions: TransactionOptions?) -> JSONRPCrequest? { + let onBlock = transactionOptions?.callOnBlock?.stringValue + var request = JSONRPCrequest() +// var tx = transaction + request.method = method + let from = transactionOptions?.from + guard var txParams = transaction.encodeAsDictionary(from: from) else {return nil} + if method == .estimateGas || transactionOptions?.gasLimit == nil { + txParams.gas = nil + } + var params = [txParams] as Array + if method.requiredNumOfParameters == 2 && onBlock != nil { + params.append(onBlock as Encodable) + } + let pars = JSONRPCparams(params: params) + request.params = pars + if !request.isValid {return nil} + return request + } + + static func createRawTransaction(transaction: EthereumTransaction) -> JSONRPCrequest? { + guard transaction.sender != nil else {return nil} + guard let encodedData = transaction.encode() else {return nil} + let hex = encodedData.toHexString().addHexPrefix().lowercased() + var request = JSONRPCrequest() + request.method = JSONRPCmethod.sendRawTransaction + let params = [hex] as Array + let pars = JSONRPCparams(params: params) + request.params = pars + if !request.isValid {return nil} + return request + } +} + +public extension EthereumTransaction { + init(to: EthereumAddress, data: Data, options: TransactionOptions) { + let defaults = TransactionOptions.defaultOptions + let merged = defaults.merge(options) + self.nonce = BigUInt(0) + + if let gP = merged.gasPrice { + switch gP { + case .manual(let value): + self.gasPrice = value + default: + self.gasPrice = BigUInt("5000000000") + } + } + + if let gL = merged.gasLimit { + switch gL { + case .manual(let value): + self.gasLimit = value + default: + self.gasLimit = BigUInt(UInt64(21000)) + } + } + + if let value = merged.value { + self.value = value + } + + self.to = to + self.data = data + } + + func mergedWithOptions(_ options: TransactionOptions) -> EthereumTransaction { + var tx = self; + + if let gP = options.gasPrice { + switch gP { + case .manual(let value): + tx.gasPrice = value + default: + tx.gasPrice = BigUInt("5000000000") + } + } + + if let gL = options.gasLimit { + switch gL { + case .manual(let value): + tx.gasLimit = value + case .limited(let value): + tx.gasLimit = value + default: + tx.gasLimit = BigUInt(UInt64(21000)) + } + } + + if options.value != nil { + tx.value = options.value! + } + if options.to != nil { + tx.to = options.to! + } + return tx + } + + static func fromJSON(_ json: [String: Any]) -> EthereumTransaction? { + guard let options = TransactionOptions.fromJSON(json) else {return nil} + guard let toString = json["to"] as? String else {return nil} + var to: EthereumAddress + if toString == "0x" || toString == "0x0" { + to = EthereumAddress.contractDeploymentAddress() + } else { + guard let ethAddr = EthereumAddress(toString) else {return nil} + to = ethAddr + } + // if (!to.isValid) { + // return nil + // } + var dataString = json["data"] as? String + if (dataString == nil) { + dataString = json["input"] as? String + } + guard dataString != nil, let data = Data.fromHex(dataString!) else {return nil} + var transaction = EthereumTransaction(to: to, data: data, options: options) + if let nonceString = json["nonce"] as? String { + guard let nonce = BigUInt(nonceString.stripHexPrefix(), radix: 16) else {return nil} + transaction.nonce = nonce + } + if let vString = json["v"] as? String { + guard let v = BigUInt(vString.stripHexPrefix(), radix: 16) else {return nil} + transaction.v = v + } + if let rString = json["r"] as? String { + guard let r = BigUInt(rString.stripHexPrefix(), radix: 16) else {return nil} + transaction.r = r + } + if let sString = json["s"] as? String { + guard let s = BigUInt(sString.stripHexPrefix(), radix: 16) else {return nil} + transaction.s = s + } + if let valueString = json["value"] as? String { + guard let value = BigUInt(valueString.stripHexPrefix(), radix: 16) else {return nil} + transaction.value = value + } + let inferedChainID = transaction.inferedChainID + if (transaction.inferedChainID != nil && transaction.v >= BigUInt(37)) { + transaction.chainID = inferedChainID + } + return transaction + } + +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Transaction/TransactionSigner.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Transaction/TransactionSigner.swift new file mode 100755 index 000000000..b5349c7a8 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Transaction/TransactionSigner.swift @@ -0,0 +1,118 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import secp256k1_swift +//import EthereumAddress + +public enum TransactionSignerError: Error { + case signatureError(String) +} + +public struct Web3Signer { + public static func signTX(transaction:inout EthereumTransaction, keystore: AbstractKeystore, account: EthereumAddress, password: String, useExtraEntropy: Bool = false) throws { + var privateKey = try keystore.UNSAFE_getPrivateKeyData(password: password, account: account) + defer {Data.zero(&privateKey)} + if (transaction.chainID != nil) { + try EIP155Signer.sign(transaction: &transaction, privateKey: privateKey, useExtraEntropy: useExtraEntropy) + } else { + try FallbackSigner.sign(transaction: &transaction, privateKey: privateKey, useExtraEntropy: useExtraEntropy) + } + } + + public static func signPersonalMessage(_ personalMessage: Data, keystore: T, account: EthereumAddress, password: String, useExtraEntropy: Bool = false) throws -> Data? { + var privateKey = try keystore.UNSAFE_getPrivateKeyData(password: password, account: account) + defer {Data.zero(&privateKey)} + guard let hash = Web3.Utils.hashPersonalMessage(personalMessage) else {return nil} + let (compressedSignature, _) = SECP256K1.signForRecovery(hash: hash, privateKey: privateKey, useExtraEntropy: useExtraEntropy) + return compressedSignature + } + + public struct EIP155Signer { + public static func sign(transaction:inout EthereumTransaction, privateKey: Data, useExtraEntropy: Bool = false) throws { + for _ in 0..<1024 { + let result = self.attemptSignature(transaction: &transaction, privateKey: privateKey, useExtraEntropy: useExtraEntropy) + if (result) { + return + } + } + throw AbstractKeystoreError.invalidAccountError + } + + private static func attemptSignature(transaction:inout EthereumTransaction, privateKey: Data, useExtraEntropy: Bool = false) -> Bool { + guard let chainID = transaction.chainID else {return false} + guard let hash = transaction.hashForSignature(chainID: chainID) else {return false} + let signature = SECP256K1.signForRecovery(hash: hash, privateKey: privateKey, useExtraEntropy: useExtraEntropy) + guard let serializedSignature = signature.serializedSignature else {return false} + guard let unmarshalledSignature = SECP256K1.unmarshalSignature(signatureData: serializedSignature) else { + return false + } + let originalPublicKey = SECP256K1.privateToPublic(privateKey: privateKey) + var d = BigUInt(0) + if unmarshalledSignature.v >= 0 && unmarshalledSignature.v <= 3 { + d = BigUInt(35) + } else if unmarshalledSignature.v >= 27 && unmarshalledSignature.v <= 30 { + d = BigUInt(8) + } else if unmarshalledSignature.v >= 31 && unmarshalledSignature.v <= 34 { + d = BigUInt(4) + } + transaction.v = BigUInt(unmarshalledSignature.v) + d + chainID + chainID + transaction.r = BigUInt(Data(unmarshalledSignature.r)) + transaction.s = BigUInt(Data(unmarshalledSignature.s)) + let recoveredPublicKey = transaction.recoverPublicKey() + if (!(originalPublicKey!.constantTimeComparisonTo(recoveredPublicKey))) { + return false + } + return true + } + } + + public struct FallbackSigner { + public static func sign(transaction:inout EthereumTransaction, privateKey: Data, useExtraEntropy: Bool = false) throws { + for _ in 0..<1024 { + let result = self.attemptSignature(transaction: &transaction, privateKey: privateKey) + if (result) { + return + } + } + throw AbstractKeystoreError.invalidAccountError + } + + private static func attemptSignature(transaction:inout EthereumTransaction, privateKey: Data, useExtraEntropy: Bool = false) -> Bool { + guard let hash = transaction.hashForSignature(chainID: nil) else {return false} + let signature = SECP256K1.signForRecovery(hash: hash, privateKey: privateKey, useExtraEntropy: useExtraEntropy) + guard let serializedSignature = signature.serializedSignature else {return false} + guard let unmarshalledSignature = SECP256K1.unmarshalSignature(signatureData: serializedSignature) else { + return false + } + let originalPublicKey = SECP256K1.privateToPublic(privateKey: privateKey) + transaction.chainID = nil + var d = BigUInt(0) + var a = BigUInt(0) + if unmarshalledSignature.v >= 0 && unmarshalledSignature.v <= 3 { + d = BigUInt(27) + } else if unmarshalledSignature.v >= 31 && unmarshalledSignature.v <= 34 { + a = BigUInt(4) + } else if unmarshalledSignature.v >= 35 && unmarshalledSignature.v <= 38 { + a = BigUInt(8) + } + transaction.v = BigUInt(unmarshalledSignature.v) + d - a + transaction.r = BigUInt(Data(unmarshalledSignature.r)) + transaction.s = BigUInt(Data(unmarshalledSignature.s)) + let recoveredPublicKey = transaction.recoverPublicKey() + if (!(originalPublicKey!.constantTimeComparisonTo(recoveredPublicKey))) { + return false + } + return true + } + } + +} + + + + diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/EIP/EIP67Code.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/EIP/EIP67Code.swift new file mode 100755 index 000000000..39ad909d8 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/EIP/EIP67Code.swift @@ -0,0 +1,138 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import CoreImage +import BigInt +//import EthereumAddress +//import EthereumABI + +extension Web3 { + + public struct EIP67Code { + public var address: EthereumAddress + public var gasLimit: BigUInt? + public var amount: BigUInt? + public var data: DataType? + + public enum DataType { + case data(Data) + case function(Function) + } + public struct Function { + public var method: String + public var parameters: [(ABI.Element.ParameterType, AnyObject)] + + public func toString() -> String? { + 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 { + return el.0.abiRepresentation + " " + String(number, radix: 10) + } else if let number = el.1 as? BigInt { + return el.0.abiRepresentation + " " + String(number, radix: 10) + } else if let data = el.1 as? Data { + return el.0.abiRepresentation + " " + data.toHexString().addHexPrefix() + } + return "" + }).joined(separator: ", ") + ")" + return encoding + } + } + + public init (address : EthereumAddress) { + self.address = address + } + + public init? (address : String) { + guard let addr = EthereumAddress(address) else {return nil} + self.address = addr + } + + public func toString() -> String { + var urlComponents = URLComponents() + let mainPart = "ethereum:"+self.address.address.lowercased() + var queryItems = [URLQueryItem]() + if let amount = self.amount { + queryItems.append(URLQueryItem(name: "value", value: String(amount, radix: 10))) + } + if let gasLimit = self.gasLimit { + queryItems.append(URLQueryItem(name: "gas", value: String(gasLimit, radix: 10))) + } + if let data = self.data { + switch data { + case .data(let d): + queryItems.append(URLQueryItem(name: "data", value: d.toHexString().addHexPrefix())) + case .function(let f): + if let enc = f.toString() { + queryItems.append(URLQueryItem(name: "function", value: enc)) + } + } + } + urlComponents.queryItems = queryItems + if let url = urlComponents.url { + return mainPart + url.absoluteString + } + return mainPart + } + + public func toImage(scale: Double = 1.0) -> CIImage { + return EIP67CodeGenerator.createImage(from: self, scale: scale) + } + } + + public struct EIP67CodeGenerator { + + public static func createImage(from: EIP67Code, scale: Double = 1.0) -> CIImage { + guard let string = from.toString().addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) else {return CIImage()} + guard let data = string.data(using: .utf8, allowLossyConversion: false) else {return CIImage()} + let filter = CIFilter(name: "CIQRCodeGenerator", parameters: ["inputMessage" : data, "inputCorrectionLevel":"L"]) + guard var image = filter?.outputImage else {return CIImage()} + let transformation = CGAffineTransform(scaleX: CGFloat(scale), y: CGFloat(scale)) + image = image.transformed(by: transformation) + return image + } + } + + public struct EIP67CodeParser { + public static func parse(_ data: Data) -> EIP67Code? { + 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} + 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} + var code = EIP67Code(address: address) + guard let components = URLComponents(string: encoding)?.queryItems else {return code} + 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} + code.amount = val + case "gas": + guard let value = comp.value else {return nil} + guard let val = BigUInt(value, radix: 10) else {return nil} + code.gasLimit = val + case "data": + guard let value = comp.value else {return nil} + guard let data = Data.fromHex(value) else {return nil} + code.data = EIP67Code.DataType.data(data) + case "function": + continue + default: + continue + } + } + return code + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/EIP/EIP681.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/EIP/EIP681.swift new file mode 100755 index 000000000..d00e76ba1 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/EIP/EIP681.swift @@ -0,0 +1,232 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress +//import EthereumABI + +extension Web3 { + +// request = "ethereum" ":" [ "pay-" ]target_address [ "@" chain_id ] [ "/" function_name ] [ "?" parameters ] +// target_address = ethereum_address +// chain_id = 1*DIGIT +// function_name = STRING +// ethereum_address = ( "0x" 40*40HEXDIG ) / ENS_NAME +// parameters = parameter *( "&" parameter ) +// parameter = key "=" value +// key = "value" / "gas" / "gasLimit" / "gasPrice" / TYPE +// value = number / ethereum_address / STRING +// number = [ "-" / "+" ] *DIGIT [ "." 1*DIGIT ] [ ( "e" / "E" ) [ 1*DIGIT ] [ "+" UNIT ] + + public struct EIP681Code { + public struct EIP681Parameter { + public var type: ABI.Element.ParameterType + public var value: AnyObject + } + public var isPayRequest: Bool + public var targetAddress: TargetAddress + public var chainID: BigUInt? + public var functionName: String? + public var parameters: [EIP681Parameter] = [EIP681Parameter]() + public var gasLimit: BigUInt? + public var gasPrice: BigUInt? + public var amount: BigUInt? + public var function: ABI.Element.Function? + + public enum TargetAddress { + case ethereumAddress(EthereumAddress) + case ensAddress(String) + public init(_ string: String) { + if let ethereumAddress = EthereumAddress(string) { + self = TargetAddress.ethereumAddress(ethereumAddress) + } else { + self = TargetAddress.ensAddress(string) + } + } + } + + public init(_ targetAddress: TargetAddress, isPayRequest: Bool = false) { + self.isPayRequest = isPayRequest + self.targetAddress = targetAddress + } + } + + public struct EIP681CodeParser { +// static var addressRegex = "^(pay-)?([0-9a-zA-Z]+)(@[0-9]+)?" + static var addressRegex = "^(pay-)?([0-9a-zA-Z.]+)(@[0-9]+)?\\/?(.*)?$" + + public static func parse(_ data: Data) -> EIP681Code? { + guard let string = String(data: data, encoding: .utf8) else {return nil} + return parse(string) + } + + public static func parse(_ string: String) -> EIP681Code? { + 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} + let matcher = try! NSRegularExpression(pattern: addressRegex, options: NSRegularExpression.Options.dotMatchesLineSeparators) + let match = matcher.matches(in: encoding, options: NSRegularExpression.MatchingOptions.anchored, range: encoding.fullNSRange) + guard match.count == 1 else {return nil} + guard match[0].numberOfRanges == 5 else {return nil} + var addressString: String? = nil + var chainIDString: String? = nil + var tail: String? = nil +// if let payModifierRange = Range(match[0].range(at: 1), in: encoding) { +// let payModifierString = String(encoding[payModifierRange]) +// print(payModifierString) +// } + if let addressRange = Range(match[0].range(at: 2), in: encoding) { + addressString = String(encoding[addressRange]) + } + if let chainIDRange = Range(match[0].range(at: 3), in: encoding) { + chainIDString = String(encoding[chainIDRange]) + } + if let tailRange = Range(match[0].range(at: 4), in: encoding) { + tail = String(encoding[tailRange]) + } + guard let address = addressString else {return nil} + let targetAddress = EIP681Code.TargetAddress(address) + + var code = EIP681Code(targetAddress) + if chainIDString != nil { + chainIDString!.remove(at: chainIDString!.startIndex) + code.chainID = BigUInt(chainIDString!) + } + if tail == nil { + return code + } + guard let components = URLComponents(string: tail!) else {return code} + if components.path == "" { + code.isPayRequest = true + } else { + code.functionName = components.path + } + guard let queryItems = components.queryItems else {return code} + var inputNumber: Int = 0 + var inputs = [ABI.Element.InOut]() + for comp in queryItems { + if let inputType = try? ABITypeParser.parseTypeString(comp.name) { + guard let value = comp.value else {continue} + var nativeValue: AnyObject? = nil + switch inputType { + case .address: + let val = EIP681Code.TargetAddress(value) + switch val { + case .ethereumAddress(let ethereumAddress): + nativeValue = ethereumAddress as AnyObject +// default: +// return nil + case .ensAddress(let ens): + do { + let web = web3(provider: InfuraProvider(Networks.fromInt(Int(code.chainID ?? 1)) ?? Networks.Mainnet)!) + let ensModel = ENS(web3: web) + try ensModel?.setENSResolver(withDomain: ens) + let address = try ensModel?.getAddress(forNode: ens) + nativeValue = address as AnyObject + } catch { + return nil + } + } + case .uint(bits: _): + if let val = BigUInt(value, radix: 10) { + nativeValue = val as AnyObject + } else if let val = BigUInt(value.stripHexPrefix(), radix: 16) { + nativeValue = val as AnyObject + } + case .int(bits: _): + if let val = BigInt(value, radix: 10) { + nativeValue = val as AnyObject + } else if let val = BigInt(value.stripHexPrefix(), radix: 16) { + nativeValue = val as AnyObject + } + case .string: + nativeValue = value as AnyObject + case .dynamicBytes: + if let val = Data.fromHex(value) { + nativeValue = val as AnyObject + } else if let val = value.data(using: .utf8) { + nativeValue = val as AnyObject + } + case .bytes(length: _): + if let val = Data.fromHex(value) { + nativeValue = val as AnyObject + } else if let val = value.data(using: .utf8) { + nativeValue = val as AnyObject + } + case .bool: + switch value { + case "true","True", "TRUE", "1": + nativeValue = true as AnyObject + case "false", "False", "FALSE", "0": + nativeValue = false as AnyObject + default: + nativeValue = true as AnyObject + } + default: + continue + } + if nativeValue != nil { + inputs.append(ABI.Element.InOut(name: String(inputNumber), type: inputType)) + code.parameters.append(EIP681Code.EIP681Parameter(type: inputType, value: nativeValue!)) + inputNumber = inputNumber + 1 + } else { + return nil + } + } else { + switch comp.name { + case "value": + guard let value = comp.value else {return nil} + let splittedValue = value.split(separator: "e") + if splittedValue.count <= 1 { + guard let val = BigUInt(value, radix: 10) else {return nil } + code.amount = val + } else if splittedValue.count == 2 { + guard let power = Double(splittedValue[1]) else { return nil } + let splittedNumber = String(splittedValue[0]).replacingOccurrences(of: ",", with: ".").split(separator: ".") + var a = BigUInt(pow(10, power)) + if splittedNumber.count == 1 { + guard let number = BigUInt(splittedNumber[0], radix: 10) else { return nil } + code.amount = number * a + } else if splittedNumber.count == 2 { + let stringNumber = String(splittedNumber[0]) + String(splittedNumber[1]) + let am = BigUInt(pow(10, Double(splittedNumber[1].count))) + a = a / am + guard let number = BigUInt(stringNumber, radix: 10) else { return nil } + code.amount = number * a + } else { return nil } + } else { return nil } + + case "gas": + guard let value = comp.value else {return nil} + guard let val = BigUInt(value, radix: 10) else {return nil} + code.gasLimit = val + case "gasLimit": + guard let value = comp.value else {return nil} + guard let val = BigUInt(value, radix: 10) else {return nil} + code.gasLimit = val + case "gasPrice": + guard let value = comp.value else {return nil} + guard let val = BigUInt(value, radix: 10) else {return nil} + code.gasPrice = val + default: + continue + } + } + } + + if code.functionName != nil { + let functionEncoding = ABI.Element.Function(name: code.functionName!, inputs: inputs, outputs: [ABI.Element.InOut](), constant: false, payable: code.amount != nil) + code.function = functionEncoding + } + + print(code) + return code + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ENS.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ENS.swift new file mode 100755 index 000000000..ec8af0c23 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ENS.swift @@ -0,0 +1,286 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +public class ENS { + + public let web3: web3 + public var registry: Registry + public var resolver: Resolver? = nil + public var baseRegistrar: BaseRegistrar? = nil + public var registrarController: ETHRegistrarController? = nil + public var reverseRegistrar: ReverseRegistrar? = nil + + public init?(web3: web3) { + self.web3 = web3 + guard let registry = Registry(web3: web3) else { + return nil + } + self.registry = registry + } + + public func setENSResolver(_ resolver: Resolver) throws { + guard resolver.web3.provider.url == self.web3.provider.url else { + throw Web3Error.processingError(desc: "Resolver should use same provider as ENS") + } + self.resolver = resolver + } + + public func setENSResolver(withDomain domain: String) throws { + guard let resolver = try? self.registry.getResolver(forDomain: domain) else { + throw Web3Error.processingError(desc: "No resolver for this domain") + } + self.resolver = resolver + } + + public func setBaseRegistrar(_ baseRegistrar: BaseRegistrar) throws { + guard baseRegistrar.web3.provider.url == self.web3.provider.url else { + throw Web3Error.processingError(desc: "Base registrar should use same provider as ENS") + } + self.baseRegistrar = baseRegistrar + } + + public func setBaseRegistrar(withAddress address: EthereumAddress) { + let baseRegistrar = BaseRegistrar(web3: web3, address: address) + self.baseRegistrar = baseRegistrar + } + + public func setRegistrarController(_ registrarController: ETHRegistrarController) throws { + guard registrarController.web3.provider.url == self.web3.provider.url else { + throw Web3Error.processingError(desc: "Registrar controller should use same provider as ENS") + } + self.registrarController = registrarController + } + + public func setRegistrarController(withAddress address: EthereumAddress) { + let registrarController = ETHRegistrarController(web3: web3, address: address) + self.registrarController = registrarController + } + + public func setReverseRegistrar(_ reverseRegistrar: ReverseRegistrar) throws { + guard reverseRegistrar.web3.provider.url == self.web3.provider.url else { + throw Web3Error.processingError(desc: "Registrar controller should use same provider as ENS") + } + self.reverseRegistrar = reverseRegistrar + } + + public func setReverseRegistrar(withAddress address: EthereumAddress) { + let reverseRegistrar = ReverseRegistrar(web3: web3, address: address) + self.reverseRegistrar = reverseRegistrar + } + + lazy var defaultOptions: TransactionOptions = { + return TransactionOptions.defaultOptions + }() + + //MARK: - Convenience public resolver methods + public func getAddress(forNode node: String) throws -> EthereumAddress { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isAddrSupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.addr.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isAddrSupports else { + throw Web3Error.processingError(desc: "Address isn't supported") + } + guard let addr = try? resolver.getAddress(forNode: node) else { + throw Web3Error.processingError(desc: "Can't get address") + } + return addr + } + + public func setAddress(forNode node: String, address: EthereumAddress, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isAddrSupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.addr.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isAddrSupports else { + throw Web3Error.processingError(desc: "Address isn't supported") + } + var options = options ?? defaultOptions + options.to = resolver.resolverContractAddress + guard let result = try? resolver.setAddress(forNode: node, address: address, options: options, password: password) else { + throw Web3Error.processingError(desc: "Can't get result") + } + return result + } + + public func getName(forNode node: String) throws -> String { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isNameSupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.name.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isNameSupports else { + throw Web3Error.processingError(desc: "Name isn't supported") + } + guard let name = try? resolver.getCanonicalName(forNode: node) else { + throw Web3Error.processingError(desc: "Can't get name") + } + return name + } + + public func setName(forNode node: String, name: String, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isNameSupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.name.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isNameSupports else { + throw Web3Error.processingError(desc: "Name isn't supported") + } + var options = options ?? defaultOptions + options.to = resolver.resolverContractAddress + guard let result = try? resolver.setCanonicalName(forNode: node, name: name, options: options, password: password) else { + throw Web3Error.processingError(desc: "Can't get result") + } + return result + } + + public func getContent(forNode node: String) throws -> String { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isContentSupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.content.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isContentSupports else { + throw Web3Error.processingError(desc: "Content isn't supported") + } + guard let content = try? resolver.getContentHash(forNode: node) else { + throw Web3Error.processingError(desc: "Can't get content") + } + return content + } + + public func setContent(forNode node: String, hash: String, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isContentSupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.content.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isContentSupports else { + throw Web3Error.processingError(desc: "Content isn't supported") + } + var options = options ?? defaultOptions + options.to = resolver.resolverContractAddress + guard let result = try? resolver.setContentHash(forNode: node, hash: hash, options: options, password: password) else { + throw Web3Error.processingError(desc: "Can't get result") + } + return result + } + + public func getABI(forNode node: String, contentType: ENS.Resolver.ContentType) throws -> (BigUInt, Data) { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isABISupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.ABI.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isABISupports else { + throw Web3Error.processingError(desc: "ABI isn't supported") + } + guard let abi = try? resolver.getContractABI(forNode: node, contentType: contentType) else { + throw Web3Error.processingError(desc: "Can't get ABI") + } + return abi + } + + public func setABI(forNode node: String, contentType: ENS.Resolver.ContentType, data: Data, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isABISupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.ABI.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isABISupports else { + throw Web3Error.processingError(desc: "ABI isn't supported") + } + var options = options ?? defaultOptions + options.to = resolver.resolverContractAddress + guard let result = try? resolver.setContractABI(forNode: node, contentType: contentType, data: data, options: options, password: password) else { + throw Web3Error.processingError(desc: "Can't get result") + } + return result + } + + public func getPublicKey(forNode node: String) throws -> PublicKey { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isPKSupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.pubkey.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isPKSupports else { + throw Web3Error.processingError(desc: "Public Key isn't supported") + } + guard let pk = try? resolver.getPublicKey(forNode: node) else { + throw Web3Error.processingError(desc: "Can't get Public Key") + } + return pk + } + + public func setPublicKey(forNode node: String, publicKey: PublicKey, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isPKSupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.pubkey.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isPKSupports else { + throw Web3Error.processingError(desc: "Public Key isn't supported") + } + var options = options ?? defaultOptions + options.to = resolver.resolverContractAddress + guard let result = try? resolver.setPublicKey(forNode: node, publicKey: publicKey, options: options, password: password) else { + throw Web3Error.processingError(desc: "Can't get result") + } + return result + } + + public func getText(forNode node: String, key: String) throws -> String { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isTextSupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.text.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isTextSupports else { + throw Web3Error.processingError(desc: "Text isn't supported") + } + guard let text = try? resolver.getTextData(forNode: node, key: key) else { + throw Web3Error.processingError(desc: "Can't get text") + } + return text + } + + public func setText(forNode node: String, key: String, value: String, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + guard let resolver = try? self.registry.getResolver(forDomain: node) else { + throw Web3Error.processingError(desc: "Failed to get resolver for domain") + } + guard let isTextSupports = try? resolver.supportsInterface(interfaceID: Resolver.InterfaceName.text.hash()) else { + throw Web3Error.processingError(desc: "Resolver don't support interface with this ID") + } + guard isTextSupports else { + throw Web3Error.processingError(desc: "Text isn't supported") + } + var options = options ?? defaultOptions + options.to = resolver.resolverContractAddress + guard let result = try? resolver.setTextData(forNode: node, key: key, value: value, options: options, password: password) else { + throw Web3Error.processingError(desc: "Can't get result") + } + return result + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSBaseRegistrar.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSBaseRegistrar.swift new file mode 100644 index 000000000..4c1c89879 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSBaseRegistrar.swift @@ -0,0 +1,82 @@ +// +// BaseRegistrar.swift +// web3swift +// +// Created by Anton on 15/04/2019. +// Copyright © 2019 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +public extension ENS { + class BaseRegistrar: ERC721 { + lazy var defaultOptions: TransactionOptions = { + return TransactionOptions.defaultOptions + }() + + public init(web3: web3, address: EthereumAddress) { + super.init(web3: web3, provider: web3.provider, address: address) + guard let contract = self.web3.contract(Web3.Utils.baseRegistrarABI, at: self.address, abiVersion: 2) else { + return + } + self.contract = contract + } + + override public init(web3: web3, provider: Web3Provider, address: EthereumAddress) { + super.init(web3: web3, provider: provider, address: address) + guard let contract = self.web3.contract(Web3.Utils.baseRegistrarABI, at: self.address, abiVersion: 2) else { + return + } + self.contract = contract + } + + @available(*, message: "Available for only owner") + public func addController(from: EthereumAddress, controllerAddress: EthereumAddress) throws -> WriteTransaction { + defaultOptions.from = from + defaultOptions.to = self.address + guard let transaction = self.contract.write("addController", parameters: [controllerAddress as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + return transaction + } + + @available(*, message: "Available for only owner") + public func removeController(from: EthereumAddress, controllerAddress: EthereumAddress) throws -> WriteTransaction { + defaultOptions.from = from + defaultOptions.to = self.address + guard let transaction = self.contract.write("removeController", parameters: [controllerAddress as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + return transaction + } + + @available(*, message: "Available for only owner") + public func setResolver(from: EthereumAddress, resolverAddress: EthereumAddress) throws -> WriteTransaction { + defaultOptions.from = from + defaultOptions.to = self.address + guard let transaction = self.contract.write("setResolver", parameters: [resolverAddress as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + return transaction + } + + public func getNameExpirity(name: BigUInt) throws -> BigUInt { + guard let transaction = self.contract.read("nameExpires", parameters: [name as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let expirity = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Can't get answer")} + return expirity + } + + @available(*, message: "This function should not be used to check if a name can be registered by a user. To check if a name can be registered by a user, check name availablility via the controller") + public func isNameAvailable(name: BigUInt) throws -> Bool { + guard let transaction = self.contract.read("available", parameters: [name as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) 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 reclaim(from: EthereumAddress, record: BigUInt) throws -> WriteTransaction { + defaultOptions.from = from + defaultOptions.to = self.address + guard let transaction = self.contract.write("reclaim", parameters: [record as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + return transaction + } + + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSRegistry.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSRegistry.swift new file mode 100644 index 000000000..b89f05086 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSRegistry.swift @@ -0,0 +1,110 @@ +// +// ENSRegistry.swift +// web3swift +// +// Created by Anton on 17/04/2019. +// Copyright © 2019 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +public extension ENS { + class Registry { + public let web3: web3 + public let registryContractAddress: EthereumAddress? + + public init?(web3: web3) { + self.web3 = web3 + switch web3.provider.network { + case .Mainnet?: + registryContractAddress = EthereumAddress("0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e") + case .Rinkeby?: + registryContractAddress = EthereumAddress("0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e") + case .Ropsten?: + registryContractAddress = EthereumAddress("0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e") + default: + let url = web3.provider.url.absoluteString + if url.contains("https://rpc.goerli.mudit.blog") + || url.contains("http://goerli.blockscout.com") + || url.contains("http://goerli.prylabs.net") + || url.contains("https://rpc.slock.it/goerli") { + registryContractAddress = EthereumAddress("0x112234455c3a32fd11230c42e7bccd4a84e02010") + } + return nil + } + } + + lazy var defaultOptions: TransactionOptions = { + return TransactionOptions.defaultOptions + }() + + lazy var registryContract: web3.web3contract = { + let contract = self.web3.contract(Web3.Utils.ensRegistryABI, at: self.registryContractAddress, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + public func getOwner(node: String) throws -> EthereumAddress { + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.registryContract.read("owner", parameters: [nameHash as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let address = result["0"] as? EthereumAddress else {throw Web3Error.processingError(desc: "No address in result")} + return address + } + + public func getResolver(forDomain domain: String) throws -> Resolver { + guard let nameHash = NameHash.nameHash(domain) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.registryContract.read("resolver", parameters: [nameHash as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let resolverAddress = result["0"] as? EthereumAddress else {throw Web3Error.processingError(desc: "No address in result")} + return Resolver(web3: self.web3, resolverContractAddress: resolverAddress) + } + + public func getTTL(node: String) throws -> BigUInt { + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.registryContract.read("ttl", parameters: [nameHash as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let ans = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "No answer in result")} + return ans + } + + public func setOwner(node: String, owner: EthereumAddress, options: TransactionOptions?, password: String? = nil) throws -> TransactionSendingResult { + var options = options ?? defaultOptions + options.to = self.registryContractAddress + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.registryContract.write("setOwner", parameters: [nameHash, owner] as [AnyObject], extraData: Data(), transactionOptions: options) else {throw Web3Error.transactionSerializationError} + guard let result = password == nil ? try? transaction.send() : try? transaction.send(password: password!, transactionOptions: options) else {throw Web3Error.processingError(desc: "Can't send transaction")} + return result + } + + public func setSubnodeOwner(node: String, label: String, owner: EthereumAddress, options: TransactionOptions?, password: String? = nil) throws -> TransactionSendingResult { + var options = options ?? defaultOptions + options.to = self.registryContractAddress + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let labelHash = NameHash.nameHash(label) else {throw Web3Error.processingError(desc: "Failed to get label hash")} + guard let transaction = self.registryContract.write("setSubnodeOwner", parameters: [nameHash, labelHash, owner] as [AnyObject], extraData: Data(), transactionOptions: options) else {throw Web3Error.transactionSerializationError} + guard let result = password == nil ? try? transaction.send() : try? transaction.send(password: password!, transactionOptions: options) else {throw Web3Error.processingError(desc: "Can't send transaction")} + return result + } + + public func setResolver(node: String, resolver: EthereumAddress, options: TransactionOptions?, password: String? = nil) throws -> TransactionSendingResult { + var options = options ?? defaultOptions + options.to = self.registryContractAddress + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.registryContract.write("setResolver", parameters: [nameHash, resolver] as [AnyObject], extraData: Data(), transactionOptions: options) else {throw Web3Error.transactionSerializationError} + guard let result = password == nil ? try? transaction.send() : try? transaction.send(password: password!, transactionOptions: options) else {throw Web3Error.processingError(desc: "Can't send transaction")} + return result + } + + public func setTTL(node: String, ttl: BigUInt, options: TransactionOptions?, password: String? = nil) throws -> TransactionSendingResult { + var options = options ?? defaultOptions + options.to = self.registryContractAddress + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.registryContract.write("setTTL", parameters: [nameHash, ttl] as [AnyObject], extraData: Data(), transactionOptions: options) else {throw Web3Error.transactionSerializationError} + guard let result = password == nil ? try? transaction.send() : try? transaction.send(password: password!, transactionOptions: options) else {throw Web3Error.processingError(desc: "Can't send transaction")} + return result + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSResolver.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSResolver.swift new file mode 100755 index 000000000..67176af8d --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSResolver.swift @@ -0,0 +1,196 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +public extension ENS { + class Resolver { + public let web3: web3 + public let resolverContractAddress: EthereumAddress + + public enum ContentType: BigUInt { + case JSON = 1 + case zlibCompressedJSON = 2 + case CBOR = 4 + case URI = 8 + } + + public enum InterfaceName { + case addr + case name + case content + case ABI + case pubkey + case text + + func hash() -> String { + switch self { + case .addr: + return "0x3b3b57de" + case .name: + return "0x691f3431" + case .content: + return "0xbc1c58d1" + case .ABI: + return "0x2203ab56" + case .pubkey: + return "0xc8690233" + case .text: + return "0x59d1d43c" + } + } + } + + lazy var resolverContract: web3.web3contract = { + let contract = self.web3.contract(Web3.Utils.resolverABI, at: self.resolverContractAddress, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + lazy var defaultOptions: TransactionOptions = { + return TransactionOptions.defaultOptions + }() + + public init(web3: web3, resolverContractAddress: EthereumAddress) { + self.web3 = web3 + self.resolverContractAddress = resolverContractAddress + } + + public func supportsInterface(interfaceID: Data) throws -> Bool { + guard let supports = try? supportsInterface(interfaceID: interfaceID.toHexString()) else {throw Web3Error.processingError(desc: "Can't get answer")} + return supports + } + + public func supportsInterface(interfaceID: String) throws -> Bool { + guard let transaction = self.resolverContract.read("supportsInterface", parameters: [interfaceID as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let supports = result["0"] as? Bool else {throw Web3Error.processingError(desc: "Can't get answer")} + return supports + } + + public func interfaceImplementer(forNode node: String, interfaceID: String) throws -> EthereumAddress { + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.read("interfaceImplementer", parameters: [nameHash, interfaceID] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let address = result["0"] as? EthereumAddress else {throw Web3Error.processingError(desc: "Can't get address")} + return address + } + + public func getAddress(forNode node: String) throws -> EthereumAddress { + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.read("addr", parameters: [nameHash as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let address = result["0"] as? EthereumAddress else {throw Web3Error.processingError(desc: "Can't get address")} + return address + } + + @available(*, message: "Available for only owner") + public func setAddress(forNode node: String, address: EthereumAddress, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + var options = options ?? defaultOptions + options.to = self.resolverContractAddress + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.write("setAddr", parameters: [nameHash, address] as [AnyObject], extraData: Data(), transactionOptions: options) else {throw Web3Error.transactionSerializationError} + guard let result = password == nil ? try? transaction.send() : try? transaction.send(password: password!, transactionOptions: options) else {throw Web3Error.processingError(desc: "Can't send transaction")} + return result + } + + public func getCanonicalName(forNode node: String) throws -> String { + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.read("name", parameters: [nameHash as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let name = result["0"] as? String else {throw Web3Error.processingError(desc: "Can't get name")} + return name + } + + @available(*, message: "Available for only owner") + func setCanonicalName(forNode node: String, name: String, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + var options = options ?? defaultOptions + options.to = self.resolverContractAddress + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.write("setName", parameters: [nameHash, name] as [AnyObject], extraData: Data(), transactionOptions: options) else {throw Web3Error.transactionSerializationError} + guard let result = password == nil ? try? transaction.send() : try? transaction.send(password: password!, transactionOptions: options) else {throw Web3Error.processingError(desc: "Can't send transaction")} + return result + } + + func getContentHash(forNode node: String) throws -> String { + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.read("contenthash", parameters: [nameHash] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let content = result["0"] as? String else {throw Web3Error.processingError(desc: "Can't get content")} + return content + } + + @available(*, message: "Available for only owner") + func setContentHash(forNode node: String, hash: String, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + var options = options ?? defaultOptions + options.to = self.resolverContractAddress + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.write("setContenthash", parameters: [nameHash, hash] as [AnyObject], extraData: Data(), transactionOptions: options) else {throw Web3Error.transactionSerializationError} + guard let result = password == nil ? try? transaction.send() : try? transaction.send(password: password!, transactionOptions: options) else {throw Web3Error.processingError(desc: "Can't send transaction")} + return result + } + + public func getContractABI(forNode node: String, contentType: ENS.Resolver.ContentType) throws -> (BigUInt, Data) { + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.read("ABI", parameters: [nameHash, contentType.rawValue] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let encoding = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Can't get encoding")} + guard let data = result["1"] as? Data else {throw Web3Error.processingError(desc: "Can't get data")} + return (encoding, data) + } + + @available(*, message: "Available for only owner") + func setContractABI(forNode node: String, contentType: ENS.Resolver.ContentType, data: Data, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + var options = options ?? defaultOptions + options.to = self.resolverContractAddress + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.write("setABI", parameters: [nameHash, contentType.rawValue, data] as [AnyObject], extraData: Data(), transactionOptions: options) else {throw Web3Error.transactionSerializationError} + guard let result = password == nil ? try? transaction.send() : try? transaction.send(password: password!, transactionOptions: options) else {throw Web3Error.processingError(desc: "Can't send transaction")} + return result + } + + public func getPublicKey(forNode node: String) throws -> PublicKey { + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.read("pubkey", parameters: [nameHash as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let x = result["x"] as? Data else {throw Web3Error.processingError(desc: "Can't get x")} + guard let y = result["y"] as? Data else {throw Web3Error.processingError(desc: "Can't get y")} + let pubkey = PublicKey(x: "0x" + x.toHexString(), y: "0x" + y.toHexString()) + return pubkey + } + + @available(*, message: "Available for only owner") + public func setPublicKey(forNode node: String, publicKey: PublicKey, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + var options = options ?? defaultOptions + options.to = self.resolverContractAddress + let pubkeyWithoutPrefix = publicKey.getComponentsWithoutPrefix() + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.write("setPubkey", parameters: [nameHash, pubkeyWithoutPrefix.x, pubkeyWithoutPrefix.y] as [AnyObject], extraData: Data(), transactionOptions: options) else {throw Web3Error.transactionSerializationError} + guard let result = password == nil ? try? transaction.send() : try? transaction.send(password: password!, transactionOptions: options) else {throw Web3Error.processingError(desc: "Can't send transaction")} + return result + } + + public func getTextData(forNode node: String, key: String) throws -> String { + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.read("text", parameters: [nameHash, key] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let text = result["0"] as? String else {throw Web3Error.processingError(desc: "Can't get text")} + return text + } + + @available(*, message: "Available for only owner") + public func setTextData(forNode node: String, key: String, value: String, options: TransactionOptions? = nil, password: String? = nil) throws -> TransactionSendingResult { + var options = options ?? defaultOptions + options.to = self.resolverContractAddress + guard let nameHash = NameHash.nameHash(node) else {throw Web3Error.processingError(desc: "Failed to get name hash")} + guard let transaction = self.resolverContract.write("setText", parameters: [nameHash, key, value] as [AnyObject], extraData: Data(), transactionOptions: options) else {throw Web3Error.transactionSerializationError} + guard let result = password == nil ? try? transaction.send() : try? transaction.send(password: password!, transactionOptions: options) else {throw Web3Error.processingError(desc: "Can't send transaction")} + return result + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSReverseRegistrar.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSReverseRegistrar.swift new file mode 100644 index 000000000..b6440a0c9 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSReverseRegistrar.swift @@ -0,0 +1,68 @@ +// +// ENSReverseRegistrar.swift +// web3swift +// +// Created by Anton on 20/04/2019. +// Copyright © 2019 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +public extension ENS { + class ReverseRegistrar { + public let web3: web3 + public let address: EthereumAddress + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(Web3.Utils.reverseRegistrarABI, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + lazy var defaultOptions: TransactionOptions = { + return TransactionOptions.defaultOptions + }() + + public init(web3: web3, address: EthereumAddress) { + self.web3 = web3 + self.address = address + } + + public func claimAddress(from: EthereumAddress, owner: EthereumAddress) throws -> WriteTransaction { + defaultOptions.from = from + defaultOptions.to = self.address + guard let transaction = self.contract.write("claim", parameters: [owner as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + return transaction + } + + public func claimAddressWithResolver(from: EthereumAddress, owner: EthereumAddress, resolver: EthereumAddress) throws -> WriteTransaction { + defaultOptions.from = from + defaultOptions.to = self.address + guard let transaction = self.contract.write("claimWithResolver", parameters: [owner, resolver] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + return transaction + } + + public func setName(from: EthereumAddress, name: String) throws -> WriteTransaction { + defaultOptions.from = from + defaultOptions.to = self.address + guard let transaction = self.contract.write("setName", parameters: [name] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + return transaction + } + + public func getReverseRecordName(address: EthereumAddress) throws -> Data { + guard let transaction = self.contract.read("node", parameters: [address] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) 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 + } + + public func getDefaultResolver() throws -> EthereumAddress { + guard let transaction = self.contract.read("defaultResolver", parameters: [] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) 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/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ETHRegistrarController.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ETHRegistrarController.swift new file mode 100644 index 000000000..88c8a7f83 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/ETHRegistrarController.swift @@ -0,0 +1,93 @@ +// +// RegistrarController.swift +// web3swift +// +// Created by Anton on 15/04/2019. +// Copyright © 2019 The Matter Inc. All rights reserved. +// + +import Foundation +import BigInt + +public extension ENS { + class ETHRegistrarController { + public let web3: web3 + public let address: EthereumAddress + + lazy var contract: web3.web3contract = { + let contract = self.web3.contract(Web3.Utils.ethRegistrarControllerABI, at: self.address, abiVersion: 2) + precondition(contract != nil) + return contract! + }() + + lazy var defaultOptions: TransactionOptions = { + return TransactionOptions.defaultOptions + }() + + public init(web3: web3, address: EthereumAddress) { + self.web3 = web3 + self.address = address + } + + public func getRentPrice(name: String, duration: UInt) throws -> BigUInt { + guard let transaction = self.contract.read("rentPrice", parameters: [name, duration] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) 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) throws -> Bool { + guard let transaction = self.contract.read("valid", parameters: [name] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) 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) throws -> Bool { + guard let transaction = self.contract.read("available", parameters: [name as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) 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) throws -> Data { + guard let transaction = self.contract.read("makeCommitment", parameters: [name, owner.address, secret] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + guard let result = try? transaction.call(transactionOptions: defaultOptions) 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 -> WriteTransaction { + defaultOptions.from = from + defaultOptions.to = self.address + guard let transaction = self.contract.write("commit", parameters: [commitment as AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + return transaction + } + + public func registerName(from: EthereumAddress, name: String, owner: EthereumAddress, duration: UInt, secret: String, price: String) throws -> WriteTransaction { + guard let amount = Web3.Utils.parseToBigUInt(price, units: .eth) else {throw Web3Error.inputError(desc: "Wrong price: no way for parsing to ether units")} + defaultOptions.value = amount + defaultOptions.from = from + defaultOptions.to = self.address + guard let transaction = self.contract.write("register", parameters: [name, owner.address, duration, secret] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + return transaction + } + + public func extendNameRegistration(from: EthereumAddress, name: String, duration: UInt32, price: String) throws -> WriteTransaction { + guard let amount = Web3.Utils.parseToBigUInt(price, units: .eth) else {throw Web3Error.inputError(desc: "Wrong price: no way for parsing to ether units")} + defaultOptions.value = amount + defaultOptions.from = from + defaultOptions.to = self.address + guard let transaction = self.contract.write("renew", parameters: [name, duration] as [AnyObject], extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + return transaction + } + + @available(*, message: "Available for only owner") + public func withdraw(from: EthereumAddress) throws -> WriteTransaction { + defaultOptions.from = from + defaultOptions.to = self.address + guard let transaction = self.contract.write("withdraw", parameters: [AnyObject](), extraData: Data(), transactionOptions: defaultOptions) else {throw Web3Error.transactionSerializationError} + return transaction + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/NameHash.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/NameHash.swift new file mode 100755 index 000000000..2a96a9ca4 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/NameHash.swift @@ -0,0 +1,52 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import CryptoSwift + +public struct NameHash { + public static func normalizeDomainName(_ domain: String) -> String? { + // TODO use ICU4C library later for domain name normalization, althoug f**k it for now, it's few megabytes large piece + let normalized = domain.lowercased() + return normalized + } + + public static func nameHash(_ domain: String) -> Data? { + guard let normalized = NameHash.normalizeDomainName(domain) else {return nil} + return namehash(normalized) + } + + static func namehash(_ name: String) -> Data? { + if name == "" { + return Data(repeating: 0, count: 32) + } + let parts = name.split(separator: ".") + guard parts.count > 0 else { + return nil + } + guard let lowerLevel = parts.first else { + return nil + } + var remainder = "" + if parts.count > 1 { + remainder = parts[1 ..< parts.count].joined(separator: ".") + } + // TODO here some better normalization can happen + var hashData = Data() + guard let remainderHash = namehash(remainder) else { + return nil + } + guard let labelData = lowerLevel.data(using: .utf8) else { + return nil + } + hashData.append(remainderHash) + hashData.append(labelData.sha3(.keccak256)) + let hash = hashData.sha3(.keccak256) + print(name) + print(hash.toHexString()) + return hash + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/PublicKey.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/PublicKey.swift new file mode 100644 index 000000000..f7b000d40 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/ENS/PublicKey.swift @@ -0,0 +1,26 @@ +// +// PublicKey.swift +// web3swift +// +// Created by Anton on 17/04/2019. +// Copyright © 2019 The Matter Inc. All rights reserved. +// + +import Foundation + +public struct PublicKey { + public let x: String + public let y: String + + public func getComponentsWithoutPrefix() -> PublicKey { + var x = self.x + var y = self.y + if x.hasHexPrefix() { + x.removeFirst(2) + } + if y.hasHexPrefix() { + y.removeFirst(2) + } + return PublicKey(x: x, y: y) + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/Hooks/NonceMiddleware.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/Hooks/NonceMiddleware.swift new file mode 100755 index 000000000..127f302f6 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Utils/Hooks/NonceMiddleware.swift @@ -0,0 +1,111 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +//import EthereumAddress +import BigInt +import PromiseKit + +extension Web3.Utils { + + fileprivate typealias AssemblyHook = web3.AssemblyHook + fileprivate typealias SubmissionResultHook = web3.SubmissionResultHook + + public class NonceMiddleware: EventLoopRunnableProtocol { + var web3: web3? + var nonceLookups: [EthereumAddress: BigUInt] = [EthereumAddress: BigUInt]() + public var name: String = "Nonce lookup middleware" + public let queue: DispatchQueue = DispatchQueue(label: "Nonce middleware queue") + public var synchronizationPeriod: TimeInterval = 300.0 // 5 minutes + var lastSyncTime: Date = Date() + + public func functionToRun() { + guard let w3 = self.web3 else {return} + var allPromises = [Promise]() + allPromises.reserveCapacity(self.nonceLookups.keys.count) + let knownKeys = Array(self.nonceLookups.keys) + for k in knownKeys { + let promise = w3.eth.getTransactionCountPromise(address: k, onBlock: "latest") + allPromises.append(promise) + } + when(resolved: allPromises).done(on: w3.requestDispatcher.queue) {results in + self.queue.async { + var i = 0 + for res in results { + switch res { + case .fulfilled(let newNonce): + let key = knownKeys[i] + self.nonceLookups[key] = newNonce + i = i + 1 + default: + i = i + 1 + } + } + } + + } + } + + public init() { + + } + + func preAssemblyFunction(tx: EthereumTransaction, contract: EthereumContract, transactionOptions: TransactionOptions) -> (EthereumTransaction, EthereumContract, TransactionOptions, Bool) { + guard let from = transactionOptions.from else { + // do nothing + return (tx, contract, transactionOptions, true) + } + guard let knownNonce = self.nonceLookups[from] else { + return (tx, contract, transactionOptions, true) + } + + let newNonce = knownNonce + 1 + + self.queue.async { + self.nonceLookups[from] = newNonce + } + // var modifiedTX = tx + // modifiedTX.nonce = newNonce + var newOptions = transactionOptions + newOptions.nonce = .manual(newNonce) + return (tx, contract, newOptions, true) + } + + func postSubmissionFunction(result: TransactionSendingResult) { + guard let from = result.transaction.sender else { + // do nothing + return + } + + let newNonce = result.transaction.nonce + + if let knownNonce = self.nonceLookups[from] { + if knownNonce != newNonce { + self.queue.async { + self.nonceLookups[from] = newNonce + } + } + return + } + self.queue.async { + self.nonceLookups[from] = newNonce + } + return + } + + public func attach(_ web3: web3) { + self.web3 = web3 + web3.eventLoop.monitoredUserFunctions.append(self) + let preHook = AssemblyHook(queue: web3.requestDispatcher.queue, function: self.preAssemblyFunction) + web3.preAssemblyHooks.append(preHook) + let postHook = SubmissionResultHook(queue: web3.requestDispatcher.queue, function: self.postSubmissionFunction) + web3.postSubmissionHooks.append(postHook) + } + + } + + +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Constants.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Constants.swift new file mode 100644 index 000000000..e975b617e --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Constants.swift @@ -0,0 +1,15 @@ +// +// Web3+Constants.swift +// web3swift +// +// Created by Anton on 24/06/2019. +// Copyright © 2019 Matter Labs. All rights reserved. +// + +import Foundation + +struct Constants { + static let infuraHttpScheme = ".infura.io/v3/" + static let infuraWsScheme = ".infura.io/ws/v3/" + static let infuraToken = "4406c3acf862426c83991f1752c46dd8" +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Contract.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Contract.swift new file mode 100755 index 000000000..93e49f3a6 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Contract.swift @@ -0,0 +1,116 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +extension web3 { + + /// The contract instance. Initialized in runtime from ABI string (that is a JSON array). In addition an existing contract address can be supplied to provide the default "to" address in all the following requests. ABI version is 2 by default and should not be changed. + public func contract(_ abiString: String, at: EthereumAddress? = nil, abiVersion: Int = 2) -> web3contract? { + return web3contract(web3: self, abiString: abiString, at: at, transactionOptions: self.transactionOptions, abiVersion: abiVersion) + } + + /// Web3 instance bound contract instance. + public class web3contract { + var contract: EthereumContract + var web3 : web3 + public var transactionOptions: TransactionOptions? = nil + + + /// Initialize the bound contract instance by supplying the Web3 provider bound object, ABI, Ethereum address and some default + /// options for further function calls. By default the contract inherits options from the web3 object. Additionally supplied "options" + /// do override inherited ones. + public init?(web3 web3Instance:web3, abiString: String, at: EthereumAddress? = nil, transactionOptions: TransactionOptions? = nil, abiVersion: Int = 2) { + self.web3 = web3Instance + self.transactionOptions = web3.transactionOptions + switch abiVersion { + case 1: + print("ABIv1 bound contract is now deprecated") + return nil + case 2: + guard let c = EthereumContract(abiString, at: at) else {return nil} + contract = c + default: + return nil + } + var mergedOptions = self.transactionOptions?.merge(transactionOptions) + if at != nil { + contract.address = at + mergedOptions?.to = at + } else if let addr = mergedOptions?.to { + contract.address = addr + } + self.transactionOptions = mergedOptions + } + + /// Deploys a constact instance using the previously provided (at initialization) ABI, some bytecode, constructor parameters and options. + /// If extraData is supplied it is appended to encoded bytecode and constructor parameters. + /// + /// Returns a "Transaction intermediate" object. + public func deploy(bytecode: Data, parameters: [AnyObject] = [AnyObject](), extraData: Data = Data(), transactionOptions: TransactionOptions? = nil) -> WriteTransaction? { + let mergedOptions = self.transactionOptions?.merge(transactionOptions) + guard var tx = self.contract.deploy(bytecode: bytecode, parameters: parameters, extraData: extraData) else {return nil} + tx.chainID = self.web3.provider.network?.chainID + let writeTX = WriteTransaction.init(transaction: tx, web3: self.web3, contract: self.contract, method: "fallback", transactionOptions: mergedOptions) + return writeTX + } + + /// Creates and object responsible for calling a particular function of the contract. If method name is not found in ABI - returns nil. + /// If extraData is supplied it is appended to encoded function parameters. Can be usefull if one wants to call + /// the function not listed in ABI. "Parameters" should be an array corresponding to the list of parameters of the function. + /// Elements of "parameters" can be other arrays or instances of String, Data, BigInt, BigUInt, Int or EthereumAddress. + /// + /// Returns a "Transaction intermediate" object. + public func method(_ method:String = "fallback", parameters: [AnyObject] = [AnyObject](), extraData: Data = Data(), transactionOptions: TransactionOptions? = nil) -> WriteTransaction? { + let mergedOptions = self.transactionOptions?.merge(transactionOptions) + guard var tx = self.contract.method(method, parameters: parameters, extraData: extraData) else {return nil} + tx.chainID = self.web3.provider.network?.chainID + let writeTX = WriteTransaction.init(transaction: tx, web3: self.web3, contract: self.contract, method: method, transactionOptions: mergedOptions) + return writeTX + } + + /// Creates and object responsible for calling a particular function of the contract. If method name is not found in ABI - returns nil. + /// If extraData is supplied it is appended to encoded function parameters. Can be usefull if one wants to call + /// the function not listed in ABI. "Parameters" should be an array corresponding to the list of parameters of the function. + /// Elements of "parameters" can be other arrays or instances of String, Data, BigInt, BigUInt, Int or EthereumAddress. + /// + /// Returns a "Transaction intermediate" object. + public func read(_ method:String = "fallback", parameters: [AnyObject] = [AnyObject](), extraData: Data = Data(), transactionOptions: TransactionOptions? = nil) -> ReadTransaction? { + let mergedOptions = self.transactionOptions?.merge(transactionOptions) + guard var tx = self.contract.method(method, parameters: parameters, extraData: extraData) else {return nil} + tx.chainID = self.web3.provider.network?.chainID + let writeTX = ReadTransaction.init(transaction: tx, web3: self.web3, contract: self.contract, method: method, transactionOptions: mergedOptions) + return writeTX + } + + /// Creates and object responsible for calling a particular function of the contract. If method name is not found in ABI - returns nil. + /// If extraData is supplied it is appended to encoded function parameters. Can be usefull if one wants to call + /// the function not listed in ABI. "Parameters" should be an array corresponding to the list of parameters of the function. + /// Elements of "parameters" can be other arrays or instances of String, Data, BigInt, BigUInt, Int or EthereumAddress. + /// + /// Returns a "Transaction intermediate" object. + public func write(_ method:String = "fallback", parameters: [AnyObject] = [AnyObject](), extraData: Data = Data(), transactionOptions: TransactionOptions? = nil) -> WriteTransaction? { + let mergedOptions = self.transactionOptions?.merge(transactionOptions) + guard var tx = self.contract.method(method, parameters: parameters, extraData: extraData) else {return nil} + tx.chainID = self.web3.provider.network?.chainID + let writeTX = WriteTransaction.init(transaction: tx, web3: self.web3, contract: self.contract, method: method, transactionOptions: mergedOptions) + return writeTX + } + + /// Parses an EventLog object by using a description from the contract's ABI. + public func parseEvent(_ eventLog: EventLog) -> (eventName:String?, eventData:[String:Any]?) { + return self.contract.parseEvent(eventLog) + } + + /// Creates an "EventParserProtocol" compliant object to use it for parsing particular block or transaction for events. + public func createEventParser(_ eventName:String, filter:EventFilter?) -> EventParserProtocol? { + let parser = EventParser(web3: self.web3, eventName: eventName, contract: self.contract, filter: filter) + return parser + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Eth+Websocket.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Eth+Websocket.swift new file mode 100644 index 000000000..46d76146b --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Eth+Websocket.swift @@ -0,0 +1,42 @@ +// +// Web3+Eth+Websocket.swift +// web3swift +// +// Created by Anton on 03/04/2019. +// Copyright © 2019 The Matter Inc. All rights reserved. +// +import Foundation +import BigInt +import PromiseKit +import Starscream + + +extension web3.Eth { + + public func getWebsocketProvider(forDelegate delegate: Web3SocketDelegate) throws -> InfuraWebsocketProvider { + var infuraWSProvider: InfuraWebsocketProvider + if !(provider is InfuraWebsocketProvider) { + guard let infuraNetwork = provider.network else { + throw Web3Error.processingError(desc: "Wrong network") + } + guard let infuraProvider = InfuraWebsocketProvider(infuraNetwork, delegate: delegate, keystoreManager: provider.attachedKeystoreManager) else { + throw Web3Error.processingError(desc: "Wrong network") + } + infuraWSProvider = infuraProvider + } else { + infuraWSProvider = provider as! InfuraWebsocketProvider + } + infuraWSProvider.connectSocket() + return infuraWSProvider + } + + public func getLatestPendingTransactions(forDelegate delegate: Web3SocketDelegate) throws { + let provider = try getWebsocketProvider(forDelegate: delegate) + try provider.setFilterAndGetChanges(method: .newPendingTransactionFilter) + } + + public func subscribeOnPendingTransactions(forDelegate delegate: Web3SocketDelegate) throws { + let provider = try getWebsocketProvider(forDelegate: delegate) + try provider.subscribeOnNewPendingTransactions() + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Eth.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Eth.swift new file mode 100755 index 000000000..134791c1d --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Eth.swift @@ -0,0 +1,358 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +extension web3.Eth { + + /// Send an EthereumTransaction object to the network. Transaction is either signed locally if there is a KeystoreManager + /// object bound to the web3 instance, or sent unsigned to the node. For local signing the password is required. + /// + /// "options" object can override the "to", "gasPrice", "gasLimit" and "value" parameters is pre-formed transaction. + /// "from" field in "options" is mandatory for both local and remote signing. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func sendTransaction(_ transaction: EthereumTransaction, transactionOptions: TransactionOptions, password:String = "web3swift") throws -> TransactionSendingResult { + let result = try self.sendTransactionPromise(transaction, transactionOptions: transactionOptions, password: password).wait() + return result + } + + /// Performs a non-mutating "call" to some smart-contract. EthereumTransaction bears all function parameters required for the call. + /// Does NOT decode the data returned from the smart-contract. + /// "options" object can override the "to", "gasPrice", "gasLimit" and "value" parameters is pre-formed transaction. + /// "from" field in "options" is mandatory for both local and remote signing. + /// + /// "onString" field determines if value is returned based on the state of a blockchain on the latest mined block ("latest") + /// or the expected state after all the transactions in memory pool are applied ("pending"). + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + func call(_ transaction: EthereumTransaction, transactionOptions: TransactionOptions) throws -> Data { + let result = try self.callPromise(transaction, transactionOptions: transactionOptions).wait() + return result + } + + /// Send raw Ethereum transaction data to the network. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func sendRawTransaction(_ transaction: Data) throws -> TransactionSendingResult { + let result = try self.sendRawTransactionPromise(transaction).wait() + return result + } + + /// Send raw Ethereum transaction data to the network by first serializing the EthereumTransaction object. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func sendRawTransaction(_ transaction: EthereumTransaction) throws -> TransactionSendingResult { + let result = try self.sendRawTransactionPromise(transaction).wait() + return result + } + + /// Returns a total number of transactions sent by the particular Ethereum address. + /// + /// "onBlock" field determines if value is returned based on the state of a blockchain on the latest mined block ("latest") + /// or the expected state after all the transactions in memory pool are applied ("pending"). + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getTransactionCount(address: EthereumAddress, onBlock: String = "latest") throws -> BigUInt { + let result = try self.getTransactionCountPromise(address: address, onBlock: onBlock).wait() + return result + } + + /// Returns a balance of particular Ethereum address in Wei units (1 ETH = 10^18 Wei). + /// + /// "onString" field determines if value is returned based on the state of a blockchain on the latest mined block ("latest") + /// or the expected state after all the transactions in memory pool are applied ("pending"). + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getBalance(address: EthereumAddress, onBlock: String = "latest") throws -> BigUInt { + let result = try self.getBalancePromise(address: address, onBlock: onBlock).wait() + return result + } + + /// Returns a block number of the last mined block that Ethereum node knows about. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getBlockNumber() throws -> BigUInt { + let result = try self.getBlockNumberPromise().wait() + return result + } + + /// Returns a current gas price in the units of Wei. The node has internal algorithms for averaging over the last few blocks. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getGasPrice() throws -> BigUInt { + let result = try self.getGasPricePromise().wait() + return result + } + + /// Returns transaction details for particular transaction hash. Details indicate position of the transaction in a particular block, + /// as well as original transaction details such as value, gas limit, gas price, etc. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getTransactionDetails(_ txhash: Data) throws -> TransactionDetails { + let result = try self.getTransactionDetailsPromise(txhash).wait() + return result + } + + /// Returns transaction details for particular transaction hash. Details indicate position of the transaction in a particular block, + /// as well as original transaction details such as value, gas limit, gas price, etc. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getTransactionDetails(_ txhash: String) throws -> TransactionDetails { + let result = try self.getTransactionDetailsPromise(txhash).wait() + return result + } + + /// Returns transaction receipt for particular transaction hash. Receipt indicate what has happened when the transaction + /// was included in block, so it contains logs and status, such as succesful or failed transaction. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getTransactionReceipt(_ txhash: Data) throws -> TransactionReceipt { + let result = try self.getTransactionReceiptPromise(txhash).wait() + return result + } + + /// Returns transaction receipt for particular transaction hash. Receipt indicate what has happened when the transaction + /// was included in block, so it contains logs and status, such as succesful or failed transaction. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getTransactionReceipt(_ txhash: String) throws -> TransactionReceipt { + let result = try self.getTransactionReceiptPromise(txhash).wait() + return result + } + + /// Estimates a minimal amount of gas required to run a transaction. To do it the Ethereum node tries to run it and counts + /// how much gas it consumes for computations. Setting the transaction gas limit lower than the estimate will most likely + /// result in a failing transaction. + /// + /// "onString" field determines if value is returned based on the state of a blockchain on the latest mined block ("latest") + /// or the expected state after all the transactions in memory pool are applied ("pending"). + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + /// Error can also indicate that transaction is invalid in the current state, so formally it's gas limit is infinite. + /// An example of such transaction can be sending an amount of ETH that is larger than the current account balance. + public func estimateGas(_ transaction: EthereumTransaction, transactionOptions: TransactionOptions?) throws -> BigUInt { + let result = try self.estimateGasPromise(transaction, transactionOptions: transactionOptions).wait() + return result + } + + /// Get a list of Ethereum accounts that a node knows about. + /// If one has attached a Keystore Manager to the web3 object it returns accounts known to the keystore. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getAccounts() throws -> [EthereumAddress] { + let result = try self.getAccountsPromise().wait() + return result + } + + + /// Get information about the particular block in Ethereum network. If "fullTransactions" parameter is set to "true" + /// this call fill do a virtual join and fetch not just transaction hashes from this block, + /// but full decoded EthereumTransaction objects. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getBlockByHash(_ hash: String, fullTransactions: Bool = false) throws -> Block { + let result = try self.getBlockByHashPromise(hash, fullTransactions: fullTransactions).wait() + return result + } + + /// Get information about the particular block in Ethereum network. If "fullTransactions" parameter is set to "true" + /// this call fill do a virtual join and fetch not just transaction hashes from this block, + /// but full decoded EthereumTransaction objects. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getBlockByHash(_ hash: Data, fullTransactions: Bool = false) throws -> Block { + let result = try self.getBlockByHashPromise(hash, fullTransactions: fullTransactions).wait() + return result + } + + /// Get information about the particular block in Ethereum network. If "fullTransactions" parameter is set to "true" + /// this call fill do a virtual join and fetch not just transaction hashes from this block, + /// but full decoded EthereumTransaction objects. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getBlockByNumber(_ number: UInt64, fullTransactions: Bool = false) throws -> Block { + let result = try self.getBlockByNumberPromise(number, fullTransactions: fullTransactions).wait() + return result + } + + /// Get information about the particular block in Ethereum network. If "fullTransactions" parameter is set to "true" + /// this call fill do a virtual join and fetch not just transaction hashes from this block, + /// but full decoded EthereumTransaction objects. + /// + /// This function is synchronous! + /// + /// Returns the Result object that indicates either success of failure. + public func getBlockByNumber(_ number: BigUInt, fullTransactions: Bool = false) throws -> Block { + let result = try self.getBlockByNumberPromise(number, fullTransactions: fullTransactions).wait() + return result + } + + /// Get information about the particular block in Ethereum network. If "fullTransactions" parameter is set to "true" + /// this call fill do a virtual join and fetch not just transaction hashes from this block, + /// but full decoded EthereumTransaction objects. + /// + /// This function is synchronous! + /// + /// + public func getBlockByNumber(_ block:String, fullTransactions: Bool = false) throws -> Block { + let result = try self.getBlockByNumberPromise(block, fullTransactions: fullTransactions).wait() + return result + } + + + /** + Convenience wrapper to send Ethereum to another address. Internally it creates a virtual contract and encodes all the options and data. + - Parameters: + - to: EthereumAddress to send funds to + - amount: BigUInt indicating the amount in wei + - extraData: Additional data to attach to the transaction + - options: Web3Options to override the default gas price, gas limit. "Value" field of the options is ignored and the "amount" parameter is used instead + + - returns: + - TransactionIntermediate object + + */ + public func sendETH(to: EthereumAddress, amount: BigUInt, extraData: Data = Data(), transactionOptions: TransactionOptions? = nil) -> WriteTransaction? { + let contract = self.web3.contract(Web3.Utils.coldWalletABI, at: to, abiVersion: 2) + var mergedOptions = self.web3.transactionOptions.merge(transactionOptions) + mergedOptions.value = amount + let writeTX = contract?.write("fallback", extraData: extraData, transactionOptions: mergedOptions) + return writeTX + } + + /** + *Convenience wrapper to send Ethereum to another address. Internally it creates a virtual contract and encodes all the options and data.* + + - parameters: + - to: EthereumAddress to send funds to + - amount: String in "units" demonimation. It can contain either "," or "." decimal separator. + - units: Ethereum units indicating the denomination of amout about + - extraData: Additional data to attach to the transaction + - options: Web3Options to override the default gas price, gas limit. "Value" field of the options is ignored and the "amount" parameter is used instead + + - returns: + - TransactionIntermediate object + + * String "1.01" and units: .eth will result in sending 1.01 ETH to another address* + */ + public func sendETH(to: EthereumAddress, amount: String, units: Web3.Utils.Units = .eth, extraData: Data = Data(), transactionOptions: TransactionOptions? = nil) -> WriteTransaction? { + guard let value = Web3.Utils.parseToBigUInt(amount, units: .eth) else {return nil} + return sendETH(to: to, amount: value, extraData: extraData, transactionOptions: transactionOptions) + } + + /** + *Convenience wrapper to send Ethereum to another address. Internally it creates a virtual contract and encodes all the options and data.* + + - parameters: + - from: EthereumAddress to send funds from + - to: EthereumAddress to send funds to + - amount: String in "units" demonimation. It can contain either "," or "." decimal separator. + - units: Ethereum units indicating the denomination of amout about + - extraData: Additional data to attach to the transaction + - options: Web3Options to override the default gas price, gas limit. "Value" field of the options is ignored and the "amount" parameter is used instead. "From" parameter is also ignored. + + - returns: + - TransactionIntermediate object + + * String "1.01" and units: .eth will result in sending 1.01 ETH to another address* + */ + public func sendETH(from: EthereumAddress, to: EthereumAddress, amount: String, units: Web3.Utils.Units = .eth, extraData: Data = Data(), transactionOptions: TransactionOptions? = nil) -> WriteTransaction? { + guard let value = Web3.Utils.parseToBigUInt(amount, units: .eth) else {return nil} + var mergedOptions = self.web3.transactionOptions.merge(transactionOptions) + mergedOptions.from = from + return sendETH(to: to, amount: value, extraData: extraData, transactionOptions: mergedOptions) + } + + /** + *Convenience wrapper to send ERC20 tokens to another address. Internally it creates a virtual contract and encodes all the options and data. Assumes that the sender knows the decimal units of the underlying token.* + + - parameters: + - tokenAddress: EthereumAddress of the token contract + - from: EthereumAddress to send tokens from + - to: EthereumAddress to send tokens to + - amount: BigUInt indicating the number of tokens in the the smallest indivisible units (mind that sender knows the number of decimals) + - options: Web3Options to override the default gas price, gas limit. "Value" field of the options is ignored and the "amount" parameter is used instead. "From" parameter is also ignored. + + - returns: + - TransactionIntermediate object + + */ + public func sendERC20tokensWithKnownDecimals(tokenAddress: EthereumAddress, from: EthereumAddress, to: EthereumAddress, amount: BigUInt, transactionOptions: TransactionOptions? = nil) -> WriteTransaction? { + let contract = self.web3.contract(Web3.Utils.erc20ABI, at: tokenAddress, abiVersion: 2) + var mergedOptions = self.web3.transactionOptions.merge(transactionOptions) + mergedOptions.from = from + guard let writeTX = contract?.write("transfer", parameters: [to, amount] as [AnyObject], transactionOptions: mergedOptions) else {return nil} + return writeTX + } + + /** + *Convenience wrapper to send ERC20 tokens to another address. Internally it creates a virtual contract and encodes all the options and data. Pulls the number of decimals of the token under the hood.* + + - parameters: + - tokenAddress: EthereumAddress of the token contract + - from: EthereumAddress to send tokens from + - to: EthereumAddress to send tokens to + - amount: String in "natura" demonimation. It can contain either "," or "." decimal separator. + - options: Web3Options to override the default gas price, gas limit. "Value" field of the options is ignored and the "amount" parameter is used instead. "From" parameter is also ignored. + + - returns: + - TransactionIntermediate object + + - important: This call is synchronous + + * If the amount is "1.01" and token has 9 decimals it will result in sending 1010000000 of the smallest invidisible token units.* + */ + public func sendERC20tokensWithNaturalUnits(tokenAddress: EthereumAddress, from: EthereumAddress, to: EthereumAddress, amount: String, transactionOptions: TransactionOptions? = nil) throws -> WriteTransaction? { + let contract = self.web3.contract(Web3.Utils.erc20ABI, at: tokenAddress, abiVersion: 2) + var mergedOptions = self.web3.transactionOptions.merge(transactionOptions) + mergedOptions.from = from + let resp = try contract?.read("decimals", transactionOptions: mergedOptions)?.callPromise().wait() + var decimals = BigUInt(0) + guard let response = resp, let dec = response["0"], let decTyped = dec as? BigUInt else {return nil} + decimals = decTyped + let intDecimals = Int(decimals) + guard let value = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else {return nil} + return sendERC20tokensWithKnownDecimals(tokenAddress: tokenAddress, from: from, to: to, amount: value, transactionOptions: mergedOptions) + } + +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+EventParser.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+EventParser.swift new file mode 100755 index 000000000..2d22054f4 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+EventParser.swift @@ -0,0 +1,307 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +fileprivate typealias PromiseResult = PromiseKit.Result + +extension web3.web3contract { + /// An event parser to fetch events produced by smart-contract related transactions. Should not be constructed manually, but rather by calling the corresponding function on the web3contract object. + public struct EventParser: EventParserProtocol { + + public var contract: ContractProtocol + public var eventName: String + public var filter: EventFilter? + var web3: web3 + public init? (web3 web3Instance: web3, eventName: String, contract: ContractProtocol, filter: EventFilter? = nil) { +// guard let _ = contract.allEvents.index(of: eventName) else {return nil} + guard let _ = contract.allEvents.firstIndex(of: eventName) else {return nil} + self.eventName = eventName + self.web3 = web3Instance + self.contract = contract + self.filter = filter + } + + /** + *Parses the block for events matching the EventParser settings.* + + - parameters: + - blockNumber: Ethereum network block number + + - returns: + - Result object + + - important: This call is synchronous + + */ + public func parseBlockByNumber(_ blockNumber: UInt64) throws -> [EventParserResultProtocol] { + let result = try self.parseBlockByNumberPromise(blockNumber).wait() + return result + } + + /** + *Parses the block for events matching the EventParser settings.* + + - parameters: + - block: Native web3swift block object + + - returns: + - Result object + + - important: This call is synchronous + + */ + public func parseBlock(_ block: Block) throws -> [EventParserResultProtocol] { + let result = try self.parseBlockPromise(block).wait() + return result + } + + /** + *Parses the transaction for events matching the EventParser settings.* + + - parameters: + - hash: Transaction hash + + - returns: + - Result object + + - important: This call is synchronous + + */ + public func parseTransactionByHash(_ hash: Data) throws -> [EventParserResultProtocol] { + let result = try self.parseTransactionByHashPromise(hash).wait() + return result + } + + /** + *Parses the transaction for events matching the EventParser settings.* + + - parameters: + - transaction: web3swift native EthereumTransaction object + + - returns: + - Result object + + - important: This call is synchronous + + */ + public func parseTransaction(_ transaction: EthereumTransaction) throws -> [EventParserResultProtocol] { + let result = try self.parseTransactionPromise(transaction).wait() + return result + } + } +} + +extension web3.web3contract.EventParser { + public func parseTransactionPromise(_ transaction: EthereumTransaction) -> Promise<[EventParserResultProtocol]> { + let queue = self.web3.requestDispatcher.queue + do { + guard let hash = transaction.hash else { + throw Web3Error.processingError(desc: "Failed to get transaction hash")} + return self.parseTransactionByHashPromise(hash) + } catch { + let returnPromise = Promise<[EventParserResultProtocol]>.pending() + queue.async { + returnPromise.resolver.reject(error) + } + return returnPromise.promise + } + } + + public func parseTransactionByHashPromise(_ hash: Data) -> Promise<[EventParserResultProtocol]> { + let queue = self.web3.requestDispatcher.queue + return self.web3.eth.getTransactionReceiptPromise(hash).map(on:queue) {receipt throws -> [EventParserResultProtocol] in + guard let results = parseReceiptForLogs(receipt: receipt, contract: self.contract, eventName: self.eventName, filter: self.filter) else { + throw Web3Error.processingError(desc: "Failed to parse receipt for events") + } + return results + } + } + + public func parseBlockByNumberPromise(_ blockNumber: UInt64) -> Promise<[EventParserResultProtocol]> { + let queue = self.web3.requestDispatcher.queue + do { + if self.filter != nil && (self.filter?.fromBlock != nil || self.filter?.toBlock != nil) { + throw Web3Error.inputError(desc: "Can not mix parsing specific block and using block range filter") + } + return self.web3.eth.getBlockByNumberPromise(blockNumber).then(on: queue) {res in + return self.parseBlockPromise(res) + } + } catch { + let returnPromise = Promise<[EventParserResultProtocol]>.pending() + queue.async { + returnPromise.resolver.reject(error) + } + return returnPromise.promise + } + } + + public func parseBlockPromise(_ block: Block) -> Promise<[EventParserResultProtocol]> { + let queue = self.web3.requestDispatcher.queue + do { + guard let bloom = block.logsBloom else { + throw Web3Error.processingError(desc: "Block doesn't have a bloom filter log") + } + if self.contract.address != nil { + let addressPresent = block.logsBloom?.test(topic: self.contract.address!.addressData) + if (addressPresent != true) { + let returnPromise = Promise<[EventParserResultProtocol]>.pending() + queue.async { + returnPromise.resolver.fulfill([EventParserResultProtocol]()) + } + return returnPromise.promise + } + } + guard let eventOfSuchTypeIsPresent = self.contract.testBloomForEventPrecence(eventName: self.eventName, bloom: bloom) else { + throw Web3Error.processingError(desc: "Error processing bloom for events") + } + if (!eventOfSuchTypeIsPresent) { + let returnPromise = Promise<[EventParserResultProtocol]>.pending() + queue.async { + returnPromise.resolver.fulfill([EventParserResultProtocol]()) + } + return returnPromise.promise + } + return Promise {seal in + + var pendingEvents : [Promise<[EventParserResultProtocol]>] = [Promise<[EventParserResultProtocol]>]() + for transaction in block.transactions { + switch transaction { + case .null: + seal.reject(Web3Error.processingError(desc: "No information about transactions in block")) + return + case .transaction(let tx): + guard let hash = tx.hash else { + seal.reject(Web3Error.processingError(desc: "Failed to get transaction hash")) + return + } + let subresultPromise = self.parseTransactionByHashPromise(hash) + pendingEvents.append(subresultPromise) + case .hash(let hash): + let subresultPromise = self.parseTransactionByHashPromise(hash) + pendingEvents.append(subresultPromise) + } + } + when(resolved: pendingEvents).done(on: queue){ (results:[PromiseResult<[EventParserResultProtocol]>]) throws in + var allResults = [EventParserResultProtocol]() + for res in results { + guard case .fulfilled(let subresult) = res else { + throw Web3Error.processingError(desc: "Failed to parse event for one transaction in block") + } + allResults.append(contentsOf: subresult) + } + seal.fulfill(allResults) + }.catch(on:queue) {err in + seal.reject(err) + } + } + } catch { +// let returnPromise = Promise<[EventParserResultProtocol]>.pending() +// queue.async { +// returnPromise.resolver.fulfill([EventParserResultProtocol]()) +// } +// return returnPromise.promise + let returnPromise = Promise<[EventParserResultProtocol]>.pending() + queue.async { + returnPromise.resolver.reject(error) + } + return returnPromise.promise + } + } + +} + +extension web3.web3contract { + + /** + *Fetches events by doing a lookup on "indexed" parameters of the event. Smart-contract developer can make some of event values "indexed" for such fast queries.* + + - parameters: + - eventName: Event name, should be present in ABI interface of the contract + - filter: EventFilter object setting the block limits for query + - joinWithReceipts: Bool indicating whether TransactionReceipt should be fetched separately for every matched transaction + + - returns: + - Result object + + - important: This call is synchronous + + */ + public func getIndexedEvents(eventName: String?, filter: EventFilter, joinWithReceipts: Bool = false) throws -> [EventParserResultProtocol] { + let result = try self.getIndexedEventsPromise(eventName: eventName, filter: filter, joinWithReceipts: joinWithReceipts).wait() + return result + } +} + +extension web3.web3contract { + public func getIndexedEventsPromise(eventName: String?, filter: EventFilter, joinWithReceipts: Bool = false) -> Promise<[EventParserResultProtocol]> { + let queue = self.web3.requestDispatcher.queue + do { + let rawContract = self.contract + guard let preEncoding = encodeTopicToGetLogs(contract: rawContract, eventName: eventName, filter: filter) else { + throw Web3Error.processingError(desc: "Failed to encode topic for request") + } + + if eventName != nil { + guard let _ = rawContract.events[eventName!] else { + throw Web3Error.processingError(desc: "No such event in a contract") + } + } + let request = JSONRPCRequestFabric.prepareRequest(.getLogs, parameters: [preEncoding]) + let fetchLogsPromise = self.web3.dispatch(request).map(on: queue) {response throws -> [EventParserResult] in + guard let value: [EventLog] = response.getValue() else { + if response.error != nil { + throw Web3Error.nodeError(desc: response.error!.message) + } + throw Web3Error.nodeError(desc: "Empty or malformed response") + } + let allLogs = value + let decodedLogs = allLogs.compactMap({ (log) -> EventParserResult? in + let (n, d) = self.contract.parseEvent(log) + 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 + }).filter{ (res:EventParserResult?) -> Bool in + if eventName != nil { + if res != nil && res?.eventName == eventName && res!.eventLog != nil { + return true + } + } else { + if res != nil && res!.eventLog != nil { + return true + } + } + return false + } + return decodedLogs + } + if (!joinWithReceipts) { + return fetchLogsPromise.mapValues(on: queue) {res -> EventParserResultProtocol in + return res as EventParserResultProtocol + } + } + return fetchLogsPromise.thenMap(on:queue) {singleEvent in + return self.web3.eth.getTransactionReceiptPromise(singleEvent.eventLog!.transactionHash).map(on: queue) { receipt in + var joinedEvent = singleEvent + joinedEvent.transactionReceipt = receipt + return joinedEvent as EventParserResultProtocol + } + } + } catch { + let returnPromise = Promise<[EventParserResultProtocol]>.pending() + queue.async { + returnPromise.resolver.reject(error) + } + return returnPromise.promise + } + } +} + + + + diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Eventloop.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Eventloop.swift new file mode 100755 index 000000000..d59a0e9e4 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Eventloop.swift @@ -0,0 +1,103 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +extension web3.Eventloop { + +// @available(iOS 10.0, *) + public func start(_ timeInterval: TimeInterval) { + if self.timer != nil { + self.timer!.suspend() + self.timer = nil + } + let queue = self.web3.requestDispatcher.queue + queue.async { + self.timer = RepeatingTimer(timeInterval: timeInterval) + self.timer?.eventHandler = self.runnable + self.timer?.resume() + } + } + + public func stop() { + if self.timer != nil { + self.timer!.suspend() + self.timer = nil + } + } + + func runnable() { + for prop in self.monitoredProperties { + let queue = prop.queue + let function = prop.calledFunction + queue.async { + function(self.web3) + } + } + + for prop in self.monitoredUserFunctions { + let queue = prop.queue + queue.async { + prop.functionToRun() + } + } + } +} + +// Thank you https://medium.com/@danielgalasko/a-background-repeating-timer-in-swift-412cecfd2ef9 +class RepeatingTimer { + + let timeInterval: TimeInterval + + init(timeInterval: TimeInterval) { + self.timeInterval = timeInterval + } + + private lazy var timer: DispatchSourceTimer = { + let t = DispatchSource.makeTimerSource() + t.schedule(deadline: .now() + self.timeInterval, repeating: self.timeInterval) + t.setEventHandler(handler: { [weak self] in + self?.eventHandler?() + }) + return t + }() + + var eventHandler: (() -> Void)? + + private enum State { + case suspended + case resumed + } + + private var state: State = .suspended + + deinit { + timer.setEventHandler {} + timer.cancel() + /* + If the timer is suspended, calling cancel without resuming + triggers a crash. This is documented here https://forums.developer.apple.com/thread/15902 + */ + resume() + eventHandler = nil + } + + func resume() { + if state == .resumed { + return + } + state = .resumed + timer.resume() + } + + func suspend() { + if state == .suspended { + return + } + state = .suspended + timer.suspend() + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+HttpProvider.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+HttpProvider.swift new file mode 100755 index 000000000..683f7d36e --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+HttpProvider.swift @@ -0,0 +1,57 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit + +/// Providers abstraction for custom providers (websockets, other custom private key managers). At the moment should not be used. +public protocol Web3Provider { + func sendAsync(_ request: JSONRPCrequest, queue: DispatchQueue) -> Promise + func sendAsync(_ requests: JSONRPCrequestBatch, queue: DispatchQueue) -> Promise + var network: Networks? {get set} + var attachedKeystoreManager: KeystoreManager? {get set} + var url: URL {get} + var session: URLSession {get} +} + + +/// The default http provider. +public class Web3HttpProvider: Web3Provider { + public var url: URL + public var network: Networks? + public var attachedKeystoreManager: KeystoreManager? = nil + public var session: URLSession = {() -> URLSession in + let config = URLSessionConfiguration.default + let urlSession = URLSession(configuration: config) + return urlSession + }() + public init?(_ httpProviderURL: URL, network net: Networks? = nil, keystoreManager manager: KeystoreManager? = nil) { + do { + guard httpProviderURL.scheme == "http" || httpProviderURL.scheme == "https" else {return nil} + url = httpProviderURL + if net == nil { + let request = JSONRPCRequestFabric.prepareRequest(.getNetwork, parameters: []) + let response = try Web3HttpProvider.post(request, providerURL: httpProviderURL, queue: DispatchQueue.global(qos: .userInteractive), session: session).wait() + if response.error != nil { + if response.message != nil { + print(response.message!) + } + return nil + } + guard let result: String = response.getValue(), let intNetworkNumber = Int(result) else {return nil} + network = Networks.fromInt(intNetworkNumber) + if network == nil {return nil} + } else { + network = net + } + } catch { + return nil + } + attachedKeystoreManager = manager + } +} + diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+InfuraProviders.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+InfuraProviders.swift new file mode 100755 index 000000000..a3a26ace4 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+InfuraProviders.swift @@ -0,0 +1,275 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// +import Foundation +import BigInt +import Starscream + +public enum BlockNumber { + case pending + case latest + case earliest + case exact(BigUInt) + + public var stringValue: String { + switch self { + case .pending: + return "pending" + case .latest: + return "latest" + case .earliest: + return "earliest" + case .exact(let number): + return String(number, radix: 16).addHexPrefix() + } + } +} + +/// Custom Web3 HTTP provider of Infura nodes. +public final class InfuraProvider: Web3HttpProvider { + public init?(_ net:Networks, accessToken token: String? = nil, keystoreManager manager: KeystoreManager? = nil) { + var requestURLstring = "https://" + net.name + Constants.infuraHttpScheme + requestURLstring += token != nil ? token! : Constants.infuraToken + let providerURL = URL(string: requestURLstring) + super.init(providerURL!, network: net, keystoreManager: manager) + } +} + +/// Custom Websocket provider of Infura nodes. +public final class InfuraWebsocketProvider: WebsocketProvider { + public var filterID: String? + public var subscriptionIDs = Set() + private var subscriptionIDforUnsubscribing: String? = nil + private var filterTimer: Timer? + + public init?(_ network: Networks, + delegate: Web3SocketDelegate, + projectId: String? = nil, + keystoreManager manager: KeystoreManager? = nil) { + guard network == Networks.Kovan + || network == Networks.Rinkeby + || network == Networks.Ropsten + || network == Networks.Mainnet else {return nil} + let networkName = network.name + let urlString = "wss://" + networkName + Constants.infuraWsScheme + guard URL(string: urlString) != nil else {return nil} + super.init(urlString, + delegate: delegate, + projectId: projectId, + keystoreManager: manager, + network: network) + } + + public init?(_ endpoint: String, + delegate: Web3SocketDelegate, + projectId: String? = nil, + keystoreManager manager: KeystoreManager? = nil) { + guard URL(string: endpoint) != nil else {return nil} + super.init(endpoint, + delegate: delegate, + projectId: projectId, + keystoreManager: manager) + } + + public init?(_ endpoint: URL, + delegate: Web3SocketDelegate, + projectId: String? = nil, + keystoreManager manager: KeystoreManager? = nil) { + super.init(endpoint, + delegate: delegate, + projectId: projectId, + keystoreManager: manager) + } + + override public class func connectToSocket(_ endpoint: String, + delegate: Web3SocketDelegate, + projectId: String? = nil, + keystoreManager manager: KeystoreManager? = nil, + network net: Networks? = nil) -> WebsocketProvider? { + guard let socketProvider = InfuraWebsocketProvider(endpoint, + delegate: delegate, + projectId: projectId, + keystoreManager: manager) else {return nil} + socketProvider.connectSocket() + return socketProvider + } + + override public class func connectToSocket(_ endpoint: URL, + delegate: Web3SocketDelegate, + projectId: String? = nil, + keystoreManager manager: KeystoreManager? = nil, + network net: Networks? = nil) -> WebsocketProvider? { + guard let socketProvider = InfuraWebsocketProvider(endpoint, + delegate: delegate, + projectId: projectId, + keystoreManager: manager) else {return nil} + socketProvider.connectSocket() + return socketProvider + } + + public static func connectToInfuraSocket(_ network: Networks, + delegate: Web3SocketDelegate, + projectId: String? = nil, + keystoreManager manager: KeystoreManager? = nil) -> InfuraWebsocketProvider? { + guard let socketProvider = InfuraWebsocketProvider(network, + delegate: delegate, + projectId: projectId, + keystoreManager: manager) else {return nil} + socketProvider.connectSocket() + return socketProvider + } + + public func writeMessage(method: InfuraWebsocketMethod, params: [Encodable]) throws { + let request = JSONRPCRequestFabric.prepareRequest(method, parameters: params) + let encoder = JSONEncoder() + let requestData = try encoder.encode(request) + print(String(decoding: requestData, as: UTF8.self)) + writeMessage(requestData) + } + + public func setFilterAndGetChanges(method: InfuraWebsocketMethod, params: [Encodable]? = nil) throws { + filterTimer?.invalidate() + filterID = nil + let params = params ?? [] + let paramsCount = params.count + guard method.requiredNumOfParameters == paramsCount || method.requiredNumOfParameters == nil else { + throw Web3Error.inputError(desc: "Wrong number of params: need - \(method.requiredNumOfParameters!), got - \(paramsCount)") + } + try writeMessage(method: method, params: params) + filterTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(getFilterChanges), userInfo: nil, repeats: true) + } + + public func setFilterAndGetChanges(method: InfuraWebsocketMethod, address: EthereumAddress? = nil, fromBlock: BlockNumber? = nil, toBlock: BlockNumber? = nil, topics: [String]? = nil) throws { + let filterParams = EventFilterParameters(fromBlock: fromBlock?.stringValue, toBlock: toBlock?.stringValue, topics: [topics], address: [address?.address]) + try setFilterAndGetChanges(method: method, params: [filterParams]) + } + + public func setFilterAndGetLogs(method: InfuraWebsocketMethod, params: [Encodable]? = nil) throws { + filterTimer?.invalidate() + filterID = nil + let params = params ?? [] + let paramsCount = params.count + guard method.requiredNumOfParameters == paramsCount || method.requiredNumOfParameters == nil else { + throw Web3Error.inputError(desc: "Wrong number of params: need - \(method.requiredNumOfParameters!), got - \(paramsCount)") + } + try writeMessage(method: method, params: params) + filterTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(getFilterLogs), userInfo: nil, repeats: true) + } + + public func setFilterAndGetLogs(method: InfuraWebsocketMethod, address: EthereumAddress? = nil, fromBlock: BlockNumber? = nil, toBlock: BlockNumber? = nil, topics: [String]? = nil) throws { + let filterParams = EventFilterParameters(fromBlock: fromBlock?.stringValue, toBlock: toBlock?.stringValue, topics: [topics], address: [address?.address]) + try setFilterAndGetLogs(method: method, params: [filterParams]) + } + + @objc public func getFilterChanges() throws { + if let id = filterID { + filterTimer?.invalidate() + let method = InfuraWebsocketMethod.getFilterChanges + try writeMessage(method: method, params: [id]) + } + } + + @objc public func getFilterLogs() throws { + if let id = filterID { + filterTimer?.invalidate() + let method = InfuraWebsocketMethod.getFilterLogs + try writeMessage(method: method, params: [id]) + } + } + + public func getFilterLogs(address: EthereumAddress? = nil, fromBlock: BlockNumber? = nil, toBlock: BlockNumber? = nil, topics: [String]? = nil) throws { + if let id = filterID { + let filterParams = EventFilterParameters(fromBlock: fromBlock?.stringValue, toBlock: toBlock?.stringValue, topics: [topics], address: [address?.address]) + let method = InfuraWebsocketMethod.getFilterLogs + try writeMessage(method: method, params: [id, filterParams]) + } + } + + public func unistallFilter() throws { + if let id = filterID { + filterID = nil + let method = InfuraWebsocketMethod.uninstallFilter + try writeMessage(method: method, params: [id]) + } else { + throw Web3Error.nodeError(desc: "No filter set") + } + } + + public func subscribe(params: [Encodable]) throws { + let method = InfuraWebsocketMethod.subscribe + try writeMessage(method: method, params: params) + } + + public func unsubscribe(subscriptionID: String) throws { + let method = InfuraWebsocketMethod.unsubscribe + subscriptionIDforUnsubscribing = subscriptionID + try writeMessage(method: method, params: [subscriptionID]) + } + + public func subscribeOnNewHeads() throws { + let method = InfuraWebsocketMethod.subscribe + let params = ["newHeads"] + try writeMessage(method: method, params: params) + } + + public func subscribeOnLogs(addresses: [EthereumAddress]? = nil, topics: [String]? = nil) throws { + let method = InfuraWebsocketMethod.subscribe + var stringAddresses = [String]() + if let addrs = addresses { + for addr in addrs { + stringAddresses.append(addr.address) + } + } +// let ts = topics == nil ? nil : [topics!] + let filterParams = EventFilterParameters(fromBlock: nil, toBlock: nil, topics: [topics], address: stringAddresses) + try writeMessage(method: method, params: ["logs", filterParams]) + } + + public func subscribeOnNewPendingTransactions() throws { + let method = InfuraWebsocketMethod.subscribe + let params = ["newPendingTransactions"] + try writeMessage(method: method, params: params) + } + + public func subscribeOnSyncing() throws { + guard network != Networks.Kovan else { + throw Web3Error.inputError(desc: "Can't sync on Kovan") + } + let method = InfuraWebsocketMethod.subscribe + let params = ["syncing"] + try writeMessage(method: method, params: params) + } + + override public func websocketDidReceiveMessage(socket: WebSocketClient, text: String) { + if let data = text.data(using: String.Encoding.utf8), + let dictionary = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] { + if filterID == nil, + let result = dictionary["result"] as? String { + // setting filter id + filterID = result + } else if let params = dictionary["params"] as? [String: Any], + let subscription = params["subscription"] as? String, + let result = params["result"] { + // subscription result + subscriptionIDs.insert(subscription) + delegate.received(message: result) + } else if let unsubscribed = dictionary["result"] as? Bool { + // unsubsribe result + if unsubscribed == true, let id = subscriptionIDforUnsubscribing { + subscriptionIDs.remove(id) + } else if let id = subscriptionIDforUnsubscribing { + delegate.gotError(error: Web3Error.processingError(desc: "Can\'t unsubscribe \(id)")) + } else { + delegate.received(message: unsubscribed) + } + } else if let message = dictionary["result"] { + // filter result + delegate.received(message: message) + } else { + delegate.gotError(error: Web3Error.processingError(desc: "Can\'t get known result. Message is: \(text)")) + } + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Instance.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Instance.swift new file mode 100755 index 000000000..f87c354c5 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Instance.swift @@ -0,0 +1,229 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit + +/// A web3 instance bound to provider. All further functionality is provided under web.*. namespaces. +public class web3 { + public var provider : Web3Provider + public var transactionOptions: TransactionOptions = TransactionOptions.defaultOptions + public var defaultBlock = "latest" + public var requestDispatcher: JSONRPCrequestDispatcher + + /// Add a provider request to the dispatch queue. + public func dispatch(_ request: JSONRPCrequest) -> Promise { + return self.requestDispatcher.addToQueue(request: request) + } + + /// Raw initializer using a Web3Provider protocol object, dispatch queue and request dispatcher. + public init(provider prov: Web3Provider, queue: OperationQueue? = nil, requestDispatcher: JSONRPCrequestDispatcher? = nil) { + provider = prov + if requestDispatcher == nil { + self.requestDispatcher = JSONRPCrequestDispatcher(provider: provider, queue: DispatchQueue.global(qos: .userInteractive), policy: .Batch(32)) + } else { + self.requestDispatcher = requestDispatcher! + } + } + + /// Keystore manager can be bound to Web3 instance. If some manager is bound all further account related functions, such + /// as account listing, transaction signing, etc. are done locally using private keys and accounts found in a manager. + public func addKeystoreManager(_ manager: KeystoreManager?) { + self.provider.attachedKeystoreManager = manager + } + + var ethInstance: web3.Eth? + + /// Public web3.eth.* namespace. + public var eth: web3.Eth { + if (self.ethInstance != nil) { + return self.ethInstance! + } + self.ethInstance = web3.Eth(provider : self.provider, web3: self) + return self.ethInstance! + } + + public class Eth:TransactionOptionsInheritable { + var provider:Web3Provider +// weak var web3: web3? + var web3: web3 + public var transactionOptions: TransactionOptions { + return self.web3.transactionOptions + } + public init(provider prov: Web3Provider, web3 web3instance: web3) { + provider = prov + web3 = web3instance + } + } + + var personalInstance: web3.Personal? + + /// 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! + } + + public class Personal:TransactionOptionsInheritable { + var provider:Web3Provider + // weak var web3: web3? + var web3: web3 + public var transactionOptions: TransactionOptions { + return self.web3.transactionOptions + } + public init(provider prov: Web3Provider, web3 web3instance: web3) { + provider = prov + web3 = web3instance + } + } + + var txPoolInstance: web3.TxPool? + + /// 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! + } + + public class TxPool: TransactionOptionsInheritable { + var provider:Web3Provider + // weak var web3: web3? + var web3: web3 + public var transactionOptions: TransactionOptions { + return self.web3.transactionOptions + } + public init(provider prov: Web3Provider, web3 web3instance: web3) { + provider = prov + web3 = web3instance + } + } + + var walletInstance: web3.Web3Wallet? + + /// 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! + } + + public class Web3Wallet { + var provider:Web3Provider +// weak var web3: web3? + var web3: web3 + public init(provider prov: Web3Provider, web3 web3instance: web3) { + provider = prov + web3 = web3instance + } + } + + var browserFunctionsInstance: web3.BrowserFunctions? + + /// 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! + } + + public class BrowserFunctions:TransactionOptionsInheritable { + var provider:Web3Provider + // weak var web3: web3? + var web3: web3 + public var transactionOptions: TransactionOptions { + return self.web3.transactionOptions + } + public init(provider prov: Web3Provider, web3 web3instance: web3) { + provider = prov + web3 = web3instance + } + } + + var eventLoopInstance: web3.Eventloop? + + /// 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! + } + + public class Eventloop: TransactionOptionsInheritable { + + public typealias EventLoopCall = (web3) -> Void + public typealias EventLoopContractCall = (web3contract) -> Void + + public struct MonitoredProperty { + public var name: String + public var queue: DispatchQueue + public var calledFunction: EventLoopCall + } + +// public struct MonitoredContract { +// public var name: String +// public var queue: DispatchQueue +// public var calledFunction: EventLoopContractCall +// } + + var provider:Web3Provider + // weak var web3: web3? + var web3: web3 + var timer: RepeatingTimer? = nil + + public var monitoredProperties: [MonitoredProperty] = [MonitoredProperty]() +// public var monitoredContracts: [MonitoredContract] = [MonitoredContract]() + public var monitoredUserFunctions: [EventLoopRunnableProtocol] = [EventLoopRunnableProtocol]() + + public var transactionOptions: TransactionOptions { + return self.web3.transactionOptions + } + public init(provider prov: Web3Provider, web3 web3instance: web3) { + provider = prov + web3 = web3instance + } + } + + public typealias AssemblyHookFunction = ((EthereumTransaction, EthereumContract, TransactionOptions)) -> (EthereumTransaction, EthereumContract, TransactionOptions, Bool) + + public typealias SubmissionHookFunction = ((EthereumTransaction, TransactionOptions)) -> (EthereumTransaction, TransactionOptions, Bool) + + public typealias SubmissionResultHookFunction = (TransactionSendingResult) -> () + + public struct AssemblyHook { + public var queue: DispatchQueue + public var function: AssemblyHookFunction + } + + public struct SubmissionHook { + public var queue: DispatchQueue + public var function: SubmissionHookFunction + } + + public struct SubmissionResultHook { + public var queue: DispatchQueue + 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/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+JSONRPC.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+JSONRPC.swift new file mode 100755 index 000000000..283ecbaf6 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+JSONRPC.swift @@ -0,0 +1,278 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +/// Global counter object to enumerate JSON RPC requests. +public struct Counter { + public static var counter = UInt64(1) + public static var lockQueue = DispatchQueue(label: "counterQueue") + public static func increment() -> UInt64 { + var c:UInt64 = 0 + lockQueue.sync { + c = Counter.counter + Counter.counter = Counter.counter + 1 + } + return c + } +} + +/// JSON RPC request structure for serialization and deserialization purposes. +public struct JSONRPCrequest: Encodable { + public var jsonrpc: String = "2.0" + public var method: JSONRPCmethod? + public var params: JSONRPCparams? + public var id: UInt64 = Counter.increment() + + enum CodingKeys: String, CodingKey { + case jsonrpc + case method + case params + case id + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(jsonrpc, forKey: .jsonrpc) + try container.encode(method?.rawValue, forKey: .method) + try container.encode(params, forKey: .params) + try container.encode(id, forKey: .id) + } + + public var isValid: Bool { + get { + if self.method == nil { + return false + } + guard let method = self.method else {return false} + return method.requiredNumOfParameters == self.params?.params.count + } + } +} + +/// JSON RPC batch request structure for serialization and deserialization purposes. +public struct JSONRPCrequestBatch: Encodable { + var requests: [JSONRPCrequest] + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(self.requests) + } +} + +/// JSON RPC response structure for serialization and deserialization purposes. +public struct JSONRPCresponse: Decodable{ + public var id: Int + public var jsonrpc = "2.0" + public var result: Any? + public var error: ErrorMessage? + public var message: String? + + enum JSONRPCresponseKeys: String, CodingKey { + case id = "id" + case jsonrpc = "jsonrpc" + case result = "result" + case error = "error" + } + + public init(id: Int, jsonrpc: String, result: Any?, error: ErrorMessage?) { + self.id = id + self.jsonrpc = jsonrpc + self.result = result + self.error = error + } + + public struct ErrorMessage: Decodable { + public var code: Int + public var message: String + } + + internal var decodableTypes: [Decodable.Type] = [[EventLog].self, + [TransactionDetails].self, + [TransactionReceipt].self, + [Block].self, + [String].self, + [Int].self, + [Bool].self, + EventLog.self, + TransactionDetails.self, + TransactionReceipt.self, + Block.self, + String.self, + Int.self, + Bool.self, + [String:String].self, + [String:Int].self, + [String:[String:[String:[String]]]].self] + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: JSONRPCresponseKeys.self) + let id: Int = try container.decode(Int.self, forKey: .id) + let jsonrpc: String = try container.decode(String.self, forKey: .jsonrpc) + let errorMessage = try container.decodeIfPresent(ErrorMessage.self, forKey: .error) + if errorMessage != nil { + self.init(id: id, jsonrpc: jsonrpc, result: nil, error: errorMessage) + return + } + var result: Any? = nil + if let rawValue = try? container.decodeIfPresent(String.self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent(Int.self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent(Bool.self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent(EventLog.self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent(Block.self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent(TransactionReceipt.self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent(TransactionDetails.self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent([EventLog].self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent([Block].self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent([TransactionReceipt].self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent([TransactionDetails].self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent(TxPoolStatus.self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent(TxPoolContent.self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent([Bool].self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent([Int].self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent([String].self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent([String: String].self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent([String: Int].self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent([String:[String:[String:String]]].self, forKey: .result) { + result = rawValue + } else if let rawValue = try? container.decodeIfPresent([String:[String:[String:[String:String?]]]].self, forKey: .result) { + result = rawValue + } + self.init(id: id, jsonrpc: jsonrpc, result: result, error: nil) + } + + /// Get the JSON RCP reponse value by deserializing it into some native class. + /// + /// Returns nil if serialization fails + public func getValue() -> T? { + let slf = T.self + if slf == BigUInt.self { + guard let string = self.result as? String else {return nil} + guard let value = BigUInt(string.stripHexPrefix(), radix: 16) else {return nil} + return value as? T + } else if slf == BigInt.self { + guard let string = self.result as? String else {return nil} + guard let value = BigInt(string.stripHexPrefix(), radix: 16) else {return nil} + return value as? T + } else if slf == Data.self { + guard let string = self.result as? String else {return nil} + guard let value = Data.fromHex(string) else {return nil} + return value as? T + } else if slf == EthereumAddress.self { + guard let string = self.result as? String else {return nil} + guard let value = EthereumAddress(string, ignoreChecksum: true) else {return nil} + return value as? T + } +// else if slf == String.self { +// guard let value = self.result as? T else {return nil} +// return value +// } else if slf == Int.self { +// guard let value = self.result as? T else {return nil} +// return value +// } + else if slf == [BigUInt].self { + guard let string = self.result as? [String] else {return nil} + let values = string.compactMap { (str) -> BigUInt? in + return BigUInt(str.stripHexPrefix(), radix: 16) + } + return values as? T + } else if slf == [BigInt].self { + guard let string = self.result as? [String] else {return nil} + let values = string.compactMap { (str) -> BigInt? in + return BigInt(str.stripHexPrefix(), radix: 16) + } + return values as? T + } else if slf == [Data].self { + guard let string = self.result as? [String] else {return nil} + let values = string.compactMap { (str) -> Data? in + return Data.fromHex(str) + } + return values as? T + } else if slf == [EthereumAddress].self { + guard let string = self.result as? [String] else {return nil} + let values = string.compactMap { (str) -> EthereumAddress? in + return EthereumAddress(str, ignoreChecksum: true) + } + return values as? T + } + guard let value = self.result as? T else {return nil} + return value + } +} + +/// JSON RPC batch response structure for serialization and deserialization purposes. +public struct JSONRPCresponseBatch: Decodable { + var responses: [JSONRPCresponse] + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + let responses = try container.decode([JSONRPCresponse].self) + self.responses = responses + } +} + +/// Transaction parameters JSON structure for interaction with Ethereum node. +public struct TransactionParameters: Codable { + public var data: String? + public var from: String? + public var gas: String? + public var gasPrice: String? + public var to: String? + public var value: String? = "0x0" + + public init(from _from:String?, to _to:String?) { + from = _from + to = _to + } +} + +/// Event filter parameters JSON structure for interaction with Ethereum node. +public struct EventFilterParameters: Codable { + public var fromBlock: String? + public var toBlock: String? + public var topics: [[String?]?]? + public var address: [String?]? +} + +/// Raw JSON RCP 2.0 internal flattening wrapper. +public struct JSONRPCparams: Encodable{ + public var params = [Any]() + + public func encode(to encoder: Encoder) throws { + var container = encoder.unkeyedContainer() + for par in params { + if let p = par as? TransactionParameters { + try container.encode(p) + } else if let p = par as? String { + try container.encode(p) + } else if let p = par as? Bool { + try container.encode(p) + } else if let p = par as? EventFilterParameters { + try container.encode(p) + } + } + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Methods.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Methods.swift new file mode 100755 index 000000000..f3ab0f28b --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Methods.swift @@ -0,0 +1,90 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +public enum JSONRPCmethod: String, Encodable { + + case gasPrice = "eth_gasPrice" + case blockNumber = "eth_blockNumber" + case getNetwork = "net_version" + case sendRawTransaction = "eth_sendRawTransaction" + case sendTransaction = "eth_sendTransaction" + case estimateGas = "eth_estimateGas" + case call = "eth_call" + case getTransactionCount = "eth_getTransactionCount" + case getBalance = "eth_getBalance" + case getCode = "eth_getCode" + case getStorageAt = "eth_getStorageAt" + case getTransactionByHash = "eth_getTransactionByHash" + case getTransactionReceipt = "eth_getTransactionReceipt" + case getAccounts = "eth_accounts" + case getBlockByHash = "eth_getBlockByHash" + case getBlockByNumber = "eth_getBlockByNumber" + case personalSign = "eth_sign" + case unlockAccount = "personal_unlockAccount" + case createAccount = "personal_createAccount" + case getLogs = "eth_getLogs" + case getTxPoolInspect = "txpool_inspect" + case getTxPoolStatus = "txpool_status" + case getTxPoolContent = "txpool_content" + + + public var requiredNumOfParameters: Int { + get { + switch self { + case .call: + return 2 + case .getTransactionCount: + return 2 + case .getBalance: + return 2 + case .getStorageAt: + return 2 + case .getCode: + return 2 + case .getBlockByHash: + return 2 + case .getBlockByNumber: + return 2 + case .gasPrice: + return 0 + case .blockNumber: + return 0 + case .getNetwork: + return 0 + case .getAccounts: + return 0 + case .getTxPoolStatus: + return 0 + case .getTxPoolContent: + return 0 + case .getTxPoolInspect: + return 0 + default: + return 1 + } + } + } +} + +public struct JSONRPCRequestFabric { + public static func prepareRequest(_ method: JSONRPCmethod, parameters: [Encodable]) -> JSONRPCrequest { + var request = JSONRPCrequest() + request.method = method + let pars = JSONRPCparams(params: parameters) + request.params = pars + return request + } + + public static func prepareRequest(_ method: InfuraWebsocketMethod, parameters: [Encodable]) -> InfuraWebsocketRequest { + var request = InfuraWebsocketRequest() + request.method = method + let pars = JSONRPCparams(params: parameters) + request.params = pars + return request + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+MutatingTransaction.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+MutatingTransaction.swift new file mode 100755 index 000000000..783b8e351 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+MutatingTransaction.swift @@ -0,0 +1,194 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +fileprivate typealias PromiseResult = PromiseKit.Result +//import EthereumAddress + +public class WriteTransaction: ReadTransaction { + + public func assemblePromise(transactionOptions: TransactionOptions? = nil) -> Promise { + var assembledTransaction : EthereumTransaction = self.transaction + let queue = self.web3.requestDispatcher.queue + let returnPromise = Promise { seal in + if self.method != "fallback" { + let m = self.contract.methods[self.method] + if m == nil { + seal.reject(Web3Error.inputError(desc: "Contract's ABI does not have such method")) + return + } + switch m! { + case .function(let function): + if function.constant { + seal.reject(Web3Error.inputError(desc: "Trying to transact to the constant function")) + return + } + case .constructor(_): + break + default: + seal.reject(Web3Error.inputError(desc: "Contract's ABI does not have such method")) + return + } + } + + var mergedOptions = self.transactionOptions.merge(transactionOptions) + if mergedOptions.value != nil { + assembledTransaction.value = mergedOptions.value! + } + var forAssemblyPipeline : (EthereumTransaction, EthereumContract, TransactionOptions) = (assembledTransaction, self.contract, mergedOptions) + + for hook in self.web3.preAssemblyHooks { + let prom : Promise = Promise {seal in + hook.queue.async { + let hookResult = hook.function(forAssemblyPipeline) + if hookResult.3 { + forAssemblyPipeline = (hookResult.0, hookResult.1, hookResult.2) + } + seal.fulfill(hookResult.3) + } + } + let shouldContinue = try prom.wait() + if !shouldContinue { + seal.reject(Web3Error.processingError(desc: "Transaction is canceled by middleware")) + return + } + } + + assembledTransaction = forAssemblyPipeline.0 + mergedOptions = forAssemblyPipeline.2 + + guard let from = mergedOptions.from else { + seal.reject(Web3Error.inputError(desc: "No 'from' field provided")) + return + } + + // assemble promise for gas estimation + var optionsForGasEstimation = TransactionOptions() + optionsForGasEstimation.from = mergedOptions.from + optionsForGasEstimation.to = mergedOptions.to + optionsForGasEstimation.value = mergedOptions.value + optionsForGasEstimation.gasLimit = mergedOptions.gasLimit + optionsForGasEstimation.callOnBlock = mergedOptions.callOnBlock + + // assemble promise for gasLimit + var gasEstimatePromise: Promise? = nil + guard let gasLimitPolicy = mergedOptions.gasLimit else { + seal.reject(Web3Error.inputError(desc: "No gasLimit policy provided")) + return + } + switch gasLimitPolicy { + case .automatic, .withMargin, .limited: + gasEstimatePromise = self.web3.eth.estimateGasPromise(assembledTransaction, transactionOptions: optionsForGasEstimation) + case .manual(let gasLimit): + gasEstimatePromise = Promise.value(gasLimit) + } + + // assemble promise for nonce + var getNoncePromise: Promise? + guard let noncePolicy = mergedOptions.nonce else { + seal.reject(Web3Error.inputError(desc: "No nonce policy provided")) + return + } + switch noncePolicy { + case .latest: + getNoncePromise = self.web3.eth.getTransactionCountPromise(address: from, onBlock: "latest") + case .pending: + getNoncePromise = self.web3.eth.getTransactionCountPromise(address: from, onBlock: "pending") + case .manual(let nonce): + getNoncePromise = Promise.value(nonce) + } + + // assemble promise for gasPrice + var gasPricePromise: Promise? = nil + guard let gasPricePolicy = mergedOptions.gasPrice else { + seal.reject(Web3Error.inputError(desc: "No gasPrice policy provided")) + return + } + switch gasPricePolicy { + case .automatic, .withMargin: + gasPricePromise = self.web3.eth.getGasPricePromise() + case .manual(let gasPrice): + gasPricePromise = Promise.value(gasPrice) + } + var promisesToFulfill: [Promise] = [getNoncePromise!, gasPricePromise!, gasEstimatePromise!] + when(resolved: getNoncePromise!, gasEstimatePromise!, gasPricePromise!).map(on: queue, { (results:[PromiseResult]) throws -> EthereumTransaction in + + promisesToFulfill.removeAll() + guard case .fulfilled(let nonce) = results[0] else { + throw Web3Error.processingError(desc: "Failed to fetch nonce") + } + guard case .fulfilled(let gasEstimate) = results[1] else { + throw Web3Error.processingError(desc: "Failed to fetch gas estimate") + } + guard case .fulfilled(let gasPrice) = results[2] else { + throw Web3Error.processingError(desc: "Failed to fetch gas price") + } + + guard let estimate = mergedOptions.resolveGasLimit(gasEstimate) else { + throw Web3Error.processingError(desc: "Failed to calculate gas estimate that satisfied options") + } + + guard let finalGasPrice = mergedOptions.resolveGasPrice(gasPrice) else { + throw Web3Error.processingError(desc: "Missing parameter of gas price for transaction") + } + + + assembledTransaction.nonce = nonce + assembledTransaction.gasLimit = estimate + assembledTransaction.gasPrice = finalGasPrice + + forAssemblyPipeline = (assembledTransaction, self.contract, mergedOptions) + + for hook in self.web3.postAssemblyHooks { + let prom : Promise = Promise {seal in + hook.queue.async { + let hookResult = hook.function(forAssemblyPipeline) + if hookResult.3 { + forAssemblyPipeline = (hookResult.0, hookResult.1, hookResult.2) + } + seal.fulfill(hookResult.3) + } + } + let shouldContinue = try prom.wait() + if !shouldContinue { + throw Web3Error.processingError(desc: "Transaction is canceled by middleware") + } + } + + assembledTransaction = forAssemblyPipeline.0 + mergedOptions = forAssemblyPipeline.2 + + return assembledTransaction + }).done(on: queue) {tx in + seal.fulfill(tx) + }.catch(on: queue) {err in + seal.reject(err) + } + } + return returnPromise + } + + public func sendPromise(password:String = "web3swift", transactionOptions: TransactionOptions? = nil) -> Promise{ + let queue = self.web3.requestDispatcher.queue + return self.assemblePromise(transactionOptions: transactionOptions).then(on: queue) { transaction throws -> Promise in + let mergedOptions = self.transactionOptions.merge(transactionOptions) + var cleanedOptions = TransactionOptions() + cleanedOptions.from = mergedOptions.from + cleanedOptions.to = mergedOptions.to + return self.web3.eth.sendTransactionPromise(transaction, transactionOptions: cleanedOptions, password: password) + } + } + + public func send(password:String = "web3swift", transactionOptions: TransactionOptions? = nil) throws -> TransactionSendingResult { + return try self.sendPromise(password: password, transactionOptions: transactionOptions).wait() + } + + public func assemble(transactionOptions: TransactionOptions? = nil) throws -> EthereumTransaction { + return try self.assemblePromise(transactionOptions: transactionOptions).wait() + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Options.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Options.swift new file mode 100755 index 000000000..d9a9b7f55 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Options.swift @@ -0,0 +1,246 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +public protocol TransactionOptionsInheritable { + var transactionOptions: TransactionOptions {get} +} + +/// Options for sending or calling a particular Ethereum transaction +public struct TransactionOptions { + /// Sets the transaction destination. It can either be a contract address or a private key controlled wallet address. + /// + /// Usually should never be nil, left undefined for a contract-creation transaction. + public var to: EthereumAddress? = nil + /// Sets from what account a transaction should be sent. Used only internally as the sender of Ethereum transaction + /// is determined purely from the transaction signature. Indicates to the Ethereum node or to the local keystore what private key + /// should be used to sign a transaction. + /// + /// Can be nil if one reads the information from the blockchain. + public var from: EthereumAddress? = nil + + public enum GasLimitPolicy { + case automatic + case manual(BigUInt) + case limited(BigUInt) + case withMargin(Double) + } + public var gasLimit: GasLimitPolicy? + + public enum GasPricePolicy { + case automatic + case manual(BigUInt) + case withMargin(Double) + } + public var gasPrice: GasPricePolicy? + + /// The value transferred for the transaction in wei, also the endowment if it’s a contract-creation transaction. + public var value: BigUInt? = nil + + public enum NoncePolicy { + case pending + case latest + case manual(BigUInt) + } + public var nonce: NoncePolicy? + + public enum CallingBlockPolicy { + case pending + case latest + case exactBlockNumber(BigUInt) + + var stringValue: String { + switch self { + case .pending: + return "pending" + case .latest: + return "latest" + case .exactBlockNumber(let number): + return String(number, radix: 16).addHexPrefix() + } + } + } + public var callOnBlock: CallingBlockPolicy? + + public init() { + } + + public static var defaultOptions: TransactionOptions { + var opts = TransactionOptions() + opts.callOnBlock = .pending + opts.nonce = .pending + opts.gasLimit = .automatic + opts.gasPrice = .automatic + return opts + } + + public func resolveGasPrice(_ suggestedByNode: BigUInt) -> BigUInt? { + guard let gasPricePolicy = self.gasPrice else {return nil} + switch gasPricePolicy { + case .automatic: + return suggestedByNode + case .manual(let value): + return value + case .withMargin(_): + return suggestedByNode + } + } + + public func resolveGasLimit(_ suggestedByNode: BigUInt) -> BigUInt? { + guard let gasLimitPolicy = self.gasLimit else {return nil} + switch gasLimitPolicy { + case .automatic: + return suggestedByNode + case .manual(let value): + return value + case .withMargin(_): + return suggestedByNode + case .limited(let limit): + if limit <= suggestedByNode { + return suggestedByNode + } + return nil + } + } + + public func merge(_ otherOptions: TransactionOptions?) -> TransactionOptions { + guard let other = otherOptions else {return self} + var opts = TransactionOptions() + opts.from = mergeIfNotNil(first: self.from, second: other.from) + opts.to = mergeIfNotNil(first: self.to, second: other.to) + opts.gasLimit = mergeIfNotNil(first: self.gasLimit, second: other.gasLimit) + opts.gasPrice = mergeIfNotNil(first: self.gasPrice, second: other.gasPrice) + opts.value = mergeIfNotNil(first: self.value, second: other.value) + opts.nonce = mergeIfNotNil(first: self.nonce, second: other.nonce) + opts.callOnBlock = mergeIfNotNil(first: self.callOnBlock, second: other.callOnBlock) + return opts + } + + public static func fromJSON(_ json: [String: Any]) -> TransactionOptions? { + var options = TransactionOptions() + if let gas = json["gas"] as? String, let gasBiguint = BigUInt(gas.stripHexPrefix().lowercased(), radix: 16) { + options.gasLimit = .limited(gasBiguint) + } else if let gasLimit = json["gasLimit"] as? String, let gasgasLimitBiguint = BigUInt(gasLimit.stripHexPrefix().lowercased(), radix: 16) { + options.gasLimit = .limited(gasgasLimitBiguint) + } else { + options.gasLimit = .automatic + } + if let gasPrice = json["gasPrice"] as? String, let gasPriceBiguint = BigUInt(gasPrice.stripHexPrefix().lowercased(), radix: 16) { + options.gasPrice = .manual(gasPriceBiguint) + } else { + options.gasPrice = .automatic + } + if let value = json["value"] as? String, let valueBiguint = BigUInt(value.stripHexPrefix().lowercased(), radix: 16) { + options.value = valueBiguint + } + if let toString = json["to"] as? String { + guard let addressTo = EthereumAddress(toString) else {return nil} + options.to = addressTo + } + if let fromString = json["from"] as? String { + guard let addressFrom = EthereumAddress(fromString) else {return nil} + options.from = addressFrom + } + if let nonceString = json["nonce"] as? String, let nonce = BigUInt(nonceString.stripHexPrefix(), radix: 16) { + options.nonce = .manual(nonce) + } else { + options.nonce = .pending + } + if let callOnBlockString = json["callOnBlock"] as? String, let callOnBlock = BigUInt(callOnBlockString.stripHexPrefix(), radix: 16) { + options.callOnBlock = .exactBlockNumber(callOnBlock) + } else { + options.callOnBlock = .pending + } + return options + } + + /// Merges two sets of topions by overriding the parameters from the first set by parameters from the second + /// set if those are not nil. + /// + /// Returns default options if both parameters are nil. + public static func merge(_ options:TransactionOptions?, with other:TransactionOptions?) -> TransactionOptions? { + if (other == nil && options == nil) { + return TransactionOptions.defaultOptions + } + var newOptions = TransactionOptions.defaultOptions + if (other?.to != nil) { + newOptions.to = other?.to + } else { + newOptions.to = options?.to + } + if (other?.from != nil) { + newOptions.from = other?.from + } else { + newOptions.from = options?.from + } + if (other?.gasLimit != nil) { + newOptions.gasLimit = other?.gasLimit + } else { + newOptions.gasLimit = options?.gasLimit + } + if (other?.gasPrice != nil) { + newOptions.gasPrice = other?.gasPrice + } else { + newOptions.gasPrice = options?.gasPrice + } + if (other?.value != nil) { + newOptions.value = other?.value + } else { + newOptions.value = options?.value + } + return newOptions + } +// +// /// merges two sets of options along with a gas estimate to try to guess the final gas limit value required by user. +// /// +// /// Please refer to the source code for a logic. +// public static func smartMergeGasLimit(originalOptions: Web3Options?, extraOptions: Web3Options?, gasEstimate: BigUInt) -> BigUInt? { +// guard let mergedOptions = Web3Options.merge(originalOptions, with: extraOptions) else {return nil} //just require any non-nils +// if mergedOptions.gasLimit == nil { +// return gasEstimate // for user's convenience we just use an estimate +// // return nil // there is no opinion from user, so we can not proceed +// } else { +// if originalOptions != nil, originalOptions!.gasLimit != nil, originalOptions!.gasLimit! < gasEstimate { // original gas estimate was less than what's required, so we check extra options +// if extraOptions != nil, extraOptions!.gasLimit != nil, extraOptions!.gasLimit! >= gasEstimate { +// return extraOptions!.gasLimit! +// } else { +// return gasEstimate // for user's convenience we just use an estimate +// // return nil // estimate is lower than allowed +// } +// } else { +// if extraOptions != nil, extraOptions!.gasLimit != nil, extraOptions!.gasLimit! >= gasEstimate { +// return extraOptions!.gasLimit! +// } else { +// return gasEstimate // for user's convenience we just use an estimate +// // return nil // estimate is lower than allowed +// } +// } +// } +// } +// +// public static func smartMergeGasPrice(originalOptions: Web3Options?, extraOptions: Web3Options?, priceEstimate: BigUInt) -> BigUInt? { +// guard let mergedOptions = Web3Options.merge(originalOptions, with: extraOptions) else {return nil} //just require any non-nils +// if mergedOptions.gasPrice == nil { +// return priceEstimate +// } else if mergedOptions.gasPrice == 0 { +// return priceEstimate +// } else { +// return mergedOptions.gasPrice! +// } +// } +} + +fileprivate func mergeIfNotNil(first: T?, second: T?) -> T? { + if second != nil { + return second + } else if first != nil { + return first + } + return nil +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Personal.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Personal.swift new file mode 100755 index 000000000..73029fd14 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Personal.swift @@ -0,0 +1,86 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +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 + + */ + public func signPersonalMessage(message: Data, from: EthereumAddress, password:String = "web3swift") throws -> Data { + let result = try self.signPersonalMessagePromise(message: message, from: from, password: password).wait() + 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 inteval before automatic account lock by Ethereum node + + - returns: + - Result object + + - important: This call is synchronous. Does nothing if private keys are stored locally. + + */ + public func unlockAccount(account: EthereumAddress, password:String = "web3swift", seconds: UInt64 = 300) throws -> Bool { + let result = try self.unlockAccountPromise(account: account).wait() + 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 + + */ + public func ecrecover(personalMessage: Data, signature: Data) throws -> EthereumAddress { + guard let recovered = Web3.Utils.personalECRecover(personalMessage, signature: signature) else { + throw Web3Error.dataError + } + return recovered + } + + /** + *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 + + */ + public func ecrecover(hash: Data, signature: Data) throws -> EthereumAddress { + guard let recovered = Web3.Utils.hashECRecover(hash: hash, signature: signature) else { + throw Web3Error.dataError + } + return recovered + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Protocols.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Protocols.swift new file mode 100755 index 000000000..42745d8e9 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Protocols.swift @@ -0,0 +1,90 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import class PromiseKit.Promise +//import EthereumAddress + +/// Protocol for generic Ethereum event parsing results +public protocol EventParserResultProtocol { + var eventName: String {get} + var decodedResult: [String:Any] {get} + var contractAddress: EthereumAddress {get} + var transactionReceipt: TransactionReceipt? {get} + var eventLog: EventLog? {get} +} + +/// Protocol for generic Ethereum event parser +public protocol EventParserProtocol { + func parseTransaction(_ transaction: EthereumTransaction) throws -> [EventParserResultProtocol] + func parseTransactionByHash(_ hash: Data) throws -> [EventParserResultProtocol] + func parseBlock(_ block: Block) throws -> [EventParserResultProtocol] + func parseBlockByNumber(_ blockNumber: UInt64) throws -> [EventParserResultProtocol] + func parseTransactionPromise(_ transaction: EthereumTransaction) -> Promise<[EventParserResultProtocol]> + func parseTransactionByHashPromise(_ hash: Data) -> Promise<[EventParserResultProtocol]> + func parseBlockByNumberPromise(_ blockNumber: UInt64) -> Promise<[EventParserResultProtocol]> + func parseBlockPromise(_ block: Block) -> Promise<[EventParserResultProtocol]> +} + +/// Enum for the most-used Ethereum networks. Network ID is crucial for EIP155 support +public enum Networks { + case Rinkeby + case Mainnet + case Ropsten + case Kovan + case Custom(networkID: BigUInt) + + public var name: String { + switch self { + case .Rinkeby: return "rinkeby" + case .Ropsten: return "ropsten" + case .Mainnet: return "mainnet" + case .Kovan: return "kovan" + case .Custom: return "" + } + } + + public var chainID: BigUInt { + switch self { + case .Custom(let networkID): return networkID + case .Mainnet: return BigUInt(1) + case .Ropsten: return BigUInt(3) + case .Rinkeby: return BigUInt(4) + case .Kovan: return BigUInt(42) + } + } + + static let allValues = [Mainnet, Ropsten, Kovan, Rinkeby] + + static func fromInt(_ networkID:Int) -> Networks? { + switch networkID { + case 1: + return Networks.Mainnet + case 3: + return Networks.Ropsten + case 4: + return Networks.Rinkeby + case 42: + return Networks.Kovan + default: + return Networks.Custom(networkID: BigUInt(networkID)) + } + } +} + +extension Networks: Equatable { + public static func ==(lhs: Networks, rhs: Networks) -> Bool { + return lhs.chainID == rhs.chainID + && lhs.name == rhs.name + } +} + +public protocol EventLoopRunnableProtocol { + var name: String {get} + var queue: DispatchQueue {get} + func functionToRun() +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+ReadingTransaction.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+ReadingTransaction.swift new file mode 100755 index 000000000..0effcba13 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+ReadingTransaction.swift @@ -0,0 +1,109 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import PromiseKit +fileprivate typealias PromiseResult = PromiseKit.Result +//import EthereumAddress + +public class ReadTransaction { + public var transaction:EthereumTransaction + public var contract: EthereumContract + public var method: String + public var transactionOptions: TransactionOptions = TransactionOptions.defaultOptions + + var web3: web3 + + public init (transaction: EthereumTransaction, web3 web3Instance: web3, contract: EthereumContract, method: String, transactionOptions: TransactionOptions?) { + self.transaction = transaction + self.web3 = web3Instance + self.contract = contract + self.method = method + self.transactionOptions = self.transactionOptions.merge(transactionOptions) + if self.web3.provider.network != nil { + self.transaction.chainID = self.web3.provider.network?.chainID + } + } + + public func callPromise(transactionOptions: TransactionOptions? = nil) -> Promise<[String: Any]> { + var assembledTransaction : EthereumTransaction = self.transaction + let queue = self.web3.requestDispatcher.queue + let returnPromise = Promise<[String:Any]> { seal in + let mergedOptions = self.transactionOptions.merge(transactionOptions) + var optionsForCall = TransactionOptions() + optionsForCall.from = mergedOptions.from + optionsForCall.to = mergedOptions.to + optionsForCall.value = mergedOptions.value + optionsForCall.callOnBlock = mergedOptions.callOnBlock + if mergedOptions.value != nil { + assembledTransaction.value = mergedOptions.value! + } + let callPromise : Promise = self.web3.eth.callPromise(assembledTransaction, transactionOptions: optionsForCall) + callPromise.done(on: queue) {(data:Data) throws in + do { + if (self.method == "fallback") { + let resultHex = data.toHexString().addHexPrefix() + seal.fulfill(["result": resultHex as Any]) + return + } + guard let decodedData = self.contract.decodeReturnData(self.method, data: data) else + { + throw Web3Error.processingError(desc: "Can not decode returned parameters") + } + seal.fulfill(decodedData) + } catch{ + seal.reject(error) + } + }.catch(on: queue) {err in + seal.reject(err) + } + } + return returnPromise + } + + public func estimateGasPromise(transactionOptions: TransactionOptions? = nil) -> Promise{ + var assembledTransaction : EthereumTransaction = self.transaction + let queue = self.web3.requestDispatcher.queue + let returnPromise = Promise { seal in + let mergedOptions = self.transactionOptions.merge(transactionOptions) + var optionsForGasEstimation = TransactionOptions() + optionsForGasEstimation.from = mergedOptions.from + optionsForGasEstimation.to = mergedOptions.to + optionsForGasEstimation.value = mergedOptions.value + + // MARK: - Fixing estimate gas problem: gas price param shouldn't be nil + if let gasPricePolicy = mergedOptions.gasPrice { + switch gasPricePolicy { + case .manual( _): + optionsForGasEstimation.gasPrice = gasPricePolicy + default: + optionsForGasEstimation.gasPrice = .manual(1) // 1 wei to fix wrong estimating gas problem + } + } + + optionsForGasEstimation.callOnBlock = mergedOptions.callOnBlock + if mergedOptions.value != nil { + assembledTransaction.value = mergedOptions.value! + } + let promise = self.web3.eth.estimateGasPromise(assembledTransaction, transactionOptions: optionsForGasEstimation) + promise.done(on: queue) {(estimate: BigUInt) in + seal.fulfill(estimate) + }.catch(on: queue) {err in + seal.reject(err) + } + } + return returnPromise + } + + public func estimateGas(transactionOptions: TransactionOptions? = nil) throws -> BigUInt { + return try self.estimateGasPromise(transactionOptions: transactionOptions).wait() + } + + public func call(transactionOptions: TransactionOptions? = nil) throws -> [String: Any] { + return try self.callPromise(transactionOptions: transactionOptions).wait() + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Structures.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Structures.swift new file mode 100755 index 000000000..32180fbcc --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Structures.swift @@ -0,0 +1,691 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +//import EthereumAddress + +fileprivate func decodeHexToData(_ container: KeyedDecodingContainer, key: KeyedDecodingContainer.Key, allowOptional:Bool = false) throws -> Data? { + if (allowOptional) { + let string = try? container.decode(String.self, forKey: key) + if string != nil { + guard let data = Data.fromHex(string!) else {throw Web3Error.dataError} + return data + } + return nil + } else { + let string = try container.decode(String.self, forKey: key) + guard let data = Data.fromHex(string) else {throw Web3Error.dataError} + return data + } +} + +fileprivate func decodeHexToBigUInt(_ container: KeyedDecodingContainer, key: KeyedDecodingContainer.Key, allowOptional:Bool = false) throws -> BigUInt? { + if (allowOptional) { + let string = try? container.decode(String.self, forKey: key) + if string != nil { + guard let number = BigUInt(string!.stripHexPrefix(), radix: 16) else {throw Web3Error.dataError} + return number + } + return nil + } else { + let string = try container.decode(String.self, forKey: key) + guard let number = BigUInt(string.stripHexPrefix(), radix: 16) else {throw Web3Error.dataError} + return number + } +} + +extension TransactionOptions: Decodable { + enum CodingKeys: String, CodingKey + { + case from + case to + case gasPrice + case gas + case value + case nonce + case callOnBlock + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + if let gasLimit = try decodeHexToBigUInt(container, key: .gas) { + self.gasLimit = .manual(gasLimit) + } else { + self.gasLimit = .automatic + } + + if let gasPrice = try decodeHexToBigUInt(container, key: .gasPrice) { + self.gasPrice = .manual(gasPrice) + } else { + self.gasPrice = .automatic + } + + let toString = try container.decode(String?.self, forKey: .to) + var to: EthereumAddress? + if toString == nil || toString == "0x" || toString == "0x0" { + to = EthereumAddress.contractDeploymentAddress() + } else { + guard let addressString = toString else {throw Web3Error.dataError} + guard let ethAddr = EthereumAddress(addressString) else {throw Web3Error.dataError} + to = ethAddr + } + self.to = to + let from = try container.decodeIfPresent(EthereumAddress.self, forKey: .to) + // var from: EthereumAddress? + // if fromString != nil { + // guard let ethAddr = EthereumAddress(toString) else {throw Web3Error.dataError} + // from = ethAddr + // } + self.from = from + + let value = try decodeHexToBigUInt(container, key: .value) + self.value = value + + if let nonce = try decodeHexToBigUInt(container, key: .nonce) { + self.nonce = .manual(nonce) + } else { + self.nonce = .pending + } + + if let callOnBlock = try decodeHexToBigUInt(container, key: .nonce) { + self.callOnBlock = .exactBlockNumber(callOnBlock) + } else { + self.callOnBlock = .pending + } + } +} + +extension EthereumTransaction:Decodable { + enum CodingKeys: String, CodingKey + { + case to + case data + case input + case nonce + case v + case r + case s + case value + } + + public init(from decoder: Decoder) throws { + let options = try TransactionOptions(from: decoder) + let container = try decoder.container(keyedBy: CodingKeys.self) + + var data = try decodeHexToData(container, key: .data, allowOptional: true) + if data != nil { + self.data = data! + } else { + data = try decodeHexToData(container, key: .input, allowOptional: true) + if data != nil { + self.data = data! + } else { + throw Web3Error.dataError + } + } + + guard let nonce = try decodeHexToBigUInt(container, key: .nonce) else {throw Web3Error.dataError} + self.nonce = nonce + + guard let v = try decodeHexToBigUInt(container, key: .v) else {throw Web3Error.dataError} + self.v = v + + guard let r = try decodeHexToBigUInt(container, key: .r) else {throw Web3Error.dataError} + self.r = r + + guard let s = try decodeHexToBigUInt(container, key: .s) else {throw Web3Error.dataError} + self.s = s + + if options.value == nil || options.to == nil || options.gasLimit == nil || options.gasPrice == nil{ + throw Web3Error.dataError + } + self.value = options.value! + self.to = options.to! + + if let gP = options.gasPrice { + switch gP { + case .manual(let value): + self.gasPrice = value + default: + self.gasPrice = BigUInt("5000000000") + } + } + + if let gL = options.gasLimit { + switch gL { + case .manual(let value): + self.gasLimit = value + default: + self.gasLimit = BigUInt(21000) + } + } + + let inferedChainID = self.inferedChainID + if (self.inferedChainID != nil && self.v >= BigUInt(37)) { + self.chainID = inferedChainID + } + } +} + +public struct TransactionDetails: Decodable { + public var blockHash: Data? + public var blockNumber: BigUInt? + public var transactionIndex: BigUInt? + public var transaction: EthereumTransaction + + enum CodingKeys: String, CodingKey + { + case blockHash + case blockNumber + case transactionIndex + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let blockNumber = try decodeHexToBigUInt(container, key: .blockNumber, allowOptional: true) + self.blockNumber = blockNumber + + let blockHash = try decodeHexToData(container, key: .blockHash, allowOptional: true) + self.blockHash = blockHash + + let transactionIndex = try decodeHexToBigUInt(container, key: .blockNumber, allowOptional: true) + self.transactionIndex = transactionIndex + + let transaction = try EthereumTransaction(from: decoder) + self.transaction = transaction + } + + public init? (_ json: [String: AnyObject]) { + let bh = json["blockHash"] as? String + if (bh != nil) { + guard let blockHash = Data.fromHex(bh!) else {return nil} + self.blockHash = blockHash + } + let bn = json["blockNumber"] as? String + let ti = json["transactionIndex"] as? String + + guard let transaction = EthereumTransaction.fromJSON(json) else {return nil} + self.transaction = transaction + if bn != nil { + blockNumber = BigUInt(bn!.stripHexPrefix(), radix: 16) + } + if ti != nil { + transactionIndex = BigUInt(ti!.stripHexPrefix(), radix: 16) + } + } +} + +public struct TransactionReceipt: Decodable { + public var transactionHash: Data + public var blockHash: Data + public var blockNumber: BigUInt + public var transactionIndex: BigUInt + public var contractAddress: EthereumAddress? + public var cumulativeGasUsed: BigUInt + public var gasUsed: BigUInt + public var logs: [EventLog] + public var status: TXStatus + public var logsBloom: EthereumBloomFilter? + + public enum TXStatus { + case ok + case failed + case notYetProcessed + } + + enum CodingKeys: String, CodingKey + { + case blockHash + case blockNumber + case transactionHash + case transactionIndex + case contractAddress + case cumulativeGasUsed + case gasUsed + case logs + case logsBloom + case status + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + guard let blockNumber = try decodeHexToBigUInt(container, key: .blockNumber) else {throw Web3Error.dataError} + self.blockNumber = blockNumber + + guard let blockHash = try decodeHexToData(container, key: .blockHash) else {throw Web3Error.dataError} + self.blockHash = blockHash + + guard let transactionIndex = try decodeHexToBigUInt(container, key: .transactionIndex) else {throw Web3Error.dataError} + self.transactionIndex = transactionIndex + + guard let transactionHash = try decodeHexToData(container, key: .transactionHash) else {throw Web3Error.dataError} + self.transactionHash = transactionHash + + let contractAddress = try container.decodeIfPresent(EthereumAddress.self, forKey: .contractAddress) + if contractAddress != nil { + self.contractAddress = contractAddress + } + + guard let cumulativeGasUsed = try decodeHexToBigUInt(container, key: .cumulativeGasUsed) else {throw Web3Error.dataError} + self.cumulativeGasUsed = cumulativeGasUsed + + guard let gasUsed = try decodeHexToBigUInt(container, key: .gasUsed) else {throw Web3Error.dataError} + self.gasUsed = gasUsed + + + let status = try decodeHexToBigUInt(container, key: .status, allowOptional: true) + if (status == nil) { + self.status = TXStatus.notYetProcessed + } else if status == 1 { + self.status = TXStatus.ok + } else { + self.status = TXStatus.failed + } + + let logsData = try decodeHexToData(container, key: .logsBloom, allowOptional: true) + if logsData != nil && logsData!.count > 0 { + self.logsBloom = EthereumBloomFilter(logsData!) + } + + let logs = try container.decode([EventLog].self, forKey: .logs) + self.logs = logs + } + + + public init(transactionHash: Data, blockHash: Data, blockNumber: BigUInt, transactionIndex: BigUInt, contractAddress: EthereumAddress?, cumulativeGasUsed: BigUInt, gasUsed: BigUInt, logs: [EventLog], status: TXStatus, logsBloom: EthereumBloomFilter?) { + self.transactionHash = transactionHash + self.blockHash = blockHash + self.blockNumber = blockNumber + self.transactionIndex = transactionIndex + self.contractAddress = contractAddress + self.cumulativeGasUsed = cumulativeGasUsed + self.gasUsed = gasUsed + self.logs = logs + self.status = status + self.logsBloom = logsBloom + } + + static func notProcessed(transactionHash: Data) -> TransactionReceipt { + let receipt = TransactionReceipt.init(transactionHash: transactionHash, blockHash: Data(), blockNumber: BigUInt(0), transactionIndex: BigUInt(0), contractAddress: nil, cumulativeGasUsed: BigUInt(0), gasUsed: BigUInt(0), logs: [EventLog](), status: .notYetProcessed, logsBloom: nil) + return receipt + } +} + +extension EthereumAddress: Decodable, Encodable { + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + let stringValue = try container.decode(String.self) + self.init(stringValue)! + } + public func encode(to encoder: Encoder) throws { + let value = self.address.lowercased() + var signleValuedCont = encoder.singleValueContainer() + try signleValuedCont.encode(value) + } +} + +public struct EventLog : Decodable { + public var address: EthereumAddress + public var blockHash: Data + public var blockNumber: BigUInt + public var data: Data + public var logIndex: BigUInt + public var removed: Bool + public var topics: [Data] + public var transactionHash: Data + public var transactionIndex: BigUInt + + +// address = 0x53066cddbc0099eb6c96785d9b3df2aaeede5da3; +// blockHash = 0x779c1f08f2b5252873f08fd6ec62d75bb54f956633bbb59d33bd7c49f1a3d389; +// blockNumber = 0x4f58f8; +// data = 0x0000000000000000000000000000000000000000000000004563918244f40000; +// logIndex = 0x84; +// removed = 0; +// topics = ( +// 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, +// 0x000000000000000000000000efdcf2c36f3756ce7247628afdb632fa4ee12ec5, +// 0x000000000000000000000000d5395c132c791a7f46fa8fc27f0ab6bacd824484 +// ); +// transactionHash = 0x9f7bb2633abb3192d35f65e50a96f9f7ca878fa2ee7bf5d3fca489c0c60dc79a; +// transactionIndex = 0x99; + + enum CodingKeys: String, CodingKey + { + case address + case blockHash + case blockNumber + case data + case logIndex + case removed + case topics + case transactionHash + case transactionIndex + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + let address = try container.decode(EthereumAddress.self, forKey: .address) + self.address = address + + guard let blockNumber = try decodeHexToBigUInt(container, key: .blockNumber) else {throw Web3Error.dataError} + self.blockNumber = blockNumber + + guard let blockHash = try decodeHexToData(container, key: .blockHash) else {throw Web3Error.dataError} + self.blockHash = blockHash + + guard let transactionIndex = try decodeHexToBigUInt(container, key: .transactionIndex) else {throw Web3Error.dataError} + self.transactionIndex = transactionIndex + + guard let transactionHash = try decodeHexToData(container, key: .transactionHash) else {throw Web3Error.dataError} + self.transactionHash = transactionHash + + guard let data = try decodeHexToData(container, key: .data) else {throw Web3Error.dataError} + self.data = data + + guard let logIndex = try decodeHexToBigUInt(container, key: .logIndex) else {throw Web3Error.dataError} + self.logIndex = logIndex + + let removed = try decodeHexToBigUInt(container, key: .removed, allowOptional: true) + if (removed == 1) { + self.removed = true + } else { + self.removed = false + } + + let topicsStrings = try container.decode([String].self, forKey: .topics) + var allTopics = [Data]() + for top in topicsStrings { + guard let topic = Data.fromHex(top) else {throw Web3Error.dataError} + allTopics.append(topic) + } + self.topics = allTopics + } +} + +public enum TransactionInBlock:Decodable { + case hash(Data) + case transaction(EthereumTransaction) + case null + + public init(from decoder: Decoder) throws { + let value = try decoder.singleValueContainer() + if let string = try? value.decode(String.self) { + guard let d = Data.fromHex(string) else {throw Web3Error.dataError} + self = .hash(d) + } else if let dict = try? value.decode([String:String].self) { +// guard let t = try? EthereumTransaction(from: decoder) else {throw Web3Error.dataError} + guard let t = EthereumTransaction.fromJSON(dict) else {throw Web3Error.dataError} + self = .transaction(t) + } else { + self = .null + } + } + + + public init?(_ data: AnyObject) { + if let string = data as? String { + guard let d = Data.fromHex(string) else {return nil} + self = .hash(d) + } else if let dict = data as? [String:AnyObject] { + guard let t = EthereumTransaction.fromJSON(dict) else {return nil} + self = .transaction(t) + } else { + return nil + } + } +} + +public struct Block:Decodable { + public var number: BigUInt + public var hash: Data + public var parentHash: Data + public var nonce: Data? + public var sha3Uncles: Data + public var logsBloom: EthereumBloomFilter? + public var transactionsRoot: Data + public var stateRoot: Data + public var receiptsRoot: Data + public var miner: EthereumAddress? + public var difficulty: BigUInt + public var totalDifficulty: BigUInt + public var extraData: Data + public var size: BigUInt + public var gasLimit: BigUInt + public var gasUsed: BigUInt + public var timestamp: Date + public var transactions: [TransactionInBlock] + public var uncles: [Data] + + enum CodingKeys: String, CodingKey + { + case number + case hash + case parentHash + case nonce + case sha3Uncles + case logsBloom + case transactionsRoot + case stateRoot + case receiptsRoot + case miner + case difficulty + case totalDifficulty + case extraData + case size + case gasLimit + case gasUsed + case timestamp + case transactions + case uncles + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + guard let number = try decodeHexToBigUInt(container, key: .number) else {throw Web3Error.dataError} + self.number = number + + guard let hash = try decodeHexToData(container, key: .hash) else {throw Web3Error.dataError} + self.hash = hash + + guard let parentHash = try decodeHexToData(container, key: .parentHash) else {throw Web3Error.dataError} + self.parentHash = parentHash + + let nonce = try decodeHexToData(container, key: .nonce, allowOptional: true) + self.nonce = nonce + + guard let sha3Uncles = try decodeHexToData(container, key: .sha3Uncles) else {throw Web3Error.dataError} + self.sha3Uncles = sha3Uncles + + let logsBloomData = try decodeHexToData(container, key: .logsBloom, allowOptional: true) + var bloom:EthereumBloomFilter? + if logsBloomData != nil { + bloom = EthereumBloomFilter(logsBloomData!) + } + self.logsBloom = bloom + + guard let transactionsRoot = try decodeHexToData(container, key: .transactionsRoot) else {throw Web3Error.dataError} + self.transactionsRoot = transactionsRoot + + guard let stateRoot = try decodeHexToData(container, key: .stateRoot) else {throw Web3Error.dataError} + self.stateRoot = stateRoot + + guard let receiptsRoot = try decodeHexToData(container, key: .receiptsRoot) else {throw Web3Error.dataError} + self.receiptsRoot = receiptsRoot + + let minerAddress = try? container.decode(String.self, forKey: .miner) + var miner:EthereumAddress? + if minerAddress != nil { + guard let minr = EthereumAddress(minerAddress!) else {throw Web3Error.dataError} + miner = minr + } + self.miner = miner + + guard let difficulty = try decodeHexToBigUInt(container, key: .difficulty) else {throw Web3Error.dataError} + self.difficulty = difficulty + + guard let totalDifficulty = try decodeHexToBigUInt(container, key: .totalDifficulty) else {throw Web3Error.dataError} + self.totalDifficulty = totalDifficulty + + guard let extraData = try decodeHexToData(container, key: .extraData) else {throw Web3Error.dataError} + self.extraData = extraData + + guard let size = try decodeHexToBigUInt(container, key: .size) else {throw Web3Error.dataError} + self.size = size + + guard let gasLimit = try decodeHexToBigUInt(container, key: .gasLimit) else {throw Web3Error.dataError} + self.gasLimit = gasLimit + + guard let gasUsed = try decodeHexToBigUInt(container, key: .gasUsed) else {throw Web3Error.dataError} + self.gasUsed = gasUsed + + let timestampString = try container.decode(String.self, forKey: .timestamp).stripHexPrefix() + guard let timestampInt = UInt64(timestampString, radix: 16) else {throw Web3Error.dataError} + let timestamp = Date(timeIntervalSince1970: TimeInterval(timestampInt)) + self.timestamp = timestamp + + let transactions = try container.decode([TransactionInBlock].self, forKey: .transactions) + self.transactions = transactions + + let unclesStrings = try container.decode([String].self, forKey: .uncles) + var uncles = [Data]() + for str in unclesStrings { + guard let d = Data.fromHex(str) else {throw Web3Error.dataError} + uncles.append(d) + } + self.uncles = uncles + } +} + +public struct EventParserResult:EventParserResultProtocol { + public var eventName: String + public var transactionReceipt: TransactionReceipt? + public var contractAddress: EthereumAddress + public var decodedResult: [String:Any] + public var eventLog: EventLog? + + public init (eventName: String, transactionReceipt: TransactionReceipt?, contractAddress: EthereumAddress, decodedResult: [String:Any]) { + self.eventName = eventName + self.transactionReceipt = transactionReceipt + self.contractAddress = contractAddress + self.decodedResult = decodedResult + self.eventLog = nil + } +} + +public struct TransactionSendingResult { + public var transaction: EthereumTransaction + public var hash: String +} + +public struct TxPoolStatus : Decodable { + public var pending: BigUInt + public var queued: BigUInt + + enum CodingKeys: String, CodingKey + { + case pending + case queued + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + guard let pending = try decodeHexToBigUInt(container, key: .pending) else {throw Web3Error.dataError} + self.pending = pending + guard let queued = try decodeHexToBigUInt(container, key: .queued) else {throw Web3Error.dataError} + self.queued = queued + } +} + +public struct TxPoolContent : Decodable { + public var pending: [EthereumAddress: [TxPoolContentForNonce]] + public var queued: [EthereumAddress: [TxPoolContentForNonce]] + + enum CodingKeys: String, CodingKey + { + case pending + case queued + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let pending = try TxPoolContent.decodePoolContentForKey(container: container, key: .pending) + self.pending = pending + let queued = try TxPoolContent.decodePoolContentForKey(container: container, key: .queued) + self.queued = queued + } + + fileprivate static func decodePoolContentForKey(container: KeyedDecodingContainer, key: KeyedDecodingContainer.Key) throws -> [EthereumAddress: [TxPoolContentForNonce]] { + let raw = try container.nestedContainer(keyedBy: AdditionalDataCodingKeys.self, forKey: key) + var result = [EthereumAddress: [TxPoolContentForNonce]]() + for addressKey in raw.allKeys { + let addressString = addressKey.stringValue + guard let address = EthereumAddress(addressString, type: .normal, ignoreChecksum: true) else { + throw Web3Error.dataError + } + let nestedContainer = try raw.nestedContainer(keyedBy: AdditionalDataCodingKeys.self, forKey: addressKey) + var perNonceInformation = [TxPoolContentForNonce]() + perNonceInformation.reserveCapacity(nestedContainer.allKeys.count) + for nonceKey in nestedContainer.allKeys { + guard let nonce = BigUInt(nonceKey.stringValue) else { + throw Web3Error.dataError + } + let n = try? nestedContainer.nestedUnkeyedContainer(forKey: nonceKey) + if n != nil { + let details = try nestedContainer.decode([TransactionDetails].self, forKey: nonceKey) + let content = TxPoolContentForNonce(nonce: nonce, details: details) + perNonceInformation.append(content) + } else { + let detail = try nestedContainer.decode(TransactionDetails.self, forKey: nonceKey) + let content = TxPoolContentForNonce(nonce: nonce, details: [detail]) + perNonceInformation.append(content) + } + } + result[address] = perNonceInformation + } + return result + } + + + fileprivate struct AdditionalDataCodingKeys: CodingKey + { + var stringValue: String + init?(stringValue: String) + { + self.stringValue = stringValue + } + + var intValue: Int? + init?(intValue: Int) + { + return nil + } + } +} + +//public struct TxPoolContentForAddress : Decodable { +// public var address: EthereumAddress +// public var content: [TxPoolContentForNonce] +// +// public init(from decoder: Decoder) throws { +// let container = try decoder.singleValueContainer() +// let addressString = container.codingPath[0].stringValue +// guard let address = EthereumAddress(addressString, type: .normal, ignoreChecksum: true) else { +// throw Web3Error.dataError +// } +// self.address = address +// +// let content = try container.decode([TxPoolContentForNonce].self) +// self.content = content +// } +//} + +public struct TxPoolContentForNonce { + public var nonce: BigUInt + public var details: [TransactionDetails] +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+TxPool.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+TxPool.swift new file mode 100755 index 000000000..ccf9efc51 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+TxPool.swift @@ -0,0 +1,25 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt + +extension web3.TxPool { + public func getInspect() throws -> [String:[String:[String:String]]] { + let result = try self.getInspectPromise().wait() + return result + } + + public func getStatus() throws -> TxPoolStatus { + let result = try self.getStatusPromise().wait() + return result + } + + public func getContent() throws -> TxPoolContent { + let result = try self.getContentPromise().wait() + return result + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Utils.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Utils.swift new file mode 100755 index 000000000..ed130482e --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+Utils.swift @@ -0,0 +1,6212 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation +import BigInt +import CryptoSwift +//import SwiftRLP +//import secp256k1_swift +//import EthereumAddress + +public typealias Web3Utils = Web3.Utils + +extension Web3 { + + /// Namespaced Utils functions. Are not bound to particular web3 instance, so capitalization matters. + public struct Utils { + + typealias Iban = IBAN + } +} + +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] as [AnyObject]) else {return nil} + guard let contractAddressData = Web3.Utils.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 { + case eth + case wei + case Kwei + case Mwei + case Gwei + case Microether + 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 + } + } + } + } + + // Precoded API for testing estimate gas fix + public static var estimateGasTestABI = """ +[{"constant":true,"inputs":[],"name":"a","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"foo","type":"uint256"}],"name":"test","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"b","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}] +""" + + /// Precoded "cold wallet" (private key controlled) address. Basically - only a payable fallback function. + public static var coldWalletABI = "[{\"payable\":true,\"type\":\"fallback\"}]" + + /// Precoded ST20 contracts ABI. Output parameters are named for ease of use. + public static var st20ABI = """ +[{"constant":false,"inputs":[],"name":"freezeTransfers","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"investorListed","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_moduleType","type":"uint8"},{"name":"_moduleIndex","type":"uint8"}],"name":"removeModule","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"finishMintingSTO","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_granularity","type":"uint256"}],"name":"changeGranularity","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"finishedSTOMinting","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","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,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"tokenBurner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"tickerRegistry","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"unfreezeTransfers","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"securityTokenVersion","outputs":[{"name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"investors","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_investor","type":"address"},{"name":"_amount","type":"uint256"}],"name":"mint","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_value","type":"uint256"}],"name":"burn","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_moduleType","type":"uint8"},{"name":"_moduleIndex","type":"uint256"}],"name":"getModule","outputs":[{"name":"","type":"bytes32"},{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_investors","type":"address[]"},{"name":"_amounts","type":"uint256[]"}],"name":"mintMulti","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_investor","type":"address"},{"name":"_checkpointId","type":"uint256"}],"name":"balanceOfAt","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"currentCheckpointId","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"granularity","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"MAX_MODULES","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_moduleType","type":"uint8"},{"name":"_moduleIndex","type":"uint8"},{"name":"_budget","type":"uint256"}],"name":"changeModuleBudget","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"freeze","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"STO_KEY","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_subtractedValue","type":"uint256"}],"name":"decreaseApproval","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"polyToken","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"renounceOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint8"},{"name":"","type":"uint256"}],"name":"modules","outputs":[{"name":"name","type":"bytes32"},{"name":"moduleAddress","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_newTokenDetails","type":"string"}],"name":"updateTokenDetails","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"polymathRegistry","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"checkpointTotalSupply","outputs":[{"name":"checkpointId","type":"uint256"},{"name":"value","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_delegate","type":"address"},{"name":"_module","type":"address"},{"name":"_perm","type":"bytes32"}],"name":"checkPermission","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"TRANSFERMANAGER_KEY","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_checkpointId","type":"uint256"}],"name":"totalSupplyAt","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_amount","type":"uint256"}],"name":"verifyTransfer","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"finishedIssuerMinting","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_moduleType","type":"uint8"},{"name":"_name","type":"bytes32"}],"name":"getModuleByName","outputs":[{"name":"","type":"bytes32"},{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"finishMintingIssuer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"PERMISSIONMANAGER_KEY","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_tokenBurner","type":"address"}],"name":"setTokenBurner","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"moduleRegistry","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"CHECKPOINT_KEY","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_start","type":"uint256"},{"name":"_iters","type":"uint256"}],"name":"pruneInvestors","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"securityTokenRegistry","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"tokenDetails","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_addedValue","type":"uint256"}],"name":"increaseApproval","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"investorCount","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getInvestorsLength","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"updateFromRegistry","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_moduleFactory","type":"address"},{"name":"_data","type":"bytes"},{"name":"_maxCost","type":"uint256"},{"name":"_budget","type":"uint256"}],"name":"addModule","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_amount","type":"uint256"}],"name":"withdrawPoly","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"uint256"}],"name":"checkpointBalances","outputs":[{"name":"checkpointId","type":"uint256"},{"name":"value","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"createCheckpoint","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"_name","type":"string"},{"name":"_symbol","type":"string"},{"name":"_decimals","type":"uint8"},{"name":"_granularity","type":"uint256"},{"name":"_tokenDetails","type":"string"},{"name":"_polymathRegistry","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_type","type":"uint8"},{"indexed":false,"name":"_name","type":"bytes32"},{"indexed":false,"name":"_moduleFactory","type":"address"},{"indexed":false,"name":"_module","type":"address"},{"indexed":false,"name":"_moduleCost","type":"uint256"},{"indexed":false,"name":"_budget","type":"uint256"},{"indexed":false,"name":"_timestamp","type":"uint256"}],"name":"LogModuleAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_oldDetails","type":"string"},{"indexed":false,"name":"_newDetails","type":"string"}],"name":"LogUpdateTokenDetails","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_oldGranularity","type":"uint256"},{"indexed":false,"name":"_newGranularity","type":"uint256"}],"name":"LogGranularityChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_type","type":"uint8"},{"indexed":false,"name":"_module","type":"address"},{"indexed":false,"name":"_timestamp","type":"uint256"}],"name":"LogModuleRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_moduleType","type":"uint8"},{"indexed":false,"name":"_module","type":"address"},{"indexed":false,"name":"_budget","type":"uint256"}],"name":"LogModuleBudgetChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_freeze","type":"bool"},{"indexed":false,"name":"_timestamp","type":"uint256"}],"name":"LogFreezeTransfers","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_checkpointId","type":"uint256"},{"indexed":false,"name":"_timestamp","type":"uint256"}],"name":"LogCheckpointCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_timestamp","type":"uint256"}],"name":"LogFinishMintingIssuer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_timestamp","type":"uint256"}],"name":"LogFinishMintingSTO","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_oldAddress","type":"address"},{"indexed":true,"name":"_newAddress","type":"address"}],"name":"LogChangeSTRAddress","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"previousOwner","type":"address"}],"name":"OwnershipRenounced","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"previousOwner","type":"address"},{"indexed":true,"name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"Minted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_burner","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Burnt","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"},{"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"}] +""" + + /// TODO: - Need to make it right + /// Precoded ERC888 contracts ABI. Output parameters are named for ease of use. + public static var erc888ABI = "[{\"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\"},]" + + /// TODO: - need to fix. + public static var erc1376ABI = "[{\"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\"},]" + + /// Precoded ERC20 contracts ABI. Output parameters are named for ease of use. + public static var erc20ABI = "[{\"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\"},]" + + public static var erc721ABI = "[{\"constant\":true,\"inputs\":[{\"name\":\"interfaceID\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"_name\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"getApproved\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_approved\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_index\",\"type\":\"uint256\"}],\"name\":\"tokenOfOwnerByIndex\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_index\",\"type\":\"uint256\"}],\"name\":\"tokenByIndex\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"ownerOf\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"_symbol\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_operator\",\"type\":\"address\"},{\"name\":\"_approved\",\"type\":\"bool\"}],\"name\":\"setApprovalForAll\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"},{\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"tokenURI\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_operator\",\"type\":\"address\"}],\"name\":\"isApprovedForAll\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_approved\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_operator\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_approved\",\"type\":\"bool\"}],\"name\":\"ApprovalForAll\",\"type\":\"event\"}]" + + // TODO: - Need to fix + public static var erc721xABI = "[{\"constant\":true,\"inputs\":[{\"name\":\"interfaceID\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"_name\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"getApproved\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_approved\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_index\",\"type\":\"uint256\"}],\"name\":\"tokenOfOwnerByIndex\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_index\",\"type\":\"uint256\"}],\"name\":\"tokenByIndex\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"ownerOf\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"_symbol\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_operator\",\"type\":\"address\"},{\"name\":\"_approved\",\"type\":\"bool\"}],\"name\":\"setApprovalForAll\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"},{\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"tokenURI\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_operator\",\"type\":\"address\"}],\"name\":\"isApprovedForAll\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_approved\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_operator\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_approved\",\"type\":\"bool\"}],\"name\":\"ApprovalForAll\",\"type\":\"event\"}]" + + // TODO: - Need to fix + public static var erc1155ABI = "[{\"constant\":true,\"inputs\":[{\"name\":\"interfaceID\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"_name\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"getApproved\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_approved\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_index\",\"type\":\"uint256\"}],\"name\":\"tokenOfOwnerByIndex\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_index\",\"type\":\"uint256\"}],\"name\":\"tokenByIndex\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"ownerOf\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"_symbol\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_operator\",\"type\":\"address\"},{\"name\":\"_approved\",\"type\":\"bool\"}],\"name\":\"setApprovalForAll\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"},{\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"tokenURI\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_operator\",\"type\":\"address\"}],\"name\":\"isApprovedForAll\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_approved\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_operator\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_approved\",\"type\":\"bool\"}],\"name\":\"ApprovalForAll\",\"type\":\"event\"}]" + + /// Precoded ERC777 contracts ABI. Output parameters are named for ease of use. + public static var erc777ABI = """ +[ + { + "constant": true, + "inputs": [], + "name": "name", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "spender", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + } + ], + "name": "approve", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "totalSupply", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "from", + "type": "address" + }, + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + } + ], + "name": "transferFrom", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "decimals", + "outputs": [ + { + "name": "", + "type": "uint8" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "owner", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "symbol", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + } + ], + "name": "transfer", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "owner", + "type": "address" + }, + { + "name": "spender", + "type": "address" + } + ], + "name": "allowance", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + } + ], + "name": "Transfer", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "owner", + "type": "address" + }, + { + "indexed": true, + "name": "spender", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + } + ], + "name": "Approval", + "type": "event" + }, + { + "constant": true, + "inputs": [], + "name": "defaultOperators", + "outputs": [ + { + "name": "", + "type": "address[]" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "name", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "totalSupply", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "granularity", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_from", + "type": "address" + }, + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + }, + { + "name": "_operatorData", + "type": "bytes" + } + ], + "name": "operatorSend", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "_tokenHolder", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_operator", + "type": "address" + } + ], + "name": "authorizeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "symbol", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + } + ], + "name": "send", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "_operator", + "type": "address" + }, + { + "name": "_tokenHolder", + "type": "address" + } + ], + "name": "isOperatorFor", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_operator", + "type": "address" + } + ], + "name": "revokeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_tokenHolder", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + }, + { + "name": "_operatorData", + "type": "bytes" + } + ], + "name": "operatorBurn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + } + ], + "name": "burn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "name": "_name", + "type": "string" + }, + { + "name": "_symbol", + "type": "string" + }, + { + "name": "_granularity", + "type": "uint256" + }, + { + "name": "_defaultOperators", + "type": "address[]" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Sent", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Minted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Burned", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "AuthorizedOperator", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "RevokedOperator", + "type": "event" + }, + { + "constant": true, + "inputs": [], + "name": "defaultOperators", + "outputs": [ + { + "name": "", + "type": "address[]" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "name", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_spender", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + } + ], + "name": "approve", + "outputs": [ + { + "name": "success", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "totalSupply", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_from", + "type": "address" + }, + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + } + ], + "name": "transferFrom", + "outputs": [ + { + "name": "success", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "decimals", + "outputs": [ + { + "name": "", + "type": "uint8" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "granularity", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_from", + "type": "address" + }, + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + }, + { + "name": "_operatorData", + "type": "bytes" + } + ], + "name": "operatorSend", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "_tokenHolder", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_operator", + "type": "address" + } + ], + "name": "authorizeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "symbol", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + } + ], + "name": "send", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + } + ], + "name": "transfer", + "outputs": [ + { + "name": "success", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "_operator", + "type": "address" + }, + { + "name": "_tokenHolder", + "type": "address" + } + ], + "name": "isOperatorFor", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "_owner", + "type": "address" + }, + { + "name": "_spender", + "type": "address" + } + ], + "name": "allowance", + "outputs": [ + { + "name": "remaining", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_operator", + "type": "address" + } + ], + "name": "revokeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_tokenHolder", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + }, + { + "name": "_operatorData", + "type": "bytes" + } + ], + "name": "operatorBurn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + } + ], + "name": "burn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "name": "_name", + "type": "string" + }, + { + "name": "_symbol", + "type": "string" + }, + { + "name": "_granularity", + "type": "uint256" + }, + { + "name": "_defaultOperators", + "type": "address[]" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Sent", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Minted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Burned", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "AuthorizedOperator", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "RevokedOperator", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + } + ], + "name": "Transfer", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "owner", + "type": "address" + }, + { + "indexed": true, + "name": "spender", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + } + ], + "name": "Approval", + "type": "event" + }, + { + "constant": true, + "inputs": [], + "name": "defaultOperators", + "outputs": [ + { + "name": "", + "type": "address[]" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "name", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "totalSupply", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "granularity", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "from", + "type": "address" + }, + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + }, + { + "name": "operatorData", + "type": "bytes" + } + ], + "name": "operatorSend", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "owner", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "operator", + "type": "address" + } + ], + "name": "authorizeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "symbol", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + } + ], + "name": "send", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "operator", + "type": "address" + }, + { + "name": "tokenHolder", + "type": "address" + } + ], + "name": "isOperatorFor", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "operator", + "type": "address" + } + ], + "name": "revokeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "from", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + }, + { + "name": "operatorData", + "type": "bytes" + } + ], + "name": "operatorBurn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "amount", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + } + ], + "name": "burn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Sent", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Minted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Burned", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "AuthorizedOperator", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "RevokedOperator", + "type": "event" + }, + { + "constant": false, + "inputs": [ + { + "name": "operator", + "type": "address" + }, + { + "name": "from", + "type": "address" + }, + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + }, + { + "name": "operatorData", + "type": "bytes" + } + ], + "name": "tokensReceived", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "operator", + "type": "address" + }, + { + "name": "from", + "type": "address" + }, + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + }, + { + "name": "userData", + "type": "bytes" + }, + { + "name": "operatorData", + "type": "bytes" + } + ], + "name": "tokensToSend", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "addr", + "type": "address" + }, + { + "name": "iHash", + "type": "bytes32" + }, + { + "name": "implementer", + "type": "address" + } + ], + "name": "setInterfaceImplementer", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "addr", + "type": "address" + } + ], + "name": "getManager", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "addr", + "type": "address" + }, + { + "name": "newManager", + "type": "address" + } + ], + "name": "setManager", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "addr", + "type": "address" + }, + { + "name": "iHash", + "type": "bytes32" + } + ], + "name": "getInterfaceImplementer", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "new_address", + "type": "address" + } + ], + "name": "upgrade", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "last_completed_migration", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "owner", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "completed", + "type": "uint256" + } + ], + "name": "setCompleted", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "constructor" + } +] +""" + /// TODO: - Make it right + /// Precoded ERC1633 contracts ABI. Output parameters are named for ease of use. + public static var erc1633ABI = """ +[ + { + "constant": true, + "inputs": [], + "name": "name", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "spender", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + } + ], + "name": "approve", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "totalSupply", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "from", + "type": "address" + }, + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + } + ], + "name": "transferFrom", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "decimals", + "outputs": [ + { + "name": "", + "type": "uint8" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "owner", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "symbol", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + } + ], + "name": "transfer", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "owner", + "type": "address" + }, + { + "name": "spender", + "type": "address" + } + ], + "name": "allowance", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + } + ], + "name": "Transfer", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "owner", + "type": "address" + }, + { + "indexed": true, + "name": "spender", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + } + ], + "name": "Approval", + "type": "event" + }, + { + "constant": true, + "inputs": [], + "name": "defaultOperators", + "outputs": [ + { + "name": "", + "type": "address[]" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "name", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "totalSupply", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "granularity", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_from", + "type": "address" + }, + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + }, + { + "name": "_operatorData", + "type": "bytes" + } + ], + "name": "operatorSend", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "_tokenHolder", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_operator", + "type": "address" + } + ], + "name": "authorizeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "symbol", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + } + ], + "name": "send", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "_operator", + "type": "address" + }, + { + "name": "_tokenHolder", + "type": "address" + } + ], + "name": "isOperatorFor", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_operator", + "type": "address" + } + ], + "name": "revokeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_tokenHolder", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + }, + { + "name": "_operatorData", + "type": "bytes" + } + ], + "name": "operatorBurn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + } + ], + "name": "burn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "name": "_name", + "type": "string" + }, + { + "name": "_symbol", + "type": "string" + }, + { + "name": "_granularity", + "type": "uint256" + }, + { + "name": "_defaultOperators", + "type": "address[]" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Sent", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Minted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Burned", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "AuthorizedOperator", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "RevokedOperator", + "type": "event" + }, + { + "constant": true, + "inputs": [], + "name": "defaultOperators", + "outputs": [ + { + "name": "", + "type": "address[]" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "name", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_spender", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + } + ], + "name": "approve", + "outputs": [ + { + "name": "success", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "totalSupply", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_from", + "type": "address" + }, + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + } + ], + "name": "transferFrom", + "outputs": [ + { + "name": "success", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "decimals", + "outputs": [ + { + "name": "", + "type": "uint8" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "granularity", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_from", + "type": "address" + }, + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + }, + { + "name": "_operatorData", + "type": "bytes" + } + ], + "name": "operatorSend", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "_tokenHolder", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_operator", + "type": "address" + } + ], + "name": "authorizeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "symbol", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + } + ], + "name": "send", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_to", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + } + ], + "name": "transfer", + "outputs": [ + { + "name": "success", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "_operator", + "type": "address" + }, + { + "name": "_tokenHolder", + "type": "address" + } + ], + "name": "isOperatorFor", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "_owner", + "type": "address" + }, + { + "name": "_spender", + "type": "address" + } + ], + "name": "allowance", + "outputs": [ + { + "name": "remaining", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_operator", + "type": "address" + } + ], + "name": "revokeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_tokenHolder", + "type": "address" + }, + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + }, + { + "name": "_operatorData", + "type": "bytes" + } + ], + "name": "operatorBurn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_amount", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + } + ], + "name": "burn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "name": "_name", + "type": "string" + }, + { + "name": "_symbol", + "type": "string" + }, + { + "name": "_granularity", + "type": "uint256" + }, + { + "name": "_defaultOperators", + "type": "address[]" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Sent", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Minted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Burned", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "AuthorizedOperator", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "RevokedOperator", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + } + ], + "name": "Transfer", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "owner", + "type": "address" + }, + { + "indexed": true, + "name": "spender", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + } + ], + "name": "Approval", + "type": "event" + }, + { + "constant": true, + "inputs": [], + "name": "defaultOperators", + "outputs": [ + { + "name": "", + "type": "address[]" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "name", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "totalSupply", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "granularity", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "from", + "type": "address" + }, + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + }, + { + "name": "operatorData", + "type": "bytes" + } + ], + "name": "operatorSend", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "owner", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "operator", + "type": "address" + } + ], + "name": "authorizeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "symbol", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + } + ], + "name": "send", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "operator", + "type": "address" + }, + { + "name": "tokenHolder", + "type": "address" + } + ], + "name": "isOperatorFor", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "operator", + "type": "address" + } + ], + "name": "revokeOperator", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "from", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + }, + { + "name": "operatorData", + "type": "bytes" + } + ], + "name": "operatorBurn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "amount", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + } + ], + "name": "burn", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Sent", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Minted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": false, + "name": "amount", + "type": "uint256" + }, + { + "indexed": false, + "name": "data", + "type": "bytes" + }, + { + "indexed": false, + "name": "operatorData", + "type": "bytes" + } + ], + "name": "Burned", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "AuthorizedOperator", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": true, + "name": "tokenHolder", + "type": "address" + } + ], + "name": "RevokedOperator", + "type": "event" + }, + { + "constant": false, + "inputs": [ + { + "name": "operator", + "type": "address" + }, + { + "name": "from", + "type": "address" + }, + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + }, + { + "name": "operatorData", + "type": "bytes" + } + ], + "name": "tokensReceived", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "operator", + "type": "address" + }, + { + "name": "from", + "type": "address" + }, + { + "name": "to", + "type": "address" + }, + { + "name": "amount", + "type": "uint256" + }, + { + "name": "userData", + "type": "bytes" + }, + { + "name": "operatorData", + "type": "bytes" + } + ], + "name": "tokensToSend", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "addr", + "type": "address" + }, + { + "name": "iHash", + "type": "bytes32" + }, + { + "name": "implementer", + "type": "address" + } + ], + "name": "setInterfaceImplementer", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "addr", + "type": "address" + } + ], + "name": "getManager", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "addr", + "type": "address" + }, + { + "name": "newManager", + "type": "address" + } + ], + "name": "setManager", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "addr", + "type": "address" + }, + { + "name": "iHash", + "type": "bytes32" + } + ], + "name": "getInterfaceImplementer", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "new_address", + "type": "address" + } + ], + "name": "upgrade", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "last_completed_migration", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "owner", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "completed", + "type": "uint256" + } + ], + "name": "setCompleted", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "constructor" + } +] +""" + public static var ensRegistryABI = """ +[{"constant":true,"inputs":[{"name":"node","type":"bytes32"}],"name":"resolver","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"node","type":"bytes32"}],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"node","type":"bytes32"},{"name":"label","type":"bytes32"},{"name":"owner","type":"address"}],"name":"setSubnodeOwner","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"node","type":"bytes32"},{"name":"ttl","type":"uint64"}],"name":"setTTL","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"node","type":"bytes32"}],"name":"ttl","outputs":[{"name":"","type":"uint64"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"node","type":"bytes32"},{"name":"resolver","type":"address"}],"name":"setResolver","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"node","type":"bytes32"},{"name":"owner","type":"address"}],"name":"setOwner","outputs":[],"payable":false,"type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"name":"node","type":"bytes32"},{"indexed":false,"name":"owner","type":"address"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"node","type":"bytes32"},{"indexed":true,"name":"label","type":"bytes32"},{"indexed":false,"name":"owner","type":"address"}],"name":"NewOwner","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"node","type":"bytes32"},{"indexed":false,"name":"resolver","type":"address"}],"name":"NewResolver","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"node","type":"bytes32"},{"indexed":false,"name":"ttl","type":"uint64"}],"name":"NewTTL","type":"event"}] +""" + /// TODO: - Need to add correct ABI for ERC1400 + /// Precoded ERC1400 contracts ABI. Output parameters are named for ease of use. + public static var erc1400ABI = "[{\"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\"},]" + + /// TODO: - Need to add correct ABI for ERC1410 + /// Precoded ERC1410 contracts ABI. Output parameters are named for ease of use. + public static var erc1410ABI = "[{\"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\"},]" + + /// TODO: - Need to add correct ABI for ERC1594 + /// Precoded ERC1594 contracts ABI. Output parameters are named for ease of use. + public static var erc1594ABI = "[{\"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\"},]" + + /// TODO: - Need to add correct ABI for ERC1644 + /// Precoded ERC1644 contracts ABI. Output parameters are named for ease of use. + public static var erc1644ABI = "[{\"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\"},]" + + /// TODO: - Need to add correct ABI for ERC1644 + /// Precoded ERC1643 contracts ABI. Output parameters are named for ease of use. + public static var erc1643ABI = "[{\"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\"},]" + + public static var deedABI = """ + [{"constant":true,"inputs":[],"name":"creationDate","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"destroyDeed","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"setOwner","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"registrar","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"value","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"previousOwner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newValue","type":"uint256"},{"name":"throwOnFailure","type":"bool"}],"name":"setBalance","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"refundRatio","type":"uint256"}],"name":"closeDeed","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newRegistrar","type":"address"}],"name":"setRegistrar","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"_owner","type":"address"}],"payable":true,"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"newOwner","type":"address"}],"name":"OwnerChanged","type":"event"},{"anonymous":false,"inputs":[],"name":"DeedClosed","type":"event"}] + """ + + public static var registrarABI = """ + [{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"releaseDeed","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"getAllowedTime","outputs":[{"name":"timestamp","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"unhashedName","type":"string"}],"name":"invalidateName","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"hash","type":"bytes32"},{"name":"owner","type":"address"},{"name":"value","type":"uint256"},{"name":"salt","type":"bytes32"}],"name":"shaBid","outputs":[{"name":"sealedBid","type":"bytes32"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"bidder","type":"address"},{"name":"seal","type":"bytes32"}],"name":"cancelBid","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"entries","outputs":[{"name":"","type":"uint8"},{"name":"","type":"address"},{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"ens","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"},{"name":"_value","type":"uint256"},{"name":"_salt","type":"bytes32"}],"name":"unsealBid","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"transferRegistrars","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"bytes32"}],"name":"sealedBids","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"state","outputs":[{"name":"","type":"uint8"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"},{"name":"newOwner","type":"address"}],"name":"transfer","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_hash","type":"bytes32"},{"name":"_timestamp","type":"uint256"}],"name":"isAllowed","outputs":[{"name":"allowed","type":"bool"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"finalizeAuction","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"registryStarted","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"sealedBid","type":"bytes32"}],"name":"newBid","outputs":[],"payable":true,"type":"function"},{"constant":false,"inputs":[{"name":"labels","type":"bytes32[]"}],"name":"eraseNode","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_hashes","type":"bytes32[]"}],"name":"startAuctions","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"hash","type":"bytes32"},{"name":"deed","type":"address"},{"name":"registrationDate","type":"uint256"}],"name":"acceptRegistrarTransfer","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_hash","type":"bytes32"}],"name":"startAuction","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"rootNode","outputs":[{"name":"","type":"bytes32"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"hashes","type":"bytes32[]"},{"name":"sealedBid","type":"bytes32"}],"name":"startAuctionsAndBid","outputs":[],"payable":true,"type":"function"},{"inputs":[{"name":"_ens","type":"address"},{"name":"_rootNode","type":"bytes32"},{"name":"_startDate","type":"uint256"}],"payable":false,"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":false,"name":"registrationDate","type":"uint256"}],"name":"AuctionStarted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":true,"name":"bidder","type":"address"},{"indexed":false,"name":"deposit","type":"uint256"}],"name":"NewBid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":true,"name":"owner","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"status","type":"uint8"}],"name":"BidRevealed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":true,"name":"owner","type":"address"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"registrationDate","type":"uint256"}],"name":"HashRegistered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":false,"name":"value","type":"uint256"}],"name":"HashReleased","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"hash","type":"bytes32"},{"indexed":true,"name":"name","type":"string"},{"indexed":false,"name":"value","type":"uint256"},{"indexed":false,"name":"registrationDate","type":"uint256"}],"name":"HashInvalidated","type":"event"}] + """ + + public static var ethRegistrarControllerABI = """ +[ + { + "constant": true, + "inputs": [ + { + "name": "interfaceID", + "type": "bytes4" + } + ], + "name": "supportsInterface", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "pure", + "type": "function" + }, + { + "constant": false, + "inputs": [], + "name": "withdraw", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_prices", + "type": "address" + } + ], + "name": "setPriceOracle", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [], + "name": "renounceOwnership", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "_minCommitmentAge", + "type": "uint256" + }, + { + "name": "_maxCommitmentAge", + "type": "uint256" + } + ], + "name": "setCommitmentAges", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "", + "type": "bytes32" + } + ], + "name": "commitments", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "name", + "type": "string" + }, + { + "name": "duration", + "type": "uint256" + } + ], + "name": "rentPrice", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "name", + "type": "string" + }, + { + "name": "owner", + "type": "address" + }, + { + "name": "duration", + "type": "uint256" + }, + { + "name": "secret", + "type": "bytes32" + } + ], + "name": "register", + "outputs": [], + "payable": true, + "stateMutability": "payable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "MIN_REGISTRATION_DURATION", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "minCommitmentAge", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "owner", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "isOwner", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "name", + "type": "string" + } + ], + "name": "valid", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "name", + "type": "string" + }, + { + "name": "duration", + "type": "uint256" + } + ], + "name": "renew", + "outputs": [], + "payable": true, + "stateMutability": "payable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "name", + "type": "string" + } + ], + "name": "available", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "maxCommitmentAge", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "commitment", + "type": "bytes32" + } + ], + "name": "commit", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "newOwner", + "type": "address" + } + ], + "name": "transferOwnership", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "name", + "type": "string" + }, + { + "name": "owner", + "type": "address" + }, + { + "name": "secret", + "type": "bytes32" + } + ], + "name": "makeCommitment", + "outputs": [ + { + "name": "", + "type": "bytes32" + } + ], + "payable": false, + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "name": "_base", + "type": "address" + }, + { + "name": "_prices", + "type": "address" + }, + { + "name": "_minCommitmentAge", + "type": "uint256" + }, + { + "name": "_maxCommitmentAge", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "name": "name", + "type": "string" + }, + { + "indexed": true, + "name": "label", + "type": "bytes32" + }, + { + "indexed": true, + "name": "owner", + "type": "address" + }, + { + "indexed": false, + "name": "cost", + "type": "uint256" + }, + { + "indexed": false, + "name": "expires", + "type": "uint256" + } + ], + "name": "NameRegistered", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "name": "name", + "type": "string" + }, + { + "indexed": true, + "name": "label", + "type": "bytes32" + }, + { + "indexed": false, + "name": "cost", + "type": "uint256" + }, + { + "indexed": false, + "name": "expires", + "type": "uint256" + } + ], + "name": "NameRenewed", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "oracle", + "type": "address" + } + ], + "name": "NewPriceOracle", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "previousOwner", + "type": "address" + }, + { + "indexed": true, + "name": "newOwner", + "type": "address" + } + ], + "name": "OwnershipTransferred", + "type": "event" + } +] +""" + + public static var baseRegistrarABI = """ +[ + { + "constant": true, + "inputs": [ + { + "name": "interfaceID", + "type": "bytes4" + } + ], + "name": "supportsInterface", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "tokenId", + "type": "uint256" + } + ], + "name": "getApproved", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "to", + "type": "address" + }, + { + "name": "tokenId", + "type": "uint256" + } + ], + "name": "approve", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "from", + "type": "address" + }, + { + "name": "to", + "type": "address" + }, + { + "name": "tokenId", + "type": "uint256" + } + ], + "name": "transferFrom", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "id", + "type": "uint256" + } + ], + "name": "reclaim", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "ens", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "from", + "type": "address" + }, + { + "name": "to", + "type": "address" + }, + { + "name": "tokenId", + "type": "uint256" + } + ], + "name": "safeTransferFrom", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "transferPeriodEnds", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "resolver", + "type": "address" + } + ], + "name": "setResolver", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "tokenId", + "type": "uint256" + } + ], + "name": "ownerOf", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "MIGRATION_LOCK_PERIOD", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "owner", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [], + "name": "renounceOwnership", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "owner", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "isOwner", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "id", + "type": "uint256" + } + ], + "name": "available", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "to", + "type": "address" + }, + { + "name": "approved", + "type": "bool" + } + ], + "name": "setApprovalForAll", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "controller", + "type": "address" + } + ], + "name": "addController", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "previousRegistrar", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "from", + "type": "address" + }, + { + "name": "to", + "type": "address" + }, + { + "name": "tokenId", + "type": "uint256" + }, + { + "name": "_data", + "type": "bytes" + } + ], + "name": "safeTransferFrom", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "GRACE_PERIOD", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "id", + "type": "uint256" + }, + { + "name": "duration", + "type": "uint256" + } + ], + "name": "renew", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "id", + "type": "uint256" + } + ], + "name": "nameExpires", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "", + "type": "address" + } + ], + "name": "controllers", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "baseNode", + "outputs": [ + { + "name": "", + "type": "bytes32" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "owner", + "type": "address" + }, + { + "name": "operator", + "type": "address" + } + ], + "name": "isApprovedForAll", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "label", + "type": "bytes32" + }, + { + "name": "deed", + "type": "address" + }, + { + "name": "", + "type": "uint256" + } + ], + "name": "acceptRegistrarTransfer", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "newOwner", + "type": "address" + } + ], + "name": "transferOwnership", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "controller", + "type": "address" + } + ], + "name": "removeController", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "id", + "type": "uint256" + }, + { + "name": "owner", + "type": "address" + }, + { + "name": "duration", + "type": "uint256" + } + ], + "name": "register", + "outputs": [ + { + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "name": "_ens", + "type": "address" + }, + { + "name": "_previousRegistrar", + "type": "address" + }, + { + "name": "_baseNode", + "type": "bytes32" + }, + { + "name": "_transferPeriodEnds", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "controller", + "type": "address" + } + ], + "name": "ControllerAdded", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "controller", + "type": "address" + } + ], + "name": "ControllerRemoved", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "id", + "type": "uint256" + }, + { + "indexed": true, + "name": "owner", + "type": "address" + }, + { + "indexed": false, + "name": "expires", + "type": "uint256" + } + ], + "name": "NameMigrated", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "id", + "type": "uint256" + }, + { + "indexed": true, + "name": "owner", + "type": "address" + }, + { + "indexed": false, + "name": "expires", + "type": "uint256" + } + ], + "name": "NameRegistered", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "id", + "type": "uint256" + }, + { + "indexed": false, + "name": "expires", + "type": "uint256" + } + ], + "name": "NameRenewed", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "previousOwner", + "type": "address" + }, + { + "indexed": true, + "name": "newOwner", + "type": "address" + } + ], + "name": "OwnershipTransferred", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "from", + "type": "address" + }, + { + "indexed": true, + "name": "to", + "type": "address" + }, + { + "indexed": true, + "name": "tokenId", + "type": "uint256" + } + ], + "name": "Transfer", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "owner", + "type": "address" + }, + { + "indexed": true, + "name": "approved", + "type": "address" + }, + { + "indexed": true, + "name": "tokenId", + "type": "uint256" + } + ], + "name": "Approval", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "owner", + "type": "address" + }, + { + "indexed": true, + "name": "operator", + "type": "address" + }, + { + "indexed": false, + "name": "approved", + "type": "bool" + } + ], + "name": "ApprovalForAll", + "type": "event" + } +] +""" + + public static var reverseRegistrarABI = """ +[ + { + "constant": false, + "inputs": [ + { + "name": "owner", + "type": "address" + }, + { + "name": "resolver", + "type": "address" + } + ], + "name": "claimWithResolver", + "outputs": [ + { + "name": "", + "type": "bytes32" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "owner", + "type": "address" + } + ], + "name": "claim", + "outputs": [ + { + "name": "", + "type": "bytes32" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "ens", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "ADDR_REVERSE_NODE", + "outputs": [ + { + "name": "", + "type": "bytes32" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "defaultResolver", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "addr", + "type": "address" + } + ], + "name": "node", + "outputs": [ + { + "name": "", + "type": "bytes32" + } + ], + "payable": false, + "stateMutability": "pure", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "name", + "type": "string" + } + ], + "name": "setName", + "outputs": [ + { + "name": "", + "type": "bytes32" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "name": "ensAddr", + "type": "address" + }, + { + "name": "resolverAddr", + "type": "address" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "constructor" + } +] +""" + + //function setAddr(bytes32 node, address addr) + public static var legacyResolverABI = """ +[ + { + "constant": true, + "inputs": [ + { + "name": "interfaceID", + "type": "bytes4" + } + ], + "name": "supportsInterface", + "outputs": [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "pure", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "key", + "type": "string" + }, + { + "name": "value", + "type": "string" + } + ], + "name": "setText", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "contentTypes", + "type": "uint256" + } + ], + "name": "ABI", + "outputs": [ + { + "name": "contentType", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "x", + "type": "bytes32" + }, + { + "name": "y", + "type": "bytes32" + } + ], + "name": "setPubkey", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "content", + "outputs": [ + { + "name": "", + "type": "bytes32" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "addr", + "outputs": [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "key", + "type": "string" + } + ], + "name": "text", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "contentType", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + } + ], + "name": "setABI", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "name", + "outputs": [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "name", + "type": "string" + } + ], + "name": "setName", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "hash", + "type": "bytes" + } + ], + "name": "setMultihash", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "hash", + "type": "bytes32" + } + ], + "name": "setContent", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "pubkey", + "outputs": [ + { + "name": "x", + "type": "bytes32" + }, + { + "name": "y", + "type": "bytes32" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "addr", + "type": "address" + } + ], + "name": "setAddr", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "multihash", + "outputs": [ + { + "name": "", + "type": "bytes" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "name": "ensAddr", + "type": "address" + } + ], + "payable": false, + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "a", + "type": "address" + } + ], + "name": "AddrChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "hash", + "type": "bytes32" + } + ], + "name": "ContentChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "name", + "type": "string" + } + ], + "name": "NameChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": true, + "name": "contentType", + "type": "uint256" + } + ], + "name": "ABIChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "x", + "type": "bytes32" + }, + { + "indexed": false, + "name": "y", + "type": "bytes32" + } + ], + "name": "PubkeyChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "indexedKey", + "type": "string" + }, + { + "indexed": false, + "name": "key", + "type": "string" + } + ], + "name": "TextChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "hash", + "type": "bytes" + } + ], + "name": "MultihashChanged", + "type": "event" + } +] +""" + + public static var resolverABI = """ +[ + { + "constant": true, + "inputs": + [ + { + "name": "interfaceID", + "type": "bytes4" + } + ], + "name": "supportsInterface", + "outputs": + [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "pure", + "type": "function" + }, + { + "constant": false, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "key", + "type": "string" + }, + { + "name": "value", + "type": "string" + } + ], + "name": "setText", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "interfaceID", + "type": "bytes4" + } + ], + "name": "interfaceImplementer", + "outputs": + [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "contentTypes", + "type": "uint256" + } + ], + "name": "ABI", + "outputs": + [ + { + "name": "", + "type": "uint256" + }, + { + "name": "", + "type": "bytes" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "x", + "type": "bytes32" + }, + { + "name": "y", + "type": "bytes32" + } + ], + "name": "setPubkey", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "hash", + "type": "bytes" + } + ], + "name": "setContenthash", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "addr", + "outputs": + [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "key", + "type": "string" + } + ], + "name": "text", + "outputs": + [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "contentType", + "type": "uint256" + }, + { + "name": "data", + "type": "bytes" + } + ], + "name": "setABI", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "name", + "outputs": + [ + { + "name": "", + "type": "string" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": [], + "name": "renounceOwnership", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "name", + "type": "string" + } + ], + "name": "setName", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "owner", + "outputs": + [ + { + "name": "", + "type": "address" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": [], + "name": "isOwner", + "outputs": + [ + { + "name": "", + "type": "bool" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "contenthash", + "outputs": + [ + { + "name": "", + "type": "bytes" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": true, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + } + ], + "name": "pubkey", + "outputs": + [ + { + "name": "x", + "type": "bytes32" + }, + { + "name": "y", + "type": "bytes32" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" + }, + { + "constant": false, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "addr", + "type": "address" + } + ], + "name": "setAddr", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": + [ + { + "name": "node", + "type": "bytes32" + }, + { + "name": "interfaceID", + "type": "bytes4" + }, + { + "name": "implementer", + "type": "address" + } + ], + "name": "setInterface", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "constant": false, + "inputs": + [ + { + "name": "newOwner", + "type": "address" + } + ], + "name": "transferOwnership", + "outputs": [], + "payable": false, + "stateMutability": "nonpayable", + "type": "function" + }, + { + "anonymous": false, + "inputs": + [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "indexedKey", + "type": "string" + }, + { + "indexed": false, + "name": "key", + "type": "string" + } + ], + "name": "TextChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": + [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "x", + "type": "bytes32" + }, + { + "indexed": false, + "name": "y", + "type": "bytes32" + } + ], + "name": "PubkeyChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": + [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "name", + "type": "string" + } + ], + "name": "NameChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": + [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": true, + "name": "interfaceID", + "type": "bytes4" + }, + { + "indexed": false, + "name": "implementer", + "type": "address" + } + ], + "name": "InterfaceChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": + [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "hash", + "type": "bytes" + } + ], + "name": "ContenthashChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": + [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": false, + "name": "a", + "type": "address" + } + ], + "name": "AddrChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": + [ + { + "indexed": true, + "name": "node", + "type": "bytes32" + }, + { + "indexed": true, + "name": "contentType", + "type": "uint256" + } + ], + "name": "ABIChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": + [ + { + "indexed": true, + "name": "previousOwner", + "type": "address" + }, + { + "indexed": true, + "name": "newOwner", + "type": "address" + } + ], + "name": "OwnershipTransferred", + "type": "event" + } +] +""" + +} + +extension Web3.Utils { + + /// 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} + return publicKey + } + + /// Convert a public key to the corresponding EthereumAddress. Accepts public keys in compressed (33 bytes), non-compressed (65 bytes) + /// or raw concat(X,Y) (64 bytes) format. + /// + /// Returns 20 bytes of address data. + public static func publicToAddressData(_ publicKey: Data) -> Data? { + if publicKey.count == 33 { + guard let decompressedKey = SECP256K1.combineSerializedPublicKeys(keys: [publicKey], outputCompressed: false) else {return nil} + return publicToAddressData(decompressedKey) + } + var stipped = publicKey + if (stipped.count == 65) { + if (stipped[0] != 4) { + return nil + } + stipped = stipped[1...64] + } + if (stipped.count != 64) { + return nil + } + let sha3 = stipped.sha3(.keccak256) + let addressData = sha3[12...31] + return addressData + } + + /// Convert a public key to the corresponding EthereumAddress. Accepts public keys in compressed (33 bytes), non-compressed (65 bytes) + /// or raw concat(X,Y) (64 bytes) format. + /// + /// Returns the EthereumAddress object. + public static func publicToAddress(_ publicKey: Data) -> EthereumAddress? { + guard let addressData = Web3.Utils.publicToAddressData(publicKey) else {return nil} + let address = addressData.toHexString().addHexPrefix().lowercased() + return EthereumAddress(address) + } + + /// Convert a public key to the corresponding EthereumAddress. Accepts public keys in compressed (33 bytes), non-compressed (65 bytes) + /// or raw concat(X,Y) (64 bytes) format. + /// + /// Returns a 0x prefixed hex string. + public static func publicToAddressString(_ publicKey: Data) -> String? { + guard let addressData = Web3.Utils.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. + public static func addressDataToString(_ addressData: Data) -> String? { + guard addressData.count == 20 else {return nil} + return addressData.toHexString().addHexPrefix().lowercased() + } + + /// Hashes a personal message by first padding it with the "\u{19}Ethereum Signed Message:\n" string and message length string. + /// Should be used if some arbitrary information should be hashed and signed to prevent signing an Ethereum transaction + /// by accident. + 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} + var data = Data() + if personalMessage.count >= prefixData.count && prefixData == personalMessage[0 ..< prefixData.count] { + data.append(personalMessage) + } else { + data.append(prefixData) + data.append(personalMessage) + } + let hash = data.sha3(.keccak256) + return hash + } + + /// Parse a user-supplied string using the number of decimals for particular Ethereum unit. + /// If input is non-numeric or precision is not sufficient - returns nil. + /// Allowed decimal separators are ".", ",". + public static func parseToBigUInt(_ amount: String, units: Web3.Utils.Units = .eth) -> BigUInt? { + let unitDecimals = units.decimals + return parseToBigUInt(amount, decimals: unitDecimals) + } + + /// Parse a user-supplied 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} + let unitDecimals = decimals + 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 + } + return mainPart + } + + /// Formats a BigInt object to String. The supplied number is first divided into integer and decimal part based on "toUnits", + /// then limit the decimal part to "decimals" symbols and uses a "decimalSeparator" as a separator. + /// + /// Returns nil of formatting is not possible to satisfy. + public static func formatToEthereumUnits(_ bigNumber: BigInt, toUnits: Web3.Utils.Units = .eth, decimals: Int = 4, decimalSeparator: String = ".") -> String? { + let magnitude = bigNumber.magnitude + guard let formatted = formatToEthereumUnits(magnitude, toUnits: toUnits, decimals: decimals, decimalSeparator: decimalSeparator) else {return nil} + switch bigNumber.sign { + case .plus: + return formatted + case .minus: + return "-" + formatted + } + } + + /// Formats a BigInt object to String. The supplied number is first divided into integer and decimal part based on "toUnits", + /// then limit the decimal part to "decimals" 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. + public static func formatToPrecision(_ bigNumber: BigInt, numberDecimals: Int = 18, formattingDecimals: Int = 4, decimalSeparator: String = ".", fallbackToScientific: Bool = false) -> String? { + let magnitude = bigNumber.magnitude + guard let formatted = formatToPrecision(magnitude, numberDecimals: numberDecimals, formattingDecimals: formattingDecimals, decimalSeparator: decimalSeparator, fallbackToScientific: fallbackToScientific) else {return nil} + switch bigNumber.sign { + case .plus: + return formatted + case .minus: + return "-" + formatted + } + } + + /// Formats a BigUInt object to String. The supplied number is first divided into integer and decimal part based on "toUnits", + /// then limit the decimal part to "decimals" symbols and uses a "decimalSeparator" as a separator. + /// + /// Returns nil of formatting is not possible to satisfy. + public static func formatToEthereumUnits(_ bigNumber: BigUInt, toUnits: Web3.Utils.Units = .eth, decimals: Int = 4, decimalSeparator: String = ".", fallbackToScientific: Bool = false) -> String? { + return formatToPrecision(bigNumber, numberDecimals: toUnits.decimals, formattingDecimals: decimals, decimalSeparator: decimalSeparator, fallbackToScientific: fallbackToScientific); + } + + /// Formats a BigUInt object to String. The supplied number is first divided into integer and decimal part based on "numberDecimals", + /// 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. + public static func formatToPrecision(_ bigNumber: BigUInt, numberDecimals: Int = 18, formattingDecimals: Int = 4, decimalSeparator: String = ".", fallbackToScientific: Bool = false) -> String? { + if bigNumber == 0 { + return "0" + } + let unitDecimals = numberDecimals + var toDecimals = formattingDecimals + if unitDecimals < toDecimals { + toDecimals = unitDecimals + } + let divisor = BigUInt(10).power(unitDecimals) + let (quotient, remainder) = bigNumber.quotientAndRemainder(dividingBy: divisor) + var fullRemainder = String(remainder); + let fullPaddedRemainder = fullRemainder.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) + } + } + if (toDecimals == 0) { + return String(quotient) + } + return String(quotient) + decimalSeparator + remainderPadded + } + + /// 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 public 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} + return Web3.Utils.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. + static public 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 = Web3.Utils.hashPersonalMessage(personalMessage) else {return nil} + guard let publicKey = SECP256K1.recoverPublicKey(hash: hash, signature: signatureData) else {return nil} + return Web3.Utils.publicToAddress(publicKey) + } + + + /// 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. + static public func hashECRecover(hash: 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 publicKey = SECP256K1.recoverPublicKey(hash: hash, signature: signatureData) else {return nil} + return Web3.Utils.publicToAddress(publicKey) + } + + /// returns Ethereum variant of sha3 (keccak256) of data. Returns nil is data is empty + static public func keccak256(_ data: Data) -> Data? { + 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 public func sha3(_ data: Data) -> Data? { + if data.count == 0 {return nil} + return data.sha3(.keccak256) + } + + /// returns sha256 of data. Returns nil is data is empty + static public func sha256(_ data: Data) -> Data? { + 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} + let bytes = signatureData.bytes + let r = Array(bytes[0..<32]) + let s = Array(bytes[32..<64]) + return SECP256K1.UnmarshaledSignature(v: bytes[64], r: Data(r), s: Data(s)) + } + + /// 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} + var completeSignature = Data(r) + completeSignature.append(Data(s)) + completeSignature.append(Data([v])) +// var completeSignature = Data(bytes: r) +// completeSignature.append(Data(bytes: s)) +// completeSignature.append(Data(bytes: [v])) + return completeSignature + } + + /// Marshals internal signature structure into a 65 byte recoverable EC signature. + static func marshalSignature(unmarshalledSignature: SECP256K1.UnmarshaledSignature) -> Data { + var completeSignature = Data(unmarshalledSignature.r) + completeSignature.append(Data(unmarshalledSignature.s)) +// completeSignature.append(Data(bytes: [unmarshalledSignature.v])) + completeSignature.append(Data([unmarshalledSignature.v])) + return completeSignature + } + + public static func hexToData(_ string: String) -> Data? { + return Data.fromHex(string) + } + + public static func hexToBigUInt(_ string: String) -> BigUInt? { + return BigUInt(string.stripHexPrefix(), radix: 16) + } + + public static func randomBytes(length: Int) -> Data? { + return Data.randomBytes(length:length) + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+WebsocketProvider.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+WebsocketProvider.swift new file mode 100644 index 000000000..29b0ade77 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3+WebsocketProvider.swift @@ -0,0 +1,307 @@ +// +// Web3+WebsocketProvider.swift +// web3swift-iOS +// +// Created by Anton on 01/04/2019. +// Copyright © 2019 The Matter Inc. All rights reserved. +// +import Starscream +import PromiseKit +import BigInt +import Foundation + +public protocol IWebsocketProvider { + var socket: WebSocket {get} + var delegate: Web3SocketDelegate {get set} + func connectSocket() throws + func disconnectSocket() throws + func writeMessage(_ message: T) +} + +public enum InfuraWebsocketMethod: String, Encodable { + + case newPendingTransactionFilter = "eth_newPendingTransactionFilter" + case getFilterChanges = "eth_getFilterChanges" + case newFilter = "eth_newFilter" + case newBlockFilter = "eth_newBlockFilter" + case getFilterLogs = "eth_getFilterLogs" + case uninstallFilter = "eth_uninstallFilter" + case subscribe = "eth_subscribe" + case unsubscribe = "eth_unsubscribe" + + public var requiredNumOfParameters: Int? { + get { + switch self { + case .newPendingTransactionFilter: + return 0 + case .getFilterChanges: + return 1 + case .newFilter: + return nil + case .newBlockFilter: + return 0 + case .getFilterLogs: + return nil + case .uninstallFilter: + return 1 + case .subscribe: + return nil + case .unsubscribe: + return 1 + } + } + } +} + +public struct InfuraWebsocketRequest: Encodable { + public var jsonrpc: String = "2.0" + public var method: InfuraWebsocketMethod? + public var params: JSONRPCparams? + public var id: UInt64 = Counter.increment() + + enum CodingKeys: String, CodingKey { + case jsonrpc + case method + case params + case id + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(jsonrpc, forKey: .jsonrpc) + try container.encode(method?.rawValue, forKey: .method) + try container.encode(params, forKey: .params) + try container.encode(id, forKey: .id) + } + + public var isValid: Bool { + get { + if self.method == nil { + return false + } + guard let method = self.method else {return false} + return method.requiredNumOfParameters == self.params?.params.count + } + } +} + +public protocol Web3SocketDelegate { + func received(message: Any) + func gotError(error: Error) +} + +/// The default websocket provider. +public class WebsocketProvider: Web3Provider, IWebsocketProvider, WebSocketDelegate { + + public func didReceive(event: WebSocketEvent, client: WebSocket) { + + } + + public func sendAsync(_ request: JSONRPCrequest, queue: DispatchQueue) -> Promise { + return Promise(error: Web3Error.inputError(desc: "Sending is unsupported for Websocket provider. Please, use \'sendMessage\'")) + } + + public func sendAsync(_ requests: JSONRPCrequestBatch, queue: DispatchQueue) -> Promise { + return Promise(error: Web3Error.inputError(desc: "Sending is unsupported for Websocket provider. Please, use \'sendMessage\'")) + } + + public var network: Networks? + public var url: URL + public var session: URLSession = {() -> URLSession in + let config = URLSessionConfiguration.default + let urlSession = URLSession(configuration: config) + return urlSession + }() + public var attachedKeystoreManager: KeystoreManager? = nil + + public var socket: WebSocket + public var delegate: Web3SocketDelegate + + private var websocketConnected: Bool = false + private var writeTimer: Timer? = nil + private var messagesStringToWrite: [String] = [] + private var messagesDataToWrite: [Data] = [] + + public init?(_ endpoint: URL, + delegate wsdelegate: Web3SocketDelegate, + projectId: String? = nil, + keystoreManager manager: KeystoreManager? = nil, + network net: Networks? = nil) { + websocketConnected = false + var endpointString = endpoint.absoluteString + if !(endpointString.hasPrefix("wss://") || endpointString.hasPrefix("ws://")) { + return nil + } + if endpointString.hasPrefix("wss://") && endpointString.hasSuffix(Constants.infuraWsScheme) { + if net == nil { + let networkString = endpointString.replacingOccurrences(of: "wss://", with: "") + .replacingOccurrences(of: Constants.infuraWsScheme, with: "") + switch networkString { + case "mainnet": + network = Networks.Mainnet + case "rinkeby": + network = Networks.Rinkeby + case "ropsten": + network = Networks.Ropsten + case "kovan": + network = Networks.Kovan + default: + break + } + } else { + network = net + } + if network != nil { + endpointString += projectId ?? Constants.infuraToken + } + } + url = URL(string: endpointString)! + delegate = wsdelegate + attachedKeystoreManager = manager + let request = URLRequest(url: url) + socket = WebSocket(request: request) + socket.delegate = self + } + + public init?(_ endpoint: String, + delegate wsdelegate: Web3SocketDelegate, + projectId: String? = nil, + keystoreManager manager: KeystoreManager? = nil, + network net: Networks? = nil) { + guard URL(string: endpoint) != nil else {return nil} + var finalEndpoint = endpoint + websocketConnected = false + if !(endpoint.hasPrefix("wss://") || endpoint.hasPrefix("ws://")) { + return nil + } + if endpoint.hasPrefix("wss://") && endpoint.hasSuffix(Constants.infuraWsScheme) { + if net == nil { + let networkString = endpoint.replacingOccurrences(of: "wss://", with: "") + .replacingOccurrences(of: Constants.infuraWsScheme, with: "") + switch networkString { + case "mainnet": + network = Networks.Mainnet + case "rinkeby": + network = Networks.Rinkeby + case "ropsten": + network = Networks.Ropsten + case "kovan": + network = Networks.Kovan + default: + break + } + } else { + network = net + } + if network != nil { + finalEndpoint += projectId ?? Constants.infuraToken + } + } + url = URL(string: finalEndpoint)! + delegate = wsdelegate + attachedKeystoreManager = manager + let request = URLRequest(url: url) + socket = WebSocket(request: request) + socket.delegate = self + } + + deinit { + writeTimer?.invalidate() + } + + public func connectSocket() { + writeTimer?.invalidate() + socket.connect() + } + + public func disconnectSocket() { + writeTimer?.invalidate() + socket.disconnect() + } + + public class func connectToSocket(_ endpoint: String, + delegate: Web3SocketDelegate, + projectId: String? = nil, + keystoreManager manager: KeystoreManager? = nil, + network net: Networks? = nil) -> WebsocketProvider? { + guard let socketProvider = WebsocketProvider(endpoint, + delegate: delegate, + projectId: projectId, + keystoreManager: manager, + network: net) else { + return nil + } + socketProvider.connectSocket() + return socketProvider + } + + public class func connectToSocket(_ endpoint: URL, + delegate: Web3SocketDelegate, + projectId: String? = nil, + keystoreManager manager: KeystoreManager? = nil, + network net: Networks? = nil) -> WebsocketProvider? { + guard let socketProvider = WebsocketProvider(endpoint, + delegate: delegate, + projectId: projectId, + keystoreManager: manager, + network: net) else { + return nil + } + socketProvider.connectSocket() + return socketProvider + } + + public func writeMessage(_ message: T) { + var sMessage: String? = nil + var dMessage: Data? = nil + if !(message.self is String) && !(message.self is Data) { + sMessage = "\(message)" + } else if message.self is String { + sMessage = message as? String + } else if message.self is Data { + dMessage = message as? Data + } + if sMessage != nil { + self.messagesStringToWrite.append(sMessage!) + } else if dMessage != nil { + self.messagesDataToWrite.append(dMessage!) + } + writeTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(performWriteOperations), userInfo: nil, repeats: true) + } + + @objc private func performWriteOperations() { + if websocketConnected { + writeTimer?.invalidate() + for s in messagesStringToWrite { + socket.write(string: s) + } + for d in messagesDataToWrite { + socket.write(data: d) + } + } + } + + public func websocketDidReceiveMessage(socket: WebSocketClient, text: String) { + print("got some text: \(text)") + delegate.received(message: text) + } + + public func websocketDidReceiveData(socket: WebSocketClient, data: Data) { + print("got some data: \(data.count)") + delegate.received(message: data) + } + + public func websocketDidConnect(socket: WebSocketClient) { + print("websocket is connected") + websocketConnected = true + } + + public func websocketDidDisconnect(socket: WebSocketClient, error: Error?) { + print("websocket is disconnected with \(error?.localizedDescription ?? "no error")") + websocketConnected = false + } + + public func websocketDidReceivePong(socket: WebSocketClient, data: Data?) { + print("Got pong! Maybe some data: \(String(describing: data?.count))") + } +} diff --git a/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3.swift b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3.swift new file mode 100755 index 000000000..60fcbfd00 --- /dev/null +++ b/Example/myWeb3Wallet/Pods/web3swift/Sources/web3swift/Web3/Web3.swift @@ -0,0 +1,85 @@ +// web3swift +// +// Created by Alex Vlasov. +// Copyright © 2018 Alex Vlasov. All rights reserved. +// + +import Foundation + +public enum Web3Error: Error { + case transactionSerializationError + case connectionError + case dataError + case walletError + case inputError(desc:String) + case nodeError(desc:String) + case processingError(desc:String) + case keystoreError(err:AbstractKeystoreError) + case generalError(err:Error) + case unknownError + + public var errorDescription: String { + switch self { + + case .transactionSerializationError: + return "Transaction Serialization Error" + case .connectionError: + return "Connection Error" + case .dataError: + return "Data Error" + case .walletError: + return "Wallet Error" + case .inputError(let desc): + return desc + case .nodeError(let desc): + return desc + case .processingError(let desc): + return desc + case .keystoreError(let err): + return err.localizedDescription + case .generalError(let err): + return err.localizedDescription + case .unknownError: + return "Unknown Error" + } + } +} + +/// An arbitary Web3 object. Is used only to construct provider bound fully functional object by either supplying provider URL +/// or using pre-coded Infura nodes +public struct 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) throws -> web3 { + guard let provider = Web3HttpProvider(providerURL) else { + throw Web3Error.inputError(desc: "Wrong provider - should be Web3HttpProvider with endpoint scheme http or https") + } + return web3(provider: provider) + } + + /// Initialized Web3 instance bound to Infura's mainnet provider. + public static func InfuraMainnetWeb3(accessToken: String? = nil) -> web3 { + let infura = InfuraProvider(Networks.Mainnet, accessToken: accessToken)! + return web3(provider: infura) + } + + /// Initialized Web3 instance bound to Infura's rinkeby provider. + public static func InfuraRinkebyWeb3(accessToken: String? = nil) -> web3 { + let infura = InfuraProvider(Networks.Rinkeby, accessToken: accessToken)! + return web3(provider: infura) + } + + /// Initialized Web3 instance bound to Infura's ropsten provider. + public static func InfuraRopstenWeb3(accessToken: String? = nil) -> web3 { + let infura = InfuraProvider(Networks.Ropsten, accessToken: accessToken)! + return web3(provider: infura) + } + + /// Initialized Web3 instance bound to Infura's kovan provider. + public static func InfuraKovanWeb3(accessToken: String? = nil) -> web3 { + let infura = InfuraProvider(Networks.Kovan, accessToken: accessToken)! + return web3(provider: infura) + } + +} diff --git a/Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.pbxproj b/Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.pbxproj new file mode 100644 index 000000000..6beaeb376 --- /dev/null +++ b/Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.pbxproj @@ -0,0 +1,815 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 55; + 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 */; }; + 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 */; }; + FA5308282721D59B002C1F06 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = FA5308262721D59B002C1F06 /* Main.storyboard */; }; + FA53082A2721D59D002C1F06 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = FA5308292721D59D002C1F06 /* Assets.xcassets */; }; + FA53082D2721D59D002C1F06 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = FA53082B2721D59D002C1F06 /* LaunchScreen.storyboard */; }; + FA5308382721D59D002C1F06 /* myWeb3WalletTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA5308372721D59D002C1F06 /* myWeb3WalletTests.swift */; }; + FA5308422721D59D002C1F06 /* myWeb3WalletUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA5308412721D59D002C1F06 /* myWeb3WalletUITests.swift */; }; + FA5308442721D59D002C1F06 /* myWeb3WalletUITestsLaunchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA5308432721D59D002C1F06 /* myWeb3WalletUITestsLaunchTests.swift */; }; + FA5308512721F5BC002C1F06 /* SplashViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA5308502721F5BC002C1F06 /* SplashViewController.swift */; }; + FA5308562721F647002C1F06 /* WalletViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA5308552721F647002C1F06 /* WalletViewController.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + FA5308342721D59D002C1F06 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = FA5308152721D59B002C1F06 /* Project object */; + proxyType = 1; + remoteGlobalIDString = FA53081C2721D59B002C1F06; + remoteInfo = myWeb3Wallet; + }; + FA53083E2721D59D002C1F06 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = FA5308152721D59B002C1F06 /* Project object */; + proxyType = 1; + remoteGlobalIDString = FA53081C2721D59B002C1F06; + remoteInfo = myWeb3Wallet; + }; +/* End PBXContainerItemProxy section */ + +/* 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 = ""; }; + FA5308242721D59B002C1F06 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; + FA5308272721D59B002C1F06 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + FA5308292721D59D002C1F06 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + FA53082C2721D59D002C1F06 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + FA53082E2721D59D002C1F06 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + FA5308332721D59D002C1F06 /* myWeb3WalletTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = myWeb3WalletTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + FA5308372721D59D002C1F06 /* myWeb3WalletTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = myWeb3WalletTests.swift; sourceTree = ""; }; + FA53083D2721D59D002C1F06 /* myWeb3WalletUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = myWeb3WalletUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + FA5308412721D59D002C1F06 /* myWeb3WalletUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = myWeb3WalletUITests.swift; sourceTree = ""; }; + FA5308432721D59D002C1F06 /* myWeb3WalletUITestsLaunchTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = myWeb3WalletUITestsLaunchTests.swift; sourceTree = ""; }; + FA5308502721F5BC002C1F06 /* SplashViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SplashViewController.swift; sourceTree = ""; }; + FA5308552721F647002C1F06 /* WalletViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WalletViewController.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + FA53081A2721D59B002C1F06 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 08D762AA7F8C96F1FEC2BDDA /* Pods_myWeb3Wallet.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FA5308302721D59D002C1F06 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 1A3D2B3177B96101E5BA3A86 /* Pods_myWeb3WalletTests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FA53083A2721D59D002C1F06 /* Frameworks */ = { + 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 = ( + D6EB035B54D0DDFE25556549 /* Pods_myWeb3Wallet.framework */, + 2DEF494BADF9FD39D553B87D /* Pods_myWeb3Wallet_myWeb3WalletUITests.framework */, + D4590F35DEE4A4CA41141602 /* Pods_myWeb3WalletTests.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + FA5308142721D59B002C1F06 = { + isa = PBXGroup; + children = ( + FA53081F2721D59B002C1F06 /* myWeb3Wallet */, + FA5308362721D59D002C1F06 /* myWeb3WalletTests */, + FA5308402721D59D002C1F06 /* myWeb3WalletUITests */, + FA53081E2721D59B002C1F06 /* Products */, + 40AC3854191B335F2FCA6C71 /* Pods */, + B67819FA7D92C1562AFD65A8 /* Frameworks */, + ); + sourceTree = ""; + }; + FA53081E2721D59B002C1F06 /* Products */ = { + isa = PBXGroup; + children = ( + FA53081D2721D59B002C1F06 /* myWeb3Wallet.app */, + FA5308332721D59D002C1F06 /* myWeb3WalletTests.xctest */, + FA53083D2721D59D002C1F06 /* myWeb3WalletUITests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + FA53081F2721D59B002C1F06 /* myWeb3Wallet */ = { + isa = PBXGroup; + children = ( + FA5308532721F615002C1F06 /* ViewController */, + FA5308522721F5C8002C1F06 /* Appdelegate */, + FA5308242721D59B002C1F06 /* ViewController.swift */, + FA5308262721D59B002C1F06 /* Main.storyboard */, + FA5308292721D59D002C1F06 /* Assets.xcassets */, + FA53082B2721D59D002C1F06 /* LaunchScreen.storyboard */, + FA53082E2721D59D002C1F06 /* Info.plist */, + FA5308502721F5BC002C1F06 /* SplashViewController.swift */, + ); + path = myWeb3Wallet; + sourceTree = ""; + }; + FA5308362721D59D002C1F06 /* myWeb3WalletTests */ = { + isa = PBXGroup; + children = ( + FA5308372721D59D002C1F06 /* myWeb3WalletTests.swift */, + ); + path = myWeb3WalletTests; + sourceTree = ""; + }; + FA5308402721D59D002C1F06 /* myWeb3WalletUITests */ = { + isa = PBXGroup; + children = ( + FA5308412721D59D002C1F06 /* myWeb3WalletUITests.swift */, + FA5308432721D59D002C1F06 /* myWeb3WalletUITestsLaunchTests.swift */, + ); + path = myWeb3WalletUITests; + sourceTree = ""; + }; + FA5308522721F5C8002C1F06 /* Appdelegate */ = { + isa = PBXGroup; + children = ( + FA5308222721D59B002C1F06 /* SceneDelegate.swift */, + FA5308202721D59B002C1F06 /* AppDelegate.swift */, + ); + path = Appdelegate; + sourceTree = ""; + }; + FA5308532721F615002C1F06 /* ViewController */ = { + isa = PBXGroup; + children = ( + FA5308542721F62E002C1F06 /* WalletController */, + ); + path = ViewController; + sourceTree = ""; + }; + FA5308542721F62E002C1F06 /* WalletController */ = { + isa = PBXGroup; + children = ( + FA5308552721F647002C1F06 /* WalletViewController.swift */, + ); + path = WalletController; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + FA53081C2721D59B002C1F06 /* myWeb3Wallet */ = { + 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; + productName = myWeb3Wallet; + productReference = FA53081D2721D59B002C1F06 /* myWeb3Wallet.app */; + productType = "com.apple.product-type.application"; + }; + FA5308322721D59D002C1F06 /* myWeb3WalletTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = FA53084A2721D59D002C1F06 /* Build configuration list for PBXNativeTarget "myWeb3WalletTests" */; + buildPhases = ( + 342829194E3F4C74B29C947B /* [CP] Check Pods Manifest.lock */, + FA53082F2721D59D002C1F06 /* Sources */, + FA5308302721D59D002C1F06 /* Frameworks */, + FA5308312721D59D002C1F06 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + FA5308352721D59D002C1F06 /* PBXTargetDependency */, + ); + name = myWeb3WalletTests; + productName = myWeb3WalletTests; + productReference = FA5308332721D59D002C1F06 /* myWeb3WalletTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + FA53083C2721D59D002C1F06 /* myWeb3WalletUITests */ = { + 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 = ( + ); + dependencies = ( + FA53083F2721D59D002C1F06 /* PBXTargetDependency */, + ); + name = myWeb3WalletUITests; + productName = myWeb3WalletUITests; + productReference = FA53083D2721D59D002C1F06 /* myWeb3WalletUITests.xctest */; + productType = "com.apple.product-type.bundle.ui-testing"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + FA5308152721D59B002C1F06 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1300; + LastUpgradeCheck = 1300; + TargetAttributes = { + FA53081C2721D59B002C1F06 = { + CreatedOnToolsVersion = 13.0; + }; + FA5308322721D59D002C1F06 = { + CreatedOnToolsVersion = 13.0; + TestTargetID = FA53081C2721D59B002C1F06; + }; + FA53083C2721D59D002C1F06 = { + CreatedOnToolsVersion = 13.0; + TestTargetID = FA53081C2721D59B002C1F06; + }; + }; + }; + buildConfigurationList = FA5308182721D59B002C1F06 /* Build configuration list for PBXProject "myWeb3Wallet" */; + compatibilityVersion = "Xcode 13.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = FA5308142721D59B002C1F06; + productRefGroup = FA53081E2721D59B002C1F06 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + FA53081C2721D59B002C1F06 /* myWeb3Wallet */, + FA5308322721D59D002C1F06 /* myWeb3WalletTests */, + FA53083C2721D59D002C1F06 /* myWeb3WalletUITests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + FA53081B2721D59B002C1F06 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + FA53082D2721D59D002C1F06 /* LaunchScreen.storyboard in Resources */, + FA53082A2721D59D002C1F06 /* Assets.xcassets in Resources */, + FA5308282721D59B002C1F06 /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FA5308312721D59D002C1F06 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FA53083B2721D59D002C1F06 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* 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; + buildActionMask = 2147483647; + files = ( + FA5308252721D59B002C1F06 /* ViewController.swift in Sources */, + FA5308212721D59B002C1F06 /* AppDelegate.swift in Sources */, + FA5308232721D59B002C1F06 /* SceneDelegate.swift in Sources */, + FA5308512721F5BC002C1F06 /* SplashViewController.swift in Sources */, + FA5308562721F647002C1F06 /* WalletViewController.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FA53082F2721D59D002C1F06 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + FA5308382721D59D002C1F06 /* myWeb3WalletTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FA5308392721D59D002C1F06 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + FA5308442721D59D002C1F06 /* myWeb3WalletUITestsLaunchTests.swift in Sources */, + FA5308422721D59D002C1F06 /* myWeb3WalletUITests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + FA5308352721D59D002C1F06 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = FA53081C2721D59B002C1F06 /* myWeb3Wallet */; + targetProxy = FA5308342721D59D002C1F06 /* PBXContainerItemProxy */; + }; + FA53083F2721D59D002C1F06 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = FA53081C2721D59B002C1F06 /* myWeb3Wallet */; + targetProxy = FA53083E2721D59D002C1F06 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + FA5308262721D59B002C1F06 /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + FA5308272721D59B002C1F06 /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + FA53082B2721D59D002C1F06 /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + FA53082C2721D59D002C1F06 /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + FA5308452721D59D002C1F06 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++17"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + FA5308462721D59D002C1F06 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++17"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + FA5308482721D59D002C1F06 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 600772647D45BC0D702D4137 /* Pods-myWeb3Wallet.debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = VPS9LBWQ55; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = myWeb3Wallet/Info.plist; + INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; + INFOPLIST_KEY_UILaunchStoryboardName = LaunchScreen; + INFOPLIST_KEY_UIMainStoryboardFile = Main; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = greenboxip.myWeb3Wallet; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + FA5308492721D59D002C1F06 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 5B0E97C0C8FE51D0241E7D19 /* Pods-myWeb3Wallet.release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = VPS9LBWQ55; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = myWeb3Wallet/Info.plist; + INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; + INFOPLIST_KEY_UILaunchStoryboardName = LaunchScreen; + INFOPLIST_KEY_UIMainStoryboardFile = Main; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = greenboxip.myWeb3Wallet; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; + FA53084B2721D59D002C1F06 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A87A2F63C4B3084139E790F5 /* Pods-myWeb3WalletTests.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = VPS9LBWQ55; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = greenboxip.myWeb3WalletTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/myWeb3Wallet.app/myWeb3Wallet"; + }; + name = Debug; + }; + FA53084C2721D59D002C1F06 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E41A5A8BF0A312348D3C52FD /* Pods-myWeb3WalletTests.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = VPS9LBWQ55; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = greenboxip.myWeb3WalletTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/myWeb3Wallet.app/myWeb3Wallet"; + }; + name = Release; + }; + FA53084E2721D59D002C1F06 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D6018FABA256C0117F85A829 /* Pods-myWeb3Wallet-myWeb3WalletUITests.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = VPS9LBWQ55; + GENERATE_INFOPLIST_FILE = YES; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = greenboxip.myWeb3WalletUITests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_TARGET_NAME = myWeb3Wallet; + }; + name = Debug; + }; + FA53084F2721D59D002C1F06 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7574A738941D92CC94F93A9E /* Pods-myWeb3Wallet-myWeb3WalletUITests.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = VPS9LBWQ55; + GENERATE_INFOPLIST_FILE = YES; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = greenboxip.myWeb3WalletUITests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_TARGET_NAME = myWeb3Wallet; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + FA5308182721D59B002C1F06 /* Build configuration list for PBXProject "myWeb3Wallet" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + FA5308452721D59D002C1F06 /* Debug */, + FA5308462721D59D002C1F06 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + FA5308472721D59D002C1F06 /* Build configuration list for PBXNativeTarget "myWeb3Wallet" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + FA5308482721D59D002C1F06 /* Debug */, + FA5308492721D59D002C1F06 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + FA53084A2721D59D002C1F06 /* Build configuration list for PBXNativeTarget "myWeb3WalletTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + FA53084B2721D59D002C1F06 /* Debug */, + FA53084C2721D59D002C1F06 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + FA53084D2721D59D002C1F06 /* Build configuration list for PBXNativeTarget "myWeb3WalletUITests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + FA53084E2721D59D002C1F06 /* Debug */, + FA53084F2721D59D002C1F06 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = FA5308152721D59B002C1F06 /* Project object */; +} diff --git a/Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..919434a62 --- /dev/null +++ b/Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/Example/myWeb3Wallet/myWeb3Wallet.xcworkspace/contents.xcworkspacedata b/Example/myWeb3Wallet/myWeb3Wallet.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..99157238b --- /dev/null +++ b/Example/myWeb3Wallet/myWeb3Wallet.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/Example/myWeb3Wallet/myWeb3Wallet.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Example/myWeb3Wallet/myWeb3Wallet.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/Example/myWeb3Wallet/myWeb3Wallet.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/Example/myWeb3Wallet/myWeb3Wallet/Appdelegate/AppDelegate.swift b/Example/myWeb3Wallet/myWeb3Wallet/Appdelegate/AppDelegate.swift new file mode 100644 index 000000000..d4f88c2b0 --- /dev/null +++ b/Example/myWeb3Wallet/myWeb3Wallet/Appdelegate/AppDelegate.swift @@ -0,0 +1,36 @@ +// +// AppDelegate.swift +// myWeb3Wallet +// +// Created by Ravi Ranjan on 21/10/21. +// + +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 + } + + // MARK: UISceneSession Lifecycle + + func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { + // Called when a new scene session is being created. + // Use this method to select a configuration to create the new scene with. + return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) + } + + func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set) { + // Called when the user discards a scene session. + // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. + // 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 new file mode 100644 index 000000000..3182cf687 --- /dev/null +++ b/Example/myWeb3Wallet/myWeb3Wallet/Appdelegate/SceneDelegate.swift @@ -0,0 +1,52 @@ +// +// SceneDelegate.swift +// myWeb3Wallet +// +// Created by Ravi Ranjan on 21/10/21. +// + +import UIKit + +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. + // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). + guard let _ = (scene as? UIWindowScene) else { return } + } + + func sceneDidDisconnect(_ scene: UIScene) { + // Called as the scene is being released by the system. + // This occurs shortly after the scene enters the background, or when its session is discarded. + // Release any resources associated with this scene that can be re-created the next time the scene connects. + // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). + } + + func sceneDidBecomeActive(_ scene: UIScene) { + // Called when the scene has moved from an inactive state to an active state. + // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. + } + + func sceneWillResignActive(_ scene: UIScene) { + // Called when the scene will move from an active state to an inactive state. + // This may occur due to temporary interruptions (ex. an incoming phone call). + } + + func sceneWillEnterForeground(_ scene: UIScene) { + // Called as the scene transitions from the background to the foreground. + // Use this method to undo the changes made on entering the background. + } + + func sceneDidEnterBackground(_ scene: UIScene) { + // Called as the scene transitions from the foreground to the background. + // Use this method to save data, release shared resources, and store enough scene-specific state information + // to restore the scene back to its current state. + } + + +} + diff --git a/Example/myWeb3Wallet/myWeb3Wallet/Assets.xcassets/AccentColor.colorset/Contents.json b/Example/myWeb3Wallet/myWeb3Wallet/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 000000000..eb8789700 --- /dev/null +++ b/Example/myWeb3Wallet/myWeb3Wallet/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,11 @@ +{ + "colors" : [ + { + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Example/myWeb3Wallet/myWeb3Wallet/Assets.xcassets/AppIcon.appiconset/Contents.json b/Example/myWeb3Wallet/myWeb3Wallet/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 000000000..9221b9bb1 --- /dev/null +++ b/Example/myWeb3Wallet/myWeb3Wallet/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,98 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "20x20" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "20x20" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "29x29" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "29x29" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "40x40" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "40x40" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "60x60" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "60x60" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "20x20" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "20x20" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "29x29" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "29x29" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "40x40" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "40x40" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "76x76" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "76x76" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "83.5x83.5" + }, + { + "idiom" : "ios-marketing", + "scale" : "1x", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Example/myWeb3Wallet/myWeb3Wallet/Assets.xcassets/Contents.json b/Example/myWeb3Wallet/myWeb3Wallet/Assets.xcassets/Contents.json new file mode 100644 index 000000000..73c00596a --- /dev/null +++ b/Example/myWeb3Wallet/myWeb3Wallet/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Example/myWeb3Wallet/myWeb3Wallet/Base.lproj/LaunchScreen.storyboard b/Example/myWeb3Wallet/myWeb3Wallet/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 000000000..865e9329f --- /dev/null +++ b/Example/myWeb3Wallet/myWeb3Wallet/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Example/myWeb3Wallet/myWeb3Wallet/Base.lproj/Main.storyboard b/Example/myWeb3Wallet/myWeb3Wallet/Base.lproj/Main.storyboard new file mode 100644 index 000000000..0625e8a6a --- /dev/null +++ b/Example/myWeb3Wallet/myWeb3Wallet/Base.lproj/Main.storyboard @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Example/myWeb3Wallet/myWeb3Wallet/Info.plist b/Example/myWeb3Wallet/myWeb3Wallet/Info.plist new file mode 100644 index 000000000..dd3c9afda --- /dev/null +++ b/Example/myWeb3Wallet/myWeb3Wallet/Info.plist @@ -0,0 +1,25 @@ + + + + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneConfigurationName + Default Configuration + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + + diff --git a/Example/myWeb3Wallet/myWeb3Wallet/SplashViewController.swift b/Example/myWeb3Wallet/myWeb3Wallet/SplashViewController.swift new file mode 100644 index 000000000..141c357ba --- /dev/null +++ b/Example/myWeb3Wallet/myWeb3Wallet/SplashViewController.swift @@ -0,0 +1,28 @@ +// +// SplashViewController.swift +// myWeb3Wallet +// +// Created by Ravi Ranjan on 22/10/21. +// + +import UIKit + +class SplashViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + Timer.scheduledTimer(timeInterval: 0.6, target: self, selector: #selector(self.moveToWalletView), userInfo: nil, repeats: false) + + // Do any additional setup after loading the view. + } + @objc func moveToWalletView(){ + + guard let walletScreen = self.storyboard?.instantiateViewController(withIdentifier: "WalletViewController") as? WalletViewController else { + #if DEBUG + printContent("Unable to get Wallet controller") + #endif + return + } + self.navigationController?.pushViewController(walletScreen, animated: true) + } +} diff --git a/Example/myWeb3Wallet/myWeb3Wallet/ViewController.swift b/Example/myWeb3Wallet/myWeb3Wallet/ViewController.swift new file mode 100644 index 000000000..de12eaa06 --- /dev/null +++ b/Example/myWeb3Wallet/myWeb3Wallet/ViewController.swift @@ -0,0 +1,19 @@ +// +// ViewController.swift +// myWeb3Wallet +// +// Created by Ravi Ranjan on 21/10/21. +// + +import UIKit + +class ViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + // Do any additional setup after loading the view. + } + + +} + diff --git a/Example/myWeb3Wallet/myWeb3Wallet/ViewController/WalletController/WalletViewController.swift b/Example/myWeb3Wallet/myWeb3Wallet/ViewController/WalletController/WalletViewController.swift new file mode 100644 index 000000000..bf4829909 --- /dev/null +++ b/Example/myWeb3Wallet/myWeb3Wallet/ViewController/WalletController/WalletViewController.swift @@ -0,0 +1,128 @@ +// +// WalletViewController.swift +// myWeb3Wallet +// +// Created by Ravi Ranjan on 22/10/21. +// + +import UIKit +import web3swift +class WalletViewController: UIViewController { + + @IBOutlet weak var walletAddressLabel: UILabel! + @IBOutlet weak var importWalletButton: UIButton! + @IBOutlet weak var createWalletButton: UIButton! + override func viewDidLoad() { + super.viewDidLoad() + self.createWalletButton.layer.cornerCurve = .continuous + self.importWalletButton.layer.cornerCurve = .continuous + + // 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) { +#if DEBUG + print("Clicked on import Wallet Option") +#endif + let alert = UIAlertController(title: "MyWeb3Wallet", message: "", preferredStyle: .alert) + alert.addTextField { textfied in + textfied.placeholder = "Enter mnemonics/private Key" + } + let mnemonicsAction = UIAlertAction(title: "Mnemonics", style: .default) { _ in +#if DEBUG + print("Clicked on Mnemonics Option") +#endif + guard let mnemonics = alert.textFields?[0].text else { return } + print(mnemonics) + } + let privateKeyAction = UIAlertAction(title: "Private Key", style: .default) { _ in +#if DEBUG + print("Clicked on Private Key Wallet Option") +#endif + 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) + alert.addAction(privateKeyAction) + alert.addAction(cancelAction) + + self.present(alert, animated: true, completion: nil) + } + + + 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) + if let myWeb3KeyStore = keystore { + let manager = KeystoreManager([myWeb3KeyStore]) + let address = keystore?.addresses?.first +#if DEBUG + print("Address :::>>>>> ", address as Any) + print("Address :::>>>>> ", manager.addresses as Any) +#endif + let walletAddress = manager.addresses?.first?.address + self.walletAddressLabel.text = walletAddress ?? "0x" + + print(walletAddress as Any) + } else { + print("error") + } + } catch { +#if DEBUG + print("error creating keyStrore") + print("Private key error.") +#endif + let alert = UIAlertController(title: "Error", message: "Please enter correct Private key", preferredStyle: .alert) + let okAction = UIAlertAction(title: "OK", style: .destructive) + 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 as Any) + self.walletAddressLabel.text = "\(walletAddress?.addresses?.first?.address ?? "0x")" + + } + + +} +extension WalletViewController { + + fileprivate func createMnemonics(){ + let mnemonics = try? BIP39.generateMnemonics(bitsOfEntropy: 256, language: .english) + print(mnemonics as Any) + let walletAddress = try? BIP32Keystore(mnemonics: mnemonics ?? "", prefixPath: "m/44'/77777'/0'/0") + print(walletAddress?.addresses as Any) + self.walletAddressLabel.text = "\(walletAddress?.addresses?.first?.address ?? "0x")" + + + } +} +extension UIViewController { + func showAlertMessage(title: String = "MyWeb3Wallet", message: String = "Message is empty", actionName: String = "OK") { + let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) + let action = UIAlertAction.init(title: actionName, style: .destructive) + alertController.addAction(action) + self.present(alertController, animated: true) + } +} diff --git a/Example/myWeb3Wallet/myWeb3WalletTests/myWeb3WalletTests.swift b/Example/myWeb3Wallet/myWeb3WalletTests/myWeb3WalletTests.swift new file mode 100644 index 000000000..5483bc0a0 --- /dev/null +++ b/Example/myWeb3Wallet/myWeb3WalletTests/myWeb3WalletTests.swift @@ -0,0 +1,33 @@ +// +// myWeb3WalletTests.swift +// myWeb3WalletTests +// +// Created by Ravi Ranjan on 21/10/21. +// + +import XCTest +@testable import myWeb3Wallet + +class myWeb3WalletTests: XCTestCase { + + override func setUpWithError() throws { + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + override func tearDownWithError() throws { + // Put teardown code here. This method is called after the invocation of each test method in the class. + } + + func testExample() throws { + // This is an example of a functional test case. + // Use XCTAssert and related functions to verify your tests produce the correct results. + } + + func testPerformanceExample() throws { + // This is an example of a performance test case. + self.measure { + // Put the code you want to measure the time of here. + } + } + +} diff --git a/Example/myWeb3Wallet/myWeb3WalletUITests/myWeb3WalletUITests.swift b/Example/myWeb3Wallet/myWeb3WalletUITests/myWeb3WalletUITests.swift new file mode 100644 index 000000000..ca6b08715 --- /dev/null +++ b/Example/myWeb3Wallet/myWeb3WalletUITests/myWeb3WalletUITests.swift @@ -0,0 +1,42 @@ +// +// myWeb3WalletUITests.swift +// myWeb3WalletUITests +// +// Created by Ravi Ranjan on 21/10/21. +// + +import XCTest + +class myWeb3WalletUITests: XCTestCase { + + override func setUpWithError() throws { + // Put setup code here. This method is called before the invocation of each test method in the class. + + // In UI tests it is usually best to stop immediately when a failure occurs. + continueAfterFailure = false + + // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. + } + + override func tearDownWithError() throws { + // Put teardown code here. This method is called after the invocation of each test method in the class. + } + + func testExample() throws { + // UI tests must launch the application that they test. + let app = XCUIApplication() + app.launch() + + // Use recording to get started writing UI tests. + // Use XCTAssert and related functions to verify your tests produce the correct results. + } + + func testLaunchPerformance() throws { + if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) { + // This measures how long it takes to launch your application. + measure(metrics: [XCTApplicationLaunchMetric()]) { + XCUIApplication().launch() + } + } + } +} diff --git a/Example/myWeb3Wallet/myWeb3WalletUITests/myWeb3WalletUITestsLaunchTests.swift b/Example/myWeb3Wallet/myWeb3WalletUITests/myWeb3WalletUITestsLaunchTests.swift new file mode 100644 index 000000000..6f0e95219 --- /dev/null +++ b/Example/myWeb3Wallet/myWeb3WalletUITests/myWeb3WalletUITestsLaunchTests.swift @@ -0,0 +1,32 @@ +// +// myWeb3WalletUITestsLaunchTests.swift +// myWeb3WalletUITests +// +// Created by Ravi Ranjan on 21/10/21. +// + +import XCTest + +class myWeb3WalletUITestsLaunchTests: XCTestCase { + + override class var runsForEachTargetApplicationUIConfiguration: Bool { + true + } + + override func setUpWithError() throws { + continueAfterFailure = false + } + + func testLaunch() throws { + let app = XCUIApplication() + app.launch() + + // Insert steps here to perform after app launch but before taking a screenshot, + // such as logging into a test account or navigating somewhere in the app + + let attachment = XCTAttachment(screenshot: app.screenshot()) + attachment.name = "Launch Screen" + attachment.lifetime = .keepAlways + add(attachment) + } +} From fd8f14e6f97359d93dec96cc545bf29a62282324 Mon Sep 17 00:00:00 2001 From: Ravi Ranjan Date: Fri, 22 Oct 2021 17:59:55 +0530 Subject: [PATCH 11/12] Example project for Wallet -> Create wallet , Import wallet --- carthage-build.sh => " m\342\211\245.sh" | 0 .../Pods/Pods.xcodeproj/project.pbxproj | 92 ++++++++---------- .../myWeb3Wallet.xcodeproj/project.pbxproj | 6 +- .../swift.imageset/Contents.json | 21 ++++ .../Assets.xcassets/swift.imageset/swift.png | Bin 0 -> 6583 bytes .../Base.lproj/LaunchScreen.storyboard | 40 +++++++- .../myWeb3Wallet/Base.lproj/Main.storyboard | 65 ++++++++++++- .../DashboardViewController.swift | 34 +++++++ .../SplashViewController.swift | 9 +- .../WalletViewController.swift | 73 ++++++++++---- 10 files changed, 263 insertions(+), 77 deletions(-) rename carthage-build.sh => " m\342\211\245.sh" (100%) create mode 100644 Example/myWeb3Wallet/myWeb3Wallet/Assets.xcassets/swift.imageset/Contents.json create mode 100644 Example/myWeb3Wallet/myWeb3Wallet/Assets.xcassets/swift.imageset/swift.png create mode 100644 Example/myWeb3Wallet/myWeb3Wallet/ViewController/WalletController/DashboardViewController.swift rename Example/myWeb3Wallet/myWeb3Wallet/{ => ViewController/WalletController}/SplashViewController.swift (69%) diff --git a/carthage-build.sh "b/ m\342\211\245.sh" similarity index 100% rename from carthage-build.sh rename to " m\342\211\245.sh" diff --git a/Example/myWeb3Wallet/Pods/Pods.xcodeproj/project.pbxproj b/Example/myWeb3Wallet/Pods/Pods.xcodeproj/project.pbxproj index d932bd39a..31d5dac83 100644 --- a/Example/myWeb3Wallet/Pods/Pods.xcodeproj/project.pbxproj +++ b/Example/myWeb3Wallet/Pods/Pods.xcodeproj/project.pbxproj @@ -212,7 +212,7 @@ 86954D3235BD19D7B94330AC9CA0D5AB /* Web3+ReadingTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61329F3723A6B1ABEF3BBCD12675C0C1 /* Web3+ReadingTransaction.swift */; }; 86AC32BC3900B807699D31D22C06A16C /* Web3+Personal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D7BC9EE36F90A14659788AD767DB322 /* Web3+Personal.swift */; }; 8919A8100FF0A5D62AB5D254FC884684 /* afterlife.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB23B3EF1286E7A0B48DF6ED3428E86B /* afterlife.swift */; }; - 89516187419F3D7FC4037DC8931E2A2A /* web3swift-Browser in Resources */ = {isa = PBXBuildFile; fileRef = 12DC6A0FDF284A2C935F5EA9F6111B0B /* web3swift-Browser */; }; + 89516187419F3D7FC4037DC8931E2A2A /* Browser.bundle in Resources */ = {isa = PBXBuildFile; fileRef = 12DC6A0FDF284A2C935F5EA9F6111B0B /* Browser.bundle */; }; 899599790D1F3E0DE49CA1985E123C35 /* UIView+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 3C843E59BC22FDE9FDA54491D8F3ECCC /* UIView+AnyPromise.m */; }; 89F43849392A22634685D2CC339648EA /* AES.swift in Sources */ = {isa = PBXBuildFile; fileRef = 889E3ECE5439BC9C800DFD88ED2F04BD /* AES.swift */; }; 8A6DA5FBD77B428568A3F4C38F6B0DE1 /* scalar.h in Headers */ = {isa = PBXBuildFile; fileRef = C798B4F4D8097C83111B844CBB1C3CE6 /* scalar.h */; settings = {ATTRIBUTES = (Project, ); }; }; @@ -503,7 +503,7 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 002B1E88BA14EBF633CD66EBFBA107E9 /* PromiseKit */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = PromiseKit; path = PromiseKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 002B1E88BA14EBF633CD66EBFBA107E9 /* PromiseKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PromiseKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 0050F742D824A11AEB8424E0DD2C63DE /* AbstractKeystore.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AbstractKeystore.swift; path = Sources/web3swift/KeystoreManager/AbstractKeystore.swift; sourceTree = ""; }; 00C245DA669E6E0BBAFA3115D6823007 /* BIP39.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BIP39.swift; path = Sources/web3swift/KeystoreManager/BIP39.swift; sourceTree = ""; }; 01316651403CC05C86D98D47F9CF04B3 /* Starscream-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Starscream-prefix.pch"; sourceTree = ""; }; @@ -530,7 +530,7 @@ 11657185FCE37F7674E70752DFF319F7 /* Cryptors.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Cryptors.swift; path = Sources/CryptoSwift/Cryptors.swift; sourceTree = ""; }; 127BE2CFB3F3A1C174D216B55D11EBAD /* Web3+Eth+Websocket.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Eth+Websocket.swift"; path = "Sources/web3swift/Web3/Web3+Eth+Websocket.swift"; sourceTree = ""; }; 12CFBD6C81A2CE71BA2C4F590B5D5927 /* util.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = util.h; path = secp256k1/util.h; sourceTree = ""; }; - 12DC6A0FDF284A2C935F5EA9F6111B0B /* web3swift-Browser */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; name = "web3swift-Browser"; path = Browser.bundle; sourceTree = BUILT_PRODUCTS_DIR; }; + 12DC6A0FDF284A2C935F5EA9F6111B0B /* Browser.bundle */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = Browser.bundle; sourceTree = BUILT_PRODUCTS_DIR; }; 138407359512A2D920EEDD6C7AEDDF81 /* ecmult.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecmult.h; path = secp256k1/ecmult.h; sourceTree = ""; }; 14105AEFAD47B97BBFD0A972AA98DF35 /* Pods-myWeb3Wallet-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-myWeb3Wallet-umbrella.h"; sourceTree = ""; }; 141B6AEB28CFF06BE48234968D5F6490 /* GCM.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GCM.swift; path = Sources/CryptoSwift/BlockMode/GCM.swift; sourceTree = ""; }; @@ -567,13 +567,13 @@ 2AEB64E397C62A9D958096179BE64189 /* Division.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Division.swift; path = Sources/Division.swift; sourceTree = ""; }; 2B5918B5A16C03780E709CF2CDD1104C /* ABIParameterTypes.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ABIParameterTypes.swift; path = Sources/web3swift/EthereumABI/ABIParameterTypes.swift; sourceTree = ""; }; 2CA6A6221D6CA8057D71BA60A8DAF0EF /* eckey_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = eckey_impl.h; path = secp256k1/eckey_impl.h; sourceTree = ""; }; - 2D1CFEA76FE44A2E6511787F74D0794C /* wk.bridge.min.js */ = {isa = PBXFileReference; includeInIndex = 1; name = wk.bridge.min.js; path = Sources/web3swift/Browser/wk.bridge.min.js; sourceTree = ""; }; + 2D1CFEA76FE44A2E6511787F74D0794C /* wk.bridge.min.js */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.javascript; name = wk.bridge.min.js; path = Sources/web3swift/Browser/wk.bridge.min.js; sourceTree = ""; }; 2DDB8CD09F1100772FC894971E35ECF6 /* BlockCipher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BlockCipher.swift; path = Sources/CryptoSwift/BlockCipher.swift; sourceTree = ""; }; 2E5F6F994922528B6B9B3A5BB5E2DA3A /* Square Root.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Square Root.swift"; path = "Sources/Square Root.swift"; sourceTree = ""; }; 307663AAE1B15058CDCC30A8C3B476C6 /* PromiseKit-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "PromiseKit-Info.plist"; sourceTree = ""; }; 30F6DD109D1E925101993EF13CC1B6DD /* Encodable+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Encodable+Extensions.swift"; path = "Sources/web3swift/Convenience/Encodable+Extensions.swift"; sourceTree = ""; }; 3241E63D9616921B2EB997B33DA65015 /* Bitwise Ops.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Bitwise Ops.swift"; path = "Sources/Bitwise Ops.swift"; sourceTree = ""; }; - 332A47430CFF99501D563788C7AAF1D2 /* secp256k1.c */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = secp256k1.c; path = secp256k1.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 332A47430CFF99501D563788C7AAF1D2 /* secp256k1.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = secp256k1.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 3339301FC43964D4764CDC289EBDD39E /* ABIEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ABIEncoding.swift; path = Sources/web3swift/EthereumABI/ABIEncoding.swift; sourceTree = ""; }; 33D9C3E44151CA8DAEC4B95DEEE84E07 /* Array+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Array+Extension.swift"; path = "Sources/CryptoSwift/Array+Extension.swift"; sourceTree = ""; }; 3402BA34F808F411E48E41CD59F05FCE /* Web3+ERC1643.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1643.swift"; path = "Sources/web3swift/Tokens/ERC1643/Web3+ERC1643.swift"; sourceTree = ""; }; @@ -711,23 +711,23 @@ 8456FEA753DE9A90D304EA54DFD5DAD3 /* NSURLSession+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSURLSession+AnyPromise.m"; path = "Extensions/Foundation/Sources/NSURLSession+AnyPromise.m"; sourceTree = ""; }; 8552720D720D203E2444F5263C6A4021 /* PBKDF1.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PBKDF1.swift; path = Sources/CryptoSwift/PKCS/PBKDF1.swift; sourceTree = ""; }; 856EEADEDD158D4873F666AE218DE570 /* PMKUIKit.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PMKUIKit.h; path = Extensions/UIKit/Sources/PMKUIKit.h; sourceTree = ""; }; - 85D99C55C6D2A7368634E17D0FC07D22 /* secp256k1.c */ = {isa = PBXFileReference; includeInIndex = 1; name = secp256k1.c; path = secp256k1/secp256k1.c; sourceTree = ""; }; + 85D99C55C6D2A7368634E17D0FC07D22 /* secp256k1.c */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.c; name = secp256k1.c; path = secp256k1/secp256k1.c; sourceTree = ""; }; 861A826AE843EA63A9502FDE98A45BB7 /* num_gmp_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = num_gmp_impl.h; path = secp256k1/num_gmp_impl.h; sourceTree = ""; }; 871B8E61AECB22BF7E4F511683743783 /* Pods-myWeb3Wallet-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-myWeb3Wallet-Info.plist"; sourceTree = ""; }; 878D77F928A64BCC11C2A541B02CA9F2 /* Pods-myWeb3Wallet.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-myWeb3Wallet.release.xcconfig"; sourceTree = ""; }; 889E3ECE5439BC9C800DFD88ED2F04BD /* AES.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AES.swift; path = Sources/CryptoSwift/AES.swift; sourceTree = ""; }; 8907A4B63AEF5B00260E490E38ACCE3E /* BigUInt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BigUInt.swift; path = Sources/BigUInt.swift; sourceTree = ""; }; - 891B2270823847ED23F2ECFC28F935EC /* Starscream */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Starscream; path = Starscream.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 891B2270823847ED23F2ECFC28F935EC /* Starscream.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Starscream.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 89216AD64050A687049C2812AE6F2D3D /* secp256k1.c.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = secp256k1.c.modulemap; sourceTree = ""; }; 89E3E5798A0F9C8B82F89E4AA1C9B933 /* firstly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = firstly.swift; path = Sources/firstly.swift; sourceTree = ""; }; - 8A2449DF78D58AD33A7C7504BB3F38A0 /* web3swift */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = web3swift; path = web3swift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 8A2449DF78D58AD33A7C7504BB3F38A0 /* web3swift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = web3swift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 8AA0DDDD58D43515BE066493834EE7F7 /* HTTPHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HTTPHandler.swift; path = Sources/Framer/HTTPHandler.swift; sourceTree = ""; }; 8AFCDD28CDD4C6AB23094990AABE6DE9 /* AES.Cryptors.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AES.Cryptors.swift; path = Sources/CryptoSwift/AES.Cryptors.swift; sourceTree = ""; }; 8C020773045EBAC1BB6CC4DCF9CF70E8 /* Pods-myWeb3WalletTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-myWeb3WalletTests-dummy.m"; sourceTree = ""; }; 8D144717D9392F89398A95CE943E7FCD /* ecmult_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecmult_impl.h; path = secp256k1/ecmult_impl.h; sourceTree = ""; }; 8DB09F270FE9B4BDA5AFBD4357E646CE /* Pods-myWeb3Wallet-myWeb3WalletUITests */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = "Pods-myWeb3Wallet-myWeb3WalletUITests"; path = Pods_myWeb3Wallet_myWeb3WalletUITests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 8DC49762D0D20DA70D0F705EC08E302F /* after.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = after.m; path = Sources/after.m; sourceTree = ""; }; - 91BB24BA472AF523E913108C9AA301F2 /* BigInt */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = BigInt; path = BigInt.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 91BB24BA472AF523E913108C9AA301F2 /* BigInt.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = BigInt.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 91E170E8B0E46F448434AEDA45BE7201 /* Comparable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Comparable.swift; path = Sources/Comparable.swift; sourceTree = ""; }; 9217736E16B090E354FA8D7B1F16A693 /* BigInt.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = BigInt.debug.xcconfig; sourceTree = ""; }; 9272051904F9CDACCBD8DE527C05C8A0 /* PMKFoundation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PMKFoundation.h; path = Extensions/Foundation/Sources/PMKFoundation.h; sourceTree = ""; }; @@ -751,7 +751,7 @@ 9B72CCFE3D10F1F6A2457EC5730BA509 /* Promise+Web3+Eth+GetAccounts.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+GetAccounts.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+GetAccounts.swift"; sourceTree = ""; }; 9C1F8F8C962B269D1B535A7E69211345 /* Codable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Codable.swift; path = Sources/Codable.swift; sourceTree = ""; }; 9CDA08FC40E440445F5B1C2087699FA4 /* Data+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Data+Extension.swift"; path = "Sources/web3swift/Convenience/Data+Extension.swift"; sourceTree = ""; }; - 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; 9DA7F20BAF89DD9B24B85E9A1A2B4FD2 /* ENSReverseRegistrar.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ENSReverseRegistrar.swift; path = Sources/web3swift/Utils/ENS/ENSReverseRegistrar.swift; sourceTree = ""; }; 9DBB832EE6B1A46B6B06C03F1FB46839 /* Promise+Web3+Eth+GetGasPrice.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+GetGasPrice.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+GetGasPrice.swift"; sourceTree = ""; }; 9DFDD8684C07E988EE7BEF8AB894F1C3 /* Web3+ERC888.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC888.swift"; path = "Sources/web3swift/Tokens/ERC888/Web3+ERC888.swift"; sourceTree = ""; }; @@ -785,7 +785,7 @@ B283E7DB525627BCDF8B64F25F729738 /* Promise+HttpProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+HttpProvider.swift"; path = "Sources/web3swift/Promises/Promise+HttpProvider.swift"; sourceTree = ""; }; B2D684B79FC7FFF779E5AF645F1E8129 /* RIPEMD160+StackOveflow.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "RIPEMD160+StackOveflow.swift"; path = "Sources/web3swift/Convenience/RIPEMD160+StackOveflow.swift"; sourceTree = ""; }; B373FED6638B961B7A97AABD5280E615 /* Promise+Web3+Eth+Call.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Web3+Eth+Call.swift"; path = "Sources/web3swift/Promises/Promise+Web3+Eth+Call.swift"; sourceTree = ""; }; - B3B83F5426FCB99B70C9BA58611231F2 /* browser.min.js */ = {isa = PBXFileReference; includeInIndex = 1; name = browser.min.js; path = Sources/web3swift/Browser/browser.min.js; sourceTree = ""; }; + B3B83F5426FCB99B70C9BA58611231F2 /* browser.min.js */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.javascript; name = browser.min.js; path = Sources/web3swift/Browser/browser.min.js; sourceTree = ""; }; B3CA76593B24771BFE57E65E82FABF4D /* hash.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = hash.h; path = secp256k1/hash.h; sourceTree = ""; }; B4C26BFD4C4F0041CB43065B7C15190C /* Blowfish.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Blowfish.swift; path = Sources/CryptoSwift/Blowfish.swift; sourceTree = ""; }; B4FC29C6A531D0517444640A0FDF354E /* Pods-myWeb3Wallet-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-myWeb3Wallet-acknowledgements.plist"; sourceTree = ""; }; @@ -869,7 +869,7 @@ E4A02AC333F90D23C1B6F38D7E3EAFD0 /* Pods-myWeb3WalletTests-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-myWeb3WalletTests-Info.plist"; sourceTree = ""; }; E55E8B81407082884426231F92E19AED /* Cipher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Cipher.swift; path = Sources/CryptoSwift/Cipher.swift; sourceTree = ""; }; E6C3B21AB95E51A2D26F2C42C0A2C164 /* basic-config.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "basic-config.h"; path = "secp256k1/basic-config.h"; sourceTree = ""; }; - E71A523B7024293D61E1102B9CC22823 /* browser.js */ = {isa = PBXFileReference; includeInIndex = 1; name = browser.js; path = Sources/web3swift/Browser/browser.js; sourceTree = ""; }; + E71A523B7024293D61E1102B9CC22823 /* browser.js */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.javascript; name = browser.js; path = Sources/web3swift/Browser/browser.js; sourceTree = ""; }; E725C147A5A1C727AA89210D74D57CBF /* Utils+Foundation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Utils+Foundation.swift"; path = "Sources/CryptoSwift/Foundation/Utils+Foundation.swift"; sourceTree = ""; }; E76D73543A413D250E98C170B65439FE /* StringHTTPHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StringHTTPHandler.swift; path = Sources/Framer/StringHTTPHandler.swift; sourceTree = ""; }; E77EA545335C3D935F993E0EC64F9B1D /* NSURLSession+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSURLSession+Promise.swift"; path = "Extensions/Foundation/Sources/NSURLSession+Promise.swift"; sourceTree = ""; }; @@ -897,7 +897,7 @@ F7902A028BC075F44A5B91EA5C782640 /* Configuration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Configuration.swift; path = Sources/Configuration.swift; sourceTree = ""; }; F7C0A6F898A3FC267475D1DAA9F64305 /* ecmult_const_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecmult_const_impl.h; path = secp256k1/ecmult_const_impl.h; sourceTree = ""; }; F7C21A8D4CE9BE9389B1B027A7F1684A /* Floating Point Conversion.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Floating Point Conversion.swift"; path = "Sources/Floating Point Conversion.swift"; sourceTree = ""; }; - F81274EDB681F11E7CB05F7DCA2BB33C /* CryptoSwift */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = CryptoSwift; path = CryptoSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + F81274EDB681F11E7CB05F7DCA2BB33C /* CryptoSwift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = CryptoSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; F8A625D05EC1B896D29CA0FCFF4B4395 /* CMAC.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CMAC.swift; path = Sources/CryptoSwift/CMAC.swift; sourceTree = ""; }; F8C128F18673E79A6E143D83ECDB3AEB /* Framer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Framer.swift; path = Sources/Framer/Framer.swift; sourceTree = ""; }; F91048DD1C7E59A1DD091512416C06A4 /* Web3+Wallet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Wallet.swift"; path = "Sources/web3swift/HookedFunctions/Web3+Wallet.swift"; sourceTree = ""; }; @@ -1064,16 +1064,16 @@ 0DF01B081E3CE50BBDCBDC81675BF37D /* Products */ = { isa = PBXGroup; children = ( - 91BB24BA472AF523E913108C9AA301F2 /* BigInt */, - F81274EDB681F11E7CB05F7DCA2BB33C /* CryptoSwift */, + 91BB24BA472AF523E913108C9AA301F2 /* BigInt.framework */, + F81274EDB681F11E7CB05F7DCA2BB33C /* CryptoSwift.framework */, 08A8472B9823BC68472175977392F4B9 /* Pods-myWeb3Wallet */, 8DB09F270FE9B4BDA5AFBD4357E646CE /* Pods-myWeb3Wallet-myWeb3WalletUITests */, 11103C5C5CFDD9B3B2EA4E84B98049A8 /* Pods-myWeb3WalletTests */, - 002B1E88BA14EBF633CD66EBFBA107E9 /* PromiseKit */, - 332A47430CFF99501D563788C7AAF1D2 /* secp256k1.c */, - 891B2270823847ED23F2ECFC28F935EC /* Starscream */, - 8A2449DF78D58AD33A7C7504BB3F38A0 /* web3swift */, - 12DC6A0FDF284A2C935F5EA9F6111B0B /* web3swift-Browser */, + 002B1E88BA14EBF633CD66EBFBA107E9 /* PromiseKit.framework */, + 332A47430CFF99501D563788C7AAF1D2 /* secp256k1.framework */, + 891B2270823847ED23F2ECFC28F935EC /* Starscream.framework */, + 8A2449DF78D58AD33A7C7504BB3F38A0 /* web3swift.framework */, + 12DC6A0FDF284A2C935F5EA9F6111B0B /* Browser.bundle */, ); name = Products; sourceTree = ""; @@ -1182,7 +1182,6 @@ C3548788EB8345E15691BB5699B8300D /* Support Files */, E4252E85FC6716FF11013746B8F44E37 /* UIKit */, ); - name = PromiseKit; path = PromiseKit; sourceTree = ""; }; @@ -1293,7 +1292,6 @@ 5CC9E23320B8991F34BC31A01FB21A1C /* ZeroPadding.swift */, B1F341B2BE61C900DD9EA2A9B56A8FB9 /* Support Files */, ); - name = CryptoSwift; path = CryptoSwift; sourceTree = ""; }; @@ -1434,7 +1432,6 @@ 37EB84EB9EE271BE501D87C519F8420A /* Resources */, 572EDFECC902962660EEB1CB04EA2F19 /* Support Files */, ); - name = web3swift; path = web3swift; sourceTree = ""; }; @@ -1488,7 +1485,6 @@ 12CFBD6C81A2CE71BA2C4F590B5D5927 /* util.h */, 4FA755BC662B391E20D9C601F408FC81 /* Support Files */, ); - name = secp256k1.c; path = secp256k1.c; sourceTree = ""; }; @@ -1590,7 +1586,6 @@ 5C8F369ECC895BB94124AC2173EB80ED /* Words and Bits.swift */, 80B7A94A648E0A02BA2B76640AFA293F /* Support Files */, ); - name = BigInt; path = BigInt; sourceTree = ""; }; @@ -1619,7 +1614,6 @@ 3B81B518FB1855580F5B38EBB277693E /* WSEngine.swift */, 38FF7B99E4C0BC8A75F62E500F3A8994 /* Support Files */, ); - name = Starscream; path = Starscream; sourceTree = ""; }; @@ -1789,7 +1783,7 @@ ); name = BigInt; productName = BigInt; - productReference = 91BB24BA472AF523E913108C9AA301F2 /* BigInt */; + productReference = 91BB24BA472AF523E913108C9AA301F2 /* BigInt.framework */; productType = "com.apple.product-type.framework"; }; 161C26511FC920CB146236AB7295D5E0 /* secp256k1.c */ = { @@ -1807,7 +1801,7 @@ ); name = secp256k1.c; productName = secp256k1; - productReference = 332A47430CFF99501D563788C7AAF1D2 /* secp256k1.c */; + productReference = 332A47430CFF99501D563788C7AAF1D2 /* secp256k1.framework */; productType = "com.apple.product-type.framework"; }; 7C579CE66A1E7A9AA33CA5F97F9C22C5 /* PromiseKit */ = { @@ -1825,7 +1819,7 @@ ); name = PromiseKit; productName = PromiseKit; - productReference = 002B1E88BA14EBF633CD66EBFBA107E9 /* PromiseKit */; + productReference = 002B1E88BA14EBF633CD66EBFBA107E9 /* PromiseKit.framework */; productType = "com.apple.product-type.framework"; }; 8CDD759A6130CA265C6D157F4407C39B /* web3swift-Browser */ = { @@ -1842,7 +1836,7 @@ ); name = "web3swift-Browser"; productName = Browser; - productReference = 12DC6A0FDF284A2C935F5EA9F6111B0B /* web3swift-Browser */; + productReference = 12DC6A0FDF284A2C935F5EA9F6111B0B /* Browser.bundle */; productType = "com.apple.product-type.bundle"; }; 99313990C1D76A6D1D017868B6975CC8 /* CryptoSwift */ = { @@ -1860,7 +1854,7 @@ ); name = CryptoSwift; productName = CryptoSwift; - productReference = F81274EDB681F11E7CB05F7DCA2BB33C /* CryptoSwift */; + productReference = F81274EDB681F11E7CB05F7DCA2BB33C /* CryptoSwift.framework */; productType = "com.apple.product-type.framework"; }; 99364D9FB07EF3FA5DFE1237001805EC /* web3swift */ = { @@ -1884,7 +1878,7 @@ ); name = web3swift; productName = web3swift; - productReference = 8A2449DF78D58AD33A7C7504BB3F38A0 /* web3swift */; + productReference = 8A2449DF78D58AD33A7C7504BB3F38A0 /* web3swift.framework */; productType = "com.apple.product-type.framework"; }; 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */ = { @@ -1902,7 +1896,7 @@ ); name = Starscream; productName = Starscream; - productReference = 891B2270823847ED23F2ECFC28F935EC /* Starscream */; + productReference = 891B2270823847ED23F2ECFC28F935EC /* Starscream.framework */; productType = "com.apple.product-type.framework"; }; A3E8E30CED7400C4962623E6F83EC78E /* Pods-myWeb3Wallet-myWeb3WalletUITests */ = { @@ -1960,7 +1954,7 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 1240; - LastUpgradeCheck = 1240; + LastUpgradeCheck = 1300; }; buildConfigurationList = 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */; compatibilityVersion = "Xcode 13.0"; @@ -2029,7 +2023,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( - 89516187419F3D7FC4037DC8931E2A2A /* web3swift-Browser in Resources */, + 89516187419F3D7FC4037DC8931E2A2A /* Browser.bundle in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -2589,7 +2583,7 @@ GCC_PREFIX_HEADER = "Target Support Files/BigInt/BigInt-prefix.pch"; INFOPLIST_FILE = "Target Support Files/BigInt/BigInt-Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -2661,7 +2655,7 @@ GCC_PREFIX_HEADER = "Target Support Files/CryptoSwift/CryptoSwift-prefix.pch"; INFOPLIST_FILE = "Target Support Files/CryptoSwift/CryptoSwift-Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -2695,7 +2689,7 @@ GCC_PREFIX_HEADER = "Target Support Files/secp256k1.c/secp256k1.c-prefix.pch"; INFOPLIST_FILE = "Target Support Files/secp256k1.c/secp256k1.c-Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -2730,7 +2724,7 @@ GCC_PREFIX_HEADER = "Target Support Files/web3swift/web3swift-prefix.pch"; INFOPLIST_FILE = "Target Support Files/web3swift/web3swift-Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -2803,7 +2797,7 @@ GCC_PREFIX_HEADER = "Target Support Files/web3swift/web3swift-prefix.pch"; INFOPLIST_FILE = "Target Support Files/web3swift/web3swift-Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -2875,7 +2869,7 @@ GCC_PREFIX_HEADER = "Target Support Files/BigInt/BigInt-prefix.pch"; INFOPLIST_FILE = "Target Support Files/BigInt/BigInt-Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -2901,7 +2895,7 @@ CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/web3swift"; IBSC_MODULE = web3swift; INFOPLIST_FILE = "Target Support Files/web3swift/ResourceBundle-Browser-web3swift-Info.plist"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; PRODUCT_NAME = Browser; SDKROOT = iphoneos; SKIP_INSTALL = YES; @@ -2925,7 +2919,7 @@ GCC_PREFIX_HEADER = "Target Support Files/PromiseKit/PromiseKit-prefix.pch"; INFOPLIST_FILE = "Target Support Files/PromiseKit/PromiseKit-Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -2960,7 +2954,7 @@ GCC_PREFIX_HEADER = "Target Support Files/PromiseKit/PromiseKit-prefix.pch"; INFOPLIST_FILE = "Target Support Files/PromiseKit/PromiseKit-Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -2994,7 +2988,7 @@ GCC_PREFIX_HEADER = "Target Support Files/Starscream/Starscream-prefix.pch"; INFOPLIST_FILE = "Target Support Files/Starscream/Starscream-Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -3156,7 +3150,7 @@ GCC_PREFIX_HEADER = "Target Support Files/secp256k1.c/secp256k1.c-prefix.pch"; INFOPLIST_FILE = "Target Support Files/secp256k1.c/secp256k1.c-Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -3182,7 +3176,7 @@ CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/web3swift"; IBSC_MODULE = web3swift; INFOPLIST_FILE = "Target Support Files/web3swift/ResourceBundle-Browser-web3swift-Info.plist"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; PRODUCT_NAME = Browser; SDKROOT = iphoneos; SKIP_INSTALL = YES; @@ -3206,7 +3200,7 @@ GCC_PREFIX_HEADER = "Target Support Files/Starscream/Starscream-prefix.pch"; INFOPLIST_FILE = "Target Support Files/Starscream/Starscream-Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -3315,7 +3309,7 @@ GCC_PREFIX_HEADER = "Target Support Files/CryptoSwift/CryptoSwift-prefix.pch"; INFOPLIST_FILE = "Target Support Files/CryptoSwift/CryptoSwift-Info.plist"; INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", diff --git a/Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.pbxproj b/Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.pbxproj index 6beaeb376..823f45db8 100644 --- a/Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.pbxproj +++ b/Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.pbxproj @@ -21,6 +21,7 @@ FA5308442721D59D002C1F06 /* myWeb3WalletUITestsLaunchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA5308432721D59D002C1F06 /* myWeb3WalletUITestsLaunchTests.swift */; }; FA5308512721F5BC002C1F06 /* SplashViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA5308502721F5BC002C1F06 /* SplashViewController.swift */; }; FA5308562721F647002C1F06 /* WalletViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA5308552721F647002C1F06 /* WalletViewController.swift */; }; + FAF01E912722D848002CEE01 /* DashboardViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FAF01E902722D848002CEE01 /* DashboardViewController.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -65,6 +66,7 @@ FA5308432721D59D002C1F06 /* myWeb3WalletUITestsLaunchTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = myWeb3WalletUITestsLaunchTests.swift; sourceTree = ""; }; FA5308502721F5BC002C1F06 /* SplashViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SplashViewController.swift; sourceTree = ""; }; FA5308552721F647002C1F06 /* WalletViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WalletViewController.swift; sourceTree = ""; }; + FAF01E902722D848002CEE01 /* DashboardViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DashboardViewController.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -150,7 +152,6 @@ FA5308292721D59D002C1F06 /* Assets.xcassets */, FA53082B2721D59D002C1F06 /* LaunchScreen.storyboard */, FA53082E2721D59D002C1F06 /* Info.plist */, - FA5308502721F5BC002C1F06 /* SplashViewController.swift */, ); path = myWeb3Wallet; sourceTree = ""; @@ -192,7 +193,9 @@ FA5308542721F62E002C1F06 /* WalletController */ = { isa = PBXGroup; children = ( + FA5308502721F5BC002C1F06 /* SplashViewController.swift */, FA5308552721F647002C1F06 /* WalletViewController.swift */, + FAF01E902722D848002CEE01 /* DashboardViewController.swift */, ); path = WalletController; sourceTree = ""; @@ -437,6 +440,7 @@ buildActionMask = 2147483647; files = ( FA5308252721D59B002C1F06 /* ViewController.swift in Sources */, + FAF01E912722D848002CEE01 /* DashboardViewController.swift in Sources */, FA5308212721D59B002C1F06 /* AppDelegate.swift in Sources */, FA5308232721D59B002C1F06 /* SceneDelegate.swift in Sources */, FA5308512721F5BC002C1F06 /* SplashViewController.swift in Sources */, diff --git a/Example/myWeb3Wallet/myWeb3Wallet/Assets.xcassets/swift.imageset/Contents.json b/Example/myWeb3Wallet/myWeb3Wallet/Assets.xcassets/swift.imageset/Contents.json new file mode 100644 index 000000000..ecea9836c --- /dev/null +++ b/Example/myWeb3Wallet/myWeb3Wallet/Assets.xcassets/swift.imageset/Contents.json @@ -0,0 +1,21 @@ +{ + "images" : [ + { + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "swift.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Example/myWeb3Wallet/myWeb3Wallet/Assets.xcassets/swift.imageset/swift.png b/Example/myWeb3Wallet/myWeb3Wallet/Assets.xcassets/swift.imageset/swift.png new file mode 100644 index 0000000000000000000000000000000000000000..4942e11ce6dc5792b7cd6da2a3f98bc5a948255b GIT binary patch literal 6583 zcmZ`-cT`ismwpMMsdOm{kw~%8L5iV8M5+jaNR4z55D0{T^ne8c4NXL(ij<#p>4X*# z1r+H7kQRzkLX}>#&)vWFoZWZcdsFYsH+SxQb7!KA?rO7~I)4fP02W;xO=AFnfKdp* z4g-TcYC{Paz+7$`+ysEnv8Rvh=)p9?LC4qt00J)o0R9;O9DrH)1pvTF1Hh6k03hE1 z052wucuxf^fZFS8YXU&QYhhV1#f;Ihz=9!I3;fpIHG04Zqpz;PZN}fHcuqq_YG@WM z0KiwEt9kSOlV2+nAsFtVea7{*I(CGS4juu!$Z2%3;gaTU#9v7vFVhycBxJOgNs8Xk zfwAqnidbc zIh>8>yGYybdBH_0cgn$%y`y#B#7kJl9qw*cmejT)A8yP_mg^fe$774NdMD`5$or++CTT5eS%#}64KK;Qew+$#fN z=oS$Vx~6V@1mbfvOL0^=LCB-Ch=j@xspeOAIiKu1QHd{gxZ?R0wJt*j2YdOIdWmWq zc{c!EpL&1o`4AzF+JMa>cP_7gTKN7wd-vh6HCMG$TM{5r=Y4#z&}bn7RawX5l4f+7 zQ3ANs>b^J8&UGq=Gk>+9M8J`9Z~pJvxRwMF!e>bAfq!jYQJ&X&Ux7p_C& za{dU_`_ujY-4`;f;DJ|Ot1L-p&tWx$bu|F|8x z!rTNJ2beb^71n}wCmiej$W<|-qJVCwb=5Tmukkv$Cj$oLA+C4^O&2u&;PI$Nsi_zh z8LdOtfv&fIOV?mgQAE8g#FAC>#Cur_B4(D*Z80pv1M0hlVlU4I08bg|K5AQ;$?&`Z zL=g74OIc*Jzs0bT=F-iz*3%CDOsIqm-Zs%Td1#z1=J|8{{MRyou`9&^ZNTw~u`V>^ zu{PvzmvN;P0peETqXytBuT$Q;7Zsi}&;vLHB+1MG;MqJueBYM?LqIrxn1okJ5?=}+ z2Z?!o*)T*4$L1}(WzD1;dgu}J+>in1T}Kh<1tox&8bypgg^(MlyA@eP4bB6VN5XV( zQphE*Lv&qTNpqd#?bi&V0Q0*iU336xx5))P@W==nhmRUo0SmWeWsBT{^1u<<&LjcG z#+0T_IQ3U_hwg%tW801!Dbb6~oH$5q68g(B$7|Cj!7Q?G^30bB0XbXx1pstbzW`v< z8MSD37+wz$iV~IFg$=$p3Q>8%?O z+&Sc%uI}m*Ka;Bv9n{wVkZa$mO%TZjxuEV$El&w3u}{e+u1TYqQP9pCoL9tOd3~a% z-|9yGAg&sG0PFCq1>kukD0v1IB{&nX7raFmoyf2qo)ZrR6j!1=@QC@$Se(WrKHKyQ8n)oUwP zXHpsxWIL`zEl_*`wwl@rl6mmq7$|=RlvgSY+Rir+Mz^X58iF0XrjjA1rW;a9a$Frh zDoRckK}cD39ep2d@5LJ|MunMXflb(qd$Fj!Fv+(xJN5H=<3jc}G z0ytTnBOxARP={~kX3c8gP&mcRekG|oMdMbeA7O}#8-3b-PKIfZ(1!se`lmQ>_nqwo1MVI)j@_bZykuEls;VRe4Pw+h!$vp0x8WGWLzYmC%C)urQ&nQh!gL*-pFJZI!JLlZBblVps*%=Y(dS7)$;uBA>D@r_z1mg{OwWbXRug0V#al(GS#LoA z1Z>XA0kFSM_AmnHzO|E^=NGryqd45QJ1C(Ovhf@}3Yz*izqM+yAPPydP6!0r8WqVl z#y$Cg?p>181PrvIXGy{ybULs8dwE>;TYhBO#4k-EGXGmGV#B#H9stEoo^9VS3a~k34i6Q<|u^N-Bc&TCe_c4}ZxS2b*s=QL23jb{Jyz|az-TdlotI$ZH*Gmz|uTA!+G2k(=sFeL(d~bVktj+KKADqWT@59g1g9^Y`EQ z%NAC)+HK%J_j22#rT>iM?&@5g!FFiLSeV1- z=*i#byd9-Y1&0IZs_2GU)<8JYyq*94R_MMyRV~<=nbNRXG-lMz-pC5?NcFlz+Z62I zynFmcOssR*=5lHC!%jrtg6c^vj;4wY2q3Rqxu+>5_CsB6eSaPoMlm&=o1)#F^y62h zw%-?(@|o74mhf{=iYA-a03UT5dMur7Z#*|^)UylYLZ<)RN*smg!&G=BM#VYR233`$D) zX~X;lno#zDMdSOUPQ#85w~A*K+@sBR|9K=v$MQV52%MWs*g)S6{z^ zpnl1t_2jryHK?fGwd+Zz&ul^)%jhSrfT@tVKR;hjB@`5P)=XWR@A@!Yk&lCC_p?5H zz+>^ic|zMktRWKTbN+-yQgLE%ee~(U(OTHtQ?^S~2CcmOME7A!|DF-**f6nJv}J!2 zHjvkMxHa&{!%^8kL8^h$tUWVDyi@9=A4oe$#tpw>L(?w4o|_7jc3^1iQFA|GFuONx zljb{tb8IJ&aRv1mVCICx?CiRoY|90UOHr}DgvlZcm(bwgIi|+1F`ac-E~hJcC+m^q z3E9x^-;2hq68J_-(!)YfPENiG9Y0eSRd)sUC)O;BEDYDme{_7*F0OYv61VYeWYGoo zDt>QE824LeXqTAZT#LHgp_{l+Ft9UlEFRd{&9bWb_Bd!;jW%vW zvt6~8RnL6YO+0jTD+nVCIX2LrE~+`l%vX+e38d|52Uk-<4v)%tBy$u!&W{$FZQ6%! z+@>}?ayalUT+x(^h5T7d5e(&fLJ8kX4y6EP&Makt@?~z^M)zT7d6jEIf+jvshN-W| z*qGN?90gqH&5gkx?pVAjfw4oQhU%_e!{ey<8GBk`gMfe{tK_*13fE~dGh}kAJN!A! zy1z7q*Sy+LlFWnP2r+HO5fP8S3;J}0~yB<|U- z9CO_axbb9Wuqe#MxhDgo8Wf=#)LP{_ON+!}BH8Ga{UgSzTRcW*tOEkB3-^6v=RB#H z=aFLgN2sD(dnbn&u?P5&LuklhYdV&-cf^G*bc5d9oTD z{VY@Z0LmmCDCg38ykv%oy+Hn~qmqphFtm!kg`%ScF<<8kdJ7n7z= z7>-VMyNk{59a@RvVcKis*ke|8PXTE^adw*gfryR{4a|8@z0qvAb0NnfWIMgF}OR?i)jH z6Xzd|k%=B6@kLgQ!L-Aw3lh6v?Ds!e0i;Z!|NdDED1f!=TBukvblIwoir z8ngoh?cjrUNGp>oVN(^1dtB0;b4SZTx580t9!ym?FPnEpcEj*+L`|4q+J;yw!~PBNu| z4!|Ab%mhx`4)%Fgc)=R?v_25LaM5ms~#e2-TqlfXC_Q)B(mVm!2=ujmeLTtCuo7%U#)AHWiv>o@OGndTff=aqNsr{uRw-vBwC9UQ{= zc;VvNI7>G5JlVZx8vkET;6@_rHs40JPGc9 z-DM<9)&Q!Ye<^497ow@c*Y`}ZT$;K@L-Uu#9TfEyBl z^J#Q7Zrr`#Sx0=@*o02yP+Z9?BPMv?NnEd&33XmmONg@BQ@GiFZYqR#uP@fx@%MLg zo{u*GSH876M$axjs&wn@7q)O_F6+5|eTRwt+vhdCT4Ch{(VPz2u?b8BLEh2q{i!%hB*iO~(0Mv6($tI-6kD;UhHzTZ~xswNa&)B`Tw^jf#Ay=ro# zdR%6Q0?#NiqAWbTbcSlo_wNIYtRz!Y2qRmBO(?Sf680v!zN6(S*-jyn6NT#g@jZfH z{Q{pNE1&v>4$wQj8h{Qe#+EkN!*7dUfxw=r7YV8fc+TnAw!+ZW{1PJXQWmAI@T(9x zrFG*c>gnj|NgeT&|J=hoWo%!a&bj!FO^wNIp7AOGE$kM+Nls(cc z_)f09F4?A^ zFW^>AS^IKWhc>CZD%!((tBY~g{c#1?D6|u{Cr92?_sv-YX3CkpMBG!xL&fehf~>59 zC8PU}6^_i99}?Z%yjI%wH<`1T7jknUAXqaaip?VvBOoUq^w)phy9ZI(L#%HN*o{#$ z?=WXwIGGHgpu)0OXJU>^H@hnc`q|S}!{7yxujip3Rj24GgktWZeU}wP)9ljI!{~#> zU6XwDpp;>?zNhYXOp&ne*$?^vcpL?H5Zlm`DAvs6{3s$~jL5yWXc#`9fi21VhJ3Hd zxd6ksxinLtVLc_?7g#~|G*p2c?bLLenp$WlzJw+MM|Q!@p`_jq?YqleKcBk~cOw;| zVnR}@o(;R$beWM+`%Q@fy~OQtKEU9}JzdBQfb*X)Ih6;#|4h`aSb1|Z#q=RknJ^4EdM&C-zCET>;LM78A|jE)cZeu{v1Ocekv-8sY(x-)k=@nw{BNfNy%grHwW%ymVCXM^yo!JVP+-xV1w2_9|k<7Tw zFtVm~*`V^=<*{n|{5#?G(+svVnpxm=psnaHRzU`Z$Lo=+?!y;ogc*B-*5|iA681aq zrjrUwBI>t{ZMPm}xtmc*xmQ^QfS71}t43BWUr8DJm1|Hv{ijU}xz~#<5<^eyTHnc> zM7*u5I|&Fzr?|N9dS+Fg9jRmn-*NC?%W>tJPkgae@yEorvq=_VfyI_BEPMbfAE0Op z^cM2QCH)TT=^7k;E{9u3l!Yjlfg2|FvbDwNu<}8kLFWNR?=$x%VexY0>O@Nk`uKD- z(tk(l%J&Wc>CZs)y|JR}s;%?X0ubN#c4Yx6}I#>K#hDta3YA?2&ynl|b&GV50Zg9q{N*&<&(&&0WTdsuY zv1UP)#gP%X>e7_QgCCnm1gpbCVeO+vU!1(T#iGskzy)?|C(*qjGfb$qe@VkQ(c`w} z|NV#r9IG?J1unl6djMW10;0aR&3zs1e4UUEK2Bf&$V$t~NXSS_$jaWAkwHq!BIOjs oq@|J4($9h)wEr&w4=+bo=YaoTVEf`~5GVlX-oC3@qG22HU+9@nvH$=8 literal 0 HcmV?d00001 diff --git a/Example/myWeb3Wallet/myWeb3Wallet/Base.lproj/LaunchScreen.storyboard b/Example/myWeb3Wallet/myWeb3Wallet/Base.lproj/LaunchScreen.storyboard index 865e9329f..91dc59f12 100644 --- a/Example/myWeb3Wallet/myWeb3Wallet/Base.lproj/LaunchScreen.storyboard +++ b/Example/myWeb3Wallet/myWeb3Wallet/Base.lproj/LaunchScreen.storyboard @@ -1,8 +1,10 @@ - - + + + - + + @@ -11,10 +13,32 @@ - + - + + + + + + + + + + + + + + + + + + @@ -22,4 +46,10 @@ + + + + + + diff --git a/Example/myWeb3Wallet/myWeb3Wallet/Base.lproj/Main.storyboard b/Example/myWeb3Wallet/myWeb3Wallet/Base.lproj/Main.storyboard index 0625e8a6a..59341573b 100644 --- a/Example/myWeb3Wallet/myWeb3Wallet/Base.lproj/Main.storyboard +++ b/Example/myWeb3Wallet/myWeb3Wallet/Base.lproj/Main.storyboard @@ -16,7 +16,7 @@ - + @@ -32,6 +32,9 @@ + + + @@ -71,7 +74,7 @@ - + @@ -87,7 +90,7 @@ - + @@ -95,19 +98,39 @@ + + + @@ -117,6 +140,7 @@ + @@ -126,8 +150,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Example/myWeb3Wallet/myWeb3Wallet/ViewController/WalletController/DashboardViewController.swift b/Example/myWeb3Wallet/myWeb3Wallet/ViewController/WalletController/DashboardViewController.swift new file mode 100644 index 000000000..fc4a8b585 --- /dev/null +++ b/Example/myWeb3Wallet/myWeb3Wallet/ViewController/WalletController/DashboardViewController.swift @@ -0,0 +1,34 @@ +// +// DashboardViewController.swift +// myWeb3Wallet +// +// Created by Ravi Ranjan on 22/10/21. +// + +import UIKit + +class DashboardViewController: UIViewController { + + @IBOutlet weak var logoImageView: UIImageView! + override func viewDidLoad() { + super.viewDidLoad() + + // Do any additional setup after loading the view. + UIView.animate(withDuration: 0.9) { + self.logoImageView.center.y = self.view.center.y + + } + } + + + /* + // MARK: - Navigation + + // In a storyboard-based application, you will often want to do a little preparation before navigation + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + // Get the new view controller using segue.destination. + // Pass the selected object to the new view controller. + } + */ + +} diff --git a/Example/myWeb3Wallet/myWeb3Wallet/SplashViewController.swift b/Example/myWeb3Wallet/myWeb3Wallet/ViewController/WalletController/SplashViewController.swift similarity index 69% rename from Example/myWeb3Wallet/myWeb3Wallet/SplashViewController.swift rename to Example/myWeb3Wallet/myWeb3Wallet/ViewController/WalletController/SplashViewController.swift index 141c357ba..6c8eef804 100644 --- a/Example/myWeb3Wallet/myWeb3Wallet/SplashViewController.swift +++ b/Example/myWeb3Wallet/myWeb3Wallet/ViewController/WalletController/SplashViewController.swift @@ -9,9 +9,16 @@ import UIKit class SplashViewController: UIViewController { + @IBOutlet weak var logoView: UIImageView! + override func viewDidLoad() { super.viewDidLoad() - Timer.scheduledTimer(timeInterval: 0.6, target: self, selector: #selector(self.moveToWalletView), userInfo: nil, repeats: false) + UIView.animate(withDuration: 0.9) { + self.logoView.center.y = self.view.center.y + Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.moveToWalletView), userInfo: nil, repeats: false) + + } + // Do any additional setup after loading the view. } diff --git a/Example/myWeb3Wallet/myWeb3Wallet/ViewController/WalletController/WalletViewController.swift b/Example/myWeb3Wallet/myWeb3Wallet/ViewController/WalletController/WalletViewController.swift index bf4829909..1326f3e7a 100644 --- a/Example/myWeb3Wallet/myWeb3Wallet/ViewController/WalletController/WalletViewController.swift +++ b/Example/myWeb3Wallet/myWeb3Wallet/ViewController/WalletController/WalletViewController.swift @@ -9,13 +9,24 @@ import UIKit import web3swift 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{ + self.continueButton.isHidden = false + self.walletAddressLabel.text = newValue + } + get { + return self._walletAddress + } + } + var _mnemonics: String = "" override func viewDidLoad() { super.viewDidLoad() - self.createWalletButton.layer.cornerCurve = .continuous - self.importWalletButton.layer.cornerCurve = .continuous + self.createWalletButton.layer.cornerRadius = 5.0 + self.importWalletButton.layer.cornerRadius = 5.0 // Do any additional setup after loading the view. } @@ -29,24 +40,32 @@ class WalletViewController: UIViewController { } @IBAction func onClickImportWalletButton(_ sender: UIButton) { -#if DEBUG print("Clicked on import Wallet Option") -#endif + 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 + printContent("Unable to get Wallet controller") + #endif + return + } + self.navigationController?.pushViewController(dashboardScreen, animated: true) + } + fileprivate func showImportALert(){ let alert = UIAlertController(title: "MyWeb3Wallet", message: "", preferredStyle: .alert) alert.addTextField { textfied in textfied.placeholder = "Enter mnemonics/private Key" } let mnemonicsAction = UIAlertAction(title: "Mnemonics", style: .default) { _ in -#if DEBUG print("Clicked on Mnemonics Option") -#endif guard let mnemonics = alert.textFields?[0].text else { return } print(mnemonics) } let privateKeyAction = UIAlertAction(title: "Private Key", style: .default) { _ in -#if DEBUG print("Clicked on Private Key Wallet Option") -#endif guard let privateKey = alert.textFields?[0].text else { return } print(privateKey) self.importWalletWith(privateKey: privateKey) @@ -56,11 +75,8 @@ class WalletViewController: UIViewController { alert.addAction(mnemonicsAction) alert.addAction(privateKeyAction) alert.addAction(cancelAction) - self.present(alert, animated: true, completion: nil) } - - func importWalletWith(privateKey: String){ let formattedKey = privateKey.trimmingCharacters(in: .whitespacesAndNewlines) guard let dataKey = Data.fromHex(formattedKey) else { @@ -109,12 +125,34 @@ class WalletViewController: UIViewController { extension WalletViewController { fileprivate func createMnemonics(){ - let mnemonics = try? BIP39.generateMnemonics(bitsOfEntropy: 256, language: .english) - print(mnemonics as Any) - let walletAddress = try? BIP32Keystore(mnemonics: mnemonics ?? "", prefixPath: "m/44'/77777'/0'/0") - print(walletAddress?.addresses as Any) - self.walletAddressLabel.text = "\(walletAddress?.addresses?.first?.address ?? "0x")" - + let userDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + let web3KeystoreManager = KeystoreManager.managerForPath(userDir + "/keystore") + do { + 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") + return + } + self._mnemonics = tMnemonics + print(_mnemonics) + let tempWalletAddress = try? BIP32Keystore(mnemonics: self._mnemonics , prefixPath: "m/44'/77777'/0'/0") + print(tempWalletAddress?.addresses?.first?.address as Any) + guard let walletAddress = tempWalletAddress?.addresses?.first else { + self.showAlertMessage(title: "", message: "We are unable to create wallet", actionName: "Ok") + return + } + self._walletAddress = walletAddress.address + let privateKey = try tempWalletAddress?.UNSAFE_getPrivateKeyData(password: "", account: walletAddress) +#if DEBUG + print(privateKey as Any, "Is the private key") +#endif + let keyData = try? JSONEncoder().encode(tempWalletAddress?.keystoreParams) + FileManager.default.createFile(atPath: userDir + "/keystore"+"/key.json", contents: keyData, attributes: nil) + } + } catch { + + } } } @@ -125,4 +163,5 @@ extension UIViewController { alertController.addAction(action) self.present(alertController, animated: true) } + } From 29b227b8fccfbc465815c9b3e476004bed1a486c Mon Sep 17 00:00:00 2001 From: Ravi Ranjan Date: Fri, 22 Oct 2021 18:04:23 +0530 Subject: [PATCH 12/12] Example project for Wallet -> Wallet screen --- .../myWeb3Wallet.xcodeproj/project.pbxproj | 30 ++++++++++++++++-- ...t_10F04849-E85A-41AB-8A17-D3FC394285AE.png | Bin 0 -> 422231 bytes ...t_38EB4733-C3DB-4280-BAF2-9ED97440A8AD.png | Bin 0 -> 93154 bytes ...t_9B13C8F6-BE7A-4919-966A-9E69A2953F31.png | Bin 0 -> 120855 bytes ...t_C6881651-9D22-410A-BDC2-4CC3FFEF4FD8.png | Bin 0 -> 115663 bytes .../DashboardViewController.swift | 0 .../SplashViewController.swift | 0 .../WalletViewController.swift | 0 8 files changed, 27 insertions(+), 3 deletions(-) create mode 100644 Example/myWeb3Wallet/myWeb3Wallet/ScreenShot/simulator_screenshot_10F04849-E85A-41AB-8A17-D3FC394285AE.png create mode 100644 Example/myWeb3Wallet/myWeb3Wallet/ScreenShot/simulator_screenshot_38EB4733-C3DB-4280-BAF2-9ED97440A8AD.png create mode 100644 Example/myWeb3Wallet/myWeb3Wallet/ScreenShot/simulator_screenshot_9B13C8F6-BE7A-4919-966A-9E69A2953F31.png create mode 100644 Example/myWeb3Wallet/myWeb3Wallet/ScreenShot/simulator_screenshot_C6881651-9D22-410A-BDC2-4CC3FFEF4FD8.png rename Example/myWeb3Wallet/myWeb3Wallet/{ViewController => ViewControllers}/WalletController/DashboardViewController.swift (100%) rename Example/myWeb3Wallet/myWeb3Wallet/{ViewController => ViewControllers}/WalletController/SplashViewController.swift (100%) rename Example/myWeb3Wallet/myWeb3Wallet/{ViewController => ViewControllers}/WalletController/WalletViewController.swift (100%) diff --git a/Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.pbxproj b/Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.pbxproj index 823f45db8..e747840be 100644 --- a/Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.pbxproj +++ b/Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.pbxproj @@ -22,6 +22,10 @@ FA5308512721F5BC002C1F06 /* SplashViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA5308502721F5BC002C1F06 /* SplashViewController.swift */; }; FA5308562721F647002C1F06 /* WalletViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA5308552721F647002C1F06 /* WalletViewController.swift */; }; FAF01E912722D848002CEE01 /* DashboardViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FAF01E902722D848002CEE01 /* DashboardViewController.swift */; }; + FAF01E942722E6F1002CEE01 /* simulator_screenshot_9B13C8F6-BE7A-4919-966A-9E69A2953F31.png in Resources */ = {isa = PBXBuildFile; fileRef = FAF01E932722E6F1002CEE01 /* simulator_screenshot_9B13C8F6-BE7A-4919-966A-9E69A2953F31.png */; }; + FAF01E962722E713002CEE01 /* simulator_screenshot_38EB4733-C3DB-4280-BAF2-9ED97440A8AD.png in Resources */ = {isa = PBXBuildFile; fileRef = FAF01E952722E713002CEE01 /* simulator_screenshot_38EB4733-C3DB-4280-BAF2-9ED97440A8AD.png */; }; + FAF01E982722E72C002CEE01 /* simulator_screenshot_C6881651-9D22-410A-BDC2-4CC3FFEF4FD8.png in Resources */ = {isa = PBXBuildFile; fileRef = FAF01E972722E72C002CEE01 /* simulator_screenshot_C6881651-9D22-410A-BDC2-4CC3FFEF4FD8.png */; }; + FAF01E9A2722E73D002CEE01 /* simulator_screenshot_10F04849-E85A-41AB-8A17-D3FC394285AE.png in Resources */ = {isa = PBXBuildFile; fileRef = FAF01E992722E73D002CEE01 /* simulator_screenshot_10F04849-E85A-41AB-8A17-D3FC394285AE.png */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -67,6 +71,10 @@ FA5308502721F5BC002C1F06 /* SplashViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SplashViewController.swift; sourceTree = ""; }; FA5308552721F647002C1F06 /* WalletViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WalletViewController.swift; sourceTree = ""; }; FAF01E902722D848002CEE01 /* DashboardViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DashboardViewController.swift; sourceTree = ""; }; + FAF01E932722E6F1002CEE01 /* simulator_screenshot_9B13C8F6-BE7A-4919-966A-9E69A2953F31.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "simulator_screenshot_9B13C8F6-BE7A-4919-966A-9E69A2953F31.png"; sourceTree = ""; }; + FAF01E952722E713002CEE01 /* simulator_screenshot_38EB4733-C3DB-4280-BAF2-9ED97440A8AD.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "simulator_screenshot_38EB4733-C3DB-4280-BAF2-9ED97440A8AD.png"; sourceTree = ""; }; + FAF01E972722E72C002CEE01 /* simulator_screenshot_C6881651-9D22-410A-BDC2-4CC3FFEF4FD8.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "simulator_screenshot_C6881651-9D22-410A-BDC2-4CC3FFEF4FD8.png"; sourceTree = ""; }; + FAF01E992722E73D002CEE01 /* simulator_screenshot_10F04849-E85A-41AB-8A17-D3FC394285AE.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "simulator_screenshot_10F04849-E85A-41AB-8A17-D3FC394285AE.png"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -145,7 +153,8 @@ FA53081F2721D59B002C1F06 /* myWeb3Wallet */ = { isa = PBXGroup; children = ( - FA5308532721F615002C1F06 /* ViewController */, + FAF01E922722E673002CEE01 /* ScreenShot */, + FA5308532721F615002C1F06 /* ViewControllers */, FA5308522721F5C8002C1F06 /* Appdelegate */, FA5308242721D59B002C1F06 /* ViewController.swift */, FA5308262721D59B002C1F06 /* Main.storyboard */, @@ -182,12 +191,12 @@ path = Appdelegate; sourceTree = ""; }; - FA5308532721F615002C1F06 /* ViewController */ = { + FA5308532721F615002C1F06 /* ViewControllers */ = { isa = PBXGroup; children = ( FA5308542721F62E002C1F06 /* WalletController */, ); - path = ViewController; + path = ViewControllers; sourceTree = ""; }; FA5308542721F62E002C1F06 /* WalletController */ = { @@ -200,6 +209,17 @@ path = WalletController; sourceTree = ""; }; + FAF01E922722E673002CEE01 /* ScreenShot */ = { + isa = PBXGroup; + children = ( + FAF01E952722E713002CEE01 /* simulator_screenshot_38EB4733-C3DB-4280-BAF2-9ED97440A8AD.png */, + FAF01E932722E6F1002CEE01 /* simulator_screenshot_9B13C8F6-BE7A-4919-966A-9E69A2953F31.png */, + FAF01E972722E72C002CEE01 /* simulator_screenshot_C6881651-9D22-410A-BDC2-4CC3FFEF4FD8.png */, + FAF01E992722E73D002CEE01 /* simulator_screenshot_10F04849-E85A-41AB-8A17-D3FC394285AE.png */, + ); + path = ScreenShot; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -310,7 +330,11 @@ buildActionMask = 2147483647; files = ( FA53082D2721D59D002C1F06 /* LaunchScreen.storyboard in Resources */, + FAF01E962722E713002CEE01 /* simulator_screenshot_38EB4733-C3DB-4280-BAF2-9ED97440A8AD.png in Resources */, + FAF01E942722E6F1002CEE01 /* simulator_screenshot_9B13C8F6-BE7A-4919-966A-9E69A2953F31.png in Resources */, + FAF01E9A2722E73D002CEE01 /* simulator_screenshot_10F04849-E85A-41AB-8A17-D3FC394285AE.png in Resources */, FA53082A2721D59D002C1F06 /* Assets.xcassets in Resources */, + FAF01E982722E72C002CEE01 /* simulator_screenshot_C6881651-9D22-410A-BDC2-4CC3FFEF4FD8.png in Resources */, FA5308282721D59B002C1F06 /* Main.storyboard in Resources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/Example/myWeb3Wallet/myWeb3Wallet/ScreenShot/simulator_screenshot_10F04849-E85A-41AB-8A17-D3FC394285AE.png b/Example/myWeb3Wallet/myWeb3Wallet/ScreenShot/simulator_screenshot_10F04849-E85A-41AB-8A17-D3FC394285AE.png new file mode 100644 index 0000000000000000000000000000000000000000..ebe338443a7df7b8b10275fc01d32d4e42ea6802 GIT binary patch literal 422231 zcmeFaXH=7Gw*{(*hynr@iZm4gm8$d_Y#<_7s7eXaTWFz$7O}uqnu-*uDhkp;AfW_8 z4?Q9!K!DIg5kiOr0wlTF`<%U%@7wqHJ!4$Pkikpx=E>96T64|0p4S(54Rtw=oI0{^ z-#!k#o7eB}+jo$8-@YRwtSpRIjHkGy8Nc>}@9SROSJWf8!1&|3gSnogfx*6ujBD0? z`y*ZUG49{DpYd~w@w0E=f%p6O9bo+4|L1G(nf`wFAoKeJe_tON`SV6tTWHO`ecJo< zu3s?@-2Y?j5aJxxN@O!7jgcuy0@Dlat!KX1?EX+3E=|kCf=MSIp-lC2CbXeR^Ez^o#|Frl!e2C_!^$yc%8? zi8jGut^5}IH~N=8KtmVPP7(rVx-l1@@7vGB%*u6I`|+=faBJ3rA1x2m^#1D|#=R^| zOjmfB{^di$hgq3}`-cq^el_&>U5~ZDDgOQi|NHuTT_&amVLzCW*nhuyn#-4Ccd!2X z(ERJi+9kT_%f^TQ`%PA6s{{Wz6vl^w&YkA^anDKJr@`=G`N6(L|Lya>T?p^Q6q%r{w1DZAKDla;_4|H{i?fSs75M`L z&a(r7%MZ0$>2uTfFGzm;Aen!X2qjk9-q^7=$u}z~fE8F;fvl>sM_{f7e)z?8qNT?N zsffqgUYGilhA+|Ac3vzJqjK_dWYYz9ejr1NM#^pd{7{R2#4=dWdPMqwo6?UjgU!$# ztBVrT-Q;C_tm&N_HJR1Eu%NZ6VOJ9b{}|lS&d+ma6z*@gz7?aMzbtPbdoSj^az+Grc;9_Yk)=EHR6 z`)A*r!A7pL%z3K4d8VJv@Sg{*%dN74NfhKfW`Ejkvit^H`BP*Q&jBY$#=9KFAHi3&iy@KL|+RL#Ai-T}NSwcvMji|gkW97l( zHDj=4bvuQL4UsMFb>b!pq%_-|x?u{0qOzid^LnzE$!C6Bu=>jScyIV%ae82ooXyng zESoa0N87U~d}5vkIfQj;#pfcAACO)vDru2Yl@mKOlqSM|vhsqKBu*e87Zinc0pD%g z;#*G^)9oo_k48}ZFT{M%-$t}kTzB3)@=PRMs+RYR?BP-%$aUTIH6KLnOH&4o7|lB0 zad^bc{Df^9;U2qIwAnfb9i|sG$Sqf;8MC+nyzrebW2#fLrIEt)wjJ$f-euCN@CGD; zblg$s2(7VHB2NUcHaRRzn+sFLG~U5c7Z*Ql!t{3y>;8#0bRsg4VI6Uzd;%ORbK91e zZGxw>)$?SB!=UROe2SId#F|P0DxvdpZS`s9OT85qd8k3pg?`pnioaguMkc@{baN`V z!SV$JvCJJ&=R#VsR_%g=EvQTlNGyK^B*?ZQ!BocL~&P=Lp^a;{$ zZFn)5v(B@J{%uC%4*-HNJ0OAbntS&ao)##s!%_zouPOJak@Rq&y$iP1OkOJSyC!?= zHwXLv8WRNGAJ?M&g6=c7`rZUAbXcX&NI=t?Io}RfH1tiu zeVtK0#aT40z&E!u`k6Ekd3J%`_Pj4<`;$)3h0VArrxYJC@w1x8qC94nYvlParsFh1 z2jrn);N-QZ#A}*|aYvA}D z6UwlMLb644>(RJOHvO0FB0F$G+ajVhs`=wTe<|8`!w|6G^v*B z65OvexudLQ;BOdqB^>2AcfKCe>a_Z3SR|@tM%AhP)lW~4VfcBYXbx;&lCHcG`Ew3F zFar>_*%Z?-9wk~!Pt=snGa$yHI_^SJR|qJkQ+~7f*w7HUxNBJD%T?9=NVT00SA=*) zOFC5#)&*{d4w(H2bk0+Lk@<&bW(1fg8a`<>CGf!$OPXrPtIH~$4Pn7~Pt=y?4G?>C z4k4Wc!q(b!^P${ujXOrP_1-uIVSuh)7fCupBoslGqbrWf;RJ9p zwasve3ayNDzYO=i0F&y?DeO^1PDi+SQ-cs2B-Jauadp#7^wai6>BNkMU9)YNQgHhg zMIfDQ$qa0I?N#-7)|oHa$dX#K8Im?Rhh%{ghJ(G^xkD3{%zAImUk1?gm z&1JPgE-c;>Ch1Nm&T=TmC(eCoKnme*?X*{k4t#k10u;GE^U{o8e9pNAwzk500(!Br zsd{ZzUAUkwln^C4QGlKWcMO@K@){{~nOJKZ?#YP)VZg<%T&YP)0pQcHizv* z^6RJ*!TEwxm$7f2UKNh6$+Z>+(`qkjiO%9bVOl3%CKX^!HBV*rkP9CGl3y;4R!Dkd z%*G^g+I4%L%Y<$Bmzl)!g*fyBL}p*GUYGybv8F9``tpv(JJAEsb1V%~csZ|rlDQ=t zR9LksDvKV`03?r13MdWZf^~HaV^@|oe3;htu2*dhls6w-EBuMF^|i5roEv|I6xG4Z zE;q*CI@-|VwX$4VuoXyoDt{>7vx@w&L4dI720d}byiRp60T}gR4p==M-b&%Qe0!%o z;#LR0rABpv)<4!lS%exC%(H)YCm^&*AH_KUh~b7MBD`_2Jm=LFZp^ovT= zrK(a^OJ+cgp@$Dd;?t;WgY%gPH<`{as4sn9!Ev((nV-xWB$>oOI^7L}9-7tpq3tTN zmKI^%_&Nw9szG;t)VS$Zhsw;@zxiNUbhBS!|5Aip)_0Z*w_EewsN2V<1@fw^Gmf#ssv)oc z25*n|g+J$2;m=y8wbPK%>NT-r$9@h}*z@(z;%nF=wV+FyPix)}cAt&ztQL-5m4j+2 zd+643eXt)tvIA}17X_%jq~Z{WsD{}KtgW+O;%rX0rMu!Jj4gDZ)KrH$u8j`A*7oXa zOSf&JkR0!0e1^!HqEDeZnmXx;O%VTeLFOk`%kN^#^A}Y^t=Sehc#ha1wM62Z6~(;vKf5<2<(JJwqQ`Picqhkwt1yY5aT*%{X9J(_TqOUgvA ztrR2J3hmqP68n@1{5v7%ctAT8zImcLH`#$-lQw@T@`DWwfS%5`D}8-`HiY?Y)0;jw zj!qv-ZTmnEP+V5Pf!LsEwTfjzMHPbuz|X;dY|!H6F=ku*fL_GGz%v~Zpb?Wo)vrD! zTZB!b57VIK=P$YJ$o;3FRD(+aHWsf`>OxuGRUNxO#v}@f-kHnI-HF`Bef#-6I>YlJ zDA4!V2)~K5-L3(|*QY8i=Z0NqEYC(?f()^b`@C;g9w#z9h_>`e7#&=y4ZCH zkG6d_u@29BH>gs!OyAil9TAEkN%z;y?_yD;p43O#PPB3of+5rRiXFj?b)qT(H%?07 zj|^8uTJ{`I&gxwA&L(xwUTlPnYJ~OS+e5UlnfQBoGds`teHPwT-mwn6nkAcxA01`l|^A0M7-Y|FWgX$A$ zsIV2hDkw0q35m49Y7TUseY{iKcgR*ak~BbdQ!>ds4ks#g3ndG!79|5pik2xOQLb|r zyYSdseK(ug4FEoqzUxn((C}8$(0~#faR95?)eZEx4+ew|e)7w<_A^CEua0o2 z=ZjR590rs%HA^Wy?fwP+4q-5c{KGCAW~^2$_W1}vuW#b@_v2$HsD@jb*h z`>kaJ-(?EmO1#b1^@wG510%$44_Z2ivW+DO6d3OqT*5r+>DF?`Et*?i#-=aJKFElJ z7vYL5zpl*Q$E>TYZVg8VQIR>Ergw@oEka#Kmy@VjZ@IZx6TK}HD-@*7Uw3B3(Ihr+ zOBE2GMrz%ymG;O49hp3K9xu3qsH|1OM>=nbXCJOKyk~>3+G; zw#`nK0x;aBsB35W&^Q&tH$Rw=#7u}!y?yI~w=-9>h+(N9Vc75RwOQcluZxu56R@6a!aK66OO zDmH&oUYSrU7H577kEwtiVXhez6>>!r`KYF5!qr3r!@7HP5me?ET6Zt%P`>g2NPWw) z==58F>ZK*l7Uipy?r$Lp$4m1}tlATvgAZ@NORO=)X`S^kM-e0JIDnb$c6Iy1cBY0a zO}6cCHwGiN3ggkEWKJ8J=z3@{(6rXOPe?v@1ok^0XYLh_e!0)7&niEUvnAa`^7h-WO$BIUJ7xVLfw|?E&}vplGr7n ziz{Xva~dI6Mu*7}F(i_z+s`3*oVTE-34ku_$G?8cbw+yXPOEcI+QZxLY8XlLN<=3t zVvga8C(`J{;mAB1n0+kWrQM#6gf1>~yVm-SUoFgr#mP8m#rxxxZ$a{ZQryfuu+p9a z86ZlU#CTBWJhIPB1|w`|PVeC((>N|+TAZ41Jvj0^8IbryJHj1w#iHlXX8NIVb=F`V zv{OoNcovouDl#V9)Iw0(th*w&nSO~gbSz|(|9;qm0-pk3;OU(HW2}h_65%%dD2E4~ z#N^@+MH=P)M(c@uRZ6LHUgo%W$*knm%7f~g(c)#|%~6k#4~|EpiJ{iDk95~5my)J(S}vN+-R8p(m4EB1zR84{p@s={ev*@8 zjz0|zZhP$jq;#pXM7`J<18wx+KlE$HF`*T2b1KC}TEa}&n3F)59%^&S)d~P0pkQnL z_#K?jV?oFCYYigNUb4ESLNRiec=;&l=BzXJO{~>|ppEWJ4L@YZx2qeN_~FJXC_u{9 z>fuwYk_K+amZlOAH^r zIbs#p-*fP_eieOalG6-%3b)mtfD%>cQazZow)&%Ya^4TGg2A(Zfr4tPUmW$Hy#byW zU#Jj|sF2*XWnVJkLMK882(A0xqz!m}cgk~t={i(4v13R zpE$@bW9i1ox}0ifVimfl1c0TahQ<5|$lZ9-E5}l0T3>Xc zLwWALLvYhEk`sOvbai~r(rm=EEe{*^v#K^9gY)V1DvI?ha6B>Pm1)!)Vc9&pF(uNo zqa$gyaQ}D8zNDX-TAholS*|NL+ZyR@Rw1i(ZTVqs(Fn}PAR$U`PT}_Uw95oEFxQxd8)^k(=kB1+ z6%$kf%7eNi(&4pASP37+$?ESX78!1XHu^3?u5`hCdK*KfCT;^LupF>q1NG5bL$cI5 zuH|Bns>@SYtpl3J?E9XDLsqJ+JTkXu%S|7kOW2$0HO2!_-lR>o2W#@PC9Jj)$KYDA z)zLv5@D6l4g%Oze)@6*c9wx@r&m|WZ<%YD*Y076b$y}=zoU$@I+AK$S^ZCN3PR|!9 zPikS)1f*{raW)$pFA$JC$>tgBSzLE!&bB~Oq%N>}>-i@6KRA)&ZQ-1NK)i%;aZF81 zg!gc*o02I2N^oO2a5wv1Yu-v47%5o)X5BvY!B?7wp>VNBeTz*NWG6Gf>3FoAlrNuZ zT#iZk;=QDM#Tso{OG;*$r7mbDROO93#oz=*39WRuJQnHl`qh}SmC7=qcz=3~@-$H` z)9vu650e@L?}F0 zK`7s4dsu`19J^9To6e;U1fzjKOZ)Ozc&6qNHd*m^V&Gje+|y&IM_&8_>jVc59BeS@D7 zD?0Y;an_hr1|r#*qvB;Uj{wJyrHsixJ#3?U!(Ty~>|Gev5Iee|Y}@-rrFForVyR22ih@){v8#d`?iAO%bI>rY_kMQT2&Z;_F-Q?QS)q~wxs z?RaX%Mp#FU)wO8RzKLO9%Pc5LHP(N)KCByV^8oE&f{ns>7Miv|pPA`Ashm7KsG%5= zyG~q9*s^$FgV%khVc4ca7CYK2Iks#@ zeQLQxPcFq0RDWNYt{m;7i<|GVMDoXj$g4J`9Ynj?^G(X`h^(!b>71qpnW?QC59X2b z;}4H7BLeM?ZiaMGrW2N!t|jeArf0+*INY7Yh}(7cNmpuB_b;&xdgP7+kLQKHpQ~~) zRQ1FZN^YBCWL4=BrM^4!0!{OERcB2GH{P(yEOjiMEy!nMrceC*u-LWIIgp*GdQ5kz za~hHVs5d_C>BroVX&UkiZNBRR);gnou`5d*?YPp^OZ}ZTsP8%`bKMJkvF;h5U#{}e zMxNh5VzO-Qh0zC#+i1&zQDI2ZP+aSB9WrPtcaYn!>f4k^nyNYV(awyoK2QWMB-^SH z9^Vr}y?HtrE>~>fr^(gDRR&7Q(_5DrzyQ3PVp9$7#68lJaG)JLk46&TXf@)Z6FinW zM0CFSou%DN(}SozsR&3@e^{g6C*6iBvMd-2+qB0n6}y?&pL<$?Q}wekZ)ry1)YgAY zh-6lC$oslql(jY!F{U|=GFb&kf{iqr@Hm_o)`tcVt`V5KEx5Aud&)a}xcqte13Q-I zRR%_kAt|S0u4>TNw{cd~ThGFq-UK`vNa)3bw?~Vk9H!gezm+%3%v4&M_3i|Vbj~~X z+>5)Hqg5@{ugb>Edn@RLFdhsWHyJ4W@ivR>^Bq%-eX(Sy2&dDo5sEnmeNQS{5T1Xz|Mv>;RKYd-sXUhZar#O<%*m&NDVOKY?*o&dNJ6nxY%0W z2Q|i^CX6y~^K4l%Lb!BYb8OP_5?Y~oFT7~xe1oUvYQ~GKvCHgTSSPUJX!RROmSuNy z_j5Qt;7CbjJ07L+m?Hk&*oW3c_r^3;$U4=N50u{3vuM8;g5$v_kxmXK6l2$&$NH2r zJ3S#OJxev52v50B)VWq^;Q4j{-x-iga0`G86_<(SQ^B@pNzIq)0apP1?bBSM=bc*NUzU17#+{eLUXzH2PHSv-;92GyH4=EaD!IcoI1T5eFlu*c zwm%93ioy@FH+Jn9F)lZ&I5b=hIlbyWzoYoA8 z-LUX9Mil$?tLzw2dmV72MA@MIg{}M$R)93yZQuQYeZ7u69H1n87MZ^3#=YtwmxO9- zwIebbj70WOSh(%?1Lm$JM(VW^$i={u%?WBEqi74}?|(15z~tu9tT zjx_pu$wpiTL^r|HSF987QCri|oA7%EMUp7#KTul*gVOAsOu^%j1fzSi@1uxs0vu;S zjhUk*B{Q4kC`y2#!Fps4rwPjQwn4&1p5`eq9smpLd=jE$-31oW^jAaBcXAh-F1>Od z%EH>d@5*T@e&PjYCaq=BxJ!na}nM$qtv0c+6l38}Gs3#R(J-3WxyJyWq z;+g|BczT-82Bs*@q<#-r4%J)72$))XQ2df(KipJjb@p z%fCd)+ua7Uzl$Cwb^zAjvHJQ>JyVH7x(h1;Irw7~t*;ZA=t@XH2{iQx&hFQi~!loEn9xY~e ztfz*SQ5RAagsGYyph@DVhnE~eL#&~8_D7d^&Wl!h4_O2F&I~QBWRA7d=h~eZy4lX_ z))u7^S1Tb;S6~_Gb%WsJC~gPp6j36NPHoe*h)ls$0PudBIW<6Ysxk*#LI1Km&9caK z$H@B!P@VX*`MG)Ph7c_jlfp3osG2^gKPOW2s7CXbdS#x+6gh2}sV7NYv92hp&YFaw z8G8=1wG3$4A^)j@JUx8@U^MqWrYgkHqJY$ij`WPW7iU0fku|O1nXXj5EO&@w_G5NO zBZE5R?Fo7ybir(#3fBdg)`~SYfQ_PqI$LD5Bt6QgjmsOYUh~~iuCH-*JMQIF<&Vov zp1_n-Zifzgh-36L}Yelj0%z%)Dp2gkkg`UoyjXHX`%fo zm!ZP^qZ7PGXvdDIog_smKYzl{;_;&9NeYerlQ95DZxtr_sqvruNWS^GiY6>p?$AmScy?Pcl2Foy5>P$=7K>Q{9U_Zo}F@dbrm8i*i zN_y=fVyL#3ZmBk0_)6tH#>zT&O67ZCm}f# zPFkt4GzMFQw05IwAiN*GsxXSPTD${{e@AxzTXYq5_SKoftN%>luM6!v42f5B!8u3o z*K2=g_NN(~f6;+|X-)GO7c2QoS^CA_y#3$934ibQ-z`1Xj{Ea#7Tt4h{r8*Nr{_=o zrY-(`!#C0W;Wlw<*xXIvk#VPw!!7Or|1nyVXrH zuY#Dxb^5MpeX!|+I~CmjKyJoG{pDkog7~%O4#|OqgxC9G6R+s_6{_)|HEX6^E0#t& zT!G9_J(>h=qzn^sM45NY&4EIlbS2brPHQVg32Z0#Oh#OgEb7u%NzC=+8kr|LRK+r_ zuj^|Jm0u>a&R2YwbGdu>v~He*wx5gC`%{4HM{U#vKTPCqLe4*t6dh@OE=~`<{6nj5 z&DBJiPp)YwuAuV1W{`tPbD+HJ9o<^pDJMk1OB*jBb5+gRHWSvL2K6R5xNtz-u5XaL zH*w3IxOsw6P;-O#Y~iVBFM-hS1f#=(u?%*FU2r9B(w(J?}<7JLKhQ}$`zkq z!QB@)nL70u)x(IbzTsWxVd@1B#-f%#qfmJEv@7W-Tby8T_HEe`m&R-hTj7T8GFF1= zZB}mheD>irYwIFLCuT>=dZKp06i2buQ7I1tA;7l=CckJ*RT_O^eO zl1%7qLAS%qV6HEB?UnM#4~{YwQD?tJ^@Q*0#7kC28=%=0zI*-w%ui$yU#lOEeRY{L z16M6q7IJhFD|k9o(^uXl(xPi#-GG6=SCH=WFxG!|ywCr)WQ~>Uy!b14Qikh0buW`o zrs|^XU0*MTk#ARy{d`vGVq-D|)j=JaYwHwjSM5$|3O@S|)WJ-mP>!6{Pb*Vn?aHZN zq!d_=?OJYan_Sj3_gk?ZY4v2*eY#I`LEK83SRWr%HEE1M&+1(l-emFQ&Uz($fQE3K zDigScQTJaoA0Nv7T`9(YM7S7aS^81!*mhdnCgG}vb#!(?RHjg=XJ6QI;rhk!&$6ev zEVn}E*>@$S?;qDM9G-4zHTz^GkZU}y6arBY6LisyFm*axKce>N++>?f7>G;dge1U; zFFCvE4N@c)e|bK5elgFYab!}7l1wf4^hNdZQVrkdFg31b_#^suZ#(=!pJyWre42x% zN(0Ys#haou<&W7^3@lgphf}#(2Uj`$)r8;>ymWI%BWpR`?5iBe>unVq-x-yFYl^#f z-!Wblkw+5=iK`xjUntBYLG9uHW%Gqs-3VU#e4QRlD z1|;CIuuT-nLW%CLbhHkX@g}e3XNQs6F=~S78ImcU-CHR;z?tA$Wm5gXb*^}(a71@n zLibxn3<`03YI4huFV5nlwE9PBM!nWMc$=^oBU2GOF>qy<%hP{obKfiJilx;%U#u0& zdH#&Tcb8?_S7+@ci?0v)Z}(n4(dB>C6ErS@{Sk$IEzg%XyhA=R^{#-P%bFbFV2*1D zwAE#f-hhn;rEc5bg~%5Q?3dojX9O;`7*enchz3H%d9-7Hz*n1LcxaRa-ne0}GV2Ph36F(h%V z8Q~WsE*7_CDX8AmMzkUk!1w4?ff^a07n#9R58by2_Ts3DVrqI- znEPVs)LA&YgLr}+cgFII643qj)rD)^EU*}3!9vme5b;>(xv-U})1Kd#JF7fp+Io$@ zrd!x9j|(m zICK1_7p%MYe_tS)n4Mh>4x^`ZduS!>C+Zek?*)wp0hYD z8uvn!+3nP8NmfkEi~vr-^TN11ZDt6^zdh4d@6uG?J66UKhpLOy;ZyFrXOp!)!w@q; zh#82Z%G*gJi*{{dkK3h-h2mZvTyh7RjP9XGk4!8;@VdkgI3d+jYdT|)DB|$YIV?;) zBR}py{^GZ1O8B5Ye>0%FZoo5#i_64L}U@6ZzgqeJaSqMB6YO} zHl$<#s9sz%#*pVHNtI|FYTvWQtZhoDH**Rt^+DR8%74UubDQwAEYI)z>Z(=SDsjgg3+WW*Vw|lyTl?f6&^XWb> z>ztM<-kQb4pus>3sjdU7NYJ1)BwAc6i&dZIgVZ>&yfQ#_oSqwcR^qh23>oXrE_{J$ zZK_B^dW6)~r>ghw_=xK;#U@4b<)mNp4#7?0K%yfN*nUk|ClG+^weUbKnX?x^68J97 z8|QMdDj5~n?ldxzhQ%|f8i?WlNb}{GUB~!xIM%8jFV zd=#I)NIbg@`TAYBeB(Pop@b;SnLnBk%a@;K*NC#aA2}Xr&~rm}gyobL*Scpd_eBqM zkll99DW>LY#GRhXa5DLeb71)#ifALHdvLC;<=tD$Zy$>^d>l;tPA_&Gytvro7y3gf ziTjNostfOPaxO~o%&gb8`qC-+5bwt6kRSsU23H%i-v89C;=)YN%5eX&yKyo$m&YU6 zk8QNpHBnBL0hWs5%B07q{kDRM%qio2JjFL+Z}0M1%sh8bH`Tx{cOSyDXZY(@me&-1 zjKGZW6t!`OH_3TbZuhXVf*mkMs-@%R?W#ndGcm-_R;7HZe5>$yh?ZN=jq8pNWm=C` z5lD(w#b*_v;4GF9OXqBR5ms5)GL~o~F9cDi!!e>z_&fB4CY&2XBPl|(gDiydkS7b`&`}a zmdOBfRz@nuHBB)RV6{5IGgVs9+zSvTtSDdC>)3&t3IjYZk1D0l(hE*~3SZ|F5ExNO zz1E#%)>lz=(a=RHyr(rWUOgojc&+_)(KI|hj^$%kjba7FR{$wnr%hGwoPz7K{YTfH zu$IR(cCZx4@Cn9berr#;7uEz?QyR&}#=y%*7gHoxdp>_cg{wvnrp`RTz^W=Li&~e^ z6$984&WadQdPfMvp=8i^p%8S6Y>sPAMGvCNF}i-jZu2BThj&@`QJwE1mOXJkA$Onw zSF{0sA9%}mqaq#yoBNLyQ(v3+W!xU$!WzRAqK|ehgI~uAikX`A+(_q;9RP)4!K%uZ zMLOzOA3sCg%;kH$o=D1C_4i{xVAAZDQ|kb|-|^UKwSpQ!!$D2{v69>iEtUuwpP5q( znw;Zh&aMH!2QZn5Gn=adCPETm*ynIVR@0Ox9i!6tnN))+zHK2FK1zk8&WqZgYm2UK zo%78abMB4J!xjE1@@dEv(mZKlfX5h!JQjYoP<+RR}TJL!1Yq*JGrgf6V)oPfWlM*fIRP|Y2YyM1i zIfGQ5wD#9gs=A-PhlXd%o~Xw8NdI=;=1-dvI^O1WNf+otV(DZHOPOHdkb*5SgB21{F^h=c-?0?bx@3y`^w`gx1fj}rKdS2p3AXZB z?IyWEa>aC_9V}02rxdji<>cb1?wwEM1MG{!0{(s$fYPXS+V+Jph9=^l4=CSN7s{_EW(mGKQ!{uI`Ei>NXPb$XSO)Rm+ zX&irK(^uGtoi<%V^dx*fBexLh>5}%`bT_vh{@}dOj2 z7sDgR*n9@Jo? zGZ3O4`wR1z2A#n=CNfJg`az2Jz6X%mZeJHDXM(KkF}^jcUYV9RD0id7K-Jb5UB1n4 z2`0xqy+sD`r2=*89b_3a85&` zIlEFzIQn(C-}+HFamXNCj}ScOUSYb+JobfOWr}Ys(*w^M1Zm2rSSd=9ia;*V;DUIz zAO+9YvK7*f-+hKGtUG!=4A#qItZP2Mxj=W;O1&WIJmg-tSg3C4QVi2Baq)G=BAyP< znJAw5nNl79ZmOz~n`K<&k&T6V&X-p4D8@4sEYAf-?s`x|xCg7kbL*x-D?Zxy)j))w z73SjA_=JJ%l+%uW3?O^0JZ7W=WC&+|0=hC?LeqU@4p3G?i9klUN;!@Mb&X7SiJ9D#Mei$)3C3LV;m?UVW01;t&{$JT1uJS<%&|{{-oIf zrSI}jkqQEFvobK|7SI{Sfrvf@Gsg@dO9sS1;rUy1v*lA=+sW5{z1f=D|m|o z1grGkFLXv^FKhmixBmhLiRtw)?8gL)JEbc;W9(~3by>d~!>+fP2js8LlLa0!HDzM~ zVBet@;yLF}-_wsbB3>J~LC40A?XU+pS34*IJzYk;Hn75YNv^b4nDN2bVU0^bYt`@a zO_kMetSsSbUSoc0qtH-&bOA`kaAo^rvV@!`r^k^4aX0t^Rl>d+;HUBJo1xI1^J9$c z+`k4|z8j?TXxmtfXJPLf_A^5diT-rPg1*n!Ym5rL`>60Xo+GO^R_XKgdv{`eEphjq zI`x$;N^8VE33~LGe`#4=pIxg=wuU&A$B+d%={+re-nkT?m(?kq7w*J{oZ_%q+qfp3_1?$V#v=6EAEVg| zu!(8@)#&F>R97x~cDr9xw|J61nj>CQ^*PTyz$jQp+1;bzhYl-j#+>2chy>6&jQwQ| zB&~%!^4-TER@M<*@VS(7zv#%QF|38PK25izNKmMTB@#O`r+Q58X#dqY@E~Vu~Pr#-S>8@#yaY#gc$zc+B~(5_}bFn9pQH_M3+O@e8pvt}kuA zEbukq<*&OPF^I&bIrCpp8Fl_iztv^mzDGx!Is*>Bm*e*n~$DO=hMy zUgh~(*^Ib-T*7|{-JLGI|D&GD{jy8pM3>xZ!%#6O1Ev>KBk?4Y9qM?0u+>{6X4)_~ zcrJz2edKb9i*1XbB0T?ddO)jN{M=Sv<_VT72G6F>rx9L-eXMI>U?%lwM?MH zw^WS11#+N5GqaN$DqoeowitXqRx$OiT$~uY`{IigP2kxdE8`Dbxc|fZe%6jS%X$6$ zn)~Rd5&zVck}dW-m#@E5dMmJ^OiOOK6Dv0=7`H9D<60xF-1Nbcd3Hr*<+j!k{*u!5 z_h#@_RLU1{ipu4swpAZ}cc>bzk_+77ATX#~%YS6{Ww*TaaJHV9A-wv8MBPQ`yRY`A zlktAJkCO6_^Juq^RZk>{5`0d~ABQaYHdRH(yT9ZBH{)*WTchGEA6RJ$L`BRX!a)ut zuMDEKM^A3wJ_5up5=R=@{wgQ*AdEftj2GP%*7k)Pvd-i+Mo#0MnSEbFM(>-pFFyPK7-o6(0HZ7Vqy5Hx9sQnd zm_!&)zWwIb?Hz@LZU(Kv!(iTCrAFCCZvf?tA?nMYEGlYd5(;F(qnbvU0a`i;l4YpSw;9a%GPg1e7C=FF4aZhWA-BJj65$-lOc`5PuHwgbm6 z@jAV8{P4PEAK@d$Rz+p*JJ0;XZ*}F06&bsR`B!43jbhX?2@y_ri~hG>clW;bY4iI= zR=cg`uQ048!*~)^;2{^`-COrh5E=f4LBhXDS^T~9_kX|ln>Pdbpww@YcI9OMlkmSi z!8p^{Z_N8I4aTyuGOLeYNzwhEJAaRO?>{jfqV*}e`d=FKwPe&h5s!Y?*v;eoHB2$a zpv4piZv0Dw(~RE72E3Zv4Nd>*)%gpI16sMcGXK(`5HDjRA)YG4{mTsNF$S$?;P)>L z&Q~&eKP~hL@-H)d>j*2ezH8oYC1Y>N_Ll5_w)&ox?KXMsJuBNaA$yK-x0l|FWxE6G zUM$-ksrTT=ZY;D1KX&8cJ;b<+Al`!?yQ1ymJ@~OZh1r82d+_7^UMjuIDE8Qo-4Jw- z{n!mb_Xw-q5Oj}Y+zmnZIL6%&bdMJPoe6*Z|8FLLg6>3E36sWteOf}O4y_q8s2N-K znD%$SW})=)Mg7h4E81tJ0L!GF4vF#6aOMQ)O+ne*f4qE zoaSy^`&SRs8GTPrvHh3!_+;LnRtb6h>EDzaBke0CMn+Qq(q0o|z>%DYFYWCu)~^k`w^+a8%bsQZ!XA5;^$VBo zxxrsKOZZ;Q`W3wPV%9IDu?H}IA&otNu?H~rp!=T*&mMIDWeM|pdDcJpaxW?VXDYPc z?_yx81=%!y#dygCZ1-178#vZ`fW8E3PVUNh&BXa*QNF?U$ zk6r(M7Qmji^*?)Zk0<;EUiNsxU*KhrC;SCo_TtxG{QAETzxHC*Ud;MsiT}gW?ZvFU zn6+2w^e0KXM?L+rggxr%7kb;%wtmHoJ#A}G+uEznW%!1@8p6FA!o9lpKLNv@#Q)0@ z_9Xs)svQ^)O4~c6@DDY-C-MI?6?=Ksuc_FpA^eqca_!|=dwJI0!8(RP{GU0iMF?Oy z97=tvpuhF!Ygo;-%Gzcd+Y#3M4I)Ov9rA08GXr2}9l3T0tu2QJz`cDGG@R zrR<*YTnD~E{mLrHjCR52lBW33?o35L*Wh%_t` zOtB6L-N4f4)@q?7Y!ZPw2baaYC??RBaEOo%~=nf>)yOb@!YM>)eNYZMXc)@&4j64S{`U%g{l_p=*t;&@83SS@c~ zYU-U=mW6r`bn@QaDQX^1GZ|issU#b%Ouvz7$uSV(v5Y+`6=_22?gXjS>~!H}R}( z=~jH|wWW_AU0_wUw73CiMw-6AFvOIe(-&BL_=krP6}4407=pe=F`?pPZ?4*{i{zw< z83j&bplWdeR8j!Fb`mXugPQHn1axNt%!b#$bfNmf-WG}m>(+|VE_BVx%LKIEU*6EG zk~I@ah5ncun3&d}UmRb_x!?B2Nb8#CHtt0~NqHN+Y`&(6Mi<{%BGLUUp|<@y1erkU zgko~XMO@sZRs0D2$W!I`0IR;|D;k>u!amUF+Zj93fwBRFPJL3{;1A zc6}dx5!flx$LnuAP)S#0`2oE1Jj#<}-GNALeFpL#JVnUAx6V`^$ z?+YVJ&?ja)aa(pt#Z+|w7;5YHtmlU)46``yEe^me=w)!BY@yU1L}*wKJTv_;G2>EU zXzxUG+hMbe)DPhH?y?^%i>ogZmNzaamgXO}NGpMU+U}rcY85q*V~?vV7gGs9o0*Ey zCBR4;c^Fz?M&CY50Mb(g2kXWLI_QqyQ>bI^bwl(O!p{d3lN`yovTF4z98@@(J}pg) z6H~rCZV*`&T1K&@_fF^)1L->(9BCV_VYA(q1c+y|>*xeU-H$|?pixDX{X^*EV|0jh z1{mDrl$P3EvuRXEmj_~?LL@=iY5LJoy7!B9Y3eEshxHSg(GSzd6WA>}*V9HUl{-e@ z0;4~WE2Sb%^0i(S<+Zd_PQ+;4utrjw}u)w_WbmS~rX%^8aaLO=Pmu8prd(ICCA-82Yc>qrVJiB5oSX6D^YKG=vS zs&h*-tV)G(gj}~#Jv_kjG`)?GR7Z(tEZdLFs-1cfI^3=3!8w!Lo$u~SVf4O@gnY(e z_4;4Q8>LZ3(J%5~+Da7Fm*v8VcA# z_x0SF5BMXrRexMqshWc;#~4Ww-kuJSvf4(f8i$K4A&-XiciK^b>SI*h)KR}>0D3sm zRoeRDHsG;xI-++8L$9V&0Nopz+h{6W%We!xac@U|2xR;hJ+|rrEf~|62_Z_YrYn^c za=X8XTkd-apVsIypc4HLI}n=QrM}(4)&>wyBUIFyVk%lb_`1CQ%cmxK>hkaX z8n+gR7uE{*`HggIp&Z)eR9nSt(%x>i_Qf2Oy&P&J>Z`$j~qI(fhj6l%GO zs{cPsy?HoP|NB2)DwGf^N=y+dMfPkn6(uPuS+Y%8vxjV1PEsT^NhsT-O%jtmSw_~Z zLzc0ReJ~hfjM>lmPOtapcU`~#XSuF(pT~VamiwG1`xCdVAb2EHGIXdXA|#*=91pu! z?OQE6R6Ir^_&WUr?;~A8TaQmrLsgGJ2INg_YktW72gNyXKh*qg_6_ZV`6d>QKU68Z zg6d=Q76>bJRH}NhPql=*NFy9U4N9!m;%{=PIO&&@av0)Y4LC3Wak_x#DQq2Ve+)p|z5F(1X2pWW-> zudaP?bZf93^B2&J41?O*L#f#1X+5Y5o3)PQW&q?3Z-|Si=Bz<%Z_;}kzMYe%yoMDT zIP9ny(>Y&;1pm$#0$cVOFm@+Uu*cnVW7ycU`;z&clhUgp-W7_{p%T4bbtu=HXB5Ba zUbusuUt4Id2~m!&tk$p9p4og}|I!1hKG1o+rb3mTyL;WwihBuS(m4)FSHk_uyBESE zi&hvV)aGuZ3LSz!3&johQVI1S*6;Z#G9J;*Rl?YICpc{(I~||0T#O^=ETKZ`@Ey1* zq=cr{yEy9LIv%NhQ@2|hjNE((Bd2+;)Y99EoFT_IWg$VgiWb29pI~Y{$gF{i(RThT z)HXUne4R;MfCD{rW^}RnBM{F~T6<3A+MqhKh(OO#FC-kWSW+CtYfddN(Z@DgUvTlB z*H*`rh$VJCTj9VD_CkBkZznbtN=5<>T=%*XSZGrBlx_Mt6b>9t3 zWM?`wFRXfon_q{AWQ`lNkvLf&oMr5=L8@6+P4Q9RcaUgD^s&;j_n>@qKTwDHQNape z<5EjeWdo7Qp(_da!cAawz?1U&QpNLES=F~vS^Wz~3ixXVJ>Pn`R;BfKvQXMgp_eam z$<>G1UX?Hs4Wmh5n5422i*T;AXCR&F0hw%}S7!^IWar+pc@xNe5V~6O>l}ALVW88o zDX9Q*V+X834+(ELJ7z1Qp;dbV7fo1UI|V~baEu^nL1DridCev0to9H&t%Fu)6_j0J z9jL-9NGV`&@8h=g;0+)_T z+h9fOt4>|XeXZ-LQ%ZS3`H~A2wykK^%eAFKTA#-uJq!>U#lp~+13z!}A~sHyrVV+8 zk&r_r>^!ImR~ZyFQl5SR4;1_6m*)b7k?%5SGaPatGY1K#bwXm#egj+tSk_4;N7EhN zgz^Bh{U2cNzH*d{kzcRIM9*)~u#BJ#7)V7(*EqfHUTN=-mDehH-tNHJ)kz`_1{f$> z;Jo;LjV-Wp9}co<7UPrXr#7S)lB&e)@t)6r@8}kx?FcKK>pF-!?jNuab>Ja)zz`qQ z&Zu7D$D2-#Mg-d3S&3q2lPt&@85vGMcB&E)ThF=hy;*A#l=~!?OLCHCKOG%b%{#Kq z!`xB73|9;8&4magM4O!AG|_H`;RuaHqC{GLx37u=$EHXd;Lg$Iflzf>Drp02ob1MqK9 zC53=T;;^+h<<@CB0`OXBhOtCni>s;YumwVx062-L`%G?cl2;OSkhKPPXRhpt^W_hu_LR79C4mfk(E3hVj& zEqtxE=ZZCQP{oPIDvZ{~>aA$|~sJmXT za1>|+F_Mp1SX`-!x`#(~2(>eA+^VJ7ww)$fgIx8;D8xEs7)&z|XNxYn9VzxB^AYWm zfe>pRm5t}3w_rgW`P*m0S*D~>py)g4j_E3>fr{sn&r!Cn&LSECM>Gj@K?7WaYH$$e z`v`%GAyaX5WYpGNXU!Hq+I0uO5nm_J z-C=-P`b@=U18Wg(M20t zqL%et@9LM6UcfF^+8LMKmss^ue_b3Q1pscUPUBIdQ!n@23UUJ`8^4-WFvOE+F5 z57Rb4YOR5q^y+S>^5PREHP&z+PFcHlcrBE~y~j0q>iCrZCJVNS4iRNz%AIClKTVygO=^DmJ8O`0GBK-W zj|zZ_?#mXDTwX!nU0*2s`;84?hB#GgUo@aD@0W3EAxOp!L?Cm4z#-AR<4Lv)v^zX` zr@V_J^1CX~)^UG~!upB^xdm}#Ln8yt@Wx8%Zza7~GzjNRH_snA$9Abv6zJR3`#szi z_$1(^+gH1dVHU;z(lYYIccE>jf0S&jsg% z_Cs22{p<29%)6;rxVcIiKGsFaXRUbl9bKM_{x#mt^?IkY_F09r(*Xao3TAkan6q$b z#t9;~xL-%&K}i;B>kxI$68~1syuoG(F*^AYssr(=kC(N^YI^}qIM()$W?=Z{;ZQhA zHZf>xS`P^c1vGO#IQXJNm^FX^!J#1!TKHt`7LgE(L)+v49H(4}wy#5Akk?!Epn_Nu zwVL%D_bd`D5={s?J4q*AGDK0Qd}GU;M4N(pM$+u7orrFb#X1MK<{gPayvN&T$f-%gQZNAT zQ$(BAcBAmqSZAcn3tA*DqeEGG6{KeCRc5w%YmXCGLAv{DS0!c?+MSIDe?Y@2hK|7B zUrq2)AiL&PR~nJK%k$iuyU;A-V4 zj^L2MwC*RcvzY0Y`K-vM}tq^8f?S!QQ2iNCeN3%+BpLhB_=yq6e8 z4eIFcIdW=i?!kO+&HQg7p_7IA?HF$T^p}qM0NIT*%P}D$N)V7=OD3=ob%69NXlp*N z7Q3MrVvgzpfEf(;@4PpHov+ID-oq0Z{`rpy#~2|m3kx6Ncg^HM6#(6$*!k}DZQ`!i zoqF~!u-aq;O+dBDw+(a4xd+F;&sA5MRVF9=hAW{4j89J5JUy4*g3Z>S`*dQ5`&8Zc z!P9n*5ihh4X=JrcYUma;5u4*LIJ4cj_-m_Qpni%k)YtZri=SMf&K)ET(qh3NkNMis z2}dB?PU81D@*I6?Aovom1-->b&=7ba_2PV#^l|x}YdjKF?V7zJA3M+)-QC&oHiBLO z9jM$QH&sNF=dIYN5ST9b&c3{6ixAFb5n*(j$+qy$HMgSr1Tx}3`A2uhLK_h(O0pIV z4o;{({7cjvjTqk_olfWmX2dswNWaFTpRalwP!sP{8Jv$I#@Ss;I|g}wwq6rE9u)-^ z-!7%;I*{m2%TEV?Ea-`{a1u%m&^y>_r-5Yj{vjIK0l9!qrgAj$mE+s-uxi6vNExcx zUJG!;eJNJ6=t2+hfYLng2(DueU<<&iQpIi{p^w9LA6$k06(RmST$d-RYu)&eObOs2 zq&EHYM;Ollaxs{8aZbfCSppZfCNqJF``40 zUa4&^pI^MHuGglj`ohh&0x-~?`cdl(CBOb`u?r`Mn7a3h|H(5Kt=%sx@%u=et7n{? zMj5(Mm;c!%h7`77a(>W)OD$ z8y>a#Xe`ALi6eyJY77lW{sozHY zvbcB+ZT1VJl4u=hIDF8;f?95p3yplrrRGD=vnU%-0uI`Z$9^JJWN)~ssxpXY=LuEW z->X2knrtEc%(}lEk|_otNaMrpj&t*%AL^-->n^26YA>Yq+Wx1Uj`fhYEDvJ7%m zupgK2n1usy`zHrs4T<@**>gPx#xsy&UyEl;KpS#!N$_uUIW*`K&mReE`^A*q@i(D!4pIpueWu{jC^G?(f9l_a!l$c(9jAI`p88e zWtx>mKA7yn22#_Aus&}ZbQh%Sp&=!j%laE0Hamqt*f@in^?3n3=KUGk&GBb_m$C@t z_ARZ^YY8>d09P zr}5F_Hm!M!FW%~z)TfWW;w_^beXk!GN(EU)jb7zyULLt<;g623!|`i+=k(S6iqUk3 zZbHV5`SRiC6-gPs<{pQ9=vC&)_%zoF%;d%!R{WJ2Tkax<#Z5fxkWV4XP8k&Czq zEn$m;X)u!NChSZxw~ay)*9UN11dT?5Jjn=N{mjI4TLj-`HVnPFWfMwBR3*CUC%Eoy&{aQ}&eH>Q(hIxF?bkyX; z%jNqrhFpv#kMwU*Q05pa?k8~udo>>p$g{`KN!m+Vn$U}FF_D2t*(8j?d2*f$oue%^hWmhNatBLBt0un%^c)Lpr?Y-7A$km`ue>a!d9bsK z!6k%8e@Az-CLWdC?6&3)UwBbA`HkWUL}8Z@7yw<`W1oD=ycPHkNw8)&(Zu7|pAopk z`Uo!CxW{S*)QInp$03>X1)-o$JTinkQqMx2_uzyk1#|Ps>3f$iq8UP zx7#}oQ4J5T(9>@D41_3FW@JLmeLfGOz)3BAi{ct;$e01Q01dqhiZc97L$Z60$SxtG zdXo3Gj?~^pLE*q6mW~uf>o$+1j42P-Zwaz(p+WfJHM%4V6S*;-l!1IVxpsVV%WlQV z!zpxbYm(MS#jPBdCbJQ-u2T=IOWLg~ZbRXxA>^S*unm~|p91D+#XsYz2P2+PTa_}g zxiGb{1HtX?6y-UUHlk~hKk%Q9DJqaqMsqu&47-9p+)8$4uY60(zOrUiAtQj1KxHEa z#D%^5eoX%J&9zEw`;+(n1kXL-A13k)c_lc}b_*%fY+}g)*rDVBFenU591Cs_A{B~{ zSChT}zBE9PN)RCE*bO9Zkm4wg=M>9fV!2uHC{R(FltzW~xy(E+-Nk=%)(9A=1L5 zVPNhiHOs)(w1};W$5EjpxG^m%P5}*(FRgjhgskzCHa7Uks`;yyhLD9eokLis<^T4D z?mfgIg1QjukvY)unYdb7Z4Qv5sD(}tajyC5KjtxBHogU8uhEbtUXM@3XF?Sy=qm3P zz;OoLBnjL1{E*>MK@N*&a7_ANbk%PPrB@)ANE#-Bnlah>;4D3VZ4(uj1 z;DFlp;j%y3)VWlBf*0Q#QF`PTe6ym>OaOF2ru&ZBU_-G+uig=?{OQ;M-2<*UmiY$v z0TGYHQ|H_=l(#0l`Clloaf6FN^O;f2FMYz?8>$^^HilpPkY4FN_ZIDhcPXjQ;OT@f zyfM5IF$~p(>2OtlPuR>kEY)6xl=HG*7rC{3CwzN{m+YiwXAfPiy$yMn8GLAGCajFw zpNI89ve5ls%+M{;xK{c*lPze^EKpo09+n1bJPe5*gMJOI_|sq-ID80?B#}WXmq;b9 zQ6Wbzr<-UsE)dRq7Lbb=`^aWuf3eqzNQH70lvP8zp^s5c z^xVz2G91A`fBZ2sG@go}NKy@*7yl zmFJ!6?#J^wnrRPz{Q4@QJaPKx8dzppi6J4#BliI-_IMHr>IMB7;bTJQA$HiOpEM50Hi*}K|GuGQx}Hhx~TwW)!ypb-PKN8&QVjh zmKi2j%OX9HGOSlj8yUb95<8jU6<7x=^KC`8!ONjw=bd3^p>9hO$2+#BTe2Ps1T$7Q zST<}n6*~;PL}#BW5PT>MKrAdd9vi}3MstVixB2fBjLhV{#23;1Q7M$~*m^aLwaoKY zDXJ|^2Czluair)LbuTVI9LykV-AS$S(dkTyw zLnC-x6f$ffT8xM8M&n9s*P_6ABh_@9OyG8>SKZJ|7EvAz4f=1@>7%M5xWqL*2Z1dP z(SRUd738Gd;XlNRGi>wE#j^F(ZQX-&c=yFQRbF(e!{uP$WrP*r^ZMmtgm4dsI=5~M zMIe)bp{f~_3zCS`(&<NS5d_{%Bzlk3qqU_=pKq&u--8&dKl?45uBf63c39 za4u4GX8IsRDUo6Lol03n@zK}a17Gg*^@3Za#t)~gZj4}+_Jv>04Vo}e^H;p*QF;U5 z9NoeWLlHGl67(Kg{C;uJEVzQzbEKzkkJIA+_bz~XTgU#C9D5&(OWJ*R8{uWtRabJj zQ%F!?GD4`N7!fiQ<5NF6V7JTUa*?x+(nBd$;|5FakaAB2#BjMVZ!7_@+8$j}@N;RNy0wjsw0m;?B z1Kd9PF-$IN+6r6-hfl#N2x|3_>SP6^8^U$?2=VgaDcwr(aBtQV*JbX0S z)0tU1p^-y|_5iW<5jgLGj5chcBB<3W%#}`$DG=-|;`tf@?-yX<&bbnz!`vfS9%;BC zTbNi>qSRz!Vp28SH;z(NI>aOkH@X>G zf!=$XU1LX>$PPPOU*qv~zX96=wO(0TLxdgRkjFI+()Ep4j9AQU@-`Ihggl=-pUL5v z2skINKh54hneGOEKYvAW+v@tuxE_CVpbne{F0W_elp@10#tOF=olMR8ZhZkQpEYnK z5|)is#2+pD4f?2gZ4-9X!9ETY;BQ^LAq2}>lt#49)>I!9v<^$zmYO-H2siE*M>=}< z7BT%z)wUR46yUyWl={v=+DlX9Y8+;}OTk*=h+bq|u;T^OO2>?({c-#g6l_~n@&^WD z_u*M@A?(Q)ag@Hr%grG{pm)*Hdq~gy(I(!Eq{8nr@wDIj3{rFt*57y5)rSP46Agvq zxdwQ`bLcrB8B+r8PonVn392zbk&WGCaVBgdz64V|h8g3FKh6i|v@unsj1KGJfNSp= zx_LuPQHiaUE}-l2KtK*eoI#YdU%V!R&xRU97d5~ip>q8)$`lL-rQ4T*@XD5`%mHW} zAyf9ZQN zXmmVpc-~NQ`MiGre>G^6icz+~n8P+sTJ%zi`rj$tu{yG5HGe@=z(p2+-4&>_qUp3`{7O_E`Kg7a6^undy3=6Kgm`M&b_dhcViyX!@* zGDR4pJ8k7$7HM4W;JTo{8jm4=Gd>u*2Ufc4cz#JHKz%NY-2TLGcs10j8J6?Lk)ftX z=)1+pqxf*qDIc}gO*m~VYHCIVAq?yZgk;z_bv|MVw5PA_mVWtYiIxA=+Rf^DjUQK7DweoTwBVklrJbs-`MFeNBaWKPI-Y(q9fh6aF*3+r!Dql8i z>M#Gf?=tn02p~B@H?!YDj?W>!BF-2{yX-SZ*m*Y?lsTB}^~$!T+l09wdoLS&(^Y{*Q3u^I|{81STSW(LW;Wib5WlI8?so6Y;0G-r8-+ zCOM}o+Ai;cwre7_Tz7*cSoM7mwfjm>y*o zDfRt&sDk!&g@+#J!Ma}S+b-{ZN+FtWiWTegKV0;m5(r2@gRRgpaahh5|0#TDU7Y`I zKNYd-LIU+JxA{lCr9H2*#6MnjDw@8*;eRW9%3aboA;07K8h;d#V>aYsJFQ!)H=$Ap zF;au0Y78EU{t+3b{0mj}gAwplJ*v3LrH;`2kL6*Q7k zCq6hk<9SatVQn`N+0mSNE59eS4gYO6eXKVa0SOWE`59`MIGeHDlF9z!1{;`ePGL%* z%oK2Plc^k>22^mG_9mcxV}`S9EnC2*bMl)lfb%hn$~zr@oww;FcrsB)yjIC)D? zi55+Ckb&BQO!bEQj)+N#o%~*Wxg4d&7kgo05H>72Bb@fKGu5}Gbf1t#h45;WTsU(Q@ znLoay@0$H-^vj}2X<3YFG?>=R>Gzk?Cyj1k+X$OjPa{l@NY<^(*7?bYb)xs24}D_2 z^;lFiA-{55`({$xfl-a6i^*!^ue8IOx2I+uE0ab>wwmP1MbBEA?w(P}6S#P{K|s*9 z*h?6tfjhxzdy{w{@xeHRhgFrcb%_o$p>B9(BQ zUwv$8^KDK*#|*~?pmE~WJ{2=LZMl|A^za#Q)9s;dz$=JP6YDpldeeE~W$>(=yu(H* z4lACeCX;+hnGyJ{1$Hp@X}xzAbUR&prCIV(6Nd4niw{|@%jfK14?TTmS}Hn!jZqo_ z%4n&XnIqFD5)jv`qUK_682s1A#4g{h-Dl8fDy@hT+!w<(Sa8wUcVy_e$eU|Ikzu4C zM1^gH%U0+VMo+n2O3ZWEWl{GU(l^hOwuePmPxJ_l@0Gc?{Y2wx$U!9)n@d*CA(tvr zb=GqdzZPpto#@VMj4A5WPCODGF1^F?$z@TQA^)q3TJ^Mi=ow*K=+wudU&N06($+4@ z6pt%`TSz@V^tBv8tH6};oPk0&sUGfI6Y)%pK$O(Y}?C<5OP!?LRIq`7Ykk&)i95ydh3<#7{ zuDq=le0*Ix67f(eVMAxVi&p~*r0vpR7i7R|hvUgwGyrL^#bL{5( z-Onz+Nng>LzTx-s>WqQnRc^?1oJFaE-qo*DsY$CH%_^JT=ab_snr2Jybi1Du2IVno z5j#Zns(pg^)BrNdUuvgb6NzI@o?dU3dDqs7fxlL%?V%3h8iC>L3MO&3F!BhW|Lr{QXr%c*@GWxFVFNKHaIo}iwhhpbzvb2vU`pBn||oVWHI+XWSsr06;Y9T$Xq7~G7UVR@#-xn z`O{pT59mLS=2Xd=Je+*hiPnBCVRs~2iKBs4PJ{rHm z6__$xI2yU*A%jH#Z9J(Ow2$9zeN^sWqq9r zJ2LY4di1?i--eoudxwQ{hJ-cT?vQ(cPeRt9q=_%^Cab{n2}P^72dHqlF{}BS`W**7 zy7w&k%^B$W8=;n7yhhqR)c1Md>-y9vhX`7F5sw~C`cE*M4Qlc9$C~vb zWX|7E-U?R}oioPC3=9^@0mh$5K5iO9V8@=x$>SgLbG2gdwG}P~+{rBFepM`x@-5q_RWqP;WyQ9wkb}`;{ z$7(|}vdq>}u=Bwfe!cJc*`!k;*D6?rj3G2*!QywL$^PF5-^<+)m=J$PzV=`j)}~|u z+v<24b1+)L(-7SI;v=I0Z#KlpNt%)`Iy`pr$E_fJF~l6_wN#&?)aDK651A7jlI#6i z{8Lnp;yb-s-X#IPY@abT$OV0b5D0ONnIbbv&cj^KJ5 zdhL7p=;*#|{K*%Ydxe7@8Q7m*x=|7W4oN-nBi-K6L$&p!!uJJFPSt7kyn9N~ zAG$z!@jsnRlRRPJ?p$Cq5zmCF9~Ql-m1+}J^|Ocpgo6I+|ILoROaErauanaJD8a=H zI(+VeSe)LwG^vfgfj=?EbNlG3H@*yQ&rLA-WDwq%dhP1bN5?EZ>Ql`AIAGXhKyJ1zd~s^X1lRL2R&Sgg1fBgvvj2=2OhDFHS3R*F#>ALDw~aJ?LFqaP?4qZY#aYZ&xt2$aRcs2_!~X-=~wr_oW@j~W}EocoRBm{lbSasbI zTb%0{s*!Be+G+NB&Zf^)ys5a#yfTAfM(G{Toh9(M#9~`AOUzPw`=*Tu2{@^}IS-m7 zS9_UNhB>l0`bDo6%fi90AY`9o{o@|5jGn z^bs7?=$H*;&(_^+pQENr-Z?z$^7+-hpuGMZDEYE{>j!f&H1_(r_(hUkHe|iOsxiOn z5B3($Q5W)!-yCWA8+)MqdbaoMn1PxPOSSS0WcIMYBL(=>BiOg6-t;7rao%?(>sfHq z-GieJ$x^ZQj2{vAccDw9ZhsDlI@vYGXvb%H-}?Kp?g{dm+9#)NE8RfKoi4=Alf$~u z=SX3wXQ>kPNN~^PL;pB#sbG@i6BF%wP2*xQ$~qI86Vz$g$ZJ6WsjeZ=6Rfm-AlOg& zCexLtM;2skRN-Ve)iT6o%bI*>p1xnZ0tcG>`6hB86$%CT#X%u(p}MX>uzzGuUh4AJb-i`PAbsG{ z?XdwpD9Zh#!1iwyoVFdZBKJJEpSVuR8nk-iu$zkNab_nel4NwcJ~$2K&W%#)tSHmutrpPm-x2~P2N(5%a6rU z;*1hzwzDc7IKMBI7iG#m0OfBn7A-HJsi*-PhFsHbqYE|C#yUkpk^PULV~fjF*zs!% zipjgGmLO}8=NT!RTn!jFv#wC31E~WYPfcz#D(b(@X~g9P(P3jp^1rV4Eu4?l|ArQcV~qqq{% z{Ej7I2h87XQKwWq-VvI?D5`0&Huo3-L#Rub2KK#r?*|TlV4Rb3h%m?h3~4H2U!^bJa#v zyLg|QCaYKiyMWd$mEC#UVTm8Url{z|<6yMcn~6OyYy^;>?cq*Jnr zvqDTH>%$`+Bn=nDvGWUItJ#p9&NHQyE#S?bzON>{@u3p6vsLJ~8RAk?gIJ8)PQUs# zffujx>qVGDem<9CO-??(W5s?PZ%PpOh4Q3 zRa=W#{#7P$B3m(q;Q2keNpe;ZBcrl-S4VybBA@NCd+lqstE{E`H2gT^dDZfST0fruc+xOE_Ljtb zD0CipZTt3N5tVSQ1@P?oR$CwLU9FT{fDQL=uLuLzah`eVqwh%PwdM>)}AfsWm3%a<}!)dBk zHRu8s{Ta*Jk!;xPc-8s={Wd#2KIJfZ@RCb?>GAY^##45`C99{AI#7_`VffbZ=s^J- zkYQmqRG+I3)iHCc?lt^R-tCX^Q_`0!{AXP0Jm5h9Z@6$g{@l6h!fOp9t=XvC*>XW$ zPX!K%JW>$rNI!KiPAib#!?{3S;xL68VUx7WxUrjK`ZXiyY}k**Z=Z)e6aBpzjp`4h zRd(DI%l?z#7dck@1PxYX#A@$zOYk2PZN}hs(HQCl;@)j12eqNqRFj9D=1frxg`%6t z^3w-n5a5c0gVEyZOpT5wpI#d0j34ql1IC%zHz(E3Vlq)#96tmY;SS-W_@;gsdp) z+KT+jC!X1b`LGZ{Ij3bLqeptLD?k?Cx&Y+XkzA z1}Q#BMD>mG>nR$8gR@5NNu%|QgHMgtyQAy47O`Gj7n2tBF&y?=xjM&&=U&@cI6YD( zS$sMOa3(jgC$)z)odm7ln;6PHFc6bc-HGxjj{7Xn_p+gzUK6TlO6@I6 zrP8lgPW>u5`yzl_(YP%u*fbYek-^^sO4irM%DC;qHfM8=*Uzo&ajsvNkjvqCCk#(1 z$2A^j7#A~|`0}O;1>`$&Y(7Kt8nuaxc(_YMk~CPjVYO{}2J+&x1P$Ij_B5N~d8KE| zxTXaucUeT8Zz1`r!+hwVy1P!jvFZTCD-%-a4y_sixNwtcIzz}KM$k5Au~+r%J$N;@~WIjMp|8#H%J96my?xeOuPZuOFoxH#O`Bggu!R?1`U0XcW z;$`S6b;+h?+Q=^{9R;s##2h18=R1Az9N7JQGJ2vtv_-#ueYgGHTQ?`*?$cnGfBN-E zAvqLuhm(HYP)W};i0>(#q21pIi6D(A6YQChXa22%sljwc(h|=wf~lW~Nhg;p^nu20C-^_rf~H)K@8FaFghY)Tv0CHRV`h z{xCoI9I^!r^e9p@2jaK&Z&7qz_45=nL~NDRba%Md?9kop zRT|C~0OfJyS3BZEZV%+cp(3M@jF*3Tn^T^Jh{|!s5Jv#vTbi53`Ist7P3YUrILj*R zKhu~FJ)J2h5iVyx1`N6M+uZEvN4x9E*Ri9R1;XX(8ixnFLH` zYW6`!f{M8L>$A4ab`7se66g$$kT?lEJk2ynn&@SUS{hg35aaO~K}H$*Y8Kj5BUCAs z<1!o`Kj%<}mx*_D^XLm>(b= zS2?pwBlv9XIjCLfqWglRX^Yo~cR!~-_bg!VpVb@uz0i9}i;YczhM^mgwxGPztRg%t zi=pi;Q2(9puijal4C}3*(O{mpf?tr)r!-mEj3OA$KusI~t~Fe|R_TAQh}>0CS8~%U zao6EemR%2`_Uu#RhcmK=UG|P-apFZIUiQiI1n18cvA3ZyoqkI{{CUW05c|1QSz~gX z<-dG^GOaS>&es^qiA)db?~{4=xc~9hmpP}6EB8H=f5m6o>YO7&dj0x3=Wg~fzAGDl zKE$soQu1^uKh$D=1H)F|;ciAfu1j~181^BjG;Xs7LQd>43+Ch+Pgm^>+J!w^B&%>< zA$RPT)&s2w=+J1h>gmXeo^ih%SH+^p68}7`Le@+cH$R7=Q1${%6~!H_PuNPdXT+Hw zAQ|jN97+s5fYf8ywIDRi0%9uZfnHnDD(26QPkyEn#aFSD zg7f0_dfWAys4%HEVW>v(p<*oVhiJ>*vioVOM~MM5un<&4w|E>>Gnc6^uqct~6G?sI?*urTvNOBupyzy<44tUEAgraM&G%n-l#+X;zp3_C z&*xt#c9c(t5K_29tlCs|G5aq^3hONraX{nid{buh#^sQMQE^O_A8oI0jll#SS5*p( zrp&d5j+ViW9xlAasJ!^CYhQ(gb+TmT8Dr7jZ&3*_vDbSNm)&dbUX2`!e`7j6AyVBe z*)lWkdAIEt<7CAPjM}TwP&>=jQ_+owj{s_&(Vvh9Vl@pplBii>(SVNn@Q3}Xy?NEr zu-;9=?xP#Md(iM-$JpuGH}hbtz0=##^$X}1V{+iW1ERyR$Bd<;A4d5z{w&%}$*b~K zecc)#WpFYW4N8KvG+!FdjhoCs(QMcj1`8$o+E~&!^j4e(0{X>O3aS4YG@0GTB*zvF z0rSYlxLgyo%VR?o?XIE_&{=7Y*BBG`ms54xT7DV;DZ5U14H(;7jX{Gyq6wcQqEBu1 zKPhfa;2Cio{H^9=Z#T%sXxQwuyGBWqI(W-I&|$f?Te!1=ffR)#49ZF7v8em8 z-4`1|1@iCj{p@=$yH#KRjM7bARNMqJpTCAfT43evN-_D*@_8v3W~MJ<8K3qq)-;~_ zVh=wb8U>)5CRJ~q`%Xh8?XpwQH{Yi_o=22wV&XI@t)YARTHZ2VRlQVEyAt4{r!m}Y zamQ0I-1Xk=6rb^466VT9aqrf)(kV|YvAOh^dB5X;bCtf&y|nM=x1Fy@#fV^?_kB>B z9Rmu7&g>Z#_N=H`Z<*V<*Ihc((zX4pg%Ox@Msd3CaC?LjHNl`-tG*%j3}wDJ%F=rY zXcZ|r6Z!P!C%LplrirNC*pI`l@jrxMm$DcS@?W2c9G2c@7i{$x$+%EQ;w1+EV$Cr1 zDm2j7N+tIGU?y>i+;GV4Nrh-On@PyQwi4gDw71J5BBY6EWcgi>9H7D=ub}(T)c~jW zmDs5kL|;)leO)k(Ntl|7^ zdjY3y?r`EUsHb@@hmvrtGO-E=_#odppJ7}cA1?`t8%xAiLNTfn(}(o*BUh@1rYMf( zap+q?pm3FmZ`LK%X5i2gN62N>I0NW_r@Wu>Eb4rYkX<;exaG@z=hH?};n?heChjC) zUHyNhK_CCOJ#bBI%2W3LXv>4ac;D<5a4ok~2{x3ysiGNa=aCT$_cTARwcKy;^~{p- zx7UJx|fF=?uO-+PhaFsI(g8AOZk6nomW&-U)1dd zY0`U#Py`f2M4BKF6%hrMCQV8ZlwPC>(gMC!<69i&J?O(2|e z_Ooqo@D9q_gQK!=+sus~(~c7& z^@jmsln3h7Dl~EvD-}}sVVfM|_XGVz23vabC4D4M)C!bq6Z*Jk&8{GR{w7Fqm&mB% z`#g>+J5F-*16*U>S&O&~UJ_RM^Y^3ZX8AiGyRqhIsw^@r@^bY<a@Lp5*dCLiRWMn;PD{usVIn-e>@wclq+GeBNI~Vrme4SzpUf4YOQHN77 z`1ZWHC8|qHL$#I#{2bvXUW;{f!al(-=>~-&j2$ctsujVtD1=Ckb6cw4W+V6C!i1hU z*B7$hwUy2|`C1ho^Un%%vwIz}|A@)bgmVb$O>@n1cOOy{R3Y$AmXJ-Cc1CE7fJNqA zlELA{9^M4$&dvK*)R0*?Ra)WQD>RPKZ3v{g>LqaMTHYF2&kGvj4oiQPXmGe1p9{(buE-|rn5r_8d8+g`UkD!UC z;eSLi<@0YN`b1;V%qK%3cUstvnKn>)7p0_zlG`HXO0{~=iQF6r7fyTh$ua+DnCHq@ zh3G{7nFIu2mV(XYGPR}UcSFq5-8l4UdIQ~Op3gYF>&rS? zc!bIo7CF_01q zIQ5LmhYrU7tPp>#lJ?HzzfokIC0rB`1-7AFq>_K=Yg-B}t$7t*v33LPol^napx_B> zQMUIVlh zT*0`n_a0Fd-wmTu>m!N(?PA4@I>Os6FuZ#$dE&`atiFUp8EA>Wd6v3*B)Sh_k6C#; zeVyqQ#rcQ<r?a6^%hziAD zU3Yz1+`lTIZb$*~N<^DCX+QwK;5UBE9<<9Y@YYAo7g&R!%fwX6V!+m&$NvNF?>53k zARJCwQUw(cNTtcYSP>3#lUCP))$lH@@ z5PEw+1v`G(;^s#_+;PMs<*5qkGc6jRaIGN|PWEKOT;rq;+n4x=I8D)Vkt?ZcE(Q|j z*hh;xj8@u`4s@nI7xZ;s9uUQ>L2hAk=FiWgTrX zd1?1qH*Xc(7I|j2$&CoVeHJOEQe^ESpK#n6L)m`qVsNdc>(Wia{h%W95O=vEqYJTz z5+8A411k-}TTK{*uGQ>6L4f47N)m87MbLZ_Q-a5~In;5sgG;2=pn$>kSxze$X z&x6Xglzl=-%H@bY_+p=TXVi08!|r|II_78sE@;3>wS?T);m}N=4951?`UV=*sDNL# z+Ro}iU3dD`KZn{2f}y)FGKNUSZAkD%2{h`NDtr#;o9Q{Mn1YwR0MVhx5JA}^f$@sn z6@steI-1LOF>J7DK7~jvtNhZaGR5otpO+7P`TKn|GUH+^Z@_U#*4n#l^Yv>Op3-;D zmT=>5q*Gqn^z?&d(i0`YWA&D^V~9l`u;}*&5@C{!+I2F_L6l+3WozV+VD;-wSSZKg z$qA88C3XGIIj6FvyiCt`Kp0v993Z>*0$t(`WPZ$aa0NWxaxY3&8dVNl`y3pNiYaPE zrz`&}ylEs2ea1GU^x0N)h{#JL8Hym@)8D0rrWchS+zRVTXOiyu<)h~neX}ArcNqm_ za6d>N&$x-dyDtN)jh`xgaNTZtq3l_;$|7?e!+qlWhyi?L>Q$-aJ6Knn#bS3>+Xpu< zV1AfjTPvk=<%nF5(&&iuV0;Rj`*NH6dEZlX1SDL$_e%>5(0@cU`kuTp#xNHTvFz5k z5{j%2BMuQ#zw!Xp>Mq^k(a?nRYv{nb3*8IoCZ{c#rB|r`z8=-Uvwf~1l_7Ig_z7|{ zT@Cynu|^f1W#aKGyN}?0V-O~=61R>q-uQ5OtC?c9A9|x)Y7&R**QL0lkwe}hUIO%Lshm#a8H>dY^f_j-+9<=svif%4q8?{yh4GH9q(|1tEaMXuZ( zB;oNafO+qQb?C#_V&FWnT~#2sS01FRT_P(>Tl=$Jw{w?lxxv9e@l5MOu~_>}EL*!1 zacTTV8$4s;cJ{4Ie5+emHUXjOyC7P|Iy1_B_-z{g{;B1RYxad|AK+*o`C&m~&w}_e z^P27{MR`xek zN0!ScxJ5dh#oa#1&<1X>=qn6d`l5h)AjFHhA!1(n%O&(_y5E>CzhaJ$?UoRg zhDipO;|#tncU8D87^Ag#765i?4Wh6<9>9u~pWQmzqm?Sl{~qE@%Rbj3bZFnSY3c{J zr`Zifb9J)PK^W6T!&L}2b{=ntD4Hh6zST6$`p$rP?lz^dYJQ-b3^x@N=!wF!LLK_> zCc&b_Bn>9i6p~j4)aMVjE-4%-BUZVDFmNO&nSbIz9-E)ssD*MmPX<*zq!AAWK1MwyQGThcvAsz29dsL{W$GVwT~Hnb7Se)G9m^6ok$!zMa9I zo7MJd8LGuu7apbpb?3w&ID!As$MkLv>hq|@lN8Nd(UxcC526{@R7%deTiCfJLl(W!xEd&IjR5LTGAGn1|w zV%)&(bpw87hQ3^ zKo-v2%g2!NDDeIf3@_OIMCa?|0Q#(M{A(EP>`yaEbech)!`tBpU+*CxjAEx$sPS(L zqC+nn-v2}tEpjoKc5zaYd-A|*uJ(h9;9~bHAPRiNF6H{l9G;YLEiO^V6&P0xRZ(?y zX1W6bBX>i`qNM-rTZaD?_Q&o~gBw{?U*BibPsWSx3)hQ9CoM6rWrnoSNOI*SzZ9S1G)vCcb==0^|l4 z+Vhs4hNVABN)|?5E;ifXIwk5<>!-1mw6@fJREdwNcLsQ*&r8NBv?LOg)af_ggT1pQ z25>&O;!vLB&(2fi){uI*&XjL3sm7FKJ`JuY|7*mz4I57G@%p+py#rq+Gzuf3oT(EN zok*}^aGfY|lGZKAOh8PKruAVskJV%YMziW{^Z|)Bez{Yoz9t>~U;UV+=WoDY|c1A!%@YQ>{?FIzM zit&{doZLQ~4b8YvEkpnQ%kYbi6QEdj9nP6_IM#5$!D8$(%E4x`KU9OSyA|K{cYG;^ z_`hfhI~inJC2Ji?!!9yG4-lRnK1b0fVw1%Fb{d9!9x9D3PIaL2cGT0PC-^%8Gl@2Cfk(CXeM|b8# zwg>0@XOlt4wV1+byZiu8(b(gg_LZPizdBrLV*Wc4jDW1qEfG1suENwQ79(^`Do=?o z=vGTsiAvcdjoItVhe#Pqpu!$ZWfB}8fSCU=+p)jF{yTwc2Q82a7MTN~)->CP(7T

4a2&Q_kZ*cW+++y-B1e6 zS2v&aHnp44pFRy%Id88%BkeT)r*kaMxxZ+S zGo2PI-Ro)C6l9b1ONjmMiqOG6`KbR=ZOd_p8`aPHQ>+;3Y%<}lu9$khh&Ub#?YVy0 z5jz~2>x4}n>P?Q+tBZyw==`iS4pbPEP}Kg_AO54{*GhROo8ps0#qh3$-DR1<4DjKv zH`Hd;AGvIEH}A2bGT=;q*%gEBYlarNVy8Aa%QCHzknMd-+oVOo$D?XGAlYW$e=bbY zHaEjI_yXKH7M!sKl~2#Ko*h+u&gAkxi~(!1z#g4-$3c>{DSz7r(CkyFPl114RD>c( z2CoZpF9+A%Rr^!-iJd!|)25(fV>`2kvM-Gf0pVW-Dp2<}tiiin0)Wmdn!cp%`wteWB3~k6wtnG#hUMBhndI#p-au0ZPj=gw?sC%8)Gw1%5#fqV6oE-D};cvBv zpMCiVu+zin=F53%e_h{SMO$qDnep{CLo`$#TO&t3{D%Zx#3=dalP=ip*PyRDo3Vc2 z_T5}^k%pa(_3_!$Ef_xt+!gwy^w96V3U6y~gqUksE6*d=FJ+kHV24oLMNdVbud+_{r{#gP(c~#!V2&;(kutA>i*!U$~STdmNPDgqLB-Hs~ZGFy_s8w9}~HN?Uyyr zsU-@%ciLeCaJ>o-K(UmMFr-_ z6c#RPoIPy4(WaHTlRN0aBC?ubc%AGSn=VRqg-pwpdHe<$8W+)@eoE>~ILMBTL6*7-WT%USHPHrq)x+qE? z{F`<6>lu^4vv`G=w-1yw0&o?s3#4=MVYld(y@M*8g|@8~<-G*Z!L~)mlJs~^b?KJ$ z|Dc1p_FTHp*cFn|F zwXUd@=}kroeB3X-v$2&UaG-mFXg*1Wa@Z%r-h&)uSfB5Daf5F&T+h0#;~ii60#T;4 z1(F9JhaFx$Elt3mPF_}wAL0J%wT%4hwd}s8)854rdX@YzVc>^v;Lo@XuLedZ$UOg; z${<0O@i4nhsAJJm`^xHV;qb@>=@xD8*n$n?WPz2I0xC`JxxuB5!=gg%{%?gOKdMSx z8|O^VENc6X0d6?Ul~VtB4c)DXZD-%-g&;#~gKH8l-}&*UQ!6#7_y;G6dE_=;l94=U z;bI4F8j9R8F7hBZ>ME)=OuF1CpW)#2^*#3^CUz8%l*KbVuu$R^Gvu(CT0+UOe+JOcZ3Yq+LurCJb3tX02d_$!_t`tE!dl<6o^uNY90c! zG{#KpoV|ahf-846E`kji_?)*kpA)}dUl9+!6nWVtVS;QQLOzHd{0Yjd7z=G_qNdia z$?rk+g#$)f$TUuVrD^tQau7^IXBl)TF-m%{T*5oNyOgHDl+fc zVsy)O@|3&di~a7$s}{zZU&rJJi8oFj9V-iVD>{l~(cHUA)k$A&Y{h&xtDk z?WdWrV;|ioVJv;WKgi2>`kKCDn@f~+V|Yfpa`(xo?V$<$Jhawg_|AiqGK#~;)Yn`p zLE{#N2X7jgU?(p2UCK?`f!^UCb^;a)z~1_fsI+~=^nx`j*NuJm)JUQ0=k1<+;pw}P zt`_cXuc{r+1SX4jwIE-U3OPUjbYJ-Q;r9hP$#w?9-}v(MFO-7#-rcLTUY`C}bc&NJN*@`wsMx8kCe>Sq)W z$rr!Ptq^E-jHcJX%h-Cf0evhDewA2=*1)Hy>);2FwP=Yr3t8K)XI!Y; zu>!Yds@%FUgj9zw?KN&)=cKOnH%b8{7PAyxnVp*b>Mn&vITK5Y=cQjusB|zUzy9@^ zqr5g&IKTmz_55xiyZM(i)`5iLn-*)%{x=H%^ZSdE7xxWP)fyK0II6WX{Mpfnmtv3Y9tTBJ6x2cL590GF$7-I*BQ`M=7vtOWZ^~-(!91@U)ER=%aDPOzsn|9t$XCp zx4l&cE-_0d+da|C0C_WU3gr<9^#O)E+{^f4)Op&5T-kfM@3Im#xIjvhqL6f}F9ug< zRqicp4YE9ueJlRw31IR!G zIt6rHxH(UA_rjA-^frU$PcHT6{?G09a}ae8{(D37U3&p@oM&^uR25XxsxDOpt z7?GmR_OOb!VQ!b=jq~FOd54EiOHc7MtD38dHQI=>Y-JZt!#24;BAMAQM=U#K0*dcx zF6NQlwj78Va}KP*Veq|Mhm_DD4u-~FS65)*vw0kxm`d&WQ0YxW1}mZv8Q5jgxTJ(_ z^keC`>MaUXSaGlg{oYG%ePi(UqaNZg^&R&RY}Ts_*blA&H)Yq;90*a!Q-45nsM%T_ zY-Z*TVQYPjy!EbUpJ2;~uyv`2}KbVXYX>*w6!)T0j8gMTfU+SuXrsQtp3-@j= zuvRI{9uH8?8v{|ON`)cQhGK$5Q^P;hpy)r;K*6$oiX~KA@;a-!pU-G(zm}XRwH`8g z4t*;<hcGK=W0jMn`lUYvyG6-pb?d#ljvCy&4V;f&geMOW#FN>j0U$c=o=_K8EsI3jtH z6JBk~@bL!!D0IJ2^&>M97E@^y?Km+@QHve+z8mQ;zeU&v18qFdop|ImU4=^C&+V4k1U(P4eW{1RDHr2ZHLde;xxdbuaEw=`@V6&@Luc~|-cfBR=Mofj5HnbBFwzQ1gSFK4rz zw`XsiU15b*mVL=-i<+#p&AZAKogS@VDL!60ZjLX!#Ix1OG(C~k+nSAkR#koD{UejK z_dm=fUZ0bmP3}A!=D=a5-1Hak#;Vv(K5-~#)!)x$BV9$}Q13-cT+j;BA?Vt(fbuqU zus}MF2n3?%E#-%j49fs3_^@FNuBvVo>M}>nqwU5d$@^^|@DQZ_XQBR*oHM{0^EaY(=(Sss7F@OI3$`c05e0ZYx`; zy?mmQ0ydMLdm$h&@={1MLFT&omM-H)aYP)I`gEC7eX{DcH1ir-RKkCK@e`IQJY-XU zTK%u)CoIbBSj4#e(1vKKhD7svl=AsxO*&z-CpWK6NECARKuATYDw$r&GQ;L~@1xfU zcNQ$27KM^eG6~@kyF!Ozqv9^7KF7X6#VjuSt+sb1R=%E_j%xhf-9gl1s+e_bQsj`T zK}#xb8u)}cmjsRY@@P5IaY6Wedj`n)p8m_jR=7$jdJ)P^6cpJnyr;Ts`)&{Iq7dfC z*ro+T$gF1KQj1&zqa8ilxmv$Xw=kj;S%7OaoS9$ul`>z6N3P?Gbt}N47u9!G9$n`ap?92 zk*V%wXQyz8#7@2$PPrFeTpJQ@d;|(&tQ%sQ$0oD*s{tvXC-v$i^-`)H0@3upgwHN+ zmdHhNiYu8ZVR0=%EhIkPsCG{``o80@EvCh{J_A@u6!ilCf2u`~h@M36yL7dF(rfY% zWsZ_QzOfy1cO-D_^h1aCwS{3_7AlzFVJG!?%#+`@W#sF}BN2A5?8yT^tuqUlE>p=; z3lC4|eDi7#R06|0r-&w>dWpqQDH_W}<~_ls{KsYP z1z-<-U{nzzwQb2Xk<`MG42^#5)wzG2I3D1fDyR&d0;ibA?amq>?S~NCi#022kZT^# zvlWb)#ogAR%!X-IV|d}_j!EuU`mfUz1^k`z-iWWu?A!~{wKNrmjS;xSH&7nH%q4n5 zGdyw##^X-imij?>TE^|uvfRKLdL}zQQ~UyC{s)UeRxTyVrumql1pjfjB{!U5!}r}@ zmR!TF>_%{k>Ln?OZi)o|NQ3Q)vi=~VbsFTa${~?w_RP7Z=qFQq==YBJ%l3gdPIZ@m zdhH_$r!7_9u&7*;r{169{oq}inbyX4G%xG_kw24Y`(balB;0QFs8CEo66I*2kXiJ- z;o>a{3Xj;x;=6JeqU-;mKMVCT6yCGF&Vs~Xgm$}@ z9UbH;w&0%6hQy_ltmj|JID_2i0&%RmO!~#JK)kz(lCVn`EKG264*y38nJ&=iv)KOI z!>N8zZjpjmY0n0W?PD@8$UJN3v-k;PRZL(_W9RvF0QV?ABPn<;z@%bX|nxDd8p3eATn_s*GS$MHY z?^MCf4(JFdr$U-v{C234J^kiw3%1_AnV#Z0xDU1PXewFyb~41D`*CSxSxyh1(^uXn zub@WpVCmWYy}U5zU1B>)(sBCxE3U7?7bODI-rL-xpt`js8^XPZX%TQoYE zyb`!dX)^I-inCf$j>hjAh?57B%ML1?+esM5Z*G46D#*p-z4XuT{_LbDj60ZA|&~QFh&E?=KGR z$rdlg#B4e7og6bZ!Y?v&CqA=ei*)*ebg*{HrPsIXf3%bh-w+W6zGrcyaHd%pb=X;X zTY8nC|0=gOFrHH;DPch&sN&(3X4npT-w9zhX{bkts-vCjs8j+Ak=4$$cSzA43fxlC zgMlltoH#~&|9PR91^lEP)#<108{mRtlVgkQHvEMXh59l^x&Orcy(Q2`&>%*2t9(f< z6NF<N|%@>+go7C$ibx@U8pw@2%K^XJo@j z_fB>0ba)aSOmIchExS!lI9))T_r&gTgq=k2vzP!5Sc810E6_RrNd?Q15C~jYj)v;% z@odT1=;{9O1G)gi0MtaA4TzA4JjMM%|2E%&|0xoM>iPnCANwS#5%>!;DsT}yFM#E2 z{A^P3nb!1FHdyJd0NxSUZdmgB^BC%I!J9ca-59@#+#;@L^#i`7mCevG2N3JP#yzxN z!zg?mg=Ib-#$d6I#u(^U{BlVdetQw z%cH~h1pB99N&jTRi{wg>nC$lczddn$2owIs@^VjNynf#6a$jongC0U-fVO1HHGJAS z$z6H>!`74p8O@0L_nz=O#MZAv4}}czkq<3qwXO@O)>2z=jbDU1QB%bniL2XU3z{^u z6HQZagse$kbs4>@*q3*Q4%W+uJt#du!TDny=_`S#?>OG76}l-htN-%)lC)m5JD$Si*NU2J0Bf16R15WQVG=SWlYTi>xlF% z<|nRZt=v*r5pZO_h7H|ipw48b?~2|cP0uZV%u;5d>o?vkGk$O)ynCH`{*KAmG#Kp| z{zH^EZz5t>u!ne_HC*GYjN%0Yj3!_oS?(zS^~yAWAZQg$S~udb=%o~VV#>CP40qUH`H$J9>-yp<< z&0I)Hma5-B$0g%fKIGz%8`~Hgp#K0-|8&VX9(P?9|7V4gWjdr`&F4*v>CEk9vN`+( z^xIF2JT9f5C8@$hZyiovepm-4hNhpQ5N)|=Nh)^PfD;%edG=-L(}F@j-WXJR(D=~?$y>@!D;X?_36n5HPrj$eYdJx zLpsvJ9)3V_l)}aT`2T_5oa{k5C%jxJ-A3Ph0f8`^KSl9F$b=&avU zvGCgTkguh|EAVQ8dvk9j_HN={s9%#?IWfn}Jd#+2|9GHXClLri*~F8)XKHLh;;2V% z9a*%8vZUkxcY5F$=L=jmc|Ms1&yVAA58xan7fs{}D{wo?3LRZVrnrkL{})N&@gF{! z_?p)^k*1pFZq6r)_l70{66uerI@&Hj7J1Se3K$yqUTR8a>s&E>LHQcN-b*X0rD67h zvaMlhH&Nt#bGO!Q+c9puv}nw8eiuF|^_W5b#Z?`dbDMcX)yZn%Vd$X#Hx=3Vc(M=p zT0Sz4o=aEF7rp3j+g}P|o|D|jgoVYcw8q!+7)5`eX35-ERqoju3GU%tcm>e{wd=f%C11!lQXH2&}v~sr` zf8(5^m31HYMwRtWVjZ7<568n!v%x_B2?U^LR$sX5Gpm-5Ie{bP=KQy$pMsM^ApG436A$T1Q2U?2)6;zP$#4|q?>9?eCkE>?s@t@IIkx+L7Fsv2(!8hzw`(BeXA&v+ zRX`X)8eBgJgPt}?2SM>nXh;7OHYnlA)-D%}ur+Fbc4qJP`wdorbotREBsey-F#!@v z(MDlHA1*9DKWfEhNZ<4GlW;#Hs< z&@VwTnsay@e}1B;34Abj0f4V6?V5?|S|?Z=P$p0OIa}v~d9?Aqrggq}e03~m5}=-V zDvP2jT(_+8_0^Gl{PCjBAMRsJc}{bUw0zC%HxW?t_%$rJXwbBi=yii~K=RiIl!bWX zB$9h#4fBSOFgx~)I8LM~tCuHD6&fzy=WYG;(tKV6bh$LgeP9tl|Tbb@4(6OCswf#F|b9NqD` zenG(KE~UCGmq6Gx81%*UBoeRvK49 zCy-PXx)GD)bd?>A@?&^%3_JE{Sz=E72G^n1rPZ0L2TsYvGKMm+o(MhEC>qvlMD?yS+fs5 zJotDz@4mi|_DyIqc3xqDB%dZ_L0iCP=kV07f+_gXw|9tu>Sdwi&-xKvmnSfXGhm2Y zMDsf@dsoo)Vc$Jf_;8{xI2Q}|y>|m~EzF|-W5D2^Y7w%@7FgRyn!2n&a;(=H-fQxg z_B|Tm5dl_UV{LEq-GbN|4BueHb1C$z3r-BzVH@=!htw_^C6P~$ki1bp;6B(%b2WJ) zQ>#?qc^)49c5t|M2dWYh?Qx<0GcUq*v9EGCwq)f>LnuPOHeFc)kXRU+zl!^9Sq&EN zBMD_^2nXdsx1-|k#BQdD=kGukE}MEDF#ZeW#dU%v?q5(PJDK3zzw^vx@^{4@I>_qT zi;MyD6kijUZ!o%7e(Q1P*3ED#Amhir)d=PD^4C+1_ECvVO?_dc^Ll= z<(J6vuVNAhVfg`RNtKWL@4UV!8gGY@X=c`IO}Kx=icuZuBHdPd|71Z!Ea5|1<; z9AnKF(%nNwEWdPF(z)HvMVCJwSk%0O?&3qGYn1vpUt%A|LhEe@1lUle^RG|;tP@S+ zE3V3u^38dP@VU(S&j>fvbBP@45CfO<;)v6&aQFrhx`WgG<+!|4=C2tqa04t08s#g% zoQBnvYz6>2aOH^+((B$iajdJ^>!F4|_g{#b_Z`}o_*!KJI!DST*Vqm6!nRhBz{2q( zkQ=E&KKODJUg!N-|=<@*^sDee(f9-#WBI18A@I!oS5H>eB#X0%Oal1CNpm zq5=m;nP8wIg?&YKROCKnImvjP!xCyJ*wZbAU)zUpc5N*hR>6VcMOl_FO7fj^r!qFR z!Uq|(F}s>$+3**>GZUWml{MYeMF(VLx&(j0Q}jX`h-LD69Bt3A3^wYrIVO8-0H@-@^;sYm~h0 z5xNo=CRd;;c}GTCEnNb=Y?oL@)L8x+RrV*@r-21ZU2gHPEu2ii)pj&_)aJ5e4_+uq}}Ao#$$UBS$gpUF~D3LqcK z`@_}Z$x;IRX&{d6LnNZf<(zYxIO8|%9(`8pyP6vx&VB@Iy!RgLV3Wgmd z{HXcpPNm7`S4|%`Cqd;hG($j9K+YC;6He612UpE7#>10O&^yqx-v?u5CqJ{dz-N#_ z-q$UXU2*W`N!>#tdclOWCfz4_l}Q(W^5W=vT}N|{VwyGvqtYnhgQu8U%?B}B%wY## zig&<(BMByt`C^X?M;PDcb(w-X)DFVrn;#12y-r}u>CS!~I$}@1P8;4JBG|W|`po9z zjPpf5htU}V(d^?9T8&`xTLGj}f5ppplV|G~DTtIkES2&$og+OpCF)9SL?jdNI8`BE5m zd@YfK(DW27al%3!YyJ{+@vHA5WIHt8b!k@Cv$3D3slTE`z&?$9&1{O>QD*W*?DRULWW{%>BDIYT@4>O17fcDemu()J#4bBh zRACiLYyz!>JoO99J7K0To3RfX^sVst${0ifGnw!EUkNJ)L0!=%reb{$X=e3JaPC0d zhc(QD4^BtXPPjoJj?2z31H7E%yk5Cj;KPl2dY=e(dcoPtye%`q-O;|1-GF)BlBFv# zcN!^h@EHkpM@Qo$x5+-vvJwj^i2;z#Dj!My%h0NYP6HjnHF{xdw+?d<8N+4dy!sW< zm#W5915CuXiEXTx1F*d!lSeR|G^W0tb~-m|H&1=(_UO7AK`y@xOe)JlExE&igU{#_ z9I!0X81C1)-|v2=b#oHlWIg)s1!zH%2>IzXm>E(ddezytjQzlH)5~0gT*rQBGWaB?u6e(s#pgSQgKbFwCjr0W@y0 zxptpA>;p+OFb4{lox(GrwDgW{eut}y zZKJ=9OQDETRgh~3Y~4pFMXkX(F54jWaVLxdZ=V7~5Y>`l%B_FU)@_QZfqzrH2AYmm z{+KVp(CBR>)3e961y>hSSh<1pHHwGQ68CR2v@ReJltPg}!zaEcqLgV-BeTnLS7+>4 zRrv~pNn&I0wDna5P> z&_=%e`PpePReqi-oy&kZzJGx zi-e#=3Tc6O&NBLzCEwJToxxKQ^^gVgWeNJKl5)71@XGEPQuInZ{296)v zbRi^%zQz`b1+&T-#}Ny1;Bk?Gc;t1FQgx83x4FASYDy3w_fa<=uXgjI3N*K1q?>eQ z#k=yvw^ez;W@2FDV}eQK-U3kx-~C^$^b;Yq3W7rx3_4mAwIa;u4;Pt$k~f!GxefUD zmbl;K_r+XyMcw2Ld^h!Kb8CU?-1cE@1wKx0en_mmcz7M>!rQBT_X~-ld_{isyL6y= z3E8rtPNF26##R)?T$rZ*T>3eV8>+5i>RZniU5P7OXIj^ix0TCkMAN5UH7rUKOStfy zqqWXZ#U*#(r)DV~XzBdcZIk}3c8Lzv%ao;Fe*s9B29C6<3=*4qBGu^v6UF%xktkKk zKrOqoF5L%bD{-**Uez+d=^5yD_IWXP_1gd#Ol@ z1TYqJwv!DVF`3C3(q*1t9q>;D7rv!*!~44*9XIUc@HX@u*4d?BQ5gVy-+*|N)7KC< zu(!7lYXB-{%Lu!u=O@42gC@K&OefZS^~#`0nN>Ehh&hY>9e_UCl9+K`Jw+b>8b1VA zy48b^c^8lIvH}u#Fm^J>E}`TUqS$>hd-!h8RJ6_#57cpDnz!Iaw?=PUG+Vub!lODc zn_hD%0*yIn%PsdrkkR($-r7kOTLdzYF3^Gb+T*s_bvUh=hZ;Ec$#BOUj;$6ss};>D zzfqU#5%bO;5`2DpuPhl$H(S5?ycrAOB_O&VTY&{Ca4yo`<8%bC{<2th0@H3dgZy;d zM;IjAUBRARVDuK;0CVvI`PD->>L1Qm9XY_N19W$)rQfC}mN@Hp!EFteE1q>z7`!s^ zpJ2?dNiiW;n|CdUTUq3#sMg1u3j$Qg6PCBCeZR5UW)h;>6j{laE_isZ-gax<4o|TY zyDI2;B=pLO;nVpBx_-%okEjPm&JVQ-Tv-H5PZi2Ym!*ipKhK^^GPXz^;;g{W$&nU! zwiHoRUNp7S@GHHt*aTOqy7Nf&hnDYlk06b_>JRU4Y!dp)YKuRB*c~i1L4is#Ajq2* zf-+prOT=>pr)LX&JC|MXJfEk_5vujM$#uSwWI@6FMy!S zdxy*j9N2CCb{Vryy5$^rN_4BIGY1DEG)417W~NKQ^|K@^)3W!vekg)MgJ~${l)s3g`Pc6 znS!o80Oy60ZY%xW*QGFo-mVkAxirMB7?~@8>fJ2sM5m3mK6lmL4DuQw;qlD=H77~2PH6PZgF$xGi}GQ7yw z%U}`s@bQ7wx4VUNks1ts@A1{CR$t?Ur|vLGUyY@RNB&4Cll2*pBE_Lqn$~t`#2j|$ zp1XD~xKOby85}nFqae#W0Ke6jxCbe#+{vX#+#Urz7%bc53%kD9G6wPdtfsiPPXfr` zskpua4Qzy&A2$O0vo(RW|B#K-x(9k741nUgN%%Ed8BGKSbO2+5t9W3g9f*e!hAlJ; z_CeCkG0LL>m}68BvuphCm%aG?>+cZO{^A_A>f}bMOz`2bf&k1b!~*mhPzLYY)rDK2 zqui|~Mx}ilU!UNk)UHoLUz&(peIlN?gHgknxwB+{ZvDt>wQtb72u<(J{B`t-Nj@TY zSflh>4m6{0eODLQ9?G9=T0Cqvbw152mcmb&h*tu;{fKK|zSY&U?z*Pe{_W-%)#j}^ zxN=ZO5Y)wg`0NiX8Z|aI;&o!3U-Js=#eY`4rD6y-9zlwy1B!<;Tcwh zMzmb>iBDN}Ib{%2P|Nv(s9^m0!+gmKz_A-dzdq4juhy$&K&4Un`W0*^M(7g@- zxH5#P@Jb-9Zuf=RoP@JoC3z)MQzG-I4DO{WMV$X(?oK!dzJJj~5wvnJnS*^W+Wg1E zJPc+ID#|Hi;r3*h_Pr9u?9LPOcO8f|x;=vhlv|QdE|2urN%U4dfWd3Ir_cX@1U#s- zI?c!Ee172*g;K`=J4C{>7`Gi#KreR$k*R%Ol2btI5I|(emwx9TCRh10$o}K*EmTrQAYca;k#ebRReIDg0GE( zl>z02@2TS0m^gv0HOg9rzzY6wgk-UX7cB>hgu)0sD4(+Xueh5VI~T;*IAjq>!mxhw|u zZ%$j*?9(OhMk!6Wf27R}=l;&4ea=zk^3#wSJMkj8>&a6-=9kM~z67AYkP;X_ewD(` znVz`k#0xiE<|H+_h-~KXq!GHLe_SIAd3S3<#c!vcyF|kry#1*ExSO!-tv6Y8!JTl$ z%j8!{ZnZeu8Tw2fE};EGuQP=n#qVLRFQrfwIuOAPfgQa+{{4Sw`to?F{_p=vmMl%$ z#y*yilr7mA5>i=HiWpf!w(PqJNfJXU6efGJh3w1NDYEa|*muSl#;o`Lyg%Q^@6Y+; zKIYz;bIRDOuakK-mT_$A_BkUjbS=F0BdA+~h)W><7$;5lw5ek_|}+wa`Jwu(5+9 z%slt7UKlB|-CGXW3Ih#>nXy}QY@z0iBt|sgGidv8svcY=fch{n#n~biXSwTF{py69 zFYr2V4GHoD<^xVK)?aGG6nT(3)}8c3BmfW14m(BgL=6}{-hGPv2lCg205S%Y zX#GdhaaNofuR!(KL(mO=P@3-%N`w?~RbDBBr~&tzZ1l}=8%DI{jX>=Fjy@`;V5S53 z_UXdNv0zr1dV=k%M+&9(OEE;FG8-AZx<@$e(rEV6|{3C_M{A$DJakcuVc;v-zykttPw@+(- z6}x2!-cqgGRApwJR>mT;(Gf`UAi`M;DYNY96q82U{|b1SKTxNE*Mh+ z{f8U8uMV_%S%3)AmUMcU<4V4x0AWwh{rSaA6qv8JSw`8YgcN4#(37e$1K#e!gzVB# z0=QZY4sIIJguvryOT{A@E7`y#*dZ6@dpWS%X{6e;JW46}4Ungs!Cdo3+n}}jxl#QN z!r>+476B@+0-}MvZYt@8rqpa}wf1$@VvH4xkv^gacV9%k4+t$Gfo#&q$paHKsF+s@ ztYJeIdo*1abk;z^1-P0zg&VC%hheGdoLKEKcx$0(1_nI@`y5C@5)|`2D9P9gf`i~9 zt$ooSAVG{!=Ws{rxGqR5aux#j2%08@Jr9~T@@(urgsJ1Ag7gDm&T2F=7z@(+9zhxa zKQ$0d^9&yA_Gk){2KsL8SHnGe&X#gEreKd~lH$T99ZlJJn?{pXDTNIdV)tGF^XUEjVTU>1WaHLI)wxs8OWV_?jd#|1c^xM=rc2YL47 zJ+nPd^8P43{EF@1$LFQs828%=Y^x{z$D8thA>1#tv#zTYS^7w}@cH5&wzmi#m0oe*~4!+|@m)b0^`7 zu$Gkm=}S5~PkcH;|Lz9Y<@uUh4S$s>d2T+=*v2CxF2it&wdTsD#P1&yb6&G@Y0igY z%^#_&d%x&I0>RQpfL>j#V_kjS&!&>ij9pvcjMMYqeE)1a!j&O8)lM9#adZ+e{_3wj zWS_k`L;tzE8RDh}D=Y3$W#Gq=jf?(*-ml}utv8EZRZ`c> zl-{L7(@X^8FfrTcEz*IGYWm(=JN(3|#SLLt<;qfAMI~61QO|&&eGnOvBAx4e^>MhE z+dpqVzOu=Or~}Qj3`2gq#nFf91jW+>nZ{mo9qBIpl`Q#mHf$zCAw!rKc;6$97C8E$ zr}#lzrWv|)(Dmi@9n(*GI?FL3*ktdT-GP2gV z;=3`6rkaLQ^bcKi|0OLj$qzM5ZAIBvm z-wR3jy?ar)c0~Mgf?P026KSi#qYjOR-#3gHoCGfWfuHG&O`F?3cBP3~hSpu;yu6mg zq-HYCqtq?@i4u*Rzn|=JM0j*u_851;k}%<_}xiQ1oh{}L1jNe`JCwri)SQPN^^V`l2c>N27NKcJ`c z?Z3ZNEMzWc{>^z)#`Yw9r+4CY?L(L97w*Y(58gT~JyOz1oELrSHp{{1%h>JuLh$+5 z56KQ)j+%*heLvmz_oV|(_M1g^m3m38V(8@&?neglnlUhkwKE}d=Mnr@AYpw|t%X*lH_%n3eYd!T$&~hpRH;YD-$^?I~VTrwNTdN$9@2j;t`BOpbp%2VAftWym@I!D}oL*^3@LECp$6cJr`fW{lX3e#6yX zNc;o^0=|5|cS7y!%e|Uu0t@ZEaThLiDq2bcJ{esBM zb8#!i_a^@^8q(gAm@zcQWE=w7buC(&x(fb!u!Nj?f$2~Nqk|RdFIO|%zCm^SF59@w zg+~5PI0US3<}3h)|{N<>#F8&u%=Q`(7yism(*J=}^~d^vqfc7b*m(C+cOPxcm@hNv35sl7gLz!}T)m4FZ%J}W0vHjC__z@6Zs=Kz$(o3GoFxHBVv!J0i^ z7-I7LmUNeHxe!-qGfgj%9s^`&Azhuwi2YOF&;Pk`nL6n|g;wo83z?5~b#af!IM>nI zo07DcJ$b@+I%pR%27ALk1@G;&ijZIa6!;;Kav3t>&tlkfcQouV*!DL?yOTS^ zEI!vewdM<6xbM#3IUCwLJve3-Z@hbb7Jz)%9Fcao_9RtjZ}WbKvW=kriL07&OAO3N z1E}yjPTD?l`|!3$rEz#5+^**f1UV;lRzltUwCTM-oM zmzjgvCg=)W^EUgK8^e5<`pLB-;HW%q|0<EHh@LnN=NcZ|{MrQIsXmnmPjP)N^7 z7J@!pNre6nFgg`_5ls;5M&5=~cDu7$+m1rBNIpQ4@q9nlIr)>uU0YSWXFqlCtn?qB zZ44b!vxKvq!H?_H&N0xBon?}(Lmdham%WiGz+o-e<;18F8oaOqAJ1;ManeknysvJ9 z^P6k@c{h)3%t@GSAU=3*%%T6V(SJgMKQ6Z1(ybxT;!sO+kwHW;50?@Ac(GoP1ddOHyc7|BDi|_uwZZ6twEI=*MNIa; zwoBV{8}6G{lXI(>yu7hG?QTG;`HKu)A;jPgx9@j_?UN27#Nh@A-`ztb`kd1?Pw2Ei z!0|5Sb&u~jxFY}esgnQ<6MGF^?~y6ADQpq z>vsp-8Xqyz9B6HRSHDZYztv1bWvB7FNueGHS5<1i$De;50SkDF=INY&n7ZXywBSH| zBH?-rHf~W-i7(#6-$_f{gse1?5mScGG6{mJDc|_HVUJ4S?~%>36Gj_*@E-mU(~G6G zwlBOcUn>8ANLmSEL+_MF);7RzhJDChw$)%^y~namx-J~E94dRyr;lz#6m@`8I!bO( z@E+`s^#u*L;*pRha)Cf0^H1iy4u->s`QIPRb{r2ii6;~sXqiT5c)d?cdYZIE=rLXY zV4C0zL1~^*J{@A2{9bJ0;JdH_b%NSbtjFdf%g)LjS{8@7tRXDCf6s+);^dWcF@KvZ zPPoex`)!{ko%ivvxPq(BaC|*zCLY3?^&rGvt=I03E<5LkJZMy~RhCjWz*1EpMiMG) zD!35N7{XXIV36vRG#suKA|d7lX(F}gJ$|<(BE63sF8F}LSR6atFEX&tS%)+!S=@7s z?GJOh@~r6>W>NYR=q8+EX{kpFE{sz&Kw;gZ$D(CPLhp=1wsH{sC;$uH}$S4F06qI)v9p{YWX|9;}kP(ILxP|+x)Y+W#G#1 zZvyZpBWUm(fm?%hItR9xE#wcR!md5dJT}lsBM-xl@su-~-(MEyoao$#f$~v1=h%X2 zrrYAy)YXH7#-m&8Q}5?IY6tV2;c7v&zar@54BB6)=q&xo{I7ss)wxdrLY{G-&E3Y( zVZJ8$=)MvI!B~ zTxx^x-{_`zOYi2@U$paY$%QWQdqZ=UJl7--KgB@3G!7}%xsd|Y0L^#=vI;rzxXpX{ zZ;z)IFSJ>83%dc=z#!vY>-pK+`C4?AjzX#&<7u4U_BtWGZwr2bMQCfM-+i9wuK5Us zboB^iMw9&Pb0f*(U$-eETXSDB%Dd*iK1xHbP^gP-@pq-E&8ow}@S}o~t4$W647(F_ zEfuF~_3(*F<=>rub$jrYWtja-MX}oZ%p)BScQKq7zQ-~AIc6@5$7HCU4jqATvLxP z9qyK2ec>@qKCbTz@)z4Cte}$_N@6X8Ubsl$9Dx8B1Mj1vK zh8Iqvg7UK~DwF^FbZ{b@m9_+w^7z@rGJZ&ieDwI+?9=eGS*5G)@ZG77zG9nR2d;pE z)RX5YU$w(u2o23gK3+^h>;J56Pm$V4XcPsfsdY@tpZBls+Frg}fn0Z3>*w8_0 zCT8+odXI{gdfWI#9!mr~eRF&GwTSE}j^&&L3v0xS!8m@sG0m+-ONMwx4IO+B$y&T{ zNGXKO^5lKS281ReX4-)k0gfi^vP}h)lV9O?6SVJV{SA?q$(LP10=dZ_LYgCSo55o= z23Hz~aN$eVH2bk11xp0ns}NZ~iDx+*dDvM`W+{t(E4NQAklL}hKH5_Ho6wD4;@gg} z6`O3EX#!Fr8(YMbc$-pWqnJh z;tODsCr+s2$`oybIgjIPh6hG_HUH63sB6$NXLMdRuyZShkP5b0iZ#IrNZ|0_@k32S z4X2J_a=%yvy^5!4LcKH5;QK?|CvUL&jajO|Vq59x=x+BDc10vX$hKzOK<=&)8?~zuBiHVPz-3bdvY_Kx+9x_dnPa%cWd`6q)-; zjN{FUXU86JfN;C+DiWS=!bV-9A#4elo6%FVyA)XQ6p~G9O3K0$sNi<*#Y5;{L+__I zjV0=n_<8=Ai7WHPlE*vq=WLd0Ody$o^SMfX!dyjhw-#dgnHQH}5Z1MQQql|Oi->#K zlPhf0$q(2EYv`0ZqGQOlvZjBmFyT#pJfTAa_j5bP0z7xI%pT6`bZoCud>AdCS4I+J zm8ypMI&0oqO0s!baF&qE44WX+7;vY$kl_%1Zme+|A9v0zTayW+S+C*qeBiIr)&Jgu zhYKf5F5h|tF@rq#%*=Ic6ZZUd#K%)#8gLZ`ci>9QHyK%!jN=i|cxiUac72K1`e#uc zHb2hYm1okM<09qtEtNPWU4uW#aUW2+HekwShz0AMRdpdc%&k zzslJJLUdl8pQ+E(NV$eP*K&1A#ymtRGVIg%Y6M7_@L^LZF~YipEvCCUP`Gyk7H3`W z*>$4*t$c@X5+|kAouWSX0xxWRCMauICYRE0#Hp~Zv!#!WRJJ~FufgC~hmte?bwyb^ zUqoU_uk>R3rAD0lhA+n#Ppye+0MiByOOkziU77gvGHW7-swf!J}g(`93UQqcF%fgt#2P>qQF|{m?C~gjxU9RzcS$farMA zv`_bL@Zrn4jWNriTKJNAaID!P6d1R;xYZw54d}w;7xWBBTVZr%`Teuq{lK*9P$dE| zRN)J)(t#9TC_-v`FK?rP_R;EbY*POgT0|jsHFxEUm3uGWna}?yssV#s{)rYZmoU3z z=?97#0Wa(DE+p9_tYmzE)Pz;(<_Ii@@u@no9jP-?|EEjGn{F85`fxd5}vN?2V!u(Y=Pfb!}zAMx0mVt<=y(k3RTgUg`#e zO3PC#X8jQn2^T-?X%W%pbA+$GQj#=x+9kS=)r}Aezw;^{YUwFBZ~F`5Pn&dHlwNt! z6Tm&_f+WS*lDMnQ?}6E=#W%pC#n>`|pa0>mb_TULm;Y5fDv*h@u2i47#(%8XBi^K% zz{oB|-yvUdfuo=u8vBzXtIXIeM$7>eB(&}|3twRsQf_*ja2|cH<(r7OS;1G~&B*ad zsmFX=?~E0vrb!>O6t3Lycr3%HO)4Mst=_&x-%NhLtQD@}Ex4?p8lO535-yXrKhg%u z;1NCNu|;oB803C`^Z8HT419D1=Jh81TDI-1Cp9-B`n{1JK0VcI{TUu!Kb)il9G~B| zDj`6)NO4yv2kObk_v8UZz#rH!3PReLC%`WJAyU(J_U|-$0Q?31j7)k-=w<(Qj(-?7 zBstb+=bxg&DeEcw#=~LvX$_uRKDw=W;r~PdjS!U0@p!kvit5qYksn(^T46alS-*YO z;wC`UXi=~X6q4O5)y9<8#z3D=#rQiFSC6TPkkG0ts&2Za^tR0C?2-AcI)>?>K9KG| zc>`b4=uQEmpz{$^9#=eQg-M=wQ6hdfiF!MyGA4n5XSrS8sb6=4*Ql?N%xw(3`aJwE4Y&fk$h1?EwfTNTVfs|)7P6G(-BKSW zjQjaP5!~AiC_GXJ{KYS=AxO>Jqt1UAqT`<`0y4t!39%$SL;On|08uXkl{|=2p28>Z zk9v}R>jTnzqWyIAP)_o_X@bWLMf=vxe{f#}iOE4u&5#RePi-vS{CNaT-E)9*JxvBp zzVmI%C0k1CFihsC9{<@EDnx($O?26DW;REr@SZvoNm|dJ`in=OM*OtG>;=sCpc7Rs-TU{Yhex6g?yE#T=#y($&aLdI$C%LyTG-$tNkT+ z+``Avw%JtLGl32M>gom3kgmYc1HJC6#xIh#OiZrZn7uxKak(5F4*Sxur^SYTNki8C z(59Q7{57&Pe{FxD3`Wbb;Az%t{*3Q%3i{FWyZ^OO-g}(g%_ABv5}WjVKnauq^kB5# ziNyYl{bHZ|CZ1_HfS}F!pNFm7xB!3fYfHovA4kYc2^2MY=)TuOK9Zj)>pq(I9hNR> z6tnW%`D}P>czSbW4IAT_F?Pv>z84C46Jy_6ilY(87&3)-Lxjsp6w|Q#)#s+v?o~3` zf0MlCH+c}S@^-7l#W8LgId4Y}PxPZ~T*3@=@h-!Tz^Bl-u(UU(gu}VEDp0y<^Sw{U z;dtfetWJNy-KJUMjgS)P=KC7Gowa>@1okV=F&EZCYMPdau6M8q0vv^B~zY+&m|j zRD?VZtfhmLVu88Bo!@Nhmc*bhTSlc-3iyWm$h@N~8k;}z^DEEJh%_#cAbItBnMqy% zqaO@dg#>mt^VKTM(xxp()_#E_1U(pZmC?G7^ZqZ+CFHz&ww;al@|Q764`k**^dD#4 zeQ$3$FqxzVMsFi7`=24^1`|~O$>ayTyhIA6>GGx{%K-L2#=b5Hf7bI+1`1d7%E!u4J_rNnFwpi?-s>d#5tJxx>Yxc-F6#x>CD)+W4>CN zR=xFV+F@5RZlKwW81;y@E~NW-GR#ze-`zfhv-ns%?pv9o8+saR@jXHRS!VkTC#kzw zdcJ_0dU$O8 z?Dq|mSv`c2Z7ACXSVNHhcRa6aA+|gX*(9fem=0Tn^l_>w^eUexdVi>wSY_EsdZFZ4 zaR`%>(F34}PK^`Sn%^MPB184P-x%iI&S_3Qx0Mx7f$#Mkg1f=HZ8`vU!M|RLhzV^je)1Jcf>teBp_YQXWwmuiFDY_$7~tB(O?bGf|{>5 zL}|Y(*PJmi@yp%i5YktN@SSm3)wAO;Tpzwm4v+xK6!iHWGH*|Z(-o0;ihi51JrF{ zTJT9W>}J!{vx|3HO&?t}bG&4yCcTG`UKk_sdc!q7NdQ-j)wX85D@$nNf6{Zg#Ufl3`Tg z)YQZ_(4v&9s4q$*ehTiDc1ekbpjf%g&Y`(zg@SU8@~QsQCYJ!yQo$51GaXrl)1~k@N8a)6GRaAf$~`7SHqof~=?kkPo4TA-dV3HN zy*aCdKRbz=?Iv9mX#)GT*x)`%I-$$K)+Cb)JnxYExvvWt^-nJqlXmcm%<=K?*{T}4 zQLo{CD(t2a6aaAb*r`Q|M~K!FC|P9*IeE*xvgyGCAq@qJA~Ro6pfH0oXngw{z2DOj zpwd*mz{ntJmW+eQ;o%+#(lB#$6$a~9Tl*NxT6ZZ>Z>)+&ksP{0Kts&|HdxiVSQ8c} z5xkqehQ!q`__d^4`^jnXRZ&R<+sXdY#=6}7W$*q@>egP00{!)uo6>yr*1htc>q*3! zFmWegh>->@vQ}}%%lp2$*=}dLyDC3@`-hZSpWfSI>dx^@ZQ~2C2dm{kix=ISdMjsB z$((jUUwpheOS zc9K?Jqn9?$NK@*4=J4VhPZ@(3yrLMk{z(}Wu%uU|ldwh08$Igcx{Ck*;%iv2F zfwwcZh)0Z$VUO>)(aF`@UTfGr#{IUw9;y)jng zt$phN1T-Xmvs*CE#`zY)rlT z-y%(V4SBWlZl4(>9qA^{{trIk%qn~*d~zKT559iV370z||5qmQbII+5AEemRfStE8 z%hEO~Jej>CQxFB;OgnKx=+W7nmwytB=Lxia`a?GE8;ly%dl?$ww^%{jfK7P*^PaHN zyT1zE;8!k!y0kTd^fV;2H5&CKCq0x<>HwF#`@6n<98?;B&PiSFIyy9>4?pvZ@@hT3 zgqZifQCtx8J;(sxp zo}$c+$>3k9tWW7n$)EkP?)7tr(a_+!4g0z0>+}_!6d1TzE_FX>Tco*-^sKKUb% zqk3;}gsO;-nBODA-#6}Vx-|D!SR%(;MEXKwP?-dm-ZoO2+74bk7lQ1#^u@^1qb_y# zcm2E_+5p|wbtizc_}e@GWnMt1W>Db`MzKkE7OofesSEVN3|y{Dafw%Z89hh#|30Vw z)Jy!C@v_yADj*&$A~|&twuH1EA$5;q(yCN9xt$4ZXYV!a9dC0=OK1ukJ37p0+d|%? zaenbD%~I$DTZaBrg2yq(KbNOc2ljT5O93Jo&G9wuSC~E6mDLlPywgjz`>F)U_Zmerjd8zLLua(|1K5nJB2dG}E(1(_M|1?6;&x z@9?OA51xlZ!WmmpbfZ?|^6z-)GBe)!0}r(mdsNtb#F@pCl(+y+l&0C*F;m?Fc;;eg z5aNJ1HGGlITM6%kt4#DoFCn@UZ}r3dWIGW$F5|$O%1ZF!t%4XZG9Q8^jmm}7cb*R0 zjG7*59yZS$YBmZg`FG_Ji-K$h7^-BmQ_JF+pRh`vo0Vu5i4^9(xQEk#XzYN#qfRXm z!mM%$=uGCG%T8Bazsqgpe-L+3AU89|(I{9}+n8DJpMw8@@YuMLeii%Hc5&q;ZB4pX z=asgEdW(Xq_+0D`6uy#pTl)Qww7ONuwaS5>y-DcbNa<~VPV<7iZRGO`7oDri8vQ{G z2>xif4YpkVkY~%>?c#+h;o8pdL-PfXmG649k!v28Pu$EK;X2#oyvI+vn z$Mhuva^3TJ*!8Hn3?HDlc5|~4SEUL=RRP?n??XURKaB2m9V6B-BiA#yY zXcR%Z@ig=z?jt>a{r=FPZS5+{ZdM$d)Cw8Xb(X<_-s* zwz}kRbOgJrpa^5)XDUXqATDlfm$95esxSIg@D|T}%{AF5t`rVr7D=*(T+0*c{UN-R z)c^2@c)=5}8@@r2Y&7K#D){{i`MeML^OFVc>S1~OHL6owd?8bnauccHy8F4etMI_K zF!SetUX%n1JkeD5I?~H#=*3?h#FJsoB%ToaS8^+-VAq%bk}{KOw-uT8?0}!bN2Hqbw!UbMO~_HYYn;!=7i3;j%fds+sm(kjft@D2;o*U81n$M_=8Pti<@J<|X@|WS#4K$~ z9){9J2mk4(v@<(PF7%CXj9EMWvf>B>&eX?ZC1dopnlcVC$yV*k3g9RhK1U=Wp!%BC zDMH)he}oXrB<*WfwISS8%%636_ew{e!?*IxUH^3s{+|!u1#u6MsV4W- z*BIUiVL7 zfmVd)98HMr`}ye+T~hcy)hlzd69)aNEU*h@$zEB1R!^$i0P9}C{H{x@*xhLj75wd` zM*+;wQk$Y;k;s-M-Ja|JVi_gU@kxZ?9b`>~y~$JhD40SDLB9fUv230m^me=mrLR?o z+uEL%(G)T5Uey&5y#~kfAH`K*u;&+pSy0LcsWpO1L1m7WpUn+b;e62IpgznYv(yM* zIn{cju&W8m6$g?rcK^8c?rFdbGr7c@U1kxQGnfBIj2NMTlAoo`hlp%JD z%oVNCU^-!h_(VYOgj6F^NhNX1-xQDc9Tka=+aJ=4;YjKiB)>B9HmD1+ zmgW!F+k`d!S&c!2uA2WeM+9D?Js#t)Tc+-rV-l?Qh)A|XKf{{2L(IRip9Q5FFylUA zb;|qqG*nPZ)Z()=aBRs0^xiUC>k&(|Nm%tHgw?1e6w}cmc@ef%&|#Oy*XbWuI=Ix9 z@38U@!UnlO8@hRR&9=-N>8Aqk>DW=|(97z?bZva}c9)idyoU31sqWtQMrmMw)tWlm z$>3{QQhP(iNqFI$uVW9X$Wlbk?46ORKiyN^>FjQv=Axj+6yGrGo2_{GioUpphIcp3g{ehqjdCF?GE36CtbOx9szF=Nyd<^sEM=13Ue3zh22lY3sIBrQ3<=h3{`d_2t(=tr|WQA zWewR03J2-Pt03-C_`?53+ARAWY8)@=MsXFX%3oHMrgdTrX z<5ta^AwqhkkK=oa3_Z3Ac&bwh8z2a@95XGf7wz`7z3)If3O=9RB!Lkt5-FHFmnY_L$;-2&#>frqq~(CJO(=I#sW)>#*)Dtk?(|K7`3Bfw?2 z!GxA+ozCZ-Bxd1OMrrT&55GLJF9R&1PCIs!ysrY?(4GMU-?_SJFUdMA3Eu0un!26r z(xx>_hirMoKt}J`^pnmGw~9aPr}YE*4bJ;ZN+IRH_$A)R1G+<;|2Q-xmv^Qh!cJM8 zz{&x13`D-BF~)=!OLbN?-+K4n2qKm!_eH20i3(fWC5^W!`omf#~ zL9?^?yy<5GYfCOSO?@}HmwxN-;N?X#UQ$aNAeR`;yja0SVjZ}B@{RFD<`tdQlb=ly z6JktBvdVvJ=%Vm$+m+14Z<4#m+@6M@kKNe-eDk~ZtE1VW8z<*3`FC)P=b}RCE*k=k z>gWd&Nl%Lb0g;ySRns(+)=K`QLrh>=3X7kI-vj;F&`3gBVcxP{6IpX zo?JcS)sv_GD&Jl)J#^4$=#M&zZL6=8dlhVZH7<&4xPAeas=iQ= zefkcx?`jNs8eBGSx_YCri|D*Diw|x9jgfRbY$PhCq3UJ3V<)(T1~0x6QI@*J;}?## z0>5FMT%^U9Z@E_Ye6tP}WAUWIdL+SUDYn~!v(mih@FiU%D>2Uge6 zF*VyZG;RK6c8zEYQ!3`@t@yj5VWA5qHp<(M4y`1YfiQ_)jcmzf#VMn0FPb-kHH2gV zz}{n?g~r35Itt%izi{>1sraJ)FlYjO{sPh&BcI*kbG+BM$Q85XvxH5=ORvE`T?Ia9 z3<2wo&Pa#`$sS6R5E@Hm8iUtH?97t&EdIxXdAJn*L?u73tulL*0pbI(QB{Pt>&Edv z?f4O#U^|$|cHpQ*=M38e=cS6p&SEXr@1-p+2Fl7YSb;JvY&!I zb$qMkR(F%;p_IKcg@+eWUYaonudm(Nkld@aU~Y<)DsR1Wqh12e;8BDnO2OesB$my%+w?c24Mqwb}7^c(qUkgU`c(@&${nkIn;N z8S=1E@71gL`K;O-8D=~5vc5BV$hWNlhy97;!~=Ozjj0m(U%>vUFvMT)dS*0jh3r3g zDd0`e)lAGiE1D3{3ffBSMc-MSqCqay(Hp7K{))(}_yvAzb8@Gh8|quwH9NRS~6 zG5A1>gbtDiP3C88t(d*)1@#+hvfKF%=6QKRW6v1W%UbYZbfNa2j|W+IE$_yV1^Qy^ zZrxTFFnWaikeP;*;|s|&XMX*^RNTg( z*71K6rE8E^kwgQFmi*)jj+yvK=9Z|hiECCo$Y^`zQ$K7VfhEK?c&Mo67&reO=C|&xrO2`#)d+Ny7cA?3orw4nGt3LpDHlatV`UBRSL5Ny zwLdmMPh>1S{Rg19u#W5u=+JCF=AGHo)_l*p@XWsDn$}O!K|B4}j1@tZ=>w04q$3J9 zU&53(Bt>u{!Fyj_a>aM59DQKVN-9+WktsRxE1lEG_ONUiw08NY^Lk1F@=a&2q)n-61ZL+gOKhZo%ZzdUBr6 z;*k-$8_b(;@;QtfU+U}iAZ|`C3h^$e8aAD{OcL6<@pCu!h=rKjqAa{x1?pd0!=6O( zhyHFTM9C@WDO6_WlzMl~41UMs*P47FwEm0Qri(5U&&Ca^>0+S^!Qw{+GCZjch7jQU zNCKVV)S&(?X)+mO)-IO5yI-=gh4jApWA3?f`FhB9&!C}Ue&rET19lFxR0 z?AsZz40820XEqF7!I#=yTWXPg1c}mxp4s`r8xe;g)c&a4Q<_JzMr{s==|rtQ>y6TN zyYU~hs@EAZ!WQ8j6!3EGC$p}4bFo5|D`PFWV^37t&)t3Oo$mFwxu>sG8ZAjj1!8nl za^6L$hCY+eNz=?3xN|*?^)?#i)c_s_THAg5a7! zzy*uJ2YI&K*-A;LF0n?@%loD@tLjDm=!J+7CRj&w^2P;Ey!&9Jf%?FNAMNWqEiS{G z-v*wvz*k5DJhW2fVU1UpWe(%O3!cwyJ4-*@CMp}XFLm_Dqo7?yJgLarFJYYvE{~~Z z%UxQel}UFMd@pV~JtF;Wq(Am%G41fA=H)Y3C>z3l0u_WMHy9p~{3l8j;7pna?XBv2K|`XDKkwg~(9 zZiCd#j{cW(gG9M+FnH-|9dZ$-DBcfpQe#{TZh__Wi^fLjF%Az^oZ!r+k^11bC!Kn? zsK_+BS9KTCR6OEST$eaZi=(C``A4_xrFGg1S{uk`wEmqZ4t{VBaeC;999_<2375h& zc|ut{cbcfmww_JO{m2-LY=eiJ68V`Mw@;l{MlN_dt}<^Phf|wU|#2Z6onqUvK`zwf}x`&4l~?gJg+c znuCAa7rd=nyEv2&>Mdn%YIwGW#Vowms9DXM=@_@0VIc8nRlML-1<0a5R2wM_a}X{BG#DUI?$1L;6q zSqv(}Z+L+K`7Kd(j^H66rMa*E=4LJfUg%vJ5lTSnJi9pM!aQT3q&?-RH{bUPaBJKU zqj23p{~Qk?F>L7I!g!k+LiBKC|NhXUoFnAIO=m0=^Zh8I-y0I-WnniuI<;jK2pom0 z?AT#RFQ=Apph74$+R;|Ob8(sI9SBgKI_Aux0u3p>f9U>eCX8@Dp~QH)q;&P|phNEr zY;3Q;tN`U_a*o{`UM%F?vKZcH9DCgB4xU+{tQ?T+GS~#>{@nWdICLO#C^jSPj&zgN z4^KNKk1}AN$2W}TXJ(c68>4CPbTj;81{ou~on{~3i*;UmK|dCk2)y+_PZYJT3GF~O zFe5fQ(<9W^Kpk`I3_p53MjsAzID{_hMsfs#8!b2}I~X^G?Kk@Q$A^x|Sp^^SdZi<$lO9k5?Fw#7{22 zxJ88enIbzKqt2W*FD%oXT|{W;{_`tZxcdV0SzAvP5Irs!hbQhboZVJ4ofNHNL*Mzr zyw^k5E7GA!vJb1>rZl+d&@^g)$ghzV9=Inv$)usLETH2eNjne}q#Fce zAl+Sp)ClQ~94ziI<(YuB~UKIcB?ea`!Jeml&XQ?XyAuJE>C?y2Z9Dcq?{ zK(j0Gv)%LM1i{)pcOz}<5zo`k6!W=?F4({W*v_??d)&ME)}wtAdbEnHU{IvJ7nMl$ zk~{Oa{{3WdkhR%5)V+%bJ6#rI1RHz|csCti&(c=??eeA@2rvqa`QyH^>1N)AYM9r6 z*S{b#&3eW(Cp~HKcIARH`cmoedl{>qw}4J>N)(k;v^)%4_3+;v|3CqUy*9pWe+SWp z-|YIFr=v%47-9o*-ULDjHbJez`%fD!lv1!d%IXx|)K@I#gU-H*%!jdu~CfI56@xYGuQnN1K@zTI&Uo%t< zV=$-Kc1wx$;<`UaYj@D{0P&e$lY4zTwUvBD3(-8>Z#{x>xKQ}?tf%AcE^Nj0b2NR1 z7{e(+6M7!B>KXs|i2*$D@2BdlgJU(II#!3@muXNA*hB_AvwD~MIBqh01R~)(19_$Z zem+QLD1p-PbCL%{GlX&K)SU5qlib;`kzYA=0KWa~^nzd`hG&v`mXn>Z06e((cp0R( z@#m{E;aF^Iyrd!}XCo?9m>?el5qRz$gM*F`<;5p5V5IV~6A#_fD7oG$8hTWmg^fCW zUJ?9bgCI&=LFDka8eDX`Es;Ng!h&wt{W*nAe3^L47*9~HeHyz!hL~7yb!-+m4(U3D zrPKjDrU}w^Qat%^9)AvM8!L`U#Y%J8euo~!StFQ&T zSxWwcCFpxTxsm)F6qA+>*vHuweF4i5TY77h`J>nG7q%Yb!aC%iJON<0eYII1|vXE9@qCI-xE^Js3a9RY1NAjGrm zge&aADxk;D{H}nDU#j-x03~HDuP^?VEEdIjzB|ZhCNTMZLmA-@X}g(24>Z*=dLjYD@=L_*IcX)K5T-qVo*mH}k5B|cju%JXN%)mKU2Z|{W|n9z28CbAa+=%2 z^u*yHEfl4n3LPL*V_Usz*RZk`kb>|cr3=pW))VPkC%zPo`<&%POFN+zccXn^k=fJ6 z(}|RQZPC%}DSZcj{&uB-R8h#=C^!qQY{wm^k&iI-?W#H$s#qw0)PZ?9h6Ag9~K zA#!`Yr^$@q`cN_4!|FAWKi+1mb_Fgmzzz5tmQwpO*WqaKKOgRc@lgYI-G%%7fT@US z{ZjFX#Xn;>AOA9)nd!flCR;$ryi&utoaZ!up(zNCn;df(gtR&u3?iW9xI!i;r!71vQ>LH(;s;;k5lRZ|*A z_D%tFI^31Cz`p!SJ^cH_ugtGG&O#o%xW>&iVQv3ciE{H1@D|he?QZlBi7TzTRcva( zvlTkGdk=z5LM0?xvsWWkP(Zcmk6pp@^nYI2#=kSkPu`C9`!D?teo=LF^*+};AHY8r zrXU|YNNR>#J>V3hTUq?lDrH?O83!Eo+@X8tnCM3%M{3H%0+m;k5B=6sGcylcvA;aP zfCeLO%lhffSHUYw?}CXK#<~MME^^{`N!g;fWyrXkzZU+;Gtm4u!9*>t2Q+GMKGL$X z$NJN+x+IMAO)KFu(^fh7n({Dl=oJeI0tB3qulT&m4<;$fg-kzJ6%Tjxu~wS&fRU<> zEt{F?N3qMVzY@;@;~?Yi#r(f7bK;=62^i;z#`Cj%PJ-#G&5IfXbtIBFOuBiWnD#j9 zhIHLg=%>F>yPmR2sVd6A^Ny$RfU0-LgK*y`)SXt7x{$f+p-vU`W!9k-QN2f>Dz041;|vdtqMhvZV$fnrunG0gv=#Het8JU) ztIL_YcGw7Vj*u=0CoN(ECErdPBJ*P3gn1rpe)WAd^Si-|X2~A(!$w*Mln8$kd_Vv_ z2(nIh%h+J$?pgMXpm*YgZQtAi_}=(iHEr6Jf`n3$H!3 z&kS^+XTM3iD63LUG?D>U?YyDLbKQU%APxb$xgxA2_LBg)3c0G_x_W?buVc`~Rp0N`)}W_1T$Bon=FUGl&yz2`OT)Am zH*?(2y+R(v$bl88`mPRGbKd&?-wd9r`tr?VAD{aF{*P^^HW%%7toxn%vvmPH$k!gH zx^{OTWGU_pyNzW`%?&o&PHNvsIk`<1U>{&R7sgBI8m94 zH(i%~Dyw$50rpQeh6mhkeR*GcB2*6L<6-79+w?NPDQT#qb~;^c<+BP5W;1J9}j-0iX4WJ+3kbo?di0 z8|u${{+J?xJD_ppu$J(>chUilP0RTRJ?WtS=d4Szz4TFU)h}eXmZ124AB-3>i7{Z| zb0sa~%Kl|FjeKl=t#>!nWeFx?FN%?f5evtsx&W|R3wWp0C zKN0V~aRx*|dbOPm{i~17?>v-D=n2NnFJje&PU6MG(w1 zsZXdxn%0RVbhnNG1<8jSm86|nbFZC;+# zzA3W)UHkCo4x+);kPRy})$K<}zCfrlSl=m%{3nuZVcJ@b_*Iuiuv=R`d#Ft z5?fRG8sLzeu$bXObocoi{1Y^mi~rFmP>-61cjDiV(=-AwKU~h%=FGFy@*n5jK3Bk^ zujluWdRglJ;hoYW9zXg-U4JUh)F1hOA{HW?y@|kS!u*7YIW$q~=Qdr7=o?q->kBgO ztt*=27jEU@W#n!>LccbFmd|hd?qhBHjV25l{v>%ctxq5CEG=d}v3gGRjxr4NcqPXZ zcToM*>g^Tlf)%`YnpC=@4QbN?a{T1r;;E-0r%iA`6H!^YuzA0g2gKf<-DZ=k|@tmYPr9zNnpa*_z2lffuIKZ){e3y+S+DEGHpS*cq)%Cj|QDG1`0#4T>f^Plu zgbn)sCmg?f{{kqcQRT0s5BnXs2QO!EYJBcyuVeC7ew*&Ke)`*5a^|YlT!GN}Mj93t z1uf=vo|XqZpEPbG72{UbN-`~%k zQ>kKC9*}@;Okl1B&_>M{RFX%E5~t*pOa?(tkld^P`$X@r;E&``#+`P*c?qIqH)O$r zurvrWn8zF);0L50sDTf>UcF(0&t0%=wV;f8*Qz$5CrCrz&*K4vj5eS?3iBRLsZ-tm zQi+7IhMhn*hbVlBm}AU@I0B{$_qqFYgs3J(%u~%arGpmnM0583@SX4L8}wEC9)Uom zbEDZiKlYe@5+<_k!({A(@H8KyVATM}IFXCmTwXR&$#YDSwTPXJco4 zzdZ}uOt!z_0^gP}wy#5p{rEm<@H6xvfF7Z+T2h9B6`Dj4$qjz8FWFFSngP<&NMS;KXKy3hDkA)E&0+CG05^AGQVZ-Jg zxBn29Qn%MOy6$cY&lUQ6tsNl@b}3C&fSxYUqYZ3Wh(L+A3ek&o$hcvuW^R6j%Uy6+ z`r=+%1Nz_u8%sRXc!b~bzPhVR9|E;~7_lQC^vHM>`$|fNgz$PTXOalCb;N#@xm&Oi zC>UT*H2KiCt{MNj|EL;Kcoj5hf(w^Ls{qkVsx{G@P#>Y=sg{4ga{1ekl4t*8GOS(l z82+7?xc+WNdC%o4QzkcqIN9?IyESh?CaxmA>-9Rz5_cSO)x8yjl4<9uG2fvKz2}@* zT5V$?+IjN0eqJM?-7MdvE2sIiAY`6^+@o6$z6j**7i5PgZVv{ZQbwzHI^Tydf7DB% z8Bb{;n|Fk;8^l0Mizk0o#$K{jGC0lGV7~VxZ8BOgNa+dQ$$zaBEl9&alr^`KG`jle z1lZkJDnuT|ACFbQrm|;L4*xihWW#bz|I7unJ^^OVH%;@)VdsP2cSd%n5l*3J5hAD1 z&(_KNuqq~7woI&ZJr2qAe7WHi#`DALTY*K-QSPmRuSF14S{7KQWMAhr*W5FLwp& zFQvzm@HetF$eA16ltJICtnT~^H2TprpE8nyr#=2Xyr*e2vZsL)W_s%bX!KsrzM|pZ zIl^K-(rS11dTHEhPslVm<{UKc76^Ng{-l*@ER?)#A(|W^fn}wkThmz1ZxhANG2u1? z#oIuv>CCiQ0`f*pg+Kov3*d&aB8}g2YVjy%zxZd?#%NTWoQ>nSG1-S-Uq=z^#?0W$ z%LAv)5=u-frVx~vNRKnO>U-(HS&o%!vR@E(GC|wL*u$Kbd&&`SivfEpXLy^)M(*X! zC8OW~%O;c&tP?jxOe$~1m~X`v=4Ah~5XhczHJxeYS$&-1lLZG7Mn2r=Rgcky^0!f7wn!!P_J>lxx)|i4wn-I zUU-S`x@zn(1+2>wizvZcVE#i0O74vedJ1wlKqiMmu>N5y<~l|y(!smBiC@VysLInM zOq|Qw&y?)6O&;=ss#jB|L(g@dlp#g!D<%YKuREH4Zwx<>d7naf-tf9N?+^NhPEdhl z_?u!UKJ0md{^8_*5;gmO7(2W47h)webWC2J8{IrSUSkDclw4oVt!WBOzFd@|%vADl zqDv6CAHi__5SrFE(AY)+kE2p`T^muTQlg={6B=u+I=d@3h#8R+H_@5vW=w{wsFL4_ zFP-RXb2=1M4z3q`@QKQe)^bidi5`q3DG9*UmFz=#EeqR8xPbNdna zFn{{YYM_fuaJw5q@*6yf0;yILuJn=J3_bzAWWYS}e_>xq7*jgu#kgo_+`D~Nrb{4E zmmJ^(U-2)xZEh3O&S1FwuT9^>jee6{fj&w@jX-#0Rq`}sz+EucD^YtDRP0Ri@_>Vj zf|fvWXI1uO>_i_$1WCEf8Iic^*TYRdf&Ny%M5aE)O#Yfh^ne0nS+V9Q{$tN?=`q2grr!SF%>3Lc`qR(#&(9@CS0G_PRKGvTl;`yo(agig$m~cjyd~sFWWM-rkFln=E?gZKjyRg zz)WVPbN2n5up~YA2RqCcBjVB2f=c0f26Xk4ES52iQZKmS;E!b(F+NB_gPl8y*Y_H@~ju*flvG z9EMPln3BxD#vO7e`PV{Gt5Xo$Ea;Hrw`mH|yrV1AmdT4?XCZ&d8|-tL+)hmTM6YIy zP4aS-?Wrjuj0U^v7nBrQ`2J+RZDLX7cj&WJ7psDv#Txy|+FJ zXu9|YQL}P`hUg5_ljZ$Q4s-tlXqr7}l`G0i*Sb8cg%^(;P9SUx1fadAIa-gIspE~G zW2^9?A5WSYZ(!d1J~*WNY_>HET}?KZ5xkEx(3l5Cr8)T91YGz^%OP`*%F#%?yTXYC z9*X(nJU8a$egbi(6SD+JBX``UJB|N(QgGzP&{j4IoI3r~ZBG)q3E4>b_V^C4a}geG zJOj;UQWxugN3VCeSnnm_#IY>mpk!VhO!s|1?8d=4uMTIm!7PI@_x)LFMm-WGa(-_6 z;vQ4+t)TvBNAjSHN5o?+MObk$%~-NZJ#o+l)~K5hddEk5R%a=<=>idmT95+j%&!>f&Q}Xu;$I zaWh?!bf`#~#}D1vjL#IpJZ)VfoD`~mu9^cQPQ*KI2*QLWsM@4yN7}EDBxc_ztJ~go zCDctnfWwX%duPTM4z~)=9g_!d_!3`L_v!q*P)0Vev}IyP4KsyIBXA2%95JaYNTOD8 z`CT;j7bjgD-jIbxja`)!dC=tz~uKJs$ zS&hD@XyvllW|jR->lt|cz+p(Zd+FsW%qPZ28~>eJfdeb<9HfwCDJgS*-{uQ=u0wSD zOK`7qP*Nr~?b`pCp8WsH!U_2&b%j$D`CcfQf|H!F7dPS zA@K!a(a67FG+02#98DWr2Hm?Q%n=!fu}RUMcGVCa*<30};&-DQ+EQ9CTOP+R@mT#; zonfi(aK0c+>;$=3R0hDucJhxdxVbDzeVfLDk3<*D{J#1W|BL|HIrk$C-{?i|{X}e( zZ(J3%%Yj*E`Fos`KOKP#UM?r)Vk9n{FJUT4R_qjX`hEwno&$#DgOA@`BiKhj4==0w zU8yyQgP8O0Z&ndQA{Yv^UTVO4Xh3%hs(&;9Rr4yhsBzKv{oeFI-{m4p<#(eO!QmRY zI^H#$tSITuSYhJkg>%@U-zkK>7VlY~>G7#dig#aFiwYSpThvLV*Xq?Hv6G}}zb~Zt zh?CY1tyJGYir#Nj`m*lHgt4<492uR)QVL-#yF&#%qorSS1KRrf&rWGvX_vC%|1bWr zor3?wP}AHE^bZC(NHObv4#z>RQd~iDI8yFk==V3yKef?_2qPcW{wna{eR5d#5!58^^Gb?yG!wM+aY1%s8>%8+KLGGWP)OfjS}F+ zR+stUVO(Mw?oz>!Jv1N8Stf%HK!j|`UI=9E4}q1T0r%#NwM@XB&T zGmC;4CTBAMr&ZgA97YBbr%p)OEC=p&U+GSTwH*(iGLwhg0+5lF|IG<_ezrMIgcEzi ztzkdJ>Nau?NLpsW#7sB_&UIbpF%DR*N1#TayClQzOf#_ckSO$L9tFH6dRugN!}4_7 z5)M!zLHz!&m=so$m>^F2ombTuufbTVpj8IsiB)+~fN{nRB6X~fromAy6Pw-V*7#TSUOv2%|gygOioeU}1Xyk5l%NVv~BrLgSL!h{F@far7Xzvt6kUbyubJ zt_74UU)Q5HB-~DyBRuz>z!(>=zi`UsrOAK=c6U)vomex5YdX}bx-C0eWNa+0y_4G( zHbHX5sTrx?$sLj=bY0cLhW==leY-k+F6HHrQP42tJ~@841xw6-ZgIipW3 zR`tHk0w$g-X*lGKtSpSqz?&x=$pln4WVN^)XvUa#y4G;R(hE&uvC^V&{N4Ls38gR4 zAM@fN)#61ys_VL%FW^XVmoM3AKgHjy=uM@CCB#*6O|*zvrq@6bX0UM!~p!Q zspM|N7(CPbf2xxg_y6SkZFO6gsIKUMGo_o7_2QDN8+=(!iT{zb?$a>1mfEz(hjEZd zTAZF-3Ks8I1Nopgb)${GGN{HF8rS8vw8iaReGbdhU1$-N5^Zg@+6;3yc(orTBJaX9%|D3$I+@ak$=dRQYk06LAYI*mL->@p?BF@Z6fj0!KRDZ9Zy!!DB}eK->zxeasB>11U_jdJV^&{=|A3Eu`(f$j5# z+cN;o@jRhi&WdpC#W0_4w`6JIg$^2Lp#R zZ(e9AEL8lk_a1o?5lSol3#~-mb%`NJ*B))R&|Rd>S*@>H6nW8kO0PMZ0 z*<@kK=CLZ$8JHml)#k-g=Dj|>A0k=vr{o@{+V|IuPmV!Mb^;%+`)twX{3M^FTp5(^nE~N3T1xC08v6(V(W6KK% zEuP)Rx5Y2SCq6o!d-pKAo0C$cD`}-BwR7$_C`RaDl{MTQ{P_~^?n~c9st)+&Yjl4Y zD;5D_1(x?YkJ`o*aCkolmdz0RoKUif;N{!dRzScsaY%;UIat*zanW&NC~LwdFK1A< zpd_kL)XilTv~Ay9I8CImbUP%(Oz7!dLrK>fi=6>qy}mloBJ|DfJ$qicdLd-U@`v$O z5N)E`(NikYsK(c$;LkuFnB-ZmL%iwJS8;3KmF_{be&s1hJ`W+)kdE4PaqVf+zA`@@ zbgu2d<~&u|cQh7uX$(+CVYNkYgN&G;5B5CZ4An{xW#dVifTjcqlX9pUR#_qSmv25!(tk^@37!xQpGzsaGN1X)83I39wn&ztLC{ zxg}Gaew_obdTie#DsOf8#6jz>jeua^aT`ZhO01uD5FBZPKr7z-OJn+*_YP5~xeIW) zWz6Fpr4l3@0#4Oudi+Yfx!p5Evooy|&W0V8)CEn^j@2N}i&S@Ue z$3ZxsAI3nc?Fd6xx(j5w(q2Y)67$`z=N@-MbG-?hi(H&>*9QZ?m$tzPLg=5#g5Aaa zp+<_D7?6tQ5=mVat6M5{qt-qVB62%J3iN|)@!o3m`!J5gHPg|<8NYnc@vWfSw~6)y zrmmMW*jU++YgiBbO{Go8o)kKqi8<6+jkq3^A1K06de!Jk1W3U%J9f?s-=nR2G6=k> zpm(hMZ$8TTj?-2Rcd3B=qvdefFUnR< zaU48%KR&NImSruO>Cz#;daXLMjm7}$Qbm?;TR^v}X4K6YtB@gsvHW@`B~hEb_p((- z$yFwi*5hWvDvidEo%@y-HQ`}x+36e?Yp=0JM5^?T=7%L|STjvrU)w*9iN^LBBts2L zTm5n{w=CA^Neo&>w)NbO3voe*tCCm1Qfl@S3**T+!Hj0{2uICRX-P1K*2O{sBU434 zvJN8!$>TOOz60+vguH(TC?S1z@VJsYKx6&iNYZ}3=xHL)Q=ON*8&T=Zz3&Lm-==&| z>~F$JTfA=v-o_AgX3aLSlcxK?c{&Kf<=9Uw0A9Kx0(udXvY4Sof) zgg6d-e;k#UrugZcKB)5JO;n_z+{zLbYd-ksVZafUW3J40c_f?Y%GnSEy^d9zhb~7B zmyT39ewjDYBjx7XseBi^<}_17|GP>;OkNNEm-5A^xBXNroL$CL+krD(Wyzvq3>!Z`4wppMbcy`(%u5M>SON8yI_j zaa{#+_QT7FADBlpfb5(-JKKkXTF~()!o`s!_IsE`XU|y5d#MJ*fhDExlUv+j zqy;8lVv98=!>>o|+Rh$m#ZZIiF3?-~yRhXQjL!E9P6nXQ6j_`j$O^XgizNT2iTDpq(W!qq_Bo4b$C+o83t3_ zMAQrK(}2GXe$+mN?mu0NCMci6UZFzjd4Vo0wSVblf{ezY+o`~rMuL~sQB|V^|hl$+er+QnaEuo`-ONN-(;G$r6yF2`4EN&{`yQZ9-3=7BGHM zxTyl7?!`^6g;vmtT(hxUPA+Y&fpj_xjZsuR(q9*_SnMujKD;e@XX1l&ui# zy&A!kAUbXI1Ns0CGYq&o93Su~dEyWsyVt#zd9Hi|?4viiE)QPYj067A%mwcpt?~dd z72FmCCS?WhykQ9T9uDLjSpljdCM#4E6WukYm%2BnfOu(+dHj)Vo#2}w#)`jPt?l2q zU`fp==_eqV!p#W(LBuSqNT-QQGgtCYitVM#uYc!9Za_h;YpO>hz7GTkLXCJ=CAwe8 zJjHICb1nZkdt6sec(l|mmY;6ZN_qv-wtkbYUOLZTTDh6+^!J4rQ3#CvD!3eXT{SkZ zkR50=2$Q%-!stbycKy_jK2l|0T;r==FguKbmfUcurEt7KPyJ@e#R=kQ*)vkA{j(C` z5Odg5owPN+@B|OV%5;Qe1ftWc&^3~5lwjZc_?%SDcIM!DU0vqzm{68OZbbk8oQ~8? zoj{&}CiH)*!ty10)=E?$^H=16YranGYu@xtgA7hTsF)pWVYGLtZZk*O*s1jk$qzpdh19RNJ|$C-UW)GF z)N~e=%hXSf)_T=(wr=Eq@3nwE%ET<(H7XRb2Y0LuKal7vw*K^{_`$W@6xj+3F@2qI>4-bn*AMNHO*B^Bg`d$duI_*?haT#YO+@!XCMN^L%oHLc zPqaRSyc?^7y-I*}RS+wVn8cn}kWVuR>QgmD9vh*W->{9g3sziQR=1=+ z=jB43fnayB;k>&YR2q-i_ihE09TZ@RJ%u2jeoV*p0#-6hS`%=;*^twT?CGsh(K*1z z_X(Ku3|WbI^I=GSP8zD>%?*THe=!Jo(wmjTL-KN0p&@fZsaQt&M1TTun5XwcHSW=} z&P^0l?(Zn=5F7AFOO%-zY0Olu5J^}wrK9dC9HCOt#2Ywf`sHA=ehFhg$a262@uq$) z4gc#lFfw&MROS0w_VZu20qxbH^s>SsQ^|{OS-dLu%O7qUJiEz#1L|`{v}uvxWpSNUn&5k^Wp*aU9YmE>OHL5RXxaeW_t6OO zYMjZmf9(DE+g0`z)+^KW2nM1z37lP*cOchqna}GkXjm5tQs0$k4e%EL$A(rcOS0Xi zz5mMinFGJ^jgts>JDCh%WU;wSC26NOvt&E#3^w=U@1L4xw|IgRSEBl~D5z!n+DE4K~|!)0DH`k3?KJcBkS-vEh_m9%^Kb7mw2tC^Qc@ErAQub`6l z-@!2h!?3w3Jiv|t;iDl;6gb!^0@O8ePI3Q$X#})dc)E2iKZ1n!6I!l&Fg8g6wFGCR zGGI=qA$>(VjwtL@`;&;a;IxZ%(+fbteY*Z92un#HbXx;EUTVjWh97hrG{a?yT zF;lz9!{l?WBdNBH62aZ)QBwXHfklu!gDhHo%0*G~cRsE0?e>4QmJ$4yQspmeh`sn~ z@Ar0hSCYeA=bAzeQa-FeItjCMJ{n?|ONT0#|B|SZlFGPdbvCY9C}?Z^R9*4ZfODl3 z;vY981x}xwZ}Uz5)7`*3i&%DBEIsw>ICv!*0XVPdK!Y3~^(gZdhZ-?`z)KdtZUMj0ljAE*H)FbfHbvdyx$i!2P)NL`^72%aHT0rn_lr(V_d9~1 z+#EKpfumXP;=QzJvhORxZg6T&9% zE+oU^Uqbsa_vQmX*;mzw;|2AH`%Y6oSsOPN4k#CQ%QVSLyh5qH+xb#QSn(n3!E6`J z2?jT8@SZ`Bzn4C3{4wp2``)#S%P?TNu4?crJp~%~ zj81XTPb{N#wc{x}-L6y-^Ig+E9;o-{5A}TZQ4^0|Spp`0sp{JoFb(-&Eujx#Psk(g z8QN<|2AO~ek>>8v^`AE;Cs~d=V6~qtqY!k8v`g>dzq%p%+qW%tel4JuuGILsew4Ju_Yj$}kM?6Pv0^xz#10x0shekJ5rikyxy)X zFd;4oJh@pq^l_DK-FzK!io_^_XJGE?#5Qa4gc0S7gV}uNSQsk2GNzpAP#XJ8kzwCL zvu1h$8jbujw+%Y~i!iK(ElXJBJ_aJU{*D(1_;)4wamWIC=+T9Y3Q=t1 zJoi|Xi1ozVuEo+%(=+^R_@Qn2ZT6*&t$bo|1;7VZo%%SB@{Akoa(Wpy7PD2vUD~Ao z;$@Ol_u%95y9n!GKZKUI+FPigc?)qDPBTG6v(3@ChfY14y z$ykx&=|&^b6_^7(gS}Kp+n1aGtELSy7)9ao9P@-568)F9yPC2Wi3%stoPdwQOTUzz-*uD0Vl5gj3(^ z=42~EBOY%gSJ`|>JW+JNQm7^Migo24zpto8Mf2m!xA1l)5AOv@h+1_wIqrO@LWkZv zQR2+kGB!yDf+*MHE6R;Z;y~yVzDb2Y_AXneJqhE{&wes5;m|_AZ$B9UI2g+QEaT7lCM?0#3`lXI1 zur?1u^x@}(YtIwnh5L?%+F7zVObowUGGghYQ7#VVU1S==d_0NLnPK? z2iaX^c%!1qK0~9ReWuoZ4kL(tX9=Y9oBj-W^k+wu7Frq{o zbYgVkhikV+HT=0Uf!WO3x-;|I5fW&0qHH`Eu-M=AiwrPX@Z{2SM(1tG#u+>+ zfRqQ<&Z0eGCuWIBf0&3hM7Bn$*Y5gVKTc@X2j7SvxK~C|KEXn%3g}0&kh|hyM%uF5;;9-2%Rm;*(Dijk8R^KkK zZ@C5iu>>w;Fz5$?_~#^6f53NG)>u0=NYwuf>l}oI^N+;^o5R|f;F!R|Z+B49H4P%GDItPFM$~qBUx>BH#F3 zr*e^WyLrPaOXVQ1o4DWrykqiSM-jA&7!JXlO=poV7=oWF2cE67cqJ9k^6JM4o^OgF zAjHSL{?5vX9DuH)7*bATjf*kazPdHxzYg6{jVs`Rm(*;6CVmvjmJP%pyTyVY@mHs4 ztu0-B8;f_Iks_MH?rlEodAb)3#GJVTHYn(eCwT6X$5G?27VfVMcd~S#$s3H!-oeV=f3;otub9nB@(sQ1YDoI4W7_5`-}-)Xr4?}8GzU<56@ppG@h-a2A~b}6Y>BG9q42CQy`OO=L31+lr$bnq3}OlxfBd{CWu zy@!ImrS~yEcJ`2^)$U3C&wXUAu=g*TP3JBcT8vl&Y@Cpbklev~7-wy`|50RrDZlqV;ur^t)XoJ%#nlO2);9|$@e@9u=QgOFHsp$QFaR`IKYN5X?^@%N}+21rL`kU+oQA)vE zS0kC9Q|Fz!LqZAC-YQ~(8=73sTp%nhn{O1~OfPtRZ%6r>Ug75bGd3lee0rZuAFid- zTUS}REz0qnU8~mZHMvsjo=zR1|A(eC4~P2w{y&w7kgO3Cg(RdbSw|s7h(gxME^D%9 zc#$o8v{*ADTSBPFHg?G_42iL28_Nua*NmBY{igTl`}=RM%jKGj`#Sf1&htFZ^WX{h zUxLytMBGI|YmE$w?HQottBx^ETYE6`#%%=m%T4A6dqR=_HSq>t%~lNT)bqb8E&j3; zD}W%>2c8tfax?srLXs!DDnNl8-3(qR8}nxhz#GJEjT|%FW`@{z#9G)-ZM)JOF;z*> zoH4}}S`*#i=Zv-s8bZ7E6AP)fbgx$${j68y8gY}rM(rSaeRdhKN^3Rhhy4Zi_V$U* zO4Wz$LEhUrFOr1NJDVlog}Zz9oHa}1SPjU2%ZnOBz=r$!_L!E_=2I^;?AL?Fr|gJ8 zDw^%J5VES53H$cX7^3=~#W>7d+*+TUMbstyQ}J6wocS<{`KwW$$xAl|GjVV z5vgB-v_l|XTPP#FIhz4;Ec;07MCyF_A zhs=O>kla6tiuA{q-yVSgbFXeWQ^jbkS)|GLK=YYbwV z6xy}2I!~Fe+;^tD0Svl)ECJ*Kv`pE-w$=9n;NfN3TlQ;M3BM+|%!atE;(~c8d9ns-GH_3n< z?R)(tSkpX9v?#XnhkiF@-8xe!Y_D^01$4MM;j&uuKu2>uh*Hq_`Bf(Hv;TJfU$3`# zChSiQ>M9hA&@_4UwZyHvrvq5~YM_z;MPw1S;5Q{9M3>$@LpWo@1mb5!cq+QuGkW=F zUQFtdk%jOscoR=D0cBgw8_B43#fyX$c)Bf)>=e3w@RjELYg-sf__YI{2SadhFa_*H z7#nElvHsXVqXKAyy9Wj+H0_=veQTvaFm$-hwqACws^%_5wP>r3l%ZF$Ta|U{R9ePb z1{wE;yl72$r;O;VbG#aG0JCrg(||sx5@^w*-gtDSnh^gAcfzgUBhao)j3VppNYggq z44Cojj*$%I1c#R~~V zcjxx?_*YH}BHC>u)aR_T_I}>r7uCA*sr|#LLD2B>A4MJ6?wHqD;wb_L?3^MqUmNA) zM=EqF{1Cl34G1^pHFl!iv1{6c|7e=8Y=;Y+cP;xyaOlMh@E|Pj*y>sM=1J zP`S6hLOqZr zGzINaAnrl**(D=o93|@8Hl*)X3D0{64Qk}6ucr>`8A-pfW|jM1bUa&ZCX64s_vx%K zwS;m)9}C8vy6 zqZgoZP^g$wAa30hh^)iFF;v$x6vfglWuoiiYIp*gst4Z@PHKI3fRdQf3nHMq_<@W< zxoxz$|D=3#e5=mfK?*}E>C3-Q@5JVu5NCkDw#kWOu)Mi+c#8HPNRe6p*fAXM9`F!)EgpENFy3Sm8b?xRmGHd};Fw>2F_Kj@(O=kC5HGi8Hqi*GF z2{~t~5_nnbDUiI~G*F)-fQQ}Me$RG3j(Cbz5mXqS?qJz8s088^((y|^E~$2%i<~G#ufRj$?rBNZ0_WaZLwk5AKZkO ztT*3&lww|H!=!^bChL${P(N3>jE>YRIdLUpHGP`UH5tI-U{>^kS5&H6gj}@5i14pv zdO||kFIgdHt{2(7F`)vI;Y(r0Re91=08F5CVnHO$)oXFSQ;uzJeoBWLg4fapHo{ zQn(Bk%@51zSSbE5in^WbOModq>!_z)MA;EgP2Zo$fvfbPMXV4Ml!6Ycpjw1W4k{B| z+1(Jyz#(82Wd#YtX3D$2w<&M4hmT;s@C(^q{9ubgaKD4*Epe%lN#7&TsoIO=d(cBY z45D;d^nR_#mIZQzuD;Q_U4fhw8Rt}-G5h0Ls31p%)q7LcWF1Z9em`;r^DlDP#po(y zOPg47Ja^>%W9c~-Tbcv%=UmIRo{XBCyhJeHxY(O}v+XXAlkxG=!11<|}_$*yn64BL!wqox;fV>QYk z=vFQc+n}$T_LHRG&wiW!xcWIXd%NCJj?(3~gFYCxz%#Z2m$fUciCM8>7r0Q8 zbN>78HTIG1D|;=t&^v!AQ3Sm?#~vxj!CT0^JPJBLi1_??N#lm%7GdSlUF04b$I^e9 z8*NP~+Ko;Pqx{6bgM=l5_sMJxUb|gkIp25B|EiGKL@Ny&5S3GcsLmm_PLBS!eI4!V z$h6Yh$7-@QB_INy7Ge%mk@<^r$mQ!yrTpHz1rOLMqcCel<`&EPQhBBL?*%dMW3&HkCO?QzKv~3-EbL}d2Pvga zWN1GwYHrOdtm5J>QDga(7jqYf_5eD;=dbut4(v>Y7>MO5Q4DCuQaR%)8GzU!vO&qi z4Crm@CqrL~{09ueZ;lXGsWy?ftTy^1pb)|=1G^o_FEnf=Iz>*nVtomiZlzv>e07mc z`bjmahCvN*g?}|N>VFaxnnJ0#5A9Q`a-aM}FD1UYlrAl@i)ADARp|6WGwm54WXFvWLv>%(=qsAAe} zi-I&mYNU1ub^^Ou<(?mdXh;i9NR5|-WOz6QVR^2^gR(qblS7yWBkdTB+vySfu=W4v zX2kK;Pysb_BYN?hpvB9KbXi#TJ$)TESfSdhi4_262Ii)N=D%uqFN!NWmLsmo0PJnUFDCXAR+{!X8kzXHp5h!eyi)DLLe zAeRcIuKtDTqcFG_Eo%EOfox3SX4LDP+1*t>++N&`Gko9!uR6IxLhYvNt;JBLLziz$ z9FUaPYsOVEz-wS0OE^>M^yM7{XN7_Wfc*n*D1O|EGgy4A=lo6(A8>_wM%j(T_lt; z3xn^z$~}u)mJ`R2r+=X|fJTnJyZ_SU@PmKCEc%c&IgC5f<5=#hRMN+rt3O}d>_Nyp zF83fT6zoZ=g`$j)g%8qD z;I2SF4c8H~>zzlhSMze=OFVRn?1wZ7WBs@fGIHQc5m{D5l1PV_TIz_gklGTwhrY!$ zPLdY-JF<*|B_^MBS7GK5+1o>6U>CPs8z`Wvq6z zwm@PI-(<~C>BSi12i3S45F9?#^Z!yj;yOmmcsAf6A$uHA=RX`b$%NIH!=aZ9y4}2P zEE)*ci^(Bzr`rOR(eVuol`fR^X~YYD3U5Aspz0)d;bZQ|g9I&9{kAjlp&A!hqL-g| zN_?62xf425zOb;+q0*9my*DR%6FGEDZstt+sn3@<^FvJiB^t|KuDxet9`PZxl`d#g zsL~xgfmArv%DboMw0{rF%sBI1^~B?Md=S6NRE`H1G}@VnB5~YhUWzRb-}}ioZpEx2 z2=xm&Q%6`tP5D(7mh)L*XPfgD%0K&4J{j@X;!-01`rkm=(WKg9*hSenf-SBIL`!SB z7kZGY6g8>tn(7luyL0op^Qs)W79K?BXXJBT(eg>#X%lC< zw{}ShbH-+`GBxj0oV<(zV9EpB>waBg(Eg!)TV>1kU8(U*ywpCdR={s@OBr;3TgH$m z5?wPzOPsvg|F#kijLm6ER5LVi(SHCfR8aW46V>-#ox z-y&3w0q|2S^i}XV;6F)-+M@~RU#n!ltrSX&)FiF^KzBNR)&HGf>@IZkqSar|$tHw? zG4oRi-nrkm%V|3gPGrNI{DmRPz#DCtzk(^VVoSpTG45d*+$xsoI7~&lF8}zG=)r+n z!y|fCg*4}z?3x2J6WB!9yY@H?vE+^QJ{LM*T?E&E(6a-x?Q*m|exgNU1J3n?Q||wJ z0Te4nhospX1r24n<#j@)!1xz}0Y;k|6Y@V{AfDl|*YAJ5dULLO$CtY>D0ibtl9fU< z?c58U%}?7Y28`(~XzR6T4h=s#QO2NR7O|QqEBGeCPU>O*mwAt-Mc0N0ew{iQ0oI28 zyshtfko;y0qK-$MpRT8h#hIV}@%RC?jZAhg-GIOKft1$bhUM5fC zmw2i{Lc2%!QC*L-0hy5HVHi~iTL#^sLAc{+kJFy*pEz;w9C6K~{51P2+z$`xOw$X& zL=LTrMIoF|Cu#ys5I>$U@|E|XVnUG?;{sK4{%r_12eLe5xg+CS8+9T)<^PY6`0yh? zSWK~T_+bFdPhz6zdc8_2?)h1C_Apvxy`b||8N0r&X4D7+y-h9PZu*l0xuz68^tj1N zQ;PLVrP=BdMn`|!oaZ}5N|DMP(-yZn^*4^NnId;X;bp@F*O?@Pu%nuuWD%*L+0P0& zs{2zl+55Kq5d}}ipULLw+!~UiO~~z!A8~j}N;w@=p0E0_Lh9b?zK;EL?6>Ff3Fyp0 z5Fb>CUevCOz$;>KJ|ZK#&z{4k;)tmYj#Nd>x;`?zE8{i6ncoHXZrtV1wiR&nHRST< z(Kf`bnQ+dHnnsc$FuVDj!!&S&AKBGDfJ8#c|B#nm$^fayWbWdsFPKI;V9te0Lxc-K zq2f^6VLJ(kX zCVzh(P(vH};$#dKJ$dtS)ETLL=P?Gx?unFT_<7SihP^MS99`sh!?OB`o5W}txesiZ zJmoF$UKx44t0~)KD?Mxvp~(+>W<>CTLN(X_6K0xBjs+)`{OeEn@JBk$jorC$Fc8_i zy=1gwF4^y512q;Vvgm*8Z>)bhat}uJC!Ex}6n*4bEN6bO#ov6dyg`dJrbCsc3#u z(^tje8UYha6{Y*0FHQlSVqX7}gV}vbNH$dJF^O&XvyA=?HH6hesBw6>|2OiAC^S3g z<4REl1YwS-al~X*i1kLeK@e3GzdvG=L0(kA9QCLb^9cN`;2K(wX=0HIQKsma(Hpyv zaUtgWw5_v+_MEqA(z<@f;2G*gGm04^rQ+r82%R77He#Ha1y2R z)eMMa?A?7#YI+ zZVL&Ioco1jMhsBa?-*CdwK3`6_pf6g?X1G79*?QUk1!!3GdWt9;o1-0_Dj*K=E@&h zfvYuFd8}S-S&xLqAtZnlm|26lG$amKLEPaR4++pI*w+kV9kiN%!i~CTe`a8e7gbgx z>XG#B6wwY$($6egKaTR{cILEI4%jCiH0a}b0D{2L7-4{D-P?|xK)=`DI&LmG`7a;P{g)5aJuH@gD)vOD6}Ye4ao+V+tCWqK{+NGoBa4aZO3$Q1AgkW( z?ZV7UE>G3(9u9vPbuF@wyc^o7Cop5$-TT}qZO4P9;0RTc-~Xz~$*n{T*ssUK%3gV0 zH_kGM+jwfeM~89_-H-(JN1AUuee<6Cgt0pc*a7amUx|=rm=!nYM}v#ean)=)K<*NxACGmDKCQ zPmzNpzg+0I^sGpa$lB7vL+U%qwoSL4y1%t626p*HO8F9cfv_n7U4Qeq2ABHzwhgPp z>LQ7=MaKy2raYn|+TvV$lwZ66Ol%d4gMUMwsxKYg4}C6A^@PdYY@mH%V04&0YRg*h ztnr?4r#+TzD;M{BBIuJuW zm;=TU`|#qY0cZ8?_ZEAYusCfhcTSihJLG(xDjmL!PG@vIaQ>w*^H1JWPSI*nB`33= z{V#>|IQH86PRrnk{xI@Nfd!!TBk0IX{f&eAV0U-<%#&&D@e?;iR@1Mx7nrX(GcAiNC(bqh}UffBNw)0~z^`JiCGjbpb|cfj=_0JXuqP6!<;Y z>*XAVa$r}JR%P4&=7m(3W-anU^Be7VpwJn2rGX4xeQN#u`ITIfdA~-JxS=vMbnd(U5gxXYyeUlzy*`PQ*qaLw&vYMn+JYp3UH`Ye1-O(O6Vi4`pP{bW&FDGd{E1m%~tu^ zc@MYQZasERAHZ?=l`Zsmn7j`bDh+<`an^tapp!5=gD_L*8}QBeh={@I`KL4P?oY;0 z_pEQ*?xI)WO-_lp=eLKlm%)pFJhPL5OjGTD%dwzRcc{wMKK zwz%f%^Zpb2ERWfA;`dBF%orD%s^WRB7pTok+vDDdnFQ@LNXHFpUx|8kNH&`l)6IPT z9^|rU?BW+DAzP2Ul1?qnM_HV(HaK%(Mr1-y?)pxITx{T7qleGg0BI%xe`{zQ`ax~< ztcE5W>0@gldxbv}?oAV}nM8M|>QC1%_;~jIs2Tkf!e&+ZER}%xvoJ|8a}ow`N2U6@ ze}1|$ijxzxNd?nF8))XH3CUHOkz=z~p)vBvu6-4{L-?4j?P0!4V^ zUvZ=^`%%ys^3f4rVM;u({rzA1Nwk~OTp3c8L?4jKlb8MUM8luaBEAnkCc=M0Rx%}G zEAY2Qls~~9?S6wYt2|uIe-tTY;5#S?nN@ve@_5&EFcVSz=t9RPY75kou2bKlu$_T) zzCd`5j=D#<>DQ6U6vUpvl z`!v2UD;!XV6)&b3J~L9L5^otE3JI@?@d;zQT^ABk?=Hb@paP!^-&()fMB!9*+(J*2p>?VP%x*3i9K{nN`u=UeOuCK_o*0C6-cY^aIM^}f{GC+ z&H|4u1F)PX9hy{5!GL3kcKtO|9q(l0$`7x&>ifb;P=gW=zR_F^e*-6@hG-FmME_>40>df7+OPgp&nkGVu7%;PD(HcJ zm7Kc!SBYX-%2kHRzi6{nu>xIdw14J1-;b!26OBCejx%q~V!rOWm@DkL z4T7f(daqFewLF7A`v+o=`Rf=5*E@uIXN^vVe}%&S=*rSeZ@1M=dFQU`d9*EgkEA2O zx%N9TkK@x-$a)mzm~O8Lww9^9E+|3HWs!gO`J+$D1Z8ui!|w{WiEmZV&iomg>0AnY z^jbKH;j1AXfpVmJIT+GsxfzS`8ygZg><;UL>j|hglg!K3xhb=KK+Ec>vSe#eY@d8> zQ=(|LPEeqBD|WAlrS#a*F0?z9`Ck{sCl9RxtVdLx&vU(L*h5T%66SK2RaDmwNC>f) zEo+n@5iLF@Wl+M5_JsC$LMBLT{o7we_X|SHn92SCiSCoYu*d;h5Y}uuMDY$^*+H}_ zZ!v=mhz)P+H!g}6v}w(g_ZpWGzb2TDA0NFe+CzQrV>P+s)gwu>?qzS;+g@&c%l9W{ zX!zmed(E3JCMyqsZ23#|sxHWv#mk(-30PX@Jj8GEEg&JSIzLTP{7d>Dgvb?1VG0m`OcCfqmOCd=Hb`x+G{$9!2t`RIH((}xd~?d@ZW zXvV%4B?IlCIzlAEeG`~6S(emL`?y;(2G`epbV%amF&drqS`;Korj!O&H~I;r^muW%>jREhcR%b zW_Oz#nZHl5fZEpvd+LW~$L)R|40C9 z@yOC+TRu$=FQPGSSHllB4uA5W_&+Os#J0CNW8865XAX9j5m>F(9KLhThPiC=iRO06 zZ%fNNvq82O94&)L_e!HK9y#hQG2+^Ko4Q$ccE=#C_fGQ$MbmV8S`o{7MIvq@?3xXM?u%$tD{G6# zMzOJ?!CXBVt2xh) zn;}mFOCOGDtgR&snCFJ`m%X&Aa}IsPeR-4UQxh=J3RVQBqC4G$p@muv23sm;{ZlBbyL6FRZU(Tzmw?hxwdg*jV|h4- zvY4mbSM8ej7d1@@YLhcF`NViQ^hFZP#tA>$u$}T{m$L= zfx31=sFF|{PVhulDt`0mUAcvAvNsiYPvaBZ>>&5ua=g#DaC9aH5uK1VpjQTNZtcJr zSG(kL4u$s1fNRac7og8HVE{MM#W0<}aW#Ei+*nS;Bd_nDS}DP`TDWM~FMRD^c+n3n z?nXTA^@~F`dka1N@pt)V0%wuw@8_ zOM*B{t@Dij^Yv-6F(~d@w1es$ErBk}y+W3>cs>8%!ixbHfyIu!2u_pDXimEy`>4vE zge<^N_bBVFMT@f)M+B4Nno}S>ko^mu@xC@Y{{)sSz*f#S+pV0eGF03_6s2AKGTKm> zD60@aZyzRAo zSDR%Q5}J>*tPbdOUYj^|Q#&}goqyN#H&Ktiu`H|t=tOaD{izPeX&E~f77*9BybrPJ z8iOC4%78u*hY9eutNhbfHX#oti%w}Y)AlMdLJtwq&xiZ}<2sVXTDjEz%Wq0pUN%wf z6OxKE^Yu$}HxKQ8T=a1LxPATO_EFU!T)Wd>Uzbt%PsU%5VtrO-2<4e9KEn;I5&J&; zA`R19t2>Yj^3uaVss$yxBjs(iye=a4#58{M-pQ1*9oW?ill`X1fl4Xm6S=qh0FzLM z19-l;wW{E4?VP31jmQqLqR%(-_a+l%q9ON^Wz_pjBmCX;`R^STIBd0NVDX>4d5;<| zZ!b0~68`rlja>bviC=KRgvX1w@Oj=)pfosH;IdpHnR1 ztKlz|=l@N$oo<1>`3(UHG2e%uEF?+|%9RqCs zM1R&ye;$J}ibCuT5z^vxgYYupzOW=;h9euDxKU_#eZ zD_Sl8&+QF)aNNB^<$1c|TeA@hz3u!7GCvUgT}hTY1K{6}umTm5SDPBCC7#;?Zt==SQYCpK16$H2R% zhfILi5f5i<*lh4>P$ZNE6&;5qrG9+N3<&~Hd{fmn8By0?Lk?E9Cp0R6#F=9K{Gv5= zGNP6ZcK(XsAAugDr@yYCg$vS_>EMyMhFO32@5R*275}>PU!i=_%87kvh5tAnVX@B| zz1xqrCa=@8(bC-8vu5T-G_xKimg-1T?l-v|9~eDP`o|54$0o$c3fv`D9cvv{y?9Z9 zk|-9N5>r_7@NQ@;e^nxr)2YQ4{q#N2wNy)Z4>JRD#u?LIH!%5L#lm16KIiewr@zAm zn&#u8&0%go>fgS3IqYSBH@1ii21=9;y>|9LxR>$Lp!9ei&-tcqECn-Zv(J>AcIW-X zPANT{9SIt9{PwjYwh!beJFsj*Q6K0M!I~>5(0?PihQ?G!fk#>TJU@SHcYRdzsAz!( zBMR=e6`+v2EC>^Fr_Ok3n%_K@Ftg150_=)1X;3_&zwF)0; zy56ZBwoixJwtzaStBw|9-y=MC>i^9g)()X^gF|NDS*$+gSf5`Zt&FzbxN_Y6v?gP=m zAJL(*w9o)=BWMG~L1W6tFZbfF@om`2MuFIso& z@}UD4iyIq%#4d+yaQAkxqn0UCjQ<3>|3e11W#l@zV`Kbp;Appr;532 z{2OZ>H_?u7Ot?tcBU$C77v3}kp=fQ0<3r{=x)N%~IQ880l+R14D4QN2ClX#j?BQ#5 z?fbnFZy>GGGtN_DN51W}EL;oRz;Ot*e|4Jz#I6kJEOOUR(7RVRxVtJF;l#a4ma39V zyw82>=$u77)f|`FOBmu%5qavA3W@lUqfc503#p2XZX4;BA6Z^Ii&(!w`Sczk-t@}R|Hp(+>0 zsq$muUDTcRr2xqw(`!-g4;XFlYF(An)!to|{hj{!T>+&HYS2$}{LKXKJi?V)&Kz7f zs-;~=XP!Rnw({#Oc3>rWp0x(1i68x(qa0`-y2$w1vly{EZ10->bChz@aO^c@Z30Y+ zxA;1D@aO>XWuiwx)ueGFs?;TWs}Yjd$4uI{aJNW}#x#tw^}^g;w(#hXM7l4dw>Mae zpO35WK`dG$7ZAAA$r4aWpxaR;Np7?~PHUQ=h)j?RcbHS0PeE46;f@(93*J|lz#`9d z14`prgkQuuHPePYni1W=HhhgHMAv@c#_CqY+)pd_6$FPkJWE#KoMTuuXjlVGxcR#i zy>F%T=l2;%>Trm|c4z3Pt0$w%dXGN;3i_q_memmJuFDt?)e{zNOoaJ2-*^203_?F- z?1@Ev?js?+(C4ioU~_zW1twfhd-bt|$oW#~)TaCKp=N?8p}Sug9qdD(!$5I$0X8_) z43toom7MxA+u6Cb-A8P-Yw=K=_SrIZqKRY#zEq=izE2)&rt0Zo2JuR{Avg4b6h~@k zKa{z?3d()&qgjIsdak>|3%~w@n08tAd=GPSRF?l8t}x@y=B3)(P1fPY_Qx0{M7FOy z2`IdeHB=ag;rY!WPFs`YJuNYAe8xr43iKu@^471n;)-|LU0(Cb-h7l?$s;q)A28pC zgu=d`w#M>eu7f$Wb`=VL8+hFA>%GZOt;OATdtBv{r_Lsy*%1{OxS!mEU%h54QM@P+ zIigNq%=q5vszQMN6>#MB!^bIWDR2Q>|0$&Ojn>UpJ&qfhvba>1Bxzcb=mPtJ!eYL5 zl^*g%np^l58>+3{=bZ)A;RPiE^L<;OCCG97?xX0yxgNex)wdSg3zaK2U#9kHsy0H) z+8uOs4>vOb>^3fbUO2z93FOk`4}I{MmK?BlWQKye-=*o`S?D@+6id}@` z3fxHuX4#zN^LJ0X)*Zv1%>NMA+<}RnnIybF!(gq1G_ideS@oLYOO>2*cXl|r2EXx? z2ZlAedD;GC-65D+xLJ?{Srk`i-FqDDg%vWD3rnXE|Zlnkv3fMiYBte^S^c z*`oParB(HZD0-g_>JRlaAE`KZ)$ab6H&Av%1^Q&UL3wLRg~ptZ->?4$#m^rJV{M81 z`fs3EOiS_Qx0)wUkqKO35jPlFjQP1QG1v%!H@h)s6?g*DVs9PjZr;4Pvy~y+5h(g1 zU5z5<@-c)JkXAiecV(?KELyIabVtrJ*0KRtD@evQW~|OR+p1~ad=_-~@~;N6EbYmf zpe4Wli_>gwj2K(5`HVH$O0k1e0Gt0vjL2RYsa->X#g2b@AM8L7EU(sq#uKnGzNE0W z9-k*3A1R?Jh@@|pPt|Cqr>RpC6++W(lcVgzZy$>s-;<+tFgf->-cWDcSK2C`&9-Sg zvnOH}GL&XJ`N*+-+k1_4G$)86eqOv0ian|=Y$xu>-OB8@30#YN8~-E5a!)LrKEOlk zq?fJgfU38Dct5G|Iwfg0V{v9>Kai#h#tfyk?4W|*8vZCtQ{EZ`{KXDmLJ79YwGaO! z-D6exCXgt#lS+E-oGzDr1grFb7Ngr=LatiQ@};lTkcUpR5L*v!P^0YWJIMem=7@H; zob4UCXFI2T0zMo(0Pr?i9Ur`XwF(WW^9_s={#|BuQ2Ry92Pb4xx@ z44;}Dalaz{%PX4xsu-SbufkW5*6}OO#1Px@^8llEHX91~kJQ=MfSJawG z0AgEcU;bGX{@-d}x3(XOW>BSY_-KrE?b5xtW- zaiO=vdhZ920it$LJDd(4>;^G@^3_#fs26=p`sbIK2NYMA*Wb^eL;(FRl?TT=YF6lW zI-5t`D~ey&r{*%@iZvZ22ix^FXJ}EgheJd}a#~lhF%AZL<9(fa>OzM9q$M>_crK|Y z`)DY}wk*Plhy*^GA+<|{;n>5TXrt~DvSSx)PHqe_!N&4#(_O%}i6#uYmdJLp*nh>g zX6k7F>$A4R`G@qWXm|ZM-MST2*8jwP-H4M4|0nKW;5-Zss>#;NbQ*vUt+FwkR$2Oh zH;b4ryiM85O^mqIZ}nV?Z?>Maehj=!DsB&T*O=?GYbs2ThoNlWP`8nFb6s<`U)m&9ff97h<9t z5oCv5(exX_&o?b(T)xi<&aWise;UGm;)-PryZpm$(61rvAiJ6-Uj>D`JcY7yN7j7`V>7eMe0@-`;7=~F z#5Sf;j?N6EiiDsI<9^c8kSG%UTzJqRMiJWG^o)}zLG#X#efx@oNHBm|1RA-ujY z^l&y*cFcIUDj`I9znaqVgxkCdZuU#6lqu%{@88le|Z=eqtUDXj(%DmV+C#$qbG|_7ast7#&yA~@|QEm5qRiI|WmLS^E4dp37Uzo%#aiX>EFZ^{r zGb$JZKBh63QYfl&*{g+JyVD4 zLyf@^vf&3(M*Xil^SsM$l+2RzW!?RqU!1+K(7mNBy2SDTaliGiV`(0yn!89DtVmRQ zZb2EfXQIY*8QsS=k$Jd`?p+G)Up>Z7U_uhqyU^wEjmz1}6jvJXLQc)=5|KHukXz8_ zdBLHurste*^&B5iiXx|mFQvLDnh1&=%gmea_?s-QiNVtU7euM>2XKMN!T%z}N0`y5 z`M*z%x~+F?Z&fWJ?g+te&nnF9+TUj36CJt#?wqUT^4?#;u-X{qFc7?w+_?Iu^Q}43 z@KMWcob0U@=5>dM&z{RI91Xwy)*~#&0m(0Fx`q1UctoOgPYGZ=EKb}uae^{73v8)X z-}yB5M5~m=D9_lDY>4}eQWQb!c=B{v0v{lcB*M5P42BZWk3CG)JLRle*ipn+_NHlI zxzA@|z#6y~X{^1<25tuRw0(||vu(@xEetDobh(|$qA{y}-Z5q6)FV@RRqh>bi~4F} z%6E<9mpn+Ro!aM=pjRnp-z~w7U6Y>fdQ1iti>me5;!jj*pLIce&nylN+NYowm2dCD zJ2Hwh@FTltXyrIq#*>8&v{VB!8n}0Hsft78^>FgQzCnUbp-1NujJF?o481^Wd61Pd%Yg1HO%(mtLd4GaSB8H z?0_zVMzR{4-}cR@mP7_#;XFBsKC`rl`jFMJCe|0@Hl1!4nAi_|AVzz)uD@d1VVx6= zY{Fb03JsMy+I>Q1GT2vNCSix!oaT4A#LxBnO0}9TX^lqD<}KIYhn`BMcRsr1Z`MfW zjGbx^?$*1tTa?YYqt!O=qs`9QDv;ha>o25UPZf`nQt0ee_1TT~HNNOIbYoqBKk9e)CtqiI7c- zq#aLX&^t7X?GPjk6R)V>t|J{>DGJ&Wl^l+lRzh;YHiqzBH$z+LK8HvgzvB#-FH$I@ z+FJV8+#7Hk45IT~_n!&)cF0-twRFdB9i~8csLm>cs>52a@Y>y!#ovI;3l1{fY_Gef zT7k7-xhn9y7(^9)(l-=Fzw3e%{|&_WRNwsvRwima^*asSGDoBy)o#SUc8&_@YPQtxN`>;z6BtdzA!u8m5iwe^_>pAz4AT3>l2Arq%gi&az zQna7jeT}J%x!*fxU-B)s8@^A<3;iI@b2SCg&O2(XNB9W;I038;zkHi87~Tfd&r5mXsjdV#$jjl0Zu)((bKYX6&_kZFIe0X#7 zz3)@kIp1@x1MZ{{HIj;q^TE(@BR&ikGFErL#~=NMVF61*7TGc>i1%&qeqGBw?>#*c zh{h0#XeT*!Gv&Vcwn+m-00Ik-gS?w9zwDYf=n&2Nn+}o4hg(uFJua!{9ltU7rf^=iz5D zcfAYne5|HWGn#t;4v0zPAvpgjA(?fnF@x2UAAKE6|e0(+OZgCc|3{I`DJ zzq5L*|L&Gcz2cLf`Z+dYiqGQ2z)w$(A!y!W%z5h4?4|rm1>aUAl#|Ihx6X>=dB$T( zGGdrVS(R(Z{e!2kzDw{t1ix*vH}16N5IdfO9@{to#&kzU#DO}kBY+~6! zCX`&Wo`j~Eb+%R`4<9n13V(C5YSaCGtPZxncMY1*B{(~eg zf_4I-D7Fn@f0_=<1X%YJs{WM}1gWa~cJc*i`e#Hu*XRkFNvLH7dVJU5wG%$QdgV3O zNlxg{Yj^xKs)uE!vsm-|2SJwqpkO&C&jxuc1fsDDPxSDDoY+#Vs`{;GJA-RqVRue2 zkUCL7Py37>ybJyXSayiEZa5vBo{_V6G5$UXyvAJ_-FFM91%wc1{msTWq%_cT<4bTb z_XeP|Ena*_B3#UPOSOfjR89|9@U4b0j}EOYJEO*wLFdK8sKEop_*>ZT`mMG2t?BwT zx4#3J0L6qY`kY;!K*J|M>_;l3Xt&F;K!WcvM}2#xxiY4zY|$2z{hb3 z8uUf%g|F&dINj8p?zN>A%kMWEic;<79zT$!^2viC1H|tOY>v6>RO+HXL6#*X?m$_> zb!m~^P?6hf2gb>Fc|Kp};Wjg18m8nvBqnTphjr2hSOZ;6=X5|39vTiSg&~opNKh03 zP~b=M^B%4`zclH}*&^iB8GvXtJOj4(Ku=TY9U(=sDYdVZZ4Hx#O4KyMV+sndmeO>8 zXcwPJ_znFA+{R}Bu(yQU<>EnKEo@6q0=Z^FRA^qz=~03l)Cw5HkJp_GDnoIa$cfR@ z)L<{ttoOf*ZYqkr*|tT42BDb9%el#iB@I9Glbm2mQZ({@diDv`@E0{3~D~bmgSG(EhsMs>Sh&`Q=Aoj)UlLWJ?erg=Ao7kb{PxayDGD z1a7gk&H|#?Li2>QQGdEYJKoW4C*1bwv(pL?5*(Wy0kdSiWJBMjo3Rlq-WWhbJYsOD zg+i3^r~iYTVc{=10|IqzM}Sy|@4mT;$7e4?73S+=G9RW5m6q-VF_5LM)7vUbxqKrv zt&g?;%-0*1AHgaCw5#T>nG0R}^V~o3F(grm!9P&cvL~Ww@739RaeuFyW@(4q*YUEK zT*Ext6GmpB7PHiO>daQP6Wi?5FAgimCHxSo1bICifK7T=(-K zVTMUz4+t}I)$m#^C}CcPqAnuWh5%l`j}PyEhDDtShqtqx^&iL>U zFay08w2nDKK9mTYI!f7?_48HQOc;h4x$8E%DKBF^{5}D`fyO{`o;;A)5hrTt$8P>T`+sQ8( zA~JzF(4c1^Sow4QI!kl>V#N8d{A@Uh6h74D8;or|9@24>Pl z2|=c%J*VCErBIax`BWkQtD;5J=z%$M`R0VnGcL`|g2KvCFR}}zh|9=jK6MAe^@Dkoe!gvP~@r(KNGATfstv^g8SEME2rjJKzBwXzJ2fuw$G{!nMB=kONM?J5e~z*9Zj`)AbC%d zkcRYcI}8tC1$gIu7-8g6*~e789Hy0&Y3l#>QypOv#PQ@n;%V#1RbD&ZPHoiinVk0V z7=ff+TAf>uLiAzBBw}k#m{(hWAYbr-H^t?I}CNzU`H z?on2{`=88dyRWO-+H8go5po8eX(beJP;St?0!!v`2rzgA7~|?&mQ)dE51YFkH;Q(k z?c&AmezBmsZO2dS0MhcV!x+0#!I;KNnT~Z_d!{@xsQ8j%<#NaT4kVE2O?bC>DXanS zHU&&>i0caY)=KZ=afA-W-S*i!cagT*;%mj{-gp5l6I3aKvs&3qI#3b%7`utBr0uHl zn7rq`nll5`!q+iV2Ag|_f3jgLujO}ZgE%lc7QJNHKZlD6WuRT{Ypo#Y$XdU6G4wig z5?a}VRGNfJFrMkGK+;^F1-1m@>DgCCs54w5AMW{H#%bPVKlWAqB48i5oY#xe>GM^t zjt2jxBCc5vg$Q%;7#C6}6zUFcPlEM+q9VC%*XK*p`30^PcMF+Z zo_mrn@hIs1=p1@JZJAnSKNj^0A5(K)p3AE>caW>$kAW2a9^?c(BDSI-4-y03wCCa5 z*v~LO`+K7ba*2s zhaTTXkdN_kOTl4ZGTRFJ`c8xrK$u7eSc84=EU}BL*zs5Bt%)@{X!TB`_H}4F@KoQX z&&PEYG@7{+>nwy9EC;oM1_6DjM?T|F=c05M(iV5BixsCTtw&FKIp(4W9NAZoWw=cy zbF9Su$Dc^CGrj2(4ZyyT$_N}czxmsut3WT{pj0bK2M3NM+!F*^7;RZ~y8k8X zioP`C`p>~l9%P|6Pk};Id1L*DD#)@FdGb3Ea+A%&;#}NL?l(COA~uf5Zw2U)AmJ`) zs_=9N|KjliWE=zLH80j^z2g^jOQKZ#w>VdVxo1H-PG!W$ejnt8L;hfYz{6vVO>0z!auy@1fJ>V) zgkr@-A2;s%QG{D0p}#jlxdT!P%9Q^S`g&FI`7CGv%HFDl{*5(67rurtTdb*}A%JIw78BSnXV%Me$$#5GA@oFJ z(|=88kMF&ztOr3nY{clw)2!4Nitf5({b!4gCT4m+`7FgaO++VEK_-e{q*YwkvM!EF@QW0~N05ezC%N_G=!qOD!72F2?;|5!@V^q&a&B}zq4d#(A4 zD1cOhusIk4{on`^a`r`as>QPr^HgHH-OD7Olo112SlPhXn#Wtw?g7Y4fp!XWO<36^ zF>2V}R|VOwl{V`E`)XtwU@(ea*&um*5R2*rtb&FEoWc-j@_Oj2(Z)8_jaEDvS?aPp z{%h@m5mfaHJd@{MxGB##X9+)kZq`2sXXw1ii6zZY(v}dw*J9jvE=Ja8*^jWu*ojAn zCP#~SY;xeAcx;OG5i@k~3_W{9H}_is{Q+8%-JgW5-b4Pr)Q3hJd-N4y5Z78A8-EhY ze8SklIs_bc%y{{DVP)>6$;lbquN&HNO8kbZk}~{HEoHmcE+`V@Psk63%Al(}7R4KH zdguUlZYAlLjTr2Bn~Zajv5Xy}3BT&(KYDs*{8^VK!0_xX5Nr-;KxfQc;d39;A=s-0 zB67aP8;ki5*gMK#4#X+#h)SQwVpuM|dw)G%0>!GHADwZ}FG8TY&+xRW^x@AZ#LRJ7 znIezhU$y>T-T0v?QcFsNffB$v9O0o)udYe;A!ULc782v zcB(RHW`QQ+koPTRW7 zeMXJ1r#+w%27vFVdYZYK7I=#foBNp)ozv{#) zEpFV&;0Q&S0B6HSZ`S|X7C}A)x}m}6ak)&vk9oN1^-NXA$!m`-RbTCr^`NEP$0y6EzBGTL-_K#O4-`samh)IF-_<1g{mwlXr1zv#N zgA#ztx57MM;<$)+iRwIIPp?cWU-Uegt3}`l@uMxmOmy7{$E18Dz9Qnu@TC4ap4}83 zZx2raur?3i{0--eg+>-z8uTO0vxk7_6f8?~Vg>fP`bDj^{1>ZRt&I%t&nd32|P~;gZPXM@q}(q{Lz{YR`Oq50PhKR784|E zN8~4pI)OFK<)#Cmm4Itt^2JAZl(`U%pxf1tASKkmUOn^ghyuh0h)MY23)<9z)Ub3KF` zPw=>qmG^m5$PKGawcU}J82S66d2sdIOKE() zS0q@(Iq5tMc?+!K!@wWm<;EG-%N;a4C*Iet4%1v)VLwxM**6Kde zx#yfgjD_*X;C69Tx6WdA4xvO)c#7)zLnyi)EPs61y0O7v$#-tKs=w3IaNTD%-N-UEmEbt%K)lIC__{0Vmm zHh!lIp1KV80J^FbnbQ~Gi`$@1aUf0&8|tzol`Dg$YX8Sg`3CmXYnVGnOlJs|skQq9 zj@3F+q&8lo-xNwHX5`&5cxhNF&P>$BJjB{Jotmy% zma&tQ-dY9~#DA(yxbj8ZE|R$A;`6hBYLbAuBP$%p8=qe*n)6rw0t^TIIDxu&0)2ke zB?iKzO$=@Jn+@L&2Vk`>W*RY$h8I^iwTY?^rL(S_O|eKD*BrMmu6-=G#MGV<7dN#{*F2t4!Tv)>xSpo}PN*PN!-KQ(ejGd#3FP`%8J6 zA1HD@OL-qam-FE4$kInayIRnndg!mmXD{#aXM~ye0QlHk>3#OrQ;K|@lSN1+-V!9X zi=V3-=j(mcy<2+d*9C$P80&h^K?A1k5>eRDnPKh#!X}dP9qub2*^H=A9YPSE$=m&* z3~Y)>R|AaXZzP9v`0wAC$4=|vy>hIhPDf1@fOZ6ZIZkj^1f>c!Bk;JsKFEdXLEolL z;Z+9>ku+emXQBJALJ$0TZpdhODFbIr4Zyvkk*OHc_6`5=>%n9mN+(X#e|6p!>Wfe6 zH}g5c&M6Oqx)M08{YO~?jYp%!P*YO=8!!9BB==zPWNu2pGhkVhnk-{y2hU$zJ^E$L zQggpxJgiJ$@N++ja!A*l{JVI4C3m121!+zi9t*0d+=2yx+ZLY#CyU%QfBrEi#YfDs z_ILVJHYTW_lu>3ex#Y%h960Q0aKQr>4rXGYEYMDr6y+KGJmB5k!c|wI4w|k5_h4RD z*kTYw4op5r_?y2{!%5P%^*#kwwYo8zvQWk&KXb|=UMpmfb zDp``M5p5uSPf^ev;5^CGMDOHJW3GWUADKHmHWoh``LWq@c6}euf0_t9HU!$#L_Q4~iEg?H6imN&+l{siwlv!}!}ssz94$+-r9w4*#fZE(scDN+?X2d!*d z6E9{JW4^10Jwzo0pCVJ@QfKi}&RDI1Ox)(BgVepu%8N2?HPw^gsNl)T12cG$X*5SF@mgT<>r0L@GisPEPf7gK_E9Hb*_Iy zXC+d4a2bUkZ^Q5=*bYIjdQXMg`=gIT0%LM&qu-TruYq404?5y+QCxB)-w{s__npkY zTl1i?W6pn4wjSM@4#W~^j+E5D&pD@qW&uk9?syGKVApsmhmmLyDXV<+tRXL@b$v3y ztk0N|={+FO>P{Fa-wy{@O5m%0UfyaqL2!cC3#>j{&<+F?6hM6t1ddHO&v@ z1fql4cj(+!8LO{%l&2VfL!mu^s9*!-4mNOu-xq~B&cFkYMWiF$9lPV=AAYA;+jci{ z`LiNXE5u<2I%D2p>f^OBH zHKfF7^@Kh~rm-;{O7M#W0y~nYaBrW^ly;_8Z`@9Su5|{6Qpl_E*?_aSCf9+ZjsGq9 zjdvN-RhWc7ojrKBge%Gol)e~o-KNC{LZ(cEW&L;Y==JZfWZiY;LLm6V7~>u=tm@%= zCDAI&*ocETpx_M#U{wD8ivCKjs6Q&0IHTJ)kc>NU#ujBGsYyoL5{8<9_I$^R^DB2I zBwI>&mvEp7yAx0CV5evO+QdihI3{h-yS0VUh|eb#_>p>aIicI8_a)o#KPV#yk4|p` z{{5H^q7F<)>lm_bC`Z}*F?Rh(P@X?QIqn>5u_@`bJf6J_Dh7SJa+%LR3A&t1Ih!&B zx`M={1G#F1{B;he+<*n2Ll_N zu^j9diLVlInQ-*8Mb%YM%x5z*yFXiBzXdtZJko9Vm!)E2W8{0^X8g&AO^ATTYi#xz zDx7vi6`A)eP{ZhK=HdAA?TY9xmU(;lDH#3~z~(@4i@+%ij{*T3gr6_~wFsOo0(cm3 zwnN|#hT>2l=vFBn!0SZ!134|SlvVKF-^YARNB7_J$R+8MTL11foGdiR$p7S#@hYQ! zFQDA=PHD}Asm9*h!ct8?M?c>2iV=Hzzdxnhh9pKME1Ik^N2DP<-I};XD7F*D?gOE{ zPdq@)L4LQcXV351ihoNtVR3R*Bbf zZ}zDi>lhbFEsV7Ga0C=_T0E2?!EquD&HHbS#(}s&oO{LMUx_1ZIOVPFZuUhUM_z&V zSamp0Pt?5mqm`zwmatuLgV@*i+=*RA^;*;_dZXtZqlj~+Tz6|>WI*xs0}DM6#1`;^ z)5Ticmcm|xidb-q{mjX+;cjz0sBEwNmi`0BeddZax3`i-RX|RvfJDL15LzhLj_^69 zJ;$lM05vpFUD;2l3_iRe7pNdQfk3Pef!gX%kGPLGBHeDROU|q>DgwUh@~da_s@YKe z_ALWlHX)nps*S=Q>iug7u%J;?w@+Y9KvwfqnwugUqiALMi}DTYC~uBU``0(uwFAM| zjo`HT_v)L5w<#>*>Fc^NhKId&p+r${1D;AnxOIb5;wSd5_s0}}T{PaSM~-}iU21pb zw=(#G0i#O$#f+?SD!U&?ygW%vJy~(u-f+Oyn=KxJ&RJVx(_n4BH92?UH}=NG&Z^K@ z$cE@c(#Bi3ot+g>#Ie`vNJZf0rt{|J^74peS5E>>giaO*ZI+@k$32&Jt!}M3aHZdD zpcPway=-MqUTdwZiH33bV(AcR=y+(Lo#H%eEP>M8f?%%JkAFzQ;B(eLU|Br0O`|;53~=t}@Hi zNc2B?Usa;DJ0>-R|842<;PMT|cl_rMGE_G85{t`)sMEDuh&4lQ>`CdAU<9V#X*lef>R2mpy;c^0+pF+=-nl*M*1>?|RPbAL-W=F6H@RVtTa7ZuO(&Y~ zeZ|v8MRIpvv$lWv{TT%_aoBy{|NFJeO}z3gV`{CpITu#kC^;Cnt+7bQzPQzm3XADL zL0UP*pf2VOC%+Xsx=#%wEKdK(awrtRs_AG|_dz$c=PB-RDBUZL>5R(lrn0K~f+-US z%^6>q%7z;M8mrjSE4XnFcXLXR4ntUpDEmdbinZuI^!chi%?G^%UiQa5>u8unu9oS; zSS?{)!nw$~f?X-N&?b7Ew@KF-BDWf}em$m=T&pK+bn-ba*`>^mG7VXwH{BBO(Lt3? zC&3WT@Szxa!RZ5`7?k;wp95{`lLKisP9}}i)aD>4@ZOw)K^A0F z?Q?QM!mY9J4co7Fv2Cv}{n38Q-p6Zi5fID&!N2%^xWufNisROgxW}~!&o>rY2_)d_ zVu1(9gRIE$O6weseP9l7l|vp%y~24-RMp=4kM}2>fQ-oLEjM)87I1w1L;iIjE^B$L z7(xripCojA<5p763_O%nGVq_D_g!7Qo|)yx58iL^&^S??e?pCsjlQp*aSM=5f&5Az zPoP-f!h+MDV7Wcq9uUYM3f#x#1@+S|3}*VmV9XFX+a|mfq(oL`WICNUQbUYqZtV3$ zrmfy&9D1xK4APzrc%c_XN_x#!*!F3Vv-i5-_!Z-CN`B1oU5TmUZ*bV%c%(%~RK!s2=+C62Tg8Nh%8f1Tc+m&mzK3ql-!r=9VIN^@VRG&Vp_iJ;Q-k>q|D=f@cdyqD(tj`B05T#Gv? zrzk>-9CVh@sQ1<34U{(5^dh65-TiK^#Vy}%w`t=lL*x_H!}*aW*@AfMwS>84p#5k~;(!tQex-kbmr|Xb~ zG|M`e&Rx}3L~ahS*wD5bQ+mEY{iEZDPPu!9o z6oa8hi#o!*7N-7;9d)Du*r^V4m`>N5|Ix{Pbu)g`X}&Xlx~Ck738Ce%i*bzmu$rv?UO$x z4!=L?xnD`UP>%|`ix-+ad5Nm0A6aerk;@X|Xt2)p#{rdPwV#Qad(4d@%E)-fCXQA) zxTN1Gz}K=g?L}fzbZEe0$6tMmJjYSk9v4W?>oKSdrdfD)o$*WfCoK`-CM?FVqst34 z;-{Z|Z6B}(qF~oKlu8``TV7uLZE*+Zzzm41HIaL--59acGNXEYccuC#BB`I6xK)9X zR-s@6UH@x}9nqbZ;<%flfu{*?I9^&!Gl9&1$uRk*){3W-fsOI;@DXCe|!W^EK+IKBe@r7z)^=h(B zF)IE2n)9Xj2VT7J2SmxM1MzD8()Sj>#j=X&oHM6!)VwTx9+n~Ew%1;;Ja>AWdXT`y zIfP|{30s@By`201{`10(`cVWwveu@v#&4B(MR7C9;>{WYk#9zhZVVqFkXxKYQa!L_ zZcIHH!{=wZ!!Ujj9Ekj;=_|W;O>ZGsa9WtJ1FyGuH65W(`mM9+mXw_ zFPfOtRufXm$b!)7RG;~J@Ko)~t8ZpOeoT@-~gYPn_6R)FUk2V-H8|REXYp zweH=``aml+yA62x>Y=;Oa+fDScuOUL`GexG|8oC-qrlR_qoCxFA^<5KzGENJnFx|1 zgWbdrzK|D1hl7lc+^UgFt9!mb5k#>oOBiQw+~OP9)>RC&?&r|gobW;CCl`u!=R&b8 zJ@q|m=rQ{{# z+z2oErE<>rps4Rj_2TS1^(L;H75l1T;y6^&@-gVF&$(Hdhfh=ZKLh)GKgEGIVYBS$ zaJWXJZ6M}IJfvRMDR3OC;Dep-0WGaMpL}eF z!MXqOp)aDY_LdbU@hE{NMH%zUeV#pW&unBi-K*IB8o>IF_lqbc=^!jA=S8ZeUf8EQdUocBxO-m1L{V-Z5gJKQvKdC;6kf6Y3% zqIcFAwL{%;niF_06Wv$cF`Ianok;&ba4MBOhrrgnd_JtqT^8u}ATsi)AaFUy5mPTb zPLzs;ArUIQbG0F>noG;5xcdH?4Qro~9KV$$iqcr5W*EVMUfv>= z)7QIDK>f$}nP7`Fd>dRx#}15EGM;L&>ND?O7}&n*;_v*}c%Q{Z_~nr>D1B52=oQ`@ z>!z1jxBDe{^3DE@(~U)b&oX}xbGgIb(2l5-92XbIe@8ce)tiSth@abMb=P@qr+lzl z70>Cl9J(vMy2!V%z8LLth4DJzIXm$hyNF<87KvyrQqk->`K_m3^X37K9(=&*ZrC z?Ffqz9!U~II4Iq2*|&HWVh#GMg622Re5R6`etoTv{jR^R8hbafgXBxuU03Fi8Fy3e z6WfH(tIV~Zv=WPJdA};_t-X1aqS9Zx+`T5!u}1AmkqvEM`=20173@R0^ve*2x04*O{P*6+q@AB-iz5T%#`zZ<}}e*mQ%kDb40ZaN$4_ zF1_}_9e*R*-{rZJyg|EaVzh!>?)mw>l#lAPvk#hA+iN(v-vNGb8FDF-we?0d}j z@2S0c*!0MTlb&M7s^cvrSO9T_%p$U!(*hJ-0mYq*bS#q($KFZ)Z&jrVE~Vh`p^sRa zG^iw)ResA{^n3=8a086x&N@2^A-WkluWI_HlCOfn$9|R!DAJdikx~W`Pb~d!obim}_T!}klA>^S!{c6O*R7TVgsugnKN=MMF(HQh z-u_1&+TpGTzpa_r7s7#}xWa_^S5IEsymjol2xP<;fsD-axkn{^>Z7*ROFgeGD6?bJ z2Ijci)w}bE-#!g1`QxMBozii9_>93O?jUKid_ zDFef{PjlsrGyW4UT=>4oO9=Y;249O5EIW(yL8LD}E8$@12-=rEB#X};`Z+?co=G^G zsjPDr2I>u@JHUaj9zWQpF0wZR(%=q}vEgkiLijqSSbBGKgL6oJ9jtu0uJH7Ko+xGOzFk(h}-tMP;X^}&)S*u z=0smF0)Db`n$ZEAl$X;2=KxcJKDHkk=#Dmo`nk&me3@BLH7@x6U;e7$4+V$3$D0P1 zz3b9S4+U5cAxLkfLAY@3CdTU^fTD3CGDX$&T7e6PimAslXi~sHVidjAOkLGNt9tI4 zt~4Adwf$@Sd=wK@KUrpUCkG#zg$G%I1Ak-}%rOQO@RH1{ySq^NeWK-C(hpQ0D#XxV zU*jcb9=%L5aQJqVLhbXk$7-@Csn!M()%BF3)1sEh_fVa%7J80T zq|Qx(ln7h7oUq1@np1;7ayoob=!%ZHv^jx?faet7E^((ckx$B>`IWxL`>nlkQnj}w z+8NDwoA0-uU)Tl#3H;)1c-~YjZ%lE6SdzpqJAS4~zs6|xo`5T(=0bj7XDla}&8;AM zrIiPzrD$ACgCOM@V_u?{8M2|0bowJ`J{!TMFsJvo&t3nA# z=pr2q{Hvpk6rJV1HydAN-6o|XqK_2!Mhegm4rQ0l2o1m88~LUBTq0vt7UL=r!W!>c zL&FvP`o%+ILqWA?KE=^JS1QWi`#N)kyExvoAvgad#M<}LxO{w&Ligr>%A6{gjG`@V zN*40fiUBY%dha~h0VF{>V5p6tD_G-ef-?i(`A7)oyf?cAnRrrmxA6N-wfC>P0iP_N zznDstbek%m_QViXM}Ku=dnR*`G~4TV_HkBHeUaO?1=VQ`bkZ5W_LF$hi;T!{yxDzb z<|)5Ahf(m+56bgCde-TBvxR_!qI=Zb#|QnQ)aY@G=Ow? zXCklp-su7T^X#O+s)*kLd!zFw8S~TPhW}I55+W_67?5*=FFNlgLiuTWAe|r#i0$(F z>cmYgNJ(bh#~J!LXXfXOSg>W|Gn>E%8euipdEqC$?=ABxf`H+&n-B9Z@_*+82BC}6MaZd5s4X0bVoDhZ8u{azWg^4}#ILcF;eTVK)? z7tswrydgJ#!2?#bWF2j%!i>r`fX$TK$!dF|SFun}(a~Gq-(KV|HW&HJXD=O(GWwUX zL69NjPS@0Ljv!5hB2}jBe)pWe@KZsP0o1_!*%9e}-1XlQo)E*- z&th;PD_c@{9VMzc@G!u8Jf`$(otUJ5Jf|CJ+ZYSHFuc$r1FDM(-^Bj+Ay#6?FHYJG zJe27HY58}}$;o->p6_jx9;aKM?u+pdo0>-N>M)Ka6D9k02C2g|?;59B%7?+Q{-roZpKY zD|{9PA=j6e`m^M6(Z}bE=TPro%$IEgYbKqDR1=R~gL41Rn1; zK|Ke2R3Q1mzFNNrrs%1*_n7mWYay0}?Cg%0AxD1Rmu(~b!w2X$z^N2HpRb?t$!HrH z^QPMU1>g^tX!#{t)t71KMBVxsz6MlrWPJZydTit1FwOqxcVq2A-QXVPB}Mt=FG7|y zCI<+u?2%kf54AB>ybk;7*8x!9$qI8`2265U^F`X;SHp_3r@!kiz9&g=NAc+3wk1J8 zH;7$e^k8MuApPL{wD<519^J)!CF}a+U`eR4`wP-HzvByyzFl<^X`4$KjVYaa&SxxcX2Pp%t+1C;!+ zNWnUn!_}zetsyhi^ztVJ*2 zHmN-6!Bi7J zMc&!@5?v=;?W&(Jvfh2r#Rk3t4#X7n$8-8Ql5l(ZXiR9ug2ww3)A~f>!aM_n>#P?bi+lChtS!-IdSrX z&m18l)y3cQ!tV1dsX=M4aJW!uc9U|rkZ#;{Q7sU3&h*T#_%=kD%|#R7YyWA8 zGQ(A8V2edB`B#WYKD;byJp9*|N2THQy7p1+arWB}uNgjGy|b#X;=&l(YooC|5g9Ff zl_)a>?9U+Lr=2M$iCq;GXSs8M>~$zImHd7uP=SBAc3tNVI38Vga=UEW;_E@sh<^Sz zr;E@E&JZuS@{g$@cx=7bW#xl5l8zYh*3Vnq!w)V@Wtxr@Yg4}EDYv+r8d{&UiGjt{ z9(K1xtw@@FBAy;(dwv!duh*)3Y6P}+&HFVPsQ%+KGT;|_aPH*|HN%VKDf!`rP-~mM zSBC`^nykNSIqG;(amQY6ZcOcIuAtS;T{69ve!h&OKQ^W-84_exKJZe zD$IIj_imdDn96p$5mHt88bA0LId|%O^i5o*f`!A_j7V9rYSRRDU89q>~gQa zC+x(MVF#v|7bec64#e%i6321W_bw;USr5&76${h7_TxGqXwwSgSB-yra=-iH)l-Jx ziURYnPw>|BeRk78Oqc6ru3oUQhg~wmbP#w4hLJsf1?4BSPYsVL^~!PhU&)`dfA^lB z{hf(4=M%9=NMb{kzA>Hp!xST!0sUCM2?3nnf5GN^dl3zq{R^G#cnQ#Xauz&EsG(~8 zB5r4r4iZ{c%d~CK8p`gUtI0&roohhYg9QjZ$25_a{3k?E z9{O`R?LgV$-uaClpZcyGC_ZeV12ZIddw~s|l+&yzv0-o_AKVkOK`=%5^GDy=b$U9V zR;zvx%}t9X^WDhqyxphLm?@K@n&P$>*h;2C3lSEt{$UdoEsBLUo8E7%?fFMd>l*3) zuKwAtw&$Fpq_lU4=Sz>I_tfTWpN57CSPb`kha9;Mpb}j~`iD3ImNgxUh)Gv(xQoh+ z#YbmJFTW2^xT>E(k>O&=bCO)-!0(^}u7>Wv{a10|gfh6CP-~fRA6ev<^Q>VMiMWJd z_lL*H_5^Z+0{zi5!+~E|zSY*5krpt9wJGzxpYZL5J*iAe>42#f(dUD9G+`E&U{7+Z z?5en58Vg~(jKoJ+*p^#OEKu)7|0<2N!{@57{ePzo48f_XKP=gv?3pgU%wcL3v~GC# zTLLMS3pob)Q5oHf>=3)@f=s(P5IrIGtK{)owARB{KNON3nPnxJV;ifuS=j!8BzCEZ z{qNla-wSGQLMCno5PknR&q%x&;AM-3a|6Tj&pAcD_1`x|qU?|*jMDgD=F z;)>O0D?5Q56?zU!Qv}=bw&I)NBTYp5YIW+jCVGQZ$Eu^<6}=j4|M-= zd;*o`%kVw^$2{#Yn{(Yqp2;L&^ZDsWT}AX#Xh*yuKroE*G--Q=+z{h@EA52 zJKDQFj(ut}#i9cV?+JI?7^0z5bcUUn%z@^FUP%vWagzEUuT~E$*YEF4mHYY2o+Fbi zWnQjzYHVYucH`LDxsJBRi^6-jp$^M%8#Xcjozr%c#^aWAGL>Dn1?wlxRN%gCX398n)rs)jm1v zk$TIGShDTcod_Nhk-B(Jg-=F3{Ss^bCw+oBjpEpFIc}HMrTMN1!>0&=+hec{w{Gq8 zcW&C*>_6X$w;^OM0EV(44;@#6(#d9fAxBe*FC0sAxieE%F7V!|bJ^n1Pv2+5aB6Zt z>M)M_^47CiIqOPL;7N7P_SJi>)}{5X%DV}aT=#&{gzVYcfWV$DxsCbbX^VutMn_6k zVvrE=3w+jVcHdI7Pc$w4@1hjqzB*!auEe(|0vR(R<-9KDGt^g@^x^qf!KC#x&iN6>t|`t@+>v8P`^}RC)kk;U6?0Gy3FXXY%Ap z#Q-8jL3rjAx1hz)u(V1CAaoe}b=i!>8ddv$^~@<__s-n;};s7|!8o z)=$ux016dU9iMPV>3mm8Au!SBJG6cyHtU2^4n#Wd*IAH( zB3*g;z@4Xv!KPu{`Hs`8qR{yEuUF~>bWDbnEHXYm0O!N0?%S@7U)!vCTrym_?T6PH zw~E=hVl8U;w_?FUdS*>-STH;}{BS8-g=fQ*Da?#GJtl4W$>m+|9S--^WeTjMR>u{z zhV|#M*87fc+XjfUdMhd=9cOPKN*wLR>SHyY+jf3W5UxARGgf=7=PFBTz^<7UJnpj0 zOjrqLdK9)+;{-ZPt`%}vfhh2Av5SNF3&mTD!vVg6CxdiR?Ak{0jwf^4JzOX`ZTvxm zVZGdEfhIEzPta)}>zW3Yb5O-~J6V{>P!;KMPAeR!DtE)b%+d45bb8t4)lB61 zB49qmP?w)!fefRr7Qcd6Jt$&`*W|*jdez<@(K)#WyL$#psQ_kbECiM zDMj$LxmUT`hKAI^e%FFiBRsf=nViwbTFlb6)>(pfrpNvBO3LyaKG9z*YVJ6NiUEeV zI)k4JcdKRJCgWADvBEi(I@CxyO1SB^)+073Ca_`@iglgaiD>opN2U*47Xz%_8GJj~ zv`fr-RsUQS6LG<>Ljt#AzH#6Q<|A!d6L|2G+%);opD3oD+N!-UW;e~5F9#bSnB<0o zV!+w)K_^oJCJ}Vj{e&LZNz_Jm2U_!hyGns9Qxb!EzIvoP|0v>jK@2WnXSuk%^>EsU zj)l$EdN>=U@U7zf0u&)$MzzAW^yL*<2u%c#XM7Vl@x zns5MYs_MiS2j26njG!Gm4$h#VQ#u}L*S8H=baB1W`ceE9?{vSL>95vG5~Y!YnuiN1WONv!$GsE32d-tRsk`>{(3ZG6y# zgMUM=qKz_~WValO+wtZI>S2d8uX(LoDy-sfTwYx2yehEoN}? z+}a702Jgj!+gi89LLppyQLi90ClKnfmOA<% z>fn2%(nRN={xj<#C7o3PD$NPaF{<<>pC?P{kXv<891l#qRr*s081CM4{!;5Pv2FV$ zrY6l-O(OzA`--r4;yVBAfV%^_zq`x`GdKl?I{rVl-a8)7uIu{_kr1K<5mAN^L~qfV zhy+QLh!#;3J$mmmdS{48bP+-H-lHTEqxaqhqcgf;OnXMo>$%_aey;a#gZUiCT6?d( z*7x_@HcMLIi=$7f)J=`6AqI0X8N(se$qdt>FF}q|YNxPnBEzj1LG^0CQGU z?b@%;IG3Lvm#d%&b9P-ZOl)W?Gg=?@y%Ym4uimAP%CO@hppA{m_QKE|oBR7a7k`97 ziW`_Etd;c9A_&b26pPci=mZQ7=4@g0uofxO?>mBGFF>W;c{YWW0JMbTd^BN0S&0bc z2E^L*L*$R50P*_}g*Mq^(kYywh^WkEfYOU-6jl9c;j~d$I`3ObDy70VE!~;R0y)2jmd0SY$&xAS*;#hs}RCLvW*6FiV@L zy#Xt4<1*N9K?>#J=WTFbU+V8P%wA4XW$XQB;dI*tW7RQ(KF-0bZ+!9P>sMTrAH-SR z7Yc^Ez6Uc5!eu5~yZYbuvoc9L$*iB&TbmeR){z`u zYFvd^xh|82DpCG_<_x?xh>ag8t-_*Twguxoi89^1W6|&kEYr)Yzv)Q zPev(T2q$uw8h67Rdpn-?fvzDZTK3z3#hqyfgbn^u_^{k^LJdpTwxJa3TN{* zUXN{jWh=yh*acy910OR5woUv7i<^7LBml?&*s`HiDp)-wj zB+B?tNIzk*IL|txngr!f5s!J9uT@>kF74XAO7%wHG(;HugTi_H=I&Y{)eLCOR@hs7 zOU}1^+8+NpH(jc>8sW5QOAzf66*YP|G*FLtjBgZaUt5@GpVc&*U?BFsMO0B| zFTbF*&ow~dS6*(Zw8LQB!Y>w|!%rhz*H4Uti2O9Zb=6NdO`asXRGdCh4F_ZDs!$V3x}b|65MoTO&Kblze-UdhvgX=qm5|SNY?JNl*MBs(Yrq!Iko+5jNRFP( zH`Kp=WNUj}ze~tX*G56qV&m#HY52LtwHYtyoMz;`{VS_y{jhPSiMauf{V%gyuFDRg zom4g(UcnRfSU%0&1GN*)Wv@)}3+7w$_nJ*MStF#c77iL`=0*!2dX-RCb^6wMt2v!5 z{y|*Sec#i};=es(s^7)AIe*8z-N`?u|s(INdk)S5@1>z0>vA13Vr2`N|XPaV;hnanWdo zKG8&E0LU9~BXXH&g<#Wh24`rS?^eFj*9y9z#)j|!Ao9{Xz& z8g5fz`^F#3FD)4iMcNM}*;$XU;}+>5R+xzMvEhCR!#^kcEEib=_Q zG~RtcY4}vtOPKsGRaz3%fozC2cuO(?C8UNj`}!IC73`DjEfuQNQP&<(gerqkikNG% z$CI`P9+~F%f+QR{Ssy-sG050DBebJaDhhF6=C{TyDSvOgYLrP`IzRKm{OPFEuakRV zLuR2i@!hTmDb;d+J`4ScyqO4JY4d*MFjeo(Qhh5db`Ftg|HB;b6}jl!z-%<9u=p9_ z57qgEpx>WTY}FwwVZQ|1CCRf(GiMQ1kt|R%#a|0MhV{-!`y7EWpx{3G_q5Zxbo%!1 zv@nZg?;YCLOsEVPCKS*KR)dr~o$b{WmD{mpHQh~eH)#Lh$d`d?o!%K@tc4BmZOpk2 zE_IQYWE?LfloIb62(M3fNDkGMV&=+fWarLA8%^6m${XD%Nd1XeLwcLeMob1`0}cW1 zO$lR`sVm-GOFj6RWrp2mXg~9m@*}*J1~$5!orV**pvg*VPX)y>^GsPXIQAXdq8Z?Kps4C+0iViYcFmHf27{8z8avAs^{z80GIgVZu8PA zJ16<(Z->RUVTCmAA{3nF^B%-zj4_=HtZCA~z=Lyxszugy5ux0%EQQ63I^uS(F$w(*P7nUuZ zkboU`9BfeyN7rc?_`-ItH-G~CJ)a|~eiG8cr0$=z@P!q&N)HzJ6`*o3tM|bIT&(Y> zd!S;jua-nCtyuYe&>3Vp3S*c7c_DevBMncaZ|439kLz+kmHRXvCN60>lR~AWpCu^U za0a2M32`Vq7N!!?XIc5SF5io0W8##0Ua--d1#R_?{+;rv;Y_~mtSuM-L4|TuTekmp|~uQN!zwggmpVRJ42b|^S5r|6I6 zN}Au0_0x15POUo)jrDJGt(2Q^3D&q7c6k3y$JSu6R>$f*w zxdwcEa?vC4%luaG-Lpc-GlNDwk^;tcDgVP>xu3O(1-}&Uxisu&7&~6IY%xrlRPJLm z5m$HZC0uROmQv+7<(vs>KmRinK{y;}nK9$v4bG5I$tw=P=A7H%4C+4sh}_6^U__M~ z7_XGHATJb`&?-%mWCJMFv60%R`8I$clYRm7vtOA0W6^1_zPR5lQwjd&Td1n+8+Q^f zwK(4ZZE&{kAA@x$$v}?3pA%XcKw0|ifTJ5gzJ7yGH>AJ%2KXdhb&BakuvmcAS1meQ zIRTN*`1f&H3DI^iels!_5)#R&lRf=oJ3me@N2kR@!UQQU`BBIRTe#&AzKmnLZY`!` zWphKg3D<9KaC@L1|L3&RvfkT*{{}8cGEc*ifhT55|A*-IxLKo#e$>bVaRe#CCC+LZ zLHcyG=`+GBX5-9IQLA331Y2PPTjClJh8j3w z8ZZ}`>bVmv%a@|1HvKj+I-w(dj#o@%#vB)Fv^ZPV}LHzUGf^AC< z5v40Una&gWHJZsHIHjRO>6LfANXwzsfw(<8g<0PiXF7lBJ%J8&&CW#6z;B&ZpFMT8 zcKKV1pr5B!&y~m0XRo8aU@s~M<(}~oy3)qA>r+BaYM`xr#c#~d6%qJ!-Bmn^KT0`6a^_Zv`D znm;vecfK7pud9tWlI7hv^a#-;ePU)7a2U=3<55%K7clc(`|QsDkg={M%YEV`b<;pl z6Tp~_EISJCC}tnNeNED-+*Av7_L^%0FmL30>`d)q67b{DUk?BB>RWHC6Lz>h?cjPqXly-n(rki{{u7i_X|(e)MkPm_YzcZ=sKu!oa)wg zJXz>%8m6c)88^(9#XgPIy>q&3>d^e*wYh&Rw$b8_$G4d}6^90-q4A*x=Wx4CDZY18 zgTFKa9nrDS=6rE@3b;8<8Ppn3VI$?ZAEplD0U0Q2Evj^8dTZqu;-q(UO9?@?~dR?{R* ze!nKQ7!DPadZe_ZR`Smk#@I2Mo1i;5x65N!V}4ky7dCpNm( z9oM%nzY}OMheycep_iK;gip7I*}1uw%SaD?Vbt ze^;nlO9qLhr=cMFSaErx=a0NR(K~(Ci=+rn%{+c#nq4`!jqQkFdh?UE#=U!Pp>SrF zN=|E*>O^u0Hlj1OvCPX9F!qO*<8g@YWV)7V@EAl>e&kSfmnC*Au3ntV6#FlE|7K}_j4ynUnlT_8$hHLe_ zK{oALz6Nlwghw7O0cZS1j9aZU)i|k2z75w!o^HA8;!CN48(H4sE%)0NER4O>PaqUy zutm|P{A4}Cq|KbdxKTI!Zkk4fA_i%K4b)G~3EDtY+YS!pds?@G`mI?-mk}hGCA5TGm0ibw{n~i~FQn zQ4bWtl*^wDbA@x2G;>{FK6IzkI@P!~QCs(U*seSH*6sI5<$L-9Dpz;X9Q&X5Ygk*Q zyou;=%Jl!C-bxJsW1i)hq_+j2dOP|~P&)=%0*)^k{8g5mU{Yg;hq-YJVMX&^C5>Kr z`(E9da^6mZN+**>` z>XNU8k{-sY*ML7J4|lpNUu8)bnufbS?`2=VQ~agO z0Zep9&-8D5lj4%TnZy+@-X^9DP7U^DthDje_?_KOm!p_xD6fA_tSQnbfc3SVbs%;| z>3cM6mAHOMqW1|~)bw>_7a^vgCgSJHYMyt#U|%nNl^v0ozWoH6z{>i<^~&yv(p9#M z9Rs@`XN%}&_SgxrysytfD8{Eu{T+P>YGzagcw_QOZFNJ?mkSN>yqF2vkc0+*5R0Js6e~d2KZ=_viL$w5p3g4=Mlmi;nFFi!EKSeb5=Y zN$*3ealu$m3aThH(JeC$#Vf2?)(R3>&Vwk<9tIqCF*^^m0%;0+HA}XthZ@AMQ!834 znLp$%IXhavuGt4l*{B7Kp8=Z8@lK4xLrtCy%ce4rP|kh2-A)45(CTu3ElV2Urhc%g zz`@3hbCTyi4?Jn#Y8xV8nfgRT?(P-0`WJsyH5`Gb(i1z|Qz+cZNe1N@&V_w^55Or& z;rOxFrxLMo)j|$~owd$Hk^`W1WyhK#Ng-9kzr`7WE|UEZU1UoZ7MoCJy&!3qoSG3f z2Pbh7>s5OWz`0}y*eA63;J=WUh0V+p$7Cea7}3+Q2v-B`^M=T!Wd5|VGHL9Of6|kX zoLx3qm8jBeE_I=iP_;P3Dh6yiFUm(01l2eS{}RY9?T{Fz%YP z#sHHg_C~k)B4=zi5)?8`r7;CiHeY=zS9zNbj$^{FS|dCD1YBzbuYRO{8F0RArb=q; zm0Gp@!~b+*s!KK#ptGUee(Qt#$W8^`x2O|Ps(8L6Z1--7cI7FRQk!PxTj71`Z9 zzX;EBO_){dj7f^>^}q~FXs6`mz*)@QO-EBB_kq14iB}0R+URhPtQnjg)h7)pmn7vGA<3o<13iC5biU zW`k*ZjTS*JX5FuqIfnthpwD1*gPVQExC9v3jd?8dpNMzQd@~_jH_>Slbw#WxZQ9_^ z?uD}B#SXPpsm3KK;6ZY`-C^y^S@VSf*?cEiZIR5no6T3QdZn8`+(e!QRsLFrhHIAc zTAEIM(`enl`#dOGaV*W#P#rT&Oi`zn=8NXbnSmy_IRWY=_eGSKeyzf=E%--LXY|9@lA${?B;JSY4`(}@5Z<>gkZXe-3CiLs9AvU+81q9KDkenmAGwF8BmKGSPD*O6v z_jWhGLHULD>S9r+kF?qD`r&N8%30G&ZY0~0#Zaa&x`KUwePkGb-Fy}}f!aAVMia=Y zn}puGs#hDEtjFv9kX405So|pvcL<3yz(*mgm*?#_T%Gt1dF6d>NhcT@UL5ruo3*yn zZFIVCSVNz*gZ(yK%}lo*o9odmEjG_QJl0Nh@Lo`qJMvjs0j4GO8mTc9EEn4-#xmnS z)(KPdY&1B1d`h;h2~yr}(q~`T)hQC0bJ^u>yfF^tv;5&)0TgiGDQ1zRzWfxtAT zWGznU6!wpuwak5iEV&};s!gz2J>&3bTRFrKJQP?8Q~uX zn8x&q3iwwi97U%;!Q1kEPkt-JFNIYiXfHF0lY=@mkP@BtPkeQ z-&hp05ut4r(chde^6n*qx0AAZe0l)LiNQgoU8Ayh9&b5?Xm$JRNdA$k{x2YGVA5+v zl+pfL+6J1IiC4LQLUSqdcok;tyY56nCiwG2!P;b9MaVw=P4n6l%~4#(^G8uX@1zH2 zMud%kEbUwF5b57?RqEpm4XEYAhrj7e zZ;VgrT_FFKUMx?2cMs3kyr7E~5QXgt+XiX`cA}p%=@J+O(WgV77xJ@Kb?wKfhWUEj z;+d!pvOvt(481^>f?$Bz5#S$k6AW&IRNs}hL637I!lUEsSsQv~!OrOZ=g-3ineTqQ z3-adDghnjNn^oRDVZZM5{si(6{$#YY*jJP`f|n*{p9S z9GU;w^h8dKj$eQLC>y#}<=Zk8X#|Om{De!Wt{?z6q^!Y7*ys$oRyuqH++F)hSz$1c zRNx*}gLm4suD6jO57pv_kE7S-tcYX0YydSqcvb$t(w@+Sj#;n|&dep|``^+wq@w~q zg|}1jNP}z8kCsUd!qY#lWsYUFzeYp3Satj~(b~gq#SUYwu`_WH@<+Vvq)`_Rxs<*k z`{XL16S?aj^A|ZbvSV>@6Nm!&3M^FMMLSC0|}Qhis|R7L$s+tRbx7E$^W0(D^D0=&84dS9!C{ zCg?za>~dP5)?Sq7wv^SlRkciGdF_CJ$XxJt_n64N@bzGdq*x{(p8ycTy>)mLx|9(jjH+|CTNo@=wH}$ck9hd`8orK>v!=91-B?B3h%)JfL`NdKRvL2TT z_ThC0jeg9O3Y~xdNHK@wXovq}V%k1l@n%X6VoXtg33m9yb3KQ$dz{}@s!FC0B6T3C z!^6teMX?2V%@Yev+3g`eJVf|5Y_>H>=8unc23Nz`k%#nuc{{zwL8KR#!rqSO932jtQPal~39Xr%P`>x6h_qRT zKBCl;E3{RlG#ec6-MVHwCV^ymUxQq{P8oy)6a!7PB?FsugKdCI{rM4d9h+cJBWA+lqL4d0L6t{Z4pO zBFa}9vblHGgJN4i{mUOY)-;Z;Sv4IqCQFse$X(~4`T(#BfZSg zRK&tT-lgX0dM3OM-Y$yk9#qcHi|0mj-T7#kCHXP`SSy?+?x74XBC}RKl@c|nzJD*b z_&+kMjzt>6JZ`Cz$9RCTNGF%vHT!K4@03ymOBDJ%b%`{5>-OPom^pKkSt~Pgh#Yi+k=L$cZ;_ z@7F|ub#$~Zq4DdN(0DvnmmnvRCHXNZ%x#lWKmU3N!}_zvw~ve%u$PKhHV4&;T^JG2R6;0G@e;!V z+~4lbq=}=CaUI%k30cqZ_{xT~SpL;3IE^APZKi!x=t;(TL$@Q>BSZZM%sZrFO5rK}9v03wjZolZw)_9s z!~8EV4K-4B33jvFyS3kb=$a*;rDq>cNU)t|Z%q_yoY!tdENx=Ob`^lZh4msC5E7#Z zO7L5?DltF9DvRGW^WQoJb-6ktEl)2zxh}KoQp&MQ8*D#SzFkrTUDysL^};LNYLguN zoOHt<`!b1{0LBxJng`k}ZB*EkF)iv#Wd6!oZL>bvE+s)VHJdIpMi>~(a*+vw3%9Ji@elU%9tCJfoG}9*!@xMb@nG^AReptB}iz3nNra zb({E@?6)rS-jCNSfIck8H4w?8mE}>3dp2%1%vJZIpE(8Om}N9F6CGd_Zv|EEaQoR+ zdVUyzam%X3+&QPP+M;*xbAaCRQ@=CQ>DS(q!v9`-zm;6~FR&Wku}6DO02JE%mo<-4 z3_v4me1>GDio_d3Ie=`RmFVTo5zebrKMBdR5Y@51X5So}2bYtP58XvIu!OC{lo|zX zSkzbT=rI}9uhp*D8{Cb|_65ODwdIfeD1M&Sr0j-$i}6GE;7vC57vuJCL974 z3Bf17B=^19fJ~jXl0V^wF`c`>Z;N$gGte=QxIOd5%*#0~oKUj7C9zG`@vNG40YpWE zQMRaNuaWs#Jc2IcX5$mPcRjWBwVb6D05(Y>GtXwpe+zHsZxX8}uzcdI6f$$V-txXi zmdwGpNuEVkfJ)GhFin$|t4$Yclw*d*mB3*_28&N=m7zVq`m$6Q9W#jK$aT`L&H4Yl zFFx!1V6L!eEh~{GzES1x)?N~E)_+ zzC$PDWVcG=_2tzKTx~S+`C}FV&ermVN1HcC(m+SA8_cPfE9Yd9)ABK|A3Hp`GoOEdhyJwTGxzl3j}iUdUJ%^1^?>DRzA6OJIB!)-TuUy& zCrZwz;eQlURWZ&XLn76-0FGR0znIHY-oL`7@%O;~Z>_UA18t-0;fL%y391nmr>4x; zDmJ%J-q5Wv)D*$(=y|%LEYb3YiziNJCZsoHj334lG#z7qt@k`*+WW0NY^V1t0atsx z)WP}Ee(!%WK?Hy<{{m0VNgE6W_^f{l;%XdYY#_~hT0;J7c;1I5THrH1QDm-fP_NW! zxl+4%s>i3k*NrHeNr2~*7$}KXvbvhN34y@H4K&=EhPhn)o;`r!`YdpBW&`y5 zc%zT0d%F|!y_mMuOKF7R{vIKz^V zDKBY^cEhuVNSa=fmH+b&Rwnh!bOWoP%M#C$|5jK3no@R%l%Jm&XC*6$`_B)= zMjIK{5T}Ssp|zMBls+9v+R@2r$cVkWn?2lQ|NWlxs^z!nouuf1?(k;YNGf}XqtCs_ zPM!p6DMkGI>Bd)p+oF&D%N2o}tRuxa09VHn@`mF(BiZ9Wq2S0bTdglrBE352G8$Yg zm*c^Obi;xV#PQymdfceqC90sgPJGc03S0wmko2CPmDP}w`sVt#Yb1I((t9UY+H6F2 zfLnUKKzbV!mKK&vK48a~EhlqeyzbShVDpw-u ztEZx;k%5eLAJ%0)F7W1`cLx@pYA5YSlmI|qyZ&#<^#6s5dCV1Kron*KlLtBh=k+p# z%(khA!)yu6iGTy0(;)n*PzW^nWl?6}I^G2w5c}~V)4LCCmX#q0RC^JS@9%oj%idA+ z^{>#AhBzCd5G)=k9_^2;#}6DgJn!-j5D|hAeM{j!^jJLv(e^a;)_B(%Gw)MHFj!vn zutMLxygG3VBVVC_=CRx;nJOqU1bSIYd*RcTds_fSftOF@-{J9v;Mn4_)=C{|VWYVd z8sKL+EpL>BYT#O)mOI)n(Edznd|#S(CH%2HC*C`le2tvO#0>uC7d-%l+=!yQe>+B& zL2v`l`&UR<5_Z|fw{zArBM7C5w3-}~?Fta7F=I)LCD&{E$FCHc`w-t}(fvu+!h^GB zX9WkOhJ9UMb#HlTt^8A~`b(W>=s0I=@j7T_gmjfAU_-c*V4P7_{q?`T@D(EIqm)Zy zt84{(oCB`xs7aVIS?Y8#0{ns-)$oD#^gX~ba21c(ej9K^hJ##iOU-)Ecp=fT zK@!HUmrX0nOUY;AndWI3&FiorZVMI%^(Mz`WR{%PJRfH^cKOc7(lCXmo$R(xRKS~u zz@zmWxdu&%2Fjmbzva(+l}}a6`4Se>mHH0bsmLmQv6QwvYhy+QYsV#I{Qu}^i3#7h zZm8`}f`UuVxi}Xy6#`HBRi!=|tOJX|M7bo#e5z%jD_jI?B+aRCnyDtToYs+G+8Y2X z8rnR-WqjV<=)ZEdiAR^5Kvhoh=kSi3L<9BA(zCowJht3UYp1Has-X{`5s)OB7En3s zp6uNRYKioNz=mM5I8VOZm*mEUs|9A}EQngqtUuafxcoqdZrq``O#~fv4zo}z4q54o zXwD#1F#kI=8mDN3n8A2x1L1QDn^U{BRzd4aoOre-->>%*DEGM!u5-8_bhSTVMgf`5 zrClYpxfyKY=!U_!-q8}}((P0*f2H!xpUq(;YW#Y+C0FuY%G3T)hpLfCY>7SH2+*iH z7UZTYSLC*9I_25~YV7t;2_5eW{d%NKnvX4~HF%-P@Tst@_gp#Q`t#KHjqGov7)EIQ zxoAVv;+&oqYAId}yC4<_dXRRM#Z={ofA9O3C!*Hajz6#;lE%Jx`0^^88d}^&OHM{e z$@`3l&X(|!(D%&5dB+L$By3FF1K>W1r>%;M55Aw>^wY~_ZhBjrocZwdNLObQXy{P? zp!_d;`Y$g4CSn=pov94(mDG$*gUG8di5=YrZ!GYW{9%{ZvZr&B)tC>^e*JTw#_l5V z2HoV{V&g~r-2M$wQ*qyj?4vcL>9({ssf@-QZ$gK%STz+739q(-%3u*&X|LDw|Aaij zTI!1CO)16G>CTm2>KOl6We5wiVk-qMJ^&*XB#skQbbg-mf-GghRw(Gpg|=2nJ#hyz z@Y^&e^`gQqpsz^!6NF6Q3(kiK2S&+S;2r>){o*N#*HOGoqS>$+= zsEz~78&~_D0cdp-d8D0?zN0p}z$(CKG2q&pv9tmDqDzY(D#^=IaT;CdXF%rg^pU%> zI{LYYtG$?YI+E`ZEWPuPkxpXHh5Q4#%+SJzxhIqFv=egKZ+=T19$^X>I%5I&nW(~( zq{9MgW7oId{8rn}&r#LPx~rK5c56g_){3M6p8+D78HI}f$`t>d2uq7fSEvG(_d(*u z=%umcen`$ORYk$s%+DJxr@!C*YF}Pb+Pt60BL4xj4INlVHDo;6^%a=jo=)U>&ib2T zw_%4oEYPGX3SVMp3Z4%5J1@RZBmLu6YpEsyiR+LjmL_`W3-1*-G}qjCc4g==0~D_& zjhVHCaf7tR->dfd)V_W|M=oKPuF6Cwdy&;qI$9=AcJ=A2>F!X$M#`tTQ_aSZ-DZhr zy&<*C5y{k9tdbR`%x%7KljCeOzQ&9)a!4Vl>i<>EcbLRq;lC=3$$;H7z+v`W)@KSM z;nX=3KFnrLoRL~`mR~nue4WCKPg~$HaYfCR_4&}8V<}nGFRnQWxlbp^qR$=UI9{V@ zLae^Nak<0ZYAKR6B$%n#A_p?O)58_O%H$Fm;t$}U*tDz}lLyt~MFASbzGs84xUYC& zeJ9VpC1?&Dlz+|73Lbc%_MiqBpFwwB)femhB1&d}tSNvt6C?s0J)|Byn3YrUNC8?3n>bMJ~>VI8i|r>&>*Kc4sCV$WD1 z%hkM94`?p?7(X#q#7?)xd-A?hg;#ThUf#|29EpWQRNx`)%$lu7M=sl+g{gLU5+LvY zo@4*Lkd?|3GsDc-+RzI*kuUHE7nLAH*FguxMkHZTCSziB-ji-&aq~LY<{)O3koQ4@ z4)$eO@`sH9Ml1Lc#&htFj^R?- z7Z+uk8S8PisSIJdweHmUFWhXQ+=w^G-<=yLgCCPS|4=KkwGphDL5-L_vxsD%uaorQ zsCef^RbJ8eOE;*0r|>@?sAv(bk}T>Oj71kQT>{-O!iHTCDf@vKXs|RkGFpEGxbmVK=z*^LL)@O#lDSVPCL2|j?6PX? z6oi#&GGTjvIQK2$Aa|FY^}llW(p`8wW6JqvhSW(R^{S)sNX}w-tLxUN3p`^#Vh2X} zH(=C&3nF!#{ZrdW=qQ)Z^$>amLjS%Zw{iwr_oWX|NT zA3sN=fv;Y@``F;S{;Vc+m@&`}lhei?c5a))jPBKuuG&|PD*Efq#~*t6u&fRAR4IZV zvFlHj)d}D5kC+T&q4Rd934wn z1ZO;HnO33plba0JoJB7LpJ?PL{(NTlDLCyD)&0&S@iR)*{TA?@L7>i^t}ODdaF}ltdd!`{e9x*>{m0LXC#@9M6cU+>C=+UEUB>{(cy;EN z1)Ph<$yC{$pUQ0kTlFHNjvZWz!=u~j1&Pi~Y*UrxlaR?=jfGhg_94%ITFwB0?K95VcDWFq0{Qx|uU4f#eY6uobWp+MMU zW^+fT){s9VaMr1(3eQKKq)TN6gZu(tPnn#)zTa0VmW7>rsW83yeN;4K>&}ZgEkvT; z&WNIP&xS^{s4~70KLa_@5fev`|lh(L3TV4($ul9 zp8y2CV5@iSIfNdXAzOhIcq4h-Bhf)3cW4Rt1*UC(6(zhuwQqen28!#CE3M`H| z?~r6!V560pZ*~FGaEckiIr*Vc-cuW9gL;|A7Py(=_baJTosJ*12)cakTSFGBma?ik9I!dHji{)voKZhjWHxmmS* zehBX@+Q?=~$W#<%c{M9FyC5gcdNo(U;?>>J?W+x^)kJnhzAq^sMM<*e-gwG}dWBQi z)`}C+>~4F)0$|M5+|ck$1b?!l6-?)QWjQB_P)+0iYst$0xAJ@^rN=`N%toY9f8k7g zHA$q3eY6(gR^XH(&Qs!qc_;GKnq2*Ygu>?+BtrDGrGU{jxI5!S$Kl?16#XX^G5GV^ zuMJ5GDSs@kZR!V2^M-Nr9Ki9pP`@yyCy!yS{$ev2qWiMn=jR@uA`J(BU3}{

lUH@xAwV+ZFGPB!s@)b8zm5cxZ~Q6p#tA24KeTLBcOfyCS9@Ht4NOlF|X z*4&Zz#cwnyf*#BdDt5BRVRgQ;M(*~zVz#>*@e1{lpe-aLrm-n5c^@-&L1ypYREoEU)Uu zZx9gI1UIWr7D)i0uY}BmALGSv94JBL7JXoHwG5iK(CPLM{6oYEW@sUY8N3Hh``U!c z@rXY!iE|tGA9H9doyjc7*z~~+Ai#W_KKK$%6{~j*=Y6Rg+B195ia<4A>8tsp$~4<| zcN{R|swO9o9$$ z-J0S`7D7YkOY<@&PjHmBzwB8|ra6!-Xq$s2cRbwIMM+X5?Y)>}n%DgZF2{+kK(Enj z5ix3SpA@a_EeR&VcD}{ZKU8@Rh zZ>dJu1#NQAc^_yQ{3QXHV5474GcJnHriW|*dyR`Iqq&<-&TU-Kt~loSf}Y9fqQDrv z`n9vE-+EGVc#+#ZqkmGcSZL$=5b#mQ7cyEXDpDR^=tGKIJ}%*E#oHAe!%|h0I?K|c z$rj4k;i;)1`o0DlyUzYNXJkVrUewu2=7+ULa}C4}c35iQiZeiGbq$@{W?bx@VC>Ox zI)PV4WpJvn+4Gcpzl)owz_Xrjw=gx~_)%LTyrCt4Za{r=e;2~QAtJl~ZSH={ubgtV z^y{sGU2Rr)QtlcBRM#Ax&e`Fi_cvB< z67BI`JPwlcU7?e~I=w8v!4^aNB=!#NbGLGvm?^Vcrf*7QeS&PCncBYOO*%^+Btl04){BNqG|RghGl**dDohv7kUOZR>Y z)ZMiOq%DH%JAJjzIdRTfaCf}kK(&mKW z#C=k&w@-%~Fx?(iOwWVAwed%P$gP5EyLVJ*+W8#_6^6AZNqQrkFAV9swgo_c7+^2l#g(^{x zI-EFl-0SgrcIe-POP&*Q`|)$!ca5m-kFH`NDm}Ec^Ui;) z+7E`{8;{t)h#*!lnB|xDZD0eE`3^V|amV|&O0_!_=%`nYr|OmMv0g?AI}CvE1e;34 zZ8S!cK?QAT8TKQ&>?#iXbmAu#JJxR4&IsREsv=^CivmH6Dp`j^hs-I{0>9d$2WFfD zna;pm-{iurVvhla2izKk)2dx&t}!YGXDCdLBoAR-fX%4tzFQQy3-k4KI`?&q`+n(>vP$w-?j`7kzQ6i>%bGqEXi6p2LAB++9(DH{&({ zZpGfYD=h6t7GqE0s;W9Ks{dn*m-*_i$djBS@!Lb6VjKH`<*#Jvm7!NfqLpoCOZ!Qj zZYA9x>9SOz%(Qoe$^d+C9uz)SH4k$kPtvkB#}+)$w#}~@iv=isQT?B~F4NqVf|9JF}0L?hwK!^3x$ zw+22QzLZ6esW%Q-VyXZqPE3~c0cU2}oedHUJ3Kl(Q9Pm-Er#xx(G+JQ$hVa_IV8jRw4(cmuw*UGIB= zzRd!!{l$aY8%OVpj;8kwVRye8oa(-rpVi$&qU7=kA6>8^v1R#+qiv3l$y1$tHi(2S zMwXYM0a#w!xAM5n6kGu20e7sSzWK*M_}lRSc@o`luw24Q5bz5WKNf+FsFE|APY97Ljm$=H2`Is2(-tSp(gL-}Jw(evU3+C%l8IBqIJ zd=I>RKPX)u-+{lK09c56h#oXVO)q};&k>r&?{$y2dA!XqKV9WPGG&|<-OI2?M$g+Y zeC>qhP^6gE<4qWt8?;+?A0>d_17!BW9>RBkh|kLalLc!Wbyn{5>_pbq`2tbw-`+04 zJ8mYf>Mpj-^it4h*d2#U-AR3Iduy;~-o5^ah9@bjQF$)PL^(0V1BIjSQ@WMN)2M*B z*W$yRQZUZV{qD}Qm!qJu6l5q=BENf7!P2MnE5ndO9nM-t6l_uW^;a`iGru5|!;+cV zoTXT&g(cf@T2cCIa>8&Tu%7Rllo(kedwr!;nsy4`#3bNhmAQVn5Me*c`&MTrft&n2 zQjV~I+%BtnH8P|>iNNazKdGhV-qT2cU3sYR0-<_5o&u+iNOMd|%Xi0&xNRI7ITc|i z75#+xtKo;jGx!gESOC&!Dz3c?(%f{&zyEkPUeK*kxBgd@g5*y6?9ib*%L4^IdxR=_ z+|#klL~QKPVoGCX)l7K??u@i`mN~jmhB%5Yv=B$DC7^+bLaH7OL}+wIO;3BZ^KWu6 zE1mCdZD%Jc)B}TB(%X2`4Fk+_1a_|cMWyt(@edi{UPBiS|KoIj#u_S0$s&wH?9W&JV zz7A&O=Z~kQ?JUU}5ewnSjp9+zAh4K);j2N~77m(yHAWWwu_})jxzD@(z-w}!{-a{d zjRa8@!`Y!e6TMd{NLH<`{m^&s+qdeJ@-wPXaIHU+8VWbA!KH7%T3T^L7+Jr|5tFh? z1`m*1sQKGA81oxRfcn0JVt^Vf-#W1R*G)b`xXXSpyv%<-#~3jaNw59v?*xmIrni;fx4Adla&JzDAb(IiRxRt)Z7JzfJ7GgRFW+n^zS$N8KGwmjLCR2AI>fX1i3`{|JYNnso>tU$GVnc>fx%3 zA!Q~t&T##K>%q0KumzrP0^@g+<8dlHx;$~~P~o(mb7ijvWD9mbLIxhh$JfIbB35>D7oE5mbNDeF0?_E@K3KFXOG&rf(T;qP9;go(wL!L9 zIE2aeq0im@O6N?$myes-ag6E#+$dO0Hl=!A&;D2=3z zbveV|=VT4yyiqfU4W#HOv2s@zie1R*EoOurK6wx*5eN4UMIDwXvZycM3I(7KyQ16a zjp7sVR!GroXt?G2?ijcC%Pz+_k0ylmE5XL#QGXWjRDcm$zasuZY?em}UzCvmCh;qT zwKKP%G6Qv;md&~~cR8hI3zaFl_S>ePMtS@VG!7CsZo^!mzcwz+L~2^H^^Zbi(!EK= zC@bjD24y#xWhg4cKXNSJa;4}AR~xU3+dy*>TN~VpS%2F-V5G$NGS3!juucC%TcB;} zQNElYS~J#mx=mbn8!U0Rh(vF)_-I_!us~x^EO}sVvwB)~I4@*G(Jp0L(NoYz-~{qK zWn?l-FXG4J^qY0nYmywdS4468@<5!(`#N4@Y0!hi^Uu>#*>EQ2w>M^8o}5gXIASR= z8U2}oUANFc70I!1*<_0yt2|_Dn|%Fn!ylX^8a#+&z1vQj$1$w6YtQg={;*=y)q#!T zbS8@XTgzcX>C+?gN0A{K1mZTu$FR+6*3~NIgBXtY>)ob^wH2%|$N!<}IvlC&-*-m# z2-)LgMMg;WIAoKVnRG-b8QCKoGn=T$h>+|(Lk`*5d!>UT>sZG;IOlnO-uM0f{)Ojr zKcCNaU-xxi*K@2=p&P|xb^$ZSOBmrD6cY9-{v8}7OWip`P?VP?=AP~`updiBZ7yQ4 zYEL~QYsGF5lZZ0`;dZC!1rSA>eeSb?DVpnpj0r2P8fI1=_aS`WCByYfOzwI0A+jRd zqc)&h57f(kmn%K=KDC+eMK1aYvq`_9iwgc#oQ|_Ox_pJQ7h?rEpf_G*zg1c@f(l@;hjhX@uss&rXp)rM|-Nl+3CwK9oSfr z9reXx#bo%x+fS>??}smui04;LyU_6M_qtf@D~G9(m3_r5690v4$&!bQP6b$RT;n2} z8!L-cN1@$%lR5rx^g+oE*IUdRiop;>;2LSideC7kc@wB+;{bo{$dew7;YS%)d81`H}pXy*LVeyehjB1qe1UP#T$bF0FXOq0o^_Le%L zLWw>4X3G-}@*A1#h{Tec*Xe7D8@W;>`?cJE8=T(x7O5zaWd5s-B1P8J_{$S_Xm9R? zf1K3=`mvY(BO#lKr=NpIX7E_GAB*xC=bLVIxu0W`hSsK>5WEKbRNbdu(2+$5200#r z?#RZohHGujt(V~|K0T~cdSF^-V^d;*_FJ858&vousJ;=1@T&bPS^&;4QQ&XV!-2! zVW_J%JtoFW(YhCTY-P1c`J>`XrxX{hamf+94{FNfTynE|USOfLcmujeZHFs#<9AZU zwtglK%uwXIQ)e#7yZev=*34$e&N7p=jW1kM^%_GM_%=5TEwL zog#|Ru8>FCjXph&0}9XGtyLG?gRer8-Z0qWTguD#kNc+XM+_@UzYoo)njjPUaw|NX zf|#zL^TF_!+a9ps zL;nYK{mQUb<;#XM*Hkj8{^u{>Fhu8T)>;Q{y>5c?JmjQ1eD-MA7T~-4vUSwCkaFqn zcv=>%S+sJg>BNiF-MaF?w_J2Myx4T7&S^_)K<0dG{6${6q4^X!<#VuP!YQk!-hLM$ zhe0Gp8dV)XHWht3+{2hV_)U7azL#FiQDfSLobApoVtB(yHz-2?veX}xK_#`FH|m2OT}+zQ3iR+^3Z!Wf%*IQB}Ii0TAh*D z$xf`ydx52zbC`W~AM~hFVBxkK8l5|`z-*R<8ud0;R7m5Zr?E-ufdx}7*b3Xyu8BWT zwAq(zF4^F?9*s>L4v2R*S!p6DgmlyElV0k?QsQ9-_tbjao(;JLXjA8BBLvnVHtRb%M05Q{3rovj-`^ZEz2l zL#M+kT$^;7di+9F?znc!b?g(&DN`=BPmcHI8w47=o;ZjL^tDKI<{Nl8S$Xu};#HE^ z#Kox95`~JLgPPM&Ffyh_E7y2-N#URw2D7e_-Woz0fm1k+t!we`e|vH_vyNg+5gDCYJE$+(p>l+?0?|i_q7(`{Twf=s*^hLRaE&#DE7VT zODf#<1iAHUdQE;UuBqO?qmQ=vsCvL{#V?XXdHa_W<%z=Ij(cKAjhnQwd9T7*08-Hf z&dGUrH>LhYCF|c?fC+;>i*+Fi=~~a(r`2>^c|iGF>39@tDUR!_4ZBlyuVdYCk8{bq zAi}Dzui}BecO%x^*v>l0N;0By75bJ?qz@hoF9H7=#kZ8a{g8}F7HAwr(I#Ka0tL1? zhP*(r^Cka=tZJPBhWD-V$U*0FbmrKtjkP$~XK05Oapliwm^{u+BPBfQsq;a}sIJ`2 z=0!4-2ec)9(4gJ8hQMpfkGEf)CqX~;oA~0CfW`B}Pa7~B(xb1)a;Q>O28aU{22&bH4jSvLoB=Je3+1t}GL5tpqxfGnQO0)r!;T=pkfQWna=o}Z8J z%|KRT!wXZN!fUsOOja^bh|sUwDsfsZZ?v8HhMS*)dNX#EL9~7=1*Lt4-izeJb!q@F z30(heZ_odG0mMh__t6FUoG;BE)TOa&`D9vyh4w#yu5PHx0q;XxS!6j0BiC?=`J&zW_JE4xtcoNrtmvZ-6 ziP9Yc_wh;vz||cU@ywW$2@qSAsekZhUK*$nJDuad-w+^AYo>)+gt**LKGFtbp^VP* z_UuJT%=eq}j9*ac$)Max&X9d4v&D(Exo7{}XE-{`^5@COxuu^^ z521XLM*g0Z@lQhQyIl{7FGxqTZ@;dK)Ji49zI%|Xp)pqWaYVQ|Hj>8Y3oV<-0VBPX z-^4fMXK`kmL&u^!`RHW@P-nD5EM>XO5F|oQ$g4z*W}4L9Te-Mxgv!#w8#DN#3a$mY z48U*$PIox&qUm$BS4BkPHLeUkYRY=-M|v#^P!KM4CZNj&(!H_P-26oWaE@?~py;_b zrt5n=Uh}SKk&jcID>f6O(E+D*e10fFzkSTDC*pJ3H&&rd9sk!wf-}fBnP%D&yZ?Pw zxogG;mDRD51{CC_zD)SDS~mMEoI2=2>a-3#WSso2HXMMhdJBw>Ao5u9tfZ+q%ODMf z%?D`v=TzcKT;P-ib`aw?G#2?ot_j$riTf*egYrN_847Gmd2jKt1Y%>?=wb3lYo2{b z6wJ#(3d}3Pn)p*488-R@vzhU(&WpM*Jr=gC05+NZVk6PVP2}xLvnx#51!y=TpS8!Vi>UzhI>s;C`{U8XriE%QUmV-RJ-K(}N3?3U9gKiX;{&C8=I-BZ+GnP7B_qbbKb;i9J~Ufraet7>p%*~ zw6k1Dy z*c)<$q#KZR-T?|x*350b8xw`^DIubJ4-cpV!`H%T_};U|McxPwl&$LIk}ZhJS@$s^ zuWJ2mFL4mvzvcAO>1|31O zbnu;h4&Mn)Qmu%D+W7?7ThB^zA3P}d>XizbbA>j7E;v{*AAQ+7DP=|}3D4ztP0mz> z;rs||pHz3wGiAN40GuuBZ~qCuFwnl-9Qz8~r47l>hHsnV9xMh;l#4 zNe@A%cUwoyUL>9Glk6tB3#W!;JafV-?iz2K;8lDiUjJtETG1HA#HX zbWZA9;?H_~0#jDK2~I#8GRMtmG)WkI(Fj5$8u5v)q=9)p0B7dj+SwNqaW1gH576RS zzO7DDujX2$epS(2obI)lbcN*qX{%)u>2G`{0VE;h^Den_9MLDU_qL;>0(&e(JxV{* zberSnL8hZoiSSqP$+u{)Z5m2xmbE8>5}@_S#{FuMsuodP(+_ss>8Mj=m+Ra#^dONhPQ>ennuQsaO zHkr=8W0w9VwRznuPIP)sJ`mFF^+Iwf)`~adrrqWDIK!K}^cMxBM<|gNUMCN1M#Y$X4k%VmzG?^L zi{dpe@*qc$mQNd4y=u%>t`k!D z!slBv!MUo2VC;mv2PJf|?=L_U{N)4a%s@JtJdv_~9a}U5d#yY0z6~IYUR^z@LPbG6 z(Q6mhK{NtDmQ7$~4E*Iuiy2Rv#*!!QRpkge_d+A94<43Gc);z7(Z9J=xI2|`l^*PS zViHt+O!I*Gvs*i;)l(fD>(1jwVE*?5m;(-bY2b{tT;$G+BVIb602^*JU+O^Vje7up z+i&FSkaZ#QXcorQb4vwvW^AIvpRPs0U1x$19$-}&{7vK`f6X3nIlzkrr zB7fDywfn@yEa`z_kKyUq3YHs+w*fP@-1Ta5Sr^wFxu-|KY%paz&u-B_CB+3NzS!zT zHF-C^PVV3$(7N^g8hcBl-R_Szwm#+EA6ea@6vqa)r#B*#?@Hdr^X_`k!2w%7Ib%xB zV&lbod*Kist!*#WUBTYyk^rF}59ktZtCfX(#@?up$CP9U;^d4apghHHR>x5{f6O2s z%9rUUtkzim9__S|508)z_Wl}kiuBgm;=TXP+U%SFR$S~S$~G-d;5eWorhmT~w!ADL z@)w~nW{h3!{zC^c2Y6<#S_GC%K#Ql--(Pf7hkm^A=o%X$i{NBDmT!UW`uIc`8$43* zR|GAFL;3YV$JaVNR6I%XKr|3716VUj9U=xDfC9up@({Reul{h$KLCizW^ddavpp|3 z*7tkDBfDw_e7cVKUHNMQTqSC{oo5wcsD0nuJbcs^ooBJc2~SSh^m!|WT{aSGCvNO> zdl`KxdXox9Ttad*g=JO_H1oy9opHg3$?S|VV;NiPrx7F2jMt&=UC)s<=VF(xSWm!f zIDQWeTRN)+_#gkVs!U8yR=<$w&Gk3mIT%Fe3UjV^U)th3A*Vt?^zlB$i7g6NVAUL4 zJfIv=9`MO7-^IAge#-aREnLlX@LcT5yB#;P9k~3J++dG6_fsD>9xteDO$bMd*qe6WwT~P2?0*x^+;t5)2}54OFWuiPR32Qd zqoi}(jzF9sZTy1pIvfA>jgRSU8RrK7!TE-QgaeY=X?FF_3#b9U7aI?0#$_ajs=C;- zy`u}g7_p)xh*w|P+=deP=(h*^Qm0>Ae?5PypR)N0W20qCuI;kzW{uE)7Vd1vkpj|NB5jm!S|{jc5d;G5U8emeyTSNfi@NCeT*eBFMr|5RcvHbM@) zyk?MqOCO#(GBD`JKy}>C#guF6iA)`-a00J4>1XG$1>IQ1unvm_mi(ibhS<4+VyJc5B;IbGFB7I+8`d4`p zB9j;J9^+(sY!5_PVv4#HyT_k!-yg2|x-w$IgG;JvAyHQLFRx~`+2)wdyA6|YLB5BQ$Fuo# zm@*ZBO#&Fdt(%i*cj@hLEB`<76p-)5U)Jp=Yd2eVozHDW%Gz!~*+aXTuyb!7fmalP zd<2BFyY2v#$DXnYFtW%&K>ZK8E?Pb(YK{6!Ga0233*%a}YujCE6Vy(xP3rERSpQZu zou=Wol(6NFZts<9J|FvJj+(_ObTFel0qz$%Yc3^sxZQDm^`}S=F@;j)gJ)fC3}eqa z$8#{#vp|bJp`4H$&@CM%X6fjOD2(OUVhrs(O4IahV&TG+o|A*@iIW!feo z<6B$0skibONK;8BICj_G%`Kda#%H7YC`5>Au%^4++&JAroCk~drp+t!LN$IlgZg*I z1TZZcv;KGLLvV>=g86}1f6)T9$fZ5@bREl;PFvHHL*lpXvm_D+zh}3%9!Vr7V@z}y z2%1E+CnBG|$Y(=%e{@~x1;>U<+Gohj>~=$FY8UU(#W2oI0_nRo#>e-5py10; z^0olkemG||IFjcwI_hKdKy~t?U@uu$4ath_(4ERhe zJ=zs_KUi@UOh~pxJ+g0OM=Yq!AC=*ltuGB3C6Y{?aSUWHZk$+NxKl}%QL^i{``@yS zv!7m7UR3cZTWMDP-Hi-q(%cH$Ygf%qveQg-UE|9PdLhM{<%;XPk}SrzR#Ia>jx(WWDC>Oz21=oP53 zd7|Y!w#I8o1iR(^n*~``wZ^a^rTit&>nW=2<65t}U@!E87czWio}&7f#2f{uOc964)|^AFEv0j(we z=A>N-98h!9t}j9@v2PAuGk}jmEMstLYqtUWd`QI^nQ|iwBxhaHHgZ~^6tb7@O7l!G zwbNJDbEamyl=F%gX*x!pXjfpyb-w?>#Sex2=B?IRzM~P!`9kbp{vwYI+f_Kis%_YO z{o}AaGKh~2sa#I|N2c*0-cgC%;}7=)c7zFYq4_B_mXG5%v8mm%OV_R5TPwG0UjMSy zY*?}--+JB?+5dBL=&3^s?M`n|_|p@)j7~>(_S;@@0&zhuA5#k4@EuPppMz3#)rVWS8`YOBk2c5#WWo2}2uH@>X1>VUoQWA0??7mpgCLd5N^ z)vBpp1$ePVI$>N=2_jl>$ea~A&Y4&z<}ITf+-ay75zGd0JG*-zp(*cTcT!RUS6cg` zV{r*r3cB|7Q|z7`e{~pyJz+m&A*w2~iZvlTjK$>20<~1l@p@9Gpw_B;(5GP*ZeqRJ zmqA~8>VH}g1p}n-8@&tuTo^A5$ou#la%vRe#5~qjvbWHXL~Xs9BU&3F^Nc_qGm6ax zjPMm0lM=q~motI0$9Mk80sX5#gHL#G$gKqy^%kNU*@N*-;I_Oa{FzLh149{lwJ*Fc z0B>)$4?W!LfS)Vlnn>4aM9bn(zvbsH+phderp>v-lUB_z5VV+y-RTW8oZ9$d^E`Zc zGIQ&MHozs+QG)Xj^1hQfxiz1|Khk#q&wFxrFkOyR_&>zl(R+SjPNts3ayS575;V+|mEYX}a7PD1p7=h^Tl zubvDk0hJ{LtQU^pQ6OP5bDTmm@Kxv_`S@Zs@E2_UMU%xP?fPVfzdv5#I~X%cRZ%`7 z6ALesZ3SdMipWmqRG&Ovz{)*cIWvat6GT7^m=3j;~(=Mc(w_)IJJ0*^^alH+aWSGvgvXd3?=c$` z4k67Zq&u!Wsgu(T?3OK;k1)&|^7JFa1JugDa2_kHNRmlD9T(Y!N*MxG4)qYnI=mX0 zh|go%hwPv=$6|S;A6Tr}PD3>yDlT;Ya=9h*?cKK&R;$dKk_p%>rr;!~CudRMMi|PS z!)M{Q361{WF*w~7EikIK`pUc^Usexgc6`8O{Y5NCX9|y1NaOfFV?(a1#8|f6| zdZ7epVXT?0-)|2=Z!$d0Y-E4%i@O~wGREP|6a6~95R}sH0@o$rD?}!%M7h$>C(G&_ z5@DJ#+*t1ilPF!B$FW?(n(=N;0n!m9xpq#Y>XOVt{L7ZVw%?1db9f~~}m z3@2rf34k#}LVBmU_1@CSx2MmaIu#q)R%|@>rVDb>^N7Jx{hxa!z?uu zyXH~zYt{QkBzzL>E<4$O8Sqc7XmJske(R}CZuUux`T5=ZaO9UJ zd<*7pa0t_?=8|@rQBmc#&mR?G9i!@&(E$nx_Q+-V1Y0AXe1^#7)`if1dAU2T&(usb zKF@d&LNn$PlDUrFt2B~`r!cD~VKyc_2pO+pcTed`@Tf?>481=xBqmOPu78 z0wVJht?8gflGUbn4u9;lO5E4yL30zT-lDq~ETFSOr9@Ysxo0e>ChgB zNV-wX-FtfV(s90lPe`jmW?z%qBaob~U!7k&_I^6rHm73)O+j-g); zppco>s)8rEVt5_WzjoLO=I2KPeHRKd2&=oe>ARBa=ggv7XSpWsZ}|VD@0HV%eEfS6 zEtg2=L}aV%;|uzp*JWz?&L9}Kwmy+!!vJ}i+F(ns8KW%kbt zIvU;%3L{J+uHdI**Jn^CRF+YhY^Pmb{CT3)GNMh_gcO8T3!IhvTEBb%=7bbtF*W4?{{-+ zUSXp;1aG99e$)n}Go2pN>q8Gy$Gb|2>{u`EBtlcKv2+#|XKEGNF`00-pi4jSXzQ31 zi^SDTzsj(iDRJhp_PqUtBbBQc^BwbY2s>l^a7HaRX6iESR@JAU(YjBga_pHtuM|F_ zWnTT53H531W}cUCK|Z#QtNRc-ddE!4F8=#1lNQ5iB5>U5LWw4avPP=5v=x!@CBJY% z1#9fO3cX;1O2j^=_VvkVGMmM9<&Eo8wIWVvh&?*zXo)zwX!Q>C=C2vGo)OA76#ndcNGHp4CMH;Uq#XjZ5_+P@^tS&=S1% z269{Qlct^Wo>Lo6kP}Mx8wK89huJs|oq6Cr!loMPGC>~6W)yu`QB@7k_Wc&E+_@*+ zi_V5m;go+;U#5g9UE3`ABM^WeOnC|(_;kblUBG+ELe)<}TXPKXUZ^%HYQA`Kd#?GV z?t7Y9sLxfY^Rr9w+x2);wP4=RvS47|GL~C%Pr$-5eDnr=(9yHVxEcomx2NH>ylo%; zVI{9{g{TSOjnYyAL16D!rRH+67bdk@Y;|5<+V!^rrb8T!jeMIT%~aadfJbs)^kZ=x3!xjubG+t z+**80k4`4grr^RqdZJS)j;^Hqm5b_0vDzsR+3YyLA|2^^9%**R>RP_MWX>DZ2yN7ul%YD3#=5tv`G|{ z2#xpI_Xx6^V@VvfqMg41I{g?gY*ZFPS+uyqcsq(7_w4_&=L}Ft2cDSm@IEEZT4vE>$;+M%t7^ zpBN3kDy~9gt=bD7C7~W=!pnIS7vP_N0PZu$8esXB!~=@&cg>2}Cu-w;OJG%SJVbpBxPusZ+yLk}Pi)4e4R!PerdJxg8k4cSq=p7eM))_> zH$P0k*#Xo$r7W=0Osg1)V|C@{3+gVIzGn?#}3=*ZE{pk$7sTZ5ULyM@Yr_I`I%qtK}mFT3^u z4jPQH=6Hs4GW5eC(i_!P6s~kZ8?xAO&W3e(^Ocu9DB(*zxJ@)FveGW6Y~QW2jWGS& zEulQUrVuWc!)5sJgMKt-wr{q=h^hr3Ma;DhVPp!tza+@da++}-SR_tj{Lbib4miK7 zk#B~5rf7j8aBguqI)6SY_0uc@zRSDu7gsbN+!bu|I3EK&g;YxE!r-$#$=*AbtCVYY zK|3x%L0#WkTYyExoZMxubib>DgiRIncr{vnF9=V{yz82KHFD&LYkUlfJ5;|t(?soe zGP`lWPqFsE3Z5KP0zA*|p205l01rp7PPJQ_cJw0`oN(r79%Xb1Ihh#dpox#M2i2J4 z%!<=!`e2?+CpDkUFCjkyZE2_TNHyM-LY8{OQC)^`MvMJ1`22HR;{a9w=g#gOLNyB; z#Yb7a@%bN~XCk-4?u&Qf9maYYfM zrB05vy1NOVcQ`~`e5%^^z{W4DokTEg{H?{qC2EAnB~=&@$Wy>XZaGH@VbkdCpoW(T z{|qP0RNbb!e<5la`$3jO^Y{lr(8peV>{M#;k*Z%gMj=R)VKEM3%J5t`K^${U)77tm zut^%zG%+z=n^H@E8Tl+~Jk6`|N9cFM54>0tJB6TA)uEoz?|3K+xY`hK(3J2wzEKMB z0EYv*!Qxpg`|<}+3Ls*?Ly7&ppIJ^|d713d``6_@r;+zOE}mFsiQnrzmdF9uGp{?& zyqg0yR^Tn77bBjzNxzis!m52xIr$8Mf7&+2-Jiuohq_93y^wy{C!iwq26ttA=)e)! z@>Cj>nMDZr!{A)zoPo7sGr6}b)-s$`^nLj`2poAupZ=4o|VkX(mI?ezu;3k#y$Jo?|C0GxI(Y<^Xes zV*tQ(_c8#KP>7_vxqW8m}|BjrGry6-9h`y`-A4ZRp zpb?+)@Q&oyzxySFby2^ruP?$rdw0E8H*r#CTIM-Vd(TDrUT*W_9~bn2bcg^~lp)VV z#vOUx(~D|6>8L7fE&#M)(=cE^Lyi~ZLJi8Hdf+1& zD2BIj*HgIU$Qj=t`~xWQNC6XTyAdncbbYpub34}wx-L_;+lZ?FAh`jxOE?AMte#D; zZhm(Gyx%?|DfQGIECZhS#in%WbjZJ$kU53={hYn5Dz(RPC#%HQiN3&Tp95}-6!99~ zwt%thxp52eUeKt%&!^pf+^f%if8kW`C7iA%pe&}1r&hx!7xo3ydeOk*%sXCq^epU9 zKVk8|;Q>G4XN)4_8$X4AuC-SD>W=>GMQ_L1bU6ymmGP0uU?dhH-#x?2Gz)AR;k z-x-%}kC1zBvTJkh%tV&QpT8uAWWp03dT+3Fyz_3}>}67iZpwD|L6{Ase-7oTZa=nY z#O5#3hRreCnqwV92jqBx#oIeFH>0m|8b{;%BFmq7O?i2u+ ztd_-kAwMPA(DcQDw$+0y&nb9wM{=bE@O$nQC-#{Lwj&Hqb78-@957sy zpVEN%``blve}5H^NQ7Fr`OjeUKPSQuh--SQ0vzA(K=I8a(38{Lw*rcV-04WQ_LasnyfGookiXN2%IWsx#_G-Z>EHcHKIJmY> zqCcKB1E+zSB9%XYxq6PfNnjg^Jh1F*wd(X>`U36@=#6b(@pg+>CaFIsz^CB60$)BE zR`C?lLVmw9W;2y{y66h6&KHNvF&jE$oS z@u9fxMR?xS_nuhWeZ47IHO;A&US;U_SpL>AgH5d=c2bb8z&!v*DW9ee>U1FVnxI~z(Rv+}27SEjRoRGpU!m`)$ ztw_12V;F4Y{3a+WxMG`~1($N+Ro<-+7M4x(N|VAn)uesa{OmOY|dv{;cVhsn!3Vs zopF}DiRp7vKCWrKL|n4{v1*=n5{7wy0FMmxw#5~gdOAy{9J{l9m%2TdFxJ(Q4d1(I zg})My2Ic}p5jr2i(R0%NZH^;|Q_jkXQ{P$FzY|1$LYK1tNKze*TRQ#mD6S~!z>Nnw z>ix9YaqlPvy?irKE%HM=6yH_PpPYx2wQOBq`fS^gQU_bncwe`xz5db6>*|6Pq4EDfvQ3VjC0K4#zz+Z+( zr9ZmAjn47B>G>+!kM4#9MN(aF_cqIVPYIOS?fz_9@==a~pGRk(55mzkw0mRRY-9(NFSplpZhI<*N1!4hO0SxlJ76wHMc>DJ-CFT)Tmxvomc{`c3&sSo8N?$ zs2Ido3m|=@4m%-((>f!hEZ70V8xJ8D^e~)okdH}_(2{ezHwp=$(D`$qlf)I8_rybZ ztNUPia~m*G_0i6Y)+#7!q3Cd^3e=Q22m~1h&J$8Y<-iETWV^Gcqc>`2Yr)J)eD0Am zNIl{VMmx#j(!#1L;SEa_jtA2Vd*H>3=(Ei*u{;ML%&J&8!YRn-Ndw59+og1l_}Qn) z*hvkVS#Q9!aPF|!sl-Fbz<(5`06T%0yWz~m(t#4;=rdyNJIxtAB%|%aZwC6`v_%VZ z4Z6z7{20m$!N}?K&!69re;az0s6#Ws&>~OZDcw2DD)0FsNUtXKlL4|;g{qxeWPU`Z z{B;D9=1Gzm*;a?VKyruuy^UW}JApLc?1W{$?GQaUPamc09_rm-ob|6nCTk=qZ#jb& zm?|Lj3zL34cGB4Y+`l@n>#j=kI3?N1muK&d2L(1I0U&8muFYN8peUGLy zK!TUP=o@0C9S`|^(06u~0J`w+6p=kxwT~bdJax|D4#@7Am`uPL6(fRY?!mIun`$d% z)DDoCRqQ;y6f^f>B@iqtrAV~yLsAeuIN@i6U*A*xmzm7fLmyns{%$@y*$Bvm)6_6E zJVi}${k5t>5Lq(LqsTpwm!n6@042zI#1)YQ@_+|iPc9)x*O>%dpA@lHn5#Ci&b_gz z!gZBr;Sm7^->@mjAw-yAdX(u)Zs)|pKmohpZ%tN(r1!SX&n?(#>(OK#1a+lExxUYq zqQJ9Mu%33VM5`^d*z+ftWccY6^}kuX2=9M?61m2$JDNFRh%b)>*j?s%$vt>KJeT;5 zGqKBGi}>-`;sO4y+#OUeO8|wdo{^aTRIx&hZed_}E|NcGs??BL_>kb5l$p%yi;E?b zG~u8NQR5b#V7d15PL&dT*PakhA9%0e;=6=BxTrj^{y9ZIeWOt;ws2(aby|tjGB2?G z6czC*ZbYy{hQ2EfDmA~Llr0tq6_Ut5(83M8xkEkg#2^eTl_>LOMH7j})QIZ{`{?!| zvZG^a1TgWPKgUB=>W70n_kr$}d`uGsP1d;#&Yg-qHt(+Lukp&&$SjVLbJ*TtH{r+X zWNcY1>kU$6S4Omf6d)F}9S`a&M1!VR46;W^%oSO3S0=6f1XDnfUU-B%liq&x|I}W!rAmyi{zE=vzDPLVJ>tlS7xM_SM?LJ`{MXwT zwK!Yu1_;>l7j=gr)`S|iy5#67QoB<>HcPdPnrMW|qezR6FTaMc3+YEeH1gB$9=O&M zm@0+QS`5w^9%<1s8Lz@qt!ML!^fo+yx^hO^8+xB6s@S2{1XDltTv7^|CFP`s$*;O+ zuJ9rf5Q2`~I?7&l36^mWP-R>D9d{HAdvimcX;cQOf`pJ^6v;<+d0WAqUBuS7nv{LH zG+vyIS7|Han>0`MqVobN)=qW>Wd8;KnlB=4$^T%csIm^5f+4Foh^{^;@L$ zu^U__Tap*lmYOE4`?$i#iXp@mwoIT+}U|w!!o0gQx*7lASeFh zEcF~2FDLQq>Arseo^ea_GI{OE-Ogx766{Rz+V}Q~S=j*eL=eVdpbG=JDrlm(^m$e(dfhEbl@5C5Jeqi)Ukv)2{{t_FdwO zIxctSW7vh|p4V^m77lEnXxk}FlAt$w1s)M5>`Om{TjrIdY5rW%?5UGa!+y$~$b7+w zI8iS`Rh=Fn6|YZ)n)5wQQR4VkfoaXHEW-@**KgWfTxBI$UtaTm*obBE;>4||BTdVQ zVS%?6UwFTjNf<8ol9Rg39cQB$&g_VmlGwv=oUZ4mUY7#-{aC;>SG`Wd;9f)$*v|yt zlItGDwdP{~JG_nQmG5o9>r9LV@mtVnYRoPGfp$OL7_34_SC4W@EpAD9QP~Y|_!iIq zed)?Lh10gc(6;YhfZ64UKYz$qr9pc)LCu|H?_`{z&*=MX4nThGJ|RWHU<`N!uqUO%c?{!p;UK zjQAOq6*<9k@yLi=KL?e&h5gLRU!I*A52zDmXnbz!a9_?#b)Z&JlBMIY{fqFk({ zXsW~Z`SyU8R`J^ApuSp=DXr>;u>g@bPOmp;ymT)PQMl6Rd*ejg1BX}c&hHWN8Bq)v zWW>IUNTy!jvZV3w8!K@;cr;v+EdD5cHm$2NuOlzs6!I#m(=!x?f_4`)x!ME9GktcN zpUc{4y#xhu85?b&HSP*>Zb1)p(wodXs!w6&&IaN>>k~kEADnoGq9dF(d)?wua33o9 z^q>Nx_7v51`C%0aFfibXek9^Jma*`36apn#g`YzqMiEXSc%|-(tgRfM+i2>Ot`h;n zfIwy%O5ET{^a*12#)zUN+;A7Mh%a);O+TrcIi!dL?ZTZWhqy{wn1hY`5kq<| zW_gvX_))@_0$}-`E8w962xNpI8@oG}%l2>uy}>&Ornt}k)k9!!uN&#tsr_GNcnDjq z{N>@RhiEa-wwV%C0GUXlAoLHvs$Xjg(kA|0{qprs+at3kaP0Zy0VHZ2eO?8);%E=7 z)1&?eJ^2XdIdfxbS~LDpfCv(PRQI2BY}%OC#$T$Ee9=n1=Q=dj@NAOnQdTFfU(P6x zEhFtM(_OEL4?%-JKJgK*^I~~xUZ@CAO-z=ih9&s+cgl>}eie9`u$8`Qjd)JlPW2bY zXSYsDEOghlPsYVvZ+Rbh-I1J~TEGNdg?=u>qBmkV;W{#>M%34QO9}$Az1hesGbGbg z7kUwMLu|C_HHl1T>9^8yd;`RZ*}Hynzn%B+5MAA8iWY6>qiYQRXRBa8*WTC3g~vaB zHL?LG6R@oHQm3@crA-{{bFQ4ny4ZjNyMso z715Z+O}@`xr>cJskgjj_Kn-v2e78wLa>ialKu(0Cf&Oz z$SK&W3*8+bLuIYO6vm~UpOUb8xyC(XxNQDpqCLieQC= zqX;Y_;-BPSt+J<9LFTTcuAnlQ(}%9w2+p<2F@e0HV7QXaw3eOB z*6n4YVae}D?D2h$qP5aCPK$bo5;=}Rc=zgITP0#gPmx1#^&4AFKinrXEXk1x@|gAy}hF23Hihr2S-4Y5^nMXXH^6#^6#I_m_+M zQ^*tl?I$i4qfji}Zk=g&UF4#_iDPi#)D24TGsx&x5<59jc6vie3e>CEoumC%q7_TF zBSW0qExxO{NB4<$?6PjOLGmch0a#`*W^X_UP~Db(eTMeEjx)Ha{?*XOplvvo9bQ=3 zvN^8yU?infj-IIdZ3lNdQhr(}8~eGB^y{=$14AAwQZsMVpd)XB5GxRfY!#uJLqXW$lc3YDQLw++zz)*N&qQfZKp7&^^Oi$v6@ebVNaZoksJ%yxw!|B zJr>C~{43bLDXuh+MOm);$$~jO|Nj8{{BpNh4;)K4xBx{e5s%N>x*ZxQfx4$~)$5Yd z*=GgiG8(C2)9>A+z1ubYFm;*XLxpxZLaL4gT4Eqz=Q zt*P!(3@Og+Nz}?GaJc@zjV=m0e^im}n%ln(ju&zJrF+Onddk!{jUdjriqj_Rh+UZR z&G+kuCnNZ z_pY7jC#uoKDZ0#M^vZ}9O4nYo5RXpO8}kDC`3d4^t}jRJ+U-;GR-0qwe(0!;>(BC% z=MG-Q??RoIyDWmfwG~^osXQFxmdEhiy^8K`#=0DHTVN;I&1f?n1KLLyfEdRgbI)3x z6bgS~wBeXAF;zHs<1S_U*Yc8pPTeh_{=&=&cP2a?^~b#9qpSx_h<9|CI1R@UpS;(Q z;w=(;+!97p-d997ca5X*84dNaaxsHbQdKBWKQi9LA7Ks39Oz)a)BEPz|lny zjb}4(6+PmNzjB#8s{uwXO?qR#|7vGan7xExYt_4tF5M541BMD7<=^Rlg>(eZPM5s* zQ_5F<0CiW2^&FBA%`%P@B5dT}J4(PB8FpWhI!7On$rgCJreV_Ah;EzwI5W4A!)vht zXS=rY6CsjRNsh)do16w7syGGMeTKar`K0maaOc|`^b$HMiQBLr65Fgg5_22-p$csL zJ~CwaxrNVtvgr?Su8nlXng?}3eoYvjaIHai{c<~_sxa21nHu(rH^IsCjTIc+3SM=q z^z?so$$u8Kbf_lX*0{pt2=_4Uh(^AVtR%W?ZZXq+XG_^F-G9@)FckYGqEB7R|+=^Mb6}P#- zy+`gX?yZ100D$+a|{S+PnC*Sk)InLvFpWXjCSlv{<3Dr#^OCZF3FMkAmby;i? z3Hj_@QF%Fhbi1J)deQRgUX^37kpDI4foT8qZhF*K!euuFl3_SX`e%L2DX0@RJv-@c z5k9%r7sUa8{E9V5M_qNp#ObFheVpx|dK)I70QtVT~-I5SUAV*hX1Y{nk8(_}^Rv^ss|*DoR}1hF_6 z@F@!20X^^>6K`4c_igetW2X43^^j@^oz%`RdT~&1Rk~`Ro}pgK)oq;Hg(DJ<=u!dn zZ6izmB#lyLu3{!GR7qt5!mTRLe{@z&z`GrL+eyMC!zS<3!f??+(>3Vjq6EFuMdj0Q zyX~?_NU#n4XHL`+sQayMez|x+WwCbH0MHSm>gfe(5QC9~T1F1-J_QQU=h-MEvxhD5%@VUzUGt^82x zTt{x~{W~s}Umm5IJp1{(xIpMxT|JpxDBXnAf zY)j)m0@kxdz1)eE=ZV&&Kd2>xCZ`&>ns$J$KRbS8ijb>{?#pFWQuxV5HS|%SFS$|| zwR11G!Y>Tl0CQx{C`{wX;?E9vCk96U=sZ9KJyZ9SAgZz1WddD!=^4NlwiEu2a@*pS ztdb{9^Y8W{N=R^v;?KG*Fh2D4%y24XP{??)(;0W zhNM((aeu`S%r0gWvk!FeC}&EoLqGphIG6(NNe8NUrh77R1a_SZzc7|S&*ckrV1L{X z|DfC4P5tF_2VOxfBq$OM?ElY2FcR@lD#M_2X>OPyF#4W->X)H((1GF}(=hp17pWm4 z(i1oXB7gbQJvho_0ROI`H)0>;jWj$PZnfQD6^t2e&9LXlp65=P_#hDM@KZxj+fKRdro7%EVfXOnrUYB8>9cz#U9uoJ8( zq5VzA+rSEeL-;HhU&tI;BqOBix+Gs#SnRTl_?6v}s&Vy;>6fuw)@$Bp)=4fp|A z$%6LHU@CP;Iaf`Wi#~2mkLn4pys7n#?I!P4W8>a-xe(eP-v2A4h#yhkkpYngRp>Sg zvB>7>W#oOci4htUIH3}C@b4#}D9v=6;B_GXke%WNaKPC>9!X{Nks(^TZpp-q6%>Wx zym11(E(<(Td{P+vyHgy~o@;bY?w%N|%7k=~mQQ8J+>fFG&z5@^FP{r!1N4lg>k>#t z-e$5t;3*3-p^1TErJYx;dTY;I`7vG}196p5mqR8?rND(1)!fX&I&dQ`7=#2 zJZ(CObu`@3IB-2c4w$*dcMa>>kgCiB_DYqc22oL3@mCe0=d~yuhhc6%eqyp$37m~W zeU+g99rlQF_|UAP2uDYBq~4Wb|B) zd(`G1sbEb<_Vo^ZG^`JoQOFz+*;PGI904+>N%m;I %EwiZ~&nz@dYmlAMe>VG) z56r*DQn6LAfpm6D9H{tv!-nJRyHA7HEcz?c6S54?GYN_ly9=zrVZQb)OST!V8+V z@8xp}9=_bD7o{(LSG(ZQw=n2>k-_!hfPX{bA^KTW6J^SryP(XrkEBtvc ztqwWEwpu39z<*D7uCSxI+H=QUhVN5#sY$m)a%@1R6zkCw*0b0`qj~58=Eue<@bGt8 zpQe95LuZT?vC(|v_mtY8J+mF~FTAHKzb{x#SA=7vyfHFyMB$5|4TNqsvk>Tm z57nFiO~^yRJxqu*tzBE-x}fAOd9bo@NP=Daj@MX!77e}-#pQ1tjrB{~-~7>o=W<^R z_gbYUFz{_$gUNMGHEseot0Zy=`jC=bQSEggd(eBlcmBUT_dlf%=5Q&fH@>T81|zB) zwJS52n9STQ-&M>gu^s+%{Ws)5Dt9x?ldcFH1v>qe+8u1EG1;g+o}sg&LOnh&zcWp!;P1fPM(BUZ)@92<;bmH`lXD9|pED>yKy$;^hPIC)-cP z(*(RJT25B8{IK2aoJ}G|iKWYRU_Feohm+UC;Dd5D#~}Wx^Cxrm70S!tvJ)g&k%e%- z`Zxe#M@eQ+%Q^N-vhy2LH5lpjG&&mIZ>)1Y@wSlDgVH^D3qf_S>{A6#6GgY3ubcH7 z{`k%6`!PiUr~je@{T!lryRDdP;0=})KTp@Xxf}8B(|k*NVPXw&MR0>bTmM^eRTTSt z<%Cs{biVAaFwZ-92zD@dpD??iN<01P&tXn8;WU*n{KwHny+ad@U;kh#Pe0t+*nvoM z>^vT8yckYfR~_uoj&I*f{_OQ_t2=z!Yl;>{k_yNR{@e!AJ0GLJ^U!8n`{yirWW=UpaQ44IeyG4pBQD-MNkX!~j#y)+)W2pP z?e1bun?s8|h)Kxz%Ix?If=$`t>BL z$ixVVgVcDK1I7JegpY}NccP7d5{ejYQ-tbI6$rW1#<=y)9Ugz%cEMqIabru}qzXer zKbp67bM-9n3Q|Yc+0{Bhc`z4=%4Y^0x~#zWz1u)oUys=n))e)UafgijVn*p&Rs6-) zzxR8LQ8JPZRCFng`{A1Ib=B(GT zi6q+~gC9SDDxk)P{Jydymt8eN$apA$@q$F(jo3^$4@qiI8L)%suOf%Q%RG>88%!q{ zxMeTXspw0d|QthTE5M#j&%Mly+2R4wMi#a^Q?p(rZ{;f3;}4 zU_x)TqZC3*6j89j`z0xKF^FGkV5`Vh&UFZ8He9$Ffek-JNbw{k*DPtq~sjK5!?4k6Ln|k>p+KmK-^uLlL+~D0wEg7T)RduYZbNc@F*zp)kBD=3#_K*jqM!fH6w_ zJE$glH!Pqdm%Mut{NG9wxvS~c%YUlpGiZIZ`OWs|3%|NkWGf=F9dF*2K(9bR&Cn9y5a@8f0=_pvqlS7bPOL93yk+wG z?OMmxVbLVc5uMTx$D;JE>7+;q+jRB}7oanLi{6d{kJWdQea#1 z6Rg9=lBS8I#jr7(g{1RVdR1I+-w;ys{5rWI_LHdsiA0k3E`;Kj*uEzK(fqzx5J$-0 z@>T)<=O~Z!Mbk~$*H`zq4yC9nIkP^rv8p~#wIihU324IKoCr1!z|hzKMw2F6)L$b9#n`Hwv!#?sMP!b_Xn&ExXv{;fx#!$I0_~eh|F^!G z;o_GGFMzF~(sK;x!nuAf+Up%FAUY;?+lL$dg?b+(rw7c72-GYZiXtyiLBN50z>GIk zRE9{n*aSVkSexR%rT4Z!AkCMUoOx0MK^#z@U=E$I>lL7Ury9j5@3V}ceRd7|wnSTJ zq@vjC-rFHH-GN;v1|x%j^2ot41`LW)Z#jy;vv~XwsJ5fL!Tn+TbQJ_P?C%WnJ+zvc zXeLd&3}?e_zr1H!7YLi#ry#quV=++NX{tt}Q9?^SGh*?fKf-&c6a8oVK}&ss+SxUk zw7r|vxcx7nEVV)m0`X20#Sx#i(f5h0Egz0}+JM#u3c@GSZO5B|A9)%?F|te>MBHIKSFopMK4|_8?C4dN4$?e@JTFn#5VQ?spDT#IKSN zbqN|e&2#y^yPJTe*@rg`t%!!Dt=F5uNYSq(2+uyMS@bmI;3ZybQGD zO%;CZ*aOU-O>%-5 zFPt9BtvsL?(t99%!CUbr{yUgrhjhylGSux$`IiTU1wq^yf!`j0QsA;mQa3?UK)0Ag zQ3c^o*B-K&xv*V)hV%fKMVRQ`NFDXOELf^TAO zpsIkz=ZgO5(11J&f|5Op@cIq)B-0!`ODv zxGI@G#jZax(dd=xV?A`g$eM!64nU$acM9o4LK7AHY#&Mt=J6F0ke{ei%jVIOUBu6O zA?cKBAjN&~yW^+yc}PkQ{LjhhiTe%rHxvWh4xqx`jCwcCWUMq;zP&N=6!W-Oo7P}Q zF@R@eCXYYCItNxc@6pak=%513oxzQ`Lbv7ZU+sftu{Epeo+Fzzv}rp^5ZrBsIP6G_ z+rrY`Y)5^^SuQw@i)R8m7)cvpA<#c)4X z4-9Vvq=?#lfwq9B4CPvaXn%f%2z&EFWmhpwqWOy%@vS0-Tsl)lwmaph z%TEOIz8~~&6ey1$v=1cTH9H_|U)zX~2spBC1IcjM@nK+(u6zptVlpIe3EzlZSrSt@ zXmTmk)c7GrICpli=(Na+fO#|!i+m=ZUDt`!T~8_gU&liD;Y3spw_!#jP+C4p zc|Nv`a?PiT1b5-bM3;346!r|6(d8%q>oeJhFqvGq!G8W>h>xvVi5G?6iSmBuUyMxj z><=>YlH|rgh_hM(Q`SGz7|aD;?86_Y5pWsJ@*>+#&to`?j`K#7;)6s|Wpk&zoMAqV z5pwA2P|Wo$V)>DL2^BREdtA0{&?iEK>`PhYxb?vc&(-(*Ae+cJ59B(FJ5A~Gz0ZykgRxJguR!OI ze$x!#?^AtV_+)l_uS>BEnvgf7Le^VdsCWJ5i-^6R3DMYl3-u(Q*uGBJvgHiVtL2@f zNj}@mKQ5EhV!$I6z3l&CrhZt5+zVjkX(^cTVsam!3z(K9e0j!SboTQ}BZkpnq9Eyr z&_Tm>2P`e1cB*GIfZWR^7PG6`(C?Zu)0ftXp9TJ!AYv)Qu&|pf%{btg7?Rxk4ZfJ9 zHv&5OYDXEs_1Dk()bM#XVK!Cw2_x)&7?@YUeNCGAd|)bCH{lpLwp6+c&#%Pd)N?kE z?>je~pn7Xy6Y{h#gN#2dso&4PYQA|Q#KhP~>pxP!uchM&jA#@ALLRq!wDxW>>?w&U z$@}#?^3XR7E!B?V0Cj!$RqtEKvMxOnZT(QuN5=zRzd_VJ6$)XdT^#P3eOAiguJ_2##nw_df1D}2pUl9gflXcvXp)D|Oi zR~;qLzy5@>*RMuWzO`OXioZH^&zYMo(Ab0!Cf2bfcBM?Ufu|j$DbwcV@dsAL+jM$s zxdoVv+)##f>z3}O+3Y-74DDQgAKJk#NpBH=nT)v|jNViRhq)x0Ep=XA{@ar`na4ty zK_}ja-r0>9Cb~q!eT@SL2}zlJi;zRo)x0o%;QvNe7Jl0(Zc`jQ-806YR+Tj6aCsbR zer|KzzKw1j`mq#f2%Z30B};ELbVEL;4frXh86m96VV^Rf{AmjHk4MwjYYUy&(q#uq)ea8M5>;$wuUd8@dQ{(H{n z_t&`Qzdu?UAR1*>z`IS>PxfQyuB|+oV65-aC4!IE*F(qRJBaV*-?s$>Bf0N-;f<{! zN2vXVp8lPA$6k^*+__-gry12he*zi=X0 za}K)!&wx?#*r$%xw4eIiz5iNDiG;Q#G_x3Ln852mCryXPDPz~a%KIcO9Hb%`b zX~#m+&FJOHa^yYU`J$ma{1n<3d3s0Y<%~djuZ3|U={BLVU%D##RHxY7pN@bB zKwl_(K^L&#K<$NB6tqvBJHNxVC=X7LL2WTeC|hVhCVK> z9w~rvVA)_-Us=ouRU}I`kGClWlsTscc64HQ8#Dk-^<>9)*oY%)(y1T`!|2f z4nv@Izxh$bk!d&u#g9ArhJ2vs@>5DSAfJ1lvoYXY2wz^?UfH#dFlfOvw=*40RCUbv z9znD8sm4n9UJ04~aK}7n#ab#u^FZ&y_!OF>s{*9xqP}Jqt|8h|bIU8wp>34;TaULwvLcNKKqo&h4wW@s zwmi8la;uM?RCJPeTbSK-`cn8yLhwTuvV=Y%n$$Yj|CBDS3u0ZmnLd8C@tNC@#EnY< zdo4l-pa@LIX)pXsT~{AH<1;T-qHCYN_^J8iuZ>gI#;Vy8`oPAV@lx^QL;kZs9)@872ZjAS@j|VGcN#)9v*H zwxt{jpQJN~jZvZ`_WtFQxYde6KBv#aIpFpuNXOT;35T6!4uAvT{`Fxxlgx{dWF^Lj zxhiTk2##p70$xH#{~72x4WBcb6R(Z_Su@Fn{&3wzGf3~8`Zsrd5w%R|EtymNeisb> zuBnB(v@i0VU}SV={lx?G1#X|pk?8~ldO$ZZ?UJ)Vd+*ir)?e7qKanpc^m?gPvc2z9 z8(sYCLBAcaJ}3aCF}?Qxyl^$pglm5BNDrktP({0kmnpGUJnO4CWBw!TV7Cqon~E@4 zZcK8%Fkg*_os`YG|BYfu9WkA9i8wCYjn?_wvt>0E`*E+(Mho%#Y}k^TLqYNU2R28=C7GKil|MXTsy#x|5vHjIQ37*hwRovsy+?I`Ypu+-Vk-Lw`}Ex4yX??%iM|DWD;m!gJ&EOP%#-6rB?R;GvN&Vr8Q$(mRAs zOmsjg!>_CU=7{88CVN9+0(7=S?2!Dnar-d$6mo|2(Kvkq<3vSO&<~%Eo$l%K?fchU z&}V`IftZrIh9HOp)VyWL%L&cUldNG>72|4&RPY_Qk>+|G6fC= z%dCnX#B#{%$L_RRlYrqcsw^G9isc-a5R7}p3u^qyzZB&ZjnTUz6~qeP#oRlDFIt~D zo3x>)e;wSF@@$A{JsCcm|85W9UeD5wz%-K?8=m2%`X?ZGanF1E`m#f4Mkb(w?1yY< zGx>Q+wjWvc0m-wL7it7z(rv0qTb$^hsFTYo5t$M$C~u;G7z9lcEwrZTEjtucuWBj# zcbj~PSr=nD*XhhDS%)$Xc#18t$xAk%-DAZv`S7fktoJ)P*7dssGYjBvJG$GqTg5+P z-V^s8GAvJ6uSR?z&HMRP%u$5|j;>FZY|IJj^uB^0&~T=fKBO+Nn+Foh4rh<3iKt|T zG-nX-{WZ^>Lq)hR8u=eiZbAE@#YvqVB@Uz-v)@eFYpaQ$EpJ%kJIwe}X9i4O!g_u# znq4ovRMXrLHfb+rG86~ss5KOi9NjH;GXF>_$X9=x|3pQrXhpA_y9O-$WWK#hL&qm> zKB94Y;}sISd){U7_WEzDi=W<$T?VOzKsd>4V6Q{=FKv`W?Ue7(V5z%~a_(*amJt7} z{?xBzoCyX@1p|?mc!<2t&Rs$0D!@`j5Po9$!1U+Y2>ysygAyFvBzsF8P9saw*rpz} z>_u65w>F-A2_zB|WDC|Y*ie6B-(kQJ4jFAmNXWjfG({z_G!%T61wZB>)tHYjRcjRw zepP;I(+O(f1wGHZlSuNpgq+L@lW9xV#TQQ!FzV==%;>FaB~b}<9t9Zt8e~CKm42ol z6AVW{l5~nWE_GMb(~n82r`f$|kix?x<@TkW?p03}<_n_C^r(&;_fnt?_#XX3=$+1# z`<2>pdQd|T6S$5SGIlZroCf*`5jW_btPvHdokYl!5-V2r4oMqVCd)|u+rayD5~K>q z=484A>pkqWj+Wg=el5hQzFRb7-v85Syw7fYFZT#uIUQEYMje*hm%v*-NZSX^`1AnM zvE(ogDu^WIvM-Q`k}$jkR#^{;XSr6hTtQknvA=vDTd^fdD#>7>81M_)P#u z-?yXuMr7U%)bKU~<4|k84{8pa(m-_5UqmvsVi6WL?{;Q-e|XJ29$1Gep`S98v6=nj zLvtoXS%Xd#Q0BHXhO~w${+v5c6tv!coP9Z++c&E50L*TVaFzRZr==$6ReoDkuKkC* zFIRtU_4VUds$XsqwLh`F9Fdg$G4(s>*JH|P_xn#3d-~@yCY#jO2z~A{fxkGysbNcg zQ}=Yx{Jxu*h*nsdglf9`W}h&v<$`Ve(`#nd0!lyX^TVYdzXB*rf}` zD)5+iu$8+4J#mytT|w~ct)jaA-`4MwBP^2RO-t^+xYM-ro9IWnS7kq_`^JJze>Lq> zApuk^;UmZjd+){)V^!^@Zx922Z` z+XVp-1puRM21IG3XZ>91M4QED`)3~RwLsZjjmO>t+cblfmx-i>aOm&eW9WTZw0_qi zuhX>AB;fp+X57X3NZB45QM%7Q@iA5Pfmb0(wMqR{6zMiXmZYd?sYVr;;XdbJ8I_hX z^KU@_CO9}Qvb$nx>)6alMDs#UeZ7&8iVS^56cS%+2&DU;WdvHzy(PP(_!7wH||Sez!(iuA942 z-*jcZ z3b++mJ$^poLjMlKVcm@EGk3{J8`>|yFaFM)riTHu5}v7OT-Qt?du^t~YX7wg=z&I9 za)T`47sV#`Yhd@i1amaQes zDXRZHFW;zVSX=uU+t+EWx0$z}Y2)W=nh+Yoyb9k7zb`o~_fC}G1}AJp+*Cgb2jlgA z)ji$!5OA%y;vi~ed&nLaj-Jn5FinoI4mYeU817^!Pq0JnM&bTb@$ENb#tH|K?sQY zb4ypVI`Mj74&X9(AQ#rKy9YRFQZ)UK8SNM$h7hMGYo(X)0d70v3}-ivp~_-g&EX7B zn9~IIEeST1i)e2h)#_~cO?gE#N7iY zs@VO~3(Pg1du|Db*q-e7fgcyFfNt+SA4jL(rt8$)FG7Y%wDM*z8tz>eJ#dAGI&@pb>qt=@euXs!W!;7Pn&U0`35b>#@}z_HqImvsr% zomJ)+)gcDj`}r;P_q=aR%uKqcG0t|)0S~9jJk+w-yqRgvIG?;IM4v@XI%U(*dCAka zUvV`l%HkwL?+p^jK&VsyEU%GN--cH!&XRogk^*7^zifaQX?~&zwZ)Dy2p^Ge>^DQ5 zK!K|x2Qk<<@6%QzWocQ!TG#PCbiLKlnoIS#RulpZsow9#d`Pt*zYcp%NZ30zb`J7| zmW_Sweqtbm(UEa|RS~xyV0(wj*YJ8Ewnwyf*h+m=sJ`$j$JMAexdm)gjZ@M+Pb4+m zEa@s9g7MbZr%00_2slm zAHOe`PwX2Hg}}5>c|cMpJrc&#GtcDK=EZ5vPwoTwq09ZGJs@b58qsqk`8c zb*28>y=_wKErI`8=wV8)2MG#}xd05!$l}9$S7)Vg_^vfa zmEs?-Zi?7I)G>sRo!lsODqg}du57M4S%S57f30(z+jo8fx>VW+;s4bGQNc*Z+5o?g z)X$0m?^uleK6#!a6sSniEZ=QU@LGFM&$srZd9wcd`t5rbv#L|!)_d>TX6kViUIK3N zF*6Ck!nglcV=0@RkTGUONFw$#f+h|Tg+TB5-Zb8DV1)n zP5}NV$on~cANm`40q`AZGsuMZdP{K_!N*iV!+~45>rjfN+^OS?d3{jlc>iCMttTsD z2Ld7D?`IuXoBR6<1FLCQR{gHcbCDgudoM!0{}Vj9ajZG8ZR8xqDCvIs-q|dihV*TF zhvOXmtv*{^N_LFcO#P?%HjgwN0T}BkNyfefd#3v%-Ua_K^TdUuqVSB{XWw6aE5ap* zhQz+-z7JgxX-*@|#FkoF<7a+f_d5@lUUGs73s)ZB4f*on9E8x^coY`=GTpX0=LkFO z`r^p+_1rGJlSO7b*a-EIsIPgaSdu&Mms1@3Uu{TPi-KR(N+p`F9rAu$Fa6~VJ-7Gu z`NyR1H=qG`;)`!L$MM2GWeeXy%w?ZDWu;R=xI}FMlrKyF;{oyqNetlI)tgI7X&Y2!P`X!+~ZcDp72 zi{wYf&IeAt`~DpD2++;N?DgVFPysU}-L0h5bU(6}2R6l+D95G6u78l)Tt4B2uYc@0 zo^DT+g)gyiK^s-~OM1=U&zm@^pS$MXACk1m(?~K6uJIUZbSYb$knaYsS;Q$7ZVVWK zd37(h)XW$!1(}-a#-&6h=012*?k6M569PJauqEV%{w1Y1-CV3+IQqcI8_f$sCl1~? zeW$zD#WvjE-i5#z)uxIjYK3XdC}n7c&y!XJ&qeZ&pd3{)IUhNH5_%H*U9ZMqh7>h( zYkkSZjGJKM)|0^5(LJbfjrW~`MlKgxg`r}SihIG4|IKIDTfzjC3L7+*lSCA6Mf(gd z&M&GL%Q`YZPSjS9KVdS9x0EQm}ea@r(3d}^m-U`ay z?8WF~?T&*+4jdqs^pe2&Ys6eY2dw3N&o_W^6P(~t6CxzT%u-30=9qo4CVC^eK>7dJ z2x@my?xIid7}~O*^)TDKPt~}5&7Spq-!!UZuH79dd?_g0skr+vw9oyAvN#>W&94i@?r)$TF42dSA`wS817vnqOE!}iy>jj?FnHDBAiSL zzAj6bAh-WrGd6z|q?7+!;<@lm^-nkNZ!Dc<;=QHv7j+df^qg5bk{8q7`fXg8vJ_Cp+lQCSS9CPjuKRj6E4=OK*-9%etD6@Ts^d35)B|56`5*;#kOD-c_}|5eeXqP z-+OiCt=5ajT6Wj|y}tI*?y=eKdc}{yMdgM-S`~H#g`8U|D$YZl)1o+3RcW;ol$o++ zZ+AuaU3+2t;)RyX=tJX100-g_3(N3F2ITnf)hbRjs=61Oau5*VRcXg*`?((-G?{SoB?xCOqxTnMiaxq;yI}UlRn*}0UYk0atC5=%O&bN4aczXg0^!=}z%{{^ z=Rw!+M??^j5ge*=c?AKhP^-}QkyrUrVf@FI)P(URDehOd?=#@aq`m4Ud9e66PlJMn z%JWBgCH-UMdP43CKDg(L8W(BdyLFG9$(lrX81;-VpS7_MlaS+sO2zE5K||77LgmRN zs9H{L`hgZzH(8zaTK7{0O1sp)5)dTao?C1Xh5236gSj-)#9Y7FGG#zJ_A!AN#OPu8 z+?KlzGQLXr#yHRVda2#_elf1LW$9Y8R80va)GT+`=~1GWbpL^)Cg3352i8dtFbi*tPMc?2Q(-j<^+_)sq%^#{sydD z63c`GgTi!f;q9DEmwAwyY`|dshWmt%qmTanBIQfG6p&2ojVvAs zreBGCn{Qf~6-g}@)wJT0|I}}dhcu{f(xh;y;@LWet%H-lE}^;MRtt~0cOx-kk^+-)Yz|WURc)cEv7EdKxTW+!|)! zILtT-4l4ZyV&xdK=T>&W>H8tybH3=5C2j2Da*$@q($$E4kap`6Ri{921F8v%x`ZVV zKoEp1orTT`*wBkhAmXxB^v~hW74&eZW2XbH*`TL-+XbJ~6?$kQL?mmcgMr`g&fdFR zYdAa(xut#TP-r$+i|SoVSNZwkQ@Z#@I*$CLNS2Xn;J|c6ZQM$hcC&c(W2tevsh+h1 zo8eKE0(krp{F%z~)!}u1Ob7M#Dh14)LuSsB0HmX5ye^uRPS8TwA^+W*2#fD0{gSKP zhsd;p7;~1hvOslaOAY$PIKG(wTZ?wU=|>&0voS=e!>1R47c!Z^efWPwBnu+!t&c1M z2bUUM#$d^Zh2AB4&18-KPI%x1Z4-NlYE9jDw4a!~>`RJ^-((;LPI5ghgsS$AFNQXV zOxFl07^r|Z%7tvI=z?>;V_JhI=(25}557_% zP#1cMNXa}$grsCPeIMAWJV+XT`DW=RR5gMJeJv7Y{@ZQg1ICHPx@A2)#`^o@ z-VgLb`z`-Xrzp&>)_Br!x<~V-cgG?tAaK2}i$Eueci=p0&p-H3oS5OA z>_+7CE4^t5KfgKVmXu~Vu5!K ztDhnCXK9Dfb&d>RPB>zWh|m`dcTod|u==u>AEY%+aIb!U1AB$kS;u_-;Y31UpQRD8 zWRQ4DZz)*Sf|sSYZ0O^4xLqtvn2Vi=(8yqIZg&9NKVnZ5dh^0;9a+ty@#?4f+u>m8 zM1_neY@BzmU*HwEdq5t1xr&huB26O_KGC&djNE17$(HJ2z#dxe6s{58f*C!=X>Vl^ z>omfSSxfxwoj*GHFDoUG%cI;Fcsyiey4>-t#?+WxA?RU_k9=Ca6no{4to}(mI2uPk zsoD%*G00%~>dphbur=lH;kp;#2^wk7(+j~U5PG!?XqhE^7U3(d(}Vxk3(+qoo_M&1 zwhTtQ_wFjJ3i<_mzXkj3elM>%BG*ayyai{0SjpPv|IAGAM3lv>rxZM3g4TD8fKEoT z^4K!C#EqC2HJ@ ztIIFBz_FPUNtx1Kx}yH$@eq&hXJq{+w2QJFM`|tab5pXP#3NV zBbr*6>t%J;1m!RX&a&P8dbRl?_{Ek=tBY(-{AB5gRFlTOjl_+`&b!jcKt3(_okZv5 z1eIR~q_d|1PfM{+_Np7VT4y{yP%U#yO)%~GIi^(=GcfLQq zgg?>vpw~QVPNvg$pDgz3&S>5#&nh|p(7qV_MD#iX{ouanAZ3xnfkr)5E!jJB=i2$g z>9!tM>5xEtg$y3U^qYYlI$P|L0kEL6r#jsu09hb$8KK!?^OrszUr_|f9ijA+5yZg* zYUjbf=wx-Eovb(jk#4#q#r0#Ax}MC5?#h~U_uxQAbGR<4=_8hm;icl$iSV03asRAC zo`$A-M%ae#$UTo0{@n+>1;-6{lnD~??G8%F%KvqW<1m4pI{V)XpE~v0&G~T zpEw8}{ufr~x_~1>3_4nP0<7r{?N4#vf%GOaLNDx%&x45sjC`Pc#b=*O2+;b<4g$Oe#`7e2S0>-sSicMd1q_gxE2GBPm!#fAcET6n zFRJtaf7qvb0_aRyb&(VaOuzn1n4ZbsOC5P^8jERu6gOr=v;6Tw+En`uV64u)je5RH z9W=xoQl#cP9JS|uSI@)C!oSE>0#|QU1%&diKwmd^RHy5&Blne=o9i_kyCK&~pK5N1 zgPD!>w1%1VZrsgEZnUVEO#I;K^I+{4X(TVcz}k>?-+--ChyF&^@0EMBLFaRNbD75A zHMkM|cB@mS`6WzITV!Rk$2c+$_(uTU{cwxRlN2aMHo5b$uk=`d-9EW}Baemu+r zvjSh4T{XU4om77NF4ty;9 z(lYEa)#y*!+1ZP?6^8;G2K;3WT%BK9F5$|%g)GMG%7@^bY}=ni>YqNa-xVfvYD=e> zcE8-X2h-I{a5a5*sxrh#g_C@r8}*fg4SAPcyRx>^;9;oh#{l;=~0TywlI4 zJ=Vd$mwg7ZB^}?jC^UVL*46bgp=2L^4cO6+FXx1ZU%!Za&Qg5E_yeMAT$lN9;l&y0 zmy=I63EBiimasurR%@O8?Q)#Titv`C$HrBF@Ap*9J#fWWZ0~o#n)+(W>(h;BhzA)* z`1mPQm?qUF1O7Whg1mZ4%ff4#__~;lHX-`y>(mM#pGrl5huRnea02N+W!|Jb>D(u& zZY{%`u`>kkTjS7vyLFIw*K@pOiXdQ7N~E?X8yY@UMOxleG@hEIP#r>o*y;>Ih#=R= zCF;!nnMYS-X_TPI@G2s^8&??5+hJYSO99eX{3ql9>B6n-DkAEHn!TGZQXrp8{|L5B4%o znq35;tSj|+1jL={{7}-7a3%>@K+DEA8VRuvod;*Dk=^Cla@$fLfj89 zO6&An4=hWr2deK=7dm^Pii6!;2Tm?>l5FlgXV>RlO{p_`5fktF1||?;j%K8g)njNy zPd}7{RJ)&XiJ5|->Cjd+a9+uY-eU6rfydesd9<4wa7&s|VT3NN4>zA158shZQTkX` z{N%;0sBRXso==~#i0p!;;7Ar3&IlfXu)nGKQj&J<=7C%u2j{^CsMM=WNxm@XQ`ygx z=L0{y;?#jnS1WneNqtwlF2r$iYzxKbdV#u#-)oW9| z@N9IT%lUjGRdH_0ZQ3g80BJA}L%bxn)|5YG-66_|K{5EApjfO&cU9sQOj%&Aa>^)Lv`w zDQn4U5;A<*r5OsRA}@%^fqy!)Ye!B=P4&|dQ^~vd=L3R@y%MLGAN#Oep)q2YE)afHa!Y6xQj^X!ni33M12Mr_qfD3|FZ6b}8JuJsLdKiDUH7=D1^~+W-J-c}LW}pPOF&Do(ukwG zO%5*WsrKrO^UgX?2w5Yp7RpVRpSw@`PuKgGQ)UuN)rhQSYPsW>Ex*CRVQ4X{s&cZa zu|bBcH}ee~$K-BvUj^~71oQvM`pUSb-uP_=1ObsQi76qSO2&4*FOSNb5F!;S+*he!eoixncS9Pld-J}Q#-Q>ix z)hD>zs=BP_VT@5du{_hap|K@ZTbNwWvNog)COe1mtkvT=g|Mz4e{yPPv~)ZoWSEPn zbR%BTx+X4u} z?sc06mEw4lr5@aNKc1!CHsb_boIIeuTgXNdL@1W*8hT28JPEcwzXFUT0%~Qj1e?KG-!r8Y+1`@< zCSrT#P&Zn_O=Sv8`;;4vFRU{q#tL{6{luaou!z3$1nt|^BJ3MIa^p7q94l~!sGG{d zCZ&l($YG)9l~NC76BPfN5S?Y6Fk6@{1GNdua0091!;D@$gzM7PKVtC+6YzdJg8-ZRT(*q!$f5C9)Wj84)nh&tFCml|={GGl_T2}m;=7fRU6Au6E zo;KnPi1~qJxCbERZ{G7@q|pHyHkv6r8JL0#F+Qlz7NKoGCPQ;(UpkySKFfaSwyX4F zQTBDsOm8CrAVijW3liRK+oWFhXaCxG5^^TdZ&zdL>ra(d51Lt`5cii_f7>^wAL~VZ zv}U?rcB82f8Vt0wmLBJYItTniW&tA!LW@66BO9BXYV{`PBm}UgDa*WrJNEG*C;ePu z$CekLRx%f19U0zSLm2(P=Hdqph*5Yn)GgjmR_~3U3*uS7dYpT1^!el?wPJ0PoU-vg zUXGGQox+*}(Wb<8DS;p<|3b2USNHp(t0d5}u3mP5khK0&DvlS32ML$~1WwRvMY;{i zOltE)V#RzV-2D6UtgLc1kB_#eiCr}ONS#fuspzls>gAMVzwGNEM$$GuW8P?*y$S;v{WZ*Oz?ZG$&tDKrZ-{yEiqdllxjHc ziT1DPjz3Z%C!^I5TIwTM0;7pL%dV~-ACh{RKz66`aPniVp}WLVoQ*4zxLr2@s|`pQ_yPgDQ^GZgI9zsu1ImDtmAfj@ zu6!>7y#Ut=ZjFZ$c8Pr-$E@TyH1>CV4 zeN_>0`y#UZIB3-O<(&{L_>sF>?t)v?=21`tG8wo}E__TmsSVO9g8zL=xPCFx4`Y|q zG5LF}@cP7k#w&a<<)k^_b>77E3Z%X+3pR(8(K@Wy1^EYRBwT z^AoP%in)zEud(@&^%X_U+1!Z=rB92Oey+36+rh7D^cdn#?YigMl3Mhe?EPME;2>Cs z`TLDsH-tl;*Ht8YneWj8T9eIdmUd8vFP_qPZ!ha{*s+yu5nf@1cS=eP7jx=-r9zggzkkaB zqtA|I*NFHpI8YCIHY<6dA9g35%r1iaSU9rMcg0S9NdU6X2{1eedDzeW*!cz%gYkI> z%qvcrGjLS8d)=}PjyDy*p{jNA92of-2g)LaU4d_hjzP!&mj%$yS`jKD{6>SETEudm z92~H$nP|Msi`%U>iUl3z)BhR3F<(*G8~Dl?hgTW6ps#D3vqOZxnftDn)82$Gyk=DQ z^1qsZs-@7<*?!mrgv@)XoD(*DVyI9*ff${KB}Py7GS(AGHe*-j0|`shN(vJT3Rfe(2GEUif|eTpK3hwb1>bw_^|{8eMs2u%|H$!t{eo*?$&V;pv9 zH?JGU4?L*yDX4ts3i?Bq?1G*=m+SOskA*ZHei3ETQma4?z}66gU6j6uz3WkMrw^~A zODR6V>{uHvQ6_gtp@tnK=JYlG=6F=wAPn($qlLA*%}L3xdRYmt;Rj(}u71%dR2lSF z`Rq7a`iF%@Yi_y%@I!g_4}7N9-7V*+X>Z<0>yJlEKwb;SwuQx+q6gL46WE!=oLvp# z^BSr@JimTN{HE&Rzk8E|ClvD@X&aHiAFb>c`;~}wVxQ*O*dj6BzqaiG@e%$>#l-l9 zglhf{H}=rQeE}lpRXERoHY57m{h;BDXW?LB)@4{ic3>_Pe_rdJ4#+_&kXZvd$i;K) z$wBy3ndim=V`9LopT;CF@ln5Nh=E-Jd9=?zsD4V_;-l52q~1%{d_GmSa5vnkC-vc< zrR~rDd_1cpiw2@&j0BvmMBsHrn-{a~f`fMVW`9yc-vvDlV&p*f61!HRh` zu@ofCtjAGr-6XU*8+U1M<31U!o31>#st}6Huks2xPK%j z#6&1uvZAknQ-38U%kJNSeb{iRp4Kk38P0t+00@Ny-ZMvGSV3B%Rv6O)Jj6e$RCiVa zN7ZG5Ms_Y5?LOLAe7g= zS_7%49*KM&U7P4{zHMXSeGcx7S;+QhZ8j7Zv!H#;qSI3b}Hd zwdCu44TW=YeuJzMIbBuoOT&vA*3lsd)~?(ODNtp8>GgAAr%7m+@p2yd4n7^S9@j60 zwRYO)SX6a8Inh-8wlkQEmzmEisJyChYvS~J<H<3%Wm;FKtMB~0;{vVx8Wh#vNR7|`bg}5zSATKZfcjEzUGH8$+kd0Y)ZM?5w4qQU z>c&piPQyOPs#pRVvBD>+I_+G!K&-5Hd9mp*bRVNF7l@`Nztt<)ewYDOmo&)z)8=A@D zRLrZPwMW%5MGF2ej&Z3p{__M}g{PsCpg9p0Z|T2I?OsIbbdo_?F`OBX?Ai4Fx~B5# zsdjU$$D88O%=~%GsfLN`bTA=uYvuX9+;ec3oD?SIdUzMb?{_{9F>Ll64fyY7^A*27 za{!N6jc}ZS1q^3S`^vVoWnX#K zbh-a5@gDl!EsU6Qo5aaxUM}pg^bZDA`Q>B-Ovww%erKWgnHstQ`%^`)%B)o0JfrK) z0g@+1ka(Z+Zwv(YdHiWUJW1wo^UyD(97#x0x?e7* z&#h3gKXm!0WG@(qlk5Mhx?q@v-34kGoM<>a1&lODlQ5|zb9YYwF zM5)HT`tjFDFx7t;F=q^`yoW8-Tjl8nKfe1_Z){IRD5rJ4(wj0wfQm<2#TahZr*tD& zp=V{J%LGKJpxNu7eQRu1I-H%5Zj;~s)T5h%Z(i;99{b9yfm;=$13Nn2idBM_wItqs zb0t&na_eV`;e`Y+>}={Dy5sx$i4H}&tfyqrsqyz_2H4rz&a-&%N;(s1@0cXcF>RNj59C&6>K|9El*$N(V!LDBz{kJ!!!vt1k+2$=3UI2 zzj=pT#hf`uhya_y$1nxyIOMq|(IZ@EUZsIH;}$gX%WULDf0;8AU?+ay+> zgkxh-77PADil`q#E^t=@Z{zJyXnoXnC?`N2G7w!53%t8j`aA(~SU)5bIAjCITUR4W zaMkTWaDd|SH@7qEo|O{W9EnR>MfcM+q+sDJL7>JbQupUgpjto*t$y!*2O(U1vp&}1 zHV>YefH%tkVyy6xLt$ciXwr*Bq)*{jS>iUy%e{!293KVx_}}L@LCkbot;P=5xbpu7 zWgQz6DUp|~BV}o@Qc_hP6uB(h-M3pvG7i#Z70ySWb9gruQjoTG{ADz^ebga~pEp&lueGOD%B!@p=x7<7L^N zqRZmMothuv+01plF0U7gIWp?-&d4|76+yXjQ}3A;FV8r_d6O59o+D2gM z-+r-;tKX`hHC&D!lvoHMs-ymyZfmO5-K{HrXSf@$+PHz!w6xFWX0tFL41o6nN={oZ zeC8RsEz9wjB0jbAb3;(@`tOD$h`>y7m30LgEnZWvX+ES-x)ZXxSZ=k;Ve5HspTj2u z{fE%zC5QCDEWFO#=(|vr*R=fZS-at={0x0!Y)CIxkB>qe!tF-(;w|Gk_p!t?I+{uF52MZ8-IP?bO3J32Oy6bJ_0Y07@lZip#XI{z>lUCb_aqs@tt%N>164 zSlL9;v4IDCUl`1oCON}~9+eD7gZ^ln?Ncu*E>ruu|1QJA${ZsW;~m5>nt07(Q%E*& zI5L6KV7tf#e)|RPVUjz*mGwgF*U$DEJVtg3*Ts3h3oKxgS`T3FCvzVJy!d#K1H(1l z+kjr`1cUPaAKvVf3sFAN=AQQPYk9{Z5|rlwg-!-<3!J#SSOhKKFA5j*@|<^u$}Mwu z`2o78Ii0}|eiQg=d^tu#0FQ=!dW1CW-pKsDyLGH2OG416GoTc(r zxCU~&;UM5e^|{Is_&m4a?s;uPYe2wcv!(39F(zi2RD7?YGRR_57q*AvuiRpW8HxU_>u(#6slPHI4S)%}znSobMSs!nQOlQA3?xZNI2mq$(_$EKQS07|n0r zt8s+pio5MpR@N$B9}$VbR>Fqgj!-r?=czE>LZFQ+a|GTq>JbS4%1;TC(9rp5_Jn{1 z*+k`ND$qFZbT9dPQs}~Bva`-1X#sq#*yxXd+FJ>5)Z3`JgFA~RJPF%Bw8qJE7H&|O zBLv7bd}rsloIdK-;XUIu*Ty> zi2T_#nj~?Y7OxyUvh=9c(^W4ZODjlYoVo(skG+mrm67ijMF1!T$Ta0Sn}eQTE*c$oiNaZGg%O)J6x-wuOibuAWvuN9gmT8kXe1BBZpf4_mE*&N@q?t<0Eh&0`t%5&q zD+n*PSS>Ds@LQfnL)i<{J`y25lb0!PRU5Q0jh;sp8U#Spl6RS8We(kr#5-D^b^Gb4 z%$f(`=35@_3QTC8%p={vPcI%=ol?RvKZ6q77N%b=l%pc0#hKiNEymZMNSfC19)Q8> zNIEFq!o$MYk^Wp%OtynMR{0m~BK731?E4QP1e;n&6rqRgto(4=LY;=2th%=s<+ui{Pnos@Hn{>_V^ zX<#w0xgk@>hqz1YJ>P7_w1LDPpi#uscNr+!#0kdI_Aec_gxR4sXdw0-TD1?)d>9IlXVhiAOk1pj?w>E z{k0RAwFl* z-lG1?42 zIdei0o-hP5csw+NpFHMa#7bZL#OSUFNVW+Z4cExUmVMENCX2C}9De6_G9mX`D&QJV zW%zMh>}OWR2p)NGumLCn?iNc0*|wLI276)~K>4}qMV!}t*0kX^U5QF4Z*_}BCG~sQ zMO;gBg)c^>VILeEZAI_1pqP|5$lE%4Fcs`EX<2^I2gdZ*2{}CjP2g2Rqm?D!zQAXp zI%$MDLh?wU3x5Oqz{rA~h10y2=Ioi+)5L(I1W+EFADeWB_p&(@rIGiev+}3tN~xC= zBD7qE0O!K8G1)P`b2=wg`uh#oL9R3C4r90b>x<8Fn)rFxcuGo^wAb{-w;Des^ukvp z19VZ}Z+=p>W~T+`H6d}!i;*)TV~gTR-id(XUDYaXxF3TaNFpjb{-e$&@V#*#r$Y^+ z!J)6@QW;>Exo|Oy@(nY5J$0DHPe7vK5#CaNjQ0H;Ow?TL_MA^G@cyGd>q@d6@EcG+ zcrccmgt+*4&&Q%NWgv6Lhv2hp22+NeEvIIjHu{Vl-Icic3#Shn$y>SlKc?Tc{^b8Y z>~uRh{8{%M%UscUwZy2DrGD9*CbbEHghG`aT9=7vgw&< zNHPE3^{Sq^X+(~D%LrUadxrV%;qdWQaeHGSF^EtGxT5Sz;q~9RC8iKtGt=Q9Xqmhq zVR$^u4jSrUF?gutO$D;6!9WP-2mekxL4gb=gy;(RCOvFMsS9$)$PxsjpXi1J^H(ix z;GX30ikBdKF>p!A6I-H`w%h=0$d+0v(&h4C0}M(-r=j+tCh6e($~$lGxK) zLp&B{A!H%rGA1hCT#nBjW^sA(tutfY8i;}IL;c`Sw)7tj%8@T82f**%w{ZW(O%mE@ z$AgJV5oq`;5<~vm9@XTy;npEL1leEXiJRw6o3O@L)Wzi>2Re;62JT$D1lo$%`Jcgz&#Rg>aoBns?hp2u#IR!<+?Jd zqhOfFm+!XYPiAih{_>Dm^Mr3UR8IP&y7z^w4;Y4=Eq2$Y#B7W;-F^09xze<=a5e|u;^ia0JG z>tXfFDk=OB3|84+MPG)}Hi#aVrPP@Tu)jrwj4G}8ZrA(WNEdBF9?p73uP}0t`yk5V zle}v8+lNS!#7r&bePH;n^MJIZ@2_%Vw(`2?vCx#X1I1$(j`2;e(L@{i->ozJGu~~De_PY6q`zy z7@u4$@#-#3AKPO8INT*e7blteXpF7{V4#JHP$2?+y}AY8fcy6+Lo|V|O&RXcN7Qqw zx1HSKJ)?(9?dDH)EVd35!rp&GXb%Auy;o_`pLjW2=|Nl zH@psO=O?TIX_mRLPT0&4j6|{r{OA79Jb$ODmxNdme!mfG^9|&;mxN{4rU@21Bi3nA z;Xn?+Iti8O%FXBQO-xI0SDVoKV-%?<2`!1Jb9(-y!s)QT{EENEr>QCdg3W`@RHCQ9 zcO*jgM1Zz2N#7j6+E1ZJ^=R>FF^+fk@b@H9AFF@_a6M&28ilC9wHLHOE8fkCO=((C3xu*Tf^mXORP=SAPyK9PM z;HZYZ3p~#7W%qWa5B=d4*LMNBmfLMx2=UE3(x06j%q}2YRZZaeJP=v%s~%28`210Y z!oFVPPOkUJ;d$Mc&Vrh``r5t6KlOmvAJ`TZ?tAN&u#MbFpN*Y~*&XlDg!m70^F8Rl z%5hB@Vf%l@O>(>^@712>eRoA|HosuKUOAQ*@2Nd)PIk&}ekCm9V=E>#9v4<)e?_L* zype>(9%?>Zf>%2B(|V>;?R?jNsh_K}I(Adfr|3n%M`vCCYx}}1+nwkTW5X#jZS$$? z+M6_`Vz=XiA9ayKHN#S%!fH``{qP{NkS{TBJ}h3qL+l?%4x~ysi9p>7!A`P1A57|4 zoU&PffA(AkLT^5$_WhuuXXfVBHR_a$0g`ZUP~IM`lH6USf88kpRj$eMqg3Af`7Opf zn_?2I3z1-y*)8%k91o>Ah`vK$(@o|ztoc;zW)4uur$0d*>d(jvF`y4@EAMvJ$pXB@ z-Z8HlOfAFnF8TEIeDEl)#y3XG(f9@H4;kpVp`u{-t3xc#eC0r)ah#wOgCD}6UJJim zcOKLpdVU3k?W8k*nMJC~i_@OqP|40_hx!%-3iPgxweoFS;??EM}!%DkQ! zRypJVMEmZp;W|)cHW?G0e$kz*J~96sAF~`r5iXb)k1ti0t6Vm68U21?p6zhqH+{_J z@TjgIr60-)XjX|DN&5IdLd0I=5|D;}I z858@-rANn*6uA-M6vXwt=UnGmhi=S48V9CL9o}ZEFVhu7uxFfq9*kis zz#H|P|7s}!D4SWp=SJCkGYOFMKZSH)t*%U!KCS$;&%CjRT0hQJ+%5^>Eq7o~`0Z}3 zo)rHh=tokAbk?jicEThfH{<&H2s?##{YYyJXL; zZcRxonQd6JTC!_;8;d08v`WEC)C0DkRoQ_D!1s)j#Xfi?-uWj6wl)fSbIHEK8{cdE zGCH8bH=9|Z zjn$vCbN^4jC2G{(UX}z_Q?*3VQbX~#g&oC(7#06{#Nxy9R+w0A`ABu!*HaRJVsOai zE3so7W0S05>>Ym^h-eZlh$8)%SN(AzUr86pqSx?_st@Kdt+(mbsYu>SWcmYq7QBt& z0%qmy)a`oifXO=YiZ~MM!(vz7KGhJ3T@gmQN^}q4^1+8efU{DIbqSkSgooA%-&K|Z z4-Le)8&(b&K{1Mak(D)l!Xd-I3)%j`JUKwc`9Mh!G5$7nwk%*zAuUE!hdwpChRq>C?w92s(ar-8FwV1YM66}@%{D51? z_VNK)5Us6iA-f>umJgOz3Rd-k`64gq@HcIj$Og!}fl2i}U8lLFOMd%~gwmbzA(hxG zJ7TT%%z33}tHIdSJ@V`-h>c7&ZihFyuN&imOU|&k%va&d*kcIgCqdmK31Csa{X<;# zza{gCEJt0im_L81N&ox><;!ECTu%*e`8$ZuX@Yl|-&;J3$S@};0FAHMzWV1>XPQAx zvXuG8%_4tNc5wW%5$aVt4A5>)eojgzf%{GyAdti(W7AuXVuf_b@rLEAFWmqgxwK`! zyQ=Q~B~U|51)PLz#&f6J9{FVBwBcxpkg-={X;*$M(!rOx2_vs#VN!VQMDOA!W#myL zWDt@D(9_Y*$rVWFy@pJ_Nqa3Z&#^{kF49ilNce|1OtlA&4p)`f%)v`|_(%y3`MDS4 zalLp41>;5zYyUjuC2TtKkf}n8gV-QL$g5bAX%Yna!{AJV0bs0L6+ENQ*m46V4e(sa zL%eRgs{ow`_#vzB6H~H4@;=_w2lKN=idHDALOk#2>$rk73QcR~z3WZ5G1vyWS~4Tu z;K?2?)YVcM#cO)mo922~a5|x(`3Jp_K?L*X3+y`C_8buB zLfv#%AK}yOOLIBkDoO=aQssZ&0ve8Pd}JeE9B2U<-DuVOn)0<%^P7%VWzRy zPW!m1IMCi&k{Jf~P_9%QzVT8vc~>)6Rp7<1 zQDS56!v~sQ@Bi$tEiy|CEJ(V2wxLR(*9iH8i|=^V?jyP-JHY(18S*XBCj8^82%G1yJ8N{;Yv`U0`u z`c2rE=Siua#xl}pSjE3`$Cp@eOD#bZYVEW`nnw}pvRsLUya=Ii-8Ab0ZPQBd5KB0s zLrj})h-VFdy~9XNID#DCQJ=0~(j;(73?Xk?^dtF+oskR=v@k{W=&EYU!Vvn`59&5H zkn-9T+vEp#lkl|k#)3QAPA{|j`Y?WDC?MI@Mj*VS zaUF>(3;7_?#0{BW$`Jhd7&%i@+gh!kUi3jJ8{o6UB78UJa$sb`73;7V(b@l56^3Nz z9`{f^n_Xl4B!ymN@{vY$ChN_zYIYoyWR#Ej@9mLfGCovHrF!$?BR-NTX7-PcUZ;a4 zAFGL#^tg#1LS$&goLlDK&YaT+kF1NSq7N$J5Z3NtX4%TN+77Lz;WpsUXT>eHz_)8( zsVP~TysfKo#clfKXDztl&%4u=>3;=@-|as@dM&zUaL*WE1to7SPQOI!icNP6yQ3Em zWdx<=-B?D1+X}w%4v*Pz?taf~>sO18%H<{4i!LnVc&Rp9VH7jM)L?x%?hoJ0GVI+^ zdbkl#jh2HebdI#>(AZe&xC|K4-|fD-N-;j`VsOf=Y;K%pgq^C09jfWfbmI!7a3l~P zoO`MF%Q6;1OiGP5;i7)M_<<6T3CI9U52|g&e-^eW+x=+BUq8mdiQ5ar{}pk=>B~>x zp8c7t2DLJ42HjwX@#PAnOz`JLubs+s70<20B;fr5adLr6EzJ2dz%dA;T0SIbKjW(J z2hSz>OV{!Myi=Xb6LByM84Z{FrA>lwHtbcvqvKcqT&^kr+m2xF43KX{XPft#dA-_d zg4&C;-*;d=R#+TX->;eDrCz}baYfZ)*#u1pWr<<}*pdS)ag7}JYcek#@Scr6f>50x z;ouX?rCR?lenQ%0={Gr}Z>~}WaOzmPSzKX;4>!lS09634*EFa51EyM^0x>YW(-E7S zC}I$1RsUgYedPUJ9(YHV2IZ5(yQODw&$1bF$2?9Lq0}XdqOqVbm5}2&(#Xv}?k`D@ zFitgh>|LesgK?3xYnz&437ohYMV6_1x4=ijj}KrE?ylGg5m@J4I%D0%^I3rok7B0Y z=RB9*0wM9>Co*;K*a9C{rih-DcY+yfrg5dT+E;wNLH9r=Ur=hR--?qQ2{`O)%dyy1 z)Z>f8DeG|xj46mS6x2jdu`L`UOK=K|x6FJa>fN!Cm_N3S0${u zNE_; zFvum4J3&Tb2KNBS6mWa_-^^UG0rHZZ&2uqyRJwA3a(f3@kv<82ds(1fA%V#n2qsx8HaO&N(70)yS5pR3$IGC``1vJJzia`v=^K*up90hiL{X6T?q5gY%<8 zTwF?(m>NI7?=&&?{rTu*O0V-5BlAR2`QFXkA7-%Xczu6gjpHcLt9RD=o1<2j`%*0~ zEU7t|Ezims>#72H+~(#&A7D+Z*8AGM3rROzsM;dQ7GL)`{MEyTR@Al4C9I)Ot2$TG z30`1VMfKnRf=qvnR_$$!bihyF*w!tsQ2&)jtf}&aBF<|htO7fM*c6XF);9c2m31up z!d1!U)Xu4_cIj2BBLU6xWhQ4f`d3v+(`s45GflKk?!$EI*hXBZ zQfn>Gr(tU`-)ogZqBiPKA6q0tP91t=-j-e$!Ia1+DD&D#*jHHKzU?(iV0L91{h@m(Mx z_MX~m!Pomap7i3IR%WkjZ<{3ft<&}YaAgDvV&7uwMD+IGZIj-(wpZV3d}SS(epFjO z_3zUT!i6Q$A>dr_P(v-Z_<5Wg16B1ABsV?!mL27H)rR~U>UR%zB#uOg`V$aLXYziR znD>mL^Wr!r+G=^a>DVR}7C}9e#Xmilg)+@J6gln@dlTEr5Q?V1Zj$m{^uPHef#=cV z*)C7dGdDQTPz3kDpB~wabM(BvO#k{P>lj}bzl(_F+Gm2f_1}l)QQ-iJ4CYag#4dmEL z$-1ig5!h;|_q$H&7Gfn9iKCmTBbIe`9Z1KDm!fy@Tccc;xe`Y)9*U12gj?QrQ-Zp+ZXHQf zHnC+9>kLR5KU;gpVnayu56#8z4f;dPm^%X|!kZ(sD;cw|tFj7qeE~u}!kyo?XGAa; z#=c3~(?|B-d(0PNGIimBmmH|!SB3atMnTJkfv%!Jn{c4Ky;IHXKO%R0Eb zO)_1?a*&o#+AZ?pak_t{AX8*fp|C#e&pK4`$adx^WDT$!i^p)kepl>DD~skC1^Y4 zC<;V}#y}1;aI_oR{omzl?5F~xocC*-ss8R_4m=V^9Mfa~_$&qza&|F}1`mPb`nEBq zpYG(qVo+BvbfoCXpC@;GjP|WS_M&l!KHU3vngDZr;?)qDhNvMvFMbvT0fwX9p)oKv z%Cvu#NDZ4x_z-OO_viOL2DX>^UIve=Q_1)Ke1;WB(m4{~ya`v-5(<*A%iPrG`kG+l zRs7*V3gDO`ITi%m{DucO0d+Sxc*8>|TZJgFvH0%Ao!#A57>2*svYMDg7&@6`q~Sf? z0t@%u>X&F9rdk}ccELy}MdQZ)=9F*1j3W5|FWvCuLz(0MVv53>@7_kV4p75Xf6Cnx(BkiYzKG9ybJU)3^HW6W@Av6rpWPM|>;yH!Ri1rHAPeDR zQE5qG#ID|NJa==b#qqtfVc^CM_UL@rr4P1u{9%~p6Io1F9@3k%c?4HoP`TNxvgUU3 zuISsYAQ2x7uV8_7jeLwm{OaspZ!hZ$?Sxg8%uD`@+OnK$~41RC6q zDu35sLNgh5|6A+t=P!Sk8v7+$2(v#+5|}e@>#!n8&6k;3#ybC^Ov&s~IGm$&Y3cpOH)3PY zc!M|RPcQIJC<&_igiX|uae@GPgdwwN7!($<^XUABWJg_3# z5^(uxvERL~2iCJKpSuq0x?X!SL=+MAY+&^CCu}GT^SI66Gai-f241ScVqROk3LV0^ z>TF?gMbeGLRLLeO3MdgJE)yQMzPdyCoFUgsIfq3EYDl#hI8RCcCSR;er)a>6;DLp2 z4spTQa&cRlnPfD)eRP=RC`QPL>^gW`Gl2(6m;URCb!;mp?vc4-QpR+A_0@llzKK)j zDzw<(z8x7$&(v_dY-_r9rJs&l$I9lah|p}tsQH@m^W4Ax+t-Xyf~!kMV~;OD-x9Yz zq`Ri(prdi`>(iQ%RUT-v+K#XQg_|pe-Y}$O7@mSSTK4O>Y-EqegN(Tq}CEXWGr3EYc za;kO6%*PH)SJd0bUD%NfBdH%uiC)K_3G zc#6yvA@_%;Re_2+sx@j}RYkPl6&-*n*skPr4p{Mc6INLZ|N&iFdPdlf`6_ z;cTZoccV8~(fij}LZmv#4zB8Ye|Z#9{QPG6#Bs0YwYytwgfKwKd!I=0L8I!s&TJ*H z`C5S(Dg7F-7KWaZP=G+$!0>N*;xPt%%klteAF+sPNEN;K|2BKc#78;V!FrXWzBxaF z2Pf*mY%|YiV`;U#W1m|pOYe@wF)BCFZG9KMQ*M4zbjvU6kL<%UvT)4fTO*#ImnOSp z%pKQ6l|JkM*N|i8)7OxuNr&Xngd39I-_B>@#MVQ zrA2?cmb)N)ZK5>2A5yw$0rh7O8G41MA?d8sJ>9HemuUX+i#O@s9H1Io9dhpJEDS6G zq|DDQ`G;gOt2=jJdQp(54vbE5U1qFQ6SXPkoi$y?^jN+JwNObc*1}+4%QhPbr)w-BPUBgJ9oV^G9SS)O`kNRejKB&z zteH1O?k4a1OyNXJLN

aNL!o z`}NL&9vY6>>gl`ML3ZAIcn}XFXiu3Se3by|7Lue(`7ZHPTU8#}j>=S0lzM9Edh4%F z9U}OTkheV0KSh>y8(UccjI4QG3y7Zn!)gLYX!+aAPs*XQIRnE<@k>8xuc{lq376u= zV>z2<&*6zqX&8{GpqJlSmGk`h?mtXuNVe@(7O{1UUoHo#AeW;4WdFNXUe5fW{fDtu z4b!~s3|G9dO5v@XRr=pNo{@K7r;tCr&uSv^lv~&9y>Z|t^_SA?vA#=jlCAJ>bXrS| zrLUT3bHy-QG{1{{^e~Z+q*^KqzZ5~W*7TwdpSa^QWsHp(dtuXM_Jj8`8OtZ)BaE#N z9}?GX!+G|KUsG@#I~{D_CDy)Mrk`JFbx4-BSC?G-LppiKdi5$roLEZ1vh|0u?X3#A z=`3lV)tX5nD8#&It6jE*YLibG&SxX%rTSrB6Lx^cJ_*Ask?W zxH@ni-KSpd{40Xhl4mKQV$wB*3#qUXl`g_T@4f0-$G z-$%9p4lFMrL@{u*zW6~9LFUDsFU=s}m(3mlp0o!C>$6_*qi=nPsB_2jP!K>74rCv+ zR5h}*lCPbBRBMB}d^Y^xb%%CwlXcitGr+z|N2vkl+QNotUHhhZZ|C40@psre1NYak zH+<^;$%EjptmJvCD8#_*J)kwsm)KQmv5fvE6qdUB(z!W-=Fjd_9noKq9pMl&&0FT?=}COPo6Q?3S0ko!pPxSVtmhM zm6MYzut~->`SF?5O3si%cA$IlxO1MO7-A}1NHI+`6J^FElPZX}DP&>o*DA#5+_JpK zhO02A557T17aYV5q7)GO&WF)m`~Z4aihHhB{IFePH!Nrq9LrR$zR)1np4qye|- zaNydG+)PTy#_2w8R^9It`?p@`?vG(`q%Im|C4Dg@N%UsoAesxQKKo&>o}V@)@PVPA z%o^Oy`i2~$HD+UDT3(bj39gM%*EE zBAWY>a0IeMf6p-$4Y=CcbSL!fZ+*HGaexOpidBiIJ^5e)TF5+6iji^zc-l<3F))?t+OxDf1iH zuZ1{&FSxqc3L><>fnZZ!MK&>>Ruel?5@r%HV&AM3Tcc&R?>|DxZI)*~7d!lI=L*Ea ztiOVH5#6v{;7#i=(9tc?k0ECGwCz_BV7)T6J64{1c)M1^ohRp&xWKvxgEeURWxFb_ zm|!L1=kUV67zk1GrU@L(!^aH*W@slMsKJ%*;lT-joF&xVj|Fx41-gA>(vPPgSc4mj=v6Rmlgm4i`oo`9@8W9J6crlCZIZ5&8S6}^S! z3o2J&mnNUSYMnw8XoG}S%CN4ocI~EsHBqkI3lEQ=2n?hy3RSC>wOF)uDxQ5N>)k;A zu!Pfly%&qj+J8991Y+(*G(65`&XoshRf&DI$HjzN_^{ykR4|bd@8D!s^FQn*{N@<@ zf&Z(o}a6><^P9h%-w*V9nO#oxyEXs__xsJ|A`WZlN)d9rpx zf#|Zy7})q_q>x-plMPB)63`1 zN0NxI&pO{v-!fxr%av!YUH&;oY zwu?uEE1MOSw_?NqthBNF~^{3zM=?M}RJe{Xm_iGYIvJ;5!*Hz zCQn6OCrd=JgP~h+L~wz=juYAgfXI z!4d}3CjyuI^KzmBtQiYJ{U4gn!=LK^{r^RxGD5N)5;AfUIrgb!uM|n**p!tm>!h;B zsjSRHLJ9{NS?Ac4y=5Jo%wrwLIEUlBe&_Rj-+q6>>%7kMbzRTL^|>~J%2w(hJchS;5*FCF<<$GCo&PU8$1@)7QP>(nYcgfH=O?DFe z4n!hfkF^THNtvD&n<7fC=N!UMebJ2AM`=tl>`IF4JzmV+UGtqo|LaqAA1L|cWZ$s# z;V38qdGy1sdYWESk3CoHb2C$1FIOr!w0yG5!((_vR-wd6aQDfzGlzVk$&3Dyw_=^6 z&F>Bb*p6-!w(?Xf*t;s+uYv?BcWt-}Z64vGUR>89OupFFN@qXR+L)EG>>VmboO~&F zUNV4)PbJu3Lh|o@C;ix73R{X_AX%Yz0%XP%e&lK;@iKZ{Iv zqJIKR5>s{y=|;(?V9cqk-Hj>6_rN`MJ_;1;yLj%!lp!Nmb~uHN6(gdztj7rmt^&r? zA226ns;{4V1@o(pPPa=UeV#jO<%dxuIAIQjw;_d{*m3L7nXE@N@e#?4 z$F`pAd}IG5_`e-{`!;=w){t;%F8mYuD-2$D0D_x6p>TU3h^PymT<`+W*>C~Nk0!R7 z)gFmSttxdB3_nzMufZNy_$@JCsI9&!$(K6j1Qe(q7eJ<@fi0p{qm`-MkUkI?nT{yzDrIKARR0nBvw6zr(D*^5wjM=Rv589s6hyPbHvY0;jga1#K zbl{56z3=Jm(__=LNR-1jw1*=W~=Wd7g08y%b^JAvDNUj?a(b*wP=L+q{mE8fEc zL)OnoCX%81IGTZ55=$o$)T!Ljb-w!UVVs`T2R91akIp>(cqoa9Acqe0)bweEo0sN% zE)YJFCKS6dKo5j<2(k(z2}hkhoB|P>dLNr;qI{gn7VsvDxqr&?NGjYvb6m}PS?1Os zKnND9`Eei9o&G$YJ|W?3$l5WM!X113Fg*x_NsDJ(B<$<^|{luaI?i}e)4IhKLM*wmB;!QZ#zJ|bfIcM5do?cI>;5}rsNos z3vWCEUhTU5QzQ6LakkYab2z|}wi=#3|B^EUR(Ywb=#%BK11D`?`JZAk%C2|Gy;j?e2Vh%jb6bi35u+|tGV-Bq; zT7|1mFW%vh>CIE~rE~od_UC^6hHX``!+X%F9p-qXN0R`pHrcJz?{qG;g74}uvwHsh zjGi`qf53ap#xSw(G7b-HtN3r&ZFjDzNl>$qJ2{;xyOup>6!JTMa8m!Z-_pcKLsm`R z+%)1@`_=PX;GeJWud>BW44=!cdhkeG-FweM!ti5Bq$h5ll(s=+of-17t&Oy^y_|oL z{Qp@1f2Jq&zlf8TTMkKYKd_GQu0q~8+&<|WYq1^eTf8Egza7B9@Co3VgVrG`q&|J~*$$&i*O8pgOwn!#&}*QF;2b zq~G6`kkEqecVYqn|34m3*g`?_?N$_lE#FoTy@x^OHC(v_6CX=dK83uu?IJB2$0q?x?{ttPs60^C zrq&3hI(%dl5m#?GybYAKM2p`^C_9*(FQZZZ!l6{5NX-~b6z)MerjZXGsa%B?bjy%2$Uz^Z+ZGD39%FU)gq*uBlN>##q9(d9jg7^=*5ad8XpQ4 z3*UHy5PmQ1PDrf%_(gnvL%D*)KlzI1gBT7xCZ%o6?;&x%S7>zWmcM={G$-1%SR7|E zZ=?rkDk%tGo__SSu?0nq(OfWyK4{mJq{LuiS+|WzB^@gI7K>aOIYaNEc(~;m*wW*g zzH^v`S^}2uy6yZBx5(gUPz>NCadH#KhR@uS-Wg)Jw|VWlRVPS`Ye$ZXeI9nQZ3I&0 zj!G>20$QBfA{7J+f%X;$F$HadAJXuitT>R}`f2pXtM@DeDeVQOyK)@ksRwWzf$jdn zQ?`d|v;lWX&4o>emYerPGZz?5E{k_#-yPtDaD$0|(c zJ4vIUfPNavhbxnHmjrqFmrv2XncC(_W1XO8J*eEElSKk|f;16Sg@FDPO&R`9hQFao zmr9e)&vuiGDRs;JB-g|}%o?5u8tnyp~B?B!*6Zz(U_?9oFjryO9aJu~<+HRLoo--F6R8Dvr{cok2Y(pIb%HlBnZ zA1VT`-2ST~D5hP3q5m2VZT4M34-Hd%DW0eyairqC`a9>`Jq6>#0oUi|IheR-GLBM< z-fyF-)RG&Gnm?VBU_Q&;G?scdZ&I5HWK-8F8QL&xU{!korW*5dH9F_Tb?fp6SZ0k+ z7jAc@%W8g27&kDVS`+$xHtX1cO)V0oPI<+z+0-hySJbEy30WY_Q%`p$~oLt3##)bcd2-)C&x#oL1eDs#CJhYI7${zrF<0DiV{&pYu&{2(9Y zHpBh_={`>q^!}7`Tl7OvV^Kg7^t}B{0&rEY(Sopbp^Y9eO>0PLA3OnHn7VNXnhChJ z8_Qi8d`5{Y(KX6h=H@{A0j_D09isAgwQIGqM94#8<;pxv{+p-vN9xCBj7twguJysE@N(a5;-<~liwi?!S(xEy#m2(s6 zz(dH_xKkaH1)s!!4nENt+@7aa`ZlWO`WpnUdw8vFdk=JV{FpA=w8%nkAq~h@CQRuesywO}_74|G&C-%?V zBoOPu%_K)d26ppUS(Otq9Cx#Bm?zswm5bfsxewK7j_fioqj8-i%pQWMH~-cgK>0Y8 zfJFeWlL?5)+j)z(2qz>QGum~Pu%ptoZB4s^hje!jtb1NP&0U=@C1JmUWXM6J&@)sl zi6Gz5>!s8fg0hGA8`Z6E`yJk#n;U4XZ~QmQ-{?Eo!E^EC8|XRZab0M_>)ZP<*Dso} zj{>esKj;#O8m7Dhua`&7q9>sy^Fw#kfpTkjrJQ*4H3^tZd7_l(D56YN2re?ZgcxKh zqYad}g`*cR2h(S(k4Ory+_wnaw?%=%AA`Vs^UfCg3^FxMa=I;LiYiuDa+j-ts02x(nqX?qWBW5UQY2 zAf-FGfpbWRT|nAIb?oI8$86p6Xv@VXoNKrLxTn3m{_s9R1t*6a`W~YCgONch);VnV z3yj6ulG&={F}}AHSgIA5znb=-^EpD9@!8K(iloHzwb*OF^62V}7vSXZsl7PHq{2x(Cyw+(hq6t0`VenG#D+;E1I@^%PA3FS z#yujqG=^2`}FEv7Y4}Oej}1 z!EdhOm)4JL0{oA(0)fkuZ);;PpZ5WgLD0$3mkfkdj0$CgI7bms*~%T=Yz_J7^YlYnZvDjVncs)+4AxK zk{w~_k+^`PB{|d2ojL_xdBG$W6?4bMlLEDKra&Esc>q-pW$J=>9?Me%@QZuSgs?HX zyo1?1ovX9nYrVoISSe;B;L>cf6j;+0r@a1o?b`P2(XzpTrWni@z0ugT-wVc$;9cOo6WfL}U>6qDI-6jDf9 zP-Y5^W}x?df2L6}q9gObjE|Hr5`5Y0X5fAw4zxgaS)uS>?W|oy-o|6zTH$aHN1v)w z?WtRr0aI#m{SxJ|yhyR5T862EEDxI!>0Ymp%06vrrW=&?C6I=C2=E#dACCkdXi~;F zH6)fUqWAxnnmrA6(rO>f8|FF`XO$XvIVq;j6t_Jv^k+>HK{ql|AuS)=`q`;1@CEav z6;izGdxl<``-Wz-xE!I;uFN{|pRYGhzR9>&-(B~TebyZgkUzl*IxnaT`TZea^Tjnh z$L-6%wcf@WL|@y*R{x8@)-~y&R6_Ira9>@&Y$7JV#a4f#AN+MgLln(Y@MM1sIibny zy`I*WMEYdaS|@u&4>O*8Z~^9jGN_?YjG7Wq5b!q?P%1WNiZm*(Y?Y$4YQMN2x&YX4O{S4ckd!8Kw6`y@^_UawbLPE<;BCoCUmw6Gy4^fWZvFg zwv$Tl_prFX-3!w?LFcJ#0*udrZYrV+8@9WT)|#~+s3kz24|0+^pdPa^NF3ttVWR$1 zt;Bo0UH0SfTOC&oOM|)F@tE@T<+qWx8I? z6QGL?soEgyw`G*SGY(Qgom8bi{~mASf=G3WZ>$V5%NX=6Z^}EVWV9JpUkN${go zI&Uig<>`3n?sR-ZG5+l=%e(kbkMGJprFNcp?hMi|W92or_O^YuDW;W?Wmzjg92~T2 z+;7#e3JZ(gmbMB0y*AL_Cidw0nbVBAS#$2^;I(k0pywa{O*vAaMU7|RoBe_K@JGnS z&aqD}gIeD)DgB`&hBX+xr_tXfWBZx!*?Ujixba?}G6cl~=5(A^12Km-b3bJ<1v_u0 zlj=`H6cFM1wbW`2SO5awPz?R2-k`bNCAb74NfU;(Y|j&D&k4i9vDOJdDj#rUU{-)` zCt(gmT>`zvBb%f^wuWjc&A?j3RTMD>w{zY)<%Bwk{Sne2RF74F4fR?Vb-ZWec7ku* zv+xVlkU-#ukENZT2V9_V!+dA9B~j>aA>^7>i|)y~}XK42qvWcxDcjQ!XkWy8i7Pdm;8GL=RbK}@>DtIpsoza z=6A%sI+ezZsG~&M4~~R)%e-cYAi06pqFJ?;Kpj8ePkJX}PvQYjoYOCdzGwQe#AC`V z?aYT)r0%wL0tsT*WG`O{Ocn$--n2#Mu;0eACl*aC4pZa@&%ml!ULG0*J0tf;cBcft8nQ>s%6f>gB8wd-CtFZ`o38Eb*cIm z$d#$U>gyzQOG;bofDP^EXrJL8mTVI~adXbP zt&&sj9|uv}6&klj^^ZpR!(ZV44LM43SW_o2=SgeOc@hwpSoW_dI+ zQr*DkjkJE<+OtO0e+&7vZ8#f14O{4%@k4|xo;J`@xJ&~Ye#v))ypy#JU%Ujyhwn6V zucTxpVCDq+fc%OLKa3f7D0)pReZYn}yW*s6!NFf=#?3F{%A%EjAsZAxLgvD@I$KIu zWu?MXWi@<0UZzNu<9P@ok^JXO@K{=xIvO?)ogEC6y=_u^^V#%6!KWhuYx zW^^|&mF9SxzyeY>!NLE^b^|tzd_Yw3pD}oMtFyFXz0LE&MrF)h+-`N8W;!kkr1akjcpRBWJLH)QPq3sx2*hos|_*teU=5SrCcJ+`CKB2BH&^BEr+tcn|};E#|4n5Qivp<}nxLPOCU{t2&_*PJwfdmD7&E~XV8kn?1jq%(d4C|3-8AZEK6W~Qwwg}!19-Zz3*RIw zoG|~J%IOJ3EVH&IhrYQ=Ok*m2a985sPsCE!Sq`p3sV~?ste>tv))iRu7RoagWBNzm zx;WORoZ-f?A`6KF75b~!>wWt<$b7BwLL(85}@;8|FA|8f}howi! zXqP)KNQXX^92S&{B7G6Huvwa=S>#{66H|V8uAlO$253uCrPB4lINVM4XA})@Se++H ziiEj#rL>sN5PVc&JN9Eq!SPKjp^N7$ti-IhRRF zq3nEH9bL+2bN+EgY5|M=i}Z?_32BjdH%&qV^HIWhAen100~!AdLt-Hm|Rn&pJG(e(@xet)J4uGT5b^juVCEcEstO2H%8k$9jh!VQk4~0+++KdS%yh57u`! zazhDszV!6mA;P~SmB}d<*hcI3O_TMY9SxH}!1^nx`N>W|=4t^Tp?S*)?Iy?C7~Bu%9~TGG*}tWAdQGs7oM%)JVQG7C72S2MS(1*fM>wz3FIU zwBx>f3P-$NES$Tfv064)Sl1}ID^37Tj<6HNm%;35LC{Bm)G*pO44;z*Ic5*senq+2 zAGrVIUQ&GL5oV5Mu6;l5O%2tH2Y9x6i$zq~$Ah-L>LasGQ1IFBxQ4E!ir%LvuV{ff zVIB`EA~Z5R;}xI7$KT7<{E*Uqwl)r3Q%76u-=W-P*_Eopv=}`+C z1z8Gb4T^Nn0a%T@uuZHn(ZWeiI9KkDoLh$VGL|IH%8{li?~*=H zC!dWV;8InONM!?!q=Y*YEGU~|^iro0vt|Y2x#aqNWCm?4IGOS$pCH3#b z0vtSK_~&j|=NZg@j<3p?yGUMvOTOHq>9nazOyJVTEJx?OpG_vG102~RN-w@$3N;qq z|MdIDGmA7-{b~bTi|uMt0X|fdso7p|&I0=9u9ved8X8chkXyQg9A^ z^JZL7hfC;}FTqg*pC4wbD`URi?qV*e`t?20Pnp_!t3^k*sE@P*_N52(n#$;NK127h zDsOY|zWi3Ya72Xn1Zoe!PyV{6yduIHHZiVp?B_}AtbVf>bbgjAqS?U#wU((@0T$|L z%>Y~>w}s>YRKEe7jz|x?BO3!(Bh_S|QPxjn*Mv~rYSuDQ7*zxS#t$^uk!uY!hH?r) z9WhKSA!gj(TO^aGK(o;ACMmFMSb=QqDR=YZUHj9Z`>eXJdeQ0DA)ZHGHm_rM68OH8 zgw*LM-*uYnRSjTjll_>T@q&uc_=qMKLihWF!Y0uVB;~6?1t8vG(IRMm{0mLwI@xnB zmGsm)v?)4V*M5rv;wwI8YhKJne~3FqzTOS-|9H5uEzqAOHJ1A$z7|H@GiYFAotGvd zfiU zj_&Zb!YH~!4^%_YGA-c20sil-g}+JD+Vr-2q8wtTk}A@7k*q`Gl8AaW=o}#?H)OkH zW^2ed8)C?DgK*zK*6)*ofY^rP;~KejZGZ7)gB@#X2g#h(Y;7{E$yaiCf1`CVWF z-tge%u-vl`w!Th_I*wEWHQ94OF z>lhs1veRFHY8*I5i&|Fw)BALj?US0WP>bE|TDkM?%)hr+jgwq#{SlQq8b%Dt1$s#=y>^jUW1eB$v=D&? zkTQ5(bjGnJ!H)?2R!NN(IQFG-rV*Yl^j@J6{Qkb0q5IT+W)gZl)wUga3SpnfKd9q} zLn^(9=l>`w9LK`muF?bdo&(KL74RfXLf7F(!y)L8RxiA0K>6p56Xc&9vzML)$quWF zozHtQBStUkueOK2?1!GKOteqyCr2~m2B$e5=p#4g9;dcP3@PGXG zZD5A_{3;Rx@E8WP$0vDJyM&i~SV~cz_EbaO02D5D7No<=%fqWA&ASk%{HLd-rzPXh z-A$&K#ExXOX?0gri?doB^!$Rjnuo`S;iAaINXTUYH~F{q)7~w`UNN&A4B0XA&3Gnm z<|}^_c!dvE0~SLxaV!e89h1P+yL{*;g!{fbhXnzW6@i@T8EQ`>f|!0q)rP#J@wr%TgigS%h}w$Q-{QOvhd2p%_RL=m`hUg?gteH~;ZO6*J!J>>yIw6c$ z?@YUZ&Z-Vr#TdJ+_bd4?i;T)kb8#SkIy^3VOuvH#S(Od%ko;n)@MW{ZE8_#pu;+H# zBLu8SM&Q?lYf5tJ)GE7I=IZEaRg$gD9_-AmDki}66Zz`tt|pA+{qe?Pw;ai9g3}g5 zqLRBG$bOvj>XI!#>N+`82|ovUk9S^x`^-fbPoj5oM&a&=lpcl;b+gt_Rv~qb48~;NSPg14h`vLs4+((NZ-3 zFS{c_IBEY@O%KpTlCV`bCm;FC?_wqpmTC=K(<_dlB@}W^db2r%53dT`&nTw+TGT`X zUZ+8qAcnk;xx4v^fHH#Iu^*2F6i?UmPg`_icK^-e52_s+HJ;YJA~TUWi(zZI!diGO zTKE|LcL(M;fvvOu?%q@mTsS;2m-)0m9piru5w;lh?})Pg_^sat0f^}Wtd*%9pHUqM z0=zeuFv*!BgcwNL1 zHQ7H330<@*vRGT6KvOo#5Lw|*pjVg3mL=&eUhCRBc<9&4^*`_<$(<~!OMh}NrQmii z$r6wqXZe63&$1a}fsCE?YLf1;!~VY_&j-Qp-sI|opw}x@DI29YojVf+La;4b@MZ$* zm%omUR58V|X43M5F$2mNTS4Abf6f7$+$z?cTjwe z_SAMR*ddtMvd(QhWL3oFQL*spVEZV`C z(JR(-hLD;>XziQb{QPI4y0_g}-Ww{;@?lF^v1!w79_l}K;^B7u-UW`?ZlR%3D2jzQ zro9+TF&622V^W8}x|{yy_vm%U=>ZS%j@0Ob0P%2MapJga=m9T$&H4A4*MA5IlGaQtNZ75P5YHjz z-bWr(Qb2MOF&*ao(~SP5Nnz`zrb)4&uwLIhUm+rl)A-2=-9?i?$fEPuY00F;kNBabWBbzpwU1N;gjlhyYojRa*M3jpuJ zBLl6e3$+w#Ln0XvJg$sF?|Szksk4E`Cchp)u#Uc!RNfa|tKA~##}LBt9_Mju5_De& zanuLcD9yle^>xNTqRk8r6oFodYb*i|UmpkUXp>k6SZf6iS_m$#U0M|LYiEYV23yPUW$65}Ys+ zXh>PphoN`MObDpG`@W7kiGT+m5Lk?S;Xx1FRxkUdPE{+pQJqL|$@EJ9{IpVkVO^_% z96Y>Vx4&-<6Z(K5MxQjXtM&wWixOoPvGdN6`o&DK|uC5pnLa&nY?<^7*cR1iPlOwF+t zdxJ-Ew&wTNIWurFRSGbzVkS6JXm|h@Cr4hmj}hnD1Q#Ru79T)D1)u2=rz4qF3XKH4 zLpiv_(>}$nUFkWWofUbbN6N@9!j;A`7?}l^Eoh5nH*7^Zd=P4v_gMMo%>xnDhoQn& z%khog!r^Pqk%1{Wh|-JFyNJ{Kiz9iXqYFgo z5&O)fy>00lHZ*Btq%@2H11@a{@@`JT*Fm%z9{Lte#Ams>UtAiw8Gj?zCf#R;QAS4P zaEQL6*4#?T?>-wJ=(njPuiuTaDY`)q4-*b(#`m@-ix9yCyTRb^y#bz2A9&vr6gdog zA?0Tn{gfnrF8tf^8mSOQ;)3!^x<9(eVUZvv?D{$CD&|vZ!#{Z-=`Z>Y{wYi8nJOrc zgg`#iCNZ=Jtzw27;>PwNBS(x@u9D(Hd~Xw>Z1_&P3qIEG84`5E=2!MhM5GN#1AKY3e+It)wiz#Q&{ z6rmc$y~OpROf*kFgx{$N)wlrQjtkAhujhkN!=n*|qU*SwjB2Bm59H`t9ypUJX`p3t zL$ApIeEjt>HzVOgv2B#*3SfW?J=w2s;2lYa_`Wl~MqBMP`UJtN&L8i+1OL*4{PdG2 z_E6x1#pu8#+?O!&i@7V$JFo~i_}d}pfqD#3ph4G=0CM3{s{HG<5mF3ZOpmmPL|g>8 z)XOXg?as$v=Hoo(R(DR^s@-ROEW)u!BAaarc4##Ez|VOYtpl+_t>A{3={O_pg==zv zGi5{&mc-)+BiS?}!w|Vs36Y~kecd*J4h?=Q1R5bRoYIa1|3Jquxh2BhnD6`p(Cd(c zF(FLeY&xbOt9lX|g{Y8kOd~`KJbmfp-&uHctT!}&z8;+e8{J-7jedUYvn+RT3e4M8`HP0NlH^ z#cGrQy)>S?!yP>@%AtE+JI8KTQ|;exwU`LhE&9^c7%%m<&f&c_>|1bNPA`O7yn+NZ zUUskzYBim3V*HNEq0zheX>B#P(53FWJ@%vZhrYxV(p1BkYe;k#JdCOrn({H? zW5mzoh=5=uZMalSJBXXiV+Re^-~98VyI}X~-}~;~X_Ec-{qLDh&ezjdKFbQicGlOx zA=Ge*-^)TRA!n_A8(rLp;X8AgYbJjnQI|c_@M2JE>s^hHt{>Vi2A|8MiH8Ur>Pm;!Ijg4p3W)!()q(JduI}+KT zV9|ArD%6{S`%Ooe++b8V7t<~D*(H>oe?Xz`tK+{nh(uwZLy662guY4_V(i^}5qxcPP=j1c(pQ$Kp_7a?^p5soB^=?9 zOE4)b>bKHmEq7dUfc5%NKNJn1z+S_FYm53Xt0}-0(D>#>&?)85@n^RS$jbmuwm$F} zfjZT7(ZX`mFl>op5X!Sbz=j0YO_$(5buLA~>5(8v{r#XYa?_9Po}E&nc?*sKi#64I z=k2)kW9j4?c{m>3gz2J%Nh-WK#aHJDLl^dFsoGt*Yk=LP3N88q!VJ!|DGUuy3#WVm zLtp>Y_+pKV^}3R~w2lUYV@CagD0PIoZs?!`ZxRu@l%SPA)S&YBl(M=$h*mQ;VWhHz zJve$u@uj*@yhe_geUfLu>SU5;!-Z4ti3{DJ7K*JdOydivda(dg+z(u(I#X@}sp$`} z89-;TIFNvx76M#V+D}<<+3*rxkzbFGN34*5SkpVOrG6H4n`w_W1$pjqe0le5$Z$3> z{=*+WB;_vsGh%u{Adr;bKPLi6Q!9VA*eHUL?dF*N>y$cOLGYG}Kx%1zp@AsSZ4SC$w zD?dkDM`6^eyVU-7buESQXye%6*I&7_-Zofv+Pvd8)2k6zw8wE+6R)o}Sg*JHxIe5) z400QZF|PlYWn*`HOdlPx(Yncnj`T2ISRlUCo|C-s@sgMuz7W*)_{xSh9o7cM;x0k)?@*wEZVq?R)|wPyRvs@1`?YD3}NAvH6-%&b#a~-Byw0 zgDABtFQ4bHiP&s?V1pYZ>vYqldAo7Jr=lN|hA--i)0GqQzX#p@!rSdckw>Q(cYqVV zN2bR4aG^$&c>vD%qQJ)2+45|2x+B*2HK`C&F?W5W}lGJ-S@2pzmlbhZ# zt(A`k_eX5TIH(+9C|=0k_g%*+=%`WIt+Dkw@x--0tTN9uwmd8T66N;v_;RKm(@gdT zgXk5TFZ?!T?hD){PtH4{;G27*8I%$H^A(COt{e=*dTth)Gd^PakLO;2Z-LFD7|cpj9hu{W0vTa5i>B91XMl_*IM(*vqq za@-dyxTLm)fL{bQmaL7lR#ucNk|TrVK6_5Vd7iaelPqn`%JGb7Ara8nnm`S zb=3{bgpGM!u`o(qO zaz9CA-Kpl{d4kqD5mE8E>4R65obqw ze&E6R2?IjLt6(MN+q=30EzJ#UlPqOZS1U|=q=RjK|K%oWe*#Zb@|H;a?Gc0vvRDiH za<(ddt>dTrB66eALo-%?+i>YcohR=L)eC%0`j46ix(_EUOYNZsi}4BHFQR*ssFTV5 zLz=AY@82V{o?!+J#~Umyu+X28UZ8}WV4buP5&38oinHu_DFi7atG^^t%2=NOQE7tH?6 z$dkDx#@?zIgQ3HUL^dAr%b!B;`jIYQ1nC9$Xs>r;I>Cp=l!ObUFiH>aWpamC)QPrI z=f{y1=oV}Botrfp3;ql6nGMN%;rEWNhkAyd1{}3Bs>yX4B{5L>e1?&PM&4f^eocT( zjUF-JDVqo&BONbpWufuWB=>-f(RmH;UD94uXx@({nBqoP00xt%;SYG%NR=PT$XMl~ zA`Airf)5*aAw4=+?!Ty>y+!TZS%vpu3^J(rB_bweJ4++KILC7UmMc39p6o|ur|EsC zxXfM6IiNIp9bfcoZ0nA~hPljsO(b`(afeHMTdAQc1?)BOwDVR6(kcebxBuAb`ogTM-_=?agPj-};GBs6>^jU6vG!%|Nb^ z;7{rfEss-q89TLTD6s1N#(#;V3Uw7nUs-ylsaqYd<651greb|TMQ8Qw!_#6OWG&G| zv``9IvGhrT2dKDy)BFK@%<7#aHFYUV4mj+D(U|u3j}bbd=l9+f&+AUq7ATfI zZ>fL(({$Hai^WTKkHt$2B|CK>H#vQ!gP+Ue@~wrOb0!9MGBPLfoVQ)GhMLkB9x{l9 zm47++CrPj>W0rYI%)VAODrCu2Cj=ZGl%f$K{d%*pLfHh#?Pniz(|i-3ErwH7!*Q4# zgYADMfu&eqto(&k($s#sVUiB)3OBhron4B2P#DHoh^5-;5xNOR5oUydk8+2shZcEV_KgwzC5EgYM;rmy}6_#^QK)# zUV0%L9`W{XAGr3R8|hQb*Qk;>(9`Sftt_EIQ;Yqkq+jpAjmyRhI=QPPImE}2ZXrVB z#n7O?ZB9hj%byL3z3g?b+_JYr#bX;<2_)ndfIbai&X-cnB%06+^y{Du>OfZcaIzKQ z{Jwv~;x5RqeMg?OW`9WrC!yb28LqMm#_JVJ?_0Yx;$V5!&27kTOtLAFwyQh+4)z*_ z$V~eTecPyjvq8dh7c|jeI37`+K_%au>yGKQ9lvVhXIL-23iraRhfdC#^Aj=Lk7lre zgDHN-zSNKWtsQ2j?VPHwl((;t9x+|0Df>jkjtyO-e%O%7o8E123&A^d5?;q2^w-v8%8e6C+NEoadyD;FR&Hr>w!Q)q=UJy~eLEIBw8E|7$0 zYvgSjeBFP5N>Bla$G$<--uKHaMYS(C$KLLE=QOfI?W-;}g*{Y7Ve;8dr|{sa6jrE5 zW_I`)Cx|+5wD7<8QcLRwB^IUW1_4DgE^`Z=52+Knp)>G|lFczny3GvSPIRlI#Sz`Z zAKXgJHkFt8xcIWr(0|k{3;vJQdw7N-A20x|d;I%tNEgQT@=f?jLqtn)%&QyWc>V9Y zdb>|3Lu%A>AFdrTkUR9OwsD|+#uG|=s;Tz>ijLX&fWTWWe@+)SY04g$-u>$~9?iCD z;~@*4(2mG5Y%=|pWke9axIQiOpnOA{D}-SOYPPB<3E>K^JJ$|qrmHi+?5;ri#wO0U zd+B$yP_<^i*^Ro1`R)JdZ$5on{`NgY<;yQcH~Clnu7SOoEkV(QqVc_uWEg5RXU2Oa&}wMh|#Hl3?NHFkb$OALXH9u;ZLJl$$-W8+gbwl20?4BT}h4I(E1UPm-SCts8tx_t1=Z^AdCtHl-F*i1L z)Pa%1$E7p8kBL`v@A`%3{iH6;|AF}WP4U8qS(oB5j~!KU$W?68hYJ+#w~?t9C{!DK za3faldT#LFxyrP!bF}X0BXBEr&YB_{F6TfgUjK360EK?p;rkccqDs_O|79L@@t_+U zmI@mpl^bc~o{pQ~4opvjgY=wjj=C_3I|n(Ymj7UiGh_>zAgN8M_PuUJQTmcZXgmNj z1ym(sI#>tbE6kkREi|!i(qBNpfxf2Aq@kZi^Ym3YO(d6HSggOuY1LD5Gh_LH`{WDk z8y@3e-HGUxVkBZ}0M}Jei5PdrQp!Q*<$wP^aNl7#r<^Xs6uhqcjNO*13S9G{4r}v7 zq}1d`AwxSBXDV*`pCA*-E>GRHGYFAYHt;%{956H2lFDmk)eU;!O<Dm zcpY+pB$z(;G}#4v!Rh~m0QuyIT0tdwAvPVI^FoWfG2O>C{bSk@9xPb`&o+gcqJQU} z)c<&c$7qb$avDOH?_>NHcReL!YA!XJO~b(Kc8@uo-6a$qZkaVH_dc7w(%YZ77Q16@ zLR8v)sDtH))MW)MguFXf&|N3Y$n{UmEK8GN$o}$Ny&Fl_;ltF9|D{WdaMGxsQyR(F zt0;-;!`y!{a@Bav;e7mpL`M0XR4BW>D8JCTYi-q47RRw(RV;@D(V2($CpT1{!tR8P zUU!igD-J4+!5XrgSx`mBx#(1zE)5uMzvhKIoZn6WX>29HL6`?=q>Z}IGBIZ!n1@jd zuq(*xDao60NC zEW5jW-}edGSC8T~iK0JR*1?{3th1u=Wu4bOyY?L**2;55#i`$$He&+~kzs|o;+re* zcFFuw69K?@UdVG{hAq)R`|?9SzHpbXUe44>Ox{d2?vUm0M^#bcYL_XZ1btOQc2G*sY|B+t^acOcTcxlg6J9NeoE>exaFgP*dZe8xyPq6r?O3UJf-q zTmUZ}**?gwq9XB)=Yi&MxzAY#=~KlDHKyL2$2G_I@=);hpGB*bJ!0_={3O{AoA48u zB}h}10lK8IZ>Bhy0y%tyV)YMOfDZ+!16Hg(%lR~5a3ZSr00jbALX%TaT`yamyF6~u z$%Z}%GM#=VMu$Fz%XOkiBHj+EUpCAL1$edW%W##N7|d>B2yNS6CGA@HGL0#une=Ow zEK$#Zz7rNh5<{?1JP9RR+4l`z-zf-dqqIi>gSZPK1D5V7_ZIF?Fm*qN%h%<^R!j~8 zZAYkE#XDT^coBO!w8tNb{h;5Ym-Z;_HUGa*baB3QdHE~qrzm|5TTEgc)GQ4Qc3PcYvG@m z{v#2;5#+p0JW{RF);9|QW|)HLBJkK zbc5B+1mVlodx&>Z#=(oxO~bc8lTm}W3zV|?F9_VBPJJuZOcI1Qen3k}M{tJE1%e?q zTh=2Cd4QI$n#x!F@KkHGA=Tj4*RaiQ&|9q@-|B4b%nen};vBf*W3ma@gJwLbogsw` zM1VzZ#UjspAmLT{Kyf^#9jgMk+eB;W^_f#)LCZOuki&3k4EJt9!(un5F1D0Evi5FF z25`_F3G;0)J5)c{NaFtWcO8dl{fxtY80?EW%^_fu;Oz;zL`tLm0ZyQYC>TQ-dDT&2 zmoHG#z_}RP?zZ3TWnRA0$o6;ux5N5=%V(do^UbB4R~X0eZ7`NWBkp9^Nwf4Re0!8F z{Z*%B8e-kTvl&gSe){~w7~7lV0nE(y-?_NGADuSvBq2Bh)2u1U0DEF%wHhkBo$J;U zTppNwX6gsTXU`6My_75=Qe5D3P4)Enon2}eDY^@IeDDqmErN+s(NN<2`s(} zid%>5x65QBPcE9Ug|C8aAg2l8N~;pEy#dMGT{TE30!&s?0Wy+xBNciF$rPN5fA|FO z2h(y`4sSbp-mg2Ijh}$Me!X{K@mCvSoTl4+%Oll|QF-rQL>Gx$k|0RbtfVHxv)75J z`Io0&1efry3!m&BFwU<~O*Um+SKp)a8~{cr5h3OyLJd8Aob^7|mGAc2<5*9=Fvp~4 z@UIT9&0>&`NC}*zIg*=z!&t`%2K_Zd_yEUN&;^n`4b7aOeabv`TPt5r#}=Yzlng1V z&nIFAPI~lCF!vCRxyxN}>2zoLg^YcRfi;6rkbV-!XnUgjtq^s*Y zx^ATMS%I1Pb8*h+{YSKJh5xBfWX=*cS7b&!BH8C9$x%o8vSb?k-}5Spefyfhcr!cY z_rf$PCB-%%mf`O}?#(H)l?S$wgURm}W+d3hcf}{J5yJEaZXF5gw_G2ed3TpH^Vn9rZo0_I;m*VdicG> zi~f+sFGj=y(j|a#GOezBO)+UhJ@w!Q?%T=J-ZE)VjxakO5m9rN*5{*QqFyoQBhn5=GSmSzb_$!sCEew-2X&9yEs{1zM|SqXNBK+=6>x?DCx(w`Z5Ypy47Fv zaw2G~I|{RGsiv%i!)$9JvZ%Wb>5z9OulLnQA*F&I$tl@HYLO)5O3+6EOcbDfz z)F0puVm|EUmW9pX;dDKysCuv_W2pWC_t@ z>0jAhY1A)Neock;`A{rX3{2>6z^F(swM*IOxk<~M=ucbuhq_t!rO zoBXio%bo;S@s2%Z0uNOPi}(D0Je~I=)$bqoD`jMb5aNVHHreZtomn!nj*Lh~_I9%O zO4&N7$lhcg`;bjG9UObaG0)*R@B8%m-uL|voFC5ndR^CRJfDx(*s&ppE3SW?Zj(cj z1d5$T=%8Qn{_?q<-8<6nu z`yPqD&&@`_W&5j~ErjVWc?8i6NKaT8{mlDb+{V|Jors&89>ckWVlgJ_tJ1e!!)sVJ zP)pzKZQ)p#WhHTiAcWJ)W9lTZM8|wIkZ}sTwzoj6AUK=e^?>+uEJO$4O42!_ZW+TA z(1SdKN<7TE>!?Gj+QNnzuS;IbA-_yJNrQ@z!>X#c3nFd3XFwUO3V3MBu&}6j)|K_6=~`AH1#F9T3!5*5FxtV zxxZ#q<8zq870e+N<>Yk#zsf|B_~+9^(SId>r0Dxfq5kHr9nB0sct@|4;PRhnjLe9V zyhR?0GF5PT=aQpx*J}WqkZ}2N^Tmkj(!J)8_1$Kw_WoKS#W59)G@qTt5!M@3sy#~m zt$x<2*N9AcT1E{XR73kIThJnT?fFtw1K+YGRL}&sOs^=1hLD8c^-1BfX!E`#x;{O# zJ_PBA61hx6Kg&yBjSopBZxs{`^DQuQ5hhJ%k+F-J_OF#QlRZgnop9j>gHQaqdxdUo zQudzAiIjj6OO3j{r4^~6a)k_`i4>T_X51jdr+%=&sdHRIOMcW62Gqk0wb5i?br5?o zg>iui<0nkx!Eb&=>xhnP=OlT$-NiMBvFYBV^u|W!9K(W51#@36yy+m19>y|Oe~+fS z*`Rb|wE6zWKZjF?zBX_cX!mYMHot8^;6jb!wF1KL!<@Yy7{_lptwYw9CKAAeO}ER? zuwe6WmOw-Nl{(v#Hhg!|=Ore9Y)2HO8TR^F28-E#Pf^%I+p43jQ&^Vt)i< zdLX1O3Fp!(S#1jbf7)qaDE#gmnxcB1Z4A>MvAZ=w8N7 zIzO47pF0=@-ZmEkcAKAmZqo(cG*#WyH<@rd#x?3kL6M%vxh>Fa3AM_#B_%CYjGoz*ySQz;hr18{)oU6c2MEGg;C^Z<1hP#U z%|#PrQUPc~5UkxmZv$UD+T`YsG;V);0R;oBlj-uyd2R5 zs)XF^CUWoi&A@1%U-z|ycVH-2xsGC+pB0qmWn%w!Axx6)k7G1KM{&!1h0Df3MuRx^ z{DDNruprIDB>h=2rAyJNw|^+(9_pPW4-aR*zYU_o=zug!BU~1WtQ08>P!(3QJ@(;y za3|^DxDBPi*&Wrolj^W9(S;=;?`HFUh?kQj&Xx zyZyOn@FlGI<#n-x$-Ob&U}-~4?Ey_O$uApz1CEsRpVeB|B4Bby)a~$1t*+?z(ZG29 ztL;oiG|5M@V@wlYqUy&Ymww)XM_lcxS?I9+ZFWstcYX)cTSSh|D53|CUE2ljJxfH+ z5A=DP^n~$bD*vW^!c_5o{G&v+sW{LxI}CO#w#98l29#ptg_*!Nf^d0#024%X0ZopY zJ=T*Dxt}7%Lu#Rke8L!g+^ijgDYOszkvf?aw?%B#3j_zxP8>Zfu)Yr_viA1rTY6gj=fqrESf`U$JNI#S@{k@(6JTY(J z5KMHLJ0-%ryUGd}`_9rdF@9b6A~ru4`n2k5MB^*~huHc$XDL-1eYmxqDPIqW=Dq!o3yx ztfXlbI2Ekri2MNBIt?Bmlna!5>^Q}b=o9+{=nGuZbl-}h9(ML5&Y$)WiXF<975a*W zw(pjNp^=clueLG+Gjc#bwbJ^%1{^0*rn1=5)0goY+kMz5IZ-a{gsRKee{m3K$lkRs zRn{kwUB)wioh<;b;iG#TW0la^1RzAw>Ej#=G#ij&Um-cY;Ol3_c`7VbUt(0n5^d`7 zcVwmWY}X54E~*;#w&)J}ao=wWyFR=jy)^}cD$OkcC�X4~kzaf)+i=+x-KMk%uYW zYFm?E`kuSiRfG#wZyd4y@*&z;wI58egR5Ek0#LTMA=6EOk zF&@dsAVOI# zHi)6EFjxO1YDoOzUY@28xE+JpCDm7!{OlA!4~5L>$D`xQg0S0WJ8DH87(j6dV5^!h#gSmxa1+I*%_0Ej;}mFyrq8N1pHwCEd(J7b z0&1SoCD@Nt?%vY1EwVi(@C*p1u4K0yj1TgAB0|}Y(`?i;o=*CtxX^i!l4)>-nUp4m zz74aCgAc~*a^FCFTRe&vzdVdFuXGuwOPAc;xX|%$ z+fCF8)U7`T1+ZZHB!*Tn@MCFEj%5=wTyn{K4v+CUf|>^Ah6~_H+^HGZf%8z%$e&6WCD(pOu=~W)xn5z%y^tW`eyzW z+6;D$9`1QK+)PE>Y*``orzQjw}^4(H(yxZlknY!8DV^ycyTCG)fl{26ky7`NX2bF27FE%Fmj@ z(301fYqIZ!z{Dmgd2YCQVbatSt@RB>@I{F9n7YPjkSQZzjT;`s$lFXQ3}aB0Z%Y`9FrW1MERXRuIfcrv#zRettCmcQvZY9v|hj&hP*Eyo3=2@6f}R z4Dp$T0F0HF4sI6kmF}cW{PNdhAI>lSI7W=^tXogAk)Q^1Nrr`_ShbC-Ve!6i2dy&X@6O>pexG=$}rhU!mBuGsq&@Aqad;;`iAnM1pef zeqG421V{{u%#*PBL*mfA7L+Neo8QBtTKc_Y-J!JSkAAkGtMJp{_Msvp&L5D-lD*i@no3;^rF@OPYvh%&W6y2vX8JbGV8;)O z5wGp;O32&mncdM^747Q-F`bDQtIe6DfxOJsgcuf{zVe|Ql>-K^;#rPI_ zrfaS-u;KezuQ5_V-Vhu)k$!MBS)_~WIx)hTVG*c<@xblDbOr3$wr2X4ae8Y1xwisf ztWX~i^y{S3bqbOCI1UR3xeqoxs-hGyAS0URkH+m^)GgrAI~MwyBFN~UpFAk zgzMI0?}36hQTx=6_4ji4;T0`?B>U3=b*jSR!WD%X>Ut2_E+7+J#E#--+RTD_CRso` z;(JOT9mIn=W)GoSCWW}~g=OzjHcsuu0bBBb@3vDlB+?lrQc%%D@nG(0T*x%`y2@UK z5$5}@D!Us1nO1UNo3Pi;+BKVrV`!v)B9x6Ku_hj*&WpsSMWJqU(gw0aQ;8rLmJSeeyZdf2V@efsIP&o}sC%4A$kCXi^c z%%ul%`lY!Eq2vEd1?Jx}3HdSC2aOq}3zd6pvOe4h_P=OGwzM}_zzMrj)HK%MxP?y0 z50%YuG;%5#T?389Fnagftv^9yD_Y@Kt>;2L!FqaR!Mg_#$)(}cJ}zoP@&SV)QAO~} zq8V*a%jW8t|LGI(w}YJ0S2^BQQ+r;?0Y|PekB}=qCFOHRNvZ2R0`uI<3y%k0@n0Kn z(Z)m1i&`s{#(Xz(({&+0z-ZRrR&@}l@|2|S1}Lt*He8xL_j6-faO~gSpN1VB_`UdbkYYlmcJ0A&k6!}|;%eB|T z({F4%|Ty=WILAKOBVri{Obtj9!E2znqljp18wyT=63qhB@oyT2L zK(~p87D0pQ^EM~A*yX|es#wt3XAm`b>!3#nZ0AI9;mus*2-e_6(RqCG!o8+Orf4?( zf};cE>t`_EH~j1IqC)09+HIt@PZm`k8c6d5qHm7`hY?UwfemJDU5)0vd)=H+& zu7kz+*3ND=F1xp1tgpIT6Re6XlSjmXEw&y;YYWmnQ8v$ze7)jDx^$E})c~pQ6F|JZ zFMaWXAjXoNt&{E?gP^`F2cS2$qrt()CO-R{# zkc{9nx%|bgRgFOHg;uH{+@>%PNcV>nCHyajj6{W9NWXkeVGd5Dcu73V`F`EVBK-`b zD{)5H+t@Xdc3qIQ-W^30kwk$&+(~w32<*Ns0IrH*Eug5Cqy@{cF+c+hl?(TXgV=W9?%1cbdX?4`I;zfdi! zQdT&+Hf+j*9`&}r^23>Z*)=CSZoyzwG@Cj;XB<;6>Bc-*xQ2#`6RJr{7ye2WS`(AcOPLc(gTq{k}~0|NIC9yzLe9M zT}TBy6KF)9ZEXtyE%v&A!zuX^tSIRWU!(_Ab-*#4F+G%O$HoH z3rX;u1)-0F5+H}!qf-VIwSwrt84nko(0keFQH(gAoLo1S#}axQR7uWri;zq)e1xY0 z$JKalg*(ny=Qj!1ihE0^GajUpEywW1cbC+~QXf6DNf~;NUHaso>_P|O1=}dsPU#r7 zieZe-r$fydSTCL$mDwMu2Oj}rUWrzoBxXV1&K!?c6otj@R>tqg!^0a_CEJ}k`pBGI z=-2oeZd9ME345l`KvQNg#QKEw_2s7B8j9I^W(h^@_!hZOn;9ok5T+)0m^>&$nlQ4r1vr@>Ne!t@{T>nWkvV_saWC6Frb^G=fK)+d+Kcj-mNK8xCF=Dasd_Io@N`L#^&GR+S;X?h~T`R|hMLo<#|lqk5Sq?C{< z;!}^eY{R3YH%0LcUOgClTp!}|MtEPRAX^9G-Qb<*E|Evh;$=>umxCDg{OJ3l-#DC1 z2>+o4ZW#B~6eGdz@o^X}`F#VfU5S8F)pi##DgAI$!O1I()s9ox=;6DUuntQJ7)=@p zdO%YCxO)z+4Z+hJci4ZdfSVN-}bVr6of}L#SZzO%hg7ACUCnC02H6Egk zBk+xpg6GplyRd!{{LLaNYX#t0`;!-F*`ei8Om0s0s+nb%g5;p(GH^)lnx&xbfeOPa z%l^Q{Z1k1}Z$@sb8vl`QTh;W@9-UJ6tR9{8hn`dq7DC1l`2gH}g*!OO@53=kBPcy#@ZF zmcX`7W@%y83-dY#+s3%Yz|Db6jEye)us<{Schv~I39o?6#oA|75sI0FN__in(w%b) z=mJKTp{cPMPYi-nFU!)!jGlHqd(_-y0)1e!%U=eNY=W`TCS-G)zuR%3W_k%!EU^UQ17$z9N7S~@(C4)Qe-F&^SuXRHBiaxpybo=ov;;_#!-Tv zgvLoz{_*Q+8>QU%Z^PjZhWPTZvrfz=T9UMe_!=k5^}~Bn(jNc7-552^))#S}!)TJW z_f+dhL5^K@~1Xzed}gv4R`uW?ynz%sBm zcd`)$>wj>bZi>&Y|Qa0n~pm|5MM8Il?G7aSpDW`ZDpZbvz;BA#01CGVfm!-)yOGc z!?kkc96-wy6XFCGu$?eTUimu->WQAgfY-;*Gk~eA)GHk&ml5E{h`J@>6Z|BeS`T~} znoW&>hd_CPFLxJ>EejM}@araKFw$=UV(lA}HN_k3G0N(+$iMFef4t9w)n#5Yh-iw| z!O$uMUhR)m-f5)LIiVcKNq;!Nx|TB`gB28a!TQd4@*jvs)L8V&+G$a_&~`A-#EN5S zhV)z7(p+#=ZchK5r3bbaC@2r$T_p?1D-BxyuGiw@e;WIfcEl|^>n3KRT)Mtb{S%`} z+N%V(3Hu$dZpo`L4CjYY-U!#6)IN9|l7LK^-I)fbGLi4Gd{2lWE96q}<^@XLUCk)~ ze0b5U2KE2+yq)$Rz%23q&H2(qJ5DnbG%XIj?9RL_jL$J!@69n}k0lQXpu)Ns?qr)iJhvJ-xN%ph*6varopt}6Rt&X9-iMv zbzO}k#0tFAMV6>2A+5mhhr2|-cJ%9C2t~lI*yq@N4l1lV=U) zQ=s|f`YD$`{vixk^u6P2Ej@U4>p6EJ{oAlkVtqMrBG9Ybt&ZwGXV>w(Kyt%j=P6%F z8w!F6 zWkq?G{!{y!`j3Q*Rz246t5L;&HQ0F1i0hzN*Wn5F_I;21Wd|`3|0&kVgZ5Q{;MMX; znG!75#q(%Lz}!M%rN8MS#o{phJs}8eCGjlS^NZRh9tY)%ybR(#@iIeI2%Arr8`jm-SIb0^@?_~TzT z1>kS?mvfWe?>RWXRT;Y#oZr$QQsHWj`(1ngj7jBN|D!Bo{2SH-)o#CJZ|wc)J`-wDhBS&(0E z<$`$+r0{I;ft8O*0df= z0A$n)oMNeZg??9#;Lk6px`a0RbR!VP;l~vGKS#V@pWWTv1i!J2Reon>tCG? z2B63G%B)%&ji)N%lmta`=%GGGHBQjZV&*HUq4q1 zGC#jWo~>;I&D$lth>?Jn^nOzK3tali^MGKL9?9(&R^0d-boe3&nhczPd2-O?et|q) zN(&?q7BSvQO4$e9xU8Ze&x^#(K&#cq-Tk2J(F3~~I3G;ZYGY>*R+7Q5^b~VPA(#td zsO3GRo#2%sF#-f%aY^*WDRwp%_xPwsF>7DE`e3=NUZCxShOL~!*Sl@H*i)4kd1cWD ztUv+|mX1ybi}#=PC(hTV0lGci=9@sbHI5*>&%PbticeL2!;3%u2rcse!VrMoM5p)t z@6_`UF}AJvK}MeaPa4HE&=Ci@1Y`R^*+59~dubla zg?r96naxLU`zjlgXSmN}Ju#=Yga+d_vCIYz3oOidQ&a_SkyOYi;sgdO&a7*OdbL}h9(^@Z^&q-uL z)1X`r=c_og@S01-GC-U|{4ts0x>5(+04{|)8zMQ50Im4#ter+=97(fEe{{;#)aTn$!E1d@2%?B)*f>6aa>Sj66ztIpc z-a4$0?hG=bdR;pI`0EOJ+$7gX=FZJdjLns?=+T8w)-jyrUClPmyDkmNg?xOL_1V2x zxDSxqhkFU&8-Y2brxD`61lZ}n1egUS*7`32_C>z~+W)ll_>lGm#r+&d$vf?978_y~ zeD;D1sCy5x{lb$Aeu++nRC=>A%D%}w+K&lTPs(LO2K*Fz=b=!w`zzb8{<<=}8)io| zcQri}$=6zv?RTVF*I`TvW{b-iZmN$+;@5thU*u4$q^=soQj~Bls3ZuJ0?k&6ux=@F zt6GiHb;G~N8&HyrR^3om=fge3w$$vKu5Jbuyh>-lkUg#K{U~N^ZK9p~%%NAu8r@iY z(NNIhf!FJTCilVjkJc?C8*`y(R@!PitHjCIT(uPX#yDxbri=pNEmXYE45UGC8ZuzP zukrh=02K&1dWk*PPXap5>3-PYHjn>sC+R(4?ZcfjZ;0bx2jVwH_wy^)FGGLgy^pCk z`!1kg&Y?~CBsBc}G}xI6L8(-!Lg;$EeK^tNkeu>!%>q<7>$W>xh1@Z~c)kxKzI%L7>IC2aJH3!bGY8|V|-cEQJq zZGymbpz*rudw^A=)GzBhv_SAWbU9V4M)(M%dGA=yKxwmJblwf$>$g(>)-os*^Pn8O zzxcA7+mVKCXx9}ayZ`qBVLMR2ke=^-C6F71y@1X9@o2&O%z%pC*#OtuHjsWGphxI3 z)~*^~e`TCtH^n3Ou@d+k^*rg{_-c#kp5#rT6B=fG0!5i<2Lr0$Cy|83P=ca2oTEWL z8RLw!w#aDyTx7g8F{MLR8dE_m@snwlTc>U=-!;JNn0WZ7a>}0`s(y$;sO|L{tpd7V zkIkk(a+k>FQ-X9`v1&ZIvKfu&D;~qZB{o{@2vdSi% zXvkZ5NtD zAx;_uI(+8ER6Nc`&^QnlbWEV(xN*qe-A&T7f`vQEXUsr^kLL-{-xp@ksR<8qyK?iF-kSsJcHt^nS2hS}gsX8QM!v&nh>g!{_=l8-ZLi^7EX%1g5br6DQ;Jd^r&Se8kNtjelM!?BsEl@CpbHg{hegI&(h6Lg%)Mo z=aBwTWfxf05#btm<=gW};Rdh&g~+q%;!PGv#CV78fUor(aAgqYp3a<3V7CpC66odY z^fNWwTfU=&`~JLUn6d77=2A@W;TXH}HbLg{UDvYe^?g?Vz-Wn&XtPK(;+_~q=}*g* z!4Wy4hhv8{eS&?_kf5xFTuSr??p&_^do2OEvHdebsK)Kb{x@cMw!LD6}LexTM%f+>qI?Rb2Au6NsM`uX!0KFn5 z#Bwa;hyL>zJ@{sRei(d%2)ah_xk_z&D#RZPy-0c2r`&+|-QU^Z!k_FO_ygn9kjJJY z*LyCqtLsij8$6S-xx3W6`OclYGmt>dg@OYJ;D&qMjt4CQDUE+GCf94$VXdi!_iMv; zh1{Lhys=1Ge01ee5?R8l?xFzxc5QK7IXWt#S_0UrJY-dlI`HGJwpl$ucXpC+yh6ZQ zkAtpeTw4Gbxh-G6)Pcsg$q(d9wa397JLm(gij4X zB>{e+NW1Z04R#{8Y#?|N{9hbrJ||#F_kFUVefqZ_xefU>c0E zME#%{Rw_Lm4Vru6N9Z*;$pQk1izEt+=yU~KUuEW;MW_P?QP=% zv7)?6sHN<6a41}ud;--R7rj^z0qA4(tEXLeQb z+Ya4T2sv+l^Wa-Lp3!>BI@(B$1E2RG>8^DBodVth8o2M;fM_(jCRZM9qXGyN+C}zW&O6C#8=9Msa|WutbcXhA!c$lX+Q}@J$)w| z?1{dAUwG@L0Ov?XiSf~AAOW4E`9YJ33m^-5JEWrMc*j?Sy;~pX!D%I8xXK?E3wBH6 z#~y#7vr6XNKD-giDDwsCD0q}4;Jb@6Bh%tpP+NnbWdY5|wnTW{H0IW#cBqoN&|&wu zJhm~~HfaFJN9$=A3IP8LbT_>G%iYnKT{vT@NzB3dsqs5!GoWeCV7GEwSqRZ|`_iis=N~NeO-t-|RRY%w5#z zDX5t=Pn8k-~^_ZItK(%Z2ep#KX?sqRoaRde{%2+zL2`|ACUu@TxCwR{S#g z->^^OzbH>|W427B7-H&AsHhxS>>qozC$GNnpqeH{>hrnU;&Sr+%X{MwUWo}FJUUuS zQ&m0Iq5duKji_O3m;Papd1@kA!CEAD##Yg{>nUGhy~8^OBrd;apN>S8?RpcRScm0P z2~}YQ85~Qej8t-21076?X>(^ck~zmw`Zp@Vl7a$1Crj9q6RuSe2~^|0m>E`hnisD^ zp?O0_A~qyDwmRo`KGBvqq~fQjU*0qfJ7@N-UG$K!Wb&b#231BHVP$vX%OD4DUuD)2gR zk3r$~nOj6R;?a8U}20@`&xM@;s$| z5KvnMe_-2f=g?U{s>}F;Gma9G|Gsntvwemd?Oj9{>pq9^T8+Vz5upEzcYX5TrybI# zB-mopn5;bLT=DfQV|{&q%1JrcQC?UnGu2WMPR zsnudo>CbY8hLm*ktugh2G{!BH2Kx#Dt1BkhZ~{6=|I+g2$qk4As4VryMyEbV1gKT) zj}*Ttaj06ygPEPw@|}G@BSSj-es93Rj09`-${T{i->_d34PKu|8HQP#F@fVh)VytM zqY3{R3$Mz4y1m+#u%RY$oJ0on-^Q>;t3JU;>N&lo#@)yG?u43zCXn~Wp%FT(+Sf~- zeVb=YA%ASMq~`FT+lMbRBcrMo{smff19`*I=AP+J1v)iRS1xFF6Yg}1MnUG(NJxmn z($I^favJNUh@Wrc4iYYm@Z*{-FCC*a2W|_E6EOrL?rnnJ4`RlnBEd(CXigPabGN#h zO5&SUB2fW=HJH>3O&zEgq0PGal^p9~>UHmbIdgTL{I^}bFP~mgV^4i7xdm4d-%OzF z&J{ozdv%Tm$2@iVDUzMe*XN4egxb&&_-W(^L{wS6UUM!%8j6f9f%pV z)6KWiq4(j3O$}^aKKv#lXrJX$Oyl9`2_`k?f6mVr#6O??FWo8>y|a+!eS8BMWTV8m zGVAkmbtAdaY(AoSy70TRUu))TgO5hDfxp$nzloGghkSI6znan8-C&hpP;;G5geONL zy(dIv_z$0FddId@ijI46s67l~?8{MLSm*@5t`GgWZ-iTKp$VHqNvblx-Ta2h zO}$fzi^`m!hB+1XT3|v@mQ6bQ-g*xPKZ-uKAvI*3O!E~0lC{;;g^rR0LGL`kw@jVx z?ULhqTt(lO{@pTtxbJKE_Wr3zku)F`&cy2Zbz<5PFHJ4{cnL%D+E0!QiA@(65IBat zx$naWA9!*`rEugu9kmngY-2}NZIe>>ov_oe_#kkhZ3uqi@4G6*yaMcn=QIi~L%WeH z^a?6aOaswx65*kox(Haliv_fw<%q?vI#c7L?ZXIxO^CS8rmM>V2pYo?P}%2Vq1)BS z(fv3l2s8WXsuxp)^uB9|NXKAws{#8U9Ooyuf9aAG%YTvDCq*fwPTWlK-b^q1mUF?Z z*~A;*j+mn>bg1^DM2nn!k7c(ypQ@0zo{T>iDc>K6pK@sHv&PYS`I}Xpk94`d;9n@K z?Oc)!Z&5X*N+`1i;(4>5?gv=q#bne}bQE;oyXnc{^f1MiZkt#*bLB3;(NX!HzL z4;z|K?)n5M2-u?qEwX`F1jlUf>L8p8jy2AK-lw!XCK5KCMH#?AL90`<&sizmh3WaT240ECGQLc6WeAA}As4)g%pU*t z)Wcb8y|`tu_a)>Md_Pf&SFA;EEEX19<8?(d$Ln>KZ{tVhX>|zSNU4AqrjLt0U}AXz z<2bXvQo@-Z&R{n$T%%~=!c$(g7e5KMi)hpX+@JA>E3QSc62vFX?-8)%|0n(U@%hBb zPrj9viGas{;NtEFDK>w9eM8~_3(48-yS{!}>MCfJ{s5l#m?x0B-eY3UJzoRsu=}?B z`%FE~4g*hK?7R)zxY91?y+t5-9vUd%ZfDiAD2UCekBx+WezphoU;M4a;D*q!5UqyL zvJ%Z&pg7|~pCuhAh?PB37~bo0x%W3*hUFy!>BM1tBPNNG{)qL@x7U}XDxn!U`)|5q z?+er9eP;__J~>KLHVW-=^|J#7ZVtr0CHK7fk{_YeH}5;9(=KwGr$>5(uztO>>a#N{ zN;eKB=pO&Mr0UDjch}5M3sJ7MF|JHb8VJw%oqG_m{t;+h5J8%8*E2!LVnM^SexKhv zOm`h!#GCnGq~SKi!~;L5I6FTAcPccgwGas{nmFwIBLgs?xfM)jLlEk}-WGBh2jNyT zjjAaFxxRg*DSo>N^uyi1cID*z{@v0)hWKTVLdOv}mQCc91vHS?Qey@(Jt=pcVFoS* zVsqOC$6ecmGv3SvE;heZa+Y0Riv#+--Vw82+&usan7Z=m{0nx8Ggb9!@dZvq*HjvGE4XyRP9sylXudzEh$+JsTYz&gR+9siRI8=t0Wt&O1vT z_OUZE_LO4J<--_%oBIRTzhX8LC1LIAh%YVF?Vs&3>@=R)skgC#Z=uwpauxNy=LocQ z2{E194JgtwEb&qzc|5ENB*))?n4BJ3dcQtENH(I1s#bI0-9o7I4?MvNF9sbxX&GI= zyZ3P7)aQEF%X~c=aF(V9+G=OZ&{FQupxy9Jzp?etk9u|@e||5Atvzd4XXN9JfM8uw zt`WZtvvEXLW<9ZA|IQLu6Stdndhmazld$F}EGc2dZGalab?&3mEmzG{NCxX}3wTL= z3OnPi9VeJXFvypfq+1bzC0yz(1f{n9IMx=>js!WpnG+be~w&(f*O|s zePlF3R%mh3NBDrSH&4qLEyFVIiAY=PSbzC_;geqmmc`F$Vy~c7n&y* z*}LxM0H|*hl!~|nuX75@y{eu~&g<8D!(W)ONq2I8>@MebL9W0d91#*FG|UEH2MhoD z79g)cVJSSpdOp?r<&+bo!}rq zcY}7)e@zZT-&boY6YVV}Lr^~E1$DOaEej1hM{&5n|Jaw!gt=2sm$$mi5)vK#Mw2y- z@vylwJpMY2NHc6vb z*z>=>`7xYzisPlg)X5YyNNB$%Y?c`Yuj@XrOYS}|SSXCXHR&kMPZW~AVX>kN>7iEQ zD&5-R@k@22`dlo`c$AHy)hO#Iqz*Rm?p3#tnpU2fc7oT-y7MY- z9~zLD&WYf)g(B?m#+a>!yhSppPa?Mln#fyfe_SO0NG^WiSJ8fVNRTPKyoi~(a*ii= z`D;>+UD>tobUMg{4>@^Bq!8sa6!@{XiBi*;eI@bGK#% zpS<~blXH*5Gkv$JP;d|K#xu5HZdYk_iSPsO0!8Eem`^mjBQ%%25Lc9OIp zsCx;mmPP&BEl=8CJ{ie-4Ajq+VC-aah(HU!Z+$^?a$W@C#pP|o?dA@9owR-snqMPt za1zfQ=ai0a2DZ>=gjD+8OZ~<&h=So$fs-dZ6V7OEIf|nV9CtfqY{*X=HMNG0`55lg z;<9UR@?P1~fx2J(SS90gp8R0|s&=vt8iD)EV(q7&g?!qA&`eF84L|PC z|L8}1ew#JP9Uj4qY3l`U51}Xf8tT1l3FT=$lTq?DH{}nX6?cS=L4k>J7?R*O3E?T( zL$Hz*AmgQ*Zah|U1k6AU6O{SkyTAF(uWA~k`)p;}+E^jlcLf4<%bBnM*fVoV&t92B zTOC~D!71+J9`Q@3)DssMrG9rW!9BTmb_aOL2F3kQ7rXBONBq=JqpgH{y@CCnd*y%Wv;7HHkWq8 z|J~W5%Vt4M=xBMW>>CnP&jZL;D0^~*!0QOLF4?#rSH#9F+4I5+4U*~_n)fKK`yPCy z)SbP?X~Gp+KYNXy#Ntzmj=D$K-TA8UYg&+v)*f{Z$W8meDI9Y-eO^ADXm$0A1-W8o z>P#nz7npGgbAlSXH!z+wf0q72jV#+R*7>mR{@K(mPCuiNH%gds(ca)v!Z1W8qyIA5 z*?NV%e6Zr(&666|qe=-h3*{d*+;)s))U+zUZP@qk!E|7hD?~p*_iwVBg@iW>K{qfk z6CLW!Xy2V4jJ*XCxllAQpiJUwzSAqNM{=aNX?|F4Ps&~aXKBEU4cdFtF4EWPf zm7j*N#w=_c3_94nt>`7|lGm?TC5}f;3TP$f1N#^}mzt2n&@AnHC~-z7elPY3V>i6V z$SaA35%?|s=|e3qLWTTf;1oE#*xdfwodHeZfAO33~BValCPYB;F6DDisS3p_bh-F8e!hw<5VozI)z8_Q7`@vTVEOu z<@<(RDJmq{iK#@3m@JWPMj! z&ph)^zyJGwdq2)`_%M!p?(06U^E$8dJZ0(7FZcGl{CgYjdd*YQrv6QlSXG^g^c}*3 z;E*)B%<%X{zT%(s$Ehh4^(XgsC}u#x>5?@wAldT$ZEqu8tKZV%jgjbD{@>lAsKSv!Ax;nds2sOzN=BXIa^S>@y8#?>o zJMGwMY5qy{l>hr{{JQ&z&*w`HALB{#-N@zC;jULeEg${%0(>IdilyAg*H>Wc-eN76 z<{vxM0bNO+!MOWq$>7uA%#aoPC(5vd(RUu`mO*8u8|ekO%QAf(RsH+n_qdcZ50CS& zTV!fnZ6Ji==1?V1x>8Kr1(7Lg2R3MoBu8Rn&SN_+-1XBL6Qr+Cf9hmP^mDuaL9R;9 zz*FCkMd3OxsOj*&kCjB5hTIahmB0){;+(IMs1nM@N*zs;m~LhySw3x8fW@^g6!Xya zsqh2KJqI*Col;gwk_~OcDTN-6|G|kn&ST%&B>dN40!DARWZJa^QL$=iz%2UT$b!LS zYBMHFbqt>w1B3H4M!WR}?lb@1UwirWT6fYGf9y|(V)~Ek&gsMQXIgJx-;;kqj z-C}k7G5WcpbpHQ&0R&G+z2? zyS(K&QjZx>*2nZeb8*@C0UqikHugdH7dHNE&CHh|&$9{U`lGEE#5BT_QNCQvV$DAT z6XAp8ZO-KE@tfzH=P$TrpA-4}qiLck^FT|j;a=<;ks2s3BSXH8`rE{;P9UBEpePBh0V~9)w0?_^9yQMXNIfSMr}yP8}Cf zigfFbO(`DiRK$?)^9AzYe)Sxy+l0}IpKr~>XONso1Ml~*XJN@tdkV-3imznrXBj^o zB-iJwGjQd6vYVIEwy4;!IPz(xGTtq+5jz?uN&lv>CP4VY14UjC8~LFqd=`j#o9)wq zyv^G$?Z~NMLGXa@Uih|UlD+=lKG?g@@bm~7y2U~H|39D#UxxAwHc5vV5F_-7` zkl@BZ(I9f(83$!0ZdKvldFW2h?U=tX-{1^!HN=NRLt&J~Exft+bFDeM>13aGgRqoK zDQwRt^W!+`KwM%R*B`R_%#v<+o)66f;6YOLdQWMW{e-L{_+%o;9OErJMfkm0_PY6a z4?~LVt0TEbib)z^q)~ce4!2Hka z#89TEP8J~{#lg7yA|nE!_r1?nw+`(feq^R8a5^(n?&nDDj9weCXfSbZG(d0P3D=E> zzMcl&?BHLCoh1~BTaKRf41D|Z{!&kX25!1rX40Kot%(mg=ThWcV%fw@NX9?LOgiWP z7EEo>J9t-~5fiL4l-&N=D}}b=(93=Q{`uVjEUqd~Z%E;m{yVYTqX;F;s&%}&oK2w5 zs27(Lzq~a0*KZ2f5as-b&D<;t<1g4Wi_@OpA3molsD5$jep9yj=rd-vIs(QdALbI7 zakojMD!^_0eZV4uxdX@DnWNamI$KiF8X{FRa#V;lvP|-?6heb6piX-^60!m2=uHP1 zG-#pdE}}%7k&s*XQ`^M#@pq|q4&h<$`&>bt9Iex)+PbruNW5O>FNIo>>GE%<7Q+c7 zNg=y%do=4;+DG7o=!O9ovem%3ViU)LvZ|#jaI(rPlVmv~kpg6u&ri32Spt`BCsH?@ zQ6FBdaM+8oqSAl`+P+hVNT0Ee*F?dK2J1h5r=?cS=wb>*3*T|amxDi5@oS99g?h*8 zpZ}hBt`|PeYDp{cs)lSQn|4y@y9uu#V0ZH3tvECL#@9PvtQW;cm$Pg9cSlz)nk=0H zDpzHh7Pqflkjbx+$%37OJB@{ z_6Lu#%vF`OWZAiU{StTNlgZQB54@GfZLQB;eK#K=aYa^2C3IG#U_wt`XjL}0(bt1 zYhal5s4GiZko5D?XVH)P3Zp4P$hUFvtD&g+u=MOS`0A~|?`DypsEx@jK?NC0?uk30 zPZ49h=0Z}UQE-T|?$K`Z#R1aQ}i+bj#Nz6X0H;MdA)*>*5Y1 z)3ojnA5a(!-H$he7ArRzWh@KaujowzzF`e+CKmb5<86!K#qZLL3B;GL=~v?<2bBQu z1WYH+^CmrXB4l_PT-xHJ&b;(%-H*Rf>bb~Vv8A|)eTbw#dm5BnL}|WQ9=F)a&4oCC zo!dIVo@D3DH|_aS9AmH4vXL9?BCo({?H@o_zm~{_Xte{~Xpo|NNQtWilLXU7Y{2As zLetpX-0z0p{!T~kVY#{9kZw;K>0UmUH~fe^<-5!gd&B)rz;`J=J3+$$-oUnRf87Hz z*M7}cQ`6Ox8jBQbS*)|=RxE{{mrGep1xh1+Md}b2YNw9hGQ$3840Z8_lW12$3>>7+ z*51yel&}c*)mOa;OsmGRMjnFXE8Y>A&PuH0NV?qfoWBcR#aMrA%c8Ign^Lc6ALoB( z$mi8oUw0a4&w%m0uy4>a+i#Lh%b)K$5jb@e)d#Ueq+9=a9i{C7!_A{F)px$?@r&A^ zh^et*peakEKPoJjKKc>gOXIN*mt@d9gv_yhnEYsnDB?79<>=99%GUnSR)WSL@*L0G z+@xWt6}>?8fH7BFUr2%}B)WN%9w*%zvC_S9tJ*6WpxTI3-0+43NK>l2rP`Puvpc}cJfu+H~%%=tlx|K8(7g02%0S$F7xVcNMaEw(x{nRLO zC~+W)HSW2{b?VLv{J0Ew2uE{7pY`>IE*pnTgT__S*S|Tw%L50u&tr<%mt3etTUeI) z?M^E0*Mi~))}bBvA{~E~t8xao7#7ZT*Ga%RdBs2vA_0yyn%9QYI>& z4Q|{j5Aj>(W_9e*ygZv(dptl&7;w-ANtb_vhtH^ZTT z%zdbSgT=SH2%YgNlrG(GM5+)>=uF`|MLo_ZTgcdJcx}2OpVdvwQ7f-!Sr;FD8~=3) zyWCMstn@!&%hbYl|C*Ojpv<%^jT`g2Wgjjytnk@Q#4qTZ-Gf{@Cs9XR$+I1&dHp@G zpfTKc?(h*I<-hr6E>s0CEMZ-)UK4b`)xIyQyL+yzbp1_jtCoA~254#XcLE6@Z;Y5y zE{B{m$SC@gQcPEo-WCUeH=b~u zZ76)cn9KY~QtT?9Nebx-=9&`%HgoRLrWN@4j6mzN<-D%ALG^Rn+=F1!kNz0-5hkI4 zhnaSM;Q(@Zbu=bYue=r`=~%V?U5_TK6j_6nZh7oC3c{-M9st=)!;6fuFE z4*!xj@k$=Oa(jH+j3KC|knh#r>9g0UPKXh8Lz(JN37};{evQaFDZLry!k0jGzZt|; z-_Ap)EM4Dxg5Xy^wMx7cAA3INipE* zp$AXlO7NPR=0RlKN>4{-gvtkZOYD$AA%oU_+0M1#9itzz2=VL?uW%R-P~2`Us#g|_ z^eo;)tpvR2XN}No;cHj?4md~}-hWy<)5A`aEsODynGmLM$udNCuF+r?(y{YRA@= zm}DMB*Ku2c2fsi8cYs+KTm5<$%D?8R+B?tIX_{7koYi_OJQx=tE4NVcp1U&eA`aPOIB??nj}#>+_w^$sq#hc=; zq?fL`g`Sy`qCa)dR;GjpOI?dHGwwL8y1QJRT?~KnLfSb16$Ce(J!S^Mo1!>Aj(!AY z9k!>C;kfa#?;my*ZuS0zUUtLK((ix%ObsS9Zr6gc2}jna_WI-Ko7FYHT+y69-Gmj` z%rs5Cgl0y$sEvXR(+#1gw@gh}x~tEzuh8-n0&T#o13gJ48K4rvtWfXM8mSTLj@t>8 zov6eTdR&ph7!Zn;$NzqRJ@l(768N@7b*uYGOwZ;)elhC8St9eS!#{ON@J9hE0R1kg zMJAqE*cV0wkdRhhXL;Yw?7DQ*OQy#928!6ev!VCcidX)Jza9vDR(tef>aSYm`{M?z zC#?DrNwxfvcNU)nWqgqce)Pd<@&4sqs|bz5RZ46!vRcL-clXGtIR8`Z>3!_ttO z$t73l*B$Kg@+s$qhv*mWNTQghV#-uNkyK{bnG}mz!M?G@~(~RojxH}kteib=`k@nU#h{LkovlfS<5k97qh8I8IB2B~*V%^yC0(GI$nRqD9nfMrp7aQMT|b+lO}dYi7hO z6L5iizc?NDK^#=Me!#DnHpS83SV?H2Hizp*t`&v@(+BN4)JJQ#fo1vtT-~MjjMBl_} z*gztFtmE2#)0TqI1?2bDwP!Ce^aGI7uBpxtc$2k*Ob2EQk9Z{NC>5_;QZC>%Q=0G0 zn}{UukD?xfQEt9RMU#7Ns@8^i?E211<4XVwHriHcoM?dihC3+hL`^)E`7sj_FwPO{Nbk${ou1=EO>`vsfU#DQ;DIf(hkyNlGd zt4hogoje0ztZm^y82m&sBQ02dS8gj<4Uesw-@jM9Sh}W(AU7G5M*4vZM&d1UIm5Z% zzOdBJEn)xchh~Jb@5^VN$H^QmmLi&>yntuzNBv1zP62DoLLAON)-GT}T~FyHVNS`` zA3H@UfDZ&(2qrz2v-G^T?>xGPfnD* zpn$o1Vh70f9}Uys%Ej;nTBS{lY8~(_7?(=#Ikl!di;_}w4NlnCJKAN|I5B|Y)jpJZ z(k=y8NN*fHYSr{KajqaxB!N+>c7tGH^9`M?K|$A_*xat95TNU zeR7HmvY#P*LQKilIeLLJKnoQ&pkj1N>OUC$vh$GE(EmWx`@<&%o(T3|1G#&?v6_8# z=wfk2`>tmk{nY<5@e2R4deRzQM_f<|D(=b@dwfU3QHV44=SyrDs)-#I*c&c8w3+dltRvR|%J)g+dWKFd0jHp>I%I#S$renEJB0cg7ybIW`So;CONFZc zb4utZ8LLOm&unJ_lH|4hfqnHXvcT`X){R%3)h%$?wJ~ZD1x~irzDlGjuS=k-r8ntE zFfB1)$Fw>06}6TEyv=%ooMC~9w(LIygOM`{Q4ji-sK|yrWEXEe?9Xqyai)mFi1Pu5 z)5VR4hJ7XgyA`1ROAOy7Ki}pchSg7Z@zPSl62MOQ5`fp7}hh z4Wf^18I?@V7>Ts8{GkZgMRUA?>e>%3C75R@y-B4b=qEgs=w~dBWFvYKw$g(lEXb9T zMSOahO~U1IdsKJ@S<)i_nU0f&nHK7aqnk9&8G2W)*lFavtKCDDbx=GE{*dv`A$+D@ zV6>3uQLf1d%HYY5@z$~mRC@3RYACIt;6D^4BEYaxQcW?pC}cd;mzktgC{to1ZPWR; zd%YkmR`B7CS6#Z+LubqdNBlojT4_FxFuA+AB%13HyL1rvu@#Gyd<;{%Kv3fBIV%@h zL>z0|K73L>Q_|GscM$Vq@Om_v&-Kffsl)Y-J?m=uRW}|59zq@Cj>-)}3gdcl=$C;*A$@ zk){_t-#M;!G4K^XU7k*cW8&$rywmCDW1MAO{-Zen*g-Gu*3=IGcu zJ^Z|-GaPiG&Fvj}ZmvSVoW~HEsGMC+_e(oov6I2{HB??U9r<#>jc8p-&H}d<;9bLp z1IXq;pl6@vhUVfRD}M~fy@(Z(@A$Z&?te>To|0kU+UbneyM72o$*MB}%6c=ZnEyST z1Qn(greAK5|Hs!7OgU_n&pFp;iU;ScLIX`git`x@$PZ*jBSoDA3{1LOr-e_sBOVHU zcpH=CqVoPEtTxzO!=o*SyD3b=1ncgYJ%hLlM{ z`9pYax(n31B+=vrYHQog(xspZuK>Cy^kMWdgbbr^?k5mvpqv@SV%&u7Ct%T&{u+{? zkBFx<8W9-L$I#C`?3B#`gCB5>y4UbK0R+fE1B|XdL^lZqv>1X zllV*9^}XuhI?@`&_tw`!=RTbdV|NvI{ucvsV{|H?I3rKejY&JMg=P)G@@iL0fBqGy zw1D(63q9P|^66y9EKHbx@G2J%(t8-PyT&B=ruEm}L<*$?-3TvNtq%=%Qvp^}NhN_P zg#krmhaK<|h4P|7tFn_nduxNzRNByxP~1x8NpBpRc0-WfYn3?Rrf61Zoyi%#loAG5 zL8&fWJ70iV9X1E8!DqBTWZ)>wzk>oCfuT@Qz;qEciSfrdMdVP}Q>mf!8yOOh?!2iymtszf(#>C-2VZ*zV7V!dITRO5 zqG+F`tWT+H3tk5#RXsF#c-FKk(N^5BY3V|?|3y{e<5*H^Un`#9uSVl! z{q+ZwZ#OV2b|S1jX1VyYt>-)f^z0wmn87~5&5E^S=KE8tGKsGY*$7j~RqXe|y7Ce-7D}GRz%BaR)oNP26BQp}quR z@!uKS(1929Ty|0!J&ZKB0MB8y*S--Qg6Q-)pz}6WLorgT;TvOXNa5tyRxe_9oL7zq zjGy;m7}8{9F;&RNaUy@_Z?V)kgYHqr2W}&$c7uv6uRnamDq+1z(C7k4JGSUJwyl#e zrA%{ri^)U*xAI)P?)y`>PjO8?0i#f9jC{^a=nw%hV|KWca_Z~ZO57{pJ3V`gWA{Jw z;ue2+a{qr6&{Za-_f*03*d^~SdrqEXAr(o=57ygi$9pq2j&T1t)@XgFWO^nj&p)qa z|HV|!BYw@)7M6NDWptI}pnXJ`r1~;1+U|HmehJyh6(r#aM>R(8e0EYHY0A}qnja~9 z9t_W`uA%14iR*WK{1x+pg;1}5O6HEfC{I+j7mSj`f1ftKIv<3+YInTR`h@olpjl~V zV-v1g&s-n5Mq)Q}J@Vd{UY9A0QPhQ0`zI*hcwItZ@%ErYLiyV_+_;POJOblHE}J<5 zh5Ng<+R)GyXvDbr(XbErYitHZk)WF}O$_dvZln*r-R0Z>oanw-nh}S~OK5;~&4u1e z6%8O@puBy>RQlQmjsl7e1m%ty0zTstE1*^=NP-5Gs|J8RDwe%Z!+b{|!Jj4GD!SNMvd4{>Bm5Vkz$qAz7YBVW>3h2Jly}s(MSnQ zm6`ol8w+IAJU-vn6fS?u`cZ$cafP=!PJ24wZ4#iH5#hksq8aj3928*Vn$Olh`}|q2 z018bsJ?PG@tzMZ$2Vyw|81@!NY2hj~(PGEvonXPB7 zMwzTXuAhS4AdS_tIaB%aiEj0C)xtCQ!y|eS>*WU{m7GYKih#&MqZzI94@|vSJ0-rb zO-@Io6@5!3Nr%0ps3#K>tcsBAd+cvFIZD!0?{3HRck0%g7T%7|P3k0@F1#c%E$65w zNGtvwwjhdc-;7c#Co-lMl0-fK@jlE;hz}9r^p7P)ZqY=S83|s4rfE3eIO0^#$TTr9 z!OSQ+&X1ud1OBuhlQ}aw0O&h5EdvA8!1h{@wXBADYb*Jh#?vfy4VF6k8&Bi^V1!HiUQre5N#R zZGh+M|HJO4w*D^Y|0wX6zx_ET44zSCUGlDeQ=T6@c1Dip5Vi12=o5cRP7CF^LY@>N zG{Y#EIMX=rC?O4e%X;sKZm{8H7W6@LflaVt64^3R}>%)ygJ2|h@{5QY|OC3K}OWgw2E2au9p=qAA9YBNC z(g4K;ff>9``StuSBfM)1>^pecBF0%b!{^(KJ=Iud0;HtkQk&9G+jg`6vYyg7o{^p(n_RhkJDmuH{{sV1e6@QhY9ASe?br?6d3Wnjv1$>rcVUNxKzR&}!G(&&^uO4=7MyJ1 zApA^kRyb8@HntD{D_lPuMqj3mIUKzMUcA3;4f3+fgHuLe%m#^N;}Vfi1MiCN2CN}I z=r>UJ+KKk&7qquFi5q2Ia^ToQ9xdEOE!s|*rr?Al_tTXCMIG}P5ir=lzZ0zbf^`;WUKQGEji zjQ;4SCi5W6TQ_pz$9M@QQ|521&&@X|Oj10DGlojWZ%f&4Cp`|yy}nOI36COviZxKz zIMN*>k45hGUmkY44Wn!~u3SOSujgkc`tYu>?s-vc-O!=-IcOmYNpPaX*CagXGQxW% z=aFS6)^G;*V(G;Py7vk8+O~Dy&d5DRdZor+#`4P*0o<|0oRU|qc%PA%Lzvbt8=*CS z$V9kCvW-S=j`0mWFjKV|Te$LawXBZ+TCLr)Y!gQAsVu^o)FMDJ2yfdy5@z@|>a5AH z5Tjj06!zHa?=CWxso&={+ZQRKa#1kwn_dQKL1QRS=fL_mf`mI5d8nw1-bf$)_u6k3 z{b_rhBr^@|>91ib4kJQ)Y0>+#$ugHs17?SC!H($OYyO3I3>76cPIx({3OPeSP z?Uij8C5vGk-F~7lM)~@hVbnlN$90uEQq4EN9oRx)Tw&j8a4nT$CoU*sSqvg)dlPyt zDwAA34-q2B-8=TrW&@ZbUzoSTF5zjB98Tf5i+kPlLg;oCsYFK1V@vFU_J!B2cxrh1 z^#Aa|hk)l}7ztcLsRR??%3Kq=nbF~qDq5?2FTU6N#|9?i^GS){{oIF?8dSN1Z{?+* z-HjLEYL@-WiKExZmcJ{w*L$br68EY$etr~EM^o8)8iqbY9IjHX(G;rBH->0CfE9M( z7@Ik93>nWAf3ocA*O)vjmP`HPVpXR)TCE;}+)rbjF20u{Nqmb19=gCzZt~ZKp?(e# z@g6q>Dw74XHNomR~^^vTWQuhnMo;C$N5Q&ieBDM28M32eh7C z)fFdfe&qc^+yX*z)1wpilw+TE6sAidxf{Vkt%m`+Jzzl*D;a)b9i(p z^7G9DKd_KKOOS@_cd(BkWdiQG#=adXDc2$PbyIe}M|aZ&Fi5wv!_%^#(tv}p`kHjoT(qh(0x$yqtb$IHyA~~Y zze6O0sP-U2Jx1=oyIEwP>skrP8Fg%03hz(bPXsYl<_ZFyv?5R$`(WueZYb7EzY@UE z6qjy|&83G8mQ_|84FWzIU6HuZX@+nVYsO!X!$vBB*rgSCim)t8;KJh8^`Y`Ilhh@Rs zk};>B*iI!KS6@`yEAmNP`s8MbKT0`VfhL)r<8@|5ZHfgOk$Yj$4#Noi+dqso2^~m; zEl(DK@zIIGu2ozSe;lSLvhY@*dHFs!XKf=R$(41)WaQ6H_sbR1JF5Li=W91MQB}5f z#~odHT=A5aB{?x@xI4sKSSq|Crk*EMz>jG9Wxhu>;WsCJ8x&I)qT*fO4!00?V{goJ zBdd!cdy<4D6G1BQ5msnw=?Cm@?{kMg)2yW@U`%qc1&wPm^a`04>^+BC%2-G%%kSO8 zlus1tOvZxh1eF79+;~yE$uPgc-~X~BGg&Q2?>}I4T(TtF4WQ^?-3dkPjkYfg=oaQ$ zrY4+qn$AfBh(6ef$d{D6aUdh<0GopQA$b6wJ^;n;Zt@5pv}6QrB)vL?d)J9H2cDf_ zvMrO=lolyQdO@Sko@vH%T}GC?K5yBwwbMouCS}iCX{lb7(^Z`vB&)a9TQTxK+`a>g zy{svpj`x2pj7%f7_j1At3|+wRKRfU$(wM%En#3peA-1D|y?x!yNFtL)GLb{fcd<(A zw3T3=lpR>Qkxqp7{QsWPNBs_6)!n~XZ}H&--wXOHZvLDUpp#%DhSgR9SNXr|- zLb(3o<+J(Nl}<}ne1{_DMDZQwdYc7G3j=;NXn}r^=T+!@R!8OzINb)@5|x`nkwx#9 zK6qCrpQ_cn1%2?J>xgLvig}UY^pDg_3gKg9pk?b{FUP<`69)<#01YCn;%aHAZs$qB zb{<1t5Y9QTk-qR}DLy_g9rx+D1Kn0-gPzuSIgheMwHCHI(Ynx0pcGFh=ss=T7D?B> zh+0_T1vDhxgx^0Wvlp4vU_#IlFyF)$Vdwo#sph!3<(9l;WUs1zzG#JBtz@#hQSQ~jqP70ux*FYq#!Be zKRw=~V~foX=B7#~HQzm;TowOo#B=M`F&yicu5&*gRS57|v@PDQa1nJ%&h*v6G3l@A zD`jPB9j&fmuHQ~_HVu`-P$xg6lgUEAtR<`t902KYc{z<{gpD&Sq+~Fmt3fM$P?ZR7 zS@9JI_7yziuri~_a3 zr`RXa(1%0UIwNVoXszUhc{KFiq^6NCeSWBh?DANn^du_2nUP?!5`;~!X{Aaq?cctJ z@#Fr)?-s*HG(smFbf?e-U|W4u78PklDT3b*JnZ}CULw%87D8Ox*JJZGEpRt6NXg}C zYeUvt7D=}hh^MUW_pt<5+?f>ccC%_BwDp9G#9b0YtT6L!dOr!LaAfF?PK&XuZCFT!U5#F^Tv~=Is(ufhYrkH4-Qgr{jlaq=!u9Np$j!^w1E8KcdvGfLvmyj z;?T2Ra^1ZV(pgaWhNkbWSUzpdBwIu6$+0*7p$r;NqyoHfVK!m%8cJtW%ylY(+H;bC zya9jO`SjVcwB^`xz%4+Iv%%MZett};0QrY@-g5|O6X~Y^t-Kfg^zwkaaa4$8fH?$f zfl1;^=U~b;N@{-H8C0iyqk?Xuubc_tjWPUAX$HBg233C*nb zOGBp44>4)ZXPse15$AU!^V8-tBN5K)Qs+h$yd6IFX>7BnXWm@ZWoG@Vp+FKC8c>R| zoKu_nyps3vmVM-n=jgU09EJi?_P68X+HIc=7th%Bdpy4?ttACWj@C0oSsC|^qoW+S z^+h z;_(`iOKdQ+NMl+jLWFL#089gG`zR`kN}r+aO+($2?LK}bbXujudM=K->p&N72xwW{)5W7z`KNpf78I(aXLxF={ia3i_ZIRpL@>j4g1XiLwq3 zew}ne_p+v;av|&%Hah7|Hdbj*7(zqR^Po`(_zo5HV~*k?r1Ec)*>B&W-ze?*adQ^fo1sL9gFg+z-5xH1*hfd_-hev)Pv}nbbB;6#Z7w$Fgt% zGn)c;KY3DrB{|IBw>8i*d;jgojFyFDMkrQoDG3wIVcfCfrE$M31LdE>8x^J6??3}3 zi+nq_$31Ie>2WVZ(jQXp9`^j6LCqX(=Ba#+v~mls1L(M`2WTxxL%e@a5gxR6F%WoAZndZz?tlshKQM+|_3N~)W#ymr z@&re{o!FH>A8Dv$yA9%_+6j974%PJFk1KuSRm%!WuYjfkh(^fV}J$8oB<(7MHbzk)6)SO#$uxq3_qzO-CM;%?j@pB=YF34eorp9HU7HUX0 zg6>tUY@q$kI7FWsNlj{W*{Y?OwjOyA=o5lsOi^c#9!&M^ecr;RS^$wQe2U0|sAuMj zVp9(o3xm$Slg2uZw5(o=VMqvish|5}@|wfN`jDIjWXIjcg^i$%_aTrI0e7-w>VI9C zhycluCQ>K`|M$Sh9Tr~BHST|W@_NyD72JfgDYMNv<55h<%&B~UhG+ELGaDbmDYa`YHfspks11(g?AIw z+DXl8>*CgEU6!ol-dWH8Vp=RcM4AbRGF@li@nd#EyuI$r(_S~CxlXvYk1~527Q1WA zh3v%SgQ)4T&cnbgVg8!*A%(1rN|-2g{)FRF_@IZ{uc0WhMqz|UdDx?y)0G+Pwk{aR zwxJv6qGP8vUe8OuJ-F6+mBtuN>V!Gn1_67GlWOAm+HKcB*f?9T4Z5~lu} zHsg?+v@xG#mrILpLLoc4(+vsXUDT^Lnr}qUZqKXA-9x>BezP95QS)z6lee(X7{-R8 zA8RR>Mjo{Fc+3bocVHv;>S4Y9bKsR{HL0n}V3p8CZtu12b2l4REZFN3Kiobzmvr|bK13Wv8jLo^;ta22WH6PGo z1v+ro2VVUxO`j34->hDH3A(JD#M$UkH;l7i2*_%o^|54y>0ruO`Tyj68*E?^VXSU$ z;-AV|nu)$ar_pDV^Q=hmXsVe#;*;iM%a}~-Og)%(vt9VsF8~@t1kx3@pHMdd@tMklHf?1$=E5?dclTD$AcG3n(E{DwH?Qd3zO)`K z|7us;U}t#hR~5lI>fAX+26;8}(qazZP$>kOBXnrxmSJk(6ic?dWaxD3nutj`f1d^u z(a2(Lg@bl_jNl8YrvVSY(Tp(nCc901Dfin)XEyXDUU1L=@9Fd@Zgt4*b=ndyt|Xa$ zaKl5FEGqt9k{%}DxS&cCVZofqT3`%v!zA^;#b4vtm&aIcZ`n(Km}hL9H&>>UF3LjP z6BRCQ44)MkGR)0A4F?W*{gS+38w=n-uDz1A^bX_!$OlOuJe9<)&`hcH(k)y;>1=?i z{KCfYLivWp2Hm-L#HsrL*!4@NkM2Rj3vLD6U971#Hje!$1bsSrxh_q=ix3Vd0k2lj z;$>i98plQIlL3s#gjb<6H9?i>ND^~v$d((jFdZp1n&~rb#m@%DBumR&%(frrJvV z)LTwgS}2yu@J9+hjdudNulSnqc;qW8HS6!j3hjf zdRulxR1d0Ez7Pc(?TXDD5fqrltUx#JD{ZN zTknSwwCS;+qQ+qicM5G;n)U(PqXovQbzgCskUv^RZYfsfIwK#1oq5S)?wW8TXE|u& z#yz$;8F`|kY&S-m*;>vf8Htv+GO1b^mrW@f%aTTTa?k%g>K}g$_s@_*yym3?Fnm_ zn7UGp+Zu*J4DlEi@_=SOf{kxl{=$yl^Q@|Cx!D`qw}Lw&&cWuC)Wj_ys8QbNVF8Zn z?C>o!!KVLuh?v6s%E{0#(INhx;_U45YZ}Oi<|S!QNA;ihkJg?u@1rtJVbe_q@ZZiz zu6D|^7FY89f}9@VtKu%T$CG$7NV=hiukYJeEV z+ok)Nbnx9#76KA;b(4O8q!%p~9{ejDrZ(pYW`3-U9J_z`zg-P6Oiq*?{}A;6oldN& z<_o;wf5q!0zY?L5#Q)=Inx+~($NWQH=1_37U>~<7r_Cli%IH;C)RMv(e*!VhvUU(ZO&75;gqm|@s z$wKwq=cWVgSJ=^hC%VZB;yN=!XT30Ywwv7!1mozt`9yBtrlG2(zjqk{m^>5^-Ktl5 z*A0t0%C+;p*bSz0NEP|eIM{IpZ*;RJ3MLVArlxJ=>u-7}OxSa(s4d)}bomsS7?Olj zq+dmxR7M}S#k6jem8);E61Z^UcWXjJ76{%NXWbO<{!Oxv+h#7-9W!il>BgNof>?ox zp~TfdV-Ur_R)8^JaZJTW@<`N*hkZd}+n?>eE$p%%WRPD}|BoXe@AsAZ+0qNj%~^3Z zP0$L%s1}ez48l-;&=0ADbNXu0cj2#al~ym`yq}YJx^{Sy)uce-DAx$Rw}|yk`5IUo zj^jE}zx@-+xcjlohidmlyq3n&A$PQ=;}v5I5%~+Bo$S}q(F1}JLR+yfr1Ex7&fulVm+bzwfVA8fwOXtvxZN9 z?eV+|eGhb%#F+PsZAXLL$cw8a+n0+~j^QZiM!eh7Jvcc%^23-`?-UGAbc10dr*x5%fBv?1MxC55^fECVG3 z?wFlR7pDG?7+SJD$fRv_5Rfj;a8D6 zo3uh!UxICDak>#@IBg5-5-W)7mLZCoGFG~>qt9=9K%aab1BsVRQ%XdUwhHUcl;-H4 zAZg#p{Lh0Gz4rmwzYs#4`S3jp;vMlSQWO{)Uq z=Rt`B{qn?DmcqOIw=wuQ zP~FT_vMFqIB0t6>V}|3pO%}2(X6?Oz3v77!nsqWvGsG!DlJ{w!4EKsZ3Ms7s@rHd? za}mnwEQxKn(M=9qQ8{kZL|F(})c>K%QDRtfZpP}&wdd3v@U4^Y%){C!Ld}_m!maM9 zTTs)-pc$=~Q%+s)aV>8nN1e#Te5v=_sdjrmoVa41i(;ZA4Do$8xg&=g#Ae)-e)xpH z7HXP0-Trwfo#sDAvF*s~k-I$R3zangy@6Q8?Zd7L3ZYcUs7BZdjOV@gh`hqPU^r3> z3^jNFf*#rK-Bbctsfm{~!LK3qe_`$^ z5tw_haZpEJ1l^ne4^wX*4dws;|EIEViR_vrNs^sp8Bxd*Qiz!BvSyct$(DUDitGy6 zl{Jig-?Fa_#=g!N%M3Hu^_$+W-{+j~-*e8KGc(t9Js)$w-*5NFZW-B@mbjTMNl$hNIuIrwz-N906u;)r|w=PN|VwybrPL5XguO6Yw_s z_a{fX*rl5s?=A_xQ2w&puHqHFWmF^g_ReF*TV-93hLMJj{r}emfNc*Oc$rF==bSBE zCDvZy7Z@dH^}`cg%>Jh7@Q8<++%ZKrbYCOHhyFf&-OLwwHj2%Qez#cbc=nADfg}ni z_T-)=;$0X~W4uW0>QVnbq+xMuR_9aaf5NgFRgK{yU!%G5zstv&YhzgJUPuwmOL6fH zD?@8zI`h6aPdRky%nbg7*M)gz{=Ss-?KZTvvEz+vjlq{+qK6EA0s9sV& zc$u`FgI4Yk<4Qj<4>tN@<&-WvTGo->^q?M_)iq2VaYUqOi`lu{EQ))Xv&lY}sZw|? zyUWb_zMHrZkDYco4)p`Sh8K+0u?~ul1T?6<(8ct56*gADwh=i|LW2;J0hPNyEv3K=n=OCKTAQLrQ%f@?*jq zO$-q~p8X4+3yKSHNb9DhvCY@Cj=#e-cyfkZIU_!}m@a=f&y!nef{6WzD{}6RR0`Z| zzKZBvtz*W9xG{XaRnLM@jHTzAo8VLSvdZpWA2=bzyUw9jA#kDhI1O^`_0Q?38M_YS zhy8B92RRq~!nXnd?Gn$}ex{0Hs8f1XdpVvec(IFna~&eeb;;8L!9@2P-;?UvJnl_I z^ZXjoDKlHcQg$3?AFK&mJLeY0O>XO{{p?}9(40VUARhaw*`ID6O;w`*qXFF#gJ$_r zZBwf&|Da&W5g7yEyAItsp)REQqLvD^JR99b^UJ-20b0nxEelJW;XO8H^Vj;%u5}N3 zF;Y584MeAc(c}?{s)X**Df0*C{1JN3P#W#it`!BCs&B@-K z!kAeTU7UF~cDd^9v3c6?N=xtVa+a-TFR2h7uLv*Eb9`JoD(MGeW{JVW5%`HOTdxl* z(#tQM5#*@ukHnNeaXGtt4{L?Y8Vl7UuC-}sC++3@n7Q$m!E>I=#Gn?7Xr@15gHmY# z2DjyTG#g(amPmto+1J`W26=N$p4NuswhIN8L)q%aeF)*_%ss?bVM(&qn8I9psN|rD zY68L@pnN^G)89tctG4%t13^36KH*U3G6{^n!0px1gt<$-6^@?-Am^g3eIX&ibXOVQHl z2f}99-L#c%?an-cr`C;q2X%DZhVye*3QVd4>%(Dos% z)sXRJ=<^}zuuuE1v{asVGB!GLSy;4cCh|`5g)<9$n(9(iaS6{&L!e)8`}{&1JGP?%87xIHAH=`I zhgWxXv%{jOcMO4_T4d|144wM89Cjp1H2Ytmpc?ZlW$M(BNwWiT1PEK~L$}_6d{}$) z3TZenbe45;dxP5#6gw}guODLNIP3x)FNY%feR+3(=4A*D)oq%*ayvt0ATAb3@vp}_ z`+@uK$7*TU)s}0Ix~IX%AIpB9_7lY5G1{_(sW*#gjz-Z?3Fs8yaBxfmA-wG`DCiRc7NhB|}aada*Qj&YH#Olf_OVagwRKi7_^o%j(1asn~ z2E_yOPxiWsGFRYt;!cz0o#msOaq)MbE!c$Q6v$@R3o#Adjm49Qe_{vCiPv8Q;JppO zz%2qgI?apce(3*Auj4#Krn0-_;nj$$hGE6V*RoVk@8z9w0`v*`EAhvH*h8f?5T=tDlPlhA6h7Zq^hbTe!M%M8El3QJ?(tceKKg|E z(c*;dMq503DUuCb$G2W-_gKB)(JpU74Uc{_i8W(aEZg$0Ye!s0q`v_Oq1v3e^5D@) zY!X!EHUPiOuD|}0uIpIWeNo7GLm*JM_EMs*BDdx*9IrWwx|!08bppm|6&2gyPxB4C zgtLXL6I1WXHV7Z$xl|`1=T}p0nTHWw8iV(?$d8B^PpRgZoamPvYd%-xWlS1KoLG*9 z2jTYo7wMBNYn7B!UiD?(|2-dUJ8Y=)VkqeEqDbJ&b%KCww;PRX6>b*?YZiKTrlX16 zCo7_Ny7K>?{F6l+K^t9S4QYz!i#W^_Q7w0@e*YM0+C2j>oguGdua=UGt*pVLhjRPr zWO@i3iy0|90m&j-3d*ain~N7cL}=FxJmP96h{-BO$KqvtdFQ2faLj}0zdtP2A2i&xYsY8f4CN?_< zvCjBcP$7|=@GP;8_@BRt+RPK?fZ%(jW*un9zP*D$_C9)Q92>tbCg9UAH`OH%WpMOH zeg4tJhRm@RGu>|f7gS;5>Ji2>W&U?bBn54j=q~W9@=de9QtZXlYxb!~EMmM~Pr?V(H$4b9vGsD4t{2(3I+ZW6;X6EwO?gT5qK_70YGai}*_h^EFNhB_pI$c!yaMJh#cx|6va z8|F?Tiul0shi4i)|L1p*Q-b@4zf#DChrk8i$+R~uV`rG}#yCYajtkGvjnt29ZgqsI zh0Z;UqP4S1nP=t@$&IwRk{;q;s6u+P!_yiX}kFG1Rq|EeTqVwWJ;M2LTy3G!^3 z2k)n<*z=3GfpSZ~i6>3?zK(feogaG>^yh=p!#isPbw_p^G;9?)AS9fwovw6I{0$4@ zOfP;~Q6v1VIUwGLXW<)0gu}p>wMsngQE8zuuxrfZ-q7MF1zOUb2^orrFJvBx(wz^~ zzz9KkDF{yRnO2RmzFv7y{Pn9X)v$GBKR>*8=E(M zwnO}3C$sHho>w@mrePbOh`nXf2Mcq)fq#Rz`JrJM^Im9gVq(leXdc5(Kkg!d;-XiO@eSX+V z_*z#`*6VXFFtsaph3n`bKcxbB-@X^iyQ|uljg?sT=x)OD3^%zRh8H(I@+5v-Z0U~r z)c-~#l}}*PPGGrcKjPS*CJME+7nzg)M=0=MRJEp;!IJ003&sW6o1+EG-CY!r`TnGxmL2WJ-an-UqtyV+#FYXe3_K}uMRhsz8yLJ-~KIm-$;HifsmH$$R5z$hp z;f?02k;K#Qgl;_~xTO&2AP{)-3Yt^+_BxF`-qCm)Nq%o0(c#9yyTlc%Rm7cwY9Me7 z=Riww*-vN|R0r&hzp$+}cPgP&-yQn6)7`8213efrJ`LCE>zp?-u$FCsS)r{LMd`M6O`qy zSSO@@&6;CFS{LJSmp)$DiGBW3p5oR$^o*1@u*r-SP+l*6=7wJXQdj*73RZ>a?ZTq3 zxyks!JG(HAy34-Xx4^tf*}wle*=qlS!TXqxDdaGNCzXe+8?|_&^5;$R0Ye5&}xN71B-nh=$|=91&MNe;C8wSKa8?B|IWR!zjGw@ z@Vcl6IjQ7g4n@3L_FK24*_q7Zi`q;?IO}4=ixsM3VPmcI{mL(u5FR6d5_ym9Wh17p zpBL;mq+%dEaH&5bQQyVGj_!dy*I>s)mCufQ#P)Qvl_7kRMA>Qi0JQ8bQE{l;1pHr? zsraP)c*NPGIU(~PeBcF8+yB%<6Vs^mG#a`oCUcA?FYiv}bUGqpe$vA(f9rNl3 z3B6t}cNnA)$j1#g8OE?I6BTyBN~dFUV#oS{s=@v-#7iOY=o2bGe`oJtm|#}l{(Vja z|8#cgMCvQX_sDqW;sAbYVZ6V7O}5DT9u)ETmt#4?i31>KUfdmiiWLmu8RJm+(QQ3^ z+5YXo26GbsdFhXLp8EKS7pxb=3UgekRmwX*ZL+FC3X6(mAPNO5~#_ zEN>GOI+`Za{u$kH97BcofB8ipu94R}wY5(yIaujbNhoh_&$Th40C=@MG&>pfsPCrJ z{o}>4#qE9sk?Y;$x_VCJduNlstYbOX@wHIQ136EvB+grCsX)XO`(#XfT=PpmuWy#G zQco_kd&WWa=UI^zxbWhT#_sN#yEFKAi`IHtU4@@-{9NK-w=Hs z=_FfXyMmc0eweN!t>q-ne|yUcB~UkBlPY=4wGN@<16w!-*XoP-XR)cKw9kmw_cD>y z@VTYvq;+QP`_r@J7(>U13$uK+IdRpH7aq62NNFhc9yI^e4}G#Sdr&SfIYb=*uY&{l zscn?9ghrM{UREE%*%{AyXSNtSjDJenCCil-^wmTop!@u!s+}k}_AgV6vLV^3&F_(j zn=fdXhhRTZSfZfxqXCYfcZIJwPu_`_BW%(;6Y5^$2vd@>2dX3qw6?u5!V-+-5l7$Z)l6w!K3anVD{mN0JUw~*w?`W`2kN7YY{CnfzNa4-GJy+_z>b* zermTn3qt8s_ z7errz2Fih3I{RmxZY9cOA^H~~ztSexoM3OIO1Kpy;W8SkVOsJk)28(`kN?0scxc`C zbx<0tnsGdIrJ5kGn04Ii6#FC$Op8(2saHv<*9?!W$mw^{n&}tVRhO zy=n){B#1vC(L@f1zo2z=A_+3XNWg3GXl>vutCQddb~~+1gH96A1<)G^*d&}S{<}+i zZkJhPhEA{V!6Qh0r~M`?(0W~|43hp?kiQj+R@eJf z>|5+*AOjMMm~T^&PriM0>>Y#SgPz9UQV|S^vOPM@+v2%G5!>8#lpM&rmm-IvOOan1 zZn%Bxp!o8w*UrgddI9d?Zs1(%-^>=dI+xCM^4hvgba}229y>>7HMkZ!%X?cW;vbi> zK*N%}neaXpD=r~l&Gcpc^YK__*5jXO)*Mo%__o<14YRgEoEtg2-|n+PKX&({Sne)% zw~#c4kj`2;!Q4-9V{b@7PJJ=sS`3gCH6MiLRbwd zk=Lu?xZ%$?xuW^d9NUs04M;(N43`|_?-2o4V zB6;p-J>8Y@s|F749PcAC!{ja=PS0)2TfR0M-T^!P>Og@IJ};+X+YR?q5@BkczRnia zXWI=84)cF<|IV~=xW_!$T1qd$7yy{mJjop+ybIA2ZJoeNt_l0R^>gLGxBJr4Y!d-! z5%`|>?YVqXI%fYM9^aD6k5+4k5rQ-Qq2!i1?d$kOJNqs_4y56mE6`7PXCK2Q{Xjqnn;gkbdb|eLL6l-^u-$%D)@I>YJMWKNs?x&|9WO zvSoZx;qXTy=IA$_*ws93Z_pk_9yZ}j4 zHkluY6y{0AZxop@xN=$ku$%6ZrBn_rHNlpHw{LQ^wRo{u!+RT4f-Os1G;ew*Z+zy( zzgJnTqN7qe9@GkhgxG3uf0JD{whZ7w#>j*2*Wak!n_lF48!Yy~(`OiV+k%3e@ERQg zH%DH{rVzWyyQm9_6!}sZ`LkvFEMwSd-_plfN$@8iik<9AX0xo`IqZZI&i zWX&ZM+zVM!eP*TxIlSc?iM>dc{^k`8 z;L+5tI}d4mBHa)Vc_M|ds5P>Hre5zu;K<2>UZVU;bXvwI22rze8+L`S!<;?)QxK$H zQ}Ng0KS=3hX2PC?_}`E61DL4!1frV3k|SReL^W7%=+Om;sqQ12#M+KcPHLfK%6EHu z{^z~R`P&e?0-W)~q(z)Y(=a2s|1hBzXY4cbX!;=0+n=96=CHV>Wt*P;X${>?Uy-+| zEjZ%nn@;M21MIKAB1q>aJ!{LeRgoRt7n~24u4aCG@WCj^p|g#-X*Ui}TA23+z~fV2 zMX(51o%ydn#E9#a8SMWjd=r*$L0L45@`HP;3yXz044A@0W$yl^{>sIdFV^{24cIUL!_5J%SQZ<5-uU;<1;kz<0*ba4!2CN8brBv-_ zrUkOW&YSBFncQ1#<4E9w8J^Lb!!E!&yq+Fa@6~BPz0m|swybDk|pKN zE=VaogxKiV!f|{Ux)GlzzLgcR?Hb9vhYXAF{al?9e$?FqrBf6M$QS}YOC;x@Z@<;W zot%Fj@QPk?`0p^pQU;2kvbro)`uYNNMXA}L`zXBO_1Ibb?U7hFYC(s&!+n3ix8&kI znSwV_DEX{q2q7GM126{?C#E(D*7pAq!Gq_1cm7AdrBYlGyN@VJCq8KR**mN7X>++UKd^UMtb%g;RXX2(?Tszg%EH{iUi0 zHpA#l#g5cCG(^kAAfS_3@Nq=|=)Z}bGQ6nycsijLZ}+mpjltD%rJd2T^HF!H*W9PB ztrj;Nj7o!a=fc!5;vA3M`%hEHt!0{Vc$QiNg-O?lTe|70-&el!#fp63Q?9CUo7kkP z%miVrm{V)~%(|PDC$WlBxi+}a>q^g8kY;7-mtg!=Y-%RhYHN1AUZYF(GMn8TC`gF! zAI8Bv7UMbB@vCfim(9)!EN6cKh})pa1(bPLT18w_13S=19!wD%X9c@0`%s?qJRS3K z5`UAPquC;f`Mc$*RMgak*`s6S(oq;q5zi^P|FI@g) zwRK4f2p>lEK9@(t!iIRhVq=&MJQHz5(Pxsm>mt{BKARuUPY~=+W5j|9YOg(hO+vb8 zW`oA~i|L!h6hI+j)T9JDc@`j~U-#|&HNp?<>x1{ZeF7H#*Ip@p!CBxxmFYQEA?H(y zwc!r0M3qaJmlETgX@$?+?%r>T7?7B?V~|S<|XI-nwGsGRY~2k7cn<*Z31Q zuwthCu;S9S)^m_pE?BY-J%qwoi<)@Xl^S@%9$jg6GSCT84la+xKJsnBTLmcr6+SI) zbzO3rhf*;CLepv(85Or7Xq#>Suxhe7Ao2DJ0-dL)R+i2n&yL9+vz+I5I1ktoIX8&f zf9qTh9}^cDgl-b)_Qr-$7*0emb6h}$Y6>6`i0^nvd>pmcQKT&Z-k`XyLpYSQ=|?RK zXr))YU7I2>ACr~CKW(uDGol5e3-y%~&vgETEyfn@9L8JA=N2vw1-rf@lEAQX-csU8 z)QfFBryP`Sc?<%5HYM?A>gF=#;zITEa8wV_{@M58&wd;=*>)h`fzJN^VB-mn0iz4s zlWEc22kVxeb8{PpWB%Yc23~P$N}(yG)ypxh_m}g|9Ek;|)aLNV+BWHK1tdtNF~%i$ z&Ju*+Thp^272?VxpQ138oebA4ZnFdcvuwiW;E3 ziMYgvS$gdI73^@hT$_&XbXUtyulNcIH0x?!f>*@hC-;xU5W9LjO|8`JZxe{)%j6Xj z$zY7)?~Zu*oq!$ET>X7Q<%fSG3QF$6&h7uM00XM0*NKn5pnpQ;3=CUuC*{5y`fL?! zozbRNu2@j5_tv%kX@qXLa)X_B;tjrl`kA{HIzA886m`8gB6M3*?p_h8#n+hQ3%M>h zg)y^BhWLgtCsQ>u+QlRty;1Y(V&A2pw2mE29cbz1R&>~M5PZjl++|l+IX4*g%^K)8 z+Nx6nF4QbZ)r!nBVWr%_1W$mgkP*(n%THLU=P~cpvP8inP;vmqJ(h_vf>40Cs1a zk9=2>H&=j}$B;<72vfn=()6Y^s0txWHU_!ZUHx%>u!fEZ-mgOWLthdDukHh%9!j=^ye1^a^T4j6* zFmf68zXYwB&8vWGc=q_$^7WDxw%5Fam==^lbAJ80)*Ssy0%|7&8BK%dpYhCk+Sq*n zI`X2zMVnU1T!K%asFbSm3s2w`cTH-jtl}pLj=P1>4r&8c&dNKpI=s5EwNLUGksqI6 z1@hU6aar@^=7!gl)7D9|_{XXq5_CHB>J4}Twa$nOkL$~mYy{&G8}!sAHTRF!rqz9Q zb)eIcg_#G{(Y6nNYac&|B)H0gO#C2tB^LiDDAwJ>(kv!qN%-1yNSBL1n%a-~J8xPv zx?TJM$v5@DooES0&h4trb9!i#oii>-fK{@rPal$W8m^&3`LtQ1=3~^vJ@(262A7J+ z9Y%^B&?iRAS-5ho8RaMVU3wq!hW4z0()T+hm@c-0mIAU$5A8nX7zQz|01?Pr`%Ynv zAAqd=>lk|XXZ${SKT#86Mzhh^W`ok>FTznz$~YMJLUA8ajdXcuP+Ge+w4cR!or%Z| zUm!&1c>}Sy+GE5qjA$KCUSl&qv!Fb}(;~x1?Fcop$40A_BQn|13sVCtt~agx+o`mxAN6by5)4B>6z+ z@zW4k0~4xiNr)$V?9QliO>u4(R>#}vcppu}60o*acMQ4s z42JrIgOq;fTzXURGcZ+Ki8aqON(>m9Q`fGn9K?x2qj*gDj$=_Rf`7vzTZL6WP^Y_^ z1y{AZ@$5MTCrIQ|Zb}Aj^epksrBN<;cVP4E6CYl~``zH&d9l2(X7Gn96P>cA&pV_LB+Ks@_dGzgjsxOWF>Xk>TSM2ih*4x@tiXZnVk^% zEa*;Y3Ug_V!c2DLvCn$Bl@QGklOQ)r}3800}N>6u??CULm(>24BoIBQbo zGAkP$RDY}~H1Xig52$AC>vSEC)RX{P*oW6$!z0);=j+bSYMV!}VaRMtyv1H3vICj{ ztxP9UhbfFp{LDEguQi0~E$D!(6s&``q_Kt-m~{|m*8JPAei(@|8gg7g25rWVD*>&b zgWw?G#BAmD8*&iuB463fu{&|Xj5>mOyl5_W{ns}pDw%-DXbdav?vl<(3ZTixw1%-Y`$Pm4%+J$gw_O{HejtL2kyh>k`*G!*1(WfNN!YQ3B)#uN1e1YeMdxgmu zU8DeDOXBa92f8}1$WeV+Aw6~W8LLfteDdYQ?ZDsON%!Bd*X;JsRY0B0+!;2aa+OMG zQ*j30#4%yvMN}gO1HEx7S9oL2_UXS*7F+SFwq|RF?QmK5owMWok;yN*Q}NQNjpIc| ze_sj@-bEXZt7FXJ?kW_W;n>VqjkH`bqck{IPZo$IC>h{pKVMqC4HbKP#fV3_Qk+%u z3vIS$+CE0Rg}fv^DTfhm_2;F(L}v&4!;PzXQp)!=qvI`4FHhu0`7z!_$NP=s+M7v+ zeB-=r-8D6R>6PSUz9!daE}8N6A>z+rM2C6c^aek0?+RjV5wfHJ;)`Vu#8_i+lzDf( z+nF_`0ymu_#bHlf^Ly; z7p2s``}Z^c5d~^QD;vR@DzYN^)2ea4>SoovPGL2NxFoERf?23DAxa)o2`7^~EAMvqsSUO2A41c5aGe2nx*# zee(_&H;v%vn0NPuE}=y#1Ol-Rfg4-#SYPK{9#mUT$j!4;e>foU{+7Hw?>S9_y9$}x z>@_c@j$qQYNB>Fyh;tT19L9JYNmnyAzE>9b?><+OBsW{Y;Ac`pcFM@?rT-Q+oqS?y>phUL^TRNJuiG%=%q!+t%la8c@L|Zcbn4& z;!9bT&rQ0)d$$yNYhJD)@CyBxbM@Qq$ZdaAc`!puNC59#suxZ3B-RKi#6jLQ@Is|O zSJ3I>I?4$#F#THW86ulsEva7*CamnN@Ytnz`2@wbMf}Bd?iOUZ`+N<0Bv8@=DUl8EjM@={*yS08u=l@G=KeNcGvxf$~a2?su_sMA%tsU9B5F%EiA z2KoV1kB$Y%|Iac=QCSwC$52^!FNP1<7)UY0 z)za)+rsRDDWQlqQ($EN2ELGU;9fQs?Mk?Luew%q)CwfkLht9iXG;fR8nWc=tlFf~{ zE^h_lT_J$0>P5$}V4{0SH4ujBYW;l3*aiKzX)Y-8={R82YBrVkmROiuCVL^ZJ>9tQlK zX?&m!d4X9axRc1nrpSGQT}DQ<#X1Uq%y~GC%ZWe05=G%Fig)0;H@I^7W$VdZZFd8C zAoAt{ptz;wMfie?o}54Y+gqLZ7KuO+6X*Z_I0{^ti^N_9{sZyup6vbi5u#Vc)t1V{@&?56Schb6QZ5j2eZCt3BHiY_+aE2IUV!*`2uJDszN^F$Z4X? zCs?s%MUjIAUTUGO`SCq6!QVD#mH1$1W9m)~o_?JT3jDfIrG&0EKM504-jxkpe|Y|~ z!Ybqunn%6!Gf|;hIMA^?qvv(8yc~m;c!I##{pkngJLcZQ z%hWWURT3B%>hoR;Ta{;1KU#v7XZeB1y(PisdtqN*I;axQ@r8Ur?=K_ny_cdUCg{io zp34m?WzmUN5rJE8)`=z^@ri{=TlH*m6T%B$-&fBp5L<4?)A#tijq@aqhBIa=7yhai zX#T^5O{HED+&Mfu5_>XdSAqFd_Ai439G=8CWgj!jGVil&bpwXf6kc*R(4XLY>xmt= z>7*jWG4aacG$?W|ydgFgb!K<+cmG?|&U2FI73A)z(E}sr*!{(HnI#^l@>E>cW__1E zDoOZv|G6V=_y)}em(NdLY4gA2N{{qW(d?^SrI8WW!(;B|Mg0)7OAHz2jFM4D7XMp- zV`d(whJH(mKy1F* z+=*hcIZ;U7nQs_EyJU*alR`^TJH(-WHGg6i2ox9ZQ7HLaW9IW8i2wikA-0Pe92UwQ z@(uFYo&<#d$d`lq()5+B9j0)pIcogjDb81OK4B{R``!;DF$!-%eFTpXDj;+K(xrX@ zXr6g86RLzU`-OG?HDKL(dr@k!3Qpfqd0SXiJRrXIVAiquP(Zu=o=KX!wdDND%&#v1Z&A29i@fr0a5gpr5{_w*4c|Nwvm}X zPx&D(bW{193-W=^J`)*3AMv!S9jNy;~*`_zq@Aus~=i$KWp zCDYDEzA@G(bwC7!1yz$TqkMNd)*29m9WJOQ4k!JpSG3-_&S@IdJ0YpqEhgN5f6o;B z{>Zlxv0FTqwbS?&!KGb6205WlF683i%Ylg?dBN31liHmh`wB{0r78ZSBT1%ewIdyO zY*b9HUQTH3Ve@dlcG2?2@{LC`{2y*pE{EQGwJa&zx2k1@=H$`Kd1JuNQb)sy=6|Km zAJlS<_Qs9s@r5ndSf#>sVGxBVtsYihS3tel|Gj_od%+%gmeF)F>r@JwI_>{F@m~)_ zk>CYN^?T6c5La-JrXx@mh4282n_`p-pUa;FZA^SSKZLs9ZMO~+4SVzL zx|LZsiR1UtfpSLm*)NjRX}ofms)~08lrJ#4=)*gBM+0y%t1=d^_H{|kq(iLp0Fv1l z=NABUVn&GqLP{h;Uh^-s{yn^peRKCvyy_s(07w&(B$McmeaM@boVd(<2yKS2IXYfzE)j2rb*er)S=fHvnfn2>7~7R7Z^I2M-TkgHN=W3i_kQWsF{gM6`R8u8W>BxFMo0D zCgv4mzU7xf55>DQ9AD3x6g_up+<`Pv`=uj5IO z=?>Ux*GxvhAY{M5HMF>`TM5R^62;k((StMYl)=f@5iZz?g-49MMJz9xCl^%#GB zy6Zh7mxDilymA^NlvcQ%vmL`T%YoOuqD0^WImhW}zARVYwL{vdqAq6TET@)LCgUaF z%!AU6DKh7sERYe+gE0qj;}F3 z{6^4&4xZP1U@E-L-1*}5op+8m7M~EMzhTr&9){|taS-*KFDZgG+6+p~7k7}W`FFZY z?CpuHJNSwQKGSu&jkPuG$dd3oQk4<&duvdoIyrdYdl^h(tY3plRs)H$ z%D+YwmM=(8R4&^u{xn4+%b;RmM}YOu5un_`55j+Yhp#ca5{z0g-i6XcEXE3nnD86Q z9zz|j(ke*{M)%dAYTXT!nZMa@5{KHJl8mY zP=>AkytDk2bMrw9dFAb!xZV5UfLLZ#Wv>7O6MhmJ zC#@y1Qs}+YBOw8fVc3pgWtdSKHg_;ONF4b^V%aHXw9Bx?KRXp{9Y0`ZQ@A;uFX4^O z=n{@sO`CZ1RW&PjcJKfZ3_-7n2W}+|`2eh72MzHB8OYOxF5c$B$_aN(ZgU68oG-X} z9w_fCs`QcZif!QziaA$MW#N5K&HFcvy!xZ3rBWy)35^L?KTx@(9NC72~z+Xs1Lrx?RKi$8SIx}bFfU2ea$m2La;H-<3D1+hnMlZI5I z1|F%uSX5IuuN@8PQPAG2m5zVb67!}onp39W)u@WFo1%2^v`MtyN(%>lr;}h>bFiEL zD0g!q1E-`{_;ogRH>Zn1InpfxMg6$=>k)XERZ7|*NS^JxC*r)?TxVOpOD{gI(ol}( zf;GNFXZ^UOT0N1cUH){&QD)#m5C;wt()?X)5aIqgtD#SwC?o#E3_FE)Qd$X)_%>0h z#xi+Sz!@Vqkh~5g50^y865?aSB07{uGoT}j`~6*j09CkQwRiN)c0Bj_x}xl@OA$Hw z8NYEHX6G0e?QWB5!0%1Za5z1<--K4*G(lGX$v3d`>k4gPTql8*j<;r%GB7#hExod; zpy7F=aoXRstg+eM-b=*d8+p?~K3~w$4&I({7PYs@a}B@^N2Be{NeC$xhlqoW^p8^T9^%i0Z*cVrR3Q|$%e*35vSxBJkMlaSWr{t>korWK%0@R)Yz~%spP1KXLBqgNy7s#B(%=WwS3d z4`kyNx|q>Bv^y2L82&ax!2SbGJw}GtWJJd(90}s36z9`|`?y=pbeu3t@l1BAjN}!C)03;tOu& z*o_YFm3m|b#^sa9Dfdc%CC`{kU|klsv46N56;qsa(&7tY3Jd3TLsu z!JqiKCHb)AG0%0b$dwQq{(Fj-nd!8OsQqd`a=-c_m1*&|M>@vvf;)$L2Rf8CSH3+? zpOx*h=uxcO%;HfZ~LFxu4kQ>ILUnE1N zbMM&ZaedcR;q4!DQX41P|;V))gGQEG97rc4J0Js9O!!YF)r#7sk4WO7*zfcG!KeLd5mU z9x?IC+z@o=uOL{v23_)}nIKTU+H$u@2CRQOFf8`9YNM@Xi&n{2+Z5P+JvDqzxS9bij|;JlWhcrH2KG+haA|{P0 zZ+-K*=KhlJ5*P_yCLfX|;uo%`A#kN-yAnMc(3?WEA+cp z5V2sL1^H+(SyAe2`m^^9UMG`@)LS_l4lg~SQcd7tjde#{*ZGTBoM2)#i&SF||J`F@ zWM2iIVC7ER0H+Jq#Yb0}AuZ4O-Xkl)@Fxm}?}{GRgX;R{ZL7eWuJPsJ&n%>-t<9y! z55dV`=mC^vLPn<_F|PJu@yS6}#qelm$YI^)iRNWi2uqimmmVOK4t@}GU+K4(2>^=R zI>s|v_>}98R5ce;K;iFk$S%tzj~q;?Hpdi0s7Jh9)+5{trS4&nPCF*tk^NC)r%<}Z zuR_^3i(~2qOJ44x+yoBjRXKx{AA8mmGh|@78B5$H=hp9pL173Npi;p5t(FJr%lImE zE8XVm=C^RyZd!1njHCTFE3xf8AwT&o;gd8ImU~t$@I7SVlQuyL@V|& z@8b{54)*MHjNy_jqmRPjBw3j!u07r+Qcqxy)o8BWNDCB6>wShOOE)^)t9}2(!(ZL& z2)~i<#_b&sX*7f@GMv7#JorHe|5%jpK2|N`iBwy5s@Ecv$mT4xS!6@U9T`J%`@#|v zzWT@%6{RWG~C5i!4) zo$!x#)?qq}1?H%OKo}ih-2`n{BpaEx_O>D-E2fwV38vZ85FOB zHPAL*U=CxZKO_)&I1XI_GvZQh_Vx$n*Ow8`I0UR0?RCGUM!(+L?Dy_E&vMMwe8nM~ zHjll@f9V1`nV`$v$2k@sO)AI|W4k+qSQ41-hKT0o6nK^3xmc~9pGiSPP<6zRqSxRRp8*r)lslmiCEcp~C#AW)ZWOKs`KKmlUV#Fh6x@unzJ1tFQmooB2zMWgsdpoL4cNxY3o&r7X;g-Fz)_AdY8|sH)b4Uc{(Pzkpw$aS4JeGs}Ul+hd zWNf5H`&u=MyMk|I6hXBVu9v!od{=)Z`Rf;<3fblO!agI=zyjFLprVY>LYvmUlkH@# z+Cj!jzUz?3y6E)G{yi*O3jZ+@Mz=lOB@6C4o@V*T1HbwaXAe?4F9~8M*t`B6&Y@=}9=$GWuGWj&$b({SJNnFI#(JfanKFi^&H! z94;ccbNcIg9vBEK%$~9`Hp1m7bfu!*Vi2eCNgp6|a%eICTQ9JDTFVdSd8cK7?NhYf zL0Zq;jlEQ%6_OBh{4a1N)5L6~3n(BZ%xykA2HULeTJ@{dpZxs#*&S3E!*P(D&v7vm zozC2rPu5|x*6>+xAg3KDhzTFj4#{z*?sT0nnLBZz9zV?TWM+tV#ljer59pCY&`3Uc zaJEH*7H@fRO0qEnkBPMe4QT@_+W#v&ds=!~Y#fuQ+=-*Bvk2nZHGz4>_a-2|I`#qZB6wG3nU6opDf$ zKUup~5p!rXZ}3|>>~fqOk55>jM&XTLGkn1~c(D-a!u@``r%UI&>~8&Rg4xHGcwq+K zmR(IJh))up5gg1i*hRSbDr)(=-cA=fPOL_7XEm7}JfvB(RAd%aSSQ%UAHTa^?`|gP zcDDEcGYd5}aG_<+3gl!O=%~Pn&?3e}db8bphD|WM>pWE5G1|mk_nIEXl>3|T&3M84 zAqX0`wR0mw*ij>V2Y3q$3WcR?gBOs=FKFDb#dFpTVSJ3$DQk|8z*0Hk%;(C;ymL=( zv5)bke-jFxm@Dz}wkrN4cC#%sI`2sx9e@6{M$=DAUd8beCgmGjL!fOE=s9#?bCD8h z@>c!1OcqU~e=&)Z>6BYE@cl|j>MN=Sc@tB0wqgsuE?%1slb^xXQED5cg zgQWqFE#=&=)<5rH9+^%uY^=V z#$EIl-LzN#^*DXwTYSPB6DUfV%|Va3x3vAfLi1fVhPwIF2nQu7zguYKHu|olsX#`0 zJ4Mtr{bdT6gGjFV54O=|SOxNOn?{G){y}lBudBEj)}-+}8aOYBtUCtFUaPyHrgD$b zE+rv&F+JgB|F;Tw%(2@O!C_T8aom_^*W|&R$nn10Dl0M2zQ(>tuerkG?MYbyc|49y z{hAzoGi#zE=GY-s)4(8YZCR#ZT?>KHdo*69y=Gt~1cI71-eAq+nUzTthQ6F}mySTY zygu9-edta(_gD2bsigYNleeCN+<$khNMdhz*!oznmXr&9CW;%!H;RW6KM*oU%|#&No!M& zFYgH>>FmqPo7T!5i)%m&Vy88%3DJfnpg;$N#}QP$ zWdsdZ1&az=#mc>D$Iieb?9zK7p*8h<@KjCk+m;H@EWe4#*E|Pry1YGimm=3}x?%J9 zx+8u^b9Dz6-F~=1B0V6RkUgyj8>Ml|R8OaGGm2uW9X-t;3$2OlL=Ax?GPrR+fP-w} z2;52do|^_Bj&flL^xvPb?skS@JHM&`<(E29+$oh#Zf3CPRyi0hC!g zpWzv33IWd_gfozOIbid#5N&xwf>oIP4cEyt+l(l2&*hNg&wroMWQ?m#ke(wt+-W0x zyBaroEAg{1`_E=WX~F}x!L&mJN#KKhZh1b`2x0ZLqbfl_vphqNrR5C!vB87Q>hZBCw&{}(2F4R}8Byv|*gU{4*!IgEVj5zH>=$A(TgOWU62s)MC9*Z* zk3Uv}Y>MEd;UxQG3@8qqM157NxaZSB9$p|1RZKc z`N(CZQT1n&v3}&~y^vCNgtVxpJExn|6!?|(LQ6=^XF$-!aDcUaJdvWTy=}o}Hu>HJ zxo2uQSE5z42D5m(AG1f>3H16+&3!H24dfGROtFG@)^*)<%fN=x1xk>e1Bfl^osr>A z77n82mwA#}%!D==zjR6m7qPFuzabVLPIksklVu<|FNg(30R6$iF-6Q7D zOV0IkmYs0I6?uVrw?@!?3Gvm~i*^oWpBa3!<-_UQW`$cnF6Djfo6hTKr9?`;ePR>h z=pIQ-;+TsZc+;joFu9F?$PbM5Q}B_{VI`#75Bp9t?Dm;+g!tcqG;s$%$GwaT4r~I7 zomEWN&U+J1z*9OkY+H{YRz~japwXOEUB$okGG6q9+A`T=(FOlcYc{~#+_;6`Y?Ytt z26i5t&|xx{^&`Y<9%i1o`{l1(R-S@IF#1MJLPjT6jm&2Lq*t({Eo% zuQDP&M47}f|04LE@s+Em>pgJWO(v#NeaBv#+Yiqvh&8ebXevcGv&%Dze{%W~=r8l# z{5?~~KB+zOMm~35f_9f>m&aBHwdD8NHb>(5to2dihwL`ILz=wOv5uyDzP=v`|pOhgJ*6K}7d)(7Be0S)R!a z;)rh~yM3E|0~^2vp6C6ucxW8Rd56!52#I>AS0wygY5_b)nNL0JG2&1QTD!>>{_F7K zMC>(CB+GSt@$&c;RLcWmFRi>4{b~l(`@RPA;KXaJQ7sNw{sdFQByZhN+o3`={sNRU zyY5RSe;u#$!e7B9bT2S-4>VEv(_(Xcf`8SL`2IfS9_C4 z*d8vF8kP%jS@e#%$R5)?G$tuXyY0GAedEDQSl$kVBq|lr!)G4hp>TyZhL3=jPXX>D zZeUsc?qt!o^@o54O`W!k+bvRF#0US_bDGE=d?6x8WReoj+UUfT^4mF_tB=SC0uZKRD;si!}EAPu`w>%#; zYr#BV6BN{>1EFCCXIf5b?mGo=Vn)~z#~42+NSN+ck536BvYKGB>vEAFPa+&5NejSI z#?XZld&L%QCQ#uSYaqYFPEuSq7)V5uJlnKx2U48G77+|{tPXEsSNWcZUiJrB5!WSW zF;GH{r-bo8ZNb^@iP0ipt(WQ@O^fyPp0M+E=~Q`3*3V@sU2LBi2F7{`Ph^Xp z{e6!(zFkyIM2sN*4%DZ(xI1pR)PeS3d&q3^;Mk%}xZtI3sPeSgvm=vA@TM)@Wz5s$ z-k+B%Iq6^Ad&g}O;uAMKqhq`POF+8nAu~|Zx_0RkO=As(TQ9ZA+ zu*p{N)Q_kAl+DTZFbgK@P$2IbY?^t8834AiaD-96E%|RZl#<*DdcW;&Dj8*Yw)2n+1}j3TNV(~1?i zveQDUJAd=e^|;)@UG;iI(W6!OUSIIjDocH*0n?wUuQJ=u?maIw+QBfp{)Yq$AHNg& z9~=4k;xtyt1b@8;>mTp!mH6$r;up3B!%38Jw7TK(@|0Ui&R>rluBAy~r8vNx>d--b zsj$CgagX6|hwwz- z{i_9baqV(qgdwG5rdKSP^ir0qpB?{lv{8h~^>amd36YPZRTngaogdcUh>MwlTlrJ$ zIeuNryX=2!CS$K8@O z*a2cvYK@AsZK-d}Nx%843LLyJ*9=ph`f>#E|7f;6DHhX z3mZhS^@3}r5zl9SX;(&_n2%tFzs$cU!*^zHecZ}bXo5I%>ZX$oi5{j)}cET3#9#Z~+76?A=ge=|fi`=Old z0uviM;5e~~A*Bi_Aiu8NFOzqc*SaiwLtZ7c-3{6Lm{nVbH>*M0B*LN?qpeUgL`DRi z(aRg11!9ETfv9E^F11CpW_AlAT=yF4VXt#Y^$gsI)MJ?-+Jh1Mv%#D&6iv&WGUtc8 zyXMVZ`(jDC@o{qz^Sj((T6{4S%t)2FcvnIBb7=j~DWd*R1&NpO;!jriLjGq^06u&e z-`!N%erTN@dV9UunI!ZxwGMoJb$Lja@>+^GHVbxrJLFa<5 z_A_e`y(`NUrW4}k*Rco!{&$e;?IS`w9Qmf2@W6!9Q?>}-e-rye!=Qq{^$RK-RREP` z3#IPBKHA=k?GaO@Np;%;gBAXQ7NP~L>Z!9b6BAT~y5J6)!+pAkLQkWaa;5x=8{Si{ zqi6M&xa+NR3m!o-`7>YB{35vnCumsmz}YQ$*=EtRtJmj(Wey6*nUskN;H88L&@kx$ zS|iqXxmIq}n7=)eC8U1ojl3W1Q@VlEf`qc&e0z4%Cz-$Mz{P-Z7JjFe- z|4*g26u{s;Qt~f*V|Mm9w6jCFDqwWF&dM<1?l3F-4IKGILm z$~*|2b!6rw1{^G3FIQ>g?RxeLcN$S4h`wBTA#~dCTx_9G1br^I33fDa^RhKPnpuk@ zX~NVwjWLcESxrVi+}(3P&Sj*O8TDQB4F?kih`m<{Ov8VGIJ48z*CIcKqE0{=jbel(Ob=& z4*TmXgBFCWdTwiP_Eq*Tx?ZHJrE22q?g3gUt^(W` z2Y$LBO%{fKz5?w6^KWg!C({U(d&)|=#4yo=x`GLs&tM62m1{+O`)@L}& zcQLcPZ1tPXl00Fg9=|;FC}>0;Ybc?^vS^S6wS9|1*VvF_9WJk0+zOQBc(h@>bdX%?epk?y=Z4MBov$+_qrWi^G+_(}><)kodb_ zXwG960>*w0|KImcNPJC8t^Vh8kJgHO!+nAao#n{ENtQ)$WE|(p7Lfe-Cd{$rqWCe( zgw?CdxlT6jDE4>X)~>J99Z=@H#Yo0E$KGcjn$`$HPx-3^{SsLT$$+OVzAs z>@Pvf;qD3k-PZq5I>4sJA;iT%9?S0A@`f!6kNi_O57T8&D z!U4N8fK=KctY!|uI0HvA&0=Ly#<|IcU5$Q}mVjOgG~6?(hU|l8J*Vq#nhLm`%^ps( zd<$F8=_0+~B5)?y9MG-3t-Nlv@LoOJlh;+=ifMUj16XmI93I6U>9tgbZ+%$r?IvB@ zPFV-5*AI`jzELfvB_r_N!Q+6J?Wrg$*6$+Ax~UQiA1F8^q5oUd68}Wpk#Oo4`1m3( z@!tKK#Utop(GU5k$%~4}$qif+-iyYAG7ha=$He6N2##G5nMkBL8Qe<6LF>)}f7Y!5 zYeM7Q^EtHCCh^mUtgH^-Oq}~5uUEGDuKI^)f8RLa@cYr}W1v~yHuO+2%BvN2qABW! zTn3B6Os0p34+5DtEM8N`vHTx}hK&6ui5rPdAF5Y8vBON79%@|2ehwaG_|m8PF3`#h z*9XnL=1vSZ$9N%&NJXh-W5+i;vz>3c+$NkcLaKgBxrT%=<@gPp>wL?^IXAQ~dK2rU zjv!unc*T`;ygmZYcdW0}NcV!3l4B@3YWW(9@b21(sZN%f?GJY%hSaQyx^Iw}b=?$I z&mau_Qz|RlqGeO^z9)vH78L*cxY325&kX(WHb(BSOi=t zA(lrc5=SZ8#DVo1kRt|u!6D6@GS>|XfZ(Br>{-Q0(Bv^# zOhpHlbl?9rI5`S-%?4dJxenS~_tEjOQ%C#)jV#yka)V#vmgt5~0b92<@3@4o*}?Y@HT{DJwld%6 z$_TC!HYfeLtFj(AyENm;A~Yq&c7DFi>$PO8wXU)Z$1brEa=O*Kp-Do7Ve346;LPK+ z3k_+&-MZ%jnhdwN(&H=&bsv^wL`W732-bm7R;L~{IkBDPMk@HKj|MZ{D7-BFF}k?J z=#jO?=^qvjyH0epcwQI*jeOM|;Q@JQbUQh(H&bbj_Cz|`KR@5z5s?Aa(>6dVrm|k! z9iSx9ltAIq`&w02H)L25^`YI*%*J z_&EnQO}(-aDn-p%2$i1{753&5jXM>v{&>zk61XLrgSZRMsPjO()aHOg0=TeY!G=DH zEII$3Qr#m+>-799hg_aAt|3brG_zvDb33>@fumiquiy}%JI$g1e(n10HUV}o(k5nl z4uGc4DUliH-JpI#l~nyw1^lE#B0QLY!mo{;6b{Df-r8ssY1dg$ z5b&P8nUT&ruaxXE>vcEkXHlel>;cKKnX*_4Yg-Y|0P(kBhAqqIarF5KmE`swiTdO& z$epNuOaqw8TOZhWM*Ys=X#@lRJ(g6Q-49tFIYtvvEBy;?mF0rMf5IUwJEC9dvIQ@8 zCAQFt7z!--*|PLL(fIy!56kf5=}5+Eu11?3wAYot<=7ohMX8RAr=7`f#*?b#zM9L- zE|prw%mG1#N~rw^VD;}B9BEC|=xx2iF#~i1DZO+R1!y+hF*MvWOM$h5ZatW&VlwVl zs%k8zEk~hSefGjHtKNH!*{88XQ-Z*|kDnNBo>K>ic+}Dp>K1vy|Tja@)IwxB5dOhNhpAiVT#d z!$y+YdeX8|EFEU$Q%xaPZl&DPp=@5Q)HlzR0>8`}%Raa&>>kCHDL2jj$%PLpan_M7 zAA`Bt7$%!q#LZ8>_2~jdPm}OKUpA&fs_miYtnq1P*?l@hCclPLfAl3G9lP@Ibb+fM zPvImXdxEInt?lJii-pkrBBDKKQ+Y43UEzk(ntD_&=Kln_;QbWi2kLT(>bmKV_!FSoj$=yLEwAL-jYIJS>z~b1!{{^{W>hriPIQ z3HE!{7MGknsU}o#Ng1K2ZfbVE7aOqmoM7W)tBD*_JP^w+>?YAtXK_}KtiW6cTA+ek z5omMNGdBmqf3KuqeJ}^rlR6yOXaw;H`-%6*omgQILEaq*gM;0?5Xg%jp9PSV7V9Dd z_~U3tBvKE@D^wc15VY=r7K?8Ir#~KG3|#DAmFbrajsj`DRoo7b8b3||cHuWf?{YGZIvoPIGJ&CWJ00+uIkPOwSOO|u_5&d%IcQiTJmTWN> zgja|-QE4NH=Y~4!eGD2T42grs3r?#quI_3FQg zN3;jWMfysm$D?1O85%5u1Z`69>rfPs^WDT{ONC&`ebE-?vJnZtW&~5E#t`^2FN%ND#X+GQi{u?Pb6r| zc=fEjeH-Z<*ymti7cp6Bxj3}v2ECWx9TjS+db?tlw+j4Jp0L~^EQ zfluyqab%k#KeMQ2P4^-NeV#^*eI)0{7rsR5gI{>31dGDI0L8H-uG7VpwkpW2qY@$7 z;EzpV+DH;!3Ays%;EMw2D!jB$d`wxN1a1br?F64$f{@i}Jo5H%vGA3B!qL{`f%+?7 ztlD>|=8y)16BW7jM^ovyA><@(yBPzT{GlB2+I#}v_03&t=?*AADv__~1j5dD$w}#S zRC$1no93?<;BpJ(AMbj;o~*m@*oWn938g>oHu2U0{7NbrV6OM<;BGL%wC+GL5}SHZ zH5O*SPga8D+=xp{E+Vu~XR>8OWZxrGrbiC3XP~n7+Dek|d_u-`cs>BjCO@JA`%Ft_ zwBCq?CIX+23ngB~hL?CqU8!2Oc3OnHg!xEW7->SMh|&A~Wf344WA3R`Q+4-PHQsu<|=z(49MsEm>vq5$5{sL14`L z_~Vx((^*)C)QvK7nUb(YGH6dntk?!1v+VPZ|CyU zINo2?RXHhhBnHis0zUosX%l#ZsX3dNWi5>)epCx)CbFe-@aKoJ(kpYx%6dFQhP!Hn--sBGhddoF+AXW@&REiCyBTLRZ-C;FOEzZby`A9Z(9Kf-T? z@EPHk;$jOEn#v5bUAjnH8U#IJCU*yiDZ;P8NlHUDb`6ihwqhGRF|>H>K^O2uRc5}4I!@lI(NKB4mkKx(6y4;vj_(er_=obx5;w4J+1OdOB0{Zm~3K;jjMXdcR_P@bURro*BPwRYz*!%N~ zeBCpM2nSVDrk`PJA9y7Z0ztPV^>HjGbgoD`e2bRL=V5o=eekG<(4ru5++ME!tO2Cv zCe9(&RAEXGFyQ(f;&h&l`psScMZ~S zSPb0$dB5(kBOnY-ixUik)y&qvGy6e*ZhM3d@km0FS)a9k|yr9T)3PEYL- zbg^o?cL_p1j}rF=LIZ>ger~bM1Gkoa_h?~20+qNV6pEkRQ!+mE^$U}R<3|vC{V%}M+3DqkVhWSS zbnbUuyddT{>*R!Am75Gfw95Qv35sxUjcD)Z9Dq|T_XD1Rq zjQP=&GzXdB9M{0&nq>uwzz*RiZOM1N185w);<4IL$$m{&dUUvfo3rlDnTx}_eet9= zc^xkeEH50CJ{i1I@mA!^@65>gK$2>eqit!2#q++ajS+8eoE&+Ke@2>KV0BF za}ktZ^X$M+foi?SQCdR1ntxPs6)eL=C!XDq@YSpfe2(~rv7C*SnFmi9-Wu1JDhk%N ziM~7g5;e#KbI_!wim<~&^iXAQ&gyA%?% z^v?5_e@XU?vRnvXRWQh{;@#c+{WDL4g0wAfc#@u7(qm z_uklZ+Ua6c*tF3C znMvtl3s*-^5|t?3In!)6f4QQf5WkZ{n#5+`8kP6IuP<2|pg8mrM-b#EmD}4NN9ug4 z#(~t^46~0%6qHs`v+0px2b1)w6S76;<9?aI-APN(I{#^*w}E6PX!TRyt_KGk05Js3 zrD8vl@Z`X87?eZq{eUY_R-7<+DLW6Fr8U?W6+4PT1W;71Pz@gCnM^D_1&{BL*0%C! zChA2`ULB)R{S9_PeQe>sk2Z7f+(&l3q~CKZyeP3}QiB5Rr)RmTG`I^zblxP53VRXb zPS#fj;3trjihkK+C;#9@+?tZ!GBYAHl<+`qP`*xmBT|dVuxb#s*K{}h-?026FdXf>pIC^YO+nK{cExCZ{ zdV`EzG?Lov(nsQ-|NYr5Z150IbTY~AT&M)NUR634taUV0yGocSn~#~X1!G+ZoC z?N4CM(W4$wG(*R2aoKCmg;8OFyVNTffv&Y*`}bhy(^N zZgh||r9*x&Bs#C`vhT6)H`>_p5Tw2@iS>I|)e$O2mvlV(;UOP)Q(27%$vnpV>Uz*h19{ z3uv|^WcI*cirur_CnA4?cT{OO40wKiETp!sBR>{cGA7Tz@@hB)bOKhCsl$<>2-@I6 zW}X#5Sq%uStUts~>UYNqg7Gz=IZ~p{b?@6wNiArfnQT*81d0WKTaX|_n*0QCnRv-k z^cBhL*y3w(OZHz!u$qg~^KfcScjY5~`%O@jvi-Md>e@*>H7Z~Dj2?}|wfqgy*!NlAMnbUnVj)+i6Mjq0mJmUnZI%sG8#iDyZ-JcT6}@{DuBZrzJi-Y7Da z)Tw$=McgYR;jVn^oXo+SjP!Zuw>|hKyN2M95{~wh*Azy4@l3AGLLZByPU&5)QNMbC zCn+YE1^vKPTKBT$M|Rwx1zXBDn*WMj#njh*KYQO2kvYGcJ~0(CDV&4Pi+;gZKl;ZF zqg&{0ecRS8ija@<%gd5aj)^oW+B;DJM2a{VE3wJK~is1VU?a! zC0OXcH6v9%T6o#J3Hk{AF-@2C9V7SY3Xc4+WEet(uu!4~+dqT8PEplGsGRx#||A z-jZ17Uun`p1Cqh(w0CqX@*wtZ|COF$xcC0PDr`JTVPcX}SbH6eBwO%;P5M>1%JM-L z8Uycg??<_%xM7QysHQU74fH7s5b z@J`em3LRRIUc?Mo{#g0{lOk&;8+VXz&3A^G-E`jkIDe5BMBpWn^FkM&s(xgu_doQD z!opFea@A?bhGUkonrRIA@mbEkciAlMN3~mhnz%2g4F^5hv&@XFuQ|Mz9$#XF>g^*r z@9;5tgjV*e1P`(J<8^Mw#^#a! zbaKLlFNp|jO4Rd53UO*{d(Jf>uCz;J1Q1)Y(BTV8l%I_xxnMl8U*E8t^NMn{ z^encd9|xCG0Po2?aA{ZA2Uy_F6LYbb0x3i&|5(!MIHl0Duv+>MrkYI#eY@eW(^%>? zQfyK9Q1kiD4o0A;bRn5l72OK)$Jpguf0NSyg-w0csy%f{4tws zaqDIQsp!q!5DJAdq9u6cs6{Yu6nFN!~atk6kIH&u{WA2+7y<#GR(3a_!Vl8 zI@Ln+G+E51RJRJSJJP3xsazG?Z zX0ZCmxA?;%9ja*sMRp5Smk4eyo$x zI;ehPWi-v4Z(O}6F^eNjk+HqAExiANbW!%;;;|} zNsC%1{owT+*#HWLmJeaaQ{!UUfsMc(_f<{uv@RBNG(QkF0zZ;%Sy)~}W2pNdk7S8! zH-4f0Rz$JTKHi8&QMYZ?a$&Se4d3?X6DN5g(2+==nny>2`k_n9toObLc4%XDbvE0G zo->;QQhjR-!+7eUwX^cn%XY#{06HVgId)le4$?NPzdfa4LEL&&C?Pwnzcl!{1ccJs z6v8mHde_K_y`5irV3(_AUNU^0;D!e{5a5ApY#njxeUCQ%_tn_-dJri1`Xg4(==vPcLE+H-=T66yPT-*`;MC!KM2OMY8@2Y?|D>u*f87n$$ z6rC#@3}y4ZoR~Wm>}eCR_2%=L?K&_7y=pQDX750b0w|hbU+*bodBb-h5inot-oXLp zY}YJii}v!3yx3fSxr< zpG#|@BILjQhpRgfM_)hcCuy!WgEEvJ(q|4Og>-o@a?>LD3F8+ThX1>~a{j%%2Hc7( zzSCzVk*C+>Vz3iSH9t~h( za@t6J*8gpf++1srWQ`dT@}B8URLA^{r{Q+mSfB0ByX?sPn-&NO(j>)XS)+bDivNu6 zs#^=}+nLc_c(bR$R)7#ea}QVDcoffuFOx~uZ)x9&ZqD0mCv6+{DJt&lpfl>`jb+N%Fv>;Ch( zzGnnyf4NqSd5xUgAO>_hUb8ly~9$dK$FZ-IZg_q3m}y^Q$@dC!p=V8FYR z4tKPo8NwMK$k&U5MjBo7cRJ%u-#-vMVbc=db&U6(*Hx4mqpbI8lf{IRHES>`rPv^F z~%@c-sW7fEOBQ-g^uotL{1qH zYMA8MIh);c*rLUi8*BOKv2{Z%Jj$Ja{yjoFF)SoQHI7efInQN3+TU)n!N=Y?=)dS0a(HGX@8d6?Ih{bGU*nZx%Vuu^v=M(4n^#|-7Z9PZj#XOm&hb?I;N-V>>9RBK< zoj-Y%sBkSWd3wSe(TpI%E__HLq(|U7j`5<2`qiW-{@c@_Eye4r9()!OFUVMHTsN3v zelodq2)qX)mKs2TzTctzWna`5p?1ScYf#jo)Fc5hA5CJyw^B?9S7`jw!=ODSb`}_| zh0_RMo*$+vbW_9j5Yw)1MuW~vi0s0Id}$B(9g=V z!u>P~4m~q+1x;%p#O`_#M^=qhFDA#W()9xGpY8xzdw8B6=_Vb!Uw-$&q}>G(Pvl5s zsQx#n>PI`^j}me(q1qO0uj&j2d#ZvEb^ks>;(?|oiL>-`Cba5Ng0^UmC;h7WHv+nZqR+OaFx()#Nqg%v0La>b~f$P zm||=B&21>Tf5D2utOL*sR%(P@RU+5xjZUus@_GAQIgm)-7lx_jJOJM)kmW8p=sSpXK)6m6axE&Jb`+BUJ_IeJH z1i|}9Bh`mpp9zCsFHOK-t)0cD0!ty*P{yX#TR7cUUGSgMMQnU@c}EwF%*ee9bwb(Zu5v)vyo%y@A! z30<|Tudza>;~^6s6`pp(;!rAt-FNaG>hqL_F=tDX{>8M7 z8HRnBzb2+wZ9EeFzy!Dp1LhiEPU~$$pkxqN$FM;~}F_^AYi_s;6F=pLfvh~#jQ)ACr zxKiBmIaJSIf=I!;0)EZiF^V-WNx+q47bLox!zh%hP0)VbjN>~S|LPe{`^*WDMdax| zyTjur(zmSkq5MC*_c#}!bJFx8tXB!eP<($Naz&jRELJBDdeFkCl5p@@U{xH)W4NzA z4syk5Bsu4T#G}7})_N=WbE<9_qsAiM(~rjuOgyRC<1JVk3FE2VI;1XDX182-Zi8FH zXkVvg4oL-nn!yW0L+8rBKDbQtMAE)seOA8Mpu*CY2R&;yI%Y5^5vYs=%HJL2SnUg2~!kdC!o3U}m`J5~$P?6nph(@_pT#al|*DeBzysCBse4NvQIw zP|Vg)a1puo&?Bw{*sS~xMG^mK%00>mP^Q#8u9|rU;XtIvu9+Xt1P(-ZVZ+#xDs?8w%@b z3#Tj>di0+(ZMk;iGHqfD&Ibtx9Ut%%xRmJ6Gf}^^8}IcIl15u+r*GeY?-#_fA=>pz zU2o6RE3$gB4-&QUqgzfBW{UKEbAD@djfl?+>!2PwMujyY#U{i@@byPq#p>Sc9ngVV zCAjh0lNH(;@qnJ{3qVoDAU7I3NyRrnBm)uS`o&DJlSABK9iwiRoK|{j7WWRKMo`oJ z*!GP(C)F4*`^z3w>#tOt@)r$*B5#IiVf^MRl3>6Q2Ut1d3Y9~(${EWPR*zpTQAAeStLBWRMs7o+|s^ZY00C;#*J zp;5&XIu|&$3?#gF5#rUmXT*MWel=`rUAbL;w>^X$a<6G4%jE6Z zSC((NA0``V$?Sd-A}Cy@$|$?AL*!j(tCkP)Q>U%(B?X4JBST^t$?ibI{a7z~B3ly# z&grbmZ)O;fsf}PubUjUXz+(qnJOj^_p0@fx+PLEN?O~^kjhu_4(@$c`6Bhi5{$Jq` z#+Nt8{?Fn4Sg(F zSE~$_s=JGrFP#S(A5aqy)IF;d;7XLSL%vlXU>Fw)2mjWFUfK2P*#-`sKD3gOV(K@O zx?b*v2$cZclUNhHCdxaBNtUQ}*HmsR0uCr|!jUeN3Ae{}5k5=>j#>9{HHWXM)EY8Y zi#9xkKU}xoaVQkG^ZEmlWGvXh0jRo9RoPM1R>{g2d-WryZ`_fByWW!Qft$r;oG zk_d%Q0Z}4dNg;#fMFehDC7j5qy)#1ZY___)pp4tZaj0*LJ9eaPlXdUoa1(A+a8I59 zr8N8q1C6&Nir(sjUo<@^xnEyZ*599-iJt^dJDLW!x$^lQOj&@f#;r`PIUHC#_&b$K zboB{V)X$-9rGi_7<9`LvbR^*AHN{SjGlQKoFOc8OkecxbRj!?g8$EqVzkb_#(NohNy=6{UecK%d;ipr|dya(A4w#a@A&!8Dqu^3B^Ho))Nm zX)dlVRUP^TDrNWnq#4`gX4+3aRI6+8`07Ww0zPK>26>u9C)#a3f(ce?NkR{%4?8A;CAw!J^g$;Htr6D|vZRX6z1o*FyUTit>YxY@pFl<8Q`f5pqz{kI zINt7Urx+7=Rpo9cegMWV{}6*w5>A1^>-Qpm>3*V3aOeztf1x+IJt0bHln7Wqtt0%? zw6aMpP~_>2*15;G`R<90dxMb5r^syA|5O^DqP>%QOU2QJcK@hqy*Z~lm$Y)9j~?m7 z%3A92Kq=k^vQh;Tc3<1I`u!fCduwFXnPzk$cwt7%=;OV@SFibX$De452B*H}sjs0i zswHP3-$S;}<4-g-pE>K;IWXZWn(AC?bmzAn7uO}js=jmo^8$!feZkkkfUr@Jtmpq= zijY-8HutxZMolWCmF@}res5N{jpm%uYXsd2R0BxmnKRJqVAoB>UBUV8&c&f+przuJ z*3AWAm>t-JmlNdB_X-D$nxT~PH|9j_xkH-)H}T~gt5ja6{F{Z67pj%$E;BnYw0>@E zDa}ewGCCZ-_DM^)f<|sz{QdhORCKD2rkx?oSZ@v~M=ksUt`p>feX93Jzvr%OzH&_N zNgn8xtLxsv`1@KsqK%dci=~SWLw#OYU%N5jJhSuoJ7DqmQ~5@Z=7Goc&u5#_m{X+q zN`$4{ck&7D`q7{;x70N_g_OhlSDuna>z*9&JvROcI*c!z;00sq6qjft4d=lnO;iiP z!Jlu8cZy6Z{2W{|l$7>p+Na{y5*qWTO&bRkVT9UnIfY0oBISy|lz|ElSW5D_a4K;J zK-VWPvTs#2Zk4-fyHFagcy_^(W@u3TMcNh?v^abl1Fci4 zAf;KgfSHh4b~*(Ryzy zOQ(0<2Ck)%c=t;M??TcIc=(UQZSQ2A#*Cd;Cqj*XB~kS4&bHcN@9ZRkyo&(eEPVVn z^hNUb&MuNbOkQx|>l($@KaP64r@t;@3~QK`^;;{b`bv9;`8V4$zhf&W+be_6?^rbb z9|&klwL4j7xe5be$Jtsxbdi_lH1(U3o_7IQdd3ug=`}FZlr(y*ew9VjRl@iGG4&o? zO}z0Iu7Zk6iHHJ%5Cs7hB_LHPQ4tXlktQlgRGLzZNXNj4NN<87QX?QDQk7mqFVc&2 z3B3hKLMTa?%-sCXIrpyn31+QXGw=H=dp~=OExK^*4OBQjXe{E#KwYN+DsXEQa8>Go z8{al^yYMoUF*FKLK)e)aJibz_XzeKUOVeO-0k+?iU*du(mkqdi#b4H}kM7LXeDc|) z81; zAuLjT_>moEU;pbc=$VEXt?H}fusO-nYAX*0CtLTD9L=of->6!Ek2Ad%F@M!1cQ?X) z%xAPGinntiFyZ!us_m;ezU2Z>j0T=raTZVj`|tsswXgkj?=C*;rR7N>ocL zW--N?T)Ue+L*9W0(;T9J=b+4~(bG)g53Da_R`c;U3K!aj`CDc%KBqVV5G0YWK0_fr zk&TLS3w3**UV$&(*?=v!K42xakTu5CcCN)cw)unt-|fdAw?f4yn|+p8JNK8@Iz)>n zS-+@?oA5mxzCw9X*m$idkUY{gQ&4fl=@{h&sqEmTYf^SCB$VrEVwpSaSU!)Qk&C&P zb*(9n<8bHCI|rloBuzK6S9K%zk6np+7p=vPp2|bFsfG8vbZy^O!3is{?oi@EuEgK6 z(9`*2#4>>cfmj9mXXk<~GrZ>zEH=F$HgdRU9#Q@-A^Ibf{RA8U7PhrU^K5Yg9$ zPWvTzL*DPt)veOQYSu?C!Li`_7MG$FlJD6QG<;UE_Q5?wt-`lq%#WjA_yuX&t)y;X29Y)F;*5CtOJnvR~2*17DLQvwweEJ|OQ~1;_5F+a4xf zy_+uIV)v=1a3tvc&j&g-H*wbC@h+ktrC)}_6YMbOS30kkp3{w0>RV5Rc|FQxpeBA& z1L)XhLrH}puNil%hmggauO}m-$&AD){l!`aaT(}FOUI2udF4z#PU8J9)?L7_ms^xiIetf5ENu!Db0zdtE= zGa;8y=NoovTs2?144HmX9xfwcIl9qupxtDj@!itF5|ARV*!899yrBQu1S|1ffLzz zw}U+5$X<@B+6lpAfYB;AHjuRF%s~x6cr~a!J0GO8{}g2#P7lFtyWb; zyrGnk-H5bOS;Zc_LUe{u#*#ejkkN{YF_oqZz{+Y>@XT~t^U(k5l+SP^CG4D2z$v@3 zp~A`>E|a9GMILkNX^fZ&t|2G$5v&kOU1|YLjSH!<#U7XLa{b2S4ry;2Z=UcIwvD`d zej?bMo*7^?7I)`sc5l;3fE<_S|>p#29K_4Y^Y zeb&}?(u}6Ee4~feZ~6|-EVG218-dlcyT;O$Ch))q1?cqfLhh6qwl#hxg}$6i&HT}f ztUA@b0L-8@&UX?%b`2_1F~z(%(TFKEu@<51>8$)3`i!EMTDA=ll(Co^FjC-!cdbz^ z+ud+CJ;Q>>tg!1r?JAW($tVqLrgsS7P^EgHlzSP&)6@cHzu zc=pOc;(Y^y8JvZ}WO2P1w(J!8aAxZX{O00lYA%7Fz%nSY+4W?WP8%)~FE&j%Q(?Ut z6H?4?{okm+Rgl%2zcmMclwn!X^h1sn&O5L@ngzAokBr{1J+Hn%pg;QORX-U83lyQ! zyh10%=w?jOw{q+&VIy38fasH~)#hWdyAk(~?l17FYKHjFyIq3^3#|$9z)R9vcWWMs z4}w4=w)O$g>Y|~zK*CypyIVT~UD0)~aGP@Xd(`vA(O7_9M32 z!nkPh#+o?VS~&qYQF#nrAc!TVz!!S&OMH(aYk|p&hoD%v-}ekI=>udf!n%~R102E> zD{d27W#lydEOI2|nhBup_b3NOFQ`lGhX%f1eb@H-G!z+?Y~>1fz1;iWR1g$$SJyi1 zb40c{wXUc3bki_x46q{xoRh>YUVghWf2o7eX6}07=gPf+cs7)#@6b&evU%#AoUd63 zFh7YB&Ixb_-2XGo*3D+UuX1>B>UHY(r~!hFne>?S>i>!dw37? z9)~{TlsYGRbDtk&AM{*%i5=?vq0h`CWD5K~Ld94Y?n6p69rk987;Y_Z9Eq4oGrsES zr0Dec?;fG6v)Z}zjER5W9-iZw`H?4#Km9yn8W)e$NP@H@--YNmchk8#*+m0AKCJ&& z2vP;v1x$Pnj5}MpB~2iA2EOE#zDev7CNSl)t`J(1Mg_Er{YzfnznQocS zx&;#F(FE8aYZq;iqP6t%HRBies}2FJ`ZU)~9f{Ux_)bDR@6H*QFa-)GBiO5;x3T&> z&WSFA6(h7g6@|drhU(pwZ!>8289a`qHE`zN%>1PQyB=aDL0rS-aP?YgpJ$8LS&~G= zV;Z^@Xe?nIQTP^2tRQ7GEy9?)o<;QdjoDQoyV8s$)TH!mcq&|Ta&sKDt#obj0nqee z{+BiEYf+}sOLgxt!3oY1*n`jjNYEN{63?~u!7~UJ@m1gKsM zvvq-l_wP-pbP`m_j@jsf8|)*d9|3l}W7p_*zdwBX2KUyv{*0lo957u#y5dCn1kzjU z%AU+DRz!=mHt|(vf2N3WH{&JamG>Qj4b0~)b*xv)=sEg&pP!#{l>W=p$sz_v-}wj6 z6U>&Mjf&Cbm2f9N{0>6ZeEJOkh%}rjLodH4`aY(M(vSy~VEq=KzFe93j7MDkrSRqgK3y?4V*B(yl7WpyQH54pn%Rn^)B-bz?^1Z-v2D#Wzxw7zxd0(v zRg#$FdtVF2hP|I1y*B<|Dh+R$s`|}=Wsr%_B2)+0JSfTAn3Xao@|LBY~wEf5NP}PDW$dQj%ZK3Mllzd{?E^SrHbJ z;dr)gFMKDV8GiZ;oL*&1hyGNF+e7AH=`2Pb=Pz#4)zP(sS;Y=qWL&PrPDoAwt}I^| z^<2wuDz1#TU}%h0t~L31-hQ*Yg23=!zr_2%H6IGO@cJy* z#zFe;U(=F2wWext9m?vO%HMcry4|r>7i#G6N#ZZQvVQqJom}pXfan8-Rh|O6<4KzK z>;N8#w)wZdT6vHN-*`!9?hB(~-Ha1qI3F{}%pq47LUp5Gw+SE<`%_#$hMQO~U39E7AE%G1yqpeqIS08ziNh=ZU)f^q z;dYzHs>@Q6ViWzg$7R32VQuNRkBzB~BYJy7_ZhuAV107)u3Fg3qcXKYTNZ6C+Q1kj@2sRkXNv{(qtOyS%t}n=TcgCio*b0R}%&sk1i0FUH69gT%?nQR~9NBZ{Mia z9fhrsEGWLrkf^K{_0sXNyhdAb=O1VAUt_D++n^KHAUFB|-#^&yPu03PDdQJRr(wnA z`iKu$edhm^sv*^vU+7yki6m6jO6s(GPo=JLFqu$B@?WsSrRLD@AZtgXdGGSr@LlI5 zQO;cHZSkw?sc=R!rgF8R zf#o^HBv!+}$h{2wbg-w(e!ROCe^H8M?0T4HU=Sr)yB>icrPevkfp`?Y_g z;KMel~|EoA*rT=)9hBi8b-ShY?Kly=>TLzg`uzCs65W!6V zg>K$^2sp$5FGfrkKE@(ugJ%$Id$bJh%7Vc3p_<;iDZYJuG%H5HLJ#e)68wrT#O9)TAf6 z*N!Mqgta=6Q?@+O(I~wD!J7|`(C42;wu^6EIjpj`(w|&^=guNqd;(+?B*8lHarlAP zyFF~Vk#p}6j|eEBpw{-?l>|7F9?m6ZIn%mk3(G=#!cJ_ly(xEaE%@DnG+vNB;%Gw0 z(||kRL6Q4-7w@4=1Ok{nUWOoUryD+!r73q42Fn-)bnNw(JK=txcCjV~J|!n%AuhOy>y0SF$%_79@S)Qyz3$v~{f>`KG!XgzeKVLo(VFxx~*ya>VL4t264i z`YYl$N!V*LIq`%OC9+W2zp?}ozXyl_G_K<_S1h+$)vYqES4I;SwzPf_iGxex6#VDJ zBGGBs8@2CI>3td-o-|0eMwEi}AbNB)PN=RVg%G!7h^iVGz=GV%8b&C|Ja2pzOAV!W zl#fERXTFNcL!9p_l5= zDFM-uHE?PB9+h@l^y@xO38xe~!k*{Zm~fOL6)Ef{#~>>(qWxIHg%q=@(9_~Vc$S44 zz%HK%X|2N8>x{SSX0#-*>jYud)VCMBSc4{sS8aW-yX{>_W!yusPgAuWbNDm(cX-7PShuyaNigLHa?x)6kzAjbY=4L!`1JUD%NN_2;f}h8eVL<2kINe1 zVv~;fw~IZ#9ms|YC!SO~ntiLq2OK$!dOrF$BRmTrsq(z@>hB^+u5f}c*P~FsPMNUzcsR{5$cA_lxa4H%_sGe#iEJ-$Y zG3_3UA28;71TU}cIon8AX1LI@lW{T=5HF?u*z zwK4^bo=Av|+LO4gZq7~y-5g~hPo;a(yVQ*SrX~Yt<>2T2?97-Ki(ph zcmDo3Gl4&o3@%PF|IDbWaT+%AjdNYJ@bBWorX@+1gT+>5*U7Q)5I^%mvDN=j7LW6* zRXrqTAFOwn6Y)0@^k2{2VpxV^E9ytrw8h^U^OR_xL3r*AetyN0j&4!|2ttqUIca`7 z8&UDmz3@TR@vLk4?|M!uncb;xS=pp#dxqhwDLE%Z+|8<1OXMPp!EbINl3oE>psq~f zk6Vy2<{pR)xEh&ryisn?YjK&|ZYg^*@A0^b9V)&MuN)U-;dH`vL+lP4JC8M9o-O{O0$N{CgVWM(*_jwab7x&Uk0

7KVCcBq*0 zLgm^|@;JF-v{kE?h#eVe;XQa=ep)air0GMVn!}@G%4gMK4V+%Wi$h|D%um zRwGLImr)DztpSycw>)^V8eI-b1SJnW>kdq(A@%9?W{v-4W~gRvz1pgor$ViWsU^#)<(H1*^I zIL(Ft*GqEOY;G42I>_kPHqCIu_sMW<(1VrS;`=`Er6*}fSk!i(J$Vs+vw17^GXSP-fP~RMxc9Ly$|I?fs1?m zrtdrF9z@*ATirkgeYvN6g?*WiR0+aXs#jL!BhOku0q73<*HG63kNhcadz4ms^=g@1 zerVy0xze4DcW+PmDjdO%>y%IBoW>&-FwWh%6Fx8Y`tfw~H}~DW!ZGVVrDxb9|MJEY^L@9(FD*~4=4*>@e>S};eL_K7gNydH z=;IyXccY&LoTkNFDO;Wj4Jg<1&D)+s)6YCPHGMGR(~|4OI3-ce_QH>+Tuy!eQ{6m4IdLm9 zLI1O0+UOWKs~PB*Z6L($jPBm zH&I}Z7>u7GB9caDKhHkH{k34HgTW20x2Ro|0HtZg9};h*LCHmc8<`tM7`s^Nu;6oc zpi!FBmEW-&&YZ<-sp4cyR@`Cb_n}=a7A*+<@h#b{6E@VV^0P~qZOX$Pha;Zy%dG+d zok4Dv&seCEk{-KqHBhL}xX2U1w)g;K(hQYGc1|pIK0r zo3KdXHeqR;u5kg1GWYYLNiv=Y8%?T!S+$!Pr$5mMthHfg$M8d^=5-cXZWfzT$%d;c z!p={-)|96`sjd$$5453~G*yFFSLMa3%9VUZf6$YjM?Ft46aoYD$noM1$B|iq1rKz~ zP56SWXAuXV)k(CvBmKsXw_Z8Afy9MNYiWEeeV%wgQ#2XapKO|RGHSo*?VRWz*PhQ& zwBV=g(Qxg&IyeSL{e$1&+;-?)Kb7PnxB7MXMjCo5=K)q>Lem7D_Y7a$T|*5Xp6l<= zGWs2sj6f1}(9}2pxu$rixByke`z`G56NH z2vUwxNB=?rZD%DpBsmt3?==oKy2<`8x-W2?5plQEP4Vq^A*fBr?mZT1bHqm=JycL2 z1t~w)(taja_uHLEMpv0vL(8Uq8twaHV)oI5*m&RoMpMAyNoe#tQ)7dbyV9CR%{RR7 zXl%YYQRu-$wR|cP2OWKS1D(!gBn60#-^DfQ1zoTj3X1v@|LjOhe{7h)-Ve4LCVd0> zqlBTV#SR)MSRDtV-5}&;xC?%*dnJ;Xtlvy0&NiCU+ppUyw9t`P>|Wdb^$KHC!OI5V zXSpW|XX<|W*i7ry79|6n1<(1lOOnR_{x~bg(k=BGTn}r^@Y7px`(iv@8M{S%T56Z5 z2R{I%)g3=!Gi}FVy7Z7<8v?!pMz37Vfa$9Eabdb~Ffpe`-0cMk5Qlrv-u5(3pHm}3 zQ2**%ODF>TCW0q1P|;V8<^$&X7*2aO2yz+Ab-+V{0XKs+hyaYF~)?arVA-J_7#%F~XS7 z*fqGHO_(`bYP-zBT9p;*@$H7iU)k*)BOQeE(rH9rx34I7wmNyz&Syi#$<2*k10N5W zg!@glj-r>H%ac(J{QwUq@=d3S^FbZSFkht4c86z&Oi0V&ZieUYpu_GXri8r2s||i(w*S*FEXZGyBm7{~ zsD@Y_PwQndW#<&g;XQ0sj6T$W%?X(^wO4ts<-**r&4^ann!aey`W!cSiGkW^MX_3PfiH2D#LAK4l8v+d>}I3+tMEU?(thQ&Xf^A?Q&wQTe2>QO2R zz8KE0+r%!z-cV(@0@mtSJMo)RsvSK7V6pf&RvI2)El{(L?I8m-{V!OW>4d3?C__Jm zP6=pu8Ycf03a{=aUO2hULgKxm2q|Nl)9|;UN3h2(JCS z06nL(4i^9$_?4>Cqa?Ku?2ivoAou>y{g;JmmEn#wKe*x!WKudA3BPzoBQRU(hyu)p zg?rbo5tKndcmR<0qWdNo{QCir*!Tw+2eZZQJf3mQV zZ=V3>N+8sLSiHZ1k9cYl$rpDIsc`7FWoEz5uHn3v-if~pZhSQ!QIvQ8qQ?G! z<#n!R{U%Rp1d^(U5!r@|h@Z)fPi@>wY=PvUlH03cM9F5~Ftd0|RPWP+o4)oIC%21* zK;_PZJfIn5IM5_O>EH8N{Yk_1 z1<|!bm@_1kwWG5w*fVdrF|&%`v!l8+^mCI($SaZ22ImcTMZI4v{hd|JhZS+jSJ;zA zBB;wHWfR%>PQDgLRgF!*Up$F)PkVe4sZh7Y&ROcK62M$fwOkR$ur}ZMbN2vhkqx~a z;5cB`1@L0@K%+<+9hGukRUI}DM~ZI_hY_BQ7Q{!*-v-H>1_m5HE}-7zOyUPW$VFoL zA6R6MQzZ%~H)BPI%6NsKjkPapYYnefzrea^bvVeXn!!SK5zgDxc+#!#=@-d_9gXd; z!aMO&kc#Tg-nT!uSJA|LLOQ8~2p_~h_M*~>o6NE>&1AV}IL)fb3|5AE`ku*0Ab}H<%FY@<$7N60)m&EXlZw?dF`hIiC0kqP*(O}jp zR}cOEQI8OhBgE?-a&sT$|9?!0*rRFSr+3dPZE&1wr6UQS)#@6zVJ>+A9RLDar79iT!a=2{xCQ44K=G7 zfrewmLA67ki+B&xdNuPwJv}QX`{<$|l5@>fM zH|1r_*DqhbO#-u@_*RZRnsGe4DYn5zG~|Zq&&YbDX+}~*&i++)e5Isbr*po2P@RUN ztx||Sb%y&L8A7UAEV+QAPv) z24%!P1O6S6d3|;^ZscfpKE_xnO$AJeLocC&bwyvpWZ zW4VcE_soYwzv%TH$Eoccpla`49Cgq5?a@7cd?)7#$41~f9@waI6GQ#C0W?(OzckLs}-15PLiP&+-5ff5DnwaSYW^u zS(cCgiYjXpJC5rHntjc7FxaQ1_Ou>IV6%h)w03CKFkG?SsJSImRyzi_wg3-t-V-!w z-yxC5rCL={JM+;b#e)p#B?famnm9v43uF|$#%YlWmSY4Ms1Uyn1c=`>r;Z2Vy`Iw$ zTFmNg-q8qORY0%26}BG6yS!Y5TBleL*%DYLIl)EL!`c9(%6bI5*Q(t+yF^jO*Baz% zU-W#Sr?g}ejugw(?c$ymMeKP+a(@r&gZ-SfYu6W_v8cPsMFCe9D`u$ce9ePcAi}7i; zP6&j%CZ}?6Jq|6lH=f*>x*%~+ef^=Zdc;Y7VYa4k@U)iL&{mh#T`je7(vji%bp&JU zTK68gaIPu@L0|EiP1%i$i1QjS=L-ve`?q&YTiti4X@59rxz zQr5O%14dU_+QoeIW_>(6gJ2TYE62iwNwqge9$Hfy*-o;ASptKdMOW3V&zkLbkAM+G zcy6Jm`UUiLby16v+=cJeu175)MAwuO%Tb>6p2lnfUAABX{H&E!U{zhie7Hk3$>z~I z0^B?Mtb?03ZWQEt;i2QcCZsz7!=n~jzqh>K89uLNXw)0}QXw<8KLP8BD_#`$XH!2v zFi;RMPW29UKA<>GkJ*bYBTHu}pF8D%-{K5=G7kt168>V^ze(k1{>oI55A( z&*Mg-Bhl5ZEku=fNjqqHM<}Bx8diW5A65^62)1;I8X5(0?Z!}pFFPl!!4jfXf;_A< zIyw1vHs3mczdFvA-*+(@7vZ~|UjVo4z@Ozm?sBc6XFqikCc0f{1MAdfMOfuo!w%?} zD?jK&AIrFNHz|w3#nYJn_2J>7EQe6cN+fDX&n@;u-v6G=S6NNC{+oQW|8?`sgY+AV zrshV!>!!KSeLR?nY(E+5UnN3Ayp--TBu$mQyR~$%RaSnRILG*`rq+qmV~3H7 zb^ZF^yk6bnh^>t6@;)FG`%zky)w?G{@$Wq@#2G88r^b}`S}pZ^t0-M^p~^UVigYHA zh4s{XgL4C|-zmyA_W_j;)vB7$RfKWJ7k%yvuueT1?4loe;kxpA4?4IHyY(eeZH=pM z)jawBBIbKBV<-55kl&RwhjF;Q`m$d)u)pp+I}w@_FI>Pt+0Dx2N8Y!9IWd*|MQ5uW zl1g^i(EJJc{Cy&RZ3VNAP7AQ@3**pWq!fX(vYLzf;U>h_@HeQAUy z%+fCrHyfjYfg7H-5MzO8PnF_-2sNMxuW2UCcQNOIsd@Zl^_;)gI5~xrT|;gq;0nBk zz=C}YQXyfZHohgG_BihTAjTKgS0z$u*b$9~4kXOTS4#v#c7HfRKMxkHVoCueF5~^iF0{ z)_01tcwgB+KcZ-5a0C}6A$g5uZwtNQ%2^BDe~M?M4Awf8iu5IIFCNljj%X*Lx8Z6z zj=;obChX^HLUq9Td4%*A4L4+c3~Jcw*jQWL z1yy(cFxA-?%n;^6VI!3wi+f-18TDZY?b<_9=>}F`G>5m84i=?ufw~-V0KIz^w}ot&XcQe&Syd79Dnfy&qV9xP??7xNlzR)J1SUqP0V4 zK`?ums1rvcw4kLYg)@jB{<|#Hw-Sy#seQlCG1>s5820zYNc`o4<6WSa!l7$aal%Hl zF;8h>VTz#e;RYWlLxBjNb9`08?_yDDWNk+I={%&2>%Dn`eMGC39qdF8E==Six1$bD zeB|%V?yS%MV_$uDK^+`yKHcU2FIMPXV>WNh{ex;~3W9&-O`A;B*hyCL*3Twgp6@XR z*X#y`O5!B<)jGV6X)qsXt~?!k=a&A@ZLEG?6OXuTQWxiaVLSOE4!+u)4@r~(fSaqh z+1Y+3SZK&am!Ob$CVTY7EiE|kz*Sp|Z`!91)~daB;>H{@OZc~WL=`E&W+d(^y+BCrO%RiTl3aZkCoCZ@{ESek3@gl#hCmC(GbocU(iPXo*9CX7 zSN;vHX@k7)QaJ6G(HiwtYv|Y0VFfQeY1l?7z?ljJP4~Pz;Sz~-D95{ot^OYRG)z3s zBpO&NS#RLr$Il_5ux|?zG&r5Bww$4AMP1%D_ebK`PY?%7#@*nx9e9)({u{lOi5$lf z#LsUB2CHct1G~+E*R=18etxv0zWGzSsa{WL>#eD_69^e;!~nEz0l3qm@T`8T3A&%) zZ)=#L$-FtnYzRFHMnm(CDrm}NJl1RcoEN^Yv4ueWiyWz@Tze@3-pgCL<}8Q?{~{-< z*YGvojhId|MgkGHzTgRAF{O+vHMU!#R&@G;ek#iw=-5D!6gT~r6?--;oOiJmI#FCX zfbKS7&cF9@Z^HTJRm^zE}fyRj+X7=G^2V`16%-pc#Vavg$WN_cepm^ zr2&jee%!XLgmH_<-HJ9Q`aK#A?Ca%Pe@7*dXay&m^a{Nhk2$=d>+zx6=-9(&+jVQy z0L{;f(fgYvBJ@+>BGBFtnttmubIqK;b~a=>G};;*CViVBSi_^;u-p_O8MB3Nd;Z8C z8pxjc($`KS%wU)H`?YIiGBDxjSzkzJ>hwjb|Hi#{Revf>*~RzfI1&?vS{T|H<3V15 zG98F~I(b@~HosKfQe|ob`$cKb|gx)E(P<*F);? zZSh;@aL(;lBVy2Mq38Id6uP-?-S{wo@HD{`>%6>9Y!60dn>2k&q-Z~umK^%=tM~y|a!JkRy*-bGn^WhV(el5-LhBuAqedLBGnZ4$ix? zZy<__@v)<)H4lr1!iwDZ7t0;T#{8h;{~RB{nlBAjnyHJACI%9#+E}gH1jxA|lWNQK z81t;&EGwRf+JOxT)C^HAQe>I<&O9p`UCik4St`z%K()f#!?-835|kG%eEtZ8@M8p* zX_@m$A$#o)ZTxIl9Ma4~iaSAZZF&5b2k*SHvPM=-fU|Se4evw_)q2> zi9XC5Q<bf^$?Fo>i*7?h zC7=AC%KD^4oyw&@{|(7TbxvKPv>jK}JB$1dN}P+)xDzUMIq1tRjpQdE3UACze^L?{ z7LJ;0e|WInNH&x#c4IT>5Ta7F{z#g>xrk|C^xYcpvfOLCD1>YFP(btdqf9>VcIuPR zsjt@!_`wF1#6gFz0^pP1-hl#gpWsk7ujr|NkE>yr0%zmZYjIZlF0TFwSt#kfQfsRx zb*^V@I851o;_iD}t^x~f zA$@CJ%3nR0EK*fVM-NaW{ni|I$}M3g_RGtYRnYJ(dO+%PcqdGLGiqNtxe{KBP7l6_ zpbo#x&66a`;HfM);2XX>RQ(70BQ7S0<|W|a|Jb;zXn;1J)Ldj z43c{d!d{NJvD?dwv<)HmA3#nH** zFyS%jWAH#n!}uuXTZwi>2rSf0Xk!ve89iSN77=$nX@=t{g-X4=1Fy|pAfZ}&d3l~= z_0e>4qpsC#shWGmMb3;QcKAuBJ8PGGUaP4DlyT-8AN=*|`B&$j`~g_XFWlsP&a{BR zxOU2R=#g{e+hE*2pWGh8y+RFGq}G1`cKG;jkHb_Q`aG;tyMWmf^=8F#2AhI*4QLoB zANv%cEnJC$8#w+ncM}t`Z8v`W-~KlFd`8572cFTsnYYqLy?e=gLR+-zGT9G54Q~oO zG|=$k_UL%e@j~L70`j^~1%f-9$GUegtK6zlS3!qoZOzuf0vpjJ6#c{b{^L3$b}(K5 zZrVarqu12P*lvOF{Qe0Z2B(ja={Rr{?d(mTIsI6qcAq!mR_K?P^7Ys6ykb)TLG%I4 zp{I?yC0jxHy?%R;-!mx9i~IQP!W_WXwS_nR13?sit*e`fjOa_x)Bcp~8Jfj^VSz%Q z=1{@W-QsxYTq~wDzXkrj0H3EOROfr0e|ZWLvr!`3K{B?#pl=;g;FF8{ZCTKpdk8A@ z1MYX|*CxH8Z{Ih4RZ+)+PqOBRqQNMHlivo3SjO;WhRbUaUgl|7;NWa1ozh37btI98 z>`#>LV#68o5Fw){@eOgDSi_((JF8H@oT~*fDjbG*@-JnMe%dA6^e&_WwQHJ5z=lEe zOK8oUjRP3B^*rtb55;esq8Oo9nbI}RpOGO2&aj2ZYoVS0)~y9Ett!3Rwn_LmPiVRj zBi?C-e|#IFJ!)O-({En%WQ^wy4`Wuls)peJCdX0nyC`m8R78h1$AU%J*%4bvd!Em~ z{ANnXkop|lw}T&gWdT@KR(hp;1fKlyr^mOSQ&flNf}`(xl^gADErMKEr)g__Ydls{ zk~URO%o^90A?>^lk=o}{m4Q8N?mYzgyMKUp(`wl*p1N5{07rt0O(%^Y2weU*@f^Uu$s>5rPanR!2eZy@p$T|6d4t^e!uDI`w#hbK@h(pL} z&Km_`DR0hoen_$`-9i5_vT-E?F}nY=r0VA{r{${xBsV0!IJ>c&-F@wqpp*bCLcf34 zaz0R>i7Gx-+aM5Br&hDt- zgZ@3U>P7hEbjpn`VcMBRkAGldcYP$89y^0yJey;4`)jINlHMs-&;vl#8MZa3J?FMrET&B~E96lgcYdimQn;`UF09pjOGjXXD z-pOfQ*kKk;aU8n|I{FT?%0_W_0QYV7*z^sJ#LT@~+qWIbw3{khDq>B7$*7g5(;q7p zr)rp6a42e`Y?^k++iOR}_rNJ)qQ(4|E!ZL!fCUiC&aDV%KQpZ6!nLuatrHrCX%^?P%8!%|V@_{ZE$C3ScN3-8>5h}|-FdLbVvs+d*U;4({u>Qu zg#+`*h2u4`l7W4fpxjw{^Y|o~wHs8A55)3!z-Y>&yN4p<*A1;;ddu*U)Xq?3R8Y$pal%( z1#P4&Kk(^oKI!>?Spa8>9Q+);bdd+U%J6}?v=8?X>VX(WXpeDAmX6Wm1U|y?W3X5R zO-3%KfN08et*O7|5qom{*+NtNV_rfF_c(5fqEm{dIW3Q;i=#o(IFj0TgppNV{YJdDEXv~T76qJiRFH{2~3eb~bow6_SCA)ah zpMO*!+UC3vW@~CTslew3-Z3Q48_t$Y`_vryW)pgoI+C7G7LPs;@<;|fkRwNd47>Tnc+>LDr@_guj> z_c@xY{BwqyAFBLMVdSmzRr9_YswlWbl4Ix9zT_KifXtpVTroGA&h=P}@ydTb^iJ`v z{ZT!~w18_b{EG}@_uf9Fa8h<5 ztLo$5Z6sjdUPMJ8$2y|&7 zJRRV?G7iP=UIRQlW#WWi>6p=IdBpED)*Q2iyMnqHVV2|UfT@* zr*V-H_orT^G|4>wqAF1+xK{>Y*`};mzsX;4rUiJ=@I^79O(L~B7(1sCGqkU!g#Yu` zfuox*MwZ`wlt4%bO9g2cQ*;8jy=8=3^lrNO<285%oS%MZjfl2v)U`fwec*N%NibfV z$Q%H81L4!dPd>cZYh1;9YXs8n@M!L##(lk}oZoM{NlzaKT3|DhD56r$i&zdEKxzwv`6WOVyy zNun}1RawKpu0Q?-FJrAku*Y(8-J5NbX=|GO0S|1kC5fmHwhA817(WMqpYGka${$&QQ=LdS~i z?BsB=H(A*`Glgv8*eiRFWbbu2#yK44eNUf$-+S+$j{jcob6)S~^D)m4krKxS^f@&Z z-(cZ9UaxBPS5~zEhv*MUf3eHzh`+4TV?A*aCR}IIx-ck9I?c!7`@Q|XnbM3$x>&miaDmL=E{XU_LK>U-{iIvq_1b-O`KKe$#a z&Pl)=&&2eL;>)5zKPXB+Nn}|hI|0g$*aDr3EZo>k(iTdL7W7wg=Evf}x^O`yu0T~U z|8Pzn;2LI%yRZb8u6_(@W4>+`J@0!S8ykuWL11nsinUAjGbtvc$1Yfh0P zJqxO2!^+^6bie6Mse*&oyX8An6C7JhcZ&R`LpR2|UymMvck3`9`4+0UK45TuBd2uu z_@n1|v-`D_H}%nfIx*Y(0mt-#wxR}|qZ9#=Pnh~9<8^+oh$@TFrrH-X$hWPyy|5q4 zXIrCsQahg~@FX+$5e4NC>utHOifv6plRIypj;g&yBC9_5P_iMu*>E%7RT?^`5}Ugf zy?y&b%68fp;@WLYvE0Q{P`>DEl(nLblF+*N<4*0W2Yf}N2f_{9yQhA&7prWmBM(HZ z2J(wKxqO_!OL?+P)iy>uw4}x@zl&p-Hz9Wids8E)$_L?ZJSi%~$GO_qzO^eTyy}k5 zTX^13J^1b}MDrn~W=#aRg&zp=?w}pf0-DjPvaBQ6p$c;|g@uI-G=i zN-PBDuwSNQXn2<`tCB-b+xLaJg}zqKx~WxVeZ;; z^`b|27rR+mj)ncP_XD{{%${BwpweP~j$1jFuOZbahmsSfU(^-tbf$x_vHMFR_9NCi z`{}Ugyx_J$fG+%D{a94?4w543%^`5NbuudQz3g)9JM7da6|27l7YVBn^Z#a!OG2ge z+=;ZXM<3MI2>fJ6*#dM9a6bQt?^bf4=5STK0k`)uPev2sJ6nH%_I^ko2diP)w8H`i zZ!LKsnoYaVca3io@p=vj98chDyi&o3y%nJ;%W7-i8qrhdZ0Q0lFWQ^|&c9jfS^dXNc5Z-jEG6~FlmMR{Gkv1DEUR@SllmA&|jLgfKi z)$I{Vkic7FAW9QM6r9{%R>At_ty(0wYhnrQXdk_yWo0=TC0^3~2T zO@uGDTOtGIkSoAG;+?=EQnt3TuZEiS4XlvTK0}AejXKOfG(#} z-V;@ry*@4%bjCeL)H}X+bVf(1g()f6mO3o&9s0XX0>6P_*hwpgilHa=s$B7*^jUss z$`n@`RspK1cbqhZhFq5GXX(iT-xmNyG$ao6FtZnIwT;?>45c~o17#>tSm7`6`$UB& zBl1~>2sSWyuUXLr<=#HQJuUo_UbMW?p3OtqXf*cw9u3x zc%{{UHzP9giL=bso6|}!rRCSLxI!OOseLv|Wn|h>)V2*bvu6@Mdo#P|BrSxK`)#DF z_2la9J5aG|8H(lma$(zT47A}=gaLI4?^<<-_{tn6gEdXlLr4UUvq;i26t17SBW zjC~L6Iq!UxiYBv??YhgCszcsngPP`PN-oN_pD~Iks6#{%_;S}N(juO#LC>soJmcbi zhBcH-?C~ze_M`~eXa1yVeZI2^l10(cioWk^?FN&!fxhLHesMOUpoB{uq`Vq}m24jz zU!C;|onXQQXSpy+V*Yh2qBe+enITk|pVxOZED;GtwCMl*ZhswvLXzizB3lF^h8lne zk%@m`Kl|+lUfx}zxlV*!{2AHmGO+lWD74r|`}?bdrw0x%Ho@KQddM7H!C}m0j_>p!jAVNYZaLNqar3W2#9yd$%{&`bYyaO4}+@;`A;Q zB1DvGb*Gd)_xJz3E$TRk35kF2@Byh7)q_PC0Ofg5Q&voOEDat!qaFYx2FL z{9__uYj(GXv3S4qi^Z*hFdWW{hd7~;@aN-LhOu;RlZX)rwH&`-Lla7 zJPvBFDIV;0vC?r{c3(3?%ZFNmM^T$DG)1=?;8(pP?qHGqOBbRhWp+g_3=Z z8jYkaJgvu&xzRc9L?-R3S9DuSdT4D%O5-vSN#Ql$SFL=9V4+%dcl--+Fot z51NI60~I~TNiV4W4A$zF$6JDPu(G~s0^MK^g>Pi&}`a{t*h}P zPRxxEVyi*e_jiIPM*FUvk}vE1v7*Y4pI?B8;~v*L9r%1(d8mS8w~E?G1f`7E#2->; zp{`*WSYjEr!Vi&qyVsED?p~@Vzod|SFEJOJFv6GELX7Iq!Qv@*UEWQQd~$hyr{|A} zn#aJd_#d(9$V)WsVxw=YiAh+_-AtH?&u)#G@@zbe%>+xkN8`U+UEeLX`}c{thd;T{ zyO2tiar`UTSl-_ZFGe{*po-sRbh{1KwAj1sUb3_A1VMJxHEtwj>bv2E`NSuGUMHd$ zFXgizL|h{TRQVy%9&HsLRwGnF31aD#sELx_UM}(VJroWBt~(XGxV`Z6PC(R5 z{#Scq2u1cT9i3;nEQPI__NaX4E3%4b_xa_zOY^w5BVhrrCH&LGy4!7NWM9vH7Rpo- zW;YM_Ld9KhDDn34^>CmU2?8ijSppy@40c0isJxp@0kH4KacWWwi4zi%03Q7FI`n$# zmi6`2s|f~&J@{Lz>zFHT-fjGIpaS}5Ed$3aaA7W+Xysdd)&q*Ya$t>MZLVamabH|V zOd%31kxK(RTR>L~*=}JwTWfG(zlFzjz#sta)4Zaw-BKR}oKPbeU(&Z1uU2_^_^|^5 z=RNQfvacEUBBc%DBH_nXY#VQM#Bb)D2xf_IJ`a)u+=5=+A~lO~!aR6BW^~(Qd9W!! z;9BAaOGlUl(uH@<6YHac>2t1t{}62G@%%erJYXGN?B6m!taQcw^%1X?Ln@d}B$Ooj zp2t1AVb9kFtP_2B5T&y$%TJj`#_Uw_qN4&#>>}+)OU^;Jm3FgH#C(ZFbh1VsQYl~? z*ah0WZ>VBwy?Stf0;CzBrkM^Mr~#C~E_K_{S8;@I)bwYv6+O!2&T~vPs zPjC;54GsA#xPO$4ux-3;tXg;PP_}EKRPYt&XJM^Sw#Pl{ROA8V)^VextfqZmkJyuL zTCjdf)9KW%Q3BqON*i~)!S;wi?5+#)IUW~44ELK0S?|=* zeCayRA$+T>#fYk2G2>Oeb*_V!x4PYsq!g) zjBMnWT{moTJYCe{5RefGwApU{G*ZFzUNT-Rksbk7K-vLVzS0V3Zo3qPyIe(EEu6F$ zT+yUyWCGhBx=v;G8O;L zrhM5RW_hK>ih;9QfgKuZ!9c~l2i|Hvfg<1(*R(U;IZ?^1O(jnai^0@oApdOb$M_-DI69Y}uf_41lF zhu%vs_SSXG%zN6NluQ;g$HWiXXAAx-GQK48b1fUN&iVwzH#Apzb@%9-Hfy|=9g%~4 zl$~FvHsszAys9I7lH6T&OJxnVfE((1FF(_{`AG+dw`K><# zF#4IOK#>2I=I*={Kq=%u{X&PQ%~j|FbfNFC{xgvLe7WG|buifedJf_GpTs1E@Dxm+ z9W~TBOcCHKed_^YQTWIRm1*;_tBamIOsZZYtYKV(PFBn5P;w!wFE>VkdN%P+f5fv& zZI3fXm|CrD`(o(Q4&ObG4VU}h9v_^ggg+VO#pY}N_=;+;z7JwrHasa1i0pu|y%LoD zV)po#P9t^X*w1L=A$BYOJu9^!GxhJ2whF@3aTC60-M0(+nOfCrsk!8Tl$4H0Q;nRO zScN|GrgMED|Lg`a8((7JF^52&dnDY^4%H(yiR~PW(gedaipv`@|i9|9CgfdghSM zxM5Aej6W-PF=LJNeNE#C-KB2Gz8m?oO{o!RIC5f6UCa&(gIm-RntH2~NE@t!bE$V|OBVL@G zHpdMrK?-oY5Qc8WLNX|F)cmL8jF;+?diL8I4Z}x5dFZ$ip|&+IL6-T4(06=+%+H+b zL&$c>{gEILCEVI;buTQY#wXUra#l(6M*a7)F$ibKfv}5C3X0)K{^;FZklV6e*u4=j z56S160z`YJqs$*zMr9yO?-+#I+jHq!s&B7d!cq1yXT`~NwZI>%3lOf#)I9>Dik+yq zimMv|+moffD@8&QuF*ELH|m|&WB>|AREMZ_TuyMPOY_J&Mur*?-Bj&{7Y)|+W(tMH z!l~cJ8nFzY1qmW2po_KLMw`B^G_Ox^b~gqRXjr`e7{&NG z%bz%dNY7U$^z!8hhrD4Aj3_0)8fCK40d#~pg1_`aTfaDmDoG48Lt8j#Kd&Lw&mT3d z!jEyKnz3&juf3e=6$jjpiUj(rnP5XL1mZ1-|GDw4l<7poV+I*(!#ZY0QcA4{Nml zG*_#Pr1Bo3(>^B3u(Q=jYlvRniqq9|0mI}^-uvGGmdV<7Px8M9MX&r3ncg|SB~A8x zl2bPVd}b&iay#B){oM$ATbOJT%C_nKnnZ}DxJ1O$Rz6~CAAn5rtJ!LSp=O^Evnibc z%T@lJ&Ru0n6?kv&_hq}BYRftD;+^l*`yHx2yKk{K%H_8vOSI zO&8q~Y6zBy=mzsdiynF8ij*XurT_}!@+a$`L*nF)fk0I0S}WDC^TTdyf#dtl^0q2w zjIy1o@tQwiLhF~+1-s7ZI3Xy{5KLUtWR(|-a)!SDq#&O@?e-WqB`^KKkU<3{UE*I$ zEnYT9T)A|?x*!hbq)?aRbNV6bCPPhNPMf#x{F%Hd2v9y{vu9h{0!#g=K^etU1&7Aj6Ed7)toWjNoPe4$JUPSKSFL2bz~+~^)6)KZG&LXoX%*D*XL>dlRiQb(W}TDzFlGH5p*}_^+z8gT8@;WaSsjBJ+iFLjOd9^FH)F6 zcYe7le-^0uFY&_qp|HSs8PJzsKq-nUCuUHTYb6w@qW)6~cM}C$(Zr@ZAbGcakDY>p zlg!1Tp7jW(qOJ<1mJ5hTHgOs83R_7&{Du>3urqC<}OoW<50c~;Uxa7?`!}e9Id+K+b?g$l!;=Q$og%={XJ|Dpsqyg#! z$=z|-ix4kKd$j{@Ai`Zdd!D7JJJJY-?OY{L+dejrE|@u$2c8)#a$%oW0D1_BMfj64 zRxQ&Xj@?TSr_co-Xkfk59eKeH-Qc9}y*a{2j@;8O3}c_-1g0~{N!V~*We*8zVvyep z0!)x`_qPf8G!C+0x!rIw5J!*h6lOjo=aK=`@$c{z@mYz%1R7y6f9W6-itxC?2y51n z)Af~4#gDpKRNpZ&5Hx;}Uq&xlBa|&IiW>BvKD;r@W>;AktM12p@8IT(2FqWZQ%t<- zuU0f>$yl7UxNPx*o{>Xqzh*>47>^RmweY@Lc?pt~b>jH5XR+dhS$8+5h_2sNNhmy2 zM*ISpK@2EnlP<8G1(ylZV2#*3)CIrO2O9(07Jh;9Vi`W7VsH zc9Yfn{<1V%OVz}DG39$v{(YPbb45_r_i(z-DUVkpc02J5*CxwJ*Y`i*~f)-$nM z4v(Q{G>sX={xb#X#XiZ7E_Ph4bi%EF<}^2l?X_&5$#_eB3tDdqO^%SHrv~|a%*j>q zO8CJU876#M$Wo@MBu_AQbCCnhpx~ESMw7UXrp-i~ypX;f>bM$G^4)?R@A!phuS>;P zDr|!LM-+#2(4_W@uiary2#|*U@=fqm#?5F3(fe7Beco4b`BulxX4L%tblh@7;#UxI zl{)pumbCIghJk`|1jkiGil^hi+Nz7Hr!MZGF&YpgKnG2-W_bXU(rTmx3b%5Bk7uZw zHy3RcB}%eQLQ?X4j028X`kgJv8XNYW9=>Sc=BLrYH!}>iK=hf!A-oFEtS7j@D_j)Z zAzX{q~;BM5r{x36omB(J}7freXk1t3i;=Kb4(Qt`n23)v=HV4lTxo||yKp^Xf8xYJg)ES!yb~sR5@=^i6s+xOzB*EwsYaCn4!YCMYJGB}wEqlc zSuWcpdq~xqWJG5Ev*a@h=hVIt?-3zzi^Ui80R@W8AStP_wjhCo%4!lChz|(JEA-a#y#khcXqt6n)Rn${dSAwmP;F?Xa zX15WA(JI@*F+GS08~4~wjVWJQ7e1NofvKt^;TQaj?YyOZLJAPgr{W0Z1us2sEw*}_Ccs0HTj_yJrd^2 zS>0cH>J|cf2Pl$ncBD|Anw!iK_*1Wm_5e3bYnzpVm$0mL9?>8EA|UH*e<>CW6)B!7 zJ`F{9wbbxw_orr`hO5z+mXt1GPafTKr%aYy^!&-yPf8i_zzq^~uw2o}d}mFy#5EQ!4gw9FOjK(*VrnSDCrr5iX8$Fq7VQ0VAu|MjSz z#NcG&imc&Ua3lPqV51+Z66Zj&^PRIW?rHD++~Mu0L;%0*V*Gm5TeyZRb%OT3vLpj| zuu^f`4mArWhCsapS3erzYORZoH_j9Q!5~mWXp;lrj&;FtluH*&;jrJ52UtDtt!s&C z*giONtO0QE9I~$icw`AKmTZ@?iX@1IdUd`}I7NlS55=Wt(7W_wp?8?gC8Z1IAI*)N;~5Q(qMgIgk_o2M12X zee~-2-=^TnaCP`i&xpA}{T8LzF!Zg$W?5pU=wbvZDbw#WCrkEk+h0j0J1=9{pYat4 zJFHd~w=7p!sARqiU%12WKhR-=nFQ4ZJ`8+bbF!V$Wi)pM({}xL(HuC&*#Bmeyh9YW?~6MaRgn;9_+xZVhP987vfL3|y?*I$o?+ zbVKH>;IA3(>}lgsM(p(BC8_S`bI)x8!l+oCi7NMNjs>4?pl%Dc>^rw_hT961@mHCd zFF<3XfoTV@T9w)PS&ThU(7&2rQq+&0IL8sl25)V)jtsJ4+b6;k-QcZN+^ui*AQhJR z4c(h54?M{}Q`or{e3hNY;@p$OK%mr$7uznBRvjXkAs8}3R{7E& z-@hIk9mkTZ3%LjRp}LmihGA+A54&#ML4#0M*RG&F{|9>`zT-oOa2zi&c2zMPElFXF z@`?7?14WK>Jy`!eV{$W;)<}c|*BO-ZnY4=rDLH2N>e?5I6yq+kf@c~8llp_70NdHIcorqiG%YuJTvZ^Xn5#T8*S{HF#$k5I+GyrPEibAHJT3i&|uSH#rnU{AHTNGb1ML@S#2R~ppUG4S!2AIL2TPQnR{m!^cw`rI8Y)6s6RTFB7TE0L1^sc}vEDNOs&+oz9Ps->b zaEj0lcNqWzz^h4W}r z8unIIIhM0BA7duk%h`Zfo~fJQ1%#0eDJXlH(S`myUF-*?Whko-*fl$@yL0@nwv%bV zCw%Y5_s)69ouXMuie<+NMN?T^-GTg&r;SWn)!kZXoBLSQVDDB_1ic-H$P|CpR}>|c zA0yD(r3!y7C;vHjAw?*UgH!oFed3GJZ_D+09n~HB4?Xtod(V}1&7Ujw_J+CyqLd%; zsl`b3#NXnM$t|>0nW6`ZEN??xi0ye&P@ff>PxF3U8!$1w)~!Q02~K8o)l*xHYC(;& zik4Q~-#!|l13I%1L|iV?SUkA0`PQW`=Mrq_>Suq?W%Jy%OBY;uIq495ZgE|&E-hM& z47&>Yv4xr1PR0SAEBiDJ+D>LKkz~=;jb)w7o>0or2PrRe#3sM32xFT2kxMjPZz2SD zzo9`lhu-n8RtODmf|?`1o^@+Z&8MzU1uY>&jQ?kBw9bY_ITGuPos0+o0?>~-0kWQ^ z`o6CCt-UL*p&EFFx*0fu%BeAs*SsPFj2l^$aO)d=8(H72$J|e~x$!WgQqI~Ud<9mT zLUQ>)9`$cu${>s;_(cfv6SSi!2RZhL&&W z-8z4d3uV(3e?1p*iRG`zn?a0iiK$1=X53U6e!^`9kUm~n+ImsXO|<=UhPLY=9!iWnI0rA0dKas4`E%}3bJWP_~wMTJ5%C5x>%Lu;Z~P# z%jioyH-Qw-Yuf1o(v+dHiv4wmY4pq zGOEfTb+ww zy`SjyURANTDLCmps^YfP#n9G$`SqldCtgLm>KbExo2N_aW|5jG%AMnHinPe8?vgxU z+DSZ*myXUV_!VkaX$fT?#S9+`;R?-d#6ir6uH5f++{aUAB?8_kmZMnlDRurF;3+OJ z<3~RUVPuEN^VoLPn4x_Hh4S+iThPlCKU8eI{$&_G_a-0@=t?4}gDC)0LTsAVU$s@t zHP;1D1zgIW%&j3UN6_BRTV%FN+*!bnu#HVzz-q>}^|92q$6H`cUnEG>2vI%^WSr-u zN`Lpk&Fe1LOc#J2@3A+Q*J4u%xY&Yaf4-%K(>kxYuee%l-@W5eoQZ^V-QQ93em6N&z+#@P$+rE0AVNEMymhe%o&80Ceb2) ziI|rZ;dq&N^06*v3ynwj7i>S6CIm&&(ypVtRxU$V4%>6dF!~f>aOoRqDjlDK#;q_o ztWkWLKvX38<8-nT0k6(IdDb2Y`fm{&%ss!uRC){a$7qN=k8|&*KPz#O4rIBvZ7TbH zDZWXN!CtYJQRZ4A(TE?^#0e;uqh=b6@}Go@@jlt%^yk#?f3%Pw=yca$t_rZQ-(f-t z7sk$q!^#h;u=5A{7yS)D4|Z*#Bct_Y_bhDf(Fe{f@Povpd7#WCa2kBtEDe0SMxa5C zi=JtKP)!2NC|?Fx`9aq7ZWMQNe47FQ<%<3=_-YIyRJQ;dKmUgL#p=BR8>&BJ6p10v zJ1N`12+qLf(wc0J!H)rr)*Gt2N8m*vp+806<@vOD62Ci_rXr#~qw9^m*O&6{@Egs%9Nd_=!H2-n+ez)TFT{dcl=D3YuyZ^WI-{=jBR{>!DYuB5 z`KwM?FzF&g&YH-ibK*%eDiWyPGUWd?=6qxgz1&lr?}?)T-sGQ+8+ICduTDT#3;6GU zAp%oL4&|kND6_+qCZfpIe%5RR=&q51#M4f5$2}xI1wP?ge_=ztq=|wI8m|Q<6o$IU zpZ4(9fZD?Pi-HH+44)9*rX7mN@JRbg0fa}b<@NpF5+8kCKMbFz{poPYPO(AnkKLC8 z+~dj>t&h;!i0l{ZO-R+2oeYC3BtiBhDORufgzO{jaXo(;ET9k&C{BgV0ySicSICP; zKzz$nAi`|uA?o#36oz-LFEz*N+X}DY?*X9Pfgk7&2(85-5Tv1A%cr z{ITsu<=`C!r$@F8{4{!UgdV^Aq9ky}6I#^geT*u{z8%u>S^^r(ZUxxI{r5E%_{-Fe zyeSIJV!K5jAo&w%`Z&fqASfdtB7n>#>ko#!FK4Xeh$^%*vr|Td<+yXZ-O<}jod34Q zS{_rkPe4W<8{Z9Oy2atut`&LR%2C#x|Y(39cTb}XeR!MoP!p{E+bkF za16Ly#ozP4x*pjAJbGsaZ0pv{2y8Z!XdZ5XU83gD4zFO?U{l9O45!$y()BAc$EO73 zF{QVRY;n8e3E44S4rBadvxy&8fk`un(rnle%qLRt9OsE>Lb)MKg)s}EQS5#~t z7f7V?q}Y?4lVQ1LE5qe%Ns#GOK3XbsA+17%Y1QX#*ueJW0=14XQ7Msvn?hXc!n4?W zt0@Z8@wtV4W@aLL;p<&-mz$_v-OKgv0}g*{*+k&6mif?@T2TfYbN%Y1_HBRq*_r#) z0&#rDGpl5_D|-ujueg^O6{Nq_bgB-Ad{{OVBaB#J!}c!1tggEQ=`V7;??Za91wxX9 z{G3(*2bHZqb~%uYz>RIwFl!#z=IZy90Um1k^m>d>M<~kaPW2;g`2os`ZV}+ss)U8O zKoo?0%L|L^a(IyQ2NsxMu{Q(37g23O9Uen_RDAhr7ryPd0rYupm}6TK0I%w4 zJBI(1aC-k`I}KEeIx7I!6L?%lIz3}u{8}L=J|GF<=bYn39=7UFL}@(siA$OOI<~rIhl?CYRmxt_g(OY?-$|QflIT zH{7B>;=hDk9L1QOzEjfTb_pC z*ZosmdihMU1X|LcflT+9tK#yx#}LfJ!+t0BzsvsrFUzSWoJ2cXW({7FTl`_5lll}c zgvRSC^^~_=rBL;^Uk(c6AaD6pDw?Cz?cz|f{z!T7cj}jB#L5MjPMKXdyuEF!vxdWQ z?Ac`HUu09AibCBmrH9TJ|$%KNhn(_ij4r{QyjRc-b6`%03YM8PNnp4fg4 z04aDj$ol-{Cw4aJE+EcttN{9}qqH2bH0^?k@D(zyI{twIuU{R|sdoXkExSB;TlgFs zuk@-__jg}iFP)n4lzeG>8KzkOQ&hy#Wr*DyeGO>*c%PJi+(I=v2+c);Gc_^q9#PVWpg#HX4oj_DW!Id4B}UbBAPb$=NDQ}j!kv3n{4zqDxz?* zxJsPi(T`hm15HaNFC6^+)a4b-;*MIK0-r8l?j}3qXO*SXbw|`87mn!<`EW1@#+$CH z975Q->ZSYvCJp!snExh_#1U$8_4v%nl>etdZ1aqm@0Ec}udFNM$=6uq=Ft+7suM;$ zODv=pb104eYJWfe{?agIkpGuWc2#Ccrj;~%6&H?97> zrOKKgZPizmUHwsE{rHuWdX2k$;Wi=ncs#L1NY)cOxsiLpXdJWHmQ#y zKO2PgilL=VUSWJg`W^T+FkN=sRu+mbT^$5u-8+iM^B=|*FoOQSwag|kQS~QBb#

-5Jj{Xh>po_9WG3FWc>iYSyOhSDwQ)chmC z`B*Dw^M*S%E!M-^z=J0V z6d7||$+~a*@IFiLZd^Yn5X=dB%H6a3bnisADNpv;0Ik^dd@HDwLMiXrZtkAVOg*p& zK@1@%v|k%8d;h=#<4sOOn5_Q(K3ofMn!$tO^G{Vk^z}@ys&}ZY=m_W}-EG|aNi%_s zz7v@!;Frlxa70ydUErKIg#M zHNm=UL2QCN|IfhnWU=4Y3h|G4!r2sD&3kWVZPiH2xB2NN4R*9Y@A4RfP&Ach>&2`F z?JDsYk3Id-9`*R2SAkfXn#pMGsYJ>2a}%QHP!0O$36!bTqZHcJqaPZ>Uqk0=l{8|X z%6rIBM{F^`I>R7;7?)UfziL^<_SCP^Rz#*D!Im@E7348jah?edHv8ba!GU8-+E&0DQC$l? zUGoy?lFrgOHUq6XL{X<}y0?m9!{z<_dM`uX+C`M*?_=t8?X57vcl4+=m>h1rw|YgO zjuHqIq^P{SijzkNdwvyI7^H16iGsZf3fPdQnOBl{dx5pZ-q*TQfCMYOd!$Bitxd1Q z*L~Uf(I3nETCR2dB@(=6++MF>r?(?oBF%Kw1aL2h*`5fXjaBAI4$f~MX*?vU;fT`{ zlLMrjOTTocI}E<9RWZR58EBTnevO&p>?MJJofTA1A>GsIAE4GW$Q;W8hJRO8&BB%J zAk)jg88MHtB3P`Gcb+_0kFL=JYoD*Kx!<9`Q05K>7icjhP;gP?KP2wg6l1YY$aS9h zX0siUo~QB%V~G$558P&dxACNOyLb-HIhQ~JD$9E!VH0Es#7|%Rvhz34?CASPGtfTkCRg)=ar2LWx z;=|NwPawZ;vPOC~D|6YASYsU;Z_77+xapheyqW^vB*JM@Z!w`*!y2qJfv;q+OCuhq z7@3H;-?vXj#)D@6NjfQRIv@X!qk1qS|6@(4!V4L&*6=>bG}XXUrtr-7$$at?D&Kw$ z7RnU%w#;|QQDTAAQ!JHJ-x*%itTCt{oZ5ypSp>ZEE}y$pK2uoLD>kYwMi77BJ%L<{ z^uw<;&1gF1);g7npK-jO(@s;%e{_m!I^8{-Eu-U;y#G$u}x(J3+2TtW1P|-PU&k+gpJdsnm=tw zASI^ePTfQk5Jp%+=L;PpDul^Owc>kx@9haLreA@ojy>sNQVYL>Z-N9@!5!1w53v`h zQlB$y&`4VZM1@M;vmp5e;oQrwb2}=dcsXIvUB&z#%mN=8W8Nhf0{JEeBPNm0LK(Vk zG;hu?tCTXdBESKqMGD?FoZrxpTQ4Vx>TMj@FH8Pr;%Uj<`UUFNUi@RRgnL1NZpO|( zqsJJtV}CQ=Z=T&&yHF6&$~jb18{ew&*P9!5;2_XqH7^Sb?bEt^+O?y(O=}T)#Py+c z)acC}CdumTCm}f)91zs`)hWWY+PwDdB`BxaGC57B{Z=9hkJVoH#gp1E^m@k-f~GvL zxDgk>MBDSATR$0ueob>)^eo*9dka#4lqD%+#p9vt&hO%r&lmq;O0F~($nl^rho zV8?KQKZ#QeS1#GlmI>bcFAD%hpR%)E;{JuTFwuGoZPL+Iy&mZ$umxex_nd9!g?J2K zBBT5wsp2fhu+sMY0LvY{2xQI#cw;eA673TnB)^l*zOsYh#j@5TA?H(gIE$PgMwk0W z@!bSFob0bWyZe%hgvaUH2@P5^wcV>g$F<$Q_C6#QIwrd&g)Gv*^3(MQW@uVJGC3d| zu*<&~58h#p7t%AB!XFzrVLSVXa?~G}>=OsrVeQ%l7x;Q^b1mb2eKs1T^ng>fm=jxE z-o=Sg533SLh3P||{rZ>a0>0HW^bZa#CPaMv#vw)bhiN;WYWpJ>@pfWR--DAj)lek@ zc@O2)k7a69YUIxdB9suwMz)?8QwWQ1*1!EZvLkUMUy zlJOKRD<-dK-ymNUbg{@#DCqd zXGLb&MAh2#jZ}Uuf*xFw^t0~+uU@CB>anp(r_B_HG9^if)FYLs9T7yakOALcRXMVS zN@BDD2v>CG?0WNeu=<8P`Z5Aq>f)Or7q2zWgj*Ihp>ws-+~A_?5ouu&TRL_Ye_jhk_b8=C0B4Mmmt8EoZL zHL}YatoW99)_?QESP&9C7~uyx;lzJYzjrbS9~~0;O(WG!$gTu5l&&DOLO6r+I+QGi z^=TQ$`DrmG#g#WfK9vVBFu75Up_Lz@$1Gk}Yn|q12vet1C3;X8Qz{@Z1yONh0o+0r z`xxB6{;ebbf9#3>)-#UXYDXpH!=sV5fcD~6d&-Y$B$l%CT0wo5V*8>peeH1#5$_&W z_-lv-_Z!(fB?Zrkh*AboMkTn$K5V>KutJ+8JSkk6B-J_K5~Ummi7uY+5F{}grARaO zkbN0S?N9g6e$BIa$6Ii4RPnj{Lfv?ETLo&SvbB;U(%!?;_6Ro5Wxw3{v>6lrC)j2G zf%X)1a%C7r2F))O`O7&xIxWlKlm;a_1?opOLtU5d3_<2+BFwrg%c zxY@Ja&gA6JKzzyRr=tEOv$rSO4&xeElP7V5E?!rl*!jzKQlK-3_jrlCsk{dkAZWx^ zkK(+^dhGp)sD|)ix;=j_6EKBgDuwk^Dz5&~Qq+;ELm*MK-dMyFG(V!m8M1$&vuSZY|VN^8$ zc^TXdTT33SMX-{J8QITro@+@4?w)s`bFNcNtBE;wWv8xZv)s?b+!s*i=(sFPrSC(6 z_i{!3o@oDQUw{fb1>}fm_qvR*m$0@xFN&66mu&BV#9H0yo|?amT5)CiJ5(hSddN(q z8OaVlplIl2YrFZo&?h!@#O{t{s$X~%BkLT z!Rc7|IJ@?$L(2yO3AIs&9P$SVS?C;8*W#McVH<5Hk9-;LPD1P^xJ+MX&+?j%SZ_`S z!Ibkii~|aLR~&ui;tAkr_*vK<$qHR5QrmkFoeiEH_Sx2Bv4>7DF9%JaRkM>V(@t`r zIs}m8t51c*umN($iNu#%-yNua%&06s$XorGK=thcvcPJuczB454&+61FZ6I} z8XYIT;oWVK216GQI|H>}Ssw#>y`KSAo!H|gO^UBUIFGcT)YF+0u=h5eg9@LH#=-X* zl;Xk;yvO_$W20@5ph2HMg6GKhh<#dEOkDn&81N?T{nRm&w0qj; zxrf|xs9z#0qQQryU()Y+GcbPp3k4#>+wit5HY@-7Y;#!=E5HV9rm=#}7;fj+)MB7o zaLK=tC8N#b+5lO5#$ZGC6h0)3xAAAU~KaLt0B|3qrPG6%$8^8aD#EZm~%zPC?zN{PfENQ-pG zfYPZnA`H?ZA*sU1Aw(La1nE#INfAMWp-V|cy1QhC9AIY7Z}fS;*Y*AbT(Hk(?X~Xp zS@*JzrHGB45nEN)NwA?;`(TSYk6O~H5A5?xnTl}_b`I%xFu7~%ZHAMFU+s3oPJ27? zuIk`kGZu*7L3FW&t@d%Ui+TzUvm7-zkoV#{LH~wmXZRaWKm4r-pXNe!@(|Cp(;%8j zcf3n51Do>AB;+b*Oq*hE0W7`!fI{Dkuog(k8q^FEY1vG9p6opRm0v)P<%-|mN^$6+F$Om->H7~(nNX9TM%sTjIoOb3~}pIFB^`OF2y1HKsQvoGEsfFM@l7M zd0Dj4aIzXRaz6QDJk5iu)sfR*J;_qhdkFYp#I%R1BAG?P&gBP{&)dsR1ZnNfK2{x4 zCs~_aF;r@J)V6(sJvpa;@e%q_a>Np6v-=@{$!A*Gc6CdSoa@l9(b-hqFP15&4`cFG zMdcsX;>Pe7YoQT%gx{Vqs)u@kk0ll?FzJL4BC;!UH@g7=hevZM}XepgzHP+LibIU;CnYAAB*49p&1OP zwa<`@=-?c^%Vohp8hG*5dr#1n^NutVgqEuK7pCC%ZCj4!TMzL3?GjG@w4e_BO%Fb& z&)Yj^itY&Lxm!S6Ap+LY=Tcsajq6w{DOLdQ&L47#4jv(l^9yBd)=Z6Lc$n#(2w0P^ z1=#Vs_bLRu&Xp|7^nCQl_@qkP$<@*#jzg`1#9^=TkbX8J=#5trvD|X;DeST^3G(`( z95J`KEj;+{vjAM=EHh74CYkuLo4*H%+OrQRo`h5^E7+ZR?Gp~%Yo#3hY-_m~_^0)S z&)I%#{-&#Ew!}*^l5x{=YyFtJMa3CoB7>Sn>9=p1y&<{hRGZLyyId-p*YUO~iylKn zQSn&%of|Y)?p(QDs3(8t&d(#21#a)N))zJ4B2e|Y0IRa8cyJlIh<$Z-YW3gBr}VX%=QfM!98qors^V18P$kT z`|{rV68MAoz9I%ngFa6{!4IKlFl z(jAX5#_6uzklvAq9;@NW$>br;e#VvXo}$Qxgot6Oj(3weQMi76u9x*nN32WAva+Md z>)UfT-!$sScV$}RM#=&ozNHHFA1C=#7@_$zHSzu%K}<7f3DNDyy3nNZAPX(QugBzc z@`A<`+uU?+{<=o+co%4j^y$w8b-+98?eZb#K%~#n73k#zdLPUOK3@N=UjsepaRLvp zrDuz30NmBzei#)^Z*1q-q4_K=B&MKZY3`NIfPep?UW~(cue*jWmqmMxh1!N0Qg5QK z4`lVz(q!oN;QJRLZF2%Yq*z zc-y=!1ZP;Ts2PTB!8a%J+cK~{SQqVmrr1xyhnjB}(uYm^3@@Q9B8V6L?uvJoa$PsL z=R1LR!hFH9iPLZc>--hD#g&#}_o*}z&!ffkSrC@sxs3BPPYT22M1xpc07J;|5j}p` zVujqhY;GIjOzY)zG5+^c#FP7xE3)~|4xg%r@Tf2dhLF5Dd8U3YK(|-H$ayqUsua%5 zU$CK(_>)5<0IiE3WH68PcqBPa7Jn;_$MF4DzeW^|Tp@$Qua+G14(sJiujx1UqCJFu zeGh(-l3)92Yb=r-#!HbU_WYjY#b><5{1g>7E4HWod#3cQt)i679Sqk=fvc=_wD=gX zYsxVsB90Yb=LoAqo_Nf4gw##6OA(vWd5+gs(2$#CK* zez=*jQZoj&^93n$12Zx9U$EjKg`3~m*)Ulz4$%c!KrJ)m_CZ6;=(8@?rOAY@4|S_zcBpOnnsyNSf1nfb$Ynl$@AW?byAH=<8k4>j z?Zz0m^8IN(2LcN*)0+J6cu}mjnX5(%Mo}#$laPF{D88C!hH;58Wo`v0K1+32Q>9~HK-*QGVqR`rU|`D0T!d_3zX+cLStD2 zf*y5P#SU%(GvduBm^*}n$A{=Nx4_S!&&J}DCJiEki0|kTH1g&B!&USrf>?y{vH`ao zhfe-L#T_6;$p;^DsuAQjqDr4V zC2};!42AAVF+RUK5kn{6B&i=6w(w55l=C3$s|Z(UX1ad3ja-(|%Gj%iDv80{2i)A^ z9o1!V#-?0BQ~j0sT2i`WoC#yV*4>O;8wK6U`Pye6a8BB~JJn)TCJom}!8Z3NJt}7#ST>;F5$_(U^VMzY`I3JOjdLEC5MO7F2=5H|UVfFA z17DN+JaVYbh8`CYV7`Qt=UtRrpTqZS)uw@3KikRAzS>>iIvpdxc zZIEoz(d#|Xi)7E%(~IQWlGfD?H`I(W_U^!WI=4U;Bzfc7Dc)Y4N;8VE<+CMJWN}6C zg-q!h3T-f7`>+O_&Wh_Kve2*F*N8^%tm7)Z8y#+bXH!I*O`*P^E5O&Ppm4i+Lb{Nx z@07zyzcE~X1>kuJRb$j|H47`^fLy;)7RLboJ>8*)lT zwc<}1w8?IUu? zyt2oSZ<9M@X!B%dfB4|&O9!bRKx{Fjbo22ML-@Ws#kW8`;pMqpdtI8CV3*X`f|X|8Y!EA;R8ZO!1<;;k}}Aa@6f z(T(P+a50_NF5f{-?tN;lCDzw}Rfp4(6rR<=WS~864!kZEAk4o0ks~@7Nv*tgG4uC1 zjU=CX`@evrl-L?s12C`O-$^Z2R_TM@^M8~q zqrhAJP=w?zz1B>-Jh;!GNsTGqU&=(pkq*QoJDRD~PGv(c3u0AFN1&`d9@w)Bj!z|2 zt)P1zGSk5AGkAu(yrBd*5_P}e9Q6Iro5(ddW8eWk!CdE_^k0c-?1nVdb$WpJXe9d# zWauPW(BFfdA5^K+hQD|Tt;?D~$6FIHw*`De)`^YV*@DxH)F{ci6-dj&ID{p(G=)39 zOvO~>q8vF0Qq0QQpQy<`%+{3@!yM2$K5}V<}~!; z_#1dac<3(@Y*s#Q9&g;8oSma1h`IJ)Gc{UGOqj#VcrYieKX=%s6WE`Uj8=c4fn_i-@*6UDPpC1OqY zimkT4Qa~gniz|M7h^Y~&!sjZ@Ai5HnCm6K)1;qQ7UD-L=+>cjX?>&Qw@%dYu!Wtcy3JlA8uCxb|!@Q5`#F+&wTkNL2X&YYmVi(F1iE-*O0a+D7(Zb;9i{ag$;d zd(et!i9<+|(AzUN`U+B0yla5C-x~Sa$_2<}%4PhoF>A8KC;oagzc-BDr98iVQvFro zp%Hkes=7yF2$~E%9&1)^0Nufc;p&%- z{ujGq?}f-~x+pc{*y?8+$(wdC2aNT8aVa+o9aogCKXrPVXuHIdintWIz*lnY;M?p9 zWtCLu_iP{CXZL}DFequP3wRASTM+0gj9oja*!SH*Tq-ZuT)_N_9OnV&(VN^~mvBBv zF?*$cjz#0N5f988kaKScahS)|`WASvr}8&fZ^bpRpWr^tfUPfnao=9J^x4netOFgZ zdJ~Jx?&l#SN2!v3DV&1NFPG4_&qc=Qpefpi`AT5QQGTk_3boe*X&mFeBRpNm=Eg~u zL>^Gi(o!ojd}p1zP*1z3o(EagZyGayh$aRTaMX|K7jJr7BfVI$4D+$4@ck-;7dX#8 zKx{2nNX`-|Z%{l9b{Am6?Dm0#au)-JhxYfuK_U9HYvO22ocP`j`HHk!a8fVgG*fUC zz{><&WJJu?I_UaM)a#z>XJ4 z(hyp1aiD+owPc5}xM#`KKB9WKK8uTl3_Zp$Yj`i|H19PIh8O7H(DpN_R~FbiEqK%G z1BP7l+yF*Zd_r(_9_w-TfalFtu(nPLl752A;UFDeVj0j$7T4Q4(n)H+zIS8r#A9iy`kIL+4>xDIM_TZw6*&)kY@m>U-1F8v* z(@*AmVZXJ&`Hi;&!m<{o>5(7LR_iUt0coTJni8B_}DJPc-uw+XqH zK0X-s&0A4}Tb!=as~yZQ$w3ayd)7Fj)y@>pGuNKda`7`f5VojI@!(ymcW8|5QyNmi z`{V1{l2*ORe4tGpPT%{|MB1b2!r)yAt9ix=+j4CHpX*p*^wJ#I`K8mGCM=5cF&`pX z{4I+AH?lO6yp5FKFej!3=L3hEb-`AD;@pPacid-=F}o*|mnI*ht(lvR%<%q)rxXys z7r1Ax57sd*e_{@}7l-=Mk*&Wkt2VA}LW32u8YuC;vZRj$`8JC)ooK(jb9tZyqJj+yk`& z04ZDmh~LEu^Ul3AaWi{`tL%4S2R%v%_b6dK)MqeFSNOIpkVqqe-D@i8iSfeiKX^ z+6F|u+tq_B)K;Qq!Tg)qRM||bV1uXQ$xAE8x7~UE;@$47-&Ie9Soc1~2$-7(?w_#H zsmy@Ly9dx#@bvssF7*DDS#+dWU&A(rEtb}`8)C?7^6tLb-r8u;DTF$XBXDE-2+4)}=uwgNc`uhyEB#>IIXVkdEk9fWcGsv#RjD?Ny?K++4`VXYBl<6LdY*y8k#cZlwfs#T0*G6Jv9G20rIEnG!{0# zGONGMbFp8P>?%N!YNnSIN2>zF7Ogr|>_0c&(b-~dgnsRiN<<_ezWv4}Hy=+qmi=( zD+bdR7$@z#^MUC6`J)kdk!U*K-AiC*$&hDk4O>f7d%*{Bb|^pLVh~IM>xBcGKvuS*fF`fslz8jF`dLBv=Ub2N1H9Ep zrlms^eu>UD5yt(#r?~PbaZ!vJ-jg!E4~R^@_r)I*zWeWjz9(1E{&%Kso8d78e8zW4 zBq81Y(^%eT%qCg z2s=)FUs>jh2kU-RP;`khQ6a%V(1TavZ3Kmdrc2hbaep?E(T{mu3y3A&v#8v^gHJ3} zQ-X0P7e6((u+gpQ2kU2QAq}8lo?-c4aZ1HRLDReMJjX4lTfu?E_=lRsekd_{=;u$F z+n+hWX9Z@T0%3kQHXOl6qBO|9gAa;$7VV&jdtI!EOLb|aMZ8xnI?vvRmVi6tjj267 z)8nAKKW2bFgeMvtsJQ|Z{SKDL>MT&^S=2E;#x(2;;gq9l>Xfg6-;p&lzy@*Cmtt_z z6SOm$;Cws$SK!#)Cye%=ob7I`RvqQeQe{{+CX1_9sIcyfe=WuBr(F-}Br3tL7Dm&w3^PjGo$9Z4zs zkMa?%TRG^+U=7|)4jH7d@2LeQ%I>;x*R_JL88PH7OHAG`N%#mOC#$Q76>h3p8=Bjc7Upgfcp$&Ur)GGZV(^YU9>>R0) z)_hco7wnb{RYv7WMw|<0ew?a5=OIc@pf)roDC|;OVI*SV7a`HWkAx=N35=E?$>v;O zB;+sQ_{8}(u*_Xp^cFYM3k{1KSK9^2NfSJ!v{)p#o?R!=k$i2kZoY#Svmh}%WEM5m zK~r3PaZh-@H}%01lW>dVtWb0jlo8sLnNR{ z(Io6|pbQTA=&!YzARns&yTEiPE38s&`YdQF$3YL_Nk=-tA~+t_>$oCS7dx`#JE}Rg zVa)QuwOYc`Y-Rw1{3guEhw@ofr8g#o1@J_De`5!~fRVBAG$SkYl>;}Cl@IIv=Rq@6 za)``YJ`!Vl0_*j>^ofx0z14V4;`?CnV{ZzuOa3Ch>PlsB()GF1Dt|k7K^&<=FPqC} z@c!tJhu_1BHNJVD@z0Fa$ROv#<9lKC(rtZ^i1Y{V!LTUCbnUMU(4n5Ct3Wvt1C_;@ zflMf@KzQ9M7yBaU)UvRC#TO>CX-C9kf1d_}sh$34|bw>@ib zV}>4Io6}%88LfZt(|U{#-7Jralti-S`&B>ZfX=ypk?K`MjoY0-(oUgmV-JRxo~cr2 zHcuQSPfYLn>>;v+T0sfHH?re+)CAG=ZUkR&n}wSgXEFk{F~?Sy-nj-g(mppEgj_M< zKKu=FP{Wqnn3TRk-@6_bd!S^-z@e4iJ19E|vz8;rSVG3`A`yjfv-nh5gEFpvoMNvW zEqZ@7`$xrG{gK-QaO`B34~S@kC1%r1OeNq9I1hY`|5HtN9qQ*=`2}0hx2WK7cXYST z0J+>St^zzT#`u-de(k)NJzaDPB7&;>d<5% zUl)4s6qzDoNb16u$QxD0xy&d3o`SpRVTrT%RVbfqz%{8S)VzNt3zdDz)lM{ITNJN> zWPJ!M%)e?AlD~B#zY&Qqkh^oQDtjFu6jd)U&4=gleQ*W;$V9AGMjVtAbXGQ62n|?% zl{lc$(8N)));mVGuf0P5DcZ=zq?~q&8cD5qc%{VP)ri z;L_KJE}WQDv`w;SXR>`<%9}dTDfSI~4qO-h!QT(V9%A1nuk`1an3Io}Z=G>((B}gJ zqj+SOk*nMRD_D;{vpj(<$w$?|Ot=TCO+Z0ZP%d=$9>o3H|?d;qRK z5>3O48<-DT^Y~tWw#dkHJ^hlN_vl>wFrr4zv|?Xp|{!b6m|M@$V9 zps6UJ#iKbuWrVWSqa5cB)wkyciVBa7v%WauY`l)!L*G|>+!dG`1CVczkS^16ym$MI zXLM!K{L687So3r`R1F&vQR1x)@!lG2^)zCV*GJGovnzb0keW_%j(dzcw(KIek42wZ zqUG`XFQ0arQC6mIC7_0ymDi#JBH9adH_~vSp7+vI9cJ)j2QMrEW9i#!CdnS z0`jZUb@)<1tIJ1#1jHK1E}avz28t zPe$(wtQ71(gYH`i1y0TZj3@HF1qaP<5Q#9Uq%#IqwQqXj;LWzz%s4h!)0?kZo9IcX zl-b4nRTcDNA={F_|HoQ8UF_&h1MDxf6Z!nh6qJr@qp}mtduL?ta}T-gmid zZ%4`F9^t@BHOf57@KQlY*ydRT>&F4*2!_uFv06fZK8&uvUeHJ?Xdz>#+)i+Y9ry9DEO z34=EGN&xPytEru~ckB#EJ*g-bte8~v?fl@4Z*vMM2RzsUlfk7f5_hY^`ejPZ2qZ@#Rm3Z)~Q#ZvtdbS8>`q!xOe)S@-)>r}%?U?}kL^;ktozQvx}HGp<-cKC`2<9_u!9@g;gRZ?m6!h&}&)UE51oC>00a1TQUAt<4vAn29ZW2^?I!@`_;=-$9RizH@uEcU`*PEf8t@5lrWftFH7>lM*V|Lhjpi4$ZzF#t zgZ!lb8{e{h^kg>q>9O+M=HJqZ#v3V9W8);a=#2UHF(`t1qekXJ|F zpvVJzT{(bXLlR`3Ebh*~m><4+zj~!^;0nO322Du0>Z~PzV-MCs&_E}gs8!?8#IqG0 zJmV#t_2C4w$BXE%VTgKircvKY3@msHs{5!wqh#lgnMpPZ`%AYz6A)ozxBsLgU*vp+ zkaHNq4_q+mZnrQ)2)n(Urp0FDaFI1gaV~J&pHfXpPYx1kmgIPnGZ*NNvt2Qn;N$O- zRRik&Q{U{l%kuWVee`}jOKjpu-~G^5Lqnn1J&9f9iA21J_b;siUK%wbTJOOOCaod; z20r4%>_OzcA3L|h#J8N0UDw#wPo~sKW2tVZ-O-p!NWS^iJ@Z3&W|(E1T5E4ohL>}2 z3L{T7>bi(l$+0Ck5wcoZ%MvzHa4Qj_meU7;HsZC+lM5$)p}MEt`HYuj?-qbyF!52* z3wCIizY}3sTL;;fcrK=@xwQ6!Sa}g9t>FC4icN zy^N64f2(f{+XDtO6QG^^{)6CY_EMF~Wqo19H?Q4(=88=jM8+ z{l-fr-hZH5`GD^F<9Hvb%e+L%4?%xpL~a!M&Xx+b(`-Nf`i3!F zFG&?v@U7b+p}c|EEz=)6&&M113q1>H7ozHjA-*}Lol7X_#qR6;nTSV*rZuMJ&tq-D z1~=7fiK`NGCtUEcJ4DqL4p2FvI$K6&3o6$yE!NKlLKA?RhFcfU;`(F0nbB%%#CfoE z0p+!Lu|XB|IC2@8*n&^0b_t)lG~ygjibE+YP^{}P=2oYGtOVzgELkQ>Uj&hgxPbq zZ-ZkQ7sWL)DB#G@d7Ax`lOtZjni$HFjErU=s_y>0Cj^(xxK&*1s2}SQSK-l6gET8d`6kRWw^bB# zHS+eTxPz&{gWp&}?AYajHAgEr!?K*L6fZLAohqrvIZ>CX zfGe|e{ZVdiR?r|)MRB2EX8-Md=ouz@fGACG&Y4+kfb~-sC-^^Gn{Ha^akkO&fh5PZN*Ck&3mDG@m@M==>tI<|& zd0#4+3pSqktqFyV7L(~&ts|9MFph?me zKKj<270g`0Y-io)s>DKL2ZO;L+jU8d-wuX4Uk%v748#;Z*sKsq0(k1_*z(Z0s$#L+?ppn^QHG%g;yxyd;^KAPcu`k& z@=DE8v)2**U1DjE&T*Insp{TKQh^mM{v#d9i?GCH;j#rFwGSoea#`?Ow*>T#e1kp) zXl9B}^s)3-q@iUGRu;|B$Z4|W5KQ?8)L?~`Ri{qoc-|cFy-oek|GG+f$N%dpsi=op zb-Z_?C1ttGCoK4+=>Cmsyna8z#CPZ<-U+oKl_C;jo(pBtaqVxVs4RxuCWu-H_mQ+S z1^uMy1+ER;;m&ZiV!=7VAD&CTg5M%n+}y6l`d z$qcx_Ux?FS-7%-Y2vjWVf#65l_jRzf)a}3O?@&q>=V7#6vB7?`VXnv-F30Urb)_1R z#rflPmOK?jbr4Q!Ko^s#eMrYJnig>CZBaFy$%KlYHSUI(dHON~%*H4Jj+_#zckGLa z^;!%M0a##~C-x4X$>3v{FEgKM)LUv5=LIX^v z>+^t?Rq^%AM35DM;dKA6G15-_;trCAtlY?x{-bK)UDHK!YrTg>bRZ2ckJ3f5YOF0IX;mWanQNc$Eb`It721 zgwC(Rc(MNq@aNC}7T}Z5KI4NnjXLxG+S}b6PqQ#)4ay|bvf{F?eVagai;jdBdJ1<& z_i6=PC?r4GZ+<;tc*ydiH(KQ?pF;5;o<~%)F>^5yK`5?Py_D27A_$HrrLU#b0vZK5 zlslp*kZUDVdl8GfiKRbZ#mR?W!uJEGpTBJCOB>ECA(qZa>^Gm2hP5gB91DLP)lN zLDPw8IcH1s&ZiewRa|mxyw7m-&gY9^f*44z=Y>gW`X1A|KlmM#v4mNu?I60z)V@~x z;RKh0F(ylsQ-v+a@AkU&V!Z`%;}&?oe2Nqqw|Rg`BexGfOdAFBwCXUK`X`efA=?9_ z@}fJuTtb!x{t&Lb*+#q#iXM4%jp7Gqc+AQHtNE?$RfR8noTXoD=+;KHORntcMXnv3 zQJ+RtUo6p=^XG=K!O0cMfBt38FVWvEnHS&k+WbN@z9OJ(`M5`hlK#dKj<>5KWcYee zeo(}C9sVEO*oyOubeKi8=`L%Z;UB|2JQK6}ZES3Ob0kj%uxYVxP_VB~uHU@z_&#b- z0n}2718#PWK3}@sWB$s)&U?(I8#W-GFlO9Quwig5(2xh$&N`8ajE=)+I{vDdGi&IYnGy4yAQsRCW>N** zalr^GY9`^2PR|-K2iLC;JZ70*dj-A)v8DM;pjuGv9hn=uQV27!90PpzZd-;!YOe6PTQxMFV z{f$rh2*+uH=~;{0XP- ztI!!?hbH?92%qvV_NEuc=u zb(saSaKMaXnE!Oim-a&1P7$pWM<(7|_(-1oAv{lg;j(5#TM;kLvB zsgSoGdr+2|yRz>%{Pf8R`Xb~k_$n$WMQ7l+lCIQ#BUI)dW|?yl3FdDrL#H! zCBGMECtzjdC{7BLOp;xSVHjobqU#TH!#RFy`xX zJ>mum?jKiBf*7_vz~e~5(OoF{;8&N`!=yDu_g_~58%xsq%j|?dh%Fl~?50`7scL8{ z&1qKjcYYLP&lY|r>AUB&U1xvmmi3N4+N}{cU)R=vhwt3h34@mYoj?2Yu&k&s-W8=c z5*^t%#xMrA1P5yE2!^d`*SO|L0ehUyu$Ks*50@E1+RfgE88J0oN1_^Uf>%Y1n>Gxs zII~yYXg7FSF=PA0*|&H4{T*BkZz7j?>LVlCqZdjx7kCSGp+2>)10Z)3^nf7zcaWu{S_jN81_A6^o;R%#N5k8|+)4j^^WR#-aJy3@27ln2NG{Ug^BPRh{IoZTGp)2b(SNLZpT5DkI zMw8x+T^_h4c_kBHNFbTozTh*dDZ)cdIrpIt z{|b|_Lciv>OK-Rz`e!79@gYr%0R?pLfGz z#S{2(`rpEVoZkhPk-k}t9rChgAZpv;>3y+dCNh{5t^}e%56-uri%KSgtwns8XxuiY z$U{Yfc=HCntreMI$AxQ*t2_n7@u1EFXRV$IZeZdJ`6vg~hql!^UJUlby?wd^4V-x2h=yj&>BGO8Vf`SbxPs0z+QB`j0RLhzMys*; zk$)g3jp;_^IdpYav||m|V*NGW9h0;4P!EP@TzT4tjI9mKXKM>iqGG0 z(OhAS8Ih!9Bu)#CXbwq44M&=T4J4yo8pGMehQ^1bvD!Y|mZ=};942<8mlZB@I zx~l!bQF7}bzmMhPcu|~6(1A1n*ol+ga*nvBzwg=FYPWdLYGZKInlE?`WT6?A2d7E?qT+>3;lzMq*3h+fw{3gUatQ#yu3y_Z>vxV z$zfk(CvpkKIEB0SYIhgm*2eHGR#lcC<}E}NY-21wca&ZWH}=IE>uQCu+g~wCcj@6kQh_diZun6(CUq`^zTjtComMKlM{ zw0ns10i~ng*!(&g*^T-9V7Ga)V3Yil^E4oMme4xD`PJQMqJ9S}4);C822LlkSpJD0eF~p5_QQLKl}cZDPd2wTXbzAoN4H*O zX6{`jpjdw-o-JEue}j!8t9~F**0TR@T{wG!c&}J!1$6E)nMT)LrD9Lw4)SM9ZnGi| zKYu$@%!s(yye--gur@Sr>+JjCXh;TT=MMIkip`R%eQiGr>8db~F!3AwDBM%=8TFHC zAIuUshZN)kpYH}^pGV>A#MaMeuwmG5?doJTp!Z(z&rNY#8nqM2M3^*giHus3{1FF; zjx^x?^*=9wjpP|^Oyry~Cgt)R@6$UNXtPW`eDSE^9xrn7R>t|y@A7~T;gOqTmylcSq zg3iU$#Zy<%%SLK0{77(PVJ+>}-{6d={yDk+U3C9LbuB*oRu5Q)}SCB?6yV4bV{Z|>#DGP;{CAny#CBZ4?#5Ax8$%E&QAWXIH2 zNi~$bZHySD1F24ekcmBX**ezYm!^Q{E~UTwu!VU1aHQSj{_5<#ePAO}pzoW#N8D&c zB--h#$O*>DHznO{tz@tj*U5*^?&w>=LD~hAPA+@MeNkT=f7J*?aYbN-{y>pYxf@4J zXfeLtW$3l1Q;B^Lh^<t2DCf-7t4f`m>|Z)fSmO!RR^umykMQa(N3PG+!mwN;{Xrb|4LE1px_W%%YeAxHJIps zIkK1?GWPc08@Ra?K1Vy!@vE^8{|45QbIv_k6~``r6{$Xof1IurkQdLMt0QsG%VXfF zbk)Gee$$_%bu3=je?EJeoJErGDtFQMmE5Xr(Nw=6+?vAp#i!J{p|9_X9jq*_7teZ= zEv^*4y6;(qD`5&rgeexDd%(|$o;KjMe@Vt*>^vGbc{y@{*~WeufpC4yZT+%}sgj-@ z^dC8VK70;IOv-2%kW^Fzol?nYap>xdGFSl4W}O)%dAUZ_?rz3qe=L5t1r_a6$YL_j zJNpMQUCq<0wB6;6AuX60Z;aoBZ8Q6ykotQaumTUCNKf!#%p-|D`TT}9#36nVT!(Fx z2IDWn01dg|-WEs++TQZ*fXLZJ6!?{Z)dsHgkoo|a7v_Cgz!>m-;T6X(G~;6WPZsLcu`WWIP)<+ za}yLgx!}0;Ie<31o(>n>SI(EZZ(;wS;t5V7IZIFE_~MdA6?A;r8d%YE4a}uJ>F$aF z7>b52y@%MC0tfW&V9eIdc9T!z${EgNL|-U^H(GjYu&qcuZ(LjXVg{^-5I9U+0p8tg z|Mrq)>p@2{TovrlNTQZX(Xg=+z(Z|cTGNOs8~wHiakiD$0#+Z%&+K z_bRk~vXZZ?%!Cl5Nn32+E)^)31If1%kD^W1vY@^8#o4*yE2Yn`eQ10+~g(UEXE zJ!wi~CR6G!G$aNFxyZ{j|4_-u$8~64OK0x4{7jTD*4Dj(Vk=TsPmAja@mVR+tT98& zT-vP@RnGAWb!X|epk=}jJR>0uvTaudTlORHAoJaF=QT<-b)I)%75VT#l=&D_c~a3= z{0(@f*q0rTE&U58%}8Pk^oB?`bPf=8&!^ZGZkQH854*~bGRX=M5_{c{uP7!IJ?_`{ zy}|v31OV=?b#!GfOQZW`HTDPdO#AmE7=IsZ+)3C@8{-7O`fSXhTqx&8Co96cp)8NY zl7os!WCXsBiaM>Pw;h*#kZSIqrda-M?J}0fy_Q7Y&%V{17{^0gVA%BBfr7l z;(&8@3-^r~0r-SBh!(s-Hno7qYqvU2VxWB>TkU_nl>dLu=QPY1u)KvL=(yi25Q@3u zf}r*cve2F@Ru2#ReIv$zD)e*tycmn8HG=V%tA>T?8@VqdXpE2XjL4JWQ>t2GNCN)H zhmB3Zin%@)R(wQI=)C8UjPDF#Y@5-wBn^vNF|uMgL-j!0x;bzpSJABL5?+b0KOH&W zF_oyyc-?(KQRC?SWW|kachAF_jjSj$9W!02ej$t@tA{(p-M; zHyU5Yd?zc5WY!owYmUQQ3=>HS4!@NoOZ(>QNi#;DQEfV4+Ob|s(? z*T8M+wk>%mj`g?J>6E>C5b_b9A{%ZW30m|*KW_c&2?%gI*!;)U4iYP^;U&xXRN^;H zY)mg{2$o{Y+DUuJ2U)7l=N-wJM@xnxsPcK=jAp104(ah_N6_4fyNNCyLR(tG|3S)( zct|;1U&{=66@sUf1+&Ao2p0qFk}nRluksdkg8ok)l7yb2t$zO^xxC36b#LP2h8pJ- zUc3X0NJq$qC`Z67RgJ*NTOmg<8S7mOB2^HdZrpNrJjU^v)DHOJUiZz!nRK1uk&omL z-3p+rMI$QugYM`DZ06_pk7QQpa}_pN{Y5sf8P1-#X{6k9Q^fPpXz^L_{etvW_%Mmp z==+!KH%@`AAA!i9uRMv=<}-TS6uPCB-4i{;!XAhW%TER+GKV4$&sqQkxoOR?zrE zz~2|G3CHd5<$v@yuh8}Ol^x1vL8184O%NF&&z4!MhC0X`JjiUdyyC>lI0SDu( zaiapnc*olz{!Hs%MSmG(z0AiF+)ONpk>D+)2;XqnhLqKgYs8hJE6&?CD-cR6jK-`; z(X$yaF>M!`O}4N!+x3NZAX_O2^?yvgc{o)6|Nq}gNv4#LWhzNgmKL&3A)+J-m1QbP zvSr_998&frBxIQ+yO1^8jC~gpvW_wKZHyVrdd_!xy+6O}`u#iC`D13zbG<)q_xpp= zW|ILtO(;n|NIs%bvMURI+?z+3gSzWIL zU2WvJp5it&`d4BO5~RBSURa*LM?yT2d2)X0wmp!gpKMmX1xCQT5NNQZqKyuJ&|)I{ zS8%nqYF07s;3wj0_$}(H# zBsJ$ZE1|1D=l+29!Ti5?1_Z`5B_0*Nf- zT?;OU1smrquz8>=Zk8p-a{Z8T44KR((FH3fv1INm@=XUvp*J0`YA2b_vT3_W|IPLj z;@(}4AC2n#+q0VYwup-^@=-)X-x#F@w0W4dehW{D%k`WR{v|It_CV%GxKF`Q=@EjI zka6|CG(=^aAmTjV)&9;LsHa_W?LKd})G>o#sa=*Q%bOk(LS7!K>Da%tT)f;SH~G5_ z=pP__OFe^+y|QuokBmVYbCl)^%Y17{j_-PCIji}DW6Qn^F46@ljaM@NZCjrYU~V!= zN~~2uQH^UF1M7P0-598}3XY{dhV3wLCzx>EhpCT$fI?r@$}bmP4+l!=?yR6-HR!(A zGV4JzKj65HSU>+*mI#wSU83O~oBYY;L~nLPZg8M;x)aGc^x4b9uJw+Y7l`P zHqd8HkWkJ4uPpulXE|H<3Vb5f|Zv!2y?wB14JV}ckD339evt_MD%+f9| zWI>F%MoZMy=0nGy`Vh+kL=ars>2?s2L!rcRJnai5pw&+QAPh%~%@Lnsg>i3sKm;_# zw~O!|rsnHS9~4)vyIU;hGoQnUXMKf_A&ljcPZo4T+ddy-Ut} z>cLSSkL)S(7DkEr{CLAcs#$OFho!Ul2*mYSw?C-q2Sqe%yD+~O{%)&W^8hNK?@44+ zN=6HOhijhb+x8cK_|@HsV5bd}?EDdF@C`gec4?DRRgw?UBxl#+T|ekGs&1GZHubyW zsCTANKarRsbN}0FWh+vbC^s%YWm$6y7wwHqM>3 zwA$N->-b;LM(4k3X{t_vqa$p3_nuRG_@wq<5cqq2*O`4Cxvj!CpNjrE+MxZdbb|Lm zgA{saV@Y|BY4^*LAn?fHw=~`#AqSqu7~L!1N}g?1mfZdd3^>~7;x4=dl~UeOGR zn!dE)H)*od9C)pF6ku=?dszc_@kd(nm+w!f98s~ECGz-B018|hJTk53>p#aDpAmDc z#~|fEU(k}WwUg_#$ogBG?nZON(OJ!Xs14zY61g6D9cixS0 z<8MGDKcF3YMB&|nb|~j=x59m9_qQ>H{p64rIxGVAuFjDUw-tNh`?FT$Y?k7Q@EudG z0l|ST+b&(mz)Tew6;!b0dF$93dWTFfixVyYMc|=X&Y6&s2=F-3K{KmmAVJAD^5 z`J>s5GL;Q7Bm_Sh-##k9z-Ul}rnbnqAP~k~#4@}%`5zxD_m2;yoGh-aRR5B6F6jCm zfw%RcF2Ao#m|nT_$IfkIFXqWaQlaohOU}H0Z_Cri19uS8N9vDbKHN^t3UB8weDQU3 zpU|tWx>x&b>{7-cs#2{Szze& zM^wqBtCWdXtj6Bc4M%i_91P2Ua$ZP~!o_fV`5IIftyy}nTMKeeaZzq{s*5Pln$q?% z_R?PDy8>cFS;@LK%jD4>b#W*P>MmJ*^x^@_s|!*ZhiWf_UVkBl$L`?Ud{kQpGLnTV9RC0BJ32-G>={a8ki8 z#p{!A-pTnq)P7|0GeL_pkx}k4p-O_@W64b~PiK9mXLq&I>|SmAEVg1#=Qf>hmir)p zb@)-2ln>1tnri1JLXy$RZjXc^>tH$NEoQ^RXCH_9X%QGT@V~5>^OxeJNnktPww+-wf0y>ubv|#D z*223h;yx4p_3We0>Q%y^PCjkFz;G6dgJvi8!p`;VdBd`K{wE^^SuWDl&PUZ5YtK2H z)oF`L=mwXeTeMdn!iAuQC#}c}_ACYO118N}cNFMD^Kk|#DBeoap87T0k6_JeOd04j49fS&vO=YOdC&w*lJH#W8%(EN@N9L`Jo z!Mp$H(Y>J^VJvSQk9|k@)UFpz9+}y9jQ`D%#RjdRaQBOu5kc`C7vKF<$ZOOV_pVD6 zWgJ7Ce3rD4m!WMJQS4QEC(VQz5w^FP|0r26xmr{AU@kz0xf0~Y$A1H31KA@DA?K#z zX~Orj9&zkZ$qM(>p;@ls@hx)z?mG)ME3t$6R9Ww<)a1BV!favo72?G^o&CEJed4;{*;wL1iyE~EvW31ejw;bBj1 zN)uHT4q-GpU-nSmvr#QbTYku!RknBic^e=Ng9a@$O5`Y}c62=7floFpC3gGGr6xiN zomE>&zFN9mze9bSZH99FOnO z`>vX*=hIo-F?)qKXTPfj-Fu#LyF9)lLa16xT6b6U+umz$rv&^v_eTuzvLba31?#K^ z3;cLn5&rua{Uk!*r`-izXvDSB=wf3{D|Z!n?WU-9;KZ-ZEa}%xVe<0er`y=92{2Kv z?YTbWWALfK7mV^KdOSW+6opygI+Ma^3=Ne%qG8z&%yr{PUS)Tl=}cc@p8?!RWKNAm?k5Q-BAt`|@Z= z4do?=iIzBk`A1)y5lJ5RQ9}GS6y8i@>^6|^w)!&TNO|zvltrV9sG-Od@6-7*9`zHz zoCa{tW(c6INqHM{opk+Wmy<5{>fZZe9U?M_foN;>-Nhqky%1s@dTSed3X8e*06>03Op_wwB z^@K+!#!I>d6AGZZ;@weju1>Jv1Ul?ogrUkF-0YG4g2Ju>rJZM@@E~UXULS4+2mXA# z;|BM?f5;c{V*;AKgK($)lH+t8>Bekr5HxTZdr0abhW7Q)JAe0CZfa)}+`rvzTOgES ziDShz+iR>G3vos@>YA*u7q0j~>dFVN#;oTxf9=E6x`V^>oO7ViRc=0kl^gvklWmCV zG=;dMS8g1bF=7RVJB&vmL|0A~ynCD{-7Bwrw;`MNGH(Jpi5T;cV7NYD!HC`{*loWv zgIUF$-sgE7$ZO0#UnNbpI0=OkYTA+B<7jc=<1usxpI$^JW^Qv!8q!O=&QFBK;Y{1IQH?MCs&9ZiLV-D#}$N_`DT zneDjx{7QT^L+e38Z%$WF(LvJuOsAsO(+F~&4eQynB#8%oCcGv5onwV?7+rL@4Wc+rZLdoXT+` zrmc1_H5qY5?y?(XCyh*!d%@LW35R-Fwc|{==>NTiDDKxQY9c}7{T%#%axcp1mmSYN z3+j0P>&~R?DKVI*%Z7T;0cm;Hc~YoR*wd0%e7@c}qp7chz6hFFZJ3&uo?4k{=;IoR ztuXH9!aNKpX*ILf*AcY1;1gD2Zt@{0{JBO`j#1vK0!G&N#pm=WY;?fm@E=AOv-l$f zq3VD1e>yONV*kiu{XlxR65>&a;d{On;)lVo5s*Q+lTI($h6_DMUatV5zcP4$)(LD! zg(Rx4#fmwGG|Q<|%bSrtOtTWxOcFs2lq`7{2=Gs3jC1)n`G;M7a1>!AErO_c5Fwmo&6>&7T*j_ zUSKHG5w)Tkzi5WW;#`lu?{1_bJn~0;Sqk^G_3@_$? zl`qblZ5cUToH+uOrNun$5~vP+pQO`hq;~G;>x+uqg;{Yg5B4C7>Ure3?()3*dY?yP zmglU&94_E!NpGsuS739J@y0#zaIn7)GxX<=si ziZZs~=w-qsjQ8|Lm?7Scb_Na1ByRW)OHqZkq+o_PxxNoFGa_DtKt5n*y~zkk_w`Gm#(&rJY_JM;kChaQ#53}@! z`VYPv45J(3cyKx%g79*STFoM#kk0bI{10t!yshTC8O>s1!O1;x&gKO15EbaQ!6o3W*7&s#mB0fO1@`X9H3`j^gKOW#0vx8AvrmY_Xd#-|Ab3?u(= z{(7uA*#7xH@qTNEQ$?u*t^b^;~}H(?@(wf@2gdOTV2=kUZidhN|FIE%kX8U!;!eenYm^r%IqU z5@hYmriQ#4_xb6+?TTnW-?Rs(irM{)^;XoK8ZPnZE7DEy?464L=-VQQ!4x5Z7rzg) zsg}jQJA^s99!|s(LQ*DT;9&Ivu(}aXLSRQ}T$2-iF;2@aSLCWr3O58d*^dH05AN7{ zP&RM?g#sfnX6G^l5uTfJ2Pg>WtCtv-p$x~lL&U-G;>l{ePKiDYD|^H)#*eiT>OhOf zG2)tcaCD!L7&Tvfmk~7X_eol*&wsib?@6!FErP0%MQ>eg9po3ECvq@ zi+qW;b+C@kNt*OO4zwKLU}?LM`faoz!~UStZTJ@WwNVGn8T)jyA^&hi3$p*GkKMd{ z*XEnee1Dmk{G~vc#6r#WE4!XB49(A)FN0=h1)hAr=V=*3|BvG(ePX-rZ{YlRTks%!}0;-%%tJPppn7|h1LIK=#!?nRJq;8 z+y0qs?w=C__O^l&nxy$`HNAV& zt}VyNBi>yhJNZ*7bI+wM273@ zKpcgFuQgQ}^7oxMKY<6p8jYwOIs$ABA%R1J$fcL3^5Fy4eNc|ZE!wzyJShhH-A%QY z>IPVbBp}|%&BzZQ;y$>EWN~A>XvO~Q_qs}ZZB4tJ(KLUG|H_J$C+&I+65qgrL{0|D zF*@Z`SW?R}nBTSfzQlI%>#Pf8+`JUhgBG?aSya~qG9SRb8H7W?OavbUidgwB_1Rzn@v^UxgjVJ<|75V-W51w4c>X#f-v@Y zX9%Ts9DdsIexC-=X={F;2RuUzxpdJm<=YUq62;?6+kwe;nvUj;;%Q;Fl3wC6qR>PU zd(dK2$FVcz6l%!%DWss0RN1_rc=&EX%yKilFk} zJ9FaiF@vUa<8y%g{|LIdK&Lz;H#_R`kIr6KJF_g& zf5>FXc;w6nqx);7`w#EqOR#W1`;hiJ=zVuRC%AA^br1X26yLq4iDI?1Y5~2-Fa9ky zm8UOGE5wA}d;gfNq;X~dv2#M0C?QA+(0#KH%U{_r^AdU5xVwOnB%BCagRx?RWbZ>*f+hhQ2=YE zGz}(Tpw(t3q5{;ON>B5L@o*f$76ENkO??-sHG2dAbjQ9ch!{)! zD@`^gt{zx~1KR{5=GTuOemgsmC3{BK5QEr$E1H4gbQ$^-NkLxZd}rAdfH#OF8faLm z=Rbbsm&bQ8yoEIC?=(3g+^W*;7}Q^Mu0Xv4ECozYL}r+EO+xZ7M}hlxDA{j4ozxcH zj$8|L#-gMEYGq4q>~Je``Ga<07*_fH)Ybd6{6u6=roRP+jbNO%t^#wOiBqc8b_P)v zLO@nE^mDJEWjDF~g}JDX^?6T~vp7|puHwMup1-eR9XQ%yH&gl2wFWwEZ!Dnu zQ8utG5hf%8GoX#9w zV=2%9*Uu0%;)g-gjxlD(zTZY{d|D90>c{-_PZ9U1e*=vM{6Mq&NUXwU$Tbj9JX0VY za~&FQVqIeRH^zEy;}DcKK{4=7eflfkhkotw--rL;DC1M^w3-F<#WqJ<2r3|XPZ46k z8JYC+6NF+MML8trRS!63hP~##wgw4)q5XM^E4Uhks3pF7c8U{B;JAXAAcYx6e`4A~ zZjbWPTuv#-i_6?jg|NhzCtu`*AvDxY-KQQNw#*IlE*LwzN)O;CG|N--)JVXn;`XtE zhEIQ<&6!F(xN~qz7~ym2j(KMj2JuZNrNFo&>g(^6;DO`m#(Ite0MCV-dlQ-M&Js5< zWI~|AAP=yO8zcQ;$u<9|T@Ak{Tlw5}oAjGzsB({qjPhewIlspUDF$s`f;w=Uc z=_6zd{3N37{$&)@{>v!vfM-+|tCx^(?7Qyr{am|>fcKF=+PNp2i*KR>9!$K9?C2;z zFD={k^pPuZIB5@0!ES98t*m_y|6=!E|JL7Lo6r(HfzrM`HmR|i^2*3!gYdC_7>314 zVoTo2?q&-Zbfp;^Q2UhBZz*W>zK>e5Boqr+_Rhi24f_D-$|% z?%c~fPh|}<5_Q)%7^+*7F07;udycEqYSrrv8-e;s+W21V=VK6S^6Nwk%ntS4zhu_l zW;}6OS8a;Y$>dX0VImeE_~2ADTz>MaqGB{0Y2O)hL_hM{$0Q(!KSmr11X#+M^fIcJ zB&(!tVToH&e3)3q+ST5NrY$jC;@O7su0iXnQyZntc*Zhbtr`SC379xoriAr=>ToEs z5$@B9b&mk}H5$auHPsG6-s($;XUKjoMzBpiwHXKx5# z7Gs3bhgcMZFD(j2m}A1ADsdcmhhfzWTc2k4tET(W&~oe!!VY#; zYmiY_-`1gFJ@l!PdssYaYRSV}^G$o&_5Df(yB-?ZzLT>M zsCjYr_{|t;f$OTLJVb?1HGJaS56^t*G%B2ZiE@uaHQ#PLk<{ultV)d@$SwHz;FQWB=L(u6 z^7(`{$0%BBze1Xn^3Ns8co3uD!~Ht)!&_;OAOw9XhvXk3j+&ImOv zrOtWkQT5AA(js#Yu(8&c)|tt|;T9e<2p^eza{l@L8`fozOY=qyE8dKu3JYm?NDGo< z_7j-6)wPg?shGy zr?gGWnuoK(s}|>{Lgw^JW*;497GTIFKranJd%GhJW&u>?5L^}I&L8}_w29lPYobhO z_@_br2!b!RxOfmWBNjJ?i99MT)|lgpswMy;T~MWmif zl0pr&vx+wx1WB}SDc_EW(MHaK`oMDwnk*ZJURL>3yVsAclsUEp$Q!$Gu%-b|u{KDB zhCm-rU;giq$|ZhEbN&CMq)=YV=tMhHFwnKv~KRrQRk1k^)>cZ}}RWv^Fk z7{t9<(#oAMBD7G$Ev@`~cMBu)uE^tFm!W#+q{X>XCFm0IkXXW9mfi{U;{BH_J?CfD zdhV3-puD1IexT}TfAw7oPJ3hp-rt0AvWlW8ZT&rq{5II-24(PCRxcnpyBHBs#Z5X1 zCpWYToM8_q*OTUq6#@UNu0^ zSNzYNrxI_y+0o?*{Og+I%ku9`M6Mh^fZ3zpxPWw$s&iY-eldGASbmuLW%)HnfK&;! z?+@g+?a+;Vy{}Z2t>o6VCl1Xc_}H~cFjUWv_PQas4F;d9YqIoAh9m|+#1lXrdUW-N zC#i`uC=NCXE}!csgKo?b$P34?4Dn+B8i7x39rle~SW%^3xP~p;`pRCo@WdL)X-Xc9 zP#RGJQsMWipRyfkdD!_;7*logZ-(&a2Q)l;dFRhX9ft&e%a|*q?+|=w=h%9d?Xm)a zG$^%~R2zeyh^uAF;a#`UHAX%-L~Hdh6}EMr(#)C;X&Go((VfD^v>UYIn{#Aie!=$% zvT~M=eFoO=;48Vh#$pzag?+-WL$wn}n)5g8o?E;HVj*QrP;!&8C5QPYsHsd4poFo2R3rn{vHFuU>zqAHg+maA!2C#r1jMq zw(}4qfx2oD0K+}r)2S1LJlBs(hK_y*b56~ex{NZ$o8i-=oIpEgZ`MGHSlu|sHJGCz z`#+yg6!#{uVQcLy@-N)^@80l7G`BbWxb$k#rs$U^5MdzzpY2B%rtC}^5AU<6@28wL zjjCLCS-3mB<`N6IuyK%e;1(BFB4<`B0UOc=?d}bb+_1wp7DMOFljTc-X8rfr%^jI> zE`~ZzYB=71Bfzf8UImCDW?g2=obqClDhCCPO6z1WXRUX{HCT&euYn&k$S;N&lTllc zsQMY^^T|jQnaz>OsDE_77Bbk3v$|?L-ej=dy2x)S4Ko`&y`PDX?pMMsHizWQ$;Dcg zL*TG28pS4_jxRz&w7t4alEj!fuxiOvTBMPWG5S8aCPPSCgLMdkwFwi)-oV>m$63+K zb@_^c+qh}9HHdYf!|I=8f&5Th0s+Jb4PWo~?#_dTz_f6Pm%lzZSp;3O9`@?P%Sa&5olkeKYpTeCgo`W&g$`5 z)g0Q2KG6`aCjc?-r7jP7&AmK`mD$3fUg-u)ixY}kM9o=9>Y*9AM^4_Xn-L22U7#uh zrv%-vXw8XXt@T1{EUo_;WY*OC@u$7lLUIo~z*4sx)LV}3)A-i&wba5cT3$W~rtUv8 zh~g(aMTQ-tH5N@I7cc6GnIe@=On=i6y1xR0! z)c}J|--k+{F3(0H%bP+@_N?O~vSfS~5!lXCIpo2-rFEgA&By%BS!zAA3vlL3LAR{ejw*Vxb%k&q|cMw>{X(#4o7P@|s1cS`y>b6KH_o2{HGp zOV{mWp6USC1>3yNT6us_fQICw=HvT?Q<%j{$2b`iDM5Y+aSDrD15I1&8-lfeSd_qa zE4%POUMqe=^xcWd3NhdmH>OB8XXWU^U&uDSx^4xMnX!I>K@bYfy+C~=FHIyon_L?v^-gcPos(#z;0(j1}<3k>EOtc zUF0dw{QT={Av~!7>323YJDO7_`)PuoPG!Z#dVVGwy#GLxU7xl#r?2Ew3{Vy}1 z=^q7iF*q;E0d`k>Bf0mM)K8fA*u#bXU(b(U7J4JUnS>1vF5&cn5ZWEUhw2gzdL$Ud zIlsmzy$CqoxWDNbmL8`)*uQsQW2DeGqA}~C@Xt}fw@2R|*{|iF^FY|4op$wG4-foa z1qY71qx9NXmgfrej-57wn()!f9~bAZJ8l!8FLqtIgap5X2qQT7{P=_Vd8)*U!LI| zhlaVAbUwB($!exu9eYn{@hviV@+*6%S87A!s|!R=BPm#HTmwY}*VyL|qJ0*c-?iS3 zn*-q$MElZFIvRWjtS{45VXo2DM9f8I-N={Z;OdJfpC1pei6$44&8Rn6TKAj9FaHU# zxcBDWR>;(O)Ajz=F#+f{!Z@h!NQV64YZ)KGT*Lq^2&<=BS#aoCVBoRtj>~#i!|!l6 z3w1a>kibw)KJjO&AGrE$s#XQOEW`Wo^xD>=9BA^K>foQ}ipkwyY%^Ff#w{O{N6Zey zDFg=RrBmO?@Op7b1VdWYE2zF4TFy($*?l+?0@@a#6!V9^mz9iZKi!}S4Fh6EbTpCu!HnmsLokiu_#P*qXA7Pj}45n z+V60VW3vpuAO32y8M^QWask!K=|D6)Bzp{4XEA_y@mlscqjd@i{vG6V{_VAUv!D^x zw65igwouwr{P|uHPHaC)3EvI>BQ>>HIoQeug0a@5hhs&M7hyb&%CF8TO(+cdN3bAS ze4#2AN*iy!bqyj3iYra*YmIq9T7&#*bl`J?t}Abl#gJ+>m`JzWn*i zmlQTrws1DFIRPR3NUz`Pt28P9UYV^Q;oUbJ=aGC@;<{-O-p44;s58S||7$7~#J!za z?N(Cf=m1lDtbQZ1kzmlT0H2wQiBwxwNR{-yo8evXsFY{pZr7LhH-14JHJe)pN@k}4HNvOj@wi8 zt>V65QLxJ#<3}rV_9YMmy);@YD|V!}#?Iw*DjWVu2)6;JZa`)y=fmCaGD)>8bg-M> zN1u09Q{^=YOp+?XM-AJ)Xc##o^0t-gaiuI-%zZsd)DBR`liR<3OM@F&IV&JzFz^s6OANlfOBc4%t1Tqt!tw^bXQx z6^JM6#yu}~^0COMg*FzioeUAwjtH(*0;w*-JEanlSqA9qCxKDm5D^LFdb;Wf{xgQI zkOC)86yY))pK&PS58`i*d<~i`@Cv_OO1r)r!^wpc5Tkz9mcOxA3bEgke(SQJ`%UDB z1a9XES{eVfrh<*8GrymKAK`B`y8~oqNT|fCHoaULi~&z!P2p+BfVc zH`sqvOPm5!Km)uYyeu2E0KmyWgdJ(oKYRBrCiQ9`?yF?89_kPWp(Weho@*OuCC4xj zGjap-V6#;EB2EA%CP^29aPp7m*twkcv!`(9=TFngkXArx9|1(}-a+4YGmHmd3wG$)v8D2dhD z)UjIhxq*2()}@w9%8Yb7-aw4={~5bsrILIUy~5!D$M$To^TEi;(&`N zzhIueWCAP?^=9?@g`6(E)VFe#-GB3V!VbDbUa)xd9@*GsSvK{4xDeO*qeIMhy-_8@aUgdcqH`cs`TeN!LC=(TZE<~c; z5S&5}D%C9~3#vnP68_`;c)eGLK8LzS`=TAD(WBiM^U8FzhXp{$;OdCj>t zoN-f{N21N9D~Ug7PK{O`SD*P|qdYNPpaKQbQdQK)5gT)I0IErh&I8`|N!M$`icm1K z$NvPC1)s6HlNk*>=stY+(aU6X3c9YhyW#pd1%=ijPTy(kl1cH9P^EfqIdzwaSuMn{~N;Gcv%{Jud2!yFCD_HPWW+ip%T z@12K%jkwjXauHy1JU(hJ0-$y28e=Cy^fUY>eZN<}F={>5*?Y!@mv?>T=E3Zc+io?H*dn z*x#r~RlWl^rjHybIqiL*UR&gJiC)7%y5>io;p0{3H6roeZ#MF$3-jyNgN1GQ&BG%2MKw4CV zp%Yz85W%V~{tW&W1YB#naqJ3fP&ETWY_Y@!t6H2{>Sc2=01BUi(5T1$1mr}P!K zv=PP;Tcx6EA`8%Z6ebniY{n!}+cn%5SII*Ty6aDZ-P-NAAtP+8kQU=Ag`_k2y~+j{ zX)i|{MQ?a-{PsFH)j{9M5Q86rTHJo@7XJAe=gs*9klAb7)^lDc4vyP0kvZhItt|m8DAgK!oRCKlkGd~K5%7byz7B!on}Vld4Z53 z6NGHhSDFmJJvp(}mYle(XJwYCH>W^Oy!$b$qU9Hus8Mmlap1A1E2?JAAMCc8?am?K z#)xW6XOv+1be$C|r4aa9{NXd6}JLA!WI`$;Ect8pf=lDEjB z9eMtkBpJ~>e&pllN?bRTTT&{Qb@@wpY~1OBPG(Pw21}h^2;c@;lm6ogONRdI4~CLg z1lb;V9DR{3w@imt;B~;t%P$wvD{S(32>9yRF9bx5mqR+=m_)DG%iaU#cF-sXE??i* zorgigmf*2p)(fnvvbJl#09C3(4-QHDy#^l~mJ?@Fi97G(ZcjAOcMh#5vro(yhT(k3 z>r2KJYx6zO6>Iy>sIA1Uh2dh{GAx9L@%^kifbD#5X{||=D=l{^2)SYI$tYG66PGK> zyxbYtQ)qj$)iky^aouEOtBQ)#ZZk^wHoWO#lJe1V#}2t8093z`0QH;mQw2B=ENq*c zyY~G$$y}D5xYU*S=4}0_R7M3o$K$s4(vgSP#$#4~(HD4UieE*4Uc^6&q=eg6cu{fd z9KFC!&||BB=GXHvC>Hnwb*!pL3kce5vEWq&&HWbs6eg}6cx)yzw{kcYXs4+fK*gs% zyxp~rFCakN{@<((IIx&`KiaMwY$pV?{s@rR#SJ$(BB(yYqc3e97@;99Il%9gagQwV zt0%lH$aFN;(^A54G`v#!{3`BjKU(+Bx;O>iYvf~a?t%B_ZFeJwxzDTc`|3-Jt z+`gs`iFhzQ%OE&*r+TTE9J}Dy9)n&@h($B#JGK6FN=}IX@||q%DKKkrp^klNknIe` zEnP#D8T=Kg1|8f=HXlLHC;EsnFFhpaW{`6< zBDqv}+_^bnscw|^z~$Pl{;Oky`0)*J{)%>pdtNOzeDTp-3LUE>~0t4(R$7{8x!#q@Zwd{ak$T4 zbG^g(Jxw_8Z8FcR%f?2%{oi~|l&l+m#-7$amU;eNm;a(=nVhP@$9>pp_k8hQ?_Ws@Z3pgriE6ZV4Uc-!9uST$lXKI!~dp^ zyDq{kS>rg`twC#Y;_Kop2;)Q8UPAcotYqg{5892B(_re?CW~Uu^rhq4u$@-WMeIc7ZskKi;y=lg$kWTB+TJlVUzn zeF&1@yyW1xrWKq$$A=ZImPfm+x zGYa6S2K-Gr*4BFOWzlO_Bw0_~94B6hKK7&Z>1V1{I8^nqt~7s}_2@$wjqG)EA1myB z&3=H(En`iuoEi1bOIK{m$JY^Z>#jd^*xfE(6Q+Q4{hhfg!7i4z50UO+;J57AonIY- zRz6NBGAXnicZUj0RMCkSDQ4RVVhNM$*SC;Dm6TWvRHh!6r}$l#P!^b#zP5cyT~)8U z2S`YL4!VhazopS)zmB6Q(eB*URU9)h6@G@Kt5l;70Sh4($z{?j4&!!DAts{UDsArX zrD>c3WT}3+`uh`Yo;^qY8txgFm|#1|eCMnJ+6@B+MGeAIw@PLLbl&Ul7;q{4O8D}= ztPproSZZ?0ieP2pwZ=D9-ca>qG#7(n+VAneJGYGKm{$6x8JAtw(z6i#`hsZrddP+J z+KqV{Q)Ppfc9(|KgId|AN1bChl33>(t@H}HdoW1r%g@`hp^&BLNzjOS02oIe0NnUO z7Fh4yFAzzhOu(;)8$n|tE>9{Hwm^Yfv*c1WRHsUu%j&Gb@pC7A zMy^0kCRuu&q|avCIQw>Io7ejEGTgQ=kVACYM)*l8THv>8wwAs}0^@8y!2wM8L zi;o!Axih9<8o69ugzKo%Yy&1v6i=p!kyvk+`sx=l$c$nMb|QXfnyO50w=}KrW4jE; z9$P`is;q381@#(`cSRME6y&>yQN_mlt;UwS=!j)y|L~(k7pp2UC>Ly_RW(&Q z?{ze9a=GoXMDmQH-PwA992qP`{I(S-Sm@gc!tFQy7WeGbTCJ67-xhMuYa$C<7$2`TMihloLF^8IIcFHDwc+Ih#n6Xd>yFy5nsmoUY(1EX%~U)$>N+_9@X- z%M@X-Z0PXqfVmI%G!z$bBENu0Tq#C-T+NKLCG0xz%5))svqwbV*#BCf{CufP>I=kk zBU9{Kaj|eknU4DWzPj6QObwNUb%#=9hm0&c-xUUN4-GsiZuV7L)lE0azEOX3U34kj zOh|b9QqCqSYxyuUOQyM^RE|t}iuC_Ts$m>{yPk&E_}5DpoGxb3Hr;K?#VPOvTb7BQ zFY(#}eyi}ynjnyn{A1POFWiO-8G$od5=p8z6lZ_NtegY7^VE=|6^BkjN&}D_K)20- z<|BZ<6P0QH5{h(jFj>hEYOO`8q8CU13PoxpQ8;@^{D!SK&Wiz`f~Kh+98QTkMO&+| zY)2kYEv{F^>N;D4e%|d~lWdDcHU+mewp1#$lF5crFj!RwtP7(ehcs$ax*6jKRz9pB zCRg2hU-oA5AIe^= zJUl`=SYI5DqjIta#$U_Ak=I^lLOx*Y9d@>LD>PpOIT})&H3qEv9~yx#pDK2)<^NdS zGP7>!v-#tJ6~UbZ=DOx-h6tjMLwpM7cjfO^h%0tzK{jJQI`=?Mls1OUkNh$}ww?)p zuaJ^Xfphsggp=-7I?k)aRmlIyFo<~)avr6vPFwYEyJVSnu9@e$Ka_&y4 zF1t$iu!4=iv*qG*`Pjky@sQ0kju+!r@|U4p!tM{HBaZkkSQ_-Z9e!fmUw5gEng|@bLw@{pjqISKhZE~U^G_aDMIz{`vP^X-WcVe0uPN=dy|6&kx1y6Jz z5b4M=;NdUjffoB@!0VNsR6(E{6Y4fcD6%7H5@#44r1=bkMrZK7TsoGK(030hp5jwn z&!jIA`zDo_teX%bB7wCm_Av~TO5Ni4y+(VWc?z@xEVXB2z(43gU1HS*r5M~+hkZ7V zGGOKtzj=p9Y=hO!(wCaaY0+aS)_Wom7@!yj=4%Ok0fqGKT*z6K3Z zYkL+*pBSVH7mzi?$O+7HDNYw%ao$d)%qtk?*xxrZIkfP*Kx6yM#;yGnGRZGZv(2O3 z-+c?Wy}P+>KV;)Fw}lkvt2ezgnNWGcrr_xa19*!z>HXAF&5rpk<5KH6sSw;Dt8O=T?FrGGens^>e<>&J$Rp|9Y@=8n3(;>L^6^G@ zkI!kYM`+8abnTLrd71QKml$d?n>6$rE|BNCw7lznC*x3?V#cnXK*!EUH)kEkif0Zn z&dh(f(AyPNe)xLYP_zF&cqRNToqOE$GS6KLnNrbIu}JntM>MQ-+b0JSoA^A(c?WWe zU8W67T1t{59+r#n0o{QfY)h#^Exn4b`;*nU@;uA+Ot& zt^L%(U!q0-Jzw*Q2&-QnU6R5wv7rS3a|4jl& zxRqtv&~ zN|H2$vV>BWkf{ifeHr_dwd}hr`F#ezmXu6K4_Z)-pn+uRlT0Kd|lmq!k@@3EGude+3 zQggqo+dY2*FIUOk6TnI)+!f6|ye{E>HuST}BS5K%%y z8rKikcid5TPd555Rtxx562rvu4j}!K9FmC`6PZUPzdOH{I0~hyb&~IW)9^>@?s>zn zBx_@WxY{m|ZxDx2J(p*rzL#2qthBDaz|_w7XEv* zNNJb8s}5(=5E`ne@4Xl--6wqPYM}C(Pe#SEDz}j$7$QZCxGAmYLx!f?CPE_SH}4}) z!;ax{=Fwd~cflTI9Kb-yH=Bbo$xcfU`~*xY(yf~`-#rn)D*4&Y+JUn`A_4Wgd4P&n>^YY}#Yew6b)1Orl~&-l~qx@SZAoGvLtecm)PIgMfC%A1egc$x8zIH&EtBb^&Eo*_@<&7 z&#)sA*Sd_Vy&NvpO~NNF^Y)&tyIqN@Cw$GHy1_!=Kblbo2VOo!JqArqd@blTlU&sm zao9rM6Rvpk{it1<0RQESY7!6Vrl&3lY`aW}rrtP_lyMhb1;nxvFNT)UdhJ6sD98bs zw-_`;xdQ%0X1{X^R|iJ71@J3oqdHJI;T^}=qY>7hWr2q)HGo~p>?~pfp58hdLTWfx z`49{hi3~TuukY@HUv%b_hjL0diRrb$BR(DMx`qhPFanIePPFBuH&eUh=hjrVq=Iwb zY=tN?y|IA?^FY?K0m}QTX`J49-0sLWiLi|$7U8Ix;CXy=XBWxlJHrAfp%cPaN`7y5 zZ}Z|;lZio9Ql(v#S_&j|2h6~M`$h-BTwX(hFkzOKa&m1pq$`a$4Zox$hyTMKo&NUA zc4KtOr4QYu4v}PYX1)FzDfpc(nxr*f1Wo;qfy++@L1ZoaiCjYk;Q0A7SQ1`)@d-Gg z=#WBkn+}>=xR04XwcB%+qJNPR*@+BeuX(@1=jkey>t;9r+smbz__*+tpRJ&+UW$a! z?hecC)rLi}A{>1VI3YjXGrpTuj}px0Xxc*_k?>4pk{1mo=Ys<4$>>rIyCSQX4h5Dg zHo$_l!*0wF)F20b-eRrYjEnN;AZBXzmzNkYxt2lW{Hv)obu+W;wPg+cPNO<8dHoSRL zSvCJ;zK>GB@b@!R&EYb-&f4@qi>M;F0*Q#(sCM4!=WLfeCF{o8#6xfx@MV4?rzt#a zyC%c{-HALKc^x;pxhpq&wRLHrcT_V3nWLc`DfIUbO;e1KSQoPyPZ)2$O&RQ(LqBd& z1BbqIzVKP$&1$)-H2CXOu*RlDhC2^hw1z|%vf?Gt!?(89N5kiN!y>k?g)q=hV{5?I z@i;d!p+i-4&v>sw_`91$i|3knBvkV;l;T(=#hI@4r`G!qM?TH?Ki^94tl8w*?VXj?-WG34mjouD~RtotgUKb+uoqFrvKr9i@lJ2c2V9ZA19fs z`XT&}HxkaD3}8yj2c3Sy);$W^TTO6ELqi)!;YH$fGhY%X%cf-*SJ2UDGLLeu;J+A@-=x-OGH3RQ?8tCtu)Emln)W zKley7_U!>V#(8lrsU~SY9r1ZQMfj-HdfPL>f?5<}T;QbsW-0ECpT|v&m(LpUXYn1w z@VbT`1LoLu1o46HGo|&>^HY_H%4(-BDLNP=PVhlu4-^5NccRx=yj}e4F*YBh`GcEZ z%BG3|9|^K`zMNKc+4oD?$E4#UUAgtsyrOlFg@7@1q01-P&z{Sru#8_24Uim!Ch&~8 z?PFDZi!q`DY?jJZAxL`5XP_@9Ti_bFBM^)f5_+h!geSYw-Yy$?k@qOwth;7bHb7xJij1d992@&FX<>BP3c zPska1pOMlWhYjwI-g zAM5rQgcmsW!OJ&e*>bNJy{Ksd3Q7;>cUa}Ci(yCwFXXyq{4%KHFaTgxTzn>gx>=rt zc>fvHr7ffH`C!A|v^4_=@u`poct9CY#|5pV0le}PuzAalm9EUSU&PmV|MfS%9B{#< z_50;=t>{YkW%;0@?tTx@^G`^$mITb_+xvw3Y%}9j?zz=t7iSAz$a5bpxW%xk4N?>H zmL}9)xaIHH`-q~eb2>U_{QS6#BvMM(KHV5a8k6!~Vss{0xTJfWbn`++g(z7I92n8~ zp?%{zD??wf#m!gPWv((_crehrPuoVXKvRC#da#KNnM}`C1y>c)erEw7YhjyX`7lmP`=S=uLe=8*corKHx$$y zE)KLngABUuB=8kqYs~um??7*VC>nVF=yKwV|MnLWUk?62V%{IPWJop2l+m?j|FHgX zXRgP~FX@htbVrAfQZk$wdv{a0fICg9K(*wX-|HVlwdilDclo3jYt#*Ng8j1zQ}@8H&5w&K6`we#rcn3N(n6IgYn5brwovD*BQvP z`pJgJ{1wxP{EwRbfowq2!*&9z#v zDd}LO+*zEKL%HOizh%&lZ!M&^+oteQM$Dpo|9jy}{qTCcckhwucPQKP`ZN@A$YaH! z1X+$xF3NXV%UX4-R}#+NmQvpi+25I{B!;z@tL9!LR;=lFgjxYvz~}cG(N5De<-gLD zb%$MG=a&tngTJ9>*x<_!|1%ke&hu;gHwM_h$AEl}GZ)yy_vFtt%&YP7(#i)FqaGT? z>MkvtAJw>&1g|&RT)cK>RpgFp-kq-RP3ss3wdxgBuYgf-=vs}BgnQza;Y0XBbmnIi zS4DxR&${wc9JgEH1e=%ln6<8+rGOgl4_>gnq*uZzJK4knG0|-tN~(Rt{TZ4?ni$ki ztaYJyQ;je3&l?Mus2l=k-IaeT6I<_WUtQlCNR~}5DUD}xSR6AZ|UAAz!18-mGu`?M4@fMu0x`+OF zB6RfOSUCw$baTbqgvij5$Yk}4(P_Buy)1#aLahR!yeWnp9XI{2w<15vDOCrx|(3&y_^fO1NdCO(;WuV2eNBT5HG~nqj0G(W$PJVrO(NeJKV~P2=k4`7Y z`KJFQ9Kt-nKWQp54O|3f2n-Nk$C5|>*roXYkf;yjnwjSBEI~cj=>XWN+Oamz2GZA0fo^fM0`r(YrhgC2& zDMA7`KsNd6l6*Qw_mWA0^18n5Li0_%(un7f95Wv>zsrVA+<+PhaBx@~=3d51a(V+? zDLz5*RXukPSuIYG3`P-)$?#p|q(VOS?!39hg-ia;xQb^5WhxKx-^;ANV8}(w`Pv5u zF-r+K@C)BrCkJ)@s`!CBBHRz^GM5iGEfKo==?&dyE61PdJ^{)5Wpm#Rw!P(XiCKRL zC^f(`A^TjJdp_g+T8q0Z_?o_}6MLAkq3GZe=GBh$uEE|Tda{#0@z{Hbyb+VxDwtY4 zF}VboSCL9#^3xfRpAf)@!q3a!D9vY0bewzt3Gc*K%!xZtPY!7{9b+kiHVtul>sFA< zKvy5`h`w=rQ$iTR08o#|E;;Xy==W+Fqzw*kDAKE(z zFdQRF3-%=*4VP9(FujYCHv3P+ZYN+d!S39Ml~P>!*Xk6Cz5Vt?k6m3Lv2d(#<`b+T zJrN_a%!eSFx0`=;*?8#k*#j$kLQpU5uf6>@Tsu3CRkm8Gx~A*7x!zl#2&I{9^s^i8 zryYty@|DFs#J?A0Te<9=^Iz2OYdMngpx{IM+zNooc{gDjVj8LLnXc^3-0D{DlM0$6UQuQDhL*U;wsC01K2_PB5ZC#lkZK>DqE*y z(Asr25Az`Je4EEFjL%~p&3Fmxz7WpbVr3~UlcO5GP63$)d=^9Y_NriP_%-9(zUm)$ zII7-;4XE+e?tsG37>?9E3Sh1i|)ltc(zJBjp^T_^XK1~ zC;mU7XE9?)4ke8l>SX{h3_LvL4? zi`t@76Vwl{S8rAiNd)nv_KXI8DnYhB6n{I!|Dg zb7T~9-Ub0zEVRj;IO6uB=fJVkoyey{xm>35*_73+C*GYlqtCl2MmG^B9Kn)TF?2T+ zxN~dxzgLKaj5^L74 z9O&UC= z*bu(|{ITTzbi?0Uqk~%S$CGVF{#I99mN*xsohLSY=yZ#~^}Tn;Ox~X1S2!PQZg61g zoV$zkxWV@YpMrwKa%zEPbu~83i%_46Z2B=^Pt}ZC$5#BHi5*SJ&_mQFKK}%Rac#8i znfMEj;sO6)*(UYJzZ)^-Pxt8FOh+hGk3fwk*?m2#_K3_S%+4rIVcuA6?x#E4pFPc0 zDx~?1HLVTCed)uErB>+aTLuxKIeEFAbkA*Ixt!sn4$KjbT10fu6Xq*X{L#LBxS;c3 zR?N^gOCP!hhJpbbEe|P}^!%r184-`pua*>z_mWw6O*#cdMFfpHBX7-r_dFnNQ&3=L zuax8v5)K{_;-EOuMPrZCz+~#_X~`qu9u&NH>SkWG;I7*GE`#H8_kL`#v7@6Gh&3xo zYpE+|S$Duh1Dx51Z_u3ccXw=Hj0A9#o43 zk)Sr5SAFZgdimX><@DY^-yY#98iJ=#xv@@(cxKI?m|FlLzDj_!8sPJv zJ92Fgu6A~&rgv2PInZLzL=#E|riKiU=mHoR@*ri9RU~zFB0^RUccWzoKLPLG(HX~g zo4p<(A?cDv*=0?Ur&Ia#HNCOUB@5$`B}0M|XR2-PG2WAWW|H9GMVIPI_3s_ISv_Y4 zkqy%dTe;GK+2v$}v-`dtgTtYSS51$_2huLh_S6|pX53nZQPE{kib;0LtUG+irvZqc zAbhU$u9<^c1Hwsu2BCrOR$mD+0^^fI3a%$ ztw!|G@Av=Ul6$mDvC^p3q08^SEYf7!RL=$8(3LvJICJm76~P+fIr$C=?q}x?NqMAK zI(l8c*9n(MY^SN{8SzT@ZCYePA5r}{3-6yHwt2TE`CmwR^yA`_sy2g5TGp_+Be`KX z8xe{U8!p2fuJ?3&pJsfrA1~H@c^&K~+o$pCiTb;?DaNBC^th((994?2<%-*%i^ ze*JgGcwulogb?$SBSuSA*u_g*{3m-Lx7R(ep6%%^U0KTfhLl`L%G7dyJkJXefll}! zWV(!Bqpw1ZkA&BDLO9Y0(b~KcT~gLa&*)u`_b1aZkMAuouuNTB?awIBcDT+sA@f%~ zzr`r-MAfgU;FYQkIwRbab&|i6VN1fNb|Wh}D8Ak&BznKz)f@lmqM83C8FY{ZIO;WiK25BI}BqlNocWU1v>N{MQE=J@sISII?UTQwFg z@YQowl?-mjsYtrSv2oL{Og?D$8}3|!r7A78XzY=ql8{}8$r5vV1WG-MwrFq|kP$Y` zm+ldA7ZaWAZaw>wtt3JzeI^*4u%la+a;kUffj_WB27~9deNFYJLusgx`__A;OL}WNl@~R zPTDe6LWugFBg1^RO(171NWAf~YmlG3=>Rp5Gb$5BDlTmyI4edhOvcLRKGFiR*birH zjOyWNz(N_ST=SS|yvh^=7Q;_nUHDf^Up{p``F~|~cA*=lwMrLGvqOCI;CuP5K7W4Z z#>iovqY^fue#2CQ$QOnCG{?S|{C)=XSgD?SqJ6-kPFTWADzW5I7D}O6wFid#eB)3i$lg6^DIGDJ#S`a^KYCV{`u>(vq ziuT5*abgMLYdp(1RgyrSIA#kpXXmPF>`BRy9-KyBWA?-ytcPZUm!*)ElO3Qw`h6TU z%|h5`RVuw7qlA=#^3Xd-9jx0Vx&@pe5Bh;v&kel!+oF31nYP1Fbx<&ia+8z0B*?)~ zNB?0cZTPU>p`&{d$R`h*Xdo|L1E2o!G}v_XtDdA>&y`Qt=Bm&l5&_vN)mPI9A^CA+ z6Mka(Q|+vK6tVgFV{Njg9MZ05RL9A#(6Zq5zTO^v_PcjII0fl$JEnekPdyP;4Kw_x z?_OtbML~x4_==QcwxU1zC`$+Z7DjO8+OiQ3q+Y6~J`xVvxx1q|pb#|WPA~~4Cck%Y z_xJ@h1vOjbbb(}au$QB8bJo+IfgM^Kz<^`=mp&;$S2*QyaEB$ZuVopEJi0`|Z*AYw zl{{U!PVzYw{?P0$%6x*mHufAIytmFO4qlntlrhireg|1H%bia{k{%=mZ1VJ`s>1P@ z_0I2za!7RIfDL|`1aP~s+(M6Z-cvNc3NMXVr{;$d)oSQPcGfkO>f{N(bI@PrJGN1` z<+>SD-oX6@&*E$fC~wZs&}*jqzaU-h~s>m8Q<73jYb{~}0B#V!lMeNmfy#aJnb zGjGK7OQ(cf@xMteQ02&eTHOj*N=j#I<*9D##*}$N9B|z-VcQ?`qpn&za^@28HG-ck zPuEQ&x#$Rv6ty81NdJt$!Ry$W%D6QnS3j7^}eG(1&7_4{80Ef5vq^Ew`AH`gr~N>1}oCpNIe4?{KVq@F-I9(6)>MrE4htaaG0V z(o1wx5j8!X<6~RkW6uoUuj8gvi5Y(9=0%?Gk;=^#!8&`2>AcH5Ms)eFDt158=5f^% zz2fPr98xJF@l8cO;Z6k|8@JZ*K9%8WCC`-pG;|;BJX*MFF8$H{N>KEwg@u6BEVUr` z=Y+wLdbaU}o9yaXeo4g|%!QuScloz}A|KjsQHs7sK{rl60WC-OQH=Vb8{w-h@9qu` zv!;7HBiQ67PUFETz0e(FQkHXzTuEL^ki`@Uv#?Eg#!>8*t|IO=>rMKo1sTZr&4&wO zoyz9@e3(rY?S>A}ohKv;=JaS>?T^+qrp2xf3qjvg2DyVz`e{BI&{kb5j9uBHx(3u# z{Uy?UYGA&?{%Nyon}x7Um%RSUxyJ6#6(BmymWe#wQ%Oa3y5NzgA74sECdynDXh@Q- z9x!G0aVZnBiVt$Q+E1GtL^-p2J`Z*L=bhg*FlM{EJ>fE9f$vCNTcU0fdf)c94fOp- zL1>W<6TKd0V(sZCct`ixEt~n?^o_Eg7qH*lpRN)cWp{RV3j=??iOaX6j-`J_jbU$I zl-MyzQ)CXP|HpJifI_d&bhhs8TRIu_&Swn}U$peAOJK^=17UiO7Rc|CAvZJnxGjuA zOQo70;t6)KpI6H!GZGfC_Z4u79ub2d?p`YzkP7(`c?vOhcNZ@y8~U%<4bldQKRmF7 z2%}Hf!&~Z=fE%0TaqL|eyh?IW^$cprV|t1qu*KO65Eln;!bSEgj9_sxt$rpUdY*yU z5sFhk?#Cbl`MsZp?X__2Xo_Zwk$eufyI|QBLKYn&^OakKMA*dM7Ic%)Ct!5fr@O2m9r2f~ijFRoz&2>#qs9qa9-xKLPh?!U4yWt|^Lub$k}ot_2-A1`b}d zkf;N5mUn!77;vuN)E#ApC_`j|@Y)P0>v!{mLG0)9mEkEFIHz&^+08BuDEHwu{{EAI z9(R{MC5bs|ExU2a?-}Yy$7t{iJh$HG!2StPfB$z+f&Qoy zw3U6&>HM13htUR}$jc_l)*ppOb?-zaJM*6luG%_x*>&>JIh~x+z}Syp%>4b1K5xpL zM9eJaA8QO-@T`*O``(+*gG{SHOsAl*(@xA9*XfKsR=HK&i-79FgGn$I`+Ub&r5&-S zY}I=gzsjXWGS_K{tA~YpDNajxCD%MgzMSRF_O{nlcMr}X?H*%u+Or^*N8clr-+0~j zVP2~TehP+>cCM7lt-)T_r3_B<3|YgWR`JATBW$+94$I{agCRh70CuiW`TVh)HspOR zDE6@%*!ShY;|r(Cw_Pj=`bz$m4Udt9%jCh>!xxZbbdN>Nj#|EtD+y1R!5`BSzBF$> zCkC2<$#k9Iz!$z)G|3RsAHOJ$4`CC$Yaun-G$MOd5&g2Az~lV~xf2cH1WqkWnw()q z#-I*6gg}Fx1i`<++A`rPvGwr3i~8gr_tc`1-*Nm(R8b_mVeYI+j9A+tg;OQYwR300 zpCeyYnDSh*=%^;s5Xa}a$4eg+IDn6$N<&1XqLTbSN{#SXmit;5Ip#XLD4LoQJq0`) zd}=hTt0NB#5GycLn^D~4U~mwtVF~af5gM;Ur?2bKXFUsabgGU+pUXPp@T=Quoa{jp zc}9n$oSEvzh0Q0-$7B4*?5IIQP|Q`(y~R1h1=9@W?P6unDA2w&Xl3fp*D{FRQnV)r ziYR2U5|>?`M&mD?NaXK?4PrW@EK{Cn)H-{`!_{|a&fh&SoPDwKX%3Xs#Y@9j&L=QY zm2!3=u%|K3Xy>xda^gG&ge4ZMd&{adf~qlC_K7uJq>d1T$cMW#qxKL~wJ*>pAqF$>IiNDe^?m=Px4L z^<4*v8oypn1e7<6+3s~yKtK-u$fy~fdOq}j$V4P6hmZFY@w(vN-ixo1zpxKv#YEUw zTlfy%=q%}$+}j(+Wxw&W!zAiOUNoUxrRVztoo`s~=r!8{8yBBD+S&&NM#Q2HwFRcd zxo6<6xfB>4V89TE2iCj1Ky&L?k#`k%vb?5yeqLe{jj!K3mI@71X>gV@ptibo%1H3d zC#EF?BCG&)A@S@RkRsHE9Q)Zx0Np-2 zFIA9mzdPz^GCJfCU%zsdW1R4vxzjy)=`Q)5!OV$S$d-kFN#X^JwQlz8iE0z)C}JK` zh03G9Y_m=p85*@RZ_-`$Z%5;^y5ajAhW-BI?7o{j-z6$oeN>Q3t;y`4udDU#S?Ldf zDnEs^f6vV8{ntr;|7M-KzgN?+ zqeYQR0;f_Ie8v-ReR^*)G@qz=NdY`Oe1v?mjqgf7I|=3|J>Zx7-130oNCj4UHP39d zm!O+q%dc|!6^ZrfZQi!vtRb9hhb&AxRVF@@6s;Snjl16lOS zz0Art-s0jqf%zWv(mU6Fb(__@d5*Nki8TPJLvCtNhtm>0 zM2Y!m!|&G`-K=T?mK`|%vV6Q=7r(MIp;w@Srn3YdXG{gwK9+O;T%1SKq1!mOf~B`e zK6YIUk3A%O;SSt=VfR4is=U4Fd}6hdoLSOG^Vd`{#jR+ROK0xIbqYhiA(#qXWv$yW zjqm?wt*W!=ir;`fn-brQOwtflYlHJpDE}maKU;BW z=KCVF0^HNe1bt|myB84BX72y+&hrZ&CZFx&piASu0tDt);woiuaDu(s+pkHwAN^=5trP|o92AFUf$v9?A>@-MD%pFa4>h6_xbw3!QZqo z4Zk?zFO7J)BwtYSJC^PKRDbN^D~8RwpUu~Y;+JdNB1?@9lt>JC;kgIxp%`TRd5H7s zczi3)z%VtW-Yg?eg>BpfI759nblx#kVFiaK$sz%lfJn~-=-iZ409wRb4;C^@; zpzdJ!p7GW2Z;UK|OE=r<}p5i+H{#Djb=-Q~E_fNzxgIIh;i*M*iINv`8 z#FwMKeA0;0=@q?VkE8W%S2eJ;bbM}$=VeZ93nnM}w+?^Q?c%#P(^dEE{@vRHiQ!#$ zq*91H=TBK7B3Ju`U$Y$6ipR3T$E9Xh&tXzyQ%AyFGG*)8-3_Z=)O_*&bQE^z@!*=9 zSX&46Dmx*X;ahJgJ>J0*D=!{pWoL@d06T9YURmuP1{+Ye`a;>}|2+b`CJ}0RGdG8+ z<+oV*_gh6W{niAb0yLa8m`vm<$Fz<;xw%W>Wg9`9<(FMRCC~=t>~n3qVj1@o_4ub+K&S%|ZZpnL~8@d)D~S#FC_p2L__d$8+nAu6(db!RnPnofRZvoqFh zRtA~=p{`dW_bM%#)mafOGUt!(rp2KU)Oo53RDP%E7}LVdi^a<}6%JzQ;n9CXt|`%M z-Mr2Rv%*u@ndq(FnENs)jte@@e?k&jO|7Hi-3!odICEP{>6$hL`iW-0AjJPf8glx@ z+b4#~dj8RUSE4RO(v|ae_*9(t^AUAbz7&7CHSFrOWjEG!K)l$WbC$kCRd>8pOLU{K z@u&18h4-cm=T>(I954CUBQ|(%R&U71SnX0pHB37i_0MNh64r)u>A?l+>2mThk%^1w2D>ysPEroc;oMwUMs3bBF+7cEMZ52c=G!|v6|V6h+8 ziXoX%y&hckw~bE(25R;bY)7_2+MRTPNf`Ja=2@nrLqE8+H_AD()kyTpP!D#dyyYCm zt67n>*~w5ICs^J4XIpV%BbZ8au!hiS2KL$fIKf;ZF|-?ca zNl04js3ymXtv0z!eZS@AT$s>qDk<}#?0#Wd&sOW5eo2#^Pk-PMb4t`7Z|X)Id#v^A zP%AR)sN}w1KPyF44@(*+boQ3dy#aM9*oaKpkyvMOtH<_><^=6mNner5Co1QyphU#M zcDVN(ew|R?5!ui|wJ*pzuS_izGD)ZSm$8Qj4s7GqT)uL~k?f&`*OkjJ$;f~MgV1Lr zG{B$}rgsqNTZvE=I51b~04X8@Sp|VD=Be@Qcx%9ogbxg6{ZX`!4ov-Oh^Wt+Z>jeA zd?FX82n!Z1Mav5pLy&G9~2u?d^0_uU?3FYEm230?)ex2y9jpf<}FRn7=%*%`pVQ!DX{= zH079%{{Krlhkph;oqzA($KkVaBU22a-Q-MtzyERl?~Khi-%TJnvP6>4#ef@|HGwk1 zCNcfyEYaa^hj@5uh%p(#P^4X=?*yoNAxGJ9@FSrNq%zLgchS9h4#R2Gq_ZDG*kQ6i z6oSFR)VzvPP1pd6yc>YNdG+S`&71$D<^Bnm|LlsMzx5ytEHN^Ifqxnf96s>GX3go( z=9dD(C-e8>ne=4QJNqm6F9!~NK-2Ve(u?$p#8mpf=!Pce<68>%3b@;Pw1F&n^yGFl zyHxqI#n6nNz1^|kFxWa4wGQ!te|$vAb%N$U%8l*z65WoZw^>eyro7rNVKwx4nl%*N z*2_*Zn}oGG+K2Zdj|I%1Rt5iJIFgVq@h_A?&S+yX7MR0TN9-^Jip$e(u} z@9F;DX*;Cl+A`r#V5kI%aY=Vu1@NU_E#pct$V)K)& zLlV7mNS(d0Yk*+^z_0MYfwHFvK|w}PSE3mcs=2W#LDQ@z5{*SQtN5W>havkl1rs_fLeVr~N zhu#92(xkZLw?!6@vQF?!K5pFy{+;{(vH)lyGF!!6wjQlwdtU0Ro;u&I|5a=Mv8Jr;>}MRg>(Fp3 zslDX6*bx^{Pj^TBT+t8)VmM5UZTsh;zIPf`+h(sbFHO7aa!Kc!uAfOXS9M@I!lx89 z;yfI@?W#`2-vDN{KhsHP<(pM2#Uy&RZx|+9j(2xE{~Dy}S2D&;P<9``v0;b0c&Ia7&R;;emu(#aL(WY_)5Zzf4o*bZ!@Xxr^O?Mct|59(&BJ{t;!hOmc74*fB7F zrN?vxep%8#d~k?t@A6FgaveG(ZeJ9!lCA7!DWV!OK@8Ovt${{F^ZjUNcU{G9>dDj` z;AlJ!fIa?dLCByB`qfQYh~f2BUHkA3xUHR6Fe%%ikJbjA%Q^pU8~ykgDx1Zo;}H`881#GFDv=H0)i{>>vj%a1rq@LZvfLh zYYyEQ#tO0j?wk`)Uk;UCLY*+aGhw}ho5b!AG=kI?k%b7b3#DdKEeLu3ZNOZEnr#+I z^*d#B`Rx2hX$~F8{41qy%=#&LiSbXJ5tewCRSo8*r9swYL%F5-M7@04gbIYBK@rm* zchCM4J<>%vFDjj=uO9XEusS75r-(NK;+05rUr@j8C19Akls-=w^reHG9nmK5HTKr)~w?474W? zJ1hi8st81daxy_?2mdR-VN)k#w&l>ooS@xY@MZkB1qmw! z3#0F+8!L7~HUPn)f*LVNU-3WTLP#`RoK*PY%Spd|KQzU%M7 zz4{mbE>wa`+ua0kSnD_KmdS1Kz3HDQjXTL%rqT%+d#&vQSKFHPlPj%q+ZC!`KUJts zN~z%AlcyDPf4`|l^_4AK=3#0~YxTo|+}s*+QXs=4 zFMqZ4@lXUXJq9s%L{{se9#ZY%oU7bplu)_T=M~oz*vULCJ2ekg!sIR-&DrOIn$^x z^7h_$9>ggIK7d{KO~oa9jL}>LhJ&(#hdK4=UI#FeuX*IjG}_jOTgr$>E3%jKT|tY& zc&+(rWfByN|52<`?dPv*&&?Sbm2^%=Q3>C$ssWJ2kIQA(Nk>m!{cS&^P@uQiPzWin z5nk-n;}34n8iQCib*FR_Rco9DHgP?MGHIzBZdBWhXTuyMC-E3oEuWdVYTv>v z<#u}v=GTuIUnMGykZ?d_V=hh8VXz^NAQyZpWBK7IJDHh;tHb!>Ako51s8Ny%Ri zM1wxNz)ND}wFev5$u(6wUYMSKZG7S4vmQq z0%3pWH6{q|xj9gs(*#2(D12bW!iB_;$*m_~v{tZ3#~7O;^4_*~cQt~4X7rd%W~9_( zO8Ts&8aXD*zRo{J?eC-UbA+;#<lgTb$w43JopnCa>MO83=ug<9{oWIU( z84K-#kjcu6t#3K^5Mpl{g~@+)eeiW*Z&ZLTr>F<~ENR>yb2CakqO3zFm&olAmxkz5#yz*h_i-ZxMSGJs_nzAme?qVmd>^RRa$fU#*w`Hug6Nv9o2|1P7=`M!DFPY^3{HcTS^JQ+0Nyxl6q4WyCTATm7)lW+vJJ>S7_tG5u-KxP1`HPn&K` z=T=Lq!*rxiCYU6MPa~$*Se#9G?*2k8mLN5#@OL{+zgl(8vnqa?R0s64k%iNd4fu65 zIC#3${t}t9Vjh0=CZhoYxBE8LrMv#Ug8~0K%79;A8@ZxxL^V6Gdx%kRMobYGlw@mtv0A@lT~9SABp2qlFw2hhCooViw$$VmDt-mqnwvzM_qrC${~{VNe`u;T7997gkN2OaFvjI1O*w7U%UUlROejHA%9`l za>;rxTtWTgerpX%m59xa?J+*D4r`gMCk`}X5_;bdKUSEoY!IY+eP&{u&>dS{m18Su_^Yq9DO8Wvvl{LhICpCt5@RDHd6iQS!R8%v^m;>t13+1fg!MT^mdUoP%lDxAp?hwRvMRVJ?YDk;$W~eR&G*Cu~~bsV|02 z3wo5osO;=~5Xm*PXDUNK=xzSy^q}J$;rOB4xneC)3%=#pHV_^=!Z+3jNHk{S_ty=( zRa7kWl+>O2tiIN@^G%NF?#fADgq5ZdP~$}F^xhTdC?i7yB*QUjPcBmEBrY8zOE_dW zes7Vo4By}h1@k###bd+MaV~S1u&~7e7=M)x-Een>7tzSpgf+n=c0YD zscF^Gl5^@V_#^JdLz|eUIQM!@8L0UEg0vWUlKSjLz-r0K^5l&K%q_TpYAoPP@)pQB z4fQyHcL}zWsK0Zj40GYm#0bh^66?@wbBR;wt900leHHf-5v4k%LYN1=v6*B+7gNG@ z7^)zvSgOP-3GETp3UP`2U_l2QEgVrg0epN(Y(MH`U>F9f#qmi>(_xzYdJP&XUqJq_ zA>em#DaiqEfncm!wLv6n$aaP~0&RZgEjPT^T}tSxF*{7!$bHduB(~DhyHyg>z1jr# zw0WwzXR3O-@TnljT4-p>p_sFlxt~=$WTwiy-i=$jW~9 zHnxePUk5W2n0>K0q?r)cdzbC(oUK0 zdJ|C^UVCbM(gsxT*6O$B6dib<<%t1x^fSTC_ms%|w=?HH<-1w5i5OSCH-35j{h=8L zhmQ(ymkx5RlIR)vW%*mw!8Iwx8_sR<s97!$48-P+51()#ixauf;?8Yeja~ zpaAKoup&pIl=H>R7y~9j;8Rx5(nSOG=No}T-I3$m$B;QBo4D@d3>DtTxls;p(m$8q zkhAp;btkwfpsEJs!XA8=dzw!S|7=L`sOKIBo7~WfI@+y8IQi(cxa}F6A={S=xlklg zSf5?uxV zwstDr=DG7aytMbLBvLd><=2z!9wb%Yi8)-^{RLn(ZM-7sq(EM9H$^=rbTe3$$zj2p zPF2mo7p|q?$JJ8PnCaLH{y1r91nz8+3y<=qelnW$q-dfGLk zH+S_8>4hTMUp<>)hl3 za9liL%0sQ)ceHc1i&5kH)6%h-CX+ir?o7G$U5#q>Ml+DXLD-;?bFZs~E&VWNfF?D@ zZw!@+=klvv%`K9#WqRh*;E{Kx^48EdrN&!fs#1IIz7x1)$yP#Syc?w#lm$6c{VZST zcrSETJK4u>g!Y^Af{@07lJo@K`V)Pp5t3wHM#`JzJLX)eSot~6NH}V?aMiO>xQjwq zzkB^^VY96VYwP1Qjw8?#0pDdd!h$k>kfdae@d(JWyw8-vwe4a8#mVa?Etsm7O$`LV z!7#Mn#IY;-5DJKKD7a}sv8CaiM;1&ILTvE7JfK{u$T=G!W$0>Cap&kUv&ApC#RKf? zS{mN2mp*L54c4amNHGr1>IMg*IknX|$6qwMZE|bLk`(17S_GFHY3IlqRWlwb!HZB+ z@Aa$PujTML8lF^3O)fD5v;d)J4|N#5@zo{J5iua#9)T7$0N+-gK=OhnZRVsINd#dSl zXF!{t`542;DHdr9Z$b4zThrb}nN;o<1+suU;Q~|e&7%tj5Jz*ql-GSOK z?D|Qtxwt~BPmG&ScY}>oKJsIB)nR<`iXbuEWfD(YYpL^=UFliNienxCW1BH}iUQ zW)VDuE1TMkw7*c-{xLLjFud#B%a-6!Xki9ftbDfW+#CJEMm0xqqYR=Ti4HGzi=!!~51zD(9>3DB4aC+F+y>w;B1vtr+@Y=|8T6|e_B$)JZ5mPFc=~^x%Ctk6XF)389 zV>UN20n~x^P^)Wv#IQiE?;QwQs+#u(92)8&DX;>{+xcmkrQc*gt9hhtM62`-f62tuN`KX}l&|&l0n9TlntC9}m#egWgd6Yk;349XLV{V%D_1dh)+- zpy%PCKTq?|8-G3kI(mYK{@lmDCo2D$5^#e8kLBTC_x*Em=7s`~?yVf!sNdJHb;Co2 z4vs(P%5&@aLxt?b2kdA6vPf9sr9bDYkjO&;Grn9eq4{qq{g?vfWtTta`cUCAC1s8O zGrNy}kqWi{^q+Ix1M{b*_TSx*|LVl{`gKh3v!+yLrfe62RTWa5q!`Ei>P>kX;M;S!vp>W$o6o{#{J`|7~&6 zh1>h;&u;;Mb}PUCEeY>des@dpzv;woZ{)XxOJTP+vfHfsJ*?cdkX;M;+0xi;=kE5` zf9vP$_Sb(aNr32gEo9e1{@-jNy69D14Q`EDgepJ8Sv0wMG1(REs?w+*IHltVbxTsD&BNeD8*gx!=#7%Enl7S_OPNSK}dNo{YZK$EHv_i z|LOQ_g&M2ZM`JIGY@mei;HIilUEP*k8Vl_+=?&NnY6vU|sjI;?F+ABOcdvW=`Ru*@ z*Rq(vIeiNW(AQm6hbko`?s1krjVomY#mhu@fysI*(6!WH)*^{N9|g^4DLnRvVkPEz} zaR^Y62^vz>?+*SaQrN-<_scxF@GsT82b;^M7B3HpcbI*CoeG=&li1~M$Rn2h<+GTB z7gdet8%G(1I>p}6aYAw`oy}zvW5z4;4$?)g;(o>x~5WB;5! zwHQFt6R)v}{$uG66%GS5w!?0Ae(Ai*MY6MfIZ^#|+|s$KkYlK5?j5@W@Po3ZWp9VfmaVlY8Jn2!RrnEc@>M;EN=Wk~ zIK;}UpZu*=sZS3?Zz-@eT2t$aUtcIJa~O139IlwPkjD!T8YN5x2(6h#lcb;Qs7xOx z1zBZ)Q^#VeOwEwztZ7>>}LPA)2KMkJiSG1%@_V)ku(wJIrzM)@D4*FX$*d z2%;{E^$gg0z0|oS+#1etsV9g8u!(7)**`x&A9hN?IF(W@9Wz~WC41IDEk<)k65TYlTsU0 znHhCK2$bNC7Yk#_Q1)q(3 zd*L``%{?}UpIc+S*Felbb%J(FreF9S$s}S>s}k$RawE6a6PP}ooV)Ew2yXWDY@Ek% zKQ4M?KmDuQ#_jR4pU@FVPs;|JH{`jbTBI7x`0klYYV7Mjz2M6e#sS94-4fbc;<&~m zv}R~%7}qzb8Y4s-FH#B}_et+ zwiOMdq2o#^D45~*3sXH46N5cW`4Tc)4Wp{<4rb6)tTIQA52dGv)5IvsYrw%(Y`zs- zPegpMXig)kit=({PB~vo);EBZjg{=Q)|~9@?6M;;{f@Ss?!Fb?1)H*z@4h#7-B~qr zc(zW*DfKdp>-6d5)Q7LNzs5Rsl26X*w&w526~WCgPy>)wgyz!2GX5I zLslk(E@!)Xj{9jzzm@UIottXttt70Z-|y2ZLWDyJN%yN+78~Uy0CedY6`N`tbPw+k z8V;|*=ftOB7Gq~3K9WQYBRH4K9_7F5$|RrkZCl*bu#z# zeYE?hLPOV@6te9DMyC&alhm0GQ@5=QJ5frk_|~pgl>XjhYlm+6E382;M~OI_oY=B6 z^#gS(FN#ewtfW1cMuGnm{Yb6M)N669R%sRmhqs*+NoT8mL_^mVB>-+ex-Tq2*uUmt zI}uOU0FK{qc`SwjQ8ltZi!!Ss6JwOIh*bfC&gffaTk}x}r{-07s&z$eFvq0v&2Za_ zkwF&#qM?R1_~8nl*?|HF8raZb`$Wl}vWx9SBYx5b?B9AG_&d9o+CS=? z(Y81YDBI&N1n%vG>n(B?$C^Cz+1C@mENv%A8Nn`Tk6t|=)d;TgbMe%uZIWc!crXNZ zByc@CXzQ({7IiCDSwW2s97NL+;^3rFr5sb%_(;B?Xl)JGyy#+RJ>0t~g?@vvNQixl z8#uKMr?HgiN>E$S%${H-@J%#MRjzg{9V8PQHgk zM^ca~ad3pxLJvt!vg{f&SrC_sU0qauCVC>eefo`6>{XksETPy-<-VKFQob9vCN4>g42e4>Wc8RoXq+jp?ds}Uvg+5bt+G5dJ+jf`O0Mqo zTh4yHoH@I{Rt-zfA+MCRDK$(Z?{L6%%mtBL#W%fo+u43O38Yge;f7nr{PCz|sf@_s zr>V~r&-8T*;+QoQ04qe=5ko4u<$OIin26yJz!{5sHZ38W#_B2%m1L69lur^%IJf)@ zA;VG;oZBE4#5+N>>0SR&41*$>A(o6F#cGy`U=hawscUC8R%atG%cs?TWp$8&NKm$w zW?EgihZLQFEAGMm>f_i2dSnba660ID4acE_fEdDv$L(RHT+xrM67Zz8^iamh** z=Wk4mrBz$iR(E<$aH#3WGMTD13eQz!b(`Ow$g)XAk8wGb;5ID0QA7$Wkvlj**4?kglr8H= z@I+-f5d3g}W~L(_TyI&PXdJodhZ1(Gs!0)~Y)SKz;LKaAP!=d1$lw|DZsVx($dtHr zs9}&JbDAA$w~Fyhl;m0s9S-jf&@W2WAba*NZ7l0!ZQf{1qqH*#RrsMvIE-sMK7hS= zsQN_dNaa?BtsqS8&URyAny3BkCD~qt#)0qK9@B@04(%``A5S=jrGD!k+`MN(E>PI0 z{3gTq2D6czv$nowec#{0jVd^Zx|@(L*%JbEO-m2J)_G^%q(pfy-+B!?G$A&cNmm@? zvxiH%FakXc!Mu~15ZI4GA1^L1cSw0y3hektFOg5239-sohIaz4U`D{Rw%t?RvcHZi z#&<@GF5I$oY6_S?5_4K2Q~OOJV=VTzkNAmx@35;>FH-+c8^-TBlpthiY$VWs-)WJh%Vm5D zCEng$#wH4#u)h~|ajy5f&sU6_>2rKpyBhj{Wx}@Qm-F+``yy%`wx;!5FL8E%US~mQ zsQf;I*JU_GjDSEZw!z0_hPkTFx=eY{!4Jb7>Hd0-SUPG(IFZwYnr_t()ez(wfes`L zuHGMTY4afib~`-rcG_1>fLaM=+&%Rf2-R#7LBe1 zAPI%qsg)St1N?3NgY_+G!3>!!y_c?^AL?fEciJ46DN@GXd26AcG$ty!A9R*4SW*A*eENcR5SJwoTDN_ zStGTWLNC^KA8@2)%N1E+W&LH!P=tG)-OLV(8?t;y$Mu&9r9!vFku5;E%=0isQ2V)? z6I1_(s8BVNG;iTXdDB<}$=WCf_X~$IoWGCT7^bVSgp9kezccEVI6$2s4<1}!2VNZr zzb;bj7VLAcq42^Pj)mU*D;>U^{BARV@I9>Go!)wZ0uS{Ya(DgH?Tt96n>fq8nUqzR z{1`d7-cq3IrQM_j4&#Jut`DMI$}~m|-if`LKrxOLi4f0j9%FhhZ+z8N|(L6 z&1#brvV}fo=|@>s_C%jSvCB#7ZC+5{_KAi2HOb(TL3a%0HZbajD0Hj5%M@&+q8z_Z zZ8#7eJCykl2N%|d}37?@70T=uI!P%}sKjNqg-I#vrMc)8kgFdn}{1b#^lxd2x3N8->f zh)nPAwA(ZIND}53+7Upcf|f{jfdGKB%Bkvc1Gp9aHN54NCdW`HLQ@{pDeVJVuTEDG=_1edjp~7xG!X+^iFKnrJlX6v9Qr~JWW{O!<=X5 zwWI9gY|_)aVaC)QTG(^*&AxG~sWvY(?t(SJzV@Z-LEYS2lQ?4toGZm067d6maJ@D9 z<;B%dn6Zr228l>ByE%9DXcrY%ur>EX;dn-omSe9$ zSogv})PUyZv~MQ*9dBo<4t&_)7+X3;(Z1VCVYXGmmPnPcQpZoin1WUrJMn0*Z$7sn zvxu3L(62J{agVl*Ve%+YyZqKGv867W2Qo4;G>r~ltaPD1)C(VBg?{R8cTyf(gp#`* z*VNLf#L)S<&L48t8pF9IE9Ju_2MM(oKgUT7qIyyMLfGL}yRJtErE&%f(!VOIel4D=A3y~dv9eB(Kjc@^UectL>m4g$PIa3TlwWj{CXCVu$hfSqWQiuUwD#!Nql% zs9WMP-SXNM)ss1ZzFvJSoohl2c6qB^)aIYAC01-hYwNKy*d&+G|)e#$y$ zZ5BSk`K$}wcBK51T(#K6X@jyWgb)( z&?uj(zrL0%41@?6M|?_Nr&OL#grmf2piS|Z3*%T z!w_s-iXq#Gz9|^DRAMDgHv`16IU>Vb85yv7XL#s`t{bFoxm#G={yOV~gDi44!I19o zz=!j;`Q1v5vi(53{TwJSsH8JNoT5RB6E;Tr88W^bOSet%%i$9s(zpO+&Dxr01O`1U zoNevf7-lE;+?;{J6xa!~=a>SC^lxcGEL>|P_EV$ZiJjOKcbph_!sSRzhn(k<@%aqf z5tjZKIbVC`O^*}$ofo#N9`y$`$s>97d3(0YRau}qvp9Lua`@?CRk#2V8R~cK;Ytn7 z;$p)m{W$T@G1w9L5$lmY{?EmwB90hmbWiFV??%uI6SLX(g+m2;-!2XoB949wZDWWr z>9KR-U;1$ANQ_Hwrbq~8-Kw$@JG|LL_u!LwY%dCcnO=FxV3M>LoK1>u+co|hW_W_D z&ChHkeOrg^)sre|4vm*`6Em#zy`=ByIQQ+-7^KBrtOW=aQ|aV~h{l*WkG4ZPMhhR{ z2#(k?3B;;f5!SBsrN=jSph(wuTBz4{U?9H}@CE`HztyDXxD9z3W@Jnj)Sj8>@xiLi zCwv=s=br!tN=ePQ$gQ8Ih3F-}k>~R?_F+Fs56;cjs&V$^ohHpVXdr~*e1(Nf@RO0@ zHr&IaHmSAieK|>?fsM~zH^&Im>WtL4BkY$uB0+L*wB6Nw+DeH@P!?e$*2m%8Hx2Bx zJ;JQO?Rv3R_|jN>(f$R#QHOz3h7tx?g%`^%fQS?oa6l<9d7@Dxgzk8AdoWrxMqcs~ zDa@3=RB;P_6Ll%D^ydm!_W>XWBkjNT>L`{bIO^o`t*4&2=?{U1A>m^2-@JgLRgHXk zxP`uzjKsTz+I1~`wl>CBjC@!c0hsN0NKWp`nTWi zJbVvmR_Fu&wC10IevYU>25LY=_&Ww*;y*|Fd0{EYLvO2QrnDUm{`}?6ZA2D&(0bJq z#ovFs{pQ31;KLplqBwtbO15OOGxRE0foFGNzht(%W4|ta_Ge`&_{#s6I!;{muE zmIY+*zZs`7Gc0h2c#-Lock9xR=IKxS{ILu6GtCVvd;P&9^U$%7|AGQ=Z}qt!1dzqb z*8xqUf597^@DBfjv~I03qIkaW51QzumO68O%KN$8=5azb+!cMjI4W$V+g3BAgui`U>VRH@hqU!vUhB zrW&o8cuAU(*W-WXC1x4_2lg7XP(Ls;HU+>%!O?=K1i(khq8tBf7e&`Zl=?D6fW7PA8BwRH~|?yJqB7XJ-=j?^B9e z`3v=io05T=gbQv3I7NOBZ!q=6gCVQI+-bw#>ugfPQ&(q`U&@ud>YA!~R^yU-SE{lr zC~KDbr?>cL4X}6BN!>5)k*c$(%k&#%4tH=1-7nFybLZ5HsA}4BXIcO9h~EL%iFdrj ze1y$kJW2&n@mtR_mD*{{{^K(Moiug_ie2;WVSjUa(ty)jR7t7*%WjwhKB~=r=Em;J zb|kPX#^3Rk`u`jS(M7w4@3Jv>*_gk<-Yy$+myOA@OELW!NbK@vf5kZeI~mT#mz0tQ z{)xOgbYK7<1gMB6XdsEn$;qypE6Jb2+2wgG1}BJ1;yatw;Q&NsRj5?#){I4xtAR2X z0*7mOsiZax8L0&LonDKRoC}vn1?hG5(+}6KFX(gm9(E@s#JD9ODtuzPfHpzi!K}>8 zWPr)1jtsBx@gPa^S`6N$>!a9_fr7`WO zKPi{#)x+)Mj+8|DV&^FpZz683unl14NyJHexDTQbl}l^AIs!VQaWY8pNHw5J8>$NF`^5JR5%e^@Tz3F_3n^Zv!!&4LARL%7~g%R&2mkMZG61`V1XJ?4dyW{Ten-lOGEf92BjCu zCU)vOFf{0#TdIKfuQa8D23Bfp4pV}nqes@n4o<@7E)#j%pDgg>VUR#v7%_uHX zF}7Rq0-89pJlDLU#w%?Zq_p>PYsAYax5sDF>VP?=T+eLr5sS&?q7U49fp!-nm__&r zo#IpD)3}0M=kxUkGQI4Vm!4V*G;qZP*=L;_lmi!2Z1uC*50!@+_5^8)55ZICuZsIX8LCu_}$Is5tREB(&Yiw>)j zb1Y!dB9pLsgJ#ioMF=Feve5$9pJ!3q-j;&LIc5QDT~3mrwC~23YDgtiY50`9$qpMO z7*HsoJNo)tYrgfi8faR%(_gVI7e&*_`$FlnGe0;~5hY|jmzF}Y>+^al7VVYNglCex zFH61GV)F|N*Bktnn`<5gc7;QIOPnrf10-Ev7rVinBo;p$qW#JJ8`LL@?2+nNG?IIW z3f)R-sO*FTM5$!#un#<^qSGt3Qr@rp4SKjj`Vdw602?PetQDZYJz;jE%VAv@TqVwR z+tfaUTPGCz%9NV~@0q|aE~WtVY&vMx0MyFLLCS08niK@L%5&3OeDxX6Bnn>jNy>KV z-r8LkC24Spv)PgfW)2Y*#W(vo02ini(pK@tp{lTyEn(K@ zDmkUy_3g5N86%KR<6`^8g)rV3Y{o_ii-&tPWFyoKs~hlm4>)8Z+>} zI}J*tWWZ}&u`@wSVw5pJD~My?8#jDU1=ra08cK5CjBe)ORA?_B>oZ58_yO;&PTm%k zl;ZP7(D;#WQjb6{9^6eBlD$ks zX}5(g=6y-vOANkL?3ON8?uJrNRtxd5;klUhwFe_%n8NYSff|-0<~SfI$0vGvLO?s) zuzX`IE2A>55De*q4z#<5@RQm@0Y`BN-HU^GlZn_afWvg^a6x{1&oz4K?Xn;25~x@l z!$BYCzm1bO`RHqE7Y2*i>4K`48bV_W?vH*SEzXzJUT-bE{&1yRN9XLLxHK2Vhm7f? zyb7`A!StipD)I`s$U|7(T_4L?&EFn!zUwZe7i4_<>`gUahTfK9IEyw7D!hKC&-J{v z!D%OPM*(@Jd@H0AXMJDW#j7=af%-*qoFN}<2M(j`4rs=G);~nutjJ*g#A%*MiCSCZ z>>as0r@~Apq@s`gaEQr+nIziA?k8R&>MdWm7V9636j)&w20b48+l{{5!3e$sAZjIQ z&9~dz6v9j2D{PbdEt4fRCkwuK?pyO5a6-V|-9xEJbX>sy%YD_y9)QWKTrFRS)Ho!d zzmCJqv`2vG8wz|krygUKuCZ2MOa)s5Mx}%F4>9lrw|K^|;#}T4#>B)jvMrgv=Q)n3)^6y>?IU*0JeM zc~#ZmNBx#2NA;<*M8$ILgZl59+7`j#eRZY^0N01(CfAXwyW^f4bLnd^kCtJ>!a6+PDLvfiBdjW%v2<`)-%K%n=iKH5 zGoVBI-`00@hzhpxnFIXR|(h~!F+Pfg;_uR;7C*@vqro;v{EZk zzodr0oIYuxDf-oiQ&r#M#5hp0kW#k?5xwvt8u+r&F$ugw2tnF=)l!P0b-Bqz%tq&N zyG2`hTvn01ERm?Vz8XDvk;MCvO?xr=iY%0V5jNiPebX>ZLFN=^lV4H2&Haj8XXB+Z z0dvuCg&f5Aa`hNjQeo^pz3j4Hg7o%0Pd z7;9>>Uj*hDAFUrMd|RL4J#)-= z%)C@M!$(@_I9d6e8!rW<&C@mnF(N7~+^{9ppZx zbS^qmr-+!lmL4Ch@Vx>%Y$tO?xF?*x`^fRxJN#EAR74aZOjMN*p0f6GwDiEG!uUcm z^~W!UKFn=Bk{YNZSgR=s>4PHVa2euslu7vi)FA?aS~s+E8BP zbJ@66FL1;~Ln%y9%ShUJaoC+~7CIrW?h=aVm6RCvm34Nq8GRY>!pz4Id#@h{@e}%t zOvC!jdvvdf2cL3kshdUCCtmCco_P@Qdi=}xaS53pO$J34OKeqoC#qoY_6B69@8z{@ z77hp;Dc3Yu%q%L5Zq~MyPCJ!V0>Jv$V`-E%8f6z|sAFNd6+$tY2S+D}-12H<5r+Ft-Q0(${SD<*^0)f}rN9~5 z`8y6)0^9M*NBWNkN6tPw6rUwEB@Q;%Wo1nI_za-uiMy#Hj+vkaSniur%hi{n<^(I5 zBRP*M*)aDm7vD=vBSnA`Q6nK{SVdZ=#x4;1j>joeFh+UZC^HUR;N70u z_ap^5gZ{51t-Vs4c6DwwbBbeTV;Yq=yKlgCPg9ncE=(1PXF!sk(9{+tI0WMd_on%m z&VTC~=dX2Q^Q6wMN3GWbmxpvXB~?|sp|xQqqjb<>xpfhd^}+?bb(tnM;n-S5k0y__ z`35SAAI%a&^m@? zIawjSl}sPmYK}1mTpOvg^ZS}b%fcs)X>MphoyfYa<2IzZH=LmlS?*0PY9JM8oU+aXogV@TC9iO_BR90sL$k_Ee=II<_5y*BqVZZxCqJ^z9-GrKbX_b zl_f(a6Z=N_iAPP1>GnBBVhVapICX=#akTOIcd`M2GLp>tE1bI%uKu@o~5am=+lWW4K7!^T*KtH9m#{D$nd*8vt-!UN-kUAMN74u` zx?AQ)!xVRBX~nFCqZE>_?FR;z_jz*`6KtHSY+o873&^~OLU=yf$7O_-Du^gTuYWXs zovHBHr(Qwi$|O)dv9r>ZqYq&jcOtot0O`JiBK`D1ZO+s6)uP~2=mZ%rXG>OAlwBpw z_^@Ym?k({_XX;l@&mekF<1@vZ7EYkDeBkvLc!2a%R0R?B<4j)4xm(24N`A>}Za;&h zyjI811^5kR@)&-z0O>Stz_oseHLEghUBhP{RY(W?CdtPvRdp&X`D@|f8nP_g?vzwk$WEo zjnL=LU#GBK+2+P* z&7;|KDKt&sw-^hPlpc_+dV*X(y!*Sf2bE zd3nPPV8IWJis(a67e!`CXEp0yu$Ii?+xU7~G6F~rdiMox61{-x0!|JpvJr$5*ecSI zos;l@ATCg5AK8|KC2;V?4l+%tCyXE_ShPTmoOK}Hcg~4_-@)U zYp}E#1*5uX4^pSAALEi>UjPnQ(=@v1jdF~UfIK$OJcKAQ%;J_rmt?nG35o&9Ad0#Q zPlheuPvR+JQb~AaiWD`$tgMhsAr-#YYzVifaBHYXj?yGudOS0c1?u>;^AQRKro~C4 zl~|=S7Ms`M^Cgv)MNRA7E<5;W0GODQ^1$I87g?;(azOv>u|oTpFm8D{*XR*|xl2n~ znHF@E*Ad`@j*X^fWf5$Y!Z_3(HO##T+H{+lC5_e62vF5z#4$u@hTfBQ{oY})&!1tv zE~K4dNn21WH5#5Vukk1+?T)e(`{EV0Frk-O^c2n^M>D0(P3rDZ`-{Fgp9NTRVGwib6rj5KGFS$%Fyh|4n5;_6Y1vyHM5KIs1Is*>Q z#AeCqpsrWnWwLM8y6VyQsuiIbW38$c8lUMcH>lhFy?TBPl*${Dq5mLyo|OXMZ;_DP z`%yp6la z)`$UYM3JU(F|4$bz0vPHQZZpfUyU|nr+(^w7N7)wdbPG4ApmDaAJh#>zoup6Q18{f?TouRKt>O3rAUD2f zSY)?{zNVdqyF6j2s_IRfoNtwL;f##YO(_PxYF_&J<|CIiFV?NibIIPrd%q7@tGO^` zR5kpuLSnF-?Hi3h-X@l_5!}5tJy#fOcm7I!o<;i!fLhJnGR&R|>J@Yv@Oq2(BW&c9 zb~miwqqgXr5k)!Oe9s^+TB6u(J7bc55!vwp6_$-9Vn^5wPM;q})Slu!i`FLy1@SC? zc~SdlzxI1!B|Y56FkAiAov+K>I-NZe(<|qDx9D@75xxi--GT_yV^H(B(uNI`ZRj_?y zVU(}quZg`}^R9u9MO9+)li}IyOR)>yY~>ZKj~$$R>%Zq+4CB)c+poUTNDwl6^Tpl) zXd7Iqc_k=w>c}(fTDlILW^wlWqt=9txZI1Zf->k4e#U-&_MKQDl6eCUed9`-JScf3 z`(=IP4q$j3sI$!6c-?U19eA+w3Boc#s+6Dpcx0lL1caq`CAgzNgU{Q7@6*Re-`sXYDb&H530CXj@2WWSagMW{>HA~p&uhj9k=@{E@MYjkhwqLD@onU0^ zCgT;#;7Irt+MThgGpM7Zqa!97!`sum*M2sAfcr!Ofj3{8KdQDcd``SVj;JRMX($7c6sJ8|Z&7=P;7KkD=UWd(ut@AVJo!ai*OtEnAda&+(So2RUi zP8a-e^e=GHK?M^wj|puRq9;sh$bP?6_NVj|5(BCa<>dhH;YQjXPX_G-;{U!6#sz8- zVUIQB*}$_aJ0s52aB)<+!+uA|EsQx$`6B4LghY~=J8X0=>BMIDqIv#c+RqQD{0k~X z_+Ve^c-dn+#mW>!+&5UNL{%IWIpO#IQSl#`2RjC;`(FK}&b+uqg1-C(C81Z?ycnPM z7ly0I^=*c0?3mafFeKqL|L1U$&lBpu-ntj|1^8@T?6MeM!O?_InS`-WUO|vwiw4Z? z)FFP8z|9*!D6ZT0i|pabIQg}T+;^kq826#HpC8NlXKk+@Duf&gnHLbtzNE`MlSmt@ z26_(Nyd5!AnQ(%eq!nQxCn>3hp#Ni~6qM4;PxoINe*<%Rv&0c{sAWK29%h_>#@LU5 zIkCB+9YN?$IQf;XijTF$yGii38E(B?L6VvmMCe|WuwaZ|rsg#>_VM#tsFgGmZmD-U z9d_a?jZVZQv02&q0;j0w^tA|%OXpeC5TL)zf(oV-9y!@&9pM|X55|qW88I?)BcfZ$ zC0Kj}aAmnxf1|nDA82X(z>CaBSpQ|fIH1Ghp4EK*M*#7U)dG|D0f5~{`s81v?y3$P zoG1}O82@F&1>gY3!otgcC>pn;7sYwM}HYHA0WpT7Tt~bLv0@_%m98f4kbqW z7q#jDoO|D}`i~_4H)poHu-~+BcgKE<({@$yA57fBr(GM{1&>|0|4j#W{n&2~WY`x;(+JxbhWY4O4G=U8HYTuE!II5M9-PD6N1CVYGE^FnU?)z!I3Qf;Hqo z$cu-ctHL}!PH%A_0D93pM#w&I-r)lACP5EJlgmDPV-xCGE_o?Bj3a;BU%{+E#ZN}h zzwF-b5K_Td_iu31fKMcxt5AQA?=MDZ+|@qqE3C6ad<0W zWd#x3M^KX!u1D)ssdzXTw%0Vu4*S1+0*t%fX!ZH2WK*NlQull|18c+3k zAVx*p(x%xG{UPdcHsyY|$mc&??8t$-|MAYAu44gt!D)Oya>Gidr~l)eIn)DzZ*wF* z+R5x}S^noc%P}jNrZuB9N>tmL(07Xd5f%JHLL~F{+(l?95-$ETSHJAa=jVV7uVZW{ zPG6xE6%vu-hAwqqAz5L!BlYS!V0Da11^2g}KXbr$>A`U?VNPOp@0l9j(8g_<2k(vU zYOmk$C1fc$vT*Np-|FWhnCL<3z52j6SLyq@DVN`2Ji@W3bihI<@S#VCx*PrDw!h?K z>S&1EkO^t8uY%-CE>E@G-rico5#6`i*XMS`a@_Gmg)vTEZXlMhTAe>EV``bbjjqI^?LXY83+{AM569V#T+~8)r9pABVARk2RGgdPVt}tWb0} z8Wm}5tpY+BJWF%WfNx0w=d!vMKY0`9!Y_M$gSdK!O=&NzZ1G|CmNZ^bQSedEBr=}g z+NmqpJl2OOIG^(+fZ56i$9IQ)3#MJTpSi@$&)crRzK#810KISXVhb`@ESZZ_M`q+QsD*VihIi# OfWXt$&t;ucLK6TOc%6^{ literal 0 HcmV?d00001 diff --git a/Example/myWeb3Wallet/myWeb3Wallet/ScreenShot/simulator_screenshot_38EB4733-C3DB-4280-BAF2-9ED97440A8AD.png b/Example/myWeb3Wallet/myWeb3Wallet/ScreenShot/simulator_screenshot_38EB4733-C3DB-4280-BAF2-9ED97440A8AD.png new file mode 100644 index 0000000000000000000000000000000000000000..7dcb7ecccc965c1073e42799a3c510f098545010 GIT binary patch literal 93154 zcmeFac|25Y_&;8vXhVyXHQI$F`!d?7B$di;L`b$I>oA%&$}&%zC5%dubu2NqnUS?D zGnHj9##llO24jq2mfz@!^y&Hi^ZoDh{hnSgua0r%ocmn&{eEB9^}g@>I*-nuGup6r z$J!MuR%|$Z>cqtrD+KsgtXSJAxSIFLr9Kfw-hV57E*c$Mk%N;Q=KXTQ$>OxLiOGrs zyko%?E5lq@@XlYclJ~QN_p@Tfs#hyltm6H@a^bUAe2ae-;D5Dh@px_L!ihznLdsUG zFj#T=#L-IuD@RE}#YvX~l_yT_IkxBUKlgXS_T7u*J1i7_S=1%7)dA^I*kaB5=Vt9i zFCy5DcodHLmYTYScuILf3Zt`YiU_Z97qj^8zLFCe+_ekVD70(m&Mx|RZWZn`$`q&7 zG4wr=#%ZHfKPw2M5~*H_eqCHNrf_56Xk>$o!j6@E{DLB~26t90JJ`>^=k5E8PyYS` zzu*Uc{=2LBmYw_SB-jZ)zKF|<@k;|{&D$#zhWS_5@!Dfcjds}7h4H?rSfNs zett#v$sL137hDuxEN|<-7rSHdMf`s}#KIr`Ib|Rl_rBo8nZNIEAbWlN|9o!VS5EDc z6*=3|ac1}5_m>qpvidJm@eA(SBqF$H#Qoi-zwa+1xMS77?fav}n}h`UH~SV{6#D!A zg8WhcVGh1WJgYy_wod<#i}ByB{o~^Qwh-tJpgVq#c>o=MBJKYK9kA1nZe0G0tL!fc zjRv@zmw44xIgR0r>gSC5@zMDyqX){QAz2)+^w1If9HY*#HFKO>BYBaExcO`&Pq_WPg#&d&^%pua9pC1B zyh7v?w60#%y7BGmz>m*n4Fze+`|$C3ug-3F;=V>^dVK&BrwmF`Fyrrt8nN%_LvQDt zefwUkHas$OZb??Hr#VYnrkccQx`&hm4HZpADGJAI)j`Ev)+u_iMw)ab)x1n#v#{d2 zJtm52XOk?I;?=QdGrZpZ;U4k@tA`4yE%=w9uA;oIk`QBx4{=J$x*^6^r{Opq-&QBB z7$$W%kIr;8WUnv0K6Q2A{+!nMEbk{WJuEgNwMoIpZQ{sFVv5@LGN<{}Tm5YtoUF55 zbPENQQ!qwE6=(ESH?~J}j@0hM_pY0{ag%)8M{jk$E~r0|9B92qo(T%m^{X9l+<#5_ zw8YSek?iWGA&u;Pp>q|c^>k|jgZ7E!FJ*@n2&l<&td~*N%|4hz=96qJ%7YT8y46sz z45Vdekm?Av@L<;KF5+OaP4^+{=WLBkj+X84LgL( z@l%cqyv8gnsf%?nNhXtzlZ<}DY6VPXzeqt(4)nSSGc2m1K|?y|RoBJ6Ns^~5M9mJI zOVZ9%J38PZ48Eik4?W>l)Or2mBm6sXM}FyviFkBPFSZh5Wm>&%tR^}Xkz^V{?^qmGn&k8Jk1}@t{!I2|4OHq?;lV-~Tdc=i&sS3g zkRIj7M_rHPIw;>wjah4-C`eCSmh_;r#)FC~pmW^_a}NDLvqlV*BBYrff8-7CaPL#}Gw=2w>I^mOVp zcy)zV{R8&P@|X~&s|l-ZVMVO*Qt-;Y`W;pjNS6us(qncEe3e+N`lcbDjS0_2 z@;h$MLeZTQgW6yBIfofW;7di1dO&)E{v zU_S+YaP3f^oCk3`2G%jwpXPKq2{b(2-f0@TK7K=uRBx4)+KW$-VSZhj4Ug% za|r280#k!H?+5OePKOi_z;f4^E9p z@*^s$kFqYIZ_hPYUwJ`%SloDN-XdkvC3p}M&?%a2c_+3l%7}N)cIMRJhsKz4}+;#JXNby4WdszEi^nQu%H-OKo{z9eD*7w`($@0c-AnuJ9Alu(ETT zrzcwMbqx;wDlouutzs|_=(|8Y8dhb0>sPh6ktTZPRktRC0w@Tn03r%rmz>9HO&CnF zfclO_ zTjSDm-iRwzWesit>R3!iNbh7dmS&JAz?>;X2cdkKa$6z{6jPs}PzrF%;K`S5gql;} zORLZvtMc^nvhjUgEq#ex8)eIA#gX}?9h}{CriyhQc82Qf z*GHtF>`lgmZ@glD-C?Mn1d^69uGKHYh$_V&M(1SaUoFeePH2 z$jqJ&Y?^Xwc$svZY@(sBnq-AEEGr)0!ZK?f;*mM{{PC0r11xQ=zH~E}*!~fh)HwJ2 zcerDb_=w}KDxw2k8eL|4TJcw7TYT0VMJQ0OfTV+xY$&dwh)AJ>*n+7w`ztGMhUD%D zE`X+jkPne#J=E8wy{8~%@p1eg-a8I{zd8NDF-E&hjgKu@{SARNC-`5#;nMQJl#72u zTm8Woa`q!8LrIKy#B4lSJ?Fj7EW*qo!;d_Jr)!ai50@#YzQp=+KGUP#Xg!ZOd4_xQ zvXA&SowFg|<9y~3o=9>(J@^f-TL&_1KGShxw~gE`cKtI%3BhNMGxea3Q1b&aU*c;V;z<2I2q=pM#(y+@`nYI8}ya|T%6UXhPolo+r%2V*B!M%{}Jp}68( zA|P@rBBMYEvwK*V7Lh}h1u#i@{WOx*Ua#uvNF+gRf?IelEBv2BRzs848b?^B6xC}< zUqm+>=v#p(wF8-G_q;04vYK7b{URFf_vd$Y&A8}O8qz5|5_C`WDcvJ4#ttPG zR#Kvmw3Zc*ov)P$G>hm6G&*9FN@V0sdenHe98yj7WO#^rcC$YnA2>}XzV{sK%$|Q3 zFxd{y*h#kUEEv(aWCH7v@~toV!*P7wm5ad@K>}_44&;n>f<*`zkUsgO=Cm9A@VDZ% zBe_DG*VtZ^RA?)NgOJF&NAyw0r-trR;*@G5w`3&UIGOv1Ai^*TFUhjo@7L4dx0a_?4oATxVy&1A*# z@biZ_uZP>lGhkQA1kKktT^93bA}E?2SvoNSeomaxGC^YVI*0f@m#3!{vI5;G=V547 z1PLIY{zUKi%XcEqlL zpMY>8<*l1PB(%Z8NpZN0vMs)DV_tXWy1DtKGh};Rs4_ zF-k&oqOWR%27x}OUG;v(u@lr^Skrp*f)Ub6vVi6@*0Qtl&S1JG+Gu~{{DT+?%bktG!8Vj;X!{CWLKvdkKMTj)3)G=32pQoRV*3oPy{w3S`eIz za~cLpV_VerttKKm2DHG)0ug`gDb z9n|U&QYl#S#w5!;s%HJkF(KH5VC?nYEp}sK1v-V@>*98{Lz=yPs*$Z7UM5!wALdL9 zM}vtdkIXUw?lt1zRLYn{1AHVj*P9gDXdeMG%_i3->Q@hwvHH~6sp%aCQ0M;q(&(zH z-Nz~kO@S8)Nm2d2wzdS}(co3X!Pzdty(Va)kKB_16wKxsIj8wiWJ93H{J5 zD98`#*HnV%--gg0ZVmAdcr;nF|i~c6Sqh2XUoNr z8g~9jYsieXq(8yn@d$mL_^LX}?cwRiu}~k<&FLq$W%c-0-Pfv`lB=AeI%D^VNEX`q zOn}>88lf~W;msq_CSUua=Jeb=6+&4RirJ)u9Wq_s{S0Y4^FI9ih}EX#OtN5&#__7w zw(;P%lV6NlOwKs0oBvp}`xzriv_rr4sVdA5e<#IpVgbt>oekB5XKIZW)Dv1ZD7Q3FMzKdZ+ z{;NKx^0Zk4gkrS~WbOa?+aDpW7{A;#it_dOb7;xg#{+~IjCuM7Upd<$nw$-5V1V$# zzs-KaYg-an>4t?c=vY11%3rI^5NmKSeYeP{38-YYR3o~7Y9EQ$R?7O1aTvYlhjKR* zrmqGgGu%#hUEIv+y-so##APHrSzqY8ZnN;Uhdmid#QOSZkO|DOyxYYTd|p3fw7DVw z8Q2C2oyj|{_>uNU`!e`Bx5lIfEd4`#k`Lt)ln+0@g670IOA)4wEQ(*@9IS1R=Onk}Qq3e{UijKNe>pk3^>vSL z9SBvudOO;kRM}{Gyx69gUFv);@zRwsckWCzepUR=+3E|W+_A1wq54c`0${9<-;6_27gLqwXl?rC*?ry6Kxc2+VB-|*UN56 zJ;DY4yCrjw^R2u{#AFQZyP*OnMlmR-eNx>)xEr3`Mb4iZoPsHlD_H@=)G1D(ab5NF zsHa4g|2ZS-?cr83l3a?h!8(LcZWd71*J+qj<8b;l<7d!vev-?)kfBA7Fa2=0sh3Tg zm8Dl`a=HT@&DPsv$1#xJ27e@Sxa}Y>IazBgVa=EKJhn}OCwF^E)(u>6-e`|TTO`t@ z)|pbQxGl%`#9+1OM&}0E7EDSZ1b@ICv|k+;V7;LjVc}31g8veVO9;5$|4f5=Bd(7y z`zge$Yx=s6K__{m<-D{L)mqFHQABunFfU=^9^3t5{%g!b1#@n3a4D{w_2rGvnbB|W z{=iz6(82g`A^o+O!V}^FR<;eC{O#+E-Dd;7e@}PvM4wU2F|;mpv@UU}J3gRbeI+*T z=HV~uaWvuSIB5+Q-{f{HO4J>L+@FI{MIswJLv|AnZ~|SmAM)Xj{78E-<{L2q&%&0` z2HVKg;A_Ur+L$%c8hx#?K>NEU^5teoUDH3lI1AR^p7M0t zD*0*s$JCdOdNt1|>LZiz?x?+XSM+^GA2{8r8u$orp({hZI~ZqJEq{#O82&viZq@pj zS=Q9k(pBD#D@My54l1pSa!MbE)<@J^Q(CXB5?Ylq6JVpOkJyH%mY08!T3yT3zk-(- zlKEVe+5cwfi9X|0TcGUF2#?2a$k4u*=0I6rgLqoXXjFf(ZvCjXK$$gUpto*)(1tQW z90El9RC`=0ll*-;-*??`->ojsk9MI$@a+&%C#+Fq)UOdoR0aiK2n5?k2MBBZGlc5ezPnVg9cO1+Q>Ab)#XnxnMU^g2d)}#co21%q)Y&F*MLtM1R zqiQ`A(qV~TQ42g`o`M%8I*4TKiCV*PPui`Hekk9xZCPVn{DL0Tisdx ztjY1&nBKvM#y2H+9?8)LL(G;^O=sGWq(RS#WKHV*TbvIiQKoDwTZQ9)Jc`AZaNi+N zXjjbusL9R-8i;#}P>R^npipzz*t<&;nz$F|&r4+Xyg1I%3^`;s6OQ=V?7J1o@xEu{ zZ-;B<#!5MC_-J<{y1>!)h=(2FaWv?5&$1)tf`b^PuK}TI!8|iYl1?nMOv5zvUs~sU<`0%4ZSd$__zdVQL zRLGIOn*K*pl6T+`8uw%Vdmo!RJAa z$nCFzCjL=BJT|+wjTwMMSV*XHCVZq4-cmW}FH z1aO%vFYTJp(MeTDxosa=|M7(msz^AGfcJDec94X5$GVby=n$e9Grou3$#YrOlvK$u z^(>@DnjIn-ch#rf*P5~6OHN>b36maJNA=~f*;7=yOj7Dh;_$kepp=o|v*oYHpb6CS z!u5gKj|)b&45y0exMjEJ72ZzR+A%GO`jeOhs|_Ql79qyW%E1>-kh&93W+-s{edP?d zRh+MtW(}5R2_TI^8AvYFuw3mO1~)??U(t9LN$)Qt@%4W7?43R#*^X(&+wn9oh@y6M z^tN@m2ut!=Ecs^1=!Olb4R5DC3p%1H`Hn5IMOmG+haHSrMvGLsXGQ_L)b`ALSE>F9 zGuc_wge%Y6RRXSn5>js?6#OuAez7K|2x}CY+GgiRRT}`SldyQwy^f?3+ULCan<%l~ zlx1CJKo#iYhIzeDmKjHaD>VvJD7Q}L?Q}%lbjbo?(+8iFD&}mON59Z`fwh7dVO2*Q zQfg)s{V%g=3BD!o7%gh;!nNA4d7thvnwSH(j-LKQQ%qL&KcTs2wBZHk*_k8az`vISDRJk{{Pc;?BF@kV&tjlo{M; z?w{-S3yBp`=fJ}{U?GL9b4zOLD-AyO1DN+i!L|J=q)v-aD5})3Zzi_wv{qt?&)KNmJQL?z|Hd8mdwQfh+zBCY80=L>Mq`}JgAqxnv&lock)-te# zWW%+yV}Gg^w|aPq=+_5h5TuAKM z1gwiuItCv?SOwZIq0@b5zMISm31ru?SGiH$xupcWMcNy*W2>FNE~i1jwrzi;Bd1|7 z#ATzpR7!~T=q=Xg4UEE262;|yda4=qWZ$;mZbonO4|UaC8b4bv6+7Qq_k*g!CTVQK zdnG%*4K@7aKR?ry-R!p-%0@@e^!EjhVHu3sCm7|nS6(QKxpb19okpXk$4J%;az9il z$6Uy+)4RrY;i12+^yZ`lccska)5NiFrCke}VY}w`G#O%xtk-Vbb(4^2?f!qr&zK~7?5$rqLH}yd&b{zT!S6t@6^v$O8 zGjw|=v00rZ*{o?j!gDV_OPz@{7b)90;sdRXo6Bt2y?4##q)X|L`;o}^JBN`3%V#Q% zx#=|;ySz)LcKe5<6uO>jc65-co(=ocLj-INSE$5%`2O_p7vod?-jlPOoLxF`hI#SM zHaoYC!R9Qr_GEk@B5@(Nm|Z-1hpg52_SV(d%%)DbR3^x=sX{}>+kr`OL|o~+QSDcT z)V^=@VYZ9x(foC$pFJ8?u@j!;&Ags?nwT&m`Obw;B|(ud%Tuuu8JF&77*Z8&>CK?F zUvb#`9`9k(?dxnUN%2r?hY+5)+~y$^Rd*~;!Rmm zIAY_wjz7%UPg0s;!XOtD?&hqq>Z7?xTVis*Z@;&e@h}L-$Sy&%JV{9-2G)%htm?jX zXBu@Sua{-6hTunCV#o&YW`;KsNtR_dsSHh{JE+UX?ezIqQr)A}fA~JKg{0cq;0*I5 zbe3I6+s0^ZxLCosK3I7(^e8)0tJB*3P)EsWm$QD4KJQe4_R*YU#5PWn+nR{#F%~%r zon6`&23+^=bPhEwzt!t%F5S4Tr_0f(=K+0=BSi1eh&(rpoe# zNdad|5LQ@~IjdOP=rtG5mtWwLYldRY{W}6nh$;><U2 zYyYrEP!^6d3l1QW1{mg~F5iME&Pde$uc7%9(^KF<(7>w`mQ*_*Yi3F-Xxu*|u$cn4 zjpj`81Y2dCe$MdtN|IRF4r~Y=UJpi=`CujTZtL_s-QV26&2ZaWyBoKBPPs~11lG;* zn~OR$@m@({cQk!S7(3B}n^?&F!B&1A3a1_qi>kQx8|bHP7#~GLZU^hLP(kVLD3gN_ z|J1LcZ{xO$KYQq4X6EsozfnX|i{kB*TAT_J(Yc=d*TYL{Wcz3{+w2_H+*saaW;j;-U1)PDCzK($%7uX6 zFlHh$kIBg6urPGVQ8GSJyG+uI0K;A-&P^e-E&CqNY55#1nhg$^;?32+rVqVLf`4%S z8damc@w=L--Zcj;BoqgAW|vE-@)thYdg%DgYv?*sM-k!BgarL?m$JKEN2jKIsy1%{ zfb+T$lw%&V?#-NGNcRV=fvp8%tqu2#2%$ZBWz=mHik(&34P}xYS2w@pY=*)P1kWiZ zYdRTfrDL?}&X&&>IcQp)ctX%C&k6RYbha7FWl{_e3hS4m2R`J^)g-su4m0TqPvu7p z6_`09XjPjKFxX0?+}V13<@0p6>uw zEia$J16D2njvy9SPXN9H@E!khC4de99lvEmz<2yP8US?sX^#cg1bheJI{@DSY|mR% zxE9d>_>Moh67U^=+5_+%i`mz2y8xOMpjrKI)vOLjYl0SQ0RY>)e`ER=%7IRBTy3Ndy$o0qPn3 zmcjXXd+dOEM$6+BpuE(dZ1IytfofmBbJvA%7O3|1r#%(`1f+q>X++ilNCW@02apCX z&L1qZ3y=l^Y2feS0Ei@ijs^f7f7$~ON&b#a0g(i#qxySF;{O&2krg^Ku2#G0-oc6q z6iIRHBJ84-pdx>JhOE`s6Zcj|#lBKe>rs3xwC78J$w8s7BFy8bp5J+NaZ~^9bn%oU z_J;&-Y^Zh121SZ_?Xs)iUHI;W-K+4T5AR5}_|Jz(9X{t!Wl{gAh9ona<5dfqX?kQv zN}x`Gk;v`;s)c-v@2>sz4#WQ{w=7utHy&5=?Ob{E&Ry!+Zo;=k%%%l`PUn$-9C`9FTikNU5&*FZNc z_BqfEf8a|HK*J*R08(0Ho}cUmkkTSh0N?P3SCj=@^de9I7rhifEgS%m(h^XBfOUBY zdwQlu@(TZW@#}9 z2V}k_1p|=z{)n>xnQxIu`2m@42_y>#z?!8+pa3%8l6nEie2dY>&%pu6e2Wpr&kPNa z`IdkJ$b5jz2kdoNjI97P0B8Wv0H6Wbfc1+9fJh05lz{Dsi;HOhGyrG-&;X!eF+c*) z0H6Ut1Aqn|4*&`)ps)gaq!%aV05tqRkA|CqD;MV_EA+Q$-o81=#3z+Zu;SMtbbV&K z;)&ylCCtsLsBRV7m#-n3&(qE>E}omH;Vr7fiq~_be#KWXt}txX8fUwizIbZz=SE|@ zBR<`|O=S8Hxz*i%ghmj%u2C5a8O$;D;%LK{$_4Eb*eHn|T@$@`uf~yIEwKj)1-HIa z1wm>WBQUH+1Rc$2VvRtYyXmla$2#07e(uKNv>B}K-5uH4Vw=p@|GGC=-HVE;y?o@k z&iH!~;LY9Be!-Jm|5%V-Kn6;}3&H%Xfe#*0O`AKAEWZQ-LBYGQ-4aj!9SZGre6gYZ zjn+AdT5bb{J)AzOOU`@`4kGy5W~%S|_fc}G{D{EbMw#-E!7iV3&=G0?8Asj_FqNVsqsJ_d&m?QoD&-UOb!g3A z2}~N6$kJM782&39a~}uiwO>7IWZ8_Fenu{hmE>R2u|V&AMWwt(rQ%zha^U@984WRy>91@CsW zN+kX=$_-cpxRf)^`GIti4!FslG=XGcORZg`b^xwEn;RWhqTT0H-rv77^0TTex@ZC(C|JuJFYf-F-{X4 zg}`dKax+U;&ArSA4!kzF-PAht40o!RUU!cEX^Ij$K_p=NzPTi`+Rc@r4io0xhkQ8C z&Our2lksFuRSns4woKIsj$oCL;CA!JRgtB^gI_+9jLxxW8Ey*$YO@RkzDNT03cM;! z*%tTq9{u$w?eY_MhsKyaG-@}5j9d3GD|GOQOv!LtQ*v3ry>V8x>_78Ru?RbbKhrn?~UNU}RxCC&$h0<~3ANU6}c= zI8dzejVTQFWgypgFKAqT2^QHrY@!@CAov#{1+RFrA+(N6iZB<~Z$_CaLG!8Yd2~?W z4t|giz7fK?J*ejO(sDJX6}1kL&oqa}f*Fudb)TC9p#9`oH&w4Wdb}{Xd@d2q4O4w|2Lp=0T{rPbs10kub(VXlnp{Y(k#(n9A#}@sW5qG?;GM z$oj;<1%KvsBbG{ZR_dT-ex!1q#be8_vMIX97DrO98sFWXwyes{JAZ*S*skZasZH8! z*F6e62`4Y?F8C-D^cBUJ@8VW8;%(Gu74=wZdc-!#z$S$m=s;tyk291tZ>sCp-^U|` z8Qh<}Ex_w-n~1$9|GnK?0d+P%*>S^NVf_#10?Bf7Nh4#aL@}gxd4N-IE6N-jJlGd; zPIt}>nHV@Hpd+J<9iou+X%@*tkEkPhOO{v8Y1^{`erV>ZqB@pKfZ>*{WLXM zH&wL%iy}C0_G@={;801 zzS}c}4<2pfu~peznhSK&S5;XzpEj$POcDyK+qUwn#IG@Srvk$pb&Q&qx~KoOhOGR= zsl4&>4afIw+4yWYHnmA?r}L!5PyeR-laN;xKYAydzuO zN}2rri_;S;rY^%`u{mXPMe}`9negP1{sB`7&!C#V0aH%WIPtjA0!I%bF^-~qNHlag z9p@GBaxu(jsjkr|H~3tq51k_qeRIJd1ltBQ6IBuF zw0dg$^mh2~Hs$f!RMRlo@~chnE0X+?!kFNJUKhJ!&TP7L$?O|CUfPybO&(tTaR5tG zG{=o{9#3TZXN6)3=o`+>SQoZ}-tVEko7b?IgO$yT53PG};w#sY+I{Q@vSCFu_gj7A zsuS&gvLf?QOf}OklYfLA`w7C

o93{9NG3bY>;BJAm^M&4`?QK~=;|jf3EmtupRx zGnoLQI3Cj0R=2Dd{CIci%&yir@$Y@V3ydd1v;8@){lrbi^h#{YYYH3$I?{*LzA z?g-sj(d3oP9TXQnhn<6bKru}5>t=a4!Hnb$Z-q00{g`QdUd(Ue4A2J_su8Qrdg34D z{mmOQ@p+2e_nVwI^R_l3R$SvQl5lz={Vt3yj zm`dhSrtix7i0F0_w>BfWcK)rk<|Gb9WiWYd7fao!1|I57laF91qwOOp8tj*oZO941 zB~0!ROe}}goh&2t%ugsTqFm5jY<6tAPs$v9BU06r%=*#Cjz}G1Kt4y*Y4#5{*O}=i zhFVdXI<)~~P7%qn!Bq;e+(uZaDM%%NCO*$CVa+~~Nz!8T_oaF5=$~d%*<4~&vZP~~ zxgMtqqmt8JNPhuWF1slz!WaWhYs@MywdSRe?r@%QP7+7?+i%+F6tZExQPH3LsDcZs z?GJUMnQqCMyG&xX!pM0pLB2i1fh)|>V*!JG%+=sf<`ius4qL>EN5Z}9ylUH(CX)PT z#8J@O{Uxh~*=!nvmXxf7aGNm4>P)}qF2+uRS&!}{i`YCnIjg=%sn-01$&K@!9*&L5 zQ!3aI>S+bUm=hFNG1d*8j!@}l*Z(JA9 zQz4EmhcJC;Mhv|}=ue-gyI{)15>^RwUW=Qkf>1}VsAo_uIEnDZ8}cJ=!uEoC$uO_Q zL2h7QSn)Beu9&&bF}Oc00=%X>a9ms`)m+4G>q@Q~dv3yXd`G`ENZJwV{nRm#7)l*M zzT~p8tPuJT$d@8+8qbNHifUGn#VZHhnwmbg2hMVtqi{2hzs`td=X0>-ZNNyzLD3cS(vtl$&8Ay8-sI`W6>#YRu>E-nC_pW@KYTJ!%WWz21-3sgfn?zT z*zmas6rh&dvLGF(<+el^BC^0H&t-`n?;VmrVfw|v0c`SIoJRW@hyGu^$#bQ5;rwDP z0N@2COF;xs3}6WYfS&;T1W*BYkr@Cq0B8Wv0H6VQ)!Q!~03szIQUZ#IEl&IbXaLXv zpaDR`Vt@po0YC$Q1^^8_9sp+IfSEX8UK*H}2Fh|T@&JGa01W^d05mKueEoF*L`sWe z;-^6XO$o@Nfh-!xqJb^Wa&_43G1Xw%wQg3H)7H@8B(rT2;S$Hy;kS-Dc^lL+4# z@neu9!`FPkaZh0Q{5<7KD(cXR${j=I1| zikn0Pi{2L`9r%ww!d|)kL0bPhGJ^=-wG>C()0RrZE~$V92C_ePEH5APOB?zkw-RO_ zp-oI*DxS8u+gVUVM6h)A;y765DLShE5HB)u<}2N z|yjTkWAZEbF0PYg-{EGq4FIxLw#AX14{lCFr_DI9cS(aP9=N^fsNy&JB zQxP>nKCT?sW^#aghQ*9!7>jQnr{CO`#G$osn>vEbP& zJ=rqR0S!!1e|LmCdUv6kAorgt2%?=GuLO^OE_4CsHK8lm)$YHs3#R-2Ix z{51EFP+3xV~# zye#UHe4#%*^W}eBa08##=7tUnlXn<{iRsNz8?(}zFB|_(Jbr!Se2Rhe?zn=ymuGm_ zbFCxXuFu&0J1<;3{d|EzREGucjMH>|-Mm31bG^S>W{@Coqp@~m9Y5Tvc~HrJ{BJvW zh-sE$+_QMi`R86|*8nc*uSUOW;>#RqShxtWtM@eJp9xnZ!LUDJfWhBVWfK#Qr$LP;9*=1 z&6J-39d;leuetvO`Sk8{XtIs+Q-|8Rxh4zCn zcMNXkU6YDk0GF7#Y#3BRe}{K-*f)xRsIcdO951|+XahW4leJxRFU!7K6n};|cA-4` z9lv1Yo{0zG==MBxKyouwKZFr|z)mCi9eA!VJWS?bH_aO)?fpflhH`L;731V(MG}uY z{Cru~5i5J5ttfadDjdlTSt}6TF>x#h+51Y;WI5ErhzeROxr;-Kcm zAdw=Hj~Z$h9_Wx3>~`ivTBsc93ge5&Y8M>5cT`0IZqb|)_5PoXjBchla6K)NX z@n-ADkCz9B_qX3)!Mnx*BSBBe;qxyfOo@UY>!0O4{n-khiLgBX#L@r4w{X9Gn~KM6 z_czYle0|x`Fr%Z}SHj)o-9mF##wTyoRT6mMVw5p^$!W=rnRNeg%xV_Pdb6t$h}kq`PE9GFX>M2oYaoeXH6ypOZN^^QTT=H7v#Uh){d5#dK z^cu;{dFJG-Hw=O-7jqp|QAysk0c);dqU@6*tUtdQX!9>X3rsS0xH z!AJULwnXaRw61Q`k&`an>yUg2pMP9#M(3bIQ}adJp|`|z)6PX|1uhL3n|Dot9 z-@qn4LK@WS3fjc3?3!!!(K_MooEs6P^Qjpg{Wh`4q4{rg+e=eE{ItU2FBjDsCiXph ze0DC#_D3Mfn|nIgD|MK0N&>lZ=;y1kHj9b~p1W_k`{$r}TA}7;@*01~ekc!l`Y6H7 zNP9HYgVj!DBT>h(f!qSKFE1*i@~5UuPfAW^;W~q@r?x@0`cmOry3Pa|@0D$|wqw?Y zhnO2BPOK6&W%uKLG+~?OWmxt9FP#*pby{2$YEj{_E*_Lh0nC7bu^UaDq)@Bo$ zVbsvdI>X@5wZcY5I*Q$8@y3+V1nrYkf*uxJgN>Au8)=M$L911Cl6(?eAQTiF0UIE6{b}g$8~&XMdW4YZqF0 zO`AcLfM4o%ShL6b%e(Qr%BQL`6h|!mNjmcSQ&YWF6&I`n$B5dnuHedw?$U8vver3F zQsDEcFENw%VQ60{MOBolUEq`8O`URufc?oW!-WnWfn#X-6J^#Ob5;ye7olnY58P|} z(EVjj#W#+L65Oy3G<_5k(p=vCMQ#DB*W-EQ;3PGEn+N1C0kE=WkC)8t0hgV|j5FHW z3Y5s-X5%&9mYTgP5g(}6IB7H6IWi<3eUU0Jd@^_{?3?OFZs2pYmY=lB5`RvZ;QC;w?L|}lbecZ-#)IV2ZKj`DtT={$O)Vh~2Zj zpN16!--0_-Pi7hl&PY3UQPb!_QmCq6_z*-DtTq4hJzTInp@4@y?fayDx`bM}T;|Bf zFs+H%kHoV<5l45{1ruo#Y*Crerk*D-h%)@sQC9@-eUIgdUh8luu;*F)aOMv0_*E}W z-#*gA>|K*bON7l<^nc6xm~J|CwxJ9fJyt$m!g~oGGa)HH1PS#C^0WbeY4&=Wytlpj zYchLm6pDC=87}fw0sBXNYapCEYEP089Ndm-s6=~8%p;%W53Ly-8&W-%n@w;dpvKL~ z38fGN_PeHt=ZMG4Ty^-%pvFK^IP~;hNg_3O+Wq4e z%)k)W!!owAbo!Z#84hN7xunnQTX=@oB@aRoH zQQ{VtT5!wRl3QjjEcm=Trt-~8z4y2UYL5MveMz4g(347Sm-nKs@ z1lUXdhqKL|CW>Z1v!oAZuWlT%7PIs_wc}Hfi;u@G`@mY{N!>|vxtLMCvZVR9zF~SL zv}c4wCPfs?WQR9!Z_W6TOm(EAi~Epe$&bNsVQ@||9W*ftxJpM6n+ z<4|mHvo$@*2hzxh>=xe3yPHq@2$PA7`xheD(6FUYooj^$1uSTx0j>_{>Fm~GzF zYzgv1VWh*?u zuR8PF^~ySo^Yo!y>wZ!EFh&6?b)@R{q}?-c=LbxDdBx}sT6p`Lr&v6*Xxj60%7w7~ zXw(M0hRAL7MtQvsk6^Dolx+0{7|WjD$xCr7@*e+;t3-I*IC91(yshP_k$^O9>Z`SX zkK^N2MG5*BL$d17(Alq^^EuI)<6R^Dq`8t2I%F)iO;{Xe9&-P7#8Bsm;*{!O>gyxf zUL)!feyP1C0;u&v6fCxD=3V@5C*JXsO45bi*qki(5s?iaCmuP9EpXX`^3_f_OA;KLb+DXyACIuw!AEWW)}78KB+@%yc6=A zn|ZVH>U=p6^j^=R#>?d}gHTL(~?0zzUc?EReN7 zgDR;1Q$m1wuRUmcA>>1bkbDNirmK)y;y(|%5$x-Z)_dSicp;;_=AW>{HXofq9Ii+Q z%kE5?EM(9)MlmwV$nAqnPm=ui(-(3={fCMMP0ZIL1WL-tuLxs|jh$~ebQ5ZV_WcY) zLBC{qizC`M>G7)gmQfFeRP1eMc^rXRWP;|st5jI$^{MWZCIThW0!2wW`Hy$Zn&uyvqXP&DIn0Fd z{`JB5SBgU@&g=bx{0W^Jw9PVjyB9pa;5V`_2-@>nOC-3yOZ~fx@L)%=IYRP+`mvi| z?#nUX=MYMYd=)3r>Be^GpVap1JWosc=k=YkIO0aaZ}!)xu||@ z;*O*IR2I^j`oo>T_Ci?fT65P4^+Xv|TIMvFx!}8V-eEL+KWF~T`~r}AbJc^0r^q`}twWH24B!}GORlaYiy+XsgP zyEy|TiuI`VWM8MDl327Gjkc=H$>bw1_EoIaI(2Xze}ku)AKLG70(}J1oW=RFW5Ed5 z(Y$Dd9=l=%@0TNId;Zz`cJ(4rwxtj>wfl^v-<3f1L7C$H*-bm^r0%{By+!d{`WURSQey?ZUhENbpb2@tE-MyGJ&OLl=c05{>DKHx zr2QiM)y_8c<*kV>ox2eSn~*0Is%EO@yMN;xG6sDp(r#U{JA~2t+Ug%k`&8;E5L8G! zo5Z{2&{}<`kMs+w33_^)Up7EQ0*l=8%e_8D`3KWivrQe9g3A~#dC958!xrQ;oo zQMsGmm+B8xSNEJJJerW#E0#UwB^IBOMzH3Ai*&&pSNgQam+BN(ai^&&tU?utmyjPJ zsGqWwc&8C0+`E?mDh>g{LO|$B3B1@+sD_y(0p5V@Ahxlg$f12s2=~DiX9(rG;d9M) zAz9Xmj5w0FiVwvB-|;T&1Fw|0K5WQG?y_7-$GTu2Mj~GIQi zZGSO9u=n}8ReZmdNy8mW16B9)Zfl^0YBpqG0l5A?iOf{bLyxA^goau0yKkNiTT+qf z?N)M_gPDR%%iKsU>rK_-8>Qg-!7_fi!udkbHR5W{uek7s_D(9VvEn4rzV8ke$oF_;9XPdVU@Al75zN? z=#PP|-LTT8gM@^LP<(2*f*fadVZ3kbV}K_mmw@lqRA%@Hch}*V%1AKmWIE)~D@O^) zFm?#4FnA4P(YMOz8s>{LP>J?STsfAcVSA;1vyV*f^zii^T1k2_|B|sW3U3}A<$b;M z9tXG?xt1ED$Avhf%QG!kSpl&wQ5Im*9n{03-C8p1A4HIx&CyHkmPT1FVg*U zI2e+Z!Y!iB8n3dirhjztmcrrK%E&F_oWrKJEK23R394_eZ>Y0~*#`Fm3x|B_Ik?+( zZF4ZsM{^g^g+*P-2L6ie%}QLjZK^P%@#sSIy~a;~Ew|u*_YJz>AXOO{od|w~IW3{@ z!c0r_XtF6zaS5Vl7YE#Cn|E1lbR{)>037!P=;gQFI&Jo^-FUGeNQ_}JM3FITjTdGo zrepo{;aFGTl1pf(pVq?ZhW61et8BW;G6DlpGjZ05E#v+7CymTwJztaT!<$nRJyMjK z?y}e}L=~2a)lBf&uLZKjZW=Bb%uZ~@4>lLROq5oa zm-gIz={K8=Q~(j_PE0dhfJ*7ypTECwl(1S7x^7^Yyg_8kpdhm(vpRGNC0l38noD@Q*~E7dbz&>hm$l?O0c4mld7_7`a1DL=@mxEvE23(aCbBVQaB*8OR{>@%X3ys@YGYN=5~9a2zzO798C zkMEfg=bmY3%}i|^4t5QusX7bA+T&KH48Vk@ytXi8hl~(?b~5`Lc<-&liz6_S=XGxD z;&0^F@Cfr@I_A4&uDB zpDW(o*$@m!9GS~Rw}jr&FIH^I%r(1^%ryAn1C|}CsPkk70fcjH?w3QJ3?hQg4xY~AE}JSwDvEw4 zzxT><*0yex{E(AikWvOQ_v0H$N-~W{65zsKo$6>4AjCDB^rb5D6Rv?{HJx;;tEmr? z-lO`^)9`35Q)R%qW2puCgo3p1Z6bI1Sanhyj7%z0J^rnz+3{8Kyz{p!udg7}#s~>l zHu>Uig0iVu1{3N0TC4#MZyZ+D(Pw<^vlx{Iz1jksX)B}qTO`VkDYIX3E|;V*tWINV z4mCzihO;*2Jq6ua?stk0^_dRs^!kF_{m7}MB;&8+PnlTKUdVvTpcwf;(AZHI2xq%H z{X0|rKva-E|8P(p2twaE2Ux*}MT=DzQ7sPntr=H5%Up60ZeRU{QMKRA@>;(~q0hE{ z*E6}YWugqR`>rpAlZ=FTt_Ud7!E}DbwzsS(sxSb8i#jRk8u#lvbt{7Z{m*~3vO1Ij z_UWwo`{2L*zGv z%h;-yI|vl*=!&ET+dB&kA;%PS4Y(Y|sS4zmFrrc_cy@1(nWe%lO99`7h@stHC#VMN zwz%4+W$TIScc^cyd~W@5se6YC4XXe;dAqG~Vspca?I_Evyw9k{&_6b#LXK%zTf+X1 z{OeV^%7_F(snYl9t+#fyNDMB?M9 zK2)Iij#iB+Hp-VI;*@^)6D-SePd*J>6Dnte!jvwSIO%M=+n11Y2@Qu zv=Km$@&0=F9ooWA0fq!y)98Qf+7^M*je#DU z%QL2SX#2Bm|9OOD{-@h!mB)sJPmVg>x|A4XQ{z~xmFT5iLuEs`E``j9{~QPKm0nk* zOR^nP&@>CYQ!~<`X;vy_GnAgCcF!D1Gl!k_KNka?eheih9(G>@KtvxUyQ|LZz(ma) z#dd);mtrrP`MTGXavW0lC@0Qp_G;QneJL@N+!7^_Zyo!5^dB;SI-BqlFCJEc&5z7Z z&m->CUPeicer?`M&tiUbwlwxq+2WTl2s%<{2VN1TDTpzB>VU3P+=#56jFP z%saFP=Jo2!@5jtQ;ss;H$fUTv)xlE>j3Fxu1FC0cQ1I5jn05Za*EBB4XQHDDQ*6~e zsRg6}NcNjcmAvJitlxRe$m^F-cN2JH&yHmeJ@xzG^xXn45c!GE+Kd1!EKaEr5Sl*d ztlwEkSmJ(FcPRC}{q!9lpDV6~bL*M6?a<*p*19+&?ALo@fNIQuJ9t^?B<21MjJExY zU~Y!FQ}xD8>|%UT+ECJ!zd|9xiN65E>kN4x^K#PfGLI3Oy% z(=39gJU{*`Agqxg)gb5`W!?!WOMee2?rf*e`+Xg|=)9Sj=qIk<7Wt#B zXf>$Z|A#TyP30GCHr)g;9@=^{X191trm&)XLWr*vJlwlyI)5`2$mVeu#~oyv%lI*cT$0l2xl)?SS-o# zY$shzTuJbZjVc{ZB^-9|cwLPPOTY{W02L1y*sFA8NT z&kv~ODw7?osDEOCvv()1mO- z>~giSChFR%0I|6DVRqy;TgoiZ+2Ur8X$cgosSSD7F50|Hrw?h2lHmVdLP-u)z2{PJ zHOX7LT}erbCVgex0n@Rj-jJGb2Nw9oBUtr(erEU(Y#`@k>Tb_Kac+;s8FHV6*J6@w z$A)Rm<2*@A%r|-O_VRB_FvnjeJod zdM=+Qi@!XnA5vD2tftIUc2SSPjbPRN;~zlgW+PuW!;6Pm!a7FM2rKB&lm1+Jpyims z5!j(lUIu0((|}u1@9j^H?mY+N)h`QrlV;2Qd=hcShBQ*mQ>n1k71br(4JeV_4?b>< z72KTzF#U5w}cf*$I_lUP^@+=OAmM=D5>o%YJoIlww$32r< z!VEwe_a8lN3g8%Gh>X(#CkFcxlsgR35lVV<1@h)NmbAT~xl`5VQ+laKSd=8qokTKH z2>j28KEtZ8Vd%}S<(2u~lG6|ZTY;oGzkl9O`kHNE`P%yl&F#Z}k836a-i^}Oy+u|l zB&RQamQ87ST+)71hudZORp{n&WvCMY);^hNjOswM>8-bg%0kN#ljsB?_0{LPM-&l; z#NOi>T4nPgp@A$@ma=3eMpJ(1LKATV40;m@zkuYS4_ZMAp*KcDRU4h4^;61=ui5n0 z5V}?!n4lQk7Cd+kGfp2BrD}vGqD8}1M{VneZtE{YoL77vwwv9z*e8m7o|AV zp*-PX<+Wm|X-3gYn#pvC;yIzVD9@I$eiJ}67^SnUJ;`)c(wn;bcJHrB zdWzIETR%3YA$lTU9j94Fic5N_%kVT(MLNQFvx`l7Givb0V+dT;Mg;jbYxpnX1yQCF z^4wgG2g<|$Y=Fez%4V|Wf%Ly@e|V5qL&Nl6z^db|uQLBcZ$zmb6qJE zPAAGPr&jss+{z7oxz?GJ7`UcsUkk?8o}(*KLq_dke&)^I^nl6|wzJ9n0ATuia$BRv zsq&2rNpN{R9m?vaVAgn+x(TYiFVMWk9$Ly?!|XY#0`}T)7mD&h&+7>#zud6y@4S7W z58*<{sT3@tarS=B8NHPK!d_d@3_yLnt7sOzxz<23BzcX&-(wsySS1LHMurNONpv-Y z-0pXN<{M#)jQYj55ARvzJN{H(NwE?7mOpKH2qW@XvieDIc`cUR&F03^1haRlqeXbOfaHuhCp_ z6``YK&qG}Lb5o)GzOME^hR#Q}qTHB|ffj@uIqbQ2eFzuMw{e+Wqy+aTS&H{bN%t1! z%8nO;!wO%%FbuXLZR`((!>xS>meTSZxSP{C_75NJ0?i~2xHU?tUp0B*ty345+2n|gN`KXT&L8Gj)AQsQ-B@1Nov1a9;#i;647gJ@znER8T zT$^_Bbs}-%G|694L%$erq$5TnExjH6++?~mCezB-e{s__Y#Pb*&=hXM3 z1M6e_5xzQnIf)x@-(x;aq1vDu>eMh&@Fk!^P>L?=0u3)1OqW4fit7s2+f2jC&dm*T zQAX;BK2;TE>-`3Ty1p*~d_NY1KL)SKN_UX^Gv8%mtX?nWszCFtu^Wk|MSuxEo z65z*SB11-jqfJ5Oq`61Dw>NZ1uS!VpmsRDekgIO>IQgdNi^I?O_BCR$l23-1=>4NG zatv=#!b;22p{ns8F~iTUpcgyFh|+5vUg~+ON7+0Les^lmWWi%7Q$UI5itTk7&7-5A{T@HWQ`(ourHSnEl-R*j=aC~MwJ+;*_; z=^{#A)LMO)wG}v!?=g6h-~&30v3RMu7xr4UN({8W;N$R24(LD=e!4`D`|wKN+;<;H z!a;t$)WuvZ>8k;Z|LE*AubOJJ(!r#_6uh2^0=7DJ0>KUu9tzS2T+GGvtC zP|=uS8OS%uu5$LU;XqG;9?LyyAQ{F^&>K2DalN%)CV#2Z$&&M>)>qEgJ&`MY&n>;m zdaaH54x1_5^Cesm!b0$qGWXk+GG0OfZOUB&>HC<5P&b=}+6T_laA2%Ps(=kS*rj}i zYEqu!sD-eeZ~brj||22p8MKzPZf{<81PY^DPRM# z{R2h4y+|>XLMe`|=auW>X5_UcnCc+}a`+;Go9|>VUHv{Dn#3q!;<_0iVFk!W6Ci?IKX+n0}IDYlOUqExP@HF-D zNOVQZ2!iG2;(BqK_-fGvJ`d%yw!0UcTFytQn*Uf7B2KgtM9NHXr_i=8)?22A<>LHNM!qP3CGf;#V>dMzUzMFYkb9$gMG(Tgbc|) ztIgT1-^-LBW6Y}|2^)C0|B@4ajc1xutvzMpg&P-NI!_GULiv((kk6f^rLW_NCrYne zwhk&_cQ63a7_JBQw`nTXE%@YEQD@&Pw`fT*O5+*`ywr8$eu6F7yv?a?%D-*{QTV;EkwBxqLH6Huw4ol5BPlF9e8PF z@!Ho@z(xHxvLyF=`9+;}NZ_fOXAFVN1s4|9CXXo$??OKCS!!lK6!UsLv6M%18dd5X zR@q2K93$W5XjrEQYHr@OBsnTR^(a4y+wlL%-s&kBn{N7yKi=3AAFE7i)MR2VwV12> zEWLTF#t;fG%$)D3a(_LIV6F8ob5zH|++vXGOG|`^G5?!Bcwfj=JC)eG=*X-`?&o1u zBOSQ5g~J@3Vd`v_Nwn7D0kM@XXQc{J@s*?ZDYp30jgzu)vSfo22T%IsX6ATK*7%1$ z1j6Ur>{BJp1f=NxuuXB+^={`RRUvP_k$5*ok|a3bWZ>1*x}x+4$jqA&tUX012g~*J zWKA%RW!6@%wbg+*kOXkM8%%N@rSP$}h#_*Er-%Fg-_Q8{5-4Vn)148glh?y7f(C#i+0 zOD*|Kd7)Lc? z)LQa@nvy;hJqdk)aaUeC+Mc_gRNddW5#Uo!fqN`3{p8Z(*(@LHdhFRQSDeQPOIy|MzJQWORX3qJ{5@5vC% z#4iMt1cZ5>t82BaP0`2~^PL32aA86(wD!89{T2(r3?YF)vC<>KUXOnFq-PF(TJ!)M z_!`Tk>uIvdBEX~dU#d;*izcA4TCwP#>!GR11dQDxacy66u#$h+cXh*Nzw$e44z=9g z6JI`}#!;{}@+?N?o>LeSv^>1!s?$vMJ3xJO&+mH&7gpR$Z zxt#2%^IVJPKX!lom>=$kKaKNJ2I!KHcg`@ks8XNvGwIHjfoBHX0-y^DmxTP78*!o8 zM|LSrO2(hP+0ziWJKeEl1bJ`x)@N682TV1uBlZgs(5T|I(z%6f_)YZmo7mXA z#?;z95vuFs{OJ^Nx{$1)*bXyXeEI%lL?`|gp6m39@f`cpeX)QOkRy)!iP}u{i@nGL zqf5`a@xC|bc7VU&tF2vbU`LUjTau?{9yZuQl^w#qcjT!ak1)&e6~n!D?uK^lG#SIN@8-IrZLn4mEg9_auELuX zT1Gwb;&2)7?Vp>+)5R7(<51ri59LB<$nKwPvPc5M_1HNADEw=&*Z{0`OMC`4 zz;zWBV0tGgcQ6pift+svMJmp9u|YW6KfT`F&g|;GIaLLTQVqV$ys!!fbwWQCvV|~$ za-oe~@D8Yq+JzYiB6cCD!Fp-Ra?Jcp@)7{H z)(z8@%-*Nd&z3K*YCW*u@UBTk-zi2ku-AX|zqYy(i`8z^+YB36oans=-f&$=&RC-D z=HE+Q<;(;&M?8VxX-8ccG&KNI&hn;DLk14`2{tv}q)F|ne7U4XNiNNRiFb0S``qV@ zZq1#_yn{hGyVzgsoF(8_8iT&yf{YGErBR|Fm-ew@BNb;(I|@FR*6dlI1uD#Mf2wUN z+?esO)A1yXnA$bcRjNjlQLVDw%z-xXMniAB8W$=(aYBq%QJW zhn0X4P+K!RE{mCq81qvXv6*Tdbp=EACC|xYj81kKb25!8V-_(&xfGcObe3|2Nchk z$GeF%?{YKVa{7?XI5x8-oUOmNCfn$P(#&DDSjZ+Gee+Wh*||d1Mw0RFQ&1||tZ{uE z&7(|!KxWm4O#IfD(oAPJ6?t9kSJ?P_e(de_oUynWxw)~z5E5p-J^qc{$a9F=Wmfo~$N|(0208=Y8ZlLjab99is%ut~r8;;U3pIQ9M zG>4JjdXclS)uF(iLYcH}of~_^F*AwqFfma%ud;L*c_B7@aDp!ldj93~oH^nK7{pNq z>y_&1omUdo{uuvL&<(k<9xA=AUy}jE`LZzLOuG%%YR%^yu+c%jJzBiezG3EIzT>`& zgaaM0D=we$K}cbSOuj8K>5vNK^dicq6RAOXjobakn=;_Sr_-f{9X!)XFnCWB(^r#>3SIaK#Bs-)8! zzI*}55@b|bPxiwi?ZbLkQ1X1owP-<9Pasy}d0B#{5hV|GF1-llf+{j7JY@m5K;&*Q z)3u}T7Ehr}N2V-cuE!H`vft-U&utKrlEoF9$m6Bn3bXR?+Q#S$%xA$F`fbv-sk_N5 z#QP=pC@C5;{6l*&N8Cr<-rv7xydf7*&mI{-WYoW|HW*aho{u}1L~2J65?uqON~R#4 zcOpuAPmE*V_KU0IAp++zYj8XM> z=o2BtCu$v?mKq7Q*9suDCD{{tW2!n;S84!v89)8JGYD#5)Rv@@KH+@(qokV~P;iU# zA13|<=vB8b-+OZ!EXj{}>?y7_&+@JzmNw24IS1x)RNl@-2cZywZ9YRLu>kBp+I`qG z7HQTRcUcJ2=Wjq%dODPq@lz2vev~J@d%xnf(^;db_mK zqBOl1`ez9SjgTY9jrOCi(ir3d!`!1?EB1$MZTC^;qRv|-(kWG7LEdT@w?yI@m)Zv0 zT;p4(jT_r5)!Z-P=rtktE1yISQ&N=z;3^gX=&IU=F{|xonv+a>BOa)1a`xGD;QjkQ zx4Znm=x6!25eXUIwE0(r&@V!7*3^SaQ!aGI{VlECdkye${1-A1G$uwc+)Cz{{Rn+i z-Xuab(`YL;k?e;J+yY~wcfe01020bYZ93prn(*HQGufh(_mT?aZ#`|3sR+1s3*SD3 zrB#7$`-{|HrnCVGsXs$elO}%%_%8(2|Fg#ez(FMxed6w`{~gcx$*3Q@T37&JgAX1v z?HSVj9hM1Dm{AMc|$6wVoY2N%=~>#Ba{&zwG00Naeunwcee2xh`ODqjW6$ z!w)Vd*B%b{?QzunpWI@3r(TxDg`ny%X>V0D=K2ci~%iKAdGWixuXC zbUc<%-U(aAqz#O1t;C*P@Z%WMC_5B<-gn}u(~0ZyJ4oNXOv48x?5*WvS9e$PstERZ z1l9P1jAbA101RW2c%^|wd+dQB^5d^jg01!x-|?(DMzDTw)y(y9hxdW|Bcl#9Z9$v4 zuTxd0%CT>ey6mv`0dqZ`g4k;yk&iCg2)Rf9maV_$S5XJtq)BRmzjR}Ft*EPTT}wF3 zoQ$a~~@WjYt@GyM1MUJTDVWuG{7}sSNyTRODOu zl}n=?KK@ka@z)Zz7xh2JcLI69Kd{`t?e6~$O}&XJU+aj--Z%JHz;v!lIIqMZwu}2u z_H#UVz)kP=g6YM2MeAk9no*E?}QcX3Gjolx%Q0K6ls_D&%8EyukHFS`@QJ>`Lh z3{(0J5O)m#J#IBR75BR+eV_qchjE17Us4JM2Xr0F-L_vrP~FY|}P_{NW~=3i`uM+m6#8p+|EG{^%x}`Sw55 zO;(cR8LDau?xDjRM0oi7T@QN01LJ?1I_DpVKHJpza8*$(tVbFfr8(x2T zKl!6};mfD8G9&4{=CciWM6*YZI+&Jc=%cH)SxV0<_RF5o0^%o!xg6dSh)(_^6Q3z_ zw-4^JZ@Xi$yTV664f0X(Wi0gun^faRKL23tNEnj8CCK4KocCVwQ+@+;SvJZ*GYx(v*Kd^TZ2ISabs zsm6{mLs_EXs$y^+3vp@50Eo|%W`iw?6$|Vl9rrz#zhS)fq$vGuntt7Rh~xoY%~a*s zlgv2Bw)KA_(cnd$0w2D<4@4Uke!S8c4QHhWggDh=7Pe$_a9Rbj71{ufe&{i?jA6V( z3!h|5eVgWS{%?MBwv|!{N-VoAaA<270ge8PDUU;@0-TBO!>Bg)Jb*)5yx#tB>j6dw z9@k@cB_#}Rqr5i6zhP^AbW5qCKm)i7#)`$3dcUic=uGWJo}UIZjLJG(W6j4{MZ}ys zLdsTE$kRf;t%rOLUu$*A-TSx4PSp4>*A}s&$+ma(E=>y&8M;@BO>tMYK5xdv`V%M^ znSA?^aqB^Xp%3m7JN2bs>KvSfwxAddl*;|=&Me@dXI?NMqYERK&VH zeP5gl3^|%$i_i?&n3y@rqqp^z)k%hKNGJBo+3}U->B+9wax?F?{++UQ*)FCe66oE? zIN0ZBk8+ubYg4l5ZO-UHR+BD025G99m!+Y?h@5~d`>Aoc@v2)AZdFrnx}{%bIuO>I zFvVz6LZjN*V8-gQfC3*(z~{yMo?~_+#XiX$wKgjgcMm)@Kzch|+!8Om^xa7hM53&Z z(ihE;#%)a075l{a`AIQJ+y}OaFAWf1+A)y2g^3k#`2%HYYNx;=Pe(EaGS^Muq_+I~ z7BAv6Y~3Jta?O+$3(7s~nz>5JnJJ{p%fT_O7*%7tvsQu<@%zplbM&IshYqS2_ zp@7=bnvR{mQ{VJ|_5wd!ws5}Qx`h+?yY<&=uQ@i}k8z!_u7*)@8f2sC#U}k+Yj1FQ3^RC3<7yMY!jD?@WLZ6w_Wz~ zb84HtEG}bo#@SZL>lEgOun_2!szDd>uUkN)JLfos=KN!TjUk=>Hjvda3?*LT-FRhlHasAPz<<9g zlpwbiF|d6{vElyzIcp(VS)m2(|9;iL;UNeVqJFGP;Q4>A2Ura0zhB*gU@wO488*z= zG4p@NW)9ukr857UnT{MnWK-QCmXONwzR&K)<%|7GJw3(6M0Yxry0{8qWWq_SD9CvW zUAP+eV!5E+#A{#A$XxnrWyPv1QLcgB`G%NqJEFMtMef}O!J}sGu=?63;{2s7xy#JBRMZkYmlw@%f~)ww73;CsE?=|9J!i9OlW zLPBw0s|Ez$Z#v~fDC@f(A=Pj1J5o=awvRmbM*=}y-}z|1NN~}+$qZ6fY1fZ^IaEP> z1?w;Lq8IyGu9l6Xf^gqM1zaMi-dK5B=b;A6nC9f>sd2CIY^_ha&~`QAgtU&*s4qlt zSr54!<6EzbEHYvE3%nN@ye)~Z92P6Udz!6I#t?06Zf$G1wlJ#=AARLJbHk|EFwp;_ zQcl$=YBKf71-bd5DgUAjj#=Y*q;4baL!usDFA$q;E~AMW{>VI3)euy&=&g{1GbN^S zOk;h6RtrZpJ(ySMO^GT}mEuj74ZIE43Ol8#-zdo#9k&Ii<9J6uDhge}ctxR0pnChg zJ5AncezVgh%_?>llXPe|h&J?iN1`O2$wkJEh?$X=1o z(5i}`Ml=0CP>VgW#n=V2yOhFOxAIh-nae~>Owd=@%e^ZPcUTt6lnJp0D26|UG=mAU5j-sqs?3TF z(u%@;hgEom+iKm3l$RB+D>|rQ zlvtiiU$T#va+O%Qof`l-T^+l4{TbN1mX1@RFHM@QT=plu#Cn+7-(RqoiBQ=2hs1G! z^M5TJ&Fx#MrNDz!HN<G8hy2v0_boZ6`Vtad6vn62?Z+&fCuE#uDST z^xuHRHH_n%9vUVoz(1KCd(!=;C1&!*ov@IC5mhSHQ4KD_qnzeD+xf%=r&2l>`fhRW zQGwBA=mj!9b++;BbsMsvN99{6?zl|fxc;$xfgu|+__?6Lsa<}FvK`#PbE71e&P9?q zvE+6{kzn$oq$|IZ!&K-WNIJV`=`j(BhlX*+hYt2yok=Ih&V8r*B zA|vG?3#}*d~v6bji<>Z)Xi??T0_kw%A@biE~`1rW(g{U_#qfp%^3+kIjHt-#|4qk zFL)}MBgL6A+tKzv6kdHbEgu#cN5K14l40X@53Ix z+*7~)fSL&m&v|g=SRv!{*RGP3>&wbQNzb45V}@5~nR;#gJ?X~a=yI7r?&XDhK z1Q#)DLj6*^!1Kw@u=YEFOTFA*!zNQp23v_}*eJg@DUdu45AG^B$3LRy9}53dIXm$3 zt+;|Cn0WB~QxO7JOlZl6D`O=o5!AlNt0T|Sk4(&6^h#MyiPnr3U@XB#Ep4T>J@UU= zB&|mK4M^c(vM_xlgfhp#=u|+1@LJxz`yeG5L#j_72X9s4PAZQ!5IWX~Cb2xb3* zz1;xA5Bj09IKteJxCe?%^GgaCY&+DP8R$=aBArruI|mXZJDWPKP%Mk@MOvm7D}%H4 zlUGm_`-=)P5KHNTrMGD|^qcR&IL^vt>xzsOYy4&ZkF~B$JM^s+#UE2~H#-J2b9EgT z>Mz>PX(MYp$SO0~*zPCuMP0$SCzjI}#w$rTz`8w)cPEx-jSe{})v2M;SWn5j60}+L zC-}X$!hbSB2H(n@Nh$>I(}XTgM4F&E?phXMPT=0r+wWi}B$V_r!FG$&HL;{OExg2f z=)LcbmRT<8)XbclpX=-N_|=+4scE%mp6QnnzZYj2z3}4dJY85aH&e%bI@gFYES_ps z*H|S}#@wYYyzL>uvaFg;JHd#fJ%N4 z&Pyh)seL|1ky0-sdT`hhPo!@#EnLrCcl*sZ?WOJ&GhcggjEjF}c7~Erb+2nqX$ivx zea3fOy)rpd0^1fDv~NpPw0=r!DB77Kr23_xZ&JRw74<^_vf`b3bv72dV+D;Krd|G9 z3~EY|(HAUgIdKb}b>hH-iu_bU-Du`ZCEqS7WJ1_c53k$ZM;fDHRIKKI$BHwLO2hq~LGE$d!A-1}$M`{Ic~Rs{1iYWk{e zcTuLSM=(4Ie^zTjigEO3$xgS?>L6IkE@*8TWp>fMGSv#pbZ6Wxz~jiHEhlFO)nS!O z)LxO}Um3zTb4cSh5M9QkJMoOCCUrK5HlMtU&?Xb`ZH_xt+I3s=O*;AONb336^Xb=p zu4g#{Y37AbOXo{U-NJ$erZ9bBvNGsr^Q5*WbTUbFrrx|qtwEaBc5C8sT ztR__|h3Ci3r$77Lb0^~k1i3Y9g(?z09mZA?QA5!)Etc%+$l| z#2#^Tj{4GAs`{TR7BL)v_XbZY*HqOz%t+9eyItw+V6Q#aPLY>pC1^)2XBQ`7?d`dg za%&!>aITOFX*2qXY&g1)Cp5=^p`PHFQxps93u8$KD7p+gS|pD&g?<9r?J; z{RN?}SPm7!xGlP+^ImLnczThRexP;gow-DXWb|u^fGDv3mpXl-@o9zuzHx|~9te%Q z(YB;EOuB4iyF(Q7wEZo%e!gcitR>6b~o zSL#{erE)IljNtH);8!XbUVq1xHtQF?bE#W_>n)pJ?VVY>i2w9?+%>CqR9bd)PcaHuFeRsy4Nys z1?%ySJR9n)n~r7Duh8pJ$}5Gmw@j^=ED^%4bKmwTH4lf`QEj4D^>x17p5Bee(6@h` zZl3ObH{6*#O5&)#F3qr$qzBQak#z56DVdT_@PE~OUf#`erY@WK6=U5{mC&?RZi!9? z<_K!(3Hh#BM^j>OE$QS~7Nt$vfLTi<&`%2ZA$fSg1(e1NZ3&FG{*O+*{)Umj|WK>E-5LU)ll9u4yQC3(iB0>Sjfiy<;{~E=k@Q!yW6a|7QV~ONT6H;&NT$ zDQbb|!8S+hj2eW6c*eA(|EaVs3m6{oYU&%DY=AmOlPYJ1i86r?w3NakV{SH8leB1A zluyUgO_RGdmqHkI{In0%vqj~^SJILKMG5stZMgrKo*$|cm9~1>`XfL=HUUPf!B(^p`E!9c!Q~7bJ&=U|*%>B-J%*dT?(XBUG+2;|vkx5Q zHnI$>UB1~Sao-tPpIKf^YCd&a^wMke`S|m>2N~wjnieG-5(&r6ht&_{RozhP-pLhW z?0bg-zoCgQ56FAuO^-2Y8H%QLLYOz{rHOi)J(Vux>Rp&BAcrsJZ5%|C;!@PCgyhu*OL zPeWWEz)Ro1YXhzOOsR+6wrKnw*$^IKeNlON7?*Pw{R6Aw`15=rloxiBHzP8)?+0vD zF%_Z@U3rJo%sv72tpC8HfS=EEj_%M2woNS()0R{@lW6O7cj7`txPQ}KsA<{7!06av z{zTFpa8K~~#HZ?6cND3ziVS}ogim#rHsH`S<87C&9AX-fEeQI(_P9>lN7=p9_qF?r z%}N&fh^vc4yyzzre)U+Lr8n7q)RCg$T^~xW27au)UBlmk8t*ag+0QWl=M5!NL8tEO zq?{P?52cbf0@`tBOGVTo++0kMsGW4)VUSeY0`N&<92U0~DXVES2isnm^ zWp7d8e4G*Xt?oez<_qlRXKI>TZ$@jpYm*4VV?N(W~OcC*6wAz7P(B*@3 zQd6-m9bQWCuy733F2!TITn~zhfWl!oTJeqV+sn%7jbC`URP+b|?xWAT{j@8-Nw26X zHR^nZNTHGLi*gM#k89fc+CdKoNQ-%k&XASqW|cO`i30H9l^_NE8)QArKWo0%PYjX- zVYnh0cX&tVicOYCVq);>{rEyb>dO!`d~R2|Jy)^SqJOfk=p(#@l92yYxmi_g&7v5}ZFJmRh*%w-p|=yaEGP@2-H#e~p{iy0i%`_*?F=l;`Pp5JeO zq?tCakfdF-w1->jC(OBzi_t_!QS>3*Ue^Yf&cpKtpHO;G_BE&@V%jsVD~tp~0f|-b z2$G+NOu`VdMm}xT6H{5Ubuw7{mI=vyJZLC(&^4#hpDbvn#q68J-ig(5TWmJ-;r~+! zJmF1h$%XawiQE_{g(}g6jCSr*21Co z-f<-oe{Y?FC01vptJH7#<)3KX&jnlliYZj2J(Pi~VUJX6b<$d3XRWi|zLPKgmdV+gK`AZeUmNXI>p+u?tQ{S7Feol?X@6c+Atz~`2Xh!ii3 z1PQJ?nI9Uz$4G%hAnbH1c2NhBO8iJpJas;EF0Ol~3EQjD<-=tZQV!D-*8z6)h*Tvv z>2436d`cMWA9emCi}5_$qg4WyrzoWBl~$IJ3?!XT$5}?z-hPvRq6&0xn#B3nE7p!RySHn>ryH<<(1cLG?b9t_y*! zV;&f&VrCyq-!@4N(ana|Tvk9D23Zv;D1{W{UWX11n0F|Ub{|uEPyb%rWFA^s{YAQD z_EW$VE?ztYf}Vd!d4kHnaKu9!siZyex}~uySATBgf0}oc>n6un8&kM-kO$h@O-FZV z+A#Kxj2@x%-TkrHt_Bmi;Q;-X(CP^VTBOKtny4ix`$nEWFzibna(X%(Z#Rcm0H*ww zjLEibWj0+-KXNase59U|VGzHav0omUw-O|}Ye^KOI7)Lu&>p~nERpcf;F%#D-nk=TYSzxyJ>l5pYXG-t) z*bzr=*W?~w{laqX!#^L9`BXT)_mBZi&*O zz4ID;c7Jh*lHj3ptZC`rAj&?WX}O_Gk@rQYPCG)W{rAm-CM{@|9YN|k(FnVGGr z{q}9?pI!glJJI^VB|uWA_4`ca_^niCrfR|lauSUaAGviEe~{|yjEOZlH?*Qc6T54) z=v}OtGWY&XxyWL%A#IPtaKj5nicJ{!0H5A5(4bn%9x>&?;~rnC^3Tjr2Ul<20~

    A+%B=ZY)+%Lx@R+jviR zw9Yawuz4Cu>dtE=K*=+SI6o=x4pSu7uSTD$f6|b6B0>gTBhmiDajahiUS)r8lpCju z^Aq5-q!b*^d&&=mcYhQtW#!`ajKD`_7KTcZ?fI=U=F(5-| zF{pe;^3!>@S4X>VOb0JA4<)APKmf3h4tL(i?pxry0FE?E1nNFLJhzZE|h|K&78=;vM<4Z?B2ROIY9tC!A zs2$A3N=#B8jPV{rjK9y}H~RTg>b(0*oXy+5zFZNT?ioRl$^>D!_PJX@#{n#~#s~5(TKgl)^c9uy4sMLME-U?uVm%QgHPinLB<0VTeq+ zM87t+;*yvaXk25H?&y~tP^zlmpS)I;R?oJ8GYf~Uqj2D#@z-fY>1{E%k-gr-xFPxo zadyeS|B9Pezov&@FZ~CpQT>{fHYy+um5LAj;gz_M;IkJ`3PJ&{!!JCTnmz7{bu-k~ zu01vmsT_M38ox_$>sRXld;k&S=l@PxUpb8vT|u(eX*+84`CVjEM=$5=| z>m6r)2X=&zW))kpmGG7MNTV3A#vb9SH<+VI9#b>j3oZ}F1#7hl2^}f=t=pnYWZbV zml^jVpCLMWd^m6JXJTd$bcyV9n` zR(`e9kz7t2voc$PIyyUQRDwEuM>XztdEsUrwBADcgxI znpsKi*i~@@m)5fV8`b2xHklA(+c|~{53sFr*6eFZ@vGI}(NpU<6x&V%cKT41wB#Rt z?yxDH@>3*})D*)%cf~%)3R#9#4oC4DjbAl1R%yysQ$8Mz!TRm*?j1iehRuKJWGg4? zD&60PeeU@7yT2|2q7PgxYBUstKuF`wGBd7N3~ipTjj#S^Qz!lG;Wc`wh^w9MeaCuu zr*a`^r>QjAmQL5$pj-6kyReBJL;)lwacoidqjr%>Pq{*nKxHQOVw8Abt99^6;jQ2! zBW1Vg6yNjs>ccVAu|ovWy2cu_Bxs9rx(}v}i2+k)d>wNG-t_QWrgrsrtPcEn*T|8m zsvid;4RaU5p1VePNcX*!;n|MtI8z$hFVHZyxTlj>_zQO!JuzdaQ} zpSfzNly(3OyZNT)4JHZ_DIN(AoHF+n-&QxAJIzqOC8m{A@3%=vARftY9Kv&qMHe%O z3NbM}D)e3baI|-A2|ObLae01Ov7=BC*?YX~$r0bnFr!pqG4;LjLNW7A*IlUne)xl8 z(ff;Umgd|sqAE@(Pw4dw@c^4anB@ol&+*oNr)>HY=fiU2=VifqBIW>I};0 zS@=Yk_c`@F@S%rhr2Cqe39EXe^-9Wy9e?aq$r?D!f`AJd&nhMh(~B+b87kUYjxuuA zz0y?6JC{jkD?6;>^qq9hiBTTIp7+ED{q0Y=VH9;b-zrA&#rKmRS5-7%kGxw#>GOwc z!-Z$vNpHZC;6_Gy?kZ^pR*_!}bCbR2f?v8lca)qk7|=4c%jxj$K0G>?qne@1QER^% zZ|Z+h+k1JCi1AozYirUN(|(_@lMz`NyBgdpFT!X#qHGq^0ELg$VVkwvgFiC;4Vgsg zN2tIi7el}DKk9S@=T!$gbdtBFHlxllt!N6H>T63Mro>YfJDKEX3Pr1VOmI*|+qv;) z@HTi1PO->}Kqk<(y;}XD@>~jXGXSVpLtXKfCvz&Zk2`Ivd;dmW5Ozm&tdiI;?+YII z2c=d+@Le60K0m;8r8!o&X6q7TCo9#O0xXr7HOw(U4*t5@LYaGKYQLcBX^U^Ql)^Dv zTbyIkUcx`a`MgOJ*l$by$!McK{r=FenyHjR-F{vz4ZeWkY|H6hmmwuVQmSlaVAJGd z-Ki&=Wd-6q;x=RY_Hs2hNj1@Bj>)squ`vHIVMVp=lRkVRfimtMONf7#(%XqxT}rdT z<)-?;=r3R?*YmR{)Q6-4x~6=sR$=qSO71x2W)nr};heknUO(iB=QCqG!0jr$vEm^; zLwsFVZ+TS;mRRC?YpSRo6&aPpW&-ZEjYe@-vY#PbT^rW@q-9JdeL-_dA=?_KpMT=^ zvC)7-TWwo8%aPPF72a{z6>O=r)a-f_4 znoJi48SBT#h=(F64R?_ges>ajq!=8CtNF6z*Z3ss=g{0(Nn?Od={)DEeLvh9my5E& zVe@0J`%c`^9CSGq_7XP2ZqN<~~WaC)?8`qZEz-I%W zeJzW9G4PMu0N52IyMkm_kn9R_^Zo_)6}ms-fvuR>iixe5*ouj*nAo?v{i>qb+a>>> zZkMpPNLV|?tOGXK*7XJZ@ zmDTCKZojLRzT5-y294@Br5o>5IhtL6DLuEUKXN>_-u&T=7_KWp{F(Q`C*O{F7`R!q z=T4QoJ~w{!6Gew57QJ1e^#)xK+at&7m38nB@FAwgggE8R&k?isx1IqXCNyR@0`ag7 zu?`ouA=rla^HKmiG}vUx$|UU2V21`&BJ@tdHulwGrzU3-*Te+CArNwaiw_Y_-f*%WSpGR?BR)%vQ^6waiw_ z8zPy-2W*kZ7K#6_BJsErc4gyP0Bn+BlMI_=*!R8tW>xm>UhI2X*3&E75Nt!RZ|-65 z(r;)3cHP0QJN{qm4tA}e)j8D0CpM9u0H>h3)qNY zBZ7^HKlUT8aA^b$6A0N-CswAQD_#V}#m@^SYua*zj|b%KobJ6*tsr(Iv^%Zo@%qKS zOrHxF+WPa`URXI`cY+g*uCpSDXYj^fkyCmMdlV#2I7k;VE7~{m$SNPGNN+V zdiCHWKOi1b;N>gATA{`6t_it;K0sZa6gnUOdp=VJh{i_d;)7C@4L5+PG79?e4g| zB@P>y`t=p3`+u`6CwtlW1rTIa1`Twttdbx5_Lv#6qLS*hm?Fn~$KESih zZ1H*c@N($p^nuXv6S8z+O@CChOA^UM!HO19<>Y$lsc4H3v{%$wgbkSJDJX!Y?l@Oh z0D{=hWby??gW*G(hnF=r92&&oA>N;on7VHxwq(hj90W!u!4fN^GwY?usLQTJld!_U z%(q3WOSv5|*ivT^G-4fxm;Q1HcMyJml=Wy5P*2xiw|bRz>}9+OB%Ylr3pUY^1)GT6 z6bSL#sf6{@5K_B@cxJ@1zp$DqDyW83s_Sl-%mnFE#IS;rZw5;4FZI@8n1$Glkkzv? zkX@?2s<#QIGzyWh$k*9Z!-33bx50HXR6&FFUwcB0)?pkd*R09U`< z#XS#oZF^V#;UnpW3vQqfwqI6gWlx0u#{WD*U1?P%O@3|%k7{swa>!RnD6UXQIK8Ss!JTG{QcqNpUV=i0 zT{lALHL#5TK+h9C$r(kEk!(qFJ0jFA8|}LY#$rBIMKZ33tge(Z`$JFtpPEi9a+)n% z^29SOyZf!-Og!+_$bL~+H)tho~eAWp>J01TGzN?zNjJ_%L9snc-#Y)>GUoF?zmy9 zcXk851_KcOsHQV9QXcM=Bmo`Wa|cV39eaI)^Yr7$b)zT(xye#n6p|j5y754b3S*!L z_N`whzNY3d5t$l6;iIqiPszdfVx07^Rvh- zK?%A5s+;)&#LtYKdqM8@Bs~hr{4OK~e}|ZfI!*pr+7T1G!?-w0Z{^t+*o!svTDfdR z3|xrC*KQz;=NWHQJAym#U`e0dL%hc=w+lx#cAvPPRaD+dBi6*z=6UG?Us+M807Rj_ z@Q+wlYaxGm)f751bHZ|ZcBLBCL$=`2`cjqaaq&y_tnP*n2X=v0G-i4IVb3U?{H{~@~OrmDjLb6Ez^ayA&zV4#(& z&XG~)3SPzL^toqqhd4q8CtYz02@hezrHJ8WgeZNRykBmyFA7baf2Q-^6W6qSY7GLi z*9~M7baYuck>|+6s)cS?D|ITT?o&W!(2R4-B$jDyxCTNC{7?Ql#5-iQ{{*i?~V0-jl(DXI$YWeTLQ1$$E*j zb<6wp+*+(wCPV9(F0g zy418|>rDC=FApd#?Stj!x#oyWsP|L&N?B2Bx;1VZpM*+-lQuj_mH_(3KbUpjJfC05 zvzQx!%(-}tPx|DKo)lgFzMQeOi6Ux+g?N;kkNBM42)}<0lgYEw+WG;%;A%sk4t8~X zCyd>h#Mqwn^tVaE00S9vr~lD^?lmrZbX!j<%8mFKIr-t@!O6$zq~p$4!qYM{R0MAE|IAwMd3Ja?h#tj9v%LoB4Q7|9)0zVbvLjnGp6je~DOWZdbx zB%kve>&u(qXdUPApnM1zKA!0q_CPdH%)cNaWVi^EyHxPjPx`mn{y98=3~#HSOk{z; z3zU`#qSJdC;A29_o{v+`OUKKqBV{ zTH-qD2%}CCC;AqS$B766@^r3SnujvZn{u+dr|gpFff>^^2b|^tg}e!E-AJnsszP|9 zRLPSC#mj--Pha{XArMzfm5cVyriH!>4iWo3B;<6M~k ztqbc^ojiUjT}gyhHTFyM5irdjH!ltfZD+=kA=w3MX~um-RZmW zP;eLoQWd}E&K)d7p5X&{T3>$(F+i|+IPN9fihG7#+!F$(>& z@Jp}OgTV_3h9|3>p35x9o#kjXIV-YXNHYF@C3grKjq{V3DHqh<=sA~*^3UeQ4ujVK zbsj!?jYs)Q+P>j?9rRpUJa#eK6y`$wGTAZHmpUC{>zQ$3J=D4ZZRvzHqq4?|+(#yR z3HH*IYs{pPMWQNrolZy&G1{3oMf-TS?X798iu8!ER%c#Q{CLmnxb>Vi|Et(B>^s2< zi5F%AF8He>Ephd()5m%ZtHZT4VvrP!igmeHMo}fBG-N$HI*bDGptx$bWg`wB7(A|W z0^ig05M_?G-0XW5a$vPpQ?nn^)uae^2`VWwy;`Qi=44TvO-DeC~sD~5&o>~A`NKto)AG=0U)oI zvfz~mF*!`v)ycSQXi&Poc^-P*)QIPRjLTVAveRLqGNY;iKv7qdU#~{R-x#Ys{%;|w zb4^VhIaFMP)S6MNF8s>Hfh)=>8;g8>)uH#miaFk82|n}uh0-D4;@s^kedF17x_H2| zTi@737+bABPV6y&qOTc~FE^SxsBzWR?GvO;RSEOy1(aFo#yIoZpTPAjM|UWv6c3Yc zniy&R9@ZfZX!-JFf2GzAY?pfqYL7oCSMO^GHWmhOye0E7QiFduL1a;(O3c-246%E{0UkE>^_O+Sbgzk{-SuB7vcg?Gv>w z4=9ZYrKhnFv$SRs;X`L>Ib{iwr%)Zb%&`mv3v*BfedUc)Ugz&!+y{TnDJb! zAd>a;{Dh1u9u5*f`uzmpe5qi}3+Y@6CBbDENv}K8{+vFLk-f^vT~;I3XsADS#&7ij zY29AN3c%FMo|eh7rXDV|G+&9z|Mu>@qI`Hz(K`%>k4E52X*#u-(v&UDXYWF+Vov&P zh(%*%p#9v|avfIt6FfTN$nC3bJ!a^Orl^BA1}2=0RT3SMgOO0=VE$>(VSiUTEp-Dz zKY`eZhkaH4hZO*09A+uSls>_@Jt2%2gW4zv_^!QVnbs=^K(y34-X}Ao?y4=558KYg%Q+@U2$8G*YhKy)teDxNqXkKt{_< zE|~Oj&}I$32E`8yRD)n;>qy`cvO0qh=81_uTSxE$D=n?m?(pj7Jx&&@6pL! z?*3t~HfYWTpgCi0Yf)AWuWAXT?--M_uxUlER7$SsvQ~$m1PTi1a%USGQn?^$Cy(-6 z$->(CdKN$`&Ip0A2;@N(gg0tW2)-{B*aXSO9{EBw;?X)?ouB`0l&MoK53Su$qE^DDuX7xsz824D>-No1azVC6rfL$t?|Iq2^DWy&kr#*FyR7YP1$2VW}@RmjjlDhkP=3zS$6Zy|(imwHZ106`z9{6T6 z7MO+n(N*)~y0!#GE;LDzOD1Akqat$^&C3nYT5b}AI9=aSmue(^a98kZ1vKP$_<(?C zPI5kcf0h-Co(Oa>zNeCYA~7<`0>Mouei=72^OdsqbG*ESHX!~60RjxvC-B-q!Oe;L z8Vn3}*^X2T?C!7rR~}RWdsE~Jeg4|Oll#r{1HXx~Kok%J{k`HWL2%9F7jW#+x3yf5 zgR>Pi4dd1l*jQx2dMkYp1O4FeJs(o(9@F|`cs zGHIK-c6L<|fF9D;b;|usw0hSE(t)xrKjZH&eAP`#HoUpnMa5{ma`5mK!EI*HqoM28 ztGWqTQ`AwQj3vFSoDfFP@PSl1Uv-#)XV`;Q$6#F#QB+WNQ33P=D;a`ynqIOFfz4#Eo1R0zbwibFVa{hq1fkr_`tCMb#o%Q>VZRd|>@bU@Cp4tL3*h1GC9K0pFbFc7& z$kn2I=VZeo=-90yvm>QcA)YbXoEMo#_Q4j8-@i(Qt=ee_vvwE%bBT)Ebf+Zz|BAgu zHM8VJ`JKqv-8ggk-mUeM^EkHx8^yA-J3&GQTehzKqA2BMeKIhUNVy#P^q5dD)l|@v zTmG){y~>y)5{SuAeB|$pH!}MFmUhtc?kDXpjR+bC&P*@;}=i5+I>#txaC=|D58m zs&-$}1B(;)tXLoP(k@w{5u2^+!vXyvLWTS%>-Je2{;&uMkepH0(b%n~C#m+@fIRV3 zCxr_WwZ5*M1FN;m8mx&58N7bZ@!V(JRoLvR)Y9J;A(0J}q08k`KidWi6!zJF`tEf@ z4UWMI%dgqR;F8=o&8@82ZsFjTBVTdl(Mya>un2dM?i9KhZ7LI6;(z#UxjHn=X5Av+ zUT#4+G%JfmM6OSQNA@4{t+^6Q)1@bODDG~YPY{byWD*{i9z`5<2rGJ}QreMPyjeeWqwGRN#59K3C>jna# zSM`R!@lIKuBG>%Mo<-NNPJwC5_#0+YGlY7=OV8dlY(Bg4z##8gd~)15mNB)CA@*Br zD?3ddj5E{@OM`l*a#R;6{5x4=f;*&rdhImCHGUzUV(SFP<}zh3spMHd_J32v+3J3O zak0R)8yu!$ci6KD)AMeTQziL{mf8wUvLs@CSuaJk{#}+I*|LU&-*7ni?*m0p>)}&) z-;Z)eMnrV0ZEJg|* zXvh(2dp3AIdwZSny!0$fJi^3A4aeEdcjZd$N4`}6&Zw26j>`b~r0y5?}(g21i3 z-<7BALLSeXfdr0fW9K$^D_33?ix>Q|Xyq|Uu}zDraovq1WPdvR1J`=uzC=gcAXj*3 zfQ)0!UFDx^}(ezlpZVuV)KoPioynn0cs3DoG=lGX-VZL3>$cw$fYAMXUq9t zZaVw0{eFpI(^;{Nb)E;-dC^`(fNyi1$2bHyQa|E6Q#h*&z3-Vh@7yME=ez0~2NzWM ziOathiC6(FI!1cs^>x#tXLtIegw#&#nZ06iZca~fd)ZNP(%#7JpJN>QRTMD4iRzLq zFxHU0P4lKrWd%7>j_Q2it6r|vktB9ttg?6O?DQHcNfSto@vN2I;PImh0FRd%e_5x$ zUm$&Uq3YB?>-FP%0E(aB@5~nRym_qK$|&zD{(I7qUp6#=fp|dk-q~7LHsfL+pFg8Y zVd|*ud#{^+z0{cY{0FfS_CP9Z?A<^3U>)HAL@(^mE40lN3ceiG>T5BOSGJ@4LSA{K zM@?yjF*lm+!upCxhSXlALR1 z*NE}bLBJKK?MzL#vD_|;cqyiPV%gZz>w zRtyJtHfJhyu=IhULGJz~H+%DkU=hw5sfXCRJF3llbP6?Y-X94*;B#;1%H!W=Hb8NG z6l$a{4o_^d>yv$|^G9w@xqQ8Milh47Ct$c3u^-kUj7njnjI#&7BM*=NcF{j@V8Sb4 z!)6wD7|4=1B8@)@Bt`n?@KwJBh1hH6Ar)@kx>WsIBO-*Aw!(nWIH1hQz2Rsc*-L?2 zBM`A^^4Iu(Ui~Y1-}EK&P{v=9M;K?ft>+Lo9)K@~PkQd&MEC7IAKOIQ=Y0m9u@-VA zJ7ItI-D~(arE|dG>!`P|<1x{CV$n#|??v$eP_-&C{?5A@{v)P93UE4p+uxeNBXaw@ zXP|Ik**@juXwNud7R#M}@Eoe{C9cJ@38kO>6+cdf6ui=?czq1amkZ;_OtuSrxo3vHy$+#n19Fi zq44&J`;yV>gOAqPBMLCl4dwj`A?vXKu!r$hP5j@;{ahjDcaIEhlNaELRMkzyF6u=2F~x~>(I4*RPI>A2QvF%`(8*iF77vte=7$j*`F)B#w5S9 z)Fnwo?dV_IgDDkS; zfn-e2Ueu4YvQv5yTfRNDeQyYq57c){tMAGE7fCzT7E>w&kV5V4A=%A&UXaVXnki&^ zDShy5^i1=k8`<(*@FOpQE1#8joWCuvMae%B!18)+4-4#O1=s5djy-1LDBX<1r?Ta( z3I}Jtgnrs7+17Sr6RBFqei`N6c4054E95+piTKk;i(DoB02IW8iWABMp@# zmT0K~R;jc7zTPg@Y_}k?K_a_B{g&Rsmi!_&v?dnFWr*}xMIp)dlOb1m4jf#M=c;Nz zZAn+0NZr(g52`vi1V9QhMmhmyi-fs3w-48Lbftmyw*|^KC;z=Sa%6Prgz4He`3?Y) zlE?pja-CZM^zAmNvU@1C?N^XM!(V4|R;sP@%)k$TY6YWH1UKcNfx|9D09OcA+C{3m zn|upLbC2`8MIWT`RmU_xvcE4beGM~cZz5ru+CUNa^jQn#-4_4}aw$G8Zar>*6(0<% znh$@ZE!b{*1}W_lZZ~IvTAkMVBv8Z0Wz=SSE6)t!fHI4Cwx2%$aUiSuXCig8I+Co+^@mc>g zYdNdglOZbnB79{viQR`3L?zFL5aHfr5g}g*ToB(0=u= z8J$bW8^^^D{hS~^PWbWcMy}kqXM_9ft~Yc2f`qIBu;>$|mn09creMI!<&4X@S5IkER8dfvQ08yhb z5xv1eN}{qtZYR`aeiOsmuPSLSr*Ziiebd9B_!rcYxb5ida`mAh7Yn{m7g%YZ8^EBy zLtC&AYiV0J%6BJpUL8!gHu}+YR>!^M&YOY!nMZ2(_fnKt@pci2x2liJvVX*z@1eYF ziH7t`uDoSe^6tD#R~!l}+YuzSiGc*5WJ6q@Kef3io@s+B6F&kHsA}|pDy(hnNp(`J zPe#?(=>)W$H5_yLM08#NY*h9WzS=@lu=fh2W1_cBgbCf+kC%&@6YG+`_tob-1lo-^Lah5 z>uxiu3JGYwkQ~CN_y*q5fCrF_B{Q)X@4tQ-*%i~@7C^k8%^BD9kEWk|jGGB=?wo+t zp^Djy-EfMw!|8cv_H+khyDwY07Dl4^c^LZXy~={TbT=<-e{%Rv+g|*H-WJqwP#dvXLBzqT-R; zPvJ6J$Vjcd(<}m%9xW}EeeZBfCW7eer98e`FeI=YvVi&X5eFZh8!evSr6eaJc7FB9 z5O~imTh6$DB6$ilk>OO1lBcuc==FvwM!#Im4p+LhXa7G+181Xt#sQMTT<{E#dsACW zul%h;YT%-yzu@SLqz4x5h7!jMr&ekXta92Ea3Y4H*Q5TmwGushghLv4OtS$vLYv!N z-n)_W7fvQOC2(Q$$qW`cMyAzm2Vmd}XT*<=HoTz!Ht5 z*rWD>*PV5m+yO$z6w9Cz+_qu8L94b7JLJeJufdkvx2fH@+EEJ-UY=fb#=l-_A4Exe z1Nt?F`vudoD1pw`@0Le{#J*dzZwC%AC~GYCUkAvW7RKXN!RBGw1ed=sWr_dgH$!2% zdUEdsTEtB7t2BRV(q75^BZQ{l5-a@VqbkzU`Ri^4{-Tvt+^!Lurt{q4Dcr3GN$@jz zlVd;6Sot16c)%OsY+&o7Ke5w_exs6CJDL2B%n|N$@!S&Pu0B9hVgau!Z#HuJUv}=D zNJp;EVj#zh#l<7CEVmxSWHT^NZq!%`9T-O|z@+~7MG4f_e3Oe*gXms_w>Fg3A z_qT1%`=+=XV><$VMuv(Lt@ZCiH$abUMc;q?mVx+8`V=l9MQWy$_2oJ1um@knc7^AE zffe95P>PQ7Y3|!M-teN++WpQCKIJ<^S<_AcHznzCJ^NobC2NZ7Mi22mOLSn&6}qEG zIB}4d{jWdPPt!GbGLF-J#V@U!!E`fa(@MIy`id)^%RfFs)&{U+Q*UQjc7=6MVnygJ zl5d?nrkp+1$Z4E-t;Mq()PWvybY&H;-Vb8Xi@?$dsw@B2`x!d2Ghc1zr-ZgfXiLkP z>;9KIBT;n+@wd}`;J6Jg{SrHrp&fh4W$qQrfMN88TRxNNm{81tG>j=NzkB7yR)_ex zo9_ay5hlno5PJms4}t?v>jt^5g?aNJg&+G3n?%IcS%$j!E)Dmj$g)pOM?0~d&wTRw z+L+#+z@Lo9Jq~|Gn|)w`c7$-AT0}>9NXf2nk^BP#M{57;5H0A+?k2weSM*ZEj26Z` z;juvAS3G~%ROs^geU;^f1bTVFdRR|&CQexI#?DYZz&(eht#bWKY<*94^t0W*VNIA6 zW8s~SpR`c0EE^H@JdX%ZQTleEBUum@x^syMum4Hi1UsnF-y5R+q;y_&JRNx#=ZnyX zo@AUglX+2?J9*_GzMHuc2KOAkJ98N404`I6!M}9ITdkjy6Baqk!8K`bVJL$WaH(%Tj;n&nZ+o7<>}_Xj;IJp85Ksf zyP(-nJC|{ixWFAwRSSdC9QwbVWH0N^yR-kgjir-#id%Zp$(D2LPB!bdSl5 zLyPCjdL{+GonNARfZ(<4V`A;Uuip!OZu5Ojxh{bQs{P7@OChWO9Wypn;q4-OF3YKP zKhVT3&eQ<{-gqSKox#7}=zGGmL^T(pqFjinKwmQVNkg_sEV=}on?mXZUgQX$T`RqA z$USs`iWPYPPe8G~qx#nqk_0`0!b_A#u27uVJ4CB5IGiu(+>BTg3PKY<>3SdvvOp?U zB=&HI`d=!n3h{PvnR$6X+D}@?T8+(BRrY(%g{t>O*=GHp($lh84p7xJu^o5n;3)bp z8#7~y<3QU=5P$q~>?=xkma#Qv_T^Ggdqo{lvF`-o=75n-Zv1St?^Dt;K~q;-T)UvVCz8QJ|LeZElz&oL{#ZaV$ryNww{^vtNPNAAndcz$1#@N)0mt9R1MsYP4F_HM`16Qm2B%UC)7uk&K@KY`CJf>s&j zz9(tRu^%G`YQLY0%QgwRP^u(-xMfAqM!ky{@2>*{OZEz`m3qLsq5Q#D*jEXdL?0I& zyS6b2x)$=+NtbaF3fmu=|u*>joF0H-`QV*0tF?OV^WaR zJpa2X1&HGV)|6Pt3yT?LU6(es26P3_f?|iUra}0P`_bFvuhE^;GT(k$;}W0Rsy~uy zO6Hko+%t{U?0~^L!6m(y{!yT*SV^)C2^p}P97zf+6#?p3?}(3XjYaEre$g;F?GNXS zhMMxs4ZGXs)$Q$W0x+tBx=0%C5f%5im1f(2TY#SiMnM-;ozklpFG@ZA&>}{@< z2h2i4)o*1?H1N81x*LR4p>a;3aa-Qc4y0prvNkve{Q6o--5sO!ZC~JGBx?fkp zg-}}pfxW9sQF#Z-IFHvtx935&#pxU!Mgdf2TL#23u7n_W7G`dBt>cC@bqen-!ktepARwK1}42gn(FuUB@?kKL|DC^c0*NKjtT(qtda4 zhElB|PIMK{H4S~d_rxBkp*9!wIC}l*Mh$u~a-grtr4b6dFl({vp+UZ6o^$}B>6TrvRL;4xT0%-Qu3M4YaS>iJEc6sYPat6 z8B7{+(*Op&G!5)Hg4+b_P%lm|oohw9NpxK+5@*<6(Kb6h*;{$_5gMlfso*9NyZHP2 zuS_uiO?a?)8M?M9Kvh%VWca;GrRb7q%dfrj^ppY2C+*m`?8D;)KeL;D9*UsZTy$yP zo)6W2g-m!1L)wTr%~#zLwtCR&;E>#McfdwrR%W34@x|5|Ghtfe-kR(S4aB(<<$fHD zfhbMv*-7`0jMPbzc>LOrm(c=wXF43x>Tk>#Y~*UqK{e@NZ8)Z^* z;grTq-cHLO79Eupv!-xK;Q`vmhQSC>py4^J^kfk(F+#ULL0rgK*q3gsHSzM<_emit z3Esk67B=^>n7|IZc5!y=?k-2#_@RxJP{T&RoYHM{YrXkAsi4S=2gTGmqh1KqU30W-wOp)8pbDl!({TW7z_AzKa-%Z4X6pQT<=)B3#Ah6 z_WqrmykjhGa0;cUA!RDKicR_l7GI!omO##E%xByPN7C4;WYWk7KKyQt_T3!#Ki{4M zN-?T=>(a0eS+JqKL|}-tb9?mi(#P zKNT_rJ8bTIxYRayc<2sPqz2F0KQfW&9`hBZqzzN=m35FWImS4k=M)+rplTAe5zA4% z-Y-GiyN9%=zzJm5%)HvK_kdY*?uD1ylYUv>xms&=bLPJIruFPZ5lI;wbWJPCD8Hq_ zbPy`e>&-Gb6*UNuqouKVfhNnf&+JR- z_5c1b+#ZP4f@Hw))rFyq=<2?jHasWfsK<0q`pB!K zC#Q1Fi>dUCC6-EV#DAP?{*tlrQkOE+!=I^zdH6>ankbrX&)+T_|LI%1DL2N;<=non9JbjA$;n3@hWbW%fgK#-$+57=yQ)@L&x?uo zkZqzi_d7ejCq}2dn`!rdyWT#*0WG{$Cd%KQ5Y~ia$bKS28s1c(PgwBY2vF@Q2syG4 zXv8bO7u`ewrGI}tQt)oQ6mWsOY4AZtJTi6KxppYUC5DJXtOi(-{H9L@>$ox*iGQxn zkI|54y}j@_#0|Pt6A;_rUD48UrSDO5V%VI;jEffWE63eJy_$?xjS+7*rTKjBCo4Y5 zhLS^*{+;c=m+)X&!bZ1e>EzwUtA3eVt3faUYoj`K+uAT?NzR;{@aO-R5o@H&&k1aI zrBupUpEGJEZY5Ep3c1NoN98T#{HMI{R4u04tHP7RW26j^@*|vnv&_F{fHAnZ|J6)x zf*XtZ%DwThQC;yDx$IRGA~4Wi7S{XP+bbz_MZfvV1U=PzRH=f}zRCW19?0X^xcCpO zCoAL>Cb>u+dACyWbHSJ2zGmhjHuHY7zCX@466gar6_Cv5e8qjiFUvoEO3fATaQLB! z5UjfDdBGtq`AJ1gN9TRM^GdR0R8(}gsa=v~P;_z=j3l>M@>c)|!X5~mf7RY6YpqTK!dW^#VyiQ@ zI&)p%dZ01t2*I_hw_s|RQ+NRW`&|}VfDj{R%#3C7H@|;mNXf~ryJRb1bEd$lpl!{y z8SHdSrF!>9PGWFJwyh+m#k_3yT}c=K@()n|Zt#AG@|C=rhD^q6h2+H43)CmfbRBc> zL;kqsm}lRC_3gFrh}gt3PiAT|8z1%cyBZZYoZ~|J$cJEd@zPG0M@nan*mGOf4N)y8 zoxsa<^e$J3Q-x-=;6k_GPg{^&xGGFJoZhQF-#ol4$s<5~by}wSATIzhe3LwG9=c7w z-i!eI7XAf1{^B1CF@Fsvy&BuJYx3cOe*eVA&W zjXV|S;5$;q^NuIoUpzD7yv_nOFU^v-NN3~ryr@2&;B%}K(msx24eHAcOI}cT>Q{Qm zj95AWuy>@@h7Mr8OrYqCESL;>Doa}#sQglAV{Y|$e$d|%r9^*2jxY`+o6?MzHr{tE zXY2lWtKlh3#<}ai&}qti!)9ln$g+@U^Ff+X3DWG0Ydw?z+|l|v;b=9d9-u~)+at;P zY>zu3PV`iM9=~GzfOJ4J5w#nuKLyGmMUI@WI`?5Av?|@La-Ek9&r~A2M$)u!>LDES zrHu^$O?H0#SB|wJ=loXY+rT0l*LFDz#&bQ&DB@TT`|&_BId|HG@awh7pOJNs9IFc& z>D8RZuG|Z)>-yJN{Um+a*s+Q)Xu^lr!#)~21#A4how@pco*dtD)57rl*4VJlhJ|@# zJo5>HY7h5E+3CcOQ$@yI-RKk}qTC@CUnC6}TGagfjeUiOr-|T;J}2jqYbul4M~3r3 z)h^dq5R0$XU)~LGvO3#g{=i0Z@&ayFr^?nQ%9bEmqBBy|sKFc+{@%rDRP1BQ8gDkfCbg_DMl>Dei=%c&g%JkIb zN>sFWgG=Ok$4TKg+1j51EsT5E8ubRerSMy1m?AUOL;GENoC;Z%DtqB zimN6FRN{NltF43g2hTfJUnuD->2}oh2|Y*i07@TZ@oQYX`Lxd$pYCM!?ObtA0r52Q zrt@H^3ZH9W{%G5W>mC>H=(y6 zeftFopd{R9(0+eE&4hPS`&Q))yaUCqm(mx^y_+VLT6?OY9ggk55>bF8SuP>|;HePP0T3bz>|LlAq^t2%Vs!|i_p`KV5$xyX zG<~Ng3sc@gkFp#-je3^FrH({i#Y!q<%w}PZpp8XnUC-z-ezsCeBycWwVP_J zKinZvf+pD%_GkK>u_V7Gt&PXxSe;t`>j&7u`~GibNd5f~Dh}w{i(nOZ+tJ)MD2t6o zMSg4gjg+YDo7F-KZ@J$o&;@U|I@)|9zk0#{>H_avK^}shnt7RU*BPI6~V9t6_1l#u<7=Fi9UH#g~AZJ+R8vu zrDjY0w&@SaUx;uh7-b!wRl1a(#i=ag&G|e@uyJ}#M{{_S|j+*uv_U#CN<61GNg}{(1p08G$ zMD$#Jz&UX(47>LSJb%@Yr7!EPO0%}6V=vX4j=f2GXwl27a{9>aK$R)$V14tX!KclM zvCJHdRY$+noD=YptN4zt|9K;DLT4g1IM8(~xHS6e;2f$BQiy9hq6?N#EF zw#LENQ9&xfYvZ6T+oYc5#E8Q(>Hokco!*6Mv3L~X7RKjaCxuum3f$Hh^yFg=bkm6R zmE?hf`)%5?r&{)UpaKYSqXd80rkXU%vuRPs`F{&N)-GHSpy9pZ0t@K%6i!7XPOpJE6n0G_b=H zvk4x;Qh7Xcp(~L}BjU|}doo+fEboOUzkZUO;BO9gc!h*tR<}Kg%fA}iUwP_7?j<974&T-Efl_3#BUgW>jSv+EURSv`m!IVGP3+rC^QfyxCN=ZOG%775qoq9f zZc6wJ{!@7&jhB5zXK^xBU9b^g9TP09pst1=g-c7>{MIhl6#fBW>(==g^DdPBy*Mmt zo|Lj>JuLsv65$J5e||n~a`+cioDA_7FDySAc|*R`-A>8+`h;g*xiadvr$;|Kol9(; z9JW(_puSG=U9W(*7ac7+#dfBYHuc+azK47?Re8m!UiOnC6yH08QA7L>s(h}Gn7MJ6 zE|({a;JOIZ7!8Asb^)DN%8xGw41Ea-XdR(@+v>@CeAx85n4vawLWz{SXA6J`_SEm| zf8HKsnH`|Q6fdVG^{qEj&6vXVDInyp%N*yLNVXEIkZ!W_>0Ms>UWn0^Sw#(mJfzLf!a3NA;iE^u&Rn?YuNfdR_p*XuRraNdQX4Peg6z zv8A7zH}6zZRGklp!4Zt+n;|KOWD~Xnuy8*W&P|uUm;*8kiM(h;pmL%~PG>ng>bjV&oLY4%+8f84*d^KR{ z$~t$mzDB+pG^e?_TKe|oMc?=*!dkmkIlwIeT{1Pd4k))kEnk%6@?B2VcR8KgHRs(l z?Q;%@OP^P1)&(kG)gjQ``R?USsc5ki zL!wpaO8$%pD(dX~vAavO4c#dxrds3r`zveJy@bix(b*byv=)aam;aT-!es$bn~Yki z;|Im^B!E5n)56I2un6b~$Dv!^Ha^9&(<$*f3O*7=2cX(*t26Eim0R%T6n>u*Ijrda zk80&n7|9Cop`1s~-huPdfRx!uedzjbr5B;KRZa4wGy6;YSpcs)^7Pm2ulc}(MW;Ok zS%ph(q@wI{%!=F!9)ezZ@q=v(&#NTGRj3`kt?TNbW-2qeNX^63QZeRzmX^SF&O8CN zTVnWqJ`B?E%K9YqkUjV_0msl|*Pp=Sp~Q<0iU*8ORZ-rRi7wuo)!&EsM+!n@Lu|Hr zm-mz0G;w&O;4s}m6a|NY@2v@a)D@~yit+b-W&Rx?4k#43HwvH%rW#X^FB95}ZG0G2 zZKhwKEMC7~l(<+vw;t5bSJHnj=k_Jb>*?}DKaKQ?-XGSMA7B(#~W?N}db-VOpEo+}H}gN? zso~I~zG2uLhqvjSL$;qYcM$* zg*+Kj=sK-orA1_#Jn;J&L!9A-n%4-9kzZ_94;ES-TS%LqVB2HuuGo5!hI z;P%P6f*yd?3aGxyD}CTO>?x7kmExq8BJODG=oPdk1K`O;00IMg9O5t8cDkT_wbL&l zwRkv~b$-45i4V=-v6p)xD7+0Q6MOkKC|K`n{mJ66Y=uB3Sr08Muh}2Jq6KRC=D#vO z$&I}TlbV;O%^orXVDy>Qn}yq#ny<^L-M+?(J?&3?%>5Y1{JTlCZ#Z_NOEdshU?0K{gXFY4x@?l-|a zxfC#RUu&fB9EMCG#vJ-%5NZUhV*F8&fooExjT!R<-Kqt3i$t1WT_1X-Ng_$DhHJjx zIH9fi568&2-RIl^xK1zLGkn~mE((UhDZwgC-;dd)YTi302R=I2Sx^Q8hfj2?u6*-9 zBd1`~lpjX@iWOAJ>d8ek=`dfmIXyW)I2ipUH~K@SqXGY)1D@MX+v1n6jT-x=0-j6# zL*&@=_FN$obM&xsss&A8Ej(Va%wVOk9mYcG9n5*^$^x6X_rL*x8a3rb(eq!hMH^gZmD67Px z>kBPuTnynzFw~i#e8knwD&yjnrlI=fMH=1DT6BT{jrdcQuoULW@{5o%Y1f$T2vHb- zJTtZ(w~6*J()pGrG5<}ZRhK&y$2?uJ%DW?SXfvSb{cP>8*WZ0(-@%G5dDBjr79~NU zS|gH{y_sV9XZWYdU7mp zo70It5fSWWA%%-aD=9rO0l4&<&*uaX_LJfo$Rpj2xM%!4%DO<&o56efX3)jt?Fd}% z7)(7tz7Y)+=Cy;@+?p4azdXIF+0bLhptftz?9Bn|X6Wn>ItX=sp2wxzMV;Fo4Yfd^ z1|bxiKF`BdqtJyQ?+?TD;BdAKm@Pv`e1MXtm0ZP_!T>Hx>N`@8EUDKg29u*AG>~-F z0VeU`jmq(|kt+c|(iH;0p?kOInFg2y+LqR+ec8aJ)7_F+_Q-anSi>umzt%`>&;)X< zh|T0#f?W9E+oS4*6dlREv}8g_ftYN5#cG&lc&QZ!-q+xs+ww*_*WYwH!6JD|tk`s1 zvq!4&RueAhx$qXDUVCE^1JVFT?8nhi4S-U`(y^+yZ#+I1g-LAkj{As{37yjOHdTvH zZLw_Q)BMPl%KKpvxG^i*4nxfiB`p2qRQ+ac@px}ftPB5?N!n@u{2(Sj7(6Wvv{mVW zj1Y_pze!#;z-~n}sDja3LF4tnctSG9%Lza;gGc- zi}f1}s6K7~>>a9vQKmm1=mVQx=oTu7SX{*n_?D%F=yeO)BgCs-Iy>+APZL^Q9|s2)hC}v73KjK$s6o>RY6=U1;wNMJX48w`?-U)`3}b!#VPXl>Fbv;Y9_Nc`Jw? z(`n=v71|W&zjXPN#DvU0zk};*+2%jB3x#YJhc{IJIgP)#Ym)xkDu;^$P&Ozg$fI0S zUH&hZS=vO5x*vJ5AbWky7v8SOMMg1WNB&^*l9xszG0D4a+X`U~y3k@i2&d5Fhn zovP;FtHe-%qQvm2{n-q#UUuq`B{x9rgzGAf%=?R6y}l?D|FC@zps%Dr+kdI2R6y;C z$r)k1&q@ucPI=xkZ_9hw^>1b}b65InEfw{i%ysArFEvzxf=srfMMJmOHeNJp)c3Tn zx(=&q-)hS3(_cJh&#s;f_Jpm1SgN}4?xf(h!V$NbZ-7yjRp@c zUwi)^_8`e@@)Iv>TQ~pmI^U_4;?{c+b-r$OK6)+**ODN!MePK^tT^9AS!W*R$=mWe z^G}_l@}1Kve%&Mi4OTPOIQ92KYG!mRl^9C(HJ$XdaGV$doYk=1w)|0I&$Bt*58L{4 z(Az^vT?W&W=qU^Mm6y$jtA$LkkNQZw`rGRaPSz5qy#&orQHd<)wx8<35)k&?1-%Ls z|=ne{o<7}06*rJ7LMK>n>0!`Do)`b6c9pxl;vva71i?L<4P z@8xOhP%6F^$*DSz%~JK7`s)j>oF&`Sn`F!QfY6Y(@toak4Al$v$%Q(x2Xd1vMLosmGRlB6jmYB-h2TLS)%KHJtLWA_QrE z7poIoAlBGRJnm4R7pY3_W!Ouj&`n32e$>BVUYA|jZIu9S@bl9!t>d&tbKeM<68_DE zCc?Vn(>sx=R3gJ`0Z1w(|2sdQLyZG`Ou7|RTDvp0I9;NyueR8yDoz?4(Hi*|L^m+Rfrv)ScS?AGd9 z-D{bnn4IaR#6IRG4tGvoJ8LJ*JPe)UUQv2D73d$cxZ-4{I_cb7C`4YUv*cH%2PfY) zd}0jH+y4sVQ&)4drv*2hn?tv?nuQISQoav!Y^?^DLg67sQNp{WmH%Y#@CE9cwn5WK zUFV#ME5=$r*I#PADS6V~kRn0NN4Iubz4yD6cxX|XLERU ziz`J2eC@N&od|2I56&)!F7ozdwkykcP4*Ug%@^qUBo#KwhR%}On~3v4sv8C&R+|&; zq!;FNlOvxtUr;H8Wqy(lPg6De7|)C{2xx6yx=r^uZtbpV{4XrG*<@XO zFSazI_uPVyzE)p}W|5V1j_ZW$G=bnc9rvy78PpHOWaIY2(o@MXpBYRbW=Azkg0x|z z_6{~MI@K^F6GX$BAeqUjxkWb#N@ywzQczOg| z)w>Q?m8uxhieA3r@%(d=&JSY3hf2$qrrqSYobxRQ=FSH2qw@jTZx%9D*Dhk*W*ucg~{TSpHrv zFSNDl2Mb+0Lr=Bo*Wn)e@r;id?=E=~ew3PwRX6~81&i*7DgRLVyxNc$Z5PZk-^TN$ ztHaQ?ZlnnSGBr|lON;N#tv|m`i{hVpYCG(=5claUtery%5rLb~zuBfeJN9zUSiRE= z@+M`vE)?d+GC2ZiT>HNA)xW88QMzErBY1P!7Dt7kq|F(^^lBY*Q<|nyMbZRLdvepI z@W;OhX1xuNch{dkkz?o-Yo2ne5^#roP6(s=dxcr3uIlAow4cBkZ3W}r_-i|gc0mfb zp1&RxMgn_~jwHA(?;SyuSOcZ9p)5-tF=^)r?ZlA15{KEqfzXAl(xGQfKx|jH=*mwx z&1_6nnCd=(dTW>6@TQlVEIsychTfuAxU19`G5*`4nJ@Bq=&I6aY^OeAiuSoIYDb9f z7BI8E_Y>iTfvzxATwP^O&Ab2k)0fcCdfO>|Yc?wT?JOcd2KTQX;WH=kxsA}^_w zNM6-fLt&K-0}rdkiJ~^jlqLZWz+jb5gtcQA3hWjv>J_S|+w0*$vGo&>ha3KK>|H^@ z!<`X+N_0opC7qmwQe}**f~P+2@x{H?+IjB)Y!zlPa8G2)XH68V8sN+ zm3DmQyutu0e;T0AAFStF%DdN-5MK=;?Z9bbH;a*`vfA|CC#-@`2L6Pv-@)#qpKV z+mm}22!zsE;2LOV^8JU*gfi(j8D$~%SEXi7o-SsrZQ` zDV0{)ks52IxLsASp8)bj1nOVJ;w7lxohW+8dK&B8xC4pUg``^08MR+0a4B-{Ey4aCmGR2xjE%Di9s0jRa~GzG(DNG(h5;CHtSJ-TroJz5KjLyBz{O zA8bnihwzLTHTHICuZ%n1t!CIKyqB94i#E>}+dcp553=X+iz7K z8kl0*y%$p>aI%cSxfu2MUzO2dAC|iHlcVNx46BQxuyRpABszPKV}I|XmcR%Pyq$*+ z*TA8{WcjI+1~kGKFaTxW#JgzW2*U6q8hL`i9|`Iu(ML4sspZ}uX3bPS(5)GlW;<+d zLJGbhq0@giCHvse9 zc27sh*|W1b{s!^{CoufPFcDz9QMWk-k|M+m>3d4>Soh=RcloH>zKNIwGe6tlx!1W% z;QI;mL*k8|`tOhZ0Q62A{Sn;jg8l}#YyR*aroJuMI2bv2=`I>41tt%Y15Zx&dm7?; zv3eJ5--f(Gja@y*iQGaJF5j&Rjb! zn9>~G{i>g(r5+1$(_l$_76cnZ$!+qAzxtIsoHlGn!rj{%JIumSu{h5G2s z`DR4~Ro$jebLLr?XuK#$Z*qzM4}w#Q(%7`FuW~ zK;Q}7`4J?0W=-eHY{?igD)Vg>_T5{#ZI|Ud!nW#HqS_+ z@HBBH;sSu~Iq#i^?+!^)Ldy1lBuU49F>U(=2wnj5ziPpESNBN_&KyF;M^SY@+PydK zoHwf!7iIQ)19U;pR=*R{dBu-t+I%)LGy$?+qn4H&uJXMv%$Aw-;R(O_bNsIW1f!CS z#h*0ws6BN9h+sR-H}n$9hk9`4ct_7O-iyY_AB=Ccwy9@`v6Iss1)zre4q!BdQj{HH ztHN>mjSMh1WJ>5&`hyqgTJwFOP{P13Kkek~jY3RiRQ*y}K6dkkR-Lw+L@CX&PUyBQ z(@IJfg))n`j6&uo6~2GwH|)&g`S++1Pdd;ngu0r8CXk!-rTDD@>2d+nq#THkZfQ!< zm}7}lG9ra)h1*L|g2NM6IrX)Ny%3A7IaTfDg%q#8FPSs|AALv(#PpsddvU$6goq30 z8*wacb$%*aJC(9mTBkr~0kPV-*H8Hlyh<> zQ9IJCj33O+xQnjH{$i;Y@DdbGU};@>xCQ$SeG zmhSpImZGT~833JA+3Yn(J$D@zg|6~$t)7mTrMsB7Zb@ES`_4sjJ3`%4AGN+O&Hshw zcbck6WLw(MO;!EG)M^kjhLu#IsgB%SoSJvJo;J7M(-|IQLH`08jn<8 z4NbQv%nxh}dKSz(P%38V+^ha8&WR6>TrPDcAS)*D?XhqpXG7d=H=w3Dq|nM8)}Qw` z#sc5p4+~vU8O*8HrxZd>8l+_;da6Sqs z=4f;_wK9uJo;ci?!Pkq$7+feYRnqoxDtQq*q6RublEs4~(ab4145W+iZU~;)zo7p# zolsJrIRUV}37dRKHWuSmRUeh9E#-W{BCDf0`1Xc0W!fMG*_o~~)5-Gh*S=J*umO$s zP%0u&2+nRDNz2YW=rH;pv_syUFs-WTE<3~qUuRV)DrtytPcUVi;OU{)9SWt+Gt^+; zTAe>_NV`;!O|xFR+gv6?@(Ydi-;n*~Wo6Sh)9w(uzv4 Yc6VxTENNUtIiGjR)D= zMin3vCOGfX>+ad32vCZNFbfj2B+f$i^uILdohpSxux>d$#uco?wwFxL*i>i>G#s3* zU_W4pf7Pk+^6e#mbiXxl94Omfpvz*dtZK>5t%_LDvq7-*!P^&rJaO?7$GuC_vO(FM zXjBT6<>gv(ltfDVwP0Dk+W>b+ba>Jd5&nK*RfRc@dlxa;VdwxR*F)2HZx#G%sF}aiBpd%z~zDau&#!?oxlO3f8R* zzP4Fj!dqO#HJ@w@6l!4eQ{9f6aAQ6Z##?1d>-$tFKj7{ws~rzU*3!-B5Lz%O;KxXBMr}VM{ZWUU4*e-9sNe z%m7CB5_`m{(4R_m=~FG zIQNOJ3kX(v96S#gW>EdKXZ5qIovMlQua^jN6uNQR71JJYpdvrVEKXV|5Xc+CfI6_| zdKKq7csLLYg_TG33R+^0CI;29))a$5gb)?7s+E3I{aSm{%h-x_lU6Nv-Qd55JN2%t z6dnI*nc0@DSAw0q7Um{? z|IPw){SbksClY;BNdgK+zh-#r3b?FmzEV4#>kkO9P>V4ZB(0IUFk`;_=sr)1?iP^4 zRUBhr-uLG?G(-W{S@Uta#Kv&Dz}tDYP8dQtNY`wRjz2lz^}$Y#Vy1U36a!KL@&w@f zMi9FA_!;-w`i}|yCvQ0iGua7yz5o?6lD!>}pMV(TYypG+f^Bnoxll-63(mL>fgIt4 zJ-7%{`}Vc@=HBieaRTnF##(F-!2n2h^s;SV2IqeEFVYl@AaDB&>&tC$nSP#duA3t( zzoF=8g_rc$`Nxn?(`Q~J{7n6~nCV(Q3cbULr7 zK*{tKSBkQ!hAVh(8z!O!LJRtpfefnK(eb_f{Nd=tqGBKq`6#thZr!#2tw%i5WWkzr+7<=mK3yx!7lOx#8210jN(Fzp`)e z1KaZ?UK$*OZf*F~yKmOyQK9;=%U!f#i_1J}n6*Ea2=rYv&;9vJL)1r(l#1Z5<_`w2 zB=TUWH^#HdcrYv$KKO?iFg?|RuePG?oxziMX+lR`MjU{xpl%ku(v9&W))$P)?`j%IG=v90|c-sn6advmFLK8ry73y_!K{Y>W#-5q^D~&k_l^KJ3XoZ3f515k}?0A1fw@; zqOc*=4(rPl_p)-@dj#ly8&vb>-}mePl^t5iBKOwQDF4iPbSw08H;Ui6Gj95+EjY-g z6aqJ%^_iRy5s3JI?7jIvlyCGuUZQA0B$X{oBt^=awN$cKvhOOgj3xVwwN0{SErU_A zWEW;^GefpYjD0Z1#9-`$F$Oct_x9S}-_Pgq{R_U2_iy(jJ?6fyb6?jv&vVZ6oHHi4 zr+R#2HmMgF(FhE;{Z@@<{(SD*s7w@M|{~Ld9IvicG`I6rZLaa8)pD) zQPq%{#V8TU%HC_{AB-FLhp6~}c^gTh2P;UVW^c=uiMmWkT^@Oq!-!sH#{4>}8-Ub0 z5-t?LyzJ8sE97c~Tpi%M?tfD?)$pi7Ia}T6P4Esm^-#0T$%t)zz9?+6i)gIDP{Q}M z{u6gj9Y!5xQO2E2{O7CyK`h=PdIobZu&wbQi2dgPo8WN$4rU~N znU&S=w;;Hb`(K+Mpc3~0`k>%>C6T`)gUvl`kHo(GmMiNisrmW>W2R$IsW1w%Z6V$F z4!zA6S-dV_!Ivv@&?No>;^ooZo+6&B+1HvVT(dyXx03&$1qZmqm^Oqd+IJt7rNql8 z;sP&7ag>CxAhPwr;>ozSl_1uy^Az6 z8M?pPmr63=Kvyhd3-z1B@j*bFuEQJt4$&|7#)cv%ZrpJ0Zu!&-WJ;AncU)ke8*~SgYc9s0;pxDo<5yIm-AnwUw7wu4!HIwOgO@eel^oiB7`Mw zPQIJy`Ug@1{sC}_KYWU9`Sh2{O4ZIaIG8ICR`(fW8YZ+FGDc2fK`9&na{1)R-d+bt z{5SW=IqnBIFa0+x zUUb1y#{+y2A54T&R>&-H$}QPbr(#=Rg)CePsFH)bwJ!n97D+#AV|HU1V8!!Ci5*p` zGo?DT4~3VrWSJI`deCw;X5Lib{}mRqWIfy>;f|Qq%{TvBLGgd~|Gcjf z72szb5ZG9j>lVtqc_@D%e83A8c9bqSoxivj(yc`h>7T{jG-D~?i{v~IhT`Ny!WPQ* zo{a@E!hsJAjvYv|=r_m`@E2(^k&1d=M%vv?gwzoGE3K$JX zSKog}H)d|C<#lRY8FBigd}O7Z#kQ|Z=0F(w>yg?O_U-?;cF!6B-qC>G=-2jpT@d7H$IU62>;FaBF9+uy}*ANU8xegwtfHu+4*)!vBp@(9S&oAaJ(2 zw^=NJolmlfQuspQs1sN*Z@p=Kqd|ye!Q+SzC%#FT0Ca(PCZri1Vqb_6{p7t{r<>s= zbQr7^9uahdxwVMZ9DrB0k0z%I?e<+nT-U^)7<2Ky9-K?=pX?@% z1r7^orA7S=AYq;#RY|fLIu}Z98SmezDDhyZ{_qO!TzMrw&UhrK4w5Rq2+ur(}w)zzJrcc^FkMIE| z!VzJ2K|3e#W-phEmj;$Ib*gLLtx`+sfI=LrllKZKJHdfG&(#k2H_5!_WQS<(UjmrM!C~5dtb_Dwq-Dc6; z2&G-WrS2%0+A7d0h?s+dz6p^5PdMc|5Nmg5Pq8+XREU%uehD5I{nVl0T#Q1~?Y==QZ)E{0?1gg`GPg6A$ z{l`{|zqjvHAUXdlf(J@JfzjeGjPjo7{w0G(o>ekEXSlEyRgC*wuw&!_x=NU6fW3Oj z$tHET82?fxuNbJUiEK__J=G0T7aWtmU(pT{K)dAWIt*rde=$;5Z)PU$%R1*aH@FljY?=_FceEEKVw_Y7KIb)4aDfSp7o~h#2Y7f{&yVKfz)6+ z$=a`A|2V+eY_Ci&x1_u!L==2&wKiP^+L-~#mgl&N0&%KcB;p3tdai27Aeb}i`%%x$ zUGyjsceBpDV(fU?v{qh8j^mMz!<7Tb(CBqzsb75?>vGb3bE*kFC&M5fy~hJiCK) zw zf7+lYnE|e2sr}i6WBa(-5g93yY1=&wdid$j`^_gtEmb$oj$Jw>*tfjR3seuCWP4RE zxY6)ZqhYxiZ-N!wpaVHpE1)&Bdhw?$6cg{$>10Qh$J2A6!MtCz4`(LZb8~ z#|v)4bee_Dj@-B?XkPp0Rq^*+yy+xlNDKj%I?wf17>&}4B9=GbT3+oe9@FxngFV*ZFWx3on$`_aR9QX>ya zSTo5%&v9CAn(oI!Js}=%Yk>pWTdFh&%7me#YSmmWnCS94~pv< z#a|q#D&XBaF`ruHQ-jSvT1;9khWt0B&{3LogWL9<%R{~Wk!c^KxnmNxV%zjm@1@^< zesxv{=ZYDJuKr5xK?bKDk9*}Paf~*mL706C-w+f9ol9Gj|jm<>)n*FhotV-PE z*m$hmo2?F?38P}W&f<)l)<#81DGPFF z_KDNDxgY1<#P1i?W?uctMjoU1sR4g{;EcRjWxpX2C))L3^EZ+^uMPegm}T|;(Qg{j zH?>ZrOV0EwPn6m7TCgo%*7PzlAYM4=fpY@NX5ArmE{#7Qd_}hOWQ7@qkVN_x$AhFy z)n7quYw%r|t#8sm_Z8ch_|mhR65a7vG#KmPKB62?xXo}kji|K1&9NMO#X&l_t9N3g z;I_lXi~kL?)8M!~`thF01Kjcbjit)mzi?Pwk2gZTtFK=r1+nC$A(O z(Bf!KB`N236K=$(&$rjGQ{i=`R<4UX?-?aL;c0fYUTJ4ag%b%A^72}Czpa!}yTMKN zAF~Kvq1!*P&T2$@?33{)_~K*!kLYo+gSYE7q!z@sPva6_5z=4ThRdcWPS&m2Hko+g z!RT|JAqMtRJfUkU$-m^smD6LL8g0@E4fsBLhC$@NhtBan3(t#}?wo0&+Q3I`IeMF1 zwiWxtBsJSF*}H3b_{$$zn+j{&3miccJ9P_eb&oeL3DUiRqy1p2z7BoCO$8n=M4`Nw zC>j+L;H7%z6JARfETCO&`qC$ec=sPCm$=@K_C zkt*hk2>94XEW?CBE`Q?h3RRPu{`@EgZ9~~HBcn!)B{saeej+cf1$X(?Ym_`)Hw~Id ze2TihX|0aBQsIzxh5Xu5G^0-B0$gOKr_+OY7C8rWs{41Abu0G|SB|59&49dk-%%_| z(ZbPVPYU0pc<>Rv$IiEdMb)7;ztdJ?L(GX^=f(zKfPu zXs6D!!$-L z$n$Km0In-SUdv(J9C^a^Ft>o`gPjTc*h`kL|NXF$&6lHMs-vu8|5b`}c8*O)?1ms^ zV|o%tN_aRLECWM-fQC#ftPAvynWh({EcE8=C1j0zJ&` z<{8hHORk56TqchxT4;dP~0sZ#2@L$0L*G%l{@NRBuQv2V-(EsNT+~>7( zZ4YX&c7Y)8d4Xw{%`Qh3mM4{hwqs;{{4xl?|0p{V)Rhk6W&fM@`Q}n?^q>1Scai_c zkNmyV%i7wvd=3^V{eQg0u?V;aI-s*uvH!O9-$UgAKryrBj!FEz-T(d_c!>IR^d38B z?bE^7|K$GPLo*Aj1S@}}d&++&?0+8KTskkRGMN5A?thNoe}6p24QSQ_#YQ~9e*gQi zzaP#NN51;s&HX2-zaIYg%l+@M{O_9l@16T!h4P=;{QrZttXpJ(yZvoJ98t|e6n?9q z7@^^?A%Ho-r0!~CoB=KB%*8vH~%tu+Wk7c(ErANQ}A z`9r{dUVxh2-+wtvlm+^Hek-TDMV}2iyT3|nz{}3# z(I3u~i6fha`)iVsJ}+9A+rRoy}!wJ9=3vD!^1u(iFf|v_u^`DIX z;vbBPCqdKasD7KTrFT26q_h2Q>N}`IQdK+~gu3>T$3H5jG8MoH2BV&rj2s+ZENU%$*E(!W6F7$1NO zE>^_zUc7x?Qph`{RK*dN`nj;b_ZJF+SPTeg?beCC9hQE_v9s}uKSBH<_=)kJ#!gE; z|DRo5ok-hk2^|TvHr4%+?b#;txL=DxV&hcLr&{Aqx#Jq zB@e4;K)lOr9ZV(&od)vQVfsK{Ls;1_rvYntsF?AK=S)%a1&f-J5m7qA#=Fm>whTLC zA=lsnH*tK-=6q)E@$eOqa~-JXinXE>Q`x{!p?5jGoH4c1O}e6 zuqqk+VKXt9zr*~xJK;btl-^zL#8r430b0}ZGw?FWDV$YTd}^&v6WIL1ohVWpE&A*^AfPcr0qYOvmB>xuMKSu*dALwA;)47+-hoFEIvn>j*f%7&{U&zXJxp(01ow4((IZA^Ea#e3Ss?7POOcwYSmn@Ck*%u0jz<)G>-ED61n^pkVvvpmOJm6)cx1MHS|vlF=W-0 z39V&_e1H6jZfy18sHePjSf>!<7J?<*nyUf@N`!(SSLLj8jc%`D4{bQ7x zk0117?}=Ok<{qA4E#EcQ_jShlbEdysH+vIpIkwR(AMuCV=3(~f3qDLp!A7-Ka=*jg z?&rAC8HiE8oQaj5%+pSuf-y8 ziwAulWE@P}9kX{DNt!%Z`?>g^8~&Q(%r#rfm&Y=izq5`>vT|t!Tc-R%XjCD`lO|sy z5uU*f+M%;OsH+&cbVy+iL~l=UX8Pgps(^tqX}c71Cqy+lK)y{umi4*iUa7`((X3yX zF@X+ug*~^`_ug%WcdiWazYX*-8}gN%C$Fr7bFn*DPev>yPv^o}CJ zk>m3H++}s=BP-R-`n4nexSiwk(@l3q%+J;}$14|ZysjwNkSomJNb@t@>9`|}PfCd} zGT8VLHp}&8qp7f9(1JWJ0%>~XI1pHr?ydGD@R#*hcYSj42%I3kgj4IM7KCM-Oj*A*^Y<77O3`rsy2H5(hfH(4{hHbsmPTCx z+bnF}UC8YTzvucUOjN4E3cCVw2**umvqu_pXwHohjPdVXKS&8nSjsgurNYkRtB0Ep?rC^!; z`Ns?^@mbM)Xp*>en6#7-VGV*$d7&#LDmqfIEaw#>|M`>Mr!cYx?lvr$=%S{)Z*u?A z*kHhITsqh%$u0Lw%Pzy6rl7^7` zzHH__Eg`y46w7Y@YZQB5MwT3>MLy$YWq%T-w(irR)cOX;*=KhO4CMtOZBGxKoAIQ1 zn^-}QkN@~#vQ0~!sxWX%;a>QLHnXM`Gal;?^v|jc`HL8(dk;MB^R14leEP3Hk36QZ z^lN~=2TB64$>|SE&Hh%xQ^6P==$*k$G2!mbhY|Bi9KT{IL-za+Bn#q7YGdcz9@+Vv z=Q+`LtPu3klK{t!7Eu?#W_Nw>Ow4^ULu@R|2SEZ36$>=CJtxv5yoEIxZMue+d;d&| zZo7Brt3|1Vw+-b&Q(Gxn@v*Wg-sm-2*EEXO#b4rPE!*9ikKK5YJwDlV!uZj}@KpDQ z&Qv6P({tQ|#>g`d7wmimr8r~|UCg3m7R*ckCbTYP3 z15al>c{-~Spq509<(AL81bieyzX1Yl%q z(ehjEgDjx(8XKyMz)=%ujx5Rk+tyg8-ZHPq$NsfMV?EDHUfv- zXOUCJ!SnE)9yR{*H z9?JCA7uog4*G4yvo6O$+BNHx}uVG`qtuT@D{!ASDUM6a`8>);Z+`Z%wVn=`FxS?q_ z#!;gh-qsG?92L)B^!k9tEYzuzgH`MEUD4O_DbFiLZ{&9izQ~~Ze1kj_zOlPOHkgm5 zxKcHvhrYULb+yTh@w{52LD5(BkD?aIraQkvc0CE^?3W+@8Oc(KXgBfxO?#IzQ7f-i z8t`%ba|sp6i9se&9AGnT+4S*D(7snt0ALBjb8>(HEdPwFKdCc{k+98v_2&W2(2a)A zBu{>#b?G#%Gv1iJ@EJbsEc{_@@=J9(G*pvEIxKaKcXMlIZ$|Yi^%W&tM+j-Z`02ie*%;f%2d~)iiCwfnmob@DkrL5%BNIV zy3&U@*Tv|h$H4>7?Ket=aUD(6k~_pRyQ##7;4$8Z;NCD&S?v~9Ty<+hDt^yc?K(4Z zwV*F)su*Q2o5)3}!;RsZC^|lM zWy<oNJFz`Z;TVQZ|s+d9EX8^oADw;ISIFxz zpm9#*?ORhq=!||M|2Xv8<-NHfirn3+{uORiNHcQ%wcGP+4WO9V!HdhRW5QYs!WF{S zlr3c|`jKJv3HZk&n~nAK{-+j3D^(LjxYqa}4ou6R3O<*t(YV(dEIY+g!*` zsdHxBG4SrW2fc0QXIICH+MX_v+SH|Hiql|QQJW{*T~QU7n{?~Tv`kO}G=S&D`z&j} z2cHfb>XIaUvmYX&XXZkb1L&oT4Y-FZ0p& z(Myy(fM?~82XS!E-TX6^CHTzRNUfaKWkgQSuTyy?qejWZYwOzZT1h8Z z&OJmlZS*}SElrv6>uSoiRzB0}a+WpZ6lR_FPQxY+Jl8;$TJF+@Ax(^J{iOqpJ!#L@X12!`aai~3yw)IhA)Ti?$Vg3v}RHDl{8QZ>ckL1g^2#YW)STcZIa^;2>VeSX&s zBy=M-b(O0Rchkb=qNI^xQrAqjiG6pt8YC3NPi|>Vj5cu&kJ#sSn`JHvDlam)zlDL| z8h(%BMVwuXwktt0I6@;ZSQ2J4-A?2kq62aXqxKz$W6m}8|4I$tFwLSjg*bVGUSX`ifBKv5qAwS zC@EDV`S>eEMYi~4Yp8KB?inX?Enq$MS$i74hD<(sZ=_=*Ss;R`z8rVWyWiC{m}kDtrZ?M-p-6$nyH zhbr&A#cIX~pyL;hz(Ky&5D;WYgJtnp95dqnmHOWV8T;*~KH9rW=>@RF#(Njd{k;I( z+It&t&STO62>U^<*X21wWik$pbIJ0*Yf>t!@v+#t^YtCg2p8%zI_`#smn62~n!}Z9 zx0o;1FbkME>3gcNns`1_MJB%pqlis(Keg6Y`JD~`qQ}DHgtXwtMe|2Y^ycF#l;cCG z>4~(NSXk}mZ5Q#+p+lI$jmYtGsF|23V^q$2c*4RP4SI9jqO;rTX9Fq$%2iL8+q!0e z>`t02vEGn?)iS9$Tu?vR9}&KBzdQF-T-tXp`rgb~yOxt1Pij?8fMUX|wUF;47Pe|R zTGqlEO>#>j0ieTHW&)@rF*XU-SkJ(lyq3AzP~jI3vga-Y&np*Nl=f8C&U=)HZJrF# zET!_i=#%;4=9Y2*uu#yIr#tI~42ZsW2!YWy{u6etOvLZlo%KtyZ~GKmcE$?}Hh!fP zU_IC|_C8kn5!0FuBD#eq7Yx>97zir63i;7*cy&|~w_2Rc-TWTB@A7Mkz4V@yK^l0tvnsXTyA>Me zY2&O`70zg1o8r%T-=CK4rpZo(XK1FIhkX#S##KWX5Xb}|5QtRmO%_&oR<06q>$Zf4%LUd(PDn}S zlZmu9&`s_*-i`wPM{jw*m;Wp}GqKsAWiYP;D-|mV5(tRTv5TPgrA}-Vd-1c!s8$(= z>gs1Wn0gZgY6p!F)3;}s`t!Wo65-!EP100io|xCPiZC+9UtW`X)R0~*^_&7dj5 zo>JhYmu|K>&x2bg=t-9=2(ev!-9-dnBOKGyy3~1m?UC(caM*Vfsuu*0jMjC;c-hhRi30^w^XKA(s=lIvu?0 ztttXOrfdy3=+B2S6+F6fr1k^RY=(7L=Vl+MvKU|4|nbf8(k&)U0tO5QJ829W5^4Z_*M+Oijb~eP+Z(z3tKvKEa0NAI21m&)o6qg^46~|Wfvm9HDO-6 zNwC1OAz^J-Cl|deCoI!H%^FQKnyD{#6R=pp6iNcrDB_+Q<>doD?*IW9{)|}gIOQ&4 zEm&MXRPyr?Q(V7AMK_#|m{{Q0pdzOXT!RoX7~QyAa}VEaAU_)j4g-*;IT;9t$m;2Q zm5j>gdG>q;f2q<+XU17&7OdCgzT1GPPL72vW%e7NaDDJBliQQt6~t$=v9x&Oa>1DS zc!#aIQS_1c3K0-xn%DswZKBH$el@yvfrkUV{$_=m@aa_|sX3plpy<&D|_Kb`yheN#ZgOQyE7b3Z%pvvT3Y>4}E9QsEb2 zw4x7+j5;^DjH1mMi=jk6OqNfa1FA7~E`KN}W?TrM(Xs zJ|7JLfzxfIksAQWCW-HEWZAkT#+O5&ul_h)PY!?Y?+%VircPxCjK{@hDqI1DUp+_A z4IOS2tnNSz&4$;QW(dbrCzpU0oU^~NiM6N?lKJE-TyfW4k@-N2UK;yx+>iTlT*VIy zJeEhJl%(K6U9E0~X$?qe=g&JgW<+T?_#kJ<^NfWGqg$0fvmCe}+6WnXM{oCaG%7GB z6ZC$tQCT&^sFV*x-Af#@i5PoGndOJVjR~0cs|#21Gu6u)va9oa6SW}Btk)h*p-gc^ zx9(XpOE^#KD1lCw4wIFNVJb)+hV6Z+C6B(VZLouHy|E`8lk>K3UE8J?Keied4!Dg3 z4QY63ZWYbrpj4fnjeK1Ue7oi1upqO^xDh>}iD*&+<*$)uJsrns9wdxaaCV041q-ZI zy8&y#(KgygC8U2zd^_zO3LKdjkvhfVE3%d0F4ygi2))~(e1^6k&gQm!1;|0{5hz7_ zo`oOrL6DidTTn8TeTGTaQVrYv=_=Asj9I>LVzvY_Vk!3gn{j|JZ0Ge2gIb%}IPV%8 zx#4${<6)fhUe+lpA7g~W?Yc(!zifOA&2N@{Y6jkGx|F0?i*E~v{?R1oY)rnSW#5>nRUCx=dFQfla0M8b1%IUII`sK&_ib{W?1eWp|BtN|T_}_7 z(2QDaIj%O^(euh1_szb?zMyU;<^zet4x0ngyCX!qXHOoK_086u?HqXq{i#Y_5cEDL zq71}6e-dZG7OFWjr#ctnF9&H!4GiyxQ$>`Q^V2tmhzpQA)H*UwNh7CoarG?&IVBFvDIsd^ zXAS;`f~0*~g*=t&JkcaM)2!|p+=Li&3K_YVwbUcyz_8XwkWy;zc@CYu6tvVQ-9D~L ze9AnlajG-pEII;zLiJz><(YlS8mSPU$U0rV-Bu0So*Khir0436045A`GgTsbN zU%|-vWyKKpNLhl6a28XfJi)EXn~7Ec9o)~i=B5LjvMZ9uPVUExer4IZS###x+Yf~;hdhRpW~{_w7lh96x2f*QOKYsXUru~ny)aIrR425AkvlidZE_de-9jrY zmub;+|EGbt=<^^}#zi<4!kUoLVDYQ8Jeii}*NM#u(*mou%Pk`CDA30Oy)sG4kw7D! z_B%pT-bEL{7eRMbnf-gTb9%{j4PLl@7xt&nu&~|FsVGV|6&vUD{(WVP(|bE`vLVhu zf{n0MoSKu(`*MinJ@!1uL()fYMRcUb(0(MZN8wmiVliG!{(j-3&h9nga5d$nFf5G` z^`1SHdMteraOXlEvHSDY=?WhuYR|VK>n^?Xg2U1 zaY)y%qpeAPEeJNA;%%=gg%Pk!`*6rBbk3H_sKMz@x819S)q%!zR=*$Sz{KnG7{&VK z<=_xbw`vo?c9oIBFI-8Yt#-e}a1A@2we?7a2w~LU%ZU-1a1W74(ta~)f$tN|o0#@Mz; z?P3plj9M2m6W~F^P4{($-^kxGW#_)>-0bE{rC;*Y&EIl2?(LfQ*B1Ll^Tbj0U#dWxacKDqlI&D?k3R zD#r7I$Zz<8I$=fLF3>0##tq*^29BK#(S)ZoEHD4;%ztz%G0jV#f=!?~9G?U|@&QVM{^oVY3%l;OdU485{I4K>MS^gJOn_NyDUc0i*k839E9xj zD!ajt0PCIy;DCIcJ#{=Pio60K`2GYrOhRu8js6K2EF90ULcFZ z^ygoScsJ%hxV0-yXbkK@Y}&{`x(oEG*CaNobTNon8m&H~%xM-2X-WI&|$Cm{3tTB)g$ z!}G27fKw|mruv44UBL;z*c5yNzd@1Y5APe7FMwD5_0ECV_ui4G%LTF`OS?t`e)!^d zFFV&OqbqRqox12NpUr1Llowsl_VJB6)iQo+8N$19VYLYf&}ZxemYc4aMC{(dj19~9 z?(pPXxS!J;`3aI3U-$XvJzQS?~?^+zJ#-t>cl*!S?NS1eSIBrC4R1nhCL^1Cie=JPc6C-z$sN#hM zr}#PCOeIMf9@Qrnr-=@+fMHSf>RGt6`?~rexcNQBCijNd3cQQ)v@_$`weDNB_QxOC zZ`_|$(d?Ahm{mSbU$`!aAY}SZeumvZO|;t-1MOGmZ2s&Bn4TjGjng(ki9j@!^&ODy zz5Mwjo1S9|t8=jB0FQ%@_)QBbX-a#A5dmy#Ijw4vvp2R?ZN`!}Zx#tPj*ED@a#mba zMV5fswc}6XE~TJsDmKloIU%3EVT^rscn0H+qXlm)X^_5)>Z&jrvH|^jLkU=S!|Fpu z()yBQXLpsV!{VSy!b_tr(*%!(4#o@yt&nf3nbGfxxi^2k5V6Q7fOJ~4?G6bCUA~!{ z-5j8Nj~$*;eR^NkaUA#96P)S{BDFCr{K|qmryI34no|RdL!RBBEQY*RgI8?uQ({2b zJREV5>0O~-AK6labH;J#xAvX^Q@9^by}EQbl^d2aAs6j3AbR6g1x@@bp=Gn#<$ecb zAvO^=r0zAO=1H(Nu7a!(^J^E(-w|i+JcN}?h{S32Ko~~r%b>LHxcX9L=(y(x?j{wf zsmyeu2;M(_v`aT}U3u3`Uj*~B`Jx$PXnAgQl$ju6pT6uqRh_r~>)TOV7zBO^I3<74 zce=e3g=o$JEUdo(QWV!sPixMRLVHZC!2132W0H~`6`OoIB8!{@@f_>4i9GA-3DAJB zx)J1*@vs=!_Jl@X%~=g1=Y&?iQY*JqSf@yk(2Jqkvd+bCXK6$~Q(E=)vT(YRVYvzJ z?mVVe!>fbjWFJ#+;%YS0J6*S(M9&}eUm5Bu&$MW)tKWwnz-I2v?X$TAybb4Z z8oNGy)aaM~jvsNC4R?K~NwF5pvX&m7H{8Gr*Wr@&tnmF`|3@aiQ4sii=4smT{jPHT?_1xn%Z#E?6(p|e|;^u&%4Jn+SK(5Lt{U1aph;y}iUE^L$Aj)z@N{6uWmqlS$* zn}Ug?fUzfLmovi=nKf%j=Z9^Nfu)|3&W(0_-!1!$Mc`s@4WduO@7n5H9g@YW49Oe) zJD97sx(B~Ub;GpX;r2oXjLB5PJiuv_1v+t3G+V0vnMCjBA9+MN(~8Jvpd%$*uyVb( z;@cd!xW3*?;W$coUAX8%k{gB!GQcX-yB;Ef`eT4r?C@ zS+2qWJUJ@_UD;5@7-wv&@a3EszH?1<^W^e3Qu)B9QYk6$%rTW@Mv%wHQZo2czSGw) z{(dO1Kkma=IfDJ=F&o35*X$FKo4+Z~5|Fx?p-P>Ie|(r)0QeZ-Lob;)a-=F^ORMZKY?1RZ;te0|14LjK~_c0bv< z#=8P&WPx96Jhrks?MWv#C_}@k#7*`mQC_LtH0=D(T3-@j!kHRyA->lrKZ9M0nE$6p(Qnph#bCbK2*KC+P*`Ve4fH{Ldy;=#*IilpK}=N>{cdAKqj!knOFBcFgu68O1q(hy;`^evu6S$>Cy% zG2IPYE5R?U{w9kUq4}~si_u;-o~XcDf)%10F%lNKCW?e(CMwsPa$?`^yq>gvq? zS%Da*4m*S2{8-l*5tjv9BnlG-$D9AIu->%`)x(v=4Xdp<;fF=~$Bg#4VCLjs&SPtS zW9zY@HY zuXA;i^4awS8FB|U5II=e^p(hUL|31EI3EslifrXg;uf@r7M+Y5;+fm=U?{{l=nxuu zs;+|wAd}K5iRpAs^er;nKp(y1H{f2ghPg8}2iv=t4~y98AVbE4VYI=Om|BO>*_tcL zkd@!w3O1UvVrtaoeO3T|cG&}toi`xRS69dtXRaaNekvdEXd1)V``=-%4H<1*nW`Ig z`LQ~rA(6pFzA7?Xb9(D5u~0*eK|0;KU$%;0NY1K8d8=W)lh@V&lo zpIJ7MXjsX&jW=rInadFwx+3Effy;eh87*w)B;C=HiNC4I6NR3;{-c)~_j`MjXud%WqN0 z#2rNiw-Gl8f{3UIAhLvnL>Lv3C9+6FmN+1yqJ(iF$daHeQ4u1t1PCNRga9#w5VDc& zc3_-gzL|5rbMF0d@42V>l{B61x9feY>Zzxy-cH_tb6YvhEmA&!m-`MZ(RVb+SSeW^ zE3I{J5#A*=1O6!>cAV&ZdH6BQepLPC)RBk)1lR6N+!x=>o1yD|ODGzr0tKxp#?}uu zdg6~bK~?XRg<1xl%#c}()_{mZxnv->65Qz^ien71#GW5xmk@+jW)T9_q2Y=$H@&?= zE73sd@Ci<6*W1<8#Z0=M-@8kUo5$WSC%dBu^xW$}W(Dm(Qh?f)bfL@X#*CjC zw|X{v#Ox%?B9-Vf4&zJ1QwPCh@JEd-KuANQj zx<-h==g{no1fPQnHKx{fbj(PGF+$x-4abEkp|9Snp7=r)?^7Y7%ArGYhSR#;x2WUJE;Q{1a1*ULC+ld{wyYOw+I;+2oF{!4p>^VPPt6?;CPi?k`N z4gdgmnxNWiJVAx3=G@_i}*uobQyYU%f|L+|$%TB8n_i zf~}TjJ@CBkwk6l-IqQ+6D*Q5h%!Py{%{FLI9ngosB}>hJO=^y(IHlZ!bM?8(MtRv& zc$dFc|0cbN0?g^K8{vLP`kQNL}}=F z2fy)+P1yT3naDcj1 zG&cDkge@XSB{q!@uK24w=kw${aB!09%gGk?uY!u@qc1^nY=nm{_x5{71jn*q{#M3^@0(r2zc(*F()lpI%lr$H<&^w6 zmTx3-$lQ$j7T1LN+JqJARN$DS=Bi)Uwp{KFOEIu#<>5 zL3oa%r`&I|uH-%@B~Vb2<1*LEC&Tu!kdoDY*1t}Z6!ry5gxnume81hRQftHM9NcJ& zkO4Qlu|yKIpt;{Az3Bp4Btn+7#3G}`bXQbMaNWvz=53L%t7p=Caiz7fk3Lhj0+{<@ z#gl?P-gkpcbl+G(bt=?87BwSf zk^7C9#pcKMyRw`IgI$S_+-Ae#QWoT8Rq6)7p}MFt$3hS8FD53U)yL(RHshB6Hj)vr z#+;du_!5BsO_nd*gD`!aL!KnY-JxIi$?Eh-8EbOtoZOLJ^m62#+>47CYfb_z`&Y;H zgEb<=Cd@l=bWrVI= zLHocBU1zY4Vx4p)xj5+2^p?Xxa-$b%{~Lb;(HmN$&ZJ=Tm0 zld@ry4ww4riGhlQ4q+?WFN`CNwkz>@bK%zSHb7tu(<)NuXScWZPL^;N5&4#+jjsyI zShx0E)}H2CIrhZ9=87?-TS4)xI1=W5#LF!t;+FT4TQ<*@uof!cwd`)#0_3!Q1466? zw%JegkFSZ^Cu|ukO)cs5{a8US&TPC~B9N-c>D*6YvDWu#Dp6_5Wv=};<6j&) zzM2u;2Jg+~Q~Q(V`X%fcQ7HHifWD%t$4yUKzx1ZPfB9iWvb%s@JSOnjWwL_+6}P9l zMuag|kDs!3k_(vp%fF@q+p}W!VHK*zmSIM~8Gw2Ga(;hgkxSo=%#V_a9FMqKlxf5X z4S%y*Q2x#%{knbWjCy9V3~ny>a}e;c)QFmp%*+) zf7hFqsC{VV&eE0Xi`>gv7^AO@QySo?8OM_Ivrcqf#G-ztnpU-BuaHsFV>9e*pc2wC z_6v0u|H0UY&ba-(K4aM7C%|+cGIqSzRqGJ{FxdaxIbheSv}1r<@Xv6q(YOVA%G*NW zi7ZU0ZIRsu$|l%5?g%e~)i7koYvJ8&@Q)xFLk^USMhE{R33{is;eln9GK- zI4SoEzhjFEh6(8@r>KE%HTMbIJjL$iMTrBlTp52U+8!cLvtxGC97Et6;pUtEv!UckEwM1>{iHZPdnc%;`H zvnfx~f9B}VUybh-&Sb&oMD5$+`D+DtVJrIu)9ggED0(@2ryx5{rj3P~pfDnAXaQXs z%IU&+Cc9ygE(CiYhFr}sMqS3*OFl6MHmcfpb{v`p04N1s7Nx5~V1CAz28(|P7#j)AMh_=N#PpxD+5JwG1IcuZax;G9kD#M+< zfVN>u8hbD%46jvXE4F%xw1-P0Ok;0Oi`q8xO4g2%ud_;H7MfG3kS>J12WRxcbNWE6 zG?8MMb>C4|lIp2=nmX71(fdW?Fq;M5nkJtZr`PazovYA(Fx#R%o{D_;ys?LhFc#`* z+4)=ppS#{;`){4yNif@=OYI_~^2Vy2`yW)LbWou3r|y?57ksBicMR-&G&FznOYyLM zzbS$rjqb?=st|A)fHO{Yg_`F9t-07xNaL>a;!?qqa2^4X!3w#zmyuUq9m$G02!e3^eUkHGk?mNr?d9@R=hrAPi8f-!^7>JH{@-x?wdl#kdB`Y zqoZ)JM{K?Yu8uMSxV#w1CYNQe+C5W3a{Sy*-|TC)j=%8^F?QYlUULY#J)8)1LG1RV zNIxQC-zs6fNs=OEuGZ9ygb(z7ZU#VlHQIz%; z9zj3500j|;$D$p$ic}SEEY+&y(odZzMlyrN9ok??=1G21roUIZF+A-YC67g@`8C&l za%R-LSKs?A)34fOF0rjRCL&}VWBFfnMmYy$?fI8UgqI6Y;lS!oxm{?!G)a0Ba&`l) zlRgR`D>-RB{d1V2$y?NE6IIH`!7o0=68+_Hv5JmcWkOiB$ZoayV~Fr}D%l*{Z*mV8 z2k@`nQ6Uh|JNegcdd8SI_=?x7_EO#}i7#Z2tq&jqhPE3@&(gz7kG;Br+eL*EBXOlD z7u*My1w{U-QEfYe&m!-l0G$sx`F%2c;_e@+d7RNtauMcurqOgW3QZFA7l_b*or+l>DVjnJ>zTenbVo$M3T zld*UUX>DJnkz4hG*xLhlis+Esl|7KxU11--n-=1%29Kjd_#g1GP#y`dbhIT^6Q_uNGJ>xQf4|{7Ut6irC3YN?8mv z2Cj&beyoO}2{#!PqiV~>9ajhnj}>J1&dc%vHD2m8pJj>os3xJgwT-w~d>^fqCkvU_ z+UHO9Ofc)$X9Ds0+Lt}o4}5Dh{9{w4Sv$vhjUi_aqn**Rv!fb#ittvHvfLLt6S3np@EO2nObm`fTad5yh()yb!o!t zfaYP+VuI#j(yxK$0W=TaKm{NP&^&!s2K=S~GfM8S$RR4j2`h;@?xra%M z2r@(y>=#ISO#&v+JWNuX|2^}tzW62b+g<=5^Qr-zpk9G`H8myh-_t8lmq1?3@$kc%-^SKgjXWMg(4^meUHtrVrPu5e*S6Z6IG2UZ2x*ngU@qys zz9I3=s(EfkD2Jvd4w*F-KKje)MO#j8}McCuNC$)35 z{`Ka(!29p%>7Txz9bM1N`+K7K=FG+5gG_b9fC_8{X9QeYQ))Os9RaP@)UqDX{DOW& zgOq-+%>q3;2vMfyR6(o-qTfG^1HkivFdmFYrqmIG5h57s{*D|btOOXdgDlFQU=k!B zKwfJqn4AZa4#)E7;$i{B1VGRTg2t)l5d@7OX#7v0ku?zYVA?c;b$fSiI|^p6z*fE~^epI8 zz%J1#op+O#1oSDOPx((i1@t4J9|8Ty9})n262YFtsrf#z3gZ7>6-2hJ&%TM)7ubv_ z+OVfJr9^&NCQ`cB@rTJLolbdL6IhOGv7V4LVr|SU4KPLvwTBBSU)WJ)eWOWrD2{pL zfIx{9ipAp$fv9b~l#NSk@?#OgB8SD9$c9i9`Ip{6c@Lr;5kMC{<%tK!M_yaupeCHi zjoIq=C8`FgR8{q&FGf#N2ZK65jqLNo;wD0QhlH!!M*K4)7im^do36rtHdZbED(v&4 zk&mnF5EKZmUdHbkp@^z^885qwqCp`f=RIpEvFb$%AE+IVBh7#x^wTKddDgWaMoM#<`F6el_R%xv`L+Dh4h zl*t+G)Z*$C`#QLKQ?~`!mr}?MYQ;N|fTt2HbUV_alB&e$Jf%{|t9yfhu=JuBSVZ~U zNbYNSV?Z_*8(wQO4ME4N+egHubXw%5Y$*0xEsak(t~wJR&7g0ZTc!a;)1v-uAh1sC zYsHYNuLn9mo8|CYb514IY=q2eXNjaSj>U5?XLN`&NiYJ9f^6vNy2h~A4%^Xfhs>s6 zGGi)uZOCTEoNMe?h=d!$woo*R8R|%Igaxavw<~Bj)xzNx>Fa1(t)sz&^%*GvHl(47 zL_?anD$XHJXBXAOpUe*{`-U>+QVuYg#t>8(6mj3HanDU8Wu|`1@dD^q1u@-xY z6K|g3FO=3xcl%*ZU4fDZgC=jd%geZ&i9csZR#7-S0+t*J;q`M7R2C}I=sP+m6XxR- zpbS_425+;^RGX@`1jEMH7{Mg2EaYPy)`V$U!W63~m)!=irce}CI83+yY z{qh6atstQ>8Z~m#ijv6{YSCyR=c@_B4Tq-^sg=TX1~Q+^X6?-y##x6lJ)wm$m0URk z$rYXXWUsQUWt7;$IB@8Zz{pFIPBzEbJ*G~9zv(d%5>+12S*%Ui-p-kr)n6(lCc}Er z6@zc=wUxItljyv9J*Tj)F2gzW7y592--}jMK8N{?fuxN3ESFAlB0Tkud#^(;YH%*3`VFTi_Q)%#1RPge2OdxqUh(+ zsH9&5B30wT(>Oj7D*ZH!-AY?n9&(A?-zSir{E?$qiyHXn$7GRJt)q27|m~J7h3{CAuj2UteI3Bg8iepD^h!ZT7&e&yz3e&u~RvY35Ja~AqXS(J~p*BV_ zUNg#;bLy<|cs7>3k)r?m;yuBE)d(7;s3H<$DrL^i z&wRM^>|hc&4yK1;lk4z3uO{^7EWmRoS(2^#GLIh zCcHZ#*LmSHr~lG@WVPH#v&aJ%NQb2{yHv6Qz7-TDt{LUCIl2v4WH^Rcf?2HNb`YU4 zxrUa35C$S4isW4ppi_oXz$GMh8L|7P=UFDFDA83)c(-Agct^K`j}sYMoPgpAcmkzp z`~*qZP{oQsmqCe~t#+)^8ABxPQ;&8ioZ#RTYU7tp$-dK4H8t zm}qi}PrzjdJX_I)?&7r>(y34{S1Q$B)X%G;N+}}gaGQ-0f^!WX&Djy;6(cCN^*hXZr*iAS?ve?+nKBE|$jnaj2@iOn+n#NhOK>Vbj@d#!FtJE9 zQ#omb^XK2ip6Hv@tjR;){ajw}G9(jut=q z{p-{dW=CV@Ox$tmL7jOzx{I}U_{O>X5g`2WL30buLjUWarbU6b_&1sSZwjhXt%ca# Wk~~uM{mf~=-`-uWI}5jaMgJF(j!DY^ literal 0 HcmV?d00001 diff --git a/Example/myWeb3Wallet/myWeb3Wallet/ScreenShot/simulator_screenshot_C6881651-9D22-410A-BDC2-4CC3FFEF4FD8.png b/Example/myWeb3Wallet/myWeb3Wallet/ScreenShot/simulator_screenshot_C6881651-9D22-410A-BDC2-4CC3FFEF4FD8.png new file mode 100644 index 0000000000000000000000000000000000000000..91063b133a3d957bebb49d6a09af6be868e554f7 GIT binary patch literal 115663 zcmeFaXFwBc*EXsG8?0afR8SC92)&5(;zk6i0@6#6A|kzp&?2y<7m?nT76qjDj!5qy z9TIxz0RjX_`=ZaY-!1#~=Q%&VbMgb2a3_*Sgl4nc!!t@)ytDJa_8Usf$k) z9&4OBML~Y*)VWEjKZyT%K2O6<{Bzn_L;lZG1$~UG#21e(bf3OdQ8~py+@?BpI?(DA z@%^Vx6Mt?Je@>ku`*8Xc8S(GwAOHJs=I>Do@(*NxZ=aj|@y3b{@7hzRWKKPO{OGy+ z>5ZAQDaKl05j+_=m9Na7Z;IaDGS_iCtxltU*^ztHXgYT^?sYj&ImcuT-Y9RhVoUl< z$mk45(3y~`QzgMA_5rChROIj9(clq@a~3c#0w%7s)ia%lkxcJDY(N_INuoV@uEH(T zocr{tH=V!AKD{IJ=G5skV4*n-)-`Led5Oe_Z1o% z8+FTCt>28D@k{&NzDOS-%^1mGNdEFG`22v9|NGz~VKBqfHSZ*hzB%Rlqs;yqn zPlk*tpyoD0^h1AkOMYay5xE?f^Ia4ieRC?D=H! zb=x0S>#mkLnGdH~BpoxkhdeG~sJ$KWa+uKUN@$*QZK1xSeGNxrUq@rUn-Roq(zQN( zcm2s~CxdO`%P;kPRr^b}d2vv|cvzI3emU1njT5*A*SuuaVpG{FwhrZf*`w^)lad;d zP!3Ltf<$rrdd9CpWxRkG6@0-_`;yX-5NF(hw|%YSQc0Q1ey$4;uXixuZ{=S;x{AS< zspBt|Z`Lqm8SSF0Qc>tC@0WJ(FC`1{+9r{ysqj!QGsDw$rlWZb-9Y+jNK3I;D&sbs z$<%`|BP*3eb<;#LW0)l9`*~5hB1AWLsSp>4q`~KAMYp_>8hTjv;5k%HX;zZd}^Pd*6XmA{)R67Fwx`4JN zwqm9&y~iaZNq$%1N@_q4gODc6DJAm@QsB%Z!2BOw-_BA|siy3gRSzMNz!YQG;iJ_d zY<$vSTt@{4(Ti5FpTMd|zrTq+Y8}h2oc4GMym|0yvcVN^J#1MCla@4F_#*E-`OXXi zhTmE(7slN&N)x=&uA$mNc<1esC$Hx5%$3U)bm`X!?Lkq{H33Q2^Kv~NojE_u4JOxu zK9;dpA@iF-*vCdorU_d<^1$WP?uGxcZfGfB%&N3SiJnf0`*OSET$s8Wzdm=#O;*6& z2Jym?8+HtZqW*Rq;SA?7_&fc$mNc^_6z<3e+2=bzVxHMAVY=z5#6_YVjK`_Ns%%(N12M^1VH4WrvTiii91Of{df_2g~Q%rZ*C%W+BeW z?KiJsw{PiWRW6$>CdGk|n1X;?F3%@93FS(^5}c;z*Mg97OnNSI$Lg2DTq(EOFvg~; zwNU#yEf3Vo$hGd9jL7x$g1JyyKV}SN>%3U}r3SSQsdKOW0jm^(=npQe^VGYKlgOG1t`* z;k3p!!oW9)AUGVq?P7ELt9a5b5FF%S{>P|RMGs^~%oCA$yxj3APj&xSJT$4JFfIF@ zY+o&cgV$H?8NF5!JS{&3+giUR?3uS0C2__YosuZ5elKUbW_Hf1avo#h#S6P1sbFm# z48CKw;=+}G<=&ahoy@RC;=~>@sD*MGCPJ*Fm)C|Vvmb!qx>&7+COzlj+hBo#gbpEX zg&Oyx8Skr2ZqP@d^s7iS)n<@wu_bc(Yk%G@kjC_K#PtU8r01)L-NR91Y5N_(TOOQ| zF&k`4z^|C4PGvKn#)JVOpF6FO%jNFfm%=UBsoi$u+nSd6c06F+$6oI<-OU4@pTfQD zQ}IOPHyWTMpD@hx-m|a`a%-*glb)Fi%D6xI{dc@ zSb$pr(|M5w9~jT7HwwLF@WEVS>dK?S!Wmq=ydQ8Ul}CGWGe)-vl?-0lvr@8G(Ft=* z`mAcC;uVgZ4(y-I=RLo@Qn&pI`i+GZI^$^#Z>M_S@T$)(TA)=IDrpO*rLj>`E1dI| z!UVvxkchJ745xuVl5_g)N+B<vhjh*yo&I? zP>1}EMj10zUtyaH0}lk9XV^;ow-=(<=^J%JyM|G~zoZ&BeF1dTt31V~yWMnY@qN`0 zb@Z}4Oxix0Vl`&-Hl_oSE8K2~&f7yVns9OKjD0BN7P(uU$D=y46Et)Up(pAN`twqnZ5m_(w>TFB z0m&7UABEJ_c}&!KUA`9jMn5YW6vr9K)$nTA2rMuJU3z1z6%6EH>f}5}A6vCdje57F zo6%7Dcyv|?u{D5>PfT_?=WHLGJ(r%=A8FH?yStu}df126DazRG7yWS5${5B~*b?a(Sx=763L5H#iq4UKn3W8z{(LQ(^n-^dwOEqTxPz9-ZNc9J#!DQEx^mM46Q+@lMX5WPpzZUDg`wa@5Jos>#d*(J^9Nr(@N@vmKZQrQ^ zrht=aWW7emF)cg$XuhAJ|GaEJB_JLL#q34JTy-|tEe$Pvx}#GLa~gS| z%!;g+Pe1z)@+5eixt!qH8ji>&bjq3s`V2F8NT({-k6%6AqKL|FTM2@5H@mmhs)pV>#-vLB{5Am538WW6HOkkGi^wml-IlwULji27>? zz^^P4&|C5OaU=Et+r`#T)$B93XH;zk5?4HFX;NP80Nm=GcX@{r_R2na@lbw$$kkE6 zDfY0!`{g=rXxRSHwac;Q&QgX1+=RT-L#ZcQM>``)X%}p9y7~GRLt{s%qB+7=n@_nC zJ$`823STyPnPrELqp~wbH+fsNW5+&~IBk`Dd{ifLU?JKeoaAJVKd+@Ov%Qw$RPfIP zFw1;+dIq#)Q){_o1vNDvbMUR|!yo$4H-8*ke38X}?zMmU*o}Q|IV1i;Z)}~|*j3bo z{QDdC{rTl7d@!tbQp6!{3H#-I5-HXPP?bNGKoqr zU$8MdGSb;qtCX+QWH7qFmPSF&rsxr34Bem~eo?xdE&D{Y@~a(qDTfmz?)Ll&>g5IO zNY=`?twxr;Ey7WYv*4axq}(IZ_d`)}I*YSL>N0$NksnO3vYOfjy{B7X4+~NSsevLP z>+&;^-B$~JM2z?s1zZWOuRADge#!aYG_g}iHLT>m@b{hZtv>YGtB^S6eDZNbkLA1^^Sj&=hH zJ0F|6ZU*K->*`hIKc3wjNO`pz{N=V_!FjMt0aJ4up;PluoUC!r{6%m>!4d@r}cCUl5~k{A>w+bRK;f9#Y(fDY#tgKf?2s*B?tu*KAKlK zVCU0c=b+Touc8azjWZa;>Ia`9+?@A$?`uZVbf=D1v?Em!8`y8^ zlw@W;)!it=waWvcV}pId^m$b6t_#P55gAveGI5SfuCWQ}e13-Nqn(*;EVAl1Xs99` zg0HB~jR2x%K7Z$BmM!ubw$fbSbviImFS6FgD?Q2gnlgw(jQH^y_}JIDw7z$-!c#wN z!^!_)fZa$Y+$=?3A8rH++avbI8Q)+>-@gUl4#a4Zp9S)R+J|DpGmR_}M`X1SUzbYP zMt-aYuQ;1u&QAC0AlM>rhl3sgzS8J4c2PDrau0nKvB76vd+`JY+xTV*PqO@^bIyd_ zsWJgeFS$=_e@fIYf+riJ5zC>-pq5zO@PqFXjmBJ3mrpkt?AG~kp3}Y@aSEmlF78w? z6m>g@Tm1~qnpmcFZj(2_JC@E2MenA(?eBHIMI?o(2VaucL)_#s>s(}WP58Mk*HKBM zwGgS57@tBsH(bxjtcC+UxC6H9Tw%(-efo5>2P4#iTjvYAaZv{7Ei{1*iL`5A#&J>7 zbo)7+zUF+Xffx;k&o6Va_ik|dPxDe=j7X1)V^Gq5r7uoMV(OHZs2}@Wa}a*Sl)ZC~ z%7>7aJfuXImdr9fX(UEa2seKbvxTZ-`$u4V)AaZ(V|w7Uk5J@>#~jcH9&d9+lOJai z*fLxf@>WcHsi%k+?&^JvtfT2T0)HQqNz(=Au`0NG)+wl2E}Wh5Z2>qKgxhAkF)^!sxyw+o(oFj{e4Mjz{MtPqb%@I#?W$xYq1t{w z=c|A1Lp&be3hTE(l9CZK%@b1&@0lNyo8{E+;* zk{2~QMk{$B_&dB1q%kZjn%(-!VK5-8uhz=(xan4WHps5n(xWqFlj+9$$xYhkPT z8#`Nk)#`Spzl$r{<_EjXAmki&mW0#dVd-T4K-j^oi*B>m;pHqZPva$Bs|Fe6&-a*h z)ueBD8AUFX0ztPK6>Vx*3wJxBXeXP*vX8bM&2w z$xL{diJ2i=0aV$@w=qVU`k^cG)vi8|ti$dG17xX0Mkn7LGtoMB;WZ>nuU!{UMQ0aP zI&RnfsG!@a2$>AxRSs1WSYbJ&ebkI{^U(;Q5Ln}~XzmGb=QFGtE|^&FQK&3f^SbG7 z6n&xDSHBB>D}nwI7?xr?e0!n-bo=dY>Bg^ln~XEXJZ3h}UQF6svj2#f?9d5|t}dS+ zMmjy2M^uOw*>HNe?&nXKCk15T7e=0?xF*9b#@9^U?>4) zl@?mMX4eFb$o`X?G?AaLW1(JU5&NNG&K3`j{2hlp5&;_*2R2eYNO67uHVo)b#L_xy1TKCNs-`)n9cv%_q5od zZOZA5wMocGUs`cvpMfRrYc$fx=-s@I`{F=2T0)nR`HTJ?>sQ?Vm0Y@@(GL`Qrb2V# z9CUzc@yfZyDSV7-XJUN%)WMr;c`kroT`b}C8S#9b1_v`_{bN3dLWy`BKSQrt@$5p} zdY^LgvifWOo13Gt-NXBwNF^w5J-6J~PKEAQ1=2%ew}kO$c5dl^mY0z!y4`N2r(~X~ z6$?U`%y!Z?H*Gmf*YD%4q65H**IB~QKN4+$z@gJC^DSEcIHx9PWL z+!hGChnXUWBJbA?i>EXL87sJ;eeib(xhg)(KYR`&IEUoGL*HRnT8h)%H+hGTY9#=h z(K=r>PK3%>a^h0LR%_~J+bcOr$QNoylTlQk=@-G@D;XX!voFVEp7h}{3b#kJA5dts z`SWQ@MXYmbs+j=c5bN~^p&{R&h~hYsG^6fZ&zr%ch#A^p&H_C$uwt^(LD%uQlXhBs zQJ+TK9ru2Jvu>I&m)(-;bE9`wu(!3hqZ`U+K3dKA%{5am9`PF2 zZKDCkw7+V(%J+QBQP+!!*_()@WT6b>jW;u_ZKk@fl$Bg(GSlK4v9;g^B=q_u2-`=j;8coJd6V z_0X<+-SK-Cm+3Z3!+&K_Ds(~L0`2V~uf)V6>DGHLS9N$dZhi>?t<`d$+lUxwuP_O=IHrwGUDg*wS!BXoni?a))<1RcmW1{2S4~J1qU+fS8=<8z zg&i^3K-@j>DHN+q&Y(}O`dJCafE>LLk4$`(s-eArBAO-E3@aviqc?59`bU6}W8R)% zu#bM3e~(euGB825NVV5WdyL4zV_}1R>ych(#ztA`KM2;7^tA~%@UTu@JYNO|=6_>1-hl!1?_|zBO4Z4ovQvJ^ON1#oSl^7b| zI@7!6$<(az_Sf0h)G}#F8AOLuv=knC0`V~S1Mkpdy32ZXYrbVxY2s3JH-eE6b$RuP zyAVsvd<7-#X3~J|`l5;UU!^Q7v=jC_9Cbni6u08XukaALpJ%dgk*xZ<^$vu;-1tum zO|97vjBi4yu(<`_m;36&gk-nlw7SK#E_iS!U!BjTRT_q)$;lSJ)$YF5;H}@8b^#m5 znBn}6_LrCEI*AgPaB8K^t5cgP82aq7-YM|FejsLh9UG~t4xSG%xNs~t;;oGRbDbar zuNMjj7lgDgUR%w$!f8EI=A_5b9l|Bn{_uoz(E94W+NrO^iQ*Pv216kQkE2vE3*vLb zyVGxwNsX2sJw5YCl~gmfb)l~Y>q~BKlZ_I*_iv!uIdNy^1_5&qXfAEo?CV#)d1Eq@ zG5o0^;m!WwQT!^?xqxotXGOMmD~;oNE4({H)S*1}`%%Dz`h8%!PF9VGB_{S_wzoza zQwBTpVZEoFVzKFV8*ONg3y@R0;aICPgH5fg8x|jH33E_A9+VWOo{&r$Nvu_i7zylF zBxm~7!Pn@62uwa8Jl??>&+4T(BBBV+;K{g!?y)-F^Ln^BLN1DX?M{R$&g(~!&Z&{U{fb}CcaN;$}q z>x_ohmV1#Gfxk4=-?jKthwzrMuGZ!UZ(!YeO#{U14_mK8*$E+2^dnK(;!j?8#>T`S zy&iO|pX%d1`?Za*^X}Go-jd+|a06ct@?1Y($G241+W0Lja?^osz^lc$!xZzK&x{u~ zVoDwdZEZSwrHp+OsO21R?e{0^@0lwNfqs2GFZq2UXG`7TM{4hCtY+j-K~7HTdH9`m zJEU4XCnGkMrT0inI1MP0QUwiZi0pPQBa{mpJ-eN1O1)Cvt%MDqs0a8Z963PIqP zOCLha)-q=28j&>2)Q99dLZQRfOB@rN6edZWBiF)c8G; zcbSumgK63cp3xg=BQ8NnUdgWac!^dt;U-{{6~J$f*(PeOx5T{vJkUIWiK*l)t8*Ce zoz4U%p9l9MB2h^R4+iTymcL?C%QPeUhK*7m*pGcRPwC?yUKMI+PftO3dU>Rwi#30o zk{G6bl$V)Vw{f*BZwFX0F4)U?bPxOG-gyiix~lf>6i)zFiW6#`?uPu5%>zkCxU+K> zmkdN!LJZ+oc2Y%|P3>AL?HfFgziCGT#5bch`=`twO*WdZY>hd$%>)aljR~jEva(5F zmq)d_hXo6y*;2IxK(m4mVPaZezA}z{~#oNP!$Fqme6>Cy>Q9adp}@>gn2%Vn!9S%rlvk%rfIC(LiQnkMo8$Y*%3*R%TwNhZz5SeAD@lh8Lwq!w{QNNXTGN>Tdi7&29C0 zPsl_@X6i!yC~MKEEGA{(oARW`mMVAo*~bqJ$cwrZ$s1WTZPT&m#Y^VxjH@MD6`#S4 zoXo6V8hqccU>wIZ#bIK!#9w(TU-MMD^qspS`XJ(E@5f>1m-Equn2`@PHPYXJY%ERm zSF5FpJX~w|D#f=z>YdoPQDFB$9<|%*il8!ZA*Y&>4&vx)o+6f(6F(U8U}tLAm6el^ zPUS{Ho%EEP!}DJVw22pa2%R2R&Cuz4!BmHDo@L6gxeFS`p7Cor`(*;JiTYG(xjbl@ z+N2J$jdDf%ODG?HJ`#U9ti;7PQLkWmxAw7N@RwoVB>cw@xkk!Pwz;zfte&#VqMx8aQfgg_5sj2*2S+|hYwZ-*X#pxzxU-?iU^ zrOyP$JOOF9s6{U4w|MFla){eJpE5IU@3;3fu~YZN zH(#fH=l_p{`u#3VX3P_f3ZBm0q%}n3B8+W5!DtlD9{FkVt~Vl$fs*_BmF7&%3h@WG z(&fEX-j=x8A^rAWW?S#FmuQKy(|s&TC|OHNQ7DnH>}*xD2_2vHKPo2#9ZHlp;94c~ z`_O2U27fJY={%H+QQq+rTx)$=YN?djCkF^SUv|f~gx$iIV`J3kE^?|4nv_$Et8T&l zybV0{OQTAP^i!W|;0nR`$|FxGWRh4sywY{tk-<4sYlqRa$OWro%wjXuZ0ms@J1Lu? zZjrAH@?T^7rg&5c#fM2R=uH864uSg*mD78i+1h9@h{cX6dWDd^AcaZYXrxtUt%tXKJGv!(>0^mSsO~5zdwJ|yqHolL zYoSRTSJ{|l9p>|)y|Jds5M}oo0eK8-J!q-L43}reN7v}SI(_T7WHPO^^I`Or3t+__}mkw#_>ExG-H!gyDKd;mlRH{#M6PzNH z>xim1QT~ui0}zDV9@V;-Ux3AyQtB)x?wfYla+P294_fec6;moTWbqUXkZ=EPP+Z_t2NZ5h zPA)xVrvC*jIJ%B$FrZVgADvO|A0?Ko`+Zz>eoa9C>)z)mSf1tmDzyK71Or!yT3nn< z+0@-%w6gyOYMLKiA!NTS&)=bq)I>&VA|o}C{l+o=@9Ux>HIS0}XG!hDe+RbziJT-y z{vR#kmkm?VMed% zYKY=$7In4@VYhio9%VJGqA_We9FrlfQ=qt7!Prxee~A;iDci2fNla6$MpEqp{zpXo zvGMxqIJYGQ9%G;}>4A#U0?()b>X+dfHT!*0w~(Js`?4{<8)}Ee4AtBtyFqZ*Qeum2RZzG3}F?Cl~=U&x}zOdHITu??A3% zRxphQdF{-Xt32bcsL9Wlv%sl>871aGdk?P0Bvpd_1vYKKC+aY8D6Ry|=%}Gh#u#aJe zv()igOrCvmfL24lOm2RliPjO0DequX-emF|F;|=_a5X!zAHMs(W4Mt7RnNt&@=?WA z+J3LaOkq}imkJ@%`ZrD(hIW{}L(4 zslsZTUPP)|At;vOgSGx@Jb(aZyyTDgixDgSnn|^e`}_x&s3i6VnlKq4NOk$E_3bGZ zgVKDiZf`KWq@=#$YQiWn`y8(EoMAk-HQ2f znC~rJ2a_<)f!Z?;NIa$UL%41itTrZH$oi$?dcI}@{Pvk)T^SjNo1g*%)?d?IUv;W) z+d~~RT$~`psabU23fvRv4Zxv6T@f2_pYM-GFq^k%bj7Jl3pn`eDm7V90>@VV`{D*& zz{b6n7;TAXb<%5w^14~q+ecS<-Vw|{{@dwR2N=ymjtE^{{XWSWXck(_wD=(dH7;?n zY%;X6Rpvzv{nxs$MTc5EbEg;Hjer$)=#q0>hRz=g@|x|>V&V~}HWLBf^VXs(l_iH) z1})>4WB*D=eZzm86}L|w!q$1XTzG_UEY*Uy_Q#T_=+s<3VQadqzOn}e zQaF$#=TMu3Uub+*+3NjPL~lonI(kYnyOfs;X21TX$w4*%c)S;5jGB%yO|XZ4!_ePK z9?GmxTa86N{Y-44UV*Bm4~cejo<5@|W0&9lx03MR34I)(Z@#A$d!C1>1|2Di$1=+`jwH7}PPT`OcMywxcH33RGkQOl)H~SWc`9fU{`I z4bYot1jD|q+_xk5YDIqKVQc9!ai!$yapW&ZQJk>w-HQv8bo{=m6%;cS1qb&ap`qlE-Lr9k@}WJL zOQ#k<^3Y^raAe91--L6%zmyas2~u1QllaS1qRZUlZ7(W4X$X~;GE`x(XFxcbjA0SM zZ4P%MCI_Q?p+CwwltRcv$<)z8<(G|E4S!2jVW&3Z}-1Fo8fti+A8 zW|ycM@csa~0jI2cXVQzWpz_kA5$JAb%$KKN4D=X5&Xv0`A)mdM>lJnXsm zmOs$s!f9#L^zIR5WruFo{pCc)F^0lvdf}?QPaDM#XIG zW~3-QWBgp{sN(wjTPSGHzWxoQ8IhYWle6FUvn(l03 zS9K+iTzcUw0Ox96zvO8=e8qQA(8;9m6Jw42C8uRKkT!n=h1@(_z>W4lSqBSwv51&0 z18o<#OUtSmIuhcSxwtu_K2{_80Irs9ZK6OAdqwB-B}Tlx6Cdme=oq`I?EE(0O$Pgf zAxHyjc0K6Exc2_m8_8W)cr<4JB7j>@-!;qo;^hvtkbi|4eJ+|uF;uUf$7Z~l-C%qW zY?D9Nbs0kqdQ9N!iEIQf65Bs+nyH8PFVCvve-$^>10~dbuzkp+FPk63*!;0$Igg`V zk|+Di`MyZ!<)ybeQtldxP{_mVQmOc%WMhFE6BBYAeqFr!Vxiiq6(rq1GQFpHI6Z4` zMo>d+X9g#$8#;MVvOwwQD~AE~;6RJMa-PSPDsei7k|kFy3xKc+-N)I&>%1k*p?<#V z-7r!2!*cXKHHxRO9AdH2Z#f+G2bs95+y`_o@21!8qysT-2Y}u!U;dRPG>M#l{EWS1 zGq=kX+)xH{LVAM}UO#$hgmmnVL)+arKKjO3b+eOi?xW>_eelsK=_9ok>dmkte6Aug zq@!44*AfPkeq6OyH%=d_!st3MkU84v>V;qxeHTv_5S1z%CkIHwR#xAFW?kd_qn&SD zv;XO;EU-^6l#ni!yh2E%3q2$7uiPjyk@X=gI77ic}2Bx39JIkhWQ*j$~qJr)RTE@ zHkg|%L=N#TV&K9_-@EG@?mYTjE0|WRds)sPHPF^)Ngi+uRf7*JKkwvVweub?y4qLG zp554`=ZP@Z*YYG7x-r;2^HMhVtmmgZL%@gwa9A|Xd9NOcYHe>DjhCwT2(r;S7(asC zG(OOLyS%4Pu4)xZIeAlypo+3DQo^z}7mUi7%S+ zL4JACFAZZqIN};z(1rS3f%mb_3keCsJU&khBBZLYVN3*$Y#>m?9nzDG{^q4>?z|tj zS*f_X-JbPbe6JE+mC?`Xw5$XD#s>#A=7?2|i&kJ{a~z{n`2Y>9bXh|GfJ3HW- z4td%tDZSpY#Y)*on5CyAc0}7>xTR`+QHn>ZmF0or0tH9f`?g9WvVY2NKWI-=(s>&J z!vGVxXI3hOw?iFbxJw*eFXb8mixQq1qJ$|>?XHu%D?*GVH}tFu#Xo9JtpMc(*v#y| z)a$*h$FyUsnN3DMTZ8-b^E1QZb;w6qrb<42`^sUF{W@W1ZKTz*^>tVAijsQpTSFGk z^2!bLr}+y*B^SQIP~K_JiCFV=3FLUvu3daZTg<5<%saMq?K56iIgB`rif<`?&NuR0 z{Fr`u_KZ|i`rr2gxM3Y^GTX*Lmu@5kHAaM8eCY-Y$Ch&h3GM0!+!i(7cLQ40)peDS zElg^i_kTWv^1pYwnUz}kvyJ<%RU^Q-`tU5J3+IKp#+5E#G)zdF*tu71l=(_qEC-c@tb$yo2p$P|5#+Uj3sA(2PgY3s=Cc&JMoxD_LA&`qbX zy20yVWSR2yD*s<#iEej~Uce0=MzrQbLy?2tPgH-zTTsPOpfeiMm*1G!PdG#CO!}fd zDi0u1>)83tiie6ODfm$9?~<=CoZ!+l?DXv2VQVSH8@_$D9zZjZS6Y0#Nep>~Ap11= zg8Uwy&TUTdhEg0d4Je^3L|1g!6t5AYoBvbZ0Ng zfIr3?+$yLSdrLp=jxL={#9JMnM!O;Pl&4Jd(^Pk>=*-@VAjs zOdopo#01F@ufEgP$?v*3c3b5@zX$VB+7i)P_a=1rT%|>eMUDar6@C(dwM`s~MTgZm-bd$TQ^l=AP`my4zzT3)4#EhZJNa#bD&>sjsAkUIO`7AtC)wS!9h(nhX*O43jyBvym`sHXd+D6_6M z9WNlQ@(boL{G}`8Cf3KTwV_%5lGmgs!WTV*Yydq`bYz-Ys!8r9^IO*;&#GBp@sT!` z^=!|By~4PAYW3dHrKOoR!P!kTBfIIa?AOC1KzC@USr|30!-nM`eyn_bu5<*NO|#4ilm_1MBWz1nP2b_(iX338i?^ z821O}${EGc=I1kx=|Sq#6mR3liNt&qF$Iho5{%@M;wgCoPcBu61+em|`tLz|aMmaD z#4@AVzLanst$=QU(2b^&3wf&ba=tOSAIr7Q%et)PpQD0#SRy_NdE$=MG(%{^J(cuw z^pK9MIEnXMJyD}0-qT5ckk_u??8J!GYsXzchP(A}ot>3)Ga2D%>5ikW4=tJd>S(Td zPPq_lrwGN#gZZ{Y7&JVNYEjttMiYO@7Md!xkegFI%$I!-cmihc>zY)(nI+;YL)jKp zKu4SD`TFeFpPWV{9MsjwYjU+w^{(p3ktYOEKOf-niyg3B;>%Q4rkk=MCYple;^+tO z$7!-RcEez9kkOOQP_ZzHjEpBLq0)@6W3TbZ4-zMbuD6#oll6+ zCVmtF3<7og%Oe*j-9p!JoZ1KdtmB^FZE5wqh?!J3-CmIOxBV_U!5h6a;5{3veQnDv(G*ER4%H2`;yD3W-??a7 zz^n^jxZJPFI-AYCy{8mt>~7rG;jtklTM4R2@w8HuCU_%;XU94gYuD3aLIS{TLS_-o zB_9S(*HRbcVKlWq@Gt+x@bqZw2F{jKyyCT8L+(a%$#L$PFbhPOIYzuaWCvG;e1 zE+2mGx)i3LCvZLafw?=E?W%UNa$)22v$-*q$TuhqB;cSif>nx&evDV6Ep0uq$DSYs?Yu&f1 z5Cb@V8&s9cyDL|&GExDrPthI&t*C?VqB5|vQnz>!7 zp$nGr7xcot`LkTgEb5kN!e*C~VmkLis&PcUKs{KL9APi!(rBYBC(wHncFVYcF%mMN0 z=845ue%Hj?w@K|2W3=^&EN~0FRGO=EjO(ckNE@zQnv!0h5!gODOL?IV>4Oeqb0GpP z9xDxXnNjhtbcJv*(9L-F#B(lR+F-04%7J9fT zdTu>%spSqQUT|Qetn-TM5`UPdK#Ejb~N4WISLfcMledc8=#@~=`ftt3TAE@Esn^DDLC#PKzUU5 z6i`t`+>>=s2|PHcC`46r$U59b(WzGGm?y@?LM83C(=2a`9y+6;l+HPei3pJW4J^I~ z)rAO?!0-4+ZhD27%q9~vWMgqq#f7@IhSbVihZ{xO?flvx-A`C_mEE zTT$FLdgu=LauoH_iztf;GyWcw8E`X22)horr{`B()ZuBIJaoK%@%v6lN^I3qop1jP z($x3;+}4Y#u<9st$~K`;x<6OTEVvS15K&CHL)N@qW2?3io1bx~vR+=TLPtwxyGS0o zcZkCnFy^W1Tm%v}?=78f{B-9GRQk{YIfI5su>cnUftO(P&aZv8Qd=i{9nGs!(a>hZ z;dl1ac^8Cp#UGp$iSMh-Vk~o9<^{WS48p;f2ExuTb_+8cdXhZ99PE#pfKE2bSz-S#T$`3>}#KiG1SYPZ*W+r9| zXZ_r6oSa0KGxmh<9Rj&E_H4^YOdvJ1OoWo6U7zJTs-E#Wql%upL0bD}DqzM1)6rMs zs(wT>(ecFKp|S~2!4>rJm*LPt`cMb2wB*hzl$1zwbG;=4+2_l3Aqz!g)iWz zF`q%%Fc?l{JLKpPb{I7+%;{kuj72alg*9qI1hI~(tSk51cJ<{Ke5Rjp3PJ)}(EP4U5OXh=#3Y;7hnXnHJpYSehl zCCylo5BG^lXB#*T*uf=YTt|C$k2AudOAnuXV2@z33jP3p5&6_AuQwpg5p@gTz0@vS ziMH$1%DR5jyLBJHT~jN~urV*8{6JuWMRs?i&c5uPpE0jU#iU1Dm_)p3Lz{wMVCs7N zySaqnBCdDWPZ!yzOp1D}SZmhNA>ORUidNldag!HwIsV$M>0xlmj=GXh5osjfW<`!R zeYgwjVI2 z8Qjne$}Tg(&ti@i$25<>qABf@JJk5)=f#cnd|Gt@Xd!}jL!(VUf27K)KU;R0-6eLn zc&gkqED-EEQ(9Ab$s2yRPOa&I~ZyjkR`*nT_Bzh(lE)_z@;@kXu= z?q0StugYpfZCh#lcgc%C>IRS4YAF6?U@v`jY28%>JKMZ=-d{!7zV|N_jo!&kxmay# z(fKI4tUA~@`te+erp^a8pxYWODDH$LM)Z9%npgUKe0F!1b3)Va$KCf38ho03le@?* z(*WvtBCGnZ`v0AS*!Io|?K(kQ{-c;bFd$}Q6Sz#*-+b;hE%B1SSWS!H3?*?B>Fox7 zQ0(NH{rtXiVliyA>$AXbhI)Tc5jVoCTPI@r&+?A1KJnTL>!s&6elzs)hjLR3DT_FP zdq2-c<_oc|Rqm7<_M4$n;vSP{r1j-b76*QO?t?ZFvh+o@e!Wx6f4}&{1aXhOTTEY0 z)U^IH_$-e|0KcSg{AOsthPcO<=*ZC%((HeZ>XR06lC@Q1e>3!|g1E<0jQsj<)`qlf z|F#9vvi&bJA$i-sy_@81|3+RCNdCKnfSeTD{v9w$vF+bHheSz!tup_#7ZN2QQIenW zmXrYe8$U@2!2iNeQr`A!``r)ZAf?;?3qMKe_P@y~NhSGrO85V&N`fV9jPqY4KF8uK zAEAK1*gx|RDge{}!ZQ2QfwO3-$=^sg3KWcf04U$TlP+R>fSd9V~|6oM}ac^+UtKVo=%(Mm%L%J)uM#&^R4v z(gpa9a@SP(Mt0kiY4bOynnj$_7|rYdMiJtb5~Ky9VJ0mQ(J)9JL~I)*c@Py13F1gG z=x5j=#UNtDCXoaZN%%?JNF;$o5`Hpk5=kIN2NFpjkpvP+_`A?UA_*jtKq3i$3$i37 zfutn-R2oSnfkYBWB!NT{h+gp13`it_L=s3O;h!q)@0A1!1jE4J_X7CoIi%tp5jaTI zRT^ee`I{I>Nab&tH!`ID1S%R*0|_xYkQzvsWk?-9L|REA2_%y6GrJ&>1QJR3S*IkC z1fu9bA_*jt@KbvtkpvP+_^CaSlmudQAdv(TNg$Dgzb`W*kpvP+Ad!T>>y#uVfutmm zl!U+Ql%#S4soe0heSt(0NF;$o5=bP0=mkH`fJ72VB!NT{{%K|+l^ck#Kq3hwl0YH} zB$7ZP3IF9t{~=4Has#Q{Kq@zo$_@XMI*}R|f4BpwCxO(H@c&FtLL1EcjY?q*1=;Ou zkH{~-Go}u7TdC)ye0QIUN`Z2l?Ddp;|EHsA#t;il3W3IFU?X~Za+oRhr zOQUV=A9kXb($+oTGrcdPdr~{^f&~))&TfAqcT*Mdu@LR`K3u=M^_?nlOnm79|KG~U zFMhs2e0BvR`ncHT1R?kj6p9g_l(7*r{O#u#{6m?3d^(KyfDMP~_4c9P+=FlBIq|s= znyOcSbE`c*JL2Oc91EG0esd$h51Pa=RZ*4S-8qkRa{qgINGo^30e;#i$t?dSF@NWH zG|VKQI|*GstcHY^q)_k=qLSj=KWOncevpFrKhpW%_(5VQzYxd&x{oi3TmEl)Oaheu zp8$%&;+o6f_W~dxCn>l4H>>*p0?+g{a}yK#JDGn-FGA4M6zdGu5YvWnGoe75$8dtm zDm@`~C<>^w`pMp2O0w|>!R9!<-^XzW&h+UFRN|?krKGnaWE%s(*} z#jmc43^HZAR<3$>!VN6+j-Ckdhy9vsx?b1rCsH1QD7-<`fD`xvD_Jtywv?Cs~ z5QFDaL+KKCP#hTxngt_pnG!QhSoUlJ8Um5-5#Qw*qCpu}OjAa0mUwByQ@5@Gj1~<` z$;t^w>3U5ISLJi|qSJNE795O5mg0x(q?gBctGhiApj|0`9)}bGB)wV`nIKya zCX(vgb4(ZngJw)Q+CPZ%0XtA_tm#VlLHfbl8&&yt_v^->d*k#m4Wd;67rkvJmLe*O@wEzy@ghJ)OYsNUMTT)-w+bRtZylD0gZc!sT}G60T*mJJQu)=S z3t(T8SsX9{=;cOq@0sd#yj>8uK)=Gj)lEw(87}{3m4Z5zB4G`VLs@FpfTi9{-8CZg zYu0pXp@Q4b3LlMNtAIFdMV;DpY>}&!+%xRMF~!ws%Rb*G#@R4tH-MZBVi>5n+DeES z632r_ck>>=a$4NfeOP88Gn|XIs69aHQCaBvs|kU&W6#cHO^>m5Cz%Ih*_fxb`K9&_ z*)dyQ^)Wt$Ei*v!Hw&g6WO$xzhZO<2ZK2Wb`=^_!GSWEXyFZm?MuazxKf$lK1LVNi zXLh$7k!+ghxMLV`y(^g~Omjof9N@}lt2}v6z2vQ=6Boc2r&wrkocV<4mU*7-E zxBMizbKmE3oyT#U=XDuT8^wP&>GDj+VevCF4u!%#*iUIWbaovxKh)U7M30c4SV56s3rRk z*+MMKkh?c%B3luC-W}!CFD4`neIvtfyV)9^gtHuNWN_GGx4ZOem1~AW{CSo{Mb_ZR zmYjNxZijnAQi+crtxR5L(Nt3-Vin;#CMJm-YF^*~rWr-d_rVFYiyyUd{{EE{h}jwy z?XJO#k}n6J_MtbHFgl=n@;jYdQDa!Rzq}rIlLVzvJbm{TTuYK+pv|wh*N&@Atzw}VU zIB#ly)D})Z4SzgyDN|kaZS1l0?V)u{x=k!aGN7!tj3cbP5t5m-a9^gkld(9@M^L zw**RG7M|(Lk)Aq(tna_PVV7^QSe@-t4N*ylCut$No7B=VXcM|BjHSFDCMOwkyq!>F zmN_V2VGfG7H)b+VO+yxI5{uHp3tfkRh*+7V)$o&}>a^J;1`S-vbq4VgR-oB;v1Dr9 zo-jN%yK{s4S!gWj7-Oys=+})$>8hdRHCW1;9>B{$ zO&(m9n%JECvMJ8zZq~!+?uWXT`i_uZUv{S4>tkHt9*Z-f$E3>!d>yh|u0k>2p^qCF zo5r;6HSgNMhUq#FrjUQIf}l=($Tk!gn=Ytb@tp{z%(hpChZZFfDl~B+l-v+u0iYNomr95 zVb?M5E*p##G>`G~U)7UGw7Tnvm0cm8UCm@TZMC2(wAiwSq#f6}(Bs{BIYV>7=`D&o z!B8ip)O8lKDe5eiz44?5dfc4REi+FAT$_S;91*xd%j|xJ-N=Cgk+Ls%obd}-#vy^wypJCrHp`2be ztlwp8MmXY~I)=3*vx$E>ftm-tN#W&g+Phx=6ARaAIju=S93T=*qX z;T1CaZm{{hZa}jTHogiJ*K$MLR(boCpVxzDU_+bk^svI^yapA>a22g-#b0V< zEOPOgzBqJ?Y`bWDAwr4+qsY+gu~#IYX{#-}MihTl{VA>F>hQ=T{j6{rT&)wmrLok1RdE-EEQmS^L`w z=Gk+w3++FJWVfJaAJ2lWc(>K7YM2hfA}dn3>rK!Z1F6_w3KrJ|3U2)A82b!bYy^0G<%AP8^yddYnq|JeN7gW zLNZ1qdS@G~1ca^{cLuSu$R(Rspq=x4l$ZwYiyiv4cF^#e6ymR~ZQN6gSbC9D#awt^ z2GNU@L5(A5Aq51jJvw)kMIXc5{*V?Q8o?U)0)}074+-qX7VnDP$<6Q;j z-m4~=)HM+f5K;FmNuaf2)uUzyow9u+bRs&WMwT;7{I(bSC- zAyq$Crc;USGb_*BCubkyS*5PefNIMD5h9k5A)4BF2>#jcHRf5NZ)Q;M&Nb$jgZ%iJ zs{jtSie%e*(IvyzHDY12l2s7e=;>q-J-WLKxx1sayH)(~3n3r_Gh3QG+I3FgFlD`v z=9`{)NSix){dPl~$CST+g*1G<3)_<$>HssW6@P&Foh70)kbNq6Z=`RB|Cp5AwE33+B@N zg*81mSrhCM7q8}rw+OS+k21zk{lqoIp*W#2-$+7fYEVG-y(878dJhV<*kjBOS1%fP zXP8)|JRWQErXxEklN|{PCmM|gGTG;tcWl>X$M3gKv}>~zvZ{I@Wi==rpNO~jQo~wn zw#3Y#DcjUi)ywBA+txwq_&3CD;EvEGXe|l3oOqC2vf5g!BhJKIkGEdN&JV~ z<>%QZ(N_0P)t5ZHHC2tjF(4}EbH*v{-8r!1bU@LR=$#y)WWHaSVYEx#`(q_6BweJm z?&dfzR(MUsxj`C2Xz0K@2w0eb1fnE7@_DspN6@H~?tnu@6v{7BO8SjrxMe`k8p%R^ zAN+PN2pdDWq&q3Dg}N1tuaOh*6*z%fj#|u+ser7g7l-+CCG7Dk9bSFZj8a+WnDBZf>1L*qNH>=pKE-R!GYhx<873EnKvPyH1N?? z@V$2eiKvoVSeWUwngd*WJvc%dI}m@-CxTt^;b)}D7zkv0+br^tzwItE;#tD6_ZDxI z?-SD|-4^r!x`vQ~Y-s(gzqM#}U!qNRZ|y>yAC)G-ywIIL*9wUU^rHl_A%|KgKM8EUOnY!PMW4 zN#Pk2U}}-8KLxHaWz8{og=Tr9#88oEdjR+V&nJX-66d}Ye8HN>#jqW<#<*_^baOcK zMUl%PC^)Iz*ahVPs>+6p{IKO!U^=`U5?ktPgu7aFL!N3!pMDwUh;V{af_Vt1aVll4 za-|YX&I&5ftzH!!IOG-{kdy{@&cX!<)S)Omo=XtZ(?wuR(#667qaA z-_8pZ64P>=UBV`_*gP<#_iJaS6Pu{dPX1%!~=EaVp980-wvFqjfh!*px{aYrZgj~PKq?>CN`zGQcJ<%jO~ z8C!Vdp=eeWZUJWEn&0|eSS_FOA}uzI+`K4}NlxjHf@=m+s4*5%=&iPiHvL6T(p3c; zn)GByPP6o-2nOM4OLuWOU*^#GdVu!%1t$+vfWn=Rar#TT@7ixF~R@XUsHcuoi9gy(Zum!_vg$nP6`_gg5Q>@Uq$^o$Po4E!#MyxFnS z;iAsUQ$X_uEK^@t7ppH?{>n_dJa}PZNWnE0A=kX3!@MkO*3D6zm96XzWI|PAQ+zKu zh?i`g^6>IBw{D!A8W~*n$hAZ?FBw>{pt{qJ2L_B*I>S)UhYjG-kHk023&!chIGA(6 zV4QK!jIG$ZD&ti&_$U5cFXo`+`B`a&D=Lp;Ue&l`*LtVu_8#ga37E0;EBI|V!ADDO z*F$8pd(?$NW|!HM>A>);7Z|AaA!{|`Fu)<)$AS{SnNEy)^CEFLmpVD|xJ(EG5CqH? zsFbdgHLB#{i`PHEDaE(pVJXk7XBeDDu#P3D4^0=N@zyXjG}4ATW!*e9`YVvmTs>Ux zwh%(C^3^_p%EfEZkvoE zV88#!KIZeZYkrbHLo^BVU4Zu8M{vJOc6hT~omb7^Y}R-5;_FjMCS<03vtmYihhxZi zj02%G8FPw?=vy1XF8C9yU_LZ7+27J6Bx{V9ncz9qM+9*vgCiA~ z;6R!WmzGi|n>pa&T$F05Jw^P5`Q%HZ?dvTt$5Q*&NmFs+ov-v9^a6l+ zN=!Y2#zxABhzvnv-#KaYBQx%Bc?2Nf9@>F5-F{nNFfQ$4I%b||apgi~pz$2>b(Y{n zzjncWF}`UYOKxHubE!qjU*)T2oAj1c>UOraI4|9pWU0g#%$H|Hy?*=_KCHGZ!qAh^ z9RT=WZ2y^l&$CI6X77=nmS=Sk)wCu?eZgY(jhQWsB$+Ji7pCZnh;-lV@;FFPJ7lkh z>gz`AgA=B|8#Ro0peO^5}S25qll#fmyE3eD<4)2uBd4HxdI63*EC?ypE52$NuaAU++}3(w_tQa?_z^TIC&~ZET_4 zK7J7^C4^L%6?4U_bd6l6knU(N@oMn8sm2y$>bK*NRD8M0rjU#o-TbZpJMkxEWo^?QQ$+lg>X?dz&n|(6}Q~eK& zTNhPmx%23~HIvZJ&>vNYZ>Drvc{T+-OOW^NP7A}Z^WBCdheFszz8xt^htg(Wi@mtS zHP6#6cV~S~%F?%qPUO;wCs`q)tAni0h^fqtYGnR;JhERh^Cm`BdG7F~OpTM_TrnXM zV+{#kAB$Gf-Q+TjtQQs@(yEAhGOWAM$IUVZhrg{PDT3@1N*u--BJnYt>pqv$cOQjy zUCwZqF<`q&TLwi*+Gfnedu89tR^dBkmc7Njz%UoNJftzP<->)JJ|VC#2Xyfs*ya_o ziA7Y&+dJ>=e=6qcCqU-Ej4iFIxVb{m2dSmFni(c8sfTInNBn_Q@F(K3 zoI1+Es3IJD-+@MO<_y*(dY9ZD_yD%%X>`rqhvpu~9C?XacuW^S6fam;3{VW##Ww1N zzkT@>*L|sSFwS|;m6<)dkF*8|*4i3w_VK&p>OZhw*v^)CgIv_+f(ZuE2}zyOS~MZG zk(76-?zM?aT0u(vfXS-`J&dM-&B@SNoJY>nvDg*Hmy4zvnbL$KZz5)r1HQ1X)Sz!K zQcLjIpVmm!;ME^33xpu)%Pj>|i3RSm?R_a>U9-%H&o^a;IW0WXx&VY)p* zGn)Oc2g|rJaB8kwRA-)UiX-qWJV>GApt(oC;xe&-lh*4MZw{JfWsVd~c-IoqH2nbQ z%@XFNc*7#;9MAaLBeC$~ z$TQ2*hdgoCI+nATe$G|Z{va1rj|Yrqs=ebIJt=$dJ3-y8JEmtYoS0opp!9P(=MH!y z8%A9S6Mj1t9m=n6jXJ;QQFE^eRJm)(LYfO|(l9mOSxW620wixJj3t6y29$M0T~&M` zNsUw&vrK2FxLA)7%k{THB*TG5Ov(@LuB9eFi_*L=jB9(nn1xUt3AAHSU$5DK<`ftv zv;{;n!Jxr2%hoegm}cVH$k$ToD!HS(o_qRgcb&TfDbB5z@R3At;&|@a6U_)Qa-EZA zaY;)pY`3IL!7Ep4R__I~QqosA3MGL}~}=w6_@+%U007 z_A>m~4;F-oA{AVo_!V+wIBaUV*sKJU_w(0tiWk@sSX~b&HaO(yad~&5k#lXXXa2pI zVT7emBC3;AKBuXQBTVH7qU^U`r-szNFOxiLaR@pF;nVQXfbxACmg+fXHkOES1DK}u zy?V@-gzheNBj>@8jWCqPyjP#>+>u%Ck&tT(lZK^eRkdAuemjm}iVEt#e@^SLh`Q4Z zB*)Y!9DZlux<}VYUM#OX!Dc8LhU^Z4-2__YOuI|ARfKm=edSD~B`9r8H&f&E7XVKN z%tk%UfVwMCyp_Pdz9dzynJXYG)oMM-aq$e2g=UJf+Z1*`Ix_#TCRt%p2v8FLnc5dG#d_$V%sb=M6dF)4_SrSvJ0)dN5>EZgt)T= zG`-8Xhr09Wty^_+1AJ>Upx1*2Qr3qiA`-ZKxIUf#M8vPS5JlFbc@WRjWZh;ql(@G-F-Gj#zkl*Ze*(Y;_m8X4M9*DvS~ZQX#LZ1G(C zX=TB5Kr)nBb70m68lAD5zrrVLF}&?eKN4eVq~2d9XAEGuO;WTohnB;0Eo&0c=Q7O% zBK=*=;E%b8-L-RCo@{Zqiw-SUA5^5=VfB7-3~1sX)n@fE;|L6sqGbSRHLKo1yq9V0 zrsQ)dt}h?7ikPyvfc(hx$Gc>jD$EM=YOa z4TTu-`QFo!rSIs5DO&%4a@~o;FZ6eFC1S?(lpE!Qb@>HBd-K z|J%i!^C5oP^fadx$zXO$-_Si(yvlRO7c-sZial<1i@EuleF{KI2zxv*gKmknp~`@h zotN^87i=rwOe;bed(ygjl2#Q86nDC2E*wcOIq;aYPdsdR>4P8j1KwUBLkzs44-4wK ziOmlCCrZ-%awx{~*cqD=_nWIT4SfpBwxb!?C@etY^NL3%ZzZsne0OFe z2vzbNx);QBS8r{3y(O_0RXIWUZj7(q_)_U*j|wegT?Y55JGdIimTf@wx^cSMgO(s0 z^!b_<|8+N1NqBxnKae5T8-^u0&jrkfOYb_j+Va*K;NW%@mZe^AvGU6)(1j!vf2Q!D zjfv|71L7k!;veXYwHaC_*3~9Ccr-%5Y?|9ddsQfeHNp;Mv9*Nr39pjeeEdfiZEMEv zi5$Ty!k?W{y2=ZV!`OVP=&Tv!zMv~lNZdu$SD)S&`w7RZ5meD-80)+`t$|@p7$#{B zG8(R4x@NJk=UjDgX$M%F?2Zh3BY}ZB`lZ3=ljL$!grqxYdUvNxBZ?062@IAjM9mM? z;KI{PDp)JS(k1xi=8nEnXyBB1<-L5$tS5$YtoLmM>{wa7WCIb(?APHT;XLK&|BJ z(m7-ziNeU@F6`#j9>@4�_Yy#z*fJ?IM1^~1T=a-rxGJh?5!)Q@OiNnY}JO`zvpdNS`Q&BepW zN#oq~5lh#?nk@1eAht|z_3TEFg|-eW0OTl6O_6pMN0`Fmp%_up%c_)KBN9ZaA6blP zVht0>n$&j8y`Mp515dBvhHS|*@)01d^HB?q{t~oCaSf)uPhEDB!JX`R{R=){lYD^h ze2E8gTz!iN7`}nKqL@(l`V--P)k zBh|e5k*3TjPSEs@^)Za&*2oe>CH^_E)Hnq5QRIgNDxRefzkcaGZwX03IfEbT&w2lAUtmJyUi)a-McK*8+gX)!AAPV1=!33Vm%2~Q3LW(5 zD|=uIzZVl&hngL&Vt%|NDRiW@is!2L(x!=v^06fZiPXnaU{ASOX$QxT`j0aK4q+cH zd-6sCw5^+Sx!;-q&1*``E8iuT%}z?`=j0@jg$LC!>fQ_W-`n@?HWF5eO6mTBD5}lQ zx=|9i%UKk$q7o~Ybqre8$YoA82CInRx?)ACy-1`n6*ZAcG z14h6Ygh(R8HkKYu8B+JcL%&R&>xae8a@?st>EGkt&@W0|Apa^YNv|_mbYolc&e_hNaF8c{De6yRN#s%upLiM^|?gTQ~?EmP;V0l|r@hDXv3^rs3H1 zt|(7CjykzX>Kz&Y7W)AcJ~>WD@*K{JOlww5eKlC=He^Rap?Ml@n&%h4D33495Op?U zG@@7fRrw{XOsK8Yme^BS0~)1-F`)HkLfRe@o)l_oT4*CBcW`_l$b@VdYqly{Wh(s}N-{Um?7B6uvthy6T7lGS6sb^S3_KT&XvWq8Wn^xVnRgb$ zc}aaV!&mrs>^CZBrgaA>A|hPk%lO1Z?{vkS5X?sPHLuApDasSPPSA{&6yNP-6{`%> ztL`_%9I^(=^BuF=eepu1A#qPbSO{;z0P5s$2-D}>SeiW9SNHBlNNQuDD@#kw zS-rn~&C1~j+4Mq^x*f#QZpDJD_NnVbq5drR_T~M%c^vcSUmV4){N)eHazlG#Q02a( zPA{qw5dAeTj<`ubvhb7jzSs`-$;z*nu?c6n)p8xB+jr{{gC{NGOPB-UUddKor$jEj zUp6N&qoJ;b(6<&aaIcc9K87Ig4(U|EuosaQjVsL_e82Tl=+uU! zFw=JWb1_O?WZCHTsYc;4V#jNukypxuyA}r^%--ppXt^a0X*GZxMs{3%ctO(t*ky9) zosEkD-p}Xt5Aq4-XpWaKm@|7G69W)_q@#q z#Y1did8%t|xpf+}dyogsx*%~EDdit-w5A}-Jc7`JQlO9Njj3?Yeq!Dz5orTe%rY9Mls?-a=6tjKuWUC5I}yfCR| zCR}xH0=pUw@ZHLxMA}KGDwJQ*|;R5A^_P@FhHt6FH(oNT9Gu!301=sNp~^4vE~ zJ2A8DL8x7coiC@ z=c`JMbYW^oLcv8Bwm;l=GS*;AuQ%}BjC$;SM#Ehph#>g4Nry{mkBVsv9nZGjOg&n3 zNG}u2X->M;MWfU(Escc>RCM3>he<9W26iqR^r=$BV7w8UO)ET~;uh5LMJB-1j*O9= z=JL8W`LG!^)F8NV;893&T2)q`y5zy(8z7Bh@s|}HV%3{g-IXie>l9{^uR@Z9prw~F zT$`u3r_&F?Z-cuDYE8pk@bw+}2!eVnB_xCADYKHc!EmxS#=OUP%#hUk^XCn5vl-M! zrs!@eme$jMffnZ!1SP z%^9?{gZc#lWfe@NwCH$Q=D^Y73>#Xi);`>vvbwIXWxq;6RWAw65Obal5T=>l_YG-o zeMc-IG-#B9uW8p8)iz(*@k`@r`?P11KsD$5L3-_dQ8>kDXxx`Omea359s&O7e>jKO zt+!6zfH&4@_Nl?x<*s*5AT`yTrG4Q%p}d=X!+V}bji%t6Wy$Gt8v3NN25oZWiWk8u z)3&qj8;G@BeVfk+QX?mLiM#S;KYyBl!mjU5ntD~&WrDa{ucCV)?qx^bG`gV^3cZdT zV-${@s1|%1m7$8#QB(_C_fU)P;!K0J;>6Mt^2h&8neu{FfK#bl=FPSMUAJK zhQza8+Jl}{L{l~^=L+6-nFVN$ayFT1ybip}P};Nd8e`kiXyoJRJ4H)rrgBCKSl}q} zGY8=!KQaK{UD2+Y9(&MU&6r#Y-QD4DDja*&_>+5gp$IvF0um3woq})PcTg~ffKt0I zLr%mZ$`p-pZ17?R!V|3A#LF8s=28hh4jKi2;~Yq>z8=q)m@-&=0Iv_0g1eRRdWmJ6 z;i{29UL!a^=(1{=8;`c8WT%_BPE%MwA;qvVl#daPgWNCdINHmuUNxeM&QvW_Yg-Y5 z8gvdi6H*Wf78%8B=uYzIFx*}H5E;RyS3c z32t}S+PV#BX728N%d@NP4g6XweYM25&+l1^k6+!Q<%;dnxf-;UWG0&$wt8mH(b9P% z8{kY;uHjcGwy*52nG-T-G^sICSFn&+Vk7VE|*Ool>U z5!1Nttk0rIP1Wd{6_U40uwM@&Dw39bEmlSsYK+3aoZ(&$YoZ`(PbOBy@|?yO1b>Y2 z@0*O}zJG9}fctHX4w~cB`594Q;&4Ab-?__Up`~OUH(1HbD1ah4cPe$QdZAL5;~7S% z>r?vBNR=teGI{&~&KFUp)gV3@ECJ(rEhr!5mCef{+z%PMVEz4c8RWZ|dFH zFJAZE#2EqvM=A#qmJWShn?WGsq2)VLBiYe@Knc8%Jq$#^60vgGi{+^P^Lq<098S0o zZz?rJqGq{jK}%C1wE&EaeM`==aA}DS>?XPOvzgn z5-Lwc%oBC}?uOmwjpPC(NaM4VO#PWtX9tc%=@@v|StA(+H@|%i87D_v@QHvh9X%|W zPClB{c;r}tMue1!oiS&(8g}zn^v^{Z#LhO7hHJq591Q0$?{t<=Zp;KOje~qiUdANe zx>s{%QRI^3mDM@bT@}lgK3ne3!%SQ0$3WK>+F%o#6~`|m?ymK6K<(dmHDrf0u=S2+ z7|BpLHc08LX;(!6lL;^&TkplK=P;%*m54N+-nOQi8Ym-m}R-OIOmD_%V~u=bEZ4svbM5g3>S8CnCZKyYpi zaYX{=gr(WJhv8%9agx__w=@Z(j^T~=>v17ia=FVV{%cbU;Q-YG-)ca~gJx^XnC?Mm zf6T*?PM1IdUfZxw_rjO!ihX8Mn+u!AiKAa*rxm20keCX_y^e_`eifmsi_`Rq0gIv( zg^&UNFYh&d_6THM?!7m#!D6Ujr`Y210AA5bVUAQ76KVyaL5M!fSFx{o*dI4$%2tQ( zt~GINsWofnWU;3sS5fug1y`7(IGS*Zq-|+r2E0?Xcb4jc8BfsjbkR?N4f>Z}lv}L4 zr#W&1#JXzaclo{iA$t$3a;oXLkzk6KBNy=%)WcMO>!NOY&Tm#;lv3W(1g1W^1a+U`)0cYJ8zYzM z7h?|bmd;+cvSP~tG zFsIu0l7Zyc9LcOcXo_xX*F8@=<``8!wwyO!(~1bo=(msh^tC0(Ga$?cf)6ItdNqzP z&W#OLdTm-)=nt!xqhr>vCuvQNe)aBo83+7NL?>Xn)&dlTE!~IS>AHN=H1-hw_Z~wF0N9CcfNLySFT?= zC7a&xVC6CW_r=!oa8D+)@UKym{6A3> zY+fPYC+E_I(?Uk#wP9H!kB@B8N>XyU@%dAmBsBRoZ$kkoz=>-mlLx;&%R^xjO=v)E z%CwpyRnyqBu!+{}>otd34(O~?DP3mte&t0=ubYM*P}qpMv-%qt%IvX)2R1-ccH56N z-Z%1-?M3OP4SJwcET-bc#0;F^FNFMh9iPtJmNeA%WA0W+jGl@dj6gA4J`REGT^j4P zqU($c0`ZZbt;~=p8<(^^3oq}WBb@4{H3`7maFfO3F%StpQ-LWk5skJ9G1> z;Kk=VJbEsgp09`|*rQ1WzYPw#@*uR3TBp zMgy(kI?bFjfadQBv{O)u8NuJ;=WZ#!lLH_dr;JOtxtCg3wngu3Jtmm?k9io;ncHd#>lc45pOTec{VXX7U5=GXqbWbH~w|Qh8J$}5@t;< z#7JmNOXYJd5oFOaQ}WsNo_%Q@i2%v@&9uGnoM731FMFBRO; zJ>vZ6ip~Sx#x4WhrrU?vwdu{^W^TV}mLq?f#W0_9KEI8c<*=J?_6h9>DlM#)C7HaW8risA60F0Ls+$-expGVcWN=?6kQBL;$aYJhbSzXaa`I(PJgU% zYUzWc)3vQYJjvjtB0bsMbjIhm?r%1OV+|kfs000)B-k_aS)taVUOz-FRH3VD6ddf2 z2?_y7!I?|%TqKBgO=#c3wW!t_`1&|%j^hX1@(hkSBFLyGC9E-rzK)F7jLowET@Xjn zcZnw!$7_4vh~j7I7Xl%clWIR8OP3>oonP!!8opdT^|6UJcpK_^<@+yO z&CIhaop+?fG3=&`Pn(ucI&eN7d*qw?`1XMCEr7v+O#YKD^bgdSkNiiqXRI3(Ya^BI zylf<;Pbqd^j$v6BypEFV)@_a+9lKQ&T~`?CviW`D`VG&pJ9gp+uXNSG!YuQK z<4=Cw-47t-isC}Xqh$H^&3HKvM@RDpQ=Jb(%7Ncb0NTqynO{wx<_w2O9P8HjR^{1) zNm@QNHxvRH8dKA_f`2xtZs1b#Kf5Z{LLWBIU3~ZWf&nbTwjlsGfwD0gL;cGBDFRUW zvp9uykGHoFzw`~6Ak8{^AMYYQb5-^Ud+wHjQ&2p{J-%dTe}ujfZ^Up@y-IH2*Rzif zz#rbK?Tgzndxr8_>XTn0lVAfQp4H(R0Ziw!q@!u8EA)DMV{GUSW5;--v!)7J0EeSb zZEGJoNJD7zKD!_J-5hH&KsAW#_tZE%dpwQkB2|wW&MsFi2lK=ap4`xE=64Qp{P3nH zFx1=F@1a;U7+`wi^aIX3sUKMg7Q={2%3B+I@@7j|pCTq@>0^esK|F~)Kh>eY0PTuP zYLw?rTI@LpVx`%8muOVte{AHk?LKDq2oo$IgM{B(w)0&T*;&ojsRJ+3zpkFe-sV2!GW)SJc^Jh+@u7*cO>*FbOh7Mu5GgnHxaN>AXC;R)4QeR!w9ve@oA;2 zwq{kZ=R)fxte&!{A=`c>CgUHs=7vUBy}$R;*0=2R~|sXUZAvyzXlCg4OoQO|Gvjd z*=uC{kFx-H`@M>I`@Je4R_XaB1shXSbk}hnZY$}sS%Q+;n|6IN?Lei*ck$3{zp4QH zMO0#(8*hqMWsZQQAEqv#&DDHWqk66^};3Q$1?f$Cf-OD4p{^I_%5g`)&IM^ zWav>o<0IdpJFZQMPNfl_u+s#uFANH2(xgITYI+I3jBGmB@;^V;V-|Hg__Ot*Y$eO& zMMQ;kufzGPy0*d^>`idPNa(6Volv~2mmaHqQB`y~A_^h(Nnz>8B zu|Lnbc|H%b=?I>#Lj}$rqNwydyMm<+xWZ6aUO=^-wmCGk%L!s zDi?z(Zp^8m9OvFkKG81fPdn8Ebdcb9zEP(cA0|CdtYDqgz!Sq3g=n6&$0MWAH;*Il zVfQB1t8y%aUr!H;QWKAj^9CBo*d!uRE=388uG2 z%1jtVk$noJIb1_;UHtJbzK;P=Ehvdt+OR1FSpnKe37;P z1@|dYQ2;?ipf{k&Pr&T#cuyGTV2x={o+pLE!OPW)NMp^-gZ*|5BggFKu!tj5uYbU6Q!ye7Y*d6!eMW(M?mC;po0=*t>=0{_t}0V9z^gU<^~JoHdEx;_*GZSXWK8>0|SxX$5jtl>cX7I&e*G9bKfu zK%daN<*>7L=fmFL{y4tq&jXEGUhnZw-W&JNH+IAn@$>VWx|wuK|I1N7awks~iv07? zy~D3xK79D)i4CIk=s%BrIege^-#-t?;lFW>cYfrrvW_-C{quVK{4%@$Je=#lU;gFn z$&(syQ{_wk<-I+7QvZ3sJ9iyBdiZem=dLvCzn{y&d-7e6y8i9?fBK2{{P*0tW&Y)Q zJ1@KaX~X}1x#h{8J$s~UtKCxn`=|fDc=+&*@*n5I{KYo6e&zlAF^7q2qkmpcPw(c5 zzkKwM4_r9KJ6+|cvitVu{&_u~TMquyjN5M6cFT6QY-h{gR)+0G>|g4~c5T_NE!!pk zAFyK^iT%SQyz`W|k=Qms-sUZT=SSPT<-e@&&lfSJZ?pXWYB+zq*cM;@u*6@; z$hIc7t%+?*mH!ZIwiV=mnB=71wt~DZ?Ek;*w`@k!SN4vN)|3ivBnSBGG#op6RR6=y zUq2X_oH}t>aj%j~{)qC>qgM{aW$8A{LHR>R;LGc3qg6wF!>h_NuHuFTu7yFzt4><$ z$vt{^`qiGydq)+1x-QT_`gT^Dw1J+u-v?xu*3n(qrOkw(wJpfStY!uaU5BPHb@~Oq z_J^GMdywz>iGR=I%rdKgYu#MF`1eoqM9!1f^iGNl--rKO6N*3c?{wuyU*+jqxbpWIx74}5A*L+bu9Wz(f&hS-Sf!(k5twgI)-We`}=e>HU+6{MP_6CwIo&x>=L@Z@s6J_x`O} zx9y6*qqS{U{KX>MS@Fjr@P|=$Z7)!N3a8r()StHaPife$6@RhFcG><5UiiIS^KX~! zKcUn%g8I`I{{eG{x54b6sCFC7{%MQwzgwPHIf zwzJ}QLcU!q{+HJZ*CP#2|2PZa|BCtTk%PaeFF%4{TaWsSTDfOikNQJs_@6M@)}#KK zFWYtFe|g>5t`$3Cw#U={S`l~wzunRMYZq%9LH)HNY$K?@P0ws2sBHwb%`5&gU-vtt z*v^XWtk}+q?X38{SZ*VzZ3OjWIo#$I+q`0%ZT~d}wzJ~zP1@~Rv0W>+vtm0den98{ z&uT?Wr?JU{)xFk=(S9Q%wl>Y*nAYhar=Zp_W5_3g#J?~5dM9t(BJ8#f!8-?0K{k-} zWb0^uqR&@CP(^8Yud21}vU6iwfZpF&<&TTz?~f$Xiy4sj zi#k%}jqs;Wj1h9SC+ka`TQ{GPi}B;=Ju${=G6J#xxPe;=F_H)I8@a_uWQBh0TsS${ zr%5~J%TtmqghVI~rxK?6!XavZ(}sVzCFkdjc0y_6*Rhh7=4cPbB{$#h)tj#*_iM!-lqw_swl?za1uQ&&!mj_rK1J8vtz4C_+#N>_{NvYm#O#U5 zeM-A=|BJHP;ii?;++VaSnZYK1`_02AE8BM2E|)E4jJLQsoebr9vZBHL*22GhQ18}5 zz5b8kYHIgR2=k*i+xrB>hXYan+;cB-{&WA)rHS!3KdwhheQbnq{KpgQ-1T_xK6lrd zU9IUan!|`+(r`NecmTcXmX`bXdDoa|@07Q_^l$Ia{-5^VE3T>Riys{+3W5R_5J5m0 zM5Q?(y;>OsMMr4{2#Aou&^rW(K}8e=8%>&Bqy-5OS`s=)fY_)Z2|ctBdLSXmJp`xy z^!`8h>E8RGPll81z4qE`eOKN43>CfiL-eBv7T)E(-yh9?B&fbC`Tl(ofyXih!9St_ zxCP)wKP~AyA-P^Hv;omC6vX=VfAtK?r;L9j$@GO=H*Rs$iuy53nQ!@qP=a7!8ZKvif0p0Li~>hpl2 zo{utAUW4dc!m<&?6YpU;OK2p&*dMY#)gw% z9W_nLxOq1UD2QzRxGU`M>rnc40W0|JS0|qBe=VsuvyvmmPRmK)T8ix3>K&17Rr1R~ z4bcYcy>d(PyaPG9M%UJnXyVH7kik(Tm6NKAeXo_=b!3Ah1!{9;o7n79nOr$$+z0u9 zo}f4p0WnkS#fS19EPbOeFx#j1nDYfbj(*XB(^<#Y41tBJg1E!rsNRt^#IjTN{bE&u zpCR|QZ}fcLZERo||;C4ZuO1^Y~w6dyu z2x)RcCgEKXS=!J^eg?YaVr?}CdouHm-lSe0UVMh|@SaKT+6xi}fU96;Hk>yBu>71T zLQf8*M7C!BU;T_C%kTsQN*XsNSrZJ%BE;LG$|h`JeCO7%uQ>Qn}{W*>`=qEH~5YGr#;n}HfCj`sXX|aiY zluwdRAnA|(JZXrK`VsN;xgE3d{=u;G4{rUX6VB=zAVTd8Zmw&4(5;UMem4W-UZ~8Q zzH@e}$XI*Hf)n16NO20PNk&@;X?W2M&o7R>&7EelbBIx|C$I_Lg8`n$u2(zoX%WP$ zUVvLy8R{ky=tH>w20-K?<+{Ni&YDX!X zIp^}R5j%}{q!-KffrI)Hr=g?pHtFd3w6IOzY`t^Lbu9r%zun0-S-l}3$F}TvOVNT+ zl}or*z>7FaCi3(%4_D-}yU4a2yN+8L$cdwkMtJ_LY(W1OLel3~a~^jYTQ5AcvL^W- z@1XkRgfF)zTBKMRBT4glq!8K^#+nf6*g^J5<=S=1HDD90Nh=_0MzQn4dxA9$hn~1| zJLepfrO)oMhGkw1nzb#BbnH@p%lW+29vrr~FPX&&94VS&(>x2Craf3bO*0FA#q>?Y ziAj7*X9}mdOJ?R{B-R(EXNvK>!{^IyT4{@QS z@?5?Fz2!bSt)yX$+-gvIvS4z4_4hRTX$xF}b5_HUqr0(NXy)y^QwvpcKBPNz${k$V z_VFymJ6g}&d4eMWph)~-qVO8)T9sz*fIXiRHrBMqk-tV4*b)}sgZq|G!WnU<-pt!z zRY_-t7iMeSXVxJ))>}UrCIxtX$ zZzi|G^5S~26!Vz^O4_OihD*f_j|F9g`E za!UQR@C#fQ&mlZKeacCZ=eLPSiVLal`r0J1CXsvsOlcn(wXUk5muii9IJRz16pNUf z84()5q7QUtak_GB*-bg5G@-`ulsPQip@U$T9x^^Kz``O0@0j*ZSBBQLuy;~d?s2Xs zQT{}<)ijNUbq#y5AdAQ}c)`RZJdEk~_Av#Mj*Opb`~6`QfI}mng!hKybjPSBM^^S& z8R_YZ_rWQ{G%L7`;ZOi!IA}De2w#MG$_znyM*149;fT0$p-RCOL7oad5|Q<`67Wub z-hP?+_$C29n+MQcxoDe1USYP~M$F5ND8oIJ9uUv$DhmdSQLuCRZ2!@)BxN}}OW-eA zS&{IL`&|VN?o~^R+iBEK80qn#CGt2742v0?uwijL7vH+#D3s`Fxy=ROH;$S{lZbtz zL72fgcIIjbDuU#Df=AGP;NB}}nLhx!g$sOQrT8N(;~94~7%r@{_qR!=(tSD?QA(Hm z)4R$4iUL>Jg%{!e2~;aE?|s4G;+P1+<=0)B8)@Qv4e<-WwLrY<_F<7#8rV zW!$t47SoSSILFO1;b*LV`ZUR+@o$abjCI+-)2JLoE?u8YS7rhd&yEX+GbwE^WFxn( z8c7a8vliM6hKe>F!I9*qX7i0>NrT&C z36UyCbP205UnIOUZGk1MKGc&nnGmqZ*#2BM zx2Yn7l4W9nB(&eG4v$pm&MGrj>jN1#E(U1QIEYAAe)`@N17t4tC5}}oP1?X(^OiR7 zS&0Y1G!1bUXKMaUMqhkB0WuVpj3e`4o#@ zRrpdjJ0G6i9H})eU&fqX1iXSuxHBcHb9;=fDH1NPjf5uD5LEc^Ga)ETuIz78Ynx~0 z{GfV2$1CLH!ydIYhFsm;YLJ#6m(H0A-bb7sDH%tMXq!4L-bG)c8H|h#8Rh50+H-BN z%%@Pw|GVLL`$7_`|m50Wxq4qBbX~1Qa*0bS3_%8@$xpd4I zxfg1ap9z~IIFnSXcxo zinro;C%xVtzwR)8{UEv~E7z<45H?z@pQ`J@Ol$V_fara_QNjJmQQRvG^aZn!4_&Qj z+*>+TcStRS&1o^-0P)oH>v*ngI~~w1f5pFlo+cNSkQZURxcolNG?4WknIGwPc^MU) z=C-_YV!Z8~ecR@6mRlYBsGJz(lbkO~eTIH?aGrCjBa5BzG9i!_De%_#(p5qOt+iKe zHP>^nN-p1US{JT6G(}70IhA?ayK8YL^H~Bo-X)EQlbh4Sm!_=J7OP`>=zZi8HZ}wj z^d#Y&avxL~k-t%ET{DkKez|=-2aXq7BrwoK3n+9zG;S}GcdU(<#g#9r|TYQS4 z0vgs-5uIY`M`TaLELA@^sh)sFv2-p2!A*`BXHs$_2YJ7=ua~KO4lo7wFqHOeLltyX zIywY7<@%Y;uQ7$_x0Qv7vdK5t9(`0?@wHy*Xc^=4ui!ah#+|`mRXE^WaGy4f}m3^id(~t0J3|{8EE7Q2DZS_uBIOi0M3rY#F?>H-`wvOgMJgo~_ss zx@4$}3#RcO(BT$jko=`#C=_4Qv{z?OctR;4SDG}@ngFNs9a+o@E;*5A!$q0ez1kH0 zMP1Q!a;`&78Lo?b?05<@L3e*r#a`d4JA5<)(e+%O-9E%c9U%c0H`@U&U*x8@`lTH- zb-{B-yIQc1N|p{Z3ypg@!ClRuZQ)11d_!AqwLeFEkK?2&F6mpTu{X%EYqTFHX*g*b z4G7msajan>d_MNplsg=-;10nZ4MxIOHat8n?pOU=%?9e;-;SZ($GT4&knWtG3dFsl zScGhQ92jF|a9UZztM#Mw+13CX*$XcQ#djVxGuxPW;q|V~;tx`DoVW(*wv5b5hCYO1 zz?eeOSJX|DVFWUiUa}ODaj}cp(F-$v9a6v73LJiws~;VdD=L<@cZ^-}6-86?s=7`5 z6XgY=@xlkhZ-N5RuE*Z-?D@rQyQumRAx_4x+mHO|POI3M*p&SgZF#P8_=-VWj>qxe7}kt`9WGSE-EB~lqUq(8FM zu}w0MtnYa8hj`86H!r)QRGq*&YFvG z)Ie$Kphi;wg3c6dirmv&sjB(CMR>_Y%`qiXn?tTc~Rea+NQ0YLTv z5T`;m;HT>IFx~CVcm9dph zD53Ac!uP@OmIW8wvRutO#%S>VCC!U@ebbmnNbMnX?P$Ne zTFv3)B*w5<8*y|;RPBr&`Xiy1r7hJbz0<&2?W5+{;X7SlrYvktbiXhIu5KHm%JMeU zITbMSZngUN*36g9d4;UgA$g3#m$;`OCk*{F8uN74dV+H&lC zl)+#nCC9`&%O6V3ZUA{REf?R5phvaDG}w=Cfow*p7ql!iIBfrX3VEdz;^G<1IkX=h zvn4@>o^GurFfY%S6J495)k!)>dCh=sd{);oN-&RD2|06ruS$WKA@&0n5D*nWK-l`9 zuipE*UccEcS(x2?^JoUIV7LF*2O>L+XlEs|xUWAcuP%it?TBy+8zoCfu(J9i zJBH&%J!7UGHISqOB48T}gQ#E+m!1FGr5IP~9)X_b%2U5BcnAN2a?a zs)#|JRZ#c3z5cu{h78Umg%Gw#Fh~ZgvO%x_?QR!@vs_4fs)W@FQbIYgCuUM?iqx2) z(m1O6R`f`d{nYaU_I~2+TcPZEqd=>ACHPmkH9KW!Fg$^9*Y za)kBy7NPA3S613Yb7|ef*txwssG)tTeqHe(g8rohX`lO{lmLrtYxm$bS9`QoeH^8u zazx(;E@xe8{6{TL1_pjP5nst2$MvLrSola8;X@ zhB`jl@KtD2uHl`_UI}f#7P$OD-35(t7B0J;7!luJsCnpct83+4R9k8o@&KAiWt8HJ zS(=l8UUKz6FD*l}*06B&98hZvIX)c?q+dQ>K(MpKXDd`%jw#}7Y~;zVRP}ucNKmLN zwY{py+;r)r1jOmQBt6vH1JX9!+fu#QoE)zQ_Mp2#%+r~1FKzb}7+fSrGv>BM-#iZ2O0b(@Ub zl>BT}+wFapYrCrY_EiTl+XAv74codveRIpyJjcAjX5H58vUOa^F2b$;f|7$Q#KyMtfyhxKRB_m9LUMz6l*wRYLV~xh?Ew>- z?mjFPoKRpmzFYZ8ROWfIN}5IYT-)a^!!yq!ni5CCo}d@KJ)*`c-HzVAy}#>PnyXfM zZg;sB4GR{I#6xnu-RKSnb!~m+Z1(?l{4ik+KGm(VzV}JxL;b#=hqE zuihHT1YUOQ{ab1}^`N{~gHb2vw$jIh-p;$Vw&YJ|P`i00B%O24+=X3)dN zs%^tgfeLC3?wBpKeH8<*ST}jlc)_Fn|n0AcDzl1+)-Dp^1@$@kb3M{Kf#eNTD zK8n_;$LtGqO<&->oO-|VOg&t?JV0CT@!#$fFAv0n0-oElfB#1ytq^=gs-Ktq`=6&m ztyO@BI(qx}O+To8Tds+!z6E5hma=9Kd6>HXpTqNjc~6z!x96{d#J`{E18O#`n(>3T zWLLKW`6)HgBC zqW4RDH8MIO9y@6hQO6JvC&Y8sb%hy&pCh@PgF;$^k-MxH#p0iIk9&e^7GF z@8BPz)w2fAJdD}Q3l+tJ3UB||_7ne1@fX}Y6X8p}pz$=QM*Y5xyPzF`hf@%9gPcE6&Q6wF_vg0J02H$pey zyN>*KG+x^C;O486NvU>muSsTyHC7!32lC~wJv96BH+cQ?pEn8*r0v{Y)RLF@Yw|&g zoTaH)M#KxZ&24|xW&ee5c6$-6SWSMsYTn4_D20??&}50(QFPkD?zyz1^ZyL_*Dq8Q z9%%7vv06kuH?}T3gXMgT4LKk zy>#2NV(y0GdE>=x-_HqDKdhW}BzM|7QTFf(&HwWiv*W;vT#g^^_<D9IPym$o(Jd< zw+#9L8IC{+G&pQw;YTC>T-ZON0|?X49s3Us9of-c;=&%cF z_rOsdC`e{LkHr}q4t5&8A$p&MqTXl!9)s{%?y9YRdbDW0uJUgy^Q?|fe}g&-*;?)X ztXN)X)T>rsYi3iHDZgyR_YSa`v!H+`0Hdm?!XyipaWiCN#o4kEG-C971h8>X&?;=L zy{t~#7+wCuPK`lt+krlq3?@jgfjh}cH9KXMx6Z~?k(;6%g#!q-YK!` z1scJO6$TgH7Ke^M1p?at<-o^iGxsa0_e(ATU$inNPgN&vbVU7!vAo}?Z5~#w`DW+d z$`U^-L4VLXYli1jb9V(Sp>i>6ratMm!w(G0yz0j*I-O1m%iYJRVa<-;_x4sBiOBXi zt$ii5A3JX}T<|@9IcExP{gdYiq*FJ9(7vZu;4;w0S1RxWJG_C z;h-Bt*VKDJ!mAWhC?E9=_zZwP(y4`+aig^{j!2fVDq=U$y(7At`Io{i>zVwgY%U_I zbHuy-Jr>=jg6vjgW$iG?51sS~#lZnsvfO)b*LrdSs3Ni#(C21gG zT(sbSj zviyk24_=Lrjg$l9;GIjus+b(JnM&QWZ{9L|-kA_$6m!u;0~}v24W*4!9B)}e9Oo8* z!h<)U-wx@d97p7fo$3qrW8X530JE|7eJIA8*tJR~gmLbWc$L?9c>q49$;JmA6eVaw zgg~RrKPU1Q_XO}vFK+CT{RXDb=J|pMvuP(3md}SZQaf+w+;LYD@AEyuzSn+x`fjs5 zRK>d26ZX2`L)bd*A>ILbp10=;j(*!kvnE0R7-#F$dbK)6N9)$srKQY=pcwFSX-+QP ztCA_dubusg$u_Kf+g2J_znF zwTkzZs|5ZPZaoXypd|p3=i9@B{db#(4`nNJJ%b*nag_#ZDFx(Y5SU4hEvdAoQ@F1t zXrO6ta~TP!67QoANsPE|uR1-*`M-}FIo|{_WdaXKYr9t1 zBCypYpA#(?_AClK9oC0G0~D4+_rQc(Z&Vj{MA1oAj}gvoqDN8u)PanV-QSpU5O^`? zTY-FO9#hUAEFAe9>jTeGJ$C-s6HLP0?uEHnV=>U>MbPW^e5q4Lp^$oxvbpSPaqRuq zoLBf8lsn6v%8Jt!Zx+UrJ}2L>z{yGZ)r%;0dZl|p#VDWx_7@38-$&5Rf#b^I!ICO06l>OycV@yW^01pl)gk|GUNWSbrmmG@8`0MO#}>h zDxZ6~Uq0b}b3fEYpKXQrtg}6_I-hXTft}z+DBS}KAt?@iz{$>j<#rN-3HK%B!-6zK z`!3`%z98P7s+voWHQu_r4>c6D5hM?z#dqB>W!ve)W4xsWqQ=ikfZ4gR4kJN@S8?%C zXX{Z>IH~R}(>`;|MqvCob4>s2L)K(M-^-g1%`rKltENh;Mip3cwlOu``q*89ZI{9L zTgA*dFpQ;nxMCQ7%3-z(Gm||LEBZ)|TM_#>YX9JMW%U9-d~&#JNhp+Vz420AOOKLo ze&rqvyl;STUvEgBiR|TKpWl3Cjc^9aCCS_{;XBy(#RPM#>OLgYb+U@S5KHG$C+u&9S+;k7FcDRe?vE%G z*o$`j1FXVIWMc+iN@y_OYPuE*95{<7b)8JNjV>02HXfAz7`X^HcUWYMlqWO{O5?Pn zt{2X%>R)`y*3#8c=QgrxkrKi=Y@>^{ba2|7KID`GEVv$kqIg-X z+VSy8lWvy5LaLhs7Z>Z|wZ)VeL1VXfDVofqFbcuxDwNU^MuLn!apeV9Vm5tFjNcp= zzVL8-N~d6{z@f^W3^6+P%5Y?pTRPRKW64DYnx}T(EG>TxpZbNW99K z>&tIkv}5Ra+@CnyO;}xR^({#A`9n8Qt0Iw)A5q~U!l1@2{8E{QQaNR1t(L21!fLth z8tQqK=~+IUE5bH7pTJ!}2LN)^b;4%19MHvyzHf62;Sn&uVsUF)h5kNA(=*1o{TIh` zyY#xxWm5N8$+632jJ)N*l+{~vsZou~F8$9gm>lYV>DD=0cq@Hl!tB#^)0vV20MwNy z=ho9+jXTQb=w})P(ZaTSk_cb$seVIGkjc_#LGp5MM?V{YIiy%aY(*feP%X^DncQgP z{YwDL4U>9rCA~i5V3^?`3;Z!{u}q6aiM|Sl} zxf>Ucy9lb=x^5br-2mICGBlCLGltHhh`A}OpHz19E%Avn>Q5fjwD`C9bN6KubXFTH zPoY!Lu2EA#7|4$J0^^EPCKgj7T*g@VP-j`rO%xhz;_bC4x%q3GxNMbMs730Y%eJMI zW8pP}n8$XPuFguskaH^u(pN_351S{ZnV_qB@?N%A?p`wWh0wK(KZvte!D=EaI|9C) z;z)T~U2qY4`uMt$uHK4pAT1=yYp8fn+e#KK*ToXJ$$MCmoF}3QQ3`>2s6l22q#AC^U9Dypvx6?Ok!?xmm5)AMMc(YeRX(LQqNG={3_?##+S zCfYx-y^nR&wn5cUsiXj5sG z*Yb=eF%O*ME;M>f9=3;!{Ef*v+Axu#g@;X~Y~z!&#>!(tgNUNV^D9r1SC6vy?JDQ` zX~>g0t2&lj2{gON%8A}C`CWb!8cBqY?=XbGs3crKkbNH2=gb%*HAgXAE8TSQu>=y| z(=sA|W+T2TvUDSovhF(-@&S&?PP3ph>+tkP{}XPNYf%41_&dhEDu>l8g|f5JPPC zBKh^zX8G5|<2iu?Nv};!-`<3khqlx{B51ds+~@!Nc1uxyNZi1$d^NYIVB6@Av^d#S z=M(MwWmL-#f3W4eieM9Jj4@rTj9s&L#cb*LUnb}Yd4Q*YqqkYusuduOWndFPxtYA% zWMbtBTGYtA@LEiN=IwZ=Tlx@ABms)w{L$2r{Mbsy`w3b;YiaVelkiqkhuV=G(DHm( za+pd~%-k8P{sQPe>{4m?eMK;^QuOpPN)76*ikNaCOy{dc^nmu6uwy2M=w+IN%(<0! zn_Z|hl(pK`^@B$#*=8$Lo4>@eqT1QnulY-ErSDAjQq2(4{66Z87jC+rp}cy#!NnO4 zZ?83E6PU;x9Qd-kaA#t=OCsS|o{BVfOANw3B$lTK4#! zsL#buy&eLC_iS`m(LYX09Z8KtVmxQ>m3~-w27`R)$+xcYh!2C$CW}5cCq2UWx;!+} z;UB2coLE6fJ9F)XJ+ru7FYBsrQOOHAvFXwv>mqqPW+!eUBG(1fzPTVxy9#J5fUFJ; z9`^mDotz3+W?QC~hjqTlk8^Th;v_K((d!syw^loB=`qmaVRE)q^Ific&sN^`KNW^0SPTzpq9pML{EoC4&qc2 zHp|S?AFasZj%P|dMDMpvY|F~+?TrAD)k(uEfo&i=jQJGi;1&F93#3MtVu}_$CsRIj zH6f8$u*p4X)T>Tku>{z=u%!!H0?A9y&?7*=F^w(Ny{HY5_XZ2Sy!k=If&|l>6eV-2 zX3D}?`gNq7rrisB=7IGG2KAQ7)<&ni4 z<=I%T{vdUQBg^D5L&{~&-lGcLT{G)Rsk}8)+VE#a3QsC6FE|fet2z5LUnEd6)Adq@ zsLMwF8i$By1$jNM`(lg+B|mcBmn$4~{6PKcwyV6UCP@2~4*{Y(dSyq;oWNS#Gmbox z{=BdDQ7%_*VR$aRIcUUYa8t-s`AQrn3+SPV562C+mT0gq*N?z26lKr#)t*k|pv0Af zunsB-_TG+JDqn*w7<$oypGNhP20O%ogqOF3%38nRC~OIA0;m)X2dPb@tH63 zf|x>w42%mOqYRq7%#GL4oeD^SKAgWSV(p`y8Xp@px7*2zJgR%H$Mttii`&BT468z~aPLVZd;=o;<19{h{Zj2>z&&c&lbvcrf`XtSQm05kgX{)7CmO zpEMhQ_Zp!{Yr^uoUT~-Ls*9ry&>r-u-}N(jTXj!KL0mTOv=Wby!ZU)MPfi|hJXkkj zt@h`mqh}rMzx3ZxD&IU;ScF2~-kP?em*>a|=PS_?&`pNaZvg^R#jWaSQHcJ6G=?t1 zO%sW`MAA&x+RVr+S2Ob2j^)&e5Hy)o8dU{#32n+KXnjC(V~@FhwTp;joCz0Yp2b-?U!hC zLXz_BBTJ-2ru@!_Z5+xR>Fk9``4B)cn}D`jLU`ZIm?aLd=V5{Bs(%1VP$%IAIq93> zGSdJrEF;y}N^^{-MJ1<4oodWwf3LIuRPVAm!_1$EQtJ}EH@`X#yFO22XeXjw8^ zI(Y*oiNn4flun6*9)W3lc1-4rX&c&p=~d}jDkNNvr*4No_wdP`q{FW)27|tZ&385n z2`IOWU*&mX&s_OJDB{0eb9@N%mW{e#JwREqchtV^cEF$BHj>n~m!LEyZ;(f;>Im=+ z8shk2t*jKX6!id@Kk3ir)r; zc>3&y&+7_M_=2yi3bHVcjHCd4xLV;`KLEm&x8on}WVML(kDpUs4YR z#E`8aYJmC}N{IgI00H^1LUdvC;L8@T#)Lh6pJB#_#EqtUI-1n_DvZ5O2Rf>LVsi?bv;# zx1{_#C>jwZ%TyBMe)r@|198sU8@YKiOIw4B;#e(G=oLDHF#!_{d4p4cceW77xF>qe zJJlP$zvnXPOx+Ey1>0TIKJt=>7bk}q6=pLCL&?s|%z12+I!UK&awTK}IRWMFn9V?T(M^{<7FqF34l`08=J~a?PJzDreA zpZcJtvTK`~CqyZ#AZ>41VZOts5M+~T-!{MBg;QeM_R+e?tWURoXChe?h9Q=FagkBA zC+br9GW=f7rwDFTQ(|iF@ywQh9?;XQfIdZlY*BtOxOb$L2}>R@jRjHMLgN+HFN9Tx zdVf!wc?dKmHF7;>Q5K9@#U*AKq3YH-uev#cO_K<5yhuV3HIQU7g*ie|fq$aB=3bj+ zIFvaLybz9Kv@hj4ywlDSTYANX`kDHyhSn=P;X;Z1xi7(5Wo}KAk6W}F)DIynNXItI z!@TM($RvDgt?K% zK8QE^!60ROn+n=R&P8?}X%qeKvhRxdbvpZTY*Pd! z)HYG%gTo4XWRf1PVr|M2Yclk9$p=L7a%jf4^z3$^V0~`a*YP#O<=iMZr;()_5g3+X z#I>DBAbPom@Yhu3z*ib#k+_#=p}GoxHHwk$Ad#BbaSJb6Tk#0>ES^(Sfx$?-0N6&? zU|E;=j|?Ux4JCvJ35%ag=%&J2j_m-)md(0K08ZdU>>lFAI{Y4(JL7GYTdBHuYhpUZ zI`dQT$H(~E-R6m)0tPsIkMwop+4~k~G{!AmIy%TD%mnIxRlyEOF4hm&M)joOSu6Kq z&mu2hra#(dGy;oyeWui2O2|D8yfPG<%YEKw1OLNkZ(@%0t+z=Wn${J;nH&!CDse?j zep4pU&VJHb&3w4_FkK~UMA1pyuhm{+h1`scFr`k_7$ViR;&GjRf_AI571JveMBBc!|!KW90d)ym7C6)}Dg`?BG zKx}C`<+BJ$D-?OCiPJpCSCiYG)jm;Gc2?kro^<8a3c(&S@B)T9vzoUvhqDPTwCw#ya4o9 zCA^$|%F|mjaDO?xJn;Q(4z_|WJ)JR|@Dj3VDS<%T1ZHAm9T{Uj_GCtcIx*MOG18DW z*RDr;8BEHRif`O3aQ+MC(d&G#zT!X-+@gJ$IRAi?+dvUJfNq_(ahPbyHuJ@8KXaH3 z4Khz4M=b~7)h68}2hKc!u%p6EM)5X-tuG1XpS|R{K8l%ZVN~}g;|$CDfC@dm_W%Xx z48Thzz@<|9RcHN!{eys>wt&v<`yrq7WmIllKa1RjjKbM;!mZ11`RWr+-~)zd zP3zPjN4De>w9&>1u!1*>Z$1UbL?bztbp6<~EL&^S<3sn& zZE4az#A|HN`yq?h){l5L0u966DXkmU5i(I&cKKDT7CxZcWMw;s%IpWR zz~DYso-D%#Yg~%zO$%SV-I4YcTNR`yHPj4BrdQ>lADoK9v6$q5t;!weI>G>%xsfF~ z+gtSD_kyvAS@~0*90z;r)q$MMOFsCM*74!i!mHpOkc*+|yx~QgAqW&=Bx}LTZ^sDb z^#sq^AI}Un8g9-YEhZK{dj2i*otI~3(#@UHnjkKxie`3Bb!X+?b^=AmRTdl^_)5a0 z-p~h5hsYm5vEq9!_-r#J&2|(G&g;94kYx5vS1JwGd?qtBUHuYn;PYM1r1xoML@N?{ zLOp%1KLaEE2qt@(V`M*50!~#joalL62SO$Doanr*2xU&LO+lS#jZL>UujgC9{gQ%| zXfx8|3H!`gGI%rM^yaJAGr(TPIG;ydpGyKpP^+4OZ5n?iDLfD*S|r1a^(!0J;cPv= z2MoXqK$P$J8%XnF#DD63Yf|0=7>f3#<*_|Kc=jJJ@ULRwdal+T1n4nw=w--%XX1Tn z{~@4T_`uu8Kk7*F0&)$W2?^vMJ`mDZp z7xmWT#dR(1074N5$D#3Sym+np3W9wuHgp=SP9EL)ujK`(^(PIK%SB18pE+BP?be?k z_5nB*Cgaz&E?ED0)CD~H`Kxa-b@(SYcp~>rY<_a%zuW-&mO#_#(9j>LSQ8(*Bzdi` zm|PeZZ{GL%`;M#DlIr_3x3%UcTL;4~*XhCasPtbdEHG;Kt@HR%E;Y2?(cs_D)|KBu z+Y;|zSGliCC^LiV}g@ZXHvvmtJc2uL*OQ_r>WlK z-_l*{(7z6fh(rF(Pp11_t{=CO5M4SO@%@BjF=iVP z0GmNT=bqq+oN9M1;EsZYkNo@28Ji3~aaBBbVDG@g+oxm;ec;F+bT$k0N_G1Kk$swC z!GYXOVE>@{leVWk$)BTe*TN4I5zc4ddi~YW@o%;`hw%ZOh|P1%=>y-%03bQLfoz9N z^t*Hal8kTi^b8MxzIs9?_In`}{}Z_Gz*FeW_oDX;LLF$us5A;^{%FMKKp)%Ql!+hM z%?jWexv9Ca@$dWienG?lbi_F4{D6$HB49xL%eOz`*3X6gXS;vy*uNbbvu8g=@jr<6 zQ^)=a7iWuLrlUgY5d z$NBSpmz^jj?$ExASh>4iB&;50-Ste^JS7ReQde5?{(Z!rVy|SqYeetaoB5N2#paz& zoRO0CEYTaaLU-Z^$cju?aYqSoCm}*#s`(>bJ{Y57f}OGX*_MN;|^?TQP>)1vCNzRQf#gQzW+##0FA>4LK`6S72rFYX{ zvV5QER?;XE!td#{cK8AC@IzzzH`f@bt%;`U&gRtX@T%$dGSB2qgO#<_ugyx=Jl|>u z;bGIeBlJ28JiTF+oq|)|$=kcbTYv=2ktZcb*C3uKh%LlN&W@BYn%D_sxqII(jHong zmu;oQt+0NBTOC@@Chi8@Pmcpo-u-Q*A`w@TVMAnX3`B6>w?m8JeA1go=}oJ~?|5!E z!UH%M^7eV&mbE#%)qOqe&+28Rz2ZIFz!xVt$8hCjURsaSjsSJ2FXuaX9f6)wWnTGu zA3+G7A-V)CA$f#;dYvrG<3Pq~i<=j3b-@UJ^z=5U-M0}f1pe#RZaseLwFL-jp z1b8`~27L&uF+k-3E|9$3A2nNV9-Od+*ck&p29)o72iCZL9#~Yr(+FeW^ax{6M!pYi zWOIC--Crc^P_$u`|5251tU24CsSO(PswD5BPBBSkk!^~zz8+!FmEKY|9OJz_a-?M7 zqxc$8mPZvJd`s9)Pcc5NRiY13eYW;C-H&9iSj0g`CxNyWiJyBrl$e))xO zFX8w$Z5&&-Ux--89717Heo5S#(rVtwKi_mnq0P_&?jila^=4`6?3+ z9L{=P`M!07QFh+15eucH!TO@>%@b!$RD8hMDLiiZ zhtcp_3bD9hO;357@vn5|vy;H_p`X9{#+IMl_=XPaLivA^4Fs3}&^4{SG1VpKegXcS NK6&m$!7=CP{|nRa_Lu+w literal 0 HcmV?d00001 diff --git a/Example/myWeb3Wallet/myWeb3Wallet/ViewController/WalletController/DashboardViewController.swift b/Example/myWeb3Wallet/myWeb3Wallet/ViewControllers/WalletController/DashboardViewController.swift similarity index 100% rename from Example/myWeb3Wallet/myWeb3Wallet/ViewController/WalletController/DashboardViewController.swift rename to Example/myWeb3Wallet/myWeb3Wallet/ViewControllers/WalletController/DashboardViewController.swift diff --git a/Example/myWeb3Wallet/myWeb3Wallet/ViewController/WalletController/SplashViewController.swift b/Example/myWeb3Wallet/myWeb3Wallet/ViewControllers/WalletController/SplashViewController.swift similarity index 100% rename from Example/myWeb3Wallet/myWeb3Wallet/ViewController/WalletController/SplashViewController.swift rename to Example/myWeb3Wallet/myWeb3Wallet/ViewControllers/WalletController/SplashViewController.swift diff --git a/Example/myWeb3Wallet/myWeb3Wallet/ViewController/WalletController/WalletViewController.swift b/Example/myWeb3Wallet/myWeb3Wallet/ViewControllers/WalletController/WalletViewController.swift similarity index 100% rename from Example/myWeb3Wallet/myWeb3Wallet/ViewController/WalletController/WalletViewController.swift rename to Example/myWeb3Wallet/myWeb3Wallet/ViewControllers/WalletController/WalletViewController.swift